SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec fnd 'val1,val2'  
-- drop proc fnd  
CREATE OR ALTER PROCEDURE [dbo].[fnd]  
@text varchar(200)  
as  
begin
declare @t varchar(10)=''
select @t = ''''
SELECT @t + ROUTINE_SCHEMA + '.' + ROUTINE_NAME + @t as Name FROM INFORMATION_SCHEMA.ROUTINES   
WHERE ROUTINE_DEFINITION LIKE '%' + @text + '%'   
AND ROUTINE_TYPE='PROCEDURE'  
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [dbo].[fndLM]  
 @rDays int = 30
as  
begin
SELECT  Name,ChangeDate,ChangeType FROM
(

SELECT name,modify_date AS ChangeDate,'ALTER' AS ChangeType 
FROM sys.objects
WHERE type = 'P'
AND  DATEDIFF(D,modify_date, sCommon.fGetDate()) < @rDays

UNION ALL

SELECT name,create_date AS ChangeDate,'CREATE' AS ChangeType 
FROM sys.objects
WHERE type = 'P'
AND  
DATEDIFF(D,create_date, sCommon.fGetDate()) < @rDays 
       
 UNION ALL
 
SELECT name,modify_date AS ChangeDate,'ALTER' AS ChangeType 
FROM sys.objects
WHERE type = 'fn'
AND  DATEDIFF(D,modify_date, sCommon.fGetDate()) < @rDays

UNION ALL

SELECT name,create_date AS ChangeDate,'CREATE' AS ChangeType 
FROM sys.objects
WHERE type = 'fn'
AND  
DATEDIFF(D,create_date, sCommon.fGetDate()) < @rDays


 ) A
 ORDER BY A.ChangeDate Desc

end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec fndt ''
-- drop proc fndt
CREATE OR ALTER PROCEDURE [dbo].[fndt]
@text varchar(200)
as
BEGIN
declare @t varchar(5)=''
select @t = ''''
SELECT s.name + '.' +   t.name as name,@t + s.name + '.' +   t.name + @t as tab
FROM sys.tables t INNER JOIN sys.schemas s ON t.schema_id = s.schema_id 
WHERE t.name LIKE '%' + @text + '%' OR s.name LIKE '%' + @text + '%'  order by s.name,t.name
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
  
CREATE OR ALTER PROCEDURE [dbo].[Get_Processdata]  
  @SourceTypeId int = 0  
AS  
BEGIN  
  
 select * from sBiometric.tProcess where SourceTypeId = @SourceTypeId  
  
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [dbo].[getPROCEDUREName]
AS 
BEGIN

select ''''+s.name+'.'+p.name +'''' as ProcedureName,p.create_date ,p.modify_date from sys.procedures  as p
LEFT JOIN sys.schemas as s on p.schema_id=s.schema_id
order by p.create_date

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [dbo].[pBioMatricListGet]
	 @rOrgId smallint = 0,
	 @rorgGroupId int = 0
AS		 
BEGIN 

	SELECT * FROM Configuration WHERE  
	((OrgId = @rOrgId) OR (@rOrgId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [dbo].[pConfigurationAdd]  
 @rId int,  
 @rOrgId int,  
 @rIsAutoPrint bit,  
 @rErrorCaseAllow bit,  
 @rAlertTo smallint,   
 @rAlertFor nvarchar(50),  
 @rIsAbsentOnTotalLateDaysMonthlyDay int,  
 @rIsAbsentOnTotalLateDaysMonthlyLeave decimal(5,2),  
 @rIsAbsentOnTotalLateHrsMonthlyDay int,  
 @rIsAbsentOnTotalLateHrsMonthlyLeave decimal(5,2),  
 @rIsAutoAttendance bit,  
 @rAutoAttendanceTime Datetime,  
 @rIsAutoAttendanceEmp bit,  
 @rAutoAttendanceTimeEmp Datetime  
   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN  
 BEGIN TRY  
   
 IF(@rId = 0)   
  BEGIN  
   If Exists(select 1 from Configuration where Id=@rId)  
    BEGIN  
    select -103 as Result  
    RETURN  
   END   
  END  
 ELSE  
  BEGIN  
   If  Exists(select 1 from Configuration where OrgId=@rOrgId AND Id<>@rId)  
   Begin  
    select -103 as Result  
    RETURN  
   End  
  END   
   
  BEGIN TRANSACTION   
    
   
 IF(@rId = 0)   
 BEGIN  
 DELETE FROM Configuration WHERE OrgId =@rOrgId  
   
 INSERT INTO Configuration   (        AutoPrint,    AlertFor,    AlertTo,    IsErrorCaseAllow,    IsAbsentOnTotalLateDaysMonthlyDay,    IsAbsentOnTotalLateDaysMonthlyLeave,    IsAbsentOnTotalLateHrsMonthlyDay,    IsAbsentOnTotalLateHrsMonthlyLeave,    OrgId,
 IsAutoAttendance,    AutoAttendanceTime,    IsAutoAttendanceEmp,  
 AutoAttendanceTimeEmp   )  VALUES   (       @rIsAutoPrint,    @rAlertFor,    @rAlertTo,    @rErrorCaseAllow,    @rIsAbsentOnTotalLateDaysMonthlyDay,    @rIsAbsentOnTotalLateDaysMonthlyLeave,    @rIsAbsentOnTotalLateHrsMonthlyDay,    
 @rIsAbsentOnTotalLateHrsMonthlyLeave,    @rOrgId,    @rIsAutoAttendance,    @rAutoAttendanceTime,    @rIsAutoAttendanceEmp,  
 @rAutoAttendanceTimeEmp   )    
      SELECT 1 AS Result  
 END    
  
ELSE  
  BEGIN  
    UPDATE  Configuration  
    SET  
    AutoPrint=@rIsAutoPrint,    AlertFor=@rAlertFor,    AlertTo=@rAlertTo,    IsErrorCaseAllow=@rErrorCaseAllow,    IsAbsentOnTotalLateDaysMonthlyDay=@rIsAbsentOnTotalLateDaysMonthlyDay,    IsAbsentOnTotalLateDaysMonthlyLeave=@rIsAbsentOnTotalLateDaysMonthlyLeave,    
	IsAbsentOnTotalLateHrsMonthlyDay=@rIsAbsentOnTotalLateHrsMonthlyDay,    IsAbsentOnTotalLateHrsMonthlyLeave=@rIsAbsentOnTotalLateHrsMonthlyLeave,    IsAutoAttendance=@rIsAutoAttendance,    AutoAttendanceTime=@rAutoAttendanceTime,
	IsAutoAttendanceEmp=@rIsAutoAttendanceEmp,
	AutoAttendanceTimeEmp=@rAutoAttendanceTimeEmp        WHERE Id = @rId  
    SELECT 2 AS Result  
   
  --COMMIT TRANSACTION  
  END     
  
 COMMIT TRANSACTION    
 END TRY  
   
 BEGIN CATCH   
  ROLLBACK TRANSACTION  
  SELECT -1 AS Result  
 END CATCH  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [dbo].[pConfigurationDelete]
	@rId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION		 
		BEGIN
			DELETE FROM Configuration WHERE Id=@rId
			SELECT 1 AS RESULT
		END

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [dbo].[pEmployeeMasterGet]
@rOrgId int = 0,
 @rBuilder1 nvarchar(max)='',
 @rBuilder2 nvarchar(max)='',
 @rEmployeeStatusId int=0,
 @rEmployeeId bigint = 0,
 @rOrgGroupId int = 0	 
AS

BEGIN

declare @lBiometricDeviceMode nVarchar(100)
SELECT @lBiometricDeviceMode = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @rOrgGroupId
        WHERE  C.ItemKey = 'Biometric.BiometricDeviceMode'

if(@lBiometricDeviceMode='Offline')
Begin
	UPDATE sHrm.tEmployeeMaster SET PunchId = NULL
	--IF EXISTS (SELECT EM.PunchId FROM sHrm.tEmployeeMaster EM INNER JOIN sBiometric.BioDetailMapping BM ON BM.EmpID = EM.Id WHERE EM.PunchId is null)
	--BEGIN
	UPDATE EM
	SET
		PunchId = BM.EmpPunchID
	FROM
	    sHrm.tEmployeeMaster EM
		INNER JOIN sBiometric.BioDetailMapping AS BM
		ON BM.EmpID = EM.Id
		WHERE PunchId is null
	--END
End


	select EM.*,isnull(EM.FirstName,'') +' '+ isnull(EM.MiddleName,'') as 'FullName',
	(SELECT Title FROM sSetup.tOrganizationMaster WHERE Id = OrgID) AS OrganizationTitle
 from sHrm.tEmployeeMaster EM
 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	where PunchId is not null
	and (EM.OrgID = @rOrgId OR @rOrgId = 0)
	AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0) 
	AND ISNULL(EM.IsOtherUser,0) = 0
	and (OM.OrgGroupId = @rOrgGroupId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
CREATE OR ALTER PROCEDURE [dbo].[pImportPunchData]          
(@rXmlDoc nvarchar(MAX))         
AS  SET NOCOUNT ON          
        
BEGIN         
        
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND') DECLARE @lInterrorCode INT,          
@intDoc INT          
             
--BEGIN TRY          
--BEGIN TRANSACTION          
        
 EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc           
           
  INSERT INTO [sBiometric].[tPunchData]          
  (          
   PunchDateTime,          
   PunchMode,          
   PunchType,            
   RFIDTagNo,          
   Reason,          
   StudentID          
  )          
  SELECT          
   convert(datetime,A.PunchDateTime),      
   A.PunchMode,      
   A.PunchType,      
   A.RFIDTagNo,      
   A.Reason,      
   A.StudentID      
  FROM OPENXML (@intDoc, '/Table/PunchData', 1)          
  WITH          
  (            
   PunchDateTime nvarchar(30) '@PunchDateTime',          
   PunchMode NCHAR(20) '@PunchMode',          
   PunchType NCHAR(40) '@PunchType',            
   RFIDTagNo NVARCHAR(100) '@RFIDTagNo',            
   Reason NVARCHAR(100) '@Reason',          
   StudentID bigINT '@StudentID'      
  ) A      
    
  WHERE  PunchDateTime NOT IN (SELECT PunchDateTime From [sBiometric].[tPunchData]  Where StudentID=A.StudentID) --  and RFIDTagNo = A.RFIDTagNo Udpate RFID Duplicate Entry
  --AND A.SourceTypeId=SourceTypeId           
  --And OrgGroupId = A.OrgGroupId          
           
     
  EXEC sp_xml_removedocument @intDoc          
  SELECT 1           
 --COMMIT TRANSACTION          
 --END TRY          
 --BEGIN CATCH          
 --SELECT -1          
 --END CATCH          
          
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [dbo].[prc_d]
@prc as varchar(50)
as
begin
	exec prc_dal @prc,'DataBaseObject','AddInParameter'
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--- Exec prc_DAL '[sExamination].[pOPDListSearchGet]', 'DataBaseObject','AddInParameter'            
--- Drop procedure prc_DAL             
CREATE OR ALTER PROCEDURE [dbo].[prc_DAL]             
@prcedure  as varchar(100)  ,            
@ObjectName as varchar(20) ,            
@DalObjectType as varchar(50)            
as             
begin               
Declare @TotalParameters as int = 0
Declare @Result as varchar(max) = '',@Lastparameter as varchar(100) = ''

select @TotalParameters=COUNT(*) from sys.parameters where object_id = object_id(@prcedure)  

if @TotalParameters = 0             
begin             
	select @Result = @Result + @ObjectName + '.' + @DalObjectType  + '("' + @prcedure + '", Nothing)'            
end             
else             
begin
	select @Result = @Result + @ObjectName + '.' + @DalObjectType + '(DbCommandObject, "' + name + '", DbType.' +    
	case when type_name(user_type_id) ='int' then 'Int32' when type_name(user_type_id) = 'bigint' then 'Int64' 
	when type_name(user_type_id) = 'varchar' or type_name(user_type_id) = 'nvarchar' then 'String'
	when type_name(user_type_id) = 'float' or type_name(user_type_id) = 'money' or type_name(user_type_id) = 'decimal' then	'String'
	else type_name(user_type_id) + '(' + convert(varchar,max_length) + ')' end + ',' + replace(name,'@r','') +');'  + CHAR(13) + CHAR(10) + CHAR(9) + CHAR(9)
	from sys.parameters where object_id = object_id(@prcedure)
end             
select @Result            
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec prc_getdata
-- drop proc prc_getdata
CREATE OR ALTER PROCEDURE [dbo].[prc_getdata]
as
begin
	select * from dbo.[Table]
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [dbo].[pTransportStudentSearchGet]
	 
	 @rOrgId int,
	 @rTransportId int,
	 @rBusrouteId int,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int,
	 @rSUId nvarchar(max)='',
	 @rDepartmentId  int,
	 @rSurName nvarchar(100)='',
	 @rPickUpId int,
	 @rStatusId int = 0,
	 @rIsStudentImage bit = 0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 		
			IF(@rIsStudentImage = 0)
			BEGIN
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS BusRoute,
				ISNULL(BM1.Title,'') AS DropRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint ,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint ,
				ISnull(SD.SUID,'') AS SUID,
				0x00000000 AS StudentPhoto,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				LEFT JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId 
				--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
				AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
				AND ((SD.Lastname like @rSurName + '%') OR (ISNULL(@rSurName,'') = ''))
				AND ((BDM.Id=@rPickUpId) OR (@rPickUpId=0))
				AND ((SD.StatusId=@rStatusId) OR (@rStatusId=0))
				AND BMM.IsInContext = 1
				order by SD.ClassId,SD.Suid,SD.Code
			END
			IF(@rIsStudentImage = 1)
			BEGIN
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS BusRoute ,
				ISNULL(BM.Title,'') AS DropRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint ,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint ,
				ISnull(SD.SUID,'') AS SUID,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
				AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
				AND ((SD.Lastname like @rSurName + '%') OR (ISNULL(@rSurName,'') = ''))
				AND ((BDM.Id=@rPickUpId) OR (@rPickUpId=0))
				AND ((SD.StatusId=@rStatusId) OR (@rStatusId=0))
				AND BMM.IsInContext = 1
				order by SD.ClassId,SD.Suid,SD.Code
			END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [dbo].[pUpdateOrderItemStatus]
	@rOrderNumber int,
	@rItemNumber int,
	@rPaneNumber int,
	@rCompNumber int,
	@rStatusCode int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lLastNumber BIGINT
IF NOT EXISTS (SELECT ORDER_NO
						FROM dbo.ORDSTAT
						WHERE  ORDER_NO = @rOrderNumber AND ITEM_NO = @rItemNumber AND PANE_NO = @rPaneNumber AND COMP_NO = @rCompNumber AND STATUS_CODE = @rStatusCode  )		

BEGIN

	SET @lLastNumber = 0
		SELECT @lLastNumber = ID FROM dbo.ORDSTAT
						WHERE  ORDER_NO = @rOrderNumber AND ITEM_NO = @rItemNumber AND PANE_NO = @rPaneNumber AND COMP_NO = @rCompNumber AND ACTIVE = 1 
						
		IF @lLastNumber <= 0
 UPDATE dbo.ORDSTAT SET ACTIVE = 0 WHERE Id IN ( SELECT  ID FROM dbo.ORDSTAT
						WHERE  ORDER_NO = @rOrderNumber AND ITEM_NO = @rItemNumber AND PANE_NO = @rPaneNumber AND COMP_NO = @rCompNumber AND ACTIVE = 1 )

			INSERT INTO dbo.ORDSTAT
				(	
				    Id,
					ORDER_NO,			
					ITEM_NO,
					PANE_NO,	
					COMP_NO,		
					STATUS_CODE,
					ACTIVE
				 
					
				)
			VALUES
				( 
					@rOrderNumber,			
					@rOrderNumber,			
					@rItemNumber,
					@rPaneNumber,
					@rCompNumber,			
					@rStatusCode,
					1
 
				)

	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [dbo].[Recover_Deleted_Data_Proc]
@Database_Name NVARCHAR(MAX),
@SchemaName_n_TableName NVARCHAR(Max),
@Date_From DATETIME='1900/01/01',
@Date_To DATETIME ='9999/12/31'
AS
 
DECLARE @RowLogContents VARBINARY(8000)
DECLARE @TransactionID NVARCHAR(Max)
DECLARE @AllocUnitID BIGINT
DECLARE @AllocUnitName NVARCHAR(Max)
DECLARE @SQL NVARCHAR(Max)
DECLARE @Compatibility_Level INT
 
 
SELECT @Compatibility_Level=dtb.compatibility_level
FROM
master.sys.databases AS dtb WHERE dtb.name=@Database_Name
 
IF ISNULL(@Compatibility_Level,0)<=80
BEGIN
    RAISERROR('The compatibility level should be equal to or greater SQL SERVER 2005 (90)',16,1)
    RETURN
END
 
IF (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE [TABLE_SCHEMA]+'.'+[TABLE_NAME]=@SchemaName_n_TableName)=0
BEGIN
    RAISERROR('Could not found the table in the defined database',16,1)
    RETURN
END
 
DECLARE @bitTable TABLE
(
  [ID] INT,
  [Bitvalue] INT
)
--Create table to set the bit position of one byte.
 
INSERT INTO @bitTable
SELECT 0,2 UNION ALL
SELECT 1,2 UNION ALL
SELECT 2,4 UNION ALL
SELECT 3,8 UNION ALL
SELECT 4,16 UNION ALL
SELECT 5,32 UNION ALL
SELECT 6,64 UNION ALL
SELECT 7,128
 
--Create table to collect the row data.
DECLARE @DeletedRecords TABLE
(
    [Row ID]            INT IDENTITY(1,1),
    [RowLogContents]    VARBINARY(8000),
    [AllocUnitID]       BIGINT,
    [Transaction ID]    NVARCHAR(Max),
    [FixedLengthData]   SMALLINT,
    [TotalNoOfCols]     SMALLINT,
    [NullBitMapLength]  SMALLINT,
    [NullBytes]         VARBINARY(8000),
    [TotalNoofVarCols]  SMALLINT,
    [ColumnOffsetArray] VARBINARY(8000),
    [VarColumnStart]    SMALLINT,
    [Slot ID]           INT,
    [NullBitMap]        VARCHAR(MAX)
     
)
--Create a common table expression to get all the row data plus how many bytes we have for each row.
;WITH RowData AS (
SELECT
 
[RowLog Contents 0] AS [RowLogContents] 
 
,[AllocUnitID] AS [AllocUnitID] 
 
,[Transaction ID] AS [Transaction ID]  
 
--[Fixed Length Data] = Substring (RowLog content 0, Status Bit A+ Status Bit B + 1,2 bytes)
,CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) AS [FixedLengthData]  --@FixedLengthData
 
-- [TotalnoOfCols] =  Substring (RowLog content 0, [Fixed Length Data] + 1,2 bytes)
,CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2)
,REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2)))) as  [TotalNoOfCols]
 
--[NullBitMapLength]=ceiling([Total No of Columns] /8.0)
,CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2)
,REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)) as [NullBitMapLength] 
 
--[Null Bytes] = Substring (RowLog content 0, Status Bit A+ Status Bit B + [Fixed Length Data] +1, [NullBitMapLength] )
,SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 3,
CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2)
,REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0))) as [NullBytes]
 
--[TotalNoofVarCols] = Substring (RowLog content 0, Status Bit A+ Status Bit B + [Fixed Length Data] +1, [Null Bitmap length] + 2 )
,(CASE WHEN SUBSTRING([RowLog Contents 0], 1, 1) In (0x10,0x30,0x70) THEN
CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0],
CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 3
+ CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2)
,REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)), 2))))  ELSE null  END) AS [TotalNoofVarCols] 
 
--[ColumnOffsetArray]= Substring (RowLog content 0, Status Bit A+ Status Bit B + [Fixed Length Data] +1, [Null Bitmap length] + 2 , [TotalNoofVarCols]*2 )
,(CASE WHEN SUBSTRING([RowLog Contents 0], 1, 1) In (0x10,0x30,0x70) THEN
SUBSTRING([RowLog Contents 0]
, CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 3
+ CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2)
,REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)) + 2
, (CASE WHEN SUBSTRING([RowLog Contents 0], 1, 1) In (0x10,0x30,0x70) THEN
CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0],
CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 3
+ CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2)
,REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)), 2))))  ELSE null  END)
* 2)  ELSE null  END) AS [ColumnOffsetArray] 
 
--  Variable column Start = Status Bit A+ Status Bit B + [Fixed Length Data] + [Null Bitmap length] + 2+([TotalNoofVarCols]*2)
,CASE WHEN SUBSTRING([RowLog Contents 0], 1, 1)In (0x10,0x30,0x70)
THEN  (
CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 4 
 
+ CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2)
,REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)) 
 
+ ((CASE WHEN SUBSTRING([RowLog Contents 0], 1, 1) In (0x10,0x30,0x70) THEN
CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0],
CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 3
+ CONVERT(INT, ceiling(CONVERT(INT, CONVERT(BINARY(2), REVERSE(SUBSTRING([RowLog Contents 0], CONVERT(SMALLINT, CONVERT(BINARY(2)
,REVERSE(SUBSTRING([RowLog Contents 0], 2 + 1, 2)))) + 1, 2))))/8.0)), 2))))  ELSE null  END) * 2)) 
 
ELSE null End AS [VarColumnStart]
,[Slot ID]
FROM sys.fn_dblog(NULL, NULL)
WHERE
AllocUnitId IN
(SELECT [Allocation_unit_id] FROM sys.allocation_units allocunits
INNER JOIN sys.partitions partitions ON (allocunits.type IN (1, 3)  
AND partitions.hobt_id = allocunits.container_id) OR (allocunits.type = 2 
AND partitions.partition_id = allocunits.container_id)  
WHERE object_id=object_ID('' + @SchemaName_n_TableName + ''))
 
AND Context IN ('LCX_MARK_AS_GHOST', 'LCX_HEAP') AND Operation in ('LOP_DELETE_ROWS') 
And SUBSTRING([RowLog Contents 0], 1, 1)In (0x10,0x30,0x70)
 
/*Use this subquery to filter the date*/
AND [TRANSACTION ID] IN (SELECT DISTINCT [TRANSACTION ID] FROM    sys.fn_dblog(NULL, NULL) 
WHERE Context IN ('LCX_NULL') AND Operation in ('LOP_BEGIN_XACT')  
And [Transaction Name] In ('DELETE','user_transaction')
And  CONVERT(NVARCHAR(11),[Begin Time]) BETWEEN @Date_From AND @Date_To)),
 
--Use this technique to repeate the row till the no of bytes of the row.
N1 (n) AS (SELECT 1 UNION ALL SELECT 1),
N2 (n) AS (SELECT 1 FROM N1 AS X, N1 AS Y),
N3 (n) AS (SELECT 1 FROM N2 AS X, N2 AS Y),
N4 (n) AS (SELECT ROW_NUMBER() OVER(ORDER BY X.n)
           FROM N3 AS X, N3 AS Y)
 
 
 
INSERT INTO @DeletedRecords
SELECT  RowLogContents
        ,[AllocUnitID]
        ,[Transaction ID]
        ,[FixedLengthData]
        ,[TotalNoOfCols]
        ,[NullBitMapLength]
        ,[NullBytes]
        ,[TotalNoofVarCols]
        ,[ColumnOffsetArray]
        ,[VarColumnStart]
        ,[Slot ID]
         ---Get the Null value against each column (1 means null zero means not null)
        ,[NullBitMap]=(REPLACE(STUFF((SELECT ',' +
        (CASE WHEN [ID]=0 THEN CONVERT(NVARCHAR(1),(SUBSTRING(NullBytes, n, 1) % 2))  ELSE CONVERT(NVARCHAR(1),((SUBSTRING(NullBytes, n, 1) / [Bitvalue]) % 2)) END) --as [nullBitMap]
         
FROM
N4 AS Nums
Join RowData AS C ON n<=NullBitMapLength
Cross Join @bitTable WHERE C.[RowLogContents]=D.[RowLogContents] ORDER BY [RowLogContents],n ASC FOR XML PATH('')),1,1,''),',',''))
FROM RowData D
 
IF (SELECT COUNT(*) FROM @DeletedRecords)=0
BEGIN
    RAISERROR('There is no data in the log as per the search criteria',16,1)
    RETURN
END
 
DECLARE @ColumnNameAndData TABLE
(
 [Row ID]           int,
 [Rowlogcontents]   varbinary(Max),
 [NAME]             sysname,
 [nullbit]          smallint,
 [leaf_offset]      smallint,
 [length]           smallint,
 [system_type_id]   tinyint,
 [bitpos]           tinyint,
 [xprec]            tinyint,
 [xscale]           tinyint,
 [is_null]          int,
 [Column value Size]int,
 [Column Length]    int,
 [hex_Value]        varbinary(max),
 [Slot ID]          int,
 [Update]           int
)
 
--Create common table expression and join it with the rowdata table
-- to get each column details
/*This part is for variable data columns*/
--@RowLogContents, 
--(col.columnOffValue - col.columnLength) + 1,
--col.columnLength
--)
INSERT INTO @ColumnNameAndData
SELECT
[Row ID],
Rowlogcontents,
NAME ,
cols.leaf_null_bit AS nullbit,
leaf_offset,
ISNULL(syscolumns.length, cols.max_length) AS [length],
cols.system_type_id,
cols.leaf_bit_position AS bitpos,
ISNULL(syscolumns.xprec, cols.precision) AS xprec,
ISNULL(syscolumns.xscale, cols.scale) AS xscale,
SUBSTRING([nullBitMap], cols.leaf_null_bit, 1) AS is_null,
(CASE WHEN leaf_offset<1 and SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0 
THEN
(Case When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) >30000
THEN
CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) - POWER(2, 15)
ELSE
CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2))))
END)
END)  AS [Column value Size],
 
(CASE WHEN leaf_offset<1 and SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=0  THEN
(Case
 
When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) >30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])<30000
THEN  (Case When [System_type_id]In (35,34,99) Then 16 else 24  end)
 
When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) >30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])>30000
THEN  (Case When [System_type_id]In (35,34,99) Then 16 else 24  end) --24 
 
When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) <30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])<30000
THEN (CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2))))
- ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart]))
 
When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) <30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])>30000
 
THEN POWER(2, 15) +CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2))))
- ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])
 
END)
 
END) AS [Column Length]
 
,(CASE WHEN SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=1 THEN  NULL ELSE
 SUBSTRING
 (
 Rowlogcontents, 
 (
 
(Case When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) >30000
THEN
CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) - POWER(2, 15)
ELSE
CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2))))
END)
 
 - 
(Case When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) >30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])<30000
 
THEN  (Case When [System_type_id]In (35,34,99) Then 16 else 24  end) --24 
When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) >30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])>30000
 
THEN  (Case When [System_type_id]In (35,34,99) Then 16 else 24  end) --24 
When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) <30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])<30000
 
THEN CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2))))
- ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])
 
When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) <30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])>30000
 
THEN POWER(2, 15) +CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2))))
- ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])
 
END)
 
) + 1,
(Case When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) >30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])<30000
 
THEN  (Case When [System_type_id] In (35,34,99) Then 16 else 24  end) --24 
When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) >30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])>30000
 
THEN  (Case When [System_type_id] In (35,34,99) Then 16 else 24  end) --24 
When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) <30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])<30000
 
THEN ABS(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2))))
- ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart]))
 
When CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2)))) <30000 And
ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])>30000
 
THEN POWER(2, 15) +CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * leaf_offset*-1) - 1, 2))))
- ISNULL(NULLIF(CONVERT(INT, CONVERT(BINARY(2), REVERSE (SUBSTRING ([ColumnOffsetArray], (2 * ((leaf_offset*-1) - 1)) - 1, 2)))), 0), [varColumnStart])
 
END)
)
 
END) AS hex_Value
,[Slot ID]
,0
FROM @DeletedRecords A
Inner Join sys.allocation_units allocunits On A.[AllocUnitId]=allocunits.[Allocation_Unit_Id]
INNER JOIN sys.partitions partitions ON (allocunits.type IN (1, 3)
AND partitions.hobt_id = allocunits.container_id) OR (allocunits.type = 2 AND partitions.partition_id = allocunits.container_id)
INNER JOIN sys.system_internals_partition_columns cols ON cols.partition_id = partitions.partition_id
LEFT OUTER JOIN syscolumns ON syscolumns.id = partitions.object_id AND syscolumns.colid = cols.partition_column_id
WHERE leaf_offset<0
UNION
/*This part is for fixed data columns*/
SELECT 
[Row ID],
Rowlogcontents,
NAME ,
cols.leaf_null_bit AS nullbit,
leaf_offset,
ISNULL(syscolumns.length, cols.max_length) AS [length],
cols.system_type_id,
cols.leaf_bit_position AS bitpos,
ISNULL(syscolumns.xprec, cols.precision) AS xprec,
ISNULL(syscolumns.xscale, cols.scale) AS xscale,
SUBSTRING([nullBitMap], cols.leaf_null_bit, 1) AS is_null,
(SELECT TOP 1 ISNULL(SUM(CASE WHEN C.leaf_offset >1 THEN max_length ELSE 0 END),0) FROM
sys.system_internals_partition_columns C WHERE cols.partition_id =C.partition_id And C.leaf_null_bit<cols.leaf_null_bit)+5 AS [Column value Size],
syscolumns.length AS [Column Length]
 
,CASE WHEN SUBSTRING([nullBitMap], cols.leaf_null_bit, 1)=1 THEN NULL ELSE
SUBSTRING
(
Rowlogcontents,(SELECT TOP 1 ISNULL(SUM(CASE WHEN C.leaf_offset >1 And C.leaf_bit_position=0 THEN max_length ELSE 0 END),0) FROM
sys.system_internals_partition_columns C where cols.partition_id =C.partition_id And C.leaf_null_bit<cols.leaf_null_bit)+5
,syscolumns.length) END AS hex_Value
,[Slot ID]
,0
FROM @DeletedRecords A
Inner Join sys.allocation_units allocunits ON A.[AllocUnitId]=allocunits.[Allocation_Unit_Id]
INNER JOIN sys.partitions partitions ON (allocunits.type IN (1, 3)
AND partitions.hobt_id = allocunits.container_id) OR (allocunits.type = 2 AND partitions.partition_id = allocunits.container_id)
INNER JOIN sys.system_internals_partition_columns cols ON cols.partition_id = partitions.partition_id
LEFT OUTER JOIN syscolumns ON syscolumns.id = partitions.object_id AND syscolumns.colid = cols.partition_column_id
WHERE leaf_offset>0
Order By nullbit
 
Declare @BitColumnByte as int
Select @BitColumnByte=CONVERT(INT, ceiling( Count(*)/8.0)) from @ColumnNameAndData Where [System_Type_id]=104
 
;With N1 (n) AS (SELECT 1 UNION ALL SELECT 1),
N2 (n) AS (SELECT 1 FROM N1 AS X, N1 AS Y),
N3 (n) AS (SELECT 1 FROM N2 AS X, N2 AS Y),
N4 (n) AS (SELECT ROW_NUMBER() OVER(ORDER BY X.n)
           FROM N3 AS X, N3 AS Y),
CTE As(
Select RowLogContents,[nullbit]
        ,[BitMap]=Convert(varbinary(1),Convert(int,Substring((REPLACE(STUFF((SELECT ',' +
        (CASE WHEN [ID]=0 THEN CONVERT(NVARCHAR(1),(SUBSTRING(hex_Value, n, 1) % 2))  ELSE CONVERT(NVARCHAR(1),((SUBSTRING(hex_Value, n, 1) / [Bitvalue]) % 2)) END) --as [nullBitMap]
 
from N4 AS Nums
Join @ColumnNameAndData AS C ON n<=@BitColumnByte And [System_Type_id]=104 And bitpos=0
Cross Join @bitTable WHERE C.[RowLogContents]=D.[RowLogContents] ORDER BY [RowLogContents],n ASC FOR XML PATH('')),1,1,''),',','')),bitpos+1,1)))
FROM @ColumnNameAndData D Where  [System_Type_id]=104)
 
Update A Set [hex_Value]=[BitMap]
from @ColumnNameAndData  A
Inner Join CTE B On A.[RowLogContents]=B.[RowLogContents]
And A.[nullbit]=B.[nullbit]
 
 
/**************Check for BLOB DATA TYPES******************************/
DECLARE @Fileid INT
DECLARE @Pageid INT
DECLARE @Slotid INT
DECLARE @CurrentLSN INT
DECLARE @LinkID INT
DECLARE @Context VARCHAR(50)
DECLARE @ConsolidatedPageID VARCHAR(MAX)
DECLARE @LCX_TEXT_MIX VARBINARY(MAX)
 
declare @temppagedata table
(
[ParentObject] sysname,
[Object] sysname,
[Field] sysname,
[Value] sysname)
 
declare @pagedata table
(
[Page ID] sysname,
[File IDS] int,
[Page IDS] int,
[AllocUnitId] bigint,
[ParentObject] sysname,
[Object] sysname,
[Field] sysname,
[Value] sysname)
 
DECLARE @ModifiedRawData TABLE
(
  [ID] INT IDENTITY(1,1),
  [PAGE ID] VARCHAR(MAX),
  [FILE IDS] INT,
  [PAGE IDS] INT,
  [Slot ID]  INT,
  [AllocUnitId] BIGINT,
  [RowLog Contents 0_var] VARCHAR(Max),
  [RowLog Length] VARCHAR(50),
  [RowLog Len] INT,
  [RowLog Contents 0] VARBINARY(Max),
  [Link ID] INT default (0),
  [Update] INT
)
 
            DECLARE Page_Data_Cursor CURSOR FOR
            /*We need to filter LOP_MODIFY_ROW,LOP_MODIFY_COLUMNS from log for deleted records of BLOB data type& Get its Slot No, Page ID & AllocUnit ID*/
            SELECT LTRIM(RTRIM(Replace([Description],'Deallocated',''))) AS [PAGE ID]
            ,[Slot ID],[AllocUnitId],NULL AS [RowLog Contents 0],NULL AS [RowLog Contents 0],Context
            FROM    sys.fn_dblog(NULL, NULL)  
            WHERE   
            AllocUnitId IN
            (SELECT [Allocation_unit_id] FROM sys.allocation_units allocunits
            INNER JOIN sys.partitions partitions ON (allocunits.type IN (1, 3)  
            AND partitions.hobt_id = allocunits.container_id) OR (allocunits.type = 2 
            AND partitions.partition_id = allocunits.container_id)  
            WHERE object_id=object_ID('' + @SchemaName_n_TableName + ''))
            AND Operation IN ('LOP_MODIFY_ROW') AND [Context] IN ('LCX_PFS') 
            AND Description Like '%Deallocated%'
            /*Use this subquery to filter the date*/
            AND [TRANSACTION ID] IN (SELECT DISTINCT [TRANSACTION ID] FROM    sys.fn_dblog(NULL, NULL) 
            WHERE Context IN ('LCX_NULL') AND Operation in ('LOP_BEGIN_XACT')  
            AND [Transaction Name]='DELETE'
            AND  CONVERT(NVARCHAR(11),[Begin Time]) BETWEEN @Date_From AND @Date_To)
            GROUP BY [Description],[Slot ID],[AllocUnitId],Context
 
            UNION
 
            SELECT [PAGE ID],[Slot ID],[AllocUnitId]
            ,Substring([RowLog Contents 0],15,LEN([RowLog Contents 0])) AS [RowLog Contents 0]
            ,CONVERT(INT,Substring([RowLog Contents 0],7,2)),Context --,CAST(RIGHT([Current LSN],4) AS INT) AS [Current LSN]
            FROM    sys.fn_dblog(NULL, NULL)  
            WHERE  
             AllocUnitId IN
            (SELECT [Allocation_unit_id] FROM sys.allocation_units allocunits
            INNER JOIN sys.partitions partitions ON (allocunits.type IN (1, 3)  
            AND partitions.hobt_id = allocunits.container_id) OR (allocunits.type = 2 
            AND partitions.partition_id = allocunits.container_id)  
            WHERE object_id=object_ID('' + @SchemaName_n_TableName + ''))
            AND Context IN ('LCX_TEXT_MIX') AND Operation in ('LOP_DELETE_ROWS') 
            /*Use this subquery to filter the date*/
            AND [TRANSACTION ID] IN (SELECT DISTINCT [TRANSACTION ID] FROM    sys.fn_dblog(NULL, NULL) 
            WHERE Context IN ('LCX_NULL') AND Operation in ('LOP_BEGIN_XACT')  
            And [Transaction Name]='DELETE'
            And  CONVERT(NVARCHAR(11),[Begin Time]) BETWEEN @Date_From AND @Date_To)
                         
            /****************************************/
 
        OPEN Page_Data_Cursor
 
        FETCH NEXT FROM Page_Data_Cursor INTO @ConsolidatedPageID, @Slotid,@AllocUnitID,@LCX_TEXT_MIX,@LinkID,@Context
 
        WHILE @@FETCH_STATUS = 0
        BEGIN
            DECLARE @hex_pageid AS VARCHAR(Max)
            /*Page ID contains File Number and page number It looks like 0001:00000130.
              In this example 0001 is file Number &  00000130 is Page Number & These numbers are in Hex format*/
            SET @Fileid=SUBSTRING(@ConsolidatedPageID,0,CHARINDEX(':',@ConsolidatedPageID)) -- Seperate File ID from Page ID
         
            SET @hex_pageid ='0x'+ SUBSTRING(@ConsolidatedPageID,CHARINDEX(':',@ConsolidatedPageID)+1,Len(@ConsolidatedPageID))  ---Seperate the page ID
            SELECT @Pageid=Convert(INT,cast('' AS XML).value('xs:hexBinary(substring(sql:variable("@hex_pageid"),sql:column("t.pos")) )', 'varbinary(max)')) -- Convert Page ID from hex to integer
            FROM (SELECT CASE substring(@hex_pageid, 1, 2) WHEN '0x' THEN 3 ELSE 0 END) AS t(pos) 
             
            IF @Context='LCX_PFS'    
              BEGIN
                        DELETE @temppagedata
                        INSERT INTO @temppagedata EXEC( 'DBCC PAGE(' + @DataBase_Name + ', ' + @fileid + ', ' + @pageid + ', 1) with tableresults,no_infomsgs;'); 
                        INSERT INTO @pagedata SELECT @ConsolidatedPageID,@fileid,@pageid,@AllocUnitID,[ParentObject],[Object],[Field] ,[Value] FROM @temppagedata
              END
            ELSE IF @Context='LCX_TEXT_MIX'
              BEGIN
                        INSERT INTO  @ModifiedRawData SELECT @ConsolidatedPageID,@fileid,@pageid,@Slotid,@AllocUnitID,NULL,0,CONVERT(INT,CONVERT(VARBINARY,REVERSE(SUBSTRING(@LCX_TEXT_MIX,11,2)))),@LCX_TEXT_MIX,@LinkID,0
              END    
            FETCH NEXT FROM Page_Data_Cursor INTO  @ConsolidatedPageID, @Slotid,@AllocUnitID,@LCX_TEXT_MIX,@LinkID,@Context
        END
     
    CLOSE Page_Data_Cursor
    DEALLOCATE Page_Data_Cursor
 
    DECLARE @Newhexstring VARCHAR(MAX);
 
    --The data is in multiple rows in the page, so we need to convert it into one row as a single hex value.
    --This hex value is in string format
    INSERT INTO @ModifiedRawData ([PAGE ID],[FILE IDS],[PAGE IDS],[Slot ID],[AllocUnitId]
    ,[RowLog Contents 0_var]
    , [RowLog Length])
    SELECT [Page ID],[FILE IDS],[PAGE IDS],Substring([ParentObject],CHARINDEX('Slot', [ParentObject])+4, (CHARINDEX('Offset', [ParentObject])-(CHARINDEX('Slot', [ParentObject])+4))-2 ) as [Slot ID]
    ,[AllocUnitId]
    ,Substring((
    SELECT
    REPLACE(STUFF((SELECT REPLACE(SUBSTRING([Value],CHARINDEX(':',[Value])+1,CHARINDEX('†',[Value])-CHARINDEX(':',[Value])),'†','')
    FROM @pagedata C  WHERE B.[Page ID]= C.[Page ID] And Substring(B.[ParentObject],CHARINDEX('Slot', B.[ParentObject])+4, (CHARINDEX('Offset', B.[ParentObject])-(CHARINDEX('Slot', B.[ParentObject])+4)) )=Substring(C.[ParentObject],CHARINDEX('Slot', C.[ParentObject])+4, (CHARINDEX('Offset', C.[ParentObject])-(CHARINDEX('Slot', C.[ParentObject])+4)) ) And
    [Object] Like '%Memory Dump%'  Order By '0x'+ LEFT([Value],CHARINDEX(':',[Value])-1)
    FOR XML PATH('') ),1,1,'') ,' ','')
    ),1,20000) AS [Value]
     
    ,
     Substring((
    SELECT '0x' +REPLACE(STUFF((SELECT REPLACE(SUBSTRING([Value],CHARINDEX(':',[Value])+1,CHARINDEX('†',[Value])-CHARINDEX(':',[Value])),'†','')
    FROM @pagedata C  WHERE B.[Page ID]= C.[Page ID] And Substring(B.[ParentObject],CHARINDEX('Slot', B.[ParentObject])+4, (CHARINDEX('Offset', B.[ParentObject])-(CHARINDEX('Slot', B.[ParentObject])+4)) )=Substring(C.[ParentObject],CHARINDEX('Slot', C.[ParentObject])+4, (CHARINDEX('Offset', C.[ParentObject])-(CHARINDEX('Slot', C.[ParentObject])+4)) ) And
    [Object] Like '%Memory Dump%'  Order By '0x'+ LEFT([Value],CHARINDEX(':',[Value])-1)
    FOR XML PATH('') ),1,1,'') ,' ','')
    ),7,4) AS [Length]
     
    From @pagedata B
    Where [Object] Like '%Memory Dump%'
    Group By [Page ID],[FILE IDS],[PAGE IDS],[ParentObject],[AllocUnitId]--,[Current LSN]
    Order By [Slot ID]
 
    UPDATE @ModifiedRawData  SET [RowLog Len] = CONVERT(VARBINARY(8000),REVERSE(cast('' AS XML).value('xs:hexBinary(substring(sql:column("[RowLog Length]"),0))', 'varbinary(Max)')))
    FROM @ModifiedRawData Where [LINK ID]=0
 
    UPDATE @ModifiedRawData  SET [RowLog Contents 0] =cast('' AS XML).value('xs:hexBinary(substring(sql:column("[RowLog Contents 0_var]"),0))', 'varbinary(Max)')  
    FROM @ModifiedRawData Where [LINK ID]=0
 
    Update B Set B.[RowLog Contents 0] =
    (CASE WHEN A.[RowLog Contents 0] IS NOT NULL AND C.[RowLog Contents 0] IS NOT NULL THEN  A.[RowLog Contents 0]+C.[RowLog Contents 0] 
        WHEN A.[RowLog Contents 0] IS NULL AND C.[RowLog Contents 0] IS NOT NULL THEN  C.[RowLog Contents 0]
        WHEN A.[RowLog Contents 0] IS NOT NULL AND C.[RowLog Contents 0] IS NULL THEN  A.[RowLog Contents 0]  
        END)
    ,B.[Update]=ISNULL(B.[Update],0)+1
    from @ModifiedRawData B
    LEFT Join @ModifiedRawData A On A.[Page IDS]=Convert(int,Convert(Varbinary(Max),Reverse(Substring(B.[RowLog Contents 0],15+14,2))))
    And A.[File IDS]=Convert(int,Convert(Varbinary(Max),Reverse(Substring(B.[RowLog Contents 0],19+14,2)))) 
    And A.[Link ID]=B.[Link ID]
    LEFT Join @ModifiedRawData C On C.[Page IDS]=Convert(int,Convert(Varbinary(Max),Reverse(Substring(B.[RowLog Contents 0],27+14,2))))
    And C.[File IDS]=Convert(int,Convert(Varbinary(Max),Reverse(Substring(B.[RowLog Contents 0],31+14,2))))
    And C.[Link ID]=B.[Link ID]
    Where  (A.[RowLog Contents 0] IS NOT NULL OR C.[RowLog Contents 0] IS NOT NULL)
 
 
    Update B Set B.[RowLog Contents 0] =
    (CASE WHEN A.[RowLog Contents 0] IS NOT NULL AND C.[RowLog Contents 0] IS NOT NULL THEN  A.[RowLog Contents 0]+C.[RowLog Contents 0] 
        WHEN A.[RowLog Contents 0] IS NULL AND C.[RowLog Contents 0] IS NOT NULL THEN  C.[RowLog Contents 0]
        WHEN A.[RowLog Contents 0] IS NOT NULL AND C.[RowLog Contents 0] IS NULL THEN  A.[RowLog Contents 0]  
        END)
    --,B.[Update]=ISNULL(B.[Update],0)+1
    from @ModifiedRawData B
    LEFT Join @ModifiedRawData A On A.[Page IDS]=Convert(int,Convert(Varbinary(Max),Reverse(Substring(B.[RowLog Contents 0],15+14,2))))
    And A.[File IDS]=Convert(int,Convert(Varbinary(Max),Reverse(Substring(B.[RowLog Contents 0],19+14,2)))) 
    And A.[Link ID]<>B.[Link ID] And B.[Update]=0
    LEFT Join @ModifiedRawData C On C.[Page IDS]=Convert(int,Convert(Varbinary(Max),Reverse(Substring(B.[RowLog Contents 0],27+14,2))))
    And C.[File IDS]=Convert(int,Convert(Varbinary(Max),Reverse(Substring(B.[RowLog Contents 0],31+14,2))))
    And C.[Link ID]<>B.[Link ID] And B.[Update]=0
    Where  (A.[RowLog Contents 0] IS NOT NULL OR C.[RowLog Contents 0] IS NOT NULL)
 
    UPDATE @ModifiedRawData  SET [RowLog Contents 0] =  
    (Case When [RowLog Len]>=8000 Then
    Substring([RowLog Contents 0] ,15,[RowLog Len]) 
    When [RowLog Len]<8000 Then
    SUBSTRING([RowLog Contents 0],15+6,Convert(int,Convert(varbinary(max),REVERSE(Substring([RowLog Contents 0],15,6)))))
    End)
    FROM @ModifiedRawData Where [LINK ID]=0
 
    UPDATE @ColumnNameAndData SET [hex_Value]=[RowLog Contents 0] 
    --,A.[Update]=A.[Update]+1
    FROM @ColumnNameAndData A
    INNER JOIN @ModifiedRawData B ON
    Convert(int,Convert(Varbinary(Max),Reverse(Substring([hex_value],17,4))))=[PAGE IDS]
    AND  Convert(int,Substring([hex_value],9,2)) =B.[Link ID] 
    Where [System_Type_Id] In (99,167,175,231,239,241,165,98) And [Link ID] <>0 
 
    UPDATE @ColumnNameAndData SET [hex_Value]=
    (CASE WHEN B.[RowLog Contents 0] IS NOT NULL AND C.[RowLog Contents 0] IS NOT NULL THEN  B.[RowLog Contents 0]+C.[RowLog Contents 0] 
    WHEN B.[RowLog Contents 0] IS NULL AND C.[RowLog Contents 0] IS NOT NULL THEN  C.[RowLog Contents 0]
    WHEN B.[RowLog Contents 0] IS NOT NULL AND C.[RowLog Contents 0] IS NULL THEN  B.[RowLog Contents 0]  
    END)
    --,A.[Update]=A.[Update]+1
    FROM @ColumnNameAndData A
    LEFT JOIN @ModifiedRawData B ON
    Convert(int,Convert(Varbinary(Max),Reverse(Substring([hex_value],5,4))))=B.[PAGE IDS]  And B.[Link ID] =0 
    LEFT JOIN @ModifiedRawData C ON
    Convert(int,Convert(Varbinary(Max),Reverse(Substring([hex_value],17,4))))=C.[PAGE IDS]  And C.[Link ID] =0 
    Where [System_Type_Id] In (99,167,175,231,239,241,165,98)  And (B.[RowLog Contents 0] IS NOT NULL OR C.[RowLog Contents 0] IS NOT NULL)
 
    UPDATE @ColumnNameAndData SET [hex_Value]=[RowLog Contents 0] 
    --,A.[Update]=A.[Update]+1
    FROM @ColumnNameAndData A
    INNER JOIN @ModifiedRawData B ON
    Convert(int,Convert(Varbinary(Max),Reverse(Substring([hex_value],9,4))))=[PAGE IDS]
    And Convert(int,Substring([hex_value],3,2))=[Link ID]
    Where [System_Type_Id] In (35,34,99) And [Link ID] <>0 
     
    UPDATE @ColumnNameAndData SET [hex_Value]=[RowLog Contents 0]
    --,A.[Update]=A.[Update]+10
    FROM @ColumnNameAndData A
    INNER JOIN @ModifiedRawData B ON
    Convert(int,Convert(Varbinary(Max),Reverse(Substring([hex_value],9,4))))=[PAGE IDS]
    Where [System_Type_Id] In (35,34,99) And [Link ID] =0
 
    UPDATE @ColumnNameAndData SET [hex_Value]=[RowLog Contents 0] 
    --,A.[Update]=A.[Update]+1
    FROM @ColumnNameAndData A
    INNER JOIN @ModifiedRawData B ON
    Convert(int,Convert(Varbinary(Max),Reverse(Substring([hex_value],15,4))))=[PAGE IDS]
    Where [System_Type_Id] In (35,34,99) And [Link ID] =0
 
    Update @ColumnNameAndData set [hex_value]= 0xFFFE + Substring([hex_value],9,LEN([hex_value]))
    --,[Update]=[Update]+1
    Where [system_type_id]=241
 
CREATE TABLE [#temp_Data]
(
    [FieldName]  VARCHAR(MAX),
    [FieldValue] NVARCHAR(MAX),
    [Rowlogcontents] VARBINARY(8000),
    [Row ID] int
)
 
INSERT INTO #temp_Data
SELECT NAME,
CASE
 WHEN system_type_id IN (231, 239) THEN  LTRIM(RTRIM(CONVERT(NVARCHAR(max),hex_Value)))  --NVARCHAR ,NCHAR
 WHEN system_type_id IN (167,175) THEN  LTRIM(RTRIM(CONVERT(VARCHAR(max),hex_Value)))  --VARCHAR,CHAR
 WHEN system_type_id IN (35) THEN  LTRIM(RTRIM(CONVERT(VARCHAR(max),hex_Value))) --Text
 WHEN system_type_id IN (99) THEN  LTRIM(RTRIM(CONVERT(NVARCHAR(max),hex_Value))) --nText 
 WHEN system_type_id = 48 THEN CONVERT(VARCHAR(MAX), CONVERT(TINYINT, CONVERT(BINARY(1), REVERSE (hex_Value)))) --TINY INTEGER
 WHEN system_type_id = 52 THEN CONVERT(VARCHAR(MAX), CONVERT(SMALLINT, CONVERT(BINARY(2), REVERSE (hex_Value)))) --SMALL INTEGER
 WHEN system_type_id = 56 THEN CONVERT(VARCHAR(MAX), CONVERT(INT, CONVERT(BINARY(4), REVERSE(hex_Value)))) -- INTEGER
 WHEN system_type_id = 127 THEN CONVERT(VARCHAR(MAX), CONVERT(BIGINT, CONVERT(BINARY(8), REVERSE(hex_Value))))-- BIG INTEGER
 WHEN system_type_id = 61 Then CONVERT(VARCHAR(MAX),CONVERT(DATETIME,CONVERT(VARBINARY(8000),REVERSE (hex_Value))),100) --DATETIME
 WHEN system_type_id =58 Then CONVERT(VARCHAR(MAX),CONVERT(SMALLDATETIME,CONVERT(VARBINARY(8000),REVERSE(hex_Value))),100) --SMALL DATETIME
 WHEN system_type_id = 108 THEN CONVERT(VARCHAR(MAX),CONVERT(NUMERIC(38,20), CONVERT(VARBINARY,CONVERT(VARBINARY(1),xprec)+CONVERT(VARBINARY(1),xscale))+CONVERT(VARBINARY(1),0) + hex_Value)) --- NUMERIC
 WHEN system_type_id =106 THEN CONVERT(VARCHAR(MAX), CONVERT(DECIMAL(38,20), CONVERT(VARBINARY,Convert(VARBINARY(1),xprec)+CONVERT(VARBINARY(1),xscale))+CONVERT(VARBINARY(1),0) + hex_Value)) --- DECIMAL
 WHEN system_type_id In(60,122) THEN CONVERT(VARCHAR(MAX),Convert(MONEY,Convert(VARBINARY(8000),Reverse(hex_Value))),2) --MONEY,SMALLMONEY
 WHEN system_type_id = 104 THEN CONVERT(VARCHAR(MAX),CONVERT (BIT,CONVERT(BINARY(1), hex_Value)%2))  -- BIT
 WHEN system_type_id =62 THEN  RTRIM(LTRIM(STR(CONVERT(FLOAT,SIGN(CAST(CONVERT(VARBINARY(8000),Reverse(hex_Value)) AS BIGINT)) * (1.0 + (CAST(CONVERT(VARBINARY(8000),Reverse(hex_Value)) AS BIGINT) & 0x000FFFFFFFFFFFFF) * POWER(CAST(2 AS FLOAT), -52)) * POWER(CAST(2 AS FLOAT),((CAST(CONVERT(VARBINARY(8000),Reverse(hex_Value)) AS BIGINT) & 0x7ff0000000000000) / EXP(52 * LOG(2))-1023))),53,LEN(hex_Value)))) --- FLOAT
 When system_type_id =59 THEN  Left(LTRIM(STR(CAST(SIGN(CAST(Convert(VARBINARY(8000),REVERSE(hex_Value)) AS BIGINT))* (1.0 + (CAST(CONVERT(VARBINARY(8000),Reverse(hex_Value)) AS BIGINT) & 0x007FFFFF) * POWER(CAST(2 AS Real), -23)) * POWER(CAST(2 AS Real),(((CAST(CONVERT(VARBINARY(8000),Reverse(hex_Value)) AS INT) )& 0x7f800000)/ EXP(23 * LOG(2))-127))AS REAL),23,23)),8) --Real
 WHEN system_type_id In (165,173) THEN (CASE WHEN CHARINDEX(0x,cast('' AS XML).value('xs:hexBinary(sql:column("hex_Value"))', 'VARBINARY(8000)')) = 0 THEN '0x' ELSE '' END) +cast('' AS XML).value('xs:hexBinary(sql:column("hex_Value"))', 'varchar(max)') -- BINARY,VARBINARY
 WHEN system_type_id =34 THEN (CASE WHEN CHARINDEX(0x,cast('' AS XML).value('xs:hexBinary(sql:column("hex_Value"))', 'VARBINARY(8000)')) = 0 THEN '0x' ELSE '' END) +cast('' AS XML).value('xs:hexBinary(sql:column("hex_Value"))', 'varchar(max)')  --IMAGE
 WHEN system_type_id =36 THEN CONVERT(VARCHAR(MAX),CONVERT(UNIQUEIDENTIFIER,hex_Value)) --UNIQUEIDENTIFIER
 WHEN system_type_id =231 THEN CONVERT(VARCHAR(MAX),CONVERT(sysname,hex_Value)) --SYSNAME
 WHEN system_type_id =241 THEN CONVERT(VARCHAR(MAX),CONVERT(xml,hex_Value)) --XML
 
 WHEN system_type_id =189 THEN (CASE WHEN CHARINDEX(0x,cast('' AS XML).value('xs:hexBinary(sql:column("hex_Value"))', 'VARBINARY(8000)')) = 0 THEN '0x' ELSE '' END) +cast('' AS XML).value('xs:hexBinary(sql:column("hex_Value"))', 'varchar(max)') --TIMESTAMP
 WHEN system_type_id=98 THEN (CASE
 WHEN CONVERT(INT,SUBSTRING(hex_Value,1,1))=56 THEN CONVERT(VARCHAR(MAX), CONVERT(INT, CONVERT(BINARY(4), REVERSE(Substring(hex_Value,3,Len(hex_Value))))))  -- INTEGER
 WHEN CONVERT(INT,SUBSTRING(hex_Value,1,1))=108 THEN CONVERT(VARCHAR(MAX),CONVERT(numeric(38,20),CONVERT(VARBINARY(1),Substring(hex_Value,3,1)) +CONVERT(VARBINARY(1),Substring(hex_Value,4,1))+CONVERT(VARBINARY(1),0) + Substring(hex_Value,5,Len(hex_Value)))) --- NUMERIC
 WHEN CONVERT(INT,SUBSTRING(hex_Value,1,1))=167 THEN LTRIM(RTRIM(CONVERT(VARCHAR(max),Substring(hex_Value,9,Len(hex_Value))))) --VARCHAR,CHAR
 WHEN CONVERT(INT,SUBSTRING(hex_Value,1,1))=36 THEN CONVERT(VARCHAR(MAX),CONVERT(UNIQUEIDENTIFIER,Substring((hex_Value),3,20))) --UNIQUEIDENTIFIER
 WHEN CONVERT(INT,SUBSTRING(hex_Value,1,1))=61 THEN CONVERT(VARCHAR(MAX),CONVERT(DATETIME,CONVERT(VARBINARY(8000),REVERSE (Substring(hex_Value,3,LEN(hex_Value)) ))),100) --DATETIME
 WHEN CONVERT(INT,SUBSTRING(hex_Value,1,1))=165 THEN '0x'+ SUBSTRING((CASE WHEN CHARINDEX(0x,cast('' AS XML).value('xs:hexBinary(sql:column("hex_Value"))', 'VARBINARY(8000)')) = 0 THEN '0x' ELSE '' END) +cast('' AS XML).value('xs:hexBinary(sql:column("hex_Value"))', 'varchar(max)'),11,LEN(hex_Value)) -- BINARY,VARBINARY
 END)
  
END AS FieldValue
,[Rowlogcontents]
,[Row ID]
FROM @ColumnNameAndData ORDER BY nullbit
 
--Create the column name in the same order to do pivot table.
 
DECLARE @FieldName VARCHAR(max)
SET @FieldName = STUFF(
(
    SELECT ',' + CAST(QUOTENAME([Name]) AS VARCHAR(MAX)) FROM syscolumns WHERE id=object_id('' + @SchemaName_n_TableName + '')
    FOR XML PATH('')), 1, 1, '')
 
--Finally did pivot table and get the data back in the same format.
 
SET @sql = 'SELECT ' + @FieldName  + ' FROM #temp_Data PIVOT (Min([FieldValue]) FOR FieldName IN (' + @FieldName  + ')) AS pvt'
EXEC sp_executesql @sql

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- EXEC SP_GetAttandanceData 3,2019,1101  
CREATE OR ALTER PROCEDURE [dbo].[SP_GetAttandanceData]          
@Monthid int,          
@year int,          
@Orgid int,          
@EmpID varchar(100) = Null          
AS          
BEGIN          
          
 SET NOCOUNT ON;          
          
 --create table #tbl (id int identity(1,1),EmpCode BigInt,EMPID Varchar(50))          
 create table #tbl (id int identity(1,1),EmpCode varchar(50),EMPID BIGINT)          
          
 --------------------------  Get Employee Id -----------------------------          
     
 insert into #tbl          
 select distinct(Code),Id from sHrm.tEmployeeMaster 
 where (@EmpID = sHrm.tEmployeeMaster.id or @EmpID is null)         
 and OrgID = @Orgid AND  ISNULL(IsOtherUser,0) = 0     
  
 ---------------------------------------------------------------------------------------          
 --------------------- Insert All Records INTO Temp Table from sBiometric.tProcess ----------------          
          
 CREATE TABLE [dbo].[#temptbl](          
 [ProcessId] [int] IDENTITY(1000,1) NOT NULL,          
 [AtdDate] [datetime] NULL,          
 [StartTime] [nvarchar](20) NULL,          
 [CheckInTime] [nvarchar](20) NULL,          
 [LateComeTime] [nvarchar](20) NULL,          
 [EndTime] [nvarchar](20) NULL,          
 [CheckOutTime] [nvarchar](20) NULL,          
 [EarlyLeaveTime] [nvarchar](10) NULL,          
 [ActualHrs] [nvarchar](20) NULL,          
 [TotalTimeHrs] [varchar](40) NULL,          
 [TotalLate] [nvarchar](20) NULL,          
 [OT] [nvarchar](20) NULL,          
 [Status] [nvarchar](20) NULL,          
 [EmpCode] [nvarchar](40) NULL,          
 [SourceId] [bigint] NULL,          
 [SourceTypeId] [int] NULL ) ON [PRIMARY]          
          
 -- Start Date         
 declare @date varchar(10) = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 1) as date))          
          
 declare @i int=1;          
 declare @j int =1;          
 DECLARE @COUNT INT =1;          
 DECLARE @EMPCODE varchar(50);          
 DECLARE @lEmpId bigint        
         
 -- Month Days        
 declare @days int= (select DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,@date),0))))           
 set @date = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 1) as date))            
 SET @COUNT = (SELECT COUNT(*) FROM #TBL)          
     
 insert into #temptbl          
 select AtdDate,StartTime,CheckInTime,LateComeTime,EndTime,CheckOutTime,EarlyLeaveTime,ActualHrs,TotalTimeHrs,          
 TotalLate,OT,Status,EmpCode,Sourceid,SourceTypeId from sBiometric.tProcess          
 left join sHrm.tEmployeeMaster on sHrm.tEmployeeMaster.id = sBiometric.tProcess.Sourceid  
 where MONTH(sBiometric.tProcess.atddate) = @Monthid          
 and year(sBiometric.tProcess.atddate) =@year          
 and sHrm.tEmployeeMaster.Orgid = @Orgid    
 and (@EmpID = sHrm.tEmployeeMaster.Id or @EmpID is null)  
 AND  ISNULL(IsOtherUser,0) = 0     
   
 --Select * from #temptbl  
  
 while (@j <= (select count(*) from #tbl))  --Looping upto Distinct Employee Table Records        
 begin          
 set @i=1;          
        
 set @days = (select DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,@date),0))))          
  while(@i<=@days)          
  begin            
   --SET @EMPCODE = (SELECT TOP 1 EMPID FROM #tbl WHERE ID = @j)         
   SELECT @EMPCODE=EmpCode,@lEmpId=EMPID From #tbl Where ID = @j        
                   
   set @date = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, @i) as date))          
          
   IF((Select count(*) from sBiometric.tProcess where DATEDIFF(day,@date,AtdDate) = 0 and Sourceid = @lEmpId) <= 0)          
   begin    
    Insert into #temptbl(AtdDate,Status,EmpCode,Sourceid,SourceTypeId)          
    select @date,'A',@EMPCODE,@lEmpId,3        
    --(select top 1 sourceid from sBiometric.tProcess where SourceId = @lEmpId), ----------------?????????????          
    --(select top 1 SourceTypeId from sBiometric.tProcess where SourceId = @lEmpId) ----------------?????????????          
   end  
   set @i = @i+1;  
   set @count = @COUNT + 1;  
  end  
   -- Delete From sBiometric.tMonthTrans              
 delete from sBiometric.tMonthTrans where EmployeeId =@lEmpId and MONTH(Attn_Dt) = @Monthid  and year(Attn_Dt) = @year            
   --Insert into sBiometric.tMonthTrans Blank Data         
 Insert into sBiometric.tMonthTrans (EmployeeId,Attn_Dt,EmpCode)           
 select distinct @lEmpId,(SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 1) as date)) as atddate,1
  -----          
  set @j = @j +1;          
 end     
      
   --select * from #temptbl        
 --------------------------------- Update sBiometric.tMonthTrans Data (With Days) ----------------------------------------------------          
 set @j =1;          
 Declare @totalhour int = 0;        
 Declare @totalEarly int = 0;        
 Declare @totalLate int  = 0;      
 Declare @totalOT int  = 0;      
   
 while (@j <= (select count(*) from #tbl))          
 begin          
     
 set @I =1;           
     
 set @days= (select DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,@date),0))))             
     
 SELECT @EMPCODE=EmpCode,@lEmpId=EMPID From #tbl Where ID = @j        
     
 declare @date1 varchar(20) = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 1) as date))          
     
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 1) as date))          
 Update sBiometric.tMonthTrans set D01 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))            
 ,D01_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D01_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D01_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D01_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D01_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D01_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D01_S = (isnull((select top 1 'SHIFT ' + convert(varchar(1),shiftid)  from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D01_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and EmployeeId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId        
     
 set @totalEarly = (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 2) as date))          
 Update sBiometric.tMonthTrans set D02 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D02_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D02_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D02_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D02_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D02_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D02_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D02_S = (isnull((select top 1 'SHIFT ' + convert(varchar(1),shiftid)  from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D02_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
       
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
         
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 3) as date))          
 Update sBiometric.tMonthTrans set D03 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D03_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D03_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D03_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D03_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D03_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D03_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D03_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid)  from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D03_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 4) as date))          
 Update sBiometric.tMonthTrans set D04 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D04_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D04_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D04_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D04_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D04_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D04_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D04_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid)  from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D04_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
           
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 5) as date))          
 Update sBiometric.tMonthTrans set D05 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D05_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D05_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D05_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D05_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D05_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D05_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D05_S = (isnull((select top 1 'SHIFT ' + convert(varchar(1),shiftid)  from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D05_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
           
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 6) as date))          
 Update sBiometric.tMonthTrans set D06 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D06_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D06_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D06_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D06_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D06_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D06_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D06_S = (isnull((select top 1 'SHIFT ' + convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D06_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
           
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 7) as date))          
 Update sBiometric.tMonthTrans set D07 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))          
 ,D07_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))           
 ,D07_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D07_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D07_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D07_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D07_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D07_S = (isnull((select top 1 'SHIFT ' + convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D07_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 8) as date))          
 Update sBiometric.tMonthTrans set D08 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))          
 ,D08_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))           
 ,D08_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D08_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D08_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D08_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D08_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D08_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid)  from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D08_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
        
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 9) as date))          
 Update sBiometric.tMonthTrans set D09 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D09_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D09_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D09_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D09_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D09_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D09_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D09_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D09_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 10) as date))          
 Update sBiometric.tMonthTrans set D10 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D10_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D10_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D10_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D10_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D10_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D10_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D10_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D10_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
           
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 11) as date))          
 Update sBiometric.tMonthTrans set D11 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))          
 ,D11_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))           
 ,D11_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D11_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D11_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D11_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D11_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D11_S = (isnull((select top 1 'SHIFT ' + convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D11_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 12) as date))          
 Update sBiometric.tMonthTrans set D12 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D12_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D12_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D12_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D12_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D12_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D12_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D12_S = (isnull((select top 1 'SHIFT ' + convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D12_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 13) as date))          
 Update sBiometric.tMonthTrans set D13 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D13_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D13_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D13_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D13_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D13_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D13_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D13_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D13_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 14) as date))          
 Update sBiometric.tMonthTrans set D14 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D14_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D14_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D14_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D14_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D14_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D14_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D14_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D14_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 15) as date))          
 Update sBiometric.tMonthTrans set D15 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))          
 ,D15_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))           
 ,D15_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D15_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D15_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D15_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D15_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D15_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D15_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 16) as date))          
 Update sBiometric.tMonthTrans set D16 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D16_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D16_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D16_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D16_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D16_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D16_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D16_S = (isnull((select top 1 'SHIFT ' + convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D16_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 17) as date))          
 Update sBiometric.tMonthTrans set D17 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D17_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D17_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D17_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D17_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D17_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D17_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D17_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D17_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 18) as date))          
 Update sBiometric.tMonthTrans set D18 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D18_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D18_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D18_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D18_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D18_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D18_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D18_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D18_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 19) as date))          
 Update sBiometric.tMonthTrans set D19 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D19_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D19_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D19_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D19_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D19_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D19_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))   
 ,D19_S = (isnull((select top 1 'SHIFT ' + convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D19_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
           
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 20) as date))          
 Update sBiometric.tMonthTrans set D20 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D20_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D20_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D20_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D20_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D20_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D20_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D20_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D20_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 21) as date))          
 Update sBiometric.tMonthTrans set D21 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D21_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D21_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D21_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D21_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D21_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D21_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D21_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D21_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 22) as date))          
 Update sBiometric.tMonthTrans set D22 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D22_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D22_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D22_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D22_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D22_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D22_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D22_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D22_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 23) as date))          
 Update sBiometric.tMonthTrans set D23 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D23_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D23_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D23_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D23_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D23_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D23_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D23_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D23_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 24) as date))          
 Update sBiometric.tMonthTrans set D24 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D24_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D24_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D24_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D24_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D24_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D24_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D24_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D24_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 25) as date))          
 Update sBiometric.tMonthTrans set D25 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D25_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D25_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D25_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D25_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D25_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D25_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D25_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D25_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 26) as date))          
 Update sBiometric.tMonthTrans set D26 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D26_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D26_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D26_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D26_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D26_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D26_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D26_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D26_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
           
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
         
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 27) as date))          
 Update sBiometric.tMonthTrans set D27 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D27_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D27_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D27_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D27_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D27_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D27_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D27_S = (isnull((select top 1 'SHIFT ' + convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D27_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 28) as date))          
 Update sBiometric.tMonthTrans set D28 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))     
 ,D28_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D28_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D28_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D28_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D28_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D28_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D28_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D28_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
          
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
           
 if(@days >=29)          
 begin          
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 29) as date))          
 Update sBiometric.tMonthTrans set D29 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D29_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D29_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D29_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D29_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D29_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D29_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D29_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D29_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId         
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
         
 end          
 else          
 begin          
 Update sBiometric.tMonthTrans set D29 = 'XX'          
 ,D29_IN = 'XX',D29_OUT = 'XX',D29_O = 'XX',D29_L = 'XX',D29_T = 'XX',D29_E = 'XX',D29_S = 'XX'          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
 end          
           
           
 if(@days >=30)          
 begin          
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 30) as date))          
 Update sBiometric.tMonthTrans set D30 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D30_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D30_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D30_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D30_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D30_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D30_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D30_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D30_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId         
         
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
         
 end          
 else          
 begin          
 Update sBiometric.tMonthTrans set D30 = 'XX'          
 ,D30_IN = 'XX',D30_OUT = 'XX',D30_O = 'XX',D30_L = 'XX',D30_T = 'XX',D30_E = 'XX',D30_S = 'XX'          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
 end        
           
 if(@days >=31)          
 begin          
 set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 31) as date))          
 Update sBiometric.tMonthTrans set D31 = (isnull((select top 1 status from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'XX'))           
 ,D31_IN = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D31_OUT = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D31_O = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D31_L = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D31_T = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D31_E = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 ,D31_S = (isnull((select top 1 'SHIFT '+ convert(varchar(1),shiftid) from sHrm.tEmployeeMaster where id = @lEmpId AND  ISNULL(IsOtherUser,0) = 0),''))          
 --,D31_S = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId),'00:00'))          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
        
 set @totalEarly = @totalEarly + (select sum((isnull((DATEPART(HOUR,EarlyLeaveTime)),0)*60) + isnull((DATEPART(MINUTE,EarlyLeaveTime)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)          
 set @totalHour = @totalHour + (select sum((isnull((DATEPART(HOUR,TotalTimeHrs)),0)*60) + isnull((DATEPART(MINUTE,TotalTimeHrs)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalLate = @totalLate + (select sum((isnull((DATEPART(HOUR,TotalLate)),0)*60) + isnull((DATEPART(MINUTE,TotalLate)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
 set @totalOT = @totalOT + (select sum((isnull((DATEPART(HOUR,OT)),0)*60) + isnull((DATEPART(MINUTE,OT)),0)) from #temptbl where DATEDIFF(day,@date,AtdDate)=0 and SourceId = @lEmpId)         
         
 end          
 else          
 begin          
 Update sBiometric.tMonthTrans set D31 = 'XX'          
 ,D31_IN = 'XX',D31_OUT = 'XX',D31_O = 'XX',D31_L = 'XX',D31_T = 'XX',D31_E = 'XX',D31_S = 'XX'          
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId          
 end          
          
  Update sBiometric.tMonthTrans set         
  TotalHour = (SELECT CAST((@totalhour / 60) AS varchar(4))) + ':' + (SELECT CAST((@totalhour % 60) AS varchar(4)))        
 ,Tot_Early = (SELECT CAST((@totalEarly / 60) AS varchar(4))) + ':' + (SELECT CAST((@totalhour % 60) AS varchar(4)))        
 ,Tot_Late = (SELECT CAST((@totalLate / 60) AS varchar(4))) + ':' + (SELECT CAST((@totalhour % 60) AS varchar(4)))        
 ,Tot_OT = (SELECT CAST((@totalOT / 60) AS varchar(4))) + ':' + (SELECT CAST((@totalhour % 60) AS varchar(4)))        
  where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId        
          
 SET @j = @j + 1             
 end          
 -------------------------------------------------------------------------------------------------------------------------          
          
 ------------------------------------------- Update Final Data -----------------------------------------------------------         
          
 set @j = 1;          
 while (@j <= (select count(*) from #tbl))          
 begin           
 set @days= (select DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,@date),0))))            
 SELECT @EMPCODE=EmpCode,@lEmpId=EMPID From #tbl Where ID = @j          
 set @date1 = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 1) as date))          
          
 Update sBiometric.tMonthTrans set         
 Tot_Abs = (select count(1) from #temptbl where Status = 'A' and month(AtdDate)=@Monthid and year(AtdDate) = @year and SourceId = @lEmpId) --- (-Weekoff - Holiday)        
 ,Tot_Attn = (select count(1) from #temptbl where Status != 'A'  and month(AtdDate)=@Monthid and year(AtdDate) = @year and SourceId = @lEmpId) --- (-Weekoff - Holiday)        
 ,Tot_WeekOFF = 0 ----------------------------?????????????????????        
 ,Tot_Holiday = 0 -----------------------------????????????????????        
 ,Tot_HD = (select count(1) from #temptbl where Status = 'HD' and month(AtdDate)=@Monthid and year(AtdDate) = @year and SourceId = @lEmpId) --- (-Weekoff - Holiday)        
 ,Tot_OD = 0 -------------------------------???????????????????????        
 ,Tot_Leave =0 -----------------------------??????????????????????        
 ,Count_Late=(select count(1) from #temptbl where ( totallate != '00:00' or totallate != '' or totallate is not null)  and month(AtdDate)=@Monthid and year(AtdDate) = @year and #temptbl.EmpCode = @lEmpId) ------ (Weekoff - Holiday)        
 ,Count_Early = (select count(1) from #temptbl where (EarlyLeaveTime != '00:00'  or EarlyLeaveTime != '' or EarlyLeaveTime is not null)  and month(AtdDate)=@Monthid and year(AtdDate) = @year and #temptbl.EmpCode = @lEmpId) ----- (Weekoff - Holiday)      
  
 ,Count_OT=(select count(1) from #temptbl where (OT != '00:00' or OT != '' or OT is not null)  and month(AtdDate)=@Monthid and year(AtdDate) = @year and #temptbl.EmpCode = @lEmpId) --- (Weekoff - Holiday)        
 ,Tot_CL=0        
 ,Tot_SL=0        
 ,Tot_EL=0        
 ,Tot_SP=0        
 ,Tot_C =0        
 ,Tot_PL= 0        
 ,Tot_ML =0        
        
 where DATEDIFF(day,@date1,Attn_Dt)=0 and EmployeeId = @lEmpId        
 set @j = @j +1;        
 end        
         
 DROP TABLE #temptbl        
 select * from sBiometric.tMonthTrans where Attn_dt= (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 1) as date))          
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
-- EXEC SP_GetAttandanceData 11,2018,1101,121  
CREATE OR ALTER PROCEDURE [dbo].[SP_GetAttandanceData_old]  
@Monthid int,  
@year int,  
@Orgid int,  
@EmpID varchar(10) = Null  
AS  
BEGIN  
  
 SET NOCOUNT ON;  
  
 create table #tbl (id int identity(1,1),EmpCode varchar(10),EMPID BIGINT)  
  
 --------------------------  Get Employee Id -----------------------------  
   
 insert into #tbl  
 select distinct(Code),Id from sHrm.tEmployeeMaster  
 where (@EmpID = sHrm.tEmployeeMaster.code or @EmpID is null)   AND  ISNULL(IsOtherUser,0) = 0
   
 ---------------------------------------------------------------------------------------  
 --------------------- Insert All Records INTO Temp Table from sBiometric.tProcess ----------------  
  
 CREATE TABLE [dbo].[#temptbl](  
 [ProcessId] [int] IDENTITY(1000,1) NOT NULL,  
 [AtdDate] [datetime] NULL,  
 [StartTime] [nvarchar](20) NULL,  
 [CheckInTime] [nvarchar](20) NULL,  
 [LateComeTime] [nvarchar](20) NULL,  
 [EndTime] [nvarchar](20) NULL,  
 [CheckOutTime] [nvarchar](20) NULL,  
 [EarlyLeaveTime] [nvarchar](10) NULL,  
 [ActualHrs] [nvarchar](20) NULL,  
 [TotalTimeHrs] [varchar](40) NULL,  
 [TotalLate] [nvarchar](20) NULL,  
 [OT] [nvarchar](20) NULL,  
 [Status] [nvarchar](20) NULL,  
 [EmpCode] [nvarchar](40) NULL,  
 [SourceId] [bigint] NULL,  
 [SourceTypeId] [int] NULL ) ON [PRIMARY]  
  
 declare @date varchar(10) = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 1) as date))  
  
 declare @i int=1;  
 declare @j int =1;  
 DECLARE @COUNT INT =1;  
 DECLARE @EMPCODE varchar(50);  
 declare @days int= (select DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,@date),0))))  
   
 set @date = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 1) as date))  
  
 SET @COUNT = (SELECT COUNT(*) FROM #TBL)  
  
 insert into #temptbl  
 select AtdDate,StartTime,CheckInTime,LateComeTime,EndTime,CheckOutTime,EarlyLeaveTime,ActualHrs,TotalTimeHrs,  
 TotalLate,OT,Status,EmpCode,SourceId,SourceTypeId from sBiometric.tProcess  
 left join sHrm.tEmployeeMaster on sHrm.tEmployeeMaster.id = sBiometric.tProcess.EmpCode  
 where MONTH(sBiometric.tProcess.atddate) = @Monthid   
 and year(sBiometric.tProcess.atddate) = @year  
 and sHrm.tEmployeeMaster.Orgid = @Orgid   
 and (@EmpID = sHrm.tEmployeeMaster.code or @EmpID is null)  
 AND  ISNULL(IsOtherUser,0) = 0
  
 while (@j <= (select count(*) from #tbl))  
 begin  
 set @i=1;  
 set @days = (select DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,@date),0))))  
  while(@i<=@days)  
  begin    
   SET @EMPCODE = (SELECT TOP 1 EMPID FROM #tbl WHERE ID = @j)       
        
   set @date = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, @i) as date))  
  
   IF((Select count(*) from sBiometric.tProcess where DATEDIFF(day,@date,AtdDate) = 0 and EmpCode = @empcode) <= 0)  
   begin  
    Insert into #temptbl(AtdDate,Status,EmpCode,Sourceid,SourceTypeId)  
    select @date,'A',@EMPCODE,(select top 1 sourceid from sBiometric.tProcess where EmpCode = @EMPCODE),  
    (select top 1 SourceTypeId from sBiometric.tProcess where EmpCode = @empcode)   
   end  
   set @i = @i+1;  
   set @count = @COUNT + 1;  
  end  
  set @j = @j +1;  
 end  
    
 --select * from #temptbl order by EmpCode,atddate  
 --------------------------------------------------------------------------------------------------------------  
  
 --------------------------- Delete From sBiometric.tMonthTrans ----------------------------------------------------------  
  
 delete from sBiometric.tMonthTrans where EmployeeId in (SELECT EMPID FROM #tbl WHERE EmpCode = @EmpID or @EmpID is null) and MONTH(Attn_Dt) = @Monthid  
 and year(Attn_Dt) = @year  
  
 -------------------------------------Insert into sBiometric.tMonthTrans Blank Data --------------------------------------  
 Insert into sBiometric.tMonthTrans (EmployeeId,Attn_Dt,EmpCode)   
 select distinct Empcode,(SELECT DATEADD(month, DATEDIFF(month, 0, atddate), 0)) as atddate,1 from #temptbl order by EmpCode,atddate  
 --------------------------------------------------------------------------------------------------------------  
  
  
 --------------------------------- Update sBiometric.tMonthTrans Data (With Days) ----------------------------------------------------  
 set @j =1;  
 while (@j <= (select count(*) from #tbl))  
 begin  
 set @I =1;   
 set @days= (select DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,@date),0))))    
 set @EMPCODE = (select top 1 EMPID from #tbl where id=@j)  
 Declare @MainStatus varchar(10) = '';  
 Declare @mainDate varchar(10)  
 Declare @D_IN varchar(10)  
 Declare @D_OUT varchar(10)  
 declare @D_O  varchar(10)  
 Declare @D_L varchar(10)  
 Declare @D_T varchar(10)  
 Declare @D_E varchar(10)  
 declare @D_S varchar(10)  
 declare @date1 varchar(20) = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, 1) as date))  
   
  while(@I<=@days)  
  begin    
    
   set @mainDate = (select cast((convert(varchar(4),@year)+'-'+convert(varchar(2),@Monthid)+'-'+convert(varchar(2),@I)) as date))  
      declare @k varchar(10) = 0;  
        
      if(@I < 10)  
    BEGIN      
    set @k = (convert(varchar(10),'0') +''+ convert(varchar(10),@I))  
    END  
    ELSE  
    BEGIN  
    set @k = @I  
    END  
      
     set @MainStatus = convert(varchar(10),convert(varchar(10),'D') +''+ convert(varchar(10),@k))  
     set @D_IN = convert(varchar(10),convert(varchar(10),'D') +''+ convert(varchar(10),@k)+'_'+  convert(varchar(10),'IN'))  
     set @D_OUT = convert(varchar(10),convert(varchar(10),'D') +''+ convert(varchar(10),@k)+'_'+  convert(varchar(10),'OUT'))  
     set @D_O = convert(varchar(10),convert(varchar(10),'D') +''+ convert(varchar(10),@k)+'_'+  convert(varchar(10),'O'))  
     set @D_L = convert(varchar(10),convert(varchar(10),'D') +''+ convert(varchar(10),@k)+'_'+  convert(varchar(10),'L'))  
     set @D_T = convert(varchar(10),convert(varchar(10),'D') +''+ convert(varchar(10),@k)+'_'+  convert(varchar(10),'T'))  
     set @D_E = convert(varchar(10),convert(varchar(10),'D') +''+ convert(varchar(10),@k)+'_'+  convert(varchar(10),'E'))  
     set @D_S = convert(varchar(10),convert(varchar(10),'D') +''+ convert(varchar(10),@k)+'_'+  convert(varchar(10),'S'))  
        
       
      
  set @date  = (SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @Monthid) + '-' + CONVERT(VARCHAR, @I) as date))  
    
  Declare @Query1 varchar(max) = ''  
      
  Declare @Query2 varchar(max) = ''  
    
  Declare @Query3 varchar(max) = ''  
    
  Declare @Query4 varchar(max) = ''  
    
  Declare @Query5 varchar(max) = ''  
    
  Declare @Query6 varchar(max) = ''  
    
  Declare @Query7 varchar(max) = ''  
    
  set @Query1 = 'Update sBiometric.tMonthTrans set '+@MainStatus+' = (isnull((select top 1 status from #temptbl where DATEDIFF(day,"'+@date+'",AtdDate)=0 and EmpCode = '+@EMPCODE+'),''A''))    
  ,'+@D_IN+' = (isnull((select top 1 CheckInTime from #temptbl where DATEDIFF(day,"'+@date+'",AtdDate)=0 and EmpCode = '+@EMPCODE+'),''XX''))'  
    
  set @Query2 =','+@D_OUT+' = (isnull((select top 1 CheckOutTime from #temptbl where DATEDIFF(day,"'+@date+'",AtdDate)=0 and EmpCode = '+@EMPCODE+'),''XX''))  
  ,'+@D_O+' = (isnull((select top 1 OT from #temptbl where DATEDIFF(day,"'+@date+'",AtdDate)=0 and EmpCode = '+@EMPCODE+'),''XX''))'  
    
  set @Query3 =  
  ','+@D_L+' = (isnull((select top 1 LateComeTime from #temptbl where DATEDIFF(day,"'+@date+'",AtdDate)=0 and EmpCode = '+@EMPCODE+'),''XX''))  
  ,'+@D_T+' = (isnull((select top 1 TotalTimeHrs from #temptbl where DATEDIFF(day,"'+@date+'",AtdDate)=0 and EmpCode = '+@EMPCODE+'),''XX''))'  
    
  set @Query4 =','+@D_E+' = (isnull((select top 1 EarlyLeaveTime from #temptbl where DATEDIFF(day,"'+@date+'",AtdDate)=0 and EmpCode = '+@EMPCODE+'),''XX''))  
  ,'+@D_S+' = (isnull((select top 1 StartTime from #temptbl where DATEDIFF(day,"'+@date+'",AtdDate)=0 and EmpCode = '+@EMPCODE+'),''XX''))  
  where DATEDIFF(day,"'+@date1+'",Attn_Dt)=0 and EmployeeId = '+@EMPCODE+''  
    
  set @Query5 = convert(varchar(max),@Query1) + convert(varchar(max),@Query2)   
    
  set @Query6 = convert(varchar(max),@Query3) + convert(varchar(max),@Query4)  
    
  set @Query7 = convert(varchar(max),@Query5) + convert(varchar(max),@Query6)  
    
  set @Query7 = REPLACE(@Query7, '"', '''')  
  
    
  exec (@Query7)  
    
  SET @I = @I + 1      
 END  
   
 SET @j = @j + 1     
 end  
 -------------------------------------------------------------------------------------------------------------------------  
  
 ------------------------------------------- Update Final Data -----------------------------------------------------------  
  
  
  
 DROP TABLE #temptbl  
 select * from sBiometric.tMonthTrans  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
CREATE OR ALTER PROCEDURE [dbo].[SP_ProcessDataSync]          
  @str nvarchar(max) = ''          
AS          
BEGIN          
          
 DECLARE @loXML XML          
    SET @loXML = CAST(@Str AS XML)          
              
           
 DECLARE @tblprocess TABLE          
 (          
    Id Int IDENTITY(1, 1)          
  , AtdDate nvarchar(20)             
  , StartTime nvarchar(20)           
  , CheckInTime  nvarchar(20)          
  , LateComeTime  nvarchar(20)           
  , EndTime       nvarchar(20)           
  , CheckOutTime nvarchar(20)           
  , EarlyLeaveTime nvarchar(20)           
  , ActualHrs nvarchar(20)           
  , TotalTimeHrs nvarchar(20)           
  , TotalLate nvarchar(20)           
  , OT nvarchar(20)           
  , [Status] nvarchar(20)           
  , EmpCode nvarchar(40)           
  , SourceId bigint           
  , SourceTypeId int           
 )           
    INSERT INTO @tblprocess          
    SELECT                   
            T.c.value('@AtdDate','nvarchar(20)') AS AtdDate,          
            T.c.value('@StartTime','nvarchar(20)') AS StartTime,          
            T.c.value('@CheckInTime','nvarchar(20)') AS CheckInTime,          
            T.c.value('@LateComeTime','nvarchar(20)') AS LateComeTime,          
            T.c.value('@EndTime','nvarchar(20)') AS EndTime,          
            T.c.value('@CheckOutTime','nvarchar(20)') AS CheckOutTime,          
            T.c.value('@EarlyLeaveTime','nvarchar(20)') AS EarlyLeaveTime,          
            T.c.value('@ActualHrs','nvarchar(20)') AS ActualHrs,          
            T.c.value('@TotalTimeHrs','nvarchar(20)') AS TotalTimeHrs,          
            T.c.value('@TotalLate','nvarchar(20)') AS TotalLate,          
            T.c.value('@OT','nvarchar(20)') AS OT,          
            T.c.value('@Status','nvarchar(20)') AS [Status],          
            T.c.value('@EmpCode','nvarchar(40)') AS EmpCode,          
            T.c.value('@SourceId','bigint') AS SourceId,          
            T.c.value('@SourceTypeId','int') AS SourceTypeId          
                      
    FROM           
            @loXML.nodes('/MainList/Main')T(c)          
          
            
  declare @cnt int = 0,@j int = 1          
            
  select @cnt = COUNT(*) from @tblprocess          
            
  while(@j <= @cnt)          
  BEGIN               
	if exists(select * from sBiometric.tProcess where AtdDate = (select AtdDate from @tblprocess where Id = @j)  and EmpCode=(select EmpCode from @tblprocess where Id = @j))   
	begin  
	delete from sBiometric.tProcess where AtdDate = (select AtdDate from @tblprocess where Id = @j)  and EmpCode=(select EmpCode from @tblprocess where Id = @j)       
	end 
	
	Select @j = @j + 1;            
 END
 
             
 --delete from sBiometric.tProcess where AtdDate = (select AtdDate from @tblprocess where Id = @j)  and EmpCode=(select EmpCode from @tblprocess where Id = @j)       
 --select * from sBiometric.tProcess
 insert into  sBiometric.tProcess
 (          
     AtdDate, StartTime, CheckInTime, LateComeTime, EndTime, CheckOutTime, EarlyLeaveTime, ActualHrs, TotalTimeHrs, TotalLate, OT, [Status], EmpCode, SourceId, SourceTypeId          
 )
 select   AtdDate,  StartTime   ,CheckInTime   ,LateComeTime,EndTime,CheckOutTime,EarlyLeaveTime,ActualHrs,TotalTimeHrs,TotalLate,OT,Status,EmpCode,SourceId,SourceTypeId
 from @tblprocess
 --values          
 --(           
 --  (select AtdDate from @tblprocess where Id = @j)           
 --  , (select StartTime from @tblprocess where Id = @j)           
 --  , (select CheckInTime from @tblprocess where Id = @j)            
 --  , (select LateComeTime from @tblprocess where Id = @j)             
 --  , (select EndTime from @tblprocess where Id = @j)             
 --  , (select CheckOutTime from @tblprocess where Id = @j)             
 --  , (select EarlyLeaveTime from @tblprocess where Id = @j)             
 --  , (select ActualHrs from @tblprocess where Id = @j)             
 --  , (select TotalTimeHrs from @tblprocess where Id = @j)             
 --  , (select TotalLate from @tblprocess where Id = @j)             
 --  , (select OT from @tblprocess where Id = @j)             
 --  ,  (select Status from @tblprocess where Id = @j)              
 --  ,  (select EmpCode from @tblprocess where Id = @j)              
 --  ,  (select SourceId from @tblprocess where Id = @j)              
 --  ,  (select SourceTypeId from @tblprocess where Id = @j)              
 --)                
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          
CREATE OR ALTER PROCEDURE [dbo].[SP_ProcessDataSync_bak]          
  @str nvarchar(max) = ''          
AS          
BEGIN          
          
 DECLARE @loXML XML          
    SET @loXML = CAST(@Str AS XML)          
              
           
 DECLARE @tblprocess TABLE          
 (          
    Id Int IDENTITY(1, 1)          
  , AtdDate nvarchar(20)             
  , StartTime nvarchar(20)           
  , CheckInTime  nvarchar(20)          
  , LateComeTime  nvarchar(20)           
  , EndTime       nvarchar(20)           
  , CheckOutTime nvarchar(20)           
  , EarlyLeaveTime nvarchar(20)           
  , ActualHrs nvarchar(20)           
  , TotalTimeHrs nvarchar(20)           
  , TotalLate nvarchar(20)           
  , OT nvarchar(20)           
  , [Status] nvarchar(20)           
  , EmpCode nvarchar(40)           
  , SourceId bigint           
  , SourceTypeId int           
 )           
    INSERT INTO @tblprocess          
    SELECT                   
            T.c.value('@AtdDate','nvarchar(20)') AS AtdDate,          
            T.c.value('@StartTime','nvarchar(20)') AS StartTime,          
            T.c.value('@CheckInTime','nvarchar(20)') AS CheckInTime,          
            T.c.value('@LateComeTime','nvarchar(20)') AS LateComeTime,          
            T.c.value('@EndTime','nvarchar(20)') AS EndTime,          
            T.c.value('@CheckOutTime','nvarchar(20)') AS CheckOutTime,          
            T.c.value('@EarlyLeaveTime','nvarchar(20)') AS EarlyLeaveTime,          
            T.c.value('@ActualHrs','nvarchar(20)') AS ActualHrs,          
            T.c.value('@TotalTimeHrs','nvarchar(20)') AS TotalTimeHrs,          
            T.c.value('@TotalLate','nvarchar(20)') AS TotalLate,          
            T.c.value('@OT','nvarchar(20)') AS OT,          
            T.c.value('@Status','nvarchar(20)') AS [Status],          
            T.c.value('@EmpCode','nvarchar(40)') AS EmpCode,          
            T.c.value('@SourceId','bigint') AS SourceId,          
            T.c.value('@SourceTypeId','int') AS SourceTypeId          
                      
    FROM           
            @loXML.nodes('/MainList/Main')T(c)          
          
            
  declare @cnt int = 0,@j int = 1          
            
  select @cnt = COUNT(*) from @tblprocess          
            
  while(@j <= @cnt)          
  BEGIN          
          
 if exists(select * from sBiometric.tProcess where AtdDate = (select AtdDate from @tblprocess where Id = @j)  and EmpCode=(select EmpCode from @tblprocess where Id = @j))   
 begin  
 delete from sBiometric.tProcess where AtdDate = (select AtdDate from @tblprocess where Id = @j)  and EmpCode=(select EmpCode from @tblprocess where Id = @j)       
 end     
 --delete from sBiometric.tProcess where AtdDate = (select AtdDate from @tblprocess where Id = @j)  and EmpCode=(select EmpCode from @tblprocess where Id = @j)       
    
 insert into  sBiometric.tProcess  
 (          
     AtdDate          
   , StartTime          
   , CheckInTime          
   , LateComeTime          
   , EndTime          
   , CheckOutTime          
   , EarlyLeaveTime          
   , ActualHrs          
   , TotalTimeHrs          
   , TotalLate          
   , OT          
   , [Status]          
   , EmpCode          
   , SourceId          
   , SourceTypeId          
 )          
 values          
 (           
   (select AtdDate from @tblprocess where Id = @j)           
   , (select StartTime from @tblprocess where Id = @j)           
   , (select CheckInTime from @tblprocess where Id = @j)            
   , (select LateComeTime from @tblprocess where Id = @j)             
   , (select EndTime from @tblprocess where Id = @j)             
   , (select CheckOutTime from @tblprocess where Id = @j)             
   , (select EarlyLeaveTime from @tblprocess where Id = @j)             
   , (select ActualHrs from @tblprocess where Id = @j)             
   , (select TotalTimeHrs from @tblprocess where Id = @j)             
   , (select TotalLate from @tblprocess where Id = @j)             
   , (select OT from @tblprocess where Id = @j)             
   ,  (select Status from @tblprocess where Id = @j)              
   ,  (select EmpCode from @tblprocess where Id = @j)              
   ,  (select SourceId from @tblprocess where Id = @j)              
   ,  (select SourceTypeId from @tblprocess where Id = @j)              
 )          
          
           Select @j = @j + 1;            
 END          
          
            
          
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [dbo].[spInsertQuarterlyData] 
   @Dt datetime
AS

DECLARE @CurrQtrDt DATETIME
DECLARE @RangeStartDt DATETIME
DECLARE @RangeEndDt DATETIME

SELECT @CurrQtrDt = DATEADD(qq, DATEDIFF(qq, 0, @Dt), 0)
SELECT @RangeStartDt = DATEADD(mm,-15,@CurrQtrDt)
SELECT @RangeEndDt = DATEADD(dd,-1,DATEADD(mm,-3,@CurrQtrDt))

INSERT INTO QtrData( ID, Qtr, Yr, Metric )
SELECT 
   ID,
   DATEPART(qq,@CurrQtrDt)-1,
   DATEPART(yyyy,@CurrQtrDt),
   SUM(Metric)
FROM Table_1
WHERE [Month] BETWEEN @RangeStartDt AND @RangeEndDt
GROUP BY ID

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [dbo].[spScholasticEvalAdd]
	 	
	@rStrXml [nvarchar](max),
	@rResultId bigint =0,
	@rsid bigint=0,
	@rSubjectSubActivity bigint=0
	
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT
  
		if not exists (select sid from  dbo.ScholasticEvaluation where sid=@rsid)
	 	begin
			INSERT INTO dbo.ScholasticEvaluation
				 
				(
					sId,
					 ResultId,
					 SubSubjectActivityId,
					IndicatorStr
				)
         		SELECT
         			 sId,
         			 @rResultId,
         			 @rSubjectSubActivity,
         			 Replace(IndicatorStr,',','.')
	         			
				FROM OPENXML (@loDoc, '/Table/ScholasticEvaluation', 1)
				WITH ( 				
						sId bigint '@sId',
						ResultId bigint '@rResultId',
						SubSubjectActivityId Bigint '@rSubjectSubActivity',					
						IndicatorStr nvarchar(20) 'IndicatorStr'
						 
					  ) 	
			
				EXEC sp_xml_removedocument @loDoc
				SELECT 1 as result
		end
		
	 else
		begin
			UPDATE  dbo.ScholasticEvaluation
			SET
				IndicatorStr = A.IndicatorStr
			 
			FROM
			(
			SELECT IndicatorStr
			FROM OPENXML (@loDoc, '/Table/ScholasticEvaluation', 1)
			WITH ( 
					IndicatorStr nvarchar(20)		
				  )) A
			WHERE  dbo.ScholasticEvaluation.sId=@rsid
			
	        SELECT 115 AS Result
		end
		
		
			--INNER JOIN sAssessment.tCCECSMaster AM ON AM.Id = A.ACTIVITYTITLE 			
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AM.OrgId AND OM.Id = @rORGId
			--AND A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCECSExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND CCECSId=AM.Id)
	     
	 
	
    -- Updated by Kp
    
	--UPDATE A SET A.DescriptiveIndicator = 
 --					stuff((select ',' + B.Title from sAssessment.tCCECSIndicatorMaster B
	--			WHERE A.CCECSid=B.CCECSId 
	--					and ','+ (replace(IndicatorIds,'.',',') )+',' like '%,'+CAST(Number as varchar(10))+',%'				
	--			for xml path('')),1,1,'') 
 --        From sAssessment.tCCECSExamScore A    
 --        INNER JOIN      			
	--		OPENXML (@loDoc, '/Table/CSEXamIndicator', 1)
	--		WITH ( 				
	--				ExamId int,
	--				AcademicId Bigint,					
	--				Term1Indicator nvarchar(20),
	--				ActivityTitle NVARCHAR(100)
	--			  )B1
	--			  ON A.ExamId=B1.ExamId AND A.AcademicId = B1.AcademicId AND B1.ActivityTitle = A.CCECSId 
	
	 SELECT 1 AS Result
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [dbo].[spSubjectActivity]
	 @rCodeNo bigint,
	 @rCode nvarchar(200),
	 @rcDesc nvarchar(200),
	 @rAddUser bigint=0,
	 @rAddDate date='',
	 @rEditUser bigint=0,
	 @rEditDate  date='',
	 @rLngId int=0,
	 @rOrderIndex int=0,
	 @rSubjectId int=0,
	 @rStdId int=0,
	 @rBordId bigint=2
AS
BEGIN
	 
	SET NOCOUNT ON;
	IF Not exists (select Id from dbo.mstSubjectActivity)
	begin
		insert into dbo.mstSubjectActivity
		(
			codeNo,
			Code,
			cDesc,
			LngId,
			ORDERINDEX,
			SubjectId,
			StdId,
			boardId
			
		)
		Values
		(
			@rCodeNo,
			@rCode,
			@rcDesc,
			@rLngId,
			@rOrderIndex,
			@rSubjectId,
			@rStdId,
			@rBordId
			
		)	
   END
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [dbo].[UpdateWac]	
	
	@rStoreLocationName varchar(150) = 0,
	@rItemcode varchar(100) = '' ,
	@rWeightedAverageoldcost Decimal(18,5) =0,
	@rWeightedAverageCost Decimal(18,5) = 0,
	@orgid int =0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

Declare @StoreLocationId bigint = 0,@ItemId bigint = 0,@StockItemPlanningId bigint = 0,@rStockInwardDetailId bigint = 0,@rStockBatchId bigint = 0,@rlocationId bigint = 0

Select @StoreLocationId = Id from sIp.tStoreLocationMaster where Title = @rStoreLocationName and OrgGroupId=@orgid

Select @rlocationId = LocationId from sIp.tStoreLocationMaster where Title = @rStoreLocationName and OrgGroupId=@orgid

Select @ItemId =  Id from sIp.tStockItemMaster where locationId=@rlocationId and code=@rItemcode and OrgGroupId = @orgid


Select @StockItemPlanningId =  Id from sIp.tStockItemPlanning where StockItemId =@ItemId 

select @rStockInwardDetailId = SIDE.ID from sProcurement.tStockInward SI 
inner join sProcurement.tStockInwardDetail SIDE on SIDE.StockInwardId = SI.Id
inner join  sProcurement.tStockInwardBatch SIB on SIB.StockInwardDetailId = SIDE.Id
inner join sProcurement.tStockBatch SB on SB.id = SIB.StockBatchId
Where SIDE.StockItemId=@ItemId  and SI.OrgGroupId=@orgid


select @rStockBatchId = SB.ID from sProcurement.tStockInward SI 
inner join sProcurement.tStockInwardDetail SIDE on SIDE.StockInwardId = SI.Id
inner join  sProcurement.tStockInwardBatch SIB on SIB.StockInwardDetailId = SIDE.Id
inner join sProcurement.tStockBatch SB on SB.id = SIB.StockBatchId
Where SIDE.StockItemId=@ItemId  and SI.OrgGroupId=@orgid

---StockItemMaster In Planning cost update 

Update sIp.tStockItemPlanning set WeightedAverageCost=@rWeightedAverageCost  where StockItemId =@ItemId
and Id=@StockItemPlanningId and OrgGroupId=@orgid

---Tranjection table Cost Update

update sIp.tWeightedAverageCostLog set WeightedAverageCost=@rWeightedAverageCost 
where ItemSourceId =@ItemId and StoreLocationId=@StoreLocationId and OrgGroupId=@orgid


---Tranjection table Value Update

update sIp.tWeightedAverageCostLog set ClosingValue=(ClosingQuantity*WeightedAverageCost) 
where ItemSourceId =@ItemId and StoreLocationId=@StoreLocationId and OrgGroupId=@orgid


---Stock Batch Price Update If Inward Avaliable 

if(len(@rStockBatchId) > 0)
Update sProcurement.tStockBatch set ItemRate=@rWeightedAverageCost where StockItemId=@ItemId
 and id=@rStockBatchId and StoreLocationId=@StoreLocationId and OrgGroupId=@orgid


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pAssignSubjectCoordinatorUpdate]
	 @rEmployeeId bigint=0,	 
	 @rSubjectId int=0,	 
	 @rDivisionId int=0,
	 @rCoordinatorEmployeeId bigint=0,	
	 @rIsUpdate int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

IF(@rIsUpdate =0)
BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION							 
			BEGIN
				BEGIN										
					UPDATE sAcademic.tTeacherSubjectDivision SET SubjectCordinatorEmployeeId=@rCoordinatorEmployeeId WHERE EmployeeId=@rEmployeeId AND SubjectId = @rSubjectId And DivisionId=@rDivisionId
				END		
				SELECT 1 AS RESULT
			END 
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
				SELECT -101 AS Result
	END CATCH		
END
ELSE
	BEGIN 
		BEGIN TRY
			BEGIN TRANSACTION							 
				BEGIN
					BEGIN										
						UPDATE sAcademic.tTeacherSubjectDivision SET SubjectCordinatorEmployeeId=NULL WHERE EmployeeId=@rEmployeeId AND SubjectId = @rSubjectId And DivisionId=@rDivisionId AND SubjectCordinatorEmployeeId=@rCoordinatorEmployeeId
					END		
				SELECT 1 AS RESULT
			END 
			COMMIT TRANSACTION
		END TRY
		BEGIN CATCH 
			ROLLBACK TRANSACTION
				SELECT -101 AS Result
		END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pClassGet]

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

BEGIN 




	
	SELECT 
			TSD.SubjectId ,
		    ISNULL( SM.Title,'') AS SubjectName,
			AC.Id,
			ISNULL(AC.Classwork,CC.ClassworkTemplate) AS Classwork,
		    ISNULL(AC.Homework,CC.HomeworkTemplate) AS Homework,
		    AC.HomeWorkEndDate,
		    DM.Id AS DivisionId,
		    DM.ClassId,
		    ISNULL(CM.Title,'')as ClassName,
		    ISNULL(DM.Title,'')as DivisionName,
			DM.OrderIndex,
			REPLACE(CONVERT(VARCHAR(20), sCommon.fGetDate(), 103),'/','') +'_'+ CONVERT(nvarchar(10),DM.Id) +'_'+CONVERT(nvarchar(10),TSD.SubjectId) AS UniqueId,
			AC.BatchId,
			ISNULL(AC.IsSubmitHomework,0) as IsSubmitHomework,
			EM.Id AS EmployeeId,																		-- MantisId : 0035929
			ISNULL(ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, ''), '') AS TeacherName		-- MantisId : 0035929	
	FROM 
			sAcademic.tTeacherSubjectDivision TSD			
			INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId = SM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON TSD.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM On CM.Id = DM.ClassId
			INNER JOIN sHrm.tEmployeeMaster EM On  TSD.EmployeeId = EM.Id
			LEFT JOIN sAcademic.tClasswork AC ON TSD.SubjectId = AC.SubjectId  
			AND  TSD.DivisionId = AC.DivisionId AND TSD.EmployeeId = AC.EmployeeId 
			AND AC.ClassWorkDate = @rClassworkDate AND AC.BatchId = @rBatchId
			AND ((AC.Id=@rId) OR (@rId=0))
			LEFT JOIN sAcademic.tClassworkConfig CC ON CC.OrgId = DM.OrgId
	
			--[sSetup].[tClassSubject] CS 
			--Left JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			--Left Join sAcademic.tClasswork AC ON AC.SubjectId=CS.SubjectId And AC.Id=@rId
			--LEFT JOIN sSetup.tClassMaster CM On CM.Id = CS.ClassId
			--LEFT JOIN sSetup.tDivisionMaster DM On DM.ClassId = CM.Id
			
	WHERE 
			((DM.OrgId=@rOrgId) OR (@rOrgId = 0))		
			AND ((TSD.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
			AND ((TSD.DivisionId=@rDivisionId) OR(@rDivisionId=0))
			AND ((TSD.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND SM.IsObsolete = 0										-- MantisId : 0035929
			AND EM.StatusId = 7											-- MantisId : 0035929
    ORDER BY 
			DM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pClassv2Get]

	 @rEmployeeId bigint,
	 @rOrgGroupId smallint,
	 @rClassworkDate Date	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lConfigValue nvarchar(50)
DECLARE @rOrgGroupBatchId int

SELECT @rOrgGroupBatchId  = Id from  sSetup.tOrgGroupBatchMaster Where OrgGroupId=@rOrgGroupId

	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

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

	SELECT 
			TSD.SubjectId ,
		    SM.Title AS SubjectName,
			ISNULL(AC.Id,0) AS ClassworkId,
			ISNULL(AC.Classwork,'') AS Classwork,
		    ISNULL(AC.Homework,'') AS Homework,
		    ISNULL(CONVERT(VARCHAR(10), AC.HomeWorkEndDate, 103),'') AS HomeWorkEndDate,
		    DM.Id AS DivisionId,
		    DM.ClassId,
		    CM.Title +'-'+DM.Title AS ClassDivisionName,
		    OM.Id As OrgId,
		    OM.DisplayTitle AS OrgTitle,
		    DM.OrderIndex
	FROM 
	
			sAcademic.tTeacherSubjectDivision TSD			
			INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId = SM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON TSD.DivisionId = DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			INNER JOIN sSetup.tClassMaster CM On CM.Id = DM.ClassId
			LEFT JOIN sAcademic.tClasswork AC ON TSD.SubjectId = AC.SubjectId  
			AND  TSD.DivisionId = AC.DivisionId AND TSD.EmployeeId = AC.EmployeeId 
			AND AC.ClassWorkDate = @rClassworkDate
															
	WHERE 
		OM.OrgGroupId=@rOrgGroupId	
		AND TSD.EmployeeId= @rEmployeeId
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
		ORDER BY OM.Id,DM.OrderIndex
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pClassv3Get]

	 @rEmployeeId bigint,
	 @rOrgGroupId smallint,
	 @rClassworkDate Date	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lConfigValue nvarchar(50)
DECLARE @rOrgGroupBatchId int

SELECT @rOrgGroupBatchId  = Id from  sSetup.tOrgGroupBatchMaster Where OrgGroupId=@rOrgGroupId

	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1
	
	SELECT 
			TSD.SubjectId ,
		    SM.Title AS SubjectName,
			ISNULL(AC.Id,0) AS ClassworkId,
			--ISNULL(AC.Classwork,'') AS Classwork,
		 --   ISNULL(AC.Homework,'') AS Homework,
		    ISNULL(AC.Classwork,CC.ClassworkTemplate) AS Classwork,
		    ISNULL(AC.Homework,CC.HomeworkTemplate) AS Homework,
		    ISNULL(CONVERT(VARCHAR(10), AC.HomeWorkEndDate, 103),'') AS HomeWorkEndDate,
		    DM.Id AS DivisionId,
		    DM.ClassId,
		    CM.Title +'-'+DM.Title AS ClassDivisionName,
		    OM.Id As OrgId,
		    OM.DisplayTitle AS OrgTitle,
		    DM.OrderIndex,
		    ISNULL(AC.ClassworkStatusId,1) AS ClassworkStatusId,
		    ISNULL(AC.HomeWorkStatusId,1) AS HomeWorkStatusId
	FROM 
			sAcademic.tTeacherSubjectDivision TSD			
			INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId = SM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON TSD.DivisionId = DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			INNER JOIN sSetup.tClassMaster CM On CM.Id = DM.ClassId
			LEFT JOIN sAcademic.tClassworkConfig CC ON CC.OrgId = DM.OrgId
			LEFT JOIN sAcademic.tClasswork AC ON TSD.SubjectId = AC.SubjectId  
			AND  TSD.DivisionId = AC.DivisionId AND TSD.EmployeeId = AC.EmployeeId 
			AND AC.ClassWorkDate = @rClassworkDate
															
	WHERE 
		OM.OrgGroupId=@rOrgGroupId	
		AND TSD.EmployeeId= @rEmployeeId
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
		ORDER BY OM.Id,DM.OrderIndex
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAcademic].[pClassv4Get]

	 @rEmployeeId bigint,
	 @rOrgGroupBatchId int,
	 @rClassworkDate Date,
	 @rOrgId smallint,
	 @rBatchId int	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

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

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

	SELECT 
			TSD.SubjectId ,
		    SM.Title AS SubjectName,
			ISNULL(AC.Id,0) AS ClassworkId,
		    ISNULL(AC.Classwork,CC.ClassworkTemplate) AS Classwork,
		    ISNULL(AC.Homework,CC.HomeworkTemplate) AS Homework,
		    ISNULL(CONVERT(VARCHAR(10), AC.HomeWorkEndDate, 103),'') AS HomeWorkEndDate,
		    DM.Id AS DivisionId,
		    DM.ClassId,
		    CM.Title +'-'+DM.Title AS ClassDivisionName,
		    OM.Id As OrgId,
		    OM.DisplayTitle AS OrgTitle,
		    DM.OrderIndex,
		    ISNULL(AC.ClassworkStatusId,1) AS ClassworkStatusId,
		    ISNULL(AC.HomeWorkStatusId,1) AS HomeWorkStatusId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM
			sAcademic.tTeacherSubjectDivision TSD			
			INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId = SM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON TSD.DivisionId = DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sSetup.tClassMaster CM On CM.Id = DM.ClassId
			LEFT JOIN sAcademic.tClasswork AC ON TSD.SubjectId = AC.SubjectId AND TSD.DivisionId = AC.DivisionId AND TSD.EmployeeId = AC.EmployeeId AND AC.ClassWorkDate = @rClassworkDate --AND AC.BatchId = @rBatchId
			LEFT JOIN sAcademic.tClassworkConfig CC ON CC.OrgId = DM.OrgId
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id  AND BM.OrgId = @rOrgId
	WHERE 
			TSD.EmployeeId= @rEmployeeId AND OGBM.Id = @rOrgGroupBatchId 
			--AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
			--AND AC.StatusId=550
	ORDER BY 
			OM.Id,DM.OrderIndex
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pClassworkAdd]
	 
	 	@rBatchId int,
        @rId bigint,
        @rSubjectId int,
        @rClassId int,
        @rDivisionId int,
		@rClasswork nvarchar(max),
		@rHomework nvarchar(max),
		@rClassWorkDate date,
		@rHomeWorkEndDate date,
		@rEmployeeId bigint,
		@rCreatedUserId bigint,
		@rOrgId int,
		@rClassworkStatusId smallint = 1,
		@rHomeWorkStatusId smallint = 1,
		@rIsSubmitHomework bit =0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lNextNumber BIGINT 
	
	-- Temp Basis Update due to Wrong OrgId,BatchId paseed from Mobile End
	DECLARE @lOrgId smallint, @lOrgGroupBatchId int, @lBatchId int
	SELECT @lOrgId = OrgId from sSetup.tSubjectMaster Where Id = @rSubjectId
	SELECT @lOrgGroupBatchId =  OrgGroupBatchId from sSetup.tBatchMaster Where Id = @rBatchId
	SELECT @lBatchId = Id from sSetup.tBatchMaster Where OrgId = @lOrgId AND OrgGroupBatchId = @lOrgGroupBatchId 
	
	SET @rBatchId = @lBatchId
	SET @rOrgId = @lOrgId
	-- Ends
	
	SELECT @rId = Id FROM sAcademic.tClasswork WHERE	
	        BatchId=@rBatchId AND
			SubjectId=@rSubjectId AND
			ClassId=@rClassId AND
			DivisionId=@rDivisionId AND
			EmployeeId = @rEmployeeId AND
			ClassWorkDate = @rClassWorkDate
	        
	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tClasswork', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tClasswork
		(
			BatchId,
			Id,
			SubjectId,
			ClassId,
			DivisionId,
			Classwork,
			Homework,
			ClassWorkDate,
			HomeWorkEndDate,
			EmployeeId,
			CreatedUserId,
			CreatedDateTime,
			ClassworkStatusId,
			HomeWorkStatusId,
			IsSubmitHomework
		)
	VALUES
		(
			@rBatchId,
			@lNextNumber,
			@rSubjectId,
			@rClassId,
			@rDivisionId,
			CASE WHEN @rClassworkStatusId=1 THEN @rClasswork ELSE 'NA' END,
			CASE WHEN @rHomeWorkStatusId=1 THEN @rHomework ELSE 'NA' END,
			@rClassWorkDate,
			@rHomeWorkEndDate,
			@rEmployeeId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClassworkStatusId,
		    @rHomeWorkStatusId,
			@rIsSubmitHomework
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 
			If @rClassworkStatusId=2 SET @rClasswork='NA'
			If @rHomeWorkStatusId=2 SET  @rHomework='NA'
	 --SET @lNextNumber = @rId
	    UPDATE  sAcademic.tClasswork
	    SET
			BatchId=@rBatchId,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			Classwork=@rClasswork,
			Homework=@rHomework,
			ClassWorkDate=@rClassWorkDate,
			HomeWorkEndDate=@rHomeWorkEndDate,
			EmployeeId=@rEmployeeId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ClassworkStatusId=@rClassworkStatusId,
			HomeWorkStatusId=@rHomeWorkStatusId,
	      IsSubmitHomework = @rIsSubmitHomework
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pClassworkCloneAdd]
	 
	 	@rBatchId int,
        @rId bigint,
        @rSubjectId int,
        @rClassId int,
        @rDivisionId int,
		@rClasswork nvarchar(max),
		@rHomework nvarchar(max),
		@rClassWorkDate date,
		@rHomeWorkEndDate date,
		@rEmployeeId bigint,
		@rCreatedUserId bigint,
		@rOrgId int,
		@rClassworkStatusId smallint = 1,
		@rHomeWorkStatusId smallint = 1
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lNextNumber BIGINT 
	
	-- Temp Basis Update due to Wrong OrgId,BatchId paseed from Mobile End
	DECLARE @lOrgId smallint, @lOrgGroupBatchId int, @lBatchId int
	SELECT @lOrgId = OrgId from sSetup.tSubjectMaster Where Id = @rSubjectId
	SELECT @lOrgGroupBatchId =  OrgGroupBatchId from sSetup.tBatchMaster Where Id = @rBatchId
	SELECT @lBatchId = Id from sSetup.tBatchMaster Where OrgId = @lOrgId AND OrgGroupBatchId = @lOrgGroupBatchId 
	
	SET @rBatchId = @lBatchId
	SET @rOrgId = @lOrgId
	-- Ends
	
	--SELECT @rId = Id FROM sAcademic.tClasswork WHERE	
	--        BatchId=@rBatchId AND
	--		SubjectId=@rSubjectId AND
	--		ClassId=@rClassId AND
	--		DivisionId=@rDivisionId AND
	--		EmployeeId = @rEmployeeId AND
	--		ClassWorkDate = @rClassWorkDate
	        
	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tClasswork', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tClasswork
		(
			BatchId,
			Id,
			SubjectId,
			ClassId,
			DivisionId,
			Classwork,
			Homework,
			ClassWorkDate,
			HomeWorkEndDate,
			EmployeeId,
			CreatedUserId,
			CreatedDateTime,
			ClassworkStatusId,
			HomeWorkStatusId
		)
	VALUES
		(
			@rBatchId,
			@lNextNumber,
			@rSubjectId,
			@rClassId,
			@rDivisionId,
			CASE WHEN @rClassworkStatusId=1 THEN @rClasswork ELSE 'NA' END,
			CASE WHEN @rHomeWorkStatusId=1 THEN @rHomework ELSE 'NA' END,
			@rClassWorkDate,
			@rHomeWorkEndDate,
			@rEmployeeId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClassworkStatusId,
		    @rHomeWorkStatusId
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 
			If @rClassworkStatusId=2 SET @rClasswork='NA'
			If @rHomeWorkStatusId=2 SET  @rHomework='NA'
	 --SET @lNextNumber = @rId
	    UPDATE  sAcademic.tClasswork
	    SET
			BatchId=@rBatchId,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			Classwork=@rClasswork,
			Homework=@rHomework,
			ClassWorkDate=@rClassWorkDate,
			HomeWorkEndDate=@rHomeWorkEndDate,
			EmployeeId=@rEmployeeId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ClassworkStatusId=@rClassworkStatusId,
			HomeWorkStatusId=@rHomeWorkStatusId
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pClassworkCloneGet]

	 @rId bigint=0,	 
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rEmployeeId bigint=0,
	 @rDivisionid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rOrgId int=0,
     --@rBatchId int
     @rOrgGroupBatchId int=0,
    @rUserId bigint =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	if(@rId = 0)
		BEGIN
			SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId)+'_Clone' AS UniqueId,
			ISNULL(AC.IsSubmitHomework,0) IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
		END 
	ELSE
		BEGIN
		SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId)+'_Clone' AS UniqueId,
			ISNULL(AC.IsSubmitHomework,0) IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			GROUP BY AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ClassworkStatusId,
			HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			AC.HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title,
		  vTSD.SubjectName,
		    EM.FirstName,  EM.LastName,
		    vTSD.ClassTitle,
		   vTSD.DivisionTitle,
		    BM.OrgId,
		    OM.DisplayTitle,
		     AC.ClassWorkDate, AC.DivisionId,AC.SubjectId,AC.IsSubmitHomework
	order by 
			AC.HomeWorkEndDate DESC
		END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pClassworkGet]

	 @rId bigint=0,	 
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rEmployeeId bigint=0,
	 @rDivisionid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rOrgId int=0,
     --@rBatchId int
     @rOrgGroupBatchId int=0,
    @rUserId bigint =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF(@rEmployeeId = -1)
	BEGIN
		SET @rEmployeeId = 0
	END

	if(@rId = 0)
		BEGIN
			SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(AC.CreatedDateTime,'')) AS CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework,
			AC.Id AS ClassworkId
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
		END 
	ELSE
		BEGIN
		SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(AC.CreatedDateTime,'')) AS CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework,
			AC.Id AS ClassworkId
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			GROUP BY AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ClassworkStatusId,
			HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			AC.HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title,
		  vTSD.SubjectName,
		    EM.FirstName,  EM.LastName,
		    vTSD.ClassTitle,
		   vTSD.DivisionTitle,
		    BM.OrgId,
		    OM.DisplayTitle,
		     AC.ClassWorkDate, AC.DivisionId,AC.SubjectId
			 ,AC.IsSubmitHomework
	order by 
			AC.HomeWorkEndDate DESC
		END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAcademic].[pClassworkHomeworkQueueGet]

	 @rId bigint=0,	 
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rEmployeeId bigint=0,
	 @rDivisionid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rOrgId int=0,
     --@rBatchId int
     @rOrgGroupBatchId int=0,
    @rUserId bigint =0,
	@rStatusId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


DECLARE @rSourceId bigint
DECLARE @rSourceTypeId int

set @rSourceId = ( SELECT SourceId FROM sSecurity.tUser where Id=@rUserId)
set @rSourceTypeId = ( SELECT ISNULL(SourceTypeId,0) FROM sSecurity.tUser where Id=@rUserId)


BEGIN 


	--if(@rId = 0)
		--BEGIN

			if(@rSourceTypeId = 95)
				BEGIN

				CREATE TABLE #TempData
				( 
					Id bigint,
					EmployeeId bigint,
					ClassId int,
					DivisionId int,
					SubjectId int,
					ClassWorkDate Date,
					Classwork nvarchar(max),
					Homework nvarchar(max),
					ClassworkStatusId int,
					HomeWorkStatusId int,
					HomeWorkEndDate date,
					CreatedDateTime datetime,
					BatchId bigint,
					Batch nvarchar(100),
					SubjectName nvarchar(100),
					TeacherName nvarchar(200),
					ClassName nvarchar(100),
					DivisionName nvarchar(100),
					OrgId int,
					Organization nvarchar(200),
					UniqueId nvarchar(500),
					StatusId int,
					SubjectCordinatorEmployeeId bigint,
					Status nvarchar(200),
					IsSubmitHomework bit
				)
				INSERT INTO #TempData  
					SELECT 
					AC.Id,
					AC.EmployeeId,
					AC.ClassId,
					AC.DivisionId,
					AC.SubjectId,
					AC.ClassWorkDate,
					AC.Classwork,
					AC.Homework,
					ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
					ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
					--AC.HomeWorkEndDate,
					ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
					AC.CreatedDateTime,
					AC.BatchId,
					BM.Title AS Batch,
					ISNULL(vTSD.SubjectName,'') as SubjectName,
					ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
					ISNULL(vTSD.ClassTitle,'') AS ClassName,
					ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
					BM.OrgId,
					OM.DisplayTitle AS Organization,
					REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
					ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
					CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
					ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
			FROM 
					sAcademic.tClasswork AC
					INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
					INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
					--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
					INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
					INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
					INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
			WHERE 
					--((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
					((AC.Id = @rId) OR (@rId = 0))
					AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
					AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
					AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
					AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
					AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
					--AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
					--AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
					AND (OGBM.Id = @rOrgGroupBatchId) 
					AND ((U.UserId = @rUserId)OR(@rUserId=0))
					AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
					AND ((ISNULL(vTSD.SubjectCordinatorEmployeeId,0) = @rSourceId) or (@rSourceId=0))
					AND ISNULL(EM.IsOtherUser,0) = 0 
			order by 
					AC.HomeWorkEndDate DESC
						
				if (EXISTS (select 1 from #TempData))
				BEGIN
				
					Select * FROM #TempData tmp
					WHERE (tmp.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
					AND (tmp.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
				END
				ELSE
				BEGIN
					SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ((ISNULL(vTSD.EmployeeId,0) = @rSourceId) or (@rSourceId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
				END

									
				DROP TABLE #TempData
				END

			ELSE IF (@rUserId = 0)
			BEGIN
			SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,

			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			--INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			--INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			--AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
			END

			ELSE
				BEGIN
					SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,

			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			--INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
				END

		--END 
	--ELSE
	--	BEGIN
	--	SELECT 
	--		AC.Id,
	--		AC.EmployeeId,
	--		AC.ClassId,
	--		AC.DivisionId,
	--		AC.SubjectId,
	--		AC.ClassWorkDate,
	--		AC.Classwork,
	--		AC.Homework,
	--		ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
	--		ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
	--		--AC.HomeWorkEndDate,
	--		ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
	--		AC.CreatedDateTime,
	--		AC.BatchId,
	--		BM.Title AS Batch,
	--	    ISNULL(vTSD.SubjectName,'') as SubjectName,
	--	    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
	--	    ISNULL(vTSD.ClassTitle,'') AS ClassName,
	--	    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
	--	    BM.OrgId,
	--	    OM.DisplayTitle AS Organization,
	--	    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId
			
	--FROM 
	--		sAcademic.tClasswork AC
	--		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
	--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
	--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
	--		INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
	--		INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
	--		INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
	--		INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	--WHERE 
	--        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
	--		((AC.Id = @rId) OR (@rId = 0))
	--		AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
	--		AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
	--		AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
	--		AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
	--		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
	--		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
	--		AND (OGBM.Id = @rOrgGroupBatchId) 
	--		AND ((U.UserId = @rUserId)OR(@rUserId=0))
	--		GROUP BY AC.Id,
	--		AC.EmployeeId,
	--		AC.ClassId,
	--		AC.DivisionId,
	--		AC.SubjectId,
	--		AC.ClassWorkDate,
	--		AC.Classwork,
	--		AC.Homework,
	--		ClassworkStatusId,
	--		HomeWorkStatusId,
	--		--AC.HomeWorkEndDate,
	--		AC.HomeWorkEndDate,
	--		AC.CreatedDateTime,
	--		AC.BatchId,
	--		BM.Title,
	--	  vTSD.SubjectName,
	--	    EM.FirstName,  EM.LastName,
	--	    vTSD.ClassTitle,
	--	   vTSD.DivisionTitle,
	--	    BM.OrgId,
	--	    OM.DisplayTitle,
	--	     AC.ClassWorkDate, AC.DivisionId,AC.SubjectId
	--order by 
	--		AC.HomeWorkEndDate DESC
	--	END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pClassworkHomeworkQueueUpdate]
	 
	 	
        @rId bigint,        
		@rStatusId int,
		@rLoginUserId bigint
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	 BEGIN TRY
		
	    UPDATE  sAcademic.tClasswork
	    SET
			StatusId=@rStatusId,ApprovedByEmployeeId=@rLoginUserId WHERE Id = @rId

	      SELECT 11 AS Result

	END TRY	
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
		END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pClassworkStudentGet]

	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate date='',
     @rToDate date='',
     @rHomeWorkEndDate	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,@lAcademicId Bigint
	SELECT @lDivisionId = DivisionId, @lAcademicId=ID FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
	
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

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

	DECLARE @lIsOptional INT = 0
	SET @lIsOptional =(SELECT TOP 1 1 FROM sAcademic.tClasswork AC 
						INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
						INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
						INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
						INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
						INNER JOIN sStudent.vStudentAcademic SA  ON AC.ClassId=SA.ClassId AND AC.DivisionId=SA.DivisionId
						INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = SM.Id
						where CS.IsOptional=1 AND SA.AcademicId =@lAcademicId)
	
	IF (@lIsOptional=1)
	BEGIN
	print @lIsOptional
	SELECT distinct
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    AC.Classwork,
		    AC.Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC			 
			INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sStudent.vStudentAcademic SA  ON AC.ClassId=SA.ClassId AND AC.DivisionId=SA.DivisionId
			INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = SM.Id
			LEFT JOIN [sAssessment].[tOptionalSubject] OS ON OS.ClassSubjectId = CS.Id AND Os.AcademicId = SA.AcademicId AND OS.AcademicId IS NULL -- Add condition Here for Mantis Id: 0036196
	WHERE 
	    AC.DivisionId = @lDivisionId		 
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
		AND ISNULL(EM.IsOtherUser,0) = 0 
		
	END

	ELSE 
	BEGIN
		SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    AC.Classwork,
		    AC.Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    --ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC			 
			INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			
	WHERE 
	    AC.DivisionId = @lDivisionId		 
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
		AND ISNULL(EM.IsOtherUser,0) = 0 
		AND AC.BatchId = @rBatchId
		order by  AC.CreatedDateTime desc
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pClassworkStudentWithStatusGet]

	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate date='',
     @rToDate date='',
     @rHomeWorkEndDate	date='' 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lDivisionId int
	DECLARE @lAcademicId bigint
	SELECT @lDivisionId = DivisionId,@lAcademicId = Id FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId

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

	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1
	
	DECLARE @lIsOptional INT = 0
	SET @lIsOptional =(SELECT TOP 1 1 FROM sAcademic.tClasswork AC 
						INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
						INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
						INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
						INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
						INNER JOIN sStudent.vStudentAcademic SA  ON AC.ClassId=SA.ClassId AND AC.DivisionId=SA.DivisionId
						INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = SM.Id
						where CS.IsOptional=1 AND SA.AcademicId =@lAcademicId)
	
	IF (@lIsOptional=1)
	BEGIN
	SELECT 
			DISTINCT(AC.Id),
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    CASE WHEN AC.ClassworkStatusId != 2 THEN AC.Classwork ELSE 'NA' END AS Classwork,
		    CASE WHEN AC.HomeWorkStatusId != 2 THEN AC.Homework ELSE 'NA' END AS Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
		    ISNULL(HCSM.Title,'Assigned') AS HomeworkStatus,
			AC.ClassWorkDate ,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC			 
			INNER JOIN sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER JOIN sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER JOIN sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER JOIN sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sStudent.tAcademic SA ON SA.ClassId = AC.ClassId AND SA.DivisionId = AC.DivisionId AND SA.BatchId = AC.BatchId
			LEFT JOIN sAcademic.tHomeworkCheck HWC ON HWC.AcademicId = SA.Id AND HWC.ClassworkId = AC.Id
			LEFT JOIN sAcademic.tHomeworkCheckStatusMaster HCSM ON HCSM.Id = HWC.HomeWorkCheckStatusId
			INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = SM.Id
			LEFT JOIN [sAssessment].[tOptionalSubject] OS ON OS.ClassSubjectId = CS.Id AND OS.AcademicId = SA.Id AND OS.AcademicId IS NULL
	WHERE 
			AC.DivisionId = @lDivisionId		 
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
			AND AC.BatchId = @rBatchId
			AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			--AND AC.StatusId=550
			--AND SA.Id = @lAcademicId
			--uncomment above AND SA.Id = @lAcademicId because HomeworkStatus not display Studentwise
			--AND OS.AcademicId IS NULL
	ORDER BY  AC.ID DESC
	END

	ELSE 
	BEGIN
		SELECT 
			DISTINCT(AC.Id),
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    CASE WHEN AC.ClassworkStatusId != 2 THEN AC.Classwork ELSE 'NA' END AS Classwork,
		    CASE WHEN AC.HomeWorkStatusId != 2 THEN AC.Homework ELSE 'NA' END AS Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
		    ISNULL(HCSM.Title,'Assigned') AS HomeworkStatus,
			AC.ClassWorkDate ,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC			 
			INNER JOIN sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER JOIN sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER JOIN sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER JOIN sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sStudent.tAcademic SA ON SA.ClassId = AC.ClassId AND SA.DivisionId = AC.DivisionId AND SA.BatchId = AC.BatchId
			LEFT JOIN sAcademic.tHomeworkCheck HWC ON HWC.AcademicId = SA.Id AND HWC.ClassworkId = AC.Id
			LEFT JOIN sAcademic.tHomeworkCheckStatusMaster HCSM ON HCSM.Id = HWC.HomeWorkCheckStatusId
	WHERE 
			AC.DivisionId = @lDivisionId		 
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
			AND AC.BatchId = @rBatchId
			AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			--AND AC.StatusId=550
			--AND SA.Id = @lAcademicId
			--uncomment above AND SA.Id = @lAcademicId because HomeworkStatus not display Studentwise
			AND SA.Id = @lAcademicId
	ORDER BY  AC.ID DESC
	END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAcademic].[pConfigurationAdd]
	 
	@rOrgId int,
	@rClassworkTemplate nvarchar(1000),
	@rHomeworkTemplate nvarchar(1000) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

 IF NOT EXISTS(SELECT OrgId FROM sAcademic.tClassworkConfig WHERE OrgId=@rOrgId)	
	  BEGIN
		INSERT INTO sAcademic.tClassworkConfig
		   (
			[OrgId],
			[ClassworkTemplate],
			[HomeworkTemplate]
		   )
		VALUES
		   (
			@rOrgId,
			@rClassworkTemplate,
			@rHomeworkTemplate
		   )
		Select 101 AS Result	   
	  END	 
	 
 ELSE
	  
	 BEGIN
	   UPDATE sAcademic.tClassworkConfig
		  SET
			 [ClassworkTemplate]=@rClassworkTemplate,
			 [HomeworkTemplate]=@rHomeworkTemplate
		  WHERE  OrgId=@rOrgId 
	   SELECT 102 AS Result
	 END 	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAcademic].[pDailyStatusGet]

     @rSearchDate datetime,
     @rOrgId smallint,
     @rBatchId int,     
     @rYear smallint,
     @rMonth smallint,
     @rDate smallint,
	 @rAttendanceTypeId int=1,
	 @rAttendanceStatusId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	 
 

	SELECT 				
			vCD.ClassDivisionName,
			ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
			[sAttendance].[fWeekHOffGet](@rYear,@rMonth,@rDate,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId) AS WeekOffStatus, 
			CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus, 
            sCommon.fCountDivisionStudent(A.DivisionId,@rBatchId) AS TotalCount, 
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,@rSearchDate,@rAttendanceTypeId,1) AS PresentCount,
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,@rSearchDate,@rAttendanceTypeId,0) AS AbsentCount,
			ISNULL(MAX(SR.UpdatedDateTime),MAX(SR.CreatedDateTime)) as UpdatedDateTime,
			--ISNULL((SELECT TOP 1 U.DisplayTitle FROM sSecurity.tUser U WHERE U.Id = ISNULL(SR.UpdatedUserId,SR.CreatedUserId)),'') AS UserName
			[sCommon].[fGetUserNameforDailyStatus](A.DivisionId,@rSearchDate,@rAttendanceTypeId)AS UserName
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			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 AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceDate=@rSearchDate 
            AND SR.AttendanceTypeId = @rAttendanceTypeId 
			AND SR.IsPresent=1 
					
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId
			--,SR.UpdatedUserId,SR.CreatedUserId
			Having (@rAttendanceStatusId=1 AND (COUNT(SR.AcademicId)=0 And (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0)) =0) )
				OR (@rAttendanceStatusId=2 and (COUNT(SR.AcademicId)<>0 OR (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0))<>0) )
				 OR ( @rAttendanceStatusId=0)	
            ORDER BY vCD.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pGetLessonPlanApi]

	 @rAcademicId bigint,
	 @rBatchId int,
	 @rDivisionId int,
	 @rSubjectId int,
	 @rFromDate datetime='',
     @rToDate datetime='',
	 @rIsCompleted int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
    --for IsCompleted false
	IF (@rIsCompleted = 2)
	BEGIN
	 SET @rIsCompleted = 0
	END
	--for IsCompleted true
	ELSE IF(@rIsCompleted = 1)
	BEGIN
		SET @rIsCompleted = 1 
	END
	--for IsCompleted All
	ELSE
	BEGIN
	SET @rIsCompleted = 2
	END

	--Select @rIsCompleted
	SELECT 
		TM.Title AS TopicName,
		LP.NoOfPeriodRequired,
		LP.Objective,
		LP.IndicativeHomework,
		LP.Summary,
		LP.StartDate,
		LP.EndDate,
		--LP.IsCompleted,			
		CASE WHEN (LP.IsCompleted = 'True') THEN  'Completed' ELSE 'InCompleted' END AS IsCompleted,
		LP.LearningExperience,
		LP.ToolsAndTechniques,
		LP.EssentialMaterial,
		LP.AssessmentQuestion,
		LP.TeacherExample,
		LP.GuidedPractice,
		LP.IndependentPractice,
		LP.SubTopic,
		Em.FirstName+' '+EM.LastName AS TeacherName,
		LP.IsCompleted ,
		LP.Session ,
		LP.TrainingMethod ,
		LP.PeriodCount,
		SM.Title AS SubjectName,
		LP.Id as LessonPlanId,
		LP.Remark
	FROM 
		--sAcademic.tLessonPlan LP
		--INNER JOIN  sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = @rSubjectId
		--INNER JOIN sStudent.tAcademic AM ON AM.BatchId = @rBatchId AND AM.DivisionId = @rDivisionId
		--Left Join  sHrm.tEmployeeMaster EM ON Em.Id=Lp.EmployeeId
			sAcademic.tLessonPlan LP
		INNER JOIN  sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
		INNER JOIN sStudent.tAcademic AM ON AM.BatchId = LP.BatchId AND AM.DivisionId = LP.DivisionId
		Left Join  sHrm.tEmployeeMaster EM ON Em.Id=Lp.EmployeeId
		
	WHERE 
		((LP.DivisionId = @rDivisionId)  OR (@rDivisionId = 0))
		AND ((LP.BatchId = @rBatchId) OR (@rBatchId = 0))
		--AND ((SM.Id = @rSubjectId) OR (SM.Id = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND AM.Id = @rAcademicId
		--AND (LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
		 --   AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)
		AND ((LP.IsCompleted = @rIsCompleted) OR (@rIsCompleted = 2))
		
	ORDER BY SM.Id
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pHomeworkNotGivenDashboardGet]
	 @rOrgGroupId int=0,
	 @rConfigurationValue int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT
		OM.Id AS OrgId,
		vEM.Code AS Code,
		vEM.EmployeeName,
		SM.Title AS EmployeeSubject,
		DATEDIFF(day, isnull(Max(ClassWorkDate),getdate()-@rConfigurationValue),getdate())  AS DayCount
	FROM
		 sHrm.vExtEmployeeMaster vEM
		 INNER JOIN sAcademic.tTeacherSubject TS ON TS.EmployeeId = vEM.EmployeeId
		 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TS.SubjectId 
		 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
		 INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id AND BM.IsActive = 1
		 LEFT JOIN sAcademic.tClasswork CW ON CW.EmployeeId = vEM.EmployeeId AND CW.SubjectId=TS.SubjectId AND BM.Id=CW.BatchId		
	WHERE 
		OM.OrgGroupId = @rOrgGroupId AND DATEDIFF(day, isnull(ClassWorkDate,getdate()-@rConfigurationValue),getdate()) >= @rConfigurationValue
	GROUP BY 
		vEM.EmployeeId,OM.Id,vEM.Code,vEM.EmployeeName,SM.Title	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pHomeworkStatusUpdate]
	 
	@rAcademicId bigint,
	@rClassworkId bigint,
	@rHomeWorkCheckStatusId tinyint,
	@rRemark nvarchar(1000),
	@rCheckedByUserId bigint,
	@rCheckedByDateTime datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		   --DECLARE @lCode nvarchar(20)
		   --SELECT @lCode=Code FROM sStudent.tStudentMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rStudentId
		   --IF @lCode IS NOT NULL
		   --BEGIN
					--SELECT -103 AS Result,@lCode AS Code
					--RETURN
		   --END 
		   
		   DELETE From sAcademic.tHomeworkCheck Where ClassworkId = @rClassworkId AND AcademicId = @rAcademicId

		   
	BEGIN TRY
	 BEGIN TRANSACTION	
		 BEGIN
		 
		 
		 INSERT INTO sAcademic.tHomeworkCheck
		 (
			ClassworkId,
			AcademicId,
			HomeWorkCheckStatusId,
			Remark,
			CheckedByUserId,
			CheckedByDateTime
		 )
		 VALUES
		 (
			@rClassworkId,
			@rAcademicId,
			@rHomeWorkCheckStatusId,
			@rRemark,
			@rCheckedByUserId,
			@rCheckedByDateTime
		 )
		 
		  --  UPDATE  sStudent.tStudentMaster
		  --  SET
			 --   Code=@rIDNo,
				--Number = (CASE WHEN @rIsNumber = 0 THEN Number WHEN @rIsNumber = 1 THEN @rIDNo END), 
				--RecordStatusId = @rRecordStatusId,				  
				--UpdatedUserId=@rCreatedUserId,
				--UpdatedDateTime=sCommon.fGetDate() 
		  --    WHERE Id = @rStudentId 	   
		 END  
		SELECT 1 AS RESULT
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pHomeworkViewAdd]
	 
	@rAcademicId bigint,
	@rClassworkId bigint,
	@rViewByUserId bigint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	 BEGIN TRANSACTION	
		 BEGIN
		 IF NOT EXISTS(SELECT ClassworkId,AcademicId,ViewByUserId FROM sAcademic.tClassworkView WHERE ClassworkId=@rClassworkId AND AcademicId=@rAcademicId AND ViewByUserId=@rViewByUserId)
		 INSERT INTO sAcademic.tClassworkView
		 (
			ClassworkId,
			AcademicId,
			ViewByUserId,
			ViewByDateTime
		 )
		 VALUES
		 (
			@rClassworkId,
			@rAcademicId,
			@rViewByUserId,
        	sCommon.fGetDate()
		 )
		SELECT 1 AS RESULT
        END  
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pHomeworkViewGet]
	 
	@rClassworkId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	 BEGIN TRANSACTION	
		 BEGIN
		 SELECT 
			 SM.Code,
			 SM.FirstName +' '+ SM.LastName as Name,
			 CV.ViewByDateTime
		 FROM
			 sAcademic.tClassworkView as CV
			 INNER JOIN sStudent.tAcademic SA on SA.Id = CV.AcademicId
			 INNER JOIN sStudent.tStudentMaster SM on SM.Id = SA.StudentId
		 WHERE
		 ClassworkId = @rClassworkId
		SELECT 1 AS RESULT
        END  
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END

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

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

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

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

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

		WHILE @lCount > 0 

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

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

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

		 END
END

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

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

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

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

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

	DECLARE @lNextNumber BIGINT 

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

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

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pLessonPlanCopy]
	 
        
        @rFromDivisionId int, 
        @rToDivisionId int, 
        @rEmployeeId bigint,
        @rBatchId int,
        @rOrgId int
         
  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 DECLARE @lNextNumber bigint
	 DECLARE @lDataCount int, @lCount int = 1
	 
	 Delete from sAcademic.tLessonPlan where DivisionId = @rToDivisionId AND EmployeeId =@rEmployeeId AND BatchId=@rBatchId	 

	CREATE TABLE #LessonPlanTemp (
    Id INT IDENTITY(1,1), 
    LessonPlanId BIGINT
	);
	INSERT INTO #LessonPlanTemp 
		SELECT Id FROM sAcademic.tLessonPlan where DivisionId =@rFromDivisionId AND EmployeeId =@rEmployeeId;
		Select @lDataCount = Count (Id) from #LessonPlanTemp 

	WHILE @lCount <= @lDataCount
		BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
		Insert into sAcademic.tLessonPlan
		(
		Id,
		DivisionId,
		TopicId,
		NoOfPeriodRequired,
		Objective,
		IndicativeHomework,
		Summary,
		StartDate,
		EndDate,
		IsCompleted,
		EmployeeId,
		BatchId,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		 UpdatedDateTime,
		LearningExperience,
		ToolsAndTechniques,
		EssentialMaterial,
		AssessmentQuestion,
		TeacherExample,
		GuidedPractice,
		IndependentPractice,
		SubTopic ,
		[Session],
		TrainingMethod,
		PeriodCount
		)
		Select 
		@lNextNumber,
		@rToDivisionId,
		TopicId,
		NoOfPeriodRequired,
		Objective,
		IndicativeHomework,
		Summary,
		StartDate,
		EndDate,
		IsCompleted,
		EmployeeId,
		BatchId,
		CreatedUserId,
		sCommon.fGetDate(),
		UpdatedUserId,
		sCommon.fGetDate(),
		LearningExperience,
		ToolsAndTechniques,
		EssentialMaterial,
		AssessmentQuestion,
		TeacherExample,
		GuidedPractice,
		IndependentPractice,
		SubTopic ,
		[Session],
		TrainingMethod,
		PeriodCount
		from sAcademic.tLessonPlan LP
		INNER JOIN #LessonPlanTemp tLP ON tLP.LessonPlanId = LP.Id
		WHERE DivisionId =@rFromDivisionId AND EmployeeId =@rEmployeeId AND tLP.Id = @lCount
		SET @lCount = @lCount + 1
		END	
		Select 1 as result
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

	 @rId bigint=0,
	 @rClassId int=0,
	 @rSubjectId int=0,
	 @rDivisionId int=0,
	 @rIsCompleted bit=0,
	 @rBatchId int=0,
	 @rEmployeeId bigint=0,
	 @rDepartmentid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rCreatedUserId bigint=0,
	 @rStatus int = 0,
	 @rIsWithHeader bit=0,
	 --Addded by dhananjay mantis - 0035004
	 @rBuilder1 nvarchar(max) = '',
	 @rBuilder2 nvarchar(max)  = ''
	--Addded by dhananjay mantis - 0035004
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pLessonPlanMobileGet]

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

BEGIN 
DECLARE @lIsCompleted bit = 0
	
	If(@rIsCompletedAPI=1)
		SET @lIsCompleted = 1
	else If(@rIsCompletedAPI=2)
		SET @lIsCompleted = 0
	
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic ,
			ISNULL(LP.[Session] ,'') As [Session] ,
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
	WHERE 
		((LP.BatchId = @rBatchId) OR (LP.BatchId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND((LP.IsCompleted=@lIsCompleted) OR (@rIsCompletedAPI=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		))
		--AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,0)=0) 
		AND  (LP.EmployeeId = @rEmployeeId OR (ISNULL(@rEmployeeId,0)=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--Added by dhananjay mantis : 43006	
		AND ISNULL(CM.IsObsolete,0) = 0
		AND ISNULL(DM.IsObsolete,0) = 0
		--Added by dhananjay mantis : 43006	
	ORDER BY
		LP.StartDate,LP.EndDate,LP.id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pLessonPlanUpdate]
	 
        @rId bigint,
        @rIsCompleted bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	 BEGIN
	    UPDATE  sAcademic.tLessonPlan
	    SET
			IsCompleted=@rIsCompleted
	      WHERE Id = @rId
	      
	    SELECT 11 AS Result
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAcademic].[pMeetingAccountAdd]
	 
        @rId bigint = 0,
		@rEmployeeId bigint=0,
		@rMeetingProviderId int,
		@rAccountName nvarchar(200)='',
		@rAccountEmail nvarchar(200)='',
		@rAccountPassword nvarchar(200)='',
		@rAPIKey nvarchar(100)='',
		@rAPISecret nvarchar(100)='',
		@rWebAPIKey nvarchar(100)='',
		@rWebAPISecret nvarchar(100)='',
		@rCreatedUserId bigint,
		@rOrgGroupId Smallint,
		@rJWTToken nvarchar(MAX)='',
		@rIsObsolete  bit =0,
		@rOAuthAccountId nvarchar(max)='',
		@rOAuthClientId nvarchar(max)='',
		@rOAuthClientSecret nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	IF EXISTS(SELECT 1 FROM sAcademic.tOnlineMeetingAccount WHERE AccountName = @rAccountName AND Id != @rId AND OrgGroupId = @rOrgGroupId)
		BEGIN
			SELECT -202 As Result
		END	
	ELSE
	BEGIN
	IF(@rId = 0)	
	BEGIN
		
	 
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAcademic.tOnlineMeetingAccount', 0, 1, 1,@outNextNumber = @lNextNumber output
	--Print @lNextNumber

	INSERT INTO sAcademic.tOnlineMeetingAccount
		(
			Id
           ,MeetingProviderId
           ,EmployeeId
           ,AccountName
           ,AccountEmailId
           ,AccountPassword
           ,APIKey
           ,APISecret
           ,WebAPIKey
           ,WebAPISecret
           ,CreatedUserId
           ,CreatedDateTime
		   ,OrgGroupId
		   ,JWTToken
		   ,IsObsolete
		   ,OAuthAccountId
		   ,OAuthClientId
		   ,OAuthClientSecret
		)
	VALUES
		(
			@lNextNumber,
			@rMeetingProviderId,
			@rEmployeeId,
			@rAccountName,
			@rAccountEmail,
			@rAccountPassword,
			@rAPIKey,
			@rAPISecret,
			@rWebAPIKey,
			@rWebAPISecret,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rJWTToken,
			@rIsObsolete,
			@rOAuthAccountId,
		    @rOAuthClientId,
		    @rOAuthClientSecret
		)
		    SELECT @lNextNumber AS Result
	END	 
	ELSE
	 BEGIN
	 SET @lNextNumber = @rId

	    UPDATE sAcademic.tOnlineMeetingAccount
	    SET
        	Id = @rId 
           ,EmployeeId = @rEmployeeId
           ,AccountName = @rAccountName
           ,AccountEmailId = @rAccountEmail
           ,AccountPassword = @rAccountPassword
           ,APIKey = @rAPIKey
           ,APISecret = @rAPISecret
		   ,WebAPIKey = @rWebAPIKey
           ,WebAPISecret = @rWebAPISecret
		   ,UpdatedUserId = @rCreatedUserId
		   ,UpdatedDateTime = sCommon.fGetDate()
		   ,OrgGroupId = @rOrgGroupId
		   ,JWTToken = @rJWTToken
		   ,IsObsolete = @rIsObsolete
		   ,OAuthAccountId = @rOAuthAccountId
		   ,OAuthClientId = @rOAuthClientId
		   ,OAuthClientSecret = @rOAuthClientSecret
	     WHERE Id = @rId
	      
		DECLARE @tOnlineLearningAccount TABLE  
		(  
		Id INT IDENTITY(1, 1),  
		OnlineLearningId BIGINT
		)   

		INSERT INTO @tOnlineLearningAccount
		SELECT Id
		FROM 
		 sAcademic.tOnlineLearning 
		WHERE MeetingAccountId = @rId AND IsCompleted = 0
		
		DECLARE @lCount int=1
		WHILE(@lCount <= (SELECT count(*) FROM @tOnlineLearningAccount))                
		BEGIN
			UPDATE sAcademic.tOnlineMeetingSettings 
			SET 
			AccountEmailId = OMA.AccountEmailId
		   ,AccountPassword = OMA.AccountPassword
		   ,APIKey = OMA.APIKey
		   ,APISecret = OMA.APISecret
		   ,WebAPIKey = OMA.WebAPIKey
		   ,WebAPISecret = OMA.WebAPISecret
		   ,MeetingProviderId = OMA.MeetingProviderId
		   ,JWTToken = OMA.JWTToken
		   ,OAuthAccountId = @rOAuthAccountId
		   ,OAuthClientId = @rOAuthClientId
		   ,OAuthClientSecret = @rOAuthClientSecret
		   FROM
			sAcademic.tOnlineMeetingAccount OMA
		   WHERE 
			OnlineLearningId = (SELECT OnlineLearningId FROM @tOnlineLearningAccount WHERE Id = @lCount)
			AND OMA.Id = @rId

			SET @lCount = @lCount + 1
		END
	      SELECT -100 AS Result
		--COMMIT TRANSACTION
	 END  	
	END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAcademic].[pMeetingAccountDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			 IF EXISTS(SELECT 1 FROM sAcademic.tOnlinelearning WHERE MeetingAccountId = @rId)
			 BEGIN
				SELECT -101 as Result
			 END
			 ELSE
			 BEGIN
				DELETE FROM sAcademic.tOnlineMeetingAccount WHERE Id = @rId
				SELECT 1 as Result
			 END
		COMMIT TRANSACTION			  
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION		
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAcademic].[pMeetingAccountGet]

	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rEmployeeId bigint = 0,
	 @rOrgGroupId smallint,
	 @rMeetingProviderId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	if(@rId = 0)
	BEGIN 
	
	SELECT 
			OMA.Id,
			OMA.AccountName,
			OMA.AccountEmailId,
			ISNULL(EM.EmployeeName,'') as EmployeeName,
			DM.Title as MeetingProvider,
			OMA.WebAPIKey,
			OMA.WebAPISecret,
			ISNULL(OMA.IsObsolete,0) as IsObsolete,
			ISNULL(OMA.OAuthAccountId,'')AS OAuthAccountId,
			ISNULL(OMA.OAuthClientId,'') AS OAuthClientId,
			ISNULL(OMA.OAuthClientSecret,'') AS OAuthClientSecret
	  FROM 
			sAcademic.tOnlineMeetingAccount OMA
			LEFT JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OMA.EmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON OMA.MeetingProviderId = DM.Id AND DM.DataTypeId = 8
	  WHERE 
  
				((OMA.AccountName like @rTitle) OR (ISNULL(@rTitle,'') = ''))
				AND OMA.OrgGroupId = @rOrgGroupId
				AND ((OMA.MeetingProviderId = @rMeetingProviderId) OR (ISNULL(@rMeetingProviderId,0) = 0))
	 
	END
	ELSE
	BEGIN
		SELECT 
			OMA.Id,
			OMA.EmployeeId as EmployeeId,
			EM.EmployeeCode as EmployeeCode,
			OMA.AccountName as AccountName,
			OMA.AccountEmailId as AccountEmailId,
			OMA.AccountPassword as AccountPassword,
			OMA.APIKey as APIKey,
			OMA.APISecret as APISecret,
			OMA.WebAPIKey as WebAPIKey,
			OMA.WebAPISecret as WebAPISecret,
			OMA.MeetingProviderId as MeetingProviderId,
			DM.Title as MeetingProvider,
			OMA.JWTToken as JWTToken,
			ISNULL(OMA.IsObsolete,0) as IsObsolete,
			ISNULL(OMA.OAuthAccountId,'')AS OAuthAccountId,
			ISNULL(OMA.OAuthClientId,'') AS OAuthClientId,
			ISNULL(OMA.OAuthClientSecret,'') AS OAuthClientSecret
	  FROM 
			sAcademic.tOnlineMeetingAccount OMA
			INNER JOIN sCommon.tDataMaster DM ON OMA.MeetingProviderId = DM.Id AND DM.DataTypeId = 8
			LEFT JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OMA.EmployeeId
	  WHERE 
			(OMA.Id = @rId) AND OMA.OrgGroupId = @rOrgGroupId
			AND ((OMA.MeetingProviderId = @rMeetingProviderId) OR (ISNULL(@rMeetingProviderId,0) = 0))
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pMigrateHistoryToOnlineLearning]
	@rFromDate DATE,
	@rToDate DATE 

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

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

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

	--insert into [sAcademic].[tOnlineLearningAttendance]

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

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

	--insert into [sAcademic].[tOnlineLearningRecording]

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

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

	--insert into [sAcademic].[tOnlineLearningAssignmentSubmitHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningAssignmentHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningReferenceHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningResourceHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningViewHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningScopeHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningHistory]

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

	DELETE FROM sAcademic.tOnlineLearningHistory
	WHERE 
	convert(date,CreatedDateTime)>=convert(date,@rFromDate) 
	AND convert(date,CreatedDateTime)<=convert(date,@rToDate) 
	--OL.Id = @rId
	 
	SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pMonthlyStatusGet]

    
	 
     @rOrgId smallint,
     @rBatchId Bigint,     
     @rYear smallint,
     @rMonth smallint,
	 @rDayOfMonth smallint,
	 @rAttendanceTypeId int =1,
	 @rClassId Bigint,
	 @rDivisionId Bigint
     --@rDate smallint,
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	



 SELECT 	A.ClassId ,A.DivisionId,vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
		  

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P1	,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,02,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,02,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-02')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-02'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P2,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,03,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,03,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-03')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-03'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P3,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,04,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,04,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-04')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-04'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P4,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,05,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,05,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-05')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-05'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P5,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,06,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,06,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-06')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-06'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P6,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,07,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,07,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-07')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-07'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P7,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,08,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,08,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-08')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-08'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P8,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,09,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,09,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-09')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-09'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P9,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,10,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,10,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-10')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-10'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P10,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,11,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,11,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-11')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-11'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P11,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,12,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,12,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-12')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-12'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId AND ISNULL(EM.IsOtherUser,0) = 0
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P12,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,13,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,13,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-13')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-13'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P13,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,14,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,14,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-14')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-14'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P14,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,15,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,15,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-15')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-15'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P15,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,16,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,16,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-16')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-16'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P16,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,17,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,17,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-17')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-17'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P17,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,18,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,18,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-18')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-18'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P18,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,19,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,19,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-19')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-19'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P19,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,20,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,20,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-20')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-20'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P20,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,21,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,21,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-21')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-21'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P21,

				(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,22,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,22,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-22')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-22'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P22,


			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,23,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,23,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-23')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-23'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P23,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,24,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,24,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-24')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-24'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P24,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,25,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,25,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-25')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-25'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P25,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,26,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,26,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-26')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-26'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P26,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,27,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,27,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-27')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-27'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P27,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,28,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,28,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-28')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-28'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P28,

			CASE WHEN @rDayOfMonth >=29 THEN

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,29,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,29,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-29')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-29'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) ELSE '' END AS P29,

			CASE WHEN @rDayOfMonth >=30 THEN

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,30,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,30,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-30')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-30'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) ELSE '' END AS P30,


			CASE WHEN @rDayOfMonth =31 THEN

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,31,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,31,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-31')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-31'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) ELSE '' END AS P31

			
		
			   
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0      
			WHERE A.ClassId=@rClassId	AND A.DivisionId=@rDivisionId 
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pNumberClassSubjectOrderIndexGet]
           
           @rClassId int,
           @rSubjectId int,
           @rOrgId smallint
WITH EXECUTE AS CALLER          
AS
SET NOCOUNT ON
BEGIN
DECLARE @lNumberString as nvarchar(1000)

SET @lNumberString = (Select ISNULL(max(TM.Number)+1,1) AS Number FROM sAcademic.tTopicMaster TM WHERE TM.ClassId=@rClassId AND TM.SubjectId = @rSubjectId AND TM.OrgId=@rOrgId)

SELECT @lNumberString AS Number

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAdd]
	 
        @rId bigint = 0,
		@rLearningTypeId int,
		@rClassId int = 0,
        @rSubjectId int,
		@rTopicId int = 0,
		@rTeacherId bigint,
		@rStartDate date,
		@rEndDate date,
		@rStartTime datetime,
		@rEndTime datetime,
		@rTitle nvarchar(100) = '',
		@rDescription nvarchar(max) = '',
		@rLecturePath nvarchar(max) = '',
		@rIsDisplayMeetingId bit =0,
		@rMeetingId nvarchar(50) = '',
		@rMeetingPass nvarchar(50) = '',
		@rIsTrackAttendance bit =0,
		@rIsAssignment bit=0,
		@rIsResource bit=0,
		@rIsRefrence bit=0,
		@rIsCompleted bit = 0,
		@rIsMeetingStarted bit = 0,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int,
		@rTempOnlineLearningId nvarchar(100) = 0,
		@rIsSubmitAssignment bit=0,
		@rIsTakeTest bit=0,
		@rTestId int=0,
		@rIsOnParticipantVideo bit=0,
		@rIsOnParticipantAudio bit=0,
		@rIsOnHostVideo bit=0,
		@rIsOnHostAudio bit=0,
		@rIsOnParticipantScreenShare bit=0,
		@rIsOnHostscreenShare bit=0,
		@rMeetingAccountId int = 0,
		@rReferenceId bigint = 0,
		@rIsMeetingCreated bit=0,
		@rAssignmentRemark nvarchar(500) = '',
		@rIsTrackAssignmentView bit = 0,
		@rCoTeacherEmployeeId1 bigint =0,
		@rCoTeacherEmployeeId2 bigint =0,
		@rSubmissionEndDate DateTime = '',
		@rIsRecording bit = 0
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	 DECLARE @lAccountEmailId NVARCHAR(200),@lAccountPassword NVARCHAR(200),@lAPIKey NVARCHAR(100),@lAPISecret NVARCHAR(100),@lWebAPIKey NVARCHAR(100),
	         @lWebAPISecret NVARCHAR(100),@lMeetingProviderId NVARCHAR(100),@lJWTToken NVARCHAR(MAX),@lOAuthAccountId NVARCHAR(MAX), @lOAuthClientId NVARCHAR(MAX),@lOAuthClientSecret NVARCHAR(MAX)

	SELECT @lAccountEmailId = AccountEmailId,@lAccountPassword = AccountPassword,@lAPIKey = APIKey,@lAPISecret = APISecret,@lWebAPIKey = WebAPIKey,@lWebAPISecret = WebAPISecret,@lMeetingProviderId = MeetingProviderId,
	@lJWTToken = JWTToken, @lOAuthAccountId = OAuthAccountId , @lOAuthClientId = OAuthClientId , @lOAuthClientSecret = OAuthClientSecret
	    FROM sAcademic.tOnlineMeetingAccount
		WHERE Id = @rMeetingAccountId

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tOnlineLearning', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sAcademic.tOnlineLearning
		(
			Id
           ,BatchId
           ,StartDate
           ,StartTime
           ,EndDate
           ,EndTime
           ,ClassId
           ,SubjectId
           ,TeacherEmployeeId
           ,Title
           ,Description
           ,LearningTypeId
           ,IsTrackAttendance
           ,TopicId
           ,LecturePath
           ,IsDisplayMeetingId
           ,MeetingId
           ,MeetingPassword
           ,IsAssignment
           ,IsReference
           ,IsResource
           ,IsCompleted
           ,IsMeetingStarted
           ,CreatedUserId
           ,CreatedDateTime
		   ,IsSubmitAssignment
		   ,IsTakeTest
		   ,TestId
		   ,MeetingAccountId
		   ,IsMeetingCreated
		   ,AssignmentRemark
		   ,IsTrackAssignmentView
		   ,CoTeacherEmployeeId1
		   ,CoTeacherEmployeeId2
		   ,AssignmentSubmissionEndDate
		   ,IsRecording
		)
	VALUES
		(
			@lNextNumber,
			@rBatchId,
			@rStartDate,
			@rStartTime,
			@rEndDate, 
			@rEndTime,
			@rClassId,
			@rSubjectId,
			@rTeacherId,
			@rTitle,
			@rDescription,
			@rLearningTypeId,
			@rIsTrackAttendance,
			@rTopicId,
			@rLecturePath,
			@rIsDisplayMeetingId,
			@rMeetingId,
			@rMeetingPass,
			@rIsAssignment,
			@rIsRefrence,
			@rIsResource,
			@rIsCompleted,
			@rIsMeetingStarted,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsSubmitAssignment,
			@rIsTakeTest,
			@rTestId,
			@rMeetingAccountId,
			@rIsMeetingCreated,
			@rAssignmentRemark,
			@rIsTrackAssignmentView,
			@rCoTeacherEmployeeId1,
			@rCoTeacherEmployeeId2,
			@rSubmissionEndDate,
			@rIsRecording
		)
		    
		IF(@rLearningTypeId = 2)
		BEGIN
		INSERT INTO sAcademic.tOnlineMeetingSettings
		(
			OnlineLearningId,
			IsOnParticipantVideo,
			IsOnParticipantAudio,
			IsOnHostVideo,
			IsOnHostAudio,
			IsOnParticipantScreenShare,
			IsOnHostscreenShare,
			AccountEmailId,
			AccountPassword,
			APIKey,
			APISecret,
			WebAPIKey,
			WebAPISecret,
			MeetingProviderId,
			JWTToken,
			OAuthAccountId,
			OAuthClientId,
			OAuthClientSecret
		)
		VALUES
		(
			@lNextNumber,
			@rIsOnParticipantVideo,
			@rIsOnParticipantAudio,
			@rIsOnHostVideo ,
			@rIsOnHostAudio ,
			@rIsOnParticipantScreenShare,
			@rIsOnHostscreenShare,
			@lAccountEmailId,
			@lAccountPassword,
			@lAPIKey,
			@lAPISecret,
			@lWebAPIKey,
			@lWebAPISecret,
			@lMeetingProviderId,
			@lJWTToken,
			@lOAuthAccountId,
			@lOAuthClientId,
			@lOAuthClientSecret
		)
		END
		IF(@rReferenceId = 0)
		BEGIN
		   IF EXISTS (SELECT 1 FROM sAcademic.tTempOnlineLearningScope WHERE TempOnlineLearningId = @rTempOnlineLearningId)
		   BEGIN
		   print 2
				IF EXISTS(SELECT 1 FROM sAcademic.tOnlineLearningScope WHERE Convert(NVARCHAR(MAX),OnlineLearningId) = @rTempOnlineLearningId)
				BEGIN
					DELETE FROM sAcademic.tOnlineLearningScope WHERE OnlineLearningId = @rTempOnlineLearningId
				END
				INSERT INTO sAcademic.tOnlineLearningScope
				SELECT @lNextNumber,SourceTypeId,SourceId
				FROM sAcademic.tTempOnlineLearningScope 
				WHERE TempOnlineLearningId = @rTempOnlineLearningId
		
				DELETE FROM sAcademic.tTempOnlineLearningScope WHERE TempOnlineLearningId = @rTempOnlineLearningId
			--COMMIT TRANSACTION 
			END     
		END
		ELSE
		BEGIN 
		   IF EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningScope WHERE OnlineLearningId = @rReferenceId)
		   BEGIN
				INSERT INTO sAcademic.tOnlineLearningScope
				SELECT @lNextNumber,SourceTypeId,SourceId
				FROM sAcademic.tOnlineLearningScope 
				WHERE OnlineLearningId = @rReferenceId
		
			--COMMIT TRANSACTION 
			END    
		END
		SELECT @lNextNumber AS Result   
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAcademic.tOnlineLearning
	    SET
			 
           StartDate = @rStartDate
           ,StartTime = @rStartTime
           ,EndDate = @rEndDate
           ,EndTime = @rEndTime
           ,ClassId = @rClassId
           ,SubjectId = @rSubjectId
           ,TeacherEmployeeId = @rTeacherId
           ,Title = @rTitle
           ,Description = @rDescription
           ,LearningTypeId = @rLearningTypeId
           ,IsTrackAttendance = @rIsTrackAttendance
           ,TopicId = @rTopicId
           ,LecturePath = @rLecturePath
           ,IsDisplayMeetingId = @rIsDisplayMeetingId
           ,MeetingId = @rMeetingId
           ,MeetingPassword = @rMeetingPass
           ,IsAssignment = @rIsAssignment
           ,IsReference = @rIsRefrence
           ,IsResource = @rIsResource
           ,IsCompleted = @rIsCompleted
		   ,UpdatedUserId=@rCreatedUserId
		   ,UpdatedDateTime=sCommon.fGetDate()
		   ,IsSubmitAssignment=@rIsSubmitAssignment
		   ,IsTakeTest=@rIsTakeTest
		   ,TestId=@rTestId
		   ,MeetingAccountId = @rMeetingAccountId
		   ,IsMeetingCreated = @rIsMeetingCreated
		   ,AssignmentRemark = @rAssignmentRemark
		   ,IsTrackAssignmentView = @rIsTrackAssignmentView
		   ,CoTeacherEmployeeId1 = @rCoTeacherEmployeeId1
		   ,CoTeacherEmployeeId2 = @rCoTeacherEmployeeId2
		   ,AssignmentSubmissionEndDate = @rSubmissionEndDate
		   ,IsRecording = @rIsRecording
	      WHERE Id = @rId
	      
		  IF(@rLearningTypeId = 2)
		  BEGIN
		  IF EXISTS (SELECT 1 FROM sAcademic.tOnlineMeetingSettings WHERE OnlineLearningId = @rId)
		  BEGIN
	      UPDATE sAcademic.tOnlineMeetingSettings
		  SET
			IsOnParticipantVideo = @rIsOnParticipantVideo,
			IsOnParticipantAudio = @rIsOnParticipantAudio,
			IsOnHostVideo = @rIsOnHostVideo,
			IsOnHostAudio = @rIsOnHostAudio,
			IsOnParticipantScreenShare = @rIsOnParticipantScreenShare,
			IsOnHostscreenShare = @rIsOnHostscreenShare,
			AccountEmailId = @lAccountEmailId,
			AccountPassword = @lAccountPassword,
			APIKey = @lAPIKey,
			APISecret = @lAPISecret,
			WebAPIKey = @lWebAPIKey,
			WebAPISecret = @lWebAPISecret,
			MeetingProviderId = @lMeetingProviderId,
			JWTToken = @lJWTToken,
			OAuthAccountId = @lOAuthAccountId,
			OAuthClientId = @lOAuthClientId,
			OAuthClientSecret = @lOAuthClientSecret
		  WHERE OnlineLearningId = @rId
	      END
		  ELSE
		  BEGIN
			INSERT INTO sAcademic.tOnlineMeetingSettings
			(
				OnlineLearningId,
				IsOnParticipantVideo,
				IsOnParticipantAudio,
				IsOnHostVideo,
				IsOnHostAudio,
				IsOnParticipantScreenShare,
				IsOnHostscreenShare,
				AccountEmailId,
				AccountPassword,
				APIKey,
				APISecret,
				WebAPIKey,
				WebAPISecret,
				MeetingProviderId,
				JWTToken,
				OAuthAccountId,
				OAuthClientId,
				OAuthClientSecret
			)
			VALUES
			(
				@rId,
				@rIsOnParticipantVideo,
				@rIsOnParticipantAudio,
				@rIsOnHostVideo ,
				@rIsOnHostAudio ,
				@rIsOnParticipantScreenShare,
				@rIsOnHostscreenShare,
				@lAccountEmailId,
				@lAccountPassword,
				@lAPIKey,
				@lAPISecret,
				@lWebAPIKey,
				@lWebAPISecret,
				@lMeetingProviderId,
				@lJWTToken,
				@lOAuthAccountId,
				@lOAuthClientId,
				@lOAuthClientSecret
			)
		  END
		  END
		  IF EXISTS (SELECT 1 FROM sAcademic.tTempOnlineLearningScope WHERE TempOnlineLearningId = @rTempOnlineLearningId)
		   BEGIN
				IF EXISTS(SELECT 1 FROM sAcademic.tOnlineLearningScope WHERE OnlineLearningId = @rTempOnlineLearningId)
				BEGIN
					DELETE FROM sAcademic.tOnlineLearningScope WHERE OnlineLearningId = @rTempOnlineLearningId
				END
				INSERT INTO sAcademic.tOnlineLearningScope
				SELECT @lNextNumber,SourceTypeId,SourceId
				FROM sAcademic.tTempOnlineLearningScope 
				WHERE TempOnlineLearningId = @rTempOnlineLearningId
		
				DELETE FROM sAcademic.tTempOnlineLearningScope WHERE TempOnlineLearningId = @rTempOnlineLearningId
			--COMMIT TRANSACTION 
			END  
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAdminDetailListGet]
	 @rId BigInt ,
	 @rEmployeeId bigint,
	 @rOrgGroupBatchId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

		SELECT 
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndTime,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			OL.LecturePath AS LecturePath,
			OL.LearningTypeId AS LearningTypeId,
			OL.IsDisplayMeetingId AS IsDisplayMeetingId,
			OL.MeetingId AS MeetingId,
			OL.MeetingPassword AS MeetingPassword,
			OL.IsCompleted AS IsCompleted,
			ISNULL(OL.Title,'') AS Title,
			ISNULL(OL.Description,'')AS Description,
			ISNULL(OL.IsMeetingStarted,'') AS IsMeetingStarted,
			CM.Id AS ClassId,
			OL.IsSubmitAssignment AS IsSubmitAssignment,
			OL.IsTakeTest AS IsTakeTest,
			OL.TestId AS TestId,
			OL.IsTrackAttendance AS IsTrackAttendance,
			OL.IsMeetingCreated AS IsMeetingCreated,
			--OL.MeetingProviderId As MeetingProviderId
			ISNULL(OL.AssignmentRemark,'') As AssignmentRemark,
			OL.SubjectId,
			ISNULL(OL.IsRecording,0) AS IsRecording
			
		FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3

		WHERE
			 OL.Id = @rId
			 AND OL.TeacherEmployeeId = @rEmployeeId
			 
			
			ORDER BY OL.CreatedDateTime
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAdminListGet]
	 
	 @rEmployeeId bigint,
	 @rSourceTypeId int,
	 @rLearningTypeId int = 0,
	 @rClassId int = 0,
	 @rSubjectId int = 0,
	 @rTopicId int = 0,
	 @rStartDate date = '',
	 @rEndDate date = '',
	 @rIsCompleted int=-1,
	 @rTitle nvarchar(100) ='',
	 @rOrgGroupBatchId int,
	 @rBatchId int,
	 @lUserId bigint,
	 @rOrgId bigint

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

	
	SELECT 
			OL.Id,
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS EmployeeName,
			EM.Code AS Code,
			EM.Id AS EmployeeId,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDate,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' 
			      WHEN OL.IsCompleted=1 THEN 'Completed'
				  WHEN OL.IsCompleted=721 THEN 'Cancel'
				  END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			CM.Id AS ClassId,
			(CASE WHEN OL.IsAssignment = 0 THEN 'N' WHEN OL.IsAssignment = NULL THEN '' ELSE 'Y' END) AS IsAssignment,
			(CASE WHEN OL.IsSubmitAssignment = 0 THEN 'N' WHEN OL.IsSubmitAssignment = NULL THEN '' ELSE 'Y' END) AS IsSubmitAssignment
			
			FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId AND CM.OrgId = @rOrgId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			

			WHERE
				((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
				AND ((OL.ClassId = @rClassId ) OR (@rClassId=0))
				AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
				AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
				AND ((OL.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OL.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				AND ((OL.TeacherEmployeeId = @rEmployeeId) OR @rEmployeeId=0)
				--AND ((EM.Id = @rEmployeeId ) OR (@rEmployeeId=0))
				AND ((Convert(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
				AND ((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND (OL.BatchId = @rBatchId)
				--AND CM.OrgId = @rOrgId
				ORDER BY OL.IsCompleted,OL.StartDate,OL.StartTime,OL.EndDate
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAllAttendanceListGet]

	@rOnlineLearningIds nvarchar(max)='' ,
	--@rClassId bigint,
	@rBatchId bigint
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

CREATE TABLE #OnlineLearningIds
  ( 
     Id INT IDENTITY (1, 1), 
     OnlineLearningId bigint
  )
  INSERT INTO #OnlineLearningIds
SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rOnlineLearningIds,',')

--Select * from #OnlineLearningIds
	
	CREATE TABLE #StudentData
	(
	OnlineLearningId bigint,
	Class nvarchar(200),
	Code nvarchar(200),
	RollNo bigint,
	StudentName nvarchar(200),
	IsPresent nvarchar(100),
	InCount int,
	ClassID bigint,
	DivisionId bigint,
	AcademicId bigint,
	IsLoggedIn nvarchar(100),
	FirstInDateTime datetime,
	IsPresentAbsent nvarchar(100),
	StartDateTime nvarchar(200),
	SubjectId bigint,
	LearningTypeId int,
	IsCompleted int,
	IsTrackAttendance bit
	--StartTime nvarchar(200)
	)

	DECLARE @lCountIds int,@Id int,@lOnlineLearningId bigint

	SELECT @lCountIds=COUNT(Id) FROM #OnlineLearningIds
	SELECT Top 1 @Id=Id FROM #OnlineLearningIds
	WHILE @Id <= @lCountIds
	BEGIN
	SELECT @lOnlineLearningId=OnlineLearningId FROM #OnlineLearningIds WHERE Id=@Id
	CREATE TABLE #SourceTypeId
	(
		Id int IDENTITY,
		SourceTypeId bigint
	)

	INSERT INTO #SourceTypeId
	Select Distinct  SourceTypeId from [sAcademic].[tOnlineLearningScope] Where OnlineLearningId=@lOnlineLearningId
	
	DECLARE @lCountSourceTypeId int,@lSourceTypeId int,@lId int

	SELECT @lCountSourceTypeId=COUNT(SourceTypeId) FROM #SourceTypeId
		SELECT Top 1 @lId=Id FROM #SourceTypeId

WHILE @lId <= @lCountSourceTypeId
	BEGIN
	SELECT @lSourceTypeId=SourceTypeId FROM #SourceTypeId WHERE Id=@lId

	--StudnetId
	IF(@lSourceTypeId=2003)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId,
			OL.LearningTypeId,
			OL.IsCompleted,
			OL.IsTrackAttendance
						
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.StudentId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId,OL.LearningTypeId,OL.IsCompleted,OL.IsTrackAttendance
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--AcademicId
	IF(@lSourceTypeId=2001)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId,
			OL.LearningTypeId,
			OL.IsCompleted,
			OL.IsTrackAttendance
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.AcademicId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId,OL.LearningTypeId,OL.IsCompleted,OL.IsTrackAttendance
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--ClassId
	ELSE IF(@lSourceTypeId=2016)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId,
			OL.LearningTypeId,
			OL.IsCompleted,
			OL.IsTrackAttendance
					
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.ClassId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId,OL.LearningTypeId,OL.IsCompleted,OL.IsTrackAttendance
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--DeparmentId
	ELSE IF(@lSourceTypeId=2017)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId,
			OL.LearningTypeId,
			OL.IsCompleted,
			OL.IsTrackAttendance
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.DepartmentId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId,OL.LearningTypeId,OL.IsCompleted,OL.IsTrackAttendance
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--OrgId
	ELSE IF(@lSourceTypeId=2021)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId,
			OL.LearningTypeId,
			OL.IsCompleted,
			OL.IsTrackAttendance
		
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.OrgId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId,OL.LearningTypeId,OL.IsCompleted,OL.IsTrackAttendance
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--Division
	ELSE IF(@lSourceTypeId=2005)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId,
			OL.LearningTypeId,
			OL.IsCompleted,
			OL.IsTrackAttendance
	
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.DivisionId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId 
			AND SA.BatchId = OL.BatchId
			
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId,OL.LearningTypeId,OL.IsCompleted,OL.IsTrackAttendance
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END

	SET @lId=@lId+1
	END
	
	DROP TABLE #SourceTypeId
	SET @Id=@Id+1

	END
	--Select * from #StudentData
	Select ROW_NUMBER() OVER (PARTITION BY SD.AcademicId ,SD.ClassId,CONVERT(Date,SD.StartDateTime,103),SD.SubjectId ORDER BY CONVERT(Varchar,SD.StartDateTime,20) ASC) AS PeriodNo,*
	from #StudentData SD 
	Where SD.LearningTypeId=2
	AND SD.IsCompleted=1 AND SD.IsTrackAttendance=1
	Order By SD.StartDateTime,SD.ClassId ASC
	
	--Select * from #OnlineLearningIds
	
	DROP TABLE #StudentData
	DROP TABLE #OnlineLearningIds
				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAllStudentAttendanceAdd]
	
	@rStrXml nvarchar(MAX),
	@rEmployeeId bigint,
    @rAttendanceTypeId tinyint,
    --@rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rAttendanceGroupId int=0,
    --@rPeriodNo int=0 ,
	@rAbsentReasonId int=0,
	@rAttendanceRemark nvarchar(10)='',
	@rAttendanceTagId int=0,
	@rCreatedUserId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	
	IF EXISTS ( SELECT	
			1			
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				AttendanceDate Date,
				IsPresent bit,
				PeriodNo int,
				SubjectId bigint
				
			  ) A 
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId = A.AcademicId
		AND SR.AttendanceDate = A.AttendanceDate AND SR.SubjectId = A.SubjectId)
		BEGIN
          SELECT -101 AS Result
		END

		ELSE
		BEGIN
		
		INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId,
			PeriodNo,
			AttendanceGroupId,
			AttendanceRemark
			)
		SELECT	
		DISTINCT	
			A.AcademicId,
			@rEmployeeId,
			@rAttendanceTypeId,
		    A.AttendanceDate,
			A.SubjectId,
			A.PeriodNo,
			--ISNULL(@rRepeatCount,0),
			A.IsPresent,
			ISNULL(@rAbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			'',
			'',
			@rAttendanceTagId,
			A.PeriodNo,
			@rAttendanceGroupId,
			@rAttendanceRemark
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				AttendanceDate Date,
				IsPresent bit,
				PeriodNo int,
				SubjectId bigint
				
			  ) A 
		LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId = A.AcademicId
		AND SR.AttendanceDate = A.AttendanceDate AND SR.PeriodNo = A.PeriodNo
		AND SR.SubjectId = A.SubjectId
		WHERE SR.AcademicId IS NULL AND SR.AttendanceDate IS NULL AND SR.PeriodNo IS NULL
		AND SR.SubjectId IS NULL

		Select 1 AS Result
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAllStudentAttendanceDelete]
	

	@rStrXml nvarchar(MAX),
	@rEmployeeId bigint,
    @rAttendanceTypeId tinyint,
    --@rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rAttendanceGroupId int=0,
    --@rPeriodNo int=0 ,
	@rAbsentReasonId int=0,
	@rAttendanceRemark nvarchar(10)='',
	@rAttendanceTagId int=0,
	@rCreatedUserId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SET @rStrXml=REPLACE(@rStrXml,'&','AND')
	DECLARE @loDoc INT

	BEGIN TRY
	
	 BEGIN TRANSACTION

	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

	IF EXISTS ( SELECT	
		DISTINCT	
			AcademicId,
			@rEmployeeId,
			@rAttendanceTypeId,
		    AttendanceDate,
			SubjectId,
			ISNULL(@rRepeatCount,0),
			IsPresent,
			ISNULL(@rAbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			'',
			'',
			@rAttendanceTagId,
			PeriodNo,
			@rAttendanceGroupId,
			@rAttendanceRemark
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				AttendanceDate Date,
				IsPresent bit,
				PeriodNo int,
				SubjectId bigint
				
			  ) A 
		WHERE EXISTS (
        SELECT AcademicId,PeriodNo,SubjectId
        FROM sAttendance.tStudentRegister 
        WHERE AcademicId = A.AcademicId AND AttendanceDate=A.AttendanceDate 
		--AND PeriodNo=A.PeriodNo 
		AND SubjectId=A.SubjectId
        ))
		BEGIN
	
	Delete sAttendance.tStudentRegister  From sAttendance.tStudentRegister  SR 
	--Select * FROM  sAttendance.tStudentRegister  SR 
    INNER JOIN 
	 (SELECT	
			
			AcademicId,
		    AttendanceDate,
			SubjectId,
			IsPresent,
			PeriodNo
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				AttendanceDate Date,
				IsPresent bit,
				PeriodNo int,
				SubjectId bigint
				
			  )) A  ON
		 SR.AcademicId = A.AcademicId AND SR.AttendanceDate=A.AttendanceDate 
		 --AND SR.PeriodNo=A.PeriodNo 
		 AND SR.SubjectId=A.SubjectId
		
          SELECT 1 AS Result
		 
		  --EXEC sp_xml_preparedocument @loDoc

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

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAssignmentAdd]
	 
        @rOnlineLearningId bigint,
		@rAssignmentPath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	INSERT INTO sAcademic.tOnlineLearningAssignment
		(
			OnlineLearningId,
			AssignmentPath
		)
	VALUES
		(
			 @rOnlineLearningId,
			 @rAssignmentPath
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAssignmentStudentCountGet]
	
	@rOnlineLearningId bigint 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT
		ISNULL(COUNT(A.AcademicId),0) as Total,
		ISNULL(COUNT(OLAS.AcademicId),0) as Uploaded,
		ISNULL(COUNT(A.AcademicId) - COUNT(OLAS.AcademicId),0) as Remaining
	FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN (
				SELECT 
					OL.Id as OnlineLearningId,
					SD.AcademicId,
					SD.Name,
					SD.Code,
					SD.ParentContactNo,	
					SD.ParentEmail,
					SD.OrgId
				FROM 
					sAcademic.tOnlineLearningScope OLS 
					INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				WHERE 
					OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2003

				UNION ALL

				SELECT 
					OL.Id as OnlineLearningId,
					SD.AcademicId,
					SD.Name,
					SD.Code,
					SD.ParentContactNo,	
					SD.ParentEmail,
					SD.OrgId
				FROM 
					sAcademic.tOnlineLearningScope OLS 
					INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				WHERE 
					OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2001

				UNION ALL	
																			 			  
				SELECT 
					OL.Id as OnlineLearningId,
					SD.AcademicId,
					SD.Name,
					SD.Code,
					SD.ParentContactNo,	
					SD.ParentEmail,
					SD.OrgId
				FROM 
					sAcademic.tOnlineLearningScope OLS 
					INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				 
				WHERE 
					OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND  OLS.SourceTypeId = 2017

				UNION ALL		
															 			 				  
				SELECT 
					OL.Id as OnlineLearningId,
					SD.AcademicId,
					SD.Name,
					SD.Code,
					SD.ParentContactNo,	
					SD.ParentEmail,
					SD.OrgId
				FROM 
					sAcademic.tOnlineLearningScope OLS 
					INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OLS.SourceId AND SD.BatchId = OL.BatchId  
				WHERE 
					OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2016

				UNION ALL	
																 			 				  
				SELECT 
					OL.Id as OnlineLearningId,
					SD.AcademicId,
					SD.Name,
					SD.Code,
					SD.ParentContactNo,	
					SD.ParentEmail,
					SD.OrgId
				FROM 
					sAcademic.tOnlineLearningScope OLS 
					INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				WHERE 
					OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2005

				UNION ALL		
															 			 				  
				SELECT 
					OL.Id as OnlineLearningId,
					SD.AcademicId,
					SD.Name,
					SD.Code,
					SD.ParentContactNo,	
					SD.ParentEmail,
					SD.OrgId
				FROM 
					sAcademic.tOnlineLearningScope OLS 
					INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
					INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				WHERE 
					OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2021
			
			) as A ON A.OnlineLearningId = OL.Id 
			 LEFT JOIN (SELECT DISTINCT AcademicId FROM sAcademic.tOnlineLearningAssignmentSubmit WHERE OnlineLearningId = @rOnlineLearningId
			 )OLAS ON  OLAS.AcademicId = A.AcademicId 
		WHERE
			OL.Id = @rOnlineLearningId   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAssignmentSubmitAdd]
	 
        @rOnlineLearningId bigint,
		@rAcademicId bigint,
		@rAssignmentPath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF NOT EXISTS(Select * from sAcademic.tOnlineLearningAssignmentSubmit Where OnlineLearningId=@rOnlineLearningId AND AcademicId= @rAcademicId AND AssignmentPath=@rAssignmentPath AND DeletedUser is null)
BEGIN
	INSERT INTO sAcademic.tOnlineLearningAssignmentSubmit
		(
			OnlineLearningId,
			AcademicId,
			AssignmentPath
		)
	VALUES
		(
			 @rOnlineLearningId,
			 @rAcademicId,
			 @rAssignmentPath
		)
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAssignmentViewAdd]
	 @rOnlineLearningId bigint ,
	 @rSourceId bigint,
	 @rIsViewReference bit = 0,
	 @rIsViewResource bit = 0,
	 @rIsViewAssignment bit = 0,
	 @rUserId bigint
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	   IF NOT EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningView WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
		BEGIN
			INSERT  INTO sAcademic.tOnlineLearningView 
			(OnlineLearningId,AcademicId,IsViewReference,IsViewResource,IsViewAssignment,ViewByUserId,LastViewByDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rIsViewReference,@rIsViewResource,@rIsViewAssignment,@rUserId,GetDate())

			SELECT 1 AS Result	
		END
	  ELSE IF(@rIsViewReference = 1)
	    BEGIN	
			UPDATE sAcademic.tOnlineLearningView 
			SET
			IsViewReference = @rIsViewReference,
			LastViewByDateTime = GetDate()
			WHERE
			OnlineLearningId = @rOnlineLearningId

			SELECT 1 AS Result	
		END
	  ELSE IF(@rIsViewResource = 1)
		BEGIN
			UPDATE sAcademic.tOnlineLearningView 
			SET
			IsViewResource = @rIsViewResource,
			LastViewByDateTime = GetDate()
			WHERE
			OnlineLearningId = @rOnlineLearningId

			SELECT 1 AS Result	
		END
	  ELSE IF(@rIsViewAssignment = 1)
		BEGIN
			UPDATE sAcademic.tOnlineLearningView 
			SET
			IsViewAssignment = @rIsViewAssignment,
			LastViewByDateTime = GetDate()
			WHERE
			OnlineLearningId = @rOnlineLearningId

			SELECT 1 AS Result	
		END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAssignmentViewListGet]
	@rOnlineLearningId bigint,
	@rIsHistory bit = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF(@rIsHistory = 1)
BEGIN
		 SELECT * FROM 
		(
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2003

			UNION ALL

			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2001

			UNION ALL	
																			 			  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND  OLS.SourceTypeId = 2017

			UNION ALL		
															 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark 
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2021
			
		) as A
		Order BY A.DivisionOrder
	END
	ELSE
	BEGIN
		SELECT * FROM 
		(
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2003

			UNION ALL

			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2001

			UNION ALL	
																			 			  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND  OLS.SourceTypeId = 2017

			UNION ALL		
															 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark 
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2021
			
		) as A
		Order BY A.DivisionOrder
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAssignmentViewUpdate]
	 @rOnlineLearningId bigint ,
	 @rSourceId bigint,
	 @rIsViewReference bit = 0,
	 @rIsViewResource bit = 0,
	 @rIsViewAssignment bit = 0,
	 @rUserId bigint ,
	 @rAssignmentTeacherRemark nvarchar(1000)
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	   IF NOT EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningView WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
		BEGIN
			INSERT  INTO sAcademic.tOnlineLearningView 
			(OnlineLearningId,AcademicId,IsViewReference,IsViewResource,IsViewAssignment,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rIsViewReference,@rIsViewResource,@rIsViewAssignment,@rUserId,GetDate(),@rAssignmentTeacherRemark)

			SELECT 1 AS Result	
		END
	  ELSE 
	    BEGIN	
			UPDATE sAcademic.tOnlineLearningView SET AssignmentTeacherRemark = @rAssignmentTeacherRemark
			WHERE OnlineLearningId = @rOnlineLearningId
			AND AcademicId = @rSourceId

			SELECT @rSourceId AS Result	
		END
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAttendanceAdd]
	 @rOnlineLearningId bigint ,
	 @rSourceId bigint,
	 @rAttendanceTypeId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	 
	 IF(@rAttendanceTypeId= 1) 
	   BEGIN
	   IF NOT EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningAttendance WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
			BEGIN
			INSERT  INTO sAcademic.tOnlineLearningAttendance 
			(OnlineLearningId,AcademicId, IsPresent ,FirstInDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,1,GetDate())
			END
			
			INSERT  INTO sAcademic.tOnlineLearningAttendanceLog 
			(OnlineLearningId,AcademicId,ActivityId,CreatedDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rAttendanceTypeId,GetDate())
		SELECT 1 AS Result	
		END
		
		ELSE IF (@rAttendanceTypeId= 2)
		BEGIN
		IF EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningAttendance WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
			BEGIN
			UPDATE  sAcademic.tOnlineLearningAttendance 
			SET LastOutDateTime = GetDate()
			Where AcademicId= @rSourceId AND OnlineLearningId= @rOnlineLearningId
			
			INSERT  INTO sAcademic.tOnlineLearningAttendanceLog 
			(OnlineLearningId,AcademicId,ActivityId,CreatedDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rAttendanceTypeId,GetDate())
			SELECT 1 AS Result
			END
			
		ELSE 
		SELECT -1 AS Result
	
END
			
				
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningAttendanceListGet]
	@rOnlineLearningId bigint ,
	@rClassId bigint,
	@rBatchId bigint
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	CREATE TABLE #SourceTypeId
	(
		Id int IDENTITY,
		SourceTypeId bigint
	)
	CREATE TABLE #StudentData
	(
	Class nvarchar(200),
	Code nvarchar(200),
	RollNo bigint,
	StudentName nvarchar(200),
	IsPresent nvarchar(100),
	InCount int,
	ClassID bigint,
	DivisionId bigint,
	AcademicId bigint,
	IsLoggedIn nvarchar(100),
	FirstInDateTime datetime,
	IsPresentAbsent nvarchar(100)
	)
--Declare @lSourceTypeId int

	INSERT INTO #SourceTypeId
	Select Distinct  SourceTypeId from [sAcademic].[tOnlineLearningScope] Where OnlineLearningId=@rOnlineLearningId
	--Select * from #SourceTypeId

	--SELECT * FROM #SourceTypeId
DECLARE @lCountSourceTypeId int,@lSourceTypeId int,@lId int

SELECT @lCountSourceTypeId=COUNT(SourceTypeId) FROM #SourceTypeId
	SELECT Top 1 @lId=Id FROM #SourceTypeId

	--SELECT @lCountSourceTypeId,@lCountSourceTypeId

	WHILE @lId <= @lCountSourceTypeId
			BEGIN
			SELECT @lSourceTypeId=SourceTypeId FROM #SourceTypeId WHERE Id=@lId

	--StudnetId
	IF(@lSourceTypeId=2003)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.StudentId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--AcademicId
	IF(@lSourceTypeId=2001)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.AcademicId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--ClassId
	ELSE IF(@lSourceTypeId=2016)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.ClassId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--DeparmentId
	ELSE IF(@lSourceTypeId=2017)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.DepartmentId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--OrgId
	ELSE IF(@lSourceTypeId=2021)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.OrgId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--Division
	ELSE IF(@lSourceTypeId=2005)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.DivisionId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId 
			AND SA.BatchId = OL.BatchId
			
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END

	SET @lId=@lId+1
	END
	Select * from #StudentData
	DROP TABLE #SourceTypeId
	DROP TABLE #StudentData
				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sAcademic.tOnlineLearningAssignment where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineLearningAssignmentSubmit where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineLearningResource where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineLearningReference where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineLearningAttendance where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineLearningAttendanceLog where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineLearningScope where OnlineLearningId=@rId
			Delete from sAcademic.tOnlineMeetingSettings Where OnlineLearningId = @rId
			Delete from sAcademic.tOnlineLearning where Id=@rId
		COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION		
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 -- exec [sAcademic].[pOnlineLearningGet] 1101000000438,'','','',0,0,0,0,0,-1,110100110
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rClassId int = 0,
	 @rSubjectId int = 0,
	 @rTopicId int = 0,
	 @rEmployeeId bigint = 0,
	 @rLearningTypeId int = 0,
	 @rIsCompleted int = -1,
	 @rBatchId int,
	 @rType int = 0,
	 @rUserId bigint = 0,
	 @rOnlineMeetingAccountId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
if(@rType = 0)
BEGIN
	if(@rId = 0)
	BEGIN 
	
	SELECT
			OL.Id,
			SM.Title as Subject,
			ISNULL(CM.DisplayTitle,'') as Class,
			ISNULL(TM.Title,'') as Topic,
			--EM.FirstName +' ' +EM.LastName as Teacher,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Teacher,
			DM.Title as LearningType,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDateTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDateTime,
			OL.IsCompleted as Status,
		    ISNULL(OL.Title,'') as Title,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as Source ,
			  OL.StartDateTime AS TeacherStartDateTime,
			  OL.EndDateTime AS TeacherEndDateTime,
			  (SELECT ISNULL(ISNULL(FirstName, ' ') + ' ' + ISNULL(LastName, ' '), ' ') FROM sHrm.tEmployeeMaster WHERE Id = OL.CoTeacherEmployeeId1) AS CoTeacherEmployee1,
			  (SELECT ISNULL(ISNULL(FirstName, ' ') + ' ' + ISNULL(LastName, ' '), ' ') FROM sHrm.tEmployeeMaster WHERE Id = OL.CoTeacherEmployeeId2) AS CoTeacherEmployee2,
			  OL.CoTeacherEmployee1StartDateTime,
			  OL.CoTeacherEmployee1EndDateTime,
			  OL.CoTeacherEmployee2StartDateTime,
			  OL.CoTeacherEmployee2EndDateTime
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN (SELECT DISTINCT OM.Id FROM sSetup.vUserOrganization OM 
			WHERE ((OM.UserId = @rUserId) OR (@rUserId = 0)) ) A ON A.Id = EM.OrgID
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
 	  WHERE 
				((OL.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
			AND ((OL.TeacherEmployeeId = @rEmployeeId) OR (@rEmployeeId = -1))
			AND ((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
			AND ((CONVERT(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
			AND (OL.BatchId = @rBatchId)
			AND ((OL.MeetingAccountId = @rOnlineMeetingAccountId) OR (@rOnlineMeetingAccountId = 0))
	 ORDER BY
			OL.StartDate , OL.StartTime asc
		
	END
	ELSE
	BEGIN
		SELECT 
			OL.Id,
			SM.Title as Subject,
			SM.Id as SubjectId,
			ISNULL(CM.Title,'') as Class,
			ISNULL(CM.Id,0) as ClassId,
			ISNULL(TM.Title,'') as Topic,
			ISNULL(TM.Id,0) as TopicId,
			EM.FirstName +' '+ EM.LastName as Teacher,
			Em.Id as TeacherId,
			DM.Title as LearningType,
			DM.Id as LearningTypeId,
			CONVERT(NVARCHAR,OL.StartDate) as StartDate,
			CONVERT(NVARCHAR,OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate) as EndDate,
			CONVERT(NVARCHAR,OL.EndTime,108) as EndTime,
			OL.IsCompleted as Status,
			OL.LecturePath,
			OL.Title as LearningTitle,
			OL.Description,
			OL.IsDisplayMeetingId,
			OL.MeetingId,
			OL.MeetingPassword,
			ISNULL(OL.IsTrackAttendance,0) as IsTrackAttendance,
			ISNULL(OL.IsAssignment,0) as IsAssignment,
			ISNULL(OL.IsSubmitAssignment,0) as IsSubmitAssignment,
			ISNULL(OL.IsTakeTest,0) as IsTakeTest,
			ISNULL(OL.IsReference,0) as IsReference,
			ISNULL(OL.IsResource,0) as IsResource,
			ISNULL(OL.IsCompleted,0) as IsCompleted,
			ISNULL(OL.IsMeetingStarted,0) as IsMeetingStarted,
			ISNULL(TestM.Id,0) AS TestId,
			ISNULL(TestM.Title,'')AS Test,
			ISNULL(OMS.IsOnParticipantVideo,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) AS IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) AS IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) AS IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) AS IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) AS IsOnHostscreenShare,
			ISNULL(OL.MeetingAccountId,0) AS MeetingAccountId,
			ISNULL(OL.IsMeetingCreated,0) AS IsMeetingCreated,
			ISNULL(OL.AssignmentRemark,'') AS AssignmentRemark,
			ISNULL(OL.IsTrackAssignmentView,0) as IsTrackAssignmentView,
			ISNULL(OL.CoTeacherEmployeeId1,0) as CoTeacherEmployeeId1,
			ISNULL(OL.CoTeacherEmployeeId2,0) as CoTeacherEmployeeId2,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE  EmployeeId = ISNULL(OL.CoTeacherEmployeeId1,0)) AS CoTeacherEmployee1,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE EmployeeId = ISNULL(OL.CoTeacherEmployeeId2,0)) AS CoTeacherEmployee2,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.StartDateTime AS TeacherStartDateTime,
			OL.EndDateTime AS TeacherEndDateTime,
			ISNULL(OL.IsRecording,0) AS IsRecording,
			BM.Id AS BatchId,
			BM.Title AS BatchName,
			OM.Id AS OrgId,
			OM.Title AS OrganizationName
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEExam.tTestMaster TestM ON OL.ClassId=TestM.ClassId AND OL.TestId=TestM.Id
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id 
			INNER JOIN sSetup.tBatchMaster BM ON OL.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON BM.OrgId=OM.Id
	  WHERE 
			(OL.Id = @rId) AND (OL.BatchId = @rBatchId)
	  ORDER BY
			OL.StartDate , OL.StartTime asc
	END
END
ELSE IF(@rType = 1)
BEGIN
		if(@rId = 0)
	BEGIN 
	
	SELECT 
			OL.Id,
			SM.Title as Subject,
			ISNULL(CM.DisplayTitle,'') as Class,
			ISNULL(TM.Title,'') as Topic,
			EM.FirstName +' '+ EM.LastName as Teacher,
			DM.Title as LearningType,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDateTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDateTime,
			OL.IsCompleted as Status,
		    ISNULL(OL.Title,'') as Title,
			OL.StartDateTime AS TeacherStartDateTime,
			OL.EndDateTime AS TeacherEndDateTime
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
	  WHERE 
  
				((OL.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
			AND ((OL.TeacherEmployeeId = @rEmployeeId) OR (@rEmployeeId = -1))
			AND ((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
			AND ((CONVERT(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
			AND (OL.BatchId = @rBatchId)
			AND OL.IsCompleted <> 721			
	 ORDER BY
			
			OL.StartDate , OL.StartTime asc
		
	END
	ELSE
	BEGIN
		SELECT 
			OL.Id,
			SM.Title as Subject,
			SM.Id as SubjectId,
			ISNULL(CM.Title,'') as Class,
			ISNULL(CM.Id,0) as ClassId,
			ISNULL(TM.Title,'') as Topic,
			ISNULL(TM.Id,0) as TopicId,
			EM.EmployeeName as Teacher,
			Em.EmployeeId as TeacherId,
			DM.Title as LearningType,
			DM.Id as LearningTypeId,
			CONVERT(NVARCHAR,OL.StartDate) as StartDate,
			CONVERT(NVARCHAR,OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate) as EndDate,
			CONVERT(NVARCHAR,OL.EndTime,108) as EndTime,
			OL.IsCompleted as Status,
			OL.LecturePath,
			OL.Title as LearningTitle,
			OL.Description,
			OL.IsDisplayMeetingId,
			OL.MeetingId,
			OL.MeetingPassword,
			ISNULL(OL.IsTrackAttendance,0) as IsTrackAttendance,
			ISNULL(OL.IsAssignment,0) as IsAssignment,
			ISNULL(OL.IsSubmitAssignment,0) as IsSubmitAssignment,
			ISNULL(OL.IsTakeTest,0) as IsTakeTest,
			ISNULL(OL.IsReference,0) as IsReference,
			ISNULL(OL.IsResource,0) as IsResource,
			ISNULL(OL.IsCompleted,0) as IsCompleted,
			ISNULL(OL.IsMeetingStarted,0) as IsMeetingStarted,
			ISNULL(TestM.Id,0) AS TestId,
			ISNULL(TestM.Title,'')AS Test,
			ISNULL(OMS.IsOnParticipantVideo,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) AS IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) AS IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) AS IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) AS IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) AS IsOnHostscreenShare,
			ISNULL(OL.MeetingAccountId,0) AS MeetingAccountId,
			ISNULL(OL.IsMeetingCreated,0) AS IsMeetingCreated,
			ISNULL(OL.AssignmentRemark,'') AS AssignmentRemark,
			ISNULL(OL.IsTrackAssignmentView,0) as IsTrackAssignmentView,
			ISNULL(OL.CoTeacherEmployeeId1,0) as CoTeacherEmployeeId1,
			ISNULL(OL.CoTeacherEmployeeId2,0) as CoTeacherEmployeeId2,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE  EmployeeId = ISNULL(OL.CoTeacherEmployeeId1,0)) AS CoTeacherEmployee1,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE EmployeeId = ISNULL(OL.CoTeacherEmployeeId2,0)) AS CoTeacherEmployee2,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.StartDateTime AS TeacherStartDateTime,
			OL.EndDateTime AS TeacherEndDateTime,
			ISNULL(OL.IsRecording,0) AS IsRecording,
			BM.Id AS BatchId,
			BM.Title AS BatchName,
			OM.Id AS OrgId,
			OM.Title AS OrganizationName
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEExam.tTestMaster TestM ON OL.ClassId=TestM.ClassId AND OL.TestId=TestM.Id
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id 
			INNER JOIN sSetup.tBatchMaster BM ON OL.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON BM.OrgId=OM.Id
	  WHERE 
			(OL.Id = @rId) AND (OL.BatchId = @rBatchId) AND OL.IsCompleted <> 721
	  ORDER BY
			OL.StartDate , OL.StartTime asc
	END
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningHistoryAdd]
	@rFromDate DATE,
	@rToDate DATE,
	@rCreatedUserId Bigint,
	@rBatchId Bigint,
	@rStatus NVARCHAR(30)

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

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

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

	--insert into [sAcademic].[tOnlineLearningAttendance]

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

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

	--insert into [sAcademic].[tOnlineLearningRecording]

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

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

	--insert into [sAcademic].[tOnlineLearningAssignmentSubmitHistory]

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


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

	--insert into [sAcademic].[tOnlineLearningAssignmentHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningReferenceHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningResourceHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningViewHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningScopeHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningHistory]

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

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

	SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningHistoryLogGet]
	@rFromDate DATE,
	@rToDate DATE,
	@rBatchId Bigint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 SELECT 
		OM.Title AS Organization,
		BM.Title AS Batch,
		OLH.FromDate,
		OLH.ToDate,
		OLH.Status
	 FROM 
		sAcademic.tOnlineLearningHistoryLog OLH
		INNER JOIN sSetup.tBatchMaster BM ON OLH.BatchId = BM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON BM.OrgId = OM.Id
	 WHERE 
		OLH.BatchId = @rBatchId
		AND	convert(date,OLH.CreatedDateTime)>=convert(date,@rFromDate) 
		AND convert(date,OLH.CreatedDateTime)<=convert(date,@rToDate) 
	 Order BY AutoId Desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningHistoryRevert]
	@rFromDate DATE,
	@rToDate DATE,
	@rCreatedUserId Bigint,
	@rBatchId Bigint,
	@rStatus NVARCHAR(30)

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

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

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

	--insert into [sAcademic].[tOnlineLearningAttendance]

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

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

	--insert into [sAcademic].[tOnlineLearningRecording]

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

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

	--insert into [sAcademic].[tOnlineLearningAssignmentSubmitHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningAssignmentHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningReferenceHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningResourceHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningViewHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningScopeHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningHistory]

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

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

	SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningMigrateToHistoryAdd]
	@rFromDate DATE

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

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

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

	--insert into [sAcademic].[tOnlineLearningAttendance]

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

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

	--insert into [sAcademic].[tOnlineLearningRecording]

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

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

	--insert into [sAcademic].[tOnlineLearningAssignmentSubmitHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningAssignmentHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningReferenceHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningResourceHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningViewHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningScopeHistory]

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

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

	--insert into [sAcademic].[tOnlineLearningHistory]

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

	DELETE FROM sAcademic.tOnlineLearning
	WHERE convert(date,CreatedDateTime)<=convert(date,@rFromDate) 
	 
	SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningMobilelectureAdd]
	 
        @rId bigint = 0,
		@rLearningTypeId int,
		@rClassId int = 0,
        @rSubjectId int,
		@rTopicId int = 0,
		@rTeacherId bigint,
		@rStartDate date,
		@rEndDate date,
		@rStartTime datetime,
		@rEndTime datetime,
		@rTitle nvarchar(100) = '',
		@rDescription nvarchar(max) = '',
		@rLecturePath nvarchar(max) = '',
		@rIsDisplayMeetingId bit =0,
		@rMeetingId nvarchar(50) = '',
		@rMeetingPass nvarchar(50) = '',
		@rIsTrackAttendance bit =0,
		@rIsAssignment bit=0,
		@rIsResource bit=0,
		@rIsRefrence bit=0,
		@rIsCompleted bit = 0,
		@rIsMeetingStarted bit = 0,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int,
		--@rTempOnlineLearningId nvarchar(100) = 0,
		@rIsSubmitAssignment bit=0,
		@rIsTakeTest bit=0,
		@rTestId int=0,
		@rIsOnParticipantVideo bit=0,
		@rIsOnParticipantAudio bit=0,
		@rIsOnHostVideo bit=0,
		@rIsOnHostAudio bit=0,
		@rIsOnParticipantScreenShare bit=0,
		@rIsOnHostscreenShare bit=0,
		@rMeetingAccountId int = 0,
		@rReferenceId bigint = 0,
		@rIsMeetingCreated bit=0,
		@rAssignmentRemark nvarchar(500) = '',
		@rIsTrackAssignmentView bit = 0,
		@rCoTeacherEmployeeId1 bigint =0,
		@rCoTeacherEmployeeId2 bigint =0,
		--@rAssignToXML nvarchar(Max) = ''
		@rSubmissionEndDate DateTime = '',
		@rIsRecording bit = 0
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	 DECLARE @lAccountEmailId NVARCHAR(200),@lAccountPassword NVARCHAR(200),@lAPIKey NVARCHAR(100),@lAPISecret NVARCHAR(100),@lWebAPIKey NVARCHAR(100),
	         @lWebAPISecret NVARCHAR(100),@lMeetingProviderId NVARCHAR(100),@lJWTToken NVARCHAR(MAX),@lOAuthAccountId NVARCHAR(MAX) ,@lOAuthClientId NVARCHAR(MAX),@lOAuthClientSecret NVARCHAR(MAX)

	SELECT @lAccountEmailId = AccountEmailId,@lAccountPassword = AccountPassword,@lAPIKey = APIKey,@lAPISecret = APISecret,@lWebAPIKey = WebAPIKey,@lWebAPISecret = WebAPISecret,@lMeetingProviderId = MeetingProviderId
	,@lJWTToken = JWTToken , @lOAuthAccountId = OAuthAccountId , @lOAuthClientId = OAuthClientId, @lOAuthClientSecret = OAuthClientSecret
	    FROM sAcademic.tOnlineMeetingAccount
		WHERE Id = @rMeetingAccountId



	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tOnlineLearning', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	
	INSERT INTO sAcademic.tOnlineLearning
		(
			Id
           ,BatchId
           ,StartDate
           ,StartTime
           ,EndDate
           ,EndTime
           ,ClassId
           ,SubjectId
           ,TeacherEmployeeId
           ,Title
           ,Description
           ,LearningTypeId
           ,IsTrackAttendance
           ,TopicId
           ,LecturePath
           ,IsDisplayMeetingId
           ,MeetingId
           ,MeetingPassword
           ,IsAssignment
           ,IsReference
           ,IsResource
           ,IsCompleted
           ,IsMeetingStarted
           ,CreatedUserId
           ,CreatedDateTime
		   ,IsSubmitAssignment
		   ,IsTakeTest
		   ,TestId
		   ,MeetingAccountId
		   ,IsMeetingCreated
		   ,AssignmentRemark
		   ,IsTrackAssignmentView
		   ,CoTeacherEmployeeId1
		   ,CoTeacherEmployeeId2
		   ,AssignmentSubmissionEndDate
		   ,IsRecording
		)
	VALUES
		(
			@lNextNumber,
			@rBatchId,
			@rStartDate,
			@rStartTime,
			@rEndDate, 
			@rEndTime,
			@rClassId,
			@rSubjectId,
			@rTeacherId,
			@rTitle,
			@rDescription,
			@rLearningTypeId,
			@rIsTrackAttendance,
			@rTopicId,
			@rLecturePath,
			@rIsDisplayMeetingId,
			@rMeetingId,
			@rMeetingPass,
			@rIsAssignment,
			@rIsRefrence,
			@rIsResource,
			@rIsCompleted,
			@rIsMeetingStarted,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsSubmitAssignment,
			@rIsTakeTest,
			@rTestId,
			@rMeetingAccountId,
			@rIsMeetingCreated,
			@rAssignmentRemark,
			@rIsTrackAssignmentView,
			@rCoTeacherEmployeeId1,
			@rCoTeacherEmployeeId2,
			@rSubmissionEndDate,
			@rIsRecording
		)
		    
		IF(@rLearningTypeId = 2)
		BEGIN
		INSERT INTO sAcademic.tOnlineMeetingSettings
		(
			OnlineLearningId,
			IsOnParticipantVideo,
			IsOnParticipantAudio,
			IsOnHostVideo,
			IsOnHostAudio,
			IsOnParticipantScreenShare,
			IsOnHostscreenShare,
			AccountEmailId,
			AccountPassword,
			APIKey,
			APISecret,
			WebAPIKey,
			WebAPISecret,
			MeetingProviderId,
			JWTToken,
			OAuthAccountId,
			OAuthClientId,
			OAuthClientSecret
		)
		VALUES
		(
			@lNextNumber,
			@rIsOnParticipantVideo,
			@rIsOnParticipantAudio,
			@rIsOnHostVideo ,
			@rIsOnHostAudio ,
			@rIsOnParticipantScreenShare,
			@rIsOnHostscreenShare,
			@lAccountEmailId,
			@lAccountPassword,
			@lAPIKey,
			@lAPISecret,
			@lWebAPIKey,
			@lWebAPISecret,
			@lMeetingProviderId,
			@lJWTToken,
			@lOAuthAccountId,
			@lOAuthClientId,
			@lOAuthClientSecret
		)
		END
		
		--COMMIT TRANSACTION 
		SELECT @lNextNumber AS Result   
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAcademic.tOnlineLearning
	    SET
			 
           StartDate = @rStartDate
           ,StartTime = @rStartTime
           ,EndDate = @rEndDate
           ,EndTime = @rEndTime
           ,ClassId = @rClassId
           ,SubjectId = @rSubjectId
           ,TeacherEmployeeId = @rTeacherId
           ,Title = @rTitle
           ,Description = @rDescription
           ,LearningTypeId = @rLearningTypeId
           ,IsTrackAttendance = @rIsTrackAttendance
           ,TopicId = @rTopicId
           ,LecturePath = @rLecturePath
           ,IsDisplayMeetingId = @rIsDisplayMeetingId
           ,MeetingId = @rMeetingId
           ,MeetingPassword = @rMeetingPass
           ,IsAssignment = @rIsAssignment
           ,IsReference = @rIsRefrence
           ,IsResource = @rIsResource
           ,IsCompleted = @rIsCompleted
		   ,UpdatedUserId=@rCreatedUserId
		   ,UpdatedDateTime=sCommon.fGetDate()
		   ,IsSubmitAssignment=@rIsSubmitAssignment
		   ,IsTakeTest=@rIsTakeTest
		   ,TestId=@rTestId
		   ,MeetingAccountId = @rMeetingAccountId
		   ,IsMeetingCreated = @rIsMeetingCreated
		   ,AssignmentRemark = @rAssignmentRemark
		   ,IsTrackAssignmentView = @rIsTrackAssignmentView
		   ,CoTeacherEmployeeId1 = @rCoTeacherEmployeeId1
		   ,CoTeacherEmployeeId2 = @rCoTeacherEmployeeId2
		   ,AssignmentSubmissionEndDate = @rSubmissionEndDate
		   ,IsRecording = @rIsRecording
	      WHERE Id = @rId
	      
		  IF(@rLearningTypeId = 2)
		  BEGIN
		  IF EXISTS (SELECT 1 FROM sAcademic.tOnlineMeetingSettings WHERE OnlineLearningId = @rId)
		  BEGIN
	      UPDATE sAcademic.tOnlineMeetingSettings
		  SET
			IsOnParticipantVideo = @rIsOnParticipantVideo,
			IsOnParticipantAudio = @rIsOnParticipantAudio,
			IsOnHostVideo = @rIsOnHostVideo,
			IsOnHostAudio = @rIsOnHostAudio,
			IsOnParticipantScreenShare = @rIsOnParticipantScreenShare,
			IsOnHostscreenShare = @rIsOnHostscreenShare,
			AccountEmailId = @lAccountEmailId,
			AccountPassword = @lAccountPassword,
			APIKey = @lAPIKey,
			APISecret = @lAPISecret,
			WebAPIKey = @lWebAPIKey,
			WebAPISecret = @lWebAPISecret,
			MeetingProviderId = @lMeetingProviderId,
			JWTToken = @lJWTToken,
			OAuthAccountId = @lOAuthAccountId,
			OAuthClientId = @lOAuthClientId,
			OAuthClientSecret = @lOAuthClientSecret
		  WHERE OnlineLearningId = @rId
	      END
		  ELSE
		  BEGIN
			INSERT INTO sAcademic.tOnlineMeetingSettings
			(
				OnlineLearningId,
				IsOnParticipantVideo,
				IsOnParticipantAudio,
				IsOnHostVideo,
				IsOnHostAudio,
				IsOnParticipantScreenShare,
				IsOnHostscreenShare,
				AccountEmailId,
				AccountPassword,
				APIKey,
				APISecret,
				WebAPIKey,
				WebAPISecret,
				MeetingProviderId,
				JWTToken,
				OAuthAccountId,
				OAuthClientId,
				OAuthClientSecret
			)
			VALUES
			(
				@rId,
				@rIsOnParticipantVideo,
				@rIsOnParticipantAudio,
				@rIsOnHostVideo ,
				@rIsOnHostAudio ,
				@rIsOnParticipantScreenShare,
				@rIsOnHostscreenShare,
				@lAccountEmailId,
				@lAccountPassword,
				@lAPIKey,
				@lAPISecret,
				@lWebAPIKey,
				@lWebAPISecret,
				@lMeetingProviderId,
				@lJWTToken,
				@lOAuthAccountId,
				@lOAuthClientId,
				@lOAuthClientSecret
			)
		  END
		  END

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningMobileScopeAdd]
	 
        @rId bigint = 0,		
		@rAssignToXML nvarchar(Max) = ''
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	


 
--	BEGIN
		DECLARE @rSourceId bigint
		DECLARE @rSourceTypeId int
		DECLARE @StrXML XML  
		SET @StrXML = CAST(@rAssignToXML AS XML)  
   
		DECLARE @tOnlineLearningScope TABLE  
		(  
		Id Int IDENTITY(1, 1),  
		SourceId BIGINT,  
		SourceTypeId  INT		
		)   
		INSERT INTO @tOnlineLearningScope  
		SELECT           
              
				T.c.value('@SourceId','bigint') AS SourceId,  
				T.c.value('@SourceTypeId','int') AS [SourceTypeId]             
		FROM   
				@StrXML.nodes('/Table/AssignToDetails')T(c) 
			
		DECLARE @count int=1 ;

		--Delete Existing Data
		Delete From sAcademic.tOnlineLearningScope where OnlineLearningId = @rId

		WHILE(@count <= (select count(*) from @tOnlineLearningScope)) 		
			BEGIN 
		SET	@rSourceId = (Select SourceId from @tOnlineLearningScope where Id = @count);
		SET	@rSourceTypeId = (Select SourceTypeId from @tOnlineLearningScope where Id = @count);

		
		  --if not Exists(Select 1 from sAcademic.tOnlineLearningScope   where SourceId = @rSourceId and SourceTypeId = @rSourceTypeId and OnlineLearningId = @rId )
				--BEGIN
					INSERT INTO sAcademic.tOnlineLearningScope(OnlineLearningId,SourceTypeId,SourceId)
					SELECT @rId,SourceTypeId,SourceId
					FROM @tOnlineLearningScope OLS where OLS.Id =  @count
					--WHERE OnlineLearningId = @rReferenceId
		
					
				--END 
				SET @count = @count + 1		   
			END 

		SELECT 1 AS Result
	--END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningRecordingAdd]
	 
        @rOnlineLearningId bigint,
		@rRecordingId nvarchar(50),
		@rRecordingStart datetime,
		@rRecordingEnd datetime,
		@rFileType nvarchar(20),
		@rFileExtension nvarchar(20),
		@rFileSize nvarchar(20),
		@rPlayURL nvarchar(1000),
		@rDownloadURL nvarchar(1000),
		@rStatus nvarchar(20),
		@rRecordingType nvarchar(100)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	

	IF EXISTS(SELECT 1 FROM sAcademic.tOnlineLearningRecording WHERE OnlineLearningId = @rOnlineLearningId AND RecordingId = @rRecordingId)
	BEGIN
		DELETE FROM sAcademic.tOnlineLearningRecording WHERE OnlineLearningId = @rOnlineLearningId AND RecordingId = @rRecordingId
	END	  
	
		INSERT INTO sAcademic.tOnlineLearningRecording
		(	
			OnlineLearningId,
			RecordingId,
			RecordingStart,
			RecordingEnd,
			FileType,
			FileExtension,
			FileSize,
			PlayURL,
			DownloadURL,
			Status,
			RecordingType,
			CreatedDateTime
		)
		Values
		(
			@rOnlineLearningId,
			@rRecordingId,
			@rRecordingStart,
			@rRecordingEnd,
			@rFileType,
			@rFileExtension,
			@rFileSize,
			@rPlayURL,
			@rDownloadURL,
			@rStatus,
			@rRecordingType,
			sCommon.fGetDate()
		)
	 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningReferenceAdd]
	 
        @rOnlineLearningId bigint,
		@rReferencePath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningReference WHERE OnlineLearningId = @rOnlineLearningId AND ReferencePath = @rReferencePath)
	BEGIN 
		SELECT 1 AS Result
	END
	ELSE
	BEGIN
		INSERT INTO sAcademic.tOnlineLearningReference
			(
				OnlineLearningId,
				ReferencePath
			)
		VALUES
			(
				 @rOnlineLearningId,
				 @rReferencePath
			)
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningResourceAdd]
	 
        @rOnlineLearningId bigint,
		@rResourceTypeId int,
		@rResourcePath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	INSERT INTO sAcademic.tOnlineLearningResource
		(
			OnlineLearningId,
			ResourceTypeId,
			ResourcePath
		)
	VALUES
		(
			 @rOnlineLearningId,
			 @rResourceTypeId,
			 @rResourcePath
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningScheduleCopy]
	 
        @rId bigint,
		@rAssignToStartDate DateTime,
		@rAssignToEndDate DateTime,
		@rCreatedUserId bigint,
		@rOrgId int
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	

	 DECLARE @lNextNumber BIGINT 

	 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tOnlineLearning', 0, 1, 1,@outNextNumber = @lNextNumber output
	 Print @lNextNumber
	 
	 INSERT INTO sAcademic.tOnlineLearning
		(
			Id
           ,BatchId
           ,StartDate
           ,StartTime
           ,EndDate
           ,EndTime
           ,ClassId
           ,SubjectId
           ,TeacherEmployeeId
           ,Title
           ,Description
           ,LearningTypeId
           ,IsTrackAttendance
           ,TopicId
           ,LecturePath
           ,IsDisplayMeetingId
           ,MeetingId
           ,MeetingPassword
		   ,IsCompleted
           ,CreatedUserId
           ,CreatedDateTime
		   ,MeetingAccountId
		   ,CoTeacherEmployeeId1
		   ,CoTeacherEmployeeId2
		)
	 SELECT 
			@lNextNumber,
			OL.BatchId,
			@rAssignToStartDate,
			OL.StartTime,
			@rAssignToEndDate, 
			OL.EndTime,
			OL.ClassId,
			OL.SubjectId,
			OL.TeacherEmployeeId,
			OL.Title,
			OL.Description,
			OL.LearningTypeId,
			OL.IsTrackAttendance,
			OL.TopicId,
			OL.LecturePath,
			OL.IsDisplayMeetingId,
			'',
			'',
			0,
			@rCreatedUserId,
			sCommon.fGetDate(),
			OL.MeetingAccountId,
			OL.CoTeacherEmployeeId1,
			OL.CoTeacherEmployeeId2
	  FROM sAcademic.tOnlineLearning OL WHERE Id = @rId

	  INSERT INTO sAcademic.tOnlineMeetingSettings
		(
			OnlineLearningId,
			IsOnParticipantVideo,
			IsOnParticipantAudio,
			IsOnHostVideo,
			IsOnHostAudio,
			IsOnParticipantScreenShare,
			IsOnHostscreenShare,
			AccountEmailId,
			AccountPassword,
			APIKey,
			APISecret,
			WebAPIKey,
			WebAPISecret,
			MeetingProviderId,
			JWTToken,
			OAuthAccountId,
			OAuthClientId,
			OAuthClientSecret
		)
		SELECT
			@lNextNumber,
			OMS.IsOnParticipantVideo,
			OMS.IsOnParticipantAudio,
			OMS.IsOnHostVideo ,
			OMS.IsOnHostAudio ,
			OMS.IsOnParticipantScreenShare,
			OMS.IsOnHostscreenShare,
			OMS.AccountEmailId,
			OMS.AccountPassword,
			OMS.APIKey,
			OMS.APISecret,
			OMS.WebAPIKey,
			OMS.WebAPISecret,
			OMS.MeetingProviderId,
			OMS.JWTToken,
			OMS.OAuthAccountId,
			OMS.OAuthClientId,
			OMS.OAuthClientSecret
		FROM 
		sAcademic.tOnlineMeetingSettings OMS
		WHERE OnlineLearningId = @rId

		 IF EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningScope WHERE OnlineLearningId = @rId)
		   BEGIN
				INSERT INTO sAcademic.tOnlineLearningScope
				SELECT @lNextNumber,SourceTypeId,SourceId
				FROM sAcademic.tOnlineLearningScope 
				WHERE OnlineLearningId = @rId
		
			END    

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 --exec [sAcademic].[pOnlineLearningScopeGet] 1101000000470
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningScopeGet]
	 @rOnlineLearningId bigint
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	  Declare  @rBatchId bigint
	  SELECT  @rBatchId= BatchId FROM sAcademic.tOnlineLearning WHERE Id = @rOnlineLearningId
	  print @rBatchId
			 SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName, 
			 0  as DivisionId
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON CS.SourceId=OM.Id
			INNER JOIN  sAcademic.tOnlineLearning OL ON OL.Id=CS.OnlineLearningId
			
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2021
			AND OL.BatchId=@rBatchId


			UNION ALL

			SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName, 
			 0 as DivisionId
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			INNER JOIN  sAcademic.tOnlineLearning OL ON OL.Id=CS.OnlineLearningId
			 
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2017
			AND OL.BatchId=@rBatchId

			UNION ALL

			SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName, 
			 0 As  DivisionId
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			INNER JOIN  sAcademic.tOnlineLearning OL ON OL.Id=CS.OnlineLearningId
			 
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2016
			AND OL.BatchId=@rBatchId

			UNION ALL

			SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			 CS.SourceId as  DivisionId
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			INNER JOIN  sAcademic.tOnlineLearning OL ON OL.Id=CS.OnlineLearningId
			 
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2005
			AND OL.BatchId=@rBatchId


			UNION ALL
			
			SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 SA.DivisionId as DivisionId
			FROM sAcademic.tOnlineLearningScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id
			INNER JOIN  sAcademic.tOnlineLearning OL ON OL.Id=CS.OnlineLearningId
			INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.StudentId AND SA.BatchId = OL.BatchId AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2003
			AND OL.BatchId=@rBatchId
			
			UNION ALL
			
			SELECT
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 SA.DivisionId as DivisionId 
			 
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN  sAcademic.tOnlineLearning OL ON OL.Id=CS.OnlineLearningId
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.AcademicId AND SA.BatchId = OL.BatchId AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			WHERE CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=2001
			AND OL.BatchId=@rBatchId
			
			UNION ALL
			
			SELECT
			
			 CS.OnlineLearningId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 0 as DivisionId 
			
			FROM sAcademic.tOnlineLearningScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			INNER JOIN  sAcademic.tOnlineLearning OL ON OL.Id=CS.OnlineLearningId
			 
			WHERE 
			CS.OnlineLearningId=@rOnlineLearningId AND CS.SourceTypeId=95
			AND OL.BatchId=@rBatchId


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningStudentAttendanceAdd]
	
	@rStrXml nvarchar(MAX),
	@rEmployeeId bigint,
    @rAttendanceTypeId tinyint,
    @rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rAttendanceGroupId int=0,
    @rPeriodNo int=0 ,
	@rAbsentReasonId int=0,
	@rAttendanceRemark nvarchar(10)='',
	@rAttendanceTagId int=0,
	@rCreatedUserId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	
	 set @rRepeatCount=@rPeriodNo
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId,
			PeriodNo,
			AttendanceGroupId,
			AttendanceRemark
			)
		SELECT	
		DISTINCT	
			AcademicId,
			@rEmployeeId,
			@rAttendanceTypeId,
		    AttendanceDate,
			ISNULL(@rSubjectId,0),
			ISNULL(@rRepeatCount,0),
			IsPresent,
			ISNULL(@rAbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			'',
			'',
			@rAttendanceTagId,
			@rPeriodNo,
			@rAttendanceGroupId,
			@rAttendanceRemark
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				AttendanceDate Date,
				IsPresent bit
				
			  ) A 
		WHERE NOT EXISTS (
        SELECT AcademicId
        FROM sAttendance.tStudentRegister 
        WHERE AcademicId = A.AcademicId AND AttendanceDate=A.AttendanceDate AND PeriodNo=@rPeriodNo AND SubjectId=@rSubjectId
        )
        SELECT 1 AS Result
	
	
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningStudentAttendanceGet]
	 
	 @rAcademicId bigint,
	 @lClassId bigint=0,
	 @lDivisionId bigint=0,
	 @rStartDate date = '',
	 @rEndDate date = ''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
Declare @lStudentId bigint
	SELECT @lClassId=ClassId,@lDivisionId=DivisionId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	SELECT @lStudentId=StudentId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	BEGIN
	Select 
	--(Select (CONVERT(NVARCHAR,OLA.FirstInDateTime,103)+' '+CONVERT(NVARCHAR(5),OLA.FirstInDateTime,108)) from sAcademic.tOnlineLearningAttendance OLA 
	--Where OL.Id=OLA.OnlineLearningId AND OLA.AcademicId=@rAcademicId)AS StartDate,
	CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDate,
	(Select (CONVERT(NVARCHAR,OLA.LastOutDateTime,103)+' '+CONVERT(NVARCHAR(5),OLA.LastOutDateTime,108)) from sAcademic.tOnlineLearningAttendance OLA 
	Where OL.Id=OLA.OnlineLearningId AND OLA.AcademicId=@rAcademicId)AS EndDate,
	(EM.FirstName +' '+EM.MiddleName +' '+EM.LastName)AS TeacherName,
	SM.Title AS SubjectName,
	(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=@rAcademicId
			 AND OLAL.OnlineLearningId = OL.Id 
			 )As AttendCount,
	ISNULL((Select (CASE WHEN OLA.IsPresent=1 THEN 'Present' ELSE 'Absent' END) from sAcademic.tOnlineLearningAttendance OLA 
	Where OL.Id=OLA.OnlineLearningId AND OLA.AcademicId=@rAcademicId),'Absent')AS PresentabsentStatus
	--OL.StartDate
	
	
	FROM 
	[sAcademic].[tOnlineLearning] OL
	INNER JOIN [sHrm].[tEmployeeMaster] EM ON OL.TeacherEmployeeId=EM.Id
	INNER JOIN [sSetup].[tSubjectMaster] SM ON SM.Id=OL.SubjectId
	INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
				WHERE (
				( 
				(OLS.SourceTypeId = 2016 AND OLS.SourceId =@lClassId) OR
				(OLS.SourceTypeId = 2005 AND OLS.SourceId =@lDivisionId) OR
				(OLS.SourceTypeId = 2003 AND OLS.SourceId =@lStudentId) OR
				(OLS.SourceTypeId = 2001 AND OLS.SourceId =@rAcademicId)
					))
				) D
				ON D.OnlineLearningId= OL.Id
	
	Where 
	--OLA.AcademicId=9935000000847 
	 OL.LearningTypeId=2 AND IsTrackAttendance=1 AND IsCompleted=1
	AND ((OL.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
	AND ((OL.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
			
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningTeacherStudentDetailListGet]
	 @rId BigInt ,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rOrgGroupBatchId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF (@rSourceTypeId = 2001)
	BEGIN 

	 DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint,
	 @lClassName nvarchar(100)


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



SELECT 
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndTime,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(@lClassName,'') AS Class,
			OL.LecturePath AS LecturePath,
			OL.LearningTypeId AS LearningTypeId,
			OL.IsDisplayMeetingId AS IsDisplayMeetingId,
			OL.MeetingId AS MeetingId,
			OL.MeetingPassword AS MeetingPassword,
			OL.IsCompleted AS IsCompleted,
			ISNULL(OL.Description,'')AS Description,
			ISNULL(OL.Title,'') AS Title,
			ISNULL(OL.IsMeetingStarted,'') AS IsMeetingStarted,
			OL.IsSubmitAssignment AS IsSubmitAssignment,
			OL.IsTakeTest AS IsTakeTest,
			OL.TestId AS TestId,
			OL.IsTrackAttendance AS IsTrackAttendance,
			OL.IsTrackAssignmentView AS IsTrackAssignmentView,
			OL.IsMeetingCreated AS IsMeetingCreated,
			--OL.MeetingProviderId As MeetingProviderId
			OL.AssignmentRemark,
			OL.BatchId,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			ISNULL(OL.IsRecording,0) As IsRecording,
			OL.IsAssignment,
			OL.IsReference,
			OL.IsResource,
			OL.IsTrackAttendance
          FROM 
				sAcademic.tOnlineLearning OL
				
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				--Left JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				--INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=CM.OrgId
				--INNER JOIN [sStudent].[tAcademic] A ON A.ClassId = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
				--LEFT JOIN (SELECT Id,Title FROM sSetup.tClassMaster WHERE ((Id = @rClassId ) OR (@rClassId=0))) CM ON CM.Id=OL.CLassId
				INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
				WHERE (
				( 
				(OLS.SourceTypeId = 2021 AND OLS.SourceId =@lOrgId) 
				OR
				(OLS.SourceTypeId = 2017 AND OLS.SourceId =@lDepartmentId) OR
				(OLS.SourceTypeId = 2016 AND OLS.SourceId =@lClassId) OR
				(OLS.SourceTypeId = 2005 AND OLS.SourceId =@lDivisionId) OR
				(OLS.SourceTypeId = 2003 AND OLS.SourceId =@lStudentId) OR
				(OLS.SourceTypeId = 2001 AND OLS.SourceId =@lAcademicId)
				 ))
				) D
				ON D.OnlineLearningId= OL.Id

            
            WHERE
				 OL.Id = @rId
				 --AND A.Id = @rSourceId
				

				ORDER BY OL.IsCompleted,OL.StartDate,OL.EndDate
		END
		
		IF(@rSourceTypeId = 95)
		BEGIN
		SELECT 
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndTime,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			OL.LecturePath AS LecturePath,
			OL.LearningTypeId AS LearningTypeId,
			OL.IsDisplayMeetingId AS IsDisplayMeetingId,
			OL.MeetingId AS MeetingId,
			OL.MeetingPassword AS MeetingPassword,
			OL.IsCompleted AS IsCompleted,
			ISNULL(OL.Title,'') AS Title,
			ISNULL(OL.Description,'')AS Description,
			ISNULL(OL.IsMeetingStarted,'') AS IsMeetingStarted,
			CM.Id AS ClassId,
			OL.IsSubmitAssignment AS IsSubmitAssignment,
			OL.IsTakeTest AS IsTakeTest,
			OL.TestId AS TestId,
			OL.IsTrackAttendance AS IsTrackAttendance,
			OL.IsTrackAssignmentView AS IsTrackAssignmentView,
			OL.IsMeetingCreated AS IsMeetingCreated,
			--OL.MeetingProviderId As MeetingProviderId
			OL.AssignmentRemark,
			OL.SubjectId,
			OL.CoTeacherEmployeeId1,
			OL.CoTeacherEmployeeId2,
			OL.BatchId,
			ISNULL(OL.IsRecording,0) As IsRecording,
			OL.IsAssignment,
			OL.IsReference,
			OL.IsResource,
			OL.TeacherEmployeeId
		FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3

		WHERE
			 OL.Id = @rId
			 AND (OL.TeacherEmployeeId = @rSourceId OR OL.CoTeacherEmployeeId1=@rSourceId OR OL.CoTeacherEmployeeId2=@rSourceId)
			 --AND OL.TeacherEmployeeId = @rSourceId
			 
			
			ORDER BY OL.CreatedDateTime
			
			END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAcademic].[pOnlineLearningTeacherStudentListGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rLearningTypeId int = 0,
	 @rClassId int = 0,
	 @rSubjectId int = 0,
	 @rTopicId int = 0,
	 @rStartDate date = '',
	 @rEndDate date = '',
	 @rIsCompleted int=-1,
	 @rTitle nvarchar(100) ='',
	 @rOrgGroupBatchId int,
	 @rBatchId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	 DECLARE @lConfigValue nvarchar(50)=''

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

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


	 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
		@lClassName=CM.Title,@lCLassId=CM.Id
     FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
	 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
	 WHERE A.Id = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
	 
	 IF(@lConfigValue = 'True')
  BEGIN
	 If (@rSourceTypeId = 2001)
	 BEGIN
	
	  SELECT 
			OL.Id,
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDate,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' WHEN OL.IsCompleted=1 THEN 'Completed'  WHEN OL.IsCompleted=721 THEN 'Cancel' END) AS Status,
			@lClassName AS Class,
			@lClassId AS ClassId,
			--ISNULL(CM.Title,'') AS Class,
			--CM.Id AS ClassId
			ISNULL(OL.Title,'') AS Title
			
		FROM 
				sAcademic.tOnlineLearning OL
				
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				--Left JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				--INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=CM.OrgId
				--INNER JOIN [sStudent].[tAcademic] A ON A.ClassId = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
				--LEFT JOIN (SELECT Id,Title FROM sSetup.tClassMaster WHERE ((Id = @rClassId ) OR (@rClassId=0))) CM ON CM.Id=OL.CLassId
				INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
				WHERE (
				( 
				(OLS.SourceTypeId = 2021 AND OLS.SourceId =@lOrgId) 
				OR
				(OLS.SourceTypeId = 2017 AND OLS.SourceId =@lDepartmentId) OR
				(OLS.SourceTypeId = 2016 AND OLS.SourceId =@lClassId) OR
				(OLS.SourceTypeId = 2005 AND OLS.SourceId =@lDivisionId) OR
				(OLS.SourceTypeId = 2003 AND OLS.SourceId =@lStudentId) OR
				(OLS.SourceTypeId = 2001 AND OLS.SourceId =@lAcademicId)
				 ))
				) D
				ON D.OnlineLearningId= OL.Id

			WHERE
				((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				--AND ((OL.ClassId = @rClassId ) OR (@rClassId=0))
				AND ((OL.EndDate >= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '1900-01-01' END)) 
				AND ((OL.StartDate <= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '9999-01-01' END))
				AND ((OL.StartTime <= CASE WHEN OL.LearningTypeId = 1 AND OL.StartDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.StartTime END)) 
				AND ((OL.EndTime >= CASE WHEN OL.LearningTypeId = 1  AND OL.EndDate = CONVERT(varchar,GETDATE(),23)THEN CONVERT(varchar,GETDATE(),14) ELSE OL.EndTime END))
				AND ((OL.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OL.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				--AND ((A.Id = @rSourceId))
				AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
				AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
				AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
				AND ((Convert(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
				AND OL.BatchId=@rBatchId AND OL.IsCompleted <> 721
				
				ORDER BY OL.IsCompleted,OL.StartDate,OL.StartTime,OL.EndDate
			END
		
	IF (@rSourceTypeId = 95)
	BEGIN 
		SELECT 
			OL.Id,
			DM.Title AS LearningType,
			--EM.EmployeeName AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDate,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' WHEN OL.IsCompleted=1 THEN 'Completed'  WHEN OL.IsCompleted=721 THEN 'Cancel' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			CM.Id AS ClassId,
			ISNULL(OL.Title,'') As Title,
			(CASE WHEN OL.IsAssignment = 0 THEN 'N' WHEN OL.IsAssignment = NULL THEN '' ELSE 'Y' END) AS IsAssignment,
			(CASE WHEN OL.IsSubmitAssignment = 0 THEN 'N' WHEN OL.IsSubmitAssignment = NULL THEN '' ELSE 'Y' END) AS IsSubmitAssignment,
			OL.StartDateTime AS TeacherStartDateTime,
			OL.EndDateTime AS TeacherEndDateTime
			FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3

			WHERE
				((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
				AND ((OL.ClassId = @rClassId ) OR (@rClassId=0))
				AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
				AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
				AND ((OL.EndDate >= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '1900-01-01' END)) 
				AND ((OL.StartDate <= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '9999-01-01' END))
				AND ((OL.StartTime <= CASE WHEN OL.LearningTypeId = 1 AND OL.StartDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.StartTime END)) 
				AND ((OL.EndTime >= CASE WHEN OL.LearningTypeId = 1 AND OL.EndDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.EndTime END))
				AND ((OL.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OL.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				AND (OL.TeacherEmployeeId = @rSourceId OR OL.CoTeacherEmployeeId1=@rSourceId OR OL.CoTeacherEmployeeId2=@rSourceId)
				AND ((Convert(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
				AND ((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND OL.BatchId=@rBatchId AND OL.IsCompleted <> 721
				ORDER BY OL.IsCompleted,OL.StartDate,OL.StartTime,OL.EndDate
		END
				
		END	
	ELSE IF(@lConfigValue = 'False')
	BEGIN
		If (@rSourceTypeId = 2001)
	 BEGIN
	
	  SELECT 
			OL.Id,
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDate,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' WHEN OL.IsCompleted=1 THEN 'Completed'  WHEN OL.IsCompleted=721 THEN 'Cancel' END) AS Status,
			@lClassName AS Class,
			@lClassId AS ClassId,
			--ISNULL(CM.Title,'') AS Class,
			--CM.Id AS ClassId
			ISNULL(OL.Title,'') AS Title
		
		FROM 
				sAcademic.tOnlineLearning OL
				
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				--Left JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				--INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=CM.OrgId
				--INNER JOIN [sStudent].[tAcademic] A ON A.ClassId = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
				--LEFT JOIN (SELECT Id,Title FROM sSetup.tClassMaster WHERE ((Id = @rClassId ) OR (@rClassId=0))) CM ON CM.Id=OL.CLassId
				INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
				WHERE (
				( 
				(OLS.SourceTypeId = 2021 AND OLS.SourceId =@lOrgId) 
				OR
				(OLS.SourceTypeId = 2017 AND OLS.SourceId =@lDepartmentId) OR
				(OLS.SourceTypeId = 2016 AND OLS.SourceId =@lClassId) OR
				(OLS.SourceTypeId = 2005 AND OLS.SourceId =@lDivisionId) OR
				(OLS.SourceTypeId = 2003 AND OLS.SourceId =@lStudentId) OR
				(OLS.SourceTypeId = 2001 AND OLS.SourceId =@lAcademicId)
				 ))
				) D
				ON D.OnlineLearningId= OL.Id

			WHERE
				((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				--AND ((OL.ClassId = @rClassId ) OR (@rClassId=0))
				AND ((OL.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
				AND ((OL.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
				--AND ((A.Id = @rSourceId))
				AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
				AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
				AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
				AND ((Convert(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
				AND OL.BatchId=@rBatchId AND OL.IsCompleted <> 721
				
				ORDER BY OL.IsCompleted,OL.StartDate,OL.StartTime,OL.EndDate
			END
		
			IF (@rSourceTypeId = 95)
			BEGIN 
			SELECT 
				OL.Id,
				DM.Title AS LearningType,
				--EM.EmployeeName AS Teacher,
				SM.Title AS SubjectName,
				TM.Title AS Topic,
				CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDate,
				CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDate,
				(CASE WHEN OL.IsCompleted=0 THEN 'Pending' WHEN OL.IsCompleted=1 THEN 'Completed'  WHEN OL.IsCompleted=721 THEN 'Cancel' END) AS Status,
				ISNULL(CM.Title,'') AS Class,
				CM.Id AS ClassId,
				ISNULL(OL.Title,'') As Title,
				(CASE WHEN OL.IsAssignment = 0 THEN 'N' WHEN OL.IsAssignment = NULL THEN '' ELSE 'Y' END) AS IsAssignment,
				(CASE WHEN OL.IsSubmitAssignment = 0 THEN 'N' WHEN OL.IsSubmitAssignment = NULL THEN '' ELSE 'Y' END) AS IsSubmitAssignment,
				OL.StartDateTime AS TeacherStartDateTime,
			    OL.EndDateTime AS TeacherEndDateTime
			
				FROM 
					sAcademic.tOnlineLearning OL
					INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
					LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
					LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
					INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
					INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3

				WHERE
					((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
					AND ((OL.ClassId = @rClassId ) OR (@rClassId=0))
					AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
					AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
					AND ((OL.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')=''))
					AND ((OL.StartDate <= @rEndDate) OR (ISNULL(@rEndDate,'')=''))
					AND (OL.TeacherEmployeeId = @rSourceId OR OL.CoTeacherEmployeeId1=@rSourceId OR OL.CoTeacherEmployeeId2=@rSourceId)
					AND ((Convert(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
					AND ((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
					AND OL.BatchId=@rBatchId AND OL.IsCompleted <> 721
					ORDER BY OL.IsCompleted,OL.StartDate,OL.StartTime,OL.EndDate
			END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pPreLessonPlanAdd]
	 
        @rId bigint=0,
        @rClassId int,
        @rSubjectId int,
        @rEmployeeId bigint,
        @rObjective nvarchar(200),
        @rSummary nvarchar(200),
        @rStartDate date='',
        @rEndDate date='',
        @rBatchId int,
        @rCreatedUserId bigint,
        @rOrgId smallint,
        @rSubTopic nvarchar(1000),
        @rTopicId int
       ,@rDivisionId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tPreLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tPreLessonPlan		(			Id,			ClassId,			SubjectId,			EmployeeId,					Objective,			Summary,			StartDate,			EndDate,			BatchId,			CreatedUserId,			CreatedDateTime,			SubTopic,			TopicId			,DivisionId		)	VALUES		(			@lNextNumber,			@rClassId,			@rSubjectId,			@rEmployeeId,			@rObjective,			@rSummary,			@rStartDate,			@rEndDate,			@rBatchId,			@rCreatedUserId,			sCommon.fGetDate(),			@rSubTopic,			@rTopicId			,@rDivisionId					)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tPreLessonPlan
	    SET
			ClassId=@rClassId,
			SubjectId=@rSubjectId,						EmployeeId = @rEmployeeId,			Objective=@rObjective,			SubTopic=@rSubTopic,			TopicId=@rTopicId,			Summary=@rSummary,			StartDate=@rStartDate,			EndDate=@rEndDate,			DivisionId=@rDivisionId,			UpdatedUserId=@rCreatedUserId,			UpdatedDateTime=sCommon.fGetDate()
			
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pPreLessonPlanCopy]
	 
        
        @rFromClassId int, 
        @rToClassId int, 
        @rEmployeeId bigint,
        @rBatchId int,
        @rOrgId int
  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 DECLARE @lNextNumber bigint
	 
	 --Delete from sAcademic.tPreLessonPlan where ClassId=@rToClassId AND EmployeeId =@rEmployeeId AND BatchId=@rBatchId
	 
	 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tPreLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	 
		Insert into sAcademic.tPreLessonPlan
		(
		Id,
		Objective,
		ClassId,
		Summary,
		StartDate,
		EndDate,
		EmployeeId,
		BatchId,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		SubTopic
		)
		Select 
		@lNextNumber,
		Objective,
		@rToClassId,
		Summary,
		StartDate,
		EndDate,
		EmployeeId,
		BatchId,
		CreatedUserId,
		sCommon.fGetDate(),
		UpdatedUserId,
		sCommon.fGetDate(),
		SubTopic
		from sAcademic.tPreLessonPlan where EmployeeId =@rEmployeeId
		
		Select 1 as result
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pPreLessonPlanGet]

	 @rId bigint,
	 @rClassId int,
	 @rSubjectId int,
	 @rEmployeeId bigint,
	 @rBatchId int
	 ,@rDivisionId int=0
	 --@rName bigint
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			DISTINCT(LP.Id),
			LP.ClassId,
			LP.SubjectId,
		    vTSD.ClassTitle AS ClassTitle,
			LP.EmployeeId,
			LP.Objective,
			LP.Summary,
			LP.BatchId,
			ISNULL(LP.StartDate,'') AS StartDate, 
			EM.FirstName+' '+EM.LastName AS Name,
			LP.SubTopic,
			LP.TopicId,
			ISNULL(LP.DivisionId,0) AS DivisionId
			
	FROM 
			sAcademic.tPreLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = LP.SubjectId
		    		AND vTSD.ClassId = LP.ClassId 
			AND vTSD.EmployeeId = LP.EmployeeId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
			--INNER JOIN sSetup.tDivisionMaster DM  ON DM.ClassId = CM.Id
	WHERE 
		  (LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((vTSD.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((LP.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.DivisionId = ISNULL(@rDivisionId,0))OR(ISNULL(@rDivisionId,0)=0))
		--AND ((EM.FirstName = @rName ) OR (@rName = 0)) 
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		--AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		Order by Id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pRptDailyStatusDetailGet]
	 @rBuilder1 nvarchar(max)='',
     @rSearchDate datetime,
     @rOrgId smallint,
     @rBatchId int,     
     @rYear smallint,
     @rMonth smallint,
     @rDate smallint,
	 @rAttendanceTypeId int=1,
	 @rAttendanceStatusId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	 
 

	SELECT 		
			@rBuilder1 AS Builder1,
			vCD.ClassDivisionName,
			ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
			[sAttendance].[fWeekHOffGet](@rYear,@rMonth,@rDate,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId) AS WeekOffStatus, 
			CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus, 
            sCommon.fCountDivisionStudent(A.DivisionId,@rBatchId) AS TotalCount, 
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,@rSearchDate,@rAttendanceTypeId,1) AS PresentCount,
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,@rSearchDate,@rAttendanceTypeId,0) AS AbsentCount,
			ISNULL(MAX(SR.UpdatedDateTime),MAX(SR.CreatedDateTime)) as UpdatedDateTime,
			[sCommon].[fGetUserNameforDailyStatus](A.DivisionId,@rSearchDate,@rAttendanceTypeId)AS UserName,
			DM.OrderIndex AS DivisionOrderIndex,--added by dhananjay for mantis id - 36431
			vCD.OrderIndex AS ClassOrderIndex --add for mantis : 0040113
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			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 AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceDate=@rSearchDate 
            AND SR.AttendanceTypeId = @rAttendanceTypeId 
			AND SR.IsPresent=1 
					
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId,DM.OrderIndex--added(DM.OrderIndex) by dhananjay for mantis id - 36431 
			Having (@rAttendanceStatusId=1 AND (COUNT(SR.AcademicId)=0 And (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0)) =0) )
				OR (@rAttendanceStatusId=2 and (COUNT(SR.AcademicId)<>0 OR (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rSearchDate,@rAttendanceTypeId,0))<>0) )
				 OR ( @rAttendanceStatusId=0)	
            ORDER BY vCD.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pRptDailyStatusMonthlyDetailGet] 
	@rBuilder1 NVARCHAR(max) = ''
	,@rBuilder2 NVARCHAR(max) = ''
	,@rOrgId SMALLINT
	,@rBatchId BIGINT
	,@rYear SMALLINT
	,@rMonth SMALLINT
	--,@rDayOfMonth SMALLINT
	,@rAttendanceTypeId INT = 1
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

	DECLARE @Days INT
		,@lFromDate DATE
		,@lToDate DATE

	SELECT @Days = sCommon.fGetDaysInMonth(@rMonth, @rYear)

	SET @lFromDate = CONVERT(DATE, (CONVERT(NVARCHAR(4), @rYear) + '-' + CONVERT(NVARCHAR(2), @rMonth) + '-01'))
	SET @lToDate = CONVERT(DATE, (CONVERT(NVARCHAR(4), @rYear) + '-' + CONVERT(NVARCHAR(2), @rMonth) + '-' + CAST(@Days AS NVARCHAR(2))))

	CREATE TABLE #Temp (
		id INT NOT NULL IDENTITY PRIMARY KEY
		,AllDate DATE
		);

	WITH AllDays
	AS (
		SELECT @lFromDate AS MyDate
			,1 AS [level]
		
		UNION ALL
		
		SELECT DATEADD(DAY, 1, MyDate)
			,[level] + 1
		FROM AllDays
		WHERE MyDate < @lToDate
		)
	INSERT INTO #Temp (AllDate)
	SELECT MyDate
	FROM AllDays
	OPTION (MAXRECURSION 0)

	SELECT A.ClassId
		,A.DivisionId
		,vCD.ClassDivisionName
		,ISNULL(EM.FirstName + ' ' + EM.LastName, '') AS ClassTeacherName
		,T.id AS DayPart
		,CASE 
			WHEN ([sAttendance].[fWeekHOffGet](@rYear, @rMonth, T.id, @rBatchId, A.ClassId, A.DivisionId, '', @rOrgId)) != ''
				THEN ([sAttendance].[fWeekHOffGet](@rYear, @rMonth, T.id, @rBatchId, A.ClassId, A.DivisionId, '', @rOrgId))
			ELSE CASE 
					WHEN COUNT(SR.AcademicId) = 0
						THEN CASE 
								WHEN (
										SELECT [sCommon].[fCountAbsentStudent](A.DivisionId, @rBatchId, T.AllDate, @rAttendanceTypeId, 0)
										) = 0
									THEN 'P'
								ELSE 'C'
								END
					ELSE 'C'
					END
			END AS AttendanceStatus
	INTO #TempDaysTempTable
	FROM #Temp T
	INNER JOIN sStudent.tAcademic A ON 1 = 1
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		AND SM.StatusId = 1
	INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId = A.ClassId
		AND vCD.OrgId = @rOrgId
		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
		AND DM.OrgId = @rOrgId
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
		AND ISNULL(EM.IsOtherUser, 0) = 0
	LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.IsPresent = 1
		AND T.AllDate = SR.AttendanceDate
	GROUP BY A.DivisionId
		,A.BatchId
		,vCD.ClassDivisionName
		,vCD.OrderIndex
		,EM.FirstName
		,EM.LastName
		,SM.StatusId
		,A.ClassId
		,T.id
		,T.AllDate

	SELECT @rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,ClassId
		,DivisionId
		,ClassDivisionName
		,ClassTeacherName
		,[1] AS D1
		,[2] AS D2
		,[3] AS D3
		,[4] AS D4
		,[5] AS D5
		,[6] AS D6
		,[7] AS D7
		,[8] AS D8
		,[9] AS D9
		,[10] AS D10
		,[11] AS D11
		,[12] AS D12
		,[13] AS D13
		,[14] AS D14
		,[15] AS D15
		,[16] AS D16
		,[17] AS D17
		,[18] AS D18
		,[19] AS D19
		,[20] AS D20
		,[21] AS D21
		,[22] AS D22
		,[23] AS D23
		,[24] AS D24
		,[25] AS D25
		,[26] AS D26
		,[27] AS D27
		,[28] AS D28
		,(CASE WHEN @Days >= 29 THEN [29] ELSE '' END)AS D29 
		,(CASE WHEN @Days >= 30 THEN [30] ELSE '' END) AS D30
		,(CASE WHEN @Days >= 31 THEN [31] ELSE '' END) AS D31
		,TotalPending
		,TotalComplete
		,TotalHoliday
		,TotalWeekOff
	FROM (
		SELECT *
			,(
				SELECT COUNT(1)
				FROM #TempDaysTempTable
				WHERE ClassId = T.ClassId
					AND DivisionId = T.DivisionId
					AND AttendanceStatus = 'P'
				) AS TotalPending
			,(
				SELECT COUNT(1)
				FROM #TempDaysTempTable
				WHERE ClassId = T.ClassId
					AND DivisionId = T.DivisionId
					AND AttendanceStatus = 'C'
				) AS TotalComplete
			,(
				SELECT COUNT(1)
				FROM #TempDaysTempTable
				WHERE ClassId = T.ClassId
					AND DivisionId = T.DivisionId
					AND AttendanceStatus = 'H'
				) AS TotalHoliday
			,(
				SELECT COUNT(1)
				FROM #TempDaysTempTable
				WHERE ClassId = T.ClassId
					AND DivisionId = T.DivisionId
					AND AttendanceStatus = 'W'
				) AS TotalWeekOff
		FROM #TempDaysTempTable T
		) d
	pivot(min(AttendanceStatus) FOR DayPart IN (
				[1]
				,[2]
				,[3]
				,[4]
				,[5]
				,[6]
				,[7]
				,[8]
				,[9]
				,[10]
				,[11]
				,[12]
				,[13]
				,[14]
				,[15]
				,[16]
				,[17]
				,[18]
				,[19]
				,[20]
				,[21]
				,[22]
				,[23]
				,[24]
				,[25]
				,[26]
				,[27]
				,[28]
				,[29]
				,[30]
				,[31]
				)) piv;


	-- For Drag n Drop DataSet for Report
	--SELECT '' AS Builder1
	--	,'' AS Builder2
	--	,0 AS ClassId
	--	,0 AS DivisionId
	--	,'' AS ClassDivisionName
	--	,'' AS ClassTeacherName
	--	,'' AS D1
	--	,'' AS D2
	--	,'' AS D3
	--	,'' AS D4
	--	,'' AS D5
	--	,'' AS D6
	--	,'' AS D7
	--	,'' AS D8
	--	,'' AS D9
	--	,'' AS D10
	--	,'' AS D11
	--	,'' AS D12
	--	,'' AS D13
	--	,'' AS D14
	--	,'' AS D15
	--	,'' AS D16
	--	,'' AS D17
	--	,'' AS D18
	--	,'' AS D19
	--	,'' AS D20
	--	,'' AS D21
	--	,'' AS D22
	--	,'' AS D23
	--	,'' AS D24
	--	,'' AS D25
	--	,'' AS D26
	--	,'' AS D27
	--	,'' AS D28
	--	,'' AS D29
	--	,'' AS D30
	--	,'' AS D31
	--	,0 AS TotalPending
	--	,0 AS TotalComplete
	--	,0 AS TotalHoliday
	--	,0 AS TotalWeekOff
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pRptDailyStatusYearlyDetailGet] 
	@rBuilder1 NVARCHAR(max) = ''
	,@rBuilder2 NVARCHAR(max) = ''
	,@rOrgId SMALLINT
	,@rBatchId BIGINT
	,@rClassId INT=0
	,@rDivisionId INT=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT
		@rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,DM.ClassId
		,DM.Id AS DivisionId
		,DM.Code AS ClassDivisionName
		,ISNULL(EM.FirstName + ' ' + EM.LastName, '') AS ClassTeacherName
		,ISNULL((MM.Code + '-' + CONVERT(NVARCHAR, MY.YearNumber)),'') AS MonthDetail
		,CONVERT(DATE, MR.UpdatedDateTime) AS Date
		,MY.MonthNumber
		,MY.YearNumber
	FROM sSetup.tDivisionMaster DM
	LEFT JOIN sStudent.vStudentName SN ON SN.DivisionId = DM.Id
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId = SN.BatchId
	INNER JOIN sCommon.tMonthMaster MM ON MY.MonthNumber = MM.Id
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId = SN.AcademicId AND MR.ForMonth = MY.MonthNumber AND MR.ForYear = MY.YearNumber
	WHERE DM.IsObsolete = 0	AND DM.OrgId = @rOrgId
	AND (DM.ClassId	= @rClassId	OR @rClassId = 0)
	AND (DM.Id = @rDivisionId OR @rDivisionId = 0)
	AND 
	((ISNULL(MY.YearNumber,0) < YEAR(GETDATE())) OR
	(ISNULL(MY.MonthNumber, 0) <= MONTH(GETDATE()) AND ISNULL(MY.YearNumber,0) = YEAR(GETDATE())))
	GROUP BY DM.ClassId,DM.Id,DM.Code,MM.Code,MY.YearNumber,DM.OrderIndex,MY.MonthNumber,CONVERT(DATE, MR.UpdatedDateTime),EM.FirstName,EM.LastName
	ORDER BY DM.OrderIndex, MY.YearNumber, MY.MonthNumber, CONVERT(DATE, MR.UpdatedDateTime) DESC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pRptLessonPlanAddGet]

	 
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit=0 ,
	 @rBatchId int,
	 @rEmployeeId bigint,
	 @rOrgId smallint ,
	 @rId  bigint,
	 @rStatus int = 0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rStatus = 0)
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
			LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			--Mantis - 44459
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			CM.Title + '' + DM.Title AS ClassDivisionName,
			--vTSD.SubjectName,
			SM.Title AS SubjectName,		    
			--Mantis - 44459
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial ,
			LP.AssessmentQuestion ,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			
			----lesson plan
			
			
			--- lesson plan fuction
			
		   ISNULL(DFl.IsObjective,0)AS IsObjective,
		   ISNULL(DFl.IsSummary,0)AS IsSummary,
		   ISNULL(DFl.IsLearningExperience,0)AS IsLearningExperience,
		   ISNULL(DFl.IsEssentialMaterial,0)AS IsEssentialMaterial,
		   ISNULL(DFl.IsToolsTechniques,0)AS IsToolsTechniques,
		   ISNULL(DFl.IsIndicativeHomework,0)AS IsIndicativeHomework,
		   ISNULL(DFl.IsAssessmentQuestion,0)AS IsAssessmentQuestion,
		   ISNULL(DFl.IsTeacherExample,0)AS IsTeacherExample,
		   ISNULL(DFl.IsGuidedPractice,0)AS IsGuidedPractice,
		   ISNULL(DFl.IsIndependentPractice,0)AS IsIndependentPractice
		   	
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--Mantis - 44459
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId  -- Mantis 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = LP.DivisionId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
			--Mantis - 44459
			LEFT JOIN sConfig.fDisplayFieldLessionGet(@rOrgId) AS DFl ON DFl.OrgId=SM.OrgId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	--Mantis - 44459
		AND((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0)) --Mantis - 44459(vTSD.DivisionId to LP.DivisionId)	
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND((DFl.OrgId=@rOrgId) OR (@rOrgId = 0))
		AND  ISNULL(EM.IsOtherUser,0) = 0
	END
	ELSE
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
			LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			--Mantis - 44459
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			CM.Title + '' + DM.Title AS ClassDivisionName,
			--vTSD.SubjectName,
			SM.Title AS SubjectName,		    
			--Mantis - 44459
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial ,
			LP.AssessmentQuestion ,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			
			----lesson plan
			
			
			--- lesson plan fuction
			
		   ISNULL(DFl.IsObjective,0)AS IsObjective,
		   ISNULL(DFl.IsSummary,0)AS IsSummary,
		   ISNULL(DFl.IsLearningExperience,0)AS IsLearningExperience,
		   ISNULL(DFl.IsEssentialMaterial,0)AS IsEssentialMaterial,
		   ISNULL(DFl.IsToolsTechniques,0)AS IsToolsTechniques,
		   ISNULL(DFl.IsIndicativeHomework,0)AS IsIndicativeHomework,
		   ISNULL(DFl.IsAssessmentQuestion,0)AS IsAssessmentQuestion,
		   ISNULL(DFl.IsTeacherExample,0)AS IsTeacherExample,
		   ISNULL(DFl.IsGuidedPractice,0)AS IsGuidedPractice,
		   ISNULL(DFl.IsIndependentPractice,0)AS IsIndependentPractice,
		   SM.Title AS SubjectName,
		   CM.Title + '' + DM.Title AS ClassDivisionName
		 
	
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--Mantis - 44459
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId  -- Mantis 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = LP.DivisionId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
			--Mantis - 44459
			LEFT JOIN sConfig.fDisplayFieldLessionGet(@rOrgId) AS DFl ON DFl.OrgId=SM.OrgId  
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			

	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	--Mantis - 44459
		AND((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	--Mantis - 44459(vTSD.DivisionId to LP.DivisionId)
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((@rStatus = 2) OR (LP.IsCompleted=@rIsCompleted))
		AND((DFl.OrgId=@rOrgId) OR (@rOrgId = 0))
		AND  ISNULL(EM.IsOtherUser,0) = 0
	END
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAcademic].[pRptLessonPlanGet]

	 
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit =0,
	  @rBatchId int,
	 @rEmployeeId bigint,
	 @rStartDate date='',
	 @rEndDate date='',
	 @rStatus int = 0,
	 @rIsWithHeader bit=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF(@rStatus = 0)
	BEGIN
	SELECT 
			--LP.Id,
			--TM.ClassId,
			--LP.DivisionId,
			--TM.SubjectId,
			--LP.TopicId,
			--LP.NoOfPeriodRequired,
			--LP.Objective,
			--LP.IndicativeHomework,
			--LP.Summary,
			--LP.StartDate,
			--LP.EndDate,
			--LP.IsCompleted,
			--LP.EmployeeId,
			--LP.BatchId,
			--LP.CreatedUserId,
			--LP.CreatedDateTime,
			--TM.Title AS TopicName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			--vTSD.SubjectName,
			----ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			--LP.LearningExperience,
			--LP.ToolsAndTechniques,
			--LP.EssentialMaterial,
			--LP.AssessmentQuestion ,
		 -- datepart(MONTH,Lp.StartDate) AS MonthId,
		 -- datename(MONTH,Lp.StartDate) AS Monthname
		  
		  LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			datepart(MONTH,Lp.StartDate) AS MonthId,
		    datename(MONTH,Lp.StartDate) AS Monthname,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4,
			--Added by dhananjay for mantis start - 37295
			ISNULL(LP.PeriodCount,0) AS PeriodCount,
			ISNULL(LP.Session,'') AS Session,
			ISNULL(LP.Remark,'') AS Remark,
			ISNULL(SM.Code,'') AS SubjectCode,
			'' AS BatchName
			--Added by dhananjay for mantis end - 37295
	FROM 
			--sAcademic.tLessonPlan LP
			----INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--inner JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			-- INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId

	WHERE 
		--(LP.BatchId = @rBatchId) 
		--AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		----AND ((LP.Id = @rId) OR (@rId = 0))
		--AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		--AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		--AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		----AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
		AND  ISNULL(EM.IsOtherUser,0) = 0
		--Added by dhananjay mantis : 43006	
		AND ISNULL(CM.IsObsolete,0) = 0
		AND ISNULL(DM.IsObsolete,0) = 0
		--Added by dhananjay mantis : 43006	
	ORDER BY
		LP.id 
	END
	ELSE
	BEGIN
	
	SELECT 
			--LP.Id,
			--TM.ClassId,
			--LP.DivisionId,
			--TM.SubjectId,
			--LP.TopicId,
			--LP.NoOfPeriodRequired,
			--LP.Objective,
			--LP.IndicativeHomework,
			--LP.Summary,
			--LP.StartDate,
			--LP.EndDate,
			--LP.IsCompleted,
			--LP.EmployeeId,
			--LP.BatchId,
			--LP.CreatedUserId,
			--LP.CreatedDateTime,
			--TM.Title AS TopicName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			--vTSD.SubjectName,
			----ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			--LP.LearningExperience,
			--LP.ToolsAndTechniques,
			--LP.EssentialMaterial,
			--LP.AssessmentQuestion ,
		 -- datepart(MONTH,Lp.StartDate) AS MonthId,
		 -- datename(MONTH,Lp.StartDate) AS Monthname
		  
		  LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			datepart(MONTH,Lp.StartDate) AS MonthId,
		    datename(MONTH,Lp.StartDate) AS Monthname,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4,
			--Added by dhananjay for mantis start - 37295
			ISNULL(LP.PeriodCount,0) AS PeriodCount,
			ISNULL(LP.Session,'') AS Session,
			ISNULL(LP.Remark,'') AS Remark,
			ISNULL(SM.Code,'') AS SubjectCode,
			BM.Title AS BatchName
			--Added by dhananjay for mantis end - 37295
	FROM 
			--sAcademic.tLessonPlan LP
			----INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--inner JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			-- INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = LP.BatchId--Added by dhananjay for mantis  - 37295
			
	WHERE 
		--(LP.BatchId = @rBatchId) 
		--AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		----AND ((LP.Id = @rId) OR (@rId = 0))
		--AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		--AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		--AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		----AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((@rStatus = 2) OR (LP.IsCompleted=@rIsCompleted))
		AND ((LP.StartDate >= @rStartDate) OR (ISNULL(@rStartDate,'')= ''))
		AND ((LP.StartDate <= @rEndDate)  OR (ISNULL(@rEndDate,'')= ''))
		AND  ISNULL(EM.IsOtherUser,0) = 0
		--Added by dhananjay mantis : 43006	
		AND ISNULL(CM.IsObsolete,0) = 0
		AND ISNULL(DM.IsObsolete,0) = 0
		--Added by dhananjay mantis : 43006	
	ORDER BY
		LP.id 
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pRptLessonPlanYearlyGet]

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

--declare @startdate datetime = '2018-01-01'
--declare @enddate datetime = '2018-12-01'

--declare @tmp table(mnt nvarchar(50),[days] int,[year] int,Objective nvarchar(1000))

--while (@startdate<=@enddate)
--begin
--	insert into @tmp values (datename(MONTH,@startdate),datediff(day, @startdate, dateadd(month, 1, @startdate)),year(@startdate),null)
--	set @startdate = DATEADD(month,1,@startdate)
--end
--select * from @tmp

declare @startdate datetime = '2018-01-01'
declare @enddate datetime = '2018-12-01'
SElect datepart(MONTH,Lp.StartDate) AS MonthId,datename(MONTH,Lp.StartDate) AS MONTH,LP.Objective,StartDate,EndDate
 from sAcademic.tLessonPlan LP
 WHERE StartDate between @startdate AND @enddate
 ORDER BY  datepart(MONTH,Lp.StartDate)  


END
EXEC [sAcademic].[pRptLessonPlanYearlyGet]

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pRptPreLessonPlanGet]

	 @rClassId int,
	 @rSubjectId int,
	 @rBatchId int,
	 @rEmployeeId bigint,
	 @rStartDate date='',
	 @rEndDate date=''
	 ,@rDivisionId int=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	If @rStartDate = '01/01/0001' OR @rStartDate IS NULL SET @rStartDate = ''
	If @rEndDate = '01/01/0001' OR @rEndDate IS NULL SET @rEndDate = ''

	SELECT 
			DISTINCT LP.Id,
			LP.ClassId,
			LP.SubjectId,
			--vTSD.DivisionId AS DivisionId,
			LP.SubTopic,
			LP.Objective,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			vTSD.ClassTitle +'-'+ vTSD.DivisionTitle AS ClassDivisionName,
			vTSD.SubjectName,
			EM.FirstName+' '+EM.LastName AS Name,
		ISNULL(LP.DivisionId,0) AS DivisionId,
		  datepart(MONTH,Lp.StartDate) AS MonthId,
		  datename(MONTH,Lp.StartDate) AS Monthname,
		  vTSD.SubjectName,
		  TM.Title AS TopicName      --Mantis - 32891
			
	FROM 
			sAcademic.tPreLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			 INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = LP.SubjectId
			AND vTSD.ClassId = LP.ClassId 
				AND ((vTSD.DivisionId = LP.DivisionId) OR (ISNULL(LP.DivisionId,-1) = -1)) --changes for mantis Id : 0032142
			AND vTSD.EmployeeId = LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId  --Mantis - 32891
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		--AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((LP.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.ClassTitle = @rClassTitle) OR (@rClassTitle = 0))
		AND ((LP.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		AND ((LP.DivisionId = @rDivisionId)OR(ISNULL(@rDivisionId,0)=0))
		AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
 AND  ISNULL(EM.IsOtherUser,0) = 0
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pTaskConsolidatedDashboardGet]

     @rOrgGroupId smallint,
     @rTypeId int,
     @rDate date,
     @rType nvarchar(20),
     @rCommonOrgGroupBatchId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

--Changes for Mantis Id: 0039838
DECLARE @lConfigValueDashboard nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValueDashboard = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValueDashboard, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValueDashboard <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValueDashboard <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

	---Attendance Task Wise 
	IF( @rType = 'Attendance')
		BEGIN
			IF(@rTypeId = 1)
				BEGIN
				SELECT 				
			OGM.Id AS OrgGroupId,
			OGM.Title AS OrgGroupName,
			 (
				 SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance FROM
				(SELECT 
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				WHERE  OGM.Id = O.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  NOT in 
				( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
				 -- IsInContext
				 AND BM.IsInContext = 1
				) Temp WHERE rowno=1
			 ) AS Pending,
			 (SELECT
					COUNT(DISTINCT DM.Id) AS TotalDivision
			  FROM
					sSetup.tDivisionMaster DM
					INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
					INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= SA.StudentId AND SM.StatusId =1
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				   
			  WHERE OGM.Id =OGMR.Id
			  AND DM.IsObsolete=0 AND OGMR.IsObsolete = 0 --AND BM.IsActive = 1 
					AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGMR.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
					-- IsInContext
					AND BM.IsInContext = 1
			) AS Total,
			(
			SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance FROM
				(SELECT 
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		   
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				WHERE  OGM.Id = O.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id   in 
				( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
				-- IsInContext
				AND BM.IsInContext = 1
				) Temp WHERE rowno=1) AS Complated
      FROM 
			sSetup.tOrgGroupMaster OGM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			
			INNER JOIN sStudent.tAcademic SA ON SA.OrgId = OM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				
					 WHERE 
		    OGM.IsObsolete = 0 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) 
			-- IsInContext
			AND BM.IsInContext = 1
	 GROUP BY
			OGM.Id, OGM.Title
	 ORDER BY
			OGM.Id	
				
				
		--			  SELECT 				
		--	OGM.Id AS OrgGroupId,
		--	OGM.Title AS OrgGroupName,
		--	 CONVERT(nvarchar(10),ISNULL(AT1.DivisionPresent,0)) AS Pending
		--	,CONVERT(nvarchar(10),ISNULL(AT2.TotalDivision,0)) AS Total
		--	,CONVERT(nvarchar(10),ISNULL(AT3.DoneAttendance,0)) AS Complated
  --    FROM 
		--	sSetup.tOrgGroupMaster OGM
		--	INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			
		--	INNER JOIN sStudent.tAcademic SA ON SA.OrgId = OM.Id
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		    
		--	LEFT JOIN --Attendance Pending
		--	(
		--	SELECT ISNULL(Count(StudentCount),0) AS DivisionPresent,OrgGroupId FROM
		--		(SELECT 
		--		(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
		--		ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
		--		FROM sStudent.tAcademic A
		--		INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		--		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--		WHERE  COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in 
		--		( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
		--		) Temp WHERE rowno=1  GROUP BY OrgGroupId
		--		) AT1 ON AT1.OrgGroupId = OGM.Id
		--	  --SELECT
		--		 --  COUNT(DISTINCT DM.Id) AS DivisionPresent,
		--		 --  OGM.Id AS OrgGroupId
		--	  --FROM
		--		 -- sSetup.tDivisionMaster DM
		--		 -- INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
		--		 -- INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--		 -- INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		 -- INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
		--		 -- INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		 -- INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--		 -- INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.Id 
		--	  --WHERE
		--		 -- SR.IsPresent = 1 AND SR.AttendanceDate = @rDate 
		--		 -- --AND BM.IsActive=1 
		--		 -- AND DM.IsObsolete=0 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
		--	  --GROUP BY
		--		 -- OGM.Id
		--	--) AT1 ON AT1.OrgGroupId = OGM.Id
		--	LEFT JOIN  --Attendance Total
		--	(
		--	  SELECT
		--			COUNT(DISTINCT DM.Id) AS TotalDivision,
		--			OGM.Id AS OrgGroupId
		--	  FROM
		--			sSetup.tDivisionMaster DM
		--			INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
		--			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
		--			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				   
		--	  WHERE
		--			DM.IsObsolete=0 AND OGM.IsObsolete = 0 --AND BM.IsActive = 1 
		--			AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
		--	  GROUP BY
		--			OGM.Id
		--	) AT2 ON AT2.OrgGroupId = OGM.Id
		--	LEFT JOIN --Attendance Done
		--	(
		--	SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance,OrgGroupId FROM
		--		(SELECT 
		--		(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
		--		ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
		--		FROM sStudent.tAcademic A
		--		INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		--		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--		WHERE  COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id   in 
		--		( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
		--		) Temp WHERE rowno=1  GROUP BY OrgGroupId
		--		) AT3 ON AT3.OrgGroupId = OGM.Id

			
	 --WHERE 
		--    OGM.IsObsolete = 0 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) 
	 --GROUP BY
		--	OGM.Id, OGM.Title,DivisionPresent,TotalDivision,DoneAttendance
	 --ORDER BY
		--	OGM.Id	
				END
				ELSE IF( @rTypeId = 11)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		,ClassOrderIndex,DivisionOrderIndex--add f or mantis : 0042058
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
						,CM.OrderIndex AS ClassOrderIndex --add f or mantis : 0042058
						,DM.OrderIndex AS DivisionOrderIndex --add f or mantis : 0042058
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId --add f or mantis : 0042058
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
				   -- IsInContext
				   AND BM.IsInContext = 1
						--AND A.Id not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						) Temp 
		WHERE 
						rowno=1
						ORDER BY OrgId, ClassOrderIndex,DivisionOrderIndex --add f or mantis : 0042058
					END
				ELSE IF( @rTypeId = 12)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		,ClassOrderIndex,DivisionOrderIndex--add f or mantis : 0042058
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
						,CM.OrderIndex AS ClassOrderIndex --add f or mantis : 0042058
						,DM.OrderIndex AS DivisionOrderIndex --add f or mantis : 0042058
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId --add f or mantis : 0042058
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
						AND A.Id not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						-- IsInContext
						AND BM.IsInContext = 1
						) Temp 
		WHERE 
						rowno=1
						ORDER BY OrgId,ClassOrderIndex,DivisionOrderIndex --add f or mantis : 0042058
					END
				ELSE IF (@rTypeId = 13)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		,ClassOrderIndex,DivisionOrderIndex--add f or mantis : 0042058
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
						,CM.OrderIndex AS ClassOrderIndex --add f or mantis : 0042058
						,DM.OrderIndex AS DivisionOrderIndex --add f or mantis : 0042058
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId --add f or mantis : 0042058
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
						AND A.Id  in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						-- IsInContext
						AND BM.IsInContext = 1
						) Temp 
		WHERE 
						rowno=1
						ORDER BY OrgId,ClassOrderIndex,DivisionOrderIndex --add f or mantis : 0042058
					END
		END
	IF(@rType = 'CW/HW')
			IF(@rTypeId=2)
				BEGIN
					SELECT 				
						OGM.Id AS OrgGroupId,
						OGM.Title AS OrgGroupName,
						ISNULL((
-- ClassworkAssigned								
					SELECT COUNT( AC.SubjectId) AS Classwork
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
					 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 1 
						AND (Classwork != '' OR  Classwork = NULL)
						-- IsInContext
						AND BM.IsInContext = 1 
						AND OGM.Id = OGM1.Id),0) 
					AS ClassworkAssigned,
					ISNULL((
--ClassworkNotAssigned
					SELECT COUNT(*)
					FROM sAcademic.tTeacherSubjectDivision TSD1 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId 
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
					INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
					Where 
					OGM1.Id= OGM.Id
					AND 
					NOT EXISTS(SELECT  *
					FROM sAcademic.tTeacherSubjectDivision TSD 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
					INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
					Where TSD.DivisionId = TSD1.DivisionId AND ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate)),0) 
					AS ClassworkNotAssigned,
					ISNULL((
--ClassworkNotApplicable
					SELECT COUNT( AC.SubjectId) AS Classwork 
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM1.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 2 
						AND COGBM.Id=@rCommonOrgGroupBatchId  
						-- IsInContext
						AND BM.IsInContext = 1
						AND OGM.Id = OGM1.Id),0) 
					AS ClassworkNotApplicable,
					ISNULL((
--HomeWorkAssigned
					SELECT COUNT( AC.SubjectId) AS Classwork
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
					 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 1 
						AND (HomeWork != '' OR HomeWork=NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
						AND OGM.Id = OGM1.Id),0) 
					AS HomeWorkAssigned,
					ISNULL((
--HomeWorkNotAssigned
					SELECT COUNT(*)
					FROM sAcademic.tTeacherSubjectDivision TSD1 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId 
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
					INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
					Where 
					OGM1.Id= OGM.Id
					AND 
					NOT EXISTS(SELECT  *
					FROM sAcademic.tTeacherSubjectDivision TSD 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
					INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
					Where TSD.DivisionId = TSD1.DivisionId AND BM.IsInContext = 1 AND ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND TSD.SubjectId = TSD1.SubjectId 
					AND AC.ClassWorkDate=@rDate)),0) 
					AS HomeWorkNotAssigned,
					ISNULL((
--HomeWorkNotApplicable
					SELECT COUNT( AC.SubjectId) AS Classwork 
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM1.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE
						AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 2
						AND COGBM.Id=@rCommonOrgGroupBatchId  
						-- IsInContext
						AND BM.IsInContext = 1
						AND OGM.Id = OGM1.Id),0) 
					AS HomeWorkNotApplicable
						 FROM 
								sSetup.tOrgGroupMaster OGM
								INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
								INNER JOIN sStudent.tAcademic A ON A.OrgId = OM.Id
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
								--LEFT JOIN 
								--(
								--  SELECT 
								--		COUNT(DISTINCT AC.SubjectId) AS Classwork,
								--		OGM.Id AS OrgGroupId
								--  FROM sAcademic.tClasswork AC
								--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
								--		INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
								--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
								--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
								--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
								--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
								--  WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
								--		AND AC.ClassWorkDate=@rDate AND ClassworkStatusId = 1 AND (Classwork != '' OR  Classwork = NULL)
								--  GROUP BY 
								--		OGM.Id
								--) CW1 ON CW1.OrgGroupId = OGM.Id
				--				LEFT JOIN(
				--					  SELECT
				--							COUNT(DISTINCT SM.Id) AS ClassWork,
				--							OGM.Id AS OrgGroupId
				--					  FROM
				--							sSetup.tSubjectMaster SM
				--							INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = SM.Id
				--							INNER JOIN sStudent.tAcademic SA ON SA.ClassId = CS.ClassId
				--							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--							INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--							INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				    
				--					  WHERE
				--							--BM.IsActive=1 AND 
				--							SM.IsObsolete=0 AND OGM.IsObsolete = 0 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
				--					  GROUP BY
				--							OGM.Id
				--						) CW2 ON CW2.OrgGroupId = OGM.Id

				--				--LEFT JOIN 
				--				--(
				--				--  SELECT 
				--				--		COUNT(DISTINCT AC.SubjectId) AS Classwork,
				--				--		OGM.Id AS OrgGroupId
				--				--  FROM sAcademic.tClasswork AC
				--				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--				--	   INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
				--				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				--				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				--				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				--				--  WHERE 
				--				--	   AC.ClassWorkDate=@rDate AND (Classwork = NULL OR Classwork='') AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--				--  GROUP BY 
				--				--		OGM.Id
				--				--) CW2 ON CW2.OrgGroupId = OGM.Id
				--				LEFT JOIN 
				--				(
				--				  SELECT 
				--						COUNT(DISTINCT AC.SubjectId) AS Classwork,
				--						OGM.Id AS OrgGroupId
				--				  FROM sAcademic.tClasswork AC
				--					   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--					   INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
				--					   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				--					   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				--					   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--					   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				--				  WHERE 
				--					   AC.ClassWorkDate=@rDate AND ClassworkStatusId = 2 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--				  GROUP BY 
				--						OGM.Id
				--				) CW3 ON CW3.OrgGroupId = OGM.Id
				--				LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					   
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 1 AND (HomeWork != '' OR HomeWork=NULL)
				--	   --AND BM.IsActive = 1 
				--	   AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW1 ON HW1.OrgGroupId = OGM.Id
				--LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					   
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 1 AND(HomeWork = NULL OR HomeWork='')
				--	   --AND BM.IsActive = 1 
				--	   AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW2 ON HW2.OrgGroupId = OGM.Id
				--LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					 
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 2 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW3 ON HW3.OrgGroupId = OGM.Id
						 WHERE 
								OGM.IsObsolete = 0  AND Bm.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
								-- IsInContext
								AND BM.IsInContext = 1
						 GROUP BY OGM.Id, OGM.Title
							--	OGM.Id, OGM.Title,CW1.Classwork,CW2.Classwork, CW3.Classwork,HW1.HomeWork,HW2.HomeWork, HW3.HomeWork
						 ORDER BY
								OGM.Id
				END
				ELSE IF( @rTypeId = 21)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
						,CM.OrderIndex AS ClassOrderIndex,-- add for mantis : 0042058
						DM.OrderIndex AS DivisionOrder -- add for mantis : 0042058
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId -- add for mantis : 0042058
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 1 
						AND (Classwork != '' OR  Classwork = NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
					Order By OMM.Id ,CM.OrderIndex,DM.OrderIndex --CM.OrderIndex add for mantis : 0042058
					END
				ELSE IF( @rTypeId = 22)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,
						EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OM.Id AS OrgId
						,CM.OrderIndex AS ClassOrderIndex,-- add for mantis : 0042058
						DM.OrderIndex AS DivisionOrder -- add for mantis : 0042058
						FROM sAcademic.tTeacherSubjectDivision TSD1 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId -- add for mantis : 0042058
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						Where ((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
						AND 
						NOT EXISTS(SELECT  *
						FROM sAcademic.tTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
						INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId

						Where TSD.DivisionId = TSD1.DivisionId AND BM.IsInContext = 1 AND((OGM1.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate )
						Order By OM.Id, CM.OrderIndex,DM.OrderIndex --CM.OrderIndex add for mantis : 0042058
					END
				ELSE IF (@rTypeId = 23)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
						,CM.OrderIndex AS ClassOrderIndex,-- add for mantis : 0042058
						DM.OrderIndex AS DivisionOrder -- add for mantis : 0042058
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId -- add for mantis : 0042058
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 2 
						AND (Classwork != '' OR  Classwork = NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
						Order By OMM.Id,CM.OrderIndex,DM.OrderIndex --CM.OrderIndex add for mantis : 0042058
					END
					ELSE IF (@rTypeId = 24)
						BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
						,CM.OrderIndex AS ClassOrderIndex,-- add for mantis : 0042058
						DM.OrderIndex AS DivisionOrder -- add for mantis : 0042058
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId -- add for mantis : 0042058
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 1 
						AND (HomeWork != '' OR HomeWork=NULL) 
						-- IsInContext
						AND BM.IsInContext = 1
					Order By OMM.Id, CM.OrderIndex,DM.OrderIndex --CM.OrderIndex add for mantis : 0042058
									
					END
				ELSE IF( @rTypeId = 25)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,
						EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,
						DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OM.Id AS OrgId
						FROM sAcademic.tTeacherSubjectDivision TSD1 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						Where ((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
						AND 
						NOT EXISTS(SELECT  *
						FROM sAcademic.tTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
						INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						Where TSD.DivisionId = TSD1.DivisionId AND BM.IsInContext = 1 AND((OGM1.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate )
						Order By DM.OrderIndex
					END
				ELSE IF (@rTypeId = 26)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact,DM.Id AS DivisionId,EM.Id AS EmployeeId,DM.ClassId,SM.Id AS SubjectId,OMM.Id AS OrgId
						,CM.OrderIndex AS ClassOrderIndex,-- add for mantis : 0042058
						DM.OrderIndex AS DivisionOrder -- add for mantis : 0042058
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId -- add for mantis : 0042058
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 2 
						AND (HomeWork != '' OR HomeWork=NULL)
						-- IsInContext
						AND BM.IsInContext = 1
						Order By OMM.Id, CM.OrderIndex,DM.OrderIndex --CM.OrderIndex add for mantis : 0042058
					END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pTeacherSubjectDivisionAdd]
	
	@rTeacherSubjectDivisionImpXml [nvarchar](max),
	@rEmployeeId bigint,
	@rSubjectId int,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rTeacherSubjectDivisionImpXml
BEGIN
	  
	BEGIN TRANSACTION
	
	 DELETE TSD FROM sAcademic.tTeacherSubjectDivision TSD 
	 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TSD.SubjectId
	 
	 WHERE   SubjectId=@rSubjectId AND SM.OrgId = @rOrgId AND EmployeeId =@rEmployeeId
	  
	 INSERT INTO sAcademic.tTeacherSubjectDivision
		(
			EmployeeId,
			SubjectId,
			DivisionId
			)
		SELECT
			EmployeeId,
			SubjectId,
			DivisionId
		FROM OPENXML (@loDoc, '/Table/TeacherSubjectDivision', 1)
		WITH ( 
				EmployeeId bigint,
				SubjectId int,
				DivisionId int
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAcademic].[pTeacherSubjectDivisionCopyToAnotherEmployee]
	
	@rExistingEmployeeId bigint,
	@rNewEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--this delete will affect all related modules
	DELETE FROM sAcademic.tTeacherSubject WHERE EmployeeId = @rNewEmployeeId
	DELETE FROM sAcademic.tTeacherSubjectDivision WHERE EmployeeId = @rNewEmployeeId

	INSERT INTO sAcademic.tTeacherSubject
           (
		   EmployeeId
           ,SubjectId
		   )
     SELECT
		    @rNewEmployeeId,
            SubjectId
	
		   FROM sAcademic.tTeacherSubject WHERE EmployeeId = @rExistingEmployeeId

	INSERT INTO sAcademic.tTeacherSubjectDivision
			   (
				EmployeeId
			   ,SubjectId
			   ,DivisionId
			   ,SubjectCordinatorEmployeeId
			   )

		 Select @rNewEmployeeId,
				SubjectId,
				DivisionId,
				null

		 FROM sAcademic.tTeacherSubjectDivision WHERE EmployeeId = @rExistingEmployeeId

		 SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pTeacherSubjectDivisionDetailsGet]
	 @rEmployeeId bigint=0,
	 @rOrgId int=0,
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rOrgGroupId int=0,
	 @rCoordinatorId bigint=0,
	 @rClassDivisionId nvarchar(MAX)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

SELECT 
    EE.EmployeeGroupId,
    TSD.EmployeeId AS TeacherId,
	[sHrm].[fEmployeeNameGet](ISNULL(EE.FirstName,''), ISNULL(EE.MiddleName,''), ISNULL(EE.LastName,''), ISNULL(OM.EmployeeNameFormatId,1)) AS TeacherName,
    --EE.EmployeeName AS TeacherName,    
    DM.ClassId,
    TSD.SubjectId,
    SM.Title AS SubjectName,
    DM.Code AS ClassDivisionName,
    OM.DisplayTitle AS Organization,
    Sm.Id,DM.Id As DivisionId ,
    EmployeeGroupId,
    EE.OrgId As OrgId,
	TSD.SubjectCordinatorEmployeeId,
	CASE WHEN TSD.SubjectCordinatorEmployeeId IS NULL THEN '' ELSE  (SELECT EmployeeName FROM  sHrm.vExtEmployee WHERE EmployeeId=TSD.SubjectCordinatorEmployeeId AND TSD.SubjectCordinatorEmployeeId IS NOT NULL AND ISNULL(IsOtherUser,0)=0 ) END AS CoordinatorName
FROM sAcademic.tTeacherSubjectDivision TSD 
	INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id  
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
	INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = TSD.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	
WHERE 
    OM.OrgGroupId=@rOrgGroupId 
	AND ((TSD.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0)) 
	AND((TSD.SubjectId = @rSubjectId) OR (@rSubjectId = 0)) 
	AND ((DM.ClassId = @rClassId) OR (@rClassId = 0)) 
	AND ((DM.Id = @rDivisionId) OR (@rDivisionId = 0))  
	AND ((OM.Id = @rOrgId) OR (@rOrgId = 0))  
	AND ((TSD.SubjectCordinatorEmployeeId = @rCoordinatorId) OR (@rCoordinatorId = 0))
	AND ((ISNULL(DM.Id,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassDivisionId,','))) OR (ISNULL(@rClassDivisionId,'')=''))
	AND StatusId =7 and ISNULL(EE.IsOtherUser,0)=0
	ORDER BY OM.Id,SM.OrderIndex,DM.OrderIndex

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pTeacherSubjectDivisionGet]

	 @rOrgId int,
	 @rSubject int,
	 @rEmployeeId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
Select 
Selected,
DivisionID,
ClassDivisionName,
EmployeeId,
SubjectId,
ClassOrderIndex,
DivisionIsObsolete
From
(

	SELECT 
			CASE WHEN TSD.DivisionId IS NULL THEN 1
			ELSE  0 END AS Selected,
		    vCD.DivisionId,
		    vCD.ClassDivisionName,
		    ISNULL(TSD.EmployeeId,0) AS EmployeeId,
		    ISNULL(TSD.SubjectId,0) AS SubjectId,
		    vCD.OrderIndex AS ClassOrderIndex,
			vCD.DivisionIsObsolete
	FROM 
			sAcademic.tTeacherSubjectDivision TSD
			RIGHT JOIN sSetup.vClassDivision vCD ON vCD.DivisionId = TSD.DivisionId AND vCD.IsObsolete=0 AND TSD.SubjectId = @rSubject AND TSD.EmployeeId = @rEmployeeId
	WHERE 
		(vCD.OrgId=@rOrgId)
		
)A Order By Selected,ClassOrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pTeacherSubjectGet]

	 @rOrgId int,
	 @rEmployeeId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
 
SELECT
SubjectId,
SubjectName,
EmployeeId,
Selected,
SubjectOrderIndex
FROM
(

	SELECT 
			CASE WHEN TS.SubjectId IS NULL THEN 1 
			ELSE 0 END AS Selected,
		    SM.Id AS SubjectId,
		    SM.Title AS SubjectName,
		    ISNULL(TS.EmployeeId,0) AS EmployeeId,
		    SM.OrderIndex AS SubjectOrderIndex
	FROM 
			sAcademic.tTeacherSubject TS 
			RIGHT JOIN sSetup.tSubjectMaster SM ON SM.Id = TS.SubjectId AND TS.EmployeeId = @rEmployeeId
	WHERE 
		(SM.OrgId=@rOrgId) 
)		 A  ORDER By Selected , SubjectOrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAcademic].[pTempOnlineLearningScopeAdd]
			@rTempOnlineLearningId NVARCHAR(MAX)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
            ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

If(@rIsDeleted=1)
BEGIN
	Delete from sAcademic.tTempOnlineLearningScope where TempOnlineLearningId=@rTempOnlineLearningId AND SourceTypeId=@rSourceTypeId 
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select TempOnlineLearningId from sAcademic.tTempOnlineLearningScope where TempOnlineLearningId=@rTempOnlineLearningId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sAcademic.tTempOnlineLearningScope
			(
				TempOnlineLearningId
			   ,SourceTypeId
			   ,SourceId
			    
			)
			VALUES
			(	
				@rTempOnlineLearningId
			   ,@rSourceTypeId
			   ,@rSourceId
			    
			)		
			SELECT 1 AS Result
		 
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pTempOnlineLearningScopeGet]
	 @rTempOnlineLearningId nvarchar(100)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName 

			FROM sAcademic.tTempOnlineLearningScope LS
			INNER JOIN sSetup.tOrganizationMaster OM ON LS.SourceId=OM.Id
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2021

			UNION ALL

			SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 

			FROM sAcademic.tTempOnlineLearningScope LS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON LS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2017

			UNION ALL

			SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tTempOnlineLearningScope LS
			INNER JOIN  sSetup.tClassMaster CM
				ON LS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			 
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2016

			UNION ALL

			SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 --DM.DisplayTitle AS Source,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tTempOnlineLearningScope LS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON LS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			 
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName 
			 
			FROM sAcademic.tTempOnlineLearningScope LS
		    INNER JOIN sStudent.tStudentMaster SM
				ON LS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON LS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			 
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 LS.TempOnlineLearningId,
			 LS.SourceTypeId,
			 LS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName 

			FROM  sAcademic.tTempOnlineLearningScope LS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON LS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			 
			WHERE LS.TempOnlineLearningId=@rTempOnlineLearningId AND LS.SourceTypeId=2001
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAcademic].[pTempOnlineLearningScopeRemove]
			
			@rTempOnlineLearningId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
            
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	Delete from sAcademic.tTempOnlineLearningScope where TempOnlineLearningId=@rTempOnlineLearningId AND SourceTypeId=@rSourceTypeId 
      AND SourceId=@rSourceId
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAcademic].[pTempOnlineLearningScopeValidate]
	 
        @rTempOnlineLearningId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempOnlineLearningId=@rTempOnlineLearningId ) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 	
				
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN  sStudent.vStudentAcademic SM
				ON CS.SourceId=SM.AcademicId AND CS.SourceTypeId= 2001
				where SM.OrgId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId )
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 	
				
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.Id AND CS.SourceTypeId=2001
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 	
			
		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.Id AND CS.SourceTypeId=2001
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 

			If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.Id AND CS.SourceTypeId=2001
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
			
			If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.Id AND CS.SourceTypeId= 2001
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Student already Exists' AS Msg
					RETURN
				END 		
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sAcademic.tTempOnlineLearningScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sAcademic.tTempOnlineLearningScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempOnlineLearningId=@rTempOnlineLearningId  )
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAcademic].[pTopicMasterAdd]
	 
        @rId int,
        @rNumber smallint,
        @rTitle nvarchar(100),
        @rSubjectId int,
        @rClassId int,
        @rOrgId smallint,
        @rCreatedUserId bigint,
		@rIsObsolete bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAcademic.tTopicMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sAcademic.tTopicMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tTopicMaster
		(
			Id,
			Number,
			Title,
			SubjectId,
			ClassId,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			----added by megha for 0024270
			IsObsolete
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rTitle,
			@rSubjectId,
			@rClassId,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tTopicMaster
	    SET
			Number=@rNumber,
			Title=@rTitle,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			OrgId=@rOrgId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			IsObsolete = @rIsObsolete
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAcademic].[pTopicMasterGet]

	 @rId int,
	 @rOrgId smallint,
	 @rClassId int,
	 @rSubjectId int,
	 @rEmployeeId bigint,
	 @rSourceTypeId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rSourceTypeId = 0)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex,
				--added by megha for 0024270
				ISNULL(TM.IsObsolete,0) AS IsObsolete,
				'' As StatusMessage
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				LEFT JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId 			
				--AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			--AND ((vTSD.EmployeeId = @rEmployeeId) OR (vTSD.EmployeeId = 0))
			--ORDER BY CM.OrderIndex
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
	ELSE IF (@rSourceTypeId = 95)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex,
				ISNULL(TM.IsObsolete,0) AS IsObsolete,
				'' As StatusMessage
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pXMLTopicMasterAdd]
	(
		@rXml  nvarchar(MAX),
		@rOrgId int,
		@rClassId int,
		@rSubjectId int,
		@rCreatedUserId bigint 
		
	)
AS

SET NOCOUNT ON

BEGIN

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		Number smallint,
		Title nvarchar(500)
	)

	INSERT INTO #tempTable
	(
		Number,
		Title
	)
	SELECT	
			A.Number,
			A.Title
	FROM OPENXML (@intDoc, '/Table/TopicMaster', 1)
	WITH
	(
			Number nvarchar(100) '@Number',
			Title nvarchar(100) '@Title' 
			 
	)A 
	 
	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable
	
	WHILE @lId <= @lCount 
	BEGIN

		DECLARE @lNumber smallint, @lTitle nvarchar(500), @lSubjectId Int, @lClassId int, @lOrgId smallint
		
		SELECT @lNumber = Number from #tempTable where  Id = @lId
		SELECT @lTitle = Title from #tempTable where  Id = @lId
		
		If Exists(select Id from sAcademic.tTopicMaster where Title=@lTitle AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
		BEGIN
			select -102 as Result, 'Title Already Exists' AS MSG
			RETURN
		END 
	
		If Exists(select Id from sAcademic.tTopicMaster where Number=@lNumber AND OrgId=@rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId)
		BEGIN
			select -103 as Result, 'Number Already Exists' AS MSG
			RETURN
		END 

			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

			print @lNextNumber

			INSERT INTO sAcademic.tTopicMaster
			(		Id,
					Number,
					Title,
					SubjectId,
					ClassID,
					OrgId,
					CreatedUserId,
					CreatedDateTime 
					
			)
			Values
			(	
					@lNextNumber,
					@lNumber,
					@lTitle,
					@rSubjectId,
					@rClassID,
					@rOrgId,
					@rCreatedUserId,
					sCommon.fGetDate()   
			)

		
	
		SELECT @lNextNumber = MAX(ID) FROM sAcademic.tTopicMaster Where OrgId=@rOrgId
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAcademic.tTopicMaster', @rCurrentNumber = @lNextNumber 

		SET @lId=@lId+1
		
	END
	EXEC sp_xml_removedocument @intDoc
	SELECT 1 as Result
	DROP Table #tempTable
	END TRY	

	BEGIN CATCH 
	SELECT -1 AS Result,error_message() AS MSG
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAcademic].[pXMLVendorMasterAdd]
    (
        @rXml NVARCHAR(MAX),		
        @rCreatedUserId BIGINT,
        @rOrgGroupId INT,
        @rLocationId bigint
    )
AS
BEGIN
    DECLARE @lInterrorCode INT, @intDoc INT;
    DECLARE @lNextNumber BIGINT;

    EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml;
	
    BEGIN TRY

        CREATE TABLE #tempTable (
            Id INT IDENTITY,
            Code NVARCHAR(100),
            Title NVARCHAR(100),
            Area NVARCHAR(100),
            City NVARCHAR(100),
            ContactPersonName NVARCHAR(300),
            Country NVARCHAR(100),
            CreditDays SMALLINT,
            Email NVARCHAR(100),
            FaxNumber NVARCHAR(100),
            PhoneNumberMobile NVARCHAR(100),
            PhoneNumberOffice NVARCHAR(100),
            State NVARCHAR(100),
            StreetOne NVARCHAR(100),
            StreetThree NVARCHAR(100),
            StreetTwo NVARCHAR(100),
            VendorCategoryId INT,
            ZipCode NVARCHAR(20)
        )

        INSERT INTO #tempTable (
        Code, Title, Area, City, ContactPersonName, Country, CreditDays,
        Email, FaxNumber, PhoneNumberMobile, PhoneNumberOffice, State,  StreetOne,
        StreetThree, StreetTwo, VendorCategoryId, ZipCode
		)
		SELECT 
			VM.Code,
			VM.Title,
			VM.Area,
			VM.City,
			VM.ContactPersonName,
			VM.Country,
			VM.CreditDays,
			VM.Email,
			VM.FaxNumber,
			VM.PhoneNumberMobile,
			VM.PhoneNumberOffice,
			VM.State,
			VM.StreetOne,
			VM.StreetThree,
			VM.StreetTwo,
			VM.VendorCategoryId,
			VM.ZipCode
    FROM OPENXML (@intDoc, '/Table/VendorMaster', 1)
    WITH
    (
        Code NVARCHAR(100) '@Code',
        Title NVARCHAR(100) '@Title',
        Area NVARCHAR(100) '@Area',
        City NVARCHAR(100) '@City',
        ContactPersonName NVARCHAR(300) '@ContactPerson',
        Country NVARCHAR(100) '@Country',
        CreditDays SMALLINT '@CreditDays',
        Email NVARCHAR(100) '@Email',
        FaxNumber NVARCHAR(100) '@FaxNumber',
        PhoneNumberMobile NVARCHAR(100) '@PhoneNumberMobile',
        PhoneNumberOffice NVARCHAR(100) '@PhoneNumberOffice',
        State NVARCHAR(100) '@State',
        StreetOne NVARCHAR(100) '@Address1',
        StreetThree NVARCHAR(100) '@Address3',
        StreetTwo NVARCHAR(100) '@Address2',
        VendorCategoryId INT '@VendorCategoryId',
        ZipCode NVARCHAR(20) '@ZipCode'
    )VM

    DECLARE @lCount INT, @lId INT;
    SELECT @lCount = COUNT(Id) FROM #tempTable;
    SELECT TOP 1 @lId = Id FROM #tempTable;

    WHILE @lId <= @lCount 
    BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tVendorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sProcurement.tVendorMaster
        SELECT @lNextNumber, Code, Title, 0, @rCreatedUserId, sCommon.fGetDate(), @rCreatedUserId, sCommon.fGetDate(), Area, City
			,ContactPersonName, Country, CreditDays, NULL,Email, FaxNumber,PhoneNumberMobile,
            PhoneNumberOffice, State,NULL, StreetOne, StreetThree, StreetTwo, VendorCategoryId, ZipCode, @rOrgGroupId, @rLocationId
        FROM 
            #tempTable 
        WHERE 
            Id = @lId;
        SET @lId = @lId + 1;
	END;

        EXEC sp_xml_removedocument @intDoc;
        SELECT 1 AS Result;
        DROP TABLE #tempTable;
    END TRY
    BEGIN CATCH
        SELECT -1 AS Result
    END CATCH;
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pAccountDelete]
		
		@rAccountId int,
		@rAccountingYearId int
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	-- Delete Transaction Detail
    DELETE TD 
		FROM sAccounting.tTransactionDetail TD
		INNER JOIN sAccounting.tTransaction T  
		ON T.Id=TD.TransactionId
		INNER JOIN sAccounting.tAccountingYearMaster AYM 
		ON AYM.Id=T.AccountingYearId
	WHERE 
		AYM.AccountId=@rAccountId
		AND ((AYM.Id=@rAccountingYearId) OR (@rAccountingYearId=0))
		
	-- Delete Transaction
    DELETE T 
		FROM sAccounting.tTransaction T
		INNER JOIN sAccounting.tAccountingYearMaster AYM 
		ON AYM.Id=T.AccountingYearId
	WHERE 
		AYM.AccountId=@rAccountId
		AND ((AYM.Id=@rAccountingYearId) OR (@rAccountingYearId=0))
	
	-- Delete Ledger Group Master 
    DELETE LGM 
		FROM sAccounting.tLedgerGroupMaster LGM
	WHERE 
		LGM.AccountId=@rAccountId
		AND ((LGM.AccountingYearId=@rAccountingYearId) OR (@rAccountingYearId=0))
		
	-- Delete Ledger Master 
    DELETE LM 
		FROM sAccounting.tLedgerMaster LM
		INNER JOIN sAccounting.tAccountingYearMaster AYM 
		ON AYM.Id=LM.AccountingYearId
	WHERE 
		AYM.AccountId=@rAccountId
		AND ((AYM.Id=@rAccountingYearId) OR (@rAccountingYearId=0))	
	
	-- Delete Accounting Year Master
    DELETE AYM 
		FROM sAccounting.tAccountingYearMaster AYM
	WHERE 
		AYM.AccountId=@rAccountId
		AND ((AYM.Id=@rAccountingYearId) OR (@rAccountingYearId=0))	
	
	-- Delete Accounting Year Master
	IF NOT EXISTS (SELECT 1 FROM  sAccounting.tAccountingYearMaster WHERE AccountId = @rAccountId)
	BEGIN
		DELETE AM 
			FROM sAccounting.tAccountMaster AM
		WHERE 
			AM.Id=@rAccountId
	END	
	
    SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pAccountingYearMasterAdd] 
	@rId INT
	,@rCode NVARCHAR(20)
	,@rTitle NVARCHAR(100)
	,@rFromDate DATE
	,@rToDate DATE
	,@rCreatedUserId BIGINT
	,@rUpdatedUserId BIGINT
	,@rOrgGroupId INT
	,@rAccountId INT
	,@rIsLocked BIT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		IF EXISTS (
				SELECT Id
				FROM sAccounting.tAccountingYearMaster
				WHERE (Title = @rTitle AND AccountId = @rAccountId)
					OR (Code = @rCode AND AccountId = @rAccountId)
				)
		BEGIN
			SELECT - 103 AS Result
			RETURN
		END

		BEGIN TRANSACTION

		DECLARE @lCount INT
		DECLARE @lNextNumber INT
		DECLARE @1CurruntAccountingYearId INT
		DECLARE @1MaxLedgerGroupId INT
		DECLARE @1MaxLedgerId INT
		DECLARE @1Count INT
		DECLARE @1LedgerGroupId INT
		DECLARE @1LedgerGroupName NVARCHAR(200)
		DECLARE @1LedgerId INT

		SELECT @lCount = ISNULL(COUNT(Id), 0)
		FROM sAccounting.tAccountingYearMaster
		WHERE AccountId = @rAccountId

		CREATE TABLE #TempLedgerGroupMaster (
			Id BIGINT identity
			,LedgerGroupName NVARCHAR(100)
			,LedgerId INT
			,LedgerGroupId INT
			)

		IF @lCount >= 1 --- If any year created get old ledger and Ledger group accordingly
		BEGIN
			SELECT @1CurruntAccountingYearId = MAX(Id)
			FROM sAccounting.tAccountingYearMaster
			WHERE OrgGroupId = @rOrgGroupId
				AND AccountId = @rAccountId

			SET @1CurruntAccountingYearId = ISNULL(@1CurruntAccountingYearId, 1)

			IF (@rId = 0)
			BEGIN
				--SELECT @1MaxLedgerGroupId =  sCommon.fGetIntIdForOrg(101,@rOrgGroupId)
				--SELECT @1MaxLedgerId = sCommon.fGetIntIdForOrg(101,@rOrgGroupId) 
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId
					,'sAccounting.tAccountingYearMaster'
					,0
					,1
					,1
					,@outNextNumber = @lNextNumber OUTPUT

				--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tAccountingYearMaster',@lNextNumber = @lNextNumber output
				INSERT INTO sAccounting.tAccountingYearMaster (
					Id
					,Code
					,Title
					,FromDate
					,ToDate
					,CreatedUserId
					,CreatedDateTime
					,AccountId
					,OrgGroupId
					,IsLocked
					)
				VALUES (
					@lNextNumber
					,@rCode
					,@rTitle
					,@rFromDate
					,@rToDate
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rAccountId
					,@rOrgGroupId
					,@rIsLocked
					)

				--END 
				INSERT INTO sAccounting.tLedgerGroupMaster
				SELECT CASE 
						WHEN @1CurruntAccountingYearId = 1
							THEN sCommon.fGetIntIdForOrg(Id, @rOrgGroupId)
						ELSE Id
						END
					,Code
					,Title
					,IsObsolete
					,LedgerMainGroupId
					,@lNextNumber
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rAccountId
					,@rOrgGroupId
				FROM sAccounting.tLedgerGroupMaster
				WHERE AccountingYearId = @1CurruntAccountingYearId

				--SELECT @1MaxLedgerGroupId = MAX(Id)  from sAccounting.tLedgerGroupMaster Where AccountingYearId = @lNextNumber
				INSERT INTO #TempLedgerGroupMaster
				SELECT LGM.Title
					,l.Id
					,LedgerGroupId AS LedgerGroup
				FROM sAccounting.tLedgerMaster l
				INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = l.LedgerGroupId
					AND lgm.AccountingYearId = @1CurruntAccountingYearId
				WHERE l.AccountingYearId = @1CurruntAccountingYearId
				ORDER BY l.Id DESC

				SELECT @1Count = COUNT(*)
				FROM #TempLedgerGroupMaster

				WHILE (@1Count > 0)
				BEGIN
					SELECT @1LedgerGroupName = LedgerGroupName
						,@1LedgerId = LedgerId
					FROM #TempLedgerGroupMaster
					WHERE Id = @1Count

					SELECT @1LedgerGroupId = Id
					FROM sAccounting.tLedgerGroupMaster
					WHERE Title = @1LedgerGroupName
						AND AccountingYearId = @lNextNumber

					INSERT INTO sAccounting.tLedgerMaster
					SELECT CASE 
							WHEN @1CurruntAccountingYearId = 1
								THEN sCommon.fGetIntIdForOrg(Id, @rOrgGroupId)
							ELSE Id
							END
						--@1MaxLedgerId + ROW_NUMBER() over(Order by Id asc)
						,Code
						,Title
						,IsObsolete
						,@1LedgerGroupId
						,0.00
						,LedgerTypeId
						,@lNextNumber
						,@rCreatedUserId
						,sCommon.fGetDate()
						,@rCreatedUserId
						,sCommon.fGetDate()
						,@rOrgGroupId
						,1 -- Added 1 for mantis 0035985 by Foram
					FROM sAccounting.tLedgerMaster
					WHERE AccountingYearId = @1CurruntAccountingYearId
						AND Id = @1LedgerId

					SET @1Count = @1Count - 1;
				END

				SELECT 1 AS RESULT
			END
			ELSE
			BEGIN
				SET @lNextNumber = @rId

				UPDATE sAccounting.tAccountingYearMaster
				SET Code = @rCode
					,Title = @rTitle
					,FromDate = @rFromDate
					,AccountId = @rAccountId
					,ToDate = @rToDate
					,UpdatedUserId = @rUpdatedUserId
					,UpdatedDateTime = sCommon.fGetDate()
					,IsLocked = @rIsLocked
				WHERE Id = @rId
			END

			SELECT @lNextNumber AS Result
		END
		ELSE --- If any year not created get old ledger and Ledger group from default
		BEGIN
			IF (@rId = 0)
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId
					,'sAccounting.tAccountingYearMaster'
					,0
					,1
					,1
					,@outNextNumber = @lNextNumber OUTPUT

				--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tAccountingYearMaster',@lNextNumber = @lNextNumber output
				INSERT INTO sAccounting.tAccountingYearMaster (
					Id
					,Code
					,Title
					,FromDate
					,ToDate
					,CreatedUserId
					,CreatedDateTime
					,AccountId
					,OrgGroupId
					,IsLocked
					)
				VALUES (
					@lNextNumber
					,@rCode
					,@rTitle
					,@rFromDate
					,@rToDate
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rAccountId
					,@rOrgGroupId
					,@rIsLocked
					)

				INSERT INTO sAccounting.tLedgerGroupMaster
				SELECT sCommon.fGetIntIdForOrg(Id, @rOrgGroupId)
					,Code
					,Title
					,IsObsolete
					,LedgerMainGroupId
					,@lNextNumber
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rAccountId
					,@rOrgGroupId
				FROM sAccounting.tLedgerGroupMaster
				WHERE OrgGroupId = 1
					AND AccountId = 1
					AND AccountingYearId = 1

				INSERT INTO sAccounting.tLedgerMaster
				SELECT sCommon.fGetIntIdForOrg(Id, @rOrgGroupId)
					,Code
					,Title
					,IsObsolete
					,sCommon.fGetIntIdForOrg(Id, @rOrgGroupId)
					,0.00
					,LedgerTypeId
					,@lNextNumber
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rOrgGroupId
					,1 -- Added 1 for mantis 0035985 by Foram
				FROM sAccounting.tLedgerMaster
				WHERE AccountingYearId = 1
					AND OrgGroupId = 1

				SELECT 1 AS RESULT
			END
			ELSE
			BEGIN
				SET @lNextNumber = @rId

				UPDATE sAccounting.tAccountingYearMaster
				SET Code = @rCode
					,Title = @rTitle
					,FromDate = @rFromDate
					,AccountId = @rAccountId
					,ToDate = @rToDate
					,UpdatedUserId = @rUpdatedUserId
					,UpdatedDateTime = sCommon.fGetDate()
					,IsLocked = @rIsLocked
				WHERE Id = @rId
			END

			SELECT @lNextNumber AS Result
		END

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pAccountingYearMasterGet]
	 
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rAccountId int,
	 @rOrgGroupId int	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  BEGIN 
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END	 
	SELECT 
	AYM.Id,
	AYM.Code,
	AYM.Title,
	AYM.FromDate,
	AYM.ToDate,
	ISNULL(AYM.AccountId,0) AS AccountId,
	Am.Title AS Account,
	ISNULL(IsLocked,0)  AS  IsLocked 
	     
  FROM 
       sAccounting.tAccountingYearMaster AYM
       INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId
        --INNER JOIN sSetup.tAffiliationMaster AM
        --ON DSM.AffiliationId= AM.Id 
  WHERE  
             ((AYM.Id = @rId) OR (@rId = 0))
        AND  ((AYM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((AYM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND  (AYM.AccountId=@rAccountId OR @rAccountId = 0)
		AND AYM.OrgGroupId = @rOrgGroupId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAccounting].[pAccountMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(100)
           ,@rTitle nvarchar(100)
           ,@rCreatedUserId bigint       
           ,@rOrgGroupId smallint
           ,@rIsActive bit,
           @rReportOrgTitle  nvarchar(200) ,
		@rSmallAddress1 nvarchar(200),
		@rSmallAddress2 nvarchar(200)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
    
	DECLARE @lNextNumber INT     

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tAccountMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sAccounting].[tAccountMaster]
           (
           [Id]
           ,[Code]
           ,[Title]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId]
           ,[IsActive],
           ReportOrgTitle,
			SmallAddress1,
			SmallAddress2
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate() 
           ,@rOrgGroupId 
           ,@rIsActive,
           @rReportOrgTitle,
			@rSmallAddress1,
			@rSmallAddress2
           ) 
           
           INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   113
		   ,@lNextNumber
		   ,@rCreatedUserId	    
           
           
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sAccounting].[tAccountMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			IsActive = @rIsActive,
			ReportOrgTitle=@rReportOrgTitle ,
		    SmallAddress1=@rSmallAddress1 ,
		    SmallAddress2=@rSmallAddress2 
	      
	      WHERE Id = @rId 	   
	 END  
		  SELECT @lNextNumber AS Result
	
		  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAccounting].[pAccountMasterGet]
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId int,
	 @rIsWildCardSearch bit = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN 
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	 
		SELECT [Id]
			  ,[Code]
			  ,[Title]   			  
			  ,[IsActive]
			  ,ReportOrgTitle
			  ,SmallAddress1
			  ,SmallAddress2
		FROM  [sAccounting].[tAccountMaster] AYM
        --INNER JOIN sSetup.tAffiliationMaster AM
        --ON DSM.AffiliationId= AM.Id 
  WHERE  
             ((AYM.Id = @rId) OR (@rId = 0))
        AND  ((AYM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((AYM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
        AND  OrgGroupId = @rOrgGroupId
        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pAccountwiseBalanceGet]
	@rOrgGroupId int,
	@rAccountId int,
	@rAccountYearTitle nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

Declare @LedgerId int 
Declare @LOpeningBalance Decimal (25,5)
Declare @OpeningBalance Decimal (25,5)
Declare @lClOsingBalance Decimal (25,5)
Declare @CreditBalance Decimal (25,5)
Declare @DebitBalance Decimal (25,5)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @LedgerName Nvarchar(150)
Declare @LedgerGroupId int
declare @lAccountYearId int
Declare @DecimalCount INT
declare @lStartDate Date,@lEndDate Date

	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
	
	IF OBJECT_ID('tempdb..#tempAccountYearMaster') IS NOT NULL DROP TABLE #tempAccountYearMaster

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

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

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

	CREATE TABLE #tempAccountYearMaster
	(	
 		Id INT IDENTITY (1, 1),
		AccountYearId int,
		AccountId int,
 		AccountYearName nvarchar(100),
	)

	INSERT INTO #tempAccountYearMaster
	select Id,AccountId,Code from sAccounting.tAccountingYearMaster where OrgGroupId = @rOrgGroupId AND AccountId = @rAccountId 
		AND IsLocked = 0 AND Title = @rAccountYearTitle
		
   CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(25,5), 
		Closing_Balance decimal(25,5),
		Transaction_Balance decimal(25,5) 
	) 
 	
	CREATE TABLE #tCashBankBookTemp
 	(	Id INT IDENTITY (1, 1),
 		LedgerId int,
 		LedgerName nvarchar(150),
 		OpBalance Decimal(25,5), 
 		CrBalance Decimal(25,5),
 		DrBalance Decimal(25,5),
 		ClBalance Decimal(25,5),
 		LedgerGroupId int
 	) 
	
	CREATE TABLE #tCashBankBook
 	(	Id INT IDENTITY (1, 1),
 		LedgerId int,
 		LedgerName nvarchar(150),
 		OpBalance Decimal(25,5),
 		LedgerTypeId int,
 		LedgerGroupId int,
		AccountYearId int
 	) 
	
	declare @lCount1 int
	SELECT @lCount1 =  COUNT(Id) FROM #tempAccountYearMaster
	
	WHILE (@lCount1 > 0)
	BEGIN	
		select @lAccountYearId= AccountYearId FROM #tempAccountYearMaster where Id = @lCount1 

		INSERT INTO #tCashBankBook
		select L.Id,L.Title,L.OpeningBalance,LedgerTypeId,L.LedgerGroupId,@lAccountYearId from sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		where LG.OrgGroupId = L.OrgGroupId AND L.IsObsolete=0 AND L.IsShowInDashBoard = 1  -- Mantis Id : 0035149	
		AND LG.OrgGroupId = @rOrgGroupId and L.AccountingYearId = @lAccountYearId AND LG.AccountingYearId = @lAccountYearId
		ORDER BY L.Id Asc

		SET @lCount1 = @lCount1 - 1
	END	 
	
	SELECT @lCount =  COUNT(Id) FROM #tCashBankBook    
	WHILE (@lCount > 0)
	BEGIN		
		SELECT @LedgerId =LedgerId,@LedgerName= LedgerName,@OpeningBalance=ISNULL(OpBalance,0),@LedgerGroupId = LedgerGroupId, 
		@lLedgerTypeId=LedgerTypeId, @lAccountYearId = AccountYearId FROM #tCashBankBook WHERE Id = @lCount				

		SELECT  @lStartDate = FromDate, @lEndDate = ToDate from sAccounting.tAccountingYearMaster where OrgGroupId = @rOrgGroupId AND Id = @lAccountYearId
		
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @lStartDate,@lEndDate,@rOrgGroupId,@lAccountYearId,@LedgerId,''

		 SELECT @LOpeningBalance=ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId And TD.LedgerId=@LedgerId
			AND T.AccountingYearId = @lAccountYearId 
			AND T.TransactionDate < @lStartDate

		SELECT @CreditBalance= -1 * ISNULL(SUM(AMOUNT), 0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 		 
			AND T.AccountingYearId = @lAccountYearId 
			AND T.TransactionDate >= @lStartDate AND T.TransactionDate <= @lEndDate
			AND TD.TransactionTypeId = 1 And TD.LedgerId=@LedgerId

		 SELECT @DebitBalance=  ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 
			AND T.AccountingYearId = @lAccountYearId 
			AND T.TransactionDate >= @lStartDate AND T.TransactionDate <= @lEndDate
			AND TD.TransactionTypeId = 2 And TD.LedgerId=@LedgerId

		SET @LOpeningBalance = @LOpeningBalance  +  @OpeningBalance

		SELECT  @lClOsingBalance = Closing_Balance FROM #tempUpdateClosingBalance WHERE LedgerId=@LedgerId

		INSERT INTO #tCashBankBookTemp  (LedgerId,LedgerName,OpBalance,CrBalance,DrBalance,ClBalance,LedgerGroupId)
		VALUES 	(@LedgerId,@LedgerName,@LOpeningBalance,@CreditBalance,@DebitBalance,@lClOsingBalance,@LedgerGroupId)
		
		SET @lCount = @lCount - 1
	END

		SELECT LedgerId,LedgerName, ([sAccounting].[fDecimalValueGet] (OpBalance, @DecimalCount)) AS OpBalance,
		  ([sAccounting].[fDecimalValueGet] (ISNULL(CrBalance,0), @DecimalCount)) AS CrBalance
		  ,([sAccounting].[fDecimalValueGet] (ISNULL(DrBalance,0), @DecimalCount)) AS DrBalance
		  ,([sAccounting].[fDecimalValueGet] (ClBalance, @DecimalCount)) AS ClBalance 
		FROM #tCashBankBookTemp

	DROP TABLE #tCashBankBook
	DROP TABLE #tCashBankBookTemp
	DROP TABLE #tempUpdateClosingBalance
	DROP TABLE #tempAccountYearMaster
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pBalanceSheet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

  --SELECT   '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
  --'' AS Builder1,
	 --    '' AS Builder2,
  --       '' AS IncomeGroup,
	 --    '' AS IncomeLedger,
	 --    '' AS Income,
	 --    '' AS ClosingBalance,
	 --    '' AS ExpenseGroup,
	 --    '' AS ExpenseLedger,
	 --    '' AS Expense,
	 --    '' AS OpeningBalance

Declare @lLedgerId int 
Declare @lOpeningBalance Decimal (12,2)
Declare @ltIncome Decimal (12,2)
Declare @ltExpense Decimal (12,2)
Declare @lInIncome Decimal(12,2)
Declare @lInClosing Decimal(12,2)
Declare @lExOpening Decimal(12,2)
Declare @lExExpense Decimal(12,2)
Declare @lGrossProfit Decimal(12,2)
Declare @lGrossLoss Decimal(12,2)
Declare @lCount int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
DECLARE @1ExpenceCount int
DECLARE @1IncomeCount int
DECLARE @lProfitLostAmount Decimal(12,2)
DECLARE @lOpenigCrAmount Decimal(12,2)
DECLARE @lOpeningDrAmount Decimal(12,2)
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)

	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
		
		SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
	
        CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 		    Transaction_Balance decimal(12,2)
 		)
 		  	
 		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
				
		
		---- Start Profilt Loss
			CREATE TABLE #TempExpenseGroup1
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroupId int,
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2) default 0.0,
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup1
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroupId int,
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2) default 0.0,
		   ClosingBalance decimal		 
		)
		
		INSERT INTO #TempExpenseGroup1
		SELECT 
		ISNULL(LG.Id,0)AS ExpenseGroupId,
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
 
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) > 0
		Order By LMG.Id	
		
		
		INSERT INTO #TempIncomeGroup1
        SELECT  		
        ISNULL(LG.Id,0)AS IncomeGroupId,
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) >  0
		Order By LMG.Id			
		

		SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup1
	    SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup1
		
		
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	          
			if @1ExpenceCount =  0 
			begin
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) 
				FROM #TempIncomeGroup1 IG 
			end
			else
			begin			
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) - isnull(SUM(Expense),0)
				FROM #TempIncomeGroup1 IG LEFT JOIN #TempExpenseGroup1 EG ON isnull(EG.Id,0) = isnull(IG.Id,0)
			end
	     END
	     ELSE
	     BEGIN
		 if @1ExpenceCount =  0 
			begin
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) 
				FROM #TempIncomeGroup1 IG 
			end
			else
			begin		
	           SELECT @lProfitLostAmount=isnull((isnull(SUM(Income),0)-isnull(SUM(Expense),0)),0)
	           FROM  #TempExpenseGroup1 EG   LEFT JOIN #TempIncomeGroup1 IG ON isnull(EG.Id,0) = isnull(IG.Id,0)
			end
	     END	
		
		SELECT @lOpenigCrAmount= SUM(OpeningBalance) from sAccounting.tLedgerMaster L 
		WHERE LedgerTypeId = 1 AND L.AccountingYearId = @rAccountingYearId

		SELECT @lOpeningDrAmount= SUM(OpeningBalance) from sAccounting.tLedgerMaster L 
		WHERE LedgerTypeId = 2 AND L.AccountingYearId = @rAccountingYearId
		
	
		---- End Profit Loass
		
		CREATE TABLE #TempExpenseGroup
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroupId int,
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2),
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroupId int,
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2),
		   ClosingBalance decimal		 
		)
		
		
		
		
		
		
		INSERT INTO #TempIncomeGroup
		SELECT 
		ISNULL(LG.Id,0)AS ExpenseGroupId,
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
	    
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 2 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) > 0 
		Order By LG.Title,LMG.Id	
		
		
		INSERT INTO #TempExpenseGroup
        SELECT  	
        ISNULL(LG.Id,0)AS IncomeGroupId,	
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 1 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) >  0
		Order By LG.Title,LMG.Id	
		
		

	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
		--- profit loss   
		IF  @lProfitLostAmount  is null 
		BEGIN
			SET @lProfitLostAmount  = 0
		END
	   IF @lProfitLostAmount > 0
	   BEGIN
			UPDATE TG SET Income = OpeningBalance 
			FROM #TempIncomeGroup TG INNER JOIN sAccounting.tLedgerMaster LM
			ON TG.IncomeLedger = LM.Title COLLATE DATABASE_DEFAULT  AND LM.Code = '4' AND LM.AccountingYearId = @rAccountingYearId
			INSERT INTO #TempIncomeGroup (IncomeGroup,IncomeLedger,Income,ClosingBalance) VALUES ('','Net Proft',@lProfitLostAmount,@lProfitLostAmount)
			--WHERE IncomeLedger = (SELECT TITLE FROM sAccounting.tLedgerMaster WHERE Code='4' AND
			--AccountingYearId=@rAccountingYearId)
	   END
	   ELSE
	   BEGIN
	  
	   	    UPDATE TG SET Expense = Isnull(lm.OpeningBalance,0) 			 
			FROM #TempExpenseGroup TG INNER JOIN sAccounting.tLedgerMaster LM
			ON  LM.Code = '4' AND LM.AccountingYearId = @rAccountingYearId	AND   TG.ExpenseLedger = LM.Title  	COLLATE DATABASE_DEFAULT 	
			INSERT INTO #TempExpenseGroup (ExpenseGroup,ExpenseLedger,Expense,OpeningBalance) VALUES ('','Net Loss',@lProfitLostAmount,@lProfitLostAmount)

			--UPDATE #TempExpenseGroup SET Expense =@lProfitLostAmount 
			--WHERE ExpenseLedger = (SELECT TITLE FROM sAccounting.tLedgerMaster WHERE Code='4' AND
			--AccountingYearId=@rAccountingYearId)
	   END
	   
	   -- Close Profit loss
		-- Opening Difference
  		IF (@lOpenigCrAmount > @lOpeningDrAmount )
		BEGIN
			INSERT INTO #TempExpenseGroup (ExpenseGroupId,ExpenseGroup,ExpenseLedger,Expense,OpeningBalance) VALUES (0,'','Diff In Opening Balance',@lOpenigCrAmount - @lOpeningDrAmount,0)
		END
		ELSE
		BEGIN
			INSERT INTO #TempIncomeGroup (IncomeGroupId,IncomeGroup,IncomeLedger,Income,ClosingBalance) VALUES (0,'','Diff In Opening Balance',@lOpeningDrAmount-@lOpenigCrAmount,0)
		END
		--end Opening Deifference
	   
	   
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	   	       
	           SELECT @ReportOrgTitle  AS OrgTitle,
	             @SmallAddress1 AS SmallAddress1,
				 @SmallAddress2 AS SmallAddress2, 
	             @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2, 
				   ISNULL(IncomeGroupId,0) AS IncomeGroupId,
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ([sAccounting].[fDecimalValueGet] (isnull(Income,0), @DecimalCount)) AS Income,	   
				   ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,           
	               ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	               ISNULL(ExpenseLedger,'') AS ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,	          
				   ([sAccounting].[fDecimalValueGet] (ISNULL(Expense,0.00), @DecimalCount)) AS Expense
	           FROM #TempIncomeGroup IG LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	             
	     END
	     ELSE
	     BEGIN
	         SELECT Isnull(@ReportOrgTitle,'')  AS OrgTitle,
	             isnull(@SmallAddress1,'') AS SmallAddress1,
				 isnull(@SmallAddress2,'') AS SmallAddress2, 
					 @rBuilder1 AS Builder1
					,@rBuilder2 AS Builder2, 
				   ISNULL(IncomeGroupId,0) AS IncomeGroupId,           
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ([sAccounting].[fDecimalValueGet] (ISNULL(Income,0), @DecimalCount)) AS Income,
	               ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,           
	               ExpenseGroup AS ExpenseGroup,
	               ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,
				   ([sAccounting].[fDecimalValueGet] (ISNULL(Expense,0), @DecimalCount)) AS Expense        
	           FROM  #TempExpenseGroup EG   LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id		        
	          
	     END	
	     
	     DROP TABLE #TempExpenseGroup
	     DROP TABLE #TempIncomeGroup
		
		
		
--SELECT  
		
--		ISNULL(CASE WHEN LMG.ID=2 THEN LG.Title END,'') AS IncomeGroup,
--		ISNULL(CASE WHEN LMG.ID=2 THEN L.Title END,'') AS IncomeLedger,
--		ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance,
--		ISNULL(CASE WHEN LMG.ID=2 THEN SUM(UC.Closing_Balance) END,0) AS Income,
--		ISNULL(CASE WHEN LMG.ID=1  THEN LG.Title END,'') AS ExpenseGroup,
--		ISNULL(CASE WHEN LMG.ID=1  THEN L.Title END,'') AS ExpenseLedger,
--		ISNULL(CASE WHEN LMG.ID=1 THEN SUM(UC.Closing_Balance) END,0) AS Expense,
--		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
--		FROM sAccounting.tLedgerMaster L 
--		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
--		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id 
--		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id AND LMG.Id in (1,2)		
--		GROUP BY LG.Title,LMG.ID
--		,L.Title	
--		Order By LMG.Id	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pBankReconsilationGet]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rLedgerMainGroupId [int],
	@rLedgerGroupId [int],
	@rAccountId int=0,
	@rChequeClearDate date
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--SELECT '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
--	   '' As Builder1,
--	   '' As Builder2,
--	   '' As Id,
--	   '' As LedgerId,
--	   '' As LedgerName,
--	   '' As OpBalance,
--	   '' As CrBalance,
--	   '' As DrBalance,
--	   '' As ClBalance,
--       '' As LedgerGroupId




Declare @LedgerId int 
Declare @LOpeningBalance Decimal (12,2)
Declare @OpeningBalance Decimal (12,2)
Declare @lClOsingBalance Decimal (12,2)
Declare @CreditBalance Decimal (12,2)
Declare @DebitBalance Decimal (12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @LedgerName Nvarchar(150)
Declare @LedgerGroupId int
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)
	

  
  SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
  
  
    DECLARE @1OpeningBalance DECIMAL(22,2)
    DECLARE @1ClosingBalance DECIMAl(22,2)
     
	CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)	    
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance
	FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId

  
 	SELECT @1OpeningBalance AS OPeningBalance,
 	T.TransactionDate,
 	T.Id,T.Chequeno,
 	ISNULL(T.ChequeDate,'1900-01-01') as ChequeDate,
 	L.Title, 
	ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * SUM(TD.AMOUNT) END,0) AS CREDIT,
	ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN SUM(TD.AMOUNT) END,0) AS DEBIT,
	ISNULL(IsChequeCleared,0) AS IsChequeCleared,
	ISNULL(T.ChequeClearDate,sCommon.fGetDate()) AS ChequeClearDate
	from sAccounting.tTransactionDetail TD 
	INNER JOIN sAccounting.tLedgerMAster L ON L.Id = TD.LedgerId 
	INNER JOIN sAccounting.tTransaction T ON T.Id = TD.TransactionId AND T.AccountingYearId = L.AccountingYearId
	Where TD.TransactionId IN
	(Select TD1.TransactionId FRom sAccounting.tTransactionDetail TD1 Where TD1.LedgerId = @rLedgerId)
	and TD.LedgerId <> @rLedgerId  AND T.AccountingYearId =@rAccountingYearId
	AND T.TransactionDate >= @rStartDate AND T.TransactionDate <= @rEndDate
	AND (T.ChequeClearDate = @rChequeClearDate OR ISNULL(@rChequeClearDate,'') = '')
	Group by T.TransactionDate,T.Id,T.Chequeno,T.ChequeDate,TD.TransactionTypeId,L.Title,IsChequeCleared,ChequeClearDate	
	
	drop table #tempUpdateClosingBalance
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pBankReconsilationUpdate]
	 
	        @rId bigint
           ,@rIsChequeCleared bit
           ,@rChequeClearDate Datetime
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	BEGIN TRANSACTION	
	BEGIN
	    UPDATE  [sAccounting].[tTransaction]
	    SET
              IsChequeCleared = @rIsChequeCleared
             ,ChequeClearDate = @rChequeClearDate             
        WHERE Id = @rId 	   
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pBudgetAdd]
	@rId	int,
	@rLedgerId	int,
	@rBudgetAmount	decimal(20, 5), --Changed for mantis : 32211 by Nilesh
	@rAccountingYearId	int,
	@rUserId	bigint,
	@rOrgGroupId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION
 DECLARE @lNextNumber int
 IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tBudget', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tBudget
	          (
	            Id,
				LedgerId,
				BudgetAmount,
				AccountingYearId,
				CreatedUserId,
				CreatedDateTime
			)
				VALUES
				( 
				@lNextNumber,
				@rLedgerId,
				@rBudgetAmount,
				@rAccountingYearId,
				@rUserId,
				sCommon.fGetDate()
				)
				SELECT 1 AS Result
	END
	  ELSE
	BEGIN
			UPDATE  sAccounting.tBudget SET
 
				LedgerId=@rLedgerId,
				BudgetAmount=@rBudgetAmount,
				UpdatedUserId=	@rUserId,
				UpdatedDateTime=sCommon.fGetDate()
			  WHERE AccountingYearId=@rAccountingYearId AND LedgerId=@rLedgerId AND Id=@rId
			  SELECT 11 AS Result
	END
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pBudgetGet]
	 
	 @rAccountYearId int,
	 @rAccountId int,
	 @rAccountYearString NVARCHAR(MAX)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
    select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from  sAccounting.tAccountingYearMaster WHERE  IsActive=0 AND AccountId=@rAccountId  AND Id!=@rAccountYearId
                    AND (ISNULL(Id,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rAccountYearString,',')) ) 
                    Order by Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
      If(ISNULL(@Cols,'')='')
		 BEGIN
		    SELECT -101 AS Result
		 RETURN
		 END
  set @query = 'SELECT Ladger,ISNULL(BudgetAmount,0) As BudgetAmount,ISNULL(LedgerId,0) AS LedgerId,ISNULL(BudgetId,0) AS BudgetId,' + @cols + ' from 
             (
               SELECT
                ISNULL(L.Title,'''') AS Ladger ,ISNULL(L.OpeningBalance,''0'') AS OpeningBalance,ISNULL(A.Title,'''') AS AccountingYear,ISNULL(L.Id,0) AS LedgerId,ISNULL(S.BudgetAmount,0) As BudgetAmount,ISNULL(S.BudgetId,0) As BudgetId
               FROM sAccounting.tLedgerMaster L
               INNER JOIN sAccounting.tAccountingYearMaster A ON A.Id=L.AccountingYearId 
               LEFT JOIN 
               (SELECT ISNULL(BudgetAmount,0) AS BudgetAmount,ISNULL(B.Id,0) AS BudgetId,ISNULL(B.LedgerId,0) AS LedgerId FROM sAccounting.tBudget B
                WHERE ((B.AccountingYearId=' + CAST(@rAccountYearId AS NVARCHAR(30))+'))) S ON  S.LedgerId=L.Id
		        WHERE 
	        ((A.AccountId=' + CAST(@rAccountId AS NVARCHAR(30))+'))
              ) x
            pivot 
            (
                SUM(OpeningBalance)
                for AccountingYear in (' + @cols + ')  
            ) p order by LedgerId'
            
  print @query
 execute(@query)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pCashBankBook]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rLedgerMainGroupId [int],
	@rLedgerGroupId [int],
	 @rAccountId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

Declare @LedgerId int 
Declare @LOpeningBalance Decimal (25,5) -- Changed for mantis 32211 by Nilesh
Declare @OpeningBalance Decimal (25,5)
Declare @lClOsingBalance Decimal (25,5) -- Changed for mantis 32211 by Nilesh
Declare @CreditBalance Decimal (25,5) -- Changed for mantis 32211 by Nilesh
Declare @DebitBalance Decimal (25,5) -- Changed for mantis 32211 by Nilesh
Declare @lCount int
Declare @lLedgerTypeId int
Declare @LedgerName Nvarchar(150)
Declare @LedgerGroupId int
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)
	
	Declare @DecimalCount INT
	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
	--EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,@rLedgerMainGroupId,@rISProfitLoss
  
  SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
  
  
   CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(25,5), -- Changed for mantis 32211 by Nilesh
		Closing_Balance decimal(25,5), -- Changed for mantis 32211 by Nilesh
		Transaction_Balance decimal(25,5) -- Changed for mantis 32211 by Nilesh
	) 
 	
	CREATE TABLE #tCashBankBookTemp
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			LedgerName nvarchar(150),
 			OpBalance Decimal(25,5), -- Changed for mantis 32211 by Nilesh
 			CrBalance Decimal(25,5), -- Changed for mantis 32211 by Nilesh
 			DrBalance Decimal(25,5), -- Changed for mantis 32211 by Nilesh
 			ClBalance Decimal(25,5), -- Changed for mantis 32211 by Nilesh
 			LedgerGroupId int
 		) 
	
	CREATE TABLE #tCashBankBook
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			LedgerName nvarchar(150),
 			OpBalance Decimal(25,5), -- Changed for mantis 32211 by Nilesh
 			LedgerTypeId int,
 			LedgerGroupId int
 		) 
 	INSERT INTO #tCashBankBook
	select L.Id,L.Title,L.OpeningBalance,LedgerTypeId,L.LedgerGroupId from sAccounting.tLedgerMaster L INNER JOIN 
	sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
	where LG.OrgGroupId = L.OrgGroupId AND
	(L.ID = @rLedgerId or @rLedgerId =0)
	AND LG.OrgGroupId = @rOrgGroupId and L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	AND (L.LedgerGroupId = @rLedgerGroupId OR @rLedgerGroupId=0)
	AND ((@rLedgerMainGroupId= 1 AND LG.Code IN ('2','3'))  OR (@rLedgerMainGroupId = 0) )
	
	ORDER BY L.Id Asc
	
	
	SELECT @lCount =  COUNT(Id) FROM #tCashBankBook    
	WHILE (@lCount > 0)
	BEGIN		
		SELECT @LedgerId =LedgerId,@LedgerName= LedgerName,@OpeningBalance=ISNULL(OpBalance,0),@LedgerGroupId = LedgerGroupId, 
		@lLedgerTypeId=LedgerTypeId FROM #tCashBankBook WHERE Id = @lCount				

		-- Update Closing Balance
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@LedgerId,'' -- change @rLedgerId to @LedgerId
		
		 SELECT @LOpeningBalance=ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId And TD.LedgerId=@LedgerId
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate < @rStartDate

		 SELECT @CreditBalance= -1 * ISNULL(SUM(AMOUNT), 0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 		 
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @rStartDate AND T.TransactionDate <= @rEndDate
			AND TD.TransactionTypeId = 1 And TD.LedgerId=@LedgerId
			
			
		 SELECT @DebitBalance=  ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 
		 --INNER JOIN sAccounting.tLedgerMaster L ON L.ID = TD.LedgerId
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @rStartDate AND T.TransactionDate <= @rEndDate
			AND TD.TransactionTypeId = 2 And TD.LedgerId=@LedgerId
			
			SET @LOpeningBalance = @LOpeningBalance  +  @OpeningBalance          
			
			SELECT  @lClOsingBalance = Closing_Balance FROM #tempUpdateClosingBalance WHERE LedgerId=@LedgerId
			
			--IF @lLedgerTypeId =1 
			--	BEGIN
			--		SET @lClOsingBalance = @LOpeningBalance  + @DebitBalance - @CreditBalance
			--	END
			--ELSE
			--	BEGIN
			--		SET @lClOsingBalance = @LOpeningBalance  - @DebitBalance + @CreditBalance
			--	END
							
			INSERT INTO #tCashBankBookTemp  (LedgerId,LedgerName,OpBalance,CrBalance,DrBalance,ClBalance,LedgerGroupId)
			VALUES 	(@LedgerId,@LedgerName,@LOpeningBalance,@CreditBalance,@DebitBalance,@lClOsingBalance,@LedgerGroupId)
			
			SET @lCount = @lCount - 1
		END	
	SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2, 
	 @rBuilder1 AS Builder1
		  ,@rBuilder2 AS Builder2,Id,LedgerId,LedgerName,
		  ([sAccounting].[fDecimalValueGet] (OpBalance, @DecimalCount)) AS OpBalance,
		  ([sAccounting].[fDecimalValueGet] (ISNULL(CrBalance,0), @DecimalCount)) AS CrBalance -- Changed for mantis 32211 by Nilesh
		  ,([sAccounting].[fDecimalValueGet] (ISNULL(DrBalance,0), @DecimalCount)) AS DrBalance,-- Changed for mantis 32211 by Nilesh
		   ([sAccounting].[fDecimalValueGet] (ClBalance, @DecimalCount)) AS ClBalance, -- Changed for mantis 32211 by Nilesh
		   LedgerGroupId FROM #tCashBankBookTemp	
	DROP TABLE #tCashBankBook
	DROP TABLE #tCashBankBookTemp
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pDashboardLedgerwiseClosingBalanceGet]
	@rOrgGroupId int,
	@rAccountYearTitle nvarchar(100)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
Declare @OpeningBalance decimal(25,5)
Declare @AccOpBalance decimal(25,5) = 0
Declare @ClosingBalance decimal(25,5)
Declare @TransactionBalance decimal(25,5)
Declare @LedgerId int 
Declare @lCount int
Declare @LedgerTypeId int,@lAccountYearId int,@lAccountId int
declare @lStartDate Date,	@lEndDate Date
	
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548

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

	CREATE TABLE #tempClosingBalance
 		(	
 		    Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(25,5),
 			Closing_Balance decimal(25,5),
 			Trasaction_Balance decimal(25,5) not null,
			AccountId int null,
			AccountingYearId int null
  		) 
	
	CREATE TABLE #tempLedger
 	    (
 	        Id INT IDENTITY (1, 1),
 			LedgerId int,
			LedgerName Nvarchar(100),
			AccountId int,
			AccountingYearId int,
 			AccOpBalance decimal(25,5),
 			LedgerTypeId int,
			StartDate DATE,
			EndDate DATE				 
 		) 

 	INSERT INTO #tempLedger
	SELECT LM.Id AS LedgerId ,LM.Title AS LedgerName ,AM.Id AS AccountId, LM.AccountingYearId, LM.OpeningBalance, LM.LedgerTypeId,AYM.FromDate,AYM.ToDate
	FROM sAccounting.tLedgerMaster LM
	INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id = LM.AccountingYearId
	INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
	WHERE LM.AccountingYearId IN (select Id from sAccounting.tAccountingYearMaster where Title = @rAccountYearTitle AND OrgGroupId = @rOrgGroupId AND IsLocked = 0) 
	AND AM.IsActive = 0 AND LM.IsObsolete = 0 AND LM.IsShowInDashBoard = 1		-- Mantis Id : 0035149	
	ORDER BY LM.Id Asc
	
	SELECT @lCount =  COUNT(Id) FROM #tempLedger
	
	WHILE (@lCount > 0)
	BEGIN
		SELECT @AccOpBalance =AccOpBalance,@LedgerTypeId= LedgerTypeId,@lAccountYearId=AccountingYearId,
		@lAccountId = AccountId, @lStartDate = StartDate, @lEndDate = EndDate, @LedgerId =LedgerId 
		FROM #tempLedger WHERE Id = @lCount

		INSERT INTO #tempClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Trasaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @lStartDate,@lEndDate,@rOrgGroupId,@lAccountYearId,@LedgerId,''
		
		--change for mantis: 39430, comment the update condition and add new update condition
		--UPDATE #tempClosingBalance SET AccountingYearId = @lAccountYearId, AccountId = @lAccountId WHERE  LedgerId = @LedgerId
		UPDATE #tempClosingBalance SET AccountingYearId = @lAccountYearId, AccountId = @lAccountId WHERE Id=(SELECT MAX(Id) FROM #tempClosingBalance WHERE LedgerId = @LedgerId)

		SET @lCount = @lCount - 1
	END
	
	DECLARE  @columns NVARCHAR(MAX) = '', @sql     NVARCHAR(MAX) = '';	
	SET @columns =(SELECT STUFF(
    ( SELECT  distinct ',' +  QUOTENAME(title) FROM sAccounting.tLedgerMaster where OrgGroupId = @rOrgGroupId AND IsObsolete = 0 AND IsShowInDashBoard = 1
					AND AccountingYearId IN (select Id from sAccounting.tAccountingYearMaster where Title = @rAccountYearTitle AND OrgGroupId = @rOrgGroupId)		-- Mantis Id : 0035149	
	FOR XML PATH('')), 1, 1, '') AS Ledgers)

	DECLARE  @columnsum NVARCHAR(MAX) = ''	
	SET @columnsum =(SELECT STUFF(
    (
        SELECT  distinct '+ ISNULL(' + QUOTENAME(Title) + ', 0) '
         FROM sAccounting.tLedgerMaster where OrgGroupId = @rOrgGroupId AND IsObsolete = 0 AND IsShowInDashBoard = 1
					AND AccountingYearId IN (select Id from sAccounting.tAccountingYearMaster where Title = @rAccountYearTitle AND OrgGroupId = @rOrgGroupId)		-- Mantis Id : 0035149	
        FOR XML PATH('')
    ), 1, 1, '') AS Ledgers)
	
	DECLARE  @columnisnull NVARCHAR(MAX) = ''	
	SET @columnisnull =(SELECT STUFF(
    (
        SELECT  distinct ', [sAccounting].[fDecimalValueGet](ISNULL(' + QUOTENAME(Title) + ', 0), '+CAST(@DecimalCount AS NVARCHAR(20)) +') AS ' + QUOTENAME(Title)
         FROM sAccounting.tLedgerMaster where OrgGroupId = @rOrgGroupId AND IsObsolete = 0 AND IsShowInDashBoard = 1
						AND AccountingYearId IN (select Id from sAccounting.tAccountingYearMaster where Title = @rAccountYearTitle AND OrgGroupId = @rOrgGroupId)		-- Mantis Id : 0035149	
        FOR XML PATH('')
    ), 1, 2, '') AS Ledgers)
	
	-- construct dynamic SQL
  SET @sql ='
  SELECT AccountId,Account, ' + @columnisnull + ', [sAccounting].[fDecimalValueGet]('+@columnsum + ','+CAST(@DecimalCount AS NVARCHAR(20))+') AS Total FROM ( 
  SELECT * FROM
  (
  SELECT  
		TCB.Closing_Balance AS Closing_Balance
		,AM.Title AS Account, AM.Id AS AccountId, LM.LedgerName
		FROM #tempClosingBalance TCB
		INNER JOIN #tempLedger LM ON LM.LedgerId=TCB.LedgerId AND TCB.AccountingYearId= LM.AccountingYearId AND TCB.AccountId = LM.AccountId
		INNER JOIN sAccounting.tAccountingYearMaster AY ON AY.Id = LM.AccountingYearId
		INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AY.AccountId
		where AM.IsActive = 0
		) AS Table1
  PIVOT(
    SUM(Closing_Balance)
    FOR LedgerName IN ('+ @columns +')
  ) AS pivot_table ) AS A';
  print @sql
  EXECUTE sp_executesql @sql;

	drop table #tempClosingBalance
	drop table #tempLedger
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


 
CREATE OR ALTER PROCEDURE [sAccounting].[pDayBook]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	  @rAccountId int=0
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
   
    --DECLARE @1OpeningBalance DECIMAL(22,2) --Commented for mantis : 32211 by Nilesh
    --DECLARE @1ClosingBalance DECIMAl(22,2) --Commented for mantis : 32211 by Nilesh
	DECLARE @1OpeningBalance DECIMAL(22,5) --Added for mantis : 32211 by Nilesh
    DECLARE @1ClosingBalance DECIMAl(22,5) --Added for mantis : 32211 by Nilesh

	/*****************Added for mantis 32211 by Nilesh************************/
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
   
   IF(@rLedgerId > 0)
    BEGIN   
    
    CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		--Temp_Op_Balance decimal(12,2), --Commented for mantis : 32211 by Nilesh
		--Closing_Balance decimal(12,2), --Commented for mantis : 32211 by Nilesh
		--Transaction_Balance decimal(12,2),--Commented for mantis : 32211 by Nilesh
		Temp_Op_Balance decimal(20,5), --Added for mantis : 32211 by Nilesh
		Closing_Balance decimal(20,5), --Added for mantis : 32211 by Nilesh
		Transaction_Balance decimal(20,5) --Added for mantis : 32211 by Nilesh
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId
    
    END
    	

	SELECT 
	@rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,
	T.TransactionDate,
	T.VoucherNumber,
	L.TITLE,
	VTM.Title As VoucherType,
	T.Narration,
	--ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0) AS CREDIT, --Commented for mantis : 32211 by Nilesh
	--ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0) AS DEBIT, --Commented for mantis : 32211 by Nilesh
	([sAccounting].[fDecimalValueGet] ((ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0)),@DecimalCount)) CREDIT, --Added for mantis : 32211 by Nilesh
	([sAccounting].[fDecimalValueGet] ((ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0)),@DecimalCount)) DEBIT, --Added for mantis : 32211 by Nilesh
	CASE WHEN TD.TransactionTypeId = 1 THEN 'CREDIT' ELSE 'DEBIT' END AS TOBY, 
	--ISNULL(@1OpeningBalance,0) AS OpeningBalance, --Commented for mantis : 32211 by Nilesh
	--ISNULL(@1ClosingBalance,0) AS ClosingBalance, --Commented for mantis : 32211 by Nilesh
	([sAccounting].[fDecimalValueGet] ((ISNULL(@1OpeningBalance,0)),@DecimalCount)) OpeningBalance, --Added for mantis : 32211 by Nilesh
	([sAccounting].[fDecimalValueGet] ((ISNULL(@1ClosingBalance,0)),@DecimalCount)) ClosingBalance, --Added for mantis : 32211 by Nilesh
	AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id 
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	
	WHERE (T.TransactionDate >= @rStartDate)  AND
	(T.TransactionDate <= @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND	
	(TD.LedgerId =  @rLedgerId  OR @rLedgerId  =0) AND
	T.AccountingYearID=@rAccountingYearId AND
	 L.AccountingYearId = @rAccountingYearId
	 AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And TransactionTypeId <> 2)	 
	 or (L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE = '2' AND VTM.Title ='Journal Voucher' And TransactionTypeId <> 2)
	 )

	AND (T.AccountId=@rAccountId OR @rAccountId=0 )  
	 
	GROUP BY 	T.TransactionDate,TD.TransactionTypeId,T.VoucherNumber,T.Id,
				L.Title,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pDayBookTShaph]
	--@rStartDate Date,
	--@rEndDate Date,
	--@rOrgId int = 0,
	--@rAccountingYearId [int]
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

Declare @TransactionDate date
Declare @OpeningBalance decimal(12,2)
Declare @CreditAmt decimal(12,2)
Declare @DebitAmt decimal(12,2)
Declare @CreditTitle nvarchar(150)
Declare @DebitTitle nvarchar(150)
Declare @ClosingBalance decimal(12,2)
Declare @lCount int
Declare @LedgerTypeId int
	
	CREATE TABLE #tempDayBookTShaph
 		(	Id INT IDENTITY (1, 1),
 			TransactionDate date,
 			OpeningBalance decimal(12,2),
 			CreditAmt decimal(12,2),
 			CreditTitle nvarchar(150),
 			DebitAmt decimal(12,2),
 			DebitTitle nvarchar(150),
 			ClosingBalance decimal(12,2)
 		) 
 	INSERT INTO #tempDayBookTShaph
	SELECT  T.TransactionDate, OpeningBalance AS OpeningBalance,
	ISNULL(CASE WHEN ISNULL(SUM(TD.AMOUNT),0) > 0 THEN SUM(TD.AMOUNT) END,0) AS CREDIT,
	ISNULL(CASE WHEN ISNULL(SUM(TD.AMOUNT),0) > 0 THEN LM.Title END,'') AS CREDITTITLE,
	ISNULL(CASE WHEN ISNULL(SUM(TD.AMOUNT),'') < 0 THEN -1*SUM(TD.AMOUNT) END,0) AS DEBIT,   
	ISNULL(CASE WHEN ISNULL(SUM(TD.AMOUNT),'') < 0 THEN LM.Title END,'') AS DEBITTITLE,
	OpeningBalance AS ClosingBalance
	FROM sAccounting.tTransaction T
	INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
	INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId
	GROUP BY T.TransactionDate,OpeningBalance,LM.Title

	SELECT * FROM #tempDayBookTShaph	
	SELECT @lCount =  COUNT(Id) FROM #tempDayBookTShaph
	WHILE (@lCount > 0)
	BEGIN
		SET @lCount = @lCount-1
	END	
	SELECT 1 AS Result		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
--Commented on 19/06/2025 - No StoreLocationId in table
--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
 SELECT 0 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pExpenseGet]
	@rId [int] = 0,
	@rRemark [nvarchar](20) = '',
	@rFromDate Date = '',
	@rToDate Date = '',
	@rExpenseGroupId [int] = 0,
	@rOrgId smallint
	--@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 

	 SELECT E.Id,
			E.Amount,
			E.Remark,
			E.CreatedUserId,
			E.CreatedDateTime,			 
			E.UpdatedUserId,
			E.UpdatedDateTime,
			E.ExpenseDate,
			E.ExpenseGroupId,
			EGM.Title AS ExpenseGroupName
	   FROM sAccounting.tExpense E INNER JOIN sAccounting.tExpenseGroupMaster EGM
	   ON E.ExpenseGroupId = EGM.Id
	  WHERE ((E.Id = @rId) OR (@rId = 0))	  
	   AND ((E.ExpenseDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))
	    AND ((E.ExpenseDate <= @rToDate ) OR (ISNULL(@rToDate, '') = ''))
	   AND ((E.ExpenseGroupId = @rExpenseGroupId) OR (@rExpenseGroupId = 0))
	   AND 	E.OrgId = 	@rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pExpenseGroupMasterAdd]
	 
	    @rOrgId int,
        @rId int,  
        @rCode nvarchar(100),
        @rTitle nvarchar(100),  
		@rIsObsolete bit,	
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
	 
		If Exists(select Id from sAccounting.tExpenseGroupMaster  where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
			If Exists(select Id from sAccounting.tExpenseGroupMaster  where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END
	END
	ELSE
	BEGIN
			If  Exists(select Id from  sAccounting.tExpenseGroupMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from  sAccounting.tExpenseGroupMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
	

	END
	
	
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpenseGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tExpenseGroupMaster
		(
			OrgId,
			Id, 
			Code,
			Title, 
			IsObsolete,			
		    CreatedUserId, 
		    CreatedDateTime, 
		    UpdatedUserId, 
            UpdatedDateTime
		)
	VALUES
		(
		    @rOrgId ,
			@lNextNumber , 
			@rCode ,      
			@rTitle ,	
			@rIsObsolete,				
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate()									
		)
		
		   SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tExpenseGroupMaster
	    SET
			Code=@rCode, 
	        Title=@rTitle,
	        IsObsolete=@rIsObsolete,
	        UpdatedUserId=@rCreatedUserId, 
            UpdatedDateTime=sCommon.fGetDate()	        			    
	      WHERE Id = @rId
	       SELECT 11 AS Result
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pExpenseGroupMasterGet]

	 @rId int,
	  @rOrgId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			EG.Id,
			EG.Code	,	
			EG.Title,				
		    EG.OrgId,
		    EG.CreatedUserId,
		    EG.CreatedDateTime,
		    EG.IsObsolete
		    
	FROM 
			sAccounting.tExpenseGroupMaster EG
	WHERE 
		(EG.OrgId = @rOrgId)
		AND	((EG.Id = @rId) OR (@rId = 0))
		AND ((EG.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((EG.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		
		ORDER BY EG.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pExpenseListGet]
(
	@rOrgId smallint,
	  @rBatchId int,
    @rId int = 0,
    @rEmployeeId  bigint=0,      
    @rExpenseGroupId int=0,   
     @rFromDate date,
    @rTodate date,       
    @rStatusId int=0
 )
AS
SET NOCOUNT ON

BEGIN
    
	SELECT 
		  
			E.Id AS ExpenseId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			E.Amount,
			E.Remark,			
			E.ExpenseDate,
			E.ExpenseGroupId,
			EGM.Title AS ExpenseGroupName,
			E.CreatedUserId,
			E.CreatedDateTime,			 
			E.UpdatedUserId,
			E.UpdatedDateTime,
			E.StatusReason,
			ISNULL(E.StatusId,0) AS StatusId,
			ISNULL(SM.Title,'Pending') AS StatusName
		  --,(ISNULL((Select NoOfLeave FROM sHrm.tLeaveTypeGradeSettings LGS WHERE LGS.EmployeeGradeId = EM.EmployeeGradeId AND LGS.LeaveTypeId = L.LeaveTypeId),0) - L.NoOfLeave) AS AvailableLeave
      
  FROM 
			sAccounting.tExpense E
	
	  INNER JOIN sAccounting.tExpenseGroupMaster EGM ON EGM.Id = E.ExpenseGroupId
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = E.EmployeeId 
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = E.StatusId
	  --INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.EmployeeGradeId = EM.EmployeeGradeId AND LTGS.LeaveTypeId = L.LeaveTypeId 
  WHERE 
		  (E.Id = @rId OR @rId = 0)
		  AND (E.OrgId = @rOrgId OR @rOrgId = 0)
		    AND (E.BatchId = @rBatchId OR @rBatchId = 0)
      AND (E.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((E.ExpenseDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((E.ExpenseDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
      AND (E.ExpenseGroupId = @rExpenseGroupId OR @rExpenseGroupId = 0)      
      
    
      AND (E.StatusId = @rStatusId OR @rStatusId = 0)
      Order By ExpenseDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pExpenseListingGet]
(
	@rOrgId smallint,
	@rOrgGroupBatchId int,
    @rId int = 0,
    @rEmployeeId  bigint=0,      
    @rExpenseGroupId int=0,
    @rEmployeeCode nvarchar(100),
    @rEmployeeName nvarchar(100) ,
    @rFromDate date,
    @rTodate date,     
    @rStatusId int=0,
    @rIsSearchHierarchWise smallint = 0
 )
AS
SET NOCOUNT ON

BEGIN
	
	CREATE TABLE #TempEmployeeId
    (
		EmployeeId bigint
    )
    
    IF(@rIsSearchHierarchWise = 1)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			  EmployeeID
			 FROM sHrm.tEmployeeJobDetail
			 WHERE ((EmployeeManagerId = @rEmployeeId) OR (@rEmployeeId = 0))
					AND ((OrgId = @rOrgId) OR (@rOrgId = 0))

			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E
		
		--Select * from #TempEmployeeId return
    END
	
	ELSE
    BEGIN
		INSERT INTO #TempEmployeeId(EmployeeId)
		SELECT EmployeeId FROM sHrm.tEmployeeJobDetail EJD 
		WHERE ((EJD.EmployeeManagerId = @rEmployeeId) OR (@rEmployeeId = 0))
			   AND ((OrgId = @rOrgId) OR (@rOrgId = 0))
    END
	
  IF(@rIsSearchHierarchWise = 0)
  BEGIN
	SELECT 
		  
			E.Id AS ExpenseId,
			E.EmployeeId,
			E.Amount,
			E.Remark,
			E.CreatedUserId,
			E.CreatedDateTime,			 
			E.UpdatedUserId,
			E.UpdatedDateTime,
			E.ExpenseDate,
			E.ExpenseGroupId,
			EGM.Title AS ExpenseGroupName,
			EM.EmployeeName,
			EM.Code AS EmployeeCode,
			E.StatusReason,
			ISNULL(E.StatusId,0) AS StatusId,
			ISNULL(SM.Title,'Pending') AS StatusName,
			OM.DisplayTitle AS OrganizationName,
			E.ActionByEmployeeId,
			CASE WHEN ISNULL(E.ActionByEmployeeId,0) = 0 AND E.StatusId = 630 THEN NULL
			WHEN E.ActionByEmployeeId = 0 AND E.StatusId != 630 THEN US.DisplayTitle
			ELSE EM.FirstName + ' ' + EM.LastName END AS ActionByEmployee 
		  --,(ISNULL((Select NoOfLeave FROM sHrm.tLeaveTypeGradeSettings LGS WHERE LGS.EmployeeGradeId = EM.EmployeeGradeId AND LGS.LeaveTypeId = L.LeaveTypeId),0) - L.NoOfLeave) AS AvailableLeave
      
  FROM 
			sAccounting.tExpense E
		    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = E.BatchId	
		    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		    INNER JOIN sAccounting.tExpenseGroupMaster EGM ON EGM.Id = E.ExpenseGroupId
		    INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = E.EmployeeId 
		    INNER JOIN sCommon.tStatusMaster SM ON SM.Id = E.StatusId
		    INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.EmployeeId
		    LEFT JOIN sSecurity.tUser US ON US.Id = E.UpdatedUserId
	        --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = E.OrgId
	        --INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.EmployeeGradeId = EM.EmployeeGradeId AND LTGS.LeaveTypeId = L.LeaveTypeId 
  WHERE 
		  (E.Id = @rId OR @rId = 0)
		  --AND (E.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		  AND ((E.ExpenseDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		  AND ((E.ExpenseDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		  AND (E.ExpenseGroupId = @rExpenseGroupId OR @rExpenseGroupId = 0)      
		  AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		  AND ((E.OrgId = @rOrgId) OR (@rOrgId = 0))
		  --AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
		  AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
		  AND (E.StatusId = @rStatusId OR @rStatusId = 0)
  ORDER BY ExpenseDate DESC
  END
  
  IF(@rIsSearchHierarchWise = 1)
  BEGIN
	SELECT 
		  
			E.Id AS ExpenseId,
			E.EmployeeId,
			E.Amount,
			E.Remark,
			E.CreatedUserId,
			E.CreatedDateTime,			 
			E.UpdatedUserId,
			E.UpdatedDateTime,
			E.ExpenseDate,
			E.ExpenseGroupId,
			EGM.Title AS ExpenseGroupName,
			EM.EmployeeName,
			EM.Code AS EmployeeCode,
			E.StatusReason,
			ISNULL(E.StatusId,0) AS StatusId,
			ISNULL(SM.Title,'Pending') AS StatusName,
			 OM.DisplayTitle AS OrganizationName,
			 E.ActionByEmployeeId,
			 CASE WHEN ISNULL(E.ActionByEmployeeId,0) = 0 AND E.StatusId = 630 THEN NULL
			 WHEN E.ActionByEmployeeId = 0 AND E.StatusId != 630 THEN US.DisplayTitle
			 ELSE EM.FirstName + ' ' + EM.LastName END AS ActionByEmployee 
		  --,(ISNULL((Select NoOfLeave FROM sHrm.tLeaveTypeGradeSettings LGS WHERE LGS.EmployeeGradeId = EM.EmployeeGradeId AND LGS.LeaveTypeId = L.LeaveTypeId),0) - L.NoOfLeave) AS AvailableLeave
      
  FROM 
			sAccounting.tExpense E
		    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = E.BatchId	
		    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		    INNER JOIN sAccounting.tExpenseGroupMaster EGM ON EGM.Id = E.ExpenseGroupId
		    INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = E.EmployeeId 
		    INNER JOIN sCommon.tStatusMaster SM ON SM.Id = E.StatusId
		    INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.EmployeeId
		    LEFT JOIN sSecurity.tUser US ON US.Id = E.UpdatedUserId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = E.OrgId
			--INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.EmployeeGradeId = EM.EmployeeGradeId AND LTGS.LeaveTypeId = L.LeaveTypeId 
  WHERE 
		  (E.Id = @rId OR @rId = 0)
		  --AND (E.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		  AND ((E.ExpenseDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		  AND ((E.ExpenseDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		  AND (E.ExpenseGroupId = @rExpenseGroupId OR @rExpenseGroupId = 0)      
		  -- AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		  -- AND ((E.OrgId = @rOrgId) OR (@rOrgId = 0))
		  --AND (E.StatusId = @rStatusId OR @rStatusId = 0)
      Order By ExpenseDate DESC
  END
  
  IF(@rIsSearchHierarchWise = 2)
  BEGIN
	SELECT 
			E.Id AS ExpenseId,
			E.EmployeeId,
			E.Amount,
			E.Remark,
			E.CreatedUserId,
			E.CreatedDateTime,			 
			E.UpdatedUserId,
			E.UpdatedDateTime,
			E.ExpenseDate,
			E.ExpenseGroupId,
			EGM.Title AS ExpenseGroupName,
			EM.EmployeeName,
			EM.Code AS EmployeeCode,
			E.StatusReason,
			ISNULL(E.StatusId,0) AS StatusId,
			ISNULL(SM.Title,'Pending') AS StatusName,
			OM.DisplayTitle AS OrganizationName,
			E.ActionByEmployeeId,
			CASE WHEN ISNULL(E.ActionByEmployeeId,0) = 0 AND E.StatusId = 630 THEN NULL
			WHEN E.ActionByEmployeeId = 0 AND E.StatusId != 630 THEN US.DisplayTitle
			ELSE EM.FirstName + ' ' + EM.LastName END AS ActionByEmployee 
		    --,(ISNULL((Select NoOfLeave FROM sHrm.tLeaveTypeGradeSettings LGS WHERE LGS.EmployeeGradeId = EM.EmployeeGradeId AND LGS.LeaveTypeId = L.LeaveTypeId),0) - L.NoOfLeave) AS AvailableLeave
      
  FROM 
		  sAccounting.tExpense E
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = E.BatchId	
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		  INNER JOIN sAccounting.tExpenseGroupMaster EGM ON EGM.Id = E.ExpenseGroupId
		  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = E.EmployeeId 
		  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = E.StatusId
		  LEFT JOIN sSecurity.tUser US ON US.Id = E.UpdatedUserId
	      --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = E.OrgId
	      --INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.EmployeeGradeId = EM.EmployeeGradeId AND LTGS.LeaveTypeId = L.LeaveTypeId 
  WHERE 
		  --(E.Id = @rId OR @rId = 0)
		  --AND (E.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		  ((E.ExpenseDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		  AND ((E.ExpenseDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		  AND (E.ExpenseGroupId = @rExpenseGroupId OR @rExpenseGroupId = 0)      
		  AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		  AND ((E.OrgId = @rOrgId) OR (@rOrgId = 0))
		  --AND (E.StatusId = @rStatusId OR @rStatusId = 0)
      Order By ExpenseDate DESC
  END
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pExpenseListingModify]
           
        @rId bigint,
        @rEmployeeId bigint,
        @rOrgId smallint,
        @rStatusId int,
        @rStatusReason nvarchar(100),
        @rActionByEmployeeId bigint
        --@rLeaveRemark nvarchar(200) 
        
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

	BEGIN
		UPDATE sAccounting.tExpense 
		SET 	 
		  StatusId=@rStatusId,
		  StatusReason=@rStatusReason,
          ActionByEmployeeId=@rActionByEmployeeId              
		WHERE EmployeeId = @rEmployeeId AND Id=@rId
	 END 
	   SELECT @rEmployeeId AS Result	   
	   COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pExpenseModify]
	@rId [int],
	@rRemark [nvarchar](100),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rExpenseDate Date,
	@rExpenseGroupId [int],
	@rOrgId smallint,
	@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 Id  <> @rId AND OrgId = @rOrgId )
BEGIN

	 UPDATE sAccounting.tExpense
		SET 
			Remark = @rRemark,
			Amount=@rAmount,
			--IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			ExpenseDate = @rExpenseDate,
			ExpenseGroupId = @rExpenseGroupId
	  WHERE Id = @rId AND OrgId = @rOrgId
	  
	  
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAccounting].[pExpenseOfCandidateAdd]
	 
	 @rOrgId smallint,
	   @rBatchId int,
	 @rId int,
	 @rEmployeeId bigint,
	 @rExpenseDate date,
	 @rExpenseGroupId int,
	 @rAmount decimal(20,5), --Changed for mantis : 32211 by Nilesh
	 @rRemark nvarchar(200),
	 @rCreatedUserId bigint,
	 --@rCreatedDateTime datetime,
	 @rUpdatedUserId bigint,
	 --@rUpdatedDateTime datetime,
	 @rStatusId int,
	 @rExpenseDetailXml nvarchar(max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rExpenseDetailXml
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

			IF(@rId = 0)	
			BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpense', 0, 1, 1,@outNextNumber = @lNextNumber output
			--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO  sAccounting.tExpense
			(
			OrgId,
			 BatchId,
			Id,
			EmployeeId	,
			ExpenseDate	,
			ExpenseGroupId,
			Amount,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StatusId	
			)
			VALUES
			(
		    @rOrgId ,
		    @rBatchId,
			@lNextNumber ,
			@rEmployeeId ,
			@rExpenseDate ,
			@rExpenseGroupId ,
			@rAmount ,
			@rRemark ,
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate(),	
			@rStatusId 								
			)
		
			INSERT INTO sAccounting.tExpenseDetail
			(ExpenseId,
			ExpenseSubGroupId,
			Amount,Remark)
			SELECT @lNextNumber,ExpenseSubGroupId,Amount,sSetup.fPortalXMLTagsReplaceReverse(Remark)
			FROM OPENXML (@loDoc, '/Table/ExpenseDetail', 1)
			WITH (ExpenseSubGroupId int,Amount decimal(20,5),Remark nvarchar(200)) --Added for mantis : 32211 by Nilesh
		    SELECT @lNextNumber AS Result
			END	 

	ELSE
			BEGIN
			SET @lNextNumber = @rId
			UPDATE  sAccounting.tExpense
		    SET
	    
			ExpenseDate=@rExpenseDate,
			ExpenseGroupId=@rExpenseGroupId,
			Amount=@rAmount,
			Remark=@rRemark,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			StatusId=@rStatusId
	    
			WHERE Id = @rId
			DELETE sAccounting.tExpenseDetail WHERE ExpenseId= @rId
			INSERT INTO sAccounting.tExpenseDetail
			(ExpenseId,ExpenseSubGroupId,Amount,Remark)
			SELECT @lNextNumber,ExpenseSubGroupId,Amount,sSetup.fPortalXMLTagsReplaceReverse(Remark)
			FROM OPENXML (@loDoc, '/Table/ExpenseDetail', 1)
			WITH (ExpenseSubGroupId int,Amount decimal(20,5),Remark nvarchar(200)) --Added for mantis : 32211 by Nilesh
	 SELECT @lNextNumber AS Result
	 END  	

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


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


 
CREATE OR ALTER PROCEDURE [sAccounting].[pExpenseSubGroupMasterAdd]	 	   
        @rOrgId smallint,
        @rId int, 
        @rExpenseGroupId int,
        @rCode nvarchar(100),
        @rTitle nvarchar(100),  
		@rIsObsolete bit,	
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rAmountLimit decimal(20,5) --Changed for mantis : 32211 by Nilesh
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
	 
		If Exists(select Id from  sAccounting.tExpenseSubGroupMaster where Code=@rCode AND OrgId=@rOrgId
		AND ExpenseGroupId=@rExpenseGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
			If Exists(select Id from sAccounting.tExpenseSubGroupMaster  where Title=@rTitle AND OrgId=@rOrgId
			AND ExpenseGroupId=@rExpenseGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
	END
	ELSE
	BEGIN
			If  Exists(select Id from  sAccounting.tExpenseSubGroupMaster where Code=@rCode AND OrgId=@rOrgId 
			AND ExpenseGroupId=@rExpenseGroupId  AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from  sAccounting.tExpenseSubGroupMaster where Title=@rTitle AND OrgId=@rOrgId 
		AND ExpenseGroupId=@rExpenseGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
	

	END
	
	
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpenseSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tExpenseSubGroupMaster
		(
			OrgId,			
			Id,
			ExpenseGroupId,
			Code,
			Title, 
			IsObsolete,			
		    CreatedUserId, 
		    CreatedDateTime, 
		    UpdatedUserId, 
            UpdatedDateTime,
            AmountLimit
		)
	VALUES
		(
		    @rOrgId ,
			@lNextNumber , 
			@rExpenseGroupId,
			@rCode ,      
			@rTitle ,	
			@rIsObsolete,				
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate(),
			@rAmountLimit									
		)
		
		   SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tExpenseSubGroupMaster
	    SET
			ExpenseGroupId=@rExpenseGroupId,
			Code=@rCode, 
	        Title=@rTitle,
	        IsObsolete=@rIsObsolete,
	        UpdatedUserId=@rCreatedUserId, 
            UpdatedDateTime=sCommon.fGetDate(),
            AmountLimit=@rAmountLimit
	      WHERE Id = @rId
	       SELECT 11 AS Result
	 END  	

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


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAccounting].[pExpenseSubGroupMasterGet]

	 @rId int,
	 @rExpenseGroupId int,
	  @rOrgId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			ES.Id,
			ES.Code	,	
			ES.Title,				
		    ES.OrgId,
		    ES.CreatedUserId,
		    ES.CreatedDateTime,
		    ES.IsObsolete,
		    ES.ExpenseGroupId,
		    EG.Title AS ExpenseGroupType,
		    ISNULL(ES.AmountLimit,0) AS AmountLimit
		    
	FROM sAccounting.tExpenseSubGroupMaster ES
	
		LEFT JOIN	sAccounting.tExpenseGroupMaster EG ON EG.Id=ES.ExpenseGroupId
	WHERE 
		(ES.OrgId = @rOrgId)
		AND	((ES.Id = @rId) OR (@rId = 0))
		AND	((ES.ExpenseGroupId = @rExpenseGroupId) OR (@rExpenseGroupId = 0))
		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((ES.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		
		ORDER BY ES.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pLedgerBook]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rLedgerGroupId [int],
	@rAccountId  int=0
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN
		--for DataSet Drag & Drop
   --  SELECT '' AS Builder1,
			-- '' AS Builder2,
   --           Convert(BigInt,0) AS TransactionId,
			--  Convert(Decimal,0) AS CREDIT,
			--  Convert(Decimal,0)AS DEBIT,
			--  0 AS LedgerId,
			--  Convert(Date,'') AS TransactionDate,
			--  0 AS VoucherNumber,
			-- '' AS Narration,
			-- '' AS VoucherType,
			-- '' AS TITLE,
			--  Convert(Decimal,0) AS OpeningBalance,
			--  Convert(Decimal,0) AS ClosingBalance,
			---- Added by dhannajay for mantis : 39500	
			-- '' As OrgTitle,
			-- '' AS SmallAddress1,
			-- '' AS SmallAddress2,
			----Added by dhannajay for mantis : 39500
			--  '' AS ChequeNo
      
    
    DECLARE @1OpeningBalance DECIMAL(22,2)
    DECLARE @1ClosingBalance DECIMAl(22,2)
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
     
	CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)	    
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance
	FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId

	SELECT 
	L.LedgerTypeId,
	 @rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,	
	--ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * SUM(TD.AMOUNT) END,0) AS CREDIT,
	--ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN SUM(TD.AMOUNT) END,0) AS DEBIT,

		--Isnull((select ABS(sum(td1.Amount)) from
	--sAccounting.tTransaction T1 
	--INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id
	--Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId
	--WHERE (TD1.LedgerId =@rLedgerId ) AND T1.AccountingYearId = @rAccountingYearId
	--AND TransactionTypeId = 2),0) AS Credit,
	([sAccounting].[fDecimalValueGet] (Isnull((select ABS(sum(td1.Amount)) from
	sAccounting.tTransaction T1 
	INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id
	Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId
	WHERE (TD1.LedgerId =@rLedgerId ) AND T1.AccountingYearId = @rAccountingYearId
	AND TransactionTypeId = 2),0),@DecimalCount)) AS Credit,

	--Isnull((select ABS(sum(td1.Amount)) from
	--sAccounting.tTransaction T1 
	--INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id
	--Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId
	--WHERE (TD1.LedgerId =@rLedgerId ) AND T1.AccountingYearId = @rAccountingYearId
	--AND TransactionTypeId = 1),0) AS Debit,
	([sAccounting].[fDecimalValueGet] (Isnull((select ABS(sum(td1.Amount)) from
	sAccounting.tTransaction T1 
	INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id
	Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId
	WHERE (TD1.LedgerId =@rLedgerId ) AND T1.AccountingYearId = @rAccountingYearId
	AND TransactionTypeId = 1),0),@DecimalCount)) AS Debit,

	--CAse When L.LedgerTypeId = 1 then 
 --  -1 * Isnull((select sum(TD1.Amount)  from
	--sAccounting.tTransaction T1 
	--INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T1.Id=T.Id 
	--AND TD1.TransactionTypeId = 1 
	--WHERE (L.LedgerTypeId = 1 ANd TD1.LedgerId =TD.LedgerId) OR (L.LedgerTypeId = 2 AND TD1.LedgerId =@rLedgerId )
	--GROUP BY 	TD1.LedgerId,T1.TransactionDate,T1.VoucherNumber,T1.Id,
	--			TD1.TransactionTypeId,T1.VoucherTypeId,T1.Narration,
	--			T1.ChequeNo
	--),0) else 0 end as Credit ,
	--CAse When L.LedgerTypeId = 1 then 0 end as debit,

	--Case When L.LedgerTypeId = 2 then 
	---1 * isnull((select sum(TD1.Amount)  from
	--sAccounting.tTransaction T1 
	--INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T1.Id=T.Id  
	--AND TD1.TransactionTypeId = 2
	--WHERE (L.LedgerTypeId = 1 ANd TD1.LedgerId =TD.LedgerId) 
	-- OR(L.LedgerTypeId = 2 AND TD1.LedgerId =@rLedgerId )
	--GROUP BY 	TD1.LedgerId,T1.TransactionDate,T1.VoucherNumber,T1.Id,
	--			TD1.TransactionTypeId,T1.VoucherTypeId,T1.Narration,
	--			T1.ChequeNo
	--),0) else 0 end as Debit,
	--CAse When L.LedgerTypeId = 2 then 0 end as Credit,


	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Narration,
	VTM.Title As VoucherType,
	T.VoucherTypeId,
	--LEFT(VTM.Title,2) As VoucherType
	L.TITLE,
	([sAccounting].[fDecimalValueGet] (ISNULL(@1OpeningBalance,0),@DecimalCount)) AS OpeningBalance,	--change by dhruvik
	([sAccounting].[fDecimalValueGet] (ISNULL(@1ClosingBalance,0),@DecimalCount)) AS ClosingBalance,	--change by dhruvik
		AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2,
			T.ChequeNo
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id AND (TD.LedgerId <> @rLedgerId)
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	
	WHERE (T.TransactionDate >= @rStartDate)  AND
	(T.TransactionDate <= @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND	
	(T.AccountingYearId=@rAccountingYearId OR @rAccountingYearId = 0)
	 AND
	(L.LedgerGroupId = @rLedgerGroupId or @rLedgerGroupId = 0) AND L.AccountingYearId=@rAccountingYearId
	AND @rLedgerId IN (SELECT LedgerId FROM sAccounting.tTransactionDetail TD1 WHERE TD1.TRANSACTIONID=T.ID AND TD1.TRansactionTypeID <> TD.TRansactionTypeID)-- L.LedgerTypeId )
	AND (T.AccountId=@rAccountId OR @rAccountId=0)  
	GROUP BY 	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Id,
				TD.TransactionTypeId,L.Title,T.VoucherTypeId,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2,
				T.ChequeNo,L.LedgerTypeId
   order by T.TransactionDate,T.VoucherNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAccounting].[pLedgerGroupMasterAdd]
	 
	@rId int,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rLedgerMainGroupId int,
	@rAccountingYearId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rIsObsolete bit,
	@rOrgGroupId int,
	@rAccountId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--	BEGIN TRY
	 
  SELECT @rAccountId = AccountId FROM sAccounting.tAccountingYearMaster WHERE Id = @rAccountingYearId
  IF(@rId = 0)	
 	BEGIN
		IF Exists(select 1 from sAccounting.tLedgerGroupMaster where Code=@rCode  AND AccountingYearId = @rAccountingYearId)
			BEGIN
			SELECT -101 AS Result
			RETURN
		END  
		   IF Exists(select 1 from sAccounting.tLedgerGroupMaster where   Title = @rTitle AND AccountingYearId = @rAccountingYearId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END  
	END
	ELSE
	BEGIN
 
	   IF Exists(select 1 from sAccounting.tLedgerGroupMaster where Code=@rCode  AND AccountingYearId = @rAccountingYearId AND ID <> @rId)
			BEGIN
			SELECT -101 AS Result
			RETURN
		END  
		   IF Exists(select 1 from sAccounting.tLedgerGroupMaster where   Title = @rTitle AND AccountingYearId = @rAccountingYearId AND ID <> @rId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END  

	END 
	
	
	
	
	 --BEGIN TRANSACTION	
 IF (@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tLedgerGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tLedgerGroupMaster',@lNextNumber = @lNextNumber output

	INSERT INTO sAccounting.tLedgerGroupMaster
		(
			Id,
			Code,
			Title,
			LedgerMainGroupId,
			AccountingYearId,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId,
			AccountId
			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rLedgerMainGroupId,
			@rAccountingYearId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete,
			@rOrgGroupId,
			@rAccountId
		)
		 SELECT 1 AS RESULT            
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	 UPDATE sAccounting.tLedgerGroupMaster
	    SET
	      Code=@rCode,
	      Title=@rTitle,
	      LedgerMainGroupId=@rLedgerMainGroupId,
	      AccountingYearId=@rAccountingYearId,
	      IsObsolete=@rIsObsolete,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate()  
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
	--	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pLedgerGroupMasterDelete]
	 
	@rId int,	 
	@rAccountingYearId int,	 
	@rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 
 
		IF Exists(select 1 from sAccounting.tLedgerMaster where LedgerGroupId = @rId  AND  AccountingYearId = @rAccountingYearId  )
			BEGIN
			SELECT -103 AS Result
			RETURN
		END  
		
		--IF EXISTS(SELECT 1 FROM sAccounting.tLedgerGroupMaster WHERE Code IN ('1','2','3','4','5'))
		--BEGIN
		--	SELECT -104 AS RESULT
		--	RETURN
		--END
		
		DELETE FROM sAccounting.tLedgerGroupMaster WHERE Id = @rId AND AccountingYearId = @rAccountingYearId 
		
		SELECT 1 AS Result
 
 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAccounting].[pLedgerGroupMasterGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rLedgerMainGroupId int,
	 @rAccountingYearId int,
	 @rOrgGroupId int,
	  @rAccountId  int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN
	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	 
	SELECT 
	@rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2, 
	LGM.Id,
	LGM.Code,
	LGM.Title,
	LGM.LedgerMainGroupId,
	LGM.AccountingYearId,
	LGM.IsObsolete,
	LMGM.Title AS LedgerMainGroupTitle ,
	AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
	
  FROM 
       sAccounting.tLedgerGroupMaster LGM
        INNER JOIN sAccounting.tLedgerMainGroupMaster LMGM
        ON LGM.LedgerMainGroupId= LMGM.Id
        INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=LGM.AccountId
       AND (LGM.AccountId=@rAccountId OR @rAccountId=0)  
             
  WHERE 
		
        ((LGM.Id = @rId) OR (@rId = 0)) AND
        ((LGM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((LGM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
        AND  ((LGM.LedgerMainGroupId= @rLedgerMainGroupId) OR (@rLedgerMainGroupId=0)) 
        AND  (LGM.OrgGroupId = @rOrgGroupId)
         --OR (LGM.OrgId = 1))
        AND  ((LGM.AccountingYearId = @rAccountingYearId))
     
         Order By  CASE ISNUMERIC(LGM.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(LGM.Code)) + LGM.Code ELSE LGM.Code  END  -- add for mantis : 0039524
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pLedgerMasterAdd]
	 
	@rId int,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rLedgerGroupId int,
	@rAccountingYearId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOpeningBalance decimal(20,5),
	@rLedgerTypeId int,
	@rIsObsolete bit,
	@rOrgGroupId int,
	@rIsShowInDashBoard bit = 0		-- Mantisid : 0035149
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
		IF(@rId = 0)	
	BEGIN
		IF Exists(select 1 from sAccounting.tLedgerMaster where Code=@rCode  AND AccountingYearId = @rAccountingYearId)
			BEGIN
			SELECT -101 AS Result
			RETURN
		END  
		   IF Exists(select 1 from sAccounting.tLedgerMaster where   Title = @rTitle AND AccountingYearId = @rAccountingYearId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END  
	END
	ELSE
	BEGIN
 
	   IF Exists(select 1 from sAccounting.tLedgerMaster where Code=@rCode  AND AccountingYearId = @rAccountingYearId AND ID <> @rId)
			BEGIN
			SELECT -101 AS Result
			RETURN
		END  
		   IF Exists(select 1 from sAccounting.tLedgerMaster where   Title = @rTitle AND AccountingYearId = @rAccountingYearId AND ID <> @rId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END  

	END 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
 BEGIN 
	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tLedgerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tLedgerMaster',@lNextNumber = @lNextNumber output

	INSERT INTO sAccounting.tLedgerMaster
		(
			Id,
			Code,
			Title,
			LedgerGroupId,
			AccountingYearId,
			CreatedUserId,
			CreatedDateTime,
			OpeningBalance,
			LedgerTypeId,
		    IsObsolete,
		    OrgGroupId,
			IsShowInDashBoard			-- Mantisid : 0035149
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rLedgerGroupId,
			@rAccountingYearId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOpeningBalance,
			@rLedgerTypeId,
			@rIsObsolete,
			@rOrgGroupId,
			@rIsShowInDashBoard			
		)
		 SELECT 1 AS RESULT            
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tLedgerMaster
	    SET
	      Code=@rCode,
	      Title=@rTitle,
	      LedgerGroupId=@rLedgerGroupId,	    
	      IsObsolete=@rIsObsolete,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate(),
	      OpeningBalance=@rOpeningBalance,
	      LedgerTypeId=@rLedgerTypeId,
		  IsShowInDashBoard = @rIsShowInDashBoard -- Mantisid : 0035149
	      WHERE Id = @rId 	AND AccountingYearId = @rAccountingYearId   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pLedgerMasterDelete]
	 
	@rId int,	 
	@rAccountingYearId int,	 
	@rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 
 
		IF Exists(select 1 from sAccounting.tTransactionDetail TD INNER JOIN sAccounting.tTransaction T ON T.Id = TD.TransactionId  
		  where TD.LedgerId = @rId AND   T.AccountingYearId = @rAccountingYearId  )
			BEGIN
			SELECT -103 AS Result
			RETURN
		END  
		
		--IF EXISTS(SELECT 1 FROM sAccounting.tLedgerMaster WHERE Code IN ('1','2','4','5'))
		--BEGIN
		--	SELECT -104 AS RESULT
		--	RETURN
		--END
		
		DELETE FROM sAccounting.tLedgerMaster WHERE Id = @rId AND AccountingYearId = @rAccountingYearId 
		
		SELECT 1 AS Result
 
 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pLedgerMasterGet]

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rId int = 0,
		--@rAffiliationId int,
		@rTitle nvarchar(100),
		@rCode nvarchar(20),
		@rLedgerGroupId int,
		@rAccountingYearId int,
		@rOrgGroupId int,
		@rAccountId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Declare @1AccountId int
      
	BEGIN
		select @1AccountId = AccountId from sAccounting.tAccountingYearMaster Where Id = @rAccountingYearId
			
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END

	--change by dhruvik
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
		LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
	 
	  SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		LM.Id,
		LM.Code,
		LM.Title,
		([sAccounting].[fDecimalValueGet] (LM.OpeningBalance, @DecimalCount)) AS OpeningBalance,	--change by dhruvik
		LM.IsObsolete,
		LGM.Id AS LedgerGroupId,
		LTM.Id AS LedgerTypeId,
		LGM.Title AS LedgerGroupTitle,
		LTM.Title AS LedgerTypeTitle,
		AM.ReportOrgTitle As OrgTitle,
		AM.SmallAddress1 AS SmallAddress1,
		AM.SmallAddress2 AS SmallAddress2,
		ISNULL(LM.IsShowInDashBoard,0) AS IsShowInDashBoard  -- Mantisid : 0035149
	      
	  FROM 
		   sAccounting.tLedgerMaster LM
			INNER JOIN sAccounting.tLedgerTypeMaster LTM
			ON LM.LedgerTypeId= LTM.Id
			 INNER JOIN sAccounting.tLedgerGroupMaster LGM
			ON LM.LedgerGroupId= LGM.Id 
			  LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=LGM.AccountId
        
  WHERE  
        ((LM.Id = @rId) OR (@rId = 0))
        AND  ((LM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((LM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
        AND  ((LM.LedgerGroupId = @rLedgerGroupId) OR (@rLedgerGroupId = 0))
        AND ((LM.AccountingYearId =  @rAccountingYearId))
        AND ((LGM.AccountingYearId = @rAccountingYearId))
        And LGM.AccountId = @1AccountId AND LM.OrgGroupId = @rOrgGroupId
        	AND (LGM.AccountId=@rAccountId OR @rAccountId=0) 
        --AND ((LGM.OrgGroupId=@rOrgGroupId))
        
        --Do not Change Order By 
        order by LM.Id asc
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAccounting].[pMonthlySummaryMonthwiseGet]
	 
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int] 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

        DECLARE @AccOpBalance decimal(12,2) = 0
		SELECT @AccOpBalance = OpeningBalance FROM sAccounting.tLedgerMaster  WHERE AccountingYearId=@rAccountingYearId AND Id = @rLedgerId
		 
		SELECT @AccOpBalance AS OpeningBalance,ISNULL(CR.MonthName,DR.MonthName) AS Region,ISNULL(Credit,0) AS Credit,ISNULL(Debit,0) AS Debit,
		
		-- @AccOpBalance + ISNULL(Debit,0) - ISNULL(Credit,0) AS ClosingBalance
		ISNULL([sAccounting].[fOpeningClosingBalanceGet](ISNULL(DATEADD(month,CR.MonthN-1,DATEADD(year,CR.YearCr-1900,0)),DATEADD(month,DR.MonthN-1,DATEADD(year,DR.YearDR-1900,0))),ISNULL(DATEADD(day,-1,DATEADD(month,CR.MonthN,DATEADD(year,CR.YearCr-1900,0))),DATEADD(day,-1,DATEADD(month,DR.MonthN,DATEADD(year,DR.YearDR-1900,0)))),@rLedgerId,1,@rOrgGroupId,@rAccountingYearId),0)+ ISNULL(Debit,0) - ISNULL(Credit,0) AS ClosingBalance
		,ISNULL(DATEADD(month,CR.MonthN-1,DATEADD(year,CR.YearCr-1900,0)),DATEADD(month,DR.MonthN-1,DATEADD(year,DR.YearDR-1900,0))) AS TransactionFromDate,
		ISNULL(DATEADD(day,-1,DATEADD(month,CR.MonthN,DATEADD(year,CR.YearCr-1900,0))),DATEADD(day,-1,DATEADD(month,DR.MonthN,DATEADD(year,DR.YearDR-1900,0)))) AS TransactionToDate
		 
		FROM (
		 
		SELECT  -1 * ISNULL(Sum(TD.Amount) ,0) AS Credit ,DATEPART(MONTH,T.TransactionDate) AS MonthN,datename(month,T.TransactionDate) AS MonthName
				 ,DATEPART(Year,T.TransactionDate) AS YearCr FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
				 ON T.Id=TD.TransactionId 		 
					AND T.AccountingYearId = @rAccountingYearId 			 
					AND TD.TransactionTypeId = 1 And TD.LedgerId=@rLedgerId
				GROUP BY DATEPART(MONTH,T.TransactionDate),datename(month,T.TransactionDate),DATEPART(Year,T.TransactionDate)
	     )   CR  FULL  OUTER JOIN 
	    (
				 SELECT  ISNULL(Sum(TD.Amount) ,0) AS Debit,DATEPART(MONTH,T.TransactionDate) AS MonthN,datename(month,T.TransactionDate) AS MonthName
				,DATEPART(Year,T.TransactionDate) AS YearDR FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
				 ON T.Id=TD.TransactionId 
				 --INNER JOIN sAccounting.tLedgerMaster L ON L.ID = TD.LedgerId
					AND T.AccountingYearId = @rAccountingYearId 			 
					AND TD.TransactionTypeId = 2 And TD.LedgerId=@rLedgerId
				GROUP BY DATEPART(MONTH,T.TransactionDate),datename(month,T.TransactionDate),DATEPART(Year,T.TransactionDate)   
		)   DR ON DR.MonthN = CR.MonthN

	 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pMonthlySummaryWeeklywiseGet]
	 
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rIntervalId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @1AccountFromDate date
DECLARE @1AccountToDate date
DECLARE @1FirstDate Date
DECLARE @1LastDate Date
Declare @lClOsingBalance Decimal (12,2)
Declare @CreditBalance Decimal (12,2)
Declare @DebitBalance Decimal (12,2)
Declare @CurruntOpeningBalance Decimal (12,2)
DECLARE @LastDateOfYear date

CREATE TABLE #TempMonthlyRegister
	(
		Id bigint identity,	 
		OpeningBalance decimal(12,2),
		Region nvarchar(200),
		Credit Decimal (12,2),
	    Debit Decimal (12,2),	    
	    ClosingBalance Decimal (12,2),
	    TransactionFromDate DATE,
	    TransactionToDate Date
	)

Declare @AccOpBalance decimal(12,2) = 0
SELECT @AccOpBalance = OpeningBalance FROM sAccounting.tLedgerMaster WHERE AccountingYearId=@rAccountingYearId AND Id = @rLedgerId

SELECT  @1AccountFromDate = FromDate,@1AccountToDate = ToDate,@LastDateOfYear = ToDate from  sAccounting.tAccountingYearMaster where Id = @rAccountingYearId
SET @1FirstDate = @1AccountFromDate
SET @CurruntOpeningBalance = @AccOpBalance

IF EXISTS (SELECT 1 from sAccounting.tTransaction T INNER JOIN 
 sAccounting.tTransactionDetail TD ON TD.TransactionId = T.Id Where LedgerId = @rLedgerId AND AccountingYearId=@rAccountingYearId) 

BEGIN
  WHILE @1AccountToDate > @1AccountFromDate
     BEGIN
     
      SET  @lClOsingBalance = 0
	  SET  @CreditBalance  = 0
	  SET  @DebitBalance  = 0 
	  
		--SET @1FirstDate = @1AccountFromDate
	    SELECT @1LastDate  =  DATEADD(day, @rIntervalId, @1FirstDate) 
	    
	  
	    IF(@1LastDate > @LastDateOfYear)
	        SET @1LastDate = @LastDateOfYear
	    
	    SELECT @CreditBalance= -1 * ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 		 
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @1FirstDate AND T.TransactionDate < @1LastDate
			AND TD.TransactionTypeId = 1 And TD.LedgerId=@rLedgerId

		 SELECT @DebitBalance=  ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 
		 --INNER JOIN sAccounting.tLedgerMaster L ON L.ID = TD.LedgerId
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @1FirstDate AND T.TransactionDate < @1LastDate
			AND TD.TransactionTypeId = 2 And TD.LedgerId=@rLedgerId 
			
	    INSERT INTO #TempMonthlyRegister
	    Select @CurruntOpeningBalance,CONVERT(nvarchar(50),@1FirstDate) + '  -  ' + CONVERT(nvarchar(50),@1LastDate),@CreditBalance,@DebitBalance,@AccOpBalance + @DebitBalance - @CreditBalance,@1FirstDate,@1LastDate
	    
	   SET @AccOpBalance =  @AccOpBalance + @DebitBalance - @CreditBalance
	   SET @1FirstDate = @1LastDate
	   SELECT @1AccountToDate = DATEADD(day, -@rIntervalId, @1AccountToDate) 
	      
     END
          
     Select * from #TempMonthlyRegister    
     drop table #TempMonthlyRegister
   END  
   
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pMonthlySummaryYearlylywiseGet]
	 
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rIntervalId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @1AccountFromDate date
DECLARE @1AccountToDate date
DECLARE @1FirstDate Date
DECLARE @1LastDate Date
Declare @lClOsingBalance Decimal (12,2)
Declare @CreditBalance Decimal (12,2)
Declare @DebitBalance Decimal (12,2)
Declare @CurruntOpeningBalance Decimal (12,2)
DECLARE @LastDateOfYear date

CREATE TABLE #TempMonthlyRegister
	(
		Id bigint identity,	 
		OpeningBalance decimal(12,2),
		Region nvarchar(200),
		Credit Decimal (12,2),
	    Debit Decimal (12,2),	 
	    ClosingBalance Decimal (12,2),
	    TransactionFromDate DATE,
	    TransactionToDate Date
	)

Declare @AccOpBalance decimal(12,2) = 0
SELECT @AccOpBalance = OpeningBalance FROM sAccounting.tLedgerMaster WHERE AccountingYearId=@rAccountingYearId AND Id = @rLedgerId

SELECT @1AccountFromDate = FromDate,@1AccountToDate = ToDate,@LastDateOfYear = ToDate 
from  sAccounting.tAccountingYearMaster where Id = @rAccountingYearId


 IF EXISTS (SELECT 1 from sAccounting.tTransaction T INNER JOIN 
 sAccounting.tTransactionDetail TD ON TD.TransactionId = T.Id Where LedgerId = @rLedgerId AND AccountingYearId=@rAccountingYearId) 

 BEGIN
 
	SET @1FirstDate = @1AccountFromDate
	SET @CurruntOpeningBalance = @AccOpBalance
    WHILE @1AccountToDate > @1AccountFromDate
     BEGIN
     
      SET  @lClOsingBalance = 0
	  SET  @CreditBalance  = 0
	  SET  @DebitBalance  = 0
         
		--SET @1FirstDate = @1AccountFromDate
	    SELECT @1LastDate  =  DATEADD(month, @rIntervalId, @1FirstDate) 
	    
	    IF(@1LastDate > @LastDateOfYear)
	        SET @1LastDate = @LastDateOfYear
	    
	    SELECT @CreditBalance= -1 * ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 		 
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @1FirstDate AND T.TransactionDate < @1LastDate
			AND TD.TransactionTypeId = 1 And TD.LedgerId=@rLedgerId

		 SELECT @DebitBalance=  ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 
		 --INNER JOIN sAccounting.tLedgerMaster L ON L.ID = TD.LedgerId
			AND T.AccountingYearId = @rAccountingYearId 
			AND T.TransactionDate >= @1FirstDate AND T.TransactionDate < @1LastDate
			AND TD.TransactionTypeId = 2 And TD.LedgerId=@rLedgerId 
			
	    INSERT INTO #TempMonthlyRegister
	    Select @CurruntOpeningBalance,
	     CASE WHEN @rIntervalId = 12
	     THEN  CONVERT(nvarchar(50),Year(@1FirstDate)) + '  ' + ' - ' + CONVERT(nvarchar(50),Year(@1LastDate))
	     ELSE
	           datename(month,@1FirstDate) + '  ' + ' - ' + datename(month,@1LastDate) END ,@CreditBalance,@DebitBalance,@AccOpBalance + @DebitBalance - @CreditBalance,@1FirstDate,@1LastDate
	     
	   SET @AccOpBalance =  @AccOpBalance + @DebitBalance - @CreditBalance
	   SET @1FirstDate = @1LastDate
	   SELECT @1AccountToDate = DATEADD(month, -@rIntervalId, @1AccountToDate) 
	      
     END
     
     SELECT * from #TempMonthlyRegister    
     
     Drop table #TempMonthlyRegister 
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pOpeningBalanceApproveGet]
	    @rLedgerId [int] = 0,	@rAccountingYearId [int]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	Declare @OpBalance decimal
	Declare @LedgerTypeId Int
	Declare @TraBalance decimal

	Select @OpBalance=OpeningBalance FROM sAccounting.tLedgerMaster WHERE ID = @rLedgerId
	Select @LedgerTypeId=LedgerTypeId FROM sAccounting.tLedgerMaster WHERE ID = @rLedgerId
	
	
	
	SELECT @TraBalance=ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionApproveDetail  TD
	INNER JOIN sAccounting.tTransactionApprove T on T.Id=TD.TransactionId
	WHERE T.AccountingYearId = 	@rAccountingYearId AND 
	      TD.LedgerId = @rLedgerId
	
	
	IF (@LedgerTypeId =1)
		BEGIN
			SELECT ' ( ' + Convert(nvarchar(20),@OpBalance - @TraBalance)   + ' ) CR' AS OpBalance
		END
	ELSE
		BEGIN
			SELECT ' ( ' + Convert(nvarchar(20),@OpBalance + @TraBalance)   + ' ) DR' AS OpBalance
		END
	      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pOpeningBalanceGet]
	    @rLedgerId [int] = 0,	@rAccountingYearId [int]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	Declare @OpBalance decimal
	Declare @LedgerTypeId Int
	Declare @TraBalance decimal

	Select @OpBalance=OpeningBalance FROM sAccounting.tLedgerMaster WHERE ID = @rLedgerId
	Select @LedgerTypeId=LedgerTypeId FROM sAccounting.tLedgerMaster WHERE ID = @rLedgerId
	
	
	
	SELECT @TraBalance=ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail  TD
	INNER JOIN sAccounting.tTransaction T on T.Id=TD.TransactionId
	WHERE T.AccountingYearId = 	@rAccountingYearId AND 
	      TD.LedgerId = @rLedgerId
	
	
	IF (@LedgerTypeId =1)
		BEGIN
			SELECT ' ( ' + Convert(nvarchar(20),@OpBalance - @TraBalance)   + ' ) CR' AS OpBalance
		END
	ELSE
		BEGIN
			SELECT ' ( ' + Convert(nvarchar(20),@OpBalance + @TraBalance)   + ' ) DR' AS OpBalance
		END
	      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAccounting].[pProfitAndLoss]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--SELECT '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
--'' AS Builder1,
--	   '' AS Builder2,
--         '' AS IncomeGroup,
--	     '' AS IncomeLedger,
--	     '' AS Income,
--	     '' AS ClosingBalance,
--	     '' AS ExpenseGroup,
--	     '' AS ExpenseLedger,
--	     '' AS Expense,
--	     '' AS OpeningBalance
	    

Declare @lLedgerId int 
Declare @lOpeningBalance Decimal (12,2)
Declare @ltIncome Decimal (12,2)
Declare @ltExpense Decimal (12,2)
Declare @lInIncome Decimal(12,2)
Declare @lInClosing Decimal(12,2)
Declare @lExOpening Decimal(12,2)
Declare @lExExpense Decimal(12,2)
Declare @lGrossProfit Decimal(12,2)
Declare @lGrossLoss Decimal(12,2)
Declare @lCount int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150) 
DECLARE @1ExpenceCount int
DECLARE @1IncomeCount int
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)

	--add by dhruvik
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548

	SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
	From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
  
  
    CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(25,5),
 			Closing_Balance decimal(25,5),
 		    Transaction_Balance decimal(25,5)
 		)  	
 		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
		
		CREATE TABLE #TempExpenseGroup
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroupId int,
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(25,5),
		   OpeningBalance decimal(25,5)	 
		)
		
		CREATE TABLE #TempIncomeGroup
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroupId int,
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(25,5),
		   ClosingBalance decimal		 
		)
		
		INSERT INTO #TempExpenseGroup
		SELECT 
        Isnull(Lg.Id,0) as ExpenseGroupId,		
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
 
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) > 0
		Order By LMG.Id	
		
		
		INSERT INTO #TempIncomeGroup
        SELECT  
        Isnull(Lg.Id,0) as IncomeGroupId,		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id having ISNULL(SUM(UC.Closing_Balance),0) > 0	
		Order By LMG.Id			
	      
	     
	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
	   If(@1InComeCount >= @1ExpenceCount)
	     BEGIN		    
	           SELECT @ReportOrgTitle  AS OrgTitle,
				@SmallAddress1 AS SmallAddress1,
				@SmallAddress2 AS SmallAddress2, 
	             @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2,
	               Isnull(IncomeGroupId,0) AS IncomeGroupId,
	               IncomeGroup, 
	               IncomeLedger,
	               ClosingBalance,
	               ([sAccounting].[fDecimalValueGet] (Income,@DecimalCount)) AS Income,	--change by dhruvik
	               ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	               ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	               ISNULL(ExpenseLedger,'') AS ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,	          
				   ([sAccounting].[fDecimalValueGet] (ISNULL(Expense,0.00),@DecimalCount)) AS Expense	--change by dhruvik
	           FROM #TempIncomeGroup IG 
	           LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	          
	     END
	     ELSE
	     BEGIN
	    
	     
	         SELECT @ReportOrgTitle  AS OrgTitle,
	             @SmallAddress1 AS SmallAddress1,
				 @SmallAddress2 AS SmallAddress2, 
				 @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2, 
				   Isnull(IncomeGroupId,0) AS IncomeGroupId,
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ([sAccounting].[fDecimalValueGet] (ISNULL(Income,0),@DecimalCount)) AS Income,	--change by dhruvik
	               Isnull(ExpenseGroupId,0) AS ExpenseGroupId,
	               ExpenseGroup AS ExpenseGroup,
	               ExpenseLedger,
				   OpeningBalance,
				   ([sAccounting].[fDecimalValueGet] (Expense,@DecimalCount)) AS Expense	--change by dhruvik
	           FROM  #TempExpenseGroup EG  LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id	
	                  
	     END	
	     
	     DROP TABLE #TempExpenseGroup
	     DROP TABLE #TempIncomeGroup
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pReimbursementAdd]
	 
	@rFromDate Date = '',
	@rToDate Date = '',
	@rCreatedUserId bigint,
	@rStoreLocationId int,
	@rTotalAmount int,
	@rApprovalAmount int,
	@rRemark nvarchar(200),
	@rApprovalRemark nvarchar(200),
	@rParticipantSourceTypeId smallint,
	@rParticipantSourceId bigint,
	@rDoctorName nvarchar(100), 
	@rAddress nvarchar(200),
	@rId int,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tReimbursement', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAccounting.tReimbursement
		(
			Id,
			FromDate,
			ToDate,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StoreLocationId,
			TotalAmount,
			ApprovedAmount,
			Remark,
			ApproverRemark,
			ParticipantSourceTypeId,
			ParticipantSourceId,
			DoctorName,
			DoctorAddress
		)
	VALUES
		(
			@lNextNumber,
			@rFromDate,
			@rToDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rStoreLocationId,
			@rTotalAmount,
			@rApprovalAmount,
			@rRemark,
			@rApprovalRemark,
			@rParticipantSourceTypeId,
			@rParticipantSourceId,
			@rDoctorName,
			@rAddress
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAccounting.tReimbursement
	    SET
	      FromDate=@rFromDate,
	      ToDate=@rToDate,
	      UpdatedUserId = @rCreatedUserId,
		  UpdatedDateTime = sCommon.fGetDate(), 
		  TotalAmount=@rTotalAmount,
		  ApprovedAmount=@rApprovalAmount,
		  Remark=@rRemark,
		  ApproverRemark=@rApprovalRemark,
		  DoctorName=@rDoctorName,
		  DoctorAddress=@rAddress
	       
	       
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pReimbursementDelete]
	
	@rId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 DELETE FROM sAccounting.tReimbursement 
	  WHERE Id=@rId 
	  DELETE FROM sAccounting.tReimbursementDetail
	  WHERE ReimbursementId=@rId
			SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pReimbursementDetailAdd]
	
	@rReimbursementDetailId int,
	@rReimbursementId int,
	@rReimbursementTypeId int, 
	@rAmount decimal(12,2),
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		BEGIN TRY	
   BEGIN TRANSACTION

    IF(@rReimbursementDetailId = 0)
    BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tReimbursementDetail', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sAccounting.tReimbursementDetail
		(
			Id,
			ReimbursementId,
			ReimbursementTypeId,
			Amount 
		)
	VALUES
		(
			@lNextNumber,
			@rReimbursementId,
			@rReimbursementTypeId,
			@rAmount
		)	
	END
	 ELSE
	 BEGIN
	  SET @lNextNumber = @rReimbursementDetailId 
	  UPDATE  sAccounting.tReimbursementDetail
	   SET	     
	      ReimbursementTypeId=@rReimbursementTypeId,
	      Amount=@rAmount
	           	    
	    WHERE [Id] = @rReimbursementDetailId
	  END 
	SELECT @lNextNumber AS Result
  
	  COMMIT TRANSACTION
         END TRY
         
        BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	    END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pReimbursementDetailGet]
	@rId [int] = 0,
	@rEmployeeCode nvarchar(20),
	@rFromDate Datetime = '',
	@rToDate Datetime = '',
	@rStoreLocationId int
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			BEGIN
				 
				SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
			END

BEGIN
 

	 SELECT 
			R.Id,
			R.FromDate,
			R.ToDate,
			R.TotalAmount,
			R.ApprovedAmount,
			R.Remark,
			R.ApproverRemark,
			R.ParticipantSourceTypeId,
			R.ParticipantSourceId,
			R.DoctorName,
			R.DoctorAddress,
			RD.Id AS ReimbursementDetailId,
			RD.ReimbursementTypeId,
			RD.Amount,
			(EM.FirstName + ' ' + EM.LastName) AS EmployeeName,
			EM.Code,
			EM.Id AS EmployeeId
	   FROM sAccounting.tReimbursement R 
	   INNER JOIN sAccounting.tReimbursementDetail RD
	   ON R.Id=RD.ReimbursementId
	   INNER JOIN sHrm.tEmployeeMaster EM
	   ON EM.Id=R.ParticipantSourceId
	    
	  WHERE ((R.Id = @rId) OR (@rId = 0))	  
	   AND ((R.CreatedDateTime >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))
	    AND ((R.CreatedDateTime <= (@rToDate+1) ) OR (ISNULL(@rToDate, '') = ''))
	    AND	((EM.Code LIKE @rEmployeeCode) OR (ISNULL(@rEmployeeCode, '') = ''))
	   AND  R.StoreLocationId=@rStoreLocationId
	   AND ISNULL(EM.IsOtherUser,0) = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pReimbursementGet]
	@rId [bigint] = 0,
	@rEmployeeCode nvarchar(20),
	@rFromDate Datetime = '',
	@rToDate Datetime = '',
	@rStoreLocationId int
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			BEGIN
				 
				SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
			END

BEGIN
 

	 SELECT 
			R.Id,
			R.FromDate,
			R.ToDate,
			R.TotalAmount,
			R.ApprovedAmount,
			R.Remark,
			R.ApproverRemark,
			R.ParticipantSourceTypeId,
			R.ParticipantSourceId,
			R.DoctorName,
			R.DoctorAddress,
			CASE R.ParticipantSourceTypeId
	   WHEN  95 THEN EM.Code
	   WHEN 1001 THEN EM2.Code
	   END AS Code,
	   CASE R.ParticipantSourceTypeId
	   WHEN  95 THEN EM.Id
	   WHEN 1001 THEN EFD.Id 
	   END AS EmployeeId,
	   CASE R.ParticipantSourceTypeId
	   WHEN  95 THEN EM.FirstName +  ' ' + EM.LastName 
	   WHEN 1001 THEN EFD.Name
	   END AS EmployeeName
			--(EM.FirstName + ' ' + EM.LastName) AS EmployeeName,
			--EM.Code,
			--EM.Id AS EmployeeId
	   FROM sAccounting.tReimbursement R 
	  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=R.ParticipantSourceId  AND R.ParticipantSourceTypeId = 95
	 LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON R.ParticipantSourceId = EFD.Id AND R.ParticipantSourceTypeId = 1001
		 LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = EFD.EmployeeId
	   --INNER JOIN sHrm.tEmployeeMaster EM
	   --ON EM.Id=R.ParticipantSourceId
	    
	  WHERE ((R.Id = @rId) OR (@rId = 0))	  
	  AND ((R.CreatedDateTime >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))
	   AND ((R.CreatedDateTime <= (@rToDate+1) ) OR (ISNULL(@rToDate, '') = ''))
	   AND (((EM.Code LIKE @rEmployeeCode) OR (ISNULL(@rEmployeeCode, '') = ''))
	   OR ((EM2.Code LIKE @rEmployeeCode) OR (ISNULL(@rEmployeeCode, '') = '')))
	  AND  R.StoreLocationId=@rStoreLocationId
	  AND ISNULL(EM.IsOtherUser,0) = 0
	   
	   order by R.Id desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pReimbursementTypeMasterGet]
	@rReimbursementId int,
	@rOrgId int 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
 

	 SELECT 
			ISNULL(RTM.Id,0) AS ReimbursementTypeId,
			RTM.Title AS Name,
			ISNULL(RD.Id,0) AS ReimbursementDetailId,
			ISNULL(RD.Amount,0) AS Amount,
			ISNULL(RD.ReimbursementId,0) AS ReimbursementId
			FROM sAccounting.tReimbursementTypeMaster RTM
		     LEFT JOIN sAccounting.tReimbursementDetail RD 
			 ON RD.ReimbursementTypeId=RTM.Id AND RD.ReimbursementId = @rReimbursementId
			
			WHERE 
				(RD.ReimbursementId=@rReimbursementId) OR (@rReimbursementId=0)
				AND RTM.Isobsolete=0
				AND RTM.OrgId=@rOrgId
END


 





 
/****** Object:  StoredProcedure [sExamination].[pLetterIssueListGet]    Script Date: 06/15/2013 16:47:07 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAccounting].[pRptAllVoucherEntryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAccountingYearId int,
	 @rTransactionDate date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rNarration nvarchar(1000),  
	 @rAmount Decimal(20,5),
	 @rVoucherTypeId int = 0,
	 @rIsApproved bit=0




	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
	  BEGIN
			SET @rNarration = sAccounting.fNarrationSearchStringGet(@rNarration) --added New function by dhananjay for mantis id - 0035082
	  END	 
BEGIN  
Declare @DecimalCount INT , @lOrgGroupId Int


	 SELECT @lOrgGroupId = OrgGroupId FROM sAccounting.tTransaction T WHERE AccountingYearId = @rAccountingYearId

	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 548


	
	 
  SELECT    
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		T.Id AS TransactionId,
		T.Narration,
		T.TransactionDate,
		T.VoucherNumber,
		TD.Amount,
		TD.Id as TransactionDetailId,
		LM.Title AS Ledger,
		VTM.Title AS VoucherType,
		TD.TransactionTypeId ,
		([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount > 0 THEN TD.Amount
		ELSE 0 END), @DecimalCount)) DebitAmount, --Added for mantis : 32211
		([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount < 0 THEN  -1 * TD.Amount
		ELSE 0 END), @DecimalCount)) CreditAmount, --Added for mantis : 32211
		AM.ReportOrgTitle As OrgTitle,
		AM.SmallAddress1 AS SmallAddress1,
		AM.SmallAddress2 AS SmallAddress2,
		T.ChequeNo,
		T.ChequeDate,
		AM.Title as AccountTitle,
		U.DisplayTitle As CreatedUserName,
		T.TransactionDate

		--sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(TD.Amount,0.00),1,2,@rOrgGroupId) AS AmountInWords
			  
  FROM 
       sAccounting.tTransaction T
       INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
       LEFT JOIN sAccounting.tLedgerMaster LM On LM.Id=TD.LedgerId
       LEFT JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
       LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	   LEFT JOIN sSecurity.tUser U ON U.Id = T.CreatedUserId
      
  WHERE 
	(T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0)
		AND (T.AccountingYearId=@rAccountingYearId)  AND LM.AccountingYearId = @rAccountingYearId
		AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '') 
		And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
		AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
		AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
		AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = '')) 
		AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
		AND ((@rIsApproved=1 AND  ISNULL(T.TransactionApproveId,0) !=0) OR (@rIsApproved = 0) )

		order by T.TransactionDate,T.VoucherNumber, LM.Id 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAccounting].[pRptExpenditureSummaryGet] 
	@rBuilder1 NVARCHAR(max) = ''
	,@rBuilder2 NVARCHAR(max) = ''
	,@rStartDate DATE
	,@rEndDate DATE
	,@rOrgGroupId INT = 0
	,@rAccountingYearId [int]
	,@rAccountId INT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @DecimalCount INT

	SELECT @DecimalCount = CASE 
			WHEN CS.Id IS NOT NULL
				THEN ISNULL(CS.ItemValue, '')
			ELSE ISNULL(CM.ItemValue, '')
			END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		AND SourceTypeId = 2010
		AND SourceId = @rOrgGroupId
	WHERE CM.Id = 548

	DECLARE @lLedgerId INT
	DECLARE @lTransactionYear INT
	DECLARE @lTransactionMonth INT
	DECLARE @lAccOpBalance DECIMAL(25, 5)
	DECLARE @lLedgerTypeId INT
	DECLARE @1ExpenceCount INT
	DECLARE @1IncomeCount INT
	DECLARE @ReportOrgTitle NVARCHAR(200)
	DECLARE @SmallAddress1 NVARCHAR(200)
	DECLARE @SmallAddress2 NVARCHAR(200)
	DECLARE @lCount int
	DECLARE @AccOpBalance DECIMAL(25, 5)
	DECLARE @LedgerTypeId Int
	DECLARE @LedgerId int
	DECLARE @OpeningBalance DECIMAL(25, 5)
	DECLARE @TransactionBalance DECIMAL(25, 5)
	DECLARE @ClosingBalance DECIMAL(25, 5)
	DECLARE @lAccountingYear NVARCHAR(100)


	SELECT @ReportOrgTitle = ReportOrgTitle
		,@SmallAddress1 = SmallAddress1
		,@SmallAddress2 = SmallAddress2
	FROM sAccounting.tAccountMaster AM
	WHERE AM.Id = @rAccountId

	SELECT @lAccountingYear = Title FROM sAccounting.tAccountingYearMaster WHERE Id = @rAccountingYearId

	IF OBJECT_ID('tempdb..#tempUpdateClosingBalance') IS NOT NULL
	BEGIN
		DROP TABLE #tempUpdateClosingBalance;
	END

	CREATE TABLE #tempUpdateClosingBalance (
		Id INT IDENTITY(1, 1)
		,LedgerId INT
		,TransactionYear INT
		,TransactionMonth INT
		,Temp_Op_Balance DECIMAL(12, 2)
		,Closing_Balance DECIMAL(12, 2)
		,Transaction_Balance DECIMAL(12, 2)
		)

	IF OBJECT_ID('tempdb..#tempLedgerMaster') IS NOT NULL
	BEGIN
		DROP TABLE #tempLedgerMaster;
	END

	CREATE TABLE #tempLedgerMaster (
		Id INT IDENTITY(1, 1)
		,LedgerId INT
		,TransactionYear INT
		,TransactionMonth INT
		,AccOpBalance DECIMAL(25, 5)
		,LedgerTypeId INT
		)

	INSERT INTO #tempLedgerMaster
	SELECT Distinct L.Id AS LedgerId
		,YEAR(T.TransactionDate) AS TransactionYear
		,MONTH(T.TransactionDate) AS TransactionMonth
		,OpeningBalance
		,LedgerTypeId
	FROM sAccounting.tLedgerMaster L
	INNER JOIN sAccounting.tTransactionDetail TD ON L.Id = TD.LedgerId
	INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
	WHERE L.AccountingYearId = @rAccountingYearId

	SELECT @lCount =  COUNT(Id) FROM #tempLedgerMaster

	WHILE (@lCount > 0)
	BEGIN
		SELECT @AccOpBalance = AccOpBalance
			,@LedgerTypeId = LedgerTypeId
			,@LedgerId = LedgerId
			,@lTransactionYear = TransactionYear
			,@lTransactionMonth = TransactionMonth
		FROM #tempLedgerMaster
		WHERE Id = @lCount

		-- Opening Balance Calulation
		BEGIN
			SELECT @OpeningBalance = ISNULL(SUM(AMOUNT), 0)
			FROM sAccounting.tTransactionDetail TD
			INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
			WHERE T.OrgGroupId = @rOrgGroupId
				AND T.AccountingYearId = @rAccountingYearId
				AND T.TransactionDate < @rStartDate
				AND TD.LedgerId = @LedgerId

				AND YEAR(T.TransactionDate) = @lTransactionYear
				AND MONTH(T.TransactionDate) = @lTransactionMonth
		END

		-- Transaction Balance
		BEGIN
			SELECT @TransactionBalance = ISNULL(SUM(AMOUNT), 0)
			FROM sAccounting.tTransactionDetail TD
			INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
			WHERE T.OrgGroupId = @rOrgGroupId
				AND T.AccountingYearId = @rAccountingYearId
				AND T.TransactionDate >= @rStartDate
				AND T.TransactionDate <= @rEndDate
				AND TD.LedgerId = @LedgerId
				AND YEAR(T.TransactionDate) = @lTransactionYear
				AND MONTH(T.TransactionDate) = @lTransactionMonth
		END

		--
		IF @LedgerTypeId = 1
		BEGIN
			SET @TransactionBalance = - 1 * @TransactionBalance
			SET @OpeningBalance = - 1 * @OpeningBalance
		END
		ELSE
		BEGIN
			SET @TransactionBalance = @TransactionBalance
			SET @OpeningBalance = @OpeningBalance
		END

		SET @OpeningBalance = @OpeningBalance + @AccOpBalance
		SET @ClosingBalance = @OpeningBalance + @TransactionBalance
			
		INSERT INTO #tempUpdateClosingBalance (
			LedgerId
			,TransactionYear
			,TransactionMonth
			,Temp_Op_Balance
			,Closing_Balance
			,Transaction_Balance
			)
		VALUES (
			@LedgerId
			,@lTransactionYear
			,@lTransactionMonth
			,@OpeningBalance
			,@ClosingBalance
			,ISNULL(@TransactionBalance, 0)
			)

		SET @lCount = @lCount - 1
	END

	--Select * from #tempUpdateClosingBalance

	CREATE TABLE #TempExpenseGroup (
		Id INT IDENTITY(1, 1)
		,TransactionYear INT
		,TransactionMonth INT
		,ExpenseGroupId INT
		,ExpenseGroup NVARCHAR(200)
		,ExpenseLedger NVARCHAR(200)
		,Expense DECIMAL(22, 2)
		,OpeningBalance DECIMAL(22, 2)
		,ExpenseTransactionBalance DECIMAL(12, 2)
		)

	INSERT INTO #TempExpenseGroup
	SELECT UC.TransactionYear
		,UC.TransactionMonth
		,ISNULL(Lg.Id, 0) AS ExpenseGroupId
		,ISNULL(LG.Title, '') AS ExpenseGroup
		,ISNULL(L.Title, '') AS ExpenseLedger
		,ISNULL(SUM(UC.Closing_Balance), 0) AS Expense
		,ISNULL(SUM(L.OpeningBalance), 0) AS OpeningBalance
		,ISNULL(SUM(UC.Transaction_Balance), 0) AS ExpenseTransactionBalance
	FROM sAccounting.tLedgerMaster L
	INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
	INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
	INNER JOIN #tempUpdateClosingBalance UC ON L.Id = UC.LedgerId
	WHERE LMG.ID = 4
		AND L.AccountingYearId = @rAccountingYearId
		AND LG.AccountingYearId = @rAccountingYearId
	GROUP BY UC.TransactionYear
		,UC.TransactionMonth
		,LG.Title
		,LMG.ID
		,L.Title
		,LG.Id
	--HAVING ISNULL(SUM(UC.Closing_Balance), 0) > 0 --remove for mantis : 0041089
	ORDER BY LMG.Id

	BEGIN
		SELECT 
			TransactionYear
			,TransactionMonth
			,@ReportOrgTitle AS OrgTitle
			,@SmallAddress1 AS SmallAddress1
			,@SmallAddress2 AS SmallAddress2
			,@rBuilder1 AS Builder1
			,@rBuilder2 AS Builder2
			,ISNULL(ExpenseGroupId, 0) AS ExpenseGroupId
			,ExpenseGroup AS ExpenseGroup
			,ExpenseLedger
			,[sAccounting].[fDecimalValueGet](OpeningBalance, @DecimalCount) AS OpeningBalance
			,[sAccounting].[fDecimalValueGet](Expense, @DecimalCount) AS Expense
			,[sAccounting].[fDecimalValueGet](ISNULL(EG.ExpenseTransactionBalance, 0.00), @DecimalCount) AS ExpenseTransactionBalance
			,@lAccountingYear AS AccountingYear

		FROM #TempExpenseGroup EG
	END

	DROP TABLE #TempExpenseGroup
--BEGIN
--		SELECT
--		  0 AS TransactionYear,
--		  0 AS TransactionMonth,
--			'' AS OrgTitle,
--			'' AS SmallAddress1,
--			'' AS SmallAddress2,
--			'' AS Builder1,
--			'' AS Builder2,
--			0 AS ExpenseGroupId,
--			'' AS ExpenseGroup,
--			'' AS ExpenseLedger,
--			0.00 AS OpeningBalance,
--			0.00 AS Expense,
--			0.00 AS ExpenseTransactionBalance,
--			'' AS AccountingYear
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAccounting].[pRptExpenseListGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeCode nvarchar(100),
    @rEmployeeName nvarchar(100) ,
	@rEmployeeId  bigint=0, 
	@rFromDate date,
    @rTodate date,   
    @rExpenseGroupId int=0,    
    @rStatusId int=0,
    @rOrgId smallint,
    @rIsDetail bit,
      @rBatchId int
	

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
		LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		AND SourceTypeId = 2010 AND SourceId = @rOrgId WHERE CM.Id = 548

       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 E.Id AS ExpenseId,
			 E.EmployeeId,
			 --E.Amount, 
			 ([sAccounting].[fDecimalValueGet] (E.Amount, @DecimalCount)) AS Amount,	--change by Nilesh
			 E.Remark,
			 E.CreatedUserId,
			 E.CreatedDateTime,			 
			 E.UpdatedUserId,
			 E.UpdatedDateTime,
			 E.ExpenseDate,
			 E.ExpenseGroupId,
			 EGM.Title AS ExpenseGroupName,
			 EM.EmployeeName,
			 EM.Code AS EmployeeCode,
			 E.StatusReason,
			 ISNULL(E.StatusId,0) AS StatusId,
			 ISNULL(SM.Title,'Pending') AS StatusName,
			 --OM.DisplayTitle AS OrganizationName,
			 --ED.Amount AS ExpenseDetailAmount,
			 ([sAccounting].[fDecimalValueGet] (ED.Amount, @DecimalCount)) AS ExpenseDetailAmount,	--change by Nilesh
			 ESGM.Title As ExpenseTitle,
			 ESGM.Id As ExpenseSubGroupId,
			 @rIsDetail AS IsDetail,
			 ED.Remark AS ExpenseSubRemark
			 
        FROM 
				sAccounting.tExpense E
	  INNER JOIN sAccounting.tExpenseGroupMaster EGM ON EGM.Id = E.ExpenseGroupId
	  INNER JOIN sAccounting.tExpenseSubGroupMaster ESGM ON ESGM.ExpenseGroupId= EGM.Id
	  LEFT JOIN sAccounting.tExpenseDetail ED ON E.Id=ED.ExpenseId ANd ED.ExpenseSubGroupId = ESGM.Id
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = E.EmployeeId 
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = E.StatusId
	  --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = E.OrgId
    	WHERE 
    		
    		
    		--(E.Id = @rId OR @rId = 0)
     (E.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((E.ExpenseDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((E.ExpenseDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
      AND (E.ExpenseGroupId = @rExpenseGroupId OR @rExpenseGroupId = 0)      
       AND ((E.OrgId = @rOrgId) OR (@rOrgId = 0))
           AND (E.BatchId = @rBatchId OR @rBatchId = 0)
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (E.StatusId = @rStatusId OR @rStatusId = 0)
      Order By ExpenseDate DESC
    		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pRptProfitAndLossGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
     Declare @DecimalCount INT
	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548

	Declare @lLedgerId int 
	Declare @lOpeningBalance Decimal (12,2)
	Declare @ltIncome Decimal (12,2)
	Declare @ltExpense Decimal (12,2)
	Declare @lInIncome Decimal(12,2)
	Declare @lInClosing Decimal(12,2)
	Declare @lExOpening Decimal(12,2)
	Declare @lExExpense Decimal(12,2)
	Declare @lGrossProfit Decimal(12,2)
	Declare @lGrossLoss Decimal(12,2)
	Declare @lCount int
	Declare @lLedgerName Nvarchar(150)
	Declare @lLedgerGroupName Nvarchar(150)
	Declare @lLedgerMainGroupName Nvarchar(150) 
	DECLARE @1ExpenceCount int
	DECLARE @1IncomeCount int
	Declare @ReportOrgTitle Nvarchar(200)
	Declare @SmallAddress1  Nvarchar(200)
	Declare	@SmallAddress2 Nvarchar(200)

	SELECT @ReportOrgTitle=ReportOrgTitle, @SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
	FROM sAccounting.tAccountMaster AM 
	WHERE AM.Id= @rAccountId  
  
	CREATE TABLE #tempUpdateClosingBalance
 	(	
		Id INT IDENTITY (1, 1),
 		LedgerId int,
 		Temp_Op_Balance decimal(12,2),
 		Closing_Balance decimal(12,2),
 		Transaction_Balance decimal(12,2)
 	)  	
 	INSERT INTO #tempUpdateClosingBalance 
	(LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
		
	--SELECT * FROM #tempUpdateClosingBalance

	CREATE TABLE #TempExpenseGroup
	(
	   Id INT IDENTITY(1,1),
	   ExpenseGroupId int,
	   ExpenseGroup nvarchar(200),
	   ExpenseLedger nvarchar(200),
	   Expense decimal(22,2),
	   OpeningBalance decimal(22,2),
	   ExpenseTransactionBalance decimal(12,2) 
	)
		
	CREATE TABLE #TempIncomeGroup
	(
	   Id INT IDENTITY(1,1),
	   IncomeGroupId int,
	   IncomeGroup nvarchar(200),
	   IncomeLedger nvarchar(200),
	   Income decimal(22,2),
	   ClosingBalance decimal,
	   IncomeTransactionBalance decimal(12,2)
	)
		
	INSERT INTO #TempExpenseGroup
	SELECT 
        ISNULL(Lg.Id,0) as ExpenseGroupId,		
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance,
		ISNULL(SUM(UC.Transaction_Balance),0) AS ExpenseTransactionBalance
	FROM 
		sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
	WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	HAVING ISNULL(SUM(UC.Closing_Balance),0) > 0
	ORDER BY LMG.Id	
		
		
	INSERT INTO #TempIncomeGroup
    SELECT  
        ISNULL(Lg.Id,0) as IncomeGroupId,		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance,
		ISNULL(SUM(UC.Transaction_Balance),0) AS IncomeTransactionBalance
	FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
	WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
	GROUP BY LG.Title,LMG.ID,L.Title,LG.Id HAVING ISNULL(SUM(UC.Closing_Balance),0) > 0	
	ORDER BY LMG.Id	
	      
	     
	SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup

	IF(@1InComeCount >= @1ExpenceCount)
	BEGIN		    
		SELECT 
			@ReportOrgTitle  AS OrgTitle,
			@SmallAddress1 AS SmallAddress1,
			@SmallAddress2 AS SmallAddress2, 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(IncomeGroupId,0) AS IncomeGroupId,
	        IncomeGroup, 
	        IncomeLedger,
	        [sAccounting].[fDecimalValueGet](ClosingBalance,@DecimalCount)AS ClosingBalance,
	        [sAccounting].[fDecimalValueGet](Income,@DecimalCount) AS Income,
	        ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	        ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	        ISNULL(ExpenseLedger,'') AS ExpenseLedger,
			[sAccounting].[fDecimalValueGet](ISNULL(OpeningBalance,0),@DecimalCount) AS OpeningBalance,	          
			[sAccounting].[fDecimalValueGet](ISNULL(Expense,0.00),@DecimalCount) AS Expense,
			[sAccounting].[fDecimalValueGet](ISNULL(IG.IncomeTransactionBalance,0.00),@DecimalCount) AS IncomeTransactionBalance,
			[sAccounting].[fDecimalValueGet](ISNULL(EG.ExpenseTransactionBalance,0.00),@DecimalCount) AS ExpenseTransactionBalance
		FROM #TempIncomeGroup IG 
			LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	          
	END
	ELSE
	BEGIN
	    SELECT 
			@ReportOrgTitle  AS OrgTitle,
	        @SmallAddress1 AS SmallAddress1,
			@SmallAddress2 AS SmallAddress2, 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			ISNULL(IncomeGroupId,0) AS IncomeGroupId,
	        ISNULL(IncomeGroup,'') AS IncomeGroup, 
	        ISNULL(IncomeLedger,'') AS IncomeLedger,
	        [sAccounting].[fDecimalValueGet](ISNULL(ClosingBalance,0),@DecimalCount) AS ClosingBalance,
	        [sAccounting].[fDecimalValueGet](ISNULL(Income,0),@DecimalCount) AS Income,
	        ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	        ExpenseGroup AS ExpenseGroup,
	        ExpenseLedger,
			[sAccounting].[fDecimalValueGet](OpeningBalance,@DecimalCount) AS OpeningBalance,
			[sAccounting].[fDecimalValueGet](Expense,@DecimalCount) AS Expense,
			[sAccounting].[fDecimalValueGet](ISNULL(EG.ExpenseTransactionBalance,0.00),@DecimalCount) AS ExpenseTransactionBalance,
			[sAccounting].[fDecimalValueGet](ISNULL(IG.IncomeTransactionBalance,0.00),@DecimalCount) AS IncomeTransactionBalance
	    FROM #TempExpenseGroup EG  
			LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id	
	 END	
	     
	 DROP TABLE #TempExpenseGroup
	 DROP TABLE #TempIncomeGroup
		

--SELECT
--	'' AS OrgTitle,
--	'' AS SmallAddress1,
--	'' AS SmallAddress2,
--	'' AS Builder1,
--	'' AS Builder2,
--	0 AS IncomeGroupId,
--	'' AS IncomeGroup,
--	'' AS IncomeLedger,
--	0.00 AS ClosingBalance,
--	0.00 AS Income,
--	0 AS ExpenseGroupId,
--	'' AS ExpenseGroup,
--	'' AS ExpenseLedger,
--	0.00 AS OpeningBalance,
--	0.00 AS Expense,
--	0.00 AS ExpenseTransactionBalance,
--	0.00 AS IncomeTransactionBalance
	    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAccounting].[pRptReceiptsAndPaymentsGet]
		   	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId  int=0
          
AS
SET NOCOUNT ON

BEGIN

     Declare @DecimalCount INT
	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548

DECLARE @lIsReportClient bit=0

IF EXISTS (SELECT 1 FROM [sCommon].[tReportClient] WHERE ReportId = 30724 AND OrgGroupId = @rOrgGroupId)
	SET @lIsReportClient = 1
	
	


DECLARE @1OpeningBalance DECIMAL(22,2)
DECLARE @1ClosingBalance DECIMAl(22,2)
DECLARE @1Credit DECIMAl(12,2)
DECLARE @1Debit DECIMAl(12,2)

DECLARE @Credit_Closing DECIMAl(12,2)
DECLARE @Debit_Closing DECIMAl(12,2)

SET @Debit_Closing=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			 ON TD1.TransactionId=T1.Id WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=2	AND TransactionTypeId = 2 
			 AND (T1.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='') AND (T1.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='')),0)
SET @Credit_Closing=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			ON TD1.TransactionId=T1.Id WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=3 AND TransactionTypeId = 1
			AND (T1.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='') AND (T1.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='')),0)

SET @1Debit=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			 ON TD1.TransactionId=T1.Id WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=2	AND TransactionTypeId = 2 
			 AND (T1.TransactionDate < @rStartDate)),0)
SET @1Credit=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			ON TD1.TransactionId=T1.Id WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=3 AND TransactionTypeId = 1
			AND (T1.TransactionDate < @rStartDate)),0)


     
	CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)	    
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,0,''
	
	select @1OpeningBalance = OpeningBalance from sAccounting.tLedgerMaster where Code = '2' and AccountingYearId = @rAccountingYearId
	--SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance 	FROM #tempUpdateClosingBalance 
	

	SELECT  
	L.LedgerTypeId,
	LGM.Title AS LedgerGroupTitle,
	L.Title AS LedgerTitle,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	T.Id AS TransactionId,	
	--Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
	--		 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId 
	--		 WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=2	AND TransactionTypeId = 2),0) AS Credit,
	--Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
	--		ON TD1.TransactionId=T1.Id AND T.Id=T1.Id Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId 
	--		WHERE T1.AccountingYearId = @rAccountingYearId	AND VoucherTypeId=3 AND TransactionTypeId = 1),0) AS Debit,
			
	Isnull((select [sAccounting].[fDecimalValueGet](ABS(sum(td1.Amount)),@DecimalCount) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			 ON TD1.TransactionId=T1.Id AND T.Id=T1.Id Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId 
			 WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=2	AND TransactionTypeId = 2),0) AS Debit,
	Isnull((select [sAccounting].[fDecimalValueGet](ABS(sum(td1.Amount)),@DecimalCount) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			ON TD1.TransactionId=T1.Id AND T.Id=T1.Id Inner join sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId AND L.AccountingYearId = T1.AccountingYearId 
			WHERE T1.AccountingYearId = @rAccountingYearId	AND VoucherTypeId=3 AND TransactionTypeId = 1),0) AS Credit,

	--@1OpeningBalance + @1Debit-@1Credit AS ClosingBalance,
	TD.LedgerId,
	CONVERT(nvarchar,ISNULL(T.TransactionDate,''),103) AS TransactionDate,
	T.VoucherNumber,
	T.Narration,
	VTM.Title As VoucherType,
	T.VoucherTypeId,	
	L.TITLE,
	CASE WHEN @lIsReportClient = 1 THEN [sAccounting].[fDecimalValueGet]((@1OpeningBalance + @1Debit-@1Credit),@DecimalCount) ELSE [sAccounting].[fDecimalValueGet](ISNULL(@1OpeningBalance,0),@DecimalCount) END AS OpeningBalance,
	CASE WHEN @lIsReportClient = 1 THEN [sAccounting].[fDecimalValueGet](((@1OpeningBalance + @1Debit-@1Credit) + @Debit_Closing - @Credit_Closing),@DecimalCount) ELSE [sAccounting].[fDecimalValueGet]((@1OpeningBalance + @1Debit-@1Credit),@DecimalCount) END AS ClosingBalance,
	--ISNULL(@1OpeningBalance,0) AS OpeningBalance,	
	AM.ReportOrgTitle As OrgTitle,
	AM.SmallAddress1 AS SmallAddress1,
	AM.SmallAddress2 AS SmallAddress2,
	T.ChequeNo
	FROM 		
		sAccounting.tTransaction T 
		INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id 
		INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
		INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
		INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
		INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	WHERE 		
		(T.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='')  
		AND	(T.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='') 
		AND(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
		AND	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) 
		AND	(T.AccountingYearId=@rAccountingYearId OR @rAccountingYearId = 0)		
		AND (L.AccountingYearId=@rAccountingYearId)
		AND (T.AccountId=@rAccountId OR @rAccountId=0)  
		AND LGM.Code not IN ( '2','3') AND VoucherTypeid in (2,3)
	
	GROUP BY 	
	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Id,TD.TransactionTypeId,L.Title,T.VoucherTypeId,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2,T.ChequeNo,L.LedgerTypeId,
	LGM.Title,L.Title
	ORDER BY 
	T.TransactionDate,T.VoucherNumber
END

----For Report

--ALTER PROCEDURE [sAccounting].[pRptReceiptsAndPaymentsGet]
		   	
--	@rBuilder1 nvarchar(max)='',
--	@rBuilder2 nvarchar(max)='', 
--	@rStartDate Date,
--	@rEndDate Date,
--	@rOrgGroupId int = 0,
--	@rAccountingYearId [int],
--	@rLedgerId [int],
--	@rLedgerGroupId [int],
--	@rAccountId  int=0
          
--AS
--SET NOCOUNT ON

--BEGIN
--SELECT
--	L.LedgerTypeId,
--	@rBuilder1 AS Builder1,
--	@rBuilder2 AS Builder2,
--	T.Id AS TransactionId,
--	Convert(Decimal,0) AS Credit,
--	Convert(Decimal,0) AS Debit,
--	TD.LedgerId,
--	T.TransactionDate,
--	T.VoucherNumber,
--	T.Narration,
--	VTM.Title As VoucherType,
--	T.VoucherTypeId,
--	Convert(Decimal,0) AS OpeningBalance,
--	Convert(Decimal,0) AS ClosingBalance,
--	AM.ReportOrgTitle As OrgTitle,
--	AM.SmallAddress1 AS SmallAddress1,
--	AM.SmallAddress2 AS SmallAddress2,
--	T.ChequeNo,
--	LGM.Title AS LedgerGroupTitle,
--	L.Title AS LedgerTitle,
--	LGM.Id AS LedgerGroupId

--FROM 		
--		sAccounting.tTransaction T 
--		INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id --AND (TD.LedgerId <> @rLedgerId)
--		INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
--		INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
--		INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
--		INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 
CREATE OR ALTER PROCEDURE [sAccounting].[pRptReceiptsAndPaymentsWithDetailsGet]
		   	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rAccountId  int=0
          
AS
SET NOCOUNT ON

BEGIN

     Declare @DecimalCount INT
	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548

DECLARE @lIsReportClient bit=0

IF EXISTS (SELECT 1 FROM [sCommon].[tReportClient] WHERE ReportId = 30724 AND OrgGroupId = @rOrgGroupId)
	SET @lIsReportClient = 1
	
	


DECLARE @1OpeningBalance DECIMAL(22,2)
DECLARE @1ClosingBalance DECIMAl(22,2)
DECLARE @1Credit int
DECLARE @1Debit int

DECLARE @2Credit int
DECLARE @2Debit int

DECLARE @Credit_Closing int
DECLARE @Debit_Closing int

SET @Debit_Closing=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id 
			 INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId 
			 INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T1.VoucherTypeId
			 WHERE T1.AccountingYearId = @rAccountingYearId AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))	 
	 or (L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE = '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))
	 ) 
		AND (T1.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='') AND (T1.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='')),0)


SET @Credit_Closing=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id
			INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD1.LedgerId 
			 INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T1.VoucherTypeId
			 WHERE T1.AccountingYearId = @rAccountingYearId AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))	 
	 or (L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE = '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))
	 ) 
		AND (T1.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='') AND (T1.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='')),0)


SELECT * INTO #DayBookTemp
FROM (SELECT 
	@rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,
	T.TransactionDate,
	T.VoucherNumber,
	L.TITLE,
	VTM.Title As VoucherType,
	T.Narration,
	ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0) AS CREDIT,
	ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0) AS DEBIT,
	CASE WHEN TD.TransactionTypeId = 1 THEN 'CREDIT' ELSE 'DEBIT' END AS TOBY,
	ISNULL(@1OpeningBalance,0) AS OpeningBalance,
	ISNULL(@1ClosingBalance,0) AS ClosingBalance,
	AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id 
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	
	WHERE (T.TransactionDate >= '1900-01-01')  AND
	(T.TransactionDate < @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND		
	T.AccountingYearID=@rAccountingYearId AND
	 L.AccountingYearId = @rAccountingYearId
	 AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))	 
	 or (L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE = '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))
	 )

	AND (T.AccountId=@rAccountId OR @rAccountId=0 )  
	 
	GROUP BY 	T.TransactionDate,TD.TransactionTypeId,T.VoucherNumber,T.Id,
				L.Title,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2) P

--SELECT * FROM #DayBookTemp

SET @1Debit = (SELECT SUM(DEBIT) FROM #DayBookTemp)
SET @1Credit = (SELECT SUM(CREDIT) FROM #DayBookTemp)

SET @2Debit=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			 ON TD1.TransactionId=T1.Id WHERE T1.AccountingYearId = @rAccountingYearId AND VoucherTypeId=2	AND TransactionTypeId = 2 
			 AND (T1.TransactionDate < @rStartDate)),0)
SET @2Credit=Isnull((select ABS(sum(td1.Amount)) from sAccounting.tTransaction T1 INNER JOIN sAccounting.tTransactionDetail TD1 
			ON TD1.TransactionId=T1.Id WHERE T1.AccountingYearId = @rAccountingYearId AND (VoucherTypeId=3 OR VoucherTypeId=1) AND TransactionTypeId = 1
			AND (T1.TransactionDate < @rStartDate)),0)


PRINT(@1Debit)
PRINT(@1Credit)
     
	CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)	    
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,0,''
	
	select @1OpeningBalance = OpeningBalance from sAccounting.tLedgerMaster where Code = '2' and AccountingYearId = @rAccountingYearId
	--SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance 	FROM #tempUpdateClosingBalance 
	--select @1OpeningBalance , @2Debit,@2Credit,@1Debit,@1Credit,@lIsReportClient

	SELECT  
	L.LedgerTypeId,
	LGM.Title AS LedgerGroupTitle,
	L.Title AS LedgerTitle,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	T.Id AS TransactionId,	
	[sAccounting].[fDecimalValueGet](ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0),@DecimalCount) AS Credit,
	[sAccounting].[fDecimalValueGet](ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0),@DecimalCount) AS Debit,			

	--@1OpeningBalance + @1Debit-@1Credit AS ClosingBalance,
	TD.LedgerId,
	CONVERT(nvarchar,ISNULL(T.TransactionDate,''),103) AS TransactionDate,
	T.VoucherNumber,
	T.Narration,
	VTM.Title As VoucherType,
	T.VoucherTypeId,	
	L.TITLE,
	CASE WHEN @lIsReportClient = 1 THEN [sAccounting].[fDecimalValueGet]((@1OpeningBalance + @2Debit-@2Credit),@DecimalCount) ELSE [sAccounting].[fDecimalValueGet]((@1OpeningBalance + @1Debit-@1Credit),@DecimalCount) END AS OpeningBalance,
	CASE WHEN @lIsReportClient = 1 THEN [sAccounting].[fDecimalValueGet](((@1OpeningBalance + @2Debit-@2Credit) + @Debit_Closing - @Credit_Closing),@DecimalCount) ELSE [sAccounting].[fDecimalValueGet](((@1OpeningBalance + @1Debit-@1Credit) + @Debit_Closing - @Credit_Closing),@DecimalCount)END AS ClosingBalance,
	--ISNULL(@1OpeningBalance,0) AS OpeningBalance,	
	AM.ReportOrgTitle As OrgTitle,
	AM.SmallAddress1 AS SmallAddress1,
	AM.SmallAddress2 AS SmallAddress2,
	T.ChequeNo
	FROM 		
		sAccounting.tTransaction T 
		INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id 
		INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
		INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
		INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
		INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	WHERE 		
		(T.TransactionDate >= @rStartDate OR ISNULL(@rStartDate,'')='')  
		AND	(T.TransactionDate <= @rEndDate OR ISNULL(@rEndDate,'')='') 
		AND(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
		AND	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) 
		AND	(T.AccountingYearId=@rAccountingYearId OR @rAccountingYearId = 0)		
		AND (L.AccountingYearId=@rAccountingYearId)
		AND (T.AccountId=@rAccountId OR @rAccountId=0)  
		AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))	 
	 or (L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE = '2' AND VTM.Title ='Journal Voucher' And (@lIsReportClient = 1 OR TransactionTypeId <> 2))
	 )		
	
	GROUP BY 	
	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Id,TD.TransactionTypeId,L.Title,T.VoucherTypeId,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2,T.ChequeNo,L.LedgerTypeId,
	LGM.Title,L.Title
	ORDER BY 
	T.TransactionDate,T.VoucherNumber
END

----For Report

--ALTER PROCEDURE [sAccounting].[pRptReceiptsAndPaymentsGet]
		   	
--	@rBuilder1 nvarchar(max)='',
--	@rBuilder2 nvarchar(max)='', 
--	@rStartDate Date,
--	@rEndDate Date,
--	@rOrgGroupId int = 0,
--	@rAccountingYearId [int],
--	@rLedgerId [int],
--	@rLedgerGroupId [int],
--	@rAccountId  int=0
          
--AS
--SET NOCOUNT ON

--BEGIN
--SELECT
--L.LedgerTypeId,
--@rBuilder1 AS Builder1,
--@rBuilder2 AS Builder2,
--T.Id AS TransactionId,
--0 AS Credit,
--0 AS Debit,
--TD.LedgerId,
--T.TransactionDate,
--T.VoucherNumber,
--T.Narration,
--VTM.Title As VoucherType,
--T.VoucherTypeId,
----LEFT(VTM.Title,2) As VoucherType
--0 AS OpeningBalance,
--0 AS ClosingBalance,
--AM.ReportOrgTitle As OrgTitle,
--AM.SmallAddress1 AS SmallAddress1,
--AM.SmallAddress2 AS SmallAddress2,
--T.ChequeNo,
--LGM.Title AS LedgerGroupTitle,
--L.Title AS LedgerTitle,
--LGM.Id AS LedgerGroupId

--FROM 		
--		sAccounting.tTransaction T 
--		INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id AND (TD.LedgerId <> @rLedgerId)
--		INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
--		INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
--		INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
--		INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pRptReimbursement]
 
	@rId [int] = 0,
	@rFromDate datetime = '1900/1/1',
	@rToDate datetime = '1900/1/1',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

IF(@rId > 0)
BEGIN
   SELECT  
			R.Id,
			CASE R.ParticipantSourceTypeId
	   WHEN  95 THEN EM.Code
	   WHEN 1001 THEN EM2.Code
	   END AS EmployeeCode,
			--EM.Code AS EmployeeCode,
			--(EM.FirstName + ' ' + EM.LastName) AS EmployeeName,
			RTM.Title AS ReimbursementTypeName,
			RD.Amount,
			R.FromDate,
			R.ToDate,
			R.DoctorName,
			R.DoctorAddress,
			EM.Id AS EmployeeId,
			R.TotalAmount,
			R.ApprovedAmount		
		,CASE R.ParticipantSourceTypeId
	   WHEN  95 THEN EM.FirstName +  ' ' + EM.LastName 
	   WHEN 1001 THEN EFD.Name
	   END AS EmployeeName,
	   @rFromDate AS FromDateSearch,
 	   @rToDate AS ToDateSearch 	
    
    
		FROM   sAccounting.tReimbursement R
		INNER JOIN sAccounting.tReimbursementDetail RD
		ON R.Id=RD.ReimbursementId
		INNER JOIN sAccounting.tReimbursementTypeMaster RTM
		ON RTM.Id=RD.ReimbursementTypeId
		--INNER JOIN sHrm.tEmployeeMaster EM
		--ON EM.Id=R.ParticipantSourceId
		LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=R.ParticipantSourceId  AND R.ParticipantSourceTypeId = 95
   LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON R.ParticipantSourceId = EFD.Id AND R.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = EFD.EmployeeId 	
		
		WHERE 
		(R.Id=@rId) OR (@rId=0)
		AND ((R.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((R.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND R.StoreLocationId=@rStoreLocationId OR (@rStoreLocationId=0)
		AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM2.IsOtherUser,0) = 0		
	END
	ELSE
		BEGIN
		 SELECT  
			R.Id,
			CASE R.ParticipantSourceTypeId
	   WHEN  95 THEN EM.Code
	   WHEN 1001 THEN EM2.Code
	   END AS EmployeeCode,
	   CASE R.ParticipantSourceTypeId
	   WHEN  95 THEN EM.Id
	   WHEN 1001 THEN EFD.Id 
	   END AS EmployeeId,
	   CASE R.ParticipantSourceTypeId
	   WHEN  95 THEN EM.FirstName +  ' ' + EM.LastName 
	   WHEN 1001 THEN EFD.Name
	   END AS EmployeeName,
			--EM.Code AS EmployeeCode,
			--(EM.FirstName + ' ' + EM.LastName) AS EmployeeName,
			R.FromDate,
			R.ToDate,
			R.DoctorName,
			R.DoctorAddress,
			EM.Id AS EmployeeId,
			R.TotalAmount,
			R.ApprovedAmount,
			@rFromDate AS FromDateSearch,
 	       @rToDate AS ToDateSearch 
    
    
		FROM   sAccounting.tReimbursement R
		--INNER JOIN sHrm.tEmployeeMaster EM
		--ON EM.Id=R.ParticipantSourceId
		LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=R.ParticipantSourceId  AND R.ParticipantSourceTypeId = 95
	 LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON R.ParticipantSourceId = EFD.Id AND R.ParticipantSourceTypeId = 1001
		 LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = EFD.EmployeeId   		
		
		WHERE 
		(R.Id=@rId) OR (@rId=0)
		AND ((R.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((R.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND R.StoreLocationId=@rStoreLocationId OR (@rStoreLocationId=0) 
		AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM2.IsOtherUser,0) = 0
		END
END

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

BEGIN

	    SELECT 
		   '' AS Title,
 	       0 AS Cost,
 	       0 AS SourceTypeId,
 	       @rFromDate AS FromDate,
 	       @rToDate AS ToDate
 		 
 	--    SELECT 
 	--       CASE SourceTypeId 
 	--       WHEN 51 THEN 'FirstAidCost'  
 	--       WHEN 48 THEN 'PharmacyCost'    
 	--       END AS Title,
 	--       SUM(WeightedAverageCost * Quantity) AS Cost,
 	--       WAC.SourceTypeId,
 	--       @rFromDate AS FromDate,
 	--       @rToDate AS ToDate
	 --     FROM sIp.tWeightedAverageCostLog WAC
			
	 --  WHERE	
		--	WAC.SourceTypeId IN (48,51)
		--AND((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		--AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		--AND WAC.StoreLocationId=@rStoreLocationId
		--AND WAC.OrgId=@rOrgId
		
		--GROUP BY SourceTypeId,CreatedDateTime
	 
		--UNION
		--SELECT 'Expense Cost',SUM(Amount),0 AS ExpenseCost,@rFromDate AS FromDate,
 	--       @rToDate AS ToDate 
		--FROM sAccounting.tExpense E
		--WHERE
		--((E.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		--AND ((E.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		--AND E.StoreLocationId=@rStoreLocationId
		--AND E.OrgId=@rOrgId
		
		--GROUP BY Amount
		
		 	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAccounting].[pRptVoucherEntryApproveGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rTransactionId bigint,
	 @rAccountingYearId int,
	 @rTransactionDate date,
	 @rOrgGroupId int,
	 @rAccountId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN  

		/**Added for mantis : 32211 by Nilesh**/
	 Declare @DecimalCount INT
	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548


  SELECT    @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			T.Id AS Id,
			T.Narration,
			T.TransactionDate,
			T.VoucherNumber,
			--TD.Amount,
			[sAccounting].[fDecimalValueGet] (TD.Amount,@DecimalCount) Amount,
			TD.Id as TransactionDetailId,
			LM.Title AS Ledger,
			VTM.Title AS VoucherType,
			TD.TransactionTypeId ,
			--(CASE WHEN TD.Amount > 0 THEN TD.Amount
			--ELSE 0 END) DebitAmount,  --Commented for mantis : 32211 by Nilesh
			--(CASE WHEN TD.Amount < 0 THEN -1 * TD.Amount
			--ELSE 0 END) CreditAmount, --Commented for mantis : 32211 by Nilesh
			([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount > 0 THEN TD.Amount
												ELSE 0 END), @DecimalCount)) DebitAmount, --Added for mantis : 32211 by Nilesh
			([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount < 0 THEN  -1 * TD.Amount
												ELSE 0 END), @DecimalCount)) CreditAmount, --Added for mantis : 32211 by Nilesh
			AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
			
			  
  FROM 
       sAccounting.tTransactionApprove T
       INNER JOIN sAccounting.tTransactionApproveDetail TD ON T.Id=TD.TransactionId
       LEFT JOIN sAccounting.tLedgerMaster LM On LM.Id=TD.LedgerId
       LEFT JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
       LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
      
      
  WHERE 
			(T.Id=@rTransactionId OR @rTransactionId = 0 )  
			AND (T.AccountingYearId=@rAccountingYearId)  AND LM.AccountingYearId = @rAccountingYearId
			ANd (T.TransactionDate=@rTransactionDate OR ISNULL(@rTransactionDate,'')='1900-01-01')     
			AND (T.OrgGroupId=@rOrgGroupId)
			AND (T.AccountId=@rAccountId )  
   Order By T.VoucherTypeId,T.VoucherNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pRptVoucherEntryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rTransactionId bigint,
	 @rAccountingYearId int,
	 @rTransactionDate date,
	 @rOrgGroupId int,
	 @rAccountId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN  
Declare @DecimalCount INT
	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
	 
  SELECT    
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		T.Id AS TransactionId,
		T.Narration,
		T.TransactionDate,
		T.VoucherNumber,
		TD.Amount,
		TD.Id as TransactionDetailId,
		LM.Title AS Ledger,
		VTM.Title AS VoucherType,
		TD.TransactionTypeId ,
		--(CASE WHEN TD.Amount > 0 THEN TD.Amount --Commented for mantis : 32211
		--ELSE 0 END) DebitAmount,
		--(CASE WHEN TD.Amount < 0 THEN -1 * TD.Amount Commented for mantis : 32211
		--ELSE 0 END) CreditAmount,
		([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount > 0 THEN TD.Amount
		ELSE 0 END), @DecimalCount)) DebitAmount, --Added for mantis : 32211
		([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount < 0 THEN  -1 * TD.Amount
		ELSE 0 END), @DecimalCount)) CreditAmount, --Added for mantis : 32211
		AM.ReportOrgTitle As OrgTitle,
		AM.SmallAddress1 AS SmallAddress1,
		AM.SmallAddress2 AS SmallAddress2,
		T.ChequeNo,
		T.ChequeDate,
		AM.Title as AccountTitle,
		U.DisplayTitle As CreatedUserName

		--sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(TD.Amount,0.00),1,2,@rOrgGroupId) AS AmountInWords
			  
  FROM 
       sAccounting.tTransaction T
       INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
       LEFT JOIN sAccounting.tLedgerMaster LM On LM.Id=TD.LedgerId
       LEFT JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
       LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	   LEFT JOIN sSecurity.tUser U ON U.Id = T.CreatedUserId
      
  WHERE 
		(T.Id=@rTransactionId OR @rTransactionId = 0 )  
		AND (T.AccountingYearId=@rAccountingYearId)  AND LM.AccountingYearId = @rAccountingYearId
		ANd (T.TransactionDate=@rTransactionDate OR ISNULL(@rTransactionDate,'')='1900-01-01')     
		AND (T.OrgGroupId=@rOrgGroupId)
		AND (T.AccountId=@rAccountId )  
   Order By T.VoucherTypeId,T.VoucherNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pTarij]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rOrderBy smallint,
	@rTarij Smallint,
	@rAccountId  int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

   --SELECT '' AS Builder1,
	  --    '' AS Builder2,
   --       '' As Id,
		 -- '' As CreditBalance,
		 -- '' AS DebitBalance,
		 -- '' As CashOpBalance,
		 -- '' AS LedgerId,
		 -- '' AS LedgerName,
		 -- '' As LedgerTypeId,
		 -- '' AS OpeningBalance,
		 -- '' AS LedgerGroup,
		 -- '' AS LedgerMainGroup,
		 -- '' AS OrgTitle,
		 --'' AS  SmallAddress1,
		 -- '' AS SmallAddress2

Declare @lLedgerId int 
Declare @lCashOpBalance Decimal (12,2)
Declare @lOpeningBalance Decimal (12,2)
Declare @lCreditBalance Decimal (12,2)
Declare @lDebitBalance Decimal (12,2)
Declare @lLOpeningBalance Decimal(12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)

	
	 SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
	--EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,@rLedgerMainGroupId,@rISProfitLoss
	
	SELECT @lLOpeningBalance = Sum(OpeningBalance) From sAccounting.tLedgerMaster L
	INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId=LG.Id AND LG.LedgerMainGroupId = 2 and L.AccountingYearId=@rAccountingYearId And LG.OrgGroupId = @rOrgGroupId
    
	--change by dhruvik
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
		LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548

	CREATE TABLE #tTarij
 		(	Id INT IDENTITY (1,1),
 			CreditBalance decimal(12,2),
 			DebitBalance decimal(12,2),
 			CashOpBalance Decimal(12,2),
 			LedgerId int,
 			LedgerName varchar(100),
 			LedgerTypeId int,
 			OpeningBalance decimal(12,2),
 			LedgerGroup varchar(100),
			LedgerMainGroup Varchar(100)		
		
 		) 
 	IF @rTarij =1 
 	BEGIN	
 		INSERT INTO #tTarij    
		SELECT 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 1 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as CreditBalance, 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 2 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as DebitBalance, 
		(Select ISNULL(Sum(OpeningBalance),0) From sAccounting.tLedgerMaster L1 INNER JOIN sAccounting.tLedgerGroupMaster LG ON LG.Id=L1.LedgerGroupId AND LG.OrgGroupId=@rOrgGroupId AND L1.AccountingYearId=@rAccountingYearId) as CashOpBalance, 
		L.Id, L.Title, L.LedgerTypeId,L.OpeningBalance, 
		LG.Title AS GName, LGM.Title AS MGName 
		
       		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		AND LG.LedgerMainGroupID <> 2
    END
     
    ELSE
    
    BEGIN
 		INSERT INTO #tTarij    
		SELECT 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 1 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as CreditBalance, 
		(Select ISNULL(Sum(Amount),0) From sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD ON T.Id= TD.TransactionId And TD.LedgerId = L.Id And TD.TransactionTypeId= 2 And T.TransactionDate>=@rStartDate And T.TransactionDate <=@rEndDate AND T.AccountingYearID=@rAccountingYearId) as DebitBalance, 
		(Select ISNULL(Sum(OpeningBalance),0) From sAccounting.tLedgerMaster L1 INNER JOIN sAccounting.tLedgerGroupMaster LG ON LG.Id=L1.LedgerGroupId AND LG.OrgGroupId=@rOrgGroupId AND L1.AccountingYearId=@rAccountingYearId) as CashOpBalance, 
		L.Id, L.Title, L.LedgerTypeId,L.OpeningBalance, 
		LG.Title AS GName, LGM.Title AS MGName 
		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId    
    END
		
	

	SELECT @lCount =  COUNT(Id) FROM #tTarij
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lLedgerId=LedgerId,@lCreditBalance=CreditBalance,@lDebitBalance=DebitBalance,@lCashOpBalance=CashOpBalance,
		@lLedgerName=LedgerName,@lLedgerTypeId=LedgerTypeId,@lOpeningBalance=OpeningBalance,@lLedgerGroupName=LedgerGroup,
		@lLedgerMainGroupName=LedgerMainGroup	FROM #tTarij WHERE Id= @lCount
		if @rTarij=1 
		BEGIN
				SET @lCreditBalance = @lCreditBalance + @lLOpeningBalance
		END
		ELSE
		BEGIN
				SET @lCreditBalance = @lLOpeningBalance
		END
		
		SET @lCreditBalance = @lCreditBalance + (-1) * @lCreditBalance
		SET @lDebitBalance = @lDebitBalance + (-1) * @lDebitBalance
		SET @lCount = @lCount - 1
	END	
	
	Update #tTarij Set CreditBalance = -1 * CreditBalance Where CreditBalance < 0
	 
		
	IF @rOrderBy = 1 
	BEGIN
	  
	    
		
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2, @rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,([sAccounting].[fDecimalValueGet] (CreditBalance, @DecimalCount)) as CreditBalance, -- Added for mantis 32211 by Nilesh
	-- Added for mantis 32211 by Nilesh
				([sAccounting].[fDecimalValueGet] (DebitBalance, @DecimalCount)) as DebitBalance, * FROM #tTarij ORDER BY LEDGERMAINGROUP
	END
	
	ELSE
	BEGIN
		SELECT	@ReportOrgTitle  AS OrgTitle,
				@SmallAddress1 AS SmallAddress1,
				@SmallAddress2 AS SmallAddress2, 
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				--change by dhruvik
				([sAccounting].[fDecimalValueGet] (CreditBalance, @DecimalCount)) as CreditBalance,
				([sAccounting].[fDecimalValueGet] (DebitBalance, @DecimalCount)) as DebitBalance,
				CashOpBalance, LedgerId,LedgerName,LedgerTypeId,OpeningBalance,LedgerGroup,LedgerMainGroup 
		FROM #tTarij ORDER BY 	LEDGERNAME
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAccounting].[pTransactionAdd]
	 
	        @rId bigint
	       ,@rOrgGroupId int
           ,@rAccountingYearId int
           ,@rTransactionDate date
           ,@rNarration nvarchar(1000)           --Change by dhananjay 150->1000 size for mantis id - 0035082
           ,@rVoucherNumber bigint
           ,@rVoucherTypeId tinyint
           ,@rIsProfitAndLoss int
           ,@rRepeatLedger int
           ,@rCreatedUserId bigint
           ,@rChequeNo nvarchar(10)
           ,@rBankName nvarchar(100)
           ,@rChequeDate datetime
           ,@rTransactionApproveId bigint=null
		   ,@rResult bigint=0 OUT 
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT
	DECLARE @1AccountId int 
	
	IF (@rId = 0)  AND  EXISTS (Select 1 FROM sAccounting.tTransaction where AccountingYearId = @rAccountingYearId AND VoucherNumber = @rVoucherNumber AND VoucherTypeId = @rVoucherTypeId AND OrgGroupId = @rOrgGroupId)
	  BEGIN
	        SELECT -111 AS Result
	  END
  
    ELSE IF(@rId = 0)	
	BEGIN
		
    Select @1AccountId = AccountId from sAccounting.tAccountingYearMaster where Id = @rAccountingYearId 
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tTransaction',@lNextNumber = @lNextNumber output
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id]
			   ,OrgGroupId
			   ,[AccountingYearId]
			   ,[TransactionDate]
			   ,[Narration]
			   ,[VoucherNumber]
			   ,[VoucherTypeId]
			   ,[IsProfitAndLoss]
			   ,[RepeatLedger]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,AccountId
			   ,[ChequeNo]
			   ,[BankName]
			   ,[ChequeDate]
			   ,TransactionApproveId
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rOrgGroupId
			   ,@rAccountingYearId
			   ,@rTransactionDate
			   ,@rNarration
			   ,@rVoucherNumber
			   ,@rVoucherTypeId
			   ,@rIsProfitAndLoss
			   ,@rRepeatLedger
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@1AccountId
			   ,@rChequeNo
			   ,@rBankName
			   ,@rChequeDate
			   ,@rTransactionApproveId
			   )
		    SELECT @lNextNumber AS Result
	SET @rResult = @lNextNumber
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAccounting].[tTransaction]
	    SET
			 
	          AccountingYearId=@rAccountingYearId
	         ,TransactionDate = @rTransactionDate 
             ,Narration = @rNarration
             ,VoucherNumber=@rVoucherNumber
             ,VoucherTypeId=@rVoucherTypeId
             ,IsProfitAndLoss=@rIsProfitAndLoss
             ,RepeatLedger=@rRepeatLedger
             ,UpdatedUserId=@rCreatedUserId
             ,UpdatedDateTime= sCommon.fGetDate() 
             ,ChequeNo = @rChequeNo
             ,ChequeDate = @rChequeDate
             ,BankName = @rBankName         
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
		  SET @rResult = @lNextNumber
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pTransactionApproveAdd]
	 
	        @rId bigint
	       ,@rOrgGroupId int
           ,@rAccountingYearId int
           ,@rTransactionDate date
           ,@rNarration nvarchar(1000) --Change by dhananjay 150->1000 size for mantis id - 0035082          
           ,@rVoucherNumber bigint
           ,@rVoucherTypeId tinyint
           ,@rIsProfitAndLoss int
           ,@rRepeatLedger int
           ,@rCreatedUserId bigint
           ,@rChequeNo nvarchar(10)
           ,@rBankName nvarchar(100)
           ,@rChequeDate datetime
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT
	DECLARE @1AccountId int 
	
	IF (@rId = 0)  AND  EXISTS (Select 1 FROM sAccounting.tTransactionApprove where AccountingYearId = @rAccountingYearId AND VoucherNumber = @rVoucherNumber AND VoucherTypeId = @rVoucherTypeId AND OrgGroupId = @rOrgGroupId)
	  BEGIN
	        SELECT -111 AS Result
	  END
  
    ELSE IF(@rId = 0)	
	BEGIN
		
    Select @1AccountId = AccountId from sAccounting.tAccountingYearMaster where Id = @rAccountingYearId 
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransactionApprove', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAccounting.tTransactionApprove
			   (
			    [Id]
			   ,OrgGroupId
			   ,[AccountingYearId]
			   ,[TransactionDate]
			   ,[Narration]
			   ,[VoucherNumber]
			   ,[VoucherTypeId]
			   ,[IsProfitAndLoss]
			   ,[RepeatLedger]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,AccountId
			   ,[ChequeNo]
			   ,[BankName]
			   ,[ChequeDate]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rOrgGroupId
			   ,@rAccountingYearId
			   ,@rTransactionDate
			   ,@rNarration
			   ,@rVoucherNumber
			   ,@rVoucherTypeId
			   ,@rIsProfitAndLoss
			   ,@rRepeatLedger
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@1AccountId
			   ,@rChequeNo
			   ,@rBankName
			   ,@rChequeDate
			   )
		    SELECT @lNextNumber AS Result
	
	 
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAccounting.tTransactionApprove
	    SET
			 
	          AccountingYearId=@rAccountingYearId
	         ,TransactionDate = @rTransactionDate 
             ,Narration = @rNarration
             ,VoucherNumber=@rVoucherNumber
             ,VoucherTypeId=@rVoucherTypeId
             ,IsProfitAndLoss=@rIsProfitAndLoss
             ,RepeatLedger=@rRepeatLedger
             ,UpdatedUserId=@rCreatedUserId
             ,UpdatedDateTime= sCommon.fGetDate() 
             ,ChequeNo = @rChequeNo
             ,ChequeDate = @rChequeDate
             ,BankName = @rBankName         
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pTransactionApproveDetailAdd]
	 
	        @rId bigint
           ,@rTransactionId bigint
           ,@rNumber bigint
		   ,@rTransactionTypeId int
		   ,@rLedgerId bigint
		   ,@rAmount decimal(20,5) --Changed for mantis : 32211 by Nilesh
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionApproveDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tTransactionApproveDetail
			   (
			    [Id]
			   ,[TransactionId] 
			   ,[Number] 
			   ,[TransactionTypeId]
			   ,[LedgerId]
			   ,[Amount]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rTransactionId
			   ,@rNumber
			   ,@rTransactionTypeId
			   ,@rLedgerId
			   ,@rAmount
			   )
		    SELECT @lNextNumber AS Result
	
		
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAccounting.tTransactionApproveDetail
	    SET
			 
	          Number=@rNumber
	         ,TransactionTypeId=@rTransactionTypeId
	         ,LedgerId=@rLedgerId
			 ,Amount=@rAmount
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pTransactionBulkAdd]
	@rXmlDoc nvarchar(MAX)		
	
AS
SET NOCOUNT ON

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

DECLARE @lCount int = 0, @lResult bigint = 0
DECLARE @lOrgGroupId bigint = 0,
		@lAccountingYearId int = 0,
		@lVoucherDate date = '',
		@lNarration nvarchar(1000) = '',--Change by dhananjay 150->1000 size for mantis id - 0035082
		@lVoucherNumber bigint = 0,
		@lVoucherType nvarchar(50) = '',
		@lVoucherTypeId tinyint = 0,		 
		@lCreatedUserId bigint = 0,
		@lCreatedDateTime datetime = '',
		@lAccountId int = 0,
		@lChequeNo nvarchar(20) = '',		
		@lChequeDate date = '',
		@lTransactionApproveId bigint = NULL,
		@lCreditAmount decimal(12,2) = 0,
		@lDebitAmount decimal(12,2) = 0,
		@lToLedger nvarchar(50) = '',
		@lByLedger nvarchar(50) = '',
		@lToLedgerId bigint = 0,
		@lByLedgerId bigint = 0

			
BEGIN TRY
BEGIN TRANSACTION												
	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	
	CREATE TABLE #tTable  
	(
		 Id bigint identity
		,OrgGroupId smallint null
		,[AccountingYearId] int not null
		,[VoucherDate] date null
		,[Narration] nvarchar(1000) null	--Change by dhananjay 150->1000 size for mantis id - 0035082
		,[VoucherNumber] bigint null
		,[VoucherType] nvarchar(50) null		 
		,[CreatedUserId] bigint not null		 		
		,[ChequeNo] nvarchar(20) null		 
		,[ChequeDate] date null
		,CreditAmount decimal(12,2) null
		,DebitAmount decimal(12,2) null
		,ToLedger nvarchar(50) null
		,ByLedger nvarchar(50) null	
		,AccountId int null
	)


	INSERT INTO #tTable
			   (			    
			   OrgGroupId
			   ,[AccountingYearId]
			   ,[VoucherDate]
			   ,[Narration]
			   ,[VoucherNumber]
			   ,[VoucherType]			    
			   ,[CreatedUserId]			   	   
			   ,[ChequeNo]			   
			   ,[ChequeDate]
			   ,CreditAmount
			   ,DebitAmount
			   ,ToLedger
			   ,ByLedger
			   ,AccountId			   
			   )
	SELECT		
		A.OrgGroupId,
		A.AccountingYearId,			
		A.VoucherDate,
		A.Narration,
		A.VoucherNumber,
		A.VoucherType,		 
		A.CreatedUserId,				
		A.ChequeNo,		
		A.ChequeDate,
		A.CreditAmount,
		A.DebitAmount,
		A.ToLedger,
		A.ByLedger,
		A.AccountId			
		
	FROM OPENXML (@intDoc, '/Table/VoucherEntryBulk', 1)
	WITH
	(						
		OrgGroupId smallint '@OrgGroupId',
		AccountingYearId int '@AccountingYearId',
		VoucherDate date '@VoucherDate',
		Narration NVARCHAR(1000) '@Narration',		----Change by dhananjay 150->1000 size for mantis id - 0035082
		VoucherNumber bigint '@VoucherNo',
		VoucherType nvarchar(50) '@VoucherType',		 		
		CreatedUserId bigint '@CreatedUserId',		
		ChequeNo nvarchar(20) '@ChequeNo',		
		ChequeDate date '@ChequeDate',
		CreditAmount decimal(12,2) '@CreditAmount',
		DebitAmount decimal(12,2) '@DebitAmount',
		ToLedger nvarchar(50) '@ToLedger',
		ByLedger nvarchar(50) '@ByLedger',
		AccountId int '@AccountId'			
	)A 

	EXEC sp_xml_removedocument @intDoc
	
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 

BEGIN
	SELECT
	@lOrgGroupId = OrgGroupId,
	@lAccountingYearId = AccountingYearId,
	@lVoucherDate = VoucherDate,
	@lNarration = Narration,
	@lVoucherNumber = VoucherNumber,
	@lVoucherType = VoucherType,	 
	@lCreatedUserId = CreatedUserId,		
	@lChequeNo = ChequeNo,	
	@lChequeDate = ChequeDate,
	@lCreditAmount = CreditAmount,
	@lDebitAmount = DebitAmount,
	@lToLedger = ToLedger,
	@lByLedger = ByLedger,
	@lAccountId = AccountId	
	FROM #tTable WHERE Id = @lCount

	SELECT @lVoucherTypeId = Id FROM sAccounting.tVoucherTypeMaster WHERE Title = @lVoucherType
	SELECT @lToLedgerId = Id FROM sAccounting.tLedgerMaster WHERE Title = @lToLedger AND AccountingYearId = @lAccountingYearId  -- Added AccountingYearId for mantis 0035071 by Foram
	SELECT @lByLedgerId = Id FROM sAccounting.tLedgerMaster WHERE Title = @lByLedger AND AccountingYearId = @lAccountingYearId  -- Added AccountingYearId for mantis 0035071 by Foram
	
	IF(@lVoucherNumber = '' OR @lVoucherNumber is null)
	BEGIN
		SELECT @lVoucherNumber =  ISNULL(Max(VoucherNumber),0) + 1
		   FROM sAccounting.tTransaction
		  WHERE
		   (VoucherTypeId=@lVoucherTypeId OR @lVoucherTypeId=0)
			AND 	AccountingYearId  = @lAccountingYearId
	END 
	--print(@lVoucherNumber)

	EXEC sAccounting.pTransactionAdd 0,@lOrgGroupId,@lAccountingYearId,@lVoucherDate,@lNarration,@lVoucherNumber,@lVoucherTypeId,0,0,@lCreatedUserId,@lChequeNo,'',@lChequeDate,@lTransactionApproveId,@lResult OUTPUT 	
	IF(@lResult > 0)
	BEGIN			
		SET @lCreditAmount = -1*@lCreditAmount
		IF(@lVoucherTypeId != 2)
		BEGIN			
			exec sAccounting.pTransactionDetailAdd 0,@lResult,0,2,@lByLedgerId,@lDebitAmount,@lOrgGroupId
			exec sAccounting.pTransactionDetailAdd 0,@lResult,0,1,@lToLedgerId,@lCreditAmount,@lOrgGroupId
		END
		ELSE
		BEGIN		
			exec sAccounting.pTransactionDetailAdd 0,@lResult,0,2,@lToLedgerId,@lDebitAmount,@lOrgGroupId
			exec sAccounting.pTransactionDetailAdd 0,@lResult,0,1,@lByLedgerId,@lCreditAmount,@lOrgGroupId
		END
	END


	SET @lCount = @lCount - 1		
END

SELECT 1
	
	COMMIT TRANSACTION	

	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAccounting].[pTransactionDetailAdd]
	 
	        @rId bigint
           ,@rTransactionId bigint
           ,@rNumber bigint
		   ,@rTransactionTypeId int
		   ,@rLedgerId bigint
		   ,@rAmount decimal(20,5) --Changed for mantis : 32211 by Nilesh
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAccounting].[tTransactionDetail]
			   (
			    [Id]
			   ,[TransactionId] 
			   ,[Number] 
			   ,[TransactionTypeId]
			   ,[LedgerId]
			   ,[Amount]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rTransactionId
			   ,@rNumber
			   ,@rTransactionTypeId
			   ,@rLedgerId
			   ,@rAmount
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAccounting].[tTransactionDetail]
	    SET
			  --Number=@rNumber
	         --,Code=@rCode
	          Number=@rNumber
	         ,TransactionTypeId=@rTransactionTypeId
	         ,LedgerId=@rLedgerId
			 ,Amount=@rAmount
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pTrialBalance]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rOrderBy smallint,
	@rLedgerGroupId int,
	@rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--SELECT '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
-- '' AS Builder1,
--	   '' AS Builder2,
--       '' As Id,
--	   '' As LedgerId,
--	   '' As LedgerName,
--	   '' As LedgerGroup,
--	   '' As LedgerMainGroup,
--	   '' As LedgerTypeId,
--	   '' As CreditBalance,
--	   '' As DebitBalance,
--	   '' As OpeningBalance,
--	   '' As ClosingBalance

Declare @lLedgerId int 
Declare @lCashOpBalance Decimal (12,2)
Declare @lOpeningBalance Decimal (12,2)
Declare @lCreditBalance Decimal (12,2)
Declare @lDebitBalance Decimal (12,2)
Declare @lLOpeningBalance Decimal(12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)
	
	--change by dhruvik
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548


	SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
	From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
	
    CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 			Transaction_Balance decimal(12,2) 			
 		)
 		
	   CREATE TABLE #tTempTrialBalance
 		(	Id INT IDENTITY (1,1),
 			LedgerId int,
 			LedgerName varchar(100),
 			LedgerGroup varchar(100),
			LedgerMainGroup Varchar(100), 			
 			LedgerTypeId int,
 			CreditBalance decimal(12,2),
 			DebitBalance decimal(12,2),
 			OpeningBalance decimal(12,2),
 			ClosingBalance Decimal(12,2)
 		) 
 		INSERT INTO #tTempTrialBalance    
		SELECT L.Id, L.Title,LG.Title AS GName, LGM.Title AS MGName ,L.LedgerTypeId,0,0,L.OpeningBalance,0		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		AND (LG.Id = @rLedgerGroupId or @rLedgerGroupId=0 )
	  
	--select * from #tTemptrialBalance
	 
	SELECT @lCount =  COUNT(Id) FROM #tTempTrialBalance
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lLedgerId=LedgerId,@lCreditBalance=CreditBalance,@lDebitBalance=DebitBalance,
		@lLedgerName=LedgerName,@lLedgerTypeId=LedgerTypeId,@lOpeningBalance=OpeningBalance,@lLedgerGroupName=LedgerGroup,
		@lLedgerMainGroupName=LedgerMainGroup	FROM #tTempTrialBalance WHERE Id= @lCount
	
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@lLedgerId,''
		SET @lCount = @lCount - 1
	END	
	
	--select *  from #tempUpdateClosingBalance UC INNER JOIN #tTemptrialBalance TB ON TB.LedgerId = UC.LedgerId
	
	IF @rOrderBy = 0 
	BEGIN
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2,  @rBuilder1 AS Builder1
	    ,@rBuilder2 AS Builder2,TB.LedgerId,TB.LedgerName,TB.LedgerGroup,TB.LedgerMainGroup,
		--change by dhruvik
		--T.Temp_Op_Balance AS OpeningBalance,
		([sAccounting].[fDecimalValueGet] (T.Temp_Op_Balance, @DecimalCount)) AS OpeningBalance,
		--ISNULL(CASE WHEN T.Transaction_Balance < 0 THEN -1 * T.Transaction_Balance END,0) AS CreditBalance,
		--ISNULL(CASE WHEN T.Transaction_Balance >= 0 THEN T.Transaction_Balance ENd,0) AS DebitBalance,
		
		--ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN 1 * T.Transaction_Balance END,0) AS CreditBalance,
		([sAccounting].[fDecimalValueGet] (ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN 1 * T.Transaction_Balance END,0),@DecimalCount)) AS CreditBalance,
		--ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN 1 * T.Transaction_Balance ENd,0) AS DebitBalance,
		([sAccounting].[fDecimalValueGet] (ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN 1 * T.Transaction_Balance ENd,0),@DecimalCount)) AS DebitBalance,
		
		--T.Closing_Balance AS ClosingBalance
		([sAccounting].[fDecimalValueGet] (T.Closing_Balance,@DecimalCount)) AS ClosingBalance
		FROM #tempUpdateClosingBalance T 
		INNER JOIN #tTempTrialBalance TB on T.LedgerId=TB.LedgerId ORDER BY TB.LedgerName
	END
	ELSE
	BEGIN
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2,  @rBuilder1 AS Builder1
	    ,@rBuilder2 AS Builder2,0 AS LedgerId,'' AS LedgerName,TB.LedgerGroup,TB.LedgerMainGroup,
		--change by dhruvik
		--Sum(T.Temp_Op_Balance) AS OpeningBalance,
		([sAccounting].[fDecimalValueGet] (Sum(T.Temp_Op_Balance),@DecimalCount)) AS OpeningBalance,
	 --   Sum(ISNULL(CASE WHEN T.Transaction_Balance < 0 THEN -1 * T.Transaction_Balance END,0)) AS CreditBalance,
		--Sum(ISNULL(CASE WHEN T.Transaction_Balance >= 0 THEN T.Transaction_Balance ENd,0)) AS DebitBalance,
		--Sum(ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN 1 * T.Transaction_Balance END,0)) AS CreditBalance,
		([sAccounting].[fDecimalValueGet] (Sum(ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN 1 * T.Transaction_Balance END,0)),@DecimalCount)) AS CreditBalance,
		--Sum(ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN 1 * T.Transaction_Balance ENd,0)) AS DebitBalance,
		([sAccounting].[fDecimalValueGet] (Sum(ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN 1 * T.Transaction_Balance ENd,0)),@DecimalCount)) AS DebitBalance,
		--Sum(T.Closing_Balance) AS ClosingBalance
		([sAccounting].[fDecimalValueGet] (Sum(T.Closing_Balance),@DecimalCount)) AS ClosingBalance
		FROM #tempUpdateClosingBalance T inner join #tTempTrialBalance TB on T.LedgerId=TB.LedgerId GRoup BY TB.LedgerGroup,TB.LedgerMainGroup
	END
	
	DROP Table #tempUpdateClosingBalance
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAccounting].[pUpdateClosingBalance]
	
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rISProfitLoss [smallint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

Declare @OpeningBalance decimal(25,5) -- Changed for mantis : 32211 by Nilesh
Declare @AccOpBalance decimal(25,5) = 0
Declare @ClosingBalance decimal(25,5) -- Changed for mantis : 32211 by Nilesh
Declare @TransactionBalance decimal(25,5) -- Changed for mantis : 32211 by Nilesh
Declare @LedgerId int 
Declare @lCount int
Declare @LedgerTypeId int
	
	
	CREATE TABLE #tempUpdateClosingBalance123
 		(	
 		    Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(25,5), -- Changed for mantis : 32211 by Nilesh
 			Closing_Balance decimal(25,5), -- Changed for mantis : 32211 by Nilesh
 			Trasaction_Balance decimal(25,5) not null -- Changed for mantis : 32211 by Nilesh
  		) 
	
	CREATE TABLE #tempLedgerMaster
 	    (
 	        Id INT IDENTITY (1, 1),
 			LedgerId int,
 			AccOpBalance decimal(25,5),
 			LedgerTypeId int				 
 		) 
 	INSERT INTO #tempLedgerMaster
	SELECT Id,OpeningBalance,LedgerTypeId FROM sAccounting.tLedgerMaster  
	WHERE AccountingYearId=@rAccountingYearId AND (ID=@rLedgerId OR @rLedgerId=0)
	ORDER BY Id Asc
	
	SELECT @lCount =  COUNT(Id) FROM #tempLedgerMaster
	WHILE (@lCount > 0)
	BEGIN
			SELECT @AccOpBalance =AccOpBalance,@LedgerTypeId= LedgerTypeId,
			@LedgerId =LedgerId FROM #tempLedgerMaster WHERE Id = @lCount	
	 -- Opening Balance Calulation
				IF @rISProfitLoss = 1 
				  BEGIN
					SELECT @OpeningBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate < @rStartDate AND TD.LedgerId=@LedgerId AND
					(TD.LedgerId = @rLedgerId OR @rLedgerId = 0) AND T.IsProfitAndLoss <> 1
				  END
				ELSE
				  BEGIN
					SELECT @OpeningBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate < @rStartDate AND TD.LedgerId=@LedgerId AND
				    (TD.LedgerId = @rLedgerId OR @rLedgerId = 0)
				  END				
   -- Transaction Balance
   				IF @rISProfitLoss = 1 
				  BEGIN
					SELECT @TransactionBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate >= @rStartDate  AND T.TransactionDate <= @rEndDate 
					AND TD.LedgerId=@LedgerId AND
					(TD.LedgerId = @rLedgerId OR @rLedgerId = 0) AND T.IsProfitAndLoss <> 1
				  END
				ELSE
				  BEGIN
					SELECT @TransactionBalance = ISNULL(SUM(AMOUNT),0) FROM sAccounting.tTransactionDetail TD
					INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
					WHERE T.OrgGroupId = @rOrgGroupId AND T.AccountingYearId = @rAccountingYearId
					AND T.TransactionDate >= @rStartDate  AND T.TransactionDate <= @rEndDate 
					AND TD.LedgerId=@LedgerId AND (TD.LedgerId = @rLedgerId OR @rLedgerId = 0)
				  END				
	--
				IF @LedgerTypeId = 1 
				BEGIN
					SET @TransactionBalance = -1 * @TransactionBalance
					SET @OpeningBalance = -1 * @OpeningBalance
				END
				ELSE
				BEGIN
					SET @TransactionBalance = @TransactionBalance
					SET @OpeningBalance = @OpeningBalance
				END
								    
				    SET @OpeningBalance = @OpeningBalance + @AccOpBalance				
					SET @ClosingBalance = @OpeningBalance + @TransactionBalance				
				    --Select @OpeningBalance AS OPBal ,@ClosingBalance AS CloseIng				
				
				INSERT INTO #tempUpdateClosingBalance123 (LedgerId ,Temp_Op_Balance ,Closing_Balance,Trasaction_Balance)
				VALUES (@LedgerId,@OpeningBalance,@ClosingBalance,ISNULL(@TransactionBalance,0)) -- Changed for mantis : 32211 by Nilesh

				SET @lCount = @lCount - 1
	END	
		SELECT LedgerId,Temp_Op_Balance,Closing_Balance,Trasaction_Balance FROM #tempUpdateClosingBalance123 ORDER BY LedgerId
		TRUNCATE TABLE #tempUpdateClosingBalance123
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAccounting].[pValidateTransactionBulk]
		@rXmlDoc nvarchar(MAX)
		,@rResult nvarchar(max)='' OUT

			
AS
SET NOCOUNT ON

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

DECLARE @lCount int = 0, @lValidationMsg nvarchar(max) = '' 
DECLARE @lOrgGroupId bigint = 0,
		@lAccountingYearId int = 0,
		@lVoucherDate date = '',
		@lNarration nvarchar(1000) = '',   --Change by dhananjay 150->1000 size for mantis id - 0035082
		@lVoucherNumber bigint = 0,
		@lVoucherType nvarchar(50) = '',
		@lVoucherTypeId tinyint = 0,		 
		@lCreatedUserId bigint = 0,
		@lCreatedDateTime datetime = '',
		@lAccountId int = 0,
		@lChequeNo nvarchar(20) = '',		
		@lChequeDate date = '',
		@lTransactionApproveId bigint = NULL,
		@lCreditAmount decimal(12,2) = 0,
		@lDebitAmount decimal(12,2) = 0,
		@lToLedger nvarchar(50) = '',
		@lByLedger nvarchar(50) = '',
		@lToLedgerId bigint = 0,
		@lByLedgerId bigint = 0

			
--BEGIN TRY
--BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	
	CREATE TABLE #tTable  
	(
		 Id bigint identity
		,OrgGroupId smallint null
		,[AccountingYearId] int not null
		,[VoucherDate] date null
		,[Narration] nvarchar(1000) null       --Change by dhananjay 150->1000 size for mantis id - 0035082
		,[VoucherNumber] bigint null
		,[VoucherType] nvarchar(50) null		 
		,[CreatedUserId] bigint not null		 		
		,[ChequeNo] nvarchar(20) null		 
		,[ChequeDate] date null
		,CreditAmount decimal(12,2) null
		,DebitAmount decimal(12,2) null
		,ToLedger nvarchar(50) null
		,ByLedger nvarchar(50) null	
		,AccountId int null	
	)


	INSERT INTO #tTable
			   (			    
			   OrgGroupId
			   ,[AccountingYearId]
			   ,[VoucherDate]
			   ,[Narration]
			   ,[VoucherNumber]
			   ,[VoucherType]			    
			   ,[CreatedUserId]			   	   
			   ,[ChequeNo]			   
			   ,[ChequeDate]
			   ,CreditAmount
			   ,DebitAmount
			   ,ToLedger
			   ,ByLedger
			   ,AccountId			   
			   )
	SELECT		
		A.OrgGroupId,
		A.AccountingYearId,			
		A.VoucherDate,
		A.Narration,
		A.VoucherNumber,
		A.VoucherType,		 
		A.CreatedUserId,				
		A.ChequeNo,		
		A.ChequeDate,
		A.CreditAmount,
		A.DebitAmount,
		A.ToLedger,
		A.ByLedger,
		A.AccountId			
		
	FROM OPENXML (@intDoc, '/Table/VoucherEntryBulk', 1)
	WITH
	(						
		OrgGroupId smallint '@OrgGroupId',
		AccountingYearId int '@AccountingYearId',
		VoucherDate date '@VoucherDate',
		Narration NVARCHAR(1000) '@Narration',		--Change by dhananjay 150->1000 size for mantis id - 0035082
		VoucherNumber bigint '@VoucherNo',
		VoucherType nvarchar(50) '@VoucherType',		 		
		CreatedUserId bigint '@CreatedUserId',		
		ChequeNo nvarchar(20) '@ChequeNo',		
		ChequeDate date '@ChequeDate',
		CreditAmount decimal(12,2) '@CreditAmount',
		DebitAmount decimal(12,2) '@DebitAmount',
		ToLedger nvarchar(50) '@ToLedger',
		ByLedger nvarchar(50) '@ByLedger',
		AccountId int '@AccountId'		
	)A 

	--SELECT * FROM #tTable

	EXEC sp_xml_removedocument @intDoc

DECLARE @lTotal int = 0
DECLARE @lValidationMsgAll nvarchar(max) = ''
SELECT @lTotal = COUNT(Id) FROM #tTable
SELECT @lCount = 1
WHILE @lCount <= @lTotal 
BEGIN
	
	SELECT
	@lOrgGroupId = OrgGroupId,
	@lAccountingYearId = AccountingYearId,
	@lVoucherDate = VoucherDate,
	@lNarration = Narration,
	@lVoucherNumber = VoucherNumber,
	@lVoucherType = VoucherType,	 
	@lCreatedUserId = CreatedUserId,		
	@lChequeNo = ChequeNo,	
	@lChequeDate = ChequeDate,
	@lCreditAmount = CreditAmount,
	@lDebitAmount = DebitAmount,
	@lToLedger = ToLedger,
	@lByLedger = ByLedger,
	@lAccountId = AccountId	
	FROM #tTable WHERE Id = @lCount

	SET @lVoucherTypeId = '' SET @lToLedgerId = '' SET @lByLedgerId = ''
	SELECT @lVoucherTypeId = Id FROM sAccounting.tVoucherTypeMaster WHERE Title = @lVoucherType
	SELECT @lToLedgerId = Id FROM sAccounting.tLedgerMaster WHERE Title = @lToLedger
	SELECT @lByLedgerId = Id FROM sAccounting.tLedgerMaster WHERE Title = @lByLedger

	--print(@lVoucherType)
	--print(@lToLedger)
	--print(@lByLedger)
	--print(@lVoucherType)
	--print(@lOrgGroupId)
	--print(@lVoucherNumber)
	--print(@lByLedgerId)
	print(@lVoucherTypeId)
	print(@lToLedgerId)
	
	SET @lValidationMsg = ''
	IF(@lVoucherTypeId = '' OR LEN(@lVoucherTypeId) = 0 OR @lVoucherTypeId is null)
	BEGIN
		SET @lValidationMsg = 'Voucher Type does not Exist,'
	END	

	IF(@lToLedgerId = '' OR LEN(@lToLedgerId) = 0 OR @lVoucherTypeId is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + 'To Ledger does not Exist,'
	END

	IF(@lByLedgerId = '' OR LEN(@lByLedgerId) = 0 OR @lByLedgerId is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + 'By Ledger does not Exist,'
	END

	IF (@lOrgGroupId  = '' OR LEN(@lOrgGroupId) = 0 OR @lOrgGroupId is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + 'OrgGroupId cannot be empty,'
	END	

	IF (@lCreatedUserId = '' OR LEN(@lCreatedUserId) = 0 OR @lCreatedUserId is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + ' CreatedUserId cannot be empty,'
	END	

	IF (@lAccountingYearId  = '' OR LEN(@lAccountingYearId) = 0 OR @lAccountingYearId is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + ' AccountingYearId cannot be empty,'
	END	

	IF (@lVoucherDate  = '' OR LEN(@lVoucherDate) = 0 OR @lVoucherDate is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + ' VoucherDate cannot be empty,'
	END		

	IF EXISTS(Select 1 FROM sAccounting.tTransaction T INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId WHERE T.AccountingYearId = @lAccountingYearId AND T.VoucherNumber = @lVoucherNumber AND T.OrgGroupId = @lOrgGroupId AND VTM.Title = @lVoucherType)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + ' Voucher Number Exists,'
	END	

	IF (@lCreditAmount <> @lDebitAmount)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + ' Credit and Debit Amount do not match,'
	END

	IF(@lVoucherTypeId = 2)
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lToLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' To Ledger does match Voucher Type'
		END

		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId NOT IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lByLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' By Ledger does match Voucher Type'
		END
	END	
	IF(@lVoucherTypeId = 3)
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lToLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' To Ledger does match Voucher Type'
		END

		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId NOT IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lByLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' By Ledger does match Voucher Type'
		END
	END
	IF(@lVoucherTypeId = 4)
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lToLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' To Ledger does match Voucher Type'			
		END
		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lByLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' By Ledger does match Voucher Type'				
		END
	END			
	IF(@lVoucherTypeId = 1)
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lToLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' To Ledger does match Voucher Type'
		END

		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lByLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' By Ledger does match Voucher Type'
		END
	END
		

	SET @lCount = @lCount + 1		
				
	SELECT @lValidationMsg AS ValidationMsg
	SET @rResult = @lValidationMsg

END

--COMMIT TRANSACTION

	--END TRY
	--BEGIN CATCH
	--ROLLBACK TRANSACTION
	--SELECT -1
	--END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pVoucherApproveListGet]

	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(1000), --Change by dhananjay 150->1000 size for mantis id - 0035082
	 @rAmount int,
	 @rAccountingYearId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  BEGIN
			SET @rNarration = sAccounting.fNarrationSearchStringGet(@rNarration)--Add New Function by dhananjay 150->1000 size for mantis id - 0035082
	  END
	 
  SELECT  
		  T.Id
		  ,VTM.Title AS VoucherType
		  ,T.VoucherNumber AS VoucherNo
		  ,T.TransactionDate AS VoucherDate
		  ,LM.Title AS Ledger
		  ,CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 ELSE 0 END AS Credit
		  ,CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) ELSE 0 END AS Debit
		  ,T.Narration AS Narration
		  ,AM.ReportOrgTitle As OrgTitle
		  ,AM.SmallAddress1 AS SmallAddress1
		  ,AM.SmallAddress2 AS SmallAddress2
		 
		
  FROM 
          sAccounting.tTransactionApprove T
          INNER JOIN sAccounting.tTransactionApproveDetail TD ON T.Id=TD.TransactionId
          INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId
          INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId 
          INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
         
        
         WHERE 
		  (T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0) 
			AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = '')) 		
			AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '') 
			And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
			AND (TD.LedgerId = @rLedgerId OR @rLedgerId=0)
			AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
			AND LM.AccountingYearId = @rAccountingYearId
			AND T.AccountingYearId = @rAccountingYearId
			AND  NOT EXISTS( SELECT 1 FROM sAccounting.tTransaction TA Where TA.TransactionApproveId=T.Id AND  TA.AccountingYearId = @rAccountingYearId )
			
            Order By T.VoucherTypeId,T.TransactionDate,T.VoucherNumber,Credit,Debit
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pVoucherApproveNoGet]
	@rVoucherTypeId [int] = 0,
	@rAccountingYearId [int]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT ISNULL(Max(VoucherNumber),0) + 1 AS VoucherNo
	   FROM sAccounting.tTransactionApprove
	  WHERE
	   (VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId=0)
		AND 	AccountingYearId  = @rAccountingYearId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pVoucherApproveSearchListGet]
	
	 @rId bigint = 0 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN  
	 
  SELECT T.Id
		 ,T.AccountId
		 ,T.AccountingYearId
		 ,T.TransactionDate
		 ,T.Narration
		 ,T.VoucherNumber
		 ,T.VoucherTypeId
		 ,T.SourceTypeId
		 ,T.SourceId
		 ,T.IsProfitAndLoss
		 ,T.RepeatLedger
		 ,T.CreatedDateTime
		 ,T.CreatedUserId
		 ,T.OrgGroupId
		 ,ISNULL(T.PayTypeId,0) AS PayTypeId
		 ,ISNULL(T.ChequeNo,'') AS ChequeNo
		 ,ISNULL(T.BankName,'') AS BankName
		 ,ISNULL(T.ChequeDate,'1900-01-01') AS ChequeDate
		 ,TD.Id as TransactionDetailId	 
		 ,TD.TransactionTypeId 
		 ,TD.LedgerId
		 ,TD.Amount
		 ,TD.Number    
  FROM 
       sAccounting.tTransactionApprove T
       INNER JOIN sAccounting.tTransactionApproveDetail TD ON T.Id=TD.TransactionId
      
  WHERE 
			(T.Id=@rId OR @rId = 0 )        
   Order By T.VoucherTypeId,T.VoucherNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pVoucherDelete]
		
		@rVoucherTypeId int,
		@rAccountId int,
		@rAccountingYearId int,
		@rVoucherNumber int,
		@rVoucherNumberTo int
	    
	WITH EXECUTE AS CALLER
AS
BEGIN
	SET NOCOUNT ON
			 
	BEGIN TRY
	BEGIN TRANSACTION

	DELETE FROM sFee.tAccountPosting 
	WHERE 
	Id IN 
		(SELECT SourceId FROM sAccounting.tTransaction AS T
			WHERE VoucherTypeId=@rVoucherTypeId 
			AND AccountId = @rAccountId 
			AND (AccountingYearId = @rAccountingYearId OR @rAccountingYearId = 0)
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0))

	DELETE FROM sAccounting.tTransactionDetail 
	WHERE
	TransactionId IN 
			(SELECT Id FROM sAccounting.tTransaction T
				WHERE VoucherTypeId=@rVoucherTypeId 
				AND AccountId = @rAccountId 
				AND (AccountingYearId = @rAccountingYearId OR @rAccountingYearId = 0)
				AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
				AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0))

	DELETE FROM sAccounting.tTransaction 
					WHERE VoucherTypeId=@rVoucherTypeId
						AND AccountId = @rAccountId 
						AND (AccountingYearId = @rAccountingYearId OR @rAccountingYearId = 0)
						AND (VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
						AND (VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)

	
	COMMIT TRANSACTION
	SELECT 1 AS Result
	END TRY

	BEGIN CATCH 
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
	SELECT	
	ERROR_MESSAGE() AS ErrorMessage,
	ERROR_NUMBER() AS ErrorCode
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pVoucherListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(1000),   --Change by dhananjay 150->1000 size for mantis id - 0035082
	 @rAmount Decimal(20,5),
	 @rAccountingYearId int = 0,
	 @rIsApproved bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN
			SET @rNarration = sAccounting.fNarrationSearchStringGet(@rNarration) --added New function by dhananjay for mantis id - 0035082
	  END

	  Declare @DecimalCount INT,@lOrgGroupId Int
	  select @lOrgGroupId = OrgGroupId from sAccounting.tTransaction T where AccountingYearId = @rAccountingYearId

	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 548
	 
  SELECT   @rBuilder1 AS Builder1
		  ,@rBuilder2 AS Builder2
		  ,T.Id
		  ,VTM.Title AS VoucherType
		  ,T.VoucherNumber AS VoucherNo
		  ,T.TransactionDate AS VoucherDate
		  ,LM.Title AS Ledger
		  --,CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 ELSE 0 END AS Credit --Commented for mantis : 32211 by Nilesh
		  ,([sAccounting].[fDecimalValueGet] ((CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 
			ELSE 0 END), @DecimalCount)) Credit --Commented for mantis : 32211 by Nilesh
		  --,CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) ELSE 0 END AS Debit --Commented for mantis : 32211 by Nilesh
		  ,([sAccounting].[fDecimalValueGet] ((CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) 
			ELSE 0 END),@DecimalCount)) Debit --Commented for mantis : 32211 by Nilesh
		  ,T.Narration AS Narration
		  ,AM.ReportOrgTitle As OrgTitle
		  ,AM.SmallAddress1 AS SmallAddress1
		  ,AM.SmallAddress2 AS SmallAddress2,
		  T.TransactionApproveId	  	      
  FROM 
          sAccounting.tTransaction T
          INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
          INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId
          INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId 
          INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId            
  WHERE 
				(T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0) 
			AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = '')) 		
			AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '') 
			And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
			AND (TD.LedgerId = @rLedgerId OR @rLedgerId=0)
			AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
			AND LM.AccountingYearId = @rAccountingYearId
			AND T.AccountingYearId = @rAccountingYearId
			AND ((@rIsApproved=1 AND  ISNULL(T.TransactionApproveId,0) !=0) OR (@rIsApproved = 0) )
			
            Order By T.TransactionDate,T.VoucherNumber, LM.Id
END

PRINT N'Altering Procedure [sAccounting].[pTransactionApproveDetailAdd]...';

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAccounting].[pVoucherListWithBalanceGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(1000),    --Change by dhananjay 150->1000 size for mantis id - 0035082
	 @rAmount Decimal(20,5),
	 @rAccountingYearId int = 0,
	 @rIsApproved bit=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN

	  BEGIN
			SET @rNarration = sAccounting.fNarrationSearchStringGet(@rNarration) --added New function by dhananjay for mantis id - 0035082
	  END

	  Declare @DecimalCount INT,@lOrgGroupId Int
	  select @lOrgGroupId = OrgGroupId from sAccounting.tTransaction T where AccountingYearId = @rAccountingYearId

	 SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 548

	CREATE TABLE #tempTransaction
	(
		AutoId INT PRIMARY KEY Identity(1,1),
		Builder1 nvarchar(max),
		Builder2 nvarchar(max),
		Id bigint,
		VoucherType nvarchar(100),
		VoucherNo bigint,
		VoucherDate date,
		Ledger nvarchar(100),
		Credit decimal(25,5),
		Debit decimal(25,5),
		Narration nvarchar(1000),  --Change by dhananjay 150->1000 size for mantis id - 0035082
		OrgTitle nvarchar(200),
		SmallAddress1 nvarchar(200),
		SmallAddress2 nvarchar(200),
		TransactionApproveId bigint
	)

	INSERT INTO #tempTransaction
	SELECT	@rBuilder1 AS Builder1
			,@rBuilder2 AS Builder2
			,T.Id
			,VTM.Title AS VoucherType
			,T.VoucherNumber AS VoucherNo
			,T.TransactionDate AS VoucherDate
			,LM.Title AS Ledger
			,([sAccounting].[fDecimalValueGet] ((CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 
			ELSE 0 END), @DecimalCount)) Credit
			,([sAccounting].[fDecimalValueGet] ((CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) 
			ELSE 0 END),@DecimalCount)) Debit
			,T.Narration AS Narration
			,AM.ReportOrgTitle As OrgTitle
			,AM.SmallAddress1 AS SmallAddress1
			,AM.SmallAddress2 AS SmallAddress2,
			T.TransactionApproveId
	FROM
		sAccounting.tTransaction T
          INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
          INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId
          INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId
          INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	WHERE
				(T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0)
			AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = ''))
			AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '')
			And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0)
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
			AND (TD.LedgerId = @rLedgerId OR @rLedgerId=0)
			AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
			AND LM.AccountingYearId = @rAccountingYearId
			AND T.AccountingYearId = @rAccountingYearId
			AND ((@rIsApproved=1 AND  ISNULL(T.TransactionApproveId,0) !=0) OR (@rIsApproved = 0))
	Order By T.TransactionDate,T.VoucherNumber;

	--select * from #tempTransaction

--Common Table Expression
	WITH RunningBalance AS (
		SELECT	AutoId,
				Builder1,
				Builder2,
				Id,
				VoucherType,
				VoucherNo,
				VoucherDate,
				Ledger,
				([sAccounting].[fDecimalValueGet] (Credit,@DecimalCount)) AS Credit,
				([sAccounting].[fDecimalValueGet] (Debit,@DecimalCount)) AS Debit,
				Narration,
				OrgTitle,
				SmallAddress1,
				SmallAddress2,
				TransactionApproveId,
				(Debit - Credit) AS net_amount,
				([sAccounting].[fDecimalValueGet] ((SELECT	SUM(Debit - Credit) 
				FROM #tempTransaction AS inner_trans
				WHERE inner_trans.AutoId <= outer_trans.AutoId),@DecimalCount)) AS Balance
		FROM
			#tempTransaction AS outer_trans
	)

	SELECT	Builder1,
			Builder2,
			Id,
			VoucherType,
			VoucherNo,
			VoucherDate,
			Ledger,
			Credit,
			Debit,
			Narration,
			OrgTitle,
			SmallAddress1,
			SmallAddress2,
			TransactionApproveId,
			Balance
	FROM
		RunningBalance

	drop table #tempTransaction
END

--SELECT	'' AS Builder1,
--		'' AS Builder2,
--		CAST(0 AS bigint) AS Id,
--		'' AS VoucherType,
--		CAST(0 AS bigint) AS VoucherNo,
--		CAST('' AS date) AS VoucherDate,
--		'' AS Ledger,
--		0.00 AS Credit,
--		0.00 AS Debit,
--		'' AS Narration,
--		'' AS OrgTitle,
--		'' AS SmallAddress1,
--		'' AS SmallAddress2,
--		CAST(0 AS bigint) AS TransactionApproveId,
--		0.00 AS Balance

--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pVoucherNoGet]
	@rVoucherTypeId [int] = 0,
	@rAccountingYearId [int]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 

	 SELECT ISNULL(Max(VoucherNumber),0) + 1 AS VoucherNo
	   FROM tTransaction
	  WHERE (VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId=0)
			AND 	AccountingYearId  = 	@rAccountingYearId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAccounting].[pVoucherSearchListGet]
	
	 @rId bigint = 0 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN  
	 
  SELECT T.Id
		 ,T.AccountId
		 ,T.AccountingYearId
		 ,T.TransactionDate
		 ,T.Narration
		 ,T.VoucherNumber
		 ,T.VoucherTypeId
		 ,T.SourceTypeId
		 ,T.SourceId
		 ,T.IsProfitAndLoss
		 ,T.RepeatLedger
		 ,T.CreatedDateTime
		 ,T.CreatedUserId
		 ,T.OrgGroupId
		 ,ISNULL(T.PayTypeId,0) AS PayTypeId
		 ,ISNULL(T.ChequeNo,'') AS ChequeNo
		 ,ISNULL(T.BankName,'') AS BankName
		 ,ISNULL(T.ChequeDate,'1900-01-01') AS ChequeDate
		 ,TD.Id as TransactionDetailId	 
		 ,TD.TransactionTypeId 
		 ,TD.LedgerId
		 ,TD.Amount
		 ,TD.Number    
  FROM 
       sAccounting.tTransaction T
       INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
      
  WHERE 
			(T.Id=@rId OR @rId = 0 )        
   Order By T.VoucherTypeId,T.VoucherNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pActivityAdd]
	 
        @rId int,
		@rTitle nvarchar(100),
		@rActivityTypeId int,
		@rFromDate date,
		@rToDate date,
		@rRemark nvarchar(200),
		@rIsGroup bit,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sActivity.tActivity where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sActivity.tActivity where Title=@rTitle AND BatchId=@rBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sActivity.tEventActivity where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sActivity.tActivity where Title=@rTitle AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tActivity', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sActivity.tActivity
		(
			Id,
			Title,
			ActivityTypeId,
			FromDate,
			ToDate,
			Remark,
			IsGroup,
			CreatedUserId,
			CreatedDateTime,
			BatchId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rActivityTypeId,
			@rFromDate,
			@rToDate,
			@rRemark,
			@rIsGroup,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rBatchId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sActivity.tActivity
	    SET
			Title=@rTitle,
			ActivityTypeId=@rActivityTypeId,
			FromDate=@rFromDate,
			ToDate=@rToDate,
			Remark=@rRemark,
			IsGroup=@rIsGroup,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pActivityDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sActivity.tActivityParticipant where ActivityId=@rId
			Delete from sActivity.tActivity where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sActivity].[pActivityGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rActivityTypeId int,
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rActivityMainTypeId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			A.Id as ActivityId,
			A.Title,
			A.ActivityTypeId,
			ATM.Title AS ActivityType,
			A.FromDate,
			A.ToDate,
		    A.Remark,
		    A.IsGroup,
			ISNULL(AMTM.Title,'') AS ActivityMainType
		    
      
  FROM 
            sActivity.tActivity A
       INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
	   LEFT JOIN sActivity.tActivityMainTypeMaster AMTM ON ATM.ActivityMainTypeId = AMTM.Id
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.ActivityTypeId = @rActivityTypeId) OR (@rActivityTypeId = 0))
	AND ((A.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((ATM.ActivityMainTypeId = @rActivityMainTypeId) OR (@rActivityMainTypeId = 0))
	AND A.BatchId=@rBatchId
	ORDER BY A.FromDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pActivityParticipantAdd]
			@rActivityId int
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
		   ,@rOrgId int
		   ,@rRemark nvarchar(1000)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
If(@rIsDeleted=1)
BEGIN
	Delete from sActivity.tActivityParticipant where ActivityId=@rActivityId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 

 
	
    
	If Exists(select ActivityId from sActivity.tActivityParticipant where ActivityId=@rActivityId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sActivity.tActivityParticipant
			(
				ActivityId
			   ,SourceTypeId
			   ,SourceId
			   ,Remark
			)
			VALUES
			(	
				@rActivityId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,@rRemark
			)		
			SELECT @rActivityId AS Result
	END
	
	 
	
	
END 	             
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sActivity].[pActivityParticipantGet]
	 
	 @rActivityId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT   
		AP.ActivityId,
		'Student' AS SourceType,
		2003 AS SourceTypeId,
		SA.StudentId as SourceId,
		SA.Code as SourceCode,
		SA.Name as SourceName,
		SA.ClassName+'-'+SA.DivisionName as DivDept,
		ISNULL(AP.Remark,'') AS UserWiseRemark
		
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=SA.StudentId 
	INNER JOIN sActivity.tActivity A ON A.Id = AP.ActivityId AND A.BatchId = SA.BatchId
	
  WHERE 
		(AP.ActivityId=@rActivityId OR @rActivityId=0)
	  AND AP.SourceTypeId=2003
	
	UNION
	
	SELECT  
		AP.ActivityId,
		'Employee' AS SourceType,
		95 AS SourceTypeId,
		EM.Id as SourceId,
		EM.Code as SourceCode,
		EM.FirstName+' '+EM.LastName as SourceName,
		DM.Title as DivDept,
		ISNULL(AP.Remark,'') AS UserWiseRemark
		
  FROM sHrm.tEmployeeMaster EM	
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
    INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
    INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=EM.Id 
  WHERE 
		(AP.ActivityId=@rActivityId OR @rActivityId=0)
	  AND AP.SourceTypeId=95
	   AND ISNULL(EM.IsOtherUser,0) = 0 	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sActivity].[pActivityTypeMasterAdd]
	 
		@rOrgGroupId int,
		@rId  int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rCreatedUserId bigint,		
		@rIsObsolete bit,
		@rUpdateduserId bigint=0,				
		@rActivityMainTypeId smallint=0
		
      
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sActivity.tActivityTypeMaster where Title=@rTitle AND Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sActivity.tActivityTypeMaster where Title=@rTitle AND Code=@rCode AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sActivity.tActivityTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sActivity.tActivityTypeMaster
		(
		OrgGroupId,
		Id,
		Code,
		Title,
		CreatedUserId,
		CreatedDateTime,
		IsObsolete,
		UpdatedUserId,
		UpdatedDateTime,					
		ActivityMainTypeId			
		)
	VALUES
		(
		@rOrgGroupId,
		@lNextNumber,
		@rCode,
		@rTitle,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rIsObsolete,
		@rCreatedUserId,				
		sCommon.fGetDate(),
		@rActivityMainTypeId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sActivity.tActivityTypeMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),						
			ActivityMainTypeId=@rActivityMainTypeId
	      WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sActivity].[pActivityTypeMasterGet]

	 @rOrgGroupId int,
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rActivityMainTypeId smallint=0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
SET @rTitle = sCommon.fSearchStringGet(@rTitle)
SET @rCode = sCommon.fSearchStringGet(@rCode)
BEGIN 
	
	
	SELECT 
	
	AM.OrgGroupId,
	AM.Id AS ActivityTypeId,
	AM.Code AS Code,
	AM.Title AS Title,
	AM.IsObsolete,	
	ISNULL(AM.ActivityMainTypeId,0) AS ActivityMainTypeId,
	ISNULL(AMTM.Title,'') AS ActivityMainType
  FROM 
            sActivity.tActivityTypeMaster AM
            LEFT JOIN sActivity.tActivityMainTypeMaster AMTM ON AM.ActivityMainTypeId = AMTM.Id
  WHERE 
   (AM.Id = @rId) OR (@rId=0)
   AND (AM.OrgGroupId = @rOrgGroupId) 
   AND ((AM.Title Like @rTitle )OR( ISNULL(@rTitle,'') = ''))
   AND ((AM.Code Like @rCode )OR( ISNULL(@rCode,'') = ''))
   AND ((AM.ActivityMainTypeId = @rActivityMainTypeId) OR (@rActivityMainTypeId=0))   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pAssignClubAdd]
	 
	@rClubId int,
	@rAcademicId bigint,
	@rIsDeleted bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
If(@rIsDeleted=1)
BEGIN
	Delete from sActivity.tAssignClub where ClubId=@rClubId AND AcademicId=@rAcademicId
	Select @rAcademicId as Result
END	
ELSE
BEGIN

	BEGIN TRY
	
	 BEGIN TRANSACTION	
	IF NOT EXISTS(Select 1 From sActivity.tAssignClub where ClubId=@rClubId AND AcademicId=@rAcademicId)
	BEGIN
	INSERT INTO sActivity.tAssignClub
		(
			ClubId,
			AcademicId
		)
	VALUES
		(
			@rClubId,
			@rAcademicId
		)
		     
	END
	SELECT @rAcademicId AS Result
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pAssignClubGet]

		   @rAcademicId bigint,
           @rCode nvarchar(20),
           @rClassId int,
           @rDivisionId int,
           @rClubTypeId int=0,
           @rClubId int,
           @rOrgId int,
           @rBatchId int,
           @rIsSearch bit,
           @rStatusId int=0
          
AS
SET NOCOUNT ON

BEGIN
If(@rIsSearch =1)
BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SELECT  
		
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,
		ISNULL(CM.Id,0) AS ClubId,
		ISNULL(CM.Title,'') AS Club,
		CASE WHEN AC.ClubId IS NULL THEN 'false' ELSE 'true' END AS IsObsolete,
		AC.ClubId
		
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId=SA.AcademicId 
	LEFT JOIN sActivity.tClubMaster CM ON CM.Id=AC.ClubId 
	
  WHERE 
		((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND	(SA.ClassId=@rClassId OR @rClassId=0)
	AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (AC.ClubId=@rClubId OR @rClubId=0)
	AND (CM.ClubTypeId=@rClubTypeId OR @rClubTypeId=0)
	AND (SA.OrgId = @rOrgId)
	AND (SA.BatchId=@rBatchId)
	AND (SA.AcademicId=@rAcademicId OR @rAcademicId=0)
	AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	Order by SA.RollNo 
END
ELSE
BEGIN
SELECT  
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		Sa.ClassId,
		SA.DivisionId,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,
		ISNULL(CM.Title,'') AS Club,
		ISNULL(CM.Id,0) AS ClubId,
		CASE WHEN AC.ClubId IS NULL THEN 'false' ELSE 'true' END AS IsObsolete,
		AC.ClubId
		
  FROM sStudent.vStudentAcademic SA
	LEFT JOIN sActivity.tAssignClub AC ON AC.AcademicId=SA.AcademicId AND (AC.ClubId=@rClubId OR @rClubId=0) 
	LEFT JOIN sActivity.tClubMaster CM ON CM.Id=AC.ClubId AND (CM.ClubTypeId=@rClubTypeId OR @rClubTypeId=0)
	
  WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
	AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND (SA.OrgId = @rOrgId)
	AND (SA.BatchId=@rBatchId)
	Order by SA.RollNo
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pAssignHouseAdd]
	 
	@rStudentId bigint,
	@rHouseId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	    UPDATE  sStudent.tStudentOther
	    SET
			HouseId=@rHouseId
			
	      WHERE StudentId = @rStudentId 
		SELECT @rStudentId AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pAssignHouseGet]
          
           @rClassId int,
           @rDivisionId int,
           @rHouseGroupId int=0,
           @rHouseId int,
           @rOrgId int,
           @rBatchId int,
           @rStatusId int=0
          
AS
SET NOCOUNT ON

BEGIN
SELECT  
		SO.StudentId,
		SO.Code,
		SO.Name,
		SO.ClassName+'-'+SO.DivisionName AS ClassName,
		ISNULL(SO.HouseId,0) HouseId,
		SO.RollNo,
		So.DivisionId
		
  FROM sStudent.vStudentOther SO
  LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
	
  WHERE 
		(SO.ClassId=@rClassId OR @rClassId=0)
	AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (HM.HouseGroupId=@rHouseGroupId OR @rHouseGroupId=0)
	AND (SO.HouseId=@rHouseId OR @rHouseId=0)
    AND (SO.StatusId=@rStatusId OR @rStatusId=0)
	AND (SO.OrgId = @rOrgId) 
	AND (SO.BatchId=@rBatchId)
	ORDER BY SO.ClassId,SO.DivisionId,SO.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pClubMasterAdd]
	 
	        @rId int,
	        @rNumber int,
	        @rCode nvarchar(50),
            @rTitle nvarchar(100),
            @rOrderIndex int,
            @rIsObsolete bit,
            @rCreatedUserId bigint,           
            @rOrgGroupId int,
            @rClubTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT Id FROM sActivity.tClubMaster WHERE Code=@rCode AND OrgGroupId=@rOrgGroupId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
		IF EXISTS (SELECT Id FROM sActivity.tClubMaster WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
		IF EXISTS (SELECT Id FROM sActivity.tClubMaster WHERE Number=@rNumber AND OrgGroupId=@rOrgGroupId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END
		IF EXISTS (SELECT Id FROM sActivity.tClubMaster WHERE OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
		BEGIN
			SELECT -104 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT Id FROM sActivity.tClubMaster WHERE Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -101 As Result
			RETURN
		END 
		IF EXISTS (SELECT Id FROM sActivity.tClubMaster WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF EXISTS (SELECT Id FROM sActivity.tClubMaster WHERE Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			SELECT -103 AS Result
			RETURN
		END
		IF EXISTS (SELECT Id FROM sActivity.tClubMaster WHERE OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -104 AS Result
			RETURN
		END
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sActivity.tClubMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sActivity].[tClubMaster]
			   (
			    [Id],
			    [Number], 
			    [Code],
			    [Title],
			    [OrderIndex],
			    [IsObsolete],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [OrgGroupId],
			    [ClubTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rNumber,
			    @rCode,
			    @rTitle,
			    @rOrderIndex,
			    @rIsObsolete,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @rOrgGroupId,
			    @rClubTypeId
			   )
			   SELECT 1 AS RESULT
	 END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sActivity].[tClubMaster]
	    SET
			  [Number] = @rNumber,
	          [Code] = @rCode,
	          [Title] = @rTitle,
	          [OrderIndex] = @rOrderIndex,
              [IsObsolete] = @rIsObsolete,                          
              [UpdatedUserId] = @rCreatedUserId,
              [UpdatedDateTime] = sCommon.fGetDate(),
              [ClubTypeId] = @rClubTypeId         
	      WHERE Id = @rId 	
	      SELECT 11 AS RESULT
	 END  
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pClubMasterGet]
          
		@rId int,
		@rCode nvarchar(50),
		@rTitle nvarchar(100),
		@rOrgGroupId smallint,
		@rClubTypeId int
AS
SET NOCOUNT ON

		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN

	SELECT 
		
		CM.Id, 
		CM.Number,
		CM.Code,
		CM.Title,
		CM.OrderIndex,
		CM.IsObsolete,
		CM.ClubTypeId,
		CTM.Title AS ClubTypeName
		
	FROM
	
		sActivity.tClubMaster CM
		INNER JOIN sActivity.tClubTypeMaster CTM 
			ON CM.ClubTypeId = CTM.Id
	
	WHERE 
		((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
		AND ((CM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND (CM.OrgGroupId = @rOrgGroupId)
		AND ((CM.ClubTypeId = @rClubTypeId) OR (@rClubTypeId = 0))
		ORDER BY  CM.OrderIndex
END

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pEmployeeHealthTrackAdd]
			
			@rId bigint
           ,@rEmployeeId bigint
           ,@rHealthCheckupTypeId int
           ,@rCheckupFromDate date
           ,@rCheckupToDate date
           ,@rChiefComplain nvarchar(100)
           ,@rDiagnosis nvarchar(100)
           ,@rActionTaken nvarchar(100)
           ,@rRemark nvarchar(200)
           ,@rExaminedBy nvarchar(100)
           ,@rCreatedUserId bigint
           ,@rOrgId int
		   ,@rGatePassInTime datetime
		   ,@rGatePassOutTime datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
  
	
	 BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEmployeeHealthTrack', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sActivity].[tEmployeeHealthTrack]
           (
            [Id]
           ,[EmployeeId]
           ,[HealthCheckupTypeId]
           ,[CheckupFromDate]
           ,[CheckupToDate]
           ,[ChiefComplain]
           ,[Diagnosis]
           ,[ActionTaken]
           ,[Remark]
           ,[ExaminedBy]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
		   ,[InTime]
		   ,[OutTime]
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId
           ,@rHealthCheckupTypeId
           ,@rCheckupFromDate
           ,@rCheckupToDate
           ,@rChiefComplain
           ,@rDiagnosis
           ,@rActionTaken
           ,@rRemark
           ,@rExaminedBy
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate()
		   ,@rGatePassInTime
		   ,@rGatePassOutTime
           )
                                 
		   SELECT @lNextNumber AS Result	
	END	 

ELSE
	 BEGIN 
	      SET @lNextNumber = @rId
	     
	      UPDATE  [sActivity].[tEmployeeHealthTrack]
			   SET  
				   [HealthCheckupTypeId] = @rHealthCheckupTypeId 
				  ,[CheckupFromDate] = @rCheckupFromDate 
				  ,[CheckupToDate] = @rCheckupToDate 
				  ,[ChiefComplain] = @rChiefComplain 
				  ,[Diagnosis] = @rDiagnosis 
				  ,[ActionTaken] = @rActionTaken 
				  ,[Remark] = @rRemark 
				  ,[ExaminedBy] = @rExaminedBy			 
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate()
				  ,[InTime] = @rGatePassInTime
				  ,[OutTime] = @rGatePassOutTime
	   
	      WHERE Id = @rId	 
	      
	       SELECT @lNextNumber AS Result      		  
	 END   

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEmployeeHealthTrackGet]
	 
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rId bigint,
           @rEmployeeId bigint,
           @rHealthCheckUpTypeId int,
           @rCheckupFromDate date,
           @rCheckupToDate date,
           @rBatchId int,
		   @rDepartmentId int=0 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
   SELECT 
   
           @rBuilder1 AS Builder1,
		   @rBuilder2 AS Builder2,
		   HT.[Id]
		  ,HT.EmployeeId
		  ,[HealthCheckupTypeId]
		  ,[CheckupFromDate]
		  ,[CheckupToDate]
		  ,[ChiefComplain]
		  ,[Diagnosis]
		  ,[ActionTaken]
		  ,[Remark]
		  ,[ExaminedBy]
		  ,EC.Code AS EmployeeCode
		  ,EC.EmployeeName AS EmployeeName
		  ,EC.DepartmentId
		  ,EC.DepartmentName
		  ,CTM.Title AS HealthCheckupType
		  ,ISNULL(HT.InTime,'') AS InTime
		  ,ISNULL(HT.OutTime,'') AS OutTime
       
	FROM  [sActivity].[tEmployeeHealthTrack]  HT 
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = HT.EmployeeId	
		INNER JOIN sActivity.tHealthCheckUpTypeMaster CTM ON CTM.Id = HT.HealthCheckupTypeId
  
	WHERE   (HT.Id = @rId OR @rId = 0)	   	 	
		AND (HT.EmployeeId = @rEmployeeId OR @rEmployeeId =  0)
		AND (HealthCheckupTypeId = @rHealthCheckUpTypeId OR @rHealthCheckUpTypeId = 0)
		AND (CheckupFromDate >= @rCheckupFromDate OR ISNULL(@rCheckupFromDate,'') = '')
		AND (CheckupFromDate <= @rCheckupToDate OR ISNULL(@rCheckupToDate,'') = '')
		--AND BatchId = @rBatchId 
		AND (EC.DepartmentId=@rDepartmentId OR @rDepartmentId=0)
		
		order by HT.CheckupFromDate Asc
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEnrollmentGet]
	 
	 @rEventScheduleId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			ISNULL(EE.Id,0) AS Id,
			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
		    ES.Remark EventRemark,
		    ES.IsCommonForAll,
		    ES.IsHoliday,
		    ES.IsEnrollment,
		    EE.Remark,
		    'Student' AS SourceType,
		    SA.Code as SourceCode,
			SA.Name as SourceName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept
  FROM 
            sStudent.vStudentAcademic SA
        INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=SA.DivisionId AND EA.SourceTypeId=2005
        INNER JOIN sActivity.tEventSchedule ES ON ES.Id=EA.EventScheduleId
        INNER JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=SA.StudentId AND EE.SourceTypeId=2003
  WHERE 
  
		((ES.Id = @rEventScheduleId) OR (@rEventScheduleId = 0))
	AND	((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND (ES.BatchId=@rBatchId)
	
	UNION ALL
	
	SELECT 
			ISNULL(EE.Id,0) AS Id,
			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
		    ES.Remark AS EventRemark,
		    ES.IsCommonForAll,
		    ES.IsHoliday,
		    ES.IsEnrollment,
		    EE.Remark,
		    'Employee' AS SourceType,
		    EJD.EmployeeCode AS SourceCode,
			EJD.EmployeeName AS SourceName,
			EJD.DepartmentName AS ClassDept 
  FROM 
            sHrm.vExtEmployeeJobDetail EJD
		--mantis id 30734, comment the below line and add another inner join of tEventAssign table
        --INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=EJD.OrganizationDepartmentId AND EA.SourceTypeId=2004
		INNER JOIN sActivity.tEventAssign EA ON ((EA.SourceId=EJD.OrganizationDepartmentId AND EA.SourceTypeId=2004) OR (EA.SourceId=EJD.EmployeeId AND EA.SourceTypeId=95))
        INNER JOIN sActivity.tEventSchedule ES ON ES.Id=EA.EventScheduleId
        INNER JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=EJD.EmployeeId AND EE.SourceTypeId=95
  WHERE 
  
		((ES.Id = @rEventScheduleId) OR (@rEventScheduleId = 0))
	AND	((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND (ES.BatchId=@rBatchId)
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pEventAssignAdd]
			@rId int
	       ,@rEventScheduleId int
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsObsolete bit
           ,@rOrgId int
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
If(@rIsObsolete=1)
BEGIN

	Delete from sActivity.tEventAssign where EventScheduleId=@rEventScheduleId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN      
	If Exists(select Id from sActivity.tEventAssign where EventScheduleId=@rEventScheduleId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			DECLARE @lNextNumber BIGINT
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventAssign', 0, 1, 1,@outNextNumber = @lNextNumber output
			
			INSERT INTO sActivity.tEventAssign
			(
				Id
			   ,EventScheduleId
			   ,SourceTypeId
			   ,SourceId
			)
			VALUES
			(	@lNextNumber
			   ,@rEventScheduleId
			   ,@rSourceTypeId
			   ,@rSourceId
			)		
			SELECT @lNextNumber AS Result
	END
	
	 
END 	             
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sActivity].[pEventAssignGet]
	 @rEventScheduleId int,
	 @rOrgId smallint,
	 @rBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as DivDept,
			2005 as SourceTypeId,
			CASE WHEN EA.SourceId IS NULL OR EA.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END AS IsObsolete,
			CM.OrderIndex AS OrderIndex,
			DM.OrderIndex AS DivisionOrderIndex --Added for mantis : 35121 by Nilesh
  FROM 
			sSetup.tDivisionMaster DM
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId --Commented for mantis : 35121 by Nilesh
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND DM.IsObsolete = 0 --Added for mantis : 35121 by Nilesh
			INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId AND BC.BatchId=@rBatchId
			LEFT JOIN sActivity.tEventAssign EA ON EA.SourceId=DM.Id AND EA.SourceTypeId=2005 AND EA.EventScheduleId=@rEventScheduleId
	 WHERE
		DM.OrgId=@rOrgId
		UNION
	SELECT 
			ODM.Id  as SourceId,
			ODM.Title as DivDept,
			2004 as SourceTypeId,
			CASE WHEN EA.SourceId IS NULL OR EA.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END AS IsObsolete,
			0 AS OrderIndex,
			0 AS DivisionOrderIndex --Added for mantis : 35121 by Nilesh
  FROM 
			sSetup.tDepartmentMaster ODM
			LEFT JOIN sActivity.tEventAssign EA ON EA.SourceId=ODM.Id AND EA.SourceTypeId=2004 AND EA.EventScheduleId=@rEventScheduleId
	WHERE
		ODM.OrgId=@rOrgId
		UNION 
	SELECT 
			EC.EmployeeId  as SourceId,
			EC.EmployeeName as DivDept,
			95 as SourceTypeId,
			CASE WHEN EA.SourceId IS NULL OR EA.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END AS IsObsolete,
			0 AS OrderIndex,
			0 AS DivisionOrderIndex --Added for mantis : 35121 by Nilesh
  FROM 
			sHrm.vEmployeeCommunication EC
			LEFT JOIN sActivity.tEventAssign EA ON EA.SourceId=EC.Id AND EA.SourceTypeId=95 AND EA.EventScheduleId=@rEventScheduleId
	WHERE
		EC.OrgId=@rOrgId 
		Order By OrderIndex,DivisionOrderIndex --Added for mantis : 35121 by Nilesh
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEventAssignImport]
			 
	        @rEventScheduleId int
           ,@rSourceTypeId smallint
           ,@rSourceId bigint,
           @rOrgId smallint
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			DECLARE @lNextNumber BIGINT
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventAssign', 0, 1, 1,@outNextNumber = @lNextNumber output
	  Insert into sActivity.tEventAssign 
	  (
		Id,
		EventScheduleId,
		SourceTypeId,
		SourceId
	  )
	  Values
	  (
		@lNextNumber,
		@rEventScheduleId,
		@rSourceTypeId,
		@rSourceId
	  )
	  Select 1 as result
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pEventAttendanceAdd]

	@rEventAttendanceXml [nvarchar](max),
	@rEventScheduleId int,
	@rSourceTypeId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEventAttendanceXml
BEGIN
	
	 BEGIN TRY
	 BEGIN TRANSACTION
	
	 DELETE EA FROM sActivity.tEventAttendance EA 
	 INNER JOIN 
	 (SELECT SourceId FROM OPENXML(@loDoc, '/Table/EventAttendance', 1)
	 WITH(SourceId bigint))A 
	 ON EA.SourceId = A.SourceId 
	 AND EA.SourceTypeId=@rSourceTypeId 
	 AND EventScheduleId=@rEventScheduleId
	
	 --DELETE FROM sActivity.tEventAttendance WHERE EventScheduleId=@rEventScheduleId AND SourceTypeId = @rSourceTypeId
	
	 INSERT INTO sActivity.tEventAttendance
		(
			EventScheduleId,
			SourceTypeId,
			SourceId,
			IsSelfPresent,
			IsFatherPresent,
			IsMotherPresent,
			IsGuardianPresent
			)
		SELECT
			@rEventScheduleId,
			@rSourceTypeId,
			SourceId,
			IsSelfPresent,
			IsFatherPresent,
			IsMotherPresent,
			IsGuardianPresent
		FROM OPENXML (@loDoc, '/Table/EventAttendance', 1)
		WITH ( 
					SourceId bigint,
					IsSelfPresent bit,
					IsFatherPresent bit,
					IsMotherPresent bit,
					IsGuardianPresent bit
			  )
			  
	   SELECT 1 AS Result
	   EXEC sp_xml_removedocument @loDoc
	   
	   COMMIT TRANSACTION
		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEventAttendanceGet]
	 
	 
	 @rEventScheduleId int,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rOrgId smallint,
	 @rBatchId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		-- For Student Deatils
		IF(@rDivisionId != 0)
		BEGIN 
			SELECT
				vSA.AcademicId AS SourceId,
				vSA.Code,
				vSA.RollNo,
				vSA.Name,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				CONVERT (bit ,CASE WHEN EAT.SourceId IS NULL OR EAT.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END) AS IsObsolete,
				vSA.BatchId
			FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sActivity.tEventAssign EA 
					ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 AND EA.EventScheduleId=@rEventScheduleId
				LEFT JOIN sActivity.tEventAttendance EAT 
					ON EAT.EventScheduleId = EA.EventScheduleId AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
			WHERE
				vSA.OrgId=@rOrgId AND vSA.DivisionId = @rDivisionId
				AND vSA.BatchId = @rBatchId
				AND (vSA.StatusId =1 )
			ORDER BY vSA.RollNo	
		END
		
		-- For Employee Deatils
		IF(@rDepartmentId != 0)
		BEGIN 
			SELECT
				vECD.EmployeeId AS SourceId,
				vECD.Code,
				vECD.EmployeeName AS Name,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				CONVERT (bit ,CASE WHEN EAT.SourceId IS NULL OR EAT.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END) AS IsObsolete
			FROM 
				sHrm.vEmployeeCommonDetail vECD
				INNER JOIN sActivity.tEventAssign EA 
					ON EA.SourceId=vECD.OrganizationDepartmentId AND EA.SourceTypeId=2004 AND EA.EventScheduleId=@rEventScheduleId
				LEFT JOIN sActivity.tEventAttendance EAT 
					ON EAT.EventScheduleId = EA.EventScheduleId AND EAT.SourceId = vECD.EmployeeId AND EAT.SourceTypeId = 95
			WHERE
				vECD.OrgId=@rOrgId AND vECD.OrganizationDepartmentId = @rDepartmentId
				AND (vECD.EmployeeStatusId = 7)
			ORDER BY vECD.Code	
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEventAttendanceListGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rCode nvarchar(20)='',
	@rFirstName nvarchar(100)='',
	@rBatchId int = 0,
	@rDepartmentId int=0,
	@rEventTypeId int = 0,
	@rEventId int=0,
	@rFromDate date='',
	@rToDate date='',
	@rAcademicId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
		END
	SELECT 
			SA.AcademicId,
			SA.FirstName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName+'-'+SA.DivisionName AS DivDept,
			--SA.DivisionId,
			SA.RollNo,
			SA.OrgId,
			ISNULL (EA.IsSelfPresent,0) AS IsSelfPresent,
			ISNULL (EA.IsMotherPresent,0) AS IsMotherPresent,
			ISNULL (EA.IsFatherPresent,0) AS IsFatherPresent,
			ISNULL (EA.IsGuardianPresent,0) AS IsGuardianPresent,
			ES.FromDate,
			ES.ToDate,
			EM.Title AS EventTypeName,
			ES.Title AS EventName,
			ES.EventTypeId AS EventTypeId,
			ISNULL (EA.EventScheduleId,0) as EventScheduleId,
		
			
			ISNULL (EA.SchoolFeedback,'') AS SchoolFeedback,
			ISNULL (EA.ParentFeedback,'') AS ParentFeedback,
			ISNULL (EA.ParentAction,'') AS ParentAction,
			ISNULL (EA.SchoolAction,'') AS SchoolAction,
		ISNULL (EA.IsTrackForReview,0) AS IsTrackForReview,
		SA.DepartmentName,
		SA.BatchName
			
		
			
  FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sActivity.tEventAttendance EA ON  SA.AcademicId = EA.SourceId AND EA.SourceTypeId = 2001
			INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
			AND ((ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
			AND ((ES.Id = @rEventId) OR (@rEventId = 0))
			AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0)) 
			AND((SA.StatusId= 1))--add for 28753 mantis

			ORDER BY SA.ClassId,SA.DivisionId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sActivity].[pEventAttendanceStudentDetailsGet]
	
	 @rUserTypeId int,
	 @rIsPresentAbsent int,
	 @rOrgId int,
	 @rAcademicId bigint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	--SET @rUserTypeId = 1 for Student
	--SET @rUserTypeId = 2 for Father
	--SET @rUserTypeId = 3 for Mother
	--SET @rUserTypeId = 4 for Relative

	--SET @rIsPresentAbsent = 1 for All
	--SET @rIsPresentAbsent = 2 for Present
	--SET @rIsPresentAbsent = 3 for Absent


	--for Student
IF(@rUserTypeId = 1 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsSelfPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch = 1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsSelfPresent = 0 OR EAT.IsSelfPresent = 1)
END

IF(@rUserTypeId = 1 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsSelfPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId		
				AND (EAT.IsSelfPresent = 1)
END

IF(@rUserTypeId = 1 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsSelfPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsSelfPresent = 0)
END

--for Father

IF(@rUserTypeId = 2 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsFatherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsFatherPresent = 0 OR EAT.IsFatherPresent = 1)
END

IF(@rUserTypeId = 2 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsFatherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsFatherPresent = 1)
END

IF(@rUserTypeId = 2 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsFatherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsFatherPresent = 0)
END

--for Mother

IF(@rUserTypeId = 3 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsMotherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsMotherPresent = 0 OR EAT.IsMotherPresent = 1)
END

IF(@rUserTypeId = 3 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsMotherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsMotherPresent = 1)
END

IF(@rUserTypeId = 3 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsMotherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsMotherPresent = 0)
END

--for Relative

IF(@rUserTypeId = 4 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsGuardianPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsGuardianPresent = 0 OR EAT.IsGuardianPresent = 1)
END

IF(@rUserTypeId = 4 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsGuardianPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsGuardianPresent = 1)
END

IF(@rUserTypeId = 4 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsGuardianPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsGuardianPresent = 0)
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sActivity].[pEventAttendanceStudentWiseGet]
	
	 @rOrgId smallint,
	 @rAcademicId bigint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		Select 
		'Student' AS [Events],
		(SELECT COUNT(EAT.IsSelfPresent)
		FROM 
						sStudent.vStudentAcademic vSA
						INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
						INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
						--AND EA.EventScheduleId=@rEventScheduleId
						INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
						AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
						INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
						INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
						inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
						INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

					WHERE
						--(vSA.ClassId=0 OR 0=0)
						--AND (vSA.DivisionId=0 OR 0=0)
						(vSA.StatusId=1)
						AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
						AND (vSA.IsActiveBatch=1)
						AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
						AND vSA.AcademicId = @rAcademicId	
						AND (EAT.IsSelfPresent = 0 OR EAT.IsSelfPresent = 1)
						) AS Total,
			(SELECT COUNT(EAT.IsSelfPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1 )
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsSelfPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsSelfPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId
							AND EAT.IsSelfPresent = 0
							) AS Absent

UNION ALL

			Select 
			'Father' AS [Events],
			(SELECT COUNT(EAT.IsFatherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND (EAT.IsFatherPresent = 0 OR EAT.IsFatherPresent = 1)
							) AS Total,
			(SELECT COUNT(EAT.IsFatherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsFatherPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsFatherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch=1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsFatherPresent = 0
							) AS Absent

UNION All

			Select 
			'Mother' AS [Events],
			(SELECT COUNT(EAT.IsMotherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND (EAT.IsMotherPresent = 0 OR EAT.IsMotherPresent = 1)
							) AS Total,
			(SELECT COUNT(EAT.IsMotherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsMotherPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsMotherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
						--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsMotherPresent = 0
							) AS Absent


UNION All

			Select 
			'Relative' AS [Events],
			(SELECT COUNT(EAT.IsGuardianPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND (EAT.IsGuardianPresent = 0 OR EAT.IsGuardianPresent = 1)
							) AS Total,
			(SELECT COUNT(EAT.IsGuardianPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsGuardianPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsGuardianPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0) --Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsGuardianPresent = 0
							) AS Absent


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sActivity].[pEventAttendanceViewGet]	
	@rOrgId int=0,
	@rBatchId int =0,
	@rEventTypeId int = 0,
	@rAcademicId bigint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 
	DECLARE @lEventAttendanceGrid NVARCHAR(MAX)=''
	SELECT  @lEventAttendanceGrid = @lEventAttendanceGrid + '<tr>
	<td align="left" scope="col">' + CONVERT(VARCHAR,ISNULL(ES.FromDate,''),103) + '</td>
	<td align="left" scope="col">' + CONVERT(VARCHAR,ISNULL(ES.ToDate,''),103) + '</td>
	<td align="left" scope="col">' + ISNULL(ES.Title,'')  + '</td>
	<td align="left" scope="col">' + CASE WHEN EA.IsSelfPresent = 1 then 'Yes' ELSE 'No' END + '</td>	
	<td align="left" scope="col">' + CASE WHEN EA.IsFatherPresent = 1 then 'Yes' ELSE 'No' END + '</td>	
	<td align="left" scope="col">' + CASE WHEN EA.IsMotherPresent = 1 then 'Yes' ELSE 'No' END + '</td>	
	<td align="left" scope="col">' + ISNULL(EA.ParentFeedBack,'')+ '</td>	
	<td align="left" scope="col">' + ISNULL(EA.SchoolFeedback,'')+ '</td>	
	</tr>'
  FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sActivity.tEventAttendance EA ON  SA.AcademicId = EA.SourceId AND EA.SourceTypeId = 2001
			INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND ((ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
			AND((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0)) 
			ORDER BY SA.ClassId,SA.DivisionId

	SELECT ISNULL(@lEventAttendanceGrid,'') as EventAttendanceGrid

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pEventEnrollmentAdd]
	 
        @rId bigint,
		@rEventScheduleId int,
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rRemark nvarchar(500),
		@rCreatedUserId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lEnrollmentId BIGINT	
	

	
	
	
			
	IF(@rId = 0)	
	BEGIN
	
		IF EXISTS(SELECT Id  FROM  sActivity.tEventEnrollment where EventScheduleId=@rEventScheduleId AND SourceTypeId=@rSourceTypeId
		 AND SourceId=@rSourceId)
		BEGIN
		SELECT @lEnrollmentId = Id  FROM  sActivity.tEventEnrollment where EventScheduleId=@rEventScheduleId AND SourceTypeId=@rSourceTypeId
		 AND SourceId=@rSourceId
			select @lEnrollmentId AS Result			 
			RETURN
		END
	
	 BEGIN TRANSACTION		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventEnrollment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sActivity.tEventEnrollment
		(
			Id,
			EventScheduleId,
			SourceTypeId,
			SourceId,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rEventScheduleId,
			@rSourceTypeId,
			@rSourceId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sActivity.tEventEnrollment
	    SET
			Remark=@rRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEventEnrollmentGet]
	 
	 @rId bigint,
	 @rEventScheduleId int,
	 @rSourceTypeId smallint,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT 
				ISNULL(EE.Id,0) AS Id,
				ES.Id as EventScheduleId,
				ES.Title,
				ES.FromDate,
				ES.ToDate,
				ES.Remark AS EventRemark,
				ES.IsCommonForAll,
				ES.IsHoliday,
				ES.IsEnrollment,
				EE.Remark
		FROM 
				sActivity.tEventSchedule ES 
			LEFT JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceTypeId=2003 AND EE.Id=@rId
		WHERE 
	  
			(ES.Id = @rEventScheduleId)
		AND (ES.BatchId=@rBatchId)
	END
	ELSE
	BEGIN
		SELECT 
				ISNULL(EE.Id,0) AS Id,
				ES.Id as EventScheduleId,
				ES.Title,
				ES.FromDate,
				ES.ToDate,
				ES.Remark AS EventRemark,
				ES.IsCommonForAll,
				ES.IsHoliday,
				ES.IsEnrollment,
				EE.Remark 
		FROM 
				sActivity.tEventSchedule ES 
			LEFT JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceTypeId=95 AND EE.Id=@rId
		WHERE 
	  
			(ES.Id = @rEventScheduleId)
		AND (ES.BatchId=@rBatchId)
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pEventFeedbackUpdate]
	 
	    @rEventScheduleId int=0,
	    @rSourceTypeId int=0,
	    @rSourceId bigint,
		@rIsSelfPresent bit,
		@rIsFatherPresent bit,
		@rIsMotherPresent bit,
		@rIsGuardianPresent bit,
		@rSchoolFeedback nvarchar(500),
		@rParentFeedback nvarchar(500),
		@rSchoolAction nvarchar(500),
		@rParentAction nvarchar(500),
		@rIsTrackForReview bit
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	

 BEGIN 
	IF EXISTS(SELECT SourceId FROM sActivity.tEventAttendance WHERE EventScheduleId = @rEventScheduleId AND SourceId=@rSourceId)
	BEGIN
	UPDATE  sActivity.tEventAttendance
	    SET	
	        IsSelfPresent= @rIsSelfPresent,
		    IsFatherPresent=@rIsFatherPresent,
		    IsMotherPresent=@rIsMotherPresent,
		    IsGuardianPresent=@rIsGuardianPresent,		
			SchoolFeedback=@rSchoolFeedback,
			ParentFeedback=@rParentFeedback,
			SchoolAction=@rSchoolAction,
			ParentAction=@rParentAction,
			IsTrackForReview=@rIsTrackForReview
			
			
	      
	     -- SELECT @lNextNumber AS Result
	      WHERE EventScheduleId = @rEventScheduleId AND SourceId=@rSourceId
	     -- SELECT @lNextNumber AS Result
	     SELECT 2 AS Result
	END
	
	ELSE
	BEGIN
	INSERT INTO sActivity.tEventAttendance
		(
		 EventScheduleId,
		SourceTypeId,
		SourceId,
		IsSelfPresent,
		IsFatherPresent,
		IsMotherPresent,
		IsGuardianPresent,
		SchoolFeedback,
		ParentFeedback,
		SchoolAction,
		ParentAction,
		IsTrackForReview		
		)
	VALUES
		(
		 @rEventScheduleId,
		 @rSourceTypeId,		 
		 @rSourceId,
		 @rIsSelfPresent,
		 @rIsFatherPresent,
		 @rIsMotherPresent,
		 @rIsGuardianPresent,
		 @rSchoolFeedback,
		 @rParentFeedback,
		 @rSchoolAction,
		 @rParentAction,
		 @rIsTrackForReview
		)
		    SELECT 1 AS Result
	
	
	
	
	
	END
	    
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEventImportAdd]
	 
	  @rBatchid int,
	  @rOrgId smallint,
	  @rInsertBatchid int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lNextNumber bigint,@lCount int
	DECLARE @Title nvarchar(100)
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventSchedule', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	Set @lCount =(select  count(Id) from sActivity.tEventSchedule where BatchId=@rBatchid  ANd Title not  in (Select  Title from sActivity.tEventSchedule where BatchId=@rInsertBatchid))
 
	if exists(select  Title from sActivity.tEventSchedule where BatchId=@rBatchid  ANd Title   in (Select  Title from sActivity.tEventSchedule where BatchId=@rInsertBatchid))
	BEGIN
		return
		 
	END
	if NOT exists(select  Title from sActivity.tEventSchedule where BatchId=@rBatchid )
	BEGIn
		Select 101 As result
		return 
	END
	Insert into sActivity.tEventSchedule
	(
		Id,
			Title,
			FromDate,
			ToDate,
			Remark,
			IsCommonForAll,
			IsHoliday,
			IsEnrollment,
			CreatedUserId,
			CreatedDateTime,
			BatchId,
			EventTypeId
	)
	
	Select
	 @lNextNumber + ROW_NUMBER() OVER(ORDER BY CASE WHEN Id < 0  THEN Id END DESC,CASE WHEN Id > 0 THEN Id END ASC) AS Id, 
	Title,FromDate,ToDate,Remark,IsCommonForAll,IsHoliday,IsEnrollment,CreatedUserId,CreatedDateTime,@rInsertBatchid,EventTypeId from sActivity.tEventSchedule
	Where BatchId=@rBatchid  
	
	
	SET @lNextNumber  = @lCount + @lNextNumber 
	 EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sActivity.tEventSchedule', @rCurrentNumber = @lNextNumber 
	 
	 
	 	Select 1 AS Result
	 
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pEventInchargeAssignToAdd]
	 
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rEventScheduleId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION
	 IF EXISTS(SELECT 1 FROM sActivity.tEventInchargeAssign WHERE SourceTypeId=@rSourceTypeId 
	 AND SourceId=@rSourceId AND EventScheduleId=@rEventScheduleId)
	 BEGIN
			SELECT @rEventScheduleId AS Result
			RETURN
	 END
	INSERT INTO sActivity.tEventInchargeAssign
		(
			SourceTypeId,
			SourceId,
			EventScheduleId
		)
	VALUES
		(
			@rSourceTypeId,
			@rSourceId,
			@rEventScheduleId
		) 
		
		SELECT @rEventScheduleId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pEventInchargeAssignToDelete]
	 
	 @rSourceId bigint,
	 @rEventScheduleId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			DELETE FROM sActivity.tEventInchargeAssign WHERE SourceId=@rSourceId AND EventScheduleId = @rEventScheduleId
			SELECT 1 AS Result
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
			SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEventInchargeAssignToGet]
	 
	 @rEventScheduleId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			ES.Id AS EventScheduleId,
			EIA.SourceTypeId,
			EIA.SourceId,
			EM.EmployeeCode AS SourceCode,
			EM.EmployeeName AS SourceName
	FROM 
			sActivity.tEventInchargeAssign EIA
		INNER JOIN sActivity.tEventSchedule ES ON ES.Id=EIA.EventScheduleId AND (ES.BatchId = @rBatchId)	
		INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId=EIA.SourceId AND EIA.SourceTypeId=95
	WHERE 
			(EIA.EventScheduleId = @rEventScheduleId)
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sActivity].[pEventScheduleAdd]
	 
        @rId int,
		@rTitle nvarchar(100),
		@rFromDate date,
		@rToDate date,
		@rRemark nvarchar(1000),
		@rIsCommonForAll bit,
		@rIsHoliday bit,
		@rIsEnrollment bit,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int,
		@rEventTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	--IF(@rId = 0)	
	--BEGIN
	--	--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId)
	--	--	BEGIN
	--	--	select -102 as Result
	--	--	RETURN
	--	--END 
	
	--	If Exists(select Id from sActivity.tEventSchedule where Title=@rTitle AND BatchId=@rBatchId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sActivity.tEventSchedule where Title=@rTitle AND BatchId=@rBatchId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventSchedule', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sActivity.tEventSchedule
		(
			Id,
			Title,
			FromDate,
			ToDate,
			Remark,
			IsCommonForAll,
			IsHoliday,
			IsEnrollment,
			CreatedUserId,
			CreatedDateTime,
			BatchId,
			EventTypeId
			
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rFromDate,
			@rToDate,
			@rRemark,
			@rIsCommonForAll,
			@rIsHoliday,
			@rIsEnrollment,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rBatchId,
			@rEventTypeId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sActivity.tEventSchedule
	    SET
			Title=@rTitle,
			FromDate=@rFromDate,
			ToDate=@rToDate,
			Remark=@rRemark,
			IsCommonForAll=@rIsCommonForAll,
			IsHoliday=@rIsHoliday,
			IsEnrollment=@rIsEnrollment,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			EventTypeId=@rEventTypeId
	      
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEventScheduleDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sActivity.tEventInchargeAssign where EventScheduleId=@rId
		    Delete from sActivity.tEventAttendance where EventScheduleId=@rId
			Delete from sActivity.tEventAssign where EventScheduleId=@rId
			Delete from sActivity.tEventSchedule where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sActivity].[pEventScheduleGet]

	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rEventTypeId int = 0,
	 
	 @rSourceId bigint = 0,
	 @rSourceTypeId smallint = 0
	 --@rSyncedEventScheduleId int = 0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 



	IF @rIsSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT 

			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ISNULL(ES.EventTypeId,0) AS EventTypeId,
			ISNULL(EM.Title,'') AS EventType,
			EM.HighlightColor,
			EM.Title AS EventTypeName,
			OM.Id as OrgId,
			OM.WeekOffs,
			ES.BatchId
		FROM 
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		WHERE 

		((ES.Id = @rId) OR (@rId = 0))
		 AND ((ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2005 AND 
				SourceId=(SELECT DivisionId FROM sStudent.vStudentName WHERE StudentId=@rSourceId 
					AND OrgId= CAST(LEFT(@rBatchId,4) AS int)  AND BatchId=@rBatchId))))
		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND 
		(
			((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
							OR 
			((ES.ToDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
		)
		--AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ES.BatchId=@rBatchId
		AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
		ORDER BY ES.FromDate DESC
	END
	ELSE IF(@rSourceTypeId=95)
	BEGIN
		SELECT 

			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ISNULL(ES.EventTypeId,0) AS EventTypeId,
			ISNULL(EM.Title,'') AS EventType,
			EM.HighlightColor,
			EM.Title AS EventTypeName,
			OM.Id as OrgId,
			OM.WeekOffs,
			ES.BatchId
		FROM 
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		WHERE 

		((ES.Id = @rId) OR (@rId = 0))
		--AND (ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2004 AND SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)))
		AND (ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId IN(2004,95) AND ((SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)) OR (SourceId=@rSourceId))  ))
		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND 
		(
			((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
							OR 
			((ES.ToDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
		)
		AND ES.BatchId=@rBatchId
		AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
		ORDER BY ES.FromDate DESC
	END
	ELSE
	BEGIN
		SELECT 

			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ISNULL(ES.EventTypeId,0) AS EventTypeId,
			ISNULL(EM.Title,'') AS EventType,
			EM.HighlightColor,
			EM.Title AS EventTypeName,
			OM.Id as OrgId,
			OM.WeekOffs,
			ES.BatchId
		FROM 
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		WHERE 

		((ES.Id = @rId) OR (@rId = 0))
		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ES.BatchId=@rBatchId
		AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
		ORDER BY ES.FromDate DESC
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pEventTypeMasterAdd]
	 
		@rOrgGroupId int,
		@rId  int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rCreatedUserId bigint,
		@rCreatedDateTime date,
		@rIsObsolete bit,
		@rUpdateduserId bigint=0,
		@rUpdatedDateTime date='',
		@rHighlightColor nvarchar(100),
		@rOrderIndex int=0,
		@rEventMainTypeId tinyint=0
		
      
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sActivity.tEventTypeMaster where Title=@rTitle AND Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sActivity.tEventTypeMaster where Title=@rTitle AND Code=@rCode AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sActivity.tEventTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sActivity.tEventTypeMaster
		(
		OrgGroupId,
		Id,
		Code,
		Title,
		CreatedUserId,
		CreatedDateTime,
		IsObsolete,
		HighlightColor,
		UpdatedUserId,
		UpdatedDateTime,
		OrderIndex,
		EventMainTypeId
			
		)
	VALUES
		(
		@rOrgGroupId,
		@lNextNumber,
		@rCode,
		@rTitle,
		@rCreatedUserId,
		@rCreatedDateTime,
		@rIsObsolete,
		@rHighlightColor,
		@rCreatedUserId,
		@rCreatedDateTime,
		@rOrderIndex,
		@rEventMainTypeId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sActivity.tEventTypeMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			HighlightColor=@rHighlightColor,
			OrderIndex=@rOrderIndex,
			EventMainTypeId=@rEventMainTypeId
	      
	      
	      WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEventTypeMasterDelete]
	 
	 @rId int,
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		

		IF EXISTS (SELECT 1 FROM  sActivity.tEventSchedule WHERE EventTypeId=@rId)
		BEGIN
			SELECT -101 AS RESULT
		END
		ELSE 
		BEGIN
			DELETE FROM sActivity.tEventTypeMaster WHERE Id=@rId AND OrgGroupId=@rOrgGroupId
			SELECT 1 AS Result
		END		
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pEventTypeMasterGet]

	 @rOrgGroupId int,
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rEventMainTypeId tinyint=0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
SET @rTitle = sCommon.fSearchStringGet(@rTitle)
BEGIN 
	
	
	SELECT 
	
	EM.OrgGroupId,
	EM.Id AS EventTypeId,
	EM.Code AS Code,
	EM.Title AS Title,
	EM.IsObsolete,
	EM.HighlightColor,
	EM.OrderIndex,
	ISNULL(EM.EventMainTypeId,'') AS EventMainTypeId,
	ISNULL(EMTM.Title,'') AS EventMainType
  FROM 
            sActivity.tEventTypeMaster EM
            LEFT JOIN sActivity.tEventMainTypeMaster EMTM ON EM.EventMainTypeId = EMTM.Id
  WHERE 
   (EM.Id = @rId) OR (@rId=0)
   AND (EM.OrgGroupId = @rOrgGroupId) 
   AND ((EM.Title Like @rTitle )OR( ISNULL(@rTitle,'') = ''))
   AND ((EM.EventMainTypeId = @rEventMainTypeId) OR (@rEventMainTypeId=0))
   ORDER BY
   EM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthCheckupAdd]
			
			@rId int           
           ,@rBatchId int
           ,@rCheckupDate date
           ,@rTitle nvarchar(100)
           ,@rRemark nvarchar(200)
           ,@rDoctorName nvarchar(100)
           ,@rCreatedUserId bigint  
           ,@rOrgId int         
           

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
  
	
	 BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tHealthCheckup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO  [sActivity].[tHealthCheckup]
           ([Id]
           ,[BatchId]
           ,[CheckupDate]
           ,[Title]
           ,[Remark]
           ,[DoctorName]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime])
     VALUES
           (
            @lNextNumber
           ,@rBatchId
           ,@rCheckupDate
           ,@rTitle
           ,@rRemark
           ,@rDoctorName
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           )
                                 
		   SELECT @lNextNumber AS Result	
		   --COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN 
	      SET @lNextNumber = @rId
	     
	      UPDATE [sActivity].[tHealthCheckup]
			   SET 
			       
				   [CheckupDate] = @rCheckupDate
				  ,[Title] = @rTitle 
				  ,[Remark] = @rRemark 
				  ,[DoctorName] = @rDoctorName       
				  ,[UpdatedUserId] = @rCreatedUserId
				  ,[UpdatedDateTime] = sCommon.fGetDate()
	   
	      WHERE Id = @rId	 
	      
	       SELECT @lNextNumber AS Result      		  
	 END   

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sActivity].[pHealthCheckupEmployeeAdd]
			
			@rHealthCheckupId int
           ,@rEmployeeId bigint
           ,@rHeightInCm decimal(6,2)
           ,@rWeightInKg decimal(6,2)
           ,@rDental nvarchar(150)
           ,@rNails nvarchar(150)
           ,@rHair nvarchar(150)
           ,@rSkin nvarchar(150)
           ,@rEar nvarchar(150)
           ,@rNose nvarchar(150)
           ,@rThroat nvarchar(150)
           ,@rRespiratory nvarchar(150)
           ,@rCardiovascular nvarchar(150)
           ,@rNervous nvarchar(150)
           ,@rEye nvarchar(150)
           ,@rOther nvarchar(150)
           ,@rImortantFinding nvarchar(150)
           ,@rRemark nvarchar(150)
           ,@rFollowupDetail nvarchar(150)
           ,@rStatusId smallint  
           ,@rOrgId int       
           ,@rBloodGroupId int

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
	
	 BEGIN TRANSACTION	 
 
	IF NOT EXISTS (Select 1 FROM sActivity.tHealthCheckupEmployee Where HealthCheckupId = @rHealthCheckupId AND EmployeeId = @rEmployeeId)
	BEGIN
	INSERT INTO  sActivity.tHealthCheckupEmployee
           ([HealthCheckupId]
           ,[EmployeeId]
           ,[HeightInCm]
           ,[WeightInKg]
           ,[Dental]
           ,[Nails]
           ,[Hair]
           ,[Skin]
           ,[Ear]
           ,[Nose]
           ,[Throat]
           ,[Respiratory]
           ,[Cardiovascular]
           ,[Nervous]
           ,[Eye]
           ,[Other]
           ,[ImportantFinding]
           ,[Remarks]
           ,[FollowupDetail]
           ,[StatusId]
		   ,[BloodGroupId])
     VALUES
           (
            @rHealthCheckupId
           ,@rEmployeeId
           ,@rHeightInCm 
           ,@rWeightInKg 
           ,@rDental 
           ,@rNails 
           ,@rHair 
           ,@rSkin 
           ,@rEar 
           ,@rNose 
           ,@rThroat 
           ,@rRespiratory 
           ,@rCardiovascular 
           ,@rNervous 
           ,@rEye 
           ,@rOther 
           ,@rImortantFinding 
           ,@rRemark
           ,@rFollowupDetail 
           ,@rStatusId 
		   ,@rBloodGroupId
           )
                                 
		   --SELECT @rHealthCheckupId AS Result	
		   SELECT 1 AS Result
		   --COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN  
	      UPDATE [sActivity].[tHealthCheckupEmployee]
			   SET [HealthCheckupId] = @rHealthCheckupId
				  ,[EmployeeId] = @rEmployeeId
				  ,[HeightInCm] = @rHeightInCm
				  ,[WeightInKg] = @rWeightInKg 
				  ,[Dental] = @rDental 
				  ,[Nails] = @rNails 
				  ,[Hair] = @rHair 
				  ,[Skin] = @rSkin 
				  ,[Ear] = @rEar 
				  ,[Nose] = @rNose 
				  ,[Throat] = @rThroat 
				  ,[Respiratory] = @rRespiratory  
				  ,[Cardiovascular] = @rCardiovascular 
				  ,[Nervous] = @rNervous 
				  ,[Eye] = @rEye 
				  ,[Other] = @rOther 
				  ,[ImportantFinding] = @rImortantFinding 
				  ,[Remarks] = @rRemark
				  ,[FollowupDetail] = @rFollowupDetail 
				  ,[StatusId] = @rStatusId 
				  ,[BloodGroupId] = @rBloodGroupId
				 Where HealthCheckupId = @rHealthCheckupId AND EmployeeId = @rEmployeeId
	      
	       --SELECT @rHealthCheckupId AS Result
		   SELECT 11 AS Result      		  
	 END   

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sActivity].[pHealthCheckupEmployeeAlertGet]
	           
           @rEmployeeId bigint,
           @rHealthCheckupId int,
           @rStatusId int,
           @rBatchId int,
           @rFromDate date = null,
           @rToDate date = null,
           @rDepartmentId int,
		   @rOrgId int  = 0,
		   @rTemplate nvarchar(max),
		   @rSubject nvarchar(100)=''               
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
  SELECT      
			   [HealthCheckupId] AS HealthCheckupId  
	          ,HT.EmployeeId 
			  ,ISNULL(EC.CompanyEmail,'') AS EmailId
			  ,ISNULL(EC.MobileNumber,'') AS MobileNo
			  ,ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
			  ,REPLACE (
			   REPLACE (
			   REPLACE (
			   REPLACE (
			   REPLACE (
			   REPLACE(@rTemplate,'[Name]',EC.FirstName+' '+EC.MiddleName+' '+EC.LastName),
			   '[Department]',ISNULL(EC.DepartmentName,'')),
			   '[Date]',Convert(Varchar,HC.CheckupDate,103)),
			   '[Other]', ISNULL(HT.Other,'')),
			   '[Remark]',ISNULL(HT.Remarks,'')),
			   '[Status]',ISNULL(SMM.Title,''))
			   AS MsgText
			   ,@rSubject AS [Subject]
			   ,0 AS ReceiverSourceTypeId
			   ,0 AS ReceiverSourceId
			   ,OM.OrgGroupId As OrgGroupId
			   ,OM.Id As OrgId
			   ,95 AS SourceTypeId
			   ,EC.EmployeeId AS SourceId,
			   [HealthCheckupId] AS DocumentId   		  
			  
  FROM		[sActivity].[tHealthCheckupEmployee] HT 
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = HT.EmployeeId	
    		INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	
    		INNER JOIN sActivity.tHealthCheckup HC ON HC.Id = HT.HealthCheckupId  
    		LEFT JOIN [sHrm].[tEmployeePersonalDetail] EPD ON EPD.EmployeeId = EC.EmployeeId
    		LEFT JOIN sCommon.tBloodGroupMaster BGM ON EPD.BloodGroupId=BGM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
    		    		
  
  WHERE  (HT.HealthCheckupId = @rHealthCheckupId OR @rHealthCheckupId = 0)	
	     AND (HT.EmployeeId = @rEmployeeId OR @rEmployeeId =  0)
	     AND (HT.StatusId = @rStatusId OR @rStatusId = 0)
         AND (HC.CheckupDate >= @rFromDate OR ISNULL(@rFromDate,'') = '')
		 AND (HC.CheckupDate <= @rToDate OR ISNULL(@rToDate,'') = '')
		 AND (HC.BatchId = @rBatchId OR @rBatchId = 0)
		 AND (EC.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		 AND (EC.OrgId = @rOrgId OR @rOrgId = 0)
			
		ORDER BY CheckupDate ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthCheckupEntryGet]
	       
           @rHealthCheckupId int,           
           @rBatchId int,
           @rDivisionId int,
           @rClassId int ,
		   @rStatusId int=0             
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
  SELECT      ISNULL([HealthCheckupId],0) AS HealthCheckupId     
	          ,SM.AcademicId 
			  ,ISNULL([HeightInCm],0) AS HeightInCm 
			  ,ISNULL([WeightInKg],0) AS WeightInKg
			  ,ISNULL([Dental],'') AS Dental
			  ,ISNULL([Nails],'') AS Nails
			  ,ISNULL([Hair],'') AS Hair
			  ,ISNULL([Skin],'') AS Skin
			  ,ISNULL([Ear],'') AS Ear
			  ,ISNULL([Nose],'') AS Nose
			  ,ISNULL([Throat],'') AS Throat
			  ,ISNULL([Respiratory],'') AS Respiratory
			  ,ISNULL([Cardiovascular],'') AS Cardiovascular
			  ,ISNULL([Nervous],'') AS Nervous
			  ,ISNULL([Eye],'') AS Eye
			  ,ISNULL([Other],'') AS Other
			  ,ISNULL([ImportantFinding],'') AS ImportantFinding
			  ,ISnull([Remarks],'') AS Remarks
			  ,ISNULL([FollowupDetail],'') AS FollowupDetail
			  ,ISNULL(HT.[StatusId],0) AS StatusId 
			  ,(SM.ClassName +'-' + SM.DivisionName) AS ClassName
			  ,SM.Name AS StudentName
			  ,SM.Code AS StudentCode
			  ,SM.RollNo AS RollNo
			  ,ISNULL(HT.BloodGroupId,0) AS BloodGroupId
			  --,HC.Title AS HealthCheckup
			  
  FROM	   
			sStudent.vStudentAcademic SM LEFT JOIN   
         	[sActivity].[tHealthCheckupStudent]       
    		HT ON SM.AcademicId = HT.AcademicId	AND (HT.HealthCheckupId = @rHealthCheckupId  )
    		--INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	
    		--INNER JOIN sActivity.tHealthCheckup HC ON HC.Id = HT.HealthCheckupId  
    		
  
  WHERE  
		 BatchId = @rBatchId 
		 AND (SM.ClassId = @rClassId OR @rClassId = 0)
		 AND (SM.DivisionId = @rDivisionId OR @rDivisionId = 0)
	     --AND (HT.AcademicId = @rAcadamicId OR @rAcadamicId =  0)
	     AND (SM.StatusId = @rStatusId OR @rStatusId = 0)
	     --AND HC.BatchId = @rBatchId
      Order By SM.RollNo ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthCheckupGet]
	 
           @rId int,
           @rBatchId int,
           @rTitle nvarchar(100),
           @rFromDate date,
           @rToDate date      
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
	   SELECT  [Id]			 
			  ,[CheckupDate]
			  ,[Title]
			  ,[Remark]
			  ,[DoctorName]
		   
	  FROM [sActivity].[tHealthCheckup]       
    	  
  
	WHERE   (Id = @rId OR @rId = 0) AND BatchId = @rBatchId
			AND (Title like @rTitle + '%' OR ISNULL(@rTitle,'') = '')   
			AND (CheckupDate >= @rFromDate OR ISNULL(@rFromDate,'') = '')
			AND (CheckupDate <= @rToDate OR ISNULL(@rToDate,'') = '')
	
	order by Id
 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pHealthCheckupRemove]

	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
     DECLARE @1IsRefferd bit
	BEGIN TRY
		BEGIN TRANSACTION	
		
		   SET @1IsRefferd = 0;		    
		   Select @1IsRefferd = 1 FROM sActivity.tHealthCheckupStudent Where HealthCheckupId = @rId 
		   
		   IF(@1IsRefferd=0)
		    BEGIN
		       DELETE FROM sActivity.tHealthCheckup Where Id = @rId
		       Select 1 As Result
		    END
		    ELSE
		    Select -101 AS Result
		    
		  			
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sActivity].[pHealthCheckupStudentAdd]
			
			@rHealthCheckupId int
           ,@rAcadamicId bigint
           ,@rHeightInCm decimal(6,2)
           ,@rWeightInKg decimal(6,2)
           ,@rDental nvarchar(150)
           ,@rNails nvarchar(150)
           ,@rHair nvarchar(150)
           ,@rSkin nvarchar(150)
           ,@rEar nvarchar(150)
           ,@rNose nvarchar(150)
           ,@rThroat nvarchar(150)
           ,@rRespiratory nvarchar(150)
           ,@rCardiovascular nvarchar(150)
           ,@rNervous nvarchar(150)
           ,@rEye nvarchar(150)
           ,@rOther nvarchar(150)
           ,@rImortantFinding nvarchar(150)
           ,@rRemark nvarchar(150)
           ,@rFollowupDetail nvarchar(150)
           ,@rStatusId smallint  
           ,@rOrgId int       
           ,@rBloodGroupId int

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
	
	 BEGIN TRANSACTION	 
 
	IF NOT EXISTS (Select 1 FROM sActivity.tHealthCheckupStudent Where HealthCheckupId = @rHealthCheckupId AND AcademicId = @rAcadamicId)
	BEGIN
	INSERT INTO  [sActivity].[tHealthCheckupStudent]
           ([HealthCheckupId]
           ,[AcademicId]
           ,[HeightInCm]
           ,[WeightInKg]
           ,[Dental]
           ,[Nails]
           ,[Hair]
           ,[Skin]
           ,[Ear]
           ,[Nose]
           ,[Throat]
           ,[Respiratory]
           ,[Cardiovascular]
           ,[Nervous]
           ,[Eye]
           ,[Other]
           ,[ImportantFinding]
           ,[Remarks]
           ,[FollowupDetail]
           ,[StatusId]
		   ,[BloodGroupId])
     VALUES
           (
            @rHealthCheckupId
           ,@rAcadamicId
           ,@rHeightInCm 
           ,@rWeightInKg 
           ,@rDental 
           ,@rNails 
           ,@rHair 
           ,@rSkin 
           ,@rEar 
           ,@rNose 
           ,@rThroat 
           ,@rRespiratory 
           ,@rCardiovascular 
           ,@rNervous 
           ,@rEye 
           ,@rOther 
           ,@rImortantFinding 
           ,@rRemark
           ,@rFollowupDetail 
           ,@rStatusId 
		   ,@rBloodGroupId
           )
                                 
		   --SELECT @rHealthCheckupId AS Result	
		   SELECT 1 AS Result
		   --COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN  
	      UPDATE [sActivity].[tHealthCheckupStudent]
			   SET [HealthCheckupId] = @rHealthCheckupId
				  ,[AcademicId] = @rAcadamicId
				  ,[HeightInCm] = @rHeightInCm
				  ,[WeightInKg] = @rWeightInKg 
				  ,[Dental] = @rDental 
				  ,[Nails] = @rNails 
				  ,[Hair] = @rHair 
				  ,[Skin] = @rSkin 
				  ,[Ear] = @rEar 
				  ,[Nose] = @rNose 
				  ,[Throat] = @rThroat 
				  ,[Respiratory] = @rRespiratory  
				  ,[Cardiovascular] = @rCardiovascular 
				  ,[Nervous] = @rNervous 
				  ,[Eye] = @rEye 
				  ,[Other] = @rOther 
				  ,[ImportantFinding] = @rImortantFinding 
				  ,[Remarks] = @rRemark
				  ,[FollowupDetail] = @rFollowupDetail 
				  ,[StatusId] = @rStatusId 
				  ,[BloodGroupId] = @rBloodGroupId
				 Where HealthCheckupId = @rHealthCheckupId AND AcademicId = @rAcadamicId
	      
	       --SELECT @rHealthCheckupId AS Result   
		   SELECT 11 AS Result   		  
	 END   

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sActivity].[pHealthCheckupStudentAlertGet]
   
           @rAcadamicId bigint,
           @rHealthCheckupId int,
           @rStatusId int,
           @rBatchId int,
           @rFromDate date = null,
           @rToDate date = null,
           @rDivisioId int,
           @rClassId int,
		   @rTemplate nvarchar(max),
		   @rSubject nvarchar(100)=''              
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
  SELECT      
			  [HealthCheckupId]     
	          ,HT.AcademicId 
			  ,ISNULL(HT.BloodGroupId,0)AS BloodGroupId
			  ,ISNULL(BGM.Title,'') AS BloodGroup
			  ,ISNULL(SC.ParentEmail,'') AS EmailId
			  ,ISNULL(SC.ParentContactNo,'') AS MobileNo
			  ,ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			  ,REPLACE (
	    REPLACE (
		REPLACE (
		REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',SM.FirstName+' '+SM.MiddleName+' '+SM.LastName),
		'[Class-Division]',ISNULL(SM.ClassName+'-'+SM.DivisionName,'')),
		'[Date]',Convert(Varchar,HC.CheckupDate,103)),
		'[Other]', ISNULL(HT.Other,'')),
		'[Remark]',ISNULL(HT.Remarks,'')),
		'[Status]',ISNULL(SMM.Title,''))
		AS MsgText,
		@rSubject AS [Subject],
		0 AS ReceiverSourceTypeId,
		0 AS ReceiverSourceId,
		OM.OrgGroupId As OrgGroupId,		  
		OM.Id As OrgId,
		2003 AS SourceTypeId,
		SM.StudentId AS SourceId,
		[HealthCheckupId] AS DocumentId 	
			  	  
  FROM		[sActivity].[tHealthCheckupStudent]       
    		HT INNER JOIN sStudent.vStudentAcademic SM ON SM.AcademicId = HT.AcademicId	
    		INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	
    		INNER JOIN sActivity.tHealthCheckup HC ON HC.Id = HT.HealthCheckupId  
    		LEFT JOIN sStudent.tStudentCommunication SC ON SM.StudentId=SC.StudentId
    		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.StudentId
    		LEFT JOIN sCommon.tBloodGroupMaster BGM ON SO.BloodGroupId=BGM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
    		    		
  
  WHERE  (HT.HealthCheckupId = @rHealthCheckupId OR @rHealthCheckupId = 0)	
	     AND (HT.AcademicId = @rAcadamicId OR @rAcadamicId =  0)
	     AND (HT.StatusId = @rStatusId OR @rStatusId = 0)
	     AND HC.BatchId = @rBatchId
         AND (HC.CheckupDate >= @rFromDate OR ISNULL(@rFromDate,'') = '')
		 AND (CheckupDate <= @rToDate OR ISNULL(@rToDate,'') = '')
		 AND (SM.ClassId = @rClassId OR @rClassId = 0)
		 ANd (SM.DivisionId = @rDivisioId OR @rDivisioId = 0)
			
		ORDER BY CheckupDate,ClassId,DivisionId,RollNo ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pHealthCheckupStudentGet]
	        
	       @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rAcadamicId bigint,
           @rHealthCheckupId int,
           @rStatusId int,
           @rBatchId int,
           @rFromDate date = null,
           @rToDate date = null,
           @rDivisioId int,
           @rClassId int                 
	
WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
  SELECT      
			  @rBuilder1 AS Builder1,
			  @rBuilder2 AS Builder2,
			  [HealthCheckupId]     
	          ,HT.AcademicId 
			  ,ISNULL([HeightInCm],0) AS HeightInCm 
			  ,ISNULL([WeightInKg],0) AS WeightInKg
			  ,[Dental]
			  ,[Nails]
			  ,[Hair]
			  ,[Skin]
			  ,[Ear]
			  ,[Nose]
			  ,[Throat]
			  ,[Respiratory]
			  ,[Cardiovascular]
			  ,[Nervous]
			  ,[Eye]
			  ,[Other]
			  ,[ImportantFinding]
			  ,[Remarks]
			  ,[FollowupDetail]
			  ,HT.[StatusId]			 			   
			  ,(SM.ClassName +'-' + SM.DivisionName) AS ClassName
			  ,SM.Name AS StudentName
			  ,SM.Code AS StudentCode
			  ,SM.RollNo
			  ,SM.ClassId
			  ,SM.DivisionId
			  ,ISNULL(SM.GenderId,0) AS GenderId
			  --,SM.Age
			  ,SC.PresentStreetOne+' '+SC.PresentStreetTwo+' '+SC.PermanentStreetThree+' '+SC.PresentCity AS Address  
			  ,SC.PresentContactNo As ContactNo
			  ,BGM.Title AS BloodGroup
			  ,SMM.Title AS Status
			  ,HC.Title AS HealthCheckup
			  ,HC.DoctorName
			  ,HC.CheckupDate
			  ,ISNULL(HT.BloodGroupId,0)AS BloodGroupId
			  ,ISNULL(BGM.Title,'') AS BloodGroup
			  
  FROM		[sActivity].[tHealthCheckupStudent]       
    		HT INNER JOIN sStudent.vStudentAcademic SM ON SM.AcademicId = HT.AcademicId	
    		INNER JOIN sCommon.tStatusMaster SMM ON SMM.Id = HT.StatusId	
    		INNER JOIN sActivity.tHealthCheckup HC ON HC.Id = HT.HealthCheckupId  
    		LEFT JOIN sStudent.tStudentCommunication SC ON SM.StudentId=SC.StudentId
    		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.StudentId
    		LEFT JOIN sCommon.tBloodGroupMaster BGM ON SO.BloodGroupId=BGM.Id
    		    		
  
  WHERE  (HT.HealthCheckupId = @rHealthCheckupId OR @rHealthCheckupId = 0)	
	     AND (HT.AcademicId = @rAcadamicId OR @rAcadamicId =  0)
	     AND (HT.StatusId = @rStatusId OR @rStatusId = 0)
	     AND HC.BatchId = @rBatchId
         AND (HC.CheckupDate >= @rFromDate OR ISNULL(@rFromDate,'') = '')
		 AND (CheckupDate <= @rToDate OR ISNULL(@rToDate,'') = '')
		 AND (SM.ClassId = @rClassId OR @rClassId = 0)
		 ANd (SM.DivisionId = @rDivisioId OR @rDivisioId = 0)
			
		ORDER BY CheckupDate,ClassId,DivisionId,RollNo ASC
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthParameterAdd]
	 
            @rId int
           ,@rTitle  nvarchar(100)
           ,@rParameterValueTypeId tinyint
           ,@rNumericFormat nvarchar(20)
           ,@rUOM nvarchar(50)
           ,@rIsObsolete bit
           ,@rOrderIndex smallint
           ,@rCreatedUserId bigint               
           ,@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
  
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tHealthParameterMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO  [sActivity].[tHealthParameterMaster]
           (
            [Id]
           ,[Title]
           ,[ParameterValueTypeId]
           ,[NumericFormat]
           ,[UOM]
           ,[IsObsolete]
           ,[OrderIndex]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgId])
     VALUES
           (            
            @lNextNumber
           ,@rTitle
           ,@rParameterValueTypeId 
           ,@rNumericFormat 
           ,@rUOM 
           ,@rIsObsolete 
           ,@rOrderIndex 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rOrgId 
           )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN 
	      SELECT @lNextNumber AS Result 
	      UPDATE [sActivity].[tHealthParameterMaster]
		   SET 
			   [Title] = @rTitle 
			  ,[ParameterValueTypeId] = @rParameterValueTypeId
			  ,[NumericFormat] = @rNumericFormat
			  ,[UOM] = @rUOM
			  ,[IsObsolete] = @rIsObsolete
			  ,[OrderIndex] = @rOrderIndex			   
			  ,[UpdatedUserId] = @rCreatedUserId
			  ,[UpdatedDateTime] = @rCreatedUserId
			  ,[OrgId] = @rOrgId
	      WHERE Id = @rId	      
		  --COMMIT TRANSACTION
	 END  	
	 
	  DELETE FROM sActivity.tHealthParameterList Where HealthParameterId = @rId

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthParameterGet]
	 
           @rId int,
           @rOrgId int,
           @rParameterValueTypeId int          
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	

	 SELECT 
	       [Id]
		  ,[Title]
		  ,[ParameterValueTypeId]
		  ,[NumericFormat]
		  ,[UOM]	 
		  ,[OrderIndex] 
		  
     FROM  [sActivity].[tHealthParameterMaster]  
     WHERE (Id = @rId OR @rId = 0)
           AND (ParameterValueTypeId = @rParameterValueTypeId OR  @rParameterValueTypeId = ParameterValueTypeId)
           AND  OrgId = @rOrgId   	   	 	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthParameterListAdd]
	 
            @rHealthParameterId int
           ,@rTitle  nvarchar(100)
           ,@rIsNormal bit
           ,@rDiagnosis  nvarchar(100)
           ,@rRecommendation nvarchar(100) 
           ,@rOrderIndex  int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
 
--IF(@rHealthParameterId = 0)	 
  BEGIN

  

   INSERT INTO  [sActivity].[tHealthParameterList]
           (
            [HealthParameterId]
           ,[Title]
           ,[IsNormal]
           ,[Diagnosis]
           ,[Recommendation]
           ,[OrderIndex]
           )
     VALUES
           (            
            @rHealthParameterId
           ,@rTitle
           ,@rIsNormal
           ,@rDiagnosis
           ,@rRecommendation
           ,@rOrderIndex
           )
		  SELECT @rHealthParameterId AS Result	
		--COMMIT TRANSACTION         
	END	 

--ELSE
--	 BEGIN 
--	      SELECT @lNextNumber AS Result 
--	   UPDATE  [sActivity].[tHealthParameterList]
--	   SET 
       
--       [Title] = @rTitle
--      ,[IsNormal] = @rIsNormal
--      ,[Diagnosis] = @rDiagnosis
--      ,[Recommendation] = @rRecommendation
--      ,[OrderIndex] = @rOrderIndex
--		  --COMMIT TRANSACTION
--	   WHERE [HealthParameterId] = @rHealthParameterId
--	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthParameterListGet]
	            
           @rHealthParameterId int
                      
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	

	 SELECT    [HealthParameterId]
			  ,[Title]
			  ,[IsNormal]
			  ,[Diagnosis]
			  ,[Recommendation]
			  ,[OrderIndex]
      
     FROM   [sActivity].[tHealthParameterList]  Where HealthParameterId = @rHealthParameterId 	   	 	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthTrackAdd]
			
			@rId bigint
           ,@rAcadamicId bigint
           ,@rHealthCheckupTypeId int
           ,@rCheckupFromDate date
           ,@rCheckupToDate date
           ,@rChiefComplain nvarchar(100)
           ,@rDiagnosis nvarchar(100)
           ,@rActionTaken nvarchar(100)
           ,@rRemark nvarchar(200)
           ,@rExaminedBy nvarchar(100)
           ,@rCreatedUserId bigint
           ,@rOrgId int
		   ,@rGatePassInTime datetime
		   ,@rGatePassOutTime datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
  
	
	 BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tHealthTrack', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sActivity].[tHealthTrack]
           (
            [Id]
           ,[AcademicId]
           ,[HealthCheckupTypeId]
           ,[CheckupFromDate]
           ,[CheckupToDate]
           ,[ChiefComplain]
           ,[Diagnosis]
           ,[ActionTaken]
           ,[Remark]
           ,[ExaminedBy]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
		   ,[InTime]
		   ,[OutTime]
           )
     VALUES
           (
            @lNextNumber
           ,@rAcadamicId
           ,@rHealthCheckupTypeId
           ,@rCheckupFromDate
           ,@rCheckupToDate
           ,@rChiefComplain
           ,@rDiagnosis
           ,@rActionTaken
           ,@rRemark
           ,@rExaminedBy
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate()
		   ,@rGatePassInTime
		   ,@rGatePassOutTime
           )
                                 
		   SELECT @lNextNumber AS Result	
		   --COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN 
	      SET @lNextNumber = @rId
	     
	      UPDATE  [sActivity].[tHealthTrack]
			   SET  
				   --[AcademicId] = @rAcademicId 
				   [HealthCheckupTypeId] = @rHealthCheckupTypeId 
				  ,[CheckupFromDate] = @rCheckupFromDate 
				  ,[CheckupToDate] = @rCheckupToDate 
				  ,[ChiefComplain] = @rChiefComplain 
				  ,[Diagnosis] = @rDiagnosis 
				  ,[ActionTaken] = @rActionTaken 
				  ,[Remark] = @rRemark 
				  ,[ExaminedBy] = @rExaminedBy			 
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate()
				  ,[InTime] = @rGatePassInTime
				  ,[OutTime] = @rGatePassOutTime
	   
	      WHERE Id = @rId	 
	      
	       SELECT @lNextNumber AS Result      		  
	 END   

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthTrackEmployeeRemove]
	 
            @rEmployeeId bigint,
            @rHealthCheckUpId int
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
         DELETE FROM sActivity.tHealthCheckupEmployee Where HealthCheckupId = @rHealthCheckUpId AND EmployeeId = @rEmployeeId 
		
		SELECT 1 AS Result
	 
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthTrackGet]
	 
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rId bigint,
           @rAcadamicId bigint,
           @rHealthCheckUpTypeId int,
           @rCheckupFromDate date,
           @rCheckupToDate date,
           @rBatchId int,
		   @rDivisionId int=0 ,
		   @rClassId int=0    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
   SELECT 
   
           @rBuilder1 AS Builder1,
		   @rBuilder2 AS Builder2,
		   HT.[Id]
		  ,HT.[AcademicId]
		  ,[HealthCheckupTypeId]
		  ,[CheckupFromDate]
		  ,[CheckupToDate]
		  ,[ChiefComplain]
		  ,[Diagnosis]
		  ,[ActionTaken]
		  ,[Remark]
		  ,[ExaminedBy]
		  ,SM.Code AS StudentCode
		  ,SM.Name AS StudentName
		  ,SM.RollNo
		  ,SM.ClassId
		  ,SM.ClassName+'-'+SM.DivisionName As ClassName
		  ,CTM.Title AS HealthCheckupType
		  ,ISNULL(HT.InTime,'') AS InTime
		  ,ISNULL(HT.OutTime,'') AS OutTime
		  ,DM.OrderIndex As OrderIndex
       
	FROM  [sActivity].[tHealthTrack]  HT INNER JOIN sStudent.vStudentAcademic SM ON SM.AcademicId = HT.AcademicId
		  INNER JOIN sActivity.tHealthCheckUpTypeMaster CTM ON CTM.Id = HT.HealthCheckupTypeId
		  Inner Join sSetup.tDivisionMaster DM on SM.DivisionId=DM.Id
  
	WHERE   (HT.Id = @rId OR @rId = 0)	   	 	
		AND (HT.AcademicId = @rAcadamicId OR @rAcadamicId =  0)
		AND (HealthCheckupTypeId = @rHealthCheckUpTypeId OR @rHealthCheckUpTypeId = 0)
		AND (CheckupFromDate >= @rCheckupFromDate OR ISNULL(@rCheckupFromDate,'') = '')
		AND (CheckupFromDate <= @rCheckupToDate OR ISNULL(@rCheckupToDate,'') = '')
		AND BatchId = @rBatchId AND (DM.Id=@rDivisionId OR @rDivisionId=0)
		AND (DM.ClassId=@rClassId OR @rClassId=0)
		
		order by HT.CheckupFromDate Asc
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHealthTrackStudentRemove]
	 
            @rAcademicId bigint,
            @rHealthCheckUpId int
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
         DELETE FROM sActivity.tHealthCheckupStudent Where HealthCheckupId = @rHealthCheckUpId AND AcademicId = @rAcademicId 
		
		SELECT 1 AS Result
	 
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHouseMasterAdd]
	 
	        @rId int,
	        @rNumber int,
	        @rCode nvarchar(50),
            @rTitle nvarchar(100),
            @rOrderIndex int,
            @rIsObsolete bit,
            @rCreatedUserId bigint,           
            @rOrgId int,
            @rHouseGroupId int,
            @rColorCode nvarchar(20)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Code=@rCode AND OrgId=@rOrgId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Number=@rNumber AND OrgId=@rOrgId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE OrderIndex=@rOrderIndex AND OrgId=@rOrgId)
		BEGIN
			SELECT -104 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -101 As Result
			RETURN
		END 
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			SELECT -103 AS Result
			RETURN
		END
		IF EXISTS (SELECT Id FROM sActivity.tHouseMaster WHERE OrderIndex=@rOrderIndex AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -104 AS Result
			RETURN
		END
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tHouseMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sActivity].[tHouseMaster]
			   (
			    [Id],
			    [Number], 
			    [Code],
			    [Title],
			    [OrderIndex],
			    [IsObsolete],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [OrgId],
			    [HouseGroupId],
			    ColorCode
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rNumber,
			    @rCode,
			    @rTitle,
			    @rOrderIndex,
			    @rIsObsolete,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @rOrgId,
			    @rHouseGroupId,
			    @rColorCode
			   )
			   SELECT 1 AS RESULT
	 END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sActivity].[tHouseMaster]
	    SET
			  [Number] = @rNumber,
	          [Code] = @rCode,
	          [Title] = @rTitle,
	          [OrderIndex] = @rOrderIndex,
              [IsObsolete] = @rIsObsolete,                          
              [UpdatedUserId] = @rCreatedUserId,
              [UpdatedDateTime] = sCommon.fGetDate(),
              [HouseGroupId] = @rHouseGroupId,
              ColorCode = @rColorCode         
	      WHERE Id = @rId 	
	      SELECT 11 AS RESULT
	 END  
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pHouseMasterGet]
          
		@rId int,
		@rCode nvarchar(50),
		@rTitle nvarchar(100),
		@rOrgId smallint,
		@rHouseGroupId int
AS
SET NOCOUNT ON

		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN

	SELECT 
		
		HM.Id, 
		ISNULL(HM.Number,0)AS Number,
		HM.Code,
		HM.Title,
		ISNULL(HM.OrderIndex,0) AS OrderIndex,
		HM.IsObsolete,
		ISNULL(HM.HouseGroupId,0) AS HouseGroupId,
		ISNULL(HGM.Title,'') AS HouseGroupName,
		ISNULL(HM.ColorCode,'#0066FF') AS ColorCode
		
	FROM
	
		sActivity.tHouseMaster HM
		LEFT JOIN sActivity.tHouseGroupMaster HGM 
			ON HM.HouseGroupId = HGM.Id
	
	WHERE 
		((HM.Id = @rId) OR (@rId = 0))
		AND ((HM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
		AND ((HM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND (HM.OrgId = @rOrgId)
		AND ((HM.HouseGroupId = @rHouseGroupId) OR (@rHouseGroupId = 0))
		ORDER BY  HM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pImmunizationChartAdd]
	 
            @rId int
           ,@rTitle nvarchar(150)
           ,@rDisease nvarchar(150)
           ,@rFromAge int
           ,@rToAge int
           ,@rDurationUnitId tinyint
           ,@rRemark nvarchar(150)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint 
           ,@rOrgGroupId int          
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN 
 
 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sActivity.tImmunizationChart', 0, 1, 1,@outNextNumber = @lNextNumber output
    --EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sActivity.tImmunizationChart',@lNextNumber = @lNextNumber output
	
	INSERT INTO sActivity.tImmunizationChart
           (
            [Id]
           ,[Title]
           ,[Disease]
           ,[FromAge]
           ,[ToAge]
           ,[DurationUnitId]
           ,[Remark]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,OrgGroupId
           
           )
     VALUES
           (
            @lNextNumber 
           ,@rTitle
           ,@rDisease
           ,@rFromAge
           ,@rToAge
           ,@rDurationUnitId
           ,@rRemark
           ,@rIsObsolete
           ,@rCreatedUserId
           ,scommon.fgetdate()
           ,@rCreatedUserId
           ,scommon.fgetdate()
           ,@rOrgGroupId
           )
           
		  
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN 
	      SET @lNextNumber  = @rId
			 UPDATE [sActivity].[tImmunizationChart]
			 SET 
			   [Title] = @rTitle
			  ,[Disease] = @rDisease
			  ,[FromAge] = @rFromAge
			  ,[ToAge] = @rToAge
			  ,[DurationUnitId] = @rDurationUnitId
			  ,[Remark] = @rRemark
			  ,[IsObsolete] = @rIsObsolete  
			  ,[UpdatedUserId] = @rCreatedUserId
			  ,[UpdatedDateTime] = sCommon.fGetDate()
			  --,[OrgId] = @rOrgId
	      WHERE Id = @rId	      
		  --COMMIT TRANSACTION
	 END  	
		
		 SELECT @lNextNumber AS Result

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pImmunizationChartGet] 
           
           @rOrgGroupId int          
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
	  SELECT 
	       [Id]
		  ,[Title]
		  ,[Disease]
		  ,[FromAge]
		  ,[ToAge]
		  ,[DurationUnitId]
		  ,[Remark]
		  ,IsObsolete 
		  
	FROM  [sActivity].[tImmunizationChart]  
	Where OrgGroupId = @rOrgGroupId
	
	ORDER BY DurationUnitId,ToAge ASC

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pImmunizationChartRemove]

	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
     DECLARE @1IsRefferd bit
	BEGIN TRY
		BEGIN TRANSACTION	
		
		   SET @1IsRefferd = 0;		    
		   Select @1IsRefferd = 1 FROM sActivity.tStudentImmunizationStatus Where ImmunizationChartId = @rId
		   
		   IF(@1IsRefferd=0)
		    BEGIN
		       DELETE FROM sActivity.tImmunizationChart Where Id = @rId
		       Select 1 As Result
		    END
		    ELSE
		    Select -101 AS Result
		    
		  			
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sActivity].[pImportEvent]
       
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rBatchId int,
	@rCreatedUserId bigint 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lTitle nvarchar(100),
			@lFromDate date,
			@lToDate date,
			@lRemark nvarchar(200),
			@lEventTypeId int,			
			@lIsHoliday bit,
			@lBatchId int	
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 (
	Id bigint identity,
	Title nvarchar(100) ,
	FromDate date ,
	ToDate date ,
	Remark nvarchar(1000),
	EventTypeId int ,	
	IsHoliday bit,
	BatchId int)
	
	INSERT INTO #tTable1(
		Title,
		FromDate,
		ToDate,
		Remark, 
		EventTypeId,
		IsHoliday,
		BatchId )
	SELECT
		 T.c.value('@Title','nvarchar(100)') AS Title,
		 T.c.value('@FromDate','date') AS FromDate,
		 T.c.value('@ToDate','date') AS ToDate,
		 T.c.value('@Remark','nvarchar(1000)') AS Remark,
		 T.c.value('@EventTypeId','int') AS EventTypeId,
		-- T.c.value('@IsHoliday','bit') AS IsHoliday,
		 CASE WHEN (T.c.value('@IsHoliday','bit') = 1) THEN  'True' ELSE 'False' END AS IsHoliday,
		 @rBatchId
		 
	FROM @loXML.nodes('/Table/ImportEvent')T(c)
	
	
	
SELECT @lCount =  COUNT(Id) FROM #tTable1
	
	
WHILE @lCount > 0 

BEGIN				
	
SELECT	
		@lTitle = Title,
		@lFromDate = FromDate,
		@lToDate = ToDate,
		@lRemark = Remark,
		@lEventTypeId = EventTypeId,
		@lIsHoliday = IsHoliday,
		@lBatchId = BatchId
			
											 	 
FROM #tTable1 WHERE Id = @lCount 

	--IF EXISTS(SELECT Id FROM sActivity.tEventSchedule WHERE Title=@lTitle AND BatchId = @rBatchId)
	--	BEGIN
	--		UPDATE sActivity.tEventSchedule
	--		SET	
	--			Title = @lTitle,				
	--			FromDate = @lFromDate,			
	--			ToDate = @lToDate,
	--			Remark = @lRemark,
	--			EventTypeId = @lEventTypeId,
	--			IsHoliday = @lIsHoliday 
	--		WHERE 
	--			Title=@lTitle AND BatchId = @rBatchId			
	--	END
	--	ELSE
	--	BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventSchedule', 0, 101, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sActivity.tEventSchedule
				(
					Id,		
					Title,
					FromDate,
					ToDate,
					Remark,
					EventTypeId,
					IsHoliday,
					BatchId,
					IsCommonForAll,
					IsEnrollment,
					CreatedUserId,
					CreatedDateTime
				)
			VALUES
				(
					@lNextNumber,
					@lTitle,					
					@lFromDate,
					@lToDate,
					@lRemark,
					@lEventTypeId,
					@lIsHoliday,
					@rBatchId,
					0,
					0,
					@rCreatedUserId,
					sCommon.fGetDate()
				)
				
			    DECLARE @lNextNumber1 BIGINT
			    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventAssign', 0, 1, 1,@outNextNumber = @lNextNumber1 output	
				
				DECLARE @TempDivision TABLE (Id int,SourceTypeId int)
				DELETE FROM  @TempDivision 
				INSERT INTO @TempDivision
				Select Id AS DivisionId,2005 from sSetup.tDivisionMaster Where OrgId = @rOrgId
				UNION ALL
				Select Id AS DepartmentId,2004 from sSetup.tDepartmentMaster Where OrgId = @rOrgId
							
				INSERT INTO sActivity.tEventAssign
				SELECT 								
				@lNextNumber1+ ROW_NUMBER() OVER(ORDER BY @lNextNumber,Id,SourceTypeId),
				@lNextNumber,
				SourceTypeId,
				Id
				FROM @TempDivision
				
				

				DECLARE @lCount1 INT
				
				SELECT @lCount1 = COUNT(1) FROM  @TempDivision
				SET @lNextNumber1  = @lCount1 + @lNextNumber1 
				
				EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sActivity.tEventAssign', @rCurrentNumber = @lNextNumber1 

				
		--END
		
		SET @lCount = @lCount - 1
	SELECT 1 AS Result, '' AS ResultDetail				

 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pMyActivityGet]
	 
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN 
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT
				ISNULL(A.Id,0) as ActivityId,
				A.Title,
				A.ActivityTypeId,
				ATM.Title AS ActivityType,
				A.FromDate,
				A.ToDate,
				A.Remark,
				A.IsGroup,
				AP.Remark AS UserWiseRemark
		FROM 
				sActivity.tActivity A 
				INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=@rSourceId AND SA.BatchId = @rBatchId
			    INNER JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceTypeId=2003
			
		WHERE 
				AP.SourceTypeId = 2003 AND AP.SourceId = @rSourceId  AND A.BatchId=@rBatchId
		--	(A.Id IN(SELECT ActivityId FROM sActivity.tActivityParticipant WHERE SourceTypeId=2003) AND 
		--		SourceId=(SELECT AcademicId FROM sStudent.vStudentAcademic WHERE StudentId=@rSourceId 
		--			AND OrgId=@rOrgId AND BatchId=@rBatchId))
		--AND (A.BatchId=@rBatchId)
		ORDER BY A.FromDate DESC
	END
	ELSE
	BEGIN
		SELECT 
				ISNULL(A.Id,0) as ActivityId,
				A.Title,
				A.ActivityTypeId,
				ATM.Title AS ActivityType,
				A.FromDate,
				A.ToDate,
				A.Remark,
				A.IsGroup,
				AP.Remark AS UserWiseRemark
		FROM 
				sActivity.tActivity A 
				INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
			INNER JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceId=@rSourceId AND AP.SourceTypeId=95
		--WHERE 
	  
		--	(A.Id IN(SELECT ActivityId FROM sActivity.tActivityParticipant WHERE SourceTypeId=95 AND 
		--		SourceId=(SELECT Id FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)))
		--AND (A.BatchId=@rBatchId)
		ORDER BY A.FromDate DESC
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pMyActivityViewGet]
	 
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN
declare @lActivityGrid nvarchar(max)='' 
	IF(@rSourceTypeId=2003)
	BEGIN
	
		SELECT
				
				@lActivityGrid = @lActivityGrid + '<tr>
				    <td align="left" scope="col">' + convert(varchar,isnull(A.FromDate,''),103) + '</td>
					<td align="left" scope="col">' + convert(varchar,isnull(A.ToDate,''),103) + '</td>
					<td align="left" scope="col">' + isnull (A.Title,'')  + '</td>
					<td align="left" scope="col">' + isnull( A.Remark,'')+ '</td>
					<td align="left" scope="col">' + isnull( AP.Remark,'')+ '</td>
					<tr>'
				
		FROM 
				sActivity.tActivity A 
				INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=@rSourceId AND SA.BatchId = @rBatchId
			    INNER JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceTypeId=2003
			
		WHERE 
				AP.SourceTypeId = 2003 AND AP.SourceId = @rSourceId  AND A.BatchId=@rBatchId
		--	(A.Id IN(SELECT ActivityId FROM sActivity.tActivityParticipant WHERE SourceTypeId=2003) AND 
		--		SourceId=(SELECT AcademicId FROM sStudent.vStudentAcademic WHERE StudentId=@rSourceId 
		--			AND OrgId=@rOrgId AND BatchId=@rBatchId))
		--AND (A.BatchId=@rBatchId)
	END
	ELSE
	BEGIN
		SELECT 
				@lActivityGrid = @lActivityGrid + '<tr>
				    <td align="left" scope="col">' + convert(varchar,isnull(A.FromDate,''),103) + '</td>
					<td align="left" scope="col">' + convert(varchar,isnull(A.ToDate,''),103) + '</td>
					<td align="left" scope="col">' + isnull (A.Title,'')  + '</td>
					<td align="left" scope="col">' + isnull( A.Remark,'')+ '</td>
					<td align="left" scope="col">' + isnull( AP.Remark,'')+ '</td>
					<tr>'
				
		FROM 
				sActivity.tActivity A 
				INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
			INNER JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceId=@rSourceId AND AP.SourceTypeId=95
		--WHERE 
	  
		--	(A.Id IN(SELECT ActivityId FROM sActivity.tActivityParticipant WHERE SourceTypeId=95 AND 
		--		SourceId=(SELECT Id FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)))
		--AND (A.BatchId=@rBatchId)
		
		
	END
	select isnull(@lActivityGrid,'') as activitygrid
END

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

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

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

		AND (ES.BatchId=@rBatchId)
	   AND ((Convert(date,ES.FromDate)<=@rFromDate) OR ISNULL(@rFromDate,'')='')
		AND ((Convert(date,ES.Todate)>=@rTodate) OR ISNULL(@rTodate,'')='')
		AND (ES.EventTypeId = @rEventTypeId OR @rEventTypeId = 0)
		--AND (ES.Id > @rSyncedEventScheduleId OR @rSyncedEventScheduleId = 0)
		ORDER BY ES.FromDate DESC
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pPlacementAdd]
	 
	@rId int,
	@rBatchId int,
	@rEventDate date,
	@rTitle nvarchar(100),
	@rPlacementCompanyId bigint,
	@rNoOfVacancies int,
	@rElibigleCriteriaRemark nvarchar(1000),
	@rJobDescriptionRemark nvarchar(1000),
	@rRemark nvarchar(100),
	@rTrainingRemark nvarchar(500),
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rOrgId int,
	@rPackageToOffer Decimal(12,2)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
IF(@rId = 0)	
BEGIN
	If Exists(select Id from sActivity.tPlacement where Title=@rTitle and BatchId=@rBatchId)
	BEGIN
		select -103 as Result
		RETURN
	END 
END
ELSE
BEGIN
	If  Exists(select Id from sActivity.tPlacement where Title=@rTitle  AND Id<>@rId and  BatchId=@rBatchId)
	BEGIN
		select -103 as Result
		RETURN
	END
	
END
	
 BEGIN TRANSACTION	
 DECLARE @lNextNumber BIGINT 
 
 IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tPlacement', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sActivity.tPlacement
		(
			Id,
			BatchId,
			EventDate,
			Title,
			Remark,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			TrainingRemark,
			PlacementCompanyId,
			NoOfVacancies,
			ElibigleCriteriaRemark,
			JobDescriptionRemark,
			PackageToOffer
		)
	VALUES
		(
			@lNextNumber,
			@rBatchId,
			@rEventDate,
			@rTitle,
			@rRemark,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rTrainingRemark,
			@rPlacementCompanyId,
			@rNoOfVacancies,
			@rElibigleCriteriaRemark,
			@rJobDescriptionRemark,
			@rPackageToOffer   
			
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sActivity.tPlacement
	    SET
		    EventDate=@rEventDate,
			Title=@rTitle,
			Remark=@rRemark,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			TrainingRemark=@rTrainingRemark,
			PlacementCompanyId=@rPlacementCompanyId,
			NoOfVacancies=@rNoOfVacancies,
			ElibigleCriteriaRemark=@rElibigleCriteriaRemark,
			JobDescriptionRemark=@rJobDescriptionRemark,
			PackageToOffer=@rPackageToOffer

	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pPlacementCompanyMasterAdd]
	    @rId int,
		@rOrgGroupId smallint,
        @rTitle nvarchar(100),
		@rCode nvarchar(100),
		@rCompanyDetaill nvarchar(1000),
		@rTrainingRemark nvarchar(500),
		@rElibigleCriteriaRemark nvarchar(500),
		@rCompnayWebsite nvarchar(200),
		@rCompnayContactNo nvarchar(100),
		@rIsObsolete bit =null,
        @rCreatedUserId bigint
        
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		

		If Exists(select Id from [sActivity].[tPlacementCompanyMaster] where code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
	
		If Exists(select Id from [sActivity].[tPlacementCompanyMaster] where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		

		If  Exists(select Id from [sActivity].[tPlacementCompanyMaster] where code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End

		If  Exists(select Id from [sActivity].[tPlacementCompanyMaster] where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sActivity.tPlacementCompanyMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sActivity.tPlacementCompanyMaster
		(
			Id,
			OrgGroupId,
			Code,
			Title,
			CompanyDetaill,
			TrainingRemark,
			ElibigleCriteriaRemark,
			CompnayWebsite,
			CompnayContactNo,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rCode,
			@rTitle,
			@rCompanyDetaill,
			@rTrainingRemark,
			@rElibigleCriteriaRemark,
			@rCompnayWebsite,
			@rCompnayContactNo,
			0,
		    @rCreatedUserId,
			sCommon.fGetDate()
		
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sActivity.tPlacementCompanyMaster
	    SET
			OrgGroupId=@rOrgGroupId,
			Code=@rCode,
			Title=@rTitle,
			CompanyDetaill=@rCompanyDetaill,
			TrainingRemark=@rTrainingRemark,
			ElibigleCriteriaRemark=@rElibigleCriteriaRemark,
			CompnayWebsite=@rCompnayWebsite,
			CompnayContactNo=@rCompnayContactNo,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--EXEC [sActivity].[pPlacementCompanyMasterGet] 100100003,1001,'','PCM003'

CREATE OR ALTER PROCEDURE [sActivity].[pPlacementCompanyMasterGet]

	 @rId int,
	 @rOrgGroupId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
	   [Id]
      ,[OrgGroupId]
      ,[Code]
      ,[Title]
      ,[CompanyDetaill]
      ,[TrainingRemark]
      ,[ElibigleCriteriaRemark]
      ,[CompnayWebsite]
      ,[CompnayContactNo]
      ,case IsObsolete when 0 then 'N' else 'Y' end as InActive 
	  ,IsObsolete
      ,[CreatedUserId]
      ,[CreatedDateTime]
      ,[UpdatedUserId]
      ,[UpdatedDateTime]
  FROM [sActivity].[tPlacementCompanyMaster] as PT
		    
	
		
	WHERE 
		(PT.OrgGroupId = @rOrgGroupId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((PT.Code like @rCode) OR (ISNULL(@rCode,'') = ''))

    ORDER BY PT.CreatedDateTime DESC


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pPlacementGet]
	 
	 @rId int = 0,
	 @rBatchId int,
	 @rTitle nvarchar(100),
	 @rEventDate datetime = null, 
	 @rIsSearch bit = 1,
	 @rPlacementCompanyId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT p.Id 
      ,p.EventDate
      ,p.Title
      ,ISNULL(CMP.Title,'') as   Company
      ,p.Remark
      ,p.IsObsolete
	  ,ISNULL(p.NoOfVacancies,0)NoOfVacancies
	  ,p.TrainingRemark
	  ,p.PlacementCompanyId
	  ,p.ElibigleCriteriaRemark
	  ,p.JobDescriptionRemark
	  ,ISNULL(p.PackageToOffer,0.00) as PackageToOffer
   
  FROM sActivity.tPlacement as p
  LEFT JOIN sActivity.tPlacementCompanyMaster as CMP on p.PlacementCompanyId = cmp.ID
  
  WHERE 
  
      ((p.Id = @rId) OR (@rId = 0))
    AND ((p.BatchId = @rBatchId) OR (@rBatchId = 0))  
	AND ((p.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((p.EventDate=@rEventDate) OR (ISNULL(@rEventDate,'') = '')) 
	AND ((p.PlacementCompanyId=@rPlacementCompanyId) OR (@rPlacementCompanyId=0))
	AND (CMP.IsObsolete = 0) -- Add for mantis : 0036558
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pPlacementInviteAdd]
@rId int,
@rBatchId int,
@rPlacementId int,
@rAcedamicId bigint,
@rPlacementStatusId int,
@rIsAttended bit,
@rOrgId int,
@rOfferedPackage decimal(18,2) 

WITH EXECUTE AS CALLER
AS


BEGIN
	SET NOCOUNT ON
	BEGIN TRY

		BEGIN TRANSACTION	

			DECLARE @lNextNumber BIGINT 
 
			DECLARE @Count INT

			SELECT @Count= COUNT(0) FROM sActivity.tPlacementInvite where PlacementId = @rPlacementId AND  AcedamicId = @rAcedamicId	AND BatchId = @rBatchId   
			SET @Count=ISNULL(@Count,0)
 
			IF(@rId = 0 AND @Count=0)	
				BEGIN
					EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tPlacementInvite', 0, 1, 1,@outNextNumber = @lNextNumber output
					INSERT INTO sActivity.tPlacementInvite
					(
						Id,
						BatchId,
						PlacementId,
						AcedamicId,
						PlacementStatusId,		 
						IsAttended,
						OfferedPackage 
					)
					VALUES
					(
						@lNextNumber,
						@rBatchId,
						@rPlacementId,
						@rAcedamicId,
						@rPlacementStatusId,
						@rIsAttended,
						@rOfferedPackage 
					)
				END	 
			ELSE
				BEGIN
					SET @lNextNumber = @rId
					UPDATE  sActivity.tPlacementInvite
					SET
						PlacementStatusId=@rPlacementStatusId,
						IsAttended=@rIsAttended,
						OfferedPackage=@rOfferedPackage
					WHERE PlacementId = @rPlacementId AND  AcedamicId = @rAcedamicId	AND BatchId = @rBatchId   
				END 
							
					SELECT 1 AS Result
							
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pPlacementInviteRemove]
	  
	  @rBatchId [int],	
	  @rPlacementId int,  
	  @rAcedamicId bigint
	  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 
	 DELETE FROM sActivity.tPlacementInvite	    
	  WHERE BatchId = @rBatchId AND PlacementId = @rPlacementId AND AcedamicId = @rAcedamicId
	  
	  Select 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--EXEC [sActivity].[pPlacementInviteStudentExportGet] ''

CREATE OR ALTER PROCEDURE [sActivity].[pPlacementInviteStudentExportGet]
	@rStudentId nvarchar(MAX),
	@rBatchId int,
	@rClassId int,
	@rDivisionId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

			DECLARE @StudentIdTable TABLE(StudentId bigint)

			IF (@rStudentId IS NOT NULL AND @rStudentId <> '')
				BEGIN
					INSERT INTO @StudentIdTable 
					SELECT item FROM Scommon.fnSplit(@rStudentId,',')
				END

			SELECT DISTINCT 
				s.StudentId
				,s.Code
				,s.Name
				,b.ClassName +'-'+ d.Title as ClassName
				,d.Title as 'DivisionName'
				,s.RollNo
				--,c.[AdmissionNumber]
				--,c.[IsTransfer]
			   --,c.[TransferFrom]
			   --,c.[PassingYear]
			   --,c.[IsTFWS]
			   --,c.[IsCertificateHolder]
			   --,c.[CertificateName] --Commented for mantis 35404 : by Nilesh
			   ,SA.[CertificateName] --Added for mantis 35404 : by Nilesh
			   ,c.[SSCBoard]
			   ,c.[SSCSchool]
			   ,c.[SSCPassingYear]
			   ,c.[SSCObtainMarks]
			   ,c.[SSCOutOfMarks]
			   ,c.[SSCPercentage]
			   ,c.[SSCMathMarks]
			   ,c.[SSCMathOutOfMarks]
			   ,c.[HSCBoard]
			   ,c.[HSCSchool]
			   ,c.[HSCPassingYear]
			   ,c.[HSCObtainMarks]
			   ,c.[HSCOutOfMarks]
			   ,c.[HSCPercentage]
			   ,c.[HSCPhysicsMarks]
			   ,c.[HSCPhysicsOutOfMarks]
			   ,c.[HSCChemistryMarks]
			   ,c.[HSCChemistryOutOfMarks]
			   ,c.[HSCMathMarks]
			   ,c.[HSCMathOutOfMarks]
			   ,c.[HSCBiologyMarks]
			   ,c.[HSCBiologyOutOfMarks]
			   ,c.[PCMMarks]
			   ,c.[PCBMarks]
			   ,c.[JEERollNo]
			   ,c.[JEEMeritNo]
			   ,c.[JEEMeritMarks]
			   ,c.[JEEOutOfMarks]
			   ,c.[DiplomaBoard]
			   ,c.[DiplomaCollege]
			   ,c.[DiplomaPassingYear]
			   ,c.[DiplomaObtainMarks]
			   ,c.[DiplomaOutOfMarks]
			   ,c.[DiplomaPercentage]
			   --,c.[ApplicationNo]
			   --,c.[AdmissionRound]
			   --,c.[MaritalStatusId]


			FROM sStudent.vStudentName  as s
				LEFT JOIN sStudent.tCollegeDetail as c on s.StudentId=c.StudentId
				LEFT JOIN sSetup.vBatchClass as b on b.ClassId=s.ClassId and b.BatchId=s.BatchId  and s.OrgId=b.OrgId	
				LEFT JOIN sSetup.tDivisionMaster as d on d.Id=s.DivisionId  and d.OrgId=s.OrgId and d.ClassId=s.ClassId
				LEFT JOIN [sStudent].[tStudentAdmission] AS SA ON SA.StudentId = s.StudentId --Added for mantis 35404 : by Nilesh
			WHERE (s.ClassId = @rClassId) 
				AND ((s.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
				AND (s.BatchId = @rBatchId)
				and s.StudentId in (SELECt StudentId FROM @StudentIdTable)

    --ORDER BY 1 DESC --Commented for mantis 35404 : by Nilesh
	ORDER BY s.Code ASC--Added for mantis 35404 : by Nilesh
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec sActivity.pPlacementInviteStudentGet @rBatchId=100100114,@rPlacementId=N'100100024',@rIsInvited=1,@rClassId=100100001,@rDivisionId=-1
--go
CREATE OR ALTER PROCEDURE [sActivity].[pPlacementInviteStudentGet]
	 
	 @rBatchId int,
	 @rPlacementId int,
	 @rIsInvited bit,
	 @rClassId int,
	 @rDivisionId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF(@rIsInvited=0)
	BEGIN 
Select SN.AcademicId,
	   SN.StudentId,
	   SN.Code,
	   SN.Name
	 	,b.ClassName +'-'+ d.Title as ClassName
		,d.Title as 'DivisionName'
		,SN.RollNo
	   from sStudent.vStudentName SN
	   LEFT JOIN sSetup.vBatchClass as b on b.ClassId=SN.ClassId and b.BatchId=SN.BatchId  and SN.OrgId=b.OrgId	
	   LEFT JOIN sSetup.tDivisionMaster as d on d.Id=SN.DivisionId  and d.OrgId=SN.OrgId and d.ClassId=SN.ClassId
   
	WHERE (SN.ClassId = @rClassId) 
	AND ((SN.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND (SN.BatchId = @rBatchId)
	AND (SN.AcademicId NOT IN (SELECT AcedamicId FROM sActivity.tPlacementInvite WHERE BatchId = @rBatchId AND PlacementId = @rPlacementId))	
	ORDER BY CAST (SN.Code as nvarchar )
	
	
 END
	ELSE
BEGIN

Select distinct SN.AcademicId,
	   SN.StudentId,
	   CAST (SN.Code as nvarchar ) Code,
	   SN.Name
	 	,b.ClassName +'-'+ d.Title as ClassName
		,d.Title as 'DivisionName'
		,SN.RollNo
	   from sStudent.vStudentName SN
	   INNER JOIN sActivity.tPlacementInvite PS ON PS.AcedamicId = SN.AcademicId 
	   AND SN.BatchId = PS.BatchId
	   LEFT JOIN sSetup.vBatchClass as b on b.ClassId=SN.ClassId and b.BatchId=SN.BatchId  and SN.OrgId=b.OrgId	
	   LEFT JOIN sSetup.tDivisionMaster as d on d.Id=SN.DivisionId  and d.OrgId=SN.OrgId and d.ClassId=SN.ClassId
   
   
WHERE (PS.BatchId = @rBatchId)
		AND (PS.PlacementId = @rPlacementId) 
		and  (SN.ClassId = @rClassId) 
	ORDER BY CAST (SN.Code as nvarchar ) 
END
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pPlacementInviteStudentGetNew]
	@rBatchId int,
	@rPlacementId int,
	@rIsInvited bit,
	@rClassId int,
	@rDivisionId int,
	@rSSCMathMarksFrom Decimal(10,2)=null,
	@rSSCMathMarksTo Decimal(10,2)=null,
	@rSSCObtainMarksFrom Decimal(10,2)=null,
	@rSSCObtainMarksTo Decimal(10,2)=null,
	@rSSCPercentageFrom Decimal(10,2)=null,
	@rSSCPercentageTo Decimal(10,2)=null,
	@rHSCChemistryMarksFrom Decimal(10,2)=null,
	@rHSCChemistryMarksTo Decimal(10,2)=null,
	@rHSCMathMarksFrom Decimal(10,2)=null,
	@rHSCMathMarksTo Decimal(10,2)=null,
	@rHSCBiologyMarksFrom Decimal(10,2)=null,
	@rHSCBiologyMarksTo Decimal(10,2)=null,
	@rHSCPhysicsMarksFrom Decimal(10,2)=null,
	@rHSCPhysicsMarksTo Decimal(10,2)=null,
	@rHSCPercentageFrom Decimal(10,2)=null,
	@rHSCPercentageTo Decimal(10,2)=null,
	@rHSCObtainMarksFrom Decimal(10,2)=null,
	@rHSCObtainMarksTo Decimal(10,2)=null,
	@rDiplomaObtainMarksFrom Decimal(10,2)=null,
	@rDiplomaObtainMarksTo Decimal(10,2)=null,
	@rDiplomaPercentageFrom Decimal(10,2)=null,
	@rDiplomaPercentageTo Decimal(10,2)=null,
	@rPCMMarksFrom Decimal(10,2)=null,
	@rPCMMarksTo Decimal(10,2)=null,
	@rPCBMarksFrom Decimal(10,2)=null,
	@rPCBMarksTo Decimal(10,2)=null,
	@rJEEMeritMarksFrom Decimal(10,2)=null,
	@rJEEMeritMarksTo Decimal(10,2)=null
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF(@rIsInvited=0)
		BEGIN 
			SELECT s.AcademicId
			,s.StudentId
			,s.Code
			,s.Name
			,b.ClassName +'-'+ d.Title as ClassName
			,d.Title as 'DivisionName'
			,s.RollNo
			FROM sStudent.vStudentName  as s
				LEFT JOIN sStudent.tCollegeDetail as c on s.StudentId=c.StudentId
				LEFT JOIN sSetup.vBatchClass as b on b.ClassId=s.ClassId and b.BatchId=s.BatchId  and s.OrgId=b.OrgId	
				LEFT JOIN sSetup.tDivisionMaster as d on d.Id=s.DivisionId  and d.OrgId=s.OrgId and d.ClassId=s.ClassId
			WHERE (s.ClassId = @rClassId) 
				AND ((s.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
				AND (s.BatchId = @rBatchId)
				AND (s.AcademicId NOT IN (SELECT AcedamicId FROM sActivity.tPlacementInvite WHERE BatchId = @rBatchId AND PlacementId = @rPlacementId))	
				AND (ISNULL(c.SSCMathMarks,0)        >= ISNULL(@rSSCMathMarksFrom,ISNULL(c.SSCMathMarks,0))               OR @rSSCMathMarksFrom=0)
				AND (ISNULL(c.SSCMathMarks,0)        <= ISNULL(@rSSCMathMarksTo,ISNULL(c.SSCMathMarks,0))                 OR @rSSCMathMarksTo=0)
				AND (ISNULL(c.SSCObtainMarks,0)      >= ISNULL(@rSSCObtainMarksFrom,ISNULL(c.SSCObtainMarks,0))           OR @rSSCObtainMarksFrom=0)
				AND (ISNULL(c.SSCObtainMarks,0)      <= ISNULL(@rSSCObtainMarksTo,ISNULL(c.SSCObtainMarks,0))             OR @rSSCObtainMarksTo=0)
				AND (ISNULL(c.SSCPercentage,0)       >= ISNULL(@rSSCPercentageFrom,ISNULL(c.SSCPercentage,0))             OR @rSSCPercentageFrom=0)
				AND (ISNULL(c.SSCPercentage,0)       <= ISNULL(@rSSCObtainMarksTo,ISNULL(c.SSCPercentage,0))              OR @rSSCObtainMarksTo=0)
				AND (ISNULL(c.HSCChemistryMarks,0)   >= ISNULL(@rHSCChemistryMarksFrom,ISNULL(c.HSCChemistryMarks,0))     OR @rHSCChemistryMarksFrom=0)
				AND (ISNULL(c.HSCChemistryMarks,0)   <= ISNULL(@rHSCChemistryMarksTo,ISNULL(c.HSCChemistryMarks,0))		  OR @rHSCChemistryMarksTo=0)
				AND (ISNULL(c.HSCMathMarks,0)        >= ISNULL(@rHSCMathMarksFrom,ISNULL(c.HSCMathMarks,0))				  OR @rHSCMathMarksFrom=0)
				AND (ISNULL(c.HSCMathMarks,0)        <= ISNULL(@rHSCMathMarksTo,ISNULL(c.HSCMathMarks,0))				  OR @rHSCMathMarksTo=0)
				AND (ISNULL(c.HSCBiologyMarks,0)     >= ISNULL(@rHSCBiologyMarksFrom,ISNULL(c.HSCBiologyMarks,0))		  OR @rHSCBiologyMarksFrom=0)
				AND (ISNULL(c.HSCBiologyMarks,0)     <= ISNULL(@rHSCBiologyMarksTo,ISNULL(c.HSCBiologyMarks,0))		      OR @rHSCBiologyMarksTo=0)
				AND (ISNULL(c.HSCPhysicsMarks,0)     >= ISNULL(@rHSCPhysicsMarksFrom,ISNULL(c.HSCPhysicsMarks,0))		  OR @rHSCPhysicsMarksFrom=0)
				AND (ISNULL(c.HSCPhysicsMarks,0)     <= ISNULL(@rHSCPhysicsMarksTo,ISNULL(c.HSCPhysicsMarks,0))		    OR @rHSCPhysicsMarksTo=0)
				AND (ISNULL(c.HSCObtainMarks,0)      >= ISNULL(@rHSCObtainMarksFrom,ISNULL(c.HSCObtainMarks,0))			  OR @rHSCObtainMarksFrom=0)
				AND (ISNULL(c.HSCObtainMarks,0)      <= ISNULL(@rHSCObtainMarksTo,ISNULL(c.HSCObtainMarks,0))			  OR @rHSCObtainMarksTo=0)
				AND (ISNULL(c.HSCPercentage,0)       >= ISNULL(@rHSCPercentageFrom,ISNULL(c.HSCPercentage,0))			  OR @rHSCPercentageFrom=0)
				AND (ISNULL(c.HSCPercentage,0)       <= ISNULL(@rHSCPercentageTo,ISNULL(c.HSCPercentage,0))				  OR @rHSCPercentageTo=0)
				AND (ISNULL(c.DiplomaObtainMarks,0)  >= ISNULL(@rDiplomaObtainMarksFrom,ISNULL(c.DiplomaObtainMarks,0))   OR @rDiplomaObtainMarksFrom=0)
				AND (ISNULL(c.DiplomaObtainMarks,0)  <= ISNULL(@rDiplomaObtainMarksTo,ISNULL(c.DiplomaObtainMarks,0))     OR @rDiplomaObtainMarksTo=0)
				AND (ISNULL(c.DiplomaPercentage,0)   >= ISNULL(@rDiplomaPercentageFrom,ISNULL(c.DiplomaPercentage,0))     OR @rDiplomaPercentageFrom=0)
				AND (ISNULL(c.DiplomaPercentage,0)   <= ISNULL(@rDiplomaPercentageTo,ISNULL(c.DiplomaPercentage,0))       OR @rDiplomaPercentageTo=0)
				AND (ISNULL(c.PCMMarks,0)            >= ISNULL(@rPCMMarksFrom,ISNULL(c.PCMMarks,0))                       OR @rPCMMarksFrom=0)
				AND (ISNULL(c.PCMMarks,0)            <= ISNULL(@rPCMMarksTo,ISNULL(c.PCMMarks,0))                         OR @rPCMMarksTo=0)
				AND (ISNULL(c.PCBMarks,0)            >= ISNULL(@rPCBMarksFrom,ISNULL(c.PCBMarks,0))                       OR @rPCBMarksFrom=0)
				AND (ISNULL(c.PCBMarks,0)            <= ISNULL(@rPCBMarksTo,ISNULL(c.PCBMarks,0))                         OR @rPCBMarksTo=0)
				AND (ISNULL(c.JEEMeritMarks,0)       >= ISNULL(@rJEEMeritMarksFrom,ISNULL(c.JEEMeritMarks,0))             OR @rJEEMeritMarksFrom=0)
				AND (ISNULL(c.JEEMeritMarks,0)       <= ISNULL(@rJEEMeritMarksTo,ISNULL(c.JEEMeritMarks,0))               OR @rJEEMeritMarksTo=0)
			ORDER BY s.Code
		END
	ELSE
	
		BEGIN
			Select SN.AcademicId
			,SN.StudentId
			,SN.Code
			,SN.Name
			,b.ClassName +'-'+ d.Title as ClassName
			,d.Title as 'DivisionName'
			,SN.RollNo
			FROM sStudent.vStudentName SN
				INNER JOIN sActivity.tPlacementInvite PS ON PS.AcedamicId = SN.AcademicId 
				AND SN.BatchId = PS.BatchId
				LEFT JOIN sSetup.vBatchClass as b on b.ClassId=SN.ClassId AND b.BatchId=SN.BatchId  AND SN.OrgId=b.OrgId	
				LEFT JOIN sSetup.tDivisionMaster as d on d.Id=SN.DivisionId  AND d.OrgId=SN.OrgId AND d.ClassId=SN.ClassId
			WHERE (PS.BatchId = @rBatchId)
				AND (PS.PlacementId = @rPlacementId) 
				and  (SN.ClassId = @rClassId) 
			ORDER BY SN.Code
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EXEC [sActivity].[pPlacementStudentGet] 100100114,100100008,null,null

CREATE OR ALTER PROCEDURE [sActivity].[pPlacementStudentGet]	 
	 
	 @rBatchId int,
	 @rPlacementId int,
	 @rPlacementStatusId int=null,
	 @rIsAttended bit=null
 	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	
	Select 
	   P.Id,
	   SA.AcademicId,
	   SA.Name,
	   SA.Code,
	   (SA.ClassName + '-' + SA.DivisionName) AS Class,
	   P.IsAttended,
	   P.PlacementStatusId,
	   P.PlacementId,
	   P.BatchId,
	   SA.DepartmentName,
	   isnull(P.OfferedPackage,0)OfferedPackage
	   from sStudent.vStudentAcademic SA
	   INNER JOIN sActivity.tPlacementInvite P ON P.AcedamicId = SA.AcademicId 
	   AND P.BatchId = SA.BatchId
	  

WHERE SA.BatchId = @rBatchId AND P.PlacementId = @rPlacementId
	AND P.PlacementStatusId=ISNULL(@rPlacementStatusId,P.PlacementStatusId)
	AND P.IsAttended=ISNULL(@rIsAttended,P.IsAttended)
ORDER BY SA.NUMBER
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EXEC [sActivity].[pPlacementStudentGetExport] 100100114,100100011,null,null

CREATE OR ALTER PROCEDURE [sActivity].[pPlacementStudentGetExport]	 
	 
	 @rBatchId int,
	 @rPlacementId int,
	 @rPlacementStatusId int=null,
	 @rIsAttended bit=null
 	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	
	Select 
	   SA.Code,
	   SA.Name,
	   (SA.ClassName + '-' + SA.DivisionName) AS Class,
		CASE  P.IsAttended WHEn 1 then 'Yes' else 'No'end  as  Attended,
		sa.DepartmentName,
	   --P.PlacementStatusId,
	   --P.PlacementId,
	   --P.BatchId,
	   --P.Id,
	   --SA.AcademicId,
	   ISNULL(st.Title,'Not Selected') as Status
	   ,ISNULL(OfferedPackage,00) as OfferPackageinLakhsAnnum
	   from sStudent.vStudentAcademic SA
	   INNER JOIN sActivity.tPlacementInvite P ON P.AcedamicId = SA.AcademicId 	   AND P.BatchId = SA.BatchId
	   LEFT JOIN sCommon.tStatusMaster as st  on P.PlacementStatusId=st.Id and  StatusTypeId=110
WHERE SA.BatchId = @rBatchId AND P.PlacementId = @rPlacementId
	AND P.PlacementStatusId=ISNULL(@rPlacementStatusId,P.PlacementStatusId)
	AND P.IsAttended=ISNULL(@rIsAttended,P.IsAttended)
ORDER BY SA.NUMBER
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pPlacementViewGet]
	 
	 @rStudentId bigint,
	 @rBatchId int,
	 @rSourceTypeId int
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
	SELECT PS.AcedamicId,
		   P.EventDate,
	       P.Title,
	      c.Title as Company,
	       P.Remark 
		   from sActivity.tPlacement P
		   INNER JOIN sActivity.tPlacementInvite PS ON PS.PlacementId = P.Id AND P.BatchId = PS.BatchId
		   INNER JOIN sStudent.vStudentName SN ON SN.AcademicId = PS.AcedamicId AND SN.BatchId = P.BatchId
		   LEFT JOIN sActivity.tPlacementCompanyMaster as c on c.id=PlacementCompanyId


WHERE (SN.StudentId = @rStudentId AND @rSourceTypeId = 2003)
	  AND P.BatchId = @rBatchId
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sActivity].[pRptActivityStudentWiseGet]
		   	
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='', 	
           @rClassId int,
           @rDivisionId int,           
           @rOrgId int,
           @rStatusId int,
           @rOrgGroupId int=0,
           @rBatchId int=0
          
AS
SET NOCOUNT ON

BEGIN
IF (@rOrgId = 0)
BEGIN
	SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		SA.AcademicId,
		ISNULL(SA.RollNo,0)AS RollNo,
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,	
		A.Id AS ActivityId,	
		(SELECT STUFF((SELECT ', ' + A1.Title  FROM sActivity.tActivity A1 INNER JOIN  sActivity.tActivityParticipant  AP1 ON A1.Id=AP1.ActivityId WHERE A1.BatchId=SA.BatchId AND  AP1.SourceId=SA.StudentId AND AP1.SourceTypeId=2003 AND A1.BatchId =  SA.BatchId 
		AND ATM.Id = A1.ActivityTypeId
		FOR XML PATH('')), 1, 2, '')) AS ActivityName,
		--A.Title AS ActivityName,
		ATM.Id AS ActivityTypeId,		
		ATM.Title AS ActivityTypeName,
		OM.Id AS OrgId,
		OM.DisplayTitle AS OrgName,
		SA.StudentId,
		ISNULL(CONVERT(VARCHAR(50),A.FromDate,103),'') AS FromDate,
		ISNULL(CONVERT(VARCHAR(50),A.ToDate,103),'') AS ToDate,
		A.Remark AS Remark		 
		
		
	FROM 
		sStudent.vStudentAcademic SA		
		INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=SA.StudentId AND AP.SourceTypeId=2003 
		INNER JOIN sActivity.tActivity A ON A.Id=AP.ActivityId AND A.BatchId=SA.BatchId
		INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id = A.ActivityTypeId	
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id	
	WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)		
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (SA.OrgId=@rOrgId OR @rOrgId=0)
		AND (ISNULL(SA.BatchStatusId,1)=1)
		AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)	
		AND SA.IsActiveBatch = 1
	--Group By SA.Code	
	Order By SA.ClassId
END
ELSE
BEGIN
DECLARE @lOrgGroupBatchId int
Select @lOrgGroupBatchId = OrgGroupBatchId from [sSetup].[tBatchMaster] Where Id = @rBatchId
Select @rBatchId = Id from [sSetup].[tBatchMaster] Where OrgId = @rOrgId AND OrgGroupBatchId = @lOrgGroupBatchId


	SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		SA.AcademicId,
		ISNULL(SA.RollNo,0)AS RollNo,
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,	
		A.Id AS ActivityId,	
		(SELECT STUFF((SELECT ', ' + A1.Title  FROM sActivity.tActivity A1 INNER JOIN  sActivity.tActivityParticipant  AP1 ON A1.Id=AP1.ActivityId WHERE A1.BatchId=SA.BatchId AND  AP1.SourceId=SA.StudentId AND AP1.SourceTypeId=2003 AND A1.BatchId =  SA.BatchId 
		AND ATM.Id = A1.ActivityTypeId
		FOR XML PATH('')), 1, 2, '')) AS ActivityName,
		--A.Title AS ActivityName,
		ATM.Id AS ActivityTypeId,		
		ATM.Title AS ActivityTypeName,
		OM.Id AS OrgId,
		OM.DisplayTitle AS OrgName,
		SA.StudentId,
		ISNULL(CONVERT(VARCHAR(50),A.FromDate,103),'') AS FromDate,
		ISNULL(CONVERT(VARCHAR(50),A.ToDate,103),'') AS ToDate,
		A.Remark AS Remark		 
		
		
	FROM 
		sStudent.vStudentAcademic SA		
		INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=SA.StudentId AND AP.SourceTypeId=2003 
		INNER JOIN sActivity.tActivity A ON A.Id=AP.ActivityId AND A.BatchId=SA.BatchId
		INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id = A.ActivityTypeId	
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id	
	WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)		
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (SA.OrgId=@rOrgId OR @rOrgId=0)
		AND (ISNULL(SA.BatchStatusId,1)=1)
		AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)	
		AND A.BatchId=@rBatchId	
	--Group By SA.Code	
	Order By SA.ClassId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pRptActivityWiseStudentListGet]

		   	
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='', 	
           @rClassId int,
           @rDivisionId int,
           @rActivityTypeId int,
           @rActivityId int,
           @rOrgId int,
           @rStatusId int,
           @rOrgGroupId int=0,
           @rBatchId int=0
          
AS
SET NOCOUNT ON

BEGIN

IF (@rOrgId = 0)
BEGIN
	 
	SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		SA.AcademicId,
		ISNULL(SA.RollNo,0)AS RollNo,
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,	
		A.Id AS ActivityId,	
		A.Title AS ActivityName,
		ATM.Id AS ActivityTypeId,		
		ATM.Title AS ActivityTypeName,
		OM.Id AS OrgId,
		OM.DisplayTitle AS OrgName,
		SA.StudentId,
		ISNULL(CONVERT(VARCHAR(50),A.FromDate,103),'') AS FromDate,
		ISNULL(CONVERT(VARCHAR(50),A.ToDate,103),'') AS ToDate,
		A.Remark AS Remark,
		AP.Remark AS ActivityRemark
		
	FROM 
		sStudent.vStudentAcademic SA		
		INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=SA.StudentId AND AP.SourceTypeId=2003 
		INNER JOIN sActivity.tActivity A ON A.Id=AP.ActivityId AND A.BatchId=SA.BatchId
		INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id = A.ActivityTypeId	
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id	
	WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND (ATM.Id=@rActivityTypeId OR ISNULL(@rActivityTypeId,0)=0)
		AND (AP.ActivityId=@rActivityId OR ISNULL(@rActivityId,0)=0)
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (SA.OrgId=@rOrgId OR @rOrgId=0)
		AND (ISNULL(SA.BatchStatusId,1)=1)
		AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)		
		AND SA.IsActiveBatch = 1
	Order By SA.ClassId

END
ELSE
BEGIN
	DECLARE @lOrgGroupBatchId int 
	Select @lOrgGroupBatchId = OrgGroupBatchId from [sSetup].[tBatchMaster] Where Id = @rBatchId
	Select @rBatchId = Id from [sSetup].[tBatchMaster] Where OrgId = @rOrgId AND OrgGroupBatchId = @lOrgGroupBatchId

	SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		SA.AcademicId,
		ISNULL(SA.RollNo,0)AS RollNo,
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,	
		A.Id AS ActivityId,	
		A.Title AS ActivityName,
		ATM.Id AS ActivityTypeId,		
		ATM.Title AS ActivityTypeName,
		OM.Id AS OrgId,
		OM.DisplayTitle AS OrgName,
		SA.StudentId,
		ISNULL(CONVERT(VARCHAR(50),A.FromDate,103),'') AS FromDate,
		ISNULL(CONVERT(VARCHAR(50),A.ToDate,103),'') AS ToDate,
		A.Remark AS Remark,
		AP.Remark AS ActivityRemark	 
		
	FROM 
		sStudent.vStudentAcademic SA		
		INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=SA.StudentId AND AP.SourceTypeId=2003 
		INNER JOIN sActivity.tActivity A ON A.Id=AP.ActivityId AND A.BatchId=SA.BatchId
		INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id = A.ActivityTypeId	
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id	
	WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND (ATM.Id=@rActivityTypeId OR ISNULL(@rActivityTypeId,0)=0)
		AND (AP.ActivityId=@rActivityId OR ISNULL(@rActivityId,0)=0)
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (SA.OrgId=@rOrgId OR @rOrgId=0)
		AND (ISNULL(SA.BatchStatusId,1)=1)
		AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)		
		AND A.BatchId=@rBatchId
	Order By SA.ClassId
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pRptAssignClubDetailGet]

		   	
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='', 	
           @rClassId int,
           @rDivisionId int,
           @rClubTypeId int,
           @rClubId int,
           @rOrgId int,
           @rStatusId int,
           @rOrgGroupId int=0
          
AS
SET NOCOUNT ON

BEGIN

	SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		SA.AcademicId,
		SA.RollNo,
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,
		CM.Id AS ClubId,
		CM.Title AS ClubName,
		CTM.Id AS ClubTypeId,
		CTM.Title AS ClubTypeName,
		OM.Id AS OrgId,
		OM.DisplayTitle AS OrgName,
		SA.StudentId 
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId=SA.AcademicId 
		INNER JOIN sActivity.tClubMaster CM ON CM.Id=AC.ClubId
		INNER JOIN sActivity.tClubTypeMaster CTM ON CTM.Id = CM.ClubTypeId
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id
	WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND (CM.ClubTypeId=@rClubTypeId OR @rClubTypeId=0)
		AND (AC.ClubId=@rClubId OR @rClubId=0)
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (SA.OrgId=@rOrgId OR @rOrgId=0)
		AND (SA.IsActiveBatch=1)
		AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pRptAssignHouseDetailGet]

		   	
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='', 	
           @rClassId int,
           @rDivisionId int,
           @rHouseGroupId int,
           @rHouseId int,
           @rOrgId int,
           @rStatusId int
          
AS
SET NOCOUNT ON
BEGIN
	SELECT  
	    @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		SA.StudentId,
		SA.RollNo,
		SA.Code,
		SA.Name,
		SA.ClassId,
	    SA.DivisionId,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,
		HM.Id AS HouseId, 
		HM.Title AS HouseName,
		HGM.Id AS HouseGroupId,
		HGM.Title AS HouseGroupName,
		OM.Id AS OrgId,
		OM.DisplayTitle AS OrgName
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sStudent.tStudentOther SO ON SA.StudentId=So.StudentId
		INNER JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
		INNER JOIN sActivity.tHouseGroupMaster HGM ON HGM.Id = HM.HouseGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON HM.OrgId = OM.Id
	WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND (HM.HouseGroupId=@rHouseGroupId OR @rHouseGroupId=0)
		AND (SO.HouseId=@rHouseId OR @rHouseId=0)
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (SA.OrgId=@rOrgId OR @rOrgId=0)
		AND (SA.IsActiveBatch=1)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sActivity].[pRptBatchwiseInvitedSelectedStudent]
** Desc:  Display data in Batchwise Placed Students
** Auth:  Savan Vaghela
** Date:  31-January-2017
** Page:  Pages/Activity/ReportCriteria/PlacementReportCriteria.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    31-January-2017      Savan Vaghela       
************************************************************/
--EXEC [sActivity].[pRptBatchwiseInvitedSelectedStudent] 1201,120100001,120100101,120100018,0,0,'','',0,0,1201
CREATE OR ALTER PROCEDURE [sActivity].[pRptBatchwiseInvitedSelectedStudent]
@rOrgId int ,
@rBatchId int ,
@rDepartmentId int ,
@rClassId int ,
@rDivisionId int,
@rStatusId int ,
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',
@rPlacementId int,
@rCompanyId int,
@rOrgGroupId int =null
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
 					
		

--SELECT '' as Builder1,'' Builder2,1 BatchId,'2011-2012' Batch,100 NoOfStudents,180 InTake union
--SELECT '' as Builder1,'' Builder2,2 BatchId,'2012-2013' Batch,150 NoOfStudents,180 InTake union
--SELECT '' as Builder1,'' Builder2,3 BatchId,'2013-2014' Batch,160 NoOfStudents,180 InTake union
--SELECT '' as Builder1,'' Builder2,4 BatchId,'2014-2015' Batch,170 NoOfStudents,180 InTake union
--SELECT '' as Builder1,'' Builder2,5 BatchId,'2015-16' Batch,180 NoOfStudents,180 InTake union
--SELECT '' as Builder1,'' Builder2,6 BatchId,'2016-2017' Batch,200 NoOfStudents,180 InTake union
--SELECT '' as Builder1,'' Builder2,7 BatchId,'2017-2018' Batch,220 NoOfStudents,200 InTake union
--SELECT '' as Builder1,'' Builder2,0 BatchId,'2010-2011' Batch,50 NoOfStudents,40 InTake union
--SELECT '' as Builder1,'' Builder2,-1 BatchId,'2009-2010' Batch,30 NoOfStudents,25 InTake 

SELECT  @rBuilder1 as Builder1
		,@rBuilder2 as Builder2
		,BM.ID AS BatchId
		,BM.Title AS Batch
		,Count(0)NoOfStudents
		,IT.InTake
	FROM  [sActivity].[tPlacementInvite] AS PIS
		INNER JOIN sStudent.tAcademic          AS  A    ON a.id= pis.AcedamicId
		INNER JOIN sStudent.tStudentMaster     AS SM    ON A.StudentId=SM.Id	
		INNER JOIN sSetup.tOrganizationMaster  AS  OM   ON SM.OrgId = OM.Id
		INNER JOIN sSetup.tClassMaster         AS CM	ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster    AS DeptM ON DeptM.Id=CM.DepartmentId
		INNER JOIN sSetup.tBatchMaster         AS BM    ON BM.Id = A.BatchId
		INNER JOIN sSetup.tDivisionMaster      AS DM 	ON DM.Id=A.DivisionId 
		INNER JOIN sActivity.tPlacement        AS PL    ON PL.id=PIS.PlacementId 
		INNER JOIN sActivity.tPlacementCompanyMaster AS PC ON PC.ID=PL.PlacementCompanyId
		INNER JOIN (
					
	SELECT  
		
		BM.ID AS BatchId
		,Count(0)InTake
		
	FROM  [sActivity].[tPlacementInvite] AS PIS
		INNER JOIN sStudent.tAcademic          AS  A    ON a.id= pis.AcedamicId
		INNER JOIN sStudent.tStudentMaster     AS SM    ON A.StudentId=SM.Id	
		INNER JOIN sSetup.tOrganizationMaster  AS  OM   ON SM.OrgId = OM.Id
		INNER JOIN sSetup.tClassMaster         AS CM	ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster    AS DeptM ON DeptM.Id=CM.DepartmentId
		INNER JOIN sSetup.tBatchMaster         AS BM    ON BM.Id = A.BatchId
		INNER JOIN sSetup.tDivisionMaster      AS DM 	ON DM.Id=A.DivisionId 
		INNER JOIN sActivity.tPlacement        AS PL    ON PL.id=PIS.PlacementId 
		INNER JOIN sActivity.tPlacementCompanyMaster AS PC ON PC.ID=PL.PlacementCompanyId
		
	WHERE  
	    PIS.PlacementStatusId=212                                       AND
		 ((PC.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0)) 			AND
		 ((SM.OrgId=@rOrgId) OR (@rOrgId=0))							AND 
		 ((A.BatchId=@rBatchId) OR (@rBatchId=0))						AND 
		 ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		AND 
		 ((A.ClassId=@rClassId) OR (@rClassId=0))						AND 
		 ((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))				AND 
		 ((SM.StatusId=@rStatusId) OR (@rStatusId=0))					AND 
		 ((PIS.PlacementId=@rPlacementId) OR (@rPlacementId=0))			AND 
		 ((PL.PlacementCompanyId=@rCompanyId) OR (@rCompanyId=0))		
	GROUP by BM.ID ,BM.Title
	
	) AS IT ON IT.BatchId=BM.ID 
	
	
	WHERE  
	    
		 ((PC.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0)) 			AND
		 ((SM.OrgId=@rOrgId) OR (@rOrgId=0))							AND 
		 ((A.BatchId=@rBatchId) OR (@rBatchId=0))						AND 
		 ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		AND 
		 ((A.ClassId=@rClassId) OR (@rClassId=0))						AND 
		 ((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))				AND 
		 ((SM.StatusId=@rStatusId) OR (@rStatusId=0))					AND 
		 ((PIS.PlacementId=@rPlacementId) OR (@rPlacementId=0))			AND 
		 ((PL.PlacementCompanyId=@rCompanyId) OR (@rCompanyId=0))		
	GROUP by BM.ID ,BM.Title,IT.InTake 
	ORDER by BM.ID
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sActivity].[pRptBatchwisePlacedStudents]
** Desc:  Display data in Batchwise Placed Students
** Auth:  Savan Vaghela
** Date:  31-January-2017
** Page:  Pages/Activity/ReportCriteria/PlacementReportCriteria.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    24-January-2017      Savan Vaghela       
************************************************************/
--EXEC [sActivity].[pRptBatchwisePlacedStudents] 1001,0,0,0,0,0,'','',0,0,1001
CREATE OR ALTER PROCEDURE [sActivity].[pRptBatchwisePlacedStudents]
@rOrgId int ,
@rBatchId int ,
@rDepartmentId int ,
@rClassId int ,
@rDivisionId int,
@rStatusId int ,
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',
@rPlacementId int,
@rCompanyId int,
@rOrgGroupId int =null
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
--select  '' Builder1,''	Builder2,0	BatchId,'AAAAAA'	Batch,100	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,1	BatchId,'BBBBBB'	Batch,145	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,2	BatchId,'CCCCCC'	Batch,158	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,3	BatchId,'DDDDDD'	Batch,184	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,4	BatchId,'EEEEEE'	Batch,184	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,5	BatchId,'FFFFFF'	Batch,183	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,6	BatchId,'GGGGGG'	Batch,105	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,7	BatchId,'HHHHHH'	Batch,104	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,8	BatchId,'IIIIII'	Batch,156	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,9	BatchId,'JJJJJJ'	Batch,156	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,10	BatchId,'KKKKKK'	Batch,108	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,11	BatchId,'LLLLLL'	Batch,190	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,12	BatchId,'MMMMMM'	Batch,113	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,13	BatchId,'NNNNNN'	Batch,114	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,14	BatchId,'OOOOOO'	Batch,125	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,15	BatchId,'PPPPPP'	Batch,175	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,16	BatchId,'QQQQQQ'	Batch,198	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,17	BatchId,'RRRRRR'	Batch,136	NoOfStudents UNION
--select  '' Builder1,''	Builder2,18	BatchId,'SSSSSS'	Batch,145	NoOfStudents UNION 
--select  '' Builder1,''	Builder2,19	BatchId,'TTTTTT'	Batch,178	NoOfStudents  
		

SELECT  @rBuilder1 as Builder1
		,@rBuilder2 as Builder2
		,BM.ID AS BatchId
		,BM.Title AS Batch
		,Count(0)NoOfStudents
	FROM  [sActivity].[tPlacementInvite] AS PIS
		INNER JOIN sStudent.tAcademic          AS  A    ON a.id= pis.AcedamicId
		INNER JOIN sStudent.tStudentMaster     AS SM    ON A.StudentId=SM.Id	
		INNER JOIN sSetup.tOrganizationMaster  AS  OM   ON SM.OrgId = OM.Id
		INNER JOIN sSetup.tClassMaster         AS CM	ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster    AS DeptM ON DeptM.Id=CM.DepartmentId
		INNER JOIN sSetup.tBatchMaster         AS BM    ON BM.Id = A.BatchId
		INNER JOIN sSetup.tDivisionMaster      AS DM 	ON DM.Id=A.DivisionId 
		INNER JOIN sActivity.tPlacement        AS PL    ON PL.id=PIS.PlacementId 
		INNER JOIN sActivity.tPlacementCompanyMaster AS PC ON PC.ID=PL.PlacementCompanyId 
	WHERE  
	    PIS.PlacementStatusId=212                                       AND 
		 ((PC.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0)) 			AND
		 ((SM.OrgId=@rOrgId) OR (@rOrgId=0))							AND 
		 ((A.BatchId=@rBatchId) OR (@rBatchId=0))						AND 
		 ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		AND 
		 ((A.ClassId=@rClassId) OR (@rClassId=0))						AND 
		 ((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))				AND 
		 ((SM.StatusId=@rStatusId) OR (@rStatusId=0))					AND 
		 ((PIS.PlacementId=@rPlacementId) OR (@rPlacementId=0))			AND 
		 ((PL.PlacementCompanyId=@rCompanyId) OR (@rCompanyId=0))		
	GROUP by BM.ID ,BM.Title 
	ORDER by BM.ID--,DeptM.ID,PC.Id,PL.id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pRptEventAttendanceGet]
	 
	 @rEventScheduleId int,
	 @rOrgId smallint, 
	 @rBatchId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 		
		--IF(@rDivisionId != 0)
		--BEGIN 
			SELECT
			    'Student' AS SourceType,
				vSA.AcademicId AS SourceId,
				vSA.Code,
				vSA.RollNo AS Number,
				vSA.Name AS Name,
				CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision, 
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				CONVERT (bit ,CASE WHEN EAT.SourceId IS NULL OR EAT.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END) AS IsObsolete,
				ES.Title AS EventName
				--,vSA.BatchId
			FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
			WHERE
				vSA.OrgId=@rOrgId
				AND vSA.BatchId = @rBatchId
			--ORDER BY vSA.RollNo	
		
		
		UNION ALL
		
		--IF(@rDepartmentId != 0)
		
			SELECT
			    'Employee' AS SourceType,
				vECD.EmployeeId AS SourceId,
				vECD.Code,
				vECD.EmployeeId AS Number,
				vECD.EmployeeName AS Name,
				'' AS ClassDivision, 
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				CONVERT (bit ,CASE WHEN EAT.SourceId IS NULL OR EAT.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END) AS IsObsolete,
				ES.Title AS EventName
				--,vECD.DepartmentId
			FROM 
				sHrm.vEmployeeCommonDetail vECD
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vECD.OrganizationDepartmentId AND EA.SourceTypeId=2004 
				AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vECD.EmployeeId AND EAT.SourceTypeId = 95
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
			WHERE
				vECD.OrgId=@rOrgId 
			--ORDER BY vECD.Code	
		--END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pRptEventSchedule]

	--@rId int = 0,
	@rTitle nvarchar(100),
	@rFromDate date,
	@rToDate date,
	@rBatchId int,
	--@rIsSearch bit = 1,
	@rEventTypeId int = 0
	--,@rSourceId bigint = 0
	--,@rSourceTypeId smallint = 0
	,@rBuilder1 nvarchar(max) = ''
	,@rBuilder2 nvarchar(max) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN

	--IF @rIsSearch = 1
	--BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	--END

	--IF(@rSourceTypeId=2003)
	--BEGIN
	--	SELECT
	--		ES.Id as EventScheduleId,
	--		ES.Title,
	--		ES.FromDate,
	--		ES.ToDate,
	--		ES.Remark,
	--		ES.IsCommonForAll,
	--		ES.IsHoliday,
	--		ES.IsEnrollment,
	--		ISNULL(ES.EventTypeId,0) AS EventTypeId,
	--		ISNULL(EM.Title,'') AS EventType,
	--		EM.HighlightColor,
	--		EM.Title AS EventTypeName,
	--		OM.Id as OrgId,
	--		OM.WeekOffs,
	--		ES.BatchId
	--	FROM
	--		sActivity.tEventSchedule ES
	--		LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
	--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	--	WHERE
	--		((ES.Id = @rId) OR (@rId = 0))
	--		AND ((ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2005 AND
	--				SourceId=(SELECT DivisionId FROM sStudent.vStudentName WHERE StudentId=@rSourceId AND
	--					OrgId= CAST(LEFT(@rBatchId,4) AS int)  AND BatchId=@rBatchId))))
	--		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	--		AND (((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--			OR ((ES.ToDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')='')))
	--		AND ES.BatchId=@rBatchId
	--		AND ((ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
	--	ORDER BY ES.FromDate DESC
	--END

	--ELSE IF(@rSourceTypeId=95)
	--BEGIN
	--	SELECT
	--		ES.Id as EventScheduleId,
	--		ES.Title,
	--		ES.FromDate,
	--		ES.ToDate,
	--		ES.Remark,
	--		ES.IsCommonForAll,
	--		ES.IsHoliday,
	--		ES.IsEnrollment,
	--		ISNULL(ES.EventTypeId,0) AS EventTypeId,
	--		ISNULL(EM.Title,'') AS EventType,
	--		EM.HighlightColor,
	--		EM.Title AS EventTypeName,
	--		OM.Id as OrgId,
	--		OM.WeekOffs,
	--		ES.BatchId
	--	FROM
	--		sActivity.tEventSchedule ES
	--		LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
	--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	--	WHERE
	--		((ES.Id = @rId) OR (@rId = 0))
	--		AND (ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId IN(2004,95) AND
	--				((SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)) OR (SourceId=@rSourceId))))
	--		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	--		AND (((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--			OR ((ES.ToDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--			AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')='')))
	--		AND ES.BatchId=@rBatchId
	--		AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
	--	ORDER BY ES.FromDate DESC
	--END

	--ELSE
	--BEGIN
		SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ES.Id as EventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ISNULL(ES.EventTypeId,0) AS EventTypeId,
			ISNULL(EM.Title,'') AS EventType,
			EM.HighlightColor,
			EM.Title AS EventTypeName,
			OM.Id as OrgId,
			OM.WeekOffs,
			ES.BatchId
		FROM
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = ES.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		WHERE
			--((ES.Id = @rId) OR (@rId = 0)) AND 
			((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ES.BatchId=@rBatchId
			AND (( ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
		ORDER BY ES.FromDate DESC
	--END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sActivity].[pRptInvitedStudentlist]
** Desc:  Display data in  Invited Student list report 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Activity/ReportCriteria/PlacementReportCriteria.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
** 2    31-January-2017      Savan Vaghela     Add  new Filter OrgGroupId  
************************************************************/
--EXEC [sActivity].[pRptInvitedStudentlist] 0,0,0,0,0,0,'','',0,0
CREATE OR ALTER PROCEDURE [sActivity].[pRptInvitedStudentlist]
@rOrgId int ,
@rBatchId int ,
@rDepartmentId int ,
@rClassId int ,
@rDivisionId int,
@rStatusId int ,
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',
@rPlacementId int,
@rCompanyId int,
@rOrgGroupId int =null
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
	SELECT   
		@rBuilder1 as Builder1
		,@rBuilder2 as Builder2
		,OM.ID as 'CollegeID'
		,OM.Title as 'College'
		,PC.Id AS 'CompanyId'
		,PL.id as PlacementId
		,PC.Title+' - '+PL.Title as PlacementCompany
		,DeptM.ID as DepartmentId
		,DeptM.Title as 'Branch'
		,CM.id as 'ClassID'
		,Dm.id as 'DivisionID'
		,ISNULL(CM.Title,'') +' - '+ ISNULL(DM.Title,'') as 'Standerd'
		,ISNULL(SM.FirstName,'') +'  '+ ISNULL( SM.MiddleName,'')+' '+ ISNULL(SM.LastName,'') as FullName 
		,SM.Code as 'StudentID'
		
		
	FROM  [sActivity].[tPlacementInvite] AS PIS
		INNER JOIN sStudent.tAcademic          AS  A    ON a.id= pis.AcedamicId
		INNER JOIN sStudent.tStudentMaster     AS SM    ON A.StudentId=SM.Id	
		INNER JOIN sSetup.tOrganizationMaster  AS  OM   ON SM.OrgId = OM.Id
		INNER JOIN sSetup.tClassMaster         AS CM	ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster    AS DeptM ON DeptM.Id=CM.DepartmentId
		INNER JOIN sSetup.tBatchMaster         AS BM    ON BM.Id = A.BatchId
		INNER JOIN sSetup.tDivisionMaster      AS DM 	ON DM.Id=A.DivisionId 
		INNER JOIN sActivity.tPlacement        AS PL    ON PL.id=PIS.PlacementId 
		INNER JOIN sActivity.tPlacementCompanyMaster AS PC ON PC.ID=PL.PlacementCompanyId 
	WHERE 
		PC.OrgGroupId=@rOrgGroupId
		AND	((SM.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((A.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((PIS.PlacementId=@rPlacementId) OR (@rPlacementId=0))
		AND ((PL.PlacementCompanyId=@rCompanyId) OR (@rCompanyId=0))
	Order by 
	OM.orderindex,CM.orderindex,dm.orderindex,sm.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sActivity].[pRptListOfCompaniesYearWise] 
** Desc:  Display data in Batchwise Placed Students
** Auth:  Savan Vaghela
** Date:  31-January-2017
** Page:  Pages/Activity/ReportCriteria/PlacementReportCriteria.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    25-January-2017      Savan Vaghela       
************************************************************/
--EXEC [sActivity].[pRptListOfCompaniesYearWise] 1001,0,0,0,0,0,'','',0,0,0
CREATE OR ALTER PROCEDURE [sActivity].[pRptListOfCompaniesYearWise]
@rOrgId int ,
@rBatchId int ,
@rDepartmentId int ,
@rClassId int ,
@rDivisionId int,
@rStatusId int ,
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',
@rPlacementId int,
@rCompanyId int,
@rOrgGroupId int =null
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
	--SELECT distinct
	--	@rBuilder1 as Builder1
	--	,@rBuilder2 as Builder2
	--	,bm.id as BatchId
	--	,BM.Title as 'BatchName'
	--	,PC.ID as 'CompanyID'
	--	,PC.Title as 'CompanyName'
	--	,BM.OrderIndex FROM  [sActivity].[tPlacement] as PL 
	--	INNER JOIN sSetup.tBatchMaster         AS BM ON BM.id=PL.BatchId
	--	INNER JOIN sActivity.tPlacementCompanyMaster AS PC ON PC.ID=PL.PlacementCompanyId 
	--WHERE  bm.OrgId=@rOrgId
	--	AND ((PL.BatchId=@rBatchId) OR (@rBatchId=0))	                 	
	--ORDER by BM.OrderIndex
	SELECT 
		@rBuilder1 as Builder1
		,@rBuilder2 as Builder2
		,bm.Id as 'BatchID'
		,bm.title as 'Batch'
		,PC.Id AS 'CompanyId'
		,PC.Title AS 'PlacementCompany'
		,PL.Id AS 'PlacementID'
		,PL.Title AS 'Placement'
		,bm.orderindex
		
		
		

	FROM  [sActivity].[tPlacementInvite] AS PIS
		INNER JOIN sStudent.tAcademic          AS  A    ON a.id= pis.AcedamicId
		INNER JOIN sStudent.tStudentMaster     AS SM    ON A.StudentId=SM.Id	
		INNER JOIN sSetup.tOrganizationMaster  AS  OM   ON SM.OrgId = OM.Id
		INNER JOIN sSetup.tClassMaster         AS CM	ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster    AS DeptM ON DeptM.Id=CM.DepartmentId
		INNER JOIN sSetup.tBatchMaster         AS BM    ON BM.Id = A.BatchId
		INNER JOIN sSetup.tDivisionMaster      AS DM 	ON DM.Id=A.DivisionId
		INNER JOIN sActivity.tPlacement        AS PL    ON pl.id =PIS.PlacementId
		INNER JOIN sActivity.tPlacementCompanyMaster AS PC ON PC.ID=PL.PlacementCompanyId 
	WHERE 
	   ((PC.OrgGroupId=@rOrgGroupId)  OR (@rOrgGroupId=0) )   AND
		((SM.OrgId=@rOrgId) OR (@rOrgId=0))		                        AND 
		((A.BatchId=@rBatchId) OR (@rBatchId=0))	                 	AND 
		((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		AND 
		((A.ClassId=@rClassId) OR (@rClassId=0))	                	AND 
		((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))	        	AND 
		((SM.StatusId=@rStatusId) OR (@rStatusId=0))		            AND 
		((PIS.PlacementId=@rPlacementId) OR (@rPlacementId=0))          AND 
		((PC.Id=@rCompanyId) OR (@rCompanyId=0))     
		
		
	GROUP by bm.Id		,bm.title 		,PC.Id		,PC.Title 		,PL.Id 	,PL.Title,bm.orderindex 
	ORDER BY
	bm.orderindex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sActivity].[pRptListOfCompaniesYearWiseWihDetail]
** Desc:  Display data in  ListOfCompaniesYearWiseWihDetail report 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Activity/ReportCriteria/PlacementReportCriteria.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    31-January-2017      Savan Vaghela       
************************************************************/
--EXEC [sActivity].[pRptListOfCompaniesYearWiseWihDetail] 0,0,0,0,0,0,'','',0,0,0
CREATE OR ALTER PROCEDURE [sActivity].[pRptListOfCompaniesYearWiseWihDetail]
@rOrgId int ,
@rBatchId int ,
@rDepartmentId int ,
@rClassId int ,
@rDivisionId int,
@rStatusId int ,
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',
@rPlacementId int,
@rCompanyId int,
@rOrgGroupId int =null
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
	SELECT   
		@rBuilder1 as Builder1
		,@rBuilder2 as Builder2
		,BM.ID AS BatchId
		,BM.Title AS Batch
		--,DeptM.ID AS DepartmentId
		--,DeptM.Title AS 'Department'
		,0 AS DepartmentId
		,'' AS 'Department'
		,PC.Id AS 'CompanyId'
		,PC.Title AS Company
		,PL.id AS PlacementId
		,PL.Title AS Placement
		,MIN(PIS.OfferedPackage)Lowest
		,MAX(PIS.OfferedPackage)Highest
		,CONVERT(DECIMAL(18,2),AVG(ISNULL(PIS.OfferedPackage,0)))Average
		
		
	FROM  [sActivity].[tPlacementInvite] AS PIS
		INNER JOIN sStudent.tAcademic          AS  A    ON a.id= pis.AcedamicId
		INNER JOIN sStudent.tStudentMaster     AS SM    ON A.StudentId=SM.Id	
		INNER JOIN sSetup.tOrganizationMaster  AS  OM   ON SM.OrgId = OM.Id
		INNER JOIN sSetup.tClassMaster         AS CM	ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster    AS DeptM ON DeptM.Id=CM.DepartmentId
		INNER JOIN sSetup.tBatchMaster         AS BM    ON BM.Id = A.BatchId
		INNER JOIN sSetup.tDivisionMaster      AS DM 	ON DM.Id=A.DivisionId 
		INNER JOIN sActivity.tPlacement        AS PL    ON PL.id=PIS.PlacementId 
		INNER JOIN sActivity.tPlacementCompanyMaster AS PC ON PC.ID=PL.PlacementCompanyId 
	WHERE  
		  PIS.PlacementStatusId=212                                                      AND
	    -- ((PC.OrgGroupId=@rOrgGroupId) OR @rOrgGroupId=0)                                AND
	     --((SM.OrgId=@rOrgId) OR (@rOrgId=0))											 AND
		 ((A.BatchId=@rBatchId) OR (@rBatchId=0))										 AND
		 ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))						 AND
		 ((A.ClassId=@rClassId) OR (@rClassId=0))										 AND
		 ((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))								 AND
		 ((SM.StatusId=@rStatusId) OR (@rStatusId=0))									 AND
		 ((PIS.PlacementId=@rPlacementId) OR (@rPlacementId=0))							 AND
		 ((PL.PlacementCompanyId=@rCompanyId) OR (@rCompanyId=0))
	
	GROUP BY BM.ID,BM.Title,PC.Id ,PC.Title,PL.id ,PL.Title
	ORDER by BM.ID,PC.Id,PL.id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sActivity].[pRptPlacedStudentList] 
** Desc:  Display data in  PlacedStudentList report 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Activity/ReportCriteria/PlacementReportCriteria.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    24-January-2017      Savan Vaghela       
************************************************************/
--EXEC [sActivity].[pRptPlacedStudentList] 0,0,0,0,0,0,'','',0,0
CREATE OR ALTER PROCEDURE [sActivity].[pRptPlacedStudentList]
@rOrgId int ,
@rBatchId int ,
@rDepartmentId int ,
@rClassId int ,
@rDivisionId int,
@rStatusId int ,
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',
@rPlacementId int,
@rCompanyId int,
@rOrgGroupId int =null
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
	SELECT  
		@rBuilder1 as Builder1
		,@rBuilder2 as Builder2
		,OM.ID as 'CollegeID'
		,OM.Title as 'College'
		,PC.Id AS 'CompanyId'
		,PC.Title AS 'PlacementCompany'
		,DeptM.ID as DepartmentId
		,DeptM.Title as 'Branch'
		,CM.id as 'ClassID'
		,Dm.id as 'DivisionID'
		,ISNULL(CM.Title,'') +' - '+ ISNULL(DM.Title,'') as 'Standerd'
		,ISNULL(SM.FirstName,'') +'  '+ ISNULL( SM.MiddleName,'')+' '+ ISNULL(SM.LastName,'') as FullName 
		,SM.Code as 'StudentID'
	    ,CONVERT(VARCHAR,ISNULL(PIS.OfferedPackage,0)) +' LPA'    as 'Package'
		

	FROM  [sActivity].[tPlacementInvite] AS PIS
		INNER JOIN sStudent.tAcademic          AS  A    ON a.id= pis.AcedamicId
		INNER JOIN sStudent.tStudentMaster     AS SM    ON A.StudentId=SM.Id	
		INNER JOIN sSetup.tOrganizationMaster  AS  OM   ON SM.OrgId = OM.Id
		INNER JOIN sSetup.tClassMaster         AS CM	ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster    AS DeptM ON DeptM.Id=CM.DepartmentId
		INNER JOIN sSetup.tBatchMaster         AS BM    ON BM.Id = A.BatchId
		INNER JOIN sSetup.tDivisionMaster      AS DM 	ON DM.Id=A.DivisionId
		INNER JOIN sActivity.tPlacement        AS PL    ON pl.id =PIS.PlacementId
		INNER JOIN sActivity.tPlacementCompanyMaster AS PC ON PC.ID=PL.PlacementCompanyId 
	WHERE 
		PIS.PlacementStatusId=212		                                AND 
		 ((PC.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0)) 			AND
		((SM.OrgId=@rOrgId) OR (@rOrgId=0))		                        AND 
		((A.BatchId=@rBatchId) OR (@rBatchId=0))	                 	AND 
		((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		AND 
		((A.ClassId=@rClassId) OR (@rClassId=0))	                	AND 
		((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))	        	AND 
		((SM.StatusId=@rStatusId) OR (@rStatusId=0))		            AND 
		((PIS.PlacementId=@rPlacementId) OR (@rPlacementId=0))          AND 
		((PC.Id=@rCompanyId) OR (@rCompanyId=0))          
	ORDER BY
	OM.orderindex,CM.orderindex,dm.orderindex,sm.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  EXEC [sActivity].[pRptPlacementSummary]
** Desc:  Display data in Placement Summary Report
** Auth:  Savan Vaghela
** Date:  31-January-2017
** Page:  Pages/Activity/ReportCriteria/PlacementReportCriteria.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    31-January-2017      Savan Vaghela       
************************************************************/
--EXEC [sActivity].[pRptPlacementSummary] 0,0,0,0,0,0,'','',0,0,0
CREATE OR ALTER PROCEDURE [sActivity].[pRptPlacementSummary]
@rOrgId int ,
@rBatchId int ,
@rDepartmentId int ,
@rClassId int ,
@rDivisionId int,
@rStatusId int ,
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',
@rPlacementId int,
@rCompanyId int,
@rOrgGroupId int =null
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

	SELECT 
		@rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,OM.ID AS OrgId
		,om.Title AS 'Organization'
		,BM.ID AS 'BatchId'
		,BM.Title AS 'AcademicYear'
		,c1.BatchID AS 'CompanyId'
		,c1.CompanyVisit
		,DeptM.ID AS 'DeparmentID'
		,DeptM.Title AS 'Department'
		,CM.id AS ClassId
		,ISNULL(CM.Title,'') +' - '+ ISNULL(DM.Title,'') AS 'Standerd'
		,COUNT(sm.ID) AS 'StudentCount'
	FROM  [sActivity].[tPlacementInvite] AS PIS
		INNER JOIN sStudent.tAcademic          AS  A    ON a.id= pis.AcedamicId
		INNER JOIN sStudent.tStudentMaster     AS SM    ON A.StudentId=SM.Id	
		INNER JOIN sSetup.tOrganizationMaster  AS  OM   ON SM.OrgId = OM.Id
		INNER JOIN sSetup.tClassMaster         AS CM	ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster    AS DeptM ON DeptM.Id=CM.DepartmentId
		INNER JOIN sSetup.tBatchMaster         AS BM    ON BM.Id = A.BatchId
		INNER JOIN sSetup.tDivisionMaster      AS DM 	ON DM.Id=A.DivisionId
		INNER JOIN sActivity.tPlacement        AS PL    ON pl.id =PIS.PlacementId
		INNER JOIN sActivity.tPlacementCompanyMaster AS PC ON PC.ID=PL.PlacementCompanyId 
		LEFT JOIN (
						SELECT a.BatchID,count(a.PlacementCompanyId) AS CompanyVisit FROM
						(
								SELECT PL.BatchID,PL.PlacementCompanyId
								FROM [sActivity].[tPlacement] AS PL
								GROUP BY PL.BatchID,PL.PlacementCompanyId 
						) AS a
						group by a.BatchID
				 ) AS  C1 ON C1.BatchID=BM.Id

	WHERE 
		PIS.PlacementStatusId=212										AND	
		((PC.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0)) 				AND
		((SM.OrgId=@rOrgId) OR (@rOrgId=0))		                        AND 
		((A.BatchId=@rBatchId) OR (@rBatchId=0))	                 	AND 
		((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		AND 
		((A.ClassId=@rClassId) OR (@rClassId=0))	                	AND 
		((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))	        	AND 
		((SM.StatusId=@rStatusId) OR (@rStatusId=0))		            AND 
		((PIS.PlacementId=@rPlacementId) OR (@rPlacementId=0))          AND 
		((PC.Id=@rCompanyId) OR (@rCompanyId=0))  

	GROUP BY BM.ID,BM.Title,DeptM.ID,DeptM.Title,CM.ID,DM.Id,BM.OrderIndex,OM.ID,om.Title,c1.CompanyVisit,c1.BatchID,CM.Title,DM.Title
	
	ORDER BY OM.ID,BM.ID,DM.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pRptPTMStudentAttendentListGet]

		   	
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='', 	
           @rClassId int,
           @rDivisionId int,
           @rOrgId int,
           @rStatusId int,
           @rOrgGroupId int=0
          
AS
SET NOCOUNT ON

BEGIN

SELECT
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,	
			    2003 AS SourceType,
				vSA.AcademicId AS SourceId,
				vSA.Code,
				vSA.RollNo AS Number,
				vSA.Name AS Name,
				vSA.ClassId,
				vSA.DivisionId,
				vSA.DivisionOrder,
				vSA.ClassName AS ClassName,
				OM.Id AS OrgId,
				OM.DisplayTitle AS OrgName,
				vSA.StudentId,
				CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision, 
				Case When ISNULL(EAT.IsSelfPresent,0)=1 OR ISNULL(EAT.IsFatherPresent,0)=1 OR ISNULL(EAT.IsMotherPresent,0)=1 OR ISNULL(EAT.IsGuardianPresent,0)=1 
				then 1 Else 0 end AS IsPresent,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				ES.Title AS EventName,
				ES.Id as EventId
			FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				(vSA.ClassId=@rClassId OR @rClassId=0)
				AND (vSA.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (vSA.StatusId=@rStatusId OR @rStatusId=0)
				AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
				AND (vSA.IsActiveBatch=1)
				AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)	
			--ORDER BY vSA.RollNo	
		
		
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sActivity].[pStudentHolidayGet]
	 	 
	 	 @rUserSourceId bigint,
	 	 @rBatchId int,
	 	 @rOrgId int, 
	 	 @rForMonth int=0,
	 	@rToDate int=0,
	 	@rForYear int=0,
	 	@rToYear int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  
	 
	SELECT 
			 Day(EP.FromDate) AS FromDay,
			 Day(EP.ToDate) As ToDay,
			  Month(EP.FromDate) AS FromMonth,
			 Month(EP.ToDate) As ToMonth,
			  YEar(EP.FromDate) AS FromYEar,
			 YEar(EP.ToDate) As ToYEar,
			 CASE WHEN EP.FromDate = EP.ToDate THEN 1 ELSE DATEDIFF(day, EP.FromDate, EP.ToDate) END AS DayCount
  FROM   
			sActivity.tEventAssign EA 
		 INNER JOIN    sActivity.tEventSchedule EP ON EP.Id=EA.EventScheduleid
		 INNER JOIN sSetup.tDivisionMaster D ON D.Id = EA.SourceId AND EA.SourceTypeId=2005
		 INNER JOIN sStudent.tAcademic A ON A.DivisionId= D.Id
					 
			 
  WHERE 
		 
        (A.OrgId = @rOrgId)
      AND (EP.BatchId = @rBatchID)
      AND A.Id=@rUserSourceId
      AND Month(EP.FromDate)=@rForMonth
      AND Month(EP.ToDate)=@rToDate
      AND Year(EP.FromDate)=@rForYear
       AND Year(EP.ToDate)=@rToYear
      AND EP.IsHoliday=1
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pStudentImmunizationStatusAdd]
	 
           @rStudentId bigint,
           @rImmunizationChartId int,
           @rIsTaken bit,
           @rTakenDate date,
           @rRemark nvarchar(150)          
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 
	 
	IF(@rIsTaken = 0)
	BEGIN
	   
	   DELETE FROM sActivity.tStudentImmunizationStatus Where StudentId = @rStudentId AND ImmunizationChartId = @rImmunizationChartId
	   SET @lNextNumber = 1
	END
	ELSE
	BEGIN	
	IF NOT EXISTS (Select 1 FROM sActivity.tStudentImmunizationStatus WHERE StudentId = @rStudentId AND ImmunizationChartId=@rImmunizationChartId) AND @rIsTaken = 1	
	BEGIN
		 
	INSERT INTO sActivity.tStudentImmunizationStatus
           (
            StudentId,
            ImmunizationChartId,
            IsTaken,
            TakenDate,
            Remark
           )
     VALUES
           (
            @rStudentId,
            @rImmunizationChartId,
            @rIsTaken,
            ISNULL(@rTakenDate,''),
            @rRemark
            )
          SET @lNextNumber = 1   
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN	     
			 UPDATE sActivity.tStudentImmunizationStatus
			 SET 			    
			    IsTaken = @rIsTaken,
			    TakenDate = ISNULL(@rTakenDate,''),
			    Remark = @rRemark
			    			    
	      WHERE StudentId = @rStudentId AND ImmunizationChartId = @rImmunizationChartId	      
		  --COMMIT TRANSACTION
		  SET @lNextNumber = 1
	 END  			
    END 
     
     SELECT @lNextNumber AS Result

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pStudentImmunizationStatusGet]
	  
           @rStudentId bigint,
           @rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION
	 	   
	  SELECT 
	       IC.[Id] AS StudentImmunizationChartId
		  ,IC.[Title] AS ImmunizationChart		  
		  ,ISNULL(SI.IsTaken,0) AS IsTaken
		  ,ISNULL(SI.[Remark],'') AS Remark
		  ,ISNULL(SI.TakenDate,'') AS TakenDate
		  ,CONVERT(nvarchar(50),FromAge) + ' - ' + CONVERT(nvarchar(50),ToAge) + ' - ' + DU.Title AS Duration
		  ,DU.Title AS DurationUnit
		  ,FromAge
		  ,ToAge		 
		  ,IC.IsObsolete 
		 -- ,ISNULL((Select (DATEDIFF(yy,ISNULL(SO.DateOfBirth,GETDATE()),GETDATE())) FROM sStudent.vStudentAllDetail SO WHERE AcademicId = @rStudentId),0) AS Age
		  ,ISNULL((Select (DATEDIFF(yy,ISNULL(SO.DateOfBirth,sCommon.fGetDate()),sCommon.fGetDate())) FROM sStudent.tAcademic A 	LEFT JOIN sStudent.tStudentOther SO
		  ON SO.StudentId=A.StudentId WHERE A.Id = @rStudentId),0) AS Age
		  --,DU.Title AS DurationUnit
		  		  
	 FROM  [sActivity].[tImmunizationChart]  IC  LEFT JOIN sCommon.tDurationUnitMaster DU ON DU.Id = IC.DurationUnitId LEFT JOIN sActivity.tStudentImmunizationStatus SI 
	 ON	   SI.ImmunizationChartId = IC.Id AND StudentId = @rStudentId
	 WHERE IC.IsObsolete = 0  AND OrgGroupId = @rOrgGroupId
	 
	 Order By DU.Id,ToAge ASC 
	 
	 --ORDER BY ToAge ASC	   	 	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pStudentListGet]
	 
	
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rHouseId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			
			SA.AcademicId As Id,					
			SA.RollNo AS RollNo,						
			SA.Name	AS Title,
			SA.Code AS IdNo,
			SO.HouseId,
			HM.Title As HouseName,
			SA.ClassName+'-'+SA.DivisionName AS DivDept
		
		
	FROM 
		 	sStudent.vStudentAcademic SA
		 	LEFT JOIN sStudent.vStudentOther SO ON SO.AcademicId=SA.AcademicId
		 	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
		
	WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (SO.HouseId=@rHouseId OR @rHouseId=0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pWeekOffSettingAdd]
	 
	
	 @rSourceTypeId int=0,
	 @rSourceId bigint,
	 
	 @rFirstWeekOffDayId tinyint=0,
	 @rFristWeekOffRuled tinyint=0,
	 @rSecondWeekOffId tinyint=0,
	 @rSEcondWeekOffRuleId tinyint=0,
	 @rCreatedUserId bigint,
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	If exists(Select 1 from sActivity.tWeekOffSetting Where SourceTypeId = @rSourceTypeId AND SourceId=@rSourceId)
	BEGIN
		Update sActivity.tWeekOffSetting
		Set
			FirstWeekOffDayId = @rFirstWeekOffDayId,
			FristWeekOffRuleId =@rFristWeekOffRuled ,
			SecondWeekOff = @rSecondWeekOffId,
			SEcondWeekOffRuleId = @rSEcondWeekOffRuleId,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
		Where
			SourceTypeId = @rSourceTypeId
			AND SourceId = @rSourceId
		Select 11 As Result
	END
	
	ELSE
	BEGIN
	Declare @lNextNumber int
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tWeekOffSetting', 0, 1, 1,@outNextNumber = @lNextNumber output
	Insert Into sActivity.tWeekOffSetting
	(
		Id,
		SourceTypeId,
		SourceId,
		FirstWeekOffDayId,
		FristWeekOffRuleId,
		SecondWeekOff,
		SEcondWeekOffRuleId,
		CreatedUserId,
		CreatedDateTime
	)
	Values
	(
		@lNextNumber,
		@rSourceTypeId,
		@rSourceId,
		@rFirstWeekOffDayId,
		@rFristWeekOffRuled,
		@rSecondWeekOffId,
		@rSEcondWeekOffRuleId,
		@rCreatedUserId,
		sCommon.fGetDate()
	)
	Select 1 As Result
	END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pWeekOffSettingDelete]
	 
	
	  
	 @rOrgId int,
	  @rSourceId bigint,
	 @rSourceTypeId int,
	 @rId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	 
			Delete from sActivity.tWeekOffSetting
			Where SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId AND Id=@rId
	 Select 1 As Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pWeekOffSettingGet]
	 
	
	 @rEmpGrade int=0,
	 @rOrgId int,
	 
	 @rEmpDesignationId int=0,
	 @rEmpTypeId int=0,
	 @rEmpGroupId int=0,
	 @rSourceTypeId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	if(@rSourceTypeId=2001)
	BEGIN
			Select 
				CM.Id As ClassID,
				Title,
				0 As EmpId,
				ISNULL(WE.Id,0) As Id,
				CASE ISNULL(WE.ID,0) WHEN 0 THEN 0 Else 1  END AS Checked,
				ISNULL(WE.FirstWeekOffDayId,0) AS FirstWeekOffDayId,
				ISNULL(WE.FristWeekOffRuleId,0) AS FristWeekOffRuleId,
				ISNULL(WE.SEcondWeekOffRuleId,0) AS SEcondWeekOffRuleId,
				ISNULL(WE.SecondWeekOff,0) AS SecondWeekOff
			From sSetup.tClassMaster CM
			LEFT JOIN sActivity.tWeekOffSetting WE ON WE.SourceId = CM.Id AnD WE.SourceTypeId =2001
			WHere OrgID=@rOrgId
			Order by OrderIndex
	END
	
	if(@rSourceTypeId=95)
	BEGIn
		Select 
			EM.ID As EmpId,
			FirstName +' '+MiddleName+' '+LastName As Name,
			0 As ClassID,
			ISNULL(WE.Id,0) AS Id,
			CASE ISNULL(WE.ID,0) WHEN 0 THEN 0 Else 1  END AS Checked,
			ISNULL(WE.FirstWeekOffDayId,0) As FirstWeekOffDayId,
			ISNULL(WE.FristWeekOffRuleId,0) As FristWeekOffRuleId,
			ISNULL(WE.SEcondWeekOffRuleId,0) As SEcondWeekOffRuleId,
			ISNULL(WE.SecondWeekOff,0) As SecondWeekOff
		From
			sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJO ON EJO.EmployeeId = EM.Id 
			LEFT JOIN sActivity.tWeekOffSetting WE ON WE.SourceId = EM.Id AnD WE.SourceTypeId =95
		Where 
			EM.OrgID=@rOrgId
			AND ((EJO.EmployeeDesignationId =@rEmpDesignationId) OR (@rEmpDesignationId=0))
			AND ((EJO.EmployeeGroupId =@rEmpGroupId ) OR (@rEmpGroupId=0))
			AND ((EJO.EmployeeGradeId =@rEmpGrade ) OR (@rEmpGrade=0))
			AND ((EJO.EmployeeTypeId = @rEmpTypeId) OR (@rEmpTypeId=0))
			AND  ISNULL(EM.IsOtherUser,0) = 0
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sActivity].[pWeekOffValidationGet]
	  
	 @rOrgId int=0,
	 @rClassId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	IF(@rClassId!=0) 
	BEGIN
		Select 
			CM.Id As ClassID,
			CASE ISNULL(WE.ID,0) WHEN 0 THEN 0 Else 1  END AS Checked,
			ISNULL(WE.FirstWeekOffDayId,0) AS FirstWeekOff,
			ISNULL(WE.FristWeekOffRuleId,0) AS FirstWeekOffRuleId,
			ISNULL(WE.SEcondWeekOffRuleId,0) AS SecondWeekOffRuleId,
			ISNULL(WE.SecondWeekOff,0) AS SecondWeekOff
	From   
	        sSetup.tClassMaster CM
			INNER JOIN sActivity.tWeekOffSetting WE ON WE.SourceId = CM.Id AnD WE.SourceTypeId =2001
			WHere OrgID=@rOrgId AND CM.Id = @rClassId
			Order by OrderIndex
	END
	ELSE
	BEGIN
		 	Select 
				 ISNULL(OM.StudentFirstWeekOffDayId,0) As StudentFirstWeekOffDayId
				,ISNULL(OM.StudentFirstWeekOffRuleId,0) As StudentFirstWeekOffRuleId 
				,ISNULL(OM.StudentSecondWeekOffDayId,0) As StudentSecondWeekOffDayId
				,ISNULL(OM.StudentSecondWeekOffRuleId,0) As StudentSecondWeekOffRuleId
			From   
				sSetup.tOrganizationMaster OM
			WHERE 
				Id = @rOrgId
				Order by OrderIndex
	END

	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sActivity].[pXMLEventHoliday]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	) 
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	DECLARE @lNextNumber BIGINT    
	DECLARE @lOrgId smallint
	DECLARE @lCount int
	DECLARE @lDivisionId int
	DECLARE @lEventSchduleCount int
	DECLARE @lEventSchduleId int
	
	
	-----------------------  UPDATE EventSchedule
	UPDATE sActivity.tEventSchedule
	SET	
		FromDate = A.FromDate,
		ToDate = A.ToDate,
		Title = A.Title,
		UpdatedUserId = 9999000000003,
		UpdatedDateTime = sCommon.fGetDate() 
	FROM 
	(
	SELECT
		Id,
		FromDate,
		ToDate,
		Title,
		BatchId
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		FromDate datetime '@FromDate',
		ToDate datetime '@ToDate',
		Title nvarchar(100) '@Title',
		BatchId int '@BatchId'	
	))A
	 WHERE sCommon.fGetIntIdForOrg(A.Id,@rOrgId) = sActivity.tEventSchedule.Id 
	AND sCommon.fGetIntIdForOrg(A.BatchId,@rOrgId) = sActivity.tEventSchedule.BatchId 
	

	-----------------------  INSERT EventSchedule holiday
	INSERT INTO sActivity.tEventSchedule
	(
		Id,
		BatchId,
		FromDate,
		ToDate,
		Title,
		IsCommonForAll,
		IsEnrollment,
		IsHoliday,
		CreatedUserId,
		CreatedDateTime
	)
	SELECT		
		sCommon.fGetIntIdForOrg(A.Id,@rOrgId),
		A.BatchId,
		A.FromDate,
		A.ToDate,
		A.Title,
		1,
		1,
		1,
		9999000000003,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		FromDate datetime '@FromDate',
		ToDate datetime '@ToDate',
		Title nvarchar(100) '@Title',
		BatchId int '@BatchId'	
	) A LEFT JOIN sActivity.tEventSchedule ES ON 
	sCommon.fGetIntIdForOrg(A.Id,@rOrgId) = ES.Id AND A.BatchId = ES.BatchId
	WHERE ES.Id IS NULL 
	
	DECLARE @lEvetntTypeId int

	SELECT @lEvetntTypeId= Id FRom sActivity.tEventTypeMaster ET Where EventMainTypeId = 1 AND OrgGroupId IN
	(select OrgGroupId from sSetup.tOrganizationMaster Where Id = @rOrgId)
	
	
	Update ES SET ES.EventTypeId = @lEvetntTypeId From sActivity.tEventSchedule ES inner join 
	(SELECT sCommon.fGetIntIdForOrg(A.Id,@rOrgId) AS Id	,BatchId	
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		BatchId int '@BatchId'	
	)A) A1  ON 
	A1.Id = ES.Id AND A1.BatchId = ES.BatchId
	
	
	CREATE Table #EventSchedule (Id Int Identity,EventScheduleId int)
	
	Insert Into #EventSchedule SELECT sCommon.fGetIntIdForOrg(A.Id,@rOrgId)		
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		BatchId int '@BatchId'	
	) A INNER JOIN sActivity.tEventSchedule ES ON 
	sCommon.fGetIntIdForOrg(A.Id,@rOrgId) = ES.Id AND A.BatchId = ES.BatchId
	
	
	SELECT @lEventSchduleCount = Max(Id) FROM #EventSchedule
	
	CREATE Table #Division (Id Int Identity,DivId int)
	Insert into #Division Select Id From sSetup.tDivisionMaster Where OrgId = @rOrgId
	
	While @lEventSchduleCount > 0
	BEGIN
		SELECT @lEventSchduleId = EventScheduleId From #EventSchedule Where Id = @lEventSchduleCount		
		Select @lCount = Max(id) From #Division	
		While @lCount > 0 
		BEGIN
			SELECT @lDivisionId = DivId From #Division Where Id = @lCount			
			IF NOT EXISTS (SELECT 1 FROM sActivity.tEventAssign WHERE SourceTypeId = 2005 AND EventScheduleId = @lEventSchduleId AND SourceId = @lDivisionId )
			BEGIN
				Exec [sActivity].[pEventAssignAdd] 0,@lEventSchduleId,2005,@lDivisionId,0,@rOrgId	
			END
			SET @lCount = @lCount - 1
		END
		SET @lEventSchduleCount = @lEventSchduleCount  -1
	END	      
           
	
	Drop Table #Division
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pXMLModifyHealthCheckupEmployee]
	
	@rXmlString [nvarchar](max),
	@rHealthCheckupId int
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		DECLARE @loDoc INT
		EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXmlString
		BEGIN
			UPDATE       HC  		  
			SET          HC.HeightInCm = E.HeightInCm,
			             HC.Dental	    =  E.Dental,
						 HC.Nails	    =  E.Nails,
						 HC.Hair	    =  E.Hair,
						 HC.Skin	    =  E.Skin,
						 HC.Ear	    =  E.Ear,
						 HC.Nose	    =  E.Nose,
						 HC.Throat	    =  E.Throat,
						 HC.Respiratory	    =  E.Respiratory,
						 HC.Cardiovascular	    =  E.Cardiovascular,
						 HC.Nervous	    =  E.Nervous,
						 HC.Eye	    =  E.Eye,
						 HC.Other	    =  E.Other,
						 HC.ImportantFinding	    =  E.ImportantFinding,
						 HC.Remarks	    =  E.Remarks,
						 HC.FollowupDetail	    =  E.FollowupDetail,
						 hc.WeightInKg = E.WeightInKg,
						 Hc.StatusId = E.StatusId,
						 Hc.BloodGroupId=E.BloodGroupId
						 	
			   			
			FROM sActivity.tHealthCheckupEmployee HC				 
			 INNER JOIN					
			    (
					SELECT EmployeeId AS EmployeeId,HealthCheckupId AS HealthCheckupId,HeightInCm AS HeightInCm,WeightInKg AS WeightInKg,
					Dental AS Dental,Nails AS Nails,Hair AS Hair,Skin AS Skin,
					Ear AS Ear,Nose AS Nose,Throat AS Throat,Respiratory AS Respiratory,Cardiovascular AS Cardiovascular
				   ,Nervous AS Nervous,Eye AS Eye,Other AS Other,ImportantFinding AS ImportantFinding,Remarks AS Remarks,
					FollowupDetail AS FollowupDetail,StatusId AS StatusId,BloodGroupId AS BloodGroupId
					FROM
					OPENXML (@loDoc, '/Table/HealthCheckupEmployee', 1)
					WITH    (
							      EmployeeId bigint, 
							      HealthCheckupId int,
							      HeightInCm decimal(6,2)
							     ,WeightInKg decimal(6,2)
							     ,Dental	nvarchar(150)
								 ,Nails	nvarchar(150)
								 ,Hair	nvarchar(150)
								 ,Skin	nvarchar(150)
								 ,Ear	nvarchar(150)
								 ,Nose	nvarchar(150)
								 ,Throat	nvarchar(150)
								 ,Respiratory	nvarchar(150)
								 ,Cardiovascular	nvarchar(150)
								 ,Nervous	nvarchar(150)
								 ,Eye	nvarchar(150)
								 ,Other	nvarchar(150)
								 ,ImportantFinding	nvarchar(150)
								 ,Remarks	nvarchar(150)
								 ,FollowupDetail	nvarchar(150)
								 ,StatusId	int
								 ,BloodGroupId tinyint
			                 )
			          )E ON E.EmployeeId = HC.EmployeeId AND E.HealthCheckupId = HC.HealthCheckupId
				
				Where E.EmployeeId = HC.EmployeeId AND E.HealthCheckupId = HC.HealthCheckupId
	 
	 
	 
	INSERT INTO [sActivity].[tHealthCheckupEmployee]
           (
            [HealthCheckupId]
           ,[EmployeeId]
           ,[HeightInCm]
           ,[WeightInKg]
           ,[Dental]
           ,[Nails]
           ,[Hair]
           ,[Skin]
           ,[Ear]
           ,[Nose]
           ,[Throat]
           ,[Respiratory]
           ,[Cardiovascular]
           ,[Nervous]
           ,[Eye]
           ,[Other]
           ,[ImportantFinding]
           ,[Remarks]
           ,[FollowupDetail]
           ,[StatusId]
		   ,[BloodGroupId]
           )             
			SELECT 
			      HealthCheckupId			      			      
			     ,EmployeeId
			     ,HeightInCm
			     ,WeightInKg
			     ,Dental
			     ,Nails
			     ,Hair
			     ,Skin
			     ,Ear
			     ,Nose
			     ,Throat
			     ,Respiratory
			     ,Cardiovascular
				 ,Nervous
				 ,Eye
				 ,Other
				 ,ImportantFinding
				 ,Remarks				  
				 ,FollowupDetail
				 ,StatusId
				 ,BloodGroupId
					FROM
					OPENXML (@loDoc, '/Table/HealthCheckupEmployee', 1)
					WITH    (
							          HealthCheckupId int '@HealthCheckupId'
								     ,EmployeeId bigint  '@EmployeeId'
									 ,HeightInCm decimal(6,2) '@HeightInCm'
									 ,WeightInKg decimal(6,2) '@WeightInKg'
									 ,Dental	nvarchar(150) '@Dental'
									 ,Nails	nvarchar(150) '@Nails'
									 ,Hair	nvarchar(150) '@Hair'
									 ,Skin	nvarchar(150) '@Skin'
									 ,Ear	nvarchar(150) '@Ear'
									 ,Nose	nvarchar(150) '@Nose'
									 ,Throat	nvarchar(150) '@Throat'
									 ,Respiratory	nvarchar(150) '@Respiratory'
									 ,Cardiovascular	nvarchar(150) '@Cardiovascular'
									 ,Nervous	nvarchar(150) '@Nervous'
									 ,Eye	nvarchar(150) '@Eye'
									 ,Other	nvarchar(150) '@Other'
									 ,ImportantFinding	nvarchar(150) '@ImportantFinding'
									 ,Remarks	nvarchar(150) '@Remarks'
									 ,FollowupDetail	nvarchar(150) '@FollowupDetail'
									 ,StatusId int '@StatusId'
									 ,BloodGroupId tinyint '@BloodGroupId'
 
			                 )A
		       WHERE A.EmployeeId NOT IN (Select EmployeeId FROM sActivity.tHealthCheckupEmployee Where HealthCheckupId = @rHealthCheckupId)
 
	  			 
			 Select 1 As Result 
		END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sActivity].[pXMLModifyHealthCheckupStudent]
	
	@rXmlString [nvarchar](max),
	@rHealthCheckupId int
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 --  BEGIN TRY
	--BEGIN TRANSACTION

		DECLARE @loDoc INT
		EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXmlString
		BEGIN
			--CREATE TABLE 
			UPDATE       HC  		  
			SET          HC.HeightInCm = E.HeightInCm,
			             HC.Dental	    =  E.Dental,
						 HC.Nails	    =  E.Nails,
						 HC.Hair	    =  E.Hair,
						 HC.Skin	    =  E.Skin,
						 HC.Ear	    =  E.Ear,
						 HC.Nose	    =  E.Nose,
						 HC.Throat	    =  E.Throat,
						 HC.Respiratory	    =  E.Respiratory,
						 HC.Cardiovascular	    =  E.Cardiovascular,
						 HC.Nervous	    =  E.Nervous,
						 HC.Eye	    =  E.Eye,
						 HC.Other	    =  E.Other,
						 HC.ImportantFinding	    =  E.ImportantFinding,
						 HC.Remarks	    =  E.Remarks,
						 HC.FollowupDetail	    =  E.FollowupDetail,
						 hc.WeightInKg = E.WeightInKg,
						 Hc.StatusId = E.StatusId,
						 Hc.BloodGroupId=E.BloodGroupId
						 	
			   			
			FROM sActivity.tHealthCheckupStudent HC	
			 
			 INNER JOIN					
			    (
					SELECT AcademicId AS AcademicId,HealthCheckupId AS HealthCheckupId,HeightInCm AS HeightInCm,WeightInKg AS WeightInKg,
					Dental AS Dental,Nails AS Nails,Hair AS Hair,Skin AS Skin,
					Ear AS Ear,Nose AS Nose,Throat AS Throat,Respiratory AS Respiratory,Cardiovascular AS Cardiovascular
				   ,Nervous AS Nervous,Eye AS Eye,Other AS Other,ImportantFinding AS ImportantFinding,Remarks AS Remarks,
					FollowupDetail AS FollowupDetail,StatusId AS StatusId,BloodGroupId AS BloodGroupId
					FROM
					OPENXML (@loDoc, '/Table/HealthCheckupStudent', 1)
					WITH    (
							      AcademicId bigint, 
							      HealthCheckupId int,
							      HeightInCm decimal(6,2)
							     ,WeightInKg decimal(6,2)
							     ,Dental	nvarchar(150)
								 ,Nails	nvarchar(150)
								 ,Hair	nvarchar(150)
								 ,Skin	nvarchar(150)
								 ,Ear	nvarchar(150)
								 ,Nose	nvarchar(150)
								 ,Throat	nvarchar(150)
								 ,Respiratory	nvarchar(150)
								 ,Cardiovascular	nvarchar(150)
								 ,Nervous	nvarchar(150)
								 ,Eye	nvarchar(150)
								 ,Other	nvarchar(150)
								 ,ImportantFinding	nvarchar(150)
								 ,Remarks	nvarchar(150)
								 ,FollowupDetail	nvarchar(150)
								 ,StatusId	int
								 ,BloodGroupId tinyint
			                 )
			          )E ON E.AcademicId = HC.AcademicId AND E.HealthCheckupId = HC.HealthCheckupId
				
				Where E.AcademicId = HC.AcademicId AND E.HealthCheckupId = HC.HealthCheckupId
	 
	 
	 
	INSERT INTO [sActivity].[tHealthCheckupStudent]
           (
            [HealthCheckupId]
           ,[AcademicId]
           ,[HeightInCm]
           ,[WeightInKg]
           ,[Dental]
           ,[Nails]
           ,[Hair]
           ,[Skin]
           ,[Ear]
           ,[Nose]
           ,[Throat]
           ,[Respiratory]
           ,[Cardiovascular]
           ,[Nervous]
           ,[Eye]
           ,[Other]
           ,[ImportantFinding]
           ,[Remarks]
           ,[FollowupDetail]
           ,[StatusId]
		   ,[BloodGroupId]
           )             
			SELECT 
			      HealthCheckupId			      			      
			     ,AcademicId
			     ,HeightInCm
			     ,WeightInKg
			     ,Dental
			     ,Nails
			     ,Hair
			     ,Skin
			     ,Ear
			     ,Nose
			     ,Throat
			     ,Respiratory
			     ,Cardiovascular
				 ,Nervous
				 ,Eye
				 ,Other
				 ,ImportantFinding
				 ,Remarks				  
				 ,FollowupDetail
				 ,StatusId
				 ,BloodGroupId
					FROM
					OPENXML (@loDoc, '/Table/HealthCheckupStudent', 1)
					WITH    (
							          HealthCheckupId int '@HealthCheckupId'
								     ,AcademicId bigint  '@AcademicId'
									 ,HeightInCm decimal(6,2) '@HeightInCm'
									 ,WeightInKg decimal(6,2) '@WeightInKg'
									 ,Dental	nvarchar(150) '@Dental'
									 ,Nails	nvarchar(150) '@Nails'
									 ,Hair	nvarchar(150) '@Hair'
									 ,Skin	nvarchar(150) '@Skin'
									 ,Ear	nvarchar(150) '@Ear'
									 ,Nose	nvarchar(150) '@Nose'
									 ,Throat	nvarchar(150) '@Throat'
									 ,Respiratory	nvarchar(150) '@Respiratory'
									 ,Cardiovascular	nvarchar(150) '@Cardiovascular'
									 ,Nervous	nvarchar(150) '@Nervous'
									 ,Eye	nvarchar(150) '@Eye'
									 ,Other	nvarchar(150) '@Other'
									 ,ImportantFinding	nvarchar(150) '@ImportantFinding'
									 ,Remarks	nvarchar(150) '@Remarks'
									 ,FollowupDetail	nvarchar(150) '@FollowupDetail'
									 ,StatusId int '@StatusId'
									 ,BloodGroupId tinyint '@BloodGroupId'
 
			                 )A
		       WHERE A.AcademicId NOT IN (Select AcademicId FROM sActivity.tHealthCheckupStudent Where HealthCheckupId = @rHealthCheckupId)
 
	  			 
			 Select 1 As Result 
		END
	--	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionAddImport]
	 
	@rClassId int=0,
	@rFromBatchId int,
	@rToBatchId int,
	@rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
BEGIN TRY 
	IF EXISTS (SELECT 1 FROM sAdmission.tAdmissionSetup WHERE BatchId = @rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	IF EXISTS (SELECT 1 FROM sAdmission.tAdmissionCriteria WHERE BatchId = @rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	IF EXISTS (SELECT 1 FROM sAdmission.tAdmissionCriteriaForm WHERE BatchId = @rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	IF EXISTS (SELECT 1 FROM sAdmission.tAdmissionCriteriaFee WHERE BatchId = @rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END

	BEGIN TRANSACTION
	IF NOT EXISTS(SELECT 1 FROM sAdmission.tAdmissionSetup WHERE BatchId=@rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
		BEGIN
		Declare @lCount int
	DECLARE @lNextNumber INT
	--Admission Setup Temp Table
	CREATE TABLE #TempAdmissionSetup(
	[AutoId] int identity,
	[Id] [int] NOT NULL,
	[ClassId] [int] NOT NULL,
	[TotalMark] [decimal](12, 2) NOT NULL,
	[BatchId] [int] NOT NULL,
	[CriteriaName] [nvarchar](150) NOT NULL
	)	
	-- End Create Table
	
	INSERT INTO #TempAdmissionSetup SELECT * FROM sAdmission.tAdmissionSetup WHERE BatchId=@rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))

		Select @lCount = COUNT(Id) From #TempAdmissionSetup
	
	While (@lCount > 0)
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO sAdmission.tAdmissionSetup
			SELECT @lNextNumber,ClassId,TotalMark,@rToBatchId,CriteriaName FROM #TempAdmissionSetup WHERE AutoId = @lCount
				--WHERE((ClassId=@rClassId) OR(@rClassId=0)) AND BatchId=@rFromBatchId
				SET @lCount = @lCount -1
	END
	Drop Table #TempAdmissionSetup 
		END
	
 	IF NOT EXISTS(SELECT 1 FROM sAdmission.tAdmissionCriteria WHERE BatchId=@rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
		BEGIN
			Declare @lAdmissionCriteriaCount int
			DECLARE @lAdmissionCriteriaNextNumber INT
			
			--Admission Setup Temp Table
			CREATE TABLE #TempAdmissionCriteria(
				[AutoId] int identity,
				[ClassId] [int] NOT NULL,
				[BatchId] [int] NOT NULL,
				[IsValidateBirthdate] [bit] NOT NULL,
				[FromDateOfBirth] [date] NULL,
				[ToDateOfBirth] [date] NULL,
				[IsParentAcademicRequired] [bit] NULL,
				[IsStudentAcademicRequired] [bit] NULL,
				[IsFamilyDetailRequired] [bit] NULL,
				[IsSiblingDetailRequired] [bit] NULL,
				[IsReferenceDetailRequired] [bit] NULL,
				[IsFixStudentAcademic] [bit] NULL,
				[StudentAcademicFor] [nvarchar](300) NULL,
				[StudentAcademicRemark] [nvarchar](max) NULL,
				[FamilyDetailRemark] [nvarchar](max) NULL,
				[IsFixParentAcademic] [bit] NULL,
				[ParentAcademicFor] [nvarchar](300) NULL,
				[ParentAcademicRemark] [nvarchar](max) NULL,
				[ConfirmationRemark] [nvarchar](max) NULL,
				[AdmissionFormRemark] [nvarchar](max) NULL,
				[Reference1] [nvarchar](150) NULL,
				[Reference2] [nvarchar](150) NULL,
				[IsOtherInformationRequired] [bit] NULL,
				[IsPayFormFeeOnline] [bit] NULL,
				[FormFeeName] [nvarchar](100) NULL,
				[FormFeeAmount] [decimal](12, 2) NULL,
				[IsHostelDetailRequired] [bit] NULL,
				[IsTransportDetailRequired] [bit] NULL,
				[IsHealthDetailRequired] [bit] NULL,
				[IsBirthPlaceDetailRequired] [bit] NULL,
				[IsAadhaarDetailRequired] [bit] NULL,
				[IsBloodGroupDetailRequired] [bit] NULL,
				[ReceiptBookId] [int] NULL,
				[IsFatherDetail] [bit] NULL,
				[IsFatherFullDetail] [bit] NULL,
				[IsFatherAcademic] [bit] NULL,
				[IsMotherDetail] [bit] NULL,
				[IsMotherFullDetail] [bit] NULL,
				[IsMotherAcademic] [bit] NULL,
				[IsGuardianDetail] [bit] NULL,
				[IsGuardianFullDetail] [bit] NULL,
				[IsGuardianAcademic] [bit] NULL,
				[IsPublish] [bit] NULL,
				[IsCustomField1Required] [bit] NULL,
				[CustomField1Remark] [nvarchar](500) NULL,
				[CustomField1TypeId] [tinyint] NULL,
				[CustomField1List] [nvarchar](500) NULL,
				[IsCustomField1Mandatory] [bit] NULL,
				[IsCustomField2Required] [bit] NULL,
				[CustomField2Remark] [nvarchar](500) NULL,
				[CustomField2TypeId] [tinyint] NULL,
				[CustomField2List] [nvarchar](500) NULL,
				[IsCustomField2Mandatory] [bit] NULL,
				[IsCustomField3Required] [bit] NULL,
				[CustomField3Remark] [nvarchar](500) NULL,
				[CustomField3TypeId] [tinyint] NULL,
				[CustomField3List] [nvarchar](500) NULL,
				[IsCustomField3Mandatory] [bit] NULL,
				[IsAdmissionFeeBreakup] [bit] NULL,
				[AgeCutOffDate] [date] NULL,
				[Remark1] [nvarchar](max) NULL,
				[Remark2] [nvarchar](max) NULL,
				[Remark3][nvarchar](max) NULL,
				[AdmissionInquiryRemark][nvarchar](max) NULL,
				[AdmissionConfirmationRemark] [nvarchar](max) NULL,
				[IsSendMailFormAttachment] [bit] NULL,
				[IsOptionalSubject] [bit] NULL
			)	
			-- End Create Table
				INSERT INTO #TempAdmissionCriteria SELECT * FROM sAdmission.tAdmissionCriteria WHERE BatchId=@rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
				Select @lAdmissionCriteriaCount = COUNT(AutoId) From #TempAdmissionCriteria
				
			
			While (@lAdmissionCriteriaCount > 0)
				BEGIN
						INSERT INTO sAdmission.tAdmissionCriteria
						SELECT  
							ClassId
							,@rToBatchId
							,IsValidateBirthdate
							,FromDateOfBirth
							,ToDateOfBirth
							,IsParentAcademicRequired
							,IsStudentAcademicRequired
							,IsFamilyDetailRequired
							,IsSiblingDetailRequired
							,IsReferenceDetailRequired
							,IsFixStudentAcademic
							,StudentAcademicFor
							,StudentAcademicRemark
							,FamilyDetailRemark
							,IsFixParentAcademic
							,ParentAcademicFor
							,ParentAcademicRemark
							,ConfirmationRemark
							,AdmissionFormRemark,
							Reference1,
							Reference2,
							IsOtherInformationRequired,
							IsPayFormFeeOnline,
							FormFeeName,
							FormFeeAmount,
							IsHostelDetailRequired,
							IsTransportDetailRequired,
							IsHealthDetailRequired,
							IsBirthPlaceDetailRequired,
							IsAadhaarDetailRequired,
							IsBloodGroupDetailRequired,
							ReceiptBookId	,
							IsFatherDetail,
							IsFatherFullDetail,
							IsFatherAcademic,
							IsMotherDetail,
							IsMotherFullDetail,
							IsMotherAcademic,
							IsGuardianDetail,
							IsGuardianFullDetail,
							IsGuardianAcademic,
							IsPublish,
							IsCustomField1Required,
							CustomField1Remark,
							CustomField1TypeId,
							CustomField1List,
							IsCustomField1Mandatory,
							IsCustomField2Required,
							CustomField2Remark,
							CustomField2TypeId,
							CustomField2List,
							IsCustomField2Mandatory,
							IsCustomField3Required,
							CustomField3Remark,
							CustomField3TypeId,
							CustomField3List,
							IsCustomField3Mandatory,
							IsAdmissionFeeBreakup,
							AgeCutOffDate,
							Remark1,
							Remark2,
							Remark3,
							AdmissionInquiryRemark,
					        AdmissionConfirmationRemark,
							IsSendMailFormAttachment,
							IsOptionalSubject
							 
						FROM #TempAdmissionCriteria
							WHERE AutoId = @lAdmissionCriteriaCount --((ClassId=@rClassId) OR(@rClassId=0)) AND BatchId=@rFromBatchId
							SET @lAdmissionCriteriaCount = @lAdmissionCriteriaCount -1
				END	
				DROP TABLE #TempAdmissionCriteria
		END
	
	IF NOT EXISTS(SELECT 1 FROM sAdmission.tAdmissionCriteriaForm WHERE BatchId=@rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
		BEGIN
			Declare @lAdmissionCriteriaFormCount int
			DECLARE @lAdmissionCriteriaFormNextNumber INT
			--Admission Setup Temp Table
			CREATE TABLE #TempAdmissionCriteriaForm(
			[AutoId] int identity,
			[Id] [int] NOT NULL,
			[ClassId] [int] NOT NULL,
			[BatchId] [int] NOT NULL,
			[FieldRemark] [nvarchar](500) NOT NULL,
			[FieldTypeId] [tinyint] NOT NULL,
			[FieldList] [nvarchar](1000) NULL, --Mantis - 40619
			[IsFieldMandatory] [bit] NOT NULL,
			[FieldGroup] [nvarchar](200) NULL,
			[FieldOrder] [smallint] NULL
			)	
			-- End Create Table
			INSERT INTO #TempAdmissionCriteriaForm SELECT * FROM sAdmission.tAdmissionCriteriaForm WHERE BatchId=@rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))


			Select @lAdmissionCriteriaFormCount = COUNT(Id) From #TempAdmissionCriteriaForm

			While (@lAdmissionCriteriaFormCount > 0)
			BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCriteriaForm', 0, 1, 1,@outNextNumber = @lAdmissionCriteriaFormNextNumber output
			INSERT INTO sAdmission.tAdmissionCriteriaForm
				SELECT @lAdmissionCriteriaFormNextNumber,ClassId,@rToBatchId,FieldRemark,FieldTypeId,FieldList,IsFieldMandatory,FieldGroup,FieldOrder FROM #TempAdmissionCriteriaForm
				WHERE AutoId=@lAdmissionCriteriaFormCount --((ClassId=@rClassId) OR(@rClassId=0)) AND BatchId=@rFromBatchId
				SET @lAdmissionCriteriaFormCount = @lAdmissionCriteriaFormCount -1
			END
			DROP TABLE #TempAdmissionCriteriaForm
			
		END
	
	IF NOT EXISTS(SELECT 1 FROM sAdmission.tAdmissionCriteriaFee WHERE BatchId=@rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
		BEGIN
		
			Declare @lAdmissionCriteriaFeeCount int
			DECLARE @lAdmissionCriteriaFeeNextNumber INT
			--Admission Setup Temp Table
			CREATE TABLE #TempAdmissionCriteriaFee(
			[AutoId] int identity,
			[Id] [int] NOT NULL,
			[BatchId] [int] NOT NULL,
			[ClassId] [int] NOT NULL,
			[FeeNumber] [smallint] NOT NULL,
			[FeeName] [nvarchar](200) NOT NULL,
			[FeeOrder] [smallint] NOT NULL,
			[FeeAmount] [decimal](12, 2) NOT NULL
			)	
			-- End Create Table
			INSERT INTO #TempAdmissionCriteriaFee SELECT * FROM sAdmission.tAdmissionCriteriaFee WHERE BatchId=@rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
				
	Select @lAdmissionCriteriaFeeCount = COUNT(Id) From #TempAdmissionCriteriaFee
	
			While (@lAdmissionCriteriaFeeCount > 0)
			BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCriteriaFee', 0, 1, 1,@outNextNumber = @lAdmissionCriteriaFeeNextNumber output
			INSERT INTO sAdmission.tAdmissionCriteriaFee
				SELECT @lAdmissionCriteriaFeeNextNumber,@rToBatchId,ClassId,FeeNumber,FeeName,FeeOrder,FeeAmount FROM #TempAdmissionCriteriaFee
				WHERE AutoId = @lAdmissionCriteriaFeeCount--((ClassId=@rClassId) OR(@rClassId=0)) AND BatchId=@rFromBatchId
				SET @lAdmissionCriteriaFeeCount = @lAdmissionCriteriaFeeCount -1
			END
			DROP TABLE #TempAdmissionCriteriaFee
		
		END
			SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION

		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionAndInquiryConsolidateDashBoardGet]
                              
    @rTypeId int, -- 1-Admission, 2-Inquiry 
    @rType nvarchar(200), -- OrgGroup, Organization
    @rOrgGroupId int=0,
    @rOrgId int=0,
    @rCommonOrgGroupBatchId int=0,
	@rInquiryStatusId int=0,
	@rClassId int =0,
	@rSyncDate int =0,
	@rInquiryMainStatus int =0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--Changes for Mantis Id: 0039838

DECLARE @lConfigValueDashboard nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValueDashboard = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValueDashboard, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValueDashboard <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValueDashboard <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

	DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
	INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
	SELECT 
		OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
	FROM
		sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
	WHERE 
		((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
		AND BM.IsObsolete = 0 AND COGBM.Id=@rCommonOrgGroupBatchId
		AND BM.IsInContext = 1
	GROUP BY
		OM.Id
		
	DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
	INSERT INTO @lTempBatchId (OrgId , BatchId)
	SELECT 
		BM.OrgId AS OrgId,
		BM.Id AS BatchId
	FROM 
		sSetup.tBatchMaster BM
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
	WHERE
		BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id=@rCommonOrgGroupBatchId
		AND BM.IsInContext = 1
	
	DECLARE @lConfigValue nvarchar(50)=''
	IF(@rOrgGroupId = 0)
	BEGIN	
		DECLARE @lOrgGroupId int
		SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId		
	
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 397 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	END
	ELSE
	BEGIN
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 397 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	END
	IF @lConfigValue = ''
		SET @lConfigValue = 'False' 

-- For Admission TypeId=1
	IF(@rTypeId=1) 
	BEGIN
		IF(@rType='OrgGroup')
		BEGIN

		IF(@rSyncDate =1)
				BEGIN
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND (OrgGroupId = @rOrgGroupId))  
				BEGIN  
					IF(@rOrgGroupId !=0)  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = null) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
					
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
				ELSE  
				BEGIN  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId 
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount

					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
		END
		ELSE
			BEGIN
			 IF  Exists(select 1 from sAdmission.tTempAdmissionFormCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102) AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId)   
			 BEGIN  
				 SELECT * FROM sAdmission.tTempAdmissionFormCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				 return  
			 END  
			 ELSE  
			 BEGIN  
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))  
				BEGIN  
					IF(@rOrgGroupId !=0)  
        
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),
				
					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
					  
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
				ELSE  
				BEGIN  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),
			
					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
				     
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1   
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
			END  
		END
	END
-- For Admission TypeId=1
	IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,OM.OrderIndex
			FROM sAdmission.tAdmissionForm AF 
			LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId AND BM.IsInContext = 1
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			
			LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE --BM.IsActive = 1 
			OM.OrgGroupId = @rOrgGroupId 	
			AND BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId 
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,OM.OrderIndex
			Order BY OM.OrderIndex
		END
-- For Admission TypeId=1
	IF(@rType='Status')
		BEGIN
			SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount ,0 AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId AND OM.Id = @rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
			Order By OM.OrderIndex
		END
-- For Admission TypeId=1
	IF(@rType='StatusOrgGroupWise')
		BEGIN
		    CREATE Table #MyTempTable(
						  OrgId Int,
						  Organization nvarchar(100),
                          StatusName nvarchar(100),
                          StatusCount BigInt)
            INSERT INTO #MyTempTable(OrgId,Organization,StatusName,StatusCount)
			SELECT OM.Id,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,AF.Id AS StatusCount 			
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1

	DECLARE 
    @columns NVARCHAR(MAX) = '', 
    @sql     NVARCHAR(MAX) = '';

	SELECT 
    @columns+=QUOTENAME(ASM.Title) + ','
  FROM 
    sAdmission.tAdmissionStatusMaster ASM
  ORDER BY 
    ASM.Title;
  -- Add Pending Column
  SET @columns = LEFT(@columns, LEN(@columns) - 1)+',Pending';


  -- construct dynamic SQL
  SET @sql ='
  SELECT * FROM #MyTempTable MT  
  PIVOT(
    Count(MT.StatusCount)
    FOR MT.StatusName IN ('+ @columns +')
  ) AS pivot_table;';

  -- execute the dynamic SQL
  EXECUTE sp_executesql @sql;
  DROP Table #MyTempTable
		END

	--For Admission Form Count
	IF(@rType='AdmissionFormOrgGroupWise')
	BEGIN
		SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount , 0 AS InquiryMainStatusId
		,OM.OrderIndex
		FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		   INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
		
		LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
		WHERE --BM.IsActive = 1 
		BM.Id = TB.BatchId
		AND BM.IsInContext = 1
		AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
		And ISNULL(O.IsObsolete,0) = 0
		GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
		Order BY OM.OrderIndex	
	END

	IF(@rType='AdmissionFormStatusWise')
	BEGIN
		SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount , 0 AS InquiryMainStatusId
		,OM.OrderIndex
		FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		   INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
		
		LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
		WHERE --BM.IsActive = 1 
		BM.Id = TB.BatchId
		AND BM.IsInContext = 1
		AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
		And ISNULL(O.IsObsolete,0) = 0
		AND ISNULL(ASM.Id,0)=@rInquiryStatusId
		GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
		Order BY OM.OrderIndex	
	END
-- For Admission TypeId=1
	ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND (@rInquiryStatusId = -1 OR (ISNULL(ASM.Id,0)=@rInquiryStatusId))
			And ISNULL(O.IsObsolete,0) = 0
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND BM.IsInContext = 1
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
			ORDER BY CM.OrderIndex --add for mantis : 0042058
		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ( @rInquiryStatusId = -1 OR (ISNULL(ASM.Id,0)=@rInquiryStatusId) )
			And ISNULL(O.IsObsolete,0) = 0
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND BM.IsInContext = 1
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
			ORDER BY CM.OrderIndex --add for mantis : 0042058

		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusStudentList')
			BEGIN
			SELECT AF.FormNo As InquiryId, AF.FirstName+' '+AF.MiddleName +' '+ AF.LastName AS StudentName,AF.ContactNo AS ContactNo 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId 
			AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ( @rInquiryStatusId = -1 OR (ISNULL(ASM.Id,0)=@rInquiryStatusId) )
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND((CM.Id = @rClassId)OR(@rClassId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY AF.FirstName,AF.MiddleName,AF.LastName,AF.ContactNo,AF.FormNo
			END
			END
	
-- For Inquiry
	IF(@rTypeId=2)
	BEGIN
	IF(@rType='OrgGroup')
		BEGIN
			IF(@rSyncDate =1)
				BEGIN
			DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND (OrgGroupId = @rOrgGroupId))  
				   BEGIN  
				   IF(@rOrgGroupId !=0)  
				   INSERT INTO sAdmission.tTempAdmissionInquiryCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
					FROM   
					sSetup.tOrgGroupMaster OGM  
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
			        
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
			        
					LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId    
					WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
					--BM.IsActive = 1  
					GROUP BY OGM.Id,OGM.Title  
					SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				   END  
      ELSE   
       BEGIN  
		    INSERT INTO sAdmission.tTempAdmissionInquiryCount  
        SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
       FROM   
       sSetup.tOrgGroupMaster OGM  
       INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
       
       INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
       LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
       INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
       INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
       LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
       WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
       --BM.IsActive = 1  
       GROUP BY OGM.Id,OGM.Title  
		  SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
       END  
				END
			ELSE
				BEGIN
						IF  Exists(select 1 from sAdmission.tTempAdmissionInquiryCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId  AND (OrgGroupId = @rOrgGroupId))  
			  BEGIN  
			   SELECT  OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			   return  
			  END  
			 ELSE  
			  BEGIN  
			  DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			  IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))  
			   BEGIN  
				IF(@rOrgGroupId !=0)  
				INSERT INTO sAdmission.tTempAdmissionInquiryCount  
				 SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
				FROM   
				sSetup.tOrgGroupMaster OGM  
				INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
		        
				INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
		        
				LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
				WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
				--BM.IsActive = 1  
				GROUP BY OGM.Id,OGM.Title  
				SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			   END  
			  ELSE  
			   BEGIN  
				DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				INSERT INTO sAdmission.tTempAdmissionInquiryCount  
				 SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
				FROM   
				sSetup.tOrgGroupMaster OGM  
				INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
				INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
				LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
				WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
				--BM.IsActive = 1  
				GROUP BY OGM.Id,OGM.Title  
				SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
       END  
		END  
		 END		
		END
-- For Inquiry
	IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId AND BM.IsInContext = 1
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			
			--sAdmission.tAdmissionForm AF 
			--LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 	
			--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			--LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE BM.Id = TB.BatchId
			And ISNULL(O.IsObsolete,0) = 0
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY OM.Id,OM.Title,OM.OrderIndex
			ORDER BY OM.OrderIndex
		END
-- For Inquiry
	IF(@rType='Status')
		BEGIN
		IF(@lConfigValue = 'True')
		BEGIN
-- 11
-- Inquiry Form 
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId >= 11
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 21
-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI1.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 21
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 31
-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 41
-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 51
-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 61
-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51  AND ISM.InquiryMainStatusId !=71
			AND ISM.InquiryMainStatusId = 61

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 61 

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		
		    UNION ALL
			
-- 71
--Confirmed Admission

			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61 

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 81
-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 91
-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 101		
-- Fees not paid
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 111			
-- Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		END
		ELSE 
		BEGIN
			SELECT 
			ISM1.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM1.Title,'') AS StatusName,
			ISNULL(COUNT(ISM1.Id),0) AS StatusCount, 
			ISM1.InquiryMainStatusId AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM1.Id,ISM1.Title,ISM1.InquiryMainStatusId,AI.OrgId,OM.OrderIndex
			ORDER BY OM.OrderIndex
		END
		END
		
	IF(@rType='StatusOrgGroupWise')
		BEGIN
		IF(@lConfigValue = 'True')
		BEGIN

-- 11
-- Inquiry Form 
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId >= 11
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISNULL(ISM.InquiryMainStatusId,0) AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 21
-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI1.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 31
-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 41
-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			
			
			UNION ALL
-- 51
-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 61
-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51  AND ISM.InquiryMainStatusId !=71
			AND ISM.InquiryMainStatusId = 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 61 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		
		UNION ALL
			
-- 71
--Confirmed Admission

			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 81
-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 91
-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 101		
-- Fees not paid
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 111			
-- Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		 END
		 ELSE
		 BEGIN
			SELECT 
			ISM1.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM1.Title,'') AS StatusName,
			ISNULL(COUNT(ISM1.Id),0) AS StatusCount,
			ISNULL(ISM1.InquiryMainStatusId,0) AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM1.Id,ISM1.Title,ISM1.InquiryMainStatusId,AI.OrgId,OM.OrderIndex
			ORDER BY OM.OrderIndex
		 END
		END

	IF(@rType='StatusClassWise')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInquiryMainStatus nvarchar(500)='' 
				IF(@rInquiryMainStatus=11)
				SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId >= 11'
				ELSE IF(@rInquiryMainStatus=21)
				SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId > 11'
				ELSE IF(@rInquiryMainStatus=31)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 21'
				ELSE IF(@rInquiryMainStatus=41)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 31'
				ELSE IF(@rInquiryMainStatus=51)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				ELSE IF(@rInquiryMainStatus=61)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 61 '
				ELSE IF(@rInquiryMainStatus=71)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 61'
				ELSE IF(@rInquiryMainStatus=81)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 81'
				ELSE IF(@rInquiryMainStatus=91)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				ELSE IF(@rInquiryMainStatus=101)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 101'
				ELSE IF(@rInquiryMainStatus=111)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 101'
				ELSE IF(@rInquiryMainStatus = 0)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 0'


				DECLARE @lSQLString nvarchar(max)=''

				SET @lSQLString = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInquiryMainStatus)+' and AI2.ForClassId = CM.Id
							AND BM.IsInContext = 1
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND BM.IsInContext = 1
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							'+CONVERT(nvarchar(500),@lInquiryMainStatus)+'
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex 
							ORDER BY CM.OrderIndex'
							--ORDER BY add for mantis : 0042058

						print @lSQLString

						execute(@lSQLString)
				END
				ELSE 
				BEGIN
						DECLARE @lSQLString1 nvarchar(max)=''

						SET @lSQLString1 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								and ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ISM1.InquiryMainStatusId  = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex,ISM1.InquiryMainStatusId
							ORDER BY CM.OrderIndex'
							--ORDER BY add for mantis : 0042058

						print @lSQLString1

						execute(@lSQLString1)
				END
			END

	ELSE IF(@rType='StatusStudentList')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInquiryMainStatusStudent nvarchar(500)='' 
				IF(@rInquiryMainStatus=11)
				SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId >=11'
				ELSE IF(@rInquiryMainStatus=21)
				SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId > 11'
				ELSE IF(@rInquiryMainStatus=31)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 21'
				ELSE IF(@rInquiryMainStatus=41)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 31'
				ELSE IF(@rInquiryMainStatus=51)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				ELSE IF(@rInquiryMainStatus=61)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				ELSE IF(@rInquiryMainStatus=71)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 61'
				ELSE IF(@rInquiryMainStatus=81)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 71 AND ISM.InquiryMainStatusId !=91'
				ELSE IF(@rInquiryMainStatus=91)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				ELSE IF(@rInquiryMainStatus=101)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 91 AND ISM.InquiryMainStatusId !=111'
				ELSE IF(@rInquiryMainStatus=111)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 101'
				ELSE IF(@rInquiryMainStatus=0)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId = 0'

				DECLARE @lSQLStduentList nvarchar(max)=''

				SET @lSQLStduentList = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
		
							SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
								sAdmission.tAdmissionInquiry AI 
								INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
								INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
								LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
								INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
								LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
								WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInquiryMainStatusStudent)+'
								AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
								AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
								AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
								AND BM.IsInContext = 1
								GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					--print @lSQLStduentList

					execute(@lSQLStduentList)

					END
					ELSE
					BEGIN	
						DECLARE @lSQLStduentList1 nvarchar(max)=''

						SET @lSQLStduentList1 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
								INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
								SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
								FROM
									sSetup.tOrganizationMaster OM
									INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
								WHERE 
									((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
									AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
								GROUP BY
									OM.Id
		
								DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
								INSERT INTO @lTempBatchId (OrgId , BatchId)
								SELECT 
									BM.OrgId AS OrgId,
									BM.Id AS BatchId
								FROM 
									sSetup.tBatchMaster BM
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
									--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
								WHERE
									BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
		
		
									SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
										sAdmission.tAdmissionInquiry AI 
										INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
										INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
										INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
										INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
										INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
										LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
										INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
										LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
										WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
										 AND ISM.InquiryMainStatusId = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
										AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
										AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
										AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
										AND BM.IsInContext = 1
										GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					print @lSQLStduentList1

						execute(@lSQLStduentList1)
			END
		END

    ELSE IF(@rType='NotDoneStatusClassWise')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInqMainStatus nvarchar(500)='' 
				SET  @lInqMainStatus = 'AND ISM.Id =' + CONVERT(nvarchar,@rInquiryStatusId)
				--IF(@rInquiryMainStatus=11)
				--SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId >= 11'
				--ELSE IF(@rInquiryMainStatus=21)
				--SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId > 11'
				--ELSE IF(@rInquiryMainStatus=31)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 21'
				--ELSE IF(@rInquiryMainStatus=41)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 31'
				--ELSE IF(@rInquiryMainStatus=51)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				--ELSE IF(@rInquiryMainStatus=61)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 61 '
				--ELSE IF(@rInquiryMainStatus=71)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 61'
				--ELSE IF(@rInquiryMainStatus=81)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 81'
				--ELSE IF(@rInquiryMainStatus=91)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				--ELSE IF(@rInquiryMainStatus=101)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 101'
				--ELSE IF(@rInquiryMainStatus=111)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLString3 nvarchar(max)=''

				SET @lSQLString3 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInqMainStatus)+' and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							'+CONVERT(nvarchar(500),@lInqMainStatus)+'
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex '

						print @lSQLString3

						execute(@lSQLString3)
				END
				ELSE 
				BEGIN
						DECLARE @lSQLString4 nvarchar(max)=''

						SET @lSQLString4 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								and ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ISM1.InquiryMainStatusId  = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex,ISM1.InquiryMainStatusId'

						print @lSQLString4

						execute(@lSQLString4)
				END
			END

	ELSE IF(@rType='NotDoneStatusStudentList')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInqMainStatusStudent nvarchar(500)='' 
				 
				SET  @lInqMainStatusStudent = 'AND ISM.Id =' + CONVERT(nvarchar,@rInquiryStatusId)
				--IF(@rInquiryMainStatus=11)
				--SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId >=11'
				--ELSE IF(@rInquiryMainStatus=21)
				--SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId > 11'
				--ELSE IF(@rInquiryMainStatus=31)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 21'
				--ELSE IF(@rInquiryMainStatus=41)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 31'
				--ELSE IF(@rInquiryMainStatus=51)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				--ELSE IF(@rInquiryMainStatus=61)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				--ELSE IF(@rInquiryMainStatus=71)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 61'
				--ELSE IF(@rInquiryMainStatus=81)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 71 AND ISM.InquiryMainStatusId !=91'
				--ELSE IF(@rInquiryMainStatus=91)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				--ELSE IF(@rInquiryMainStatus=101)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 91 AND ISM.InquiryMainStatusId !=111'
				--ELSE IF(@rInquiryMainStatus=111)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLStduentList3 nvarchar(max)=''

				SET @lSQLStduentList3 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
		
							SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
								sAdmission.tAdmissionInquiry AI 
								INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
								INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
								LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
								INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
								LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
								WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInqMainStatusStudent)+'
								AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
								AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
								AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
								AND BM.IsInContext = 1
								GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					--print @lSQLStduentList

					execute(@lSQLStduentList3)

					END
					ELSE
					BEGIN	
						DECLARE @lSQLStduentList4 nvarchar(max)=''

						SET @lSQLStduentList4 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
								INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
								SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
								FROM
									sSetup.tOrganizationMaster OM
									INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
								WHERE 
									((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
									AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
								GROUP BY
									OM.Id
		
								DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
								INSERT INTO @lTempBatchId (OrgId , BatchId)
								SELECT 
									BM.OrgId AS OrgId,
									BM.Id AS BatchId
								FROM 
									sSetup.tBatchMaster BM
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
									--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
								WHERE
									BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
		
		
									SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
										sAdmission.tAdmissionInquiry AI 
										INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
										INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
										INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
										INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
										INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
										LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
										INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
										LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
										WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
										 AND ISM.InquiryMainStatusId = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
										AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
										AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
										AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
										AND BM.IsInContext = 1
										GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					print @lSQLStduentList4

						execute(@lSQLStduentList4)
			END
		END
	END


	-- For AdmissionConverted Tab
	IF(@rTypeId = 3)
	BEGIN
		IF(@rType='OrgGroupWise')
		BEGIN
			-- Organization wise Count
			SELECT OrgId, Organization, ISNULL(Inquiry, 0) AS InquiryCount, ISNULL(Form, 0) AS FormCount, (ISNULL([Converted Inquiry], 0) + ISNULL([Converted Form], 0)) AS ConvertedCount
			FROM  
			(
				SELECT 
					ISNULL(OM.Id,0) AS OrgId,
					OM.Title AS Organization,
					'Inquiry' AS Type,
					ISNULL(COUNT(AI.Id),0) AS Total
				FROM sAdmission.tAdmissionInquiry AI 
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					--AND OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
					AND BM.IsInContext = 1
				GROUP BY OM.Id,OM.Title

				UNION ALL

				SELECT 
					OM.Id, 
					OM.Title AS Organization,
					'Form' AS Type,
					COUNT(AF.Id) AS Total
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND BM.IsInContext = 1
				GROUP BY OM.Id, OM.Title

				UNION ALL

				SELECT
					ISNULL(OM.Id,0) AS OrgId,
					OM.Title AS Organization,
					'Converted Inquiry' AS Type,
					COUNT(AI.Id) AS Total
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId AND BM.IsInContext = 1
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
					LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
				WHERE 
					BM.Id = TB.BatchId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					AND ISM.InquiryMainStatusId = 71
					--AND OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
				GROUP BY OM.Id, OM.Title

				UNION ALL

				SELECT 
					OM.Id, 
					OM.Title AS Organization,
					'Converted Form' AS Type,
					COUNT(AF.Id) AS Total
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND AF.StatusId = 208 --Closed
					AND BM.IsInContext = 1
				GROUP BY OM.Id, OM.Title
			   ) AS A
				PIVOT  
				(SUM(Total) FOR [Type] IN ([Inquiry],[Form],[Converted Inquiry],[Converted Form])) AS A1
		END

		IF(@rType='ClassWise')
		BEGIN
			-- Class wise Count
			SELECT ClassId, ClassName, OrderIndex, ISNULL(Inquiry, 0) AS InquiryCount, ISNULL(Form, 0) AS FormCount,(ISNULL([Converted Inquiry], 0) + ISNULL([Converted Form], 0)) AS ConvertedCount
			FROM  
			(
				--Inquiry
				SELECT 
					AI.ForClassId AS ClassId, CM.Title AS ClassName, 'Inquiry' AS Type, ISNULL(COUNT(AI.Id),0) AS Total, CM.OrderIndex
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
				WHERE 
					BM.Id = TB.BatchId 
					AND ((CM.OrgId = @rOrgId) OR (@rOrgId=0))
					AND BM.IsInContext = 1				
				Group BY AI.ForClassId,CM.Title,CM.OrderIndex 

				UNION ALL 

				-- Form
				SELECT 
					CM.Id AS ClassId, CM.DisplayTitle AS ClassName, 'Form' AS Type, ISNULL(COUNT(AF.Id),0) AS Total, CM.OrderIndex 
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId		-- Mantis Id : 	0038726	Change condition OM.OrgGroupId = 9911 to  OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
					AND ((CM.OrgId = @rOrgId) OR (@rOrgId=0))
					AND BM.IsInContext = 1
				GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex

				UNION ALL
				
				SELECT 
					AI.ForClassId AS ClassId, CM.Title AS ClassName, 'Converted Inquiry' AS Type, ISNULL(COUNT(AI.Id),0) AS Total, CM.OrderIndex
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
				WHERE 
					BM.Id = TB.BatchId 
					AND ((CM.OrgId = @rOrgId )OR(@rOrgId=0))
					AND ISM.InquiryMainStatusId = 71		
					AND BM.IsInContext = 1	
				Group BY AI.ForClassId,CM.Title,CM.OrderIndex 

				UNION ALL

				SELECT 
					CM.Id AS ClassId, CM.DisplayTitle AS ClassName, 'Converted Form' AS Type, ISNULL(COUNT(AF.Id),0) AS Total, CM.OrderIndex 
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND AF.StatusId = 208 --Closed
					AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
					AND BM.IsInContext = 1
				GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
			)  
			AS A
			PIVOT  
			(SUM(Total) FOR [Type] IN ([Inquiry],[Form],[Converted Inquiry],[Converted Form])) AS A2
			ORDER BY OrderIndex
		END
	END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaAdd]
		 @rId int
		,@rCode nvarchar(20)
		,@rTitle nvarchar(100)
		,@rCreatedDateTime datetime=''
		,@rUpdatedUserId bigint=''
		,@rUpdatedDateTime datetime=''
		,@rCreatedUserId bigint
		,@rOrgId smallint
		,@rIsObsolete bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	

	
 BEGIN TRANSACTION	
 
 IF(@rId = 0)	
	BEGIN
	 
		IF Exists(select Code from sAdmission.tAdmissionCriteriaMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -101 as Result
			RETURN
		END 
	
	
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCriteriaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sAdmission.tAdmissionCriteriaMaster
		(
			 Id
			 ,Code
			 ,Title
			 ,IsObsolete
			,CreatedUserId
			,CreatedDateTime
			,OrgId
		)
	VALUES
		(
			 @lNextNumber
			,@rCode
			,@rTitle
			,@rIsObsolete
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rOrgId
		)
		     SELECT 103 AS Result
	END	 
		
	
	 ELSE
	 BEGIN
 
	 	IF Exists(select Id from sAdmission.tAdmissionCriteriaMaster where Code=@rCode AND OrgId=@rOrgId And Id <> @rId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	 
	 
	 SET @lNextNumber = @rId
	    UPDATE sAdmission.tAdmissionCriteriaMaster
	    SET 
			 Code = @rCode
			,Title = @rTitle
			,IsObsolete = @rIsObsolete
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
		 
			
	      WHERE Id = @rId 	   
	 END  
		SELECT 104 AS Result
	
		COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaFeeAdd]
	 
	 	@rBatchId int,
	 	@rOrgId int,
        @rId int,
        @rClassId int,
        @rFeeNumber  smallint,
        @rFeeName nvarchar(200),
        @rFeeOrder smallint,
		@rFeeAmount decimal(12,2)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId,   'sAdmission.tAdmissionCriteriaFee', 0, 1, 1,@outNextNumber = @lNextNumber output
	select @lNextNumber
	INSERT INTO sAdmission.tAdmissionCriteriaFee
		([Id],[BatchId],[ClassId],[FeeNumber],[FeeName],[FeeOrder],[FeeAmount])
	VALUES
		(@lNextNumber,@rBatchId,@rClassId,@rFeeNumber,@rFeeName,@rFeeOrder,@rFeeAmount)
		     SELECT @lNextNumber AS Result
	
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAdmission.tAdmissionCriteriaFee
	    SET
			BatchId=@rBatchId,
			ClassId=@rClassId,
			FeeNumber=@rFeeNumber,
			FeeName=@rFeeName,
			FeeOrder=@rFeeOrder,
			FeeAmount=@rFeeAmount
	      WHERE Id = @rId
	     SELECT @lNextNumber AS Result
	 END  	

 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaFeeDelete]
@rClassId int,
@rBatchId int
AS
BEGIN
 	 
		DELETE	FROM sAdmission.tAdmissionCriteriaFee WHERE ClassId=@rClassId AND BatchId = @rBatchId
		SELECT 1 AS RESULT
	   
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaFeeGet]
	 
	@rClassId int,
	@rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
	   [Id]
      ,[BatchId]
      ,[ClassId]
      ,[FeeNumber]
      ,[FeeName]
      ,[FeeOrder]
      ,[FeeAmount]
	FROM 
		sAdmission.tAdmissionCriteriaFee
	WHERE 
		ClassId = @rClassId
		AND BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaFormAdd]
		 
	@rId int,
	@rOrgId int,
	@rClassId int,
	@rBatchId int,
	@rFieldRemark nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(1000),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	
 
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCriteriaForm', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sAdmission.tAdmissionCriteriaForm
	(
		Id
		,ClassId
		,BatchId
		,FieldRemark
		,FieldTypeId
		,FieldList
		,IsFieldMandatory
		,FieldGroup
		,FieldOrder
	)
	VALUES
	(
		@lNextNumber
		,@rClassId
		,@rBatchId
		,@rFieldRemark
		,@rFieldTypeId
		,@rFieldList
		,@rIsFieldMandatory
		,@rFieldGroup
		,@rFieldOrder
	)
END	 
ELSE
BEGIN
	SET @lNextNumber = @rId
	
	UPDATE sAdmission.tAdmissionCriteriaForm
	SET 
		FieldRemark = @rFieldRemark
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
	WHERE Id = @rId 	   
END  
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaFormGet]
	 
	@rClassId int,
	@rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		Id,
		ClassId,
		BatchId,
		FieldRemark,
		FieldTypeId,
		FieldList,
		IsFieldMandatory,
		FieldGroup,
		FieldOrder
	FROM 
		sAdmission.tAdmissionCriteriaForm
	WHERE 
		ClassId = @rClassId
		AND BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaGet]
	 
	 @rId int=0,
	 @rCode nvarchar(20)='',
	 @rOrgId smallint,
	 @rTitle nvarchar(20)=''

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	 

BEGIN 
	 
	 
	
	SELECT 
		Id,
		Code,
		Title,
		IsObsolete	 
      
  FROM 
            sAdmission.tAdmissionCriteriaMaster 
			 
  WHERE 
  
		(Code=@rCode) OR (@rCode = '') 
		AND((Id=@rId) OR (@rId =0))
		AND ((Title=@rTitle) OR (@rTitle = ''))
		AND(OrgId=@rOrgId) 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaOnlineGet]
	 @rClassId int = 0,
	 @rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
	   [ClassId]
      ,[BatchId]
      ,[IsValidateBirthdate]
      ,[FromDateOfBirth]
      ,[ToDateOfBirth]
      ,[IsParentAcademicRequired]
      ,[IsStudentAcademicRequired]
      ,[IsFamilyDetailRequired]
      ,[IsSiblingDetailRequired]
      ,[IsReferenceDetailRequired]
      ,[IsFixStudentAcademic]
      ,[StudentAcademicFor]
      ,[StudentAcademicRemark]
      ,[FamilyDetailRemark]
      ,[IsFixParentAcademic]
      ,[ParentAcademicFor]
      ,[ParentAcademicRemark]
      ,[ConfirmationRemark]
      ,[AdmissionFormRemark]
      ,[Reference1]
      ,[Reference2]
      ,[IsOtherInformationRequired]
      ,[IsPayFormFeeOnline]
      ,[FormFeeName]
      ,[FormFeeAmount]
      ,Isnull(IsHostelDetailRequired,0) As IsHostelDetailRequired
      ,Isnull(IsTransportDetailRequired,0) AS IsTransportDetailRequired
      ,Isnull(IsHealthDetailRequired,0) AS IsHealthDetailRequired
      ,Isnull(IsBirthPlaceDetailRequired,0) aS IsBirthPlaceDetailRequired
      ,Isnull(IsAadhaarDetailRequired,0) As IsAadhaarDetailRequired
      ,Isnull(IsBloodGroupDetailRequired,0) As IsBloodGroupDetailRequired,
      Isnull(IsFatherDetail,0) As IsFatherDetail,
      Isnull(IsFatherFullDetail,0) As IsFatherFullDetail,
       Isnull(IsFatherAcademic,0) As IsFatherAcademic,
       Isnull(IsMotherDetail,0) As IsMotherDetail,
        Isnull(IsMotherFullDetail,0) As IsMotherFullDetail,
         Isnull(IsMotherAcademic,0) As IsMotherAcademic,
          Isnull(IsGuardianDetail,0) As IsGuardianDetail,
        Isnull(IsGuardianFullDetail,0) As IsGuardianFullDetail   ,
        Isnull(IsGuardianAcademic,0) As IsGuardianAcademic,
        ISNULL(IsAdmissionFeeBreakup,0) AS IsAdmissionFeeBreakup,
        ISNULL(AdmissionConfirmationRemark,'') As AdmissionConfirmationRemark,
		ISNULL(IsOptionalSubject,0) AS IsOptionalSubject
  FROM sAdmission.tAdmissionCriteria
  WHERE 
		 ((ClassId=@rClassId) OR (@rClassId=0))
		AND BatchId=@rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaOptionalSubjectAdd]
	  
	@rClassId int=0,
	@rBatchId int=0,
	@rStrXml nvarchar(max) = ''
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
SET @rStrXml=REPLACE(@rStrXml,'ANDapos;','&apos;')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
		DELETE FROM [sAdmission].[tAdmissionCriteriaOptionalSubject] WHERE ClassId = @rClassId AND BatchId = @rBatchId
	
		INSERT INTO [sAdmission].[tAdmissionCriteriaOptionalSubject]
		(
			ClassId,
			BatchId,
			ClassSubjectId
		)
		SELECT
			@rClassId,@rBatchId,ClassSubjectId
		FROM
			OPENXML (@loDoc, '/Table/OptionalSubject', 1) WITH 
			( 			
			ClassSubjectId int
			)
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaSetupAdd] 
	 @rClassId INT
	,@rBatchId INT
	,@rIsValidateBirthdate BIT
	,@rFromDateOfBirth DATE
	,@rToDateOfBirth DATE
	,@rIsParentAcademicRequired BIT
	,@rIsStudentAcademicRequired BIT
	,@rIsFamilyDetailRequired BIT
	,@rIsSiblingDetailRequired BIT
	,@rIsReferenceDetailRequired BIT
	,@rIsFixStudentAcademic BIT
	,@rStudentAcademicFor NVARCHAR(300)
	,@rStudentAcademicRemark NVARCHAR(max)
	,@rFamilyDetailRemark NVARCHAR(max)
	,@rIsFixParentAcademic BIT
	,@rParentAcademicFor NVARCHAR(300)
	,@rParentAcademicRemark NVARCHAR(max)
	,@rConfirmationRemark NVARCHAR(max)
	,@rAdmissionFormRemark NVARCHAR(max)
	,@rReference1 NVARCHAR(150)
	,@rReference2 NVARCHAR(150)
	,@rIsOtherInformationRequired BIT
	,@rIsPayFormFeeOnline BIT = NULL
	,@rFormFeeName NVARCHAR(100) = NULL
	,@rFormFeeAmount DECIMAL(12, 2) = NULL
	,@rIsHostelDetailRequired BIT
	,@rIsTransportDetailRequired BIT
	,@rIsHealthDetailRequired BIT
	,@rIsBirthPlaceDetailRequired BIT
	,@rIsAadhaarDetailRequired BIT
	,@rIsBloodGroupDetailRequired BIT
	,@rReceiptBookId INT = NULL
	,@rIsFatherDetail BIT = 0
	,@rIsFatherFullDetail BIT = 0
	,@rIsFatherAcademic BIT = 0
	,@rIsMotherDetail BIT = 0
	,@rIsMotherFullDetail BIT = 0
	,@rIsMotherAcademic BIT = 0
	,@rIsGuardianDetail BIT = 0
	,@rIsGuardianFullDetail BIT = 0
	,@rIsGuardianAcademic BIT = 0
	,@rIsPublish BIT = 0
	,@rIsCustomField1Required BIT = 0
	,@rCustomField1Remark NVARCHAR(500) = NULL
	,@rCustomField1TypeId INT = 0
	,@rCustomField1List NVARCHAR(500) = NULL
	,@rIsCustomField1Mandatory BIT = 0
	,@rIsCustomField2Required BIT = 0
	,@rCustomField2Remark NVARCHAR(500) = NULL
	,@rCustomField2TypeId INT = 0
	,@rCustomField2List NVARCHAR(500) = NULL
	,@rIsCustomField2Mandatory BIT = 0
	,@rIsCustomField3Required BIT = 0
	,@rCustomField3Remark NVARCHAR(500) = NULL
	,@rCustomField3TypeId INT = 0
	,@rCustomField3List NVARCHAR(500) = NULL
	,@rIsCustomField3Mandatory BIT = 0
	,@rIsAdmissionFeeBreakup BIT = 0
	,@rAgeCutOffDate DATE
	,@rExtraRemark1 NVARCHAR(max) = NULL
	,@rExtraRemark2 NVARCHAR(max) = NULL
	,@rExtraRemark3 NVARCHAR(max) = NULL
	,@rAdmissionInquiryRemark NVARCHAR(max)
	,@rAdmissionConfirmationRemark NVARCHAR(max)
	,@rIsSendMailFormAttachment BIT = 0
	,@rIsOptionalSubject BIT = 0
	,@rOnlineAdmissionField NVARCHAR(MAX) = ''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--BEGIN TRY
	IF (@rIsPublish = 1)
	BEGIN
		UPDATE sAdmission.tAdmissionCriteria
		SET IsPublish = 0
		WHERE ClassId = @rClassId
	END

	--BEGIN TRANSACTION	
	IF (@rFormFeeAmount = 0)
		SET @rFormFeeAmount = NULL

	DELETE FROM sAdmission.tAdmissionCriteria
	WHERE ClassId = @rClassId AND BatchId = @rBatchId

	INSERT INTO sAdmission.tAdmissionCriteria (
		ClassId
		,BatchId
		,IsValidateBirthdate
		,FromDateOfBirth
		,ToDateOfBirth
		,IsParentAcademicRequired
		,IsStudentAcademicRequired
		,IsFamilyDetailRequired
		,IsSiblingDetailRequired
		,IsReferenceDetailRequired
		,IsFixStudentAcademic
		,StudentAcademicFor
		,StudentAcademicRemark
		,FamilyDetailRemark
		,IsFixParentAcademic
		,ParentAcademicFor
		,ParentAcademicRemark
		,ConfirmationRemark
		,AdmissionFormRemark
		,Reference1
		,Reference2
		,IsOtherInformationRequired
		,IsPayFormFeeOnline
		,FormFeeName
		,FormFeeAmount
		,IsHostelDetailRequired
		,IsTransportDetailRequired
		,IsHealthDetailRequired
		,IsBirthPlaceDetailRequired
		,IsAadhaarDetailRequired
		,IsBloodGroupDetailRequired
		,ReceiptBookId
		,IsFatherDetail
		,IsFatherFullDetail
		,IsFatherAcademic
		,IsMotherDetail
		,IsMotherFullDetail
		,IsMotherAcademic
		,IsGuardianDetail
		,IsGuardianFullDetail
		,IsGuardianAcademic
		,IsPublish
		,IsCustomField1Required
		,CustomField1Remark
		,CustomField1TypeId
		,CustomField1List
		,IsCustomField1Mandatory
		,IsCustomField2Required
		,CustomField2Remark
		,CustomField2TypeId
		,CustomField2List
		,IsCustomField2Mandatory
		,IsCustomField3Required
		,CustomField3Remark
		,CustomField3TypeId
		,CustomField3List
		,IsCustomField3Mandatory
		,IsAdmissionFeeBreakup
		,AgeCutOffDate
		,Remark1
		,Remark2
		,Remark3
		,AdmissionInquiryRemark
		,AdmissionConfirmationRemark
		,IsSendMailFormAttachment
		,IsOptionalSubject
		,OnlineAdmissionField
		)
	VALUES (
		@rClassId
		,@rBatchId
		,@rIsValidateBirthdate
		,@rFromDateOfBirth
		,@rToDateOfBirth
		,@rIsParentAcademicRequired
		,@rIsStudentAcademicRequired
		,@rIsFamilyDetailRequired
		,@rIsSiblingDetailRequired
		,@rIsReferenceDetailRequired
		,@rIsFixStudentAcademic
		,@rStudentAcademicFor
		,@rStudentAcademicRemark
		,@rFamilyDetailRemark
		,@rIsFixParentAcademic
		,@rParentAcademicFor
		,@rParentAcademicRemark
		,@rConfirmationRemark
		,@rAdmissionFormRemark
		,@rReference1
		,@rReference2
		,@rIsOtherInformationRequired
		,@rIsPayFormFeeOnline
		,@rFormFeeName
		,@rFormFeeAmount
		,@rIsHostelDetailRequired
		,@rIsTransportDetailRequired
		,@rIsHealthDetailRequired
		,@rIsBirthPlaceDetailRequired
		,@rIsAadhaarDetailRequired
		,@rIsBloodGroupDetailRequired
		,@rReceiptBookId
		,@rIsFatherDetail
		,@rIsFatherFullDetail
		,@rIsFatherAcademic
		,@rIsMotherDetail
		,@rIsMotherFullDetail
		,@rIsMotherAcademic
		,@rIsGuardianDetail
		,@rIsGuardianFullDetail
		,@rIsGuardianAcademic
		,@rIsPublish
		,@rIsCustomField1Required
		,@rCustomField1Remark
		,@rCustomField1TypeId
		,@rCustomField1List
		,@rIsCustomField1Mandatory
		,@rIsCustomField2Required
		,@rCustomField2Remark
		,@rCustomField2TypeId
		,@rCustomField2List
		,@rIsCustomField2Mandatory
		,@rIsCustomField3Required
		,@rCustomField3Remark
		,@rCustomField3TypeId
		,@rCustomField3List
		,@rIsCustomField3Mandatory
		,@rIsAdmissionFeeBreakup
		,@rAgeCutOffDate
		,@rExtraRemark1
		,@rExtraRemark2
		,@rExtraRemark3
		,@rAdmissionInquiryRemark
		,@rAdmissionConfirmationRemark
		,@rIsSendMailFormAttachment
		,@rIsOptionalSubject
		,@rOnlineAdmissionField
		)

	SELECT 103 AS Result
		--COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaSetupDelete]
@rClassId int,
@rBatchId int
AS
BEGIN
 	 
		DELETE	FROM sAdmission.tAdmissionCriteria WHERE ClassId=@rClassId AND BatchId = @rBatchId
		SELECT 1 AS RESULT
	   
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaSetupGet] 
	 @rClassId INT = 0
	,@rBatchId INT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		 ClassId
		,BatchId
		,ISNULL(IsValidateBirthdate, '') AS IsValidateBirthdate
		,ISNULL(FromDateOfBirth, '') AS FromDateOfBirth
		,ISNULL(ToDateOfBirth, '') AS ToDateOfBirth
		,ISNULL(IsParentAcademicRequired, '') AS IsParentAcademicRequired
		,ISNULL(IsStudentAcademicRequired, '') AS IsStudentAcademicRequired
		,ISNULL(IsFamilyDetailRequired, '') AS IsFamilyDetailRequired
		,ISNULL(IsSiblingDetailRequired, '') AS IsSiblingDetailRequired
		,ISNULL(IsReferenceDetailRequired, '') AS IsReferenceDetailRequired
		,ISNULL(IsFixStudentAcademic, '') AS IsFixStudentAcademic
		,StudentAcademicFor
		,StudentAcademicRemark
		,FamilyDetailRemark
		,ISNULL(IsFixParentAcademic, '') AS IsFixParentAcademic
		,ParentAcademicFor
		,ParentAcademicRemark
		,ConfirmationRemark
		,AdmissionFormRemark
		,ISNULL(Reference1, '') AS Reference1
		,ISNULL(Reference2, '') AS Reference2
		,ISNULL(IsOtherInformationRequired, 0) AS IsOtherInformationRequired
		,ISNULL(IsPayFormFeeOnline, 0) AS IsPayFormFeeOnline
		,ISNULL(FormFeeName, '') AS FormFeeName
		,ISNULL(FormFeeAmount, 0) AS FormFeeAmount
		,ISNULL(IsHostelDetailRequired, 0) AS IsHostelDetailRequired
		,ISNULL(IsTransportDetailRequired, 0) AS IsTransportDetailRequired
		,ISNULL(IsHealthDetailRequired, 0) AS IsHealthDetailRequired
		,ISNULL(IsBirthPlaceDetailRequired, 0) AS IsBirthPlaceDetailRequired
		,ISNULL(IsAadhaarDetailRequired, 0) AS IsAadhaarDetailRequired
		,ISNULL(IsBloodGroupDetailRequired, 0) AS IsBloodGroupDetailRequired
		,ISNULL(ReceiptBookId, 0) AS ReceiptBookId
		,ISNULL(IsFatherDetail, 0) AS IsFatherDetail
		,ISNULL(IsFatherFullDetail, 0) AS IsFatherFullDetail
		,ISNULL(IsFatherAcademic, 0) AS IsFatherAcademic
		,ISNULL(IsMotherDetail, 0) AS IsMotherDetail
		,ISNULL(IsMotherFullDetail, 0) AS IsMotherFullDetail
		,ISNULL(IsMotherAcademic, 0) AS IsMotherAcademic
		,ISNULL(IsGuardianDetail, 0) AS IsGuardianDetail
		,ISNULL(IsGuardianFullDetail, 0) AS IsGuardianFullDetail
		,ISNULL(IsGuardianAcademic, 0) AS IsGuardianAcademic
		,ISNULL(IsPublish, 0) AS IsPublish
		,ISNULL(IsCustomField1Required, 0) AS IsCustomField1Required
		,ISNULL(CustomField1Remark, '') AS CustomField1Remark
		,ISNULL(CustomField1TypeId, 0) AS CustomField1TypeId
		,ISNULL(CustomField1List, '') AS CustomField1List
		,ISNULL(IsCustomField1Mandatory, 0) AS IsCustomField1Mandatory
		,ISNULL(IsCustomField2Required, 0) AS IsCustomField2Required
		,ISNULL(CustomField2Remark, '') AS CustomField2Remark
		,ISNULL(CustomField2TypeId, 0) AS CustomField2TypeId
		,ISNULL(CustomField2List, '') AS CustomField2List
		,ISNULL(IsCustomField2Mandatory, 0) AS IsCustomField2Mandatory
		,ISNULL(IsCustomField3Required, 0) AS IsCustomField3Required
		,ISNULL(CustomField3Remark, '') AS CustomField3Remark
		,ISNULL(CustomField3TypeId, 0) AS CustomField3TypeId
		,ISNULL(CustomField3List, '') AS CustomField3List
		,ISNULL(IsCustomField3Mandatory, 0) AS IsCustomField3Mandatory
		,ISNULL(IsAdmissionFeeBreakup, 0) AS IsAdmissionFeeBreakup
		,ISNULL(AgeCutOffDate, '') AS AgeCutOffDate
		,ISNULL(Remark1, '') AS ExtraRemark1
		,ISNULL(Remark2, '') AS ExtraRemark2
		,ISNULL(Remark3, '') AS ExtraRemark3
		,ISNULL(AdmissionInquiryRemark, '') AS AdmissionInquiryRemark
		,ISNULL(AdmissionConfirmationRemark, '') AS AdmissionConfirmationRemark
		,ISNULL(IsSendMailFormAttachment, 0) AS IsSendMailFormAttachment
		,ISNULL(IsOptionalSubject, 0) AS IsOptionalSubject
		,ISNULL(OnlineAdmissionField, '') AS OnlineAdmissionField
	
	FROM sAdmission.tAdmissionCriteria
	
	WHERE (ClassId = @rClassId)
		AND BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionCustomSearchGet]
	
	@rPageIndex int = null, 
	@rOrgId smallint,
	@rBatchId int,
	@rClassId int,
	@rClassIds nvarchar(max)='',
	@rFormNo nvarchar(max)='',
	@rFromFormNo nvarchar(max)='',
	@rToFormNo nvarchar(max)='',
	@rStatusId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rDOBFromDate Date = '',
	@rDOBToDate Date = '',
	@rDOAFromDate Date = '',
	@rDOAToDate Date = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rContactNo nvarchar(50) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rNationality nvarchar(max) = '',
	@rMotherTongue nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = ''
AS
BEGIN
 
	SET NOCOUNT ON;

   IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9990-12-31'
	IF(@rDOAFromDate IS NULL)
		SET @rDOAFromDate='0001-01-01'
	IF(@rDOAToDate IS NULL)
		SET @rDOAToDate='9990-12-31'

	If @rDOBToDate <> '9999-12-31'
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)
	If @rDOAToDate <> '9999-12-31'
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)

		SELECT * INTO #MyAdmissionSearchList
	FROM
	(SELECT OM.Title AS Organization, BM.Title AS Batch, AF.FormNo AS FormNo, AF.FirstName + ' '+  AF.LastName AS Name,CM.Title AS Class,
		SM.Title as Status, AF.Id as AdmissionId, AF.BatchId as BatchId,ROW_NUMBER() OVER (ORDER BY FormNo asc) as RowIndex
		from sAdmission.tAdmissionForm AF		
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN  sCommon.tStatusMaster SM ON AF.StatusId = SM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFD ON AFD.AdmissionFormId = AF.Id
		WHERE ((AF.OrgId = @rOrgId ) OR (@rOrgId = 0))
				AND ((AF.BatchId = @rBatchId) OR (@rBatchId = 0))
				AND ((AF.ForClassId = @rClassId) OR (@rClassId = 0))
				AND ((ISNULL(AF.ForClassId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rClassIds,',')) OR (@rClassIds='')))
				AND ((AF.FormNo = @rFormNo) OR (@rFormNo = ''))
				AND ((AF.FormNo  >= @rFromFormNo) OR (ISNULL(@rFromFormNo,'') = ''))
				AND (( AF.FormNo  <= @rToFormNo) OR (ISNULL(@rToFormNo,'') = ''))
				AND (AF.StatusId = @rStatusId)
				AND ((AF.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
				AND ((AF.LastName Like @rLastName + '%') OR (@rLastName = ''))
				AND ((AFD.FatherName like @rFatherName+'%') OR (@rFatherName=''))
				AND ((AFD.MotherName like @rMotherName+'%') OR (@rMotherName=''))
				AND (( AF.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND (( AF.DateOfBirth  <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
				AND ((Convert(nvarchar(12),AF.CreatedDateTime) >=  @rDOAFromDate) OR (@rDOAFromDate=''))
				AND ((Convert(nvarchar(12),AF.CreatedDateTime) <=  @rDOAToDate) OR (@rDOAToDate=''))
				AND ((ISNULL(AF.Country,'') Like @rCountry + '%')OR(@rCountry = ''))
				AND ((ISNULL(AF.State,'') Like @rState + '%')OR(@rState = ''))
				AND ((ISNULL(AF.City,'') Like @rCity + '%')OR(@rCity = ''))
				AND ((AF.ContactNo=@rContactNo) OR (@rContactNo=0))
				AND (ISNULL(AF.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND (ISNULL(AF.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
				AND (ISNULL(AF.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
				AND ((AF.Nationality Like '%' + @rNationality+ '%') OR (@rNationality = ''))
				AND (ISNULL(AF.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
				AND ((AF.MotherTongue Like '%' + @rMotherTongue+ '%') OR (@rMotherTongue = ''))
				AND ((AF.PreviousSchool Like '%' + @rPreviousSchool+ '%') OR (@rPreviousSchool = ''))
				AND ((AFD.FatherQualification Like '%' + @rFatherQualification+ '%') OR (@rFatherQualification = ''))
				AND ((AFD.MotherQualification Like '%' + @rMotherQualification+ '%') OR (@rMotherQualification = ''))
				AND ((AFD.FatherOccupation Like '%' + @rFatherOccupation+ '%') OR (@rFatherOccupation = ''))
				AND ((AFD.MotherOccupation Like '%' + @rMotherOccupation+ '%') OR (@rMotherOccupation = ''))
				) AS AdmissionCustomSearch

			select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
			print(@rPageIndex)
			declare @lTotalRecords int, @lPageSize int = 10, @lResult nvarchar(max) = '', @lPaging nvarchar(max) = ''
			select @lTotalRecords = COUNT(*) FROM #MyAdmissionSearchList
			print(@lTotalRecords)
			select @lPaging = dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
			print(@lPaging)
			
			Select *
			from #MyAdmissionSearchList
			WHERE RowIndex BETWEEN ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
			select @lPaging as Paging,@lTotalRecords as TotalRecords
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 
	 @rOrgGroupId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
  IF(@rType='Organization')
  BEGIN
  SELECT
	(
		SELECT 
			COUNT(AF.Id) FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime)=CONVERT(DATE,GETDATE())
	) AS DailyCount,
	(
		SELECT 
			COUNT(AF.Id) FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))
	) AS YesterdayCount,
	 
	(
		SELECT 
			COUNT(AF.Id) FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
	) AS WeeklyCount,
	(
		SELECT 
			COUNT(AF.Id) FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
	)  AS MonthlyCount
  END
  
  IF(@rType='Class')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT 
			CM.Title AS ClassName, COUNT(AF.Id) AS YesterdayCount FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))
			GROUP BY CM.Title
	END
	IF(@rDay=1)
	BEGIN
		SELECT 
			CM.Title AS ClassName, COUNT(AF.Id) AS DailyCount FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime)=CONVERT(DATE,GETDATE())
			GROUP BY CM.Title
	END
	IF(@rDay=7)
	BEGIN
		SELECT 
			CM.Title AS ClassName, COUNT(AF.Id) AS WeeklyCount FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
			GROUP BY CM.Title
	END
	IF(@rDay=30)
	BEGIN
		SELECT 
			CM.Title AS ClassName, COUNT(AF.Id) AS MonthlyCount FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			GROUP BY CM.Title
	END
  END
  
  IF(@rType='OrgGroup')
  BEGIN
  	IF(@rDay=-1)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization, COUNT(AF.Id) AS YesterdayCount 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))
			GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=1)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization, COUNT(AF.Id) AS DailyCount 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime)=CONVERT(DATE,GETDATE())
			GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=7)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization, COUNT(AF.Id) AS WeeklyCount FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
			GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=30)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization, COUNT(AF.Id) AS MonthlyCount FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND (AF.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AF.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AF.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			GROUP BY OM.Id,OM.DisplayTitle
	END
  END
  
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionDetailsGet]
	
	 @rForClassId int,
	 
	 @rOrgId int,
	 @rFirstName nvarchar(100),
	 @rLastName nvarchar(100),
	 
	 @rMeritMarks decimal(10,2)
	 --@rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	
	SELECT 
			 AF.Id AS AdmissionFormId
			
			,AF.FirstName+' '+ISNULL(AF.MiddleName,'')+' '+AF.LastName AS FullName
			,AF.ForClassId
			,AF.FormNo
			,CM.Title AS ClassName
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			,AF.StatusId
			,ISNULL(SM.Title,'') as StatusName
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.GenderId
			,GM.Title AS Gender
			
			
      
  FROM 
            sAdmission.tAdmissionForm AF
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			
  WHERE 
  
      
    ((AF.FirstName=@rFirstName) OR (@rFirstName=''))
    AND ((AF.LastName=@rLastName) OR (@rLastName=''))
   
	AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	AND AF.OrgId=@rOrgId
	AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
	
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionDocumentAdd]
	 
	 	
        @rDocumentId int,
        @rClassId int,
		@rBatchId int,
		@rRemark nvarchar(1000),
		@rIsMandatory bit
	 	
        

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	DECLARE @rCountId int 

	SET @rCountId = (SELECT ISNULL(COUNT(1),0) FROM sAdmission.tAdmissionCriteriaDocument WHERE [BatchId]=@rBatchId AND [ClassId]=@rClassId AND [SubmitDocumentMasterId]= @rDocumentId)

	BEGIN		
	
	if(@rCountId = 0)
	BEGIN
	INSERT INTO sAdmission.tAdmissionCriteriaDocument
		([BatchId],[ClassId],[SubmitDocumentMasterId],[Remark],[IsMandatory])
	VALUES
		(@rBatchId,@rClassId,@rDocumentId,@rRemark,@rIsMandatory)
		     SELECT 11 AS Result	
	END
	ELSE
		UPDATE sAdmission.tAdmissionCriteriaDocument SET [BatchId]=@rBatchId,[ClassId]=@rClassId,[SubmitDocumentMasterId]=@rDocumentId, [Remark]=@rRemark,IsMandatory=@rIsMandatory
		WHERE [BatchId]=@rBatchId AND [ClassId]=@rClassId AND [SubmitDocumentMasterId]= @rDocumentId

		     SELECT 11 AS Result	 
	END

	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionDocumentGet]
	 
	@rClassId int,
	@rBatchId int,
	@rDocumentId int,
	@rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		ACD.BatchId,ACD.ClassId,ACD.SubmitDocumentMasterId AS DocumentId,SDM.DocumentName,ISNULL(ACD.Remark,'') AS Remark,ISNULL(ACD.IsMandatory,0) IsMandatory 
	FROM 
		sAdmission.tAdmissionCriteriaDocument ACD
		LEFT JOIN sCommon.tSubmitDocumentMaster SDM ON SDM.Id = ACD.SubmitDocumentMasterId and SDM.OrgId=@rOrgId
	WHERE 
		(ACD.ClassId = @rClassId OR ISNULL(@rClassId,0)=0)
		AND (ACD.BatchId = @rBatchId OR ISNULL(@rBatchId,0)=0)
		AND (ACD.SubmitDocumentMasterId = @rDocumentId OR ISNULL(@rDocumentId,0)=0)

		UNION
		SELECT 
		0 BatchId,0 ClassId,Id AS DocumentId,DocumentName,'' AS Remark,CAST('FALSE' as bit) IsMandatory
	FROM 
		sCommon.tSubmitDocumentMaster SDM		
		WHERE  SubmitDocumentFunctionalityId=3 AND ID NOT IN(SELECT SubmitDocumentMasterId FROM sAdmission.tAdmissionCriteriaDocument WHERE ClassId = @rClassId AND  BatchId = @rBatchId )
		AND OrgId=@rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormAdd]
		 @rId bigint
		,@rFormNo int
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName	nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int		 
		,@rDateOfBirth date
		,@rDateOfBirthInWord nvarchar(100)
		,@rOrgId smallint
		,@rBatchId int
		,@rStatusId	smallint
		,@rStreetOne nvarchar(150) --Changed length from 50 to 150 for mantis : 37243
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode	nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10, 2)
		,@rMeritGrade nvarchar(20)
		,@rGenderId	int
		,@rReligionId int
		,@rFamilyCast nvarchar(100)
		,@rFamilySubCast nvarchar(100)
		,@rCastCategoryId int
		,@rCreatedUserId bigint
		,@rFormPassword nvarchar(100)=''
		,@rDataEntryModeId smallint
		,@rDataEntryStatusId smallint
		,@rStudentPhoto varbinary(max),
		 @rNationality nvarchar(150),
		 @rMotherTongue nvarchar(150),
		 @rOtherInformation nvarchar(150),
		 @rIsPysicalDeformity bit,
		 @rPysicalDeformityRemark nvarchar(200),
         @rIsMajorIllness bit,
         @rMajorIllnessRemark nvarchar(200),
         @rIsAllergy bit,
         @rAllergyRemark nvarchar(200),
         @rBirthPlace nvarchar(150),
         @rBirthTaluka nvarchar(150),
         @rBirthDistrict nvarchar(150),
         @rBloodGroupId tinyint,
         @rAdhaarNumber nvarchar(20),
         @rIsHostelRequired bit=0,
		 @rIsTransportRequired bit=0,
		 @rBirthState nvarchar(150)='',
		 @rBirthCountry nvarchar(150)='',
		 @rCustomField1Answer nvarchar(200)='',
		 @rCustomField2Answer nvarchar(200)='',
		 @rCustomField3Answer nvarchar(200)='',
		 --@rFatherAdhaarNumber nvarchar(50) ,
		 @OutAdmissionFormId BIGINT = NULL OUTPUT,
		 @rOriginalStudentPhoto varbinary(max) = null,
		 @rAdmissionDate date='',
		 @rWhatsappContactNo nvarchar(20) = '' -- Added column of WhatsappContact for mantis : 29772
		 ,@rPENNumber bigint = 0 --mantis : 0043425
		,@rApaarIdNumber nvarchar(50) = '' --mantis : 0043425
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	

	
 --BEGIN TRANSACTION	
 DECLARE @lNextNumber BIGINT
 DECLARE @lBIGID BIGINT
 DECLARE @lSMALLID INT
 
 IF(@rId = 0)	
	BEGIN
	
	
	
		IF Exists(select FormNo from sAdmission.tAdmissionForm where FormNo=@rFormNo AND BatchId=@rBatchId)
			BEGIN
			select -101 as Result
			RETURN
		END 
	
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2006,@rStoreLocationId = 0, @rNextNumber  = @rFormNo OUTPUT

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

	--	IF @rFormNo = '-300'
	--  BEGIN
	--	SELECT -300 AS Result, '' AS Number, 0 AS Id 
	--	RETURN
	--  END
	IF(@rFormNo = 0)
	BEGIN
	SELECT @rFormNo = ISNULL(MAX(FormNo),0) + 1 FROM sAdmission.tAdmissionForm WHERE BatchId=@rBatchId
	
	END
	
	IF(@rFormPassword = '')
	BEGIN
	SELECT @rFormPassword = @rFormNo
	
	END
	
	
	BEGIN TRANSACTION	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionForm', 0, 1, 1,@outNextNumber = @lNextNumber output
	
--SET	 @lBIGID  = @lNextNumber
--SET	 @lSMALLID  = CONVERT(int, @lBIGID)
	-- IF(@rFormNo = 0)
	-- BEGIN
	-- select convert(int,@lNextNumber)
	--SET @rFormNo = ISNULL(@rFormNo,@lNextNumber)
	--END

	INSERT INTO sAdmission.tAdmissionForm
		(
			 Id
			,FormNo
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,DateOfBirthInWord
			,OrgId
			,BatchId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,GenderId
			,ReligionId
			,FamilyCast
			,FamilySubCast
			,CastCategoryId
			,CreatedUserId
			,CreatedDateTime
			,FormPassword
			,DataEntryModeId
			,DataEntryStatusId
			,StudentPhoto,
			Nationality,
			MotherTongue,
			OtherInformation,
			IsPysicalDeformity,
           PysicalDeformityRemark,
           IsMajorIllness,
           MajorIllnessRemark,
           IsAllergy,
           AllergyRemark,
           BirthPlace,
         BirthTaluka,
         BirthDistrict,
         BloodGroupId,
         AdhaarNumber,
         IsHostelRequired,
         IsTransportRequired,
         BirthState,
         BirthCountry,
         CustomField1Answer,
         CustomField2Answer,
         CustomField3Answer,
		 OriginalStudentPhoto,
		 AdmissionDate,
		 WhatsappContactNo -- Added column of WhatsappContact for mantis : 29772
         --FatherAdhaarNumber
		 ,PENNumber
		 ,ApaarIdNumber
		)
	VALUES
		(
			 @lNextNumber
			,@rFormNo
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId			 
			,@rForBatchId
			,@rDateOfBirth
			,@rDateOfBirthInWord
			,@rOrgId
			,@rBatchId
			,@rStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rGenderId
			,@rReligionId
			,@rFamilyCast
			,@rFamilySubCast
			,@rCastCategoryId
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rFormPassword
			,@rDataEntryModeId
			,@rDataEntryStatusId
			,@rStudentPhoto,
			@rNationality,
			@rMotherTongue,
			@rOtherInformation,
			@rIsPysicalDeformity,
			   @rPysicalDeformityRemark,
			   @rIsMajorIllness,
			   @rMajorIllnessRemark,
			   @rIsAllergy,
			   @rAllergyRemark,
			  @rBirthPlace,
			 @rBirthTaluka,
			 @rBirthDistrict,
			 @rBloodGroupId,
			 @rAdhaarNumber,
			 @rIsHostelRequired,
			 @rIsTransportRequired,
			 @rBirthState,
			@rBirthCountry,
			 @rCustomField1Answer,
			 @rCustomField2Answer,
			 @rCustomField3Answer,
			 @rOriginalStudentPhoto,
			 @rAdmissionDate,
			 @rWhatsappContactNo -- Added column of WhatsappContact for mantis : 29772
			 --@rFatherAdhaarNumber
			,@rPENNumber
			,@rApaarIdNumber
		)
		             
	END	 
	 ELSE
	 BEGIN
	 
	 
	 
	 	IF Exists(select FormNo from sAdmission.tAdmissionForm where FormNo=@rFormNo AND BatchId=@rBatchId And Id <> @rId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		
	 BEGIN TRANSACTION	
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionForm
	    SET
	        FormNo = @rFormNo
			,FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId			
			,DateOfBirth=@rDateOfBirth
			,DateOfBirthInWord=@rDateOfBirthInWord
			,StatusId=@rStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,GenderId=@rGenderId
			,ReligionId=@rReligionId
			,FamilyCast=@rFamilyCast
			,FamilySubCast=@rFamilySubCast
			,CastCategoryId=@rCastCategoryId
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			--,DataEntryModeId = @rDataEntryModeId
			--,DataEntryStatusId = @rDataEntryStatusId
			,StudentPhoto = @rStudentPhoto,
			Nationality =@rNationality,
			MotherTongue=@rMotherTongue,
			OtherInformation=@rOtherInformation,
			IsPysicalDeformity=@rIsPysicalDeformity,
           PysicalDeformityRemark=@rPysicalDeformityRemark,
           IsMajorIllness=@rIsMajorIllness,
           MajorIllnessRemark=@rMajorIllnessRemark,
           IsAllergy=@rIsAllergy,
           AllergyRemark=@rAllergyRemark,
           BirthPlace=@rBirthPlace,
		   BirthTaluka=@rBirthTaluka,
			BirthDistrict=@rBirthDistrict,
			BloodGroupId=@rBloodGroupId,
			AdhaarNumber=@rAdhaarNumber,
			IsHostelRequired= @rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired,
			BirthState=@rBirthState,
			BirthCountry=@rBirthCountry,
			CustomField1Answer=@rCustomField1Answer,
			CustomField2Answer=@rCustomField2Answer,
			CustomField3Answer=@rCustomField3Answer,
			OriginalStudentPhoto=@rOriginalStudentPhoto,
			AdmissionDate=@rAdmissionDate,
			WhatsappContactNo = @rWhatsappContactNo  -- Added column of WhatsappContact for mantis : 29772
			--FatherAdhaarNumber = @rFatherAdhaarNumber
			,PENNumber=@rPENNumber
			,ApaarIdNumber = @rApaarIdNumber
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	SET @OutAdmissionFormId=@lNextNumber
		COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormConfirmGet]
	 @rAdmissionFormId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
			iSNULL(AF.Id,0) as Id,
			AF.FormNo,
			AF.FirstName,
			AF.MiddleName,
			AF.LastName,
			AF.ForClassId,
			iSNULL(AF.ForBatchId, 0) as ForBatchId,
			AF.ForBatch,
			AF.DateOfBirth,
			AF.DateOfBirthInWord,
			AF.OrgId,
			AF.BatchId,
			AF.StatusId,
			AF.StreetOne,
			AF.StreetTwo,
			AF.StreetThree,
			AF.Country,
			AF.State,
			AF.City,
			AF.ZipCode,
			AF.ContactNo,
			AF.ContactEmail,
			AF.Remark,
			AF.PreviousSchool,
			AF.MeritMarks,
			AF.MeritGrade,
			iSNULL(AF.GenderId,0) as GenderId,
			iSNULL(AF.ReligionId,0) as ReligionId ,
			AF.FamilyCast,
			AF.FamilySubCast,
			iSNULL(AF.CastCategoryId,0) as CastCategoryId,
			AF.CreatedUserId,
			AF.CreatedDateTime,
			iSNULL(AF.UpdatedUserId,0) aS UpdatedUserId,
			AF.UpdatedDateTime,
			iSNULL(AF.StudentId,0) as StudentId,
			AF.FormPassword,
			iSNULL(AF.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(AF.DataEntryStatusId,0) as DataEntryStatusId,
			AF.StudentPhoto,
			iSNULL(AF.AdmissionCategoryId,0) AS AdmissionCategoryId,
			AF.Nationality,
			AF.MotherTongue,
			AF.OtherInformation,
			iSNULL(AF.IsPysicalDeformity,0) aS IsPysicalDeformity ,
			AF.PysicalDeformityRemark,
			iSNULL(AF.IsMajorIllness,0) aS IsMajorIllness ,
			AF.MajorIllnessRemark,
			iSNULL(AF.IsAllergy,0) aS IsAllergy,
			AF.AllergyRemark,
			AF.BirthPlace,
			AF.BirthTaluka,
			AF.BirthDistrict,
			iSNULL(AF.BloodGroupId,0) AS  BloodGroupId,
			AF.AdhaarNumber,
			iSNULL(AF.IsHostelRequired,0) as IsHostelRequired,
			iSNULL(AF.IsTransportRequired,0) as IsTransportRequired,
			AF.BirthState,
			AF.BirthCountry,
			OM.Title AS SchoolName,
			BM.Title AS BatchName,
			CM.Title AS ClassName,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			BGM.Title AS BloodGroup,
			ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,
			ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,
			ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
			AF.WhatsappContactNo -- Change done for mantis 29772
			,ISNULL(AF.PENNumber,0) AS PENNumber  --mantis : 0043425
			,ISNULL(AF.ApaarIdNumber,'') AS ApaarIdNumber  --mantis : 0043425
  FROM
   sAdmission.tAdmissionForm AF
   LEFT JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 
   LEFT JOIN sSetup.tBatchMaster BM ON AF.BatchId=BM.Id 
   LEFT JOIN sSetup.tClassMaster CM ON AF.ForClassId = CM.Id 
   LEFT JOIN sCommon.tGenderMaster GM ON AF.GenderId = GM.Id
    LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = AF.ReligionId 
    LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = AF.CastCategoryId 
    LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = AF.BloodGroupId
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
       
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION SD			 
			--Delete from sSecurity.tUserAccess where SourceId=@rId AND SourceTypeId = 2019
			Delete from sAdmission.tAdmissionFormFamilyDetail where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionFormParentAcademic where AdmissionFormId = @rid
			Delete from sAdmission.tAdmissionFormReference where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionFormSelected where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionFormSibling where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionFormStudentAcademic where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionSetupStudent where AdmissionFormId = @rId
			Delete from sAdmission.tAdmissionForm where Id=@rId
			Delete from sAdmission.tAdmissionFormField where AdmissionFormId =  @rId 
			DELETE FROM sAdmission.tAdmissionOptionalSubject WHERE AdmissionFormId = @rId 
			
			
			
		 
		COMMIT TRANSACTION	SD
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION SD
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormFamilyDetailAdd]
		 @rId bigint,
		 @rFatherName nvarchar(100),
		 @rFatherDateOfBirth date,
		 @rFatherOccupation nvarchar(50),
		 @rFatherQualification nvarchar(50),
		 @rFatherContactNo nvarchar(50),
		 @rFatherMail nvarchar(50),
		 @rFatherOfficeAddress nvarchar(300),
		 @rFatherIncome int,

		 
		 @rMotherName nvarchar(100),
		 @rMotherDateOfBirth date,
		 @rMotherOccupation nvarchar(50),
		 @rMotherQualification nvarchar(50),
		 @rMotherContactNo nvarchar(50),
		 @rMotherMail nvarchar(50),
		 @rMotherOfficeAddress nvarchar(300),
		 @rMotherIncome int,

		
		 @rRelationshipName nvarchar(100),
		 @rGuardianName nvarchar(100),
		 @rGuardianDateOfBirth date,
		 @rGuardianOccupation nvarchar(50),
		 @rGuardianQualification nvarchar(50),
		 @rGuardianContactNo nvarchar(50),
		 @rGuardianMail nvarchar(50),
		 @rGuardianOfficeAddress nvarchar(300),
		 @rGuardianIncome int,
		 @rCreatedUserId bigint,
		 @rCreatedDateTime date,
		 --@rUpdatedUserId bigint,
		 --@rUpdatedDateTime date,
		 @rFatherPhoto varbinary(max)=0,
		  @rMotherPhoto varbinary(max)=0,
		 @rGuardianPhoto varbinary(max)=0,
		 @rFatherOrganization nvarchar(200)='',
		 @rFatherDesignation nvarchar(100)='',
		 @rFatherOfficePhone nvarchar(100)='',
		 @rMotherOrganization nvarchar(200)='',
		 @rMotherDesignation nvarchar(100)='',
		 @rMotherOfficePhone nvarchar(100)='',
		 @rRelativeOrganization nvarchar(200)='',
		 @rRelativeDesignation nvarchar(100)='',
		 @rRelativeOfficePhone nvarchar(100)='',
		 @rLiveWithId smallint=0,
		 @rIsFatherExStudent bit=0,
		 @rFatherPassOutYear nvarchar(50)='',
		 @rIsMotherExStudent bit=0,
		 @rMotherPassOutYear nvarchar(50)='',
		 @rIsRelativeExStudent bit=0,
		 @rRelativePassOutYear nvarchar(50)='',
		 @rFatherAdhaarNumber nvarchar(50),
		 @rOriginalFatherPhoto varbinary(max),
		 @rOriginalMotherPhoto varbinary(max),
		 @rOriginalRelativePhoto varbinary(max),
		 @rMotherAadhaarNumber nvarchar(20) = '',
		 @rGuardianAadhaarNumber nvarchar(20) = '',
		 @rFatherPanCard nvarchar(20)='',
		 @rMotherPanCard nvarchar(20)=''
		 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	

	
 BEGIN TRANSACTION	
	
	IF NOT EXISTS (Select AdmissionFormId from sAdmission.tAdmissionFormFamilyDetail where AdmissionFormId = @rId)
	BEGIN
	INSERT INTO sAdmission.tAdmissionFormFamilyDetail
		(
		AdmissionFormId,
		 FatherName,
		 FatherDateOfBirth,
		 FatherOccupation,
		 FatherQualification,
		 FatherContactNo,
		 FatherAdhaarNumber,
		 FatherMail,
		 FatherOfficeAddress,
		 FatherIncome,
		 MotherName,
		 MotherDateOfBirth,
		 MotherOccupation,
		 MotherQualification,
		 MotherContactNo,
		 MotherMail,
		 MotherOfficeAddress,
		 MotherIncome,
		 
		 RelationshipName,
		 RelativeName,
		 RelativeDateOfBirth,
		 RelativeOccupation,
		 RelativeQualification,
		 RelativeContactNo,
		 RelativeMail,
		 RelativeOfficeAddress,
		 RelativeIncome,
		 CreatedUserId,
		 CreatedDateTime,
		 FatherPhoto,
		 MotherPhoto,
		 RelativePhoto,
		 FatherOrganization,
		 FatherDesignation,
		 FatherOfficePhone,
		 MotherOrganization,
		 MotherDesignation,
		 MotherOfficePhone,
		 RelativeOrganization,
		 RelativeDesignation,
		 RelativeOfficePhone,
		 LiveWithId,
		 IsFatherExStudent,
		 FatherPassOutYear,
		 IsMotherExStudent,
		 MotherPassOutYear,
		 IsRelativeExStudent,
		 RelativePassOutYear,
		 OriginalFatherPhoto,
		 OriginalMotherPhoto,
		 OriginalRelativePhoto,
		 MotherAadhaarNumber,
		 RelativeAadhaarNumber,
		 FatherPANCardNumber,
         MotherPANCardNumber
		)
	VALUES
		(
	     @rId,
		 @rFatherName,
		 @rFatherDateOfBirth,
		 @rFatherOccupation,
		 @rFatherQualification,
		 @rFatherContactNo,
		 @rFatherAdhaarNumber,
		 @rFatherMail,
		 @rFatherOfficeAddress,
		 @rFatherIncome,
		 
		 @rMotherName,
		 @rMotherDateOfBirth,
		 @rMotherOccupation,
		 @rMotherQualification,
		 @rMotherContactNo,
		 @rMotherMail,
		 @rMotherOfficeAddress,
		 @rMotherIncome,
		 
		 @rRelationshipName,
		 @rGuardianName,
		 @rGuardianDateOfBirth,
		 @rGuardianOccupation,
		 @rGuardianQualification,
		 @rGuardianContactNo,
		 @rGuardianMail,
		 @rGuardianOfficeAddress,
		 @rGuardianIncome,
		 
		 @rCreatedUserId,
		 @rCreatedDateTime,
		 
		 @rFatherPhoto,
		 @rMotherPhoto,
		 @rGuardianPhoto,
		 @rFatherOrganization,
		 @rFatherDesignation,
		 @rFatherOfficePhone,
		 @rMotherOrganization,
		 @rMotherDesignation,
		 @rMotherOfficePhone,
		 @rRelativeOrganization,
		 @rRelativeDesignation,
		 @rRelativeOfficePhone,
		 @rLiveWithId,
		 @rIsFatherExStudent,
		 @rFatherPassOutYear,
		 @rIsMotherExStudent,
		 @rMotherPassOutYear,
		 @rIsRelativeExStudent,
		 @rRelativePassOutYear,
		 @rOriginalFatherPhoto,
		 @rOriginalMotherPhoto ,
		 @rOriginalRelativePhoto, 
		 @rMotherAadhaarNumber,
		 @rGuardianAadhaarNumber,
		 @rFatherPanCard,
		 @rMotherPanCard
		)
		             
	END	 
	 ELSE
	 BEGIN

	    UPDATE  sAdmission.tAdmissionFormFamilyDetail
	    SET

	     AdmissionFormId = @rId,
		 FatherName = @rFatherName,
		 FatherDateOfBirth = @rFatherDateOfBirth,
		 FatherOccupation = @rFatherOccupation,
		 FatherQualification = @rFatherQualification,
		 FatherContactNo = @rFatherContactNo,
		 FatherAdhaarNumber = @rFatherAdhaarNumber,
		 FatherMail = @rFatherMail,
		 FatherOfficeAddress = @rFatherOfficeAddress,
		 FatherIncome = @rFatherIncome,
		 MotherName = @rMotherName,
		 MotherDateOfBirth = @rMotherDateOfBirth,
		 MotherOccupation = @rMotherOccupation,
		 MotherQualification = @rMotherQualification,
		 MotherContactNo = @rMotherContactNo,
		 MotherMail = @rMotherMail,
		 MotherOfficeAddress = @rMotherOfficeAddress,
		 MotherIncome = @rMotherIncome,
		 RelationshipName = @rRelationshipName,
		 RelativeName = @rGuardianName,
		 RelativeDateOfBirth = @rGuardianDateOfBirth,
		 RelativeOccupation = @rGuardianOccupation,
		 RelativeQualification = @rGuardianQualification,
		 RelativeContactNo = @rGuardianContactNo,
		 RelativeMail = @rGuardianMail,
		 RelativeOfficeAddress = @rGuardianOfficeAddress,
		 RelativeIncome = @rGuardianIncome,
		 UpdatedUserId = @rCreatedUserId,
		 UpdatedDateTime = sCommon.fGetDate(),
		 FatherPhoto = @rFatherPhoto,
		 MotherPhoto = @rMotherPhoto,
		 RelativePhoto = @rGuardianPhoto,
		 FatherOrganization=@rFatherOrganization,
	      FatherDesignation =@rFatherDesignation,
	      FatherOfficePhone=@rFatherOfficePhone,
	      MotherOrganization=@rMotherOrganization,
	      MotherDesignation=@rMotherDesignation,
	    MotherOfficePhone=@rMotherOfficePhone,
	    RelativeOrganization=@rRelativeOrganization,
	    RelativeDesignation=@rRelativeDesignation,
	    RelativeOfficePhone=@rRelativeOfficePhone ,
	    LiveWithId=@rLiveWithId,
	    IsFatherExStudent =@rIsFatherExStudent ,
	    FatherPassOutYear = @rFatherPassOutYear,
	    IsMotherExStudent = @rIsMotherExStudent,
	    MotherPassOutYear = @rMotherPassOutYear,
	    IsRelativeExStudent =@rIsRelativeExStudent,
	    RelativePassOutYear = @rRelativePassOutYear,
	    OriginalFatherPhoto = @rOriginalFatherPhoto,
		OriginalMotherPhoto = @rOriginalMotherPhoto,
		OriginalRelativePhoto = @rOriginalRelativePhoto,
	    MotherAadhaarNumber = @rMotherAadhaarNumber,
		RelativeAadhaarNumber = @rGuardianAadhaarNumber ,
		FatherPANCardNumber = @rFatherPanCard ,
        MotherPANCardNumber	= @rMotherPanCard
	      WHERE AdmissionFormId = @rId 	   
	 END  
		SELECT @rId AS Result
	
		COMMIT TRANSACTION
		
	
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormFeeAdd]
	@rAdmissionFormId bigint,
	@rAdmissionCriteriaFeeId int,
	@rFeeAmount decimal(12,2)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT AdmissionFormId,AdmissionCriteriaFeeId FROM sAdmission.tAdmissionFormFee WHERE AdmissionFormId = @rAdmissionFormId AND  AdmissionCriteriaFeeId=@rAdmissionCriteriaFeeId)	
			BEGIN
				
			--EXECUTE sCommon.pTableRowIdGet @rOrgId,   'sAdmission.tAdmissionFormFee', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sAdmission.tAdmissionFormFee
				(AdmissionFormId,AdmissionCriteriaFeeId,FeeAmount)
			VALUES
				(@rAdmissionFormId,@rAdmissionCriteriaFeeId,@rFeeAmount)
				 SELECT @rAdmissionFormId AS Result
		END	 

	ELSE
		 BEGIN
			UPDATE sAdmission.tAdmissionFormFee
			SET FeeAmount=@rFeeAmount--,AdmissionCriteriaFeeId =@rAdmissionCriteriaFeeId
			WHERE  AdmissionCriteriaFeeId=@rAdmissionCriteriaFeeId AND AdmissionFormId = @rAdmissionFormId
			 SELECT @rAdmissionFormId AS Result
		 END 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormFeeReceiptAdd]
	
			@rOrgId smallint,
			@rSourceTypeId smallint,
			@rSourceId bigint,
			--@rReceiptDate date,
			@rReceiptAmount decimal(12,2),
			@rPayTypeId smallint,
			@rBatchId int,
			@rBankName nvarchar(100)='',
			@rChequeNo nvarchar(40)='',
			@rChequeDate date=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	DECLARE @lNextNumber BIGINT=0
	DECLARE @lReceiptNumber int=0
	
	IF NOT EXISTS(SELECT 1 FROM sAdmission.tAdmissionFormReceipt WHERE SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId)
	BEGIN
	
	--SELECT @lReceiptNumber = COUNT(ISNULL(Id,0)) + 1 FROM sAdmission.tAdmissionFormReceipt WHERE BatchId=@rBatchId
	SELECT @lReceiptNumber = MAX(ReceiptNumber) + 1 FROM sAdmission.tAdmissionFormReceipt WHERE BatchId=@rBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionFormReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAdmission.tAdmissionFormReceipt
		(
			Id,
			SourceTypeId,
			SourceId,
			ReceiptNumber,
			ReceiptDate,
			ReceiptAmount,
			PayTypeId,
			ChequeNo,
			BankName,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ChequeDate
		)
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@lReceiptNumber,
			sCommon.fGetDate(),
			@rReceiptAmount,
			@rPayTypeId,
			@rChequeNo,
			@rBankName,
			@rBatchId,
			0,
			sCommon.fGetDate(),
			0,
			sCommon.fGetDate(),
			@rChequeDate
		)

	SELECT @lNextNumber AS Result
	
	END
	
	--SELECT 0 AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormFieldAdd]
	  
	@rAdmissionFormIdId bigint=0,
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
SET @rStrXml=REPLACE(@rStrXml,'ANDapos;','&apos;')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
		DELETE FROM sAdmission.tAdmissionFormField WHERE AdmissionFormId=@rAdmissionFormIdId
	
		INSERT INTO sAdmission.tAdmissionFormField
		(
			AdmissionFormId,
			AdmissionCriteriaFormId,
			AdmissionFormFieldResponse
		)
		SELECT
			@rAdmissionFormIdId,AdmissionCriteriaFormId,AdmissionFormFieldResponse
		FROM
			OPENXML (@loDoc, '/Table/AdmissionFormField', 1)WITH 
			( 
			AdmissionCriteriaFormId int,
			AdmissionFormFieldResponse nvarchar(1000)
			)
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormGet]

	 @rAdmissionFormId bigint = 0,
	 @rFormNo int,
	 @rForClassId int,
	 @rBatchId int=0,
	 @rStatusId smallint='',
	 @rOrgId int,
	 @rFirstName nvarchar(100),
	 @rLastName nvarchar(100),
	 @rMeritMarks decimal(10,2),
	 @rFromDate datetime= '1900-01-01',
	 @rToDate datetime = '9990-12-31',
	 @rDepartmentId int=0,
	 @rIsTransportFilter int=2,
	 @rIsHostelFilter int=2,
	 @rDataEntryStatusId smallint=0,
	 @rIsCommonSearch bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	SET @rToDate = DATEADD(d,1,@rToDate)		 

BEGIN 
		--IF @rIsSearch = 1
		BEGIN
		SET @rFirstName = ISNULL(@rFirstName,'')
		SET @rLastName = ISNULL(@rLastName,'')
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
		--- Mantis : 0038918 As per To Date Filter Changes to as required. chnages to <= to < sign in filter : By Krunal K Patel.
	SELECT 
			 AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName

			--,AF.FirstName+' '+AF.LastName as Name
			,[sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name

			,AF.ForClassId
			,AF.BatchId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			,AF.DateOfBirthInWord
			,AF.StatusId
			,SM.Title as StatusName
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate
			,ISNULL(AF.StudentId,0) AS StudentId
			,ISNULL(AF.AdmissionDate,'') AS AdmissionDate
			--,AF.StudentPhoto,
			,(CASE WHEN @rIsCommonSearch=0 THEN ISNULL(AF.StudentPhoto,0) ELSE NULL END) AS StudentPhoto
			
			,ISNULL(AFFD.FatherName,'') AS FatherName,
			Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			isnull(AFFD.FatherOrganization,'') as FatherOrganization,
			isnull(AFFD.FatherDesignation,'') as FatherDesignation,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.MotherName,'') AS MotherName,
			iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherOrganization,'') as MotherOrganization,
			isnull(AFFD.MotherDesignation,'') as MotherDesignation,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
			AF.MotherTongue AS MotherTongue,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeOrganization,'') as RelativeOrganization,
			isnull(AFFD.RelativeDesignation,'') as RelativeDesignation,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AF.IsHostelRequired,0) AS IsHostelRequired  ,
			isnull(AF.IsTransportRequired,0) AS IsTransportRequired,
			isnull(AF.BirthPlace,'') AS BirthPlace,
			isnull(AF.BirthTaluka,'') AS BirthTaluka,
			isnull(AF.BirthDistrict,'') AS BirthDistrict,
			isnull(AF.BloodGroupId,0) AS BloodGroupId,
			isnull(AF.AdhaarNumber,'') AS AdhaarNumber,
			isnull(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
			isnull(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			isnull(AF.IsMajorIllness,0) AS IsMajorIllness,
			isnull(AF.MajorIllnessRemark,'') AS MajorIllnessRemark,
			isnull(AF.IsAllergy,0) AS IsAllergy,
			isnull(AF.AllergyRemark,'') AS AllergyRemark,
			isnull(AF.BirthState,'') AS BirthState,
			isnull(AF.BirthCountry,'') AS BirthCountry,
			isnull(SA.PreviousStandard,'') As PreviousStandard,
	        isnull(AFFD.LiveWithId,0) AS LiveWithId,
			--isnull(ASB.SiblingName,'') AS SiblingName,
			--isnull(ASB.SiblingRelation,'')AS SiblingRelation,
			
			--isnull(ASB.SiblingStandard,'') AS SiblingStandard,
			--isnull(ASB.SiblingSchool,'')AS SiblingSchool
			
			 ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,
			 ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,
			 ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
			 SM1.Title AS DataEntryStatus,
			 AF.Nationality,
			 ISNULL(AFFD.FatherAdhaarNumber,'') AS FatherAdhaarNumber,
			 AF.CreatedDateTime AS AdmissionFormDate,
			 ISNULL(AFFD.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
			 ISNULL(AFFD.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
			 ISNULL(AFFD.FatherOfficePhone,'') AS FatherOfficePhone,
			 ISNULL(AFFD.MotherOfficePhone,'') AS MotherOfficePhone,
			 CASE WHEN AF.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode,
			 ISNULL(AF.WhatsappContactNo,'') AS WhatsappContactNo		--add for 29511 mantis
			 ,ISNULL(AF.PENNumber,0) AS PENNumber --0043425	
			 ,ISNULL(AF.ApaarIdNumber,'') AS ApaarIdNumber --0043425	
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sCommon.tStatusMaster SM1 ON SM1.Id=AF.DataEntryStatusId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = AF.StudentId
			 --LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentID=AF.StudentID
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		--AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)>= @rFromDate) OR (@rFromDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)>= @rFromDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime>= @rFromDate) or (@rFromDate=''))
		--AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)< @rToDate) OR (@rToDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)< @rToDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime< @rToDate) or (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
        AND ((ISnull(AF.IsHostelRequired,0)=@rIsHostelFilter ) OR   (ISNULL(@rIsHostelFilter,2)=2) )
	   AND ((ISNUll(AF.IsTransportRequired,0)=@rIsTransportFilter) OR (isnull(@rIsTransportFilter,0) = 2))
	  
 order by AF.FormNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormOnlineGet]  
  @rAdmissionFormId bigint = 0,  
  @rFormNo int,  
  @rOrgId int  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
    
 SELECT   
   iSNULL(Id,0) as id,  
   FormNo,  
   FirstName,  
   MiddleName,  
   LastName,  
   ForClassId,  
   iSNULL(ForBatchId, 0) as ForBatchId,  
   ForBatch,  
   DateOfBirth,  
   DateOfBirthInWord,  
   OrgId,  
   BatchId,  
   StatusId,  
   StreetOne,  
   StreetTwo,  
   StreetThree,  
   Country,  
   State,  
   City,  
   ZipCode,  
   ContactNo,  
   ContactEmail,  
   Remark,  
   PreviousSchool,  
   MeritMarks,  
   MeritGrade,  
   iSNULL(GenderId,0) as GenderId,  
   iSNULL(ReligionId,0) as ReligionId ,  
   FamilyCast,  
   FamilySubCast,  
   iSNULL(CastCategoryId,0) as CastCategoryId,  
   CreatedUserId,  
   CreatedDateTime,  
   iSNULL(UpdatedUserId,0) aS UpdatedUserId,  
   UpdatedDateTime,  
   iSNULL(StudentId,0) as StudentId,  
   FormPassword,  
   iSNULL(DataEntryModeId,0) as DataEntryModeId,  
   iSNULL(DataEntryStatusId,0) as DataEntryStatusId,  
   StudentPhoto,  
   iSNULL(AdmissionCategoryId,0) AS AdmissionCategoryId,  
   Nationality,  
   MotherTongue,  
   OtherInformation,  
   iSNULL(IsPysicalDeformity,0) aS IsPysicalDeformity ,  
   PysicalDeformityRemark,  
   iSNULL(IsMajorIllness,0) aS IsMajorIllness ,  
   MajorIllnessRemark,  
   iSNULL(IsAllergy,0) aS IsAllergy,  
   AllergyRemark,  
   BirthPlace,  
   BirthTaluka,  
   BirthDistrict,  
   iSNULL(BloodGroupId,0) AS  BloodGroupId,  
   AdhaarNumber,  
   iSNULL(IsHostelRequired,0) as IsHostelRequired,  
   iSNULL(IsTransportRequired,0) as IsTransportRequired,  
   BirthState,  
   BirthCountry,  
   ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,  
   ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,  
   ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
   WhatsappContactNo -- Change done for mantis 29772
   	,ISNULL(AF.PENNumber,0) AS PENNumber --mantis : 0043425
	,ISNULL(AF.ApaarIdNumber,'') AS ApaarIdNumber --mantis : 0043425
  FROM   
           sAdmission.tAdmissionForm AF  
  WHERE   
    
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))  
  AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))  
  AND AF.OrgId=@rOrgId  
         
 order by AF.FormNo  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormParentAcademicAdd]
	
	@rStudentAcademicDetailsImpXml [nvarchar](max),
	@rId bigint,
	@rRelationshipId tinyint
	--,
	--@rFeeMainGroupId int,
	--@rFeeHeadId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStudentAcademicDetailsImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sAdmission.tAdmissionFormParentAcademic WHERE AdmissionFormId=@rId AND
	 RelationshipId = @rRelationshipId
	
	 INSERT INTO sAdmission.tAdmissionFormParentAcademic
		(
			AdmissionFormId,
			AcademicYear,
			AdmissionClass,
			InstituteName,
			InstituteCity,
			InstituteAffiliaton,
			RelationshipId,
			Language
			)
		SELECT
			AdmissionFormId,
			sSetup.fPortalXMLTagsReplaceReverse(AcademicYear),
			sSetup.fPortalXMLTagsReplaceReverse(AdmissionClass),
			sSetup.fPortalXMLTagsReplaceReverse(InstituteName),
			sSetup.fPortalXMLTagsReplaceReverse(InstituteCity),
			sSetup.fPortalXMLTagsReplaceReverse(InstituteAffiliaton),
			@rRelationshipId,
			sSetup.fPortalXMLTagsReplaceReverse(Language)
			
		FROM OPENXML (@loDoc, '/Table/AdmissionFormStudentAcademic', 1)
		WITH ( 
				AdmissionFormId bigint,
				AcademicYear nvarchar(20),
				AdmissionClass nvarchar(20),
				InstituteName nvarchar(150),
				InstituteCity nvarchar(150),
				InstituteAffiliaton varchar(150),
				RelationshipId tinyint,
				Language nvarchar(50)
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormReceiptAdd]
	
	@rOrgId smallint,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rReceiptDate date,
	@rReceiptAmount decimal(12,2),
	@rPayTypeId smallint,
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	DECLARE @lNextNumber BIGINT=0
	DECLARE @lReceiptNumber int=0
	
	IF NOT EXISTS(SELECT 1 FROM sAdmission.tAdmissionFormReceipt WHERE SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId)
	BEGIN
	
	--SELECT @lReceiptNumber = COUNT(ISNULL(Id,0)) + 1 FROM sAdmission.tAdmissionFormReceipt WHERE BatchId=@rBatchId
	SELECT @lReceiptNumber = ISNULL(MAX(ReceiptNumber), 0) + 1 FROM sAdmission.tAdmissionFormReceipt WHERE BatchId=@rBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionFormReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAdmission.tAdmissionFormReceipt
		(
			Id,
			SourceTypeId,
			SourceId,
			ReceiptNumber,
			ReceiptDate,
			ReceiptAmount,
			PayTypeId,
			ChequeNo,
			BankName,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@lReceiptNumber,
			sCommon.fGetDate(),
			@rReceiptAmount,
			@rPayTypeId,
			NULL,
			NULL,
			@rBatchId,
			0,
			sCommon.fGetDate(),
			0,
			sCommon.fGetDate()
		)

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormReferenceAdd]
	
	@rAdmissionFormReferenceDetailXml [nvarchar](max),
	@rId bigint
	--@rRelationshipId tinyint
	--,
	--@rFeeMainGroupId int,
	--@rFeeHeadId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAdmissionFormReferenceDetailXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId=@rId
	
	 INSERT INTO sAdmission.tAdmissionFormReference
		(
			AdmissionFormId,
			ReferenceDetail,
			ReferenceName,
			ReferenceRelation,
			ReferenceContactNo
			)
		SELECT
			 AdmissionFormId ,
			sSetup.fPortalXMLTagsReplaceReverse(ReferenceDetail),
			sSetup.fPortalXMLTagsReplaceReverse(ReferenceName),
			sSetup.fPortalXMLTagsReplaceReverse(ReferenceRelation),
			sSetup.fPortalXMLTagsReplaceReverse(ReferenceContactNo)
			
		FROM OPENXML (@loDoc, '/Table/AdmissionFormReferenceDetail', 1)
		WITH ( 
				AdmissionFormId bigint,
				ReferenceDetail nvarchar(100),
				ReferenceName nvarchar(50),
				ReferenceRelation nvarchar(50),
				ReferenceContactNo nvarchar(50)
				
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormSiblingAdd]
	
	@rAdmissionFormSiblingDetailXml [nvarchar](max),
	@rId bigint
	--@rRelationshipId tinyint
	--,
	--@rFeeMainGroupId int,
	--@rFeeHeadId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAdmissionFormSiblingDetailXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId=@rId
	
	 INSERT INTO sAdmission.tAdmissionFormSibling
		(
			AdmissionFormId,
			SiblingName,
			SiblingRelation,
			SiblingStandard,
			SiblingSchool,
			Code
			)
		SELECT
			AdmissionFormId,
			sSetup.fPortalXMLTagsReplaceReverse(SiblingName),
			sSetup.fPortalXMLTagsReplaceReverse(SiblingRelation),
			sSetup.fPortalXMLTagsReplaceReverse(SiblingStandard),
			sSetup.fPortalXMLTagsReplaceReverse(SiblingSchool),
			Code
		FROM OPENXML (@loDoc, '/Table/AdmissionFormSiblingDetail', 1)
		WITH ( 
				AdmissionFormId bigint,
				SiblingName nvarchar(100),
				SiblingRelation nvarchar(50),
				SiblingStandard nvarchar(50),
				SiblingSchool nvarchar(150),
				Code nvarchar(20)
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionFormStudentAcademicAdd]
	
	@rStudentAcademicDetailsImpXml [nvarchar](max),
	@rId bigint
	--,
	--@rFeeMainGroupId int,
	--@rFeeHeadId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStudentAcademicDetailsImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sAdmission.tAdmissionFormStudentAcademic WHERE AdmissionFormId=@rId
	
	 INSERT INTO sAdmission.tAdmissionFormStudentAcademic
		(
			AdmissionFormId,
			AcademicYear,
			AdmissionClass,
			InstituteName,
			InstituteCity,
			InstituteAffiliaton,
			Result,
			Language
			)
		SELECT
			AdmissionFormId,
			sSetup.fPortalXMLTagsReplaceReverse(AcademicYear),
			sSetup.fPortalXMLTagsReplaceReverse(AdmissionClass),
			sSetup.fPortalXMLTagsReplaceReverse(InstituteName),
			sSetup.fPortalXMLTagsReplaceReverse(InstituteCity),
			sSetup.fPortalXMLTagsReplaceReverse(InstituteAffiliaton),
			sSetup.fPortalXMLTagsReplaceReverse(Result),
			sSetup.fPortalXMLTagsReplaceReverse(Language)
			
		FROM OPENXML (@loDoc, '/Table/AdmissionFormStudentAcademic', 1)
		WITH ( 
				AdmissionFormId bigint,
				AcademicYear nvarchar(20),
				AdmissionClass nvarchar(20),
				InstituteName nvarchar(150),
				InstituteCity nvarchar(150),
				InstituteAffiliaton varchar(150),
				Result nvarchar(50),
				Language nvarchar(50)
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionGenerateReport]
 
	@rId bigint,
	@rClassId int,
	@rClassIds nvarchar(max)='',
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rFormNo [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rMotherTongue nvarchar(max) = '',
	@rNationality nvarchar(max) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rBatchId int = 0,
	@rFromFormNo nvarchar(20), 
	@rToFormNo nvarchar(20),
	@rContactNo nvarchar(50) = '',
	@rReportName nvarchar(50) ='',
	@rPageIndex int,
	@rCreatedUserId bigint,
	@rIsCommon bit = 0,
	@rIsCommonForOrg bit = 0,
	@rSavedReport nvarchar(max) = ''
	

AS
BEGIN
	 
	SET NOCOUNT ON;

    IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9990-12-31'
	IF(@rDOAFromDate IS NULL)
		SET @rDOAFromDate='0001-01-01'
	IF(@rDOAToDate IS NULL)
		SET @rDOAToDate='9990-12-31'

	If @rDOBToDate <> '9999-12-31'
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)
	If @rDOAToDate <> '9999-12-31'
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)
		
		IF(@rReportName != '' AND @rId = 0)
		BEGIN
			DECLARE @lNextNumber BIGINT, @query  AS NVARCHAR(MAX), @lColumnValue nvarchar(max) 
			declare @lColumnName nvarchar(max), @lClmNm nvarchar(max)
			declare @lOrderBy nvarchar(max), @lOrdBy nvarchar(max)
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
			--PRINT(@lNextNumber)
			--Removing Table Alias while Inserting in Table
			SET @lColumnName = @rColumnName
			SET @lClmNm = Replace(@lColumnName,'AT.','')
			SET @lClmNm = Replace(@lClmNm,'ACF.','')
			
			SET @lOrderBy = @rOrderBy
			SET @lOrdBy = Replace(@lOrderBy,'AT.','')
			SET @lOrdBy = Replace(@lOrdBy,'ACF.','')
			--print(@lOrdBy)
			--print(@lClmNm)
			INSERT INTO sAdmission.tAdmissionCustomSearch
			(
				Id,Title,ColumnName,OrderBy,OrgId,BatchId, ClassId, FormNo, FromFormNo, ToFormNo,StatusId,ClassIds,FirstName,LastName,FatherName, 
				MotherName, DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,Country,State,City,ContactNo,GenderId,ReligionId,CastCategoryId,
				Nationality,BloodGroupId,MotherTongueId,PreviousSchool,FatherQualification,MotherQualification,FatherOccupation,MotherOccupation,
				IsCommonUsers,IsCommonForOrg, CreatedUserId,CreatedDateTime
			)
			VALUES
			(
				@lNextNumber,@rReportName,@lClmNm,@lOrdBy,@rOrgId,@rBatchId,@rClassId,@rFormNo,@rFromFormNo,@rToFormNo,@rStatusId,@rClassIds,@rFirstName,@rLastName,
				@rFatherName,@rMotherName,@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rCountry,@rState,
				@rCity,@rContactNo,@rGenderId,@rReligionId,@rCastCategoryId,@rNationality,@rBloodGroupId,@rMotherTongue,
				@rPreviousSchool,@rFatherQualification,@rMotherQualification,@rFatherOccupation,@rMotherOccupation,
				@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate()
			)
		END
		--IF(@rId > 0)
		--BEGIN
		--	Select @rColumnName=ColumnName,@rOrderBy=OrderBy,@rOrgId=OrgId,@rBatchId=BatchId,@rClassId=ClassId,@rFormNo=FormNo,
		--	@rFromFormNo=FromFormNo,@rToFormNo=ToFormNo,@rStatusId=StatusId,@rClassIds=ClassIds,@rFirstName=FirstName,@rLastName=LastName,
		--	@rFatherName=FatherName,@rMotherName=MotherName,@rDOBFromDate=DOBFromDate,@rDOBToDate=DOBToDate,@rDOAFromDate=DOAFromDate,
		--	@rDOAToDate=DOAToDate,@rCountry=Country,@rState=State,@rCity=City,@rContactNo=ContactNo,@rGenderId=GenderId,@rReligionId=ReligionId,
		--	@rCastCategoryId=CastCategoryId,@rNationality=Nationality,@rBloodGroupId=BloodGroupId,@rMotherTongue=MotherTongueId,@rPreviousSchool=PreviousSchool,
		--	@rFatherQualification=FatherQualification,@rMotherQualification=MotherQualification,@rFatherOccupation=FatherOccupation,@rMotherOccupation=MotherOccupation
		--	FROM sAdmission.tAdmissionCustomSearch WHERE Id=@rId
		--END

		DECLARE @Sql nvarchar(MAX)= ''
		
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rFatherName = sCommon.fSearchStringGet(@rFatherName)
		SET @rMotherName = sCommon.fSearchStringGet(@rMotherName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		SET @rCity = sCommon.fSearchStringGet(@rCity)
		SET @rNationality = sCommon.fSearchStringGet(@rNationality)
		SET @rMotherTongue = sCommon.fSearchStringGet(@rMotherTongue)
		SET @rPreviousSchool = sCommon.fSearchStringGet(@rPreviousSchool)
		SET @rFatherQualification = sCommon.fSearchStringGet(@rFatherQualification)
		SET @rMotherQualification = sCommon.fSearchStringGet(@rMotherQualification)
		SET @rFatherOccupation = sCommon.fSearchStringGet(@rFatherOccupation)
		SET @rMotherOccupation = sCommon.fSearchStringGet(@rMotherOccupation)
		
		






	SELECT * INTO #MyAdmissionSearchTable 
	FROM
	(SELECT  CASE 
			WHEN AF.BloodGroupId = 1 THEN 'A+'
			WHEN AF.BloodGroupId = 2 THEN 'A-'
			WHEN AF.BloodGroupId = 3 THEN 'B+'
			WHEN AF.BloodGroupId = 4 THEN 'B-'
			WHEN AF.BloodGroupId = 5 THEN 'O+'
			WHEN AF.BloodGroupId = 6 THEN 'O-'
			WHEN AF.BloodGroupId = 7 THEN 'AB+'
			WHEN AF.BloodGroupId = 8 THEN 'AB-'
			WHEN AF.BloodGroupId = 9 THEN '-'
		END AS BloodGroup, 
		CASE 
			WHEN AFD.LiveWithId = 1 THEN 'Both'
			WHEN AFD.LiveWithId = 2 THEN 'Father'
			WHEN AFD.LiveWithId = 3 THEN 'Mother'
			WHEN AFD.LiveWithId = 4 THEN 'Guardian'
		END AS LiveWith,
		CASE 
			WHEN AF.GenderId = 1 THEN 'Male'
			WHEN AF.GenderId = 2 THEN 'Female'
		END AS Gender,
		AF.Id,
		AF.FormNo as FormNo,
		AF.FirstName,
		AF.MiddleName,
		AF.LastName as SurName,
		AF.FirstName + ' '+  AF.LastName AS StudentName,
		AF.DateOfBirth,
		AF.OrgId,
		AF.BatchId,
		AF.StatusId,
		AF.StreetOne,
		AF.StreetTwo,
		AF.StreetThree,
		AF.Country,
		AF.State,
		AF.City,
	   AF.ZipCode,
	   AF.ContactNo,
	   AF.ContactEmail,
	   AF.Remark,
	   AF.PreviousSchool,
	   AF.MeritMarks,
	   AF.MeritGrade,
	   AF.GenderId,
	   AF.ReligionId,
	   AF.FamilyCast,
	   AF.FamilySubCast,
	   AF.CastCategoryId,
	   AF.StudentId,
	   AF.FormPassword,
	   AF.Nationality,
	   AF.MotherTongue,
	   AF.IsPysicalDeformity,
	   AF.PysicalDeformityRemark,
	   AF.IsMajorIllness,
	   AF.MajorIllnessRemark,
	   AF.IsAllergy,
	   AF.AllergyRemark,
	   AF.BirthPlace,
	   AF.BirthTaluka,
	   AF.BirthDistrict,
	   AF.BloodGroupId,
	   AF.AdhaarNumber,
	   AF.BirthState,
	   AF.BirthCountry,
	   AF.OriginalStudentPhoto,
	   AF.OtherInformation as OtherInformation,
	   AF.AdmissionDate AS AdmissionFormDate,
	   CASE WHEN AF.IsHostelRequired = 0 THEN 'No' WHEN AF.IsHostelRequired = 1 THEN 'Yes' END AS HostelRequired,
	   CASE WHEN AF.IsTransportRequired = 0 THEN 'No' WHEN AF.IsTransportRequired = 1 THEN 'Yes' END AS TransportRequired,
	   OM.Title as Organization, 
	   OM.AffiliationId,
	   BM.Title as Batch, 
	   BM.FromDate, 
	   BM.ToDate, 
	   SM.Title as Status,
	   CM.Id as ClassId,
	   CM.Title as Class,
	   RM.Title AS Religion,
	   APA1.AcademicYear as FatherAcademicYear,
	   APA1.AdmissionClass as FatherAdmissionClass,
	   APA1.InstituteName as FatherInstituteName,
	   APA1.InstituteCity as FatherInstituteCity,
	   APA1.InstituteAffiliaton as FatherInstituteAffiliation,
	   APA1.Language as FatherMediumOfStudy,
	   APA2.AcademicYear as MotherAcademicYear,
	   APA2.AdmissionClass as MotherAdmissionClass,
	   APA2.InstituteName as MotherInstituteName,
	   APA2.InstituteCity as MotherInstituteCity,
	   APA2.InstituteAffiliaton as MotherInstituteAffiliation,
	   APA2.Language as MotherMediumOfStudy,
	   APA3.AcademicYear as GuardianAcademicYear, 
	   APA3.AdmissionClass as GuardianAdmissionClass,
	   APA3.InstituteName as GuardianInstituteName,
	   APA3.InstituteCity as GuardianInstituteCity,
	   APA3.InstituteAffiliaton as GuardianInstituteAffiliation,
	   APA3.Language as GuardianMediumOfStudy,
	   RSM.Title,
	   (STUFF((SELECT ',' + ReferenceDetail FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceDetail,
	   (STUFF((SELECT ',' + ReferenceName FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceName,
	   (STUFF((SELECT ',' + ReferenceRelation FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceRelation,
	   (STUFF((SELECT ',' + ReferenceContactNo FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceContactNo,
	   AFSA.AcademicYear as StudentAcademicYear,
	   AFSA.AdmissionClass as StudentAdmissionClass,
	   (STUFF((SELECT ',' + SiblingName FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingName,
	   (STUFF((SELECT ',' + SiblingRelation FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingRelation,
	   (STUFF((SELECT ',' + SiblingStandard FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingStandard,
	   (STUFF((SELECT ',' + SiblingSchool FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingSchool,
	   (STUFF((SELECT ',' + Code FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS Code,
	   AFSA.InstituteName as StudentInstituteName,
	   AFSA.InstituteCity as StudentInstituteCity,
	   AFSA.InstituteAffiliaton as StudentInstituteAffiliation, 
	   AFSA.Result, 
	   AFSA.Language,
	   AFD.FatherName, 
	   AFD.FatherDateOfBirth,
	   AFD.FatherOccupation,
	   AFD.FatherQualification,
	   AFD.FatherContactNo,
	   AFD.FatherMail,
	   AFD.FatherOfficeAddress,
	   AFD.FatherIncome AS FatherAnnualIncome, -- MantisId : 0029214 Changed label FatherIncome to FatherAnnualIncome
	   AFD.MotherName,
	   AFD.MOtherDateOfBirth,
	   AFD.MotherOccupation,
	   AFD.MotherQualification,
	   AFD.MotherContactNo,
	   AFD.MotherMail,
	   AFD.MotherOfficeAddress, 
	   AFD.MotherIncome AS MotherAnnualIncome, -- MantisId : 0029214 Changed label MotherIncome to MotherAnnualIncome
	   AFD.RelationshipName,
	   AFD.RelativeName,
	   AFD.RelativeDateOfBirth,
	   AFD.RelativeOccupation,
	   AFD.RelativeQualification,
	   AFD.RelativeContactNo,
	   AFD.RelativeMail,
	   AFD.RelativeOfficeAddress,
	   AFD.RelativeIncome AS RelativeAnnualIncome,	-- MantisId : 0029214 Changed label RelativeIncome to RelativeAnnualIncome
	   AFD.FatherPhoto,
	   AFD.MotherPhoto,
	   AFD.RelativePhoto,
	   AFD.FatherOrganization,
	   AFD.FatherDesignation,
	   AFD.FatherOfficePhone,
	   AFD.MotherOrganization,
	   AFD.MotherDesignation,
	   AFD.MotherOfficePhone,
	   AFD.RelativeOrganization,
	   AFD.RelativeDesignation,
	   AFD.RelativeOfficePhone,
	   AFD.IsFatherExStudent,
	   AFD.FatherPassOutYear,
	   AFD.IsMotherExStudent,
	   AFD.MotherPassOutYear, 
	   AFD.IsRelativeExStudent,
	   AFD.RelativePassOutYear,
	   AFD.FatherAdhaarNumber,
	   AFD.OriginalFatherPhoto,
	   AFD.OriginalMotherPhoto,
	   AFD.OriginalRelativePhoto,
	   AFD.MotherAadhaarNumber,
	   AFD.RelativeAadhaarNumber,
	   U.LoginTitle As AdmissionHandledBy,
	   SM1.CreatedDateTime AS AdmissionFormConvertedDate,
	   ISNULL(AFD.FatherPANCardNumber,'') AS FatherPANCardNumber,	--add for mantis: 38342
	   ISNULL(AFD.MotherPANCardNumber,'') AS MotherPANCardNumber,	--add for mantis: 38342
	   ISNULL(AF.WhatsappContactNo,'') AS WhatsappContactNo		--add for mantis: 38342
		from sAdmission.tAdmissionForm AF
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN  sCommon.tStatusMaster SM ON AF.StatusId = SM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		INNER JOIN sSecurity.tUser U ON U.Id = AF.CreatedUserId
		LEFT JOIN  sStudent.tStudentAdmission SA ON SA.AdmissionFormId = AF.Id
		LEFT JOIN  sStudent.tStudentMaster SM1 ON SM1.Id = AF.StudentId AND AF.StatusId=208
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = AF.ReligionId
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA1 ON APA1.AdmissionFormId = AF.Id AND APA1.RelationShipId = 1
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA2 ON APA2.AdmissionFormId = AF.Id AND APA2.RelationShipId = 2
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA3 ON APA3.AdmissionFormId = AF.Id AND APA3.RelationShipId = 7
		LEFT JOIN sCommon.tRelationshipMaster RSM ON RSM.Id = APA1.RelationshipId
		LEFT JOIN sCommon.tRelationshipMaster RSM1 ON RSM1.Id = APA2.RelationshipId
		LEFT JOIN sCommon.tRelationshipMaster RSM2 ON RSM2.Id = APA3.RelationshipId
		--LEFT JOIN sAdmission.tAdmissionFormReference AFR ON AFR.AdmissionFormId = AF.Id
		--LEFT JOIN sAdmission.tAdmissionFormSibling AFS ON AFS.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionFormStudentAcademic AFSA ON AFSA.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFD ON AFD.AdmissionFormId = AF.Id
		WHERE ((AF.OrgId = @rOrgId ) OR (@rOrgId = 0))
				AND ((AF.BatchId = @rBatchId) OR (@rBatchId = 0))
				AND ((AF.ForClassId = @rClassId) OR (@rClassId = 0))
			    AND ((ISNULL(AF.ForClassId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rClassIds,',')) OR (@rClassIds='')))
				AND ((AF.FormNo = @rFormNo) OR (@rFormNo = ''))
				AND ((AF.FormNo  >= @rFromFormNo) OR (ISNULL(@rFromFormNo,'') = ''))
				AND ((AF.FormNo  <= @rToFormNo) OR (ISNULL(@rToFormNo,'') = ''))
			    AND (AF.StatusId = @rStatusId)
				AND ((AF.FirstName Like @rFirstName) OR (@rFirstName = ''))
				AND ((AF.LastName Like @rLastName)OR(@rLastName = ''))
				AND ((AFD.FatherName like @rFatherName) OR (@rFatherName=''))
				AND ((AFD.MotherName like @rMotherName) OR (@rMotherName=''))
				AND (( AF.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND (( AF.DateOfBirth  <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
				AND ((Convert(nvarchar(12),AF.CreatedDateTime) >=  @rDOAFromDate) OR (@rDOAFromDate=''))
			    AND ((Convert(nvarchar(12),AF.CreatedDateTime) <=  @rDOAToDate) OR (@rDOAToDate=''))
				AND ((ISNULL(AF.Country,'') Like @rCountry )OR(@rCountry = ''))
				AND ((ISNULL(AF.State,'') Like @rState)OR(@rState = ''))
				AND ((ISNULL(AF.City,'') Like @rCity)OR(@rCity = ''))
				AND ((AF.ContactNo=@rContactNo) OR (@rContactNo=0))
				AND (ISNULL(AF.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND (ISNULL(AF.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
				AND (ISNULL(AF.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
				AND ((AF.Nationality Like @rNationality) OR (@rNationality = ''))
				AND (ISNULL(AF.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
				AND ((AF.MotherTongue Like @rMotherTongue) OR (@rMotherTongue = ''))
				AND ((AF.PreviousSchool Like  @rPreviousSchool) OR (@rPreviousSchool = ''))
				AND ((AFD.FatherQualification Like  @rFatherQualification) OR (@rFatherQualification = ''))
				AND ((AFD.MotherQualification Like @rMotherQualification) OR (@rMotherQualification = ''))
				AND ((AFD.FatherOccupation Like @rFatherOccupation) OR (@rFatherOccupation = ''))
				AND ((AFD.MotherOccupation Like @rMotherOccupation) OR (@rMotherOccupation = '')) 
				) AS AdmissionReportGeneration
				
		  --SELECT * FROM #MyAdmissionSearchTable

		  --AdmissionCriteriaFields
		  DECLARE @cols AS NVARCHAR(MAX),@criteriaquery  AS NVARCHAR(MAX)
			-- CTE for Admission Form Field
			;WITH AdmissionCriteriaFormCTE AS (SELECT  DISTINCT FieldRemark FROM sAdmission.tAdmissionCriteriaForm ACF
			LEFT JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
			--WHERE (ACF.BatchId = @rBatchId OR @rBatchId = 0) AND (ACF.ClassId = @rClassId OR @rClassId = 0)
			GROUP BY Id,FieldRemark,ClassId,BatchId
			)
			SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(FieldRemark) FROM AdmissionCriteriaFormCTE
			GROUP BY FieldRemark
			ORDER BY FieldRemark FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')
			

			IF object_id('tempdb..##tempAdmissionCriteriaForm') IS NOT NULL 
			BEGIN
			--print('Hi')
			   DROP TABLE ##tempAdmissionCriteriaForm 
			END
			IF(@cols IS NOT NULL)
			BEGIN 
				SET @criteriaquery = 'SELECT DISTINCT AdmissionFormId,' + @cols + ' INTO ##tempAdmissionCriteriaForm FROM 
							 (
								SELECT DISTINCT  AFF.AdmissionFormId,AdmissionFormFieldResponse, FieldRemark
								FROM 
								sAdmission.tAdmissionCriteriaForm ACF
								INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
								WHERE ((ACF.BatchId = '+CONVERT(nvarchar(10),@rBatchId)+') OR (' +CONVERT(nvarchar(10),@rBatchId)+' = 0)) AND ((ACF.ClassId = '+CONVERT(nvarchar(10),@rClassId)+') OR ('+CONVERT(nvarchar(10),@rClassId)+' = 0))
							) x
							PIVOT
							(
								MAX(AdmissionFormFieldResponse)
								FOR FieldRemark IN (' + @cols + ')
							) p' 
				print(@criteriaquery)
				exec (@criteriaquery)
				
				  --SELECT * FROM #MyAdmissionSearchTable
				--SELECT * FROM ##tempAdmissionCriteriaForm ACF
			END
			IF(@cols IS NULL)
				Declare @lSQLAlt nvarchar(max)=''
				IF(@rOrderBy = '' OR @rOrderBy = NULL)
				BEGIN
					SET @lSQLAlt = @lSQLAlt + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT '
					print(@lSQLAlt)
					exec(@lSQLAlt)
				END
				ELSE
				BEGIN
				print(@rOrderBy)
				SET @lSQLAlt = @lSQLAlt + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT GROUP BY ' +@rColumnName+ ',' +@rOrderBy+ ' ORDER BY ' +@rOrderBy+ ';'
				print(@lSQLAlt)
				exec (@lSQLAlt)
				END

		  --
		IF(@cols IS NOT NULL)
		Declare @lSQL nvarchar(max) ='', @lqry nvarchar(max)=''
		IF(@rOrderBy = '' OR @rOrderBy = NULL)
		BEGIN
			--SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT'
			SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT LEFT JOIN ##tempAdmissionCriteriaForm ACF ON AT.Id = ACF.AdmissionFormId'
			print(@lSQL)
			exec(@lSQL)
		END
		ELSE
		BEGIN
		print(@rOrderBy)
			SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT LEFT JOIN ##tempAdmissionCriteriaForm ACF ON AT.Id = ACF.AdmissionFormId ORDER BY ' +@rOrderBy+ ';'
			print(@lSQL)
			exec (@lSQL)
			IF OBJECT_ID(N'dbo.MyTable0', N'U') IS NOT NULL 
			 DROP Table ##tempAdmissionCriteriaForm
		END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionHSCDetailAdd]
	    @rId bigint,
		@rHSCSchoolName	nvarchar(200),
		@rIsHSCSchoolLocal	bit,
		@rHSCStreamId	int,
		@rHSCSeatNo	nvarchar(20),
		@rHSCJoinDate	date,
		@rHSCLeaveDate	date,
		@rHSCNoOfTrials	tinyint,
		@rHSCPassingMonth	tinyint,
		@rHSCPassingYear	tinyint,
		@rHSCTotalMarks	smallint,
		@rHSCObtainMarks	smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
 BEGIN TRANSACTION	
	
	IF NOT EXISTS (Select AdmissionFormId from sAdmission.tAdmissionHSCDetail where AdmissionFormId = @rId)
	BEGIN
	INSERT INTO sAdmission.tAdmissionHSCDetail
		(
		AdmissionFormId,
		HSCSchoolName,
		IsHSCSchoolLocal,
		HSCStreamId,
		HSCSeatNo,
		HSCJoinDate,
		HSCLeaveDate,
		HSCNoOfTrials,
		HSCPassingMonth,
		HSCPassingYear,
		HSCTotalMarks,
		HSCObtainMarks

		)
	VALUES
		(
	    @rId,
		@rHSCSchoolName,
		@rIsHSCSchoolLocal,
		@rHSCStreamId,
		@rHSCSeatNo,
		@rHSCJoinDate,
		@rHSCLeaveDate,
		@rHSCNoOfTrials,
		@rHSCPassingMonth,
		@rHSCPassingYear,
		@rHSCTotalMarks,
		@rHSCObtainMarks
		)
		             
	END	 
	 ELSE
	 BEGIN

	    UPDATE  sAdmission.tAdmissionHSCDetail
	    SET
		HSCSchoolName=@rHSCSchoolName,
		IsHSCSchoolLocal=@rIsHSCSchoolLocal,
		HSCStreamId=@rIsHSCSchoolLocal,
		HSCSeatNo=@rHSCSeatNo,
		HSCJoinDate=@rHSCJoinDate,
		HSCLeaveDate=@rHSCLeaveDate,
		HSCNoOfTrials=@rHSCNoOfTrials,
		HSCPassingMonth=@rHSCPassingMonth,
		HSCPassingYear=@rHSCPassingYear,
		HSCTotalMarks=@rHSCTotalMarks,
		HSCObtainMarks =@rHSCObtainMarks
	      WHERE AdmissionFormId = @rId 	
	 END  
		SELECT @rId AS Result
	
		COMMIT TRANSACTION
		
	
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionInquiryAdd]
		 @rId bigint
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName nvarchar(100)
		,@rForClassId int
		,@rForBatchId int =0
		--,@rForBatch	nvarchar(20)
		,@rDateOfBirth date
		,@rOrgId smallint
		--,@rStatusId	smallint
		,@rInquiryStatusMasterId int
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rInquiryModeId tinyint
		,@rInquiryReferenceId int
		,@rAdmissionCategoryId int
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10,2) 
		,@rMeritGrade nvarchar(20)
		,@rMeritMarksBreakup nvarchar(100)
		,@rGenderId tinyint
		,@rFollowupDate date
		,@rFollowupRemark nvarchar(1000) --Changed length from nvarchar(150) to nvarchar(1000) for mantis : 36940
		,@rCreatedUserId bigint
		,@rInquiryDate date
		,@rNumber nvarchar(20) 
		,@rHandledBy nvarchar(100) 
		,@rOrgGroupId int,
		@rCastCategoryId int=0,
		@rIsHostelRequired bit=0,
		@rIsTransportRequired bit=0,
		@rIsValidateInquiryAsPerAdmission bit=0,
		@rIsGivenAdmissionForm bit=0,
		@rAlternateContactNo nvarchar(100)='',
		@rAlternateContactEmail	nvarchar(200) = '',
		@rMotherName nvarchar(100)='',
		@rDataEntryModeId smallint = 562 ,
		@rMinorityStatusId smallint = 0,
		@rLiveWithId smallint = 0,
		@rAdhaarNumber nvarchar(20)='',
		@rBloodGroupId smallint = 0,
		@rFatherName nvarchar(100)='',
		@rFatherOccupation nvarchar(50)='',
		@rFatherIncome int = 0,
		@rFatherContactNo nvarchar(50)='',
		@rFatherMail nvarchar(50)='',
		@rFatherQualification nvarchar(50)='',
	    @rMotherOccupation nvarchar(50)='',
		@rMotherIncome int=0,
		@rMotherContactNo nvarchar(50)='',
		@rMotherMail nvarchar(50)='',
		@rMotherQualification nvarchar(50)='',
		@rStream nvarchar(20)='',
		@rBoard nvarchar(50)='' ,
		@rInquiryReferenceRemark nvarchar(200) = '' ,
		@rWhatsAppContact nvarchar(50)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lOrgGroupBatchId int=0	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster BM WHERE BM.Id = @rForBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	--mantis: 42227, comment the below configuraiton line and add new
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	SELECT @lConfigValue = ISNULL(CS.ItemValue,ISNULL(CM.ItemValue,'')) FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId=CM.Id WHERE CM.Id = 341
	 
	DECLARE @lConfigValueForAdmissionNumber nvarchar(50)=''
	SELECT @lConfigValueForAdmissionNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 462 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId 

	DECLARE @lConfigValueAdmissionAlphaNUmeric nvarchar(50)=''
	SELECT @lConfigValueAdmissionAlphaNUmeric = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 595 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId 
	
	DECLARE @lInquiryNumber BIGINT = 0

	IF(@lConfigValueForAdmissionNumber = 'True' AND (@lConfigValueAdmissionAlphaNUmeric = '' OR @lConfigValueAdmissionAlphaNUmeric = 'False'))
	BEGIN
		IF(@lConfigValue='OrgGroupBatch')
		BEGIN
			SELECT @rNumber = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
			WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId
		END
		ELSE IF(@lConfigValue='Batch')
		BEGIN
			SELECT @rNumber = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI
			WHERE AI.ForBatchId = @rForBatchId
		END
		ELSE IF (@lConfigValue = 'Continuous')
		BEGIN
			SELECT @rNumber =(ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry  
			WHERE OrgGroupId = @rOrgGroupId
		END

		SET @lInquiryNumber= @rNumber

	END
	--Changes for mantis Id: 0042910,44866
	ELSE IF((@lConfigValueForAdmissionNumber = 'False' OR @lConfigValueForAdmissionNumber = '') AND @lInquiryNumber= 0 AND (@lConfigValueAdmissionAlphaNUmeric = '' OR @lConfigValueAdmissionAlphaNUmeric = 'False'))
	BEGIN
		IF(@lConfigValue='OrgGroupBatch')
		BEGIN
			SELECT @rNumber = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
			WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId
		END
		ELSE IF(@lConfigValue='Batch')
		BEGIN
			SELECT @rNumber = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI
			WHERE AI.ForBatchId = @rForBatchId
		END
		ELSE IF (@lConfigValue = 'Continuous')
		BEGIN
			SELECT @rNumber =(ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry  
			WHERE OrgGroupId = @rOrgGroupId
		END

		SET @lInquiryNumber= @rNumber
	END
	--Changes End for mantis Id: 0042910
	
	Declare @lStatusId smallint,@lIsValidateBirthdate bit,@lFromDateOfBirth date,@lToDateOfBirth date
	SET @lStatusId= 0
	
	if(@rIsValidateInquiryAsPerAdmission=1)
	Begin
		Select @lIsValidateBirthdate=IsValidateBirthdate,@lFromDateOfBirth=FromDateOfBirth,@lToDateOfBirth=ToDateOfBirth from  sAdmission.tAdmissionCriteria where ClassId=@rForClassId AND BatchID=@rForBatchId
		
		if(@lIsValidateBirthdate=1 AND @rDateOfBirth NOT between @lFromDateOfBirth And @lToDateOfBirth)
		BEGIN
			Select  -101 AS Result
			return
		End
	End
	 
	 

 BEGIN TRANSACTION	
	IF(@rId = 0)	
	BEGIN	

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionInquiryCriteriaAdd]

@rClassId int = 0,
@rBatchId int = 0,
@rIsPublish bit = 0,
@rIsValidateBirthdate bit,
@rFromDateOfBirth date,
@rToDateOfBirth date,
@rAgeCutOffDate date,
@rAdmissionInquiryRemark nvarchar(max)='',
@rAdmissionInquiryConfirmationRemark nvarchar(max)='',
@rIsHostelDetailRequired bit = 0,				-- Mantis Id : 0039749
@rIsTransportDetailRequired bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF EXISTS (SELECT 1 FROM sAdmission.tAdmissionInquiryCriteria WHERE ClassId = @rClassId AND BatchId = @rBatchId) 
	BEGIN  
		UPDATE sAdmission.tAdmissionInquiryCriteria 
		SET IsPublish = @rIsPublish,IsValidateBirthdate=@rIsValidateBirthdate,FromDateOfBirth=@rFromDateOfBirth,ToDateOfBirth=@rToDateOfBirth,AgeCutOffDate=@rAgeCutOffDate,
		AdmissionInquiryRemark = @rAdmissionInquiryRemark,
		AdmissionInquiryConfirmationRemark= @rAdmissionInquiryConfirmationRemark,
		IsHostelDetailRequired = @rIsHostelDetailRequired, IsTransportDetailRequired = @rIsTransportDetailRequired	-- Mantis Id : 0039749
		WHERE ClassId = @rClassId AND BatchId = @rBatchId 
	END  
ELSE 
	BEGIN 
		INSERT INTO sAdmission.tAdmissionInquiryCriteria 
		(
			ClassId,
			BatchId,
			IsPublish,
			IsValidateBirthdate,
			FromDateOfBirth,
			ToDateOfBirth,
			AgeCutOffDate,
			AdmissionInquiryRemark,
			AdmissionInquiryConfirmationRemark,
			IsHostelDetailRequired,				-- Mantis Id : 0039749
			IsTransportDetailRequired
		)
		VALUES 
		(
			@rClassId,
			@rBatchId,
			@rIsPublish,
			@rIsValidateBirthdate,
			@rFromDateOfBirth,
			@rToDateOfBirth,
			@rAgeCutOffDate,
			@rAdmissionInquiryRemark,
			@rAdmissionInquiryConfirmationRemark,
			@rIsHostelDetailRequired,			-- Mantis Id : 0039749
			@rIsTransportDetailRequired	
		)  
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionInquiryFieldAdd]
	  
	@rAdmissionInquiryId nvarchar(20)='', --changes in Mantis :0041025
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
		DELETE FROM sAdmission.tAdmissionInquiryField WHERE AdmissionInquiryId=@rAdmissionInquiryId
	
		INSERT INTO sAdmission.tAdmissionInquiryField
		(
			AdmissionInquiryId,
			AdmissionInquiryFormId,
			AdmissionInquiryFieldResponse
		)
		SELECT
			@rAdmissionInquiryId,AdmissionInquiryFormId,AdmissionInquiryFieldResponse
		FROM
			OPENXML (@loDoc, '/Table/AdmissionInquiryFormField', 1)WITH 
			( 
			AdmissionInquiryFormId int,
			AdmissionInquiryFieldResponse nvarchar(1000)
			)
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionInquiryFollowupAdd]
		@rId	bigint,	
		@rAdmissionInquiryId	bigint,
		@rFollowupDate	date,
		@rFollowupRemark	nvarchar(150),
		@rCreatedUserId	bigint,
		@rHandledBy	nvarchar(100),	
		@rOrgId smallint,
		@rNextFollowupDate date=''
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY
 BEGIN TRANSACTION	
IF(@rId = 0)	
	BEGIN
 DECLARE @lNextNumber BIGINT 
 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiryFollowup', 0, 1, 1,@outNextNumber = @lNextNumber output
			
	INSERT INTO sAdmission.tAdmissionInquiryFollowup
		(
			Id,
			AdmissionInquiryId,
			FollowupDate,
			FollowupRemark,
			CreatedUserId,
			CreatedDateTime,
			HandledBy
		)
	VALUES
		(
			@lNextNumber,
			@rAdmissionInquiryId,
			@rFollowupDate,
			@rFollowupRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rHandledBy
		)
		    SELECT 1 AS Result         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionInquiryFollowup
	    SET
	         AdmissionInquiryId=@rAdmissionInquiryId,
	         FollowupDate=@rFollowupDate,
	         FollowupRemark=@rFollowupRemark,
			 UpdatedUserId=@rCreatedUserId,
			 HandledBy=@rHandledBy,
			 UpdatedDateTime=sCommon.fGetDate()
			
	      WHERE Id = @rId 	   
	      SELECT 11 AS Result      
	      
	 END  
	BEGIN 
	  UPDATE  sAdmission.tAdmissionInquiry
	  SET
	  FollowupDate=@rNextFollowupDate
	   WHERE Id = @rAdmissionInquiryId 	  
	END 
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionInquiryFollowupGet]
	
	 @rId bigint = 0,
	 @rFromDate date='',
	 @rToDate date='',
	 @rOrgId Smallint=0,
	 @rOrgGroupBatchId int = 0,
	 @rAdmissionInquiryId bigint=0,
	 @rBatchId int = 0,
	 @rFromNextFollowupDate date='',
	 @rToNextFollowupDate date='',
	 @rInquiryNumber nvarchar(20) = '', --Added for mantis : 37222 -- changes for Mantis Id :0041025
	 @rFirstName nvarchar(100)='' --Added for mantis : 37222
	 	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)--Added for mantis : 37222
	END

	SELECT  
		AF.Id,
		AF.AdmissionInquiryId,
		ISNULL(AF.FollowupDate,'') AS  FollowupDate,
		AF.FollowupRemark,
		AF.HandledBy,
		AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,
		ISNULL(AI.FollowupDate,'0001/01/01') AS NextFollowupDate,
		AI.OrgId,
		OM.DisplayTitle AS OrgName,
		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.Id = @rId) OR (@rId = 0))
      AND ((AF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	  AND ((AF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.FollowupDate>= @rFromNextFollowupDate) OR (ISNULL(@rFromNextFollowupDate,'')=''))
	  AND ((AI.FollowupDate<= @rToNextFollowupDate) OR (ISNULL(@rToNextFollowupDate,'')=''))
	  AND ((AI.OrgId=@rOrgId) OR (@rOrgId=0))
	  AND ((AF.AdmissionInquiryId = @rAdmissionInquiryId) OR (@rAdmissionInquiryId = 0))
	  AND ((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	  --AND (AI.ForBatchId=@rBatchId)
	  AND((AI.Number = @rInquiryNumber) OR (ISNULL(@rInquiryNumber,'') = '')) --Added for mantis : 37222 -- changes for Mantis Id :0041025
	  AND((AI.FirstName LIKE @rFirstName) OR (ISNULL(@rFirstName,'') = '')) --Added for mantis : 37222

	  Order by AF.FollowupDate DESC 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionInquiryFormAdd]
		 
	@rId int,
	@rOrgId int,
	@rClassId int,
	@rBatchId int,
	@rFieldRemark nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	
 
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiryForm', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sAdmission.tAdmissionInquiryForm
	(
		Id
		,ClassId
		,BatchId
		,FieldRemark
		,FieldTypeId
		,FieldList
		,IsFieldMandatory
		,FieldGroup
		,FieldOrder
	)
	VALUES
	(
		@lNextNumber
		,@rClassId
		,@rBatchId
		,@rFieldRemark
		,@rFieldTypeId
		,@rFieldList
		,@rIsFieldMandatory
		,@rFieldGroup
		,@rFieldOrder
	)
END	 
ELSE
BEGIN
	SET @lNextNumber = @rId
	
	UPDATE sAdmission.tAdmissionInquiryForm
	SET 
		FieldRemark = @rFieldRemark
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
	WHERE Id = @rId 	   
END  
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionInquiryFormGet]
	 
	@rClassId int,
	@rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		Id,
		ClassId,
		BatchId,
		FieldRemark,
		FieldTypeId,
		FieldList,
		IsFieldMandatory,
		FieldGroup,
		FieldOrder
	FROM 
		sAdmission.tAdmissionInquiryForm
	WHERE 
		ClassId = @rClassId
		AND BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionInquiryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rId bigint = 0,	 
	 @rForClassId int = 0,
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	-- @rStatusId smallint,
	 @rInquiryStatusMasterId int = 0,
	 @rOrgId int,
	 @rFirstName nvarchar(100) = '',
	 @rLastName nvarchar(100) = '',
	 @rFromDate datetime=Null, -- MantisId : 0030699 changed '' to null
	 @rToDate datetime=Null, -- MantisId : 0030699 changed '' to null
	 @rForBatchId int = 0,
	 @rDepartmentId int = 0,
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryModeId smallint=0,
	 @rInquiryReferenceId int=0,
	 @rNumber nvarchar(20)='', --changes in Mantis :0041025
	 @rOrgGroupBatchId int = 0,
	 @rFollowUpdate datetime='',
	 @rIsTransportRequired int=0,
	 @rIsHostelRequired int=0,
	 @rOrderBy int =0,
	 @rIsGivenAdmissionForm int = -1,  -- Changed 0 to -1 for MantisId : 0032411
	 @rContactNo nvarchar(100)='',
	 @rAdmissionInquiryIdText nvarchar(20) = '',
	 @rHandledBy nvarchar(100) = '',
	 @rGenderId int=0
	  --@rIsGivenAdmissionFormNew int =0
	 --@rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
	BEGIN
		SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName= sCommon.fSearchStringGet(@rLastName)
		SET @rHandledBy= sCommon.fSearchStringGet(@rHandledBy)
		--SET @rContactNo= sCommon.fSearchStringGet(@rContactNo)
	END
	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CASE WHEN @rAdmissionInquiryIdText = '' THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText, ----changes in Mantis :0041025
		 AI.Id
		,AI.ForBatchId
		,AI.ForClassId
		,AI.StatusId
		,ISNULL(SM.Id,0) AS InquiryStatusMasterId
		,ISNULL(AI.GenderId,0) AS GenderId
		,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
		,ISNULL(IMM.Title,'') AS InquiryMode
		,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		,AI.OrgId
		,ISNULL(AI.Number,'') AS InquiryNumber ----changes in Mantis :0041025
		,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		,OM.DisplayTitle AS OrgName
		,BM.Title AS ForBatch
		,ISNULL(CM.Title,'') AS ClassName	
		,AI.FirstName
		,AI.MiddleName
		,AI.LastName
		,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
		,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
		,ISNULL(AI.DateOfBirth,'') As DateOfBirth
		,ISNULL(GM.Title,'') As Gender			
		,AI.ContactNo
		,AI.ContactEmail			
		,AI.StreetOne
		,AI.StreetTwo
		,AI.StreetThree
		,AI.Country
		,AI.State
		,AI.City
		,AI.ZipCode
		,ISNULL(AI.Remark,'') AS Remark						
		,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
		,ISNULL(AI.MeritMarks,0) AS MeritMarks
		,ISNULL(AI.MeritGrade,'') AS MeritGrade
		,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
		,SM.Title as StatusName	
		--,cast(replace(FollowupDate,'/','-') as date) As FollowupDate
		,ISNULL(AI.FollowupDate,'') As FollowupDate
		,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
		,ISNULL(IRM.Title ,'') AS InquiryReference	
		,ISNULL(SCM.Title,'') AS AdmissionCategory		
		,ISNULL(AI.HandledBy,'') AS HandledBy
		,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
		,ISNULL(AI.StudentId,0) AS StudentId,
		ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
		ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
		ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
		CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
		--ISNULL(AI.IsGivenAdmissionForm,0) AS IsGivenAdmissionForm,
		ISNULL(SM.HighlightColor,'') AS HighlightColor,
		ISNULL(SA.PreviousStandard,'') As PreviousStandard,
		AI.AlternateContactNo,
		AI.AlternateContactEmail
		,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
		ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
		ISNULL(AI.MotherName,'') AS MotherName,
		CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
		,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		,ISNULL(AI.LiveWithId,0) AS LiveWithId
		,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
		,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
		 ,ISNULL(AI.FatherName,'') AS FatherName
		,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
		,ISNULL(AI.FatherIncome,0) AS FatherIncome 
		,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
		,ISNULL(AI.FatherMail,'') AS FatherMail
		,ISNULL(AI.FatherQualification,'') AS FatherQualification
		,ISNULL(AI.MotherOccupation,'') As MotherOccupation
		,ISNULL(AI.MotherIncome,0) AS MotherIncome
		,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
		,ISNULL(AI.MotherMail,'') AS MotherMail 
		,ISNULL(AI.MotherQualification,'') AS  MotherQualification
		,ISNULL(AI.Stream,'') AS Stream
		,ISNULL(AI.Board,'') AS Board
		,ISNULL(CCM.Title,'') AS CasteCategory
		,ISNULL(AI.InquiryReferenceRemark,'') AS InquiryReferenceRemark
		,ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo
		--,(SELECT STUFF ((SELECT ',' +' ' + AIF.FieldRemark+' - '+AIF.FieldGroup+ ' - ' +AI1.AdmissionInquiryFieldResponse
		--	FROM sAdmission.tAdmissionInquiryForm AIF 
		--	LEFT JOIN sAdmission.tAdmissionInquiryField AI1 ON AI1.AdmissionInquiryFormId = AIF.Id AND AI1.AdmissionInquiryId =  AI.Number
		--	WHERE (ClassId = @rForClassId  OR @rForClassId=0)
		--	AND (AI1.AdmissionInquiryFormId = @rId  OR @rId = 0)
		--	AND (BatchId = @rForBatchId OR @rForBatchId=0) ORDER BY AIF.FieldOrder
		--	FOR XML PATH('')),1,1,'')) AS AdmissionCustomField
  FROM 
		sAdmission.tAdmissionInquiry AI
        LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
        --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
        INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
		LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
		LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
		LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
		LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
		LEFT JOIN  scommon.tCastCategoryMaster CCM on CCM.Id = AI.CastCategoryId
		--LEFT JOIN sAdmission.tAdmissionInquiryField AIF ON AIF.AdmissionInquiryFormId = AI.Id 
		--LEFT JOIN sAdmission.tAdmissionInquiryForm AIF1 ON AIF.AdmissionInquiryFormId = AIF1.Id   
  WHERE  
		((AI.Id = @rId) OR (@rId = 0))
		AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AI.LastName like @rLastName) OR (@rLastName=''))
		AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		--AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
		AND (AI.OrgId=@rOrgId OR @rOrgId=0)
		AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
		AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
		AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
		AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
		AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
		AND ((AI.Number=@rNumber) OR (ISNULL(@rNumber,'')='')) --changes in Mantis :0041025
		AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
		AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
	  --AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=0)OR (@rIsGivenAdmissionForm=-1))
		AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
         END)	  
		AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
		--AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
		 --AND (AI.IsGivenAdmissionForm = CASE @rIsGivenAdmissionForm WHEN 0 THEN ISNULL(AI.IsGivenAdmissionForm,0) WHEN 2 THEN 1 WHEN 1 THEN 0 END)
		AND ((AI.ContactNo = @rContactNo) OR (ISNULL(@rContactNo, '')=''))
		AND ((AI.HandledBy like @rHandledBy) OR (ISNULL(@rHandledBy, '')=''))
		AND ((GM.Id = @rGenderId) OR (@rGenderId = 0))
	  --AND ((AI.IsTransportRequired=@rIsTransportRequired) OR (@rIsTransportRequired=0))	   
	    --AND ((AI.IsHostelRequired =@rIsHostelRequired) OR (@rIsHostelRequired=0))
	  Order by Case @rOrderBy When 1 then AI.MeritMarks END desc ,
			    Case @rOrderBy when 0 then 
				/** Make changes for mantis : 42151 **/
				CASE WHEN AI.Number like '%[0-9]%' 
				THEN Replicate('0', 100 - Len(AI.Number)) + AI.Number
				ELSE AI.Number  END 
				Else 
			    CASE WHEN AI.Number like '%[0-9]%' 
				THEN Replicate('0', 100 - Len(AI.Number)) + AI.Number
				ELSE AI.Number  END END desc   			    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionMarkEntryReportGet]
                              
    @rForClassId int, 
    @rBatchId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	--Declare int IdNo
	--Declare nvarchar FirstName 
	
	
	Select 1
	
	--DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX),@displaycols AS NVARCHAR(MAX) 
	--select @cols = STUFF((SELECT ',' + QUOTENAME(AOS.CriteriaName) FROM sAdmission.tAdmissionSetup AOS 
	--where AOS.ClassId=@rForClassId AND AOS.BatchId=@rBatchId FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')

	--set @query = 'SELECT distinct IdNo,FirstName,' + @cols + '  from (  select ISNULL(AOS.CriteriaName,0) AS CriteriaName, 
	--ISNULL(ASS.ObtainMark,0) AS mark, AF.FormNo AS IdNo,  (AF.FirstName+'' ''+AF.MiddleName+'' ''+AF.LastName) AS FirstName 
	--from sAdmission.tAdmissionForm AF INNER JOIN sAdmission.tAdmissionSetup AOS ON AOS.ClassId = AF.ForClassId 
	--AND AOS.BatchId = AF.BatchId  LEFT JOIN sAdmission.tAdmissionSetupStudent ASS ON AF.Id = ASS.AdmissionFormId 
	--AND AOS.Id = ASS.AdmissionSetupId INNER JOIN sAdmission.tAdmissionFormSelected AFS ON AFS.AdmissionFormId = AF.Id 
	--where AF.ForClassId= ' + @rForClassId + ' AND AF.BatchId= ' + @rBatchId + ') x   pivot  ( max(mark)   for CriteriaName in (' + @cols + ')  ) p ' 

	--Select @query;
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionMeritListAdd]

		@rAdmissionFormId bigint,
		@rTotalObtainMark decimal(10,2)=0,
		@rAdmissionStatusId tinyint
		--@rChecked bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

  
 --IF(@rChecked = 1)	
	BEGIN
	
	
	
		IF NOT Exists(select * from sAdmission.tAdmissionFormSelected where AdmissionFormId=@rAdmissionFormId)
			BEGIN
					Insert into sAdmission.tAdmissionFormSelected 
					(AdmissionFormId
					,TotalObtainMark
					,AdmissionStatusId
					)
					 values 
					(
					@rAdmissionFormId,
					@rTotalObtainMark,
					@rAdmissionStatusId
					)
					
					Select 1 AS Result
					RETURN
			END	 
		      
	
	
	ELSE
	 UPDATE  sAdmission.tAdmissionFormSelected
	    SET
			
			TotalObtainMark=@rTotalObtainMark,
			AdmissionStatusId=@rAdmissionStatusId
			where
			AdmissionFormId=@rAdmissionFormId
			
			 Select 1 AS Result
			END
	
	 --ELSE
	 --BEGIN
	 
	 --Delete from sAdmission.tAdmissionFormSelected Where AdmissionFormId=@rAdmissionFormId 
	 
	-- Select 1 AS Result
	 
	-- RETURN
	--END
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionMeritListGET]

	 @rClassId  nvarchar(max) = '',
	 @rBatchId int = 0,
	 @rOrgId int,
	 @rStatus int,
	 @rMinMeritMarks decimal(12,2),
	 @rMaxMeritMarks decimal(12,2),
	 @rFromDate date,
	 @rToDate date,
	 @rAdmissionMinMeritMarks decimal(10,2),
	 @rAdmissionMaxMeritMarks decimal(10,2)
	 --@rTitle nvarchar(100),
	 --@rStatusId smallint
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
BEGIN 
	SELECT AF.Id,
		AFS.AdmissionFormId,
		AFS.AdmissionStatusId,
		AF.FormNo,
	    (AF.FirstName+' '+AF.MiddleName+' '+AF.LastName)AS Name,
		AF.ContactNo,
		AFS.DiscussionDate,
		ASM.Title,
		SUM(ASS.ObtainMark)AS obtain,
		AF.StatusId 
	FROM sAdmission.tAdmissionForm AF 
		Inner JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
		Left JOIN sAdmission.tAdmissionSetupStudent ASS ON AF.Id=ASS.AdmissionFormId 
		LEFT JOIN sAdmission.tAdmissionSetup ADS ON ASS.AdmissionSetupId=ADS.Id 
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId             
	WHERE ((AF.ForClassId IN(@rClassId)) OR (@rClassId=0))
		AND((AF.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (( AFS.DiscussionDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND (( AFS.DiscussionDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((AF.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND ((ASS.ObtainMark >=@rMinMeritMarks) OR (ISNULL(@rMinMeritMarks,0) =0))
		--AND ((ASS.ObtainMark <=@rMaxMeritMarks) OR (ISNULL(@rMaxMeritMarks,0) =0))
		AND((AFS.AdmissionStatusId = @rStatus) OR (@rStatus=0))
		--AND((AFS.AdmissionStatusId = @rStatus) OR (@rStatus=0))
		--AND((AFS.AdmissionStatusId = @rStatus) OR (@rStatus=0))
		AND ((AF.MeritMarks >=@rAdmissionMinMeritMarks) OR (ISNULL(@rAdmissionMinMeritMarks,0) =0))
		AND ((AF.MeritMarks <=@rAdmissionMaxMeritMarks) OR (ISNULL(@rAdmissionMaxMeritMarks,0) =0))
		
		GROUP BY AF.Id,AF.FormNo,AF.ContactNo,AF.FirstName,AF.MiddleName,AF.LastName,AFS.AdmissionFormId,AFS.AdmissionStatusId,ASM.Title,AF.StatusId,AFS.DiscussionDate
		Having 
		(SUM(ASS.ObtainMark) >= @rMinMeritMarks OR  (ISNULL(@rMinMeritMarks,0) =0) ) 
		AND (SUM(ASS.ObtainMark) <= @rMaxMeritMarks OR (ISNULL(@rMaxMeritMarks,0) =0))
		ORDER BY AF.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionOptionalSubjectAdd]
	  
	@rAdmissionFormIdId bigint=0,
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
SET @rStrXml=REPLACE(@rStrXml,'ANDapos;','&apos;')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
		DELETE FROM sAdmission.tAdmissionOptionalSubject WHERE AdmissionFormId=@rAdmissionFormIdId
	
		INSERT INTO sAdmission.tAdmissionOptionalSubject
		(
			AdmissionFormId,
			ClassSubjectId
		)
		SELECT
			@rAdmissionFormIdId,ClassSubjectId
		FROM
			OPENXML (@loDoc, '/Table/OptionalSubject', 1) WITH 
			( 			
			ClassSubjectId int
			)
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionSetupAdd]
	 
	 	@rBatchId int,
        @rId int,
        @rClassId int,
        @rTotalMarks decimal(12,2),
		@rCriteriaName nvarchar(150),
		@rOrgId int=0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAdmission.tAdmissionSetup
		(
			
			Id,
			BatchId,
			ClassId,
			TotalMark,
			CriteriaName
		)
	VALUES
		(
			 
			@lNextNumber,
			@rBatchId,
			@rClassId,
			@rTotalMarks,
			@rCriteriaName
		)
		     SELECT @lNextNumber AS Result
	
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAdmission.tAdmissionSetup
	    SET
			 
			BatchId=@rBatchId,
			ClassId=@rClassId,
			TotalMark=@rTotalMarks,
			CriteriaName=@rCriteriaName
	      
	      WHERE Id = @rId
	     SELECT @lNextNumber AS Result
	 END  	

 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionSetupClassDelete]
@rClassId int
AS
BEGIN
 	 
		DELETE	FROM sAdmission.tAdmissionSetup WHERE ClassId=@rClassId	
		SELECT 1 AS RESULT
	   
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionSetupDelete]
@rId int
AS
BEGIN
 	 
		DELETE	FROM sAdmission.tAdmissionSetup WHERE Id=@rId	
		SELECT 1 AS RESULT
	   
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionSetupGet]
	 
	 @rClassId int=0,
	 @rBatchId int=0
	 
	  

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	 

BEGIN 
	 
	 
	
	SELECT 
		Id,
		ClassId,
		TotalMark,
		CriteriaName	 
      
  FROM 
            sAdmission.tAdmissionSetup
			 
  WHERE 
   (ClassId=@rClassId)
   AND BatchId=@rBatchId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionSetupStudentAllAdd]
	 	
	@rStrXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	
	
	
	 
 
		INSERT INTO sAdmission.tAdmissionSetupStudent
			 (AdmissionFormId,
			 AdmissionSetupId,
			 ObtainMark)
			SELECT		
				A.AdmissionFormId,
				A.AdmissionSetupId,
				A.ObtainMark
			FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
			WITH ( 					
					AdmissionFormId bigint,
					AdmissionSetupId int,
					ObtainMark decimal(12,2)
					
				  )A
				  LEFT JOIN sAdmission.tAdmissionSetupStudent RD
			  ON  A.AdmissionFormId = RD.AdmissionFormId 
			  AND A.AdmissionSetupId = RD.AdmissionSetupId  
			  WHERE 
			   RD.AdmissionFormId IS NULL 
			   AND RD.AdmissionSetupId IS NULL
		 
 
			
			UPDATE  sAdmission.tAdmissionSetupStudent
			SET
				
				ObtainMark = A.ObtainMark
				
			FROM
			(
			SELECT AdmissionFormId,AdmissionSetupId,ObtainMark
			FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
			WITH ( 
					AdmissionFormId bigint,
					AdmissionSetupId int,
					ObtainMark Decimal(12,2)
					
				  )) A
			INNER JOIN sAdmission.tAdmissionSetupStudent RD 
			ON RD.AdmissionFormId = A.AdmissionFormId 
			AND RD.AdmissionSetupId = A.AdmissionSetupId
			
		SELECT 1 AS Result	
 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionStudentDocumentAdd]
	 
        @rAdmissionFormId bigint,
		@rSubmitDocumentMasterId int,
		@rDocumenet NVARCHAR(MAX)
		--@rDocumenetXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		
	BEGIN		
	
	declare @rCount int

	Set @rCount = (SELECT ISNULL(COUNT (*),0)  FROM sAdmission.tAdmissionStudentDocument WHERE AdmissionFormId = @rAdmissionFormId AND SubmitDocumentMasterId= @rSubmitDocumentMasterId )

	if(@rCount =0)
	begin
	
	INSERT INTO sAdmission.tAdmissionStudentDocument
		([AdmissionFormId],[SubmitDocumentMasterId],[DocumentName])
	VALUES
		(@rAdmissionFormId,@rSubmitDocumentMasterId,@rDocumenet)
		     SELECT 1 AS Result	
			 end
			 else
			 begin
			 UPDATE  sAdmission.tAdmissionStudentDocument  SET  SubmitDocumentMasterId= @rSubmitDocumentMasterId ,DocumentName=@rDocumenet   WHERE AdmissionFormId = @rAdmissionFormId AND SubmitDocumentMasterId= @rSubmitDocumentMasterId 
			 end
	
	
	
	SELECT 1 AS Result 
	
	COMMIT TRANSACTION
	END
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionStudentDocumentDelete]
	 
        @rAdmissionFormId bigint,
		@rDocumentId bigint
		--@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN


	DELETE FROM sAdmission.tAdmissionStudentDocument Where AdmissionFormId=@rAdmissionFormId and SubmitDocumentMasterId=@rDocumentId

	
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionStudentDocumentGet]
	 
    @rAdmissionFormId bigint,
	@rOrgId bigint,
	@rClassId bigint,
	@rBatchId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN

	SELECT 
		ISNULL(D.Id,0) AS DocumentId,
		ISNULL(D.DocumentName,'')AS DocumentName,
		S.DocumentName AS DocumentFileName ,
		D.Id AS AdmissionDocumentId
		FROM sCommon.tSubmitDocumentMaster D
		INNER JOIN sAdmission.tAdmissionStudentDocument  S ON S.SubmitDocumentMasterId=D.Id AND (S.AdmissionFormId= @rAdmissionFormId  OR @rAdmissionFormId=0)	-- MantisId : 0033671
		-- #Start : Comment for Mantis Id: 	0033671 
		--INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
		--INNER JOIN 
		--(Select D1.DocumentName,D1.Id AS AdmissionDocumentId,S.DocumentName AS DocumentFileName FROM sCommon.tSubmitDocumentMaster D1
		--INNER JOIN sAdmission.tAdmissionStudentDocument  S ON S.SubmitDocumentMasterId=D1.Id AND (S.AdmissionFormId= @rAdmissionFormId  OR @rAdmissionFormId=0)
		--WHERE  D1.SubmitDocumentFunctionalityId='3' AND D1.OrgId=@rOrgId 
		--AND D1.Id IN (select SubmitDocumentMasterId from sAdmission.tAdmissionCriteriaDocument WHERE ClassId=@rClassId AND BatchId = @rBatchId  ))A ON  A.DocumentName = D.DocumentName
		-- #End : Comment for Mantis Id: 	0033671

		WHERE OrgId=@rOrgId AND D.SubmitDocumentFunctionalityId='3' -- AND DS.SourceTypeId = 2016 AND DS.SourceId = @rClassId   : Comment for Mantis Id: 	0033671
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionStudentDocumentSubmitGet]
	 
        @rAdmissionFormId bigint,
		@rOrgId bigint,
		@rClassId bigint,
	@rBatchId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN

	IF(@rAdmissionFormId =0)
	BEGIN
			SELECT  Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName, ISNULL(S.DocumentName,'') as DocumentFileName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'False'END AS IsCheck, (SELECT ISNULL(IsMandatory,0) from  sAdmission.tAdmissionCriteriaDocument where SubmitDocumentMasterId = D.Id and ClassId=@rClassId AND BatchId = @rBatchId ) IsMandatory
			 --'False' AS IsCheck
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join sAdmission.tAdmissionStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND (S.AdmissionFormId= @rAdmissionFormId  OR @rAdmissionFormId=0)
			WHERE  SubmitDocumentFunctionalityId='3' AND D.OrgId=@rOrgId AND D.Id IN (select SubmitDocumentMasterId from sAdmission.tAdmissionCriteriaDocument WHERE ClassId=@rClassId AND BatchId = @rBatchId  )
			END

			ELSE
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,ISNULL(S.DocumentName,'') as DocumentFileName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck,(SELECT ISNULL(IsMandatory,0) from  sAdmission.tAdmissionCriteriaDocument where SubmitDocumentMasterId = D.Id and ClassId=@rClassId AND BatchId = @rBatchId ) IsMandatory
			-- 'False'  AS IsCheck
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join sAdmission.tAdmissionStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND (S.AdmissionFormId= @rAdmissionFormId  OR @rAdmissionFormId=0)
			WHERE  SubmitDocumentFunctionalityId='3' AND  D.OrgId=@rOrgId AND D.Id IN (select SubmitDocumentMasterId from sAdmission.tAdmissionCriteriaDocument WHERE ClassId=@rClassId AND BatchId = @rBatchId  )
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionStudentSetupAdd]
		 @rAdmissionFormId bigint
		,@rAdmissionSetupId int
		,@rObtainMark decimal(12,2)  -- Changed decimal to decimal(12,2) for mantis 0029297 By Foram
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
 
 BEGIN TRANSACTION	
  
	 
	 
		--IF Exists(select ObtainMark from sAdmission.tAdmissionSetupStudent where Code=@rCode AND OrgId=@rOrgId)
		--	BEGIN
		--	select -101 as Result
		--	RETURN
		--END 
	
	
		--DECLARE @lNextNumber BIGINT
		--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCriteriaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	IF NOT Exists(Select ObtainMark from sAdmission.tAdmissionSetupStudent where AdmissionFormId=@rAdmissionFormId AND AdmissionSetupId=@rAdmissionSetupId)
	BEGIN
	
	INSERT INTO sAdmission.tAdmissionSetupStudent
		(
			 AdmissionFormId
			 ,AdmissionSetupId
			 ,ObtainMark
			 
		)
	VALUES
		(
			 
			 @rAdmissionFormId
			,@rAdmissionSetupId
			,@rObtainMark
			 
		)
		     SELECT 103 AS Result
	END	 
		
ELSE
	 
	 BEGIN
	 
	 
	    UPDATE  sAdmission.tAdmissionSetupStudent
	    SET 
			-- AdmissionFormId = @rAdmissionFormId
			--,AdmissionSetupId = @rAdmissionSetupId
			--,
			ObtainMark = @rObtainMark
			 
			
	      WHERE AdmissionFormId = @rAdmissionFormId AND AdmissionSetupId=@rAdmissionSetupId
	
		SELECT 104 AS Result
	END
		COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionStudentSetupAllGet]
	  @rBatchId int=0,
	  @rClassId int=0,
	  @rFormId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	 
BEGIN 
 
	SELECT 
			 ADS.Id,
			ADS.TotalMark,
			ADS.CriteriaName,
			ISNULL(ASS.ObtainMark,0) AS ObtainMark
	 
  FROM 
             
			sAdmission.tAdmissionSetup ADS
 	 LEFT JOIN sAdmission.tAdmissionSetupStudent ASS ON ADS.Id = ASS.AdmissionSetupId AND ASS.AdmissionFormId=@rFormId
	 
 	 
  WHERE   
	 
	 (ADS.BatchId=@rBatchId)
	  AND (ADS.ClassId=@rClassId)
 
 
	 
	   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionStudentSetupGet]
	 
	 @rFormId int=0 ,
	-- @rForClassId int,
	 @rBatchId int
	 

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	 

BEGIN 
	 
	 
	
	SELECT 
			 AF.Id,
			 AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName
			,AF.FirstName+' '+AF.LastName as Name
			,AF.ForClassId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			,AF.DateOfBirthInWord
			,AF.StatusId
			,SM.Title as StatusName
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail
			,AF.Remark
			,AF.PreviousSchool
			,ISNULL(AF.MeritMarks,0) AS MeritMarks
			,ISNULL(AF.MeritGrade,'') AS MeritGrade
			,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate
			,ISNULL(AF.StudentId,0) AS StudentId
  FROM 
             
			sAdmission.tAdmissionForm AF
             
            INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER  JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			 
  WHERE   
	AF.FormNo=@rFormId 
	--((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pAdmissionSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rBatchId int=0,
	@rDepartmentId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'InquiryList')
		BEGIN
			SELECT
				(SELECT COUNT(Id) FROM sAdmission.tAdmissionInquiry
				WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((ForBatchId=@rBatchId)OR(@rBatchId=0)) )AS InquiryCount,
				(SELECT COUNT(Id) FROM sAdmission.tAdmissionInquiry
				WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((ForBatchId=@rBatchId)OR(@rBatchId=0)) -- remove StatusId = 0 for MonthlyInquiryCount mantis : 0038939
				AND CONVERT(DATE,InquiryDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())) AS MonthlyInquiryCount,
				(SELECT COUNT(Id) FROM sAdmission.tAdmissionInquiry
				WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((ForBatchId=@rBatchId)OR(@rBatchId=0)) AND StatusId = 211) AS ConvertedCount
				
		END
	ELSE IF(@rType = 'InquiryGraph')
		BEGIN
			SELECT CM.Id,CM.Title,ISNULL(T.InquiryCount,0) AS InquiryCount,ISNULL(T2.ConvertedCount,0) AS ConvertedCount
			FROM  sSetup.tClassMaster CM 
				LEFT JOIN 
				(
					SELECT COUNT(Id) AS InquiryCount,ForClassId FROM sAdmission.tAdmissionInquiry
					WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((ForBatchId=@rBatchId)OR(@rBatchId=0))
					GROUP BY ForClassId
				)T ON T.ForClassId = CM.Id
				--LEFT JOIN 
				--(
				--	SELECT COUNT(Id) AS MonthlyInquiryCount,ForClassId FROM sAdmission.tAdmissionInquiry
				--	WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((ForBatchId=@rBatchId)OR(@rBatchId=0)) AND StatusId = 0
				--	AND CONVERT(DATE,InquiryDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
				--	GROUP BY ForClassId
				--)T1 ON T1.ForClassId = CM.Id
				LEFT JOIN 
				(
					SELECT COUNT(Id)AS ConvertedCount,ForClassId FROM sAdmission.tAdmissionInquiry
					WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((ForBatchId=@rBatchId)OR(@rBatchId=0)) AND StatusId = 211
					GROUP BY ForClassId
				)T2 ON T2.ForClassId = CM.Id
			WHERE ((CM.OrgId =@rOrgId)OR(@rOrgId=0))
			ORDER BY CM.OrderIndex
		END
		
		IF(@rType = 'AdmissionList')
		BEGIN
			SELECT
				(SELECT COUNT(Id) FROM sAdmission.tAdmissionForm
				WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((BatchId=@rBatchId)OR(@rBatchId=0)) )AS AdmissionCount,
				(SELECT COUNT(Id) FROM sAdmission.tAdmissionForm
				WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((BatchId=@rBatchId)OR(@rBatchId=0)) 
				AND CONVERT(DATE,CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())) AS MonthlyAdmissionCount,
				(SELECT COUNT(Id) FROM sAdmission.tAdmissionForm
				WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((BatchId=@rBatchId)OR(@rBatchId=0)) AND StatusId = 208) AS ConvertedCount
				
		END
	ELSE IF(@rType = 'AdmissionGraph')
		BEGIN
			SELECT CM.Id,CM.Title,ISNULL(T.AdmissionCount,0) AS AdmissionCount,ISNULL(T2.ConvertedCount,0) AS ConvertedCount
			FROM  sSetup.tClassMaster CM 
				LEFT JOIN 
				(
					SELECT COUNT(Id) AS AdmissionCount,ForClassId FROM sAdmission.tAdmissionForm
					WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((BatchId=@rBatchId)OR(@rBatchId=0))
					GROUP BY ForClassId
				)T ON T.ForClassId = CM.Id
				--LEFT JOIN 
				--(
				--	SELECT COUNT(Id) AS MonthlyAdmissionCount,ForClassId FROM sAdmission.tAdmissionForm
				--	WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((BatchId=@rBatchId)OR(@rBatchId=0)) 
				--	AND CONVERT(DATE,CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
				--	GROUP BY ForClassId
				--)T1 ON T1.ForClassId = CM.Id
				LEFT JOIN 
				(
					SELECT COUNT(Id)AS ConvertedCount,ForClassId FROM sAdmission.tAdmissionForm
					WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((BatchId=@rBatchId)OR(@rBatchId=0)) AND StatusId = 208
					GROUP BY ForClassId
				)T2 ON T2.ForClassId = CM.Id
			WHERE ((CM.OrgId =@rOrgId)OR(@rOrgId=0))
			ORDER BY CM.OrderIndex
		END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAPIAdmissionInquiryAdd]
		 @rAdmissionInquiryId bigint
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int 
		,@rDateOfBirth date
		,@rOrgId smallint
		,@rInquiryStatusMasterId int
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rInquiryModeId tinyint
		,@rInquiryReferenceId int
		,@rAdmissionCategoryId int
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10,2) 
		,@rMeritGrade nvarchar(20)
		,@rMeritMarksBreakup nvarchar(100)
		,@rGenderId tinyint
		,@rFollowupDate date
		,@rFollowupRemark nvarchar(150)
		,@rCreatedUserId bigint
		,@rInquiryDate date
		,@rNumber nvarchar(20) 
		,@rHandledBy nvarchar(100) 
		,@rOrgGroupId int,
		@rCastCategoryId int=0,
		@rIsHostelRequired bit=0,
		@rIsTransportRequired bit=0,
		@rIsValidateInquiryAsPerAdmission bit=0,
		@rIsGivenAdmissionForm bit=0,
		@rAlternateContactNo nvarchar(100)='',
		@rAlternateContactEmail	nvarchar(200) = '',
		@rMotherName nvarchar(100)='',
		@rDataEntryModeId smallint = 561
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lOrgGroupBatchId int=0
	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster BM WHERE BM.Id = @rForBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	DECLARE @lConfigValueAdmissionAlphaNUmeric nvarchar(50)=''
	SELECT @lConfigValueAdmissionAlphaNUmeric = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 595 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId 
	
	DECLARE @lInquiryNumber BIGINT = 0

	IF(@lConfigValueAdmissionAlphaNUmeric = '' OR @lConfigValueAdmissionAlphaNUmeric = 'False')
	BEGIN
		IF(@lConfigValue='OrgGroupBatch')
		BEGIN
			SELECT @rNumber = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId
		END
		ELSE IF(@lConfigValue='Batch')
		BEGIN
			SELECT @rNumber = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI WHERE AI.ForBatchId = @rForBatchId
		END
		ELSE IF (@lConfigValue = 'Continuous')
		BEGIN
			SELECT @rNumber =(ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry WHERE OrgGroupId = @rOrgGroupId
		END
		SET @lInquiryNumber= @rNumber
	END
	
	Declare @lStatusId smallint,@lIsValidateBirthdate bit,@lFromDateOfBirth date,@lToDateOfBirth date
	SET @lStatusId= 0
	
	IF(@rIsValidateInquiryAsPerAdmission=1)
	Begin
		Select @lIsValidateBirthdate=IsValidateBirthdate,@lFromDateOfBirth=FromDateOfBirth,@lToDateOfBirth=ToDateOfBirth from  sAdmission.tAdmissionCriteria where ClassId=@rForClassId AND BatchID=@rForBatchId
		
		if(@lIsValidateBirthdate=1 AND @rDateOfBirth NOT between @lFromDateOfBirth And @lToDateOfBirth)
		BEGIN
			Select  -101 AS Result
			return
		End
	End
	 
	BEGIN TRANSACTION	
	IF(@rAdmissionInquiryId = 0)	
	BEGIN	

	DECLARE @lNextNumber BIGINT 
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiry', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SET @rInquiryStatusMasterId = (SELECT TOP 1 ISM.Id FROM [sAdmission].[tInquiryStatusMaster] ISM INNER JOIN [sCommon].[tStatusMaster] SM ON SM.Id=ISM.StatusId WHERE SM.Id=205 AND SM.StatusTypeId=104 AND ISM.OrgGroupId=@rOrgGroupId AND ISM.InquiryMainStatusId = 11) 
	
	IF(@lInquiryNumber = 0 )
	BEGIN
		SET @lInquiryNumber = @lNextNumber
	END
			
	INSERT INTO sAdmission.tAdmissionInquiry
	(
		 Id
		,FirstName
		,MiddleName
		,LastName
		,ForClassId			 
		,ForBatchId
		,DateOfBirth
		,OrgId
		,StatusId
		,StreetOne
		,StreetTwo
		,StreetThree
		,Country
		,State
		,City
		,ZipCode
		,ContactNo
		,ContactEmail
		,Remark
		,InquiryModeId
		,InquiryReferenceId
		,AdmissionCategoryId
		,PreviousSchool
		,MeritMarks
		,MeritGrade
		,MeritMarksBreakup
		,GenderId
		,FollowupDate
		,FollowupRemark
		,CreatedUserId
		,CreatedDateTime
		,InquiryDate
		,Number
		,HandledBy
		,OrgGroupId
		,InquiryStatusId,
		CastCategoryId,
		IsHostelRequired,
		IsTransportRequired,
		IsGivenAdmissionForm,
		AlternateContactNo,
		AlternateContactEmail,
		MotherName,
		DataEntryModeId,
		InquiryNumber
	)
	VALUES
	(
		 @lNextNumber
		,@rFirstName
		,@rMiddleName
		,@rLastName
		,@rForClassId
		,@rForBatchId			 
		,@rDateOfBirth
		,@rOrgId
		,@lStatusId
		,@rStreetOne
		,@rStreetTwo
		,@rStreetThree
		,@rCountry
		,@rState
		,@rCity
		,@rZipCode
		,@rContactNo
		,@rContactEmail
		,@rRemark
		,@rInquiryModeId
		,@rInquiryReferenceId
		,@rAdmissionCategoryId
		,@rPreviousSchool
		,@rMeritMarks
		,@rMeritGrade
		,@rMeritMarksBreakup
		,@rGenderId
		,@rFollowupDate
		,@rFollowupRemark
		,@rCreatedUserId
		,sCommon.fGetDate()
		,@rInquiryDate
		,@rNumber
		,@rHandledBy
		,@rOrgGroupId
		,@rInquiryStatusMasterId,
		@rCastCategoryId,
		@rIsHostelRequired,
		@rIsTransportRequired,
		@rIsGivenAdmissionForm,
		@rAlternateContactNo,
		@rAlternateContactEmail,
		@rMotherName,
		@rDataEntryModeId,
		@lInquiryNumber
	)

	    SELECT @lNextNumber AS Result         
	END	 
	ELSE
	BEGIN
		SET @lNextNumber = @rAdmissionInquiryId
	    
		UPDATE  sAdmission.tAdmissionInquiry
	    SET
			 FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId
			,ForBatchId = @rForBatchId		 
			,DateOfBirth=@rDateOfBirth
			,OrgId=@rOrgId
			,StatusId=@lStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,InquiryModeId=@rInquiryModeId
			,InquiryReferenceId=@rInquiryReferenceId 
			,AdmissionCategoryId=@rAdmissionCategoryId
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,MeritMarksBreakup=@rMeritMarksBreakup
			,GenderId=@rGenderId
			,FollowupDate=@rFollowupDate
			,FollowupRemark=@rFollowupRemark
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			,InquiryDate=@rInquiryDate
			,HandledBy=@rHandledBy
			,InquiryStatusId = @rInquiryStatusMasterId,
			CastCategoryId = @rCastCategoryId,
			IsHostelRequired=@rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired,
			IsGivenAdmissionForm =@rIsGivenAdmissionForm,
			AlternateContactNo = @rAlternateContactNo,
			AlternateContactEmail = @rAlternateContactEmail,
			MotherName = @rMotherName,
			DataEntryModeId = @rDataEntryModeId
	      WHERE Id = @rAdmissionInquiryId 	   
		  
		  SELECT @lNextNumber AS Result 
	      --SELECT 11 AS Result      
	 END  
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		SELECT ERROR_MESSAGE()
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAPIAdmissionInquiryDetailGet]

	 @rAdmissionInquiryId bigint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Select
			AI.Id AS AdmissionInquiryId,
			AI.ForBatchId AS BatchId,
			AI.ForClassId AS ClassId,
			AI.StatusId,
			ISNULL(SM.Id,0) AS InquiryStatusMasterId,
			ISNULL(AI.GenderId,0) AS GenderId,
			ISNULL(AI.InquiryModeId,0) AS InquiryModeId,
			ISNULL(IMM.Title,'') AS InquiryMode,
			ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId,
		    ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId,
		    AI.OrgId,
		    ISNULL(AI.Number,'') AS InquiryNumber,
		    ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate,
		    OM.DisplayTitle AS OrgName,
		    BM.Title AS BatchName,
			ISNULL(CM.Title,'') AS ClassName,
			AI.FirstName,
			AI.MiddleName,
			AI.LastName,
			[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName,
			AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,				
			ISNULL(AI.DateOfBirth,'') As DateOfBirth,
			ISNULL(GM.Title,'') As Gender,			
			AI.ContactNo,
			AI.ContactEmail,			
			AI.StreetOne,
			AI.StreetTwo,
			AI.StreetThree,
			AI.Country,
			AI.State,
			AI.City,
			AI.ZipCode,
			ISNULL(AI.Remark,'') AS Remark,					
		    ISNULL(AI.PreviousSchool,'') as PreviousSchool,			
			ISNULL(AI.MeritMarks,0) AS MeritMarks,
			ISNULL(AI.MeritGrade,'') AS MeritGrade,
			ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup,
			SM.Title as StatusName,
			ISNULL(AI.FollowupDate,'') As FollowupDate,
			ISNULL(AI.FollowupRemark,'') As FollowupRemark,	
			ISNULL(IRM.Title ,'') AS InquiryReference,
			ISNULL(SCM.Title,'') AS AdmissionCategory,	
			ISNULL(AI.HandledBy,'') AS HandledBy,
			ISNULL(AI.CreatedDateTime,'') As CreatedDateTime,
			ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard,
			AI.AlternateContactNo,
			AI.AlternateContactEmail
			,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
			ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
			ISNULL(AI.MotherName,'') AS MotherName,
			CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode,
			U.DisplayTitle AS CreatedUser
			
			FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId
			INNER JOIN sSecurity.tUser U ON AI.CreatedUserId = U.Id
			Where 
			AI.Id = @rAdmissionInquiryId
					    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pAPIAdmissionInquiryGet]
	

	 @rInquiryStatusId int,
	 @rBatchId int,
	 @rOrgId int,
	 @rOrgGroupId int,
	 @rFromDate DateTime = '',
	 @rToDate DateTime = '',
	 @rInquiryNumber nvarchar(20)='' --mantis : 41025

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Select
			AI.Id AS AdmissionInquiryId,
			AI.ForBatchId AS BatchId,
			AI.ForClassId AS ClassId,
			AI.StatusId,
			ISNULL(SM.Id,0) AS InquiryStatusMasterId,
			ISNULL(AI.GenderId,0) AS GenderId,
			ISNULL(AI.InquiryModeId,0) AS InquiryModeId,
			ISNULL(IMM.Title,'') AS InquiryMode,
			ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId,
		    ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId,
		    AI.OrgId,
		    ISNULL(AI.Number,'') AS InquiryNumber, --mantis : 41025
		    ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate,
		    OM.DisplayTitle AS OrgName,
		    BM.Title AS BatchName,
			ISNULL(CM.Title,'') AS ClassName,
			AI.FirstName,
			AI.MiddleName,
			AI.LastName,
			[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName,
			AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,				
			ISNULL(AI.DateOfBirth,'') As DateOfBirth,
			ISNULL(GM.Title,'') As Gender,			
			AI.ContactNo,
			AI.ContactEmail,			
			AI.StreetOne,
			AI.StreetTwo,
			AI.StreetThree,
			AI.Country,
			AI.State,
			AI.City,
			AI.ZipCode,
			ISNULL(AI.Remark,'') AS Remark,					
		    ISNULL(AI.PreviousSchool,'') as PreviousSchool,			
			ISNULL(AI.MeritMarks,0) AS MeritMarks,
			ISNULL(AI.MeritGrade,'') AS MeritGrade,
			ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup,
			SM.Title as StatusName,
			ISNULL(AI.FollowupDate,'') As FollowupDate,
			ISNULL(AI.FollowupRemark,'') As FollowupRemark,	
			ISNULL(IRM.Title ,'') AS InquiryReference,
			ISNULL(SCM.Title,'') AS AdmissionCategory,	
			ISNULL(AI.HandledBy,'') AS HandledBy,
			ISNULL(AI.CreatedDateTime,'') As CreatedDateTime,
			ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard,
			AI.AlternateContactNo,
			AI.AlternateContactEmail
			,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
			ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
			ISNULL(AI.MotherName,'') AS MotherName,
			CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode,
			U.DisplayTitle AS CreatedUser
			
			FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId
			INNER JOIN sSecurity.tUser U ON AI.CreatedUserId = U.Id
			Where 
			((AI.InquiryStatusId = @rInquiryStatusId) OR (@rInquiryStatusId = 0))
			And ((AI.Number= @rInquiryNumber) OR (ISNULL(@rInquiryNumber,'') = '')) --mantis : 41025
			AND AI.ForBatchId = @rBatchId
			AND AI.OrgId = @rOrgId
			AND AI.OrgGroupId = @rOrgGroupId
			AND ((AI.InquiryDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
			AND ((AI.InquiryDate <=  @rToDate) OR (ISNULL(@rToDate,'') = ''))


			
			    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pExportAdmissionInquiryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rId bigint = 0,	 
	 @rForClassId int = 0,
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	 @rInquiryStatusMasterId int = 0,
	 @rOrgId int,
	 @rFirstName nvarchar(100) = '',
	 @rLastName nvarchar(100) = '',
	 @rFromDate datetime=Null,
	 @rToDate datetime=Null,
	 @rForBatchId int = 0,
	 @rDepartmentId int = 0,
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryModeId smallint=0,
	 @rInquiryReferenceId int=0,
	 @rNumber nvarchar(20)='', --changes in Mantis :0041025
	 @rOrgGroupBatchId int = 0,
	 @rFollowUpdate datetime='',
	 @rIsTransportRequired int=0,
	 @rIsHostelRequired int=0,
	 @rOrderBy int =0,
	 @rIsGivenAdmissionForm int =0,
	 @rContactNo nvarchar(100)='',
	 @rAdmissionInquiryIdText nvarchar(20) ='',
	 @rHandledBy nvarchar(100) = '',
	 @rGenderId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	SET @rToDate = DATEADD(d,1,@rToDate)
	BEGIN
		SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName= sCommon.fSearchStringGet(@rLastName)
		SET @rHandledBy= sCommon.fSearchStringGet(@rHandledBy)
	END

DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

-- CTE for Admission Form custom Field
;WITH AdmissionInquiryCriteriaFormCTE AS (SELECT DISTINCT (AIF.FieldGroup+' - '+AIF.FieldRemark) AS FieldRemark FROM sAdmission.tAdmissionInquiryForm AIF 
	LEFT JOIN sAdmission.tAdmissionInquiryField AI ON AI.AdmissionInquiryFormId = AIF.Id 
	WHERE (ClassId = @rForClassId  OR @rForClassId=0)
	AND (AI.AdmissionInquiryFormId = @rId  OR @rId = 0)
	AND (BatchId = @rForBatchId OR @rForBatchId=0) 
)

SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(FieldRemark) FROM AdmissionInquiryCriteriaFormCTE GROUP BY FieldRemark
ORDER BY FieldRemark FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

IF object_id('tempdb..##tempAdmissionInquiryCustomField') IS NOT NULL 
BEGIN
   DROP TABLE ##tempAdmissionInquiryCustomField 
END

IF(@cols IS NOT NULL)
BEGIN 
	SET @query = N'SELECT DISTINCT AdmissionInquiryId,' + @cols + N' INTO ##tempAdmissionInquiryCustomField FROM 
	(
		SELECT DISTINCT  AI.AdmissionInquiryId,AI.AdmissionInquiryFieldResponse, (AIF.FieldGroup+'' - ''+AIF.FieldRemark) AS FieldRemark
		FROM sAdmission.tAdmissionInquiryForm AIF
		LEFT JOIN sAdmission.tAdmissionInquiryField AI ON AI.AdmissionInquiryFormId = AIF.Id
		WHERE (AIF.ClassId = '+CONVERT(nvarchar(10),@rForClassId)+'  OR '+CONVERT(nvarchar(10),@rForClassId)+'=0)
		AND (AIF.BatchId = '+CONVERT(nvarchar(10),@rForBatchId)+' OR '+CONVERT(nvarchar(10),@rForBatchId)+'=0)
	) x
	PIVOT
	(
		MAX(AdmissionInquiryFieldResponse)
		FOR FieldRemark IN (' + @cols + N')
	) p'

	exec sp_executesql @query
	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CASE WHEN @rAdmissionInquiryIdText = '' THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText --changes in Mantis :0041025
		,AI.Id
		,AI.ForBatchId
		,AI.ForClassId
		,AI.StatusId
		,ISNULL(SM.Id,0) AS InquiryStatusMasterId
		,ISNULL(AI.GenderId,0) AS GenderId
		,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
		,ISNULL(IMM.Title,'') AS InquiryMode
		,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		,AI.OrgId
		,ISNULL(AI.Number,'') AS InquiryNumber --changes in Mantis :0041025
		,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		,OM.DisplayTitle AS OrgName
		,BM.Title AS ForBatch
		,ISNULL(CM.Title,'') AS ClassName	
		,AI.FirstName
		,AI.MiddleName
		,AI.LastName
		,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
		,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
		,ISNULL(AI.DateOfBirth,'') As DateOfBirth
		,ISNULL(GM.Title,'') As Gender			
		,AI.ContactNo
		,AI.ContactEmail			
		,AI.StreetOne
		,AI.StreetTwo
		,AI.StreetThree
		,AI.Country
		,AI.State
		,AI.City
		,AI.ZipCode
		,ISNULL(AI.Remark,'') AS Remark						
		,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
		,ISNULL(AI.MeritMarks,0) AS MeritMarks
		,ISNULL(AI.MeritGrade,'') AS MeritGrade
		,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
		,SM.Title as StatusName	
		,ISNULL(AI.FollowupDate,'') As FollowupDate
		,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
		,ISNULL(IRM.Title ,'') AS InquiryReference	
		,ISNULL(SCM.Title,'') AS AdmissionCategory		
		,ISNULL(AI.HandledBy,'') AS HandledBy
		,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
		,ISNULL(AI.StudentId,0) AS StudentId,
		ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
		ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
		ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
		CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
		ISNULL(SM.HighlightColor,'') AS HighlightColor,
		ISNULL(SA.PreviousStandard,'') As PreviousStandard,
		AI.AlternateContactNo,
		AI.AlternateContactEmail
		,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
		ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
		ISNULL(AI.MotherName,'') AS MotherName,
		CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
		,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		,ISNULL(AI.LiveWithId,0) AS LiveWithId
		,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
		,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
		,ISNULL(AI.FatherName,'') AS FatherName
		,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
		,ISNULL(AI.FatherIncome,0) AS FatherIncome 
		,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
		,ISNULL(AI.FatherMail,'') AS FatherMail
		,ISNULL(AI.FatherQualification,'') AS FatherQualification
		,ISNULL(AI.MotherOccupation,'') As MotherOccupation
		,ISNULL(AI.MotherIncome,0) AS MotherIncome
		,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
		,ISNULL(AI.MotherMail,'') AS MotherMail 
		,ISNULL(AI.MotherQualification,'') AS  MotherQualification
		,ISNULL(AI.Stream,'') AS Stream
		,ISNULL(AI.Board,'') AS Board
		,ISNULL(CCM.Title,'') AS CasteCategory
		,ISNULL(AI.InquiryReferenceRemark,'') AS InquiryReferenceRemark
		,ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo
		,tempACF.*
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
			LEFT JOIN  scommon.tCastCategoryMaster CCM on CCM.Id = AI.CastCategoryId
			LEFT JOIN sAdmission.tAdmissionInquiryField AIF ON AIF.AdmissionInquiryFormId = AI.Id 
			LEFT JOIN sAdmission.tAdmissionInquiryForm AIF1 ON AIF.AdmissionInquiryFormId = AIF1.Id   
			LEFT JOIN ##tempAdmissionInquiryCustomField tempACF ON tempACF.AdmissionInquiryId = AI.Number
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (ISNULL(@rNumber,'')='')) --changes in Mantis :0041025
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1 END)
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1 END)
	 AND ((AI.ContactNo = @rContactNo) OR (ISNULL(@rContactNo, '')=''))
	 AND ((AI.HandledBy like @rHandledBy) OR (ISNULL(@rHandledBy, '')=''))
	 AND ((GM.Id = @rGenderId) OR (@rGenderId = 0))
	 Order by Case @rOrderBy When 1 then AI.MeritMarks END desc, Case @rOrderBy when 0 then AI.Number Else AI.Number END desc  
END	
ELSE 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CASE WHEN @rAdmissionInquiryIdText = '' THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText, --changes in Mantis :0041025
		 AI.Id
		,AI.ForBatchId
		,AI.ForClassId
		,AI.StatusId
		,ISNULL(SM.Id,0) AS InquiryStatusMasterId
		,ISNULL(AI.GenderId,0) AS GenderId
		,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
		,ISNULL(IMM.Title,'') AS InquiryMode
		,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		,AI.OrgId
		,ISNULL(AI.Number,'') AS InquiryNumber --changes in Mantis :0041025
		,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		,OM.DisplayTitle AS OrgName
		,BM.Title AS ForBatch
		,ISNULL(CM.Title,'') AS ClassName	
		,AI.FirstName
		,AI.MiddleName
		,AI.LastName
		,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
		,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
		,ISNULL(AI.DateOfBirth,'') As DateOfBirth
		,ISNULL(GM.Title,'') As Gender			
		,AI.ContactNo
		,AI.ContactEmail			
		,AI.StreetOne
		,AI.StreetTwo
		,AI.StreetThree
		,AI.Country
		,AI.State
		,AI.City
		,AI.ZipCode
		,ISNULL(AI.Remark,'') AS Remark						
		,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
		,ISNULL(AI.MeritMarks,0) AS MeritMarks
		,ISNULL(AI.MeritGrade,'') AS MeritGrade
		,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
		,SM.Title as StatusName
		,ISNULL(AI.FollowupDate,'') As FollowupDate
		,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
		,ISNULL(IRM.Title ,'') AS InquiryReference	
		,ISNULL(SCM.Title,'') AS AdmissionCategory		
		,ISNULL(AI.HandledBy,'') AS HandledBy
		,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
		,ISNULL(AI.StudentId,0) AS StudentId,
		ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
		ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
		ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
		CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
		ISNULL(SM.HighlightColor,'') AS HighlightColor,
		ISNULL(SA.PreviousStandard,'') As PreviousStandard,
		AI.AlternateContactNo,
		AI.AlternateContactEmail
		,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
		ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
		ISNULL(AI.MotherName,'') AS MotherName,
		CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
		,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		,ISNULL(AI.LiveWithId,0) AS LiveWithId
		,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
		,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
		,ISNULL(AI.FatherName,'') AS FatherName
		,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
		,ISNULL(AI.FatherIncome,0) AS FatherIncome 
		,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
		,ISNULL(AI.FatherMail,'') AS FatherMail
		,ISNULL(AI.FatherQualification,'') AS FatherQualification
		,ISNULL(AI.MotherOccupation,'') As MotherOccupation
		,ISNULL(AI.MotherIncome,0) AS MotherIncome
		,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
		,ISNULL(AI.MotherMail,'') AS MotherMail 
		,ISNULL(AI.MotherQualification,'') AS  MotherQualification
		,ISNULL(AI.Stream,'') AS Stream
		,ISNULL(AI.Board,'') AS Board
		,ISNULL(CCM.Title,'') AS CasteCategory
		,ISNULL(AI.InquiryReferenceRemark,'') AS InquiryReferenceRemark
		,ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo
		,0 AS AdmissionInquiryId
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
			LEFT JOIN  scommon.tCastCategoryMaster CCM on CCM.Id = AI.CastCategoryId 
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (ISNULL(@rNumber,'')='')) --changes in Mantis :0041025
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1  END)
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1 END)
	 AND ((AI.ContactNo = @rContactNo) OR (ISNULL(@rContactNo, '')=''))
	 AND ((AI.HandledBy like @rHandledBy) OR (ISNULL(@rHandledBy, '')=''))
	 AND ((GM.Id = @rGenderId) OR (@rGenderId = 0))
	 Order by Case @rOrderBy When 1 then AI.MeritMarks END desc, Case @rOrderBy when 0 then AI.Number Else  AI.Number END desc  
END		    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pExportAllAdmissionFormDetail]
	 @rAdmissionFormId bigint = 0,
	 @rFormNo int=0,
	 @rForClassId int=0,
	 @rBatchId int=0,
	 @rStatusId smallint='',
	 @rOrgId int,
	 @rFirstName nvarchar(200)='',
	 @rLastName nvarchar(200)='',
 
	 @rFromDate datetime= '1900-01-01',
	 @rToDate datetime = '9990-12-31',
	 @rDepartmentId int=0,
	 @rDataEntryStatusId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	SET @rToDate = DATEADD(d,1,@rToDate)		 

BEGIN 
		--IF @rIsSearch = 1
		--BEGIN
		--SET @rFirstName = ISNULL(@rFirstName,'')
		--SET @rLastName = ISNULL(@rLastName,'')
		--	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		--	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		--END
	CREATE Table #tempAdmissionForm
	(
		AdmissionFormId bigint,
		FormNo int,
		FirstName nvarchar(500),
		MiddleName nvarchar(500),
		LastName nvarchar(500),
		Name nvarchar(500),
		ClassId int,
		ClassName nvarchar(500),
		ForBatch nvarchar(500),
		DateOfBirth date,
		--StatusName nvarchar(200),
		ProcessStatus nvarchar(100),
		FormStatus nvarchar(500),
		StreetOne nvarchar(500),
		StreetTwo nvarchar(500),
		StreetThree nvarchar(500),
		Country nvarchar(500),
		State nvarchar(500),
		City nvarchar(500),
		ZipCode nvarchar(500),
		ContactNo nvarchar(500),
		ContactEmail nvarchar(500),
		Religion nvarchar(500),
		Nationality nvarchar(500),
		MotherTongue nvarchar(500),
		OtherInformation nvarchar(500),
		IsPysicalDeformity	bit	,
		PysicalDeformityRemark	nvarchar(500)	,
		IsMajorIllness	bit	,
		MajorIllnessRemark	nvarchar(500)	,
		IsAllergy	bit	,
		AllergyRemark	nvarchar(500)	,
		BirthPlace	nvarchar(500)	,
		BirthTaluka	nvarchar(500)	,
		BirthDistrict	nvarchar(500),
		BloodGroupName	nvarchar(500)	,
		AdhaarNumber	nvarchar(500)	,
		IsHostelRequired	nvarchar(500)	,
		IsTransportRequired	nvarchar(500)	,
		Remark nvarchar(500),
		PreviousSchool nvarchar(500),
		MeritMarks decimal(6,2),
		MeritGrade nvarchar(500),
		Gender nvarchar(500),
		
		FamilyCast nvarchar(500),
		FamilySubCast nvarchar(500),
		 
		AdmissionFormDate datetime,
		FatherName nvarchar(500),
		--FatherDateOfBirth date,
		FatherOccupation nvarchar(500),
		FatherQualification nvarchar(500),
		FatherDesignation  nvarchar(500),
		FatherOrganization nvarchar(500),
		FatherOfficePhone nvarchar(500),
		FatherContactNo nvarchar(500),
		FatherMail nvarchar(500),
		FatherOfficeAddress nvarchar(500),
		FatherIncome int	,
		FatherAadharNo nvarchar(20),
		MotherName nvarchar(500),
		--MotherDateOfBirth date ,
		MotherOccupation nvarchar(500),
		MotherQualification nvarchar(500),
		MotherDesignation nvarchar(500),
		MotherOrganization nvarchar(500),
		MotherOfficePhone nvarchar(500),
		MotherContactNo nvarchar(500),
		MotherMail nvarchar(500),
		MotherOfficeAddress nvarchar(500), 
		MotherIncome int,
		RelationshipName nvarchar(500),
		GuardianName nvarchar(500),
		--GuardianDateOfBirth date,
		GuardianOccupation nvarchar(500),
		GuardianQualification nvarchar(500),
		GuardianOrganization nvarchar(500),
		GuardianDesignation nvarchar(500),
		GuardianOfficePhone nvarchar(500),
		GuardianContactNo nvarchar(500),
		GuardianMail nvarchar(500),
		GuardianOfficeAddress nvarchar(500),
		GuardianIncome int,
		FatherPassOutYear nvarchar(500),
		MotherPassOutYear nvarchar(500),
		RelativePassOutYear nvarchar(500),
		CustomField1Answer  nvarchar(500),
		CustomField2Answer  nvarchar(500),
		CustomField3Answer  nvarchar(500),
		CastCategory nvarchar(50),
		DataEntryMode nvarchar(20),
		StatusName nvarchar(200) -- Added for mantis : 34323 by Nilesh
		,PENNumber bigint -- Added for mantis : 43425 by Vishruti
		,ApaarIdNumber nvarchar(100) -- Added for mantis : 43425 by Vishruti
		
	)
	Insert into #tempAdmissionForm
	(
		AdmissionFormId,
		FormNo ,
		FirstName ,
		MiddleName ,
		LastName ,
		Name ,
		ClassId,
		ClassName ,
		ForBatch ,
		DateOfBirth ,
		--StatusName ,
		ProcessStatus ,
		FormStatus ,
		StreetOne ,
		StreetTwo ,
		StreetThree,
		Country,
		State ,
		City ,
		ZipCode ,
		ContactNo ,
		ContactEmail,
		Religion,
		Nationality,
		MotherTongue,
		OtherInformation,
		IsPysicalDeformity,
		PysicalDeformityRemark,
		IsMajorIllness,
		MajorIllnessRemark,
		IsAllergy,
		AllergyRemark,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BloodGroupName,
		AdhaarNumber,
		IsHostelRequired,
		IsTransportRequired,
		Remark ,
		PreviousSchool,
		MeritMarks ,
		MeritGrade,
		Gender,
		
		FamilyCast ,
		FamilySubCast,
		 
		AdmissionFormDate,
		FatherName ,
		--FatherDateOfBirth ,
		FatherOccupation,
		FatherQualification ,
		FatherDesignation,
		FatherOrganization,
		FatherOfficePhone,
		FatherContactNo  ,
		FatherMail  ,
		FatherOfficeAddress   ,
		FatherIncome  	,
		FatherAadharNo,
		MotherName  ,
		--MotherDateOfBirth   ,
		MotherOccupation  ,
		MotherQualification  ,
		MotherDesignation,
		MotherOrganization,
		MotherOfficePhone,
		MotherContactNo  ,
		MotherMail  ,
		MotherOfficeAddress  , 
		MotherIncome  ,
		RelationshipName  ,
		GuardianName  ,
		--GuardianDateOfBirth  ,
		GuardianOccupation  ,
		GuardianQualification  ,
		GuardianDesignation,
		GuardianOrganization,
		GuardianOfficePhone,
		GuardianContactNo  ,
		GuardianMail  ,
		GuardianOfficeAddress   ,
		GuardianIncome  ,
		FatherPassOutYear,
		MotherPassOutYear,
		RelativePassOutYear,
		CustomField1Answer,
		CustomField2Answer,
		CustomField3Answer,
		CastCategory,
		DataEntryMode,
		StatusName -- Added for mantis : 34323 by Nilesh
		,PENNumber
		,ApaarIdNumber
	)
	SELECT 
			  AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName
			,AF.FirstName+' '+AF.LastName as Name
			--,AF.ForClassId
			--,AF.BatchId
			,CM.Id AS ClassId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			--,AF.DateOfBirthInWord
			--,AF.StatusId
			--,SM.Title as StatusName
			,SM1.Title AS DataEntryStatus
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail,
			RM.Title AS Religion,
			AF.Nationality,
			AF.MotherTongue,
			AF.OtherInformation,
			AF.IsPysicalDeformity,
			AF.PysicalDeformityRemark,
			AF.IsMajorIllness,
			AF.MajorIllnessRemark,
			AF.IsAllergy,
			AF.AllergyRemark,
			AF.BirthPlace,
			AF.BirthTaluka,
			AF.BirthDistrict,
			BGm.Title,
			AF.AdhaarNumber,
			CAse WHEn ISnull(AF.IsHostelRequired,0)=0 THEN 'No' Else 'Yes' END AS IsHostelRequired,
			CAse WHEn ISnull(AF.IsTransportRequired,0)=0 THEN 'No' Else 'Yes' END AS IsTransportRequired
			
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			--,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			--,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			--,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate,
			--,ISNULL(AF.StudentId,0) AS StudentId
			--,AF.StudentPhoto,
			ISNULL(AFFD.FatherName,'') AS FatherName,
			--Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherDesignation,'') AS FatherDesignation,
			Isnull(AFFD.FatherOrganization,'') AS FatherOrganization,
			Isnull(AFFD.FatherOfficePhone,'') AS FatherOfficePhone,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.FatherAdhaarNumber,'') as FatherAadharNo,
			Isnull(AFFD.MotherName,'') AS MotherName,
			--iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			
			Isnull(AFFD.MotherDesignation,'') AS MotherDesignation,
			Isnull(AFFD.MotherOrganization,'') AS MotherOrganization,
			Isnull(AFFD.MotherOfficePhone,'') AS MotherOfficePhone,
			
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			--isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			
			Isnull(AFFD.RelativeDesignation,'') AS GuardianDesignation,
			Isnull(AFFD.RelativeOrganization,'') AS GuardianOrganization,
			Isnull(AFFD.RelativeOfficePhone,'') AS GuardianOfficePhone,
			
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AFFD.FatherPassOutYear,'') AS FatherPassOutYear,
			isnull(AFFD.MotherPassOutYear,'')As MotherPassOutYear,
			isnull(AFFD.RelativePassOutYear,'') As RelativePassOutYear,
			isnull(AF.CustomField1Answer,'') AS CustomField1Answer,
			isnull(AF.CustomField2Answer,'')As CustomField2Answer,
			isnull(AF.CustomField3Answer,'') As CustomField3Answer,
   			ISNULL(CCM.Title,'') AS CastCategory,
			CASE WHEN AF.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END AS DataEntryMode,
			SM.Title as StatusName -- Added for mantis : 34323 by Nilesh
			,ISNULL(PENNumber,0) AS PENNumber -- Added for mantis : 43425 by Vishruti
			,ISNULL(ApaarIdNumber,'') AS ApaarIdNumber -- Added for mantis : 43425 by Vishruti
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sCommon.tStatusMaster SM1 ON SM1.Id=AF.DataEntryStatusId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId			
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			LEFT JOIN sCommon.tReligionMaster RM on RM.Id= AF.religionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM on BGM.Id= AF.BloodGroupId
			--LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=AF.CastCategoryId
			 
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
 
 create table #tempStudentAcademic
(
	AdmissionFormId bigint,
	StudentAcademicYear1 nvarchar(500),	StudentAdmissionClass1 nvarchar(500),	StudentInstituteName1 nvarchar(500),	StudentInstituteCity1 nvarchar(500),			StudentInstituteAffiliaton1 nvarchar(500),	StudentLanguage1 nvarchar(500),	StudentResult1 Nvarchar(500),
	StudentAcademicYear2 nvarchar(500),	StudentAdmissionClass2 nvarchar(500),	StudentInstituteName2 nvarchar(500),	StudentInstituteCity2 nvarchar(500),	StudentInstituteAffiliaton2 nvarchar(500),	StudentLanguage2 nvarchar(500),	StudentResult2 Nvarchar(500),
	StudentAcademicYear3 nvarchar(500),	StudentAdmissionClass3 nvarchar(500),	StudentInstituteName3 nvarchar(500),	StudentInstituteCity3 nvarchar(500),	StudentInstituteAffiliaton3 nvarchar(500),	StudentLanguage3 nvarchar(500),	StudentResult3 Nvarchar(500),
	StudentAcademicYear4 nvarchar(500),	StudentAdmissionClass4 nvarchar(500),	StudentInstituteName4 nvarchar(500),	StudentInstituteCity4 nvarchar(500),	StudentInstituteAffiliaton4 nvarchar(500),	StudentLanguage4 nvarchar(500),	StudentResult4 Nvarchar(500),
	StudentAcademicYear5 nvarchar(500),	StudentAdmissionClass5 nvarchar(500),	StudentInstituteName5 nvarchar(500),	StudentInstituteCity5 nvarchar(500),	StudentInstituteAffiliaton5 nvarchar(500),	StudentLanguage5 nvarchar(500),	StudentResult5 Nvarchar(500),
	StudentAcademicYear6 nvarchar(500),	StudentAdmissionClass6 nvarchar(500),	StudentInstituteName6 nvarchar(500),	StudentInstituteCity6 nvarchar(500),	StudentInstituteAffiliaton6 nvarchar(500),	StudentLanguage6 nvarchar(500),	StudentResult6 Nvarchar(500),
	StudentAcademicYear7 nvarchar(500),	StudentAdmissionClass7 nvarchar(500),	StudentInstituteName7 nvarchar(500),	StudentInstituteCity7 nvarchar(500),	StudentInstituteAffiliaton7 nvarchar(500),	StudentLanguage7 nvarchar(500),	StudentResult7 Nvarchar(500),
	StudentAcademicYear8 nvarchar(500),	StudentAdmissionClass8 nvarchar(500),	StudentInstituteName8 nvarchar(500),	StudentInstituteCity8 nvarchar(500),	StudentInstituteAffiliaton8 nvarchar(500),	StudentLanguage8 nvarchar(500),	StudentResult8 Nvarchar(500),
	StudentAcademicYear9 nvarchar(500),	StudentAdmissionClass9 nvarchar(500),	StudentInstituteName9 nvarchar(500),	StudentInstituteCity9 nvarchar(500),	StudentInstituteAffiliaton9 nvarchar(500),	StudentLanguage9 nvarchar(500),	StudentResult9 Nvarchar(500),
	StudentAcademicYear10 nvarchar(500),	StudentAdmissionClass10 nvarchar(500),	StudentInstituteName10 nvarchar(500),	StudentInstituteCity10 nvarchar(500),	StudentInstituteAffiliaton10 nvarchar(500),	StudentLanguage10 nvarchar(500),	StudentResult10 Nvarchar(500) )
INsert into #tempStudentAcademic
(AdmissionFormId, 
StudentAcademicYear1  ,	StudentAdmissionClass1  ,	StudentInstituteName1  ,	StudentInstituteCity1  ,	StudentInstituteAffiliaton1   ,	StudentLanguage1  ,	StudentResult1  ,
	StudentAcademicYear2  ,	StudentAdmissionClass2  ,	StudentInstituteName2  ,	StudentInstituteCity2  ,	StudentInstituteAffiliaton2  ,	StudentLanguage2  ,	StudentResult2   ,
	StudentAcademicYear3   ,	StudentAdmissionClass3  ,	StudentInstituteName3  ,	StudentInstituteCity3  ,	StudentInstituteAffiliaton3  ,	StudentLanguage3  ,	StudentResult3  ,
	StudentAcademicYear4  ,	StudentAdmissionClass4  ,	StudentInstituteName4  ,	StudentInstituteCity4  ,	StudentInstituteAffiliaton4  ,	StudentLanguage4   ,	StudentResult4  ,
	StudentAcademicYear5  ,	StudentAdmissionClass5  ,	StudentInstituteName5  ,	StudentInstituteCity5  ,	StudentInstituteAffiliaton5  ,	StudentLanguage5  ,	StudentResult5  ,
	StudentAcademicYear6  ,	StudentAdmissionClass6  ,	StudentInstituteName6  ,	StudentInstituteCity6  ,	StudentInstituteAffiliaton6  ,	StudentLanguage6  ,	StudentResult6  ,
	StudentAcademicYear7  ,	StudentAdmissionClass7  ,	StudentInstituteName7  ,	StudentInstituteCity7  ,	StudentInstituteAffiliaton7  ,	StudentLanguage7   ,	StudentResult7  ,
	StudentAcademicYear8  ,	StudentAdmissionClass8  ,	StudentInstituteName8  ,	StudentInstituteCity8  ,	StudentInstituteAffiliaton8  ,	StudentLanguage8  ,	StudentResult8  ,
	StudentAcademicYear9  ,	StudentAdmissionClass9  ,	StudentInstituteName9  ,	StudentInstituteCity9  ,	StudentInstituteAffiliaton9  ,	StudentLanguage9  ,	StudentResult9  ,
	StudentAcademicYear10  ,	StudentAdmissionClass10  ,	StudentInstituteName10  ,	StudentInstituteCity10  ,	StudentInstituteAffiliaton10  ,	StudentLanguage10  ,	StudentResult10  
)

SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  AcademicYear  end),'') StudentAcademicYear1,
  ISNULL(max(case when    rn = 1  then  AdmissionClass  end),'') StudentAdmissionClass1,
   ISNULL(max(case when    rn = 1  then  InstituteName  end),'') StudentInstituteName1,
  ISNULL(max(case when    rn = 1  then  InstituteCity  end),'') StudentInstituteCity1,
  ISNULL(max(case when    rn = 1  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton1,
  ISNULL(max(case when    rn = 1  then  Language  end),'') StudentLanguage1,
    ISNULL(max(case when    rn = 1  then  Result  end),'') StudentResult1,
     
  ISNULL(max(case when    rn = 2 then  AcademicYear  end),'') StudentAcademicYear2,
  ISNULL(max(case when    rn = 2  then  AdmissionClass  end),'') StudentAdmissionClass2,
   ISNULL(max(case when    rn = 2  then  InstituteName  end),'') StudentInstituteName2,
  ISNULL(max(case when    rn = 2  then  InstituteCity  end),'') StudentInstituteCity2,
  ISNULL(max(case when    rn = 2  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton2,
  ISNULL(max(case when    rn = 2  then  Language  end),'') StudentLanguage2,
    ISNULL(max(case when    rn = 2  then  Result  end),'') StudentResult2,

     
  ISNULL(max(case when    rn = 3  then  AcademicYear  end),'') StudentAcademicYear3,
  ISNULL(max(case when    rn = 3  then  AdmissionClass  end),'') StudentAdmissionClass3,
   ISNULL(max(case when    rn = 3  then  InstituteName  end),'') StudentInstituteName3,
  ISNULL(max(case when    rn = 3  then  InstituteCity  end),'') StudentInstituteCity3,
  ISNULL(max(case when    rn = 3  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton3,
  ISNULL(max(case when    rn = 3  then  Language  end),'') StudentLanguage3,
  ISNULL(max(case when    rn = 3  then  Result  end),'') StudentResult3,
     
  ISNULL(max(case when    rn = 4  then  AcademicYear  end),'') StudentAcademicYear4,
  ISNULL(max(case when    rn = 4  then  AdmissionClass  end),'') StudentAdmissionClass4,
   ISNULL(max(case when    rn = 4  then  InstituteName  end),'') StudentInstituteName4,
  ISNULL(max(case when    rn = 4  then  InstituteCity  end),'') StudentInstituteCity4,
  ISNULL(max(case when    rn = 4  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton4,
  ISNULL(max(case when    rn = 4  then  Language  end),'') StudentLanguage4,
  ISNULL(max(case when    rn = 4  then  Result  end),'') StudentResult4,
           
  ISNULL(max(case when    rn = 5  then  AcademicYear  end),'') StudentAcademicYear5,
  ISNULL(max(case when    rn = 5  then  AdmissionClass  end),'') StudentAdmissionClass5,
   ISNULL(max(case when    rn = 5  then  InstituteName  end),'') StudentInstituteName5,
  ISNULL(max(case when    rn = 5  then  InstituteCity  end),'') StudentInstituteCity5,
  ISNULL(max(case when    rn = 5  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton5,
  ISNULL(max(case when    rn = 5  then  Language  end),'') StudentLanguage5,
    ISNULL(max(case when    rn = 5  then  Result  end),'') StudentResult5,
   
  ISNULL(max(case when    rn = 6  then  AcademicYear  end),'') StudentAcademicYear6,
  ISNULL(max(case when    rn = 6  then  AdmissionClass  end),'') StudentAdmissionClass6,
   ISNULL(max(case when    rn = 6  then  InstituteName  end),'') StudentInstituteName6,
  ISNULL(max(case when    rn = 6  then  InstituteCity  end),'') StudentInstituteCity6,
  ISNULL(max(case when    rn = 6  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton6,
  ISNULL(max(case when    rn = 6  then  Language  end),'') StudentLanguage6,
  ISNULL(max(case when    rn = 6  then  Result  end),'') StudentResult6,
     
  ISNULL(max(case when    rn = 7  then  AcademicYear  end),'') StudentAcademicYear7,
  ISNULL(max(case when    rn = 7  then  AdmissionClass  end),'') StudentAdmissionClass7,
  ISNULL(max(case when    rn = 7  then  InstituteName  end),'') StudentInstituteName7,
  ISNULL(max(case when    rn = 7  then  InstituteCity  end),'') StudentInstituteCity7,
  ISNULL(max(case when    rn = 7  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton7,
  ISNULL(max(case when    rn = 7  then  Language  end),'') StudentLanguage7,
   ISNULL(max(case when    rn = 7  then  Result  end),'') StudentResult7,
  
  ISNULL(max(case when    rn = 8  then  AcademicYear  end),'') StudentAcademicYear8,
  ISNULL(max(case when    rn = 8  then  AdmissionClass  end),'') StudentAdmissionClass8,
   ISNULL(max(case when    rn = 8  then  InstituteName  end),'') StudentInstituteName8,
  ISNULL(max(case when    rn = 8  then  InstituteCity  end),'') StudentInstituteCity8,
  ISNULL(max(case when    rn = 8  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton8,
  ISNULL(max(case when    rn = 8  then  Language  end),'') StudentLanguage8,
  ISNULL(max(case when    rn = 8  then  Result  end),'') StudentResult8,
     
  ISNULL(max(case when    rn = 9  then  AcademicYear  end),'') StudentAcademicYear9,
  ISNULL(max(case when    rn = 9  then  AdmissionClass  end),'') StudentAdmissionClass9,
   ISNULL(max(case when    rn = 9  then  InstituteName  end),'') StudentInstituteName9,
  ISNULL(max(case when    rn = 9  then  InstituteCity  end),'') StudentInstituteCity9,
  ISNULL(max(case when    rn = 9  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton9,
  ISNULL(max(case when    rn = 9  then  Language  end),'') StudentLanguage9,
   ISNULL(max(case when    rn = 9  then  Result  end),'') StudentResult9,
     
  ISNULL(max(case when    rn = 10  then  AcademicYear  end),'') StudentAcademicYear10,
  ISNULL(max(case when    rn = 10 then  AdmissionClass  end),'') StudentAdmissionClass10,
   ISNULL(max(case when    rn = 10 then  InstituteName  end),'') StudentInstituteName10,
  ISNULL(max(case when    rn = 10  then  InstituteCity  end),'') StudentInstituteCity10,
  ISNULL(max(case when    rn = 10  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton10,
  ISNULL(max(case when    rn = 10  then  Language  end),'') StudentLanguage10,
    ISNULL(max(case when    rn = 10  then  Result  end),'') StudentResult10
                     
from
(
  select AP.AdmissionFormId,  AcademicYear, AdmissionClass, InstituteName, InstituteCity,InstituteAffiliaton,Language,Result
      , row_number() over(partition by AP.AdmissionFormId 
                          Order by AP.AdmissionFormId) rn
  from sAdmission.tAdmissionFormStudentAcademic AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
  
) d
group by AdmissionFormId order by AdmissionFormId 

Create Table #tempFatherAcademic
(
	AdmissionFormId bigint,
	FatherAcademicYear1 nvarchar(500),
	FatherInstituteName1 nvarchar(500),
	FatherInstituteCity1 nvarchar(500),
	FatherInstituteAffilation1 nvarchar(500),
	FatherAdmissionClass1 nvarchar(500),
	FatherMediumStudy1 nvarchar(500),
	
	FatherAcademicYear2 nvarchar(500),
	FatherInstituteName2 nvarchar(500),
	FatherInstituteCity2 nvarchar(500),
	FatherInstituteAffilation2 nvarchar(500),
	FatherAdmissionClass2 nvarchar(500),
	FatherMediumStudy2 nvarchar(500),
	
	
	FatherAcademicYear3 nvarchar(500),
	FatherInstituteName3 nvarchar(500),
	FatherInstituteCity3 nvarchar(500),
	FatherInstituteAffilation3 nvarchar(500),
	FatherAdmissionClass3 nvarchar(500),
	FatherMediumStudy3 nvarchar(500),
	
	
	
	FatherAcademicYear4 nvarchar(500),
	FatherInstituteName4 nvarchar(500),
	FatherInstituteCity4 nvarchar(500),
	FatherInstituteAffilation4 nvarchar(500),
	FatherAdmissionClass4 nvarchar(500),
	FatherMediumStudy4 nvarchar(500),
	
	FatherAcademicYear5 nvarchar(500), 
	FatherInstituteName5 nvarchar(500), 
	FatherInstituteCity5 nvarchar(500),
    FatherInstituteAffilation5 nvarchar(500),
    FatherAdmissionClass5 nvarchar(500),
    FatherMediumStudy5 nvarchar(500),
	
	MotherAcademicYear1 nvarchar(500),
	MotherInstituteName1 nvarchar(500),
	MotherInstituteCity1 nvarchar(500),
	MotherInstituteAffilation1 nvarchar(500),
	MotherMediumStudy1 nvarchar(500),
	MotherAdmissionClass1 nvarchar(500),
	
	MotherAcademicYear2 nvarchar(500),
	MotherInstituteName2 nvarchar(500),
	MotherInstituteCity2 nvarchar(500),
	MotherInstituteAffilation2 nvarchar(500),
	MotherMediumStudy2 nvarchar(500),
	MotherAdmissionClass2 nvarchar(500),
	
	MotherAcademicYear3 nvarchar(500),
	MotherInstituteName3 nvarchar(500),
	MotherInstituteCity3 nvarchar(500),
	MotherInstituteAffilation3 nvarchar(500),
	MotherMediumStudy3 nvarchar(500),
	MotherAdmissionClass3 nvarchar(500),
	
	
	MotherAcademicYear4 nvarchar(500),
	MotherInstituteName4 nvarchar(500),
	MotherInstituteCity4 nvarchar(500),
	MotherInstituteAffilation4 nvarchar(500),
	MotherMediumStudy4 nvarchar(500),
	MotherAdmissionClass4 nvarchar(500),
	
	MotherAcademicYear5 nvarchar(500), 
	MotherInstituteName5 nvarchar(500), 
	MotherInstituteCity5 nvarchar(500), 
	MotherInstituteAffilation5 nvarchar(500), 
	MotherMediumStudy5 nvarchar(500), 
	MotherAdmissionClass5 nvarchar(500) ,
	
	GuardianAcademicYear1 nvarchar(500),
	GuardianInstituteName1 nvarchar(500),
	GuardianInstituteCity1 nvarchar(500),
	GuardianInstituteAffilation1 nvarchar(500),
	GuardianAdmissionClass1 nvarchar(500),
	GuardianMediumStudy1 nvarchar(500),
	
	
	GuardianAcademicYear2 nvarchar(500),
	GuardianInstituteName2 nvarchar(500),
	GuardianInstituteCity2 nvarchar(500),
	GuardianInstituteAffilation2 nvarchar(500),
	GuardianAdmissionClass2 nvarchar(500),
	GuardianMediumStudy2 nvarchar(500),
	
	
	GuardianAcademicYear3 nvarchar(500),
	GuardianInstituteName3 nvarchar(500),
	GuardianInstituteCity3 nvarchar(500),
	GuardianInstituteAffilation3 nvarchar(500),
	GuardianAdmissionClass3 nvarchar(500),
	GuardianMediumStudy3 nvarchar(500),
	
	
	GuardianAcademicYear4 nvarchar(500),
	GuardianInstituteName4 nvarchar(500),
	GuardianInstituteCity4 nvarchar(500),
	GuardianInstituteAffilation4 nvarchar(500),
	GuardianAdmissionClass4 nvarchar(500),
	GuardianMediumStudy4 nvarchar(500),
	
	GuardianAcademicYear5 nvarchar(500),
	GuardianInstituteName5 nvarchar(500),
	GuardianInstituteCity5 nvarchar(500),
	GuardianInstituteAffilation5 nvarchar(500),
	 GuardianAdmissionClass5 nvarchar(500),
	 GuardianMediumStudy5 nvarchar(500)
	
)	
Insert into #tempFatherAcademic
(
	AdmissionFormId, 
	FatherAcademicYear1,FatherInstituteName1,FatherInstituteCity1,FatherInstituteAffilation1,FatherMediumStudy1,FatherAdmissionClass1,
	FatherAcademicYear2,FatherInstituteName2,FatherInstituteCity2,FatherInstituteAffilation2,FatherMediumStudy2,FatherAdmissionClass2,
	FatherAcademicYear3,FatherInstituteName3,FatherInstituteCity3,FatherInstituteAffilation3,FatherMediumStudy3,FatherAdmissionClass3,
	FatherAcademicYear4,FatherInstituteName4,FatherInstituteCity4,FatherInstituteAffilation4,FatherMediumStudy4,FatherAdmissionClass4,
	FatherAcademicYear5,FatherInstituteName5,FatherInstituteCity5,FatherInstituteAffilation5,FatherMediumStudy5,FatherAdmissionClass5,
	
	 
	MotherAcademicYear1,MotherInstituteName1,MotherInstituteCity1,MotherInstituteAffilation1,MotherMediumStudy1,MotherAdmissionClass1,
	MotherAcademicYear2,MotherInstituteName2,MotherInstituteCity2,MotherInstituteAffilation2,MotherMediumStudy2,MotherAdmissionClass2,
	MotherAcademicYear3,MotherInstituteName3,MotherInstituteCity3,MotherInstituteAffilation3,MotherMediumStudy3,MotherAdmissionClass3,
	MotherAcademicYear4,MotherInstituteName4,MotherInstituteCity4,MotherInstituteAffilation4,MotherMediumStudy4,MotherAdmissionClass4,
	MotherAcademicYear5,MotherInstituteName5,MotherInstituteCity5,MotherInstituteAffilation5,MotherMediumStudy5,MotherAdmissionClass5,
	    
	GuardianAcademicYear1,GuardianInstituteName1, GuardianInstituteCity1,GuardianInstituteAffilation1,GuardianMediumStudy1,GuardianAdmissionClass1,
	GuardianAcademicYear2,GuardianInstituteName2,GuardianInstituteCity2,GuardianInstituteAffilation2,GuardianMediumStudy2,GuardianAdmissionClass2,
	GuardianAcademicYear3,GuardianInstituteName3,GuardianInstituteCity3,GuardianInstituteAffilation3,GuardianMediumStudy3,GuardianAdmissionClass3,
	GuardianAcademicYear4,GuardianInstituteName4,GuardianInstituteCity4,GuardianInstituteAffilation4,GuardianMediumStudy4,GuardianAdmissionClass4,
	GuardianAcademicYear5,GuardianInstituteName5,GuardianInstituteCity5,GuardianInstituteAffilation5,GuardianMediumStudy5,GuardianAdmissionClass5
	
	 
)
SELECT AdmissionFormId,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') FatherAcademicYear1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') FatherInstituteName1, 
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') FatherInstituteCity1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') FatherInstituteAffilation1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') FatherMediumStudy1,
     ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') FatherAdmissionClass1,
     
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') FatherAcademicYear2,
    ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') FatherInstituteName2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') FatherInstituteCity2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') FatherInstituteAffilation2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') FatherMediumStudy2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') FatherAdmissionClass2,


  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') FatherAcademicYear3,
 ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') FatherInstituteName3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') FatherInstituteCity3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') FatherInstituteAffilation3,
    ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') FatherMediumStudy3,
    ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') FatherAdmissionClass3,

  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') FatherAcademicYear4,
      ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') FatherInstituteName4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') FatherInstituteCity4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') FatherInstituteAffilation4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') FatherMediumStudy4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') FatherAdmissionClass4,

  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') FatherAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') FatherInstituteName5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') FatherInstituteCity5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') FatherInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') FatherMediumStudy5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') FatherAdmissionClass5,
   
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') MotherAcademicYear1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') MotherInstituteName1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') MotherInstituteCity1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') MotherInstituteAffilation1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') MotherMediumStudy1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') MotherAdmissionClass1,

  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') MotherAcademicYear2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') MotherInstituteName2,
    ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') MotherInstituteCity2,
     ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') MotherInstituteAffilation2,
       ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') MotherMediumStudy2,
       ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') MotherAdmissionClass2,
    
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') MotherAcademicYear3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') MotherInstituteName3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') MotherInstituteCity3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') MotherInstituteAffilation3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') MotherMediumStudy3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') MotherAdmissionClass3,
  
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') MotherAcademicYear4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') MotherInstituteName4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') MotherInstituteCity4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') MotherInstituteAffilation4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') MotherMediumStudy4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') MotherAdmissionClass4,
  
  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') MotherAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') MotherInstituteName5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') MotherInstituteCity5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') MotherInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') MotherMediumStudy5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') MotherAdmissionClass5,
   
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') GuardianAcademicYear1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') GuardianInstituteName1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') GuardianInstituteCity1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') GuardianMediumStudy1, 
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') GuardianAdmissionClass1,
    
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') GuardianAcademicYear2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') GuardianInstituteName2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') GuardianInstituteCity2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') GuardianMediumStudy2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') GuardianAdmissionClass2,
  
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') GuardianAcademicYear3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') GuardianInstituteName3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') GuardianInstituteCity3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') GuardianMediumStudy3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') GuardianAdmissionClass3,
   
   
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') GuardianAcademicYear4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') GuardianInstituteName4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') GuardianInstituteCity4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') GuardianMediumStudy4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') GuardianAdmissionClass4,
  
  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') GuardianAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') GuardianInstituteName5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') GuardianInstituteCity5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') GuardianMediumStudy5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') GuardianAdmissionClass5  
   
from
(
  select AP.AdmissionFormId, RelationshipId, AcademicYear, AdmissionClass, InstituteName, InstituteCity,InstituteAffiliaton,Language
      , row_number() over(partition by AP.AdmissionFormId, RelationshipId
                          order by RelationshipId) rn
  from sAdmission.tAdmissionFormParentAcademic AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 


 

create table #tempReference
(
	AdmissionFormId bigint ,
	ReferenceDetail1 nvarchar(500),
	ReferenceName1 nvarchar(500),
	ReferenceRelation1 nvarchar(500),
	ReferenceContactNo1 nvarchar(500),
	ReferenceDetail2 nvarchar(500),
	ReferenceName2 nvarchar(500),
	ReferenceRelation2 nvarchar(500),
	ReferenceContactNo2 nvarchar(500)
)
INsert Into  #tempReference
 (
	AdmissionFormId,
	ReferenceDetail1,
	ReferenceName1,
	ReferenceRelation1,
	ReferenceContactNo1,
	ReferenceDetail2,
	ReferenceName2,
	ReferenceRelation2,
	ReferenceContactNo2
 )
SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  ReferenceDetail  end),'') ReferenceDetail1,
  ISNULL(max(case when   rn = 1  then  ReferenceName  end),'') ReferenceName1,
  ISNULL(max(case when    rn = 1  then  ReferenceRelation  end),'') ReferenceRelation1,
  ISNULL(max(case when    rn = 1  then  ReferenceContactNo  end),'') ReferenceContactNo1,
  
  ISNULL(max(case when  rn = 2  then  ReferenceDetail  end),'') ReferenceDetail2,
  ISNULL(max(case when   rn = 2  then  ReferenceName  end),'') ReferenceName2,
  ISNULL(max(case when   rn = 2  then  ReferenceRelation  end),'') ReferenceRelation2,
  ISNULL(max(case when  rn = 2 then  ReferenceContactNo  end),'') ReferenceContactNo2
   
from
(
  select AP.AdmissionFormId,ReferenceDetail, ReferenceName, ReferenceRelation, ReferenceContactNo 
      , row_number() over(partition by AP.AdmissionFormId 
                           order by AP.AdmissionFormId ) rn
  from sAdmission.tAdmissionFormReference AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 

Create table #TempSibling
(
	AdmissionFormId bigint,
	Code1 nvarchar(500),
	SiblingName1 nvarchar(500),
	SiblingRelation1 nvarchar(500),
	SiblingStandard1 nvarchar(500),
	SiblingSchool1 nvarchar(500),
	Code2 nvarchar(500),
	SiblingName2 nvarchar(500),
	SiblingRelation2 nvarchar(500),
	SiblingStandard2 nvarchar(500),
	SiblingSchool2 nvarchar(500),
	Code3 nvarchar(500),
	SiblingName3 nvarchar(500),
	SiblingRelation3 nvarchar(500),
	SiblingStandard3 nvarchar(500),
	SiblingSchool3 nvarchar(500),
	Code4 nvarchar(500),
	SiblingName4 nvarchar(500),
	SiblingRelation4 nvarchar(500),
	SiblingStandard4 nvarchar(500),
	SiblingSchool4 nvarchar(500)
)
Insert Into #TempSibling
(AdmissionFormId,
Code1,	
SiblingName1,
	SiblingRelation1,
	SiblingStandard1,
	SiblingSchool1,
	Code2,	
	SiblingName2,
	SiblingRelation2,
	SiblingStandard2,
	SiblingSchool2,
	Code3,	
	SiblingName3,
	SiblingRelation3,
	SiblingStandard3,
	SiblingSchool3,
	Code4,	
	SiblingName4,
	SiblingRelation4,
	SiblingStandard4,
	SiblingSchool4
)
SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  Code  end),'') Code1,
  ISNULL(max(case when    rn = 1  then  SiblingName  end),'') SiblingName1,
  ISNULL(max(case when    rn = 1  then  SiblingRelation  end),'') SiblingRelation1,
   ISNULL(max(case when    rn = 1  then  SiblingStandard  end),'') SiblingStandard1,
    ISNULL(max(case when    rn = 1  then  SiblingSchool  end),'') SiblingSchool1,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code2,
  ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName2,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation2,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard2,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool2,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code3,
   ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName3,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation3,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard3,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool3,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code4,
   ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName4,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation4,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard4,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool4
   
from
(
  select AP.AdmissionFormId,    SiblingName, SiblingRelation, SiblingStandard,SiblingSchool,Code  
      , row_number() over(partition by AP.AdmissionFormId 
                          order by AP.AdmissionFormId) rn
  from sAdmission.tAdmissionFormSibling AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 

 
DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

-- CTE for Admission Form Field
;WITH AdmissionCriteriaFormCTE AS (SELECT  DISTINCT FieldRemark FROM sAdmission.tAdmissionCriteriaForm ACF
INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
WHERE ACF.BatchId = @rBatchId
GROUP BY Id,FieldRemark,ClassId,BatchId
)

SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(FieldRemark) FROM AdmissionCriteriaFormCTE
GROUP BY FieldRemark
ORDER BY FieldRemark FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

IF object_id('tempdb..##tempAdmissionCriteriaForm') IS NOT NULL 
BEGIN
   DROP TABLE ##tempAdmissionCriteriaForm 
END

IF(@cols IS NOT NULL)
BEGIN 
	SET @query = N'SELECT DISTINCT AdmissionFormId,' + @cols + N' INTO ##tempAdmissionCriteriaForm FROM 
				 (
					SELECT DISTINCT  AFF.AdmissionFormId,AdmissionFormFieldResponse, FieldRemark
					FROM 
					sAdmission.tAdmissionCriteriaForm ACF
					INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
					WHERE ACF.BatchId = '+CONVERT(nvarchar(10),@rBatchId)+'
				) x
				PIVOT
				(
					MAX(AdmissionFormFieldResponse)
					FOR FieldRemark IN (' + @cols + N')
				) p '
			
	exec sp_executesql @query
	
	SELECT * from #tempAdmissionForm tempAF
	LEFT JOIN #tempStudentAcademic tempSA ON tempSA.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN #tempFatherAcademic tempFA ON tempFA.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #tempReference tempRF on tempRF.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #TempSibling tempSB ON tempSB.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN ##tempAdmissionCriteriaForm tempACF ON tempACF.AdmissionFormId = tempAF.AdmissionFormId
	Order by tempAF.Formno

END
ELSE 
BEGIN 
	SELECT * from #tempAdmissionForm tempAF
	LEFT JOIN #tempStudentAcademic tempSA ON tempSA.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN #tempFatherAcademic tempFA ON tempFA.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #tempReference tempRF on tempRF.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #TempSibling tempSB ON tempSB.AdmissionFormId = tempAF.AdmissionFormId
	Order by tempAF.Formno
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE  [sAdmission].[pGetDropDownLists]
	-- Add the parameters for the stored procedure here
	@rOrgId int =0,
	@rOrgGroupId int = 0,
	@rUserId bigint,
	@rBatchId int = 0,
	@rClassId int = 0,
	@rType int = 0
AS

	DECLARE @lGenderType nvarchar(20) = ''
	SELECT @lGenderType =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 557 AND SourceTypeId = 1016 AND SourceId = @rOrgId

if(@rType = 1)
BEGIN
	declare  @lStatusRes nvarchar(max)='', @lOrganizationRes nvarchar(max)='',@lStatusdropdown nvarchar(max)=''
	declare @lGenderdropdown nvarchar(max)='',@lReligiondropdown nvarchar(max)='',@lcastdropdown nvarchar(max)=''
	declare @lblooddropdown nvarchar(max)='', @lClassRes nvarchar(max)='', @lDivisionRes nvarchar(max)=''
	declare @lSavedReport nvarchar(max)='', @lclassdropdown2 nvarchar(max)='', @lAvailableRes nvarchar(max)=''
	declare @lReportList nvarchar(max)=''
	 
    -- Insert statements for procedure here

	
	select @lStatusRes = @lStatusRes + '<option value="207">Open</option>'
	select @lStatusRes = @lStatusRes + '<option value="208">Closed</option>'



	select @lOrganizationRes = @lOrganizationRes + '<option value="0"> -- ALL -- </option>'
	select @lOrganizationRes = @lOrganizationRes + '<option ' + case when Id = @rOrgId then 'selected="selected"' else '' end + ' value="' + convert(varchar,Id) + '">' + DisplayTitle + '</option>'
	from sSetup.vUserOrganization where IsObsolete = 0 AND OrgGroupId = isnull(@rOrgGroupId,0) and UserId = @rUserId
	order by OrderIndex


	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	
	
	select @lclassdropdown2 = @lclassdropdown2 + '<option value="' + convert( NVARCHAR,DivisionId) + '">' + convert( NVARCHAR,ClassName) + '</option>'
	from sSetup.vBatchClassDivision where IsObsolete = 0 and BatchId = 0 order by OrderIndex

	select @lStatusdropdown = @lStatusdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
	from sStudent.tStatusMaster where IsObsolete = 0

	select @lGenderdropdown = @lGenderdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
	from sCommon.tGenderMaster where IsObsolete = 0
													AND Id = CASE						-- Add Id condition MantisId : 0034447
													WHEN @lGenderType = 'Male' THEN 1
													WHEN @lGenderType = 'Female' THEN 2
													ELSE Id
													END

	select @lReligiondropdown = @lReligiondropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
	from sCommon.tReligionMaster where IsObsolete = 0 AND OrgGroupId = isnull(@rOrgGroupId,0)

	select @lcastdropdown = @lcastdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
	from sCommon.tCastCategoryMaster where IsObsolete = 0 AND OrgGroupId = isnull(@rOrgGroupId,0)
	order by OrderIndex

	select @lblooddropdown = @lblooddropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
	from sCommon.tBloodGroupMaster where IsObsolete = 0

	select @lSavedReport = @lSavedReport + '<option value="0"> -- Select -- </option>'
					select @lSavedReport =  @lSavedReport + '<option value="' + convert(varchar,ACS.Id)+ '">' + ACS.Title + '</option>'
					from sAdmission.tAdmissionCustomSearch ACS
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ACS.OrgId AND OM.OrgGroupId = @rOrgGroupId
					LEFT JOIN sSecurity.tUser U ON U.Id=ACS.CreatedUserId 
					WHERE (ACS.CreatedUserId = @rUserId) OR (ACS.IsCommonUsers = 1) OR (ACS.IsCommonForOrg = 1)
	
			 --SELECT 
			 --ISNULL(DM.Id,0) AS DisplayFieldId
			--,ISNULL(DM.Name,'') AS Name
			 -- ,ISNULL(DM.FieldSource,'') AS FieldSource 
			--,(CASE WHEN DO.DisplayFieldId Is Null THEN 'False'  ELSE 'True' END) AS Selected 
			--,(CASE WHEN DO.IsFieldMandatory Is Null THEN 'False' WHEN DO.IsFieldMandatory = 1 THEN 'True' ELSE 'False' END) AS IsMandatory 
      
			--FROM sConfig.tDisplayFieldMaster DM
			-- LEFT JOIN sConfig.tDisplayFieldOrg DO ON DM.Id=DO.DisplayFieldId
				--AND DO.OrgId=@rOrgId
			--WHERE (DM.FieldSource=@rFieldSource) 
			SET @lAvailableRes = @lAvailableRes + '<option value="1">Organization</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="2">Batch</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="3">FormNo</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="4">StudentName</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="5">Class</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="6">Gender</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="7">BirthDate</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="8">Status</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="9">City</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="10">ContactNo</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="11">ContactEmail</option>'
		   select @lAvailableRes = @lAvailableRes + '<option value="' + Convert(varchar(max), ISNULL(DM.Id,0)) + '">' + Convert(varchar(max),ISNULL(DM.Name,'')) + '</option>'
				FROM sConfig.tDisplayFieldMaster DM				
				WHERE (DM.FieldSource='Admission Form' AND DM.Id NOT IN(312,316,1233,1234))  --1233,1234 add for mantis : 0043425
				
				--DECLARE @lAvailableAdmissionColumns nvarchar(max)=''
				--DECLARE @lAvailableAdmissionCustomRes nvarchar(max)=''
				--Declare @Title as nvarchar(max)
				--select @lAvailableAdmissionCustomRes = @lAvailableAdmissionCustomRes + '<option value="' + Convert(varchar(max), ISNULL(AC.Id,0)) + '">' + Convert(varchar(max),ISNULL(AC.FieldRemark,'')) + '</option>'
				--FROM sAdmission.tAdmissionCriteriaForm AC 
				--WHERE ((AC.ClassId= @rClassId) OR (AC.ClassId=0)) AND ((AC.BatchId= @rBatchId) OR (AC.BatchId=0))			
				

				--SET @lAvailableAdmissionColumns=   STUFF((SELECT ',' + QUOTENAME(AC.FieldRemark,'[]'), '' AS FieldRemark, '' AS SalaryMonth
						--from sAdmission.tAdmissionCriteriaForm AC WHERE ((AC.ClassId= @rClassId) OR (AC.ClassId=0)) AND ((AC.BatchId= @rBatchId) OR (AC.BatchId=0))
				--FOR XML PATH(''), TYPE
				--).value('.', 'NVARCHAR(MAX)') 
			--,1,1,'')
	        
		--DECLARE @lAdmissionCustomFields TABLE
		--(
		  --Title nvarchar(max)
		--)
		 --INSERT INTO  @lAdmissionCustomFields      
		--select Item AS Title from sCommon.fnSplit(@lAvailableAdmissionColumns , ',')
	        
		--select @lAvailableAdmissionCustomRes = @lAvailableAdmissionCustomRes +'<option class=StudentCustom value="|' + Title + '||">|' + Title + '||</option>'
		--from @lAdmissionCustomFields
		
		--print @lAvailableAdmissionCustomRes



			select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + ACS.Title + '</td>
	<td style="width:670px; word-wrap:break-word;">' + ACS.ColumnName + '</td>
	<td style="width:80px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),ACS.Id) + ');">View</a></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;text-align: center;"><a onclick="DeleteReport(' + convert(varchar,ACS.Id) + ');"><img src="../../Images/Del.png"></a></td></tr>'
	from sAdmission.tAdmissionCustomSearch ACS
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ACS.OrgId
	LEFT JOIN sSecurity.tUser U ON U.Id = ACS.CreatedUserId   
	WHERE ACS.CreatedUserId = @rUserId OR (ACS.IsCommonUsers = 1) OR (ACS.IsCommonForOrg = 1)


	select  @lClassRes as ClassRes, @lStatusRes as StatusRes,@lGenderdropdown As Gendercheckboxlist,@lReligiondropdown As Religionchklist,@lcastdropdown as castcategorychklist,
	@lblooddropdown AS bloodgrpchklist,@lOrganizationRes as OrganizationRes,@lSavedReport AS SavedReportList, @lclassdropdown2 AS classdivRes, @lAvailableRes AS AvailableRes,
	@lReportList as ReportList
END	


If(@rType = 2)
BEGIN			
declare @lBatchId int =0, @lBatchRes1 nvarchar(max)='', @lBatchdropdown nvarchar(max)='',  @lclassdropdown nvarchar(max)=''
declare  @lclassdivRes nvarchar(max)=''
		select @lBatchRes1 = @lBatchRes1 + '<option value="0"> -- ALL -- </option>'
		select @lBatchRes1 = @lBatchRes1 + '<option value="' + convert( NVARCHAR, Id) + '">' + Title + '</option>'
		from sSetup.tBatchMaster   WHERE OrgId = @rOrgId

		select @lclassdivRes = @lclassdivRes + '<option value="0"> -- ALL -- </option>'

		 
		select @lclassdropdown = @lclassdropdown + '<option value="' + convert( NVARCHAR,DivisionId) + '">' + convert( NVARCHAR,ClassName) + '</option>'
		from sSetup.vBatchClassDivision where IsObsolete = 0 and BatchId = @lBatchId order by OrderIndex

		select @lBatchRes1 as BatchRes, @lclassdivRes as classdivRes,  @lclassdropdown as ClassCheckBoxList
END

If(@rType = 3)
BEGIN
declare @lBatchId1 int =0 
select @rBatchId = Id from sSetup.tBatchMaster WHERE OrgId = @rOrgId   
declare	 @lBatchRes2 nvarchar(max)='', @lClassRes1 nvarchar(max)='', @lclassdropdown1 nvarchar(max)=''
	select @lClassRes1 = @lClassRes1 + '<option value="0"> -- ALL -- </option>'
	select @lClassRes1 = @lClassRes1	 + '<option value="' + convert(varchar,ClassId) + '">' + ClassName + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 and BatchId = @rBatchId  order by OrderIndex

	select @lclassdropdown1 = @lclassdropdown1 + '<option value="' + convert( NVARCHAR,ClassId) + '">' + convert( NVARCHAR,ClassName) + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex
	
	select @lClassRes1 as ClassRes, @lclassdropdown1 as ClassCheckBoxList
END

If(@rType = 4)
BEGIN
declare @lAvailableRes1 nvarchar(max)='', @lAvailableAdmissionCustomRes1 nvarchar(max)=''

	SET @lAvailableRes1 = @lAvailableRes1 + '<option value="1">Organization</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="2">Batch</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="3">FormNo</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="4">StudentName</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="5">Class</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="6">Gender</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="7">BirthDate</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="8">Status</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="9">City</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="10">ContactNo</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="11">ContactEmail</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="12">AdmissionFormDate</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="13">AdmissionHandledBy</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="14">AdmissionFormConvertedDate</option>'
			select @lAvailableRes1 = @lAvailableRes1 + '<option value="' + Convert(varchar(max), ISNULL(DM.Id,0)) + '">' + Convert(varchar(max),ISNULL(DM.Name,'')) + '</option>'
				FROM sConfig.tDisplayFieldMaster DM  		
				WHERE (DM.FieldSource='Admission Form' AND DM.Id NOT IN(312,316,1233,1234)) --1233,1234 add for mantis : 0043425

				--select Distinct AC.FieldRemark
				--FROM sAdmission.tAdmissionCriteriaForm AC
				--WHERE ((AC.BatchId= @rBatchId) OR (AC.BatchId=0)) --((AC.ClassId= @rClassId) OR (AC.ClassId=0)) AND 	
			
			DECLARE @lAvailableAdmissionColumns nvarchar(max)=''
			DECLARE @lAvailableAdmissionCustomRes nvarchar(max)=''
			--DECLARE @lAvailbleStudentColumns nvarchar(max)=''
			Declare @Title as nvarchar(max)


			SET @lAvailableAdmissionColumns=   STUFF((SELECT Distinct',' + QUOTENAME(AC.FieldRemark,'[]'), '' AS FieldTitle, '' AS SalaryMonth
						from sAdmission.tAdmissionCriteriaForm AC Where BatchId = @rBatchId
				FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
	        print @lAvailableAdmissionColumns
		DECLARE @lStudentCustomFields TABLE
		(
		  Title nvarchar(max)
		)
		 INSERT INTO  @lStudentCustomFields      
		select Item AS Title from sCommon.fnSplit(@lAvailableAdmissionColumns , ',')
    
		select  @lAvailableAdmissionCustomRes = @lAvailableAdmissionCustomRes +'<option class=AdmissionCustom value="|' + Title + '||">|' + Title + '||</option>'
		from @lStudentCustomFields

		

		Select @lAvailableRes1 AS AvailableResCust1,@lAvailableAdmissionCustomRes1 as AvailableAdmissionCustomRes1,@lAvailableAdmissionCustomRes as AvailableAdmissionCustomResCust
END
If(@rType = 5)
BEGIN
declare @lAvailableResCust1 nvarchar(max)='', @lAvailableAdmissionCustomResCust1 nvarchar(max)=''

	SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="1">Organization</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="2">Batch</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="3">FormNo</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="4">StudentName</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="5">Class</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="6">Gender</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="7">BirthDate</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="8">Status</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="9">City</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="10">ContactNo</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="11">ContactEmail</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="12">AdmissionFormDate</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="13">AdmissionHandledBy</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="14">AdmissionFormConvertedDate</option>'
			select @lAvailableResCust1 = @lAvailableResCust1 + '<option value="' + Convert(varchar(max), ISNULL(DM.Id,0)) + '">' + Convert(varchar(max),ISNULL(DM.Name,'')) + '</option>'
				FROM sConfig.tDisplayFieldMaster DM				
				WHERE (DM.FieldSource='Admission Form' AND DM.Id NOT IN(312,316,1233,1234)) --1233,1234 add for mantis : 0043425

				--select Distinct AC.FieldRemark
				--FROM sAdmission.tAdmissionCriteriaForm AC
				--WHERE ((AC.BatchId= @rBatchId) OR (AC.BatchId=0)) --((AC.ClassId= @rClassId) OR (AC.ClassId=0)) AND 	
			
			DECLARE @lAvailableAdmissionColumnsCust nvarchar(max)=''
			DECLARE @lAvailableAdmissionCustomResCust nvarchar(max)=''
			--DECLARE @lAvailbleStudentColumns nvarchar(max)=''
			Declare @TitleCust as nvarchar(max)


			SET @lAvailableAdmissionColumnsCust= STUFF((SELECT Distinct ',' + QUOTENAME(AC.FieldRemark,'[]'), '' AS FieldTitleCust, '' AS SalaryMonthCust
						from sAdmission.tAdmissionCriteriaForm AC Where  ClassId = @rClassId
				FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
			print(@rClassId)
	        print @lAvailableAdmissionColumnsCust
			print(1)
		DECLARE @lStudentCustomFieldsCust TABLE
		(
		  Title nvarchar(max)
		)
		 INSERT INTO  @lStudentCustomFieldsCust      
		select Item AS Title from sCommon.fnSplit(@lAvailableAdmissionColumnsCust , ',')
    
		select  @lAvailableAdmissionCustomResCust = @lAvailableAdmissionCustomResCust +'<option class=AdmissionCustom value="|' + Title + '||">|' + Title + '||</option>'
		from @lStudentCustomFieldsCust

		

		Select @lAvailableResCust1 AS AvailableResCust1,@lAvailableAdmissionCustomResCust as AvailableAdmissionCustomResCust
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pImportAdmissionForm]
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int,
	@rOrgGroupId int


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,
		@lFormNo int,@lStudentName nvarchar(100),@lFatherName nvarchar(100),@lSurName nvarchar(100),@lForClassId int,@lForClass nvarchar(100),
		@lDateOfBirth date,@lDateOfBirthInWord nvarchar(100),@lStreetOne nvarchar(50),@lStreetTwo nvarchar(50),@lStreetThree nvarchar(50),
		@lCountry nvarchar(50),@lState nvarchar(50),@lCity nvarchar(50),@lZipCode nvarchar(20),@lContactNo nvarchar(20),@lContactEmail nvarchar(50),
		@lRemark nvarchar(200),@lPreviousSchool nvarchar(200),@lMeritMarks decimal(10,2),@lMeritGrade nvarchar(20),@lGenderId int,@lReligionId int,
        @lGender nvarchar(100),@lReligion nvarchar(100),@lFamilyCaste nvarchar(100),@lCastCategory nvarchar(20),
		@lHostelRequired nvarchar(20) ,@lTransportRequired nvarchar(20),@lHostelRequiredId int ,
		@lTransportRequiredId int,@lCastCategoryId int=0,@lBirthPlace nvarchar(150),
		@lPlaceOfBirth nvarchar(150),@lFatherFullName nvarchar(100), @lFatherOccupation  nvarchar(50),
	    @lFatherContactNo nvarchar(50), @lFatherDesignation nvarchar(100),@lMotherContactNo nvarchar(50), @lMotherDesignation nvarchar(100),@lMotherIncome int,
	    @lFatherIncome int, @lMotherFullName nvarchar(100)='', @lMotherOccupation  nvarchar(50),@lMotherQualification nvarchar(50)='',@lFatherQualification nvarchar(50)
		,@lPENNumber BIGINT,@lApaarIdNumber NVARCHAR(50) --add for mantis : 0043425
			
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,
		FormNo int,
		ForClass nvarchar(100),
		StudentName nvarchar(100), 
		FatherName nvarchar(100),
		SurName nvarchar(100),
		DateOfBirth date ,
		DateOfBirthInWord nvarchar(100),
	    StreetOne nvarchar(50), 
	    StreetTwo nvarchar(50), 
	    StreetThree nvarchar(50), 
	    State nvarchar(50), 
	    City nvarchar(50),
	    Country nvarchar(50), 
	    ZipCode nvarchar(20), 
	    ContactNo nvarchar(20), 
	    ContactEmail nvarchar(50), 
	    Remark nvarchar(200) , 
	    PreviousSchool nvarchar(200),
	    MeritMarks decimal(10,2),
	    MeritGrade nvarchar(20), 
	    Gender nvarchar(100), 
	    Religion nvarchar(100), 
	    FamilyCaste nvarchar(100), 
	    CastCategory nvarchar(100),
	    HostelRequired nvarchar(20), 
	    TransportRequired nvarchar(20),
	    PlaceOfBirth nvarchar(150),
	    FatherFullName nvarchar(100), 
	    FatherQualification nvarchar(50),
	    FatherOccupation  nvarchar(50),
	    FatherContactNo nvarchar(50),
	    FatherDesignation nvarchar(100),
	    FatherIncome int,
	    MotherFullName nvarchar(100), 
	    MotherQualification nvarchar(50),
	    MotherOccupation  nvarchar(50),
	    MotherContactNo nvarchar(50),
	    MotherDesignation nvarchar(100),
	    MotherIncome int
		,PENNumber BIGINT --add for mantis : 0043425
		,ApaarIdNumber NVARCHAR(50) --add for mantis : 0043425
	)
	INSERT INTO #tTable
	(   FormNo,ForClass,StudentName,FatherName,SurName,DateOfBirth,DateOfBirthInWord, StreetOne, StreetTwo, StreetThree, 
	    State,  City,Country,ZipCode,ContactNo, ContactEmail,Remark,PreviousSchool,MeritMarks,MeritGrade, Gender,	  Religion,FamilyCaste,CastCategory,HostelRequired,TransportRequired,PlaceOfBirth,FatherFullName,FatherQualification,
		FatherOccupation,FatherContactNo,FatherDesignation,FatherIncome,
	    MotherFullName,MotherQualification,MotherOccupation,MotherContactNo,MotherDesignation,MotherIncome
		,PENNumber
		,ApaarIdNumber
	)
	SELECT
		FormNo,ForClass,StudentName,FatherName,SurName,DateOfBirth, DateOfBirthInWord,StreetOne, StreetTwo, StreetThree, 
	    State,  City,Country,ZipCode,ContactNo, ContactEmail,Remark,PreviousSchool,MeritMarks,MeritGrade, Gender,	Religion,FamilyCaste,CastCategory,HostelRequired,TransportRequired,PlaceOfBirth,FatherFullName,FatherQualification,
		FatherOccupation,FatherContactNo,FatherDesignation,FatherIncome,
	    MotherFullName,MotherQualification,MotherOccupation,MotherContactNo,MotherDesignation,MotherIncome
		,PENNumber 
		,ApaarIdNumber
	FROM OPENXML (@intDoc, '/Table/ImportAdmissionForm', 1)
	WITH
	( 	
	    FormNo int  '@FormNo',
		ForClass nvarchar(100) '@ForClass',
		StudentName nvarchar(100) '@StudentName', 
		FatherName nvarchar(100) '@FatherName',
		SurName nvarchar(100) '@SurName',
		DateOfBirth date  '@DateOfBirth',
		DateOfBirthInWord nvarchar(100) '@DateOfBirthInWord',
	    StreetOne nvarchar(50) '@StreetOne', 
	    StreetTwo nvarchar(50) '@StreetTwo', 
	    StreetThree nvarchar(50) '@StreetThree', 
	    State nvarchar(50) '@State', 
	    City nvarchar(50) '@City',
	    Country nvarchar(50) '@Country', 
	    ZipCode nvarchar(20) '@ZipCode', 
	    ContactNo nvarchar(20) '@ContactNo', 
	    ContactEmail nvarchar(50) '@ContactEmail', 
	    Remark nvarchar(200) '@Remark' , 
	    PreviousSchool nvarchar(200) '@PreviousSchool',
	    MeritMarks decimal(10,2) '@MeritMarks',
	    MeritGrade nvarchar(20) '@MeritGrade', 
	    Gender nvarchar(100) '@Gender', 
	    Religion nvarchar(100) '@Religion', 
	    FamilyCaste nvarchar(100) '@FamilyCaste', 
	    CastCategory nvarchar(100) '@CastCategory',
	    HostelRequired nvarchar(20) '@HostelRequired', 
	    TransportRequired nvarchar(20) '@TransportRequired',
	    PlaceOfBirth nvarchar(150) '@PlaceOfBirth',
	    FatherFullName nvarchar(100) '@FatherFullName', 
	    FatherQualification nvarchar(50) '@FatherQualification',
	    FatherOccupation  nvarchar(50) '@FatherOccupation',
	    FatherContactNo nvarchar(50) '@FatherContactNo',
	    FatherDesignation nvarchar(100) '@FatherDesignation',
	    FatherIncome int '@FatherIncome',
	    MotherFullName nvarchar(100) '@MotherName', 
	    MotherQualification nvarchar(50) '@MotherQualification',
	    MotherOccupation  nvarchar(50) '@MotherOccupation',
	    MotherContactNo nvarchar(50) '@MotherContactNo',
	    MotherDesignation nvarchar(100) '@MotherDesignation',
	    MotherIncome int '@MotherIncome'
		,PENNumber BIGINT '@PENNumber'--Mantis - 0043425
		,ApaarIdNumber NVARCHAR(50) '@ApaarIdNumber'--Added by 0043425
	    )

SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 
BEGIN	
	SET @lFormNo=0
	SET @lForClass=''
	SET @lStudentName=''
	SET @lFatherName=''
	SET @lSurName=''
	SET @lDateOfBirth =''
	SET @lStreetOne=''
	SET @lStreetTwo=''
	SET @lStreetThree=''
	SET @lState=''
	SET @lCity=''
	SET @lCountry=''
	SET @lZipCode=''
	SET @lContactNo=''
	SET @lContactEmail=''
	SET @lRemark=''
	SET @lPreviousSchool=''
	SET @lMeritMarks=0
	SET @lMeritGrade=''
	SET @lGender =''
	SET @lReligion=''
	SET @lFamilyCaste=''
	SET @lCastCategory=''
	SET @lHostelRequired=''
	SET @lTransportRequired=''
	SET @lForClassId=0
	SET @lGenderId=0
	SET @lReligionId=0
	SET @lBirthPlace=''
	SET @lForClassId=0
	SET @lDateOfBirthInWord =''
    SET  @lHostelRequiredId=0
    SET @lTransportRequiredId=0
    SET @lCastCategoryId=0
    SET @lPlaceOfBirth =''
    SET @lFatherFullName =''
    SET @lFatherOccupation  =''
	SET @lFatherContactNo =''
	SET @lFatherDesignation =''
	SET @lMotherContactNo =''
	SET @lMotherDesignation =''
	SET @lMotherIncome=0
	SET @lFatherIncome=0
	SET @lMotherFullName=''
	SET @lMotherOccupation =''
	SET @lMotherQualification=''
	SET @lFatherQualification=''
	SET @lPENNumber = NULL --Mantis - 0043425
	SET @lApaarIdNumber = '' --mantis : 0043425

  SELECT		
		@lFormNo=FormNo,
		@lForClass=ForClass,
		@lStudentName=StudentName,
		@lFatherName=FatherName,
		@lSurName=SurName,
		@lDateOfBirth =DateOfBirth ,
		@lDateOfBirthInWord=DateOfBirthInWord,
		@lStreetOne=StreetOne,
		@lStreetTwo=StreetTwo,
		@lStreetThree= StreetThree,
		@lState= State,
		@lCity=City,
		@lCountry=Country,
		@lZipCode=ZipCode,
		@lContactNo=ContactNo,
		@lContactEmail=ContactEmail,
		@lRemark=Remark,
		@lPreviousSchool=PreviousSchool,
		@lMeritMarks=MeritMarks,
		@lMeritGrade=MeritGrade,
		@lGender = Gender ,
		@lReligion= Religion,
		@lFamilyCaste=FamilyCaste,
		@lCastCategory=CastCategory,
		@lHostelRequired=HostelRequired,
		@lTransportRequired=TransportRequired,
		@lBirthPlace =PlaceOfBirth,
		 @lFatherFullName =FatherFullName,
		 @lFatherOccupation  =FatherOccupation,
		 @lFatherContactNo =FatherContactNo,
		 @lFatherDesignation =FatherDesignation,
		 @lMotherContactNo =MotherContactNo,
		 @lMotherDesignation =MotherDesignation,
		 @lMotherIncome=MotherIncome,
		 @lFatherIncome=FatherIncome,
		 @lMotherFullName=MotherFullName,
		 @lMotherOccupation =MotherOccupation,
		 @lMotherQualification=MotherQualification,@lFatherQualification=FatherQualification
		 ,@lPENNumber = PENNumber --Mantis - 0043425
		 ,@lApaarIdNumber = ApaarIdNumber --mantis : 0043425

FROM #tTable WHERE Id = @lCount  

SELECT	@lGenderId = Id FROM sCommon.tGenderMaster WHERE Title = @lGender AND IsObsolete=0
SELECT	@lForClassId  = Id FROM sSetup.tClassMaster WHERE Title = @lForClass AND OrgId = @rOrgId AND IsObsolete=0
SELECT	@lReligionId = Id FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId=@rOrgGroupId AND IsObsolete=0
SELECT  @lCastCategoryId=Id  FROM sCommon.tCastCategoryMaster WHERE IsObsolete = 0 AND OrgGroupId=@rOrgGroupId AND Title = @lCastCategory
SET @lHostelRequiredId=0 SET @lTransportRequiredId=0
if(@lHostelRequired='Yes')
BEGIN
SET @lHostelRequiredId=1
END
if(@lTransportRequired='Yes')
BEGIN
SET @lTransportRequiredId=1
END
	--BEGIN TRANSACTION
		DECLare @lAdmissionFormId bigint=0,@OutAdmissionFormId bigint=0
--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionForm', 0, 1, 1,@outNextNumber = @lAdmissionFormId output

  BEGIN	
 -- INSERT INTO sAdmission.tAdmissionForm
	--	(Id, FormNo, FirstName, MiddleName, LastName, ForClassId, ForBatchId, ForBatch, DateOfBirth, DateOfBirthInWord, OrgId, BatchId, StatusId, 
	--	StreetOne, StreetTwo,StreetThree, Country, State, City, ZipCode, ContactNo, ContactEmail, Remark, PreviousSchool, MeritMarks, MeritGrade,GenderId, ReligionId,
	--	 FamilyCast, FamilySubCast, CastCategoryId, CreatedUserId, CreatedDateTime, FormPassword, DataEntryModeId, DataEntryStatusId, StudentPhoto, AdmissionCategoryId, Nationality, MotherTongue, 
	--	 OtherInformation, IsPysicalDeformity, PysicalDeformityRemark, IsMajorIllness, MajorIllnessRemark, IsAllergy, AllergyRemark, BirthPlace, BirthTaluka, BirthDistrict, BloodGroupId, AdhaarNumber, IsHostelRequired, IsTransportRequired, BirthState, BirthCountry
	--	)
	--VALUES
	--	( @lAdmissionFormId,@lFormNo,@lStudentName,@lFatherName,@lSurName,@lForClassId,0,null,@lDateOfBirth,@lDateOfBirthInWord,@rOrgId,@rBatchId,207
	--	     ,@lStreetOne,@lStreetTwo,@lStreetThree,@lCountry,@lState,@lCity,@lZipCode,@lContactNo,@lContactEmail,@lRemark,@lPreviousSchool,@lMeritMarks
	--		,@lMeritGrade,@lGenderId,@lReligionId,@lFamilyCaste,null,@lCastCategoryId,@rUserId,sCommon.fGetDate(),@lFormNo,572,562,null, 0, null, null,null,
	--	 	 0,  null, 0, null, 0, null,@lBirthPlace,null, null,0,null, @lHostelRequiredId, @lTransportRequiredId, null, null
	--	) 
	
    EXEC [sAdmission].[pAdmissionFormAdd] 0,@lFormNo,@lStudentName,@lFatherName,@lSurName,@lForClassId,0,@lDateOfBirth,@lDateOfBirthInWord,@rOrgId,@rBatchId,207,@lStreetOne,
    @lStreetTwo,@lStreetThree,@lCountry,@lState,@lCity,@lZipCode,@lContactNo,@lContactEmail,@lRemark,@lPreviousSchool,@lMeritMarks,@lMeritGrade,@lGenderId,
	@lReligionId,@lFamilyCaste,null,@lCastCategoryId,@rUserId,@lFormNo,562,572,null,null,null,null,0,null,0,null,0,null,@lBirthPlace,null,null,0,null,
	@lHostelRequiredId,@lTransportRequiredId,null,null,null,null,null,@OutAdmissionFormId  output
	,null,'',null,@lPENNumber,@lApaarIdNumber
   END
   BEGIN
   INSERT INTO  sAdmission.tAdmissionFormFamilyDetail(AdmissionFormId,FatherName, FatherOccupation,FatherQualification,MotherQualification,
		 FatherContactNo,FatherIncome,MotherName,MotherOccupation,MotherContactNo,MotherIncome,CreatedUserId, CreatedDateTime,MotherDesignation,FatherDesignation
		) VALUES(@OutAdmissionFormId,@lFatherFullName, @lFatherOccupation,@lFatherQualification,@lMotherQualification,
		 @lFatherContactNo,@lFatherIncome,@lMotherFullName,@lMotherOccupation,@lMotherContactNo,@lMotherIncome,@rUserId,sCommon.fGetDate(),@lMotherDesignation,@lFatherDesignation)
   END
		 SET @lCount = @lCount - 1
		 
	--COMMIT TRANSACTION	
END
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pInquiryDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 
	 @rOrgGroupId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
  IF(@rType='Organization')
  BEGIN
  SELECT
	(
		SELECT 
			COUNT(AI.Id) FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate)=CONVERT(DATE,GETDATE())
	) AS DailyCount,
	(
		SELECT 
			COUNT(AI.Id) FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate)=DATEADD(day, -1, convert(date, GETDATE()))
	) AS YesterdayCount,
	
	 
	(
		SELECT 
			COUNT(AI.Id) FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
	) AS WeeklyCount,
	(
		SELECT 
			COUNT(AI.Id) FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
	)  AS MonthlyCount
  END
  
  IF(@rType='Class')
  BEGIN
   IF(@rDay=-1)
	BEGIN
		SELECT 
			CM.Title AS ClassName, COUNT(AI.Id) AS YesterdayCount FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tClassMaster CM ON AI.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate)=DATEADD(day, -1, convert(date, GETDATE()))
			GROUP BY CM.Title
	END
	IF(@rDay=1)
	BEGIN
		SELECT 
			CM.Title AS ClassName, COUNT(AI.Id) AS DailyCount FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tClassMaster CM ON AI.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate)=CONVERT(DATE,GETDATE())
			GROUP BY CM.Title
	END
	IF(@rDay=7)
	BEGIN
		SELECT 
			CM.Title AS ClassName, COUNT(AI.Id) AS WeeklyCount FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tClassMaster CM ON AI.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
			GROUP BY CM.Title
	END
	IF(@rDay=30)
	BEGIN
		SELECT 
			CM.Title AS ClassName, COUNT(AI.Id) AS MonthlyCount FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tClassMaster CM ON AI.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			GROUP BY CM.Title
	END
  END
  
  IF(@rType='OrgGroup')
  BEGIN
  
  IF(@rDay=-1)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization, COUNT(AI.Id) AS YesterdayCount FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tClassMaster CM ON AI.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate)=DATEADD(day, -1, convert(date, GETDATE()))
			GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=1)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization, COUNT(AI.Id) AS DailyCount FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tClassMaster CM ON AI.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate)=CONVERT(DATE,GETDATE())
			GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=7)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization, COUNT(AI.Id) AS WeeklyCount FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tClassMaster CM ON AI.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) 
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
			GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=30)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization, COUNT(AI.Id) AS MonthlyCount FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tClassMaster CM ON AI.ForClassId = CM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)  
			AND (AI.OrgId = @rOrgId OR @rOrgId=0) 
			AND (AI.ForBatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,AI.InquiryDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			GROUP BY OM.Id,OM.DisplayTitle
	END
  END	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pInquiryStatusMaster]

	 @rOrgGroupId int,
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100)
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
SET @rTitle = sCommon.fSearchStringGet(@rTitle)
BEGIN 
	
	
	SELECT 
	
	ISM.OrgGroupId,
	ISM.Id AS InquiryStatusId,
	ISM.Code AS Code,
	ISM.Title AS Title,
	ISM.StatusId
	

  FROM 
            sAdmission.tInquiryStatusMaster ISM
  WHERE 
   (ISM.Id = @rId) OR (@rId=0)
   AND (ISM.OrgGroupId = @rOrgGroupId) 
   AND ((ISM.Title Like @rTitle )OR( ISNULL(@rTitle,'') = ''))
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pInquiryStatusMasterDelete]
	 @rId int,
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sAdmission.tInquiryStatusMaster where Id=@rId AND OrgGroupId=@rOrgGroupId
			
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pInquiryStatusMasterGET]

	 @rOrgGroupId int,
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rStatusId smallint
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
SET @rTitle = sCommon.fSearchStringGet(@rTitle)
BEGIN 
	
	
	SELECT 
	
	ISM.OrgGroupId,
	ISM.Id,
	ISM.Code AS Code,
	ISM.Title AS Title,
	ISM.StatusId,
	ISM.IsObsolete,
	ISM.StatusId,
	SM.Title AS StatusName,
	ISM.HighlightColor,
	ISNULL (IMSM.Id ,0)As InquiryMainStatusId,
	ISNULL(IMSM.Title,'') As InquiryMainStatus

  FROM 
            sAdmission.tInquiryStatusMaster ISM
            INNER JOIN sCommon.tStatusMaster SM ON ISM.StatusId = SM.Id
			LEFT JOIN  sAdmission.tInquiryMainStatusMaster IMSM ON IMSM.Id = ISM.InquiryMainStatusId
  WHERE 
   ((ISM.Id = @rId) OR (@rId=0))
   AND (ISM.OrgGroupId = @rOrgGroupId) 
   AND ((ISM.Title Like @rTitle )OR( ISNULL(@rTitle,'') = ''))
   AND ((ISM.StatusId = @rStatusId) OR (@rStatusId=0))
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pInquiryTypeMasterAdd]
		
	@rId  int,
	@rCode nvarchar(50),
	@rTitle nvarchar(50),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rCreatedDateTime date,
	@rUpdateduserId bigint=0,
	@rUpdatedDateTime date='',
	@rOrgGroupId int,
	@rStatusId smallint=0,
	@rHighlightColor nvarchar(20),
	@rInquiryMainStatusId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	IF(@rId = 0)	
	BEGIN
		
		If Exists(select Id from sAdmission.tInquiryStatusMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sAdmission.tInquiryStatusMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		IF(@rStatusId = 211)
		BEGIN
			If Exists(select Id from sAdmission.tInquiryStatusMaster where StatusId=211 AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -107 as Result
				RETURN
			END 
		END
	END
	ELSE
	BEGIN
		
		If  Exists(select Id from sAdmission.tInquiryStatusMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End
		If  Exists(select Id from sAdmission.tInquiryStatusMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId  AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		IF(@rStatusId = 211)
		BEGIN
			If Exists(select Id from sAdmission.tInquiryStatusMaster where StatusId=211 AND OrgGroupId=@rOrgGroupId)
				BEGIN
				select -107 as Result
				RETURN
			END 
		END
	END
	
	
	
	 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAdmission.tInquiryStatusMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAdmission.tInquiryStatusMaster
		(
		
		Id,
		Code,
		Title,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		OrgGroupId,
		StatusId,
		HighlightColor,
		InquiryMainStatusId	
		)
	VALUES
		(
		
		@lNextNumber,
		@rCode,
		@rTitle,
		@rIsObsolete,
		@rCreatedUserId,
		@rCreatedDateTime,
		@rCreatedUserId,
		@rCreatedDateTime,
		@rOrgGroupId,
		@rStatusId,
		@rHighlightColor,
		@rInquiryMainStatusId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tInquiryStatusMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			StatusId = @rStatusId,
			HighlightColor=@rHighlightColor,
			InquiryMainStatusId = @rInquiryMainStatusId
			
			
	      
	      
	      WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormFamilyGet]
	 
	 @rOrgId smallint=0,
	 @rBatchId int,
	 @rForClassId  int,
	 @rFormNo nvarchar(max)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 declare @query varchar(max)=''
	select @query ='SELECT 
		*
  FROM 
        sAdmission.tAdmissionFormFamilyDetail AD
        INNER JOIN   sAdmission.tAdmissionForm AF ON AF.Id=AD.AdmissionFormId
        WHERE  (AF.OrgId= ' + convert(varchar,@rOrgId) + ')
			  AND AF.BatchId= ' + convert(varchar,@rBatchId) + '
			  AND ((AF.ForClassId= ' + convert(varchar,@rForClassId) +') OR ( ' + convert(varchar,@rForClassId)+' =0))
			  AND AF.FormNo in (' + @rFormNo + ')'
  execute(@query)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormGet]
	 
	 @rOrgId smallint=0,
	 @rBatchId int,
	 @rForClassId  int,
	 @rFormNo nvarchar(200)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
declare @qur varchar(max)=''
select @qur = '
	SELECT 
		*
  FROM 
            sAdmission.tAdmissionForm
			 
  WHERE 
   (OrgId= ' + convert(varchar,@rOrgId) + ')
  AND BatchId= ' + convert(varchar,@rBatchId) + '
  AND ((ForClassId= ' + convert(varchar,@rForClassId) +') OR ( ' + convert(varchar,@rForClassId)+' =0))
  AND FormNo in (' + @rFormNo + ')'
  
  exec(@qur)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormParentAcademicGet]
	     @rOrgId smallint=0,
		 @rBatchId int,
		 @rForClassId  int,
		 @rFormNo nvarchar(max)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	  declare @query varchar(max)=''
	select @query ='SELECT 
		*
  FROM 
        sAdmission.tAdmissionFormParentAcademic PA
         INNER JOIN   sAdmission.tAdmissionForm AF ON AF.Id=PA.AdmissionFormId
        WHERE (AF.OrgId= ' + convert(varchar,@rOrgId) + ')
			  AND AF.BatchId= ' + convert(varchar,@rBatchId) + '
			  AND ((AF.ForClassId= ' + convert(varchar,@rForClassId) +') OR ( ' + convert(varchar,@rForClassId)+' =0))
			  AND AF.FormNo in (' + @rFormNo + ')'
			 execute(@query)
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormReferenceGet]
	 @rOrgId smallint=0,
	@rBatchId int,
	@rForClassId  int,
	 @rFormNo nvarchar(max)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	declare @query varchar(max)=''
	select @query = 'SELECT 
		*
  FROM 
        sAdmission.tAdmissionFormReference RA
         INNER JOIN   sAdmission.tAdmissionForm AF ON AF.Id=RA.AdmissionFormId
    WHERE (AF.OrgId= ' + convert(varchar,@rOrgId) + ')
			  AND AF.BatchId= ' + convert(varchar,@rBatchId) + '
			  AND ((AF.ForClassId= ' + convert(varchar,@rForClassId) +') OR ( ' + convert(varchar,@rForClassId)+' =0))
			  AND AF.FormNo in (' + @rFormNo + ')'
			  execute(@query)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormSiblingGet]
	  @rOrgId smallint=0,
	  @rBatchId int,
	  @rForClassId  int,
	  @rFormNo nvarchar(max)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	declare @query varchar(max)=''
	select @query = 'SELECT 
		*
  FROM 
        sAdmission.tAdmissionFormSibling RA
        INNER JOIN   sAdmission.tAdmissionForm AF ON AF.Id=RA.AdmissionFormId
    WHERE  (AF.OrgId= ' + convert(varchar,@rOrgId) + ')
			  AND AF.BatchId= ' + convert(varchar,@rBatchId) + '
			  AND ((AF.ForClassId= ' + convert(varchar,@rForClassId) +') OR ( ' + convert(varchar,@rForClassId)+' =0))
			  AND AF.FormNo in (' + @rFormNo + ')'
			   execute(@query)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pPortalAdmissionFormStudentAcademicGet]
	@rOrgId smallint=0,
	@rBatchId int,
	@rForClassId  int,
	 @rFormNo nvarchar(max)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 declare @query varchar(max)=''
	select @query = 'SELECT 
		*
  FROM 
        sAdmission.tAdmissionFormStudentAcademic SA
         INNER JOIN   sAdmission.tAdmissionForm AF ON AF.Id=SA.AdmissionFormId
    WHERE (AF.OrgId= ' + convert(varchar,@rOrgId) + ')
			  AND AF.BatchId= ' + convert(varchar,@rBatchId) + '
			  AND ((AF.ForClassId= ' + convert(varchar,@rForClassId) +') OR ( ' + convert(varchar,@rForClassId)+' =0))
			  AND AF.FormNo in (' + @rFormNo + ')'
			  execute(@query)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pPortalAdmissionInquiryGet]
	 
	  @rOrgGroupId	int=0,
	  @rBatchId int,
	  @rForClassId  int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	SELECT 
		*
  FROM 
        sAdmission.tAdmissionInquiry AI
    WHERE  AI.OrgGroupId=@rOrgGroupId 
			  AND AI.ForBatchId=@rBatchId
			  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0))
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pPortalStudentDetailGetDownload]
	 @rOrgId smallint=0,
	@rBatchId int,
	@rForClassId  int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	SELECT 
		Id,FormNo,FirstName+' ' + MiddleName + ' '  + LastName As Name
  FROM 
        sAdmission.tAdmissionForm 
    WHERE  OrgId=@rOrgId
		AND  BatchId=@rBatchId
		AND  ForClassId=@rForClassId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionBlankFormFieldGet]

	@rClassId int = 0
	
AS
SET NOCOUNT ON

BEGIN 
	SELECT DISTINCT
		ACF.ClassId,
		ACF.FieldGroup,
		ACF.FieldRemark
	FROM  
		sAdmission.tAdmissionCriteriaForm ACF
	WHERE 	
		ACF.ClassId = @rClassId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionBlankFormGet]
	@rClassId int = 0,
	@rBatchId int = 0

AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

   select 
	 ISNULL(AC.ClassId,0) AS ClassId,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	 ISNULL(AC.ConfirmationRemark,'') AS ConfirmationRemark,
	 ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	 ISNULL(AC.CustomField1Remark,'') AS CustomField1Remark,
	 ISNULL(AC.CustomField2Remark,'') AS CustomField2Remark,
	 ISNULL(AC.CustomField3Remark,'') AS CustomField3Remark,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](302,OM.Id) AS IsBirthPlace,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](303,OM.Id) AS IsBirthTaluka,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](304,OM.Id) AS IsBirthDistrict,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](305,OM.Id) AS IsBirthState,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](306,OM.Id) AS IsBirthCountry,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](307,OM.Id) AS IsPreviousSchool,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](308,OM.Id) AS IsStudentPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](316,OM.Id) AS IsContactEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](317,OM.Id) AS IsReligion,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](318,OM.Id) AS IsFamilyCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](319,OM.Id) AS IsNationality,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](320,OM.Id) AS IsCasteCategory,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](388,OM.Id) AS IsFamilySubCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](321,OM.Id) AS IsMotherTongue,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](322,OM.Id) AS IsAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](323,OM.Id) AS IsOtherInformation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](324,OM.Id) AS IsLiveWith,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](325,OM.Id) AS IsHotelRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](326,OM.Id) AS IsTransportRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](327,OM.Id) AS IsMotherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](328,OM.Id) AS IsMotherMobilNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](329,OM.Id) AS IsMotherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](330,OM.Id) AS IsMotherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](331,OM.Id) AS IsMotherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](332,OM.Id) AS IsMotherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](333,OM.Id) AS IsMotherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](334,OM.Id) AS IsMotherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](337,OM.Id) AS IsMotherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](338,OM.Id) AS IsMotherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](410,OM.Id) AS IsMotherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](349,OM.Id) AS IsFatherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](350,OM.Id) AS IsFatherMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](351,OM.Id) AS IsFatherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](352,OM.Id) AS IsFatherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](353,OM.Id) AS IsFatherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](354,OM.Id) AS IsFatherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](355,OM.Id) AS IsFatherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](356,OM.Id) AS IsFatherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](359,OM.Id) AS IsFatherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](360,OM.Id) AS IsFatherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](409,OM.Id) AS IsFatherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](361,OM.Id) AS IsGuardianFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](362,OM.Id) AS IsGuardianMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](363,OM.Id) AS IsGuardianPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](396,OM.Id) AS IsGuardianQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](397,OM.Id) AS IsGuardianOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](398,OM.Id) AS IsGuardianEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](399,OM.Id) AS IsGuardianIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](400,OM.Id) AS IsGuardianOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](401,OM.Id) AS IsGuardianDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](403,OM.Id) AS IsGuardianRelationship,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](405,OM.Id) AS IsGuardianOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](411,OM.Id) AS IsGuardianAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](369,OM.Id) AS IsPhysicalDeformity,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](370,OM.Id) AS IsPhysicalDeformityRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](371,OM.Id) AS IsMajorIllness,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](372,OM.Id) AS IsMajorIllnessRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](373,OM.Id) AS IsAllergy,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](374,OM.Id) AS IsAllergyRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](407,OM.Id) AS IsMeritMarks,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](408,OM.Id) AS IsMeritGrade,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](395,OM.Id) AS IsBloodGroup,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](309,OM.Id) AS IsStreetOneAddress
	 ,[sAdmission].[fAdmissionFormDisplayFieldGet](1233,OM.Id) AS IsPENNumber --mantis : 0043425
	 ,[sAdmission].[fAdmissionFormDisplayFieldGet](1234,OM.Id) AS IsApaarIdNumber--mantis : 0043425
	FROM  
		    sAdmission.tAdmissionCriteria AC 
		    INNER JOIN sSetup.tClassMaster CM ON CM.Id=AC.ClassId
			INNER JOIN sSetup.tBatchMaster BM  ON  BM.Id=AC.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=BM.OrgId
	WHERE 	
	((AC.ClassId = @rClassId) OR (@rClassId = 0))	
	AND ((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionDetailsGet]
	
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId int,
	 @rDepartmentId int,
	 @rFromMeritMarks int,
	 @rToMeritMarks int,
	 @rIsDetail bit =0 --Mantis : 0028438
AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	
	 AF.FormNo,
	 AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
	 AF.ForClassId,
	 AF.DateOfBirth,
	 AF.BatchId,
	 AF.OrgId,
	 AF.City,
	 AF.Country,
	 AF.State AS CityState,
	 AF.ContactEmail,
	 AF.ContactNo,
	 AF.PreviousSchool,
	 AF.MeritGrade,
	 AF.MeritMarks,
	 AF.GenderId,
	 GM.Title AS Gender,
	 CM.Title AS Class,
	 AF.FamilyCast,
	 AF.FamilySubCast,
	 AF.CastCategoryId,
	 @rBuilder1 AS Builder1,
	 @rBuilder2 AS Builder2,
	 @rIsDetail AS IsDetail
	 
  FROM 
				sAdmission.tAdmissionForm AF
				INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId=CM.Id
				LEFT JOIN sCommon.tGenderMaster GM ON AF.GenderId=GM.Id
				LEFT JOIN sCommon.tStatusMaster SM ON AF.StatusId=SM.Id	
 WHERE 	
       AF.BatchId=@rBatchId
    --AND AF.OrgId=@rOrgId
		AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND ((AF.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
		AND ((AF.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
		AND ((CM.Id=@rClassId) OR (@rClassId = 0))
		AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	    AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
	--Group By FormNo,GM.Title,FirstName,MiddleName,LastName,DateOfBirth,City,Country,State,ContactEmail,
	--         ContactNo,PreviousSchool,MeritGrade,MeritMarks,FamilyCast,FamilySubCast,CastCategoryId
				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

BEGIN 
	
	SELECT 
		 AF.FormNo,
		 AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		 AF.ForClassId,
		 AF.BatchId,
		 AF.OrgId,
		 AF.City,
		 AF.FamilyCast,
		 CM.Title AS Class,
		 AF.FamilySubCast,
		 AF.CastCategoryId,
		 --for online and offline display same feename
		 AC.FormFeeName AS FeeName,
		 --ACF.FeeName,
		 --in online entry display amount from pt  and in offline entry amount display from aff
		 CASE WHEN AF.DataEntryModeId = 561 THEN PT.PayAmount ELSE AFF.FeeAmount END  AS FeeAmount,
		 --AFF.FeeAmount,
		 --ACF.FeeNumber,
		 @rIsDetail AS IsDetail,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 ISNULL(AF.CreatedDateTime,'') AS CreatedDateTime,
		 ISNULL(AFR.ReceiptNumber, 0) AS ReceiptNumber --Mantis - 0033981
	 
	 FROM 
		sAdmission.tAdmissionForm AF	
		INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId=CM.Id
		LEFT JOIN sAdmission.tAdmissionFormFee AFF ON AFF.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionCriteriaFee ACF ON ACF.Id = AFF.AdmissionCriteriaFeeId
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id AND AC.BatchId = @rBatchId
		LEFT JOIN sOp.tPaymentTransaction PT ON AF.Id = PT.PayerSourceId AND PT.TransactionSourceTypeId = 2027 AND PT.TransactionStatusId IN (2,4)
		LEFT JOIN sAdmission.tAdmissionFormReceipt AFR ON AF.Id = AFR.SourceId AND  AF.BatchId = AFR.BatchId --Mantis - 0033981

	WHERE 	
		AF.BatchId=@rBatchId
		--AND AF.OrgId=@rOrgId
		AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
		AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	    AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
	    ORDER BY AF.FormNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionFormFieldGet]

	@rId bigint
	
AS
SET NOCOUNT ON

BEGIN 
	SELECT
	
		CONVERT(nvarchar(20),AFF.AdmissionFormId) AS AdmissionFormIdText,
		AFF.AdmissionFormId,
		ACF.FieldGroup,
		ACF.FieldRemark,
		AFF.AdmissionFormFieldResponse,
		ACF.FieldOrder
	FROM  
		sAdmission.tAdmissionCriteriaForm ACF
		INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id=AFF.AdmissionCriteriaFormId
	WHERE 	
		AFF.AdmissionFormId = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionFormGet]
 
	
	@rId bigint = 0,
	@rRelationShipId int=0,
	@rClassId int = 0,	 	
	@rFromDate date = '',
	@rToDate date = '',
	@rOrgId int = 0,
	@rDepartmentId int = 0,
	@rFromMeritMarks int = 0,
	@rToMeritMarks int = 0,
	@rBatchId int = 0

AS
 SET NOCOUNT ON

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),@rRelationShipId) AS RelationShipIdText,
	 ISNULL(AF.Id,0) AS AdmissionFromId,
	 ISNULL(AF.FormNo,0) AS FormNo,
	 [sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name,
	 ISNULL(AF.FirstName,'')AS FirstName,
	 ISNULL(AF.ForClassId,0) AS ForClassId,
	 ISNULL(AF.DateOfBirth,'') AS DateOfBirth,
	 ISNULL(AF.BatchId,0)AS BatchId,
	 ISNULL(CM.Title,'') AS ClassName,
	 ISNULL(AF.OrgId,0)AS OrgId,
	 ISNULL(AF.StreetOne,'')AS StreetOne,
	 ISNULL(AF.StreetTwo,'')AS StreetTwo,
	 ISNULL(AF.StreetThree,'')AS StreetThree,
	 ISNULL(AF.Country,'')AS Country,
	 ISNULL(AF.City,'')AS City,
	 ISNULL(AF.State,'')AS State,
	 ISNULL(AF.ZipCode,'') AS ZipCode,
	 ISNULL(AF.ContactEmail,'')AS ContactEmail,
	 ISNULL(AF.ContactNo,'') AS ContactNo,
	 ISNULL(AF.PreviousSchool,'')AS PreviousSchool,
	 ISNULL(AF.StudentPhoto,0x) As StudentPhoto,
	 ISNULL(AF.ReligionId,0) AS ReligionId,
	 IsNULL(RM.Title,'') AS ReligionName,
	 ISNULL(AF.MeritGrade,'')AS MeritGrade,
	 ISNULL(AF.MeritMarks,0) AS MeritMarks,
	 ISNULL(AF.GenderId,0) AS GenderId,
	 ISNULL(GM.Title,'') AS Gender,
	 ISNULL(AF.FamilyCast,'')AS FamilyCast,
	 ISNULL(AF.FamilySubCast,'')AS FamilySubCast,
	 ISNULL(AF.CastCategoryId,0) AS CastCategoryId,
	 ISNULL(CCM.Title,'') AS CastCategory ,
	 ISNULL(OM.DisplayTitle,'')AS DisplayTitle ,
	 ISNULL(BM.Title,'') As Batch,
	 ISNULL(AFM.FatherName,'') AS FatherName ,
	 ISNULL(AFM.FatherDateOfBirth,'')As FatherDateOfBirth,
	 ISNULL(AFM.FatherOccupation,'') AS FatherOccupation,
	 ISNULL(AFM.FatherOfficeAddress,'') AS FatherOfficeAddress,
	 ISNULL(AFM.FatherIncome,0) AS FatherIncome,
	 ISNULL(AFM.FatherQualification,'') AS FatherQualification,
	 ISNULL(AFM.FatherContactNo,'') AS FatherContactNo ,
	 ISNULL(AFM.FatherMail,'') AS FatherMail,
	 ISNULL(AFM.FatherOrganization,'') AS FatherOrganization,
	 ISNULL(AFM.MotherName,'') AS MotherName,
	 IsNull(AFM.MotherDateOfBirth,'')As MotherDateOfBirth,
	 ISNULL(AFM.MotherIncome,0) AS MotherIncome,
	 ISNULL(AFM.MotherOccupation,'') AS MotherOccupation,
	 ISNULL(AFM.MotherOfficeAddress,'') AS MotherOfficeAddress,
	 ISNULL(AFM.MotherQualification,'') AS MotherQualification,
	 ISNULL(AFM.MotherContactNo,'') AS MotherContactNo,
	 ISNULL(AFM.MotherMail,'') AS MotherMail,
	 ISNULL(AFM.MotherOrganization,'') AS MotherOrganization,
	 isnull(AFM.RelativeName,'') AS RelativeName ,
	 ISNULL(AFM.RelativeDateOfBirth,'') AS RelativeDateOfBirth,
	 ISNULL(AFM.RelativeOccupation,'') AS RelativeOccupation,
	 ISNULL(AFM.RelativeContactNo,'') AS RelativeContactNo,
	 ISNULL(AFM.RelativeMail,'') AS RelativeMail,
	 ISNULL(AFM.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
	 ISNULL(AFM.RelativeIncome,0) AS RelativeIncome,
	 ISNULL(AFM.RelativeQualification,'') AS RelativeQualification,
	 ISNULL(AFM.RelationshipName,'') AS RelationshipName ,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	 ISNULL(AC.ConfirmationRemark,'') AS ConfirmationRemark,
	 ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	
	 ISNULL(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
	 ISNULL(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
	 ISNULL(AF.IsMajorIllness,0) AS IsMajorIllness,
	 ISNULL(AF.MajorIllnessRemark, '') As MajorIllnessRemark,
	 ISNULL(AF.IsAllergy,0)AS IsAllergy,
	 ISNULL(AF.AllergyRemark,'') As AllergyRemark,
	 ISNULL(AF.BirthPlace,'') As BirthPlace,
	 ISNULL(AF.BirthTaluka,'') As BirthTaluka,
	 ISNULL(AF.BirthDistrict,'') As BirthDistrict,
	 Isnull(BGM.Title,'') As BloodGroupName,
	 ISNULL(AF.AdhaarNumber,'') AS AdhaarNumber,
	 ISNULL(AF.IsHostelRequired,0)AS IsHostelRequired,
	 ISNULL(AF.IsTransportRequired,0)AS IsTransportRequired,
	 ISNULL(AFM.FatherPhoto,0x)As FatherPhoto,
	  ISNULL(AFM.MotherPhoto,0x) As MotherPhoto,
	 ISNULL(AFM.RelativePhoto,0x) As RelativePhoto,
	 ISNULL(AF.BirthState,'')AS BirthState,
	 ISNULL(AF.BirthCountry,'') AS BirthCountry,
	 ISNULL(AC.CustomField1Remark,'') AS CustomField1Remark,
	 ISNULL(AC.CustomField2Remark,'') AS CustomField2Remark,
	 ISNULL(AC.CustomField3Remark,'') AS CustomField3Remark,
	 ISNULL(AF.CustomField1Answer,'')As CustomField1Answer,
	 ISNULL(AF.CustomField2Answer,'')As CustomField2Answer,
	 ISNULL(AF.CustomField3Answer,'')As CustomField3Answer,
	 ISNULL(AF.Nationality,'') AS Nationality,
	 ISNULL(AF.MotherTongue,'') AS MotherTongue,
	 ISNULL(AF.OtherInformation,'') AS OtherInformation,
	 ISNULL(LWM.Title,'') AS LiveWith,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 ISNULL(AF.DateOfBirthInWord,'') AS DOBInWords,
	 ISNULL(AF.CreatedDateTime,'') As FormDate,
	  ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	 ISNULL (AFM.FatherAdhaarNumber,'') AS FatherAadhaarNumber,
	 ISNULL (AFM.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
	 ISNULL (AFM.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
	 ISNULL( (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=324
	 ),0)AS IsOtherDetailsLiveWith,
	 ISNULL( (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=323
	 ),0)AS IsOtherDetailsOtherInformation,
	 ISNULL(AF.MiddleName,'') AS MiddleName,
	 ISNULL(AF.LastName,'')AS LastName,
	 ISNULL(PT.Id,0) AS PaymentTransactionId,
	 ISNULL(PT.PayAmount,0.00) AS PayAmount,
	 ISNULL(PT.TransactionStatusId,0) AS TransactionStatusId,
	 ISNULL(PT.PayDateTime,'') AS PayDateTime,
	 ISNULL(AFM.IsFatherExStudent,0) AS IsFatherExStudent,
	 ISNULL(AFM.IsMotherExStudent,0) AS IsMotherExStudent,
	 ISNULL(AFM.IsRelativeExStudent,0)AS IsRelativeExStudent,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](302,OM.Id) AS IsBirthPlace,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](303,OM.Id) AS IsBirthTaluka,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](304,OM.Id) AS IsBirthDistrict,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](305,OM.Id) AS IsBirthState,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](306,OM.Id) AS IsBirthCountry,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](307,OM.Id) AS IsPreviousSchool,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](308,OM.Id) AS IsStudentPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](316,OM.Id) AS IsContactEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](317,OM.Id) AS IsReligion,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](318,OM.Id) AS IsFamilyCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](319,OM.Id) AS IsNationality,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](320,OM.Id) AS IsCasteCategory,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](388,OM.Id) AS IsFamilySubCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](321,OM.Id) AS IsMotherTongue,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](322,OM.Id) AS IsAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](323,OM.Id) AS IsOtherInformation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](324,OM.Id) AS IsLiveWith,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](325,OM.Id) AS IsHotelRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](326,OM.Id) AS IsTransportRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](327,OM.Id) AS IsMotherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](328,OM.Id) AS IsMotherMobilNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](329,OM.Id) AS IsMotherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](330,OM.Id) AS IsMotherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](331,OM.Id) AS IsMotherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](332,OM.Id) AS IsMotherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](333,OM.Id) AS IsMotherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](334,OM.Id) AS IsMotherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](337,OM.Id) AS IsMotherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](338,OM.Id) AS IsMotherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](410,OM.Id) AS IsMotherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](349,OM.Id) AS IsFatherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](350,OM.Id) AS IsFatherMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](351,OM.Id) AS IsFatherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](352,OM.Id) AS IsFatherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](353,OM.Id) AS IsFatherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](354,OM.Id) AS IsFatherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](355,OM.Id) AS IsFatherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](356,OM.Id) AS IsFatherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](359,OM.Id) AS IsFatherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](360,OM.Id) AS IsFatherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](409,OM.Id) AS IsFatherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](361,OM.Id) AS IsGuardianFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](362,OM.Id) AS IsGuardianMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](363,OM.Id) AS IsGuardianPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](396,OM.Id) AS IsGuardianQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](397,OM.Id) AS IsGuardianOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](398,OM.Id) AS IsGuardianEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](399,OM.Id) AS IsGuardianIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](400,OM.Id) AS IsGuardianOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](401,OM.Id) AS IsGuardianDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](403,OM.Id) AS IsGuardianRelationship,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](405,OM.Id) AS IsGuardianOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](411,OM.Id) AS IsGuardianAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](369,OM.Id) AS IsPhysicalDeformity,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](370,OM.Id) AS IsPhysicalDeformityRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](371,OM.Id) AS IsMajorIllness,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](372,OM.Id) AS IsMajorIllnessRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](373,OM.Id) AS IsAllergy,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](374,OM.Id) AS IsAllergyRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](407,OM.Id) AS IsMeritMarks,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](408,OM.Id) AS IsMeritGrade,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](395,OM.Id) AS IsBloodGroup,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](309,OM.Id) AS IsStreetOneAddress ,

	  ISNULL(AFM.FatherDesignation,'') AS FatherDesignation ,
	  ISNULL(AFM.FatherPassOutYear,'') AS FatherPassOutYear ,
	  ISNULL(AFM.MotherDesignation,'') AS MotherDesignation ,
	  ISNULL(AFM.MotherPassOutYear,'') AS MotherPassOutYear ,
	  AF.AdmissionDate, --add for Mentis : 0034078
	  ISNULL(AC.AdmissionConfirmationRemark,'') AS AdmissionConfirmationRemark			-- MantisId : 0038036
	  ,[sAdmission].[fAdmissionFormDisplayFieldGet](1233,OM.Id) AS IsPENNumber
	  ,[sAdmission].[fAdmissionFormDisplayFieldGet](1234,OM.Id) AS IsApaarIdNumber
	  ,ISNULL(AF.PENNumber,0) AS PENNumber --Mantis -0043425
	  ,ISNULL(AF.ApaarIdNumber,'') AS ApaarIdNumber --Mantis -0043425

  FROM  
		    sAdmission.tAdmissionForm AF 
		     
			--INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AF.OrgId
			INNER JOIN sSetup.tBatchMaster BM  ON  BM.Id=AF.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=AF.ReligionId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=AF.BloodGroupId
			--LEFT JOIN sAdmission.tAdmissionFormParentAcademic PA ON PA.AdmissionFormId=AF.Id
			--INNER JOIN sCommon.tRelationshipMaster RSM ON RSM.Id=PA.RelationshipId
			LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=AF.CastCategoryId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFM ON AFM.AdmissionFormId=AF.Id
			LEFT JOIN sCommon.tLiveWithMaster LWM ON LWM.Id = AFM.LiveWithId
			LEFT JOIN  sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id  AND AC.BatchId=AF.BatchId		
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.PayerSourceId = AF.Id AND PT.PayerSourceTypeId = 2027 AND (PT.TransactionStatusId = 2 OR PT.TransactionStatusId = 4)
 WHERE 	
  (AF.Id = @rId OR @rId = 0)
  AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
  AND ((AF.BatchId = @rBatchId) OR (@rBatchId = 0))
	AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
	AND ((AF.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	AND ((AF.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))		
	AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
 

				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionFormParentAcademicSubGet]
	
	@rId bigint ,
	 @rRelationShipId int=0

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),ISNULL(@rRelationShipId,0)) AS RelationShipIdText,
	 AF.Id,
	 PA.AcademicYear,
	 PA.AdmissionClass,
	 PA.InstituteAffiliaton,
	 PA.InstituteCity,
	 PA.InstituteName,
	 PA.RelationshipId,
	 PA.Language AS Medium
	
	      
  FROM  
		    sAdmission.tAdmissionForm AF 
			INNER JOIN sAdmission.tAdmissionFormParentAcademic PA ON PA.AdmissionFormId=AF.Id
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=PA.RelationshipId
			
				
 WHERE 	
  AF.Id = @rId 
 AND PA.RelationShipId = @rRelationShipId
 AND (PA.AcademicYear!='' OR PA.AdmissionClass!='' OR PA.InstituteAffiliaton!='' OR PA.InstituteCity!='' OR  PA.InstituteName!='' OR PA.Language!='')
				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionFormReceiptGet]
	 	 
	 	 @rAdmissionFormReceiptId bigint,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rFeeName nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			AF.FirstName +' '+AF.LastName AS StudentName,
			--AF.MiddleName AS FatherName,
			AFFD.FatherName AS FatherName,
			AFFD.MotherName AS MotherName,
			AF.StreetOne+', '+AF.StreetTwo+', '+AF.StreetThree+', '+AF.City+', '+AF.State+', '+AF.Country+' - '+AF.ZipCode AS StudentAddress,
			AF.ContactNo AS MobileNo,
			AF.FormNo,
			AFR.ReceiptNumber,
			AFR.ReceiptDate,
			CM.Title AS ClassName,
			BM.Title AS BatchName,
			AFR.ReceiptAmount,
			@rFeeName AS FeeName,
			PTM.Title AS PayTypeName
	FROM 
		sAdmission.tAdmissionForm AF
		LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
		INNER JOIN sAdmission.tAdmissionFormReceipt AFR ON AF.Id = AFR.SourceId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId 
		INNER JOIN sOp.tPayTypeMaster PTM ON PTM.Id = AFR.PayTypeId 
	WHERE
		AFR.Id = @rAdmissionFormReceiptId
		AND AF.BatchId = @rBatchId
		AND AF.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionFormReferenceSubGet]
	
	@rId bigint

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 AF.Id,
	 AFR.ReferenceDetail,
	 isnull(AFR.ReferenceName,'') AS ReferenceName ,
	 AFR.ReferenceRelation,
	 AFR.ReferenceContactNo
	
	      
  FROM  
		    sAdmission.tAdmissionForm AF 
			INNER JOIN sAdmission.tAdmissionFormReference AFR ON AFR.AdmissionFormId=AF.Id
				
 WHERE 	
  AF.Id = @rId
  AND ( AFR.ReferenceDetail!='' OR ReferenceName!='' OR  AFR.ReferenceRelation!='' OR AFR.ReferenceContactNo!='')

				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionFormSiblingSubGet]
	
	@rId bigint

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 AF.Id,
	 isnull(ADS.SiblingName,'') AS SiblingName,
	 ADS.SiblingRelation,
	 ADS.SiblingStandard,
	 ADS.SiblingSchool,
	 ISNULL(ADS.Code,'') AS Code
	      
  FROM  
		    sAdmission.tAdmissionForm AF 
			INNER JOIN sAdmission.tAdmissionFormSibling ADS ON ADS.AdmissionFormId=AF.Id
				
 WHERE 	
  AF.Id = @rId
  AND ADS.SiblingName IS NOT NULL 
  AND ADS.SiblingName != ''
				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionFormStudentAcademicSubGet]
	
	@rId bigint

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 AF.Id,
	 SA.AcademicYear,
	 SA.AdmissionClass,
	 SA.InstituteAffiliaton,
	 SA.InstituteCity,
	 SA.InstituteName,
	 SA.Language AS Medium,
	 SA.Result
	 
	
	      
  FROM  
		    sAdmission.tAdmissionForm AF 
			INNER JOIN sAdmission.tAdmissionFormStudentAcademic SA ON SA.AdmissionFormId=AF.Id
				
 WHERE 	
  AF.Id = @rId
  AND ( SA.AcademicYear!='' OR SA.AdmissionClass!= '' OR SA.InstituteAffiliaton!=''
	 OR SA.InstituteCity!='' OR SA.InstituteName!='' OR  SA.Language!=''
	 OR SA.Result!='')
				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionInquiryBlankFieldGet]

	@rClassId int = 0,
	@rBatchId int = 0
	
AS
SET NOCOUNT ON

BEGIN 
	SELECT
		AIF.ClassId,
		AIF.BatchId,
		AIF.FieldGroup,
		AIF.FieldRemark
	FROM  
		sAdmission.tAdmissionInquiryForm AIF
	WHERE 	
		AIF.ClassId = @rClassId
		AND AIF.BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionInquiryBlankGet]
	
	 @rClassId int = 0,
	 @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
		ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
		AIC.ClassId,
		AIC.BatchId

	FROM
        sAdmission.tAdmissionInquiryCriteria AIC
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AIC.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AIC.BatchId
	WHERE  
	   ((AIC.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((AIC.BatchId = @rBatchId) OR (@rBatchId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionInquiryFieldGet]

	@rId nvarchar(20) --mantis: 41025

AS
SET NOCOUNT ON

BEGIN
	SELECT
		CONVERT(nvarchar(20),AI.AdmissionInquiryId) AS AdmissionInquiryIdText,
		AI.AdmissionInquiryId,
		AIF.FieldGroup,
		AIF.FieldRemark,
		AI.AdmissionInquiryFieldResponse,
		AIF.FieldOrder
	FROM
		sAdmission.tAdmissionInquiryForm AIF
		INNER JOIN sAdmission.tAdmissionInquiryField AI ON AIF.Id=AI.AdmissionInquiryFormId
	WHERE
		AI.AdmissionInquiryId = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionInquiryListGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rClassId int = 0,
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rFromDate datetime='',
	 @rToDate datetime='',
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryStatusId int =0,
	 @rBatchId int = 0 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		AI.Id InquiryId,
		ISNULL(AI.Number,'') AS InquiryNumber,
		AI.ForClassId AS ClassId,
		ISNULL(CM.Title,'') AS ClassName,
		AI.FirstName,
		AI.MiddleName,
		AI.LastName,
		[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName,
		ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate,
		ISNULL(AI.FatherContactNo,'') AS FatherContactNo,
		ISNULL(AI.MotherContactNo,'') AS MotherContactNo,
		SM.Title AS InquiryStatus
	FROM 
        sAdmission.tAdmissionInquiry AI
        INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
	 WHERE  
		((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((AI.InquiryDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((AI.ForClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rInquiryStatusId) OR (@rInquiryStatusId=0))
		AND (AI.OrgId=@rOrgId OR @rOrgId=0)
		AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
		AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))	
		AND ((AI.ForBatchId=@rBatchId) OR (@rBatchId=0))		    
END

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

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionListWIthMeritMarksGet]
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId int,
	 @rDepartmentId int,
	 @rFromMeritMarks int,
	 @rToMeritMarks int
AS
 SET NOCOUNT ON

BEGIN
SELECT
	 AF.FormNo,
	 AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
	 AF.ForClassId,
	 CM.Title AS Class,
	 @rBuilder1 AS Builder1,
	 @rBuilder2 AS Builder2,
	 SUM(SS.ObtainMark) As MeritMark,
	 SA.AdmissionDate,
	 SM.Code,
	 CM.OrderIndex AS ClassOrder
	
  FROM 
				sAdmission.tAdmissionForm AF
				INNER JOIN sSetup.tClassMaster CM ON AF.ForClassId=CM.Id
				LEFT JOIN sAdmission.tAdmissionSetupStudent SS ON SS.AdmissionFormId=AF.Id
				INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=AF.StudentId AND SA.BatchId=@rBatchId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id=AF.StudentId
 WHERE 	
        AF.BatchId=@rBatchId
		AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND ((SS.ObtainMark >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
		AND ((SS.ObtainMark <= @rToMeritMarks) OR (@rToMeritMarks=0))
		AND ((CM.Id=@rClassId) OR (@rClassId = 0))
	
	    AND ((convert(date,AF.CreatedDateTime)>= convert(date,@rFromDate)) OR (@rFromDate=''))
		AND ((convert(date,AF.CreatedDateTime) <= @rToDate) OR (@rToDate=''))
		GROUP BY  AF.FormNo,AF.FirstName,AF.MiddleName,AF.LastName, AF.ForClassId,CM.Title ,SA.AdmissionDate,SM.Code,CM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionMarkEntry]
	
	 @rClassName nvarchar(max)='',
	 @rClassId int = 0,
	 @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT 
			@rClassName AS ClassName,
			Id, 
			ClassId,
			TotalMark,
			CriteriaName 
	FROM 
			sAdmission.tAdmissionSetup 
		
	WHERE 
			ClassId =  @rClassId  
			AND BatchId= @rBatchId
	    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionMarkEntryGet]
	

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rId bigint = 0,
	 @rForClassId int = 0,
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	-- @rStatusId smallint,
	 @rInquiryStatusMasterId int = 0,
	 @rOrgId int = 0,
	 @rFirstName nvarchar(100) = '',
	 @rLastName nvarchar(100) = '',
	 @rFromDate datetime='',
	 @rToDate datetime='',
	 @rForBatchId int = 0,
	 @rDepartmentId int = 0,
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryModeId smallint=0,
	 @rInquiryReferenceId int=0,
	 @rNumber bigint=0,
	 @rOrgGroupBatchId int = 0,
	 @rFollowUpdate datetime='',
	 @rIsTransportRequired int=0,
	 @rIsHostelRequired int=0,
	 @rOrderBy int =0,
	 @rIsGivenAdmissionForm int =0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
    AF.Id AS FormId, 
	ISNULL(ASS.ObtainMark,0) AS mark,
	AOS.CriteriaName AS CriteriaName, 
	AF.FormNo AS FormNo,  
	AOS.TotalMark,
	(AF.FirstName + AF.MiddleName + AF.LastName) AS FirstName 
FROM 
	sAdmission.tAdmissionForm AF 
	INNER JOIN sAdmission.tAdmissionSetup AOS ON AOS.ClassId = AF.ForClassId AND AOS.BatchId = AF.BatchId 
	LEFT JOIN sAdmission.tAdmissionSetupStudent ASS ON AF.Id = ASS.AdmissionFormId AND AOS.Id = ASS.AdmissionSetupId
	INNER JOIN sAdmission.tAdmissionFormSelected AFS ON AFS.AdmissionFormId = AF.Id
WHERE
	AF.ForClassId=  @rClassId  
	AND AF.BatchId= @rBatchId
	AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
	AND ((AF.CreatedDateTime <= @rToDate) OR (@rToDate=''))
GROUP BY 
	AF.Id,ASS.ObtainMark,AOS.CriteriaName,AF.FormNo,AOS.TotalMark,AF.FirstName,AF.MiddleName,AF.LastName,AF.CreatedDateTime
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionReceiptGet] 
	 	 
	 	 @rBatchId int,
	 	 @rOrgId int ,
	 	 @rFormNo int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			ISNULL(AF.FirstName,'') + ' ' + ISNULL(AF.MiddleName, '') + ' ' + ISNULL(AF.LastName,'') AS StudentName,
			AFF.FatherName AS FatherName,
			AFF.MotherName AS MotherName,
			AF.StreetOne+' ' +AF.StreetTwo+' ' +AF.StreetThree+' ' +AF.City +' ' +AF.State+' '+AF.Country AS StudentAddress,
			AF.ContactNo AS MobileNo,
			AF.FormNo as FormNo,
			0 as ReceiptNumber,
			Convert(date,ISNULL(AF.CreatedDateTime,'')) as ReceiptDate,
			CM.DisplayTitle AS ClassName,
			BM.Title AS BatchName,
			AC.FormFeeAmount as FormFeeAmount,
			AC.FormFeeName AS FormFeeName,
			ACF.FeeNumber ,
			ACF.FeeName,
			ACF.FeeOrder,
			AFFE.FeeAmount,
			ISNULL(AF.Remark,'') AS Remark,
			ISNULL(AF.DateOfBirth,'') AS DateOfBirth,
			ISNULL(AF.FirstName,'') AS StudentFirstName,
			ISNULL(AF.MiddleName, '') AS StudentMiddleName,
			ISNULL(AF.LastName,'') AS StudentLastName,
			ISNULL(GM.Title,'') as Gender,
			AFR.ReceiptNumber AS ReceiptNo, --Added for mantis : 33847 by Nilesh
			AFR.ReceiptAmount,	--Add for mantis: 34077
			AFR.ReceiptDate As AdmissionFormReceiptDate,		-- MantisId : 0036023	
			--PTM.Title AS PayTypeName --Add for mantis : 0036152
			CASE WHEN
			EXISTS(SELECT 1 FROM sOp.tPaymentTransaction WHERE PayerSourceTypeId = 2027 AND PayerSourceId = AF.Id and TransactionStatusId IN(2,4) and PaymentGatewayId !=0) THEN 'Payment Gateway' 
			ELSE PTM.Title END AS PayTypeName --Add for mantis : 0036152
	FROM 
			sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId 
			INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id AND AC.BatchId = @rBatchId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFF ON AFF.AdmissionFormId= AF.Id 
			LEFT JOIN sAdmission.tAdmissionFormFee  AFFE ON AFFE.AdmissionFormId = AF.Id
			LEFT JOIN sAdmission.tAdmissionCriteriaFee ACF ON ACF.Id = AFFE.AdmissionCriteriaFeeId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormReceipt AFR ON AF.Id = AFR.SourceId --Added for mantis : 33847 by Nilesh
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = AFR.PayTypeId --Add for mantis : 0036152	--change Inner to left for mantis: 37184
			
	WHERE
			AF.BatchId = @rBatchId
			AND AF.OrgId = @rOrgId
			AND AF.FormNo =@rFormNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionSlipGet]
	
	 @rDepartmentId int,
	 @rBatchId int,
	 @rClassId int,
	 @rFromDate date,
	 @rToDate date,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)=''
	
	 --@rOrgId int,
	 
	 --@rFromMeritMarks int,
	 --@rToMeritMarks int
	  
AS
	SET NOCOUNT ON			 
BEGIN 
	
	SELECT
		 AF.Id,
		 AF.FirstName + ' ' + AF.MiddleName + ' ' + AF.LastName AS Name,
		 AF.DateOfBirth,
		 AF.BatchId,
		 AF.OrgId,
		 SA.AdmissionDate AS AdmissionDate,
		 CM.DisplayTitle AS AdmissionStandard,
		 AF.MiddleName AS FatherName,
		 ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 BM.Title AS Batch,
		 ISNULL(AF.ContactNo,'') AS ContactNo
	FROM
		sAdmission.tAdmissionForm AF
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId = AF.StudentId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=AF.BatchId

	WHERE 	
		AF.BatchId = @rBatchId
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		AND ((CM.Id = @rClassId) OR (@rClassId = 0))
		AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
		AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAdmission].[pRptAdmissionSummaryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgGroupBatchId int = 0,
	 @rOrgId int = 0,
	 @rBatchId int,
	 @rDepartmentId int = 0,
 	 @rClassId int,
	 @rDivisionId int,
	 @rStatusId int,
	 @rFromDate date,
	 @rToDate date
AS
 SET NOCOUNT ON
			 

BEGIN 
  SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		A.Id AS AcademicId,
		SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
		SA.AdmissionDate,
		SM.Code,
		A.RollNo,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		CM.Title As Class,
		A.BatchId as Batch,
		SA.BatchId As AdmissionBatch,
		--AF.ContactNo AS ContactNo
		SC.ParentContactNo AS ContactNo,
		OM.DisplayTitle AS Organization,
		OM.Id AS OrgId,
		CM.Id AS ClassId,
		DM.Id AS DivisionId,
		CM.OrderIndex
  FROM 
		sStudent.tAcademic A 
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId  				 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id AND SA.BatchId = BM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SM.Id = SC.StudentId
  WHERE 	
		(BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND (OM.Id = @rOrgId OR @rOrgId = 0)
		AND (BM.Id = @rBatchId OR @rBatchId = 0)
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		AND ((CM.Id = @rClassId) OR (@rClassId = 0))
		AND ((DM.Id = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((ISNULL(SA.AdmissionDate,'') >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((ISNULL(SA.AdmissionDate,'') <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pRptPreviousStudentAnalysisGet]
	 
	 
	 @rClassId int,
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rBuilder1 nvarchar(MAX),
	 @rBuilder2 nvarchar(max)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	 
	SELECT 
		Count(SA.StudentId) AS Student,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.PreviousSchool,
		SA.AdmissionStandardId AS Class,
		CM.Title AS ClassName,
		Cm.OrderIndex As ClassOrderIndex
		
		
  FROM 
			 sStudent.tStudentAdmission SA
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.AdmissionStandardId
WHERE		 
	SA.BatchId =@rBatchId
	AND ((SA.AdmissionStandardId =@rClassId) OR (@rClassId=0))
	 AND ((SA.AdmissionDate >=@rFromDate) OR (@rFromDate=''))
	 AND ((SA.AdmissionDate<=@rToDate)OR(@rToDate=''))
Group BY SA.PreviousSchool,
		SA.AdmissionStandardId,
		CM.Title,CM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pRptStudentNewAdmissionListGet]
	
	 @rBatchId int,
	 @rClassId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rDivisionId int,
	 @rStatusId int
AS
 SET NOCOUNT ON
			 

BEGIN 
  SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
		SA.AdmissionDate,
		SM.Code,
		A.RollNo,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		CM.Title As Class,
		A.BatchId as Batch,
		SA.BatchId As AdmissionBatch,
		--AF.ContactNo AS ContactNo
		SC.ParentContactNo AS ContactNo 
  FROM 
		sStudent.tAcademic A 
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id AND SA.BatchId = A.BatchId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId  				 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
		--LEFT JOIN sAdmission.tAdmissionForm AF ON AF.StudentId=A.StudentId AND AF.BatchId=A.BatchId AND AF.OrgId=A.OrgId
		LEFT JOIN sStudent.tStudentCommunication SC ON SM.Id = SC.StudentId
  WHERE 	
		A.BatchId=@rBatchId 
		AND ((ISNULL(SA.AdmissionDate,'') >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((ISNULL(SA.AdmissionDate,'') <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND ((CM.Id=@rClassId) OR (@rClassId = 0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId = 0))
		AND ((SM.StatusId=@rStatusId) OR (@rStatusId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pSortedAdmissionFormAdd]

		@rAdmissionFormId bigint,
		@rTotalObtainMark decimal(10,2),
		@rChecked bit,
		@rDiscussionDate Date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

  
 IF(@rChecked = 1)	
	BEGIN
	
	
	
		IF NOT Exists(select * from sAdmission.tAdmissionFormSelected where AdmissionFormId=@rAdmissionFormId)
			BEGIN
					Insert into sAdmission.tAdmissionFormSelected 
					(AdmissionFormId
					,TotalObtainMark
					,AdmissionStatusId
					,DiscussionDate
					)
					 values 
					(
					@rAdmissionFormId,
					@rTotalObtainMark,
					2,
					@rDiscussionDate
					)
					
					Select 1 AS Result
					RETURN
			END	 
		      
	
	
	ELSE
	 UPDATE  sAdmission.tAdmissionFormSelected
	    SET
			
			TotalObtainMark=@rTotalObtainMark,
			AdmissionStatusId=2,
			DiscussionDate = @rDiscussionDate
			where
			AdmissionFormId=@rAdmissionFormId
			
			 Select 1 AS Result
			END
	
	 ELSE
	 BEGIN
	 
	 Delete from sAdmission.tAdmissionFormSelected Where AdmissionFormId=@rAdmissionFormId 
	 
	 Select 1 AS Result
	 
	 RETURN
	END
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pSortedAdmissionFormGET]

	 @rClassId  nvarchar(max) = '',
	 @rBatchId int = 0,
	 @rOrgId int,
	 @rFirstName nvarchar(100),
	 @rLastName nvarchar(100),
	 @rMinMeritMarks decimal(10,2),
	 @rMaxMeritMarks decimal(10,2),
	 @rFormNo int ,
	 @rCastCategoryId int=0,
	 @rDataEntryStatusId smallint=0,
	 @rConvertStatusId smallint=0
	 --@rTitle nvarchar(100),
	 --@rStatusId smallint
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT AF.Id,
		AFS.AdmissionFormId,
		AF.FormNo,
		AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		AF.ContactNo,
		AF.ContactEmail,
		ISNULL(AF.MeritMarks,0) AS MeritMarks,
		AF.MeritGrade,
		CM.DisplayTitle AS ClassName,
		AFS.DiscussionDate AS DiscussionDate,
		CCM.Title AS CasteCategory,
		SM.Title AS DataEntryStatus
    FROM sAdmission.tAdmissionForm AF 
		Left JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId 
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=AF.CastCategoryId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=AF.DataEntryStatusId
	WHERE  
		((AF.FirstName like '%'+@rFirstName+'%') OR ISNULL(@rFirstName,'') = '')
		AND ((AF.LastName like'%'+ @rLastName+'%') OR ISNULL(@rLastName,'') = '')
		AND((AF.ForClassId IN(@rClassId)) OR (@rClassId=0))
		--AND(ISNULL(AF.ForClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId='')
		AND((AF.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((AF.OrgId=@rOrgId) OR (@rOrgId=0))
		AND((AF.MeritMarks >=@rMinMeritMarks) OR(@rMinMeritMarks =0.00))
		AND((AF.MeritMarks <=@rMaxMeritMarks) OR(@rMaxMeritMarks =0.00))
		AND((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND((AF.CastCategoryId=@rCastCategoryId) OR (@rCastCategoryId=0))
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
		AND ((CASE WHEN (AF.StudentId IS NOT NULL) THEN 1 ELSE 2 END) =  @rConvertStatusId OR (@rConvertStatusId = 0))
		ORDER BY AF.ForClassId , AF.FormNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAdmission].[pStudentCustomFieldAdd]
		 
	@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	
 
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sStudent.tStudentCustomFieldMaster
	(
		Id
		,FieldTitle
		,FieldTypeId
		,FieldList
		,IsFieldMandatory
		,FieldGroup
		,FieldOrder
	)
	VALUES
	(
		@lNextNumber
		
		,@rFieldTitle
		,@rFieldTypeId
		,@rFieldList
		,@rIsFieldMandatory
		,@rFieldGroup
		,@rFieldOrder
	)
END	 
ELSE
BEGIN
	SET @lNextNumber = @rId
	
	UPDATE sStudent.tStudentCustomFieldMaster
	SET 
		FieldTitle = @rFieldTitle
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
	WHERE Id = @rId 	   
END  
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAdmission].[pValidateImportAdmissionForm]
    @rOrgId smallint,
	@rBatchId int,
	@rOrgGroupId int,
	@rXmldoc [nvarchar](max)


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,@lCode nvarchar(20),
		@lFormNo int,@lStudentName nvarchar(100),@lSurName nvarchar(100),@lForClass nvarchar(100),@lDateOfBirth nvarchar(max) = '' ,
        @lGender nvarchar(100),@lReligion nvarchar(100),@lCastCategory nvarchar(20),@lSetClass nvarchar(max)='',@lDuplicateFormNo  nvarchar(max) = '' ,
		@lHostelRequired nvarchar(20) ,@lTransportRequired nvarchar(20),@1ExistFormNo nvarchar(MAX)='',
		@lCastCategoryId int=0,@1ValidDOB nvarchar(max) = '' ,@lSETReligion nvarchar(max)='',@lSETCastCategory nvarchar(MAX)='',@lContactNo nvarchar(20)=''
		,@lFatherContactNo nvarchar(20)='',@lMotherContactNo nvarchar(20)='' --mantis: 0041560
		,@lPENNumber nvarchar(100)='',
		@1ExistPENNumber nvarchar(max) = '',
		@1DuplicatePENNumber nvarchar(max) = '',
		@lDuplicatePENNumber nvarchar(max) = '',
		@lApaarIdNumber nvarchar(50) = '',            
		@1ExistApaarIdNumber nvarchar(max) = '',
		@1DuplicateApaarIdNumber nvarchar(max) = ''
		,@lDuplicateApaarIdNumber nvarchar(max) = ''

			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
--mantis: 0041560 : Krunal Patel Added valdiation ContactNoDigit
DECLARE @lConfigValueAdmissionContactNoDigitVal nvarchar(50)=''
DECLARE @lPENNumberActive nvarchar(50)='' 
DECLARE @lApaarIdNumberActive nvarchar(50)=''
DECLARE @lIsActivateUniquePENNumber bit = 0 
DECLARE @lIsActivateUniqueApaarIdNumber bit = 0 

SELECT @lConfigValueAdmissionContactNoDigitVal = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 599 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
--add for mantis : 0043425
SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId 
SELECT @lApaarIdNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 587 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
 
	IF (ISNULL(@lPENNumberActive, '') = '') OR (@lPENNumberActive = 'False')
		SET @lIsActivateUniquePENNumber = 0
	ELSE
		SET @lIsActivateUniquePENNumber = 1	

	IF (ISNULL(@lApaarIdNumberActive, '') = '') OR (@lApaarIdNumberActive = 'False')
		SET @lIsActivateUniqueApaarIdNumber = 0
	ELSE
		SET @lIsActivateUniqueApaarIdNumber = 1	
 --add for mantis : 0043425
	CREATE TABLE #tTable  
	(
		Id bigint identity,
		FormNo int,
		ForClass nvarchar(100),
		StudentName nvarchar(100), 
		SurName nvarchar(100),
		DateOfBirth date ,
	    Gender nvarchar(100), 
	    Religion nvarchar(100), 
	    CastCategory nvarchar(100),
	    HostelRequired nvarchar(20), 
	    TransportRequired nvarchar(20),
		ContactNo nvarchar(20), --mantis: 0041560  FatherContactNo ,MotherContactNo             
        FatherContactNo nvarchar(20), 
        MotherContactNo nvarchar(20) 
		,PENNumber nvarchar(100) --add for mantis : 0043425
		,ApaarIdNumber nvarchar(50) --add for mantis : 0043425
	)
	INSERT INTO #tTable
	(   FormNo,ForClass,StudentName,SurName,DateOfBirth, Gender, 
	    Religion,CastCategory,HostelRequired,TransportRequired,ContactNo,FatherContactNo,MotherContactNo  --mantis: 0041560
		,PENNumber,ApaarIdNumber --add for mantis : 0043425
	)
	SELECT
		FormNo,ForClass,StudentName,SurName,DateOfBirth, Gender, 
	    Religion,CastCategory,HostelRequired,TransportRequired,ContactNo,FatherContactNo,MotherContactNo   --mantis: 0041560
		,PENNumber,ApaarIdNumber --add for mantis : 0043425
	FROM OPENXML (@intDoc, '/Table/ImportAdmissionForm', 1)
	WITH
	( 	
	    FormNo int  '@FormNo',
		ForClass nvarchar(100) '@ForClass',
		StudentName nvarchar(100) '@StudentName', 
		SurName nvarchar(100) '@SurName',
		DateOfBirth date  '@DateOfBirth',
	    Gender nvarchar(100) '@Gender', 
	    Religion nvarchar(100) '@Religion',
	    CastCategory nvarchar(100) '@CastCategory',
	    HostelRequired nvarchar(20) '@HostelRequired', 
	    TransportRequired nvarchar(20) '@TransportRequired',
		ContactNo nvarchar(20) '@ContactNo', --mantis: 0041560
        FatherContactNo nvarchar(20) '@FatherContactNo', --mantis: 0041560
        MotherContactNo nvarchar(20) '@MotherContactNo' --mantis: 0041560
		,PENNumber nvarchar(100) '@PENNumber'
		,ApaarIdNumber nvarchar(50) '@ApaarIdNumber'
	    )

EXEC sp_xml_removedocument @intDoc


   IF EXISTS(SELECT 1 fROM #tTable WHERE FormNo=null OR FormNo ='')
BEGIN
	SELECT 'FormNo Should not be empty' AS FormNo
END
 ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE ForClass IS NULL OR ForClass COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'ForClass Should not be empty' AS ForClass
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE StudentName IS NULL OR StudentName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'StudentName Should not be empty' AS StudentName
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE SurName IS NULL OR SurName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'SurName Should not be empty' AS SurName
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE DateOfBirth IS NULL OR DateOfBirth ='' )
BEGIN
	SELECT 'DateOfBirth Should not be empty' AS DateOfBirth
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE Gender IS NULL OR Gender COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Gender Should not be empty' AS Gender
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE HostelRequired IS NULL OR HostelRequired COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'HostelRequired Should not be empty' AS HostelRequired
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE TransportRequired IS NULL OR TransportRequired COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'TransportRequired Should not be empty' AS TransportRequired
END
ELSE
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 
BEGIN	
  SELECT @lFormNo = FormNo,
  @lForClass=ForClass,@lReligion=Religion,@lGender=Gender,@lCastCategory=CastCategory,@lHostelRequired=HostelRequired,
  @lTransportRequired=TransportRequired,@lContactNo=ContactNo,@lFatherContactNo=FatherContactNo,
  @lMotherContactNo=MotherContactNo
  ,@lPENNumber = PENNumber,@lApaarIdNumber = ApaarIdNumber --add for mantis : 0043425
FROM #tTable WHERE Id = @lCount 
IF NOT EXISTS(SELECT  1 FROM sSetup.tClassMaster WHERE OrgId=@rOrgId AND Title=@lForClass)
	BEGIN
 SET @lSetClass=@lSetClass+',' + @lForClass
	END		
 ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender NOT IN('Male','Female'))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS gender
			RETURN
		END
 ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE HostelRequired COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND HostelRequired NOT IN('Yes','NO'))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Hostel ( Yes / No )' AS Hostel
			RETURN
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE TransportRequired COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND TransportRequired NOT IN('Yes','NO'))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Transport ( Yes / No )' AS Transport
			RETURN
	END
	--mantis: 0041560 : Krunal Patel Added valdiation ContactNoDigit
	IF(@lConfigValueAdmissionContactNoDigitVal is not null OR @lConfigValueAdmissionContactNoDigitVal !='') --mantis: 0041560
        BEGIN                
            IF(@lContactNo != '' AND LEN(@lContactNo) > 0)
            BEGIN  
					declare @lContactNotmp nvarchar(20) 
                    set @lContactNotmp = LEN(@lContactNo)
					IF(@lContactNotmp != @lConfigValueAdmissionContactNoDigitVal)
                    BEGIN 
                            SELECT 'Contact No should be atleast of '+ @lConfigValueAdmissionContactNoDigitVal +' digits' AS StudentCode
                            RETURN
                    END
            END        
   END     
   IF(@lConfigValueAdmissionContactNoDigitVal is not null OR @lConfigValueAdmissionContactNoDigitVal !='') 
    BEGIN               
            IF(@lFatherContactNo != '' AND LEN(@lFatherContactNo) > 0)
            BEGIN  
                    declare @lFatherContactNotmp nvarchar(20)
                    set @lFatherContactNotmp = LEN(@lFatherContactNo)
                    IF(@lFatherContactNotmp != @lConfigValueAdmissionContactNoDigitVal)
                    BEGIN
                            SELECT 'Father Contact No should be atleast of '+ @lConfigValueAdmissionContactNoDigitVal +' digits' AS StudentCode
                            RETURN
                    END                
            END            
   END    

   IF(@lConfigValueAdmissionContactNoDigitVal is not null OR @lConfigValueAdmissionContactNoDigitVal !='') --mantis: 0041560
    BEGIN           
            IF(@lMotherContactNo != '' AND LEN(@lMotherContactNo) > 0)
            BEGIN  
                                        declare @lMotherContactNotmp nvarchar(20)
                    set @lMotherContactNotmp = LEN(@lMotherContactNo)
                    IF(@lMotherContactNotmp != @lConfigValueAdmissionContactNoDigitVal)
                    BEGIN
                            SELECT 'Mother Contact No should be atleast of '+ @lConfigValueAdmissionContactNoDigitVal +' digits' AS StudentCode
                   RETURN
                    END
            END
   END

   
    --End Code :   mantis: 0041560 : Krunal Patel Added valdiation ContactNoDigit
	IF (@lIsActivateUniquePENNumber = 1 AND @lPENNumber != '')
	BEGIN
		IF (ISNUMERIC(@lPENNumber) = 0)
		BEGIN
			SELECT 'PENNumber must be numeric' AS PENNumberErrorMessage;
			RETURN;
		END
		IF (LEN(@lPENNumber) > 12)
		BEGIN
			SELECT 'PENNumber ID Number must be  12 digits' AS ErrorMessage
			RETURN
		END
	END
	IF (@lIsActivateUniqueApaarIdNumber = 1 AND LEN(@lApaarIdNumber) > 0)
	BEGIN
		IF ISNUMERIC(@lApaarIdNumber) = 0
		BEGIN
			SELECT 'Apaar ID Number must be numeric' AS ApaarIdNumberErrorMessage
			RETURN
		END
		IF LEN(@lApaarIdNumber) != 12
		BEGIN
			SELECT 'Apaar ID Number must be exactly 12 digits' AS ErrorMessage
			RETURN
		END
	END
   
	IF(@lReligion!='' OR @lReligion!=null )
	BEGIN
	IF NOT EXISTS(SELECT 1 FROM sCommon.tReligionMaster WHERE  OrgGroupId=@rOrgGroupId AND IsObsolete=0 AND Title=@lReligion)
	BEGIN
	SET @lSETReligion=@lSETReligion++','+@lReligion 
	END
	END
	IF(@lCastCategory!='' OR @lCastCategory!=null )
	BEGIN
	IF NOt EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE  OrgGroupId=@rOrgGroupId AND IsObsolete=0 AND Title=@lCastCategory )
	BEGIN
	SET @lSETCastCategory=@lSETCastCategory+@lCastCategory  +','
	END
	END
	IF ((@lDateOfBirth) IS NOT NULL AND @lDateOfBirth != '')
		BEGIN
			SET @lDateOfBirth = 'Wrong DOB ' + @lDateOfBirth
		END
	IF Exists ((select 1 from sAdmission.tAdmissionForm where BatchId=@rBatchId AND FormNo=  @lFormNo  ))               
    BEGIN
		SET @1ExistFormNo =@1ExistFormNo+ convert(varchar,@lFormNo )+ ','
    END	
	
	--IF (@lIsActivateUniquePENNumber = 1)
	--BEGIN
	--	IF(convert(bigint,@lPENNumber) > 0)
	--	BEGIN 		
	--		 IF Exists ((select 1 from sAdmission.tAdmissionForm AF INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =AF.OrgId 
	--			where AF.PENNumber = convert(bigint,@lPENNumber)
	--		)) 		
	--		BEGIN
 -- 				SET @1ExistPENNumber = @1ExistPENNumber + CAST(@lPENNumber AS NVARCHAR(200)) + ','
	--		END	       
	--	END
	--END
	--IF(@lIsActivateUniqueApaarIdNumber=1)
 --   BEGIN
	--	IF(convert(bigint,@lApaarIdNumber) > 0)
	--	BEGIN 		
	--		 IF Exists ((select 1 from sAdmission.tAdmissionForm AF INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =AF.OrgId 
	--			where AF.ApaarIdNumber = @lApaarIdNumber
	--		)) 		
	--		BEGIN
 -- 				SET @1ExistApaarIdNumber = @1ExistApaarIdNumber + CAST(@lApaarIdNumber AS NVARCHAR(200)) + ','
	--		END	       
	--	END
	--END

  SET @lCount = @lCount - 1	
END

SELECT @lDuplicateFormNo=COALESCE(@lDuplicateFormNo ,'') + convert(varchar,FormNo) + ',' FROM #tTable GROUP BY FormNo HAVING ( COUNT(FormNo) > 1 )	

--SELECT  @lDuplicatePENNumber = COALESCE(@lDuplicatePENNumber, '') + PENNumber + ',' FROM #tTable GROUP BY PENNumber HAVING COUNT(*) > 1

 IF(@lDuplicateFormNo IS NOT NULL AND @lDuplicateFormNo != '')
	BEGIN
		SET @lDuplicateFormNo = 'Duplicate Form No : ' + convert(varchar,@lDuplicateFormNo)
	END
	--add for mantis : 0043425
	IF @lIsActivateUniqueApaarIdNumber = 1
	BEGIN
		SELECT  @lDuplicateApaarIdNumber = COALESCE(@lDuplicateApaarIdNumber, '') + ApaarIdNumber + ',' FROM #tTable GROUP BY ApaarIdNumber HAVING COUNT(ApaarIdNumber) > 1
		IF (@lDuplicateApaarIdNumber =',')
		BEGIN
			SET @lDuplicateApaarIdNumber =''
		END
		IF @lDuplicateApaarIdNumber IS NOT NULL AND @lDuplicateApaarIdNumber <> '' 
		BEGIN
			SET @lDuplicateApaarIdNumber = 'Duplicate Apaar Id Number : ' + @lDuplicateApaarIdNumber;
		END
	END
	
	IF @lIsActivateUniquePENNumber = 1
	BEGIN
		SELECT  @lDuplicatePENNumber = COALESCE(@lDuplicatePENNumber, '') + PENNumber + ',' FROM #tTable GROUP BY PENNumber HAVING COUNT(*) > 1
		IF (@lDuplicatePENNumber =',')
		BEGIN
			SET @lDuplicatePENNumber =''
		END
		IF @lDuplicatePENNumber IS NOT NULL AND @lDuplicatePENNumber <> ''
		BEGIN
			SET @lDuplicatePENNumber = 'Duplicate PEN Number : ' +convert(varchar,@lDuplicatePENNumber);
		END
	END
	--add for mantis : 0043425
   If(@1ExistFormNo!='' AND @1ExistFormNo IS NOT NULL)

   BEGIN

   SET @1ExistFormNo=' Already Exists  Form No: ' +@1ExistFormNo
   END
    If(@lSetClass!='' AND @lSetClass IS NOT NULL)
   BEGIN
   SET @lSetClass=' Enter proper value for Class as per Institute Setup > Class Master  :' +@lSetClass
   END
    If(@lSETReligion!='' AND @lSETReligion IS NOT NULL)
   BEGIN
   SET @lSETReligion= ' Enter proper value / Check spelling for Religion :'  +@lSETReligion
   END
      If(@lSETCastCategory!='' AND @lSETCastCategory IS NOT NULL)
   BEGIN
   SET @lSETCastCategory= 'Enter proper value / Check spelling for CastCategory :'  +@lSETCastCategory
   END
	 ----   IF (@lIsActivateUniquePENNumber = 1)
		----BEGIN
	 --  If(@1ExistPENNumber!='' AND @1ExistPENNumber IS NOT NULL)
	 --  BEGIN
	 --  SET @1ExistPENNumber=' Already Exists  PEN Number: ' +@1ExistPENNumber
	 --  END
	 --  --END
	 --  --IF(@lIsActivateUniqueApaarIdNumber=1)
	 --  --BEGIN
	 --  If(@1ExistApaarIdNumber!='' AND @1ExistApaarIdNumber IS NOT NULL)
	 --  BEGIN
	 --  SET @1ExistApaarIdNumber=' Already Exists  ApaarIdNumber: ' +@1ExistApaarIdNumber
	 --  END
	 --  --END
   
	SELECT	@lDuplicateFormNo+Isnull(@lSetClass,'')+ISNULL(@lSETCastCategory,'')+ISNULL(@lSETReligion,'')+ISNULL(@lDateOfBirth,'')+ISNULL(@1ExistFormNo,'')
	--+ ISNULL(@1ExistPENNumber,'') + ISNULL(@1ExistApaarIdNumber,'') 
	+ @lDuplicateApaarIdNumber+Isnull(@lSetClass,'') + @lDuplicatePENNumber+Isnull(@lSetClass,'')
END
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAbsentEmployeeGet]

	 	 @rFromDate date='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0,
		 @rIsPresent bit,
		 @rMailSubject nvarchar(500)='',
		 @rTemplate nvarchar(max),
		 @rSourceId bigint=0,
		 @rEmployeeIds nvarchar(max) = ''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Select
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			Convert(Varchar,EAR.AttendanceDate,105) AS AttendanceDate,
			CASE WHEN @rIsPresent=0 THEN										
			replace(replace(replace(@rTemplate,'[Name]',EC.EmployeeName),		
			'[AbsentReason]',IsNULL(LR.Title,'')),
			'[AbsentDates]',Convert(Varchar,EAR.AttendanceDate,105))	
			ELSE
			replace(replace(replace(@rTemplate,'[Name]',EC.EmployeeName),
			'[PresentDates]',Convert(Varchar,EAR.AttendanceDate,105)),
			'[Department]',EC.DepartmentName)										
			END
			AS MsgText,
			@rMailSubject AS Subject,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.OrgId,
			OM.OrgGroupId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.DepartmentName,
			EAR.AttendanceDate AS AbsentDates,
			ISNULL(LR.Title,'') AS AbsentReason,
			EAR.AttendanceDate AS PresentDates,
			EC.WhatsAppContactNo

	From
		sHrm.vEmployeeCommunication EC
	INNER JOIN sHrm.tEmployeeAttendanceRegister EAR  ON EAR.EmployeeId = EC.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
	LEFT JOIN sHrm.tLeaveReasonMaster LR ON EAR.AbsentReasonId = LR.Id

	WHERE
		(EC.OrgId=@rOrgId)
		AND (ISNULL(EC.EmployeeId,0) IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rEmployeeIds,','))OR ISNULL(@rEmployeeIds,'')='')
		AND (EAR.BatchId=@rBatchId)
		AND (EC.StatusId=7)
		AND ((EAR.AttendanceDate = @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND (EAR.IsPresent = @rIsPresent)
		AND EC.IsOtherUser=0 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

CREATE TABLE #tmpData
(
AcademicId bigint,
Code nvarchar(20),
Name nvarchar(300),
MobileNo nvarchar(50),
EmailId nvarchar(50),
StudentContactNo nvarchar(50),
StudentEmail nvarchar(50),
FatherContactNo nvarchar(50),
FatherMail nvarchar(50),
MotherContactNo nvarchar(50),
MotherMail nvarchar(50),
MsgText nvarchar(max),
Subject nvarchar(max),
SourceId bigint,
SourceTypeId int,
OrgId int,
OrgGroupId int,
ReceiverSourceId bigint,
ReceiverSourceTypeId int,
Class nvarchar(100),
Division nvarchar(100),
AbsentDates date,
AbsentReason nvarchar(100),
PresentDates date,
WhatsAppContactNo nvarchar(20),
ConsecDates date
)

INSERT INTO #tmpData
Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			--CASE WHEN 0=0 THEN
			--replace (replace (
			--replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			--'[Class]',SC.ClassName),
			--'[Division]',SC.DivisionName),
			--'[AbsentDates]',SR.AttendanceDate),
			--'[AbsentReason]',ISNULL(AR.Title,''))
			--ELSE
			--replace (
			--replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			--'[Class]',SC.ClassName),
			--'[Division]',SC.DivisionName),
			--'[PresentDates]',SR.AttendanceDate)
			--END
			-- AS MsgText,
			'' AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			SR.AttendanceDate AS AbsentDates,
			ISNULL(AR.Title,'') AS AbsentReason,
			SR.AttendanceDate AS PresentDates,
			SC.WhatsAppContactNo,
			 (
            select min(b.AttendanceDate) from sAttendance.tStudentRegister b where SR.AcademicId = b.AcademicId 
            and b.AttendanceDate >= SR.AttendanceDate
            and not exists ( 
                select 1 from sAttendance.tStudentRegister c where c.AcademicId = b.AcademicId and dateadd( dd, 1, b.AttendanceDate) = c.AttendanceDate  
            )
            ) ConsecDates

	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
			
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
   ORDER BY SR.AcademicId,SR.AttendanceDate asc
   --Select * from #tmpData ORDER BY AcademicId

--Select * from #tmpData

CREATE TABLE #tmp
(
AcademicId bigint ,
ConsecDates date ,
AbsentDays nvarchar(max),
FullAbsentDate nvarchar(max)
)
INSERT INTO #tmp
SELECT AcademicId,ConsecDates,
isnull(STUFF((SELECT ',' + CONVERT(nvarchar,DATEPART(day,d.AbsentDates)) from #tmpData d  
WHERE d.AcademicId=a.AcademicId AND d.ConsecDates = a.ConsecDates FOR XML PATH('')), 1, 1, ''),''),
/**Added new field  for mantis : 29178**/
isnull(STUFF((SELECT ', ' + CONVERT(nvarchar, d.AbsentDates,103) from #tmpData d  
WHERE d.AcademicId=a.AcademicId AND d.ConsecDates = a.ConsecDates FOR XML PATH('')), 1, 1, ''),'')
FROM #tmpData a

CREATE TABLE #Finaltmp
(
AcademicId bigint ,
ConsecDates date ,
AbsentDays nvarchar(max),
FullAbsentDate nvarchar(max)
)
INSERT INTO #Finaltmp
Select * from #tmp GROUP BY AcademicId,ConsecDates,AbsentDays,FullAbsentDate having COUNT(ConsecDates) >= @rDays
ORDER BY AcademicId,ConsecDates asc



ALTER TABLE #tmpData
DROP COLUMN AbsentDates,
 AbsentReason,
PresentDates;

--Select * from #Finaltmp
--Select * from #tmpData
Select Distinct
			tmp.AcademicId,
			tmp.Code,
			tmp.Name,
			tmp.MobileNo,	
			tmp.EmailId,
			tmp.StudentContactNo,
			tmp.StudentEmail,
			tmp.FatherContactNo,
			tmp.FatherMail,
			tmp.MotherContactNo,
			tmp.MotherMail,
			CASE WHEN 0=0 THEN
			
			replace(replace(replace(replace(replace(@rTemplate,'[Name]',tmp.Name),
			'[Class]',tmp.Class),
			'[Division]',tmp.Division),
			'[AbsentDates]',isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')),
			'[FullAbsentDate]',isnull(STUFF((SELECT ',' + f.FullAbsentDate from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')) --Added new field  for mantis : 29178
			
			--'[AbsentDates]',SR.AttendanceDate),
			--'[AbsentReason]',ISNULL(AR.Title,''))
			ELSE
			replace(replace (replace(
			replace(replace(@rTemplate,'[Name]',tmp.Name),
			'[Class]',tmp.Class),
			'[Division]',tmp.Division),
			'[AbsentDates]',isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')),
			'[FullAbsentDate]',isnull(STUFF((SELECT ',' + f.FullAbsentDate from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'') --Added new field  for mantis : 29178
			)
			--'[PresentDates]',SR.AttendanceDate)
			END
			 AS MsgText,
			tmp.Subject,
			tmp.SourceId,
			tmp.SourceTypeId,
			tmp.OrgId,
			tmp.OrgGroupId,
			tmp.ReceiverSourceId,
			tmp.ReceiverSourceTypeId,
			tmp.Class,
			tmp.Division,
			--tmp.AbsentDates,
			--tmp.AbsentReason,
			--tmp.PresentDates,
			tmp.WhatsAppContactNo,
			--finaltmp.ConsecDates,
			--finaltmp.AbsentDays
			isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')AS AbsentDays,
			isnull(STUFF((SELECT ',' + f.FullAbsentDate from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')AS FullAbsentDate --Added new field  for mantis : 29178


	From 
		#tmpData tmp
	INNER JOIN #Finaltmp finaltmp ON tmp.AcademicId = finaltmp.AcademicId AND tmp.ConsecDates =finaltmp.ConsecDates
	
DROP TABLE #tmpData
DROP TABLE #tmp
DROP TABLE #Finaltmp
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAbsentStudentGet]

	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rIsPresent bit,
	 	 @rMailSubject nvarchar(500)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--SET @rToDate = dateadd(d,1,@rToDate)

	Select
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			CASE WHEN @rIsPresent=0 THEN
			replace (replace (replace (						--add replace
			replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[AbsentDates]',Convert(Varchar,SR.AttendanceDate,105)),	--add convert
			'[AbsentReason]',ISNULL(AR.Title,'')),
			'[RollNo]',ISNULL(SC.RollNo,0))								--add
			ELSE
			replace(replace(											--add replace
			replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[PresentDates]',Convert(Varchar,SR.AttendanceDate,105)),	--add Convert
			'[RollNo]',ISNULL(SC.RollNo,0))								--add
			END
			 AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			SR.AttendanceDate AS AbsentDates,
			ISNULL(AR.Title,'') AS AbsentReason,
			SR.AttendanceDate AS PresentDates,
			SC.WhatsAppContactNo

	From
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id

	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
   ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAbsentStudentSchedulerGet]
	 	 
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rIsPresent bit,	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lConfigValue int = 0
	IF @rIsPresent=0
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 160 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	ELSE
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 161 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	SELECT 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			AC.AbsentCount,
			AC1.AveragePresence,
			REPLACE
			(REPLACE
			(REPLACE
			(@rTemplate,'[Name]',SC.Name),--Added (+ CONVERT(varchar, CONVERT(datetime, sCommon.fGetDate()), 103))by dhananjay for mantis : 35730
			'[AbsentCount]',COUNT(SC.AcademicId)),
			'[AveragePresence]', AC1.AveragePresence)
			AS MsgText,
			@rMailSubject AS Subject,
			SC.WhatsAppContactNo
	FROM 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	INNER JOIN
	(
		SELECT SC.AcademicId,COUNT(SC.AcademicId) AS AbsentCount
		FROM sStudent.vStudentCommunication SC
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
		WHERE 
		SC.OrgId=@rOrgId
		AND SC.BatchId=@rBatchId
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND SR.AttendanceTypeId=1 AND SR.IsPresent=0 AND SC.StatusId=1 AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
		GROUP BY SC.AcademicId
    ) AC ON AC.AcademicId = SC.AcademicId
    INNER JOIN 
    (
		SELECT SC.AcademicId, COUNT(SC.AcademicId) AS AbsentCount1, (CONVERT(DECIMAl(5,2),(CONVERT(DECIMAl(5,2),COUNT(SC.AcademicId))*100)/(CONVERT(DECIMAl(5,2),COUNT(SC.AcademicId)+AC.AbsentCount)))) AS AveragePresence FROM sStudent.vStudentCommunication SC
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
		INNER JOIN
		(
			SELECT SC.AcademicId,COUNT(SC.AcademicId) AS AbsentCount
			FROM sStudent.vStudentCommunication SC
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
			WHERE 
			SC.OrgId=@rOrgId
			AND SC.BatchId=@rBatchId
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND SR.AttendanceTypeId=1 AND SR.IsPresent=1 AND SC.StatusId=1 AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
			GROUP BY SC.AcademicId
		) AC ON AC.AcademicId = SC.AcademicId
	    
		WHERE
			SC.OrgId=@rOrgId
			AND SC.BatchId=@rBatchId
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND SR.AttendanceTypeId=1 AND SR.IsPresent=@rIsPresent AND SC.StatusId=1 AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
			GROUP BY 
			SC.AcademicId,
			AC.AbsentCount
    )AC1 ON  AC1.AcademicId = SC.AcademicId
	
	WHERE
		SC.OrgId=@rOrgId
		AND SC.BatchId=@rBatchId AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND SR.AttendanceTypeId=1 AND SR.IsPresent=@rIsPresent AND SC.StatusId=1
		AND (((@rIsPresent = 0) AND @lConfigValue!=0 AND @lConfigValue <= AC.AbsentCount)
        OR ((@rIsPresent = 1) AND @lConfigValue!=0 AND @lConfigValue >= AC1.AveragePresence))
		GROUP BY 
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo,	
		SC.ParentEmail,
		AC.AbsentCount,
		AC1.AbsentCount1,
		SC.DivisionOrderIndex,
		SC.RollNo,
		AC1.AveragePresence,
		SC.WhatsAppContactNo
	ORDER BY SC.DivisionOrderIndex,SC.RollNo 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

--SET @rToDate = dateadd(d,1,@rToDate)
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			CASE WHEN @rIsPresent=0 THEN
			replace (replace (
			replace(replace(replace(replace(replace(@rTemplate,'[Name]',SC.Name),--Added (+ CONVERT(varchar, CONVERT(datetime, sCommon.fGetDate()), 103))by dhananjay for mantis : 35730
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[AbsentDates]',SR.AttendanceDate),
			'[AbsentReason]',ISNULL(AR.Title,'')),
			'[SubjectName]',ISNULL(SM.TItle,'')),
			'[LectureNo]',ISNULL(SR.PeriodNo,''))
			ELSE
			replace (
			replace(replace(replace(replace(replace(@rTemplate,'[Name]',SC.Name),--Added (+ CONVERT(varchar, CONVERT(datetime, sCommon.fGetDate()), 103))by dhananjay for mantis : 35730
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[PresentDates]',SR.AttendanceDate),
			'[SubjectName]',ISNULL(SM.TItle,'')),
			'[LectureNo]',ISNULL(SR.PeriodNo,''))
			END
			 AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			2001 AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			SC.WhatsAppContactNo,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			SR.AttendanceDate AS AbsentDates,
			SR.AttendanceDate AS PresentDates,
			ISNULL(AR.Title,'') AS AbsentReason,
			ISNULL(SM.TItle,'') AS SubjectName,
			ISNULL(SR.PeriodNo,'') AS LectureNo
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sSetup.tSubjectMaster SM on SM.Id=SR.SubjectId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
	 	
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND ((SR.PeriodNo=@rPeriodNo) OR (@rPeriodNo=0))
		AND (ISNULL(SC.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR ISNULL(@rDivisionIds,'')='')
		AND (SR.AttendanceGroupId = @rAttendanceGroupId OR ISNULL(@rAttendanceGroupId,0) = 0)			-- Mantis Id : 0041707
   ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pAddressBookGet]
	 	 
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rContactTypeId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			CM.Id AS AcademicId,
			'' AS Code,
			'' AS Name,
			CM.PhoneNumberOffice AS MobileNo,	
			CM.Email AS EmailId,
			@rTemplate AS Template,
			CM.PhoneNumberOffice AS WhatsAppContactNo
		
		
	From 
		sSupport.tContactMaster CM
		
	WHERE
			(CM.OrgId=@rOrgId)
		AND ((CM.ContactTypeId=@rContactTypeId) OR (@rContactTypeId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pAdmissionFormReceiptEntryGet]
	 	 
	 	 @rAdmissionFormId bigint,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			AF.FirstName +' '+AF.MiddleName+ ' ' +AF.LastName AS Name,
			AF.ContactNo AS MobileNo,
			AF.ContactEmail AS EmailId,
			@rSubject AS Subject,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',AF.FirstName +' '+AF.MiddleName+ ' ' +AF.LastName),
			'[Organization]',OM.DisplayTitle),
			'[Batch]',BM.Title),
			'[Class]',CM.Title),
			'[ReceiptNumber]',AFR.ReceiptNumber),
			'[ReceiptDate]',AFR.ReceiptDate),
			'[PaidAmount]',convert(int,AFR.ReceiptAmount))
			 AS MsgText,
			 0 AS ReceiverSourceTypeId,
			 0 AS ReceiverSourceId,
			 OM.DisplayTitle AS Organization,
			 BM.Title AS Batch,
			 CM.Title AS Class,
			 AFR.ReceiptNumber AS ReceiptNumber,
			 AFR.ReceiptDate AS ReceiptDate,
			 convert(int,AFR.ReceiptAmount) AS PaidAmount,
			 AF.ContactNo AS WhatsAppContactNo
	FROM 
		sAdmission.tAdmissionForm AF
		INNER JOIN sAdmission.tAdmissionFormReceipt AFR ON AF.Id = AFR.SourceId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId 
	WHERE
		AFR.Id = @rAdmissionFormId
		AND AF.BatchId = @rBatchId
		AND AF.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAdmissionGet]
	
	@rAdmissionFormId bigint,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		AF.Id AS AdmissionFormId,
		AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		AF.ContactNo AS MobileNo,	
		AF.ContactEmail AS EmailId,
		REPLACE (
	    REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',AF.FirstName+' '+AF.MiddleName+' '+AF.LastName),
		'[Organization]',ISNULL(OM.DisplayTitle,'')),
		'[ForClass]',ISNULL(CM.Title,'')),
		'[AdmissionFormNo]', ISNULL(AF.FormNo,0))
		AS MsgText,
		@rSubject AS [Subject],
		0 AS ReceiverSourceTypeId,
		0 AS ReceiverSourceId,
		ISNULL(OM.DisplayTitle,'') AS Organization,
		ISNULL(CM.Title,'') AS ForClass,
		AF.ContactNo AS WhatsAppContactNo
	FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
	WHERE	
		AF.Id = @rAdmissionFormId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAdmissionInquiryFollowupGet]
	
	 @rFromDate date='',
	 @rToDate date='',
	 @rOrgId Smallint=0,
	 @rBatchId int = 0,
     @rTemplate nvarchar(max),
	 @rSubject nvarchar(100)=''	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT  
	AF.Id,
	AI.ForBatchId AS BatchId,
	AI.ForClassId AS ClassId,
	AI.OrgId AS OrgId,
	AI.OrgId AS OrgGroupId,
	AI.Number AS InquiryNumber,
	ISNULL(AF.FollowupDate,'') AS  FollowupDate,
	AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,
	AI.ContactNo AS MobileNo,
	AI.ContactEmail AS EmailId
	,REPLACE (
	 REPLACE (
	 REPLACE (
	 REPLACE(@rTemplate,'[Name]',AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName),
	 '[Organization]',ISNULL(OM.DisplayTitle,'')),
	 '[InquiryNumber]', ISNULL(AI.Number,0)),
	 '[FollowupDate]', CONVERT(VARCHAR(10), AF.FollowupDate, 103))
	  AS Template
	 ,@rSubject AS Subject
	 ,AI.ContactNo AS MobileNo
	 ,AI.ContactNo AS WhatsAppContactNo
	 ,AI.ContactEmail AS EmailId
	 ,ISNULL(AF.Id,0) AS SourceId
	 ,CONVERT(smallint,0) AS SourceTypeId
	 ,ISNULL(AF.Id,0) AS ReceiverSourceId
	 ,CONVERT(smallint,0) AS ReceiverSourceTypeId
	
  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  ((AI.OrgId=@rOrgId) OR (@rOrgId=0))
      AND ((AF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	  AND ((AF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
      AND (AI.ForBatchId=@rBatchId)
	  Order by AF.FollowupDate DESC 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAdmissionInquiryGet]
	
	@rAdmissionInquiryId bigint,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		AI.Id AS AdmissionInquiryId,
		AI.FirstName+' '+AI.MiddleName+' '+AI.LastName AS Name,
		AI.ContactNo AS MobileNo,	
		AI.ContactEmail AS EmailId,
		REPLACE(
		REPLACE (
		REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',AI.FirstName+' '+AI.MiddleName+' '+AI.LastName),
		'[Organization]',ISNULL(OM.DisplayTitle,'')),
		'[ForClass]',ISNULL(CM.Title,'')),
		'[InquiryFormNo]', ISNULL(AI.Number,'')),
		'[InquiryDate]', ISNULL(AI.InquiryDate,NULL)) --Added for mantis : 39907
		AS MsgText,
		@rSubject AS [Subject],
		0 AS ReceiverSourceTypeId,
		0 AS ReceiverSourceId,
		ISNULL(OM.DisplayTitle,'') AS Organization,
		ISNULL(CM.Title,'') AS ForClass,
		AI.WhatsAppContactNo AS WhatsAppContactNo,
		AI.OrgId,
		OM.OrgGroupId,
		CONVERT(bigint,0) AS SourceId,
		CONVERT(smallint,0) AS SourceTypeId
	FROM sAdmission.tAdmissionInquiry AI 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AI.OrgId
	WHERE	
		AI.Id = @rAdmissionInquiryId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pAdmissionStatusGet]
	
	@rAdmissionFormId bigint,
	@rBatchId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		AF.Id AS AdmissionFormId,
		AF.FormNo,
		AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		AF.ContactNo AS MobileNo,	
		AF.ContactEmail AS EmailId,
	    REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',AF.FirstName+' '+AF.MiddleName+' '+AF.LastName),
		'[AdmissionStatus]',ISNULL(ASM.Title,'')),
		'[ForClass]',ISNULL(CM.Title,''))
		AS MsgText,
		@rSubject AS [Subject],
		0 AS ReceiverSourceTypeId,
		0 AS ReceiverSourceId,
		ISNULL(ASM.Title,'') AS AdmissionStatus,
		ISNULL(CM.Title,'') AS ForClass,
		AF.ContactNo AS WhatsAppContactNo

	FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId 
	WHERE	
		AF.Id = @rAdmissionFormId AND AF.BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAdVendorMasterAdd]
	 
        @rId int,
        @rCode nvarchar(100),
        @rTitle nvarchar(100),
        @rAdBanner varbinary(max)=NULL,
        @rAdUrl nvarchar(100),
        @rOrgGroupId smallint,
        @rIsObsolete bit,
        @rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT 1 FROM sAlert.tAdVendorMaster WHERE Code=@rCode AND OrgGroupId=@rOrgGroupId)
		BEGIN 
			SELECT -101 AS Result 
			RETURN 
		END 
		IF EXISTS (SELECT 1 FROM sAlert.tAdVendorMaster WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		BEGIN 
			SELECT -102 AS Result 
			RETURN 
		END
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT 1 FROM sAlert.tAdVendorMaster WHERE Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN 
			SELECT -101 AS Result 
			RETURN 
		END
		
		IF EXISTS (SELECT 1 FROM sAlert.tAdVendorMaster WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN 
			SELECT -102 AS Result 
			RETURN 
		END
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber int 

	IF(@rId = 0)	
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAlert.tAdVendorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sAlert.tAdVendorMaster
		(
			Id,
			Code,
			Title,
			AdBanner,
			AdUrl,
			OrgGroupId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rAdBanner,
			@rAdUrl,
			@rOrgGroupId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
	
		SELECT 1 AS Result
	END	 
	ELSE
	BEGIN
		SET @lNextNumber = @rId
		UPDATE sAlert.tAdVendorMaster
		SET 
		    Code=@rCode,
			Title=@rTitle,
			AdBanner=@rAdBanner,
			AdUrl=@rAdUrl,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE Id = @rId AND OrgGroupId= @rOrgGroupId
		SELECT 11 AS Result
	END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAdVendorMasterGet]

	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rOrgGroupId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	SELECT 
			
			AVM.Id,
			AVM.Code,
			AVM.Title,
			ISNULL(AVM.AdBanner, CONVERT(VARBINARY(MAX), 0)) AS AdBanner ,
			AVM.AdUrl,
			AVM.OrgGroupId,
			AVM.IsObsolete
	FROM 
			sAlert.tAdVendorMaster AVM
	WHERE 
		(AVM.OrgGroupId = @rOrgGroupId)
		AND	((AVM.Id = @rId) OR (@rId = 0))
		AND ((AVM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((AVM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertConfigurationAdd]
	@rOrgId smallint,
	@rEventId [smallint],
	@rRecipientTypeId [tinyint],
	@rRecipientId [bigint],
	@rTemplate nvarchar(max),
	@rDuration [smallint],
	@rDurationUnitId [tinyint],
	@rAlertModeId [tinyint],
	@rTriggerId [tinyint],
	@rIsObsolete [bit],
	@rCreatedBy [smallint],
	@rAttachmentTypeId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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


	INSERT INTO sAlert.tAlertConfiguration
		(
			OrgId,
			Id,
			EventId,
			RecipientTypeId,
			RecipientId,
			Template,
			Duration,
			DurationUnitId,
			AlertModeId,
			TriggerId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttachmentTypeId
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rEventId,
			@rRecipientTypeId,
			@rRecipientId,
			@rTemplate,
			@rDuration,
			@rDurationUnitId,
			@rAlertModeId,
			@rTriggerId,
			@rIsObsolete,
			@rCreatedBy,
			sCommon.fGetDate(),
			@rCreatedBy,
			sCommon.fGetDate(),
			@rAttachmentTypeId
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertConfigurationGet]
	@rOrgId int,
	@rId [int] = 0,
	@rModuleId [tinyint] = 0,
	@rEventId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT	AC.Id AS AlertId,
			MM.Id AS ModuleId,
			MM.Title AS ModuleName,
			AC.EventId AS EventId,
			EM.Title AS EventName,
			AC.RecipientTypeId AS RecipientTypeId,
			RTM.Title AS RecipientType,
			AC.RecipientId AS RecipientId,
			(CASE AC.RecipientTypeId
					WHEN 1 THEN
						AR.Title
					WHEN 2 THEN
						R.Title
					WHEN 3 THEN
						EU.EmployeeName
					WHEN 4 THEN
						ER.Title
						
				END) AS Recipient,
			ISNULL(AC.Template,'') AS TemplateName,
			--TM.Title AS Template,
			AC.Duration AS DurationValue,
			AC.DurationUnitId AS DurationFormatId,
			DUM.Title AS DurationFormat,
			AC.AlertModeId AS ModeId,
			AMM.Title AS ModeName,
			AC.TriggerId AS TriggerId,
			TRM.Title AS [Trigger],
			AC.IsObsolete AS IsObsolete,
			AC.AttachmentTypeId,
			ATM.Title AS AttachmentName

	FROM	sAlert.tAlertConfiguration AC
				INNER JOIN sAlert.tEventMaster EM ON
					AC.EventId = EM.Id
				INNER JOIN sCommon.tModuleMaster MM ON
					EM.ModuleId = MM.Id
				INNER JOIN sAlert.tRecipientTypeMaster RTM ON
					AC.RecipientTypeId = RTM.Id
				--INNER JOIN sAlert.tTemplateMaster TM ON
				--	AC.TemplateId = TM.Id
				INNER JOIN sCommon.tDurationUnitMaster DUM ON
					AC.DurationUnitId = DUM.Id
				INNER JOIN sAlert.tAlertModeMaster AMM ON
					AC.AlertModeId = AMM.Id
				INNER JOIN sAlert.tTriggerMaster TRM ON
					AC.TriggerId = TRM.Id
				LEFT JOIN sAlert.tAttachmentTypeMaster ATM ON
					ATM.Id=AC.AttachmentTypeId	
				LEFT OUTER JOIN sAlert.tAlertRoleMaster AR ON
					AC.RecipientId = AR.Id 	AND AC.RecipientTypeId = 1				
				LEFT OUTER JOIN sSecurity.tRole R ON
					AC.RecipientId = R.Id AND AC.RecipientTypeId = 2
				LEFT OUTER JOIN sSecurity.vExtUser EU ON	
					AC.RecipientId = EU.Id AND AC.RecipientTypeId = 3 AND AC.OrgId = EU.OrgId
				LEFT OUTER JOIN sAlert.tExternalRecipientMaster ER ON
					AC.RecipientId = ER.Id AND AC.RecipientTypeId = 4
					
					
	
	WHERE	((AC.Id = @rId) OR (@rId = 0))
			AND ((EM.ModuleId = @rModuleId) OR (@rModuleId = 0))
			AND ((AC.EventId = @rEventId) OR (@rEventId = 0))
			AND AC.OrgId = @rOrgId
		 
			order by AC.Id desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertConfigurationGetByEvent]
	@rOrgId int,
	@rEventId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

		SELECT	sAlert.tAlertConfiguration.Id AS AlertId,
				sAlert.tAlertConfiguration.EventId AS EventId,
				sAlert.tEventMaster.Title AS EventName,
				sAlert.tRecipientTypeMaster.Title AS RecipientType,
				(CASE sAlert.tAlertConfiguration.RecipientTypeId
					WHEN 1 THEN
						sSecurity.tRole.Title
					WHEN 2 THEN
						sSecurity.tRole.Title
					WHEN 3 THEN
						sSecurity.tUser.DisplayTitle
				END) AS Recipient,
				--sAlert.tTemplateMaster.Title AS Template,
				'' AS Template,				 
				sAlert.tAlertConfiguration.Duration AS DurationValue,
				sCommon.tDurationUnitMaster.Title AS DurationFormat,
				sAlert.tAlertModeMaster.Title AS ModeName,
				sAlert.tTriggerMaster.Title AS [Trigger],
				sAlert.tAlertConfiguration.IsObsolete AS IsObsolete
			
		FROM	sAlert.tAlertConfiguration 
				INNER JOIN sAlert.tEventMaster ON
					sAlert.tAlertConfiguration.EventId = sAlert.tEventMaster.Id
				INNER JOIN sAlert.tRecipientTypeMaster ON
					sAlert.tAlertConfiguration.RecipientTypeId = sAlert.tRecipientTypeMaster.Id
				--INNER JOIN sAlert.tTemplateMaster ON
				--	sAlert.tAlertConfiguration.TemplateId = sAlert.tTemplateMaster.Id
				INNER JOIN sCommon.tDurationUnitMaster ON
					sAlert.tAlertConfiguration.DurationUnitId = sCommon.tDurationUnitMaster.Id
				INNER JOIN sAlert.tAlertModeMaster ON
					sAlert.tAlertConfiguration.AlertModeId = sAlert.tAlertModeMaster.Id
				INNER JOIN sAlert.tTriggerMaster ON
					sAlert.tAlertConfiguration.TriggerId = sAlert.tTriggerMaster.Id
				LEFT OUTER JOIN sSecurity.tRole ON
					sAlert.tAlertConfiguration.RecipientId = sSecurity.tRole.Id
				LEFT OUTER JOIN sSecurity.tUser ON	
					sAlert.tAlertConfiguration.RecipientId = sSecurity.tUser.Id
	
		WHERE	sAlert.tAlertConfiguration.IsObsolete = 0
				AND sAlert.tAlertConfiguration.OrgId = @rOrgId
--				sAlert.tAlertConfiguration.EventId = @rEventId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertConfigurationGetTemplateByEvent]
	@rOrgId int,
	@rEventId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

		SELECT	sAlert.tAlertConfiguration.Id AS AlertId,
				sAlert.tAlertConfiguration.EventId AS EventId,
				sAlert.tAlertConfiguration.RecipientTypeId AS RecipientTypeId,
				sAlert.tAlertConfiguration.RecipientId AS RecipientId,
				sAlert.tAlertConfiguration.Duration AS DurationValue,
				sAlert.tAlertConfiguration.DurationUnitId AS DurationFormatId,
				sAlert.tAlertConfiguration.AlertModeId AS ModeId,
				sAlert.tAlertConfiguration.TriggerId AS TriggerId,
				--sAlert.tAlertConfiguration.TemplateId AS TemplateId,
				0 AS TemplateId,
				sAlert.tAlertConfiguration.AttachmentTypeId

		FROM	sAlert.tAlertConfiguration 

		WHERE	sAlert.tAlertConfiguration.IsObsolete = 0
				AND sAlert.tAlertConfiguration.EventId = @rEventId
				AND sAlert.tAlertConfiguration.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertConfigurationModify]
	@rId [int],
	@rEventId [smallint],
	@rRecipientTypeId [tinyint],
	@rRecipientId [bigint],
	@rTemplate nvarchar(max),
	@rDuration [smallint],
	@rDurationUnitId [tinyint],
	@rAlertModeId [tinyint],
	@rTriggerId [tinyint],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rAttachmentTypeId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	IF @rIsObsolete = 1
	
		BEGIN
		
			UPDATE	sAlert.tAlertConfiguration
			
			SET		IsObsolete = @rIsObsolete,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
			
			WHERE	Id = @rId
		
		END
		
	ELSE
	
		BEGIN
		
			UPDATE	sAlert.tAlertConfiguration
			
			SET		EventId = @rEventId,
					RecipientTypeId = @rRecipientTypeId,
					RecipientId = @rRecipientId,
					Template = @rTemplate,
					Duration = @rDuration,
					DurationUnitId = @rDurationUnitId,
					AlertModeId = @rAlertModeId,
					TriggerId = @rTriggerId,
					IsObsolete = @rIsObsolete,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = sCommon.fGetDate(),
					AttachmentTypeId=@rAttachmentTypeId
			WHERE	Id = @rId
		
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertGetAlertValue]
	@rOrgId [int],
	@rTemplateId [smallint],
	@rId [smallint],
	@rAlertId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lViewName NVarchar(MAX)
	DECLARE @lContentValue NVarchar(MAX)
	DECLARE @lCharIndexBegin INT
	DECLARE @lCharIndexEnd INT
	DECLARE @lSqlStr NVARCHAR(MAX)
	DECLARE @lStringLen INT

	SET @lCharIndexBegin = 0
	SET @lCharIndexEnd = 0
	SET @lSqlStr = ''
	SET @lStringLen = LEN(@lContentValue)
	SET @lSqlStr = 'SELECT ' + CAST(@rTemplateId AS NVARCHAR(20)) + ' AS TemplateId, ' + CAST(@rId AS NVARCHAR(20)) + ' IdentifierId, ' + @lSqlStr 

	SELECT @lViewName = EM.ViewName, 
			 @lContentValue = TM.ContentValue 
	  FROM sAlert.tTemplatemaster TM
			 INNER JOIN sAlert.tEventmaster EM ON EM.Id = TM.EventId
	 WHERE TM.Id = @rTemplateId  

	WHILE (1 = 1)
		  BEGIN
				SET @lCharIndexEnd = CHARINDEX('[', @lContentValue, @lCharIndexBegin)
				
				IF @lCharIndexEnd > @lCharIndexBegin
					  BEGIN
							
							
							SET @lCharIndexBegin = @lCharIndexBegin + 1
							
							---- Modified By Gul
							--SET @lCharIndexBegin = @lCharIndexBegin + 0
							
							
							SET @lSqlStr = @lSqlStr + ' + '' ' + SUBSTRING(@lContentValue, @lCharIndexBegin, (@lCharIndexEnd - @lCharIndexBegin)) + ''''
							--SELECT 'a', @lSqlStr
							SET @lCharIndexBegin = @lCharIndexEnd
							IF @lCharIndexBegin = @lStringLen BREAK
					  END
				ELSE IF @lCharIndexEnd <> 0
					  BEGIN
							SET @lCharIndexBegin = @lCharIndexEnd
							SET @lCharIndexEnd = CHARINDEX(']', @lContentValue, @lCharIndexBegin)
							SET @lSqlStr = @lSqlStr + ' + CAST(' + SUBSTRING(@lContentValue, @lCharIndexBegin, (@lCharIndexEnd + 1 - @lCharIndexBegin)) + ' AS NVARCHAR(MAX))'
							--SELECT 'b', @lSqlStr
							SET @lCharIndexBegin = @lCharIndexEnd
							IF @lCharIndexBegin = @lStringLen BREAK
					  END
				ELSE
					  BEGIN
							SET @lSqlStr = @lSqlStr + ' + '' ' + SUBSTRING(@lContentValue, @lCharIndexBegin + 1, LEN(@lContentValue)) + ''''
							
							---- Modified By Gul
							--SET @lSqlStr = @lSqlStr + ' + '' ' + SUBSTRING(@lContentValue, @lCharIndexBegin + 0, LEN(@lContentValue)) + ''''
							
							--SELECT 'c', @lSqlStr
							BREAK;
						
					  END
		  END

	SET @lSqlStr = @lSqlStr + ' AS AlertMessage, ' + CAST(@rAlertId AS NVARCHAR(200)) + ' AS AlertId FROM ' + @lViewName 
	SET @lSqlStr = @lSqlStr + ' WHERE ID = ' + CAST(@rId AS NVARCHAR(200))
	EXEC sp_executesql @lSqlStr

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertLogAdd]
	
	@rXML nvarchar(max),
	@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
BEGIN TRY
	
	BEGIN TRANSACTION
	 
	SET @rXML=REPLACE(@rXML,'&','&amp;')
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT

			--SET @rXML=Replace(@rXML,'<br/>',char(13))
			--SET @rXML=Replace(Replace(@rXML,'&nbsp;',' '),'<br/>',char(13))
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML
	
	--Select @rXML

	-- Added @lMaxAlertLogId logic for loading and deadlock issue on 19/05/2025 by Foram
	DECLARE @lNextNumber BIGINT, @lMaxAlertLogId bigint = 0 
	DECLARE @lFromNextNumber BIGINT  
	
	SELECT @lMaxAlertLogId = ISNULL(MAX(Id), 0) FROM sAlert.tAlertLog WITH (NOLOCK) WHERE OrgId = @rOrgId
	
	IF(@lMaxAlertLogId = 0)
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tAlertLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	END
	ELSE
	BEGIN
		SET @lNextNumber =  @lMaxAlertLogId + 1 
	END

	
	SET @lFromNextNumber=@lNextNumber-1
	INSERT INTO sAlert.tAlertLog
		(
			Id,
			ContactId,
			AlertMessage,
			AlertSubject,
			StatusId,
			ResultMessage,
			SMSType,
			SourceEvent,
			EventId,
			AlertModeId,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			ReceiverSourceTypeId,
			ReceiverSourceId
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY ContactId),
			ContactId,
			sSetup.fPortalXMLTagsReplaceReverse(AlertMessage),
			--AlertMessage,
			sSetup.fPortalXMLTagsReplaceReverse(AlertSubject),
			StatusId,
			ResultMessage,
			SMSType,
			SourceEvent,
			EventId,
			AlertModeId,
			@rOrgId,
			CASE WHEN CreatedUserId = 1 THEN sCommon.fGetBigIntIdForOrg(CreatedUserId,@rOrgId) ELSE CreatedUserId END,			
			sCommon.fGetDate(),
			ReceiverSourceTypeId,
			ReceiverSourceId
		
	FROM OPENXML (@intDoc, '/Table/AlertLog', 1)
	WITH
	(
		ContactId nvarchar(100) 'ContactId',
		AlertMessage nvarchar(max) 'AlertMessage',
		AlertSubject nvarchar(500) 'AlertSubject',
		StatusId int 'StatusId',
		ResultMessage nvarchar(500) 'ResultMessage',		-- Changed Length 255 to 500 For Mantis 0035547 by Foram
		SMSType nvarchar(50) 'SMSType',
		SourceEvent nvarchar(50) 'SourceEvent',
		EventId int 'EventId',
		AlertModeId tinyint 'AlertModeId',
		CreatedUserId bigint 'CreatedUserId',
		ReceiverSourceTypeId smallint 'ReceiverSourceTypeId',
		ReceiverSourceId bigint 'ReceiverSourceId'
	)

	SELECT @lCount = COUNT(1) FROM OPENXML (@intDoc, '/Table/AlertLog', 1)
				 WITH ( ContactId nvarchar(50))
	SET @lNextNumber  = @lCount + @lFromNextNumber 
		
	--EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAlert.tAlertLog', @rCurrentNumber = @lNextNumber 
	UPDATE sCommon.tTableRowId WITH (rowlock) 
	SET CurrentNumber = @lNextNumber,UpdatedDateTime = sCommon.fGetDate() 
	WHERE TableTitle = 'sAlert.tAlertLog' AND OrgId = @rOrgId

	EXEC sp_xml_removedocument @intDoc
		
	SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertModeMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			TitleResourceKeyId,
			Remark
	   FROM sAlert.tAlertModeMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertQueueAdd]
	@rOrgId int,
	@rEventId [smallint],
	@rRecipientTypeId [tinyint],
	@rIdentifierId [int],
	@rCreatedBy [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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

	
	INSERT INTO sAlert.tAlertQueue
	(
		Id,
		EventId,
		RecipientTypeId,
		IdentifierId,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		OrgId
	)
	VALUES
	(
		@lNextNumber,
		@rEventId,
		@rRecipientTypeId,
		@rIdentifierId,
		@rCreatedBy,
		sCommon.fGetDate(),
		@rCreatedBy,
		sCommon.fGetDate(),
		@rOrgId
	)

	SELECT @lNextNumber AS Result
		

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertQueueDashboardGet]
	@rOrgGroupId int =0,
	@rFromDate date = '',
	@rToDate date = '',
	@rTypeId smallint = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rTypeId = 1) -- OrgGroup wise Summary
	BEGIN
		SELECT 
			OGM.Id AS OrgGroupId, 
			OGM.Title AS OrgGroupTitle, 
			COUNT(AQL.AutoId) AS QueueAlertTotal, 
			COUNT(QL.Id) AS ReceivedQueueAlertTotal,
			COUNT(AQL.AutoId) - COUNT(QL.Id) AS PendingQueueAlertTotal
		FROM sAlert.tAlertQueueLog AQL
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = AQL.OrgId
		LEFT JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
		LEFT JOIN NVQueue.dbo.QueueLog QL ON AQL.AutoId = QL.MessageId
		WHERE OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0
			AND (AQL.CreatedDateTime >= @rFromDate OR ISNULL(@rFromDate, '') = '')
			AND (AQL.CreatedDateTime <= @rToDate OR ISNULL(@rToDate, '') = '')
		GROUP BY OGM.Id, OGM.Title
	END
	IF(@rTypeId = 2) -- Organization wise Summary
	BEGIN
		SELECT 
			AQL.OrgId AS OrgId, 
			OM.Title AS OrganizationTitle,
			COUNT(AQL.AutoId) AS QueueAlertTotal, 
			COUNT(QL.Id) AS ReceivedQueueAlertTotal,
			COUNT(AQL.AutoId) - COUNT(QL.Id) AS PendingQueueAlertTotal
		FROM sAlert.tAlertQueueLog AQL
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = AQL.OrgId
		LEFT JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
		LEFT JOIN NVQueue.dbo.QueueLog QL ON AQL.AutoId = QL.MessageId
		WHERE OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0
			AND (AQL.CreatedDateTime >= @rFromDate OR ISNULL(@rFromDate, '') = '')
			AND (AQL.CreatedDateTime <= @rToDate OR ISNULL(@rToDate, '') = '')
		GROUP BY AQL.OrgId, OM.Title
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertQueueDetailAdd]
	@rOrgId int,
	@rAlertQueueId [bigint],
	@rAlertConfigurationId [smallint],
	@rAlertModeId [tinyint],
	@rDurationUnitId [tinyint],
	@rDuration [smallint],
	@rMessageToSend [nvarchar](max),
	@rContact [nvarchar](100),
	@rAttachment [nvarchar](200),
	@rIsSent [bit],
	@rCreatedBy [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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


	INSERT INTO sAlert.tAlertQueueDetail
	(
		Id,
		AlertQueueId,
		AlertConfigurationId,
		AlertModeId,
		DurationUnitId,
		Duration,
		MessageToSend,
		Contact,
		Attachment,
		IsSent,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		OrgId
	)
	VALUES
	(
		@lNextNumber,
		@rAlertQueueId,
		@rAlertConfigurationId,
		@rAlertModeId,
		@rDurationUnitId,
		@rDuration,
		@rMessageToSend,
		@rContact,
		@rAttachment,
		@rIsSent,
		@rCreatedBy,
		sCommon.fGetDate(),
		@rCreatedBy,
		sCommon.fGetDate(),
		@rOrgId
	)

	
	SELECT @lNextNumber AS Result
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertQueueDetailGet]
	@rOrgId int,
	@rAlertQueueId [bigint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT	Id AS AlertQueueDetailId,
			AlertQueueId AS AlertQueueId,
			AlertConfigurationId AS AlertConfigurationId,
			AlertModeId AS AlertModeId,
			DurationUnitId AS DurationFormatId,
			Duration AS DurationValue,
			MessageToSend AS MessageToSend,
			Contact AS ContactAddress,
			Attachment,
			IsSent AS IsSent

	FROM	sAlert.tAlertQueueDetail
	
	WHERE AlertQueueId = @rAlertQueueId AND OrgId = @rOrgId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertQueueDetailModify]
	@rId [bigint],
	@rIsSent [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	UPDATE	sAlert.tAlertQueueDetail
		
	SET		IsSent = @rIsSent
	  
	WHERE Id = @rId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertQueueGet]
	@rOrgId int,
	@rId [bigint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT	Id AS AlertQueueId,
			EventId AS EventId,
			RecipientTypeId AS RecipientTypeId,
			IdentifierId AS IdentifierId
	
	FROM	sAlert.tAlertQueue
	
	WHERE ((Id = @rId) OR (@rId = 0)) AND OrgId = @rOrgId
END

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

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

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

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertQueueModify]
	@rId [bigint],
	@rEventId [smallint],
	@rRecipientTypeId [tinyint],
	@rIdentifierId [int],
	@rUpdatedBy [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAlert.tAlertQueue
		SET 
			EventId = @rEventId,
			RecipientTypeId = @rRecipientTypeId,
			IdentifierId = @rIdentifierId,
			UpdatedUserId = @rUpdatedBy,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertStatusUpdate]
	 
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	
 
    BEGIN 
		IF OBJECT_ID('tempdb..#TempAlertLog') IS NOT NULL DROP TABLE #TempAlertLog
		IF OBJECT_ID('tempdb..#TempNotificationLog') IS NOT NULL DROP TABLE #TempNotificationLog

		IF EXISTS(SELECT name FROM master.dbo.sysdatabases WHERE name = 'NVQueue')
		BEGIN

			CREATE TABLE #TempAlertLog
			(
				Id bigint IDENTITY,
				AlertLogId bigint,
				AlertModeId tinyint
			)
		
			INSERT INTO #TempAlertLog SELECT Id, AlertModeId FROM [sAlert].[tAlertLog] WHERE StatusId = 0
		
			DECLARE @lCount int = (SELECT COUNT(Id) FROM #TempAlertLog)

			IF (@lCount > 0)
			BEGIN
				WHILE(@lCount > 0)
				BEGIN
					DECLARE @lId bigint = (SELECT AlertLogId FROM #TempAlertLog WHERE Id = @lCount)
					DECLARE @lAlertModeId int = (SELECT AlertModeId FROM #TempAlertLog WHERE Id = @lCount)

					IF EXISTS(SELECT 1 FROM [NVqueue].[dbo].[QueueDetailLog] WHERE AlertLogId = @lId) 
					BEGIN 
						DECLARE @lResponse int=0,@lResponseText nvarchar(100)=0
						
						SELECT @lResponse = CASE WHEN ISNULL(IsError, 0) = 1 THEN -1 ELSE ISNULL(IsSuccess, 0) END 
						FROM [NVqueue].[dbo].[QueueDetailLog] WHERE AlertLogId = @lId AND @lAlertModeId IN (1, 4)
						
						UPDATE [sAlert].[tAlertLog] SET StatusId = @lResponse WHERE Id = @lId AND AlertModeId IN (1, 4)


						SELECT 
							@lResponse = CASE WHEN ISNULL(IsError, 0) = 1 THEN -1 ELSE ISNULL(IsSuccess, 0) END,
							@lResponseText = ISNULL(Response, '')
						FROM [NVqueue].[dbo].[QueueDetailLog] 
						WHERE AlertLogId = @lId AND @lAlertModeId = 2
						
						UPDATE [sAlert].[tAlertLog] 
						SET StatusId = CASE WHEN @lResponse = -1 THEN -1 ELSE (SELECT Id FROM sAlert.tSMSStatusMaster WHERE Code = @lResponseText) END
						WHERE Id = @lId AND AlertModeId = 2
					END

					SET @lCount = @lCount - 1
				END
			END

			CREATE TABLE #TempNotificationLog
			(
				Id bigint IDENTITY,
				AlertLogId bigint
			)
		
			INSERT INTO #TempNotificationLog SELECT Id FROM [sAlert].[tNotificationLog] WHERE ISNULL(APIResponse, '') = ''
		
			DECLARE @lCount1 int = (SELECT COUNT(Id) FROM #TempNotificationLog)

			IF (@lCount1 > 0)
			BEGIN
				WHILE(@lCount1 > 0)
				BEGIN
					DECLARE @lId1 bigint = (SELECT AlertLogId FROM #TempNotificationLog WHERE Id = @lCount1)
					IF EXISTS(SELECT 1 FROM [NVqueue].[dbo].[QueueDetailLog] WHERE AlertLogId = @lId1) 
					BEGIN 
						DECLARE @lAPIResponse nvarchar(500) = ''
						SELECT @lAPIResponse = ISNULL(Response, '') 
						FROM [NVqueue].[dbo].[QueueDetailLog] WHERE AlertLogId = @lId1 AND IsSuccess = 1

						UPDATE [sAlert].[tNotificationLog] SET APIResponse = @lAPIResponse WHERE Id = @lId1 
					END
					SET @lCount1 = @lCount1 - 1
				END
			END
		END

		DROP TABLE #TempAlertLog
		DROP TABLE #TempNotificationLog		 
		SELECT 1 As Result
	END  
	
	COMMIT TRANSACTION
	
END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rBatchId int=0,
	@rDepositHeadId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'AlertList')
		BEGIN 
		SELECT 
			--SMS TOTAL COUNT
			(Select COUNT(*)  from sAlert.tAlertLog Where AlertModeId = 2 AND ((OrgId = @rOrgId)OR(@rOrgId=0))) AS 'SMS Total Count',
			--SMS MONTH COUNT 
			(Select COUNT(*)  from sAlert.tAlertLog Where AlertModeId = 2 AND MONTH(CreatedDateTime) =  MONTH(sCommon.fGetDate())AND YEAR(CreatedDateTime) =  YEAR(sCommon.fGetDate())  AND ((OrgId = @rOrgId)OR(@rOrgId=0)))AS 'SMS Month Count',
			--SMS TODAY COUNT
			(Select COUNT(*) from sAlert.tAlertLog Where AlertModeId = 2 AND CONVERT(date,CreatedDateTime) =  CONVERT(date,getdate(),102) AND ((OrgId = @rOrgId)OR(@rOrgId=0)))AS  'SMS Toady Count' 
		END
	ELSE IF(@rType = 'AlertGraph')
		BEGIN
			SELECT 
			CONVERT(varchar,LEFT(M.Title,3)) + '-' + CONVERT(varchar,RIGHT(MY.YearNumber,2)) AS 'Month Name' ,
				(
				SELECT COUNT(*) FROM sAlert.tAlertLog AL 
				Where ((OrgId = @rOrgId )OR( @rOrgId=0)) AND MONTH(AL.CreatedDateTime) = M.Id AND AL.AlertModeId = 2 AND YEAR(AL.CreatedDateTime) = MY.YearNumber
				) AS 'SMS Count',
				(
				SELECT COUNT(*) FROM sAlert.tAlertLog AL 
				WHERE ((OrgId = @rOrgId)OR(@rOrgId=0)) AND MONTH(AL.CreatedDateTime) = M.Id AND AL.AlertModeId = 1 AND YEAR(AL.CreatedDateTime) = MY.YearNumber
				) AS 'Mail Count'
			FROM  sSetup.fMonthYearForBatchGET(@rBatchId) MY
			LEFT JOIN sCommon.tMonthMaster M ON M.Id = MY.MonthNumber
			GROUP BY  M.Id,M.Title, MY.YearNumber
			ORDER BY  MY.YearNumber
		END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pAlertTrackAdd]
   
    
	@rOrgId int,
	@rScreenId smallint,
	@rScreenTitle NVARCHAR(100),
	@rReceiver NVARCHAR(MAX),
	@rStartDateTime DateTime,
	@rAlertModeId smallint,
	@rSourceId bigint = 0,
	@rSourceTypeId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
BEGIN TRY
	
	BEGIN TRANSACTION
	 
	DECLARE @lNextNumber BIGINT  
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tAlertTrack', 0, 1, 1,@outNextNumber = @lNextNumber output
	 
	INSERT INTO sAlert.tAlertTrack
		(
			Id,
			OrgId,
			ScreenId,
			ScreenTitle,
			Receiver,
			StartDateTime,
			AlertModeId,
			SourceId,
			SourceTypeId
		)
	 VALUES
		(
			@lNextNumber,
			@rOrgId,
			@rScreenId,
			@rScreenTitle,
			@rReceiver,
			@rStartDateTime,
			@rAlertModeId,
			@rSourceId,
			@rSourceTypeId
		)
	
		 
		SELECT @lNextNumber AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertTrackAppNotificationGet]     
   
 @rFromDate date,  
 @rToDate date,  
 @rOrgId int = 0
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
  
BEGIN  

SELECT DISTINCT * From
   (SELECT   
   OM.DisplayTitle as Organization,
   ScreenTitle,
   Receiver,
   StartDateTime,
   EndDateTime,
   ST.Title AS SourceType,  
   SA.Code AS Code     
     
  FROM  
   sAlert.tAlertTrack NL    
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=NL.OrgId 
  WHERE  
   ((CONVERT(date,NL.StartDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.EndDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.OrgId = @rOrgId
   AND NL.SourceTypeId=2003
   
   
   UNION

   SELECT   
   OM.DisplayTitle as Organization,
   ScreenTitle,
   Receiver,
   StartDateTime,
   EndDateTime,
   ST.Title AS SourceType,  
   SA.Code AS Code     
     
  FROM  
   sAlert.tAlertTrack NL    
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tAcademic A ON A.Id=NL.SourceId
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=A.StudentId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=NL.OrgId 
      
  WHERE  
    ((CONVERT(date,NL.StartDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.EndDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.OrgId = @rOrgId 
   AND NL.SourceTypeId=2001

   UNION 
   
   SELECT   
   OM.DisplayTitle as Organization,
   ScreenTitle,
   Receiver,
   StartDateTime,
   EndDateTime,
   ST.Title AS SourceType,  
   tEM.Code AS Code    
     
  FROM  
   sAlert.tAlertTrack NL    
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=NL.OrgId 
  WHERE  
  ((CONVERT(date,NL.StartDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.EndDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=95
   AND NL.OrgId = @rOrgId
    AND ISNULL(tEM.IsOtherUser,0) = 0
    
   UNION 
   
   SELECT   
   OM.DisplayTitle as Organization,
   ScreenTitle,
   Receiver,
   StartDateTime,
   EndDateTime,
   ST.Title AS SourceType,  
   '' AS Code    
     
  FROM  
   sAlert.tAlertTrack NL    
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=NL.OrgId 
  WHERE  
   ((CONVERT(date,NL.StartDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.EndDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))   
   AND (NL.SourceTypeId!=2003 AND NL.SourceTypeId!=2001 AND NL.SourceTypeId!=95)
   AND NL.OrgId = @rOrgId
   )AS tmp
   
   ORDER BY tmp.StartDateTime DESC 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAlert].[pAllBirthdayWishListGet]
	 	 
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rDayOfBirth int=0,
	 @rTemp int=0,
	 @rIsStudent bit=0,
	 @rIsEmployee bit=0,
	 @rMother bit=0,
	 @rFather bit=0,
	 @rReletive bit=0,
	 @rClassStatusId int=0,
	 /****Added for mantis : 35770 by Nilesh****/
	 @rFromBirthDayDate date = '' ,
	 @rToBirthDayDate date = ''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	Select 
			
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SC.ParentContactNo AS MobileNo,			 
			'Student' AS CategoryName,
			'' AS PersonName,
			SO.DateOfBirth,
			MONTH(SO.DateOfBirth),
			ISNULL(SI.StudentPhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
		    CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
	
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--sStudent.vStudentAllDetail SC
		
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			AND ((MONTH(SO.DateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND ((DAY(SO.DateOfBirth) = @rDayOfBirth) OR (@rDayOfBirth = 0 ))
			AND ((SM.StatusId= @rStatusId) OR(@rStatusId = 0)) --Changed For mantis : 35958 by Nilesh
			AND (SM.StatusId != 3) --Changed For mantis : 38547 
			AND (@rIsStudent=1)
			AND SO.DateOfBirth!=''
			AND (A.ClassStatusId=@rClassStatusId OR  ISNULL(A.ClassStatusId,0)=0 OR @rClassStatusId=0)
			/****Added for mantis : 35770 by Nilesh****/
			AND((SO.DateOfBirth>=@rFromBirthDayDate) OR (ISNULL(@rFromBirthDayDate,'')=''))		
			AND((SO.DateOfBirth<=@rToBirthDayDate) OR (ISNULL(@rToBirthDayDate,'')=''))
			--Added For mantis : 35958 by Nilesh
			AND((SM.Code = @rStrCode)OR(ISNULL(@rStrCode,'')='')) 
			AND((A.RollNo>=@rFromRollNo) OR (ISNULL(@rFromRollNo,'')=''))		
			AND((A.RollNo<=@rToRollNo) OR (ISNULL(@rToRollNo,'')=''))
			AND ((A.StudentId= @rStudentId) OR(@rStudentId = 0))
	 	
			
UNION ALL

Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.FatherContactNo AS MobileNo,			 
			'Father' AS CategoryName,
			SF.FatherName AS PersonName,
			SF.FatherDateOfBirth AS DateOfBirth,
			MONTH(SF.FatherDateOfBirth),
			SI.FatherPhoto AS Photo,
			 CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.FatherDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND ((MONTH(SF.FatherDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND ((SM.StatusId= @rStatusId) OR(@rStatusId = 0))--Changed For mantis : 35958 by Nilesh		
			AND(@rFather=1)
			AND SF.FatherDateOfBirth != ''
			AND (A.ClassStatusId=@rClassStatusId OR  ISNULL(A.ClassStatusId,0)=0 OR @rClassStatusId=0)
			/****Added for mantis : 35770 by Nilesh****/
			AND((SF.FatherDateOfBirth>=@rFromBirthDayDate) OR (ISNULL(@rFromBirthDayDate,'')=''))		
			AND((SF.FatherDateOfBirth<=@rToBirthDayDate) OR (ISNULL(@rToBirthDayDate,'')=''))
			--Added For mantis : 35958 by Nilesh
			AND((SM.Code = @rStrCode)OR(ISNULL(@rStrCode,'')=''))  
			AND((A.RollNo>=@rFromRollNo) OR (ISNULL(@rFromRollNo,'')=''))		
			AND((A.RollNo<=@rToRollNo) OR (ISNULL(@rToRollNo,'')=''))
			AND ((A.StudentId= @rStudentId) OR(@rStudentId = 0))
	
	UNION ALL

	Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.MotherContactNo AS MobileNo,			 
			'Mother' AS CategoryName,
			SF.MotherName AS PersonName,
			SF.MotherDateOfBirth AS DateOfBirth,
			MONTH(SF.MotherDateOfBirth),
			ISNULL(SI.MotherPhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.MotherDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND  ((MONTH(SF.MotherDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND ((SM.StatusId= @rStatusId) OR(@rStatusId = 0))--Changed For mantis : 35958 by Nilesh	
			AND(@rMother=1)
			AND SF.MotherDateOfBirth != ''	
			AND (A.ClassStatusId=@rClassStatusId OR  ISNULL(A.ClassStatusId,0)=0 OR @rClassStatusId=0)
			/****Added for mantis : 35770 by Nilesh****/
			AND((SF.MotherDateOfBirth>=@rFromBirthDayDate) OR (ISNULL(@rFromBirthDayDate,'')=''))		
			AND((SF.MotherDateOfBirth<=@rToBirthDayDate) OR (ISNULL(@rToBirthDayDate,'')=''))
			 --Added For mantis : 35958 by Nilesh
			AND((A.RollNo>=@rFromRollNo) OR (ISNULL(@rFromRollNo,'')=''))		
			AND((A.RollNo<=@rToRollNo) OR (ISNULL(@rToRollNo,'')=''))
			AND ((A.StudentId= @rStudentId) OR(@rStudentId = 0))
			AND((SM.Code = @rStrCode)OR(ISNULL(@rStrCode,'')=''))
	UNION ALL

	Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.RelativeContactNo AS MobileNo,			 
			--SF.RelationshipName AS CategoryName,
			'Relative' AS CategoryName,
			SF.RelativeName AS PersonName,
			SF.RelativeDateOfBirth AS DateOfBirth,
			MONTH(SF.RelativeDateOfBirth),
			ISNULL(SI.RelativePhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
			
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.RelativeDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND ((MONTH(SF.RelativeDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND ((SM.StatusId= @rStatusId) OR(@rStatusId = 0))--Changed For mantis : 35958 by Nilesh	
			AND(@rReletive=1)
			AND SF.RelativeDateOfBirth != ''	
			AND (A.ClassStatusId=@rClassStatusId OR  ISNULL(A.ClassStatusId,0)=0 OR @rClassStatusId=0)
			/****Added for mantis : 35770 by Nilesh****/
			AND((SF.RelativeDateOfBirth>=@rFromBirthDayDate) OR (ISNULL(@rFromBirthDayDate,'')=''))		
			AND((SF.RelativeDateOfBirth<=@rToBirthDayDate) OR (ISNULL(@rToBirthDayDate,'')=''))		
			--Added For mantis : 35958 by Nilesh	
			AND((A.RollNo>=@rFromRollNo) OR (ISNULL(@rFromRollNo,'')=''))		
			AND((A.RollNo<=@rToRollNo) OR (ISNULL(@rToRollNo,'')=''))
			AND ((A.StudentId= @rStudentId) OR(@rStudentId = 0))
			AND((SM.Code = @rStrCode)OR(ISNULL(@rStrCode,'')=''))
	
	UNION ALL
		
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS AcademicId,
			EM.Code,
			EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,
	        '' AS RollNo,
	        EC.MobileNumber AS MobileNo,
	        'Employee' AS CategoryName,
	        '' AS PersonName,
			EPD.DateOfBirth,
			MONTH(EPD.DateOfBirth) ,
			ISNULL(EI.EmployeePhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			ISNULL(ODM.Title,'') AS ClassName
	FROM 
			--[sHrm].[vExtEmployeeMaster] EM	
			sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
			LEFT JOIN sHrm.tEmployeeImages EI ON EM.Id=EI.EmployeeId
			LEFT JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 	
	WHERE  	    
			(EM.OrgId = @rOrgId)
			AND ((MONTH(EPD.DateOfBirth) = @rDateOfBirth) or (@rDateOfBirth=0) )
			AND ((DAY(EPD.DateOfBirth) = @rDayOfBirth) OR (@rDayOfBirth = 0 ))
			AND (@rIsEmployee=1)
			AND (EM.StatusId=7)	
			AND EPD.DateOfBirth!=''
			AND ISNULL(EM.IsOtherUser,0) = 0 		
			/****Added for mantis : 35770 by Nilesh****/
			AND((EPD.DateOfBirth>=@rFromBirthDayDate) OR (ISNULL(@rFromBirthDayDate,'')=''))		
			AND((EPD.DateOfBirth<=@rToBirthDayDate) OR (ISNULL(@rToBirthDayDate,'')=''))
			--Added For mantis : 35958 by Nilesh
			AND((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlumniStudentBirthdayWishGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	SELECT
		R.Id As RegistrationId,
		R.FirstName,
		R.LastName,
		R.MappedStudentId As AcademicId,
		SC.StudentId,
		SC.Name As StudentName,
		replace(
		replace(
		replace (					
		replace (
		@rTemplate,'[Name]',SC.Name)
		,'[Class]',SC.ClassName)
		,'[Division]',SC.DivisionName)
		,'[SchoolName]',OM.Title)
		AS MsgText,
		@rMailSubject AS Subject,
		OM.OrgGroupId AS OrgGroupId,
		OM.Id As OrgId,
		OM.Title As SchoolName,
		BM.Id AS BatchId,
		SC.StudentId AS SourceId,
		2003 AS SourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		2003 AS ReceiverSourceTypeId,
		ISNULL(CM.DisplayTitle,'') AS Class,
		ISNULL(SC.Code,'') as Code,
		ISNULL(SC.ClassName +'-'+ SC.DivisionName,'') as ClassDivision,
		ISNULL(Sc.ParentContactNo,'') AS MobileNo,
		ISNULL(SC.ParentEmail,'') As EmailId,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM  [sStudent].[vStudentCommunication]  SC
		INNER JOIN sAlumni.tRegistration R ON SC.AcademicId = R.MappedStudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=R.PassingClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=R.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.PassingBatchId
		
	WHERE R.MappedStudentId <> 0
		AND (DAY(SC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(SC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		--AND (SC.StatusId=1)
		AND (SC.OrgId=@rOrgId) AND SC.IsBlockAllAlert=0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pAppNonRegisteredUserGet]
	
	@rOrgId int,
	@rOSTypeId tinyint=0,	
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rCode nvarchar(20)='',
	@rUserSourceTypeId smallint,
	@rOrgGroupBatchId int=0,
	@rStatusId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
if(@rUserSourceTypeId=2003)
BEGIN
    SELECT 
		OM.Title AS OrganizationName,
		--RU.UserSourceId AS UserSourceId,
		--RU.UserSourceTypeId AS UserSourceTypeId,
		'Student' AS UserTypeName,
		SA.Code AS Code,
		SA.ClassName + ' - ' + SA.DivisionName AS Class,
		SA.Name AS Name,
		SA.DepartmentName AS Department	
	FROM		
		sStudent.vStudentAcademic SA 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId	
		LEFT JOIN  sCommunication.tRegisteredUsers RU ON RU.UserSourceId = SA.StudentId And RU.UserSourceTypeId = 2003
	WHERE
	--SA.StudentId NOT IN(SELECT RU.UserSourceId FROM sCommunication.tRegisteredUsers RU)
	--AND 
		RU.UserSourceId IS NULL 
		AND SA.OrgGroupBatchId = @rOrgGroupBatchId
		AND((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND((SA.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND ((SA.StatusId = @rStatusId) OR (@rStatusId=0))
END
ELSE
BEGIN
    SELECT 
		OM.Title AS OrganizationName,
		'Employee' AS UserTypeName,
		Emp.Code  AS Code,
		Emp.DepartmentName As Department,	
		Emp.FirstName +  ' ' + Emp.LastName AS Name
	FROM		
		sHrm.vExtEmployeeMaster Emp  
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Emp.OrgId	 
		LEFT JOIN 	sCommunication.tRegisteredUsers RU ON RU.UserSourceId = Emp.Id And RU.UserSourceTypeId = 95  												
	WHERE
		RU.UserSourceId IS NULL 
		--Emp.Id NOT IN(SELECT RU.UserSourceId FROM sCommunication.tRegisteredUsers RU)
		AND  ((Emp.OrgId = @rOrgId) OR (@rOrgId=0))
	    AND((Emp.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	    AND ((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	    AND ((Emp.StatusId = @rStatusId) OR (@rStatusId=0))
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAlert].[pAppNotificationGet]     
   
 @rOSTypeId tinyint,  
 @rEventId int,  
 @rSourceTypeId smallint,  
 @rFromDate date,  
 @rToDate date,  
 @rCode nvarchar(max),  
 @rReceiverSourceTypeId int,
 @rOrgGroupId int = 0,
 @rIsHistory bit = 0
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
  
BEGIN  

IF(@rIsHistory = 1)
BEGIN  
IF(@rCode IS NULL OR @rCode='')  
BEGIN  
 IF(@rReceiverSourceTypeId=2003)  
 BEGIN   
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=@rReceiverSourceTypeId    
   AND OM.OrgGroupId=@rOrgGroupId
   ORDER BY NL.CreatedDateTime DESC  
 END   
 ELSE IF(@rReceiverSourceTypeId=95)  
 BEGIN   
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   tEM.Code AS Code    
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=@rReceiverSourceTypeId
   AND ISNULL(tEM.IsOtherUser,0) = 0  
   AND OM.OrgGroupId=@rOrgGroupId   
   ORDER BY NL.CreatedDateTime DESC  
 END  
 ELSE  
 BEGIN   

   SELECT DISTINCT * From
   (SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND NL.SourceTypeId=2003
   AND OM.OrgGroupId=@rOrgGroupId
   
   UNION

   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  

   INNER JOIN sStudent.tAcademic A ON A.Id=NL.SourceId
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=A.StudentId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
      
  WHERE  
    ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND NL.SourceTypeId=2001
   AND OM.OrgGroupId=@rOrgGroupId

   UNION 
   
   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   tEM.Code AS Code    
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
   AND NL.SourceTypeId=95
   AND OM.OrgGroupId=@rOrgGroupId
    AND ISNULL(tEM.IsOtherUser,0) = 0
    
  -- UNION 
   
  -- SELECT   
  -- NL.Id,  
  -- NL.CreatedDateTime AS Date,  
  -- OT.Title AS OSType,  
  -- 'Custom Alert' AS EventName,  
  -- ST.Title AS SourceType,  
  -- NL.MessageTitle,  
  -- NL.NotificationMessage AS Message,
  -- '' AS Code    
     
  --FROM  
  -- sAlert.tNotificationLog NL    
  -- INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
  -- LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
  -- INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId 
  -- INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LEFT(NL.Id,4)
  --WHERE  
  -- ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
  -- AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
  -- AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
  -- AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
  -- AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
  -- AND OM.OrgGroupId=@rOrgGroupId
   
   UNION 
   
   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   '' AS Code    
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LEFT(NL.Id,4)  
   
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND OM.OrgGroupId=@rOrgGroupId
   AND (NL.SourceTypeId!=2003 AND NL.SourceTypeId!=2001 AND NL.SourceTypeId!=95)
   )AS tmp
   
   ORDER BY tmp.Date DESC 
 END  
END  
ELSE  
BEGIN  
 IF(@rReceiverSourceTypeId=95)  
 BEGIN  
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,  
   tEm.Code AS Code  
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId AND NL.SourceTypeId=@rReceiverSourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId  
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='')     
   AND ISNULL(tEM.IsOtherUser,0) = 0
   AND OM.OrgGroupId=@rOrgGroupId
   ORDER BY NL.CreatedDateTime DESC   
  END   
  Else IF(@rReceiverSourceTypeId=2003)  
  BEGIN   
     
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,  
   SA.Code AS Code
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId AND NL.SourceTypeId=@rReceiverSourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId  
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')   
   AND OM.OrgGroupId=@rOrgGroupId
  
  ORDER BY NL.CreatedDateTime DESC  
 END  
END
END
ELSE
BEGIN
	IF(@rCode IS NULL OR @rCode='')  
BEGIN  
 IF(@rReceiverSourceTypeId=2003)  
 BEGIN   
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=@rReceiverSourceTypeId    
   AND OM.OrgGroupId=@rOrgGroupId
   ORDER BY NL.CreatedDateTime DESC  
 END   
 ELSE IF(@rReceiverSourceTypeId=95)  
 BEGIN   
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   tEM.Code AS Code    
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=@rReceiverSourceTypeId
   AND ISNULL(tEM.IsOtherUser,0) = 0  
   AND OM.OrgGroupId=@rOrgGroupId   
   ORDER BY NL.CreatedDateTime DESC  
 END  
 ELSE  
 BEGIN   

   SELECT DISTINCT * From
   (SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND NL.SourceTypeId=2003
   AND OM.OrgGroupId=@rOrgGroupId
   
   UNION

   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  

   INNER JOIN sStudent.tAcademic A ON A.Id=NL.SourceId
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=A.StudentId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
      
  WHERE  
    ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND NL.SourceTypeId=2001
   AND OM.OrgGroupId=@rOrgGroupId

   UNION 
   
   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   tEM.Code AS Code    
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
   AND NL.SourceTypeId=95
   AND OM.OrgGroupId=@rOrgGroupId
    AND ISNULL(tEM.IsOtherUser,0) = 0
    
  -- UNION 
   
  -- SELECT   
  -- NL.Id,  
  -- NL.CreatedDateTime AS Date,  
  -- OT.Title AS OSType,  
  -- 'Custom Alert' AS EventName,  
  -- ST.Title AS SourceType,  
  -- NL.MessageTitle,  
  -- NL.NotificationMessage AS Message,
  -- '' AS Code    
     
  --FROM  
  -- sAlert.tNotificationLog NL    
  -- INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
  -- LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
  -- INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId 
  -- INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LEFT(NL.Id,4)
  --WHERE  
  -- ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
  -- AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
  -- AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
  -- AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
  -- AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
  -- AND OM.OrgGroupId=@rOrgGroupId
   
   UNION 
   
   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   '' AS Code    
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LEFT(NL.Id,4)  
   
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND OM.OrgGroupId=@rOrgGroupId
   AND (NL.SourceTypeId!=2003 AND NL.SourceTypeId!=2001 AND NL.SourceTypeId!=95)
   )AS tmp
   
   ORDER BY tmp.Date DESC 
 END  
END  
ELSE  
BEGIN  
 IF(@rReceiverSourceTypeId=95)  
 BEGIN  
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,  
   tEm.Code AS Code  
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId AND NL.SourceTypeId=@rReceiverSourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId  
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='')     
   AND ISNULL(tEM.IsOtherUser,0) = 0
   AND OM.OrgGroupId=@rOrgGroupId
   ORDER BY NL.CreatedDateTime DESC   
  END   
  Else IF(@rReceiverSourceTypeId=2003)  
  BEGIN   
     
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   ISNULL(EM.Title,'Custom Alert') AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,  
   SA.Code AS Code
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   LEFT JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId AND NL.SourceTypeId=@rReceiverSourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId  
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')   
   AND OM.OrgGroupId=@rOrgGroupId
  
  ORDER BY NL.CreatedDateTime DESC  
 END  
END
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pAppRegisteredUserDelete]
	 @rOrgId int,
	 @rOSTypeId tinyint=0,
	 @rUserSourceTypeId smallint,
	 @rUserSourceId bigint,
	 @rUserId bigint,
	 @rDeviceToken nvarchar(200) = '',
	 @rDate DateTime
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	

		--Add If Else for IOS mantis id : 0040542
		IF(LEN(@rDeviceToken) > 0 AND @rOSTypeId = 2)
		BEGIN
			UPDATE sCommunication.tRegisteredUsers SET DeviceDetail = 'Deleted ' + DeviceDetail
			WHERE OrgId = @rOrgId 
			AND UserId = @rUserId 
			AND UserSourceId = @rUserSourceId 
			AND UserSourceTypeId = @rUserSourceTypeId 
			AND OSTypeId = @rOSTypeId
			AND ISNULL(DeviceToken,'') = ISNULL(@rDeviceToken,'')
			AND CONVERT(DATE,CreatedDateTime) = @rDate

			SELECT 1 AS Result
		END
		ELSE
		BEGIN
			DELETE FROM 
			sCommunication.tRegisteredUsers 
			WHERE 
			OrgId = @rOrgId 
			AND UserId = @rUserId 
			AND UserSourceId = @rUserSourceId 
			AND UserSourceTypeId = @rUserSourceTypeId 
			AND OSTypeId = @rOSTypeId
			AND ISNULL(DeviceToken,'') = ISNULL(@rDeviceToken,'')
			AND CONVERT(DATE,CreatedDateTime) = @rDate

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pAppRegisteredUserGet]
	@rOrgId int,
	@rOSTypeId tinyint=0,	
	@rFromDate date,
	@rToDate date,
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rCode nvarchar(20)='',
	@rUserSourceTypeId smallint	,
	@rOrgGroupId int=0,
	@rStatusId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
if(@rUserSourceTypeId=2003)
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	OM.Id AS OrgId,
	RU.UserId AS UserId,
	RU.UserSourceId AS UserSourceId,
	RU.UserSourceTypeId AS UserSourceTypeId,
	'Student' AS UserTypeName,
	SA.Code AS Code,
	SA.ClassName + ' - ' + SA.DivisionName AS Class,
	SA.Name AS Name,
	RU.CreatedDateTime AS Date,
	OT.Title AS OSType,
	RU.OSTypeId AS OSTypeId,
	SA.DepartmentName AS Department,
	CONVERT(bit,CASE WHEN ISNULL(RU.DeviceToken,'') = '' THEN 0 ELSE 1 END) AS IsDeviceToken,
	ISNULL(RU.DeviceToken,'') AS DeviceToken,
	ISNULL(RU.AppVersion,'') AS AppVersion
	FROM		
		sCommunication.tRegisteredUsers RU
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId				
		INNER JOIN sAlert.tOSType OT ON OT.ID =RU.OSTypeId											
		INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId = RU.UserSourceId AND RU.UserSourceTypeId=2003	
	WHERE
	    ((RU.OrgId = @rOrgId) OR (@rOrgId=0))
		AND((RU.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))		
		AND((SA.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
	    AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CONVERT(date,RU.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,RU.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))	
		AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
		AND ((SA.StatusId = @rStatusId) OR (@rStatusId=0))
		--mantis id : 0040542
		AND RU.DeviceDetail Not Like '%deleted%'
	ORDER BY RU.OrgId,RU.OSTypeId,RU.UserId ASC,RU.CreatedDateTime DESC	
END
ELSE
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	OM.Id AS OrgId,
	RU.UserId AS UserId,
	RU.UserSourceId AS UserSourceId,
	RU.UserSourceTypeId AS UserSourceTypeId,
	'Employee' AS UserTypeName,
	Emp.Code  AS Code,
	Emp.DepartmentName As Department,	
	Emp.FirstName +  ' ' + Emp.LastName AS Name,
	RU.CreatedDateTime AS Date,
	OT.Title AS OSType,
	RU.OSTypeId AS OSTypeId,
	'' AS Class,
	CONVERT(bit,CASE WHEN ISNULL(RU.DeviceToken,'') = '' THEN 0 ELSE 1 END) AS IsDeviceToken,
	ISNULL(RU.DeviceToken,'') AS DeviceToken,
	ISNULL(RU.AppVersion,'') AS AppVersion
	FROM		
		sCommunication.tRegisteredUsers RU
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId				
		INNER JOIN sAlert.tOSType OT ON OT.ID =RU.OSTypeId			
		
	    INNER JOIN sHrm.vExtEmployeeMaster Emp ON Emp.Id = RU.UserSourceId AND RU.UserSourceTypeId=95	    												
	WHERE
	((RU.OrgId = @rOrgId) OR (@rOrgId=0))
		AND((RU.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))	
	    AND((Emp.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND ((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CONVERT(date,RU.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,RU.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))	
		AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
		AND ((Emp.StatusId = @rStatusId) OR (@rStatusId=0))
		--mantis id : 0040542
		AND RU.DeviceDetail Not Like '%deleted%'
		ORDER BY RU.OrgId,RU.OSTypeId,RU.UserId ASC,RU.CreatedDateTime DESC	
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pApprovalRequestGet]	 
	 @rSourceTypeId smallint,
	 @rId bigint,
	 @rOrgId int,
	 @rTemplate nvarchar(max)='',
	 @rSubject nvarchar(100)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
	DECLARE @lSourceTypeId int = 0
	SELECT @lSourceTypeId = ParticipantSourceTypeId FROM sWorkflow.tApprovalRequest WHERE Id = @rId
	DECLARE @lOrgGroupId int = 0
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	
	IF(@lSourceTypeId=2001)
	BEGIN
		SELECT 
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			AR.ParticipantSourceTypeId AS SourceTypeId,
			SC.AcademicId AS SourceId,
			SC.Name AS Name,
			REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[RequestFor]', ISNULL(WFM.Title,'')),
				'[Name]',ISNULL(SC.Name,'')),
				'[Status]',ISNULL((CASE ISNULL(ASM.title,'') WHEN '' THEN 'Pending' ELSE ASM.Title END),'')),
				'[StatusRemark]',ISNULL(AA.ActionRemark,'')),
				'[UpdatedDate]',ISNULL(Convert(varchar,AR.UpdatedDateTime,103),'')),
				'[RequestDate]',ISNULL(Convert(varchar,AR.CreatedDateTime,103),'')) AS MsgText,
			@rSubject AS [Subject],
			SC.OrgId,
			@lOrgGroupId AS OrgGroupId,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			INNER JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = AR.ParticipantSourceId AND AR.ParticipantSourceTypeId = 2001
		WHERE 
			SC.OrgId=@rOrgId  
			AND AR.ParticipantSourceId IS NOT NULL  
			AND AR.ParticipantSourceTypeId =@lSourceTypeId
			AND AR.Id=@rId
			AND SC.IsBlockAllAlert = 0
			AND SC.StatusId = 1
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	END
	IF(@lSourceTypeId=95)
	BEGIN
		SELECT 
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ReceiverSourceTypeId,
			vEC.EmployeeId AS ReceiverSourceId,
			AR.ParticipantSourceTypeId AS SourceTypeId,
			vEC.EmployeeId AS SourceId,
			vEC.EmployeeName AS Name,
			REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[RequestFor]', ISNULL(WFM.Title,'')),
				'[Name]',ISNULL(vEC.EmployeeName,'')),
				'[Status]',ISNULL((CASE ISNULL(ASM.title,'') WHEN '' THEN 'Pending' ELSE ASM.Title END),'')),
				'[StatusRemark]',ISNULL(AA.ActionRemark,'')),
				'[UpdatedDate]',ISNULL(Convert(varchar,AR.UpdatedDateTime,103),'')),
				'[RequestDate]',ISNULL(Convert(varchar,AR.CreatedDateTime,103),'')) AS MsgText,
			@rSubject AS [Subject],
			vEC.OrgId,
			@lOrgGroupId AS OrgGroupId,
			vEC.MobileNumber AS MobileNo,
			vEC.CompanyEmail AS EmailId,
			ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			INNER JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			LEFT JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = AR.ParticipantSourceId
		WHERE 
			vEC.OrgId=@rOrgId  
			AND AR.ParticipantSourceId IS NOT NULL  
			AND AR.ParticipantSourceTypeId =@lSourceTypeId
			AND AR.Id=@rId
			AND (ISNULL(vEC.CompanyEmail,'') <> '' OR ISNULL(vEC.WhatsAppContactNo, '') <> '' OR ISNULL(vEC.MobileNumber, '') <> '')
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pApprovalRequestManagerGet]	 
	 @rSourceTypeId smallint,
	 @rId bigint,
	 @rOrgId int,
	 @rTemplate nvarchar(max)='',
	 @rSubject nvarchar(100)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	IF(@rSourceTypeId=2001)
	BEGIN
		SELECT 
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			95 AS ReceiverSourceTypeId,
			vEC.EmployeeId AS ReceiverSourceId,
			95 AS SourceTypeId,
			vEC.EmployeeId AS SourceId,
			SA.Name AS Name,
			REPLACE (REPLACE (
			REPLACE(@rTemplate,'[RequestFor]', ISNULL(WFM.Title,'')),
				'[Remark]',ISNULL(AR.Remark,'')),
				'[RequestDate]',ISNULL(Convert(varchar,AR.CreatedDateTime,103),'')) AS MsgText,
			@rSubject AS [Subject],
			SA.OrgId,
			@lOrgGroupId AS OrgGroupId,
			vEC.MobileNumber AS MobileNo,
			vEC.CompanyEmail AS EmailId,
			ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId AND AR.ParticipantSourceTypeId = 2001
			LEFT JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = SA.InchargeEmployeeId 
		WHERE 
			SA.OrgId=@rOrgId  
			AND AR.ParticipantSourceId IS NOT NULL  
			AND AR.ParticipantSourceTypeId =@rSourceTypeId
			AND AR.Id=@rId
			AND (ISNULL(vEC.CompanyEmail,'') <> '' OR ISNULL(vEC.WhatsAppContactNo, '') <> '' OR ISNULL(vEC.MobileNumber, '') <> '')
	END
	IF(@rSourceTypeId=95)
	BEGIN
		SELECT 
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ReceiverSourceTypeId,
			vEC.EmployeeId AS ReceiverSourceId,
			AR.ParticipantSourceTypeId AS SourceTypeId,
			vEC.EmployeeId AS SourceId,
			vEC.EmployeeName AS Name,
			REPLACE (REPLACE (
			REPLACE(@rTemplate,'[RequestFor]', ISNULL(WFM.Title,'')),
				'[Remark]',ISNULL(AR.Remark,'')),
				'[RequestDate]',ISNULL(Convert(varchar,AR.CreatedDateTime,103),'')) AS MsgText,
			@rSubject AS [Subject],
			EJD.OrgId,
			@lOrgGroupId AS OrgGroupId,
			vEC.MobileNumber AS MobileNo,
			vEC.CompanyEmail AS EmailId,
			ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = AR.ParticipantSourceId
			LEFT JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = EJD.EmployeeManagerId
		WHERE 
			EJD.OrgId=@rOrgId  
			AND AR.ParticipantSourceId IS NOT NULL  
			AND AR.ParticipantSourceTypeId =@rSourceTypeId
			AND AR.Id=@rId
			AND (ISNULL(vEC.CompanyEmail,'') <> '' OR ISNULL(vEC.WhatsAppContactNo, '') <> '' OR ISNULL(vEC.MobileNumber, '') <> '')
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pAssetInchargeUserEmailListGet]
          
           @rAssetTitles varchar(500),	
           @rMaintananceDate varchar(15), 	 
	 	   @rSubject nvarchar(100),
	 	   @rTemplate nvarchar(max),
           @rOrgId int--,
          
AS
SET NOCOUNT ON

BEGIN

DECLARE @Emails VARCHAR(8000) 
SELECT 
 
	 
   ISNULL(EM.CompanyEmail,'') AS EmailId,
   ISNULL(EM.PhoneNoCompany,'') AS MobileNo,
   --ISNULL('mohit.patel@vidyalayaschoolsoftware.com','') AS EmailId,
   replace (replace(@rTemplate,'[Assets]',@rAssetTitles),'[MaintananceDate]',@rMaintananceDate)AS MsgText,
   @rSubject AS Subject,
   95 AS ReceiverSourceTypeId,
   ISNULL(EM.EmployeeId,0) AS ReceiverSourceId  ,
   @rAssetTitles AS Assets,
   @rMaintananceDate AS MaintananceDate ,
    ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
     
FROM  sAssetManagement.tAssetInchargeUser AI 
	  INNER JOIN  sSecurity.tUser  U  ON  AI.InchargeUserId = U.Id   
	  INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id=u.OrgId
	  INNER JOIN sAssetManagement.tAssetMaster AM ON AM.Id=AI.AssetId
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON U.SourceId=EM.EmployeeId 
	  LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
	 WHERE OM.Id = @rOrgId AND SourceId IS NOT NULL AND SourceId<>0
	 
	 
    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pAssignedTaskStatusGet]

	@rTemplate nvarchar(max),
	@rSourceId bigint,
	@rSourceTypeId smallint,
	@rOrgId int,
	@rSubject nvarchar(max),
	@rId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rSourceTypeId = 2003)
	BEGIN
		SELECT 
				SC.AcademicId,
				SC.Code,
				SC.Name,
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
				ISNULL(SC.StudentEmail,'') AS StudentEmail,
				ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
				ISNULL(SC.FatherMail,'') AS FatherMail,
				ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
				ISNULL(SC.MotherMail,'') AS MotherMail,
				replace(
				replace (					
				replace (
				replace (
				replace(@rTemplate,'[StartDate]',AT.AssignedDate),
				'[DueDate]',AT.DueDate),
				'[AssignedBy]',ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
					 ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'')),
				'[IsCompleted]',(CASE WHEN AT.IsCompleted = 1 THEN 'Completed' ELSE 'Not Completed' END)),
				'[Remark]',AT.Remark)
				 AS MsgText,
				 @rSubject AS Subject,
				 2003 AS ReceiverSourceTypeId,
				 SC.StudentId AS ReceiverSourceId,
				 2003 AS SourceTypeId,
				 SC.StudentId AS SourceId,
				 SC.OrgGroupId,
				 SC.OrgId,
				 AT.AssignedDate AS StartDate,
				 AT.DueDate AS DueDate,
				 ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
					 ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'') AS AssignedBy,
				(CASE WHEN AT.IsCompleted = 1 THEN 'Completed' ELSE 'Not Completed' END) IsCompleted,
				AT.Remark AS Remark,
				SC.WhatsAppContactNo

		FROM 
				sStudent.vStudentCommunication SC
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
				INNER JOIN sCommunication.tAssignTask AT ON AT.AssignedToSourceId = SC.StudentId AND AT.AssignedToSourceTypeId = 2003
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId

		WHERE AT.Id = @rId
		AND (SC.OrgId=@rOrgId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
		AND SC.IsActiveBatch = 1
	END
	ELSE IF (@rSourceTypeId = 95)
	BEGIN 
		SELECT 
			EM.EmployeeId AS EmployeeId,
			EM.Code,
			EM.EmployeeName AS Name,
			EM.MobileNumber AS MobileNo,	
			EM.CompanyEmail AS EmailId,
			replace(
			replace (					
			replace (
			replace (
			replace(@rTemplate,'[StartDate]',AT.AssignedDate),
			'[DueDate]',AT.DueDate),
			'[AssignedBy]',ISNULL(CASE WHEN U.SourceTypeId = 95 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
					ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'')),
			'[IsCompleted]',(CASE WHEN AT.IsCompleted = 1 THEN 'Completed' ELSE 'Not Completed' END)),
			'[Remark]',AT.Remark)
				AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EM.EmployeeId AS ReceiverSourceId,
			95 AS SourceTypeId,
			EM.EmployeeId AS SourceId,
			OM.OrgGroupId,
			EM.OrgID,
			AT.AssignedDate AS StartDate,
			AT.DueDate AS DueDate,
			ISNULL(CASE WHEN U.SourceTypeId = 95 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
					ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'') AS AssignedBy,
			(CASE WHEN AT.IsCompleted = 1 THEN 'Completed' ELSE 'Not Completed' END) IsCompleted,
			AT.Remark AS Remark,
			ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo

		FROM 
				sHrm.vExtEmployeeMaster EM
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id
				INNER JOIN sCommunication.tAssignTask AT ON AT.AssignedToSourceId = EM.EmployeeId AND AT.AssignedToSourceTypeId = 95
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId

		WHERE AT.Id = @rId
		AND (EM.OrgId=@rOrgId)
		AND (EM.StatusId=7) 
		AND EM.IsOtherUser = 0
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pAssignedToEmployeeQueryGet]
	 	 
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max)--,
	 	 --@rFromSourceTypeId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @AssignedTo bigint;
	DECLARE @AssignedToEmailId varchar(100);
	
		   SELECT 
		     QM.Id AS QueryId,
		     (ISNULL(EM.CompanyEmail,'')) AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		     replace(replace(@rTemplate,'[Name]',EM.EmployeeName),'[QueryNo]',QM.number) AS MsgText,
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 OM.Id AS OrgId,
			 OM.OrgGroupId,
			 95 AS SourceTypeId,
			 EM.EmployeeId AS SourceId  ,
			 EM.EmployeeName AS Name,
			 QM.number AS QueryNo,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.AssignedToEmployeeId=EM.EmployeeId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
	      WHERE
		    QM.Id = @rQueryId 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE OR ALTER PROCEDURE [sAlert].[pAssociateRecipientAdd]
	 
		@rForUserId	bigint,
		@rEventId	smallint,
		@rEmailIds	nvarchar(200),
		@rMobileIds	nvarchar(200),
		@rDefaultEmailIds	nvarchar(200),
		@rDefaultMobileIds	nvarchar(200),
		@rId int
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT 1 FROM sAlert.tAssociateRecipient WHERE ForUserId=@rForUserId AND EventId=@rEventId)
		BEGIN 
			SELECT -101 AS Result 
			RETURN 
		END 
	END
	ELSE
	BEGIN
	if(@rEventId!=39 AND @rEventId!=37 AND @rEventId!=38  AND @rEventId!=40)
	  BEGIN
	 
		IF EXISTS (SELECT 1 FROM sAlert.tAssociateRecipient WHERE  ForUserId=@rForUserId AND EventId=@rEventId AND AutoId<>@rId)
		BEGIN 
			SELECT -101 AS Result 
			RETURN 
		END
		END
	END
	BEGIN TRANSACTION	
   IF(@rId = 0)	
	BEGIN
	
		INSERT INTO sAlert.tAssociateRecipient
		(
			ForUserId, 
			EventId,
			EmailIds,
			MobileIds, 
			DefaultEmailIds, 
			DefaultMobileIds
		)
		VALUES
		(
			@rForUserId, 
			@rEventId,
			@rEmailIds,
			@rMobileIds, 
			@rDefaultEmailIds, 
			@rDefaultMobileIds
		)
		SELECT 1 AS Result
		END
		ELSE
	BEGIN
		
		UPDATE sAlert.tAssociateRecipient
		SET 
		    MobileIds=@rMobileIds,DefaultEmailIds=@rDefaultEmailIds,DefaultMobileIds=@rDefaultMobileIds,
		   EmailIds=@rEmailIds
	     	WHERE ForUserId=@rForUserId AND EventId= @rEventId
		SELECT 11 AS Result
	END  	
	
		COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE OR ALTER PROCEDURE [sAlert].[pAssociateRecipientGet]
	 
		@rForUserId	bigint=0,
		@rEventId	nvarchar(max)='',
		@rAutoId int=0,
		@rRoleId int=0,
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select A.*,SR.Title As RoleName,U.DisplayTitle AS UserName,R.RoleId,
 	EM.Title As EventType
	 From sAlert.tAssociateRecipient A
	INNER JOIN sSecurity.tUserRole R ON R.UserId=A.ForUserId AND R.IsObsolete = 0
	INNER JOIN sSecurity.tRole SR ON SR.Id=R.RoleId AND SR.IsObsolete = 0
	INNER JOIN sSecurity.tUser U ON U.Id=R.UserId AND U.IsObsolete = 0
	Inner JOIN [sAlert].[tEventMaster] EM ON EM.Id=A.EventId
	Where 
	--(EventId=@rEventId OR @rEventId=0)
	 (ISNULL(EventId,'') IN( SELECT cast(item as nvarchar(max)) FROM  sCommon.fnsplit(@rEventId,',')) OR @rEventId='') 
	AND (ForUserId=@rForUserId OR @rForUserId=0)
	AND (AutoId=@rAutoId OR @rAutoId=0)
	AND (R.RoleId=@rRoleId OR @rRoleId=0)
	AND U.OrgId=@rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE OR ALTER PROCEDURE [sAlert].[pAssociateRecipientSEttingAdd]
	 
		@rForUserId	bigint,
		@rEventId	smallint,
		@rEmailIds	nvarchar(200),
		@rMobileIds	nvarchar(200)
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
   IF NOt EXists (SELECT 1 FROM sAlert.tAssociateRecipient WHERE  ForUserId=@rForUserId AND EventId=@rEventId)	
	BEGIN
	
		INSERT INTO sAlert.tAssociateRecipient
		(
			ForUserId, 
			EventId,
			EmailIds,
			MobileIds
		)
		VALUES
		(
			@rForUserId, 
			@rEventId,
			@rEmailIds,
			@rMobileIds
		)
		SELECT 1 AS Result
		END
		ELSE
	BEGIN
		
		UPDATE sAlert.tAssociateRecipient
		SET 
		    MobileIds=@rMobileIds,
		  EmailIds=@rEmailIds
		WHERE ForUserId=@rForUserId AND EventId= @rEventId
		SELECT 11 AS Result
	END  	
	
		COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pBehaviourEntryCreateGet]
	@rOrgId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rBehaviourId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		ISNULL(SC.ParentContactNo,'') As MobileNo,
		ISNULL(SC.ParentEmail,'') AS EmailId,
		REPLACE (
		REPLACE (
		REPLACE (
		REPLACE (
		REPLACE (
		REPLACE (
		REPLACE(@rTemplate,
				'[IdNo]',ISNULL(SC.Code,'')
				),
				'[Name]',ISNULL(SC.Name,'')
				),
				'[Class]',ISNULL(SC.ClassName,'')
				),
				'[BehaviourType]',ISNULL(BTM.Title,'')
				),
				'[BehaviourDate]',ISNULL(B.BehaviourDate,'')
				),
				'[Title]',ISNULL(B.Title,'')
				),
				'[Remark]',B.Remark
				) AS MsgText,
		@rSubject AS [Subject],
		SC.OrgId,
		SC.OrgGroupId,
		SC.StudentId AS SourceId,
		2003 AS SourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		2003 AS ReceiverSourceTypeId,
		SC.WhatsAppContactNo AS WhatsAppContactNo
	FROM [sCommunication].[tBehaviour] B
		INNER JOIN sStudent.vStudentCommunication SC ON B.AcademicId = SC.AcademicId
		LEFT JOIN sCommunication.tBehaviourTypeMaster BTM ON BTM.Id = B.BehaviourTypeId
	WHERE SC.OrgId = @rOrgId 
		AND B.Id = @rBehaviourId 
		AND (ISNULL(SC.ParentContactNo, '') <> '' OR ISNULL(SC.parentemail,'') <> '' OR SC.WhatsAppContactNo <> '')
		AND SC.IsActiveBatch = 1 
		AND SC.IsBlockAllAlert=0 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAlert].[pBehaviourEntryGet]
	
	@rOrgId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rBehaviourId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
SELECT 

ISNULL(EC.MobileNumber,'') As MobileNo,
ISNULL(EC.CompanyEmail,'') AS EmailId,
REPLACE (
REPLACE (
REPLACE (
REPLACE(@rTemplate,
		'[BehaviourDate]',ISNULL(B.BehaviourDate,'')),
		'[Code]',ISNULL(SC.Code,'')),
		'[Name]',SC.Name),
		'[Remark]',B.Remark)
		AS MsgText,
@rSubject AS [Subject],
SC.OrgId,
SC.OrgGroupId,
EC.EmployeeId AS SourceId,
95 AS SourceTypeId,
EC.EmployeeId AS ReceiverSourceId,
95 AS ReceiverSourceTypeId,
SC.WhatsAppContactNo AS WhatsAppContactNo
from [sCommunication].[tBehaviour] B
INNER JOIN sStudent.vStudentCommunication SC ON B.AcademicId = SC.AcademicId
INNER JOIN [sSetup].[tOrganizationMaster] OM ON SC.OrgId = OM.Id
LEFT JOIN [sHrm].[tEmployeeCommunications] EC ON OM.EmployeeId = EC.EmployeeId
Where OM.Id = @rOrgId AND B.Id = @rBehaviourId


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pBookDueGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rDepartmentId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rDueDate date,
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS Template,
			'2001' AS SourceTypeId,
			@rMailSubject AS Subject,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			BM.Code AS BookCode,
			BM.Title AS BookName,
			BL.DueDate AS DueDate,
			SC.WhatsAppContactNo
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=SC.StudentId AND BL.ReaderSourceTypeId=2003 
			AND BL.IsCurrentStatus=1 AND BL.StatusId=523 AND BL.DueDate <= @rDueDate
	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId AND BL.ResourceSourceTypeId=2009
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
		
	UNION ALL
	
	Select 
			EC.EmployeeId AS AcademicId,
			EC.Code,
			EC.EmployeeName AS name,
			EC.PhoneNoCompany AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			'' AS StudentContactNo,
			'' AS StudentEmail,
			'' AS FatherContactNo,
			'' AS FatherMail,
			'' AS MotherContactNo,
			'' AS MotherMail,
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			AS Template,
			'95' AS SourceTypeId,
		    @rMailSubject AS Subject,
			'' AS Class,
			'' AS Division,
			BM.Code AS BookCode,
			BM.Title AS BookName,
			BL.DueDate AS DueDate,
			EC.WhatsAppContactNo
		
	From 
		sHrm.vEmployeeCommunication EC
	INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=EC.EmployeeId AND BL.ReaderSourceTypeId=95 
				AND BL.IsCurrentStatus=1 AND BL.StatusId=523 AND BL.DueDate <= @rDueDate
	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId AND BL.ResourceSourceTypeId=2009
	WHERE
			((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (EC.OrgId=@rOrgId)
		AND (EC.StatusId=7) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pBookIssueGet]
	 	 
		 @rBookIssueId bigint,
	 	 @rLibraryId int,
	 	 @rBatchId int,	 	 	 	
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 

			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (		--Mantis: 34674
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate),
			'[DueDate]',BL.DueDate)		--Mantis: 34674
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			BM.Code AS BookCode,
			BM.Title AS BookName,
			LM.Title AS LibraryName,
			BL.LogDate AS IssueDate,
			SC.WhatsAppContactNo
		
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=SC.StudentId AND BL.ReaderSourceTypeId=2003 
			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
		 (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pBookIssueListGet]
	 	 
		 --@rBookIssueId bigint,
		 @rOrgId int,
		 @rBatchId int,
		 @rDepartmentId int,
		 @rClassId int,
		 @rDivisionId int,	 	 	 	
	 	 @rLibraryId int,
		 @rIssueDate date,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 

			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (		--Mantis Id: 34674
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate),
			'[DueDate]',BL.DueDate)		--Mantis Id: 34674
			 AS Template,
			replace (		--Mantis Id: 34674
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate),
			'[DueDate]',BL.DueDate)		--Mantis Id: 34674
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			BM.Code AS BookCode,
			BM.Title AS BookName,
			LM.Title AS LibraryName,
			BL.LogDate AS IssueDate,
			SC.WhatsAppContactNo
		
		
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=SC.StudentId AND BL.ReaderSourceTypeId=2003 AND SC.OrgId = BL.OrgId
		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
		(SC.OrgId = @rOrgId)
		AND (SC.BatchId = @rBatchId)
		AND ((SC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND BL.LibraryId=@rLibraryId
		AND BL.LogDate <= @rIssueDate
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pBusRouteGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rBusRouteId int,
	 	 @rOrgGroupBatchId int,
		 @rTransportId int=0,
		 @rPickupDropIds nvarchar(max) = ''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',isnull(SC.Name,'')),
			'[Class]',isnull(SC.ClassName,'')),
			'[Division]',isnull(SC.DivisionName,'')),
			'[BusRoute]',isnull(BRM.Title,'')),
			'[PickupPoint]',isnull(BRDM.Title,'')),
			'[PickupTime]',isnull(BRDM.PickupTime,'')),
			'[DropTime]',isnull(BRDM.DropTime,''))
			 AS Template,
			 isnull(SC.ClassName,'') AS Class,
			 isnull(SC.DivisionName,'') AS Division,
			 isnull(BRM.Title,'') AS BusRoute,
			 isnull(BRDM.Title,'') AS PickupPoint,
			 isnull(BRDM.PickupTime,'') AS PickupTime,
			 isnull(BRDM.DropTime,'') AS DropTime,
			 SC.WhatsAppContactNo
		
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SC.StudentId AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND BRM.OrgGroupBatchId = SC.OrgGroupBatchId 
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BRM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (SC.StatusId=1)
		AND ((BRM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
		AND (BRDM.Id IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rPickupDropIds,',')) OR @rPickupDropIds='')

	UNION

	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',isnull(SC.Name,'')),
			'[Class]',isnull(SC.ClassName,'')),
			'[Division]',isnull(SC.DivisionName,'')),
			'[BusRoute]',isnull(BRM.Title,'')),
			'[PickupPoint]',isnull(BRDM.Title,'')),
			'[PickupTime]',isnull(BRDM.PickupTime,'')),
			'[DropTime]',isnull(BRDM.DropTime,''))
			 AS Template,
			 isnull(SC.ClassName,'') AS Class,
			 isnull(SC.DivisionName,'') AS Division,
			 isnull(BRM.Title,'') AS BusRoute,
			 isnull(BRDM.Title,'') AS PickupPoint,
			 isnull(BRDM.PickupTime,'') AS PickupTime,
			 isnull(BRDM.DropTime,'') AS DropTime,
			 SC.WhatsAppContactNo
		
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SC.StudentId AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.DropDestinationId
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND BRM.OrgGroupBatchId = SC.OrgGroupBatchId 
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BRM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (SC.StatusId=1)
		AND ((BRM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
		AND (BRDM.Id IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rPickupDropIds,',')) OR @rPickupDropIds='')

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pChargeReceiptEntryGet]
	 	 
	 	 @rReceiptId bigint,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rFromDate date,
	 	 @rToDate date
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			@rSubject AS Subject,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ReceiptNumber]',CR.ReceiptNumber),
			'[ReceiptDate]',CR.ReceiptDate),
			'[Amount]',(SELECT SUM(Amount) FROM sFee.tChargeReceiptDetail WHERE ChargeReceiptId=CR.Id))
			 AS MsgText,
			 2001 AS ReceiverSourceTypeId,
			 SC.AcademicId AS ReceiverSourceId,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 CR.ReceiptNumber,
			 CR.ReceiptDate,
			 (SELECT SUM(Amount) FROM sFee.tChargeReceiptDetail WHERE ChargeReceiptId=CR.Id) AS Amount,
			 SC.WhatsAppContactNo
		
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sFee.tChargeReceipt CR ON CR.SourceId=SC.AcademicId AND CR.SourceTypeId=2001 AND CR.IsObsolete=0
			AND ((CR.ChargeReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			--AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.Id=@rReceiptId) OR (@rReceiptId=0))
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
		
		ORDER BY CR.ReceiptNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAlert].[pCheckEventTemplateGet]

	@rOrgId smallint,
	@rEventId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			AlertModeId,
			ISNULL(IsAutoSend,'false') AS IsAutoSend,
			Template,
			MailSubject,
			ISNULL(DefaultAlertTo,'') AS DefaultAlertTo,
			EMailCC,
			EMailBCC,
			ISNULL(WhatsAppTemplate,'') AS WhatsAppTemplate,
			ISNULL(WhatsAppTemplateLanguage,'') AS WhatsAppTemplateLanguage,
			ISNULL(DefaultAlertToEUId,'') AS DefaultAlertToEUId
	FROM 
			sAlert.tEventTemplate
	WHERE	
			EventId=@rEventId
			AND OrgId=@rOrgId
	ORDER BY AlertModeId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAlert].[pCircularSchedulerGet]
	 	 
	 	 @rOrgId smallint
	 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
 
			A.MobileNumber AS MobileNo,	
			A.EmailId AS EmailId,
			CR.Title AS MsgText,
			CR.Title AS Subject,
			(SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			A.OrgId AS OrgId,
			A.Id AS SourceId,
			A.SourceTypeId AS SourceTypeId,
			A.Id AS ReceiverSourceId,
			A.SourceTypeId AS ReceiverSourceTypeId,
			A.Name,
			A.Code,
			A.WhatsAppContactNo
	From 
			sCommunication.tCircular CR
			INNER JOIN (
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = CS.SourceId AND SC.IsActiveBatch = 1
			WHERE 
			    convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND SC.IsBlockAllAlert=0 AND CS.SourceTypeId = 2003  AND C.IsPublishInFuture = 1

			UNION ALL

			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = CS.SourceId AND SC.IsActiveBatch = 1
			WHERE 
			    convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 AND CS.SourceTypeId = 2001
				AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = CS.SourceId 
			WHERE 
			    convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND vEC.StatusId = 7 AND CS.SourceTypeId = 95
				AND C.IsPublishInFuture = 1 AND vEC.IsOtherUser = 0

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DepartmentId = CS.SourceId AND SC.IsActiveBatch = 1
				 
			WHERE 
				convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND  CS.SourceTypeId = 2017 AND CS.AssigneeToId = 2
				AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.DepartmentId = CS.SourceId 
			WHERE 
			    convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND vEC.StatusId = 7 
				AND CS.SourceTypeId = 2017 AND CS.AssigneeToId = 3 AND C.IsPublishInFuture = 1 AND vEC.IsOtherUser = 0

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DepartmentId = CS.SourceId AND SC.IsActiveBatch = 1
				 
			WHERE 
				convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND  CS.SourceTypeId = 2017 AND CS.AssigneeToId = 2 AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.ClassId = CS.SourceId AND SC.IsActiveBatch = 1
				 
			WHERE 
				convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND  CS.SourceTypeId = 2016 AND CS.AssigneeToId = 2 AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = CS.SourceId AND SC.IsActiveBatch = 1
				 
			WHERE 
				convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND  CS.SourceTypeId = 2005 AND CS.AssigneeToId = 2 AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.OrgId = CS.SourceId AND SC.IsActiveBatch = 1
				 
			WHERE 
				convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND  CS.SourceTypeId = 2021 AND CS.AssigneeToId = 2 AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.OrgID = CS.SourceId 
			WHERE 
			    convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND vEC.StatusId = 7 
				AND CS.SourceTypeId = 2021 AND CS.AssigneeToId = 3 AND C.IsPublishInFuture = 1 AND vEC.IsOtherUser = 0
			
		) as A ON A.CircularId = CR.Id 
	WHERE
			convert(varchar, CR.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND A.OrgId = @rOrgId AND CR.IsPublishInFuture = 1
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAlert].[pClassHomeworkStatusGet]
	 	 
	 	 @rAcademicId bigint,
	 	 @rClassworkId bigint,
	 	 @rBatchId int,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)=''
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT 
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			SA.StudentId AS SourceId,
			'2003' AS SourceTypeId,
			SM.Title AS SubjectName,
			@rMailSubject AS Subject,
			(replace
				(replace
					(replace
						(replace(@rTemplate,'[Name]',SC.Name), 
					 '[SubjectName]',SM.Title),
				'[Status]',HCSM.Title), 
			'[HomeworkEndDate]',Convert(Varchar,AC.HomeWorkEndDate,103))) AS MsgText, --Changed HomeWorkEndDate format as dd-MM-yyyy for mantis : 40576
			OM.Id AS OrgId,
			OM.OrgGroupId,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			SM.Title AS SubjectName,
			--HCSM.Title AS Status,		-- Mantis Id : 	0040416 For whatsapp alert it gave error
			--AC.HomeWorkEndDate AS HomeworkEndDate,--commented for mantis : 40576
			Convert(Varchar,AC.HomeWorkEndDate,103) AS HomeworkEndDate, --Changed format as dd-MM-yyyy for mantis : 40576
			SC.WhatsAppContactNo
			
	FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId=SA.AcademicId
			INNER JOIN sAcademic.tClasswork AC ON AC.ClassId = SA.ClassId AND AC.BatchId = @rBatchId
			LEFT JOIN sAcademic.tHomeworkCheck HWC ON HWC.ClassworkId = AC.Id AND HWC.ClassworkId = @rClassworkId AND HWC.AcademicId = @rAcademicId
			LEFT JOIN sAcademic.tHomeworkCheckStatusMaster HCSM ON HCSM.Id = HWC.HomeWorkCheckStatusId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = AC.SubjectId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE
			AC.BatchId = @rBatchId
			AND AC.Id = @rClassworkId
			AND SA.AcademicId = @rAcademicId AND SC.IsBlockAllAlert=0
   ORDER BY 
			SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.RollNo
			
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pClassworkStudentListGet]
	 
		 @rDivisionId bigint,
		 @rOrgId int,
	 	 @rBatchId int,	 	 	 	
	 	 @rTemplate nvarchar(max) 	,
		 @rMailSubject nvarchar(500)='',
		 @rSubjectId bigint,
		 @rClassworkId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	declare @lIsOptional int = 0
	SET @lIsOptional =(select top 1 1 from sAcademic.tClasswork AC 
						INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = AC.SubjectId 
						where AC.DivisionId = @rDivisionId AND AC.SubjectId = @rSubjectId AND AC.Id =@rClassworkId AND CS.IsOptional = 1)

	IF (@lIsOptional=1)
	BEGIN
			Select 
		SC.OrgGroupId,
		SC.OrgId,
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		(replace(replace(replace(replace(replace
		(@rTemplate,'[TeacherName]',EM.FirstName +''+EM.MiddleName+''+EM.LastName), 
		'[SubjectName]',SM.Title),
		'[ClassWork]',AC.Classwork), 
		'[HomeWork]',AC.Homework), 
		'[HomeworkEndDate]',AC.HomeWorkEndDate)) AS MsgText,
		'2003' AS SourceTypeId,
		SC.StudentId AS SourceId,
		2003 AS ReceiverSourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		@rMailSubject AS Subject,
		AC.ClassId,
		AC.DivisionId,
		AC.SubjectId,
		EM.FirstName +''+EM.MiddleName+''+EM.LastName AS TeacherName,
		SM.Title AS SubjectName,
		AC.Classwork,
		AC.Homework,
		AC.HomeWorkEndDate,
		SC.WhatsAppContactNo,
		AC.Id AS DocumentId
				
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sAcademic.tClasswork AC ON AC.ClassId = SC.ClassId AND AC.DivisionId=SC.DivisionId AND AC.BatchId =SC.BatchId
		INNER JOIN sStudent.vStudentAcademic SA  ON SC.AcademicId=SA.AcademicId AND SC.ClassId=SA.ClassId AND SC.DivisionId=SA.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId AND OM.Id=SC.OrgId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = AC.SubjectId
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AC.EmployeeId
		INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = SC.ClassId AND CS.SubjectId = SM.Id
		LEFT JOIN [sAssessment].[tOptionalSubject] OS ON OS.ClassSubjectId = CS.Id AND Os.AcademicId = SA.AcademicId
	WHERE (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND (SC.DivisionId = @rDivisionId)
		AND (AC.SubjectId=@rSubjectId)
		AND AC.Id = @rClassworkId
		AND OS.AcademicId IS NOT NULL
	END

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

	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pContactExternalRecipientGet]
	@rOrgId [int],
	@rRecipientId [bigint],	
	@rModeId [int]
	
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

 SELECT Email,Mobile FROM sAlert.tExternalRecipientMaster WHERE
 Id = @rRecipientId AND OrgId = @rOrgId
 
 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pContactRoleBasedOnFunctionalityGet]
	@rOrgId [int],
	@rEventId [int],
	@rEventAlertRoleId [int],
	@rModeId [int],
	@rIdentifierId nvarchar(20)
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lViewName AS Nvarchar(200) 
DECLARE @lQuery AS Nvarchar(1000) 

SELECT @lViewName = ViewName FROM sAlert.tEventAlertRoleMaster WHERE Id = @rEventAlertRoleId

SET @lQuery = 'SELECT Id,Email,Mobile FROM ' +  @lViewName + ' WHERE Id = ' +  @rIdentifierId
 
	EXECUTE sp_executesql @lQuery

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pCustomTemplateMasterAdd]

	@rId int,
	@rOrgId smallint,
	@rTitle nvarchar(100),
	@rMailSubject nvarchar(100),
	@rMailTemplate nvarchar(max),
	@rSMSTemplate nvarchar(max),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rOrgGroupId smallint,
	@rIsAllOrg bit,
	@rSMSTemplateID nvarchar(100),
	@rWhatsAppTemplate nvarchar(max)='',
	@rMobileAppTemplate nvarchar(max)='',
	@rWhatsAppTemplateName nvarchar(100)=''		-- Mantis Id : 	0038790	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	
	--IF(@rId = 0)	
	--BEGIN
	--	If Exists(select Id from sAlert.tCustomTemplateMaster where Title=@rTitle AND OrgId=@rOrgId )
	--		BEGIN
	--		select -100 as Result
	--		RETURN
	--	END 
	--END
	
	BEGIN TRANSACTION	
	
	--IF(@rId = 0)	
	
	If NOT Exists(select Id from sAlert.tCustomTemplateMaster where Title=@rTitle AND OrgId=@rOrgId )
	BEGIN	
	DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tCustomTemplateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sAlert.tCustomTemplateMaster
		(
			Id,
			OrgId,
			Title,
			MailSubject,
			MailTemplate,
			SMSTemplate,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			SMSTemplateID,
			WhatsAppTemplate,
			MobileAppTemplate,
			WhatsAppTemplateName		-- Mantis Id : 	0038790	
		)
	VALUES
		(
			@lNextNumber,
			@rOrgId,
			@rTitle,
			@rMailSubject,
			@rMailTemplate,
			@rSMSTemplate,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSMSTemplateID,
			@rWhatsAppTemplate,
			@rMobileAppTemplate,
			@rWhatsAppTemplateName		-- Mantis Id : 	0038790	
		)
	END	 
	--ELSE IF(@rIsAllOrg=1)
	--BEGIN
	--SET @lNextNumber = @rId
	--UPDATE  sAlert.tCustomTemplateMaster
	--    SET
	--		MailSubject=@rMailSubject,
	--		MailTemplate=@rMailTemplate,
	--		SMSTemplate=@rSMSTemplate,
	--		IsObsolete=@rIsObsolete,
	--		UpdatedUserId=@rCreatedUserId,
	--		UpdatedDateTime=sCommon.fGetDate()
			
	--      WHERE Title=@rTitle 
	--		AND OrgId IN(SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId)
	-- END  
	ELSE
	BEGIN
	SET @lNextNumber = 1
	UPDATE  sAlert.tCustomTemplateMaster
	    SET
			Title=@rTitle,
			MailSubject=@rMailSubject,
			MailTemplate=@rMailTemplate,
			SMSTemplate=@rSMSTemplate,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			SMSTemplateID=@rSMSTemplateID,
			WhatsAppTemplate = @rWhatsAppTemplate,
			MobileAppTemplate = @rMobileAppTemplate,
			WhatsAppTemplateName = @rWhatsAppTemplateName	-- Mantis Id : 	0038790	
			
	      WHERE Title=@rTitle AND OrgId=@rOrgId  
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pCustomTemplateMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rMailSubject nvarchar(100),
	 @rOrgId int,
	 @rIsSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	IF(@rIsSearch=1)
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rMailSubject = sCommon.fSearchStringGet(@rMailSubject)
		END
	
	SELECT 
	
			CTM.Id,
			CTM.Title,
			CTM.MailSubject,
			CTM.MailTemplate,
			CTM.SMSTemplate,
			CTM.IsObsolete,
			CTM.OrgId,
			OM.DisplayTitle AS Organization,
			CTM.SMSTemplateID,
			ISNULL(CTM.WhatsAppTemplate,'')AS WhatsAppTemplate,
			ISNULL(CTM.MobileAppTemplate,'')AS MobileAppTemplate,
			ISNULL(CTM.WhatsAppTemplateName,'')AS WhatsAppTemplateName		-- Mantis Id : 	0038790	
			
    FROM 
            sAlert.tCustomTemplateMaster CTM
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CTM.OrgId
             
    WHERE 
	  
			((CTM.Id = @rId) OR (@rId = 0))
		AND ((CTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
		AND ((CTM.MailSubject like @rMailSubject) OR (ISNULL(@rMailSubject,'') = '')) 
		AND ((CTM.OrgId=@rOrgId) OR (@rOrgId=0))

		ORDER BY CTM.Title ASC
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pDepositAdjustmentGet]
	 	 
	 	 @rTemplate nvarchar(max),
	 	 @rDepositAdjustmentId bigint,
	 	 @rAcademicId bigint=0  ,
	 	 @rDepositHeadId int,
		 @rSubject nvarchar(100) = ''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	-- #Start Mantis Id : 0041395
	DECLARE @lBalanceAmount Decimal(12,2);
	SELECT  @lBalanceAmount = ISNULL((SUM(A.DepositAmount)-SUM(A.AdjustAmount)-SUM(A.RefundAmount)),0) FROM 
		(SELECT ISNULL(DA.AMount,0) AS DepositAmount,0 As AdjustAmount,0 AS RefundAmount ,DepositHeadId,DA.AcademicId
		FROM sFee.tDepositAdd DA WHERE  DA.DepositHeadId = @rDepositHeadId AND DA.AcademicId = @rAcademicId
		UNION All
		SELECT  0 AS DepositAmount,ISNULL(AD.Amount,0) AS AdjustAmount,0 AS RefundAmount ,DepositHeadId,AD.AcademicId   
		FROM   sFee.tDepositAdjustment AD WHERE AD.DepositHeadId = @rDepositHeadId AND AD.AcademicId = @rAcademicId
		UNION all
		SELECT 0 AS DepositAmount,0 AS AdONjustAmount,Isnull(RefundAmount,0) AS  RefundAmount,DepositHeadId,DR.AcademicId
		FROM  sFee.tDepositRefund DR WHERE DR.DepositHeadId = @rDepositHeadId AND DR.AcademicId = @rAcademicId )A
		Group By DepositHeadId,AcademicId
	-- #End Mantis Id : 0041395

	Select 
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		replace (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace(@rTemplate,'[Name]',SC.name),
		'[Class]',SC.ClassName),
		'[Division]',SC.DivisionName),
		'[DepositHead]',DH.Title),
		'[Amount]',DA.Amount),	
		'[AdjustmentDate]',DA.AdjustmentDate),
		'[Remark]',DA.Remark),
		'[BalanceAmount]',@lBalanceAmount)		-- Mantis Id : 0041395
		AS MsgText,
		@rSubject AS Subject,
		2001 AS ReceiverSourceTypeId,
		SC.AcademicId AS ReceiverSourceId,
		SC.WhatsAppContactNo,
		SC.ClassName AS Class,
		SC.DivisionName AS Division,
		DH.Title AS DepositHead,
		DA.Amount AS Amount,
		DA.AdjustmentDate AS AdjustmentDate,
		DA.Remark AS Remark
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = SC.AcademicId 
		INNER JOIN sFee.tDepositHeadMaster DH ON DH.Id=DA.DepositHeadId
	WHERE
	    DA.Id=@rDepositAdjustmentId
		AND DA.AcademicId = @rAcademicId
		AND DA.DepositHeadId=@rDepositHeadId
		AND SC.StatusId=1 AND SC.IsBlockAllAlert=0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pDigitalFormApprovalStatusGet]
	 @rOrgGroupId int,
	 @rOrgId int,
	 @rOrgGroupBatchId int,
	 @rDigitalFormId bigint,
	 @rTemplate nvarchar(max) = '',
	 @rSubject nvarchar(100)= '',
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rFieldIds nvarchar(max) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rSourceTypeId = 2003)
	BEGIN
		SELECT
			REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Title]', ISNULL(DF.Title,'')),
				'[Code]',ISNULL(DF.Code,'')),
				'[StudentName]',ISNULL(SC.Name,'')),
				'[ActionRemark]',ISNULL(DFS.ActionRemark,'')),
				'[Status]',ISNULL(SM.Title,'')),
				'[Source]',(ISNULL(SC.ClassName,'') + ' - ' + ISNULL(SC.DivisionName,''))),
				--'[FieldType]',ISNULL(STUFF((SELECT DISTINCT ', ' + convert(nvarchar(500), 
				--						CASE WHEN FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 2 THEN (SELECT 'StudentCustomFields' as SubFunctionalityName FROM sStudent.tStudentCustomFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 3 THEN 'StudentDocument' END, 120)
				--						FROM sStudent.tDigitalFormField WHERE DigitalFormId = DFS.DigitalFormId AND UpdateFieldId = A.Id
				--						FOR XML PATH ('')), 1, 1, ''),'')),
				'[Field]',ISNULL(STUFF((SELECT ', ' + convert(nvarchar(500), 
										CASE WHEN FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
											 WHEN FieldTypeId = 2 THEN (SELECT FieldTitle FROM sStudent.tStudentCustomFieldMaster WHERE Id = UpdateFieldId)
											 WHEN FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 1 AND Id = UpdateFieldId ) END, 120)
										FROM sStudent.tDigitalFormField WHERE DigitalFormId = DFS.DigitalFormId AND UpdateFieldId = A.Id
										FOR XML PATH ('')), 1, 1, ''),'')) AS MsgText,
			@rSubject AS [Subject],
			2001 AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS SourceTypeId,
			SC.AcademicId AS SourceId,
			SC.ParentContactNo AS MobileNo,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			[sStudent].[tDigitalFormStudent] DFS
			INNER JOIN sStudent.tDigitalForm DF ON DF.Id = DFS.DigitalFormId
			INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = DFS.AcademicId
			INNER JOIN (SELECT cast(item as bigint) AS Id FROM sCommon.fnsplit(@rFieldIds,',')) A ON A.Id = DFS.UpdateFieldId
			LEFT JOIN sCommon.tStatusMaster SM ON DFS.StatusId = SM.Id
		WHERE 
			SC.OrgId=@rOrgId  
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND DFS.DigitalFormId=@rDigitalFormId
			--AND DFS.UpdateFieldId IN (SELECT cast(item as bigint) FROM sCommon.fnsplit(@rFieldIds,','))
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
			AND DFS.AcademicId = @rSourceId
	END
	
	IF(@rSourceTypeId = 95)
	BEGIN
		SELECT
			REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Title]', ISNULL(DF.Title,'')),
				'[Code]',ISNULL(DF.Code,'')),
				'[EmployeeName]',ISNULL(vEC.EmployeeName,'')),
				'[ActionRemark]',ISNULL(DFS.ActionRemark,'')),
				'[Status]',ISNULL(SM.Title,'')),				
				'[Source]',ISNULL(vEC.DepartmentName,'')),
				--'[FieldType]',ISNULL(STUFF((SELECT DISTINCT ', ' + convert(nvarchar(500), 
				--						CASE WHEN FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 2 THEN (SELECT 'EmployeeCustomFields' as SubFunctionalityName FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 3 THEN 'EmployeeDocument' END, 120)
				--						FROM sHrm.tDigitalFormField WHERE DigitalFormId = DFS.DigitalFormId AND UpdateFieldId = A.Id
				--						FOR XML PATH ('')), 1, 1, ''),'')),
				'[Field]',ISNULL(STUFF((SELECT ', ' + convert(nvarchar(500), 
										CASE WHEN FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
											 WHEN FieldTypeId = 2 THEN (SELECT FieldTitle FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = UpdateFieldId)
											 WHEN FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 1 AND Id = UpdateFieldId ) END, 120)
										FROM sHrm.tDigitalFormField WHERE DigitalFormId = DFS.DigitalFormId AND UpdateFieldId = A.Id
										FOR XML PATH ('')), 1, 1, ''),'')) AS MsgText,
			@rSubject AS [Subject],
			95 AS ReceiverSourceTypeId,
			vEC.EmployeeId AS ReceiverSourceId,
			95 AS SourceTypeId,
			vEC.EmployeeId AS SourceId,
			vEC.MobileNumber AS MobileNo,
			@rOrgGroupId AS OrgGroupId,
			vEC.OrgId,
			vEC.CompanyEmail AS EmailId,
			ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			[sHrm].[tDigitalFormEmployee] DFS
			INNER JOIN sHrm.tDigitalForm DF ON DF.Id = DFS.DigitalFormId
			INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = DFS.EmployeeId
			INNER JOIN (SELECT cast(item as bigint) AS Id FROM sCommon.fnsplit(@rFieldIds,',')) A ON A.Id = DFS.UpdateFieldId
			LEFT JOIN sCommon.tStatusMaster SM ON DFS.StatusId = SM.Id
		WHERE 
			vEC.OrgId=@rOrgId  
			AND DFS.DigitalFormId=@rDigitalFormId
			AND vEC.StatusId=7	
			--AND DFS.UpdateFieldId IN (SELECT cast(item as bigint) FROM sCommon.fnsplit(@rFieldIds,','))	
			AND (ISNULL(vEC.CompanyEmail,'') <> '' OR ISNULL(vEC.WhatsAppContactNo, '') <> '' OR ISNULL(vEC.MobileNumber, '') <> '')
			AND DFS.EmployeeId = @rSourceId		
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pDigitalFormMasterAdd]
	 @rOrgGroupId int,
	 @rOrgId int,
	 @rOrgGroupBatchId int,
	 @rDigitalFormId bigint,
	 @rTemplate nvarchar(max) = '',
	 @rSubject nvarchar(100)= '',
	 @rSourceTypeId smallint 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	IF(@rSourceTypeId = 2003)
	BEGIN
		SELECT
			REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Title]', ISNULL(DF.Title,'')),
				'[Code]',ISNULL(DF.Code,'')),
				'[SourceType]', 'Department'),
				'[CreatedDateTime]',ISNULL(Convert(varchar,DF.CreatedDateTime,103),'')),
				'[StudentName]',ISNULL(SC.Name,'')),
				'[Source]',(ISNULL(SC.ClassName,'') + ' - ' + ISNULL(SC.DivisionName,''))),
				--'[FieldType]',ISNULL(STUFF((SELECT DISTINCT ', ' + convert(nvarchar(500), 
				--						CASE WHEN FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 2 THEN (SELECT 'StudentCustomFields' as SubFunctionalityName FROM sStudent.tStudentCustomFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 3 THEN 'StudentDocument' END, 120)
				--						FROM sStudent.tDigitalFormField WHERE DigitalFormId = DF.Id
				--						FOR XML PATH ('')), 1, 1, ''),'')),
				'[Field]',ISNULL(STUFF((SELECT ', ' + convert(nvarchar(500), 
										CASE WHEN FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
											 WHEN FieldTypeId = 2 THEN (SELECT FieldTitle FROM sStudent.tStudentCustomFieldMaster WHERE Id = UpdateFieldId)
											 WHEN FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 1 AND Id = UpdateFieldId ) END, 120)
										FROM sStudent.tDigitalFormField WHERE DigitalFormId = DF.Id
										FOR XML PATH ('')), 1, 1, ''),'')) AS MsgText,
			@rSubject AS [Subject],
			DFS.SourceTypeId AS ReceiverSourceTypeId,
			SC.DepartmentId AS ReceiverSourceId,
			DFS.SourceTypeId AS SourceTypeId,
			SC.DepartmentId AS SourceId,
			SC.ParentContactNo AS MobileNo,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sStudent.tDigitalForm DF 
			INNER JOIN sStudent.tDigitalFormScope DFS ON DF.Id = DFS.DigitalFormId
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = DFS.SourceId AND DFS.SourceTypeId = 2017
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.DepartmentId = DM.Id 
		WHERE 
			SC.OrgId=@rOrgId  
			AND DFS.SourceId IS NOT NULL  
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND DF.Id=@rDigitalFormId
			AND DFS.SourceTypeId = 2017
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	 
		 UNION ALL

		 SELECT
			REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Title]', ISNULL(DF.Title,'')),
				'[Code]',ISNULL(DF.Code,'')),
				'[SourceType]', 'Class'),
				'[CreatedDateTime]',ISNULL(Convert(varchar,DF.CreatedDateTime,103),'')),
				'[StudentName]',ISNULL(SC.Name,'')),
				'[Source]',(ISNULL(SC.ClassName,'') + ' - ' + ISNULL(SC.DivisionName,''))),
				--'[FieldType]',ISNULL(STUFF((SELECT DISTINCT ', ' + convert(nvarchar(500), 
				--						CASE WHEN FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 2 THEN (SELECT 'StudentCustomFields' as SubFunctionalityName FROM sStudent.tStudentCustomFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 3 THEN 'StudentDocument' END, 120)
				--						FROM sStudent.tDigitalFormField WHERE DigitalFormId = DF.Id
				--						FOR XML PATH ('')), 1, 1, ''),'')),
				'[Field]',ISNULL(STUFF((SELECT ', ' + convert(nvarchar(500), 
										CASE WHEN FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
											 WHEN FieldTypeId = 2 THEN (SELECT FieldTitle FROM sStudent.tStudentCustomFieldMaster WHERE Id = UpdateFieldId)
											 WHEN FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 1 AND Id = UpdateFieldId ) END, 120)
										FROM sStudent.tDigitalFormField WHERE DigitalFormId = DF.Id
										FOR XML PATH ('')), 1, 1, ''),'')) AS MsgText,
			@rSubject AS [Subject],
			DFS.SourceTypeId AS ReceiverSourceTypeId,
			SC.ClassId AS ReceiverSourceId,
			DFS.SourceTypeId AS SourceTypeId,
			SC.ClassId AS SourceId,
			SC.ParentContactNo AS MobileNo,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sStudent.tDigitalForm DF 
			INNER JOIN sStudent.tDigitalFormScope DFS ON DF.Id = DFS.DigitalFormId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DFS.SourceId AND DFS.SourceTypeId = 2016
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.ClassId = CM.Id
		WHERE 
			SC.OrgId=@rOrgId  
			AND DFS.SourceId IS NOT NULL  
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND DF.Id=@rDigitalFormId
			AND DFS.SourceTypeId = 2016
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')

		UNION ALL
		
		SELECT
			REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Title]', ISNULL(DF.Title,'')),
				'[Code]',ISNULL(DF.Code,'')),
				'[SourceType]', 'Division'),
				'[CreatedDateTime]',ISNULL(Convert(varchar,DF.CreatedDateTime,103),'')),
				'[StudentName]',ISNULL(SC.Name,'')),
				'[Source]',(ISNULL(SC.ClassName,'') + ' - ' + ISNULL(SC.DivisionName,''))),
				--'[FieldType]',ISNULL(STUFF((SELECT DISTINCT ', ' + convert(nvarchar(500), 
				--						CASE WHEN FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 2 THEN (SELECT 'StudentCustomFields' as SubFunctionalityName FROM sStudent.tStudentCustomFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 3 THEN 'StudentDocument' END, 120)
				--						FROM sStudent.tDigitalFormField WHERE DigitalFormId = DF.Id
				--						FOR XML PATH ('')), 1, 1, ''),'')),
				'[Field]',ISNULL(STUFF((SELECT ', ' + convert(nvarchar(500), 
										CASE WHEN FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
											 WHEN FieldTypeId = 2 THEN (SELECT FieldTitle FROM sStudent.tStudentCustomFieldMaster WHERE Id = UpdateFieldId)
											 WHEN FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 1 AND Id = UpdateFieldId ) END, 120)
										FROM sStudent.tDigitalFormField WHERE DigitalFormId = DF.Id
										FOR XML PATH ('')), 1, 1, ''),'')) AS MsgText,
			@rSubject AS [Subject],
			DFS.SourceTypeId AS ReceiverSourceTypeId,
			SC.DivisionId AS ReceiverSourceId,
			DFS.SourceTypeId AS SourceTypeId,
			SC.DivisionId AS SourceId,
			SC.ParentContactNo AS MobileNo,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sStudent.tDigitalForm DF 
			INNER JOIN sStudent.tDigitalFormScope DFS ON DF.Id = DFS.DigitalFormId
			LEFT JOIN sSetup.tDivisionMaster DM ON DM.Id = DFS.SourceId AND DFS.SourceTypeId = 2005
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = DFS.SourceId
		WHERE 
			SC.OrgId=@rOrgId  
			AND DFS.SourceId IS NOT NULL  
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND DF.Id=@rDigitalFormId
			AND DFS.SourceTypeId = 2005
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')

		UNION ALL
		
		SELECT
			REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Title]', ISNULL(DF.Title,'')),
				'[Code]',ISNULL(DF.Code,'')),
				'[SourceType]', 'Student'),
				'[CreatedDateTime]',ISNULL(Convert(varchar,DF.CreatedDateTime,103),'')),
				'[StudentName]',ISNULL(SC.Name,'')),
				'[Source]',(ISNULL(SC.ClassName,'') + ' - ' + ISNULL(SC.DivisionName,''))),
				--'[FieldType]',ISNULL(STUFF((SELECT DISTINCT ', ' + convert(nvarchar(500), 
				--						CASE WHEN FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 2 THEN (SELECT 'StudentCustomFields' as SubFunctionalityName FROM sStudent.tStudentCustomFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 3 THEN 'StudentDocument' END, 120)
				--						FROM sStudent.tDigitalFormField WHERE DigitalFormId = DF.Id
				--						FOR XML PATH ('')), 1, 1, ''),'')),
				'[Field]',ISNULL(STUFF((SELECT ', ' + convert(nvarchar(500), 
										CASE WHEN FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
											 WHEN FieldTypeId = 2 THEN (SELECT FieldTitle FROM sStudent.tStudentCustomFieldMaster WHERE Id = UpdateFieldId)
											 WHEN FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 1 AND Id = UpdateFieldId ) END, 120)
										FROM sStudent.tDigitalFormField WHERE DigitalFormId = DF.Id
										FOR XML PATH ('')), 1, 1, ''),'')) AS MsgText,
			@rSubject AS [Subject],
			DFS.SourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			DFS.SourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.ParentContactNo AS MobileNo,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sStudent.tDigitalForm DF 
			INNER JOIN sStudent.tDigitalFormScope DFS ON DF.Id = DFS.DigitalFormId
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = DFS.SourceId AND DFS.SourceTypeId = 2003
		WHERE 
			SC.OrgId=@rOrgId  
			AND DFS.SourceId IS NOT NULL  
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND DF.Id=@rDigitalFormId
			AND DFS.SourceTypeId = 2003
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	END
	
	IF(@rSourceTypeId = 95)
	BEGIN
		SELECT
			REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Title]', ISNULL(DF.Title,'')),
				'[Code]',ISNULL(DF.Code,'')),
				'[SourceType]', 'Department'),
				'[CreatedDateTime]',ISNULL(Convert(varchar,DF.CreatedDateTime,103),'')),
				'[EmployeeName]',ISNULL(vEC.EmployeeName,'')),
				'[Source]',ISNULL(vEC.DepartmentName,'')),
				--'[FieldType]',ISNULL(STUFF((SELECT DISTINCT ', ' + convert(nvarchar(500), 
				--						CASE WHEN FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 2 THEN (SELECT 'EmployeeCustomFields' as SubFunctionalityName FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 3 THEN 'EmployeeDocument' END, 120)
				--						FROM sHrm.tDigitalFormField WHERE DigitalFormId = DF.Id
				--						FOR XML PATH ('')), 1, 1, ''),'')),
				'[Field]',ISNULL(STUFF((SELECT ', ' + convert(nvarchar(500), 
										CASE WHEN FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
											 WHEN FieldTypeId = 2 THEN (SELECT FieldTitle FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = UpdateFieldId)
											 WHEN FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 1 AND Id = UpdateFieldId ) END, 120)
										FROM sHrm.tDigitalFormField WHERE DigitalFormId = DF.Id
										FOR XML PATH ('')), 1, 1, ''),'')) AS MsgText,
			@rSubject AS [Subject],
			DFS.SourceTypeId AS ReceiverSourceTypeId,
			vEC.DepartmentId AS ReceiverSourceId,
			DFS.SourceTypeId AS SourceTypeId,
			vEC.DepartmentId AS SourceId,
			vEC.MobileNumber AS MobileNo,
			@rOrgGroupId AS OrgGroupId,
			vEC.OrgId,
			vEC.CompanyEmail AS EmailId,
			ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sHrm.tDigitalForm DF 
			INNER JOIN sHrm.tDigitalFormScope DFS ON DF.Id = DFS.DigitalFormId
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = DFS.SourceId AND DFS.SourceTypeId = 2017
			LEFT JOIN sHrm.vEmployeeCommunication vEC ON vEC.DepartmentId = DM.Id 
		WHERE 
			vEC.OrgId=@rOrgId  
			AND DFS.SourceId IS NOT NULL  
			AND DF.Id=@rDigitalFormId
			AND DFS.SourceTypeId = 2017
			AND vEC.StatusId=7		
			AND (ISNULL(vEC.CompanyEmail,'') <> '' OR ISNULL(vEC.WhatsAppContactNo, '') <> '' OR ISNULL(vEC.MobileNumber, '') <> '')
	 
		UNION ALL

		SELECT
			REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Title]', ISNULL(DF.Title,'')),
				'[Code]',ISNULL(DF.Code,'')),
				'[SourceType]', 'Employee'),
				'[CreatedDateTime]',ISNULL(Convert(varchar,DF.CreatedDateTime,103),'')),
				'[EmployeeName]',ISNULL(vEC.EmployeeName,'')),
				'[Source]',ISNULL(vEC.DepartmentName,'')),
				--'[FieldType]',ISNULL(STUFF((SELECT DISTINCT ', ' + convert(nvarchar(500), 
				--						CASE WHEN FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 2 THEN (SELECT 'EmployeeCustomFields' as SubFunctionalityName FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = UpdateFieldId) 
				--							 WHEN FieldTypeId = 3 THEN 'EmployeeDocument' END, 120)
				--						FROM sHrm.tDigitalFormField WHERE DigitalFormId = DF.Id
				--						FOR XML PATH ('')), 1, 1, ''),'')),
				'[Field]',ISNULL(STUFF((SELECT ', ' + convert(nvarchar(500), 
										CASE WHEN FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = UpdateFieldId) 
											 WHEN FieldTypeId = 2 THEN (SELECT FieldTitle FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = UpdateFieldId)
											 WHEN FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 1 AND Id = UpdateFieldId ) END, 120)
										FROM sHrm.tDigitalFormField WHERE DigitalFormId = DF.Id
										FOR XML PATH ('')), 1, 1, ''),'')) AS MsgText,
			@rSubject AS [Subject],
			DFS.SourceTypeId AS ReceiverSourceTypeId,
			vEC.EmployeeId AS ReceiverSourceId,
			DFS.SourceTypeId AS SourceTypeId,
			vEC.EmployeeId AS SourceId,
			vEC.MobileNumber AS MobileNo,
			@rOrgGroupId AS OrgGroupId,
			vEC.OrgId,
			vEC.CompanyEmail AS EmailId,
			ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sHrm.tDigitalForm DF 
			INNER JOIN sHrm.tDigitalFormScope DFS ON DF.Id = DFS.DigitalFormId
			LEFT JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = DFS.SourceId 
		WHERE 
			vEC.OrgId=@rOrgId  
			AND DFS.SourceId IS NOT NULL  
			AND DF.Id=@rDigitalFormId
			AND DFS.SourceTypeId = 95
			AND vEC.StatusId=7		
			AND (ISNULL(vEC.CompanyEmail,'') <> '' OR ISNULL(vEC.WhatsAppContactNo, '') <> '' OR ISNULL(vEC.MobileNumber, '') <> '')
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pDSRGet]
	
	 	 @rFDSRId int,
	 	 @rTemplate nvarchar(max),
	 	 @rUserId bigint,
         @rOrgId int,
         @rSubject nvarchar(100),
         @rLDSRId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lEmployeeId bigint=0
	SELECT @lEmployeeId = SourceId FROM sSecurity.tUser WHERE Id = @rUserId AND SourceTypeId = 95
	
	SELECT 
			EM.EmployeeId,
			EM.Code,
			EM.EmployeeName,
			CASE
            WHEN ISNULL(EM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,2) LIKE ',%,' THEN stuff(stuff(ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,2), 1, 1, ''),LEN(stuff(ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,2), 1, 1, '')),1,'')
            WHEN ISNULL(EM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,2) LIKE ',%' THEN stuff(ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,2), 1, 1, '')
            WHEN ISNULL(EM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,2) LIKE '%,' THEN stuff(ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,2), LEN(ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,2)), 1, '')
            ELSE ISNULL(EM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,2)
            END AS MobileNo,
			CASE
		    WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,1) LIKE ',%,' THEN stuff(stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,1), 1, 1, ''),LEN(stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,1), 1, 1, '')),1,'')
            WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,1) LIKE ',%' THEN stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,1), 1, 1, '')
			WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,1) LIKE '%,' THEN stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,1), LEN(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,1)), 1, '')
			ELSE ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@rUserId,69,1)
			END AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EM.EmployeeName),
			'[DSRDate]',D.ReportDate),
			'[Module]',D.Module),
			'[WorkDescription]',ISNULL(D.WorkDescription,'')),
			'[HoursWorked]',ISNULL(D.HoursWorked,''))
			 AS MsgText,
			@rSubject AS Subject
	FROM 
	    sErp.tDSR D
		INNER JOIN [sSecurity].[tUser] U ON U.Id = D.CreatedUserId 
		INNER JOIN 	sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId =@lEmployeeId
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = @lEmployeeId
        LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId	
	WHERE
		 D.Id >= @rFDSRId  AND  D.Id <= @rLDSRId
		AND D.CreatedUserId=@rUserId
		AND D.OrgId=@rOrgId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAlert].[pEExamDetailGet]
	
	@rTestId bigint,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rOrgGroupBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
SELECT 
		
TM.Id AS TestId,
SC.ParentContactNo AS MobileNo,	
SC.ParentEmail AS EmailId,
REPLACE (
REPLACE (
REPLACE(@rTemplate,
		'[ExamName]',ISNULL(TM.Title,'')),
		'[Subject]',ISNULL(CS.SubjectName,'')),
		'[TestDate]',TM.TestDate)		
		AS MsgText,
@rSubject AS [Subject],
SC.OrgId,
SC.OrgGroupId,
SC.StudentId AS SourceId,
2003 AS SourceTypeId,
SC.StudentId AS ReceiverSourceId,
2003 AS ReceiverSourceTypeId,
SC.WhatsAppContactNo AS WhatsAppContactNo

From sStudent.vStudentCommunication SC
INNER JOIN sEExam.tTestAssign TA ON SC.StudentId = TA.SourceId
INNER JOIN sEExam.tTestMaster TM ON TA.TestId = TM.Id
INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = TM.ClassSubjectId
WHERE StatusId = 1 
AND  IsActiveBatch = 1 
AND IsBlockAllAlert=0 
AND OrgGroupBatchId = @rOrgGroupBatchId 
AND TA.TestId = @rTestId
AND TA.SourceTypeId = 2003

UNION 

SELECT

TM.Id AS TestId,
SC.ParentContactNo AS MobileNo,	
SC.ParentEmail AS EmailId,
REPLACE (
REPLACE (
REPLACE(@rTemplate,
		'[ExamName]',ISNULL(TM.Title,'')),
		'[Subject]',ISNULL(CS.SubjectName,'')),
		'[TestDate]',TM.TestDate)		
		AS MsgText,
@rSubject AS [Subject],
SC.OrgId,
SC.OrgGroupId,
SC.StudentId AS SourceId,
2003 AS SourceTypeId,
SC.StudentId AS ReceiverSourceId,
2003 AS ReceiverSourceTypeId,
SC.WhatsAppContactNo AS WhatsAppContactNo
From sStudent.vStudentCommunication SC
INNER JOIN sEExam.tTestAssign TA ON SC.DivisionId = TA.SourceId
INNER JOIN sEExam.tTestMaster TM ON TA.TestId = TM.Id
INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = TM.ClassSubjectId
WHERE StatusId = 1 
AND  IsActiveBatch = 1 
AND IsBlockAllAlert = 0 
AND OrgGroupBatchId = @rOrgGroupBatchId 
AND TA.TestId = @rTestId
AND TA.SourceTypeId = 2005

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pEmailConfigurationAdd]
	
	@rOrgId smallint,
	@rMailTypeId tinyint,
	@rSMTPServer nvarchar(500),
	@rSMTPPort int,
	@rEnableSSL bit,
	@rSendUserName nvarchar(200),
	@rSendPassword nvarchar(200),
	@rFromMail nvarchar(200),
	@rOrgGroupId smallint,
	@rIsAllOrg bit,
	@rAPIKey nvarchar(200)='',
	@rSecretKey nvarchar(200)='',
	@rIsAuthenticateUsername bit = 0,
	@rDisplayName nvarchar(200) = '',
	@rIsPrimaryAccount bit = 0,
	@rIsObsolete bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 IF(@rIsAllOrg=1)
	 BEGIN
		DECLARE @lCount INT
		
		CREATE TABLE #tTable  
		(
			Id bigint identity,
			OrgId smallint
		)
		INSERT INTO #tTable
		(
			OrgId
		)
		SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId
		
		SELECT @lCount =  COUNT(Id) FROM #tTable
		WHILE @lCount > 0 
		BEGIN
			SELECT @rOrgId=OrgId FROM #tTable WHERE Id = @lCount
					
		IF NOT EXISTS(SELECT OrgId FROM sAlert.tEmailConfiguration WHERE OrgId=@rOrgId AND IsPrimaryAccount = 1 AND MailTypeId = @rMailTypeId)
		BEGIN
			IF NOT EXISTS(SELECT OrgId FROM sAlert.tEmailConfiguration WHERE OrgId=@rOrgId AND MailTypeId = @rMailTypeId)
			BEGIN
				INSERT INTO sAlert.tEmailConfiguration
				(
					OrgId,
					MailTypeId,
					SMTPServer,
					SMTPPort,
					EnableSSL,
					SendUserName,
					SendPassword,
					FromMail,
					APIKey,
					SecretKey,
					IsAuthenticateUsername,
					DisplayName,					
					IsObsolete
				)
				VALUES
				(
					@rOrgId,
					@rMailTypeId,
					@rSMTPServer,
					@rSMTPPort,
					@rEnableSSL,
					@rSendUserName,
					@rSendPassword,
					@rFromMail,
					@rAPIKey,
					@rSecretKey,
					@rIsAuthenticateUsername,
					@rDisplayName,					
					@rIsObsolete
				)
			END				 
			ELSE
			BEGIN
				UPDATE  sAlert.tEmailConfiguration
				SET
					MailTypeId=@rMailTypeId,
					SMTPServer=@rSMTPServer,
					SMTPPort=@rSMTPPort,
					EnableSSL=@rEnableSSL,
					SendUserName=@rSendUserName,
					SendPassword=@rSendPassword,
					FromMail=@rFromMail,
					APIKey=@rAPIKey,
					SecretKey=@rSecretKey,
					IsAuthenticateUsername = @rIsAuthenticateUsername,
					DisplayName=@rDisplayName,					
					IsObsolete = @rIsObsolete
				WHERE OrgId = @rOrgId AND MailTypeId = @rMailTypeId	   
			END
		END  
			SELECT @rOrgId AS Result
			SET @lCount = @lCount - 1
		END
	 END
	 ELSE
	 BEGIN
	IF NOT EXISTS(SELECT OrgId FROM sAlert.tEmailConfiguration WHERE OrgId=@rOrgId AND MailTypeId = @rMailTypeId)
	BEGIN
		INSERT INTO sAlert.tEmailConfiguration
			(
				OrgId,
				MailTypeId,
				SMTPServer,
				SMTPPort,
				EnableSSL,
				SendUserName,
				SendPassword,
				FromMail,
				APIKey,
				SecretKey,
				IsAuthenticateUsername,
				DisplayName,
				IsPrimaryAccount,
				IsObsolete
			)
		VALUES
			(
				@rOrgId,
				@rMailTypeId,
				@rSMTPServer,
				@rSMTPPort,
				@rEnableSSL,
				@rSendUserName,
				@rSendPassword,
				@rFromMail,
				@rAPIKey,
				@rSecretKey,
				@rIsAuthenticateUsername,
				@rDisplayName,
				@rIsPrimaryAccount,
				@rIsObsolete
			)
		END	 
	 ELSE
		 BEGIN
			UPDATE  sAlert.tEmailConfiguration
			SET
				MailTypeId=@rMailTypeId,
				SMTPServer=@rSMTPServer,
				SMTPPort=@rSMTPPort,
				EnableSSL=@rEnableSSL,
				SendUserName=@rSendUserName,
				SendPassword=@rSendPassword,
				FromMail=@rFromMail,
				APIKey=@rAPIKey,
				SecretKey=@rSecretKey,
				IsAuthenticateUsername = @rIsAuthenticateUsername,
				DisplayName = @rDisplayName,
				IsPrimaryAccount = @rIsPrimaryAccount,
				IsObsolete = @rIsObsolete
		      
			  WHERE OrgId = @rOrgId AND MailTypeId = @rMailTypeId	   
		 END  

	IF(@rIsPrimaryAccount = 1)
	BEGIN
		UPDATE sAlert.tEmailConfiguration SET IsPrimaryAccount = 0 WHERE OrgId <> @rOrgId
		UPDATE sAlert.tEmailConfiguration SET IsPrimaryAccount = 0 WHERE OrgId = @rOrgId AND MailTypeId <> @rMailTypeId
	END

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAlert].[pEmailConfigurationGet]
	 
	 @rOrgId smallint,
	 @rIsPrimaryAccount bit = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	IF(@rIsPrimaryAccount = 1)
	BEGIN
		DECLARE @lOrgGroupId int = (SELECT OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId)
		IF EXISTS(SELECT 1 FROM sAlert.tEmailConfiguration EC INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId WHERE EC.IsPrimaryAccount = 1 AND ISNULL(EC.IsObsolete,0) = 0 AND OM.OrgGroupId = @lOrgGroupId)
		BEGIN
		SELECT
				EC.MailTypeId,
				EC.SMTPServer,
				EC.SMTPPort,
				EC.EnableSSL,
				EC.SendUserName,
				EC.SendPassword,
				EC.FromMail,
				EC.OrgId,
				ISNULL(EC.APIKey,'') AS APIKey,
				ISNULl(EC.SecretKey,'') AS SecretKey,
				ISNULL(EC.IsAuthenticateUsername,0) AS IsAuthenticateUsername,
				ISNULl(EC.DisplayName,'') AS DisplayName
		FROM
				sAlert.tEmailConfiguration EC
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
		WHERE 
				EC.IsPrimaryAccount = 1 AND ISNULL(EC.IsObsolete,0) = 0 AND OM.OrgGroupId = @lOrgGroupId
		END
		ELSE
		BEGIN
			SELECT
				EC.MailTypeId,
				EC.SMTPServer,
				EC.SMTPPort,
				EC.EnableSSL,
				EC.SendUserName,
				EC.SendPassword,
				EC.FromMail,
				@rOrgId AS OrgId,
				ISNULL(EC.APIKey,'') AS APIKey,
				ISNULl(EC.SecretKey,'') AS SecretKey,
				ISNULL(EC.IsAuthenticateUsername,0) AS IsAuthenticateUsername,
				ISNULl(EC.DisplayName,'') AS DisplayName
			FROM
					sAlert.tEmailConfiguration EC
			WHERE 
					EC.OrgId=@rOrgId AND ISNULL(IsObsolete,0) = 0
		END
	END
	ELSE
	BEGIN
		SELECT
				EC.MailTypeId,
				EC.SMTPServer,
				EC.SMTPPort,
				EC.EnableSSL,
				EC.SendUserName,
				EC.SendPassword,
				EC.FromMail,
				@rOrgId AS OrgId,
				ISNULL(EC.APIKey,'') AS APIKey,
				ISNULl(EC.SecretKey,'') AS SecretKey,
				ISNULL(EC.IsAuthenticateUsername,0) AS IsAuthenticateUsername,
				ISNULl(EC.DisplayName,'') AS DisplayName
		FROM
				sAlert.tEmailConfiguration EC
		WHERE 
				EC.OrgId=@rOrgId AND ISNULL(IsObsolete,0) = 0
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pEmailConfigurationMasterGet]
	 
	 @rOrgId smallint = 0,
	 @rMailTypeId smallint = 0,
	 @rOrgGroupId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 

	SELECT
			EC.MailTypeId,
			EC.SMTPServer,
			EC.SMTPPort,
			EC.EnableSSL,
			EC.SendUserName,
			EC.SendPassword,
			EC.FromMail,
			--@rOrgId AS OrgId,
			ISNULL(EC.APIKey,'') AS APIKey,
			ISNULl(EC.SecretKey,'') AS SecretKey,
			ISNULL(EC.IsAuthenticateUsername,0) AS IsAuthenticateUsername,
			ISNULl(EC.DisplayName,'') AS DisplayName,
			ISNULL(MTM.Title,'') AS MailType,
			ISNULL(EC.IsPrimaryAccount,0) AS IsPrimaryAccount,
			ISNULL(EC.IsObsolete,0) AS IsObsolete,
			EC.OrgId,
			OM.DisplayTitle AS Organization
	FROM
			sAlert.tEmailConfiguration EC
			INNER JOIN sAlert.tMailTypeMaster MTM ON MTM.Id = EC.MailTypeId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
	WHERE 
			(EC.OrgId=@rOrgId OR @rOrgId = 0)
			AND ((EC.MailTypeId = @rMailTypeId) OR (@rMailTypeId = 0))
			AND OM.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
		if(@rEventId=0)
		begin 
			set @rEventId=135
		end
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

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

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

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

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

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						CreatedDateTime [datetime] NOT NULL,--For Optimization
						AutoId bigint not null--For Optimization
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId
				,min(CDT.CreatedDateTime),min(CDT.Autoid) --For Optimization
				from [sBiometric].[tCloudTransactionData] CDT
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 
				--For Optimization
				AND CDT.Autoid>@lCloudTransactionDataId
				--AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=95 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))
				--For Optimization
				Group by SourceId,SourceTypeId
			END
			
			--For Optimization
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				'' AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS StudentName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				sHrm.vEmployeeCommonDetail EM 
				Inner Join  [sHrm].[tEmployeeMaster] E on EM.EmployeeId=E.Id
				INNER JOIN #tShift tempshift ON tempshift.ShiftCode=E.ShiftId
				LEFT JOIN #tTable temp ON  temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				LEFT JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				EM.OrgID =@rOrgId
				AND temp.In_Out_Time is null
				AND E.StatusId = 7  -- Added
				AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<>'W')
				AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<> 'H')

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeBiometricFirstInLastOutListGet]
	@rEventId int,--127 for firstin 128 LastOut
	@rOrgId int,
	@rTemplate nvarchar(max),
	@rDate dateTime,
	@rMailSubject nvarchar(max)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--set @rDate=cast(@rDate as datetime)

	DECLARE @lDay as nvarchar(3)

	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	if(@rEventId=127)
	begin
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	end
	else if(@rEventId=128)
	begin
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_Out'
	end
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query = 'SELECT
					EC.EmployeeId AS AcademicId,
					EC.MobileNumber AS MobileNo,	
					EC.CompanyEmail AS EmailId,
					replace (
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[EmployeeName]'',EC.EmployeeName),
					''[PresentTime]'','+@lColumnName+'),
					''[TimeStamp]'','+@lColumnName+'),
					''[PresentDate]'','''+ISNULL(CONVERT(varchar,@rDate,103),'''')+''')
					 AS Template,
					 '''+@rMailSubject+''' as MailSubject,
					95 AS ReceiverSourceTypeId,
					EC.EmployeeId AS ReceiverSourceId,
					EC.EmployeeName AS Name,
					ISNULL(EC1.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EC.EmployeeId AS SourceId,
					EC.OrgId,
					OM.OrgGroupId,
					EM.Id AS EmployeeId,
					EM.Code,
					OM.Title AS SchoolName,
					OM.DisplayTitle AS OrganizationTitle
		FROM 
				sHrm.tEmployeeMaster EM
				Inner join sHrm.vEmployeeCommonDetail EC ON EM.Id=EC.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC1 ON EC1.EmployeeId = EC.EmployeeId
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = EM.Id AND MT.SourceTypeId = 95 
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				INNER Join sBiometric.tShiftMasterCloud SM ON SM.ShiftName='+CONVERT(nvarchar(20),@lShiftColumntName)+'
		WHERE
				EM.OrgID = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MT.Attn_dt=cast(rtrim(YEAR('''+CONVERT(nvarchar(20),@rDate)+''') *10000+ Month('''+CONVERT(nvarchar(20),@rDate)+''') *100+ 01) as datetime)
				And '+@lColumnName+' <> ''00:00'' 
				AND EM.StatusId = 7	'
		print (@Query)
		execute (@Query)	


	
END

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

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

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

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

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

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

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


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null
 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=128 and SourceTypeId=95),0)
			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=128 AND OrgId=@rOrgId and AlertModeId = 1 ),'')
			--declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)
	 
			--select * from #tShift
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						OutTimeAlertTime time NOT NULL,
						CreatedDateTime [datetime] NOT NULL,
				AutoId bigint not null
					)
			--if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,cast(SMC.OutTimeAlertTime as time),Max(CreatedDateTime) ,min(CDT.Autoid)
				from [sBiometric].[tCloudTransactionData] CDT 
				INNER JOIN sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 
				AND SMC.IsOutTimeAlertTime=1
				AND CAST(OutTimeAlertTime AS Time) > CAST(CDT.In_Out_Time AS Time)
				Group by SourceId,SourceTypeId,SMC.OutTimeAlertTime
			END

			--select * from #tTable
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				'' AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS StudentName,
				EM.Code AS Code,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				128,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				
				temp.OutTimeAlertTime < cast(@rToDateTime as Time)
				AND temp.OutTimeAlertTime >= Cast(@rFromDateTime As Time)
				AND EM.OrgID =@rOrgId

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


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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		 @rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)='',
		@rEventId int=137,
		@rShiftCode int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay as nvarchar(3)

	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 398 AND SourceId = @rOrgId

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
	--IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	--BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	print (@Query)
	SET @Query = 'SELECT
					EC.MobileNumber AS MobileNo,	
					EC.CompanyEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lSMSTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS SMSText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lMailTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MailText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lNotificationTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS NotificationText,
					  replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lWhatsappTemplete)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS WhatsappText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					95 AS ReceiverSourceTypeId,
					EC.EmployeeId AS ReceiverSourceId,
					EC.EmployeeName AS EmployeeName,
					ISNULL(EC1.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EC.EmployeeId AS SourceId,
					EC.OrgId,
					OM.OrgGroupId,
					EM.Id AS EmployeeId,
					EM.Code,
					ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS  EmployeeName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle
		FROM 
				sHrm.tEmployeeMaster EM
				Inner join sHrm.vEmployeeCommonDetail EC ON EM.Id=EC.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC1 ON EC1.EmployeeId = EC.EmployeeId
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = EM.Id AND MT.SourceTypeId = 95 
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				INNER Join sBiometric.tShiftMasterCloud SM ON SM.ShiftName='+CONVERT(nvarchar(20),@lShiftColumntName)+' And (SM.ShiftCode='+CONVERT(nvarchar(20),@rShiftCode)+' OR '+CONVERT(nvarchar(20),@rShiftCode)+'=0)
		WHERE
				EM.OrgID = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				AND '+@lColumnName+' > DATEADD(minute, SM.GraceAfter,SM.StartTime)
				--AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND EM.StatusId = 7	
				--add for 29339 mantis
				AND YEAR(MT.Attn_dt) = YEAR('''+CONVERT(nvarchar(20),@lDate)+''')'
		print (@Query)
		execute (@Query)	
	--END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeBirthdayAllGet]	
		 @rDepartmentId INT,
	 	 @rOrgId INT,
	 	 @rTemplate NVARCHAR(MAX)
	 	 
	WITH EXECUTE AS CALLER
AS

SET NOCOUNT ON

BEGIN
	DECLARE @rCount INT = (SELECT COUNT(*) FROM sHrm.vEmployeeCommunication WHERE DAY(DateOfBirth) = DAY(sCommon.fGetDate()) AND (MONTH(DateOfBirth) = MONTH(sCommon.fGetDate())))
	
	IF(@rCount>1)
	BEGIN
		IF OBJECT_ID('tempdb..#tEmployeeBirthdayTable') IS NOT NULL DROP TABLE #tEmployeeBirthdayTable
		CREATE TABLE #tEmployeeBirthdayTable  
			(
				ID INT IDENTITY(1, 1),
				EmployeeId BIGINT,
				EmployeeName Nvarchar(201),
				DateOfBirth Date
			)
		INSERT INTO #tEmployeeBirthdayTable
			(   
				EmployeeId,
				EmployeeName,
				DateOfBirth
			)
		SELECT 
			EC.EmployeeId,
			EC.EmployeeName,
			EC.DateOfBirth
		FROM 
			sHrm.vEmployeeCommunication EC
			INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
		WHERE
			((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (EC.OrgId=@rOrgId)
			AND (EC.StatusId=7)
			AND (DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
			AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
					
		DECLARE @rCount1 INT = (Select COUNT(*) from #tEmployeeBirthdayTable )

		CREATE TABLE #tempEmployeeTable  
			(
				AcademicId BIGINT,	
				Code NVARCHAR(20),
				Name NVARCHAR(201),
				MobileNo NVARCHAR(20),
				EmailId NVARCHAR(100),
				Template NVARCHAR(500),
				SchoolName NVARCHAR(100),
				WhatsAppContactNo NVARCHAR(20),
				DateOfBirth DATE
			)
		
		WHILE(@rCount1 > 0)
		BEGIN
			DECLARE @rEmployeeId BIGINT = (Select EmployeeId from #tEmployeeBirthdayTable WHERE ID = @rCount1)

			INSERT INTO #tempEmployeeTable
			(   
				AcademicId,	
				Code,
				Name,
				MobileNo,
				EmailId,
				Template,
				SchoolName,
				WhatsAppContactNo,
				DateOfBirth 
			)
			SELECT 
				EC.EmployeeId AS AcademicId,
				EC.Code,
				EC.EmployeeName AS Name,
				EC.MobileNumber AS MobileNo,	
				EC.CompanyEmail AS EmailId,
				REPLACE(REPLACE(@rTemplate,'[Name]',
				(SELECT EmployeeName FROM #tEmployeeBirthdayTable 
				 WHERE EmployeeId=@rEmployeeId AND DAY(DateOfBirth) = DAY(sCommon.fGetDate()) AND (MONTH(DateOfBirth) = MONTH(sCommon.fGetDate())))),'[SchoolName]',OM.Title)
				AS Template,
				OM.Title AS SchoolName,
				EC.WhatsAppContactNo,
				EC.DateOfBirth
			FROM 
				sHrm.vEmployeeCommunication EC
				INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
			WHERE
				((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND (EC.OrgId=@rOrgId)
				AND (EC.StatusId=7)
				AND EXISTS(
							SELECT 1 FROM 
							sHrm.vEmployeeCommunication EC
							INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
							WHERE
								((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
								AND (EC.OrgId=@rOrgId)
								AND (DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
								AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
								AND (EC.StatusId=7)
							)
			ORDER BY EC.DateOfBirth DESC

			SET @rCount1 = @rCount1 - 1
			
		END

		SELECT * from #tempEmployeeTable

	END

	ELSE
		BEGIN
			SELECT 
			EC.EmployeeId AS AcademicId,
			EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			REPLACE(REPLACE(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title)
			AS Template,
			OM.Title AS SchoolName,
			EC.WhatsAppContactNo,
			EC.DateOfBirth
			FROM 
				sHrm.vEmployeeCommunication EC
				INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
			WHERE
				((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND (EC.OrgId=@rOrgId)
				AND (DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
				AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
				AND (EC.StatusId=7)

			UNION
			
			SELECT 
				EC.EmployeeId AS AcademicId,
				EC.Code,
				EC.EmployeeName AS Name,
				EC.MobileNumber AS MobileNo,	
				EC.CompanyEmail AS EmailId,
				REPLACE(REPLACE(@rTemplate,'[Name]',(SELECT EmployeeName FROM sHrm.vEmployeeCommunication WHERE DAY(DateOfBirth) = DAY(sCommon.fGetDate()) AND (MONTH(DateOfBirth) = MONTH(sCommon.fGetDate())))),'[SchoolName]',OM.Title)
				AS Template,
				OM.Title AS SchoolName,
				EC.WhatsAppContactNo,
				EC.DateOfBirth
			FROM 
				sHrm.vEmployeeCommunication EC
				INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
			WHERE
				((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND (EC.OrgId=@rOrgId)
				AND (EC.StatusId=7)
				AND EXISTS(
							SELECT 1 FROM 
							sHrm.vEmployeeCommunication EC
							INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
							WHERE
								((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
								AND (EC.OrgId=@rOrgId)
								AND (DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
								AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
								AND (EC.StatusId=7)
							)
			ORDER BY EC.DateOfBirth DESC
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeBirthdayAllSchedulerGet]
	 	 
	 	 @rOrgId SMALLINT,
	 	 @rTemplate NVARCHAR(MAX),
	 	 @rMailSubject NVARCHAR(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @rCount INT = (SELECT COUNT(*) FROM sHrm.vEmployeeCommunication WHERE DAY(DateOfBirth) = DAY(sCommon.fGetDate()) AND (MONTH(DateOfBirth) = MONTH(sCommon.fGetDate())))

	IF(@rCount>1)
	BEGIN
		IF OBJECT_ID('tempdb..#tEmployeeBirthTable') IS NOT NULL DROP TABLE #tEmployeeBirthTable
		
		CREATE TABLE #tEmployeeBirthTable  
			(
				ID INT IDENTITY(1, 1),
				EmployeeId BIGINT,
				EmployeeName Nvarchar(201),
				DateOfBirth Date
			)
		INSERT INTO #tEmployeeBirthTable
			(   
				EmployeeId,
				EmployeeName,
				DateOfBirth
			)
		SELECT 
			EC.EmployeeId,
			EC.EmployeeName,
			EC.DateOfBirth
		FROM 
			sHrm.vEmployeeCommunication EC
			INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
		WHERE
			(DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
			AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
			AND (EC.StatusId=7)
			AND (EC.OrgId=@rOrgId)

		DECLARE @rCount1 INT = (Select COUNT(*) from #tEmployeeBirthTable )

		CREATE TABLE #tempEmpTable  
			(
				MobileNo NVARCHAR(20),	
				EmailId NVARCHAR(100),
				MsgText NVARCHAR(500),
				Subject NVARCHAR(30),
				OrgGroupId SMALLINT,
				OrgId SMALLINT,
				SourceId BIGINT,
				SourceTypeId INT,
				ReceiverSourceId BIGINT,
				ReceiverSourceTypeId INT,
				Name NVARCHAR(201),
				SchoolName NVARCHAR(100),
				WhatsAppContactNo NVARCHAR(20),
				DateOfBirth DATE
			)

		WHILE(@rCount1 > 0)
		BEGIN
			DECLARE @rEmployeeId BIGINT = (Select EmployeeId from #tEmployeeBirthTable WHERE ID = @rCount1)

			INSERT INTO #tempEmpTable
			(   
				MobileNo,	
				EmailId,
				MsgText,
				Subject,
				OrgGroupId,
				OrgId,
				SourceId,
				SourceTypeId,
				ReceiverSourceId,
				ReceiverSourceTypeId,
				Name,
				SchoolName,
				WhatsAppContactNo,
				DateOfBirth
			)
			SELECT 
			EC.MobileNumber AS MobileNo,		
			(CASE WHEN ISNULL(EC.PersonalEmail,'')='' THEN EC.CompanyEmail
			ELSE EC.PersonalEmail END) AS EmailId,
			REPLACE(REPLACE(@rTemplate,'[Name]',(SELECT EmployeeName FROM #tEmployeeBirthTable 
			WHERE EmployeeId=@rEmployeeId AND DAY(DateOfBirth) = DAY(sCommon.fGetDate()) AND (MONTH(DateOfBirth) = MONTH(sCommon.fGetDate())))),'[SchoolName]',OM.Title)
			AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeName AS [Name],
			OM.Title AS SchoolName,
			EC.WhatsAppContactNo AS WhatsAppContactNo,
			EC.DateOfBirth

		FROM 
			sHrm.vEmployeeCommunication EC
			INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
		WHERE 
			(EC.StatusId=7)
			AND (EC.OrgId=@rOrgId)
			AND EXISTS(
							SELECT 1 FROM 
							sHrm.vEmployeeCommunication EC
							INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
							WHERE
								(EC.OrgId=@rOrgId)
								AND (DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
								AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
								AND (EC.StatusId=7)
							)
			ORDER BY EC.DateOfBirth DESC

			SET @rCount1 = @rCount1 - 1
			
		END

		SELECT * from #tempEmpTable
	END

	ELSE
	BEGIN
		SELECT 
			EC.MobileNumber AS MobileNo,		
			(CASE WHEN ISNULL(EC.PersonalEmail,'')='' THEN EC.CompanyEmail
			ELSE EC.PersonalEmail END) AS EmailId,
			REPLACE(REPLACE(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title) AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeName AS [Name],
			OM.Title AS SchoolName,
			EC.WhatsAppContactNo AS WhatsAppContactNo,
			EC.DateOfBirth

		FROM 
			sHrm.vEmployeeCommunication EC
			INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
		WHERE
			(DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
			AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
			AND (EC.StatusId=7)
			AND (EC.OrgId=@rOrgId)

		UNION

		SELECT 
			EC.MobileNumber AS MobileNo,		
			(CASE WHEN ISNULL(EC.PersonalEmail,'')='' THEN EC.CompanyEmail
			ELSE EC.PersonalEmail END) AS EmailId,
			REPLACE(REPLACE(@rTemplate,'[Name]',(Select EmployeeName from sHrm.vEmployeeCommunication where DAY(DateOfBirth) = DAY(sCommon.fGetDate()) AND (MONTH(DateOfBirth) = MONTH(sCommon.fGetDate())))),'[SchoolName]',OM.Title) AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeName AS [Name],
			OM.Title AS SchoolName,
			EC.WhatsAppContactNo AS WhatsAppContactNo,
			EC.DateOfBirth

		FROM 
			sHrm.vEmployeeCommunication EC
			INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
		WHERE 
				(EC.StatusId=7)
			AND (EC.OrgId=@rOrgId)
			AND EXISTS(SELECT 1 FROM 
						sHrm.vEmployeeCommunication EC
						INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
						WHERE (EC.OrgId=@rOrgId)
							AND (DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
							AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
							AND (EC.StatusId=7)
						)

		ORDER BY EC.DateOfBirth DESC
	END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeBirthdayWishGet]
	 	 
	 	 @rDepartmentId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rDateOfBirth date
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			EC.EmployeeId AS AcademicId,
			EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			replace(replace(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title)
			 AS Template,
			 OM.Title AS SchoolName,
			 EC.WhatsAppContactNo
		
		
	From 
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
	WHERE
			((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (EC.OrgId=@rOrgId)
		AND (DAY(EC.DateOfBirth) = DAY(@rDateOfBirth))
		AND (MONTH(EC.DateOfBirth) = MONTH(@rDateOfBirth))
		AND (EC.StatusId=7)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeBirthdayWishSchedulerGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			EC.MobileNumber AS MobileNo,	
			--EC.PersonalEmail AS EmailId,			
			(CASE WHEN ISNULL(EC.PersonalEmail,'')='' THEN EC.CompanyEmail
			ELSE EC.PersonalEmail END) AS EmailId,
			replace(replace(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title)
			AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeName AS [Name],
			OM.Title AS SchoolName,
			EC.WhatsAppContactNo AS WhatsAppContactNo,
			'' AS AttachMent
		
	From 
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
	WHERE
			(DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		AND (EC.StatusId=7)
		AND (EC.OrgId=@rOrgId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeDetailGet]
	 
	 @rDepartmentId int,
	 @rOrgId int,
	 @rHouseIds nvarchar(max) = '', 
	 @rClubIds nvarchar(max) = '', 
	 @rCommitteeIds nvarchar(max) = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF(@rDepartmentId = 0 and @rHouseIds = '' and @rClubIds = '' and @rCommitteeIds = '')
	BEGIN
		SELECT
				ODM.Id,
				ODM.Title	
		FROM
				sSetup.tDepartmentMaster ODM
		WHERE 
				ODM.IsObsolete = 0
			AND ODM.OrgId=@rOrgId ORDER BY ODM.Title
	END
	ELSE IF(@rHouseIds != '')
	BEGIN
	
		SELECT 
			Distinct
				EM.Id,
				EM.FirstName+' '+EM.LastName AS Title,
				EM.Code
			
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=EJD.OrganizationDepartmentId AND ODM.Id=@rDepartmentId
			INNER JOIN sHrm.tAssignHouse AH ON EM.Id = AH.EmployeeId
		WHERE 		
				EM.OrgId=@rOrgId 
			AND EM.StatusId=7
			AND ISNULL(EM.IsOtherUser,0) = 0 
			--AND ((ODM.Id=@rDepartmentId) OR (@rDepartmentId = 0))	--mantis: 38927, comment this line and add in inner join
			AND (ISNULL(AH.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseIds,','))OR @rHouseIds='')
			ORDER BY EM.Code
	END
	ELSE IF(@rClubIds != '')
	BEGIN
		SELECT 
			Distinct
				EM.Id,
				EM.FirstName+' '+EM.LastName AS Title,
				EM.Code
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=EJD.OrganizationDepartmentId AND ODM.Id=@rDepartmentId
			INNER JOIN sHrm.tAssignClub AC ON EM.Id = AC.EmployeeId
		WHERE 		
				EM.OrgId=@rOrgId 
			AND EM.StatusId=7
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubIds,','))OR @rClubIds='')
			ORDER BY EM.Code
	END
	ELSE IF(@rCommitteeIds != '')
	BEGIN
		SELECT 
			Distinct
				EM.Id,
				EM.FirstName+' '+EM.LastName AS Title,
				EM.Code
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=EJD.OrganizationDepartmentId AND ODM.Id=@rDepartmentId
			INNER JOIN sHrm.tAssignCommittee AC ON EM.Id = AC.EmployeeId
		WHERE 		
				EM.OrgId=@rOrgId 
			AND EM.StatusId=7
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND (ISNULL(AC.CommitteeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCommitteeIds,','))OR @rCommitteeIds='')
			ORDER BY EM.Code
	END
	ELSE
	BEGIN
		SELECT 
				EM.Id,
				EM.FirstName+' '+EM.LastName AS Title
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=EJD.OrganizationDepartmentId AND ODM.Id=@rDepartmentId
		WHERE 		
				EM.OrgId=@rOrgId 
			AND EM.StatusId=7
			AND ISNULL(EM.IsOtherUser,0) = 0 
				ORDER BY EM.Code
	END


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeEntryGet]
	 	 
		 @rEmployeeId bigint, 	  	 	 	
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			EM.OrgId,
			EM.EmployeeId,
			EM.Code,
			EM.EmployeeName,
			ISNULL(EC.MobileNumber,'') AS MobileNo,	
			ISNULL(EC.CompanyEmail,'') AS EmailId,				
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EM.EmployeeName),			
			'[Code]',EM.Code),			
			'[JoiningDate]',EM.DateOfJoining),
			'[Department]',EM.DepartmentName)
			 AS MsgText,
			'95' AS ParticipantSourceTypeId,
			EM.EmployeeId AS SourceId,
			@rMailSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			ISNULL(EM.EmployeeId,0) AS ReceiverSourceId,
			EM.EmployeeName AS Name,
			EM.DateOfJoining AS JoiningDate,
			EM.DepartmentName AS Department,
			ISNULL(EC.WhatsAppContactNo ,'') AS WhatsAppContactNo
		
		
	From 
		sHrm.vExtEmployeeMaster EM	
		INNER JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId
	WHERE
	(EM.EmployeeId= @rEmployeeId)
	AND (EM.OrgID=@rOrgId)	
	AND (EM.StatusId=7)	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeGatePassGet]
	
		 @rEmployeeGatePassId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max)
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			EM.OrgId AS OrgId,
			OM.OrgGroupId,
			OM.DisplayTitle AS Organization,
			EG.Id,
			EM.Code,
			EM.FirstName+' '+EM.MiddleName+' '+EM.LastName AS Name,
			EG.EmployeeId,
			EG.ReasonOfGatePass,
			EG.GatePassDate,
			EC.CompanyEmail AS EmailId,
			EC.MobileNumber AS MobileNo,
			ISNULL(EG.ReturnGatePassDate,'') AS ReturnGatePassDate,
			EG.GatePassTime,
			ISNULL(EG.ReturnGatePassTime,'') AS ReturnGatePassTime,
			EG.EntryModeStatusId,
			SM.Title AS EntryModeStatus,
			95 AS SourceTypeId,
			EM.Id AS SourceId,
			95 AS ReceiverSourceTypeId,
			EM.Id AS ReceiverSourceId,
			EC.WhatsAppContactNo AS WhatsAppContactNo,
			'' AS Subject,
				replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EM.FirstName+' '+EM.MiddleName+' '+EM.LastName),
			'[EntryModeStatus]',SM.Title),
			'[GatePassDate]',CONVERT(varchar(11),ISNULL(EG.GatePassDate,'') ,103)),
			'[GatePassTime]',CONVERT(varchar(15),ISNULL(EG.GatePassTime,''),100)),
			'[ReasonOfGatePass]',EG.ReasonOfGatePass)
			AS MsgText

	FROM 
	sFrontOffice.tEmployeeGatePass EG 
		    INNER JOIN  sHrm.tEmployeeMaster EM ON EG.EmployeeId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EG.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=EG.EntryModeStatusId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EG.EmployeeId
	WHERE
		EG.Id=@rEmployeeGatePassId
		AND ((EG.OrgId=@rOrgId) OR (@rOrgId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


 
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeLeaveGet]
	
	 	 @rLeaveId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rEmployeeId bigint,
         @rBatchId int,
         @rOrgId int,
         @rStatusId int,
         @rSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lUserId bigint=0
	SELECT @lUserId = Id FROM sSecurity.tUser WHERE SourceId = @rEmployeeId AND SourceTypeId = 95
	
	SELECT 
			EM.EmployeeId,
			EM.Code,
			EM.EmployeeName,
			EM.MobileNumber AS MobileNo,	
			CASE
		    WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1) LIKE ',%,' THEN stuff(stuff(ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), 1, 1, ''),LEN(stuff(ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), 1, 1, '')),1,'')
            WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1) LIKE ',%' THEN stuff(ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), 1, 1, '')
			WHEN ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1) LIKE '%,' THEN stuff(ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1), LEN(ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1)), 1, '')
			ELSE ISNULL(EM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,37,1)
			END AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EM.EmployeeName),
			'[EmployeeManagerName]',ISNULL(vEM.EmployeeName,'')),
			'[FromDate]',Convert(Varchar,L.FromDate,103)), --Changed HomeWorkEndDate format as dd-MM-yyyy for mantis : 40576
			'[ToDate]',Convert(Varchar,L.FromDate,103)), --Changed HomeWorkEndDate format as dd-MM-yyyy for mantis : 40576
			'[LeaveRemark]',ISNULL(L.LeaveRemark,'')),
			'[LeaveReason]',ISNULL(L.LeaveReason,''))
			 AS MsgText,
			@rSubject AS Subject,
			(SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=@rOrgId) AS OrgGroupId,@rOrgId AS OrgId,
			 @rEmployeeId AS SourceId, 95 AS SourceTypeId,
			 95 AS ReceiverSourceTypeId,
			 @rEmployeeId AS ReceiverSourceId,
			 ISNULL(vEM.EmployeeName,'') AS EmployeeManagerName,
			 L.FromDate AS FromDate,
			 L.ToDate AS ToDate,
			 ISNULL(L.LeaveRemark,'') AS LeaveRemark,
			 ISNULL(L.LeaveReason,'') AS LeaveReason,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			 EM.EmployeeName AS Name
	FROM 
		sHrm.vEmployeeCommonDetail EM
	INNER JOIN [sHrm].[tLeave] L ON  EM.EmployeeId = L.EmployeeId
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
    LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId	
	LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = L.EmployeeId
	WHERE
		L.Id = @rLeaveId 
		AND L.EmployeeId=@rEmployeeId
		AND L.OrgId=@rOrgId
		AND L.BatchId=@rBatchId
		AND ((L.StatusId = @rStatusId) OR (@rStatusId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


 
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeManagerGet]
	
	 	 @rLeaveId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rEmployeeId bigint,
         @rBatchId int,
         @rOrgId int,
         @rStatusId int,
         @rSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lUserId bigint=0
	SELECT @lUserId = Id FROM sSecurity.tUser WHERE SourceId = @rEmployeeId AND SourceTypeId = 95
	
	SELECT 
			ISNULL(vEM.EmployeeId,0) AS EmployeeId,
			ISNULL(vEM.Code,'') AS Code,
			ISNULL(vEM.EmployeeName,'') AS EmployeeName,
		    --CASE
            --WHEN ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,2) LIKE ',%,' THEN stuff(stuff(ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,2), 1, 1, ''),LEN(stuff(ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,2), 1, 1, '')),1,'')
            --WHEN ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,2) LIKE ',%' THEN stuff(ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,2), 1, 1, '')
            --WHEN ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,2) LIKE '%,' THEN stuff(ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,2), LEN(ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,2)), 1, '')
            --ELSE ISNULL(vEM.MobileNumber,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,2)
            --END AS MobileNo,
			ISNULL(vEM.MobileNumber,'') AS MobileNo,	
			[sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,2) AS OtherMobileNo,	
			CASE
		    WHEN ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,1) LIKE ',%,' THEN stuff(stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,1), 1, 1, ''),LEN(stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,1), 1, 1, '')),1,'')
            WHEN ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,1) LIKE ',%' THEN stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,1), 1, 1, '')
			WHEN ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,1) LIKE '%,' THEN stuff(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,1), LEN(ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,1)), 1, '')
			ELSE ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,1)
			END AS EmailId,
			--ISNULL(vEM.CompanyEmail,'') +','+ [sAlert].[fAssociateRecipientMobileNoAndEmailGet](@lUserId,40,1) AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EM.EmployeeName),
			'[EmployeeManagerName]',ISNULL(vEM.EmployeeName,'')),
			--'[FromDate]',L.FromDate),
			--'[ToDate]',L.ToDate),
			'[FromDate]',Convert(Varchar,L.FromDate,103)), --Changed HomeWorkEndDate format as dd-MM-yyyy for mantis : 40576
			'[ToDate]',Convert(Varchar,L.FromDate,103)), --Changed HomeWorkEndDate format as dd-MM-yyyy for mantis : 40576
			'[LeaveRemark]',ISNULL(L.LeaveRemark,'')),
			'[LeaveReason]',ISNULL(L.LeaveReason,''))
			 AS MsgText,
			@rSubject AS Subject,
			(SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=@rOrgId) AS OrgGroupId,@rOrgId AS OrgId,
			-- @rEmployeeId AS SourceId, 
			EJD.EmployeeManagerId AS SourceId, 
			 95 AS SourceTypeId,
			 95 AS ReceiverSourceTypeId,
			 EJD.EmployeeManagerId AS ReceiverSourceId,
			 ISNULL(vEM.EmployeeName,'') AS EmployeeManagerName,
			 L.FromDate AS FromDate,
			 L.ToDate AS ToDate,
			 ISNULL(L.LeaveRemark,'') AS LeaveRemark,
			 ISNULL(L.LeaveReason,'') AS LeaveReason,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			 EM.EmployeeName AS Name
	FROM 
		sHrm.tLeave L
		INNER JOIN sHrm.vEmployeeCommonDetail EM  ON  EM.EmployeeId = L.EmployeeId
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
		LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = L.EmployeeId
	WHERE
		L.Id = @rLeaveId 
		AND L.EmployeeId=@rEmployeeId
		AND L.OrgId=@rOrgId
		AND L.BatchId=@rBatchId
		AND ((L.StatusId = @rStatusId) OR (@rStatusId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeePendingDocumentsGet]
	 	 
	 	 @rDepartmentId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)='' 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		EC.EmployeeId AS AcademicId,
		EC.Code,
		EC.EmployeeName AS Name,
		EC.MobileNumber AS MobileNo,	
		EC.CompanyEmail AS EmailId,
		REPLACE (REPLACE(@rTemplate,'[EmployeeName]',EC.EmployeeName),'[Documents]',[sAlert].[fPendingDocumentsGet](EC.EmployeeId,95)) AS Template,
		@rMailSubject AS MailSubject,
		[sAlert].[fPendingDocumentsGet](EC.EmployeeId,95) AS Documents,
		EC.WhatsAppContactNo
	FROM 
		sHrm.vEmployeeCommunication EC
	WHERE
		((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (EC.OrgId=@rOrgId)
		AND (EC.StatusId=7)
		AND [sAlert].[fPendingDocumentsGet](EC.EmployeeId,95) != ''
END

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


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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--work aniversory 
 
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeWorkAnniversary]
			
			@rDepartmentId int,
			@rOrgId int,
			@rTemplate nvarchar(max),
			@rDateOfJoining date,
			@rMailSubject NVARCHAR(100)
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SELECT 
			--EC.EmployeeId AS AcademicId,
			--EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			REPLACE(REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title),'[DateOfJoining]',EC.DateOfJoining),'[NoOfYear]',[sCommon].[fAgeAtDate](EC.DateOfJoining,getdate())) AS MsgText,
			EC.ParticipantSourceTypeId AS SourceTypeId,
			OM.Title AS SchoolName,
			(CASE WHEN ISNULL(EC.PersonalEmail,'')='' THEN EC.CompanyEmail
			ELSE EC.PersonalEmail END) AS EmailId, 
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			OM.Title AS SchoolName,
			EC.EmployeeName AS [Name],
			EC.DateOfJoining AS DateOfJoining,
			[sCommon].[fAgeAtDate](EC.DateOfJoining,getdate()) AS NoOfYear,
			EC.WhatsAppContactNo

		FROM
			sHrm.vEmployeeCommunication EC
			INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
		WHERE
			(EC.DepartmentId=@rDepartmentId OR @rDepartmentId=0)
			AND (EC.OrgId=@rOrgId)
			AND (DAY(EC.DateOfJoining) = DAY(@rDateOfJoining))
			AND (MONTH(EC.DateOfJoining) = MONTH(@rDateOfJoining))
			AND (EC.StatusId=7)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pEmployeeWorkAnniversaryWishGet]
			
			@rDepartmentId int,
			@rOrgId int,
			@rTemplate nvarchar(max),
			@rDateOfJoining date
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SELECT 
			EC.EmployeeId AS AcademicId,
			EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			REPLACE(REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title),'[DateOfJoining]',EC.DateOfJoining),'[NoOfYear]',[sCommon].[fAgeAtDate](EC.DateOfJoining,getdate())) AS Template,
			EC.ParticipantSourceTypeId AS SourceTypeId,
			OM.Title AS SchoolName,
			EC.DateOfJoining AS DateOfJoining,
			[sCommon].[fAgeAtDate](EC.DateOfJoining,getdate()) AS NoOfYear,
			EC.WhatsAppContactNo
		FROM
			sHrm.vEmployeeCommunication EC
			INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
		WHERE
			(EC.DepartmentId=@rDepartmentId OR @rDepartmentId=0)
			AND (EC.OrgId=@rOrgId)
			AND (DAY(EC.DateOfJoining) = DAY(@rDateOfJoining))
			AND (MONTH(EC.DateOfJoining) = MONTH(@rDateOfJoining))
			AND (EC.StatusId=7)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pEventAlertRoleGet]
	@rOrgId [int],
	@rEventId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT	
		EAR.Id AS RecipientId,
		AR.Title AS RecipientName
	FROM
		sAlert.tEventAlertRoleMaster EAR
		INNER JOIN sAlert.tAlertRoleMaster AR
		ON EAR.AlertRoleId = AR.Id  				
  WHERE 	 
		 EAR.EventId = @rEventId
 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAlert].[pEventEmployeeAttendanceGet]

	 	 --@rEventScheduleId int,
		 @rEventName nvarchar(max),
	 	 --@rEmployeeId bigint,
		 @rFromDate Date,
		 @rToDate Date,
		 --@rAttendanceType nvarchar(max),
		 @rIsPresent bit = 0,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)='',
		 @rEventAttendanceXml nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEventAttendanceXml
BEGIN
	CREATE TABLE #EventAttendanctemp  
	(
		EmployeeId bigint,
		IsPresent bit
	)
	INSERT INTO #EventAttendanctemp
	(
		EmployeeId ,
		IsPresent 
	)
	SELECT *
			FROM OPENXML (@loDoc, '/Table/EventAttendance', 1)
			WITH
			(						
				SourceId bigint,
				IsSelfPresent bit
			)
	Select
			EC.EmployeeId,
			EC.Code,
			EC.EmployeeName,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[EventName]',@rEventName),
			'[EmployeeName]',EC.EmployeeName),
			'[Code]',EC.Code), 
			'[Date]',convert(varchar, @rFromDate, 103)  + '-' + convert(varchar, @rToDate, 103)),
			'[Type]',
			' Present : ' + CASE WHEN tmp.IsPresent = 1 THEN 'YES' ELSE 'NO' END) 
			AS MsgText,
			@rMailSubject AS Subject,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.OrgId,
			OM.OrgGroupId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.WhatsAppContactNo

	From
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
		INNER JOIN #EventAttendanctemp tmp ON EC.EmployeeId = tmp.EmployeeId
		WHERE 
		--EC.EmployeeId = @rEmployeeId
		EC.StatusId = 7

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pEventMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT	Id,
			ModuleId,
			Title,
		--	TitleResourceKeyId,
			Remark,
			ViewName,
			IsShowRoleBasedOnFunctionality
	
	FROM	sAlert.tEventMaster
	  
	WHERE ((Id = @rId) OR (@rId = 0))

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pEventRoleGet]
	@rOrgId [int],
	@rEventId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT	sAlert.tEventRoleMaster.RoleId AS RecipientId,
			(CASE WHEN sAlert.tEventRoleMaster.RoleId > 0 THEN
					sSecurity.tRole.Title
				WHEN sAlert.tEventRoleMaster.RoleId = 3 THEN
					'Patient'
				WHEN sAlert.tEventRoleMaster.RoleId = -1 THEN
					'Vendor'
			END) AS RecipientName

	FROM	sAlert.tEventRoleMaster
			LEFT OUTER JOIN sSecurity.tRole ON
				sSecurity.tRole.Id = sAlert.tEventRoleMaster.RoleId
	  
	WHERE ((EventId = @rEventId) OR (@rEventId = 0)) AND sAlert.tEventRoleMaster.OrgId = @rOrgId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAlert].[pEventStudentAttendanceGet]

	 	 --@rEventScheduleId int,
		 @rEventName nvarchar(max),
	 	 --@rAcademicId bigint,
		 @rFromDate Date,
		 @rToDate Date,
		 @rAttendanceType nvarchar(max),
		 --@rIsStudentPresent bit,
		 --@rIsFatherPresent bit,
		 --@rIsMotherPresent bit,
		 --@rIsGuardianPresent bit,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)='',
		 @rEventAttendanceXml nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEventAttendanceXml
BEGIN
	CREATE TABLE #EventAttendanctemp  
	(
		AcademicId bigint,
		IsStudentPresent bit,
		IsFatherPresent bit,
		IsMotherPresent bit,
		IsGuardianPresent bit
	)
	INSERT INTO #EventAttendanctemp
	(
		AcademicId ,
		IsStudentPresent ,
		IsFatherPresent ,
		IsMotherPresent ,
		IsGuardianPresent 
	)
	SELECT *
			FROM OPENXML (@loDoc, '/Table/EventAttendance', 1)
			WITH
			(						
				SourceId bigint,
				IsSelfPresent bit,
				IsFatherPresent bit,
				IsMotherPresent bit,
				IsGuardianPresent bit
			)

	Select
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[EventName]',@rEventName),
			'[StudentName]',vSA.Name),
			'[Code]',vSA.Code), 
			'[Date]',convert(varchar, @rFromDate, 103)  + '-' + convert(varchar, @rToDate, 103)),
			'[AttendanceType]',@rAttendanceType),
			'[Type]',
			' Student Present : ' + CASE WHEN tmp.IsStudentPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Father Present : ' + CASE WHEN tmp.IsFatherPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Mother Present : ' + CASE WHEN tmp.IsMotherPresent = 1 THEN 'YES' ELSE 'NO' END + 
			', Guardian Present : ' + CASE WHEN tmp.IsGuardianPresent = 1 THEN 'YES' ELSE 'NO' END) 
			AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.WhatsAppContactNo

	From
	
		--sActivity.tEventSchedule ES
		--INNER JOIN sActivity.tEventAttendance EA ON ES.Id = EA.EventScheduleId
		sStudent.vStudentAcademic vSA 
		INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = vSA.AcademicId
		INNER JOIN #EventAttendanctemp tmp ON vSA.AcademicId =  tmp.AcademicId
		WHERE 
		--vSA.AcademicId = @rAcademicId
		SC.IsBlockAllAlert=0
		AND (SC.StatusId=1)

	DROP TABLE #EventAttendanctemp

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pEventTemplateAdd]
	 
	
	@rEventTemplateDetailXml [nvarchar](max),
	--@rAcademicId bigint,
	@rAlertModeId int,
	@rOrgId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEventTemplateDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	
	 DELETE FROM sAlert.tEventTemplate
				 WHERE AlertModeId =@rAlertModeId  AND OrgId=@rOrgId
	
 
	 INSERT INTO sAlert.tEventTemplate
		(
			OrgId,
			EventId,
			MailSubject,
			Template,
			AlertModeId,
			IsAutoSend,
			DefaultAlertTo,
			SMSTemplateID,
			EMailCC,
			EMailBCC,
			WhatsAppTemplate,
			WhatsAppTemplateLanguage,
			DefaultAlertToEUId
			)
		SELECT
		
			OrgId,
			EventId,
			MailSubject,
			Template,
			AlertModeId,
			IsAutoSend,
			DefaultAlertTo,
			SMSTemplateID,
			EMailCC,
			EMailBCC,
			WhatsAppTemplate,
			WhatsAppTemplateLanguage,
			DefaultAlertToEUId
			
		FROM OPENXML (@loDoc, '/Table/EventTemplateDetail', 1)
		WITH ( 
				OrgId int,
				EventId bigint,
				AlertModeId int,
				MailSubject nvarchar(100),
				Template nvarchar(max),
				IsAutoSend bit,
				DefaultAlertTo nvarchar(500),
				SMSTemplateID nvarchar(100),
				EMailCC nvarchar(500),
				EMailBCC nvarchar(500),
				WhatsAppTemplate nvarchar(100),
				WhatsAppTemplateLanguage nvarchar(100),
				DefaultAlertToEUId nvarchar(max)
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pEventTemplateGet]

	@rOrgId smallint,
	@rId smallint,
	@rAlertModeId tinyint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT 
			Template,
			IsAutoSend,
			MailSubject
	FROM 
			sAlert.tEventTemplate
	WHERE	
			EventId=@rId
		--AND OrgId=@rOrgId 
		AND ((OrgId=@rOrgId) OR (@rOrgId=0))
		AND AlertModeId=@rAlertModeId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pEventTemplateListGet]

	@rAlertModeId int,
	@rOrgGroupId smallint,
	@rOrgId int,
	@rIsAutoSend bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
			EM.Title AS EventName,
			ISNULL(ET.Template,ISNULL(EM.Template,'')) AS TemplateName,
			EM.Id,
			ISNULL(ET.AlertModeId,0) AS AlertModeId,
			ISNULL(IsAutoSend,0) AS IsAutoSend,
			EM.Fields AS FieldName,
			MM.Title AS ModuleName,
			MM.Id AS ModuleId,
			ISNULL(ET.MailSubject,ISNULL(EM.MailSubject,'')) AS MailSubject,
			ISNULL(EM.IsAllowAutoSend,0) AS IsAllowAutoSend,
			ISNULL(ET.DefaultAlertTo,'') AS DefaultAlertTo,
			ISNULL(EM.IsAssignDefaultAlert,0) AS IsAssignDefaultAlert,
			ISNULL(ET.SMSTemplateID,'')AS SMSTemplateID,
			ISNULL(ET.EMailCC,'') AS EMailCC,
			ISNULL(ET.EMailBCC,'') AS EMailBCC,
			ISNULL(ET.WhatsAppTemplate,'') AS WhatsAppTemplate,
			ISNULL(ET.WhatsAppTemplateLanguage,'') AS WhatsAppTemplateLanguage,
			ISNULL(ET.DefaultAlertToEUId,'') AS DefaultAlertToEUId
	FROM 
			 sAlert.tEventMaster EM
			 INNER JOIN sCommon.tModuleMaster MM ON MM.Id=EM.ModuleId
			 LEFT JOIN sAlert.tEventTemplate ET ON ET.EventId=EM.Id AND ET.OrgId=@rOrgId AND ((ET.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			 INNER JOIN sSecurity.tModulePermission MP ON MP.OrgGroupId=@rOrgGroupId AND MP.ModuleId=EM.ModuleId 
			 --AND MP.ModuleId!=162
	WHERE	
			(EM.IsObsolete=0)
			ORDER BY ModuleName

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pExternalRecipientMasterAdd]
	@rOrgId [int],
	@rTitle [nvarchar](100),
	@rMobile [nvarchar](20),
	@rEmail [nvarchar](100),
	@rCreatedUserId [bigint],
	@rIsObsolete [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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


	INSERT INTO sAlert.tExternalRecipientMaster
		(
			Id,
			Title,
			Mobile,
			Email,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rMobile,
			@rEmail,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)


	SELECT @lNextNumber AS Result
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pExternalRecipientMasterGet]
	@rId [tinyint] = 0,
	@rName nvarchar(100),
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			BEGIN
				 
				SET @rName = sCommon.fSearchStringGet(@rName)
			END

BEGIN
	 SELECT Id,
			Title,
			Mobile,
			Email,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sAlert.tExternalRecipientMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
		AND	((Title LIKE @rName) OR (ISNULL(@rName, '') = ''))
		AND OrgId=@rOrgId
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pExternalRecipientMasterModify]
	@rOrgId [int],
	@rTitle [nvarchar](100),
	@rMobile [nvarchar](20),
	@rEmail [nvarchar](100),
	@rCreatedUserId [bigint],
	@rIsObsolete [bit],
	@rId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAlert.tExternalRecipientMaster
		SET 
			Title = @rTitle,
			Mobile = @rMobile,
			Email = @rEmail,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(), 
			OrgId=@rOrgId
	  WHERE Id = @rId
	  
	  SELECT 1 AS Result


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pFeedbackGet]
	  
        @rFeedbackId bigint=0,
        @rOrgId int,
	 	@rTemplate nvarchar(max),
		@rSubject nvarchar(100)=''
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			   
			From sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS Name,
		 
		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 Code
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 Code
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS Code,

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

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

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

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



 
CREATE OR ALTER PROCEDURE [sAlert].[pFeeDueGet]

		 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rToDate date,
	 	 @rMailSubject nvarchar(500)='',
	 	 @rAdmissionCategoryId int=0,
	 	 @rIdNos nvarchar(500)='',
		 @rDepartmentId int=0,
		 @rCollectionGroupId int=0,
		 /***Added for mantis : 35914 by Nilesh***/
		 @rFromAmount decimal = 0.00,
		 @rToAmount decimal = 0.00
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	CREATE TABLE #TempOptional (
		Id int,
		Amount decimal(12,2),
		StartDate date,
		EndDate date,
		ReceiptBookId int,
		AcademicId bigint
	)
	
	CREATE TABLE #TempReceipt (
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint
	)
	
	INSERT INTO #TempOptional
	SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			
			UNION ALL

			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))

	
	INSERT INTO #TempReceipt
	SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId
			FROM
				sFee.tReceipt R 

				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0) 
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			GROUP BY 
				FeeSetupId,R.SourceId
	
	SELECT 
		D.AcademicId,
		D.RollNo,
		D.Name,
		D.Code,
		D.MobileNo,	
		D.EmailId,
		D.StudentContactNo,
		D.StudentEmail,
		D.FatherContactNo,
		D.FatherMail,
		D.MotherContactNo,
		D.MotherMail,
		SUM(D.PendingAmount) As PendingAmount,
		REPLACE (REPLACE(
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',D.Name),
		'[Class]',D.ClassName),
		'[Division]',D.DivisionName),
		'[PendingAmount]',CONVERT(decimal(12,2),(SUM(D.PendingAmount)))),--Changed datatype from int to decimal for mantis : 35914
		'[Code]',D.Code)
		AS Template,
		REPLACE (REPLACE(
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',D.Name),
		'[Class]',D.ClassName),
		'[Division]',D.DivisionName),
		'[PendingAmount]',CONVERT(decimal(12,2),(SUM(D.PendingAmount)))),--Changed datatype from int to decimal for mantis : 35914
		'[Code]',D.Code)
		AS MsgText,
		@rMailSubject AS [Subject],
		D.ClassName AS Class,
		D.DivisionName AS Division,				
		D.WhatsAppContactNo,
		D.AcademicId AS ReceiverSourceId,
		2001 AS ReceiverSourceTypeId,
		D.OrgId,
		D.OrgGroupId,
		D.AcademicId AS SourceId,
		'2001' AS SourceTypeId
	FROM
	(
	SELECT
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.ClassName,
		SA.DivisionName,
		SA.Code,
		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,
		SA.DivisionOrder,
		((ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00))-((ISNULL(FA.NotApplicableAmount,0.00) + ISNULL(FA.DiscountAmount,0.00)+ISNULL(R.PaidAmount,0.00))))  AS PendingAmount,
		SC.WhatsAppContactNo,
		SA.OrgId,
		o.OrgGroupId
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN  #TempOptional FS ON FS.AcademicId=SA.AcademicId 
		LEFT JOIN sFee.tFeeAllocation FA
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #TempReceipt	R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN  sStudent.vStudentCommunication SC ON SC.AcademicId = SA.AcademicId
	WHERE	
		SA.StatusId = 1 AND SC.IsBlockAllAlert=0 
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
		AND ((FS.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		
		AND ((ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)) - (ISNULL(FA.DiscountAmount,0.00)+ISNULL(FA.NotApplicableAmount,0.00)+ISNULL(R.PaidAmount,0.00)) >0)			
		AND (SA.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		) D
	GROUP BY 
		D.AcademicId,D.RollNo,D.Name,D.ClassName,D.DivisionName,D.Code,
		D.MobileNo,D.EmailId,D.StudentContactNo,D.StudentEmail,D.FatherContactNo,D.FatherMail,D.MotherContactNo,D.MotherMail,D.DivisionOrder,D.WhatsAppContactNo,D.OrgId,D.OrgGroupId
		/***Added for mantis : 35914 by Nilesh***/
		HAVING ((SUM(D.PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(D.PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
	ORDER BY 
		D.DivisionOrder,D.Rollno	

	DROP TABLE #TempOptional
	DROP TABLE #TempReceipt
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pFeeFollowupGet]
	
	@rId bigint = 0,
	@rOrgId Smallint=0,
	@rOrgGroupBatchId int = 0,
	@rAcademicId bigint = 0,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100) = ''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		@rSubject AS Subject,
		replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Code]',SC.Code),
			'[ClassDivision]',SC.ClassName+' / '+SC.DivisionName),
			'[FollowupRemark]',FF.FollowupRemark),
			'[FollowupDate]',CONVERT(varchar(11),ISNULL(FF.FollowupDate,'') ,103)),
			'[HandledBy]',FF.HandledBy),
			'[NextFollowupDate]',CONVERT(varchar(11),ISNULL(FF.NextFollowupDate,'') ,103))
		AS MsgText,
		SC.OrgId,
		SC.OrgGroupId,
		SC.AcademicId AS SourceId,
		2001 AS SourceTypeId,
		2001 AS ReceiverSourceTypeId,
		SC.AcademicId AS ReceiverSourceId,
		SC.ClassName AS Class,
		SC.DivisionName AS Division,
		SC.WhatsAppContactNo
	FROM 
		sFee.tFeeFollowup FF
		INNER JOIN sStudent.vStudentCommunication SC ON  SC.AcademicId = FF.AcademicId
	WHERE  
		(FF.Id = @rId OR @rId = 0)		
		AND (SC.OrgId=@rOrgId OR @rOrgId=0)		
		AND (SC.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		AND (SC.AcademicId=@rAcademicId OR @rAcademicId=0 )		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pFeeInvoiceGet]
	@rInvoiceIds nvarchar(max),
	@rTemplate nvarchar(max),
	@rMailSubject nvarchar(max)
AS
BEGIN
	SET NOCOUNT ON;

   SELECT 
		vSA.Name AS Name,ClassName,DivisionName, ISNULL(ParentEmail,'') AS EmailId,
		replace (					
		replace (
		replace (
		replace (					
		replace (
		replace (
		replace (
		replace(@rTemplate,'[Name]',vSA.Name),
		'[Class]',ClassName),
		'[Division]',DivisionName),
		'[InvoiceNumber]',InvoiceNumber),
		'[InvoiceDate]',InvoiceDate),
		'[InvoiceAmount]',InvoiceDate),
		'[ReceiptBook]',RBM.Title),
		'[CollectionGroup]',CGM.Title) AS MSGText
		,@rMailSubject AS [Subject]
		,SourceId AS SourceId, InvoiceNumber 
		,InvoiceDate,InvoiceAmount
		,RBM.Title AS ReceiptBook
		,RBM.Id AS ReceiptBookId
		,CGM.Title AS CollectionGroup
        FROM sStudent.vStudentCommunication vSA
        INNER JOIN sFee.tFeeInvoice FI ON FI.SourceId=vSA.AcademicId
        INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FI.ReceiptBookId
        INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FI.CollectionGroupId 
        WHERE IsBlockAllAlert=0 AND CAST(FI.Id AS nvarchar(Max)) in ((SELECT cast(item as bigint) FROM sCommon.fnsplit(@rInvoiceIds,',')))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAlert].[pFeeReceiptCancelGet]
	 	 
	 	 @rReceiptId bigint,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rAdmissionCategoryId int=0,
	 	 @rIdNos nvarchar(500)='',
		 @rCollectionGroupId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SELECT 
				SC.AcademicId,
				SC.Code,
				SC.Name,
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
				ISNULL(SC.StudentEmail,'') AS StudentEmail,
				ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
				ISNULL(SC.FatherMail,'') AS FatherMail,
				ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
				ISNULL(SC.MotherMail,'') AS MotherMail,
				@rSubject AS Subject,
				replace (
				replace (
				replace (
				replace (
				replace (
				replace (
				replace(@rTemplate,'[Name]',SC.Name),
				'[Class]',SC.ClassName),
				'[Division]',SC.DivisionName),
				'[ReceiptNumber]',R.ReceiptNumber),
				'[ReceiptDate]',convert(varchar,R.ReceiptDate,103)),
				'[PaidAmount]',convert(int,R.ReceiptAmount)),
				'[ChequeNo]',ISNULL(R.Chequeno,''))
				 AS MsgText,				 
				 SC.OrgId,
				 SC.OrgGroupId,
				 SC.AcademicId AS SourceId,
				 2001 AS SourceTypeId,
				 2001 AS ReceiverSourceTypeId,
				 SC.AcademicId AS ReceiverSourceId,
				 SC.ClassName AS Class,
				 SC.DivisionName AS Division,
				 R.ReceiptNumber AS ReceiptNumber,
				 convert(varchar,R.ReceiptDate,103) AS ReceiptDate,
				 convert(int,R.ReceiptAmount) AS PaidAmount,
				 ISNULL(R.Chequeno,'') AS ChequeNo,
				 SC.WhatsAppContactNo
		FROM 
			sStudent.vStudentCommunication SC
		INNER JOIN sFee.tReceipt R ON R.SourceId=SC.AcademicId AND R.SourceTypeId=2001 AND R.IsObsolete=1
				AND ((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((R.Id=@rReceiptId) OR (@rReceiptId=0))
				AND ((R.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			
		WHERE
				((SC.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (SC.StatusId=1)
			AND (SC.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
			AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			AND SC.IsBlockAllAlert=0
			ORDER BY R.ReceiptNumber	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pFeeReceiptEntryGet]
	 	 
	 	 @rReceiptId bigint,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rAdmissionCategoryId int=0,
	 	 @rIdNos nvarchar(500)='',
	 	 @rIsObsolete bit=0,
		 @rCollectionGroupId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF CHARINDEX('[PendingAmount]',@rTemplate) > 0   
	BEGIN
		SELECT 
				SC.AcademicId,
				SC.Code,
				SC.Name,
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
				ISNULL(SC.StudentEmail,'') AS StudentEmail,
				ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
				ISNULL(SC.FatherMail,'') AS FatherMail,
				ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
				ISNULL(SC.MotherMail,'') AS MotherMail,
				@rSubject AS Subject,
				replace (
				replace (
				replace (
				replace (
				replace (
				replace (
				replace (
				replace(@rTemplate,'[Name]',SC.Name),
				'[Class]',SC.ClassName),
				'[Division]',SC.DivisionName),
				'[ReceiptNumber]',R.ReceiptNumber),
				'[ReceiptDate]',convert(varchar,R.ReceiptDate,103)),
				'[PaidAmount]',convert(int,R.ReceiptAmount)),
				'[PendingAmount]',ISNULL([sFee].[fPendingFeeAmountForAlertGet](SC.AcademicId),0)),
				'[ChequeNo]',ISNULL(R.Chequeno,''))
				 AS MsgText,
				 SC.OrgId,
				 SC.OrgGroupId,
				 SC.AcademicId AS SourceId,
				 2001 AS SourceTypeId,
				 2001 AS ReceiverSourceTypeId,
				 SC.AcademicId AS ReceiverSourceId,
				 SC.ClassName AS Class,
				 SC.DivisionName AS Division,
				 R.ReceiptNumber,
				convert(varchar,R.ReceiptDate,103) AS ReceiptDate,
				convert(int,R.ReceiptAmount) AS PaidAmount,
				ISNULL([sFee].[fPendingFeeAmountForAlertGet](SC.AcademicId),0) AS PendingAmount,
				ISNULL(R.Chequeno,'') AS ChequeNo,
				SC.WhatsAppContactNo
				 
		FROM 
			sStudent.vStudentCommunication SC
		INNER JOIN sFee.tReceipt R ON R.SourceId=SC.AcademicId AND R.SourceTypeId=2001 AND R.IsObsolete=@rIsObsolete
				AND ((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((R.Id=@rReceiptId) OR (@rReceiptId=0))
				AND ((R.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			
		WHERE
				((SC.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (SC.StatusId=1)
			AND (SC.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
			AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			AND SC.IsBlockAllAlert=0
			ORDER BY R.ReceiptNumber	
	END
	ELSE
	BEGIN
		SELECT 
				SC.AcademicId,
				SC.Code,
				SC.Name,
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
				ISNULL(SC.StudentEmail,'') AS StudentEmail,
				ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
				ISNULL(SC.FatherMail,'') AS FatherMail,
				ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
				ISNULL(SC.MotherMail,'') AS MotherMail,
				@rSubject AS Subject,
				replace (
				replace (
				replace (
				replace (
				replace (
				replace (
				replace(@rTemplate,'[Name]',SC.Name),
				'[Class]',SC.ClassName),
				'[Division]',SC.DivisionName),
				'[ReceiptNumber]',R.ReceiptNumber),
				'[ReceiptDate]',convert(varchar,R.ReceiptDate,103)),
				'[PaidAmount]',convert(int,R.ReceiptAmount)),
				'[ChequeNo]',ISNULL(R.Chequeno,''))
				 AS MsgText,				 
				 SC.OrgId,
				 SC.OrgGroupId,
				 SC.AcademicId AS SourceId,
				 2001 AS SourceTypeId,
				 2001 AS ReceiverSourceTypeId,
				 SC.AcademicId AS ReceiverSourceId,
				 SC.ClassName AS Class,
				 SC.DivisionName AS Division,
				 R.ReceiptNumber,
				convert(varchar,R.ReceiptDate,103) AS ReceiptDate,
				convert(int,R.ReceiptAmount) AS PaidAmount,				
				ISNULL(R.Chequeno,'') AS ChequeNo,
				SC.WhatsAppContactNo
				 
		FROM 
			sStudent.vStudentCommunication SC
		INNER JOIN sFee.tReceipt R ON R.SourceId=SC.AcademicId AND R.SourceTypeId=2001 AND R.IsObsolete=@rIsObsolete
				AND ((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((R.Id=@rReceiptId) OR (@rReceiptId=0))
				AND ((R.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			
		WHERE
				((SC.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (SC.StatusId=1)
			AND (SC.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
			AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			AND SC.IsBlockAllAlert=0
			ORDER BY R.ReceiptNumber	
	END
	
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pForgotPasswordFailureLogGet]
	@rUserId bigint,
	@rUserSourceTypeId int,
	@rFailureLogId bigint =0 
AS
BEGIN
		DECLARE @lCode nvarchar(100),@lSourceId bigint
		UPDATE sSecurity.tUser set TempPasswordCode = newid() WHERE Id = @rUserId 
		SELECT @lCode = TempPasswordCode,@lSourceId = SourceId from sSecurity.tUser where Id = @rUserId and SourceTypeId = 95
		SELECT @lCode = TempPasswordCode,@lSourceId = SourceId from sSecurity.tUser where Id = @rUserId and SourceTypeId = 2003

		Select @lCode AS Code
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pGetEmployeeMananger]
	 	 @rLeadFollowupId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rOrgGroupId smallint,
	 	 @rEmployeeManagerId bigint 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			replace(
			replace(
			replace(
			replace (
			replace (
			replace(@rTemplate,'[EmployeeName]',(EM.FirstName +' '+ EM.MiddleName +' '+ EM.LastName)),			
			'[LeadName]',LM.Title),
			'[StreetDetail]', LM.StreetDetail),
			'[Area]',LM.AreaName),
			'[city]', LM.CityName),
			'[Displacement]',ISNULL(LF.Displacement,0))
			 AS MsgText,
			'95' AS SourceTypeId,
			@rEmployeeManagerId AS SourceId,
			LM.OrgId,
			@rOrgGroupid As OrgGroupId
	FROM 
		  sErp.tLeadMaster LM
		  INNER JOIN sErp.tLeadFollowup LF ON LF.LeadId = LM.Id 
		  INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LF.FollowupEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0

	WHERE LF.Id = @rLeadFollowupId 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAlert].[pGetWebNotificationList]
@rSourceId bigint,
@rSourceTypeId int,
@rIsTop bit = 1

AS
BEGIN
	DECLARE @lnotifictiongrid NVARCHAR(max)=''

IF(@rIsTop = 1)
BEGIN
SELECT Top 10 @lnotifictiongrid = @lnotifictiongrid + '<div class="card notifications-wrapper"><a class="text-light-blue" onclick="window.open(' + '''' + Replace(S.Page,'~','') + '?Id=' + convert(varchar,NL.DocumentId) + '''' +');">
								  <div class="card-body notification-item " style="padding: 2px 0px 5px 0px !important;"><h5 class="card-title item-info" style = "font-weight: 700;"> ' + ISNULL(NL.MessageTitle,'') + '</h5>' +
								  '<hr/><h6 class="card-subtitle mb-2 text-muted">' + ISNULL(NL.NotificationMessage,'') + '</h6>' +
								  '</div>' +
								  ' </a> ' +
								  ' </div> ' 
 FROM
	[sAlert].[tNotificationLog]  NL
	INNER JOIN [sSecurity].[tScreen] S ON CONVERT(int,NL.StatusCode) = S.Id
	WHERE OSTypeId  = 3 
	AND SourceId = @rSourceId
	AND SourceTypeId = @rSourceTypeId
	ORDER BY CreatedDateTime DESC

	--select @lnotifictiongrid
	IF(@lnotifictiongrid <> '')
	BEGIN
		select '<ul aria-labelledby="dLabel"><div class="notifications-wrapperMain">' +
		isnull(@lnotifictiongrid,'')  +'</div></ul><u><a class="text-light-blue" onclick="NotificationClick(false)"><p style="margin-bottom: 0.1rem;padding: 0px 10px;" class="item-info">' + 'Show More' +'
			</p></a></u>'  as NotificationGrid
	END
END
ELSE
BEGIN	
CREATE TABLE #tmp
(
	PagePath nvarchar(500),
	DocumentId bigint,
	MessageTitle nvarchar(200),
	NotificationMessage nvarchar(max)
)
INSERT INTO #tmp (PagePath , DocumentId , MessageTitle, NotificationMessage)
SELECT 
S.Page AS PagePath, NL.DocumentId ,NL.MessageTitle , NL.NotificationMessage
FROM
	[sAlert].[tNotificationLog]  NL
	INNER JOIN [sSecurity].[tScreen] S ON CONVERT(int,NL.StatusCode) = S.Id
	WHERE OSTypeId  = 3 
	AND SourceId = @rSourceId
	AND SourceTypeId = @rSourceTypeId
	ORDER BY CreatedDateTime DESC
	
SELECT @lnotifictiongrid = @lnotifictiongrid + '<div class="card notifications-wrapper"><a class="text-light-blue" onclick="window.open(' + '''' + Replace(tmp.PagePath,'~','') + '?Id=' + convert(varchar,tmp.DocumentId) + '''' +');">
								  <div class="card-body notification-item " style="padding: 2px 0px 5px 0px !important;"><h5 class="card-title item-info" style = "font-weight: 700;"> ' + ISNULL(tmp.MessageTitle,'') + '</h5>' +
								  '<hr/><h6 class="card-subtitle mb-2 text-muted">' + ISNULL(tmp.NotificationMessage,'') + '</h6></div></a></div>' 
								 
 FROM
	#tmp tmp
	--Select @lnotifictiongrid
	
	select '<ul aria-labelledby="dLabel"><div class="notifications-wrapperMain">' +
		isnull(@lnotifictiongrid,'')  +'</div></ul><u><a class="text-light-blue" onclick="NotificationClick(false)"><p style="margin-bottom: 0.1rem;padding: 0px 10px;" class="item-info">' + 'Show More' +'
			</p></a></u>'  as NotificationGrid

	DROP TABLE #tmp
END


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pHostelAdmissionGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rHostelId int,
	 	 @rOrgGroupId int,
	 	 @rAdmissionDate date,
	 	 @rSourceId bigint=0  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (					
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[HostelName]',HM.Title),
			'[BuildingName]',BM.Title),
			'[RoomName]',RM.Title),	
			'[AdmissionDate]',HA.AllocateDate)
			 AS MsgText,
			 '' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 SC.AcademicId AS ReceiverSourceId,
			 SC.WhatsAppContactNo,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 HM.Title AS HostelName,
			 BM.Title AS BuildingName,
			 RM.Title AS RoomName,
			 HA.AllocateDate AS AdmissionDate
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sSetup.tBatchMaster BMast ON BMast.Id=SC.BatchId AND BMast.IsActive = 1
	INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = SC.StudentId AND AR.SourceTypeId=2003 
	INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId AND ((HM.Id=@rHostelId) OR (@rHostelId=0))
	INNER JOIN sHostel.tHostelAdmission HA ON HA.SourceId = SC.StudentId AND AR.SourceTypeId=2003
	LEFT JOIN sHostel.tBuildingMaster BM ON BM.Id = RM.BuildingId 
	
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (HM.OrgGroupId=@rOrgGroupId)
		AND (HA.AllocateDate = @rAdmissionDate)
		AND ((HA.SourceId=@rSourceId) OR (@rSourceId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pHostelChangeRoomGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rHostelId int,
	 	 @rOrgGroupId int,
	 	 @rLogDate date,
	 	 @rSourceId bigint=0 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (					
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[HostelName]',HM.Title),
			'[BuildingName]',BM.Title),
			'[ChangeRoomName]',RM.Title),
			'[LogDate]',CR.LogDate)
			 AS MsgText,
			 '' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 SC.AcademicId AS ReceiverSourceId,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 HM.Title AS HostelName,
			 BM.Title AS BuildingName,
			 RM.Title AS ChangeRoomName,
			 CR.LogDate AS LogDate,
			 SC.WhatsAppContactNo
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sSetup.tBatchMaster BMast ON BMast.Id=SC.BatchId AND BMast.IsActive = 1	
	INNER JOIN sHostel.tChangeRoom CR ON CR.SourceId=SC.StudentId  AND CR.SourceTypeId=2003
	INNER JOIN sHostel.tRoomMaster RM ON RM.Id = CR.RoomId
	INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId AND ((HM.Id=@rHostelId) OR (@rHostelId=0))
	LEFT JOIN sHostel.tBuildingMaster BM ON BM.Id = RM.BuildingId
	
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (HM.OrgGroupId=@rOrgGroupId)
		AND (CR.LogDate=@rLogDate)
		AND ((CR.SourceId=@rSourceId) OR (@rSourceId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pHostelStudentGatePassBulkGet]
	
	@rStudentGatePassId nvarchar(max),
	@rOrgGroupBatchId int=0,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			HSGP.Id, 
			HSGP.Id AS HostelStudentGatePassId,
			vSA.Code,
			vSA.FirstName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			HSGP.StudentId,
			HSGP.CreatedDateTime,
			HSGP.GatePassDate,
			HSGP.GatePassInDate,
			CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
			CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100) As GatePassInTime,
			HSGP.EntryModeStatusId,
			SM.Title AS EntryModeStatus,
			HGRM.Title AS HostelGetPassReason,	
			CM.ParentContactNo AS MobileNo,
	
	 REPLACE (
		REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',vSA.FirstName+' '+vSA.LastName),
		'[Status]',ISNULL(SM.Title,'')),
		'[Date]',ISNULL(HSGP.CreatedDateTime,'')),
		'[Reason]',ISNULL(HGRM.Title,''))
		AS MsgText,
		@rSubject AS [Subject]
		
		
	FROM
	 sStudent.vStudentAcademic vSA
	 LEFT JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId
	LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId   AND  HSGP.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
		LEFT JOIN sStudent.tStudentCommunication CM ON vSA.StudentId=CM.StudentId
		 
	WHERE	
		HSGP.Id  IN (@rStudentGatePassId )
		AND vSA.OrgGroupBatchId = @rOrgGroupBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pHostelStudentGatePassGet]

	@rStudentGatePassId bigint=0,
	@rStudentGatePassIdBulk nvarchar(max)= '',
	@rOrgGroupBatchId int=0,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF (@rStudentGatePassId!=0)
	BEGIN
		SELECT
			HSGP.Id,
			HSGP.Id AS HostelStudentGatePassId,
			vSA.Code,
			vSA.FirstName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			HSGP.StudentId,
			HSGP.CreatedDateTime,
			HSGP.GatePassDate,
			HSGP.GatePassInDate,
			CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
			CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100) As GatePassInTime,
			HSGP.EntryModeStatusId,
			SM.Title AS EntryModeStatus,
			HGRM.Title AS HostelGetPassReason,
			CM.ParentContactNo AS MobileNo,
			CM.ParentEmail AS EmailId,

			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[Name]',vSA.FirstName+' '+vSA.LastName),
			'[Status]',ISNULL(SM.Title,'')),
			'[Date]',  CASE WHEN HSGP.EntryModeStatusId=581 THEN CONVERT(varchar(11),ISNULL(HSGP.GatePassDate,'') ,103)
							ELSE CONVERT(varchar(11),ISNULL(HSGP.GatePassInDate,''),103) END),
			'[Time]',  CASE WHEN HSGP.EntryModeStatusId=581 THEN CONVERT(varchar(15),ISNULL(HSGP.GatePassTime,''),100)
							ELSE CONVERT(varchar(15),ISNULL(HSGP.GatePassInTime,''),100) END),
			'[Reason]',ISNULL(HGRM.Title,'')) AS MsgText,
			@rSubject AS [Subject],
			2003 AS ReceiverSourceTypeId,
			ISNULL(HSGP.StudentId,0) AS ReceiverSourceId,
			ISNULL(SM.Title,'') AS [GatePassStatus],  --mantis: 42034, change alias from [Status] to [GatePassStatus]
			(CASE WHEN HSGP.EntryModeStatusId=581 THEN CONVERT(varchar(11),ISNULL(HSGP.GatePassDate,''),103) ELSE CONVERT(varchar(11),ISNULL(HSGP.GatePassInDate,''),103) END) [Date],
			(CASE WHEN HSGP.EntryModeStatusId=581 THEN CONVERT(varchar(15),ISNULL(HSGP.GatePassTime,''),100) ELSE CONVERT(varchar(15),ISNULL(HSGP.GatePassInTime,''),100) END) [Time],
			ISNULL(HGRM.Title,'') AS Reason,
			ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo,
			--mantis: 42034, start
			OM.Id AS OrgId,
			OM.OrgGroupId AS OrgGroupId,
			vSA.AcademicId AS SourceId,
			2001 AS SourceTypeId
			--mantis: 42034, end

		FROM
			sStudent.vStudentAcademic vSA
			LEFT JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId
			LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId   AND  HSGP.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
			LEFT JOIN sStudent.tStudentCommunication CM ON vSA.StudentId=CM.StudentId AND CM.IsBlockAllAlert=0
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId  --mantis: 42034, add
		WHERE
			HSGP.Id = @rStudentGatePassId
			AND vSA.OrgGroupBatchId = @rOrgGroupBatchId
	END
	ELSE
	BEGIN
		SELECT
			HSGP.Id,
			HSGP.Id AS HostelStudentGatePassId,
			vSA.Code,
			vSA.FirstName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			HSGP.StudentId,
			HSGP.CreatedDateTime,
			HSGP.GatePassDate,
			HSGP.GatePassInDate,
			CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
			CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100) As GatePassInTime,
			HSGP.EntryModeStatusId,
			SM.Title AS EntryModeStatus,
			HGRM.Title AS HostelGetPassReason,
			CM.ParentContactNo AS MobileNo,
			CM.ParentEmail AS EmailId,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[Name]',vSA.FirstName+' '+vSA.LastName),
			'[Status]',ISNULL(SM.Title,'')),
			'[Date]',  CASE WHEN HSGP.EntryModeStatusId=581 THEN CONVERT(varchar(11),ISNULL(HSGP.GatePassDate,'') ,103)
							ELSE CONVERT(varchar(11),ISNULL(HSGP.GatePassInDate,''),103) END),
			'[Time]',  CASE WHEN HSGP.EntryModeStatusId=581 THEN CONVERT(varchar(15),ISNULL(HSGP.GatePassTime,''),100)
							ELSE CONVERT(varchar(15),ISNULL(HSGP.GatePassInTime,''),100) END),
			'[Reason]',ISNULL(HGRM.Title,'')) AS MsgText,
			@rSubject AS [Subject],
			@rStudentGatePassId,
			2003 AS ReceiverSourceTypeId,
			ISNULL(HSGP.StudentId,0) AS ReceiverSourceId,
			ISNULL(SM.Title,'') AS [GatePassStatus],  --mantis: 42034, change alias from [Status] to [GatePassStatus]
			(CASE WHEN HSGP.EntryModeStatusId=581 THEN CONVERT(varchar(11),ISNULL(HSGP.GatePassDate,''),103) ELSE CONVERT(varchar(11),ISNULL(HSGP.GatePassInDate,''),103) END) [Date],
			(CASE WHEN HSGP.EntryModeStatusId=581 THEN CONVERT(varchar(15),ISNULL(HSGP.GatePassTime,''),100) ELSE CONVERT(varchar(15),ISNULL(HSGP.GatePassInTime,''),100) END) [Time],
			ISNULL(HGRM.Title,'') AS Reason,
			ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo,
			--mantis: 42034, start
			OM.Id AS OrgId,
			OM.OrgGroupId AS OrgGroupId,
			vSA.AcademicId AS SourceId,
			2001 AS SourceTypeId
			--mantis: 42034, end

		FROM
			sStudent.vStudentAcademic vSA
			LEFT JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId
			LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId   AND  HSGP.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
			LEFT JOIN sStudent.tStudentCommunication CM ON vSA.StudentId=CM.StudentId AND CM.IsBlockAllAlert=0
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId  --mantis: 42034, add
		WHERE
			HSGP.Id  IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGatePassIdBulk,','))
			AND vSA.OrgGroupBatchId = @rOrgGroupBatchId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pHostelVacantGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rHostelId int,
	 	 @rOrgGroupId int,
	 	 @rVacantDate date,
	 	 @rSourceId bigint=0    
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (					
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[HostelName]',HM.Title),
			'[BuildingName]',BM.Title),
			'[RoomName]',RM.Title),	
			'[VacantDate]',HA.VacantDate)
			 AS MsgText,
			 '' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 SC.AcademicId AS ReceiverSourceId,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 HM.Title AS HostelName,
			 BM.Title AS BuildingName,
			 RM.Title AS RoomName,
			 HA.VacantDate AS VacantDate,
			 SC.WhatsAppContactNo

	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sSetup.tBatchMaster BMast ON BMast.Id=SC.BatchId AND BMast.IsActive = 1	
	INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = SC.StudentId AND AR.SourceTypeId=2003
	INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId AND ((HM.Id=@rHostelId) OR (@rHostelId=0))
	INNER JOIN sHostel.tHostelAdmission HA ON HA.SourceId = SC.StudentId AND AR.SourceTypeId=2003
	LEFT JOIN sHostel.tBuildingMaster BM ON BM.Id = RM.BuildingId 
	
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (HM.OrgGroupId=@rOrgGroupId)
		AND (HA.VacantDate = @rVacantDate)
		AND ((HA.SourceId=@rSourceId) OR (@rSourceId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pIssueBookAllGet]
	 
	 @rSourceTypeId smallint,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rDepartmentId int = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0,
	 @rTemplate nvarchar(max),	 	
	 @rMailSubject nvarchar(max)='',
	 @rIsCurrentStatus bit = 0  --MantisId : 0028808
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		SELECT distinct
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name AS Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			SC.WhatsAppContactNo,
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
					From sLibrary.tBookLog BL1
					INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId
					INNER JOIN sStudent.vStudentCommunication SC1 ON SC1.StudentId = BL1.ReaderSourceId AND SC1.BatchId = BL1.BatchId  AND BL1.ReaderSourceTypeId=2003
					INNER JOIN sSetup.tBatchMaster BMM1 ON BMM1.Id = BL1.BatchId 
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = BL1.OrgId
					INNER JOIN sLibrary.tLibraryMaster LM1 ON LM.Id=BL1.LibraryId
					WHERE
							(BL1.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
						AND ((BL1.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
						AND ((BL1.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
						AND (BL1.OrgId = @rOrgId)
						AND (BL1.BatchId = @rBatchId)
						AND (BL1.ReaderSourceTypeId != 0)
						AND ((SC1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
						AND ((SC1.ClassId=@rClassId) OR (@rClassId=0))
						AND ((SC1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
						AND (BL1.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808
						AND BL1.StatusId = 523
						AND BL1.ReaderSourceId=BL.ReaderSourceId	
						AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
                    FOR XML PATH('')),1,1,''))),
			'[LibraryName]',LM.Title)
			 AS Template,
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) + ' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
					From sLibrary.tBookLog BL1
					INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=2003
					AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = SC.StudentId AND BL1.BatchId =SC.BatchId  
					AND BMM.Id = BL1.BatchId  AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id
					AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
					AND BL1.StatusId = 523
					AND (BL1.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808		
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			LM.Title AS LibraryName
	From 
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = BL.ReaderSourceId AND SC.BatchId = BL.BatchId  AND BL.ReaderSourceTypeId=2003
		INNER JOIN sSetup.tBatchMaster BMM ON BMM.Id = BL.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE
		(BL.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND (BL.OrgId = @rOrgId OR @rOrgId=0)
		AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
		AND (BL.ReaderSourceTypeId != 0)
		AND ((SC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND BL.StatusId = 523
		AND (BL.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808

	UNION 

	SELECT distinct
			OM.OrgGroupId,
			EC.OrgId,
			EC.EmployeeId As AcademicId,
			EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			EC.WhatsAppContactNo,
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) +' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
						From sLibrary.tBookLog BL1
							INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=95
							AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = EC.EmployeeId 
							AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id AND ODM.Id = EC.DepartmentId
							AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7
							AND (BL1.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808
							AND BL1.StatusId = 523
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS Template,
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),			
			'[BookCode - BookName - IssueDate]',(SELECT STUFF ((SELECT distinct ',' + CHAR(10) + ' ' + BM1.Code +' - '+BM1.Title+' - '+ CONVERT(nvarchar(100), BL1.LogDate, 103)
						From sLibrary.tBookLog BL1
							INNER JOIN sLibrary.tBookMaster BM1 ON BM1.Id=BL1.ResourceSourceId AND BL1.ReaderSourceTypeId=95
							AND BL1.ReaderSourceId=BL.ReaderSourceId  AND BL1.ReaderSourceId = EC.EmployeeId 
							AND BL1.OrgId = OM.Id AND  BL1.LibraryId =LM.Id AND ODM.Id = EC.DepartmentId
							AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7
							AND BL1.StatusId = 523
							AND (BL1.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808
                    FOR XML PATH('')),1,1,'') )),
			'[LibraryName]',LM.Title)
			 AS MsgText,
			'95' AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			@rMailSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			LM.Title AS LibraryName
	         
	FROM 
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EC.DepartmentId
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = EC.OrgId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId

	WHERE 

		 (BL.OrgId = @rOrgId OR @rOrgId=0)
		AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
		AND ((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.ReaderSourceTypeId=@rSourceTypeId OR @rSourceTypeId=0)
		AND ISNULL(EC.IsOtherUser,0) = 0  AND EC.StatusId = 7	
		AND BL.StatusId = 523
		AND (BL.IsCurrentStatus=@rIsCurrentStatus OR @rIsCurrentStatus = 0) --MantisId : 0028808
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pLeaveBalanceAddRequestGet]
	
	 	 @rLeaveBalanceAddRequestId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rEmployeeId bigint,
         @rBatchId int,
         @rSubject nvarchar(100),
         @rStatusId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			EM.EmployeeId,
			EM.Code,
			EM.EmployeeName,
			EM.MobileNumber AS MobileNo,	
			EM.CompanyEmail AS EmailId,
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EM.EmployeeName),
			'[EmployeeManagerName]',ISNULL(vEM.EmployeeName,'')),
			'[AddRequestBalance]',LBAR.AddRequestBalance),
			'[AddRequestBalanceRemark]',ISNULL(LBAR.AddRequestBalanceRemark,''))
			 AS MsgText,
			@rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			 EM.EmployeeName AS Name,
			 ISNULL(vEM.EmployeeName,'') AS EmployeeManagerName,
			 LBAR.AddRequestBalance AS AddRequestBalance,
			 ISNULL(LBAR.AddRequestBalanceRemark,'') AS AddRequestBalanceRemark
	FROM 
		sHrm.vEmployeeCommonDetail EM
	INNER JOIN sHrm.tLeaveBalanceAddRequest LBAR ON  EM.EmployeeId = LBAR.EmployeeId
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = LBAR.EmployeeId
    LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId	
	LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
	WHERE
		LBAR.Id = @rLeaveBalanceAddRequestId 
		AND LBAR.EmployeeId=@rEmployeeId
		AND LBAR.BatchId=@rBatchId
		AND ((LBAR.StatusId = @rStatusId) OR (@rStatusId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pLeaveBalanceAddRequestManagerGet]
	
	 	 @rLeaveBalanceAddRequestId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rEmployeeId bigint,
         @rBatchId int,
         @rSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			ISNULL(vEM.EmployeeId,0) AS EmployeeId,
			ISNULL(vEM.Code,'') AS Code,
			ISNULL(vEM.EmployeeName,'') AS EmployeeName,
			ISNULL(vEM.MobileNumber,'') AS MobileNo,	
			ISNULL(vEM.CompanyEmail,'') AS EmailId,
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EM.EmployeeName),
			'[EmployeeManagerName]',ISNULL(vEM.EmployeeName,'')),
			'[AddRequestBalance]',LBAR.AddRequestBalance),
			'[AddRequestBalanceRemark]',ISNULL(LBAR.AddRequestBalanceRemark,''))
			 AS MsgText,
			@rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 ISNULL(vEM.EmployeeId,0) AS ReceiverSourceId,
			 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			 EM.EmployeeName AS Name,
			 ISNULL(vEM.EmployeeName,'') AS EmployeeManagerName,
			 LBAR.AddRequestBalance AS AddRequestBalance,
			 ISNULL(LBAR.AddRequestBalanceRemark,'') AS AddRequestBalanceRemark
	FROM 
		sHrm.tLeaveBalanceAddRequest LBAR
		INNER JOIN sHrm.vEmployeeCommonDetail EM  ON  EM.EmployeeId = LBAR.EmployeeId
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = LBAR.EmployeeId
		LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = LBAR.EmployeeId
	WHERE
		LBAR.Id = @rLeaveBalanceAddRequestId 
		AND LBAR.EmployeeId=@rEmployeeId
		AND LBAR.BatchId=@rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pLeaveHierarchyListingGet]
	
	 	 @rLeaveId bigint,
		 @rOrgId int,
		 @rEmployeeId bigint,
		 @rStatusId int,
	 	 @rTemplate nvarchar(max),
		 @rSubject nvarchar(100)=''
		 --@rHierarchyLevelCount int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lLeaveCount int,@lEmployeeId bigint, @lLeaveFromDate date, @lLeaveToDate date, @lLeaveReason nvarchar(200),
@lLeaveStatus nvarchar(100),@lEmployeeName nvarchar(100),@lActionByEmployeeName nvarchar(200), @lHierarchyLevelCount int
	
	SELECT @lLeaveCount = COUNT(AutoId) FROM [sHrm].[tLeaveHierarchyLevel] WHERE LeaveId = @rLeaveId
	
	SELECT @lHierarchyLevelCount = ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 485 AND SourceId = @rOrgId
	--SELECT @lLeaveCount,@lHierarchyLevelCount
IF(@lHierarchyLevelCount > 1)
BEGIN
	SELECT 
	 @lLeaveFromDate = FromDate,
	 @lLeaveToDate = ToDate,
	 @lLeaveReason = LeaveReason,
	 @lLeaveStatus = (CASE WHEN @rStatusId = 549 THEN 'Pending' 
						   WHEN @rStatusId = 550 THEN 'Approved'
						   ELSE 'Rejected' END),
	@lEmployeeName = ECD.EmployeeName
	from sHrm.tLeave L 
	INNER JOIN sHrm.vEmployeeCommonDetail ECD  ON L.EmployeeId = ECD.EmployeeId
	 WHERE L.Id = @rLeaveId 
	 --AND L.OrgId = @rOrgId

	 --Select @lEmployeeId

	IF(@lHierarchyLevelCount <> @lLeaveCount)
	BEGIN
		SELECT @lEmployeeId = EmployeeManagerId from sHrm.tEmployeeJobDetail WHERE EmployeeId = @rEmployeeId 
		--AND OrgId = @rOrgId
		SELECT @lActionByEmployeeName = EmployeeName from sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rEmployeeId 
		--AND OrgId = @rOrgId 

		--Select @lEmployeeId , @lActionByEmployeeName
	END

	ELSE
	--on last approval send alert to employee (Who enter leave)
	BEGIN
	Select @lEmployeeId = EmployeeId from sHrm.tLeave WHERE Id = @rLeaveId 
	--AND OrgId = @rOrgId
	SELECT @lActionByEmployeeName = EmployeeName from sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rEmployeeId 
	--AND OrgId = @rOrgId 
	END

	print @lEmployeeId
	print @lEmployeeName
Select 
		EM.Id AS EmployeeId,
		EM.Code,
		ECD.EmployeeName,
		EC.MobileNumber AS MobileNo,	
		EC.CompanyEmail AS EmailId,
		replace (
		replace (
		replace (
		replace (
		replace (
		replace(@rTemplate,'[EmployeeName]',ISNULL(@lEmployeeName,'')),
		'[LeaveFromDate]',ISNULL(@lLeaveFromDate,'')),
		'[LeaveToDate]',ISNULL(@lLeaveToDate,'')),
		'[LeaveReason]',ISNULL(@lLeaveReason,'')),
		'[LeaveStatus]',ISNULL(@lLeaveStatus,'')),
		'[ActionByEmployeeName]',ISNULL(@lActionByEmployeeName,''))
			AS MsgText,
		@rSubject AS Subject,		
		95 AS SourceTypeId,
		EM.Id AS SourceId,
		95 AS ReceiverSourceTypeId,
		EM.Id AS ReceiverSourceId,
		ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		ECD.EmployeeName AS Name,
		EM.OrgId,
		OM.OrgGroupId

FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.vEmployeeCommonDetail ECD ON EM.Id = ECD.EmployeeId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id	

		WHERE 
		EM.Id = @lEmployeeId 
		--AND EM.OrgId = @rOrgId

END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pLessonPlanComplete]
	 	 
		 @rEmployeeName nvarchar(max),
		 @rSubjectName nvarchar(max),
		 @rTopic nvarchar(max),
		 @rStartDate nvarchar(max),
		 @rEndDate nvarchar(max),
	 	 @rBatchId int,	 	 	 	
	 	 @rOrgId int,
		 @rClassId bigint,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)='',
		 @rDivisionId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 

			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(
			replace(
			replace (
			replace (
			replace(@rTemplate,'[EmployeeName]',@rEmployeeName),			
			'[Subject]',@rSubjectName),
			'[Topic]',@rTopic),
			'[StartDate]',@rStartDate),
			'[EndDate]',@rEndDate)
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			@rEmployeeName AS EmployeeName,
			@rSubjectName AS Subject,
			@rTopic AS StartDate,
			@rEndDate AS EndDate,
			SC.WhatsAppContactNo
		
		
	From 
		sStudent.vStudentCommunication SC
	WHERE
	
		 (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND (SC.ClassId = @rClassId)
		AND SC.DivisionId = @rDivisionId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pMonthlyAttendanceGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rForYear smallint,
	 	 @rForMonth tinyint,
	 	 @rMailSubject nvarchar(500)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),--Added (+ CONVERT(varchar, CONVERT(datetime, sCommon.fGetDate()), 103)) by dhanajay for mantis -35730 
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ForYear]',MR.ForYear),
			'[ForMonth]',MM.Title),
			'[TotalCount]',MR.TotalCount),
			'[PresentCount]',MR.PresentCount),
			'[AbsentCount]',MR.AbsentCount),
			'[AveragePresence]',MR.AveragePresence),
			'[AbsentDates]',MR.AbsentDays)
			 AS MsgText,
			 @rMailSubject AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 SC.AcademicId AS ReceiverSourceId,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 Mr.ForYear,
			 MM.Title AS ForMonth,
			 MR.TotalCount,
			 MR.PresentCount,
			 MR.AbsentCount,
			 MR.AveragePresence,
			 MR.AbsentDays AS AbsentDates,
			 SC.WhatsAppContactNo
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SC.AcademicId	
			AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
			AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
	INNER JOIN sCommon.tMonthMaster MM ON MR.ForMonth = MM.Id
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
		ORDER BY SC.DivisionOrderIndex,SC.Rollno
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pMonthlySubjectwiseAttendanceGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rForYear smallint,
	 	 @rForMonth tinyint,
	 	 @rMailSubject nvarchar(500)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	select 
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		replace(
		replace (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace(@rTemplate,'[Name]',SC.Name),--Added (+ CONVERT(varchar, CONVERT(datetime, sCommon.fGetDate()), 103))by dhananjay for mantis : 35730
		'[Class]',SC.ClassName),
		'[Division]',SC.DivisionName),
		'[ForYear]',MY.YearNumber),
		'[ForMonth]',MM.Title),
		'[TotalCount]',(isnull(TCount,0.00)+isnull(ACount,0.00))),
		'[PresentCount]',convert(decimal(5,2),isnull(TCount,0.00))),
		'[AbsentCount]',convert(decimal(5,2),isnull(ACount,0.00))),
		'[AveragePresence]',case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
							convert(decimal(5,2),(convert(decimal(5,2),isnull(TCount,0.00)*100)/convert(decimal(5,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
							else 
							0.00 end),
		'[AbsentDates]',[sAttendance].[fAbsentDaysGet](MY.MonthNumber,MY.YearNumber, 5,@rSubjectId,SC.AcademicId)),
		'[SubjectName]',CS.SubjectName)
			AS MsgText,
			 
			@rMailSubject AS Subject,
			2001 AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			MY.YearNumber as ForYear,
			MM.Title AS ForMonth,
			(isnull(TCount,0.00)+isnull(ACount,0.00)) as TotalCount,
			convert(decimal(5,2),isnull(TCount,0.00)) as PresentCount,
			convert(decimal(5,2),isnull(ACount,0.00)) as AbsentCount,
			case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
							convert(decimal(5,2),(convert(decimal(5,2),isnull(TCount,0.00)*100)/convert(decimal(5,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
							else 
							0.00 end as AveragePresence,
			[sAttendance].[fAbsentDaysGet](MY.MonthNumber,MY.YearNumber, 5,@rSubjectId,SC.AcademicId) AS AbsentDates,
			SC.WhatsAppContactNo
	 from 
	sStudent.vStudentCommunication SC 
	LEFT JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SC.BatchId
		AND MY.MonthNumber=@rForMonth AND MY.YearNumber=@rForYear
	--LEFT JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SC.ClassId
	--	AND MS.ForMonth=MY.MonthNumber AND MS.ForYear=MY.YearNumber AND MS.BatchId=@rBatchID
	--LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SC.AcademicId
	--	AND SS.ForMonth=MY.MonthNumber AND SS.ForYear=MY.YearNumber
	LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS TCount 
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 		
			SR1.AttendanceTypeId=5
			AND (SR1.SubjectId=@rSubjectId)
			AND (DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth  )
			AND (DATENAME(YEAR,SR1.AttendanceDate)=@rForYear ) 		 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) TC ON TC.AcademicId = SC.AcademicId
    LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS ACount  
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 
		   SR1.IsPresent = 0		
			AND SR1.AttendanceTypeId=5
			AND (SR1.SubjectId=@rSubjectId) 
			AND (DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth  )
			AND (DATENAME(YEAR,SR1.AttendanceDate)=@rForYear ) 		 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) AC ON AC.AcademicId = SC.AcademicId
	INNER JOIN sCommon.tMonthMaster MM ON MY.MonthNumber = MM.Id
	Inner JOIn sSetup.vClassSubject CS  On  CS.IsObsolete = 0 AND CS.ClassId=@rClassId AND CS.SubjectId=@rSubjectId
	WHERE
	(MY.BatchId=@rBatchId) 
	 AND SC.BatchId = @rBatchId
	 AND ((SC.ClassId = @rClassId))
	 AND ((SC.DivisionId = @rDivisionId) OR @rDivisionId=0)
	 AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pMultiPhotoCategoryGet]	 
	 @rSourceTypeId smallint,
	 @rOrgGroupId int,
	 @rOrgId int,
	 @rPhotoCategoryId bigint,
	 @rUserId bigint,
	 @rTemplate nvarchar(max) = '',
	 @rSubject nvarchar(100)='',
	 @rOrgGroupBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN 		
	IF @rSourceTypeId=2021
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Organization'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PC.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sSetup.tOrganizationMaster OM
			LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId
			LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id AND ((UO.UserId=@rUserId) OR (@rUserId=0))
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.OrgId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2021
		WHERE 
			OM.OrgGroupId=@rOrgGroupId 
			AND PC.ScopeSourceId IS NOT NULL 
			AND PC.ScopeSourceTypeId=@rSourceTypeId
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND PM.Id=@rPhotoCategoryId
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	END
	IF @rSourceTypeId=2017
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Department'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PC.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		 FROM 
			sCommunication.tMultiPhotoCategoryMaster PM
			LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id = PC.MultiPhotoCategoryId AND PC.ScopeSourceTypeId=@rSourceTypeId 
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.DepartmentId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2017 
			INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId= SC.DepartmentId AND UA.SourceTypeId=2017 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
		 WHERE 
			SC.OrgId=@rOrgId  
			AND PC.ScopeSourceId IS NOT NULL
			AND PC.ScopeSourceTypeId=@rSourceTypeId
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND PM.Id=@rPhotoCategoryId
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	END	
	IF @rSourceTypeId=2016
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]',ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]','Class'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PC.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		 FROM  sCommunication.tMultiPhotoCategoryMaster PM 
			LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id = PC.MultiPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.ClassId = PC.ScopeSourceId			
		 WHERE 
			OrgId=@rOrgId 
			AND PC.ScopeSourceId IS NOT NULL 
			AND PC.ScopeSourceTypeId=@rSourceTypeId   
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND (SC.ClassId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2016) 
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
			AND MultiPhotoCategoryId=@rPhotoCategoryId
	END
	IF @rSourceTypeId=2005
	BEGIN
		IF(@lConfigValue='Class Teacher' OR @lConfigValue='Class Teacher Batch')
		BEGIN
			SELECT  
				REPLACE (REPLACE (REPLACE (
				REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Division'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
				@rSubject AS [Subject],
				PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.ParentContactNo AS MobileNo,
				PC.ScopeSourceTypeId AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgGroupId,
				SC.OrgId,
				SC.ParentEmail AS EmailId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM  
				sSetup.tDivisionMaster OM
				LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId
				LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2005 
			WHERE 
				SC.OrgId=@rOrgId
				AND OM.InchargeemployeeId = (SELECT ISNULL(SourceId,0) FROM sSecurity.tUser WHERE Id=@rUserId AND OrgId= @rOrgId) 
				AND PC.ScopeSourceId IS NOT NULL 
				AND PC.ScopeSourceTypeId=@rSourceTypeId
				AND SC.StatusId = 1 
				AND SC.IsActiveBatch = 1 
				AND SC.IsBlockAllAlert=0
				AND SC.OrgGroupBatchId=@rOrgGroupBatchId
				AND (SC.DivisionId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2005)
				AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
				AND MultiPhotoCategoryId=@rPhotoCategoryId
		END
		ELSE IF(@lConfigValue='Academic Setup')
		BEGIN			
			SELECT 
				REPLACE (REPLACE (REPLACE (
				REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Division'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
				@rSubject AS [Subject],
				PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.ParentContactNo AS MobileNo,
				PC.ScopeSourceTypeId AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgGroupId,
				SC.OrgId,
				SC.ParentEmail AS EmailId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sSetup.tDivisionMaster OM
				INNER JOIN sSetup.tOrganizationMaster tOM ON tOM.Id = OM.OrgId
				INNER JOIN sAcademic.vTeacherSubjectDivision TSD ON TSD.OrgId=OM.OrgId AND TSD.DivisionId= OM.Id
				LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId
				LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2005 
			WHERE
				TSD.EmployeeId= (SELECT ISNULL(SourceId,0) FROM sSecurity.tUser WHERE Id=@rUserId)					 
				AND PC.ScopeSourceId IS NOT NULL  
				AND PC.ScopeSourceTypeId=@rSourceTypeId
				AND SC.StatusId = 1 
				AND SC.IsActiveBatch = 1 
				AND SC.IsBlockAllAlert=0
				AND SC.OrgGroupBatchId=@rOrgGroupBatchId
				AND (SC.DivisionId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2005)
				AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
				AND MultiPhotoCategoryId=@rPhotoCategoryId
		END
		ELSE IF(@lConfigValue='User Access')
		BEGIN
			SELECT
				REPLACE (REPLACE (REPLACE (
				REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Division'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
				@rSubject AS [Subject],
				PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.ParentContactNo AS MobileNo,
				PC.ScopeSourceTypeId AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgGroupId,
				SC.OrgId,
				SC.ParentEmail AS EmailId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM sSetup.tDivisionMaster OM
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = OM.Id AND U.SourceTypeId= 2005
				LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId
				LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2005 
			WHERE 
				OM.OrgId=@rOrgId  
				AND U.UserId = (SELECT ISNULL(ID,0) FROM sSecurity.tUser WHERE Id=@rUserId AND OrgId= @rOrgId)
				AND PC.ScopeSourceId IS NOT NULL  
				AND PC.ScopeSourceTypeId=@rSourceTypeId
				AND SC.StatusId = 1 
				AND SC.IsActiveBatch = 1 
				AND SC.IsBlockAllAlert=0
				AND SC.OrgGroupBatchId=@rOrgGroupBatchId
				AND (SC.DivisionId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2005)
				AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
				AND MultiPhotoCategoryId=@rPhotoCategoryId
		END
		ELSE
		BEGIN
			SELECT
				REPLACE (REPLACE (REPLACE (
				REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Division'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
				@rSubject AS [Subject],
				PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.ParentContactNo AS MobileNo,
				PC.ScopeSourceTypeId AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgGroupId,
				SC.OrgId,
				SC.ParentEmail AS EmailId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM  
				sSetup.tDivisionMaster OM
				LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId
				LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2005 
			WHERE 
				OM.OrgId=@rOrgId  
				AND PC.ScopeSourceId IS NOT NULL  
				AND PC.ScopeSourceTypeId=@rSourceTypeId
				AND SC.StatusId = 1 
				AND SC.IsActiveBatch = 1 
				AND SC.IsBlockAllAlert=0
				AND SC.OrgGroupBatchId=@rOrgGroupBatchId
				AND (SC.DivisionId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2005)
				AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
				AND MultiPhotoCategoryId=@rPhotoCategoryId
		END
	END
	IF @rSourceTypeId=2014
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Hostel'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PC.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM
			sCommunication.tMultiPhotoCategoryMaster PM
			LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id = PC.MultiPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
			LEFT JOIN sHostel.tHostelAdmission HA ON HA.Hosteld = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2014
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = HA.SourceId AND HA.SourceTypeId=2003
			INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId = HA.Hosteld AND UA.SourceTypeId=2014 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
		WHERE
			PM.OrgGroupId=@rOrgGroupId  
			AND PC.ScopeSourceId IS NOT NULL  
			AND PC.ScopeSourceTypeId=@rSourceTypeId
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND PM.Id=@rPhotoCategoryId
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
			AND SC.OrgId = @rOrgId
	END 
	IF @rSourceTypeId=2029
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'House'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PC.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM  
			sCommunication.tMultiPhotoCategoryMaster PM
			LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id = PC.MultiPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
			LEFT JOIN sStudent.tStudentOther SO ON SO.HouseId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2029
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = SO.StudentId
		WHERE
			SC.OrgId=@rOrgId  
			AND PC.ScopeSourceId IS NOT NULL  
			AND PC.ScopeSourceTypeId=@rSourceTypeId
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND PM.Id=@rPhotoCategoryId
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	END	 	
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Student'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PC.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			PM.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sCommunication.tMultiPhotoCategoryMaster PM
			LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id = PC.MultiPhotoCategoryId AND PC.ScopeSourceTypeId=@rSourceTypeId
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 2003
		WHERE 
			SC.OrgId=@rOrgId  
			AND PC.ScopeSourceId IS NOT NULL  
			AND PC.ScopeSourceTypeId=@rSourceTypeId
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND PM.Id=@rPhotoCategoryId
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	END
	IF(@rSourceTypeId=95)
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Employee'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PC.ScopeSourceTypeId AS ReceiverSourceTypeId,
			vEC.EmployeeId AS ReceiverSourceId,
			vEC.MobileNumber AS MobileNo,
			PC.ScopeSourceTypeId AS SourceTypeId,
			vEC.EmployeeId AS SourceId,
			PM.OrgGroupId,
			vEC.OrgId,
			vEC.CompanyEmail AS EmailId,
			ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sCommunication.tMultiPhotoCategoryMaster PM
			LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PM.Id = PC.MultiPhotoCategoryId AND PC.ScopeSourceTypeId=@rSourceTypeId
			LEFT JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = PC.ScopeSourceId AND PC.ScopeSourceTypeId = 95
		WHERE 
			ISNULL(vEC.IsOtherUser,0) = 0 
			AND vEC.StatusId=7			
			AND (ISNULL(vEC.CompanyEmail,'') <> '' or WhatsAppContactNo <> '')	
			AND PC.ScopeSourceId IS NOT NULL  
			AND PC.ScopeSourceTypeId=@rSourceTypeId
			AND vEC.OrgId=@rOrgId  
			AND PM.Id=@rPhotoCategoryId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pNewAdmissionGet]
	
	@rClassId int,
	@rDivisionId int,
	@rOrgId smallint,
	@rBatchId int,
	@rTemplate nvarchar(max),
	@rFromDate date,
	@rToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	declare @Sql nvarchar(max)
	
	SELECT 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (					
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[SchoolName]',OM.Title)
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 OM.Title AS SchoolName,
			 ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
	FROM 
			sStudent.vStudentCommunication SC
			INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SC.StudentId
				AND ((ISNULL(SA.AdmissionDate,'') >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((ISNULL(SA.AdmissionDate,'') <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	WHERE	
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
		
		ORDER BY SC.ClassOrderIndex,SC.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pNewAdmissionInquiryGet]
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	 @rOrgId int,
	 @rFromDate datetime=Null,
	 @rToDate datetime=Null,
	 @rDepartmentId int = 0,
	 @rTemplate nvarchar(max),
	 @rSubject nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT
		 AI.ForBatchId AS BatchId
		,AI.ForClassId AS ClassId
		,AI.InquiryStatusId AS StatusId
		,AI.OrgId
		,AI.OrgGroupId
		,ISNULL(AI.Number,0) AS InquiryNumber
		,ISNULL(AI.InquiryDate,'') AS InquiryDate
		,ISNULL(CM.Title,'') AS ClassName
		,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
		,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name
		,REPLACE (
		REPLACE (
		REPLACE (
	    REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName),
		'[Organization]',ISNULL(OM.DisplayTitle,'')),
		'[Class]',ISNULL(CM.Title,'')),
		'[InquiryNumber]', ISNULL(AI.Number,'')),
		'[InquiryDate]', CONVERT(VARCHAR(10), AI.InquiryDate, 103)),
		'[InquiryStatus]', ISNULL(SM.Title,''))
		 AS Template
		,@rSubject AS Subject
		,AI.ContactNo AS MobileNo
		,AI.ContactEmail AS EmailId
		,ISNULL(AI.Id,0) AS SourceId
		,CONVERT(smallint,0) AS SourceTypeId
		,ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo
		,0 AS ReceiverSourceTypeId
		,ISNULL(AI.Id,0) AS ReceiverSourceId
		,ISNULL(OM.DisplayTitle,'') AS Organization
	FROM 

		sAdmission.tAdmissionInquiry AI
		INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
		LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
  WHERE   
		(AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rBatchId) OR (@rBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.ForClassId=@rClassId) OR (@rClassId=0))
	  AND (AI.InquiryStatusId  = @rStatusId OR @rStatusId = 0)
	  AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))		    
END

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pNotificationLogAdd]
	
	@rXML nvarchar(max),
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
BEGIN TRY
	
	BEGIN TRANSACTION
	 
	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 @rOrgGroupId, 'sAlert.tNotificationLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SET @lFromNextNumber=@lNextNumber-1
	
	INSERT INTO sAlert.tNotificationLog
		(
			Id,
			OSTypeId,
			SourceTypeId,
			SourceId,
			EventId,
			DocumentId,
			MessageTitle,
			NotificationMessage,
			APIResponse,
			StatusCode,
			CreatedUserId,
			CreatedDateTime,
			IsViewed
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY SourceId),
			OSTypeId,
			SourceTypeId,
			SourceId,
			EventId,
			DocumentId,
			MessageTitle,
			NotificationMessage,
			APIResponse,
			StatusCode,
			CreatedUserId,
			sCommon.fGetDate(),
			(CASE WHEN OSTypeId = 3 THEN 0 ELSE NULL END)IsViewed
			
	FROM OPENXML (@intDoc, '/Table/NotificationLog', 1)
	WITH
	(
			OSTypeId tinyint 'OSTypeId',
			SourceTypeId smallint 'SourceTypeId',
			SourceId bigint 'SourceId',
			EventId int 'EventId',
			DocumentId bigint 'DocumentId',
			MessageTitle nvarchar(200) 'MessageTitle',
			NotificationMessage nvarchar(max) 'NotificationMessage',
			APIResponse nvarchar(500) 'APIResponse',
			StatusCode nvarchar(50) 'StatusCode',
			CreatedUserId bigint 'CreatedUserId'
	)
	
		SELECT @lCount = COUNT(1) FROM OPENXML (@intDoc, '/Table/NotificationLog', 1)
			WITH (SourceId bigint)
				 
		SET @lNextNumber  = @lCount + @lFromNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAlert.tNotificationLog', @rCurrentNumber = @lNextNumber 
		
		EXEC sp_xml_removedocument @intDoc
		
		SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAlert].[pNotificationLogGet]

		@rOSTypeId tinyint,
		@rUserId bigint,
		@rUserSourceTypeId smallint,
		@rUserSourceId bigint,
		@rSyncedNotificationId bigint,
		@rFromDate Date='',
		@rToDate Date='',
		@rEventId int=0
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lAcademicId bigint
	DECLARE @lEmployeeId bigint
	DECLARE @lStudentId bigint
	DECLARE @lDivisionId int
	DECLARE @lClassId int
	DECLARE @lDepartmentId int
	DECLARE @lOrgId int
	
	IF(@rUserSourceTypeId=2003)
	BEGIN
		SELECT 
		@lAcademicId=AcademicId,
		@lStudentId=StudentId,
		@lDivisionId=DivisionId,
		@lClassId=ClassId,
		@lDepartmentId=DepartmentId,
		@lOrgId=OrgId
		FROM sStudent.vStudentAcademic WHERE StudentId = @rUserSourceId AND IsActiveBatch=1
	 
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName -- This changes done by parth as discussed with rajendrasir (Just added createdname)
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId NOT IN (14,15)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND (NL.EventId = 14) AND (NL.SourceTypeId=2001 OR NL.SourceTypeId=2003 OR  NL.SourceTypeId=2005 OR NL.SourceTypeId=2016)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 2
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId  AND (C.AssigneeId=2 OR C.AssigneeId=1) 
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2021
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		 
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 2
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId AND (C.AssigneeId=2 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2017
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )

		UNION ALL
		--Commented for mantis : 42198
		--SELECT 
		--		NL.Id AS NotificationId,
		--		NL.EventId,
		--		NL.DocumentId,
		--		NL.MessageTitle,
		--		NL.NotificationMessage AS 'Message',
		--		CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
		--		--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
		--		EM.Title as EventName,
		--		u.DisplayTitle as CreatedName
		--FROM 
		--	sAlert.tNotificationLog NL
		--	Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
		--	INNER JOIN sCommunication.tAssignmentScope AC ON AC.SourceTypeId = NL.SourceTypeId AND AC.SourceId = NL.SourceId AND AC.AssignmentId=NL.DocumentId
		--	INNER JOIN sCommunication.tAssignment A ON A.Id = AC.AssignmentId AND AC.AssignmentId=NL.DocumentId 
		--	LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		--WHERE 
		--(
		--(NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		--OR(NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		--) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		--AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		--AND (NL.EventId = 15) AND (NL.SourceTypeId=2003 OR NL.SourceTypeId=2005)
		--AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		--Commented for mantis : 42198

		--Added for mantis : 42198
		SELECT 
	NL.Id AS NotificationId,
	NL.EventId,
	NL.DocumentId,
	NL.MessageTitle,
	NL.NotificationMessage AS 'Message',
	CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
	EM.Title as EventName,
	U.DisplayTitle as CreatedName
FROM 
	sAlert.tNotificationLog NL
	Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
	INNER JOIN sCommunication.tAssignmentScope AC ON AC.SourceTypeId = NL.SourceTypeId AND NL.SourceTypeId = 2005 
		AND AC.SourceId = NL.SourceId AND AC.AssignmentId=NL.DocumentId
	INNER JOIN sCommunication.tAssignment A ON A.Id = AC.AssignmentId AND AC.AssignmentId=NL.DocumentId 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.SourceId 
	INNER JOIN [sSetup].[tClassSubject] CS ON CS.SubjectId = A.SubjectId AND DM.ClassId = CS.ClassId
	LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
WHERE 
CS.IsOptional = 0 AND
(
(NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
OR(NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
AND (NL.EventId = 15) AND (NL.SourceTypeId=2003 OR NL.SourceTypeId=2005)
AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )

UNION ALL

SELECT 
	NL.Id AS NotificationId,
	NL.EventId,
	NL.DocumentId,
	NL.MessageTitle,
	NL.NotificationMessage AS 'Message',
	CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
	EM.Title as EventName,
	U.DisplayTitle as CreatedName
FROM 
	sAlert.tNotificationLog NL
	Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = NL.SourceId AND NL.SourceTypeId = 2003  AND IsActiveBatch=1
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
	INNER JOIN sCommunication.tAssignmentScope AC ON NL.SourceTypeId = 2003 AND AC.SourceId = DM.Id AND AC.AssignmentId=NL.DocumentId
	INNER JOIN sCommunication.tAssignment A ON A.Id = AC.AssignmentId AND AC.AssignmentId=NL.DocumentId 
	INNER JOIN [sSetup].[tClassSubject] CS ON CS.SubjectId = A.SubjectId AND DM.ClassId = CS.ClassId AND SA.ClassId = CS.ClassId
	INNER JOIN [sAssessment].[tOptionalSubject] AS OS ON OS.ClassSubjectId = CS.Id AND OS.AcademicId = SA.AcademicId
	LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
WHERE 
CS.IsOptional = 1 AND
((NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)) 
AND NL.Id > @rSyncedNotificationId 
AND OSTypeId=@rOSTypeId
AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
AND (NL.EventId = 15) AND (NL.SourceTypeId=2003)
AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
--Added for mantis : 42198		
	END
		
	IF(@rUserSourceTypeId=95)
	BEGIN
	
		SELECT 
		@lEmployeeId=EmployeeId,
		@lDepartmentId=OrganizationDepartmentId,
		@lOrgId=OrgId
		FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId != 14
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND (NL.EventId = 14 AND NL.SourceTypeId=95)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 3
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId  AND (C.AssigneeId=3 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2021
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )

		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 3
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId AND (C.AssigneeId=3 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2017
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pNotificationViewGet]
	@rSourceId bigint = 0,
	@rSourceTypeId smallint = 0,
	@rIsFlag bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
declare  @lAlertgrid NVARCHAR(max)=''
BEGIN

IF(@rIsFlag = 0)
BEGIN
select 'Notification' AS SourceEvent,EM.Title,AL.MessageTitle,[sCommon].[fXMLTagsReplace](AL.NotificationMessage) as AlertMessage,AL.CreatedDateTime
	Into #tempAlertLogStudent360
	FROM
			sAlert.tNotificationLog AL
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
	WHERE  AL.SourceId = @rSourceId AND AL.SourceTypeId = @rSourceTypeId
	ORDER BY AL.CreatedDateTime DESC	
	SELECT  @lAlertgrid = @lAlertgrid + '<tr>
	<td align="left" scope="col">' + isnull(SourceEvent,'') + '</td>
	<td align="left" scope="col">' + isnull(Title,'') + '</td>
	<td align="left" scope="col">' +  isnull(MessageTitle,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertMessage,'') + '</td>
	<td align="left" scope="col">' + Convert(varchar,isnull(CreatedDateTime,''),120) + '</td>
	</tr>'	
	FROM #tempAlertLogStudent360

	DROP TABLE #tempAlertLogStudent360
END
ELSE
BEGIN
	select 'Notification' AS SourceEvent,EM.Title,AL.MessageTitle,[sCommon].[fXMLTagsReplace](AL.NotificationMessage) as AlertMessage,AL.CreatedDateTime
	Into #tempAlertLogStudentDetailForm
	FROM
			sAlert.tNotificationLog AL
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
	WHERE  AL.SourceId = @rSourceId AND AL.SourceTypeId = @rSourceTypeId
	AND CAST(AL.CreatedDateTime AS DATE) = CAST(sCommon.fGetDate() AS DATE)
	ORDER BY AL.CreatedDateTime DESC	
	SELECT  @lAlertgrid = @lAlertgrid + '<tr>
	<td align="left" scope="col">' + isnull(SourceEvent,'') + '</td>
	<td align="left" scope="col">' + isnull(Title,'') + '</td>
	<td align="left" scope="col">' +  isnull(MessageTitle,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertMessage,'') + '</td>
	<td align="left" scope="col">' + Convert(varchar,isnull(CreatedDateTime,''),120) + '</td>
	</tr>'	
	FROM #tempAlertLogStudentDetailForm

	DROP TABLE #tempAlertLogStudentDetailForm
END
END
 SELECT ISNULL(@lAlertgrid,'') AS Alertgrid

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pOnlineAdmissionGet]
	
	@rAdmissionFormId bigint,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
SELECT 
		
AF.Id AS AdmissionFormId,
		
AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		
AF.ContactNo AS MobileNo,	
		
AF.ContactEmail AS EmailId,
REPLACE (    
REPLACE (
		
REPLACE (
		
REPLACE (
		
REPLACE (
		
REPLACE (
		
REPLACE(@rTemplate,'[Name]',AF.FirstName+' '+AF.MiddleName+' '+AF.LastName),'[Organization]',ISNULL(OM.DisplayTitle,'')),
		'[ForClass]',ISNULL(CM.Title,'')),'[AdmissionFormNo]',ISNULL(AF.FormNo,0)),'[BatchName]',ISNULL(BM.Title,'')),'[Amount]',ISNULL(AC.FormFeeAmount,0)),'[FormPassword]',ISNULL(AF.FormPassword,''))	AS MsgText,
		
@rSubject AS [Subject],
0 As ReceiverSourceId,
0 As ReceiverSourceTypeId,
AF.WhatsappContactNo AS WhatsAppContactNo,		--add for 29511 mantis
ISNULL(AF.FormNo,0) AS AdmissionFormNo,
ISNULL(OM.DisplayTitle,'') AS Organization,
ISNULL(CM.Title,'') AS ForClass,
ISNULL(BM.Title,'') AS BatchName,
ISNULL(AC.FormFeeAmount,0) AS Amount,
ISNULL(AF.FormPassword,'') AS FormPassword


FROM sAdmission.tAdmissionForm AF
INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
LEFT JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId = CM.Id  AND AC.BatchId= BM.Id
INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
WHERE	
		
AF.Id = @rAdmissionFormId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pOnlineLearningAbsentStudentListGet]
	@rOnlineLearningId bigint,
	@rTemplate nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		 SELECT 
			A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[LearningType]',DM.Title),
			'[Name]',A.Name),
			'[StartDate]',CONVERT(varchar(11),ISNULL(OL.StartDate,'') ,103)),
			'[EndDate]',CONVERT(varchar(11),ISNULL(OL.EndDate,'') ,103)),
			'[Subject]',SM.Title),
			'[Topic]',ISNULL(TM.Title,'')),
			'[Teacher]',EE.EmployeeName),
			'[Title]',OL.Title),
			'[StartTime]',CONVERT(varchar(11),ISNULL(OL.StartTime,'') ,8)),
			'[EndTime]',CONVERT(varchar(11),ISNULL(OL.EndTime,'') ,8))
			AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 A.OrgId AS OrgId,
			 (SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			 A.AcademicId AS ReceiverSourceId,
			 A.AcademicId AS SourceId,
			 2001 AS SourceTypeId,
			 DM.Title AS LearningType,
			 CONVERT(varchar(11),ISNULL(OL.StartDate,'') ,103) AS StartDate,
			 CONVERT(varchar(11),ISNULL(OL.EndDate,'') ,103) AS EndDate,
			 SM.Title AS Subject,
			 ISNULL(TM.Title,'') AS Topic,
			 EE.EmployeeName AS Teacher,
			 OL.Title AS Title,
			 CONVERT(varchar(11),ISNULL(OL.StartTime,'') ,8) AS StartTime,
			 CONVERT(varchar(11),ISNULL(OL.EndTime,'') ,8) AS EndTime,
			 A.WhatsAppContactNo
	FROM 
		sAcademic.tOnlineLearning OL
		INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
		LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
		INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = OL.TeacherEmployeeId
		INNER JOIN (
			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2003

			UNION ALL

			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2001

			UNION ALL	
																			 			  
			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
				 
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND  OLS.SourceTypeId = 2017

			UNION ALL		
															 			 				  
			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OLS.SourceId AND SD.BatchId = OL.BatchId  
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OLS.SourceId AND SD.BatchId = OL.BatchId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId 
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2021
			
		) as A ON A.OnlineLearningId = OL.Id 
		LEFT JOIN sAcademic.tOnlineLearningAttendance OLA ON OLA.OnlineLearningId = OL.Id AND OLA.AcademicId = A.AcademicId
	WHERE
		OL.Id = @rOnlineLearningId AND ISNULL(OLA.IsPresent,0) <> 1
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pOnlineLearningLectureAdd]
	
		 @rOnlineLearningId bigint,
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[LearningType]',DM.Title),
			'[StartDate]',CONVERT(varchar(11),ISNULL(OL.StartDate,'') ,103)),
			'[EndDate]',CONVERT(varchar(11),ISNULL(OL.EndDate,'') ,103)),
			'[Subject]',SM.Title),
			'[Topic]',ISNULL(TM.Title,'')),
			'[Teacher]',EE.EmployeeName),
			'[Title]',OL.Title)
			AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 A.OrgId AS OrgId,
			 (SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			 A.AcademicId AS ReceiverSourceId,
			 A.AcademicId AS SourceId,
			 2001 AS SourceTypeId,
			 DM.Title AS LearningType,
			 CONVERT(varchar(11),ISNULL(OL.StartDate,'') ,103) AS StartDate,
			 CONVERT(varchar(11),ISNULL(OL.EndDate,'') ,103) AS EndDate,
			 SM.Title AS Subject,
			 ISNULL(TM.Title,'') AS Topic,
			 EE.EmployeeName AS Teacher,
			 OL.Title AS Title,
			 A.WhatsAppContactNo
	FROM 
		sAcademic.tOnlineLearning OL
		INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
		LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
		INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = OL.TeacherEmployeeId
		INNER JOIN (
			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2003

			UNION ALL

			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2001

			UNION ALL	
																			 			  
			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND  OLS.SourceTypeId = 2017

			UNION ALL		
															 			 				  
			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OLS.SourceId AND SD.BatchId = OL.BatchId  
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				OL.Id as OnlineLearningId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2021
			
		) as A ON A.OnlineLearningId = OL.Id
	WHERE
		OL.Id = @rOnlineLearningId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pOnlineRecruitmentGet]
	
	@rCandidateId bigint,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
SELECT 
		
CM.CandidateNumber AS CandidateNumber,
CM.FirstName+' '+CM.MiddleName+' '+CM.LastName AS Name,
CM.ApplicationPassword AS Password,
V.Title AS Vacancy,
CM.MobileNo AS MobileNo,	
CM.PersonalEmail AS EmailId,
REPLACE (
REPLACE (
REPLACE (
REPLACE (
REPLACE(@rTemplate,
		'[Name]',CM.FirstName+' '+CM.MiddleName+' '+CM.LastName),
		'[CandidateNo]',ISNULL(CM.CandidateNumber,'')),
		'[Password]',ISNULL(CM.ApplicationPassword,'')),
		'[Vacancy]',ISNULL(V.Title,0)),
		'[ApplicationNo]',ISNULL(CM.ApplicationNumber,0))		
		AS MsgText,
		
@rSubject AS [Subject],
0 As ReceiverSourceId,
0 As ReceiverSourceTypeId,
ISNULL(CM.CandidateNumber,'') AS CandidateNo,
ISNULL(V.Title,0) AS Vacancy,
ISNULL(CM.ApplicationNumber,0) AS ApplicationNo,
ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo	--add for mantis:34273

FROM sRecruitment.tCandidateMaster CM
INNER JOIN sRecruitment.tVacancy V ON CM.VacancyId=V.Id AND CM.OrgGroupId=V.OrgGroupId
WHERE	
		
CM.Id = @rCandidateId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pOtherGroupDetailAdd]

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

BEGIN
	
	DELETE FROM sAlert.tOtherGroupDetail WHERE OtherGroupId = @rOtherGroupId
	
	INSERT INTO sAlert.tOtherGroupDetail 
		(
			OtherGroupId,
		    MobileNo,
		    Email, 
		    Title
		)
		
		SELECT		
			
			@rOtherGroupId,
			MobileNo,
			Email,
			Title
						
		FROM OPENXML (@loDoc, '/Table/OtherGroupDetail', 1)
		WITH 
			 ( 
				MobileNo nvarchar(20),
			    Email nvarchar(100),
			    Title nvarchar(100)
			  ) 
		
        SELECT 1 AS Result
	END	 
	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pOtherGroupDetailGet]
	 
	 @rOtherGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OGM.Title,
			OGM.Code,
			OGM.IsObsolete,
			ISNULL(OGM.Id,0) AS OtherGroupId,
			ISNULL(OGD.MobileNo,'') AS MobileNo,
			ISNULL(OGD.Email,'') AS Email,
			ISNULL(OGD.Title,'') AS OtherGroupDetailTitle
  FROM 
			sAlert.tOtherGroupMaster OGM
			LEFT JOIN sAlert.tOtherGroupDetail OGD ON OGD.OtherGroupId=OGM.Id
WHERE 
			OGM.Id=@rOtherGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pOtherGroupMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAlert.tOtherGroupMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAlert.tOtherGroupMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAlert.tOtherGroupMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAlert.tOtherGroupMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END

	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAlert.tOtherGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAlert.tOtherGroupMaster
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
		    SELECT @lNextNumber AS Result
       
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAlert.tOtherGroupMaster
	    SET
			  Code=@rCode
	         ,Title=@rTitle
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result

	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pOtherGroupMasterDelete]
@rId int
AS
BEGIN
BEGIN TRY
	  BEGIN
		DELETE FROM sAlert.tOtherGroupDetail WHERE OtherGroupId IN (SELECT Id FROM sAlert.tOtherGroupMaster WHERE Id=@rId)
		DELETE	FROM sAlert.tOtherGroupMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pOtherGroupMasterGet]
          
           --@rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int           
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			Set @rCode = sCommon.fSearchStringGet(@rCode)
		--END

BEGIN
SELECT OGM.Id as OtherGroupId
	  ,OGM.Title
	  ,OGM.Code
      ,OGM.IsObsolete
     
  FROM sAlert.tOtherGroupMaster OGM 
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((OGM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND OGM.OrgGroupId = @rOrgGroupId

	--AND  CCM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pParentPortalLoginGet]
	 	 
	@rOrgId smallint,
	@rBatchId int,
	--@rIsPendingLogin bit,
	--@rIsCreatedLogin bit,
	@rClassId int =0,
	@rDivisionId int=0,
	--@rNotRegister bit=0,
	@rTemplate nvarchar(max),
	@rStudentId bigint = 0,
	@rSubject nvarchar(100)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		replace(replace(replace(replace(@rTemplate,'[UserName]',U.LoginTitle),'[Password]','[Password]'),'[StudentName]',SC.Name),'[Class]', SC.ClassName + '-' + SC.DivisionName)
		 AS Template,
		 --Add for StudentWise
		 replace(replace(replace(replace(@rTemplate,'[UserName]',U.LoginTitle),'[Password]','[Password]'),'[StudentName]',SC.Name),'[Class]', SC.ClassName + '-' + SC.DivisionName)
		 AS MsgText,
		 @rSubject AS Subject,
		 2003 AS ReceiverSourceTypeId,
		 SC.StudentId AS ReceiverSourceId,
		 SC.StudentId AS SourceId,
		 2003 AS SourceTypeId,
		 SC.OrgGroupId,
		 SC.OrgId,
		 SC.ClassName AS Class,
		 SC.DivisionName AS Division,
		 SC.WhatsAppContactNo,
		 U.LoginPassword AS Password
	FROM 
		sStudent.vStudentCommunication SC
		INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
		INNER JOIN sStudent.tStatusMaster SM ON SM.Id = SC.StatusId 
			 
	WHERE 
		(SC.OrgId = @rOrgId)
		AND (SC.BatchId = @rBatchId) 
		AND ((SC.ClassId = @rClassId) OR(@rClassId=0))
		AND ((SC.DivisionId = @rDivisionId) OR(@rDivisionId=0))
		AND SC.StatusId = 1 AND U.ISobsolete = 0
		AND ((SC.StudentId = @rStudentId) OR (@rStudentId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pPDCEntryGet]
	  
	@rSubject nvarchar(100),
	@rTemplate nvarchar(max),
	@rIdNos nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF OBJECT_ID('tempdb..#PDCIDsTempTable') IS NULL
		BEGIN
			CREATE TABLE #PDCIDsTempTable (
				AcademicId BIGINT,
				PDCDetail NVARCHAR(MAX)
			);
		END
			INSERT INTO #PDCIDsTempTable (AcademicId, PDCDetail)
			SELECT 
				PDP.SourceId AS AcademicId,
				STUFF((
					SELECT 
						CHAR(13) + CHAR(10) +'PayType: ' + ISNULL(PTM.Title,'')
						+ ' ChequeDate: ' + convert(varchar,InnerPDP.PaymentClearanceDate,103)
						+ ' ChequeNo: ' + ISNULL(InnerPDP.Chequeno,'')
						+ ' BankName: ' + ISNULL(InnerPDP.BankName,'')
						+ ' Amount: ' + Convert(Varchar(15),ISNULL(InnerPDP.Amount,0))
						+ ' Remark: ' + ISNULL(InnerPDP.Remark,'')
					FROM sFee.tPostDatePayment AS InnerPDP
					INNER JOIN sFinanceCommon.tPayTypeMaster AS PTM ON PTM.Id = InnerPDP.PayTypeId
					WHERE InnerPDP.SourceId = PDP.SourceId
					  AND (InnerPDP.Id IN (SELECT CAST(item AS BIGINT) FROM sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos, '') = '')
					  AND InnerPDP.SourceTypeId = 2001
					FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS PDCDetail
			FROM 
				sFee.tPostDatePayment AS PDP
			WHERE  
				(PDP.Id IN (SELECT CAST(item AS BIGINT) FROM sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos, '') = '')
				AND PDP.SourceTypeId = 2001
			GROUP BY 
				PDP.SourceId;

	SELECT 
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		@rSubject AS Subject,
		replace (
		replace (
		replace (
		replace(@rTemplate,'[Name]',SC.Name),
		'[Code]',SC.Code),
		'[ClassDivision]',SC.ClassName + '/' +SC.DivisionName),
		'[PDCDetails]',pTemp.PDCDetail)
			AS MsgText,				 
		SC.OrgId,
		SC.OrgGroupId,
		SC.AcademicId AS SourceId,
		2001 AS SourceTypeId,
		2001 AS ReceiverSourceTypeId,
		SC.AcademicId AS ReceiverSourceId,
		SC.ClassName AS Class,
		SC.DivisionName AS Division,
		SC.WhatsAppContactNo
					 
	FROM 
		sStudent.vStudentCommunication SC
		INNER JOIN #PDCIDsTempTable pTemp ON pTemp.AcademicId = SC.AcademicId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pPhotoCategoryGet]	 
	 @rSourceTypeId smallint,
	 @rOrgGroupId int,
	 @rOrgId int,
	 @rPhotoCategoryId bigint,
	 @rUserId bigint,
	 @rTemplate nvarchar(max) = '',
	 @rSubject nvarchar(100)='',
	 @rOrgGroupBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN 		
	IF @rSourceTypeId=2021
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Organization'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PM.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sSetup.tOrganizationMaster OM
			LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
			LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id AND ((UO.UserId=@rUserId) OR (@rUserId=0))
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.OrgId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2021
		WHERE 
			OM.OrgGroupId=@rOrgGroupId 
			AND PC.ScopeSourceId IS NOT NULL 
			AND PM.ScopeSourceTypeId=@rSourceTypeId
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND PM.Id=@rPhotoCategoryId
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	END
	IF @rSourceTypeId=2017
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Department'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PM.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		 FROM 
			sCommunication.tPhotoCategoryMaster PM
			LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id = PC.PhotoCategoryId AND PM.ScopeSourceTypeId=@rSourceTypeId 
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.DepartmentId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2017 
			INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId= SC.DepartmentId AND UA.SourceTypeId=2017 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
		 WHERE 
			SC.OrgId=@rOrgId  
			AND PC.ScopeSourceId IS NOT NULL
			AND PM.ScopeSourceTypeId=@rSourceTypeId
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND PM.Id=@rPhotoCategoryId
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	END	
	IF @rSourceTypeId=2016
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]',ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]','Class'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PM.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		 FROM  sCommunication.tPhotoCategoryMaster PM 
			LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.ClassId = PC.ScopeSourceId			
		 WHERE 
			OrgId=@rOrgId 
			AND PC.ScopeSourceId IS NOT NULL 
			AND PM.ScopeSourceTypeId=@rSourceTypeId   
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND (SC.ClassId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2016) 
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
			AND PhotoCategoryId=@rPhotoCategoryId
	END
	IF @rSourceTypeId=2005
	BEGIN
		IF(@lConfigValue='Class Teacher' OR @lConfigValue='Class Teacher Batch')
		BEGIN
			SELECT  
				REPLACE (REPLACE (REPLACE (
				REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Division'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
				@rSubject AS [Subject],
				PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.ParentContactNo AS MobileNo,
				PM.ScopeSourceTypeId AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgGroupId,
				SC.OrgId,
				SC.ParentEmail AS EmailId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM  
				sSetup.tDivisionMaster OM
				LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
				LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2005 
			WHERE 
				SC.OrgId=@rOrgId
				AND OM.InchargeemployeeId = (SELECT ISNULL(SourceId,0) FROM sSecurity.tUser WHERE Id=@rUserId AND OrgId= @rOrgId) 
				AND PC.ScopeSourceId IS NOT NULL 
				AND PM.ScopeSourceTypeId=@rSourceTypeId
				AND SC.StatusId = 1 
				AND SC.IsActiveBatch = 1 
				AND SC.IsBlockAllAlert=0
				AND SC.OrgGroupBatchId=@rOrgGroupBatchId
				AND (SC.DivisionId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2005)
				AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
				AND PhotoCategoryId=@rPhotoCategoryId
		END
		ELSE IF(@lConfigValue='Academic Setup')
		BEGIN			
			SELECT 
				REPLACE (REPLACE (REPLACE (
				REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Division'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
				@rSubject AS [Subject],
				PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.ParentContactNo AS MobileNo,
				PM.ScopeSourceTypeId AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgGroupId,
				SC.OrgId,
				SC.ParentEmail AS EmailId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sSetup.tDivisionMaster OM
				INNER JOIN sSetup.tOrganizationMaster tOM ON tOM.Id = OM.OrgId
				INNER JOIN sAcademic.vTeacherSubjectDivision TSD ON TSD.OrgId=OM.OrgId AND TSD.DivisionId= OM.Id
				LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
				LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2005 
			WHERE
				TSD.EmployeeId= (SELECT ISNULL(SourceId,0) FROM sSecurity.tUser WHERE Id=@rUserId)					 
				AND PC.ScopeSourceId IS NOT NULL  
				AND PM.ScopeSourceTypeId=@rSourceTypeId
				AND SC.StatusId = 1 
				AND SC.IsActiveBatch = 1 
				AND SC.IsBlockAllAlert=0
				AND SC.OrgGroupBatchId=@rOrgGroupBatchId
				AND (SC.DivisionId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2005)
				AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
				AND PhotoCategoryId=@rPhotoCategoryId
		END
		ELSE IF(@lConfigValue='User Access')
		BEGIN
			SELECT
				REPLACE (REPLACE (REPLACE (
				REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Division'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
				@rSubject AS [Subject],
				PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.ParentContactNo AS MobileNo,
				PM.ScopeSourceTypeId AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgGroupId,
				SC.OrgId,
				SC.ParentEmail AS EmailId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM sSetup.tDivisionMaster OM
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = OM.Id AND U.SourceTypeId= 2005
				LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
				LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2005 
			WHERE 
				OM.OrgId=@rOrgId  
				AND U.UserId = (SELECT ISNULL(ID,0) FROM sSecurity.tUser WHERE Id=@rUserId AND OrgId= @rOrgId)
				AND PC.ScopeSourceId IS NOT NULL  
				AND PM.ScopeSourceTypeId=@rSourceTypeId
				AND SC.StatusId = 1 
				AND SC.IsActiveBatch = 1 
				AND SC.IsBlockAllAlert=0
				AND SC.OrgGroupBatchId=@rOrgGroupBatchId
				AND (SC.DivisionId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2005)
				AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
				AND PhotoCategoryId=@rPhotoCategoryId
		END
		ELSE
		BEGIN
			SELECT
				REPLACE (REPLACE (REPLACE (
				REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Division'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
				@rSubject AS [Subject],
				PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.ParentContactNo AS MobileNo,
				PM.ScopeSourceTypeId AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgGroupId,
				SC.OrgId,
				SC.ParentEmail AS EmailId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM  
				sSetup.tDivisionMaster OM
				LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
				LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2005 
			WHERE 
				OM.OrgId=@rOrgId  
				AND PC.ScopeSourceId IS NOT NULL  
				AND PM.ScopeSourceTypeId=@rSourceTypeId
				AND SC.StatusId = 1 
				AND SC.IsActiveBatch = 1 
				AND SC.IsBlockAllAlert=0
				AND SC.OrgGroupBatchId=@rOrgGroupBatchId
				AND (SC.DivisionId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2005)
				AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
				AND PhotoCategoryId=@rPhotoCategoryId
		END
	END
	IF @rSourceTypeId=2014
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Hostel'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PM.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM
			sCommunication.tPhotoCategoryMaster PM
			LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
			LEFT JOIN sHostel.tHostelAdmission HA ON HA.Hosteld = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2014
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = HA.SourceId AND HA.SourceTypeId=2003
			INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId = HA.Hosteld AND UA.SourceTypeId=2014 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
		WHERE
			PM.OrgGroupId=@rOrgGroupId  
			AND PC.ScopeSourceId IS NOT NULL  
			AND PM.ScopeSourceTypeId=@rSourceTypeId
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND PM.Id=@rPhotoCategoryId
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
			AND SC.OrgId = @rOrgId
	END 
	IF @rSourceTypeId=2029
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'House'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PM.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			SC.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM  
			sCommunication.tPhotoCategoryMaster PM
			LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
			LEFT JOIN sStudent.tStudentOther SO ON SO.HouseId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2029
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = SO.StudentId
		WHERE
			SC.OrgId=@rOrgId  
			AND PC.ScopeSourceId IS NOT NULL  
			AND PM.ScopeSourceTypeId=@rSourceTypeId
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND PM.Id=@rPhotoCategoryId
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	END	 	
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Student'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.ParentContactNo AS MobileNo,
			PM.ScopeSourceTypeId AS SourceTypeId,
			SC.StudentId AS SourceId,
			PM.OrgGroupId,
			SC.OrgId,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sCommunication.tPhotoCategoryMaster PM
			LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id = PC.PhotoCategoryId AND PM.ScopeSourceTypeId=@rSourceTypeId
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 2003
		WHERE 
			SC.OrgId=@rOrgId  
			AND PC.ScopeSourceId IS NOT NULL  
			AND PM.ScopeSourceTypeId=@rSourceTypeId
			AND SC.StatusId = 1 
			AND SC.IsActiveBatch = 1 
			AND SC.IsBlockAllAlert=0
			AND SC.OrgGroupBatchId=@rOrgGroupBatchId
			AND PM.Id=@rPhotoCategoryId
			AND (ISNULL(SC.ParentEmail,'') <> '' OR ISNULL(SC.WhatsAppContactNo, '') <> '' OR ISNULL(SC.ParentContactNo, '') <> '')
	END
	IF(@rSourceTypeId=95)
	BEGIN
		SELECT 
			REPLACE (REPLACE (REPLACE (
			REPLACE(@rTemplate,'[Name]', ISNULL(PM.Title,'')),
				'[Remark]',ISNULL(PM.Remark,'')),
				'[SourceType]', 'Employee'),
				'[CreatedDateTime]',ISNULL(PM.CreatedDateTime,'')) AS MsgText,
			@rSubject AS [Subject],
			PM.ScopeSourceTypeId AS ReceiverSourceTypeId,
			vEC.EmployeeId AS ReceiverSourceId,
			vEC.MobileNumber AS MobileNo,
			PM.ScopeSourceTypeId AS SourceTypeId,
			vEC.EmployeeId AS SourceId,
			PM.OrgGroupId,
			vEC.OrgId,
			vEC.CompanyEmail AS EmailId,
			ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM 
			sCommunication.tPhotoCategoryMaster PM
			LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PM.Id = PC.PhotoCategoryId AND PM.ScopeSourceTypeId=@rSourceTypeId
			LEFT JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = PC.ScopeSourceId AND PM.ScopeSourceTypeId = 95
		WHERE 
			ISNULL(vEC.IsOtherUser,0) = 0 
			AND vEC.StatusId=7			
			AND (ISNULL(vEC.CompanyEmail,'') <> '' or WhatsAppContactNo <> '')	
			AND PC.ScopeSourceId IS NOT NULL  
			AND PM.ScopeSourceTypeId=@rSourceTypeId
			AND vEC.OrgId=@rOrgId  
			AND PM.Id=@rPhotoCategoryId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pPresentStudentLastPeriodGet]

	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rIsPresent bit = 1,
	 	 @rMailSubject nvarchar(500)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


	Select
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(replace(											
			replace(replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[PresentDates]',Convert(Varchar,SR.AttendanceDate,105))  AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			SR.AttendanceDate AS AbsentDates,
			ISNULL(AR.Title,'') AS AbsentReason,
			SR.AttendanceDate AS PresentDates,
			SC.WhatsAppContactNo

	From
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id

	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
   ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAlert].[pPublishExamScheduleGet]
	 	 @rExamId int,
		 @rBatchId int,
		 @rSubject nvarchar(100)='',
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select		
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			@rSubject AS [Subject],
			replace (
			replace (
			replace (
			replace(@rTemplate,
			'[StudentName]',SC.Name),
			'[ExamName]',ESGM.Title),
			'[ClassName]',SC.ClassName),
			'[ExamSubjectDetail]', STUFF    
            (    
                (
					Select  ',' + Char(10) + SM.Title +':' + CONVERT(nvarchar,ED.ExamDate) +':'+ CONVERT(nvarchar,ED.ExamTime) +':' + ED.ExamTopic 
					from sSetup.tSubjectMaster SM 
					INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = SM.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
					Where CS.ClassId = CM.Id
					FOR XML PATH('')    
                )    
                    
            ,1,1,''))
			 AS MsgText,
			 -- Add Char(10) in above due to this mantis 0028117
			 SC.ClassName AS Class,
			 SC.AcademicId AS SourceId,
			 2001 AS SourceTypeId,
			 SC.OrgId,
			 SC.OrgGroupId,
			 SC.AcademicId AS ReceiverSourceId,
			 2001 AS ReceiverSourceTypeId,
			 SC.WhatsAppContactNo,
			 ESGM.Title AS ExamName
 FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			--INNER JOIN sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId=SM.Id	
			LEFT JOIN sStudent.vStudentCommunication SC ON SC.ClassId = EM.ClassId  AND EM.BatchId = SC.BatchId AND SC.StatusId = 1
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
   WHERE       
            EM.Id=@rExamId
			AND EM.BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pQueryCategoryCreate]
	 @rOrgGroupId int,
	 @rQueryCategoryId bigint,
	 @rTemplate nvarchar(max) = '',
	 @rSubject nvarchar(100)= ''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

SELECT 
		    replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			OM.OrgGroupId,
			SA.OrgId AS OrgId, 
			2003 AS SourceTypeId,
			SA.StudentId AS SourceId,
			SC.WhatsAppContactNo
	FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sSetup.tOrganizationMaster OM ON QCS.SourceId = OM.Id 
		INNER JOIN sStudent.vStudentAcademic SA ON OM.Id = SA.OrgId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	WHERE 
		  QCS.SourceTypeId = 2021 AND QCS.AssigneeToId = 2 
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId

UNION

SELECT 
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			ISNULL(ECS.CompanyEmail,'') AS EmailId,
			ISNULL(ECS.MobileNumber,'') AS MobileNo,
			QCM.OrgGroupId,
			EC.OrgId AS OrgId, 
			95 AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			ECS.WhatsAppContactNo
	FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sSetup.tOrganizationMaster OM ON QCS.SourceId = OM.Id 
		--INNER JOIN sStudent.vStudentAcademic SA ON OM.Id = SA.OrgId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1
		INNER JOIN sHrm.vEmployeeCommonDetail EC ON  OM.Id = EC.OrgId AND EC.EmployeeStatusId = 7 
		LEFT JOIN sHrm.tEmployeeCommunications ECS ON EC.EmployeeId = ECS.EmployeeId
	WHERE 
		  QCS.SourceTypeId = 2021 AND QCS.AssigneeToId = 3 
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId


UNION

Select 
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			QCM.OrgGroupId,
			SA.OrgId AS OrgId, 
			2003 AS SourceTypeId,
			SA.StudentId AS SourceId,
			SC.WhatsAppContactNo

FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sSetup.tDepartmentMaster DM ON QCS.SourceId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
		INNER JOIN sStudent.vStudentAcademic SA ON DM.Id = SA.DepartmentId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1 
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		WHERE 
		  QCS.SourceTypeId = 2017 AND QCS.AssigneeToId = 2
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId


UNION


Select 
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			ISNULL(ECS.CompanyEmail,'') AS EmailId,
			ISNULL(ECS.MobileNumber,'') AS MobileNo,
			QCM.OrgGroupId,
			EC.OrgId AS OrgId, 
			95 AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			ECS.WhatsAppContactNo

FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sSetup.tDepartmentMaster DM ON QCS.SourceId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id  
		INNER JOIN sHrm.vEmployeeCommonDetail EC ON  QCS.SourceId = EC.DepartmentId AND EC.EmployeeStatusId = 7 AND EC.OrgId = OM.Id
		
		LEFT JOIN sHrm.tEmployeeCommunications ECS ON EC.EmployeeId = ECS.EmployeeId
		WHERE 
		  QCS.SourceTypeId = 2017 AND QCS.AssigneeToId = 3
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId


UNION

Select 
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			OM.OrgGroupId,
			SA.OrgId AS OrgId, 
			2003 AS SourceTypeId,
			SA.StudentId AS SourceId,
			SC.WhatsAppContactNo
FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN  sSetup.tClassMaster CM ON QCS.SourceId=CM.Id
		INNER JOIN sStudent.vStudentAcademic SA ON CM.Id = SA.ClassId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		WHERE 
		  QCS.SourceTypeId = 2016
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId


UNION

Select 
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			OM.OrgGroupId,
			SA.OrgId AS OrgId, 
			2003 AS SourceTypeId,
			SA.StudentId AS SourceId,
			SC.WhatsAppContactNo
FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN   sSetup.tDivisionMaster DM ON QCS.SourceId=DM.Id
		INNER JOIN 	sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
		INNER JOIN sStudent.vStudentAcademic SA ON DM.Id = SA.DivisionId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		WHERE 
		  QCS.SourceTypeId = 2005
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId


UNION

Select
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			OM.OrgGroupId,
			SA.OrgId AS OrgId, 
			2003 AS SourceTypeId,
			SA.StudentId AS SourceId,
			SC.WhatsAppContactNo


FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sStudent.vStudentAcademic SA ON QCS.SourceId=SA.StudentId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId=OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		WHERE 
		  QCS.SourceTypeId = 2003
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId

UNION

Select
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			ISNULL(ECS.CompanyEmail,'') AS EmailId,
			ISNULL(ECS.MobileNumber,'') AS MobileNo,
			OM.OrgGroupId,
			EC.OrgId AS OrgId, 
			95 AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			ECS.WhatsAppContactNo
FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sHrm.vEmployeeCommonDetail EC ON  QCS.SourceId = EC.EmployeeId AND EC.EmployeeStatusId = 7 
		INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId=OM.Id 
		LEFT JOIN sHrm.tEmployeeCommunications ECS ON EC.EmployeeId = ECS.EmployeeId

		WHERE 
		  QCS.SourceTypeId = 95
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId
END

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

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

		END
	END
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pQueryStatusGet]
	 	 
		 @rOrgId int,
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rFromSourceTypeId=2003)
		BEGIN
	
		 SELECT 
			QM.Id AS QueryId,
		    ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (	
				replace (
				    replace (
				         replace(
						  replace(
									@rTemplate,'[Number]',QM.Number),
									'[Query Category]',QCM.Title),
								    '[Title]',QM.Title),
								    '[Name]',SC.Name) ,
								    '[Status]',(CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' ELSE '' END))
								 
				            AS MsgText,
		     
		       @rSubject AS Subject,
			   2003 AS ReceiverSourceTypeId,
			   SC.StudentId AS ReceiverSourceId,
			   QM.OrgGroupId,
			   @rOrgId AS OrgId, 
			   2003 AS SourceTypeId,
			   SC.StudentId AS SourceId,
			   ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
			INNER JOIN sStudent.vStudentCommunication SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId

	      WHERE
		    QM.Id = @rQueryId AND BM.IsActive=1 
		
		END
   
   IF(@rFromSourceTypeId=95)
		BEGIN
			SELECT 
			QM.Id AS QueryId,
		    ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		    ISNULL(EM.MobileNumber,'') AS MobileNo,
		   replace (	
				replace (
				    replace (
				         replace(
						  replace(
									@rTemplate,'[Number]',QM.Number),
									'[Query Category]',QCM.Title),
								    '[Title]',QM.Title),
								    '[Name]',EM.EmployeeName) ,
								    '[Status]',(CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' ELSE '' END))
								 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId,
			 @rOrgId AS OrgId, 
			 95 AS SourceTypeId,
			 EM.EmployeeId AS SourceId,
			 ISNULL(EM.WhatsAppContactNo,'') AS WhatsAppContactNo 
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
		
	      WHERE
		    QM.Id = @rQueryId 

		END
	--END
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pReceiptChequeClearGet]
	 	 
	 	 @rReceiptId bigint,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rAdmissionCategoryId int=0,
	 	 @rIdNos nvarchar(500)='',
	 	 @rIsObsolete bit=0,
		 @rCollectionGroupId int 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SELECT 
				SC.AcademicId,
				SC.Code,
				SC.Name,
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
				ISNULL(SC.StudentEmail,'') AS StudentEmail,
				ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
				ISNULL(SC.FatherMail,'') AS FatherMail,
				ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
				ISNULL(SC.MotherMail,'') AS MotherMail,
				@rSubject AS Subject,
				replace (
				replace (
				replace (
				replace (
				replace (
				replace (
				replace (
				replace (
				replace (
				replace(@rTemplate,'[Name]',SC.Name),
				'[Class]',SC.ClassName),
				'[Division]',SC.DivisionName),
				'[ReceiptBook]',RB.Title),
				'[ReceiptNumber]',R.ReceiptNumber),
				'[ReceiptDate]',convert(varchar,R.ReceiptDate,103)),
				'[PaidAmount]',convert(int,R.ReceiptAmount)),
				'[BankName]',R.BankName),
				'[ChequeClearDate]',R.ChequeClearDate),
				'[ChequeNumber]' , R.ChequeNo)
				 AS MsgText,
				 SC.OrgId,
				 SC.OrgGroupId,
				 SC.AcademicId AS SourceId,
				 2001 AS SourceTypeId,
				 2001 AS ReceiverSourceTypeId,
				 SC.AcademicId AS ReceiverSourceId,
				 SC.ClassName AS Class,
				 SC.DivisionName AS Division,
				 RB.Title AS ReceiptBook,
				 R.ReceiptNumber AS ReceiptNumber,
				 convert(varchar,R.ReceiptDate,103) AS ReceiptDate,
				 convert(int,R.ReceiptAmount) AS PaidAmount,
				 R.BankName AS BankName,
				 R.ChequeClearDate AS ChequeClearDate,
				 R.ChequeNo AS ChequeNumber,
				 SC.WhatsAppContactNo
		FROM 
			sStudent.vStudentCommunication SC
		INNER JOIN sFee.tReceipt R ON R.SourceId=SC.AcademicId AND R.SourceTypeId=2001 AND R.IsObsolete=@rIsObsolete
				AND ((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND ((R.ChequeClearDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((R.ChequeClearDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND ((R.Id=@rReceiptId) OR (@rReceiptId=0))
				AND ((R.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
		INNER JOIN sFee.tReceiptBookMaster RB ON RB.Id = R.ReceiptBookId
			
		WHERE
				((SC.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (SC.StatusId=1)
			AND (SC.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
			AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			AND SC.IsBlockAllAlert=0
			ORDER BY R.ReceiptNumber	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pRecipientTypeMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			TitleResourceKeyId,
			Remark
	   FROM sAlert.tRecipientTypeMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAlert].[pRecruitmentStatusGet]
	
	@rCandidateId bigint,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
SELECT 
		
CM.CandidateNumber AS CandidateNumber,
CM.FirstName+' '+CM.MiddleName+' '+CM.LastName AS Name,
CM.MobileNo AS MobileNo,	
CM.PersonalEmail AS EmailId,
REPLACE (
REPLACE (
REPLACE (
REPLACE (
REPLACE(@rTemplate,
		'[Name]',CM.FirstName+' '+CM.MiddleName+' '+CM.LastName),
		'[ContactNumber]',ISNULL(CM.MobileNo,'')),
		'[EmailId]',ISNULL(CM.PersonalEmail,'')),
		'[CurrentStatus]',ISNULL(RSM.Title,'')),
		'[Address]',ISNULL(CC.PresentStreetOne,'')+' '+ISNULL(CC.PresentStreetTwo,'')+' '+ISNULL(CC.PresentStreetThree,'')+' '+ISNULL(CC.PresentCountry,'')+' '+ISNULL(CC.PresentState,'')+' '+ISNULL(CC.PresentCity,''))		
		AS MsgText,
		
@rSubject AS [Subject],
0 As ReceiverSourceId,
0 As ReceiverSourceTypeId,
ISNULL(CM.CandidateNumber,'') AS CandidateNo,
ISNULL(CM.ApplicationNumber,0) AS ApplicationNo,
CM.MobileNo AS WhatsAppContactNo

FROM sRecruitment.tCandidateMaster CM
INNER JOIN sRecruitment.tRecruitmentStatusLog  RSL ON CM.Id = RSL.CandidateId AND CM.OrgGroupID = RSL.OrgGroupId
LEFT JOIN sRecruitment.tRecruitmentStatusMaster RSM on RSM.Id=RSL.RecruitmentStatusId	
LEFT JOIN sRecruitment.tCandidateCommunications	 CC ON 	CC.CandidateId=CM.Id
WHERE	
		
	CM.Id = @rCandidateId
	AND CM.OrgGroupId = @rOrgGroupId
	AND RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId) -- in alert RecruitmentStatus send wrong due to multiple rows mantisid -- 0032651
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pResultGet]
	 	 
 	 @rBatchId int,
 	 @rClassId int,
 	 @rDivisionId int,
 	 @rOrgId int,
 	 @rTemplate nvarchar(max),
 	 @rExamId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[Percentile]',R.Percentile),
			'[ExamRemark3]',ISNULL(E.Remark3,''))	-- MantisId : 0034978
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 ES.Title AS ExamName,
			 CONVERT(int,TotalMarks) AS TotalMarks,
			 CONVERT(int,TotalObtain) AS ObtainMarks,
			 R.ResultStatus AS ResultStatus,
			 R.ResultGrade AS ResultGrade,
			 R.ResultGradePoint AS ResultGradePoint,
			 R.RankNumber AS RankNumber,
			 R.Percentage AS Percentage,
			 R.Percentile AS Percentile,
			 SC.WhatsAppContactNo
	FROM 
			sStudent.vStudentCommunication SC
			INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
			INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (SC.OrgId=@rOrgId)
			AND (SC.BatchId=@rBatchId)
			AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	ORDER BY 
			SC.DivisionOrderIndex,SC.Rollno
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAlert].[pResultWithDetailsGet]
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rExamId int,
	 	 @rSubjectId int=0,
		 @rIsSubjectInNewLine bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Declare @lSubjectCode nvarchar(20)
	IF(@rSubjectId > 0)
		BEGIN
		Select @lSubjectCode = Code from sSetup.tSubjectMaster Where Id = @rSubjectId
		END
	ELSE
		BEGIN
		SET @lSubjectCode = 'All'
		END

	IF(@rIsSubjectInNewLine = 0)
	BEGIN
		Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[SubjectMark]', CHAR(13) + ISNULL([sAlert].[fResultGet](R.Id,@rSubjectId,1),'')),
			'[SubjectMarkWithMax]',ISNULL([sAlert].[fResultWithMaxGet](R.Id,@rSubjectId),'')),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[SubjectGrade]',ISNULL([sAlert].[fResultGet](R.Id,@rSubjectId,2),'')),
			'[Percentile]',R.Percentile),
			'[Subject]',ISNULL(@lSubjectCode,''))			-- MantisId : 0035349
			
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 ES.Title AS ExamName,
			 CONVERT(int,TotalMarks) AS TotalMarks,
			 CONVERT(int,TotalObtain) AS ObtainMarks,
			 R.ResultStatus AS ResultStatus,
			 R.ResultGrade AS ResultGrade,
			 R.ResultGradePoint AS ResultGradePoint,
			 R.RankNumber AS RankNumber,
			 R.Percentage AS Percentage,
			 R.Percentile AS Percentile,
			 [sAlert].[fResultGet](R.Id,@rSubjectId,2) AS SubjectGrade,
			 [sAlert].[fResultWithMaxGet](R.Id,@rSubjectId) AS SubjectMarkWithMax,
			 SC.WhatsAppContactNo
		
	From 
	sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	 
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))	 
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
	END
	ELSE
	BEGIN
		Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[SubjectMark]',ISNULL([sAlert].[fResultGetWithLineBreak](R.Id,@rSubjectId,1),'')),
			'[SubjectMarkWithMax]',ISNULL([sAlert].[fResultWithMaxGetWithLineBreak](R.Id,@rSubjectId),'')),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[SubjectGrade]',ISNULL([sAlert].[fResultGetWithLineBreak](R.Id,@rSubjectId,2),'')),
			'[Percentile]',R.Percentile),
			'[Subject]',ISNULL(@lSubjectCode,''))			-- MantisId : 0035349
			
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 ES.Title AS ExamName,
			 CONVERT(int,TotalMarks) AS TotalMarks,
			 CONVERT(int,TotalObtain) AS ObtainMarks,
			 R.ResultStatus AS ResultStatus,
			 R.ResultGrade AS ResultGrade,
			 R.ResultGradePoint AS ResultGradePoint,
			 R.RankNumber AS RankNumber,
			 R.Percentage AS Percentage,
			 R.Percentile AS Percentile,
			 [sAlert].[fResultGet](R.Id,@rSubjectId,2) AS SubjectGrade,
			 [sAlert].[fResultWithMaxGet](R.Id,@rSubjectId) AS SubjectMarkWithMax,
			 SC.WhatsAppContactNo
		
	From 
	sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	 
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))	 
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAlert].[pResultWithSubjectGet]
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rExamId int,
	 	 @rSubjectId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Declare @lSubjectCode nvarchar(20)
	IF(@rSubjectId > 0)
		BEGIN
		Select @lSubjectCode = Code from sSetup.tSubjectMaster Where Id = @rSubjectId
		END
	ELSE
		BEGIN
		SET @lSubjectCode = 'All'
		END

	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[SubjectMark]', CHAR(13) + ISNULL([sAlert].[fResultGet](R.Id,@rSubjectId,1),'')),
			'[SubjectMarkWithMax]', ISNULL([sAlert].[fResultWithMaxGet](R.Id,@rSubjectId),'')),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[SubjectGrade]', ISNULL([sAlert].[fResultGet](R.Id,@rSubjectId,2),'')),
			'[Percentile]',R.Percentile),
			'[ExamTopic]',ISNULL(sAlert.fExamDetailGet(@rExamId,@rSubjectId,1),'')),
			'[ExamTime]',ISNULL(sAlert.fExamDetailGet(@rExamId,@rSubjectId,2),'')),
			'[ExamDate]',ISNULL(sAlert.fExamDetailGet(@rExamId,@rSubjectId,3),'')),
			'[HighestMark]',ISNULL([sAlert].[fHighestMarkGet](E.Id, @rSubjectId, @rDivisionId, @rClassId, @rBatchId),'')), --Added for Mantis : 35024 by Nilesh
			'[Subject]',ISNULL(@lSubjectCode,''))		-- MantisId : 0035349
			
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 ES.Title AS ExamName,
			 CONVERT(int,TotalMarks) AS TotalMarks,
			 CONVERT(int,TotalObtain) AS ObtainMarks,
			 R.ResultStatus AS ResultStatus,
			 R.ResultGrade AS ResultGrade,
			 R.ResultGradePoint AS ResultGradePoint,
			 R.RankNumber AS RankNumber,
			 R.Percentage AS Percentage,
			 R.Percentile AS Percentile,
			 [sAlert].[fResultGet](R.Id,@rSubjectId,2) AS SubjectGrade,
			 [sAlert].[fResultWithMaxGet](R.Id,@rSubjectId) AS SubjectMarkWithMax,
			 SC.WhatsAppContactNo
		
	From 
	sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	 
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))	 
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pSMSConfigurationAdd]
	
	@rOrgId smallint,
	@rSMSURL nvarchar(1000),
	@rSMSCreditURL nvarchar(1000),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(50),
	@rLoginSenderId nvarchar(50),
	@rSMSXMLURL nvarchar(1000),
	@rVendorId smallint,
	@rOrgGroupId smallint,
	@rIsAllOrg bit,
	@rSMSUnicodeURL nvarchar(1000)='',
	@rVoiceSMSURL nvarchar(1000),
	@rVoiceSMSLoginId nvarchar(50),
	@rVoiceSMSLoginPassword nvarchar(50),
	@rPEID nvarchar(50)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 IF(@rIsAllOrg=1)
	 BEGIN
		DECLARE @lCount INT
		CREATE TABLE #tTable  
		(
			Id bigint identity,
			OrgId smallint
		)
		INSERT INTO #tTable
		(
			OrgId
		)
		SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId
		
		SELECT @lCount =  COUNT(Id) FROM #tTable
		WHILE @lCount > 0 
		BEGIN
			SELECT @rOrgId=OrgId FROM #tTable WHERE Id = @lCount
			IF NOT EXISTS(SELECT OrgId FROM sAlert.tSMSConfiguration WHERE OrgId=@rOrgId)
BEGIN

	INSERT INTO sAlert.tSMSConfiguration
		(
			OrgId,
			SMSURL,
			SMSCreditURL,
			LoginId,
			LoginPassword,
			LoginSenderId,
			SMSXMLURL,
			VendorId,
			SMSUnicodeURL,
			VoiceSMSURL,
			VoiceLoginId,
			VoiceLoginPassword,
			PEID
		)
	VALUES
		(
			@rOrgId,
			@rSMSURL,
			@rSMSCreditURL,
			@rLoginId,
			@rLoginPassword,
			@rLoginSenderId,
			@rSMSXMLURL,
			@rVendorId,
			@rSMSUnicodeURL,
			@rVoiceSMSURL,
	@rVoiceSMSLoginId,
	@rVoiceSMSLoginPassword,
	@rPEID
		)
		             
	END	 
	 ELSE
	 BEGIN
	    UPDATE  sAlert.tSMSConfiguration
	    SET
			SMSURL=@rSMSURL,
			SMSCreditURL=@rSMSCreditURL,
			LoginId=@rLoginId,
			LoginPassword=@rLoginPassword,
			LoginSenderId=@rLoginSenderId,
			SMSXMLURL=@rSMSXMLURL,
			VendorId=@rVendorId,
			SMSUnicodeURL=@rSMSUnicodeURL,
			VoiceSMSURL=@rVoiceSMSURL,
			VoiceLoginId=@rVoiceSMSLoginId,
			VoiceLoginPassword=@rVoiceSMSLoginPassword,
			PEID=@rPEID
	      
	      WHERE OrgId = @rOrgId 	   
	 END  
		SELECT @rOrgId AS Result
			SET @lCount = @lCount - 1
		END
	 END
	 ELSE
	 BEGIN
	 
 IF NOT EXISTS(SELECT OrgId FROM sAlert.tSMSConfiguration WHERE OrgId=@rOrgId)
BEGIN

	INSERT INTO sAlert.tSMSConfiguration
		(
			OrgId,
			SMSURL,
			SMSCreditURL,
			LoginId,
			LoginPassword,
			LoginSenderId,
			SMSXMLURL,
			VendorId,
			SMSUnicodeURL,
			PEID
		)
	VALUES
		(
			@rOrgId,
			@rSMSURL,
			@rSMSCreditURL,
			@rLoginId,
			@rLoginPassword,
			@rLoginSenderId,
			@rSMSXMLURL,
			@rVendorId,
			@rSMSUnicodeURL,
			@rPEID
		)
		             
	END	 
	 ELSE
	 BEGIN
	    UPDATE  sAlert.tSMSConfiguration
	    SET
			SMSURL=@rSMSURL,
			SMSCreditURL=@rSMSCreditURL,
			LoginId=@rLoginId,
			LoginPassword=@rLoginPassword,
			LoginSenderId=@rLoginSenderId,
			SMSXMLURL=@rSMSXMLURL,
			VendorId=@rVendorId,
			SMSUnicodeURL=@rSMSUnicodeURL,
			PEID=@rPEID
	      
	      
	      WHERE OrgId = @rOrgId 	   
	 END  
		SELECT @rOrgId AS Result
	END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pSMSConfigurationGet]
	 
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT
			SC.SMSURL,
			SC.SMSCreditURL,
			SC.LoginId,
			SC.LoginPassword,
			SC.LoginSenderId,
			SC.SMSXMLURL,
			SC.VendorId,
			ISNULL(SC.SMSUnicodeURL,'') AS SMSUnicodeURL,
			ISNULL(SC.VoiceSMSURL,'') as VoiceSMSURL, 
			ISNULL(SC.VoiceLoginId,'') AS VoiceLoginId,
			ISNULL(SC.VoiceLoginPassword,'') AS VoiceLoginPassword,
			SC.PEID
	FROM
			sAlert.tSMSConfiguration SC
	WHERE 
			SC.OrgId=@rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pSMSDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 
	 @rOrgGroupId int,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
  SELECT
	(
		SELECT 
			COUNT(AL.Id) FROM sAlert.tAlertLog AL
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime)=CONVERT(DATE,GETDATE())
    ) AS DailyCount,
    (
		SELECT 
			COUNT(AL.Id) FROM sAlert.tAlertLog AL
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))
    ) AS YesterdayCount,
    
	(
		SELECT 
			COUNT(AL.Id) FROM sAlert.tAlertLog AL
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
	) AS WeeklyCount,
	(
		SELECT 
			COUNT(AL.Id) FROM sAlert.tAlertLog AL
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
	)  AS MonthlyCount
  END
  
  IF(@rType='Event')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT 
			EM.Title AS EventName,COUNT(AL.Id) AS YesterdayCount FROM sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON AL.EventId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))
		GROUP BY EM.Title 
	END
	IF(@rDay=1)
	BEGIN
		SELECT 
			EM.Title AS EventName,COUNT(AL.Id) AS DailyCount FROM sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON AL.EventId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime)=CONVERT(DATE,GETDATE())
		GROUP BY EM.Title 
	END
	IF(@rDay=7)
	BEGIN
		SELECT 
			EM.Title AS EventName,COUNT(AL.Id) AS WeeklyCount FROM sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON AL.EventId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		GROUP BY EM.Title 
	END
	IF(@rDay=30)
	BEGIN
		SELECT 
			EM.Title AS EventName,COUNT(AL.Id) AS MonthlyCount FROM sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON AL.EventId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		GROUP BY EM.Title 
	END
  END
  
  IF(@rType='OrgGroup')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization,COUNT(AL.Id) AS YesterdayCount FROM sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON AL.EventId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			--AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))
		GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=1)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization,COUNT(AL.Id) AS DailyCount FROM sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON AL.EventId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			--AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime)=CONVERT(DATE,GETDATE())
		GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=7)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization,COUNT(AL.Id) AS WeeklyCount FROM sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON AL.EventId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
			--AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
		GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=30)
	BEGIN
		SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization,COUNT(AL.Id) AS MonthlyCount FROM sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON AL.EventId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId 
		WHERE 
			AL.AlertModeId=2
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)
		--	AND (AL.OrgId = @rOrgId OR @rOrgId=0)
			AND CONVERT(DATE,AL.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		GROUP BY OM.Id,OM.DisplayTitle
	END
  END
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pSMSHistoryGet]
	
	@rOrgId smallint,
	@rStatusId int,
	@rContactId nvarchar(50),
	@rEventId int,
	@rSourceEvent nvarchar(50),
	@rUserName nvarchar(100),
	@rAlertModeId tinyint,
	@rFromDate date,
	@rToDate date,
	@rOrgGroupId int,
	@rCode nvarchar(max),
	@rReceiverSourceTypeId int,
	@rIsHistory bit = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rIsHistory = 1)
	BEGIN
		IF(@rCode IS NULL OR @rCode='')
		BEGIN
			IF(@rReceiverSourceTypeId=0)
				BEGIN	
		
				SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
				FROM
				sAlert.tAlertLogHistory AL
				INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
				LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
				WHERE
					((AL.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
					AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
					AND ((AL.EventId=@rEventId) OR (@rEventId=0))
					AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
					AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
					AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
					AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
					AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
					AND OM.OrgGroupId = @rOrgGroupId	
					AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)					
					ORDER BY AL.CreatedDateTime DESC
				END	
	
			ELSE IF(@rReceiverSourceTypeId=2003)
				BEGIN	
				SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
				FROM
					sAlert.tAlertLogHistory AL
					INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
					LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
					INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			
				WHERE
					((AL.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
					AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
					AND ((AL.EventId=@rEventId) OR (@rEventId=0))
					AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
					AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
					AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
					AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
					AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
					AND OM.OrgGroupId = @rOrgGroupId	
					AND ((AL.ReceiverSourceTypeId=@rReceiverSourceTypeId) OR AL.ReceiverSourceTypeId = 2001) -- Add Condition for Mantis Id:0031787
					ORDER BY AL.CreatedDateTime DESC
				END
			ELSE IF(@rReceiverSourceTypeId=95)
			BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 					
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
	END
			ELSE 
			BEGIN
		SELECT DISTINCT tmp1.* From(
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=2003			
			AND OM.OrgGroupId = @rOrgGroupId	
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLogHistory AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR  (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND AL.ReceiverSourceTypeId=2001
		AND OM.OrgGroupId = @rOrgGroupId		
	
	UNION
	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=95			
			AND OM.OrgGroupId = @rOrgGroupId	
		
		UNION
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			
			--AND (AL.ReceiverSourceTypeId NOT IN (95,2001,2003))
			
			AND ((AL.ReceiverSourceTypeId=0 OR @rReceiverSourceTypeId=0))	
			--ORDER BY AL.CreatedDateTime DESC	
	
	)AS tmp1				
			ORDER BY tmp1.CreatedDateTime DESC
	END
		END

	ELSE
	BEGIN
		SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			tEM.Code AS Code
		FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
		
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SA.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')
END		
		
--SELECT DISTINCT OM.Title, D.Code,OM.OrderIndex,D.OrderIndex FROM sSetup.tDivisionMaster D
--INNER JOIN ssetup.tOrganizationMaster OM
--ON D.OrgId = OM.Id
--WHERE D.Id IN
--(
--select DivisionId from sStudent.tAcademic A INNER JOIN
--sStudent.tStudentCommunication SC ON A.StudentId = SC.StudentId
--INNER JOIN SAlert.tAlertLog AL ON SC.ParentContactNo = AL.ContactId
--AND AL.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = 1141 )
--AND AL.AlertModeId = 2)
--order by  OM.OrderIndex,D.OrderIndex
	END
ELSE 
BEGIN
	IF(@rCode IS NULL OR @rCode='')
	BEGIN
		IF(@rReceiverSourceTypeId=0)
		BEGIN	
		
		SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			'' AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId) 
			
			ORDER BY AL.CreatedDateTime DESC
	END	
	
		ELSE IF(@rReceiverSourceTypeId=2003)
		BEGIN	
		SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SA.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND ((AL.ReceiverSourceTypeId=@rReceiverSourceTypeId) OR AL.ReceiverSourceTypeId=2001) -- Add Condition for Mantis Id:0031787
			ORDER BY AL.CreatedDateTime DESC
	END
		ELSE IF(@rReceiverSourceTypeId=95)
		BEGIN	
		SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 					
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
		END
	ELSE 
	BEGIN
		SELECT DISTINCT tmp1.* From(		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=2003			
			AND OM.OrgGroupId = @rOrgGroupId	
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR  (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND AL.ReceiverSourceTypeId=2001
		AND OM.OrgGroupId = @rOrgGroupId		
	
	UNION
	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=95			
			AND OM.OrgGroupId = @rOrgGroupId	
		
		UNION
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			
			AND (AL.ReceiverSourceTypeId NOT IN (95,2001,2003))
			
			--AND ((AL.ReceiverSourceTypeId=0 OR @rReceiverSourceTypeId=0))	
			--ORDER BY AL.CreatedDateTime DESC	
	
	)AS tmp1				
			ORDER BY tmp1.CreatedDateTime DESC
	END
		END

	ELSE
	BEGIN
	SELECT 
		AL.Id AS Id,
		AL.ContactId,
		AL.AlertMessage,
		AL.AlertSubject,
		CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
		--AL.ResultMessage
		CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
		--EM.Title AS EventName,
		AL.SourceEvent,
		U.DisplayTitle AS UserName,
		AL.CreatedDateTime,
		OM.Id AS OrgId,
		OM.DisplayTitle AS Organization,
		tEM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
		
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SA.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')
END		
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pSMSLogGet]
	
	@rCreatedUserId bigint,
	@rFromId bigint,
	@rToId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			AL.Id AS MsgID,
			AL.ContactId AS MobileNo,
			AL.AlertMessage AS MsgText
			--replace (
			--replace (
			--replace(AL.AlertMessage,'<','&lt;'),
			--'>','&gt;'),
			--'&','%26amp;') AS MsgText
	FROM
			sAlert.tAlertLog AL
	WHERE
			(AL.StatusId=0)
		--AND (AL.CreatedUserId=@rCreatedUserId)
		AND (AL.Id>=@rFromId)
		AND (AL.Id<=@rToId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pSMSLogModify]
	
	@rXML nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
--BEGIN TRY
	
--	BEGIN TRANSACTION
	 
	SET @rXML=REPLACE(@rXML,'&','AND')
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML
	
	UPDATE sAlert.tAlertLog
		SET 
			StatusId = ISNULL(SSM.Id,0),
			ResultMessage = ISNULL(SSM.Title,XmlTable.Code)
		FROM OPENXML (@intDoc, '/Table/SMSLog', 2)
				 WITH ( 
						Id bigint,
						Code nvarchar(20),
						VendorId smallint
					  ) XmlTable
			INNER JOIN sAlert.tAlertLog AL ON AL.Id=XmlTable.Id
			LEFT JOIN sAlert.tSMSStatusMaster SSM ON SSM.Code=XmlTable.Code
	

	EXEC sp_xml_removedocument @intDoc
	
		SELECT 1 AS Result
	
	--	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pSMSViewGet]
	@rMobileNumber nvarchar(50),
	@rEmail nvarchar(50),
	@rOrgId int,
	@rIsFlag bit = 0,
	@rAlertModeId tinyint = 0,
	@rReceiverSourceId bigint = 0 --Mantis: 0044870
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
declare  @lAlertgrid NVARCHAR(max)=''
BEGIN

IF(@rIsFlag = 0)
BEGIN
	select AL.SourceEvent,EM.Title,AL.AlertSubject,[sCommon].[fXMLTagsReplace](AL.AlertMessage) as AlertMessage,AL.CreatedDateTime
	Into #tempAlertLogStudent360
	FROM
			sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
	WHERE  ((AL.ContactId = @rMobileNumber) OR (AL.ContactId = @rEmail))
		And AL.OrgId=@rOrgId	
		AND (AL.AlertModeId = @rAlertModeId OR @rAlertModeId = 0)
		AND AL.ReceiverSourceId = @rReceiverSourceId
	ORDER BY AL.CreatedDateTime DESC	
	SELECT  @lAlertgrid = @lAlertgrid + '<tr>
	<td align="left" scope="col">' + isnull(SourceEvent,'') + '</td>
	<td align="left" scope="col">' + isnull(Title,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertSubject,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertMessage,'') + '</td>
	<td align="left" scope="col">' + Convert(varchar,isnull(CreatedDateTime,''),120) + '</td>
	</tr>'	
	FROM #tempAlertLogStudent360

	DROP TABLE #tempAlertLogStudent360
END
ELSE
BEGIN
	select AL.SourceEvent,EM.Title,AL.AlertSubject,[sCommon].[fXMLTagsReplace](AL.AlertMessage) as AlertMessage,AL.CreatedDateTime
	Into #tempAlertLogStudentDetailForm
	FROM
			sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
	WHERE  ((AL.ContactId = @rMobileNumber) OR (AL.ContactId = @rEmail))
		And AL.OrgId=@rOrgId	
		AND CAST(CreatedDateTime AS DATE) = CAST(sCommon.fGetDate() AS DATE)
		AND (AL.AlertModeId = @rAlertModeId OR @rAlertModeId = 0)
		AND AL.ReceiverSourceId = @rReceiverSourceId
	ORDER BY AL.CreatedDateTime DESC

	SELECT  @lAlertgrid = @lAlertgrid + '<tr>
	<td align="left" scope="col">' + isnull(SourceEvent,'') + '</td>
	<td align="left" scope="col">' + isnull(Title,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertSubject,'') + '</td>
	<td align="left" scope="col">' +  isnull(AlertMessage,'') + '</td>
	<td align="left" scope="col">' + Convert(varchar,isnull(CreatedDateTime,''),120) + '</td>
	</tr>'	
	FROM #tempAlertLogStudentDetailForm

	DROP TABLE #tempAlertLogStudentDetailForm
END
    	
END
 SELECT ISNULL(@lAlertgrid,'') AS Alertgrid

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

			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(
			replace (
			replace (
			replace(@rTemplate,'[IssueNo]',@rStockIssueId),			
			'[IssueDate]',@rIssueDate),
			'[IssueItem]',@rIssueItem),
			'[Name]',SC.Name)
			 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAlert].[pStudentAdmissionGet]
	 	 
		 @rStudentId bigint,	 	 
	 	 @rBatchId int,	 	 	 	
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,			
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[Code]',SC.Code),			
			'[AdmissionDate]',replace(ISNULL(SA.AdmissionDate,''),'1900-01-01','')),
			'[AdmissionClass]',SC.ClassName)
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SA.AdmissionDate AS AdmissionDate,
			SC.ClassName AS AdmissionClass,
			SC.WhatsAppContactNo
		
		
	From 
		sStudent.vStudentCommunication SC	
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SC.StudentId
	WHERE
	(SC.StudentId= @rStudentId)
	AND (SC.OrgId=@rOrgId)
	AND (SC.BatchId=@rBatchId)
	AND (SC.StatusId=1) AND (SC.IsBlockAllAlert=0)	
END

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			
			--For Optimization
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2001),0)		--Mantis: 34829, change 2003 => 2001 by dhruvik

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

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

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

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						CreatedDateTime [datetime] NOT NULL,--For Optimization
						AutoId bigint not null--For Optimization
					)

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

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

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

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

	

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

			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2001 AND CAST(CreatedDateTime as date)=CAST(@lDateTimeNow as date)),0)	 --Mantis: 34829, change 2003 => 2001 by dhruvik
			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
		
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				AutoId bigint not null,

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

			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS SMSText,
				 replace (
				replace (
				replace (
				replace(@lMailTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MailText,
				  replace (
				replace (
				replace (
				replace(@lNotificationTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS NotificationText,
				 replace (
				replace (
				replace (
				replace(@lWhatsappTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS WhatsappText,
				Subject AS Subject,
				2001 AS ReceiverSourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2001 AS SourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
				SourceId AS SourceId,
				OrgId,
				OrgGroupId,
				Time,
				OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			WHERE
			   AlertUniqueId=@AlertUniqueId


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

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=130 and SourceTypeId=2001),0)	   --Mantis: 34829, change 2003 => 2001 by dhruvik
			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 1),'')
			

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				OutTimeAlertTime time NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				LastOutAlertBasedOnId int NOT NULL,
				ShiftCode int NOT NULL,
				AutoId bigint not null,
			)
			
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,SMC.OutTimeAlertTime,Max(CreatedDateTime),SMC.LastOutAlertBasedOnId,CDT.ShiftCode,max(CDT.Autoid)
				from [sBiometric].[tCloudTransactionData] CDT with (nolock)  
				--inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				 INNER JOIN sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=CDT.ShiftCode
				where  Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())
					AND	((SMC.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
					AND SMC.IsOutTimeAlertTime=1
					AND CDT.SourceTypeId=2001		--Mantis: 34829, change 2003 => 2001 by dhruvik
					AND (
							(
								(LastOutAlertBasedOnId=1 OR (LastOutAlertBasedOnId=2  and CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time)<=cast(CDT.In_Out_Time as Time)
								AND CAST(OutTimeAlertTime AS Time) > CAST(CDT.In_Out_Time AS Time)))
								 AND CAST(OutTimeAlertTime AS Time)<cast(@rToDateTime as Time) 
								AND CAST(OutTimeAlertTime AS Time) > CAST(@rFromDateTime AS Time) 
							)
							OR
							(
							LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time)<=cast(CDT.In_Out_Time as Time)
							AND CAST(OutTimeAlertTime AS Time) > CAST(CDT.In_Out_Time AS Time)
							--AND CDT.Autoid>@lCloudTransactionDataId 
							AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=130 and SourceTypeId=2001 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))		--Mantis: 34829, change 2003 => 2001 by dhruvik
							)
						)
				Group by SourceId,SourceTypeId,SMC.OutTimeAlertTime,SMC.LastOutAlertBasedOnId,CDT.ShiftCode
				--select * from #tTable

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



			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS SMSText,
				 replace (
				replace (
				replace (
				replace(@lMailTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MailText,
				  replace (
				replace (
				replace (
				replace(@lNotificationTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS NotificationText,
				 replace (
				replace (
				replace (
				replace(@lWhatsappTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS WhatsappText,
				Subject AS Subject,
				2001 AS ReceiverSourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2001 AS SourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
				SourceId AS SourceId,
				OrgId,
				OrgGroupId,
				 Time,
				 OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			WHERE
			   AlertUniqueId=@AlertUniqueId

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pStudentBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		@rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)='',
		@rEventId int=137,
		@rShiftCode int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay as nvarchar(3)
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 399 AND SourceId = @rOrgId

	declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
	set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
	set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
	set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
	set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
	set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
	--IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	--BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query ='SELECT
					SC.ParentContactNo AS MobileNo,	
					SC.ParentEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lSMSTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS SMSText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lMailTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MailText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lNotificationTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS NotificationText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lWhatsappTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS WhatsappText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					2001 AS ReceiverSourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
					AC.Id AS ReceiverSourceId,		--Mantis: 34829, change SC.StudentId => AC.Id by dhruvik
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS StudentName,
					ISNULL(SC.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					2001 AS SourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
					AC.Id AS SourceId,		--Mantis: 34829, change SC.StudentId => AC.Id by dhruvik
					SM.OrgId,
					OM.OrgGroupId,
					SM.Id AS StudentId,
					SM.Code,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS  StudentName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle	
		FROM 
				sStudent.tStudentMaster SM
				Inner join sStudent.tStudentCommunication SC ON SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgID = OM.Id
				INNER JOIN sStudent.tAcademic AC ON AC.StudentId = SM.Id		--Mantis: 34829, add INNER JOIN by dhruvik
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AC.BatchId		--Mantis: 34829, add INNER JOIN by dhruvik
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = AC.Id AND MT.SourceTypeId = 2001		--Mantis: 34829, change SM.Id => AC.Id and 2003 => 2001 by dhruvik
				INNER Join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftName='+@lShiftColumntName+' And (SMC.ShiftCode='+CONVERT(nvarchar(20),@rShiftCode)+' OR '+CONVERT(nvarchar(20),@rShiftCode)+'=0)
		WHERE
				SM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				--AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND '+@lColumnName+' > DATEADD(minute, SMC.GraceAfter,SMC.StartTime)
				AND SM.StatusId = 1
				--add for 29339 mantis
				AND YEAR(MT.Attn_dt) = YEAR('''+CONVERT(nvarchar(20),@lDate)+''')
				AND BM.IsActive = 1		--Mantis: 34829, add condition by dhruvik'
				
		print (@Query)
		execute (@Query)			
	--END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pStudentBirthdayWishGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rDateOfBirth date
	 	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(replace(replace(replace(@rTemplate,'[Name]',SC.Name),'[Class]',SC.ClassName),'[Division]',SC.DivisionName),'[SchoolName]',OM.Title)
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 OM.Title AS SchoolName,
			 SC.WhatsAppContactNo
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (DAY(SC.DateOfBirth) = DAY(@rDateOfBirth))
		AND (MONTH(SC.DateOfBirth) = MONTH(@rDateOfBirth))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pStudentBirthdayWishSchedulerGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
 
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			replace(replace(@rTemplate,'[Name]',SC.Name),'[SchoolName]',OM.Title)
			 AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			SC.StudentId AS SourceId,
			2003 AS SourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			2003 AS ReceiverSourceTypeId,
			SC.Name AS [Name],
			OM.Title AS SchoolName,
			SC.WhatsAppContactNo AS WhatsAppContactNo,
			'' AS AttachMent
			
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
	WHERE
			(DAY(SC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(SC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		AND (SC.StatusId=1)
		AND (SC.OrgId=@rOrgId)
		AND SC.IsActiveBatch = 1 AND SC.IsBlockAllAlert=0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pStudentDetailGet]
	 
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rUserId bigint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF(@rClassId = 0)
	BEGIN
		SELECT
				BC.ClassId AS Id,
				BC.ClassName AS Title,
				0 AS RollNo	
		FROM
				sSetup.vBatchClass BC
		WHERE 
				BC.IsObsolete = 0
			AND BC.BatchId=@rBatchId ORDER BY BC.OrderIndex
	END
	ELSE IF(@rDivisionId =0)
	BEGIN
		SELECT
				DM.Id,
				DM.Title,
				0 AS RollNo
		FROM
				sSetup.tDivisionMaster DM
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
		WHERE 
				DM.IsObsolete = 0
			AND DM.OrgId=@rOrgId
			AND DM.ClassId=@rClassId 
			AND U.UserId = @rUserId
			ORDER BY DM.OrderIndex
			
	END
	ELSE
	BEGIN
		SELECT 
				SA.AcademicId AS Id,
				SA.Name AS Title,
				SA.RollNo
		FROM 
				[sStudent].[vStudentAcademic]  SA 
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
		WHERE 
					(SA.ClassId=@rClassId)
				AND (SA.DivisionId=@rDivisionId)
				AND SA.BatchId=@rBatchId
				AND SA.OrgID=@rOrgId 
				AND SA.StatusId=1
				AND U.UserId = @rUserId
				ORDER BY SA.DivisionOrder, SA.RollNo
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pStudentGatePassGet]
	
		 @rStudentGatePassId int,
	 	 @rAcademicId bigint,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			replace (		--mantis: 42879
			replace (		--mantis: 42879
			replace (		--add for mantis: 35426
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[EntryModeStatus]',SM.Title),
			'[GatePassDate]',CONVERT(varchar(11),ISNULL(SGP.GatePassDate,'') ,103)),
			'[GatePassTime]',CONVERT(varchar(15),ISNULL(SGP.GatePassTime,''),100)),
			'[ReasonOfGatePass]',SGP.ReasonOfGatePass),
			'[ReceivedBy]',SGP.VisitorName),
			'[Class]',SC.ClassName),		--add for mantis: 35426
			'[Relation]',ISNULL(SGP.Relation,'')),		--mantis: 42879
			'[VisitorName]',ISNULL(SGP.VisitorName,''))	--mantis: 42879
			AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 SC.AcademicId AS ReceiverSourceId,
			 2001 AS SourceTypeId,
			 SC.AcademicId AS SourceId,
			 SM.Title AS EntryModeStatus,
			 CONVERT(varchar(11),ISNULL(SGP.GatePassDate,'') ,103) AS GatePassDate,
			 CONVERT(varchar(15),ISNULL(SGP.GatePassTime,''),100) AS GatePassTime,
			 SGP.ReasonOfGatePass AS ReasonOfGatePass,
			 SGP.VisitorName AS ReceivedBy,
			 SC.WhatsAppContactNo

	FROM 
		sStudent.vStudentCommunication SC
	INNER JOIN 	sFrontOffice.tStudentGatePass SGP ON SC.AcademicId = SGP.AcademicId
	INNER JOIN sCommon.tStatusMaster SM ON SM.Id = SGP.EntryModeStatusId
	WHERE
		SGP.Id=@rStudentGatePassId
		AND SC.AcademicId = @rAcademicId
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pStudentLeaveApproveRejectGet]

	@rAcademicId bigint,
	@rTemplate nvarchar(max),
	@rMailSubject nvarchar(500)='',
	@rLeaveFromDate Date,
	@rLeaveToDate Date,
	@rOrgId int,
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		SA.AcademicId,
		SA.Code,
		SA.Name,
		REPLACE (
		REPLACE (
		REPLACE (
		REPLACE(@rTemplate,'[Name]',SA.Name),
		'[FromDate]',SLR.LeaveFromDate),
		'[ToDate]',SLR.LeaveToDate), 
		'[LeaveReason]',SLR.LeaveReason) AS MsgText,
		@rMailSubject AS Subject,
		2003 AS SourceTypeId,
		SC.StudentId AS SourceId,
		2003 AS ReceiverSourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		SC.OrgGroupId,
		SC.OrgId
		
	From 
		sStudent.vStudentAcademic SA
		INNER JOIN sStudent.vStudentCommunication SC ON SA.AcademicId = SC.AcademicId AND SC.ClassId=SA.ClassId AND SC.DivisionId=SA.DivisionId
		INNER JOIN sAttendance.tStudentLeaveRequest SLR ON SA.AcademicId = SLR.AcademicId
	WHERE
		(SA.OrgId=@rOrgId)
		AND (SA.BatchId=@rBatchId)
		AND SA.AcademicId = @rAcademicId
		AND SLR.LeaveFromDate = @rLeaveFromDate 
		AND SLR.LeaveToDate = @rLeaveToDate
		AND SC.StatusId = 1
		AND SC.IsBlockAllAlert = 0	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pStudentLeaveGet]
	 	 
	 	 @rAcademicId bigint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)='',
	 	 @rLeaveFromDate Date,
		 @rLeaveToDate Date

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			SA.AcademicId,
			SA.Code,
			SA.Name,
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[Name]',SA.Name),
			'[FromDate]',SLR.LeaveFromDate),
			'[ToDate]',SLR.LeaveToDate), 
			'[LeaveReason]',SLR.LeaveReason) AS MsgText,
			@rMailSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EM.Id AS ReceiverSourceId,
			ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			95 AS SourceTypeId,
			EM.Id AS SourceId,
			EM.OrgId,
			OM.OrgGroupId
		
	From 
		sStudent.vStudentAcademic SA
		--INNER JOIN sStudent.vStudentCommunication SC ON SA.AcademicId = SC.AcademicId
		INNER JOIN sAttendance.tStudentLeaveRequest SLR ON SA.AcademicId = SLR.AcademicId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SC.DepartmentId
		LEFT JOIN sHrm.tEmployeeMaster EM ON SA.InchargeEmployeeId = EM.Id	
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id
	WHERE
	
	SA.AcademicId = @rAcademicId
	AND SLR.LeaveFromDate = @rLeaveFromDate 
	AND SLR.LeaveToDate = @rLeaveToDate
	AND EM.IsObsolete = 0 AND ISNULL(EM.IsOtherUser,0) = 0 AND EM.StatusId = 7

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pStudentLeavingCertificateGet]
	 	 
	 	 @rLCId bigint =0,
	 	 @rTemplate nvarchar(max)='',
	 	 @rMailSubject nvarchar(500)=''
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@rTemplate,'[Code]',SC.Code),
		'[Name]',SC.Name),
		'[ClassDivision]',SC.ClassName +' - '+ SC.DivisionName),
		'[LCNumber]',L.LCNumber),
		'[LCDate]',L.LCDate),
		'[CreatedBy]',U.DisplayTitle) AS MsgText,
		@rMailSubject AS [Subject],
		SC.AcademicId AS SourceId,
		2001 AS SourceTypeId,
		SC.OrgId,
		SC.OrgGroupId,
		2001 AS ReceiverSourceTypeId,
		SC.AcademicId AS ReceiverSourceId,
		SC.WhatsAppContactNo,
		SC.ClassName +' - '+ SC.DivisionName AS ClassDivision,
		L.LCNumber AS LCNumber,
		L.LCDate,
		U.DisplayTitle AS CreatedBy
	FROM 
		sStudent.vStudentCommunication SC
		INNER JOIN sCertificate.tLeaving L ON L.AcademicId=SC.AcademicId
		INNER JOIN sSecurity.tUser U ON U.Id = L.CreatedUserId
	WHERE
		L.Id = @rLCId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pStudentListGet]
	 	 
	 	 @rOrgId int,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)='',
	 	 @rStatusId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
            REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE (
			REPLACE(@rTemplate,'[Name]',SC.Name),
			'[Code]',SC.Code),
			'[Class]',SC.ClassName), 
			'[Division]',SC.DivisionName),
			'[RollNo]',SC.RollNo),
			'[Organization]',OM.DisplayTitle),
			'[Batch]',BM.Title),
			'[Department]',DM.Title) AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			SC.RollNo AS RollNo,
			OM.DisplayTitle AS Organization,
			BM.Title AS Batch,
			DM.Title AS Department,
			SC.WhatsAppContactNo
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SC.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SC.DepartmentId
			
	WHERE
	(SC.OrgId=@rOrgId)
	AND (SC.BatchId=@rBatchId) AND SC.IsBlockAllAlert=0
	AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((SC.StatusId = @rStatusId) OR (@rStatusId =0))

    ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlert].[pStudentPendingDocumentsGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,
	@rTemplate nvarchar(max),
	@rMailSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		REPLACE (REPLACE(@rTemplate,'[StudentName]',SC.Name),'[Documents]',[sAlert].[fPendingDocumentsGet](SC.StudentId,2001)) AS Template,
		@rMailSubject AS MailSubject,
		[sAlert].[fPendingDocumentsGet](SC.StudentId,2001) AS Documents,
		SC.WhatsAppContactNo
	FROM 
		sStudent.vStudentCommunication SC
	WHERE	
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
		AND [sAlert].[fPendingDocumentsGet](SC.StudentId,2001) != ''
		ORDER BY SC.ClassOrderIndex,SC.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlert].[pStudentSMSHistoryGet]
	
	@rOrgId smallint,
	@rStatusId int,
	@rContactId nvarchar(50),
	@rEventId int,
	@rSourceEvent nvarchar(50),
	@rUserName nvarchar(100),
	@rAlertModeId tinyint,
	@rFromDate date,
	@rToDate date,
	@rOrgGroupId int,
	@rCode nvarchar(max),
	--@rReceiverSourceTypeId int,
	@rIsHistory bit = 0,
	@rBatchId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF(@rIsHistory = 1)
BEGIN
	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code,
				CM.Title +'-'+ DM.Title AS ClassDivision,
			    (SA.FirstName +' ' + SA.MiddleName + ' ' + SA.LastName)AS StudentName

		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			INNER JOIN sStudent.tAcademic A ON SA.Id = A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
			
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=2003)	
			AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
			AND A.BatchId = @rBatchId
			--ORDER BY AL.CreatedDateTime DESC

	UNION

	SELECT 
		AL.Id AS Id,
		AL.ContactId,
		AL.AlertMessage,
		AL.AlertSubject,
		CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
		--AL.ResultMessage
		EM.Title AS EventName,
		AL.SourceEvent,
		U.DisplayTitle AS UserName,
		AL.CreatedDateTime,
		OM.Id AS OrgId,
		OM.DisplayTitle AS Organization,
		SA.Code AS Code,
		CM.Title +'-'+ DM.Title AS ClassDivision,
		(SA.FirstName +' ' + SA.MiddleName + ' ' + SA.LastName)AS StudentName				
	FROM
			sAlert.tAlertLogHistory AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
		--INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
		--INNER JOIN sStudent.tAcademic A ON SA.Id = A.StudentId
		INNER JOIN sStudent.tAcademic A ON A.Id = AL.ReceiverSourceId
		INNER JOIN sStudent.tStudentMaster SA ON SA.Id=A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
		INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
			
WHERE
		((AL.OrgId=@rOrgId) OR (@rOrgId=0))
	AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
	AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
	AND ((AL.EventId=@rEventId) OR (@rEventId=0))
	AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
	AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
	AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
	AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND OM.OrgGroupId = @rOrgGroupId	
	AND (AL.ReceiverSourceTypeId=2001)	
	AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
	AND A.BatchId = @rBatchId
	--ORDER BY AL.CreatedDateTime DESC
END

ELSE
BEGIN
	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code,
				CM.Title +'-'+ DM.Title AS ClassDivision,
			    (SA.FirstName +' ' + SA.MiddleName + ' ' + SA.LastName)AS StudentName
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			INNER JOIN sStudent.tAcademic A ON SA.Id = A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
			
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=2003)	
			AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
			AND A.BatchId = @rBatchId
			--ORDER BY AL.CreatedDateTime DESC

	UNION

	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code,
				CM.Title +'-'+ DM.Title AS ClassDivision,
			    (SA.FirstName +' ' + SA.MiddleName + ' ' + SA.LastName)AS StudentName			
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			INNER JOIN sStudent.tAcademic A ON A.Id = AL.ReceiverSourceId
			INNER JOIN sStudent.tStudentMaster SA ON SA.Id=A.StudentId
			--INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			--INNER JOIN sStudent.tAcademic A ON SA.Id = A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
			
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=2001)	
			AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
			AND A.BatchId = @rBatchId
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pStudentTriggerSet]	 	 
	 	 @rEnabled bit	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  
	    IF(@rEnabled=1)
	      BEGIN
	        ALTER TABLE sStudent.tStudentMaster ENABLE TRIGGER AuditStudentMaster
		    ALTER TABLE sStudent.tStudentAdmission ENABLE TRIGGER AuditStudentAdmission
		    ALTER TABLE sStudent.tStudentCommunication ENABLE TRIGGER AuditStudentCommunication
		    ALTER TABLE sStudent.tStudentOther ENABLE TRIGGER AuditStudentOther
		    ALTER TABLE sStudent.tStudentHealth ENABLE TRIGGER AuditStudentHealth
		    ALTER TABLE sStudent.tStudentSibling ENABLE TRIGGER AuditStudentSibling
		    ALTER TABLE sStudent.tStudentAdditional ENABLE TRIGGER AuditStudentAdditional
		  END
		ELSE
		  BEGIN
		    ALTER TABLE sStudent.tStudentMaster DISABLE TRIGGER AuditStudentMaster
		    ALTER TABLE sStudent.tStudentAdmission DISABLE TRIGGER AuditStudentAdmission
		    ALTER TABLE sStudent.tStudentCommunication DISABLE TRIGGER AuditStudentCommunication
		    ALTER TABLE sStudent.tStudentOther DISABLE TRIGGER AuditStudentOther
		    ALTER TABLE sStudent.tStudentHealth DISABLE TRIGGER AuditStudentHealth
		    ALTER TABLE sStudent.tStudentSibling DISABLE TRIGGER AuditStudentSibling
		    ALTER TABLE sStudent.tStudentAdditional DISABLE TRIGGER AuditStudentAdditional    
		  END   
		  
		  SELECT 1     
		  
END

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pSubjectwiseAttendanceGet]	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int=0,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rMailSubject nvarchar(500)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rSubjectId = 0 OR @rSubjectId IS NULL)
	BEGIN 
		select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[FromDate]',CONVERT(VARCHAR(10), @rFromDate, 103)),
			'[ToDate]',CONVERT(VARCHAR(10), @rToDate, 103)),
			'[TotalCount]',(isnull(TCount,0.00)+isnull(ACount,0.00))),
			'[PresentCount]',convert(decimal(12,2),isnull(TCount,0.00))),
			'[AbsentCount]',convert(decimal(12,2),isnull(ACount,0.00))),
			'[AveragePresence]',case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
								convert(decimal(12,2),(convert(decimal(12,2),isnull(TCount,0.00)*100)/convert(decimal(12,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
								else 0.00 end),
			'[AbsentDates]',[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId)),
			'[SubjectName]','All Subject')
			AS MsgText,			 
			@rMailSubject AS Subject,
			2001 AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			(isnull(TCount,0.00)+isnull(ACount,0.00)) as TotalCount,
			convert(decimal(12,2),isnull(TCount,0.00)) as PresentCount,
			convert(decimal(12,2),isnull(ACount,0.00)) as AbsentCount,
			case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
							convert(decimal(12,2),(convert(decimal(12,2),isnull(TCount,0.00)*100)/convert(decimal(12,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
							else 0.00 end as AveragePresence,
			[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId) AS AbsentDates,
			SC.WhatsAppContactNo
	FROM 
	sStudent.vStudentCommunication SC 
	LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS TCount 
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 		
			SR1.AttendanceTypeId=5
			AND SR1.IsPresent =1 
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) TC ON TC.AcademicId = SC.AcademicId
    LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS ACount  
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 
			SR1.IsPresent = 0		
			AND SR1.AttendanceTypeId=5
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 	 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) AC ON AC.AcademicId = SC.AcademicId
	--INner JOIn sSetup.vClassSubject CS  On  CS.IsObsolete = 0 AND CS.ClassId=@rClassId 
	WHERE
	 SC.BatchId = @rBatchId
	 AND ((SC.ClassId = @rClassId))
	 AND ((SC.DivisionId = @rDivisionId) OR @rDivisionId=0)
	 AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	 Order by SC.AcademicId 
	END
	ELSE
	BEGIN
		select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[FromDate]',CONVERT(VARCHAR(10), @rFromDate, 103)),
			'[ToDate]',CONVERT(VARCHAR(10), @rToDate, 103)),
			'[TotalCount]',(isnull(TCount,0.00)+isnull(ACount,0.00))),
			'[PresentCount]',convert(decimal(12,2),isnull(TCount,0.00))),
			'[AbsentCount]',convert(decimal(12,2),isnull(ACount,0.00))),
			'[AveragePresence]',case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
								convert(decimal(12,2),(convert(decimal(12,2),isnull(TCount,0.00)*100)/convert(decimal(12,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
								else 0.00 end),
			'[AbsentDates]',[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId)),
			'[SubjectName]',CS.SubjectName)
			AS MsgText,			 
			@rMailSubject AS Subject,
			2001 AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			(isnull(TCount,0.00)+isnull(ACount,0.00)) as TotalCount,
			convert(decimal(12,2),isnull(TCount,0.00)) as PresentCount,
			convert(decimal(12,2),isnull(ACount,0.00)) as AbsentCount,
			case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
							convert(decimal(12,2),(convert(decimal(12,2),isnull(TCount,0.00)*100)/convert(decimal(12,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
							else 0.00 end as AveragePresence,
			[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId) AS AbsentDates,
			SC.WhatsAppContactNo
	 from 
	sStudent.vStudentCommunication SC 
	LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS TCount 
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 		
			SR1.AttendanceTypeId=5
			AND SR1.IsPresent = 1 
			AND (SR1.SubjectId=@rSubjectId OR (ISNULL(@rSubjectId,0)=0))
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) TC ON TC.AcademicId = SC.AcademicId
    LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS ACount  
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 
		   SR1.IsPresent = 0		
			AND SR1.AttendanceTypeId=5
			AND (SR1.SubjectId=@rSubjectId OR (ISNULL(@rSubjectId,0)=0)) 
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 	 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) AC ON AC.AcademicId = SC.AcademicId
	INner JOIn sSetup.vClassSubject CS  On  CS.IsObsolete = 0 AND CS.ClassId=@rClassId 
	WHERE
	 SC.BatchId = @rBatchId
	 AND ((SC.ClassId = @rClassId))
	 AND ((SC.DivisionId = @rDivisionId) OR @rDivisionId=0)
	 AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	 AND (CS.SubjectId=@rSubjectId OR @rSubjectId= 0)
	 Order by SC.AcademicId 
	END
	
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pSubjectwiseStudentAttendanceStatusGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 --@rSubjectId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 --@rIsPresent bit,
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--SET @rToDate = dateadd(d,1,@rToDate)
	CREATE TABLE #TMP 
	(
	AcademicId bigint,
	Code nvarchar(20),
	Name nvarchar(300),
	MobileNo nvarchar(50),
	EmailId nvarchar(50),
	SubjectId bigint,
	AttendanceDate Date,
	DivisionName nvarchar(100),
	WhatsAppContactNo nvarchar(20)
	)
	INSERT INTO #TMP
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			SR.SubjectId,
			SR.AttendanceDate,
			DM.Code
			,SC.WhatsAppContactNo
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SR.SubjectId=SM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON SC.DivisionId=DM.Id
			
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		--AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
		GROUP BY SC.AcademicId,SC.Code,SC.Name,SC.ParentContactNo,	SC.ParentEmail,SR.SubjectId,SR.AttendanceDate,DM.Code,SC.WhatsAppContactNo
   --ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno
   --Select * from #TMP
   Select 
   			AcademicId,
			Code,
			Name,
			MobileNo,	
			EmailId,
			AttendanceDate,
			replace (
			replace (
			replace(@rTemplate,'[Name]',tmp.Name),
			--'[Class]',ClassName),
			'[Division]',tmp.DivisionName),
			--'[AbsentDates]',SR.AttendanceDate),
			'[SubjectLectureStatusReason]', CHAR(13) +[sAlert].[fPeriodWiseAttendanceGet](tmp.AcademicId,STUFF(
                 (SELECT ',' + CONVERT(VARCHAR,tmp1.SubjectId) FROM #TMP tmp1
				  WHERE tmp1.AcademicId=tmp.AcademicId 
				  FOR XML PATH ('')), 1, 1, ''
               ),AttendanceDate,@rOrgId))
			AS MsgText,
			[sAlert].[fPeriodWiseAttendanceGet](tmp.AcademicId,STUFF(
                 (SELECT ',' + CONVERT(VARCHAR,tmp1.SubjectId) FROM #TMP tmp1
				  WHERE tmp1.AcademicId=tmp.AcademicId 
				  FOR XML PATH ('')), 1, 1, ''
               ),AttendanceDate,@rOrgId),
			@rMailSubject AS Subject,			   
			ISNULL(tmp.WhatsAppContactNo,'') AS WhatsAppContactNo
		
    from #TMP tmp
	GROUP BY AcademicId,Code,Name,MobileNo,EmailId,AttendanceDate,DivisionName,WhatsAppContactNo

	DROP TABLE #TMP
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pTemplateMasterAdd]
	@rOrgId [int],
	@rTitle [nvarchar](100),
	@rRemark [nvarchar](300),
	@rAlertModeId [tinyint],
	@rEventId [smallint],
	@rContentValue [nvarchar](max),
	@rIsObsolete [bit],
	@rCreatedBy [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

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


	INSERT INTO sAlert.tTemplateMaster
		(
			Id,
			Title,
			Remark,
			AlertModeId,
			EventId,
			ContentValue,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rAlertModeId,
			@rEventId,
			@rContentValue,
			@rIsObsolete,
			@rCreatedBy,
			sCommon.fGetDate(),
			@rCreatedBy,
			sCommon.fGetDate(),
			@rOrgId
		)


	SELECT @lNextNumber AS Result
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pTemplateMasterGet]
	@rOrgId [int] = 0,
	@rId [int] = 0,
	@rTitle [nvarchar](100) = '',
	@rSearch [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF ( @rSearch = 1 )
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)	
	END

	 SELECT TM.Id TemplateId,
			TM.Title,
			TM.Remark,
			AlertModeId,
			EventId,
			ContentValue,
			TM.IsObsolete,
			TM.CreatedUserId,
			TM.CreatedDateTime,
			TM.UpdatedUserId,
			TM.UpdatedDateTime,
			EM.ModuleId
	   FROM sAlert.tTemplateMaster TM
			INNER JOIN sAlert.tEventMaster EM ON EM.Id = TM.EventId
	  WHERE ((TM.Id = @rId) OR (@rId = 0)) AND
			((TM.Title LIKE @rTitle) OR (@rTitle = ''))
			AND TM.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pTemplateMasterModify]
	@rId [smallint],
	@rTitle [nvarchar](100),
	@rRemark [nvarchar](300),
	@rAlertModeId [tinyint],
	@rEventId [smallint],
	@rContentValue [nvarchar](max),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAlert.tTemplateMaster
		SET 
			Title = @rTitle,
			Remark = @rRemark,
			AlertModeId = @rAlertModeId,
			EventId = @rEventId,
			ContentValue = @rContentValue,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  
	  SELECT 1 AS Result


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pTemplateMasterViewColumnsGet]
	@rEventId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lTableName			Nvarchar(50) 
DECLARE	@lViewName			Nvarchar(50) 
DECLARE	@lSchemaName		Nvarchar(50)	

SELECT 
				@lTableName = ViewName 
		FROM 
				sAlert.tEventMaster 
		WHERE 
				Id = @rEventId



SELECT @lSchemaName = SUBSTRING(@lTableName, 1, CHARINDEX('.', @lTableName, 1)-1)
SELECT @lViewName = SUBSTRING(@lTableName, CHARINDEX('.', @lTableName, 1) + 1, LEN(@lTableName))

--SELECT @lTableName	[Table Name]
--SELECT @lViewName	[View Name]
--SELECT @lSchemaName	[Schema Name]	

	SELECT 
		column_name [ColumnNames], ORDINAL_POSITION AS ORGINAL_POSITION
	FROM 
		information_schema.columns
	WHERE 
		table_name = @lViewName AND 
		table_schema = @lSchemaName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pTotalPendingFeeGet]

		 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rToDate date,
	 	 @rMailSubject nvarchar(500)='',
	 	 @rAdmissionCategoryId int=0,
	 	 @rIdNos nvarchar(500)='',
		 @rDepartmentId int=0,
		 @rCollectionGroupId int=0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	CREATE TABLE #TempOptional (
		Id int,
		Amount decimal(12,2),
		StartDate date,
		EndDate date,
		ReceiptBookId int,
		AcademicId bigint
	)
	
	CREATE TABLE #TempReceipt (
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint
	)
	
	INSERT INTO #TempOptional
	SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			
			UNION ALL

			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))

	
	INSERT INTO #TempReceipt
	SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId
			FROM
				sFee.tReceipt R 

				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0) 
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			GROUP BY 
				FeeSetupId,R.SourceId
	
	--SELECT * FROM #TempOptional
	--SELECT * FROM #TempReceipt

	SELECT 
		D.AcademicId,
		D.RollNo,
		D.Name,
		D.Code,
		D.MobileNo,	
		D.EmailId,
		D.StudentContactNo,
		D.StudentEmail,
		D.FatherContactNo,
		D.FatherMail,
		D.MotherContactNo,
		D.MotherMail,
		SUM(D.PendingAmount) As PendingAmount,		
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',D.Name),		
		'[PendingAmount]',CONVERT(int,(SUM(D.PendingAmount)))),
		'[Code]',D.Code)
		AS Template,
		@rMailSubject AS [Subject],				
		D.WhatsAppContactNo,
		CONVERT(int,(SUM(D.Amount))) AS Amount,
		CONVERT(int,(SUM(D.VariableAmount))) AS VariableAmount,
		CONVERT(int,(SUM(D.NAAmount))) AS NAAmount,
		CONVERT(int,(SUM(D.Discount))) AS DiscountAmount,
		CONVERT(int,(SUM(D.PaidAmount))) AS PaidAmount
	FROM
	(
	SELECT
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.ClassName,
		SA.DivisionName,
		SA.Code,
		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,
		SA.DivisionOrder,
		(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) - ISNULL(FA.DiscountAmount,0.00) - ISNULL(R.PaidAmount,0.00))  AS PendingAmount,
		SC.WhatsAppContactNo,
		ISNULL(FS.Amount,0.00) AS Amount,
		ISNULL(FA.VariableAmount,0.00) AS VariableAmount,
		ISNULL(FA.AdditionalAmount,0.00) AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00) AS NAAmount,
		ISNULL(FA.DiscountAmount,0.00) AS Discount,
		ISNULL(R.PaidAmount,0.00) AS PaidAmount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN  #TempOptional FS ON FS.AcademicId=SA.AcademicId 
		LEFT JOIN sFee.tFeeAllocation FA
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #TempReceipt	R ON SA.AcademicId = R.SourceId AND R.FeeSetupId = FS.Id
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN  sStudent.vStudentCommunication SC ON SC.AcademicId = SA.AcademicId
	WHERE	
		SA.StatusId = 1 AND SC.IsBlockAllAlert=0 
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
		AND ((FS.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))			
		AND (SA.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		
		) D
	GROUP BY 
		D.AcademicId,D.RollNo,D.Name,D.ClassName,D.DivisionName,D.Code,
		D.MobileNo,D.EmailId,D.StudentContactNo,D.StudentEmail,D.FatherContactNo,D.FatherMail,D.MotherContactNo,D.MotherMail,D.DivisionOrder,D.WhatsAppContactNo
	HAVING CONVERT(int,(SUM(D.PaidAmount))) = 0
	ORDER BY 
		D.Code	

	DROP TABLE #TempOptional
	DROP TABLE #TempReceipt
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAlert].[pTransportAttendanceListGet]	 
	@rBusRouteId int,
	@rRouteMode nvarchar(5),
	@rOrgGroupBatchId int,
	@rOrgGroupId int,
	@rAttendanceDate date,
	@rTemplate nvarchar(max),
	@rMailSubject nvarchar(500),
	@rIsPresent bit = 0,
	@rStudentIds nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lTransportMode nvarchar(10)
IF(UPPER(@rRouteMode) = 'IN')
    SET @lTransportMode = 'Pickup'
ELSE
    SET @lTransportMode = 'Drop'

BEGIN
	SELECT 
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		CASE WHEN @rIsPresent = 0 THEN --for absent
		REPLACE (REPLACE (			
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',SC.Name),
		'[Class]',SC.ClassName),
		'[Division]',SC.DivisionName),
		'[AbsentDates]',ATR.AttendanceDate),
		'[TransportMode]',@lTransportMode)
		ELSE --for present
		REPLACE(REPLACE (					
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',SC.Name),
		'[Class]',SC.ClassName),
		'[Division]',SC.DivisionName),
		'[PresentDates]',ATR.AttendanceDate),
		'[TransportMode]',@lTransportMode)			
		END
			AS MsgText,
		@rMailSubject AS Subject,
		SC.AcademicId AS SourceId,
		2001 AS SourceTypeId,
		SC.OrgId,
		SC.OrgGroupId,
		SC.AcademicId AS ReceiverSourceId,
		2001 AS ReceiverSourceTypeId,
		SC.ClassName AS Class,
		SC.DivisionName AS Division,
		SC.WhatsAppContactNo
	FROM 
		sStudent.vStudentCommunication SC
		INNER JOIN sTransport.tAssignRoute  AR ON SC.StudentId = AR.SourceId AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM 
		ON (BRDM.Id = AR.PickupDestinationId AND UPPER(@rRouteMode)='IN')OR(BRDM.Id = AR.DropDestinationId AND UPPER(@rRouteMode)='OUT')
		INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id=BRDM.BusRouteId
		LEFT JOIN sTransport.tAttendanceRegister ATR ON ATR.SourceId=SC.StudentId 
			
	WHERE 
		BRDM.BusRouteId = @rBusRouteId
		AND BR.OrgGroupBatchId=@rOrgGroupBatchId
		AND SC.OrgGroupBatchId=@rOrgGroupBatchId 
		AND BR.OrgGroupId=@rOrgGroupId
		AND ATR.AttendanceDate=@rAttendanceDate
		AND (
        (@rRouteMode = 'IN' AND  ISNULL(ATR.IsPresentPickup, 0) = @rIsPresent) OR
        (@rRouteMode = 'OUT' AND  ISNULL(ATR.IsPresentDrop, 0) = @rIsPresent)
		)
		AND SC.IsActiveBatch = 1
        AND SC.StatusId = 1
		AND SC.StudentId IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStudentIds,','))

	ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pTriggerMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			TitleResourceKeyId,
			Remark
	   FROM sAlert.tTriggerMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAlert].[pUserPasswordChangeListGet]
	 	 
	 	 @rOrgId int,
	 	 @rBatchId int,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(500)='',
		 @rPasswordReminderDays int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--DECLARE @lCurrentDateTime DateTime = GETDATE() 
	DECLARE @lFinalDateTime DateTime = DATEADD(day,- @rPasswordReminderDays,GETDATE())

	SELECT 
			SC.AcademicId AS SourceId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
            @rTemplate AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.WhatsAppContactNo
	From 
	
		sStudent.vStudentCommunication SC
		INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SC.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SC.DepartmentId
			
	WHERE
	(SC.OrgId=@rOrgId)
	AND (SC.BatchId=@rBatchId)
	AND ((SC.StatusId = 1))
	AND (U.UpdatedDateTime <= @lFinalDateTime)

    --ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno 

	UNION 

	SELECT 
			EC.EmployeeId AS SourceId,
			EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
            @rTemplate AS MsgText,
			@rMailSubject AS Subject,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.WhatsAppContactNo
	From 
	
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId=95
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
		--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EC.BatchId
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EC.DepartmentId
			
	WHERE
	(EC.OrgId=@rOrgId)
	--AND (SC.BatchId=@rBatchId)
	AND ((EC.StatusId = 7))
	AND (U.UpdatedDateTime <= @lFinalDateTime)

    

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pViewQueryGet]

	 	 @rQueryId bigint,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--mantis: 44100, start
	IF(@rFromSourceTypeId=0)
	BEGIN
		SELECT @rFromSourceTypeId=FromSourceTypeId FROM sCommunication.tQuery WHERE Id=@rQueryId
	END
	--mantis: 44100, end

	IF(@rFromSourceTypeId=2003)
	BEGIN
		SELECT
			QM.Id AS QueryId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			--'mohit.patel@vidyalayaschoolsoftware.com' AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (
				replace (
					replace(
						@rTemplate,'[Name]',SC.Name),
						'[Status]',CASE WHEN QM.StatusId = 209 THEN 'Open'
										WHEN QM.StatusId = 210 THEN 'Closed'
										WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END),
						'[QueryNo]',QM.number)
					AS MsgText,

			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.Name AS Name,
			(CASE WHEN QM.StatusId = 209 THEN 'Open' 
				WHEN QM.StatusId = 210 THEN 'Closed' 
				WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END) [Status1],	--mantis: 44100, change column name Status => Stauts1
			QM.number AS QueryNo,
			SC.WhatsAppContactNo
		FROM
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId
		WHERE
			QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId AND BM.IsActive=1 AND SC.IsBlockAllAlert=0
	END
	IF(@rFromSourceTypeId=95)
	BEGIN
		SELECT
			QM.Id AS QueryId,
			ISNULL(EM.CompanyEmail,'') AS EmailId,
			ISNULL(EM.MobileNumber,'') AS MobileNo,
			replace(
				replace(
					replace(
						@rTemplate,'[Name]',EM.EmployeeName),
						'[Status]',CASE WHEN QM.StatusId = 209 THEN 'Open'
										WHEN QM.StatusId = 210 THEN 'Closed'
										WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END),
						'[QueryNo]',QM.number)
					AS MsgText,

			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EM.EmployeeId AS ReceiverSourceId
		FROM
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId
		WHERE
			QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId
	END
END

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAlert].[pWeeklyAttendanceGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rFromDate datetime,
	 	 @rToDate datetime,
	 	 @rMailSubject nvarchar(500)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (						
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),			
			'[TotalCount]',ISNULL(COUNT(MR.AcademicId),0)),
			'[PresentCount]',ISNULL(CASE WHEN MR.IsPresent = 1 THEN COUNT(MR.AcademicId) END,0)),
			'[AbsentCount]',ISNULL(CASE WHEN MR.IsPresent = 0 THEN COUNT(MR.AcademicId) END,0))			
			 AS Template,
			 @rMailSubject AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 SC.AcademicId AS ReceiverSourceId,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,			 
			 ISNULL(CASE WHEN MR.IsPresent = 1 THEN COUNT(MR.AcademicId) END,0) AS PresentCount,
			 ISNULL(CASE WHEN MR.IsPresent = 0 THEN COUNT(MR.AcademicId) END,0) AS AbsentCount,
			 ISNULL(COUNT(MR.AcademicId),0) AS TotalCount,			 
			 SC.WhatsAppContactNo
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister MR ON MR.AcademicId=SC.AcademicId	
			AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((MR.AttendanceDate >= @rFromDate) OR (@rFromDate=''))
			AND ((MR.AttendanceDate <= @rToDate) OR (@rToDate=''))			
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
		--ORDER BY SC.DivisionOrderIndex,SC.Rollno
		GROUP BY SC.AcademicId,
			SC.Code,
			SC.Name,
			MR.IsPresent,
			SC.ParentContactNo,	
			SC.ParentEmail,
			SC.StudentContactNo,
			SC.StudentEmail,
			SC.FatherContactNo,
			SC.FatherMail,
			SC.MotherContactNo,
			SC.MotherMail,
			SC.ClassName,
			SC.DivisionName,
			SC.WhatsAppContactNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pWhatsAppConfigurationAdd]
	
	@rOrgId smallint,
	@rWhatsAppURL nvarchar(1000),	
	@rAdminUsername nvarchar(50),
	@rAdminPassword nvarchar(50),			
	@rOrgGroupId smallint,
	@rIsAllOrg bit,	
	@rRegisteredContactNo nvarchar(20),
	@rWhatsAppNamespace nvarchar(100) = ''	,
	@rWhatsAppVendorId smallint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 IF(@rIsAllOrg=1)
	 BEGIN
		DECLARE @lCount INT
		CREATE TABLE #tTable  
		(
			Id bigint identity,
			OrgId smallint
		)
		INSERT INTO #tTable
		(
			OrgId
		)
		SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId
		
		SELECT @lCount =  COUNT(Id) FROM #tTable
		WHILE @lCount > 0 
		BEGIN
			SELECT @rOrgId=OrgId FROM #tTable WHERE Id = @lCount
			IF NOT EXISTS(SELECT OrgId FROM sAlert.tWhatsAppConfiguration WHERE OrgId=@rOrgId)
BEGIN

	INSERT INTO sAlert.tWhatsAppConfiguration
		(
			OrgId,
			WhatsAppURL,			
			AdminUsername,
			AdminPassword,
			RegisteredContactNo,
			WhatsAppNamespace,
			VendorId
		)
	VALUES
		(
			@rOrgId,
			@rWhatsAppURL,
			@rAdminUsername,
			@rAdminPassword,			
			@rRegisteredContactNo,
			@rWhatsAppNamespace,
			@rWhatsAppVendorId
		)
		             
	END	 
	 ELSE
	 BEGIN
	    UPDATE  sAlert.tWhatsAppConfiguration
	    SET
			WhatsAppURL=@rWhatsAppURL,
			AdminUsername=@rAdminUsername,
			AdminPassword=@rAdminPassword,
			RegisteredContactNo=@rRegisteredContactNo,
			WhatsAppNamespace=@rWhatsAppNamespace,
			VendorId=@rWhatsAppVendorId
	      WHERE OrgId = @rOrgId 	   
	 END  
		SELECT @rOrgId AS Result
			SET @lCount = @lCount - 1
		END
	 END
	 ELSE
	 BEGIN
	 
 IF NOT EXISTS(SELECT OrgId FROM sAlert.tWhatsAppConfiguration WHERE OrgId=@rOrgId)
BEGIN

	INSERT INTO sAlert.tWhatsAppConfiguration
		(
			OrgId,
			WhatsAppURL,			
			AdminUsername,
			AdminPassword,
			RegisteredContactNo,
			WhatsAppNamespace,
			VendorId
		)
	VALUES
		(
			@rOrgId,
			@rWhatsAppURL,
			@rAdminUsername,
			@rAdminPassword,			
			@rRegisteredContactNo,
			@rWhatsAppNamespace,
			@rWhatsAppVendorId
		)
		             
	END	 
	 ELSE
	 BEGIN
	    UPDATE  sAlert.tWhatsAppConfiguration
	    SET
			WhatsAppURL=@rWhatsAppURL,
			AdminUsername=@rAdminUsername,
			AdminPassword=@rAdminPassword,
			RegisteredContactNo=@rRegisteredContactNo,
			WhatsAppNamespace=@rWhatsAppNamespace,
			VendorId=@rWhatsAppVendorId			
	      WHERE OrgId = @rOrgId 	   
	 END  
		SELECT @rOrgId AS Result
	END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAlert].[pWhatsAppConfigurationGet]
	 
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT
			WC.WhatsAppURL,
			WC.AdminUsername,
			WC.AdminPassword,
			WC.RegisteredContactNo,
			CASE -- Added for vendorid 3
				WHEN WC.VendorId = 3
					THEN ISNULL(WC.WhatsAppNamespace,'')
				ELSE WC.Token
			END AS Token,
			ISNULL(WC.WhatsAppNamespace,'') AS 	WhatsAppNamespace,
			ISNULL(WC.VendorId,1) AS VendorId
	FROM
			sAlert.tWhatsAppConfiguration WC
	WHERE 
			WC.OrgId=@rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlert].[pWhatsAppHistoryGet]

@rSourceId bigint = 0,
@rSourceTypeId smallint = 0 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT
			WL.AutoId,
			WL.SourceId,
			WL.SourceTypeId,
			WL.CreatedDateTime,
			WL.WhatsAppMessage AS [Message],
			'' AS Attachment
		FROM 
			sAlert.tWhatsAppLog WL
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = WL.SourceId AND WL.SourceTypeId = 2003			
		WHERE
			WL.SourceId = @rSourceId AND WL.SourceTypeId = @rSourceTypeId
		
		UNION ALL 

		SELECT 
			0,
			@rSourceId AS SourceId, 
			@rSourceTypeId AS SourceTypeId,
			AL.CreatedDateTime,
			AL.AlertMessage AS [Message],
			ISNULL(AAL.AttachmentPath,'') AS Attachment
		FROM 
			sAlert.tAlertLog AL			
			INNER JOIN sStudent.tStudentCommunication SC ON SC.WhatsAppContactNo = AL.ContactId  
			LEFT JOIN sAlert.tAlertAttachmentLog AAL ON AAL.AlertLogId = AL.Id
		WHERE 
			SC.StudentId = @rSourceId AND AL.AlertModeId = 4 AND AL.AlertMessage <> ''  
		ORDER By 
			CreatedDateTime DESC

	END
	ELSE IF(@rSourceTypeId=95)
	BEGIN
		SELECT
			WL.AutoId,
			WL.SourceId,
			WL.SourceTypeId,
			WL.CreatedDateTime,
			WL.WhatsAppMessage AS [Message],
			'' AS Attachment		
		FROM 
			sAlert.tWhatsAppLog WL
			INNER JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = WL.SourceId AND WL.SourceTypeId = 95			
		WHERE
			WL.SourceId = @rSourceId AND WL.SourceTypeId = @rSourceTypeId


		UNION ALL 

		SELECT 
			0,
			@rSourceId AS SourceId, 
			@rSourceTypeId AS SourceTypeId,
			AL.CreatedDateTime,
			AL.AlertMessage AS [Message],
			ISNULL(AAL.AttachmentPath,'') AS Attachment
		FROM 
			sAlert.tAlertLog AL 			
			INNER JOIN sHrm.tEmployeeCommunications EC ON EC.WhatsAppContactNo = AL.ContactId  
			LEFT JOIN sAlert.tAlertAttachmentLog AAL ON AAL.AlertLogId = AL.Id
		WHERE 
			EC.EmployeeId = @rSourceId AND AL.AlertModeId = 4 AND AL.AlertMessage <> ''  
		ORDER By 
			CreatedDateTime DESC
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAlumni].[pPendingGet] 
	
	--@rId int  =0,
		@rFirstName nvarchar(100) = NULL,
		@rLastName nvarchar(100) = NULL,
		@rOrgId int  = 0,
		@rClassId bigint = 0,
		@rBatchId bigint =0,
		--@rRegistrationId int=0
		@rCode nvarchar(20) = null,
		@rOrgGroupId int = 0,
		@rOrgGroupBatchId bigint =0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--IF NOT EXISTS (SELECT 1 FROM sAlumni.tRegistration WHERE MappedStudentId <>1)	
BEGIN
SELECT DISTINCT  
	SF.AcademicId,
	SF.Name,
	OM.Title AS[OrgantionName],
	SF.OrgId AS[OrgantionId],
	BM.Title AS[PassingBatch],
	CM.DisplayTitle AS[PassingClass],
	ISNULL(R.MappedStudentId,0) AS MappedStudentId
	FROM sStudent.vStudentFull SF
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=SF.ClassId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SF.BatchId
	LEFT JOIN sAlumni.tRegistration R ON R.MappedStudentId = SF.AcademicId
	Where
	((SF.FirstName like '%'+@rFirstName+'%') OR (@rFirstName=''))
	AND ((SF.LastName like '%'+@rLastName+'%') OR (@rLastName=''))
	AND ((SF.OrgId=@rOrgId) OR (@rOrgId=0))
	AND((SF.BatchId = @rBatchId ) OR (@rBatchId = 0))
	AND ((SF.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SF.Code = ''+@rCode+'') OR (@rCode=''))
	AND ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAlumni].[pRegistrationAdd] 
		@rId bigint = 0, 
		@rFirstName nvarchar(100),
		@rMiddleName nvarchar(100),
		@rLastName nvarchar(100),
		@rGenderId tinyint,
		@rRegistrationDate date,
		@rEmailId nvarchar(150),
		@rMobileNo nvarchar(11),
		@rOrgId int,
		@rPassingBatchId int,
		@rPassingClassId int,
		@rMappedStudentId bigint=0,
		@rEmployeementTypeId int,
		@rEmployerName nvarchar(150),
		@rDesignation nvarchar(150),
		@rEmployeementCountry nvarchar(150),
		@rEmployeementState nvarchar(150),
		@rEmployeementCity nvarchar(150),
		@rSpecialAchievement nvarchar(500),
		@rUniversityName nvarchar(200),
		@rHigherStudyCountry nvarchar(150),
		@rHigherStudyState nvarchar(150),
		@rHigherStudyCity nvarchar(150),
		@rResidentialCountry nvarchar(150),
		@rResidentialState nvarchar(150),
		@rResidentialCity nvarchar(150),
		@rOfficePhone nvarchar(150),
		@rResidentialPhone nvarchar(150),
		@rCreatedUserId bigint=0  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION		
	DECLARE @lNextNumber BIGINT 
		
	IF(@rId = 0)	
	BEGIN		
		--If Exists(select Id from sAlumni.tRegistration where MobileNo = @rMobileNo AND EmailId = @rEmailId)		-- Comment for Mantis : 0034447	
		--	BEGIN
		--	select -103 as Result
		--	RETURN
		--END 
		If Exists(select Id from sAlumni.tRegistration where MobileNo = @rMobileNo)			-- Add for Mantis : 0034447	
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sAlumni.tRegistration where EmailId = @rEmailId)			-- Add for Mantis : 0034447	
			BEGIN
			select -102 as Result
			RETURN
		END 
	END
	 
	IF(@rId = 0)	
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlumni.tRegistration', 0, 1, 1,@outNextNumber = @lNextNumber output
		Print @lNextNumber
		INSERT INTO sAlumni.tRegistration
		(
			Id,FirstName,MiddleName,LastName,GenderId,RegistrationDate ,EmailId,MobileNo,OrgId,PassingBatchId,
			PassingClassId,MappedStudentId,EmployeementTypeId,EmployerName,Designation,EmployeementCountry,
			EmployeementState,EmployeementCity,SpecialAchievement,UniversityName,HigherStudyCountry,HigherStudyState,
			HigherStudyCity,ResidentialCountry,ResidentialState,ResidentialCity,OfficePhone,ResidentialPhone,
			CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
		)
	    VALUES
		(
			@lNextNumber,@rFirstName,@rMiddleName,@rLastName,@rGenderId,@rRegistrationDate,@rEmailId,@rMobileNo,
			@rOrgId,@rPassingBatchId,@rPassingClassId,@rMappedStudentId,@rEmployeementTypeId,@rEmployerName,
			@rDesignation,@rEmployeementCountry,@rEmployeementState,@rEmployeementCity,@rSpecialAchievement,
			@rUniversityName,@rHigherStudyCountry,@rHigherStudyState,@rHigherStudyCity,@rResidentialCountry,
			@rResidentialState,	@rResidentialCity,@rOfficePhone,@rResidentialPhone,@rCreatedUserId,	sCommon.fGetDate() ,
			@rCreatedUserId,sCommon.fGetDate()
		)
	END
	ELSE
	BEGIN
		   UPDATE sAlumni.tRegistration
		   SET Id=@rId,FirstName=@rFirstName,MiddleName=@rMiddleName,LastName=@rLastName,GenderId=@rGenderId ,
		   RegistrationDate=@rRegistrationDate,EmailId=@rEmailId,MobileNo=@rMobileNo,OrgId=@rOrgId,
		   PassingBatchId=@rPassingBatchId,PassingClassId=@rPassingClassId,MappedStudentId=@rMappedStudentId,
		   EmployeementTypeId=@rEmployeementTypeId,EmployerName=@rEmployerName,Designation=@rDesignation,
		   EmployeementCountry=@rEmployeementCountry,EmployeementState=@rEmployeementState,
		   EmployeementCity=@rEmployeementCity,SpecialAchievement=@rSpecialAchievement,UniversityName=@rUniversityName,
		   HigherStudyCountry=@rHigherStudyCountry, HigherStudyState=@rHigherStudyState,HigherStudyCity=@rHigherStudyCity,
		   ResidentialCountry=@rResidentialCountry,ResidentialState=@rResidentialState,ResidentialCity=@rResidentialCity,
		   OfficePhone=@rOfficePhone,ResidentialPhone=@rResidentialPhone,CreatedUserId=@rCreatedUserId,
		   CreatedDateTime=sCommon.fGetDate(),UpdatedUserId=@rCreatedUserId,UpdatedDateTime=sCommon.fGetDate()
		   
	END
		
		
	    SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAlumni].[pRegistrationGet] 
		@rId Bigint =0,
		@rFirstName nvarchar(100) =NULL,
		@rLastName nvarchar(100)=NULL,
		@rMobileNo nvarchar(11)=NULL,
		@rOrgId int=0 ,
		@rOrgGroupId smallint=0,
		@rFromDate date =NULL,
		@rToDate date =NULL
WITH EXECUTE AS CALLER 
AS
SET NOCOUNT ON
BEGIN
	IF  EXISTS (SELECT 1 FROM sAlumni.tRegistration WHERE ID=@rId )
	BEGIN
		Select  R.Id AS[Id],
		ISNULL(R.MappedStudentId,0) AS MappedStudentId,
		R.FirstName +' '+R.MiddleName+' '+R.LastName AS[Name],
		R.FirstName AS[FirstName],
		R.LastName AS[LastName],
		R.PassingBatchId AS[PassingBatchId],
		R.PassingClassId AS[PassingClassId],
		R.OrgId AS[OrgantionId],
		OM.Title AS[OrgantionName],
		BM.Title AS[PassingBatch],
		CM.DisplayTitle AS[PassingClass],
		R.RegistrationDate,
		R.EmailId,
		R.MobileNo,
		ET.Title AS EmployeementType,
		R.EmployerName,
		R.Designation,
		R.EmployeementCountry,
		R.EmployeementState,
		R.EmployeementCity,
		R.SpecialAchievement,
		R.UniversityName,
		R.HigherStudyCountry,
		R.HigherStudyState,
		R.HigherStudyCity,
		R.ResidentialCountry,
		R.ResidentialState,
		R.ResidentialCity,
		R.OfficePhone,
		R.ResidentialPhone,
		ISNULL(S.OrganizationName,'') as Organization,
		ISNULL(S.BatchName,'') as AcademicYear,
		ISNULL(S.Code,'') as IdNo,
		ISNULL(S.ClassName +'-'+ S.DivisionName,'') as ClassDivision		
		From sAlumni.tRegistration R
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=R.PassingClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=R.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.PassingBatchId
		LEFT JOIN sAlumni.tEmployeementType ET ON ET.Id = R.EmployeementTypeId
		LEFT JOIN sStudent.vStudentAcademic S ON S.AcademicId = R.MappedStudentId
		where((R.Id=@rId) OR (@rId=0));
END
	ELSE
		BEGIN
			select  
				R.Id AS[Id],
				ISNULL(R.MappedStudentId,0) AS MappedStudentId,
				R.FirstName +' '+R.MiddleName+' '+R.LastName AS[Name],
				R.FirstName AS[FirstName],
				R.LastName AS[LastName],
				R.PassingBatchId AS[PassingBatchId],
				R.PassingClassId AS[PassingClassId],
				R.OrgId AS[OrgantionId],
				OM.Title AS[OrgantionName],
				BM.Title AS[PassingBatch],
				CM.DisplayTitle AS[PassingClass],
				R.RegistrationDate,
				R.EmailId,
				R.MobileNo,
				ET.Title AS EmployeementType,
				R.EmployerName,
				R.Designation,
				R.EmployeementCountry,
				R.EmployeementState,
				R.EmployeementCity,
				R.SpecialAchievement,
				R.UniversityName,
				R.HigherStudyCountry,
				R.HigherStudyState,
				R.HigherStudyCity,
				R.ResidentialCountry,
				R.ResidentialState,
				R.ResidentialCity,
				R.OfficePhone,
				R.ResidentialPhone,
				ISNULL(S.OrganizationName,'') as Organization,
				ISNULL(S.BatchName,'') as AcademicYear,
				ISNULL(S.Code,'') as IdNo,
				ISNULL(S.ClassName +'-'+ S.DivisionName,'') as ClassDivision
				From sAlumni.tRegistration R
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=R.PassingClassId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=R.OrgId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.PassingBatchId
				LEFT JOIN sAlumni.tEmployeementType ET ON ET.Id = R.EmployeementTypeId
				LEFT JOIN sStudent.vStudentAcademic S ON S.AcademicId = R.MappedStudentId
				Where ((R.FirstName like '%'+@rFirstName+'%') OR (@rFirstName=''))
				AND ((R.LastName like '%'+@rLastName+'%') OR (@rLastName=''))
				AND ((MobileNo=@rMobileNo) OR (@rMobileNo=''))
				AND ((RegistrationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
				AND ((RegistrationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				And ((R.OrgId=@rOrgId) OR (@rOrgId=0))
				AND OM.OrgGroupId=@rOrgGroupId
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAlumni].[pStudentMappingAdd]	 
		  @rSId bigint,
		  @rId bigint,
		  @rOrgId bigint
          

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--	IF(@rSId = 0)	
--		BEGIN		

--			If Exists(select 1 from sAlumni.tRegistration  where  OrgId=@rOrgId)
--				BEGIN
--					select -103 as Result
--				RETURN
--		END 
--	END
--ELSE
--	BEGIN	
--		If  Exists(select 1 from sAlumni.tRegistration  where  OrgId=@rOrgId AND Id<>@rSId)
--			Begin
--				select -103 as Result
--				RETURN
--			End
--	END

IF NOT EXISTS (SELECT 1 FROM sAlumni.tRegistration WHERE MappedStudentId=@rId AND OrgId =@rOrgId )
--IF NOT EXISTS (SELECT 1 FROM sFee.tAccountMapping WHERE FeeSetupId=@rFeeSetupId)		
	BEGIN
		UPDATE sAlumni.tRegistration
		SET MappedStudentId=@rId
		WHERE Id = @rSId	
		SELECT 1 AS Result
	 END
ELSE
	BEGIN
		Begin
			select -102 as Result
			RETURN
		End 
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAlumni].[pStudentMappingGet] 
	
	@rOrgId int =0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF  EXISTS (SELECT 1 FROM sAlumni.tRegistration  WHERE MappedStudentId <> 0 )
	BEGIN
		Select  R.Id AS[Id],
		FirstName +' '+MiddleName+' '+LastName AS[Name],
		R.FirstName AS[FirstName],
		R.LastName AS[LastName],
		R.PassingBatchId AS[PassingBatchId],
		R.PassingClassId AS[PassingClassId],
		R.OrgId AS[OrgantionId],
		OM.Title AS[OrgantionName],
		BM.Title AS[PassingBatch],
		CM.DisplayTitle AS[PassingClass],
		R.MappedStudentId
		From sAlumni.tRegistration R
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=R.PassingClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=R.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.PassingBatchId
		 WHERE MappedStudentId <> 0
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



--exec sAppraisal.pAppraisalStatusGet @rAppraisalTypeId=148800008,@rOrgGroupDeptId=0,@rDepartmentId=0,@rGradeId=0,@rDesignationId=0,@rEmployeeTypeId=0,@rEmployeeGroupId=0,@rGenderId=0,@rStatusId=7,@rEmpCode=N'T-HMEC-098',@rOrgId=N'1488'
--go
CREATE OR ALTER PROCEDURE [sAppraisal].[pAppraisalStatusGet]  
   
 @rOrgGroupDeptId int,  
 @rAppraisalTypeId int,   
 @rDepartmentId int,  
 @rGradeId int,  
 @rDesignationId int,  
 @rEmployeeTypeId int,  
 @rEmployeeGroupId smallint,  
 @rGenderId smallint,  
 @rStatusId smallint,  
 @rEmpCode nvarchar(10),  
 @rOrgId smallint  
   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
     
  SELECT  
     DISTINCT EM.Id AS EmployeeId,  
     EM.Code AS EmpCode,  
     EM.Number As Number,  
     ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS EmployeeName,  
     ECD.DepartmentName AS EmpDept,  
     CASE WHEN ISNULL(ERD.MyRating,0) > 0 THEN 'Completed' ELSE 'Pending' END AS EmployeeStatus,  
     ISNULL(EM1.FirstName + ' ' + EM1.LastName,'') AS EmpManagerName,  
     CASE WHEN ISNULL(ERD.ManagerRating,0) > 0 THEN 'Completed' ELSE 'Pending' END AS EmpManagerRatingStatus,  
     ISNULL(EM2.FirstName + ' ' + EM2.LastName,'') AS EmpBusinessHeadName,  
     CASE WHEN ISNULL(KER.BusinessHeadRating,0) > 0 THEN 'Completed' ELSE 'Pending' END AS EmpBusinessHeadRatingStatus  
  FROM  
     sHrm.tEmployeeMaster EM  
     INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = EM.Id   
     INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id  
     LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = EJD.EmployeeManagerId  
     LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = EJD.EmployeeBusinessHeadId  
     INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId  
     LEFT JOIN sHrm.tEmployeeMaster EM3 ON EM3.Id = OM.EmployeeId  
     LEFT JOIN sAppraisal.tKPAEmployee KPA ON KPA.EmployeeId=EM.Id   
     LEFT JOIN sAppraisal.tKPAEmployeeDetail KPAD ON KPAD.KPAEmployeeId=KPA.Id   
     LEFT JOIN sAppraisal.tKPATypeMaster KTM ON KTM.Id = KPAD.KPATypeId  
     LEFT JOIN sAppraisal.tKPAEmployeeRating KER ON KER.KPAEmployeeId=KPA.Id  
     LEFT JOIN sAppraisal.tKPAEmployeeRatingDetail ERD ON ERD.KPAEmployeeRatingId = KER.Id AND ERD.KPAEmployeeDetailId =  KPAD.Id  
     LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.OrgGroupId = OM.OrgGroupId AND  ((OGDM.Id = @rOrgGroupDeptId) OR (@rOrgGroupDeptId = 0))  
  WHERE  
     ((EM.Code = @rEmpCode) OR (@rEmpCode = ''))   
     AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)  
     AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)  
     AND (ECD.EmployeeStatusId = @rStatusId OR @rStatusId = 0)  
     AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)  
     AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)  
     AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)        
     AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)   
     AND (OM.Id = @rOrgId)  
	 AND KER.AppraisalTypeId = @rAppraisalTypeId  
      
  ORDER BY  
     EM.Number  
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pAppraisalTypeMasterAdd]
** Desc:  Create and Update Data in Loan [tAppraisalTypeMaster]
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/AppraisalTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
--EXEC [sAppraisal].[pAppraisalTypeMasterAdd] 0,1001,3333,1001000000009
CREATE OR ALTER PROCEDURE [sAppraisal].[pAppraisalTypeMasterAdd]
	    @rId int,
		@rTitle nvarchar(200),
		@rRemark nvarchar(1000),
		@rValidFrom DATE,
		@rValidTo DATE,
		@rOrgId SmallINT,
		@rBatchId int,
		@rIsObsolete bit =null,
        @rCreatedUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		IF(@rId = 0)	
			BEGIN
				IF Exists(SELECT Id FROM [sAppraisal].[tAppraisalTypeMaster] WHERE Title=@rTitle AND BatchId=@rBatchId )
					BEGIN
						SELECT -101 as Result
						RETURN
					END 
				
			END
		
		ELSE
			BEGIN
				IF  Exists(SELECT Id FROM [sAppraisal].[tAppraisalTypeMaster] WHERE Title=@rTitle AND BatchId=@rBatchId AND Id<>@rId )
					BEGIN
						SELECT -101 as Result
						RETURN
					END
			END
	
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
	
		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tAppraisalTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sAppraisal].[tAppraisalTypeMaster]
				(
					Id,
					Title,
					Remark,
					ValidFrom,
					ValidTo,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					BatchId
				)
				VALUES
				(
					@lNextNumber,
					@rTitle,
					@rRemark,
					@rValidFrom,
					@rValidTo,
					0,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rBatchId
				)
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sAppraisal].[tAppraisalTypeMaster]
				SET
				Title=@rTitle,
				Remark=@rRemark,
				ValidFrom=@rValidFrom,
				ValidTo=@rValidTo,
				IsObsolete=@rIsObsolete,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
				WHERE Id = @rId
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pAppraisalTypeMasterAdd]
** Desc:  Create and Update Data in Loan [tAppraisalTypeMaster]
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/AppraisalTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
--EXEC [sAppraisal].[pAppraisalTypeMasterGet] '',0,1001,1001
CREATE OR ALTER PROCEDURE [sAppraisal].[pAppraisalTypeMasterGet]
	@rTitle VARCHAR(250),
	@rBatchId int,
	@rOrgId smallint,
	@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	SET @rBatchId= CASE WHEN @rBatchId=-1 THEN 0 ELSE @rBatchId END
	SELECT 
		ATM.Id
		,ATM.Title
		,ATM.Remark
		,CONVERT(VARCHAR,ATM.ValidFrom,107)ValidFromDate
		,CONVERT(VARCHAR,ATM.ValidTo,107)ValidToDate
		,CONVERT(VARCHAR,ATM.ValidFrom,103)ValidFrom
		,CONVERT(VARCHAR,ATM.ValidTo,103)ValidTo
		,ATM.BatchId
		,BMS.Title AS BatchName
		,BMS.OrgId
		,ATM.IsObsolete
		,CASE ATM.[IsObsolete] WHEN 0 THEN 'N' ELSE 'Y' END AS InActive
	FROM 
		[sAppraisal].[tAppraisalTypeMaster] AS ATM
		LEFT JOIN [sSetup].[tBatchMaster]   AS BMS ON BMS.Id=ATM.BatchId
		LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG On ORG.Id=BMS.OrgId 

	WHERE		ORG.OrgGroupId=@rOrgGroupId
			AND ((BMS.OrgId=@rOrgId)       OR (@rOrgId=0))
			AND ((ATM.BatchId=@rBatchId)   OR (@rBatchId=0))
			AND ((ATM.Title LIKE @rTitle)  OR (@rTitle='')) 
	Order BY ATM.CreatedDateTime DESC, ATM.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeRatingStatusChange]
** Desc:  Employee Rating Status SET
** Auth:  Savan Vaghela
** Date:  24-March-2017
** Page:  /Pages/Hrm/Appraisal/BusinessHeadRatings.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    24-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pKPAEmployeeRatingStatusChange] 1001000000172,100100114,100100042,3,'7,8,9,10,11,12,','1,1,1,1,1,1,','a,b,c,d,e,f'
CREATE OR ALTER PROCEDURE [sAppraisal].[pBHRatingStatusChange]
	   @rKPAEmployeeRatingId BIGINT,
	   @rBusinessHeadRating DECIMAL(5,2),
	   @rBusinessHeadRecommendationIncrement DECIMAL(5,2),
	   @rBusinessHeadRecommendationDesignation nvarchar(200),
	   @rBusinessHeadId BIGINT = null,
	   @rAppraisalTypeId INT=null
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
		BEGIN TRANSACTION	
			BEGIN
				UPDATE [sAppraisal].[tKPAEmployeeRating] 
				SET 
					BusinessHeadRating=@rBusinessHeadRating
					,BusinessHeadRecommendationIncrement=@rBusinessHeadRecommendationIncrement
					,BusinessHeadRecommendationDesignation=@rBusinessHeadRecommendationDesignation
					,RatingStatusId=5 
				WHERE ID =@rKPAEmployeeRatingId	


				IF NOT EXISTS(
						SELECT BusinessHeadId 
						FROM [sAppraisal].[tBusinessHeadsRatingStatus] 
						WHERE BusinessHeadId=@rBusinessHeadId AND AppraisalTypeId=@rAppraisalTypeId)
					BEGIN
						INSERT INTO [sAppraisal].[tBusinessHeadsRatingStatus] 
						(
							BusinessHeadId
							,AppraisalTypeId
							,BHRatingStatusId
						)
						VALUES 
						(
							@rBusinessHeadId
							,@rAppraisalTypeId
							,1
						)
					END



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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeGet]
** Desc:  Get Employee details for Business Head Ratting Status
** Auth:  Savan Vaghela
** Date:  24-March-2017
** Page:  /Pages/Hrm/Appraisal/SetKPAForTeam.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    24-March-2017      Savan Vaghela       
************************************************************/

--[sAppraisal].[pBusinessHeadRatingsStatusGet] 0,100100114,1001,1001,100100063
CREATE OR ALTER PROCEDURE [sAppraisal].[pBusinessHeadRatingsStatusGet]
	@rEmployeeManagerId           BIGINT,
	@rBatchId					  INT,
	@rOrgId						  SMALLINT,
	@rOrgGroupId				  SMALLINT,
	@rAppraisalTypeId			  INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	 SELECT 
		 EMP.Id
		,EMP.Code
		,ISNULL(EMP.FirstName,'') +' '+ ISNULL(EMP.LastName,'') AS Employee
		,ISNULL(DEG.Id,'') AS DesignationId
		,ISNULL(DEG.Title,'') AS DesignationName
		,ManagerRat.ManagerRating
		,KER.RecommendationDesignation AS PromotionRecommend
		,CONVERT(NVARCHAR(50),KER.RecommendationIncrement) +' %' AS ManagerRecommend
		,KER.BusinessHeadRating AS BHRating
		,CONVERT(NVARCHAR(20),KER.BusinessHeadRecommendationIncrement)+' %' AS BHRecommend
		,KER.BusinessHeadRecommendationDesignation AS BHPromotionRecommend
		,KER.Id AS KPAEmployeeRatingId
		,KER.RatingStatusId
		,CASE WHEN KER.RatingStatusId=4 THEN  CONVERT(BIT,1) ELSE CONVERT(BIT,0) END AS Enabled
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE ID =ISNULL(KER.RatingStatusId,1))  AS RatingStatus
	FROM [sHrm].[tEmployeeMaster]  AS EMP
		LEFT JOIN [sHrm].[tEmployeeJobDetail]			AS EJD ON EJD.EmployeeId=EMP.Id
		LEFT JOIN [sHrm].[tEmployeeMaster]				AS EMD ON EMD.Id= EJD.EmployeeManagerId
		LEFT JOIN [sSetup].[tOrganizationMaster]		AS ORG ON Org.id=EMP.OrgID
		LEFT JOIN [sHrm].[tEmployeeDesignationMaster]   AS DEG ON DEG.Id=EJD.EmployeeDesignationId
		LEFT JOIN [sAppraisal].[tKPAEmployee]			AS KPA ON KPA.EmployeeId=EMP.Id
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating]		AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN 
					(
						SELECT KER.KPAEmployeeId,KRD.KPAEmployeeRatingId,CONVERT(DECIMAL(18,2),AVG(KRD.ManagerRating))ManagerRating 
						FROM [sAppraisal].[tKPAEmployeeRating]             AS KER
						INNER JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS KRD ON KRD.KPAEmployeeRatingId=KER.Id
						GROUP BY KER.KPAEmployeeId,KRD.KPAEmployeeRatingId
					) AS ManagerRat ON ManagerRat.KPAEmployeeId=KPA.Id AND ManagerRat.KPAEmployeeRatingId=KER.Id


	WHERE
		ORG.OrgGroupId=@rOrgGroupId 
		AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		AND	EJD.EmployeeBusinessHeadId=@rEmployeeManagerId 
		AND Emp.ID<>@rEmployeeManagerId 
		AND EMP.StatusId=7
		AND KPA.BatchId=@rBatchId
		AND KER.AppraisalTypeId=@rAppraisalTypeId
		--AND KER.RatingStatusId>=4
		AND ISNULL(EMP.IsOtherUser,0) = 0 
		AND ISNULL(EMD.IsOtherUser,0) = 0 
	Order by EMP.FirstName, EMP.Code





	DECLARE @ManagerRat TABLE (ManagerRating DECIMAL(18,2))
	INSERT INTO @ManagerRat 

	SELECT  ManagerRat.ManagerRating
	FROM [sHrm].[tEmployeeMaster]  AS EMP
		LEFT JOIN [sHrm].[tEmployeeJobDetail]			AS EJD ON EJD.EmployeeId=EMP.Id
		LEFT JOIN [sHrm].[tEmployeeMaster]				AS EMD ON EMD.Id= EJD.EmployeeManagerId
		LEFT JOIN [sSetup].[tOrganizationMaster]		AS ORG ON Org.id=EMP.OrgID
		LEFT JOIN [sHrm].[tEmployeeDesignationMaster]   AS DEG ON DEG.Id=EJD.EmployeeDesignationId
		LEFT JOIN [sAppraisal].[tKPAEmployee]			AS KPA ON KPA.EmployeeId=EMP.Id
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating]		AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN 
					(
						SELECT KER.KPAEmployeeId,KRD.KPAEmployeeRatingId,CONVERT(DECIMAL(18,2),AVG(KRD.ManagerRating))ManagerRating 
						FROM [sAppraisal].[tKPAEmployeeRating]             AS KER
						INNER JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS KRD ON KRD.KPAEmployeeRatingId=KER.Id
						GROUP BY KER.KPAEmployeeId,KRD.KPAEmployeeRatingId
					) AS ManagerRat ON ManagerRat.KPAEmployeeId=KPA.Id AND ManagerRat.KPAEmployeeRatingId=KER.Id



	WHERE
		ORG.OrgGroupId=@rOrgGroupId 
		AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		AND	EJD.EmployeeBusinessHeadId=@rEmployeeManagerId 
		AND Emp.ID<>@rEmployeeManagerId 
		AND EMP.StatusId=7
		AND KPA.BatchId=@rBatchId
		AND KER.AppraisalTypeId=@rAppraisalTypeId
		AND KER.RatingStatusId>=4
		AND ISNULL(EMD.IsOtherUser,0) = 0 
		AND ISNULL(EMP.IsOtherUser,0) = 0 
	--GROUP BY ManagerRat.ManagerRating
	





	
	
	
	
	SELECT 1 AS Rank,'5%'  AS Per,1 AS Normal,COUNT(0)Actual FROM @ManagerRat WHERE ManagerRating>4 UNION ALL
	SELECT 2 AS Rank,'15%' AS Per,1 AS Normal,COUNT(0)Actual FROM @ManagerRat WHERE ManagerRating<=4 AND ManagerRating>3 UNION ALL
	SELECT 3 AS Rank,'60%' AS Per,2 AS Normal,COUNT(0)Actual FROM @ManagerRat WHERE ManagerRating<=3 AND ManagerRating>2 UNION ALL
	SELECT 4 AS Rank,'15%' AS Per,1 AS Normal,COUNT(0)Actual FROM @ManagerRat WHERE ManagerRating<=2 AND ManagerRating>1 UNION ALL
	SELECT 5 AS Rank,'5%'  AS Per,1 AS Normal,COUNT(0)Actual FROM @ManagerRat WHERE ManagerRating<=1 AND ManagerRating>0 


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  30-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    30-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductTypeMasterAdd]
CREATE OR ALTER PROCEDURE [sAppraisal].[pBusinessHeadRatingStatusChange]
	  	@rBusinessHeadsId			  BIGINT,
		@rBHRatingStatusId            SMALLINT,
		@rEmployeeBusinessHeadId      BIGINT,
		@rAppraisalTypeId			  INT,
		@rBatchId					  INT,
		@rOrgId						  SMALLINT,
		@rOrgGroupId				  SMALLINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			IF (@rBHRatingStatusId=3)
				BEGIN
					DECLARE @rTotalEmployee INT = 0
					DECLARE @AwaitingApprovalBH  INT=0

					SELECT @AwaitingApprovalBH=COUNT(0)
					FROM [sAppraisal].[tKPAEmployee] AS KPA
					LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
					WHERe KPA.BatchId=@rBatchId 
					AND KER.AppraisalTypeId=@rAppraisalTypeId
					AND KER.RatingStatusId>=5
					AND  KPA.EmployeeId in 
					(
						SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
						INNER JOIN [sHrm].[tEmployeeJobDetail]         AS EJD On EJD.EmployeeId=EMP.Id
						LEFT  JOIN [sSetup].[tOrganizationMaster]      AS ORG ON Org.id=EMP.OrgID	
						WHERE ORG.OrgGroupId=@rOrgGroupId	
						AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
						AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
						AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
						AND ISNULL(EMP.IsOtherUser,0) = 0 

					)
					SELECT @rTotalEmployee=COUNT(0)
					FROM [sAppraisal].[tKPAEmployee] AS KPA
					LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
					WHERe KPA.BatchId=@rBatchId 
					AND KER.AppraisalTypeId=@rAppraisalTypeId
					AND  KPA.EmployeeId in 
					(
						SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
						INNER JOIN [sHrm].[tEmployeeJobDetail]         AS EJD On EJD.EmployeeId=EMP.Id
						LEFT  JOIN [sSetup].[tOrganizationMaster]      AS ORG ON Org.id=EMP.OrgID	
						WHERE ORG.OrgGroupId=@rOrgGroupId	
						AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
						AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
						AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
						AND ISNULL(EMP.IsOtherUser,0) = 0 
					)

					IF (@AwaitingApprovalBH>0)
						BEGIN
							IF (@AwaitingApprovalBH=@rTotalEmployee)
								BEGIN
									UPDATE [sAppraisal].[tBusinessHeadsRatingStatus]		
									SET 
										BHRatingStatusId=@rBHRatingStatusId 
									WHERE 
										Id=@rBusinessHeadsId
								END
						END

		
					UPDATE [sAppraisal].[tKPAEmployeeRating] 
					SET RatingStatusId=6
					WHERE 
					RatingStatusId=5  
					AND AppraisalTypeId=@rAppraisalTypeId
					AND  KPAEmployeeId IN
					(
						SELECT 
						KER.KPAEmployeeId
						FROM [sAppraisal].[tKPAEmployee] AS KPA
						LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
						WHERe KPA.BatchId=@rBatchId 
						AND KER.AppraisalTypeId=@rAppraisalTypeId AND KER.RatingStatusId=5
						AND  KPA.EmployeeId in 
						(
							SELECT EMP.Id	
							FROM [sHrm].[tEmployeeMaster]            AS EMP 
							INNER JOIN [sHrm].[tEmployeeJobDetail]   AS EJD On EJD.EmployeeId=EMP.Id
							LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID	
							WHERE ORG.OrgGroupId=@rOrgGroupId	
							AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
							AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
							AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
							AND ISNULL(EMP.IsOtherUser,0) = 0 
						)
					)
				END
			ELSE
			BEGIN
				UPDATE [sAppraisal].[tBusinessHeadsRatingStatus]		
					SET 
						BHRatingStatusId=@rBHRatingStatusId 
					WHERE 
						Id=@rBusinessHeadsId
			END

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAppraisal].[pBusinessHeadsRatingStatusBHWiseGet]
	
	@rEmployeeBusinessHeadId      BIGINT,
	@rBatchId					  INT,
	@rOrgId						  SMALLINT,
	@rOrgGroupId				  SMALLINT,
	@rAppraisalTypeId			  INT,
	@rUserFullName				  nVARCHAR(100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @rTotalEmployee INT = 0
	DECLARE @rTotalKPAEmployee INT = 0
	DECLARE @AvgRating DECIMAL(10,2)=0
	DECLARE @AvgIncrement DECIMAL(10,2)=0	
	DECLARE @AvgPromotions INT=0
	DECLARE @AwaitingApprovalBH  INT=0
	
	--DECLARE @OrgIncharge BIGINT
	--SELECT @OrgIncharge = EmployeeId From sSetup.tOrganizationMaster Where Id = @rOrgId
	
	--If(@OrgIncharge = @rEmployeeBusinessHeadId) SET @rEmployeeBusinessHeadId = 0

		SELECT 
		@AvgRating=ISNULL(AVG(BusinessHeadRating),0)
		,@AvgIncrement=ISNULL(AVG(BusinessHeadRecommendationIncrement),0) 
		FROM [sAppraisal].[tKPAEmployee] AS KPA
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
		WHERE KPA.BatchId=@rBatchId 
		AND KER.AppraisalTypeId=@rAppraisalTypeId AND KER.RatingStatusId>=5
		AND  KPA.EmployeeId in 
		(
			SELECT EMP.Id	
			FROM [sHrm].[tEmployeeMaster]            AS EMP 
			INNER JOIN [sHrm].[tEmployeeJobDetail]   AS EJD On EJD.EmployeeId=EMP.Id
			LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID	
			WHERE ORG.OrgGroupId=@rOrgGroupId	
			AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
			AND	((EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId) OR (@rEmployeeBusinessHeadId = 0)) 		
			AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
			AND ISNULL(EMP.IsOtherUser,0) = 0 
		)

		SELECT @AvgPromotions=ISNULL(COUNT(1),0) 
		FROM [sAppraisal].[tKPAEmployee]			AS KPA
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
		WHERe KPA.BatchId=@rBatchId 
		AND KER.AppraisalTypeId=@rAppraisalTypeId AND KER.RatingStatusId>=5
		AND LEN(RTRIM(LTRIM(KER.BusinessHeadRecommendationDesignation)))>=4
		AND  KPA.EmployeeId in 
		(
			SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
			INNER JOIN [sHrm].[tEmployeeJobDetail]		   AS EJD On EJD.EmployeeId=EMP.Id
			LEFT  JOIN [sSetup].[tOrganizationMaster]	   AS ORG ON Org.id=EMP.OrgID	
			WHERE ORG.OrgGroupId=@rOrgGroupId	
			AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
			AND	((EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId) OR (@rEmployeeBusinessHeadId = 0))		
			AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
			AND ISNULL(EMP.IsOtherUser,0) = 0 
		)

		IF EXISTS (
					SELECT KER.Id FROM [sAppraisal].[tKPAEmployee] AS KPA
					LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
					WHERe KPA.BatchId=@rBatchId 
					AND KER.AppraisalTypeId=@rAppraisalTypeId AND  KPA.EmployeeId in (SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
					INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD On EJD.EmployeeId=EMP.Id
					LEFT  JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID	
					WHERE ORG.OrgGroupId=@rOrgGroupId	
					AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
					AND	((EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId) OR (@rEmployeeBusinessHeadId = 0))		
					AND Emp.ID<>@rEmployeeBusinessHeadId 		
					AND EMP.StatusId=7 AND ISNULL(EMP.IsOtherUser,0) = 0 )
				  )
		
			BEGIN
				SELECT @AwaitingApprovalBH=COUNT(0)
				FROM [sAppraisal].[tKPAEmployee] AS KPA
				LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
				WHERe KPA.BatchId=@rBatchId 
				AND KER.AppraisalTypeId=@rAppraisalTypeId
				AND KER.RatingStatusId>=5
				AND  KPA.EmployeeId IN 
				(
					SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
					INNER JOIN [sHrm].[tEmployeeJobDetail]         AS EJD On EJD.EmployeeId=EMP.Id
					LEFT  JOIN [sSetup].[tOrganizationMaster]      AS ORG ON Org.id=EMP.OrgID	
					WHERE ORG.OrgGroupId=@rOrgGroupId	
					AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
					AND	((EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId) OR (@rEmployeeBusinessHeadId = 0))			
					AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
					AND ISNULL(EMP.IsOtherUser,0) = 0 
				)
				SELECT @rTotalEmployee=COUNT(0)
				FROM [sAppraisal].[tKPAEmployee] AS KPA
				LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
				WHERe KPA.BatchId=@rBatchId 
				AND KER.AppraisalTypeId=@rAppraisalTypeId
				AND  KPA.EmployeeId IN 
				(
					SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
					INNER JOIN [sHrm].[tEmployeeJobDetail]         AS EJD On EJD.EmployeeId=EMP.Id
					LEFT  JOIN [sSetup].[tOrganizationMaster]      AS ORG ON Org.id=EMP.OrgID	
					WHERE ORG.OrgGroupId=@rOrgGroupId	
					AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
					AND	((EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId) OR (@rEmployeeBusinessHeadId = 0))			
					AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
					AND ISNULL(EMP.IsOtherUser,0) = 0 
				)
			END


		SELECT 
		BHS.Id																		  AS Id
		,CASE WHEN @rEmployeeBusinessHeadId != 0 THEN @rUserFullName 
		ELSE EM.FirstName                   END                                       AS UserName
		,@AvgRating														 	          AS AvgRating
		,@AvgIncrement													 	          AS AvgIncrement
		,@AvgPromotions													   	          AS AvgPromotions
		
		,CASE 
			WHEN (BHS.BHRatingStatusId=4) THEN 4
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH<>@rTotalEmployee)) THEN 1
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId<>3)) THEN 2
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId=3)) THEN 3
			ELSE 1	END	  
		AS BHRatingStatusId
		
		,CASE
			WHEN (BHS.BHRatingStatusId=4) THEN 'Rejected'  
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH<>@rTotalEmployee)) THEN 'Not Confirmed yet' 
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND  (BHS.BHRatingStatusId<>3)) THEN 'Completed, Awaiting your approval' 
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId=3)) THEN 'Completed & Approved' 
			ELSE 'Not Applicable Right Now'	END	  
		AS Title

		,CASE WHEN  (@AwaitingApprovalBH>0 AND  @AwaitingApprovalBH<>@rTotalEmployee) THEN 1 ELSE 0 END              AS  RatingStatus 
		,CASE WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId=3)) THEN CONVERT(BIT,0) ELSE CONVERT(BIT,1) END AS  Enabled 
		from [sAppraisal].[tBusinessHeadsRatingStatus] AS BHS
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = BHS.BusinessHeadId
		LEFT JOIN  [sAppraisal].[tBHRatingStatus] AS BRS ON BRS.Id =BHS.BHRatingStatusId
		WHERE ((BHS.BusinessHeadId=@rEmployeeBusinessHeadId) OR (@rEmployeeBusinessHeadId = 0))	
		AND AppraisalTypeId=@rAppraisalTypeId
		AND ISNULL(EM.IsOtherUser,0) = 0 

	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeGet]
** Desc:  Get Employee details for set KPA Details
** Auth:  Savan Vaghela
** Date:  29-March-2017
** Page:  /Pages/Hrm/Appraisal/RatingStatusofBusinessHead.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    29-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pBusinessHeadsRatingStatusGet] 0,100100114,1001,1001,100100067,'Admin'
CREATE OR ALTER PROCEDURE [sAppraisal].[pBusinessHeadsRatingStatusGet]
	@rEmployeeBusinessHeadId      BIGINT,
	@rBatchId					  INT,
	@rOrgId						  SMALLINT,
	@rOrgGroupId				  SMALLINT,
	@rAppraisalTypeId			  INT,
	@rUserFullName				  nVARCHAR(100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @rTotalEmployee INT = 0
	DECLARE @rTotalKPAEmployee INT = 0
	DECLARE @AvgRating DECIMAL(10,2)=0
	DECLARE @AvgIncrement DECIMAL(10,2)=0
	DECLARE @AvgPromotions INT=0
	DECLARE @AwaitingApprovalBH  INT=0
	
 --   DECLARE @OrgIncharge BIGINT
	--SELECT @OrgIncharge = EmployeeId From sSetup.tOrganizationMaster Where Id = @rOrgId
	
	--If(@OrgIncharge = @rEmployeeBusinessHeadId) SET @rEmployeeBusinessHeadId = 0

	--If(@rEmployeeBusinessHeadId != 0)
	BEGIN

		SELECT 
		@AvgRating=ISNULL(AVG(BusinessHeadRating),0)
		,@AvgIncrement=ISNULL(AVG(BusinessHeadRecommendationIncrement),0) 
		FROM [sAppraisal].[tKPAEmployee] AS KPA
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
		WHERE KPA.BatchId=@rBatchId 
		AND KER.AppraisalTypeId=@rAppraisalTypeId AND KER.RatingStatusId>=5
		AND  KPA.EmployeeId in 
		(
			SELECT EMP.Id	
			FROM [sHrm].[tEmployeeMaster]            AS EMP 
			INNER JOIN [sHrm].[tEmployeeJobDetail]   AS EJD On EJD.EmployeeId=EMP.Id
			LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID	
			WHERE ORG.OrgGroupId=@rOrgGroupId	
			AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
			AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
			AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
			AND ISNULL(EMP.IsOtherUser,0) = 0 
		)

		SELECT @AvgPromotions=ISNULL(COUNT(1),0) 
		FROM [sAppraisal].[tKPAEmployee]			AS KPA
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
		WHERe KPA.BatchId=@rBatchId 
		AND KER.AppraisalTypeId=@rAppraisalTypeId AND KER.RatingStatusId>=5
		AND LEN(RTRIM(LTRIM(KER.BusinessHeadRecommendationDesignation)))>=4
		AND  KPA.EmployeeId in 
		(
			SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
			INNER JOIN [sHrm].[tEmployeeJobDetail]		   AS EJD On EJD.EmployeeId=EMP.Id
			LEFT  JOIN [sSetup].[tOrganizationMaster]	   AS ORG ON Org.id=EMP.OrgID	
			WHERE ORG.OrgGroupId=@rOrgGroupId	
			AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
			AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
			AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
			AND ISNULL(EMP.IsOtherUser,0) = 0 
		)

		IF EXISTS (
					SELECT KER.Id FROM [sAppraisal].[tKPAEmployee] AS KPA
					LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
					WHERe KPA.BatchId=@rBatchId 
					AND KER.AppraisalTypeId=@rAppraisalTypeId AND  KPA.EmployeeId in (SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
					INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD On EJD.EmployeeId=EMP.Id
					LEFT  JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID	
					WHERE ORG.OrgGroupId=@rOrgGroupId	
					AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
					AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
					AND Emp.ID<>@rEmployeeBusinessHeadId 		
					AND EMP.StatusId=7 AND ISNULL(EMP.IsOtherUser,0) = 0 )
				  )
		
			BEGIN
				SELECT @AwaitingApprovalBH=COUNT(0)
				FROM [sAppraisal].[tKPAEmployee] AS KPA
				LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
				WHERe KPA.BatchId=@rBatchId 
				AND KER.AppraisalTypeId=@rAppraisalTypeId
				AND KER.RatingStatusId>=5
				AND  KPA.EmployeeId IN 
				(
					SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
					INNER JOIN [sHrm].[tEmployeeJobDetail]         AS EJD On EJD.EmployeeId=EMP.Id
					LEFT  JOIN [sSetup].[tOrganizationMaster]      AS ORG ON Org.id=EMP.OrgID	
					WHERE ORG.OrgGroupId=@rOrgGroupId	
					AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
					AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
					AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
					AND ISNULL(EMP.IsOtherUser,0) = 0 
				)
				SELECT @rTotalEmployee=COUNT(0)
				FROM [sAppraisal].[tKPAEmployee] AS KPA
				LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
				WHERe KPA.BatchId=@rBatchId 
				AND KER.AppraisalTypeId=@rAppraisalTypeId
				AND  KPA.EmployeeId IN 
				(
					SELECT EMP.Id	FROM [sHrm].[tEmployeeMaster]  AS EMP 
					INNER JOIN [sHrm].[tEmployeeJobDetail]         AS EJD On EJD.EmployeeId=EMP.Id
					LEFT  JOIN [sSetup].[tOrganizationMaster]      AS ORG ON Org.id=EMP.OrgID	
					WHERE ORG.OrgGroupId=@rOrgGroupId	
					AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0)) 
					AND	EJD.EmployeeBusinessHeadId=@rEmployeeBusinessHeadId 		
					AND Emp.ID<>@rEmployeeBusinessHeadId AND EMP.StatusId=7
					AND ISNULL(EMP.IsOtherUser,0) = 0 
				)
			END


		SELECT 
		BHS.Id																		  AS Id
		,@rUserFullName                                                               AS UserName
		,@AvgRating														 	          AS AvgRating
		,@AvgIncrement													 	          AS AvgIncrement
		,@AvgPromotions													   	          AS AvgPromotions
		
		,CASE 
			WHEN (BHS.BHRatingStatusId=4) THEN 4
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH<>@rTotalEmployee)) THEN 1
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId<>3)) THEN 2
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId=3)) THEN 3
			ELSE 1	END	  
		AS BHRatingStatusId
		
		,CASE
			WHEN (BHS.BHRatingStatusId=4) THEN 'Rejected'  
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH<>@rTotalEmployee)) THEN 'Not Confirmed yet' 
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND  (BHS.BHRatingStatusId<>3)) THEN 'Completed, Awaiting your approval' 
			WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId=3)) THEN 'Completed & Approved' 
			ELSE 'Not Applicable Right Now'	END	  
		AS Title

		,CASE WHEN  (@AwaitingApprovalBH>0 AND  @AwaitingApprovalBH<>@rTotalEmployee) THEN 1 ELSE 0 END              AS  RatingStatus 
		,CASE WHEN ((@AwaitingApprovalBH>0)  AND  (@AwaitingApprovalBH=@rTotalEmployee) AND (BHS.BHRatingStatusId=3)) THEN CONVERT(BIT,0) ELSE CONVERT(BIT,1) END AS  Enabled 
		from [sAppraisal].[tBusinessHeadsRatingStatus] AS BHS
		LEFT JOIN  [sAppraisal].[tBHRatingStatus] AS BRS ON BRS.Id =BHS.BHRatingStatusId
		WHERE BHS.BusinessHeadId=@rEmployeeBusinessHeadId AND AppraisalTypeId=@rAppraisalTypeId

  END
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  08-March-2017
** Page:  /Pages/Hrm/Appraisal/ConductTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    08-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductAdd]
CREATE OR ALTER PROCEDURE [sAppraisal].[pConductAdd]
	    @rId BIGINT,
		@rConductDate DATETIME,
		@rEmployeeId BIGINT,
		@rConductTypeId INT,
		@rBatchId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(400),
		@rOrgId SmallINT,
		@rOrgGroupId SmallINT,
		@rCreatedUserId BIGINT		       
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		--IF(@rId = 0)	
		--	BEGIN
		--		IF Exists(SELECT Id FROM [sAppraisal].[tConductTypeMaster]  WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId )
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END 
		--	END
		
		--ELSE
		--	BEGIN
		--		IF  Exists(SELECT Id FROM [sAppraisal].[tConductTypeMaster]  WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId )
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END
		--	END
	
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
	
		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tConduct', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sAppraisal].[tConduct]
				(
					Id,
					ConductDate,
					EmployeeId,
					ConductTypeId,
					Title,
					Remark,
					BatchId,
					CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rConductDate,
					@rEmployeeId,
					@rConductTypeId,
					@rTitle,
					@rRemark,
					@rBatchId,
					@rCreatedUserId,
					sCommon.fGetDate()
					
				)
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sAppraisal].[tConduct]
				SET
					Title=@rTitle,
					Remark=@rRemark,
					ConductDate=@rConductDate, 
					ConductTypeId = @rConductTypeId -- Added field ConductTypeId for mantis 30032 
					
				WHERE Id = @rId
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[ptLoanDetailGet]   
** Desc:  Employee Loan Detail 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/IncomeTaxChallan.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/
--EXEC [sAppraisal].[pConductGet] 0,0,'',null,null,-1
CREATE OR ALTER PROCEDURE [sAppraisal].[pConductGet]
	@rId BIGINT, 
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rTitle VARCHAR(50)='',
	@rFromDate datetime ,
	@rToDate datetime ,
	@rConductTypeId INT,
	@rEmployeeId BIGINT=null,
	@rBatchId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
		CND.Id
		,CND.ConductDate
		,CONVERT(VARCHAR(20),CND.ConductDate,105) AS ConductDateJSON
		,CND.EmployeeId
		,EMP.Code AS EmpCode
		,ISNULL(EMP.FirstName,'') +' '+ ISNULL(EMP.LastName,'') AS EmpName
		,CND.ConductTypeId
		,CTM.Title AS ConductType
		,CND.Title
		,CND.Remark 
		,EMP.[OrgID]
		,OMD.Title AS 'OrgName'
		,DEP.title AS 'EmpDept'
		,USR.DisplayTitle
		,CND.CreatedDateTime
		,CONVERT(VARCHAR(20),CND.CreatedDateTime,105) AS CreatedDateTimeJSON
		,CTM.ConductIndicatorId
		,CIM.Title AS ConductIndicator
	FROM [sAppraisal].[tConduct] AS CND
		INNER JOIN [sAppraisal].[tConductTypeMaster]       AS CTM ON CTM.Id=CND.ConductTypeId
		INNER JOIN [sAppraisal].[tConductIndicatorMaster]  AS CIM ON CIM.Id=CTM.ConductIndicatorId
		INNER JOIN [sHrm].[tEmployeeMaster]				   AS EMP ON EMP.Id=CND.EmployeeId
		INNER JOIN [sSetup].[tOrganizationMaster]		   AS OMD ON OMD.Id=EMP.OrgID
		INNER JOIN [sHrm].[tEmployeeJobDetail]			   AS EJD ON EJD.EmployeeId=EMP.id
		INNER JOIN [sSetup].[tDepartmentMaster]			   AS DEP ON DEP.id=EJD.OrganizationDepartmentId
		LEFT  JOIN [sSecurity].[tUser]                     AS USR ON USR.Id=CND.CreatedUserId 
	WHERE	
		((CND.BatchId=@rBatchId))
		AND	((OMD.[OrgGroupId] = @rOrgGroupId)   OR (@rOrgGroupId=0))
		AND ((OMD.[Id] = @rOrgId)                OR (@rOrgId=0))
		AND ((CND.EmployeeId = @rEmployeeId)     OR (@rEmployeeId=0))
		AND ((CND.Id = @rId )                    OR (@rId =0))
		AND ((CND.ConductTypeId=@rConductTypeId) OR (@rConductTypeId=0))
		AND ((EMP.[FirstName] +' '+ EMP.[LastName] LIKE @rTitle) OR (@rTitle=''))
		AND CONVERT(DATE,CND.ConductDate)	BETWEEN CONVERT(DATE,ISNULL(@rFromDate, CONVERT(DATE,CND.ConductDate))) 
		AND CONVERT(DATE,ISNULL(@rToDate, CONVERT(DATE,CND.ConductDate)))
		AND ISNULL(EMP.IsOtherUser,0) = 0 

	ORDER BY 
		EMP.Code,CND.ConductDate

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  08-March-2017
** Page:  /Pages/Hrm/Appraisal/ConductTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    08-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductTypeMasterAdd]
CREATE OR ALTER PROCEDURE [sAppraisal].[pConductTypeMasterAdd]
	    @rId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(400),
		@rConductIndicatorId SmallINT,
		@rOrgId SmallINT,
		@rOrgGroupId SmallINT,
		@rIsObsolete bit =null,
        @rCreatedUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		IF(@rId = 0)	
			BEGIN
				IF Exists(SELECT Id FROM [sAppraisal].[tConductTypeMaster]  WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId )
					BEGIN
						SELECT -102 as Result
						RETURN
					END 
			END
		
		ELSE
			BEGIN
				IF  Exists(SELECT Id FROM [sAppraisal].[tConductTypeMaster]  WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId )
					BEGIN
						SELECT -102 as Result
						RETURN
					END
			END
	
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
	
		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tConductTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sAppraisal].[tConductTypeMaster]
				(
					Id,
					Title,
					Remark,
					ConductIndicatorId,
					OrgGroupId,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rTitle,
					@rRemark,
					@rConductIndicatorId,
					@rOrgGroupId,
					0,
					@rCreatedUserId,
					sCommon.fGetDate()
					
				)
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sAppraisal].[tConductTypeMaster]
				SET
					Title=@rTitle,
					Remark=@rRemark,
					ConductIndicatorId=@rConductIndicatorId,
					IsObsolete=@rIsObsolete,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate()
				WHERE Id = @rId
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  08-March-2017
** Page:  /Pages/Hrm/Appraisal/ConductTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    08-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductTypeMasterGet] '',2,1001
CREATE OR ALTER PROCEDURE [sAppraisal].[pConductTypeMasterGet]
	@rTitle VARCHAR(250),
	@rConductIndicatorId smallint,
	@rOrgGroupId SmallINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	
	SELECT
		LT.Id
		,LT.Title
		,LT.Remark
		,CIM.Title AS Behaviour
		,LT.ConductIndicatorId
		,LT.IsObsolete
		,LT.CreatedUserId
		,LT.CreatedDateTime
		,LT.UpdatedUserId
		,LT.UpdatedDateTime
		,CASE LT.[IsObsolete] WHEN 0 THEN 'N' ELSE 'Y' END AS InActive
	FROM [sAppraisal].[tConductTypeMaster] AS LT
		INNER JOIN [sAppraisal].[tConductIndicatorMaster] AS CIM ON CIM.Id=LT.ConductIndicatorId
	WHERE (LT.OrgGroupId = @rOrgGroupId)  AND 
		  ((LT.Title LIKE @rTitle) OR (@rTitle=''))  AND  
		  ((LT.ConductIndicatorId =@rConductIndicatorId) OR  (@rConductIndicatorId=-1))
	ORDER BY LT.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAppraisal].[pConductViewGet]
	
	@rEmployeeId BIGINT=null,
	@rBatchId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		CONVERT(VARCHAR,CND.ConductDate,103)ConductDate
		,CTM.Title AS ConductType
		,CND.Title
		,CND.Remark 
		FROM [sAppraisal].[tConduct] AS CND
		INNER JOIN [sAppraisal].[tConductTypeMaster]       AS CTM ON CTM.Id=CND.ConductTypeId
		INNER JOIN [sAppraisal].[tConductIndicatorMaster]  AS CIM ON CIM.Id=CTM.ConductIndicatorId
	

	WHERE		((CND.BatchId=@rBatchId))
			AND ((CND.EmployeeId = @rEmployeeId) )
		
	ORDER BY 
	CND.ConductDate

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAppraisal].[pDeleteAppraisalData]
	
	@rAppraisalTypeId int, 
	@rEmployeeIdStr nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	IF @rEmployeeIdStr = '' SET @rEmployeeIdStr = NULL
	
	Delete KRD 
	from sAppraisal.tKPAEmployeeRating KER
	INNER JOIN sAppraisal.tKPAEmployeeRatingDetail KRD ON KRD.KPAEmployeeRatingId = KER.Id
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = KER.KPAEmployeeId
	Where KER.AppraisalTypeId = @rAppraisalTypeId
	AND EM.Id IN ((SELECT item from sCommon.fnSplit(@rEmployeeIdStr,',')))
	
	Delete KER 
	from sAppraisal.tKPAEmployeeRating KER
	LEFT JOIN sAppraisal.tKPAEmployeeRatingDetail KRD ON KRD.KPAEmployeeRatingId = KER.Id
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = KER.KPAEmployeeId
	Where KER.AppraisalTypeId = @rAppraisalTypeId
	AND EM.Id IN ((SELECT item from sCommon.fnSplit(@rEmployeeIdStr,',')))
	AND ISNULL(EM.IsOtherUser,0) = 0 
	Select 1 AS Result
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pKPATemplateMasterGet]
** Desc:  Employee Rating Status SET
** Auth:  Savan Vaghela
** Date:  22-March-2017
** Page:  /Pages/Hrm/Appraisal/EmployeeRateEntry.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    22-March-2017      Savan Vaghela       
************************************************************/
-- [sAppraisal].[pEmployeeRatingStatusGet] 1001000000154,100100114,100100063
CREATE OR ALTER PROCEDURE [sAppraisal].[pEmployeeRatingStatusGet]
	@rEmployeeId BIGINT,
	@rBatchId INT,
	@rAppraisalTypeId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

SELECT 
		KED.Id AS KPAEmployeeDetailId
		,Indicator AS Name
		, KPAMeasureId AS TypeID
		,KMD.Title AS TypeName 
		, IndicatorRemark AS Remarks
		,CONVERT(int,Weightage) AS Weightage
		,ERD.MyRating
		,ERD.MyRemark
		,ERD.ManagerRemark
		,ERD.ManagerRating
		,KER.RatingStatusId
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE ID = ISNULL(KER.RatingStatusId,1)) AS RatingStatus
	FROM [sAppraisal].[tKPAEmployee] AS KPA
		LEFT JOIN [sAppraisal].[tKPAEmployeeDetail]       AS KED ON KED.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAMeasureMaster]        AS KMD ON KMD.Id=KED.KPAMeasureId
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating]       AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS ERD ON ERD.KPAEmployeeRatingId=KER.Id AND ERD.KPAEmployeeDetailId=KED.Id
	WHERE  KPATypeId=1 
		AND KPA.EmployeeId=@rEmployeeId 
		AND KPA.BatchId=@rBatchId 
		AND KER.AppraisalTypeId=@rAppraisalTypeId 
		AND KER.RatingStatusId>=2
	ORDER BY KED.Id

	SELECT 
		KED.Id AS KPAEmployeeDetailId
		,Indicator AS Name
		, KPAMeasureId AS TypeID
		,KMD.Title AS TypeName 
		, IndicatorRemark AS Remarks
		,CONVERT(int,Weightage) AS Weightage
		,ERD.MyRating
		,ERD.MyRemark
		,ERD.ManagerRemark
		,ERD.ManagerRating
		,KER.RatingStatusId
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE ID = ISNULL(KER.RatingStatusId,1)) AS RatingStatus 
	FROM [sAppraisal].[tKPAEmployee] AS KPA
		LEFT JOIN [sAppraisal].[tKPAEmployeeDetail]       AS KED ON KED.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAMeasureMaster]        AS KMD ON KMD.Id=KED.KPAMeasureId
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating]       AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS ERD ON ERD.KPAEmployeeRatingId=KER.Id AND ERD.KPAEmployeeDetailId=KED.Id
	WHERE  KPATypeId=2 
		AND KPA.EmployeeId=@rEmployeeId 
		AND KPA.BatchId=@rBatchId 
		AND KER.AppraisalTypeId=@rAppraisalTypeId
		AND KER.RatingStatusId>=2
	ORDER BY KED.Id





	 SELECT 
		 KPA.Id
		,KPA.EmployeeId
		,KPA.BatchId	
		,KPA.KPAStatusId
		,KPS.Title AS KPAStatus
		,ISNULL(KER.RatingStatusId,1)RatingStatusId
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE ID = ISNULL(KER.RatingStatusId,1)) AS RatingStatus
		,RecommendationIncrement,RecommendationDesignation,RecommendationJustification,Remark
	FROM [sAppraisal].[tKPAEmployee] AS KPA
		LEFT JOIN (
					SELECT AppraisalTypeId,KPAEmployeeId,RatingStatusId ,CONVERT(smallint,RecommendationIncrement)RecommendationIncrement,RecommendationDesignation,RecommendationJustification,ISNULL(Remark,'') AS Remark
					FROM [sAppraisal].[tKPAEmployeeRating] 
					WHERE  AppraisalTypeId=@rAppraisalTypeId
				  )	AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAStatus] AS KPS ON KPS.id=KPA.KPAStatusId
		
		
		 
			
	WHERE KPA.EmployeeId=@rEmployeeId AND KPA.BatchId=@rBatchId 
	ORDER BY KPA.Id

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAppraisal].[pGetMyRatingApi]
@rEmployeeId bigint,
@rBatchId int
as
begin
	
	SELECT 
		KPATypeId,
		ATM.Title As AppraisalType
		,Indicator AS IndicatorName
		, KPAMeasureId AS MeasureTypeID
		,KMD.Title AS MeasureTypeName 
		, IndicatorRemark AS Remarks
		,ISNULL(ERD.MyRating,0) AS MyRating
		,ISNULL(ERD.ManagerRating,0) AS ManagerRating
		,ISNULL(KER.BusinessHeadRating,0) AS BusinessHeadRating
	FROM [sAppraisal].[tKPAEmployee] AS KPA
		LEFT JOIN [sAppraisal].[tKPAEmployeeDetail]       AS KED ON KED.KPAEmployeeId=KPA.Id
		LEFT JOIN [sAppraisal].[tKPAMeasureMaster]        AS KMD ON KMD.Id=KED.KPAMeasureId
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating]       AS KER ON KER.KPAEmployeeId=KPA.Id
		left Join [sAppraisal].[tAppraisalTypeMaster]	AS ATM ON ATM.Id=KER.AppraisalTypeId
		LEFT JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS ERD ON ERD.KPAEmployeeRatingId=KER.Id AND ERD.KPAEmployeeDetailId=KED.Id
	WHERE KPA.EmployeeId=@rEmployeeId 
		AND KPA.BatchId=@rBatchId 
		AND KER.RatingStatusId>=5
	ORDER BY KED.Id

	
	
	
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [sAppraisal].[pGetMyRatingHtml] 1001000000164,100100114,2
-- drop proc [sAppraisal].[pGetMyRatingHtml]
CREATE OR ALTER PROCEDURE [sAppraisal].[pGetMyRatingHtml]
@rEmployeeId bigint,
@rBatchId int,
@rKPATypeId SmallINT
as
begin
	IF	EXISTS(SELECT ID from [sAppraisal].[tAppraisalTypeMaster] 
			WHERE ID IN(SELECT AppraisalTypeId FROM [sAppraisal].[tKPAEmployeeRating] WHERE  RatingStatusId >=5 AND KPAEmployeeId IN (SELECT ID FROM [sAppraisal].[tKPAEmployee] WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId))
			AND IsObsolete=0)
		BEGIN


			declare @lTableMain varchar(500)='',@lTableHead varchar(max)='',@lTableTail varchar(500)=''
			select @lTableMain = @lTableMain + '
			<table style="width: 100%; border: 1px solid #E5EFF8; width: 100%; border-collapse: collapse; margin: 0px auto;">
				<tr>
					<td  style="background: #F4F9FE;"></td>
					<td style="font-size: 11px; font-weight: bold; padding: 3px; background: none repeat scroll 0% 0% #F4F9FE; border: 1px solid #E5EFF8; text-align: center; color: #66A3D3;">Title</td>
					<td>
						<table style="width: 100%; border: 1px solid #E5EFF8; width: 100%; border-collapse: collapse; margin: 0px auto;"><tr>'
	
			select @lTableHead = @lTableHead + 
			'<td width="20%"   style="font-size: 11px; font-weight: bold; padding: 3px; background: none repeat scroll 0% 0% #F4F9FE; border: 1px solid #E5EFF8; text-align: center; color: #66A3D3;" colspan="3">' + isnull(Title,'') + 
			'</td>'
			from [sAppraisal].[tAppraisalTypeMaster] 
			WHERE ID IN(SELECT AppraisalTypeId FROM [sAppraisal].[tKPAEmployeeRating] WHERE  RatingStatusId >=5 AND KPAEmployeeId IN (SELECT ID FROM [sAppraisal].[tKPAEmployee] WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId))
			AND IsObsolete=0


		
			select @lTableHead = @lTableHead + '</tr>'
	
			declare @tbltmp table(tid int identity(1,1),Title varchar(500))
			insert into @tbltmp
			select Title from [sAppraisal].[tAppraisalTypeMaster]
			WHERE ID IN(SELECT AppraisalTypeId FROM [sAppraisal].[tKPAEmployeeRating] WHERE  RatingStatusId >=5 AND KPAEmployeeId IN (SELECT ID FROM [sAppraisal].[tKPAEmployee] WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId))
			AND IsObsolete=0
	
			declare @cnt int,@i int,@res varchar(max)=''
			select @cnt = count(*),@i = 1 from @tbltmp
	
			select @res = @res + '<tr>'
	
			while @i<= @cnt
			begin		
				select @res = @res + '
				<td style="font-size: 11px; font-weight: bold; padding: 3px; background: none repeat scroll 0% 0% #F4F9FE; border: 1px solid #E5EFF8; text-align: center; color: #66A3D3;"  width="30"> Self </td>
				<td style="font-size: 11px; font-weight: bold; padding: 3px; background: none repeat scroll 0% 0% #F4F9FE; border: 1px solid #E5EFF8; text-align: center; color: #66A3D3;"  width="50"> Manager </td>
				<td style="font-size: 11px; font-weight: bold; padding: 3px; background: none repeat scroll 0% 0% #F4F9FE; border: 1px solid #E5EFF8; text-align: center; color: #66A3D3;"  width="85"> Bussiness Head </td>'
				select @i = @i + 1		
			end
			select @res = @res + '</tr></table>'
	
			select @lTableHead = @lTableHead + @res
			select @lTableTail = @lTableTail + '</td></tr>'
	
			declare @lTableResult varchar(max)=''
			select @lTableResult = @lTableResult + '<tr>
			<td style="color: #678197; text-align: center; border: 1px solid #E5EFF8; background: none repeat scroll 0% 0% #FFF; margin: 0px; padding: 2px;">' + CONVERT(VARCHAR, ROW_NUMBER() OVER (ORDER BY KED.Id))  + '</td>
			<td style="color: #678197; text-align: center; border: 1px solid #E5EFF8; background: none repeat scroll 0% 0% #FFF; margin: 0px; padding: 2px; font-size: 12PX;
    font-weight: 600" >' + isnull(KED.Indicator,'') + '</td>
			' + [sAppraisal].[fGetInnerHtml](KED.Id) + '</tr>'
			from [sAppraisal].[tKPAEmployee] AS KPA
			LEFT JOIN [sAppraisal].[tKPAEmployeeDetail] AS KED ON KED.KPAEmployeeId = KPA.Id
	
	
			WHERE KED.KPATypeId=@rKPATypeId AND KPA.EmployeeId = @rEmployeeId AND KPA.BatchId = @rBatchId
			ORDER BY KED.Id
		
			select @lTableMain + @lTableHead + @lTableTail + @lTableResult + '</table>' as Head,CONVERT(BIT,1) AS Status
		END
	ELSE
	BEGIN
		select '<table width="100%"><tr><td style="width: 100%; text-align: center; color: rgb(102, 163, 211); font-size: 15px; font-weight: bold; background: rgb(244, 249, 254); border-width: 1px; border-style: solid; border-color: rgb(229, 239, 248); border-image: initial; padding: 7px;">No ratings available for the selected financial year</td></tr></table>' as Head, CONVERT(BIT,0) AS Status
	END
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  20-March-2017
** Page:  /Pages/Hrm/Appraisal/SetKPAForTeam.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    20-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pKPAEmployeeAdd]
CREATE OR ALTER PROCEDURE [sAppraisal].[pKPAEmployeeAdd]
	    @rEmployeeId BIGINT,
		@rBatchId INT,
		@rKPATemplateId INT,
		@rOrgId SmallINT,
		@rOrgGroupId SmallINT,
		@rCreatedUserId bigint,
		@KPATypeId NVARCHAR(MAX),
		@KPAMeasureId NVARCHAR(MAX),
		@Indicator NVARCHAR(MAX),
		@IndicatorRemark NVARCHAR(MAX),
		@Weightage NVARCHAR(MAX)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
		BEGIN TRANSACTION	
		
		DECLARE @lNextNumber BIGINT 
		DECLARE @KPAEmployeeId BIGINT 
		

		IF NOT EXISTS(SELECT Id FROM [sAppraisal].[tKPAEmployee]  WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId )
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tKPAEmployee', 0, 1, 1,@outNextNumber = @lNextNumber output
		
				INSERT INTO [sAppraisal].[tKPAEmployee]
				(
					Id,
					EmployeeId,
					KPAStatusId,
					BatchId,
					KPATemplateId,
					CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rEmployeeId,
					2,
					@rBatchId,
					@rKPATemplateId,
					@rCreatedUserId,
					sCommon.fGetDate()			
				)

				INSERT INTO [sAppraisal].[tKPAEmployeeDetail](KPAEmployeeId,KPATypeId,KPAMeasureId,Indicator,IndicatorRemark,Weightage)
				SELECT @lNextNumber,KPATypeId.item,KPAMeasureId.item,ISNULL(Indicator.item,''),ISNULL(IndicatorRemark.item,''),Weightage.item
				FROM scommon.fnSplitRowID(@KPATypeId,',') AS KPATypeId
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@IndicatorRemark,',')) AS IndicatorRemark
				ON KPATypeId.RowID=IndicatorRemark.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Weightage,','))AS Weightage
				ON KPATypeId.RowID=Weightage.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Indicator,','))AS Indicator
				ON KPATypeId.RowID=Indicator.RowID   
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@KPAMeasureId,','))AS KPAMeasureId
				ON KPATypeId.RowID=KPAMeasureId.RowID  
				
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN

			SELECT @KPAEmployeeId=Id FROM [sAppraisal].[tKPAEmployee]  WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId
						
				UPDATE  [sAppraisal].[tKPAEmployee]
				SET
					KPATemplateId=@rKPATemplateId,
					KPAStatusId=2,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate()
				WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId
				
				DELETE FROM [sAppraisal].[tKPAEmployeeDetail] WHERE KPAEmployeeId=@KPAEmployeeId
				
				INSERT INTO [sAppraisal].[tKPAEmployeeDetail](KPAEmployeeId,KPATypeId,KPAMeasureId,Indicator,IndicatorRemark,Weightage)
				
				SELECT @KPAEmployeeId,KPATypeId.item,KPAMeasureId.item,ISNULL(Indicator.item,''),ISNULL(IndicatorRemark.item,''),Weightage.item
				FROM scommon.fnSplitRowID(@KPATypeId,',') AS KPATypeId
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@IndicatorRemark,',')) AS IndicatorRemark
				ON KPATypeId.RowID=IndicatorRemark.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Weightage,','))AS Weightage
				ON KPATypeId.RowID=Weightage.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Indicator,','))AS Indicator
				ON KPATypeId.RowID=Indicator.RowID   
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@KPAMeasureId,','))AS KPAMeasureId
				ON KPATypeId.RowID=KPAMeasureId.RowID  
				
				
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pKPATemplateMasterGet]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
-- [sAppraisal].[pKPAEmployeeDetailGet] 1001000000001
CREATE OR ALTER PROCEDURE [sAppraisal].[pKPAEmployeeDetailGet]
	@KPAEmployeeId BIGINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	
	SELECT 
		KED.Id
		,Indicator AS Name
		, KPAMeasureId AS Type
		, IndicatorRemark AS Remarks
		,CONVERT(int,Weightage) AS Weightage
		,KMD.Title AS TypeName 
	FROM [sAppraisal].[tKPAEmployeeDetail] AS KED
		LEFT JOIN [sAppraisal].[tKPAMeasureMaster] AS KMD ON KMD.Id=KED.KPAMeasureId
	WHERE  KPAEmployeeId=@KPAEmployeeId AND KPATypeId=1 
	ORDER BY Id
	
	SELECT 
		KED.Id
		,Indicator AS Name
		, KPAMeasureId AS Type
		, IndicatorRemark AS Remarks
		,CONVERT(int,Weightage) AS Weightage
		,KMD.Title AS TypeName 
	FROM [sAppraisal].[tKPAEmployeeDetail] AS KED
		LEFT JOIN [sAppraisal].[tKPAMeasureMaster] AS KMD ON KMD.Id=KED.KPAMeasureId
	WHERE  KPAEmployeeId=@KPAEmployeeId AND KPATypeId=2 
	ORDER BY Id
	
	
	SELECT KPAStatusId,KPS.Title AS KPAStatus 
	FROM [sAppraisal].[tKPAStatus] AS KPS
		INNER JOIN [sAppraisal].[tKPAEmployee]  AS EMP on EMP.KPAStatusId=KPS.Id
	WHERE EMP.id=@KPAEmployeeId






END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

 
/******************************
** Name:  [sAppraisal].[pKPAEmployeeGet]
** Desc:  Get Employee details for set KPA Details
** Auth:  Savan Vaghela
** Date:  18-March-2017
** Page:  /Pages/Hrm/Appraisal/SetKPAForTeam.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    18-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pKPAEmployeeGet] 1002000000011,0,0,1001
CREATE OR ALTER PROCEDURE [sAppraisal].[pKPAEmployeeGet]
	@rEmployeeManagerId BIGINT,
	@rBatchId int,
	@rOrgId smallint,
	@rOrgGroupId smallint,
	@rEmployeeCode nvarchar(20) = '',
	@rDepartmentId int = 0,
	@rDesignationId int = 0,
	@rKPAStatusId tinyint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	select 
		EMP.Id
		,EMP.Code
		,ISNULL(EMP.FirstName,'') +' '+ ISNULL(EMP.LastName,'') AS Employee
		,ISNULL(DEP.Id,'') AS DepartmentId
		,ISNULL(DEP.Title,'') AS DepartmentName
		,ISNULL(DEG.Id,'') AS DesignationId
		,ISNULL(DEG.Title,'') AS DesignationName
		,EMP.ShortName
		,EMP.StatusId
		,EJD.EmployeeManagerId
		,ISNULL(EMD.FirstName,'') +' '+ISNULL(EMD.LastName,'') AS ManagerName
		,EMP.OrgID
		,ORG.DisplayTitle
		,ISNULL(KPAStatus.KPAStatusId,1) AS KPAStatusId
		,(SELECT Title FROM [sAppraisal].[tKPAStatus] WHERE Id=ISNULL(KPAStatus.KPAStatusId,1)) AS KPAStatus
		,CASE WHEN ISNULL(KPAStatus.KPAStatusId,1) in (1,4) THEN CONVERT(BIT,1) ELSE CONVERT(BIT,0) END AS Enabled
	from [sHrm].[tEmployeeMaster]  AS EMP
		LEFT JOIN [sHrm].[tEmployeeJobDetail] AS EJD On EJD.EmployeeId=EMP.Id
		LEFT JOIN [sHrm].[tEmployeeMaster] AS EMD ON EMD.Id= EJD.EmployeeManagerId AND ISNULL(EMD.IsOtherUser,0) = 0
		LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID
		LEFT JOIN [sSetup].[tDepartmentMaster] AS DEP ON DEP.Id=EJD.OrganizationDepartmentId
		LEFT JOIN [sHrm].[tEmployeeDesignationMaster] AS DEG ON DEG.Id=EJD.EmployeeDesignationId
		LEFT JOIN (
					SELECT EmployeeId,KPAStatusId 
					FROM [sAppraisal].[tKPAEmployee] 
					Where BatchId=@rBatchId
				  ) AS KPAStatus
				    ON KPAStatus.EmployeeId=EMP.Id
	where 
		ORG.OrgGroupId=@rOrgGroupId 
		AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		AND	((EJD.EmployeeManagerId=@rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) 
		AND Emp.ID<>@rEmployeeManagerId 
		AND EMP.StatusId=7
		AND ISNULL(EMP.IsOtherUser,0) = 0
		AND (EMP.Code = @rEmployeeCode OR @rEmployeeCode = '')
		AND (EJD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND (EJD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
		AND (EJD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
		AND (ISNULL(KPAStatus.KPAStatusId,1) = @rKPAStatusId OR @rKPAStatusId = 0)
	Order by EMP.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductTypeMasterAdd]
CREATE OR ALTER PROCEDURE [sAppraisal].[pKPAEmployeeRatingAdd]
	  	@rOrgId                       SMALLINT,
		@rCreatedUserId				  BIGINT,
		@rAppraisalTypeId			  INT,
		@rKPAEmployeeId				  BIGINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
		
		DECLARE @lNextNumber BIGINT 
						 
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tKPAEmployeeRating', 0, 1, 1,@outNextNumber = @lNextNumber output
				
				IF EXISTS(SELECT 1 FROM [sAppraisal].[tKPAEmployeeRating] WHERE KPAEmployeeId=@rKPAEmployeeId AND AppraisalTypeId=@rAppraisalTypeId)
				BEGIN
					DELETE FROM [sAppraisal].[tKPAEmployeeRating] WHERE KPAEmployeeId=@rKPAEmployeeId AND AppraisalTypeId=@rAppraisalTypeId
				END
				
				
				INSERT INTO [sAppraisal].[tKPAEmployeeRating]
				(
					Id,
					AppraisalTypeId,
					KPAEmployeeId,
					RatingStatusId,
				 	CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rAppraisalTypeId,
					@rKPAEmployeeId,
					2,
				 	@rCreatedUserId,
					sCommon.fGetDate()			
				)

				 IF EXISTS(SELECT 1 FROM [sAppraisal].[tKPAEmployeeRatingDetail] WHERE KPAEmployeeDetailId=@rKPAEmployeeId AND KPAEmployeeRatingId=@lNextNumber)
				 BEGIN
					DELETE FROM [sAppraisal].[tKPAEmployeeRatingDetail] WHERE KPAEmployeeDetailId=@rKPAEmployeeId AND KPAEmployeeRatingId=@lNextNumber
			   	 END

				 INSERT INTO [sAppraisal].[tKPAEmployeeRatingDetail](KPAEmployeeRatingId,KPAEmployeeDetailId)
				 SELECT @lNextNumber,Id FROM [sAppraisal].[tKPAEmployeeDetail]  WHERE KPAEmployeeId=@rKPAEmployeeId ORDER BY Id
				
				SELECT 1 AS Result
			END	 
		 
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pKPAEmployeeRatingStatusChange]
** Desc:  Employee Rating Status SET
** Auth:  Savan Vaghela
** Date:  22-March-2017
** Page:  /Pages/Hrm/Appraisal/EmployeeRateEntry.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    22-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pKPAEmployeeRatingStatusChange] 1001000000172,100100114,100100042,3,'7,8,9,10,11,12,','1,1,1,1,1,1,','a,b,c,d,e,f'
CREATE OR ALTER PROCEDURE [sAppraisal].[pKPAEmployeeRatingStatusChange]
	   @rEmployeeId BIGINT,
	   @rBatchId INT ,
	   @rAppraisalTypeId INT,
	   @rRatingStatusId INT,
	   @rKPAEmployeeDetailId NVARCHAR(MAX),
	   @rMyRating NVARCHAR(MAX),
	   @rMyRemark NVARCHAR(MAX),
	   @rRecommendationIncrement DECIMAL(5,2)=null,
	   @rRecommendationDesignation nvarchar(200)=null,
	   @rRecommendationJustification nvarchar(200)=null,
	   @rRemark NVARCHAR(500)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
		BEGIN TRANSACTION	
			
			DECLARE @KPAEmployeeId BIGINT,@KPAEmployeeRatingId BIGINT
			SELECT @KPAEmployeeId =Id FROM [sAppraisal].[tKPAEmployee] WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId
			SET @KPAEmployeeId=ISNULL(@KPAEmployeeId,0)
			 
			UPDATE [sAppraisal].[tKPAEmployeeRating] SET RatingStatusId=@rRatingStatusId,Remark=@rRemark WHERE AppraisalTypeId=@rAppraisalTypeId AND KPAEmployeeId=@KPAEmployeeId

			IF (@rRatingStatusId=4)
				BEGIN
					UPDATE [sAppraisal].[tKPAEmployeeRating]  
						SET RecommendationIncrement=@rRecommendationIncrement
							,RecommendationDesignation=@rRecommendationDesignation
							,RecommendationJustification=@rRecommendationJustification
						WHERE AppraisalTypeId=@rAppraisalTypeId AND KPAEmployeeId=@KPAEmployeeId
				END


			SELECT @KPAEmployeeRatingId=Id FROM [sAppraisal].[tKPAEmployeeRating] WHERE AppraisalTypeId=@rAppraisalTypeId AND KPAEmployeeId=@KPAEmployeeId
			SET @KPAEmployeeRatingId=ISNULL(@KPAEmployeeRatingId,0)


			
			DECLARE @Counter SMALLINT=(SELECT COUNT(1)FROM scommon.fnSplitRowID(@rKPAEmployeeDetailId,','))
			DECLARE @RatingDetailTable TABLE (RowID int ,DetailId BIGINT,MyRating DECIMAL(10,2),MyRemark NVARCHAR(500)) -- Mantis - 41510(Size increase 400 to 500)

				
			INSERT INTO @RatingDetailTable
			SELECT DetailId.RowID,DetailId.item,MyRating.item,MyRemark.item FROM scommon.fnSplitRowID(@rKPAEmployeeDetailId,',') AS DetailId
			LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@rMyRating,',')) AS MyRating
			ON DetailId.RowID= MyRating.RowID
			LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@rMyRemark,',')) AS MyRemark
			ON DetailId.RowID= MyRemark.RowID
		 
			WHILE (@Counter <>0)
				BEGIN
					DECLARE @KPAEmployeeDetailId BIGINT,@MyRating DECIMAL(10,2),@MyRemark NVARCHAR(500)	-- Mantis - 41510(Size increase 400 to 500)
					SELECT @KPAEmployeeDetailId=DetailId,@MyRating=MyRating,@MyRemark=MyRemark FROM @RatingDetailTable WHERE RowID=@Counter
					--PRINT 'KPAEmployeeDetailId ' + CONVERT(NVARCHAR(20),@KPAEmployeeDetailId) + ',  MyRating '+ CONVERT(NVARCHAR(20),@MyRating) + ', MyRemark ' ++ CONVERT(NVARCHAR(20),@MyRemark)

					IF (@rRatingStatusId=3)
						BEGIN
							UPDATE [sAppraisal].[tKPAEmployeeRatingDetail] SET MyRating=@MyRating,MyRemark=@MyRemark WHERE KPAEmployeeDetailId=@KPAEmployeeDetailId AND KPAEmployeeRatingId=@KPAEmployeeRatingId
						END
					ELSE IF (@rRatingStatusId=4)
						BEGIN
							UPDATE [sAppraisal].[tKPAEmployeeRatingDetail] SET ManagerRating=@MyRating,ManagerRemark=@MyRemark WHERE KPAEmployeeDetailId=@KPAEmployeeDetailId AND KPAEmployeeRatingId=@KPAEmployeeRatingId
						END

					
					SET @Counter=@Counter-1
				END
		
		SELECT 1 AS Result
			 
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pKPATemplateMasterGet]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
-- [sAppraisal].[pKPAEmployeeStatusChange] 1001000000001
CREATE OR ALTER PROCEDURE [sAppraisal].[pKPAEmployeeStatusChange]
	@rEmployeeId BIGINT,
	@rBatchId INT,
	@rKPAStatusId TINYINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			UPDATE [sAppraisal].[tKPAEmployee] SET KPAStatusId=@rKPAStatusId  WHERE EmployeeId=@rEmployeeId AND BatchId=@rBatchId
			SELECT 1 AS Result
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pKPATemplateMasterGet]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
-- [sAppraisal].[pKPATemplateDetailGet] 100100001
CREATE OR ALTER PROCEDURE [sAppraisal].[pKPATemplateDetailGet]
	@KPATemplateId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT AutoId AS Id, Indicator AS Name, KPAMeasureId AS Type, IndicatorRemark AS Remarks,CONVERT(int,Weightage) AS Weightage FROM [sAppraisal].[tKPATemplateDetail] WHERE  KPATemplateId=@KPATemplateId AND KPATypeId=1 ORDER BY AutoId
	SELECT AutoId AS Id, Indicator AS Name, KPAMeasureId AS Type, IndicatorRemark AS Remarks,CONVERT(int,Weightage) AS Weightage FROM [sAppraisal].[tKPATemplateDetail] WHERE  KPATemplateId=@KPATemplateId AND KPATypeId=2 ORDER BY AutoId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pConductTypeMasterAdd]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pConductTypeMasterAdd]
CREATE OR ALTER PROCEDURE [sAppraisal].[pKPATemplateMasterAdd]
	    @rId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(400),
		@rOrgId SmallINT,
		@rOrgGroupId SmallINT,
		@rIsObsolete bit =null,
        @rCreatedUserId bigint,
		@KPATypeId NVARCHAR(MAX),
		@KPAMeasureId NVARCHAR(MAX),
		@Indicator NVARCHAR(MAX),
		@IndicatorRemark NVARCHAR(MAX),
		@Weightage NVARCHAR(MAX)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY



		IF(@rId = 0)	
				BEGIN
					IF Exists(SELECT Id FROM [sAppraisal].[tKPATemplateMaster]  WHERE Indicator=@rTitle AND OrgGroupId=@rOrgGroupId )
						BEGIN
							SELECT -102 as Result
							RETURN
						END 
				END
		
			ELSE
				BEGIN
					IF  Exists(SELECT Id FROM [sAppraisal].[tKPATemplateMaster]  WHERE Indicator=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId )
						BEGIN
							SELECT -102 as Result
							RETURN
						END
				END


		BEGIN TRANSACTION	
		
		DECLARE @lNextNumber BIGINT 


		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tKPATemplateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sAppraisal].[tKPATemplateMaster]
				(
					Id,
					Indicator,
					Remark,
					OrgGroupId,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rTitle,
					@rRemark,
					@rOrgGroupId,
					0,
					@rCreatedUserId,
					sCommon.fGetDate()			
				)

				INSERT INTO [sAppraisal].[tKPATemplateDetail](KPATemplateId,KPATypeId,KPAMeasureId,Indicator,IndicatorRemark,Weightage)
				SELECT @lNextNumber,KPATypeId.item,KPAMeasureId.item,ISNULL(Indicator.item,''),ISNULL(IndicatorRemark.item,''),Weightage.item
				FROM scommon.fnSplitRowID(@KPATypeId,',') AS KPATypeId
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@IndicatorRemark,',')) AS IndicatorRemark
				ON KPATypeId.RowID=IndicatorRemark.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Weightage,','))AS Weightage
				ON KPATypeId.RowID=Weightage.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Indicator,','))AS Indicator
				ON KPATypeId.RowID=Indicator.RowID   
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@KPAMeasureId,','))AS KPAMeasureId
				ON KPATypeId.RowID=KPAMeasureId.RowID  
				
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sAppraisal].[tKPATemplateMaster]
				SET
					Indicator=@rTitle,
					Remark=@rRemark,
					IsObsolete=@rIsObsolete,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate()
				WHERE Id = @rId
				
				DELETE FROM [sAppraisal].[tKPATemplateDetail] WHERE KPATemplateId=@lNextNumber
				
				INSERT INTO [sAppraisal].[tKPATemplateDetail](KPATemplateId,KPATypeId,KPAMeasureId,Indicator,IndicatorRemark,Weightage)
				
				SELECT @lNextNumber,KPATypeId.item,KPAMeasureId.item,ISNULL(Indicator.item,''),ISNULL(IndicatorRemark.item,''),Weightage.item
				FROM scommon.fnSplitRowID(@KPATypeId,',') AS KPATypeId
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@IndicatorRemark,',')) AS IndicatorRemark
				ON KPATypeId.RowID=IndicatorRemark.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Weightage,','))AS Weightage
				ON KPATypeId.RowID=Weightage.RowID
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@Indicator,','))AS Indicator
				ON KPATypeId.RowID=Indicator.RowID   
				LEFT JOIN (SELECT * FROM scommon.fnSplitRowID(@KPAMeasureId,','))AS KPAMeasureId
				ON KPATypeId.RowID=KPAMeasureId.RowID  
				
				
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sAppraisal].[pKPATemplateMasterGet]
** Desc:  Create and Update Data in Loan ConductTypeMaster
** Auth:  Savan Vaghela
** Date:  17-March-2017
** Page:  /Pages/Hrm/Appraisal/KPATemplatesMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    17-March-2017      Savan Vaghela       
************************************************************/
-- [sAppraisal].[pKPATemplateMasterGet] 1001,''
CREATE OR ALTER PROCEDURE [sAppraisal].[pKPATemplateMasterGet]
	@rOrgGroupId SmallINT,
	@rTitle NVARCHAR(250)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	
	SELECT 
		KTM.Id
		,KTM.Indicator
		,KTM.Remark
		,USR.DisplayTitle
		,KTM.[IsObsolete]
		,CONVERT(VARCHAR,KTM.CreatedDateTime,107)CreatedDateTime
		,CASE KTM.[IsObsolete] WHEN 0 THEN 'Y' ELSE 'N' END AS InActive
	FROM 
		[sAppraisal].[tKPATemplateMaster] AS KTM
		LEFT  JOIN [sSecurity].[tUser]    AS USR ON USR.Id=KTM.CreatedUserId 
	WHERE  (KTM.OrgGroupId = @rOrgGroupId)  AND 
			  ((KTM.Indicator LIKE @rTitle) OR (@rTitle=''))    
	ORDER BY KTM.CreatedDateTime 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
/******************************
** Name:  [sAppraisal].[pKPAEmployeeGet]
** Desc:  Get Employee details for set KPA Details
** Auth:  Savan Vaghela
** Date:  18-March-2017
** Page:  /Pages/Hrm/Appraisal/SetKPAForTeam.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    21-March-2017      Savan Vaghela       
************************************************************/
--[sAppraisal].[pRolloutAppraisalsStatusGet] 1002000000011,0,0,1001,0
--[sAppraisal].[pRolloutAppraisalsStatusGet] 0,100100114,1001,1001,0
CREATE OR ALTER PROCEDURE [sAppraisal].[pRolloutAppraisalsStatusGet]
	@rEmployeeManagerId           BIGINT,
	@rBatchId					  INT,
	@rOrgId						  SMALLINT,
	@rOrgGroupId				  SMALLINT,
	@rAppraisalTypeId			  INT,
	@rIsRollOutAppraisalsAdmin	  BIT = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    IF(@rIsRollOutAppraisalsAdmin=0)
	BEGIN
	SELECT 
		EMP.Id
		,EMP.Code
		,ISNULL(EMP.FirstName,'') +' '+ ISNULL(EMP.LastName,'') AS Employee
		,ISNULL(DEP.Id,'') AS DepartmentId
		,ISNULL(DEP.Title,'') AS DepartmentName
		,ISNULL(DEG.Id,'') AS DesignationId
		,ISNULL(DEG.Title,'') AS DesignationName
		,EMP.ShortName
		,EMP.StatusId
		,EJD.EmployeeManagerId
		,ISNULL(EMD.FirstName,'') +' '+ISNULL(EMD.LastName,'') AS ManagerName
		,EMP.OrgID
		,ORG.DisplayTitle
		,ISNULL(KPAStatus.KPAStatusId,1) AS KPAStatusId
		,(SELECT Title FROM [sAppraisal].[tKPAStatus] WHERE Id=ISNULL(KPAStatus.KPAStatusId,1)) AS KPAStatus
		,ISNULL(RatingStatus.RatingStatusId,1) AS RatingStatusId
		,CASE WHEN ISNULL(KPAStatus.KPAStatusId,1)=3 AND ISNULL(RatingStatus.RatingStatusId,1)=1 THEN CONVERT(BIT,1) ELSE CONVERT(BIT,0) END AS Enable
		--,CONVERT(BIT,1)  AS Enable
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE Id=ISNULL(RatingStatus.RatingStatusId,1)) AS RattingStatus
		,ISNULL(KPAEmployee.KPAEmployeeId,0) KPAEmployeeId
	FROM [sHrm].[tEmployeeMaster]  AS EMP
		LEFT JOIN [sHrm].[tEmployeeJobDetail] AS EJD On EJD.EmployeeId=EMP.Id
		LEFT JOIN [sHrm].[tEmployeeMaster] AS EMD ON EMD.Id= EJD.EmployeeManagerId
		LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID
		LEFT JOIN [sSetup].[tDepartmentMaster] AS DEP ON DEP.Id=EJD.OrganizationDepartmentId
		LEFT JOIN [sHrm].[tEmployeeDesignationMaster] AS DEG ON DEG.Id=EJD.EmployeeDesignationId
		LEFT JOIN (
					SELECT EmployeeId,KPAStatusId 
					FROM [sAppraisal].[tKPAEmployee] 
					Where BatchId=@rBatchId
				  ) AS KPAStatus
			    ON KPAStatus.EmployeeId=EMP.Id
		LEFT JOIN (
					SELECT ERD.AppraisalTypeId,KPA.EmployeeId,ERD.RatingStatusId FROM [sAppraisal].[tKPAEmployee] AS KPA 
					INNER JOIN [sAppraisal].[tKPAEmployeeRating] AS ERD on ERD.KPAEmployeeId=KPA.Id
					WHERE KPA.BatchId=@rBatchId AND ERD.AppraisalTypeId=@rAppraisalTypeId
		) AS  RatingStatus ON RatingStatus.EmployeeId =EMP.Id  

		LEFT JOIN (
					SELECT Id AS KPAEmployeeId,EmployeeId  FROM [sAppraisal].[tKPAEmployee] Where BatchId=@rBatchId
				  ) AS KPAEmployee ON  KPAEmployee.EmployeeId=EMP.Id
	where 
		ORG.OrgGroupId=@rOrgGroupId 
		AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		AND	((EJD.EmployeeManagerId=@rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) 
		AND Emp.ID<>@rEmployeeManagerId 
		AND EMP.StatusId=7
		AND ISNULL(EMP.IsOtherUser,0) = 0 AND  ISNULL(EMD.IsOtherUser,0) = 0
	Order by  EMP.Number
	END
	ELSE
	BEGIN
	SELECT 
		EMP.Id
		,EMP.Code
		,ISNULL(EMP.FirstName,'') +' '+ ISNULL(EMP.LastName,'') AS Employee
		,ISNULL(DEP.Id,'') AS DepartmentId
		,ISNULL(DEP.Title,'') AS DepartmentName
		,ISNULL(DEG.Id,'') AS DesignationId
		,ISNULL(DEG.Title,'') AS DesignationName
		,EMP.ShortName
		,EMP.StatusId
		,EJD.EmployeeManagerId
		,ISNULL(EMD.FirstName,'') +' '+ISNULL(EMD.LastName,'') AS ManagerName
		,EMP.OrgID
		,ORG.DisplayTitle
		,ISNULL(KPAStatus.KPAStatusId,1) AS KPAStatusId
		,(SELECT Title FROM [sAppraisal].[tKPAStatus] WHERE Id=ISNULL(KPAStatus.KPAStatusId,1)) AS KPAStatus
		,ISNULL(RatingStatus.RatingStatusId,1) AS RatingStatusId
		,CASE WHEN ISNULL(KPAStatus.KPAStatusId,1)=3 AND ISNULL(RatingStatus.RatingStatusId,1)=1 THEN CONVERT(BIT,1) ELSE CONVERT(BIT,0) END AS Enable
		--,CONVERT(BIT,1)  AS Enable
		,(SELECT Title FROM [sAppraisal].[tRatingStatus] WHERE Id=ISNULL(RatingStatus.RatingStatusId,1)) AS RattingStatus
		,ISNULL(KPAEmployee.KPAEmployeeId,0) KPAEmployeeId
	FROM [sHrm].[tEmployeeMaster]  AS EMP
		LEFT JOIN [sHrm].[tEmployeeJobDetail] AS EJD On EJD.EmployeeId=EMP.Id
		LEFT JOIN [sHrm].[tEmployeeMaster] AS EMD ON EMD.Id= EJD.EmployeeManagerId
		LEFT JOIN [sSetup].[tOrganizationMaster] AS ORG ON Org.id=EMP.OrgID
		LEFT JOIN [sSetup].[tDepartmentMaster] AS DEP ON DEP.Id=EJD.OrganizationDepartmentId
		LEFT JOIN [sHrm].[tEmployeeDesignationMaster] AS DEG ON DEG.Id=EJD.EmployeeDesignationId
		LEFT JOIN (
					SELECT EmployeeId,KPAStatusId 
					FROM [sAppraisal].[tKPAEmployee] 
					Where BatchId=@rBatchId
				  ) AS KPAStatus
			    ON KPAStatus.EmployeeId=EMP.Id
		LEFT JOIN (
					SELECT ERD.AppraisalTypeId,KPA.EmployeeId,ERD.RatingStatusId FROM [sAppraisal].[tKPAEmployee] AS KPA 
					INNER JOIN [sAppraisal].[tKPAEmployeeRating] AS ERD on ERD.KPAEmployeeId=KPA.Id
					WHERE KPA.BatchId=@rBatchId AND ERD.AppraisalTypeId=@rAppraisalTypeId
		) AS  RatingStatus ON RatingStatus.EmployeeId =EMP.Id  

		LEFT JOIN (
					SELECT Id AS KPAEmployeeId,EmployeeId  FROM [sAppraisal].[tKPAEmployee] Where BatchId=@rBatchId
				  ) AS KPAEmployee ON  KPAEmployee.EmployeeId=EMP.Id
	where 
		ORG.OrgGroupId=@rOrgGroupId 
		AND ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		--AND	((EJD.EmployeeManagerId=@rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) 
		--AND Emp.ID<>@rEmployeeManagerId 
		AND EMP.StatusId=7
		AND ISNULL(EMP.IsOtherUser,0) = 0 AND  ISNULL(EMD.IsOtherUser,0) = 0
	Order by  EMP.Number
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAppraisal].[pRptAppraisalReport]

		@rOrgId SMALLINT=0,
		@rBatchId INT=0,
		@rAppraisalTypeId INT=0,
		@rEmployeeId BIGINT=0,
		@rDepartmentId INT=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT	EMP.Id,
			EMP.Code,
			EMP.FirstName + ' ' + EMP.LastName AS EmployeeName,
			R.MyRating AS EmployeeRating,
			KER.Remark AS EmployeeRemark,
			R.ManagerRating,
			KER.RecommendationDesignation AS ManagerRemark,
			KER.BusinessHeadRating AS OHRating,
			KER.BusinessHeadRecommendationDesignation AS OHRemark

	FROM [sHrm].[tEmployeeMaster] AS EMP
		INNER JOIN sHrm.vEmployeeCommonDetail AS ECD ON ECD.EmployeeId = EMP.Id   
		LEFT JOIN [sAppraisal].[tKPAEmployee] AS KPA ON KPA.EmployeeId=EMP.Id
		LEFT JOIN [sAppraisal].[tKPAEmployeeRating] AS KER ON KER.KPAEmployeeId=KPA.Id
		LEFT JOIN 
				(
					SELECT KER.KPAEmployeeId,KRD.KPAEmployeeRatingId,CONVERT(DECIMAL(18,2),AVG(KRD.ManagerRating))ManagerRating,CONVERT(DECIMAL(18,2),AVG(KRD.MyRating))MyRating
					FROM [sAppraisal].[tKPAEmployeeRating] AS KER
						INNER JOIN [sAppraisal].[tKPAEmployeeRatingDetail] AS KRD ON KRD.KPAEmployeeRatingId=KER.Id
					GROUP BY KER.KPAEmployeeId,KRD.KPAEmployeeRatingId
				) AS R ON R.KPAEmployeeId=KPA.Id AND R.KPAEmployeeRatingId=KER.Id

	WHERE ((EMP.OrgID=@rOrgId)OR(@rOrgId=0))
		AND EMP.StatusId=7
		AND ((EMP.Id=@rEmployeeId) OR (ISNULL(@rEmployeeId,0)=0))
		AND KPA.BatchId=@rBatchId
		AND KER.AppraisalTypeId=@rAppraisalTypeId
		AND ISNULL(EMP.IsOtherUser,0) = 0
		AND ((ECD.DepartmentId=@rDepartmentId) OR (ISNULL(@rDepartmentId,0)=0))
	ORDER BY EMP.FirstName, EMP.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAppraisal].[pRptKPAEmployeeDetailsGet]
	@rKPAEmployeeId bigint,
	@rBatchId int = 0,
	@IsDisplayRating int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @ID bigint

	SELECT @ID = Id FROM sAppraisal.tKPAEmployee WHERE EmployeeId = @rKPAEmployeeId
	
	SELECT 
		 KED.Id AS KPAEmployeeDetailId
		,KED.KPAMeasureId AS [Type]
		,KED.IndicatorRemark AS Remarks
		,ISNULL(KMD.Title,'') AS TypeName
		,ISNULL(ER.BusinessHeadRating,0.00) AS BusinessHeadRating
		,KED.Id AS EmployeeDetailId
		,ISNULL(ERD.MyRating,0.00) AS MyRating
		,ISNULL(ERD.ManagerRating,0.00) AS ManagerRating
		,ISNULL(ERD.ManagerRemark,'') AS ManagerRemark
		,ISNULL(ERD.MyRemark,'') AS MyRemark
		,ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS EmployeeManager
		,ISNULL(EM1.FirstName + ' ' + EM1.LastName,'') AS EmployeeBusinessHead
		,ISNULL(KTM.Id,0) AS KPATypeId
		,ISNULL(KTM.Title,'') AS KPATypeTitle
		,KED.Indicator
		,KED.Weightage
		,ISNULL((Select Title from sSetup.tBatchMaster Where Id = @rBatchId),'') AS BatchName
		,ISNULL((SELECT FirstName + ' ' + LastName FROM sHrm.tEmployeeMaster WHERE Id = @rKPAEmployeeId),'') AS EmployeeName
		,@IsDisplayRating AS IsDisplayRating
	FROM sAppraisal.tKPAEmployeeDetail AS KED
		INNER JOIN sAppraisal.tKPAEmployee KE ON KED.KPAEmployeeId = KE.Id
		INNER JOIN sAppraisal.tKPATypeMaster KTM ON KTM.Id = KED.KPATypeId
		INNER JOIN sAppraisal.tKPAEmployeeRating ER ON ER.KPAEmployeeId = KED.KPAEmployeeId
		INNER JOIN sAppraisal.tKPAEmployeeRatingDetail ERD ON ERD.KPAEmployeeRatingId = ER.Id AND ERD.KPAEmployeeDetailId =  KED.Id
		INNER JOIN sAppraisal.tKPAMeasureMaster AS KMD ON KMD.Id=KED.KPAMeasureId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = KE.EmployeeId
		LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeManagerId
		LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = EJD.EmployeeBusinessHeadId
	WHERE  KED.KPAEmployeeId=@ID
	ORDER BY KED.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAppraisal].[pRptTeacherPerformanceGet]
    
    @rBatchId int,
    @rEmployeeId bigint,
	@rAppraisalTypeId int,
	@rKPAStatus tinyint,
	@rOrgGroupDeptId int,
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rOrgId smallint
    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			  
		SELECT
			  EM.Id AS EmployeeId,
			  ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS EmployeeName,
			  ISNULL(EM1.FirstName + ' ' + EM1.LastName,'') AS EmployeeManagerName,
			  ISNULL(EM2.FirstName + ' ' + EM2.LastName,'') AS EmployeeBusinessHeadName,
			  ISNULL(EM3.FirstName + ' ' + EM3.LastName,'') AS OrgInchargeName,
			  ISNULL([sAppraisal].[fClassTeacherGet](EM.Id),'') AS ClassTeacher,
			  ISNULL([sAppraisal].[fTeacherSujectClassGet](EM.Id),'') AS ClassSubject,
			  ISNULL(KPAD.Indicator,'') AS Indicator,
			  ISNULL(KPAD.Weightage,0.0) AS Weightage,
			  ISNULL(KTM.Code,'') AS KPAType,
			  ISNULL(KER.BusinessHeadRating,0.0) AS BusinessHeadRating,
			  ISNULL(ERD.ManagerRating,0.0) AS ManagerRating,
			  ISNULL(KER.BusinessHeadRecommendationDesignation,'') AS BHReview,
			  ISNULL((Select Title from sSetup.tBatchMaster Where Id = @rBatchId),'') AS BatchName,
			  ISNULL(KPAD.Id,0) AS KPAId,
			  -- Mantis Start - 0033855
			  ISNULL(ERD.MyRating,0.0) AS EmployeeRating,
			  ISNULL(KER.Remark,'') AS EmployeeRemark
			  -- Mantis End - 0033855
		
		FROM
			  sHrm.tEmployeeMaster EM
			  INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = EM.Id 
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			  INNER JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = EJD.EmployeeManagerId
			  INNER JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = EJD.EmployeeBusinessHeadId
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			  INNER JOIN sHrm.tEmployeeMaster EM3 ON EM3.Id = OM.EmployeeId
			  LEFT JOIN sAppraisal.tKPAEmployee KPA ON KPA.EmployeeId=EM.Id AND KPA.BatchId = @rBatchId
			  LEFT JOIN sAppraisal.tKPAEmployeeDetail KPAD ON KPAD.KPAEmployeeId=KPA.Id 
			  LEFT JOIN sAppraisal.tKPATypeMaster KTM ON KTM.Id = KPAD.KPATypeId  AND ((KTM.Id = @rKPAStatus) OR (@rKPAStatus = 0))
			  LEFT JOIN sAppraisal.tKPAEmployeeRating KER ON KER.KPAEmployeeId=KPA.Id AND KER.AppraisalTypeId = @rAppraisalTypeId
			  LEFT JOIN sAppraisal.tKPAEmployeeRatingDetail ERD ON ERD.KPAEmployeeRatingId = KER.Id AND ERD.KPAEmployeeDetailId =  KPAD.Id
			  LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.OrgGroupId = OM.OrgGroupId AND OGDM.Id = @rOrgGroupDeptId
		WHERE
			  ((EM.Id = @rEmployeeId) OR (@rEmployeeId = 0)) 
			  AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
			  AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			  AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
			  AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
			  AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
			  AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
			  AND (ECD.GenderId = @rGenderId OR @rGenderId = 0) 
		ORDER BY
			  EM.Id
			  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[ExamSettingApplyAllClassUpdate]
	 
			@rBatchId int
			,@rExamSubGroupId int           
			,@rClassId int
			,@rIsRankNo bit
			,@rIsGrade bit
			,@rIsPercentile bit
			,@rIsPercentage bit
			,@rIsSubjectPercentile bit
			,@rGradeSetId int
			,@rIsProcessResult bit
			,@rIsMarkInDecimal bit
			,@rIsNegativeMarks bit
			,@rIsPrePrinted bit
			,@rIsDisplayBirthDate bit
			,@rIsDisplayPhoto bit
			,@rIsDisplayschoolName bit
			,@rIsIncludeCoScholastic bit
			,@rIsLockForEdit bit
			,@rRemark1 nvarchar(1000)
			,@rRemark2 nvarchar(300)
			,@rDisplayTitle nvarchar(150)
			,@rFooterAdjustment smallint
			,@rReportId smallint
			,@rRemark3 nvarchar(300)
			,@rIsDisplayHeightWeight bit
			,@rIsDisplayAttendance bit
			,@rIsDisplayResultStatus bit
			,@rDetailAdjustment smallint
			,@rTermScopeId smallint
			,@rMaximumMark Decimal
			,@rOrgId int,
			@rCoScholasticScopeId smallint,
			@rCoScholasticGradeSet int,
			@rPercentileScope smallint,
			@rIsDisplayTeacherSign bit,
			@rIsDisplayPrincipalSign bit,
			@rSubjectGroupPerPage smallint,
			@rIsExcludeAbsentTotal bit,
			@rDecimalUpto nvarchar(10),
			@rIsShowTotalMark bit=0,
			@rRemark1Caption nvarchar(100),
			@rRemark2Caption nvarchar(100),
			@rRemark3Caption nvarchar(100),
			@rTeacherSignCaption nvarchar(100),
			@rPrincipalSignCaption nvarchar(100),
			@rParentSignCaption nvarchar(100),
			@rIsAllExamPassRequired bit=0 , 
			@rIsGenerateRankNo bit = 0,
			@rResultSheetAdditionalTitle nvarchar(100)='',
			@rDisplayAttendanceId Smallint=0,
			@rReportHeaderId smallint=0,
			@rIsFailPercentageZero bit = 0,
			@rIsDisplayParentName bit = 0,
			@rIsDisplayGradeString bit = 0,
			@rIsShowResultIndicator bit = 0,
			@rIsDisplayHighestDivisionMark bit = 0,
			@rIsDisplayHighestDivisionGrade bit = 0,
			@rIsDisplayActivityGrade bit = 0,
			@rIsDisplayImageHeader bit = 0			-- MantisId : 0038303

			WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	IF (@rTermScopeId < 0)
	SET @rTermScopeId = 0
	
	
	
	 BEGIN		
	    UPDATE  [sAssessment].[tExamMaster]
	    SET
			    IsRankNo=@rIsRankNo 
			   ,IsGrade=@rIsGrade 
			   ,IsPercentile =@rIsPercentile 
			   ,IsSubjectPercentile = @rIsSubjectPercentile
			   ,IsPercentage=@rIsPercentage 
			   ,GradeSetId =@rGradeSetId 
			   ,IsProcessResult = @rIsProcessResult
			   ,IsMarksInDecimal = @rIsMarkInDecimal			   
			   ,IsNegativeMarks = @rIsNegativeMarks
			   
			   ,IsOnPrePrinted = @rIsPrePrinted
			   ,IsDisplayBirthDate=@rIsDisplayBirthDate
			   ,IsDisplayPhoto=@rIsDisplayPhoto
			   ,IsDisplaySchoolName=@rIsDisplayschoolName
			   ,IsIncludeCoScholastic=@rIsIncludeCoScholastic
			   ,IsLockForEdit=@rIsLockForEdit
			   ,IsDisplayAttendance=@rIsDisplayAttendance
			   ,IsDisplayHeightWeight=@rIsDisplayHeightWeight
			   ,IsResultStatus=@rIsDisplayResultStatus
			   ,Remark1=@rRemark1
			   ,Remark2=@rRemark2
			   ,Remark3=@rRemark3
			   ,DisplayTitle=@rDisplayTitle
			   ,FooterAdjustment=@rFooterAdjustment
			   ,DetailAdjustment=@rDetailAdjustment
			   ,ReportId = @rReportId
			   ,TermScopeId=@rTermScopeId
			   ,ExamMaximum=@rMaximumMark,
			   CoScholasticScopeId=@rCoScholasticScopeId,
			   coscholasticgradesetid = @rCoScholasticgradeset,
			   percentilescopeid=@rpercentilescope,
			   isdisplayteachersign = @rIsdisplayteachersign,
			   isdisplayprincipalsign = @risdisplayprincipalsign,
			   SubjectGroupPerPage = @rSubjectGroupPerpage,
			   IsExcludeAbsentTotal = @rIsExcludeAbsentTotal,
			   DecimalFormat = @rDecimalUpto,
			   IsDisplayTotalMark = @rIsShowTotalMark,
			   Remark1Caption=@rRemark1Caption,
			   Remark2Caption=@rRemark2Caption,
			   Remark3Caption=@rRemark3Caption,
			   TeacherSignCaption = @rTeacherSignCaption,
			   PrincipalSignCaption =@rPrincipalSignCaption,
			   ParentSignCaption =@rParentSignCaption,
			   IsAllExamPassRequired =@rIsAllExamPassRequired,
			   IsGenerateRankNo = @rIsGenerateRankNo,
			   ResultSheetAdditionalTitle=@rResultSheetAdditionalTitle,
			   DisplayAttendanceId=@rDisplayAttendanceId,
			   ReportHeaderId=@rReportHeaderId,
			   IsRemovePercentageForFail=@rIsFailPercentageZero,
			   IsDisplayParentName=@rIsDisplayParentName,
			   IsDisplayGradeString=@rIsDisplayGradeString,
			   IsDisplayResultIndicator = @rIsShowResultIndicator,
			   IsDisplayHighestDivisionMark=@rIsDisplayHighestDivisionMark,
			   IsDisplayHighestDivisionGrade=@rIsDisplayHighestDivisionGrade,
			   IsDisplayActivityGrade =@rIsDisplayActivityGrade,
			   IsDisplayImageHeader = @rIsDisplayImageHeader			-- MantisId : 0038303
             
	      WHERE ClassId = @rClassId AND ExamSubGroupId=@rExamSubGroupId AND BatchId = @rBatchId
	      
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAbsentStudentExamWiseSubjectListGet]
	 @rClassId int,
	 @rExamID int,
	 @rSubjectId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
		A.RollNO,
		SB.Title As SubjectName
	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN [sSetup].[tClassMaster] CM ON CM.Id=A.ClassID
			INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			INNER JOIN sSetup.tSubjectMaster SB ON SB.Id = CS.SubjectId
			INNER JOIN sAttendance.tStudentRegister Reg ON Reg.AcademicId=A.Id AND Reg.SubjectId=SB.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id	AND ED.ExamId = @rExamID
			  
			
	Where (A.Classid=@rClassId)
	AND ED.ExamID=@rExamId 	    
	AND SB.Id=@rSubjectId
			order by CS.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAbsentStudentListGet]
	
	 @rAcademicId bigint=0,
	 --@rStudentId bigint=0,
	 @rBatchId int=0,
	 @rExamId int=0,
	 @rExamGroupId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

IF(@rExamGroupId>0)
BEGIN
	SELECT	
	AD.Id AS AcademicId,
	EM.Id AS ExamId,
	SBM.Id AS SubjectId,
	ESGM.Title AS ExamName,
	RD.Id AS ResultDetailId,
	SBM.Title AS SubjectName,	
	RD.IsPresent AS IsPresent		
	
	from
	sStudent.tStudentMaster SM
	INNER JOIN sStudent.tAcademic AD ON SM.Id = AD.StudentId
	INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id
	INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId
	INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	
	Where
	((AD.Id=@rAcademicId) OR (@rAcademicId=0))
	--AND((AD.StudentId = @rStudentId) OR (@rStudentId=0))
	AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
	--AND ((EM.Id=@rExamId) OR (@rExamId=0))
	AND ((ESGM.ExamGroupId=@rExamGroupId) OR (@rExamGroupId=0))
	AND RD.IsPresent=0
	order by  ExamId
 END
 ELSE
 BEGIN
	SELECT	
	AD.Id AS AcademicId,
	EM.Id AS ExamId,
	SBM.Id AS SubjectId,
	ESGM.Title AS ExamName,
	RD.Id AS ResultDetailId,
	SBM.Title AS SubjectName,	
	RD.IsPresent AS IsPresent		
	
	from
	sStudent.tStudentMaster SM
	INNER JOIN sStudent.tAcademic AD ON SM.Id = AD.StudentId
	INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id
	INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId
	INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	
	Where
	((AD.Id=@rAcademicId) OR (@rAcademicId=0))
	--AND((AD.StudentId = @rStudentId) OR (@rStudentId=0))
	AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
	AND ((EM.Id=@rExamId) OR (@rExamId=0))
	--AND ((ESGM.ExamGroupId=@rExamGroupId) OR (@rExamGroupId=0))
	AND RD.IsPresent=0
 order by  ExamId
 END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAssessment].[pActivityDefaultAdd]
	 @rStrXml [nvarchar](max),
	 @rOrgId int	
AS
BEGIN
 
	SET NOCOUNT ON;
	SET @rStrXml=REPLACE(@rStrXml,'&','AND')
	DECLARE @loDoc INT
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN 
	 BEGIN	
		if exists(select 1 
		FROM sAssessment.tCCESubjectSubActivityExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
						AcademicId bigint,
						SubjectSubActivityId int,
						ExamId int,
						Term1Grade nvarchar(20),
						GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.SubjectSubActivityId = AI.SubjectSubActivityId 
		)
		BEGIN
		SELECT 1 AS Result
			return
			 
		END
		Else
		
		INSERT INTO  sAssessment.tCCESubjectSubActivityExamScore
			(ExamId,AcademicId,SubjectSubActivityId,Grade,GradeIndicator)
			
			SELECT	
			A.ExamId,A.AcademicId,A.SubjectSubActivityId,Term1Grade,GradeTitle
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,					
					Term1Grade nvarchar(20),
					GradeTitle nvarchar(50),
					SubjectSubActivityId int
				  ) A  LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.SubjectSubActivityId = AI.SubjectSubActivityId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.SubjectSubActivityId IS NULL)
			  
 			SELECT 1 AS Result
	END		
	 
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pActivityIndicatorScoreAdd]

			@rAcademicId bigint
			,@rExamId int
			,@rSubActivityId int
			,@rGrade nvarchar(10),
			@rGradeIndicator nvarchar(50)
			,@rDescriptiveIndicator nvarchar(200)
			,@rIndicatodIds nvarchar(50),
			@rMarks decimal(18,0)
			,@rIsIndicatodIds bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRANSACTION	--add for mantis: 39511
		IF NOT EXISTS(SELECT SubjectSubActivityId FROM sAssessment.tCCESubjectSubActivityExamScore WHERE SubjectSubActivityId=@rSubActivityId AND  AcademicId=@rAcademicId AND ExamId = @rExamId)
		BEGIN
			INSERT INTO sAssessment.tCCESubjectSubActivityExamScore
			(
				[ExamId]
				,[AcademicId],
				SubjectSubActivityId
				,[Grade]
				,[GradeIndicator]
				,[DescriptiveIndicator]
				,[IndicatorIds],
				Marks
			)
			VALUES
			(
				@rExamId
				,@rAcademicId
				,@rSubActivityId
				,@rGrade
				,@rGradeIndicator
				,@rDescriptiveIndicator
				,@rIndicatodIds,
				@rMarks
			)
		END
		ELSE
		BEGIN
			UPDATE  [sAssessment].[tCCESubjectSubActivityExamScore]
			SET
				[AcademicId]=@rAcademicId
				,[ExamId] =@rExamId
				,[Grade]=@rGrade
				,[GradeIndicator] =@rGradeIndicator
				,DescriptiveIndicator=@rDescriptiveIndicator
				,IndicatorIds = @rIndicatodIds,
				Marks= @rMarks
			WHERE SubjectSubActivityId=@rSubActivityId AND AcademicId=@rAcademicId AND ExamId =@rExamId
		END

		if @rIsIndicatodIds = 1
		BEGIN
			Declare @lQuery Nvarchar(max)
			SET @lQuery = 'UPDATE A SET A.DescriptiveIndicator = 
 							stuff((select '','' + B.Title from sAssessment.tCCESubjectSubActivityIndicatorMaster B
						WHERE A.SubjectSubActivityId=B.CCESubjectSubActivityId
								and '',''+ (replace(IndicatorIds,''.'','','') )+'','' like ''%,''+CAST(Number as varchar(10))+'',%'' 				
						for xml path('''')),1,1,'''') 
				 From sAssessment.tCCESubjectSubActivityExamScore A WHERE A.SubjectSubActivityId='+ CAST(@rSubActivityId AS NVARCHAR(50)) +' 
				 AND A.AcademicId= '+ CAST (@rAcademicId  AS NVARCHAR(50))+'
				  AND A.ExamId ='+ CAST(@rExamId AS NVARCHAR(50))

			EXECUTE (@lQuery)
		END

		SELECT 1 AS Result
	COMMIT TRANSACTION

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pActivityIndicatorScoreGet]
	  @rAcademicId bigint
	  ,@rOrgId int
	  ,@rExamId int,
	  @rClassSubjectId int 
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
 
			SELECT 	
			
				
					SAM.Id AS ActivityId,
					SSA.Id AS SubActivityId,
					--AIM.Id AS SubjectIndicatorId,
					ISNULL(SAM.Title,'') AS ActivityTitle,
					ISNULL(SSA.Title,'')AS SubActivityTitle, 
					--ISNULL(AIM.Title,'')AS IndicatorTitle, 
					
					
					ISNULL(SEC.Grade,'') AS Grade,
					ISNULL(SEC.GradeIndicator,'')AS GradeIndicator,
					ISNULL(SEC.DescriptiveIndicator,'')  AS DescriptiveIndicator,			
					ISNULL(SEC.IndicatorIds,'') AS Indicator,
					ISNULL(SEC.Marks,0) AS Marks,
					ISNULL(SAM.GradeSetId,0) AS GradeSetId ,
					--ISNULL(AIM.GradeSetDetailId,0) AS GradeSetDetailId,
					ISNULL(SA.Id,0) AS AcademicId ,
					ISNULL(SEC.ExamId,0) AS ExamId ,
					SAM.ClassSubjectId,
					CS.suBJECTNAME ,
					SA.batchid
					
						
			FROM  
				 sStudent.tAcademic SA 
				 INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassID=SA.ClassID
				INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.ClassSubjectID=	CS.ClassSubjectId
				INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId		 
				LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id	AND SEC.AcademicId=@rAcademicId  AND SEC.ExamId=@rExamId 			
				LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.Id and o.ClassSubjectId=CS.ClassSubjectId  
			    AND SA.Id =@rAcademicId 
				  --AND SEC.ExamId=@rExamId 
				
		where 
		
			SSA.OrgId=@rOrgId
			  AND SAM.ClassSubjectId=@rClassSubjectId
			 AND SA.Id=@rAcademicId
			 AND ((CS.IsOptional = 1 AND  isnull(o.AcademicId,0)<>0) OR (CS.IsOptional = 0))
			 AND SAM.IsObsolete = 0
			   
			Order by SAM.orderIndex
			
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pAddZeroMarksForAllExams]

	 @rExamId int,	
	 @rAcademicId bigint,
	 @rUserId bigint,
	 @rOrgId int,
	 @rClassId int,
	 @rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

CREATE TABLE #AllExams
(
ExId int IDENTITY,
ExamIds int
)
INSERT INTO #AllExams
(
ExamIds
)
SELECT  EM.Id  FROM [sAssessment].[tExamMaster] EM 
		INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

INSERT INTO #AllExams
(
ExamIds
)
SELECT EM.Id   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

DECLARE @lCountExamId int,@EId int,@lExamId int

SELECT @lCountExamId=COUNT(ExId) FROM #AllExams
	SELECT Top 1 @EId=ExId FROM #AllExams
	
		WHILE @EId <= @lCountExamId
			BEGIN
			SELECT @lExamId=ExamIds FROM #AllExams WHERE ExId=@EId
			
				IF EXISTS (SELECT 1 FROM [sAssessment].[tResult] WHERE ExamId=@lExamId)
				BEGIN
				--DELETE FROM [sAssessment].[tResult] WHERE ExamId=@lExamId AND AcademicId=@rAcademicId
						IF NOT EXISTS (SELECT 1 FROM [sAssessment].[tResult] WHERE ExamId=@lExamId AND AcademicId=@rAcademicId)
							BEGIN
							 
							DECLARE @lResultId BIGINT
							EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lResultId output
							
							INSERT INTO [sAssessment].[tResult]
								(
									Id,
									AcademicId,
									ExamId,
									TotalMarks,
									TotalObtain,
									ResultStatus,
									ResultGrade,
									ResultIndicator,
									ResultGradePoint,
									RankNumber,
									Percentage,
									Percentile,
									ResultRemark,
									OtherRemark1,
									UpdatedUserId,
									UpdatedDateTime

								)
							VALUES
								(
									@lResultId,
									@rAcademicId,
									@lExamId,
									0,
									0,
									'',
									'',
									'',
									0,
									0,
									0,
									0,
									'',
									'',
									@rUserId,
									GETDATE()
								)
								END
								CREATE TABLE #tempExamDetail
								(	
									Id int IDENTITY,
									ExamDetailId int 
								)
							DELETE FROM #tempExamDetail
							INSERT INTO #tempExamDetail
							(
								ExamDetailId
							)
							SELECT Id AS ExamDetailId FROM [sAssessment].[tExamDetail] WHERE ExamId=@lExamId
								
								DECLARE @lCountExamDetailId INT,@Id INT,@lExamDetailId INT

								Select @lCountExamDetailId=COUNT(Id) from #tempExamDetail
								Select Top 1 @Id=Id from #tempExamDetail
						
		                 WHILE @Id <= @lCountExamDetailId
							BEGIN
								 SELECT @lResultId=Id FROM [sAssessment].[tResult] WHERE ExamId=@lExamId AND AcademicId=@rAcademicId
								 --DELETE  FROM [sAssessment].[tResult] WHERE ExamId=@lExamId AND AcademicId=@rAcademicId
								DECLARE @lResultDetailId BIGINT
								
								SELECT @lExamDetailId=ExamDetailId from #tempExamDetail WHERE Id=@Id
								
								EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lResultDetailId output
							--DELETE  FROM [sAssessment].[tResultDetail] WHERE ResultId=@lResultId AND ExamDetailId=@lExamDetailId
							If NOT EXISTS(SELECT 1 FROM [sAssessment].[tResultDetail] WHERE ResultId=@lResultId AND ExamDetailId=@lExamDetailId)
								--Select 1
								BEGIN
									
								INSERT INTO  [sAssessment].[tResultDetail] 
								(
									Id,
									ResultId,
									ExamDetailId,
									Obtain,
									IsPresent,
									Remark,
									SubjectGrade,
									SubjectGradePoint,
									Percentile,
									GraceMark,
									KrupaMark
								)
								VALUES( 
									@lResultDetailId,
									@lResultId,
									@lExamDetailId,
									0,
									0,
									'',
									'',
									0,
									0,
									0,
									0)
								END
							
								SET @Id=@Id+1

							--END
							END
							DROP TABLE #tempExamDetail
								
					END			
	
					SET @EId=@EId+1
				
			END



		DROP TABLE #AllExams
	
		--DROP TABLE #ExamTemp

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pAllBatchClassGroupAdd]
	 
        @rOrgId smallint,
		@rClassXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rClassXml
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
	BEGIN
	DELETE FROM sAssessment.tAllBatchClassGroup WHERE OrgId=@rOrgId
	INSERT INTO sAssessment.tAllBatchClassGroup
		(
			OrgId,
			ClassGroupId
		)
		SELECT
		   @rOrgId,
			ClassGroupId
		FROM OPENXML (@loDoc, '/Table/AssignClass', 1)
		WITH (  
				ClassGroupId int
			  ) 
			  SELECT 1 AS Result
	END	 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pAllBatchClassGroupGet]
	 
        @rOrgId smallint
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	SELECT CM.Id AS ClassGroupId ,
	CM.Title AS ClassGroupName,
	CASE  WHEN BG.ClassGroupId IS null THEN 0 Else 1 END AS IsObsolete
	 FROM sSetup.tClassGroupMaster CM
	 LEFT JOIN  sAssessment.tAllBatchClassGroup BG  ON CM.Id=BG.ClassGroupId
	AND BG.OrgId=@rOrgId
	WHERE CM.Id In (103,101,102,104,1,2,3,4,5,6,7,8,9,10,11,12)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pAllBatchSubjectAdd]
	 
        @rOrgId smallint,
		@rSubjectXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rSubjectXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	BEGIN
	DELETE FROM sAssessment.tAllBatchSubject WHERE OrgId=@rOrgId
	INSERT INTO sAssessment.tAllBatchSubject
		(
			OrgId,
			SubjectId
		)
	SELECT
		   @rOrgId,
			SubjectId
		FROM OPENXML (@loDoc, '/Table/AssignSubject', 1)
		WITH (  
				SubjectId int
			  ) 
	
	SELECT 1 AS Result
	END	 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pAllBatchSubjectGet]
	 
        @rOrgId smallint
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	SELECT SM.Id AS SubjectId ,
	SM.Title AS SubjectName,
	CASE  WHEN BS.SubjectId IS null THEN 0 Else 1 END AS IsObsolete
	 FROM sSetup.tSubjectMaster SM
	 LEFT JOIN  sAssessment.tAllBatchSubject BS  ON SM.Id=BS.SubjectId
	WHERE  SM.OrgId=@rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pAPICCESubjectActivityExamScoreAdd]
	 	
	@rDetails [nvarchar](max),
	@rCCEExamId int,
	@rSubjectActivityId int,
	@rClassId int,
	@rBatchId int
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rDetails=REPLACE(@rDetails,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDetails

BEGIN 
	declare @lDataSetID int,@lCount int,@MinimumScore decimal(5,2),@GradeTitle nvarchar(10),@lCountTemp int,
			@lAcademicId Bigint,@lSubjectActivityId int,@lExamId int,@lMark decimal(10,2)
	 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCESubjectActivityMaster WHERE  Id=	@rSubjectActivityId	
	 
		if exists(select 1 from sAssessment.tCCESubjectActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectActivityId int, 
							ExamId int
					 )
					 A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=@rCCEExamId
			AND AI.SubjectActivityId =@rSubjectActivityId )
	 BEGIN	
		UPDATE AI SET AI.Marks = Mark FROM sAssessment.tCCESubjectActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectActivityId int,--CCECSId int,
							ExamId int,
							Mark decimal(10,2)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=@rCCEExamId
			AND AI.SubjectActivityId = @rSubjectActivityId
			 --AND A.CCECSId = AI.CCECSId 
			
			
			
			 
		END
	else
	BEGIN	
		INSERT INTO sAssessment.tCCESubjectActivityExamScore
			(ExamId,AcademicId,SubjectActivityId,Marks)
			
			SELECT	@rCCEExamId,AcademicId,@rSubjectActivityId,Mark
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					AcademicId Bigint,					
					Mark decimal(10,2)--CCECSId int
				  ) A 	
			 --A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCESubjectActivityExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND SubjectActivityId=AM.Id)
	     SELECT 1 AS Result
	     
	END 
 
 CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(20),
		GradePoint decimal(6,2) 					 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,GradeCode,GradePoint		
	FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	order by MinimumScore DESC
	
	Select @lCount= count(id) from #tempGradeSetDetail
	while (@lCount>0)
	BEGIN
	 Select @MinimumScore =MinimumScore,@GradeTitle=GradeTitle from #tempGradeSetDetail Where Id=@lCount
	 UPDATE AI SET AI.Grade = @GradeTitle FROM sAssessment.tCCESubjectActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectActivityId int,--CCECSId int,
							ExamId int,
							Mark decimal(10,2)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=@rCCEExamId
			AND AI.SubjectActivityId = @rSubjectActivityId
			AND A.Mark >=@MinimumScore 
			
		 Set @lCount=@lCount-1	  			
		END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pAPICSExamGradeAdd]
	 	
	@rStrXml [nvarchar](max)
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
	 BEGIN	
		UPDATE AI 
		SET AI.Grade = Term1Grade,
		AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCECSExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						Term1Grade nvarchar(20),
						GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId 
		
		INSERT INTO sAssessment.tCCECSExamScore
			(ExamId,AcademicId,CCECSId,Grade,GradeIndicator)
			
			SELECT	
			A.ExamId,A.AcademicId,A.CCECSId,Term1Grade,GradeTitle
         			
			FROM OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,					
					Term1Grade nvarchar(20),
					GradeTitle nvarchar(50),
					CCECSId int
				  ) A  LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
	
 	 SELECT 1 AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAPICSExamGradeGet]
	  @rClassId bigint,
	  @rDivisionId Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
CREATE TABLE #OptionalSubjecttmp
(
AcademicId bigint,
CCECSId int,
Selected bit,
IsOptional bit
)
INSERT INTO #OptionalSubjecttmp	
SELECT 
SS.AcademicId,
CM.Id AS CCECSId,
--CM.Title AS ActivityName,
CASE WHEN isnull(OCES.CCECSId,0) <> 0 THEN 'true' ELSE 'false' END AS Selected,
CASE WHEN ISNULL(SS.IsOptional,0)=0 then 'false' ELSE 'true' END AS IsOptional
FROM
(SELECT
SA.AcademicId,
CS.CCECSId as CCECSId,
CS.IsOptional

FROM
 (select * FROM sStudent.vStudentAcademic where DivisionId=@rDivisionId AND StatusId=1 AND BatchId=@rBatchId )SA  
 CROSS JOIN    (select * FROM sAssessment.tCCECSForClass B   WHERE  B.ClassId = @rClassId and BatchId=@rBatchID ) AS CS 
 ) AS SS
 INNER JOIN sAssessment.tCCECSMaster CM ON SS.CCECSId = Cm.Id 
 LEFT JOIN sAssessment.tOptionalCCECS OCES ON OCES.AcademicId = SS.AcademicId AND OCES.CCECSId = SS.CCECSId
 Where CM.CCECAGroupId= @rCCECSGroupId
 AND ((CM.Id = @rCCECSId  OR @rCCECSId = 0))

SELECT 
	SA.AcademicId,
	SA.RollNo,
	SA.Code As Number,
	SA.Name,  
	AM.Title, 
	ISNULL(AIS.Grade,'') AS CoScholasticActivityGrade,
	ISNULL(GSD.Id,0) AS GradeId,
	tmp.Selected,
	tmp.IsOptional
FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.CCECSGroupId = @rCCECSGroupId AND CA.BatchID = @rBatchID
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID = @rClassId  AND CL.BatchId=@rBatchId
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= @rExamId
	INNER JOIN sAssessment.vCCECSGROUPMASTER GM ON GM.Id = CA.CCECSGroupId AND GM.ClassId = CA.ClassId AND GM.BatchId = CA.BatchID
	LEFT JOIN sAssessment.tGradeSetDetail GSD ON GSD.GradeSetId = GM.GradeSetId AND GSD.GradeCode = AIS.Grade
	INNER JOIN #OptionalSubjecttmp tmp ON tmp.AcademicId = SA.AcademicId AND tmp.CCECSId = AM.Id
WHERE 
	SA.ClassId= @rClassId
	And SA.DivisionId = @rDivisionId
	And SA.BatchId = @rBatchId 
	And AM.CCECAGroupId= @rCCECSGroupId
	AND ((AM.Id = @rCCECSId  OR @rCCECSId = 0))
	Order By SA.RollNo ASC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pAPICSEXamIndicatorAdd]
	 	
	@rStrXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT

			  	
					 
			UPDATE AI SET AI.IndicatorIds = Replace(Term1Indicator,',','.') FROM sAssessment.tCCECSExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/CSEXamIndicator', 1)
				WITH ( 				
							AcademicId Bigint,
							CCECSId int,
							ExamId int,
							Term1Indicator NVARCHAR(20)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
			AND A.CCECSId = AI.CCECSId 
			 --INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id = @rORGId	
		 
		INSERT INTO sAssessment.tCCECSExamScore
			(AcademicId,CCECSId,ExamId,IndicatorIds)
			
			SELECT	A.AcademicId,A.CCECSId,A.ExamId,Replace(Term1Indicator,',','.') 
         			
			FROM OPENXML (@loDoc, '/Table/CSEXamIndicator', 1)
			WITH ( 			
					AcademicId Bigint,
					CCECSId int,	
					ExamId int,
					Term1Indicator nvarchar(20) 
					 
				  ) A 	
			LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
			
			--sAssessment.tCCECSMaster AM ON AM.Id = A.CCECSId 			
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AM.OrgId AND OM.Id = @rORGId
			--AND A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCECSExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND CCECSId=AM.Id)
	     
	
    -- Updated by Kp
	UPDATE A SET A.DescriptiveIndicator = 
 					stuff((select ',' + B.Title from sAssessment.tCCECSIndicatorMaster B
				WHERE A.CCECSid=B.CCECSId 
						and ','+ (replace(IndicatorIds,'.',',') )+',' like '%,'+CAST(Number as varchar(10))+',%'				
				for xml path('')),1,1,'') 
         From sAssessment.tCCECSExamScore A    
         INNER JOIN      			
			OPENXML (@loDoc, '/Table/CSEXamIndicator', 1)
			WITH ( 		
					AcademicId Bigint,	
					CCECSId int,	
					ExamId int,
					Term1Indicator nvarchar(20) 
					 
				  )B1
				  ON A.ExamId=B1.ExamId AND A.AcademicId = B1.AcademicId AND B1.CCECSId = A.CCECSId 
	
	 SELECT 1 AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAPICSExamIndicatorGet]
	  @rClassId bigint,
	  @rDivisionId Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
CREATE TABLE #OptionalSubjecttmp
(
AcademicId bigint,
CCECSId int,
Selected bit,
IsOptional bit
)
INSERT INTO #OptionalSubjecttmp	
SELECT 
SS.AcademicId,
CM.Id AS CCECSId,
--CM.Title AS ActivityName,
CASE WHEN isnull(OCES.CCECSId,0) <> 0 THEN 'true' ELSE 'false' END AS Selected,
CASE WHEN ISNULL(SS.IsOptional,0)=0 then 'false' ELSE 'true' END AS IsOptional
FROM
(SELECT
SA.AcademicId,
CS.CCECSId as CCECSId,
CS.IsOptional

FROM
 (select * FROM sStudent.vStudentAcademic where DivisionId=@rDivisionId AND StatusId=1 AND BatchId=@rBatchId )SA  
 CROSS JOIN    (select * FROM sAssessment.tCCECSForClass B   WHERE  B.ClassId = @rClassId and BatchId=@rBatchID ) AS CS 
 ) AS SS
 INNER JOIN sAssessment.tCCECSMaster CM ON SS.CCECSId = Cm.Id 
 LEFT JOIN sAssessment.tOptionalCCECS OCES ON OCES.AcademicId = SS.AcademicId AND OCES.CCECSId = SS.CCECSId
 Where CM.CCECAGroupId= @rCCECSGroupId
 AND ((CM.Id = @rCCECSId  OR @rCCECSId = 0))

SELECT 
	SA.AcademicId,
	SA.RollNo,
	SA.Code As Number,
	SA.Name,
	AM.Title,	 
	ISNULL(AIS.IndicatorIds,'') AS CoScholasticActivityIndicator,
	tmp.Selected,
	tmp.IsOptional
FROM sStudent.vStudentAcademic SA
INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID = @rBatchID
INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID = @rClassId ANd CL.BatchId = @rBatchID
LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= @rExamId AND (AIS.CCECSId = @rCCECSId OR @rCCECSId = 0 ) 
INNER JOIN #OptionalSubjecttmp tmp ON tmp.AcademicId = SA.AcademicId AND tmp.CCECSId = AM.Id
WHERE SA.ClassId = @rClassId
And SA.DivisionId = @rDivisionId	
And SA.BatchId = @rBatchId	
And AM.CCECAGroupId= @rCCECSGroupId
AND ((AM.Id = @rCCECSId) OR(@rCCECSId = 0))
Order By SA.RollNo ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAPICSExamMarkEntryGet]
	  @rClassId bigint,
	  @rDivisionId Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0
	  --@rFilter int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

CREATE TABLE #OptionalSubjecttmp
(
AcademicId bigint,
CCECSId int,
Selected bit,
IsOptional bit
)
INSERT INTO #OptionalSubjecttmp	
SELECT 
SS.AcademicId,
CM.Id AS CCECSId,
--CM.Title AS ActivityName,
CASE WHEN isnull(OCES.CCECSId,0) <> 0 THEN 'true' ELSE 'false' END AS Selected,
CASE WHEN ISNULL(SS.IsOptional,0)=0 then 'false' ELSE 'true' END AS IsOptional
FROM
(SELECT
SA.AcademicId,
CS.CCECSId as CCECSId,
CS.IsOptional

FROM
 (select * FROM sStudent.vStudentAcademic where DivisionId=@rDivisionId AND StatusId=1 AND BatchId=@rBatchId )SA  
 CROSS JOIN    (select * FROM sAssessment.tCCECSForClass B   WHERE  B.ClassId = @rClassId and BatchId=@rBatchID ) AS CS 
 ) AS SS
 INNER JOIN sAssessment.tCCECSMaster CM ON SS.CCECSId = Cm.Id 
 LEFT JOIN sAssessment.tOptionalCCECS OCES ON OCES.AcademicId = SS.AcademicId AND OCES.CCECSId = SS.CCECSId
 Where CM.CCECAGroupId= @rCCECSGroupId
 AND ((CM.Id = @rCCECSId  OR @rCCECSId = 0))


 SELECT 
	SA.RollNo,
	SA.Code As Number,
	SA.Name,
	AM.Title, 
	ISNULL(AIS.ObtianMark,0) AS CoScholasticActivityMark,
	SA.AcademicId,
	AM.Id AS CCECSId,
	tmp.Selected,
	tmp.IsOptional
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID=@rBatchId
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID=@rClassId AND CL.BatchId=@rBatchId
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= @rExamId  AND (AIS.CCECSId = @rCCECSId   OR @rCCECSId = 0 ) 
	INNER JOIN #OptionalSubjecttmp tmp ON tmp.AcademicId = SA.AcademicId AND tmp.CCECSId = AM.Id
	WHERE SA.ClassId=@rClassId
	AND SA.DivisionId = @rDivisionId
	AND SA.BatchId = @rBatchId
	AND AM.CCECAGroupId= @rCCECSGroupId
	AND ((AM.Id = @rCCECSId  OR @rCCECSId = 0))
	Order By SA.RollNo ASC


 DROP TABLE #OptionalSubjecttmp
--EXECUTE(@query)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pAPICSExamScoreSetupAdd]
	 	
	@rStrXml [nvarchar](max)
	--@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
	 BEGIN	
	 
	
		UPDATE AI 
		SET AI.ObtianMark = A.TotalMarks 
			--AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCECSExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						TotalMarks decimal(12,2) 
						 
						--GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId 
	
		INSERT INTO sAssessment.tCCECSExamScore
			(ExamId,AcademicId,CCECSId,ObtianMark )
			
			SELECT	
			A.ExamId,A.AcademicId,A.CCECSId,A.TotalMarks 
         			
			FROM OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,	
					CCECSId int,				
					TotalMarks decimal(12,2) 
					 
					--GradeTitle nvarchar(50),
					
				  ) A  LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
		
 	 SELECT 1 AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pAPISubjectActivityExamIndicatorAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT

			UPDATE AI SET AI.IndicatorIds = Replace(Term1Indicator,',','.') FROM sAssessment.tCCESubjectSubActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectSubActivityId int,--CCECSId int,
							ExamId int,
							Term1Indicator NVARCHAR(20)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
			AND A.SubjectSubActivityId = AI.SubjectSubActivityId--AND A.CCECSId = AI.CCECSId 
			INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id = @rORGId	
			  			
		
	
	BEGIN	
		INSERT INTO sAssessment.tCCESubjectSubActivityExamScore
			(ExamId,AcademicId,SubjectSubActivityId,IndicatorIds)
			
			SELECT	ExamId,AcademicId,AM.Id,Replace(Term1Indicator,',','.')
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId Bigint,					
					Term1Indicator nvarchar(20),
					SubjectSubActivityId int--CCECSId int
				  ) A 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster AM ON AM.Id = A.SubjectSubActivityId 			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AM.OrgId AND OM.Id = @rORGId
			AND A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCESubjectSubActivityExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND SubjectSubActivityId=AM.Id)
	     
	END
	
    -- Updated by Kp
	 UPDATE A SET A.DescriptiveIndicator = 
 					stuff((select ',' + B.Title from sAssessment.tCCESubjectSubActivityIndicatorMaster B 
				WHERE A.SubjectSubActivityId=B.CCESubjectSubActivityId 
						and ','+ (replace(IndicatorIds,'.',',') )+',' like '%,'+CAST(Number as varchar(10))+',%'				
				for xml path('')),1,1,'') 
         From sAssessment.tCCESubjectSubActivityExamScore A    
         INNER JOIN      			
			OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId Bigint,					
					Term1Indicator nvarchar(20),
					SubjectSubActivityId int
				  )B1
				  ON A.ExamId=B1.ExamId AND A.AcademicId = B1.AcademicId AND B1.SubjectSubActivityId = A.SubjectSubActivityId 
	
	   SELECT 1 AS Result
	END		
	 END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAPISubjectActivityExamIndicatorGet]
	  @rClassId bigint,
	  @rDivisionId Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0 --@rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

SELECT 
	SA.AcademicId,
	SA.RollNo,
	SA.Code AS Number,
	SA.Name,
	SSA.Title,	 
	ISNULL(SEC.IndicatorIds,'') AS ActivityIndicator
FROM  
	sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id AND SA.StatusId=1
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= @rExamId AND (SEC.SubjectSubActivityId = @rSubActivityId  OR @rSubActivityId = 0 )
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicID and o.ClassSubjectId=CS.ClassSubjectId  
	AND SEC.ExamId= @rExamId
WHERE  
	SSA.OrgId= @rOrgId 
	AND SAM.ClassSubjectId= @rClassId
	AND SSA.SubjectActivityId= @rSubjectActivityId
	AND SA.DivisionId= @rDivisionId
	And SA.BatchId = @rBatchId
	AND ((CS.IsOptional = 1 AND  isnull(o.AcademicId,0)<>0) OR (CS.IsOptional = 0))
	AND SSA.Id = @rSubActivityId
	Order By SA.RollNo ASC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pAPISubjectActivityMarkEntryBulkAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN 
	 BEGIN	
		UPDATE AI SET AI.Marks = Mark FROM sAssessment.tCCESubjectSubActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectSubActivityId int,--CCECSId int,
							ExamId int,
							Mark decimal(10,2)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
			AND A.SubjectSubActivityId = AI.SubjectSubActivityId--AND A.CCECSId = AI.CCECSId 
			INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id = @rORGId	
			  			
		
	
	BEGIN	
		INSERT INTO sAssessment.tCCESubjectSubActivityExamScore
			(ExamId,AcademicId,SubjectSubActivityId,Marks)
			
			SELECT	ExamId,AcademicId,AM.Id,Mark
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId Bigint,					
					
					SubjectSubActivityId int,
					Mark decimal(10,2)--CCECSId int
				  ) A 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster AM ON AM.Id = A.SubjectSubActivityId 			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AM.OrgId AND OM.Id = @rORGId
			AND A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCESubjectSubActivityExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND SubjectSubActivityId=AM.Id)
	     SELECT 1 AS Result
	END
	
	 
	 
    END	
	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAPISubjectActivityMarkGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0, --@rCCECSId int=0,
	  @rSubjectId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

SELECT 
	SA.AcademicId,
	SA.RollNo,
	SA.Code AS Number,
	SA.Name,
	SSA.Title,	 
	ISNULL(SEC.Marks,'0') AS ActivityMark
FROM  
	sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= @rExamId
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=CS.ClassSubjectId
WHERE  
	SSA.OrgId= @rOrgId
	AND SSA.SubjectActivityId= @rSubjectActivityId
	AND SAM.ClassSubjectId= @rClassId
	AND SA.DivisionId= @rDivisionID
	And SA.BatchId = @rBatchId
	ANd CS.ClassSubjectId = @rSubjectId
	AND ((CS.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (CS.IsOptional = 0))
	AND SA.StatusId=1
	AND SSA.Id = @rSubActivityId
	Order By SA.RollNo ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pAPISubjectActivityScoreBulkAdd]
	 	
	@rStrXml [nvarchar](max)
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN 
	 BEGIN	
		UPDATE AI 
		SET AI.Grade = Term1Grade,
		AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCESubjectSubActivityExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
						AcademicId bigint,
						SubjectSubActivityId int,
						ExamId int,
						Term1Grade nvarchar(20),
						GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.SubjectSubActivityId = AI.SubjectSubActivityId 
		
		INSERT INTO  sAssessment.tCCESubjectSubActivityExamScore
			(ExamId,AcademicId,SubjectSubActivityId,Grade,GradeIndicator)
			
			SELECT	
			A.ExamId,A.AcademicId,A.SubjectSubActivityId,Term1Grade,GradeTitle
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,					
					Term1Grade nvarchar(20),
					GradeTitle nvarchar(50),
					SubjectSubActivityId int
				  ) A  LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.SubjectSubActivityId = AI.SubjectSubActivityId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.SubjectSubActivityId IS NULL)
	
 	 SELECT 1 AS Result
	END		
	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAPISubjectActivityScoreBulkGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0 --@rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

SELECT 
	SA.AcademicId,
	SA.RollNo,
	SA.Code AS Number,
	SA.Name,
	SSA.Title, 
	ISNULL(SEC.Grade,'') AS ActivityGrade,
	ISNULL(GSD.Id,0) AS GradeId
FROM  
	sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= @rExamId  AND (SEC.SubjectSubActivityId = @rSubActivityId  OR @rSubActivityId = 0 )
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicID and o.ClassSubjectId=CS.ClassSubjectId  
	AND SEC.ExamId = @rExamId 
    LEFT JOIN sAssessment.tGradeSetDetail GSD ON SAM.GradeSetId = GSD.GradeSetId AND GSD.GradeCode = SEC.Grade
WHERE  
	SSA.OrgId= @rOrgId
	AND SAM.ClassSubjectId= @rClassId
	AND SSA.SubjectActivityId= @rSubjectActivityId
	AND SA.DivisionId= @rDivisionID
	And SA.BatchId = @rBatchId
	AND SA.StatusID=1
	AND SSA.Id = @rSubActivityId
	Order By SA.RollNo ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pAssessmentAdminDelete]
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAcademicId bigint,	 
	 @rExamId int,
	 @rExamDetailId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	BEGIN TRY
	
	 BEGIN TRANSACTION 
			DELETE RD FROM sAssessment.tResultDetail RD  
					INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
					INNER JOIN sStudent.tAcademic A ON 	R.AcademicId = A.Id
					WHERE A.DivisionId = @rDivisionId
						AND A.ClassId = @rClassId
						AND ((R.AcademicId=@rAcademicId) OR(@rAcademicId=0))
						AND R.ExamId = @rExamId 
						AND A.BatchId=@rBatchId
						AND ((RD.ExamDetailId=@rExamDetailId) OR (@rExamDetailId=0))
						
	IF NOT EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD  
					INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
					INNER JOIN sStudent.tAcademic A ON 	R.AcademicId = A.Id
					WHERE A.DivisionId = @rDivisionId
						AND A.ClassId = @rClassId
						AND ((R.AcademicId=@rAcademicId) OR(@rAcademicId=0))
						AND R.ExamId = @rExamId 
						AND A.BatchId=@rBatchId)
						 
		BEGIN			
			DELETE R FROM
			 sAssessment.tResult R INNER JOIN sStudent.tAcademic A
			 ON R.AcademicId = A.Id			 
			 WHERE A.DivisionId = @rDivisionId
				  AND A.ClassId = @rClassId
				  AND ((R.AcademicId=@rAcademicId) OR (@rAcademicId=0))
				  AND R.ExamId = @rExamId 
				  AND A.BatchId=@rBatchId
		END		 
				  
			SELECT 1 AS RESULT
		 
 	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAssessmentConsolidatedDashboardGet]
	 
	@rExamSubGroupId nvarchar(max)='',
	@rCommonOrgGroupBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

--Changes for Mantis Id: 0039838
Declare @lOrgGroupId int 

Select @lOrgGroupId = O.Id from sSetup.tCommonOrgGroupBatchMaster COGBM
	INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
	INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId
	Where COGBM.Id=@rCommonOrgGroupBatchId   

DECLARE @lConfigValueDashboard nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValueDashboard = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValueDashboard, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;

IF(@lConfigValueDashboard <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValueDashboard <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

	IF @rExamSubGroupId = '' SET @rExamSubGroupId = NULL

	BEGIN
		 SELECT 
				OGM.Id AS OrgGroupId,
				OGM.Title AS OrgGroupName
				,COUNT(R1.AcademicId) AS PassStudentCount
				,COUNT(R2.AcademicId) AS FailStudentCount,
				CASE WHEN COUNT(R1.AcademicId)= 0 AND COUNT(R2.AcademicId)=0 THEN 0 
				When COUNT(R1.AcademicId) > 0 AND COUNT(R2.AcademicId)=0 THEN 100
				WHEN COUNT(R1.AcademicId) = 0 AND COUNT(R2.AcademicId) > 0 THEN 0
				ELSE (COUNT(R1.AcademicId) * 100)/(COUNT(R1.AcademicId)+COUNT(R2.AcademicId))END AS PassStudentPercentage
         FROM 
				sSetup.tOrgGroupMaster OGM
			    INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id			   
				INNER JOIN sStudent.tAcademic A ON A.OrgId = OM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				
				LEFT JOIN
				(
					SELECT
						R.AcademicId AS AcademicId
					FROM
						sAssessment.tResult R  
						INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 	    
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId							
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						
					WHERE
						UPPER(R.ResultStatus)='PASS' AND COGBM.Id=@rCommonOrgGroupBatchId    
						--AND BM.IsActive = 1
						AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='')
						-- IsInContext
						AND BM.IsInContext = 1
					GROUP BY
						R.AcademicId
				) R1 ON R1.AcademicId = A.Id
				LEFT JOIN
				(
					SELECT
						R.AcademicId AS AcademicId
					FROM
						sAssessment.tResult R  
						INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 	 
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						
					WHERE
						UPPER(R.ResultStatus)='FAIL' AND COGBM.Id=@rCommonOrgGroupBatchId    
						--AND BM.IsActive = 1
						AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='')
						-- IsInContext
						AND BM.IsInContext = 1
					GROUP BY
						R.AcademicId
				) R2 ON R2.AcademicId = A.Id
				
		 WHERE 
				ISNULL(OGM.IsObsolete,0) = 0
				--AND BM.IsActive = 1
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				-- IsInContext
				AND BM.IsInContext = 1
		 GROUP BY
				OGM.Id, OGM.Title 
		 ORDER BY
				OGM.Id
				
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAssessmentLabelSetupAdd]
--@rId int,
@rOrgId int,
@rSchoolName nvarchar(200),
@rMedium nvarchar(100),
@rName nvarchar(200),
@rCode nvarchar(100),
@rSUID nvarchar(100),
@rClass nvarchar(100),
@rBirthDate nvarchar(100),
@rRollNo nvarchar(100),
@rFatherName nvarchar(100),
@rMotherName nvarchar(100),
@rTotalWorkingDays nvarchar(100),
@rTotalPresentDays nvarchar(100),
@rHeight nvarchar(100),
@rWeight nvarchar(100),
@rSubject nvarchar(100),
@rMaxMarks nvarchar(100),
@rTotal nvarchar(100),
@rGrade nvarchar(100),
@rGrandTotal nvarchar(100),
@rResultStatus nvarchar(100),
@rRankNo nvarchar(100),
@rPercentile nvarchar(100),
@rPercentage nvarchar(100),
@rOverallGrade nvarchar(100),
@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DELETE FROM [sAssessment].[tAssessmentLabelSetup] WHERE OrgId = @rOrgId
INSERT INTO [sAssessment].[tAssessmentLabelSetup]
           (
            OrgId
           ,SchoolNameLabel
           ,MediumLabel
           ,NameLabel
           ,CodeLabel
           ,SUIDLabel
           ,ClassLabel
           ,BirthDateLabel
           ,RollNoLabel
           ,FatherNameLabel
           ,MotherNameLabel
           ,TotalWorkingDaysLabel
           ,TotalPresentDaysLabel
           ,HeightLabel
           ,WeightLabel
           ,SubjectLabel
           ,MaxMarksLabel
           ,TotalLabel
           ,GradeLabel
           ,GrandTotalLabel
           ,ResultStatusLabel
           ,RankNoLabel
           ,PercentileLabel
           ,PercentageLabel
           ,OverallGradeLabel
		   ,CreatedUserId
		   ,CreatedDateTime
		   )
     VALUES
           (
		    @rOrgId
           ,@rSchoolName
           ,@rMedium
           ,@rName
           ,@rCode
           ,@rSUID
           ,@rClass
           ,@rBirthDate
           ,@rRollNo
           ,@rFatherName
           ,@rMotherName
           ,@rTotalWorkingDays
           ,@rTotalPresentDays
           ,@rHeight
           ,@rWeight
           ,@rSubject
           ,@rMaxMarks
           ,@rTotal
           ,@rGrade
           ,@rGrandTotal
           ,@rResultStatus
           ,@rRankNo
           ,@rPercentile
           ,@rPercentage
           ,@rOverallGrade
		   ,@rCreatedUserId
		   ,sCommon.fGetDate()
		   )
		   
		   SELECT 0 AS Result
	--if(@rId=0) 
	--BEGIN
	--	If Exists(select Id from [sAssessment].[tAssessmentLabelSetup] where OrgId=@rOrgId)
	--	BEGIN
	--		select -101 as Result
	--		RETURN
	--	END
		
	--END
	--ELSE
	--BEGIN
	--	IF Exists(select Id from [sAssessment].[tAssessmentLabelSetup] where OrgId=@rOrgId AND Id<>@rId)
	--	BEGIN
	--		select -102 as Result
	--		RETURN
	--	END
		
	--END
	
	--IF(@rId=0)
	--BEGIN
	--	--DECLARE @lNextNumber BIGINT 
	--	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tAssessmentLabelSetup', 0, 1, 1,@outNextNumber = @lNextNumber output

	--	INSERT INTO [sAssessment].[tAssessmentLabelSetup]
 --          (
 --           OrgId
 --          ,SchoolNameLabel
 --          ,MediumLabel
 --          ,NameLabel
 --          ,CodeLabel
 --          ,SUIDLabel
 --          ,ClassLabel
 --          ,BirthDateLabel
 --          ,RollNoLabel
 --          ,FatherNameLabel
 --          ,MotherNameLabel
 --          ,TotalWorkingDaysLabel
 --          ,TotalPresentDaysLabel
 --          ,HeightLabel
 --          ,WeightLabel
 --          ,SubjectLabel
 --          ,MaxMarksLabel
 --          ,TotalLabel
 --          ,GradeLabel
 --          ,GrandTotalLabel
 --          ,ResultStatusLabel
 --          ,RankNoLabel
 --          ,PercentileLabel
 --          ,PercentageLabel
 --          ,OverallGradeLabel
	--	   ,CreatedUserId
	--	   ,CreatedDateTime
	--	   )
 --    VALUES
 --          (
	--	    @rOrgId
 --          ,@rSchoolName
 --          ,@rMedium
 --          ,@rName
 --          ,@rCode
 --          ,@rSUID
 --          ,@rClass
 --          ,@rBirthDate
 --          ,@rRollNo
 --          ,@rFatherName
 --          ,@rMotherName
 --          ,@rTotalWorkingDays
 --          ,@rTotalPresentDays
 --          ,@rHeight
 --          ,@rWeight
 --          ,@rSubject
 --          ,@rMaxMarks
 --          ,@rTotal
 --          ,@rGrade
 --          ,@rGrandTotal
 --          ,@rResultStatus
 --          ,@rRankNo
 --          ,@rPercentile
 --          ,@rPercentage
 --          ,@rOverallGrade
	--	   ,@rCreatedUserId
	--	   ,sCommon.fGetDate()
	--	   )
	
	--	SELECT 0 AS Result
	--END
	--ELSE
	--BEGIN
	--	--SET @lNextNumber = @rId

	--	UPDATE [sAssessment].[tAssessmentLabelSetup]
	--   SET
	--	  SchoolNameLabel = @rSchoolName
	--	  ,MediumLabel = @rMedium
	--	  ,NameLabel = @rName
	--	  ,CodeLabel = @rCode
	--	  ,SUIDLabel = @rSUID
	--	  ,ClassLabel = @rClass
	--	  ,BirthDateLabel = @rBirthDate
	--	  ,RollNoLabel = @rRollNo
	--	  ,FatherNameLabel = @rFatherName
	--	  ,MotherNameLabel = @rMotherName
	--	  ,TotalWorkingDaysLabel = @rTotalWorkingDays
	--	  ,TotalPresentDaysLabel = @rTotalPresentDays
	--	  ,HeightLabel = @rHeight
	--	  ,WeightLabel = @rWeight
	--	  ,SubjectLabel = @rSubject
	--	  ,MaxMarksLabel = @rMaxMarks
	--	  ,TotalLabel = @rTotal
	--	  ,GradeLabel = @rGrade
	--	  ,GrandTotalLabel = @rGrandTotal
	--	  ,ResultStatusLabel = @rResultStatus
	--	  ,RankNoLabel = @rRankNo
	--	  ,PercentileLabel = @rPercentile
	--	  ,PercentageLabel = @rPercentage
	--	  ,OverallGradeLabel = @rOverallGrade
	--	  ,UpdatedUserId =@rCreatedUserId
	--	  ,UpdatedDateTime = sCommon.fGetDate()
	-- WHERE Id=@rId

	--	 SELECT @rId AS Result
	--END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pAssessmentLabelSetupGet]
	@rOrgId int
	--@rId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SELECT
	   Id
      ,OrgId
      ,SchoolNameLabel
      ,MediumLabel
      ,NameLabel
      ,CodeLabel
      ,SUIDLabel
      ,ClassLabel
      ,BirthDateLabel
      ,RollNoLabel
      ,FatherNameLabel
      ,MotherNameLabel
      ,TotalWorkingDaysLabel
      ,TotalPresentDaysLabel
      ,HeightLabel
      ,WeightLabel
      ,SubjectLabel
      ,MaxMarksLabel
      ,TotalLabel
      ,GradeLabel
      ,GrandTotalLabel
      ,ResultStatusLabel
      ,RankNoLabel
      ,PercentileLabel
      ,PercentageLabel
      ,OverallGradeLabel
FROM [sAssessment].[tAssessmentLabelSetup]
WHERE 
--((Id = @rId) OR (@rId = 0))
((OrgId = @rOrgId) OR (@rOrgId = 0))

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pBestTwoExamMark]  
	 	
	@rExamId int,
	@rClassId int,
	@rDivisionId int,
	 @rExamList nvarchar(500),
	 @rOrgId int=0,
	@rBatchId int,
	@rNoExam int ,
	@rBasedOnPresent int = 0	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 
BEGIN
	 
	 BEGIN	
	 
	 CREATE Table #tempTable
	 (
		 
		 
		ExamDetailId int,
		ClassSubjectId int,
		ExamId int,
		AcademicId bigint,
		Obtain decimal(5,2),
		Maximum decimal(5,2),
		Id int   ,
		IsPresent int
	 )
	 Insert into #tempTable
	 (
		ExamDetailId,
		ClassSubjectId,
		ExamId,
		AcademicId,
		Obtain,
		Maximum,
		Id,
		IsPresent 
	 )
	  
	 
    SELECT 
		 
			RD.ExamDetailId,
			ED.ClassSubjectId,
			EM.Id,
			A.AcademicId,
			RD.Obtain,ED.Maximum,
		 ROW_NUMBER() 
		 
    over (
        PARTITION BY   ED.ClassSubjectId, A.AcademicId 
        order by RD.[Obtain] desc
    ) AS RowNo ,
	RD.IsPresent
    FROM  
			 
			 sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId  		
			INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rbatchId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			 INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
			  INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId 
			 AND (A.DivisionId=@rDivisionid)
			 
			 INNER JOIN (Select Id,ClassSubjectId,Maximum from sAssessment.tExamDetail Where ExamId=@rexamid) EID ON EID.ClassSubjectId = ED.ClassSubjectId  
			  Where  ED.ExamID in (SELECT  cast(item as int) AS ExamID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rExamList,'(',''),')','') ,','))
 --Select * from #tempTable
	
	Create Table #tempData
	(
		ClassSubjectId int,
		AcademicId bigint,
		Obtain decimal (5,2),
		Maximum decimal(5,2),
		IsPresent int
	)
	IF(@rBasedOnPresent = 0)
	BEGIN
		INSert INto #tempData
		(
			ClassSubjectId,AcademicId,Obtain,Maximum,IsPresent
		)
		Select ClassSubjectId,AcademicId,Sum(Obtain),SUM(Maximum),MIN(CONVERT(INT,IsPresent)) AS IsPresent from #tempTable  WHERE  Id <=@rNoExam group By ClassSubjectId,AcademicId
	END
	ELSE
	BEGIN
	INSert INto #tempData
		(
			ClassSubjectId,AcademicId,Obtain,Maximum,IsPresent
		)
		Select ClassSubjectId,AcademicId,Sum(Obtain),SUM(Maximum),MAX(CONVERT(INT,IsPresent)) AS IsPresent from #tempTable  WHERE  Id <=@rNoExam group By ClassSubjectId,AcademicId
	END
	
	--Select * from #tempData
 
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max)
	  DECLARE @lMaxId Bigint
	 Declare @lDecimalFormat nvarchar(10)
	  Declare @lIsMarksInDecimal bit
	 Declare @lHigh1 decimal(5,2),@lHigh2 decimal(5,2)
	select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id =@rExamId 
	Declare @lCountMark int,@lSum_Highest decimal(5,2),@lSum decimal(5,2)
	Declare @lMaximum decimal(5,2)
	Select @lMaximum = Maximum from sAssessment.tExamDetail where ExamId=@rExamId
	 
	 
	 --SELECT SubExamId From sAssessment.tExamCombine where (ExamId = @rExamId)
	  
 
	
     IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@rExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
		 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@rExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,sCommon.fGetDate()
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END
  
    IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@rExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND A.DivisionId=@rDivisionId
    )
    BEGIN	
			--SET @Query = ' 
			 
			 
			 --UPDATE RD SET RD.OBTAIN =  A.Obtain,RD.IsPresent=A.IsPresent  FROM
				--		( 
				--		SELECT  (@lMaximum * Obtain) /Maximum AS Obtain, AcademicId,ClassSubjectId,IsPresent  FROM #tempData   
				--		) A
				--	INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
				--	INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
				--	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				--	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId =  @rClassId  
				--	AND (SA.DIVISIONID= @RDivisionId)  
				--	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
				--	AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId

			--comment above code because @lMaximum take first maximum instead of Subjectwise Maximum - mantisid - 0023630
			 UPDATE RD SET RD.OBTAIN =  (ED.Maximum* A.Obtain)/A.Maximum ,RD.IsPresent=A.IsPresent  FROM
						( 
						SELECT  Obtain,Maximum, AcademicId,ClassSubjectId,IsPresent  FROM #tempData   
						) A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId =  @rClassId  
					AND (SA.DIVISIONID= @RDivisionId)  
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId

		--EXECUTE(@query)
				Select 1 As Result
    END
   ELSE
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
				   
				 --Select @lNextNumber
						--INSERT INTO sAssessment.tResultDetail
						--	 (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						--SELECT  
						--	@lNextNumber  + ROW_number()OVER(Order by R.Id) AS Id,
							 
						--	R.Id as R_Id,
						--	ED1.Id AS ExamDetailId,
						--	A.IsPresent AS IsPresent,
						--	A.Obtain 
						--	from 
					 -- 	 sAssessment.tResult R 
					 -- 	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					 --   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
						--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
						--INNER JOIN( 
						--			SELECT   AcademicId,ClassSubjectId,(@lMaximum * Obtain) /Maximum AS Obtain ,IsPresent
						--			FROM #tempData group by   AcademicId,ClassSubjectId,Obtain,Maximum,IsPresent
						--		)A   ON R.AcademicId= A.AcademicID  AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
						-- WHERE SA.ClassId = @rClassId AND  SA.DIVISIONID= @rDivisionId 
						--AND R.ExamId = @rExamId
						 
						 --comment above code because @lMaximum take first maximum instead of Subjectwise Maximum - mantisid - 0023630
						INSERT INTO sAssessment.tResultDetail
							 (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT  
							@lNextNumber  + ROW_number()OVER(Order by R.Id) AS Id,
							 
							R.Id as R_Id,
							ED1.Id AS ExamDetailId,
							A.IsPresent AS IsPresent,
							--A.Obtain 
							((ED1.maximum * A.Obtain) / A.Maximum) AS Obtain
							from 
					  	 sAssessment.tResult R 
					  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					    INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
						INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
						INNER JOIN( 
									SELECT   AcademicId,ClassSubjectId,Obtain,Maximum,IsPresent
									FROM #tempData group by   AcademicId,ClassSubjectId,Obtain,Maximum,IsPresent
								)A   ON R.AcademicId= A.AcademicID  AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
						 WHERE SA.ClassId = @rClassId AND  SA.DIVISIONID= @rDivisionId 
						AND R.ExamId = @rExamId
									
		SELECT @lMaxId=MAx(RD.Id)   FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R On R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id =R.ExamId
		INNER JOIN sSetup.tBatchMaster BM ON BM.ID = EM.BatchId 
		WHERE BM.OrgId = @rOrgId
		  
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lMaxId 
		 Select 11 As Result
		 
   END
    
   
   Drop Table  #tempTable
	
  
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pBestTwoExamMarkDifferentSubjectWise]  
	 	
	@rExamId int,
	@rClassId int,
	@rDivisionId int,
	@rExamList nvarchar(500),
	@rOrgId int=0,
	@rBatchId int,
	@rNoExam int ,
	@rBasedOnPresent int = 0,
	@rExamDetailList nvarchar(max),
	@rExamDetailId int = 0 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 
BEGIN
	 
	 BEGIN	
	 
	 CREATE Table #tempTable
	 (
		ExamDetailId int,
		ClassSubjectId int,
		ExamId int,
		AcademicId bigint,
		Obtain decimal(5,2),
		Maximum decimal(5,2),
		Id int   ,
		IsPresent int
	 )
	 Insert into #tempTable
	 (
		ExamDetailId,
		ClassSubjectId,
		ExamId,
		AcademicId,
		Obtain,
		Maximum,
		Id,
		IsPresent 
	 )
	  
	 
    SELECT 
		 
			RD.ExamDetailId,
			ED.ClassSubjectId,
			EM.Id,
			A.AcademicId,
			RD.Obtain,ED.Maximum,
		 ROW_NUMBER() 
		 
    over (
        PARTITION BY   ED.ClassSubjectId, A.AcademicId 
        order by RD.[Obtain] desc
    ) AS RowNo ,
	RD.IsPresent
    FROM  
			 
			 sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId  		
			INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rbatchId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
			INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId 
			AND (A.DivisionId=@rDivisionid)
			 
			--INNER JOIN (Select Id,ClassSubjectId,Maximum from sAssessment.tExamDetail Where ExamId=@rexamid) EID ON EID.ClassSubjectId = ED.ClassSubjectId  
			Where  ED.ExamID in (SELECT  cast(item as int) AS ExamID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rExamList,'(',''),')','') ,','))
			AND ED.Id in (SELECT  cast(item as int) AS SubjectID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rExamDetailList,'(',''),')','') ,','))
			--AND (ED.Id=@rSubjectId OR @rSubjectId = 0)
 --Select * from #tempTable
	
	Create Table #tempData
	(
		ClassSubjectId int,
		AcademicId bigint,
		Obtain decimal (5,2),
		Maximum decimal(5,2),
		IsPresent int
	)
	IF(@rBasedOnPresent = 0)
	BEGIN
		INSert INto #tempData
		(
			ClassSubjectId,AcademicId,Obtain,Maximum,IsPresent
		)
		Select ClassSubjectId,AcademicId,Sum(Obtain),SUM(Maximum),MIN(CONVERT(INT,IsPresent)) AS IsPresent from #tempTable  WHERE  Id <=@rNoExam group By ClassSubjectId,AcademicId
	END
	ELSE
	BEGIN
	INSert INto #tempData
		(
			ClassSubjectId,AcademicId,Obtain,Maximum,IsPresent
		)
		Select ClassSubjectId,AcademicId,Sum(Obtain),SUM(Maximum),MAX(CONVERT(INT,IsPresent)) AS IsPresent from #tempTable  WHERE  Id <=@rNoExam group By ClassSubjectId,AcademicId
	END
	
	--Select * from #tempData
 
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max)
	  DECLARE @lMaxId Bigint
	 Declare @lDecimalFormat nvarchar(10)
	  Declare @lIsMarksInDecimal bit
	 Declare @lHigh1 decimal(5,2),@lHigh2 decimal(5,2)
	select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id =@rExamId 
	Declare @lCountMark int,@lSum_Highest decimal(5,2),@lSum decimal(5,2)
	Declare @lMaximum decimal(5,2)
	Select @lMaximum = Maximum from sAssessment.tExamDetail where ExamId=@rExamId
	 
	 
	 --SELECT SubExamId From sAssessment.tExamCombine where (ExamId = @rExamId)
	  
 
	
     IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@rExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
		 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@rExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,sCommon.fGetDate()
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END
  
    IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@rExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND A.DivisionId=@rDivisionId 
	AND (RD.ExamDetailId = @rExamDetailId OR @rExamDetailId = 0)
    )
    BEGIN	
			--SET @Query = ' 
			 
			 
			 --UPDATE RD SET RD.OBTAIN =  A.Obtain,RD.IsPresent=A.IsPresent  FROM
				--		( 
				--		SELECT  (@lMaximum * Obtain) /Maximum AS Obtain, AcademicId,ClassSubjectId,IsPresent  FROM #tempData   
				--		) A
				--	INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
				--	INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
				--	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				--	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId =  @rClassId  
				--	AND (SA.DIVISIONID= @RDivisionId)  
				--	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
				--	AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId

			--comment above code because @lMaximum take first maximum instead of Subjectwise Maximum - mantisid - 0023630
			 UPDATE RD SET RD.OBTAIN =  (ED.Maximum* A.Obtain)/A.Maximum ,RD.IsPresent=A.IsPresent  FROM
						( 
						SELECT  Obtain,Maximum, AcademicId,ClassSubjectId,IsPresent  FROM #tempData   
						) A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId =  @rClassId  
					AND (SA.DIVISIONID= @rDivisionId)  
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  
					--AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId
					--AND (ED.Id=@rSubjectId OR @rSubjectId = 0)
					AND (ED.Id=@rExamDetailId OR @rExamDetailId = 0)

		--EXECUTE(@query)
				Select 1 As Result
    END
   ELSE
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
				   
				 --Select @lNextNumber
						--INSERT INTO sAssessment.tResultDetail
						--	 (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						--SELECT  
						--	@lNextNumber  + ROW_number()OVER(Order by R.Id) AS Id,
							 
						--	R.Id as R_Id,
						--	ED1.Id AS ExamDetailId,
						--	A.IsPresent AS IsPresent,
						--	A.Obtain 
						--	from 
					 -- 	 sAssessment.tResult R 
					 -- 	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					 --   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
						--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
						--INNER JOIN( 
						--			SELECT   AcademicId,ClassSubjectId,(@lMaximum * Obtain) /Maximum AS Obtain ,IsPresent
						--			FROM #tempData group by   AcademicId,ClassSubjectId,Obtain,Maximum,IsPresent
						--		)A   ON R.AcademicId= A.AcademicID  AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
						-- WHERE SA.ClassId = @rClassId AND  SA.DIVISIONID= @rDivisionId 
						--AND R.ExamId = @rExamId
						 
						 --comment above code because @lMaximum take first maximum instead of Subjectwise Maximum - mantisid - 0023630
						INSERT INTO sAssessment.tResultDetail
							 (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT  
							@lNextNumber  + ROW_number()OVER(Order by R.Id) AS Id,
							 
							R.Id as R_Id,
							ED1.Id AS ExamDetailId,
							A.IsPresent AS IsPresent,
							--A.Obtain 
							((ED1.maximum * A.Obtain) / A.Maximum) AS Obtain
							from 
					  	 sAssessment.tResult R 
					  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					    INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
						INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
						INNER JOIN( 
									SELECT   AcademicId,ClassSubjectId,Obtain,Maximum,IsPresent
									FROM #tempData group by   AcademicId,ClassSubjectId,Obtain,Maximum,IsPresent
								)A   ON R.AcademicId= A.AcademicID  
								--AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
						 WHERE SA.ClassId = @rClassId AND  SA.DIVISIONID= @rDivisionId 
						AND R.ExamId = @rExamId
						--AND (ED1.Id=@rSubjectId OR @rSubjectId = 0)
						AND (ED1.Id=@rExamDetailId OR @rExamDetailId = 0)
									
		SELECT @lMaxId=MAx(RD.Id)   FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R On R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id =R.ExamId
		INNER JOIN sSetup.tBatchMaster BM ON BM.ID = EM.BatchId 
		WHERE BM.OrgId = @rOrgId
		  
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lMaxId 
		 Select 11 As Result
		 
   END
    
   
   Drop Table  #tempTable
	
  
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pBestTwoExamMarkSubjectWise]  
	 	
	@rExamId int,
	@rClassId int,
	@rDivisionId int,
	@rExamList nvarchar(max),
	@rOrgId int=0,
	@rBatchId int,
	@rNoExam int ,
	@rBasedOnPresent int = 0,
	@rExamDetailId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 
BEGIN
	 
	 BEGIN	

	 DECLARE @lClassSubjectId int

	 SELECT @lClassSubjectId = ClassSubjectId From sAssessment.tExamDetail WHERE Id = @rExamDetailId
	 
	 CREATE Table #tempTable
	 (
		ExamDetailId int,
		ClassSubjectId int,
		ExamId int,
		AcademicId bigint,
		Obtain decimal(5,2),
		Maximum decimal(5,2),
		Id int   ,
		IsPresent int
	 )
	 Insert into #tempTable
	 (
		ExamDetailId,
		ClassSubjectId,
		ExamId,
		AcademicId,
		Obtain,
		Maximum,
		Id,
		IsPresent 
	 )
	  
	 
    SELECT 
		 
			RD.ExamDetailId,
			ED.ClassSubjectId,
			EM.Id,
			A.AcademicId,
			RD.Obtain,ED.Maximum,
		 ROW_NUMBER() 
		 
    over (
        PARTITION BY   ED.ClassSubjectId, A.AcademicId 
        order by RD.[Obtain] desc
    ) AS RowNo ,
	RD.IsPresent
    FROM  
			 
			 sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId  		
			INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rbatchId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
			INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId 
			AND (A.DivisionId=@rDivisionid)
			 
			INNER JOIN (Select Id,ClassSubjectId,Maximum from sAssessment.tExamDetail Where ExamId=@rexamid) EID ON EID.ClassSubjectId = ED.ClassSubjectId  
			Where  ED.ExamID in (SELECT  cast(item as int) AS ExamID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rExamList,'(',''),')','') ,','))
			AND (ED.ClassSubjectId=@lClassSubjectId OR @lClassSubjectId = 0)
 --Select * from #tempTable
	
	Create Table #tempData
	(
		ClassSubjectId int,
		AcademicId bigint,
		Obtain decimal (5,2),
		Maximum decimal(5,2),
		IsPresent int
	)
	IF(@rBasedOnPresent = 0)
	BEGIN
		INSert INto #tempData
		(
			ClassSubjectId,AcademicId,Obtain,Maximum,IsPresent
		)
		Select ClassSubjectId,AcademicId,Sum(Obtain),SUM(Maximum),MIN(CONVERT(INT,IsPresent)) AS IsPresent from #tempTable  WHERE  Id <=@rNoExam group By ClassSubjectId,AcademicId
	END
	ELSE
	BEGIN
	INSert INto #tempData
		(
			ClassSubjectId,AcademicId,Obtain,Maximum,IsPresent
		)
		Select ClassSubjectId,AcademicId,Sum(Obtain),SUM(Maximum),MAX(CONVERT(INT,IsPresent)) AS IsPresent from #tempTable  WHERE  Id <=@rNoExam group By ClassSubjectId,AcademicId
	END
	
	--Select * from #tempData
 
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max)
	  DECLARE @lMaxId Bigint
	 Declare @lDecimalFormat nvarchar(10)
	  Declare @lIsMarksInDecimal bit
	 Declare @lHigh1 decimal(5,2),@lHigh2 decimal(5,2)
	select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id =@rExamId 
	Declare @lCountMark int,@lSum_Highest decimal(5,2),@lSum decimal(5,2)
	Declare @lMaximum decimal(5,2)
	Select @lMaximum = Maximum from sAssessment.tExamDetail where ExamId=@rExamId
	 
	 
	 --SELECT SubExamId From sAssessment.tExamCombine where (ExamId = @rExamId)
	  
 
	
     IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@rExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
		 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@rExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,sCommon.fGetDate()
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END
  
    IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@rExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND A.DivisionId=@rDivisionId 
	AND (RD.ExamDetailId = @rExamDetailId OR @rExamDetailId = 0)
    )
    BEGIN	
			--SET @Query = ' 
			 
			 
			 --UPDATE RD SET RD.OBTAIN =  A.Obtain,RD.IsPresent=A.IsPresent  FROM
				--		( 
				--		SELECT  (@lMaximum * Obtain) /Maximum AS Obtain, AcademicId,ClassSubjectId,IsPresent  FROM #tempData   
				--		) A
				--	INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
				--	INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
				--	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				--	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId =  @rClassId  
				--	AND (SA.DIVISIONID= @RDivisionId)  
				--	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
				--	AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId

			--comment above code because @lMaximum take first maximum instead of Subjectwise Maximum - mantisid - 0023630
			 UPDATE RD SET RD.OBTAIN =  (ED.Maximum* A.Obtain)/A.Maximum ,RD.IsPresent=A.IsPresent  FROM
						( 
						SELECT  Obtain,Maximum, AcademicId,ClassSubjectId,IsPresent  FROM #tempData   
						) A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId =  @rClassId  
					AND (SA.DIVISIONID= @RDivisionId)  
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId
					AND (ED.Id=@rExamDetailId OR @rExamDetailId = 0)

		--EXECUTE(@query)
				Select 1 As Result
    END
   ELSE
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
				   
				 --Select @lNextNumber
						--INSERT INTO sAssessment.tResultDetail
						--	 (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						--SELECT  
						--	@lNextNumber  + ROW_number()OVER(Order by R.Id) AS Id,
							 
						--	R.Id as R_Id,
						--	ED1.Id AS ExamDetailId,
						--	A.IsPresent AS IsPresent,
						--	A.Obtain 
						--	from 
					 -- 	 sAssessment.tResult R 
					 -- 	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					 --   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
						--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
						--INNER JOIN( 
						--			SELECT   AcademicId,ClassSubjectId,(@lMaximum * Obtain) /Maximum AS Obtain ,IsPresent
						--			FROM #tempData group by   AcademicId,ClassSubjectId,Obtain,Maximum,IsPresent
						--		)A   ON R.AcademicId= A.AcademicID  AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
						-- WHERE SA.ClassId = @rClassId AND  SA.DIVISIONID= @rDivisionId 
						--AND R.ExamId = @rExamId
						 
						 --comment above code because @lMaximum take first maximum instead of Subjectwise Maximum - mantisid - 0023630
						INSERT INTO sAssessment.tResultDetail
							 (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT  
							@lNextNumber  + ROW_number()OVER(Order by R.Id) AS Id,
							 
							R.Id as R_Id,
							ED1.Id AS ExamDetailId,
							A.IsPresent AS IsPresent,
							--A.Obtain 
							((ED1.maximum * A.Obtain) / A.Maximum) AS Obtain
							from 
					  	 sAssessment.tResult R 
					  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					    INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
						INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
						INNER JOIN( 
									SELECT   AcademicId,ClassSubjectId,Obtain,Maximum,IsPresent
									FROM #tempData group by   AcademicId,ClassSubjectId,Obtain,Maximum,IsPresent
								)A   ON R.AcademicId= A.AcademicID  AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
						 WHERE SA.ClassId = @rClassId AND  SA.DIVISIONID= @rDivisionId 
						AND R.ExamId = @rExamId
						AND (ED1.Id=@rExamDetailId OR @rExamDetailId = 0)
									
		SELECT @lMaxId=MAx(RD.Id)   FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R On R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id =R.ExamId
		INNER JOIN sSetup.tBatchMaster BM ON BM.ID = EM.BatchId 
		WHERE BM.OrgId = @rOrgId
		  
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lMaxId 
		 Select 11 As Result
		 
   END
    
   
   Drop Table  #tempTable
	
  
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pBrightStudentConsolidatedListGet]
	 
	 @rGroupId int=0,
	 @rTop int=0,
	 @rOrgGroupId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEN @rGroupId =4 THEN OM.Id END
				ORDER BY R.Percentage DESC) rn,
			
			OM.ShortCode AS OrgCode,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			CM.DisplayTitle AS Class,
			R.Percentage,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id  END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization' END AS GroupTitle
				
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id= OM.OrgGroupId
	WHERE 
		    --((EM.BatchId = @rBatchId) OR (@rBatchId = 0))
			--AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
			--AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			--AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			--((A.StatusId=@rStatusId) OR (@rStatusId=0))
			BM.IsActive = 1
			AND ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
	)r1
	WHERE ((r1.rn <= @rTop) Or (@rTop = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCCECSConvertExamGradeIndicator]
	 
            @rAcademicId bigint
           ,@rExamId int
		   ,@rOldIndicator nvarchar(50)
		   ,@rNewIndicator nvarchar(50)
		   ,@rCCECSId int
		   ,@rCCECSGroupId int
		    
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	  Update  CCECSEx 
		set CCECSEx.GradeIndicator = @rNewIndicator
	 from sAssessment.tCCECSExamScore AS CCECSEx 
		  INNER JOIN sAssessment.tCCECSMaster CCECSM on CCECSM.Id = CCECSEx.CCECSId 
	 WHERE ((CCECSM.CCECAGroupId=@rCCECSGroupId) OR (@rCCECSGroupId=0)) 
			AND CCECSEx.GradeIndicator =@rOldIndicator
			AND CCECSEx.ExamId =@rExamId
		    AND ((CCECSEx.AcademicId =@rAcademicId) OR (@rAcademicId=0))
			AND ((CCECSM.Id =@rCCECSId) OR (@rCCECSId=0))
	     
	 SELECT 1 AS Result
	 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCCECSConvertExamGradeScore]
	 
            @rAcademicId bigint
           ,@rExamId int
		   ,@rOldGrade nvarchar(10)
		   ,@rNewGrade nvarchar(10)
		   ,@rCCECSId int
		   ,@rCCECSGroupId int
		    
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	  Update  CCECSEx 
		set CCECSEx.Grade = @rNewGrade
	 from sAssessment.tCCECSExamScore AS CCECSEx 
		  INNER JOIN sAssessment.tCCECSMaster CCECSM on CCECSM.Id = CCECSEx.CCECSId 
	 WHERE ((CCECSM.CCECAGroupId=@rCCECSGroupId) OR (@rCCECSGroupId=0)) 
			AND CCECSEx.Grade =@rOldGrade
			AND CCECSEx.ExamId =@rExamId
		    AND ((CCECSEx.AcademicId =@rAcademicId) OR (@rAcademicId=0))
			AND ((CCECSM.Id =@rCCECSId) OR (@rCCECSId=0))
	     
	 SELECT 1 AS Result
	 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCCECSConvertMarkAdd]
	 
     --       @rAcademicId bigint
     --      ,@rExamId int
     --      ,@rIndicator nvarchar(200)
		   --,@rGrade nvarchar(10)
		   --,@rDescriptiveIndicator nvarchar(max)
		   
		   @rCCECSId int,
		   @rClassId int,
		   @rTotalMark decimal(12,2),
		   @rConvertToMark decimal(12,2)
		   --,@rIndicatodIds nvarchar(50)
		   --,@rIsIndicatodIds bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT CCECSID FROM sAssessment.tCCECSForClass WHERE CCECSId=@rCCECSId AND ClassId=@rClassId)
BEGIN
	INSERT INTO sAssessment.tCCECSForClass
			   (
			    [CCECSId]
			   ,ClassId
			   ,TotalMark
			   ,ConvertToMark
			  
			   )
		 VALUES
			   (
				@rCCECSId
			   ,@rClassId	
			   , @rTotalMark
			   , @rConvertToMark
			   
			   )
		   
	END	 
	
	 ELSE
	 BEGIN
	    UPDATE  [sAssessment].[tCCECSForClass]
	    SET
			 
	          [CCECSId]=@rCCECSId
	         ,ClassId =@rClassId
	         ,TotalMark=@rTotalMark
			 ,ConvertToMark =@rConvertToMark
			 
	      WHERE CCECSId=@rCCECSId AND ClassId=@rClassId 
	     
	     
	 END  
  
	  SELECT 1 AS Result
	 
COMMIT TRANSACTION		
 
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 


CREATE OR ALTER PROCEDURE [sAssessment].[pCCECSExamScoreAdd]
	 
            @rAcademicId bigint
           ,@rExamId int
           ,@rIndicator nvarchar(200)
		   ,@rGrade nvarchar(10)
		   ,@rDescriptiveIndicator nvarchar(max)
		   ,@rCCECSId int
		   ,@rIndicatodIds nvarchar(50)
		   ,@rIsIndicatodIds bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT CCECSID FROM sAssessment.tCCECSExamScore WHERE CCECSId=@rCCECSId AND AcademicId=@rAcademicId AND ExamId = @rExamId)	
BEGIN
	INSERT INTO [sAssessment].[tCCECSExamScore]
			   (
			    [CCECSId]
			   ,[ExamId]
			   ,[AcademicId]
			   ,[GradeIndicator]
			   ,[Grade]
			   ,[DescriptiveIndicator]
			   ,[IndicatorIds]
			   )
		 VALUES
			   (
				@rCCECSId
			   ,@rExamId	
			   ,@rAcademicId
			   ,@rIndicator
			   ,@rGrade
			   ,@rDescriptiveIndicator
			   ,@rIndicatodIds
			   )
		   
	END	 
	 ELSE
	 BEGIN
	    UPDATE  [sAssessment].[tCCECSExamScore]
	    SET
			 
	          [AcademicId]=@rAcademicId
	         ,[ExamId] =@rExamId
	         ,GradeIndicator=@rIndicator
			 ,Grade =@rGrade
			 ,DescriptiveIndicator=@rDescriptiveIndicator
			 ,IndicatorIds = @rIndicatodIds
	      WHERE CCECSId=@rCCECSId AND AcademicId=@rAcademicId 
	      AND ExamId = 	   @rExamId
	     
	 END  
	 
	if @rIsIndicatodIds = 1 
	BEGIN 	

		-- Updated by Jash on 21/12/2020 for MantisId :- 0013797
		-- Issue :-  Indicator Title not according to Indicator Code order in CS Exam All Entry screen
		-- Commented Below code and added new code after it


		--Declare @lQuery Nvarchar(max)
		--SET  @lQuery =	'UPDATE A SET A.DescriptiveIndicator = 
 	--					stuff((select '','' + B.Title from sAssessment.tCCECSIndicatorMaster B
		--			WHERE A.CCECSid=B.CCECSId 
		--					and '',''+ (replace(IndicatorIds,''.'','','') )+'','' like ''%,''+CAST(Number as varchar(10))+'',%''				
		--			for xml path('''')),1,1,'''') 
		--	 From sAssessment.tCCECSExamScore A WHERE A.CCECSId='+ CAST(@rCCECSId AS NVARCHAR(50)) +' 
		--	 AND A.AcademicId= '+ CAST (@rAcademicId  AS NVARCHAR(50))+'
		--	  AND A.ExamId ='+ CAST(@rExamId AS NVARCHAR(50))        
        
		--EXECUTE (@lQuery)

		DECLARE @s varchar(20) = ''
		DECLARE @Indicator nvarchar(max) = ''
		SELECT @s = IndicatorIds FROM sAssessment.tCCECSExamScore WHERE AcademicId = @rAcademicId AND ExamId =@rExamId AND CCECSId=@rCCECSId

		while len(@s) > 0
		begin
		  DECLARE @TempIndicator nvarchar(max)
		  SELECT @TempIndicator = (select B.Title from sAssessment.tCCECSIndicatorMaster B  
			 WHERE A.CCECSid=B.CCECSId   
			 AND (Number = (LEFT(@s,charindex('.',@s+'.')-1))))        -- Getting value before first '.'   For ex ('20.21' -> '20')
			From sAssessment.tCCECSExamScore A WHERE A.CCECSId=@rCCECSId   
			AND A.AcademicId= @rAcademicId  
			 AND A.ExamId =@rExamId

			 SET @Indicator = @Indicator + @TempIndicator + ','
			 SET @s = stuff(@s, 1, charindex('.', @s+'.'), '')   -- Setting s to value after first '.' in the current string. For ex ('20.21' -> '21') 
  
		end
		SET @Indicator = left(@Indicator, len(@Indicator)-1)	-- removing last ',' from @Indicator
		UPDATE sAssessment.tCCECSExamScore SET DescriptiveIndicator = @Indicator WHERE AcademicId = @rAcademicId AND ExamId = @rExamId AND CCECSId = @rCCECSId
	END
	  SELECT 1 AS Result
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCCECSIDGet]
	  @rCSGroupId int,
	  @rTitle nvarchar(100)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
SELECT 			ISNULL(Id,0) AS Id
FROM 
			sAssessment.tCCECSMaster Where CCECAGroupId = @rCSGroupId  ANd TItle=@rTitle
				
			  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCCECSScoreAdd]
	 
            @rAcademicId bigint
           ,@rIndicator nvarchar(200)
		   ,@rGrade nvarchar(10)
		   ,@rGradePoint decimal(6,2)
		   ,@rCCECSId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT CCECSID FROM sAssessment.tCCECSScore WHERE CCECSId=@rCCECSId AND AcademicId=@rAcademicId)	
BEGIN
	INSERT INTO [sAssessment].[tCCECSScore]
			   (
			    [CCECSId]
			   ,[AcademicId]
			   ,[Indicator]
			   ,[Grade]
			   ,[GradePoint]
			   )
		 VALUES
			   (
				@rCCECSId
			   ,@rAcademicId
			   ,@rIndicator
			   ,@rGrade
			   ,@rGradePoint
			   )
		    SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	    UPDATE  [sAssessment].[tCCECSScore]
	    SET
			 
	          [AcademicId]=@rAcademicId
	         ,Indicator=@rIndicator
			 ,Grade =@rGrade
			 ,GradePoint=@rGradePoint
	      WHERE CCECSId=@rCCECSId AND AcademicId=@rAcademicId 	   
	      SELECT 1 AS Result
	 END  
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCCEExamCombineGet]
	 @rClassId int
	,@rCCEExamId SMALLINT
	,@rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	SELECT 
	 EC.SubExamId AS SubExamId,
	EM.ClassId AS ClassId ,
	 ISNULL(EC.Weightage,0) AS Weightage,
	 ISNULL(ExamOrder,0) AS ExamOrder,
	 EM.Id AS ExamId
  FROM 
			[sAssessment].[tExamMaster] EM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			
			 INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId=EM.Id
			 INNER JOIN sAssessment.tCCEExamSetting CS ON CS.CLASSID = CM.ID 
			AND CS.ExamSubGroupId = EM.ExamSubGroupId
WHERE 
			((EM.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((EM.BatchId = @rBatchId) Or (@rBatchId = 0))
			 AND CS.CCEExamId = @rCCEExamId
		
			ORDER BY EM.ExamSubGroupId ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCCEExamMappingAdd]
	 
            @rClassId int
           ,@rCCEExamId int
           ,@rExamId int
           ,@rBatchId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
BEGIN
    
    IF EXISTS (SELECT CLASSID FROM [sAssessment].[tCCEExamMapping] WHERE CCEExamId = @rCCEExamId AND CLASSID = @rClassId AND ExamId <> @rExamId ) 
    BEGIN
		DELETE  RD FROM sAssessment.tCCEResultDetail  RD
			INNER JOIN sAssessment.tCCEResult R ON R.AcademicId=RD.AcademicId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId
			WHERE (SA.ClassId=@rClassId OR @rClassId = 0)
	END
	
    IF NOT EXISTS (SELECT CLASSID FROM [sAssessment].[tCCEExamMapping] WHERE CCEExamId = @rCCEExamId AND CLASSID = @rClassId  ) 
	BEGIN
	INSERT INTO [sAssessment].[tCCEExamMapping]
			   (
			    [CCEExamId]
			   ,[ClassId]
			   ,[BatchId]
			   ,[ExamId]
			   )
		 VALUES
			   (
			    @rCCEExamId
			   ,@rClassId
			   ,@rBatchId
			   ,@rExamId
			   )
	 END

 
	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCCEExamMappingGet]
	  @rClassId int,
	  @rBatchId int,
	  @rDivisionId int,
	  @rCCEEXAMID int=0 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
SELECT
	ISNULL(EM.ID,0) AS CCEEXAMID,
	ISNULL(CE.CLASSId,0) AS CLASSID,
	ISNULL(CE.ExamId,0) AS ExamId,
	EM.Title AS ExamName,
	0 AS MaxMark,
	isnull(SM.Title,'Process Schedule') AS Status,
	ISNULL(ES.Id,0) AS ExamStatusId,
	ISNULL(CM.DisplayTitle + ' - ' + DM.Displaytitle,'') as ClassName,
	ISNULL(DM.Id,0) as DivisionId
FROM
sAssessment.tCCEExamMapping CE
RIGHT JOIN sAssessment.tCCEEXAMMASTER EM ON EM.Id = CE.CCEExamId AND CE.ClassId = @rClassId 
INNER JOIN sAssessment.tCCEExamSetting CSE ON CSE.CCEExamId=EM.Id AND CSE.CLASSId = @rClassId
INNER JOIN sSetup.tClassMaster CM ON CM.Id=@rClassId
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =@rClassId
LEFT JOIN sAssessment.tCCEExamStatus ES ON EM.Id=ES.CCEExamId AND ES.DivisionId=DM.Id
LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=ES.StatusId
WHERE  
EM.Id IN (7,8) and
		 (DM.Id=@rDivisionId OR @rDivisionId =0)
	--AND EM.Id = case  when @rCCEEXAMID = 7 Then EM.Id=7 end
		ORDER BY  EM.Title ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCCEExamSettingAdd]
	 
            @rClassId int
           ,@rCCEExamId int
		   ,@rMaxMark Decimal
		   ,@rGradeSetId Int
		   ,@rExamSubGroupId Int
		   ,@rBatchId Int,
		   @rCSgradeSetId int=0,
		   @rDecimalFormat nvarchar(10),
		   @rIsGradeUpgrade bit
		   
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
BEGIN  
  BEGIN
	DELETE FROM [sAssessment].[tCCEExamSetting] WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId
 	INSERT INTO [sAssessment].[tCCEExamSetting]
			   (
			    [CCEExamId]
			   ,[ClassId]
			   ,[MaxMark]
			   ,[ExamSubGroupId]
			   ,[GradeSetId]
			   ,[BatchId],
			   CSGradeSetId,
			   DecimalFormat,
			   IsUpgradGrade
			   )
		 VALUES
			   (
			    @rCCEExamId
			   ,@rClassId
			   ,@rMaxMark
			   ,@rExamSubGroupId
			   ,@rGradeSetId
			   ,@rBatchId,
			   @rCSGradeSetId,
			   @rDecimalFormat,
			  @rIsGradeUpgrade
			   )
		    SELECT 1 AS Result
	END
		--COMMIT TRANSACTION         
END	 
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCCEExamSettingGet]
	  @rClassId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
SELECT
	ISNULL(EM.ID,0) AS CCEEXAMID,
	ISNULL(CE.CLASSId,0) AS CLASSID,
	ISNULL(CE.MAXMARK,0) AS MAXMARK,
	ISNULL(CE.ExamSubGroupId,0) AS ExamSubGroupId,
	ISNULL(CE.GradeSetId,0) AS GradeSetId,
	EM.Title AS ExamName,
	ISNULL(CE.CSGradeSetId,0) AS CSGradeSetId,
	ISNULL(CE.DecimalFOrmat,0) AS DecimalFOrmat,
	ISNULL(CE.isupgradGrade,0) As IsUpgradeGrade
FROM
sAssessment.tCCEEXAMSETTING CE 
RIGHT JOIN sAssessment.tCCEEXAMMASTER EM ON EM.Id = CE.CCEExamId AND CE.CLASSId = @rClassId 
--WHERE EM.ID>=7

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCCEExamStatusAdd]
	 
	        @rId bigint
           ,@rCCEExamId int
		   ,@rDivisionId int
		   ,@rStatusId int
		   ,@rBatchId int
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF NOT EXISTS (SELECT 1 FROM sAssessment.tCCEExamStatus WHERE CCEExamId =@rCCEExamId AND DivisionId = @rDivisionId )	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEExamStatus', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCEExamStatus]
			   (
			    Id
			   ,CCEExamId 
			   ,DivisionId 
			   ,StatusId 
			   ,BatchId
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCCEExamId
			   ,@rDivisionId 
			   ,@rStatusId
			   ,@rBatchId
			   )
		    SELECT @lNextNumber AS Result
		       
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCEExamStatus]
	    SET
			   -- ExamId =@rExamId 
			   --,DivisionId=@rDivisionId
			   StatusId=@rStatusId 
	      --WHERE Id = @rId 
	      WHERE CCEExamId =@rCCEExamId AND DivisionId=@rDivisionId	 AND BatchId=@rBatchId
	      SELECT @lNextNumber AS Result
	
		
	 END  
--COMMIT TRANSACTION		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCCEFAExamScoreAdd]
	 
            @rAcademicId bigint
           ,@rExamId int
           ,@rClassSubjectId int
           ,@rIndicator nvarchar(200)
		   ,@rGrade nvarchar(10)
		   ,@rDescriptiveIndicator nvarchar(200)
		   ,@rCCEFAId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT CCEFAId FROM sAssessment.tCCEFAExamScore WHERE CCEFAId=@rCCEFAId AND AcademicId=@rAcademicId)	
BEGIN
	INSERT INTO [sAssessment].[tCCEFAExamScore]
			   (
			    [CCEFAId]
			   ,[ExamId]
			   ,[ClassSubjectId]
			   ,[AcademicId]
			   ,[GradeIndicator]
			   ,[Grade]
			   ,[DescriptiveIndicator]
			   )
		 VALUES
			   (
				@rCCEFAId
			   ,@rExamId	
			   ,@rClassSubjectId
			   ,@rAcademicId
			   ,@rIndicator
			   ,@rGrade
			   ,@rDescriptiveIndicator
			   )
		    SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	    UPDATE  [sAssessment].[tCCEFAExamScore]
	    SET
			 
	          [AcademicId]=@rAcademicId
	         ,[ExamId] =@rExamId
	         ,[ClassSubjectId]=@rClassSubjectId
	         ,GradeIndicator=@rIndicator
			 ,Grade =@rGrade
			 ,DescriptiveIndicator=@rDescriptiveIndicator
	      WHERE CCEFAId=@rCCEFAId AND AcademicId=@rAcademicId 	   
	      SELECT 1 AS Result
	 END  
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCCEMarkEntryDetailGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rCCEExamId int,
	 @rClassSubjectId int
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

SELECT 
	
	SA.Name AS StudentName,
	SA.RollNo,
	SA.Code,
	SA.AcademicId,
	ISNULL(R.AcademicId,0) AS CCEResultId,
	ISNULL(RD.AcademicId,0) AS CCEResultDetailId,
	ISNULL((select MaxMark from sAssessment.tCCEExamSetting where CCEExamId=@rCCEExamId AND ClassId=@rClassId),0) AS MaxMark,
	ISNULL((SELECT CASE(@rCCEExamId) WHEN 1 THEN RD.GradePointFA1
							 WHEN 2 THEN RD.GradePointFA2
							 WHEN 3 THEN RD.GradePointSA1 
							 WHEN 4 THEn RD.GradePointFA3 
							 WHEN 5 THEN RD.GradePointFA4 
							 ELSE RD.GradePointSA2 END where RD.ClassSubjectId=@rClassSubjectId),0)  AS GradePoint
	
							 
							 
							 
	
	
from 
	sStudent.vStudentAcademic SA 
	LEFT JOIN sAssessment.tCCEResult R ON R.AcademicId=SA.AcademicId
	LEFT JOIN sAssessment.tCCEResultDetail RD ON RD.AcademicId=R.AcademicId AND ClassSubjectId=@rClassSubjectId
	--LEFT JOIN sSetup.tClassSubject CS ON RD.ClassSubjectId=
	
	
	

Where 
       (SA.DivisionId=@rDivisionId OR @rDivisionId = 0)
	   AND (SA.ClassId = @rClassId OR @rClassId = 0)  
	 
	  
Order By SA.RollNo
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCCEMarkEntryGet]
	 @rClassId int,
	 @rExamId int,
	 @rAcademicId bigint,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

	SELECT 
	ISNULL(RD.ID,0) AS ResultDetailId,
	ED.ClassSubjectId AS ClassSubjectId,
	ISNULL(RD.Obtain,0) AS Obtain
	--/isnull(ED.Maximum,1)*100
FROM sAssessment.tResultDetail RD 
	INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId
	INNER JOIN 	sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId
	INNER JOIN sAssessment.tExamMaster EM ON SA.ClassId = EM.ClassId  AND EM.Id=R.ExamId 
	AND (EM.Id = @rExamId) AND EM.ClassId=@rClassId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id AND RD.ExamDetailId = ED.Id		
Where   SA.ACADEMICID = @rAcademicId AND  SA.StatusId=1 AND SA.BatchId=@rBatchId Order By SA.RollNo
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAssessment].[pCCEResultAdd] 
	        @rAcademicId bigint
		   ,@rUpdatedUserId bigint
		   ,@rOrgId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	 DECLARE @lNextNumber BIGINT 
 	
IF NOT EXISTS(SELECT 1 FROM sAssessment.tCCEResult WHERE AcademicId=@rAcademicId) 
BEGIN
	 
	INSERT INTO [sAssessment].[tCCEResult]
			   (
			  [AcademicId]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@rAcademicId
			   ,@rUpdatedUserId		   
			   ,sCommon.fGetDate()
			   )
		  
	END	 
 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAssessment].[pCCEResultDetailAdd]
	 
	     
            @rAcademicId bigint
		   ,@rClassSubjectId int
		   ,@rObtain decimal(6,2)		
		   ,@rExamOrder int
		   ,@rCCEExamId INT  -- CCEId
		   ,@rSubExamId INT  -- CCEId
		   ,@rOrgId int
		   ,@rIsPresent bit = null,
		   @rCCEGradePointMarks decimal(6,2)=0,
		   @rClassId int=0,
		   @rSubjectMaximum decimal(6,2)=0,
		   @rFA1DecimalFormat int=0,
		   @rFA2DecimalFormat int=0,
		   @rFA3DecimalFormat int=0,
		   @rFA4DecimalFormat int=0,
		   @rSA1DecimalFormat int=0,
		   @rSA2DecimalFormat int=0,
		   @rTerm1DecimalFormat int=0,
		   @rTerm2DecimalFormat int=0,
		   @rAnnualDecimalFormat int=0 ,
		    @rFA1GradePointMax decimal(6,2)=0,
		   @rFA2GradePointMax decimal(6,2)=0,
		   @rFA3GradePointMax decimal(6,2)=0,
		   @rFA4GradePointMax decimal(6,2)=0,
		   @rSA1GradePointMax decimal(6,2)=0,
		   @rSA2GradePointMax decimal(6,2)=0,
		  
		   @rIsIncludeInTotal bit=0,
		   @rIncludeInTotalTerm1 bit=0,
		   @rIncludeInTotalTerm2 bit=0,
		   @rIncludeInTotalAnnual bit=0,
		   @rIsGradeUpdate bit=0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMaxiMark decimal(6,2)
	 --SELECT  @lMaxiMark = Maximum FROM sAssessment.tExamDetail Where ExamId = @rSubExamId AND ClassSubjectId = @rClassSubjectId
	 SET @lMaxiMark = @rSubjectMaximum
	

 
--IF ISNULL(@lCCEResultDetailId,0) = 0
	IF NOT EXISTS(select 1 from  sAssessment.tCCEResultDetail Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId)
	 BEGIN

	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	

	INSERT INTO [sAssessment].[tCCEResultDetail]
			   (
				[AcademicId] 
			   ,[ClassSubjectId]
			   ,[GradePointFA1]
			   ,[GradePointFA2]
			   ,[GradePointSA1]
			   ,[GradePointFA3]
			   ,[GradePointFA4]
			   ,[GradePointSA2]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime],
			   MaxGradePointFA1,
			   MaxGradePointFA2,
			   MaxGradePointSA1,
			   MaxGradePointFA3,
			   MaxGradePointFA4,
			   MaxGradePointSA2,
			    IncludeInTotalTerm1,
			    IncludeInTotalTerm2,
			    IncludeInTotalAnnual,
			    IsUpgradedGrade
			   
			   )
		 VALUES
			   (
			    @rAcademicId
			   ,@rClassSubjectId
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0
			   ,sCommon.fGetDate(),
			   0.00,
			   0.00,
			   0.00,
			   0.00,
			   0.00,
			   0.00,
			   0,
			   0,
			   0,
			   @rIsGradeUpdate
			   ) 
			  
END		 
     		IF(@rExamOrder=1) 
     		BEGIN
     			if (@rIsIncludeInTotal = 1 )  
     			begin   		
     				set @rFA1GradePointMax = @rFA1GradePointMax
     			END
     			else
     			BEGIN
     			set @rFA1GradePointMax = 0     		 
     		    END 
     	 
     		UPDATE [sAssessment].[tCCEResultDetail] 
            SET [FA1]=ISNULL(@rObtain,0),FA1Max =@lMaxiMark ,IsPresentFA1=@rIsPresent,
     		GRADEPOINTFA1 = round((@rCCEGradePointMarks *ISNULL(@rObtain,0))/@lMaxiMark,@rFA1DecimalFormat), 
     		MaxGradePointFA1 = @rFA1GradePointMax
     		Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
     	 
     		END		
     		
		    IF(@rExamOrder=2) 
			BEGIN
			if (@rIsIncludeInTotal = 1 )     	
			BEGIN	
     			set @rFA2GradePointMax = @rFA2GradePointMax
     		END
     		else
			BEGIN
     			set @rFA2GradePointMax = 0     	
     		END	
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [FA2]=ISNULL(@rObtain,0),FA2Max =@lMaxiMark ,IsPresentFA2=@rIsPresent,
			GradePointFA2 =round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,@rFA2DecimalFOrmat),
			MaxGradePointFA2 =@rFA2GradePointMax
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			END
			
			 IF(@rExamOrder=3)
			BEGIN
			if (@rIsIncludeInTotal = 1 )   
		 		
     			set @rSA1GradePointMax = @rSA1GradePointMax
     	 
     		else
     		 
     			set @rSA1GradePointMax = 0     
     			
     	    if (@rIncludeInTotalTerm1 = 1 )   
		 		
     			set @rIncludeInTotalTerm1 = @rIncludeInTotalTerm1
     	 
     		else
     		 
     			set @rIncludeInTotalTerm1 = 0      
     				
			 UPDATE [sAssessment].[tCCEResultDetail] 
			 SET [SA1]=ISNULL(@rObtain,0),SA1Max =@lMaxiMark ,IsPresentSA1=@rIsPresent,
			 GradePointSA1 =round((@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark,@rSA1DecimalFormat),
			  MaxGradePointSA1 = @rSA1GradePointMax,IncludeInTotalTerm1=@rIncludeInTotalTerm1
			 Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			 
			 UPDATE [sAssessment].[tCCEResultDetail] 
			 SET [Term1]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(SA1,0),Term1TotalGradePoint =  ROUND(GradePointFA1+ ISNULL(GradePointFA2,0)+ GradePointSA1,
			  @rTerm1DecimalFormat) 
			  --Term1GradePoint = ROUND(( ISNULL(GradePointFA1,0)+ ISNULL(GradePointFA2,0)+ ISNULL(GradePointSA1,0)) * 10 / 50 ,@rTerm1DecimalFormat) 
			 Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			 END
			 
			IF(@rExamOrder=4) 
			BEGIn
			if (@rIsIncludeInTotal = 1 )  
			BEGIN   		
     			set @rFA3GradePointMax = @rFA3GradePointMax
     		ENd
     		else
     		BEGIN
     			set @rFA3GradePointMax = 0   
     		ENd
     			  
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [FA3]=ISNULL(@rObtain,0),FA3Max =@lMaxiMark ,IsPresentFA3=@rIsPresent,
			GradePointFA3 = round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,@rFA3DecimalFormat)  ,
			MaxGradePointFA3 = @rFA3GradePointMax
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			END
			
			IF(@rExamOrder=5) 
			BEGIN
			if (@rIsIncludeInTotal = 1 )     	
			BEGIN	
     			set @rFA4GradePointMax = @rFA4GradePointMax
     		END
     		else
     		BEGIN
     			set @rFA4GradePointMax = 0   
     		END
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [FA4]=ISNULL(@rObtain,0),FA4Max =@lMaxiMark ,IsPresentFA4=@rIsPresent,
			GradePointFA4 =round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,@rFA4DecimalFormat) ,
			MaxGradePointFA4 = @rFA4GradePointMax
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			END
			
			  IF(@rExamOrder=6) 
			BEGIN
			if (@rIsIncludeInTotal = 1 )     	
			BEGIN	
     			set @rSA2GradePointMax = @rSA2GradePointMax
			END
     		else
     		BEGIN
     			set @rSA2GradePointMax = 0  
     		END
     		if (@rIncludeInTotalTerm2 = 1 )     	
			BEGIN	
     			set @rIncludeInTotalTerm2 = @rIncludeInTotalTerm2
			END
     		else
     		BEGIN
     			set @rIncludeInTotalTerm2 = 0  
     		END
     		if (@rIncludeInTotalAnnual = 1 )     	
			BEGIN	
     			set @rIncludeInTotalAnnual = @rIncludeInTotalAnnual
			END
     		else
     		BEGIN
     			set @rIncludeInTotalAnnual = 0  
     		END
     		
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [SA2]=ISNULL(@rObtain,0),SA2Max =@lMaxiMark ,IsPresentSA2=@rIsPresent,
			GradePointSA2 =round((@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark,@rSA2DecimalFormat),
			  MaxGradePointSA2 = @rSA2GradePointMax,IncludeInTotalTerm2=@rIncludeInTotalTerm2,IncludeInTotalAnnual=@rIncludeInTotalAnnual
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
		 
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [FA]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0),
			FAGradePoint=ROUND(GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4,0) 
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [SA]=ISNULL(SA1,0)+ISNULL(SA2,0),SAGradePoint = ROUND( GradePointSA1+GradePointSA2  ,0) 
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
				
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [Term2]=ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA2,0), 
			Term2TotalGradePoint =  ROUND(GradePointFA3+GradePointFA4+ GradePointSA2, @rTerm2DecimalFormat ) 
			--Term2GradePoint = ROUND(( ISNULL(GradePointFA3,0)+ISNULL(GradePointFA4,0)+ISNULL(GradePointSA2,0)) * 10 / 50 ,@rTerm2DecimalFormat) 
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
			UPDATE [sAssessment].[tCCEResultDetail] 
			SET [TOTAL]=ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA1,0)+ISNULL(SA2,0) 
			Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
		     END
        
--	END	 
--ELSE
--	 BEGIN
 
	     	 
	     
--	        IF(@rExamOrder=1) 
--	        UPDATE [sAssessment].[tCCEResultDetail] SET [FA1]=ISNULL(@rObtain,0),FA1Max =@lMaxiMark ,IsPresentFA1=@rIsPresent,	GRADEPOINTFA1 = round((@rCCEGradePointMarks *ISNULL(@rObtain,0))/@lMaxiMark,Convert(INT,@rFA1DecimalFormat))Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			ELSE IF(@rExamOrder=2) UPDATE [sAssessment].[tCCEResultDetail] SET [FA2]=ISNULL(@rObtain,0),FA2Max =@lMaxiMark ,IsPresentFA2=@rIsPresent,GradePointFA2 =round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,Convert(INT,@rFA2DecimalFOrmat)) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			ELSE IF(@rExamOrder=3)
--			BEGIN
--			 UPDATE [sAssessment].[tCCEResultDetail] SET [SA1]=ISNULL(@rObtain,0),SA1Max =@lMaxiMark ,IsPresentSA1=@rIsPresent,GradePointSA1 =round((@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark,Convert(INT,@rSA1DecimalFormat)) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			 UPDATE [sAssessment].[tCCEResultDetail] SET [Term1]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(SA1,0),Term1TotalGradePoint = ROUND(GradePointFA1+GradePointFA2+GradePointSA1 ,Convert(INT,@rTerm1DecimalFormat)),Term1GradePoint = ROUND(( ISNULL(GradePointFA1,0)+ ISNULL(GradePointFA2,0)+ ISNULL(GradePointSA1,0)) * 10 / 50 ,Convert(INT,@rTerm1DecimalFormat)) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			 END
--			ELSE IF(@rExamOrder=4) UPDATE [sAssessment].[tCCEResultDetail] SET [FA3]=ISNULL(@rObtain,0),FA3Max =@lMaxiMark ,IsPresentFA3=@rIsPresent,GradePointFA3 =   round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,Convert(INT,@rFA3DecimalFormat))  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			ELSE IF(@rExamOrder=5) UPDATE [sAssessment].[tCCEResultDetail] SET [FA4]=ISNULL(@rObtain,0),FA4Max =@lMaxiMark ,IsPresentFA4=@rIsPresent,GradePointFA4 =round((@rCCEGradePointMarks * ISNULL(@rObtain,0))/@lMaxiMark,Convert(INT,@rFA4DecimalFormat)) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			ELSE IF(@rExamOrder=6) UPDATE [sAssessment].[tCCEResultDetail] SET [SA2]=ISNULL(@rObtain,0),SA2Max =@lMaxiMark ,IsPresentSA2=@rIsPresent,GradePointSA2 =round((@rCCEGradePointMarks *ISNULL(@rObtain,0) )/@lMaxiMark,Convert(INT,@rSA2DecimalFormat))   Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			BEGIN
--			UPDATE [sAssessment].[tCCEResultDetail] SET [FA]= ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0),FAGradePoint=ROUND(GradePointFA1+GradePointFA2+GradePointFA3 +GradePointFA4,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			UPDATE [sAssessment].[tCCEResultDetail] SET [SA]=ISNULL(SA1,0)+ISNULL(SA2,0),SAGradePoint = ROUND( GradePointSA1+GradePointSA2  ,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
--			UPDATE [sAssessment].[tCCEResultDetail] SET [Term2]=ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA2,0), Term2TotalGradePoint = ROUND(GradePointFA3+GradePointFA4+GradePointSA2 ,Convert(INT,@rTerm2DecimalFormat)),Term2GradePoint = ROUND(( ISNULL(GradePointFA3,0)+ISNULL(GradePointFA4,0)+ISNULL(GradePointSA2,0)) * 10 / 50,Convert(INT,@rTerm2DecimalFormat)) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId

--			UPDATE [sAssessment].[tCCEResultDetail] SET [TOTAL]=ISNULL(FA1,0)+ISNULL(FA2,0)+ISNULL(FA3,0)+ISNULL(FA4,0)+ISNULL(SA1,0)+ISNULL(SA2,0) Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
--			END 
		 
		
	
--	 END  
		
 
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 


CREATE OR ALTER PROCEDURE [sAssessment].[pCCEResultDetailGradeUpdate]
	 
	     
            @rAcademicId bigint
		   ,@rClassSubjectId int
		   ,@rObtain decimal(6,2)		
		   ,@rExamOrder int
		   ,@rCCEExamId INT  -- CCEId
		   ,@rSubExamId INT  -- CCEId
		   ,@rOrgId int
		   ,@rIsPresent bit = null,
		   @rCCEGradePointMarks decimal(6,2)=0,
		   @rClassId int=0
		 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
 
 
 
 
 
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMaxiMark decimal(6,2)	
	 DECLARE @lCCEResultDetailId BIGINT
     DECLARE @lDataSetID INT 
     
 SELECT  @lMaxiMark = Maximum FROM sAssessment.tExamDetail Where ExamId = @rSubExamId AND ClassSubjectId = @rClassSubjectId
 SELECT @lDataSetID=GradeSetId  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId
		
--Grade Evaluation
DECLARE @MinimumScore decimal(5,2)
DECLARE @GradeTitle nvarchar(10)
DECLARE @GradePoint decimal(6,2)
DECLARE @lCount int

--DECLARE @lClassId int

DECLARE @lTempMark decimal(6,2)
 

 	
  

CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(10),
		GradePoint decimal(6,2) 					 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,GradeCode,GradePoint		
	FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	order by MinimumScore DESC

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
DECLARE @lloopCount int
--set @lloopCount=1
while ( @lCount > 0 )
BEGIN
		SELECT @MinimumScore =MinimumScore,@GradeTitle=GradeTitle,@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		 
		IF @rExamOrder = 1 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA1 = @GradeTitle,FA1Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA1 * 100)/@lMaxiMark  >= @MinimumScore 
			
		END
		IF @rExamOrder = 2 
		BEGIN							
			Update sAssessment.tCCEResultDetail  Set GradeFA2 = @GradeTitle,FA2Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA2 * 100)/@lMaxiMark >= @MinimumScore 
			
		END
		IF @rExamOrder = 3 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeSA1 = @GradeTitle,SA1Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (SA1 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
		IF @rExamOrder = 4 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA3 = @GradeTitle,FA3Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA3 * 100)/@lMaxiMark >= @MinimumScore 
			
		END
		IF @rExamOrder = 5 
		BEGIN				
			Update sAssessment.tCCEResultDetail  Set GradeFA4 = @GradeTitle,FA4Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (FA4 * 100)/@lMaxiMark >= @MinimumScore 
			 
		END
		IF @rExamOrder = 6 
		BEGIN		
			Update sAssessment.tCCEResultDetail  Set GradeSA2 = @GradeTitle,SA2Max=@lMaxiMark WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId AND (SA2 * 100)/@lMaxiMark >= @MinimumScore 
			 SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0) FROM sAssessment.tCCEResultDetail 
			WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set FAGRADE = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (FA * 100)/@lTempMark >= @MinimumScore 
			END
		END
		
		 
		

			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set [FATerm1] = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND ((FA1+FA2) * 100)/@lTempMark >= @MinimumScore 
			END

			SELECT @lTempMark = ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set [FATerm2] = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND ((FA3+FA4) * 100)/@lTempMark >= @MinimumScore 
			END
			
			SELECT @lTempMark = ISNULL(SA1MAX,0)+ISNULL(SA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set SAGRADE = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (SA * 100)/@lTempMark >= @MinimumScore 
			END
			
			
			
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN
				Update sAssessment.tCCEResultDetail  Set Term1Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				--AND (TERM1 * 100)/@lTempMark >= @MinimumScore 
				AND (Term1GradePoint * 10) >= @MinimumScore
			END
			
			SELECT @lTempMark = ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0 
			BEGIN	
				Update sAssessment.tCCEResultDetail  Set Term2Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				--AND (TERM2 * 100)/@lTempMark >= @MinimumScore 
				AND (Term2GradePoint*10)>=@MinimumScore
			END
		
		
		
			SELECT @lTempMark = ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0)+ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) FROM sAssessment.tCCEResultDetail WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
			IF @lTempMark <> 0  
			BEGIN
				Update sAssessment.tCCEResultDetail  Set Grade = @GradeTitle WHERE AcademicId=@rAcademicId AND ClassSubjectID=@rClassSubjectId 
				AND (TOTAL * 100)/@lTempMark >= @MinimumScore 
			END 
		SET @lCount = @lCount - 1
 END
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAssessment].[pCCEResultDetailSubjectGradeUpdate]
	  
	
	  @rExamOrder INT
	 ,@rCCEExamId INT
	 ,@rSubExamId INT
	 ,@rBatchId INT
	 ,@rClassId INT,	
	  @rDivisionId int 
		
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
--BEGIN TRY
-- BEGIN TRANSACTION	

	
		DECLARE @MinimumScore decimal(5,2)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @lCount int
		DECLARE @lDataSetID INT
		DECLARE @lMaxiMark Decimal(5,2)
		--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId 
		
		
		 --  Update  D  Set D.FATerm1 = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId
			
		 --  Update  D  Set D.Term1Grade = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	
			
			--Update  D  Set D.FATerm2 = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	

			
			--Update  D  Set D.SAGRADE = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 

			--Update  D  Set D.FAGRADE = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 

	        
	  --      Update  D  Set D.Term2Grade = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	

			
			--Update  D  Set D.Grade = NULL FROM  
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	
	
			
		
	
		 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId AND BatchId = @rBatchId
		 
		 -- CREATE TABLE #tempAcademic
			--(
			--	AcademicId bigint,
			--	classSubjectId decimal(5,2) 				 
			--) 
		 
		CREATE TABLE #tempGradeSetDetail
			(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(10),
		GradePoint decimal(6,2) 					 
			) 
			INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,GradeCode,GradePoint		
	FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	order by MinimumScore DESC

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
 
  
while ( @lCount > 0 )
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@GradeTitle=GradeTitle,
		@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount

		 IF @rExamOrder = 1 
		BEGIN				
			Update  D  Set D.GradeFA1 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			
			AND (((D.FA1 * 100)/FA1Max)  >= @MinimumScore ) 
			--AND FA1MAX > 0 
			 
			
		END
		IF @rExamOrder = 2 
		BEGIN							
		
		
			Update  D  Set D.GradeFA2 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			
			AND (((D.FA2 * 100)/FA2Max)  >= @MinimumScore)  
			--AND FA2MAX > 0
			
		END
		IF @rExamOrder = 3 
		BEGIN				
			
			
		Update  D  Set D.GradeSA1 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId
			
			AND (D.SA1 * 100)/SA1Max  >= @MinimumScore 
			--AND SA1MAX > 0
			 
		END
		IF @rExamOrder = 4 
		BEGIN				
		
		
				
			Update  D  Set D.GradeFA3 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			
			AND (D.FA3 * 100)/FA3Max  >= @MinimumScore
			--AND FA3MAX > 0 
			
		END
		IF @rExamOrder = 5 
		BEGIN				
		
			
			Update  D  Set D.GradeFA4 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			
			AND (D.FA4 * 100)/FA4Max  >= @MinimumScore 
			--And FA4MAx > 0
		END
		IF @rExamOrder = 6 
		BEGIN		
		
			Update  D  Set D.GradeSA2 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			
			AND (D.SA2 * 100)/SA2Max  >= @MinimumScore 
			--AND SA2Max > 0
			 
		END
		
		
	if (@rCCEExamId = 7 AND @rExamOrder=3)
	begin
	
	   --Truncate Table #tempAcademic
	 
		--INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where (ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0) > 0 )
		 
	
	
			-- ALL FA Term1	
			
			
			
			
			
			Update  D  Set D.FATerm1 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND  ((ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)) > 0 )	
			AND ISNULL( ((D.FA1+D.FA2) * 100)/NULLIF(ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0),0),0)  >= @MinimumScore
			AND (NULLIF(ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0),0) > 0)
			
	
	
		--   Truncate Table #tempAcademic
	 
		--INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where ((ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) > 0 ))		
			
			-- Term1
			
			
			
			Update  D  Set D.Term1Grade = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND ((ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0) > 0 ))
			 AND ISNULL(( Term1TotalGradePoint * 100)/NULLIF(ISNULL(MaxGradePointFA1,0)+ISNULL(MaxGradePointFA2,0)+ISNULL(MaxGradePointSA1,0),0),0)  >= @MinimumScore 
		 	--DECLARE @lGrade nvarchar(10),@lGradePoint decimal(6,2)
			--Set @lGrade = (Select GS.GradeCode,GS.GradePoint from 	sAssessment.tGradeSetDetail GS 
			--INNER JOIN #tempGradeSetDetail TG ON TG.Id = GS.gradesetId WHere GS.Gradesetid=@lDataSetID)
			
			 UPDATE sAssessment.tCCEResultDetail Set Term1GradePoint = @GradePoint 
			 Where  Term1Grade = @GradeTitle AND AcademicId IN (Select Id From sStudent.tAcademic 
			 Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)	
	
		 
	END	
		
	if (@rCCEExamId = 8 AND @rExamOrder=6)
	BEGIN
	    
	    
	 --   		   Truncate Table #tempAcademic
	 
		--INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where ((ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)) > 0 )		
	       
			-- Term2 FA	Grade
			
			
			
				Update  D  Set D.FATerm2 = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND ((ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)) > 0 )		
			AND ((D.FA3+D.FA4) * 100)/NULLIF(ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0),0)  >= @MinimumScore
		     AND (NULLIF(ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0),0) > 0)
		
		--		INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where ( (ISNULL(SA1MAX,0)+ISNULL(SA2MAX,0))	> 0)
		
			-- All SA	
		
		

			
				Update  D  Set D.SAGRADE = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND ( (ISNULL(SA1MAX,0)+ISNULL(SA2MAX,0))	> 0)
			AND (( D.SA * 100)/NULLIF(ISNULL(SA1MAX,0)+ISNULL(SA2MAX,0),0)  >= @MinimumScore)
			
	
		--		INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where ((ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)) > 0 )
		
			-- ALL FA Grade	
			


			
			Update  D  Set D.FAGRADE = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND ((ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)) > 0 )
			AND ((D.FA * 100)/NULLIF(ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0),0)   >= @MinimumScore )


		--		INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where (ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0)) > 0		
			
	        -- Term 2 Grade
	   
	        
			Update  D  Set D.Term2Grade = @GradeTitle FROM
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND (ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0)) > 0
			AND (( Term2TotalGradePoint * 100)/NULLIF(ISNULL(MaxGradePointFA3,0)+ISNULL(MaxGradePointFA4,0)+ISNULL(MaxGradePointSA2,0),0)  >= @MinimumScore)
			
			--select   @GradeTitle,A.Id,D.Term2TotalGradePoint,( Term2TotalGradePoint * 100)/NULLIF(ISNULL(MaxGradePointFA3,0)+ISNULL(MaxGradePointFA4,0)+ISNULL(MaxGradePointSA2,0),0),@MinimumScore    FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			-- WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			-- AND (( Term2TotalGradePoint * 100)/NULLIF(ISNULL(MaxGradePointFA3,0)+ISNULL(MaxGradePointFA4,0)+ISNULL(MaxGradePointSA2,0),0)  >= @MinimumScore)
			
			
			 UPDATE sAssessment.tCCEResultDetail Set Term2GradePoint = @GradePoint 
			 Where  Term2Grade = @GradeTitle AND AcademicId IN (Select Id From sStudent.tAcademic 
			 Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)	
	
		--			INSERT INTO #tempAcademic
		--SELECT AcademicId,ClassSubjectId	
		--FROM sAssessment.tCCEResultDetail where (ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0)) > 0
			-- overall Grade
		
			
			
			Update  D  Set D.Grade = @GradeTitle FROM  
			sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			--INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 
			--AND (ISNULL(FA1MAX,0)+ISNULL(FA2MAX,0)+ISNULL(SA1MAX,0)+ISNULL(FA3MAX,0)+ISNULL(FA4MAX,0)+ISNULL(SA2MAX,0)) > 0
			--AND ( (D.Term1TotalGradePoint+D.Term2TotalGradePoint) * 100)/NULLIF(ISNULL(MaxGradePointFA1,0)+ISNULL(MaxGradePointFA2,0)+ISNULL(MaxGradePointSA1,0)+ISNULL(MaxGradePointFA3,0)+ISNULL(MaxGradePointFA4,0)+ISNULL(MaxGradePointSA2,0),0)  >= @MinimumScore
			AND Round((D.Term1TotalGradePoint+D.Term2TotalGradePoint),0)  >= @MinimumScore
   	      UPDATE sAssessment.tCCEResultDetail Set GradePoint = (@GradePoint) Where  Grade = @GradeTitle AND AcademicId IN (Select Id From sStudent.tAcademic Where ClassId=@rClassId And BatchId=@rBatchId AND DivisionId=@rDivisionId)	
	

	
	END		 
 
		 
		 
			SET @lCount = @lCount - 1
		
 END
 
 if (@rCCEExamId = 7 AND @rExamOrder=3)
	begin
	
		update CR set Term1CGPA =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(ISNULL(Term1GradePoint,0)) AS GradePoint,AcademicId 
		From sAssessment.tCCEResultDetail WHERE ISNULL(IncludeInTotalTerm1,0) > 0  Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId 
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		
	
	end
 	  
  if (@rCCEExamId = 8 AND @rExamOrder=6)
	BEGIN
	
		update CR set Term2CGPA =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(ISNULL(Term2GradePoint,0)) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail WHERE ISNULL(IncludeInTotalTerm2,0) > 0 Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId 
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
         
	
	
		update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
			Inner Join (select Avg(ISNULL(GradePoint,0)) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail WHERE  ISNULL(IncludeInTotalAnnual,0)  > 0 Group By ACademicId ) CRD 
			ON CR.AcademicId = CRD.AcademicId
			INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
			AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
			
		 
    END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pCCEResultGenerate]
	
	@rClassId int,
	@rExamId int,
	@rBatchId int,
	@rOrgId int,
	@rExamOrder int,
	@rCCEExamId int,
	@rDivisionId int,
	@rExam int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	
	
	DECLARE @lCount_MarkEntryStudent int
	DECLARE @lAcademicId bigint,@lGradeUpdate bit,@lExam1 int,@lExam2 int,@lExam3 int
	Declare @lCCESettingMaxMark decimal(6,2),@lIncludeInTotalTerm1 bit,@lIncludeInTotalTerm2 bit,@lIncludeInTotalAnnual bit 
	Declare @lFA1GradePointMax decimal(6,2),@lFA2GradePointMax decimal(6,2),@lSA1GradePointMax decimal(6,2),@lFA3GradePointMax decimal(6,2),
			@lFA4GradePointMax decimal(6,2),@lSA2GradePointMax decimal(6,2),@lTerm1GradePointMax decimal(6,2),@lTerm2GradePointMax decimal(6,2),@lAnnualGradePointMAx decimal(6,2)
	
	
	SELECT @lCCESettingMaxMark=MaxMark  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rExamOrder AND ClassId = @rClassId AND BatchId = @rBatchId
	SELECT @lGradeUpdate=IsUpgradGrade FROM sAssessment.tCCEExamSetting WHERE  ClassId = @rClassId AND BatchId = @rBatchId AND CCEExamId=@rCCEExamId
		 
	 Declare @lFA1DecimalFormat nvarchar(10),@lFA2DecimalFormat nvarchar(10),@lFA3DecimalFormat nvarchar(10),@lFA4DecimalFormat nvarchar(10),@lSA1DecimalFormat nvarchar(10),@lSA2DecimalFormat nvarchar(10)
	 Declare @lTerm1DecimalFormat nvarchar(10),@lTerm2DecimalFormat nvarchar(10),@lAnnualDecimalFormat nvarchar(10)
	
	
	 Select @lFA1DecimalFormat = DecimalFormat,@lFA1GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 1 AND BatchId = @rBatchId
	 Select @lFA2DecimalFormat = DecimalFormat,@lFA2GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 2 AND BatchId = @rBatchId
	 Select @lFA3DecimalFormat = DecimalFormat,@lFA3GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 4 AND BatchId = @rBatchId
	 Select @lFA4DecimalFormat = DecimalFormat,@lFA4GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 5 AND BatchId = @rBatchId
	 Select @lSA1DecimalFormat = DecimalFormat,@lSA1GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 3 AND BatchId = @rBatchId
	 Select @lSA2DecimalFormat = DecimalFormat,@lSA2GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 6 AND BatchId = @rBatchId
	 Select   @lTerm1DecimalFormat = DecimalFormat,@lTerm1GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND   CCEExamId = 7 AND BatchId = @rBatchId
	 Select   @lTerm2DecimalFormat = DecimalFormat,@lTerm2GradePointMax=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 8 AND BatchId = @rBatchId
	 Select  @lAnnualDecimalFormat = DecimalFormat,@lAnnualGradePointMAx=MaxMark from sAssessment.tCCEExamSetting Where ClassId =@rClassId AND  CCEExamId = 9 AND BatchId = @rBatchId
	 
	 Select @lExam1=EM.Id from sAssessment.tCCEExamSetting ES	 
	 INNER JOIN sAssessment.tExamMaster EM oN EM.ExamSubGroupId = ES.ExamSubGroupId 
	 Where ES.ClassId =@rClassId AND ES.CCEExamId = 7 AND ES.BatchId = @rBatchId AND  EM.ClassId = @rClassId
	 
	  Select @lExam2=EM.Id  from sAssessment.tCCEExamSetting ES 
	  INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = ES.ExamSubGroupId
	  Where ES.ClassId=@rClassId and ES.CCEExamId =8 and Es.BatchId=@rBatchId AND  EM.ClassId = @rClassId
	  
	  Select  @lExam3=EM.Id from sAssessment.tCCEExamSetting ES 
	  INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId= ES.ExamSubGroupId
	  wHERE ES.ClassId=@rClassId AND ES.CCEExamId=9 AND ES.BatchId=@rBatchId AND  EM.ClassId = @rClassId
	  
	  if @lFA1DecimalFormat ='0' BEGIN SET @lFA1DecimalFormat=0 END
	  if @lFA1DecimalFormat ='0.0' BEGIN SET @lFA1DecimalFormat=1 END
	  if @lFA1DecimalFormat ='0.00' BEGIN SET @lFA1DecimalFormat=2 END
	  if @lFA2DecimalFormat ='0' BEGIN SET @lFA2DecimalFormat=0 END
	  if @lFA2DecimalFormat ='0.0' BEGIN SET @lFA2DecimalFormat=1 END
	  if @lFA2DecimalFormat ='0.00' BEGIN SET @lFA2DecimalFormat=2 END
	  if @lFA3DecimalFormat ='0' BEGIN SET @lFA3DecimalFormat=0 END
	  if @lFA3DecimalFormat ='0.0' BEGIN SET @lFA3DecimalFormat=1 END
	  if @lFA3DecimalFormat ='0.00' BEGIN SET @lFA3DecimalFormat=2 END
	  if @lFA4DecimalFormat ='0' BEGIN SET @lFA4DecimalFormat=0 END
	  if @lFA4DecimalFormat ='0.0' BEGIN SET @lFA4DecimalFormat=1 END
	  if @lFA4DecimalFormat ='0.00' BEGIN SET @lFA4DecimalFormat=2 END
	   
	  if @lSA1DecimalFormat ='0' BEGIN SET @lSA1DecimalFormat=0 END
	  if @lSA1DecimalFormat ='0.0' BEGIN SET @lSA1DecimalFormat=1 END
	  if @lSA1DecimalFormat ='0.00' BEGIN SET @lSA1DecimalFormat=2 END
	  if @lSA2DecimalFormat ='0' BEGIN SET @lSA2DecimalFormat=0 END
	  if @lSA2DecimalFormat ='0.0' BEGIN SET @lSA2DecimalFormat=1 END
	  if @lSA2DecimalFormat ='0.00' BEGIN SET @lSA2DecimalFormat=2 END
	  if @lTerm1DecimalFormat ='0' BEGIN SET @lTerm1DecimalFormat=0 END
	  if @lTerm1DecimalFormat ='0.0' BEGIN SET @lTerm1DecimalFormat=1 END
	  if @lTerm1DecimalFormat ='0.00' BEGIN SET @lTerm1DecimalFormat=2 END
	  if @lTerm2DecimalFormat ='0' BEGIN SET @lTerm2DecimalFormat=0 END
	  if @lTerm2DecimalFormat ='0.0' BEGIN SET @lTerm2DecimalFormat=1 END
	  if @lTerm2DecimalFormat ='0.00' BEGIN SET @lTerm2DecimalFormat=2 END
	   if @lAnnualDecimalFormat ='0' BEGIN SET @lAnnualDecimalFormat=0 END
	  if @lAnnualDecimalFormat ='0.0' BEGIN SET @lAnnualDecimalFormat=1 END
	  if @lAnnualDecimalFormat ='0.00' BEGIN SET @lAnnualDecimalFormat=2 END


	
	CREATE TABLE #TempMarkEntryStudent(
	[AutoId] [int] identity,
	[AcademicId] [bigint] NOT NULL,
	[ExamId] [int] NULL,
	[OrgId] [int] NULL,
	[ClassId] [int] NULL,
	)
	 
	INSERT INTO #TempMarkEntryStudent 
	SELECT  
		SA.Id  AS AcademicId,
		EM.Id AS ExamId,
		SA.OrgId,
		EM.ClassId
    FROM  
		sStudent.tAcademic  SA 
		INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id 
		INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId 
		INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.Id
		--LEFT JOIN sAssessment.tCCEResult CR ON CR.AcademicId = SA.AcademicId
	WHERE 
		(EM.ClassId = @rClassId OR @rClassId = 0 )    
		AND (EM.Id=@rExamId OR @rExamId = 0)
		AND (EM.BatchId = @rBatchId or @rBatchId=0)
		AND SM.StatusId=1
		AND SA.BatchId=@rBatchId
		AND SA.DivisionId=@rDivisionId
    
    SET @lCount_MarkEntryStudent = 0
    SELECT @lCount_MarkEntryStudent = COUNT(AutoId) FROM #TempMarkEntryStudent
     
     --SELECT * FROM #TempMarkEntryStudent
    
  --  EXEC sAssessment.pCCEResultDetailSubjectGradeUpdate @rExamOrder,@rCCEExamId,@rExamId,@rBatchId,@rClassId,@rDivisionId,
		--@rFA1GradePointMax = @lFA1GradePointMax,@rFA2GradePointMax=@lFA2GradePointMax,@rFA3GradePointMax=@lFA3GradePointMax,@rFA4GradePointMax=@lFA4GradePointMax,
		--@rSA1GradePointMax=@lSA1GradePointMax,@rSA2GradePointMax=@lSA2GradePointMax,@rTerm1GradePointMax=@lTerm1GradePointMax,@rTerm2GradePointMax=@lTerm2GradePointMax,
		--@rAnnualGradePointMax=@lAnnualGradePointMAx
    
	CREATE TABLE #TempCCEMarkEntry (
	[AutoId] [int] identity,
	[AcademicId] [bigint] NOT NULL ,
	[ResultDetailId] [bigint] NULL,
	[ClassSubjectId] [int] NULL,
	[Obtain] [decimal](5,2) NULL,
	[IsPresent] [bit] NULL,
	[ExamId] [int] NULL,
	SubjectMaximum [decimal](5,2) NULL,
	IsIncludeInTotal bit NULL 
	)
	Declare @lConvertedMark decimal(6,2)
	 
	WHILE (@lCount_MarkEntryStudent > 0)
	BEGIN
		
		SET @lAcademicId = 0
		SELECT @lAcademicId = AcademicId FROM #TempMarkEntryStudent WHERE AutoId = @lCount_MarkEntryStudent
		 
	    EXEC sAssessment.pCCEResultAdd @rAcademicId=@lAcademicId,@rUpdatedUserId=0,@rOrgId=@rOrgId
			
		INSERT INTO #TempCCEMarkEntry 
		SELECT 
			SA.Id as AcademicId,
			ISNULL(RD.ID,0) AS ResultDetailId,
			ED.ClassSubjectId AS ClassSubjectId,
			ISNULL(RD.Obtain,0) AS Obtain,
			RD.IsPresent,
			@rExamId,
			ED.Maximum AS SubjectMaximum,
			ED.IsIncludeInTotal
		FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId
			INNER JOIN 	sStudent.tAcademic SA ON SA.Id = R.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON  EM.Id=R.ExamId 	
			INNER JOIN sAssessment.tExamDetail ED ON  RD.ExamDetailId = ED.Id		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.Id and o.ClassSubjectId=CS. Id  
			    AND SA.Id =@lAcademicId
		WHERE
			(SA.ClassId = @rClassId)    
			AND SM.StatusId=1
			AND SA.BatchId=@rBatchId
			AND R.ExamId = @rExamId
			AND R.AcademicId = @lAcademicId
			AND SA.DivisionId =@rDivisionId
			 AND ((CS.IsOptional = 1 AND  isnull(o.AcademicId,0)<>0) OR (CS.IsOptional = 0))   
			 
			DECLARE @lCount int
			SET @lCount = 0
			SELECT @lCount = COUNT(AcademicId) FROM #TempCCEMarkEntry
			 
				WHILE (@lCount > 0)
				BEGIN
					DECLARE @lClassSubjectId int
				    DECLARE @lObtain decimal(5,2)
				    DECLARE @lIsPresent bit
				    DECLARE @rIsPresent bit
				    DECLARE @lSubjectMaximum decimal(5,2)
				    Declare @lIsIncludeInTotal bit  
					SELECT @lClassSubjectId = ClassSubjectId,@lIsIncludeInTotal=IsIncludeInTotal, @lObtain = Obtain,@lIsPresent = IsPresent,@lSubjectMaximum = SubjectMaximum   FROM #TempCCEMarkEntry WHERE AcademicId = @lAcademicId AND ExamId = @rExamId AND AutoId = @lCount
					
					if @rExamOrder=3
				BEGIN
					Select @lIncludeInTotalTerm1=IsIncludeInTotal  from sAssessment.tExamDetail Where Examid = @lExam1 AND ClassSubjectId= @lClassSubjectId
					 --Select @lIncludeInTotalTerm1,@lClassSubjectId
				END
					if @rExamOrder=6
					BEGIN
					Select @lIncludeInTotalTerm2=IsIncludeInTotal  from sAssessment.tExamDetail Where Examid = @lExam2 AND ClassSubjectId= @lClassSubjectId
					Select @lIncludeInTotalAnnual=IsIncludeInTotal  from sAssessment.tExamDetail Where Examid = @lExam3 AND ClassSubjectId= @lClassSubjectId
					--select  @lIncludeInTotalAnnual,@lClassSubjectId,@lExam3
				END
				 
					EXEC sAssessment.pCCEResultDetailAdd @rAcademicId=@lAcademicId,@rClassSubjectId=@lClassSubjectId,@rObtain=@lObtain,@rExamOrder=@rExamOrder,@rCCEExamId=@rCCEExamId,@rSubExamId=@rExamId,@rOrgId=@rOrgId,@rIsPresent=@lIsPresent,@rCCEGradePointMarks=@lCCESettingMaxMark,@rClassId=@rClassId,@rSubjectMaximum = @lSubjectMaximum,@rFA1DecimalFormat=@lFA1DecimalFormat,
												@rFA2DecimalFormat=@lFA2DecimalFormat,@rFA3DecimalFormat=@lFA3DecimalFormat,@rFA4DecimalFormat=@lFA4DecimalFormat,
												@rSA1DecimalFormat=@lSA1DecimalFormat,@rSA2DecimalFormat=@lSA2DecimalFormat,@rTerm1DecimalFormat=@lTerm1DecimalFormat,@rTerm2DecimalFormat=@lTerm2DecimalFormat,@rAnnualDecimalFormat=@lAnnualDecimalFormat ,
												@rFA1GradePointMax = @lFA1GradePointMax,@rFA2GradePointMax=@lFA2GradePointMax,@rFA3GradePointMax=@lFA3GradePointMax,@rFA4GradePointMax=@lFA4GradePointMax,
												@rSA1GradePointMax=@lSA1GradePointMax,@rSA2GradePointMax=@lSA2GradePointMax 
												,@rIsIncludeInTotal = @lIsIncludeInTotal,@rIncludeInTotalTerm1=@lIncludeInTotalTerm1,@rIncludeInTotalTerm2=@lIncludeInTotalTerm2,
												@rIncludeInTotalAnnual=@lIncludeInTotalAnnual,@rIsGradeUpdate=@lGradeUpdate
					SET @lCount = @lCount -1
						
					
				END
				
				 TRUNCATE TABLE #TempCCEMarkEntry
				--DELETE FROM #TempCCEMarkEntry
				--DBCC CHECKIDENT (#TempCCEMarkEntry, RESEED, 1);
		SET @lCount_MarkEntryStudent = @lCount_MarkEntryStudent -1
	    
	END

	 
	EXEC sAssessment.pCCEResultDetailSubjectGradeUpdate @rExamOrder,@rCCEExamId,@rExamId,@rBatchId,@rClassId,@rDivisionId  
		 
	IF (@rExamOrder = 3)
	BEGIN
	Update   CCER  Set   WorkingDaysTerm1 = TotalDays,AttendanceTerm1 = PresentDays from	
	sAssessment.tCCEResult CCER INNER JOIN sAssessment.tStudentRemark SR ON SR.AcademicID = CCER.Academicid 
	WHere SR.ExamID =@rExam AND @rCCEExamId=7
	END
	
	IF (@rExamOrder = 6)
	BEGIN
	Update   CCER  Set   WorkingDaysTerm2= TotalDays,AttendanceTerm2 = PresentDays from 
	sAssessment.tCCEResult CCER INNER JOIN sAssessment.tStudentRemark SR ON SR.AcademicID = CCER.Academicid 
	WHere SR.ExamID =@rExam AND @rCCEExamId=8
	
	Exec sAssessment.pCCEResultOverallGradeUpdate @rExamOrder,@rCCEExamId,@rBatchId,@rClassId,@rDivisionId
	
	END
	 
	 IF @rExamOrder =6 AND @lGradeUpdate=1
	 BEGIN
		 
		 EXEC sAssessment.pCCESubjectGradeUpgrade  @rBatchId=@rBatchId,@rClassId=@rClassId,@rDivisionId=@rDivisionId,@rOrgId=@rOrgId 
	  
	END		
	--	END
		DROP TABLE #TempMarkEntryStudent
	DROP TABLE #TempCCEMarkEntry
	SELECT 1 AS Result
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCCEResultGenerateDelete]
	 
	 @rClassId int,
	 @rBatchId int,
	 @rDivisionId int,
	 @rExamId  int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
		BEGIN 		
			DELETE RD FROM sAssessment.tCCEResultDetail RD
					INNER JOIN sStudent.tAcademic A ON A.Id = RD.AcademicId 
			WHERE A.ClassId = @rClassId AND A.BatchId = @rBatchId AND A.DivisionId=@rDivisionId 
			
			DELETE R FROM sAssessment.tCCEResult R 
					INNER JOIN sStudent.tAcademic  A ON A.Id=R.AcademicId 
			WHERE A.ClassId = @rClassId AND A.BatchId = @rBatchId AND A.DivisionId=@rDivisionId
			DELETE FROM sAssessment.tCCEExamStatus WHERE CCEExamId = @rExamId AND DivisionId = @rDivisionId
			SELECT 1 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT 0 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAssessment].[pCCEResultOverallGradeUpdate]
	  
	
	  @rExamOrder INT
	 ,@rCCEExamId INT
	 ,@rBatchId INT
	 ,@rClassId INT,	
	  @rDivisionId int
		
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
--BEGIN TRY
-- BEGIN TRANSACTION	

	
		DECLARE @MinimumScore decimal(5,2)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @lCount int
		DECLARE @lDataSetID INT
		DECLARE @lMaxiMark Decimal(5,2)
		--SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId 
		
		
		 --  Update  D  Set D.FATerm1 = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId
			
		 --  Update  D  Set D.Term1Grade = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	
			
			--Update  D  Set D.FATerm2 = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	

			
			--Update  D  Set D.SAGRADE = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 

			--Update  D  Set D.FAGRADE = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId			 

	        
	  --      Update  D  Set D.Term2Grade = NULL FROM
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	

			
			--Update  D  Set D.Grade = NULL FROM  
			--sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			----INNER JOIN #tempAcademic TA ON D.AcademicId = TA.AcademicId AND D.ClassSubjectId = TA.ClassSubjectid
			--WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId	
	
			
		
	
		 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId AND BatchId = @rBatchId
 
		 -- CREATE TABLE #tempAcademic
			--(
			--	AcademicId bigint,
			--	classSubjectId decimal(5,2) 				 
			--) 
		 
		CREATE TABLE #tempGradeSetDetail
		(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(10),
		GradePoint decimal(6,2) 					 
		) 
			INSERT INTO #tempGradeSetDetail
		SELECT MinimumScore,GradeCode,GradePoint		
		FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
		order by MinimumScore DESC 
SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
while ( @lCount > 0 )
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@GradeTitle=GradeTitle,
		@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		 
			 
			Update  D  Set D.AnnualGrade = @GradeTitle FROM
			sAssessment.tCCEResult D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId
			AND (D.CGPA * 10)>= @MinimumScore
			
			--AND SA2Max > 0
		 Set @lCount=@lCount-1
    END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCCERptCoScholasticEvaluationGet]
	 
	 
	 @rClassId int,
	 @rBatchId int,
	 @rOrgId int,
	 @rDivisionId int,
	@rCCEExamId int,
	 @rStatus int =0 ,
	@rCode nvarchar(20)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			
			cceCSS.AcademicId,
			convert(nvarchar,cceCSS.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			cceCSS.Grade,
			cceCSS.DescriptiveIndicator AS DiscriptiveIndicators,
			cceCSM.Title AS LifeSkills,
			cceCSGM.Code AS GrpLifeSkillsCode,
			cceCSGM.Title AS GrpLifeSkills,			
			cceCSGTM.Title AS CoScholasticGroupType,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division
	
			
      
	FROM 
			sAssessment.tCCECSExamScore cceCSS
			--INNER JOIN sAssessment.tCCECSIndicatorMaster cceCSIM ON cceCSIM.Id=cceCSS.CCECSIndicatorId
			LEFT JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			LEFT JOIN sAssessment.tCCECSGroupTypeMaster cceCSGTM ON cceCSGM.CCECSGroupTypeId=cceCSGTM.Id
			INNER JOIN sStudent.tAcademic A ON cceCSS.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.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 sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId
			
			
	WHERE 
			     (A.BatchId=@rBatchId)
			     AND (A.OrgId=@rOrgId)
		    AND (A.ClassId=@rClassId  OR @rClassId=0)
		    AND (A.DivisionId=@rDivisionId  OR @rDivisionId=0)
		   AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
		
	
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pCCERptFAIndicatiorListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 --@rBatchId int,
	 @rOrgId int,
	 @rFAGrpId int,
	 @rFAMasterId int
	
	 --@rClassSubjectId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			FAIM.Title AS IndicatorName,
			FAIM.Id AS IndicatorId,
			FAIM.Remark AS IndicatiorRemark,
			FA.Title AS FAMasterName,
			FA.Id As FAMasterId,
			FA.Remark AS FAMasterRemark,
			FAGM.Title AS FAGrpName,
			FAGM.Number AS FAGrpNumber,
			FAGM.Code AS FAGrpCode
			
			
			
			
      
	FROM 
			sAssessment.tCCEFAIndicatorMaster FAIM
			INNER JOIN sAssessment.tCCEFAMaster FA ON FA.Id=FAIM.CCEFAId
			INNER JOIN sAssessment.tCCEFAGroupMaster FAGM ON FAGM.Id=FA.CCEFAGroupId
			
			
			
	WHERE 
			
		    (FAIM.OrgId=@rOrgId) AND
		     (FAIM.IsObsolete=0)
		    AND ((FA.Id=@rFAMasterId) OR (@rFAMasterId=0))
		    AND ((FAGM.Id=@rFAGrpId) OR (@rFAGrpId=0))
		   
		
	
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 


CREATE OR ALTER PROCEDURE [sAssessment].[pCCERptFirstTermResultGet] 
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	-- @rOrgId int,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rClassSubjectId int=0,
	 @rCCEExamId int=0,
	 @rAcademicId bigint=0,
	 @rStatus int =0 ,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,	
	 @rToRollNo int=0 

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 


--DECLARE @GradeString nvarchar(1000),
--@GradeSetId int 
--SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rCCEExamId
--SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

--DECLARE @rExamId int,@rCSGradeSetId int
--	SELECT @rExamId = EM.Id FROM	sAssessment.tCCEExamSetting CS INNER JOIN sAssessment.tExamMaster EM
--	ON CS.ExamSubGroupId = 	EM.ExamSubGroupId AND CS.ClassId = EM.ClassId AND CS.BatchId = EM.BatchId
--	  WHERE Cs.CCEExamId = @rCCEExamId AND CS.BatchId = @rBatchId AND Cs.ClassId = @rClassId
		
--		SELECT Distinct @rCSGradeSetId = CG.GradeSetId  from  sAssessment.tCCECSExamScore ES INNER JOIN sAssessment.tCCECSMaster CM ON ES.cceCsId = CM.Id
--		INNER JOIN sAssessment.tCCECSGroupMaster CG ON CM.CCECAGroupId = CG.Id WHERE ES.ExamId = @rExamId
Declare @GradeString nvarchar(500),@GradeSetId int,@CSGradeString nvarchar(max),@CSGradeSetId int	  
SELECT @GradeSetId = GradesetId  FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId

Select @CSGradeSetId =CSGradeSetId from sAssessment.tCCEExamSetting Where CCEExamId= @rCCEExamID
	 
	
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
Select @CSGradeString = [sAssessment].[fCSGradeStringGet](@CSGradeSetId)

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

BEGIN 
	SELECT 
		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2
			,
			
			SM.Code,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			Convert(Nvarchar,@rBatchId) As BatchIdText,
			CONVERT(NVARCHAR,@rCCEExamId) AS CCEExamIdText,
			
			Convert(nvarchar(20),EM.CoScholasticScopeId)AS CoScholasticScopeIdText,--added 
			CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			ED.IsIncludeInTotal,
	
	 
		
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			--SO.DateOfBirth,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(CCERD.GradeFA1,'') AS GradeFA1,
			ISNULL(CCERD.GradeFA2,'') AS GradeFA2,
			ISNULL(CCERD.GradeFA3,'')AS GradeFA3,
			ISNULL(CCERD.GradeFA4,'') AS GradeFA4,
			ISNULL(CCERD.GradeSA1,'') AS GradeSA1,
			ISNULL(CCERD.GradeSA2,'') AS GradeSA2,
			ISNULL(CCERD.FAGrade,'') AS FAGrade,
			ISNULL(CCERD.SAGrade,'') AS SAGrade,
			ISNULL(CCERD.GradePoint,0) AS OverallGrade,
			ISNULL(CCERD.Grade,'') AS Grade,
			ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(CCER.Height,0) AS Height,
			ISNULL(CCER.Weight,0) AS Weight,
			 
			SubM.Title As ClassSubject,
			SubM.OrderIndex AS SubjectOrderIndex,
			Subm.Code AS SubjectCode,
			CCERD.classSubjectId,
			Cs.isOptional,
			ISNULL(BGM.Title,'') AS BloodGroup,
			ISNULL(CCERD.Term1GradePoint,0) AS Term1GradePoint,
			ISNULL(CCERD.Term1Grade,'') AS Term1Grade,
			ISNULL(CCERD.Term2GradePoint,0) AS Term2GradePoint,
			ISNULL(CCERD.Term2Grade,'') AS Term2Grade,
			--ISNULL(SI.StudentPhoto,CONVERT(varbinary(max),SI.StudentPhoto,1)) AS StudentPhoto
			--SI.StudentPhoto AS StudentPhoto 
			--CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayResultStatus,
			CCERD.FA1,
			CCERD.FA2,
			CCERD.FA3,
			CCERD.FA4,
			CCERD.SA1,
			CCERD.SA2,
			CCERD.TERM1,
			CCERD.TERM2,
			CCERD.TOTAL,
			EM.IsOnPrePrinted,
			EM.IsDisplayBirthDate,
			EM.IsDisplayPhoto,
			EM.IsDisplaySchoolName,			
			EM.IsLockForEdit,
			EM.IsIncludeCoScholastic,
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,	
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			EM.ExamSubGroupId,
 
			ESM.Code AS ExamSubGroupTitle,	
			EM.DisplayTitle,
			SI.StudentPhoto,
			ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
			ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			ISNULL(EM.TermScopeId,0) AS TermScopeId,	
			TSM.Title AS TermScopeTitle,
			ISNULL(EM.ReportId,0) as ReportId,
			@GradeString AS GradeString,
			A.BatchId,
			BM.Title,
			CS.OrderIndex AS ClassSubjectOrderIndex,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			SR.StudentHeight,
			SR.StudentWeight,
			EM.IsDisplayGradeString,
			CCERD.IspresentFA1,
			CCERD.IsPresentFA2,
			CCERD.IspresentSA1,
			CCERD.IspresentFA3,
			CCERD.IsPresentFA4,
			CCERD.IspresentSA2,
			SR.ResultRemark1,
			SR.ResultRemark2,
			CCERD.GradePoint,
			CCERD. FATerm1,
			CCERD.FATerm2,
			CS.IsOptional,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			EI.EmployeeSign,
			AD.TotalDaysTerm1,
			AD.PresentDaysTerm1,
			AD.TotalDaysTerm2,
			AD.PresentDaysTerm2,
		 
			CCER.CGPA,
			ISNULL(SR.AreaOfInterest,'')As AreaOfInterest,
			ISNULL(SR.Responsibility,'') AS Responsibility,
			ISNULL(SR.MyGoal,'')AS MyGoal,
			ISNULL(SR.MyInterestHobby,'')AS MyInterestHobby,
			ISNULL(SR.MyStrength,'')AS MyStrength,
			ISNULL(SR.Achievements,'')AS Achievements,
			ISNULL(SR.DentalHygiene,'')AS DentalHygiene, 
			ISNULL(SR.VisionLeft,'')AS VisionLeft,
			ISNULL(SR.VisionRight,'')AS VisionRight,
			ISNULL(CCER.Term1Grade,'') Term1OverAllGrade,
			ISNULL( CCER.Term2Grade,'') Term2OverAllGrade,
			ISNULL(CCER.AnnualGrade,'') AnnualOverAllGrade,
			CONVERT (nvarchar(20),EM.CoScholasticGradeSetId) AS CoScholasticGradeSetIdText,
			EM.IsMarksInDecimal,
		
			CCERD.FA,
			CCERD.SA,
		
			ISNULL(CCER.Term1TotalMarks,0) AS Term1TotalMarks,
			ISNULL(CCER.Term1TotalObtain,0) AS Term1TotalObtain,
			ISNULL(CCER.Term2TotalMarks,0) AS Term2TotalMarks,
			ISNULL(CCER.Term2TotalObtain,0) AS Term2TotalObtain,
			ISNULL(CCER.AnnualTotalMarks,0) AS AnnualTotalMarks,
			ISNULL(CCER.AnnualTotalObtain,0) AS AnnualTotalObtain,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			EM.DecimalFormat,
			CCER.Term1CGPA,
			CCER.Term2CGPA,
			CCERD.GradePointFA1,
			CCERD.GradePointFA2,
			CCERD.GradePointSA1,
			CCERD.GradePointFA3,
			CCERD.GradePointFA4,
			CCERD.GradePointSA2,
			CCERD.FAGradePoint,
			CCERD.SAGradePoint,
			SubM.Code As SubjectCode,
			@CSGradeString AS CoScholasticGradeString ,
			@CSGradeSetId AS ABCD,
			ED.IsShowSubjectMark,
			ED.IsShowSubjectGrade,
			CCERD.FA1Max,
			CCERD.FA2Max,
			CCERD.SA1Max,
			CCERD.FA3Max,
			CCERD.FA4Max,
		
			CCERD.SA2Max,
		
			CCERD.Term1TotalGradePoint,
			ccerd.Term2TotalGradePoint,
			(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=1) AS FA1DecimalFormat,
			(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=2) AS FA2DecimalFOrmat,
			(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=4) AS FA3DecimalFormat,
			(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=5) AS FA4DecimalFormat,
			(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=3) AS SA1DecimalFormat,
			(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=6) AS SA2DecimalFormat,
			(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=7) AS Term1DecimalFormat,
			(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=8) AS Term2DecimalFormat,
			(Select DecimalFormat from sAssessment.tCCEExamSetting where ClassId =@rClassId AND BatchId=@rBatchId AND  CCEExamID=9) AS AnnualDecimalFormat ,
			ISNULL(CCERD.IsUpgradedGrade,0) AS IsUpgradedGrade,
			ISNULL(ED.IsIncludeInTotal,0) As IsIncludeInTotal,
			(Select ED.IsDisplayInMarksheet  
			From  sAssessment.tCCEEXAMMASTER CM 
			--INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = CE.ExamSubGroupId
			--INNER JOIN sAssessment.tExamMaster eEM ON eEM.ExamSubGroupId = CE.ExamSubGroupId
			 --INNER JOIN sAssessment.tExamDetail ED ON ED.Examid = eEM.Id AND ClassSubjectId =CCERD.ClassSubjectId
			Where CE.BatchId = @rBatchId  AND  CM.Id=@rCCEExamID 
			--ANd EM.ClassId= @rClassId  
			) As IsDisplayInMarksheet,
			CE.IsUpgradGrade AS CSUpgradeGrade,
			SR.ExamSeatNo,
			CONVERT(bit,@lDecimalConfig) AS IsDecimal
		
		 
		
		 
	
			
			--		--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
	
			sAssessment.tCCEResultDetail CCERD
			
			INNER JOIN sAssessment.tCCEResult CCER  ON CCERD.AcademicId=CCER.AcademicId
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sSetup.tClassSubject CS ON CS.Id=CCERD.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id=CS.SubjectId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.ClassSubjectId = CS.Id
		
			 
			LEFT JOIN sAssessment.tStudentRemark SR ON CCERD.AcademicId = SR.AcademicId AND ED.ExamId = SR.ExamId 
			
			
			
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId

			Inner Join sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			
			  
	WHERE 
			
    A.BatchId = @rBatchId 
		
	AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((A.ClassId=@rClassId) OR (@rClassId=0) )
	AND ((CCERD.ClassSubjectId=@rClassSubjectId) OR (@rClassSubjectId=0))
	AND ((CE.CCEExamId = @rCCEExamId) OR (@rCCEExamId=0))
	AND ( CCER.AcademicId=@rAcademicId OR @rAcademicId=0)
	AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND((A.RollNo >= @rFromRollNo) OR (@rFromRollNo = 0))
	AND((A.RollNo <= @rToRollNo) OR (@rToRollNo = 0))
	ORDER BY A.RollNo,CS.OrderIndex	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAssessment].[pCCERptMyGoalsGet]
	 @rOrgId int,
	 @rBatchId int,
	 @rCCEExamId int,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rAcademicId bigint=0,
	  @rStatus int =0 ,
	@rCode nvarchar(20)=''
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			
			SR.MyGoal,
			SR.MyStrength,
			Sr.MyInterestHobby,
			SR.Achievements,
			SR.AcademicId,
			Convert(nvarchar,SR.AcademicId) AS AcademicIdText,
			Convert(nvarchar,EM.Id)AS ExamIdText,
			Convert(nvarchar,@rCCEExamId) AS CCEExamIdText
		
	FROM 
			 
			
			 sAssessment.tCCEResult CCER 
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			LEFT JOIN sAssessment.tStudentRemark SR ON A. Id = SR.AcademicId AND EM. Id = SR.ExamId
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
	where
	 A.BatchId = @rBatchId 
		
		AND(CE.CCEExamId = @rCCEExamId OR @rCCEExamId=0)
	AND ( CCER.AcademicId=@rAcademicId OR @rAcademicId=0)	
	AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pCCESubjectActivityExamScoreAdd]
	 	
	@rDetails [nvarchar](max),
	@rCCEExamId int,
	@rSubjectActivityId int,
	@rClassId int,
	@rBatchId int
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rDetails=REPLACE(@rDetails,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDetails

BEGIN 
	declare @lDataSetID int,@lCount int,@MinimumScore decimal(5,2),@GradeTitle nvarchar(10),@lCountTemp int,
			@lAcademicId Bigint,@lSubjectActivityId int,@lExamId int,@lMark decimal(10,2)
	 SELECT @lDataSetID=GradeSetId FROM sAssessment.tCCESubjectActivityMaster WHERE  Id=	@rSubjectActivityId	
	 
		if exists(select 1 from sAssessment.tCCESubjectActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectActivityId int, 
							ExamId int
					 )
					 A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=@rCCEExamId
			AND AI.SubjectActivityId =@rSubjectActivityId )
	 BEGIN	
		UPDATE AI SET AI.Marks = Mark FROM sAssessment.tCCESubjectActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectActivityId int,--CCECSId int,
							ExamId int,
							Mark decimal(10,2)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=@rCCEExamId
			AND AI.SubjectActivityId = @rSubjectActivityId
			 --AND A.CCECSId = AI.CCECSId 
			
			
			
			 
		END
	else
	BEGIN	
		INSERT INTO sAssessment.tCCESubjectActivityExamScore
			(ExamId,AcademicId,SubjectActivityId,Marks)
			
			SELECT	@rCCEExamId,AcademicId,@rSubjectActivityId,Mark
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					AcademicId Bigint,					
					Mark decimal(10,2)--CCECSId int
				  ) A 	
			 --A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCESubjectActivityExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND SubjectActivityId=AM.Id)
	     SELECT 1 AS Result
	     
	END 
 
 CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(20),
		GradePoint decimal(6,2) 					 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,GradeCode,GradePoint		
	FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	order by MinimumScore DESC
	
	Select @lCount= count(id) from #tempGradeSetDetail
	while (@lCount>0)
	BEGIN
	 Select @MinimumScore =MinimumScore,@GradeTitle=GradeTitle from #tempGradeSetDetail Where Id=@lCount
	 UPDATE AI SET AI.Grade = @GradeTitle FROM sAssessment.tCCESubjectActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectActivityId int,--CCECSId int,
							ExamId int,
							Mark decimal(10,2)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=@rCCEExamId
			AND AI.SubjectActivityId = @rSubjectActivityId
			AND A.Mark >=@MinimumScore 
			
		 Set @lCount=@lCount-1	  			
		END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pCCESubjectGradeUpdate]
	  
	
	   
	  @rCCEExamId INT
	  
	 ,@rBatchId INT
	 ,@rClassId INT,
	  @rDivisionId int,
	  @rAcademicid bigint,
	  @rOrgId smallint ,
	  @rConvertedMark decimal(6,2)
	  
	  	
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
--BEGIN TRY
-- BEGIN TRANSACTION	
	--Declare @lConvertedMark decimal(6,2)
	Declare @lCount int,@lGradeSetId int,@lGradeCode nvarchar(10),@lGradePoint decimal(6,2)
	 Select top 1 @lGradeSetId=GradeSetId from sAssessment.tGradeSetDetail Where GradeSetId = (SELECT  GradeSetId FROM sAssessment.tCCEExamSetting WHERE CCEExamId = @rCCEExamId AND ClassId = @rClassId AND BatchId = @rBatchId)
	 
	 Create table #TempGrade 
			(
				Id int Identity(1,1),
				Grade nvarchar(10),
				ClassSubjectID int,
				AcademicId bigint
			)
			
	if(@rConvertedMark>=53 AND @rConvertedMark<=65)
	BEGIN  
	 
			Insert into #TempGrade
			(
				Grade,
				ClassSubjectID,
				AcademicId
			)
			 SELECT top 2 Grade,CS.Id AS ClassSubjectID,D.AcademicId From 
			 sAssessment.tCCEResultDetail D
			 INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			 INNER JOIN sSetup.tClassSubject CS oN CS.Id= D.ClassSubjectID
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND  A.ClassId = @rClassId AND D.AcademicId=@rAcademicid
			AND CS.Id in (select ID from sSetup.tClassSubject where classid=@rClassId  AND Orgid=@rOrgId ) AND CS.Isoptional=0 
			AND D.Grade NOT IN ('A1','E1','E2') 
			--AND ISNULL(D.IncludeInTotalAnnual,0)!=0
			 order by D.Grade  desc  
			Set @lCount =0
			Select @lCount = Count(Id) from #TempGrade	
			 
		While @lCOunt>0
		BEGIN
						
					 select top 1   @lGradeCode= GradeCode, @lGradePoint=GradePoint from sAssessment.tGradeSetDetail where MinimumScore > 
					(select MinimumScore from sAssessment.tGradeSetDetail WHERE GradeCode in (Select Grade From #TempGrade Where  Id = @lCOunt) 
					 AND GradeSetId = @lGradeSetId) AND GradeSetId = @lGradeSetId
					Order by MinimumScore	
					 
					 
					 
						 Update  D  Set D.Grade =  @lGradeCode,D.GradePoint=@lGradePoint,IsUpgradedgrade=1 FROM  
						sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
						INNER JOIN sSetup.tClassSubject CS oN CS.Id= D.ClassSubjectID
						WHERE	A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId AND A.Id=@rAcademicid		
						AND CS.Id in (select ClassSubjectID from #TempGrade	where id=@lcount)    
						
						update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(ISNULL(GradePoint,0)) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail WHERE  ISNULL(IncludeInTotalAnnual,0)  > 0  Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		
					  
					  
					 
			Set @lCOunt =@lCOunt-1		
	    END
	END	
	else  if (@rConvertedMark>=40 AND @rConvertedMark<=52)
	BEGIN
	 
			Insert into #TempGrade
			(
				Grade,
				ClassSubjectID
			)
			
			 SELECT top 1 Grade,CS.Id AS ClassSubjectID From 
			 sAssessment.tCCEResultDetail D
			 INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
			 INNER JOIN sSetup.tClassSubject CS oN CS.Id= D.ClassSubjectID
			WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND  A.ClassId = @rClassId AND D.AcademicId=@rAcademicid 
			AND CS.Id in (select ID from sSetup.tClassSubject where classid=@rClassId  AND Orgid=@rOrgId ) AND CS.Isoptional=0 AND 
			D.Grade NOT IN ('A1' ,'E1','E2') 
			--AND ISNULL(D.IncludeInTotalAnnual,0)!=0 
			order by D.Grade  desc  
			Set @lCount=0
			Select @lCount = Count(Id) from #TempGrade
			While @lCOunt>0
			BEGIN
					
					 select top 1 @lGradeCode = GradeCode,@lGradePoint=GradePoint from sAssessment.tGradeSetDetail where MinimumScore > 
					(select MinimumScore from sAssessment.tGradeSetDetail WHERE GradeCode in (Select Grade From #TempGrade Where  Id = @lCOunt)  AND GradeSetId = @lGradeSetId) AND GradeSetId = @lGradeSetId
					Order by MinimumScore
			 
				 
					Update  D  Set D.Grade =  @lGradeCode , D.GradePoint=@lGradePoint,D.IsupgradedGrade=1 FROM  
					sAssessment.tCCEResultDetail D INNER JOIN sStudent.tAcademic A ON D.AcademicId = A.Id
					INNER JOIN sSetup.tClassSubject CS oN CS.Id= D.ClassSubjectID
					WHERE	A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND A.ClassId = @rClassId AND A.Id=@rAcademicid		
					AND CS.Id in (select ClassSubjectID from #TempGrade	)   
					
					
					update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(ISNULL(GradePoint,0)) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail WHERE  ISNULL(IncludeInTotalAnnual,0)  > 0  Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		 
				 
			END
	END
		
 
	  
		 
			 
			 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pCCESubjectGradeUpgrade]
	   
	  @rBatchId INT
	 ,@rClassId INT,
	  @rDivisionId int,
	  @rOrgId int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 
	Create Table #tempMark 
	(
		Id int identity(1,1),
		Convertedmark decimal(6,2),
		AcademicId bigint
	)
	INsert Into #tempMark
	(
		Convertedmark,
		AcademicId
	)
	 SELECT   sum(Isnull(CC.Convertedmark,0)),SA.Id 
		FROM  sAssessment.tCCECSMaster CM	
		  INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
		  INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id				
		   INNER JOIN sStudent.tAcademic SA ON   SA.ClassId = CL.ClassId 
		  INNER JOIN   sAssessment.tCCECSExamScore CC  ON CC.CCECSID=CM.ID   AND CC.AcademicId = SA. Id  
		   
		  WHERE 
		  --((SA.AcademicId = @lAcademicId) OR (@lAcademicId=0))						  
		  SA.DivisionId=@rDivisionId and SA.Batchid = @rBatchId
		  Group by SA.Id 
		  
        
        
		Update CR SET  CR.ConvertedMark=temp.Convertedmark from
		sAssessment.tCCEResult CR
		INNER JOIN #tempMark temp on temp.AcademicId = CR.AcademicId
			
		 
		 
		CREATE Table #tempdetail
		(
			AcademicId bigint,
			Grade nvarchar(10),
			HigherGrade nvarchar(10),
			GradePoint decimal(6,2),
			HigherGradePoint decimal(6,2),
			ConvertedMark decimal(6,2),
			ClassSubjectId int
			 
		) ;
	 
		 
	  WITH cte  AS 
	 (
		 
		SELECT  D.AcademicId,D.ClassSubjectId,D.Grade,sAssessment.fGetHigherGrade(D.Grade) AS HigherGrade,D.GradePoint,sAssessment.fGetHigherGradepoint(D.GradePoint) AS HigherGradePoint,
				CR.ConvertedMark,
		row_number() OVER(PARTITION BY D.AcademicId ORDER BY D.Grade desc) AS [rn]
		FROM  sAssessment.tCCEResultDetail D 
	 
		inner join  sStudent.tAcademic A ON A.id=D.academiciD
		INNER JOIN sAssessment.tCCEResult CR on CR.Academicid= A.id
		WHERE D.Grade NOT IN ('A1','E1','E2') And A.batchid=@rBatchId ANd A.divisionid=@rDivisionId AND CR.Convertedmark>=53 AND CR.ConvertedMark<=65 AND ISNULL(D.IncludeInTotalAnnual,0)  > 0
	 )
	 INSERT INTo #tempdetail
		(
			AcademicId, 
			Grade,
			HigherGrade,
			GradePoint,
			HigherGradePoint ,
			ConvertedMark,
			ClassSubjectId 
		) 
	  
	select AcademicId,Grade,HigherGrade,GradePoint,HigherGradePoint,ConvertedMark,ClassSubjectId from cte WHERE [rn] <= 2  
	 
		Update D Set D.Grade=temp.HigherGrade,D.GradePoint=temp.HigherGradePoint,IsUpgradedgrade=1
		from sAssessment.tCCEResultDetail  D INNER JOIN  #tempdetail temp on temp.Academicid= D.Academicid 
		 And  temp.ClassSubjectId = D.ClassSubjectId
		
		update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(ISNULL(GradePoint,0)) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail WHERE  ISNULL(IncludeInTotalAnnual,0)  > 0  Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId;
	 
	WITH T  AS 
	 (
		SELECT  D.AcademicId,D.ClassSubjectId,D.Grade,sAssessment.fGetHigherGrade(D.Grade) AS HigherGrade,D.GradePoint,sAssessment.fGetHigherGradepoint(D.GradePoint) AS HigherGradePoint,
				CR.ConvertedMark,D.IncludeInTotalAnnual,
		row_number() OVER(PARTITION BY D.AcademicId ORDER BY D.Grade desc) AS [rn]
		FROM  sAssessment.tCCEResultDetail D 
	 
		inner join  sStudent.tAcademic A ON A.id=D.academiciD
		INNER JOIN sAssessment.tCCEResult CR on CR.Academicid= A.id
		WHERE D.Grade NOT IN ('A1','E1','E2') And A.batchid=@rBatchId ANd A.divisionid=@rDivisionId AND CR.Convertedmark>=40 AND CR.ConvertedMark<=52  AND ISNULL(D.IncludeInTotalAnnual,0)  > 0
	 )
	  INSERT INTo #tempdetail
		(
			AcademicId, 
			Grade,
			HigherGrade,
			GradePoint,
			HigherGradePoint,
			ConvertedMark,
			ClassSubjectId
		) 
	select AcademicId,Grade,HigherGrade,GradePoint,HigherGradePoint,ConvertedMark,ClassSubjectId from T WHERE [rn] <= 1	
		 
		Update D Set D.Grade=temp.HigherGrade,D.GradePoint=temp.HigherGradePoint,IsUpgradedgrade=1
		from sAssessment.tCCEResultDetail  D INNER JOIN  #tempdetail temp on temp.Academicid= D.Academicid AND temp.ClassSubjectId = D.ClassSubjectId
		
		update CR set cgpa =  (CRD.GradePoint) from  sAssessment.tCCEResult CR 
		Inner Join (select Avg(ISNULL(GradePoint,0)) AS GradePoint,AcademicId From sAssessment.tCCEResultDetail WHERE  ISNULL(IncludeInTotalAnnual,0)  > 0  Group By ACademicId ) CRD 
		ON CR.AcademicId = CRD.AcademicId
		INNER JOIN sStudent.tAcademic A ON CR.AcademicId = A.Id
		AND A.ClassId=@rClassId And A.BatchId=@rBatchId AND A.DivisionId=@rDivisionId
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pConfigurationAdd]
	 
	@rOrgId int,
	@rAnalysisGradeSetId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

 IF NOT EXISTS(SELECT AnalysisGradeSetId FROM sAssessment.tConfiguration WHERE OrgId=@rOrgId)	
	  BEGIN
		INSERT INTO sAssessment.tConfiguration
		   (
			[OrgId],
			[AnalysisGradeSetId]
		   )
		VALUES
		   (
			@rOrgId,
			@rAnalysisGradeSetId
		   )
		Select 101 AS Result	   
	  END	 
	 
 ELSE
	  
	 BEGIN
	   UPDATE  sAssessment.tConfiguration
		  SET
			 --[OrgId]=@rOrgId,
			 [AnalysisGradeSetId]=@rAnalysisGradeSetId
		  WHERE  OrgId=@rOrgId 
	   SELECT 102 AS Result
	 END 	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pConsolidatedBrightStudentAnalysisListGet]
	 
	 @rExamSubGroupId nvarchar(max)='',
	 @rGroupId int=0,
	 @rTop int=0,
	 @rOrgGroupId int = 0,
	 @rCommonOrgGroupBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

IF @rExamSubGroupId='' SET @rExamSubGroupId = NULL

SELECT r1.*
FROM
(	SELECT 	
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEN @rGroupId =4 THEN OM.Id END
				ORDER BY R.Percentage DESC) rn,
			A.Id AS SourceId,
			OM.Id AS OrgId,
			OM.Title AS OrgCode,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			CM.DisplayTitle + '-' + DM.DisplayTitle AS Class,
			R.Percentage,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id  END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization' END AS GroupTitle
				
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id= OM.OrgGroupId
	        INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
	WHERE 
			BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
			AND ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='')
			
	)r1
	WHERE ((r1.rn <= @rTop) Or (@rTop = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pConvertGradeAdd]
	 @rExamId int,
	 
	 @rSubjectSubActivityId int,
	 @rOrgId smallint,
	 @rDataSetID int,
	 @rDivisionId int,
	 @rBatchId int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN  
DECLARE @MinimumScore decimal(5,2)
DECLARE @Grade nvarchar(20)
DECLARE @GradePoint Decimal(6,2)
DECLARE @lCount int
DECLARE @GradeTitle nvarchar(50)

begin
	CREATE TABLE #tempGradeSetDetail
 		(
 			Id INT IDENTITY (1, 1),
 			MinimumScore decimal(5,2),
 			Grade nvarchar(20),
 			GradePoint Decimal(6,2),
 			GradeTitle nvarchar(50)
 		) 
 		INSERT INTO #tempGradeSetDetail
 		SELECT MinimumScore,GradeCode,GradePoint,GradeTitle		
		FROM sAssessment.tGradeSetDetail where GradesetId=@rDataSetID
		order by Id Asc

 
 --SELECT * FROM #tempGradeSetDetail 	
SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
while (@lCount > 0)
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@Grade= Grade,
		@GradePoint = GradePoint,
		@GradeTitle = GradeTitle
		FROM #tempGradeSetDetail  WHERE Id = @lCount
		
	Update sAssessment.tCCESubjectSubActivityExamScore Set Grade=@Grade,GradeIndicator=@GradeTitle  WHERE Marks >= @MinimumScore
		 
		AND ExamId= @rExamId
		 
		AND SubjectSubActivityId = @rSubjectSubActivityId  
	SET @lCount = @lCount - 1
 END	
END
SELECT 1 AS Result
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pConvertMarkentryDifferentSubjectGet]

	 
	 @rClassId int,
	 @rBatchId int, 
	 @rDestinatinExamDetailId int

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
 
					 
	SELECT 
		 ESGM.Title AS Exam,		 
		 ED.Id AS ExamDetailId,
		 SM.Title AS SubjectName,
		 EM.Id AS ExamId
	FROM  
			  sAssessment.tExamMaster EM  
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
			INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
			
  WHERE		(EM.ClassId=@rClassId OR @rClassId =0) 			
			AND EM.BatchId=@rBatchId						 
			--AND ED.ClassSubjectId=@lClassSubjectId
			 AND ED.ID <> @rDestinatinExamDetailId
			
 ORDER BY  ESGM.Title ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pConvertMarkentrySubjectGet]

	 
	 @rClassId int,
	 @rBatchId int, 
	 @rDestinatinExamDetailId int

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	

DECLARE @lClassSubjectId int
select @lClassSubjectId =  ClassSubjectId from sAssessment.tExamDetail	 where Id = @rDestinatinExamDetailId
					 
	SELECT 
		    ESGM.Title AS Exam,		 
		    ED.Id AS ExamDetailId ,	
		    SM.Title AS SubjectName,
			EM.Id AS ExamId
	FROM  
			sAssessment.tExamMaster EM  
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
			INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		 
  WHERE		(EM.ClassId=@rClassId OR @rClassId =0) 			
			AND EM.BatchId=@rBatchId						 
			AND ED.ClassSubjectId=@lClassSubjectId
			AND ED.ID <> @rDestinatinExamDetailId
			
 ORDER BY  ESGM.Title ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCopyExamAdd]
	 
	      @rFromBatchId int,
	      @rClassId int,
	      @rOrgId int,
	      @rToBatchId int,
		  @rExamSubGroupId Int = 0	--	Mantis Id : 0036712
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 BEGIN TRANSACTION	
	 
	 
	DECLARE @lNextNumber BIGINT,@lExamdetailNextNumber BIGINT,@lExamCombineNextNumber bigint,@lCombineNextNumber bigint
	Declare @lCount int,@lExamDetailCount int,@lExamCombineCount int,@lCombineCount int ,
	@lClass nvarchar(50), @lExamName nvarchar(50)
	 
	
		
	if exists (Select 1  from sAssessment.tExamMaster  WHere BatchId = @rToBatchId AND ((ClassID=@rClassId) OR (@rClassId=0)) AND ( ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)) --	Mantis Id : 0036712 (@@rExamSubGroupIds)
	BEGIN
		Select @lClass=CM.Title, @lExamName = ESGM.Title from sAssessment.tExamMaster EM INNER JOIN sSetup.tClassMaster CM ON CM.Id= EM.ClassID
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId Where EM.BatchId = @rToBatchId AND ((EM.ClassID=@rClassId) OR (@rClassId=0)) AND ( EM.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)
		Select 1 as REsult,@lClass As Class, @lExamName As ExamName
		COMMIT TRANSACTION		
	
		Return
		
	END


	Select @lCount = Count(Id) from sAssessment.tExamMaster where BatchId = @rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)) AND ( ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)
	  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	
	Insert into sAssessment.tExamMaster
	( 
		Id,BatchId,ExamSubGroupId,ClassId,IsRankNo,IsGrade,IsPercentile,IsPercentage,IsSubjectPercentile,
		GradeSetId,RankSetId,LevelSetId,UpdatedUserId,UpdatedDateTime,IsProcessResult,IsMarksInDecimal,
		IsNegativeMarks,IsIncludeCoScholastic,IsOnPrePrinted,ReportId,DisplayTitle,Remark1,Remark2,
		Remark3,IsDisplayPhoto,FooterAdjustment,IsDisplayBirthDate,IsLockForEdit,
		IsDisplaySchoolName,DetailAdjustment,IsDisplayHeightWeight,IsDisplayAttendance,TermScopeId,
		IsResultStatus,ExamMaximum,IsDisplayGradeString,IsIncludeGradeSubject,GradeSubjectGradeSetId,
		IsIncludeSubExam,IsCoScholasticGrade,IsCoScholasticGradeIndicator,
		IsCoScholasticGradeDesIndicator,IsCoScholasticCombine,OldExamId,IsPublished,IsDisplayHighestDivisionMark,
		IsDisplayHighestDivisionGrade,IsDisplayParentName,CoScholasticScopeId,SubjectGroupPerPage,
		IsDisplayTeacherSign,IsDisplayPrincipalSign,PercentileScopeId,CoScholasticGradeSetId,IsExcludeAbsentTotal,
		CoScholasticTitle,IsDisplayMonthlyAttendance,IsDisplayImageHeader,DecimalFormat,IsDisplayTotalMark,
		IsDisplayResultIndicator,IsRemovePercentageForFail,Remark1Caption,Remark2Caption,Remark3Caption,
		TeacherSignCaption,PrincipalSignCaption,ParentSignCaption,IsSubjectWeightage,OldImportExamId,IsDisplayActivityGrade,
		IsAllExamPassRequired,HeaderAdjustment,IsPublishExamSchedule,LinkExamId,OverallPercentageForGrace,MinimumGracePercetage,
		GraceMaxMark,KrupaMaxMark,IsApplySiddhiKrupa,IsDisplayGraph,IsGenerateRankNo,ResultSheetAdditionalTitle		-- Add ResultSheetAdditionalTitle Mantis Id : 0036712
	)
	 Select  
		@lNextNumber + ROW_NUMBER() OVER(ORDER BY Id) ,@rToBatchId,ExamSubGroupId,@rClassId,IsRankNo,IsGrade,IsPercentile,IsPercentage,
		IsSubjectPercentile,GradeSetId,RankSetId,LevelSetId,UpdatedUserId,sCommon.fGetDate(),IsProcessResult,
		IsMarksInDecimal,IsNegativeMarks,IsIncludeCoScholastic,IsOnPrePrinted,ReportId,DisplayTitle,Remark1,
		Remark2,Remark3,IsDisplayPhoto,FooterAdjustment,IsDisplayBirthDate,IsLockForEdit,
		IsDisplaySchoolName,DetailAdjustment,IsDisplayHeightWeight,IsDisplayAttendance,TermScopeId,
		IsResultStatus,ExamMaximum,IsDisplayGradeString,IsIncludeGradeSubject,GradeSubjectGradeSetId,
		IsIncludeSubExam,IsCoScholasticGrade,IsCoScholasticGradeIndicator,
		IsCoScholasticGradeDesIndicator,IsCoScholasticCombine,OldExamId,IsPublished,IsDisplayHighestDivisionMark,
		IsDisplayHighestDivisionGrade,IsDisplayParentName,CoScholasticScopeId,SubjectGroupPerPage,IsDisplayTeacherSign,
		IsDisplayPrincipalSign,PercentileScopeId,CoScholasticGradeSetId,IsExcludeAbsentTotal,CoScholasticTitle,
		IsDisplayMonthlyAttendance,IsDisplayImageHeader,DecimalFormat,IsDisplayTotalMark,IsDisplayResultIndicator,
		IsRemovePercentageForFail,Remark1Caption,Remark2Caption,Remark3Caption,TeacherSignCaption,
		PrincipalSignCaption,ParentSignCaption,IsSubjectWeightage,Id,IsDisplayActivityGrade,IsAllExamPassRequired,
		HeaderAdjustment,IsPublishExamSchedule,0,OverallPercentageForGrace,MinimumGracePercetage,GraceMaxMark,KrupaMaxMark,
		IsApplySiddhiKrupa,IsDisplayGraph,IsGenerateRankNo,ResultSheetAdditionalTitle
	from sAssessment.tExamMaster Where BatchId = @rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)) AND ( ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)
	
	 SET @lNextNumber  = @lCount + @lNextNumber 
	  EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamMaster', @rCurrentNumber = @lNextNumber 

	
	
	
	select @lExamDetailCount =count (Ed.id) from sAssessment.tExamDetail Ed INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId Where ((Em.ClassId=@rClassId) OR (@rClassID=0)) and Em.batchId=@rFromBatchId AND ( EM.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamDetail', 0, 1, 1,@outNextNumber = @lExamdetailNextNumber output

	
	--Delete EC from sAssessment.tExamDetail EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamID where ((Em.ClassId = @rClassId) OR (@rClassID=0)) AND EM.BatchId=@rToBatchID
	--Add TobatchId in SubQuery because it get multiple records of batch 
	Insert into sAssessment.tExamDetail
	( 
		Id,ExamId,ClassSubjectId,Maximum,Minimum,IsIncludeInTotal,IsDisplayInMarksheet,IsShowSubjectGrade,DisplayOrder,GradeSetId,ExamDate,ExamTime,ExamTopic,UpdatedUserId,UpdatedDateTime,NoOfQuestion,IsShowSubjectMark,ExamLanguage		-- Add ExamLanguage Mantis Id : 0036712
	)  
	Select
		@lExamdetailNextNumber+ ROW_NUMBER() OVER(ORDER BY ClassSubjectId),
		ExamId = (SELECT Id FROM sAssessment.tExamMaster E1 WHERE E1.OldImportExamId = Ed.ExamId and E1.ClassId=@rClassId AND E1.BatchId = @rToBatchId AND ( E1.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0))
		,ClassSubjectId,Maximum,Minimum,IsIncludeInTotal,IsDisplayInMarksheet,IsShowSubjectGrade,DisplayOrder,ED.GradeSetId,ExamDate,ExamTime,ExamTopic,ED.UpdatedUserId,sCommon.fGetDate(),NoOfQuestion,IsShowSubjectMark,ExamLanguage
	from sAssessment.tExamDetail Ed INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	Where ((Em.ClassId=@rClassId) OR (@rClassID=0)) and Em.batchId=@rFromBatchId AND ( EM.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)
	
	SET @lExamdetailNextNumber  = @lExamDetailCount + @lExamdetailNextNumber 
	EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamDetail', @rCurrentNumber = @lExamdetailNextNumber 
	
	Select  @lExamCombineCount = count(EC.id) from sAssessment.tExamCombine Ec INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId
	WHere ((Em.ClassId =@rClassId) OR (@rClassID=0)) ANd BatchId =@rFromBatchId AND ( EM.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamCombine', 0, 1, 1,@outNextNumber = @lExamCombineNextNumber output
	
	--Delete EC from sAssessment.tExamCombine EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId Where Em.batchId=@rToBatchId AND ((Em.ClassId=@rClassID) OR (@rClassID=0))  
	--Add TobatchId in SubQuery because it get multiple records of batch
	Insert into sAssessment.tExamCombine
	(
		Id,ExamId,SubExamId,weightage,ExamOrder,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
	)
	Select
		@lExamCombineNextNumber+ROW_NUMBER() OVER(ORDER BY ExamId),ExamId = (Select Id from sAssessment.tExamMaster E1 where E1.OldImportExamId = Ec.ExamId  and E1.ClassId=@rClassId AND E1.BatchId = @rToBatchId AND ( E1.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)),
		SubExamId = (Select Id from sAssessment.tExamMaster E1 where E1.OldImportExamId = Ec.SubExamId and E1.ClassId=@rClassId AND E1.BatchId = @rToBatchId),weightage,ExamOrder,EC.CreatedUserId,SCommon.fGetdate(),EC.UpdatedUserId,sCommon.fGetDate()
	From sAssessment.tExamCombine EC INNER JOIN sAssessment.tExamMaster EM on EM.Id =EC.ExamId where EM.BatchId=@rFromBatchId and ((EM.ClassId=@rClassId) OR (@rClassID=0)) AND ( EM.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)
	
	SET @lExamCombineNextNumber  = @lExamCombineCount + @lExamCombineNextNumber 
	EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamCombine', @rCurrentNumber = @lExamCombineNextNumber 

	--Add TobatchId in SubQuery because it get multiple records of batch
	--DElete EC From sAssessment.tExamCombineSubject EC INNER JOIN sAssessment.tExamMaster  EM ON EM.Id=EC.ExamId WHere ((Em.ClassID =@rClassId) OR (@rClassId=0)) AND EM.BatchId=@rToBatchId
	Insert into sAssessment.tExamCombineSubject
	(
		ExamId,SubExamId,ClassSubjectId,SubjectWeightage
	)
	Select 
		ExamId = (Select Id from sAssessment.tExamMaster E1  Where E1.OldImportExamId = Ec.ExamId AND E1.BatchId = @rToBatchId AND ( E1.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)),
		
		SubExamId =(select Id from sAssessment.tExamMaster E1 Where  E1.OldImportExamId= ec.SubExamId AND E1.BatchId = @rToBatchId),
		ClassSubjectId,SubjectWeightage
	from sAssessment.tExamCombineSubject EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId where ((EM.ClassId =@rClassId) OR (@rClassId=0)) and Em.BatchID=@rFromBatchId AND ( EM.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId = 0)
	
	select 11 as result
COMMIT TRANSACTION		
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCoScholasticExamScoreDelete]
	 @rOrgId int=0,
	 @rClassId int,
	 @rDivisionId int,
	 @rAcademicId bigint,	 
	 @rExamId int,
	 @rBatchId int,
	 @rCCEGroupId int,
	 @rCCEId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	 
			
			 
	 
			DELETE CC FROM  sAssessment.tCCECSExamScore CC				
					INNER JOIN sStudent.tAcademic A ON 	CC.AcademicId = A.Id
					LEFT JOIN sAssessment.tCCECSMaster CGM ON CGM.Id = CC.CCECSId
					LEFt JOIN sAssessment.tCCECSGroupMaster CM ON CM.Id=CGM.CCECAGroupId
					WHERE A.DivisionId = @rDivisionId
						AND A.ClassId = @rClassId
						AND ((CC.AcademicId=@rAcademicId) OR(@rAcademicId=0))
						AND CC.ExamId = @rExamId 
						AND ((CC.CCECSId=@rCCEId) OR (@rCCEId=0))
						AND A.BatchId=@rBatchId
						AND ((CGM.CCECAGroupId=@rCCEGroupId) OR (@rCCEGroupId=0))
						
					
			 
				  
			SELECT 1 AS RESULT
		 
 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCSClassActivityAdd]
	 
     --       @rAcademicId bigint
     --      ,@rExamId int
     --      ,@rIndicator nvarchar(200)
		   --,@rGrade nvarchar(10)
		   --,@rDescriptiveIndicator nvarchar(max)
		   
		   @rCCECSId int,
		   @rClassId int,
		   @rTotalMark decimal(12,2)=0,
		   @rConvertToMark decimal(12,2)=0,
		    @rIsDeleted int,
		    @rIsOptional int=0,
		    @rBatchID int
		   --,@rIndicatodIds nvarchar(50)
		   --,@rIsIndicatodIds bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	 
	  
IF   EXISTS(SELECT 1 FROM sAssessment.tCCECSForClass WHERE CCECSId=@rCCECSId AND ClassId=@rClassId and @rIsDeleted=0 AND  BatchId=@rBatchID)
BEGIN
	Delete from sAssessment.tCCECSForClass where CCECSId =@rCCECSId ANd ClassId =@rClassID AND BatchId=@rBatchID
	 SELECT 1 AS Result
END
ELSE 
BEGIN
	IF exists(Select 1 from sAssessment.tCCECSForClass where CCECSId=@rCCECSId AND ClassId=@rClassId  AND @rIsDeleted=1 ANd BatchId=@rBatchID)
	BEGIN
		Update sAssessment.tCCECSForClass 
		Set
			CCECSId =@rCCECSId,
			ClassId=@rClassId,
			TotalMark=@rTotalMark,
			ConvertToMark=@rConvertToMark,
			IsOptional =@rIsOptional
			Where CCECSId=@rCCECSId AND ClassId=@rClassId 
			AND BatchID=@rBatchID
			Select 1 as Result
	END
	ELSE
	BEGIn
		IF @rIsDeleted=1
		BEGIN
			INSERT INTO sAssessment.tCCECSForClass
			   (
			    [CCECSId]
			   ,ClassId
			   ,TotalMark
			   ,ConvertToMark,
			   IsOptional
			   ,BatchId
			   )
		 VALUES
			   (
				@rCCECSId
			   ,@rClassId	
			   , @rTotalMark
			   , @rConvertToMark,
			   @rIsOptional,
			   @rBatchID
			   )
			   Select 1 as Result
		END	
		 
		
	END
END


 
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCSClassAdd]
	 
	        @rId int
           ,@rCCECSGroupId int
           ,@rClassId int
		   ,@rUpdatedUserId bigint
		   ,@rOrgId bigint
		   ,@rIsDeleted bit
		   ,@rOrderIndex smallint
		   ,@rBatchId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0 AND @rIsDeleted = 1 )	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCECSClass', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCECSClass]
			   (
			    [Id]
			   ,[CCECSGroupId]
			   ,[ClassId]
			   ,[OrderIndex]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,BatchId
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCCECSGroupId
			   ,@rClassId
			   ,@rOrderIndex
			   ,@rUpdatedUserId			   
			   ,sCommon.fGetDate()
			   ,@rBatchId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
 BEGIN
   IF @rIsDeleted = 1
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCECSClass]
	    SET
			 
	          [CCECSGroupId]=@rCCECSGroupId
	         ,ClassId=@rClassId
	         ,OrderIndex = @rOrderIndex
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId And BatchId=@rBatchId 	   
	      SELECT @lNextNumber AS Result
	  END    
   ELSE IF EXISTS (SELECT 1 FROM sAssessment.tCCECSExamScore CS
				   INNER JOIN sStudent.tAcademic A ON CS.AcademicId = A.Id 
				   INNER JOIN sAssessment.tCCECSMaster CM ON CM.Id = CS.CCECSId				  
				   INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id = CM.CCECAGroupId 
				   INNER JOIn sAssessment.tCCECSClass CL ON Cl.ClassId=A.ClassId AND CL.CCECSGroupId=@rCCECSGroupId AND CL.BatchId =@rBatchId   
				   WHERE A.ClassId = @rClassId AND CGM.Id = @rCCECSGroupId  ANd A.BatchId=@rBatchId)
				   
	  BEGIN
		SELECT -101 AS RESULT
	  END	  	
   ELSE
	BEGIN
		DELETE FROM sAssessment.tCCECSClass WHERE Id = @rId ANd BatchId=@rBatchId
		SELECT 1 AS RESULT
	END	
		--COMMIT TRANSACTION
  END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSClassGet]
	  @rClassId int,
	  @rOrgId int,
	  @rbatchid int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
SELECT 
			ISNULL(FS.Id,0) AS Id,
			ISNULL(FGM.ID,0) AS CCEFSGroupId,
			ISNULL(FS.ClassId,0) AS ClassId,			
			FGM.Title AS CCECSGroupName,
			ISNULL(FS.OrderIndex ,0) AS OrderIndex,
			CASE WHEN ISNULL(FS.ClassId,0)=0 THEN 'false' ELSE 'true' END AS Selected
FROM 
			
			sAssessment.tCCECSGroupMaster FGM 
			LEFT JOIN sAssessment.tCCECSCLASS FS ON FGM.Id=FS.CCECSGroupId	
			AND (FS.ClassId=@rClassId OR @rClassId=0) ANd FS.BatchId=@rbatchid
	WHERE FGM.OrgId =   @rOrgId
				
			  
END
--SELECT * FROM sAssessment.tCCECSClass
--SELECT * FROM sAssessment.tCCECSGroupMaster 

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSClassGroupActivityGet]
 
	  @rOrgId int,
	 
	  @rClassId int,
	  @rBatchID int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
 
			SELECT 		
				ISNULL(CGM.Title,'') AS CSGroup,
				ISNULL(CM.Title,'') AS CS,				
			 
				CGM.GradeSetId,
				CM.Id as CMID,
				Isnull(CCFC.TotalMark,0) AS TotalMark,
				Isnull(CCFC.ConvertToMark,0) AS ConvertToMark,
				CASE WHEN ISNULL(CCFC.CCECSId,0)=0 THEN  'False' ELSE 'True' END AS Checked,
				CASE WHEN ISNULL(CCFC.IsOptional,0)=0 then 'false' ELSE 'True' END AS IsOptional
						
			FROM   
				sAssessment.tCCECSGroupMaster CGM  
				INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id
				 LEFT join sAssessment.tCCECSMaster  CM ON CM.CCECAGroupId = CGM.Id AND CM.OrgId=@rOrgId
				LEFT JOIN sAssessment.tCCECSForClass CCFC ON CCFC.CCECSId = CM.Id AND CCFC.ClassId=@rClassId AND CCFC.BatchID=@rBatchID
				
				WHERE 
					   CM.OrgId = @rOrgId
					 AND  CL.ClassId = @rClassId
					AND CL.BatchId=@rBatchID
			ORDER BY CGM.OrderIndex
			 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCSExamGradeAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
	 BEGIN	
		UPDATE AI 
		SET AI.Grade = Term1Grade,
		AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCECSExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						Term1Grade nvarchar(20),
						GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId 
		
		INSERT INTO sAssessment.tCCECSExamScore
			(ExamId,AcademicId,CCECSId,Grade,GradeIndicator)
			
			SELECT	
			A.ExamId,A.AcademicId,A.CCECSId,Term1Grade,GradeTitle
         			
			FROM OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,					
					Term1Grade nvarchar(20),
					GradeTitle nvarchar(50),
					CCECSId int
				  ) A  LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
	
 	 SELECT 1 AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSExamGradeGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(CM.Title) FROM sAssessment.tCCECSGroupMaster CGM
					INNER JOIN sAssessment.tCCECSMaster CM ON CM.CCECAGroupId=CGM.Id AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id ANd CC.BatchId=@rBatchId
					INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= CM.Id AND CL.ClassID= @rClassId  
					AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId  AND CL.BatchId=@rBatchID
					AND CGM.Id=@rCCECSGroupId 
					
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
      
	SET @query = 'Select AcademicId,RollNo,Code As Number,Name,  ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code,SA.Name,  AM.Title, ISNULL(AIS.Grade,'''') AS Term1Indicator
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.CCECSGroupId='+CONVERT(nvarchar,@rCCECSGroupId) +' AND CA.BatchID='+Convert(nvarchar,@rBatchID)+'
	
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID='+ CONVERT(nvarchar,@rClassId) +' AND CL.BatchId='+convert(nvarchar,@rBatchId)+'
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= ' + Convert(nvarchar,@rExamId) +'
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' 
	And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '	
	And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' 
	And AM.CCECAGroupId= ' + CONVERT(nvarchar,@rCCECSGroupId) + '
	AND ((AM.Id = '+ CONVERT(nvarchar,@rCCECSId) +') OR ('+CONVERT(nvarchar,@rCCECSId)+'=0))
	) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

 --print @query
EXECUTE(@query)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCSEXamIndicatorAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT

			  	
					 
			UPDATE AI SET AI.IndicatorIds = Replace(Term1Indicator,',','.') FROM sAssessment.tCCECSExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/CSEXamIndicator', 1)
				WITH ( 				
							AcademicId Bigint,
							CCECSId int,
							ExamId int,
							Term1Indicator NVARCHAR(20)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
			AND A.CCECSId = AI.CCECSId 
			 --INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id = @rORGId	
		 
		INSERT INTO sAssessment.tCCECSExamScore
			(AcademicId,CCECSId,ExamId,IndicatorIds)
			
			SELECT	A.AcademicId,A.CCECSId,A.ExamId,Replace(Term1Indicator,',','.') 
         			
			FROM OPENXML (@loDoc, '/Table/CSEXamIndicator', 1)
			WITH ( 			
					AcademicId Bigint,
					CCECSId int,	
					ExamId int,
					Term1Indicator nvarchar(20) 
					 
				  ) A 	
			LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
			
			--sAssessment.tCCECSMaster AM ON AM.Id = A.CCECSId 			
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AM.OrgId AND OM.Id = @rORGId
			--AND A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCECSExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND CCECSId=AM.Id)
	     
	
    -- Updated by Kp
	UPDATE A SET A.DescriptiveIndicator = 
 					stuff((select ',' + B.Title from sAssessment.tCCECSIndicatorMaster B
				WHERE A.CCECSid=B.CCECSId 
						and ','+ (replace(IndicatorIds,'.',',') )+',' like '%,'+CAST(Number as varchar(10))+',%'				
				for xml path('')),1,1,'') 
         From sAssessment.tCCECSExamScore A    
         INNER JOIN      			
			OPENXML (@loDoc, '/Table/CSEXamIndicator', 1)
			WITH ( 		
					AcademicId Bigint,	
					CCECSId int,	
					ExamId int,
					Term1Indicator nvarchar(20) 
					 
				  )B1
				  ON A.ExamId=B1.ExamId AND A.AcademicId = B1.AcademicId AND B1.CCECSId = A.CCECSId 
	
	 SELECT 1 AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSEXamIndicatorDelete]
 @rDivisionId int
,@rExamId int
,@rCCECSId int

AS
BEGIN

BEGIN TRY

DELETE	S 
FROM sAssessment.tCCECSExamScore S
INNER JOIN sStudent.tAcademic A 
ON s.AcademicId = A.Id
WHERE S.ExamId = @rExamId 
AND (S.CCECSId=@rCCECSId OR @rCCECSId =0) 
AND A.DivisionId = @rDivisionId


		--DELETE	FROM sAssessment.tCCECSExamScore WHERE ExamId = @rExamId 
		--AND (CCECSId=@rCCECSId OR @rCCECSId =0) 
		--AND AcademicId IN
		--(Select Id From sStudent.tAcademic Where DivisionId =@rDivisionId)		
		SELECT 1 AS RESULT
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSEXamIndicatorGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
--BEGIN TRY
	DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(CM.Title) FROM sAssessment.tCCECSGroupMaster CGM
					INNER JOIN sAssessment.tCCECSMaster CM ON CM.CCECAGroupId=CGM.Id
					INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id AND CC.BatchID=@rBatchId
					INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= CM.Id AND CL.ClassID= @rClassId
					AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId AND CGM.Id=@rCCECSGroupId AND CL.BatchID=@rBatchId
					AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Code As Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code,SA.Name,AM.Title,	 ISNULL(AIS.IndicatorIds,'''') AS Term1Indicator
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID='+convert(nvarchar,@rBatchID)+'
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID='+ CONVERT(nvarchar,@rClassId)+' ANd CL.BatchId='+convert(nvarchar,@rBatchID)+'
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= ' + Convert(nvarchar,@rExamId) + ' AND (AIS.CCECSId = ' + convert(nvarchar,@rCCECSId) + ' OR ' + convert(nvarchar,@rCCECSId) + ' = 0 ) 
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' 
	And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '	
	And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	And AM.CCECAGroupId= ' + CONVERT(nvarchar,@rCCECSGroupId) + '
	 
	) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	print @query
EXECUTE(@query)
--END TRY
--BEGIN CATCH
--	SELECT -1 AS RESULT
--END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSExamScoreConvertTo]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int,
	@rExamId int=0,
	@rCSGroupId int=0,
	@rBatchId int=0
	
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT,@lIsMarkIndecimal bit,@lDecimalPlace nvarchar(10),@lGradeSetId int

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
Select @lIsMarkIndecimal = IsMarksInDecimal from sAssessment.tExamMaster where id= @rExamId
Select @lDecimalPlace = DecimalFormat from sAssessment.tExamMaster where id= @rExamId
 
Select  @lGradeSetId=GradeSetId FROM sAssessment.tCCECSMaster CSM 
 INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 	 
						CCECSId int  
				  ) A 	ON CSM. Id = A.CCECSId  
 INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.ID = CSM.CCECAGroupId
  
WHERE CGM.Id =  @rCSGroupId AND CSM.Id = A. CCECSId AND CGM.OrgId =@rOrgId
	--Select @lGradeSetId		 
--Select @lIsMarkIndecimal, @lDecimalPlace
BEGIN
	BEGIN TRY
	 BEGIN	
	 
		Create Table #temp
		(
			AcademicId bigint,	
			CCECSId int,
			ExamId int,
			TotalMarks decimal(12,2),
			 ClassId int
		)
		Insert Into #temp
		(
			AcademicId,
			CCECSId,
			ExamId,
			TotalMarks,
			ClassId
		)		
		
		Select * from OPENXML (@loDoc, '/Table/CSExamGrade', 1)
		WITH ( 				
						AcademicId bigint,	
						CCECSId int,
						ExamId int,
						TotalMarks decimal(12,2),
						 ClassId int
		)
		
		Create Table #tempT
		(
			Id INT IDENTITY (1, 1),
			AcademicId bigint,	
			CCECSId int,
			ExamId int,
			TotalMarks decimal(12,2) 
		)
		Insert Into #tempT
		(
			AcademicId,
			CCECSId,
			ExamId,
			TotalMarks
		)
		Select * from OPENXML (@loDoc, '/Table/CSExamGrade', 1)
		WITH ( 				
					AcademicId bigint,	
					CCECSId int,
					ExamId int,
					TotalMarks decimal(12,2) 
			)
			
		 --Select * from #tempT
		 --Select * from sAssessment.tCCECSExamScore Where AcademicId = '1991000002213' AND CCECSId = '199100001'AND ExamId = '199100222'
		UPDATE AI 
		--SET  
				--AI.ConvertedMark =ROund( ( T.TotalMarks * CC.ConvertToMark)/CC.TotalMark,0)
				SET AI.ConvertedMark = 
					CASE 
						WHEN @lIsMarkIndecimal = 1 AND @lDecimalPlace = '0.0'						-- Mantis Id : 0037575	(add based on @lIsMarkIndecimal)
							THEN ROUND((T.TotalMarks * CC.ConvertToMark) / CC.TotalMark, 1)
						WHEN @lIsMarkIndecimal = 1 AND @lDecimalPlace = '0.00'
							THEN ROUND((T.TotalMarks * CC.ConvertToMark) / CC.TotalMark, 2)
						ELSE 
							ROUND((T.TotalMarks * CC.ConvertToMark) / CC.TotalMark, 0)
					END
		 FROM sAssessment.tCCECSExamScore AI
		 INNER JOIN #temp T On T.AcademicId = AI.AcademicId AND T.CCECSId = AI.CCECSId AND T.ExamId =AI.ExamId
		 INNER JOIN sAssessment.tCCECSForClass CC ON CC.CCECSId =AI.CCECSId AND CC.ClassId =T.ClassId
		 WHERE T.TotalMarks = AI.ObtianMark AND CC.BatchId = @rBatchId
		 
		-- INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
		--	WITH ( 				
		--				AcademicId bigint,	
		--				CCECSId int,
		--				ExamId int,
		--				TotalMarks decimal(12,2),
		--				 ClassId int
		--				--GradeTitle nvarchar(50)
									
		--		  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
				  
		--AND A.CCECSId = AI.CCECSId 
		--INNER JOIN sAssessment.tCCECSForClass CC ON CC.CCECSId = AI.CCECSId AND CC.ClassId = A.ClassId	
		--WHERE A.TotalMarks = AI.ObtianMark AND CC.BatchId = @rBatchId
		Create Table #Gradetemp
		(
			Id int,
			GradeSetId bigint,	
			MinimumScore Decimal(12,2),		-- Changed int to Decimal Mantis Id : 0037575	
			GradeCode nvarchar(20),
			GradeTitle nvarchar(50),
			GradePoint int,
			MarkRange nvarchar(50)

		)
		INSERT INTO #Gradetemp
		Select * from sAssessment.tGradeSetDetail Where GradeSetId = @lGradeSetId
		Order By MinimumScore DESC

		--Select * from #Gradetemp

			DECLARE @lCount int ,@AcademicId bigint ,@ExamId1 int,@CCECSId1 int
			SELECT @lCount =  COUNT(AcademicId) FROM #tempT
			--Select @lCount
		while (@lCount > 0)
		BEGIN
				Select @AcademicId= AcademicId FROM #tempT Where Id=@lCount
				Select @ExamId1= ExamId FROM #tempT Where Id=@lCount
				Select @CCECSId1= CCECSId FROM #tempT Where Id=@lCount
				 
				 Update AI 
					Set Grade = GS.GradeCode ,GradeIndicator=GS.GradeTitle
					from  sAssessment.tCCECSExamScore AI 
					INNER JOIN #tempT T ON T.AcademicId=AI.AcademicId AND T.ExamId=AI.ExamId AND T.CCECSId=AI.CCECSId
					INNER JOIN sAssessment.tCCECSMaster CSM ON CSM.Id = T.CCECSId
					INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id =CSM.CCECAGroupId
					INNER JOIN #Gradetemp GS ON GS.GradeSetId =CGM.GradeSetId
					Where CGM.GRadeSetId=@lGradeSetId AND AI.ConvertedMark>=GS.MinimumScore
					AND T.ExamId=@ExamId1 AND T.CCECSId=@CCECSId1 AND AI.AcademicId=@AcademicId 
					SET @lCount = @lCount - 1
					SET @AcademicId=0
		END
		DROP TABLE #temp
		DROP TABLE #tempT
		DROP TABLE #Gradetemp
 	 SELECT  @lGradeSetId AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSExamScoreGet]
	  @rAcademicId bigint=0
	  ,@rOrgId int
	  ,@rExamId int
	  ,@rBatchId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				ISNULL(CGM.Title,'') AS CSGroup,
				ISNULL(CM.Title,'') AS CS,				
				ISNULL(CC.Grade,'')  AS Grade,
				ISNULL(CC.GradeIndicator,'') AS Indicator,
				ISNULL(CC.DescriptiveIndicator,'')  AS DescriptiveIndicator,			
				ISNULL(SA.AcademicId,0) AS AcademicId,
				ISNULL(CC.IndicatorIds,'') AS IndicatorIds,
				CGM.GradeSetId,
				CM.Id as CMID,
				ISNULL(CC.ConvertedMark,0) AS ConvertedMark,
				SA.batchid,
				SA.DivisionID,
				Sa.ClassID
						
			FROM    
				sAssessment.tCCECSMaster CM 
				INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
				INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id AND CL.BatchID=@rBatchID			
				INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CL.ClassId 
				INNER JOIN  sAssessment.tCCECSForClass CFC ON CFC.CCECSID=CM.Id AND CL.ClassId =CFC.ClassId AND CFC.BatchID=@rBatchID
				LEFT JOIN   sAssessment.tCCECSExamScore CC  ON CC.CCECSID=CM.ID  
				
				AND CC.AcademicId = SA.AcademicId AND ExamId=@rExamId	AND CC.AcademicId = @rAcademicId	
				WHERE ((SA.AcademicId = @rAcademicId) OR (@rAcademicId=0))
		
			ORDER BY CM.OrderIndex
			SELECT 1 AS RESULT
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCSExamScoreSetupAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int,
	@rFilter int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
	 BEGIN	
	 
	 if @rFilter=1
	 BEGIN
	 --    if exists (select 1 from sAssessment.tCCECSExamScore AI INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
		--	WITH ( 				
		--				AcademicId bigint,
		--				CCECSId int,
		--				ExamId int,
		--				TotalMarks decimal(12,2) 
						 
		--				--GradeTitle nvarchar(50)
									
		--		  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		--AND A.CCECSId = AI.CCECSId )
		--BEGIN
		UPDATE AI 
		SET AI.ObtianMark = A.TotalMarks 
			--AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCECSExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						TotalMarks decimal(12,2) 
						 
						--GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId 
		--End
		
		--Else
		--BEGIN
		INSERT INTO sAssessment.tCCECSExamScore
			(ExamId,AcademicId,CCECSId,ObtianMark )
			
			SELECT	
			A.ExamId,A.AcademicId,A.CCECSId,A.TotalMarks 
         			
			FROM OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,	
					CCECSId int,				
					TotalMarks decimal(12,2) 
					 
					--GradeTitle nvarchar(50),
					
				  ) A  LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
			--END
	END
	
	IF @rFilter=2
	BEGIN
	--if exists (select 1 from sAssessment.tCCECSExamScore AI
	--	INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
	--		WITH ( 				
	--					AcademicId bigint,
	--					CCECSId int,
	--					ExamId int,
						 
	--					 ConvertToMarks decimal(12,2)
	--					--GradeTitle nvarchar(50)
									
	--			  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
	--	AND A.CCECSId = AI.CCECSId )
	--	BEGIN
		UPDATE AI 
		SET  
			AI.ConvertedMark = A.ConvertToMarks
			--AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCECSExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
						AcademicId bigint,
						CCECSId int,
						ExamId int,
						 
						 ConvertToMarks decimal(12,2)
						--GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.CCECSId = AI.CCECSId 
		--END
		--ELse
		--BEGIN
		 
		INSERT INTO sAssessment.tCCECSExamScore
			(ExamId,AcademicId,CCECSId, ConvertedMark)
			
			SELECT	
			A.ExamId,A.AcademicId,A.CCECSId, A.ConvertToMarks
         			
			FROM OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,					
					 CCECSId int,
					ConvertToMarks decimal(12,2) 
					--GradeTitle nvarchar(50),
					 
				  ) A  LEFT JOIN sAssessment.tCCECSExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.CCECSId = AI.CCECSId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.CCECSId IS NULL)
			       --END
	END
	
 	 SELECT 1 AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSExamScoreSetupGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0,
	  @rFilter int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(CM.Title) FROM sAssessment.tCCECSGroupMaster CGM
					INNER JOIN sAssessment.tCCECSMaster CM ON CM.CCECAGroupId=CGM.Id
					INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id AND CC.BatchId=@rBatchID
					INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= CM.Id AND CL.ClassID= @rClassId
					AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId 
					AND CGM.Id=@rCCECSGroupId AND CL.BatchId=@rBatchID
					AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
     IF @rFilter = 1
     BEGIN  
	SET @query = 'Select AcademicId,RollNo,Code As Number,Name , ' + @cols + '
	FROM
	(
		SELECT SA.RollNo,SA.Code,SA.Name,AM.Title, ISNULL(AIS.ObtianMark,0) AS TotalMark,SA.AcademicId
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID='+Convert(nvarchar,@rBatchId)+'
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID='+ CONVERT(nvarchar,@rClassId)+' AND CL.BatchId='+convert(nvarchar,@rBatchId)+'
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= ' + Convert(nvarchar,@rExamId) + ' AND (AIS.CCECSId = ' + convert(nvarchar,@rCCECSId) + ' OR ' + convert(nvarchar,@rCCECSId) + ' = 0 ) 
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' 
	And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '	
	And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' 
	And AM.CCECAGroupId= ' + CONVERT(nvarchar,@rCCECSGroupId) + '
 
	) MAIN
	PIVOT
	(
		max(TotalMark)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	END
	IF @rFilter=2
	BEGIN
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT  SA.RollNo,SA.Code AS Number,SA.Name,AM.Title, ISNULL(AIS.ConvertedMark,0) AS ConvertToMarks,SA.AcademicId
			FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID='+Convert(nvarchar,@rBatchId)+'
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID='+ CONVERT(nvarchar,@rClassId) +'
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= ' + Convert(nvarchar,@rExamId) + ' AND (AIS.CCECSId = ' + convert(nvarchar,@rCCECSId) + ' OR ' + convert(nvarchar,@rCCECSId) + ' = 0 ) 
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' 
	And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '	
	And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' 
	And AM.CCECAGroupId= ' + CONVERT(nvarchar,@rCCECSGroupId) + '
	 
	) MAIN
	PIVOT
	(
		max(ConvertToMarks)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	END
  --print @query
EXECUTE(@query)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSGradeWiseIndicatorAdd]
	 
            @rCCECSId int
           ,@rTitle nvarchar(100)
		   ,@rGradeSetDetailId int	  
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF NOT EXISTS (Select CCECSID FROM sAssessment.tCCECSIndicatorGrade WHERE CCECSId=@rCCECSId AND GradeSetDetailId=@rGradeSetDetailId)
  BEGIN
	INSERT INTO [sAssessment].[tCCECSIndicatorGrade]
			   (
			    [CCECSId]
			   ,[Title]
			   ,[GradeSetDetailId] 
			   )
		 VALUES
			   (
			    @rCCECSId
			   ,@rTitle
			   ,@rGradeSetDetailId
			   )
		    SELECT 1 AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	
	    UPDATE  [sAssessment].[tCCECSIndicatorGrade]
	    SET			 
			Title=@rTitle
	    WHERE CCECSId = @rCCECSId AND GradeSetDetailId =@rGradeSetDetailId
	   	SELECT 1 AS RESULT	
	
		--COMMIT TRANSACTION
	 END  
	
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSGradeWiseIndicatorDelete]
@rCCECSId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT CCECSId FROM sAssessment.tCCECSScore WHERE CCECSId = @rCCECSId)	
	  BEGIN
		DELETE	FROM sAssessment.tCCECSIndicatorGrade WHERE CCECSId=@rCCECSId
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSGroupForMarkConvertGet]
 
	  @rOrgId int
	 ,
	  @rExamId int=0,
	  @rClassId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				ISNULL(CGM.Title,'') AS CSGroup,
				ISNULL(CM.Title,'') AS CS,				
			 
				CGM.GradeSetId,
				CM.Id as CMID,
				Isnull(CCFC.TotalMark,0) AS TotalMark,
				Isnull(CCFC.ConvertToMark,0) AS ConvertToMark,
				CASE WHEN ISNULL(CCFC.CCECSId,0)=0 THEN 'False' ELSE 'True' END AS Checked
				
						
			FROM   
				sAssessment.tCCECSMaster CM 
				INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
				INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id 
				LEFT JOIN sAssessment.tCCECSForClass CCFC ON CCFC.CCECSId = CM.Id AND CCFC.ClassId = @rClassId 		 
				
				WHERE 
					   CM.OrgId = @rOrgId
					 AND CL.ClassId = @rClassId
		
			ORDER BY CGM.OrderIndex
			 
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSGroupMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
	       ,@rNumber int
           ,@rTitle nvarchar(100)
           ,@rCSGroupTypeId int
           ,@rGradeSetId int
           ,@rIsObsolete bit
           ,@rOrderIndex int
           ,@rUpdatedUserId bigint           
           ,@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tCCECSGroupMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAssessment.tCCECSGroupMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
		If Exists(select Id from sAssessment.tCCECSGroupMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tCCECSGroupMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAssessment.tCCECSGroupMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sAssessment.tCCECSGroupMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCECSGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tCCECSGroupMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Number]
			   ,[Title]
			   ,[CCECSGroupTypeId]
			   ,[GradeSetId]
			   ,[IsObsolete]
			   ,[OrderIndex]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rNumber
			   ,@rTitle
			   ,@rCSGroupTypeId
			   ,@rGradeSetId
			   ,@rIsObsolete
			   ,@rOrderIndex
			   ,@rUpdatedUserId
			   ,sCommon.fGetDate()			
			   ,@rOrgId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCECSGroupMaster]
	    SET
			  Code=@rCode
			 ,Number=@rNumber
	         ,Title=@rTitle
	         ,CCECSGroupTypeId=@rCSGroupTypeId
	         ,GradeSetId=@rGradeSetId
	         ,OrderIndex=@rOrderIndex
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rUpdatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSGroupMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF EXISTS (SELECT CCECSId FROM sAssessment.tCCECSIndicatorMaster FI
			INNER JOIN sAssessment.tCCECSMaster FM ON FI.CCECSId=FM.Id AND FM.CCECAGroupId = @rId)	
	  BEGIN	
		SELECT -101 AS RESULT
	   END
	ELSE IF EXISTS (SELECT Id FROM sAssessment.tCCECSClass WHERE CCECSGroupId = @rId)  
	  BEGIN
		SELECT -101 AS RESULT
	  END	 
	ELSE
		BEGIN
			DELETE	FROM sAssessment.tCCECSMaster WHERE CCECAGroupId=@rId		
			DELETE FROM sAssessment.tCCECSGroupMaster WHERE Id = @rId	
			SELECT 1 AS RESULT			
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSGroupMasterGet] 
          
           --@rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgId int
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			Set @rCode = sCommon.fSearchStringGet(@rCode)
		--END

BEGIN
SELECT FGM.Id AS Id
	  ,FGM.Title AS Title
	  ,FGM.Code AS Code
	  ,FGM.Number AS Number
	  ,GTM.Title AS CSGroupType	  
	  ,FGM.OrderIndex AS OrderIndex
      ,FGM.IsObsolete AS IsObsolete
     
  FROM [sAssessment].[tCCECSGroupMaster] FGM     
       INNER JOIN [sAssessment].[tCCECSGroupTypeMaster] GTM ON GTM.Id=FGM.CCECSGroupTypeId
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((FGM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((FGM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND FGM.OrgId = @rOrgId
	Order By FGM.OrderIndex ASC
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSIndicatorDetailAdd]
	 
	        @rId int
           ,@rCCECSId int
           ,@rTitle nvarchar(200)
           --,@rCode nvarchar(200)
           ,@rNumber smallint
		   ,@rOrderIndex int	
		   ,@rGradeSetDetailId int	  
		   ,@rUpdatedUserId bigint
		   ,@rIsObsolete bit
		   ,@rOrgId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCECSIndicatorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCECSIndicatorMaster]
			   (
			    [Id]
			   ,[CCECSId]
			   ,[Title]
			   --,[Code]
			   ,[Number] 
			   ,[OrgId]
			   ,[IsObsolete]
			   ,[OrderIndex]	
			   ,[GradeSetDetailId] 
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCCECSId
			   ,@rTitle
			   --,@rCode
			   ,@rNumber
			   ,@rOrgId
			   ,@rIsObsolete
			   ,@rOrderIndex
			   ,@rGradeSetDetailId
			   ,@rUpdatedUserId			   
			   ,sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCECSIndicatorMaster]
	    SET
			 
	          CCECSId=@rCCECSId
	         ,Title=@rTitle
	         --,Code=@rCode
	         ,Number=@rNumber
	         ,OrgId=@rOrgId
	         ,IsObsolete=@rIsObsolete
			 ,OrderIndex=@rOrderIndex
			 ,GradeSetDetailId=@rGradeSetDetailId
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSIndicatorDetailGet]
	 @rCCECSId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT			
			FIM.Id,
			FIM.CCECSId,
			--FIM.Code,
			FIM.Number,
			FIM.TITLE,
			FIM.GradeSetDetailId,
			FIM.OrderIndex
  FROM 
			sAssessment.[tCCECSIndicatorMaster] FIM
WHERE 
			(FIM.CCECSId=@rCCECSId OR @rCCECSId=0)  order by FIM.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSIndicatorGradeWiseGet]
	 @rCCECSId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
  SELECT			
			CM.Id AS CCECSId,
			GD.Id AS GradeSetDetailId,
			ISNULL(CS.Title,'') AS Title,
			GD.GradeCode As GradeTitle
  FROM		sAssessment.tGradeSetMaster GS 
			INNER Join sAssessment.tGradeSetDetail GD ON GD.GradeSetID = GS.Id
			INNER JOIN sAssessment.tCCECSGroupMaster GM ON GM.GradeSetId = GS.Id
			INNER JOIN sAssessment.tCCECSMaster CM ON CM.CCECAGroupId= GM.Id
			LEFT JOIN  sAssessment.[tCCECSIndicatorGrade] CS ON CS.GradeSetDetailId = GD.Id AND CS.CCECSId=CM.Id
WHERE 
			(CM.ID=@rCCECSId OR @rCCECSId=0)  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSIndicatorGroupDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT CCECSId FROM sAssessment.tCCECSScore WHERE CCECSId = @rId) OR
		NOT EXISTS (SELECT CCECSId FROM sAssessment.tCCECSExamScore WHERE CCECSId = @rId) 
	  BEGIN
		DELETE	FROM sAssessment.tCCECSIndicatorMaster WHERE CCECSId=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSIndicatorMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT 1 FROM sAssessment.tCCECSScore WHERE Indicator IN 
		(SELECT TITLE FROM sAssessment.tCCECSIndicatorMaster WHERE Id=@rId)) OR
		NOT EXISTS (SELECT * FROM sAssessment.tCCECSExamScore WHERE REPLACE(IndicatorIds,'.',',') IN 
		(SELECT CONVERT(NVARCHAR,NUMBER) FROM sAssessment.tCCECSIndicatorMaster Where Id= @rId))	
	  BEGIN
		DELETE	FROM sAssessment.tCCECSIndicatorMaster WHERE Id=@rId	
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSMasterAdd]
	 
	        @rId int
           ,@rCCECSGroupId int
           --,@rCode nvarchar(100)
           ,@rNumber int
           ,@rTitle nvarchar(100)
		   ,@rOrderIndex int		  
		   ,@rUpdatedUserId bigint
		   ,@rOrgId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCECSMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCECSMaster]
			   (
			    [Id]
			   ,[CCECAGroupId]
			   --,[Code]
			   ,[Title] 
			   ,[Number]
			   ,[OrderIndex]
			   ,[OrgId]			 
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[IsObsolete]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCCECSGroupId
			   --,@rCode
			   ,@rTitle
			   --,[sCommon].[fXMLTagsReplace](@rTitle)
			   ,@rNumber
			   ,@rOrderIndex
			   ,@rOrgId
			   ,@rUpdatedUserId
			   ,0
			   ,0
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCECSMaster]
	    SET
			 
	          CCECAGroupId=@rCCECSGroupId
	          ,Title = @rTitle
	         --,Title=[sCommon].[fXMLTagsReplace](@rTitle)
	         --,Code=@rCode
	         ,Number=@rNumber
			 ,OrderIndex=@rOrderIndex
			 ,OrgId=@rOrgId
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT Id FROM sAssessment.tCCECSIndicatorMaster WHERE CCECSId = @rId)	
	  BEGIN
		DELETE	FROM sAssessment.tCCECSMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSMasterDetailGet]
	 @rCCECSGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT
			CGM.Id,
			CGM.Code As Code,
			[sCommon].[fXMLTagsReplaceReverse](CGM.Title) AS Title,
			CGM.Number AS Number,
			CGM.CCECSGroupTypeId,
			CGM.GradeSetId,
			CGM.OrderIndex AS OrderIndex,
			CGM.IsObsolete AS IsObsolete,
			CM.Id AS CSMasterID,
			CM.CCECAGroupId AS CSGroupId,
			CM.TITLE AS CSMasterTitle,
			--CM.Code AS CSMasterCode,
			CM.Number AS CSMasterNumber,
			CM.OrderIndex AS CSOrderIndex,
			CGM.title
			
  FROM 
			[sAssessment].[tCCECSGroupMaster] CGM
			INNER JOIN sAssessment.tCCECSMaster CM ON CGM.Id=CM.CCECAGroupId
			INNER JOIN [sAssessment].[tCCECSGroupTypeMaster] GTM ON GTM.Id= CGM.CCECSGroupTypeId
			--INNER JOIN [sAssessment].[tGradeSetMaster] GSM ON GSM.Id = CGM.GradeSetId
WHERE 
			(CGM.Id=@rCCECSGroupId OR @rCCECSGroupId=0)  order by CGM.OrderIndex ASC,CM.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSOptionalActivityGet]
                  
          @rDivisionId  int,
          @rClassId  int,
          @rBatchId int ,
		  @rActivityId int = 0
      
AS
SET NOCOUNT ON

BEGIN

SELECT 
SS.AcademicId,
SS.CCECSId,
SS.StudentName, 
SS.Code,
SS.RollNo,
CM.Title AS CS,
CASE WHEN isnull(OCES.CCECSId,0) <> 0 THEN 'true' ELSE 'false' END AS Selected
FROM
(SELECT
SA.AcademicId,
CS.CCECSId as CCECSId,
SA.Name as StudentName,
SA.Code,
SA.RollNo 
 
FROM
 (select * FROM sStudent.vStudentAcademic where DivisionId=@rDivisionId AND StatusId=1 AND BatchId=@rBatchId )SA  
 CROSS JOIN    (select * FROM sAssessment.tCCECSForClass B   WHERE  B.IsOptional=1 AND   B.ClassId = @rClassId and BatchId=@rBatchID 
) AS CS 
 ) AS SS
 INNER JOIN sAssessment.tCCECSMaster CM ON SS.CCECSId = Cm.Id 
 LEFT JOIN sAssessment.tOptionalCCECS OCES ON OCES.AcademicId = SS.AcademicId AND OCES.CCECSId = SS.CCECSId

 where (CM.Id = @rActivityId OR @rActivityId = 0) 
ORDER BY SS.RollNo,CM.OrderIndex
	   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pCSScoreAdd]
	 
	        @rId bigint
           ,@rAcademicId bigint
           ,@rCCECSIndicator nvarchar(200)
		   ,@rGrade nvarchar(10)
		   ,@rGradePoint decimal(6,2)
		   ,@rCCECSId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF NOT EXISTS (SELECT ACADEMICID FROM sAssessment.tCCECSScore WHERE AcademicId=@rAcademicId AND CCECSId=@rCCECSId)	
BEGIN
	INSERT INTO [sAssessment].[tCCECSScore]
			   (
			  
			   [AcademicId]
			   ,[Indicator]
			   ,[Grade]
			   ,[GradePoint]
			   ,[CCECSId]
			   )
		 VALUES
			   (			
			    @rAcademicId
			   ,@rCCECSIndicator
			   ,@rGrade
			   ,@rGradePoint
			   ,@rCCECSId
			   )
		    SELECT 1 AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 
	    UPDATE  [sAssessment].[tCCECSScore]
	    SET
			 
	          [AcademicId]=@rAcademicId
	         ,Indicator=@rCCECSIndicator
			 ,Grade =@rGrade
			 ,GradePoint=@rGradePoint
	      WHERE AcademicId = @rAcademicId AND CCECSId=@rCCECSId
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSScoreGet]
	  @rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT DISTINCT				
				ISNULL(CGM.Title,'') AS CSGroup,
				ISNULL(CM.Title,'') AS CS,
				ISNULL(CST.Grade,'')  AS Grade,
				ISNULL(CST.Indicator,'') AS Indicator,
				ISNULL(CST.GradePoint,0)  AS GradePoint,
				ISNULL(CM.Id,0) AS CMID,
				ISNULL(CGM.GradeSetId,0) AS GradeSetId,SA.AcademicId,CGM.OrderIndex,CM.OrderIndex
						
			FROM   
				 sAssessment.tCCECSClass CC 
				INNER JOIN sStudent.vStudentFull SA ON CC."ClassId" = SA."ClassId" 
				INNER JOIN sAssessment.tCCECSMaster CM ON CC."CCECSGroupId" = CM."CCECAGroupId"  AND CM.ORGID=SA.ORGID
				INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId 
			    
				LEFT JOIN
				(SELECT CSM.ID,			
				CS.AcademicId,CS.Grade,CS.GradePoint,CS.Indicator 
				FROM sAssessment.tCCECSScore CS  
				inner JOIN sAssessment.tCCECSMaster CSM ON CS.CCECSId = CSM.ID ) AS CST
				ON CST.Id = CM.Id AND CST.AcademicId = SA.AcademicId 
			    
			WHERE SA.AcademicId = @rAcademicId 
			ORDER BY CGM.OrderIndex
			SELECT 1 AS RESULT
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSSCSExamScoreGadePointGet]
	 @rGradeSetDetailId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
 BEGIN TRY	
DECLARE @GRADEPOINT DECIMAL
	SELECT GradePoint FROM SASSESSMENT.tGradeSetDetail WHERE ID = @rGradeSetDetailId 	
	SELECT 1 AS RESULT
END TRY
BEGIN CATCH
	 SELECT -1 AS RESULT
END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSSCSExamScoreIndicatorGet]
	  @rGradeSetDetailId int
	 ,@rCCECSId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
 BEGIN TRY	
	SELECT Title AS Indicator 
	FROM SASSESSMENT.tCCECSIndicatorGrade 
	WHERE GradeSetDetailID = @rGradeSetDetailId AND CCECSId=@rCCECSId
END TRY
BEGIN CATCH
	 SELECT -1 AS RESULT
END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSSCSIndicatorAssignGadePointGet]
	 @rGradeSetDetailId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
 BEGIN TRY	
DECLARE @GRADEPOINT DECIMAL
	SELECT GradePoint FROM SASSESSMENT.tGradeSetDetail WHERE ID = @rGradeSetDetailId 	
	SELECT 1 AS RESULT
END TRY
BEGIN CATCH
	 SELECT -1 AS RESULT
END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSSCSIndicatorAssignIndicatorGet]
	  @rGradeSetDetailId int
	 ,@rCCECSId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
 BEGIN TRY	
	SELECT Title AS Indicator 
	FROM SASSESSMENT.tCCECSIndicatorGrade 
	WHERE GradeSetDetailID = @rGradeSetDetailId AND CCECSId=@rCCECSId
END TRY
BEGIN CATCH
	 SELECT -1 AS RESULT
END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSStudentDetailGet]
	  
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='', 
	  @rClassId int,
	  @rDivisionId int,
	  @rExamId int,
	  @rCCECSGroupId int,
	  @rCCECSIndicatorId int,
	  @rOrgId int,
	  @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,	
			SA.Name AS Name,
			SA.RollNo,
			SA.Number,
			CGM.Title AS IndicatorGroup,
			CM.Title AS Indicator,
			AIS.Grade,
			SA.ClassName + '-' + SA.DivisionName AS Class,
			SA.ClassId,
			SA.DivisionId,
			AIS.DescriptiveIndicator
  FROM 
  
			sStudent.vStudentAcademic SA
			INNER JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId
			INNER JOIN sAssessment.tCCECSMaster CM ON AIS.CCECSId=CM.Id			
			INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.ID= CM.CCECAGroupId			
			--INNER JOIN sAssessment.tCCECSClass CC ON CC.ClassId=SA.ClassId
			
WHERE 
			SA.OrgId = @rOrgId
			AND (SA.BatchId = @rBatchId) 
			AND ((SA.ClassId = @rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			AND ((AIS.ExamId= @rExamId) OR (@rExamId=0))
			AND ((CGM.Id=@rCCECSGroupId) OR (@rCCECSGroupId=0))
			AND ((CM.Id =@rCCECSIndicatorId) OR (@rCCECSIndicatorId=0)) 
			
			ORDER BY SA.RollNo
			
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSStudentOptionalSubjectGet]
	 
	 @rDivisionId  int,
	 @rClassId int=0,
	 --@rCCECAGroupId int=0,
	 @rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	--SELECT 
	--	OCCECS.AcademicId,
	--	OCCECS.CCECSId,
	--	AM.Title AS ActivityName
	--FROM sAssessment.tOptionalCCECS OCCECS  
	--INNER JOIN sAssessment.tCCECSForClass CL ON OCCECS.CCECSId = CL.CCECSId  
	--INNER JOIN sAssessment.tCCECSMaster AM ON AM.Id=CL.CCECSId AND AM.Id=OCCECS.CCECSId  
	--INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id=AM.CCECAGroupId  
	--WHERE 
	--Cl.classid=@rClassId 
	--AND ((AM.CCECAGroupId= @rCCECAGroupId ) OR (@rCCECAGroupId= 0))
	--AND CL.BatchId = @rBatchId 
	--AND AM.IsObsolete = 0 
	--AND CG.IsObsolete = 0


SELECT 
SS.AcademicId,
SS.CCECSId,
CM.Title AS ActivityName,
CASE WHEN isnull(OCES.CCECSId,0) <> 0 THEN 'true' ELSE 'false' END AS Selected,
CASE WHEN ISNULL(SS.IsOptional,0)=0 then 'false' ELSE 'true' END AS IsOptional
FROM
(SELECT
SA.AcademicId,
CS.CCECSId as CCECSId,
CS.IsOptional

FROM
 (select * FROM sStudent.vStudentAcademic where DivisionId=@rDivisionId AND StatusId=1 AND BatchId=@rBatchId )SA  
 CROSS JOIN    (select * FROM sAssessment.tCCECSForClass B   WHERE  B.ClassId = @rClassId and BatchId=@rBatchID ) AS CS 
 ) AS SS
 INNER JOIN sAssessment.tCCECSMaster CM ON SS.CCECSId = Cm.Id 
 LEFT JOIN sAssessment.tOptionalCCECS OCES ON OCES.AcademicId = SS.AcademicId AND OCES.CCECSId = SS.CCECSId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSSubActivityDelete]
@rId bigint
AS
BEGIN 
	--IF NOT EXISTS (SELECT Id FROM sAssessment.tCCECSIndicatorMaster WHERE CCECSId = @rId)	
	--  BEGIN
		DELETE	FROM sAssessment.tCCESubjectSubActivityMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	--   END
	--ELSE
	--	BEGIN
	--		SELECT -101 AS RESULT
	--	END 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSSubjectActivityAdd]
	 
	        @rId int,
	        @rClassSubjectId int
	       ,@rNumber smallint
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rOrgId smallint
           ,@rIsObsolete bit
           ,@rOrderIndex int
           ,@rUpdatedUserId bigint           
           ,@rGradeSetId int
		   ,@rRemark nvarchar(max)='' --add for mantis : 0038981
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tCCESubjectActivityMaster where Code=@rCode AND OrgId=@rOrgId AND ClassSubjectId = @rClassSubjectId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAssessment.tCCESubjectActivityMaster where Title=@rTitle AND OrgId=@rOrgId AND ClassSubjectId = @rClassSubjectId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
		If Exists(select Id from sAssessment.tCCESubjectActivityMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tCCESubjectActivityMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId  AND ClassSubjectId = @rClassSubjectId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAssessment.tCCESubjectActivityMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId AND ClassSubjectId = @rClassSubjectId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sAssessment.tCCESubjectActivityMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId AND Id<>@rId AND ClassSubjectId=@rClassSubjectId)
		Begin
			select -104 as Result
			RETURN
		End
		

	END
	
	
	
	 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCESubjectActivityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tCCESubjectActivityMaster]
			   (
			    [Id]
			   ,[ClassSubjectId]
			   ,[Number]
			   ,[Code]
			   ,[Title]
			   ,[OrgId]
			   ,[IsObsolete]
			   ,[OrderIndex]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[GradeSetId]
			   ,[Remark]--add for mantis : 0038981
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rClassSubjectId
			   ,@rNumber,
				@rCode
			   ,@rTitle
			   ,@rOrgId
			   ,@rIsObsolete
			   ,@rOrderIndex
			   ,@rUpdatedUserId
			   ,sCommon.fGetDate()			
				,@rGradeSetId
				,@rRemark	--add for mantis : 0038981   
			   )
		    SELECT @lNextNumber AS Result
      
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCESubjectActivityMaster]
	    SET
			ClassSubjectId= @rClassSubjectId,
			  Code=@rCode
			 ,Number=@rNumber
	         ,Title=@rTitle
	         
	         ,GradeSetId=@rGradeSetId
	         ,OrderIndex=@rOrderIndex
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rUpdatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate() 
			 ,[Remark] = @rRemark    --add for mantis : 0038981     
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
	 
	 END  	

	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSSubjectActivityCopy]
		@rClassId int=0,
		@rOrgId int,
		@rSubjectId int,
		   @rToClassId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 DECLARE @lNextNumber BIGINT,@lClassSubjectId int
	 Select  @lClassSubjectId =Id from sSetup.tClassSubject where SubjectId = @rSubjectId and ClassId=@rToClassId
	 
	declare @lCount int,@lNumber smallint,@lOrderIndex smallint
	declare @lId int
 
	
	create table #temp
	(
		Id int identity,
		ActivityId int
	)
	Insert into #temp
	(
		ActivityId
	)
	select SA.Id from   sAssessment.tCCESubjectActivityMaster SA INNER JOIN sSetup.tClassSubject CS ON CS.Id=SA.ClassSubjectID
	Where CS.ClassID=@rClassId AND SA.OrgId=@rOrgId And CS.SubjectId=@rSubjectId  
	
	Select @lCount=count(Id) from #temp
	 select @lNumber=max(number), @lOrderIndex =max(OrderIndex) from sAssessment.tCCESubjectActivityMaster where OrgId=@rOrgid
	 
	 while(@lcount>0)
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCESubjectActivityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	Select @lId =SA.Id from sAssessment.tCCESubjectActivityMaster SA
				INNER JOIN #temp t on t.ActivityId = SA.Id 
				Where  t.Id=@lCount
				
	INSERT INTO [sAssessment].[tCCESubjectActivityMaster]
			   (
			    [Id]
			   ,[ClassSubjectId]
			   ,[Number]
			   ,[Code]
			   ,[Title]
			   ,[OrgId]
			   ,[IsObsolete]
			   ,[OrderIndex]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[GradeSetId]
			   )
		Select @lNextNumber,@lClassSubjectId,@lNumber+1,SA.Code,SA.Title,SA.OrgId,SA.IsObsolete,@lOrderIndex+1,SA.UpdatedUserId,sCommon.fGetDate(),SA.GradeSetId
				from sAssessment.tCCESubjectActivityMaster SA
				INNER JOIN #temp t on t.ActivityId = SA.Id 
				Where  t.Id=@lCount
				 EXEC sAssessment.pCSSubjectSubActivityCopy  @lNextNumber,@rOrgId,@rClassId,@rSubjectId,@rToClassId,@lId
				set @lcount=@lcount-1
		END
		 
		SELECT 1 AS Result 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSSubjectActivityDelete]
@rId bigint
AS
BEGIN 
	--IF EXISTS (SELECT CCECSId FROM sAssessment.tCCECSIndicatorMaster FI
	--		INNER JOIN sAssessment.tCCECSMaster FM ON FI.CCECSId=FM.Id AND FM.CCECAGroupId = @rId)	
	--  BEGIN	
	--	SELECT -101 AS RESULT
	--   END
	--ELSE IF EXISTS (SELECT Id FROM sAssessment.tCCECSClass WHERE CCECSGroupId = @rId)  
	--  BEGIN
	--	SELECT -101 AS RESULT
	--  END	 
	--ELSE
	--	BEGIN
			DELETE	FROM sAssessment.tCCESubjectSubActivityMaster WHERE SubjectActivityId=@rId		
			DELETE FROM sAssessment.tCCESubjectActivityMaster WHERE Id = @rId	
			SELECT 1 AS RESULT			
		--END
 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSSubjectActivityGet] 
          
           --@rId bigint,
          
           @rOrgId int,
           @rClassId int,
           @rClassSubjectId int 
          
AS
SET NOCOUNT ON

		 

BEGIN
SELECT SAM.Id AS Id
	  ,SAM.Title AS Title
	  ,SAM.Code AS Code,
	  SAM.ClassSubjectId
	  ,SAM.Number AS Number,
	   CM.Title AS ClassName,
	   SM.Title AS SubjectName
	   
	  ,SAM.OrderIndex  
      ,SAM.IsObsolete  
     
  FROM sAssessment.tCCESubjectActivityMaster SAM INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
  INNER JOIN sSetup.tClassMaster CM ON CM.Id=CS.ClassId
  INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
       
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	 
	 SAM.OrgId = @rOrgId
	AND ((CS.ClassId=@rClassId)OR (@rClassId=0))
	AND ((CS.ClassSubjectId=@rClassSubjectId) OR(@rClassSubjectId=0))
	Order By SAM.OrderIndex ASC
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSSubjectActivityIndicatorAdd]
	 
	        @rId int,
	        @rCCESubjectSubActivityId int
	       ,@rTitle nvarchar(200) 
	       ,@rGradeSetDetailId int
           ,@rOrgId smallint
           ,@rOrderIndex smallint,
			@rCreatedUserId bigint=0 ,
			@rNumber smallint =0,
           @rUpdatedUserId bigint=0           
            
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tCCESubjectSubActivityIndicatorMaster where Title=@rTitle AND OrgId=@rOrgId AND CCESubjectSubActivityId = @rCCESubjectSubActivityId )
			BEGIN
			select -102 as Result
			RETURN
		END 
	
	--	If Exists(select Id from sAssessment.tCCESubjectActivityMaster where Title=@rTitle AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
		
	--	If Exists(select Id from sAssessment.tCCESubjectActivityMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId)
	--		BEGIN
	--		select -104 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
	--	If Exists(select Id from sAssessment.tCCESubjectActivityMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -102 as Result
	--		RETURN
	--	End
	--	If  Exists(select Id from sAssessment.tCCESubjectActivityMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End
	--	If  Exists(select Id from sAssessment.tCCESubjectActivityMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -104 as Result
	--		RETURN
	--	End
		

	 END
	  
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCESubjectSubActivityIndicatorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tCCESubjectSubActivityIndicatorMaster]
			   (
			    [Id]
			   ,[CCESubjectSubActivityId]
			   ,Title
			   ,GradeSetDetailId
			   ,OrgId
			   ,[OrderIndex],
			    Number,
				CreatedUserId,
				CreatedDateTime 
			 
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCCESubjectSubActivityId
			   ,@rTitle,
				@rGradeSetDetailId
			  
			   ,@rOrgId
			 
			   ,@rOrderIndex,
			   @rNumber
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()			
				 	   
			   )
		    SELECT @lNextNumber AS Result
      
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAssessment.tCCESubjectSubActivityIndicatorMaster
	    SET
			CCESubjectSubActivityId= @rCCESubjectSubActivityId,
			  Title=@rTitle
			 ,GradeSetDetailId=@rGradeSetDetailId
			 
	         ,OrderIndex=@rOrderIndex,
	         Number=@rNumber 
	          
             ,[UpdatedUserId] = @rUpdatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
	 
	 END  	

	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pCSSubjectActivityIndicatorGet]
		 @rCCESubjectSubActivityId int,
	 @rOrgId smallint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			

BEGIN 		
		
	SELECT
			AIM.Id,
			AIM.Title,
			SSA.Id AS SubActivityId,
			AIM.OrgId,
		 
			 
			AIm.OrderIndex,
			AIM.GradeSetDetailId,
			SAM.GradeSetId,
			ISNULL(AIM.Number,0) AS Number 
			 
			
			
			
  FROM 
			sAssessment.tCCESubjectSubActivityIndicatorMaster AIM
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SSA.Id=AIM.CCESubjectSubActivityId
			INNER  JOIN	sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSA.SubjectActivityId  
			
			 
	
WHERE 
			 
			 ((SSA.Id=@rCCESubjectSubActivityId ) or (@rCCESubjectSubActivityId=0))
			 AND	AIm.OrgId=@rOrgId	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSSubjectSubActivityAdd]
	 
	        @rId int
           ,@rSubjectActivityId int
            ,@rCode nvarchar(100)
           ,@rNumber smallint
           ,@rTitle nvarchar(200),
           @rIsObsolete bit 
		   ,@rOrderIndex int,
		   @rOrgId smallint		  
		   ,@rUpdatedUserId bigint 
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCESubjectSubActivityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAssessment.tCCESubjectSubActivityMaster
			   (
			    [Id]
			   ,[SubjectActivityId]
			   ,[Number]
			   ,[Code] 
			   ,[Title]
			   ,[IsObsolete],
			   [OrgId]
			   
			   ,[OrderIndex]			 
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			    
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rSubjectActivityId
			    ,@rNumber
				,@rCode
			   ,@rTitle,
			    @rIsObsolete,
			    @rOrgId
			  
			   ,@rOrderIndex
			 
			   ,@rUpdatedUserId
			  	   ,sCommon.fGetDate()
			    
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAssessment.tCCESubjectSubActivityMaster
	    SET
			 
	          SubjectActivityId=@rSubjectActivityId
	          ,Title = @rTitle
	       
	          ,Code=@rCode
	         ,Number=@rNumber
			 ,OrderIndex=@rOrderIndex,
			 IsObsolete= @rIsObsolete
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSSubjectSubActivityCopy]
	 
	         
            @rSubjectActivityId int,
		   @rOrgId smallint,
		   @rClassId int,
		   @rSubjectId int,
		   @rToClassId int,
		   @rActivity int
		    
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT ,@lClassSubjectId int,@lCount int
	 
	 create table #temp_Data
	 (
		Id int identity,
		ActivityId int,
		MainActivity int
	 )
	 Insert into #temp_Data
	 (
		ActivityId,
		MainActivity
	 )
	 
	 Select SSA.Id,SA.Id from sAssessment.tCCESubjectSubActivityMaster SSA INNER JOIN sAssessment.tCCESubjectActivityMaster SA oN SA.Id=SSA.SubjectActivityId
			 INNER JOIN sSetup.tClassSubject CS ON CS.Id=SA.ClassSubjectID
			Where ClassId=@rClassId AND SSA.OrgId=@rOrgId AND CS.SubjectId = @rSubjectId  
	select @lcount=count(id) from #temp_Data
 
	  --Select @lClassSubjectId = Id  from sSetup.tClassSubject where SubjectId = @rSubjectId AND ClassId=@rToClassId
	 while(@lCount>0)
	 BEGIN
	 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCESubjectSubActivityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sAssessment.tCCESubjectSubActivityMaster
			   (
			    [Id]
			   ,[SubjectActivityId]
			   ,[Number]
			   ,[Code] 
			   ,[Title]
			   ,[IsObsolete],
			   [OrgId]
			   
			   ,[OrderIndex]			 
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			    
			   )
		 Select @lNextNumber,@rSubjectActivityId,SSA.Number,SSA.Code,SSA.Title,SSA.IsObsolete,@rOrgId,SSA.OrderIndex,SSA.UpdatedUserId,sCommon.fGetDate()
		 from sAssessment.tCCESubjectSubActivityMaster SSA INNER JOIN #temp_Data t on t.ActivityId=SSA.Id
			Where  t.id=@lCount AND T.MainActivity=@rActivity
			set @lcount=@lCount-1
		END     
		--COMMIT TRANSACTION         
		drop table #temp_Data
COMMIT TRANSACTION		
 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pCSSubjectSubActivityDetailGet]
	 @rCCESubjectActivityId int,
	 @rOrgId smallint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT
			 SAM.Id,
			SAM.Code As Code,
			[sCommon].[fXMLTagsReplaceReverse](SAM.Title) AS Title,
			SAM.Number AS Number,
			
			SAM.OrderIndex AS OrderIndex,
			SAM.IsObsolete AS IsObsolete,
			isnull(SSA.Id,0) AS SubActivityId,
			isnull(SSA.SubjectActivityId,0) AS SubjectActivityId,
			 
			Isnull(SSA.TITLE,'') AS SubActivityTitle,
			 isnull(SSA.Code,'') AS SubActivityCode,
			isnull(SSA.Number,'') AS SubActivityNumber,
			SAM.GradeSetId,
			SAM.ClassSubjectId,
			isnull(SSA.IsObsolete,0) AS SubActivityIsObsolete,
			Isnull(SSA.OrderIndex,0) AS SubActivityOrderIndex,
			isnull(SAM.OrgId,0) AS SAMORGID,
			SSA.OrgID AS SSAORGID ,
			CS.ClassId,
			ISNULL(SAM.Remark,'') AS Remark --add for mantis : 0038981
			 
			
  FROM 
			sAssessment.tCCESubjectActivityMaster SAM
			Left JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SSA.SubjectActivityId=SAM.Id  AND SSA.OrgId=@rOrgId 
			 INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAm.ClassSubjectId
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id= CS.ClassID
WHERE 
			((SAM.Id=@rCCESubjectActivityId) OR (@rCCESubjectActivityId=0)) 
			 AND  SAM.OrgId=@rOrgId 
			
			
		 
			order by SAM.OrderIndex ASC,SSA.OrderIndex ASC
			
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pDashboardMarkEntryAllSubjectCountGet]
	 
	 @rExamId int,
	 @rBatchId int,
	 @rClassId int=0,
	 @rDivisionId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  distinct ',' +   QUOTENAME(CS.SubjectCode) 
					  From  
					   sSetup.vExamSubject CS  
					   INNER JOIN sAssessment.tExamMaster E ON E.Id=CS.ExamId AND E.ExamSubGroupId =  @rExamId 
					   INNER JOIN sSetup.tClassMaster CL on CL.Id=CS.ClassId
					   INNER JOIN sSetup.tDivisionMaster CM ON CM.ClassId=CL.Id
					    WHere ((CM.ClassId =@rClassID) OR (@rClassId=0)) AND ((CM.Id=@rDivisionId) OR (@rDivisionId=0))
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
 
set @query = 'SELECT  ClassId,DivisionId,ClassName,ExamId,StudentCount,Status,

 ' + @cols + '
FROM
(
Select   CM.Id As ClassId,DM.Id as DivisionId,CM.Title+'' ''+DM.Title ClassName,Count(A.AcademicId) AS AcademicId,ED.ExamId, SM.Code as ExamDetailId,

(Select Count(AcademicId) from sStudent.vStudentAcademic A WHERE A.StatusId=1 AND A.BatchId='+ CONVERT(nvarchar(10),@rBatchId) +'
AND A.ClassId= CM.Id AND A.DivisionId = DM.Id) AS StudentCount,

(Select ISNULL(SM.Title,''Process Schedule'') AS Title  From sAssessment.tExamMaster EM LEFT JOIN sAssessment.tExamStatus ES ON ES.ExamId = ED.ExamId 
LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=ES.StatusID Where EM.ClassId = CM.Id AND ISProcessREsult = 1 
AND EM.BatchId='+ CONVERT(nvarchar(10),@rBatchId) +' AND EM.ExamSubGroupId='+ CONVERT(nvarchar(10),@rExamId) +'AND ES.DivisionID = DM.Id) AS Status

FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id 
 
WHERE A.StatusId =1 AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) +' And  EM.ExamSubGroupId = ' + convert(nvarchar(15),@rExamId) + 'AND ISNULL(RD.Obtain,0)>0 AND ((A.ClassId='+convert(nvarchar(15),@rClassId)+') OR (' +convert(nvarchar(15),@rClassId) + '=0)) AND ((A.DivisionId='+Convert(nvarchar(15),@rDivisionId)+') OR ('+Convert(nvarchar(15),@rDivisionId)+'=0))
Group By ED.ExamId,Ed.Id,CM.Title,DM.TItle,Cm.Id,Dm.Id,SM.Code) 
MAIN
PIVOT
(
	MAX(AcademicId )
FOR ExamDetailId IN (' + @cols + ')
)pvt '

--print (@query)
execute(@query)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pDashboardStudentPercAnalysisSubjectWise]
	 
	 @rOrgId int,
	 @rClassId int=0,
	 @rExamSubGroupId int=0,
	 @rBatchId int,
	 @rStatusId int = 0,
	 @rGroupId int 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lCount int
DECLARE @lMarkRange nvarchar(50)
DECLARE @lAnalysisGradeSetId int
DECLARE @lMinimumScore decimal(5,2)
DECLARE @cols NVARCHAR(MAX),@query NVARCHAR(MAX);

BEGIN

SELECT @lAnalysisGradeSetId = ISNULL(AnalysisGradeSetId,0) From sAssessment.tConfiguration Where OrgId = @rOrgId

    CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		MarkRange nvarchar(50),
		GradeSetId int				 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,MarkRange,GradeSetId		
	FROM   sAssessment.tGradeSetDetail 
	WHERE  GradesetId=@lAnalysisGradeSetId
	ORDER BY MinimumScore DESC
	
	--Select * from #tempGradeSetDetail return
	
	CREATE TABLE #tempMarkUpdate
	(
		Id INT IDENTITY (1, 1),
		ResultDetailId bigint,
		ObtainedMarks decimal(5,2),
		MarkRange nvarchar(50)				 
	) 
	
	INSERT INTO #tempMarkUpdate (ResultDetailId,ObtainedMarks)
	SELECT RD.Id, (SELECT RD.Obtain * 100 / ED.Maximum) AS ObtainedMarks	
	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 sStudent.tAcademic A ON A.Id = R.AcademicId
		   INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId 
	WHERE  A.BatchId = @rBatchId AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId
		   AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
		   AND ((CS.ClassId = @rClassId) OR (@rClassId = 0))
		  
	--Select * from #tempMarkUpdate return

	SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
	WHILE (@lCount > 0)
	BEGIN
		SELECT
			  @lMarkRange = MarkRange,
			  @lMinimumScore = MinimumScore
		FROM 
			  #tempGradeSetDetail WHERE Id = @lCount
			
		UPDATE T SET T.MarkRange=@lMarkRange 
	    FROM   #tempMarkUpdate T
			   INNER JOIN sAssessment.tResultDetail RD ON RD.Id = T.ResultDetailId 
			   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 = R.ExamId
			   INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = R.AcademicId
			   INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		WHERE  T.ObtainedMarks >= @lMinimumScore 
		       AND EM.ExamSubGroupId = @rExamSubGroupId
		       AND A.BatchId = @rBatchId
		       AND EM.BatchId = @rBatchId
		       AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
		       AND ((CS.ClassId = @rClassId) OR (@rClassId = 0))
		SET @lCount = @lCount - 1
    END	
    
    --Select * from #tempMarkUpdate return
    
    SET @cols = STUFF(
			   (SELECT ',' +  QUOTENAME(T.MarkRange)
				FROM 
					 #tempGradeSetDetail T
					 INNER JOIN sAssessment.tGradeSetMaster GSM ON GSM.Id = T.GradeSetId
					 INNER JOIN sAssessment.tGradeSetDetail GSD ON GSD.GradeSetId = GSM.Id
				GROUP BY 
					 T.MarkRange
				ORDER BY 
					 T.MarkRange DESC
				FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
				,1,1,'')	

	 set @query = 'SELECT GroupId,GroupName,GroupTitle,SubjectId,SubjectName,' + @cols + ' FROM
				(
				 SELECT
				 CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.Id WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.ClassId END AS GroupId,
		         CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.Code WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.ClassName END AS GroupName,
		         CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.OrderIndex WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.OrderIndex END AS OrderIndex,
		         CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN '+ '''Class/Division''' +' WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN '+'''Class'''+' END AS GroupTitle,
		         COUNT(R.AcademicId) AS StudentCount,T.MarkRange,
		         SM.Id AS SubjectId, SM.Title AS SubjectName
				 FROM 
				 #tempMarkUpdate T
				 INNER JOIN sAssessment.tResultDetail RD ON RD.Id = T.ResultDetailId
				 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 sStudent.vStudentAcademic A ON A.AcademicId = R.AcademicId
				 INNER JOIN ssetup.tDivisionMaster DM ON DM.Id = A.DivisionId
				 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
				 INNER JOIN  sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId 
				 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId 
				 WHERE ((CM.ClassId='+CONVERT(nvarchar(20),@rClassId)+') OR ('+CONVERT(nvarchar(20),@rClassId)+'=0))
				 AND A.BatchId ='+CONVERT(nvarchar(20),@rBatchId)+'
				 AND EM.BatchId ='+CONVERT(nvarchar(20),@rBatchId)+'
				 AND CM.BatchId ='+CONVERT(nvarchar(20),@rBatchId)+'
				 AND EM.ExamSubGroupId ='+CONVERT(nvarchar(20),@rExamSubGroupId)+'
				 GROUP BY T.MarkRange,
				 CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.Id WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.ClassId END,
				 CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.Code WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.ClassName END,
				 CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.OrderIndex WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.OrderIndex END,
				 SM.Id,SM.Title
				 ) x
				 pivot 
				 (
					SUM(StudentCount)
					for MarkRange in (' + @cols + ')
				 ) p '
   
   Execute(@query)
   
   DROP Table #tempMarkUpdate
   DROP Table #tempGradeSetDetail
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pDashboardStudentPercentageAnalysis]
	 
	 @rOrgId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rDepartmentId int = 0,
	 @rGroupId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lCount int
DECLARE @lMarkRange nvarchar(50)
DECLARE @lPercentage decimal(5,2)
DECLARE @lAnalysisGradeSetId int
DECLARE @lMinimumScore decimal(5,2)
DECLARE @cols NVARCHAR(MAX),@query NVARCHAR(MAX)

SELECT @lAnalysisGradeSetId = ISNULL(AnalysisGradeSetId,0) From sAssessment.tConfiguration Where OrgId = @rOrgId

	CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		MarkRange nvarchar(50),
		GradeSetId int				 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,MarkRange,GradeSetId		
	FROM   sAssessment.tGradeSetDetail 
	WHERE  GradesetId=@lAnalysisGradeSetId
	ORDER BY MinimumScore DESC
	
	--Select * from #tempGradeSetDetail return
	
	CREATE TABLE #tempPercentageUpdate
	(
		Id INT IDENTITY (1, 1),
		ResultId bigint,
		AcademicId bigint,
		Percentage decimal(5,2),
		MarkRange nvarchar(50)				 
	) 
	
	INSERT INTO #tempPercentageUpdate (ResultId,AcademicId,Percentage)
	SELECT R.Id,R.AcademicId,R.Percentage	
	FROM  sAssessment.tResult R 
		  INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
		  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	WHERE A.BatchId = @rBatchId AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId
	
	--Select * from #tempPercentageUpdate return
	 
    SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
	WHILE (@lCount > 0)
	
	BEGIN
		SELECT
			  @lMarkRange = MarkRange,
			  @lMinimumScore = MinimumScore
		FROM 
			  #tempGradeSetDetail WHERE Id = @lCount
			
			
		UPDATE T SET T.MarkRange=@lMarkRange 
	    FROM   #tempPercentageUpdate T
			   INNER JOIN sAssessment.tResult R ON R.Id = T.ResultId
			   INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			   INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = T.AcademicId
			   INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE  R.Percentage >= @lMinimumScore 
		       AND EM.ExamSubGroupId = @rExamSubGroupId
		       AND A.BatchId = @rBatchId
		       AND EM.BatchId = @rBatchId
		       AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
		       AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		       AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId =0))
		SET @lCount = @lCount - 1
    END	
	
   --Select * from #tempPercentageUpdate return
	
	SET @cols = STUFF(
           (SELECT ',' +  QUOTENAME(T.MarkRange)
			FROM 
				 #tempGradeSetDetail T
				 INNER JOIN sAssessment.tGradeSetMaster GSM ON GSM.Id = T.GradeSetId
				 INNER JOIN sAssessment.tGradeSetDetail GSD ON GSD.GradeSetId = GSM.Id
			GROUP BY 
				 T.MarkRange
			ORDER BY 
				 T.MarkRange DESC
			FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
			
   set @query = 'SELECT GroupId,GroupName,GroupTitle,' + @cols + ' FROM
				(
				 SELECT
				 CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.Id WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.ClassId WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=3 THEN Dept.Id WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=4 THEN OM.Id END AS GroupId,
		         CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.Code WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.ClassName WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=3 THEN Dept.Title WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=4 THEN OM.Title END AS GroupName,
		         CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.OrderIndex WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.OrderIndex WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=3 THEN Dept.Id WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=4 THEN OM.OrderIndex END AS OrderIndex,
		         CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN '+ '''Class/Division''' +' WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN '+'''Class'''+' WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=3 THEN '+'''Department'''+' WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=4 THEN '+'''Organization'''+' END AS GroupTitle,
		         COUNT(T.AcademicId) AS StudentCount, MarkRange
				 FROM 
				 #tempPercentageUpdate T
		         INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = T.AcademicId
				 INNER JOIN ssetup.tDivisionMaster DM ON DM.Id = A.DivisionId
				 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
				 INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
				 INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
				 WHERE ((DM.ID='+CONVERT(nvarchar(20),@rDivisionId)+') OR ('+CONVERT(nvarchar(20),@rDivisionId)+'=0))
				 AND ((CM.ClassId='+CONVERT(nvarchar(20),@rClassId)+') or ('+CONVERT(nvarchar(20),@rClassId)+'=0))
				 AND CM.BatchId='+CONVERT(nvarchar(20),@rBatchId)+'
				 AND EM.BatchId ='+CONVERT(nvarchar(20),@rBatchId)+'
				 AND EM.ExamSubGroupId ='+CONVERT(nvarchar(20),@rExamSubGroupId)+'
				 AND ((CM.DepartmentId = '+CONVERT(nvarchar(20),@rDepartmentId)+') OR ('+CONVERT(nvarchar(20),@rDepartmentId)+' =0))
				 GROUP BY MarkRange,
				 CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.Id WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.ClassId WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=3 THEN Dept.Id WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=4 THEN OM.Id END,
				 CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.Code WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.ClassName WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=3 THEN Dept.Title WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=4 THEN OM.Title END,
				 CASE WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=1 THEN DM.OrderIndex WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=2 THEN CM.OrderIndex WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=3 THEN Dept.Id WHEN '+CONVERT(nvarchar(20),@rGroupId)+'=4 THEN OM.OrderIndex END
				 ) x
				 pivot 
				 (
					SUM(StudentCount)
					for MarkRange in (' + @cols + ')
				 ) p '
   
   Execute(@query)
   
   DROP Table #tempPercentageUpdate
   DROP Table #tempGradeSetDetail
	
	
	--DECLARE  @TempFields TABLE
	--(
	--	MarkRange nvarchar(20),
	--	StudentCount int,
	--	GroupId int,
	--	GroupName nvarchar(75),
	--	GroupTitle nvarchar(75),
	--	OrderIndex int
	--)

   --SELECT * from @TempFields
   
   --DROP Table @TempFields
	--MarkRange,OM.Id,OM.Title,OM.OrderIndex,Dept.Id,Dept.Title,CM.ClassId,CM.ClassName,CM.OrderIndex,DM.Id,
	--DM.DisplayTitle,DM.OrderIndex
	
	--DROP Table @TempFields
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamCombine_AddGet]
	 @rClassId int
	,@rExamId int
	,@rExamSubGroupId int
	,@rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	SELECT 
	0 AS ExamCombineId,
    'false' AS CombineSelected,
	EM.Id AS SubExamId ,
	ESGM.Title AS ExamName,
	EGM.Title AS ExamGroupName,
	0 AS Weightage,
	0 AS ExamOrder
 FROM 
			[sAssessment].[tExamMaster] EM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN [sAssessment].[tExamSubGroupMaster] ESGM ON ESGM.ID = EM.ExamSubGroupId
			INNER JOIN [sAssessment].[tExamGroupMaster] EGM ON EGM.ID = ESGM.EXAMGROUPID 
		--	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
			AND EM.BatchId = @rBatchId
ORDER BY   CASE WHEN ESGM.Id = @rExamSubGroupId THEN 0 ELSE 1 END,EGM.Title ASC,ESGM.Title ASC		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pExamCombineAdd]
	 
	        @rId int
           ,@rExamId int
		   ,@rSubExamId int
		   ,@rWeightage decimal(5,2)
		   ,@rExamOrder Smallint
		   ,@rCreatedUserId bigint
		   ,@rOrgId int
		   ,@rIsObsolete bit
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
IF NOT EXISTS (SELECT 1 FROM [sAssessment].[tExamCombine] WHERE ExamId = @rExamId AND SubExamId = @rSubExamId)
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamCombine', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tExamCombine]
			   (
			    [Id]
			   ,ExamId 
			   ,SubExamId 
			   ,Weightage 
			   ,ExamOrder
			   ,CreatedUserId
			   ,CreatedDateTime
			   ,UpdatedUserId
			   ,UpdatedDateTime
			   
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rExamId 
			   ,@rSubExamId 
			   ,@rWeightage 
			   ,@rExamOrder
			   ,@rCreatedUserId 
			   ,sCommon.fGetDate() 
			   ,0
			   ,sCommon.fGetDate() 
			   )
			   
			   END
		    SELECT 1 AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE IF (@rIsObsolete = 0 AND @rId > 0)
	 BEGIN
	 --IF EXISTS (SELECT * FROM sAssessment.tExamCombine EC INNER JOIN sAssessment.tResult R ON R.ExamId = EC.SubExamId AND EC.ExamId = @rExamId) 
		--AND @rIsObsolete = 1
		--BEGIN
			SET @lNextNumber = @rId
			UPDATE  [sAssessment].[tExamCombine]
			SET	    Weightage=@rWeightage 
				   ,ExamOrder=@rExamOrder
				   ,UpdatedUserId=@rCreatedUserId
				   ,UpdatedDateTime=sCommon.fGetDate() 
			  WHERE Id = @rId 	   
			  SELECT 1 AS Result  
		--END
	 --ELSE IF @rIsObsolete = 1 
		-- BEGIN
		-- SET @lNextNumber = @rId
		--	UPDATE  [sAssessment].[tExamCombine]
		--	SET
		--			ExamId =@rExamId 
		--		   ,SubExamId =@rSubExamId 
		--		   ,Weightage=@rWeightage 
		--		   ,ExamOrder=@rExamOrder
		--		   ,UpdatedUserId=@rCreatedUserId
		--		   ,UpdatedDateTime=sCommon.fGetDate() 
		--	  WHERE Id = @rId 	   
		--	  SELECT @lNextNumber AS Result
		  END
ELSE IF (@rIsObsolete = 1 AND @rId > 0)
		BEGIN
			DELETE FROM [sAssessment].[tExamCombine] WHERE ID = @rId
			SELECT @rId AS Result
		END		  
   --END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamCombineFullGet]
	 @rId int,
	 @rClassId int,
	 @rExamGroupId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	SELECT 
	CASE WHEN ISNULL(EC.Id,0) <> 0 AND EC.ExamId = @rId THEN ISNULL(EC.Id,0) ELSE 0 END AS ExamCombineId, 
	ISNULL(EM.Id,0) AS SubExamId,
	CASE WHEN ISNULL(Weightage,0) <> 0 AND EC.ExamId = @rId THEN ISNULL(Weightage,0) ELSE 0 END AS Weightage, 
	CASE WHEN ISNULL(ExamOrder,0) <> 0 AND EC.ExamId = @rId THEN ISNULL(ExamOrder,0) ELSE 0 END AS ExamOrder, 
	ESGM.Title AS ExamName,
	EGM.Title AS ExamGroupName,
	CASE WHEN ISNULL(EC.Id,0) <> 0 AND EC.ExamId = @rId THEN 'true' ELSE 'false' END AS CombineSelected
	
FROM  		[sAssessment].[tExamMaster] EM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId
			LEFT JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId = @rId
			LEFT JOIN [sAssessment].[tExamGroupMaster] EGM ON EGM.ID = ESGM.ExamGroupId
 
WHERE		(EM.Id <> @rId OR @rId = 0 ) AND
			(CM.Id=@rClassId OR @rClassId = 0)
			AND EM.BatchId = @rBatchId

ORDER BY CASE WHEN EGM.Id = @rExamGroupId THEN 0 ELSE 1 END,EGM.Title ASC,ESGM.Title ASC	
  --(EM.Id <> @rId Or @rId=0) AND
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamCombineMarkEntryExcludeAbsentGet]
	
	 @rExamId int,
	 @rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

IF EXISTS (SELECT ID from sAssessment.tExamCombine where ExamId = @rExamId)
BEGIN
select  
(case WHEN A.Maxi = 0 then 0
else
ISNULL((A.Obtain*ED.Maximum)/A.Maxi,0) END) AS Obtain,


@rAcademicId AS AcademicId,
ED.Id AS ExamDetailID,
ED.ExamId,
CONVERT(bit, 1) AS  IsPresent
--ISNULL((select IsPresent from sAssessment.tResultDetail rd1 
--		   inner join sAssessment.tResult r1 on r1.Id=rd1.ResultId and r1.ExamId=@rExamId and r1.AcademicId=@rAcademicId
--		   and rd1.ExamDetailId=ED.Id ),0)  AS IsPresent

from
(SELECT
	CASE WHEN   ECS.ExamId IS nULL THEN
		Sum(Obtain*weightage/100)  
	ELSE
		Sum(Obtain*Subjectweightage/100)
	END AS Obtain,
	CASE WHEN ECS.ExamId IS nULL THEN
		Sum(Maximum*weightage/100)  
	ELSE
		Sum(Maximum*Subjectweightage/100)
		END AS Maxi,
		RM.AcademicId,
		ED.ClassSubjectId
FROM sAssessment.tResult RM 
	INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id
	INNER JOIN sAssessment.tExamCombine EC ON ED.ExamId=EC.SubExamId
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  	
	LEFT JOIN sAssessment.tExamCombineSubject ECS ON ECS.ExamId  = EC.ExamId AND ECS.SubExamId = EC.SubExamId AND ECS.ClassSubjectId = ED.ClassSubjectId 	
	
	WHERE EC.ExamId=@rExamId 
	AND RD.IsPresent = 1
	
GROUP BY RM.AcademicId,ED.ClassSubjectId,ECS.ExamId  having RM.AcademicId=@rAcademicId) AS A
INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId=A.ClassSubjectId
Where ED.ExamId =@rExamId
END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pExamCombineMarkEntryGet]
	
	 @rExamId int,
	 @rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

IF EXISTS (SELECT ID from sAssessment.tExamCombine where ExamId = @rExamId)
BEGIN
select  
(case WHEN A.Maxi = 0 then 0
else
ISNULL((A.Obtain*ED.Maximum)/A.Maxi,0) END) AS Obtain,


@rAcademicId AS AcademicId,
ED.Id AS ExamDetailID,
ED.ExamId,
--CONVERT(bit, 1) AS  IsPresent

-- Edited By Kundan
-- Uncomment code due to at Time of Result generate 
-- Absent Student status auto update as Present cause default present status pass 1 (as above comment)
case when
(select IsPresent from sAssessment.tResultDetail rd1 
		   inner join sAssessment.tResult r1 on r1.Id=rd1.ResultId and r1.ExamId=@rExamId and r1.AcademicId=@rAcademicId
		   and rd1.ExamDetailId=ED.Id) is null then CONVERT(bit, 1) else (select IsPresent from sAssessment.tResultDetail rd1 
		   inner join sAssessment.tResult r1 on r1.Id=rd1.ResultId and r1.ExamId=@rExamId and r1.AcademicId=@rAcademicId
		   and rd1.ExamDetailId=ED.Id)  end AS IsPresent

from
(

SELECT 
	CASE WHEN ECS.ExamId IS nULL THEN
		Sum(Obtain*weightage/100) 
	ELSE
		Sum(Obtain*Subjectweightage/100) 
	END  AS Obtain,
	CASE WHEN ECS.ExamId IS nULL THEN
		Sum(Maximum*weightage/100) 
	ELSE
		Sum(Maximum*Subjectweightage/100) 
	END	AS Maxi,
	
RM.AcademicId,ED.ClassSubjectId
FROM sAssessment.tResult RM 
	INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id 
	and RM.ExamId = ED.ExamId -- added on 21-03-2023 to avoid unrelated data by rajendra
	INNER JOIN sAssessment.tExamCombine EC ON ED.ExamId=EC.SubExamId
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  	
    LEFT JOIN sAssessment.tExamCombineSubject ECS ON ECS.ExamId  = EC.ExamId 
    AND ECS.SubExamId = EC.SubExamId AND ECS.ClassSubjectId = ED.ClassSubjectId AND ECS.Subjectweightage > 0     
	WHERE EC.ExamId=@rExamId 
	
GROUP BY RM.AcademicId,ED.ClassSubjectId,ECS.ExamId having RM.AcademicId=@rAcademicId

) AS A
INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId=A.ClassSubjectId
Where ED.ExamId =@rExamId
END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamCombineSubjectAdd]
	 @rExamId int,
	 @rSubExamId int,
	 @rClassSubjectId int,
	 @rSubjectWeightage decimal(5,2)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	if exists(Select 1 from sAssessment.tExamCombineSubject where SubExamId =@rSubExamId AND ClassSubjectId =@rClassSubjectId)
	BEGIN
		Update sAssessment.tExamCombineSubject set SubjectWeightage = @rSubjectWeightage where SubExamId =@rSubExamId AND ClassSubjectId =@rClassSubjectId
	END
	ELSE
	BEGIN
	INSERT INTO sAssessment.tExamCombineSubject
	(
		ExamId,
		SubExamId,
		ClassSubjectId,
		SubjectWeightage
	)			
	Values
	(
		@rExamId,
		@rSubExamId,
		@rClassSubjectId,
		@rSubjectWeightage
	)
	Select 1 As Result
	END
	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamCombineSubjectFullGet]
@rClassId int,
@rExamId int,
@rSubExamId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		 ES.SubjectWeightage  AS Weightage,
		EM.Id AS ExamId,
		CS.Id AS ClassSubjectId,
		SM.Title AS SubjectName,
		@rSubExamId As SubexamId
	from
		[sAssessment].[tExamMaster] EM 
		INNER JOIN sSetup.tClassSubject CS ON EM.ClassId = CS.ClassId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		LEFT JOIN sAssessment.tExamCombineSubject ES ON ES.ClassSubjectId = CS.Id AND ES.SubExamId=@rSubExamId 
	WHERE CS.ClassId = @rClassId AND EM.Id = @rExamId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamCombineSubjectWightFullGet]
@rClassId int,
@rExamId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
    select @cols = STUFF((SELECT ',' + QUOTENAME(EM.Id) 
                    from sAssessment.tExamCombine EC INNER JOIN sAssessment.tExamMaster EM ON   EC.SubExamId=EM.Id AND EC.ExamId = @rExamId
                    INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query = 'SELECT ClassSubjectId,SubjectName,' + @cols + ' from 
             (
               Select
                 ISnull(ES.SubjectWeightage,0) AS SubjectWeightage ,VS.SubjectName ,VS.ClassSubjectId,isnull(EM.Id,0) AS ExamId,isnull(ES.SubExamId,0) AS SubExamId
               FROM sAssessment.tExamMaster EM 
               INNER JOIN sSetup.vExamSubject  VS ON  EM.Id=Vs.ExamId
		      LEFT JOIN sAssessment.tExamCombineSubject ES ON ES.ClassSubjectId = VS.ClassSubjectId 
		      WHERE
	         EM.ClassId=' + CAST(@rClassId AS NVARCHAR(30))+'
             AND EM.ID='+ CAST(@rExamId  as Nvarchar(30))+'
              ) x
            pivot 
            (
               MAx(SubjectWeightage)  
                for SubExamId in (' + @cols + ')
            ) p '
            
--print @query
if(isnull(@query,'')='')
 BEGIN
 SELECT  -102 
 RETURN
 ENd
 execute(@query)
END

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

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


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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pExamFullDetailGet]
	 @rId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	SELECT 
	EM.Id,
	EM.BatchId,
	ESGM.Code,
	ESGM.Title AS Name,
	ESGM.Id AS ExamGRoupId,
	EM.ClassId,
	EM.IsRankNo,
	EM.IsGrade,
	EM.IsPercentile,
	EM.IsPercentage,
	EM.IsSubjectPercentile,
	ISNULL(EM.GradeSetId,0) AS GradeSetId,
	ISNULL(EM.RankSetId,0) AS RankSetId,
	ISNULL(EM.LevelSetId,0) AS LevelSetId ,
	CASE WHEN ISNULL(IsProcessResult,0) = 0 THEN 'false' ELSE 'true' END AS IsProcessResult,
	CASE WHEN IsNull(IsMarksInDecimal,0) = 0 THEN 'false' ELSE 'true' END AS IsMarksInDecimal,
	CASE WHEN ISNULL(ISNegativeMarks,0)=0 THEN 'false' ELSE 'true' END AS ISNegativeMarks,
	Isnull(ED.Id,0) as ExamDetailId,
	ISNULL(ED.GradeSetId,0) as GradeSetDetailId,
	ISNULL(ED.ExamId,0) as ExamId,
	ISNULL(CS.Id,0) as ClassSubjectId,
	ISNULL(ED.Maximum,0) as Maximum,
	ISNULL(ED.Minimum,0) as Minimum,
	ISNULL(ED.IsIncludeInTotal,0) as IsIncludeInTotal,
	ISNULL(ED.IsDisplayInMarksheet,0) as IsDisplayInMarksheet,
	ISNULL(ED.IsShowSubjectGrade,0) as IsShowSubjectGrade,
	ISNULL(ED.IsShowSubjectMark,1) as IsShowSubjectMark,
	
	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	ISNULL(ED.ExamTime,'') as ExamTime,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	GSM.Title as GradeSET,
	EGM.Title as ExamGroup,
	ESGM.Title as ExamName,
	SM.Title as SubjectName,
	CM.DisplayTitle as ClassName,
	
	CASE WHEN ISNULL(IsOnPrePrinted,0) = 0 THEN 'false' ELSE 'true' END AS IsOnPrePrinted,
	CASE WHEN ISNULL(IsDisplayBirthDate,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayBirthDate,
	CASE WHEN ISNULL(IsDisplayPhoto,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayPhoto,
	CASE WHEN ISNULL(IsDisplaySchoolName,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplaySchoolName,
	CASE WHEN ISNULL(IsLockForEdit,0) = 0 THEN 'false' ELSE 'true' END AS IsLockForEdit,
	CASE WHEN ISNULL(IsIncludeCoScholastic,0) = 0 THEN 'false' ELSE 'true' END AS IsIncludeCoScholastic,
	CASE WHEN ISNULL(IsCoScholasticGrade,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGrade,
	CASE WHEN ISNULL(IsCoScholasticGradeIndicator,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGradeIndicator,
	CASE WHEN ISNULL(IsCoScholasticGradeDesIndicator,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGradeDesIndicator,
	
	CASE WHEN ISNULL(IsDisplayAttendance,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayAttendance,
	CASE WHEN ISNULL(IsDisplayHeightWeight,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayHeightWeight,
	CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayResultStatus,
	CASE WHEN ISNULL(IsIncludeSubExam,0) = 0 then 'false' ELSE 'true' END AS IsIncludeSubExam,
	
	CASE WHEN ISNULL(IsPublished,0) = 0 then 'false' ELSE 'true' END AS IsPublished,
	CASE WHEN ISNULL(IsDisplayHighestDivisionMark,0) = 0 then 'false' ELSE 'true' END AS IsDisplayHighestDivisionMark,
	CASE WHEN ISNULL(IsDisplayHighestDivisionGrade,0) = 0 then 'false' ELSE 'true' END AS IsDisplayHighestDivisionGrade,
	CASE WHEN ISNULL(IsDisplayGradeString,0) = 0 then 'false' ELSE 'true' END AS IsDisplayGradeString,
	
	CASE WHEN ISNULL(IsExcludeAbsentTotal,0) = 0 then 'false' ELSE 'true' END AS IsExcludeAbsentTotal,
	
	EM.Remark1,
	EM.Remark2,
	EM.Remark3,
	EM.DisplayTitle,
	ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
	ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
	ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
	ISNULL(EM.TermScopeId,0) AS TermScopeId,	
	ISNULL(EM.ReportId,0) as ReportId,
	CASE WHEN ED.ClassSubjectId=CS.Id THEN 'true' ELSE 'false' END AS Selected,
	
	ISNULL(EM.CoScholasticScopeId,0) AS CoScholasticScopeId,
	ISNULL(EM.SubjectGroupPerPage,0) AS SubjectGroupPerPage,
	CASE WHEN ISNULL(IsDisplayParentName,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayParentName,
	CASE WHEN ISNULL(IsDisplayTeacherSign,0)=0 THEN 'false' ELSE 'true' END AS IsDisplayTeacherSign,
	CASE WHEN ISNULL(IsDisplayPrincipalSign,0)=0 THEn 'false' ELSE 'true' END AS IsDisplayPrincipalSign,
	ISNULL(EM.PercentileScopeId,0) AS PercentileScopeId,
	ISNULL(EM.CoScholasticGradeSetId,0) AS CoScholasticGradeSetId ,
	ISNULL(EM.IsRemovePercentageForFail,0) AS IsFailPercentageZero,
	--CASE WHEN ISNULL(IsGenerateRankNo,0) = 0 THEN 'No' ELSE 'Yes' END AS IsGenerateRankNo
	ISNULL(EM.IsGenerateRankNo,0) as IsGenerateRankNo
	
	
	
  FROM 
			[sAssessment].[tExamMaster] EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
						
WHERE       
            EM.Id=@rId
			order by Selected Desc,DisplayOrder Asc,ESGM.Title Desc
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pExamFullGet]
	 @rId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ESGM.Id AS ExamGRoupId,
			EM.ClassId,
			EM.IsRankNo,
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			ISNULL(EM.GradeSetId,0) AS GradeSetId,
			ISNULL(EM.RankSetId,0) AS RankSetId,
			ISNULL(EM.LevelSetId,0) AS LevelSetId ,
			CASE WHEN ISNULL(IsProcessResult,0) = 0 THEN 'false' ELSE 'true' END AS IsProcessResult,
			CASE WHEN IsNull(IsMarksInDecimal,0) = 0 THEN 'false' ELSE 'true' END AS IsMarksInDecimal,
			CASE WHEN ISNULL(ISNegativeMarks,0)=0 THEN 'false' ELSE 'true' END AS ISNegativeMarks,
			Isnull(ED.Id,0) as ExamDetailId,
			ISNULL(ED.GradeSetId,0) as GradeSetDetailId,
			ISNULL(ED.ExamId,0) as ExamId,
			ISNULL(CS.Id,0) as ClassSubjectId,
			ISNULL(ED.Maximum,0) as Maximum,
			ISNULL(ED.Minimum,0) as Minimum,
			ISNULL(ED.IsIncludeInTotal,0) as IsIncludeInTotal,
			ISNULL(ED.IsDisplayInMarksheet,0) as IsDisplayInMarksheet,
			ISNULL(ED.IsShowSubjectGrade,0) as IsShowSubjectGrade,
			ISNULL(ED.IsShowSubjectMark,1) as IsShowSubjectMark,
			
			ISNULL(ED.DisplayOrder,0) as DisplayOrder,
			ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
			ISNULL(ED.ExamTime,'') as ExamTime,
			ISNULL(ED.ExamTopic,'') as ExamTopic,
			ISNULL(ED.ExamLanguage,'') as Language,
			GSM.Title as GradeSET,
			EGM.Title as ExamGroup,
			ESGM.Title as ExamName,
			SM.Title as SubjectName,
			CS.SubjectId,
			CM.DisplayTitle as ClassName,
			
			CASE WHEN ISNULL(IsOnPrePrinted,0) = 0 THEN 'false' ELSE 'true' END AS IsOnPrePrinted,
			CASE WHEN ISNULL(IsDisplayBirthDate,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayBirthDate,
			CASE WHEN ISNULL(IsDisplayPhoto,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayPhoto,
			CASE WHEN ISNULL(IsDisplaySchoolName,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplaySchoolName,
			CASE WHEN ISNULL(IsLockForEdit,0) = 0 THEN 'false' ELSE 'true' END AS IsLockForEdit,
			CASE WHEN ISNULL(IsIncludeCoScholastic,0) = 0 THEN 'false' ELSE 'true' END AS IsIncludeCoScholastic,
			CASE WHEN ISNULL(IsCoScholasticGrade,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGrade,
			CASE WHEN ISNULL(IsCoScholasticGradeIndicator,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGradeIndicator,
			CASE WHEN ISNULL(IsCoScholasticGradeDesIndicator,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGradeDesIndicator,
			
			CASE WHEN ISNULL(IsDisplayAttendance,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayAttendance,
			CASE WHEN ISNULL(IsDisplayHeightWeight,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayHeightWeight,
			CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayResultStatus,
			CASE WHEN ISNULL(IsIncludeSubExam,0) = 0 then 'false' ELSE 'true' END AS IsIncludeSubExam,
			
			CASE WHEN ISNULL(IsPublished,0) = 0 then 'false' ELSE 'true' END AS IsPublished,
			CASE WHEN ISNULL(IsDisplayHighestDivisionMark,0) = 0 then 'false' ELSE 'true' END AS IsDisplayHighestDivisionMark,
			CASE WHEN ISNULL(IsDisplayHighestDivisionGrade,0) = 0 then 'false' ELSE 'true' END AS IsDisplayHighestDivisionGrade,
			CASE WHEN ISNULL(IsDisplayGradeString,0) = 0 then 'false' ELSE 'true' END AS IsDisplayGradeString,
			
			CASE WHEN ISNULL(IsExcludeAbsentTotal,0) = 0 then 'false' ELSE 'true' END AS IsExcludeAbsentTotal,
			
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			EM.DisplayTitle,
			ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
			ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			ISNULL(EM.TermScopeId,0) AS TermScopeId,	
			ISNULL(EM.ReportId,0) as ReportId,
			CASE WHEN ED.ClassSubjectId=CS.Id THEN 'true' ELSE 'false' END AS Selected,
			
			ISNULL(EM.CoScholasticScopeId,0) AS CoScholasticScopeId,
			ISNULL(EM.SubjectGroupPerPage,0) AS SubjectGroupPerPage,
			CASE WHEN ISNULL(IsDisplayParentName,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayParentName,
			CASE WHEN ISNULL(IsDisplayTeacherSign,0)=0 THEN 'false' ELSE 'true' END AS IsDisplayTeacherSign,
			CASE WHEN ISNULL(IsDisplayPrincipalSign,0)=0 THEn 'false' ELSE 'true' END AS IsDisplayPrincipalSign,
			ISNULL(EM.PercentileScopeId,0) AS PercentileScopeId,
			ISNULL(EM.CoScholasticGradeSetId,0) AS CoScholasticGradeSetId,
			ISNULL(EM.DecimalFormat,'') AS DecimalFormat,
			ISNULL(EM.IsDisplayTotalMark,0) AS IsDisplayTotalMarks,
			ISNULL(EM.IsDisplayResultIndicator,0) AS IsDisplayResultIndicator,
			ISNULL(Em.IsRemovePercentageForFail,0) AS IsFailPercentageZero,
			Isnull(EM.Remark1Caption,'') AS Remark1Caption,
			Isnull(EM.Remark2Caption,'') AS Remark2Caption,
			Isnull(EM.Remark3Caption,'') AS Remark3Caption,
			--CASE WHEN ISNULL(EM.TeacherSignCaption,'') like '' THEN '' ELSE EM.TeacherSignCaption END As TeacherSignCaption,
			--CASE WHEN ISNULL(EM.PrincipalSignCaption,'') like '' THEN '' ELSE EM.PrincipalSignCaption END As PrincipalSignCaption,
			--CASE WHEN ISNULL(EM.ParentSignCaption,'') like '' THEN '' ELSE EM.ParentSignCaption END As ParentSignCaption,
			 EM.TeacherSignCaption,
			 EM.PrincipalSignCaption,
			 EM.ParentSignCaption,
			isnull(IsSubjectWeightage,0) AS IsSubjectWeightage,
			ISNULL(IsDisplayActivityGrade,0)As IsDisplayActivityGrade,
			ISNULL(IsAllExamPassRequired,0) As IsAllExamPassRequired,
			ISNULL(IsPublishExamSchedule,0) As IsPublishExamSchedule,
			ISNULL(LinkExamId,0) As LinkExamId,
			ISNULL(OverallPercentageForGrace,0) As OverallPercentageForGrace,
			ISNULL(MinimumGracePercetage,0) As MinimumGracePercetage,
			ISNULL(GraceMaxMark,0) As GraceMaxMark,
			ISNULL(KrupaMaxMark,0) As KrupaMaxMark,
			ISNULL(EM.IsApplySiddhiKrupa,0) As IsApplySiddhiKrupa,
			ISNULL (EM.IsDisplayGraph,0) As IsDisplayGraph,
			ISNULL(EM.CoScholasticTitle,'') As CoScholasticTitle,
			ISNULL(EM.IsGenerateRankNo,0)As IsGenerateRankNo,
			ISNULL(EM.IsDisplayAbsentCount,0)As IsDisplayAbsentCount,
			ISNULL(EM.GraphId,0)AS GraphId,
			ISNULL(EM.HeaderId,0)AS HeaderId,
			ISNULL(EM.TotalId,0)AS TotalId,
			ISNULL(EM.CoordinatorEmployeeId,0) AS CoordinatorEmployeeId,
			Isnull(EM.ResultSheetAdditionalTitle,'') AS ResultSheetAdditionalTitle,
			ISNULL(EM.DisplayAttendanceId,0) AS DisplayAttendanceId,
			ISNULL(EM.ReportHeaderId,0) AS ReportHeaderId,
			ISNULL(EM.IsPublishMarkEntry, 0) AS IsPublishMarkEntry			-- Mantis Id : 0036462
   FROM 
			[sAssessment].[tExamMaster] EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE       
            EM.Id=@rId
			AND CS.IsObsolete = 0
			order by Selected Desc,DisplayOrder Asc,ESGM.Title Desc
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamIdGet]
	@rExamSubGroupId int,
	@rClassId int,
	@rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY 		
	BEGIN
	IF NOT EXISTS (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId AND ExamSubGroupId = @rExamSubGroupId And BatchId =@rBatchId )
		BEGIN
			SELECT 1
		END
	ELSE
		BEGIN
			SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId AND ExamSubGroupId = @rExamSubGroupId And BatchId =@rBatchId 
		END
	END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamListForMarkEntryGet]
	 @rExamSubGroupId int,
	 @rClassId int,
	 @rBatchId int,
	 @rSubjectId int=0

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	SELECT 
		EM.ClassId,
		EM.Id AS ExamId,
		ESGM.Title AS Exam

	FROM sSetup.tClassMaster CM
			INNER JOIN sAssessment.tExamMaster EM ON   CM.Id= EM.ClassId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			
  WHERE		(EM.ClassId=@rClassId OR @rClassId =0) 
			--AND EM.IsProcessResult = 0 
			AND EM.BatchId=@rBatchId			
			AND  EM.Id <> @rExamSubGroupId
 ORDER BY CM.OrderIndex, ESGM.Title ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pExamListGet]
	
	@rAcademicId bigint=0,
	@rBatchId int=0

AS
BEGIN
	DECLARE @lTotalMarks decimal=0,@lTotalObtain decimal=0,@lResultStatus nvarchar(50)='' ,@lResultGrade nvarchar(10)='',@lRankNumber int=0,@lPercentage decimal=0,@lPercentile decimal=0
	DECLARE @lempgrid NVARCHAR(max)=''
	SELECT  @lempgrid = @lempgrid + '<tr>
	<td align="left" scope="col">' + ISNULL(Cm.DisplayTitle,'')+' - '+isnull(Dm.DisplayTitle,'')+' : '+isnull(E.Name,'') +' '+'<a  class="fa fa-plus-square"  
    onclick="GetExamDetailList(' + convert(varchar,isnull(E.Id,0)) + ','+ convert(varchar,@rAcademicId) +');"></a>'+ '</td>
	<td align="left" scope="col">' + isnull(BM.Title,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.TotalMarks,0)) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.TotalObtain,'')) + '</td>
	<td align="left" scope="col">' + isnull(R.ResultStatus,'') + '</td>
	<td align="left" scope="col">' + isnull(R.ResultGrade,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.RankNumber,0)) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.Percentage,0)) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.Percentile,0)) + '</td>
	  <td scope="col" align="center"><a  class="fa fa-plus-square"  
    onclick="SelectResult(this,' + convert(varchar,isnull(E.Id,0)) + ');"></a></td></tr>'	
 From
 sStudent.tAcademic AD 
 INNER JOIN  sAssessment.vExamMaster E ON E.BatchId = AD.BatchId AND E.ClassId = AD.ClassId
 INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
 INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=AD.DivisionId
 INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = E.Id
 
 WHERE ((AD.Id=@rAcademicId) OR (@rAcademicId=0))
	--AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
	 AND IsProcessResult=1
	 ORDER BY DM.OrderIndex DESC
	select isnull(@lempgrid,'') as EmpGrid
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamMasterAdd]
	 
	        @rId int
	       ,@rBatchId int
           ,@rExamSubGroupId int           
           ,@rClassId int
           ,@rIsRankNo bit
           ,@rIsGrade bit
           ,@rIsPercentile bit
           ,@rIsPercentage bit
           ,@rIsSubjectPercentile bit
           ,@rGradeSetId int
           ,@rRankSetId int
           ,@rLevelSetId int
           ,@rIsProcessResult bit
           ,@rIsMarkInDecimal bit
           ,@rIsNegativeMarks bit
           ,@rIsPrePrinted bit
           ,@rIsDisplayBirthDate bit
           ,@rIsDisplayPhoto bit
           ,@rIsDisplayschoolName bit
           ,@rIsIncludeCoScholastic bit
           ,@rIsCoScholasticGrade bit
           ,@rIsCoScholasticGradeIndicator bit
           ,@rIsCoScholasticGradeDesIndicator bit
           ,@rIsLockForEdit bit
           ,@rRemark1 nvarchar(1000)
           ,@rRemark2 nvarchar(150)
           ,@rDisplayTitle nvarchar(150)
           ,@rFooterAdjustment smallint
           ,@rReportId smallint
           ,@rRemark3 nvarchar(150)
           ,@rIsDisplayHeightWeight bit
           ,@rIsDisplayAttendance bit
           ,@rIsDisplayResultStatus bit
           ,@rDetailAdjustment smallint
           ,@rTermScopeId smallint
           ,@rMaximumMark Decimal
           ,@rIsIncludeSubExam bit
           ,@rCreatedUserId bigint
           ,@rOrgId int
           ,@rIsPublished bit
           ,@rIsDisplayHighestDivisionMark bit
           ,@rIsDisplayHighestDivisionGrade bit
           ,@rIsDisplayGradeString bit,
            @rCoScholasticScopeId tinyint,
            @rIsDisplayParentsName bit=0,
			@rSubjectGroupPerPage tinyint,
			@rIsDisplayTeacherSign bit,
			@rIsDisplayPrincipalSign bit,
			@rPercentileScope tinyint=0,
			@rCoScholasticGradeSetId int =0,
			@rIsExcludeAbsentTotal bit =0,
			@rDecimalUpto nvarchar(10),
			@rIsShowAddress bit=0,
			@rIsShowTotalMarks  bit =0,
			@rIsShowResultIndicator  bit =0,
			@rIsFailPercentageZero bit=0,
			@rRemark1Caption nvarchar(100),
			@rRemark2Caption nvarchar(100),
			@rRemark3Caption nvarchar(100),
			@rTeacherSignCaption nvarchar(100),
			@rPrincipalSignCaption nvarchar(100),
			@rParentSignCaption nvarchar(100),
			@rIsSubjectWeightage bit=0,
			@rIsDisplayActivityGrade bit=0,
			@rIsAllExamPassRequired bit=0,
			@rIsPublishExamSchedule bit=0,
			@rLinkedExamId int=0,
			@rOverallPercentageForGrace smallint = 0,
			@rMinimumGracePercetage smallint = 0,
			@rGraceMaxMark smallint = 0,
			@rKrupaMaxMark smallint = 0,
			@rIsSiddhiKrupaApplicable bit = 0,
			@rIsGenerateRankNo bit=0,
			@rIsDisplayAbsentCount bit=0,
			@rGraphId int=0,
			@rHeaderId int=0,
			@rTotalId int=0,
			@rCoordinatorEmployeeId bigint,
			@rResultSheetAdditionalTitle nvarchar(100)='',
			@rDisplayAttendanceId Smallint=0,
			@rReportHeaderId smallint=0,
			@rIsPublishMarkEntry bit = 0			-- Mantis Id : 0036462
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId AND ClassId=@rClassId AND BatchId=@rBatchId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		--If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId and ClassId=@rClassId AND BatchId=@rBatchId)
		--	BEGIN
		--	select -103 as Result
		--	RETURN
		--END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId AND ClassId=@rClassId AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		--If  Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId and ClassId=@rClassId AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -103 as Result
		--	RETURN
		--End

	END
	
	
	
	 	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tExamMaster]
			   (
			     Id 
				,BatchId 
				--,Code 
				--,Name 
				,ExamSubGroupId 
				,ClassId 
				,IsRankNo 
				,IsGrade 
				,IsPercentile
				,IsSubjectPercentile
				,IsPercentage
				,GradeSetId 
				,RankSetId 
				,LevelSetId
				,IsProcessResult
				,IsMarksInDecimal
				,IsNegativeMarks
				,IsOnPrePrinted
				,IsDisplayBirthDate
				,IsDisplayPhoto
				,IsDisplaySchoolName
				,IsLockForEdit
				,IsIncludeCoScholastic
				,IsCoScholasticGrade
				,IsCoScholasticGradeIndicator
				,IsCoScholasticGradeDesIndicator
				,IsDisplayAttendance
				,IsDisplayHeightWeight
				,IsResultStatus
				,Remark1
				,Remark2
				,Remark3
				,DisplayTitle
				,FooterAdjustment
				,DetailAdjustment
				,ReportId
				,TermScopeId
				,ExamMaximum
				,IsIncludeSubExam
				,UpdatedUserId
				,UpdatedDateTime
				,IsPublished
				,IsDisplayHighestDivisionMark
				,IsDisplayHighestDivisionGrade
				,IsDisplayGradeString,
				CoScholasticScopeId,
				IsDisplayParentName,
				 SubjectGroupPerPage,
				 IsdisplayTeacherSign,
				 IsDisplayPrincipalSign,
				 PercentileScopeId,
				 CoScholasticGradeSetId,
				 IsExcludeAbsentTotal,
				 DecimalFormat,
				 IsDisplayTotalMark,
				 IsDisplayResultIndicator,
				 IsRemovePercentageForFail,
				 Remark1Caption ,
				 Remark2Caption ,
				 Remark3Caption,
				 TeacherSignCaption,
				 PrincipalSignCaption,
				 ParentSignCaption,
				 IsSubjectWeightage,
				 IsDisplayActivityGrade,
				 IsAllExamPassRequired,
				 IsPublishExamSchedule,
				 LinkExamId,
			     OverallPercentageForGrace,
			     MinimumGracePercetage,
			     GraceMaxMark,
			     KrupaMaxMark,
			     IsApplySiddhiKrupa,
				 IsGenerateRankNo,
				 IsDisplayAbsentCount,
				 GraphId,
				 HeaderId,
				 TotalId,
				 CoordinatorEmployeeId,
				 ResultSheetAdditionalTitle,
				 DisplayAttendanceId,
				 ReportHeaderId,
				 IsPublishMarkEntry				-- Mantis Id : 0036462
			   )
		 VALUES
			   (
				@lNextNumber 
			   ,@rBatchId 
			   --,@rCode 
			   --,@rExamName 
			   ,@rExamSubGroupId 
			   ,@rClassId 
			   ,@rIsRankNo 
			   ,@rIsGrade 
			   ,@rIsPercentile 
			   ,@rIsSubjectPercentile
			   ,@rIsPercentage 
			   ,@rGradeSetId 
			   ,@rRankSetId 
			   ,@rLevelSetId 
			   ,@rIsProcessResult
			   ,@rIsMarkInDecimal
			   ,@rIsNegativeMarks
			   ,@rIsPrePrinted
			   ,@rIsDisplayBirthDate
			   ,@rIsDisplayPhoto
			   ,@rIsDisplayschoolName
			   ,@rIsLockForEdit
			   ,@rIsIncludeCoScholastic
			   ,@rIsCoScholasticGrade
               ,@rIsCoScholasticGradeIndicator
               ,@rIsCoScholasticGradeDesIndicator
			   ,@rIsDisplayAttendance
			   ,@rIsDisplayHeightWeight
			   ,@rIsDisplayResultStatus
			   ,@rRemark1
			   ,@rRemark2
			   ,@rRemark3
			   ,@rDisplayTitle
			   ,@rFooterAdjustment
			   ,@rDetailAdjustment
			   ,@rReportId
			   ,@rTermScopeId
			   ,@rMaximumMark
			   ,@rIsIncludeSubExam
			   ,0
			   ,sCommon.fGetDate()
			   ,@rIsPublished
			   ,@rIsDisplayHighestDivisionMark
			   ,@rIsDisplayHighestDivisionGrade
			   ,@rIsDisplayGradeString,
			   @rCoScholasticScopeId,
			   @rIsDisplayParentsName,
			   
			   
			  @rSubjectGroupPerPage ,
			  @rIsDisplayTeacherSign,
			  @rIsDisplayPrincipalSign,
			  @rPercentileScope,
			  @rCoScholasticGradeSetId,
			  @rIsExcludeAbsentTotal,
			  @rDecimalUpto,
			  @rIsShowTotalMarks,
			  @rIsShowResultIndicator,
			  @rIsFailPercentageZero,
			  @rRemark1Caption ,
			  @rRemark2Caption ,
			  @rRemark3Caption,
			  @rTeacherSignCaption,
			  @rPrincipalSignCaption,
			  @rParentSignCaption,
			  @rIsSubjectWeightage,
			  @rIsDisplayActivityGrade,
			  @rIsAllExamPassRequired,
			  @rIsPublishExamSchedule	,
			  @rLinkedExamId,
			  @rOverallPercentageForGrace,
			  @rMinimumGracePercetage,
			  @rGraceMaxMark,
			  @rKrupaMaxMark,
			  @rIsSiddhiKrupaApplicable,
			  @rIsGenerateRankNo,
			  @rIsDisplayAbsentCount,
			  @rGraphId,
			  @rHeaderId,
			  @rTotalId,
			  @rCoordinatorEmployeeId,
			  @rResultSheetAdditionalTitle,
			  @rDisplayAttendanceId,
			  @rReportHeaderId,
			  @rIsPublishMarkEntry
			   )
				SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tExamMaster]
	    SET
			   -- Code =@rCode 
			   --,Name = @rExamName 
			    ExamSubGroupId =@rExamSubGroupId 
			   ,ClassId =@rClassId 
			   ,IsRankNo=@rIsRankNo 
			   ,IsGrade=@rIsGrade 
			   ,IsPercentile =@rIsPercentile 
			   ,IsSubjectPercentile = @rIsSubjectPercentile
			   ,IsPercentage=@rIsPercentage 
			   ,GradeSetId =@rGradeSetId 
			   ,RankSetId=@rRankSetId 
			   ,LevelSetId=@rLevelSetId 
			   ,IsProcessResult = @rIsProcessResult
			   ,IsMarksInDecimal = @rIsMarkInDecimal			   
			   ,IsNegativeMarks = @rIsNegativeMarks
			   
			   ,IsOnPrePrinted = @rIsPrePrinted
			   ,IsDisplayBirthDate=@rIsDisplayBirthDate
			   ,IsDisplayPhoto=@rIsDisplayPhoto
			   ,IsDisplaySchoolName=@rIsDisplayschoolName
			   ,IsIncludeCoScholastic=@rIsIncludeCoScholastic
			   ,IsCoScholasticGrade=@rIsCoScholasticGrade
			   ,IsCoScholasticGradeIndicator=@rIsCoScholasticGradeIndicator
			   ,IsCoScholasticGradeDesIndicator=@rIsCoScholasticGradeDesIndicator
			   ,IsLockForEdit=@rIsLockForEdit
			   ,IsDisplayAttendance=@rIsDisplayAttendance
			   ,IsDisplayHeightWeight=@rIsDisplayHeightWeight
			   ,IsResultStatus=@rIsDisplayResultStatus
			   ,Remark1=@rRemark1
			   ,Remark2=@rRemark2
			   ,Remark3=@rRemark3
			   ,DisplayTitle=@rDisplayTitle
			   ,FooterAdjustment=@rFooterAdjustment
			   ,DetailAdjustment=@rDetailAdjustment
			   ,ReportId = @rReportId
			   ,TermScopeId=@rTermScopeId
			   ,ExamMaximum=@rMaximumMark
			   ,IsIncludeSubExam = @rIsIncludeSubExam
			   ,UpdatedUserId=@rCreatedUserId
			   ,UpdatedDateTime=sCommon.fGetDate()          
			   ,IsPublished=@rIsPublished
			   ,IsDisplayHighestDivisionMark=@rIsDisplayHighestDivisionMark
			   ,IsDisplayHighestDivisionGrade=@rIsDisplayHighestDivisionGrade
			   ,IsDisplayGradeString=@rIsDisplayGradeString,
			   CoScholasticScopeId=@rCoScholasticScopeId,
			   IsDisplayParentName=@rIsDisplayParentsName,
			   SubjectGroupPerPage = @rSubjectGroupPerPage,
			   IsDisplayTeacherSign = @rIsDisplayTeacherSign,
			   IsDisplayPrincipalSign = @rIsDisplayPrincipalSign,
			   PercentileScopeId = @rPercentileScope,
			   CoScholasticGradeSetId=@rCoScholasticGradeSetId,
			   IsExcludeAbsentTotal = @rIsExcludeAbsentTotal,
			   DecimalFormat = @rDecimalUpto,
			   IsDisplayTotalMark = @rIsShowTotalMarks,
			   IsDisplayResultIndicator = @rIsShowResultIndicator,
			   IsRemovePercentageForFail=@rIsFailPercentageZero,
			   Remark1Caption= @rRemark1Caption ,
			   Remark2Caption= @rRemark2Caption ,
			   Remark3Caption= @rRemark3Caption,
			   TeacherSignCaption=@rTeacherSignCaption,
			   PrincipalSignCaption=@rPrincipalSignCaption,
			   ParentSignCaption=@rParentSignCaption,
			   IsSubjectWeightage=@rIsSubjectWeightage,
			   IsDisplayActivityGrade =@rIsDisplayActivityGrade,
			   IsAllExamPassRequired =@rIsAllExamPassRequired,
               IsPublishExamSchedule = @rIsPublishExamSchedule,
               LinkExamId= @rLinkedExamId,
               OverallPercentageForGrace=@rOverallPercentageForGrace,
			   MinimumGracePercetage=@rMinimumGracePercetage,
			   GraceMaxMark=@rGraceMaxMark,
			   KrupaMaxMark=@rKrupaMaxMark,
			   IsApplySiddhiKrupa=@rIsSiddhiKrupaApplicable,
			   IsGenerateRankNo=@rIsGenerateRankNo,
			   IsDisplayAbsentCount=@rIsDisplayAbsentCount,
			   GraphId= @rGraphId,
			   HeaderId= @rHeaderId,
			   TotalId= @rTotalId,
			   CoordinatorEmployeeId = @rCoordinatorEmployeeId,
			   ResultSheetAdditionalTitle=@rResultSheetAdditionalTitle,
			   DisplayAttendanceId=@rDisplayAttendanceId,
			   ReportHeaderId=@rReportHeaderId,
			   IsPublishMarkEntry = @rIsPublishMarkEntry			-- Mantis Id : 0036462
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		 
	 END  	

	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamMasterDelete]
	@rId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY 		
	IF EXISTS (SELECT 1 FROM sAssessment.tExamCombine WHERE SubExamId = @rId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END
	IF EXISTS (SELECT 1 FROM sAssessment.tResult WHERE ExamId = @rId )
	BEGIN 
		SELECT -102 AS Result
		RETURN
	END
	IF EXISTS (SELECT 1 FROM sAssessment.tGradeSujbectExamScore WHERE ExamId = @rId )
	BEGIN 
		SELECT -103 AS Result
		RETURN
	END
	IF EXISTS (SELECT 1 FROM  sAssessment.tCCECSExamScore WHERE ExamId = @rId )
	BEGIN 
		SELECT -104 AS Result
		RETURN
	END
	
	--ELSE IF EXISTS (SELECT ExamId FROM sAssessment.tCCEExamMapping WHERE ExamId = @rId )
	--BEGIN 
	--	SELECT -103 AS Result
	--END	
 
 

		DELETE RD FROM sAssessment.tResult RM INNER JOIN  sAssessment.tResultDetail RD ON RD.ResultId=RM.Id WHERE RM.ExamId = @rId
		DELETE RD FROM sAssessment.tResultDetail RD INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id WHERE ED.ExamId = @rId
		DELETE FROM sAssessment.tResult WHERE ExamId = @rId
		
		DELETE FROM sAssessment.tGradeSujbectExamScore WHERE ExamId = @rId
		DELETE FROM sAssessment.tCCECSExamScore WHERE ExamId = @rId
		DELETE FROM sAssessment.tStudentRemark WHERE ExamId = @rId
		DELETE FROM sAssessment.tTempAllExam WHERE ExamIdText = @rId
		DELETE FROM sAssessment.tTempCoScholasticExam WHERE ExamId = @rId
		
		DELETE FROM sAssessment.tExamStatus WHERE ExamId = @rId
		DELETE FROM sAssessment.tExamCombine  WHERE ExamId = @rId
		DELETE FROM sAssessment.tExamDetail  WHERE ExamId = @rId
		DELETE FROM sAssessment.tExamMaster  WHERE Id = @rId
		
		
		SELECT 1 AS RESULT
 
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamMasterGet]
	 @rTitle nvarchar(100),
	 @rExamGroupId int,
	 @rClassId int,
	 @rOrgId int ,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	SELECT 
		Distinct 
		EM.Id,
		EM.ClassID,
		EGM.Title as ExamGroup,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		ISNULL(IsProcessResult,0) AS IsProcessResult,
		IsNull(IsMarksInDecimal,0) AS IsMarksInDecimal,
		ISNULL(ISNegativeMarks,0) AS ISNegativeMarks ,
		ISNULL(IsIncludeCoScholastic,0) AS IsIncludeCoScholastic,
		ISNULL(IsIncludeSubExam,0) AS IsIncludeSubExam ,
		ISNULL(EM.IsPublished,0) AS IsPublished,
		isnull(EM.IsPublishExamSchedule,0) AS IsPublishExamSchedule,
		isnull(EM.IsPublishMarkEntry, 0) AS IsPublishMarkEntry			-- Mantis Id : 0036462
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		--LEFT JOIN sAssessment.vExamClassDivision ECD ON ECD.Id=EM.Id AND ECD.ClassId=EM.ClassId AND ECD.ExamSubGroupId=EGM.Id AND ECD.BatchId=@rBatchId
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) AND (EM.BatchId=@rBatchId)
		AND (EGM.Id=@rExamGroupId OR @rExamGroupId=0)
		AND (CM.Id=@rClassId or @rClassId=0)
		AND ESGM.IsObsolete=0 
	ORDER BY 
		EGM.Title ,ESGM.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pExamMasterOldGet]
	 @rTitle nvarchar(100),
	 @rExamGroupId int,
	 @rClassId int,
	 @rOrgId int ,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	SELECT 
	EM.Id,
	EM.ClassID,
	EGM.Title as ExamGroup,
	ESGM.Title as ExamName,
	CM.DisplayTitle as ClassName,
	ISNULL(IsProcessResult,0) AS IsProcessResult,
	IsNull(IsMarksInDecimal,0) AS IsMarksInDecimal,
	ISNULL(ISNegativeMarks,0) AS ISNegativeMarks ,
	ISNULL(IsIncludeCoScholastic,0) AS IsIncludeCoScholastic,
	ISNULL(IsIncludeSubExam,0) AS IsIncludeSubExam  
  FROM	
			[sAssessment].[tExamMaster] EM			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			 
			 
WHERE		(CM.OrgId = @rOrgId  OR @rOrgId=0) AND (EM.BatchId=@rBatchId)
			AND (EGM.Id=@rExamGroupId OR @rExamGroupId=0)
			AND (CM.Id=@rClassId or @rClassId=0)  
		--	AND ((EM.Name Like  @rTitle )OR(ISNULL(@rTitle,'') = ''))
		    AND ESGM.IsObsolete=0
			ORDER BY EGM.Title ,ESGM.Title

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamRemarkSetupAdd]
@rId int,
@rExamId Int,
@rCode nvarchar(20),
@rTitle nvarchar(200),
@rOrderIndex int,
@rCreatedUserId bigint,
@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	if(@rId=0) 
	BEGIN
		If Exists(select Id from [sAssessment].[tExamRemarkSetup] where Code=@rCode)
		BEGIN
			select -101 as Result
			RETURN
		END
		If Exists(select Id from [sAssessment].[tExamRemarkSetup] where Title=@rTitle)
		BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from [sAssessment].[tExamRemarkSetup] WHERE OrderIndex=@rOrderIndex)
		BEGIN 
			select -105 as Result
			RETURN
		END
	END
	ELSE
	BEGIN
		If Exists(select Id from [sAssessment].[tExamRemarkSetup] where Code=@rCode AND Id<>@rId)
		BEGIN
			select -101 as Result
			RETURN
		END
		IF Exists(select Id from [sAssessment].[tExamRemarkSetup] where Title=@rTitle AND Id<>@rId)
		BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from [sAssessment].[tExamRemarkSetup] WHERE OrderIndex=@rOrderIndex AND Id<>@rId)
		BEGIN 
			select -105 as Result
			RETURN
		END
	END
	
	IF(@rId=0)
	BEGIN
		DECLARE @lNextNumber BIGINT 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamRemarkSetup', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO [sAssessment].[tExamRemarkSetup]
           ([Id]
		   ,[ExamId]
           ,[Code]
           ,[Title]
           ,[OrderIndex]
           ,[CreatedUserId]
			   ,[CreatedDateTime])
		 VALUES
			   (@lNextNumber
			   ,@rExamId
			   ,@rCode
			   ,@rTitle
			   ,@rOrderIndex
			   ,@rCreatedUserId
			   ,sCommon.fGetDate())
		SELECT @lNextNumber AS Result
	END
	ELSE
	BEGIN
		SET @lNextNumber = @rId
		UPDATE [sAssessment].[tExamRemarkSetup]
		   SET [ExamId] =@rExamId
			  ,[Code] = @rCode
			  ,[Title] = @rTitle
			  ,[OrderIndex] = @rOrderIndex
			  ,[UpdatedUserId] =@rCreatedUserId
			  ,[UpdatedDateTime] = sCommon.fGetDate()
		 WHERE Id=@rId
		 SELECT @lNextNumber AS Result
	END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pExamRemarkSetupGet]
          
   @rId int,
   @rTitle nvarchar(100),
   @rOrgId int,
   @rClassId int,
   @rExamId int,
   @rBatchId int=0          
          
AS
SET NOCOUNT ON

   SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN
  SELECT 
	   ERS.Id as Id
	  ,ERS.Title as Title
	  ,ISNULL(ERS.Code,'') as Code
	  --,ISNULL(EM.DisplayTitle,'') AS ExamTitle
	  ,ISNULL(ESGM.Title,'') AS ExamTitle
	  ,ERS.ExamId AS ExamId
	  ,ISNULL(ERS.OrderIndex,0) AS OrderIndex
       ,ISNULL(EM.ClassId,0) AS ClassId
  FROM [sAssessment].[tExamRemarkSetup] ERS 
	   INNER JOIN [sAssessment].[tExamMaster] EM ON EM.Id = ERS.ExamId
	   --inner Join sAssessment.tExamGroupMaster EGM ON EGM.Id=EM.ExamSubGroupId 
	   INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
	   INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId 
  WHERE 
	    ((ERS.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	    AND (ERS.ExamId=@rExamId OR @rExamId=0)
		AND EGM.OrgId = @rOrgId
		AND (ERS.Id = @rId  OR @rId = 0)
		AND(EM.ClassId=@rClassId OR @rClassId=0)
		AND (EM.BatchId=@rBatchId OR @rBatchId=0)
   Order by OrderIndex 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamScheduleClassWiseGet]	 
	 @rOrgId int ,
	 @rBatchId int,	 
	 @rUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

	DECLARE @lEmployeeId bigint=0
	SELECT @lEmployeeId=SourceId FROM sSecurity.tUser WHERE Id=@rUserId

	DECLARE @lMarkEntryBasedOn nvarchar(50)=''
	SELECT @lMarkEntryBasedOn=ItemValue FROM [sConfig].[tConfigurationSetup] where ConfigurationId=188 and SourceId=@rOrgId

IF(@lMarkEntryBasedOn = 'Class Teacher' AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,		
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId= CM.Id
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 		
		AND (DM.InchargeemployeeID=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		CM.Id
END
ELSE IF(@lMarkEntryBasedOn = 'Class Teacher Batch'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,		
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id 
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 		
		AND (DIE.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		CM.Id
END
ELSE IF(@lMarkEntryBasedOn = 'Academic Setup'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,		
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id	
		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = CM.Id AND vTSD.SubjectId = SM.Id 
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 		
		AND (vTSD.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		CM.Id
END

ELSE IF(@lMarkEntryBasedOn = 'User Access'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,		
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id 
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND SourceTypeId = 2005
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 		
		AND (U.UserId=@rUserId OR ISNULL(@rUserId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		CM.Id
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamScheduleDateWiseGet]	 
	 @rOrgId int ,
	 @rBatchId int,
	 @rExamDate Date,
	 @rUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

	DECLARE @lEmployeeId bigint=0
	SELECT @lEmployeeId=SourceId FROM sSecurity.tUser WHERE Id=@rUserId

	DECLARE @lMarkEntryBasedOn nvarchar(50)=''
	SELECT @lMarkEntryBasedOn=ItemValue FROM [sConfig].[tConfigurationSetup] where ConfigurationId=188 and SourceId=@rOrgId

IF(@lMarkEntryBasedOn = 'Class Teacher' AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON CM.Id = DM.ClassId
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (DM.InchargeemployeeID=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		ExamDate
END
ELSE IF(@lMarkEntryBasedOn = 'Class Teacher Batch'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON CM.Id = DM.ClassId
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (DIE.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		ExamDate
END
ELSE IF(@lMarkEntryBasedOn = 'Academic Setup'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id	
		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = CM.Id AND vTSD.SubjectId = SM.Id 
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (vTSD.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		ExamDate
END

ELSE IF(@lMarkEntryBasedOn = 'User Access'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON CM.Id = DM.ClassId
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND SourceTypeId = 2005
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (U.UserId=@rUserId OR ISNULL(@rUserId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		ExamDate
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamScheduleGet]
 
	@rExamId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		SM.Title AS 'Subject',
		ED.ExamDate AS ExamDate,
		ED.ExamTime AS ExamTime,
		ISNULL(ED.ExamTopic,'') AS ExamTopic
	FROM 
		sAssessment.tExamMaster E 
		INNER JOIN sAssessment.tExamDetail ED ON E.Id = ED.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
	WHERE 
		ED.ExamId = @rExamId  AND ISNULL(E.IsPublishExamSchedule,0) = 1
	ORDER BY 
		ED.ExamDate	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pExamSettingAdd]
	(
		--@rExamSettingXml nvarchar(MAX),
		--@rOrgId int

		@rExamSettingXml nvarchar(max),
		@rExamSettingTypeId int,
		@rCreatedUserId bigint
	)
AS

SET NOCOUNT ON

BEGIN
SET @rExamSettingXml=REPLACE(@rExamSettingXml,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rExamSettingXml
	
	IF(@rExamSettingTypeId = 1)
	BEGIN
		UPDATE sAssessment.tExamMaster
		SET 
			--IsProcessResult = E.IsProcessResult,
			IsNegativeMarks = E.IsNegativeMarks,
			IsLockForEdit = E.IsLockForEdit,
			IsPublished = E.IsPublished,
			IsPublishExamSchedule = E.IsPublishExamSchedule,
			ReportId = CASE WHEN E.IsPublished = 1 THEN 20438 ELSE 0 END,
			--(CASE WHEN E.IsPublished = 1 THEN ReportId = 20438 ELSE '' END),
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM (
		SELECT
			ExamId,
			IsProcessResult,
			IsNegativeMarks,
			IsLockForEdit,
			IsPublished,
			IsPublishExamSchedule
			FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
		WITH
		(
			ExamId bigint,
			IsProcessResult bit ,
			IsNegativeMarks bit ,
			IsLockForEdit bit,
			IsPublished bit,
			IsPublishExamSchedule bit
		))E 
		Where sAssessment.tExamMaster.Id = E.ExamId
	END
	
	ELSE IF(@rExamSettingTypeId = 2)
	BEGIN
		UPDATE sAssessment.tExamMaster
		SET 
			IsGrade = E.IsGrade,
			IsPercentile = E.IsPercentile,
			IsRankNo = E.IsRankNo,
			IsGenerateRankNo = E.IsGenerateRankNo,
			IsPercentage = E.IsPercentage,
			IsRemovePercentageForFail = E.IsFailPercentageZero,
			IsSubjectPercentile = E.IsSubjectPercentile,
			IsResultStatus = E.IsDisplayResultStatus,
			IsAllExamPassRequired = E.IsAllExamPassRequired,
			IsExcludeAbsentTotal = E.IsExcludeAbsentTotal,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM (
		SELECT
			ExamId,
			IsGrade,
			IsPercentile,
			IsRankNo,
			IsGenerateRankNo,
			IsPercentage,
			IsFailPercentageZero,
			IsSubjectPercentile,
			IsDisplayResultStatus,
			IsAllExamPassRequired,
			IsExcludeAbsentTotal
			FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
		WITH
		(
			ExamId bigint,
			IsGrade bit,
			IsPercentile bit,
			IsRankNo bit,
			IsGenerateRankNo bit,
			IsPercentage bit,
			IsFailPercentageZero bit,
			IsSubjectPercentile bit,
			IsDisplayResultStatus bit,
			IsAllExamPassRequired bit,
			IsExcludeAbsentTotal bit
		))E 
		Where sAssessment.tExamMaster.Id = E.ExamId
	END
	
	ELSE IF(@rExamSettingTypeId = 3)
	BEGIN
		UPDATE sAssessment.tExamMaster
			SET 
				IsDisplayPhoto = E.IsDisplayPhoto,
				IsDisplaySchoolName = E.IsDisplaySchoolName,
				IsDisplayBirthDate = E.IsDisplayBirthDate,
				IsDisplayParentName = E.IsDisplayParentName,
				IsDisplayHeightWeight = E.IsDisplayHeightWeight,
				IsDisplayGradeString = E.IsDisplayGradeString,
				IsDisplayTotalMark = E.IsDisplayTotalMark,
				IsDisplayResultIndicator = E.IsDisplayResultIndicator,
				IsDisplayHighestDivisionMark = E.IsDisplayHighestDivisionMark,
				IsDisplayHighestDivisionGrade = E.IsDisplayHighestDivisionGrade,
				IsDisplayTeacherSign = E.IsDisplayTeacherSign,
				IsDisplayPrincipalSign = E.IsDisplayPrincipalSign,
				IsDisplayActivityGrade = E.IsDisplayActivityGrade,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			FROM (
			SELECT
				ExamId,
				IsDisplayPhoto ,
				IsDisplaySchoolName ,
				IsDisplayBirthDate ,
				IsDisplayParentName ,
				IsDisplayHeightWeight ,
				IsDisplayGradeString ,
				IsDisplayTotalMark ,
				IsDisplayResultIndicator ,
				IsDisplayHighestDivisionMark ,
				IsDisplayHighestDivisionGrade ,
				IsDisplayTeacherSign ,
				IsDisplayPrincipalSign ,
				IsDisplayActivityGrade 
				FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
			WITH
			(
				ExamId bigint,
				IsDisplayPhoto bit,
				IsDisplaySchoolName bit,
				IsDisplayBirthDate bit,
				IsDisplayParentName bit,
				IsDisplayHeightWeight bit,
				IsDisplayGradeString bit,
				IsDisplayTotalMark bit,
				IsDisplayResultIndicator bit,
				IsDisplayHighestDivisionMark bit,
				IsDisplayHighestDivisionGrade bit,
				IsDisplayTeacherSign bit,
				IsDisplayPrincipalSign bit,
				IsDisplayActivityGrade bit
			))E 
			Where sAssessment.tExamMaster.Id = E.ExamId
	END
		
	ELSE
	BEGIN
		UPDATE sAssessment.tExamMaster
			SET 
				IsIncludeCoScholastic = E.IsIncludeCoScholastic,
				IsCoScholasticGradeIndicator = E.IsCoScholasticGradeIndicator,
				IsCoScholasticGradeDesIndicator = E.IsCoScholasticGradeDesIndicator,
				IsCoScholasticGrade = E.IsCoScholasticGrade,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				CoScholasticScopeId = 1
			FROM (
			SELECT
				ExamId,
				IsIncludeCoScholastic ,
				IsCoScholasticGradeIndicator ,
				IsCoScholasticGradeDesIndicator ,
				IsCoScholasticGrade 
				FROM OPENXML (@intDoc, '/Table/ExamSetting', 1)
			WITH
			(
				ExamId bigint,
				IsIncludeCoScholastic bit,
				IsCoScholasticGradeIndicator bit,
				IsCoScholasticGradeDesIndicator bit,
				IsCoScholasticGrade bit
			))E 
			Where sAssessment.tExamMaster.Id = E.ExamId

	END

	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAssessment].[pExamSettingGet]
	 @rExamId int,
	 @rClassId int,
	 @rExamSettingTypeId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
DECLARE @lExamIds nvarchar(max)	
CREATE TABLE #AllExams
(
ExamIds int
)
INSERT INTO #AllExams
SELECT EM.Id FROM [sAssessment].[tExamMaster] EM 
		WHERE EM.Id =@rExamId  AND EM.CLassId = @rClassId


INSERT INTO #AllExams
SELECT EM.Id FROM [sAssessment].[tExamMaster] EM 
		INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId =@rExamId  AND EM.CLassId = @rClassId


INSERT INTO #AllExams
SELECT EM.Id 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

		--SELECT * FROM #AllExams

SELECT @lExamIds = STUFF((SELECT ','+ CONVERT(varchar,ExamIds)
                FROM #AllExams
              -- WHERE t.prodtype = 'XYZ'
             FOR XML PATH('')), 1, 1, '')

--SELECT @lExamIds

IF(@rExamSettingTypeId = 1)
BEGIN
SELECT 


			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			--ISNULL(IsProcessResult,0) AS IsProcessResult,
			ISNULL(IsNegativeMarks,0) AS IsNegativeMarks,
			ISNULL(IsLockForEdit,0) AS IsLockForEdit,
			ISNULL(IsPublished,0) AS IsPublished,
			ISNULL(IsPublishExamSchedule,0) As IsPublishExamSchedule

   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
   WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId AND EM.IsProcessResult = 1
			order by ESGM.Title
END

ELSE IF(@rExamSettingTypeId = 2)		 
BEGIN
	SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsRankNo,
			ISNULL(EM.IsGenerateRankNo,0)As IsGenerateRankNo,
			ISNULL(EM.IsPercentage,0) AS IsPercentage,
			ISNULL(Em.IsRemovePercentageForFail,0) AS IsFailPercentageZero,
			ISNULL(EM.IsSubjectPercentile,0) AS IsSubjectPercentile,
			ISNULL(IsResultStatus,0) AS IsDisplayResultStatus,
			ISNULL(IsAllExamPassRequired,0) As IsAllExamPassRequired,
			ISNULL(IsExcludeAbsentTotal,0) AS IsExcludeAbsentTotal


   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
  WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId AND EM.IsProcessResult = 1
			order by ESGM.Title

END
ELSE IF(@rExamSettingTypeId = 3)		 
BEGIN
	SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ISNULL(IsDisplayPhoto,0) AS IsDisplayPhoto,
			ISNULL(IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			ISNULL(IsDisplayBirthDate,0) AS IsDisplayBirthDate,
			ISNULL(IsDisplayParentName,0) AS IsDisplayParentName,
			ISNULL(IsDisplayHeightWeight,0) AS IsDisplayHeightWeight,
			ISNULL(IsDisplayGradeString,0) AS IsDisplayGradeString,
			ISNULL(EM.IsDisplayTotalMark,0) AS IsDisplayTotalMark,
			ISNULL(EM.IsDisplayResultIndicator,0) AS IsDisplayResultIndicator,
			ISNULL(IsDisplayHighestDivisionMark,0) AS IsDisplayHighestDivisionMark,
			ISNULL(Convert(bit,IsDisplayHighestDivisionGrade),0) AS IsDisplayHighestDivisionGrade,
			ISNULL(IsDisplayTeacherSign,0) AS IsDisplayTeacherSign,
			ISNULL(IsDisplayPrincipalSign,0) AS IsDisplayPrincipalSign,
			ISNULL(IsDisplayActivityGrade,0) AS IsDisplayActivityGrade
			
   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId AND EM.IsProcessResult = 1
			order by ESGM.Title

END
ELSE
BEGIN
SELECT 
			EM.Id,
			EM.BatchId,
			ESGM.Code,
			ESGM.Title AS Name,
			ISNULL(IsIncludeCoScholastic,0) AS IsIncludeCoScholastic,
			ISNULL(IsCoScholasticGradeIndicator,0) AS IsCoScholasticGradeIndicator,
			ISNULL(IsCoScholasticGradeDesIndicator,0) AS IsCoScholasticGradeDesIndicator,
			ISNULL(IsCoScholasticGrade,0) AS IsCoScholasticGrade
   FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			--INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			--LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			--LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
   WHERE      
			(ISNULL(EM.Id,0) IN( SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='') 
            AND EM.ClassId=@rClassId AND EM.IsProcessResult = 1
			order by ESGM.Title
END

DROP TABLE #AllExams
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pExamStatusAdd]
	 
	        @rId bigint
           ,@rExamId int
		   ,@rDivisionId int
		   ,@rOrgId int
		   ,@rExamStatusCode smallint
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF NOT EXISTS (SELECT 1 FROM sAssessment.tExamStatus WHERE ExamId =@rExamId AND DivisionId = @rDivisionId )	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamStatus', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tExamStatus]
			   (
			    [Id]
			   ,ExamId 
			   ,DivisionId 
			   ,StatusId 
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rExamId 
			   ,@rDivisionId 
			   ,@rExamStatusCode
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tExamStatus]
	    SET
			   -- ExamId =@rExamId 
			   --,DivisionId=@rDivisionId
			   --,
			   StatusId=@rExamStatusCode 
	      --WHERE Id = @rId 
	      WHERE ExamId =@rExamId AND DivisionId=@rDivisionId	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pExamSubGroupMasterAdd]
	 
    @rId int
   ,@rCode nvarchar(20)
   ,@rTitle nvarchar(100)
   ,@rIsObsolete bit
   ,@rExamGroupId int
   ,@rCreatedUserId bigint           
   ,@rOrgId int,
   @rNumber int,
   @rOrderIndex int,
   @rExamTypeId smallint,
   @rExamSubGroupDisplayTitle nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tExamSubGroupMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sAssessment.tExamSubGroupMaster where Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END
		If Exists(select Id from sAssessment.tExamSubGroupMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId)
			BEGIN
			select -105 as Result
			RETURN
		END
		If Exists(select Id from sAssessment.tExamSubGroupMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tExamSubGroupMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
			If Exists(select Id from sAssessment.tExamSubGroupMaster where Number=@rNumber AND OrgId=@rOrgId  AND Id<>@rId)
			BEGIN
			select -104 as Result
			RETURN
		END
		If Exists(select Id from sAssessment.tExamSubGroupMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId  AND Id<>@rId)
			BEGIN
			select -105 as Result
			RETURN
		END
		If  Exists(select Id from sAssessment.tExamSubGroupMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sAssessment].[tExamSubGroupMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[ExamGroupId]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId],
			   [Number],
			   [OrderIndex],
			   [ExamTypeId],
			   ExamSubGroupDisplayTitle
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rExamGroupId
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId,
			   @rNumber,
			   @rOrderIndex,
			   @rExamTypeId,
			   @rExamSubGroupDisplayTitle
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tExamSubGroupMaster]
	    SET
			  Code=@rCode
	         ,Title=@rTitle
	         ,ExamGroupId = @rExamGroupId,
	         Number=@rNumber,
	         OrderIndex=@rOrderIndex,
	         ExamTypeId=@rExamTypeId
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate(),
             ExamSubGroupDisplayTitle = @rExamSubGroupDisplayTitle        
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamSubGroupMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT 1 FROM sAssessment.tExamMaster WHERE ExamSubGroupId = @rId)	
	  BEGIN
		DELETE	FROM sAssessment.tExamSubGroupMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pExamSubGroupMasterGet]
          
   @rId int,
   @rExamGroupId int,
   @rTitle nvarchar(100),
   @rOrgId int           
          
AS
SET NOCOUNT ON

   SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN
  SELECT 
	   ESGM.Id as Id
	  ,ESGM.Title as Title
	  ,ISNULL(ESGM.Code,'') as Code
	  ,ISNULL(EGM.Title,'') AS ExamGroupTitle
	  ,ISNULL(ESGM.ExamGroupId,0) as ExamGroupId,
	  ISNULL(ESGM.Number,0) AS Number,
	  ISNULL(ESGM.OrderIndex,0) AS OrderIndex
      ,ESGM.IsObsolete as IsObsolete,
       ISNULL(ESGM.ExamTypeId,0) AS ExamTypeId,
       ExamSubGroupDisplayTitle
  FROM [sAssessment].[tExamSubGroupMaster] ESGM 
	   INNER JOIN [sAssessment].[tExamGroupMaster] EGM ON EGM.Id = ESGM.ExamGroupId
  WHERE 
	    ((ESGM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	    AND (ESGM.ExamGroupId=@rExamGroupId OR @rExamGroupId=0)
		AND ESGM.OrgId = @rOrgId
		AND (ESGM.Id = @rId  OR @rId = 0)
   Order by OrderIndex 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pExamSubjectDivisionAdd]
	 
	@rExamId Int,
	@rDivisionId Int,
	@rExamDetailId Int,
	@rIsAssign bit
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	 DELETE FROM sAssessment.tExamSubjectDivision 
     WHERE 
     ExamId  = @rExamId 
     AND DivisionId = @rDivisionId 
     AND ExamDetailId = @rExamDetailId
	
	IF(@rIsAssign = 1)
	BEGIN
		INSERT INTO [sAssessment].[tExamSubjectDivision]
           (ExamId
           ,DivisionId
           ,ExamDetailId)
		VALUES
           (
            @rExamId,
            @rDivisionId,
            @rExamDetailId)
    END      
          SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pExamSubjectListGet]
	 @rClassId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	--Add CS.IsObsolete = 0 for mantisid - 0028508	
	SELECT 
	    0 AS ExamDetailId,
		SM.Title as SubjectName,
		CS.Id as ClassSubjectId,
		'0' AS Minimum,
		'0' AS Maximum,
		ISNULL(CS.ORDERINDEX,0) AS DisplayOrder,
		'false' AS IsDisplayInMarksheet,
		'false' AS IsIncludeInTotal,
		'false' AS IsShowSubjectGrade,
		sCommon.fGetDate() AS ExamDate,
		'0' AS ExamTime,
		'0' AS ExamTopic,
		'0' AS ExamLanguage,
		'0' AS GradeSetDetailId,
		'false' as Selected
	FROM 
			[sSetup].[tClassMaster] CM INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId	
			LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id	AND ED.ExamId = 0
			
	Where (CS.Classid=@rClassId or @rClassId=0) AND CS.IsObsolete = 0  	    
			order by CS.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pFAExamScoreGet]
	  @rAcademicId bigint
	  ,@rOrgId int
	  ,@rExamId int
	  ,@rClassSubjectId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				ISNULL(CGM.Title,'') AS FAGroup,
				ISNULL(CM.Title,'') AS FA,				
				ISNULL(CC.Grade,'')  AS Grade,
				ISNULL(CC.GradeIndicator,'') AS Indicator,
				ISNULL(CC.DescriptiveIndicator,'')  AS DescriptiveIndicator,			
				ISNULL(SA.AcademicId,0) AS AcademicId,
				CM.Id as FAID
				
						
			FROM   
				sAssessment.tCCEFAGroupMaster CGM
				INNER JOIN sAssessment.tCCEFAMaster CM ON CM.CCEFAGroupId = CGM.ID AND CM.ORGID=@rOrgId
				INNER JOIN sAssessment.tCCEFASubject FS ON FS.CCEFAGroupId = CGM.Id
				LEFT JOIN sAssessment.tCCEFAExamScore CC  ON CC.CCEFAID=CM.ID 
					AND ExamId=@rExamId AND CC.AcademicId = @rAcademicId AND
					FS.ClassSubjectId = CC.ClassSubjectId 
				LEFT JOIN sStudent.vStudentFull SA ON CC.AcademicId = SA.AcademicId  
		Where FS.ClassSubjectId  = @rClassSubjectId
				
		
			ORDER BY CGM.OrderIndex
			SELECT 1 AS RESULT
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pFAGroupMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
	       ,@rNumber int
           ,@rTitle nvarchar(100)
           ,@rGradeSetId int
           ,@rIsObsolete bit
           ,@rOrderIndex int
           ,@rUpdatedUserId bigint           
           ,@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tCCEFAGroupMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAssessment.tCCEFAGroupMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
		If Exists(select Id from sAssessment.tCCEFAGroupMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tCCEFAGroupMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAssessment.tCCEFAGroupMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sAssessment.tCCEFAGroupMaster where OrderIndex=@rOrderIndex AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEFAGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tCCEFAGroupMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Number]
			   ,[Title]
			   ,[GradeSetId]
			   ,[IsObsolete]
			   ,[OrderIndex]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rNumber
			   ,@rTitle
			   ,@rGradeSetId
			   ,@rIsObsolete
			   ,@rOrderIndex
			   ,@rUpdatedUserId
			   ,sCommon.fGetDate()			
			   ,@rOrgId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCEFAGroupMaster]
	    SET
			  Code=@rCode
			 ,Number=@rNumber
	         ,Title=@rTitle
	         ,OrderIndex=@rOrderIndex
	         ,GradeSetId=@rGradeSetId
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rUpdatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pFAGroupMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF EXISTS (SELECT CCEFAId FROM sAssessment.tCCEFAIndicatorMaster FI
			INNER JOIN sAssessment.tCCEFAMaster FM ON FI.CCEFAId=FM.Id AND FM.CCEFAGroupId = @rId)	
	  BEGIN	
			SELECT -101 AS RESULT
	  END
	ELSE IF EXISTS (SELECT Id FROM sAssessment.tCCEFASubject WHERE CCEFAGroupId = @rId)
	BEGIN
		SELECT -101 AS RESULT
	END
	ELSE
		BEGIN
			DELETE	FROM sAssessment.tCCEFAMaster WHERE CCEFAGroupId=@rId		
			DELETE FROM sAssessment.tCCEFAGroupMaster WHERE Id = @rId	
			SELECT 1 AS RESULT
			
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pFAGroupMasterGet] 
          
           --@rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100)   ,
           @rOrgId int        
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			Set @rCode = sCommon.fSearchStringGet(@rCode)
		--END

BEGIN
SELECT FGM.Id AS Id
	  ,FGM.Title AS Title
	  ,FGM.Code AS Code
	  ,FGM.Number AS Number
	  ,FGM.OrderIndex AS OrderIndex
      ,FGM.IsObsolete AS IsObsolete
     
  FROM [sAssessment].[tCCEFAGroupMaster] FGM 
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((FGM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((FGM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND FGM.OrgId=@rOrgId
	Order By FGM.OrderIndex ASC
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pFailPercentageZeroUpdate]

	 @rExamId int,
	 @rDivisionId int,
	 @rBatchId int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN  
 
 	 DECLARE @lFailePercentageZero bit
	 
	 SELECT @lFailePercentageZero = ISNULL(IsRemovePercentageForFail,0) FROM sAssessment.tExamMaster EM
	 WHERE EM.Id = @rExamId AND BatchId = @rBatchId
 	 
		
IF ( @lFailePercentageZero	= 1)
BEGIN	
    Update R Set R.Percentage=0  FROM sAssessment.tResult R
		 
		WHERE R.ResultStatus like 'FAIL'
		AND R.ExamId= @rExamId  
		AND R.AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND BatchId = @rBatchId AND StatusId=1)
	END
  
SELECT 1 AS Result
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pFAIndicatorDetailAdd]
	 
	        @rId int
           ,@rCCEFAId int
           ,@rTitle nvarchar(100)
           ,@rRemark nvarchar(200)
		   ,@rOrderIndex int		  
		   ,@rUpdatedUserId bigint
		   ,@rIsObsolete bit
		   ,@rOrgId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEFAIndicatorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCEFAIndicatorMaster]
			   (
			    [Id]
			   ,[CCEFAId]
			   ,[Title]
			   ,[Remark] 
			   ,[OrgId]
			   ,[IsObsolete]
			   ,[OrderIndex]	 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCCEFAId
			   ,@rTitle
			   ,@rRemark
			   ,@rOrgId
			   ,@rIsObsolete
			   ,@rOrderIndex
			   ,@rUpdatedUserId			   
			   ,sCommon.fGetDate()
			   ,0
			   ,0
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCEFAIndicatorMaster]
	    SET
			 
	          CCEFAId=@rCCEFAId
	         ,Title=@rTitle
	         ,Remark=@rRemark
	         ,OrgId=@rOrgId
	         ,IsObsolete=@rIsObsolete
			 ,OrderIndex=@rOrderIndex
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pFAIndicatorDetailGet]
	 @rCCEFAId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT			
			FIM.Id AS Id,
			FIM.CCEFAId AS CCEFAId,
			FIM.TITLE,
			FIM.Remark,
			FIM.OrderIndex
  FROM 
			sAssessment.[tCCEFAIndicatorMaster] FIM
WHERE 
			(FIM.CCEFAId=@rCCEFAId OR @rCCEFAId=0)  order by FIM.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pFAMasterAdd]
	 
	        @rId int
           ,@rCCEFAGroupId int
           ,@rTitle nvarchar(100)
		   ,@rRemark nvarchar(100)
		   ,@rOrderIndex int		  
		   ,@rCreatedUserId bigint
		    ,@rOrgId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEFAMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	select @rCCEFAGroupId,@rTitle,@rRemark,@rOrderIndex,@rOrgId,@rCreatedUserId,sCommon.fGetDate()
	INSERT INTO [sAssessment].[tCCEFAMaster]
			   (
			    [Id]
			   ,[CCEFAGroupId]
			   ,[Title] 
			   ,[Remark]
			   ,[OrderIndex]
			   ,[OrgId]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[IsObsolete]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCCEFAGroupId
			   ,@rTitle
			   ,@rRemark
			   ,@rOrderIndex
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,0
			   ,0
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCEFAMaster]
	    SET
			  --Number=@rNumber
	         --,Code=@rCode
	          CCEFAGroupId=@rCCEFAGroupId
	         ,Title=@rTitle
	         ,Remark=@rRemark
			 ,OrderIndex=@rOrderIndex
			 ,OrgId=@rOrgId
			 ,UpdatedUserId =@rCreatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pFAMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT Id FROM sAssessment.tCCEFAIndicatorMaster WHERE CCEFAId = @rId)	
	  BEGIN
		DELETE	FROM sAssessment.tCCEFAMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pFAMasterDetailGet]
	 @rCCEFAGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT  FGM.Id,
			FGM.Code As Code,
			FGM.Title AS Title,
			FGM.Number AS Number,
			FGM.OrderIndex AS OrderIndex,
			ISNULL(FGM.GradeSEtId,0) AS GradeSetId,
			FGM.IsObsolete AS IsObsolete,
			FM.Id AS FAMasterID,
			FM.CCEFAGroupId AS CCEFAGroupId,
			FM.TITLE AS FATitle,
			FM.Remark AS Remark,
			FM.OrderIndex AS FAOrderIndex
			
  FROM 
			[sAssessment].[tCCEFAGroupMaster] FGM
			INNER JOIN sAssessment.tCCEFAMaster FM ON FGM.Id=FM.CCEFAGroupId
WHERE 
			(FGM.Id=@rCCEFAGroupId OR @rCCEFAGroupId=0)  order by FGM.OrderIndex ASC,FM.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pFAScoreAdd]
	 
	        @rId bigint
           ,@rAcademicId bigint
           ,@rCCEFAIndicatorId bigint
           ,@rClassSubjectId bigint
		   --,@rGradeSetDetailId int
		   ,@rOrgId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEFAScore', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tCCEFAScore]
			   (
			    [Id]
			   ,[AcademicId]
			   ,[ClassSubjectId]
			   ,[CCEFAIndicatorId]
			--   ,[GradeSetDetailId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rAcademicId
			   ,@rClassSubjectId
			   ,@rCCEFAIndicatorId
		--	   ,@rGradeSetDetailId		   
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tCCEFAScore]
	    SET
			 
	          [AcademicId]=@rAcademicId
	         ,ClassSubjectId=@rClassSubjectId 
	         ,CCEFAIndicatorId=@rCCEFAIndicatorId
		--	 ,GradeSetDetailId =@rGradeSetDetailId
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pFAScoreGet]
	  @rAcademicId bigint
	 ,@rClassSubjectId bigint 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT   
            ISNULL(Score.FASCoreId,0) AS Id,
			ISNULL(FGM.Title,'') AS FAGroup,
			ISNULL(FAM.Title,'') AS FA,
			ISNULL(Score.IndicatorId,'') AS IndicatorId,
--			ISNULL(CS.GradeSetDetailId,0)  AS GradeSetDetailId,
			ISNULL(FAM.Id,0) AS FMID,
			--ISNULL(GSD.GradeSetId,0) AS GradeSetId,
			0 AS GradeSetDetailId,
			FS.ClassSubjectId
FROM		
[sAssessment].[tCCEFASubject] FS 
INNER JOIN [sAssessment].[tCCEFAGroupMaster] FGM ON  FS.CCEFAGroupId = FGM.ID
INNER JOIN [sAssessment].[tCCEFAMaster] FAM ON FAM.CCEFAGroupId = FGM.ID
INNER JOIN sSetup.tClassSubject CS ON FS.ClassSubjectId = CS.Id 

LEFT JOIN ( SELECT FAS.Id AS FASCoreId, FAM.Id AS FAId,FAS.CCEFAIndicatorId AS IndicatorId,FAS.ClassSubjectId FROM sAssessment.tCCEFAScore FAS
			INNER JOIN sAssessment.tCCEFAIndicatorMaster IM ON FAS.CCEFAIndicatorId = IM.Id
			INNER JOIN [sAssessment].[tCCEFAMaster] FAM ON IM.CCEFAId = FAM.ID
			INNER JOIN [sAssessment].[tCCEFAGroupMaster] FGM ON FAM.CCEFAGroupId = FGM.Id
			WHERE FAS.AcademicId = @rAcademicId AND FAS.ClassSubjectId = @rClassSubjectId ) SCORE			
			ON FS.ClassSubjectId = SCORE.ClassSubjectId AND FAM.Id = Score.FAId 
			
			
			
			
			--FAS.ClassSubjectId = CS.Id AND FAS.AcademicId = @rAcademicId 	
			WHERE FS.ClassSubjectId = @rClassSubjectId
			 AND CS.ClassId = (select classId from sStudent.tAcademic where Id = @rAcademicId)
			-- AND SA.StatusId=1
			ORDER BY FGM.OrderIndex,FAM.OrderIndex
END


			 

--BEGIN 	
--IF EXISTS (SELECT Id FROM [sAssessment].[tCCEFAScore]  WHERE AcademicId=@rAcademicId AND ClassSubjectId=@rClassSubjectId)
--BEGIN
--SELECT      ISNULL(CS.Id,0) AS Id,
--			ISNULL(CGM.Title,'') AS FAGroup,
--			ISNULL(CM.Title,'') AS FA,
--			ISNULL(CS.CCEFAIndicatorId,'') AS IndicatorId,
--			--ISNULL(CS.GradeSetDetailId,0)  AS GradeSetDetailId,
--			ISNULL(CM.Id,0) AS FMID,
--			--ISNULL(GSD.GradeSetId,0) AS GradeSetId,
--			CC.ClassSubjectId
--FROM		
--			[sAssessment].[tCCEFAScore] CS
--			LEFT JOIN [sStudent].[vStudentAcademic] SA ON SA.AcademicId = CS.AcademicId  
--			RIGHT JOIN [sAssessment].[tCCEFASubject] CC ON CC.ClassSubjectId = cs.ClassSubjectId
--			INNER JOIN [sAssessment].[tCCEFAGroupMaster] CGM ON CGM.Id = CC.CCEFAGroupId
--			INNER JOIN [sAssessment].[tCCEFAMaster] CM ON CM.CCEFAGroupId = CGM.ID
--			LEFT JOIN [sAssessment].[tCCECSIndicatorMaster] CIM ON CIM.CCECSId=CM.Id AND CS.CCEFAIndicatorId=CIM.Id
--			--LEFT JOIN [sAssessment].[tGradeSetDetail] GSD ON CS.GradeSetDetailId=GSD.Id			
--			WHERE CC.ClassSubjectId = @rClassSubjectId AND SA.AcademicId = @rAcademicId AND SA.StatusId=1
--			ORDER BY CGM.OrderIndex,CM.OrderIndex
--END
--ELSE
--BEGIN


--SELECT   
--            ISNULL(Score.FASCoreId,0) AS Id,
--			ISNULL(FGM.Title,'') AS FAGroup,
--			ISNULL(FAM.Title,'') AS FA,
--			ISNULL(Score.IndicatorId,'') AS IndicatorId,
----			ISNULL(CS.GradeSetDetailId,0)  AS GradeSetDetailId,
--			ISNULL(FAM.Id,0) AS FMID,
--			--ISNULL(GSD.GradeSetId,0) AS GradeSetId,
--			0 AS GradeSetDetailId,
--			FS.ClassSubjectId
--FROM		
--[sAssessment].[tCCEFASubject] FS 
--INNER JOIN [sAssessment].[tCCEFAGroupMaster] FGM ON  FS.CCEFAGroupId = FGM.ID
--INNER JOIN [sAssessment].[tCCEFAMaster] FAM ON FAM.CCEFAGroupId = FGM.ID
--INNER JOIN sSetup.tClassSubject CS ON FS.ClassSubjectId = CS.Id 

--LEFT JOIN ( SELECT FAS.Id AS FASCoreId, FAM.Id AS FAId,FAS.CCEFAIndicatorId AS IndicatorId,FAS.ClassSubjectId FROM sAssessment.tCCEFAScore FAS
--			INNER JOIN sAssessment.tCCEFAIndicatorMaster IM ON FAS.CCEFAIndicatorId = IM.Id
--			INNER JOIN [sAssessment].[tCCEFAMaster] FAM ON IM.CCEFAId = FAM.ID
--			INNER JOIN [sAssessment].[tCCEFAGroupMaster] FGM ON FAM.CCEFAGroupId = FGM.Id
--			WHERE FAS.AcademicId = @rAcademicId AND FAS.ClassSubjectId = @rClassSubjectId ) SCORE			
--			ON FS.ClassSubjectId = SCORE.ClassSubjectId AND FAM.Id = Score.FAId 
			
			
			
			
--			--FAS.ClassSubjectId = CS.Id AND FAS.AcademicId = @rAcademicId 	
--			WHERE FS.ClassSubjectId = @rClassSubjectId
--			 AND CS.ClassId = (select classId from sStudent.tAcademic where Id = @rAcademicId)
--			-- AND SA.StatusId=1
--			ORDER BY FGM.OrderIndex,FAM.OrderIndex
--END
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pFASubjectAdd]
	 
	  
           @rCCEFAGroupId int
          ,@rClassSubjectId int
		  ,@rSchilasticSubjectsDetailXml nvarchar(max)
		  
		  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rSchilasticSubjectsDetailXml

BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	-- DECLARE @lNextNumber BIGINT 
--IF(@rId = 0)	
--BEGIN
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCEFASubject', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	DELETE FROM [sAssessment].[tCCEFASubject] WHERE ClassSubjectId = @rClassSubjectId 
	--AND CCEFAGroupId = @rCCEFAGroupId

INSERT INTO sAssessment.tCCEFASubject
		(
			CCEFAGroupId,
			ClassSubjectId,
			OrderIndex,
			UpdatedUserId,
			UpdatedDateTime
			
			)
		SELECT		
			CCEFAGroupId,
			ClassSubjectId,
			OrderIndex,
			UpdatedUserId,
			sCommon.fGetDate()
			
		FROM OPENXML (@loDoc, '/Table/SchilasticSubjectsDetail', 1)
		WITH ( 
				CCEFAGroupId int,
				ClassSubjectId int,
				OrderIndex smallint,
				UpdatedUserId bigint
				
			  ) 
		
        SELECT 1 AS Result
	
	--	--COMMIT TRANSACTION         
	--END	 
--ELSE
-- BEGIN
--   IF @rIsDeleted = 1
--	 BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  [sAssessment].[tCCEFASubject]
--	    SET
			 
--	          [CCEFAGroupId]=@rCCEFAGroupId
--	         ,ClassSubjectId=@rClassSubjectId
--			 ,UpdatedUserId =@rUpdatedUserId
--			 ,UpdatedDateTime=sCommon.fGetDate()
--	      WHERE Id = @rId 	   
--	      SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION
--	 END  
--   ELSE IF EXISTS (SELECT * FROM sAssessment.tCCEFAScore CS 
--				   INNER JOIN sAssessment.tCCEFAIndicatorMaster CIM ON CS.CCEFAIndicatorId=CIM.Id
--				   INNER JOIN sAssessment.tCCEFAMaster CM ON CM.Id = CIM.CCEFAId
--				   INNER JOIN sAssessment.tCCEFAGroupMaster CGM ON CGM.Id = CM.CCEFAGroupId AND CGM.Id = @rCCEFAGroupId)
--	  BEGIN
--		SELECT -101 AS RESULT
--	  END	  	
--   ELSE
--	BEGIN
--		DELETE FROM sAssessment.tCCECSClass WHERE Id = @rId
--		SELECT 1 AS RESULT
--	END			
--  END
----END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pFASubjectGet]
	  @rClassSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
SELECT 
			ISNULL(FS.Id,0) AS Id,
			ISNULL(FGM.ID,0) AS CCEFAGroupId,
			ISNULL(FS.ClassSubjectId,0) AS ClassSubjectId,	
			ISNULL(FS.OrderIndex,0) AS OrderIndex,			
			FGM.Title AS FAGroupName,
			CASE WHEN ISNULL(ClassSubjectId,0)=0 THEN 'false' ELSE 'true' END AS Selected
FROM 
	sAssessment.tCCEFASubject FS
	RIGHT JOIN sAssessment.tCCEFAGroupMaster FGM ON FGM.Id=FS.CCEFAGroupId 
	AND (FS.ClassSubjectId=@rClassSubjectId OR @rClassSubjectId=0)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pGeneralExamColumnNameGet]

AS
SET NOCOUNT ON

BEGIN
		Select COLUMN_NAME AS ColumnName from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sAssessment' AND TABLE_NAME='vGeneralExamColumnName'
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pGeneralExamCustomReportListGet]
	@rCreatedUserId bigint,
	@rOrgId smallint
AS
SET NOCOUNT ON

BEGIN
		SELECT 
			ECS.Id,
			ECS.Title,
			ECS.ColumnName,
			U.DisplayTitle AS CreatedUserName,
			CASE WHEN ECS.CreatedUserId = @rCreatedUserId THEN 'true' ELSE 'false' END AS IsDelete
		FROM sAssessment.tGeneralExamCustomSearch ECS
		INNER JOIN sSecurity.tUser U ON U.Id=ECS.CreatedUserId
		WHERE 
			    ((ECS.CreatedUserId = @rCreatedUserId) OR (ECS.IsCommon = 1))
			AND ECS.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pGeneralExamCustomSearchGet]
(
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rPageIndex int = null,
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int,
	@rDepartmentId int=0,
	@rCastCategoryId nvarchar(max) = ''
 )
AS
SET NOCOUNT ON
BEGIN
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
	
	
	SELECT ECS.* into #TempExam11
	FROM sAssessment.vGeneralExamCustomSearch ECS
	--INNER Join sSetup.tClassSubject CS ON ECS.ClassId=CS.ClassId				
 --   INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id AND SM.OrgId = ECS.OrgId		
	WHERE (ECS.OrgId = @rOrgId) AND (ECS.BatchId = @rBatchId)
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
	AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
	AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
	AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
	AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
	AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
	AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
	AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
	AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
	AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
	AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
	AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	AND ((ECS.DepartmentId =@rDepartmentId) OR (@rDepartmentId =0))
	AND (ISNULL(ECS.CastCategoryId,'') IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
	SET @sql='SELECT Code AS Code,Name,ClassName,RollNo,TotalMarks,TotalObtain,
	ResultStatus,ResultGrade,ResultGradePoint,RankNumber,Percentage,Percentile,
	ResultReMark,OtherRemark1,ExamName FROM #TempExam11 ORDER BY ' + @rOrderBy
	
	exec(@Sql)
	
	create table #TEMPExam
	(
		tid int identity(1,1),t_AcedemicId bigint,t_ResultId bigint
	)
	SET @sql='insert into #TEMPExam SELECT AcademicId,ResultId FROM #TempExam11 ORDER BY ' + @rOrderBy

	exec (@sql)

	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',@lResult varchar(max)=''
	
	select @lTotalRecords = count(*) from #TEMPExam
	select @lPaging = @lPaging + dbo.fnc_searchpagingformat(@rPageIndex,@lTotalRecords,@lPageSize)
	 
	select @lResult = @lResult + '<tr><td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
	<td>' + isnull(convert(varchar,RollNo),'') + '</td><td>' + isnull(ExamName,'') + '</td>
	<td>' + isnull(convert(varchar,TotalMarks),'') + '</td><td>' + isnull(convert(varchar,TotalObtain),'') + '</td>
	<td>' + isnull(ResultStatus,'') + '</td><td>' + isnull(ResultGrade,'') + '</td>

	<td>' + isnull(convert(varchar,RankNumber),'') + '</td>
	<td>' + isnull(convert(varchar,Percentage),'') + '</td><td>' + isnull(convert(varchar,Percentile),'') + '</td>
	<td>' + isnull(ResultReMark,'') + '</td><td>' + isnull(OtherRemark1,'') + '</td></tr>' 
	from #TempExam11,#TEMPExam
	where AcademicId = t_AcedemicId and  ResultId = t_ResultId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	Order By tid
	
	select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP table #TEMPExam
	DROP Table #TempExam11
	
		--<td>' + isnull(convert(varchar,ResultGradePoint),'') + '</td>
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAssessment].[pGeneralExamGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rBatchId int,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int,
	@rCastCategoryId nvarchar(max) = ''
	--@rSubjectId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	      
	 BEGIN TRANSACTION	
	 
  IF OBJECT_ID('sAssessment.tTempGeneralExam1', 'U') IS NOT NULL
  DROP TABLE sAssessment.tTempGeneralExam1; 
  
  IF OBJECT_ID('sAssessment.tTempGeneralExam', 'U') IS NOT NULL
  DROP TABLE sAssessment.tTempGeneralExam; 

	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tGeneralExamCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAssessment.tGeneralExamCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgId,
			BatchId,
			Code,
			FirstName,	
			LastName,
			DivisionId,
			ExamId,
			FromMarks,
			ToMarks,
			FromGradePoint,
			ToGradePoint,
			FromRankNumber,
			ToRankNumber,
			FromPercentage,
			ToPercentage,
			FromPercentile,
			ToPercentile,
			ResultGrade,
			IsCommon,
			CreatedUserId,
			CreatedDateTime,
			ClassId,
			ExamSubGroupId
			--SubjectId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgId,
			@rBatchId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rDivisionId,
			@rExamId,
			@rFromMarks,
			@rToMarks,
			@rFromGradePoint,
			@rToGradePoint,
			@rFromRankNumber,
			@rToRankNumber,
			@rFromPercentage,
			@rToPercentage,
			@rFromPercentile,
			@rToPercentile,
			@rResultGrade,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rDropDownClassId,
			@rDropDownExamSubGroupId
			--@rSubjectId
		)
		--SELECT @lNextNumber AS Result
	END
	 
	SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rDivisionId=DivisionId,
				@rExamId=ExamId,
				@rFromMarks=FromMarks,
				@rToMarks=ToMarks,
				@rFromGradePoint=FromGradePoint,
				@rToGradePoint=ToGradePoint,
				@rFromRankNumber=FromRankNumber,
				@rToRankNumber=ToRankNumber,
				@rFromPercentage=FromPercentage,
				@rToPercentage=ToPercentage,
				@rFromPercentile=FromPercentile,
				@rToPercentile=ToPercentile,
				@rResultGrade=ResultGrade,
				@rDropDownClassId = ClassId,
				@rDropDownExamSubGroupId = ExamSubGroupId
				--@rSubjectId=SubjectId
				
		FROM
			sAssessment.tGeneralExamCustomSearch
		WHERE
			Id=@rId
	END
	 SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	 
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
	
	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
	SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Title,'[]'), '' AS AcademicId, '' AS ExamSubGroupId
					FROM sAssessment.tExamMaster EM 
					INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
                    INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id AND RD.ExamDetailId = ED.Id
					INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = EM.ClassId
					INNER JOIN sSetup.tSubjectMaster CM ON CM.Id = CS.SubjectId
					WHERE EM.ExamSubGroupId = @rDropDownExamSubGroupId AND EM.BatchId = @rBatchId
					group by CM.Title
                    order by CM.Title	
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       --Select @cols
      IF(@cols IS NOT NULL)
      BEGIN
	  set @query = 'SELECT ExamSubGroupId AS ExamSubGroupId1, AcademicId AS AcademicId1 ,' + @cols + ' into sAssessment.tTempGeneralExam1 FROM 
             (
                    SELECT EM.ExamSubGroupId,R.AcademicId,RD.Obtain,CM.Title
                    FROM 
                    sAssessment.tExamMaster EM 
					INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
                    INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id AND RD.ExamDetailId = ED.Id
					INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = EM.ClassId AND ED.ClassSubjectId = CS.Id
					INNER JOIN sSetup.tSubjectMaster CM ON CM.Id = CS.SubjectId
					WHERE EM.ExamSubGroupId = '+CONVERT(nvarchar,@rDropDownExamSubGroupId)+' AND EM.BatchId = '+CONVERT(nvarchar,@rBatchId)+'
            ) x 
            pivot 
            (
                SUM(Obtain)
                for  Title in (' +@cols  + ')
            ) p '
	    execute(@query)
		--Select * from sAssessment.tTempGeneralExam1
	    SELECT 
				*
		into sAssessment.tTempGeneralExam
		FROM sAssessment.vGeneralExamCustomSearch ECS
		INNER JOIN sAssessment.tTempGeneralExam1 T ON ECS.AcademicId = T.AcademicId1 AND ECS.ExamSubGroupId =  T.ExamSubGroupId1
		
		WHERE 
				(ECS.OrgId = @rOrgId)
			AND (ECS.BatchId = @rBatchId)
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
			AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
			AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
			AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
			AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
			AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
			AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
			AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
			AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
			AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
			AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
			
		    AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')	
	        --AND ((ECS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
			AND ((ECS.CastCategoryId IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,',')))OR (ISNULL(@rCastCategoryId,'')=''))
			--AND ((ECS.SubjectId = @rSubjectId)OR(@rSubjectId = 0))
			
			--select * from sAssessment.tTempGeneralExam
	   END 
	   ELSE
	   
	   BEGIN 
	     SELECT 
				*
		into sAssessment.tTempGeneralExam
		FROM sAssessment.vGeneralExamCustomSearch ECS
	
		WHERE 
				(ECS.OrgId = @rOrgId)
			AND (ECS.BatchId = @rBatchId)
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
			AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
			AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
			AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
			AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
			AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
			AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
			AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
			AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
			AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
			AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
			
		    AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')	
	        --AND ((ECS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
			AND ((ECS.CastCategoryId IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,',')))OR (ISNULL(@rCastCategoryId,'')=''))
			--AND ((ECS.SubjectId = @rSubjectId)OR(@rSubjectId = 0))
		
	   END
		SET @sql=
		'SELECT '+ @rColumnName+' FROM sAssessment.tTempGeneralExam ORDER BY '+@rOrderBy
		exec(@Sql)
		
		DROP Table sAssessment.tTempGeneralExam
		
		IF(@cols IS NOT NULL)
		BEGIN
			DROP Table sAssessment.tTempGeneralExam1
		END
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sAssessment].[pGenerateResultSheetStandardMultiExam]
	 
	 @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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0
	
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam

 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

 

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2),
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		 ParentSignCaption nvarchar(100),
		 ImprovementArea nvarchar(200),
		 ProgressArea nvarchar(200),
		 GeneralRemark nvarchar(200),
		 MyActivity nvarchar(200),
		 ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2)
	)	
	 --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,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
   IsShowWithDetail,
 IsPresent,
 GradeTitle,
	
	 SubjectHighestDivisionGrade,
	 SubjectHighestDivisionMark
	)
	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,
		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,
		@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),
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark 
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.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
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.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 sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 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.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		AND ISNULL(EMP.IsOtherUser,0) = 0 
	 
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--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)+'=RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					  TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code					 
					 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 = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

  --end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [sAssessment].[pRptResultSheetStandardMultiExamGet] @rFromRank=0,@rGrade=N'',@rBuilder2=N'',@rCode=N'',@rFromRollNo=0,@rToRollNo=0,@rBuilder1=N'<b>Exam : </b>FA_U_1<br><br>',@rBatchId=110100101,@rClassId=110100001,@rDivisionId=110100001,@rSubjectId=0,@rExamId=110100164,@rStatusId=1

--EXEC [sAssessment].[pGenerateResultSheetStandardMultiExamNEW] @rBatchId=110100101,@rClassId=110100001,@rDivisionId=110100001,@rExamId=110100164,@rStatusId=1
 
CREATE OR ALTER PROCEDURE [sAssessment].[pGenerateResultSheetStandardMultiExamNEW]
	 
		@rBatchId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rExamId int,
		@rStatusId int=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
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

DELETE FROM sAssessment.tTempAllExam 
--#TempAllExam  	
	INSERT INTO  sAssessment.tTempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	Percentile,
	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,
	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,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	HouseRemark,
	BloodGroup,
	BatchIdText,
   IsShowWithDetail,
	 IsPresent,
	 GradeTitle,
	 SubjectHighestDivisionGrade,
	 SubjectHighestDivisionMark
	)
	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,
		R.Percentile,
		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,
		(CASE ISNULL(ED.DisplayOrder,0) WHEN 0 THEN CS.OrderIndex	ELSE ED.DisplayOrder END) 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,
		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,
		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,
		0 AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		RD.GraceMark,
		@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),
		0 AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark 
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.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
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.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
	 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 ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
	AND ISNULL(EMP.IsOtherUser,0) = 0
	Order By ED.DisplayOrder
 
	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
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam

	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					  TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code					 
					 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 	sAssessment.tTempAllExam  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
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	sAssessment.tTempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	SELECT  T.*	FROM sAssessment.tTempAllExam  T
		
	drop table #tempcombineExam
	--Drop table TempAllExam
	END

  --end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE OR ALTER PROCEDURE  [sAssessment].[pGetExamWiseSubjectLists]
	@rExamId int,
	@rClassId int,
	@rBatchId int
AS
BEGIN
declare @lSubjectNames nvarchar(max)=''
SELECT @lSubjectNames =
STUFF(
--(SELECT ' ' + '<option value="'+ replace(SM.Title,' ','') +'">' +replace(SM.Title,' ','')+'</option>'
(SELECT ' ' + '<option>' + '{' + SM.Title + '}' +'</option>'
FROM 
	sAssessment.tExamMaster EM
	INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
	INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
	INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
	INNER JOIN sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
	INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id	
	INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
	Where ESGM.Id = @rExamId AND CM.Id = @rClassId AND EM.BatchId = @rBatchId
FOR XML PATH (''))
, 1, 1, '')
Select [sCommon].[fXMLTagsReplaceReverse](@lSubjectNames) AS SubjectNames
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetClassSubjectDetailAdd]
	 
	        @rId int,
            @rGradeSetDetailId int,
			@rGradeSetClassSubjectId int,
			@rGradeRemark nvarchar(200),
			@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 DECLARE @lNextNumber BIGINT 
	 
	 DELETE From sAssessment.tGradeSetClassSubjectDetail Where GradeSetDetailId = @rGradeSetDetailId AND GradeSetClassSubjectId = @rGradeSetClassSubjectId

IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tGradeSetClassSubjectDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	
    INSERT INTO sAssessment.tGradeSetClassSubjectDetail
	   (
	    Id,
	    GradeSetDetailId,
	    GradeSetClassSubjectId,
	    GradeRemark
	   )
	VALUES
	   (
		@lNextNumber,
	    @rGradeSetDetailId,
	    @rGradeSetClassSubjectId,
	    @rGradeRemark
	   )
    SELECT @lNextNumber AS Result
	
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetClassSubjectDetailGet]
	
	 @rGradeSetId int,
	 @rClassId int,
	 @rSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

-- used In Sub report to display grade based on gradesetId			 

BEGIN 		
		
	SELECT 
			GCSM.Id AS GradeSetClassSubjectId, 
			GCSM.ClassId,	
			GCSM.SubjectId,
			GCSM.OrgId,
			GCSM.GradeSetId,
			ISNULL(GCSD.GradeRemark,'') AS GradeRemark,
			ISNULL(GCSD.GradeSetDetailId,'') AS GradeSetDetailId
    FROM 
			sAssessment.tGradeSetClassSubjectMaster GCSM
			INNER JOIN sAssessment.tGradeSetDetail GSD ON GSD.GradeSetId = GCSM.GradeSetId
			INNER JOIN sAssessment.tGradeSetClassSubjectDetail GCSD ON GCSD.GradeSetDetailId = GSD.Id
			AND GCSD.GradeSetClassSubjectId = GCSM.Id
    WHERE 
			((GCSM.GradeSetId=@rGradeSetId) OR (@rGradeSetId = 0))
			AND ((GCSM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((GCSM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			 
    ORDER BY GCSD.GradeSetClassSubjectId Desc
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetClassSubjectMasterAdd]
	 
			@rId int,
	        @rOrgId int,
            @rClassId int = 0,
            @rSubjectId int = 0,
			@rGradeSetId int = 0,
			@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DELETE sAssessment.tGradeSetClassSubjectMaster WHERE OrgId = @rOrgId AND ClassId=@rClassId AND SubjectId=@rSubjectId AND GradeSetId = @rGradeSetId 
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tGradeSetClassSubjectMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sAssessment.tGradeSetClassSubjectMaster
			   (
			    Id,
				OrgId,
				GradeSetId,
				ClassId,
				SubjectId,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime
			   )
		 VALUES
			   (
				@lNextNumber,
				@rOrgId,
				@rGradeSetId,
				@rClassId,
				@rSubjectId,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    0,
			    sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetClassSubjectMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF EXISTS (SELECT 1 FROM sAssessment.tExamMaster WHERE GradeSetId= @rId)	
		BEGIN
			SELECT -101 AS RESULT
			RETURN
		END
	IF Exists (Select 1 From sAssessment.tCCECSGroupMaster Where GradeSetId = @rId) 
		BEGIN
			SELECT -101 AS RESULT
			RETURN
		END
	IF EXISTS (SELECT 1 FROM sAssessment.tExamDetail WHERE GradeSetId= @rId)	
		BEGIN
			SELECT -101 AS RESULT
			RETURN
		END

	  BEGIN
		DELETE FROM sAssessment.tGradeSetClassSubjectDetail WHERE GradeSetClassSubjectId IN (SELECT ID FROM sAssessment.tGradeSetClassSubjectMaster WHERE ID=@rId)
		DELETE	FROM sAssessment.tGradeSetClassSubjectMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetClassSubjectMasterGet]
          
   @rGradeSetId int,
   @rClassId int,
   @rOrgId int,
   @rSubjectId int           
          
AS
SET NOCOUNT ON

BEGIN

  SELECT
       GCSM.Id AS Id,
	   GSM.Title AS GradeSetName,
	   GCSM.GradeSetId,
	   GCSM.ClassId,
	   GCSM.SubjectId,
	   GCSM.OrgId,
	   GCSM.Id AS GradeSetClassSubjectId,
	   CM.Title AS ClassName,
	   SM.Title AS SubjectName

  FROM  
       sAssessment.tGradeSetClassSubjectMaster GCSM 
       INNER JOIN sAssessment.tGradeSetMaster GSM ON GSM.Id = GCSM.GradeSetId
	   INNER JOIN sSetup.tClassMaster CM ON GCSM.ClassId = CM.Id
	   INNER JOIN sSetup.tSubjectMaster SM ON GCSM.SubjectId = SM.Id
        
  WHERE 
	   ((GCSM.OrgId = @rOrgId) OR (@rOrgId = 0))
       AND ((ClassId = @rClassId) OR (@rClassId = 0))
	   AND ((SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	   AND ((GradeSetId = @rGradeSetId) OR (@rGradeSetId = 0))  
	   
  ORDER BY GCSM.Id
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetCoScholasticDetailGet]
	 --@rGradeSetId int,
	 @rCCEExamId int,
	 @rBatchId int,
	 @rClassId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

-- used In Sub report to display grade based on gradesetId			 

BEGIN 		

DECLARE @rExamId int,@rGradeSetId int
	SELECT @rExamId = EM.Id FROM	sAssessment.tCCEExamSetting CS INNER JOIN sAssessment.tExamMaster EM
	ON CS.ExamSubGroupId = 	EM.ExamSubGroupId AND CS.ClassId = EM.ClassId AND CS.BatchId = EM.BatchId
	  WHERE Cs.CCEExamId = @rCCEExamId AND CS.BatchId = @rBatchId AND Cs.ClassId = @rClassId
		
		SELECT Distinct @rGradeSetId = CG.GradeSetId  from  sAssessment.tCCECSExamScore ES INNER JOIN sAssessment.tCCECSMaster CM ON ES.cceCsId = CM.Id
		INNER JOIN sAssessment.tCCECSGroupMaster CG ON CM.CCECAGroupId = CG.Id WHERE ES.ExamId = @rExamId
		
		
	SELECT 
			distinct(GM.Id),
			Convert(nvarchar(20),cceCES.ExamId) AS  ExamIdText,
			
			GM.TITLE,
			GM.Code,
			GMD.GradeCode,
			GMD.GradeTitle,
			GMD.MinimumScore,
			GMD.GradePoint,
			GM.IsObsolete
			
  FROM 
			[sAssessment].[tGradeSetMaster] GM
			INNER JOIN sAssessment.tGradeSetDetail GMD ON GMD.GradeSetId=GM.id
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.GradeSetId = Gm.Id
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.CCECAGroupId = cceCSGM.Id
			INNER JOIN sAssessment.tCCECSExamScore cceCES ON cceCES.CCECSId = cceCSM.Id
			--INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCES.ExamId 
		 WHERE
			 
			--(GMD.GradeSetId=@rGradeSetId OR @rGradeSetId=0)
			   cceCES.ExamId = @rCCEExamId OR @rCCEExamId= 0 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetDetailAdd]
	 
	        @rId int
           ,@rGradeSetId int
           ,@rMinimumScore decimal(12,2)
		   ,@rGradeCode nvarchar(20)
		   ,@rGradeTitle nvarchar(50)
		   ,@rGradePoint decimal(6,2)
		   ,@rOrgId int,
		   @rMarkRange nvarchar(50)
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
--If(@rIsDeleted=1)
--BEGIN
--	Delete from sFee.tChargeMaster where Id=@rId
--	Select @rId as Result
--END	
--ELSE
--BEGIN     
	
--If Exists(select top(1)* from sFee.tChargeMaster where Title=@rTitle AND OrgId=@rOrgId)
--BEGIN
--	If NOT Exists(select top(1)* from sFee.tChargeMaster where Title=@rTitle AND OrgId=@rOrgId AND Id=@rId)
--	BEGIN
--		select -101 as Result
--	END
--	ELSE
--	BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  [sFee].[tChargeMaster]
--	    SET
--			  --Number=@rNumber
--	         --,Code=@rCode
--	         Title=@rTitle
--	         ,ChargeCategoryId=@rChargeCategoryId
--	         ,ChargeAmount=@rChargeAmount
--	         ,OrderIndex=@rOrderIndex
--             ,[IsObsolete] = @rIsObsolete                          
--             ,[UpdatedUserId] = @rCreatedUserId
--             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
--	      WHERE Id = @rId 	 
--	      SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION  
--	 END  
--END
--ELSE
--BEGIN
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tGradeSetDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tGradeSetDetail]
			   (
			    [Id]
			   ,[GradeSetId] 
			   ,[MinimumScore] 
			   ,[GradeCode]
			   ,[GradeTitle]
			   ,[GradePoint],
			   MarkRange
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rGradeSetId
			   ,@rMinimumScore
			   ,@rGradeCode
			   ,@rGradeTitle
			   ,@rGradePoint,
			   @rMarkRange
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tGradeSetDetail]
	    SET
			  --Number=@rNumber
	         --,Code=@rCode
	          GradeSetId=@rGradeSetId
	         ,MinimumScore=@rMinimumScore
	         ,GradeCode=@rGradeCode
			 ,GradeTitle=@rGradeTitle
			 ,GradePoint =@rGradePoint,
			 MarkRange = @rMarkRange             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetDetailGet]
	 @rGradeSetId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

-- used In Sub report to display grade based on gradesetId			 

BEGIN 		
		
	SELECT 
			Convert(nvarchar(20),GMD.GradeSetId) AS  GradeSetIdText,	
			GM.TITLE,
			GM.Code,
			GMD.GradeSetId,
			GMD.Id,
			GMD.GradeCode,
			GMD.GradeTitle,
			GMD.MinimumScore,
			GMD.GradePoint,
			GM.IsObsolete,
			ISNULL(GMD.MarkRange,'') AS MarkRange,
			ISNULL(GM.GradeStringHtml,'') AS GradeStringHtml,
			ISNULL(GM.GradeStringText,'') AS GradeStringText
			
  FROM 
			[sAssessment].[tGradeSetMaster] GM
			INNER JOIN sAssessment.tGradeSetDetail GMD ON GMD.GradeSetId=GM.id
WHERE 
			(GMD.GradeSetId=@rGradeSetId)  order by GMD.MinimumScore Desc
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgId int,
           @rGradeStringHtml nvarchar(1000)='',
           @rGradeStringText nvarchar(1000)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tGradeSetMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAssessment.tGradeSetMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tGradeSetMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAssessment.tGradeSetMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tGradeSetMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tGradeSetMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId],
			   GradeStringHtml,
			   GradeStringText
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId,
			   @rGradeStringHtml,
			   @rGradeStringText
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tGradeSetMaster]
	    SET
			  Code=@rCode
	         ,Title=@rTitle
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate(),
             GradeStringHtml =@rGradeStringHtml,
             GradeStringText = @rGradeStringText          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF EXISTS (SELECT 1 FROM sAssessment.tExamMaster WHERE GradeSetId= @rId)	
		BEGIN
			SELECT -101 AS RESULT
			RETURN
		END
	IF Exists (Select 1 From sAssessment.tCCECSGroupMaster Where GradeSetId = @rId) 
		BEGIN
			SELECT -101 AS RESULT
			RETURN
		END
	IF EXISTS (SELECT 1 FROM sAssessment.tExamDetail WHERE GradeSetId= @rId)	
		BEGIN
			SELECT -101 AS RESULT
			RETURN
		END

	  BEGIN
		DELETE FROM sAssessment.tGradeSetDetail WHERE GradeSetId IN (SELECT ID FROM sAssessment.tGradeSetMaster WHERE ID=@rId)
		DELETE	FROM sAssessment.tGradeSetMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pGradeSetMasterGet]
          
           --@rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgId int           
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			Set @rCode = sCommon.fSearchStringGet(@rCode)
		--END

BEGIN
SELECT GM.Id as GradeSetId
	  ,GM.Title as Title
	  ,GM.Code as Code
      ,GM.IsObsolete as IsObsolete,
      GM.GradeStringHtml,
      GM.GradeStringtext
     
  FROM [sAssessment].[tGradeSetMaster] GM 
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((GM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND OrgId = @rOrgId

	--AND  CCM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAssessment].[pGraphicalTeacherEvaluationAnalysisGet]
	 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rGroupByid int=0,
	 @rEmployeeId bigint=0
 	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Sm.OrderIndex As SubjectOrderIndex,
		case when @rGroupByid=1 THEN Dm.Id
		when @rGroupByid=2 THEN CM.Classid
		when @rGroupByid=3 THEN CM.DepartmentId
	    when @rGroupByid=4 THEN OM.Id
		ELSE 0  END  AS HeadId,
		case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle   
		when @rGroupByid=2 THEN ' Class : ' + CM.ClassName 
		when @rGroupByid=3 THEN 'Department: ' + DP.Title 
		WHen @rGroupByid=4 THen  'Organization : '+Om.Title END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN DP.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
		

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
		INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.EmployeeId=@rEmployeeId
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
	  AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND TS.EmployeeId=@rEmployeeId) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	 INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	 INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	 INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.EmployeeId=@rEmployeeId
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND TS.EmployeeId=@rEmployeeId) AS FailStudent 
	  
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	 INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
    --INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.EmployeeId=@rEmployeeId
INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId And TS.EMployeeID=@rEmployeeId AND TS.DivisionId=DM.ID
		WHERE 
			((DM.ID=@rDivisionId) or (@rDivisionId=0))
			AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
			AND CM.BatchId=@rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
			AND EM.BatchId = @rBatchId
			AND TS.EmployeeId=@rEmployeeId
 -- UNION ALL
  
  
 -- 	 select 
	--	@rBuilder1 AS Builder1,
	--	DM.Classid As ClassId,
	--	Dm.id As DivisionId,
	--	--Cm.ClassName As Classname,
	--	--DM.DisplayTitle As DivisionName,
	--0 AS ClassSubjectId,
	--	0 AS SubjectId,
	--	'Over All' AS SubjectName,
	--	0 AS ClassOrderIndex,
	--	case when @rGroupByid=1 THEN Dm.Id
	--	when @rGroupByid=2 THEN CM.Classid
	--	when @rGroupByid=3 THEN CM.DepartmentId
	--    when @rGroupByid=4 THEN OM.Id
	--	ELSE 0    END  AS HeadId,
	--	case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle  
	--	when @rGroupByid=2 THEN ' Class : ' + CM.ClassName  
	--	when @rGroupByid=3 THEN 'Department: ' + DP.Title 
	--	WHen @rGroupByid=4 THEN  'Organization : '+OM.Title
	--	END  AS HeadName,
	--	CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
	--			WHEN @rGroupByid=2  THEN CM.OrderIndex
	--			WHEN @rGroupByid=3  THEN DP.Id
	--			WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
	 

 --(select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND R.ResultStatus='PASS') AS PassStudent,
	  
	--  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent 
	  
	-- from
	-- ssetup.tDivisionMaster DM
	-- INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	-- INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	--INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	-- INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	-- INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
 --   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
 --   INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.EmployeeId=@rEmployeeId
	--	WHERE 
	--		((DM.ID=@rDivisionId) or (@rDivisionId=0))
	--		AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
	--		AND CM.BatchId=@rBatchId
	--		AND EM.ExamSubGroupId = @rExamSubGroupId
	--		AND EM.BatchId = @rBatchId
	--		AND TS.EmployeeId=@rEmployeeId
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pGraphPassFailAnalysisSubjectWise]
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)=''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	

	 select 
		--@rBuilder1 AS Builder1,
		--Cm.Classid As ClassId,
		--Dm.id As DivisionId,
		--Cm.ClassName As Classname,
		--DM.DisplayTitle As DivisionName,
		--CS.Id AS ClassSubjectId,
		--SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		--Sm.OrderIndex As SubjectOrderIndex,
		--DM.OrderIndex AS DivisionOrderIndex,
		--CM.OrderIndex AS ClassOrderIndex,
	 

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	   INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id 
	   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
	  AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum) AS FailStudent 
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId

		WHERE 
			((DM.ID=@rDivisionId) or (@rDivisionId=0))
			AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
			AND CM.BatchId=@rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
			AND EM.BatchId = @rBatchId
			AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	
  UNION ALL
  
  
  	 select 
	--	@rBuilder1 AS Builder1,
	--	DM.Classid As ClassId,
	--	Dm.id As DivisionId,
	--	Cm.ClassName As Classname,
	--	DM.DisplayTitle As DivisionName,
	--0 AS ClassSubjectId,
	--	0 AS SubjectId,
		'Over All' AS SubjectName,
		--0 As SubjectOrderIndex,
		--0 AS DivisionOrderIndex,
		--0 AS ClassOrderIndex,

   (select COUNT(R.AcademicId) from   sAssessment.tResult R  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId	 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND R.ResultStatus='PASS') AS PassStudent,
	  (select COUNT(R.AcademicId) from   sAssessment.tResult R   
	  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId
	   AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent 
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	 INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
		WHERE 
			((DM.ID=@rDivisionId) or (@rDivisionId=0))
			AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
			AND CM.BatchId=@rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
			AND EM.BatchId = @rBatchId
			 AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pGSEBExamCombineGet]
	 @rClassId int
	,@rExamId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	SELECT 
	EC.SubExamId AS SubExamId,
	EM.ClassId AS ClassId,
	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
			INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId=EM.Id
WHERE 
			(EM.ClassId=@rClassId OR @rClassId=0)  
			AND EC.ExamId = @rExamId
			ORDER BY EC.ExamOrder ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pImportCoScholasticIndicator]
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,@lCoScholasticGroup nvarchar(100),@lCoScholastic nvarchar(100),
		@lTitle nvarchar(100),@lNumber int,@lOrderIndex int,@lCCECSId int
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	
		CoScholasticGroup nvarchar(100),
		CoScholastic nvarchar(100), 
		Number int, 
		Indicator nvarchar(100),
		OrderIndex int
	)
	INSERT INTO #tTable
	(   
		CoScholasticGroup, 
		CoScholastic,
		Number, 
		Indicator,
		OrderIndex 
	)
	SELECT
		CoScholasticGroup, 
		CoScholastic,
		Number, 
		Indicator,
		OrderIndex 
	FROM OPENXML (@intDoc, '/Table/ImportIndicator', 1)
	WITH
	( 
		CoScholasticGroup nvarchar(100) '@CoScholasticGroup',
		CoScholastic nvarchar(100)  '@CoScholastic',	
		Number Int '@Number',		
		Indicator nvarchar(100) '@Indicator',
		OrderIndex int '@OrderIndex'
	)
EXEC sp_xml_removedocument @intDoc
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 
BEGIN	
		SET @lCoScholasticGroup = ''
		SET @lCoScholastic = ''
		SET @lTitle = ''
		SET @lNumber = 0
		SET @lCCECSId = 0
		SET @lOrderIndex = 0
		
  SELECT		
		@lCoScholasticGroup = CoScholasticGroup,@lCoScholastic=CoScholastic,@lTitle = Indicator,@lNumber = Number,@lOrderIndex = OrderIndex
	  
FROM #tTable WHERE Id = @lCount  
		--BEGIN TRANSACTION
SELECT @lCCECSId=CM.id from sAssessment.tCCECSMaster CM INNER join  sAssessment.tCCECSGroupMaster  CG on CG.Id=CM.CCECAGroupId WHERE 
CM.OrgId=@rOrgId AND CM.Title=@lCoScholastic AND CG.Title=@lCoScholasticGroup

	 --IF NOT EXISTS(select 1 from sAssessment.tCCECSIndicatorMaster where Code=@lCode AND OrgId=@rOrgId)
  BEGIN	
		EXEC [sAssessment].[pCSIndicatorDetailAdd] 0,@lCCECSId,@lTitle,@lNumber,@lOrderIndex,0,@rUserId,0,@rOrgId
	END
		 SET @lCount = @lCount - 1
		--COMMIT TRANSACTION			
END
	SELECT 1
	END TRY
	BEGIN CATCH
	
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pImportExamSetupGet]
	 @rClassId int,
	 @rFromBatchId int,
	 @rToBatchId int,
	 @rExamGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

SELECT 
		ESGM.Id AS ExamSubGroupId, 
		ESGM.Title AS ExamName,

		(Select (Select ESGM1.Title +','  from sAssessment.tExamMaster EM1 INNER JOIN sAssessment.tExamSubGroupMaster ESGM1 ON ESGM1.ID = EM1.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC  ON EC.SubExamId=EM1.Id AND EC.ExamId = (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id ) where (EM1.Id <> (SELECT Id FROM sAssessment.tExamMaster  WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id )) AND (EM1.ClassId = @rClassId ) AND EM1.BatchId = @rFromBatchId FOR XML PATH('')) ) AS FromBatchCombine,

		(Select (Select CONVERT(VARCHAR(15), ESGM1.Id) +','  from sAssessment.tExamMaster EM1 INNER JOIN sAssessment.tExamSubGroupMaster ESGM1 ON ESGM1.ID = EM1.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC  ON EC.SubExamId=EM1.Id AND EC.ExamId = (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id ) where (EM1.Id <> (SELECT Id FROM sAssessment.tExamMaster  WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id )) AND (EM1.ClassId = @rClassId ) AND EM1.BatchId = @rFromBatchId FOR XML PATH('')) ) AS FromBatchCombineIds,

		ISNULL((SELECT COUNT(ESGM1.Title) FROM sAssessment.tExamMaster EM1 INNER JOIN sAssessment.tExamSubGroupMaster ESGM1 ON ESGM1.ID = EM1.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId = EM1.Id AND EC.ExamId = (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id) WHERE EM1.Id <> (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id) AND EM1.ClassId = @rClassId AND EM1.BatchId = @rFromBatchId),0) AS FromBatchCombineCount,

		(Select (Select ESGM2.Title +','  from sAssessment.tExamMaster EM2 INNER JOIN sAssessment.tExamSubGroupMaster ESGM2 ON ESGM2.ID = EM2.ExamSubGroupId  
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM2.Id AND EC.ExamId in (select SubExamId  from sAssessment.tExamCombine 
		where examid=(SELECT Id FROM sAssessment.tExamMaster  WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id )) 
		where (EM2.ClassId = @rClassId ) AND EM2.BatchId = @rFromBatchId FOR XML PATH(''))  From sAssessment.tExamMaster EM3  where EM3.Id = 
		(SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id ) AND EM3.IsIncludeSubExam = 1 ) AS FromBatchSubCombine,
		
		(Select (Select CONVERT(VARCHAR(15), ESGM2.Id) +','  from sAssessment.tExamMaster EM2 INNER JOIN sAssessment.tExamSubGroupMaster ESGM2 ON ESGM2.ID = EM2.ExamSubGroupId  
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM2.Id AND EC.ExamId in (select SubExamId  from sAssessment.tExamCombine 
		where examid=(SELECT Id FROM sAssessment.tExamMaster  WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id )) 
		where (EM2.ClassId = @rClassId ) AND EM2.BatchId = @rFromBatchId FOR XML PATH(''))  From sAssessment.tExamMaster EM3  where EM3.Id = 
		(SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id ) AND EM3.IsIncludeSubExam = 1 ) AS FromBatchSubCombineIds,

		ISNULL((SELECT (SELECT COUNT(ESGM2.Id) FROM sAssessment.tExamMaster EM2 INNER JOIN sAssessment.tExamSubGroupMaster ESGM2 ON ESGM2.ID = EM2.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId = EM2.Id AND EC.ExamId IN (SELECT SubExamId FROM sAssessment.tExamCombine WHERE 
		examid = (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id)) 
		WHERE EM2.ClassId = @rClassId AND EM2.BatchId = @rFromBatchId) FROM sAssessment.tExamMaster EM3 WHERE EM3.Id = (SELECT Id FROM sAssessment.tExamMaster 
		WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id) AND EM3.IsIncludeSubExam = 1),0) AS FromBatchSubCombineCount
		
	FROM 
	sAssessment.tExamMaster EM 
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	INNER JOIN sAssessment.tExamGroupMaster EGM ON ESGM.ExamGroupId = EGM.Id

	WHERE 
	EM.BatchId = @rFromBatchId 
	AND EM.ClassId = @rClassId
	AND (EGM.Id = @rExamGroupId  OR @rExamGroupId = 0)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pImportExamSubGroupMasterAddGet]
          
 @rStrXml nvarchar(MAX),
 @rOrgId int
     
          
AS

SET NOCOUNT ON

BEGIN

SET @rStrXml=REPLACE(@rStrXml,'&','AND') 
DECLARE @lInterrorCode INT,	@intDoc INT
DECLARE @lNextNumber BIGINT
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml
	 
	-- Lead Master Temp Table
	CREATE TABLE #TempExamSubGroupMaster
	(
		[AutoId] int identity,
		[ShortName] nvarchar(20) NULL,
		[Number] smallint NULL,
		[Name] nvarchar(100) NULL,
		[DisplayTitle] nvarchar(100) NULL,
		[ExamGroupId] int NULL, 
		[OrderIndex] smallint NULL, 
		[ExamTypeId] smallint NULL, 
		[IsObsolete] bit null,
		[OrgId] smallint null,
		[CreatedUserId] bigint null, 
		[UpdatedUserId] bigint null, 
		

	)
	
	INSERT INTO #TempExamSubGroupMaster 
	SELECT * FROM OPENXML (@intDoc, '/Table/Import', 1)
	WITH(
			ShortName nvarchar(20) '@ShortName',
			Number smallint '@Number',
			Name nvarchar(100) '@Name',
			DisplayTitle nvarchar(100) '@DisplayTitle',			
			ExamGroupId int '@ExamGroupId',
			OrderIndex smallint '@OrderIndex',
			ExamTypeId int '@ExamTypeId',
			IsObsolete bit '@IsObsolete',
			OrgId smallint '@OrgId',		
			CreatedUserId bigint '@CreatedUserId',
			
			UpdatedUserId bigint '@UpdatedUserId'
		
		)
		DECLARE @lTempExamSubGroupCount int
		SELECT @lTempExamSubGroupCount = COUNT(AutoId) FROM #TempExamSubGroupMaster
		WHILE (@lTempExamSubGroupCount > 0)
		BEGIN
			
			 DECLARE @lTitle nvarchar(200)
			 --DECLARE @lContactPerson nvarchar(100)
			 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				
				INSERT INTO sAssessment.tExamSubGroupMaster
				(
					Id,
					Code,
					Number,
					Title,
					OrgId,
					IsObsolete,
					OrderIndex,
					ExamSubGroupDisplayTitle,
					ExamGroupId,
					ExamTypeId,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime
					
				) 
				SELECT
					@lNextNumber,
					ShortName,
					Number,
					Name,
					OrgId,
					IsObsolete,
					OrderIndex,
					DisplayTitle,
					ExamGroupId,					
					ExamTypeId,					
					CreatedUserId,
					GETDATE(),
					UpdatedUserId,
					GETDATE()
					
					FROM #TempExamSubGroupMaster
					WHERE 
						AutoId = @lTempExamSubGroupCount
						
				SET @lTempExamSubGroupCount = @lTempExamSubGroupCount -1		
					
	    END		 
		
	   SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pImportOptionalSubjectBatchWise]
                  
          @rFromBatch int,
          @rToBatch int 
      
AS
SET NOCOUNT ON

BEGIN
		DELETE OS FROM sAssessment.tOptionalSubject OS inner join sStudent.tAcademic A ON OS.AcademicId = A.id WHERE A.BatchId = @rToBatch

		--IF EXISTS(SELECT 1 FROM sAssessment.tOptionalSubject OS inner join sStudent.tAcademic A ON OS.AcademicId = A.id WHERE A.BatchId = @rToBatch)
		--BEGIN
		--	SELECT -101 AS Result
		--	RETURN
		--END 
		
		INSERT INTO sAssessment.tOptionalSubject
		SELECT 
			ISNULL((SELECT A.Id FROM sStudent.tAcademic A WHERE A.StudentId = AA.StudentId AND A.BatchId = @rToBatch),0) AS AcademicId, 
			ISNULL((SELECT TOP 1 CS.Id FROM sStudent.tAcademic A INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = A.ClassId AND A.OrgId = CS.OrgId AND tCS.SubjectId=CS.SubjectId WHERE A.StudentId = AA.StudentId AND A.BatchId = @rToBatch),0) AS ClassSubjectId
		FROM
			sAssessment.tOptionalSubject OS INNER JOIN sStudent.tAcademic AA ON OS.AcademicId = AA.id
			INNER JOIN sSetup.tClassSubject tCS ON tCS.Id = OS.ClassSubjectId
		WHERE 
			AA.BatchId = @rFromBatch 
		
		DELETE FROM sAssessment.tOptionalSubject WHERE (AcademicId = 0 OR ClassSubjectId = 0)
		SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pImportSubjectActivity]
    @rOrgId smallint ,
	@rXmldoc [nvarchar](max),
	@rUserId bigint


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,@lCode nvarchar(100),@lTitle nvarchar(200),@lNumber int,@lGradeSetId int,@lOrderIndex int,	@lClass nvarchar(100),@lGradeSet nvarchar(100),
	    @lSubject nvarchar(100),  @lClassSubjectId int,@lSubCode nvarchar(100),@lSubTitle nvarchar(200),@lSubNumber int,@lSubOrderIndex int,@lSubjectActivityId int=0
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	CREATE TABLE #tTable  
	(
		Id bigint identity,
		Code nvarchar(100), 
		Number int, 
		Name nvarchar(200),
		GradeSet nvarchar(100), 
		OrderIndex int,
	    Class Nvarchar(100),
	    Subject Nvarchar(100),
		SubNumber int, 
		SubCode nvarchar(100), 
		SubName nvarchar(200),
		SubOrderIndex int
	)
	INSERT INTO #tTable
	(  
		Code, Number,Name,GradeSet, OrderIndex ,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex
	)
	SELECT
		Code, Number, Name, GradeSet, OrderIndex,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex
	FROM OPENXML (@intDoc, '/Table/ImportSubjectActivity', 1)
	WITH
	(   
		Code nvarchar(100) '@Code',			
		Name nvarchar(200) '@Name',			
		Number int '@Number',			
		GradeSet nvarchar(100) '@GradeSet',			
		OrderIndex int '@OrderIndex',
		Class nvarchar(100) '@Class',
		Subject  nvarchar(100) '@Subject',
		SubNumber int '@SubNumber',
		SubCode nvarchar(100) '@SubCode',			
		SubName nvarchar(200) '@SubName',
		SubOrderIndex int '@SubOrderIndex'
		
	)
EXEC sp_xml_removedocument @intDoc
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 
BEGIN	
		SET @lCode = ''
		SET @lTitle = ''
		SET @lNumber = 0
		SET @lGradeSetId = 0
		SET @lOrderIndex = 0
		SET @lClass=''
		SET @lSubject=''
		SET @lClassSubjectId =0
		SET @lGradeSet=''
		SET @lSubTitle=''
		SET @lSubCode=''
		SET @lSubNumber =0
		SET @lSubOrderIndex =0
		SET @lSubjectActivityId=0
		SET @lSubTitle=''
  SELECT		
		@lCode = Code,@lTitle = Name,@lNumber = Number,@lOrderIndex = OrderIndex,
		@lClass=Class,@lSubject=Subject,@lGradeSet=GradeSet,@lSubNumber=SubNumber,@lSubCode=SubCode,@lSubTitle=SubName,@lSubOrderIndex=SubOrderIndex
FROM #tTable WHERE Id = @lCount  
--BEGIN TRANSACTION
	SELECT  @lClassSubjectId=ClassSubjectId FROM sSetup.vClassSubject  VS
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id=VS.ClassId where VS.IsObsolete=0 AND CM.Title=@lClass  AND Vs.SubjectName=@lSubject AND CM.OrgId=@rOrgId
    SELECT @lGradeSetId=Id FROM sAssessment.tGradeSetMaster WHERE  OrgId=@rOrgId   AND Title=@lGradeSet AND OrgId=@rOrgId
  DECLARE @lNextNumber INT=0
  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCESubjectActivityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
    IF NOT EXISTS(select 1 from sAssessment.tCCESubjectActivityMaster where Code=@lCode AND OrgId=@rOrgId AND ClassSubjectId = @lClassSubjectId)
     BEGIN	
     INSERT INTO sAssessment.tCCESubjectActivityMaster (Id, ClassSubjectId, Number, Code, Title, OrgId, IsObsolete, OrderIndex, UpdatedUserId, UpdatedDateTime, GradeSetId)Values
		(@lNextNumber,@lClassSubjectId,@lNumber,@lCode,@lTitle,@rOrgId,0,@lOrderIndex,@rUserId,sCommon.fGetDate(),@lGradeSetId)
	END
	ELSE
	BEGIN
	SELECT @lSubjectActivityId= ID FROM sAssessment.tCCESubjectActivityMaster WHERE Code=@lCode AND OrgId=@rOrgId AND ClassSubjectId = @lClassSubjectId
	SET @lNextNumber=@lSubjectActivityId
	
	END
IF NOT EXISTS(select 1 from sAssessment.tCCESubjectSubActivityMaster where Code=@lSubCode AND OrgId=@rOrgId AND SubjectActivityId =@lNextNumber )
 BEGIN
SElect @lNextNumber
 EXEC  [sAssessment].[pCSSubjectSubActivityAdd] 0,@lNextNumber,@lSubCode,@lSubNumber,@lSubTitle,0,@lSubOrderIndex,@rOrgId,@rUserId
  END 
		 SET @lCount = @lCount - 1
	--COMMIT TRANSACTION			
END
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pImportSubjectActivityIndicator]
    @rOrgId smallint ,
	@rXmldoc [nvarchar](max),
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
	
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,@lActivity nvarchar(200),@lSubActivity nvarchar(200),@lNumber int,@lGradeSetdetailid int,@lOrderIndex int,	
@lGrade nvarchar(100),@lSubActivityId int,@lIndicator nvarchar(100),@lClass nvarchar(100),@lSubject nvarchar(100),@lGradeSetId int
	 
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	CREATE TABLE #tTable  
	(
		Id bigint identity,
		Class nvarchar(100),
		Subject nvarchar(100),
		Activity nvarchar(200), 
		SubActivity nvarchar(200), 
		Number int, 
		Indicator nvarchar(100),
		Grade nvarchar(100), 
		OrderIndex int
	)
	INSERT INTO #tTable
	(  
		Class,Subject,Activity,SubActivity, Number,Indicator,Grade, OrderIndex
	)
	SELECT
		Class,Subject,Activity,SubActivity, Number,Indicator,Grade, OrderIndex
	FROM OPENXML (@intDoc, '/Table/ImportSubjectActivityIndicator', 1)
	WITH
	(   
	    Class nvarchar(100) '@Class',	
	    Subject nvarchar(100) '@Subject',	
		Activity nvarchar(200) '@Activity',			
		SubActivity nvarchar(200) '@SubActivity',			
		Number int '@Number',			
		Indicator nvarchar(100) '@Indicator',
		Grade nvarchar(100) '@Grade',
		OrderIndex int '@OrderIndex'
	)
EXEC sp_xml_removedocument @intDoc
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 
BEGIN	
		SET @lActivity = ''
		SET @lSubActivity = ''
		SET @lClass = ''
		SET @lSubject = ''
		SET @lNumber = 0
		SET @lIndicator = ''
		SET @lOrderIndex = 0
		SET @lGrade=''
		SET @lSubActivityId =0
		SET @lGradeSetdetailid=0 
	
  SELECT		
		@lActivity = Activity,@lSubActivity = SubActivity,@lNumber = Number,@lOrderIndex = OrderIndex,
		@lIndicator=Indicator,@lGrade=Grade,@lClass=Class,@lSubject=Subject
FROM #tTable WHERE Id = @lCount  
--BEGIN TRANSACTION
	SELECT  @lSubActivityId=SA.Id,@lGradeSetId= AM.GradeSetId from sAssessment.tCCESubjectSubActivityMaster SA INNER JOIN  sAssessment.tCCESubjectActivityMaster AM ON SA.SubjectActivityId=AM.Id
    INNER JOIN sSetup.tClassSubject  CS On AM.ClassSubjectId=Cs.Id INNER JOIN sSetup.tClassMaster CM ON CM.Id=Cs.ClassId INNER JOIN  sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
    WHERE  SA.OrgId=@rOrgId AND SA.Title=@lSubActivity AND AM.Title=@lActivity AND SM.Title=@lSubject AND CM.Title=@lClass AND CS.OrgId=@rOrgId
    SELECT @lGradeSetdetailid=Id FROM sAssessment.tGradeSetDetail WHERE GradeCode=@lGrade  and GradeSetId=@lGradeSetId

    IF NOT EXISTS(select 1 from sAssessment.tCCESubjectSubActivityIndicatorMaster  where Title=@lIndicator AND OrgId=@rOrgId AND CCESubjectSubActivityId = @lSubActivityId )
     BEGIN	
     EXEC [sAssessment].[pCSSubjectActivityIndicatorAdd] 0,@lSubActivityId,@lIndicator,@lGradeSetdetailid,@rOrgId,@lOrderIndex,@rUserId,@lNumber,@rUserId
  	END
		 SET @lCount = @lCount - 1
	--COMMIT TRANSACTION			
END
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pLevelSetDetailAdd]
	 
	        @rId int
           ,@rLevelSetId int
           ,@rMinimumScore decimal(12,2)
		   ,@rLevelCode nvarchar(20)
		   ,@rLevelTitle nvarchar(50)
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tLevelSetDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tLevelSetDetail]
			   (
			    [Id]
			   ,[LevelSetId] 
			   ,[MinimumScore] 
			   ,[LevelCode]
			   ,[LevelTitle]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rLevelSetId
			   ,@rMinimumScore
			   ,@rLevelCode
			   ,@rLevelTitle
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tLevelSetDetail]
	    SET
			  --Number=@rNumber
	         --,Code=@rCode
	          LevelSetId=@rLevelSetId
	         ,MinimumScore=@rMinimumScore
	         ,LevelCode=@rLevelCode
			 ,LevelTitle=@rLevelTitle
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pLevelSetDetailGet]
	 @rLevelSetId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			LM.TITLE,
			LM.Code,
			LMD.LevelSetId,
			LMD.Id,
			LMD.LevelTitle,
			LMD.MinimumScore,
			LMD.LevelCode,
			LM.IsObsolete
			
  FROM 
			[sAssessment].[tLevelSetMaster] LM
			INNER JOIN sAssessment.tLevelSetDetail LMD ON LMD.LevelSetId=LM.id
WHERE 
			(LMD.LevelSetId=@rLevelSetId OR @rLevelSetId=0)  order by LMD.MinimumScore Desc
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pLevelSetMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tLevelSetMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAssessment.tLevelSetMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tLevelSetMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAssessment.tLevelSetMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tLevelSetMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tLevelSetMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tLevelSetMaster]
	    SET
			  Code=@rCode
	         ,Title=@rTitle
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pLevelSetMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT Id FROM sAssessment.tExamMaster WHERE LevelSetId= @rId)	
	  BEGIN
		DELETE FROM sAssessment.tLevelSetDetail WHERE LevelSetId IN (SELECT ID FROM sAssessment.tLevelSetMaster WHERE ID=@rId)
		DELETE	FROM sAssessment.tLevelSetMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pLevelSetMasterGet]
          
           --@rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100) ,
            @rOrgId int          
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			Set @rCode = sCommon.fSearchStringGet(@rCode)
		--END

BEGIN
SELECT GM.Id as LevelSetId
	  ,GM.Title as Title
	  ,GM.Code as Code
      ,GM.IsObsolete as IsObsolete
     
  FROM [sAssessment].[tLevelSetMaster] GM 
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((GM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND OrgId = @rOrgId

         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryAllExamSubjectGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId nvarchar(Max),
	 @rBatchId int,
	 @rClassSubjectId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

DECLARE @ExamIDTable TABLE (ExamID BIGINT)
INSERT INTO @ExamIDTable(ExamID)
SELECT item FROM sCommon.fnSplit(@rExamId,',')

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(E.Id) 
					  From sAssessment.vExamMaster  E
					  --INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					   Where ClassId = @rClassId AND E.Id in (SELECT ExamID FROM @ExamIDTable)
					   Order by E.OrderIndex --E.ExamSubGroupId -- Changed for mantis 0028212 by foram
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        --select @cols
set @query = 'SELECT  AcademicId, Name,RollNo,Code,ClassName, ' + @cols + '
FROM
(
Select ISNULL(RD.Obtain,0) AS Obtain, A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Code,CM.Title ClassName 
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectID
LEFT JOIN sAssessment.tOptionalSubject OP ON OP.AcademicId=A.AcademicId ANd CS.Id=OP.ClassSubjectId  
WHERE A.StatusId =1   AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) + ' AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId in( ' + convert(nvarchar(Max),@rExamId) + ') 
And ED.ClassSubjectId='+convert(nvarchar(14),@rClassSubjectId)+'  AND ((CS.IsOptional = 1 AND  isnull(oP.AcademicId,0) <> 0) OR (CS.IsOptional = 0)) 
 ) MAIN

PIVOT
(
	MAX(obtain )
FOR ExamID IN (' + @cols + ')
)pvt Order by RollNo'
  --print @query
execute(@query)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryAllSubjectAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT
	 
		IF EXISTS (SELECT ResultId FROM OPENXML (@loDoc, '/Table/ResultMaster', 1)
			WITH ( 	ResultId Bigint) Where ResultId = 0)
		BEGIN			
		 
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	 
		END
		
		 
		INSERT INTO  sAssessment.tResult 
			(
				Id,
				AcademicId,
				ExamId,
				TotalMarks,
				TotalObtain,
				ResultStatus,
				ResultGrade,
				ResultGradePoint,
				RankNumber,
				Percentage,
				Percentile,
				ResultRemark,
				OtherRemark1,
				UpdatedUserId,
				UpdatedDateTime
				)
			SELECT		
				@lNextNumber+ ROW_NUMBER() OVER(ORDER BY ExamId,AcademicId) AS Id,
				AcademicId,
				ExamId,
				0 AS TotalMarks,
				0 AS TotalObtain,
				'' AS ResultStatus,
				'' AS ResultGrade,
				0 AS ResultGradePoint,
				0 AS RankNumber,
				0 AS Percentage,
				0 AS Percentile,
				'' AS ResultRemark,
				'' AS OtherRemark1,
				UpdatedUserId,
				sCommon.fGetDate() as UpdatedDateTime
							
			FROM OPENXML (@loDoc, '/Table/ResultMaster', 1)
			WITH ( 	ResultId Bigint,				
					AcademicId Bigint,
					ExamId int,					
					UpdatedUserId bigint			
				  ) 
			Where ResultId = 0
	
		SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/ResultMaster', 1)
				 WITH ( Id int )
		SET @lNextNumber  = @lCount + @lNextNumber 
		 
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber 
	    
			--UPDATE  sAssessment.tResult
			--SET
			--	ACADEMICID = A.ACADEMICID,
			--	EXAMID = A.EXAMID
			--FROM
			--(
			--SELECT ACADEMICID,EXAMID,ResultId 
			--FROM OPENXML (@loDoc, '/Table/ResultMaster', 1)
			--WITH ( 
			--		ResultId bigint,
			--		AcademicId Bigint,
			--		ExamId int		
			--	  )) A
			--WHERE sAssessment.tResult.Id = A.ResultId AND sAssessment.tResult.Id <> 0
			
	        SELECT 1 AS Result
	 END	
	 END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
	 
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryAllSubjectCountGet]
	 
	 @rExamId int,
	 @rBatchId int,
	 @rClassId int=0,
	 @rDivisionId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  distinct ',' +   QUOTENAME(CS.SubjectCode) 
					  From  
					   sSetup.vExamSubject CS  
					   INNER JOIN sAssessment.tExamMaster E ON E.Id=CS.ExamId AND E.ExamSubGroupId =  @rExamId 
					   INNER JOIN sSetup.tClassMaster CL on CL.Id=CS.ClassId
					   INNER JOIN sSetup.tDivisionMaster CM ON CM.ClassId=CL.Id
					    WHere ((CM.ClassId =@rClassID) OR (@rClassId=0)) AND ((CM.Id=@rDivisionId) OR (@rDivisionId=0)) 
						AND E.BatchId=@rBatchId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
 
set @query = 'SELECT  ClassId,DivisionId,ClassName,ExamId,

 ' + @cols + '
FROM
(
Select   CM.Id As ClassId,DM.Id as DivisionId,CM.Title+'' ''+DM.Title ClassName,Count(A.AcademicId) AS AcademicId,ED.ExamId, SM.Code as ExamDetailId
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id 
 
WHERE A.StatusId =1 AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) +' And  EM.ExamSubGroupId = ' + convert(nvarchar(15),@rExamId) + 
'AND ISNULL(RD.Obtain,0)>0 AND ((A.ClassId='+convert(nvarchar(15),@rClassId)+') OR (' +convert(nvarchar(15),@rClassId) + '=0)) 
AND ((A.DivisionId='+Convert(nvarchar(15),@rDivisionId)+') OR ('+Convert(nvarchar(15),@rDivisionId)+'=0))
Group By ED.ExamId,Ed.Id,CM.Title,DM.TItle,Cm.Id,Dm.Id,SM.Code) 
MAIN
PIVOT
(
	MAX(AcademicId )
FOR ExamDetailId IN (' + @cols + ')
)pvt '
--AND ISNULL(RD.Obtain,0)>0 (Ramesh Gurjar)Date: 19/02/2022 Remove this condition, for DPS chas 0 mark entry not count in verify screen
--print (@query)
execute(@query)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryAllSubjectExportGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(Ed.Id) 
					  From sAssessment.tExamMaster E
					  INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					  AND ClassId = @rClassId AND E.Id =  @rExamId 
					  INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId AND Ed.ExamId=@rExamId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
set @query = 'SELECT AcademicId,ResultId,0 AS ResultDetailId, ExamId,Name,RollNo,Code,IsMarkInDecimal, ' + @cols + '
FROM
(
Select ISNULL(RD.Obtain,0) AS Obtain,ED.Id AS ExamDetailId,A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Code,ISNULL(R.Id,0) AS ResultId,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
WHERE A.StatusId =1 AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) + ' AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId = ' + convert(nvarchar(15),@rExamId) + '
) MAIN
PIVOT
(
	MAX(Obtain)
FOR ExamDetailId IN (' + @cols + ')
)pvt Order by RollNo,Code,Academicid'
--print (@query)
execute(@query)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryAllSubjectGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)='',@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(Ed.Id) 
					  From sAssessment.tExamMaster E
					  INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					  AND ClassId = @rClassId AND E.Id =  @rExamId order by Ed.DisplayOrder
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
set @query = 'SELECT AcademicId,ResultId,0 AS ResultDetailId, ExamId,Name,RollNo,Code,IsMarkInDecimal, ' + @cols + '
FROM
(
Select ISNULL(RD.Obtain,0) AS Obtain,ED.Id AS ExamDetailId,A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Code,ISNULL(R.Id,0) AS ResultId,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
WHERE A.StatusId =1 AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) + ' AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId = ' + convert(nvarchar(15),@rExamId) + '
) MAIN
PIVOT
(
	MAX(Obtain)
FOR ExamDetailId IN (' + @cols + ')
)pvt Order by RollNo,Code,Academicid'
 --print (@query)
If(isnull(@query,'')='')
BEGIN
SELECT  -101 AS Result
RETURN
END
EXEC (@query)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryConvert]  
	 	
	@rExamId int,
	@rClassId int,
	@rDivisionId int,
	@rExamList nvarchar(500),
	@rOrgId int=1101,
	@rBatchId int,
	@rBasedOnPresent int = 0 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
BEGIN
	 
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max)
	  DECLARE @lMaxId Bigint
	 Declare @lDecimalFormat nvarchar(10)
	  Declare @lIsMarksInDecimal bit
	 
	select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id =@rExamId
	
	 CREATE Table #tempMarkEntry
	 (
			Id bigint Identity(1,1),
			ExamDetailId int,
			ClassSubjectId int,
			ExamId int,
			AcademicId bigint,
			Obtain decimal(5,2),
			Converted_Marks Decimal(5,2),
			Maximum decimal(5,2),
			IsPresent int
	 )
	 INSERT INTO #tempMarkEntry
	 (
			 
			ExamDetailId,
			ClassSubjectId,
			ExamId,
			AcademicId,
			Obtain,
			Converted_Marks,
			Maximum,
			IsPresent
	 )
	 Select 
		 
			RD.ExamDetailId,
			ED.ClassSubjectId,
			EM.Id,
			A.AcademicId,
			RD.Obtain,
						 
				CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
					Round((RD.OBTAIN*EID.Maximum)/ED.Maximum,1) 
				  WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00' ) THEN
					CONVERT(Decimal(5,2),(RD.OBTAIN*EID.Maximum)/ED.Maximum) 
				 ELSE			  
				  ROUND((RD.OBTAIN*EID.Maximum)/ED.Maximum,0)
			 END AS Converted_Marks,
			 
			ED.Maximum,
			RD.IsPresent
			
	FROM 
			 
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId  		
			INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rbatchId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			 INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
			  INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId 
			 AND (A.DivisionId=@rDivisionid)
			 INNER JOIN (Select Id,ClassSubjectId,Maximum from sAssessment.tExamDetail Where ExamId=@rexamid) EID ON EID.ClassSubjectId = ED.ClassSubjectId  
			Where ED.ExamId IN (SELECT  cast(item as int) AS ExamID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rExamList,'(',''),')','') ,',')) 
	 			  
 --Select * from #tempMarkEntry
	 
	
     IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@rExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@rExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,sCommon.fGetDate()
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END
 --------- Result Detail Entry  
  
    IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@rExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND A.DivisionId=@rDivisionId
    )
    BEGIN	
	IF(@rBasedOnPresent = 0)
	BEGIN
	--SET @Query = ' 
			 UPDATE RD SET RD.OBTAIN =  A.Obtain,
			 RD.IsPresent=A.IsPresent
			  FROM
						( 
						SELECT MAX(Converted_Marks)AS Obtain,AcademicId,ClassSubjectId,MIN(CONVERT(INT,IsPresent)) AS IsPresent  FROM #tempMarkEntry group by   AcademicId,ClassSubjectId
						) A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId =  @rClassId  
					AND (SA.DIVISIONID= @RDivisionId)  
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId
		--EXECUTE(@query)
	END
	ELSE
	BEGIN
		 UPDATE RD SET RD.OBTAIN =  A.Obtain,
			 RD.IsPresent=A.IsPresent
			  FROM
						( 
						SELECT MAx(Converted_Marks)AS Obtain,AcademicId,ClassSubjectId,MAX(CONVERT(INT,IsPresent)) AS IsPresent  FROM #tempMarkEntry group by   AcademicId,ClassSubjectId
						) A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId =  @rClassId  
					AND (SA.DIVISIONID= @RDivisionId)  
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId
	END
			
 
		SELECT 11 AS RESULT	 
    END
   ELSE
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
				 
				--Select * from 	  #tempMarkEntry
				 --Select @lNextNumber
	IF(@rBasedOnPresent = 0)
	BEGIN
	INSERT INTO sAssessment.tResultDetail
						(Id,ResultId,ExamDetailId,IsPresent,Obtain) 
				SELECT  
					@lNextNumber  + ROW_number()OVER(Order by R.Id) AS Id,
							 
					R.Id as R_Id,
					ED1.Id AS ExamDetailId,
					A.IsPresent AS IsPresent,
					A.Obtain  
					from 
					sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
				INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
				INNER JOIN( 
							SELECT MAx(Converted_Marks)AS Obtain,AcademicId,ClassSubjectId ,MIN(CONVERT(INT,IsPresent)) AS IsPresent
							FROM #tempMarkEntry group by   AcademicId,ClassSubjectId
						)A   ON R.AcademicId= A.AcademicID  AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
					WHERE SA.ClassId = @rClassId AND  SA.DIVISIONID= @rDivisionId 
				AND R.ExamId = @rExamId
	END
	ELSE
	BEGIN 
	INSERT INTO sAssessment.tResultDetail
						(Id,ResultId,ExamDetailId,IsPresent,Obtain) 
				SELECT  
					@lNextNumber  + ROW_number()OVER(Order by R.Id) AS Id,
							 
					R.Id as R_Id,
					ED1.Id AS ExamDetailId,
					A.IsPresent AS IsPresent,
					A.Obtain  
					from 
					sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
				INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
				INNER JOIN( 
							SELECT MAx(Converted_Marks)AS Obtain,AcademicId,ClassSubjectId ,MAX(CONVERT(INT,IsPresent)) AS IsPresent
							FROM #tempMarkEntry group by   AcademicId,ClassSubjectId
						)A   ON R.AcademicId= A.AcademicID  AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
					WHERE SA.ClassId = @rClassId AND  SA.DIVISIONID= @rDivisionId 
				AND R.ExamId = @rExamId
	END	
						 
		
									
		SELECT @lMaxId=MAx(RD.Id)   FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R On R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id =R.ExamId
		INNER JOIN sSetup.tBatchMaster BM ON BM.ID = EM.BatchId 
		WHERE BM.OrgId = @rOrgId
		  
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lMaxId 
  
		SELECT 1 AS RESULT
   END
   
   
   Drop Table  #tempMarkEntry
    
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryConvertForDifferentSubject]  
	 	
	 
	@rClassId int, 
	@rDivisionId int,
	@rSourceExamDetailIdList nvarchar(500),
	@rOrgId smallint,
	@rBatchId int,
	@rDestinationExamDetailId  int=0,
	@rBasedOnPresent int = 0 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT,@lIsMarksInDecimal bit
Declare @lDecimalFormat nvarchar(10)
select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =(Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId)
select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= (Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId)
BEGIN
	 
	 BEGIN	
	 
	 
	--select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId;
	 
	CREATE Table #MarkEntrySubjectWise_CTE ( AcademicId  bigint,  SourceObtain decimal(5,2),SourceMaximum decimal(5,2),IsPresent int)
 
-- Define the CTE query.
	INSERT INTO #MarkEntrySubjectWise_CTE 
	(
		AcademicId,
	 
		SourceObtain,
		SourceMaximum,
		IsPresent
		--ClassSubjectId
	)
	
   Select 			
		
		R.AcademicId,	
		 	 
		SUM(RD.Obtain)AS SourceObtain,
		SUM(ED.Maximum) AS SourceMaximum,
		(CASE WHEN @rBasedOnPresent = 0 THEN MIN(CONVERT(INT,RD.IsPresent)) ELSE MAX(CONVERT(INT,RD.IsPresent)) END)AS IsPresent
		--ED.ClassSubjectId		
	 
	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.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id			 			 			  			 			 
			 Where
			 A.ClassId = @rClassId AND A.BatchId=@rbatchId 
			 AND ED.Id IN (SELECT  cast(item as int) AS ExamDetailID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rSourceExamDetailIdList,'(',''),')','') ,','))  
			Group By R.AcademicId 
		 
		--Select * from #MarkEntrySubjectWise_CTE 


	DECLARE @lNextNumber BIGINT 
	DECLARE @lResultId BIGINT
	DECLARE @lCount INT
	DECLARE @lMarkInDecimal bit
	Declare @lExamId BigInt
	DECLARE @Query nvarchar(max)
	DECLARE @lMaxId Bigint
	Declare @lHigh1 decimal(5,2),@lHigh2 decimal(5,2)
	Declare @lCountMark int,@lSum_Highest decimal(5,2),@lSum decimal(5,2)
	Declare @lMaximum decimal(5,2)
	Select @lMaximum = Maximum from sAssessment.tExamDetail where Id = @rDestinationExamDetailId

	DECLARE @lDestinationExamId bigint
	SELECT @lDestinationExamId = ExamId FROM sAssessment.tExamDetail WHERE Id = @rDestinationExamDetailId

	IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@lDestinationExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
		 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@lDestinationExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,sCommon.fGetDate()
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END

	IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@lDestinationExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0))
	AND (RD.ExamDetailId = @rDestinationExamDetailId OR @rDestinationExamDetailId = 0)
    )
    BEGIN	
	
	  UPDATE RD SET RD.OBTAIN  =
								(CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
									Round((MC.SourceObtain * ED.Maximum)/MC.SourceMaximum,1) 
								WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00' ) THEN
									CONVERT(Decimal(5,2),(MC.SourceObtain * ED.Maximum)/MC.SourceMaximum) 
								ELSE			  
									ROUND((MC.SourceObtain * ED.Maximum)/MC.SourceMaximum,0)
								END),RD.IsPresent=MC.IsPresent
	  
	  FROM	  
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sAssessment.tExamDetail  ED ON RD.ExamDetailId = ED.Id
			INNER JOIN #MarkEntrySubjectWise_CTE MC ON R.AcademicId = MC.AcademicId 
			AND RD.ExamDetailId = @rDestinationExamDetailId 
				
	Select 11 AS Result
	END
	ELSE
	BEGIN

		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO sAssessment.tResultDetail
							 (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT
							@lNextNumber  + ROW_number()OVER(Order by R.AcademicId) AS Id,
							R.Id as ResultId,
							@rDestinationExamDetailId AS ExamDetailId,
							--ED1.Id AS ExamDetailId,
							A.IsPresent AS IsPresent,
							--A.Obtain 
							((ED1.Maximum * A.SourceObtain) / A.SourceMaximum) AS Obtain
							from 
					  	 sAssessment.tResult R 
					  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					    INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
						INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
						INNER JOIN( 
									SELECT   AcademicId,SourceObtain,SourceMaximum,IsPresent
									FROM #MarkEntrySubjectWise_CTE 
									--group by   AcademicId,
									----ClassSubjectId,
									--SourceObtain,SourceMaximum,IsPresent
								)A   ON R.AcademicId= A.AcademicId  
								--AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
						 WHERE SA.ClassId = @rClassId AND  ((SA.DIVISIONID= @rDivisionId ) OR (@rDivisionId = 0))
						AND R.ExamId = @lDestinationExamId AND ED1.Id = @rDestinationExamDetailId
									
		SELECT @lMaxId=MAx(RD.Id)   FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R On R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id =R.ExamId
		INNER JOIN sSetup.tBatchMaster BM ON BM.ID = EM.BatchId 
		WHERE BM.OrgId = @rOrgId
		  
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lMaxId 
		 Select 1 As Result
	END
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryConvertForSubject]  
	 	
	 
	@rClassId int, 
	@rDivisionId int,
	@rSourceExamDetailIdList nvarchar(500),
	@rOrgId smallint,
	@rBatchId int,
	@rDestinationExamDetailId  int=0 ,
	@rBasedOnPresent int = 0 	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT,@lIsMarksInDecimal bit
Declare @lDecimalFormat nvarchar(10)
select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =(Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId)
select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= (Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId)
BEGIN
	 
	 BEGIN	
	 
	 
	--select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId;
	 
	CREATE Table #MarkEntrySubjectWise_CTE ( AcademicId  bigint, ClassSubjectId int,SourceObtain decimal(5,2),SourceMaximum decimal(5,2),IsPresent int)
 
-- Define the CTE query.
	INSERT INTO #MarkEntrySubjectWise_CTE 
	(
		AcademicId,
		ClassSubjectId,
		SourceObtain,
		SourceMaximum,
		IsPresent
	)
	
   Select 			
		
		R.AcademicId,	
		ED.ClassSubjectId,	 
		SUM(RD.Obtain)AS SourceObtain,
		SUM(ED.Maximum) AS SourceMaximum,
		(CASE WHEN @rBasedOnPresent = 0 THEN MIN(CONVERT(INT,RD.IsPresent)) ELSE MAX(CONVERT(INT,RD.IsPresent)) END)AS IsPresent
	 
	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.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id			 			 			  			 			 
			 Where
			 A.ClassId = @rClassId AND A.BatchId=@rbatchId 
			 AND ED.Id IN (SELECT  cast(item as int) AS ExamDetailID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rSourceExamDetailIdList,'(',''),')','') ,','))  
			Group By R.AcademicId,ED.ClassSubjectId 
		 
		--Select * from #MarkEntrySubjectWise_CTE 
	--Select ExamId  from sAssessment.tExamDetail WHere Id = @rDestinationExamDetailId

	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max)
	 DECLARE @lMaxId Bigint
	 Declare @lHigh1 decimal(5,2),@lHigh2 decimal(5,2)
	 Declare @lCountMark int,@lSum_Highest decimal(5,2),@lSum decimal(5,2)
	 Declare @lMaximum decimal(5,2)
	 Select @lMaximum = Maximum from sAssessment.tExamDetail where Id = @rDestinationExamDetailId

	 DECLARE @lDestinationExamId bigint
	 SELECT @lDestinationExamId = ExamId FROM sAssessment.tExamDetail WHERE Id = @rDestinationExamDetailId

	  IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@lDestinationExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
		 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@lDestinationExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,sCommon.fGetDate()
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END

	IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@lDestinationExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0))
	AND (RD.ExamDetailId = @rDestinationExamDetailId OR @rDestinationExamDetailId = 0)
    )
    BEGIN
	  UPDATE RD SET RD.OBTAIN  =
								(CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
									Round((MC.SourceObtain * ED.Maximum)/MC.SourceMaximum,1) 
								WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00' ) THEN
									CONVERT(Decimal(5,2),(MC.SourceObtain * ED.Maximum)/MC.SourceMaximum) 
								ELSE			  
									ROUND((MC.SourceObtain * ED.Maximum)/MC.SourceMaximum,0)
								END),RD.IsPresent=MC.IsPresent
	  
	   --Convert(Decimal(5,2),(MC.SourceObtain * ED.Maximum)/MC.SourceMaximum)
	  FROM	  
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sAssessment.tExamDetail  ED ON RD.ExamDetailId = ED.Id
			INNER JOIN #MarkEntrySubjectWise_CTE MC ON R.AcademicId = MC.AcademicId AND ED.ClassSubjectId = MC.ClassSubjectId
			AND RD.ExamDetailId = @rDestinationExamDetailId 
	 
	
	Select 11 AS Result
   END
    ELSE
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sAssessment.tResultDetail
							 (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT  
							@lNextNumber  + ROW_number()OVER(Order by R.Id) AS Id,
							 
							R.Id as ResultId,
							@rDestinationExamDetailId AS ExamDetailId,
							A.IsPresent AS IsPresent,
							--A.Obtain 
							((ED1.maximum * A.Obtain) / A.Maximum) AS Obtain
							from 
					  	 sAssessment.tResult R 
					  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					    INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId  
						INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = EM.Id 
						INNER JOIN( 
									SELECT   AcademicId,ClassSubjectId,SourceObtain AS Obtain,SourceMaximum AS Maximum,IsPresent
									FROM #MarkEntrySubjectWise_CTE 
									--GROUP BY  AcademicId,ClassSubjectId,SourceObtain,SourceMaximum,IsPresent
								)A   ON R.AcademicId= A.AcademicId  AND A.ClassSubjectId = ED1.ClassSubjectId						
				 		 
						 WHERE SA.ClassId = @rClassId AND  ((SA.DIVISIONID= @rDivisionId ) OR (@rDivisionId = 0))
						 AND R.ExamId = @lDestinationExamId AND ED1.Id = @rDestinationExamDetailId
									
		SELECT @lMaxId=MAX(RD.Id)   FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R On R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id =R.ExamId
		INNER JOIN sSetup.tBatchMaster BM ON BM.ID = EM.BatchId 
		WHERE BM.OrgId = @rOrgId
		  
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lMaxId 
		 Select 1 As Result
		 
   END

   DROP TABLE #MarkEntrySubjectWise_CTE
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryDelete]
	@rDivisionId int,
	@rExamId int,
	@rExamDetailId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--BEGIN TRY 		
	IF EXISTS (SELECT ExamId FROM sAssessment.tExamCombine WHERE SubExamId = @rExamId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END
	ELSE
	BEGIN
	
 
 
DELETE RD
FROM sAssessment.tResultDetail RD
INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
Where R.ExamId = @rExamId AND A.DivisionId = @rDivisionId   
AND RD.ExamDetailId = @rExamDetailId
 
IF NOT EXISTS ( SELECT 1 FROM sAssessment.tResultDetail RD
INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
Where R.ExamId = @rExamId AND A.DivisionId = @rDivisionId )  
 BEGIN
		 DELETE R
		 FROM   sAssessment.tResult R 
		 INNER JOIN sStudent.tAcademic A
		 ON R.AcademicId = A.Id
		 Where R.ExamId = @rExamId AND A.DivisionId = @rDivisionId   
   END
	
		--DELETE FROM sAssessment.tResultDetail  WHERE ExamDetailId = @rExamDetailId AND ResultId In
		--(SELECT Id FROM sAssessment.tResult  
		--	WHERE ExamId = @rExamId AND AcademicId IN (Select Id From sStudent.tAcademic where DivisionId=@rDivisionId))
		--DELETE FROM sAssessment.tResult  WHERE ExamId = @rExamId AND AcademicId IN (Select Id From sStudent.tAcademic where DivisionId=@rDivisionId)
		SELECT 1 AS RESULT
	END
--END TRY
--BEGIN CATCH
--		SELECT -1 AS RESULT
--END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryDetailAdd]
	 
	        @rId bigint
           ,@rResultId bigint
		   ,@rExamDetailId int
		   ,@rObtain Decimal(6,2)=0
		   ,@rIsPresent bit
		   ,@rExamId int
		   ,@rAcademicId bigint
		   ,@rOrgId int
		   ,@rAbsentRemark nvarchar(100) = ''
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMarkInDecimal bit
	 DECLARE @lClassId int
	 DECLARE @lDecimalPlace nvarchar(10)
	 DECLARE @lIsNegativeMarks bit


Select @lMarkInDecimal=IsMarksInDecimal,@lClassId = ClassId,@lDecimalPlace=DecimalFormat,@lIsNegativeMarks=IsNegativeMarks from sAssessment.tExamMaster Where Id = @rExamId
	 
--Select @lMarkInDecimal=IsMarksInDecimal from sAssessment.tExamMaster Where Id = @rExamId And ClassId IN (SELECT ClassId FROM sStudent.tAcademic WHERE ID=@rAcademicId)
--Select @lClassId = ClassId From sAssessment.tExamMaster Where Id=@rExamId

IF @lMarkInDecimal = 1 AND @lDecimalPlace='0.0'
	BEGIN
		SET @rObtain = ROUND(@rObtain,1)
		
	END
ELSE if @lMarkInDecimal = 1 AND @lDecimalPlace='0.00'
	BEGIN	 
			SET @rObtain =round(round(@rObtain,2),2)
		END	
ELSE
	BEGIN
		SET @rObtain =round(ROUND(@rObtain,2),0)
		END		
	

IF(@rObtain < 0 AND @lIsNegativeMarks=0)
	SET @rObtain = 0
		
If NOT EXISTS (SELECT 1 FROM sAssessment.tExamDetail Where Id= @rExamDetailId And   ClassSubjectId in 
				(Select cs.Id from sSetup.tClassSubject CS 
					Left join sAssessment.tOptionalSubject O ON o.ClassSubjectId=cs.Id 
					AND O.AcademicId=@rAcademicId
					WHERE (CS.ClassId =@lClassId AND IsOptional = 0) OR (IsOptional = 1 AND AcademicId IS NOt Null))
					)
BEGIN
	SELECT 1 as Result
END

ELSE IF NOT EXISTS(SELECT Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	 
	INSERT INTO [sAssessment].[tResultDetail]
			   (
			    [Id]
			   ,[ResultId] 
			   ,[ExamDetailId]
			   ,[Obtain]
			   ,[IsPresent]
			   ,[AbsentRemark]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rResultId
			   ,@rExamDetailId
			   ,@rObtain
			   ,@rIsPresent
			   ,@rAbsentRemark
			   )
			  
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	 
	 Select @rId = Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId
	
	    UPDATE  [sAssessment].[tResultDetail]
	    SET
	         -- ResultId=@rResultId
	         --,ExamDetailId=@rExamDetailId,
			 Obtain=@rObtain
			 ,IsPresent=@rIsPresent
			 ,SubjectGrade = ''
			 ,SubjectGradePoint=0
			 ,Percentile=0
			 ,AbsentRemark = @rAbsentRemark
	      WHERE Id = @rId 	   
	      SELECT @rId AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryDetailAllSubjectAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 

	 	Select Distinct @lExamId =  ExamId FROM OPENXML (@loDoc, '/Table/ResultDetail', 1) WITH (ExamId bigint)
		Select @lMarkInDecimal=IsMarksInDecimal from sAssessment.tExamMaster E WHERE E.Id = @lExamId
	 
		IF EXISTS (SELECT ResultDetailId FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
			WITH (ResultDetailId bigint) WHERE ResultDetailId = 0 )
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
		END
		
		INSERT INTO sAssessment.tResultDetail
			( Id,ResultId,ExamDetailId,Obtain,IsPresent )
			SELECT		
				@lNextNumber + ROW_NUMBER() OVER(ORDER BY A.ExamDetailId) AS Id,
				sAssessment.fGetResultId(A.AcademicId,A.ExamId)AS ResultId,A.ExamDetailId,A.Obtain,A.IsPresent					
			FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
			WITH ( 					
					ExamDetailId int,
					Obtain decimal(5,2),
					IsPresent bit,
					ResultDetailId bigint,
					ResultId bigint,
					AcademicId bigint,ExamId int			
				  ) A 
				  LEFT JOIN sAssessment.tResultDetail RD
			  ON  A.ResultId = RD.ResultId AND A.ExamDetailId = RD.ExamDetailId  
			  WHERE 
			   RD.ResultId IS NULL AND RD.ExamDetailId IS NULL
			 --  RD.Id IS NULL
				 
			 --WHERE ResultDetailId = 0 AND ExamDetailId Not In 
			 --(Select ExamDetailId From sAssessment.tResultDetail Where ResultId = sAssessment.fGetResultId(AcademicId,ExamId))
				 
		SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
				 WITH ( Id int )
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lNextNumber 
		
		


		--- UPDATE RESULTDETAIL IF RESULTDETAILID EXIST
			UPDATE  sAssessment.tResultDetail
			SET
				--ExamDetailId = A.ExamDetailId,
				Obtain = CASE @lMarkInDecimal WHEN 0 THEN ROUND(A.Obtain,0)
				ELSE  A.Obtain
				END
				--,
				--IsPresent = A.IsPresent
			FROM
			(
			SELECT ExamDetailId,Obtain,IsPresent,ResultDetailId,ResultId 
			FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
			WITH ( 
					ExamDetailId int,
					Obtain Decimal(5,2),
					IsPresent bit,
					ResultDetailId bigint,
					ResultId Bigint		
				  )) A
			INNER JOIN sAssessment.tResultDetail RD 
			ON RD.ResultId = A.ResultId AND RD.ExamDetailId = A.ExamDetailId
			--WHERE sAssessment.tResultDetail.ResultId = A.ResultId AND  sAssessment.tResultDetail.ExamDetailId = A.ExamDetailId
			

		
		--IF @lMarkInDecimal = 0
		--BEGIN		
		
		--UPDATE  sAssessment.tResultDetail
		--	SET				
		--		Obtain = ROUND(A.Obtain,0)
		--	FROM
		--	(
		--	SELECT ExamDetailId,Obtain,ResultId 
		--	FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
		--	WITH ( 
		--			ExamDetailId int,
		--			Obtain Decimal(5,2),
		--			ResultId Bigint		
		--		  )) A
		--	WHERE sAssessment.tResultDetail.ResultId = A.ResultId AND  sAssessment.tResultDetail.ExamDetailId = A.ExamDetailId
		--END		
		SELECT 1 AS Result	
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryGenerate]
	 	
	@rExamId int,
	@rClassId int,
	@rDivisionId int,
	@rExamList nvarchar(500),
	@rOrgId int,
	@rBatchId int 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
BEGIN
	--BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max),@lIsMarksInDecimal bit,@lDecimalFormat nvarchar(10)
	 
		
	 select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= @rExamId

------- Result Master Entry	 
     IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@rExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@rExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,GETDATE() 
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END
 --------- Result Detail Entry  
  
    IF EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@rExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND (A.DivisionId=@rDivisionId OR @rDivisionId = 0)
    )
    BEGIN	
		
				  UPDATE RD SET RD.OBTAIN =  
(CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
Round((A.OBTAIN/Maxi)*ED.Maximum ,1)
WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00') 
THEN Round(Round((A.OBTAIN/Maxi)*ED.Maximum,2),2) 
ELSE	   
Round(ROUND((A.OBTAIN/Maxi)*ED.Maximum ,2),0) END)
											
								 FROM
						(SELECT 
							Sum(Obtain) AS Obtain,
							Sum(Maximum) AS Maxi,RM.AcademicId,ED.ClassSubjectId
						FROM sAssessment.tResult RM 
							INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
							INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId AND SA.ClassId = @rClassId
							AND (SA.DIVISIONID= @RDivisionId OR @RDivisionId = 0 )
							INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
							WHERE RM.ExamId IN (SELECT  cast(item as int) AS ExamID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rExamList,'(',''),')','') ,','))
						GROUP BY RM.AcademicId,ED.ClassSubjectId )A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = @rClassId
					AND (SA.DIVISIONID= @RDivisionId OR @RDivisionId = 0 )
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId
		 
    END
   ELSE
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
				
				SET @Query = 'INSERT INTO sAssessment.tResultDetail (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT ' + CONVERT(NVARCHAR,@lNextNumber) + ' + ROW_NUMBER() OVER(ORDER BY ED1.ClassSubjectId) AS Id,
						R.Id,ED1.Id AS ExamDetailId,1 AS IsPresent,
						CASE WHEN  (SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) * ED1.Maximum IS NULL THEN 0 ELSE 
						
						(SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) END  * ED1.Maximum  AS OBTAIN
					FROM 	sAssessment.tResult R 
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
							INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = R.ExamId
							AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )					
							and R.ExamId=' + CONVERT(NVARCHAR,@rExamId)
			
								
		--print(@Query)
		execute(@Query)
		
		SELECT @lCount = COUNT(RD.Id) FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id AND R.ExamId=@rExamId 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId AND SA.ClassId=@rClassId AND (SA.DivisionId=@rDivisionId OR @rDivisionId =0) AND SA.BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lNextNumber 
	
	END
		SELECT 1 AS RESULT
   END
   --COMMIT TRANSACTION
	--END TRY

	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryGenerate_New]
	 	
	@rExamId int,
	@rClassId int,
	@rDivisionId int,
	@rExamList nvarchar(500),
	@rOrgId int,
	@rBatchId int,
	@rBasedOnPresent int = 0  	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
BEGIN
	--BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max),@lIsMarksInDecimal bit,@lDecimalFormat nvarchar(10)
	 
		
	 select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= @rExamId
	IF(@rBasedOnPresent = 0)
	BEGIN
------- Result Master Entry	 
     IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@rExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@rExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,GETDATE() 
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END
 --------- Result Detail Entry   
 
    IF NOT EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@rExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND (A.DivisionId=@rDivisionId OR @rDivisionId = 0)
    )
    BEGIN	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
				
				SET @Query = 'INSERT INTO sAssessment.tResultDetail (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT ' + CONVERT(NVARCHAR,@lNextNumber) + ' + ROW_NUMBER() OVER(ORDER BY ED1.ClassSubjectId) AS Id,
						R.Id,ED1.Id AS ExamDetailId,
						
					ISNULL((SELECT MIN(CONVERT(INT,RD.IsPresent)) AS IsPresent FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId),0)  AS IsPresent,
	
						CASE WHEN  (SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) * ED1.Maximum IS NULL THEN 0 ELSE 
						
						(SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) END  * ED1.Maximum  AS OBTAIN
					FROM 	sAssessment.tResult R 
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
							INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = R.ExamId
							AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )					
							and R.ExamId=' + CONVERT(NVARCHAR,@rExamId)
		
		--print(@Query)
		execute(@Query)
		
		SELECT @lCount = COUNT(RD.Id) FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id AND R.ExamId=@rExamId 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId AND SA.ClassId=@rClassId AND (SA.DivisionId=@rDivisionId OR @rDivisionId =0) AND SA.BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lNextNumber 
		END

UPDATE RD SET RD.OBTAIN =  	
(CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN	
Round((A.Obtain/Maxi)*ED.Maximum ,1)	
WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00') 	
THEN Round(Round((A.Obtain/Maxi)*ED.Maximum,2),2) 	
ELSE	   	
Round(ROUND((A.OBTAIN/Maxi)*ED.Maximum ,2),0) END),	
RD.IsPresent=A.IsPresent
											
								 FROM
						(SELECT 
							Sum(Obtain) AS Obtain,
							Sum(Maximum) AS Maxi,RM.AcademicId,ED.ClassSubjectId,MIN(CONVERT(INT,RD.IsPresent))AS IsPresent
						FROM sAssessment.tResult RM 
							INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
							INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId AND SA.ClassId = @rClassId
							AND (SA.DIVISIONID= @RDivisionId OR @RDivisionId = 0 )
							INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
							WHERE RM.ExamId IN (SELECT  cast(item as int) AS ExamID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rExamList,'(',''),')','') ,','))
						GROUP BY RM.AcademicId,ED.ClassSubjectId)A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = @rClassId
					AND (SA.DIVISIONID= @RDivisionId OR @RDivisionId = 0 )
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId
	END
	ELSE
	BEGIN
		------- Result Master Entry	 
     IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@rExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@rExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,GETDATE() 
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END
 --------- Result Detail Entry   
 
    IF NOT EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@rExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND (A.DivisionId=@rDivisionId OR @rDivisionId = 0)
    )
    BEGIN	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
				
				SET @Query = 'INSERT INTO sAssessment.tResultDetail (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT ' + CONVERT(NVARCHAR,@lNextNumber) + ' + ROW_NUMBER() OVER(ORDER BY ED1.ClassSubjectId) AS Id,
						R.Id,ED1.Id AS ExamDetailId,
						
					ISNULL((SELECT MAX(CONVERT(INT,RD.IsPresent)) AS IsPresent FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId),0)  AS IsPresent,
	
						CASE WHEN  (SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) * ED1.Maximum IS NULL THEN 0 ELSE 
						
						(SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) END  * ED1.Maximum  AS OBTAIN
					FROM 	sAssessment.tResult R 
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
							INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = R.ExamId
							AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )					
							and R.ExamId=' + CONVERT(NVARCHAR,@rExamId)
		
		--print(@Query)
		execute(@Query)
		
		SELECT @lCount = COUNT(RD.Id) FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id AND R.ExamId=@rExamId 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId AND SA.ClassId=@rClassId AND (SA.DivisionId=@rDivisionId OR @rDivisionId =0) AND SA.BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lNextNumber 
		END

UPDATE RD SET RD.OBTAIN =  	
(CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN	
Round((A.Obtain/Maxi)*ED.Maximum ,1)	
WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00') 	
THEN Round(Round((A.Obtain/Maxi)*ED.Maximum,2),2) 	
ELSE	   	
Round(ROUND((A.OBTAIN/Maxi)*ED.Maximum ,2),0) END),	
RD.IsPresent=A.IsPresent
											
					FROM
						(SELECT 
							Sum(Obtain) AS Obtain,
							Sum(Maximum) AS Maxi,RM.AcademicId,ED.ClassSubjectId,MAX(CONVERT(INT,RD.IsPresent))AS IsPresent
						FROM sAssessment.tResult RM 
							INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
							INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId AND SA.ClassId = @rClassId
							AND (SA.DIVISIONID= @RDivisionId OR @RDivisionId = 0 )
							INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
							WHERE RM.ExamId IN (SELECT  cast(item as int) AS ExamID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rExamList,'(',''),')','') ,','))
						GROUP BY RM.AcademicId,ED.ClassSubjectId)A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = @rClassId
					AND (SA.DIVISIONID= @RDivisionId OR @RDivisionId = 0 )
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId
	END
		SELECT 1 AS RESULT
   END
  
END

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

BEGIN 		

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

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

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

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

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryGradeUpdate]
	 @rExamId int,
	 @rDataSetId int,
	 @rDivisionId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION		
DECLARE @MinimumScore decimal(5,2)
DECLARE @Grade nvarchar(10)
DECLARE @GradePoint Decimal(6,2)
DECLARE @lCount int,@GradeIndicator nvarchar(50)

begin
	CREATE TABLE #tempGradeSetDetail
 		(
 			Id INT IDENTITY (1, 1),
 			MinimumScore decimal(5,2),
 			Grade nvarchar(10),
 			GradePoint Decimal(6,2),
 			GradeTitle 	nvarchar(50)				 
 		) 
 		INSERT INTO #tempGradeSetDetail
 		SELECT MinimumScore,GradeCode,GradePoint,GradeTitle		
		FROM sAssessment.tGradeSetDetail where GradesetId=@rDataSetID
		order by MinimumScore DESC

--SELECT * FROM #tempGradeSetDetail 	
SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
while (@lCount > 0)
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@Grade= Grade,
		@GradePoint = GradePoint,
		@GradeIndicator = GradeTitle
		FROM #tempGradeSetDetail WHERE Id = @lCount
		
	Update sAssessment.tResult Set ResultGrade=@Grade,ResultGradePoint=@GradePoint,ResultIndicator=@GradeIndicator WHERE Percentage >= @MinimumScore 
		--AND (ISNULL(ResultGrade,'') = '') 
		AND ExamId= @rExamId
		AND AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND BatchId = @rBatchId AND StatusId=1)

	SET @lCount = @lCount - 1
 END	
END
SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryMasterAdd]	 
	        @rId bigint
	       ,@rAcademicId bigint
           ,@rExamId int
           ,@rCreatedUserId bigint
           ,@rOrgId int
          
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF NOT EXISTS(SELECT 1 FROM sAssessment.tResult WHERE AcademicId = @rAcademicId AND ExamId = @rExamId)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tResult]
			   (
			    [Id]
			   ,[AcademicId]
			   ,[ExamId]
			   ,[TotalMarks]
			   ,[TotalObtain]
			   ,[ResultStatus]
			   ,[ResultGrade]
			   ,[ResultGradePoint]
			   ,[RankNumber]
			   ,[Percentage]
			   ,[Percentile]
			   ,[ResultRemark]
			   ,[OtherRemark1]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rAcademicId
			   ,@rExamId
			   ,0
			   ,0
			   ,''
			   ,''
			   ,0
			   ,0
			   ,0.0
			   ,0.0
			   ,''
			   ,''
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 IF (@rId = 0)
		SELECT @lNextNumber = ID FROM sAssessment.tResult WHERE AcademicId = @rAcademicId AND ExamId = @rExamId	 
	 ELSE	  
	 SET @lNextNumber = @rId
	 
	    UPDATE  [sAssessment].[tResult]
	    SET
			  AcademicId=@rAcademicId
	         ,ExamId=@rExamId
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryMasterUpdate]	 
           
       @rExamId int,
       @rDivisionId int,
       @rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 -- decimal Percentage Based on Config Assessment.IsShowPercentageRoundoff - mantisid - 0028336

	 DECLARE @lOrgGroupId int
	 SELECT @lOrgGroupId = OM.OrgGroupId From sSetup.tBatchMaster BM
					  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					  Where BM.Id = @rBatchId

	 DECLARE @lPercentageConfigValue bit
	 SELECT @lPercentageConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 538 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupId,4)
	 --SELECT @lPercentageConfigValue

	 --Get Siddhi Krupa Configuration Value
	 DECLARE @lConfigValue bit, @lOrgId int
	 DECLARE @lSiddhiKrupaApplicable bit
	 SELECT @lSiddhiKrupaApplicable = ISNULL(IsApplySiddhiKrupa,0) From sAssessment.tExamMaster Where Id = @rExamId
	 
	 SELECT @lOrgId = OM.Id From sSetup.tBatchMaster BM
					  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					  Where BM.Id = @rBatchId
 	 
 	 SELECT @lConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM
						    LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId AND SourceTypeId = 1016 AND SourceId = @lOrgId
						    WHERE CS.ConfigurationId = 278 
	 
	 --DECLARE @lMinimum int, @lObtain int, @lSiddhiMark int, @lKrupaMark int
	 --SELECT @lMinimum = ED.Minimum, @lObtain= RD.Obtain, @lSiddhiMark = RD.GraceMark, @lKrupaMark = RD.KrupaMark
		--			    FROM sAssessment.tResultDetail RD
		--			    INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		--			    INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId
		--			    INNER JOIN sAssessment.tExamMaster EM ON EM.Id = ED.ExamId
		--			    INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = EM.ClassId
		--			    WHERE EM.Id = @rExamId AND EM.BatchId = @rBatchId AND DM.Id = @rDivisionId
	 --End Here
	 
	 DECLARE @lIsExcludeAbsentTotal bit,@lIsAllExamPassRequired bit, @lIsFailPercentageZero bit
	 
	 SELECT @lIsExcludeAbsentTotal = IsExcludeAbsentTotal,@lIsAllExamPassRequired=IsAllExamPassRequired FROM sAssessment.tExamMaster EM
	 WHERE EM.Id = @rExamId AND BatchId = @rBatchId
	 
	 SELECT @lIsFailPercentageZero = IsRemovePercentageForFail FROM sAssessment.tExamMaster EM WHERE EM.Id = @rExamId AND BatchId = @rBatchId
	 
		   UPDATE RD SET	SubjectGrade='',
							SubjectGradePoint=0,
							Percentile=0.00 
							--Remark=''
			FROM sAssessment.tResultDetail RD  
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND R.ExamId = @rExamId AND SA.DivisionId=@rDivisionId 
			
			UPDATE R SET	TotalMarks=0,
							TotalObtain=0,
							ResultStatus='',
							ResultGrade='',
							ResultGradePoint = 0,
							RankNumber =0,
							Percentage = 0.00,
							Percentile =0.00
							--resultRemark=''			
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.vStudentAcademic  SA ON SA.AcademicId=R.AcademicId AND ExamId = @rExamId AND DivisionId=@rDivisionId 
	 
	 DECLARE @lIsMarksInDecimal bit,@lDecimalFormat nvarchar(10)
	 select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= @rExamId
	
	IF @lIsExcludeAbsentTotal = 0
	BEGIN  
	UPDATE sAssessment.tResult SET TotalMarks= A.Maximum, 
					TotalObtain=A.Obtain,
	--Percentage = (A.Obtain/A.Maximum)*100
	Percentage = CASE WHEN @lPercentageConfigValue = 1 THEN ROUND((A.Obtain/A.Maximum)*100,0) ELSE (A.Obtain/A.Maximum)*100 END
	FROM 
	(SELECT
		CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
				Round(SUM(Obtain) ,1)
			WHEN ( @lIsMarksInDecimal= 1 AND @lDecimalFormat='0.00' ) THEN
				ROUND(ROUND(SUM(Obtain),2),2) 	
			ELSE			  
				ROUND(ROUND(SUM(Obtain),2) ,0) 
			END  AS Obtain,
		  
		  --round(SUM(Obtain),0) AS Obtain,
		  SUM(Maximum) AS Maximum,R.Id 
		  FROM sAssessment.tResultDetail RD
		  INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId --AND RD.IsPresent =1
		  INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
		  INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.Id=RD.ExamDetailId
		  INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = EM.ClassId AND R.AcademicId=SA.AcademicId AND EM.BatchId=SA.BatchId
		  WHERE (R.ExamId = @rExamId OR @rExamId = 0) AND (SA.DivisionId=@rDivisionId or @rDivisionId=0) AND  ED.IsIncludeInTotal=1
		  AND EM.BatchId = @rBatchId AND SA.BatchId = @rBatchId
		  GROUP BY R.Id ) AS A 	
		  WHERE (ExamId = @rExamId OR @rExamId = 0) AND A.Id=sAssessment.tResult.Id
	END
	ELSE
	BEGIN
	
	UPDATE sAssessment.tResult SET TotalMarks= A.Maximum, 
	TotalObtain=A.Obtain,
	--Percentage = (A.Obtain/A.Maximum)*100
	Percentage = CASE WHEN @lPercentageConfigValue = 1 THEN ROUND((A.Obtain/A.Maximum)*100,0) ELSE (A.Obtain/A.Maximum)*100 END
	FROM 
	(SELECT  
		CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
				Round(Round(SUM(Obtain) ,1) ,1)
			WHEN ( @lIsMarksInDecimal= 1 AND @lDecimalFormat='0.00' ) THEN
				Round(ROUND(SUM(Obtain),2) ,2) 
			ELSE			  
				Round(ROUND(SUM(Obtain),2),0) 
			END  AS Obtain,
		--round(SUM(Obtain),0) AS Obtain,
		SUM(Maximum) AS Maximum,R.Id 
	FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId AND RD.IsPresent = 1
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.Id=RD.ExamDetailId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = EM.ClassId AND R.AcademicId=SA.AcademicId AND EM.BatchId=SA.BatchId
	WHERE (R.ExamId = @rExamId OR @rExamId = 0) AND (SA.DivisionId=@rDivisionId or @rDivisionId=0) AND  ED.IsIncludeInTotal=1
	AND EM.BatchId = @rBatchId AND SA.BatchId = @rBatchId
	GROUP BY R.Id ) AS A 	
	WHERE (ExamId = @rExamId OR @rExamId = 0) AND A.Id=sAssessment.tResult.Id
	
	END
	--- Update Result Status	
	

	
	UPDATE R
	SET ResultStatus='' 
	FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A
	ON R.AcademicId = A.Id
	WHERE R.ExamId = @rExamId 
	AND A.DivisionId = @rDivisionId
	AND A.BatchId = @rBatchId
	
	
	--UPDATE R
	--SET ResultStatus='FAIL' 
	--FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	--INNER JOIN
	--(
	--SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
	--INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	--INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
	--INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
	--AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
	--AND A.BatchId = @rBatchId
	--INNER JOIN sAssessment.tOptionalSubject OS ON OS.ClassSubjectId = ED.ClassSubjectId AND OS.AcademicId = R.AcademicId
	--WHERE
	---- ClassSubjectId
	----NOT IN (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE AcademicId=A.Id) 
	----AND 
	--RD.Obtain < Minimum
	-- ) D ON R.Id = D.Id	
	--WHERE R.ExamId = @rExamId	 
	--AND A.DivisionId = @rDivisionId 
	--AND A.BatchId = @rBatchId	

	
	--UPDATE R
	--SET ResultStatus='PASS' 
	--FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A
	--ON R.AcademicId = A.Id
	--WHERE R.ExamId = @rExamId 
	--AND R.ResultStatus = ''
	--AND A.DivisionId = @rDivisionId 
	--AND A.BatchId = @rBatchId
	
	
	--	UPDATE sAssessment.tResult SET ResultStatus='' 
	--WHERE ExamId = @rExamId
	--AND AcademicId IN (SELECT Id FROM sStudent.tAcademic WHERE
	--DivisionId = @rDivisionId AND BatchId = @rBatchId)
	
	IF @lIsExcludeAbsentTotal = 0
	BEGIN
		UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
		SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
		INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
		INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
		AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
		AND A.BatchId = @rBatchId	
		WHERE 
		--ClassSubjectId
		--NOT IN (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE AcademicId=A.Id) 
		--AND 
		RD.Obtain < Minimum
		)
		
	END
	ELSE
	BEGIN
		UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
		SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
		INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
		INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
		AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
		AND A.BatchId = @rBatchId
		AND RD.IsPresent = 1
		WHERE
		 RD.Obtain < Minimum	
		)		
	END
	
	IF @lIsAllExamPassRequired = 1
	BEGIN
		UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ExamId = @rExamId AND  AcademicId 
		IN (	
		SELECT DISTINCT R.AcademicId FROM sAssessment.tResult R
		INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId = R.ExamId AND EC.ExamId = @rExamId
		WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND R.ResultStatus = 'FAIL')
		
		IF @lConfigValue = 1 AND @lSiddhiKrupaApplicable = 1
		BEGIN
			UPDATE sAssessment.tResult SET ResultStatus='PASS' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark >= Minimum AND RD.GraceMark > 0 --AND RD.KrupaMark > 0
			)
		
			UPDATE sAssessment.tResult SET ResultStatus='PROMOTED' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='PASS'
			WHERE RD.KrupaMark > 0
			)
			
			UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			--AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark < Minimum 
			)
			
		END		
	END
	
	
	UPDATE sAssessment.tResult SET ResultStatus='PASS' 
	WHERE ExamId = @rExamId AND ResultStatus <> 'FAIL'
	AND AcademicId IN (SELECT Id FROM sStudent.tAcademic WHERE
	DivisionId = @rDivisionId AND BatchId = @rBatchId)
	
	

	IF @lConfigValue = 1 AND @lSiddhiKrupaApplicable = 1
	BEGIN
		BEGIN
		    UPDATE sAssessment.tResult SET ResultStatus='PASS' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark >= Minimum --AND RD.GraceMark > 0 --AND RD.KrupaMark > 0
			)
		
			UPDATE sAssessment.tResult SET ResultStatus='PROMOTED' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='PASS'
			WHERE RD.KrupaMark > 0
			)
			
			UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			--AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark < Minimum 
			)
			
			
		END	
	END
	
	IF @lIsFailPercentageZero =  1
	BEGIN
		UPDATE RT SET RT.Percentage=0 FROM sAssessment.tResult RT
		INNER JOIN sStudent.tAcademic SA ON SA.Id = RT.AcademicId
		AND RT.ExamId = @rExamId AND SA.DivisionId = @rDivisionId AND SA.BatchId = @rBatchId
		AND RT.ResultStatus='FAIL'

		IF @lConfigValue = 1 AND @lSiddhiKrupaApplicable = 1
		BEGIN
			UPDATE sAssessment.tResult SET ResultStatus='PASS' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark >= Minimum --AND RD.GraceMark > 0 --AND RD.KrupaMark > 0
			)
		
			UPDATE sAssessment.tResult SET ResultStatus='PROMOTED' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='PASS'
			WHERE RD.KrupaMark > 0
			)
			
			UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			--AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark < Minimum 
			)
			
		END
	END
	
	
	SELECT 1 AS RESULT 
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT ERROR_MESSAGE()
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryMaxMarkGet]
	 @rExamDetailId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

SELECT 
	convert(int,Maximum) AS MaxMark
FROM
	sAssessment.tExamDetail ED  
Where (ED.Id=@rExamDetailId OR @rExamDetailId = 0 )
 	  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryOptionalSubjectGet]
	  @rExamDetailId int
	 ,@rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


IF EXISTS(	SELECT * FROM sAssessment.tOptionalSubject OS
	INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = OS.ClassSubjectId
	INNER JOIN sSetup.tClassSubject CS ON CS.Id= ED.ClassSubjectId AND OS.ClassSubjectId=CS.Id
	AND CS.IsOptional=1 WHERE ED.Id=@rExamDetailId AND OS.AcademicId = @rAcademicId)
BEGIN
	SELECT 0 AS RESULT
	RETURN
END
ELSE IF  EXISTS (	SELECT 1 FROM sAssessment.tExamDetail ED 
					INNER JOIN sSetup.tClassSubject CS ON CS.Id= ED.ClassSubjectId AND IsOptional = 0
					WHERE ED.Id=@rExamDetailId)
BEGIN
	SELECT 0 AS RESULT
	RETURN
END
ELSE IF NOT EXISTS(SELECT 1 FROM sAssessment.tExamDetail ED 
	INNER JOIN sSetup.tClassSubject CS ON CS.Id= ED.ClassSubjectId AND IsOptional = 1
	INNER JOIN sAssessment.tOptionalSubject OS ON OS.ClassSubjectId = CS.Id
	WHERE ED.Id=@rExamDetailId
)
BEGIN
	SELECT 1 AS RESULT
	RETURN	
END
ELSE 
BEGIN
	SELECT 1 AS RESULT
END
 	  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryOtherDetailAdd]
	 
	        @rId bigint
          -- ,@rResultId bigint
		   ,@rExamDetailId int
		   --,@rObtain Decimal(6,2)
		   --,@rIsPresent bit
		   ,@rExamId int
		   ,@rAcademicId bigint
		   ,@rOrgId int,
		   @rRemark nvarchar(100)
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
 BEGIN TRANSACTION	
--	 DECLARE @lNextNumber BIGINT 
--	 DECLARE @lMarkInDecimal bit
--	 DECLARE @lClassId int

--Select @lMarkInDecimal=IsMarksInDecimal,@lClassId = ClassId from sAssessment.tExamMaster Where Id = @rExamId
	 
--Select @lMarkInDecimal=IsMarksInDecimal from sAssessment.tExamMaster Where Id = @rExamId And ClassId IN (SELECT ClassId FROM sStudent.tAcademic WHERE ID=@rAcademicId)
--Select @lClassId = ClassId From sAssessment.tExamMaster Where Id=@rExamId

--IF @lMarkInDecimal = 0
--	BEGIN
--		SET @rObtain = ROUND(@rObtain,0)
--	END
		
--If NOT EXISTS (SELECT 1 FROM sAssessment.tExamDetail Where Id= @rExamDetailId And   ClassSubjectId in 
--				(Select cs.Id from sSetup.tClassSubject CS 
--					Left join sAssessment.tOptionalSubject O ON o.ClassSubjectId=cs.Id 
--					AND O.AcademicId=@rAcademicId
--					WHERE (CS.ClassId =@lClassId AND IsOptional = 0) OR (IsOptional = 1 AND AcademicId IS NOt Null))
--					)
--BEGIN
--	SELECT 1 as Result
--END

--ELSE IF NOT EXISTS(SELECT Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId)	
--BEGIN

--	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	 
--	INSERT INTO [sAssessment].[tResultDetail]
--			   (
--			    [Id]
--			   ,[ResultId] 
--			   ,[ExamDetailId],
--			   --,[Obtain]
--			   --,[IsPresent],
--			   Remark
--			   )
--		 VALUES
--			   (
--				@lNextNumber
--			   ,@rResultId
--			   ,@rExamDetailId,
--			  -- ,@rObtain
--			   --,@rIsPresent,
--			   @rRemark
--			   )
			  
--		    SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION         
--	END	 
--ELSE
--	 BEGIN
	 
	 Select @rId = Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId
	
	    UPDATE  [sAssessment].[tResultDetail]
	    SET
	         -- ResultId=@rResultId
	         --,ExamDetailId=@rExamDetailId,
			-- Obtain=@rObtain
			-- ,IsPresent=@rIsPresent
			-- SubjectGrade = ''
			-- ,SubjectGradePoint=0
			  --Percentile=0,
			 Remark = @rRemark
	      WHERE Id = @rId 	   
	      SELECT @rId AS Result
	
		--COMMIT TRANSACTION
	 --END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryOtherDetailGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rExamDetailId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


SELECT 
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,ISNULL(RD.Id,0) AS ResultDetailId
	,ISNULL(R.Id,0) AS ResultId  
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,ISNULL(RD.Obtain,0) AS Obtain
	,
	CASE
		WHEN RD.IsPresent = 'True' THEN 'Y'
		Else 'N'
	END  as IsPresent_Detail
	,ED.Id AS ExamDetailId
	,CONVERT(INT,ISNULL(ED.Maximum,0)) AS MaximumMark
	,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal,
	RD.Remark
from sStudent.vStudentAcademic SA 
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId

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


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryOtherOptionalSubjectDelete]
	  @rExamId int,
	  @rClassId int 
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
BEGIN TRY

	--DELETE RD from sAssessment.tResultDetail RD
	--INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	--inner jOIN sAssessment.tExamMaster E ON E.Id = Ed.ExamId
	--INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id
	--where CS.IsOptional = 1 AND RD.Obtain = 0
	--AND E.ClassId = @rClassId AND E.Id = @rExamId
	--AND E.ClassId = 115600002 AND E.Id = 115600015
 	  
	CREATE TABLE #tempResult
	(	Id int IDENTITY,
		ResultID bigint,
		AcademicId bigint
	)
  
		
	INSERT INTO #tempResult (ResultID,AcademicId) 
	SELECT R.Id,A.Id from sAssessment.tResult R 
		INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
	WHERE A.ClassId = @rClassId AND R.ExamId = @rExamId

	DECLARE @lCount int,@lAcademicId bigint,@lResultId bigint
  
	SELECT @lCount = MAX(Id) from #tempResult
 
	WHILE (@lCount > 0)
	BEGIN
	
		SELECT @lAcademicId = AcademicId,@lResultId = ResultID FROM #tempResult WHERE Id = @lCount
			
		DELETE RD FROM sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id
			AND CS.IsOptional = 1
			AND CS.Id NOT IN (SELECT ClassSubjectId from sAssessment.tOptionalSubject WHERE AcademicId = @lAcademicId)  
		WHERE 
		ResultId = @lResultId
		
		SET @lCount = @lCount -1
	
	END
	DROP TABLE #tempResult
		SELECT 1 AS Result
	END TRY
BEGIN CATCH
    DROP TABLE #tempResult
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryPercentileClassWiseUpdate]
	 @rExamId int,
	 --@rDivisionId int,
	 @rClassId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY 
 BEGIN TRANSACTION		
DECLARE @AcademicId int
DECLARE @TotalObtain Decimal(6,2)
DECLARE @lCount int
DECLARE @TotalStudent int
DECLARE @CountStuent int
DECLARE @Percentile Decimal(6,2)

begin
	CREATE TABLE #tempPercentile
 		(
 			Id INT IDENTITY (1, 1),
			AcademicId bigint, 			
 			TotalObtain decimal(6,2)
 		) 
 		INSERT INTO #tempPercentile
 		SELECT R.AcademicId,R.TotalObtain		
		FROM sAssessment.tResult R
		--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.DivisionId=@rDivisionId AND SA.BatchId = @rBatchId AND StatusId=1
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId=@rClassId AND SA.BatchId = @rBatchId AND StatusId=1
		where R.ExamId=@rExamId 		
		order by R.TotalObtain ASC,R.AcademicId

--SELECT * FROM #tempPercentile 	
SELECT @lCount =  COUNT(Id) FROM #tempPercentile
SET @TotalStudent=@lCount

while (@lCount > 0 )
BEGIN
	    SELECT @CountStuent=count(R.Id)	
		FROM sAssessment.tResult R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId=@rClassId AND SA.BatchId = @rBatchId	AND StatusId=1	
		where R.ExamId=@rExamId AND R.TotalObtain < (Select TotalObtain From #tempPercentile Where Id = @lCount)

		SET @Percentile = @CountStuent*100/@TotalStudent
		
		Update R Set R.Percentile = @Percentile From sAssessment.tResult R
		INNER JOIN 		#tempPercentile tP	ON R.AcademicId=tP.AcademicId
		Where R.ExamId=@rExamId AND tp.Id=@lCount
		
		SET @lCount = @lCount - 1
 END	
END
Drop Table #tempPercentile
SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
 	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryPercentileUpdate]
	 @rExamId int,
	 @rDivisionId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 
 BEGIN TRANSACTION		
DECLARE @AcademicId int
DECLARE @TotalObtain Decimal(6,2)
DECLARE @lCount int
DECLARE @TotalStudent int
DECLARE @CountStuent int
DECLARE @Percentile Decimal(6,2)

begin
	CREATE TABLE #tempPercentile
 		(
 			Id INT IDENTITY (1, 1),
			AcademicId bigint, 			
 			TotalObtain decimal(6,2)
 		) 
 		INSERT INTO #tempPercentile
 		SELECT R.AcademicId,R.TotalObtain		
		FROM sAssessment.tResult R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.DivisionId=@rDivisionId AND SA.BatchId = @rBatchId AND StatusId=1
		where R.ExamId=@rExamId 		
		order by R.TotalObtain ASC,R.AcademicId

--SELECT * FROM #tempPercentile 	
SELECT @lCount =  COUNT(Id) FROM #tempPercentile
SET @TotalStudent=@lCount

while (@lCount > 0 )
BEGIN
	    SELECT @CountStuent=count(R.Id)	
		FROM sAssessment.tResult R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.DivisionId=@rDivisionId AND SA.BatchId = @rBatchId	AND StatusId=1	
		where R.ExamId=@rExamId AND R.TotalObtain < (Select TotalObtain From #tempPercentile Where Id = @lCount)

		SET @Percentile = @CountStuent*100/@TotalStudent
		
		Update R Set R.Percentile = @Percentile From sAssessment.tResult R
		INNER JOIN 		#tempPercentile tP	ON R.AcademicId=tP.AcademicId
		Where R.ExamId=@rExamId AND tp.Id=@lCount
		
		SET @lCount = @lCount - 1
 END	
END
Drop Table #tempPercentile
SELECT 1 AS Result
	COMMIT TRANSACTION		
 
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

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

DECLARE  @lOrgId smallint,@lSiddhiKrupaApplicable bit, @lIsSkipRankConfigValue bit=0 

SELECT @lOrgId = OM.Id From sSetup.tBatchMaster BM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId Where BM.Id = @rBatchId
	 
SELECT @lSiddhiKrupaApplicable = ISNULL(IsApplySiddhiKrupa,0) From sAssessment.tExamMaster Where Id = @rExamId

-- Configuration Value
-- Config Assessment.IsSkipRank						     
SELECT @lIsSkipRankConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId WHERE CS.ConfigurationId = 315 AND SourceTypeId = 1016							     					     



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

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

	
	DECLARE @lIsShowSiddhiKrupaExamField bit, @lIsSetSiddhiAppliedStudentRank0 bit, @lIsMoveSiddhiRankToLast bit,@lMaxRank int
		
	-- Config Assessment.IsShowSiddhiKrupaExamField
	SELECT @lIsShowSiddhiKrupaExamField = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationSetup CS LEFT JOIN sConfig.tConfigurationMaster CM ON CM.Id = CS.ConfigurationId	WHERE CS.ConfigurationId = 278 AND SourceId = @lOrgId AND SourceTypeId = 1016

	-- Config Assessment.IsSetSiddhiAppliedStudentRank0
	SELECT @lIsSetSiddhiAppliedStudentRank0 = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId WHERE CS.ConfigurationId = 280 AND SourceTypeId = 1016

	-- Config Assessment.IsMoveSiddhiRankToLast
	SELECT @lIsMoveSiddhiRankToLast = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId	WHERE CS.ConfigurationId = 281 AND SourceTypeId = 1016	

	-- Create temp table for get ResultDetail(GraceMark,KrupaMark)
	CREATE TABLE #TempResultDetail (ResultId bigint,AcademicId bigint,GraceMark Decimal(5,2),KrupaMark Decimal(5,2))
	INSERT INTO #TempResultDetail
	SELECT DISTINCT RD.ResultId,SA.Id AS AcademicId,RD.GraceMark,RD.KrupaMark
	FROM sAssessment.tResult RS INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
	WHERE RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId

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

		AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where KrupaMark > 0) -- Edited by Kundan. Manage rank only for Grace Mark. (Updated from Grace Mark to Krupa Mark)
		) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
		AND R.Id NOT IN (Select ResultId from #TempResultDetail Where KrupaMark > 0) -- Edited by Kundan. Manage rank only for Grace Mark. (Updated from Grace Mark to Krupa Mark)
	END
	ELSE
	BEGIN
	   Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS	
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS'
		AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where KrupaMark > 0) -- Edited by Kundan. Manage rank only for Grace Mark. (Updated from Grace Mark to Krupa Mark)
		 ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
		AND R.Id NOT IN (Select ResultId from #TempResultDetail Where KrupaMark > 0) -- Edited by Kundan. Manage rank only for Grace Mark. (Updated from Grace Mark to Krupa Mark)
	END

If @lIsShowSiddhiKrupaExamField = 1 AND @lSiddhiKrupaApplicable = 1
BEGIN

-- Set Rank 0 to Those whose Siddhi/GraceMark > 0
IF @lIsSetSiddhiAppliedStudentRank0 = 1 
	BEGIN
		Update R Set R.RankNumber = 0 From sAssessment.tResult R 
		Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
		AND R.ExamId=@rExamId
		AND A.DivisionId = @rDivisionId 
		AND A.BatchId = @rBatchId
		
		IF(@lIsSkipRankConfigValue=0)
		BEGIN		
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
		END
		ELSE
		BEGIN
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
		END
	END
ELSE IF @lIsMoveSiddhiRankToLast = 1
	BEGIN
			SELECT @lMaxRank = Max(RankNumber) 
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic SA ON SA.Id= R.AcademicId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = EM.ClassId and DM.Id = SA.DivisionId
			WHERE EM.Id = @rExamId  AND DM.Id = @rDivisionId AND EM.BatchId= @rBatchId AND R.Percentage > 0
 

			IF(@lIsSkipRankConfigValue=0)
			BEGIN				
				Update R Set R.RankNumber= convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
				INNER JOIN
				(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
				from sAssessment.tResult RS
				INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
				AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
				AND RS.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0 )
				AND ResultStatus in ('PASS','PROMOTED')) A
				ON A.AcademicId = R.AcademicId 
				WHERE R.ExamId = @rExamId
				AND R.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0 )
			END
			ELSE
			BEGIN
				Update R Set R.RankNumber=convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
				INNER JOIN
				(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
				from sAssessment.tResult RS
				INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
				AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
				AND RS.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0)
				AND ResultStatus in ('PASS','PROMOTED')) A
				ON A.AcademicId = R.AcademicId 
				WHERE R.ExamId = @rExamId 
				AND R.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0)	       	       	       
			END
			END		
END

	DROP TABLE #TempResultDetail

END 

	SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryRankUpdateOld]
	 
	 @rExamId int,
	 @rDivisionId int,
	 @rBatchId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 		
--Get Siddhi Krupa Configuration Value
DECLARE @lConfigValue bit, @lRankConfigValueToSet0 bit, @lSetRankLastConfig bit, @lOrgId smallint,@lMaxRank int
DECLARE @lSiddhiKrupaApplicable bit
DECLARE @lIsSkipRankConfigValue bit=0
	 
SELECT @lSiddhiKrupaApplicable = ISNULL(IsApplySiddhiKrupa,0) From sAssessment.tExamMaster Where Id = @rExamId

SELECT @lOrgId = OM.Id From sSetup.tBatchMaster BM
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				 Where BM.Id = @rBatchId
SELECT @lConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationSetup CS
					   LEFT JOIN sConfig.tConfigurationMaster CM ON CM.Id = CS.ConfigurationId	
					   WHERE CS.ConfigurationId = 278 AND SourceId = @lOrgId AND SourceTypeId = 1016
SELECT @lRankConfigValueToSet0 = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM
							     LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId
							     WHERE CS.ConfigurationId = 280 AND SourceTypeId = 1016
SELECT @lSetRankLastConfig = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM 
						     LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId	
						     WHERE CS.ConfigurationId = 281 AND SourceTypeId = 1016	
						     
						     
SELECT @lIsSkipRankConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM 
						     LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId	
						     WHERE CS.ConfigurationId = 315 AND SourceTypeId = 1016							     					     
--End Here


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


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

   Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
	INNER JOIN
	(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
	--(Select ROW_NUMBER() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
	--(Select RANK() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
	AcademicId 
	from sAssessment.tResult RS
	INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
	AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
	AND ResultStatus='PASS' ) A
	ON A.AcademicId = R.AcademicId 
	WHERE R.ExamId = @rExamId
   
END
	
If @lConfigValue = 1 AND @lSiddhiKrupaApplicable = 1
BEGIN
      IF(@lIsSkipRankConfigValue=0)
       BEGIN
	  
		Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R		
		INNER JOIN
		(Select DENSE_RANK() OVER ( ORDER BY ResultStatus,Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus in ('PASS','PROMOTED') ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId 
		AND R.Id Not in (Select ResultId from sAssessment.tResultDetail RD where RD.ResultId=R.Id and RD.KrupaMark > 0)
		-- If krupa Mark obtain then Rank set 0
	  END
	  ELSE
	  BEGIN
	
	     Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R		
		 INNER JOIN
		(Select RANK() OVER ( ORDER BY ResultStatus,Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus in ('PASS','PROMOTED') ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId 
		AND R.Id Not in (Select ResultId from sAssessment.tResultDetail RD where RD.ResultId=R.Id and RD.KrupaMark > 0)
		-- If krupa Mark obtain then Rank set 0	  
	  END
	  
		
		IF  @lSetRankLastConfig = 1 -- Set Rank of Student Whose Siddhi/GraceMark >0 after Normal Pass Student
									-- Assessment.IsMoveSiddhiRankToLast
		BEGIN
		
			Update R Set R.RankNumber = 0 From sAssessment.tResult R 
			Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
			AND R.ExamId=@rExamId
			AND A.DivisionId = @rDivisionId 
			AND A.BatchId = @rBatchId
		
		IF(@lIsSkipRankConfigValue=0)
		BEGIN
		
			Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND RS.Id Not IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			AND ResultStatus in ('PASS','PROMOTED')) A ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId --AND R.Percentage > 0
			AND R.Id Not IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
		END
		ELSE
		BEGIN
		
		    Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND RS.Id Not IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			AND ResultStatus in ('PASS','PROMOTED')) A ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId --AND R.Percentage > 0
			AND R.Id Not IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)		     
		END	
			
			SELECT @lMaxRank = Max(RankNumber) 
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic SA ON SA.Id= R.AcademicId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = EM.ClassId and DM.Id = SA.DivisionId
			WHERE EM.Id = @rExamId  AND DM.Id = @rDivisionId AND EM.BatchId= @rBatchId AND R.Percentage > 0
			
		IF(@lIsSkipRankConfigValue=0)
		  BEGIN				
		 
			Update R Set R.RankNumber=@lMaxRank + A.RankNumber From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND RS.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			AND ResultStatus in ('PASS','PROMOTED')) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId --AND R.Percentage > 0
			AND R.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
		 END
	    ELSE
	       BEGIN
		   
	          Update R Set R.RankNumber=convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
			  INNER JOIN
			  (Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			   from sAssessment.tResult RS
			   INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			   AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			   AND RS.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			   AND ResultStatus in ('PASS','PROMOTED')) A
			   ON A.AcademicId = R.AcademicId 
			   WHERE R.ExamId = @rExamId --AND R.Percentage > 0
			   AND R.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)	       	       	       
	       END
	    	 
		 	
		END		
	
	 IF @lRankConfigValueToSet0 = 1  -- Set Rank 0 to Those whose Siddhi/GraceMark > 0
										-- Assessment.tIsSetSiddhiAppliedStudentRank0
		BEGIN
		
		IF(@lIsSkipRankConfigValue=0)
		 BEGIN		
		 
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			
			Update R Set R.RankNumber=0
			From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
		  END
		  
	     ELSE
		  
		  BEGIN
		  
		     Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			
			Update R Set R.RankNumber=0
			From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
		  
		  END
		  			
		END
END   
    
SELECT 1 AS Result
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryRankUpdateRankNotApplyToSiddhi]
	 
	 @rExamId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
--for Siddhi Rank not Apply
-- ROW_NUMBER() OVER (ORDER BY TotalObtain) AS "Row Number"    -- Row number
-- RANK() OVER (ORDER BY TotalObtain) AS Rank                  -- skip next number
-- DENSE_RANK() OVER (ORDER BY TotalObtain) AS "Dense Rank"    -- continue next number 
-- NTILE(4) OVER (ORDER BY TotalObtain) AS Quartile            -- make number of rank group    

DECLARE  @lOrgId smallint,@lSiddhiKrupaApplicable bit, @lIsSkipRankConfigValue bit=0 

SELECT @lOrgId = OM.Id From sSetup.tBatchMaster BM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId Where BM.Id = @rBatchId
	 
SELECT @lSiddhiKrupaApplicable = ISNULL(IsApplySiddhiKrupa,0) From sAssessment.tExamMaster Where Id = @rExamId

-- Configuration Value
-- Config Assessment.IsSkipRank						     
SELECT @lIsSkipRankConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId WHERE CS.ConfigurationId = 315 AND SourceTypeId = 1016							     					     



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

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

	
	DECLARE @lIsShowSiddhiKrupaExamField bit, @lIsSetSiddhiAppliedStudentRank0 bit, @lIsMoveSiddhiRankToLast bit,@lMaxRank int
		
	-- Config Assessment.IsShowSiddhiKrupaExamField
	SELECT @lIsShowSiddhiKrupaExamField = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationSetup CS LEFT JOIN sConfig.tConfigurationMaster CM ON CM.Id = CS.ConfigurationId	WHERE CS.ConfigurationId = 278 AND SourceId = @lOrgId AND SourceTypeId = 1016

	-- Config Assessment.IsSetSiddhiAppliedStudentRank0
	SELECT @lIsSetSiddhiAppliedStudentRank0 = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId WHERE CS.ConfigurationId = 280 AND SourceTypeId = 1016

	-- Config Assessment.IsMoveSiddhiRankToLast
	SELECT @lIsMoveSiddhiRankToLast = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId	WHERE CS.ConfigurationId = 281 AND SourceTypeId = 1016	

	-- Create temp table for get ResultDetail(GraceMark,KrupaMark)
	CREATE TABLE #TempResultDetail (ResultId bigint,AcademicId bigint,GraceMark Decimal(5,2),KrupaMark Decimal(5,2))
	INSERT INTO #TempResultDetail
	SELECT DISTINCT RD.ResultId,SA.Id AS AcademicId,RD.GraceMark,RD.KrupaMark
	FROM sAssessment.tResult RS INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
	WHERE RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId

	IF(@lIsSkipRankConfigValue=0)
	BEGIN
		Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS' 
		AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
		) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
		AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
	END
	ELSE
	BEGIN
	   Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS	
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS'
		AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
		 ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
		AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
	END

If @lIsShowSiddhiKrupaExamField = 1 AND @lSiddhiKrupaApplicable = 1
BEGIN

-- Set Rank 0 to Those whose Siddhi/GraceMark > 0
IF @lIsSetSiddhiAppliedStudentRank0 = 1 
	BEGIN
		Update R Set R.RankNumber = 0 From sAssessment.tResult R 
		Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
		AND R.ExamId=@rExamId
		AND A.DivisionId = @rDivisionId 
		AND A.BatchId = @rBatchId
		
		IF(@lIsSkipRankConfigValue=0)
		BEGIN		
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
		END
		ELSE
		BEGIN
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
		END
	END
ELSE IF @lIsMoveSiddhiRankToLast = 1
	BEGIN
			SELECT @lMaxRank = Max(RankNumber) 
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic SA ON SA.Id= R.AcademicId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = EM.ClassId and DM.Id = SA.DivisionId
			WHERE EM.Id = @rExamId  AND DM.Id = @rDivisionId AND EM.BatchId= @rBatchId AND R.Percentage > 0
 

			IF(@lIsSkipRankConfigValue=0)
			BEGIN				
				Update R Set R.RankNumber= convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
				INNER JOIN
				(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
				from sAssessment.tResult RS
				INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
				AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
				AND RS.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0 )
				AND ResultStatus in ('PASS','PROMOTED')) A
				ON A.AcademicId = R.AcademicId 
				WHERE R.ExamId = @rExamId
				AND R.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0 )
			END
			ELSE
			BEGIN
				Update R Set R.RankNumber=convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
				INNER JOIN
				(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
				from sAssessment.tResult RS
				INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
				AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
				AND RS.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0)
				AND ResultStatus in ('PASS','PROMOTED')) A
				ON A.AcademicId = R.AcademicId 
				WHERE R.ExamId = @rExamId 
				AND R.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0)	       	       	       
			END
			END		
END

	DROP TABLE #TempResultDetail

END 

	SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntryStudentGet]
	 @rClassId int
	,@rExamId int
	,@rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

SELECT  
	    SA.AcademicId
	   ,EM.Id AS ExamId
	   ,SA.OrgId
	   ,EM.ClassId
FROM  
	sStudent.vStudentAcademic SA 
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId 
	LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
    LEFT JOIN sAssessment.[tCCEResult] CR ON CR.AcademicId = SA.AcademicId

WHERE 
   (EM.ClassId = @rClassId OR @rClassId = 0 )    
   AND (EM.Id=@rExamId OR @rExamId = 0)
   AND (EM.BatchId = @rBatchId or @rBatchId=0)
   AND SA.StatusId=1
   
ORDER BY SA.RollNo
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntrySubjectGradeUpdate]

	 @rExamId int,
	 @rDataSetId int,
	 @rDivisionId int,
	 @rBatchId int,
	 @rClassSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION	
 
 
 	 DECLARE @lIsExcludeAbsentTotal bit
	 
	 SELECT @lIsExcludeAbsentTotal = ISNULL(IsExcludeAbsentTotal,0) FROM sAssessment.tExamMaster EM
	 WHERE EM.Id = @rExamId AND BatchId = @rBatchId
 	
DECLARE @MinimumScore decimal(5,2)
DECLARE @Grade nvarchar(20)
DECLARE @GradePoint Decimal(6,2)
DECLARE @lCount int

begin
	CREATE TABLE #tempGradeSetDetail
 		(
 			Id INT IDENTITY (1, 1),
 			MinimumScore decimal(5,2),
 			Grade nvarchar(20),
 			GradePoint Decimal(6,2)						 
 		) 
 		INSERT INTO #tempGradeSetDetail
 		SELECT MinimumScore,GradeCode,GradePoint		
		FROM sAssessment.tGradeSetDetail where GradesetId=@rDataSetID
		--order by Id Asc
 	order by MinimumScore desc
SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
while (@lCount > 0)
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@Grade= Grade,
		@GradePoint = GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		select * from #tempGradeSetDetail
IF ( @lIsExcludeAbsentTotal	= 0)
BEGIN	
    Update RD Set SubjectGrade=@Grade,SubjectGradePoint=@GradePoint 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 IsShowSubjectGrade = 1
		WHERE RD.Obtain >= @MinimumScore
		--AND (ISNULL(RD.SubjectGrade,'') = '')
		AND R.ExamId= @rExamId AND ED.GradeSetId = @rDataSetId
		AND ED.ClassSubjectId = @rClassSubjectId
		AND R.AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND BatchId = @rBatchId 
		--AND StatusId=1
		)
	END
ELSE
BEGIN	
    Update RD Set SubjectGrade=@Grade,SubjectGradePoint=@GradePoint 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 IsShowSubjectGrade = 1
		WHERE RD.Obtain >= @MinimumScore
		AND ED.ClassSubjectId = @rClassSubjectId
		--AND (ISNULL(RD.SubjectGrade,'') = '')
		AND RD.IsPresent = 1
		AND R.ExamId= @rExamId AND ED.GradeSetId = @rDataSetId
		AND R.AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND BatchId = @rBatchId 
		--AND StatusId=1
		)
	END
	SET @lCount = @lCount - 1
 END	
END
SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntrySubjectNameGet]
	 @rExamDetailId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

SELECT 
	SubjectCode + '-' + CONVERT(nvarchar,CONVERT(INT,ISNULL(ED.Maximum,0)))   AS SubjectName
FROM
	sAssessment.tExamDetail ED  
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
Where (ED.Id=@rExamDetailId OR @rExamDetailId = 0 )
 	  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMarkEntrySubjectPercentileUpdate]
	 @rExamId int,
	 @rDivisionId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION		
DECLARE @AcademicId int
DECLARE @TotalObtain Decimal(8,2)
DECLARE @lCount int
DECLARE @lCountSub int
DECLARE @TotalStudent int
DECLARE @CountStudent int
DECLARE @CountSubject int
DECLARE @Percentile Decimal(8,2)

begin
	CREATE TABLE #tempSubject
 		(
 			Id INT IDENTITY (1, 1),
 			ExamDetailId int
 		) 
 		INSERT INTO #tempSubject
 		SELECT Id FROM  sAssessment.tExamDetail WHERE ExamId = @rExamId Order By Id
		 
 		
		--SELECT ExamDetailId FROM  sAssessment.tResultDetail RD
		--INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId ANd R.ExamId=@rExamId
		--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.DivisionId=@rDivisionId AND StatusId=1
		--Order By ExamDetailId

--SELECT * FROM #tempSubject 	
SELECT @lCountSub =  COUNT(Id) FROM #tempSubject
WHILE  (@lCountSub > 0 )
BEGIN

		CREATE TABLE #tempSubjectPercentile
 		(
 			Id INT IDENTITY (1, 1),
			ResultId bigint, 			
 			SubjectObtain decimal(5,2),
 			ExamDetailId int
 		) 
 		 		INSERT INTO #tempSubjectPercentile
		SELECT R.Id,Obtain AS SubjectObtain,RD.ExamDetailId FROM  sAssessment.tResultDetail RD
		Inner join sAssessment.tResult R ON R.Id=RD.ResultId ANd R.ExamId=@rExamId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.DivisionId=@rDivisionId AND SA.BatchId = @rBatchId AND StatusId=1
		INNER JOIN #tempSubject tS ON tS.ExamDetailId = RD.ExamDetailId AND tS.Id=@lCountSub
		Order By ExamDetailId,Obtain

			--SELECT * FROM #tempSubjectPercentile 	
			SELECT @lCount =  COUNT(Id) FROM #tempSubjectPercentile 
			SET @TotalStudent=@lCount
			while (@lCount > 0 )
			BEGIN
					SELECT @CountStudent=count(RD.Id)	
					FROM sAssessment.tResultDetail RD
					INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.DivisionId=@rDivisionId AND SA.BatchId = @rBatchId	AND StatusId=1
					INNER JOIN 	#tempSubjectPercentile tSP ON tSP.ExamDetailId = RD.ExamDetailId
					where R.ExamId=@rExamId AND RD.Obtain < tSP.SubjectObtain AND tSP.Id = @lCount
					
					
					SET @Percentile = @CountStudent*100/@TotalStudent
					
					Update RD Set RD.Percentile = @Percentile From sAssessment.tResultDetail RD
					INNER JOIN 	#tempSubjectPercentile tSP	ON RD.ResultId=tSP.ResultId AND tSP.ExamDetailId = RD.ExamDetailId
					WHERE tSP.Id = @lCount
					
					SET @lCount = @lCount - 1
			  END	
		SET @lCountSub= @lCountSub-1
		drop table #tempSubjectPercentile
	END
END
 
SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pMonthlyRegisterGet]

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

BEGIN 

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

where 

	((YR.AcademicId=@rAcedamicId) OR (@rAcedamicId=0))
	AND YR.AttendanceTypeId = 1 -- MantisId : 0029240
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMyResultDetailGet]
	 
	@rExamSubGroupId int = 0,
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0,
	@rResultId bigint=0,
	@rExamId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		R.Id AS ResultId, 
		R.ExamId,
		ISNULL(E.ReportId,0) AS ReportId,
		ESGM.Title AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.ResultStatus,
		R.ResultGrade,
		R.RankNumber,
		R.Percentage,
		R.Percentile,	
		ESGM.Id AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName,
		ED.Maximum,
		ED.Minimum,
		RD.Obtain,
		SM.Code AS SubjectCode, 
		SM.Title AS SubjectTitle, 
		ISNULL(RD.SubjectGrade,'') AS SubjectGrade,
		ISNULL(E.IsRankNo,0) AS IsRank,
		ISNULL(E.IsPercentage,0) AS IsPercentage,
		ISNULL(E.IsPercentile,0) AS IsPercentile,
		ISNULL(E.IsGrade,0) AS IsResultGrade,
		ISNULL(E.IsResultStatus,0) AS IsResultStatus,
		ISNULL(E.IsMarksInDecimal,0) AS IsMarksInDecimal,
		ISNULL(E.IsDisplayTotalMark,0) IsDisplayTotalMark,
		ISNULL(ED.IsShowSubjectMark,0) As IsSubjectMark,
		ISNULL(ED.IsShowSubjectGrade,0) AS IsSubjectGrade,
		ISNULL(E.DecimalFormat,'0.00') AS DecimalFormat,
		ED.ClassSubjectId,
		CM.Id as ClassID,
		RD.IsPresent
FROM 
			sAssessment.tResult R 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			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 sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=E.Id AND RD.ExamDetailId=ED.Id 
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId=CS.Id
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		
			
	WHERE 
	
			(ESGM.Id=@rExamSubGroupId OR @rExamSubGroupId=0)
		--AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId =0))
		AND  ((StuM.Id = @rStudentId) or(@rStudentId=0))
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND (E.IsPublished = 1)  AND ISNULL(E.ReportId,0)  > 0
		AND ((R.Id=@rResultId)OR(@rResultId=0))
		AND ((R.ExamId=@rExamId)OR(@rExamId=0))
	
		ORDER BY ED.DisplayOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMyResultDetailMarkEntryWiseGet]
	 
	@rExamSubGroupId int = 0,
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0,
	@rResultId bigint=0,
	@rExamId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		R.Id AS ResultId, 
		R.ExamId,
		ISNULL(E.ReportId,0) AS ReportId,
		ESGM.Title AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.ResultStatus,
		R.ResultGrade,
		R.RankNumber,
		R.Percentage,
		R.Percentile,	
		ESGM.Id AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName,
		ED.Maximum,
		ED.Minimum,
		RD.Obtain,
		SM.Code AS SubjectCode, 
		SM.Title AS SubjectTitle, 
		ISNULL(RD.SubjectGrade,'') AS SubjectGrade,
		ISNULL(E.IsRankNo,0) AS IsRank,
		ISNULL(E.IsPercentage,0) AS IsPercentage,
		ISNULL(E.IsPercentile,0) AS IsPercentile,
		ISNULL(E.IsGrade,0) AS IsResultGrade,
		ISNULL(E.IsResultStatus,0) AS IsResultStatus,
		ISNULL(E.IsMarksInDecimal,0) AS IsMarksInDecimal,
		ISNULL(E.IsDisplayTotalMark,0) IsDisplayTotalMark,
		ISNULL(ED.IsShowSubjectMark,0) As IsSubjectMark,
		ISNULL(ED.IsShowSubjectGrade,0) AS IsSubjectGrade,
		ISNULL(E.DecimalFormat,'0.00') AS DecimalFormat,
		ED.ClassSubjectId,
		CM.Id as ClassID,
		RD.IsPresent
FROM 
			sAssessment.tResult R 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			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 sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=E.Id AND RD.ExamDetailId=ED.Id 
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId=CS.Id
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
					
	WHERE 
	
		(ESGM.Id=@rExamSubGroupId OR @rExamSubGroupId=0)
		AND  ((StuM.Id = @rStudentId) or(@rStudentId=0))
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND ((R.Id=@rResultId)OR(@rResultId=0))
		AND ((R.ExamId=@rExamId)OR(@rExamId=0))
		AND E.IsPublishMarkEntry = 1
	
		ORDER BY ED.DisplayOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pMyResultGet]
	 
	@rExamSubGroupId int = 0,
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 345 AND SourceTypeId = 1016 AND SourceId = LEFT(@rBatchId,4)


IF(@lConfigValue= 'True')
BEGIN
	SELECT
		R.Id AS ResultId, 
		R.ExamId,
		ISNULL(E.ReportId,0) AS ReportId,
		ESGM.Title AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain AS Obtain,
		R.ResultStatus,
		R.ResultGrade,
		R.RankNumber,
		R.Percentage,
		R.Percentile,	
		ESGM.Id AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName
		
		
FROM 
			sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			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 sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN sAssessment.tExamStatus ES ON E.Id=ES.ExamId AND ES.DivisionId=DM.Id
			
		
			
	WHERE 
	
			(ESGM.Id=@rExamSubGroupId OR @rExamSubGroupId=0)
		--AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId =0))
		AND  StuM.Id = @rStudentId 
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND (E.IsPublished = 1)  AND ISNULL(E.ReportId,0)  > 0
		AND (ES.StatusId = 504)
		--AND (R.ResultStatus <> '')

	
		 order by ESGM.OrderIndex asc
		
		
END
ELSE
BEGIN
		SELECT
		R.Id AS ResultId, 
		R.ExamId,
		ISNULL(E.ReportId,0) AS ReportId,
		ESGM.Title AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain AS Obtain,
		R.ResultStatus,
		R.ResultGrade,
		R.RankNumber,
		R.Percentage,
		R.Percentile,	
		ESGM.Id AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName
		
		
FROM 
			sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			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 sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN sAssessment.tExamStatus ES ON E.Id=ES.ExamId AND ES.DivisionId=DM.Id
			
		
			
	WHERE 
	
			(ESGM.Id=@rExamSubGroupId OR @rExamSubGroupId=0)
		--AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId =0))
		AND  StuM.Id = @rStudentId 
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND (E.IsPublished = 1)  AND ISNULL(E.ReportId,0)  > 0
		--AND (ES.StatusId = 504)
		--AND (R.ResultStatus <> '')

	
		 order by ESGM.OrderIndex asc
		
		
END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAssessment].[pMyResultMarkEntryWiseGet]
	 
	@rExamSubGroupId int = 0,
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT
		R.Id AS ResultId, 
		R.ExamId,
		ISNULL(E.ReportId,0) AS ReportId,
		ESGM.Title AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain AS Obtain,
		R.ResultStatus,
		R.ResultGrade,
		R.RankNumber,
		R.Percentage,
		R.Percentile,	
		ESGM.Id AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName
				
	FROM 
		sAssessment.tResult R 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		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 sAssessment.tExamMaster E ON R.ExamId = E.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
					
	WHERE 
		(ESGM.Id=@rExamSubGroupId OR @rExamSubGroupId=0)
		AND  StuM.Id = @rStudentId 
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND E.IsPublishMarkEntry = 1
	ORDER BY ESGM.OrderIndex ASC
				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pObtainMarksUpdate]
	 
	@rResultDetailsId bigint,
	@rObtainMarks decimal(8,2)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
BEGIN TRY
BEGIN TRANSACTION	
		UPDATE sAssessment.tResultDetail SET Obtain=@rObtainMarks WHERE Id=@rResultDetailsId
		SELECT 1 Result
		
COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
		
END


--select *From sAssessment.tResultDetail

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAssessment].[pOptionalAcativityAdd]
  
	@rAcademicId bigint=0,
	@rCCECSId int=0,
	@rIsOptional int=0,
	@rXmlDoc nvarchar(max) = ''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN
		SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT			

	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	
	CREATE TABLE #tTable  
	(
		 Id bigint identity
		,Academicid bigint not null
		,CCECSId int not null
		,IsOptional bit null		
	)


	INSERT INTO #tTable
			   (			    
			   Academicid
			   ,CCECSId
			   ,IsOptional			   	   		   
			   )
	SELECT		
		A.AdademicId,
		A.CCECSId,			
		A.IsOptional		
		
	FROM OPENXML (@intDoc, '/Table/CCEOptionalActivity', 1)
	WITH
	(						
		AdademicId bigint '@AdademicId',
		CCECSId int '@CCECSId',
		IsOptional bit '@IsOptional'		
	)A 

	SELECT * FROM #tTable		

	EXEC sp_xml_removedocument @intDoc

	DECLARE @lCount int = 1
	DECLARE @lTotal int = (SELECT COUNT(Id) FROM #tTable)	
	WHILE @lCount <= @lTotal 
	BEGIN						
		DECLARE @lAcademicId bigint = (SELECT AcademicId FROM #tTable WHERE Id = @lCount)		
		DECLARE @lCCECSId bigint = (SELECT CCECSId FROM #tTable WHERE Id = @lCount)		
		DECLARE @lIsOptional bigint = (SELECT IsOptional FROM #tTable WHERE Id = @lCount)	
		
		
		DELETE FROM sAssessment.tOptionalCCECS WHERE AcademicId=@lAcademicId AND CCECSId=@lCCECSId

	--	if Exists(Select 1 From sAssessment.tOptionalCCECS WHere AcademicId=@lAcademicId AND CCECSId=@lCCECSId AND 	@lIsOptional=0)
	--			BEGIN
	--				Delete from sAssessment.tOptionalCCECS where academicid=@lAcademicId AND CCECSId=@lCCECSId  
	--				Select 1 As result 
	--			END
	--		ELSe
	--		BEGIn
	--			IF exists(Select 1 from sAssessment.tOptionalCCECS where AcademicId=@lAcademicId AND CCECSId=@lCCECSId  AND @lIsOptional=1)	
	--			BEGIN
	--			Update  sAssessment.tOptionalCCECS 
	--			Set	 
	--				CCECSId=@lCCECSId
	--				Where academicid=@lAcademicId
	--				Select 1 As Result
	--		END
	--		ELSE
	--BEGIn	
	IF @lIsOptional=1
		BEGIN
			INSERT INTO sAssessment.tOptionalCCECS 
			   (
			    academicid
			   ,CCECSId
			   )
		 VALUES
			   (
				@lAcademicId
			   ,@lCCECSId	 
			   )			   	

		END
		SET @lCount = @lCount + 1	
	END	
	Select 1 as Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pOptionalSubjectAdd]
	 
	 @rAcademicId  bigint,
     @rAssignSubjectXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignSubjectXml
BEGIN
BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 DELETE FROM sAssessment.tOptionalSubject  WHERE  AcademicId=@rAcademicId
	
		INSERT INTO sAssessment.tOptionalSubject
		(
			 AcademicId,
			ClassSubjectId
		)
		SELECT
		
		    @rAcademicId,
			ClassSubjectId
		  
		FROM OPENXML (@loDoc, '/Table/AssignSubject', 1)
		WITH ( 
			
				ClassSubjectId int
			  ) 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pOptionalSubjectStatusGet]
  
	@rAcademicId [bigint],	
	@rSubjectId [bigint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
			IF EXISTS (SELECT R.Id from sAssessment.tResult R
						INNER JOIN sAssessment.tResultDetail RD on R.Id=RD.ResultId 
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id 
						INNER JOIN sAssessment.tOptionalSubject O ON R.AcademicId = O.AcademicId AND ED.ClassSubjectId = O.ClassSubjectId
						WHERE O.AcademicId = @rAcademicId AND O.ClassSubjectId = @rSubjectId)
				BEGIN
					SELECT 100 AS RESULT
				END
			ELSE
				BEGIN
					SELECT 1 AS RESULT
				END
END
 



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pOptionalSubjectStudentMarkEntryDelete]
	  @rAcademicList NVARCHAR(MAX),
	  @rClassSubjectList NVARCHAR(max),
	  @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
		DECLARE @lQuery Nvarchar(max)
	
		SET @lQuery = 'DELETE RD 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 sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=' + Convert(nvarchar,@rBatchId) + '
				AND R.AcademicId IN ' + @rAcademicList + ' 
				AND ED.ClassSubjectId IN ' + @rClassSubjectList
		execute(@lQuery)
		
		SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pOptionalSubjectStudentStatusGet]
	  @rAcademicList NVARCHAR(MAX),
	  @rClassSubjectList NVARCHAR(max),
	  @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
	DECLARE @lQuery Nvarchar(max)
	
	
	SET @lQuery = 'SELECT CASE WHEN EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
				INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamMaster E ON R.ExamId  = E.Id	
				INNER JOIN sAssessment.tExamDetail ED ON ED.Id= RD.ExamDetailId AND E.Id = ED.ExamId
						
				WHERE
				E.BatchId = ' + CAST(@rBatchId as NVARCHAR(10)) + '
				AND R.AcademicId IN ' + @rAcademicList + ' 
				AND ED.ClassSubjectId IN ' + @rClassSubjectList + ') THEN 1 ELSE 0 END AS RESULT'
	execute(@lQuery)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pOptionalSubjectWiseListGet]  
	 
	 @rSubjectId int=0,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			 SA.AcademicId,
			 CS.Id AS ClassSubjectId,
			 SA.FirstName+ ' ' +SA.MiddleName + ' ' +SA.LastName AS  StudentName,
			 CS.SubjectId,
			SM.Title as SubjectName,
			SA.Code,
			SA.RollNo,
			Dm.Id AS DivisionId,
			Dm.DisplayTitle,
			Cm.Id AS ClassId,
			Cm.Title AS ClassName,
			Dm.orderIndex AS DivisionOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			SM.OrderIndex AS SubjectOrderIndex,
		 
			
			CASE WHEN isnull(OS.ClassSubjectId,0) <> 0 THEN 'true' ELSE 'false' END AS Selected
			
			FROM 
			
			sStudent.vStudentAcademic  SA
			INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=SA.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
			INNER JOIN sSetup.tClassMaster Cm ON Cm.Id=CS.ClassId
			INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = CS.Id
			
	 WHERE 
		 
		SA.BatchId=@rBatchId
		AND ((CS.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((CS.Id=@rSubjectId )OR (@rSubjectId=0))
		AND SA.StatusId=1
		order by SA.RollNo,CS.OrderIndex 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRankSetDetailAdd]
	 
	        @rId int
           ,@rRankSetId int
		   ,@rRankCode nvarchar(20)
		   ,@rRankTitle nvarchar(50)
		   ,@rMarks Decimal(6,2)
		   ,@rMarkLimitTypeId Decimal(6,2)
		   ,@rNumberOfSubject Decimal(6,2)
		   ,@rSubjectLimitTypeId Decimal(6,2)
		   ,@rOrgId int
		   
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tRankSetDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tRankSetDetail]
			   (
			    [Id]
			   ,[RankSetId] 
			   ,[RankCode]
			   ,[RankTitle]
			   ,[Marks]
			   ,[MarksLimitTypeId]
			   ,[NumberOfSubject]
			   ,[SubjectsLimitTypeId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rRankSetId
			   ,@rRankCode
			   ,@rRankTitle
			   ,@rMarks
			   ,@rMarkLimitTypeId
			   ,@rNumberOfSubject
			   ,@rSubjectLimitTypeId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tRankSetDetail]
	    SET
	          RankSetId=@rRankSetId
	         ,RankCode=@rRankCode
			 ,RankTitle=@rRankTitle
			 ,Marks=@rMarks
			 ,MarksLimitTypeId=@rMarkLimitTypeId
			 ,NumberOfSubject=@rNumberOfSubject
			 ,SubjectsLimitTypeId=@rSubjectLimitTypeId
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRankSetDetailGet]
	 @rRankSetId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			RM.TITLE,
			RM.Code,
			RMD.RankSetId,
			RMD.Id,
			RMD.RankTitle,
			RMD.RankCode,
			RMD.Marks,
			RMD.MarksLimitTypeId,
			RMD.NumberOfSubject,
			RMD.SubjectsLimitTypeId,
			RM.IsObsolete
			
  FROM 
			[sAssessment].[tRankSetMaster] RM
			INNER JOIN sAssessment.tRankSetDetail RMD ON RMD.RankSetId=RM.id
WHERE 
			(RMD.RankSetId=@rRankSetId OR @rRankSetId=0)  order by RMD.Marks Desc
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRankSetMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tRankSetMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sAssessment.tRankSetMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tRankSetMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sAssessment.tRankSetMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tRankSetMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tRankSetMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tRankSetMaster]
	    SET
			  Code=@rCode
	         ,Title=@rTitle
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRankSetMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT Id FROM sAssessment.tExamMaster WHERE RankSetId= @rId)	
	  BEGIN
		DELETE FROM sAssessment.tRankSetDetail WHERE RankSetId IN (SELECT ID FROM sAssessment.tRankSetMaster WHERE ID=@rId)
		DELETE	FROM sAssessment.tRankSetMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRankSetMasterGet]
          
           --@rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100) ,
            @rOrgId int          
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			Set @rCode = sCommon.fSearchStringGet(@rCode)
		--END

BEGIN
SELECT GM.Id as RankSetId
	  ,GM.Title as Title
	  ,GM.Code as Code
      ,GM.IsObsolete as IsObsolete
     
  FROM [sAssessment].[tRankSetMaster] GM 
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((GM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND OrgId = @rOrgId
	--AND  CCM.IsObsolete = 0
         
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pResultAnalysisAdd]
	 @rExamId int,
	 @rAcademicId bigint,
	 @rDivisionRank tinyint,
	 @rClassRank tinyint,
	 @rPassSubject tinyint,
	 @rFailSubject tinyint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 	
 	Begin TRY
 	
 	
 	 
  
	Insert into sAssessment.tResultAnalysis
		 (AcademicId,
		  ExamId,
		  DivisionRank,
		  ClassRank,
		  PassedSubject,
		  FailedSubject
		 )
		 Values
		 (
			@rAcademicId,
			@rExamId,
			@rDivisionRank,
			@rClassRank,
			@rPassSubject,
			@rFailSubject
		)
		Select 11 AS Result
	 End Try
	 Begin Catch
		select -1 AS Result
	End Catch
	
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pResultAnalysisDetailAdd]
	 @rExamId int,
	 @rAcademicId bigint,
	 @rSubjectClassRank tinyint,
	 @rSubjectDivisionRank tinyint,
	 @rClassSubjectId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 	
 	Begin TRY
 	
   
   
	Insert into sAssessment.tResultAnalysisDetail
		 (AcademicId,
		  ExamId,
		  SubjectDivisionRank,
		  SubjectClassRank,
		  ClassSubjectId
		 )
		 Values
		 (
			@rAcademicId,
			@rExamId,
			@rSubjectDivisionRank,
			@rSubjectClassRank,
			@rClassSubjectId
		)
		Select 11 AS Result
	  ENd TRY
	  BEGIn CATCH
		Select -1 AS Result
		END CATCH
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pResultAnalysisDivisionAdd]
	 @rExamId int,
	 @rDivisionId  int,
	 @rHighestClassMark decimal(8,2),
	 @rHighestDivisionMark decimal(8,2),
	 @rHighestClassGrade nvarchar(50),
	 @rHighestDivisionGrade nvarchar(50),
	 @rAverageClassMark decimal(8,2),
	 @rAverageDivisionMark decimal(8,2),
	 @rDivisionPercentile decimal(5,2),
	 @rClassPercentile decimal(5,2),
	 @rTotalStudentDivision smallint,
	 @rTotalStudentClass smallint,
	 @rHighestClassPercentage decimal(5,2),
	 @rHighestDivisionPercentage decimal(5,2),
	 @rAverageClassPercentage decimal(5,2),
	 @rAverageDivisionPercentage decimal(5,2)
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 
 BEGIn TRY
 
	 
	
	
	Insert into sAssessment.tResultAnalysisDivision
		 (DivisionId,
		  ExamId,
		  HighestClassMark,
		  HighestDivisionMark,
		  HighestClassGrade,
		  HighestDivisionGrade,
		  AverageClassMark,
		  AverageDivisionMark,
		  DivisionPercentile,
		  ClassPercentile,
		  TotalStudentClass,
		  TotalStudentDivision,
		  HighestClassPercentage,
		  HighestDivisionPercentage,
		  AverageClassPercentage,
		  AverageDivisionPercentage
		 )
		 Values
		 (
			@rDivisionId,
			@rExamId,
			@rHighestClassMark,
			@rHighestDivisionMark,
			@rHighestClassGrade,
			@rHighestDivisionGrade,
			@rAverageClassMark,
			@rAverageDivisionMark,
			@rDivisionPercentile,
			@rClassPercentile,
			@rTotalStudentClass,
			@rTotalStudentDivision,
			@rHighestClassPercentage,
			@rHighestDivisionPercentage,
			@rAverageClassPercentage,
			@rAverageDivisionPercentage
		)
		Select 11 AS Result
	  	
		 END TRY
		 BEGIN CATCH
			Select -1 AS Result
			ENd CATCH
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pResultAnalysisDivisionDetailAdd]
	 @rExamId int,
	 @rDivisionId  int,
	 @rClassSubjectId int,
	 @rSubjectHighestClassMark decimal(5,2),
	 @rSubjectHighestDivisionMark decimal(5,2),
	 @rSubjectHighestClassGrade nvarchar(50),
	 @rSubjectHighestDivisionGrade nvarchar(50),
	 @rSubjectAverageClassMark decimal(5,2),
	 @rSubjectAverageDivisionMark decimal(5,2) 
	  
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 		 
  BEGIn TRY
  
  
  
  
	Insert into sAssessment.tResultAnalysisDivisionDetail
		 (DivisionId,
		  ExamId,
		  ClassSubjectId,
		  SubjectHighestClassMark,
		  SubjectHighestDivisionMark,
		  SubjectHighestClassGrade,
		  SubjectHighestDivisionGrade,
		  SubjectAverageClassMark,
		  SubjectAverageDivisionMark 
		 
		 )
		 Values
		 (
			@rDivisionId,
			@rExamId,
			@rClassSubjectId,
			@rSubjectHighestClassMark,
			@rSubjectHighestDivisionMark,
			@rSubjectHighestClassGrade,
			@rSubjectHighestDivisionGrade,
			@rSubjectAverageClassMark,
			@rSubjectAverageDivisionMark 
		)
		Select 11 AS Result
	 END TRY
	 BEGIN CATCH
		Select -1 As Result
	END Catch
		 
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pResultAnalysisGet]
	 
	 @rExamId int,
	 
	 @rClassId int,
	 @rBatchid int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 SELECT RES.ExamId,A.AcademicId,A.ClassRankNumber,RES.RankNumber  
			From  sAssessment.tResult RES 
	 INNER JOIN 
		(Select ROW_NUMBER() OVER(ORDER BY  TotalObtain Desc, RS.AcademicId Asc) AS ClassRankNumber , RS.AcademicId,SA.DivisionId  from sAssessment.tResult RS 
				 
				INNER JOIN  sAssessment.tExamMaster EM ON RS.ExamId=EM.Id INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId 
			 INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId  
			 
					 
					  AND EM.ExamSubGroupId=@rExamId
					 AND SA.ClassId= @rClassId AND SA.BatchId =@rBatchid AND ResultStatus='PASS'  ) A
					 ON A.AcademicId = RES.AcademicId
					  
					 INNER JOIN  sAssessment.tExamMaster EM ON RES.ExamId=EM.Id 
					  INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId  where EM.ExamSubGroupId=333300026
	  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pResultGenerateDelete]
	 @rExamId int
	,@rDivisionId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	IF EXISTS (SELECT ExamId FROM sAssessment.tExamCombine WHERE SubExamId = @rExamId)
	BEGIN 
		SELECT -101 AS Result
	END
	ELSE
		BEGIN 		
			DELETE RD FROM sAssessment.tResultDetail RD  INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
					INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND R.ExamId = @rExamId AND A.DivisionId=@rDivisionId 
			DELETE R FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic  A ON A.Id=R.AcademicId AND ExamId = @rExamId AND A.DivisionId=@rDivisionId
			DELETE FROM sAssessment.tExamStatus WHERE ExamId = @rExamId AND DivisionId = @rDivisionId
			SELECT 1 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pResultGenerateFlush]
	 @rExamId int
	,@rDivisionId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	
		BEGIN 		
			
			UPDATE RD SET	SubjectGrade='',
							SubjectGradePoint=0,
							Percentile=0.00 
							--Remark=''
			FROM sAssessment.tResultDetail RD  
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sStudent.tAcademic SA ON SA.Id = R.AcademicId 
			AND R.ExamId = @rExamId AND SA.DivisionId=@rDivisionId 
			
			UPDATE R SET	TotalMarks=0,
							TotalObtain=0,
							ResultStatus='',
							ResultGrade='',
							ResultGradePoint = 0,
							RankNumber =0,
							Percentage = 0.00,
							Percentile =0.00,
							resultRemark=''			
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic  SA ON SA.Id=R.AcademicId 
			AND ExamId = @rExamId 
			AND DivisionId=@rDivisionId
			
			
			UPDATE sAssessment.tExamStatus SET  STATUSID=503 WHERE ExamId = @rExamId AND DivisionId = @rDivisionId
			
			SELECT 1 AS RESULT
			
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pResultGenerateListGet]
	 @rExamSubGroupId int,
	 @rClassId int,
	 @rBatchId int,
	 @rDivisionId int = 0,
	 @rIsHierarchyWise bit = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	IF(@rIsHierarchyWise = 0)				 
	BEGIN
		SELECT 
		EM.ClassId,
		EM.Id AS ExamId,
		ISNULL(DM.Id,0) as DivisionId,
		ISNULL(CM.DisplayTitle + ' - ' + DM.Displaytitle,'') as Class,
		CM.DisplayTitle AS ClassName,
		ESGM.Title AS Exam,	
		isnull(SM.Title,'Process Schedule') AS Status,
		ISNULL(ES.Id,0) AS ExamStatusId,
		ISNULL(EM.ReportId,0) as ReportId,
		ESGM.Id AS ExamSubGroupId

FROM  		[sAssessment].[tExamGroupMaster] EGM			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ExamGroupId = EGM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = ESGM.Id 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 	AND (DM.Id=@rDivisionId OR @rDivisionId = 0)
			LEFT JOIN sAssessment.tExamStatus ES ON EM.Id=ES.ExamId AND ES.DivisionId=DM.Id
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=ES.StatusId
			
  WHERE		(ESGM.Id = @rExamSubGroupId Or @rExamSubGroupId=0) AND
			(EM.ClassId=@rClassId OR @rClassId =0) AND ISProcessREsult = 1 AND EM.BatchId=@rBatchId
			ORDER BY DM.OrderIndex, ESGM.Title ASC
	END
	--Hierarchywise
	ELSE
	BEGIN

		DECLARE @lExamId int

		Select  @lExamId = EM.Id FROM  [sAssessment].[tExamGroupMaster] EGM			
						  INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ExamGroupId = EGM.Id
			              INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = ESGM.Id 
		                  WHERE	(ESGM.Id = @rExamSubGroupId Or @rExamSubGroupId=0) AND (EM.ClassId=@rClassId OR @rClassId =0)  AND EM.BatchId=@rBatchId AND EM.ISProcessREsult = 1

--ExamGroup
		Select  
			EM.ClassId,
			EM.Id AS ExamId,
			ISNULL(DM.Id,0) as DivisionId,
			ISNULL(CM.DisplayTitle + ' - ' + DM.Displaytitle,'') as Class,
			CM.DisplayTitle AS ClassName,
			ESGM.Title AS Exam,	
			isnull(SM.Title,'Process Schedule') AS Status,
			ISNULL(ES.Id,0) AS ExamStatusId,
			ISNULL(EM.ReportId,0) as ReportId,
			ESGM.Id AS ExamSubGroupId,
			EM.IsIncludeSubExam
		FROM  [sAssessment].[tExamGroupMaster] EGM			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ExamGroupId = EGM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = ESGM.Id 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 	AND (DM.Id=@rDivisionId OR @rDivisionId = 0)
			LEFT JOIN sAssessment.tExamStatus ES ON EM.Id=ES.ExamId AND ES.DivisionId=DM.Id
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=ES.StatusId
		WHERE 
		(ESGM.Id = @rExamSubGroupId Or @rExamSubGroupId=0) 
		AND (EM.ClassId=@rClassId OR @rClassId =0)  
		AND EM.BatchId=@rBatchId 
		AND EM.ISProcessREsult = 1
--Combine Exams	
UNION ALL
SELECT  EM.ClassId,
		EM.Id AS ExamId,
		ISNULL(DM.Id,0) as DivisionId,
		ISNULL(CM.DisplayTitle + ' - ' + DM.Displaytitle,'') as Class,
		CM.DisplayTitle AS ClassName,
		ESGM.Title AS Exam,	
		isnull(SM.Title,'Process Schedule') AS Status,
		ISNULL(ES.Id,0) AS ExamStatusId,
		ISNULL(EM.ReportId,0) as ReportId,
		ESGM.Id AS ExamSubGroupId,
		EM.IsIncludeSubExam
FROM [sAssessment].[tExamMaster] EM 
		INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 	AND (DM.Id=@rDivisionId OR @rDivisionId = 0)
		LEFT JOIN sAssessment.tExamStatus ES ON EM.Id=ES.ExamId AND ES.DivisionId=DM.Id
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=ES.StatusId
		WHERE 
		EC.ExamId =@lExamId  
		AND (EM.ClassId=@rClassId OR @rClassId =0) 
		AND EM.BatchId =@rBatchId 
		AND EM.ISProcessREsult = 1
--SubCombine Exams
UNION ALL
SELECT EM.ClassId,
		EM.Id AS ExamId,
		ISNULL(DM.Id,0) as DivisionId,
		ISNULL(CM.DisplayTitle + ' - ' + DM.Displaytitle,'') as Class,
		CM.DisplayTitle AS ClassName,
		ESGM.Title AS Exam,	
		isnull(SM.Title,'Process Schedule') AS Status,
		ISNULL(ES.Id,0) AS ExamStatusId,
		ISNULL(EM.ReportId,0) as ReportId,
		ESGM.Id AS ExamSubGroupId,
		EM.IsIncludeSubExam
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=@lExamId)
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 	AND (DM.Id=@rDivisionId OR @rDivisionId = 0)
		LEFT JOIN sAssessment.tExamStatus ES ON EM.Id=ES.ExamId AND ES.DivisionId=DM.Id
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=ES.StatusId 
		WHERE   
		(EM.ClassId=@rClassId OR @rClassId =0) 
		AND EM.BatchId =@rBatchId 
		AND EM.ISProcessREsult = 1
	END
		 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pResultMasterListGet]
	 @rExamId int,
	 @rDivisionId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	SELECT 
	EC.ExamId AS ExamId,
	ISNULL(RM.ID,0) as ResultId,
	SA.AcademicId,
	DM.OrgId
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tClassMaster CM ON CM.Id= SA.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId=CM.Id AND EM.BatchId = SA.BatchId
	INNER JOIN sAssessment.tExamCombine EC ON EM.Id=EC.SubExamId
	LEFT JOIN sAssessment.tResult RM ON RM.ExamId=EC.ExamId	AND RM.AcademicId=SA.AcademicId
	WHERE  (EC.ExamId=@rExamId AND DM.Id =@rDivisionId AND SA.StatusId=1)
	GROUP BY RM.Id,EC.ExamId,SA.AcademicId,DM.OrgId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pResultSheetStandardMultiExamGet]	 	 	
	 @rExamId int,	
	 @rAcademicId bigint=0,
	 @rIsUseInStudent360 bit =0		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
	    SRNO INT IDENTITY(1,1) PRIMARY KEY, 
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		
		
		
		IsResultStatus bit,
		
		ResultRemark nvarchar(200),
	
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		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),
		
		
--		ResultDetailId int,
		ResultDetailId1 bigint,
		ResultDetailId2 bigint,
		ResultDetailId3 bigint,
		ResultDetailId4 bigint,
		ResultDetailId5 bigint,
		ResultDetailId6 bigint,
		ResultDetailId7 bigint,
		ResultDetailId8 bigint,
		ResultDetailId9 bigint,
		ResultDetailId10 bigint,
		ResultDetailId11 bigint,
		ResultDetailId12 bigint,
		
		
	
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		
		SubjectGroupId int,
		--SubjectGroupTitle nvarchar(50),
		--SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		--IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		
		
		AchievementsTerm1 nvarchar(200),
		AchievementsTerm2 nvarchar(200),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2)
	)	
	 --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,
	
	IsResultStatus,
	
	ResultRemark,
	
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	
	
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	
	SubjectGroupId,
	--SubjectGroupTitle,
	--SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	
    IsPresent,
    GradeTitle,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2	
	)
	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.IsResultStatus,		
		ISNULL(R.ResultRemark,'') AS ResultRemark,		
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
	
	    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,
		
		
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		
		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,
		
		IsPresent,
		GradeTitle ,
		
		
		'' 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	
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	--LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId	
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id	
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId	
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId	
	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
		
	 WHERE
		R.ExamId = @rExamId 		
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))	
		 AND ISNULL(EMP.IsOtherUser,0) = 0		    
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--ON 
	
	--If no any combine exam exist in current exam then insert current exam in combineExam for final level
	IF NOT EXISTS(select 1 FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId)
	BEGIN
	  INSERT INTO #tempcombineExam (ExamID) 
	  SELECT C.Id From sAssessment.tExamMaster C WHERE C.Id  = @rExamId
	END
	
	
	-- 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
	--print @lCount
	--select * From #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 --ExamDetailId' + convert(nvarchar(15),@lCount)+'=RD.ExamDetailId,
					  ResultDetailId' + convert(nvarchar(15),@lCount)+'=RD.Id,
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND  EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
				print @query							
	   execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					AchievementsTerm1 = SR.Achievements,
					GeneralRemarkTerm1 = SR.GeneralRemark,
					ResultRemark1Term1 = SR.ResultRemark1,
					ResultRemark2Term1 = SR.ResultRemark2,
					SR_HeightTerm1 = SR.StudentHeight,
					SR_WeightTerm1 = SR.StudentWeight,
					SR_PresentDaysTerm1 = SR.PresentDays,
					SR_TotalDaysTerm1 = SR.TotalDays
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END		
	
	SELECT T.*
	FROM #TempAllExam T  where 
	T.ExamId=@rExamId AND 
	AcademicId= @rAcademicId
	
	
	--Declare @Count AS Integer
    --SET @Count=(SELECT  count(ClassSubjectID) FROM #TempAllExam T)
    DECLARE @lCounter INT
    SET @lCounter = 1
    DECLARE @lMAXID INT=0
    
    SELECT @lMAXID = COUNT(*) FROM #TempAllExam
    Declare @FinalHtml nvarchar(max)=''
	Declare @tdHtml nvarchar(max)
	Declare @trHtml nvarchar(max)
	Declare @HeaderHtml nvarchar(max)
	Declare @HeaderCounter int=0
	Declare @thHtml nvarchar(max)
	
	WHILE (@lCounter <= @lMAXID)
	BEGIN 
	     Declare @ClassSubject nvarchar(max)
	     Declare @ResultDetailId1 nvarchar(max)
	     Declare @ResultDetailId2 nvarchar(max)
	     Declare @ResultDetailId3 nvarchar(max)
	     Declare @ResultDetailId4 nvarchar(max)
	     Declare @ResultDetailId5 nvarchar(max)
	     Declare @ResultDetailId6 nvarchar(max)
	     Declare @ResultDetailId7 nvarchar(max)
	     Declare @ResultDetailId8 nvarchar(max)
	     Declare @ResultDetailId9 nvarchar(max)
	     Declare @ResultDetailId10 nvarchar(max)
	     Declare @ResultDetailId11 nvarchar(max)
	     Declare @ResultDetailId12 nvarchar(max)
	     
	     Declare @Obtain1 decimal(10,2)
	     Declare @Obtain2 decimal(10,2)
	     Declare @Obtain3 decimal(10,2)
	     Declare @Obtain4 decimal(10,2)
	     Declare @Obtain5 decimal(10,2)
	     Declare @Obtain6 decimal(10,2)
	     Declare @Obtain7 decimal(10,2)
	     Declare @Obtain8 decimal(10,2)
	     Declare @Obtain9 decimal(10,2)
	     Declare @Obtain10 decimal(10,2)
	     Declare @Obtain11 decimal(10,2)
	     Declare @Obtain12 decimal(10,2)
	     
	     
	     Declare @ExamMaximumMarks1 decimal(10,2)
	     Declare @ExamMaximumMarks2 decimal(10,2)
	     Declare @ExamMaximumMarks3 decimal(10,2)
	     Declare @ExamMaximumMarks4 decimal(10,2)
	     Declare @ExamMaximumMarks5 decimal(10,2)
	     Declare @ExamMaximumMarks6 decimal(10,2)
	     Declare @ExamMaximumMarks7 decimal(10,2)
	     Declare @ExamMaximumMarks8 decimal(10,2)
	     Declare @ExamMaximumMarks9 decimal(10,2)
	     Declare @ExamMaximumMarks10 decimal(10,2)
	     Declare @ExamMaximumMarks11 decimal(10,2)
	     Declare @ExamMaximumMarks12 decimal(10,2)
	     
	     
	     Declare @Exam1Name nvarchar(max)
	     Declare @Exam2Name nvarchar(max)
	     Declare @Exam3Name nvarchar(max)
	     Declare @Exam4Name nvarchar(max)
	     Declare @Exam5Name nvarchar(max)
	     Declare @Exam6Name nvarchar(max)
	     Declare @Exam7Name nvarchar(max)
	     Declare @Exam8Name nvarchar(max)
	     Declare @Exam9Name nvarchar(max)
	     Declare @Exam10Name nvarchar(max)
	     Declare @Exam11Name nvarchar(max)
	     Declare @Exam12Name nvarchar(max)
	     Declare @IsMarksInDecimal bit
	     
	     
	     SET @ClassSubject=(SELECT SubjectName from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId1=(SELECT ResultDetailId1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId2=(SELECT ResultDetailId2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId3=(SELECT ResultDetailId3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId4=(SELECT ResultDetailId4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId5=(SELECT ResultDetailId5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId6=(SELECT ResultDetailId6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId7=(SELECT ResultDetailId7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId8=(SELECT ResultDetailId8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId9=(SELECT ResultDetailId9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId10=(SELECT ResultDetailId10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId11=(SELECT ResultDetailId11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId12=(SELECT ResultDetailId12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     SET @Obtain1=(SELECT Obtain1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain2=(SELECT Obtain2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain3=(SELECT Obtain3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain4=(SELECT Obtain4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain5=(SELECT Obtain5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain6=(SELECT Obtain6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain7=(SELECT Obtain7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain8=(SELECT Obtain8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain9=(SELECT Obtain9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain10=(SELECT Obtain10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain11=(SELECT Obtain11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain12=(SELECT Obtain12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     
	     
	     SET @Exam1Name=(SELECT Exam1Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam2Name=(SELECT Exam2Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam3Name=(SELECT Exam3Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam4Name=(SELECT Exam4Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam5Name=(SELECT Exam5Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam6Name=(SELECT Exam6Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam7Name=(SELECT Exam7Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam8Name=(SELECT Exam8Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam9Name=(SELECT Exam9Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam10Name=(SELECT Exam10Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam11Name=(SELECT Exam11Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam12Name=(SELECT Exam12Name from #TempAllExam WHERE SRNO=@lCounter)
	     
	     SET @ExamMaximumMarks1=(SELECT MaximumMark1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks2=(SELECT MaximumMark2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks3=(SELECT MaximumMark3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks4=(SELECT MaximumMark4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks5=(SELECT MaximumMark5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks6=(SELECT MaximumMark6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks7=(SELECT MaximumMark7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks8=(SELECT MaximumMark8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks9=(SELECT MaximumMark9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks10=(SELECT MaximumMark10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks11=(SELECT MaximumMark11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks12=(SELECT MaximumMark12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     
	     SET @IsMarksInDecimal=(SELECT IsMarksInDecimal from #TempAllExam WHERE SRNO=@lCounter)
	     --print @IsMarksInDecimal
	  IF(@rIsUseInStudent360 = 0)
	  BEGIN
	     IF(@HeaderCounter=0)
	     BEGIN
	      SET @thHtml='<th>Subjects</th>'
	      if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
	      SET @thHtml=@thHtml+'<th>'+@Exam1Name+'</th>';   
	      if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam2Name+'</th>';  
	       if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam3Name+'</th>';   
	       if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam4Name+'</th>';  
	      if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	  	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam5Name+'</th>';  
	       if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam6Name+'</th>';  
	        if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	  	  	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam7Name+'</th>';  
	        if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	  	  	    		    
	      SET @thHtml=@thHtml+'<th>'+@Exam8Name+'</th>';  
	       if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam9Name+'</th>';  
	          if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam10Name+'</th>'; 
	       if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th>'+@Exam11Name+'</th>';  
	      if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th>'+@Exam12Name+'</th>';  
	     END   
	     SET @HeaderCounter=@HeaderCounter+1;
	    
	     
	     SET @tdHtml='<td class=Sub width=200>'+@ClassSubject+'</td>';
	     
	     Declare @SetDecimalFunction nvarchar(max)
	    --print @IsMarksInDecimal
	     IF(@IsMarksInDecimal=1)
			 BEGIN
			  SET @SetDecimalFunction='onblur="javascript:return fnValidateDecimal(this,10,2)" onKeypress="javascript:return MaskDecimal(event,10,2)"';
		
			  
		 if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain1)+'</div><input  class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks1)+' value='+CONVERT(varchar(20),@Obtain1)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain2)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks2)+' value='+CONVERT(varchar(20),@Obtain2)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain3)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks3)+' value='+CONVERT(varchar(20),@Obtain3)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain4)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks4)+' value='+CONVERT(varchar(20),@Obtain4)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain5)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks5)+' value='+CONVERT(varchar(20),@Obtain5)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain6)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks6)+' value='+CONVERT(varchar(20),@Obtain6)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain7)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks7)+' value='+CONVERT(varchar(20),@Obtain7)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain8)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks8)+' value='+CONVERT(varchar(20),@Obtain8)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain9)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks9)+' value='+CONVERT(varchar(20),@Obtain9)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain10)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks10)+' value='+CONVERT(varchar(20),@Obtain10)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	     SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain11)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks11)+' value='+CONVERT(varchar(20),@Obtain11)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain12)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks12)+' value='+CONVERT(varchar(20),@Obtain12)+' '+@SetDecimalFunction+' MaxLength="100"/></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
			  
			  
			  
			 END
	     ELSE
			 BEGIN
			   
			  SET @SetDecimalFunction='onblur="javascript:return fnValidateDecimal(this,10,0)" onKeypress="javascript:return MaskDecimal(event,10,0)"';
			  
			  
		if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain1 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks1)+' value='+CONVERT(varchar(20),CAST(@Obtain1 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain2 AS int))+'</div><input class=numbersOnly type=text   ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks2)+' value='+CONVERT(varchar(20),CAST(@Obtain2 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain3 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks3)+' value='+CONVERT(varchar(20),CAST(@Obtain3 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain4 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks4)+' value='+CONVERT(varchar(20),CAST(@Obtain4 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain5 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks5)+' value='+CONVERT(varchar(20),CAST(@Obtain5 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain6 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks6)+' value='+CONVERT(varchar(20),CAST(@Obtain6 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain7 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks7)+' value='+CONVERT(varchar(20),CAST(@Obtain7 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain8 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks8)+' value='+CONVERT(varchar(20),CAST(@Obtain8 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain9 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks9)+' value='+CONVERT(varchar(20),CAST(@Obtain9 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain10 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks10)+' value='+CONVERT(varchar(20),CAST(@Obtain10 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	     SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain11 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks11)+' value='+CONVERT(varchar(20),CAST(@Obtain11 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain12 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks12)+' value='+CONVERT(varchar(20),CAST(@Obtain12 AS int))+' '+@SetDecimalFunction+' MaxLength="100"/></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
			  
			  
			 END
	     
	    SET @trHtml= '<tr>'+@tdHtml+'</tr>';
	    SET @FinalHtml=@FinalHtml+@trHtml;
       END
	   ELSE
	   BEGIN
	    IF(@HeaderCounter=0)
	     BEGIN
	      SET @thHtml='<th>Subjects</th>'
	      if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam1Name+'</th>';   
	      if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam2Name+'</th>';  
	       if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam3Name+'</th>';   
	       if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam4Name+'</th>';  
	      if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	  	    	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam5Name+'</th>';  
	       if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam6Name+'</th>';  
	        if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	  	  	    	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam7Name+'</th>';  
	        if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	  	  	    		    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam8Name+'</th>';  
	       if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam9Name+'</th>';  
	          if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam10Name+'</th>'; 
	       if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam11Name+'</th>';  
	      if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam12Name+'</th>';  

		  if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL OR @Exam2Name<>'' OR @Exam2Name IS NOT NULL OR @Exam3Name<>'' OR @Exam3Name IS NOT NULL OR
		     @Exam4Name<>'' OR @Exam4Name IS NOT NULL OR @Exam5Name<>'' OR @Exam5Name IS NOT NULL OR @Exam6Name<>'' OR @Exam6Name IS NOT NULL OR
			 @Exam7Name<>'' OR @Exam7Name IS NOT NULL OR @Exam8Name<>'' OR @Exam8Name IS NOT NULL OR @Exam9Name<>'' OR @Exam9Name IS NOT NULL OR
			 @Exam10Name<>'' OR @Exam10Name IS NOT NULL OR @Exam11Name<>'' OR @Exam11Name IS NOT NULL OR @Exam12Name<>'' OR @Exam12Name IS NOT NULL)
			 BEGIN
			 SET @thHtml=@thHtml+'<tr><td></td>';
				  if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				 
				 SET @thHtml=@thHtml+'</tr>';
			 END

	     END   
	     SET @HeaderCounter=@HeaderCounter+1;
	    
	     
	     SET @tdHtml='<td class=Sub width=200>'+@ClassSubject+'</td>';
	     
	     Declare @SetDecimalFunction1 nvarchar(max)
	    --print @IsMarksInDecimal
	     IF(@IsMarksInDecimal=1)
			 BEGIN
			  SET @SetDecimalFunction1='onblur="javascript:return fnValidateDecimal(this,10,2)" onKeypress="javascript:return MaskDecimal(event,10,2)"';
		
			  
		 if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml
		  +'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain1)+'</div></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain2)+'</div></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain3)+'</div></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain4)+'</div></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain5)+'</div></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain6)+'</div></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain7)+'</div></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain8)+'</div></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain9)+'</div></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	       SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain10)+'</div></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain11)+'</div></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain12)+'</div></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
			  
			  
			  
			 END
	     ELSE
			 BEGIN
			   
			  SET @SetDecimalFunction1='onblur="javascript:return fnValidateDecimal(this,10,0)" onKeypress="javascript:return MaskDecimal(event,10,0)"';
			  
			  
		if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml
		  +'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain1)+'</div></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain2)+'</div></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain3)+'</div></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain4)+'</div></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain5)+'</div></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain6)+'</div></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain7)+'</div></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain8)+'</div></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain9)+'</div></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	       SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain10)+'</div></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain11)+'</div></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain12)+'</div></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
			  
			  
			 END
	     
	    SET @trHtml= '<tr>'+@tdHtml+'</tr>';
	    SET @FinalHtml=@FinalHtml+@trHtml;
	   END
	     SET @lCounter = @lCounter + 1
	END
	 --print @thHtml
	select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover" style=position:relative><tr>'+@thHtml+'</tr>'+@FinalHtml+'</table>' AS Html; 
	--if(@FinalHtml IS NOT NULL and @FinalHtml <> '')	    
 --   select '<table  id="ExamDataTbl" class="table table-striped table-bordered table-hover" ><tr>'+@thHtml+'</tr>'+@FinalHtml+'</table>' AS Html; 
 --   ELSE
 --   select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover"><tr>No record found.</tr></table>' AS Html; 
			
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

--	SELECT @rBuilder1,@rBuilder2, T.* FROM sAssessment.tTempAllExam T
--end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptAllClassOverallGradeAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(max)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rDepartmentId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--select
	
	--	'' AS Grade1,
	--	'' AS Grade2,
	--	'' AS Grade3,
	--	'' AS Grade4,
	--	'' AS Grade5,
	--	'' AS Grade6,
	--	'' AS Grade7,
	--	'' AS Grade8,
	--	'' AS Grade9,
	--	'' AS Grade10,
	--	0 AS GradeCount1,
	--	0 AS GradeCount2,
	--	0 AS GradeCount3,
	--	0 AS GradeCount4,
	--	0 AS GradeCount5,
	--	0 AS GradeCount6,
	--	0 AS GradeCount7,
	--	0 AS GradeCount8,
	--	0 AS GradeCount9,
	--	0 AS GradeCount10,
	--	0 AS ClassId,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	0 AS DivisionId,
	--	0 AS NoOfStudent,
	--	0.00 AS HighestPerMark,
	--	0.00 AS AveragePerMark,
	--	0.00 AS LowestPerMark,
	    --'' AS Builder1
		
		
 
	 DECLARE @GradeSetId int
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
		
	 Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
		  
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
	 
	 	 Set @G1=(Select GradeCode from #Temp where Id=1) 
	 	 Set @G2=(Select GradeCode from #Temp where Id=2) 
	 	 Set @G3=(Select GradeCode from #Temp where Id=3) 
	 	 Set @G4=(Select GradeCode from #Temp where Id=4) 
	     Set @G5=(Select GradeCode from #Temp where Id=5) 
         Set @G6=(Select GradeCode from #Temp where Id=6) 
	     Set @G7=(Select GradeCode from #Temp where Id=7) 
	 	 Set @G8=(Select GradeCode from #Temp where Id=8) 
	 	 Set @G9=(Select GradeCode from #Temp where Id=9) 
		 Set @G10=(Select GradeCode from #Temp where Id=10)  
	   
	 select 
		@rBuilder1 AS Builder1,
		BC.ClassId As ClassId,
		Dm.id As DivisionId,
		BC.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
	  (select COUNT(R.Academicid) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) ) AS NoOfStudent,
	  
	 

	  (select MAX(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS HighestPerMark,

	  (select AVG(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS AveragePerMark,
	  
	  (select MIN(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS LowestPerMark ,
	  
	  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G1 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS GradeCount1,
  
	  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G2 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS GradeCount2,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G3 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G4 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G5 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G6 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G7 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G8 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G9 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS GradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G10 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount10,
	  
	  
   
	  ISNULL(@G1,'*') AS Grade1,
	  ISNULL(@G2,'*') AS Grade2,
	  ISNULL(@G3,'*') AS Grade3,
	  ISNULL(@G4,'*') AS Grade4,
	  ISNULL(@G5,'*') As Grade5,
	  ISNULL(@G6,'*') As Grade6,
	  ISNULL(@G7,'*') AS Grade7,
	  ISNULL(@G8,'*') AS Grade8,
	  ISNULL(@G9,'*') AS Grade9,
	 ISNULL(@G10,'*')  AS Grade10
	  

	 from
	 ssetup.tDivisionMaster DM
	 --INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	 INNER JOIN sSetup.vBatchClass BC ON BC.ClassId = DM.ClassId
	
	--INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = BC.ClassId 
	  INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=@rExamSubGroupId
		WHERE 
		    (DM.ID=@rDivisionId OR @rDivisionId=0)
			AND (Dm.ClassId=@rClassId OR @rClassId=0)
			AND BC.BatchId=@rBatchId
			--AND ESGM.Id =@rExamSubGroupId
			AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND ((BC.DepartmentId = @rDepartmentId) OR (@rDepartmentId =0))
			AND BC.Isobsolete = 0
			AND DM.IsObsolete = 0
	
  
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptAllClassSubjectGradeAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
		
 
	 DECLARE @GradeSetId int
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
		
	 --Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId AND (ClassId = @rClassId OR @rClassId = 0))

	 --According to AssessmentConfiguration
	 Set @GradeSetId = (Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId = @rOrgId)
		  --Select @GradeSetId
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
	 
	 	 Set @G1=(Select GradeCode from #Temp where Id=1) 
	 	 Set @G2=(Select GradeCode from #Temp where Id=2) 
	 	 Set @G3=(Select GradeCode from #Temp where Id=3) 
	 	 Set @G4=(Select GradeCode from #Temp where Id=4) 
	     Set @G5=(Select GradeCode from #Temp where Id=5) 
         Set @G6=(Select GradeCode from #Temp where Id=6) 
	     Set @G7=(Select GradeCode from #Temp where Id=7) 
	 	 Set @G8=(Select GradeCode from #Temp where Id=8) 
	 	 Set @G9=(Select GradeCode from #Temp where Id=9) 
		 Set @G10=(Select GradeCode from #Temp where Id=10)  
	   
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As ClassName,
		DM.DisplayTitle As DivisionName,
		
		 
	  
	  (select COUNT(RD.Id) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS NoOfStudent,
	  
	 

	  (select MAX(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS HighestPerMark,

	  (select AVG(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id   
	    INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1) AS AveragePerMark, -- Add RD.IsPresent = 1 for Mantis : 0028928
	  
	  (select MIN(RD.Obtain) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id 
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	    INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1) AS LowestPerMark , -- Add RD.IsPresent = 1 for Mantis : 0028928
	  
	  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G1  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount1,
	  
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G2  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount2,
	 

  (Select COUNT(R.AcademicId)from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G3  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A
.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G4  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((
A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G5  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A
.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G6  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A
.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G7  AND CS.SubjectId=SM.Id  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND (
(A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G8  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((
A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G9  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((
A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G10  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((
A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))AND (EM.ClassId=@rClassId OR @rClassId=0))AS GradeCount10,
	  
	  
   
	  ISNULL(@G1,'*') AS Grade1,
	  ISNULL(@G2,'*') AS Grade2,
	  ISNULL(@G3,'*') AS Grade3,
	  ISNULL(@G4,'*') AS Grade4,
	  ISNULL(@G5,'*') As Grade5,
	  ISNULL(@G6,'*') As Grade6,
	  ISNULL(@G7,'*') AS Grade7,
	  ISNULL(@G8,'*') AS Grade8,
	  ISNULL(@G9,'*') AS Grade9,
	 ISNULL(@G10,'*')  AS Grade10,
	 Sm.Id AS SubjectId,
	  SM.Title AS SubjectName,
	  CS.OrderIndex AS OrderIndex,
	  (select COUNT(R.AcademicId) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
		where 
			A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
			AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id 
			AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND ISNULL(RD.IsPresent,0) = 0 
		) AS AbsentCount,
		(select MAX(ED.Maximum) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS MaximumMark, --Mantis : 0028713

	  	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((RD.Obtain<ED.Minimum) OR (RD.IsPresent = 0)) AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS FailStudent, -- add for mantis : 0035813

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  --EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain > 0.9 * ED.Maximum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1) AS Above90PercentStudent -- add for mantis : 0035813
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND (RD.Obtain * 100/ ED.Maximum) > 90 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1) AS Above90PercentStudent -- addfor mantis : 0035813
	  
	 from
 

		sAssessment.tExamDetail ED		
		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 sSetup.tClassMaster CLM ON CLM.Id=EM.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CLM.Id
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
		
	
		WHERE 
 
			
			EM.BatchId = @rBatchId 
			AND (EM.ClassId=@rClassId OR @rClassId=0) 
			AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
			AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
			AND CM.BatchId = @rBatchId
			AND (CLM.DepartmentId=@rDepartmentId OR @rDepartmentId=0)	
			AND (ISNULL(CLM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND CLM.IsObsolete = 0 AND DM.IsObsolete=0

  	
END

-- SP Drag and Drop
--BEGIN
	--SELECT 
	-- '' AS Builder1,
	-- 0 AS ClassId,
	-- 0 AS DivisionId,
	-- '' AS ClassName,
	-- '' AS DivisionName,
	-- 0 AS NoOfStudent,
	-- Convert(DECIMAL,0) HighestPerMark,
	-- Convert(DECIMAL,0) AveragePerMark,
	-- Convert(DECIMAL,0) LowestPerMark,
	-- 0 AS GradeCount1,
	-- 0 AS GradeCount2,
	-- 0 AS GradeCount3,
	-- 0 AS GradeCount4,
	-- 0 AS GradeCount5,
	-- 0 AS GradeCount6,
	-- 0 AS GradeCount7,
	-- 0 AS GradeCount8,
	-- 0 AS GradeCount9,
	-- 0 AS GradeCount10,
	-- '' AS Grade1,
	-- '' AS Grade2,
	-- '' AS Grade3,
	-- '' AS Grade4,
	-- '' AS Grade5,
	-- '' AS Grade6,
	-- '' AS Grade7,
	-- '' AS Grade8,
	-- '' AS Grade9,
	-- '' AS Grade10,
	-- 0 AS SubjectId,
	-- '' AS SubjectName,
	-- 0 AS OrderIndex,
	-- 0 AS AbsentCount,
	-- Convert(DECIMAL,0) MaximumMark,
	-- 0 AS FailStudent,
	-- 0 AS Above90PercentStudent

--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptAllClassSubjectPercentageAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @GradeSetId int
	 Declare @M1 nvarchar(20),@M2 nvarchar(20),@M3 nvarchar(20),@M4 nvarchar(20),@M5 nvarchar(20),@M6 nvarchar(20),@M7 nvarchar(20),@M8 nvarchar(20),@M9 nvarchar(20),@M10 nvarchar(20)	
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
	 --Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = 130100010 AND BatchId=130100001)
	 Set @GradeSetId =(Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId=@rOrgId)
		  
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		MarkRange nvarchar(20),
		MinimumScore decimal(6,2)
	)
	Insert into #Temp
	
		select MarkRange,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId ORDER BY MarkRange DESC

		 Set @M1=(Select MarkRange from #Temp where Id=1) 
	 	 Set @M2=(Select MarkRange from #Temp where Id=2) 
	 	 Set @M3=(Select MarkRange from #Temp where Id=3) 
	 	 Set @M4=(Select MarkRange from #Temp where Id=4) 
	     Set @M5=(Select MarkRange from #Temp where Id=5) 
         Set @M6=(Select MarkRange from #Temp where Id=6) 
	     Set @M7=(Select MarkRange from #Temp where Id=7) 
	 	 Set @M8=(Select MarkRange from #Temp where Id=8) 
	 	 Set @M9=(Select MarkRange from #Temp where Id=9) 
		 Set @M10=(Select MarkRange from #Temp where Id=10) 

		-- Select * from #Temp
		CREATE Table #Temp1
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp1
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId ORDER BY MinimumScore DESC
	 --Select * from #Temp1
	 	 Set @G1=(Select MinimumScore from #Temp1 where Id=1) 
	 	 Set @G2=(Select MinimumScore from #Temp1 where Id=2) 
	 	 Set @G3=(Select MinimumScore from #Temp1 where Id=3) 
	 	 Set @G4=(Select MinimumScore from #Temp1 where Id=4) 
	     Set @G5=(Select MinimumScore from #Temp1 where Id=5) 
         Set @G6=(Select MinimumScore from #Temp1 where Id=6) 
	     Set @G7=(Select MinimumScore from #Temp1 where Id=7) 
	 	 Set @G8=(Select MinimumScore from #Temp1 where Id=8) 
	 	 Set @G9=(Select MinimumScore from #Temp1 where Id=9) 
		 Set @G10=(Select MinimumScore from #Temp1 where Id=10)

		 --Select @G2

		 CREATE TABLE #DetailData 
		 (
		 AcademicId bigint,
		 Maximum int,
		 Obtain int,
		 Marks decimal,
		 ClassId int,
		 SubjectId int,
		 DivisionId int
		 )

INSERT INTO #DetailData
		Select R.AcademicId,
		ED.Maximum,
		RD.Obtain,
		(RD.Obtain * 100 /ED.Maximum),
		CS.ClassId,
		CS.SubjectId,
		A.DivisionId
		from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	    INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	    INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	    where 
	    EM.ExamSubGroupId = @rExamSubGroupId 
		AND EM.BatchId = @rBatchId 
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) 
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND (EM.ClassId=@rClassId OR @rClassId=0) 

		--SELECT * FROM #DetailData  Where (Marks Between @G2 AND @G1) AND ClassId=130100002 AND SubjectId=130100001 AND DivisionId=130100003
		--Where Marks>=90

		--SELECT * FROM #DetailData

		SELECT 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		
	  (select COUNT(RD.Id) from    sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS NoOfStudent,
	  
	  (select MAX(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS HighestPerMark,

	  (select AVG(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id   
	    INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS AveragePerMark,
	  
	  (select MIN(RD.Obtain) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id 
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	    INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS LowestPerMark ,
	
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   Marks >= @G1  AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount1,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	  --AND Marks >=80 AND Marks<90
	   ((Marks >= @G2 )AND (Marks < @G1)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount2,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G3)AND (Marks < @G2)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount3,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G4 )AND (Marks < @G3)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount4,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G5 )AND (Marks < @G4)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount5,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G6)AND (Marks < @G5)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount6,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G7)AND (Marks < @G6)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount7,
	   (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G8)AND (Marks < @G7)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount8,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G9)AND (Marks < @G8)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount9,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G10)AND (Marks < @G9)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount10,
   
	  ISNULL(@M1,'-') AS Mark1,
	  ISNULL(@M2,'-') AS Mark2,
	  ISNULL(@M3,'-') AS Mark3,
	  ISNULL(@M4,'-') AS Mark4,
	  ISNULL(@M5,'-') As Mark5,
	  ISNULL(@M6,'-') As Mark6,
	  ISNULL(@M7,'-') AS Mark7,
	  ISNULL(@M8,'-') AS Mark8,
	  ISNULL(@M9,'-') AS Mark9,
	 ISNULL(@M10,'-')  AS Mark10,
	 Sm.Id AS SubjectId,
	  SM.Title AS SubjectName,
	  CS.OrderIndex AS OrderIndex 
	  

	 from

		sAssessment.tExamDetail ED		
		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 sSetup.tClassMaster CLM ON CLM.Id=EM.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CLM.Id
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	
		WHERE 
 
			EM.BatchId = @rBatchId 
			AND (EM.ClassId=@rClassId OR @rClassId=0) 
			AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
			AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
			AND CM.BatchId = @rBatchId
			AND (ISNULL(CLM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND CLM.IsObsolete = 0 AND DM.IsObsolete = 0 

		 	DROP TABLE #Temp
			DROP Table #Temp1
			DROP TABLE #DetailData
	   
  	
	
 -- select 
	--	@rBuilder1 AS Builder1,
	--	0 As ClassId,
	--	0 As DivisionId,
	--	'' As Classname,
	--	'' As DivisionName,
		
		 
	--  0 AS NoOfStudent,
	  
	 

	--  0 AS HighestPerMark,

	--  0 AS AveragePerMark,
	  
	--  0 AS LowestPerMark ,
	  
	--  0 AS MarkCount1,
	  
 -- 0 AS MarkCount2,
	 

 -- 0 AS MarkCount3,
	 

 --0 AS MarkCount4,
	 
 --0 AS MarkCount5,
	 
 -- 0 AS MarkCount6,
	 
 --0 AS MarkCount7,
	 
 -- 0 AS MarkCount8,
	 
 -- 0 AS MarkCount9,
	 
 -- 0 AS MarkCount10,
	  
	  
   
	--  0 AS Mark1,
	--  0 AS Mark2,
	--  0 AS Mark3,
	--  0 AS Mark4,
	--  0 As Mark5,
	--  0 As Mark6,
	--  0 AS Mark7,
	--  0 AS Mark8,
	--  0 AS Mark9,
	-- 0  AS Mark10,
	--0 AS SubjectId,
	--  '' AS SubjectName,
	--  0 AS OrderIndex 
	 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptBatchWiseProgressCardCoscholasticGet]
	  @rCode nvarchar(20)='',
	  @rOrgId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	declare @quer varchar(max)=''
	DEClare @lOrgId int,@lCode nvarchar(20),@lClassId int,@lDivisionId int,@lBatchId int
	DEClare @lClassGroupId int
	
  		SET @lOrgId=ISNULL(@rOrgId,0)
  		SET @lBatchId=ISNULL(@rBatchId,0)
  		SET @lClassId=ISNULL(@rClassId,0)
  		SET @lDivisionId=ISNULL(@rDivisionId,0)
  	    SET @lCode=ISNULL(@rCode,'')
     DELETE FROM sAssessment.tAllBatchResultCoScholestic 
 select @quer = 'INSERT INTO sAssessment.tAllBatchResultCoScholestic 
  	(
	CCECSId,StudentId
	)
	 SELECT 
			 DISTINCT CM.Id AS CCECSId,STM.Id AS StudentID FROM
              sAssessment.tCCECSMaster CM
              INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id=CM.CCECAGroupId
              INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CG.Id  	
              INNER JOIN sStudent.tAcademic SA ON   SA.ClassId = CL.ClassId 
              INNER JOIN sStudent.tStudentMaster STM ON STM.Id=SA.StudentId
              INNER JOIN  sAssessment.tCCECSForClass CFC ON CFC.CCECSID=CM.Id AND CL.ClassId =CFC.ClassId AND CFC.BatchID='+Convert(varchar,@lBatchId)+'
              Where CG.number=101 AND  ((STM.Code =''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
					 AND  ((SA.ClassId =''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
					 AND  ((SA.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
					  AND  SA.BatchId='+Convert(varchar,@lBatchId)+''
              
            
  			--SELECT  @quer
  	     EXEC (@quer)
  	     
	    DEClare @query varchar(max)

  		select @query=  ' UPDATE  AR  SET PG = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic   AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=101
			AND CG.Number=101'
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=102
			AND CG.Number=101'
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET SrKg = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=104
			AND CG.Number=101'
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=103
			AND CG.Number=101'
			
		
		 	exec (@query)
		 	
   select @query=  ' UPDATE  AR  SET First = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=1
			AND CG.Number=101'
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Second = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=2
			AND CG.Number=101'
			
		 	exec (@query)
		 	
		 
	select @query=  ' UPDATE  AR  SET Third = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId  
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=3
			AND CG.Number=101'
			
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId  
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +' AND CGM.ClassGroupId=4
			AND CG.Number=101'
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Fifth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE    ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=5
			AND CG.Number=101'
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=6
			AND CG.Number=101'
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=7
			AND CG.Number=101'
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Eighth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=8
			AND CG.Number=101'
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +' AND CGM.ClassGroupId=9
			AND CG.Number=101'
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Tenth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=10
			AND CG.Number=101'
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh = CCEX.DescriptiveIndicator  FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=11
			AND CG.Number=101'
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Twelfth = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''101'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=12
			AND CG.Number=101'
			exec (@query)
			
		 	select @query=  ' UPDATE  AR  SET PG1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=101 
			AND CG.Number=101'
			
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=102 
			AND CG.Number=101'
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=104 
			AND CG.Number=101'
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId 
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=103 
			AND CG.Number=101'
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=1 
			AND CG.Number=101'
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=2 
			AND CG.Number=101'
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=3 
			AND CG.Number=101'
		
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=4 
			AND CG.Number=101'
			
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=5 
			AND CG.Number=101'
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Sixth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=6 
			AND CG.Number=101'
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=7 
			AND CG.Number=101'
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eighth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=8 
			AND CG.Number=101'
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Ninth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=9 
			AND CG.Number=101'
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Tenth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=10 
			AND CG.Number=101'
			
		 	exec (@query)
		 	
		 	
	select @query=  ' UPDATE  AR  SET Eleventh1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=11 
			AND CG.Number=101'
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth1 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''102'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +  ' AND CGM.ClassGroupId=12 
			AND CG.Number=101'
				exec (@query)
		 
		 	select @query=  ' UPDATE  AR  SET PG2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=101 
			AND CG.Number=101'
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET Nursary2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=102 
			AND CG.Number=101'
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=104 
			AND CG.Number=101'
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +' AND CGM.ClassGroupId=103 
			AND CG.Number=101'
		
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=1 
			AND CG.Number=101'
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=2 
			AND CG.Number=101'
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=3 
			AND CG.Number=101'
			
		   exec (@query)
		   	
	select @query=  ' UPDATE  AR  SET Fourth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=4 
			AND CG.Number=101'
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=5 
			AND CG.Number=101'
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=6 
			AND CG.Number=101'
			exec (@query)
			
select @query=  ' UPDATE  AR  SET Seventh2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE   ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=7 
			AND CG.Number=101'
			
		 	exec (@query)
		 		
	select @query=  ' UPDATE  AR  SET Eighth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +' AND CGM.ClassGroupId=8 
			AND CG.Number=101'
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=9 
			AND CG.Number=101'
			
		 	exec (@query)
		 		
select @query=  ' UPDATE  AR  SET Tenth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) +' AND CGM.ClassGroupId=10 
			AND CG.Number=101'
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=11 
			AND CG.Number=101'
	
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth2 = CCEX.DescriptiveIndicator FROM 
			sAssessment.tAllBatchResultCoScholestic  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tCCECSExamScore CCEX ON CCEX.ExamId=EM.Id AND CCEX.AcademicId=A.Id 
			INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=CCEX.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CG ON CG.Id= CCE.CCECAGroupId AND CG.OrgId = ' + convert(varchar,@lOrgId) + '
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			WHERE  ESGM.Number = ''103'' AND A.StudentId= AR.StudentId AND AR.CCECSId = CCEX.CCECSId 
			AND CCE.OrgId =' + convert(varchar,@lOrgId) + ' AND CGM.ClassGroupId=12 
			AND CG.Number=101'
	   	exec (@query)
	   
		 	select @query='SELECT AR.StudentId,CCE.Id AS CCECSId,Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	, CCE.Title As CCETitle,A.Code,A.Name,A.BatchName,A.BatchId,CCE.OrderIndex,A.RollNo,CM.Id As ClassId,Cm.Title As Class,CM.OrderIndex As ClassOrder
		     FROM sStudent.vStudentLastAcademic A  INNER JOIN  sAssessment.tAllBatchResultCoScholestic AR ON  AR.StudentId=A.StudentId 
		     INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	       INNER JOIN sAssessment.tCCECSMaster CCE ON CCE.Id=AR.CCECSId 
	       
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) +' ' 
		    
		   
		 exec (@query)
		 
		  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptBatchWiseResultGet]
	  @rCode nvarchar(20)='',
	  @rOrgId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	declare @quer varchar(max)=''
	DEClare @lOrgId int,@lCode nvarchar(20),@lClassId int,@lDivisionId int,@lBatchId int
	DEClare @lClassGroupId int
	
  		SET @lOrgId=ISNULL(@rOrgId,0)
  		SET @lBatchId=ISNULL(@rBatchId,0)
  		SET @lClassId=ISNULL(@rClassId,0)
  		SET @lDivisionId=ISNULL(@rDivisionId,0)
  	    SET @lCode=ISNULL(@rCode,'')
     DELETE FROM sAssessment.tAllBatchResult 
 select @quer = 'INSERT INTO sAssessment.tAllBatchResult 
  	(
	SubjectId,StudentId
	)
	 SELECT 
			 DISTINCT SM.Id AS Subject,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId 
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			  INNER JOIn sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			  INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			  AND SM.OrgId=' + convert(varchar,@lOrgId) + '
			  INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=SM.Id 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '
  			  AND AB.OrgId =' + convert(varchar,@lOrgId) + '
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''
  			--SELECT  @quer
  	     EXEC (@quer)
  	     
	    DEClare @query varchar(max)

  		select @query=  ' UPDATE  AR  SET PG = RD.Obtain, PGPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary = RD.Obtain, NursaryPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET SrKg = RD.Obtain, SrKgPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg = RD.Obtain, JrKgPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		
		 	exec (@query)
		 	
   select @query=  ' UPDATE  AR  SET First = RD.Obtain, FirstPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Second = RD.Obtain, SecondPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 
	select @query=  ' UPDATE  AR  SET Third = RD.Obtain, ThirdPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth = RD.Obtain, FourthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Fifth = RD.Obtain, FifthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth = RD.Obtain, SixthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh = RD.Obtain, SeventhPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Eighth = RD.Obtain, EighthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth = RD.Obtain, NinthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Tenth = RD.Obtain, TenthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh = RD.Obtain, EleventhPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Twelfth = RD.Obtain , TwelfthPercentage = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
		 	select @query=  ' UPDATE  AR  SET PG1 = RD.Obtain, PGPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	select @query=  ' UPDATE  AR  SET Nursary1 = RD.Obtain, NursaryPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg1 = RD.Obtain, SrKgPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg1 = RD.Obtain, JrKgPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First1 = RD.Obtain, FirstPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second1 = RD.Obtain, SecondPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third1 = RD.Obtain, ThirdPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		   exec (@query)
		  
	select @query=  ' UPDATE  AR  SET Fourth1 = RD.Obtain, FourthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth1 = RD.Obtain, FifthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Sixth1 = RD.Obtain, SixthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Seventh1 = RD.Obtain, SeventhPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eighth1 = RD.Obtain, EighthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
	select @query=  ' UPDATE  AR  SET Ninth1 = RD.Obtain, NinthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
select @query=  ' UPDATE  AR  SET Tenth1 = RD.Obtain, TenthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
		 	
	select @query=  ' UPDATE  AR  SET Eleventh1 = RD.Obtain, EleventhPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth1 = RD.Obtain , TwelfthPercentage1 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
				exec (@query)
		 
		 	select @query=  ' UPDATE  AR  SET PG2 = RD.Obtain, PGPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET Nursary2 = RD.Obtain, NursaryPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET SrKg2 = RD.Obtain, SrKgPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	select @query=  ' UPDATE  AR  SET JrKg2 = RD.Obtain, JrKgPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
			
		 	exec (@query)
		 
   select @query=  ' UPDATE  AR  SET First2 = RD.Obtain, FirstPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 
		
select @query=  ' UPDATE  AR  SET Second2 = RD.Obtain, SecondPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Third2 = RD.Obtain, ThirdPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		   exec (@query)
		   	
	select @query=  ' UPDATE  AR  SET Fourth2 = RD.Obtain , FourthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Fifth2 = RD.Obtain, FifthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
select @query=  ' UPDATE  AR  SET Sixth2 = RD.Obtain, SixthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			exec (@query)
			
select @query=  ' UPDATE  AR  SET Seventh2 = RD.Obtain, SeventhPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
	select @query=  ' UPDATE  AR  SET Eighth2 = RD.Obtain, EighthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Ninth2 = RD.Obtain, NinthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 		
select @query=  ' UPDATE  AR  SET Tenth2 = RD.Obtain, TenthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
			
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Eleventh2 = RD.Obtain, EleventhPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		
		 	exec (@query)
		 	
	select @query=  ' UPDATE  AR  SET Twelfth2 = RD.Obtain , TwelfthPercentage2 = R.Percentage FROM 
			sAssessment.tAllBatchResult  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   	exec (@query)
	   
		 	select @query='SELECT AR.StudentId,SM.Id AS SubjectId,Isnull(PG,0) AS PG,Isnull(Nursary,0) AS Nursary,Isnull(SrKg,0) AS SrKg , Isnull(JrKg,0) AS JrKg,Isnull(First,0) AS FirstAnnual,
		 	Isnull(Second,0) AS Second, Isnull(Third,0) As  Third, Isnull(Fourth,0) AS Fourth,Isnull(Fifth,0) AS Fifth, Isnull(Sixth,0) AS Sixth, Isnull(Seventh,0) AS Seventh, Isnull(Eighth,0) AS Eighth, Isnull(Ninth,0) AS Ninth, 
		 	Isnull(Tenth,0) As Tenth, Isnull(Eleventh,0) As Eleventh, Isnull(Twelfth,0) As Twelfth ,
		 	Isnull(PG1,0) AS PG1,Isnull(Nursary1,0) AS Nursary1,Isnull(SrKg1,0) AS SrKg1 , Isnull(JrKg1,0) AS JrKg1,Isnull(First1,0) AS First1,
		 	Isnull(Second1,0) AS Second1, Isnull(Third1,0) As  Third1, Isnull(Fourth1,0) AS Fourth1,Isnull(Fifth1,0) AS Fifth1, Isnull(Sixth1,0) AS Sixth1, Isnull(Seventh1,0) AS Seventh1, Isnull(Eighth1,0) AS Eighth1, Isnull(Ninth1,0) AS Ninth1, 
		 	Isnull(Tenth1,0) As Tenth1, Isnull(Eleventh1,0) As Eleventh1, Isnull(Twelfth1,0) As Twelfth1,
		 	Isnull(PG2,0) AS PG2,Isnull(Nursary2,0) AS Nursary2,Isnull(SrKg2,0) AS SrKg2 , Isnull(JrKg2,0) AS JrKg2,Isnull(First2,0) AS First2,
		 	Isnull(Second2,0) AS Second2, Isnull(Third2,0) As  Third2, Isnull(Fourth2,0) AS Fourth2,Isnull(Fifth2,0) AS Fifth2, Isnull(Sixth2,0) AS Sixth2, Isnull(Seventh2,0) AS Seventh2, Isnull(Eighth2,0) AS Eighth2, Isnull(Ninth2,0) AS Ninth2, 
		 	Isnull(Tenth2,0) As Tenth2, Isnull(Eleventh2,0) As Eleventh2, Isnull(Twelfth2,0) As Twelfth2,
		 	SM.Code As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			Isnull(PGPercentage,0) AS PGPercentage,Isnull(PGPercentage1,0) AS PGPercentage1, Isnull(PGPercentage2,0) AS PGPercentage2,
			Isnull(NursaryPercentage,0) AS NursaryPercentage,Isnull(NursaryPercentage1,0) AS NursaryPercentage1, Isnull(NursaryPercentage2,0) AS NursaryPercentage2,
			Isnull(SrKgPercentage,0) AS SrKgPercentage,Isnull(SrKgPercentage1,0) AS SrKgPercentage1, Isnull(SrKgPercentage2,0) AS SrKgPercentage2,
			Isnull(JrKgPercentage,0) AS JrKgPercentage,Isnull(JrKgPercentage1,0) AS JrKgPercentage1, Isnull(JrKgPercentage2,0) AS JrKgPercentage2,
			Isnull(FirstPercentage,0) AS FirstPercentage,Isnull(FirstPercentage1,0) AS FirstPercentage1, Isnull(FirstPercentage2,0) AS FirstPercentage2,
			Isnull(SecondPercentage,0) AS SecondPercentage,Isnull(SecondPercentage1,0) AS SecondPercentage1, Isnull(SecondPercentage2,0) AS SecondPercentage2,
			Isnull(ThirdPercentage,0) AS ThirdPercentage,Isnull(ThirdPercentage1,0) AS ThirdPercentage1, Isnull(ThirdPercentage2,0) AS ThirdPercentage2,
			Isnull(FourthPercentage,0) AS FourthPercentage,Isnull(FourthPercentage1,0) AS FourthPercentage1, Isnull(FourthPercentage2,0) AS FourthPercentage2,
			Isnull(FifthPercentage,0) AS FifthPercentage,Isnull(FifthPercentage1,0) AS FifthPercentage1, Isnull(FifthPercentage2,0) AS FifthPercentage2,
			Isnull(SixthPercentage,0) AS SixthPercentage,Isnull(SixthPercentage1,0) AS SixthPercentage1, Isnull(SixthPercentage2,0) AS SixthPercentage2,
			Isnull(SeventhPercentage,0) AS SeventhPercentage,Isnull(SeventhPercentage1,0) AS SeventhPercentage1, Isnull(SeventhPercentage2,0) AS SeventhPercentage2,
			Isnull(EighthPercentage,0) AS EighthPercentage,Isnull(EighthPercentage1,0) AS EighthPercentage1, Isnull(EighthPercentage2,0) AS EighthPercentage2,
			Isnull(NinthPercentage,0) AS NinthPercentage,Isnull(NinthPercentage1,0) AS NinthPercentage1, Isnull(NinthPercentage2,0) AS NinthPercentage2,
			Isnull(TenthPercentage,0) AS TenthPercentage,Isnull(TenthPercentage1,0) AS TenthPercentage1, Isnull(TenthPercentage2,0) AS TenthPercentage2,
			Isnull(EleventhPercentage,0) AS EleventhPercentage,Isnull(EleventhPercentage1,0) AS EleventhPercentage1, Isnull(EleventhPercentage2,0) AS EleventhPercentage2,
			Isnull(TwelfthPercentage,0) AS TwelfthPercentage,Isnull(TwelfthPercentage1,0) AS TwelfthPercentage1, Isnull(TwelfthPercentage2,0) AS TwelfthPercentage2
		     FROM sStudent.vStudentLastAcademic A  INNER JOIN  sAssessment.tAllBatchResult AR ON  AR.StudentId=A.StudentId 
	       INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ' '
		   
		 exec (@query)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptBatchWiseResultGradeGet]
	  @rCode nvarchar(20)='',
	  @rOrgId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rBatchId int=0,
	  @rTotalDaysPresentDays int=0,
	  @rStudentHeightWeight int=0
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @quer varchar(max)=''
	DECLARE @lOrgId int,@lCode nvarchar(20),@lClassId int,@lDivisionId int,@lBatchId int
	DECLARE @lClassGroupId int
	
  		SET @lOrgId=ISNULL(@rOrgId,0)
  		SET @lBatchId=ISNULL(@rBatchId,0)
  		SET @lClassId=ISNULL(@rClassId,0)
  		SET @lDivisionId=ISNULL(@rDivisionId,0)
  	    SET @lCode=ISNULL(@rCode,'')
		  	    
    DELETE FROM sAssessment.tAllBatchResultGrade 
	SELECT @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  	(
	SubjectId,StudentId
	)
	 SELECT 
			 DISTINCT SM.Id AS Subject,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId 
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			  INNER JOIn sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			  INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			  AND SM.OrgId=' + convert(varchar,@lOrgId) + '
			  INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=SM.Id 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '
  			  AND AB.OrgId =' + convert(varchar,@lOrgId) + '
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''
  			--SELECT  @quer
  	     EXEC (@quer)
  	     
 -- Add New Field :  Height, Weight
 If( @rStudentHeightWeight = 1)
 BEGIN
	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -1,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			  
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			  
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
  	   
  	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -2,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			  
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			  
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
END
 
If( @rTotalDaysPresentDays = 1)
BEGIN   
  	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -3,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			  
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			 
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
  	   
  	select @quer = 'INSERT INTO sAssessment.tAllBatchResultGrade 
  		(
		SubjectId,StudentId
		)
		 SELECT 
			 -4,STM.Id AS StudentID FROM
              sStudent.tStudentMaster STM
			  INNER JOIN sStudent.tAcademic AD ON STM.Id = AD.StudentId			   
			  AND STM.OrgId=' + convert(varchar,@lOrgId) + '			 
  	          WHERE STM.OrgId=' + convert(varchar,@lOrgId) + '  			  
  			  AND ((STM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
  			  AND ((AD.ClassId = ''' + convert(varchar,@lClassId) + ''') OR (' + convert(varchar,@lClassId) + ' = 0))
  			  AND ((AD.DivisionId = ''' + convert(varchar,@lDivisionId) + ''') OR (' + convert(varchar,@lDivisionId) + ' = 0))
  			  AND  AD.BatchId='+Convert(varchar,@lBatchId)+''  			
  	   EXEC (@quer)
END  	   
-- Ends here 
  	     
	    DEClare @query varchar(max)
	    DEClare @query1 varchar(max)

  		select @query=  ' UPDATE  AR  SET PG = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
		select @query=  ' UPDATE  AR  SET Nursary = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
		select @query=  ' UPDATE  AR  SET SrKg = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		
		select @query=  ' UPDATE  AR  SET JrKg = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
        select @query=  ' UPDATE  AR  SET First = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
	 		INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 
        select @query=  ' UPDATE  AR  SET Second = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
		 
	    select @query=  ' UPDATE  AR  SET Third = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		  
	    select @query=  ' UPDATE  AR  SET Fourth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
		exec (@query)
		 
        select @query=  ' UPDATE  AR  SET Fifth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
        select @query=  ' UPDATE  AR  SET Sixth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
        select @query=  ' UPDATE  AR  SET Seventh = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 
	    select @query=  ' UPDATE  AR  SET Eighth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
	    select @query=  ' UPDATE  AR  SET Ninth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
		exec (@query)
		 	
       select @query=  ' UPDATE  AR  SET Tenth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Eleventh = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
	   select @query=  ' UPDATE  AR  SET Twelfth = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
			
	   select @query=  ' UPDATE  AR  SET PG1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Nursary1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	
	   select @query=  ' UPDATE  AR  SET SrKg1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET JrKg1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
       select @query=  ' UPDATE  AR  SET First1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		
       select @query=  ' UPDATE  AR  SET Second1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Third1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		  
	   select @query=  ' UPDATE  AR  SET Fourth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
       select @query=  ' UPDATE  AR  SET Fifth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
       select @query=  ' UPDATE  AR  SET Sixth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
       select @query=  ' UPDATE  AR  SET Seventh1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Eighth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
	   select @query=  ' UPDATE  AR  SET Ninth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
       select @query=  ' UPDATE  AR  SET Tenth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
		 	
	   select @query=  ' UPDATE  AR  SET Eleventh1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Twelfth1 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 
	   select @query=  ' UPDATE  AR  SET PG2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET Nursary2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET SrKg2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	   
	   select @query=  ' UPDATE  AR  SET JrKg2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) +''
	  exec (@query)
		 
      select @query=  ' UPDATE  AR  SET First2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId 
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	 exec (@query)
		 
		
	  select @query=  ' UPDATE  AR  SET Second2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		 	
	  select @query=  ' UPDATE  AR  SET Third2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		   	
	  select @query=  ' UPDATE  AR  SET Fourth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		 	
	  select @query=  ' UPDATE  AR  SET Fifth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	  exec (@query)
		 	
	  select @query=  ' UPDATE  AR  SET Sixth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
			
	   select @query=  ' UPDATE  AR  SET Seventh2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 		
	   select @query=  ' UPDATE  AR  SET Eighth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Ninth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 		
	   select @query=  ' UPDATE  AR  SET Tenth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Eleventh2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
		 	
	   select @query=  ' UPDATE  AR  SET Twelfth2 = RD.SubjectGrade FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
			INNER JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sAssessment.tAllBatchSubject AB ON AB.SubjectId=CS.SubjectId 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = AB.SubjectId 
			AND AB.OrgId =' + convert(varchar,@lOrgId) + ''
	   exec (@query)
	
---- Start Here Height, Weight, TotalDays, PresentDays Value Update

 DECLARE @Updatequery varchar(max)
	
  ---Sub Exam 1 Starts
 If( @rStudentHeightWeight = 1)
 BEGIN
	select @Updatequery=  ' UPDATE  AR  SET PG = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET PG = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END  

If( @rStudentHeightWeight = 1)
BEGIN
	select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END  

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
    select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
       select @Updatequery=  ' UPDATE  AR  SET First = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET First = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
        select @Updatequery=  ' UPDATE  AR  SET Second = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Second = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
     select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
     select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN  
    select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN     
   select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 101 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END   
  ---Sub Exam 1 Ends   
  ---Sub Exam 2 Starts

If( @rStudentHeightWeight = 1)
BEGIN   
   	select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END   

If( @rStudentHeightWeight = 1)
BEGIN   
	select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN     
   select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
	exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET First1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET First1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
    select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN 
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
     select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
    select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN  
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN 
    select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN     
   select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth1 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 102 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END   
  ---Sub Exam 2 Ends   
  ---Sub Exam 3 Starts

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET PG2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=101 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN
	select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Nursary2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=102 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET JrKg2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=103 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET SrKg2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=104 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
       select @Updatequery=  ' UPDATE  AR  SET First2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET First2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET First2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=1 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END
   
If( @rStudentHeightWeight = 1)
BEGIN
     select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Second2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=2 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Third2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=3 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fourth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=4 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Fifth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=5 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Sixth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=6 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Seventh2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=7 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eighth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=8 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
    select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Ninth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=9 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN    
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Tenth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=10 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Eleventh2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=11 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rStudentHeightWeight = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.StudentHeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -1 
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.StudentWeight FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -2
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END

If( @rTotalDaysPresentDays = 1)
BEGIN   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.TotalDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -3
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
   
   select @Updatequery=  ' UPDATE  AR  SET Twelfth2 = SR.PresentDays FROM 
			sAssessment.tAllBatchResultGrade  AR
			INNER join sStudent.tAcademic A ON A.StudentId = AR.StudentId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
			INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND SR.AcademicId = A.Id			
			INNER JOIN  sAssessment.tAllBatchClassGroup CGM ON CGM.ClassGroupId = CM.ClassGroupId ANd CGM.OrgId=' + convert(varchar,@lOrgId) + '		 
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			WHERE CGM.ClassGroupId=12 AND  ESGM.Number = 103 AND A.StudentId= AR.StudentId AND AR.SubjectId = -4
			AND CGM.OrgId =' + convert(varchar,@lOrgId) + ''	
   exec (@Updatequery)
END
END  
   -- Sub Exam 3 Ends   
 --   End Here Height, Weight, TotalDays, PresentDays Update 

 --add for 27332 mantis start
	CREATE TABLE #TempAllBatchClassGroup
	(
		ClassGroupId int,
		ClassGroupName nvarchar(50),
		IsObsolete bit
	)
	INSERT INTO #TempAllBatchClassGroup
	SELECT CM.Id AS ClassGroupId ,
		CM.Title AS ClassGroupName,
		CASE  WHEN BG.ClassGroupId IS null THEN 0 Else 1 END AS IsObsolete
	FROM sSetup.tClassGroupMaster CM
		LEFT JOIN  sAssessment.tAllBatchClassGroup BG  ON CM.Id=BG.ClassGroupId AND BG.OrgId=@rOrgId
	WHERE CM.Id In (103,101,102,104,1,2,3,4,5,6,7,8,9,10,11,12)

	DECLARE @lIsObsoletePG bit, @lIsObsoleteNursary bit, @lIsObsoleteJrKg bit, @lIsObsoleteSrKg bit, @lIsObsoleteFirst bit, @lIsObsoleteSecond bit, @lIsObsoleteThird bit, @lIsObsoleteFourth bit, @lIsObsoleteFifth bit, @lIsObsoleteSixth bit, @lIsObsoleteSeventh bit, @lIsObsoleteEighth bit, @lIsObsoleteNinth bit, @lIsObsoleteTenth bit, @lIsObsoleteEleventh bit, @lIsObsoleteTwelfth bit

	SELECT @lIsObsoletePG = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 101
	SELECT @lIsObsoleteNursary = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 102
	SELECT @lIsObsoleteJrKg = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 103
	SELECT @lIsObsoleteSrKg = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 104
	SELECT @lIsObsoleteFirst = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 1
	SELECT @lIsObsoleteSecond = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 2
	SELECT @lIsObsoleteThird = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 3
	SELECT @lIsObsoleteFourth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 4
	SELECT @lIsObsoleteFifth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 5
	SELECT @lIsObsoleteSixth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 6
	SELECT @lIsObsoleteSeventh = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 7
	SELECT @lIsObsoleteEighth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 8
	SELECT @lIsObsoleteNinth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 9
	SELECT @lIsObsoleteTenth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 10
	SELECT @lIsObsoleteEleventh = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 11
	SELECT @lIsObsoleteTwelfth = IsObsolete from #TempAllBatchClassGroup WHERE ClassGroupId = 12
--27332 mantis end

	If( @rTotalDaysPresentDays = 1 AND @rStudentHeightWeight = 1)	
	BEGIN
	   select @query='SELECT AR.StudentId,
			Case When AR.SubjectId > 0 then SM.Id 
			When AR.SubjectId = -1 then 999999991 
		 	When AR.SubjectId = -2 then 999999992 
		 	When AR.SubjectId = -3 then 999999993
		 	When AR.SubjectId = -4 then 999999994 end AS SubjectId,
			Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,Case When AR.SubjectId > 0 then SM.Code 
		 	When AR.SubjectId = -1 then ''HEIGHT'' 
		 	When AR.SubjectId = -2 then ''WEIGHT'' 
		 	When AR.SubjectId = -3 then ''TOTAL DAYS'' 
		 	When AR.SubjectId = -4 then ''PRESENT DAYS''		 	
		 	end As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN  sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''
		execute (@query)	
	END
	
	If( @rStudentHeightWeight = 1)	
	BEGIN
	   select @query='SELECT AR.StudentId,
			Case When AR.SubjectId > 0 then SM.Id 
			When AR.SubjectId = -1 then 999999991 
		 	When AR.SubjectId = -2 then 999999992 end AS SubjectId,		 	
			Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,Case When AR.SubjectId > 0 then SM.Code 
		 	When AR.SubjectId = -1 then ''HEIGHT'' 
		 	When AR.SubjectId = -2 then ''WEIGHT'' 
		 	end As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN  sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''
	   execute (@query)	
	END
	
	IF( @rTotalDaysPresentDays = 1)	
	BEGIN
       select @query='SELECT AR.StudentId,
			Case When AR.SubjectId > 0 then SM.Id
		 	When AR.SubjectId = -3 then 999999993
		 	When AR.SubjectId = -4 then 999999994 end AS SubjectId,
			Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,Case When AR.SubjectId > 0 then SM.Code
		 	When AR.SubjectId = -3 then ''TOTAL DAYS'' 
		 	When AR.SubjectId = -4 then ''PRESENT DAYS''
		 	end As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN  sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''
		execute (@query)	
	END
	
	ELSE
	BEGIN	
	   select @query='SELECT AR.StudentId,SM.Id AS SubjectId,Isnull(PG,'''') AS PG,Isnull(Nursary,'''') AS Nursary,Isnull(SrKg,'''') AS SrKg , Isnull(JrKg,'''') AS JrKg,Isnull(First,'''') AS FirstAnnual,
		 	Isnull(Second,'''') AS Second, Isnull(Third,'''') As  Third, Isnull(Fourth,'''') AS Fourth,Isnull(Fifth,'''') AS Fifth, Isnull(Sixth,'''') AS Sixth, Isnull(Seventh,'''') AS Seventh, Isnull(Eighth,'''') AS Eighth, Isnull(Ninth,'''') AS Ninth, 
		 	Isnull(Tenth,'''') As Tenth, Isnull(Eleventh,'''') As Eleventh, Isnull(Twelfth,'''') As Twelfth ,
		 	Isnull(PG1,'''') AS PG1,Isnull(Nursary1,'''') AS Nursary1,Isnull(SrKg1,'''') AS SrKg1 , Isnull(JrKg1,'''') AS JrKg1,Isnull(First1,'''') AS First1,
		 	Isnull(Second1,'''') AS Second1, Isnull(Third1,'''') As  Third1, Isnull(Fourth1,'''') AS Fourth1,Isnull(Fifth1,'''') AS Fifth1, Isnull(Sixth1,'''') AS Sixth1, Isnull(Seventh1,'''') AS Seventh1, Isnull(Eighth1,'''') AS Eighth1, Isnull(Ninth1,'''') AS Ninth1, 
		 	Isnull(Tenth1,'''') As Tenth1, Isnull(Eleventh1,'''') As Eleventh1, Isnull(Twelfth1,'''') As Twelfth1,
		 	Isnull(PG2,'''') AS PG2,Isnull(Nursary2,'''') AS Nursary2,Isnull(SrKg2,'''') AS SrKg2 , Isnull(JrKg2,'''') AS JrKg2,Isnull(First2,'''') AS First2,
		 	Isnull(Second2,'''') AS Second2, Isnull(Third2,'''') As  Third2, Isnull(Fourth2,'''') AS Fourth2,Isnull(Fifth2,'''') AS Fifth2, Isnull(Sixth2,'''') AS Sixth2, Isnull(Seventh2,'''') AS Seventh2, Isnull(Eighth2,'''') AS Eighth2, Isnull(Ninth2,'''') AS Ninth2, 
		 	Isnull(Tenth2,'''') As Tenth2, Isnull(Eleventh2,'''') As Eleventh2, Isnull(Twelfth2,'''') As Twelfth2
		 	,SM.Code As SubjectCode,A.Code,A.Name,A.BatchName,A.BatchId,SM.OrderIndex,A.RollNo,
			'+convert(varchar,@lIsObsoletePG)+' AS IsObsoletePG, ' + convert(varchar,@lIsObsoleteNursary) + ' AS IsObsoleteNursary, 
			' + convert(varchar,@lIsObsoleteJrKg) + ' AS IsObsoleteJrKg, ' + convert(varchar,@lIsObsoleteSrKg) + ' AS IsObsoleteSrKg,
			' + convert(varchar,@lIsObsoleteFirst) + ' AS IsObsoleteFirst, ' + convert(varchar,@lIsObsoleteSecond) + ' AS IsObsoleteSecond, 
			' + convert(varchar,@lIsObsoleteThird) + ' AS IsObsoleteThird, ' + convert(varchar,@lIsObsoleteFourth) + ' AS IsObsoleteFourth,
			' + convert(varchar,@lIsObsoleteFifth) + ' AS IsObsoleteFifth, ' + convert(varchar,@lIsObsoleteSixth) + ' AS IsObsoleteSixth, 
			' + convert(varchar,@lIsObsoleteSeventh) + ' AS IsObsoleteSeventh, ' + convert(varchar,@lIsObsoleteEighth) + ' AS IsObsoleteEighth,
			' + convert(varchar,@lIsObsoleteNinth) + ' AS IsObsoleteNinth, ' + convert(varchar,@lIsObsoleteTenth) + ' AS IsObsoleteTenth, 
			' + convert(varchar,@lIsObsoleteEleventh) + ' AS IsObsoleteEleventh, ' + convert(varchar,@lIsObsoleteTwelfth) + ' AS IsObsoleteTwelfth 	
		    FROM sStudent.vStudentLastAcademic A  
		    INNER JOIN sAssessment.tAllBatchResultGrade AR ON  AR.StudentId=A.StudentId 
	        LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=AR.SubjectId 
		    WHERE A.OrgId=' + convert(varchar,@lOrgId) + ''	
	    execute (@query)
		print @query

		DROP TABLE #TempAllBatchClassGroup

	--SELECT
	--	CONVERT(BIGINT, 0) AS StudentId,
	--	0 AS SubjectId,
	--	CONVERT(NVARCHAR(10),'') AS PG,
	--	CONVERT(NVARCHAR(10),'') AS Nursary,
	--	CONVERT(NVARCHAR(10),'') AS SrKg,
	--	CONVERT(NVARCHAR(10),'') AS JrKg,
	--	CONVERT(NVARCHAR(10),'') AS FirstAnnual,
	--	CONVERT(NVARCHAR(10),'') AS Second, 
	--	CONVERT(NVARCHAR(10),'') As  Third, 
	--	CONVERT(NVARCHAR(10),'') AS Fourth,
	--	CONVERT(NVARCHAR(10),'') AS Fifth, 
	--	CONVERT(NVARCHAR(10),'') AS Sixth, 
	--	CONVERT(NVARCHAR(10),'') AS Seventh, 
	--	CONVERT(NVARCHAR(10),'') AS Eighth, 
	--	CONVERT(NVARCHAR(10),'') AS Ninth, 
	--	CONVERT(NVARCHAR(10),'') As Tenth, 
	--	CONVERT(NVARCHAR(10),'') As Eleventh, 
	--	CONVERT(NVARCHAR(10),'') As Twelfth ,
	--	CONVERT(NVARCHAR(10),'') AS PG1,
	--	CONVERT(NVARCHAR(10),'') AS Nursary1,
	--	CONVERT(NVARCHAR(10),'') AS SrKg1 , 
	--	CONVERT(NVARCHAR(10),'') AS JrKg1,
	--	CONVERT(NVARCHAR(10),'') AS First1,
	--	CONVERT(NVARCHAR(10),'') AS Second1, 
	--	CONVERT(NVARCHAR(10),'') As  Third1, 
	--	CONVERT(NVARCHAR(10),'') AS Fourth1,
	--	CONVERT(NVARCHAR(10),'') AS Fifth1, 
	--	CONVERT(NVARCHAR(10),'') AS Sixth1, 
	--	CONVERT(NVARCHAR(10),'') AS Seventh1, 
	--	CONVERT(NVARCHAR(10),'') AS Eighth1, 
	--	CONVERT(NVARCHAR(10),'') AS Ninth1, 
	--	CONVERT(NVARCHAR(10),'') As Tenth1, 
	--	CONVERT(NVARCHAR(10),'') As Eleventh1, 
	--	CONVERT(NVARCHAR(10),'') As Twelfth1,
	--	CONVERT(NVARCHAR(10),'') AS PG2,
	--	CONVERT(NVARCHAR(10),'') AS Nursary2,
	--	CONVERT(NVARCHAR(10),'') AS SrKg2 , 
	--	CONVERT(NVARCHAR(10),'') AS JrKg2,
	--	CONVERT(NVARCHAR(10),'') AS First2,
	--	CONVERT(NVARCHAR(10),'') AS Second2, 
	--	CONVERT(NVARCHAR(10),'') As  Third2, 
	--	CONVERT(NVARCHAR(10),'') AS Fourth2,
	--	CONVERT(NVARCHAR(10),'') AS Fifth2, 
	--	CONVERT(NVARCHAR(10),'') AS Sixth2, 
	--	CONVERT(NVARCHAR(10),'') AS Seventh2, 
	--	CONVERT(NVARCHAR(10),'') AS Eighth2, 
	--	CONVERT(NVARCHAR(10),'') AS Ninth2, 
	--	CONVERT(NVARCHAR(10),'') As Tenth2, 
	--	CONVERT(NVARCHAR(10),'') As Eleventh2, 
	--	CONVERT(NVARCHAR(10),'') As Twelfth2,
	--	CONVERT(NVARCHAR(20),'') AS SubjectCode,
	--	CONVERT(NVARCHAR(20),'') as Code,
	--	CONVERT(NVARCHAR(300),'') as Name,
	--	CONVERT(NVARCHAR(100),'') as BatchName,
	--	0 as BatchId,
	--	CONVERT(SMALLINT,0) AS OrderIndex,
	--	0 AS RollNo,
	--	CONVERT(BIT,0) AS IsObsoletePG,
	--	CONVERT(BIT,0) AS IsObsoleteNursary,
	--	CONVERT(BIT,0) AS IsObsoleteJrKg,
	--	CONVERT(BIT,0) AS IsObsoleteSrKg,
	--	CONVERT(BIT,0) AS IsObsoleteFirst,
	--	CONVERT(BIT,0) AS IsObsoleteSecond,
	--	CONVERT(BIT,0) AS IsObsoleteThird,
	--	CONVERT(BIT,0) AS IsObsoleteFourth,
	--	CONVERT(BIT,0) AS IsObsoleteFifth,
	--	CONVERT(BIT,0) AS IsObsoleteSixth,
	--	CONVERT(BIT,0) AS IsObsoleteSeventh,
	--	CONVERT(BIT,0) AS IsObsoleteEighth,
	--	CONVERT(BIT,0) AS IsObsoleteNinth,
	--	CONVERT(BIT,0) AS IsObsoleteTenth,
	--	CONVERT(BIT,0) AS IsObsoleteEleventh,
	--	CONVERT(BIT,0) AS IsObsoleteTwelfth
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pRptBrightStudentAnalysisListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass NVARCHAR(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rDepartmentId int = 0,
	 @rFromRank int = 0,
	 @rToRank int = 0,
	 @rResultStatus nvarchar(20)='',  --Mantis - 34666
	 @rUniqueRank bit = 1

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
IF @rUniqueRank = 0
	BEGIN
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			DENSE_RANK() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY R.Percentage DESC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId )  AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			R.TotalMarks,
			R.TotalObtain,
			R.ResultGrade,
			DENSE_RANK() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY R.Percentage DESC) RankNumber,
			R.ResultStatus -- Add for mantis id : 0034777
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	WHERE 
		    ((EM.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((ESGM.Id=@rExamSubGroupId ) OR (@rExamSubGroupId = 0))
			AND ((SM.Code=@rCode) OR (@rCode=''))
			AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
			AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))		
			AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
			AND ((Dept.Id = @rDepartmentId) OR (@rDepartmentId =0))
			AND ((R.RankNumber>= @rFromRank) OR (@rFromRank=0))
			AND ((R.RankNumber<= @rToRank) OR (@rToRank=0))
			AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))	  --Mantis - 34666
	)r1
	WHERE ((r1.RankNumber <= @rTop) Or (@rTop = 0))
	END

ELSE

BEGIN
	SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY R.Percentage DESC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId )  AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			R.TotalMarks,
			R.TotalObtain,
			R.ResultGrade,
			R.RankNumber,
			R.ResultStatus -- Add for mantis id : 0034777
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	WHERE 
		    ((EM.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((ESGM.Id=@rExamSubGroupId ) OR (@rExamSubGroupId = 0))
			AND ((SM.Code=@rCode) OR (@rCode=''))
			AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
			AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))		
			AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
			AND ((Dept.Id = @rDepartmentId) OR (@rDepartmentId =0))
			AND ((R.RankNumber>= @rFromRank) OR (@rFromRank=0))
			AND ((R.RankNumber<= @rToRank) OR (@rToRank=0))
			AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))	  --Mantis - 34666
	)r1
	WHERE ((r1.rn <= @rTop) Or (@rTop = 0))
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptBrightStudentAnalysisListSubjectWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rSubjectId int=0,
	 --@rFromPercentage decimal(5,2)=0,
	 --@rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(max)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rDepartmentId int = 0,
	 @rFromMark decimal (5,2)=0,
	 @rToMark decimal (5,2)=0,
	 @rSubject nvarchar(max)='',--Added by dhananjay mantis id : 0035435
	 @rIsMultipleSubjects bit = 0,  --Added by dhananjay mantis id : 0035435
	 @rResultStatus nvarchar(20)=''  --Added by dhananjay mantis id : 38285
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pRptCCEResultGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	-- @rOrgId int,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rClassSubjectId int=0,
	 @rCCEExamId int=0,
	 @rAcademicId bigint=0,
	 @rStatus int =0 ,
	@rCode nvarchar(20)='',
	@rFromRollNo int,
	@rToRollNo int

	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			--@rBuilder1 AS Builder1,
			--@rBuilder2 AS Builder2,
			 CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			  CONVERT (nvarchar(20),EM.CoScholasticGradeSetId) AS CoScholasticGradeSetIdText,
			SM.Code,
			  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			A.RollNo,
			CCER.AcademicId,
			CONVERT(NVARCHAR,CCER.AcademicId) AS AcademicIdText,
			CONVERT(NVARCHAR,EM.Id)AS ExamIdText,
			CONVERT(NVARCHAR,@rCCEExamId) AS CCEExamIdText,
			CONVERT(Nvarchar,@rBatchId) AS BatchIdText,
			 
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			 
			ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			--SO.DateOfBirth,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			ISNULL(SR.StudentHeight,0) AS Height,
			ISNULL(SR.StudentWeight,0) AS Weight,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(BGM.Title,'') AS BloodGroup,
			EM.IsOnPrePrinted,
			EM.IsDisplayBirthDate,
			EM.IsDisplayPhoto,
			EM.IsDisplaySchoolName,			
			EM.IsLockForEdit,
			EM.IsIncludeCoScholastic,
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			EM.ExamSubGroupId,
			ESM.Code AS ExamSubGroupTitle,	
			EM.DisplayTitle,
			SI.StudentPhoto,
			ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
			ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
			ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
			ISNULL(EM.TermScopeId,0) AS TermScopeId,	
			TSM.Title AS TermScopeTitle,
		ISNULL(EM.ReportId,0) as ReportId,
			'' AS GradeString,
			A.BatchId,
			BM.Title,
			SR.ResultRemark1,
			SR.ResultRemark2,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
				ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
				SR.ExamSeatNo		
			
			
			--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
	
			
            sAssessment.tCCEResult CCER  
            
			INNER JOIN sStudent.tAcademic A ON CCER.AcademicId=A.Id
		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			INNER JOIN sAssessment.tCCEExamSetting CE ON CE.ClassId = CM.Id AND CE.CCEExamId = @rCCEExamId AND CE.BatchId = @rBatchId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = CE.ExamSubGroupId AND EM.ClassId = CE.ClassId AND EM.BatchId = @rBatchId 
			Inner Join sAssessment.tExamSubGroupMaster ESM ON ESM.Id=EM.ExamSubGroupId
		 --INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId
			LEFT JOIN sAssessment.tStudentRemark SR ON A. Id = SR.AcademicId AND EM. Id = SR.ExamId
			Inner Join sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			--CROSS JOIN  sAssessment.tcceRptGroup RG ON CCER.AcademicId = RG.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
				LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	WHERE 
			
    A.BatchId = @rBatchId 
		
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	 
	AND(CE.CCEExamId = @rCCEExamId OR @rCCEExamId=0)
	AND ( CCER.AcademicId=@rAcademicId OR @rAcademicId=0)
	AND (SM.StatusId=@rStatus OR @rStatus=0) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND((A.RollNo>=@rFromRollNo)OR (@rFromRollNo=0))
	AND ((A.RollNo<=@rToRollNo) OR(@rToRollNo=0))
	
	ORDER BY A.RollNo 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptClassWiseGradeAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 --@rGroupByid int=0,
	 --@rOrgId  int=0,
	 @rSubjectId int=0
	
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
		
		Select 
		A.Id AS AcademicId,
		CM.Id AS ClassId,
		DM.Id AS DivisionId,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		SM.Id AS SubjectId,
		CM.Title AS Class,
		DM.Title AS Division,
		GD.Id AS GradeId,
		--R.Id,
		D.DivisionwiseCount,
		GD.MinimumScore,
		EM.DisplayTitle AS ExamName,
		DM.OrderIndex AS DivisionOrderIndex
		 FROM sAssessment.tResultDetail  RD
		INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON A.StudentId=StuM.Id	 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		INNER JOIN 
		(Select COUNT(A1.Id) AS DivisionwiseCount,DM1.Id
			FROM sAssessment.tResultDetail  RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id=Rd1.ResultId
			INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id 
			INNER JOIN sStudent.tStudentMaster StuM1 ON A1.StudentId=StuM1.Id	
			INNER JOIN sSetup.tClassMaster CM1 ON CM1.Id=A1.ClassId
			INNER JOIN sSetup.tDivisionMaster DM1 ON DM1.Id=A1.DivisionId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ID=RD1.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id=ED1.ExamId
			INNER JOIN  sSetup.tClassSubject CS1 ON CS1.Id=ED1.ClassSubjectId 
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
		Where 
		 EM1.ExamSubGroupId=@rExamSubGroupId
		AND EM1.BatchId=@rBatchId AND StuM1.StatusId=1
		AND ((CM1.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM1.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM1.Id=@rSubjectId)  OR (@rSubjectId=0))
		Group By DM1.Id
		)D ON D.Id = DM.Id
		where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		AND EM.BatchId=@rBatchId AND StuM.StatusId=1
		AND ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Id=@rSubjectId)  OR (@rSubjectId=0))
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptCSExamIndicatorGet]
	  
	   @rOrgId int
	  ,@rExamId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rBatchId int,
	  @rCCECAGroupId int,
	  @rCCEMasterId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				--ISNULL(CGM.Title,'') AS CSGroup,
				--ISNULL(CM.Title,'') AS CS,				
				--ISNULL(CC.Grade,'')  AS Grade,
				--ISNULL(CC.GradeIndicator,'') AS Indicator,
				--ISNULL(CC.DescriptiveIndicator,'')  AS DescriptiveIndicator,			
				--ISNULL(SA.AcademicId,0) AS AcademicId,
				--ISNULL(CC.IndicatorIds,'') AS IndicatorIds,
				--CGM.GradeSetId,
				--CM.Id as CMID
				
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.IndicatorIds,'') AS Term1Indicator,
				 ISNULL(AIS.DescriptiveIndicator,'')  AS DescriptiveIndicator,		
				 CCEM.Title AS GroupTitle,
				 AM.Title AS MasterTitle
				 
			FROM sStudent.vStudentAcademic SA
				INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1
				INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
				INNER JOIN sAssessment.tCCECSGroupMaster CCEM ON CCEM.Id=AM.CCECAGroupId
				LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND CCECSId= AM.Id And AIS.ExamId=@rExamId
			WHERE
				 SA.ClassId=@rClassId 
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				AND AIS.ExamId=@rExamId
				and ((AM.CCECAGroupId=@rCCECAGroupId) OR (@rCCECAGroupId=0))
				AND((AM.Id=@rCCEMasterId) OR (@rCCEMasterId=0))	
				and AM.OrgId=@rOrgId
						
			--FROM   
			--	sAssessment.tCCECSMaster CM 
			--	INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
			--	INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id				
			--	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CL.ClassId 
			--	LEFT JOIN   sAssessment.tCCECSExamScore CC  ON CC.CCECSID=CM.ID  
			--	AND CC.AcademicId = SA.AcademicId AND ExamId=@rExamId	AND CC.AcademicId = @rAcademicId	
			--	WHERE ((SA.AcademicId = @rAcademicId) OR (@rAcademicId=0))
			--		and SA.ClassId=@rClassId and SA.DivisionId=@rDivisionId
		
			 ORDER BY SA.RollNo
			
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

BEGIN 	
BEGIN TRY
			SELECT 		
				--ISNULL(CGM.Title,'') AS CSGroup,
				--ISNULL(CM.Title,'') AS CS,				
				--ISNULL(CC.Grade,'')  AS Grade,
				--ISNULL(CC.GradeIndicator,'') AS Indicator,
				--ISNULL(CC.DescriptiveIndicator,'')  AS DescriptiveIndicator,			
				--ISNULL(SA.AcademicId,0) AS AcademicId,
				--ISNULL(CC.IndicatorIds,'') AS IndicatorIds,
				--CGM.GradeSetId,
				--CM.Id as CMID
				
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Grade,'') AS Term1Indicator,
				 CCEM.Title AS GroupTitle,
				 AM.Title AS MasterTitle,
				ISNULL(AIS.ConvertedMark,0) AS ConvertedMark,
				ISNULL(AIS.GradeIndicator,'') AS Indicator,
				ISNULL(AIS.DescriptiveIndicator,'')  AS DescriptiveIndicator	,
				CM.Id AS ClassId,
				CM.Title AS ClassTitle,
				DM.Id AS DivisionId,
				DM.Title AS DivisionTitle,
				SA.Code AS Code,
				(SELECT DisplayTitle FROM sAssessment.tExamMaster WHERE Id = @rExamId) AS ExamTitle	,
				(CASE EM.IsDisplayPhoto WHEN 1 THEN
		        SI.StudentPhoto
			    ELSE NULL END)AS StudentPhoto,
				EM.IsDisplayPhoto,
				EM.IsOnPrePrinted,
				ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
				--(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
				--OI.MarksheetHeaderA4 
				--ELSE 
				--NULL END) AS MarksheetHeaderA4,	--Mantis: 36644, this MarksheetHeaderA4 statement is commented because it takes to much time and it is not used in any report
				ISNULL(AIS.ObtianMark,0) AS ObtianMark,
				ESGM.Title AS ExamName, -- Add for mantis : 0036797
				CCEM.OrderIndex AS CCECSGroupOrderIndex -- Add for mantis : 0036797
								 
			FROM sStudent.vStudentAcademic SA
				INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchId = SA.BatchId--Added (CA.BatchId = SA.BatchId) by dhannanjay for mantis : 42395
				INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
				INNER JOIN sAssessment.tCCECSGroupMaster CCEM ON CCEM.Id=AM.CCECAGroupId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId AND SA.OrgId = CM.OrgId
				INNER JOIN sSetup.tDivisionmaster DM ON DM.Id = SA.DivisionId AND SA.OrgId = DM.OrgId
				LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND CCECSId= AM.Id And AIS.ExamId=@rExamId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = AIS.ExamId
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
				LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
				INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId -- Add for mantis : 0036797

			WHERE
				 SA.ClassId=@rClassId 
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				AND AIS.ExamId=@rExamId
				and ((AM.CCECAGroupId=@rCCECAGroupId) OR (@rCCECAGroupId=0))
				AND((AM.Id=@rCCEMasterId) OR (@rCCEMasterId=0))	
				and AM.OrgId=@rOrgId
				and ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
						
			--FROM   
			--	sAssessment.tCCECSMaster CM 
			--	INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
			--	INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id				
			--	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CL.ClassId 
			--	LEFT JOIN   sAssessment.tCCECSExamScore CC  ON CC.CCECSID=CM.ID  
			--	AND CC.AcademicId = SA.AcademicId AND ExamId=@rExamId	AND CC.AcademicId = @rAcademicId	
			--	WHERE ((SA.AcademicId = @rAcademicId) OR (@rAcademicId=0))
			--		and SA.ClassId=@rClassId and SA.DivisionId=@rDivisionId
		
			 ORDER BY SA.RollNo
			
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptCSIndicatorDetailGet]
	 @rCCECSId int,
	 @rCCECSIndicatorId int,
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT			
			CSI.Id,
			CSI.CCECSId,
			--FIM.Code,
			CSI.Number,
			CSI.TITLE,
			CSI.OrderIndex,
			CCEM.Id AS GroupMasterId,
			CCEM.Title AS GroupTitle,
			CCM.Id AS MasterId,
			CCM.Title AS MasterTitle
			
  FROM 
			sAssessment.[tCCECSIndicatorMaster] CSI
			INNER JOIN sAssessment.tCCECSMaster CCM ON CCM.Id=CSI.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CCEM ON CCEM.Id=CCM.CCECAGroupId
WHERE 
			(CSI.CCECSId=@rCCECSId OR @rCCECSId=0)  
			AND (CCM.CCECAGroupId=@rCCECSIndicatorId or @rCCECSIndicatorId=0)
			AND (CSI.OrgId=@rOrgId)
			order by CSI.OrderIndex ASC
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptCSSubjectActivityIndicatorGet]
		 @rCCESubjectSubActivityId int,
		 @rCCESubjectActivityId int,
	 @rOrgId smallint,
	 @rClassSubjectId int,
	 @rBuilder1 nvarchar(max)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			

BEGIN 		
		
	SELECT
			@rBuilder1 AS Builder1,
			AIM.Id,
			AIM.Title,
			SSA.Id AS SubActivityId,
			AIM.OrgId,
		 
			 
			AIm.OrderIndex,
			AIM.GradeSetDetailId,
			SAM.GradeSetId,
			ISNULL(AIM.Number,0) AS Number,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS SubjectActivityId,
			SAM.OrderIndex AS SubjectActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex
			
			
			
  FROM 
			sAssessment.tCCESubjectSubActivityIndicatorMaster AIM
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SSA.Id=AIM.CCESubjectSubActivityId
			INNER  JOIN	sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSA.SubjectActivityId  
			
			 
	
WHERE 
			 ((SAM.Id=@rCCESubjectActivityId) OR (@rCCESubjectActivityId=0))
			 AND ((SSA.Id=@rCCESubjectSubActivityId ) or (@rCCESubjectSubActivityId=0))
			 AND	AIm.OrgId=@rOrgId	
			 AND SAM.ClassSubjectId = @rClassSubjectId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptExamAdmitcard]
	  
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	 -- @rExamId int=0,
	  @rExamSubGroupId int=0,
	  @rCode nvarchar(20),
	  @rFromRollNo Int,
	  @rToRollNo Int,
	  @rDepartmentId int,
	  @rSubjectId int=0,
	  @rStatusId int=0,
	  @rClassStatusId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	
	SELECT 		
	       	ESGM.Title AS ExamName,
	       	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	        ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	        ISNULL(ED.ExamTime,'') as ExamTime,
	        V.SubjectName AS SubjectName,
	        CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	         CM.DisplayTitle AS ClassName,
	         CM.Id As ClassId,
	         DM.Id AS DiVisionId,
	        V.ClassSubjectId AS ClassSubjectId,
	        SA.Name,
	        SA.RollNo,
	        SA.Code,
	        SF.FatherName,
	        So.DateOfBirth,
	        GM.Title AS Gender,
	        EM.Remark1,
	        EM.Remark2,
	        EM.Remark3,
	        SA.AcademicId,
	        SI.StudentPhoto,
	        SF.MotherName,
	        SR. ExamCenter,
	        SR.ExamSeatNo,
	        V.SubjectCode AS SubjectCode,
		
	         
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4 ,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			EM.IsOnPrePrinted ,
	        --EM.Id As ExamId,
			EM.IsDisplayPhoto,
			SR.ExamBlock,
			EI.EmployeeSign,
			EM.TeacherSignCaption,
			EM.PrincipalSignCaption,
			EM.ParentSignCaption,
			ISNULL(EM.DisplayTitle,'') AS DisplayTitle ,
			ISNULL(ED.ExamTopic,'') AS ExamTopic,
			ISNULL(ED.ExamLanguage,'') AS ExamLanguage,
			ISNULL(SA.OrganizationName,'') AS OrganizationName,
			ISNULL(SA.SUId,'') AS SUId ,
			EM.IsDisplayPrincipalSign AS IsDisplayPrincipalSign,
			ISNULL(SO.UIDNumber,'') AS UId ,
			CSM.Title As CasteCategory ,
		    ISNULL(SO.AdhaarNumber,'') AS AdhaarNumber,
			ISNULL(SO.FamilySubCast,'') AS FamilySubCast,
			DM.DisplayTitle AS DivisionName,   -- 30455
			--mantis Start - 36986		
			ISNULL(SR.ResultRemark1,'') AS ResultRemark1,
			ISNULL(SR.ResultRemark2,'') AS ResultRemark2,
			ISNULL(SR.ResultRemark3,'') AS ResultRemark3,
			--mantis End - 36986	
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.MarksheetHeaderA4 
			ELSE NULL END)AS  MarksheetHeader, --Mantis - 40209
			--Added by dhananjay For mantis : 43184
			EMI.EmployeeSign AS ExamCoordinatorSignature, 
			ISNULL(SC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(SC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(SC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(SC.PresentCountry,'') AS PresentCountry,
			ISNULL(SC.PresentState,'') AS PresentState,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			ISNULL(SC.PresentZipCode,'') AS PresentZipCode,
			--Added by dhananjay For mantis : 43184
			EM.ResultSheetAdditionalTitle	--Mantis - 43319


			FROM
			sStudent.vStudentAcademic SA 
			INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  ANd Em.BatchId=SA.BatchId 
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId--Added by dhananjay For mantis : 43184
			LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId=SA.AcademicId and OS.ClassSubjectId=V.ClassSubjectId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId  
			LEFT JOIN sStudent.tStudentOther SO ON So.StudentId=SA.StudentId  
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=So.GenderId   
			LEFT JOIN  sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId=EM.Id AND SR.AcademicId=SA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			LEFT JOIN sHrm.tEmployeeImages EMI ON EMI.EmployeeId = EM.CoordinatorEmployeeId --Added by dhananjay For mantis : 43184

	WHERE 
			SA.BatchId = @rBatchId 
		 AND (SA.ClassId=@rClassId OR @rClassId=0) 
		 AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))	
	     AND ((SA.Code=@rCode) OR (@rCode=''))
	     AND (SA.DepartmentId=@rDepartmentId OR @rDepartmentId=0) 
	     AND (V.SubjectId=@rSubjectId OR @rSubjectId=0) 
	    AND ((V.IsOptional = 1 AND  isnull(OS.AcademicId,0) <> 0) OR (V.IsOptional = 0))
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId = 0))
		AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
	
	Order by ED.ExamDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptExamFullGet]
	 @rId int=0,
	 @rExamIds nvarchar(200)='',
	 @rBuilder1 nvarchar(200)='' 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	

					 
	SELECT 
	EM.Id,
	@rBuilder1 AS Builder1,
	Convert (nvarchar(20),EM.Id) AS ExamIdText,
	EM.BatchId,
	ESGM.Code,
	ESGM.Title AS Name,
	ESGM.Id AS ExamGRoupId,
	EM.ClassId,
	--EC.Id,
	--EM.IsRankNo,
	CASE WHEN ISNULL(IsRankNo,0) = 0 THEN 'No' ELSE 'Yes' END AS IsIsRankNo,
	--EM.IsGrade,
	CASE WHEN ISNULL(IsGrade,0) = 0 THEN 'No' ELSE 'Yes' END AS IsGrade,
	--EM.IsPercentile,
	CASE WHEN ISNULL(IsPercentile,0) = 0 THEN 'No' ELSE 'Yes' END AS IsPercentile,
	--EM.IsPercentage,
	CASE WHEN ISNULL(IsPercentage,0) = 0 THEN 'No' ELSE 'Yes' END AS IsPercentage,
	--EM.IsSubjectPercentile,
	CASE WHEN ISNULL(IsSubjectPercentile,0) = 0 THEN 'No' ELSE 'Yes' END AS IsSubjectPercentile,
	ISNULL(EM.GradeSetId,0) AS GradeSetId,
	ISNULL(EM.RankSetId,0) AS RankSetId,
	ISNULL(EM.LevelSetId,0) AS LevelSetId ,
	CASE WHEN ISNULL(IsProcessResult,0) = 0 THEN 'No' ELSE 'Yes' END AS IsProcessResult,
	CASE WHEN IsNull(IsMarksInDecimal,0) = 0 THEN 'No' ELSE 'Yes' END AS IsMarksInDecimal,
	CASE WHEN ISNULL(ISNegativeMarks,0)=0 THEN 'No' ELSE 'Yes' END AS ISNegativeMarks,
	Isnull(ED.Id,0) as ExamDetailId,
	ISNULL(ED.GradeSetId,0) as GradeSetDetailId,
	ISNULL(ED.ExamId,0) as ExamId,
	ISNULL(CS.Id,0) as ClassSubjectId,
	ISNULL(ED.Maximum,0) as Maximum,
	ISNULL(ED.Minimum,0) as Minimum,
	--ISNULL(ED.IsIncludeInTotal,0) as IsIncludeInTotal,
	CASE WHEN ISNULL(IsIncludeInTotal,0)=0 THEN 'No' ELSE 'Yes' END AS IsIncludeInTotal,
	--ISNULL(ED.IsDisplayInMarksheet,0) as IsDisplayInMarksheet,
	CASE WHEN ISNULL(IsDisplayInMarksheet,0)=0 THEN 'No' ELSE 'Yes' END AS IsDisplayInMarksheet,
	--ISNULL(ED.IsShowSubjectGrade,0) as IsShowSubjectGrade,
	CASE WHEN ISNULL(IsShowSubjectGrade,0)=0 THEN 'No' ELSE 'Yes' END AS IsShowSubjectGrade,
	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	ISNULL(ED.ExamTime,'') as ExamTime,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	ISNULL(ED.ExamLanguage,'') as ExamLanguage,
	GSM.Title as GradeSET,
	EGM.Title as ExamGroup,
	ESGM.Title as ExamName,
	SM.Title as SubjectName,
	CM.DisplayTitle as ClassName,
	
	CASE WHEN ISNULL(IsOnPrePrinted,0) = 0 THEN 'No' ELSE 'Yes' END AS IsOnPrePrinted,
	CASE WHEN ISNULL(IsDisplayBirthDate,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayBirthDate,
	CASE WHEN ISNULL(IsDisplayPhoto,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayPhoto,
	CASE WHEN ISNULL(IsDisplaySchoolName,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplaySchoolName,
	CASE WHEN ISNULL(IsLockForEdit,0) = 0 THEN 'No' ELSE 'Yes' END AS IsLockForEdit,
	CASE WHEN ISNULL(IsIncludeCoScholastic,0) = 0 THEN 'No' ELSE 'Yes' END AS IsIncludeCoScholastic,
	
	CASE WHEN ISNULL(IsDisplayAttendance,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayAttendance,
	CASE WHEN ISNULL(IsDisplayHeightWeight,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayHeightWeight,
	CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayResultStatus,
	EM.Remark1,
	EM.Remark2,
	EM.Remark3,
	EM.DisplayTitle,
	ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
	ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
	ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
	--ISNULL(EM.TermScopeId,0) AS TermScopeId,	
	TSM.Title AS TermScopeTitle,
	ISNULL(EM.ReportId,0) as ReportId,
	CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected,
	CASE WHEN ISNULL(IsShowSubjectMark,0)=0 THEN 'No' ELSE 'Yes' END AS IsShowSubjectMark,
	CASE WHEN ISNULL(EM.IsDisplayParentName,0)=0 THEN 'No' ELSE 'Yes' ENd AS IsDisplayParentName,
	ISNULL(EM.SubjectGroupPerPage,0)AS SubjectGroupPerPage,
	CASE WHEN ISNULL(EM.IsDisplayTeacherSign,0)=0 THEN 'No' ELSe 'Yes' END AS IsDisplayTeacherSign,
	CASE WHEN ISNULL(EM.IsDisplayPrincipalSign,0)=0 THEN 'No' ELSe 'Yes' ENd  AS IsDisplayPrincipalSign,
	CASE WHEN ISNULL(EM.PercentileScopeId,0)=0 THEN 'No' ELSE 'Yes' END AS PercentileScopeId ,
 	CASE WHEN 	ISNULL(EM.CoScholasticScopeId,0)=1 THEn 'Single' ELSE 'Combine' END AS CoScholasticScope,
 	CASE WHEN ISNULL(EM.IsExcludeAbsentTotal,0) = 0 THEN 'No' ELSE 'Yes' END AS IsExcludeAbsentTotal,
	ISNULL(EM.IsDisplayTotalMark,0) AS IsDisplayTotalMarks,
	CASE WHEN ISNULL(IsAllExamPassRequired,0)=0 THEN 'No' ELSE 'Yes' END AS IsAllExamPassRequired,
	CASE WHEN ISNULL(IsGenerateRankNo,0) = 0 THEN 'No' ELSE 'Yes' END AS IsGenerateRankNo,
	ISNULL(EM.ResultSheetAdditionalTitle,'')  AS ResultSheetAdditionalTitle,
	ISNULL(DM1.Title,'Default (No)') AS DisplayAttendence,
	ISNULL(DM2.Title,'Default (No)') AS ReportHeader
  FROM 
			--		sAssessment.tExamCombine EC
			--INNER JOIN 
			sAssessment.tExamMaster EM  
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId			
			INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId 
			INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id
			LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			Left Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId
			left Join sCommon.tDataMaster DM1 ON DM1.DataTypeId=14 And DM1.Id=EM.DisplayAttendanceId
			Left Join sCommon.tDataMaster DM2 ON DM2.DataTypeId=15 And DM1.Id=EM.ReportHeaderId
			
												
						
WHERE       
           
            (EM.Id=@rId OR @rId = 0)			 
            AND (ISNULL(EM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamIds,','))OR @rExamIds='')
			 
          	
			order by  DisplayOrder
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAssessment].[pRptExamResultSubCombine]
	 
	 -- @rAcademicId bigint=0,
	 @rExamSubGroupId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rOrgId int =0,
	 @rBatchId int ,
	 @rDepartmentid int=0,
	 @rStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			 
			 CONVERT(nvarchar(20),EM.Id) AS ExamIdText,
			 CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
			 CONVERT(nvarchar(20),DM.Id) AS DivisionIdText,
			 CONVERT(nvarchar(20),@rBatchId) AS BatchIdText,
			 CONVERT(nvarchar(20),@rStatusId) AS StatusIdText,
	 
			 
			CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision,
			DM.Title AS Division,
			CM.Title AS Class,
			E.FirstName + ' ' + E.LastName AS ClassTeacherName,
			BM.Title AS Batch,
			DM.Id AS DivisionId,
			CM.Id AS ClassId
			FROM 
			 
		 
			sAssessment.tExamMaster EM
			--INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId
		 --   INNER JOIN sStudent.tAcademic A	ON A.Id=R.Academic
			 INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=EM.ExamSubGroupId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			--INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
			 LEFT JOIN sHrm.tEmployeeMaster E ON E.Id =DM.InchargeEmployeeId
			--INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId = OM.Id
			 INNER JOIN sSetup.tBatchMaster BM ON BM.Id=EM.BatchId
	WHERE 
	 
	     (CM.Id=@rClassId OR @rClassId=0) 
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)
		AND (EM.ExamSubGroupId = @rExamSubGroupId OR @rExamSubGroupId =0)
		AND  ISNULL(E.IsOtherUser,0) = 0
		--AND OM.Id=@rOrgId
		AND BM.Id = @rBatchId
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptExamSetting]
	 @rId int=0,
	 @rExamIds nvarchar(200)='',
	 @rBuilder1 nvarchar(200)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	

					 
	SELECT 
	 ESGM.Title AS Name,
	 
	 @rBuilder1 AS Builder1,
 
-- Convert(nvarchar(10),EM.Id) AS ExamIdText,
	CASE WHEN ISNULL(IsRankNo,0) = 0 THEN 'No' ELSE 'Yes' END AS IsIsRankNo,
	 
	CASE WHEN ISNULL(IsGrade,0) = 0 THEN 'No' ELSE 'Yes' END AS IsGrade,
	 
	CASE WHEN ISNULL(IsPercentile,0) = 0 THEN 'No' ELSE 'Yes' END AS IsPercentile,
	 
	CASE WHEN ISNULL(IsPercentage,0) = 0 THEN 'No' ELSE 'Yes' END AS IsPercentage,
	 
	CASE WHEN ISNULL(IsSubjectPercentile,0) = 0 THEN 'No' ELSE 'Yes' END AS IsSubjectPercentile,
	 
	CASE WHEN ISNULL(IsProcessResult,0) = 0 THEN 'No' ELSE 'Yes' END AS IsProcessResult,
	--CASE WHEN IsNull(IsMarksInDecimal,0) = 0 THEN 'No' ELSE 'Yes' END AS IsMarksInDecimal,
	CASE WHEN ISNULL(ISNegativeMarks,0)=0 THEN 'No' ELSE 'Yes' END AS ISNegativeMarks,
	 
	--CASE WHEN ISNULL(IsIncludeInTotal,0)=0 THEN 'No' ELSE 'Yes' END AS IsIncludeInTotal,
	 
	--CASE WHEN ISNULL(IsDisplayInMarksheet,0)=0 THEN 'No' ELSE 'Yes' END AS IsDisplayInMarksheet,
	 
--	CASE WHEN ISNULL(IsShowSubjectGrade,0)=0 THEN 'No' ELSE 'Yes' END AS IsShowSubjectGrade,
	 
	CASE WHEN ISNULL(IsOnPrePrinted,0) = 0 THEN 'No' ELSE 'Yes' END AS IsOnPrePrinted,
	CASE WHEN ISNULL(IsDisplayBirthDate,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayBirthDate,
	CASE WHEN ISNULL(IsDisplayPhoto,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayPhoto,
	CASE WHEN ISNULL(IsDisplaySchoolName,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplaySchoolName,
	CASE WHEN ISNULL(IsLockForEdit,0) = 0 THEN 'No' ELSE 'Yes' END AS IsLockForEdit,
	CASE WHEN ISNULL(IsIncludeCoScholastic,0) = 0 THEN 'No' ELSE 'Yes' END AS IsIncludeCoScholastic,
	
	CASE WHEN ISNULL(IsDisplayAttendance,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayAttendance,
	CASE WHEN ISNULL(IsDisplayHeightWeight,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayHeightWeight,
	CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayResultStatus ,
	 
	 CASE WHEn ISNULL(EM.IsDisplayParentName,0)=0 THEN 'No' ELSE 'Yes' ENd AS IsDisplayParentName,
	CASE WHEN ISNULL(EM.IsDisplayTeacherSign,0)=0 THEN 'No' ELSE 'Yes' ENd AS IsDisplayTeacherSign,
	CASE WHEn ISNULL(EM.IsDisplayPrincipalSign,0)=0 THEN 'No' ELSE 'Yes' END AS IsDisplayPrincipalSign,
	CASE WHEn ISNULL(EM.IsExcludeAbsentTotal,0)=0 THEN 'No' ELSE 'Yes' END AS IsExcludeAbsentTotal,
	CASE WHEn ISNULL(EM.IsAllExamPassRequired,0)=0 THEN 'No' ELSE 'Yes' END AS IsAllExamPassRequired
--	CASE WHEN ISNULL(IsShowSubjectMark,0)=0 THEN 'No' ELSE 'Yes' END AS IsShowSubjectMark
	
	 
	
  FROM 
		 --		sAssessment.tExamCombine EC
		 --INNER JOIN 
			sAssessment.tExamMaster EM  
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId			
			--INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId 
		 
			 --INNER  JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			 			
			 			 
WHERE       
           
            (EM.Id=@rId OR @rId = 0)			 
            AND (ISNULL(EM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamIds,','))OR @rExamIds='')
		 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptFASAAnalysisGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int,
	 @rStatusId int =0,
	 @rClassStatusId int=0
	-- @rClass nvarchar(max)=''
	 --@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
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 
--SELECT 
--	@rBuilder1 AS Builder1,
--	'' AS SubjectName,
--	0 as DivisionId,
--	'' as DivisionName,
--	0 AS ClassSubjectId,
--'' AS FA0SA0,
--'' AS FA0SA7,
--'' AS FA0SA13,
--'' AS FA0SA19,
--'' AS FA0SA25,
--'' AS FA5SA0,
--'' AS FA5SA7,
--'' AS FA5SA13,
--'' AS FA5SA19,
--'' AS FA5SA25,
--'' AS FA9SA0,
--'' AS FA9SA7,
--'' AS FA9SA13,
--'' AS FA9SA19,
--'' AS FA9SA25,
--'' AS FA13SA0,
--'' AS FA13SA7,
--'' AS FA13SA13,
--'' AS FA13SA19,
--'' AS FA13SA25,
--'' AS FA17SA0,
--'' AS FA17SA7,
--'' AS FA17SA13,
--'' AS FA17SA19,
--'' AS FA17SA25

DECLARE   @lExamId Bigint
DECLARE   @IsIncludeSubExam bit

SELECT @lExamId = Id FRom sAssessment.tExamMaster where ExamSubGroupId = @rExamSubGroupId AND ClassId =@rClassId
SELECT  @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @lExamId
 
 
 
CREATE TABLE #TempAllExam
	(
		
		AcademicId bigint,
		RollNo int,
		Obtain1 decimal(8,2),
		Obtain2 decimal(8,2),
		Obtain3 decimal(8,2),
		Obtain4 decimal(8,2),
		Obtain5 decimal(8,2),
		Obtain6 decimal(8,2),
		Obtain7 decimal(8,2),
		Obtain8 decimal(8,2),
		Obtain9 decimal(8,2),
		Obtain10 decimal(8,2),
		ResultId bigint,
		ClassSubjectID int ,
		ExamId int,
		SubjectName nvarchar(50),
		
		DivisionId int,
		DivisionName nvarchar(200)
	
	)
	
	
	
--	CREATE TABLE #TempExam
--(
--	Id int IDENTITY,
--	ExamSubGroupId int
--	)
--INSERT INTO #TempExam
--(
--	ExamSubGroupId
--)
--select ExamSubGroupId from sAssessment.tExamMaster 

-- DECLARE @lCount2 int,@lExamSubGroupId int
-- --select @lCount2= MAX(Id) from #TempExam
  
-- while (@lCount2>0)
-- begin
 
--	select @lExamSubGroupId=ExamSubGroupId from #TempExam

		INSERT into #TempAllExam
			(
				AcademicId,
				RollNo,
				--Obtain,
				ResultId,
				ClassSubjectID,
				ExamId,
				SubjectName,
				DivisionId,
				DivisionName
				
			)
			
			
		SELECT
			A.Id,
			A.RollNo,
			--RD.Obtain,
			R.Id AS ResultId,
			ED.ClassSubjectId,
			Ed.ExamId,
			Sm.Title AS SubjectName,
			Dm.Id AS DivisionId,
			DM.DisplayTitle AS DivisionName
			
			
		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 sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			inner join sStudent.tStudentMaster STM ON STM.Id = A.StudentId 
		WHERE
			 R.ExamId = @lExamId 
				AND ((CS.Id=@rSubjectId) OR (@rSubjectId=0))
				AND ((A.ClassId =  @rClassId) OR (@rClassId=0))	
				 AND ((DM.Id =  @rDivisionId) OR (@rDivisionId=0))	 
				AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
				and((STM.StatusId=@rStatusId) or (@rStatusId=0))
				AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))  
				
	
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine   WHERE ExamId  = @lExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	 
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @lExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	 
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
	select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount	
	
		set @query ='update T SET
					  --MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain
					  										
				 From
					sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						execute(@query)
			set @lCount = @lCount -1
		end
		
		--set @lcount2=@lCount2-1
		-- END
 
		
	 
	SELECT  
		
		@rBuilder1 AS Builder1,
		DM.Title AS DivisionName,
		DM.Id AS DivisionId,
		 CS.ID AS ClassSubjectId,
		SM.Title AS SubjectName,
		--(Select  COALESCE( @rollno + ',','') + CAST(RollNo AS Varchar(200)) from  #TempAllExam   where (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=0 and Obtain3<=6) )
	 
		--Select @rollno AS FA0SA0,
		 
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId   and T.DivisionId=Dm.Id
		 		AND ED.ExamId=T.ExamId AND (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) 
		 		AND (Obtain3>=0 and Obtain3<=6) FOR XML Path('')),1,1,'')) 
		 ) AS FA0SA0,
		 --(select stuff((select CAST(RollNo AS Varchar(200 ))+ ',' from  #TempAllExam  
			--where (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=7 and Obtain3<=12) FOR XML Path('')),1,1,'')) AS FA0SA7,
	    (SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=7 and Obtain3<=12) FOR XML Path('')),1,1,'')) 
		 )AS FA0SA7,
	    
	    (SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=13 and Obtain3<=18) FOR XML Path('')),1,1,'')) 
		 ) AS FA0SA13,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=19 and Obtain3<=24) FOR XML Path('')),1,1,'')) 
		 ) AS FA0SA19,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=0 AND Obtain1+Obtain2<=4) AND (Obtain3>=25 and Obtain3<=30) FOR XML Path('')),1,1,'')) 
		 ) AS FA0SA25,
		
		 (SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=5 AND Obtain1+Obtain2<=8) AND (Obtain3>=0 and Obtain3<=6) FOR XML Path('')),1,1,'')) 
		 ) AS FA5SA0,
		 	
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=5 AND Obtain1+Obtain2<=8) AND (Obtain3>=7 and Obtain3<=12) FOR XML Path('')),1,1,'')) 
		 )AS FA5SA7,
			
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=5 AND Obtain1+Obtain2<=8) AND (Obtain3>=13 and Obtain3<=18) FOR XML Path('')),1,1,'')) 
		 ) AS FA5SA13,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId   AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id  AND (Obtain1+Obtain2>=5 AND Obtain1+Obtain2<=8) AND (Obtain3>=19 and Obtain3<=24) FOR XML Path('')),1,1,'')) 
		 ) AS FA5SA19,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId   AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=5 AND Obtain1+Obtain2<=8) AND (Obtain3>=25 and Obtain3<=30) FOR XML Path('')),1,1,'')) 
		 ) AS FA5SA25,
		
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=9 AND Obtain1+Obtain2<=12) AND (Obtain3>=0 and Obtain3<=6) FOR XML Path('')),1,1,'')) 
		 ) AS FA9SA0,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND  T.ExamId=@lExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=9 AND Obtain1+Obtain2<=12) AND (Obtain3>=7 and Obtain3<=12) FOR XML Path('')),1,1,'')) 
		 ) AS FA9SA7,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where  ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=9 AND Obtain1+Obtain2<=12) AND (Obtain3>=13 and Obtain3<=18) FOR XML Path('')),1,1,'')) 
		 ) AS FA9SA13,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=9 AND Obtain1+Obtain2<=12) AND (Obtain3>=19 and Obtain3<=24) FOR XML Path('')),1,1,'')) 
		 ) AS FA9SA19,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id  AND (Obtain1+Obtain2>=9 AND Obtain1+Obtain2<=12) AND (Obtain3>=25 and Obtain3<=30) FOR XML Path('')),1,1,'')) 
		 ) AS FA9SA25,
		
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=13 AND Obtain1+Obtain2<=16) AND (Obtain3>=0 and Obtain3<=6)
		 		 FOR XML Path('')),1,1,'')) 
		 ) AS FA13SA0,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=13 AND Obtain1+Obtain2<=16) AND (Obtain3>=7 and Obtain3<=12) 
		 		FOR XML Path('')),1,1,'')) 
		 ) AS FA13SA7,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where  ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=13 AND Obtain1+Obtain2<=16) AND (Obtain3>=13 and Obtain3<=18)
		 		 FOR XML Path('')),1,1,'')) 
		 ) AS FA13SA13,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=13 AND Obtain1+Obtain2<=16) AND (Obtain3>=19 and Obtain3<=24)
		 		 FOR XML Path('')),1,1,'')) 
		 ) AS FA13SA19,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=13 AND Obtain1+Obtain2<=16) AND (Obtain3>=25 and Obtain3<=30) 
		 		FOR XML Path('')),1,1,'')) 
		 ) AS FA13SA25,
		
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=17 AND Obtain1+Obtain2<=20) AND (Obtain3>=0 and Obtain3<=6)
		 		 FOR XML Path('')),1,1,'')) 
		 ) AS FA17SA0, 
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where  ED.ClassSubjectId=T.ClassSubjectId AND ED.ExamId=T.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=17 AND Obtain1+Obtain2<=20) AND (Obtain3>=7 and Obtain3<=12)
		 		 FOR XML Path('')),1,1,'')) 
		 )AS FA17SA7,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where ED.ClassSubjectId=T.ClassSubjectId  AND ED.ExamId=T.ExamId  and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=17 AND Obtain1+Obtain2<=20) AND (Obtain3>=13 and Obtain3<=18)
		 		 FOR XML Path('')),1,1,'')) 
		 )AS FA17SA13,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where  ED.ClassSubjectId=T.ClassSubjectId and T.ExamId=Ed.ExamId and T.DivisionId=Dm.Id AND (Obtain1+Obtain2>=17 AND Obtain1+Obtain2<=20) AND 
		 			(Obtain3>=19 and Obtain3<=24) FOR XML Path('')),1,1,'')) 
		 ) AS FA17SA19,
		(SELECT  
			(select stuff((select ',' +CAST(RollNo AS Varchar(200)) from  #TempAllExam  T 
		 		where 
		 		ED.ClassSubjectId=T.ClassSubjectId AND  T.ExamId=Ed.ExamId and T.DivisionId=Dm.Id
		 	    AND (Obtain1+Obtain2>=17 
		 		AND Obtain1+Obtain2<=20) AND (Obtain3>=25 and Obtain3<=30) FOR XML Path('')),1,1,'')) 
		 ) AS FA17SA25
		
		
			 
	
 FROM  sAssessment.tExamMaster EM INNER JOIN sAssessment.tExamDetail ED 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	
 INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
 WHERE EM.Id = @lExamId
 AND (CS.Id = @rSubjectId OR @rSubjectId=0)
 AND (DM.Id=@rDivisionId OR @rDivisionId=0) 
 
	 
		
	-- drop table #tempcombineExam
	-- Drop table #TempAllExam


 end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptGenderWiseOverallGradeAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(max)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rDepartmentId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--select
	
	--	'' AS Grade1,
	--	'' AS Grade2,
	--	'' AS Grade3,
	--	'' AS Grade4,
	--	'' AS Grade5,
	--	'' AS Grade6,
	--	'' AS Grade7,
	--	'' AS Grade8,
	--	'' AS Grade9,
	--	'' AS Grade10,
	--	0 AS GradeCount1,
	--	0 AS GradeCount2,
	--	0 AS GradeCount3,
	--	0 AS GradeCount4,
	--	0 AS GradeCount5,
	--	0 AS GradeCount6,
	--	0 AS GradeCount7,
	--	0 AS GradeCount8,
	--	0 AS GradeCount9,
	--	0 AS GradeCount10,
	--	0 AS MaleGradeCount1,
	--	0 AS MaleGradeCount2,
	--	0 AS MaleGradeCount3,
	--	0 AS MaleGradeCount4,
	--	0 AS MaleGradeCount5,
	--	0 AS MaleGradeCount6,
	--	0 AS MaleGradeCount7,
	--	0 AS MaleGradeCount8,
	--	0 AS MaleGradeCount9,
	--	0 AS MaleGradeCount10,
	--	0 AS FemaleGradeCount1,
	--	0 AS FemaleGradeCount2,
	--	0 AS FemaleGradeCount3,
	--	0 AS FemaleGradeCount4,
	--	0 AS FemaleGradeCount5,
	--	0 AS FemaleGradeCount6,
	--	0 AS FemaleGradeCount7,
	--	0 AS FemaleGradeCount8,
	--	0 AS FemaleGradeCount9,
	--	0 AS FemaleGradeCount10,
	--	0 AS ClassId,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	0 AS DivisionId,
	--	0 AS NoOfStudent,
	--  0 AS NoOfMaleStudent,
	--  0 AS NoOfFemaleStudent,
	--	0.00 AS HighestPerMark,
	--  0.00 AS MaleHighestPerMark,
	--  0.00 AS FemaleHighestPerMark,
	--	0.00 AS AveragePerMark,
	--  0.00 AS MaleAveragePerMark,
	--  0.00 AS FemaleAveragePerMark,
	--	0.00 AS LowestPerMark,
	--  0.00 AS MaleLowestPerMark,
	--  0.00 AS FemaleLowestPerMark,
	--'' AS Builder1
		
		
 
	 DECLARE @GradeSetId int
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
		
	 Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
		  
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
	 
	 	 Set @G1=(Select GradeCode from #Temp where Id=1) 
	 	 Set @G2=(Select GradeCode from #Temp where Id=2) 
	 	 Set @G3=(Select GradeCode from #Temp where Id=3) 
	 	 Set @G4=(Select GradeCode from #Temp where Id=4) 
	     Set @G5=(Select GradeCode from #Temp where Id=5) 
         Set @G6=(Select GradeCode from #Temp where Id=6) 
	     Set @G7=(Select GradeCode from #Temp where Id=7) 
	 	 Set @G8=(Select GradeCode from #Temp where Id=8) 
	 	 Set @G9=(Select GradeCode from #Temp where Id=9) 
		 Set @G10=(Select GradeCode from #Temp where Id=10)  
	   
	 select 
		@rBuilder1 AS Builder1,
		BC.ClassId As ClassId,
		Dm.id As DivisionId,
		BC.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
	  (select COUNT(R.Academicid) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) ) AS NoOfStudent,
	  (select COUNT(R.Academicid) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND A.GenderId = 1 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) ) AS NoOfMaleStudent,
	  (select COUNT(R.Academicid) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND A.GenderId = 2 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) ) AS NoOfFemaleStudent,
	 

	  (select MAX(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS HighestPerMark,
	  (select MAX(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS MaleHighestPerMark,
	  (select MAX(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS FemaleHighestPerMark,

	  (select AVG(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS AveragePerMark,
	  (select AVG(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS MaleAveragePerMark,
	  (select AVG(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS FemaleAveragePerMark,
	  
	  (select MIN(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS LowestPerMark ,
	  (select MIN(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS MaleLowestPerMark ,
	  (select MIN(R.Percentage) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS FemaleLowestPerMark ,
	  
	  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G1 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS GradeCount1,
  
	  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G2 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS GradeCount2,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G3 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G4 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G5 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G6 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G7 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G8 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G9 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS GradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND  ResultGrade = @G10 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS GradeCount10,
	  
	  --Male
	  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND  ResultGrade = @G1 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS MaleGradeCount1,
  
	  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND  ResultGrade = @G2 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS MaleGradeCount2,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND  ResultGrade = @G3 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS MaleGradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND  ResultGrade = @G4 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS MaleGradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND  ResultGrade = @G5 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS MaleGradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND  ResultGrade = @G6 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS MaleGradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND  ResultGrade = @G7 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS MaleGradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND  ResultGrade = @G8 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS MaleGradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND  ResultGrade = @G9 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS MaleGradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 1 AND EM.BatchId = @rBatchId AND  ResultGrade = @G10 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS MaleGradeCount10,

	  --Female
	  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND  ResultGrade = @G1 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS FemaleGradeCount1,
  
	  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND  ResultGrade = @G2 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS FemaleGradeCount2,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND  ResultGrade = @G3 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS FemaleGradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND  ResultGrade = @G4 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS FemaleGradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND  ResultGrade = @G5 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS FemaleGradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND  ResultGrade = @G6 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS FemaleGradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND  ResultGrade = @G7 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS FemaleGradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND  ResultGrade = @G8 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS FemaleGradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND  ResultGrade = @G9 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) )AS FemaleGradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResult R INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND A.GenderId = 2 AND EM.BatchId = @rBatchId AND  ResultGrade = @G10 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)))AS FemaleGradeCount10,
   
	  ISNULL(@G1,'*') AS Grade1,
	  ISNULL(@G2,'*') AS Grade2,
	  ISNULL(@G3,'*') AS Grade3,
	  ISNULL(@G4,'*') AS Grade4,
	  ISNULL(@G5,'*') As Grade5,
	  ISNULL(@G6,'*') As Grade6,
	  ISNULL(@G7,'*') AS Grade7,
	  ISNULL(@G8,'*') AS Grade8,
	  ISNULL(@G9,'*') AS Grade9,
	 ISNULL(@G10,'*')  AS Grade10
	  

	 from
	 ssetup.tDivisionMaster DM
	 --INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	 INNER JOIN sSetup.vBatchClass BC ON BC.ClassId = DM.ClassId
	
	--INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = BC.ClassId 
	  INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=@rExamSubGroupId
		WHERE 
		    (DM.ID=@rDivisionId OR @rDivisionId=0)
			AND (Dm.ClassId=@rClassId OR @rClassId=0)
			AND BC.BatchId=@rBatchId
			--AND ESGM.Id =@rExamSubGroupId
			AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND ((BC.DepartmentId = @rDepartmentId) OR (@rDepartmentId =0))
			AND BC.Isobsolete = 0
	
  
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--created by megha for 0027269
CREATE OR ALTER PROCEDURE [sAssessment].[pRptGradeAnalysisMainCategoryWise]
	 
	 --@rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int =0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rClass nvarchar(MAX)='',
	 @rStatusId int =0,
	 @rClassStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
	
	select 
	@rBuilder1 AS Builder1,
 
	
		 count(R.id),
		GM.Title AS Gender,
		R.ResultGrade,
		--ISNULL(CCM.Title,'') AS CastCatagory,
		A.ClassId,
		A.DivisionId,
		CM.Title AS ClassName,
		DM.Title AS DivisionName,
		ISNULL(MCM.Title,'') As MainCastCategory
	 
		 
 from sAssessment.tResult  R
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		Inner join sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId 
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId 	
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
		LEFT  JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	    LEFT JOIN sCommon.tMainCastCategoryMaster MCM ON MCM.Id = CCM.MainCastCategoryId

		
	where (A.ClassId=@rClassId OR @rClassId=0)
		AND (A.DivisionID=@rDivisionId Or @rDivisionId=0)
		and A.BatchId=@rBatchId
		and EM.ExamSubGroupId=@rExamSubGroupId
		AND    (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		and ((sm.StatusId=@rStatusId) or (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		 Group by R.ResultGrade, GM.Title,MCM.Title,A.ClassId,A.DivisionId,CM.Title,DM.Title 
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptGraphAllClassOverallGradeAnalysis]
@rClassId int=0,
@rDivisionId int=0,
@rExamSubGroupId int=0,
@rBuilder1 nvarchar(MAX)='',
@rBatchId int,
@rOrgId int=0,
@rGroupByid int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
 create table #Temphead
 (Id Int Identity (1,1),
  HEADID int,
  total_count int
  )
  INSERT INTO #Temphead
	select 
	 CASE WHEN @rGroupByid=1 THEN A.DivisionId 
		WHEN @rGroupByid=2 THEN A.ClassId
		WHEN @rGroupByid =3 THEN Dept.Id
		WHEN @rGroupByid =4 THEN A.OrgId 
		ELSE 0  END AS HeadId,
		COUNT(R.Academicid) AS total_count
		
	FROM sAssessment.tResult R
      INNER JOIN sStudent.tAcademic A  ON R.AcademicId = A.Id  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id
      INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
      INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
      WHERE (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND (A.ClassId=@rClassId OR @rClassId=0)
		AND EM.BatchId=@rBatchId
		AND EM.ExamSubGroupId =@rExamSubGroupId
		GROUP BY CASE WHEN @rGroupByid=1 THEN A.DivisionId 
		WHEN @rGroupByid=2 THEN A.ClassId
		WHEN @rGroupByid =3 THEN Dept.Id
		WHEN @rGroupByid =4 THEN A.OrgId 
		ELSE 0 END 
      
      SELECT  A.Builder1,A.ResultGrade,T.HeadId,A.HeadName,A.NoofStudent,T.total_count,A.OrderIndex FROM(
		SELECT 
		COUNT(R.Academicid) AS NoofStudent,
		@rBuilder1 AS Builder1,
		ISNUll(R.ResultGrade,'') AS ResultGrade ,
	--Case when ResultGrade= '' Then ' * ' ELSE ISNULL(R.ResultGrade,' * ')  END AS ResultGrade,
		 CASE WHEN @rGroupByid=1 THEN A.DivisionId 
		WHEN @rGroupByid=2 THEN A.ClassId
		WHEN @rGroupByid =3 THEN Dept.Id
		WHEN @rGroupByid =4 THEN A.OrgId ELSE 0  END AS HeadId,
		
		CASE WHEN @rGroupByid=1 THEN ' Division : ' +CM.Title+ ' / '+Dm.DisplayTitle 
		WHEN @rGroupByid=2 THEN ' Class : ' + CM.Title
		WHEN @rGroupByid=3 THEN 'Department: ' + Dept.Title
		WHEN @rGroupByid=4 THEN  'Organization : '+OM.Title	END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN Dept.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex
		FROM sAssessment.tResult R
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
		INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id	
		WHERE (DM.ID=@rDivisionId OR @rDivisionId=0)
		AND (DM.ClassId=@rClassId OR @rClassId=0)
		AND EM.BatchId=@rBatchId
		AND EM.ExamSubGroupId =@rExamSubGroupId
		Group BY ResultGrade,
		 CASE WHEN @rGroupByid=1 THEN A.DivisionId 
		WHEN @rGroupByid=2 THEN A.ClassId
		WHEN @rGroupByid =3 THEN Dept.Id
		WHEN @rGroupByid =4 THEN A.OrgId ELSE 0  END,
		CASE WHEN @rGroupByid=1 THEN  ' Division : ' +CM.Title+ ' / '+Dm.DisplayTitle 
		WHEN @rGroupByid=2 THEN ' Class : ' + CM.Title
		WHEN @rGroupByid=3 THEN 'Department: ' + Dept.Title
		WHEN @rGroupByid=4 THEN  'Organization : '+OM.Title	END,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN Dept.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END
		)A	
		INNER JOIN 	#Temphead T ON T.HeadId=A.HEADID
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptGraphicalPassFailAnalysisSubjectWise]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 --@rClass nvarchar(MAX)='',
	 @rGroupByid int=0,
 	 @rSubject nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		 
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Sm.OrderIndex As SubjectOrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		CM.OrderIndex AS ClassOrderIndex,
		case when @rGroupByid=1 THEN Dm.Id
		when @rGroupByid=2 THEN CM.Classid
		when @rGroupByid=3 THEN CM.DepartmentId
	    when @rGroupByid=4 THEN OM.Id
		ELSE 0  END  AS HeadId,
		case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle   
		when @rGroupByid=2 THEN ' Class : ' + CM.ClassName 
		when @rGroupByid=3 THEN 'Department: ' + DP.Title 
		WHen @rGroupByid=4 THen  'Organization : '+Om.Title END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
		WHEN @rGroupByid=2  THEN CM.OrderIndex
		WHEN @rGroupByid=3  THEN DP.Id
		WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
		

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	  INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
	  AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum) AS FailStudent 
	  
	  
	-- from
	-- ssetup.tDivisionMaster DM
	-- INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	--INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	--INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	--INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	-- INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
 --   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId

	--	WHERE 
	--		((DM.ID=@rDivisionId) or (@rDivisionId=0))
	--		AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
	--		AND CM.BatchId=@rBatchId
	--		AND EM.ExamSubGroupId = @rExamSubGroupId
	--		AND EM.BatchId = @rBatchId
	--		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
	
	from		
		sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	WHERE 		
		
		EM.BatchId = @rBatchId 
		AND  ((@rClassId > 0 AND cs.ClassId=@rClassId)
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
		AND	CM.BatchId = @rBatchId
		AND EM.ExamSubGroupId = @rExamSubGroupId
		AND EM.BatchId = @rBatchId
		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject=''))
	
  UNION ALL
  
  
  	 select 
		@rBuilder1 AS Builder1,
		DM.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
	0 AS ClassSubjectId,
		0 AS SubjectId,
		'Over All' AS SubjectName,
		0 As SubjectOrderIndex,
		0 AS DivisionOrderIndex,
		0 AS ClassOrderIndex,
		case when @rGroupByid=1 THEN Dm.Id
		when @rGroupByid=2 THEN CM.Classid
		when @rGroupByid=3 THEN CM.DepartmentId
	    when @rGroupByid=4 THEN OM.Id
		ELSE 0    END  AS HeadId,
		case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle  
		when @rGroupByid=2 THEN ' Class : ' + CM.ClassName  
		when @rGroupByid=3 THEN 'Department: ' + DP.Title 
		WHen @rGroupByid=4 THEN  'Organization : '+OM.Title
		END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN DP.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
	 

 (select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND R.ResultStatus='PASS') AS PassStudent,
	  
	  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent 
	  
    
	 --from
	 --ssetup.tDivisionMaster DM
	 --INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	 --INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	 --INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
  --  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
		--WHERE 
		--	((DM.ID=@rDivisionId) or (@rDivisionId=0))
		--	AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
		--	AND CM.BatchId=@rBatchId
		--	AND EM.ExamSubGroupId = @rExamSubGroupId
		--	AND EM.BatchId = @rBatchId
		
	FROM		
		sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	WHERE 		
		
		EM.BatchId = @rBatchId 
		AND  ((@rClassId > 0 AND cs.ClassId=@rClassId)
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
		AND	CM.BatchId = @rBatchId
		AND EM.ExamSubGroupId = @rExamSubGroupId
		AND EM.BatchId = @rBatchId
		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject=''))
			
			--AND (ISNULL(ClassSubjectId,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptGraphicalStudentGradeAnalysisSubjectWise]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rGroupByid int=0,
	 @rOrgId  int=0,
	 @rSubject nvarchar(MAX)='',
	 @rStatusId int=0,			-- #Start MantisId : 0031568
	 @rClassStatusId int=0		-- #End MantisId : 0031568
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
CREATE TABLE #TempCradeCount
(Id Int Identity (1,1),
 HEADID int,
 Subjectid int, 
 TotalCount int
)
INSERT INTO  #TempCradeCount
SELECT 
CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id
				ELSE 0 END AS HeadId,
				SM.Id AS  Subjectid,
					COUNT(R.Id) AS total_count
					FROm sAssessment.tResultDetail  RD
		  INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		--LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		--GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId		-- MantisId : 0031568
		where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))						-- #Start MantisId : 0031568
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))		-- #End MantisId : 0031568
		GROUP BY CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id
				ELSE 0 END,
				SM.Id
				
				
SELECT ISNULL(A.GradeCount,0) AS GradeCount, A.Builder1,A.SubjectGrade,A.SubjectName,A.HeadId,A.HeadName,T.Subjectid,ISNULL(T.TotalCount,0) AS TotalCount,A.OrderIndex FROM(
				
SElect
		COUNT(RD.Id) AS GradeCount,
		@rBuilder1 AS Builder1,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		SM.Id AS SubjectId,
		SM.OrderIndex AS SubjectOrderIndex,
		GD.GradeSetId AS GradeSetId,
		CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id
				ELSE 0
				 END AS HeadId,CS.IsOptional ,
				
			case when @rGroupByid=1 THEN ' Division : ' +CM.Title+ ' / '+Dm.DisplayTitle  
		when @rGroupByid=2 THEN ' Class : ' + CM.Title  
		when @rGroupByid=3 THEN 'Department: ' + Dept.Title 
		WHen @rGroupByid=4 THEN  'Organization : '+OM.Title
		
		END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN Dept.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex
		from sAssessment.tResultDetail  RD
		  INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId		-- MantisId : 0031568
	where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))						-- #Start MantisId : 0031568
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))		-- #End MantisId : 0031568
		
		Group by RD.SubjectGrade,SM.Title
		 ,GD.GradeSetId,
		 	CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id ELSE 0 END ,	SM.Id,
		case when @rGroupByid=1 THEN ' Division : ' +CM.Title+ ' / '+Dm.DisplayTitle 
		when @rGroupByid=2 THEN ' Class : ' + CM.Title    
		when @rGroupByid=3 THEN 'Department: ' + Dept.Title 
		WHen @rGroupByid=4 THEN  'Organization : '+OM.Title END,
		SM.OrderIndex,CS.IsOptional ,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN Dept.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END 
		) A 
		INNER JOIN #TempCradeCount T ON T.HEADID=A.HeadId 
		AND T.Subjectid=A.Subjectid
		AND (ISNULL(T.Subjectid,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
		
			
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptGraphicalTeacherEvaluationAnalysis2Get]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int,
	 @rOrgId int=0, 
	 @rGroupByid int=0,
	 @rEmployeeId bigint=0
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	ESGM.Title AS ExamName,
	TSD.EmployeeId,
	EmpM.Code AS EmployeeCode,
	SM.Id AS SubjectId,
	SM.Code AS SubjectCode,
	SM.Title AS SubjectName,
	SM.OrderIndex AS SubjectOrderIndex,
	CS.Id AS ClassSubjectId,
	DM.Id AS DivisionId,
	DM.DisplayTitle AS DivisionName,
	CM.Id AS ClassId,
	CM.DisplayTitle AS ClassName,
	A.Id As AcademicId,
	EM.Id AS ExamId,
	RD.IsPresent,
	RD.Obtain AS SubjectObtain,
	ED.Maximum AS SubjectMaximum,
	CAST(ROUND((ISNULL(RD.Obtain, 0) * 100.0) / ED.Maximum, 2) AS DECIMAL(5,2)) AS SubjectPercentage,
	CASE WHEN @rGroupByid=1 THEN DM.Id
		WHEN @rGroupByid=2 THEN CM.Id
		WHEN @rGroupByid=3 THEN CM.DepartmentId
	    WHEN @rGroupByid=4 THEN OM.Id
		ELSE 0  END  AS HeadId,
	CASE WHEN @rGroupByid=1 THEN 'Division : ' +CM.DisplayTitle+ ' / '+DM.DisplayTitle   
		WHEN @rGroupByid=2 THEN 'Class : ' + CM.DisplayTitle 
		WHEN @rGroupByid=3 THEN 'Department : ' + DP.Title 
		WHEN @rGroupByid=4 THEN  'Organization : '+OM.Title END  AS HeadName,
	CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
		WHEN @rGroupByid=2 THEN CM.OrderIndex
		WHEN @rGroupByid=3 THEN DP.Id
		WHEN @rGroupByid=4 THEN OM.OrderIndex  END AS OrderIndex,
		ED.DisplayOrder 

	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			
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId						
		INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id AND EmpM.StatusId = 7			
			
	WHERE ESGM.Id = @rExamSubGroupId
		AND ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND TSD.EmployeeId=@rEmployeeId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pRptGraphicalTeacherEvaluationAnalysis3Get]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int = 0,
	 @rOrgId int=0, 
	 @rGroupByid int=0,
	 @rEmployeeId bigint=0,
	 @rExamSubGroupIds nvarchar(max)=''--Added by dhananjay : 42465
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	ESGM.Title AS ExamName,
	ESGM.Id AS ExamSubGroupId,
	TSD.EmployeeId,
	EmpM.Code AS EmployeeCode,
	SM.Id AS SubjectId,
	SM.Code AS SubjectCode,
	SM.Title AS SubjectName,
	SM.OrderIndex AS SubjectOrderIndex,
	CS.Id AS ClassSubjectId,
	DM.Id AS DivisionId,
	DM.DisplayTitle AS DivisionName,
	CM.Id AS ClassId,
	CM.DisplayTitle AS ClassName,
	A.Id As AcademicId,
	EM.Id AS ExamId,
	RD.IsPresent,
	RD.Obtain AS SubjectObtain,
	ED.Maximum AS SubjectMaximum,
	ED.Minimum AS SubjectMinimum,
	CAST(ROUND((ISNULL(RD.Obtain, 0) * 100.0) / NULLIF(ED.Maximum, 0), 2) AS DECIMAL(5,2)) AS SubjectPercentage,
	ED.DisplayOrder,
	--EmpM.ShortName AS TeacherName,
	ISNULL(EmpM.FirstName, '') + ' ' + ISNULL(EmpM.LastName, '') AS TeacherName,
	EmpM.FirstName,
	EmpM.MiddleName,
	EmpM.LastName,
	R.ResultStatus

	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			
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId						
		INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id AND EmpM.StatusId = 7			
			
	WHERE (ESGM.Id = @rExamSubGroupId OR @rExamSubGroupId = 0)
		AND ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND TSD.EmployeeId=@rEmployeeId
		AND (ISNULL(ESGM.Id ,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rExamSubGroupIds,',')) OR @rExamSubGroupIds='')--Added by dhananjay : 42465
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptGraphStudentWiseGradeList]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rClass nvarchar(MAX)='',
	 @rSubjectId int=0,
	 @rGroupId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
	
	select 
		
		 RD.Id AS TotalCount,
		@rBuilder1 AS Builder1,
		SM.Title AS SubjectName,
		CS.IsOptional ,
		ISNULL(GD.MarkRange,'') AS MarkRange,
		SM.OrderIndex AS SubjectOrderIndex, 
		--(select count(A.Id) from sStudent.tAcademic A  
		
		--INNER JOIN sAssessment.tResult R1 ON A.Id = R1.AcademicId 
	 --   INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R1.ExamId
		--INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		  
		--where  A.BatchId =  @rBatchId AND  EM.ExamSubGroupId=@rExamSubGroupId
		--and EM.BatchId=@rBatchId
		--and (CM.Id=@rClassId OR @rClassId=0)
		--AND (DM.ID=@rDivisionId OR @rDivisionId=0)
	 
		
		--) AS DivisionCount,
		CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN 'Division :'+ CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN 'Class :' + CM.DisplayTitle
				WHEN @rGroupId=3 THEN 'Department :' +Dept.Title 
				WHEN @rGroupId=4 THEN 'Organization :' +OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				SM.Id AS SubjectId
				
			
		 
from sAssessment.tResultDetail  RD
   
		 Inner join sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
		 
		
	where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and (CM.Id=@rClassId OR @rClassId=0)
		AND (DM.ID=@rDivisionId OR @rDivisionId=0)
		AND (SM.Id=@rSubjectId)
		  AND (ISNULL(Cm.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		 --Group by RD.SubjectGrade,GD.MarkRange,SM.Title,CS.IsOptional ,DM.Id,DM.DisplayTitle,Cs.Id,CM.DisplayTitle,SM.OrderIndex,CM.OrderIndex ,
		 --		CASE WHEN @rGroupId=1 THEN DM.Id 
			--	WHEN @rGroupId=2 THEN CM.Id 
			--	WHEN @rGroupId =3 THEN Dept.Id 
			--	WHEn @rGroupId =4 THEN OM.Id END ,
			--CASE WHEN @rGroupId=1 THEN 'Division :'+ CM.DisplayTitle+'/'+DM.DisplayTitle
			--	WHEN @rGroupId=2 THEN 'Class :' + CM.DisplayTitle
			--	WHEN @rGroupId=3 THEN 'Department :' +Dept.Title 
			--	WHEN @rGroupId=4 THEN 'Organization :' +OM.Title END ,
			--CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
			--	WHEN @rGroupId=2  THEN Cm.OrderIndex
			--	WHEN @rGroupId=3  THEN Dept.Id
			--	WHen @rGroupId=4 THen OM.OrderIndex  END,SM.Id
					
				
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAssessment].[pRptGSEBResultSheetCoScholasticGet]
	 
	 
	 --@rExamId int,
	 --@rAcademicId bigint
	 @rAcademicId bigint,
	 @rExamId bigint 
 
	 
	  
		
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

--DECLARE @lIsCoScholasticGrade	bit,@lIsCoScholasticGradeIndicator bit, @lIsCoScholasticGradeDesIndicator bit  
 
 
--SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
--@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
--@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator  
 
 
--FROM sAssessment.tExamMaster WHERE Id = @rExamId  
	SELECT		
			 
			Convert(nvarchar(10),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,	
			 
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.OrderIndex AS CoSujbectOrderIndex,
			cceCSGM.OrderIndex AS CoSubjectGroupOrderIndex,
			--@lIsCoScholasticGrade AS IsCoScholasticGrade,
			--@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
			--@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
			cceCSGM.CCECSGroupTypeId,
			cceCSGM.Code,
			
			CASE WHEN cceCSM.Number%2 = 0 THEN 2
				 ELSE 1
				 END AS COSCHOLASTIC 
	FROM 
			sAssessment.tCCECSExamScore cceCSS		
			 
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
	WHERE 
		     cceCSS.ExamId=@rExamId
		     AND cceCSS.AcademicId=@rAcademicId	
		    
		      
END

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

BEGIN

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

	FROM 
		--sAssessment.tResultDetail RD
		sAssessment.tResult R 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId 		
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
		--INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
		--INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		--INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id AND EmpM.StatusId = 7			
		--LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
		--LEFT JOIN
		--(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
		--INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
		--INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT ON RT.SourceId = StuM.Id 
			
	WHERE ESGM.Id = @rExamSubGroupId
		AND ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))		
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptPassFailAnalysisSubjectWise]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rSubject nvarchar(MAX)='',
	 @rClassStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		 
	 select 	
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Sm.OrderIndex As SubjectOrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		CM.OrderIndex AS ClassOrderIndex,
	 

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS FailStudent ,
	  ED.Minimum AS SubjectMinimum,
	  ED.Maximum AS SubjectMaximum,
	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND R.ResultStatus='PROMOTED' AND RD.Obtain<ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS PromotedStudentFail,

	  	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND R.ResultStatus='PROMOTED' AND RD.Obtain>=ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS PromotedStudentPass
	  
	  
	 from		
		sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	WHERE 		
		
		EM.BatchId = @rBatchId 
		AND  ((@rClassId > 0 AND cs.ClassId=@rClassId)
		OR (@rClassId = 0 AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')))		
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
		AND	CM.BatchId = @rBatchId
		AND EM.ExamSubGroupId = @rExamSubGroupId
		AND EM.BatchId = @rBatchId
		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
		
END



-- UNION ALL
  
 --  select 	
	--	@rBuilder1 AS Builder1,
	--	Cm.Classid As ClassId,
	--	Dm.id As DivisionId,
	--	Cm.ClassName As Classname,
	--	DM.DisplayTitle As DivisionName,
	--	CS.Id AS ClassSubjectId,
	--	SM.Id AS SubjectId,
	--	SM.Code AS SubjectName,
	--	Sm.OrderIndex As SubjectOrderIndex,
	--	DM.OrderIndex AS DivisionOrderIndex,
	--	CM.OrderIndex AS ClassOrderIndex,
	 

	--  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	--	INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	--	INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	--	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	--	INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS PassStudent,
  
	--(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	--	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	--	INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	--	INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	--	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	--	INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	--  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS FailStudent 
	  
	  
	-- from		
	--	sAssessment.tExamMaster EM 
	--	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
	--	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	--	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	--	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	--	INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
	--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
	--	INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
	--	INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	--WHERE 		
		
	--	EM.BatchId = @rBatchId 
	--	AND (CS.ClassId=@rClassId OR @rClassId=0) 
	--	AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
	--	AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	--	AND	CM.BatchId = @rBatchId
	--	AND EM.ExamSubGroupId = @rExamSubGroupId
	--	AND EM.BatchId = @rBatchId
	--	AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptPassFailOverAllAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rDepartmentId int =0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(Max)='',
	 @rGroupId int=1,
	 @rStatusId int = 0,
	 @rClassStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--create table #Temphead
-- (Id Int Identity (1,1),
--  HEADID int,
--  PassStudent int,
--  FailStudent int
--  )
--  INSERT INTO #Temphead
--  (select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.tAcademic AC ON R.AcademicId = AC.Id 
--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
--  	  WHERE EM.ExamSubGroupId = @rExamSubGroupId 
--	  AND EM.BatchId = @rBatchId 
--	  AND AC.BatchId = @rBatchId 
--	  AND R.ResultStatus='PASS') AS PassStudent,
--	  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic AC ON R.AcademicId = AC.Id 
--	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
--	  	 WHERE EM.ExamSubGroupId = @rExamSubGroupId 
--	  AND EM.BatchId = @rBatchId 
--	  AND AC.BatchId = @rBatchId 
--	  AND R.ResultStatus='FAIL' AND AC.BatchId = @rBatchId ) AS FailStudent
	  	
	  
		
--	FROM sAssessment.tResult R
--      INNER JOIN sStudent.tAcademic A  ON R.AcademicId = A.Id  INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id
--      INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
--      INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
--      WHERE (A.DivisionId=@rDivisionId OR @rDivisionId=0)
--		AND (A.ClassId=@rClassId OR @rClassId=0)
--		AND EM.BatchId=@rBatchId
--		AND EM.ExamSubGroupId =@rExamSubGroupId
--		GROUP BY CASE WHEN @rGroupByid=1 THEN A.DivisionId 
--		WHEN @rGroupByid=2 THEN A.ClassId
--		WHEN @rGroupByid =3 THEN Dept.Id
--		WHEN @rGroupByid =4 THEN A.OrgId 
--		ELSE 0 END 
 

  SELECT A.GroupId,A.Builder1,A.ClassId,A.DivisionId,A.Classname,A.DivisionName,A.DivisionOrderIndex,A.ClassOrderIndex,A.TotalPassStudent,A.TotalFailStudent,A.GroupName,A.GroupTitle,A.OrderIndex,
  
  (select COUNT(R.AcademicId) from   sAssessment.tResult R  
  
  INNER JOIN sStudent.vStudentAcademic AC ON R.AcademicId = AC.AcademicId 
  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
  INNER JOIN sSetup.tClassMaster CM ON CM.Id = EM.ClassId
  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId

	  where
	
	 CASE WHEN @rGroupId = 4  THEN AC.OrgId
                 WHEN @rGroupId = 2 THEN AC.ClassId 
                  WHEN @rGroupId = 3 THEN Dept.Id 
                 ELSE AC.DivisionId 
            END = A.GroupId
         --AND
	
	   
	 --((@rGroupId = 3 AND AC.OrgId = A.GroupId)  OR (1 = 1) )
	 --AND ((@rGroupId = 2 AND AC.ClassId = A.GroupId) OR (1 = 1)    )
  --   AND ((@rGroupId = 1 AND AC.DivisionId = A.GroupId) OR (1 = 1) )
      

	  -------- AND ((A.GroupId = 1 AND AC.DivisionId = A.GroupId) OR 1 = 1)
	
	  
	  AND EM.ExamSubGroupId = @rExamSubGroupId 
	  AND EM.BatchId = @rBatchId 
	  AND AC.BatchId = @rBatchId 
	  AND R.ResultStatus='PASS'
	  AND ((AC.ClassId=@rClassId ) or (@rClassId=0))
	  AND ((AC.DivisionId=@rDivisionId) or (@rDivisionId=0))
	  AND ((Ac.StatusId=@rStatusId) OR (@rStatusId=0)) 
	  AND ((AC.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 
	  ) AS PassStudent,
	  
	  
	  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.vStudentAcademic AC ON R.AcademicId = AC.AcademicId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	  	INNER JOIN sSetup.tClassMaster CM ON CM.ID = EM.ClassId
        INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
	   where  CASE WHEN @rGroupId = 4  THEN AC.OrgId
                 WHEN @rGroupId = 2 THEN AC.ClassId 
                  WHEN @rGroupId = 3 THEN Dept.Id 
                 ELSE AC.DivisionId 
            END = A.GroupId
	   AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL' AND AC.BatchId = @rBatchId 
	     AND ((AC.ClassId=@rClassId ) or (@rClassId=0))
	       AND ((AC.DivisionId=@rDivisionId ) or (@rDivisionId=0))
	       AND ((Ac.StatusId=@rStatusId) OR (@rStatusId=0))
		    AND ((AC.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 
	   ) AS FailStudent
   FROM 
   (
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		 
		DM.OrderIndex AS DivisionOrderIndex,
		CM.OrderIndex AS ClassOrderIndex,
	 
 (select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	  			 
	  where 
	 A.ClassId = Cm.ClassId AND 
	 EM.ExamSubGroupId = @rExamSubGroupId 
	 AND EM.BatchId = @rBatchId  
	 AND R.ResultStatus='PASS'
	 AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 
	 ) AS TotalPassStudent,
	  
  
  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId
	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	  where 
	  A.ClassId = CM.ClassId AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL' AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))  AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 ) AS TotalFailStudent ,
	  
	  
	  
	--(select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent ,
	  CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.ClassId 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEN @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.ClassName+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.ClassName
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN DM.OrderIndex
				WHEN @rGroupId=2  THEN CM.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHEN @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHEN @rGroupId=4 THen  'Organization'  END AS GroupTitle
				
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	 INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	 INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
	 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
		WHERE 
			((DM.ID=@rDivisionId) or (@rDivisionId=0))
			AND ((Dm.ClassId=@rClassId ) or (@rClassId=0))
			AND CM.BatchId=@rBatchId
			AND EM.BatchId = @rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
		    AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		    AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId =0))
	) A
  
	
END

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

BEGIN 

-- Select * from dbo.TempTableForProgress
	--SELECT 
	--	Convert(BigInt,0) AS AcademicId,
	--	Convert(date,'') AS ExamDate,
	--	Convert(Decimal,0) AS Maximum,
	--	Convert(Decimal,0) AS Obtain,
	--	Convert(Decimal,0) AS Percentage,
	--	'' AS ExamTopic,
	--	'' AS SubjectName,
	--	'' AS ExamGroup,
	--	Convert(varbinary,0) AS StudentPhoto,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	'' AS StudentName,
	--	0 AS RollNo,
	--    Convert(bit,0) AS IsMarksInDecimal,
	--	'' AS Year,
	--	'' AS MonthFrom,
	--	'' AS MonthTo,
	--	'' AS Code,
	--	'' AS EXAMNAME,
	--	'' AS ResultStatus,
	--	Convert(bit,0) As IsPresent,
	--  Convert(decimal,0) AS TotalObtainSubWise,
	--  Convert(decimal,0) AS TotalMarkSubWise,
	--  Convert(decimal,0) AS PercentageSubWise,
	--	Convert(bit,0) IsIncludeInTotal, --mantis - 35312
	--	'' As DecimalFormat, --mantis - 35312
	--	'' AS ExamSeatNo, --mantis - 35312
	--  0 AS ExamSubGroupOrderIndex, --Added by dhananjay for mantis Start -35688
	--  '' As DepartmentName, --Added by dhananjay for mantis End -35688
	-- '' ExamNameTitle
		

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

AND AM.DivisionId = ' + CONVERT(NVARCHAR(500),@rDivisionId) + '
AND EGM.Id IN (' + CONVERT(NVARCHAR(500),@rExamGroupIdStr) + ')
AND ED.ClassSubjectId IN (' + CONVERT(NVARCHAR(500),@rClassSubjectIdStr) + ')
AND ED.EXAMDATE >= ''' + CONVERT(NVARCHAR,@rFromDate) +
''' AND ED.EXAMDATE <= ''' + CONVERT(NVARCHAR,@rToDate) +
''' AND ((AM.RollNo >= '''+ CONVERT(NVARCHAR(10),@rFromRollNo)+''') OR (' + CONVERT(NVARCHAR(10),@rFromRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.RollNo <= '''+ CONVERT(NVARCHAR(10),@rToRollNo) + ''' ) OR (' + CONVERT(NVARCHAR(10),@rToRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.Id = '''+ CONVERT(NVARCHAR(20),@rAcadedmidId) + ''' ) OR (' + CONVERT(NVARCHAR(20),@rAcadedmidId)+'='''+ CONVERT(NVARCHAR(20),0) + ''')) 
GROUP BY R.AcademicId,ED.ClassSubjectId,ED.ExamDate,ED.ExamId,RD.IsPresent'
-- Remove RD.IsPresent = 1 Condition from @query (As requirement Absent and present students data should be visibled) Mantis :0027445
 --print @query
execute(@query)

-- To maintain Group Footer length add in report row	
--select 1, '.' + replicate('`', 600)  + '.'   font size 1
--Select * from #tempProgressCard
SELECT
T.AcademicId,
T.ExamDate,
T.Maximum,
T.Obtain,
T.Percentage,
CASE WHEN ED.ExamTopic = '0' THEN '' ELSE ED.ExamTopic  END AS ExamTopic,
CS.SubjectName AS SubjectName,
EGM.Title AS ExamGroup,
SF.StudentPhoto as StudentPhoto , 
SF.ClassName,
SF.DivisionName,
SF.Name AS StudentName,SF.RollNo, 
EM.IsMarksInDecimal,
SF.Code,
sCommon.fGetMonthName(DatePart(MM,@rFromDate)) AS MonthFrom,
sCommon.fGetMonthName(DatePart(MM,@rToDate)) AS MonthTo,
BM.Title AS Year,
ISNULL(ESGM.Title,'') AS EXAMNAME ,
(Select ResultStatus FROM sAssessment.tResult Where AcademicId = T.AcademicId AND  ExamId = EM.Id)AS ResultStatus,
T.IsPresent,
-- Mantis Start - 35312
(SELECT SUM(T2.Obtain)
     FROM #tempProgressCard T2
     WHERE T2.AcademicId = T.AcademicId
       AND T2.ClassSubjectId = T.ClassSubjectId
 ) AS TotalObtainSubWise,
 (SELECT SUM(T2.Maximum)
     FROM #tempProgressCard T2
     WHERE T2.AcademicId = T.AcademicId
       AND T2.ClassSubjectId = T.ClassSubjectId
 ) AS TotalMarkSubWise,
 (SELECT (SUM(T2.Obtain) * 100) / SUM(T2.Maximum)
     FROM #tempProgressCard T2
     WHERE T2.AcademicId = T.AcademicId
       AND T2.ClassSubjectId = T.ClassSubjectId
 ) AS PercentageSubWise,
 ISNULL(ED.IsIncludeInTotal,0) AS IsIncludeInTotal, 
ISNULL(Em.DecimalFormat,'') AS DecimalFormat,
ISNULL(AD.ExamSeatNo,'') AS ExamSeatNo, 
	--Mantis End - 35312
	--Added by dhananjay for mantis Start -35688
	ESGM.OrderIndex AS ExamSubGroupOrderIndex,
	DM.Title As DepartmentName,
	--Added by dhananjay for mantis End -35688
	ISNULL(EM.DisplayTitle,'') AS ExamNameTitle,
(SELECT SUM(T2.Maximum)
     FROM #tempProgressCard T2
     WHERE T2.AcademicId = T.AcademicId
	 AND MONTH(T2.ExamDate) = MONTH(T.ExamDate)
       --AND T2.ClassSubjectId = T.ClassSubjectId
 ) AS TotalMaximum		--Mantis - 36168


FROM #tempProgressCard T 
INNER JOIN sAssessment.tExamMaster EM on EM.Id=T.ExamId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = T.ExamId AND EM.Id=ED.ExamId AND T.ExamDate = ED.ExamDate
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
--INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id
INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId AND CS.ClassSubjectId=T.ClassSubjectId 
INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId	= T.AcademicId AND SF.StatusId=1
INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SF.BatchId
LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId=EM.Id AND SR.AcademicId=T.AcademicId

INNER JOIN sSetup.tDepartmentMaster DM ON  DM.id = SF.DepartmentId   --Added by dhananjay for mantis - 35688
LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = T.AcademicId
Order By SF.RollNo,CS.OrderIndex,T.ExamDate Desc



DROP TABLE #tempProgressCard

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptProgressCardSubjectWiseDetailsGet]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int=0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--Select
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	'' AS AcademicIdText,
	--	'' Code,
	--	'' AS Name,
	--		0 AS RollNo,
	--	Convert(BigInt,0) AcademicId,			
	--	'' ResultStatus,
	--	'' AS Class,
	--	'' AS Division,
	--  0 AS ExamId,
	--	'' AS ExamName,
	--  Convert(Date,null) AS ExamDate,
	--		Convert(Decimal,0) TotalMark,
	--	Convert(Decimal,0) TotalObtain,
	--	0 AS RankNumber,
	--	Convert(Decimal,0) Percentage,
	--	'' AS ResultGrade,
	--	Convert(Decimal,0) Percentile,
	--	Convert(BigInt,0) ResultDetailId,		
	--	Convert(Bit,0) IsDisplayInMarksheet,
	--	Convert(Bit,0) IsShowSubjectGrade,
	--	Convert(Bit,0) IsIncludeInTotal,
	--	Convert(Decimal,0) AS SubjectObtain,
	--  '' AS SubjectGrade,
	--	Convert(Decimal,0) AS SubjectMinimum,
	--	Convert(Decimal,0) AS SubjectMaximum,
	--		'' AS SubjectCode,
	--	'' AS SubjectName,
	--	0 AS SubjectOrderIndex,
	--	Convert(BigInt,0) AS ResultId,
	--	0 AS SubjectId,			 	
	--	Convert(Bit,0) IsMarksInDecimal,		
	--	'' AS Remark1,
	--	'' AS Remark2,
	--	'' AS Remark3,
	--	'' AS DisplayTitle,
	--	Convert(Bit,0) IsRankNo, 
	--	Convert(Bit,0) IsGrade,
	--	Convert(Bit,0) IsPercentile,
	--	Convert(Bit,0) IsPercentage,
	--	Convert(Bit,0) IsSubjectPercentile,
	--	Convert(Bit,0) IsProcessResult,			 
	--	Convert(Bit,0) IsNegativeMarks,
	--	Convert(Bit,0) IsIncludeCoScholastic,
	--	Convert(Bit,0) IsOnPrePrinted,
	--	Convert(Bit,0) IsDisplayPhoto,
	--	Convert(Bit,0) IsDisplayBirthDate,
	--	Convert(Bit,0) IsLockForEdit,
	--	Convert(Bit,0) IsDisplaySchoolName,			
	--	Convert(Bit,0) IsDisplayAttendance,
	--	Convert(Bit,0) IsDisplayHeightWeight,
	--	Convert(Bit,0) IsResultStatus,
	--  '' AS IsDisplayMonthlyAttendanceText,
	--  Convert(Bit,0) IsDisplayMonthlyAttendance,
	--	'' AS FooterAdjustmentText,
	--	'' AS DetailAdjustmentText,
	--	0 AS FooterAdjustment,
	--	0 AS DetailAdjustment,		 		 		 
	--	Convert(Bit,0) IsPresent,			
	--	'' SmallAddress1,
	--	Convert(Bit,0) IsDisplayParentName,				
	--	Convert(Bit,0) AS IsShowSubjectMark,			
	--	Convert(Bit,0) IsDisplayTeacherSign,
	--	Convert(Bit,0) IsDisplayPrincipalSign,		 			 
	--	Convert(Bit,0) AS IsImageHeader,			 
	--	'' AS DecimalFormat,	 			 
	--	'' AS FatherName,
	--	'' AS MotherName,
	--  0 AS SubjectCount,
	--  Convert(Decimal,0) AS TotalDays,
	--  Convert(Decimal,0) AS PresentDays

CREATE TABLE #TempExam
(
    Id int IDENTITY(1,1) PRIMARY KEY,
    ExamId int,
    Exam nvarchar(100)
)

INSERT INTO #TempExam
(
	 ExamId,
	 Exam 	
)

SELECT 
@rExamId AS ExamId,
ESGM.Title AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
WHERE EM.ClassId=@rClassId AND EM.BatchId =@rBatchId AND EM.Id = @rExamId

UNION ALL

SELECT 
EM.Id AS ExamId,
ESGM.Code AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

UNION ALL 

SELECT
EM.Id AS ExamId,
ESGM.Title AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId IN (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId)  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

CREATE TABLE #TempSubjectCount(
ExamId int,
AcademicId BigInt,
SubjectCount int
)
INSERT INTO #TempSubjectCount(ExamId, AcademicId, SubjectCount)
    SELECT R.ExamId, R.AcademicId, COUNT(RD.Id) AS SubjectCount
    FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
    INNER JOIN #TempExam TE ON TE.ExamId = R.ExamId
    GROUP BY R.ExamId,R.AcademicId

--select * from #TempExam
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			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,
			EC.ExamId,
			EC.Exam AS ExamName,
			ED.ExamDate,
			R.TotalMarks AS TotalMark,
			R.TotalObtain,
			R.RankNumber,
			R.Percentage,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			RD.SubjectGrade,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			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.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,		 		 		 
			RD.IsPresent,	
			OM.SmallAddress1,
			EM.IsDisplayParentName,			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,		 		 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,			 
			EM.DecimalFormat,						 
			SF.FatherName,
			SF.MotherName,
			TSC.SubjectCount AS SubjectCount,
			--start mantis : 0035105
			ISNULL(SR.TotalDays,0) AS TotalDays, 
			ISNULL(SR.PresentDays,0) AS PresentDays
			--end mantis : 0035105
						
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.ExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			INNER JOIN #TempSubjectCount TSC ON TSC.ExamId = EM.Id  AND TSC.AcademicId = A.Id 
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

	ORDER BY A.RollNo , EC.Id
		
	 DROP TABLE #TempExam
	 DROP TABLE #TempSubjectCount
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

BEGIN 

--select * from sAssessment.tTempAllExam
-- drop table sAssessment.tTempAllExam


 
	
 

	CREATE TABLE #TempAllExam
	(
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(10),
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(6,2),
		TotalObtain decimal(6,2),
		Percentage decimal(6,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),
		ClassSubjectID int,
		SubjectGrade NVarchar(50),
		
		MaximumMark1 decimal(6,2),
		Exam1Name Nvarchar(150),
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(6,2),
		
		MaximumMark2 decimal(6,2),
		Exam2Name nvarchar(150),
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(6,2),
		
		MaximumMark3 decimal(6,2),
		Exam3Name nvarchar(150),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(6,2),
		
		MaximumMark4 decimal(6,2),
		Exam4Name nvarchar(150),
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(6,2),
		
		MaximumMark5 decimal(6,2),
		Exam5Name nvarchar(150),
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(6,2),
		
		MaximumMark6 decimal(6,2),
		Exam6Name nvarchar(150),
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(6,2),
		IsMarksInDecimal bit,
		 column_visible bit
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicId,ExamName,StudCode ,StudentName ,RollNo ,ResultStatus ,ClassName ,Division ,
	TotalMark ,TotalObtain ,Percentage ,RankNumber ,ResultGrade ,
	SubjectName ,SubjectCode,ClassSubjectID,SubjectGrade,IsMarksInDecimal ,column_visible)
	SELECT 
	A.Id,ISNULL(ESGM.Title,'') AS EXAMNAME,
	StuM.Code AS StudCode,StuM.FirstName + ' ' + StuM.LastName AS Name,A.RollNo,
	R.ResultStatus,CM.DisplayTitle AS ClassName,DM.DisplayTitle AS Division,
	R.TotalMarks AS TotalMark,R.TotalObtain,R.Percentage,R.RankNumber,R.ResultGrade,
	SM.Title AS SubjectName,ISNULL(SM.Code,'') AS SubjectCode,ED.ClassSubjectId,RD.SubjectGrade,
	EM.IsMarksInDecimal,1
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	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 sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	WHERE EM.ClassId=@rClassId And  EM.Id = @rExamId 
	Order By ED.DisplayOrder
 
 --print 'temp insert'
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int)
	INSERT INTO #tempcombineExam (ExamID) 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
	
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
			
		set @query ='update T set MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain 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.tExamCombine EC ON EC.SubExamId = EM.Id
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID=ED.ClassSubjectId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
						WHERE EM.ClassId=' + convert(nvarchar(15), @rClassId) +' And T.AcademicId = R.AcademicId
						AND EC.SubExamId =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
--	print (@query)
		set @lCount = @lCount -1
	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 @lCount1 = @lCount1 + 1
	END
	
	SELECT @rBuilder1,@rBuilder2, * 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=''))		
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by T.RollNo,CS.ORDERINDEX
		
	drop table #tempcombineExam
	Drop table #TempAllExam
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultAnalysisBatchClassandGradewise]
	  
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rExamSubGroupId int=0,
	 @rBatchId1 int,
	 @rBatchId2 int,
	 @rIsDetail bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--select
	--   '' AS Builder1,
	--   '' AS Builder2,
	--   0 AS AcademicId,
	--   0 AS ClassId,
	--   0 AS DivisionId,
	--   '' AS ClassName,
	--   '' AS DivisionName,
	--   '' AS ResultGrade,
	--   0 AS BatchId,
	--   '' AS GradeCode,
	--   0 AS MinimumScore,
	--   '' AS ExamName,
	--   0 AS ExamId,
	--   '' AS BatchName,
	--   0 AS IsDetail
		
 DECLARE @GradeSetId int
	 DECLARE @GradeSetId1 int
		
	 Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId1)
	 Set @GradeSetId1=(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId2)  
	CREATE Table #Temp
	(
		Id Int ,
		GradeSetId int,
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	CREATE Table #Temp1
	(
		Id Int ,
		GradeSetId int,
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
		select  Id,GradeSetId,GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
		
	Insert into #Temp1
		select Id,GradeSetId,GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId1

Select 
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   A.AcademicId,
	   A.ClassId,
	   A.DivisionId,
	   A.ClassName,
	   A.DivisionName,
	   R.ResultGrade,
	   BC.BatchId,
	   tmp.GradeCode,
	   tmp.MinimumScore	,
	   ESGM.Code AS ExamName,
	   ESGM.Id AS ExamId,
	   BM.Code AS BatchName,
	   @rIsDetail AS IsDetail
 from sAssessment.tResult R 
	INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id
	INNER JOIN #Temp tmp ON tmp.GradeSetId=EM.GradeSetId AND tmp.GradeCode=R.ResultGrade
	INNER JOIN   ssetup.tDivisionMaster DM ON A.DivisionId=DM.Id
	INNER JOIN sSetup.vBatchClass BC ON BC.ClassId = DM.ClassId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=@rExamSubGroupId
	LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=BC.BatchId

	WHERE 
	
		BC.BatchId=@rBatchId1 AND EM.BatchId=@rBatchId1
		AND A.DivisionId = DM.Id
		AND EM.ExamSubGroupId = @rExamSubGroupId
	
	UNION
Select 
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   A.AcademicId,
	   A.ClassId,
	   A.DivisionId,
	   A.ClassName,
	   A.DivisionName,
	   R.ResultGrade,
	   BC.BatchId,
	   tmp1.GradeCode,
	   tmp1.MinimumScore,
	   ESGM.Code AS ExamName,
	   ESGM.Id AS ExamId,
	   BM.Code AS BatchName,
	   @rIsDetail AS IsDetail
 from sAssessment.tResult R 
	INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	INNER JOIN sAssessment.tExamMaster EM ON R.ExamId = EM.Id
	INNER JOIN #Temp1 tmp1 ON tmp1.GradeSetId=EM.GradeSetId AND tmp1.GradeCode=R.ResultGrade
	INNER JOIN   ssetup.tDivisionMaster DM ON A.DivisionId=DM.Id
	INNER JOIN sSetup.vBatchClass BC ON BC.ClassId = DM.ClassId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id=@rExamSubGroupId
	LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=BC.BatchId

	WHERE 
	
		BC.BatchId=@rBatchId2 AND EM.BatchId=@rBatchId2
		AND A.DivisionId = DM.Id
		AND EM.ExamSubGroupId = @rExamSubGroupId
		
		Order By ClassId,DivisionId,GradeCode
		
		DROP Table #Temp
		DROP Table #Temp1

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultAnalysisBatchClassandSubjectWise]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rDepartmentId int=0,
	 @rExamSubGroupId int ,
	 @rBatchId1 int,
	 @rBatchId2 int,
	 --@rClassStatusId int=0 ,
	 @rIsDisplayAvgTotal bit=0,
	 @rIsDetail bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
 
	BEGIN

	SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			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.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,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal,
			@rIsDetail AS IsDetail
	
	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 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			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
		
	WHERE 
			
		EM.BatchId = @rBatchId1
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId1
		AND ESGM.Id = @rExamSubGroupId
		AND StuM.StatusId = 1

UNION 
	
		SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			--temp.tempAcademicId,
			A.Id AS 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,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal,
			@rIsDetail AS IsDetail

			--2 As ExamNo
	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 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			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
	WHERE 
		   EM.BatchId = @rBatchId2
		   AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		   AND	A.BatchId = @rBatchId2
		   AND ESGM.Id = @rExamSubGroupId
		   AND StuM.StatusId = 1
		order by A.RollNo,ClassOrderIndex
	--	SELECT * FROM #temp
	--RETURN 
		END
		--DROP Table #Temp_Academic
		--DROP Table #Temp_StudentId
		
			--SELECT 
			--0 AS IsDisplayAvgTotal,
			--'' AS Builder1,
			--'' AS Builder2,
			--0 AS ExamId,
			--'' AS Exam,
			--0 As BatchId,
			--'' As BatchName,
			--''  AS Code,
			--'' AS Name,
			--0 AS RollNo,
			----temp.tempAcademicId,
			--0 AS AcademicId,
			--0 AS Obtain,
			--'' AS ResultStatus,
			--'' AS Class,
			--0  AS ClassId,
			--'' AS Division,
			--0 AS DivisionId,
			--0 AS DivisinOrderIndex,
			--0 AS TotalMarks,
			--0 AS TotalObtain,
			--0 AS Percentage,
			--0 AS RankNumber,
			--'' AS ResultGrade,
			--'' AS ClassSubject,
			--0 AS ResultDetailId,
			--0 AS ResultId,
			--0 AS SubjectId,
			--0 AS Maximum,
			--'' AS SubjectGrade, 
			
			--0 AS IsMarksInDecimal,
			----SM.OrderIndex AS SubjectCode,
			--'' AS SubjectCode,
			--0 AS SubjectOrderIndex,
			--0 AS ClassOrderIndex,
			--0 AS IsPresent,
			-- 0 AS IsGrade,
			--0 AS IsPercentage,
			--0 AS IsResultStatus,
			--0 AS IsRankNo ,
			--0 AS  Minimum,
			--0 AS GraceMark,
			--'' AS DecimalFormat,
			--0 AS IsOptional,
			--0 AS PresentDays,
			--0 AS TotalDays,
			--0 As AvgTotal,
			--0 AS IsDetail
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultAnalysisBatchStudentWise]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int,
	 @rDivisionId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int =0,
	 @rToRollNo int =0,
	 @rStatusId int = 0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rExamId1 int ,
	 @rExamId2 int ,
	 @rBatchId1 int,
	 @rBatchId2 int,
	 @rClassStatusId int=0 ,
	 @rIsDisplayAvgTotal bit=0,
	 @rIsDetail bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
 
	BEGIN
	
	CREATE TABLE #Temp_StudentId (StudentId bigint);
	INSERT INTO #Temp_StudentId
	SELECT A1.StudentId From sStudent.tAcademic A1 
	INNER JOIN
	sStudent.tAcademic A2 ON A1.StudentId = A2.StudentId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A1.StudentId
	WHERE A1.BatchId =  @rBatchId1 AND A2.BatchId = @rBatchId2
	AND (A1.ClassId=@rClassId OR @rClassId=0) 
	AND (A1.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND ((A1.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((A1.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND SM.StatusId = 1
	AND ((A1.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	
	
CREATE TABLE #Temp_Academic (tempAcademicId bigint);
INSERT INTO #Temp_Academic 
SELECT  A.Id As tempAcademicId FROM sAssessment.tResult R 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		WHERE BM.Id = @rBatchId2 AND R.ExamId =@rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		  
	--SELECT * FROM #temp
	--RETURN 	
		
	SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			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,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal,
			@rIsDetail AS IsDetail
			
			--RD.SubjectGrade AS TermSubjectGrade,
			--RD.SubjectGrade AS SubjectGrade
			--1 As ExamNo
	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
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			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
			
	WHERE 
			
		EM.BatchId = @rBatchId1
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((EM.Id=@rExamId1 )	OR (@rExamId1 = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId1
		AND R.ExamId = @rExamId1
		 AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

UNION 
	
		SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A2.RollNo,
			--temp.tempAcademicId,
			A2.Id AS AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM2.DisplayTitle AS Class,
			Cm2.Id AS ClassId,
			DM2.DisplayTitle AS Division,
			DM2.Id AS DivisionId,
			DM2.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,
			CM2.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,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal,
			@rIsDetail AS IsDetail

			--2 As ExamNo
	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
			INNER JOIN #Temp_Academic temp ON temp.tempAcademicId= A.Id  
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			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
			INNER JOIN sStudent.tAcademic A2 ON A2.StudentId = TEMP2.StudentId AND A2.BatchId = @rBatchId1
			INNER JOIN sSetup.tClassMaster CM2 ON CM2.Id=A2.ClassId
			INNER JOIN sSetup.tDivisionMaster DM2 ON DM2.Id=A2.DivisionId
	WHERE 
			
		EM.BatchId = @rBatchId2
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((EM.Id=@rExamId2 )	OR (@rExamId2 = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	((A.BatchId = @rBatchId2 ))
		AND R.ExamId = @rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,ClassOrderIndex
	--	SELECT * FROM #temp
	--RETURN 
		END
		DROP Table #Temp_Academic
		DROP Table #Temp_StudentId
		
		----For Report Dataset
		--SELECT 
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	EM.DisplayTitle AS Exam,
		--	EM.Id AS ExamId,
		--	StuM.Code,
		--	[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		--	A.RollNo,
		--	--temp.tempAcademicId,
		--	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,
		--	SR.PresentDays,
		--	SR.TotalDays,
		--	BM.Id As BatchId,
		--	BM.Title As BatchName
		--	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
		--	INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
		--	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
		--	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		--	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			


			--SELECT 
			--0 AS IsDisplayAvgTotal,
			--'' AS Builder1,
			--'' AS Builder2,
			--0 AS ExamId,
			--'' AS Exam,
			--0 As BatchId,
			--'' As BatchName,
			--''  AS Code,
			--'' AS Name,
			--0 AS RollNo,
			----temp.tempAcademicId,
			--0 AS AcademicId,
			--0 AS Obtain,
			--'' AS ResultStatus,
			--'' AS Class,
			--0  AS ClassId,
			--'' AS Division,
			--0 AS DivisionId,
			--0 AS DivisinOrderIndex,
			--0 AS TotalMarks,
			--0 AS TotalObtain,
			--0 AS Percentage,
			--0 AS RankNumber,
			--'' AS ResultGrade,
			--'' AS ClassSubject,
			--0 AS ResultDetailId,
			--0 AS ResultId,
			--0 AS SubjectId,
			--0 AS Maximum,
			--'' AS SubjectGrade, 
			
			--0 AS IsMarksInDecimal,
			----SM.OrderIndex AS SubjectCode,
			--'' AS SubjectCode,
			--0 AS SubjectOrderIndex,
			--0 AS ClassOrderIndex,
			--0 AS IsPresent,
			-- 0 AS IsGrade,
			--0 AS IsPercentage,
			--0 AS IsResultStatus,
			--0 AS IsRankNo ,
			--0 AS  Minimum,
			--0 AS GraceMark,
			--'' AS DecimalFormat,
			--0 AS IsOptional,
			--0 AS PresentDays,
			--0 AS TotalDays,
			--0 As AvgTotal,
			--0 AS IsDetail
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 


CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultAnusuchiGet]
	 
  --@rBuilder1 nvarchar(max)='',
	 --@rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int=0,
	
	 @rExamId int=0,
	  @rClassStatusId 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
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	
	--Select 
	--	   '' as FA1SA1,'' as FA2SA1,'' as FA3SA1,'' as FA4SA1,'' as FA5SA1,
	--	   '' as FA1SA2,'' as FA2SA2,'' as FA3SA2,'' as FA4SA2,'' as FA5SA2,
	--	   '' as FA1SA3,'' as FA2SA3,'' as FA3SA3,'' as FA4SA3,'' as FA5SA3,
	--	   '' as FA1SA4,'' as FA2SA4,'' as FA3SA4,'' as FA4SA4,'' as FA5SA4,
	--	   '' as FA1SA5,'' as FA2SA5,'' as FA3SA5,'' as FA4SA5,'' as FA5SA5
	
	
	 Create table #tempOrder
	 (
		SubExamId int,
		OrderIndex int
	 )
	 Insert into #tempOrder
	 (
		SubExamId,
		OrderIndex
	 )
	 select SubExamId,ExamOrder
	 From	sAssessment.tExamCombine Where ExamId=@rExamId  Order By ExamOrder Desc
	 
	 Update #tempOrder Set OrderIndex = 0 Where OrderIndex < (Select MAX(OrderIndex) FRom #tempOrder)
	 
	 --select * from #tempOrder
	  
	   
		 
	  
		
	 
	 Create table #temp
	 (
		 
		FA1SA1 nvarchar(max),
		FA2SA1 nvarchar(max),
		FA3SA1 nvarchar(max),
		FA4SA1 nvarchar(max),
		FA5SA1 nvarchar(max)  ,
		FA1SA2 nvarchar(max),
		FA2SA2 nvarchar(max),
		FA3SA2 nvarchar(max),
		FA4SA2 nvarchar(max),
		FA5SA2 nvarchar(max),
		FA1SA3 nvarchar(max),
		FA2SA3 nvarchar(max),
		FA3SA3 nvarchar(max),
		FA4SA3 nvarchar(max),
		FA5SA3 nvarchar(max),
		FA1SA4 nvarchar(max),
		FA2SA4 nvarchar(max),
		FA3SA4 nvarchar(max),
		FA4SA4 nvarchar(max),
		FA5SA4 nvarchar(max),
		FA1SA5 nvarchar(max),
		FA2SA5 nvarchar(max),
		FA3SA5 nvarchar(max),
		FA4SA5 nvarchar(max),
		FA5SA5 nvarchar(max)
	 )
	 Insert into #temp
	 (
		 FA1SA1,FA2SA1,FA3SA1,FA4SA1,FA5SA1  ,
		FA1SA2,FA2SA2,FA3SA2,FA4SA2,FA5SA2 ,
		FA1SA3,FA2SA3,FA3SA3,FA4SA3,FA5SA3 ,
		FA1SA4,FA2SA4,FA3SA4,FA4SA4,FA5SA4 ,
		FA1SA5,FA2SA5,FA3SA5,FA4SA5,FA5SA5  
	 )
	 Select		  
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=0 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=4) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=0AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=6)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA1SA1,  
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
						AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId
		 
		 INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId
		 INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		 WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=5 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=8) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=0AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=6)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA2SA1,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
						AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId
		 
		 INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId
		 INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		 WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=9 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=12) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=0AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=6)
		AND CS.SubjectId=@rSubjectId
		 Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA3SA1,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
						AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId
		 
		 INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId
		  INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		  WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		Group By A.Rollno, CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=13 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=16) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=0AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=6)
		AND CS.SubjectId=@rSubjectId
		 Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA4SA1,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
						AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId
		 
		 INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId
		  INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		  WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=17 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=20) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=0AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=6)
		AND CS.SubjectId=@rSubjectId
		 Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA5SA1,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=0 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=4) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=7AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=12)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA1SA2,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId	
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=5 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=6) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=7AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=12)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA2SA2,
		 
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId		
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	  
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=9 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=12) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=7AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=12)
		AND CS.SubjectId=@rSubjectId
		 
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA3SA2, 
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId		
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=13 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=16) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=7AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=12)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA4SA2, 
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 	 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=17 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=20) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=7AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=12)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA5SA2, 
		
		 (Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 	 	 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=0 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=4) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=13AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=18)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA1SA3,
		
		 (Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId		
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 	 	  
		Group By A.Rollno, CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=5 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=8) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=13AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=18)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA2SA3,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId		
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId	
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=9 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=12) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=13AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=18)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA3SA3,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 	 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=13 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=16) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=13AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=18)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA4SA3,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId		 
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 	 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=17 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=20) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=13AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=18)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA5SA3,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId		
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 	  
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=0 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=4) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=19AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=24)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA1SA4,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId		
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=5 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=8) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=19AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=24)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA2SA4,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId	
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		Group By A.Rollno, CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=9 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=12) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=19AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=24)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA3SA4,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))		 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=13 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=16) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=19AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=24)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA4SA4,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))		 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=17 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=20) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=19AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=24)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA5SA4,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))			 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=0 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=4) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=25AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=30)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA1SA5,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId		 
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))			 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=5 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=8) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=25AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=30)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA2SA5,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))			 	 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=9 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=12) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=25AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=30)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA3SA5,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=13 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=16) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=25AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=30)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA4SA5,
		
		(Select  Stuff ((SELECT ',' + convert(nvarchar(max),A.RollNo)		 
		From sStudent.tAcademic A 
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON  RD.ResultId = R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId =ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamId AND EM.BatchId = @rBatchId AND EM.ClassId=@rClassId		 
		INNER JOIN #tempOrder Temp ON Temp.SubExamId =EC.SubExamId	
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.CLassSubjectId	
		WHERE  ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	 
		Group By A.Rollno,CS.SubjectId
		Having 
		(sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)>=17 AND 
		sum(case when Temp.OrderIndex = 0 then (RD.Obtain/Ed.Maximum)*10 end)<=20) AND 
		(sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)>=25AND   
		sum(case when Temp.OrderIndex <> 0 then (RD.Obtain/Ed.Maximum)*30 end)<=30)
		AND CS.SubjectId=@rSubjectId
		Order By A.RollNo
			FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		)AS FA5SA5
		
		
		 Select * from #temp
		 
	



 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultListAnalysisGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int=0,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rGroupId int=0,
	 @rClass nvarchar(MAX)='',
	 @rSubject nvarchar(max)='',
	 @rStatusId int =0,
	 @rClassStatusId int=0
	 
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT  
	
			
			@rBuilder1 AS Builder1,
	 		A.RollNo,
	 		R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			 DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
		 
			--CM.DisplayTitle AS Class,
			
			ED.ClassSubjectId AS ClassSubjectId,
			RD.Obtain AS SubjectObtain,
			Subj.Id AS SubjectId,
			 
			Subj.Code AS SubjectCode,
			
			Subj.Title AS SubjectName,
			BM.Title,
			BM.Id AS Batch,
			 Subj.OrderIndex AS SubjectOrderIndex,
			 BM.OrderIndex AS BatchOrderIndex,
			--CM.OrderIndex AS ClassOrderIndex ,
			RD.SubjectGrade,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,	
				
				Dept.Title AS DepartmentName,
				OM.Title AS OraganizationName
      
	FROM 
			
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster Subj ON Subj.Id=CS.SubjectId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId			
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EM.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			inner join sStudent.tStudentMaster STM ON STM.Id = A.StudentId 
			
			 
	WHERE 
			
		 ((EM.batchId = @rBatchId  ) OR (@rBatchId=0))
	    AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 
		AND (( EM.ExamSubGroupId = @rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		 AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND (ISNULL(Subj.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
		and((STM.StatusId=@rStatusId) or (@rStatusId=0))
		 AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultListAnalysisGet1]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int=0,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId nvarchar(max)='',
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rGroupId int=0,
	 @rClass nvarchar(MAX)='',
	 @rSubject nvarchar(max)='',
	 @rStatusId int =0
	 
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT  
	EM.ExamSubGroupId,
			R.ExamId,
			@rBuilder1 AS Builder1,
	 		A.RollNo,
	 		R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			 DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
		 
			--CM.DisplayTitle AS Class,
			
			ED.ClassSubjectId AS ClassSubjectId,
			RD.Obtain AS SubjectObtain,
			Subj.Id AS SubjectId,
			 
			Subj.Code AS SubjectCode,
			
			Subj.Title AS SubjectName,
			BM.Title,
			BM.Id AS Batch,
			 Subj.OrderIndex AS SubjectOrderIndex,
			 BM.OrderIndex AS BatchOrderIndex,
			--CM.OrderIndex AS ClassOrderIndex ,
			RD.SubjectGrade,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,	
				
				Dept.Title AS DepartmentName,
				OM.Title AS OraganizationName
      
	FROM 
			
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster Subj ON Subj.Id=CS.SubjectId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId			
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EM.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			inner join sStudent.tStudentMaster STM ON STM.Id = A.StudentId 
			
			 
	WHERE 
			
		 ((EM.batchId = @rBatchId  ) OR (@rBatchId=0))
	    AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 
		--AND (( EM.ExamSubGroupId = @rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		 AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT item FROM  sCommon.fnsplit(@rExamSubGroupId ,','))OR @rExamSubGroupId ='')
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		 AND (ISNULL(EM.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND (ISNULL(Subj.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
		and((STM.StatusId=@rStatusId) or (@rStatusId=0))
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultListCastCategorywiseRangeGet]
	 
	@rBuilder1 nvarchar(max)='', 
	@rBuilder2 nvarchar(max)='', 
	@rBatchId int = 0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rExamId int = 0,
	@rStatusId int=0,
	@rClassStatusId int=0,
	@rCasteCategoryIds nvarchar(max) = '',
	@rFilterId int=0,
	@rOrgGroupBatchId int=0
	 		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	A.Id AS AcademicId,
	EM.Id AS ExamId,
	ESGM.Title AS ExamName,
	R.Percentage,
	StuO.GenderId,
	ISNULL(CCM.Id,0) AS CasteCategoryId,
	ISNULL(CCM.Title,'') AS CasteCategory

	FROM
	sAssessment.tResult R
	INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId	
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	LEFT JOIN sStudent.tStudentOther StuO ON StuO.StudentId = StuM.Id
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = StuO.CastCategoryId
	LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
	LEFT JOIN
		(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT ON RT.SourceId = StuM.Id 

	WHERE
	EM.Id = @rExamId 
	AND (EM.BatchId = @rBatchId OR  @rBatchId = 0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	AND (
			(@rFilterId = 0) -- All
			OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

BEGIN

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

	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	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
		--INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
		INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id AND EmpM.StatusId = 7			
		LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
		LEFT JOIN
		(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT ON RT.SourceId = StuM.Id 
			
	WHERE ESGM.Id = @rExamSubGroupId
		AND ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))		
		AND (
			(@rFilterId = 0) -- All
			OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			) 
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultListConsolidatedWithMarks2Get]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rDepartmentId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--Select
	--	'' AS AcademicIdText,
	--	'' AS ExamIdText,
	--	0 AS AnnualExamId,
	--	'' AS AnnualExam,
	--	'' AS Builder1,
	--	'' Code,
	--	'' AS Name,
	--	0 AS RollNo,
	--	Convert(BigInt,0) AcademicId,			
	--	'' ResultStatus,
	--	'' AS Class,
	--	'' AS Division,
	--	Convert(Decimal,0) TermTotalMark,
	--	Convert(Decimal,0) TermTotalObtain,
	--	0 AS TermRankNumber,
	--	Convert(Decimal,0) TermPercentage,
	--	'' AS TermGrade,
	--	Convert(Decimal,0) TermPercentile,			
	--	Convert(BigInt,0) ResultDetailId,		
	--	Convert(Bit,0) IsDisplayInMarksheet,
	--	Convert(Bit,0) IsShowSubjectGrade,
	--	Convert(Bit,0) IsIncludeInTotal,
	--	Convert(Decimal,0) AS SubjectObtain,
	--	Convert(Decimal,0) AS SubjectMinimum,
	--	Convert(Decimal,0) AS SubjectMaximum,			
	--	'' AS SubjectCode,
	--	'' AS SubjectName,
	--	0 AS SubjectOrderIndex,
	--	Convert(BigInt,0) AS ResultId,
	--	0 AS SubjectId,			 	
	--	Convert(Bit,0) IsMarksInDecimal,
			
	--	'' AS Remark1,
	--	'' AS Remark2,
	--	'' AS Remark3,
	--	'' AS DisplayTitle,
	--	Convert(Bit,0) IsRankNo, 
	--	Convert(Bit,0) IsGrade,
	--	Convert(Bit,0) IsPercentile,
	--	Convert(Bit,0) IsPercentage,
	--	Convert(Bit,0) IsSubjectPercentile,
	--	Convert(Bit,0) IsProcessResult,			 
	--	Convert(Bit,0) IsNegativeMarks,
	--	Convert(Bit,0) IsIncludeCoScholastic,
	--	Convert(Bit,0) IsOnPrePrinted,
	--	Convert(Bit,0) IsDisplayPhoto,
	--	Convert(Bit,0) IsDisplayBirthDate,
	--	Convert(Bit,0) IsLockForEdit,
	--	Convert(Bit,0) IsDisplaySchoolName,			
	--	Convert(Bit,0) IsDisplayAttendance,
	--	Convert(Bit,0) IsDisplayHeightWeight,
	--	Convert(Bit,0) IsResultStatus,
	--	'' AS FooterAdjustmentText,
	--	'' AS DetailAdjustmentText,
	--	0 AS FooterAdjustment,
	--	0 AS DetailAdjustment,		 		 
	--	0 AS TermScopeId,		 
	--	Convert(Bit,0) IsPresent,
	--	Convert(Bit,0) IsDisplayGradeString,			
	--	'' SmallAddress1,
	--	Convert(Bit,0) IsDisplayParentName,			 
	--	Convert(Bit,0) AS IsShowSubjectMark,			
	--	Convert(Bit,0) IsDisplayTeacherSign,
	--	Convert(Bit,0) IsDisplayPrincipalSign,		 			 
	--	Convert(Bit,0) AS IsImageHeader,			 
	--	0 AS ExamOrderIndex,
	--	'' AS DecimalFormat,
	--	0 TermExamId,
	--	'' AS ExamName, 			 
	--	'' AS FatherName,
	--	'' AS MotherName
	
 
 DECLARE @lAnnualExam Nvarchar(100) 
 SELECT @lAnnualExam = ESGM.Title FROM [sAssessment].[tExamMaster] EM 
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
	WHERE EM.ClassId=@rClassId AND EM.BatchId =@rBatchId AND EM.Id = @rExamId

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

INSERT INTO #TempExam
(
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 	
)
 
SELECT EC.ExamOrder,
EM.Id AS TermExamId,
@rExamId AS AnnualExamId,
ESGM.Title AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS AnnualExamIdText,
			EC.AnnualExamId,
			@lAnnualExam AS AnnualExam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks AS TermTotalMark,
			R.TotalObtain AS TermTotalObtain,
			R.RankNumber AS TermRankNumber,
			R.Percentage AS TermPercentage,
			R.ResultGrade AS TermGrade,
			R.Percentile AS TermPercentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			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.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,		 		 
			EM.TermScopeId,		 
			RD.IsPresent,
			EM.IsDisplayGradeString,	
			OM.SmallAddress1,
			EM.IsDisplayParentName,			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,		 		 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,			 
			EC.ExamOrderIndex,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamName, 						 
			SF.FatherName,
			SF.MotherName
						
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.TermExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
						
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
		    LEFT JOIN
			(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT ON RT.SourceId = StuM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.AnnualExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
		AND (
			(@rFilterId = 0) -- All
			OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			) 
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		
	 drop table #TempExam
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

BEGIN 

 --Select
 --           '' AS AcademicIdText,
	--		'' AS ExamIdText,
	--		'' AS IsDisplayMonthlyAttendanceText,
	--		'' AS Exam,
	--		'' AS Builder1,
	--		'' Code,
	--		'' AS Name,
	--		0 RollNo,
	--		Convert(bigInt, 0) AS AcademicId,			
	--		'' ResultStatus,
	--		'' AS Class,
	--		'' AS Division,
	--		--Convert(decimal , 0) AS TotalMarks,
	--		--Convert(decimal , 0) AS TotalObtain,
	--		Convert(decimal , 0) AS Percentage,
	--		0 RankNumber,
	--		'' ResultGrade,
	--		Convert(decimal , 0) AS Percentile,			
	--		Convert(bigInt, 0) AS ResultDetailId,		
	--		Convert(bit, 0) AS IsDisplayInMarksheet,
	--		Convert(bit, 0) AS IsShowSubjectGrade,
	--		Convert(bit, 0) AS IsIncludeInTotal,
	--		Convert(decimal , 0) AS SubjectObtain,
	--		Convert(decimal , 0) AS SubjectMinimum,
	--		Convert(decimal , 0) AS SubjectMaximum,			
	--		'' AS SubjectCode,
	--		'' AS SubjectName,
	--		0 AS SubjectOrderIndex,
	--		Convert(bigInt, 0) AS ResultId,
	--		0 AS SubjectId,			 	
	--		Convert(bit, 0) AS IsMarksInDecimal,
			
	--		'' AS Remark1,
	--		'' AS Remark2,
	--		'' AS Remark3,
	--		'' DisplayTitle,
	--		Convert(bit, 0) AS IsRankNo, 
	--		Convert(bit, 0) AS IsGrade,
	--		Convert(bit, 0) AS IsPercentile,
	--		Convert(bit, 0) AS IsPercentage,
	--		Convert(bit, 0) AS IsSubjectPercentile,
	--		Convert(bit, 0) AS IsProcessResult,
			 
	--		Convert(bit, 0) AS IsNegativeMarks,
	--		Convert(bit, 0) AS IsIncludeCoScholastic,
	--		Convert(bit, 0) AS IsOnPrePrinted,
	--		Convert(bit, 0) AS IsDisplayPhoto,
	--		Convert(bit, 0) AS IsDisplayBirthDate,
	--		Convert(bit, 0) AS IsLockForEdit,
	--		Convert(bit, 0) AS IsDisplaySchoolName,			
	--		Convert(bit, 0) AS IsDisplayAttendance,
	--		Convert(bit, 0) AS IsDisplayHeightWeight,
	--		Convert(bit, 0) AS IsResultStatus,
	--		'' AS FooterAdjustmentText,
	--		'' AS DetailAdjustmentText,
	--		0 FooterAdjustment,
	--		0 DetailAdjustment,
		 		 
	--		Convert(tinyInt, 0) AS TermScopeId,
		 
	--		Convert(bit, 0) AS IsPresent,
	--		'' AS GradeString,
	--		Convert(bit, 0) AS IsDisplayGradeString,
	--		 ''  AS HighestDivisionGrade,			
	--		'' SmallAddress1,
	--		Convert(bit, 0) AS IsDisplayParentName,
			 
	--		Convert(bit, 0) AS IsShowSubjectMark,
			
	--		Convert(bit, 0) AS IsDisplayTeacherSign,
	--		Convert(bit, 0) AS IsDisplayPrincipalSign,
		 
	--		Convert(bit, 0) AS IsDisplayMonthlyAttendance,
			 
	--		Convert(bit, 0) AS IsImageHeader,
			 
	--		0 AS SubExamId,
	--		0 AS ExamOrderIndex,
	--		0 AS AnnualExamId ,
	--		'' DecimalFormat,
	--		0 AS TermExamId,
	--		'' AS ExamNAme, 			 
	--		'' AS AnnualSubjectGrade,
	--		Convert(decimal , 0) As AnnualSubjectObtain,
	--		'' AS TermSubjectGrade,
	--		Convert(decimal , 0) As TermSubjectObtain ,
	--		'' AS SubjectGrade,
	--		'' AS Remark,
	--		'' AS FatherName,
	--		'' AS MotherName,
	--		Convert(decimal , 0) AS TotalDays,
	--		Convert(decimal , 0) AS PresentDays,
	--		Convert(decimal , 0) AS TotalMarks,
	--		Convert(decimal , 0) AS TotalObtain,
	--        Convert(decimal , 0) AS TermMaximum,
	--		Convert(decimal , 0) AS AnnualMaximum,
	--		Convert(decimal , 0) AS AnnualTotal,
	--		Convert(decimal , 0) AS AnnualObtain,
	--		Convert(decimal , 0) AS AnnualPercentage,
	--      Convert(bit, 0) AS IsDecimal
			
 
 
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@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

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

INSERT INTO #TempExam
(
	 SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 
	
)
Select  
	EC.SubExamId,
	EC.ExamOrder,
	EC.ExamId AS TermExamId,
	@rExamId AS AnnualExamId,
	ES.Title AS Exam	
	from  sAssessment.tExamCombine EC 
	INNER JOIN sAssessment.tExamMaster EM  ON EC.ExamId = EM.Id 
	 INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId
	 INNER JOIN (select SubExamId from sAssessment.tExamCombine where examId = @rExamId) AS SE
	 ON EC.ExamId = SE.SubExamId  
	--WHere EC.ExamId  in  (select SubExamId from sAssessment.tExamCombine where examId = @rExamId  )
	--Select * from #TempExam
	
 
		Declare @lAnnualExamMaximum int,@lExamId int
		Select @lExamId= AnnualExamId FROM #TempExam 

		Select @lAnnualExamMaximum=Maximum from sAssessment.tExamDetail Where ExamId=@lExamId
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			--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,			
			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.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
		 		 
			EM.TermScopeId,
		 
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			 
			EC.SubExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamNAme, 	
			(Select RD1.SubjectGrade from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS AnnualSubjectGrade,		 
			--ARD.SubjectGrade AS AnnualSubjectGrade,
			(Select RD1.Obtain from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS AnnualSubjectObtain,
			ARD.Obtain As AnnualSubjectObtain,
			(Select RD1.SubjectGrade from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.TermExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS TermSubjectGrade,
			--TRD.SubjectGrade AS TermSubjectGrade,
			(Select RD1.Obtain from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.TermExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS TermSubjectObtain,
			EC.TermExamId,
			RD.Id,
			RD.SubjectGrade AS SubjectGrade,
			ISNULL(ARD.Remark,'')  AS Remark,
			SF.FatherName,
			SF.MotherName,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			R.TotalMarks AS TotalMarks,
			R.TotalObtain,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.TermExamId AND CS.Id=Exd.ClassSubjectId
			)AS TermMaximum,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.AnnualExamId AND CS.Id=Exd.ClassSubjectId
			)AS AnnualMaximum,
			R.ExamId,
			(Select R1.TotalMarks from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=@rExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS AnnualTotal,
			(Select R1.TotalObtain from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=@rExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS AnnualObtain,
			(Select R1.Percentage from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=@rExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS AnnualPercentage,
			CONVERT(bit,@lDecimalConfig) AS IsDecimal
			
			
			
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.SubExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id 
			--AND ACS.SubjectId = @rSubjectId  
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.TermExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id 
			--AND TCS.SubjectId = @rSubjectId 
			
			
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
		    LEFT JOIN
			(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = StuM.Id 
				
			--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
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			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
	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 (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		--order by A.RollNo,CS.OrderIndex 
		
	 drop table #TempExam
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultListConsolidateWithMarksGet]
	 
	 @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
	
	 --,@rcolumn_visible bit
	

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

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

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

	
	)	
	 --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 
	
	)
	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
	
		
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.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
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
				  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 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  ISNULL(EMP.IsOtherUser,0) = 0
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	    
	Order By ED.DisplayOrder

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

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


	CREATE TABLE #CombineExam
	(
	Id int IDENTITY,
	ExamId int
	)

	INSERT INTO #CombineExam(ExamId)
	SELECT 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 Order By EC.ExamId ASC

		--Select * from #CombineExam
		DECLARE @lIdCount int,@query1  AS NVARCHAR(MAX),@lExamId int,@lTotalCount int,@query2  AS NVARCHAR(MAX),@query3  AS NVARCHAR(MAX)
  
	Select Top 1 @lIdCount = Id from #CombineExam
	Select @lTotalCount=Count(Id)From #CombineExam
	--Select @lIdCount
	DECLARE @ExamName nvarchar(150)
	--Select @lIdCount,@lTotalCount
	WHILE (@lIdCount <= @lTotalCount)
	
	BEGIN
	--DECLARE @ExamName nvarchar(150)
		select @lExamId = ExamID from #CombineExam Where Id = @lIdCount 
		Select @ExamName=DisplayTitle from [sAssessment].[tExamMaster] Where Id=@lExamId
		
			IF(@lIdCount=1)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam1Name = ' +''''+  @ExamName  +''''
					

					set @query2 ='update T set					 
						ComExam1Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId) 
						
						set @query3 ='update T set					 
						ComExam1Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)  


				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=2)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam2Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam2Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)

						set @query3 ='update T set					 
						ComExam2Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=3)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam3Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam3Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)

						set @query3 ='update T set					 
						ComExam3Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=4)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam4Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam4Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)

						set @query3 ='update T set					 
						ComExam4Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=5)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam5Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam5Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)

						set @query3 ='update T set					 
						ComExam5Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=6)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam6Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam6Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)

					set @query3 ='update T set					 
						ComExam6Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=7)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam7Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam7Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)

					set @query3 ='update T set					 
						ComExam7Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
				
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=8)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam8Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam8Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)

					set @query3 ='update T set					 
						ComExam8Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=9)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam9Name = ' +''''+  @ExamName  +''''

					set @query2 ='update T set					 
						ComExam9Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)

					set @query3 ='update T set					 
						ComExam9Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=10)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam10Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam10Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)

					set @query3 ='update T set					 
						ComExam10Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=11)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam11Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam11Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
						
					set @query3 ='update T set					 
						ComExam11Mark=RD.Obtain
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)
				
				execute(@query1)
				execute(@query2)
				execute(@query3)
			END
			IF(@lIdCount=12)
				BEGIN
				
					set @query1 ='update #TempAllExam SET 					 
						ComExam12Name = ' +''''+  @ExamName  +''''
					set @query2 ='update T set					 
						ComExam12Grade=RD.SubjectGrade
								 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lExamId)

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --          0 As TotalDaysSubjectWise,
 --          0 As PresentDaysubjectWise

		
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end

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

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		Exam1CombineExamName Nvarchar(150),

		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		Exam2CombineExamName Nvarchar(150),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		Exam3CombineExamName Nvarchar(150),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		Exam4CombineExamName Nvarchar(150),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		Exam5CombineExamName Nvarchar(150),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		Exam6CombineExamName Nvarchar(150),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		Exam7CombineExamName Nvarchar(150),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		Exam8CombineExamName Nvarchar(150),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		Exam9CombineExamName Nvarchar(150),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		Exam10CombineExamName Nvarchar(150),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		Exam11CombineExamName Nvarchar(150),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		Exam12CombineExamName Nvarchar(150),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo int,
		AdmissionDate Date
		
	)	
	 --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
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


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

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

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

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

	set @lCount = @lCount -1
	end
	

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign			
-- SELECT  AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T

 SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T

	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

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

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

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

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


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

		Select @lAnnualExamMaximum=Maximum from sAssessment.tExamDetail Where ExamId=@lExamId
	
	DECLARE @lMaxMarkStudentName nvarchar(100) = '' --start: add for mantis : 0041835

	Select TOP 1 @lMaxMarkStudentName = SM.LastName+' ' +SM.FirstName +' ' +SM.MiddleName FROM
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			INNER JOIN sStudent.tAcademic A ON A.Id=R1.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
			Where ED1.ExamId=@rExamId AND A.BatchId = @rBatchId AND A.ClassId = @rClassId AND A.DivisionId = @rDivisionId --class and Division mandatory
			ORDER BY R1.TotalObtain DESC
			--end: add for mantis : 0041835


	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			--(Select R1.TotalObtain from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS TotalMarks,
			AR.TotalObtain AS TotalMarks,
			--R.TotalMarks,
			(Select R1.Percentage from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS Percentage,
			R.TotalObtain,
			R.RankNumber,
			(Select R1.ResultGrade from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS ResultGrade,
			--R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			@lIsMarksInDecimal AS IsMarksInDecimal,
			
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			 
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
		 		 
			EM.TermScopeId,
		 
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			 
			EC.SubExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			@lDecimalFormat AS DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamNAme, 	
					 
			ARD.SubjectGrade AS AnnualSubjectGrade,
			--(Select RD1.SubjectGrade from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS AnnualSubjectGrade,
			--(Select RD1.Obtain from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS AnnualSubjectObtain,
			ARD.Obtain As AnnualSubjectObtain,
			--(Select RD1.SubjectGrade from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.TermExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS TermSubjectGrade,
			--TRD.SubjectGrade AS TermSubjectGrade,		--mantis: 39828, comment this and add new function
			[sAssessment].[fSubjectGradeGet](A.Id, EC.TermExamId, CS.Id) AS TermSubjectGrade,		--mantis: 39828, comment above line and add new function
			--(Select RD1.Obtain from 
			--sAssessment.tResultDetail RD1
			--INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			--INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			--Where ED1.ExamId=EC.TermExamId AND ED1.ClassSubjectId=CS.Id 
			--AND R1.AcademicId=R.AcademicId
			--)AS TermSubjectObtain,
			--TRD.Obtain AS TermSubjectObtain,		--mantis: 39828, comment this and add new function
			[sAssessment].[fSubjectObtainGet](A.Id, EC.TermExamId, CS.Id) AS TermSubjectObtain,		--mantis: 39828, comment above line and add new function
			EC.TermExamId,
			RD.Id,
			RD.SubjectGrade AS SubjectGrade,
			ISNULL(ARD.Remark,'')  AS Remark,
			SF.FatherName,
			SF.MotherName,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			--R.TotalMarks AS TotalMark,
			R.TotalObtain,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.TermExamId AND CS.Id=Exd.ClassSubjectId
			)AS TermMaximum,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.AnnualExamId AND CS.Id=Exd.ClassSubjectId
			)AS AnnualMaximum,
			(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
			CS.Id,
			--(Select R.TotalMarks From sAssessment.tResult)
			--@lAnnualExamMaximum AS AnnualMaximum, ROW_NUMBER() OVER (
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			RD.AbsentRemark,
			--mantis start : 37158 
			AR.ResultIndicator as ResultIndicator, 
			EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName
			--mantis End : 37158
			--start mantis : 0041835
			,AR.TotalMarks AS FinalTotalMarks
			,@lMaxMarkStudentName AS MaxMarkStudentName 
			--end mantis : 0041835									
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.TermExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id AND ACS.Id= CS.Id
			--AND ACS.SubjectId = @rSubjectId  
			--mantis: 39828, comment the below 4 inner joins and add the 2 new functions fSubjectGradeGet and fSubjectObtainGet
			--INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.TermExamId 
			--INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			--INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			--INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id AND TCS.Id= CS.Id
			--AND TCS.SubjectId = @rSubjectId 
			
			
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
		    LEFT JOIN
			(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT ON RT.SourceId = StuM.Id 
		
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.AnnualExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
			LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId AND  ISNULL(EMP.IsOtherUser,0) = 0 --added by dhananjay for mantis - 37158
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		--AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))Total Marks
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		--order by A.RollNo,CS.OrderIndex 
		
	 drop table #TempExam
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultListFloatingSubCombineExam]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rIsShowWithDetail bit =0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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

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


CREATE TABLE #TempExam
(
	SubCombineExamId int, 
	ExamOrderIndex int,
	CombineExamId int,
	AnnualExamId int, 
	Exam nvarchar(50) 
)


INSERT INTO #TempExam
(
	 SubCombineExamId,
	 ExamOrderIndex,
	 CombineExamId,
	 AnnualExamId,
	 Exam 
	
)
 
SELECT	EM.Id AS SubCombineExamId,
		EC.ExamOrder,
		EC.ExamId AS CombineExamId,
		@rExamId AS AnnualExamId,
		ESGM.Code AS Exam
FROM [sAssessment].[tExamMaster] EM 
		INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (select SubExamId 
							  from sAssessment.tExamCombine 
							  where examid=@rExamId) AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId
		--INNER JOIN sAssessment.tExamCombine EC1 ON EC1.SubExamId=EM.Id AND EC1.ExamId =@rExamId
  --WHERE (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId


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

INSERT INTO #TempCombineExam
(
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam
)

SELECT EC.ExamOrder,
EM.Id AS TermExamId,
@rExamId AS AnnualExamId,
ESGM.Code AS Exam
  FROM [sAssessment].[tExamMaster] EM 
		INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

	
	--Select * from #TempExam

		Declare @lAnnualExamMaximum int,@lExamId int
		Select @lExamId= AnnualExamId FROM #TempExam 

		Select @lAnnualExamMaximum=Maximum from sAssessment.tExamDetail Where ExamId=@lExamId
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			(Select R1.TotalObtain from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS TotalMarks,
			(Select R1.Percentage from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS Percentage,
			R.TotalObtain,
			R.RankNumber,
			(Select R1.ResultGrade from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			@lIsMarksInDecimal AS IsMarksInDecimal,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			EM.TermScopeId,
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			EC.SubCombineExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			@lDecimalFormat AS DecimalFormat,
			EC.CombineExamId,
			EC.Exam AS ExamNAme,
			ARD.SubjectGrade AS AnnualSubjectGrade,
			ARD.Obtain As AnnualSubjectObtain,
			TRD.SubjectGrade AS TermSubjectGrade,
			TRD.Obtain AS TermSubjectObtain,
			RD.SubjectGrade AS SubjectGrade,
			ISNULL(ARD.Remark,'')  AS Remark,
			SF.FatherName,
			SF.MotherName,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			R.TotalObtain,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.CombineExamId AND CS.Id=Exd.ClassSubjectId
			)AS TermMaximum,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.AnnualExamId AND CS.Id=Exd.ClassSubjectId
			)AS AnnualMaximum,
			(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END) AS Gender,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			RD.AbsentRemark
			,TCE.Exam AS CombineExamName
						
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.SubCombineExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id AND ACS.Id= CS.Id
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.SubCombineExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id AND TCS.Id= CS.Id
			
			
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
		    LEFT JOIN
			(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT ON RT.SourceId = StuM.Id 

			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.AnnualExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
			LEFT JOIN #TempCombineExam TCE ON TCE.TermExamId = EC.CombineExamId
			
	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 ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		
	 drop table #TempExam

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

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rDepartmentid int=0,
	 @rStatus int =1,
	 @rGenderId int,
	 @rClassStatusId int=0,
	 @rResultStatus nvarchar(20)='',
	 @rMultiCode nvarchar(max)='',
	 @rOrderBy int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
			CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
			CONVERT (nvarchar(20),@rBatchId) AS BatchIdText,
			CONVERT(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0))AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			EM.IsMarksInDecimal,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
				ELSE NULL END)AS StudentPhoto,
			EM.DisplayTitle,
			OM.SmallAddress1,
			R.ResultRemark,
			R.OtherRemark1,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			SR.ResultRemark2,
			EM.GradeSetId,
			R.ResultStatus,
			SR.ResultRemark1,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			(CASE EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
				ELSE NULL END ) AS EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			EM.DecimalFormat,
			CM.Id AS ClassId,
			@rOrderBy AS OrderBy,
			CONVERT(bit,@DecimalConfigId) AS IsDecimal
      
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=A.Id AND SR.ExamId = EM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			
			 
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (EM.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((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 ((SM.Code=@rCode) OR (@rCode=''))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		ANd ((SM.StatusId= @rStatus) OR (@rStatus = 0))
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND (ISNULL(SM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

		ORDER BY 
			CASE @rOrderBy WHEN 0 THEN SM.Code END , 
			CASE @rOrderBy WHEN 1 THEN R.RankNumber END , 
			CASE @rOrderBy WHEN 2 THEN A.RollNo END, 
			CASE @rOrderBy WHEN 3 THEN SM.FirstName END,
			CASE @rOrderBy WHEN 4 THEN R.TotalObtain END
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultListSubjectWiseConsolidatedGet]
	 
	 @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)='',
	 @rFromObtainExam decimal(5,2)=0,
	 @rToObtainExam decimal(5,2)=0
	
	 --,@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(200),
		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
		--Mantis End - 0032150

		)
	 --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
	)
	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
				
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 sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId 

= AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId        --Mantis 0030303
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=StuM.AdmissionCategoryId	--Mantis - 0031091
	 
	 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							
					 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 --Mantis - 0032150
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lCombineExamId) 
				
				--Print @query		
		execute(@query)
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum,
					 AbsentRemarkTerm1 = RD. AbsentRemark,
					 IsPresentTerm1 = RD.IsPresent
					 							 
					 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)
				
		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
									 
					 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)  
		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			 
					 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)
		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, @rFromObtainExam as FromObtainExam ,@rToObtainExam as ToObtainExam,
	T.*
	FROM #TempAllExam T 
	WHERE ((Obtain1 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain1 <= @rToObtainExam OR @rToObtainExam =0)) OR 
		  ((Obtain2 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain2 <= @rToObtainExam OR @rToObtainExam =0)) OR
		  ((Obtain3 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain3 <= @rToObtainExam OR @rToObtainExam =0)) OR
		  ((Obtain4 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain4 <= @rToObtainExam OR @rToObtainExam =0)) OR
		  ((Obtain5 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain5 <= @rToObtainExam OR @rToObtainExam =0)) OR
	      ((Obtain6 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain6 <= @rToObtainExam OR @rToObtainExam =0)) OR
	      ((Obtain7 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain7 <= @rToObtainExam OR @rToObtainExam =0)) OR 
		  ((Obtain8 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain8 <= @rToObtainExam OR @rToObtainExam =0)) OR
		  ((Obtain9 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain9 <= @rToObtainExam OR @rToObtainExam =0)) OR
		  ((Obtain10 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain10 <= @rToObtainExam OR @rToObtainExam =0)) OR
		  ((Obtain11 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain11 <= @rToObtainExam OR @rToObtainExam =0)) OR
		  ((Obtain12 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain12 <= @rToObtainExam OR @rToObtainExam =0)) OR
		  ((Obtain13 >= @rFromObtainExam OR @rFromObtainExam =0) AND (Obtain13 <= @rToObtainExam OR @rToObtainExam =0))
		 
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--SELECT * FROM #TempAllExam	
	drop table #tempcombineExam
	Drop table #TempAllExam
	
	--Select
	--	'' As Builder1,
	--	'' As Builder2,
	--    '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
	--	'' As IsDisplayMonthlyAttendanceText,
	--    '' AS ClassIdText,
	--	0 As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	0 As TotalMark ,
	--	0 As TotalObtain,
	--	0 As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
 --       '' As IsMarksInDecimal,
 --    0 As column_visible,

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign ,	
 --			'' As FatherOccupation ,
 --			0 AS IsDecimal,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm1,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm2,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm3

-- SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, @rFromObtainExam AS FromObtainExam, @rToObtainExam AS ToObtainExam, T.* FROM sAssessment.tTempAllExam T
 
	END
--	SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, @rFromObtainExam AS FromObtainExam, @rToObtainExam AS ToObtainExam, T.* FROM sAssessment.tTempAllExam T
	
--end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetCCEMultiExamGet]
	 
	 @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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

 --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam

 
  
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(150),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		IsDisplayParentName bit,
		FatherName nvarchar(30),
		MotherName nvarchar(30),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) 
		 
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch 
	
 
 
	 
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		SI.StudentPhoto,
		@GradeString AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    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,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		EI.EmployeeSign,
		BM.Title AS Batch 
		
		
		 
			
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN 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
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		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.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		 
	 
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--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)+'=RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	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
							 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code					 
					 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 = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade					 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From
						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
	
	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
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

--end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticGradeSub]
	 
	@rExamId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		Convert(nvarchar(10),@rExamId) AS ExamIdText,
		EM.Id AS ExamId,
		EM.DisplayTitle As ExamTitle,
		GSD.MinimumScore AS MiniMumScore,
		GSD.GradeCode AS GradeCode,
		GSD.GradeTitle As GradeTitle,
		GSD.GradePoint As GradePoint,
		GSD.MarkRange As MarkRange,
		isnull(T.GradeCount,0) AS GradeCount ,
		GSD.GradeSetId
	FROM 
		sAssessment.tExamMaster EM
		INNER JOIN sAssessment.tGradeSetDetail GSD ON EM.CoScholasticGradeSetId=GSD.GradeSetId
		LEFT JOIN (SELECT EM.ID AS ExamId, COUNT (GSD.GradeSetId) AS GradeCount FROM sAssessment.tExamMaster EM
		INNER JOIN sAssessment.tGradeSetDetail GSD ON EM.CoScholasticGradeSetId=GSD.GradeSetId 
		Where EM.Id = @rExamId GROUP BY EM.Id )T ON T.ExamId =EM.Id 
	Where 
		EM.Id = @rExamId 
	order by 
		GSD.MinimumScore desc
	End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticRemarkSubGet]
	 
	 @rExamId int,
	 @rAcedamicId bigint=0
   
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 BEGIN
SELECT 
    Convert(nvarchar(20),SA.AcademicId) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
    RD.Remark,
    SA.AcademicId,
    V.SubjectName AS SubjectName,
    V.SubjectCode AS SubjectCode,
    ED.ClassSubjectId AS ClassSubjectId
  
FROM 
	 sStudent.vStudentAcademic SA 
	INNER JOIN sAssessment.tResult R ON R.ExamId=@rExamId AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=@rExamId 
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	INNER JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	--LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId
	 
	 WHERE  
	 ((SA.AcademicId=@rAcedamicId) OR (@rAcedamicId=0))
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubCombineGet]
	 
	 

	 --@rAcademicIdTextText bigint,
	 --@rExamIdTextText bigint
	  @rAcademicId bigint,
	 @rExamId bigint ,
	 @rCoScholasticScopeId int=0,
	 @rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--DECLARE
--@rAcademicIdText bigint,
--@rExamIdText int
--SET @rAcademicIdText = convert(bigint, @rAcademicIdTextText)
--SET @rExamIdText = convert(bigint, @rExamIdTextText)
DECLARE
@lIsCoScholasticGrade	bit,
@lIsCoScholasticGradeIndicator bit, 
@lIsCoScholasticGradeDesIndicator bit,
@lIsCoScholasticCombine bit	 	 

--@lCoScholasticScopeId tinyint

SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator,
@lIsCoScholasticCombine = IsCoScholasticCombine 
FROM sAssessment.tExamMaster WHERE Id = @rExamId
 

DECLARE 
@Exam1 int,
@Exam2 int,
@Exam3 int


--@Grade2 nvarchar(50),
--@GradeIndicator1 nvarchar(50),
--@Grade2 nvarchar(50),
--@CategoryID int,
--@BrandID int



 
SELECT @Exam1 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 1
SELECT @Exam2 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 2
SELECT @Exam3 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 3

SELECT
Convert(nvarchar(10),@rExamId) AS ExamIdText,
Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,
  
Convert(nvarchar(20),@rBatchId) AS   BatchIdText,
@rAcademicId AS AcademicId,
--(CASE Term1.AcademicId  WHEN  null THEN Convert(nvarchar(10),Term2.AcademicId)
--ELSE Convert(nvarchar(10),Term1.AcademicId) END) AS   AcademicIdText,
@rExamId AS ExamId, 
Convert(nvarchar(20), @rCoScholasticScopeId ) AS CoScholasticScopeIdText,

--(CASE Term1.AcademicId  WHEN  null THEN Term2.AcademicId
--ELSE Term1.AcademicId END) AS   AcademicId ,
(CASE Term1.CoSubject  WHEN  null THEN Term2.CoSubject
ELSE Term1.CoSubject END) AS   CoSubject ,
(CASE Term1.CoSubjectGroup  WHEN  null THEN Term2.CoSubjectGroup
ELSE Term1.CoSubjectGroup END) AS   CoSubjectGroup ,
(CASE Term1.CoSubjectGroupOrder  WHEN  null THEN Term2.CoSubjectGroupOrder
ELSE Term1.CoSubjectGroupOrder END) AS   CoSubjectGroupOrder ,
(CASE Term1.CoSubjectOrder  WHEN  null THEN Term2.CoSubjectOrder
ELSE Term1.CoSubjectOrder END) AS   CoSubjectOrder , 
ISNULL(Term1.Grade,'') AS Grade1,
ISNULL(Term1.GradeIndicator,'') AS GradeIndicator1,
ISNULL(Term1.DescriptiveIndicator,'') AS DescriptiveIndicator1,
ISNULL(Term2.Grade,'') AS Grade2,
ISNULL(Term2.GradeIndicator,'') AS GradeIndicator2,
ISNULL(Term2.DescriptiveIndicator,'') AS DescriptiveIndicator2,
ISNULL(Term3.Grade,'') AS Grade3,
ISNULL(Term3.GradeIndicator,'') AS GradeIndicator3,
ISNULL(Term3.DescriptiveIndicator,'') AS DescriptiveIndicator3,
@lIsCoScholasticGrade AS IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
ISNULL(Term1.GroupTypeId,0) AS GroupTypeId,
ISNULL(Term1.GroupType,0) AS GroupType ,

ISNULL(Term1.ExamName,'') AS ExamTerm1,
ISNULL(Term2.ExamName,'') AS ExamTerm2,
ISNULL(Term3.ExamName,'') AS ExamTerm3,
Term1.CoScholasticTitle AS CoScholasticTitle


 

FROM 

	(
	SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType ,
			 ESM.Title AS ExamName,
			 EM.CoScholasticTitle 
			
	FROM 
			sAssessment.tCCECSExamScore cceCSS	
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
			INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId	-- #Start MantisId : 0031752
			LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId				-- #End MantisId : 0031752

	WHERE 
		     cceCSS.ExamId=@Exam1		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId
			 AND (FC.IsOptional = 0 OR (FC.IsOptional = 1 AND OCS.AcademicId IS NOT NULL))			-- MantisId : 0031752
			 	) Term1
		     
		     FULL OUTER JOIN

		 	(
			SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			ESM.Title AS ExamName 
			 --EM.CoScholasticTitle 
			
			 
			
			
			    
	FROM 
			sAssessment.tCCECSExamScore cceCSS		 
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
			INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId		-- #Start MantisId : 0031752
			LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId					-- #End MantisId : 0031752
	WHERE 
		     cceCSS.ExamId=@Exam2		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId	
			 AND (FC.IsOptional = 0 OR (FC.IsOptional = 1 AND OCS.AcademicId IS NOT NULL))					-- MantisId : 0031752
			 ) Term2
		     ON Term1.CoSubjectId = Term2.CoSubjectId    
		     
		     
			FULL OUTER JOIN

		 	(
			SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			ESM.Title AS ExamName 
			 --EM.CoScholasticTitle 	
			    
	FROM 
			sAssessment.tCCECSExamScore cceCSS		 
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
			INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId				-- #Start MantisId : 0031752
			LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId							-- #End MantisId : 0031752
	WHERE 
		     cceCSS.ExamId=@Exam3		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId
			 AND (FC.IsOptional = 0 OR (FC.IsOptional = 1 AND OCS.AcademicId IS NOT NULL))				-- MantisId : 0031752
			 	) Term3
		     ON Term1.CoSubjectId = Term3.CoSubjectId    

		     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubCombineNewGet]
	
	@rAcademicId bigint,
	@rExamId bigint ,
	@rCoScholasticScopeId int=0,
	@rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE
	@lIsCoScholasticGrade	bit,
	@lIsCoScholasticGradeIndicator bit, 
	@lIsCoScholasticGradeDesIndicator bit,
	@lIsCoScholasticCombine bit,
	@lCoScholasticTitle nvarchar(150)	 	 


	SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
	@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
	@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator,
	@lIsCoScholasticCombine = IsCoScholasticCombine,
	@lCoScholasticTitle = CoScholasticTitle
	FROM sAssessment.tExamMaster WHERE Id = @rExamId
 
	IF OBJECT_ID('tempdb..#CoScholasticTempTable') IS NOT NULL
		BEGIN
			DROP TABLE #CoScholasticTempTable;
		END

	IF OBJECT_ID('tempdb..#SubExamIdTemp') IS NOT NULL
		BEGIN
			DROP TABLE #SubExamIdTemp;
		END

	CREATE TABLE #SubExamIdTemp
	(
		Id int Identity(1,1),
		ExamId int,
		SubExamId int
	)

	INSERT INTO #SubExamIdTemp
	(ExamId, SubExamId)
		SELECT @rExamId, SubExamId FROM sAssessment.tExamCombine
		WHERE ExamId = @rExamId Order by ExamOrder


	CREATE TABLE #CoScholasticTempTable(
	ExamIdText nvarchar(20),
	AcademicIdText nvarchar(20),
	BatchIdText nvarchar(20),
	AcademicId BigInt,
	ExamId Int,
	CCECSId Int,
	CoScholasticScopeIdText nvarchar(20),
	CoSubject nvarchar(100),
	CoSubjectGroup nvarchar(100),
	CoSubjectGroupOrder SmallInt,
	CoSubjectOrder SmallInt,
	ExamTerm1 nvarchar(100),
	ExamTerm2 nvarchar(100),
	ExamTerm3 nvarchar(100),
	ExamTerm4 nvarchar(100),
	Grade1 nvarchar(10),
	Grade2 nvarchar(10),
	Grade3 nvarchar(10),
	Grade4 nvarchar(10),
	GradeIndicator1 nvarchar(50),
	GradeIndicator2 nvarchar(50),
	GradeIndicator3 nvarchar(50),
	GradeIndicator4 nvarchar(50),
	DescriptiveIndicator1 nvarchar(max),
	DescriptiveIndicator2 nvarchar(max),
	DescriptiveIndicator3 nvarchar(max),
	DescriptiveIndicator4 nvarchar(max),
	IsCoScholasticGrade bit,
	IsCoScholasticGradeIndicator bit,
	IsCoScholasticGradeDesIndicator bit,
	GroupTypeId tinyInt,
	GroupType nvarchar(100),
	ExamTerm nvarchar(100),
	CoScholasticTitle nvarchar(150)
	)

	INSERT INTO #CoScholasticTempTable
	(
	ExamIdText,
	AcademicIdText,
	BatchIdText,
	AcademicId,
	ExamId,
	CCECSId,
	CoSubject,
	CoSubjectGroup,
	CoSubjectGroupOrder,
	CoSubjectOrder,
	CoScholasticScopeIdText,
	IsCoScholasticGrade,
	IsCoScholasticGradeIndicator,
	IsCoScholasticGradeDesIndicator,
	CoScholasticTitle,
	GroupTypeId,
	GroupType
	)

	SELECT
		DISTINCT
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,
		Convert(nvarchar(20),@rBatchId) AS   BatchIdText,
		@rAcademicId AS AcademicId,
		@rExamId AS ExamId,
		cceCSM.Id AS CCECSId,
		cceCSM.Title AS CoSubject,
		cceCSGM.Title AS CoSubjectGroup,
		cceCSGM.OrderIndex AS CoSubjectGroupOrder,
		cceCSM.OrderIndex AS CoSubjectOrder,
		Convert(nvarchar(20), @rCoScholasticScopeId ) AS CoScholasticScopeIdText,
		@lIsCoScholasticGrade AS IsCoScholasticGrade,
		@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
		@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
		ISNULL(@lCoScholasticTitle,'') AS CoScholasticTitle,
		cceCST.Id AS GroupTypeId,
		cceCST.Title AS GroupType
	FROM 
		sAssessment.tCCECSExamScore cceCSS		 
		INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
		INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
		INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
		INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
		INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
		INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
		INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId
		LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId	
	WHERE
		cceCSS.ExamId IN (SELECT SubExamId FROM #SubExamIdTemp)     
		AND cceCSS.AcademicId=@rAcademicId
		AND CCC.BatchID=@rBatchId
		AND (FC.IsOptional = 0 OR (FC.IsOptional = 1 AND OCS.AcademicId IS NOT NULL))

	--SELECT * FROM #CoScholasticTempTable

	DECLARE @lCount SmallInt, @query NVarchar(Max), @lSubExamId Int
	SELECT @lCount = MAX(Id) FROM #SubExamIdTemp
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lSubExamId = SubExamId FROM #SubExamIdTemp WHERE Id = @lCount

		SET @query ='update T SET
		Grade'  + convert(nvarchar(15),@lCount)+ '= cceCSS.Grade,
		GradeIndicator'  + convert(nvarchar(15),@lCount)+ '= cceCSS.GradeIndicator,
		DescriptiveIndicator'  + convert(nvarchar(15),@lCount)+ '= cceCSS.DescriptiveIndicator,
		ExamTerm'  + convert(nvarchar(15),@lCount)+ '= ESM.Title
		FROM 
		sAssessment.tCCECSExamScore cceCSS	
		INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
		INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
		INNER JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
		INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
		INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
		INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
		INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId =' + convert(nvarchar(15),@rBatchId)+ '
		LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId
		INNER JOIN #CoScholasticTempTable T ON T.AcademicId = A.Id AND cceCSS.CCECSId = T.CCECSId 

		WHERE		     
		cceCSS.AcademicId=' + convert(nvarchar(20),@rAcademicId) + '
		AND CCC.BatchID=' + convert(nvarchar(15),@rBatchId)+ '
		AND (FC.IsOptional = 0 OR (FC.IsOptional = 1 AND OCS.AcademicId IS NOT NULL))
		AND ISNULL(cceCSS.ExamId,0) ='  + convert(nvarchar(15), @lSubExamId)
		EXECUTE (@query)
		--PRINT @query

		SET @lCount = @lCount - 1
	END

	SELECT * FROM #CoScholasticTempTable


	--For SP Drag and Drop in Dataset
	--SELECT
	--'' AS ExamIdText,
	--'' AS AcademicIdText,
	--'' AS BatchIdText,
	--Convert(BigInt,0) AS AcademicId,
	--0 AS ExamId,
	--'' AS CoScholasticScopeIdText,
	--'' AS CoSubject,
	--'' AS CoSubjectGroup,
	--0 AS CoSubjectGroupOrder,
	--0 AS CoSubjectOrder,
	--'' AS ExamTerm1,
	--'' AS ExamTerm2,
	--'' AS ExamTerm3,
	--'' AS ExamTerm4,
	--'' AS Grade1,
	--'' AS Grade2,
	--'' AS Grade3,
	--'' AS Grade4,
	--'' AS GradeIndicator1,
	--'' AS GradeIndicator2,
	--'' AS GradeIndicator3,
	--'' AS GradeIndicator4,
	--'' AS DescriptiveIndicator1,
	--'' AS DescriptiveIndicator2,
	--'' AS DescriptiveIndicator3,
	--'' AS DescriptiveIndicator4,
	--Convert(bit,0) AS IsCoScholasticGrade,
	--Convert(bit,0) AS IsCoScholasticGradeIndicator,
	--Convert(bit,0) AS IsCoScholasticGradeDesIndicator,
	--Convert(tinyInt,0) AS GroupTypeId,
	--'' AS GroupType,
	--'' AS ExamTerm,
	--'' AS CoScholasticTitle

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubSingleGet]
	 --@rExamId int,
	 --@rAcademicId bigint
	 @rAcademicId bigint,
	 @rExamId bigint ,
	 @rCoScholasticScopeId int=0,
	 @rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

DECLARE @lIsCoScholasticGrade	bit,@lIsCoScholasticGradeIndicator bit, @lIsCoScholasticGradeDesIndicator bit  
 
 
SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator  
 
FROM sAssessment.tExamMaster WHERE Id = @rExamId --and coscholasticscopeid=@rCoScholasticScopeId
	SELECT		
			 
			Convert(nvarchar(10),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,	
			Convert(nvarchar(20),@rCoScholasticScopeId) AS   CoScholasticScopeIdText,	
			Convert(nvarchar(20),@rBatchId) AS   BatchIdText,	
		 
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.OrderIndex AS CoSujbectOrderIndex,
			cceCSGM.OrderIndex AS CoSubjectGroupOrderIndex,
			@lIsCoScholasticGrade AS IsCoScholasticGrade,
			@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
			@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
			cceCSGM.CCECSGroupTypeId,
			cceCSGM.Code,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			EM.CoScholasticTitle,
			cceCSS.ConvertedMark,
			cceCSS.ObtianMark,
			cceCSM.OrderIndex,
			CASE WHEN cceCSGM.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			FC.TotalMark
			
	FROM 
			sAssessment.tCCECSExamScore cceCSS		
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamId
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId			 
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id
			INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId
			 
	WHERE 
		     cceCSS.ExamId=@rExamId
		     AND cceCSS.AcademicId=@rAcademicId	
		     AND CCC.BatchID=@rBatchId
		     AND FC.IsOptional = 0
		      
	UNION ALL
	
		SELECT		
			 
			Convert(nvarchar(10),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,	
			Convert(nvarchar(20),@rCoScholasticScopeId) AS   CoScholasticScopeIdText,	
			Convert(nvarchar(20),@rBatchId) AS   BatchIdText,	
		 
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.OrderIndex AS CoSujbectOrderIndex,
			cceCSGM.OrderIndex AS CoSubjectGroupOrderIndex,
			@lIsCoScholasticGrade AS IsCoScholasticGrade,
			@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
			@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
			cceCSGM.CCECSGroupTypeId,
			cceCSGM.Code,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			EM.CoScholasticTitle,
			cceCSS.ConvertedMark,
			cceCSS.ObtianMark,
			cceCSM.OrderIndex,
			CASE WHEN cceCSGM.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			FC.TotalMark
	FROM 
			sAssessment.tCCECSExamScore cceCSS		
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamId
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId			 
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
			INNER JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId
	WHERE 
		     cceCSS.ExamId=@rExamId
		     AND cceCSS.AcademicId=@rAcademicId	
		     AND CCC.BatchID=@rBatchId 
		     AND FC.IsOptional = 1 
		      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetFloating]
	 
	 @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,
	 @rClassStatusId int=0 ,
	 @rMultiCode nvarchar(max)=''

	
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 --Select * from dbo.Float
DECLARE @GradeString nvarchar(1000),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

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

CREATE TABLE #TempExam
(
	ExamId int, 
	ExamOrderIndex int 
)
INSERT INTO #TempExam
(
	ExamId,	 
	ExamOrderIndex
)
Select 
	--EC.ExamId,
	EC.SubExamId,
	EC.ExamOrder 	 
	from sAssessment.tExamMaster EM 
	INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId = EM.Id 
	WHERE EM.Id=@rExamId 
	
INSERT INTO #TempExam
(
	ExamId,
	--SubExamId,
	ExamOrderIndex
)
Select 
	--EC.ExamId,
	@rExamId,
	999
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			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,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			--ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			SR.StudentHeight,
			SR.StudentWeight,		
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
			ELSE NULL END) AS StudentPhoto,
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			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,
			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,
			 
			EC.ExamId,
			EC.ExamOrderIndex,
			EM.DecimalFormat,
			SM.Code,
			CONVERT(bit,@DecimalConfigId) AS IsDecimal
			
			--[sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId) AS HighestDivisionMark,
			--[sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId) AS HighestDivisionGrade
			
			
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.ExamId = EM.Id 	
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sSetup.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 sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND (R.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(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		order by A.RollNo,CS.OrderIndex 
		 drop table #TempExam
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetGradeSub]
	 
	@rExamId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		Convert(nvarchar(10),@rExamId) AS ExamIdText,
		EM.Id AS ExamId,
		EM.DisplayTitle As ExamTitle,
		GSD.MinimumScore AS MiniMumScore,
		GSD.GradeCode AS GradeCode,
		GSD.GradeTitle As GradeTitle,
		GSD.GradePoint As GradePoint,
		GSD.MarkRange As MarkRange,
		isnull(T.GradeCount,0) AS GradeCount ,
		GSD.GradeSetId
	FROM 
		sAssessment.tExamMaster EM
		INNER JOIN sAssessment.tGradeSetDetail GSD ON EM.GradeSetId=GSD.GradeSetId
		LEFT JOIN (SELECT EM.ID AS ExamId, COUNT (GSD.GradeSetId) AS GradeCount FROM sAssessment.tExamMaster EM
		INNER JOIN sAssessment.tGradeSetDetail GSD ON EM.GradeSetId=GSD.GradeSetId 
		Where EM.Id = @rExamId GROUP BY EM.Id )T ON T.ExamId =EM.Id 
	Where 
		EM.Id = @rExamId 
	order by 
		GSD.MinimumScore desc
	End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetGSEB10MultiExamGet]
	 
	 @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
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

 --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam

 
  
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),	
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	

		MaximumMark10 decimal(8,2),	
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	

		MaximumMark11 decimal(8,2),	
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(150),
		Remark2 nvarchar(150),
		Remark3 nvarchar(150),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		Exam9Name nvarchar(150),
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),

		Exam10Name nvarchar(150),
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),

		Exam11Name nvarchar(150),
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		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,
		IsDisplayParentName bit,
		FatherName nvarchar(30),
		MotherName nvarchar(30),
		IsShowSubjectMark bit, 
		SubjectGroupTypeId smallint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit
		 
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam
	(
	AcademicIdText,
	ExamIdText,
	
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark ,
	SubjectGroupTypeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	MarksheetHeaderA4,
	IsImageHeader
 
 
	 
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
 
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		SI.StudentPhoto,
		@GradeString AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    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,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		CASE WHEN CS.IsOptional =0 AND CS.IsPractical=0 THEN 1 
			WHEN CS.IsOptional = 1 AND CS.IsPractical = 0 THEN 2
			WHEN CS.IsPractical = 1 THEN 4
		            
         END as SubjectGroupTypeId  	,
         		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		EI.EmployeeSign,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader			
		--EMP.FirstName
		
		 
			
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN 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
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		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) ) 
		 
	 
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--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)+'=RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	-- Print @query
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
	--	 Print @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
							 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus				 
					 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 = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade					 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set					 
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus		
					 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
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

--end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetNCRTExamGet]
	 
	 @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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 

  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam

 Declare @lLinkExamId int
 Select @lLinkExamId = LinkExamId From sAssessment.tExamMaster Where ClassId=@rClassID AND Id=@rExamId ANd BatchId=@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 = @lLinkExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

 

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(300),
		RollNo int,
		ResultStatus Nvarchar(50),	
		ClassName NVarchar(100),		
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
			MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2),
		ExamMaximum12 decimal(8,2),
		IsPresent12 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(100),
		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(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(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(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(100),
		SubjectGroupCode nvarchar(20),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		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(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2)
	)	
	 --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,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
   IsShowWithDetail,
 IsPresent,
 GradeTitle,
	
	 SubjectHighestDivisionGrade,
	 SubjectHighestDivisionMark
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@lLinkExamId),
		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,
		@lLinkExamId,
		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,
		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,
		@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),
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark 
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.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
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.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 sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @lLinkExamId 
		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.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		 AND  ISNULL(EMP.IsOtherUser,0) = 0
	 
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @lLinkExamId 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  = @lLinkExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--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)+'=RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					  TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @lLinkExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code					 
					 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  = @lLinkExamId 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				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @lLinkExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

  --end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetOnlyCoScholasticCombineGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20),
	 @rStatusId int,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
 
 --select * from  dbo.tTempCoScholasticCombine
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int, 
@Exam1 int,
@Exam2 int

SELECT @Exam1 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 1
SELECT @Exam2 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 2
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

DECLARE @lOrgId int=0
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
DECLARE @DecimalConfidId nvarchar(20)=''
SELECT @DecimalConfidId =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId
 
 	CREATE TABLE #TempExam 
	(
		AcademicId bigint,
		ExamId int,
		CCECSId int,
		CCECSGroupId int,
		CoSubject nvarchar(150),
		CoSubjectGroup nvarchar(150),
		CoSubjectOrderIndex int,
		CoSubjectGroupOrderIndex int,
		Grade1 nvarchar(10) NULL,
		GradeIndicator1 nvarchar(50) NULL,
		DescriptiveIndicator1 nvarchar(200) NULL,
		Grade2 nvarchar(10) NULL,
		GradeIndicator2 nvarchar(50) NULL,
		DescriptiveIndicator2 nvarchar(200) NULL
	 )
	 
 

 INSERT INTO  #TempExam 
	(
	AcademicId,
	ExamId,
	CCECSId,
	CCECSGroupId,
	CoSubject,
	CoSubjectGroup,
	CoSubjectOrderIndex,
	CoSubjectGroupOrderIndex
	
	)
 SELECT A.Id,@rExamId,CS.Id,CS.CCECAGroupId,CS.Title,csg.Title,CS.OrderIndex,CSG.OrderIndex 
 FROM sStudent.tAcademic A INNER JOIN
 sAssessment.tCCECSClass C ON A.ClassId = C.ClassId  
 INNER JOIN sAssessment.tCCECSMaster CS ON C.CCECSGroupId = cs.CCECAGroupId
 INNER JOIN sAssessment.tCCECSGroupMaster CSG ON CS.CCECAGroupId = CSG.Id 
 WHERE DivisionId = @rDivisionId
 AND A.BatchId = @rBatchId
 
UPDATE
    TE
SET
    TE.Grade1 = ES.Grade,
    TE.GradeIndicator1 = ES.GradeIndicator,
    TE.DescriptiveIndicator1 = ES.DescriptiveIndicator
FROM
    #TempExam TE
    INNER JOIN sAssessment.tCCECSExamScore ES
    ON TE.AcademicId = ES.AcademicId AND   
    TE.CCECSId = ES.CCECSId
    AND ES.ExamId = @Exam1
    
  UPDATE
    TE
SET
    TE.Grade2 = ES.Grade,
    TE.GradeIndicator2 = ES.GradeIndicator,
    TE.DescriptiveIndicator2 = ES.DescriptiveIndicator
FROM
    #TempExam TE
    INNER JOIN sAssessment.tCCECSExamScore ES
    ON TE.AcademicId = ES.AcademicId AND   
    TE.CCECSId = ES.CCECSId
    AND ES.ExamId = @Exam2

	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			TE.AcademicId,			 
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks ,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,'') AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,		 
			ISNULL(R.Id ,0) AS ResultId, 
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,	 
			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,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			TE.CoSubject,
			TE.CoSubjectGroup,
			TE.CoSubjectGroupOrderIndex,
			TE.CoSubjectOrderIndex,
			TE.Grade1,
			TE.GradeIndicator1,
			TE.DescriptiveIndicator1,
			TE.Grade2,
			TE.GradeIndicator2,
			TE.DescriptiveIndicator2,
			SF.FatherName,
			SF.MotherName,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			(CASE EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
			SR.StudentHeight,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			SR.StudentWeight,
			ISNULL(SR.MyGoal,'') AS MyGoal,
			ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
			ISNULL(SR.Responsibility,'') AS Responsibility,
			ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
			ISNULL(SR.MyStrength,'') AS MyStrength,
			ISNULL(SR.Achievements,'') AS Achievements,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
			ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
			ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
			ISNULL(SR.ImprovementArea,'') As ImprovementArea,
			ISNULL(SR.ProgressArea,'') AS ProgressArea,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			ISNULL(SR.MyActivity,'') AS MyActivity,
			ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
			ISNULL(Sr.HouseRemark,'') As HouseRemark,
			ISNULL(BGM.Title,'') AS BloodGroup,
			SR.ResultRemark3,
			SR.ResultRemark1,
			Sr.ResultRemark2,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			CONVERT(bit, @DecimalConfidId) AS IsDecimal
	FROM 
			#TempExam TE INNER JOIN 	 
			sAssessment.tExamMaster EM ON EM.Id=TE.ExamId 		 
			INNER JOIN sStudent.tAcademic A ON A.Id=TE.AcademicId
			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 sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID			 
			LEFT JOIN sAssessment.tResult R	ON TE.AcademicId = R.AcademicId AND TE.ExamId = R.ExamId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	WHERE 
			EM.BatchId = @rBatchId 
			AND (A.ClassId=@rClassId OR @rClassId=0) 
			--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
			AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
			AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
			AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))		
			AND (TE.ExamId = @rExamId)
			AND ((StuM.Code=@rCode) OR (@rCode=''))		
			AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=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 A.RollNo,TE.CoSubjectGroupOrderIndex,TE.CoSubjectOrderIndex 
			--AND A.id = 1005000000007



		--SELECT 
		--	'' AS Exam,
		--	'' AS Code,
		--	'' AS Name,
		--	0 AS RollNo,
		--	CONVERT(bigint,0) AS AcademicId,			 
		--	'' AS ResultStatus,
		--	'' AS Class,
		--	'' AS Division,
		--	CONVERT(decimal ,0) AS TotalMarks ,
		--	CONVERT(decimal ,0) AS TotalObtain,
		--	CONVERT(decimal ,0) AS Percentage,
		--	0 AS RankNumber,
		--	'' AS ResultGrade,
		--	CONVERT(decimal ,0) AS Percentile,		 
		--	CONVERT(bigint ,0) AS ResultId, 
		--	CONVERT(bit ,0)IsMarksInDecimal,
		--	--SM.OrderIndex AS SubjectCode,	 
		--	'' AS Remark1,
		--	'' AS Remark2,
		--	'' AS Remark3,
		--	'' AS DisplayTitle,
		--	CONVERT(bit ,0) AS IsRankNo, 
		--	CONVERT(bit ,0) AS IsGrade,
		--	CONVERT(bit ,0) AS IsPercentile,
		--	CONVERT(bit ,0) AS IsPercentage,
		--	CONVERT(bit ,0) AS IsSubjectPercentile,
		--	CONVERT(bit ,0) AS IsProcessResult,
			 
		--	CONVERT(bit ,0) AS IsNegativeMarks,
		--	CONVERT(bit ,0) AS IsIncludeCoScholastic,
		--	CONVERT(bit ,0) AS IsOnPrePrinted,
		--	CONVERT(bit ,0) AS IsDisplayPhoto,
		--	CONVERT(bit ,0) AS IsDisplayBirthDate,
		--	CONVERT(bit ,0) AS IsLockForEdit,
		--	CONVERT(bit ,0) AS IsDisplaySchoolName,			
		--	CONVERT(bit ,0) AS IsDisplayAttendance,
		--	CONVERT(bit ,0) AS IsDisplayHeightWeight,
		--	CONVERT(bit ,0) AS IsResultStatus,
		--	'' AS FooterAdjustmentText,
		--	'' AS DetailAdjustmentText,
		--	0 AS FooterAdjustment,
		--	0 AS DetailAdjustment,
		--	'' AS ResultRemark,
		--	CONVERT(date , null) AS DateOfBirth,
		--	CONVERT(decimal ,0) AS HeightTerm1,
		--	CONVERT(decimal ,0) AS WeightTerm1,
		--	CONVERT(decimal ,0) AS HeightTerm2,
		--	CONVERT(decimal ,0) AS WeightTerm2,
		--	CONVERT(decimal ,0) AS HeightAnnual,
		--	CONVERT(decimal ,0) AS WeightAnnual,
		--	0 AS PresentDaysTerm1,
		--	0 AS PresentDaysTerm2,
		--	0 AS PresentDaysAnnual,
		--	0 AS TotalDaysTerm1,
		--	0 AS TotalDaysTerm2,
		--	0 AS TotalDaysAnnual,
		--	CONVERT(tinyint ,0) AS TermScopeId,
		--	CONVERT(varbinary ,0) AS StudentPhoto,
		--	'' AS GradeString,
		--	CONVERT(bit ,0) AS IsDisplayGradeString,
		--	'' AS CoSubject,
		--	'' AS CoSubjectGroup,
		--	0 AS CoSubjectGroupOrderIndex,
		--	0 AS CoSubjectOrderIndex,
		--	'' AS Grade1,
		--	'' AS GradeIndicator1,
		--	'' AS DescriptiveIndicator1,
		--	'' AS Grade2,
		--	'' AS GradeIndicator2,
		--	'' AS DescriptiveIndicator2,
		--	'' AS FatherName,
		--	'' AS MotherName,
		--	CONVERT(bit ,0) AS IsDisplayPrincipalSign,
		--	CONVERT(bit ,0) AS IsDisplayTeacherSign,
		--	CONVERT(varbinary ,0) AS EmployeeSign ,
		--	CONVERT(decimal ,0) AS StudentHeight,
		--	CONVERT(decimal ,0) AS TotalDays,
		--	CONVERT(decimal ,0) AS PresentDays,
		--	CONVERT(decimal ,0) AS StudentWeight,
		--	'' AS MyGoal,
		--	'' AS AreaOfInterest,
		--	'' AS Responsibility,
		--	'' AS MyInterestHobby,
		--	'' AS MyStrength,
		--	'' AS Achievements,
		--	'' AS DentalHygiene,
		--	'' AS VisionLeft,
		--	'' AS VisionRight,
		--	'' AS TeacherSignCaption,
		--	'' AS PrincipalSignCaption,
		--	'' As ParentSignCaption,
		--	'' As ImprovementArea,
		--	'' AS ProgressArea,
		--	'' As GeneralRemark,
		--	'' AS MyActivity,
		--	'' As ClassTeacherRemark,
		--	'' As HouseRemark,
		--	'' AS BloodGroup,
		--	'' AS ResultRemark3,
		--	'' AS ResultRemark1,
		--	'' AS ResultRemark2,
		--	CONVERT(varbinary ,0) AS MarksheetHeaderA4,
		--	CONVERT(bit ,0) AS IsImageHeader,
		--	CONVERT(bit , 0) AS IsDecimal


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 


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

BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

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

	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			CCEEM.AcademicId,
			--RD.Obtain,
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,0) AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,
			--SM.Title AS ClassSubject,
			--RD.Id AS ResultDetailId,
			ISNULL(R.Id,0) AS ResultId,
			--CS.Id AS SubjectId,
			--ED.Maximum,
			--RD.SubjectGrade,
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			--SM.Code AS SubjectCode,
			--SM.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			AD.HeightTerm1,
			AD.WeightTerm1,
			AD.HeightTerm2,
			AD.WeightTerm2,
			AD.HeightAnnual,
			AD.WeightAnnual,
			AD.PresentDaysTerm1,
			AD.PresentDaysTerm2,
			AD.PresentDaysAnnual,
			AD.TotalDaysTerm1,
			AD.TotalDaysTerm2,
			AD.TotalDaysAnnual,
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
				ELSE NULL END)AS StudentPhoto,
			@GradeString AS GradeString,
			CCEEM.Grade,
			CCEEM.GradeIndicator,
			CCEEM.DescriptiveIndicator,
			CCEM.Title AS CoSubject,
			CCEM.OrderIndex AS CoOrderIndex,
			CCEGM.Title AS CoSubjectGroup,
			CCEGM.OrderIndex AS CoOrderIndexGroup,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
			ELSE NULL END)AS EmployeeSign,
			SR.StudentHeight,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			SR.StudentWeight,
			EM.IsCoScholasticGrade,
			EM.IsCoScholasticGradeIndicator,
			EM.IsCoScholasticGradeDesIndicator,
				ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		SR.ResultRemark3,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		SR.ResultRemark1,
		SR.ResultRemark2,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
  
  
  CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetOptionalSubjectSubCombineGet]  
  
  --@rAcademicIdTextText bigint,  
  --@rExamIdTextText bigint  
  @rAcademicIdText bigint,  
  @rExamIdText int   
   
    
    
    
   
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
  
BEGIN   
--DECLARE  
--@rAcademicIdText bigint,  
--@rExamIdText int  
--SET @rAcademicIdText = convert(bigint, @rAcademicIdTextText)  
--SET @rExamIdText = convert(bigint, @rExamIdTextText)  
DECLARE  
@lIsCoScholasticGrade bit,  
@lIsCoScholasticGradeIndicator bit,   
@lIsCoScholasticGradeDesIndicator bit,  
@lIsCoScholasticCombine bit     
SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,  
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,  
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator,  
@lIsCoScholasticCombine = IsCoScholasticCombine  
FROM sAssessment.tExamMaster WHERE Id = @rExamIdText  
   
  
DECLARE   
@Exam1 int,  
@Exam2 int  
  
  
--@Grade2 nvarchar(50),  
--@GradeIndicator1 nvarchar(50),  
--@Grade2 nvarchar(50),  
--@CategoryID int,  
--@BrandID int  
  
  
  
   
SELECT @Exam1 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamIdText AND ExamOrder = 1  
SELECT @Exam2 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamIdText AND ExamOrder = 2  
  
   
         
   
 SELECT  
   
Convert(nvarchar(10),@rExamIdText) AS ExamIdText,  
Convert(nvarchar(20),@rAcademicIdText) AS   AcademicIdText,  
@rAcademicIdText AS AcademicId,   
@rExamIdText AS ExamId,   
(CASE Term1.SubjectName  WHEN  null THEN Term2.SubjectName  
ELSE Term1.SubjectName END) AS   SubjectName ,   
(CASE Term1.SubjectOrder  WHEN  null THEN Term2.SubjectOrder  
ELSE Term1.SubjectOrder END) AS   CoSubjectOrder ,   
ISNULL(Term1.SubjectGrade,'') AS Grade1,  
ISNULL(Term1.GradeIndicator,'') AS GradeIndicator1,  
ISNULL(Term1.DescriptiveIndicator,'') AS DescriptiveIndicator1,  
ISNULL(Term2.SubjectGrade,'') AS Grade2,  
ISNULL(Term2.GradeIndicator,'') AS GradeIndicator2,  
ISNULL(Term2.DescriptiveIndicator,'') AS DescriptiveIndicator2,  
@lIsCoScholasticGrade AS IsCoScholasticGrade,  
@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,  
@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator   
   
 FROM  
   
   
 (SELECT     
   GSE.AcademicId,  
   GSE.ExamId,  
   GSE.ClassSubjectId,  
   SM.Title AS SubjectName,  
   CS.OrderIndex AS SubjectOrder,  
   -- GSE.Grade,  
   GSE.GradeIndicator,   
   GSE.DescriptiveIndicator,  
   RD.SubjectGrade    
     
     
      
 FROM   
   sAssessment.tGradeSujbectExamScore GSE  
   INNER JOIN sAssessment.tExamMaster EM ON GSE.ExamId = EM.ID  
   INNER JOIN sAssessment.tExamDetail ED ON EM.Id = Ed.ExamId AND GSE.ClassSubjectId = ED.ClassSubjectId  
   INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id   
   INNER JOIN sSetup.tSubjectMaster SM ON Cs.SubjectId = SM.Id   
   INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id AND R.AcademicId = @rAcademicIdText  
   INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId AND ED.Id = RD.ExamDetailId   
   WHERE   GSE.AcademicId =  @rAcademicIdText AND GSE.ExamId = @Exam1   
   AND ED.IsDisplayInMarksheet = 0   
   AND ED.IsIncludeInTotal = 0 AND Ed.IsShowSubjectGrade = 1) Term1  
     
      FULL OUTER JOIN  
     
   (SELECT     
   GSE.AcademicId,  
   GSE.ExamId,  
   GSE.ClassSubjectId,  
  -- GSE.Grade,  
   GSE.GradeIndicator,   
   GSE.DescriptiveIndicator,  
   RD.SubjectGrade,     
   SM.Title AS SubjectName,  
   CS.OrderIndex AS SubjectOrder  
     
      
 FROM   
     
     
   sAssessment.tGradeSujbectExamScore GSE  
   INNER JOIN sAssessment.tExamMaster EM ON GSE.ExamId = EM.ID  
   INNER JOIN sAssessment.tExamDetail ED ON EM.Id = Ed.ExamId AND GSE.ClassSubjectId = ED.ClassSubjectId  
   INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id   
   INNER JOIN sSetup.tSubjectMaster SM ON Cs.SubjectId = SM.Id   
   INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id AND R.AcademicId = @rAcademicIdText  
   INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId AND ED.Id = RD.ExamDetailId   
   WHERE  GSE.AcademicId =  @rAcademicIdText AND GSE.ExamId = @Exam2   
   AND ED.IsDisplayInMarksheet = 0   
   AND ED.IsIncludeInTotal = 0 AND Ed.IsShowSubjectGrade = 1) Term2  
   
      ON Term1.ClassSubjectId = Term2.ClassSubjectId         
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetOptionalSubjectSubSingleGet]

	 --@rAcademicIdTextText bigint,
	 --@rExamIdTextText bigint
	 @rAcademicId bigint,
	 @rExamId int
	
	 
	 
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--DECLARE
--@rAcademicIdText bigint,
--@rExamIdText int
--SET @rAcademicIdText = convert(bigint, @rAcademicIdTextText)
--SET @rExamIdText = convert(bigint, @rExamIdTextText)
DECLARE
@lIsCoScholasticGrade	bit,
@lIsCoScholasticGradeIndicator bit, 
@lIsCoScholasticGradeDesIndicator bit,
@lIsCoScholasticCombine bit		 
SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator,
@lIsCoScholasticCombine = IsCoScholasticCombine
FROM sAssessment.tExamMaster WHERE Id = @rExamId
 
 

 
		     
	
 
	
	SELECT	
			Convert(nvarchar(10),@rExamId) AS ExamIdText,
		    Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,		
			GSE.AcademicId,
			GSE.ExamId,
			GSE.ClassSubjectId,
			SM.Title AS SubjectName,
			CS.OrderIndex AS SubjectOrder,
			 --GSE.Grade,
			GSE.GradeIndicator, 
			GSE.DescriptiveIndicator,
			RD.SubjectGrade,
			@lIsCoScholasticGrade AS IsCoScholasticGrade,
			@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
			@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
			RD.SubjectGrade   
			
			
    
	FROM 
			sAssessment.tResult R
			LEFT JOIN sAssessment.tGradeSujbectExamScore GSE ON R.ExamId =GSE.ExamId
			INNER JOIN sAssessment.tExamMaster EM ON GSE.ExamId = EM.ID AND R.AcademicId = @rAcademicId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id = Ed.ExamId AND GSE.ClassSubjectId = ED.ClassSubjectId
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id 
			INNER JOIN sSetup.tSubjectMaster SM ON Cs.SubjectId = SM.Id 
			 
			
			INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId AND ED.Id = RD.ExamDetailId 
			WHERE GSE.AcademicId =  @rAcademicId AND GSE.ExamId = @rExamId 
			AND ED.IsDisplayInMarksheet = 0 
			AND ED.IsIncludeInTotal = 0 AND Ed.IsShowSubjectGrade = 1 
			
     
		     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR 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

	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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardGet_AllCombine]
	 
	 @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 @lDecimalConfig nvarchar(20)='', @lOrgId int
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId
 
	SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder1 AS Builder2,
		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.Id AS ClassId,
		CM.DisplayTitle AS Class,
		DM.Id AS DivisionId,
		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,		
		ISNULL(SR.PresentDays,0)AS PresentDays,			
		ISNULL(SR.TotalDays,0)AS 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,
		--RAD.SubjectHighestDivisionGrade,
		--RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ED2.ExamDate AS ExamDate2,
		SM.Title AS SubjectName2,
		RD2.Obtain AS SubjectObtain2,
		ED2.Minimum AS SubjectMinimum2,
		ED2.Maximum AS SubjectMaximum2,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD2.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark2,
		ED.Id AS ExamDetailId2,
		EM2.DisplayTitle As Exam2,
		EM2.Id As ExamId,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal
		
	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId
		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
		INNER JOIN sAssessment.tExamCombine EC2 ON EC2.ExamId = EM.Id
		INNER JOIN sAssessment.tExamMaster EM2 ON EM2.Id = EC2.SubExamId
		INNER JOIN sAssessment.tExamDetail ED2 ON EM2.Id = ED2.ExamId AND ED2.ClassSubjectId = ED.ClassSubjectId
		INNER JOIN sAssessment.tResult R2 ON R2.ExamId = EM2.Id AND R2.AcademicId = A.Id
		INNER JOIN sAssessment.tResultDetail RD2 ON ED2.Id = RD2.ExamDetailId AND RD2.ResultId = R2.Id

	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.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,ExamDate2
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardGetwithResultDetailOther]
	 
	 @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
	
	 
	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
 
	SELECT 
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsMarksInDecimal,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		--ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		--	OI.CertificateHeaderA4 
		--ELSE 
		--	NULL END) AS MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		ISNULL(SR.PresentDays,0)AS PresentDays,			
		ISNULL(SR.TotalDays,0)AS 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,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RDO.TotalCount,
		RDO.PresentCount,
		RDO.Remark As Remark4,
		[sAssessment].[fSubjectEmployeeGet](DM.Id,SM.Id) As ClassTeacherName

	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId
		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 sAssessment.tResultDetailOther RDO ON  RDO.ExamId = EM.Id AND R.Academicid =RDO.AcademicId AND ED.ClassSubjectId = RDO.ClassSubjectId
	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))
		order by A.RollNo,ED.DisplayOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExam_Get]
	 
	 @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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rMultiCode nvarchar(max)=''
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 
 --Select * from sAssessment.tTempAll_Exam 
   --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam

 
--#TempAllExam
	 
	SELECT 
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) As CoScholasticScopeIdText ,
		A.Id AS AcademicId,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS StudentName,
		A.RollNo,
 
		R.Id AS ResultId,

	 
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
	     
		SF.FatherName,
		SF.MotherName,
		 
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		    
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption  
	
		 
		 	
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	 
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	 
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID 
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
	 
	 
 
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		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.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		 
	 
	Order By ED.DisplayOrder
	
	 
	
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR 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

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

--	 FROM sAssessment.tTempAllExam T
	
	
--end

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

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		SchoolNameLabel nvarchar(200),
		MediumLabel nvarchar(100),
		NameLabel nvarchar(200),
		CodeLabel nvarchar(100),
		SUIDLabel nvarchar(100),
		ClassLabel nvarchar(100),
		BirthDateLabel nvarchar(100),
		RollNoLabel nvarchar(100),
		FatherNameLabel nvarchar(100),
		MotherNameLabel nvarchar(100),
		TotalWorkingDaysLabel nvarchar(100),
		TotalPresentDaysLabel nvarchar(100),
		HeightLabel nvarchar(100),
		WeightLabel nvarchar(100),
		SubjectLabel nvarchar(100),
		MaxMarksLabel nvarchar(100),
		TotalLabel nvarchar(100),
		GradeLabel nvarchar(100),
		GrandTotalLabel nvarchar(100),
		ResultStatusLabel nvarchar(100),
		RankNoLabel nvarchar(100),
		PercentileLabel nvarchar(100),
		PercentageLabel nvarchar(100),
		OverallGradeLabel nvarchar(100),
		DisplayAttendanceId int,
		ReportHeaderId int,
		StudentImage nvarchar(500)
		
	)	
	 --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,
	ResultSheetAdditionalTitle,
	SchoolNameLabel,
	MediumLabel,
	NameLabel,
	CodeLabel,
	SUIDLabel,
	ClassLabel,
	BirthDateLabel,
	RollNoLabel,
	FatherNameLabel,
	MotherNameLabel,
	TotalWorkingDaysLabel,
	TotalPresentDaysLabel,
	HeightLabel,
	WeightLabel,
	SubjectLabel,
	MaxMarksLabel,
	TotalLabel,
	GradeLabel,
	GrandTotalLabel,
	ResultStatusLabel,
	RankNoLabel,
	PercentileLabel,
	PercentageLabel,
	OverallGradeLabel,
	DisplayAttendanceId,
	ReportHeaderId,
	StudentImage
	)
	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(EM.ResultSheetAdditionalTitle,'') AS ResultSheetAdditionalTitle,
		ISNULL(ALS.SchoolNameLabel,'')AS SchoolNameLabel,
		ISNULL(ALS.MediumLabel,'') AS MediumLabel,
		ISNULL(ALS.NameLabel,'') AS NameLabel,
		ISNULL(ALS.CodeLabel,'') AS CodeLabel,
		ISNULL(ALS.SUIDLabel,'') AS SUIDLabel,
		ISNULL(ALS.ClassLabel,'') AS ClassLabel,
		ISNULL(ALS.BirthDateLabel,'') AS BirthDateLabel,
		ISNULL(ALS.RollNoLabel,'') AS RollNoLabel,
		ISNULL(ALS.FatherNameLabel,'') AS FatherNameLabel,
		ISNULL(ALS.MotherNameLabel,'') AS MotherNameLabel,
		ISNULL(ALS.TotalWorkingDaysLabel,'')AS TotalWorkingDaysLabel,
		ISNULL(ALS.TotalPresentDaysLabel,'') AS TotalPresentDaysLabel,
		ISNULL(ALS.HeightLabel,'') AS HeightLabel,
		ISNULL(ALS.WeightLabel,'') AS WeightLabel,
		ISNULL(ALS.SubjectLabel,'') AS SubjectLabel,
		ISNULL(ALS.MaxMarksLabel,'') AS MaxMarksLabel,
		ISNULL(ALS.TotalLabel,'') AS TotalLabel,
		ISNULL(ALS.GradeLabel,'') AS GradeLabel,
		ISNULl(ALS.GrandTotalLabel,'') AS GrandTotalLabel,
		ISNULl(ALS.ResultStatusLabel,'') AS ResultStatusLabel,
		ISNULL(ALS.RankNoLabel,'') AS RankNoLabel,
		ISNULL(ALS.PercentileLabel,'') AS PercentileLabel,
		ISNULl(ALS.PercentageLabel,'') AS PercentageLabel,
		ISNULL(ALS.OverallGradeLabel,'') AS OverallGradeLabel,
		ISNULL(EM.DisplayAttendanceId,'') AS DisplayAttendanceId,
		ISNULL(EM.ReportHeaderId,'') AS ReportHeaderId,
		--('~/Content/' + A.OrgId + A.StudentId + '.jpg')AS StudentImage
		'~/Content/9911/9911000000299.jpg' AS StudentImage
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tStreamMaster StM ON CM.StreamId = Stm.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = OM.Id
	 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  ISNULL(EMP.IsOtherUser,0) = 0
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

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

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

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

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

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


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

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

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGetwithResultDetailOther]
	@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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	
	 --,@rcolumn_visible bit
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
 
  
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

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

	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(50),@rDivisionId),
		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,
		--ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		[sAssessment].[fSubjectEmployeeGet](DM.Id,SM.Id) As ClassTeacherName,
		ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS InchargeEmployeeName,
		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,
	    ISNULL(RDO.TotalCount,0) As TotalCount,
	    ISNULL(RDO.PresentCount,0) As PresentCount,
	    Isnull(RDO.Remark,'') As Remark4,
	    ---[sAssessment].[fSubjectEmployeeGet](DM.Id,SM.Id) As ClassTeacherName
	   	CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		ISNULL(EMP.ShortName,'') as ClassTeacherShortName,
		OI.SchoolStamp AS SchoolStamp,
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle		--Mantis - 43012
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.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
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.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 sAssessment.tResultDetailOther RDO ON  RDO.ExamId = EM.Id AND R.Academicid =RDO.AcademicId AND ED.ClassSubjectId = RDO.ClassSubjectId
	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 sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 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.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
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					--Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

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


--SELECT @rBuilder1,@rBuilder2, T.* FROM sAssessment.tTempAllExamResultSheet T
--end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
 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,
		ExamMaximum1 decimal(10,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(10,2),	
		SubjectGrade2 NVarchar(10),
		Obtain2 decimal(5,2) Default 0,
		ExamMaximum2 decimal(10,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(10,2),
		SubjectGrade3 NVarchar(10),
		Obtain3 decimal(5,2) Default 0,
		ExamMaximum3 decimal(10,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(10,2),	
		SubjectGrade4 NVarchar(10),
		Obtain4 decimal(5,2) Default 0,
		ExamMaximum4 decimal(10,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(10,2),		
		SubjectGrade5 NVarchar(10),
		Obtain5 decimal(5,2) Default 0,
		ExamMaximum5 decimal(10,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(10,2),		
		SubjectGrade6 NVarchar(10),
		Obtain6 decimal(5,2) Default 0,
		ExamMaximum6 decimal(10,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(10,2),		
		SubjectGrade7 NVarchar(10),
		Obtain7 decimal(5,2) Default 0,
		ExamMaximum7 decimal(10,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(10,2),	
		SubjectGrade8 NVarchar(10),
		Obtain8 decimal(5,2) Default 0,
		ExamMaximum8 decimal(10,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(10,2),		
		SubjectGrade9 NVarchar(10),
		Obtain9 decimal(5,2) Default 0,
		ExamMaximum9 decimal(10,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(10,2),		
		SubjectGrade10 NVarchar(10),
		Obtain10 decimal(5,2) Default 0,
		ExamMaximum10 decimal(10,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(10,2),		
		SubjectGrade11 NVarchar(10),
		Obtain11 decimal(5,2) Default 0,
		ExamMaximum11 decimal(10,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(10,2),		
		SubjectGrade12 NVarchar(10),
		Obtain12 decimal(5,2) Default 0,
		ExamMaximum12 decimal(10,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(10,2),		
		SubjectGrade13 NVarchar(10),
		Obtain13 decimal(5,2) Default 0,
		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(200),
		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)
		)
	 --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
	)
	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
				
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 sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId 
= AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId        --Mantis 0030303
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=StuM.AdmissionCategoryId	--Mantis - 0031091
	 
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

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

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

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 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)
				
		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
									 
					 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)  
		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				 
					 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)
		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
	
	--Select
	--	'' As Builder1,
	--	'' As Builder2,
	--    '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
	--	'' As IsDisplayMonthlyAttendanceText,
	--    '' AS ClassIdText,
	--	0 As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	0 As TotalMark ,
	--	0 As TotalObtain,
	--	0 As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
 --       '' As IsMarksInDecimal,
 --             0 As column_visible,

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign ,	
 --			'' As FatherOccupation ,
 --			0 AS IsDecimal,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm1,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm2,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm3

-- SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
--	SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExamWithAllTerm
 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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(8,2),		
		SubjectGrade13 NVarchar(50),
		Obtain13 decimal(8,2) Default 0,
		ExamMaximum13 decimal(8,2),
		IsPresent13 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		SubjectGradeTerm4 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 

		TotalMarkTerm4	decimal(8,2),
		TotalObtainTerm4 decimal(8,2),
		PercentageTerm4 decimal(8,2),
		RankNumberTerm4 int,
		ResultGradeTerm4 NVarchar(50),
		PercentileTerm4 decimal(8,2),
		ResultStatusTerm4 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		Exam1CombineExamName Nvarchar(150),
				
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		Exam2CombineExamName Nvarchar(150),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		Exam3CombineExamName Nvarchar(150),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		Exam4CombineExamName Nvarchar(150),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		Exam5CombineExamName Nvarchar(150),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		Exam6CombineExamName Nvarchar(150),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		Exam7CombineExamName Nvarchar(150),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		Exam8CombineExamName Nvarchar(150),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		Exam9CombineExamName Nvarchar(150),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		Exam10CombineExamName Nvarchar(150),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		Exam11CombineExamName Nvarchar(150),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		Exam12CombineExamName Nvarchar(150),

		Exam13Name nvarchar(150),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(8,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(50),
		Percentile13 decimal(8,2),
		ResultStatus13 Nvarchar(20),
		Exam13CombineExamName Nvarchar(150),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		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),
		ExamNameTerm4 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectObtainTerm4  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		SubjectMaxTerm4 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		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(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(50) ,
		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),
		ExamMaximumTerm4 decimal(6,2),
		--Added by dhananjay mantis : 43188
		ResultIndicator nvarchar(50),
		IsDisplayResultIndicator bit
		--Added by dhananjay mantis : 43188

		)	
	 --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,
	--Added by dhananjay mantis : 43188
	ResultIndicator,
	IsDisplayResultIndicator 
	--Added by dhananjay mantis : 43188
	)
	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,
		--Added by dhananjay mantis : 43188
		ISNULL(R.ResultIndicator,'') AS ResultIndicator,
		EM.IsDisplayResultIndicator 
		--Added by dhananjay mantis : 43188
				
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 sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

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

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

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 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)
				
		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
									 
					 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)  
		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				 
					 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)
		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)

		--for 4 Term
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 4
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm4=RD.SubjectGrade,
					SubjectObtainTerm4 = RD.Obtain,
					SubjectMaxTerm4= ED.Maximum
									 
					From
					sAssessment.tResultDetail RD
					INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
					INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 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)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm4 = R.TotalMarks,
					TotalObtainTerm4 =R.TotalObtain,
					PercentageTerm4 =R.Percentage,
					RankNumberTerm4 =R.RankNumber,
					ResultGradeTerm4 =R.ResultGrade,
					PercentileTerm4  = R.Percentile,
					ResultStatusTerm4  = R.ResultStatus,
					ExamNameTerm4 = ESGM.Code,
					ExamMaximumTerm4 = 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
	
	--Select
	--	'' As Builder1,
	--	'' As Builder2,
	--    '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
	--	'' As IsDisplayMonthlyAttendanceText,
	--    '' AS ClassIdText,
	--	0 As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	0 As TotalMark ,
	--	0 As TotalObtain,
	--	0 As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
 --       '' As IsMarksInDecimal,
 --             0 As column_visible,

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
	--		0x AS CoordinatorEmployeeSign ,	
 --			'' As FatherOccupation ,
 --			0 AS IsDecimal,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm1,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm2,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm3,
 --			'' AS ResultIndicator AS ResultIndicator,
 --		    0 AS IsDisplayResultIndicator 

	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExamWithAllTerm T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiMaxExamGet]
	 
	 @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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	 --,@rcolumn_visible bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 
  
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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2),
		ExamMaximum1 decimal(8,2),
		ObtainedMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		ObtainedMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		ObtainedMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		ObtainedMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2),
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		Percentile decimal(5,2),
		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(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(200),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		HouseId int,
		HouseName nvarchar(100),
		IsDecimal bit
	)	
	 
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	Percentile,
	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,
	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,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
    IsShowWithDetail,
    IsPresent,
    GradeTitle,
	
	 SubjectHighestDivisionGrade,
	 SubjectHighestDivisionMark,
	 HouseName,
	 HouseId,
	 IsDecimal
	)
	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,
		R.Percentile,
		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,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) 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,
		(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,
		@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),
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark ,
		HM.Title As HouseName,HM.Id as HouseId,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.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
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
			  
	
	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.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=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 ED.DisplayOrder
 
	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
 	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
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		if(@lCount <= 4)
		BEGIN
			set @query ='update T SET
						 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
						 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
						 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,
					
						 ObtainedMaximum' + convert(nvarchar(15),@lCount)+ '= CASE WHEN EM.IsDisplayHighestDivisionMark = 1
									THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
									ELSE 0  END,
						 				
						 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
						 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
						 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
						 From
							sAssessment.tResultDetail RD
							INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
							INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
							INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
							INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
							INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
							INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
							LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
							WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId) 
			
			execute(@query)
			
		END
		
		ELSE
		
		BEGIN
			set @query ='update T SET
						 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
						 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
						 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
						 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
						 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
						 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays
						 										
						 From
							sAssessment.tResultDetail RD
							INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
							INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
							INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
							INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
							INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
							INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
							LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
							WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
			
					
			execute(@query)
			
		END
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code					 
					 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 = 2
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	-- For Getting Highest Mark in Class in 2nd and 3rd Exam in One Field
	
	CREATE TABLE #HighestMarkTerm2Term3
	(
		SubjectId int,
		Term2Term3ClassHighestMarkSum decimal(8,2)
	)
	INSERT INTO #HighestMarkTerm2Term3 
	(
		SubjectId,
		Term2Term3ClassHighestMarkSum
	)
	SELECT 
		CS.SubjectId,		 
		MAX(RD.Obtain) AS Term2Term3ClassHighestMarkSum
	FROM
	sAssessment.tResultDetail RD INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id
	 INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	INNER JOIN sAssessment.tExamMaster EM ON ED.ExamId = EM.Id
	INNER JOIN  sSetup.tClassSubject CS  ON ED.ClassSubjectId = CS.Id
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	WHERE
	A.BatchId = @rBatchId
	AND EM.BatchId =  @rBatchId
	AND	((A.ClassId = @rClassId) OR (@rClassId = 0)) 
		AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0)) 
		--AND ((CS.Id = @rSubjectId) OR (@rSubjectId = 0))
		AND ((EM.Id = @rExamId) OR (@rExamId = 0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		group by CS.SubjectId,A.DivisionId 
		
	
	
	
	
	SELECT 
		  @rBuilder1,@rBuilder2, T.*,H.Term2Term3ClassHighestMarkSum
	FROM 
	      #TempAllExam T
		  INNER JOIN #HighestMarkTerm2Term3 H ON H.SubjectId = T.SubjectId
	
	
	Drop table #tempcombineExam
	
	Drop table #TempAllExam
	
	Drop table #HighestMarkTerm2Term3
	
	END
	
	
	--SELECT @rBuilder1,@rBuilder2,T.* FROM sAssessment.tTempAllExam T
 -- end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardWithAnalysisGet]
	 
	 @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),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId) 

DECLARE @lOrgId int=0
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
Declare @DecimalConfigId nvarchar(20)=''
SELECT @DecimalConfigId =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId
 
	SELECT 
			--Convert(nvarchar(20),A.Id) AS AcademicIdText,
			--Convert(nvarchar(20),@rExamId) AS ExamIdText,
			RAD.SubjectHighestClassMark,
			RAD.SubjectHighestDivisionMark,
			RAD.SubjectAverageClassMark,
			RAD.SubjectAverageDivisionMark,
			RAD.SubjectHighestClassGrade,
			RAD.SubjectHighestDivisionGrade,
			RAD.ClassSubjectId,
			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,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			--ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			SR.StudentHeight,
			SR.StudentWeight,		
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
				ELSE NULL END)AS StudentPhoto,
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			SF.FatherName,
			SF.MotherName,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			RAN.HighestClassMark,
			RAN.HighestDivisionMark AS DivisionHighestMark,
			RAn.HighestClassGrade,
			RAN.HighestDivisionGrade AS DivisionHighestGrade,
			RAN.AverageClassMark,
			RAn.AverageDivisionMark,
			RAN.DivisionPercentile,
			RAN.ClassPercentile 
			,RAN.TotalStudentClass,
			RAN.TotalStudentDivision,
		 
			RA.ClassRank,
			RA.DivisionRank,
			RD.Remark,
			RA.PassedSubject,
			RA.FailedSubject,
			EMP.Id AS EmployeeId,
			--TSD.EmployeeId,
			EMP.FirstName + ' ' +EMP.MiddleName +' ' +Emp.LastName AS EmployeeName,
			(CASE EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
				ELSE NULL END ) AS EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.DecimalFormat,
			SR.ResultRemark3,
			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,
			ISNULL(SR.MyGoal,'') AS MyGoal,
			ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
			ISNULL(SR.Responsibility,'') AS Responsibility,
			ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
			ISNULL(SR.MyStrength,'') AS MyStrength,
			ISNULL(SR.Achievements,'') AS Achievements,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight, 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			--(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 ,
			CONVERT(bit,@DecimalConfigId) AS IsDecimal
	FROM 
			 sAssessment.tResultDetail RD
			 INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			 INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			 INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
			 INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			  INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			 LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM .InchargeEmployeeId
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId		
			 --Left Join sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId = SM.Id AND Tsd.DivisionId=A.DivisionId
			 --AND TSD.EmployeeId = EI.EmployeeId
			 LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id=EI.EmployeeId 
			
			  
			  LEFT JOin sAssessment.tResultAnalysis RA ON RA.AcademicId = A.Id AND RA.ExamId = EM.Id
			  LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
			  LEFT JOIN sAssessment.tResultAnalysisDivision RAN ON RAN.DivisionId = A.DivisionId AND RAN.ExamId = EM.Id
			   
			  
		      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 sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			
			  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
			  LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
				 
	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,CS.OrderIndex 
			--AND A.id = 1005000000007
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardWithGradeGet]
	 
	 @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 @lOrgId int=0
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
Declare @DecimalConfigId nvarchar(20)=''
SELECT @DecimalConfigId =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId

 
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
				Convert(nvarchar(20),@rBatchId) AS BatchIdText,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsMarksInDecimal,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			--ISNULL(R.ResultRemark,'') AS ResultRemark,
			SO.DateOfBirth,
			SR.StudentHeight,
			SR.StudentWeight,		
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			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,
			ISNULL(SR.MyGoal,'') AS MyGoal,
			ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
			ISNULL(SR.Responsibility,'') AS Responsibility,
			ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
			ISNULL(SR.MyStrength,'') AS MyStrength,
			ISNULL(SR.Achievements,'') AS Achievements,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
			BM.Title AS BatchName,
			Em.DecimalFormat,
			SR.Resultremark3,
			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(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,
		GS.GradeTitle,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		GSCSD.GradeRemark,
		CONVERT(bit,@DecimalConfigId) AS IsDecimal
			--[sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId) AS HighestDivisionMark,
			--[sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId) AS HighestDivisionGrade
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId
			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.tGradeSetClassSubjectMaster GSCSM ON GSCSM.ClassId = CM.Id AND GSCSM.SubjectId = SM.Id AND GSCSM.GradeSetId = GS.GradeSetId
			LEFT JOIN sAssessment.tGradeSetClassSubjectDetail GSCSD ON GSCSD.GradeSetDetailId = GS.Id AND GSCSD.GradeSetClassSubjectId = GSCSM.Id
			
			LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.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
		--AND A.id = 1005000000007
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClass int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rOrgId int=0,
	 @rMultiCode nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 	

 --Select * from   sAssessment.tTempAllExamSubjectActivity
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
SELECT @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

Declare @lDecimalConfig nvarchar(20)=''
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		
		ResultStatus Nvarchar(50),	
		
		ClassName NVarchar(100),
				
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		--MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		--Obtain1 decimal(8,2),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	

		SubjectGrade9 NVarchar(50),
		IsPresent9 bit,

		SubjectGrade10 NVarchar(50),
		IsPresent10 bit,

		SubjectGrade11 NVarchar(50),
		IsPresent11 bit,

		SubjectGrade12 NVarchar(50),
		IsPresent12 bit,

		SubjectGrade13 NVarchar(50),
		IsPresent13 bit,
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(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(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		SubActivityGrade1 nvarchar(50),
		ActivityGrade1 nvarchar(50),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		SubActivityGrade2 nvarchar(50),
		ActivityGrade2 nvarchar(50),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		SubActivityGrade3 nvarchar(50),
		ActivityGrade3 nvarchar(50),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		SubActivityGrade4 nvarchar(50),
		ActivityGrade4 nvarchar(50),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		SubActivityGrade5 nvarchar(50),
		ActivityGrade5 nvarchar(50),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		SubActivityGrade6 nvarchar(50),
		ActivityGrade6 nvarchar(50),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		SubActivityGrade7 nvarchar(50),
		ActivityGrade7 nvarchar(50),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),

		SubActivityGrade8 nvarchar(50),
		ActivityGrade8 nvarchar(50),

		Exam9Name Nvarchar(150),
		Exam10Name Nvarchar(150),
		Exam11Name Nvarchar(150),
		Exam12Name Nvarchar(150),
		Exam13Name Nvarchar(150),

		SubActivityGrade9 nvarchar(50),
		ActivityGrade9 nvarchar(50),

		SubActivityGrade10 nvarchar(50),
		ActivityGrade10 nvarchar(50),

		SubActivityGrade11 nvarchar(50),
		ActivityGrade11 nvarchar(50),

		SubActivityGrade12 nvarchar(50),
		ActivityGrade12 nvarchar(50),

		SubActivityGrade13 nvarchar(50),
		ActivityGrade13 nvarchar(50),

		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,
		IsDisplayParentName bit,
		
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(50),
		 ActivityGrade nvarchar(50),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Height7 decimal(6,2),
		Height8 decimal(6,2),
		Height9 decimal(6,2),
		Height10 decimal(6,2),
		Height11 decimal(6,2),
		Height12 decimal(6,2),
		Height13 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		Weight7 decimal(6,2),
		Weight8 decimal(6,2),
		Weight9 decimal(6,2),
		Weight10 decimal(6,2),
		Weight11 decimal(6,2),
		Weight12 decimal(6,2),
		Weight13 decimal(6,2),
		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),
		--Manits - 41461(Increase size 200 to 2000)
		MyActivity1 nvarchar(2000),  
		MyActivity2 nvarchar(2000),
		MyActivity3 nvarchar(2000),
		MyActivity4 nvarchar(2000),
		MyActivity5 nvarchar(2000),
		MyActivity6 nvarchar(2000),
		MyActivity7 nvarchar(2000),
		MyActivity8 nvarchar(2000),
		MyActivity9 nvarchar(2000),
		MyActivity10 nvarchar(2000),
		MyActivity11 nvarchar(2000),
		MyActivity12 nvarchar(2000),
		MyActivity13 nvarchar(2000),
		--Manits - 41461
		GeneralRemark1 nvarchar(1000),
		GeneralRemark2 nvarchar(1000),
		GeneralRemark3 nvarchar(1000),
		GeneralRemark4 nvarchar(1000),
		GeneralRemark5 nvarchar(1000),
		GeneralRemark6 nvarchar(1000),
		GeneralRemark7 nvarchar(1000),
		GeneralRemark8 nvarchar(1000),
		GeneralRemark9 nvarchar(1000),
		GeneralRemark10 nvarchar(1000),
		GeneralRemark11 nvarchar(1000),
		GeneralRemark12 nvarchar(1000),
		GeneralRemark13 nvarchar(1000),
		PresentAddress nvarchar(500) ,
		MobileNo nvarchar(50),
		House nvarchar(100),
		 
		AttendanceTerm1 decimal(6, 2) ,
		AttendanceTerm2 decimal(6, 2),
		WorkingDaysTerm1 decimal(6, 2),
		WorkingDaysTerm2 decimal(6, 2),
		
		BloodGroup nvarchar(20),
		GradeSetIdText nvarchar(50),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ParentEmail nvarchar(500),
		MyGoal nvarchar(200),
		MyStrength nvarchar(200),
		MyInterestHobby nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		Achievements nvarchar(1000),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		MyActivity nvarchar(2000),
		ClassTeacherRemark nvarchar(1000),
		ClassTeacherName Nvarchar(100),
		HouseRemark nvarchar(1000),
		GeneralRemark nvarchar(1000),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		IsDecimal bit,
		Name nvarchar(150),
		--mantis 0029914
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		AdmissionNo nvarchar(50),
		StudentContactNo nvarchar(50),
		DescriptiveIndicator nvarchar(200),
		DescriptiveIndicator1 nvarchar(200),
		DescriptiveIndicator2 nvarchar(200),
		DescriptiveIndicator3 nvarchar(200),
		DescriptiveIndicator4 nvarchar(200),
		DescriptiveIndicator5 nvarchar(200),
		DescriptiveIndicator6 nvarchar(200),
		DescriptiveIndicator7 nvarchar(200),
		DescriptiveIndicator8 nvarchar(200),
		DescriptiveIndicator9 nvarchar(200),
		DescriptiveIndicator10 nvarchar(200),
		DescriptiveIndicator11 nvarchar(200),
		DescriptiveIndicator12 nvarchar(200),
		DescriptiveIndicator13 nvarchar(200),
		--for mantis Start - 36640 
		RelativeName varchar(100),
		PresentCity varchar (50),
		--for mantis End - 36640 ,
		--for mantis Start: 0039950
		Exam1DisplayTitle nvarchar(200),
		Exam2DisplayTitle nvarchar(200),
		Exam3DisplayTitle nvarchar(200),
		Exam4DisplayTitle nvarchar(200),
		Exam5DisplayTitle nvarchar(200),
		Exam6DisplayTitle nvarchar(200),
		Exam7DisplayTitle nvarchar(200),
		Exam8DisplayTitle nvarchar(200),
		Exam9DisplayTitle nvarchar(200),
		Exam10DisplayTitle nvarchar(200),
		Exam11DisplayTitle nvarchar(200),
		Exam12DisplayTitle nvarchar(200),
		Exam13DisplayTitle nvarchar(200),
		ResultSheetAdditionalTitle nvarchar(200) --Mantis - 40152
		--for mantis End: 0039950
		,UIDNumber nvarchar(200)
	)	
	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	SubActivityGrade,
	ActivityGrade,
	ActivityName,
	SubActivityName,
	SubActivityId,
	ActivityId,
	SubActivityGradeIndicator,
	SubActivityDescriptiveIndicator,
	SubjectActivityOrderIndex,
	SubActivityOrderIndex,
	ColumnSubjectCount,
	MarksheetHeaderA4,
	IsImageHeader,
	PresentAddress,
 	MobileNo,
	House,
	AttendanceTerm1   ,
	AttendanceTerm2  ,
	WorkingDaysTerm1  ,
	WorkingDaysTerm2  ,
	BloodGroup,
	GradeSetIdText,
	IsDisplayMonthlyAttendanceText,
	DentalHygiene,
	VisionLeft,
	VisionRight,
	TeacherSignCaption,
	PrincipalSignCaption,ParentSignCaption,
	ParentEmail,
	MyGoal ,
	MyStrength ,
	MyInterestHobby ,
	AreaOfInterest ,
	Responsibility ,
	Achievements ,
	ImprovementArea ,
	ProgressArea ,
	MyActivity ,
	ClassTeacherRemark ,
	ClassTeacherName ,
	HouseRemark ,
	GeneralRemark ,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail,
	MotherMail,
	IsDecimal,
	Name,
	-- mantis-0029914
	PermanentStreetOne,
	PermanentStreetTwo,
	PermanentStreetThree,
	AdmissionNo,
	StudentContactNo,
	DescriptiveIndicator,
	--for mantis Start - 36640 
	RelativeName,
	PresentCity,
	ResultSheetAdditionalTitle --Mantis - 40152
	--for mantis End - 36640 
	,UIDNumber
	)
	
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS StudentName,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


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

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		CASE WHEN EM.IsDisplayPhoto = 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,
	    SAM.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		SSA.Grade AS SubActivityGrade,
		ISNULL(SAS.Grade,'') AS ActivityGrade,
		SAM.Title AS ActivityName,
		SSAM.Title AS SubActivityName,
		SSA.SubjectSubActivityId AS SubActivityId,
		SAM.Id AS ActivityId,
		SSA.GradeIndicator AS SubActivityGradeIndicator,
		SSA.DescriptiveIndicator AS SubActivityDescriptiveIndicator,
		SAM.OrderIndex AS SubjectActivityOrderIndex,
		SSAM.OrderIndex AS SubActivityOrderIndex,
		CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.MarksheetHeaderA4
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	,
		ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		 SC.ParentContactNo,
		ISNULL(HM.Title,'') AS House,
		ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
		ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
		ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
		ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
		ISNULL(BGM.Title,'') AS BloodGroup,
		CONVERT (nvarchar(50),EM.GradeSetId) AS GradeSetIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
		--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(ParentSignCaption,'') AS ParentSignCaption,
		SC.ParentEmail As ParentEmail,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		-- mantis-0029914
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		StuA.AdmissionNumber,
		SC.StudentContactNo,
		SSA.DescriptiveIndicator AS DescriptiveIndicator,
		--for mantis Start - 36640 
		ISNULL(SF.RelativeName,'') AS RelativeName,
		ISNULL(SC.PresentCity,'') AS PresentCity,
		--for mantis End - 36640 
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle	--Mantis - 40152
		,ISNULL(SO.UIDNumber,'') AS UIDNumber --add for mantis : 0042613	
	FROM 
		sAssessment.tCCESubjectSubActivityExamScore SSA
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
		INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
		LEFT JOIN sAssessment.tCCESubjectActivityExamScore SAS ON SAS.SubjectActivityId= SAM.Id AND SSA.AcademicId = SAS.AcademicId AND SSA.ExamId = SAS.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId	
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
		INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = SAM.ClassSubjectId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
    	INNER JOIN sStudent.tAcademic  A ON   SSA.AcademicId = A.Id
		LEFT JOIN sAssessment.tCCEResult CCER    ON  CCER.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = ED.ClassSubjectId  
		LEFT JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId = SSA.ExamId
		LEFT JOIN sAssessment.tResultDetail RD  ON R.Id = RD.ResultId AND ED.ID = RD.ExamDetailId 
		LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =Stum.ID
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
		--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
		--0029914
		LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	
	 WHERE
		SSA.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClass) OR (@rClass=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		--AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		--AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		--AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) --uncommented by Dhananjay for mantis : 41990
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		--AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=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.SubExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	 
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int  
	Select @lCount = MAX(Id) from #tempcombineExam	
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		set @query ='update T SET
					
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
					 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
					 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
					 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark,
					 Exam' + convert(nvarchar(15),@lCount)+ 'DisplayTitle=ESGM.ExamSubGroupDisplayTitle 
					 									
					 From
						 
						 sAssessment.tResult R 
						INNER JOIN  sAssessment.tResultDetail RD ON RD.ResultId = R.Id						
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 							
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
 
	 set @query ='update T SET
					
					 
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade,
					 DescriptiveIndicator' + convert(nvarchar(15),@lCount)+ '=SSA.DescriptiveIndicator	
					 						
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA				
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE SSA.ExamId =' + convert(nvarchar(15), @lSubExamId)  


						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	
	--					LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 					
	--					WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
 ----PRINT(@QUERY)	
 --  EXECUTE(@query)
	
						
		/*	set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	execute(@query)*/
		
		
	set @lCount = @lCount -1
	end
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam

	--Select 
	-- '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
		
	--	CONVERT(bigint , 0) As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	CONVERT(decimal , 0) As TotalMark ,
	--	CONVERT(decimal , 0) As TotalObtain,
	--	CONVERT(decimal , 0) As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
		
	--	--MaximumMark1 decimal(8,2),		
	--	'' As SubjectGrade1 ,
	--	--Obtain1 decimal(8,2),
	--	--ExamMaximum1 decimal(8,2),
	--	CONVERT(bit , 0) As IsPresent1,
						
	--	CONVERT(decimal , 0) As MaximumMark2 ,	
	--	'' As SubjectGrade2 ,
	--	CONVERT(decimal , 0) As Obtain2 ,
	--	CONVERT(decimal , 0) As ExamMaximum2 ,
	--	CONVERT(bit , 0) As IsPresent2,
				
	--	CONVERT(decimal , 0) As MaximumMark3 ,
	--	'' As SubjectGrade3 ,
	--	CONVERT(decimal , 0) As Obtain3 ,
	--	CONVERT(decimal , 0) As ExamMaximum3 ,
	--	CONVERT(bit , 0) As IsPresent3 ,		
		
	--	CONVERT(decimal , 0) As MaximumMark4 ,	
	--	'' As SubjectGrade4 ,
	--	CONVERT(decimal , 0) As Obtain4 ,
	--	CONVERT(decimal , 0) As ExamMaximum4 ,
	--	CONVERT(bit , 0) As IsPresent4 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark5 ,		
	--	'' As SubjectGrade5 ,
	--	CONVERT(decimal , 0) As Obtain5 ,
	--	CONVERT(decimal , 0) As ExamMaximum5 ,
	--	CONVERT(bit , 0) As IsPresent5 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark6 ,		
	--	'' As SubjectGrade6,
	--	CONVERT(decimal , 0) As Obtain6 ,
	--	CONVERT(decimal , 0) As ExamMaximum6 ,
	--	CONVERT(bit , 0) As IsPresent6 ,	
		
	--	CONVERT(decimal , 0) As MaximumMark7 ,		
	--	'' As SubjectGrade7,
	--	CONVERT(decimal , 0) As Obtain7 ,
	--	CONVERT(decimal , 0) As ExamMaximum7 ,
	--	CONVERT(bit , 0) As IsPresent7 ,	
	
	--	CONVERT(decimal , 0) As MaximumMark8 ,	
	--	'' As SubjectGrade8,
	--	CONVERT(decimal , 0) As Obtain8 ,
	--	CONVERT(decimal , 0) As ExamMaximum8 ,
	--	CONVERT(bit , 0) As IsPresent8 ,	
		
	--	'' As SubjectGrade9,
	--	CONVERT(bit , 0) As IsPresent9 ,

	--	'' As SubjectGrade10,
	--	CONVERT(bit , 0) As IsPresent10 ,

	--	'' As SubjectGrade11,
	--	CONVERT(bit , 0) As IsPresent11 ,

	--	'' As SubjectGrade12,
	--	CONVERT(bit , 0) As IsPresent12 ,

	--	'' As SubjectGrade13,
	--	CONVERT(bit , 0) As IsPresent13 ,

	--	'' As SubjectGradeTerm1,
	--	'' As SubjectGradeTerm2 ,
	--	CONVERT(bit , 0) As IsMarksInDecimal ,
	--	CONVERT(bit , 0) As column_visible ,
	--	--Obtain decimal(5,2),
	--	CONVERT(decimal , 0) As Percentile,
	--	--ClassSubject nvarchar(100),
	--	CONVERT(bigint , 0) As ResultDetailId ,
	--	CONVERT(bigint , 0) As ResultId ,	
	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	CONVERT(bit , 0) As IsRankNo , 
	--	CONVERT(bit , 0) As IsGrade ,
	--	CONVERT(bit , 0) As IsPercentile ,
	--	CONVERT(bit , 0) As IsPercentage ,
	--	CONVERT(bit , 0) As IsSubjectPercentile ,
	--	CONVERT(bit , 0) As IsProcessResult ,
	--	CONVERT(bit , 0) As IsNegativeMarks ,
	--	CONVERT(bit , 0) As IsIncludeCoScholastic ,
	--	CONVERT(bit,0) As IsOnPrePrinted ,
	--	CONVERT(bit , 0) As IsDisplayPhoto ,
	--	CONVERT(bit , 0) As IsDisplayBirthDate ,
	--	CONVERT(bit , 0) As IsLockForEdit ,
	--	CONVERT(bit , 0) As IsDisplaySchoolName ,			
	--	CONVERT(bit , 0) As IsDisplayAttendance ,
	--	CONVERT(bit , 0) As IsDisplayHeightWeight ,
	--	CONVERT(bit , 0) As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	CONVERT(Date , null) As DateOfBirth ,
	--	CONVERT(decimal , 0) As HeightTerm1 ,
	--	CONVERT(decimal , 0) As WeightTerm1 ,
	--	CONVERT(decimal , 0) As HeightTerm2,
	--	CONVERT(decimal , 0) As WeightTerm2 ,
	--	CONVERT(decimal , 0) As HeightAnnual ,
	--	CONVERT(decimal , 0) As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	CONVERT(decimal , 0) As TotalMarkTerm1 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm1 ,
	--	CONVERT(decimal , 0) As PercentageTerm1,
	--	0 As RankNumberTerm1 ,
	--	'' As ResultGradeTerm1,
	--	CONVERT(decimal , 0) As PercentileTerm1 ,
	--	'' As ResultStatusTerm1,		   
	--	CONVERT(decimal , 0) As TotalMarkTerm2 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm2 ,
	--	CONVERT(decimal , 0) As PercentageTerm2 ,
	--	0 As RankNumberTerm2 ,
	--	'' As ResultGradeTerm2 ,
	--	CONVERT(decimal , 0) As PercentileTerm2 ,
	--	'' As ResultStatusTerm2 , 
	--	CONVERT(tinyInt , 0) As TermScopeId ,		 
	--	Convert (varbinary(max) , '') As StudentPhoto ,
	--	'' As GradeString,
	--	CONVERT(bit , 0) As IsDisplayGradeString ,		 
	--	CONVERT(bit , 0) As IsDisplayInMarksheet ,
	--	CONVERT(bit , 0) As IsShowSubjectGrade ,
	--	CONVERT(bit , 0) As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	CONVERT(decimal , 0) As SubjectMinimum ,		
	--	CONVERT(decimal , 0) As SubjectMaximum ,
	--	CONVERT(decimal , 0) As SubjectObtain ,
		
	--	'' As Exam1Name ,		
	--	CONVERT(decimal , 0) As TotalMarks1 ,		
	--	CONVERT(decimal , 0) As TotalObtain1 ,
	--	CONVERT(decimal , 0) As Percentage1 ,
	--	0 As RankNumber1 ,
	--	'' As ResultGrade1,
	--	CONVERT(decimal , 0) As Percentile1 ,
	--	'' As ResultStatus1 ,
		
	--	'' As SubActivityGrade1,
	--	'' As ActivityGrade1,
		
	--	'' As Exam2Name ,	
	--	CONVERT(decimal , 0) As TotalMarks2 ,
	--	CONVERT(decimal , 0) As TotalObtain2 ,
	--	CONVERT(decimal , 0) As Percentage2 ,
	--	0 As RankNumber2 ,
	--	'' As ResultGrade2 ,
	--	CONVERT(decimal , 0) As Percentile2 ,
	--	'' As ResultStatus2 ,
		
	--	'' As SubActivityGrade2,
	--	'' As ActivityGrade2 ,
		
	--	'' As Exam3Name ,	
	--	CONVERT(decimal , 0) As TotalMarks3 ,
	--	CONVERT(decimal , 0) As TotalObtain3 ,
	--	CONVERT(decimal , 0) As Percentage3 ,
	--	0 As RankNumber3 ,
	--	'' As ResultGrade3 ,
	--	CONVERT(decimal , 0) As Percentile3 ,		
	--	'' As ResultStatus3,
		
	--	'' As SubActivityGrade3 ,
	--	'' As ActivityGrade3 ,
		
	--	'' As Exam4Name ,	
	--	CONVERT(decimal , 0) As TotalMarks4 ,
	--	CONVERT(decimal , 0) As TotalObtain4,
	--	CONVERT(decimal , 0) As Percentage4 ,
	--	0 As RankNumber4 ,
	--	'' As ResultGrade4 ,
	--	CONVERT(decimal , 0) As Percentile4 ,
	--	'' As ResultStatus4 ,
		
	--	'' As SubActivityGrade4,
	--	'' As ActivityGrade4 ,
		
	--	'' As Exam5Name ,		
	--	CONVERT(decimal , 0) As TotalMarks5 ,
	--	CONVERT(decimal , 0) As TotalObtain5 ,
	--	CONVERT(decimal , 0) As Percentage5 ,
	--	0 As RankNumber5 ,
	--	'' As ResultGrade5 ,
	--	CONVERT(decimal , 0) As Percentile5 ,
	--	'' As ResultStatus5 ,
		
	--	'' As SubActivityGrade5 ,
	--	'' As ActivityGrade5 ,
		
	--	'' As Exam6Name ,	
	--	CONVERT(decimal , 0) As TotalMarks6 ,
	--	CONVERT(decimal , 0) As TotalObtain6,
	--	CONVERT(decimal , 0) As Percentage6 ,
	--	0 As RankNumber6 ,
	--	'' As ResultGrade6 ,
	--	CONVERT(decimal , 0) As Percentile6 ,
	--	'' As ResultStatus6 ,
		
	--	'' As SubActivityGrade6 ,
	--	'' As ActivityGrade6 ,
		
	--	'' As Exam7Name ,		
	--	CONVERT(decimal , 0) As TotalMarks7 ,
	--	CONVERT(decimal , 0) As TotalObtain7,
	--	CONVERT(decimal , 0) As Percentage7 ,
	--	0 As RankNumber7 ,
	--	'' As ResultGrade7,
	--	CONVERT(decimal , 0) As Percentile7 ,
	--	'' As ResultStatus7 ,
		
	--	--SubActivityGrade7 nvarchar(10),
		
	--	'' As Exam8Name,
	--	CONVERT(decimal , 0) As TotalMarks8 ,
	--	CONVERT(decimal , 0) As TotalObtain8 ,
	--	CONVERT(decimal , 0) As Percentage8,
	--	0 As RankNumber8 ,
	--	'' As ResultGrade8 ,
	--	CONVERT(decimal , 0) As Percentile8,
	--	'' As ResultStatus8,

	--	'' As Exam9Name,
	--	'' As Exam10Name,
	--	'' As Exam11Name,
	--	'' As Exam12Name,
	--	'' As Exam13Name,

	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,
	--	CONVERT(decimal , 0) As TotalDays ,
	--	CONVERT(decimal , 0) As PresentDays ,
	--	CONVERT(decimal , 0) As StudentHeight,
	--	CONVERT(decimal , 0) As StudentWeight ,
	--	'' As ExamSeatNo ,
	--	0 As ExamId ,
	--	CONVERT(bit , 0) As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	CONVERT(bit , 0) As IsShowSubjectMark , 
	--	CONVERT(bit , 0) As IsOptionalSubject ,
	--	CONVERT(tinyInt , 0) As CoScholasticScopeId ,
	--	CONVERT(bit , 0) As IsDisplayPrincipalSign ,
	--	CONVERT(bit , 0) As IsDisplayTeacherSign ,
	--	Convert (varbinary(max) , '') As EmployeeSign,
		
	--	'' As ActivityName ,
	--	'' As SubActivityName ,
	--	0 As SubActivityId ,
	--	0 As ActivityId ,
	--	 '' As SubActivityGrade,
	--	 '' As ActivityGrade ,
	--	'' As SubActivityGradeIndicator ,
	--	'' As SubActivityDescriptiveIndicator,
	--	0 As SubjectActivityOrderIndex ,
	--	0 As SubActivityOrderIndex ,
	--	0 As ColumnSubjectCount ,
	--	Convert (varbinary(max) , '') As MarksheetHeaderA4 ,
	--	CONVERT(bit,0) As IsImageHeader ,
	--	CONVERT(decimal , 0) As Height1 ,
	--	CONVERT(decimal , 0) As Height2 ,
	--	CONVERT(decimal , 0) As Height3,
	--	CONVERT(decimal , 0) As Height4 ,
	--	CONVERT(decimal , 0) As Height5,
	--	CONVERT(decimal , 0) As Height6 ,
	--	CONVERT(decimal , 0) As Height7 ,
	--	CONVERT(decimal , 0) As Height8 ,
	--	CONVERT(decimal , 0) As Height9,
	--	CONVERT(decimal , 0) As Height10 ,
	--	CONVERT(decimal , 0) As Height11,
	--	CONVERT(decimal , 0) As Height12 ,
	--	CONVERT(decimal , 0) As Height13 ,

	--	CONVERT(decimal , 0) As Weight1 ,
	--	CONVERT(decimal , 0) As Weight2 ,
	--	CONVERT(decimal , 0) As Weight3 ,
	--	CONVERT(decimal , 0) As Weight4,
	--	CONVERT(decimal , 0) As Weight5 ,
	--	CONVERT(decimal , 0) As Weight6 ,
	--	CONVERT(decimal , 0) As Weight7 ,
	--	CONVERT(decimal , 0) As Weight8 ,
	--	CONVERT(decimal , 0) As Weight9 ,
	--	CONVERT(decimal , 0) As Weight10,
	--	CONVERT(decimal , 0) As Weight11 ,
	--	CONVERT(decimal , 0) As Weight12 ,
	--	CONVERT(decimal , 0) As Weight13 ,

	--	CONVERT(decimal , 0) As TotalDays1 ,
	--	CONVERT(decimal , 0) As PresentDays1 ,
	--	CONVERT(decimal , 0) As TotalDays2 ,
	--	CONVERT(decimal , 0) As PresentDays2 ,
	--	CONVERT(decimal , 0) As TotalDays3 ,
	--	CONVERT(decimal , 0) As PresentDays3 ,
	--	CONVERT(decimal , 0) As TotalDays4 ,
	--	CONVERT(decimal , 0) As PresentDays4 ,
	--	CONVERT(decimal , 0) As TotalDays5 ,
	--	CONVERT(decimal , 0) As PresentDays5 ,
	--	CONVERT(decimal , 0) As TotalDays6 ,
	--	CONVERT(decimal , 0) As PresentDays6 ,
	--	CONVERT(decimal , 0) As TotalDays7 ,
	--	CONVERT(decimal , 0) As PresentDays7 ,
	--	CONVERT(decimal , 0) As TotalDays8 ,
	--	CONVERT(decimal , 0) As PresentDays8 ,
	--	CONVERT(decimal , 0) As TotalDays9 ,
	--	CONVERT(decimal , 0) As PresentDays9 ,
	--	CONVERT(decimal , 0) As TotalDays10 ,
	--	CONVERT(decimal , 0) As PresentDays10 ,
	--	CONVERT(decimal , 0) As TotalDays11 ,
	--	CONVERT(decimal , 0) As PresentDays11 ,
	--	CONVERT(decimal , 0) As TotalDays12 ,
	--	CONVERT(decimal , 0) As PresentDays12 ,
	--	CONVERT(decimal , 0) As TotalDays13 ,
	--	CONVERT(decimal , 0) As PresentDays13 ,

	--	'' As MyActivity1,
	--	'' As MyActivity2 ,
	--	'' As MyActivity3,
	--	'' As MyActivity4 ,
	--	'' As MyActivity5,
	--	'' As MyActivity6,
	--	'' As MyActivity7,
	--	'' As MyActivity8 ,
	--	'' As MyActivity9,
	--	'' As MyActivity10 ,
	--	'' As MyActivity11,
	--	'' As MyActivity12,
	--	'' As MyActivity13,

	--	'' As GeneralRemark1,
	--	'' As GeneralRemark2 ,
	--	'' As GeneralRemark3 ,
	--	'' As GeneralRemark4,
	--	'' As GeneralRemark5,
	--	'' As GeneralRemark6,
	--	'' As GeneralRemark7,
	--	'' As GeneralRemark8 ,
	--	'' As GeneralRemark9 ,
	--	'' As GeneralRemark10,
	--	'' As GeneralRemark11,
	--	'' As GeneralRemark12,
	--	'' As GeneralRemark13,

	--	'' As PresentAddress ,
	--	'' As  MobileNo,
	--	'' As House ,
		 
	--	CONVERT(decimal , 0) As AttendanceTerm1  ,
	--	CONVERT(decimal , 0) As AttendanceTerm2 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm1 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm2 ,
	--	  '' As BloodGroup ,
	--	  '' As GradeSetIdText ,
	--	  '' As IsDisplayMonthlyAttendanceText ,
	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
	--	'' As ParentEmail ,
	--  '' AS MyGoal,
	--	'' AS MyStrength,
	--	'' AS MyInterestHobby,
	--	'' AS AreaOfInterest,
	--	'' AS Responsibility,
	--	'' AS Achievements,
	--	'' As ImprovementArea,
	--	'' AS ProgressArea,
	--	'' AS MyActivity,
	--	'' As ClassTeacherRemark,
	--	'' AS ClassTeacherName,
	--	'' As HouseRemark,
	--	'' As GeneralRemark,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo,
	--	'' AS FatherMail,
	--	'' AS MotherMail,
	--  CONVERT(bit , 0) As IsDecimal,
	--  '' As Name,
	--'' AS PermanentStreetOne,
	--'' AS PermanentStreetTwo,
	--'' AS PermanentStreetThree,
	--'' AS AdmissionNo,
	--'' AS StudentContactNo,
	--'' AS DescriptiveIndicator ,
	--'' AS DescriptiveIndicator1,
	--'' AS DescriptiveIndicator2,
	--'' AS DescriptiveIndicator3,
	--'' AS DescriptiveIndicator4,
	--'' AS DescriptiveIndicator5,
	--'' AS DescriptiveIndicator6,
	--'' AS DescriptiveIndicator7,
	--'' AS DescriptiveIndicator8,
	--'' AS DescriptiveIndicator9,
	--'' AS DescriptiveIndicator10,
	--'' AS DescriptiveIndicator11,
	--'' AS DescriptiveIndicator12,
	--'' AS DescriptiveIndicator13,
	--'' AS RelativeName,
	--'' AS PresentCity,
	--'' AS Exam1DisplayTitle,
	--'' AS Exam2DisplayTitle	,
	--'' AS Exam3DisplayTitle	,
	--'' AS Exam4DisplayTitle	,
	--'' AS Exam5DisplayTitle	,
	--'' AS Exam6DisplayTitle	,
	--'' AS Exam7DisplayTitle	,
	--'' AS Exam8DisplayTitle	,
	--'' AS Exam9DisplayTitle	,
	--'' AS Exam10DisplayTitle,	
	--'' AS Exam11DisplayTitle,	
	--'' AS Exam12DisplayTitle,	
	--'' AS Exam13DisplayTitle,
	--'' AS ResultSheetAdditionalTitle	--Mantis - 40152
	--,'' AS UIDNumber --add for mantis : 0042613	
		


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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

BEGIN 	

	--Declare @lDecimalConfig nvarchar(20)='', @lOrgId int
	--SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
	--SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId
 
			SELECT 	
				 
				 --@rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Marks,0) AS Marks,
				 
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex,
				 SM.Title AS SubjectName,
				 SAM.ClassSubjectId,
				 ISNULL(AIS.Grade,'') AS Grade,
				 ISNULL(AIS.GradeIndicator,'') AS GradeIndicator,
				 ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
				 CMM.Id
				 --(SELECT EM.FirstName + ' ' + EM.LastName  From sHrm.tEmployeeMaster EM 
				 -- INNER JOIN sSetup.tDivisionMaster DM ON EM.Id = DM.InchargeEmployeeId Where DM.Id = @rDivisionId) AS ClassTeacher,
				 -- ISNULL(SR.TotalDays,0)AS TotalDays,
				 -- ISNULL(SR.PresentDays,0)AS PresentDays,
				 -- CONVERT(bit,@lDecimalConfig) AS IsDecimal,
				 -- ISNULL(SR.GeneralRemark,'') AS GeneralRemark,
				 -- ISNULL(SR.Achievements,'') AS Achievements,
				 -- ISNULL(SR.ResultRemark1,'') AS ResultRemark1,
				 -- ISNULL(SR.ResultRemark2,'') AS ResultRemark2,
				 -- ISNULL(SR.ResultRemark3,'') AS ResultRemark3
					 
			FROM 
			  sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId		
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id And AIS.ExamId=@rExamId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			--LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId AND SR.ExamId = @rExamId -- Mantis : 0027635

	    	 WHERE
				-- ((SAM.ClassSubjectId=@rClass) OR (@rClass=0))
				--And SA.DivisionId =@rDivisionID	
				--And SA.BatchId =@rBatchId
				--AND AIS.ExamId=@rExamId
				--and ((SSA.SubjectActivityId=@rActivityId) OR (@rActivityId=0))
				--AND((SSA.Id=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))	
				--and SSA.OrgId=@rOrgId
				  SA.AcademicId = @rAcademicId
				  AND SA.StatusId = 1		
		 
			 --ORDER BY SA.RollNo
			
END

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

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		--IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		--IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		SchoolNameLabel nvarchar(200),
		MediumLabel nvarchar(100),
		NameLabel nvarchar(200),
		CodeLabel nvarchar(100),
		SUIDLabel nvarchar(100),
		ClassLabel nvarchar(100),
		BirthDateLabel nvarchar(100),
		RollNoLabel nvarchar(100),
		FatherNameLabel nvarchar(100),
		MotherNameLabel nvarchar(100),
		TotalWorkingDaysLabel nvarchar(100),
		TotalPresentDaysLabel nvarchar(100),
		HeightLabel nvarchar(100),
		WeightLabel nvarchar(100),
		SubjectLabel nvarchar(100),
		MaxMarksLabel nvarchar(100),
		TotalLabel nvarchar(100),
		GradeLabel nvarchar(100),
		GrandTotalLabel nvarchar(100),
		ResultStatusLabel nvarchar(100),
		RankNoLabel nvarchar(100),
		PercentileLabel nvarchar(100),
		PercentageLabel nvarchar(100),
		OverallGradeLabel nvarchar(100),
		DisplayAttendanceId int,
		ReportHeaderId int,
		StudentImage varbinary(max)
		
	)	
	 --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,
	ResultSheetAdditionalTitle,
	SchoolNameLabel,
	MediumLabel,
	NameLabel,
	CodeLabel,
	SUIDLabel,
	ClassLabel,
	BirthDateLabel,
	RollNoLabel,
	FatherNameLabel,
	MotherNameLabel,
	TotalWorkingDaysLabel,
	TotalPresentDaysLabel,
	HeightLabel,
	WeightLabel,
	SubjectLabel,
	MaxMarksLabel,
	TotalLabel,
	GradeLabel,
	GrandTotalLabel,
	ResultStatusLabel,
	RankNoLabel,
	PercentileLabel,
	PercentageLabel,
	OverallGradeLabel,
	DisplayAttendanceId,
	ReportHeaderId,
	StudentImage
	)
	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(EM.ResultSheetAdditionalTitle,'') AS ResultSheetAdditionalTitle,
		ISNULL(ALS.SchoolNameLabel,'')AS SchoolNameLabel,
		ISNULL(ALS.MediumLabel,'') AS MediumLabel,
		ISNULL(ALS.NameLabel,'') AS NameLabel,
		ISNULL(ALS.CodeLabel,'') AS CodeLabel,
		ISNULL(ALS.SUIDLabel,'') AS SUIDLabel,
		ISNULL(ALS.ClassLabel,'') AS ClassLabel,
		ISNULL(ALS.BirthDateLabel,'') AS BirthDateLabel,
		ISNULL(ALS.RollNoLabel,'') AS RollNoLabel,
		ISNULL(ALS.FatherNameLabel,'') AS FatherNameLabel,
		ISNULL(ALS.MotherNameLabel,'') AS MotherNameLabel,
		ISNULL(ALS.TotalWorkingDaysLabel,'')AS TotalWorkingDaysLabel,
		ISNULL(ALS.TotalPresentDaysLabel,'') AS TotalPresentDaysLabel,
		ISNULL(ALS.HeightLabel,'') AS HeightLabel,
		ISNULL(ALS.WeightLabel,'') AS WeightLabel,
		ISNULL(ALS.SubjectLabel,'') AS SubjectLabel,
		ISNULL(ALS.MaxMarksLabel,'') AS MaxMarksLabel,
		ISNULL(ALS.TotalLabel,'') AS TotalLabel,
		ISNULL(ALS.GradeLabel,'') AS GradeLabel,
		ISNULl(ALS.GrandTotalLabel,'') AS GrandTotalLabel,
		ISNULl(ALS.ResultStatusLabel,'') AS ResultStatusLabel,
		ISNULL(ALS.RankNoLabel,'') AS RankNoLabel,
		ISNULL(ALS.PercentileLabel,'') AS PercentileLabel,
		ISNULl(ALS.PercentageLabel,'') AS PercentageLabel,
		ISNULL(ALS.OverallGradeLabel,'') AS OverallGradeLabel,
		ISNULL(EM.DisplayAttendanceId,0) AS DisplayAttendanceId,
		ISNULL(EM.ReportHeaderId,0) AS ReportHeaderId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
		SI.StudentPhoto
		ELSE NULL END)AS StudentImage
		--('~/Content/' + A.OrgId + A.StudentId + '.jpg')AS StudentImage
		--'~/Content/9911/9911000000299.jpg' AS StudentImage
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tStreamMaster StM ON CM.StreamId = Stm.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = OM.Id
	 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  ISNULL(EMP.IsOtherUser,0) = 0
		-- AND (
	 --(@rFilterId = 0) -- All
  --   OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
  --   OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
  --   OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
  --  )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign			
--SELECT  '' AS Builder1,'' AS Builder2, T.* FROM sAssessment.tTempAllExam T

 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultSheetWithSubjectActivityExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rFromRollNo Int=0,
	 @rToRollNo Int=0,
	 --@rFromRank int=0,
	 --@rToRank int=0,
	 @rCode nvarchar(20)='',
	 @rStatusId int=0,
	 --@rAcademicId bigint=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0
	 --@rMultiCode nvarchar(max)='' 
	
	

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),
		ExamMaximum2 decimal(10,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(10,2),
		SubjectGrade3 NVarchar(10),
		Obtain3 decimal(5,2),
		ExamMaximum3 decimal(10,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(10,2),	
		SubjectGrade4 NVarchar(10),
		Obtain4 decimal(5,2),
		ExamMaximum4 decimal(10,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(10,2),		
		SubjectGrade5 NVarchar(10),
		Obtain5 decimal(5,2),
		ExamMaximum5 decimal(10,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(10,2),		
		SubjectGrade6 NVarchar(10),
		Obtain6 decimal(5,2),
		ExamMaximum6 decimal(10,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(10,2),		
		SubjectGrade7 NVarchar(10),
		Obtain7 decimal(5,2),
		ExamMaximum7 decimal(10,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(10,2),	
		SubjectGrade8 NVarchar(10),
		Obtain8 decimal(5,2),
		ExamMaximum8 decimal(10,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(10,2),		
		SubjectGrade9 NVarchar(10),
		Obtain9 decimal(5,2),
		ExamMaximum9 decimal(10,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(10,2),		
		SubjectGrade10 NVarchar(10),
		Obtain10 decimal(5,2),
		ExamMaximum10 decimal(10,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(10,2),		
		SubjectGrade11 NVarchar(10),
		Obtain11 decimal(5,2),
		ExamMaximum11 decimal(10,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(10,2),		
		SubjectGrade12 NVarchar(10),
		Obtain12 decimal(5,2),
		ExamMaximum12 decimal(10,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(10,2),		
		SubjectGrade13 NVarchar(10),
		Obtain13 decimal(5,2),
		ExamMaximum13 decimal(10,2),
		IsPresent13 bit,
		
		MaximumMark14 decimal(10,2),		
		SubjectGrade14 NVarchar(10),
		Obtain14 decimal(5,2),
		ExamMaximum14 decimal(10,2),
		IsPresent14 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(10),
		SubjectGradeTerm2 NVarchar(10),
		SubjectGradeTerm3 NVarchar(10),
		IsMarksInDecimal bit,
		column_visible bit,
		Percentile decimal(5,2),
		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,
		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),

		Exam14Name nvarchar(100),	
		TotalMarks14 decimal(8,2),
		TotalObtain14 decimal(8,2),
		Percentage14 decimal(5,2),
		RankNumber14 int,
		ResultGrade14 NVarchar(10),
		Percentile14 decimal(5,2),
		ResultStatus14 Nvarchar(50),
		Exam14CombineExamName 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),
		Exam14Code 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),
		BatchIdText nvarchar(20),
		--IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 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),
		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),
		ObtainedMaximum14 decimal(10,2),
		ResultIndicator nvarchar(50),   
		IsResultIndicator bit,		
		ExamBlock nvarchar(100), 
		AbsentRemarkTerm1 nvarchar(100),    
		AbsentRemarkTerm2 nvarchar(100),
		AbsentRemarkTerm3 nvarchar(100),
		IsPresentTerm1 bit,
		IsPresentTerm2 bit,
		IsPresentTerm3 bit ,        
		SubjectGroupOrderIndex smallint,		
		RelativeName nvarchar(100), 
		SubjectMinTerm1 decimal(10,2), 
		SubjectMinTerm2 decimal(10,2), 
		SubjectMinTerm3 decimal(10,2),  
		BirthDateInWord nvarchar(150), 
		SchoolStamp varbinary(max),  
		SubjectWiseTeacher nvarchar(max), 
		RelativeContactNo nvarchar(50), 
		PENNumber BigInt, 
		ApaarIdNumber nvarchar(50)
		,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)
		,MinimumMark14 decimal(10,2)

		)
	 --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,
	PermanentStreetOne,
	PermanentStreetTwo,
	PermanentStreetThree,
	CasteCategory,
	FeeCategory,
	StudentContactNo,
	ResultIndicator,		
	IsResultIndicator,		
	ExamBlock,             
	--BMI,
	SubjectGroupOrderIndex,		
	RelativeName,  
	BirthDateInWord, 
	SchoolStamp,  
	SubjectWiseTeacher, 
	RelativeContactNo, 
	PENNumber,
	ApaarIdNumber 

	)
	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,
		OI.MarksheetHeaderA4 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,
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		CSM.Title As CasteCategory,      
		ACM.Title AS FeeCategory,
		SC.StudentContactNo AS StudentContactNo,
		R.ResultIndicator as ResultIndicator, 
		EM.IsDisplayResultIndicator as IsResultIndicator, 
		SR.ExamBlock as ExamBlock,        
		--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,			
		ISNULL(SF.RelativeName,'') AS RelativeName, 
		ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord, 
		NULL AS SchoolStamp,		
		[sAttendance].[fSubjectTeacherGet](DM.Id,SM.Id) AS SubjectWiseTeacher,		
		ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo ,
		ISNULL(StuM.PENNumber,0) AS PENNumber,
		ISNULL(StuM.ApaarIdNumber,'') AS ApaarIdNumber

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

	--Select * from #TempAllExam
 --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,	
					 		
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 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)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lCombineExamId) 
				
				--Print @query		
		execute(@query)
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum,
					 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					 
					 
					ExamNameTerm1 = ESGM.Code,
					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,
					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
 
					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
 
					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
	
	
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	drop table #tempcombineExam
	Drop table #TempAllExam
	
 
	END

--SELECT
--		@rBuilder1 AS Builder1,
--		@rBuilder2 AS Builder2,
--		AcademicIdText ,
--		ExamIdText ,
--		CoScholasticScopeIdText ,
--		IsDisplayMonthlyAttendanceText ,
--		ClassIdText ,
--		AcademicId ,
--		ExamName ,
--		StudCode ,
--		StudentName ,
--		RollNo ,
--		ResultStatus ,	
--		ClassName ,		
--		Division ,
--		TotalMark ,
--		TotalObtain ,
--		Percentage ,
--		RankNumber ,
--		ResultGrade ,
--		MaximumMark1 ,		
--		SubjectGrade1 ,
--		Obtain1 ,
--		ExamMaximum1 ,
--		IsPresent1 ,
						
--		MaximumMark2 ,	
--		SubjectGrade2 ,
--		Obtain2 ,
--		ExamMaximum2 ,
--		IsPresent2 ,
				
--		MaximumMark3 ,
--		SubjectGrade3 ,
--		Obtain3 ,
--		ExamMaximum3 ,
--		IsPresent3 ,		
		
--		MaximumMark4 ,	
--		SubjectGrade4 ,
--		Obtain4 ,
--		ExamMaximum4 ,
--		IsPresent4 ,	
				
--		MaximumMark5 ,		
--		SubjectGrade5 ,
--		Obtain5 ,
--		ExamMaximum5 ,
--		IsPresent5 ,	
				
--		MaximumMark6 ,		
--		SubjectGrade6 ,
--		Obtain6 ,
--		ExamMaximum6 ,
--		IsPresent6 ,	
		
--		MaximumMark7 ,		
--		SubjectGrade7 ,
--		Obtain7 ,
--		ExamMaximum7 ,
--		IsPresent7 ,	
		
--		MaximumMark8 ,	
--		SubjectGrade8 ,
--		Obtain8 ,
--		ExamMaximum8 ,
--		IsPresent8 ,	
		
--		MaximumMark9 ,		
--		SubjectGrade9 ,
--		--Obtain9  Default 0,	----remove this line and add below line for mantis: 31081
--		Obtain9 ,
--		ExamMaximum9 ,
--		IsPresent9 ,	
		
		
--		MaximumMark10 ,		
--		SubjectGrade10 ,
--		--Obtain10  Default 0,	--remove this line and add below line for mantis: 31081
--		Obtain10 ,
--		ExamMaximum10 ,
--		IsPresent10 ,	
		
--		MaximumMark11 ,		
--		SubjectGrade11 ,
--		--Obtain11  Default 0,	--remove this line and add below line for mantis: 31081
--		Obtain11 ,
--		ExamMaximum11 ,
--		IsPresent11 ,
		
--		MaximumMark12 ,		
--		SubjectGrade12 ,
--		--Obtain12  Default 0,	--remove this line and add below line for mantis: 31081
--		Obtain12 ,
--		ExamMaximum12 ,
--		IsPresent12 ,
		
--		MaximumMark13 ,		
--		SubjectGrade13 ,
--		--Obtain13  Default 0,	--remove this line and add below line for mantis: 31081
--		Obtain13 ,
--		ExamMaximum13 ,
--		IsPresent13 ,
		
--		Convert (decimal(10,2), 0) AS MaximumMark14 ,		
--		Convert (NVarchar(10), '') AS SubjectGrade14 ,
--		--Obtain13  Default 0,	--remove this line and add below line for mantis: 31081
--		Convert (decimal(5,2),0) AS Obtain14 ,
--		Convert (decimal(10,2), 0) AS ExamMaximum14 ,
--		Convert (bit, 0) AS IsPresent14 ,		
		 
		 
--		SubjectGradeTerm1 ,
--		SubjectGradeTerm2 ,
--		SubjectGradeTerm3 ,
--		IsMarksInDecimal ,
--		column_visible ,
--		Percentile ,
--		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 ,
--		TermScopeId ,		 
--		StudentPhoto ,
--		GradeString ,
--		IsDisplayGradeString ,		 
--		IsDisplayInMarksheet ,
--		IsShowSubjectGrade ,
--		IsIncludeInTotal ,
--		ClassSubjectID ,
--		SubjectId ,
--		--Maximum ,
--		SubjectOrderIndex ,
--		SubjectGrade ,
--		SubjectName ,
--		SubjectCode ,	
--		SubjectMinimum ,		
--		SubjectMaximum ,
--		SubjectObtain  ,
		
--		Exam1Name ,		
--		TotalMarks1 ,		
--		TotalObtain1 ,
--		Percentage1 ,
--		RankNumber1 ,
--		ResultGrade1 ,
--		Percentile1 ,
--		ResultStatus1 ,
--		Exam1CombineExamName ,
				
--		Exam2Name ,	
--		TotalMarks2 ,
--		TotalObtain2 ,
--		Percentage2 ,
--		RankNumber2 ,
--		ResultGrade2 ,
--		Percentile2 ,
--		ResultStatus2 ,
--		Exam2CombineExamName ,
		
--		Exam3Name ,	
--		TotalMarks3 ,
--		TotalObtain3 ,
--		Percentage3 ,
--		RankNumber3 ,
--		ResultGrade3 ,
--		Percentile3 ,		
--		ResultStatus3 ,
--		Exam3CombineExamName ,
		
--		Exam4Name ,	
--		TotalMarks4 ,
--		TotalObtain4 ,
--		Percentage4 ,
--		RankNumber4 ,
--		ResultGrade4 ,
--		Percentile4 ,
--		ResultStatus4 ,
--		Exam4CombineExamName ,
		
--		Exam5Name ,		
--		TotalMarks5 ,
--		TotalObtain5 ,
--		Percentage5 ,
--		RankNumber5 ,
--		ResultGrade5 ,
--		Percentile5 ,
--		ResultStatus5 ,
--		Exam5CombineExamName ,
		
--		Exam6Name ,	
--		TotalMarks6 ,
--		TotalObtain6 ,
--		Percentage6 ,
--		RankNumber6 ,
--		ResultGrade6 ,
--		Percentile6 ,
--		ResultStatus6 ,
--		Exam6CombineExamName ,
		
--		Exam7Name ,		
--		TotalMarks7 ,
--		TotalObtain7 ,
--		Percentage7 ,
--		RankNumber7 ,
--		ResultGrade7 ,
--		Percentile7 ,
--		ResultStatus7 ,
--		Exam7CombineExamName ,
		
--		Exam8Name ,
--		TotalMarks8 ,
--		TotalObtain8 ,
--		Percentage8 ,
--		RankNumber8 ,
--		ResultGrade8 ,
--		Percentile8 ,
--		ResultStatus8 ,
--		Exam8CombineExamName ,
		
		
--		Exam9Name ,	
--		TotalMarks9 ,
--		TotalObtain9 ,
--		Percentage9 ,
--		RankNumber9 ,
--		ResultGrade9 ,
--		Percentile9 ,
--		ResultStatus9 ,
--		Exam9CombineExamName ,
		
--		Exam10Name ,	
--		TotalMarks10 ,
--		TotalObtain10 ,
--		Percentage10 ,
--		RankNumber10 ,
--		ResultGrade10 ,
--		Percentile10 ,
--		ResultStatus10 ,
--		Exam10CombineExamName ,
		
--		Exam11Name ,	
--		TotalMarks11 ,
--		TotalObtain11 ,
--		Percentage11 ,
--		RankNumber11 ,
--		ResultGrade11 ,
--		Percentile11 ,
--		ResultStatus11 ,
--		Exam11CombineExamName ,
		
--		Exam12Name ,	
--		TotalMarks12 ,
--		TotalObtain12 ,
--		Percentage12 ,
--		RankNumber12 ,
--		ResultGrade12 ,
--		Percentile12 ,
--		ResultStatus12 ,
--		Exam12CombineExamName ,

--		Exam13Name ,	
--		TotalMarks13 ,
--		TotalObtain13 ,
--		Percentage13 ,
--		RankNumber13 ,
--		ResultGrade13 ,
--		Percentile13 ,
--		ResultStatus13 ,
--		Exam13CombineExamName ,

--		Convert (nvarchar(100), '') AS Exam14Name ,	
--		Convert (decimal(8,2), 0) AS  TotalMarks14 ,
--		Convert (decimal(8,2), 0) AS  TotalObtain14 ,
--		Convert (decimal(5,2), 0) AS  Percentage14 ,
--		Convert (int, 0) AS  RankNumber14 ,
--		Convert (NVarchar(10), '') AS  ResultGrade14 ,
--		Convert (decimal(5,2), 0) AS  Percentile14 ,
--		Convert (nvarchar(50), '') AS  ResultStatus14 ,
--		Convert (nvarchar(100),'') AS  Exam14CombineExamName ,
		
--		ResultRemark1 ,
--		ResultRemark2 ,
		
--		TotalDays ,
--		PresentDays ,
--		StudentHeight ,
--		StudentWeight ,
--		ExamSeatNo ,
--		ExamId ,
		
--		ExamCode ,
--		Exam1Code ,
--		Exam2Code ,
--		Exam3Code ,
--		Exam4Code ,
--		Exam5Code ,
--		Exam6Code ,
--		Exam7Code ,
--		Exam8Code ,
--		Exam9Code ,
--		Exam10Code ,
--		Exam11Code ,
--		Exam12Code ,
--		Exam13Code ,
--		Convert (nvarchar(20), '') AS Exam14Code,
--		IsDisplayParentName ,
--		FatherName ,
--		MotherName ,
--		IsShowSubjectMark , 
--		IsOptionalSubject ,
--		CoScholasticScopeId ,
--		IsDisplayPrincipalSign ,
--		IsDisplayTeacherSign ,
--		EmployeeSign ,
--		Batch ,
--		ExamNameTerm1 ,
--		ExamNameTerm2  ,
--		ExamNameTerm3 ,
--		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 ,
--		SubjectObtainTerm1 ,	
--		SubjectObtainTerm2 ,
--		SubjectObtainTerm3  ,
--		SubjectMaxTerm1 ,
--		SubjectMaxTerm2 ,
--		SubjectMaxTerm3 ,
--		ContactNo ,
--		PresentAddress ,
--		TeacherSignCaption ,
--		PrincipalSignCaption ,
--		ParentSignCaption ,
--		ImprovementArea ,
--		ProgressArea ,
--		GeneralRemark ,
--		MyActivity ,
--		ClassTeacherRemark ,
--		HouseRemark ,
--		BloodGroup ,
--		BatchIdText ,
--		--IsShowWithDetail ,
--		IsPresent ,
--		GradeTitle ,
--		SubjectHighestDivisionGrade ,
--		SubjectHighestDivisionMark ,
--		HouseId ,
--		HouseName ,
--		AdhaarNumber ,
--		UIdNumber ,
--		FatherContactNo ,
--		MotherContactNo ,
--		FatherMail ,
--		MotherMail ,
--		Gender ,
--		CoordinatorEmployeeSign ,
--		StudentAddress ,
--		SUId ,
--		HighestDivisionMark ,
--		HighestDivisionGrade ,
--		StreamTitle ,
--		AdmissionNo ,
--		AdmissionDate ,
--		MiddleName  ,
--		FatherOccupation ,
--		ResultSheetAdditionalTitle ,
--		IsDecimal ,
--		IsAbsentRemark ,
--		FinalAbsentRemark ,
--		ExamMaximumTerm1 ,
--		ExamMaximumTerm2 ,
--		ExamMaximumTerm3 ,
--		PermanentStreetOne ,
--		PermanentStreetTwo ,
--		PermanentStreetThree ,
--		CasteCategory ,
--		FeeCategory ,
--		StudentContactNo ,
--		ObtainedMaximum1 ,
--		ObtainedMaximum2 ,
--		ObtainedMaximum3 ,
--		ObtainedMaximum4 ,
--		ObtainedMaximum5 ,
--		ObtainedMaximum6 ,
--		ObtainedMaximum7 ,
--		ObtainedMaximum8 ,
--		ObtainedMaximum9 ,
--		ObtainedMaximum10 ,
--		ObtainedMaximum11 ,
--		ObtainedMaximum12 ,
--		ObtainedMaximum13 ,
--		Convert (decimal(10,2), 0) AS ObtainedMaximum14 ,
--		ResultIndicator ,   
--		IsResultIndicator ,		
--		ExamBlock , 
--		AbsentRemarkTerm1 ,    
--		AbsentRemarkTerm2 ,
--		AbsentRemarkTerm3 ,
--		IsPresentTerm1 ,
--		IsPresentTerm2 ,
--		IsPresentTerm3  ,        
--		SubjectGroupOrderIndex ,		
--		RelativeName , 
--		SubjectMinTerm1 , 
--		SubjectMinTerm2 , 
--		SubjectMinTerm3 , 
--		BirthDateInWord , 
--		SchoolStamp ,  
--		SubjectWiseTeacher , 
--		RelativeContactNo , 
--		--PENNumber , 
--		--ApaarIdNumber 
--		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
--		,Convert (decimal, 0) AS MinimumMark14
--		,'' As SubjectRemarkOther
--	 FROM sAssessment.tTempAllExam T
	
	
--end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultStatistics]	 
   @rBuilder1 nvarchar(max)='', 
   @rBuilder2 nvarchar(max)='', 
   
   @rBatchId int,
   @rClassId int,
   @rDivisionId int,
   @rExamSubGroupId int,
   
  
   @rOrgId int,
   @rClass nvarchar(MAX)='',
   @rStatusId int = 0,
   @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--ESGM.Title AS Exam,
			--StuM.Code,
			--StuM.FirstName+' '+StuM.LastName AS Name,
			--A.RollNo,
			--R.AcademicId,
			--RD.Obtain,
			--R.ResultStatus,
			CM.ClassName AS Class,
			CM.ClassId AS ClassId,
			CM.OrderIndex AS ClassOrderIndex,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			(SELECT COUNT(A.AcademicId) FROM sStudent.vStudentAcademic A WHERE A.DivisionId = DM.Id AND A.BatchId = @rBatchId AND ((A.StatusId=@rStatusId) or (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS TotalStudents,
			(SELECT COUNT(A.AcademicId) FROM sStudent.vStudentAcademic A INNER JOIN 
			 sAssessment.tResult R ON A.AcademicId = R.AcademicId  INNER JOIN 
			 sAssessment.tExamMaster E ON R.ExamId = E.Id 
			 WHERE A.DivisionId = DM.Id AND A.BatchId = @rBatchId AND E.ExamSubGroupId = @rExamSubGroupId AND ((A.StatusId=@rStatusId) or (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS AppearedStudents,
			 (SELECT COUNT(A.AcademicId) FROM sStudent.vStudentAcademic A INNER JOIN 
			 sAssessment.tResult R ON A.AcademicId = R.AcademicId  INNER JOIN 
			 sAssessment.tExamMaster E ON R.ExamId = E.Id 
			 WHERE A.DivisionId = DM.Id AND A.BatchId = @rBatchId AND E.ExamSubGroupId = @rExamSubGroupId AND R.ResultStatus = 'FAIL' AND ((A.StatusId=@rStatusId) or (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS FailedStudents,			 			 
			(SELECT COUNT(A.AcademicId) FROM sStudent.vStudentAcademic A INNER JOIN 
			 sAssessment.tResult R ON A.AcademicId = R.AcademicId  INNER JOIN 
			 sAssessment.tExamMaster E ON R.ExamId = E.Id 
			 WHERE A.DivisionId = DM.Id AND A.BatchId = @rBatchId AND E.ExamSubGroupId = @rExamSubGroupId AND R.ResultStatus = 'PASS' AND ((A.StatusId=@rStatusId) or (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS PassedStudents,			 	 
			'0' AS TotalResult,		 
			'0' AS ResultOnAppearedStudents,
			'0' AS GracedStudents,
			'0' AS RepeatorStudents
 
	FROM 
	
	sSetup.tDivisionMaster DM
	--INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	
	WHERE 	
 
		((CM.ClassId=@rClassId) OR (@rClassId=0))		 
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND DM.OrgId = @rOrgId
		AND Cm.BatchId = @rBatchId
		AND EM.ExamSubGroupId =@rExamSubGroupId
		
		AND    (ISNULL(Cm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultWithAllSubjectListFilterGet]
	 
   	 @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,
	 @rFromMarks decimal(5,2)=0,
	 @rToMarks decimal(5,2)=0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

   
   CREATE TABLE #TempExamFilter(ResultId bigint)
    INSERT INTO  #TempExamFilter (ResultId)
    SELECT Distinct R.Id AS ResultId
    FROM 
	sStudent.tAcademic A 
	INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId    
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId AND	((EM.Id=@rExamId )	OR (@rExamId = 0))AND EM.BatchId = @rBatchId	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sSetup.tClassSubject CS ON Cs.Id = Ed.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	INNER JOIN sAssessment.tResultDetail RD ON ED.Id=RD.ExamDetailId 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0)) 
		AND R.Id = RD.ResultId
	WHERE 
		 EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((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 ((RD.Obtain>=@rFromMarks) OR (@rFromMarks=0))
		AND ((RD.Obtain<=@rToMarks) OR(@rToMarks=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) 

    --SELECT *From #TempExamFilter

	SELECT 
			@rFromMarks AS FromMarks,
			@rToMarks AS ToMarks,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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.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
      
	FROM 
	
	sStudent.tAcademic A 
	INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId    
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId AND	((EM.Id=@rExamId )	OR (@rExamId = 0))AND EM.BatchId = @rBatchId	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sSetup.tClassSubject CS ON Cs.Id = Ed.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	INNER JOIN sAssessment.tResultDetail RD ON ED.Id=RD.ExamDetailId 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0)) 
		AND R.Id = RD.ResultId
	INNER JOIN #TempExamFilter TEF ON TEF.ResultId = R.Id
	AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) 
		order by A.RollNo,CS.OrderIndex 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultWithAllSubjectListFilterGet1]
	 
   	 @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,
	 @rFromMarks decimal(5,2)=0,
	 @rToMarks decimal(5,2)=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
   
   CREATE TABLE #TempExamFilter(ResultId bigint)
    INSERT INTO  #TempExamFilter (ResultId)
    SELECT Distinct R.Id AS ResultId
    FROM 
	sStudent.tAcademic A 
	INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId    
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId AND	((EM.Id=@rExamId )	OR (@rExamId = 0))AND EM.BatchId = @rBatchId	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sSetup.tClassSubject CS ON Cs.Id = Ed.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	INNER JOIN sAssessment.tResultDetail RD ON ED.Id=RD.ExamDetailId 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0)) 
		AND R.Id = RD.ResultId
	WHERE 
		 EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((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 ((RD.Obtain>=@rFromMarks) OR (@rFromMarks=0))
		AND ((RD.Obtain<=@rToMarks) OR(@rToMarks=0))
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
	    AND	A.BatchId = @rBatchId 

    --SELECT *From #TempExamFilter

	SELECT 
			@rFromMarks AS FromMarks,
			@rToMarks AS ToMarks,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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.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
      
	FROM 
	
	sStudent.tAcademic A 
	INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId    
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId AND	((EM.Id=@rExamId )	OR (@rExamId = 0))AND EM.BatchId = @rBatchId	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sSetup.tClassSubject CS ON Cs.Id = Ed.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	INNER JOIN sAssessment.tResultDetail RD ON ED.Id=RD.ExamDetailId 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0)) 
		AND R.Id = RD.ResultId
	INNER JOIN #TempExamFilter TEF ON TEF.ResultId = R.Id
		order by A.RollNo,CS.OrderIndex 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultWithAllSubjectListGet]
	 
   	@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,
	@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,
			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.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,
			(EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			ISNULL(RD.AbsentRemark,'') AS AbsentRemark
      
	FROM 
	
	sStudent.tAcademic A 
	INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId    
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId AND	((EM.Id=@rExamId )	OR (@rExamId = 0))AND EM.BatchId = @rBatchId	
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sSetup.tClassSubject CS ON Cs.Id = Ed.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sAssessment.tResultDetail RD ON ED.Id=RD.ExamDetailId 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0)) 
		AND R.Id = RD.ResultId
	LEFT JOIN sHrm.tEmployeeMaster EmpM ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.StatusId = 7
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	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
	
			
	WHERE 
	     
	   --(CS.ClassId=@rClassId OR @rClassId=0) 
		 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 
		(
			(@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)))
		) 
		order by A.RollNo,CS.OrderIndex 

		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectAnalysisBatchwise]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 --@rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 --@rExamId int,
     --@rExamSubGroupId1 int=0,
     --@rExamSubGroupId2 int=0,
	 @rCode nvarchar(20),
	 @rFromRollNo int =0,
	 @rToRollNo int =0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rExamId1 int ,
	 @rExamId2 int ,
	 @rBatchId1 int,
	 @rBatchId2 int,
	 @rClassStatusId int=0 ,
	 @rIsDisplayAvgTotal bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
 
	BEGIN
	
CREATE TABLE #Temp_StudentId (StudentId bigint);
	INSERT INTO #Temp_StudentId
	SELECT A1.StudentId From sStudent.tAcademic A1 
	INNER JOIN
	sStudent.tAcademic A2 ON A1.StudentId = A2.StudentId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A1.StudentId
	WHERE A1.BatchId =  @rBatchId1 AND A2.BatchId = @rBatchId2
	AND (A1.ClassId=@rClassId OR @rClassId=0) 
	AND (A1.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND ((A1.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((A1.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND SM.StatusId = 1
	AND ((A1.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	
	
CREATE TABLE #Temp_Academic (tempAcademicId bigint);
INSERT INTO #Temp_Academic 
SELECT  A.Id As tempAcademicId FROM sAssessment.tResult R 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		WHERE BM.Id = @rBatchId2 AND R.ExamId =@rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		  
	--SELECT * FROM #temp
	--RETURN 	

CREATE TABLE #tmp
(
IsDisplayAvgTotal int,
Builder1 nvarchar(max),
Builder2 nvarchar(max),
ExamId int,
Exam nvarchar(300),
BatchId int,
BatchName nvarchar(300),
Code nvarchar(200),
Name nvarchar(max),
RollNo int,
AcademicId bigint,
Obtain decimal(5,2),
ResultStatus nvarchar(100),
Class nvarchar(200),
ClassId int,
Division nvarchar(200),
DivisionId int,
DivisinOrderIndex int,
TotalMarks decimal(8,2),
TotalObtain decimal(8,2),
Percentage  decimal(5,2),
RankNumber int,
ResultGrade nvarchar(20),
ClassSubject nvarchar(200),
ResultDetailId bigint,
ResultId bigint,
SubjectId int,
Maximum decimal(10,2),
SubjectGrade nvarchar(200),
IsMarkInDecimal bit,
SubjectCode nvarchar(200),
SubjectOrderIndex int,
ClassOrderIndex int,
IsPresent bit,
IsGrade bit,
IsPercentage bit,
IsResultStatus bit,
IsRankNo  bit,
Minimum decimal(10,2),
GraceMark decimal(5,2),
DecimalFormat nvarchar(20),
IsOptional bit,
PresentDays decimal(6,2),
TotalDays decimal(6,2),
AvgTotal decimal(6,2)

)

INSERT INTO #tmp
	SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			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,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal
			
			--RD.SubjectGrade AS TermSubjectGrade,
			--RD.SubjectGrade AS SubjectGrade
			--1 As ExamNo
	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
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			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
			
	WHERE 
			
		EM.BatchId = @rBatchId1
		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 (@rExamSubGroupId1 = 0))		
		AND ((EM.Id=@rExamId1 )	OR (@rExamId1 = 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 = @rBatchId1
		--AND BM.Id = @rBatchId1
		AND R.ExamId = @rExamId1
		 AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

UNION 
	
		SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A2.RollNo,
			--temp.tempAcademicId,
			A2.Id AS AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM2.DisplayTitle AS Class,
			Cm2.Id AS ClassId,
			DM2.DisplayTitle AS Division,
			DM2.Id AS DivisionId,
			DM2.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,
			CM2.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,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal

			--2 As ExamNo
	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
			INNER JOIN #Temp_Academic temp ON temp.tempAcademicId= A.Id  
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			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
			INNER JOIN sStudent.tAcademic A2 ON A2.StudentId = TEMP2.StudentId AND A2.BatchId = @rBatchId1
			INNER JOIN sSetup.tClassMaster CM2 ON CM2.Id=A2.ClassId
			INNER JOIN sSetup.tDivisionMaster DM2 ON DM2.Id=A2.DivisionId
	WHERE 
			
		EM.BatchId = @rBatchId2
		--AND (A.ClassId=@rClassId OR @rClassId=0)  
		--AND (A.ClassId=temp.tempClassId )
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0))
		--AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		--AND (A.DivisionId=temp.tempDivisionId )
		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 = @rExamSubGroupId2) OR (@rExamSubGroupId2 = 0))		
		AND ((EM.Id=@rExamId2 )	OR (@rExamId2 = 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 = @rBatchId2 ))
		--AND ((BM.Id = @rBatchId2))
		AND R.ExamId = @rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,ClassOrderIndex
	--	SELECT * FROM #temp
	--RETURN 
	--Select AvgTotal from #tmp tmp1 Where tmp1.ExamId = 993100076 AND tmp1.AcademicId = tmp.AcademicId
	Select *,
	(Select AvgTotal from #tmp tmp1 Where tmp1.ExamId = @rExamId1 AND tmp1.AcademicId = tmp.AcademicId AND tmp1.SubjectId = tmp.SubjectId)-
	(Select AvgTotal from #tmp tmp1 Where tmp1.ExamId = @rExamId2 AND tmp1.AcademicId = tmp.AcademicId AND tmp1.SubjectId = tmp.SubjectId) AS SubjectDifference,
	(Select TOP 1 Percentage from #tmp tmp1 Where tmp1.ExamId = @rExamId1 AND tmp1.AcademicId = tmp.AcademicId AND tmp1.SubjectId = tmp.SubjectId) - 
	(Select TOP 1 Percentage from #tmp tmp1 Where tmp1.ExamId = @rExamId2 AND tmp1.AcademicId = tmp.AcademicId AND tmp1.SubjectId = tmp.SubjectId) AS SubjectPerDifference,
	--(CASE WHEN IsDisplayAvgTotal = 1 AND IsPresent = 1 THEN AvgTotal
	--	  WHEN IsDisplayAvgTotal = 0 AND IsPresent = 1 THEN TotalObtain
	--	  ELSE 0
	--END ) AS SubjectWiseTotalDiff
	(Select (CASE WHEN IsDisplayAvgTotal = 1 THEN SUM(AvgTotal)
		  WHEN IsDisplayAvgTotal = 0 THEN (TotalObtain)
		  ELSE 0 END )from #tmp tmp1 
		  Where tmp1.ExamId = @rExamId1 AND tmp1.AcademicId = tmp.AcademicId  Group By IsDisplayAvgTotal,TotalObtain) - 
	(Select (CASE WHEN IsDisplayAvgTotal = 1 THEN SUM(AvgTotal)
		  WHEN IsDisplayAvgTotal = 0 THEN (TotalObtain)
		  ELSE 0 END )from #tmp tmp1 
		  Where tmp1.ExamId = @rExamId2 AND tmp1.AcademicId = tmp.AcademicId  Group By IsDisplayAvgTotal,TotalObtain)
	AS SubjectWiseTotalDiff

	  from #tmp tmp
		END
		DROP Table #Temp_Academic
		DROP Table #Temp_StudentId
		DROP TABLE #tmp
		
		----For Report Dataset
		--SELECT 
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	EM.DisplayTitle AS Exam,
		--	EM.Id AS ExamId,
		--	StuM.Code,
		--	[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		--	A.RollNo,
		--	--temp.tempAcademicId,
		--	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,
		--	SR.PresentDays,
		--	SR.TotalDays,
		--	BM.Id As BatchId,
		--	BM.Title As BatchName
		--	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
		--	INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
		--	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
		--	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		--	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			


			--SELECT 
			--0 AS IsDisplayAvgTotal,
			--'' AS Builder1,
			--'' AS Builder2,
			--0 AS ExamId,
			--'' AS Exam,
			--0 As BatchId,
			--'' As BatchName,
			--''  AS Code,
			--'' AS Name,
			--0 AS RollNo,
			----temp.tempAcademicId,
			--0 AS AcademicId,
			--0 AS Obtain,
			--'' AS ResultStatus,
			--'' AS Class,
			--0  AS ClassId,
			--'' AS Division,
			--0 AS DivisionId,
			--0 AS DivisinOrderIndex,
			--0 AS TotalMarks,
			--0 AS TotalObtain,
			--0 AS Percentage,
			--0 AS RankNumber,
			--'' AS ResultGrade,
			--'' AS ClassSubject,
			--0 AS ResultDetailId,
			--0 AS ResultId,
			--0 AS SubjectId,
			--0 AS Maximum,
			--'' AS SubjectGrade, 
			
			--0 AS IsMarksInDecimal,
			----SM.OrderIndex AS SubjectCode,
			--'' AS SubjectCode,
			--0 AS SubjectOrderIndex,
			--0 AS ClassOrderIndex,
			--0 AS IsPresent,
			-- 0 AS IsGrade,
			--0 AS IsPercentage,
			--0 AS IsResultStatus,
			--0 AS IsRankNo ,
			--0 AS  Minimum,
			--0 AS GraceMark,
			--'' AS DecimalFormat,
			--0 AS IsOptional,
			--0 AS PresentDays,
			--0 AS TotalDays,
			--0 As AvgTotal,
			-- 0 AS SubjectDifference,
			-- 0 AS SubjectPerDifference,
			-- 0 AS SubjectWiseTotalDiff
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectListAbsentStudentGet]
	 
   	 @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
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 

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

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			RD.AbsentRemark
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN 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
	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 RD.IsPresent = 0
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) 
	ORDER BY
		A.RollNo,CS.OrderIndex 

		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR 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
	 
	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
	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
		order by A.RollNo,CS.OrderIndex 

		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentAllBatchResultGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
    @rSubjectId int=0,
	--@rBatchId int,
	@rClassId int=0,
	@rDivisionId int=0,
	@rExamSubGroupId int=0,
	@rCode nvarchar(20)='',
	@rFromRollNo int=0,
	@rToRollNo int=0,
	@rFromRank int=0,
	@rToRank int=0,
	@rGrade nvarchar(20)='',
	@rFromPercentage decimal(5,2)=0,
	@rToPercentage decimal(5,2)=0,
	@rExamSubGroup nvarchar(MAX)='',
	@rStatusId int = 0,
	@rClassStatusId int=0
	 
	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		--R.AcademicId,
		ESGM.Title AS ExamName,
		 [sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		StuM.Id AS StudentId,
		A.RollNo,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		CM.OrderIndex AS ClassOrderIndex,
		R.Percentage,
		StuM.Code,
	--	CM.Title AS ClassTitle,
	--	DM.Title AS DivisionTitle,
	--	a.CreatedDateTime,
		BM.Title AS BatchName,
		R.ResultGrade
		
	
FROM 
			sAssessment.tResult R 
			INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId
			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 sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM  ON StuM.OrgId = OM.Id
			
	WHERE 
	
		--	E.BatchId = @rBatchId 
		--(A.ClassId=@rClassId OR @rClassId=0) 
		 --((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		--AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 (A.ClassId=@rClassId OR @rClassId=0) 
		 AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		 AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		 AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		 AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		 AND E.IsProcessResult = 1
		
		AND ((R.Percentage>=@rFromPercentage) OR(@rFromPercentage=0))
		AND((R.Percentage<=@rToPercentage)OR(@rToPercentage=0))
		----AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId =0))
		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND (ISNULL(ESGM.Id,0) IN (Select item from sCommon.fnsplit(@rExamSubGroup,','))OR @rExamSubGroup='')
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentAllBatchResultWithDetailGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
    @rSubjectId int	,
	--@rBatchId int,
	@rClassId int,
	@rDivisionId int,
	@rExamSubGroupId int,
	@rCode nvarchar(20),
	@rFromRollNo int,
	@rToRollNo int,
	@rFromRank int,
	@rToRank int,
	@rGrade nvarchar(20),
	@rFromPercentage decimal(5,2)=0,
	@rToPercentage decimal(5,2)=0,
	@rDepartmentId int=0,
	@rClassStatusId int=0

	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		--R.AcademicId,
		ESGM.Title AS ExamName,
		StuM.Id AS StudentId,
		  [sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		--A.RollNo,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		CM.OrderIndex AS ClassOrderIndex,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.Percentile,
		StuM.Code,
	--	CM.Title AS ClassTitle,
	--	DM.Title AS DivisionTitle,
	--	a.CreatedDateTime,
		
		R.ResultGrade,
		R.ResultStatus,
		BM.Title AS BatchName,
		
		
		
		
		
		
		
			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,			 	
			E.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
	   
			--CS.OrderIndex AS SubjectOrderIndex,
			ISNULL(E.Remark1,'') AS Remark1,
			ISNULL(E.Remark2,'') AS Remark2,
			E.DisplayTitle,
			E.IsRankNo, 
			E.IsGrade,
			E.IsPercentile,
			E.IsPercentage,
			E.IsSubjectPercentile,
			E.IsProcessResult,
			E.IsMarksInDecimal,
			E.IsNegativeMarks,
			E.IsIncludeCoScholastic,
			E.IsOnPrePrinted,
			E.IsDisplayPhoto,
			E.IsDisplayBirthDate,
			E.IsLockForEdit,
			E.IsDisplaySchoolName,			
			E.IsDisplayAttendance,
			E.IsDisplayHeightWeight,
			E.IsResultStatus,
			REPLICATE(',',E.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',E.DetailAdjustment) AS DetailAdjustmentText,
			E.FooterAdjustment,
			E.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,
			E.TermScopeId,
			--SI.StudentPhoto,
			CASE WHEN ROW_NUMBER() OVER (PARTITION BY SI.StudentId  ORDER BY SI.StudentId ) =1 THEN SI.StudentPhoto ELSE 0x END AS StudentPhoto,
			--OVER(ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevCol
			--COALESCE(NULLIF(SI.StudentPhoto,0x), SI.StudentPhoto) AS StudentPhoto,
			--@GradeString AS GradeString,
			E.IsDisplayGradeString

		
		
	
FROM 
			sAssessment.tResult R 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			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 sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			
			
			
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			--INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			--INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			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 sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			--INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		
			
	WHERE 
	
	
			
	--	E.BatchId = @rBatchId 
		(CM.DepartmentId=@rDepartmentId OR @rDepartmentId=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))
		 --((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		--AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND E.IsProcessResult = 1
		----AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId =0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
	
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentAllExamResultGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int,
	 @rClassId int=0,
	 @rDivisionId int=0,
	  @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rExamSubGroup nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		R.AcademicId,
		ESGM.Title AS Exam,
		  [sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.Percentage,
		StuM.Code,
		CM.Title,
		DM.Title,
		R.ResultStatus,
		ISNULL(SI.StudentPhoto,0x) AS StudentPhoto --Add for mantis : 0040248
	
FROM 
			sAssessment.tResult R 
			INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId
			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 sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id --Add for mantis : 0040248
			
	WHERE 
			
		E.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND E.IsProcessResult = 1
		
		AND ((R.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		--AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		
		--AND ((R.ExamId = @rExamId) OR (@rExamId =0))
		AND ((ESGM.Id=@rExamSubGroupId) OR (@rExamSubGroupId=0))
		AND ((E.Id=@rExamId )	OR (@rExamId = 0))
		
		 AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rExamSubGroup,','))OR @rExamSubGroup='')
		  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
		  AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by ESGM.OrderIndex
		--AND ((StuM.Code=@rCode) OR (@rCode=''))
		
		--order by A.RollNo,CS.OrderIndex 
		--AND A.id = 1005000000007
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentAnalysisDetailsGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rSubjectId int = 0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rOrgGroupBatchId int=0,
	 @rIsPercentageDisplay bit=0
	
	 --@rFromRank int=0,
	 --@rToRank int=0,
	 --@rGrade nvarchar(20)='',
	 --@rResultId bigint=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,
	 --@rMultiCode nvarchar(max)=''
	
	 --,@rcolumn_visible bit
	

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2) Default 0,		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2) Default 0,	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2) Default 0,
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2) Default 0,	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2) Default 0,		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2) Default 0,		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2) Default 0,		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2) Default 0,	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2) Default 0,		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2) Default 0,		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2) Default 0,		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2) Default 0,		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150) default '',		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150) default '',	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150) default '',	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150) default '',	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150) default '',		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150) default '',	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150) default '',		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150) default '',
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150) default '',	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150) default '',	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150) default '',	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150) default '',	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		--IsDetail bit,
		IsPercentageDisplay bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		--IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(25),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo int,
		AdmissionDate Date
		
	)	
	 --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,
	IsPercentageDisplay,
	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
	)
	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,
		@rIsPercentageDisplay AS IsPercentageDisplay,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		RD.KrupaMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		--@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm1,
	    ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm2,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm1,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm2,
	    HM.Title As HouseName,HM.Id as HouseId,
	    ISNULL(SO.AdhaarNumber,'') As AdhaarNumber,
	    ISNULL(SO.UIdNumber,'') As UIdNumber,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		(SC.PresentStreetOne +' '+ SC.PresentStreetTwo +' '+ SC.PresentStreetThree +' '+ SC.PresentCity +' '+ SC.PermanentState) AS StudentAddress,
		ISNULL(Stum.SUId,'') AS SUId,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,
		ISNULL(StM.Title,'') AS StreamTitle,
		ISNULL(StuA.AdmissionFormNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS Admissio
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tStreamMaster StM ON CM.StreamId = Stm.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		--AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		--AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		--AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		--AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		--AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		--AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		--AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		--AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		AND  ISNULL(EMP.IsOtherUser,0) = 0
		-- AND (
	 --(@rFilterId = 0) -- All
  --   OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
  --   OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
  --   OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
  --  )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	--AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	AND StuM.StatusId = 1
	Order By ED.DisplayOrder

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentClassWise]
	 
	  --@rAcademicId bigint=0,
	 @rExamId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int =0,
	 @rStatusId int=0	
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			-- CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
			 CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
			 CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
			 CONVERT (nvarchar(20),@rDivisionId) AS DivisionIdText,
			 --CONVERT(nvarchar(20),@rBatchId) AS BatchIdText,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A	
				INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND SO.GenderId=2) AS TotalGirls,
		
			 (Select COUNT(A.Id) from sStudent.tAcademic A
			 INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1) AS TotalBoys,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=2 AND SM.StatusId=3) AS LeftGirls,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1 AND SM.StatusId=3) AS LeftBoys,
			
			
			(Select COUNT(R.AcademicId) from sAssessment.tResult R 
				 INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				 INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				 INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2) AS AppearedGirls,
				 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND So.GenderId=1) AS AppearedBoys,	
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND RD.IsPresent=0) AS AbsentGirls,
				 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				  AND RD.IsPresent=0) AS AbsentBoys,
			 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				 INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				 INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				 INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
					AND R.ResultStatus='PASS') AS PassedGirls,    
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE  A.ClassId=@rClassId  AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND  A.BatchId=@rBatchId  AND  R.ExamId=@rExamId  AND SO.GenderId=1
					AND R.ResultStatus='PASS') AS PassedBoys,      
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther  SO ON SO.StudentId=A.StudentId
				WHERE  A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND  A.BatchId=@rBatchId AND  R.ExamId=@rExamId AND SO.GenderId=2
					 AND R.ResultStatus='PROMOTED') AS PassWithGraceGirls,
				
			 (Select COUNT(R.AcademicId) from  sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id =R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther  SO ON SO.StudentId=A.StudentId
				WHERE  A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND   R.ExamId=@rExamId AND SO.GenderId=1
					AND R.ResultStatus='PROMOTED') AS PassWithGraceBoys,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON  SO.StudentId=A.StudentId
				WHERE   A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0))  AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
					AND R.ResultStatus='FAIL') AS FailedGirls,
					
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
						AND R.ResultStatus='FAIL') AS FailedBoys,
						
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId) Total
			 
			FROM 
			sAssessment.tExamMaster EM 
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
 
	WHERE 
		  ((EM.Id=@rExamId) OR (@rExamId=0))
		 AND((CM.Id=@rClassId) OR (@rClassId=0))
		 AND((DM.Id=@rDivisionId) OR (@rDivisionId=0))
 
 		AND EM.BatchId=@rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentDynamicRemarkSub]
	 
	@rExamId bigint,
	@rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

Select 
ERS.Title,
SER.Remark 
from sAssessment.tExamRemarkSetup ERS 
INNER JOIN sAssessment.tStudentExamRemark SER ON ERS.Id = SER.ExamRemarkSetupId
WHERE 
ERS.ExamId = @rExamId 
AND SER.AcademicId = @rAcademicId
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentGradeAnalysisGenderCatagoryWise]
	 
	  --@rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int =0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rClass nvarchar(MAX)='',
	 @rStatusId int =0,
	 @rClassStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
	
	select 
	@rBuilder1 AS Builder1,
 
	
		 count(R.id),
		GM.Title AS Gender,
		R.ResultGrade,
		ISNULL(CCM.Title,'') AS CastCatagory,
		A.ClassId,
		A.DivisionId,
		CM.Title AS ClassName,
		DM.Title AS DivisionName
	 
		 
 from sAssessment.tResult  R
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		Inner join sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId 
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId 	
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
		LEFT  JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId

		
	where (A.ClassId=@rClassId OR @rClassId=0)
		AND (A.DivisionID=@rDivisionId Or @rDivisionId=0)
		and A.BatchId=@rBatchId
		and EM.ExamSubGroupId=@rExamSubGroupId
		AND    (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		and ((sm.StatusId=@rStatusId) or (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		 Group by R.ResultGrade, GM.Title,CCM.Title,A.ClassId,A.DivisionId,CM.Title,DM.Title 
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentGradeAnalysisSubjectWise]
	 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rGroupId int=0

	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
   SELECT 
		COUNT(RD.id),
		@rBuilder1 AS Builder1,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		CS.IsOptional ,
		DM.Id AS DivisionId,
		Dm.DisplayTitle as DivisionName,
		Cm.Id AS ClassId,
		CM.DisplayTitle AS ClassName,
		ISNULL(GD.MarkRange,'') AS MarkRange,
		SM.OrderIndex AS SubjectOrderIndex,
		GM.Title AS Gender,
		GM.Id AS GenderId,
		GD.GradeSetId,
		GD.Minimumscore,

		CASE WHEN @rGroupId=1 THEN DM.Id
				WHEN @rGroupId=2 THEN CM.Id END AS GroupId,
				
		CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle END AS GroupName,
				
		CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex END AS OrderIndex,
				
		CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class' END AS GroupTitle,
		@rBatchId AS BatchId,
		SUM(CASE WHEN RD.IsPresent = 1 THEN 0 ELSE 1 END) AS AbsentCount    --Mantis 30006
				
  FROM 
		sAssessment.tResultDetail  RD
		Inner join sAssessment.tResult R ON R.Id=Rd.ResultId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId 	
		INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode		
   WHERE 
	    EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND (ISNULL(Cm.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	    and((STM.StatusId=@rStatusId) or (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
   GROUP BY 
		RD.SubjectGrade,GD.MarkRange,SM.Title,CS.IsOptional ,DM.Id,DM.DisplayTitle,CM.Id,CM.DisplayTitle,SM.OrderIndex,GM.Title,GM.Id,GD.GradeSetId,GD.Minimumscore
		,Dm.OrderIndex,Cm.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentMultiSubjectAnalysisGet]
	 
	  
     @rClassId int=0,
	 @rDivisionId int=0,
	 --@rExamSubGroupId int=0,
	 @rExamId int,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 --@rGroupByid int=0,

	 --@rOrgId  int=0,
	 --@rSubject nvarchar(MAX)=''
	 @rCode nvarchar(20)='' --mentis : 0031596
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE @lExamIds nvarchar(500)

select @lExamIds = 
STUFF(
(SELECT ', ' + convert(nvarchar(500), EM.Id, 120)
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id 
where  EC.ExamId =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId
FOR XML PATH (''))
, 1, 1, '')
--Select @lExamIds
	SELECT
		--0 AS GradeCount,
		(Select Title from vExamSubGroupMaster Where ExamId =@rExamId) AS Builder1,
		A.Id As AcademicId ,
		A.StudentId As StudentId ,
		A.RollNo As RollNo ,
		STM.FirstName As StudentName ,
		STM.MiddleName As FatherName ,
		STM.LastName As SurName,
		STM.FirstName+' '+STM.MiddleName+' '+STM.LastName AS Name ,
		--EM.DisplayTitle As ExamName ,
		ESGM.Title AS ExamName,
		CM.Id As ClassId, 
		CM.Title As Class ,
		CM.DisplayTitle As ClassName ,
		DM.Id As DivisionId, 
		DM.Title As Division ,
		DM.DisplayTitle As DivisionName ,
		SM.Title AS SubjectName,
		RD.Obtain AS ObtainMarks,
		SM.OrderIndex AS SubjectOrderIndex
		--GD.GradeSetId AS GradeSetId,	
	from 
		sAssessment.tResultDetail  RD
		INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId
		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.tStudentMaster StuM ON StuM.Id=A.StudentId
		--LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		--GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		--INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	where 
		--EM.ExamSubGroupId=@rExamSubGroupId
		(EM.Id IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='')
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
	order by 
		A.RollNo

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentOptionalSubjectListGet]
         
	@rBatchId int,
	@rClassId bigint,         
    @rDivisionId bigint,
    @rSubjectId bigint ,
	@rClassStatusId int=0   ,
	@rStatusId int=1,
    @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)=''
      
AS
SET NOCOUNT ON

BEGIN
	SELECT
		A.Id AS AcademicId,
		SM.FirstName +' '+SM.LastName AS  StudentName,
		SM.Code,
		A.RollNo,
		ISNULL((SELECT  (STUFF(( SELECT  ',' + ISNULL(SM.Title , ',') FROM sSetup.tSubjectMaster SM
		INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = SM.Id AND CS.IsOptional = 1
		INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = CS.Id
		WHERE ((CS.SubjectId = @rSubjectId) OR @rSubjectId = 0)
		FOR XML PATH(''), TYPE).
		value('.','NVARCHAR(MAX)'),1,1,''))),'') As SubjectName,
		ISNULL(SC.StudentContactNo, '-') AS StudentContactNo,
		--Mantis Start - 41546
		ISNULL(CM.Title,'') AS Class,
		ISNULL(DM.Title,'') AS Division
		--Mantis End - 41546
	FROM
		sStudent.tAcademic A
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
		INNER JOIN sAssessment.tOptionalSubject OS1 ON OS1.AcademicId = A.Id
		INNER JOIN sSetup.tClassSubject CS1 ON OS1.ClassSubjectId = CS1.Id AND CS1.IsOptional = 1
		INNER JOIN sSetup.tSubjectMaster SM1 ON CS1.SubjectId = SM1.Id
		LEFT OUTER JOIN sStudent.tStudentCommunication AS SC ON SC.StudentId = A.StudentId
		--Mantis Start - 41546
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		--Mantis End - 41546

		WHERE 
		A.BatchId =@rBatchId 
		AND (A.ClassId = @rClassId OR @rClassId=0)
		AND (DivisionId =@rDivisionId OR @rDivisionId=0)
		AND ((CS1.SubjectId = @rSubjectId) OR @rSubjectId = 0)
		AND (SM.StatusId = @rStatusId OR @rStatusId = 0)					--MantisId : 0031013
		AND (A.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)		--MantisId : 0031013
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentPercentageAnalysis]
	 
	 @rOrgId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rDepartmentId int = 0,
	 @rGroupId int=0,
	 @rClassStatusId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

--DECLARE  @TempFields TABLE

--(
--	MarkRange nvarchar(20),
--	StudentCount int,
--	GroupId int,
--	GroupName nvarchar(75),
--	GroupTitle nvarchar(75),
--	OrderIndex int
--)

DECLARE @lCount int
DECLARE @lMarkRange nvarchar(50)
DECLARE @lPercentage decimal(5,2)
DECLARE @lAnalysisGradeSetId int
DECLARE @lMinimumScore decimal(5,2)

SELECT @lAnalysisGradeSetId = ISNULL(AnalysisGradeSetId,0) From sAssessment.tConfiguration Where OrgId = @rOrgId

	CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		MarkRange nvarchar(50),				 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,MarkRange		
	FROM   sAssessment.tGradeSetDetail 
	WHERE  GradesetId=@lAnalysisGradeSetId
	ORDER BY MinimumScore DESC
	
	CREATE TABLE #tempPercentageUpdate
	(
		Id INT IDENTITY (1, 1),
		ResultId bigint,
		AcademicId bigint,
		Percentage decimal(5,2),
		MarkRange nvarchar(50)				 
	) 
	
	INSERT INTO #tempPercentageUpdate (ResultId,AcademicId,Percentage)
	SELECT R.Id,R.AcademicId,R.Percentage	
	FROM  sAssessment.tResult R 
		  INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
		  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	WHERE A.BatchId = @rBatchId AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	
	 
    SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
	WHILE (@lCount > 0)
	
	BEGIN
		SELECT
			  @lMarkRange = MarkRange,
			  @lMinimumScore = MinimumScore
		FROM 
			  #tempGradeSetDetail WHERE Id = @lCount
			
			
		UPDATE T SET T.MarkRange=@lMarkRange 
	    FROM   #tempPercentageUpdate T
			   INNER JOIN sAssessment.tResult R ON R.Id = T.ResultId
			   INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			   INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = T.AcademicId
			   INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE  ROUND(R.Percentage,0) >= @lMinimumScore 
		       AND EM.ExamSubGroupId = @rExamSubGroupId
		       AND A.BatchId = @rBatchId
		       AND EM.BatchId = @rBatchId
		       AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
		       AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		       AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId =0))
			   AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		SET @lCount = @lCount - 1
    END	
	
	SELECT	 
		  MarkRange, Count(T.AcademicId) AS StudentCount,
		  
		  CASE WHEN @rGroupId=1 THEN DM.Id 
			   WHEN @rGroupId=2 THEN CM.ClassId 
			   WHEN @rGroupId=3 THEN Dept.Id 
			   WHEN @rGroupId=4 THEN OM.Id 
		  END AS GroupId,
			
		  CASE WHEN @rGroupId=1 THEN DM.Code
			   WHEN @rGroupId=2 THEN CM.ClassName
			   WHEN @rGroupId=3 THEN Dept.Title 
			   WHEN @rGroupId=4 THEN OM.Title 
		  END AS GroupName,
			
		  CASE WHEN @rGroupId=1 THEN DM.OrderIndex
			   WHEN @rGroupId=2 THEN CM.OrderIndex
			   WHEN @rGroupId=3 THEN Dept.Id
			   WHEN @rGroupId=4 THen OM.OrderIndex  
		  END AS OrderIndex,
			
		  CASE WHEN @rGroupId=1 THEN 'Class/Division'
			   WHEN @rGroupId=2 THEN 'Class'
			   WHEN @rGroupId=3 THEN 'Department'
			   WHEN @rGroupId=4 THEN 'Organization'  
		  END AS GroupTitle
					
   FROM     
         #tempPercentageUpdate T
		 INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = T.AcademicId
		 INNER JOIN ssetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
		 INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
		 INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
   WHERE	 
         ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		 AND ((DM.ClassId=@rClassId ) or (@rClassId=0))
		 AND CM.BatchId=@rBatchId
		 AND EM.BatchId = @rBatchId
		 AND EM.ExamSubGroupId = @rExamSubGroupId
	     AND (ISNULL(DM.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	     AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId =0))
		 AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
   GROUP BY 
		 MarkRange
		 ,
		 
		 CASE WHEN @rGroupId=1 THEN DM.Id WHEN @rGroupId=2 THEN CM.ClassId  
		 WHEN @rGroupId=3 THEN Dept.Id WHEN @rGroupId=4 THEN OM.Id END
		 , 
		 
		 CASE WHEN @rGroupId=1 THEN DM.Code WHEN @rGroupId=2 THEN CM.ClassName  
		 WHEN @rGroupId=3 THEN Dept.Title WHEN @rGroupId=4 THEN OM.Title END
		 ,
		 
		 CASE WHEN @rGroupId=1 THEN DM.OrderIndex WHEN @rGroupId=2 THEN CM.OrderIndex  
		 WHEN @rGroupId=3 THEN Dept.Id WHEN @rGroupId=4 THEN OM.OrderIndex END
		 
   ORDER BY OrderIndex ASC, MarkRange DESC ,GroupName ASC 
	
   DROP Table #tempPercentageUpdate
   DROP Table #tempGradeSetDetail
	
	
   --SELECT * from @TempFields
   
   --DROP Table @TempFields
	--MarkRange,OM.Id,OM.Title,OM.OrderIndex,Dept.Id,Dept.Title,CM.ClassId,CM.ClassName,CM.OrderIndex,DM.Id,
	--DM.DisplayTitle,DM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentProfileGet]
	 
	 @rAcademicId bigint=0,
	 @rExamId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
		    Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
			A.Id AS AcademicId,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,			 
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.MotherName,'')AS MotherName,
			CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
			A.RollNo,
			CM.DisplayTitle AS Class,
			--DM.DisplayTitle AS Division,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			HM.Title AS House,
			SI.StudentPhoto,
			EM.FirstName + ' ' + EM.LastName AS ClassTeacherName,
			DM.DisplayTitle AS Division,
			BM.Title AS Batch,
			SA.AdmissionDate,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight
			 
			--CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected
      
	FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			left Join sStudent.tStudentFamily SF ON SF.StudentId =SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=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.tBatchMaster BM ON BM.Id=A.BatchId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id =DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND SR.ExamId=@rExamId
			
	WHERE 
		((A.Id=@rAcademicId) OR (@rAcademicId=0))
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentResultDetailSub]
	 
	@rExamId bigint,
	@rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
CREATE TABLE #tmp
(
Id int identity(1,1),
ResultDetailsName nvarchar(100),
ResultDetailsValue nvarchar(100)
)
INSERT INTO #tmp
	SELECT Distinct
		ISNULL(NULLIF(ALS.PercentageLabel,''),'Percentage') AS ResultDetailsName,
		Convert(nvarchar,R.Percentage)AS ResultDetailsValue
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
		LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = A.OrgId
	WHERE 
		(A.Id=@rAcademicId) 
		AND (R.ExamId = @rExamId)
		AND EM.IsPercentage = 1
UNION  All
SELECT Distinct
		--'Grade' AS ResultDetailsName,
		ISNULL(NULLIF(ALS.OverallGradeLabel,''),'Over All Grade') AS ResultDetailsName,
		R.ResultGrade AS ResultDetailsValue
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
		LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = A.OrgId
	WHERE 
		(A.Id=@rAcademicId) 
		AND (R.ExamId = @rExamId)
		AND EM.IsGrade = 1
UNION ALL
SELECT Distinct
		--'Result Status' AS ResultDetailsName,
		ISNULL(NULlIF(ALS.ResultStatusLabel,''),'Result Status') AS ResultDetailsName,
		R.ResultStatus AS ResultDetailsValue
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
		LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = A.OrgId
	WHERE 
		(A.Id=@rAcademicId)
		AND (R.ExamId = @rExamId)
		AND EM.IsResultStatus = 1
UNION All
SELECT Distinct
		--'Rank No' AS ResultDetailsName,
		ISNULL(NULlIF(ALS.RankNoLabel,''),'Rank No') AS ResultDetailsName,
		Convert(nvarchar,R.RankNumber) AS ResultDetailsValue
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
		LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = A.OrgId
	WHERE 
		(A.Id=@rAcademicId)
		AND (R.ExamId = @rExamId)
		AND EM.IsRankNo = 1

UNION All
SELECT Distinct
		--'Percentile' AS ResultDetailsName,
		ISNULL(NULLIF(ALS.PercentileLabel,''),'Percentile') AS ResultDetailsName,
		Convert(nvarchar,R.Percentile) AS ResultDetailsValue
	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 sStudent.tAcademic A ON A.Id=R.AcademicId
		LEFT JOIN sAssessment.tAssessmentLabelSetup ALS ON ALS.OrgId = A.OrgId
	WHERE 
		(A.Id=@rAcademicId)
		AND (R.ExamId = @rExamId)
		AND EM.IsPercentile = 1


		--Select * from #tmp
		Select (Select COUNT(Id)FROM #tmp) As TotalCount,ResultDetailsName,ResultDetailsValue from #tmp
		--GROUP BY Id
		DROP TABLE #tmp
 
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentSingleSubjectAnalysisGet]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 --@rGroupByid int=0,
	 --@rOrgId  int=0,
	 --@rSubject nvarchar(MAX)=''
	 @rCode nvarchar(20)='' --mentis : 0031596
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT
		--0 AS GradeCount,
		(Select Title from SASSESSMENT.TEXAMSUBGROUPmASTER Where Id =@rExamSubGroupId) AS Builder1,
		A.Id As AcademicId ,
		A.StudentId As StudentId ,
		A.RollNo As RollNo ,
		STM.FirstName As StudentName ,
		STM.MiddleName As FatherName ,
		STM.LastName As SurName,
		STM.FirstName+' '+STM.MiddleName+' '+STM.LastName AS Name ,
		EM.DisplayTitle As ExamName ,
		CM.Id As ClassId, 
		CM.Title As Class ,
		CM.DisplayTitle As ClassName ,
		DM.Id As DivisionId, 
		DM.Title As Division ,
		DM.DisplayTitle As DivisionName ,
		SM.Title AS SubjectName,
		RD.Obtain AS ObtainMarks,
		SM.OrderIndex AS SubjectOrderIndex
		--GD.GradeSetId AS GradeSetId,	
	from 
		sAssessment.tResultDetail  RD
		INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		--LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		--GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		--INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	where 
		EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
	order by 
		A.RollNo
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentSubjectWise]  
	 
	 -- @rAcademicId bigint=0,
	 @rExamId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
 
	@rBatchId int=0,
	@rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			 --CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
			 CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
			 CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
			 CONVERT (nvarchar(20),@rDivisionId) AS DivisionIdText,
	
			 CONVERT (nvarchar(20),SM.Title) AS SubjectName,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A	
				INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE CS.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId  AND SO.GenderId=2) AS TotalGirls,
		
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1) AS TotalBoys,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=2 AND SM.StatusId=3) AS LeftGirls,
			
			 (Select COUNT(A.Id) from sStudent.tAcademic A
				
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE ClassId=@rClassId AND ((DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND BatchId=@rBatchId AND SO.GenderId=1 AND SM.StatusId=3) AS LeftBoys,
			
			
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId
				 )  AS AppearedGirls,
				 
			(Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId
				
				) AS AppearedBoys,	
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.IsPresent=0
				) AS AbsentGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.IsPresent=0
				) AS AbsentBoys,
			 
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain >= ED.Minimum AND ISNULL(RD.GraceMark,0) = 0
				 ) AS PassedGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain >= ED.Minimum AND ISNULL(RD.GraceMark,0)=0
				 ) AS PassedBoys,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain + RD.GraceMark >= ED.Minimum AND ISNULL(RD.GraceMark,0) > 0
				 ) AS PassWithGraceGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain + RD.GraceMark >= ED.Minimum AND ISNULL(RD.GraceMark,0) > 0
				  ) AS PassWithGraceBoys,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=2
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain + ISNULL(RD.GraceMark,0) < ED.Minimum 
				 ) AS FailedGirls,
				
			 (Select COUNT(R.AcademicId) from sAssessment.tResult R 
				INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
				INNER JOIN sAssessment.tExamDetail ED ON Rd.ExamDetailId = ED.Id
				INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
				INNER JOIN  sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				 WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId AND R.ExamId=@rExamId AND SO.GenderId=1
				 AND ED.ClassSubjectId = EDO.ClassSubjectId AND RD.Obtain +ISNULL(RD.GraceMark ,0)< ED.Minimum  
				 ) AS FailedBoys,
				
			 (Select COUNT(A.Id) from sStudent.tAcademic A	
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id= A.StudentId
				INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
				WHERE A.ClassId=@rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId = 0)) AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0)) AND A.BatchId=@rBatchId) AS Total,
			--A.RollNo,
			--A.Id AS AcademicId,
			
			SM.Title AS SubjectName,
			SM.Id AS SubjectId
		 
		 
			FROM 
			
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tExamDetail EDO ON EDO.ExamId=EM.Id
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=EDO.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		
	WHERE 
		 
	 ((EM.Id=@rExamId) OR (@rExamId=0))
	 AND((CS.ClassId =@rClassId) OR (@rClassId=0))
	 AND((DM.Id =@rDivisionId)  OR(@rDivisionId=0))
	 
	 AND(EM.BatchId=@rBatchId)
		order by CS.OrderIndex
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentTopperClassSectionWise]
	 
	--  @rAcademicId bigint=0,
	 @rExamId int=0,
	 @rClassId int=0, 
	 @rBatchId int=0,
	 --@rDivisionId int=0,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	
	SELECT  
	 
			R.Percentage,
			ROW_NUMBER() OVER(PARTITION BY 
				  CM.Id 
			 ORDER BY R.Percentage DESC) CM ,
	 		--CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
		    CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
		    CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
		    --CONVERT(nvarchar(20),@rDivisionId) AS DivisionIdText,
					
		      R.RankNumber AS RankNumber,	
		      
			 R.TotalObtain AS ObtMarks,
			   
			 R.TotalMarks AS  OutOfMarks,
				
			 CM.Title + '-' + DM.Title AS ClassDivision,
			STM.FirstName + ' ' + STM.LastName AS Name,
			A.RollNo ,
			 DM.Id AS DivisionId
			 
			 
			
		 FROM
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId 
		    INNER JOIN sStudent.tAcademic A	ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster STM ON STM.Id=A.StudentId
		  
		   INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			
	 WHERE 
		 ((EM.Id=@rExamId) OR (@rExamId=0))
		 AND ((EM.ClassId=@rClassId) OR (@rClassId=0))
		 
		 AND ((R.RankNumber <=3) AND (R.RankNumber<>0))
		 AND ((STM.StatusId=@rStatusId)OR(@rStatusId=0))
			 
		)r1
		WHERE((r1.CM <=3) OR (r1.Cm=0))
			
			 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentTopperClassWise]
	 
	 -- @rAcademicId bigint=0,
	 @rExamId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT  
			
			 
			R.Percentage,
	 		--CONVERT(nvarchar(20),A.Id) AS AcademicIdText,
		    CONVERT(nvarchar(20),@rExamId) AS ExamIdText,
		    CONVERT(nvarchar(20),@rClassId) AS ClassIdText,
		    CONVERT(nvarchar(20),@rDivisionId) AS DivisionIdText,
				
		      R.RankNumber AS RankNumber,	
		      
			R.TotalObtain AS ObtMarks,
			 R.TotalMarks AS OutOfMarks,
			 
			STM.FirstName + ' ' + STM.LastName AS Name,
			A.RollNo,
			A.Id AS AcademicId,
			EM.Id AS ExamId
			
		 
			FROM 
				sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId
		    INNER JOIN sStudent.tAcademic A	ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster STM ON STM.Id=A.StudentId
		 
		 
	 WHERE 
		 ((EM.Id=@rExamId) OR (@rExamId=0))
		 AND((EM.ClassId=@rClassId) OR (@rClassId=0))
		 AND((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  
		 AND ((R.RankNumber <= 3) AND(R.RankNumber<>0))
		 AND ((STM.StatusId=@rStatusId)OR(@rStatusId=0))
			order by A.DivisionId,R.RankNumber 
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptStudentWiseGradeList]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rClass nvarchar(MAX)='',
	 @rSubjectId int=0,
	 @rStatusId int =0,
	 @rClassStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
	
	select 
		
		 count(RD.id),
		 
		@rBuilder1 AS Builder1,
		 
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		CS.IsOptional ,
		DM.Id AS DivisionId,
		Dm.DisplayTitle as DivisionName,
		Cs.Id AS ClassId,
		CM.DisplayTitle AS ClassName,
		ISNULL(GD.MarkRange,'') AS MarkRange,
		SM.OrderIndex AS SubjectOrderIndex, 
		CM.OrderIndex AS ClassOrderIndex,
		(select count(A.Id) from sStudent.tAcademic A  
		
		INNER JOIN sAssessment.tResult R1 ON A.Id = R1.AcademicId 
	    INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R1.ExamId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		  
		where  A.BatchId =  @rBatchId AND  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and (CM.Id=@rClassId OR @rClassId=0)
		AND (DM.ID=@rDivisionId OR @rDivisionId=0)
	 
		
		) AS DivisionCount
		 
		 
 
		 
from sAssessment.tResultDetail  RD
   
		 Inner join sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		
		
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		inner join sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
		 
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		 
		
	where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and (CM.Id=@rClassId OR @rClassId=0)
		AND (DM.ID=@rDivisionId OR @rDivisionId=0)
		AND SM.Id=@rSubjectId
		  AND (ISNULL(Cm.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		   and((STM.StatusId=@rStatusId) or (@rStatusId=0))
		   AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		 Group by RD.SubjectGrade,GD.MarkRange,SM.Title,CS.IsOptional ,DM.Id,DM.DisplayTitle,Cs.Id,CM.DisplayTitle,SM.OrderIndex,CM.OrderIndex 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubExamCombineGet]
	
	 @rId bigint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT			
			
			EC.Id,
			-- Convert(nvarchar(10),@rId) AS ExamIdText,
			EC.SubExamId,
			EC.weightage,
			EGM.Title AS ExamGroupName,
			ESGM.Title AS ExamName,
			EC.ExamOrder			
	FROM 
		
			sAssessment.tExamCombine EC
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = EC.SubExamId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON EM.ExamSubGroupId = ESGM.Id
			INNER JOIN sAssessment.tExamGroupMaster EGM ON ESGM.ExamGroupId = EGM.Id			 
	WHERE 
		     EC.ExamId=@rId
		     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubGradeSetDetail]
	  @rExamId int,
	  @rDivisionId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
DECLARE @lGradeSetId int 
SELECT @lGradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId

CREATE TABLE #tmp
(
id int identity,
GradeCode nvarchar(50),
StudentCount int
)
INSERT INTO #tmp
SELECT 
		
		GSD.GradeCode AS GradeCode,
		(Select COUNT(distinct A.Id) from sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId AND R.ResultGrade = GSD.GradeCode
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sAssessment.tGradeSetDetail GSD1 ON EM.GradeSetId=GSD1.GradeSetId AND ED.GradeSetId = GSD1.GradeSetId
			Where 
				EM.Id = @rExamId AND ED.GradeSetId = @lGradeSetId AND A.DivisionId = @rDivisionId AND GSD.GradeCode = GSD1.GradeCode
				AND StuM.StatusId =1
			)AS StudentCount
	FROM 
	
		sAssessment.tExamMaster EM
		INNER JOIN sAssessment.tGradeSetDetail GSD ON EM.GradeSetId=GSD.GradeSetId
		
	Where 
		EM.Id = @rExamId 
		ORDER BY GSD.Id

		Select id,GradeCode,StudentCount,
		(Select COUNT(id) from #tmp) AS GradeCount
		from #tmp
		--Select isnull(STUFF((SELECT ',' + GradeCode FROM #tmp
		--				   FOR XML PATH('')), 1, 1, ''),'')AS Grade
		--Select isnull(STUFF((SELECT ',' + CONVERT(varchar,StudentCount) FROM #tmp
		--FOR XML PATH('')), 1, 1, ''),'')AS Grade

		DROP TABLE #tmp
		
		--Select 0 as id,'' AS GradeCode,0 as StudentCount,0 AS GradeCount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)='',
		@rStatusId int=0 --Added by dhannajay for mantis : 41990

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 

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

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

	SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade, 
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			[sStudent].[fStudentNameGet](StuM.FirstName , ISNULL(StuM.MiddleName,'') , StuM.LastName,OM.StudentNameFormatId ) AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EI.EmployeeSign ELSE NULL END AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
			ELSE 
			NULL END) AS MarksheetHeaderA4,
			--CONVERT(varbinary(max),'0x') AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			--@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			TeacherSignCaption,
			EM.PrincipalSignCaption,
			ParentSignCaption,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			SR.ResultRemark1,
			SR.ResultRemark2,	
			SR.ResultRemark3,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			
			ISNULL(SR.MyGoal,'') AS MyGoal,
			ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
			ISNULL(SR.Responsibility,'') AS Responsibility,
			ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
			ISNULL(SR.MyStrength,'') AS MyStrength,
			ISNULL(SR.Achievements,'') AS Achievements,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			ISNULL(SR.ImprovementArea,'') As ImprovementArea,
			ISNULL(SR.ProgressArea,'') AS ProgressArea,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			ISNULL(SR.MyActivity,'') AS MyActivity,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			DivisionId,
			SM.ID,
			( EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			AIS.Marks,
			SR.ExamSeatNo AS ExamSeatNo,					--add for 27710 mantis
			 --added by dhananjay for mantis Start : 36640
			ISNULL(SF.RelativeName, '') AS GuardianName,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			 --added by dhananjay for mantis End : 36640
			 ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle, -- Add for mantis : 0036885
			 SAM.Number AS SubjectActivityNumber --Added by dhananjay for mantis : 40533
			 ,ESM.Title AS ExamName -- add for mantis : 0041553
	 FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			--INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId		-- Comment for Mantis Id : 0034172
			--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id			-- Comment for Mantis Id : 0034172
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			LEFT JOIN sHrm.tEmployeeMaster EmpM 
				ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.IsObsolete = 0
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =StuM.ID
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId = SA.Id and OS.ClassSubjectId = CS.Id		-- Mantis Id : 0034172
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId --add for mantis : 0041553
	    --LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			----------------------------------------------------------------------------
			--sAssessment.tCCESubjectActivityMaster SAM 	
			--INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId 
			--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			--INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CS.ClassId 
			--INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			--LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id 	
			--LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			--LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		 
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			--LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			--LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			--LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID 
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			--AND StuM.StatusId = 1
			AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
			AND (ISNULL(STum.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
			AND SAM.IsObsolete = 0
			AND (CS.IsOptional = 0 OR (CS.IsOptional = 1 AND ISNULL(OS.AcademicId, 0) <> 0))			-- Mantis Id : 0034172

		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailWithTermGradeGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)='',
		@rStatusId int=0  --added by dhananjay mantis : 41990
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 
Declare @GradeString nvarchar(500),@GradeSetId int
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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


--Declare @rIsDisplayStudentPhoto bit, @rIsDisplayTeacherSign bit, @rIsDisplayPrincipalSign bit, @rIsDisplayImageHeader bit
--SELECT @rIsDisplayStudentPhoto = ISNULL(IsDisplayPhoto,0), @rIsDisplayTeacherSign = ISNULL(IsDisplayTeacherSign,0),
--	   @rIsDisplayPrincipalSign = ISNULL(IsDisplayPrincipalSign,0),@rIsDisplayImageHeader = ISNULL(IsDisplayImageHeader,0)
--	   From sAssessment.tExamMaster Where Id = @rExamId
	   
		--DECLARE @lAcademicId TABLE (AcademicId bigint, ClassSubjectId int, Term1Grade nvarchar(20), Term2Grade nvarchar(20), AnnualGrade nvarchar(20),
		--Term1PresentDays Int, Term1TotalDays Int, Term2PresentDays Int, Term2TotalDays Int)
		
		--INSERT INTO @lAcademicId (AcademicId, ClassSubjectId)
		--(
		--	SELECT 			 
		--		SA.AcademicId,
		--		CS.ClassSubjectId
		--	FROM 
		--		sStudent.vStudentAcademic SA
		--		INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId
		--		INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
		--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId 
		--		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		--	WHERE
		--		((SA.AcademicId=@rAcademicId) OR(@rAcademicId=0))
		--		AND ((CS.ClassId=@rClass) OR (@rClass=0))
		--		And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
		--		And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
		--		And ((EM.Id = @rExamId) OR (@rExamId = 0))
		--		and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((SA.Code = @rCode) OR(@rCode=''))
		--		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--		AND SA.StatusId = 1
		--)
		
		--Declare @FirstTermExamId AS INT,@SecondTermExamId AS INT, @Term1PresentDays AS INT, @Term1TotalDays AS INT,
		--@Term2PresentDays AS INT, @Term2TotalDays AS INT
		
		--Select @FirstTermExamId=SubExamId  from sAssessment.tExamCombine Where ExamId = @rExamId AND ExamOrder = 1
		
		--Select @SecondTermExamId=SubExamId from sAssessment.tExamCombine Where ExamId = @rExamId AND ExamOrder = 2
		
		
	
		--UPDATE @lAcademicId 
		--SET Term1Grade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @FirstTermExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
	    
		--UPDATE @lAcademicId 
		--SET Term2Grade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @SecondTermExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
		
		--UPDATE @lAcademicId 
		--SET AnnualGrade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @rExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
		
		--UPDATE @lAcademicId 
		--SET Term1PresentDays = SR.PresentDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @FirstTermExamId AND SR.AcademicId = A.AcademicId
		
		--UPDATE @lAcademicId 
		--SET Term1TotalDays = SR.TotalDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @FirstTermExamId AND SR.AcademicId = A.AcademicId
		
	 --   UPDATE @lAcademicId 
		--SET Term2PresentDays = SR.PresentDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @SecondTermExamId AND SR.AcademicId = A.AcademicId
		
		--UPDATE @lAcademicId 
		--SET Term2TotalDays = SR.TotalDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @SecondTermExamId AND SR.AcademicId = A.AcademicId
	    
	    --Select * from @lAcademicId
	    
	    SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade, 
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			StuM.FirstName + ' ' +StuM.MiddleName +' ' +StuM.LastName AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		    ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
			ParentSignCaption,
			SR.ResultRemark3,
			--ARD.SubjectGrade,																												-- Comment for Mantis Id : 0034172
			(Select TOP 1 SubjectGrade From sAssessment.tResultDetail Where ExamDetailId = ED.Id AND ResultId IN (Select Id from sAssessment.tResult Where AcademicId = SA.Id AND  ExamId = EM.Id)) AS SubjectGrade,		-- Mantis Id : 0034172
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
			ISNULL(C.ParentContactNo,'') AS ParentContactNo,
			ISNULL(C.StudentContactNo,'') AS StudentContactNo,
			(C.PresentStreetOne+' '+C.PresentStreetTwo+' '+C.PresentStreetThree+' '+C.PresentCountry+' '+C.PresentState+' '+C.PresentCity+' '+C.PresentZipCode) AS Address1,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			--added by megha for 0027299
			--AR.ResultGrade As OverallGrade,																								-- Comment for Mantis Id : 0034172
			(Select Top 1 ResultGrade From sAssessment.tResult Where AcademicId = SA.Id AND  ExamId = EM.Id ) AS OverallGrade,				-- Mantis Id : 0034172
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS StudentName,
			ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
			ISNULL(SR.Achievements,'') AS Achievements,   ---Mantis - 31821
			ISNULL(SR.MyActivity,'') AS MyActivity		---Mantis - 31821
			,ESM.ExamSubGroupDisplayTitle		-- add for mantis : 0041543
			
			--A.Term1Grade,
			--A.Term2Grade,
			--A.AnnualGrade,
			--A.Term1PresentDays,
			--A.Term1TotalDays,
			--A.Term2PresentDays,
			--A.Term2TotalDays			
			
		FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			--INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId			-- Comment for Mantis Id : 0034172
			--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id				-- Comment for Mantis Id : 0034172
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId	
			--LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id=DM.InchargeEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 -- Mantis : 28354	
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId = SA.Id and OS.ClassSubjectId = CS.Id		-- Mantis Id : 0034172
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId -- add for mantis : 0041543
			
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			--AND StuM.StatusId = 1
			AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))--added by dhananjay mantis : 41990
			AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
			AND (CS.IsOptional = 0 OR (CS.IsOptional = 1 AND ISNULL(OS.AcademicId, 0) <> 0))					-- Mantis Id : 0034172

		--ORDER BY 
		--	SA.RollNo ASC,
		--	SAM.OrderIndex ASC,
		--	SSA.OrderIndex ASC;
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

BEGIN 	
 
			SELECT 		
				 
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Marks,0) AS Marks,
				 
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex,
				 SM.Title AS SubjectTitle,
				 SAM.ClassSubjectId,
				 AIS.DescriptiveIndicator,
				 CS.OrderIndex AS SubOrderIndex
				 
			FROM 
			  sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id And AIS.ExamId=@rExamId
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			 WHERE
				 ((SAM.ClassSubjectId=@rClass) OR (@rClass=0))
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				--AND AIS.ExamId=@rExamId
				and ((SSA.SubjectActivityId=@rActivityId) OR (@rActivityId=0))
				AND((SSA.Id=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))	
				and SSA.OrgId=@rOrgId
				AND  SA.StatusId = 1		
		 
			 ORDER BY SA.RollNo
			
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamMarkGet]

		@rOrgId int,
		@rExamId int,
		@rClass int,
		@rDivisionId int,
		@rBatchId int,
		@rActivityId int,
		@rSubjectSubActivityId int,
		@rBuilder1 nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN

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

			SELECT
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,

				 ISNULL(AIS.Marks,0) AS Marks,

				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex,
				 SM.Title AS SubjectName,
				 SAM.ClassSubjectId,
				 ISNULL(AIS.Grade,'') AS Grade,
				 ISNULL(AIS.GradeIndicator,'') AS GradeIndicator,
				 ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
				 (SELECT EM.FirstName + ' ' + EM.LastName  From sHrm.tEmployeeMaster EM
				  INNER JOIN sSetup.tDivisionMaster DM ON EM.Id = DM.InchargeEmployeeId Where DM.Id = @rDivisionId) AS ClassTeacher,
				  ISNULL(SR.TotalDays,0)AS TotalDays,
				  ISNULL(SR.PresentDays,0)AS PresentDays,
				  CONVERT(bit,@lDecimalConfig) AS IsDecimal,
				  ISNULL(SR.GeneralRemark,'') AS GeneralRemark,
				  ISNULL(SR.Achievements,'') AS Achievements,
				  ISNULL(SR.ResultRemark1,'') AS ResultRemark1,
				  ISNULL(SR.ResultRemark2,'') AS ResultRemark2,
				  ISNULL(SR.ResultRemark3,'') AS ResultRemark3,
				  ISNULL(SR.StudentHeight,0) AS StudentHeight, --Mantis: 41902
				  ISNULL(SR.StudentWeight,0) AS StudentWeight --Mantis: 41902

			FROM
			  sAssessment.tCCESubjectActivityMaster SAM
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
			INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id And AIS.ExamId=@rExamId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId AND SR.ExamId = @rExamId -- Mantis : 0027635

	    	 WHERE
				 ((SAM.ClassSubjectId=@rClass) OR (@rClass=0))
				And SA.DivisionId =@rDivisionID
				And SA.BatchId =@rBatchId
				--AND AIS.ExamId=@rExamId
				and ((SSA.SubjectActivityId=@rActivityId) OR (@rActivityId=0))
				AND((SSA.Id=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))
				and SSA.OrgId=@rOrgId
				AND  SA.StatusId = 1

			 ORDER BY SA.RollNo

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamScoreGet]
	  
	   @rOrgId int
	  ,@rExamId int,
	  @rClassSubjectId int,
	  @rDivisionId int,
	  @rBatchId int,
	  @rActivityId int=0,
	  @rSubjectSubActivityId int=0,
	  @rBuilder1 nvarchar(max)='',
	  @rAcademicId bigint=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				 
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Grade,'') AS Term1Indicator,
				 SAM.Title AS SubjectActivityTitle,
				 SSA.Title AS SubjectSubActivityTitle,
				 SAM.Id AS ActivityId,
				 SSA.Id AS SubjectSubActivityId,
				 SAM.OrderIndex AS ActivityOrderIndex,
				 SSA.OrderIndex AS SubjectSubActivityOrderIndex,
				 ISNULL(AIS.GradeIndicator,'')AS GradeIndicator,
				ISNULL(AIS.DescriptiveIndicator,'')  AS DescriptiveIndicator,	
				ISNULL(AIS.Marks,0) AS Marks
				 
			FROM 
			 	
			 sAssessment.tCCESubjectActivityMaster SAM 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
			INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
			LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId  AND AIS.SubjectSubActivityId= SSA.Id  And AIS.ExamId=@rExamId
			
			 WHERE
				 SAM.ClassSubjectId=@rClassSubjectId 
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId	
				AND AIS.ExamId=@rExamId
				and ((SSA.SubjectActivityId=@rActivityId) OR (@rActivityId=0))
				AND((SSA.Id=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))	
				and SSA.OrgId=@rOrgId
				AND  SA.StatusId = 1
				AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
			 ORDER BY SA.RollNo
			
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectActivityMaxMarkGradeTwoColumnGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)='',
		@rStatusId int=0  --added by dhananjay mantis : 41990
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 

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

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

	SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade, 
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			[sStudent].[fStudentNameGet](StuM.FirstName , ISNULL(StuM.MiddleName,'') , StuM.LastName,OM.StudentNameFormatId ) AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EI.EmployeeSign ELSE NULL END AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
			ELSE 
			NULL END) AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			--@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			TeacherSignCaption,
			EM.PrincipalSignCaption,
			ParentSignCaption,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			SR.ResultRemark1,
			SR.ResultRemark2,	
			SR.ResultRemark3,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			
			ISNULL(SR.MyGoal,'') AS MyGoal,
			ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
			ISNULL(SR.Responsibility,'') AS Responsibility,
			ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
			ISNULL(SR.MyStrength,'') AS MyStrength,
			ISNULL(SR.Achievements,'') AS Achievements,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			ISNULL(SR.ImprovementArea,'') As ImprovementArea,
			ISNULL(SR.ProgressArea,'') AS ProgressArea,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			ISNULL(SR.MyActivity,'') AS MyActivity,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			DivisionId,
			SM.ID,
			( EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			AIS.Marks,
			SR.ExamSeatNo AS ExamSeatNo,					--add for 27710 mantis
			[sAssessment].[fSubjectWiseGradeGet](SA.Id,@rExamId,SAM.Id,SAM.ClassSubjectId,@rBatchId,@rClass) AS SubjectGrade,
			ED.Maximum AS SubjectMaximum,
			ED.IsShowSubjectMark --Added by dhananjay for mantis id : 0035701

	 FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			--INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId			-- Comment for Mantis Id : 0034172
			--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id				-- Comment for Mantis Id : 0034172
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			LEFT JOIN sHrm.tEmployeeMaster EmpM 
				ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.IsObsolete = 0
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =StuM.ID
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId = SA.Id and OS.ClassSubjectId = CS.Id		-- Mantis Id : 0034172
	    --LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			----------------------------------------------------------------------------
			--sAssessment.tCCESubjectActivityMaster SAM 	
			--INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId 
			--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			--INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CS.ClassId 
			--INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			--LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id 	
			--LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			--LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		 
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			--LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			--LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			--LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID 
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			--AND StuM.StatusId = 1
			AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))--added by dhananjay mantis : 41990
			AND (ISNULL(STum.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
			AND SAM.IsObsolete = 0
			AND (CS.IsOptional = 0 OR (CS.IsOptional = 1 AND ISNULL(OS.AcademicId, 0) <> 0))			-- Mantis Id : 0034172

		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectGradeScoreGet]
	   @rOrgId int
	  ,@rBatchId int
	  ,@rDivisionId int
	  ,@rExamId int
	  ,@rClassSubjectId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				 ISNULL(GSES.ExamId,0) AS ExamId,
				ISNULL(GSES.ClassSubjectId,0) AS ClassSubjectId,
				SA.AcademicId,
				SA.NUMBER AS Code,
				SA.ROLLNO,
				SA.NAME AS StudentName,
				ISNULL(GSES.Grade,'') AS Grade,
				ISNULL(GSES.GradeIndicator,'') AS GradeIndicator,
				ISNULL(GSES.DescriptiveIndicator,'') AS DecriptiveIndicator,
				ISNULL(GSES.IndicatorIds,'') AS IndicatorIds ,
				SM.Title AS SubjectName,
				CM.Title AS CLASSNAME,
				ESGM.Title AS ExamName,
				(Select GradeSetId From sAssessment.tExamMaster Where Id = @rExamId) as GradeSetId
			FROM  
			 sStudent.vStudentFull SA
			 
  					LEFT JOIN sAssessment.tGradeSujbectExamScore GSES	ON GSES.AcademicId = SA.AcademicId  
  						AND GSES.ExamId = @rExamId AND(( GSES.ClassSubjectId=@rClassSubjectId) OR (@rClassSubjectId=0))
  						
  			 inner join 	sSetup.tClassSubject CS ON CS.Id=GSES.ClassSubjectId
					INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=CS.ClassId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=GSES.ExamId
					INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID		
					
  						
			WHERE
				 SA.DivisionId = @rDivisionId AND SA.BatchId=@rBatchId  AND StatusId = 1  
					 AND((GSES.ClassSubjectId=@rClassSubjectId) OR (@rClassSubjectId=0))
			ORDER BY SA.RollNo
			
			
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectIndicatorGet]
	 @rSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT			
			SIM.Id,
			SIM.SubjectId,
			SIM.Number,
			SIM.TITLE,
			SIM.OrderIndex,
			SM.Title AS SubjectName,
			Sm.OrderIndex As SubjectOrderIndex
  FROM 
			sAssessment.[tSubjectIndicatorMaster] SIM
			INNER JOIN  sSetup.tSubjectMaster SM On SM.Id = SIM.SubjectId
WHERE 
			((SIM.SubjectId=@rSubjectId) OR (@rSubjectId=0))  order by SIM.OrderIndex ASC		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectRemarkGet]
 
	 @rExamId bigint,
	 
	 @rAcademicId bigint=0,
	 @rDivisionId  int=0,
	 @rClassId int=0 ,
	 @rBatchId int=0 ,
	 @rFromROllNO int=0,
	 @rToRollno int=0,
	  @rClassSubjectId int=0
	 
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


SELECT 
	convert(nvarchar(20),@rExamId) AS ExamIdText,
	Convert(nvarchar(20),@rAcademicId)As AcademicIdText,
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,ISNULL(RD.Remark,'') AS SubjectRemark,
	V.SubjectName,
	V.SubjectId
	,ED.Id AS ExamDetailId,
	 [sAttendance].[fSubjectTeacherGet](SA.DivisionId,V.SubjectID)AS EmployeeName,
	 SR.ClassTeacherRemark,
	 SR.HouseRemark,
	 EMP.FirstName+' ' + EMP.LastNAme AS TEacherNAme,
	 --ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
	 [SHostel].[fWardenGet](HM.ID) AS WardenName
	 
	 
	 
from sStudent.vStudentAcademic SA 
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	LEFT JOIN sHrm.tEmployeeMaster EMp on EMP.Id = Dm.InchargeEmployeeId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
	LEFT JOIN sAssessment.tResultDetailOther RD ON  RD.AcademiciD=SA.AcademicId  AND EM.ID=RD.ExamId   AND RD.ClassSubjectID = Ed.ClassSubjectId 
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicID =SA.Academicid AND SR.ExamID = @rExamId
	LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
	LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
    LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId      
     --       LEFT JOIN
     --       (
		   --SELECT 
		   --employeeId, 
		   --HostelId,   
		   --ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   --FROM sHostel.tHostelwarden 
     --       )  HW ON HW.HostelId=HM.Id AND RowNo = 1  
     -- LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id
      LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId=SA.AcademicId and OS.ClassSubjectId=V.ClassSubjectId
	Where  
		(DM.Id=@rDivisionId OR @rDivisionId = 0)
	    AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND  (EM.Id=@rExamId OR @rExamId = 0)
	   AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	   AND ((SA.ROllNo >=@rFromROllNO) OR(@rFromROllNo=0)) 
	   AND ((SA.RollNo<=@rToRollno) OR (@rToRollno=0))
	  AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	 AND ((V.IsOptional = 1 AND  isnull(OS.AcademicId,0) <> 0) OR (V.IsOptional = 0))
	  AND ((ED.ClassSubjectId = @rClassSubjectId) OR (@rClassSubjectId=0))
	--Order By SA.RollNo
	Order By ED.DisplayOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectResultDetailRemarkGet]
	 @rExamId nvarchar(20),
	 @rAcademicId nvarchar(20)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT
		 CONVERT(NVARCHAR(20),@rExamId) As ExamIdText,
		 CONVERT(nvarchar(20),@rAcademicId) As AcademicIdText,
		 R.ExamId,
		 A.Id As AcademicId,
		 SM.Title As SubjectName,
		 RD.Remark
	FROM 
	
	 sStudent.tAcademic A 
	INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId    
	INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			
	WHERE 
	     
	    R.ExamId = @rExamId
	    AND A.Id=@rAcademicId
		order by A.RollNo,CS.OrderIndex 

		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectResultListFloating]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	@rIsShowWithDetail bit =0,
	@rFilterId int=0,
	@rOrgGroupBatchId int=0,
	@rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 --Select * from dbo.Float
 --Select
 --           ''  AS AcademicIdText,
	--		'' AS ExamIdText,
	--		'' AS IsDisplayMonthlyAttendanceText,
	--		'' AS Exam,
	--		'' AS Builder1,
	--		'' Code,
	--		'' AS Name,
	--		0 RollNo,
	--		Convert(BigInt ,0) AS AcademicId,			
	--		'' ResultStatus,
	--		'' AS Class,
	--		'' AS Division,
	--		Convert(decimal , 0) TotalMarks,
	--		Convert(decimal , 0) TotalObtain,
	--		Convert(decimal , 0) Percentage,
	--		0 RankNumber,
	--		'' ResultGrade,
	--		Convert(decimal , 0) Percentile,			
	--		Convert(BigInt ,0) AS ResultDetailId,		
	--		Convert(bit, 0) IsDisplayInMarksheet,
	--		Convert(bit, 0) IsShowSubjectGrade,
	--		Convert(bit, 0) IsIncludeInTotal,
	--		Convert(decimal , 0) AS SubjectObtain,
	--		Convert(decimal , 0) AS SubjectMinimum,
	--		Convert(decimal , 0) AS SubjectMaximum,			
	--		'' AS SubjectCode,
	--		'' AS SubjectName,
	--		0 AS SubjectOrderIndex,
	--		Convert(BigInt ,0) AS ResultId,
	--		0 AS SubjectId,			 	
	--		Convert(bit, 0) IsMarksInDecimal,
			
	--		 '' AS Remark1,
	--		'' AS Remark2,
	--		'' AS Remark3,
	--		'' DisplayTitle,
	--		Convert(bit, 0) IsRankNo, 
	--		Convert(bit, 0) IsGrade,
	--		Convert(bit, 0) IsPercentile,
	--		Convert(bit, 0) IsPercentage,
	--		Convert(bit, 0) IsSubjectPercentile,
	--		Convert(bit, 0) IsProcessResult,
			 
	--		Convert(bit, 0) IsNegativeMarks,
	--		Convert(bit, 0) IsIncludeCoScholastic,
	--		Convert(bit, 0) IsOnPrePrinted,
	--		Convert(bit, 0) IsDisplayPhoto,
	--		Convert(bit, 0) IsDisplayBirthDate,
	--		Convert(bit, 0) IsLockForEdit,
	--		Convert(bit, 0) IsDisplaySchoolName,			
	--		Convert(bit, 0) IsDisplayAttendance,
	--		Convert(bit, 0) IsDisplayHeightWeight,
	--		Convert(bit, 0) IsResultStatus,
	--		'' AS FooterAdjustmentText,
	--		'' AS DetailAdjustmentText,
	--		0 FooterAdjustment,
	--		0 DetailAdjustment,
		 		 
	--		0 TermScopeId,
		 
	--		Convert(bit, 0) IsPresent,
	--		'' AS GradeString,
	--		Convert(bit, 0) IsDisplayGradeString,
	--		Convert(decimal , 0) HighestDivisionMark,
	--		 ''  AS HighestDivisionGrade,			
	--		'' SmallAddress1,
	--		Convert(bit, 0) IsDisplayParentName,
			 
	--		Convert(bit, 0) AS IsShowSubjectMark,
			
	--		Convert(bit, 0) IsDisplayTeacherSign,
	--		Convert(bit, 0) IsDisplayPrincipalSign,
		 
	--		Convert(bit, 0) AS IsDisplayMonthlyAttendance,
			 
	--		Convert(bit, 0) AS IsImageHeader,
			 
	--		0 SubExamId,
	--		0 ExamOrderIndex,
	--		0 AnnualExamId ,
	--		'' DecimalFormat,
	--		0 TermExamId,
	--		'' AS ExamNAme, 			 
	--		'' AS AnnualSubjectGrade,
	--		Convert(decimal , 0) As AnnualSubjectObtain,
	--		'' AS TermSubjectGrade,
	--		Convert(decimal , 0) As TermSubjectObtain ,
	--		'' AS SubjectGrade,
	--      '' AS Remark,
	--      Convert(decimal , 0) AS ExamMaximum,
	--	  Convert(bit, 0) IsAbsentRemark,
	--	  '' AS AbsentRemark,
	--		0 TermExamOrderIndex
	  
			
 
 
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int, @lOrgId int, @lAbsentRemarkConfig nvarchar(20) = ''
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId

CREATE TABLE #TempExam
(
	SubExamId int, 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50),
	ExamMaximum decimal(6,2),
	TermExamOrderIndex int		-- MantisId : 0031760
)
--INSERT INTO #TempExam
--(
--	SubExamId,	 
--	ExamOrderIndex,
--	ExamId,
--	Exam 
--)
--Select 
	 
--	EC.SubExamId,
--	EC.ExamOrder,
--	EM.Id As ExamId,
--	ES.Title AS Exam
--	from sAssessment.tExamMaster EM 
--	INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId = EM.Id 
--	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId 
--	WHERE EM.Id=@rExamId 
Declare @lExamMaximum decimal(6,2)
Select @lExamMaximum = ExamMaximum from sAssessment.tExamMaster Where Id = @rExamId
INSERT INTO #TempExam
(
	 SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam,
	 ExamMaximum,
	 TermExamOrderIndex		-- Mantis Id : 0031760
)
Select  
	EC.SubExamId,
	EC.ExamOrder,
	EC.ExamId AS TermExamId,
	@rExamId AS AnnualExamId,
	ES.Title AS Exam,
	@lExamMaximum,
	SE.ExamOrder AS TermExamOrderIndex		-- Mantis Id : 0031760

	from  sAssessment.tExamCombine EC 
	INNER JOIN sAssessment.tExamMaster EM  ON EC.ExamId = EM.Id 
	 INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId
	 INNER JOIN (select SubExamId, ExamOrder from sAssessment.tExamCombine where examId = @rExamId) AS SE
	 ON EC.ExamId = SE.SubExamId  
	--WHere EC.ExamId  in  (select SubExamId from sAssessment.tExamCombine where examId = @rExamId  )
	--Select * from #TempExam
	
 
		
	
	
	
--INSERT INTO #TempExam
--(
--	ExamId, 
--	ExamOrderIndex
--)
--Select 
	 
--	@rExamId,
--	999 
	 --Select * from #TempExam
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			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,			
			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.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
		 		 
			EM.TermScopeId,
		 
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			 
			EC.SubExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamNAme, 			 
			ARD.SubjectGrade AS AnnualSubjectGrade,
			ARD.Obtain As AnnualSubjectObtain,
			TRD.SubjectGrade AS TermSubjectGrade,
			TRD.Obtain As TermSubjectObtain ,
			RD.SubjectGrade AS SubjectGrade,
			ISNULL(ARD.Remark,'')  AS Remark,
			EC.ExamMaximum,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			ISNULL(RD.AbsentRemark,'') AS AbsentRemark,
			EC.TermExamOrderIndex								-- Mantis Id : 0031760
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.SubExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id AND ACS.SubjectId = @rSubjectId  
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.TermExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id AND TCS.SubjectId = @rSubjectId 
			
			
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
		    LEFT JOIN
			(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = StuM.Id 
				
			--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
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--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
	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 (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		--order by A.RollNo,CS.OrderIndex 
		
	 drop table #TempExam
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectwisePassFailAndAbsentAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 --@rClass nvarchar(MAX)='',
	 @rGroupByid int=0,
 	 @rSubject nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		 
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Sm.OrderIndex As SubjectOrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		CM.OrderIndex AS ClassOrderIndex,
		case when @rGroupByid=1 THEN Dm.Id
		when @rGroupByid=2 THEN CM.Classid
		when @rGroupByid=3 THEN CM.DepartmentId
	    when @rGroupByid=4 THEN OM.Id
		ELSE 0  END  AS HeadId,
		case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle   
		when @rGroupByid=2 THEN ' Class : ' + CM.ClassName 
		when @rGroupByid=3 THEN 'Department: ' + DP.Title 
		WHen @rGroupByid=4 THen  'Organization : '+Om.Title END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
		WHEN @rGroupByid=2  THEN CM.OrderIndex
		WHEN @rGroupByid=3  THEN DP.Id
		WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
		

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	  INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
	  AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum) AS FailStudent,
	  
	  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.IsPresent = 0) AS AbsentStudent  
	  
	  
	-- from
	-- ssetup.tDivisionMaster DM
	-- INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	--INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	--INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	--INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	-- INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
 --   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId

	--	WHERE 
	--		((DM.ID=@rDivisionId) or (@rDivisionId=0))
	--		AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
	--		AND CM.BatchId=@rBatchId
	--		AND EM.ExamSubGroupId = @rExamSubGroupId
	--		AND EM.BatchId = @rBatchId
	--		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
	
	from		
		sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	WHERE 		
		
		EM.BatchId = @rBatchId 
		AND  ((@rClassId > 0 AND cs.ClassId=@rClassId)
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
		AND	CM.BatchId = @rBatchId
		AND EM.ExamSubGroupId = @rExamSubGroupId
		AND EM.BatchId = @rBatchId
		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject=''))
	
  UNION ALL
  
  
  	 select 
		@rBuilder1 AS Builder1,
		DM.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
	0 AS ClassSubjectId,
		0 AS SubjectId,
		'Over All' AS SubjectName,
		0 As SubjectOrderIndex,
		0 AS DivisionOrderIndex,
		0 AS ClassOrderIndex,
		case when @rGroupByid=1 THEN Dm.Id
		when @rGroupByid=2 THEN CM.Classid
		when @rGroupByid=3 THEN CM.DepartmentId
	    when @rGroupByid=4 THEN OM.Id
		ELSE 0    END  AS HeadId,
		case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle  
		when @rGroupByid=2 THEN ' Class : ' + CM.ClassName  
		when @rGroupByid=3 THEN 'Department: ' + DP.Title 
		WHen @rGroupByid=4 THEN  'Organization : '+OM.Title
		END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN DP.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
	 

 (select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND R.ResultStatus='PASS') AS PassStudent,
	  
	  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent,
	  
	 0 AS AbsentStudent  
	  
    
	 --from
	 --ssetup.tDivisionMaster DM
	 --INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	 --INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	 --INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
  --  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
		--WHERE 
		--	((DM.ID=@rDivisionId) or (@rDivisionId=0))
		--	AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
		--	AND CM.BatchId=@rBatchId
		--	AND EM.ExamSubGroupId = @rExamSubGroupId
		--	AND EM.BatchId = @rBatchId
		
	FROM		
		sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	WHERE 		
		
		EM.BatchId = @rBatchId 
		AND  ((@rClassId > 0 AND cs.ClassId=@rClassId)
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
		AND	CM.BatchId = @rBatchId
		AND EM.ExamSubGroupId = @rExamSubGroupId
		AND EM.BatchId = @rBatchId
		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject=''))
			
			--AND (ISNULL(ClassSubjectId,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pRptSubjectWiseRemarkGet]
 
	 @rExamId bigint,
	 @rAcademicId bigint=0,
	 @rBatchId int=0 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


	SELECT 
		convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),@rAcademicId)As AcademicIdText
		,ED.ClassSubjectId AS ClassSubjectId
		,SA.Name AS StudentName
		,ISNULL(RD.Remark,'') AS SubjectRemark,
		V.SubjectName
	from sStudent.vStudentAcademic SA
		 INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
		 INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
		 INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id
		 INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id
		 LEFT JOIN sAssessment.tResultDetailOther RD ON  RD.AcademiciD=SA.AcademicId  AND EM.ID=RD.ExamId   AND RD.ClassSubjectID = Ed.ClassSubjectId 
		 LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId     
	Where  
		(EM.Id=@rExamId OR @rExamId = 0)
		AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND SA.StatusId=1 AND SA.BatchId=@rBatchId
		AND ((V.IsOptional = 1 AND  isnull(SA.AcademicId,0) <> 0) OR (V.IsOptional = 0))
	Order By ED.DisplayOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAssessment].[pRptTeacherEvaluationExamWise]
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rDepartmentId int=0,
	 @rClassId int,
	 @rDivisionId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rOrgId int,		-- Changed to @rOrgId From @rOrggroupId, Mantis Id : 0036668
	 @rTop int=0,
	 @rTeacherClass NVARCHAR(MAX)='',
	 @rEmployeeId bigint,
	 @rClassExam NVARCHAR(MAX)='',
	 @rBatchId int,
	 @rClassStatusId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lMarkEntryBasedOn nvarchar(50)
SELECT @lMarkEntryBasedOn=CS.ItemValue FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.Configurationid AND CS.SourceId=@rOrgId WHERE CM.Id = 188


IF(@lMarkEntryBasedOn='Class Teacher')
BEGIN

SELECT 
			@rTop RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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,
			EM.Id AS ExamId
	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
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			--INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		--AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.DivisionId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,CS.OrderIndex 
	
END 
IF(@lMarkEntryBasedOn='Class Teacher Batch')
BEGIN
SELECT 
			@rTop AS RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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,
			EM.Id AS ExamId
	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
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
			
	WHERE 
		EM.BatchId = @rBatchId 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.DivisionId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND DIE.Number = (SELECT MIN(Number) FROM sSetup.tDivisionInchargeEmployee WHERE  DIE.DivisionId = DM.Id AND DIE.BatchId = @rBatchId)
		order by A.RollNo,CS.OrderIndex 
END 

IF(@lMarkEntryBasedOn='Academic Setup')
BEGIN
SELECT 
			@rTop AS RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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,
			EM.Id AS ExamId
			
	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
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			
	WHERE 
		EM.BatchId = @rBatchId 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.DivisionId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,CS.OrderIndex 
END 

IF(@lMarkEntryBasedOn='User Access')
BEGIN
SELECT 
			@rTop AS RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			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,
			EM.Id AS ExamId
	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
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			--INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId= 2005
			
	WHERE 
		EM.BatchId = @rBatchId 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		--AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.DivisionId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,CS.OrderIndex 
END 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pRptTeacherEvaluationSubjectAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0
	,@rEmployeeId bigint=0
	 ,@rFromRollNo int
	 ,@rToRollNo int
	 ,@rCode nvarchar(20)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		
		
 
	 DECLARE @GradeSetId int
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
		
	 --Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = @rExamSubGroupId AND BatchId=@rBatchId AND (ClassId = @rClassId OR @rClassId = 0))

	 --According to AssessmentConfiguration
	 Set @GradeSetId = (Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId = @rOrgId)
		  --Select @GradeSetId
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId
	 
	 	 Set @G1=(Select GradeCode from #Temp where Id=1) 
	 	 Set @G2=(Select GradeCode from #Temp where Id=2) 
	 	 Set @G3=(Select GradeCode from #Temp where Id=3) 
	 	 Set @G4=(Select GradeCode from #Temp where Id=4) 
	     Set @G5=(Select GradeCode from #Temp where Id=5) 
         Set @G6=(Select GradeCode from #Temp where Id=6) 
	     Set @G7=(Select GradeCode from #Temp where Id=7) 
	 	 Set @G8=(Select GradeCode from #Temp where Id=8) 
	 	 Set @G9=(Select GradeCode from #Temp where Id=9) 
		 Set @G10=(Select GradeCode from #Temp where Id=10)  
	   
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As ClassName,
		DM.DisplayTitle As DivisionName,
		
		 
	  
	  (select COUNT(RD.Id) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id	  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) 
	  AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	  AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	  AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	  AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS NoOfStudent,
	  
	 

	  (select MAX(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS HighestPerMark,

	  (select AVG(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id   
	    INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS AveragePerMark, -- Add RD.IsPresent = 1 for Mantis : 0028928
	  
	  (select MIN(RD.Obtain) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id 
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	    INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS LowestPerMark , 
	  
	  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G1		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  )AS GradeCount1,
	  
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G2		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  )AS GradeCount2,
	 

  (Select COUNT(R.AcademicId)from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R   ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G3		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0) AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  )AS GradeCount3,
	 

  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
		AND  SubjectGrade = @G4  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) 
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	)AS GradeCount4,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G5		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  )AS GradeCount5,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G6		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  )AS GradeCount6,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
		AND  SubjectGrade = @G7  AND CS.SubjectId=SM.Id  AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) 
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
		)AS GradeCount7,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
		AND  SubjectGrade = @G8	  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	)AS GradeCount8,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id  
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
	  AND  SubjectGrade = @G9  AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (EM.ClassId=@rClassId OR @rClassId=0)
	AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((A.Code=@rCode) OR (@rCode=''))
	)AS GradeCount9,
	 
  (Select COUNT(R.AcademicId) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id   
  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND  SubjectGrade = @G10		AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND (EM.ClassId=@rClassId OR @rClassId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	)AS GradeCount10,
	  
	  
   
	  ISNULL(@G1,'*') AS Grade1,
	  ISNULL(@G2,'*') AS Grade2,
	  ISNULL(@G3,'*') AS Grade3,
	  ISNULL(@G4,'*') AS Grade4,
	  ISNULL(@G5,'*') As Grade5,
	  ISNULL(@G6,'*') As Grade6,
	  ISNULL(@G7,'*') AS Grade7,
	  ISNULL(@G8,'*') AS Grade8,
	  ISNULL(@G9,'*') AS Grade9,
	 ISNULL(@G10,'*')  AS Grade10,
	 Sm.Id AS SubjectId,
	  SM.Title AS SubjectName,
	  CS.OrderIndex AS OrderIndex,
	  (select COUNT(R.AcademicId) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
		where 
			A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
			AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) AND CS.SubjectId=SM.Id 
			AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
			AND ISNULL(RD.IsPresent,0) = 0 
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		) AS AbsentCount,
		(select MAX(ED.Maximum) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
	  AND CS.SubjectId=SM.Id		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS MaximumMark, 

	  	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((RD.Obtain<ED.Minimum) OR (RD.IsPresent = 0)) AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) 
	  AND ((A.ClassStatusId = @rClassStatusId) OR (@rClassStatusId=0))
	  AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	  AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	  AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS FailStudent, 

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND (CASE WHEN ED.Maximum <> 0 THEN (RD.Obtain * 100.0 / ED.Maximum) ELSE 0 END) > 90 AND ((A.StatusId=@rStatusId) OR			(@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) AND RD.IsPresent = 1
	  AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((A.Code=@rCode) OR (@rCode=''))
	  ) AS Above90PercentStudent -- add for mantis : 0035813
	  ,TSD.EmployeeId
	,ISNULL(EmpM.FirstName, '') + ' ' + ISNULL(EmpM.LastName, '') AS TeacherName,
	EmpM.FirstName,
	EmpM.MiddleName,
	EmpM.LastName,
	EmpM.Code AS EmployeeCode
	  
	 from
 

		sAssessment.tExamDetail ED		
		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 sSetup.tClassMaster CLM ON CLM.Id=EM.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CLM.Id
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
		INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON SM.Id = TSD.SubjectId AND DM.Id = TSD.DivisionId
		INNER JOIN sHrm.tEmployeeMaster EmpM ON TSD.EmployeeId = EmpM.Id 
		AND EmpM.StatusId = 7		
	
		WHERE 
 
			
			EM.BatchId = @rBatchId 
			AND (EM.ClassId=@rClassId OR @rClassId=0) 
			AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
			AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
			AND CM.BatchId = @rBatchId
			AND (CLM.DepartmentId=@rDepartmentId OR @rDepartmentId=0)	
			AND (ISNULL(CLM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND CLM.IsObsolete = 0 AND DM.IsObsolete=0
			AND TSD.EmployeeId = @rEmployeeId
  	
END

-- SP Drag and Drop
--BEGIN
--	SELECT 
--	 '' AS Builder1,
--	 0 AS ClassId,
--	 0 AS DivisionId,
--	 '' AS ClassName,
--	 '' AS DivisionName,
--	 0 AS NoOfStudent,
--	 Convert(DECIMAL,0) HighestPerMark,
--	 Convert(DECIMAL,0) AveragePerMark,
--	 Convert(DECIMAL,0) LowestPerMark,
--	 0 AS GradeCount1,
--	 0 AS GradeCount2,
--	 0 AS GradeCount3,
--	 0 AS GradeCount4,
--	 0 AS GradeCount5,
--	 0 AS GradeCount6,
--	 0 AS GradeCount7,
--	 0 AS GradeCount8,
--	 0 AS GradeCount9,
--	 0 AS GradeCount10,
--	 '' AS Grade1,
--	 '' AS Grade2,
--	 '' AS Grade3,
--	 '' AS Grade4,
--	 '' AS Grade5,
--	 '' AS Grade6,
--	 '' AS Grade7,
--	 '' AS Grade8,
--	 '' AS Grade9,
--	 '' AS Grade10,
--	 0 AS SubjectId,
--	 '' AS SubjectName,
--	 0 AS OrderIndex,
--	 0 AS AbsentCount,
--	 Convert(DECIMAL,0) MaximumMark,
--	 0 AS FailStudent,
--	 0 AS Above90PercentStudent
--	, '' AS TeacherName
--	, '' AS FirstName
--	, '' AS MiddleName
--	, '' AS LastName
--	, '' AS EmployeeCode

--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pRptWeekStudentAnalysisListGet]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 --@rGrade nvarchar(20)='',
	 --@rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rDepartmentId int = 0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rResultStatus nvarchar(20)=''  --Mantis - 34666

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

SELECT r1.* from 
(
	SELECT 
	 
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		 
			ROW_NUMBER() OVER(PARTITION BY 
							CASE WHEN @rGroupId=1 THEN DM.Id 
							WHEN @rGroupId=2 THEN CM.Id 
							WHEN @rGroupId =3 THEN Dept.Id 
							WHEn @rGroupId =4 THEN OM.Id END  
					 ORDER BY R.Percentage ASC) rn,
			
			ESGM.Title AS Exam,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId )  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			R.TotalMarks,
			R.TotalObtain,
			R.ResultGrade,
			R.ResultStatus   --Mantis - 34666
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND ((Dept.Id = @rDepartmentId) OR (@rDepartmentId =0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank = 0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank = 0))
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))  --Mantis - 34666
		) r1
		
	WHERE ( r1.rn <= @rTop Or @rTop = 0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSiddhiKrupaFieldsGet]

	  @rTypeId smallint,
	  @rDivisionId int,
	  @rExamSubGroupId int,
	  @rBatchId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF (@rTypeId = 1)		 --- For Applying Siddhi Marks	 
	BEGIN 	
			DECLARE @tAcademicIdSiddhi Table (Id Int identity, AcademicId bigint)
			
			-- Make Unique Academic List as per Applicable for Siddhi
			INSERT INTO @tAcademicIdSiddhi(AcademicId)
			SELECT DISTINCT SA.AcademicId 
			FROM sAssessment.tExamMaster EM 
				 INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
				 INNER JOIN sAssessment.tResult RM ON RM.ExamId = EM.Id
				 INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RM.Id AND RD.ExamDetailId = ED.Id
				 INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId AND SA.DivisionId = @rDivisionId 
			WHERE 
				 EM.ExamSubGroupId = @rExamSubGroupId  AND EM.BatchId = @rBatchId
				 AND SA.DivisionId = @rDivisionId  
				 AND Percentage-OverallPercentageForGrace >  0 	   
				 AND RD.Obtain < ED.Minimum AND Obtain >= MinimumGracePercetage --AND SA.StatusId = 1 
			
			-- List of Siddhi Applicable Subject AcademicId wise
			CREATE Table #tTempSiddhiDataTable  
			(Id Int identity,AcademicId bigint, ClassSubjectId int, Minimum int, Obtain int,Percentage int, ApplicableGrace int, OverallPercentageForGrace int, MinimumGracePercetage int, GraceMaxMark int, KrupaMaxMark int)
			
			DECLARE @lCountSiddhi int,@lCountProcessSiddhi int,@lAcademicIdSiddhi bigint
			DECLARE @ApplicableSiddhiMarkNotFull int
			DECLARE @ApplicableSiddhiMarkFull int
			
			SELECT @lCountSiddhi = COUNT(Id) FROM @tAcademicIdSiddhi 

			--  Update Division wise All Academic Student GraceMark/KrupaMark set to "0"
			UPDATE RD SET RD.GraceMark = 0,RD.KrupaMark = 0	
			FROM sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult RM ON RM.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 sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId
			WHERE SA.DivisionId=@rDivisionId AND EM.ExamSubGroupID=@rExamSubGroupId 

			WHILE (@lCountSiddhi > 0)  -- AcademicId wise Loop
			BEGIN
				SELECT  @lAcademicIdSiddhi = AcademicId FROM @tAcademicIdSiddhi WHERE Id=@lCountSiddhi 
				TRUNCATE TABLE #tTempSiddhiDataTable   -- Reset SiddhiData Table AcademicId Wise And Load Data Applicable SiddhiMark Subject
				INSERT INTO #tTempSiddhiDataTable
				SELECT				
					 SA.AcademicId,
					 ED.ClassSubjectId,
					 CONVERT(int,ED.Minimum) AS Minimum,
					 CONVERT(int,RD.Obtain) AS Obtain,
					 Percentage,
					 CONVERT(int,Case When Round(Percentage,0)-isnull(OverallPercentageForGrace,0) <=  ISNULL(EM.GraceMaxMark,0) 
					 Then Round(Percentage,0)-isnull(OverallPercentageForGrace,0) Else ISNULL(EM.GraceMaxMark,0) End ) AS ApplicableGrace,
					 ISNULL(EM.OverallPercentageForGrace,0) AS OverallPercentageForGrace,
					 ISNULL(EM.MinimumGracePercetage,0) AS MinimumGracePercetage, 
					 ISNULL(EM.GraceMaxMark,0) AS GraceMaxMark, 
					 ISNULL(EM.KrupaMaxMark,0) AS KrupaMaxMark
				FROM  
					 sAssessment.tExamMaster EM 
					 INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
					 INNER JOIN sAssessment.tResult RM ON RM.ExamId = EM.Id
					 INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RM.Id AND RD.ExamDetailId = ED.Id
					 INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId AND SA.DivisionId = @rDivisionId 				
				WHERE 
					 EM.ExamSubGroupId = @rExamSubGroupId  AND EM.BatchId = @rBatchId
					 AND SA.DivisionId = @rDivisionId  --AND SA.StatusId = 1
					 AND Percentage-OverallPercentageForGrace >  0 	   
					 AND RD.Obtain < ED.Minimum AND Obtain >= MinimumGracePercetage AND SA.AcademicId = @lAcademicIdSiddhi
			
				SELECT @lCountProcessSiddhi = COUNT(Id) FROM #tTempSiddhiDataTable
	
	
				SET @ApplicableSiddhiMarkFull = 0
				WHILE (@lCountProcessSiddhi >  0 )
				BEGIN
					
					DECLARE @lSubjectIdSiddhi int ,@AcademicIdSiddhi bigint,@lApplicableMarkSiddhi int, @lObtainSiddhi int,@lMinimumGraceSiddhi int, @lUpdateMarkSiddhi int
					DECLARE @lGraceMarkSiddhi int , @lMinimumMarkSiddhi int
					
					SELECT @lSubjectIdSiddhi = ClassSubjectId,@lApplicableMarkSiddhi = ApplicableGrace,@lObtainSiddhi = Obtain, @lMinimumMarkSiddhi = Minimum,
					@lMinimumGraceSiddhi = MinimumGracePercetage FROM #tTempSiddhiDataTable WHERE Id = @lCountProcessSiddhi
					
					
					If @ApplicableSiddhiMarkFull = 0 AND @ApplicableSiddhiMarkFull <> @lApplicableMarkSiddhi  -- Setting for only once Applicable Marks For All Subject of AcademicId
					BEGIN
						SET @ApplicableSiddhiMarkFull = @lApplicableMarkSiddhi															
					END

					IF @ApplicableSiddhiMarkFull >  0
					BEGIN
						IF(@lMinimumMarkSiddhi - @lObtainSiddhi > @ApplicableSiddhiMarkFull)
						BEGIN	
							UPDATE RD SET RD.GraceMark = @ApplicableSiddhiMarkFull	
							FROM sAssessment.tResultDetail RD
							INNER JOIN sAssessment.tResult RM ON RM.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 sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId
							WHERE ED.ClassSubjectID = @lSubjectIdSiddhi AND RM.AcademicId = @lAcademicIdSiddhi AND EM.ExamSubGroupID=@rExamSubGroupId
							
							SET @ApplicableSiddhiMarkFull =  -1  -- Indicate : Siddhi Mark Completed

						END	
						ELSE
						BEGIN
							SET @ApplicableSiddhiMarkNotFull= (@lMinimumMarkSiddhi - @lObtainSiddhi)

							UPDATE RD SET RD.GraceMark = @ApplicableSiddhiMarkNotFull  --ED.Minimum - RD.Obtain	
							FROM sAssessment.tResultDetail RD
							INNER JOIN sAssessment.tResult RM ON RM.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 sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId
							WHERE ED.ClassSubjectID = @lSubjectIdSiddhi AND RM.AcademicId = @lAcademicIdSiddhi AND EM.ExamSubGroupID=@rExamSubGroupId
							SET @ApplicableSiddhiMarkFull= @ApplicableSiddhiMarkFull -@ApplicableSiddhiMarkNotFull
							If @ApplicableSiddhiMarkFull = 0 
							begin
									SET @ApplicableSiddhiMarkFull  = -1  -- Indicate : Siddhi Mark Completed
							End
						END	
					END
					SET @lCountProcessSiddhi = @lCountProcessSiddhi -1
				END 
				
			  SET @lCountSiddhi = @lCountSiddhi - 1
			END
				  DROP TABLE #tTempSiddhiDataTable
			
			
			SELECT 1 AS Result
	END

	IF (@rTypeId=2) -- For Applying Krupa Marks
	BEGIN
			DECLARE @tAcademicIdKrupa Table (Id Int identity, AcademicId bigint)
			
			UPDATE RD SET RD.KrupaMark = 0	
			FROM sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult RM ON RM.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 sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId
			WHERE SA.DivisionId=@rDivisionId AND EM.ExamSubGroupID=@rExamSubGroupId 
			
			-- Make Unique Academic List as per Applicable for Krupa
			INSERT INTO @tAcademicIdKrupa(AcademicId)
			SELECT DISTINCT SA.AcademicId
			FROM sAssessment.tExamMaster EM 
				 INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
				 INNER JOIN sAssessment.tResult RM ON RM.ExamId = EM.Id
				 INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RM.Id AND RD.ExamDetailId = ED.Id
				 INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId AND SA.DivisionId = @rDivisionId 
			WHERE 
				 EM.ExamSubGroupId = @rExamSubGroupId  AND EM.BatchId = @rBatchId
				 AND SA.DivisionId = @rDivisionId  
				 AND Percentage-OverallPercentageForGrace >  0 	   
				 AND (RD.Obtain + GraceMark) < ED.Minimum  AND Obtain >= MinimumGracePercetage --AND SA.StatusId = 1
				 --AND SA.AcademicId = 1101000006737
			
			-- List of Krupa Applicable Subject AcademicId wise
			CREATE Table #tTempKrupaDataTable  
			(Id Int identity,AcademicId bigint, ClassSubjectId int, Minimum int, Obtain int,Percentage int, ApplicableGrace int, OverallPercentageForGrace int, MinimumGracePercetage int, GraceMaxMark int, KrupaMaxMark int, SiddhiGraceMark int)
			
			DECLARE @lCountKrupa int,@lCountProcessKrupa int,@lAcademicIdKrupa bigint
			DECLARE @ApplicableKrupaMarkNotFull int
			DECLARE @ApplicableKrupaMarkFull int
			
			SELECT @lCountKrupa = COUNT(Id) FROM @tAcademicIdKrupa 

			WHILE (@lCountKrupa > 0)  -- AcademicId wise Loop
			BEGIN
				SELECT  @lAcademicIdKrupa = AcademicId FROM @tAcademicIdKrupa WHERE Id=@lCountKrupa 
				TRUNCATE TABLE #tTempKrupaDataTable  -- Reset KrupaData Table AcademicId Wise And Load Data Applicable KrupaMark Subject
				INSERT INTO #tTempKrupaDataTable
				SELECT				
					 SA.AcademicId,
					 ED.ClassSubjectId,
					 CONVERT(int,ED.Minimum) AS Minimum,
					 CONVERT(int,RD.Obtain) AS Obtain,
					 Percentage,
					  ISNULL(EM.KrupaMaxMark,0) AS ApplicableGrace,
					 ISNULL(EM.OverallPercentageForGrace,0) AS OverallPercentageForGrace,
					 ISNULL(EM.MinimumGracePercetage,0) AS MinimumGracePercetage, 
					 ISNULL(EM.GraceMaxMark,0) AS GraceMaxMark, 
					 ISNULL(EM.KrupaMaxMark,0) AS KrupaMaxMark,
					 ISNULL(RD.GraceMark,0) AS SiddhiGraceMark
				FROM  
					 sAssessment.tExamMaster EM 
					 INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
					 INNER JOIN sAssessment.tResult RM ON RM.ExamId = EM.Id
					 INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RM.Id AND RD.ExamDetailId = ED.Id
					 INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId AND SA.DivisionId = @rDivisionId 				
				WHERE 
					 EM.ExamSubGroupId = @rExamSubGroupId  AND EM.BatchId = @rBatchId
					 AND SA.DivisionId = @rDivisionId  --AND SA.StatusId = 1
					 AND Percentage - OverallPercentageForGrace >  0 	   
					 AND (RD.Obtain + RD.GraceMark) < ED.Minimum AND Obtain >= MinimumGracePercetage AND SA.AcademicId = @lAcademicIdKrupa
				
				
				SELECT @lCountProcessKrupa = COUNT(Id) FROM #tTempKrupaDataTable
				
				SET @ApplicableKrupaMarkFull = 0
				
				WHILE (@lCountProcessKrupa >  0 )
				BEGIN
				
					DECLARE @lSubjectIdKrupa int ,@AcademicIdKrupa bigint,@lApplicableMarkKrupa int, @lObtainKrupa int,@lMinimumGraceKrupa int, @lUpdateMarkKrupa int
					DECLARE @lGraceMarkKrupa int , @lMinimumMarkKrupa int, @lSiddhiGraceMark int
					
					SELECT @lSubjectIdKrupa = ClassSubjectId,@lApplicableMarkKrupa = ApplicableGrace,@lObtainKrupa = Obtain, @lMinimumMarkKrupa = Minimum,
					@lMinimumGraceKrupa = MinimumGracePercetage, @lSiddhiGraceMark = SiddhiGraceMark FROM #tTempKrupaDataTable WHERE Id = @lCountProcessKrupa
					
					If @ApplicableKrupaMarkFull = 0 AND @ApplicableKrupaMarkFull <> @lApplicableMarkKrupa  -- Setting for only once Applicable Marks For All Subject of AcademicId
					BEGIN
						SET @ApplicableKrupaMarkFull = @lApplicableMarkKrupa															
					
					END	
					IF @ApplicableKrupaMarkFull >  0
					BEGIN
						IF(@lMinimumMarkKrupa - (@lObtainKrupa + @lSiddhiGraceMark) > @ApplicableKrupaMarkFull)
						BEGIN	
							UPDATE RD SET RD.KrupaMark = @ApplicableKrupaMarkFull	
							FROM sAssessment.tResultDetail RD
							INNER JOIN sAssessment.tResult RM ON RM.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 sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId
							WHERE ED.ClassSubjectID = @lSubjectIdKrupa AND RM.AcademicId = @lAcademicIdKrupa AND EM.ExamSubGroupID=@rExamSubGroupId
							SET @ApplicableKrupaMarkFull =  -1    -- Indicate : Krupa Mark Completed
							
							--SELECT @ApplicableKrupaMarkFull,@lAcademicIdKrupa,@lSubjectIdKrupa
						END	
						ELSE
						BEGIN
							SET @ApplicableKrupaMarkNotFull = (@lMinimumMarkKrupa - (@lObtainKrupa + @lSiddhiGraceMark))
						
						   -- SELECT @ApplicableKrupaMarkFull,@lAcademicIdKrupa,@lSubjectIdKrupa
						
							UPDATE RD SET RD.KrupaMark = @ApplicableKrupaMarkNotFull	
							FROM sAssessment.tResultDetail RD
							INNER JOIN sAssessment.tResult RM ON RM.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 sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId
							WHERE ED.ClassSubjectID = @lSubjectIdKrupa AND RM.AcademicId = @lAcademicIdKrupa AND EM.ExamSubGroupID=@rExamSubGroupId
							
							
							
							SET @ApplicableKrupaMarkFull= @ApplicableKrupaMarkFull -@ApplicableKrupaMarkNotFull
							IF @ApplicableKrupaMarkFull = 0 
							BEGIN
									SET @ApplicableKrupaMarkFull  = -1  -- Indicate : Krupa Mark Completed
							END
						END	
					END
					SET @lCountProcessKrupa = @lCountProcessKrupa -1
				END 
				
			  SET @lCountKrupa = @lCountKrupa - 1
			END
				  SELECT 101 AS Result
				  DROP TABLE #tTempKrupaDataTable
				  
	END
	
	DECLARE @lExamId int
	SELECT @lExamId = EM.Id from sAssessment.tExamMaster EM
				      INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = EM.ClassId
				      Where EM.ExamSubGroupId=@rExamSubGroupId AND EM.BatchId = @rBatchId AND DM.Id = @rDivisionId

	exec [sAssessment].[pMarkEntryMasterUpdate]	@rExamId = @lExamId, @rDivisionId = @rDivisionId,@rBatchId = @rBatchId
	exec [sAssessment].[pMarkEntryRankUpdate] @rExamId = @lExamId,@rDivisionId = @rDivisionId,@rBatchId = @rBatchId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pStaticCCECSGroupMasterAdd]
	 
	     @rOrgId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lNextNumber BIGINT,@lCount int 
	 declare @lCheckCount int 
	 Select @lCheckCount = Count(Id) from sAssessment.tCCECSGroupMaster where OrgId=@rOrgId 
	 
	 if @lCheckCount<=0
	 BEGIN
	--Create Table #TempStaticGroup
	--(
	--	IdNumber int  identity,Id BIGINT,
	--	Code NVARCHAR(20),Number smallint,Title nvarchar(100),OrgId smallint,CCECSGroupTypeId tinyint,GradeSetId int,IsObsolete bit,OrderIndex smallint,UpdatedUserId bigint,UpdatedDateTime datetime
	--)
	--Insert into #TempStaticGroup
	--(
	--	Id,
	--	Code,Number,Title,OrgId,CCECSGroupTypeId,GradeSetId,IsObsolete,OrderIndex,UpdatedUserId,UpdatedDateTime
	--)
	--Select 
	--	Id,Code,Number,Title,@rOrgId,CCECSGroupTypeId,GradeSetId,IsObsolete,OrderIndex,UpdatedUserId,sCommon.fGetDate()
	--fROM sAssessment.tStaticCCECSGroupMaster Where IsObsolete=0
	 
	--Select @lCount = COUNT(Id) From #TempStaticGroup
	--while (@lCount>0)
	--BEGIN
	--	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCECSGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			 insert Into sAssessment.tCCECSGroupMaster
	 (
		Id,
		Code,Number,Title,OrgId,CCECSGroupTypeId,GradeSetId,IsObsolete,OrderIndex,UpdatedUserId,UpdatedDateTime
	 )
	 Select 
	 sCommon.fGetIntIdForOrg(Id,@rOrgId),Code,Number,Title,@rOrgId,CCECSGroupTypeId,sCommon.fGetIntIdForOrg(GradesetId,@rOrgId),IsObsolete,OrderIndex,UpdatedUserId,sCommon.fGetDate()
	 From sAssessment.tStaticCCECSGroupMaster Where  IsObsolete=0
	--    Set @lCount=@lCount-1
	--END
	Select 1 as result
	END
	else
	BEGIN
		Select 101 as result
	END
  
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pStaticCCECSMasterAdd]
	 
	 @rOrgId smallint    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	  DECLARE @lNextNumber BIGINT ,@lCount int 
	  Declare @lCheckCount int
	  Select @lCheckCount = COUNT(Id) from sAssessment.tCCECSMaster where OrgId=@rOrgId
	  if @lCheckCount<=0
	  BEGIN
	  
	--  Create Table #TempStaticGroup
	--(
	--	IdNumber int  identity,Id BIGINT,
	--	CCECAGroupId int,Number smallint,Title nvarchar(100),OrgId smallint,IsObsolete bit,OrderIndex smallint,UpdatedUserId bigint,UpdatedDateTime datetime 
	--)
	--Insert into #TempStaticGroup
	--(
	--	 Id,CCECAGroupId,Number,Title,OrgId,IsObsolete,OrderIndex,UpdatedUserId,UpdatedDateTime
	--)
	--Select 
	--	Id,CCECAGroupId,Number,Title,@rOrgId,IsObsolete,OrderIndex,UpdatedUserId ,sCommon.fGetDate()
	--fROM sAssessment.tStaticCCECSMaster Where IsObsolete=0
	--Select @lCount = COUNT(Id) From #TempStaticGroup
	
	--while (@lCount>0)
	--BEGIN
	
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tCCECSMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 insert Into sAssessment.tCCECSMaster 
	 (
		 Id,CCECAGroupId,Number,Title,OrgId,IsObsolete,OrderIndex,UpdatedUserId,UpdatedDateTime
	 )
	 Select 
		sCommon.fGetIntIdForOrg(Id,@rOrgId),sCommon.fGetIntIdForOrg(CCECAGroupId,@rOrgId),Number,Title,@rOrgId,IsObsolete,OrderIndex,UpdatedUserId,sCommon.fGetDate()
	 From sAssessment.tStaticCCECSMaster Where  IsObsolete=0
	 
	--	  Set @lCount=@lCount-1
	--END
	Select 1 as result
	END
	Else
	BEgin
		Select 101 as result
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pStudentExamDetailGet]
	
	@rDivisionId int =0,
	@rBatchId int = 0,
	@rExamId int = 0,
	@rOrgId int = 0,
	@rUserId bigint = 0

AS
BEGIN
	
	DECLARE @lEmployeeId bigint=0
	SELECT @lEmployeeId=SourceId FROM sSecurity.tUser WHERE Id=@rUserId
	PRint @lEmployeeId
	DECLARE @lMarkEntryBasedOn nvarchar(50)=''
	SELECT @lMarkEntryBasedOn=ItemValue FROM [sConfig].[tConfigurationSetup] where ConfigurationId=188 and SourceId=@rOrgId
	Print @lMarkEntryBasedOn
	IF(@lMarkEntryBasedOn = 'Class Teacher' AND @lMarkEntryBasedOn IS NOT NULL)
	BEGIN
		Select DISTINCT 
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS StudentName,
			StuM.Code,
			A.RollNo,
			R.AcademicId,
			ISNULL(R.TotalMarks,0)AS TotalMarks,
			ISNULL(R.TotalObtain,'')AS TotalObtain,
			ISNULL(R.ResultStatus,'')AS ResultStatus,
			ISNULL(R.Percentage,0)AS Percentage
		FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId 
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId= EM.ClassId
		Where ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
			AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND ((R.ExamId = @rExamId) OR (@rExamId = 0))
			AND (DM.InchargeemployeeID=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
	END

	ELSE IF(@lMarkEntryBasedOn = 'Class Teacher Batch'  AND @lMarkEntryBasedOn IS NOT NULL)
	BEGIN
		Select DISTINCT 
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS StudentName,
			StuM.Code,
			A.RollNo,
			R.AcademicId,
			ISNULL(R.TotalMarks,0)AS TotalMarks,
			ISNULL(R.TotalObtain,'')AS TotalObtain,
			ISNULL(R.ResultStatus,'')AS ResultStatus,
			ISNULL(R.Percentage,0)AS Percentage
		FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId 
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId= EM.ClassId
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id

		Where ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
			AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND ((R.ExamId = @rExamId) OR (@rExamId = 0))
			AND (DIE.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
	END

	ELSE IF(@lMarkEntryBasedOn = 'Academic Setup'  AND @lMarkEntryBasedOn IS NOT NULL)
	BEGIN
		Select DISTINCT 
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS StudentName,
			StuM.Code,
			A.RollNo,
			R.AcademicId,
			ISNULL(R.TotalMarks,0)AS TotalMarks,
			ISNULL(R.TotalObtain,'')AS TotalObtain,
			ISNULL(R.ResultStatus,'')AS ResultStatus,
			ISNULL(R.Percentage,0)AS Percentage
		FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId 
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId 
		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = EM.ClassId AND vTSD.SubjectId = SM.Id 

		Where ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
			AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND ((R.ExamId = @rExamId) OR (@rExamId = 0))
			AND (vTSD.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
	END

	ELSE IF(@lMarkEntryBasedOn = 'User Access'  AND @lMarkEntryBasedOn IS NOT NULL)
	BEGIN
		Select DISTINCT 
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS StudentName,
			StuM.Code,
			A.RollNo,
			R.AcademicId,
			ISNULL(R.TotalMarks,0)AS TotalMarks,
			ISNULL(R.TotalObtain,'')AS TotalObtain,
			ISNULL(R.ResultStatus,'')AS ResultStatus,
			ISNULL(R.Percentage,0)AS Percentage
		FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId 
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=EM.ClassId
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND SourceTypeId = 2005

		Where ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
			AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND ((R.ExamId = @rExamId) OR (@rExamId = 0))
			AND (U.UserId=@rUserId OR ISNULL(@rUserId,0)=0)
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pStudentExamNameGet]
 
	@rAcademicId bigint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lClassId int = 0
	DECLARE @lBatchId int = 0
	SELECT @lClassId = ClassId, @lBatchId = BatchId FROM sStudent.tAcademic WHERE Id=@rAcademicId
BEGIN 
	SELECT
	E.Id AS ExamId,
	ESGM.Title AS ExamName
	FROM 
	sAssessment.tExamMaster E
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
	WHERE 
	E.ClassId = @lClassId AND E.BatchId = @lBatchId AND ISNULL(E.IsPublishExamSchedule,0) = 1
	ORDER BY 
	--ESGM.OrderIndex comment for MantisID: 0029788
	E.UpdatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pStudentRemarkDelete]
 @rDivisionId int
,@rExamId int
AS
BEGIN
BEGIN TRY

DELETE FROM R
FROM sAssessment.tStudentRemark R
INNER JOIN sStudent.tAcademic A
ON R.AcademicId = A.Id
WHERE R.ExamId = @rExamId AND A.DivisionId = @rDivisionId
		--DELETE	FROM sAssessment.tStudentRemark WHERE ExamId = @rExamId AND AcademicId IN
		--(Select Id From sStudent.tAcademic Where DivisionId =@rDivisionId)		
		SELECT 1 AS RESULT
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sAssessment].[pStudentResultAdd] 
        
        @rResultDetailId bigint,
	    @rRemark nvarchar(max),
	    @rGraceMark decimal,
	    @rKrupaMark decimal,
	    @rResultStatus nvarchar(max),
	    @rResultId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	  
	  
	 BEGIN TRANSACTION	
	
	
 
	Update  sAssessment.tResultDetail 
	set
		GraceMark = @rGraceMark,
		KrupaMark = @rKrupaMark,
		Remark = @rRemark
		
	where Id = @rResultDetailId
		
		Update R
		set 
			ResultStatus = @rResultStatus
		from sAssessment.tResult R 
		Inner join  sAssessment.tResultDetail RD ON R.Id = RD.ResultId
		where R.Id=@rResultId
	 	  
 
	COMMIT TRANSACTION		
	 select 1 AS Result
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pStudentResultGet]
	
	 @rAcademicId bigint=0,
	 @rStudentId bigint=0,
	 @rBatchId int=0,
	 @rExamId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


SELECT

	R.Id AS ResultId,
	RD.Id AS ResultDetailId,
	AD.Id AS AcademicId,
	AD.StudentId,
	AD.BatchId,
	EM.Id AS ExamId,
	ESGM.Title AS ExamName,
	SBM.Code AS Code,
	SBM.Title AS SubjectName,
	RD.Obtain,
	SM.FirstName,
	R.TotalMarks,
	R.TotalObtain,
	R.ResultStatus,
	R.ResultGrade,
	R.RankNumber,
	R.Percentage,
	R.Percentile,
	RD.GraceMark,
	RD.KrupaMark,
	RD.Remark,
	[sAssessment].[fGetHighestDivisionMark](AD.DivisionId ,RD.ExamDetailId)
			 AS HighestDivisionMark,
	[sAssessment].[fGetAverageDivisionMark](AD.DivisionId ,RD.ExamDetailId)
		 AS DivisionAverage,
	ED.Maximum,
	ED.Minimum,
	ESGM.ExamGroupId AS ExamGroupId
	
	from
	sStudent.tStudentMaster SM
	INNER JOIN sStudent.tAcademic AD ON SM.Id = AD.StudentId
	INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id
	INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId
	INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	
	Where
	((AD.Id=@rAcademicId) OR (@rAcademicId=0))
	AND((AD.StudentId = @rStudentId) OR (@rStudentId=0))
	AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
	AND 
	((EM.Id=@rExamId) OR (@rExamId=0))
 order by  ed.DisplayOrder

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pStudentResultRemarkBulkImport]
	@rXml nvarchar(max),
	@rOrgId Int = 0,
	@rBatchId Int = 0,
	@rCategoryId Int = 0,
	@rSubCategoryField nvarchar(1000) = '',
	@rExamSubGroupId Int = 0
	--,@rUserId bigint = 0
AS
BEGIN
	--SET @rXml = REPLACE(@rXml, '&', '&amp;')
	--SET @rXml = REPLACE(@rXml, '<', '&lt;')
	--SET @rXml = REPLACE(@rXml, '>', '&gt;')
	--SET @rXml = REPLACE(@rXml, '''', '&apos;')
	--SET @rXml = REPLACE(@rXml, '"', '&quot;')
	DECLARE @loXML XML,@Sql nvarchar(max)
	SET @loXML = CAST(@rXml AS XML)
	CREATE table #ListofData(tid int identity(1,1),ecode nvarchar(200),AcademicId bigint,ExamId int,sdata nvarchar(2000),UserId bigint,IsExist bit)
	INSERT INTO #ListofData(ecode,AcademicId,ExamId,sdata,UserId,IsExist)
	SELECT
		T.c.value('@Code','nvarchar(200)') AS StudentCode,
		T.c.value('@AcademicId','bigint') AS AcademicId,
		T.c.value('@ExamId','int') AS ExamId,
		T.c.value('@StudentData','nvarchar(2000)') AS StudentData,
		T.c.value('@UserId','bigint') AS UpdatedUserId,
		0 AS IsExist
	FROM @loXML.nodes('/Table/BulkImport')T(c)

	--select * from #ListofData

	if(@rCategoryId=1)
	BEGIN
		UPDATE #ListofData SET IsExist=1
		WHERE AcademicId NOT IN (SELECT SC.AcademicId FROM sAssessment.tStudentRemark SC INNER JOIN #ListofData LD ON LD.AcademicId=SC.AcademicId  where SC.ExamId=LD.ExamId)

		--select * from #ListofData

		set @sql='INSERT INTO sAssessment.tStudentRemark
					(AcademicId,ExamId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.AcademicId,Ld.ExamId,Ld.sdata,LD.UserId,sCommon.fGetDate()
					FROM
						#ListofData LD WHERE LD.IsExist=1 AND Len(LD.sdata) > 0'
		Exec sp_executesql @sql

		set @sql='UPDATE sAssessment.tStudentRemark SET '+@rSubCategoryField+' = LD.sdata,
						UpdatedUserId=LD.UserId,
						UpdatedDateTime=sCommon.fGetDate()
				from sAssessment.tStudentRemark SC
					INNER JOIN #ListofData LD ON SC.AcademicId=LD.AcademicId AND SC.ExamId=LD.ExamId and IsExist=0 AND Len(LD.sdata) > 0'
		Exec sp_executesql @sql

		set @sql='UPDATE sAssessment.tStudentRemark set '+@rSubCategoryField+' = NULL,
						UpdatedUserId=LD.UserId,
						UpdatedDateTime=sCommon.fGetDate()
				from sAssessment.tStudentRemark SC
					INNER JOIN #ListofData LD ON SC.AcademicId=LD.AcademicId AND SC.ExamId=LD.ExamId and IsExist=0 AND Len(LD.sdata) = 0'
		Exec sp_executesql @sql
	END

	if(@rCategoryId=2)
	BEGIN
		UPDATE #ListofData SET IsExist=1 
		WHERE AcademicId NOT IN (SELECT SER.AcademicId FROM sAssessment.tStudentExamRemark SER INNER JOIN #ListofData LD ON LD.AcademicId=SER.AcademicId where SER.ExamId=LD.ExamId AND SER.ExamRemarkSetupId=@rSubCategoryField)

		--select * from #ListofData

		INSERT INTO sAssessment.tStudentExamRemark
			(AcademicId,ExamRemarkSetupId,ExamId,Remark,CreatedUserId,CreatedDateTime)
		SELECT
			LD.AcademicId,@rSubCategoryField,Ld.ExamId,Ld.sdata,LD.UserId,sCommon.fGetDate()
		FROM
			#ListofData LD WHERE LD.IsExist=1 AND Len(LD.sdata) > 0

		UPDATE sAssessment.tStudentExamRemark set Remark= LD.sdata,
			UpdatedUserId=LD.UserId,
			UpdatedDateTime=sCommon.fGetDate()
		FROM sAssessment.tStudentExamRemark SER
			INNER JOIN #ListofData LD ON SER.AcademicId=LD.AcademicId AND SER.ExamRemarkSetupId=@rSubCategoryField AND SER.ExamId=LD.ExamId and IsExist=0 AND Len(LD.sdata) > 0

		Delete SER FROM sAssessment.tStudentExamRemark SER
			INNER JOIN #ListofData LD ON SER.AcademicId=LD.AcademicId
			AND SER.ExamId=LD.ExamId AND SER.ExamRemarkSetupId=@rSubCategoryField and  IsExist=0 AND Len(LD.sdata) = 0
	END

	DROP TABLE #ListofData
	SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pStudentResultRemarkGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,
	 @rIsBlank bit,
	 @rStatusId int,
	 @rOrderBy int,
	 @rExamId int,
	 @rDepartmentId int =0	
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1),@lOrderBy nvarchar(10)
		if(@rOrderBy=1)
		BEGIN
		  SET @lOrderBy='RollNo';
		END
		ELSE if(@rOrderBy=2)
		BEGIN 
		 SET @lOrderBy='Code';
		END
		ELSE if(@rOrderBy=3)
		BEGIN 
		 SET @lOrderBy='FirstName';
		END
		ELSE if(@rOrderBy=4)
		BEGIN 
		 SET @lOrderBy='MiddleName';
		END
		ELSE if(@rOrderBy=5)
		BEGIN 
		 SET @lOrderBy='LastName';
		END

		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		--IF(@rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup' 
		--	OR @rSubCategory = 'CastCategory' OR @rSubCategory = 'TransportMode' OR @rSubCategory = 'House'
		--	OR @rSubCategory = 'MotherTongue' OR @rSubCategory = 'Nationality' OR @rSubCategory = 'AdmissionStandard' OR  @rSubCategory = 'AdmissionCategory'
		--	)
		--BEGIN
		--	SET @rSubCategory = @rSubCategory + 'Id'
		--END
		 Declare @Sql nvarchar(max)
		 if(@rCategoryId=1) 
		 BEGIN
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- Result
						'Select SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SR.'+@rSubCategory+','''') 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SR.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SR.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SR.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SR.'+@rSubCategory+',''0'') 
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
							LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=SA.AcademicId AND (SR.ExamId='+CAST(@rExamId AS nvarchar(15))+')
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+' AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ ' OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ ' OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND (CM.DepartmentId =' +CAST (@rDepartmentId as nvarchar(15)) + ' OR ' + CAST (@rDepartmentId AS Nvarchar(15))+'=0)
							
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SR.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SR.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SR.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SR.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
								OR ('+@lDataTypeId+'=5 AND ISNULL(SR.'+@rSubCategory+',''0'')=''0'')'+--Added by dhananjay for mantis id - 35452
								+'
							)
							ORDER BY SA.' + @lOrderBy
					END
							
					
		print @Sql    
		
	   
	  EXECUTE  sp_executesql @Sql
		END	
			ELSE IF(@rCategoryId=2)	
			BEGIN
			Declare @lExamRemarkSetupId int
			Select @lExamRemarkSetupId = Id from sAssessment.tExamRemarkSetup Where Title = @rSubCategory
			Select 
					SA.AcademicId,
					SA.Code,
					SA.Name,
					SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
					SA.RollNo,
					SA.Number,
					ISNULL(SR.Remark,'') AS SubCategory
			FROM 
					sStudent.vStudentAcademic SA
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
					LEFT JOIN sAssessment.tStudentExamRemark SR ON SR.AcademicId=SA.AcademicId AND (SR.ExamId=@rExamId) AND SR.ExamRemarkSetupId = @lExamRemarkSetupId
					Where SA.OrgId=@rOrgId AND (SA.ClassId=@rClassId OR @rClassId=0)
					AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (SA.StatusId=@rStatusId OR @rStatusId=0)
					AND (SA.BatchId=@rBatchId)
					AND (CM.DepartmentId =@rDepartmentId OR @rDepartmentId=0)
			ORDER BY case When @rOrderBy=1 then  SA.RollNo 
					When @rOrderBy=2 then  SA.Code  
					When @rOrderBy=3 then  SA.FirstName  
					When @rOrderBy=4 then  SA.MiddleName
					else SA.LastName END
			END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pStudentResultRemarkModify]	 
	@rCategoryId int,
	@rXML nvarchar(max),
	@rSubCategoryField nvarchar(1000),
	@rOrgId int = 0,
	@rExamRemarkSetupId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--SET @rXML=REPLACE(@rXML,'&','AND')
SET @rXML=REPLACE(@rXML,'&','&amp;')

--SET @rXML = [sCommon].[fXMLTagsReplaceReverse](@rXML)


DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT

 
--BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	 
		
	CREATE TABLE #ListofData(Id bigint,AcademicId bigint,ExamId int, SubCategory nvarchar(2000),UpdatedUserId bigint,IsExist bit);
	insert into #ListofData
		select 0,E.AcademicId,E.ExamId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT AcademicId,ExamId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						AcademicId BIGINT, 
						ExamId int,
						SubCategory nvarchar(2000),
						UpdatedUserId bigint)	
						)E 	
	IF(@rCategoryId= 1)
		BEGIN
		
		UPDATE #ListofData SET IsExist=1 WHERE AcademicId NOT IN(SELECT SC.AcademicId FROM sAssessment.tStudentRemark  SC INNER JOIN #ListofData LD ON LD.AcademicId=SC.AcademicId  where SC.ExamId=LD.ExamId ) 
		
		set @sql='INSERT INTO sAssessment.tStudentRemark
					(AcademicId,ExamId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.AcademicId,Ld.ExamId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						#ListofData LD WHERE LD.IsExist=1 AND Len(LD.SubCategory) > 0'
		Exec sp_executesql @sql
		set @sql='UPDATE sAssessment.tStudentRemark set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAssessment.tStudentRemark SC 
					INNER JOIN #ListofData LD ON SC.AcademicId=LD.AcademicId AND SC.ExamId=LD.ExamId and IsExist=0 AND Len(LD.SubCategory) > 0'
		
		Exec sp_executesql @sql
		
			set @sql='UPDATE sAssessment.tStudentRemark set '+@rSubCategoryField+' = NULL,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAssessment.tStudentRemark SC 
					INNER JOIN #ListofData LD ON SC.AcademicId=LD.AcademicId 
					AND SC.ExamId=LD.ExamId and IsExist=0 AND Len(LD.SubCategory) = 0'
 
		Exec sp_executesql @sql	
		
		
	    END
	else if(@rCategoryId= 2)
	BEGIN
		UPDATE #ListofData SET IsExist=1 WHERE AcademicId NOT IN(SELECT SER.AcademicId FROM sAssessment.tStudentExamRemark  SER INNER JOIN #ListofData LD ON LD.AcademicId=SER.AcademicId where SER.ExamId=LD.ExamId AND SER.ExamRemarkSetupId=@rExamRemarkSetupId) 
			
			INSERT INTO sAssessment.tStudentExamRemark 
				(AcademicId,ExamRemarkSetupId,ExamId,Remark,CreatedUserId,CreatedDateTime)
				SELECT
					LD.AcademicId,@rExamRemarkSetupId,Ld.ExamId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
				FROM
					#ListofData LD WHERE LD.IsExist=1 AND Len(LD.SubCategory) > 0
		UPDATE sAssessment.tStudentExamRemark set Remark= LD.SubCategory,
				UpdatedUserId=LD.UpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()  
				from sAssessment.tStudentExamRemark SER 
				INNER JOIN #ListofData LD ON SER.AcademicId=LD.AcademicId AND SER.ExamRemarkSetupId=@rExamRemarkSetupId AND   SER.ExamId=LD.ExamId and IsExist=0 AND Len(LD.SubCategory) > 0

		Delete SER
					  
					from sAssessment.tStudentExamRemark SER 
					INNER JOIN #ListofData LD ON SER.AcademicId=LD.AcademicId 
					AND SER.ExamId=LD.ExamId AND SER.ExamRemarkSetupId=@rExamRemarkSetupId and  IsExist=0 AND Len(LD.SubCategory) = 0

	END
 Drop Table #ListofData
			 SELECT 1 AS StatusCode
END 
	   --COMMIT TRANSACTION

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pStudentResultViewGet]
	
	@rAcademicId bigint=0,
	@rBatchId int=0,
	@rExamId int=0,
	@rPayElementTypeId smallint= 0
 
AS
BEGIN
	
	DECLARE @lResultGrid NVARCHAR(max)=''
	SELECT @lResultGrid = @lResultGrid + '<tr>
	<td align="left" scope="col">' + isnull(SBM.Title,'') + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(ED.Maximum,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(ED.Minimum,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(RD.Obtain,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(RD.GraceMark,0)) + '</td>
	<td align="left" scope="col">' + isnull(RD.Remark,'') + '</td>
	<tr>'
    	
   FROM sStudent.tAcademic AD
	INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id
	INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId
	INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	Where
	((AD.Id=@rAcademicId) OR (@rAcademicId=0))
	AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
   AND ((EM.Id=@rExamId) OR (@rExamId=0))
  
select isnull(@lResultGrid,'') as ResultGrid
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pStudentWiseExamDetailGet]
	
	@rAcademicId bigint=0,
	@rBatchId int=0,
	@rExamId int=0

AS
BEGIN
	
	SELECT 
		ISNULL(SBM.Title,'') AS SubjectName,
		ISNULL(ED.Maximum,0)AS Maximum,
		ISNULL(ED.Minimum,0)AS Minimum,
		ISNULL(RD.Obtain,0)AS Obtain,
		ISNULL(RD.GraceMark,0) AS GraceMark,
		ISNULL(RD.Remark,'') AS Remark , 
		ISNULL(R.TotalMarks,0)AS TotalMarks,
		ISNULL(R.TotalObtain,'')AS TotalObtain,
		ISNULL(R.Percentage,0)AS Percentage
    FROM sStudent.tAcademic AD 
    INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId 
    INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id 
    INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id 
    INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId 
    INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId 
    INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId 
    INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
    Where 
	((AD.Id = @rAcademicId) OR (@rAcademicId = 0)) 
     AND ((AD.BatchId = @rBatchId) OR (@rBatchId = 0))
     AND ((EM.Id = @rExamId) OR (@rExamId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pStudentwiseOptionalSubjectAdd]
  
	@rDivisionId [int],	
	@rMapping [nvarchar](max),
	@rSubjectId [int],
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT



EXEC sp_xml_preparedocument @loDoc OUTPUT, @rMapping
BEGIN
		

if @rSubjectId = 0 
begin
	DELETE FROM sAssessment.tOptionalSubject WHERE AcademicId in (select Id from sStudent.tAcademic where DivisionId = @rDivisionId AND BatchId=@rBatchId)
end
else
begin
	DELETE FROM sAssessment.tOptionalSubject WHERE AcademicId in (select Id from sStudent.tAcademic where DivisionId = @rDivisionId AND BatchId=@rBatchId) and ClassSubjectId=@rSubjectId
end

INSERT INTO  sAssessment.tOptionalSubject (
							AcademicId, 
							ClassSubjectId 
							)		
			SELECT AcademicId, ClassSubjectId
			FROM
			OPENXML (@loDoc, '/Items/Item', 2)
			WITH (
					AcademicId bigint,			         
			        ClassSubjectId int) A
 
			SELECT 1 As Result	
END
EXEC sp_xml_removedocument @loDoc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR 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)) 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))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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pStudentwiseStudentRemarkAdd]
  
	@rDivisionId [int],	
	@rMapping [nvarchar](max),
	@rExamId [int]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT



EXEC sp_xml_preparedocument @loDoc OUTPUT, @rMapping
BEGIN
		

DELETE FROM sAssessment.tStudentRemark WHERE AcademicId in (select Id from sStudent.tAcademic where DivisionId = @rDivisionId) and ExamId=@rExamId

INSERT INTO  sAssessment.tStudentRemark (
							AcademicId, 
							ExamId,
							ResultRemark1, 
							ResultRemark2,
							UpdatedUSerId,
							UpdatedDateTime
							)		
			SELECT AcademicId, ExamId,ResultRemark1,ResultRemark2,UpdatedUserId,sCommon.fGetDate() as UpdatedDateTime
			FROM
			OPENXML (@loDoc, '/Items/Item', 2)
			WITH (
					AcademicId bigint,			         
			        ExamId int,
			        ResultRemark1 nvarchar(200),
			        ResultRemark2 nvarchar(200),
			        UpdatedUserId bigint) A
 
			SELECT 1 As Result	
END
EXEC sp_xml_removedocument @loDoc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pStudentwiseStudentRemarkListGet]
                  
          @rDivisionId bigint,
          @rExamId bigint ,
          @rBatchId int          
      
AS
SET NOCOUNT ON

BEGIN

SELECT 
SA.AcademicId,
SA.Name AS StudentName,
SA.Code,
SA.RollNo,
ISNULL(SR.ResultRemark1,'') AS ResultRemark1,
ISNULL(SR.ResultRemark2,'') AS ResultRemark2
FROM  sStudent.vStudentAcademic SA
	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicID=SA.AcademicId 	 AND SR.ExamId=@rExamId			
WHERE DivisionId=@rDivisionId AND StatusId=1 AND SA.BatchId=@rBatchId
ORDER BY SA.RollNo,SA.AcademicId
	   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubExamMaxMarkListGet]
	 @rId nvarchar(200)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	DEclare @rQuery nvarchar(MAX)				 
	SET @rQuery = 'SELECT 
	SUM(ISNULL(ED.Maximum,0)) as Maximum,
	ISNULL(ED.ClassSubjectId,0) AS ClassSubjectId
  FROM 	   sAssessment.tExamDetail ED 
  WHERE   ED.ExamId IN (' + @rId + ')
  Group BY ED.ClassSubjectId'
  
  exec (@rQuery)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityCheckDelete]
	 @rSubjectAcId int,
	 @rOrgId int,
	 @rClassId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
	if exists(Select Id from sAssessment.tCCESubjectSubActivityIndicatorMaster where  CCESubjectSubActivityId in (
			 Select SAM.Id from sAssessment.tCCESubjectSubActivityMaster SAM
			 INNER JOIN sAssessment.tCCESubjectActivityMaster CA ON SAM.SubjectActivityId = CA.ID
			 INNER JOIN sSetup.tClassSubject SB on SB.Id=CA.ClassSubjectId
			 where  SAM.OrgId=@rOrgId AND SB.ClassId=@rClassId  AND SAM.SubjectActivityId=@rSubjectAcId))
	Begin
		select 1 as result
	END
	
	else if exists (Select 1 from sAssessment.tCCESubjectSubActivityExamScore where SubjectSubActivityId in (
					Select SAM.Id from sAssessment.tCCESubjectSubActivityMaster SAM 
					INNER JOIN sAssessment.tCCESubjectActivityMaster CA ON SAM.SubjectActivityId = CA.ID
					INNER JOIN sSetup.tClassSubject SB on SB.Id=CA.ClassSubjectId
					where SAM.OrgId=@rOrgId AND SB.classid=@rClassid AND SAM.SubjectActivityId =@rSubjectAcId))
	BEGIN
		Select 101 As Result
	END
	else
	BEGIN
		Delete from sAssessment.tCCESubjectActivityMaster Where Id=@rSubjectAcId And OrgId=@rOrgId
		Delete from sAssessment.tCCESubjectSubActivityMaster where SubjectActivityId=@rSubjectAcId And OrgId=@rOrgId
		select 11 As Result
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityCSConvertExamGradeIndicator]
	 
	    @rAcademicId bigint,
        @rExamId int,
	    @rOldIndicator nvarchar(50),
	    @rNewIndicator nvarchar(50),
	    @rSubjectSubActivityId int,
	    @rSubjectActivityId int
		    
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			
		 UPDATE  CCESAES 
		      SET CCESAES.GradeIndicator = @rNewIndicator
	     FROM 
			  sAssessment.tCCESubjectSubActivityExamScore CCESAES 
		      INNER JOIN sAssessment.tCCESubjectSubActivityMaster CCESSAM ON CCESSAM.Id = CCESAES.SubjectSubActivityId 
	     WHERE 
	          ((CCESSAM.SubjectActivityId=@rSubjectActivityId) OR (@rSubjectActivityId=0)) 
			  AND CCESAES.GradeIndicator =@rOldIndicator
			  AND CCESAES.ExamId = @rExamId
			  AND ((CCESAES.AcademicId =@rAcademicId) OR (@rAcademicId=0))
			  AND ((CCESSAM.Id =@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))
	     
	     SELECT 1 AS Result
	 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityCSConvertExamGradeScore]
	 
            @rAcademicId bigint,
            @rExamId int,
		    @rOldGrade nvarchar(10),
		    @rNewGrade nvarchar(10),
		    @rSubjectSubActivityId int,
		    @rSubjectActivityId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	     UPDATE  CCESAES 
		      SET CCESAES.Grade = @rNewGrade
	     FROM 
			  sAssessment.tCCESubjectSubActivityExamScore CCESAES 
		      INNER JOIN sAssessment.tCCESubjectSubActivityMaster CCESSAM ON CCESSAM.Id = CCESAES.SubjectSubActivityId 
	     WHERE 
	          ((CCESSAM.SubjectActivityId=@rSubjectActivityId) OR (@rSubjectActivityId=0)) 
			  AND CCESAES.Grade =@rOldGrade
			  AND CCESAES.ExamId =@rExamId
			  AND ((CCESAES.AcademicId =@rAcademicId) OR (@rAcademicId=0))
			  AND ((CCESSAM.Id =@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))
	     
	     SELECT 1 AS Result
	 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityExamGradeScoreDelete]
	 
	 @rOrgId int=0,
	 @rClassId int,
	 @rDivisionId int,
	 @rAcademicId bigint,	 
	 @rExamId int,
	 @rBatchId int,
	 @rSubjectActivityId int,
	 @rSubjectSubActivityId int,
	 @rClassSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
		DELETE  CCESAES 
		FROM    sAssessment.tCCESubjectSubActivityExamScore CCESAES			
				INNER JOIN sStudent.tAcademic A ON 	CCESAES.AcademicId = A.Id
				INNER JOIN sAssessment.tCCESubjectSubActivityMaster CCESSAM ON CCESSAM.Id = CCESAES.SubjectSubActivityId
		WHERE   CCESSAM.OrgId = @rOrgId
				AND A.DivisionId = @rDivisionId
				AND A.ClassId = @rClassId
				AND ((CCESAES.AcademicId=@rAcademicId) OR(@rAcademicId=0))
				AND CCESAES.ExamId = @rExamId 
				AND ((CCESAES.SubjectSubActivityId=@rSubjectSubActivityId) OR (@rSubjectSubActivityId=0))
				AND A.BatchId=@rBatchId
				AND ((CCESSAM.SubjectActivityId=@rSubjectActivityId) OR (@rSubjectActivityId=0))
				
				
		SELECT 1 AS RESULT
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityExamIndicatorAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	 BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT

			UPDATE AI SET AI.IndicatorIds = Replace(Term1Indicator,',','.') FROM sAssessment.tCCESubjectSubActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectSubActivityId int,--CCECSId int,
							ExamId int,
							Term1Indicator NVARCHAR(20)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
			AND A.SubjectSubActivityId = AI.SubjectSubActivityId--AND A.CCECSId = AI.CCECSId 
			INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id = @rORGId	
			  			
		
	
	BEGIN	
		INSERT INTO sAssessment.tCCESubjectSubActivityExamScore
			(ExamId,AcademicId,SubjectSubActivityId,IndicatorIds)
			
			SELECT	ExamId,AcademicId,AM.Id,Replace(Term1Indicator,',','.')
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId Bigint,					
					Term1Indicator nvarchar(20),
					SubjectSubActivityId int--CCECSId int
				  ) A 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster AM ON AM.Id = A.SubjectSubActivityId 			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AM.OrgId AND OM.Id = @rORGId
			AND A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCESubjectSubActivityExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND SubjectSubActivityId=AM.Id)
	     
	END
	
    -- Updated by Kp
	 UPDATE A SET A.DescriptiveIndicator = 
 					stuff((select ',' + B.Title from sAssessment.tCCESubjectSubActivityIndicatorMaster B 
				WHERE A.SubjectSubActivityId=B.CCESubjectSubActivityId 
						and ','+ (replace(IndicatorIds,'.',',') )+',' like '%,'+CAST(Number as varchar(10))+',%'				
				for xml path('')),1,1,'') 
         From sAssessment.tCCESubjectSubActivityExamScore A    
         INNER JOIN      			
			OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId Bigint,					
					Term1Indicator nvarchar(20),
					SubjectSubActivityId int
				  )B1
				  ON A.ExamId=B1.ExamId AND A.AcademicId = B1.AcademicId AND B1.SubjectSubActivityId = A.SubjectSubActivityId 
	
	   SELECT 1 AS Result
	END		
	 END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityEXamIndicatorDelete]
 @rDivisionId int
,@rExamId int
,@rSubjectSubActivityId int

AS
BEGIN

 
DELETE	S 
FROM sAssessment.tCCESubjectSubActivityExamScore S
INNER JOIN sStudent.tAcademic A 
ON s.AcademicId = A.Id
WHERE S.ExamId = @rExamId 
AND (S.SubjectSubActivityId=@rSubjectSubActivityId OR @rSubjectSubActivityId =0) 
AND A.DivisionId = @rDivisionId


		--DELETE	FROM sAssessment.tCCECSExamScore WHERE ExamId = @rExamId 
		--AND (CCECSId=@rCCECSId OR @rCCECSId =0) 
		--AND AcademicId IN
		--(Select Id From sStudent.tAcademic Where DivisionId =@rDivisionId)		
		SELECT 1 AS RESULT
 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityExamIndicatorGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0 --@rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	DECLARE @cols AS NVARCHAR(MAX),
	
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)


select @cols = STUFF((SELECT  ',' + QUOTENAME( Title) FROM sAssessment.tCCESubjectSubActivityMaster 
					 Where  OrgId=@rOrgId AND  SubjectActivityId=@rSubjectActivityId AND (( Id=@rSubActivityId)OR (@rSubActivityId=0))

					-- FROM sAssessment.tCCESubjectActivityMaster CGM
					--INNER JOIN sAssessment.tCCESubjectSubActivityMaster CM ON CM.SubjectActivityId=CGM.Id
					
					--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=CGM.ClassSubjectId AND CS.ClassSubjectId=@rClassId
					--INNER JOIN sSetup.tClassMaster C ON C.Id=CS.ClassId 
					--	AND CGM.OrgId=@rOrgId AND CGM.Id=@rSubjectActivityId AND ((CM.Id=@rSubActivityId)OR (@rSubActivityId=0))
				  
					 
					Order by  OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code AS Number,SA.Name,SSA.Title,	 ISNULL(SEC.IndicatorIds,'''') AS Term1Indicator
	FROM  
	 sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id AND SA.StatusId=1
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= ' + Convert(nvarchar,@rExamId)+ ' AND (SEC.SubjectSubActivityId = ' + convert(nvarchar,@rSubActivityId) + ' OR ' + convert(nvarchar,@rSubActivityId) + ' = 0 )
	 LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicID and o.ClassSubjectId=CS.ClassSubjectId  
			 
				AND SEC.ExamId='+cONVERT(NVARCHAR,@rExamId )+'
	WHERE  SSA.OrgId= '+ CONVERT(nvarchar,@rOrgId) + ' 
	 AND SAM.ClassSubjectId= ' + CONVERT(nvarchar,@rClassId) + ' 
	 AND SSA.SubjectActivityId= '+ CONVERT(nvarchar,@rSubjectActivityId) + ' 
	 AND SA.DivisionId= ' + CONVERT(nvarchar,@rDivisionID) + '
	 And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	  AND ((CS.IsOptional = 1 AND  isnull(o.AcademicId,0)<>0) OR (CS.IsOptional = 0))
	 ) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

EXECUTE(@query)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityGradeScoreDelete]
	 
	 @rClassId int,
	 @rDivisionId int,
	 @rAcademicId bigint,	 
	 @rExamId int,
	 @rBatchId int,
	 @rCCEGroupId int,
	 @rCCEId int,
	 @rFilter int=0,
	 @rClassSubjectId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	 
			if @rFilter=0 
			BEGIN
				DELETE CC FROM  sAssessment.tCCESubjectSubActivityExamScore CC				
					INNER JOIN sStudent.tAcademic A ON 	CC.AcademicId = A.Id
					LEFT JOIN sAssessment.tCCESubjectSubActivityMaster CGM ON CGM.Id = CC.SubjectSubActivityId
					LEFt JOIN sAssessment.tCCESubjectActivityMaster CM ON CM.Id=CGM.SubjectActivityId
					WHERE A.DivisionId = @rDivisionId
						AND A.ClassId = @rClassId
						AND ((CC.AcademicId=@rAcademicId) OR(@rAcademicId=0))
						AND CC.ExamId = @rExamId 
						AND ((CC.SubjectSubActivityId=@rCCEId) OR (@rCCEId=0))
						AND A.BatchId=@rBatchId
						AND ((CGM.SubjectActivityId=@rCCEGroupId) OR (@rCCEGroupId=0))
						AND CM.ClassSubjectId=@rClassSubjectId
			END
			else
			BEGIN
			if @rFilter =1 
			BEGIN
				Update CC Set Grade='' FROM  sAssessment.tCCESubjectSubActivityExamScore CC 
					INNER JOIN sStudent.tAcademic A ON 	CC.AcademicId = A.Id
					LEFT JOIN sAssessment.tCCESubjectSubActivityMaster CGM ON CGM.Id = CC.SubjectSubActivityId
					LEFt JOIN sAssessment.tCCESubjectActivityMaster CM ON CM.Id=CGM.SubjectActivityId
					 Where 
					 A.DivisionId = @rDivisionId
						AND A.ClassId = @rClassId
						AND ((CC.AcademicId=@rAcademicId) OR(@rAcademicId=0))
						AND CC.ExamId = @rExamId 
						AND ((CC.SubjectSubActivityId=@rCCEId) OR (@rCCEId=0))
						AND A.BatchId=@rBatchId
						AND ((CGM.SubjectActivityId=@rCCEGroupId) OR (@rCCEGroupId=0))
						AND CM.ClassSubjectId=@rClassSubjectId
					END
			else if @rfilter=2
			BEGIN
				Update CC Set IndicatorIds='' FROM  sAssessment.tCCESubjectSubActivityExamScore CC 
					INNER JOIN sStudent.tAcademic A ON 	CC.AcademicId = A.Id
					LEFT JOIN sAssessment.tCCESubjectSubActivityMaster CGM ON CGM.Id = CC.SubjectSubActivityId
					LEFt JOIN sAssessment.tCCESubjectActivityMaster CM ON CM.Id=CGM.SubjectActivityId
					 Where 
					 A.DivisionId = @rDivisionId
						AND A.ClassId = @rClassId
						AND ((CC.AcademicId=@rAcademicId) OR(@rAcademicId=0))
						AND CC.ExamId = @rExamId 
						AND ((CC.SubjectSubActivityId=@rCCEId) OR (@rCCEId=0))
						AND A.BatchId=@rBatchId
						AND ((CGM.SubjectActivityId=@rCCEGroupId) OR (@rCCEGroupId=0))
						AND CM.ClassSubjectId=@rClassSubjectId
						
			END
			else if @rFilter=3
			BEGIN
					Update CC Set Marks=NULL FROM  sAssessment.tCCESubjectSubActivityExamScore CC 
					INNER JOIN sStudent.tAcademic A ON 	CC.AcademicId = A.Id
					LEFT JOIN sAssessment.tCCESubjectSubActivityMaster CGM ON CGM.Id = CC.SubjectSubActivityId
					LEFt JOIN sAssessment.tCCESubjectActivityMaster CM ON CM.Id=CGM.SubjectActivityId
					 Where 
					 A.DivisionId = @rDivisionId
						AND A.ClassId = @rClassId
						AND ((CC.AcademicId=@rAcademicId) OR(@rAcademicId=0))
						AND CC.ExamId = @rExamId 
						AND ((CC.SubjectSubActivityId=@rCCEId) OR (@rCCEId=0))
						AND A.BatchId=@rBatchId
						AND ((CGM.SubjectActivityId=@rCCEGroupId) OR (@rCCEGroupId=0))
						AND CM.ClassSubjectId=@rClassSubjectId
			END
			 END
				  
			SELECT 1 AS RESULT
		 
 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityIndicatorGroupDelete]
@rId bigint
AS
BEGIN
 
  	 
		DELETE	FROM sAssessment.tCCESubjectSubActivityIndicatorMaster WHERE CCESubjectSubActivityId=@rId		
		SELECT 1 AS RESULT
	 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityIndicatorMasterDelete]
@rId	 bigint
AS
BEGIN
BEGIN TRY
	--IF NOT EXISTS (SELECT Id FROM sGSEB.tClassActivity WHERE ActivityId = @rActivityId)	
	  BEGIN
		DELETE	FROM sAssessment.tCCESubjectSubActivityIndicatorMaster WHERE Id=@rId	
		SELECT 1 AS RESULT
	   END
	--ELSE
	--	BEGIN
	--		SELECT -101 AS RESULT
	--	END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityMarkEntryBulkAdd]
	 	
	@rStrXml [nvarchar](max),
		@rOrgId int	
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN 
	 BEGIN	
		UPDATE AI SET AI.Marks = Mark FROM sAssessment.tCCESubjectSubActivityExamScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
				WITH ( 				
							AcademicId Bigint,
							SubjectSubActivityId int,--CCECSId int,
							ExamId int,
							Mark decimal(10,2)			
					  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
			AND A.SubjectSubActivityId = AI.SubjectSubActivityId--AND A.CCECSId = AI.CCECSId 
			INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id = @rORGId	
			  			
		
	
	BEGIN	
		INSERT INTO sAssessment.tCCESubjectSubActivityExamScore
			(ExamId,AcademicId,SubjectSubActivityId,Marks)
			
			SELECT	ExamId,AcademicId,AM.Id,Mark
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId Bigint,					
					
					SubjectSubActivityId int,
					Mark decimal(10,2)--CCECSId int
				  ) A 	
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster AM ON AM.Id = A.SubjectSubActivityId 			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AM.OrgId AND OM.Id = @rORGId
			AND A.AcademicId NOT IN (Select AcademicId From sAssessment.tCCESubjectSubActivityExamScore Where AcademicId =A.AcademicId AND A.ExamId = ExamId AND SubjectSubActivityId=AM.Id)
	     SELECT 1 AS Result
	END
	
	 
	 
    END	
	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityMarkEntryGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rBatchId int,
	 @rSubjectActivityId int,
	 @rSubjectSubActivityId int,
	 	  @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
--select @cols = STUFF((SELECT  ',' + QUOTENAME(Ed.Id) 
--					  From sAssessment.tExamMaster E
--					  INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
--					  AND ClassId = @rClassId AND E.Id =  @rExamId 
--            FOR XML PATH(''), TYPE
--            ).value('.', 'NVARCHAR(MAX)') 
--        ,1,1,'')


select @cols = STUFF((SELECT  ',' + QUOTENAME(CM.Title) FROM sAssessment.tCCESubjectActivityMaster CGM
					INNER JOIN sAssessment.tCCESubjectSubActivityMaster CM ON CM.SubjectActivityId=CGM.Id					
					INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=CGM.ClassSubjectId AND CS.ClassSubjectId=@rClassId
					INNER JOIN sSetup.tClassMaster C ON C.Id=CS.ClassId 
					AND CGM.OrgId=@rOrgId AND CGM.Id=@rSubjectActivityId AND ((CM.Id=@rSubjectSubActivityId)OR (@rSubjectSubActivityId=0))
				   
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
        
set @query = 'SELECT AcademicId ,RollNo,Number,Name, ' + @cols + '
FROM
(

 sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= ' + Convert(nvarchar,@rExamId)+ '
	 
	WHERE  SSA.OrgId= '+ CONVERT(nvarchar,@rOrgId) + ' 
	 AND SSA.SubjectActivityId= '+ CONVERT(nvarchar,@rSubjectActivityId) + ' 
	 AND SAM.ClassSubjectId= ' + CONVERT(nvarchar,@rClassId) + '
	  
	 AND SA.DivisionId= ' + CONVERT(nvarchar,@rDivisionID) + '
	 And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	 ) MAIN
	PIVOT
	(
		max(Mark)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
 
  
  execute(@query)
		
END




--	Select SA.AcademicId,SA.RollNo,SA.Number,SA.Name,SSA.Title,	 ISNULL(SEC.Marks,''0'') AS Mark
--FROM sStudent.vStudentAcademic A 
--INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
--INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
--INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
--LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
--INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
--LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
--WHERE A.StatusId =1 AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) + ' AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId = ' + convert(nvarchar(15),@rExamId) + '
--) MAIN
--PIVOT
--(
--	MAX(Obtain)
--FOR ExamDetailId IN (' + @cols + ')
--)pvt Order by RollNo,Number,Academicid'
--print (@query)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityMarkGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0, --@rCCECSId int=0,
	  @rSubjectId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	DECLARE @cols AS NVARCHAR(MAX),
	
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)


select @cols = STUFF((SELECT  ',' + QUOTENAME( Title) FROM    sAssessment.tCCESubjectSubActivityMaster 
					 Where  OrgId=@rOrgId AND  SubjectActivityId=@rSubjectActivityId AND (( Id=@rSubActivityId)OR (@rSubActivityId=0))
					
					--sAssessment.tCCESubjectActivityMaster CGM
					--INNER JOIN sAssessment.tCCESubjectSubActivityMaster CM ON CM.SubjectActivityId=CGM.Id					
					--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=CGM.ClassSubjectId AND CS.ClassSubjectId=@rClassId
					--INNER JOIN sSetup.tClassMaster C ON C.Id=CS.ClassId 
					--AND CGM.OrgId=@rOrgId AND CGM.Id=@rSubjectActivityId AND ((CM.Id=@rSubActivityId)OR (@rSubActivityId=0))
				  
					--INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id 
					--AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId 
					--AND CGM.Id=@rCCECSGroupId AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by  OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
        --print @cols
       
	SET @query = 'Select AcademicId,RollNo,Code AS Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code,SA.Name,SSA.Title,	 ISNULL(SEC.Marks,''0'') AS Mark
	FROM  
	 sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= ' + Convert(nvarchar,@rExamId)+ '
	 LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=CS.ClassSubjectId
	WHERE  SSA.OrgId= '+ CONVERT(nvarchar,@rOrgId) + ' 
	 AND SSA.SubjectActivityId= '+ CONVERT(nvarchar,@rSubjectActivityId) + ' 
	 AND SAM.ClassSubjectId= ' + CONVERT(nvarchar,@rClassId) + '
	  
	 AND SA.DivisionId= ' + CONVERT(nvarchar,@rDivisionID) + '
	 And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '
	 ANd CS.ClassSubjectId = '+ convert(nvarchar,@rSubjectId) + '
	  AND ((CS.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (CS.IsOptional = 0))
	  AND SA.StatusId=1
	 ) MAIN
	PIVOT
	(
		max(Mark)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

EXECUTE(@query)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityScoreBulkAdd]
	 	
	@rStrXml [nvarchar](max),
		@rOrgId int	
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN 
	 BEGIN	
		UPDATE AI 
		SET AI.Grade = Term1Grade,
		AI.GradeIndicator = GradeTitle   
		FROM sAssessment.tCCESubjectSubActivityExamScore AI
		INNER JOIN OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
						AcademicId bigint,
						SubjectSubActivityId int,
						ExamId int,
						Term1Grade nvarchar(20),
						GradeTitle nvarchar(50)
									
				  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
		AND A.SubjectSubActivityId = AI.SubjectSubActivityId 
		
		INSERT INTO  sAssessment.tCCESubjectSubActivityExamScore
			(ExamId,AcademicId,SubjectSubActivityId,Grade,GradeIndicator)
			
			SELECT	
			A.ExamId,A.AcademicId,A.SubjectSubActivityId,Term1Grade,GradeTitle
         			
			FROM OPENXML (@loDoc, '/Table/SubjectActivityScoreBulk', 1)
			WITH ( 				
					ExamId int,
					AcademicId bigint,					
					Term1Grade nvarchar(20),
					GradeTitle nvarchar(50),
					SubjectSubActivityId int
				  ) A  LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AI ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId  AND A.SubjectSubActivityId = AI.SubjectSubActivityId 
			       WHERE (AI.AcademicId IS NULL AND AI.ExamId IS NULL AND AI.SubjectSubActivityId IS NULL)
	
 	 SELECT 1 AS Result
	END		
	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityScoreBulkDefaultGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int=0,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0 --@rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	DECLARE @cols AS NVARCHAR(MAX),
	
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)


select @cols = STUFF((SELECT  ',' + QUOTENAME(Title) FROM sAssessment.tCCESubjectSubActivityMaster 
					 Where  OrgId=@rOrgId AND  SubjectActivityId=@rSubjectActivityId AND (( Id=@rSubActivityId)OR (@rSubActivityId=0))
					
				  
					--INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id 
					--AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId 
					--AND CGM.Id=@rCCECSGroupId AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by  OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Code AS Number,Name,  ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code,SA.Name,SSA.Title, ISNULL(SEC.Grade,'''') AS Term1Indicator
	FROM  
	 sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON   SEC.AcademicId=SA.AcademicId AND SEC.ExamId= ' + Convert(nvarchar,@rExamId)+ ' 
	 LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicID and o.ClassSubjectId=CS.ClassSubjectId  
				AND SEC.ExamId='+cONVERT(NVARCHAR,@rExamId )+'
	WHERE  SSA.OrgId= '+ CONVERT(nvarchar,@rOrgId) + ' 
	 AND SAM.ClassSubjectId= ' + CONVERT(nvarchar,@rClassId) + ' 
	  AND SSA.SubjectActivityId= '+ CONVERT(nvarchar,@rSubjectActivityId) + ' 
	 AND SA.DivisionId= ' + CONVERT(nvarchar,@rDivisionID) + '
	 And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	  AND ((CS.IsOptional = 1 AND  isnull(o.AcademicId,0)<>0) OR (CS.IsOptional = 0))
	 AND SA.StatusID=1
	 ) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

EXECUTE(@query)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectActivityScoreBulkGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0 --@rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	DECLARE @cols AS NVARCHAR(MAX),
	
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)


select @cols = STUFF((SELECT  ',' + QUOTENAME(Title) FROM sAssessment.tCCESubjectSubActivityMaster 
					 Where  OrgId=@rOrgId AND  SubjectActivityId=@rSubjectActivityId AND (( Id=@rSubActivityId)OR (@rSubActivityId=0))
					
				  
					--INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id 
					--AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId 
					--AND CGM.Id=@rCCECSGroupId AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by  OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Code AS Number,Name,  ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code,SA.Name,SSA.Title, ISNULL(SEC.Grade,'''') AS Term1Indicator
	FROM  
	 sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id 
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= ' + Convert(nvarchar,@rExamId)+ ' AND (SEC.SubjectSubActivityId = ' + convert(nvarchar,@rSubActivityId) + ' OR ' + convert(nvarchar,@rSubActivityId) + ' = 0 )
	 LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicID and o.ClassSubjectId=CS.ClassSubjectId  
				AND SEC.ExamId='+cONVERT(NVARCHAR,@rExamId )+'
	WHERE  SSA.OrgId= '+ CONVERT(nvarchar,@rOrgId) + ' 
	 AND SAM.ClassSubjectId= ' + CONVERT(nvarchar,@rClassId) + ' 
	  AND SSA.SubjectActivityId= '+ CONVERT(nvarchar,@rSubjectActivityId) + ' 
	 AND SA.DivisionId= ' + CONVERT(nvarchar,@rDivisionID) + '
	 And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	  --AND ((CS.IsOptional = 1 AND  isnull(o.AcademicId,0)<>0) OR (CS.IsOptional = 0))
	 AND SA.StatusID=1
	 ) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

EXECUTE(@query)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectGradeExamScoreAdd]
	 
            @rAcademicId bigint
           ,@rExamId int
           ,@rClassSubjectId int
           ,@rIndicator nvarchar(200)
		   ,@rGrade nvarchar(10)
		   ,@rDescriptiveIndicator nvarchar(200)
		   ,@rIndicatorIds nvarchar(50)
		    ,@rIsIndicatodIds bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT AcademicId FROM sAssessment.tGradeSujbectExamScore WHERE ClassSubjectId=@rClassSubjectId AND AcademicId=@rAcademicId AND ExamId=@rExamId)	
BEGIN
	INSERT INTO [sAssessment].[tGradeSujbectExamScore]
			   (		  
			    [ExamId]
			   ,[ClassSubjectId]
			   ,[AcademicId]
			   ,[GradeIndicator]
			   ,[Grade]
			   ,[DescriptiveIndicator]
			   ,[IndicatorIds]
			   )
		 VALUES
			   (
			    @rExamId	
			   ,@rClassSubjectId
			   ,@rAcademicId
			   ,@rIndicator
			   ,@rGrade
			   ,@rDescriptiveIndicator
			   ,@rIndicatorIds
			   )
		   -- SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	    UPDATE  [sAssessment].[tGradeSujbectExamScore]
	    SET
			 
	          [AcademicId]=@rAcademicId
	         ,[ExamId] =@rExamId
	         ,[ClassSubjectId]=@rClassSubjectId
	         ,GradeIndicator=@rIndicator
			 ,Grade =@rGrade
			 ,DescriptiveIndicator=@rDescriptiveIndicator
			 ,IndicatorIds=@rIndicatorIds
	      WHERE ClassSubjectId=@rClassSubjectId AND ExamId=@rExamId AND AcademicId=@rAcademicId 	   
	      --SELECT 1 AS Result
	 END  
	IF @rIsIndicatodIds = 1 
	BEGIN 	 
	UPDATE A SET A.DescriptiveIndicator = 
 					stuff((select ',' + B.Title from sAssessment.tSubjectIndicatorMaster B
				WHERE B.SubjectId=CS.SubjectId 
						and ','+ (replace(IndicatorIds,'.',',') )+',' like '%,'+CAST(Number as varchar(10))+',%'				
				for xml path('')),1,1,'') 
         From sAssessment.tGradeSujbectExamScore A
         INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = A.ClassSubjectId
          WHERE A.ClassSubjectId=@rClassSubjectId  
         AND A.AcademicId= @rAcademicId 
	      AND A.ExamId =@rExamId 
	 END    
	    
	  SELECT 1 AS Result
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectGradeExamScoreDelete]
 @rDivisionId int
,@rExamId int
,@rClassSubjectId int
AS
BEGIN
BEGIN TRY


DELETE S
FROM sAssessment.tGradeSujbectExamScore S
INNER JOIN sStudent.tAcademic A
ON S.AcademicId = A.Id
WHERE S.ExamId = @rExamId  AND S.ClassSubjectId=@rClassSubjectId
AND A.DivisionId = @rDivisionId


		--DELETE	FROM sAssessment.tGradeSujbectExamScore WHERE ExamId = @rExamId 
		--AND ClassSubjectId=@rClassSubjectId AND AcademicId IN
		--(Select Id From sStudent.tAcademic Where DivisionId =@rDivisionId)		
		SELECT 1 AS RESULT
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectGradeScoreGet]
	   @rOrgId int
	  ,@rBatchId int
	  ,@rDivisionId int
	  ,@rExamId int
	  ,@rClassSubjectId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				 --ISNULL(GSES.ExamId,0) AS ExamId,
				--ISNULL(GSES.ClassSubjectId,0) AS ClassSubjectId,
				SA.AcademicId,
				SA.NUMBER AS Code,
				SA.ROLLNO,
				SA.NAME AS StudentName,
				ISNULL(GSES.Grade,'') AS Grade,
				ISNULL(GSES.GradeIndicator,'') AS GradeIndicator,
				ISNULL(GSES.DescriptiveIndicator,'') AS DecriptiveIndicator,
				ISNULL(GSES.IndicatorIds,'') AS IndicatorIds ,
				--SM.Title AS SubjectName,
				--CM.Title AS CLASSNAME,
				--ESGM.Title AS ExamName,
				(Select GradeSetId From sAssessment.tExamMaster Where Id = @rExamId) as GradeSetId
			FROM  
			 sStudent.vStudentFull SA
			 
  					LEFT JOIN sAssessment.tGradeSujbectExamScore GSES	ON GSES.AcademicId = SA.AcademicId  
  						AND GSES.ExamId = @rExamId AND(( GSES.ClassSubjectId=@rClassSubjectId) OR (@rClassSubjectId=0))
  						
  						
					 	
					
  						 
			WHERE
				 SA.DivisionId = @rDivisionId AND SA.BatchId=@rBatchId  AND StatusId = 1  
				 
			ORDER BY SA.RollNo
			
			
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectIndicatorDetailAdd]
	 
	        @rId int
           ,@rSubjectId int
           ,@rTitle nvarchar(100)
           ,@rNumber smallint
		   ,@rOrderIndex int	
		   ,@rUpdatedUserId bigint
		   ,@rIsObsolete bit
		   ,@rOrgId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tSubjectIndicatorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tSubjectIndicatorMaster]
			   (
			    [Id]
			   ,[SubjectId]
			   ,[Title]
			   ,[Number] 
			   ,[OrgId]
			   ,[IsObsolete]
			   ,[OrderIndex]	
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rSubjectId
			   ,@rTitle
			   ,@rNumber
			   ,@rOrgId
			   ,@rIsObsolete
			   ,@rOrderIndex			   
			   ,@rUpdatedUserId			   
			   ,sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tSubjectIndicatorMaster]
	    SET
			 
	          SubjectId=@rSubjectId
	         ,Title=@rTitle
	         ,Number=@rNumber
	         ,OrgId=@rOrgId
	         ,IsObsolete=@rIsObsolete
			 ,OrderIndex=@rOrderIndex
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectIndicatorDetailGet]
	 @rSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT			
			SIM.Id,
			SIM.SubjectId,
			SIM.Number,
			SIM.TITLE,
			SIM.OrderIndex
  FROM 
			sAssessment.[tSubjectIndicatorMaster] SIM
WHERE 
			((SIM.SubjectId=@rSubjectId) OR (@rSubjectId=0))  order by SIM.OrderIndex ASC		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectIndicatorGroupDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
 IF NOT EXISTS (SELECT RD.ClassSubjectId FROM sGSEB.tResultDetailOptional RD 
                INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=RD.ClassSubjectId AND CS.SubjectId = @rId)	
	  BEGIN
		DELETE	FROM sAssessment.tSubjectIndicatorMaster WHERE SubjectId=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectIndicatorMasterDelete]
@rId	 bigint
AS
BEGIN
BEGIN TRY
	--IF NOT EXISTS (SELECT Id FROM sGSEB.tClassActivity WHERE ActivityId = @rActivityId)	
	  BEGIN
		DELETE	FROM sAssessment.tSubjectIndicatorMaster WHERE Id=@rId	
		SELECT 1 AS RESULT
	   END
	--ELSE
	--	BEGIN
	--		SELECT -101 AS RESULT
	--	END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectIndicatorScoreAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT
	 
	
	IF NOT EXISTS (SELECT RDO.AcademicId FROM sAssessment.tGradeSujbectExamScore RDO
			   INNER JOIN OPENXML (@loDoc, '/Table/SubjectIndicatorScore', 1)
			   WITH (AcademicId Bigint,SubjectTitle NVARCHAR(100), ExamId int) B 
			   ON RDO.AcademicId = B.AcademicId
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = RDO.ClassSubjectId
		AND RDO.ExamId = B.ExamId
		AND CS.ORGID = @rORGId	AND CS.SubjectName=B.SubjectTitle)
	 BEGIN	
		
		INSERT INTO sAssessment.tGradeSujbectExamScore
			(AcademicId,ClassSubjectId,ExamId,IndicatorIds)			
			SELECT AcademicId,CS.ClassSubjectId,ExamId,Term1Indicator
			FROM OPENXML (@loDoc, '/Table/SubjectIndicatorScore', 1)
			WITH ( 				
					AcademicId Bigint,
					SubjectTitle NVARCHAR(100),
					ExamId int,
					Term1Indicator nvarchar(20)
				  ) A 	
			INNER JOIN sSetup.vClassSubject CS ON CS.SubjectName = A.SubjectTitle AND CS.ORGID = @rORGId	
			INNER JOIN sStudent.tAcademic AC ON AC.Id = A.AcademicId AND AC.ClassId = CS.ClassId 
	 END  
	
	 ELSE
	
	 BEGIN
	
	 	UPDATE RDO
	 	SET
			RDO.AcademicId=B.AcademicId,
			RDO.ClassSubjectId=B.ClassSubjectId,
			RDO.ExamId = B.ExamId,
			RDO.IndicatorIds=B.Term1Indicator
		FROM	
		sAssessment.tGradeSujbectExamScore RDO 					
		INNER JOIN (
			SELECT AcademicId,CS.ClassSubjectId,ExamId,Term1Indicator										
			FROM OPENXML (@loDoc, '/Table/SubjectIndicatorScore', 1)
			WITH ( 				
					AcademicId Bigint,
					SubjectTitle NVARCHAR(100),
					ExamId int,
					Term1Indicator nvarchar(20)
				  ) A 	
			INNER JOIN sSetup.vClassSubject CS ON CS.SubjectName = A.SubjectTitle AND CS.ORGID = @rORGId	
			INNER JOIN sStudent.tAcademic AC ON AC.Id = A.AcademicId AND AC.ClassId = CS.ClassId ) AS B
			ON RDO.ACADEMICID = B.ACADEMICID AND RDO.ClassSubjectId=B.ClassSubjectId AND RDO.ExamId=B.ExamId
		 
	 END  
	 
	 UPDATE A SET A.DescriptiveIndicator = 
 					stuff((select ',' + B.Title from sAssessment.tSubjectIndicatorMaster B
				WHERE B.SubjectId=CS.SubjectId 
						and ','+ (replace(IndicatorIds,'.',',') )+',' like '%,'+CAST(Number as varchar(10))+',%'				
				for xml path('')),1,1,'') 
         From sAssessment.tGradeSujbectExamScore A
         INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = A.ClassSubjectId
         INNER JOIN OPENXML (@loDoc, '/Table/SubjectIndicatorScore', 1)
			WITH ( 				
					AcademicId Bigint,
					SubjectTitle NVARCHAR(100),
					ExamId int,
					Term1Indicator nvarchar(20)
				  ) A1 ON A.ACADEMICID = A1.ACADEMICID AND A.EXAMID = A1.EXAMID
	 
	     SELECT 1 AS Result
	END
	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectIndicatorScoreDelete]
 @rDivisionId int
,@rExamId int

AS
BEGIN
BEGIN TRY

DELETE S
FROM sAssessment.tGradeSujbectExamScore S
INNER JOIN sStudent.tAcademic A
ON S.AcademicId = A.Id
WHERE S.ExamId = @rExamId AND A.DivisionId = @rDivisionId

 	
		SELECT 1 AS RESULT
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectIndicatorScoreGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

 
	
 	DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(CS.SubjectName) 
					  From sSetup.vClassSubject CS 
					  INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CS.ClassId
					  INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId AND ED.ClassSubjectId=CS.ClassSubjectId AND EM.Id=@rExamId
					  WHERE CS.ClassId = @rClassId 
					  AND IsShowSubjectGrade = 1 AND IsShowSubjectMark = 0 
					  AND IsIncludeInTotal = 0   Order By OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

       
	BEGIN
	SET @query = 'Select  AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Number,SA.Name,CS.SubjectName, ISNULL(RDO.IndicatorIds,'''') AS Term1Indicator		
	FROM sStudent.vStudentAcademic SA
		 
		LEFT JOIN sAssessment.tGradeSujbectExamScore RDO	ON RDO.AcademicId = SA.AcademicId  
  			AND RDO.ExamId = '+ CONVERT(nvarchar,@rExamId) + '
  	LEFT  join  sSetup.vClassSubject CS ON  CS.ClasssubjectId = RDO.ClasssubjectId
	
	WHERE  SA.StatusId = 1 AND   SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + ' And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' 
			
	) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR  SubjectName IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	

	END

 --print (@query)

 execute(@query)
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectRemarkAdd]
	 
	       
		    @rSubjectRemark nvarchar(1000)
		   ,@rExamId int
		   ,@rAcademicId bigint
		   ,@rClassSubjectId int
		   ,@rPresentCount int
		   ,@rTotalCount int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	if exists (select 1 from sAssessment.tResultDetailOther where ExamId = @rExamid and AcademicId = @racademicid and classsubjectid= @rclasssubjectid)
	begin
		update sAssessment.tResultDetailOther
		Set 
			Remark =@rSubjectRemark,
			PresentCount=@rPresentCount,
			TotalCount = @rTotalCount
		Where  ExamId = @rExamid and AcademicId = @racademicid and classsubjectid= @rclasssubjectid
		Select 11 As Result
	end
	 
ELSE
	 BEGIN
	     
	INSERT INTO sAssessment.tResultDetailOther
			   (
			    ExamId
			   ,AcademicId 
			   ,ClassSubjectId
			   ,Remark
			   ,PresentCount
			   ,TotalCount
			   )
		 VALUES
			   (
				@rExamId
			   ,@rAcademicId
			   ,@rClassSubjectId
			   ,@rSubjectRemark
			   ,@rPresentCount
			   ,@rTotalCount
			   )
		    SELECT 1 AS Result
	 END  
		 
 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectRemarkGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	  
	 @rClassSubjectId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


SELECT 
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,ISNULL(RD.Remark,'') AS SubjectRemark
	,ISNULL(RD.TotalCount,0) As TotalCount
	,ISNULL(RD.PresentCount,0)As PresentCount
	 
from 
	sStudent.vStudentAcademic SA 
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id	
	LEFT JOIN sAssessment.tResultDetailOther RD ON  RD.ExamId = Em.Id AND SA.Academicid =RD.AcademicId AND ED.ClassSubjectId = RD.ClassSubjectId
	INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.Academicid AND o.ClassSubjectId=CS.ID
	 
Where  
	  (DM.Id=@rDivisionId OR @rDivisionId = 0)
	   AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND (EM.Id=@rExamId OR @rExamId = 0)
	   AND ED.ClassSubjectId = @rClassSubjectId
	   AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	   AND ((CS.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (CS.IsOptional = 0))
Order By SA.RollNo


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAssessment].[pSubjectSubActivityIDGet]
	  @rCSGroupId int,
	  @rTitle nvarchar(200)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
SELECT 			ISNULL(Id,0) AS Id
FROM 
			sAssessment.tCCESubjectSubActivityMaster Where SubjectActivityId = @rCSGroupId AND Title like @rTitle
				
			  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAssessment].[pTeacherEvaluationSubjectWiseGet]
	 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 --@rOrgId int=0,
	 @rGroupid int=0,
	 @rEmployeeId bigint=0,
	 @rSubjectId int=0
 	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	 select 
		@rBuilder1 AS Builder1,
		CM.ClassId  As ClassId,
		Dm.id As DivisionId,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Cm.ClassName AS ClassName,
		DM.DisplayTitle AS DivisionName,
		Sm.OrderIndex As SubjectOrderIndex,
		
		case when @rGroupid=1 THEN Dm.Id
		when @rGroupid=2 THEN CM.ClassId
		when @rGroupid=3 THEN CM.DepartmentId
	    when @rGroupid=4 THEN OM.Id
		ELSE 0  END  AS HeadId,
		
		case when @rGroupid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle   
		when @rGroupid=2 THEN ' Class : ' + CM.ClassName
		when @rGroupid=3 THEN 'Department: ' + DP.Title 
		WHen @rGroupid=4 THen  'Organization : '+Om.Title END  AS HeadName,
		CASE WHEN @rGroupid=1 THEN DM.OrderIndex
				WHEN @rGroupid=2  THEN CM.OrderIndex
				WHEN @rGroupid=3  THEN DP.Id
				WHen @rGroupid=4 THen OM.OrderIndex  END AS OrderIndex,
		TSV.EmployeeId,
		EMP.FirstName+' ' +EMP.MiddleName+' '+EMP.LastName AS EMPName,
	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
		INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.SubjectId=@rSubjectId  AND TS.EmployeeId=TSV.EmployeeId
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
	  AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND TS.SubjectId=@rSubjectId) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	 INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	 INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	 INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.SubjectId=@rSubjectId AND TS.EmployeeId=TSV.EmployeeId
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND TS.SubjectId=@rSubjectId) AS FailStudent 
	  
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId 
	INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId 
	 INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
INNER JOIN sAcademic.tTeacherSubjectDivision TSV ON TSV.SubjectId=CS.SubjectId  AND TSV.DivisionId=DM.ID
INNER JOIN sHrm.tEmployeeMaster EMP ON EMP.Id=TSV.EmployeeId AND  ISNULL(EMP.IsOtherUser,0) = 0
		WHERE 
			((DM.ID=@rDivisionId) or (@rDivisionId=0))
			AND ((CM.ClassId=@rClassId) or (@rClassId=0))
			AND   CM.BatchId=@rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
			AND EM.BatchId = @rBatchId
			 AND TSV.SubjectId=@rSubjectId
			AND EMP.StatusId =7
			
 -- UNION ALL
  
  
 -- 	 select 
	--	@rBuilder1 AS Builder1,
	--	DM.Classid As ClassId,
	--	Dm.id As DivisionId,
	--	--Cm.ClassName As Classname,
	--	--DM.DisplayTitle As DivisionName,
	--0 AS ClassSubjectId,
	--	0 AS SubjectId,
	--	'Over All' AS SubjectName,
	--	0 AS ClassOrderIndex,
	--	case when @rGroupByid=1 THEN Dm.Id
	--	when @rGroupByid=2 THEN CM.Classid
	--	when @rGroupByid=3 THEN CM.DepartmentId
	--    when @rGroupByid=4 THEN OM.Id
	--	ELSE 0    END  AS HeadId,
	--	case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle  
	--	when @rGroupByid=2 THEN ' Class : ' + CM.ClassName  
	--	when @rGroupByid=3 THEN 'Department: ' + DP.Title 
	--	WHen @rGroupByid=4 THEN  'Organization : '+OM.Title
	--	END  AS HeadName,
	--	CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
	--			WHEN @rGroupByid=2  THEN CM.OrderIndex
	--			WHEN @rGroupByid=3  THEN DP.Id
	--			WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
	 

 --(select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND R.ResultStatus='PASS') AS PassStudent,
	  
	--  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent 
	  
	-- from
	-- ssetup.tDivisionMaster DM
	-- INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	-- INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	--INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	-- INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	-- INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
 --   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
 --   INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.EmployeeId=@rEmployeeId
	--	WHERE 
	--		((DM.ID=@rDivisionId) or (@rDivisionId=0))
	--		AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
	--		AND CM.BatchId=@rBatchId
	--		AND EM.ExamSubGroupId = @rExamSubGroupId
	--		AND EM.BatchId = @rBatchId
	--		AND TS.EmployeeId=@rEmployeeId
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pTypeWiseAssessmentConsolidatedDashboardGet]
	 
	@rOrgId int=0,
	@rTypeId int=0,
	@rCommonOrgGroupBatchId int=0,
	@rExamSubGroupId nvarchar(max)='',
	@rRangeId int=0,
	@rClassId int =0,
	@rDivisionId int =0,
	@rSubjectId int=0,
	@rEmployeeId bigint=0,
	@rIsCount bit=1
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
/******
	TypeId = 1 Class wise Count
	TypeId = 2 DiVision Wise Count
	TypeId = 3 Subject Wise Count
	TypeId = 4 Teacher Wise Count
	
	TypeId = 11 Class wise Detail's
	TypeId = 21 DiVision Wise Detail's
	TypeId = 31 Subject Wise Detail's
	TypeId = 41 Teacher Wise Detail's
******/
   
	CREATE TABLE #TblFinalRecord
			(
				Id int identity,
				FromPercentage DECIMAL(10,2),
				ToPercentage DECIMAL(10,2)
			) 
				--INSERT INTO #TblFinalRecord(FromPercentage,ToPercentage) VALUES (90.49,100),(80.49,90.49),(70.49,80.49),(60.49,70.49),(50.49,60.49),(40.49,50.49),(-1,40.49)	
				INSERT INTO #TblFinalRecord(FromPercentage,ToPercentage) VALUES (90.49,100),(75.49,90.49),(60.49,75.49),(45.49,60.49),(0,45.49)	
			DECLARE @lFromPercentage DECIMAL(10,2),@lToPercentage DECIMAL(10,2)
			 
	IF(@rTypeId=1)--TypeId = 1  is For Class Wise Count
		BEGIN
		  IF(@rIsCount = 1)
		  BEGIN
			SELECT CM.Id AS ClassId,CM.Title AS ClassName,
			COUNT(R90.R90) AS '> 90',
			COUNT(R80.R80) AS '> 75',
			COUNT(R70.R70) AS '> 60',
			COUNT(R60.R60) AS '> 45',
			--COUNT(R50.R50) AS '51-60',
			--COUNT(R40.R40) AS '41-50',
			COUNT(R30.R30) AS '< 45'
			FROM  sSetup.tClassMaster CM
					INNER JOIN sAssessment.tExamMaster EM ON CM.Id = EM.ClassId
					INNER JOIN sAssessment.tResult R ON  EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					--LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.classId AND 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
				(SELECT R1.Id AS R90  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100			
					  )R90 ON R90.R90 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R80  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49			
					  )R80 ON R80.R80 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R70  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49			
					  )R70 ON R70.R70 = R.Id	
				   LEFT JOIN 
					  (SELECT R1.Id AS R60  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49			
					  )R60 ON R60.R60 = R.Id
				  LEFT JOIN
					  (SELECT R1.Id AS R30  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
					  )R30 ON R30.R30 = R.Id
	--				  (SELECT R1.Id AS R90  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100			
	--				  )R90 ON R90.R90 = R.Id
	--			 LEFT JOIN 
	--				  (SELECT R1.Id AS R80  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 80.49 AND R1.Percentage <= 90.49			
	--				  )R80 ON R80.R80 = R.Id
	--			 LEFT JOIN 
	--				  (SELECT R1.Id AS R70  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 70.49 AND R1.Percentage <= 80.49			
	--				  )R70 ON R70.R70 = R.Id	
	--			   LEFT JOIN 
	--				  (SELECT R1.Id AS R60  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 60.49 AND R1.Percentage <= 70.49			
	--				  )R60 ON R60.R60 = R.Id
	--			  LEFT JOIN 
	--				  (SELECT R1.Id AS R50  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49		
	--				  )R50 ON R50.R50 = R.Id
	--			 LEFT JOIN 
	--				  (SELECT R1.Id AS R40  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49
	--				  )R40 ON R40.R40 = R.Id
	--			 LEFT JOIN 
	--				  (SELECT R1.Id AS R30  FROM sAssessment.tResult R1
	--WHERE R1.Percentage <= 40.49
	--				  )R30 ON R30.R30 = R.Id
				   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null) 
				--AND CM.Id = 110100003
				AND CM.OrgId = @rOrgId
				GROUP BY CM.Id,CM.Title
		  END
		  ELSE 
		  BEGIN
			SELECT CM.Id AS ClassId,CM.Title AS ClassName,
				   (COUNT(R90.R90) * 100 / COUNT(A.Id)) AS '> 90 Per',
				   (COUNT(R80.R80) * 100 / COUNT(A.Id)) AS '> 75 Per',
				   (COUNT(R70.R70) * 100 / COUNT(A.Id)) AS '> 60 Per',
				   (COUNT(R60.R60) * 100 / COUNT(A.Id)) AS '> 45 Per',
				   (COUNT(R30.R30) * 100 / COUNT(A.Id)) AS '< 45 Per'
			FROM  sSetup.tClassMaster CM
					INNER JOIN sAssessment.tExamMaster EM ON CM.Id = EM.ClassId
					INNER JOIN sAssessment.tResult R ON  EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					--LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.classId AND 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
				(SELECT R1.Id AS R90  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100			
					  )R90 ON R90.R90 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R80  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49			
					  )R80 ON R80.R80 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R70  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49			
					  )R70 ON R70.R70 = R.Id	
				   LEFT JOIN 
					  (SELECT R1.Id AS R60  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49			
					  )R60 ON R60.R60 = R.Id
				  LEFT JOIN
					  (SELECT R1.Id AS R30  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
	--R1.Percentage <= 0
					  )R30 ON R30.R30 = R.Id
				   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null) 
				--AND CM.Id = 110100003
				AND CM.OrgId = @rOrgId
				GROUP BY CM.Id,CM.Title
		  END
		END
	ELSE IF (@rTypeId=2)--TypeId = 2 is For Division Wise Count
		BEGIN
		  IF(@rIsCount = 1)
		  BEGIN
			SELECT DM.Id AS DivisionId,DM.Code AS ClassDivisionName,
				--COUNT(R90.R90) AS '91-100',
				--COUNT(R80.R80) AS '81-90',
				--COUNT(R70.R70) AS '71-80',
				--COUNT(R60.R60) AS '61-70',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				--COUNT(R30.R30) AS 'Below-40'
				COUNT(R90.R90) AS '> 90',
				COUNT(R80.R80) AS '> 75',
				COUNT(R70.R70) AS '> 60',
				COUNT(R60.R60) AS '> 45',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				COUNT(R30.R30) AS '< 45'
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
					  (SELECT R1.Id AS R90,A1.DivisionId AS DivisionId   FROM sAssessment.tResult R1
					   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
		        			  )R90 ON R90.R90 = R.Id AND DM.Id = R90.DivisionId	
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R80,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49
		        			  )R80 ON R80.R80 = R.Id AND DM.Id = R80.DivisionId	
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R70,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49
		        			  )R70 ON R70.R70 = R.Id AND DM.Id = R70.DivisionId		
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R60,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49
					  )R60 ON R60.R60 = R.Id AND DM.Id = R60.DivisionId	
				--	    LEFT JOIN 
				--			  (SELECT R1.Id AS R50,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				--			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49
				--			  )R50 ON R50.R50 = R.Id AND DM.Id = R50.DivisionId	
				--		LEFT JOIN 
				--			  (SELECT R1.Id AS R40,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				--			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49
				--			  )R40 ON R40.R40 = R.Id AND DM.Id = R40.DivisionId	
			LEFT JOIN 
				  (SELECT R1.Id AS R30,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	        WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
			--R1.Percentage <= 0
				  )R30 ON R30.R30 = R.Id AND DM.Id = R30.DivisionId	
			   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
				AND DM.OrgId = @rOrgId AND DM.IsObsolete = 0
				GROUP BY DM.Id,DM.Code,DM.OrderIndex
				ORDER BY DM.OrderIndex
		  END
		  ELSE
		  BEGIN
				SELECT DM.Id AS DivisionId,DM.Code AS ClassDivisionName,
				(COUNT(R90.R90) * 100 / COUNT(A.Id)) AS '> 90 Per',
				(COUNT(R80.R80) * 100 / COUNT(A.Id)) AS '> 75 Per',
				(COUNT(R70.R70) * 100 / COUNT(A.Id)) AS '> 60 Per',
				(COUNT(R60.R60) * 100 / COUNT(A.Id)) AS '> 45 Per',
				(COUNT(R30.R30) * 100 / COUNT(A.Id)) AS '< 45 Per'
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
					  (SELECT R1.Id AS R90,A1.DivisionId AS DivisionId   FROM sAssessment.tResult R1
					   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
		        			  )R90 ON R90.R90 = R.Id AND DM.Id = R90.DivisionId	
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R80,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49
		        			  )R80 ON R80.R80 = R.Id AND DM.Id = R80.DivisionId	
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R70,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49
		        			  )R70 ON R70.R70 = R.Id AND DM.Id = R70.DivisionId		
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R60,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49
					  )R60 ON R60.R60 = R.Id AND DM.Id = R60.DivisionId	
				--	    LEFT JOIN 
				--			  (SELECT R1.Id AS R50,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				--			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49
				--			  )R50 ON R50.R50 = R.Id AND DM.Id = R50.DivisionId	
				--		LEFT JOIN 
				--			  (SELECT R1.Id AS R40,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				--			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49
				--			  )R40 ON R40.R40 = R.Id AND DM.Id = R40.DivisionId	
			LEFT JOIN 
				  (SELECT R1.Id AS R30,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	        WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
			--R1.Percentage <= 0
				  )R30 ON R30.R30 = R.Id AND DM.Id = R30.DivisionId	
			   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
					AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
					AND DM.OrgId = @rOrgId AND DM.IsObsolete = 0
				GROUP BY DM.Id,DM.Code,DM.OrderIndex
				ORDER BY DM.OrderIndex
		  END
		END
	ELSE IF (@rTypeId=3)--TypeId = 3 is For Subject Wise Count
		BEGIN
		  IF(@rIsCount = 1)
			BEGIN
			 SELECT SM.Id AS SubjectId,SM.Title AS SubjectName,
				--COUNT(R90.R90) AS '91-100',
				--COUNT(R80.R80) AS '81-90',
				--COUNT(R70.R70) AS '71-80',
				--COUNT(R60.R60) AS '61-70',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				--COUNT(R30.R30) AS 'Below-40' 
				COUNT(R90.R90) AS '> 90',
				COUNT(R80.R80) AS '> 75',
				COUNT(R70.R70) AS '> 60',
				COUNT(R60.R60) AS '> 45',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				COUNT(R30.R30) AS '< 45'
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
				  (SELECT R.Id As R90,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
					INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
					INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			   WHERE  RD.Obtain > 90.49 AND RD.Obtain <=100
	       			  )R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
	       		  LEFT JOIN 
	       			  (SELECT R.Id As R80,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
	       				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
	       				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
	       				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	       				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
	       				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			   WHERE  RD.Obtain > 75.49 AND RD.Obtain <= 90.49 
	       			  )R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
	       		 LEFT JOIN 
	       			  (SELECT R.Id As R70,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
	       				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
	       				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
	       				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	       				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
	       				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			   WHERE  RD.Obtain > 60.49 AND RD.Obtain <= 75.49 
				   ) R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
				 LEFT JOIN 
				  (SELECT R.Id As R60,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
					INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
					INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			   WHERE  RD.Obtain > 45.49 AND RD.Obtain <= 60.49 
				   )R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
				--	  LEFT JOIN 
				--		  (SELECT R.Id As R50,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				--			INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				--			INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				--			INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				--			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				--			LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE  RD.Obtain > 50.49 AND RD.Obtain <= 60.49 
				--		   )R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
				--	 LEFT JOIN 
				--		  (SELECT R.Id As R40,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				--			INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				--			INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				--			INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				--			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				--			LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE  RD.Obtain > 40.49 AND RD.Obtain <= 50.49 
				--		   )R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
			 LEFT JOIN 
				  (SELECT R.Id As R30,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
					INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
					INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				   WHERE RD.Obtain > 0 AND RD.Obtain <=45.49
				   --RD.Obtain <= 0
				 )R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
		   
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
					--AND CM.Id = 110100003
				AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0 
				AND (DM.Id = @rDivisionId OR DM.ClassId = @rClassId)
			GROUP BY SM.Id,SM.title,SM.OrderIndex 
			ORDER BY SM.OrderIndex 
			END
			ELSE
			BEGIN
				SELECT SM.Id AS SubjectId,SM.Title AS SubjectName,
					(COUNT(R90.R90) * 100 / COUNT(A.Id)) AS '> 90 Per',
					(COUNT(R80.R80) * 100 / COUNT(A.Id)) AS '> 75 Per',
					(COUNT(R70.R70) * 100 / COUNT(A.Id)) AS '> 60 Per',
					(COUNT(R60.R60) * 100 / COUNT(A.Id)) AS '> 45 Per',
					(COUNT(R30.R30) * 100 / COUNT(A.Id)) AS '< 45 Per'
				FROM  sAssessment.tResult R 
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
					INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN 
					  (SELECT R.Id As R90,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
						INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
						INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
						INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
						LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
						INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				   WHERE  RD.Obtain > 90.49 AND RD.Obtain <=100
	       				  )R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
	       			  LEFT JOIN 
	       				  (SELECT R.Id As R80,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
	       					INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
	       					INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
	       					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	       					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
	       					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
	       					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				   WHERE  RD.Obtain > 75.49 AND RD.Obtain <= 90.49 
	       				  )R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
	       			 LEFT JOIN 
	       				  (SELECT R.Id As R70,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
	       					INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
	       					INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
	       					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	       					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
	       					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
	       					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				   WHERE  RD.Obtain > 60.49 AND RD.Obtain <= 75.49 
					   ) R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
					 LEFT JOIN 
					  (SELECT R.Id As R60,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
						INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
						INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
						INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
						LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
						INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				   WHERE  RD.Obtain > 45.49 AND RD.Obtain <= 60.49 
					   )R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
					--	  LEFT JOIN 
					--		  (SELECT R.Id As R50,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
					--			INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
					--			INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
					--			INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					--			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					--			LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
					--WHERE  RD.Obtain > 50.49 AND RD.Obtain <= 60.49 
					--		   )R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
					--	 LEFT JOIN 
					--		  (SELECT R.Id As R40,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
					--			INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
					--			INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
					--			INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					--			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					--			LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
					--WHERE  RD.Obtain > 40.49 AND RD.Obtain <= 50.49 
					--		   )R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
				 LEFT JOIN 
					  (SELECT R.Id As R30,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
						INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
						INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
						INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
						LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
						INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
					   WHERE RD.Obtain > 0 AND RD.Obtain <=45.49
					   --RD.Obtain <= 0
					 )R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
		   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
					AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
						--AND CM.Id = 110100003
					AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0 
					AND (DM.Id = @rDivisionId OR DM.ClassId = @rClassId)
				GROUP BY SM.Id,SM.title,SM.OrderIndex 
				ORDER BY SM.OrderIndex 
			END
		END
		
	ELSE IF (@rTypeId=4)--TypeId = 4 is For Teacher Wise Count
		BEGIN
		 IF(@rIsCount = 1)
		  BEGIN
			SELECT ISNULL(DM.Id,'') AS DivisionId,ISNULL(DM.Code,'') AS ClassDivisionName,ISNULL(SM.Id,'') AS SubjectId,ISNULL(SM.Title,'') AS SubjectName,
				--COUNT(R90.R90) AS '91-100',
				--COUNT(R80.R80) AS '81-90',
				--COUNT(R70.R70) AS '71-80',
				--COUNT(R60.R60) AS '61-70',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				--COUNT(R30.R30) AS 'Below-40',
				COUNT(R90.R90) AS '> 90',
				COUNT(R80.R80) AS '> 75',
				COUNT(R70.R70) AS '> 60',
				COUNT(R60.R60) AS '> 45',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				COUNT(R30.R30) AS '< 45',
				EMP.EmployeeName,EMP.EmployeeId
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId	
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id		
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId --AND CS.ClassId = A.classId
				LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				LEFT JOIN sSetup.tDivisionMaster DM ON  DM.ClassId = EM.ClassId
				INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId AND TS.DivisionId=DM.ID AND TS.EmployeeId = @rEmployeeId
				--INNER JOIN  sHrm.tEmployeeMaster EM ON EM.ID = TS.EmployeeId
				INNER JOIN sSetup.tBatchMaster BM ON  BM.Id = EM.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT Id AS EmployeeId,FirstName+' '+ LastName AS EmployeeName FROM sHrm.tEmployeeMaster WHERE ISNULL(IsOtherUser,0) = 0
				) EMP ON EMP.EmployeeId = TS.EmployeeId 
			
				LEFT JOIN 
				(SELECT R1.Id AS R90,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					-- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
					INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
	       			)R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R80,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49 
	       			)R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R70,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49 
	       			)R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R60,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49 
				)R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
				--		LEFT JOIN 
				--		(SELECT R1.Id AS R50,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				--			INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--			--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				--			INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49 
				--		)R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
				--		LEFT JOIN 
				--		(SELECT R1.Id AS R40,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				--			INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--			--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				--			INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49 
				--		)R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
				LEFT JOIN 
				(SELECT R1.Id AS R30,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
					INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	      WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
		  --R1.Percentage <= 0
			    )R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
			WHERE COGBM.Id = @rCommonOrgGroupBatchId
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
				AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0
			GROUP BY SM.Id,SM.title,EMP.EmployeeName,EMP.EmployeeId,DM.Code,DM.Id,SM.OrderIndex 
			ORDER BY SM.OrderIndex 
		 END
		  ELSE
		   BEGIN
			SELECT ISNULL(DM.Id,'') AS DivisionId,ISNULL(DM.Code,'') AS ClassDivisionName,ISNULL(SM.Id,'') AS SubjectId,ISNULL(SM.Title,'') AS SubjectName,
				(COUNT(R90.R90) * 100 / COUNT(A.Id)) AS '> 90 Per',
				(COUNT(R80.R80) * 100 / COUNT(A.Id)) AS '> 75 Per',
				(COUNT(R70.R70) * 100 / COUNT(A.Id)) AS '> 60 Per',
				(COUNT(R60.R60) * 100 / COUNT(A.Id)) AS '> 45 Per',
				(COUNT(R30.R30) * 100 / COUNT(A.Id)) AS '< 45 Per',
				EMP.EmployeeName,EMP.EmployeeId
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId	
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id		
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId --AND CS.ClassId = A.classId
				LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				LEFT JOIN sSetup.tDivisionMaster DM ON  DM.ClassId = EM.ClassId
				INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId AND TS.DivisionId=DM.ID AND TS.EmployeeId = @rEmployeeId
				--INNER JOIN  sHrm.tEmployeeMaster EM ON EM.ID = TS.EmployeeId
				INNER JOIN sSetup.tBatchMaster BM ON  BM.Id = EM.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT Id AS EmployeeId,FirstName+' '+ LastName AS EmployeeName FROM sHrm.tEmployeeMaster WHERE ISNULL(IsOtherUser,0) = 0
				)EMP ON EMP.EmployeeId = TS.EmployeeId 
			
				LEFT JOIN 
				(SELECT R1.Id AS R90,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					-- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
					INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
	       			)R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R80,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49 
	       			)R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R70,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49 
	       			)R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R60,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49 
				)R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
				--		LEFT JOIN 
				--		(SELECT R1.Id AS R50,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				--			INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--			--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				--			INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49 
				--		)R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
				--		LEFT JOIN 
				--		(SELECT R1.Id AS R40,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				--			INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--			--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				--			INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49 
				--		)R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
				LEFT JOIN 
				(SELECT R1.Id AS R30,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
					INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	      WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
		  --R1.Percentage <= 0
			    )R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
			WHERE COGBM.Id = @rCommonOrgGroupBatchId
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
				AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0
			GROUP BY SM.Id,SM.title,EMP.EmployeeName,EMP.EmployeeId,DM.Code,DM.Id,SM.OrderIndex 
			ORDER BY SM.OrderIndex 
		   END
		END
		
		
	ELSE IF(@rTypeId=11)--TypeId = 11  is For Class Wise Detail's
		BEGIN
		
				SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
				SELECT CM.Id AS ClassId,CM.Title AS ClassName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo--,COUNT(RAll.RAll) AS 'RAll'
				FROM  sAssessment.tResult R 
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
					LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.classId AND CM.Id = EM.ClassId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN 
					(SELECT R1.Id AS RAll  FROM sAssessment.tResult R1
	WHERE R1.Percentage > @lFromPercentage AND R1.Percentage <= @lToPercentage			
					)RAll ON RAll.RAll = R.Id
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
				--AND EM.ExamSubGroupId = @rExamSubGroupId
				AND CM.OrgId = @rOrgId AND ((CM.Id = @rClassId)OR(@rClassId=0))
				GROUP BY CM.Id,CM.Title,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
				HAVING COUNT(RAll.RAll) >0

				DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId=21) -- TypeId = 21  is For Division Wise Detail's
		BEGIN
		
		SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
			SELECT DM.Id AS ClassId,DM.Code AS ClassName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
				FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
				(SELECT R1.Id AS RAll,A1.DivisionId AS DivisionId   FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > @lFromPercentage AND R1.Percentage <= @lToPercentage
				--WHERE  R1.Percentage <= 40
				)RAll ON RAll.RAll = R.Id AND DM.Id = RAll.DivisionId	
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			--AND EM.ExamSubGroupId = @rExamSubGroupId 
			 AND ((DM.Id = @rDivisionId)OR(@rDivisionId=0))
			AND DM.OrgId = @rOrgId
			GROUP BY DM.Id,DM.Code,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
			HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId=31) -- TypeId = 31  is For Subject Wise Detail's
		BEGIN
			SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
			SELECT SM.Id AS SubjectId,SM.Title AS SubjectName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
				FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
					(SELECT R1.Id AS RAll,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM 
					sAssessment.tResultDetail RD 
                	INNER Join sAssessment.tResult R1 ON  RD.ResultId = R1.Id
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE RD.Obtain > @lFromPercentage AND RD.Obtain <= @lToPercentage
				)RAll ON RAll.RAll = R.Id AND SM.Id = RAll.SubjectId	AND DM.Id = RAll.DivisionId
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			--AND EM.ExamSubGroupId = @rExamSubGroupId 
			 AND ((SM.Id = @rSubjectId)OR(@rSubjectId=0))
			 AND (DM.ClassId = @rClassId OR DM.Id = @rDivisionId)
			AND DM.OrgId = @rOrgId
			GROUP BY SM.Id,SM.title,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
				HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId=41) -- TypeId = 41  is For Teacher Wise Detail's
		BEGIN
				 SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId


			SELECT ISNULL(STM.Code,'')AS Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
			--,EMP.EmployeeName,EMP.EmployeeId
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id			
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
				LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				LEFT JOIN sSetup.tDivisionMaster DM ON  DM.ClassId = EM.ClassId
				INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId AND TS.DivisionId=DM.ID
				--INNER JOIN  sHrm.tEmployeeMaster EM ON EM.ID = TS.EmployeeId
				INNER JOIN sSetup.tBatchMaster BM ON  BM.Id = EM.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT Id AS EmployeeId,FirstName+' '+ LastName AS EmployeeName FROM sHrm.tEmployeeMaster WHERE ISNULL(IsOtherUser,0) = 0
				)EMP ON EMP.EmployeeId = TS.EmployeeId 
				
				LEFT JOIN 
				  (SELECT R1.Id AS RAll,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				  -- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				   INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
				   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > @lFromPercentage AND R1.Percentage <= @lToPercentage
				  )RAll ON RAll.RAll = R.Id AND SM.Id = RAll.SubjectId	AND DM.Id = RAll.DivisionId
		 	
		   
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			--AND EM.ExamSubGroupId = @rExamSubGroupId  
			--AND CM.Id = 110100003
				AND SM.OrgId = @rOrgId
				AND DM.Id = @rDivisionId AND SM.Id = @rSubjectId AND EMP.EmployeeId = @rEmployeeId
				GROUP BY STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
			HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
			
		END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssessment].[pTypeWiseAssessmentConsolidatedDashboardGet_old]
	 
	@rOrgId int=0,
	@rTypeId int=0,
	@rCommonOrgGroupBatchId int=0,
	@rExamSubGroupId nvarchar(max)='',
	@rRangeId int=0,
	@rClassId int =0,
	@rDivisionId int =0,
	@rSubjectId int=0,
	@rEmployeeId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
/******
	TypeId = 1 Class wise Count
	TypeId = 2 DiVision Wise Count
	TypeId = 3 Subject Wise Count
	TypeId = 4 Teacher Wise Count
	
	TypeId = 11 Class wise Detail's
	TypeId = 21 DiVision Wise Detail's
	TypeId = 31 Subject Wise Detail's
	TypeId = 41 Teacher Wise Detail's
******/
   
	CREATE TABLE #TblFinalRecord
			(
				Id int identity,
				FromPercentage DECIMAL(10,2),
				ToPercentage DECIMAL(10,2)
			) 
				INSERT INTO #TblFinalRecord(FromPercentage,ToPercentage) VALUES (90.49,100),(80.49,90.49),(70.49,80.49),(60.49,70.49),(50.49,60.49),(40.49,50.49),(-1,40.49)	
			DECLARE @lFromPercentage DECIMAL(10,2),@lToPercentage DECIMAL(10,2)
			 
	IF(@rTypeId=1)--TypeId = 1  is For Class Wise Count
		BEGIN
			SELECT CM.Id AS ClassId,CM.Title AS ClassName,COUNT(R90.R90) AS '91-100',COUNT(R80.R80) AS '81-90',COUNT(R70.R70) AS '71-80',COUNT(R60.R60) AS '61-70'
			,COUNT(R50.R50) AS '51-60',COUNT(R40.R40) AS '41-50',COUNT(R30.R30) AS 'Below-40'
			FROM  sSetup.tClassMaster CM
					INNER JOIN sAssessment.tExamMaster EM ON CM.Id = EM.ClassId
					INNER JOIN sAssessment.tResult R ON  EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					--LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.classId AND 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
					  (SELECT R1.Id AS R90  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100			
					  )R90 ON R90.R90 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R80  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 80.49 AND R1.Percentage <= 90.49			
					  )R80 ON R80.R80 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R70  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 70.49 AND R1.Percentage <= 80.49			
					  )R70 ON R70.R70 = R.Id	
				   LEFT JOIN 
					  (SELECT R1.Id AS R60  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 70.49			
					  )R60 ON R60.R60 = R.Id
				  LEFT JOIN 
					  (SELECT R1.Id AS R50  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49		
					  )R50 ON R50.R50 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R40  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49
					  )R40 ON R40.R40 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R30  FROM sAssessment.tResult R1
	WHERE R1.Percentage <= 40.49
					  )R30 ON R30.R30 = R.Id
				   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null) 
				--AND CM.Id = 110100003
				AND CM.OrgId = @rOrgId
				GROUP BY CM.Id,CM.Title
		END
	ELSE IF (@rTypeId=2)--TypeId = 2 is For Division Wise Count
		BEGIN
			SELECT DM.Id AS DivisionId,DM.Code AS ClassDivisionName,COUNT(R90.R90) AS '91-100',COUNT(R80.R80) AS '81-90',COUNT(R70.R70) AS '71-80',COUNT(R60.R60) AS '61-70'
			,COUNT(R50.R50) AS '51-60',COUNT(R40.R40) AS '41-50',COUNT(R30.R30) AS 'Below-40'
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			LEFT JOIN 
				  (SELECT R1.Id AS R90,A1.DivisionId AS DivisionId   FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
				  )R90 ON R90.R90 = R.Id AND DM.Id = R90.DivisionId	
		    LEFT JOIN 
				  (SELECT R1.Id AS R80,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 80.49 AND R1.Percentage <= 90.49
				  )R80 ON R80.R80 = R.Id AND DM.Id = R80.DivisionId	
		    LEFT JOIN 
				  (SELECT R1.Id AS R70,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 70.49 AND R1.Percentage <= 80.49
				  )R70 ON R70.R70 = R.Id AND DM.Id = R70.DivisionId		
			LEFT JOIN 
				  (SELECT R1.Id AS R60,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 70.49
				  )R60 ON R60.R60 = R.Id AND DM.Id = R60.DivisionId	
		    LEFT JOIN 
				  (SELECT R1.Id AS R50,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49
				  )R50 ON R50.R50 = R.Id AND DM.Id = R50.DivisionId	
			LEFT JOIN 
				  (SELECT R1.Id AS R40,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49
				  )R40 ON R40.R40 = R.Id AND DM.Id = R40.DivisionId	
			LEFT JOIN 
				  (SELECT R1.Id AS R30,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage <= 40.49
				  )R30 ON R30.R30 = R.Id AND DM.Id = R30.DivisionId	
			   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
				AND DM.OrgId = @rOrgId AND DM.IsObsolete = 0
				GROUP BY DM.Id,DM.Code,DM.OrderIndex
				ORDER BY DM.OrderIndex
		END
	ELSE IF (@rTypeId=3)--TypeId = 3 is For Subject Wise Count
		BEGIN
			SELECT SM.Id AS SubjectId,SM.Title AS SubjectName,COUNT(R90.R90) AS '91-100',COUNT(R80.R80) AS '81-90',COUNT(R70.R70) AS '71-80',COUNT(R60.R60) AS '61-70'
			,COUNT(R50.R50) AS '51-60',COUNT(R40.R40) AS '41-50',COUNT(R30.R30) AS 'Below-40' 
			FROM  sAssessment.tResult R 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
			INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
			LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		    LEFT JOIN 
			  (SELECT R.Id As R90,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE  RD.Obtain > 90.49 AND RD.Obtain <=100
			  )R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
		  LEFT JOIN 
			  (SELECT R.Id As R80,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE  RD.Obtain > 80.49 AND RD.Obtain <= 90.49 
			  )R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
		 LEFT JOIN 
			  (SELECT R.Id As R70,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE  RD.Obtain > 70.49 AND RD.Obtain <= 80.49 
			   ) R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
		  LEFT JOIN 
			  (SELECT R.Id As R60,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE  RD.Obtain > 60.49 AND RD.Obtain <= 70.49 
			   )R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
		  LEFT JOIN 
			  (SELECT R.Id As R50,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE  RD.Obtain > 50.49 AND RD.Obtain <= 60.49 
			   )R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
		 LEFT JOIN 
			  (SELECT R.Id As R40,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE  RD.Obtain > 40.49 AND RD.Obtain <= 50.49 
			   )R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
		 LEFT JOIN 
			  (SELECT R.Id As R30,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			   WHERE RD.Obtain <= 40.49
			 )R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
		   
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			 --AND CM.Id = 110100003
			AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0 
			AND (DM.Id = @rDivisionId OR DM.ClassId = @rClassId)
			GROUP BY SM.Id,SM.title,SM.OrderIndex 
			ORDER BY SM.OrderIndex  
		END
		
	ELSE IF (@rTypeId=4)--TypeId = 4 is For Teacher Wise Count
		BEGIN
			SELECT ISNULL(DM.Id,'') AS DivisionId,ISNULL(DM.Code,'') AS ClassDivisionName,ISNULL(SM.Id,'') AS SubjectId,ISNULL(SM.Title,'') AS SubjectName,COUNT(R90.R90) AS '91-100',COUNT(R80.R80) AS '81-90',COUNT(R70.R70) AS '71-80',COUNT(R60.R60) AS '61-70'
			,COUNT(R50.R50) AS '51-60',COUNT(R40.R40) AS '41-50',COUNT(R30.R30) AS 'Below-40',EMP.EmployeeName,EMP.EmployeeId
			FROM  sAssessment.tResult R 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId			
			INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId --AND CS.ClassId = A.classId
			LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			LEFT JOIN sSetup.tDivisionMaster DM ON  DM.ClassId = EM.ClassId
			INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId AND TS.DivisionId=DM.ID AND TS.EmployeeId = @rEmployeeId
			--INNER JOIN  sHrm.tEmployeeMaster EM ON EM.ID = TS.EmployeeId
			INNER JOIN sSetup.tBatchMaster BM ON  BM.Id = EM.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			LEFT JOIN (
			SELECT Id AS EmployeeId,FirstName+' '+ LastName AS EmployeeName FROM sHrm.tEmployeeMaster WHERE ISNULL(IsOtherUser,0) = 0
			)EMP ON EMP.EmployeeId = TS.EmployeeId
			
			LEFT JOIN 
			(SELECT R1.Id AS R90,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				-- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
			)R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
			LEFT JOIN 
			(SELECT R1.Id AS R80,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 80.49 AND R1.Percentage <= 90.49 
			)R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
			LEFT JOIN 
			(SELECT R1.Id AS R70,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 70.49 AND R1.Percentage <= 80.49 
			)R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
			LEFT JOIN 
			(SELECT R1.Id AS R60,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 70.49 
			)R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
			LEFT JOIN 
			(SELECT R1.Id AS R50,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49 
			)R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
			LEFT JOIN 
			(SELECT R1.Id AS R40,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49 
			)R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
			LEFT JOIN 
			(SELECT R1.Id AS R30,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage <= 40.49
			)R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
			WHERE COGBM.Id = @rCommonOrgGroupBatchId
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0
			GROUP BY SM.Id,SM.title,EMP.EmployeeName,EMP.EmployeeId,DM.Code,DM.Id,SM.OrderIndex 
			ORDER BY SM.OrderIndex 
		END
		
		
	ELSE IF(@rTypeId=11)--TypeId = 11  is For Class Wise Detail's
		BEGIN
		
				SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
				SELECT CM.Id AS ClassId,CM.Title AS ClassName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo--,COUNT(RAll.RAll) AS 'RAll'
				FROM  sAssessment.tResult R 
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
					LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.classId AND CM.Id = EM.ClassId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN 
					(SELECT R1.Id AS RAll  FROM sAssessment.tResult R1
	WHERE R1.Percentage > @lFromPercentage AND R1.Percentage <= @lToPercentage			
					)RAll ON RAll.RAll = R.Id
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
				--AND EM.ExamSubGroupId = @rExamSubGroupId
				AND CM.OrgId = @rOrgId AND ((CM.Id = @rClassId)OR(@rClassId=0))
				GROUP BY CM.Id,CM.Title,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
				HAVING COUNT(RAll.RAll) >0

				DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId=21) -- TypeId = 21  is For Division Wise Detail's
		BEGIN
		
		SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
			SELECT DM.Id AS ClassId,DM.Code AS ClassName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
				FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
				(SELECT R1.Id AS RAll,A1.DivisionId AS DivisionId   FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > @lFromPercentage AND R1.Percentage <= @lToPercentage
				--WHERE  R1.Percentage <= 40
				)RAll ON RAll.RAll = R.Id AND DM.Id = RAll.DivisionId	
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			--AND EM.ExamSubGroupId = @rExamSubGroupId 
			 AND ((DM.Id = @rDivisionId)OR(@rDivisionId=0))
			AND DM.OrgId = @rOrgId
			GROUP BY DM.Id,DM.Code,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
			HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId=31) -- TypeId = 31  is For Subject Wise Detail's
		BEGIN
			SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
			SELECT SM.Id AS SubjectId,SM.Title AS SubjectName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
				FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
					(SELECT R1.Id AS RAll,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM 
					sAssessment.tResultDetail RD 
                	INNER Join sAssessment.tResult R1 ON  RD.ResultId = R1.Id
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE RD.Obtain > @lFromPercentage AND RD.Obtain <= @lToPercentage
				)RAll ON RAll.RAll = R.Id AND SM.Id = RAll.SubjectId	AND DM.Id = RAll.DivisionId
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			--AND EM.ExamSubGroupId = @rExamSubGroupId 
			 AND ((SM.Id = @rSubjectId)OR(@rSubjectId=0))
			 AND (DM.ClassId = @rClassId OR DM.Id = @rDivisionId)
			AND DM.OrgId = @rOrgId
			GROUP BY SM.Id,SM.title,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
				HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId=41) -- TypeId = 41  is For Teacher Wise Detail's
		BEGIN
				 SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId


			SELECT ISNULL(STM.Code,'')AS Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
			--,EMP.EmployeeName,EMP.EmployeeId
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id			
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
				LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				LEFT JOIN sSetup.tDivisionMaster DM ON  DM.ClassId = EM.ClassId
				INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId AND TS.DivisionId=DM.ID
				--INNER JOIN  sHrm.tEmployeeMaster EM ON EM.ID = TS.EmployeeId
				INNER JOIN sSetup.tBatchMaster BM ON  BM.Id = EM.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT Id AS EmployeeId,FirstName+' '+ LastName AS EmployeeName FROM sHrm.tEmployeeMaster WHERE ISNULL(IsOtherUser,0) = 0
				)EMP ON EMP.EmployeeId = TS.EmployeeId
				
				LEFT JOIN 
				  (SELECT R1.Id AS RAll,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				  -- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				   INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
				   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > @lFromPercentage AND R1.Percentage <= @lToPercentage
				  )RAll ON RAll.RAll = R.Id AND SM.Id = RAll.SubjectId	AND DM.Id = RAll.DivisionId
		 	
		   
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			--AND EM.ExamSubGroupId = @rExamSubGroupId  
			--AND CM.Id = 110100003
				AND SM.OrgId = @rOrgId
				AND DM.Id = @rDivisionId AND SM.Id = @rSubjectId AND EMP.EmployeeId = @rEmployeeId
				GROUP BY STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
			HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
			
		END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pVaidationImportExamSubGroupMaster]
          
 @rStrXml nvarchar(MAX),
 @rOrgId int
     
          
AS

SET NOCOUNT ON

BEGIN

SET @rStrXml=REPLACE(@rStrXml,'&','AND') 
DECLARE @lInterrorCode INT,	@intDoc INT
DECLARE @lNextNumber BIGINT
DECLARE @1ExistCode nvarchar(max) = ''
DECLARE @1ExistNumber nvarchar(max) = ''
DECLARE @1ExistTitle nvarchar(max) = ''
DECLARE @1ExistOrderIndex nvarchar(max) = ''

EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml
	 
	-- Lead Master Temp Table
	CREATE TABLE #TempExamSubGroupMaster
	(
		[AutoId] int identity,
		[ShortName] nvarchar(20) NULL,
		[Number] smallint NULL,
		[Name] nvarchar(100) NULL,
		[DisplayTitle] nvarchar(100) NULL,
		[ExamGroupId] int NULL, 
		[OrderIndex] smallint NULL, 
		[ExamTypeId] smallint NULL, 
		[IsObsolete] bit null,
		[OrgId] smallint null,
		[CreatedUserId] bigint null, 
		[UpdatedUserId] bigint null, 
		

	)
	
	INSERT INTO #TempExamSubGroupMaster 
	SELECT * FROM OPENXML (@intDoc, '/Table/Import', 1)
	WITH(
			ShortName nvarchar(20) '@ShortName',
			Number smallint '@Number',
			Name nvarchar(100) '@Name',
			DisplayTitle nvarchar(100) '@DisplayTitle',			
			ExamGroupId int '@ExamGroupId',
			OrderIndex smallint '@OrderIndex',
			ExamTypeId int '@ExamTypeId',
			IsObsolete bit '@IsObsolete',
			OrgId smallint '@OrgId',		
			CreatedUserId bigint '@CreatedUserId',
			
			UpdatedUserId bigint '@UpdatedUserId'
		
		)
		DECLARE @lTempExamSubGroupCount int
		SELECT @lTempExamSubGroupCount = COUNT(AutoId) FROM #TempExamSubGroupMaster
		WHILE (@lTempExamSubGroupCount > 0)
		BEGIN
			
			 DECLARE @lTitle nvarchar(200)
			 --DECLARE @lContactPerson nvarchar(100)
			 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			 
			 DECLARE @lCode nvarchar(max)
			 SET @lCode=(SELECT ShortName FROM #TempExamSubGroupMaster WHERE AutoId=@lTempExamSubGroupCount)
			 
			 DECLARE @lNumber nvarchar(max)
			 SET @lNumber=(SELECT Number FROM #TempExamSubGroupMaster WHERE AutoId=@lTempExamSubGroupCount)
			 
			 DECLARE @lOrderIndex nvarchar(max)
			 SET @lOrderIndex=(SELECT OrderIndex FROM #TempExamSubGroupMaster WHERE AutoId=@lTempExamSubGroupCount)
			 
			 DECLARE @lTitle1 nvarchar(max)
			 SET @lTitle1=(SELECT Name FROM #TempExamSubGroupMaster WHERE AutoId=@lTempExamSubGroupCount)
			 
				
			If Exists(select Id from sAssessment.tExamSubGroupMaster where Code=@lCode AND OrgId=@rOrgId)
			 BEGIN			   		
			   SET @1ExistCode = @1ExistCode + @lCode + ','		       			 
		    END 
		    
		    If Exists(select Id from sAssessment.tExamSubGroupMaster where Number=@lNumber AND OrgId=@rOrgId)
			 BEGIN			   		
			   SET @1ExistNumber = @1ExistNumber + @lNumber + ','		       			 
		    END 	
		    
		    If Exists(select Id from sAssessment.tExamSubGroupMaster where Title=@lTitle1 AND OrgId=@rOrgId)
			 BEGIN			   		
			   SET @1ExistTitle = @1ExistTitle + @lTitle1 + ','		       			 
		     END 	
		     
		    If Exists(select Id from sAssessment.tExamSubGroupMaster where OrderIndex=@lOrderIndex AND OrgId=@rOrgId)
			 BEGIN			   		
			   SET @1ExistOrderIndex = @1ExistOrderIndex + @lOrderIndex + ','		       			 
		     END 	
		     		
				
				SET @lTempExamSubGroupCount = @lTempExamSubGroupCount -1		
					
	    END		 
		IF(@1ExistCode is not null AND @1ExistCode!='')
		BEGIN
		  SET @1ExistCode= 'Short Code already exist for ' + @1ExistCode
		  SELECT @1ExistCode AS Result
		  return
		END  
		ELSE IF(@1ExistNumber is not null AND @1ExistNumber!='')
		BEGIN
		  SET @1ExistNumber= 'Number already exist for ' + @1ExistNumber
		  SELECT @1ExistNumber AS Result
		  return
		END  
		ELSE IF(@1ExistTitle is not null AND @1ExistTitle!='')
		BEGIN
		  SET @1ExistTitle= 'Title already exist for ' + @1ExistTitle
		  SELECT @1ExistTitle AS Result
		  return
		END  
		ELSE IF(@1ExistOrderIndex is not null AND @1ExistOrderIndex!='')
		BEGIN
		  SET @1ExistOrderIndex= 'Order Index already exist for ' + @1ExistOrderIndex
		  SELECT @1ExistOrderIndex AS Result
		  return
		END  
		ELSE
		SELECT 1 AS Result 
		
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE OR ALTER PROCEDURE [sAssessment].[pValidateImportCoScholasticIndicator]
     @rOrgId smallint,
	 @rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,  @lCode nvarchar(50),  @lTitle nvarchar(100), @lNumber int=0,      
        @1ReturnCode int = 1, @1DuplicateCode nvarchar(max) = '',@lCCECSId int,@lCoScholasticGroup nvarchar(100),@lCoScholastic nvarchar(100),
        @1ExistNumber nvarchar(max) = '',@1ExistTitle nvarchar(max) = '',@1DuplicateTitle nvarchar(max) = '',
        @1DuplicateNumber nvarchar(max) = '',@1DuplicateOrderIndex nvarchar(max) = '',@1ExistOrderIndex nvarchar(max)='',@lOrderIndex int=0
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
CREATE TABLE #tTable1 
 (
		Id bigint identity,	
		CoScholasticGroup nvarchar(100),
		CoScholastic nvarchar(100), 
		Number int, 
		Indicator nvarchar(100),
		OrderIndex int
  )
  INSERT INTO #tTable1
	(
	  CoScholasticGroup,CoScholastic,Number, Indicator,OrderIndex  
    ) 
   SELECT
        CoScholasticGroup,CoScholastic,Number, Indicator,OrderIndex  
   FROM OPENXML (@intDoc, '/Table/ImportIndicator', 1)
   With
   (
        CoScholasticGroup nvarchar(100) '@CoScholasticGroup',
		CoScholastic nvarchar(100)  '@CoScholastic',	
		Number Int '@Number',		
		Indicator nvarchar(100) '@Indicator',
		OrderIndex int '@OrderIndex'
   ) 
EXEC sp_xml_removedocument @intDoc
    IF EXISTS(SELECT 1 fROM #tTable1 WHERE CoScholasticGroup IS NULL OR CoScholasticGroup COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'CoScholasticGroup Should not be empty' AS ValidateCode
END
 ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE CoScholastic IS NULL OR CoScholastic COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	 SELECT 'CoScholastic Should not be empty' AS ValidateCode
END
ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Indicator IS NULL OR Indicator COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	 SELECT 'Indicator Should not be empty' AS ValidateCode
END
ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number='' OR Number Is NUll )
BEGIN
	SELECT 'Number Should not be empty' AS ValidateCode
END
ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE OrderIndex = '' OR OrderIndex Is NUll )
BEGIN
	SELECT 'OrderIndex Should not be empty' AS ValidateCode
END
ELSE
BEGIN	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 
BEGIN
	SELECT @lCoScholasticGroup = CoScholasticGroup,@lCoScholastic=CoScholastic,@lTitle = Indicator,@lNumber = Number,@lOrderIndex = OrderIndex
	FROM #tTable1 WHERE Id = @lCount 
	IF NOT Exists (	SELECT 1 from sAssessment.tCCECSMaster CM INNER join  sAssessment.tCCECSGroupMaster  CG on CG.Id=CM.CCECAGroupId WHERE CM.OrgId=@rOrgId AND CM.Title=@lCoScholastic AND CG.Title=@lCoScholasticGroup)
      BEGIN
   SET    @lCCECSId=0
		 SELECT 'Enter proper value for CoScholasticGroup/CoScholastic : ' + @lCoScholasticGroup+'/'+@lCoScholastic  AS ValidateCode
    END	
    ELSE
    BEGIN
     	  SELECT @lCCECSId=CM.Id from sAssessment.tCCECSMaster CM INNER join  sAssessment.tCCECSGroupMaster  CG on CG.Id=CM.CCECAGroupId WHERE CM.OrgId=@rOrgId AND CM.Title=@lCoScholastic AND CG.Title=@lCoScholasticGroup
    END  
    IF Exists ((select 1 from sAssessment.tCCECSIndicatorMaster where OrgId=@rOrgId AND CCECSId=@lCCECSId AND Title COLLATE DATABASE_DEFAULT = @lTitle COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistTitle = @1ExistTitle + @lTitle + ','
    END	  
    IF Exists ((select 1 from sAssessment.tCCECSIndicatorMaster where OrgId=@rOrgId AND CCECSId=@lCCECSId AND convert(varchar,Number) COLLATE DATABASE_DEFAULT = convert(varchar,@lNumber) COLLATE DATABASE_DEFAULT ))         
    BEGIN
		SET @1ExistNumber = @1ExistNumber + convert(varchar,@lNumber )+ ','
    END	 
      IF Exists ((select 1 from sAssessment.tCCECSIndicatorMaster where OrgId=@rOrgId AND CCECSId=@lCCECSId AND convert(varchar,OrderIndex)  COLLATE DATABASE_DEFAULT = convert(varchar,@lOrderIndex) COLLATE DATABASE_DEFAULT ))               
    BEGIN
		SET @1ExistOrderIndex = @1ExistOrderIndex + convert(varchar,@lOrderIndex )+ ','
    END	 
	SET @lCount = @lCount - 1	
	END
SELECT @1DuplicateTitle=COALESCE(@1DuplicateTitle ,'') + Indicator + ',' FROM #tTable1 GROUP BY Indicator,CoScholasticGroup,CoScholastic  HAVING ( COUNT(Indicator) > 1 )	
SELECT @1DuplicateNumber=COALESCE(@1DuplicateNumber ,'') + CONVERT(varchar,Number) + ',' FROM #tTable1 GROUP BY Number,CoScholasticGroup,CoScholastic HAVING ( COUNT(Number) > 1 )	
SELECT @1DuplicateOrderIndex=COALESCE(@1DuplicateOrderIndex ,'') +CONVERT(varchar, OrderIndex) + ',' FROM #tTable1 GROUP BY OrderIndex,CoScholasticGroup,CoScholastic HAVING ( COUNT(OrderIndex) > 1 )	


	IF(@1DuplicateTitle IS NOT NULL AND @1DuplicateTitle != '')
	BEGIN
		SET @1DuplicateTitle = 'Duplicate Indicator : ' + @1DuplicateTitle
	END
	IF(@1DuplicateNumber IS NOT NULL AND @1DuplicateNumber != '')
	BEGIN
		SET @1DuplicateNumber = 'Duplicate Number : ' + @1DuplicateNumber
	END
	IF(@1DuplicateOrderIndex IS NOT NULL AND @1DuplicateOrderIndex != '')
	BEGIN
		SET @1DuplicateOrderIndex = 'Duplicate OrderIndex : ' + @1DuplicateOrderIndex
	END
	 IF (@1ExistTitle IS NOT NULL AND @1ExistTitle != '' )
	BEGIN
		SET @1ExistTitle = 'Exist Indicator : ' + @1ExistTitle
	END
	 IF (@1Existnumber IS NOT NULL AND @1Existnumber != '' )
	BEGIN
		SET @1Existnumber = 'Exist Number : ' + @1Existnumber
	END
	 IF (@1ExistOrderIndex IS NOT NULL AND @1ExistOrderIndex != '' )
	BEGIN
		SET @1ExistOrderIndex = 'Exist OrderIndex : ' + @1ExistOrderIndex
	END
	SELECT isnull(@1ExistTitle,'') +isnull(@1Existnumber,'')+ isnull(@1ExistOrderIndex ,'')+isnull(@1DuplicateTitle,'')+isnull(@1DuplicateNumber,'')+isnull(@1DuplicateOrderIndex,'')  AS ValidateCode 
 
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pValidateImportSubjectActivity]
     @rOrgId smallint,
	 @rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT, @lCode nvarchar(100),  @lTitle nvarchar(200), @lNumber int,@lClass nvarchar(100), 
        @lSubCode nvarchar(100),  @lSubTitle nvarchar(200), @lSubNumber int,@lSubClass nvarchar(100),@1SubOrderIndex int,
	    @lSubject nvarchar(100), @1OrderIndex int,  @1ReturnCode int = 1,@lGradeSet nvarchar(100),@1SubDuplicateCode nvarchar(max) = '',
        @1ExistCode nvarchar(max) = '',@1DuplicateCode nvarchar(max) = '', @1ExistOrderIndex nvarchar(max) = '',
        @1DuplicateTitle nvarchar(max) = '', @1DuplicateOrderIndex nvarchar(max) = '', @1SubDuplicateTitle nvarchar(max) = '', @1SubDuplicateOrderIndex nvarchar(max) = '',
        @1ExistNumber nvarchar(max) = '',@1ExistTitle nvarchar(max) = '',@lClassSubjectId int,@lOrderIndex int,@1DuplicateNumber nvarchar(max)='',@SubDuplicateNumber nvarchar(max)='',
        @1SubExistNumber nvarchar(max) = '',@1SubExistTitle nvarchar(max) = '', @1SubExistCode nvarchar(max) = '',@1SubExistOrderIndex nvarchar(max) = '',@lSubjectActivityId int=0
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
CREATE TABLE #tTable1 
 (
		Id bigint identity,
		Code nvarchar(100), 
		Name nvarchar(200),
		Number int, 
	    OrderIndex int,
		GradeSet nvarchar(100),
	    Class Nvarchar(100),
	    Subject Nvarchar(100),
	    SubNumber int, 
		SubCode nvarchar(100), 
		SubName nvarchar(200),
		SubOrderIndex int
  )
  INSERT INTO #tTable1(Code,Name,Number,OrderIndex,GradeSet,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex)
    
   SELECT
          Code,Name,Number,OrderIndex,GradeSet,Class,Subject,SubNumber,SubCode,SubName,SubOrderIndex
   FROM OPENXML (@intDoc, '/Table/ImportSubjectActivity', 1)
   With
   (
        Code nvarchar(100) '@Code',			
		Name nvarchar(200) '@Name',			
		Number int '@Number',			
		GradeSet nvarchar(100) '@GradeSet',			
		OrderIndex int '@OrderIndex',
		Class nvarchar(100) '@Class',
		Subject  nvarchar(100) '@Subject',
		SubNumber int '@SubNumber',
		SubCode nvarchar(100) '@SubCode',			
		SubName nvarchar(200) '@SubName',
		SubOrderIndex int '@SubOrderIndex'
   )     
   
EXEC sp_xml_removedocument @intDoc
			
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Code Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Name IS NULL OR Name COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Name Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Class Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Subject IS NULL OR Subject COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Subject Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number ='')
BEGIN
	SELECT 'Number Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE OrderIndex IS NULL OR OrderIndex ='')
BEGIN
	SELECT 'OrderIndex Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubName IS NULL OR SubName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Sub Name Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubCode IS NULL OR SubCode COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Sub Code Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubOrderIndex IS NULL OR SubOrderIndex ='')
BEGIN
	SELECT 'Sub OrderIndex Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubNumber IS NULL OR SubNumber ='')
BEGIN
	SELECT 'Sub Number Should not be empty' AS ValidateCode
END
ELSE
BEGIN	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 
BEGIN
	SELECT @lCode = Code,@lTitle=Name,@lNumber=Number,@lOrderIndex=OrderIndex,@lSubject=Subject,@lClass=Class,@lGradeSet=GradeSet,
	@lSubCode =SubCode,@lSubTitle=SubName,@1SubOrderIndex=SubOrderIndex,@lSubNumber=SubNumber
	FROM #tTable1 WHERE Id = @lCount  
IF NOT EXists(SELECT  1 FROM sSetup.vClassSubject  VS
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id=VS.ClassId where VS.IsObsolete=0 AND CM.Title=@lClass  AND Vs.SubjectName=@lSubject AND CM.OrgId=@rOrgId)
 BEGIN
     SELECT 'Enter proper value for Class  or Subject  :' + @lClass + '/' + @lSubject AS ValidateCode
    END
    ELSE
    BEGIN
    SET @lClassSubjectId=0
    SELECT @lClassSubjectId= ClassSubjectId FROM sSetup.vClassSubject  VS
	INNER JOIN  sSetup.tClassMaster CM ON CM.Id=VS.ClassId where VS.IsObsolete=0 AND CM.Title=@lClass  AND Vs.SubjectName=@lSubject AND CM.OrgId=@rOrgId 
    END
	 IF NOT EXists( SELECT 1 FROM sAssessment.tGradeSetMaster WHERE  OrgId=@rOrgId  AND Title=@lGradeSet )
  BEGIN
     SELECT 'Enter proper value for Gradeset : ' + @lGradeSet  AS ValidateCode
    END
 IF NOT Exists (select 1  FROM  sAssessment.tCCESubjectActivityMaster where OrgId=@rOrgId AND Code=@lCode AND ClassSubjectId = @lClassSubjectId )
 BEGIN
 SET @lSubjectActivityId=0
 END
 ELSE
 BEGIN
   SELECT @lSubjectActivityId=Id FROM   sAssessment.tCCESubjectActivityMaster   where OrgId=@rOrgId AND Code=@lCode
  IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND SubjectActivityId = @lSubjectActivityId AND Code COLLATE DATABASE_DEFAULT = @lSubCode COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistCode = @1SubExistCode + @lSubCode + ','
    END	  
 IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND SubjectActivityId = @lSubjectActivityId AND Title COLLATE DATABASE_DEFAULT = @lSubTitle COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistTitle = @1SubExistTitle + @lSubTitle + ','
    END	  
  IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND OrderIndex =Convert(varchar,@1SubOrderIndex) AND SubjectActivityId = @lSubjectActivityId AND Convert(varchar,OrderIndex) COLLATE DATABASE_DEFAULT = Convert(varchar,@1SubOrderIndex) COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1SubExistOrderIndex= @1SubExistOrderIndex + Convert(varchar,@1SubOrderIndex )+ ','
    END	  
 IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityMaster where OrgId=@rOrgId AND Number =Convert(varchar,@lSubNumber) AND SubjectActivityId = @lSubjectActivityId AND Convert(varchar,Number) COLLATE DATABASE_DEFAULT = Convert(varchar,@lSubNumber) COLLATE DATABASE_DEFAULT))               
    BEGIN
		SET @1SubExistNumber= @1SubExistNumber + Convert(varchar,@lSubNumber) + ','
    END	  
  END
  IF Exists ((select 1 from sAssessment.tCCESubjectActivityMaster where OrgId=@rOrgId AND OrderIndex =Convert(varchar,@lOrderIndex) AND Convert(varchar,OrderIndex) COLLATE DATABASE_DEFAULT = Convert(varchar,@lOrderIndex) COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistOrderIndex= @1ExistOrderIndex + Convert(varchar,@lOrderIndex )+ ','
    END	
	SET @lCount = @lCount - 1	
 END
 

	SELECT @1SubDuplicateCode=COALESCE(@1SubDuplicateCode ,'') + SubCode + ',' FROM #tTable1 GROUP BY SubCode,Class,subject,Code,Name HAVING ( COUNT(SubCode) > 1 )	
    SELECT @1SubDuplicateTitle=COALESCE(@1SubDuplicateTitle ,'') + SubName + ',' FROM #tTable1 GROUP BY SubName,Class,subject,Code,Name HAVING ( COUNT(SubName) > 1 )	
  	SELECT @1SubDuplicateOrderIndex=COALESCE(@1SubDuplicateOrderIndex,'')  + convert(varchar,SubOrderIndex) + ',' FROM #tTable1 GROUP BY SubOrderIndex,Class,subject,Code,Name HAVING ( COUNT(SubOrderIndex) > 1 )	
  	SELECT @SubDuplicateNumber=COALESCE(@SubDuplicateNumber,'')  + convert(varchar,SubNumber) + ',' FROM #tTable1 GROUP BY SubNumber,Class,subject,Code,Name HAVING ( COUNT(SubNumber) > 1 )
	SELECT @1DuplicateOrderIndex=COALESCE(@1DuplicateOrderIndex,'')  + convert(varchar,OrderIndex) + ',' FROM #tTable1 GROUP BY OrderIndex,Class,subject,Code,Name HAVING ( COUNT(OrderIndex) > 1 )		
	IF(@1SubDuplicateCode IS NOT NULL AND @1SubDuplicateCode != '')
	BEGIN
		SET @1SubDuplicateCode = 'Duplicate Sub Code : ' + @1SubDuplicateCode
	END
	IF(@1SubDuplicateTitle IS NOT NULL AND @1SubDuplicateTitle != '')
	BEGIN
	SET @1SubDuplicateTitle = 'Duplicate Sub Name : ' + @1SubDuplicateTitle
	END
	IF(@1SubDuplicateOrderIndex IS  NOT NULL AND @1SubDuplicateOrderIndex != '')
	BEGIN
	SET @1SubDuplicateOrderIndex = 'Duplicate Sub OrderIndex : ' + @1SubDuplicateOrderIndex
	END
	IF(@SubDuplicateNumber IS NOT NULL AND @SubDuplicateNumber != '')
	BEGIN
	SET @SubDuplicateNumber = 'Duplicate Sub Number : ' + @SubDuplicateNumber
	END
	 IF (@1SubExistCode IS NOT NULL AND @1SubExistCode != '' )
	BEGIN
		SET @1SubExistCode = 'Exist Sub Code : ' + @1SubExistCode
	END
	ELSE IF (@1SubExistCode IS NOT NULL AND @1SubExistCode = '' )
	BEGIN
		SET @1SubExistCode=''
	END
	 IF (@1SubExistTitle IS NOT NULL AND @1SubExistTitle != '' )
	BEGIN
		SET @1SubExistTitle = 'Exist Sub Title : ' + @1SubExistTitle
	END
	
	 IF (@1SubExistOrderIndex IS NOT NULL  AND @1SubExistOrderIndex != '' )
	BEGIN
		SET @1SubExistOrderIndex = 'Exist Sub OrderIndex : ' + @1SubExistOrderIndex
	END
	
	 IF (@1ExistOrderIndex IS NOT NULL  AND @1ExistOrderIndex != '' )
	BEGIN
		SET @1ExistOrderIndex = 'Exist OrderIndex : ' + @1ExistOrderIndex
	END

  	 IF (@1SubExistNumber IS NOT NULL AND @1SubExistNumber != '' )
	BEGIN
		SET @1SubExistNumber = 'Exist Sub Number : ' + @1SubExistNumber
	END
	END
	Select Isnull(@1SubDuplicateCode,'')+Isnull(@1SubDuplicateTitle,'')+Isnull(@SubDuplicateNumber,'')+Isnull(@1SubDuplicateOrderIndex,'')+
	Isnull(@1SubExistCode,'') +Isnull(@1SubExistTitle,'')+Isnull(@1SubExistNumber,'')+Isnull(@1SubExistOrderIndex,'') +Isnull(@1DuplicateOrderIndex,'')+Isnull(@1ExistOrderIndex,'')
	  AS ValidateCode
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssessment].[pValidateImportSubjectActivityIndicator]
     @rOrgId smallint,
	 @rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT, @lActivity nvarchar(200), @lNumber int, 
	    @1OrderIndex int, @lGrade nvarchar(100),@lGradeSetId int=0,
        @1ExistOrderIndex nvarchar(max) = '',@lSubActivity nvarchar(200),@lSubject nvarchar(100),
        @1DuplicateTitle nvarchar(max) = '', @1DuplicateOrderIndex nvarchar(max) = '',@lIndicator nvarchar(100),@lclass nvarchar(100),
        @1ExistNumber nvarchar(max) = '',@1ExistTitle nvarchar(max) = '',@lSubActivityId int=0,@lOrderIndex int,@1DuplicateNumber nvarchar(max)=''
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
  CREATE TABLE #tTable1 
 (
	    Id bigint identity,Class nvarchar(100),Subject nvarchar(100),
		Activity nvarchar(200), SubActivity nvarchar(200),Number nvarchar(max), 
		Indicator nvarchar(100),Grade nvarchar(100), OrderIndex  nvarchar(max)
  )
  INSERT INTO #tTable1(Class,Subject,Activity,SubActivity, Number,Indicator,Grade, OrderIndex)
   SELECT
          Class,Subject,Activity,SubActivity, Number,Indicator,Grade, OrderIndex
   FROM OPENXML (@intDoc, '/Table/ImportSubjectActivityIndicator', 1)
   With
   (
        Class nvarchar(100) '@Class',	
	    Subject nvarchar(100) '@Subject',	
		Activity nvarchar(200) '@Activity',			
		SubActivity nvarchar(200) '@SubActivity',			
		Number nvarchar(max) '@Number',			
		Indicator nvarchar(100) '@Indicator',
		Grade nvarchar(100) '@Grade',
		OrderIndex nvarchar(max) '@OrderIndex'
		
   )   
EXEC sp_xml_removedocument @intDoc
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Class Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Subject IS NULL OR Subject COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Subject Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE Activity='' OR Activity COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Activity Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE SubActivity IS NULL OR SubActivity COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'SubActivity Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number='' OR Number Is NUll )
BEGIN
	SELECT 'Number Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Indicator IS NULL OR Indicator COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Indicator Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Grade IS NULL OR Grade COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Grade Should not be empty' AS ValidateCode
END
 IF EXISTS(SELECT 1 fROM #tTable1 WHERE OrderIndex=''  OR OrderIndex Is NUll)
BEGIN
	SELECT 'OrderIndex Should not be empty' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1  Where isnumeric(Number)<>1 )
BEGIN
	SELECT 'Number Must Be Numeric ' AS ValidateCode
END
IF EXISTS(SELECT 1 fROM #tTable1  Where isnumeric(OrderIndex)<>1 )
BEGIN
	SELECT 'OrderIndex Must Be Numeric ' AS ValidateCode
END
ELSE
BEGIN	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 
BEGIN
	SELECT 	@lActivity = Activity,@lSubActivity = SubActivity,@lNumber = Number,@lOrderIndex = OrderIndex,
		@lIndicator=Indicator,@lGrade=Grade,@lClass=Class,@lSubject=Subject
	FROM #tTable1 WHERE Id = @lCount  
IF NOT EXists( SELECT  1 from sAssessment.tCCESubjectSubActivityMaster SA INNER JOIN  sAssessment.tCCESubjectActivityMaster AM ON SA.SubjectActivityId=AM.Id
    INNER JOIN sSetup.tClassSubject  CS On AM.ClassSubjectId=Cs.Id INNER JOIN sSetup.tClassMaster CM ON CM.Id=Cs.ClassId INNER JOIN  sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
    WHERE  
    SA.OrgId=@rOrgId AND SA.Title=@lSubActivity AND AM.Title=@lActivity AND SM.Title=@lSubject AND CM.Title=@lClass AND CS.OrgId=@rOrgId)
  BEGIN
     SELECT 'Enter proper value for Activity  or SubActivity  for class subject  : '+ @lclass +''  + @lSubject+ ' '+ @lActivity + '-' + @lSubActivity AS ValidateCode 
    END
    ELSE
    BEGIN
    SET @lSubActivityId=0 
    SET @lGradeSetId=0
    SELECT @lSubActivityId=SA.Id,@lGradeSetId= AM.GradeSetId from sAssessment.tCCESubjectSubActivityMaster SA INNER JOIN  sAssessment.tCCESubjectActivityMaster AM ON SA.SubjectActivityId=AM.Id
    INNER JOIN sSetup.tClassSubject  CS On AM.ClassSubjectId=CS.Id INNER JOIN sSetup.tClassMaster CM ON CM.Id=Cs.ClassId INNER JOIN  sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
    WHERE  SA.OrgId=@rOrgId AND SA.Title=@lSubActivity AND AM.Title=@lActivity AND SM.Title=@lSubject AND CM.Title=@lClass AND CS.OrgId=@rOrgId

  END
	 IF NOT EXists(SELECT 1 FROM sAssessment.tGradeSetDetail WHERE GradeCode=@lGrade  AND GradeSetId=@lGradeSetId )
  BEGIN
     SELECT 'Enter proper value for Gradeset : ' + @lgrade  AS ValidateCode
    END
  IF Exists ((select 1 from sAssessment.tCCESubjectSubActivityIndicatorMaster where Title=@lIndicator AND OrgId=@rOrgId AND CCESubjectSubActivityId = @lSubActivityId  AND Title COLLATE DATABASE_DEFAULT = @lIndicator COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistTitle = @1ExistTitle + @lclass+'-'+@lSubject+'/' +@lIndicator + ','
    END	 
	SET @lCount = @lCount - 1	
 END
	 SELECT @1DuplicateTitle=COALESCE(@1DuplicateTitle,'') +Class+'-'+Subject+'/' + + Indicator + ',' FROM #tTable1  GROUP BY Indicator,Class,Subject,Activity,SubActivity  HAVING ( COUNT(Indicator) > 1 )
	 SELECT @1DuplicateNumber=COALESCE(@1DuplicateNumber,'') +Class+'-'+Subject+'/' + Convert(varchar,Number) + ',' FROM #tTable1   GROUP BY Number,Class,Subject,Activity,SubActivity HAVING ( COUNT(Number) > 1 )
	 SELECT @1DuplicateOrderIndex=COALESCE(@1DuplicateOrderIndex,'') +Class+'-'+Subject+'/' + Convert(Varchar,OrderIndex) + ',' FROM #tTable1 GROUP BY OrderIndex,Class,Subject,Activity,SubActivity  HAVING ( COUNT(OrderIndex) > 1 )	
	IF(@1DuplicateTitle IS NOt NULL AND @1DuplicateTitle != '')
	BEGIN
		SET @1DuplicateTitle = 'Duplicate Indicator : ' + @1DuplicateTitle
	END
  IF(@1DuplicateNumber IS NOt  NULL AND @1DuplicateNumber != '')
	BEGIN
		SET @1DuplicateNumber = 'Duplicate Number : ' + Convert(varchar,@1DuplicateNumber)
		
	END
 IF(@1DuplicateOrderIndex IS  NOt  NULL AND @1DuplicateOrderIndex != '')
	BEGIN
		SET @1DuplicateOrderIndex = 'Duplicate OrderIndex : ' + @1DuplicateOrderIndex
	END
   IF(@1ExistTitle IS NOT NULL AND @1ExistTitle!= '')
	BEGIN
		SET @1ExistTitle = 'Exists  indicator : ' + @1ExistTitle
	END
	END
SELECT @1ExistTitle+''+isnull(@1DuplicateTitle,'') +''+isnull(@1DuplicateNumber,'')+''+isnull(@1DuplicateOrderIndex,'') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE OR ALTER PROCEDURE [sAssessment].[pViewResultGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rStatusId smallint,
	 @rFromObtain decimal(12,5)=0,
	 @rToObtain decimal(12,5)=0,
	 @rResultStatus nvarchar(10)='',
	 @rOrderBy int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX),@sqlcondition as nvarchar(max)
select @cols = STUFF((SELECT  ',' + QUOTENAME(Ed.Id) 
					  From sAssessment.tExamMaster E
					  INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					  AND ClassId = @rClassId AND E.Id =  @rExamId Order By Ed.DisplayOrder
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'),1,1,'')
set @sqlcondition = CASE WHEN @rOrderBy=0 THEN 'Order by CODE' 
                         WHEN @rOrderBy=1 THEN 'Order by RankNumber' 
                         WHEN @rOrderBy=2 THEN 'Order by Percentage' 
                         WHEN @rOrderBy=3 THEN 'Order by TotalObtain'
                         ELSE 'Order by RollNo' END
                         

--set @sqlcondition = ' Order by CASE WHEN ' + convert(nvarchar(10),@rOrderBy) + ' = ''0'' THEN  convert(nvarchar(100),CODE) WHEN ' + convert(nvarchar(10),@rOrderBy) + ' = 1 THEN RankNumber WHEN ' + convert(nvarchar(10),@rOrderBy) + ' = 2 THEN Percentage  WHEN ' + convert(nvarchar(10),@rOrderBy) + ' = 3 THEN TotalObtain WHEN ' + convert(nvarchar(10),@rOrderBy) + ' = 4 THEN  RollNo END ASC'        
        
set @query = 'SELECT AcademicId,ResultId,0 AS ResultDetailId, ExamId,Name,RollNo,CODE,
TotalMarks,TotalObtain,ResultStatus,ResultGrade,RankNumber,Percentage,Percentile,
IsRankNo,IsGrade,IsPercentage,IsPercentile,
 ' + @cols + '
FROM
(
Select convert(nvarchar(15),ISNULL(RD.Obtain,0)) AS Obtain,ED.Id AS ExamDetailId,A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.CODE,ISNULL(R.Id,0) AS ResultId,
ISNULL(R.TotalMarks,0) AS TotalMarks,ISNULL(R.TotalObtain,0) AS TotalObtain,ISNULL(R.ResultStatus,'''') AS ResultStatus,
ISNULL(R.ResultGrade,'''') AS ResultGrade,ISNULL(R.RankNumber,0) AS RankNumber,ISNULL(R.Percentage,0) AS Percentage,ISNULL(R.Percentile,0) AS Percentile,
IsRankNo,IsGrade,IsPercentage,IsPercentile
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id AND A.BatchId=EM.BatchId
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
WHERE ((A.StatusId ='+convert(nvarchar(10),@rStatusId)+') OR ('+convert(nvarchar(10),@rStatusId)+'=0)	) AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId = ' + convert(nvarchar(15),@rExamId) + ' AND ((R.TotalObtain>='+convert(nvarchar(15),@rFromObtain)+') OR ('+convert(nvarchar(15),@rFromObtain)+'=0)) AND ((R.TotalObtain<='+convert(nvarchar(15),@rToObtain)+') OR ('+convert(nvarchar(15),@rToObtain)+'=0)) 
And ((R.ResultStatus ='''+convert(nvarchar(10),@rResultStatus)+''') OR ('''+convert(nvarchar(10),@rResultStatus)+'''=''''))
) MAIN
PIVOT
(
	MAX(Obtain)
FOR ExamDetailId IN (' + @cols + ')
)pvt 
'
set @query = @query + @sqlcondition

print (@query)
execute(@query)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssessment].[pWrongExamMarkEntryGet]
    @rWrongExamId int
AS
BEGIN
	SELECT
		SA.Id As AcademicId,
		SM.Id AS StudentId,
		SM.Code As Code,
		SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
		CM.Title AS Class,
		V.SubjectName AS Subject,
		RD.Obtain As ObtainMarks,
		R.ExamId,
		RD.Id As ResultDetailId,
		RD.ResultId As ResultId,
		RD.ExamdetailId As ExamdetailId,
		RD.IsPresent,
		ISNULL(RD.Remark,'') AS Remark,
		RD.SubjectGrade  AS SubjectGrade,
		RD.SubjectGradePoint As SubjectGradePoint,
		RD.Percentile,
		RD.GraceMark,
		RD.KrupaMark,
		ISNULL(RD.AbsentRemark,'') AS AbsentRemark

	FROM 
	sAssessment.tResultDetail RD 
	INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id
	INNER JOIN sStudent.tAcademic SA ON SA.Id = R.AcademicId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id 
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  	
	
	WHERE R.ExamId=@rWrongExamId AND RD.ExamDetailId NOT IN(SELECT Id from sAssessment.tExamDetail WHERE ExamId = @rWrongExamId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[AssetMasterCodeItemGet]
    @rOrgId int,
	@rId [int] = 0,
	@rCode [nvarchar](10),  
	@rTitle [nvarchar](100),  
	@rIsObsolete [bit] = 0,
	@rIsWildCardSearch [bit] = 1,
	@rStoreLocationId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF @rIsObsolete = 0
	BEGIN
		IF @rIsWildCardSearch = 1
			BEGIN
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END
	END
	
	SELECT 	 Id AS AssetId,
			 Code AS Code,
			 Title AS AssetName,
			 OrgId,
			 StoreLocationId,
			 AssetCode AS AssetCode
			 
	   FROM	 
		sAssetManagement.tAssetMaster 
	 WHERE
		((Id=@rId) OR (@rId=0))
	  AND ((OrgId=@rOrgId) OR (@rOrgId=0))
	  AND ((StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	  AND ((AssetCode LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	  AND (((Title LIKE @rTitle) AND @rIsObsolete = 0) OR (@rTitle = '' AND @rIsObsolete = 0) OR ((Title = @rTitle ) AND @rIsObsolete = 1))
	 --((SIM.Id = @rId) OR (@rId = 0)) 
		--AND	((SIM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
		--AND	(((SIM.Title LIKE @rTitle) AND @rIsAbsoluteTitle = 0) OR (@rTitle = '' AND @rIsAbsoluteTitle = 0) OR ((SIM.Title = @rTitle ) AND @rIsAbsoluteTitle = 1))
		--AND SIM.OrgId = @rOrgId
		--AND ((SIM.LocationId = @rLocationId) OR (@rLocationId = 0)) 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[AssetMasterItemGet]
    @rOrgId int,
	@rId [int] = 0,
	@rCode [nvarchar](10),  
	@rTitle [nvarchar](100),  
	@rIsObsolete [bit] = 0,
	@rIsWildCardSearch [bit] = 1,
	@rStoreLocationId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF @rIsObsolete = 0
	BEGIN
		IF @rIsWildCardSearch = 1
			BEGIN
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END
	END
	
	SELECT 	 Id AS AssetId,
			 Code AS AssetCode,
			 Title AS AssetName,
			 OrgId,
			 StoreLocationId
			 
	   FROM	 
		sAssetManagement.tAssetMaster 
	 WHERE
		((Id=@rId) OR (@rId=0))
	  AND ((OrgId=@rOrgId) OR (@rOrgId=0))
	  AND ((StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	  AND ((Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	  AND (((Title LIKE @rTitle) AND @rIsObsolete = 0) OR (@rTitle = '' AND @rIsObsolete = 0) OR ((Title = @rTitle ) AND @rIsObsolete = 1))
	 --((SIM.Id = @rId) OR (@rId = 0)) 
		--AND	((SIM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
		--AND	(((SIM.Title LIKE @rTitle) AND @rIsAbsoluteTitle = 0) OR (@rTitle = '' AND @rIsAbsoluteTitle = 0) OR ((SIM.Title = @rTitle ) AND @rIsAbsoluteTitle = 1))
		--AND SIM.OrgId = @rOrgId
		--AND ((SIM.LocationId = @rLocationId) OR (@rLocationId = 0)) 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAdjustmentAdd]
	@rOrgId [int],
	@rNumber [nvarchar](20) OUTPUT,
	@rCreatedUserId [bigint],
	@rStoreLocationId int,
	@rAssetAdjustmentDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssetManagement.tAssetAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output

	--DECLARE @loNextNumber Nvarchar(20)
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 98,@rStoreLocationId = @rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
	
	--IF (@loNextNumber IS NULL)
	--BEGIN
	--	RAISERROR('5000', 15, 106)
	--	RETURN
	--END
			
--SELECT @rNumber = ISNULL(max(Number),0) FROM sAssetManagement.tAssetAdjustment WHERE StoreLocationId = @rStoreLocationId
--SET @rNumber = @rNumber + 1
		DECLARE @lPrefixSetupId bigint 
		DECLARE @lPrefix Nvarchar(10)  
		DECLARE @loNextId bigint  
		DECLARE @lNumberLength TinyInt  
		DECLARE @rNextNumber [nvarchar](100) 

		SELECT @lPrefixSetupId = PS.Id,   
			   @lPrefix = Prefix,   
			   @lNumberLength = ISNULL(NumberLength, 7)  
		FROM sCommon.tPrefixSetup PS 
		WHERE PrefixFunctionalityId = 98  
		AND PS.IsObsolete = 0 
		AND Ps.OrgId =  @rOrgId
		AND PS.StoreLocationId = @rStoreLocationId
		AND EffectiveDate = (SELECT MAX(EffectiveDate)  
		FROM sCommon.tPrefixSetup  
		WHERE PrefixFunctionalityId = 98 
		AND OrgId =  @rOrgId 
		AND IsObsolete = 0  
		AND StoreLocationId=@rStoreLocationId
		AND EffectiveDate <= sCommon.fGetDate()
		)  

		EXECUTE sCommon.pPrefixSetupCurrentNumberModify @rId = @lPrefixSetupId, @rNextNumber = @loNextId OUTPUT  
   
		--SELECT @lPrefix, @lNumberLength, @loNextId  
		SET @rNextNumber = sCommon.fNumberStringGet(@lPrefix, @lNumberLength, @loNextId)

		SET @rNumber = ISNULL(@rNextNumber, '-300')
		
		IF @rNumber = '-300'
		BEGIN
			SELECT -300 AS Result, '' AS Number, 0 AS Id 
			RETURN
		END

	INSERT INTO sAssetManagement.tAssetAdjustment
		(
			Id,
			Number,			
			CreatedUserId,
			CreatedDateTime,
			OrgId,
			StoreLocationId
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,			
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rStoreLocationId
		)
		
	SET @rNumber = @rNumber
	EXEC sAssetManagement.pAssetAdjustmentDetailAdd @rOrgId, @lNextNumber, @rAssetAdjustmentDetailXml
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAdjustmentDetailAdd]
	@rOrgId [int],
	@rAssetAdjustmentId [int],
	@rAssetAdjustmentDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @loIdoc INT
	DECLARE @lAssetAdjustmentDetailCurrentId INT
	DECLARE @lCount INT 
		
	SET @lCount = 0	

	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rAssetAdjustmentDetailXml
	EXEC sCommon.pTableRowIdGet  @rOrgId, 'sAssetManagement.tAssetAdjustmentDetail', 1, 1, 1,@outNextNumber = @lAssetAdjustmentDetailCurrentId output
	
	INSERT INTO sAssetManagement.tAssetAdjustmentDetail
		(
			Id,
			AssetAdjustmentId,
			AssetAuditDetailId,
			Remark,
			StatusId,
			ReasonId
		)
	SELECT  
		@lAssetAdjustmentDetailCurrentId + ROW_NUMBER() OVER(ORDER BY AssetAuditDetailId) AS Id, 
		@rAssetAdjustmentId,
		AssetAuditDetailId,
		Remark,
		StatusId,
		ReasonId 
	FROM OPENXML (@loIdoc, '/AssetAdjustment/AssetAdjustmentDetail', 1)
		WITH ( 
				AssetAuditDetailId INT, 
				StatusId INT,
				Remark NVARCHAR(100), 
				ReasonId INT
			  ) 
		
		UPDATE sAssetManagement.tAssetMaster
		SET UsageStatusId = AAD.StatusId		
		FROM OPENXML (@loIdoc, '/AssetAdjustment/AssetAdjustmentDetail', 1)
		WITH ( 
				AssetAuditDetailId INT, 
				StatusId INT,
				Remark NVARCHAR(100), 
				ReasonId INT
			  ) AAD		
		INNER JOIN 	sAssetManagement.tAssetAuditDetail AAUD
		ON AAD.AssetAuditDetailId =  AAUD.Id
		INNER JOIN  sAssetManagement.tAssetMaster AM
		ON AM.Id = AAUD.AssetId
				
		
		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/AssetAdjustment/AssetAdjustmentDetail', 1)
				 WITH ( AssetId INT)
		
		
		SET @lAssetAdjustmentDetailCurrentId  = @lCount + @lAssetAdjustmentDetailCurrentId 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgId, @rTableTitle = 'sAssetManagement.tAssetAdjustmentDetail', @rCurrentNumber = @lAssetAdjustmentDetailCurrentId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAdjustmentDetailGet]
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			AssetAdjustmentId,
			AssetAuditDetailId,
			Remark,
			ReasonId
	   FROM sAssetManagement.tAssetAdjustmentDetail
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAdjustmentDetailModify]
	@rId [int],
	@rAssetAdjustmentId [int],
	@rAssetAuditDetailId [int],
	@rRemark [nvarchar](300),
	@rReasonId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAssetManagement.tAssetAdjustmentDetail
		SET 
			AssetAdjustmentId = @rAssetAdjustmentId,
			AssetAuditDetailId = @rAssetAuditDetailId,
			Remark = @rRemark,
			ReasonId = @rReasonId
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAdjustmentGet]
	@rOrgId [int],
	@rNumber [nvarchar](100) = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  SELECT 
			ASSTADJ.AssetAuditDetailId AS AssetAuditDetailId,
			LM.Title AS StoreLocation,
			SIM.Code AS AssetTag,
			SIM.Title AS [Description],
			SIM.ModelNumber AS ModelNumber,
			SM.Title AS OldStatus,
			ASSTADJ.StatusId AS StatusId,
			ASSTADJ.ReasonId AS ReasonId,
			ASSTADJ.Remark AS Remark,
			CM.Title AS Category,
			CM.Id AS CategoryId,
			LM.Id AS LocationId,
			SIM.DepartmentId,
			LM.Title AS LocationCode,
			ODM.Title As Department,
			AA.Number AS AuditNumber,
			SIM.AssetCode AS NewAssetCode		
			
	FROM sAssetManagement.tAssetAdjustmentDetail ASSTADJ	
	INNER JOIN sAssetManagement.tAssetAdjustment ASSTA
	ON 	ASSTADJ.AssetAdjustmentId = ASSTA.Id
	INNER JOIN sAssetManagement.tAssetAuditDetail AAD
	ON ASSTADJ.AssetAuditDetailId = AAD.Id
	INNER JOIN sAssetManagement.tAssetAudit AA
	ON  AAD.AssetAuditId = AA.Id
	INNER JOIN sFixedAsset.vExtLocationMaster LM
	ON  LM.Id = AA.LocationId
	INNER JOIN sCommon.tStatusMaster SM
	ON	SM.Id = AA.StatusId
	INNER JOIN sAssetManagement.tAssetMaster SIM
	ON 	SIM.ID = AAD.AssetId
	INNER JOIN sFixedAsset.tCategoryMaster CM
		ON CM.Id = SIM.CategoryId
	INNER JOIN sSetup.tDepartmentMaster ODM
	ON ODM.Id = SIM.DepartmentID
	--INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
	--	ON AD.DepartmentId = SIM.DepartmentID
	WHERE
		ASSTA.Number = @rNumber
    AND ((ASSTA.OrgId = @rOrgId) OR @rOrgId=0)
    
	ORDER BY SIM.Code DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAdjustmentModify]
	@rId [int],
	@rNumber [nvarchar](20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAssetManagement.tAssetAdjustment
		SET 
			Number = @rNumber
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAdjustmentSearchGet]
	@rOrgId [int],
	@rFromDate [datetime],
	@rToDate [datetime],
	@rLocationId [int] = 0,
	@rCategoryId [int] = 0,
	@rCode [nvarchar](30) = '',
	@rTitle [nvarchar](30) = '',
	@rStoreLocationId int,
	@rDepartmentId int,
	@rOrgGroupId smallint=0 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
      
    IF(@rLocationId = -1)
    SET @rLocationId = 0
    
    IF(@rCategoryId = -1)
    SET @rCategoryId = 0
    
    IF(@rDepartmentId = -1)
    SET @rDepartmentId = 0
    
    SELECT 
                  AAD.Id AS AssetAuditDetailId,
                  LM.Title AS StoreLocation,
                  SIM.Code AS AssetTag,
                  SIM.Title AS [Description],
                  SIM.ModelNumber AS ModelNumber,
                  SM.Title AS OldStatus,
                  CM.Title AS Category,
                  ODM.Title As Department,
                  AA.Number AS AuditNumber,
				  SIM.AssetCode AS NewAssetCode
                  
      FROM sAssetManagement.tAssetAuditDetail AAD     
      INNER JOIN sAssetManagement.tAssetAudit AA
      ON  AAD.AssetAuditId = AA.Id 
      INNER JOIN sFixedAsset.vExtLocationMaster LM
      ON  LM.Id = AA.LocationId
      INNER JOIN sCommon.tStatusMaster SM
      ON    SM.Id = AA.StatusId
      INNER JOIN sAssetManagement.tAssetMaster SIM
      ON    SIM.ID = AAD.AssetId AND SIM.LocationId=LM.Id
      INNER JOIN sFixedAsset.tCategoryMaster CM
      ON CM.Id = SIM.CategoryId
      	INNER JOIN sSetup.tDepartmentMaster ODM
	ON ODM.Id = SIM.DepartmentID
   --   INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
	  --ON AD.DepartmentId = SIM.DepartmentID
      WHERE
            (CAST(AA.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE) AND CAST(AA.CreatedDateTime AS DATE) <= CAST((@rToDate + 1) AS DATE))
            AND ((SIM.Code = @rCode) OR (@rCode = '')) 
            AND ((SIM.Title = @rTitle) OR (@rTitle = '')) 
            AND ((SIM.LocationId = @rLocationId) OR (@rLocationId = 0)) 
            AND ((SIM.CategoryId = @rCategoryId) OR (@rCategoryId = 0))
            AND (AAD.Id NOT IN ( SELECT AssetAuditDetailId FROM sAssetManagement.tAssetAdjustmentDetail))
          
      --      AND (AAD.AssetCheck = 0)
      --      AND (AAD.Id = (SELECT MAX(TAAD.ID) FROM sAssetManagement.tAssetAuditDetail TAAD WHERE AAD.AssetId = TAAD.AssetId))  
			   --AND ((AA.OrgId = @rOrgId) OR @rOrgId=0)
			   
            AND ((AA.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
            AND ((SIM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
            AND ((SIM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
            
            ORDER BY SIM.Code DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAuditAdd]
	@rNumber [nvarchar](20) OUTPUT,
	@rLocationId [int],
	--@rRemark [nvarchar](300),
	@rStatusId [smallint],
	@rCreatedUserId [bigint],
	@rAssetAuditDetailXml [nvarchar](max),
	@rOrgId int,
	@rStoreLocationId int,
	@rAuditedBy nvarchar(50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sAssetManagement.tAssetAudit', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	--DECLARE @loNextNumber Nvarchar(20)
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId,@rPrefixFunctionalityId = 90,@rStoreLocationId = @rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT

	--IF (@loNextNumber IS NULL)
	--	BEGIN
	--		RAISERROR('5000', 15, 106)
	--		RETURN
	--	END
	
	SELECT @rNumber = ISNULL(max(Number),0) FROM sAssetManagement.tAssetAudit WHERE StoreLocationId = @rStoreLocationId
	SET @rNumber = @rNumber + 1
	
	
	INSERT INTO sAssetManagement.tAssetAudit
		(
			Id,
			Number,
			LocationId,
			AuditedBy,
			--Remark,
			StatusId,
			CreatedUserId,
			CreatedDateTime,
			OrgId,
			StoreLocationId
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rLocationId,
			@rAuditedBy,
			--@rRemark,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rStoreLocationId
		)
		
		SET @rNumber = @rNumber
		EXEC sAssetManagement.pAssetAuditDetailAdd @lNextNumber, @rAssetAuditDetailXml,@rOrgId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAuditDetailAdd]
	@rAssetAuditId [int],
	@rAssetAuditDetailXml [nvarchar](max),
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @loIdoc INT
	DECLARE @lStockAuditDetailCurrentId INT
	DECLARE @lCount INT 
		
	SET @lCount = 0

	

	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rAssetAuditDetailXml
	EXEC sCommon.pTableRowIdGet  @rOrgId,'sAssetManagement.tAssetAuditDetail', 1, 1, 1,@outNextNumber = @lStockAuditDetailCurrentId output

	INSERT INTO sAssetManagement.tAssetAuditDetail
		(
			Id,
			AssetAuditId,
			AssetId,
			AssetCheck
		)
	SELECT  
		@lStockAuditDetailCurrentId + ROW_NUMBER() OVER(ORDER BY AssetId) AS Id, 
		@rAssetAuditId,
		AssetId,
		AssetCheck
	FROM OPENXML (@loIdoc, '/AssetAudit/AssetAuditDetail', 1)
		WITH ( 
				AssetId INT, 
				AssetCheck BIT
			  ) 
		
		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/AssetAudit/AssetAuditDetail', 1)
				 WITH ( AssetId INT)
		
		
		SET @lStockAuditDetailCurrentId  = @lCount + @lStockAuditDetailCurrentId 
		
		EXECUTE sCommon.pTableRowIdModify  @rOrgId,@rTableTitle = 'sAssetManagement.tAssetAuditDetail', @rCurrentNumber = @lStockAuditDetailCurrentId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAuditDetailGet]
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			AssetAuditId,
			AssetId,
			AssetCheck
	   FROM sAssetManagement.tAssetAuditDetail
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAuditDetailListGet]
	@rNumber [nvarchar](20) = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;

BEGIN
      
      SELECT      AA.Id,
                  AA.Number,
                  AA.LocationId,
                  AA.CreatedUserId,
                  AAD.AssetAuditId,
                  AAD.AssetId,
                  AAD.AssetCheck, 
                  LM.Title AS StoreLocation,
                  SIM.Title AS AssetName,
                  SIM.Code AS AssetCode,
                  SIM.UsageStatusId AS StatusId,
                  SIM.CategoryId,
                  CM.Title AS Category,
                  ODM.Id AS DepartmentId,
                  LM.Title AS LocationTitle,
				  ODM.Title AS DepartmentTitle,
			      STAT.Title	AS StatusTitle,
			      AA.AuditedBy,
			      SIM.ModelNumber	
                  
                  
                  
      FROM sAssetManagement.tAssetAudit AA
      INNER JOIN 
            sAssetManagement.tAssetAuditDetail AAD
      ON
            AAD.AssetAuditId = AA.Id
      INNER JOIN
            sFixedAsset.vExtLocationMaster LM
      ON
            LM.Id = AA.LocationId
      INNER JOIN
          sCommon.tStatusMaster SM
      ON    SM.Id = AA.StatusId
      INNER JOIN sAssetManagement.tAssetMaster SIM
      ON SIM.ID = AAD.AssetId AND SIM.StoreLocationId=@rStoreLocationId
      --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
      --ON AD.DepartmentId = SIM.DepartmentID
       	INNER JOIN sSetup.tDepartmentMaster ODM
	ON ODM.Id = SIM.DepartmentID
      INNER JOIN sFixedAsset.tCategoryMaster CM
      ON CM.Id = SIM.CategoryId
      INNER JOIN  sCommon.tStatusMaster STAT
      ON STAT.ID =  SIM.UsageStatusId 
      
      WHERE AA.Number = @rNumber
      AND AA.StoreLocationId=@rStoreLocationId
      ORDER BY SIM.Title DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAuditDetailModify]
	@rId [int],
	@rAssetAuditId [int],
	@rAssetId [int],
	@rAssetCheck [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAssetManagement.tAssetAuditDetail
		SET 
			AssetAuditId = @rAssetAuditId,
			AssetId = @rAssetId,
			AssetCheck = @rAssetCheck
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAuditGet]
	@rNumber [nvarchar](100) = 0
	--@rOrgId int,
	--@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			ASSTADJ.AssetAuditDetailId AS AssetAuditDetailId,
			LM.Title AS StoreLocation,
			SIM.Code AS AssetTag,
			SIM.Title AS [Description],
			SIM.ModelNumber AS ModelNumber,
			SM.Title AS OldStatus,
			ASSTADJ.StatusId AS StatusId,
			ASSTADJ.Remark AS Remark,
			AA.AuditedBy			
			
	FROM sAssetManagement.tAssetAdjustmentDetail ASSTADJ	
	INNER JOIN sAssetManagement.tAssetAdjustment ASSTA
	ON 	ASSTADJ.AssetAdjustmentId = ASSTA.Id
	INNER JOIN sAssetManagement.tAssetAuditDetail AAD
	ON ASSTADJ.AssetAuditDetailId = AAD.Id
	INNER JOIN sAssetManagement.tAssetAudit AA
	ON  AAD.AssetAuditId = AA.Id
	INNER JOIN sFixedAsset.vExtLocationMaster LM
	ON  LM.Id = AA.LocationId
	INNER JOIN sAssetManagement.tAssetMaster SIM
	ON 	SIM.ID = AAD.AssetId
	INNER JOIN sCommon.tStatusMaster SM
	ON	SM.Id = SIM.UsageStatusId	
	INNER JOIN sFixedAsset.vExtCategoryMaster CM
		ON CM.Id = SIM.CategoryId
	WHERE
		ASSTA.Number = @rNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAuditModify]
	@rId [int],
	@rNumber [nvarchar](20),
	@rLocationId [smallint],
	@rRemark [nvarchar](300),
	@rStatusId [smallint],
	@rAuditedBy nvarchar(50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAssetManagement.tAssetAudit
		SET 
			AuditedBy=@rAuditedBy,
			Number = @rNumber,
			LocationId = @rLocationId,
			Remark = @rRemark,
			StatusId = @rStatusId
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetAuditSearchGet]
	@rLocationId [int],
	@rAssetCategoryId [int] = 0,
	@rStatusId [int],
	@rCode [nvarchar](30) = '',
	@rTitle [nvarchar](30) = '',
	@rDepartmentId [int],
	@rOrgId int,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    SELECT 
			AM.Id,
			AM.Code, 
			AM.Title,
			CM.Title AS Category,
			LOC.Title AS LocationTitle,
			ODM.Title AS DepartmentTitle,
			STAT.Title	AS StatusTitle,
			AM.OrgId,
			AM.StoreLocationId,
			AM.UsageStatusId AS AssetStatusId ,
			AM.ModelNumber
			
	FROM sAssetManagement.tAssetMaster AM
		INNER JOIN sFixedAsset.tCategoryMaster CM
		ON CM.Id = AM.CategoryId
	 	INNER JOIN sSetup.tDepartmentMaster ODM
	   ON ODM.Id = AM.DepartmentID
        INNER JOIN  sCommon.tStatusMaster STAT
        ON STAT.ID =  AM.UsageStatusId 
        INNER JOIN  sFixedAsset.VextLocationMaster LOC
        ON LOC.ID = AM.LocationId
	WHERE 
		((LocationId = @rLocationId)  AND (AM.DepartmentID = @rDepartmentId))
	AND ((LocationId = @rLocationId)  AND (ODM.Id = @rDepartmentId) AND ((CategoryId  =  @rAssetCategoryId) OR (@rAssetCategoryId = 0)))
	AND ((UsageStatusId = @rStatusId) OR (@rStatusId=0))
	AND ((AM.Code = @rCode) OR (@rCode = '')) 
	AND ((AM.Title = @rTitle) OR (@rTitle = '')) 
	AND ((AM.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((AM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	ORDER BY AM.Title DESC
	
END


/****** Object:  StoredProcedure [sProcurement].[pRptStockItemListing]    Script Date: 07/09/2013 16:22:58 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetCheckAdd]
	 
        @rId int,
        @rAssetId int,
		@rNumber  nvarchar(20),
		@rCheckedDate datetime,
		@rCheckStatusId smallint,
		@rRemark nvarchar(300),
		@rOrgGroupId smallint,
		@rCreatedUserId bigint,
		@rStoreLocationId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber int
	--IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAssetManagement.tAssetCheck', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAssetManagement.tAssetCheck
		(
			Id,
			AssetId,
			Number,
			CheckedDate,
			CheckStatusId,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			StoreLocationId
		)
	VALUES
		(
			@lNextNumber,
			@rAssetId,
			@rNumber,
			@rCheckedDate,
			@rCheckStatusId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId,
			@rStoreLocationId
		)
		SELECT 1 AS Result
	END	 

--ELSE
	 --BEGIN
	 --SET @lNextNumber = @rId
	 --   UPDATE  sAssetManagement.tAssetCheck
	 --   SET
		--	AssetId=@rAssetId,
		--	Number=@rNumber,
		--	CheckedDate=@rCheckedDate,
		--	Remark=@rRemark,
		--	@rCreatedUserId=@rCreatedUserId,
		--	CreatedDateTime=sCommon.fGetDate()
	 --     WHERE Id = @rId
	 --     AND StoreLocationId=@rStoreLocationId
	 --     SELECT @lNextNumber AS Result
	 --END  
	 BEGIN
	 UPDATE  sAssetManagement.tAssetMaster
	    SET
			CheckedLastDate=@rCheckedDate,	
			CheckedByUserId=@rCreatedUserId,	
			CheckedStatusId=@rCheckStatusId,
			CheckedRemark=@rRemark
	      WHERE Id = @rAssetId AND OrgGroupId=@rOrgGroupId AND  StoreLocationId=@rStoreLocationId
	 END	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetCheckGet]
   @rOrgGroupId smallint,
   --@rStoreLocationId int=0,
   @rAssetName nvarchar(100)='',
   @rFromDate DateTime='',
   @rToDate DateTime='',
   @rCheckStatusId smallint='',
   @rId int=0
   
AS
BEGIN
SET @rAssetName= sCommon.fSearchStringGet(@rAssetName)
	SELECT 
       AC.Id,
	   AC.AssetId,
	   AM.Title AS AssetName ,
	   AC.Remark,
	   ST.Title AS CheckStatus,
	   LM.Title AS Location,
	   --SM.Title AS SubLocation,
	   AC.CheckedDate,
	   U.DisplayTitle AS CheckedBy,
	   AC.Number,
	   AC.StoreLocationId,
	  ISNULL(AC.CheckStatusId,0) AS CheckStatusId
	 
	FROM
	sAssetManagement.tAssetCheck AC 
	INNER JOIN sAssetManagement.tAssetMaster AM ON  AM.Id=AC.AssetId
    --INNER JOIN sAssetManagement.tAssetUser AU ON AM.Id = AU.AssetId  AND AU.AssignedUserId = @rUserId
    INNER JOIN sCommon.tStatusMaster ST ON ST.Id=AC.CheckStatusId
    INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id=AM.LocationId
    --INNER JOIN  sIp.tStoreLocationMaster  SM ON SM.Id= AC.StoreLocationId
    INNER JOIN sSecurity.tUser U ON U.Id=AC.CreatedUserId
	  WHERE 
	    AC.OrgGroupId = @rOrgGroupId 
	    AND  AM.IsCheckRequired=1
	   AND ((AC.Id=@rId) OR (@rId=0))
	  --AND ((AC.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	  AND ((AC.CheckStatusId=@rCheckStatusId) OR (@rCheckStatusId=0))
	  AND ((AC.CheckedDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
	  AND ((AC.CheckedDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AM.Title Like @rAssetName) OR (ISNULL(@rAssetName,'')=''))
	  order by AC.CheckedDate desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetCheckListGet]
@rOrgGroupId smallint,
--@rStoreLocationId int,
@rCheckedDate DateTime,
@rUserId bigint
AS
BEGIN
	SELECT 
     -- ISnull(AC.Id,0)AS Id,
	   AM.Id AS AssetId,
	   AM.Title AS AssetName ,
	   ISNUll(AM.CheckedStatusId ,0)AS CheckStatusId,
	   LM.Title AS Location,
	   --SM.Title AS SubLocation,
	   AM.CheckedLastDate,
	   AM.CheckList,
	   AM.StoreLocationId ,
	   AM.CheckFrequencyId
	FROM sAssetManagement.tAssetMaster AM 
    INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId  AND AU.InchargeUserId = @rUserId
    INNER JOIN sFixedAsset.tLocationMaster  LM ON  LM.Id=AM.LocationId
    --INNER JOIN  sIp.tStoreLocationMaster  SM ON SM.Id= AM .StoreLocationId
	  WHERE 
	  AM.OrgGroupId = @rOrgGroupId 
	  AND ISNULL(AM.IsCheckRequired,0) = 1 
	---- AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,getdate()) OR AM.CheckFrequencyId=2
	  AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,@rCheckedDate) OR AM.CheckFrequencyId=2
    ---- AND AM.CheckedLastDate <=  DATEADD(dd,7,getdate()) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,getdate()))
      AND AM.CheckedLastDate <=  DATEADD(dd,7,@rCheckedDate) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,@rCheckedDate))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetCustomFieldAdd]
		 
	@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsObsolete int =0
	--@rDataTypeId int = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	

DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
 
IF(@rId = 0)	
BEGIN
    IF NOT EXISTS(SELECT 2 FROM sAssetManagement.tAssetCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup)
	BEGIN
	      DECLARE @lNextNumber int
	      EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssetManagement.tAssetCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		  Print @lNextNumber
	      INSERT INTO sAssetManagement.tAssetCustomFieldMaster
	      (
		    Id
		   ,FieldTitle
		   ,FieldTypeId
		   ,FieldList
		   ,IsFieldMandatory
		   ,FieldGroup
		   ,FieldOrder
		   ,CreatedUserId
		   ,CreatedDateTime
		   ,OrgGroupId
		   ,IsObsolete
		   --,DataId
	      )
	     VALUES
	     (
		   @lNextNumber
		  ,@rFieldTitle
		  ,@rFieldTypeId
		  ,@rFieldList
		  ,@rIsFieldMandatory
		  ,@rFieldGroup
		  ,@rFieldOrder
		  ,@rCreatedUserId
		  ,@rCreatedDateTime
		  ,@lOrgGroupId
		  ,@rIsObsolete
		  --,@rDataTypeId
	     )
     END
	 ELSE
	 SELECT -101 As RESULT
END
	 	 
ELSE
BEGIN
	SET @lNextNumber = @rId

	
	
		UPDATE sAssetManagement.tAssetCustomFieldMaster
		SET 
		FieldTitle = @rFieldTitle
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,IsObsolete=@rIsObsolete
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
		,UpdatedUserId=@rUpdatedUserId
		,UpdatedDateTime=@rUpdatedDateTime
		--,DataId = @rDataTypeId
		WHERE Id = @rId 
	
	
END  
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetCustomFieldDataModify]	 
	--@rCategoryId int,
	@rXML nvarchar(max),
	--@rSubCategoryField nvarchar(100),
	@rOrgId int = 0,
	@rCustomFieldId nvarchar(100)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT


EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,AssetId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
	
	insert into ListofData(Id,AssetId,SubCategory,CustomFieldId,UpdatedUserId,IsExist)
		select 0,E.AssetId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),@rCustomFieldId,E.UpdatedUserId,0
		from
		(
				SELECT AssetId,SubCategory,CustomFieldId,UpdatedUserId FROM
				OPENXML (@loDoc, '/Asset/Asset', 2)
				WITH (						
						AssetId BIGINT,
						--AutoId int,
						SubCategory nvarchar(150),
                        CustomFieldId int,
						UpdatedUserId bigint
						)	
						)E 	
		UPDATE LD SET IsExist=1 
		   FROM sAssetManagement.tAssetCustomFieldData AC
		      LEFT JOIN ListofData LD ON AC.AssetId=LD.AssetId 
		      AND  EXISTS (SELECT AssetCustomFieldId FROM sAssetManagement.tAssetCustomFieldData WHERE AssetId=LD.AssetId AND AssetCustomFieldId = LD.CustomFieldId) 
		
		
		
		set @sql='INSERT INTO sAssetManagement.tAssetCustomFieldData
					(AssetId,AssetCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.AssetId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=0'
					
		--print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sAssetManagement.tAssetCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAssetManagement.tAssetCustomFieldData AC 
					INNER JOIN ListofData LD ON AC.AssetId=LD.AssetId AND AC.AssetCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	   
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetCustomFieldDelete]

@rId int,
@rOrgId smallint=0,
@rOrgGroupId int=0
AS
BEGIN
 	 
	 IF NOT EXISTS(Select 1 from sAssetManagement.tAssetCustomFieldData ACF 
	          INNER JOIN sAssetManagement.tAssetMaster AM ON AM.Id=ACF.AssetId
	          INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AM.OrgId 
	        WHERE ACF.AssetCustomFieldId=@rId AND StatusId=1 AND OM.OrgGroupId=@rOrgGroupId
	           AND (ACF.FieldData <> '0' AND ACF.FieldData<>'' AND ACF.FieldData IS NOT NULL))
	 BEGIN
        
        DELETE ACF FROM sAssetManagement.tAssetCustomFieldData ACF 
           INNER JOIN sAssetManagement.tAssetMaster AM ON AM.Id=ACF.AssetId
	       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AM.OrgId 
        WHERE ACF.AssetCustomFieldId=@rId AND StatusId=1 AND OM.OrgGroupId=@rOrgGroupId
         
		DELETE	FROM sAssetManagement.tAssetCustomFieldMaster WHERE Id=@rId 
		SELECT 1 AS RESULT
	  END 

	  ELSE

	    SELECT -101 As RESULT

 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetCustomFieldDetailsGet]	 
	@rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		Id,
	    FieldTitle,	
		FieldGroup,	
		FieldTypeId,
		FieldList,
		IsFieldMandatory,
		IsObsolete,
		FieldOrder
		--ISNULL(DataId,0) DataId
	FROM 
		 sAssetManagement.tAssetCustomFieldMaster

	WHERE 
		OrgGroupId = @rOrgGroupId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetCustomFieldsUpdateGet]
	 		
	 @rOrgId int,
	 @rDepartmentId int,
	 @rLocationId int,
	 @rSubCategoryId int
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=FieldTypeId FROM sAssetManagement.tAssetCustomFieldMaster WHERE Id=@rSubCategoryId
		
		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		  ----0038705 : By Krunal K Patel -- Added FieldTypeId=5 for Date.
		 --IF(@lDataTypeId=3)   --For Free Text and Numeric
		 --BEGIN
	SET @Sql = 'select * from (
				Select Row_Number() OVER (PARTITION BY AM.Id ORDER BY CASE WHEN ACF.FieldTypeId IS NOT NULL THEN ACF.FieldTypeId END Desc) as RowNumber
				,AM.Id AS AssetId, AM.Title,CM.Title AS Category, AM.Code AS AssetCode,
				CASE WHEN ACF.FieldTypeId=3 OR ACF.FieldTypeId=4 THEN
				ISNULL(AC.FieldData,'''') 
				WHEN ACF.FieldTypeId=2 THEN
				ISNULL(AC.FieldData,''0'')
				WHEN ACF.FieldTypeId=1 THEN
				ISNULL(AC.FieldData,''False'')
				WHEN ACF.FieldTypeId=5 THEN
				ISNULL(AC.FieldData,'''') 				
				END AS SubCategory
			FROM 
		         sAssetManagement.tAssetMaster AM
				 INNER JOIN sFixedAsset.tCategoryMaster CM ON AM.CategoryId = CM.Id
		         LEFT JOIN sAssetManagement.tAssetCustomFieldData AC ON AC.AssetId=AM.Id
		         LEFT JOIN sAssetManagement.tAssetCustomFieldMaster ACF ON ACF.Id=AC.AssetCustomFieldId AND ACF.FieldTypeId='''+@lDataTypeId+'''  AND ACF.Id= '''+CAST(@rSubCategoryId AS nvarchar(15))+''' AND ACF.IsObsolete=0 
		         
		    Where AM.OrgId='+CAST(@rOrgId AS nvarchar(15))
				+'AND (AM.DepartmentId='+CAST(@rDepartmentId AS nvarchar(15))+ 'OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
				AND (AM.LocationId='+CAST(@rLocationId AS nvarchar(15))+ 'OR '+CAST(@rLocationId AS nvarchar(15))+'=0))AS a where RowNumber =1'     
		 			
		  print @Sql		
		   		
			EXECUTE  sp_executesql @Sql		
	   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetDataModify]	 
	@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


EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Name')
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Name','Title')
	END
	
	IF(	@rSubCategoryField = 'AssetCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'AssetCategory','Category') + 'Id'
	END
	
	IF(	@rSubCategoryField = 'AlertPeriod' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'AlertPeriod','MaintenanceAlertPeriod')
	END
	
	IF(	@rSubCategoryField = 'CheckFrequency' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'CheckFrequency','CheckFrequencyId') 
	END
	
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,AssetId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);

		insert into ListofData
		select 0,E.AssetId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT AssetId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Asset/Asset', 2)
				WITH (
						AssetId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE AssetId NOT IN(SELECT Id FROM sAssetManagement.tAssetMaster) 
		--Select * from ListofData
		set @sql='INSERT INTO sAssetManagement.tAssetMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.AssetId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sAssetManagement.tAssetMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAssetManagement.tAssetMaster AM 
					INNER JOIN ListofData LD ON AM.Id=LD.AssetId AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetDataUpdateGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(500),
	 @rOrgId int,
     @rDepartmentId int,
	 @rLocationId int,
	 @rIsBlank bit
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		IF(@rSubCategory = 'Name')
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Name','Title')
		END
		IF(@rSubCategory = 'AssetCategory')
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'AssetCategory','Category') + 'Id'
		END
		IF(@rSubCategory = 'AlertPeriod')
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'AlertPeriod','MaintenanceAlertPeriod')
		END
		IF(@rSubCategory = 'CheckFrequency')
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'CheckFrequency','CheckFrequencyId')
		END

		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		 
		 SET @Sql =  
						'Select AM.Id AS AssetId, AM.Title,CM.Title AS Category, AM.AssetCode,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(AM.'+@rSubCategory+','''') 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(AM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(AM.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(AM.'+@rSubCategory+',''0001/01/01'') 
						END AS SubCategory
							FROM 
							sAssetManagement.tAssetMaster AM
							INNER JOIN sFixedAsset.tCategoryMaster CM ON AM.CategoryId = CM.Id
							Where AM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (AM.DepartmentId='+CAST(@rDepartmentId AS nvarchar(15))+ 'OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (AM.LocationId='+CAST(@rLocationId AS nvarchar(15))+ 'OR '+CAST(@rLocationId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(AM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(AM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(AM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(AM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							 '
	   Print @Sql
	   if(@Sql1 IS NOT NULL)		
			EXECUTE  sp_executesql @Sql1
	   else
			EXECUTE  sp_executesql @Sql
	   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetInchargeUserAdd]
	@rAssetId int,	
	@rInchargeUserId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	 If Exists(select 1 from sAssetManagement.tAssetInchargeUser where AssetId=@rAssetId AND InchargeUserId=@rInchargeUserId)
			BEGIN
			select -102 as Result
			RETURN
			END
			BEGIN TRANSACTION	
	    
INSERT INTO sAssetManagement.tAssetInchargeUser (
                            AssetId,
							InchargeUserId
							)	
							VALUES
							(@rAssetId,
							@rInchargeUserId
							)
							SELECT 1 As Result	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetInchargeUserEmailListGet]
          
           @rAssetTitles bigint,	 	 
	 	   @rSubject nvarchar(100),
	 	   @rTemplate nvarchar(max),
           @rOrgGroupId int--,
           --@rAssetId int=0,
           --@rUserId bigint=0,
           --@rSourceTypeId smallint=0,
           --@rAssetCode nvarchar(50)='',
           --@rAssetName nvarchar(100)=''
           --@rStoreLocationId int
AS
SET NOCOUNT ON

BEGIN
--SET @rAssetCode=sCommon.fSearchStringGet(@rAssetCode)
--SET @rAssetName=sCommon.fSearchStringGet(@rAssetName)
DECLARE @Emails VARCHAR(8000) 
SELECT 
 
	 --ISNULL(AI.InchargeUserId,0) AS InchargeUserId,
  --   ISNULL(U.DisplayTitle,'') AS InchargeUser,
  --   ISNULL(AM.Code,'') AS AssetCode,
  --   ISNULL(AM.Title,'') AS AssetName,
  --   ISNULL(AI.AssetId,0)AS AssetId,U.SourceId,U.SourceTypeId
  --@Emails = COALESCE(@Emails + ', ', '') + CompanyEmail 
   ISNULL(EM.CompanyEmail,'') AS EmailId,
   replace(@rTemplate,'[AssetName]',@rAssetTitles) 
				            AS MsgText,@rSubject AS Subject    		    
     
FROM  sAssetManagement.tAssetInchargeUser AI 
	  INNER JOIN  sSecurity.tUser  U  ON  AI.InchargeUserId = U.Id   
	  INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id=u.OrgId
	  INNER JOIN sAssetManagement.tAssetMaster AM ON AM.Id=AI.AssetId
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON U.SourceId=EM.EmployeeId 
	 WHERE OM.OrgGroupId = 1101 AND SourceId IS NOT NULL AND SourceId<>0
	 
	 
    --  WHERE
    --  (( AI.AssetId = @rAssetId) OR (@rAssetId=0))      
    --  AND   OM.OrgGroupId = @rOrgGroupId
    --  AND ((AI.InchargeUserId=@rUserId) OR (@rUserId=0))
    -- AND ((AM.Code like @rAssetCode) OR (ISNULL(@rAssetCode,'')=''))
    -- AND ((AM.Title like @rAssetName) OR (ISNULL(@rAssetName,'')=''))
    -- --AND ((U.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
    ----AND AM.StoreLocationId=@rStoreLocationId
    -- AND U.IsObsolete = 0
    --select @Emails
    
    

END



--select *from sAssetManagement.tAssetInchargeUser where InchargeUserId=1001000000121

--select *from sSecurity.tUser where Id=1001000000121

--update sSecurity.tUser set 

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetInchargeUserGet]
          
           @rOrgGroupId int,
           @rAssetId int=0,
           @rUserId bigint=0,
           @rSourceTypeId smallint=0,
           @rAssetCode nvarchar(50)='',
           @rAssetName nvarchar(100)=''
           --@rStoreLocationId int
AS
SET NOCOUNT ON

BEGIN
--SET @rAssetCode=sCommon.fSearchStringGet(@rAssetCode)
SET @rAssetName=sCommon.fSearchStringGet(@rAssetName)
SELECT 
 
ISNULL(AI.InchargeUserId,0) AS InchargeUserId,
     isnull(U.DisplayTitle + ' - '+ U.LoginTitle,'') AS InchargeUser,
     ISNULL(AM.Code,'') AS AssetCode,
     ISNULL(AM.Title,'') AS AssetName,
     ISNULL(AI.AssetId,0)AS AssetId
     
FROM  sAssetManagement.tAssetInchargeUser AI 
	  INNER JOIN  sSecurity.tUser  U  ON  AI.InchargeUserId = U.Id   
	  INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id=u.OrgId
	  INNER JOIN sAssetManagement.tAssetMaster AM ON AM.Id=AI.AssetId
      WHERE
      (( AI.AssetId = @rAssetId) OR (@rAssetId=0))      
      AND   OM.OrgGroupId = @rOrgGroupId
      AND ((AI.InchargeUserId=@rUserId) OR (@rUserId=0))
     AND ((AM.Code like @rAssetCode) OR (ISNULL(@rAssetCode,'')=''))
     AND ((AM.Title like @rAssetName) OR (ISNULL(@rAssetName,'')=''))
     AND ((U.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
    --AND AM.StoreLocationId=@rStoreLocationId
     AND U.IsObsolete = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetMaintenanceDetailGet]
	@rOrgId int,
	@rNumber nvarchar(20) = '',
	@rAssetId int = 0,
	@rFromMaintenanceDate Date ='',
	@rToMaintenanceDate Date = '',
	@rId int = 0,
	@rStatusId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;

BEGIN
	
	SELECT	AMT.Id,
			AMT.Number,
			AMT.AssetId,
			AMT.CreatedUserId,
			AMT.MaintenenceBy,
			AMT.MaintenenceCost,
			--CONVERT(varchar,AMT.MaintenenceDate, 105) as MaintenenceDate, 
			AMT.MaintenenceDate,
			AMT.MaintenenceReason,
			--CONVERT(varchar,AMT.NextMaintenenceDate, 105) as NextMaintenenceDate,
			AMT.NextMaintenenceDate,
			LM.Title AS LocationName,
			LM.Id,
			AM.StatusId,
			AM.Title AS AssetName,
			AM.Code AS AssetCode,
			AM.CategoryId AS AssetCategoryId,
			LM.Id AS LocationId,
			AMT.DocumentNo,
			AMT.DocumentDate,
			AD.Title AS DepartmentName,
			SM.Title AS StatusName,
			CM.Title AS CategoryName,
			AM.ModelNumber AS ModelNumber,
			ISNULL(AM.AssetCode,'') AS NewAssetCode
			
			
	FROM sAssetManagement.tMaintenence AMT
	INNER JOIN 
		sAssetManagement.tAssetMaster AM
	ON
		AMT.AssetId = AM.Id
	INNER JOIN
		sFixedAsset.vExtLocationMaster LM
	ON
		AM.LocationId = LM.Id
	INNER JOIN sSetup.tDepartmentMaster  AD
	ON	AD.Id=AM.DepartmentId
	INNER JOIN
	    sCommon.tStatusMaster SM
	ON	 SM.Id = AM.StatusId
	INNER JOIN sFixedAsset.tCategoryMaster CM
	ON CM.Id=AM.CategoryId 

	WHERE ((AMT.Number = @rNumber) OR (@rNumber = 0)) AND AM.UsageStatusId <> 124 
	AND AMT.OrgId = @rOrgId AND ((AMT.AssetId = @rAssetId) OR (@rAssetId = 0))
	AND ((AMT.MaintenenceDate >= @rFromMaintenanceDate) OR (ISNULL(@rFromMaintenanceDate,'')='')) 
	AND ((AMT.MaintenenceDate <= @rToMaintenanceDate) OR (ISNULL(@rToMaintenanceDate,'') = '')) 
	AND ((AMT.Id = @rId) OR (@rId = 0))
	AND ((AM.StatusId = @rStatusId) OR (@rStatusId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetManagementDelete]

		@rOrgId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
		BEGIN

				-- Detete Department Location
				DELETE LM From sAssetManagement.tDepartmentLocation DL 
				Inner Join sFixedAsset.tLocationMaster LM ON LM.Id=DL.AssetLocationId Where DL.OrgId=@rOrgId
				
				-- Detete Location Master
				Delete LM From sFixedAsset.tLocationMaster LM  Where LM.OrgId=@rOrgId
				
				-- Detete Category Master
				Delete CM From sFixedAsset.tCategoryMaster CM WHERE CM.OrgId=@rOrgId
				
				-- Detete Asset Adjustment Detail
				DELETE AAD FROM [sAssetManagement].[tAssetAdjustmentDetail] AAD 
				INNER Join [sAssetManagement].[tAssetAudit] AAU ON AAD.AssetAdjustmentId=AAU.Id WHERE AAU.OrgId=@rOrgId
				
				-- Detete Asset Audit
				DELETE AAU FROM [sAssetManagement].[tAssetAudit] AAU WHERE AAU.OrgId=@rOrgId
				
				-- Detete Asset Audit Detail
				DELETE AAUD FROM [sAssetManagement].[tAssetAuditDetail] AAUD 
				Inner Join sAssetManagement.tAssetMaster AM ON AAUD.AssetId=AM.Id WHERE AM.OrgId=@rOrgId
				
				-- Detete Asset Adjustment 
				DELETE AA FROM  [sAssetManagement].[tAssetAdjustment] AA WHERE AA.OrgId=@rOrgId
				
				-- Detete Asset Check
				DELETE AC FROM [sAssetManagement].[tAssetCheck] AC 
				Inner Join sAssetManagement.tAssetMaster AM ON AC.AssetId=AM.Id WHERE AM.OrgId=@rOrgId

				-- Detete Asset Incharge User
				DELETE AIU FROM [sAssetManagement].[tAssetInchargeUser] AIU 
				Inner Join sAssetManagement.tAssetMaster AM ON AIU.AssetId=AM.Id WHERE AM.OrgId=@rOrgId
				
				-- Detete Maintenence
				Delete M FROM [sAssetManagement].[tMaintenence] M 
				Inner Join sAssetManagement.tAssetMaster AM ON M.AssetId=AM.Id WHERE AM.OrgId=@rOrgId
				
				-- Detete Record Manual Event
				DELETE RME FROM [sAssetManagement].[tRecordManualEvent] RME
				Inner Join sAssetManagement.tAssetMaster AM  ON RME.AssetId=AM.Id WHERE AM.OrgId=@rOrgId

				-- Detete Movement
				DELETE Mov FROM [sAssetManagement].[tMovement] Mov
				Inner Join [sAssetManagement].[tMovementDetail] MD ON Mov.Id=MD.MovementId
				Inner Join sAssetManagement.tAssetMaster AM  ON MD.AssetId=AM.Id  WHERE AM.OrgId=@rOrgId

				-- Detete Movement Detail
				Delete MD FROM [sAssetManagement].[tMovementDetail] MD 
				Inner Join sAssetManagement.tAssetMaster AM  ON MD.AssetId=AM.Id  WHERE AM.OrgId=@rOrgId

				-- Detete Asset Master
				Delete AM FROM sAssetManagement.tAssetMaster AM WHERE AM.OrgId=@rOrgId

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetMasterAdd]
	@rOrgId [int],
	@rOrgGroupId smallint,
	@rCode [nvarchar](50) = '',
	@rTitle [nvarchar](100) = '',
	@rSpecification [nvarchar](300) = '',
	@rAccessories [nvarchar](300) = '',
	@rLocationId [int] = 0,
	@rStatusId [int] = 0,
	@rVendorId [int] = 2,
	@rGoodsReceiptNumber [nvarchar](20),
	@rGoodsReceiptDate [date],
	@rIsInstallationRequired [bit] = 'True',
	@rInstallationDate [date] = '',
	@rCategoryId [int] = 2,
	@rDepreciationUptoDate [date] = '',
	@rIsFullyDepreciated [bit] = 'True',
	@rStandardPrice [decimal](22, 6) = 0,
	@rMinStockRequired [int] = 0,
	@rMaintenancePeriod [int] = 0,
	@rIsAmc [bit] = 'True',
	@rMaintenanceAlertPeriod [smallint] = 0,
	@rAmcVendorId [int] = 2,
	@rUsageStatusId [smallint],
	@rLastServiceCost [decimal](22, 6) = 0,
	@rTotalServiceCost [decimal](22, 6) = 0,
	@rLastDownTime [smallint] = 0,
	@rTotalDownTime [smallint] = 0,
	@rLastMaintenanceDate [datetime] = '',
	@rNextMaintenanceDate [datetime] = '',
	@rModelNumber [nvarchar](50) = 0,
	@rIsCritical [bit] = 'True',
	@rIsObsolete [bit] = 'True',
	@rCreatedUserId [bigint],
	@rNoOfRecords [int] = 1,
	@rDeptId [int] = 0,
	@rServiceEntry [datetime] = '',
	@rStoreLocationId int,
	@rNumber Nvarchar(20) = '',
	
	@rIsCheckRequired	bit,	
	@rCheckFrequencyId	int,	
	@rCheckList	nvarchar(300),	
	@rCheckedLastDate	date,	
	--@rCheckedByUserId	bigint,	
	--@rCheckedStatusId	smallint,	
	--@rCheckedRemark	nvarchar(200),	
	@rIsRenewRequired	bit	,
	@rRenewLastDate	date=NULL,	
	@rRenewNextDate	date=NULL,	
	@rRenewRemark	nvarchar(300),	
	@rRenewCheckList	nvarchar(300),	
	@rRenewAlertBeforeDays	smallint,
    @rIsMaintenanceRequired	bit,
	@rWarrantyDate date = '',
	@rAssetImage varbinary(max)=null,
	@rAssetCode nvarchar(50) = ''
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


SELECT @rNumber = ISNULL(max(convert(int,Code)),0) FROM sAssetManagement.tAssetMaster WHERE StoreLocationId = @rStoreLocationId
 
SET @rNumber = @rNumber + 1
IF @rLocationId = 0 
SET @rLocationId = NULL


SET @rNoOfRecords = ISNULL(@rNoOfRecords, 1)

DECLARE @lFirstCode Nvarchar(300)
DECLARE @lLastCode Nvarchar(300)
DECLARE @lTotalRecords Int
DECLARE @lAssetIds Nvarchar(Max)=''

SET @lTotalRecords = @rNoOfRecords

WHILE @rNoOfRecords > 0
BEGIN
	

	DECLARE @loNumber Nvarchar(100)
	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2011,@rStoreLocationId = @rStoreLocationId, @rNextNumber  = @loNumber OUTPUT
	SET @loNumber = ISNULL(@loNumber, '-300')
	IF @loNumber = '-300'
	BEGIN
		SELECT -300 AS Result
		RETURN
	END
	--IF EXISTS (SELECT Id from sAssetManagement.tAssetMaster WHERE AssetCode=@rAssetCode)
	--BEGIN
	--	SELECT -100 AS Result
	--	RETURN
	--END 


	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssetManagement.tAssetMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	--IF @lTotalRecords = @rNoOfRecords
	--	SET @lFirstCode = @loNumber
	--IF @rNoOfRecords = 1
	--	SET @lLastCode = @loNumber	
	--IF @rAmcVendorId = 0
	--	SET @rAmcVendorId = NULL


	INSERT INTO sAssetManagement.tAssetMaster
		(
			Id,
			Code,
			Title,
			Specification,
			Accessories,
			LocationId,
			StatusId,
			VendorId,
			GoodsReceiptNumber,
			GoodsReceiptDate,
			IsInstallationRequired,
			InstallationDate,
			CategoryId,
			DepreciationUptoDate,
			IsFullyDepreciated,
			StandardPrice,
			MinStockRequired,
			MaintenancePeriod,
			IsAmc,
			MaintenanceAlertPeriod,
			AmcVendorId,
			UsageStatusId,
			LastServiceCost,
			TotalServiceCost,
			LastDownTime,
			TotalDownTime,			
			NextMaintenanceDate,
			ModelNumber,
			IsCritical,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			DepartmentID,
			ServiceEntry,
			OrgId,
			StoreLocationId,
			
			IsCheckRequired,
			CheckFrequencyId,	
			CheckList,	
			CheckedLastDate,	
			--CheckedByUserId,	
			--CheckedStatusId,
			--CheckedRemark,
			IsRenewRequired,
			RenewLastDate,
			RenewNextDate,
			RenewRemark,
			RenewCheckList,
			RenewAlertBeforeDays,
			IsMaintenanceRequired,
			OrgGroupId,
			WarrantyDate,
			AssetImage,
			AssetCode
		
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rTitle,
			@rSpecification,
			@rAccessories,
			@rLocationId,
			121,
			@rVendorId,
			@rGoodsReceiptNumber,
			@rGoodsReceiptDate,
			@rIsInstallationRequired,
			@rInstallationDate,
			@rCategoryId,
			@rDepreciationUptoDate,
			@rIsFullyDepreciated,
			@rStandardPrice,
			@rMinStockRequired,
			@rMaintenancePeriod,
			@rIsAmc,
			@rMaintenanceAlertPeriod,
			@rAmcVendorId,
			@rUsageStatusId,
			@rLastServiceCost,
			@rTotalServiceCost,
			@rLastDownTime,
			@rTotalDownTime,			
			--@rNextMaintenanceDate,
			DATEADD(dd, @rMaintenancePeriod, sCommon.fGetDate()),
			@rModelNumber,
			@rIsCritical,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rDeptId,
			@rServiceEntry,
			@rOrgId,
			@rStoreLocationId,
			
			@rIsCheckRequired,
			@rCheckFrequencyId	,	
			@rCheckList,	
			@rCheckedLastDate,	
			--@rCheckedByUserId,	
			--@rCheckedStatusId,
			--@rCheckedRemark,
			@rIsRenewRequired,
			@rRenewLastDate,
			@rRenewNextDate,
			@rRenewRemark,
			@rRenewCheckList,
			@rRenewAlertBeforeDays,
			@rIsMaintenanceRequired,
			@rOrgGroupId,
			@rWarrantyDate,
			@rAssetImage,
			@loNumber
		)

		set @lAssetIds = @lAssetIds +cast(@lNextNumber as nvarchar) + ','
		SET @rNoOfRecords = @rNoOfRecords - 1
END
	
--IF @lTotalRecords = 1
--SELECT 1 AS Result, @lFirstCode AS Msg, @lNextNumber As Id , @lAssetIds AS AssetIds
--ELSE		
SELECT 1 AS Result, 'From: ' + @lFirstCode + ' To: ' + @lLastCode AS Msg, @lNextNumber As Id, @lAssetIds AS AssetIds
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetMasterCustomFieldAdd]
	  
	@rAssetId bigint=0,
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
SELECT @rStrXml
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
	UPDATE [sAssetManagement].[tAssetCustomFieldData]
			SET 
				AssetCustomFieldId=A.AssetCustomFieldId,
				FieldData=[sSetup].[fPortalXMLTagsReplaceReverse](A.FieldData),				
				UpdatedUserId=A.UpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
			FROM (
			SELECT
				AssetCustomFieldId,FieldData,UpdatedUserId,AssetId,AutoId	
				FROM OPENXML (@loDoc, '/Table/AssetCustomField', 1)
			WITH
			(
				AutoId int '@AutoId',		
				AssetId Bigint '@AssetId',
				AssetCustomFieldId INT '@AssetCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			))A 
			INNER JOIN [sAssetManagement].[tAssetCustomFieldData] ACM ON  ACM.AssetId=A.AssetId AND ACM.AutoID=A.AutoId
	
	
	  INSERT INTO [sAssetManagement].[tAssetCustomFieldData]
		(
		    
			AssetId,
			AssetCustomFieldId,
			FieldData,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
		SELECT
				A.AssetId,A.AssetCustomFieldId,[sSetup].[fPortalXMLTagsReplaceReverse](A.FieldData),A.CreatedUserId,sCommon.fGetDate(),A.UpdatedUserId,sCommon.fGetDate()	
				FROM OPENXML (@loDoc, '/Table/AssetCustomField', 1)
			WITH
			(		
			    AutoId int '@AutoId',		
				AssetId Bigint '@AssetId',
				AssetCustomFieldId INT '@AssetCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			)A 
			LEFT JOIN [sAssetManagement].[tAssetCustomFieldData] ACM ON ACM.AssetId=A.AssetId AND ACM.AutoID=A.AutoId
			WHERE ACM.AssetId IS NULL 
			
	
		
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetMasterGet]
	@rOrgId [int] ,
	@rId [int] = 0,
	@rCode [nvarchar](100) = '',
	@rTitle [nvarchar](100) = '',
	@rLocationId [int] = 0,
	@rIsWildCard [bit] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rCode  = ISNULL(@rCode, '') 
SET @rTitle = ISNULL(@rTitle, '') 

IF @rIsWildCard = 1
BEGIN
SET @rCode  = sCommon.fSearchStringGet(@rCode)
SET @rTitle = sCommon.fSearchStringGet(@rTitle)
END

       SELECT AM.Id,
                  AM.Code,
                  AM.Title,
                  Specification,
                  Accessories,
                  AM.LocationId,
                  StatusId,
                  VendorId,
                  VM.Title AS VendorName,
                  GoodsReceiptNumber,
                  GoodsReceiptDate,
                  IsInstallationRequired,
                  InstallationDate,
                  CategoryId,
                  DepreciationUptoDate,
                  IsFullyDepreciated,
                  StandardPrice,
                  MinStockRequired,
                  MaintenancePeriod,
                  IsAmc,                  
                  MaintenanceAlertPeriod,
                  AmcVendorId,
                  VM1.Title AS AmcVendorName,
                  UsageStatusId,
                  LastServiceCost,
                  TotalServiceCost,
                  LastDownTime,
                  TotalDownTime,
                  LastMaintenanceDate,
                  NextMaintenanceDate,
                  ModelNumber,
                  IsCritical,
                  AM.IsObsolete,
                  AM.CreatedUserId,
                  AM.CreatedDateTime,
                  AM.UpdatedUserId,
                  AM.UpdatedDateTime,
                  AM.DepartmentID,
                  ServiceEntry,
                  ODM.Title AS DepartmentTitle,
                  LM.Title AS LocationTitle,
                  FCM.Title AS CategoryTitle,
                  CM.Title AS StatusTitle
         FROM sAssetManagement.tAssetMaster AM
         LEFT JOIN sProcurement.tVendorMaster VM
                  ON VM.Id = AM.VendorId 
            LEFT JOIN   sProcurement.tVendorMaster VM1
                  ON VM1.Id = AM.AmcVendorId 
             	INNER JOIN sSetup.tDepartmentMaster ODM
				ON ODM.Id = AM.DepartmentId
				INNER JOIN sFixedAsset.tLocationMaster LM
				ON LM.Id = AM.LocationId
            --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) VAD
            --ON VAD.DepartmentId = AM.DepartmentID
            --INNER JOIN (SELECT DISTINCT LocationId, LocationTitle FROM sAssetManagement.vExtAssetDepartment) VAD1
            --ON VAD1.LocationId = AM.LocationId
            INNER JOIN (SELECT DISTINCT Id, Title FROM sFixedAsset.tCategoryMaster ) FCM
            ON FCM.Id = AM.CategoryId
            INNER JOIN (SELECT DISTINCT Id, Title FROM sCommon.tStatusMaster) CM
            ON CM.Id = AM.UsageStatusId
        WHERE ((AM.Id = @rId) OR (@rId = 0)) AND ((AM.Code LIKE @rCode) OR (@rCode = '')) AND ((AM.Title LIKE @rTitle) OR (@rTitle = ''))
        AND AM.OrgId = @rOrgId
        AND AM.StoreLocationId=@rStoreLocationId
        ORDER BY AM.Code DESC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetMasterListDataGet]
 	@rOrgGroupId smallint,

	@rId [int] = 0,
	@rCode [nvarchar](100) = '',
	@rTitle [nvarchar](100) = '',
	@rLocationId [int] = 0,
	@rIsWildCard [bit] = 0,
	@rStoreLocationId int,
	@rDepartmentId int

 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rCode  = ISNULL(@rCode, '') 
SET @rTitle = ISNULL(@rTitle, '') 

IF @rIsWildCard = 1
BEGIN
SET @rCode  = sCommon.fSearchStringGet(@rCode)
SET @rTitle = sCommon.fSearchStringGet(@rTitle)
END

       SELECT AM.Id,
                  AM.Code,
                  AM.Title,
                  Specification,
                  Accessories,
                  AM.LocationId,
                  StatusId,
                  VendorId,
                  VM.Title AS VendorName,
                  GoodsReceiptNumber,
                  GoodsReceiptDate,
                  IsInstallationRequired,
                  InstallationDate,
                  CategoryId,
                  DepreciationUptoDate,
                  IsFullyDepreciated,
                  StandardPrice,
                  MinStockRequired,
                  MaintenancePeriod,
                  IsAmc,                  
                  MaintenanceAlertPeriod,
                  AmcVendorId,
                  VM1.Title AS AmcVendorName,
                  UsageStatusId,
                  LastServiceCost,
                  TotalServiceCost,
                  LastDownTime,
                  TotalDownTime,
                  LastMaintenanceDate,
                  NextMaintenanceDate,
                  ModelNumber,
                  IsCritical,
                  AM.IsObsolete,
                  AM.CreatedUserId,
                  AM.CreatedDateTime,
                  AM.UpdatedUserId,
                  AM.UpdatedDateTime,
                  AM.DepartmentID,
                  ServiceEntry,
                  ODM.Title AS DepartmentTitle,
                  VAD1.Title AS LocationTitle,
                  FCM.Title AS CategoryTitle,
                  CM.Title AS StatusTitle,
                  
                   AM.IsCheckRequired,
				  ISNULL (AM.CheckFrequencyId,0) AS CheckFrequencyId,	
				  AM.CheckList,	
                  --AM.CheckedLastDate,
                   ISNULL(AM.CheckedLastDate,'0001/01/01') AS CheckedLastDate,
                  AM.CheckedByUserId,
                  ISNULL(AM.CheckedStatusId,0) AS CheckedStatusId,
                  AM.CheckedRemark,
                  IsRenewRequired,
                  ISNULL(RenewLastDate,'0001/01/01') AS RenewLastDate,
                  ISNULL(RenewNextDate,'0001/01/01') AS RenewNextDate,
                --  AM.RenewLastDate,
                  --AM.RenewNextDate,
				  AM.RenewRemark,
				  AM.RenewCheckList,
				  AM.RenewAlertBeforeDays,
				  U.LoginTitle AS UserTitle
				,ISNULL (AM.IsMaintenanceRequired,0) AS IsMaintenanceRequired
				,ISNULL(AM.WarrantyDate,'0001/01/01') AS WarrantyDate
				,AM.AssetImage AS AssetImage
				,ISNULL(AM.AssetCode,'') AS AssetCode
         FROM sAssetManagement.tAssetMaster AM
         LEFT JOIN sProcurement.tVendorMaster VM
                  ON VM.Id = AM.VendorId 
         LEFT JOIN sProcurement.tVendorMaster VM1
                  ON VM1.Id = AM.AmcVendorId 
            --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) VAD
            --ON VAD.DepartmentId = AM.DepartmentID
            INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = AM.DepartmentId
             --left JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = AM.DepartmentId
            INNER JOIN sFixedAsset.tLocationMaster VAD1
            ON VAD1.Id = AM.LocationId 
            INNER JOIN (SELECT DISTINCT Id, Title FROM sFixedAsset.tCategoryMaster ) FCM
            ON FCM.Id = AM.CategoryId
            INNER JOIN (SELECT DISTINCT Id, Title FROM sCommon.tStatusMaster) CM
            ON CM.Id = AM.UsageStatusId
             LEFT JOIN sSecurity.tUser U ON U.Id=AM.CheckedByUserId
        WHERE ((AM.Id = @rId) OR (@rId = 0)) 
		AND ((AM.Code LIKE @rCode) OR (@rCode = '')) 
		--AND ((AM.AssetCode LIKE @rAssetCode) OR (@rAssetCode = ''))
		AND ((AM.Title LIKE @rTitle) OR (@rTitle = ''))
        AND AM.OrgGroupId = @rOrgGroupId
        AND AM.StoreLocationId=@rStoreLocationId
        AND ((AM.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((AM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
        ORDER BY TRY_CAST(AM.Code AS INT) DESC, AM.Code DESC --Changed for mantis : 37133

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetMasterListGet]
	@rOrgId [int] ,
	@rAssetTag [int] = 0,
	@rAssetDescription [nvarchar](50) = '',
	@rModelNo [nvarchar](50) = '',
	@rManufacturer [nvarchar](50) = '',
	@rCategoryId [int] = 0,
	@rLocationId [int] = 0,
	@rDepartmentId [int] = 0,
	@rCode [nvarchar](50) = '',
	@rStatusId [int] = 0,
	@rTag [int] = 0,
	@rFromDate [datetime] = '',
	@rToDate [datetime] = '',
	@rIscritical [bit] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
        IF @rFromDate IS NULL
         SET @rFromDate = sCommon.fGetDate()
         
       SELECT Tas.Id AS AssetTag,
                  Tas.CODE,
                  Tas.Title AS AssetDescription,
                  Tas.LocationId,
                  LOC.Title AS Location,
                  Tas.StatusId,
                  STAT.title AS status,
                  Tas.ModelNumber AS ModelNo,
                  Tas.CategoryId,
                  Cat.TITLE AS Category,
                  'AS' AS Manufacturer,
                  Tas.MaintenanceAlertPeriod,
                  day(Tas.NextMaintenanceDate) AS NextMaintenanceDate,
                  Tas.NextMaintenanceDate AS DueDate,
                  ISNULL(Tas.NextMaintenanceDate, sCommon.fGetDate()) AS NextDate,
            Tas.LastMaintenanceDate AS lastDate,
            Tas.Iscritical,
            AD.Title AS  DepartmentTitle,
			ISNULL(Tas.AssetCode,'') AS AssetCode 

          FROM sAssetManagement.tAssetMaster Tas
         INNER JOIN  sFixedAsset.tCategoryMaster Cat
         ON TAS.CATEGORYID = CAT.ID and  Tas.OrgId = @rOrgId 
         INNER JOIN  sCommon.tStatusMaster STAT
         ON STAT.ID =  Tas.UsageStatusId 
         INNER JOIN  sFixedAsset.VextLocationMaster LOC
         ON LOC.ID = TAS.LocationId
         INNER JOIN sSetup.tDepartmentMaster  AD
         ON AD.Id = Tas.DepartmentID
           
        WHERE 
        
         ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
        AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 0 AND Tas.UsageStatusId <> 124 )
        
        OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
         AND  (CONVERT(NVARCHAR(10), DATEADD(DD,(- Tas.MaintenanceAlertPeriod), Tas.NextMaintenanceDate), 111)  <=  CONVERT(NVARCHAR(10), @rFromDate, 111) )  
        AND  (Tas.NextMaintenanceDate  >=  @rFromDate ) 
         AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 1 AND Tas.UsageStatusId <> 124  ) 
          OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
          AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0)) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0)) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))
        AND  (CONVERT(NVARCHAR(10), Tas.NextMaintenanceDate, 111)  >=  CONVERT(NVARCHAR(10), @rFromDate, 111) ) 
        AND (Tas.NextMaintenanceDate  <= (@rToDate + 1) )
        AND((Tas.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
        AND ((Iscritical = @rIscritical))) AND @rTag = 2 AND Tas.UsageStatusId <> 124 ) 
        
        ORDER BY  Tas.Id DESC
         
        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetMasterModify]
	@rId [int],
	@rTitle [nvarchar](100),
	@rSpecification [nvarchar](300),
	@rAccessories [nvarchar](300),
	@rLocationId [int],
	@rStatusId [smallint],
	@rVendorId [int],
	@rGoodsReceiptNumber [nvarchar](20),
	@rGoodsReceiptDate [date],
	@rIsInstallationRequired [bit],
	@rInstallationDate [date],
	@rCategoryId [int],
	@rMinStockRequired [smallint],
	@rMaintenancePeriod [smallint],
	@rIsAmc [bit],
	@rMaintenanceAlertPeriod [smallint],
	@rAmcVendorId [int],
	@rUsageStatusId [smallint],
	@rLastServiceCost [decimal](22, 6),
	@rTotalServiceCost [decimal](22, 6),
	@rLastDownTime [smallint],
	@rTotalDownTime [smallint],
	@rLastMaintenanceDate [datetime],
	@rNextMaintenanceDate [datetime],
	@rModelNumber [nvarchar](50),
	@rIsCritical [bit],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rDeptId [int],
	@rServiceEntry [datetime],
	@rIsCheckRequired	bit,	
	@rCheckFrequencyId	smallint,	
	@rCheckList	nvarchar(300),	
	@rCheckedLastDate	date,	
	--@rCheckedByUserId	bigint,	
	--@rCheckedStatusId	smallint,	
	--@rCheckedRemark	nvarchar(200),	
	@rIsRenewRequired	bit	,
	@rRenewLastDate	date,	
	@rRenewNextDate	date,	
	@rRenewRemark	nvarchar(300),	
	@rRenewCheckList	nvarchar(300),	
	@rRenewAlertBeforeDays	smallint,
	@rIsMaintenanceRequired	bit,
	@rWarrantyDate date = '',
	@rAssetImage varbinary(max)=null,
	@rAssetCode nvarchar(50) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF EXISTS (SELECT Id from sAssetManagement.tAssetMaster WHERE AssetCode=@rAssetCode AND Id!=@rId)
		BEGIN
			SELECT -100 AS Result
			RETURN
		END 

	 IF @rAmcVendorId = 0
		SET @rAmcVendorId = NULL
	 UPDATE sAssetManagement.tAssetMaster
		SET 			
			Title = @rTitle,
			Specification = @rSpecification,
			Accessories = @rAccessories,
			LocationId = @rLocationId,
			StatusId = @rStatusId,
			VendorId = @rVendorId,
			GoodsReceiptNumber = @rGoodsReceiptNumber,
			GoodsReceiptDate = @rGoodsReceiptDate,
			IsInstallationRequired = @rIsInstallationRequired,
			InstallationDate = @rInstallationDate,
			CategoryId = @rCategoryId,			
			MinStockRequired = @rMinStockRequired,
			MaintenancePeriod = @rMaintenancePeriod,
			IsAmc = @rIsAmc,
			MaintenanceAlertPeriod = @rMaintenanceAlertPeriod,
			AmcVendorId = @rAmcVendorId,
			UsageStatusId = @rUsageStatusId,
			LastServiceCost = @rLastServiceCost,
			TotalServiceCost = @rTotalServiceCost,
			LastDownTime = @rLastDownTime,
			TotalDownTime = @rTotalDownTime,			
			NextMaintenanceDate = @rNextMaintenanceDate,
			ModelNumber = @rModelNumber,
			IsCritical = @rIsCritical,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
		    DepartmentID =  @rDeptId,
		    ServiceEntry = @rServiceEntry,
		       IsCheckRequired=@rIsCheckRequired,
		    CheckFrequencyId=@rCheckFrequencyId	,	
			CheckList=@rCheckList,
			CheckedLastDate=@rCheckedLastDate,	
			IsRenewRequired=@rIsRenewRequired,
			RenewLastDate=@rRenewLastDate,
			RenewNextDate=@rRenewNextDate,
			RenewRemark=@rRenewRemark,
			RenewCheckList=@rRenewCheckList,
			RenewAlertBeforeDays=@rRenewAlertBeforeDays,
			IsMaintenanceRequired=@rIsMaintenanceRequired,
			WarrantyDate=@rWarrantyDate,
			AssetImage=@rAssetImage,
			AssetCode=@rAssetCode
			
	  WHERE Id = @rId
	  
	  SELECT 1 AS Result, 'Update' AS Msg, @rId As Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pAssetMasterRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAssetManagement.tAssetMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pDepartmentLocationAdd]
	@rOrgId [int],
	@rDeptId [int],
	@rCreatedUserId [bigint],
	@rLocationXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lCurrentId INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssetManagement.tDepartmentLocation', 1, 1, 1	,@outNextNumber = @lCurrentId output
	DECLARE @lCount INT

	DECLARE @loIdoc INT
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rLocationXml
	
	INSERT INTO sAssetManagement.tDepartmentLocation
		(
			Id,
			OrganizationDepartmentId,
			AssetLocationId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	SELECT		
			@lCurrentId + ROW_NUMBER() OVER(ORDER BY LocationId) AS Id, 
			@rDeptId,
			LocationId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId		
	FROM OPENXML (@loIdoc, '/Root/Location', 1)
		 WITH ( LocationId INT )
		 
		 SELECT		
		    @lCurrentId + ROW_NUMBER() OVER(ORDER BY LocationId) AS Id, 			
			@rDeptId,
			LocationId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()		
	FROM OPENXML (@loIdoc, '/Root/Location', 1)
		 WITH ( LocationId INT )
		 
	SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/Root/Location', 1)
				 WITH (LocationId INT)
	SET @lCurrentId  = @lCount + @lCurrentId 
		
	EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sAssetManagement.tDepartmentLocation', @rCurrentNumber = @lCurrentId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pDepartmentLocationGet]
	@rOrgId int,
	@rCode [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT DL.Id AS Id,			
			DL.OrganizationDepartmentId AS DeptId,
			ODM.Code AS DeptCode,
			ODM.Title AS DeptName,
			DL.AssetLocationId AS LocationId,
			SLM.Code AS LocationCode,
			SLM.Title AS LocationTitle
			
	   FROM sAssetManagement.tDepartmentLocation DL
			INNER JOIN sSetup.tDepartmentMaster ODM
		ON DL.OrganizationDepartmentId = ODM.Id
			INNER JOIN sFixedAsset.tLocationMaster SLM
		ON DL.AssetLocationId = SLM.Id
		
	  WHERE ((ODM.Code = @rCode) OR (@rCode = ''))
			AND SLM.IsObsolete = 0
			AND DL.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pDepartmentLocationModify]
	@rId [int],
	@rOrganizationDepartmentId [smallint],
	@rAssetLocationId [smallint],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAssetManagement.tDepartmentLocation
		SET 
			OrganizationDepartmentId = @rOrganizationDepartmentId,
			AssetLocationId = @rAssetLocationId,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pFetchMovementId]
	@rOrgId Int,
	@rNumber [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	
	DECLARE @lId INT 
	SET @lId = 0
	IF EXISTS (SELECT Id FROM sAssetManagement.tMovement 
		WHERE Number  = @rNumber AND OrgId  = @rOrgId)
		SELECT @lId = Id FROM sAssetManagement.tMovement 
				WHERE Number  = @rNumber AND OrgId  = @rOrgId
	SELECT @lId AS ID 
		
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pImportAssetAdd] 
	@rOrgGroupId int,
	@rXmldoc [nvarchar](max),
	@rCustomFieldXML nvarchar(max),
	@rCreatedUserId bigint,
	@rOrgId int,
	@rStoreLocationId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @lCount INT
Declare @lResult int, @lresultCode nvarchar(100)
DECLARE @lInterrorCode INT,@intDoc INT
DECLARE @lInterrorCode1 INT,@intDoc1 INT

Declare 
	@lCode nvarchar(20),
	@lName nvarchar(100) = '',
	@lAssetCategory nvarchar(50) = '',
	@lModelNumber nvarchar(50) = '',
	@lSpecification nvarchar(300) = '',
	@lAccessories nvarchar(300) = '',
	@lIsMaintenance bit = null,
	@lServiceEntry date =  Null,
	@lMaitenancePeriod smallint = null,
	@lAlertPeriod smallint = null,
	@lCurrentDepartment nvarchar(50) ='',
	@lCurrentLocation nvarchar(50) ='',
	@lUsageStatus nvarchar(50) ='',
	@lLastServiceCost decimal(22,6) = null,
	@lTotalServiceCost decimal(22,6)  = null,
	@lLastMaintenanceDate datetime = null,
	@lNextMaintenanceDate datetime = null,
	@lIsCheckRequired bit = null,
	@lCheckFrequency nvarchar(50) = '',
	@lCheckList nvarchar(300) = null,
	@lCheckedLastDate date = null,
	@lCheckedByUserId bigint = null,
	@lCheckedStatus nvarchar(300) =  null,
	@lCheckedRemark nvarchar(200) = null,
	@lIsRenewRequired bit = null,
	@lRenewLastDate date = null,
	@lRenewNextDate date = null,
	@lRenewRemark nvarchar(300) =  null,
	@lRenewCheckList nvarchar(300) = null,
	@lRenewAlertBeforeDays smallint = null,
	@lAssetCategoryId bigint = 0,
	@lCurrentDepartmentId bigint = 0,
	@lCurrentLocationId int = 0,
	@lUsageStatusId bigint = 0,
	@lCheckFrequencyId bigint = 0,
	@lCheckedStatusId bigint = 0,
	@lGoodsReceiptNumber nvarchar (20) = '',
	@lGoodsReceiptDate date = null,
	@lQuantity decimal = 1,
	@lNumber Nvarchar(20) = '',
	--@lAssetCode nvarchar(50) = '',
	@lWarrantyDate date = null,
	@lUniqueId INT=0
	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	EXECUTE @lInterrorCode1 = sp_xml_preparedocument @intDoc1 OUTPUT, @rCustomFieldXML

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

	CREATE TABLE #tempTable  
	(
			Id bigint identity,
			Name nvarchar(100),
			AssetCategory nvarchar(50),
			ModelNumber nvarchar(50),
			Quantity decimal null,
			Specification nvarchar(300),
			Accessories nvarchar(300),
			IsMaintenance bit null,
			ServiceEntry date  Null,
			MaitenancePeriod smallint null,
			AlertPeriod smallint null,
			CurrentDepartment nvarchar(50),
			CurrentLocation nvarchar(50),
			UsageStatus nvarchar(50),
			LastServiceCost decimal(22,6) null,
			TotalServiceCost decimal(22,6) null,
			LastMaintenanceDate datetime Default null,
			NextMaintenanceDate datetime Default null,
			IsCheckRequired bit null,
			CheckFrequency nvarchar(50),
			CheckList nvarchar(300) null,
			CheckedLastDate date Default null,
			IsRenewRequired bit null,
			RenewLastDate date Default null,
			RenewNextDate date Default null,
			RenewRemark nvarchar(300) null,
			RenewCheckList nvarchar(300) null,
			RenewAlertBeforeDays smallint null,
			--AssetCode nvarchar(50) null,
			WarrantyDate date null,
			UniqueId Int
	)
	print('Table Created')
	INSERT INTO #tempTable
	(
			Name,
			AssetCategory,
			ModelNumber,
			Quantity,
			Specification,
			Accessories,
			IsMaintenance,
			ServiceEntry,
			MaitenancePeriod,
			AlertPeriod,
			CurrentDepartment,
			CurrentLocation,
			UsageStatus,
			LastServiceCost,
			TotalServiceCost,
			LastMaintenanceDate,
			NextMaintenanceDate,
			IsCheckRequired,
			CheckFrequency,
			CheckList,
			CheckedLastDate,
			IsRenewRequired,
			RenewLastDate,
			RenewNextDate,
			RenewRemark,
			RenewCheckList,
			RenewAlertBeforeDays,
			--AssetCode,
			WarrantyDate,
			UniqueId
	)

	SELECT *
			FROM OPENXML (@intDoc, '/Table/ImportAsset', 1)
	WITH
	(						
			Name nvarchar(100) '@Name',
			AssetCategory nvarchar(50) '@AssetCategory',
			ModelNumber nvarchar(50) '@ModelNumber',
			Quantity decimal '@Quantity',
			Specification nvarchar(300) '@Specification',
			Accessories nvarchar(300) '@Accessories',
			IsMaintenance bit '@IsMaintenance',
			ServiceEntry date '@ServiceEntry',
			MaitenancePeriod smallint '@MaintenancePeriod',
			AlertPeriod smallint '@AlertPeriod',
			CurrentDepartment nvarchar(50)'@CurrentDepartment',
			CurrentLocation nvarchar(50)'@CurrentLocation',
			UsageStatus nvarchar(50)'@UsageStatus',
			LastServiceCost decimal(22,6) '@LastServiceCost',
			TotalServiceCost decimal(22,6) '@TotalServiceCost',
			LastMaintenanceDate datetime '@LastMaintenanceDate',
			NextMaintenanceDate datetime '@NextMaintenanceDate',
			IsCheckRequired bit '@IsCheckRequired',
			CheckFrequency nvarchar(50)'@CheckFrequency',
			CheckList nvarchar(300) '@CheckList',
			CheckedLastDate date '@CheckedLastDate',
			IsRenewRequired bit '@IsRenewRequired',
			RenewLastDate date '@RenewLastDate',
			RenewNextDate date '@RenewNextDate',
			RenewRemark nvarchar(300) '@RenewRemark',
			RenewCheckList nvarchar(300) '@RenewCheckList',
			RenewAlertBeforeDays smallint '@RenewAlertBeforeDays',
			--AssetCode nvarchar(50) '@AssetCode',
			WarrantyDate date '@WarrantyDate',
			UniqueId INT '@UniqueId'
	) A 
	

	print('Master Insert')

	CREATE TABLE #tempTableCustomField
	(
		Id bigint identity,
		UniqueId Int,
		FieldName nvarchar(500),
		FieldData nvarchar(500)
		--AssetId bigint
	)
	print('Created')
	INSERT INTO #tempTableCustomField
	(
		UniqueId,
		FieldName,
		FieldData
		--AssetId
	)

	SELECT A.UniqueId, A.FieldName,A.FieldData
			FROM OPENXML (@intDoc1, '/Table/ImportCustomField', 1)
	WITH
	(
		UniqueId nvarchar(500) '@UniqueId',
		FieldName nvarchar(500) '@FieldName',
		FieldData nvarchar(500) '@FieldData'				
	) A 

	EXEC sp_xml_removedocument @intDoc

	EXEC sp_xml_removedocument @intDoc1

	print('Custom Add')

	DECLARE @lTotal int = 0, @lCustomUniqueId int = 0
	SELECT @lTotal = COUNT(Id) FROM #tempTable
	SELECT @lCount = 1
	
	WHILE @lCount <= @lTotal 
	BEGIN
	SELECT 
			@lName = Name,
			@lAssetCategory = AssetCategory,
			@lModelNumber = ModelNumber,
			@lQuantity = Quantity,
			@lSpecification = Specification,
			@lAccessories = Accessories,
			@lIsMaintenance = IsMaintenance,
			@lServiceEntry = ServiceEntry,
			@lMaitenancePeriod = MaitenancePeriod,
			@lAlertPeriod = AlertPeriod,
			@lCurrentDepartment = CurrentDepartment,
			@lCurrentLocation = CurrentLocation,
			@lUsageStatus = UsageStatus,
			@lLastServiceCost = LastServiceCost,
			@lTotalServiceCost = TotalServiceCost,
			@lLastMaintenanceDate = LastMaintenanceDate,
			@lNextMaintenanceDate = NextMaintenanceDate,
			@lIsCheckRequired = IsCheckRequired,
			@lCheckFrequency = CheckFrequency,
			@lCheckList = CheckList,
			@lCheckedLastDate = CheckedLastDate,
			@lIsRenewRequired = IsRenewRequired,
			@lRenewLastDate = RenewLastDate,
			@lRenewNextDate = RenewNextDate,
			@lRenewRemark = RenewRemark,
			@lRenewCheckList =RenewCheckList,
			@lRenewAlertBeforeDays = RenewAlertBeforeDays,
			--@lAssetCode = AssetCode,
			@lWarrantyDate = WarrantyDate
			FROM #tempTable WHERE Id = @lCount

			SET @lCustomUniqueId = (Select UniqueId from #tempTable WHERE Id = @lCount)

			SET @lAssetCategoryId = '' SET @lCurrentDepartmentId = '' SET @lCurrentLocationId = 0
			SET @lUsageStatusId = ''  SET @lCheckFrequencyId =''     SET @lCheckedStatusId = ''
			SET @lGoodsReceiptNumber = '' SET @lGoodsReceiptDate = ''

			SELECT @lAssetCategoryId = Id FROM sFixedAsset.tCategoryMaster WHERE  Title = @lAssetCategory 
			SELECT @lCurrentDepartmentId = Id FROM sSetup.tDepartmentMaster WHERE  Title = @lCurrentDepartment AND OrgId = @rOrgId
			SELECT @lCurrentLocationId = Id FROM sFixedAsset.tLocationMaster WHERE  Title = @lCurrentLocation AND OrgId = @rOrgId
			--SELECT @lUsageStatusId = Id FROM sFixedAsset.tCategoryMaster WHERE  Title = @lAssetCategory
			SELECT @lCheckFrequencyId = Id FROM sCommon.tCheckFrequencyMaster WHERE  Title = @lCheckFrequency
			--SELECT @lCheckedStatusId = Id FROM sCommon.tStatusMaster WHERE  Title = @lCheckedStatus
			IF(@lUsageStatus = 'Spare')
			BEGIN
				SET @lUsageStatusId = '121'
				SET @lGoodsReceiptNumber = 'GRN01'
			END
			IF(@lUsageStatus = 'Deployed')
			BEGIN
				SET @lUsageStatusId = '122'
			END
			IF(@lUsageStatus = 'Maintenance')
			BEGIN
				SET @lUsageStatusId = '123'
			END
			IF(@lUsageStatus = 'Retired')
			BEGIN
				SET @lUsageStatusId = '124'
			END
			IF(@lUsageStatus = 'Removed')
			BEGIN
				SET @lUsageStatusId = '125'
			END
			IF(LEN(@lCheckList) = 0)
			BEGIN
				SET @lCheckList = Null
			END
			IF(@lCheckedLastDate = '1900-01-01')
			BEGIN
				SET @lCheckedLastDate = Null
			END
			IF(@lRenewLastDate = '1900-01-01')
			BEGIN
				SET @lRenewLastDate = Null
			END
			IF(@lRenewNextDate = '1900-01-01')
			BEGIN
				SET @lRenewNextDate = Null
			END
			IF(LEN(@lRenewRemark) = 0)
			BEGIN
				SET @lRenewRemark = Null
			END
			IF(LEN(@lRenewCheckList) = 0)
			BEGIN
				SET @lRenewCheckList = Null
			END
			IF(@lRenewAlertBeforeDays = 0)
			BEGIN
				SET @lRenewAlertBeforeDays = Null
			END
			IF(@lWarrantyDate = '1900-01-01')
			BEGIN
				SET @lWarrantyDate = Null
			END

			IF(@lQuantity=0)
			BEGIN
				SET @lQuantity=1
			END
			SET @lGoodsReceiptDate =   GETDATE();
			
			DECLARE @lNextNumber INT
			DECLARE @lTotalRecords Int
			
			DECLARE @loNumber Nvarchar(100)
			
		WHILE @lQuantity > 0
		BEGIN

		print @lQuantity
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAssetManagement.tAssetMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

			EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2011,@rStoreLocationId = @rStoreLocationId, @rNextNumber  = @loNumber OUTPUT

			SELECT @lNumber = ISNULL(max(convert(int,Code)),0) FROM sAssetManagement.tAssetMaster WHERE StoreLocationId = @rStoreLocationId
			SET @lNumber = @lNumber + 1

			INSERT INTO sAssetManagement.tAssetMaster
			(
				Id,
				Code,
				Title,
				Specification,
				Accessories,
				LocationId,
				StatusId,
				VendorId,
				GoodsReceiptNumber,
				GoodsReceiptDate,
				IsInstallationRequired,
				CategoryId,
				DepreciationUptoDate,
				IsFullyDepreciated,
				StandardPrice,
				MinStockRequired,
				MaintenancePeriod,
				IsAmc,
				MaintenanceAlertPeriod,
				AmcVendorId,
				UsageStatusId,
				LastServiceCost,
				TotalServiceCost,
				LastDownTime,
				TotalDownTime,
				NextMaintenanceDate,
				ModelNumber,
				IsCritical,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				DepartmentID,
				ServiceEntry,
				OrgId,
				StoreLocationId,
			
				IsCheckRequired,
				CheckFrequencyId,	
				CheckList,	
				CheckedLastDate,	
				IsRenewRequired,
				RenewLastDate,
				RenewNextDate,
				RenewRemark,
				RenewCheckList,
				RenewAlertBeforeDays,
				IsMaintenanceRequired,
				OrgGroupId,
				WarrantyDate,
				AssetCode
		
			)
		VALUES
			(
				@lNextNumber,
				@lNumber,
				@lName,
				@lSpecification,
				@lAccessories,
				@lCurrentLocationId,
				@lUsageStatusId,
				0,
				@lGoodsReceiptNumber,
				@lGoodsReceiptDate,
				0,
				@lAssetCategoryId,
				'1900-01-01',
				1,
				0,
				0,
				@lMaitenancePeriod,
				0,
				@lAlertPeriod,
				0,
				@lUsageStatusId,
				@lLastServiceCost,
				@lTotalServiceCost,
				0,
				0,
				--@lNextMaintenanceDate,
				DATEADD(dd, @lMaitenancePeriod, sCommon.fGetDate()),
				@lModelNumber,
				0,
				0,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@lCurrentDepartmentId,
				@lServiceEntry,
				@rOrgId,
				0,

				@lIsCheckRequired,
				@lCheckFrequencyId,	
				@lCheckList,	
				@lCheckedLastDate,	
				@lIsRenewRequired,
				@lRenewLastDate,
				@lRenewNextDate,
				@lRenewRemark,
				@lRenewCheckList,
				@lRenewAlertBeforeDays,
				@lIsMaintenance,
				@rOrgGroupId,
				@lWarrantyDate,
				@loNumber
			)

			--Execute sAssetManagement.pImportAssetCustomFieldAdd @rCustomFieldXML, @lNextNumber, @rCreatedUserId, @lCustomUniqueId
			--UPDATE #tempTableCustomField SET AssetId = @lNextNumber WHERE UniqueId = @lCustomUniqueId

			DECLARE @lCount1 int,@lId1 int
			SELECT @lCount1 = COUNT(Id) FROM #tempTableCustomField WHERE UniqueId = @lCustomUniqueId
			SELECT Top 1 @lId1 = Id FROM #tempTableCustomField WHERE UniqueId = @lCustomUniqueId

			WHILE @lId1 <= @lCount1 
			BEGIN
				DECLARE @lField1 nvarchar(200), @lCustomFieldId int, @lFieldData1 nvarchar(200)
				
				Select @lField1 = FieldName from #tempTableCustomField where Id = @lId1

				Select @lCustomFieldId = Id from sAssetManagement.tAssetCustomFieldMaster where FieldTitle = @lField1
				
				Select @lFieldData1 = FieldData From #tempTableCustomField where Id = @lId1
				
				INSERT INTO [sAssetManagement].[tAssetCustomFieldData]
				(
				    
					AssetId,
					AssetCustomFieldId,
					FieldData,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime
				)
				Values
				(
					 @lNextNumber
					,@lCustomFieldId
					,@lFieldData1
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rCreatedUserId
					,sCommon.fGetDate()
				)		
				SET @lId1=@lId1+1
			END

			SET @lNextNumber = null
			SET @lQuantity = @lQuantity - 1
		END

		
			--EXECUTE [sIp].[pStockItemPlanningAdd] 0,@lNextNumber,0,0,0,0,null,null,@rStoreLocationId,@rOrgGroupId
  	  --EXECUTE sProcurement.pStockBatchAdd  @rOrgGroupId,@rStoreLocationId,@lNextNumber,null,null,0,@rUserId ,0 
		SET @lResult = 1
		SET @lCount = @lCount + 1;
		SET @lQuantity = ISNULL(@lQuantity, 1)
	END
	
	Select @lResult AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pImportAssetCustomFieldValidate]
	  
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lInterrorCode INT,@intDoc INT
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml

BEGIN
		
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		FieldName nvarchar(500),
		FieldData nvarchar(500),
		UniqueId Int
	)

	INSERT INTO #tempTable
	(
		FieldName,
		FieldData,
		UniqueId
	)

	SELECT  A.FieldName,A.FieldData,A.UniqueId
			FROM OPENXML (@intDoc, '/Table/ImportCustomField', 1)
	WITH
	(
		FieldName nvarchar(500) '@FieldName',
		FieldData nvarchar(500) '@FieldData',
		UniqueId nvarchar(500) '@UniqueId'			
	) A
	
	EXEC sp_xml_removedocument @intDoc

	
	DECLARE @lFieldName nvarchar(500),@lFieldData nvarchar(500)

	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable

	Declare @lCustomFieldCount int, @ltempCustomFieldCount int

	select @lCustomFieldCount = Count(Id) from sAssetManagement.tAssetCustomFieldMaster
		
	WHILE @lId <= @lCount 
	BEGIN
		DECLARE @lField nvarchar(max)
		
		select @ltempCustomFieldCount = Count(UniqueId) from #tempTable where UniqueId = @lId group by UniqueId
		
		IF (@ltempCustomFieldCount != @lCustomFieldCount)
		BEGIN
			Select -102 As Result, 'Count of Custom Field is Not Match With Asset Custom Field' AS Msg
			RETURN
		END

		Select @lField = FieldName from #tempTable where Id = @lId
		
		IF NOT EXISTS(Select * from sAssetManagement.tAssetCustomFieldMaster where  FieldTitle = @lField)
		BEGIN
		 Select -101 As Result, @lField + ' Field is wrong' AS Msg
		 RETURN
		END

		SET @lId=@lId+1
	END

	DECLARE @lCount1 int,@lId1 int
	SELECT @lCount1 = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId1=Id FROM #tempTable

	WHILE @lId1 <= @lCount1 
	BEGIN
		DECLARE @lField1 nvarchar(200), @lFieldTypeId int, @lFieldData1 nvarchar(200), @lFieldList nvarchar(500)
		
		Select @lField1 = FieldName from #tempTable where Id = @lId1

		Select @lFieldTypeId = FieldTypeId from sAssetManagement.tAssetCustomFieldMaster where FieldTitle = @lField1
		Select @lFieldList = FieldList from sAssetManagement.tAssetCustomFieldMaster where FieldTitle = @lField1
		
		Select @lFieldData1 = FieldData From #tempTable where Id = @lId1
		
		IF(@lFieldTypeId = 1)
		BEGIN
			IF ((@lFieldData1 NOT LIKE '%Yes%') AND (@lFieldData1 Not Like '%No%'))
				BEGIN
					Select -103 As Result, @lField1 + ' is not matching with Custom Field' AS Msg
					Return
				END
		END

		ELSE IF(@lFieldTypeId = 2)
		BEGIN
		
			IF ((@lFieldData1 NOT IN(SELECT cast(item as nvarchar(200)) FROM  sCommon.fnsplit(@lFieldList,','))))
				BEGIN
					Select -103 As Result,@lField1 + ' is not matching with Custom Field' AS Msg
					Return
				END
		END

		ELSE IF(@lFieldTypeId = 4)
		BEGIN
			IF ((SELECT IsNumeric(@lFieldData1))=0)
				BEGIN
					Select -103 As Result,@lField1 + ' is not matching with Custom Field' AS Msg
					Return
				END
		END
		
		SET @lId1=@lId1+1
	END
	
	DROP Table #tempTable
	END TRY

	BEGIN CATCH 
	SELECT -1 AS Result,error_message()
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pLocationIdsForDeptGet]
	@rOrgId int,
	@rCode [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
BEGIN

	SET NOCOUNT ON
	SELECT 
		LM.Id AS LocationId, 
		LM.Code AS LocationCode,
		LM.Title AS LocationTitle,
		ODM.Title AS DeptName
	FROM
		sFixedAsset.tLocationMaster LM, sSetup.tDepartmentMaster ODM
	WHERE
		LM.IsObsolete = 0 AND ODM.Code = @rCode
		AND ODM.OrgId = @rOrgId
		AND LM.OrgId=@rOrgId
	ORDER BY LM.Code	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pMaintenenceAdd]
	@rNumber [nvarchar](20) OUTPUT,
	@rOrgId [int],
	@rAssetId [int],
	@rMaintenenceDate [datetime],
	@rMaintenenceBy [nvarchar](300),
	@rMaintenenceReason [nvarchar](300),
	@rMaintenenceCost [decimal](22, 6),
	@rNextMaintenenceDate [datetime],
	@rCreatedUserId [bigint],
	@rAssetMaintenanceDetailXml [nvarchar](max),
	@rDocumentNo [nvarchar](20),
	@rDocumentDate [datetime],
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssetManagement.tMaintenence', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	--DECLARE @loNextNumber Nvarchar(20)
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 92,@rStoreLocationId=@rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
	
	--IF (@loNextNumber IS NULL)
	--	BEGIN
	--		RAISERROR('5000', 15, 106)
	--		RETURN
	--	END
	
	
	SELECT @rNumber = ISNULL(max(Number),0) FROM  sAssetManagement.tMaintenence WHERE StoreLocationId = @rStoreLocationId
	SET @rNumber = @rNumber + 1

	INSERT INTO sAssetManagement.tMaintenence
		(
			Id,
			Number,
			AssetId,
			MaintenenceDate,
			MaintenenceBy,
			MaintenenceReason,
			MaintenenceCost,
			NextMaintenenceDate,
			CreatedUserId,
			CreatedDateTime,
			DocumentNo,
			DocumentDate,
			OrgId,
			StoreLocationId
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rAssetId,
			--(SELECT NextMaintenanceDate FROM sAssetManagement.tAssetMaster WHERE id = @rAssetId),
			@rMaintenenceDate,
			@rMaintenenceBy,
			@rMaintenenceReason,
			@rMaintenenceCost,
			--(SELECT DATEADD(dd, (SELECT MaintenancePeriod FROM sAssetManagement.tAssetMaster WHERE Id = @rAssetId), (SELECT NextMaintenanceDate FROM sAssetManagement.tAssetMaster WHERE Id = @rAssetId))),
			@rNextMaintenenceDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rDocumentNo,
			@rDocumentDate,
			@rOrgId,
			@rStoreLocationId
		)
		SET @rNumber = @rNumber
	
		IF @rNextMaintenenceDate <= sCommon.fGetDate() 
		BEGIN
			UPDATE sAssetManagement.tAssetMaster
				SET LastMaintenanceDate = @rMaintenenceDate, NextMaintenanceDate = (SELECT DATEADD(dd, (SELECT MaintenancePeriod FROM sAssetManagement.tAssetMaster WHERE Id = @rAssetId), sCommon.fGetDate())),
					LastServiceCost = @rMaintenenceCost,
					TotalServiceCost = sAssetManagement.tAssetMaster.TotalServiceCost + @rMaintenenceCost
					WHERE Id = @rAssetId
		END
		ELSE
		BEGIN
			UPDATE sAssetManagement.tAssetMaster
				SET LastMaintenanceDate = @rMaintenenceDate, NextMaintenanceDate =  @rNextMaintenenceDate,
					LastServiceCost = @rMaintenenceCost,
					TotalServiceCost = sAssetManagement.tAssetMaster.TotalServiceCost + @rMaintenenceCost
					WHERE Id = @rAssetId
		END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pMaintenenceGet]
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Number,
			AssetId,
			MaintenenceDate,
			MaintenenceBy,
			MaintenenceReason,
			MaintenenceCost,
			NextMaintenenceDate,
			CreatedUserId,
			CreatedDateTime
	   FROM sAssetManagement.tMaintenence
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pMaintenenceModify]
	@rId [int],
	@rNumber [nvarchar](20),
	@rAssetId [int],
	@rMaintenenceDate [datetime],
	@rMaintenenceBy [nvarchar](300),
	@rMaintenenceReason [nvarchar](300),
	@rMaintenenceCost [decimal](22, 6),
	@rNextMaintenenceDate [datetime]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAssetManagement.tMaintenence
		SET 
			Number = @rNumber,
			AssetId = @rAssetId,
			MaintenenceDate = @rMaintenenceDate,
			MaintenenceBy = @rMaintenenceBy,
			MaintenenceReason = @rMaintenenceReason,
			MaintenenceCost = @rMaintenenceCost,
			NextMaintenenceDate = @rNextMaintenenceDate
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To add records to sAssetManagement.tMovement table
	Created date     : 15 Jan 2012
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : To departmentid added as input parameter to detail sp
	Test script      : EXECUTE sAssetManagement.pMovementAdd  @rMovementDate = 0, @rRemark = '', @rFromLocationId = 0, @rToLocationId = 0, @rCreatedUserId = 0, @rMovementDetailXml = '', @rId = 0, @rFromDepartmentId = 0, @rToDepartmentId = 0, @rOwnerId = 0
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sAssetManagement].[pMovementAdd]
	(
		@rOrgId SmallInt = 0,
		@rMovementDate Date,
		@rRemark Nvarchar(300),
		@rFromLocationId Int,
		@rToLocationId Int,
		@rFromDepartmentId Int,
		@rToDepartmentId Int,
		@rCreatedUserId BigInt,
		@rOwnerId bigInt = 0,
		@rStoreLocationId int,
		@rMovementDetailXml Nvarchar(Max),
		@rId Int out
	)
AS

SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssetManagement.tMovement', 0, 1, 1,@outNextNumber = @lNextNumber output

	--DECLARE @loNextNumber Nvarchar(20)
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 88,@rStoreLocationId=@rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
			
	--IF (@loNextNumber IS NULL)
	--	BEGIN
	--		RAISERROR('5000', 15, 106)
	--		RETURN
	--	END
	DECLARE @rNumber [nvarchar](20)
SELECT @rNumber = ISNULL(max(Number),0)   FROM sAssetManagement.tMovement WHERE StoreLocationId = @rStoreLocationId
SET @rNumber = @rNumber + 1

	INSERT INTO sAssetManagement.tMovement
		(
			Id,
			Number,
			MovementDate,
			Remark,
			FromLocationId,
			ToLocationId,
			FromDepartmentId,
			ToDepartmentId,
			OwnerId,
			CreatedUserId,
			CreatedDateTime,
			OrgId,
			StoreLocationId
		)
	
VALUES
		(
			@lNextNumber,
			@rNumber,
			@rMovementDate,
			@rRemark,
			@rFromLocationId,
			@rToLocationId,
			@rFromDepartmentId,
			@rToDepartmentId,
			CASE WHEN @rOwnerId = 0 THEN NULL ELSE @rOwnerId END,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rStoreLocationId
		)
		
		SELECT @rId = ID FROM sAssetManagement.tMovement WHERE Number = @rNumber AND OrgId = @rOrgId 
		
		EXEC [sAssetManagement].[pMovementDetailAdd] @rOrgId, @rId, @rToLocationId, @rToDepartmentId, @rMovementDetailXml, @rCreatedUserId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pMovementDetailAdd]
	@rOrgId Int = 0,
	@rMovementId [int],
	@rToLocationId [int] = 0,
	@rToDepartmentId [int] = 0,
	@rMovementDetailXml [nvarchar](max),
	@rCreatedUserId [bigint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @loIdoc INT
	DECLARE @lCount INT
	DECLARE @lMovementDetailCurrentId INT 
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rMovementDetailXml
	EXEC sCommon.pTableRowIdGet @rOrgId, 'sAssetManagement.tMovementDetail', 1, 1, 1,@outNextNumber = @lMovementDetailCurrentId output


	INSERT INTO sAssetManagement.tMovementDetail
		(
			Id,
			MovementId,
			AssetId
		)
	SELECT  
		@lMovementDetailCurrentId + ROW_NUMBER() OVER (ORDER BY AssetId), 
		@rMovementId,	
		AssetId	
	FROM OPENXML (@loIdoc, '/AssetManagement/MovementDetail', 1)
		WITH ( 
				AssetId INT		
			  )
		
		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/AssetManagement/MovementDetail', 1)
				 WITH ( AssetId INT)
		SET @lMovementDetailCurrentId  = @lCount + @lMovementDetailCurrentId 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssetManagement.tMovementDetail', @rCurrentNumber = @lMovementDetailCurrentId 
		
		
		UPDATE sAssetManagement.tAssetMaster
		SET LocationId = @rToLocationId,
			DepartmentId = @rToDepartmentId,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		WHERE Id IN (SELECT AssetId FROM OPENXML (@loIdoc, '/AssetManagement/MovementDetail', 1)
								WITH ( 
										AssetId INT		
									  )
						)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pMovementDetailGet]
	@rOrgId [int],
	@rMovementId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT MD.Id,
			MD.MovementId,
			MD.AssetId,
			AM.Code,
			AM.Title,
			AM.ModelNumber,
			AM.Id AssetId
	   FROM 
			sAssetManagement.tMovementDetail MD
	   INNER JOIN
			sAssetManagement.tAssetMaster AM
		ON
			AM.Id = MD.AssetId
	  WHERE ((MovementId = @rMovementId) OR (@rMovementId = 0))
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pMovementDetailModify]
	@rId [int],
	@rMovementId [int],
	@rAssetId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAssetManagement.tMovementDetail
		SET 
			MovementId = @rMovementId,
			AssetId = @rAssetId
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pMovementGet]
	@rOrgId [int],
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT M.Id,
			M.Number,
			M.MovementDate,
			M.Remark,
			M.FromLocationId,
			M.ToLocationId,
			M.FromDepartmentId,
			M.ToDepartmentId,
			M.CreatedUserId,
			M.CreatedDateTime,
			ISNULL(EM.EmployeeName, '') EmployeeName,
			ISNULL(M.OwnerId, 0) OwnerId
	FROM 
		sAssetManagement.tMovement M
	LEFT JOIN
		sCommon.vEmployeeMaster EM
	ON
		EM.Id = M.OwnerId		
	WHERE ((M.Id = @rId) OR (@rId = 0)) AND M.OrgId = @rOrgId
	
	
	EXEC [sAssetManagement].[pMovementDetailGet] @rOrgId,  @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pMovementModify]
	@rId [int],
	@rNumber [nvarchar](20),
	@rMovementDate [date],
	@rRemark [nvarchar](300),
	@rFromLocationId [smallint],
	@rToLocationId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAssetManagement.tMovement
		SET 
			Number = @rNumber,
			MovementDate = @rMovementDate,
			Remark = @rRemark,
			FromLocationId = @rFromLocationId,
			ToLocationId = @rToLocationId
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssetManagement].[pMovementSearchGet]
	@rOrgId int,
	@rId int = 0,
	@rMovementDate Date = '',
	@rFromDepartmentId int = 0,
	@rFromLocationId int = 0,
	@rToDepartmentId int = 0,
	@rToLocationId int = 0,
	@rOwnerEmployeeId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT M.Id,
			M.Number,
			CONVERT(varchar, M.MovementDate, 105) as MovementDate,
			ISNULL(M.Remark,''),
			ISNULL(EM.EmployeeName, '') EmployeeName,
			ISNULL(M.OwnerId, 0) OwnerId,
			ISNULL((SELECT Title FROM sSetup.tDepartmentMaster WHERE Id = M.FromDepartmentId),'') as FromDepartment,
			ISNULL((SELECT Title FROM sSetup.tDepartmentMaster WHERE Id = M.ToDepartmentId),'') as ToDepartment,
			ISNULL((SELECT Title FROM sFixedAsset.tLocationMaster WHERE Id = M.FromLocationId),'') as FromLocation,
			ISNULL((SELECT Title FROM sFixedAsset.tLocationMaster WHERE Id = M.ToLocationId),'') as ToLocation,
			AM.Code as AssetTag,
			AM.Title as AssetTitle,
			ISNULL(AM.AssetCode,'') AS AssetCode
	FROM 
		sAssetManagement.tMovement M
		INNER JOIN sAssetManagement.tMovementDetail MD ON M.Id = MD.MovementId
		INNER JOIN sAssetManagement.tAssetMaster AM ON MD.AssetId = AM.Id
		LEFT JOIN sCommon.vEmployeeMaster EM ON EM.Id = M.OwnerId		
	WHERE 
		((M.Id = @rId) OR (@rId = 0)) AND M.OrgId = @rOrgId
		AND ((M.MovementDate = @rMovementDate) OR (@rMovementDate = ''))
		AND ((M.FromDepartmentId = @rFromDepartmentId) OR (@rFromDepartmentId = 0))
		AND ((M.FromLocationId = @rFromLocationId) OR (@rFromLocationId = 0))
		AND ((M.ToDepartmentId = @rToDepartmentId) OR (@rToDepartmentId = 0))
		AND ((M.ToLocationId = @rToLocationId) OR (@rToLocationId = 0))
		AND ((M.OwnerId = @rOwnerEmployeeId) OR (@rOwnerEmployeeId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pRecordManualEventAdd]
	@rNumber [nvarchar](20) OUTPUT,
	@rOrgId [int],
	@rAssetId [int],
	@rStatusId [smallint],
	@rRemark [nvarchar](300),
	@rCreatedUserId [bigint],
	@rEventDate [datetime],
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssetManagement.tRecordManualEvent', 0, 1, 1,@outNextNumber = @lNextNumber output

	--DECLARE @loNextNumber Nvarchar(20)
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 93, @rStoreLocationId=@rStoreLocationId,@rNextNumber = @loNextNumber OUTPUT
	
	--IF (@loNextNumber IS NULL)
	--	BEGIN
	--		RAISERROR('5000', 15, 106)
	--		RETURN
	--	END
	
	SELECT @rNumber = ISNULL(max(Number),0) FROM  sAssetManagement.tRecordManualEvent WHERE StoreLocationId = @rStoreLocationId
	SET @rNumber = @rNumber + 1
		
	INSERT INTO sAssetManagement.tRecordManualEvent
		(
			Id,
			Number,
			AssetId,
			StatusId,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			EventDate,
			OrgId,
			StoreLocationId
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rAssetId,
			@rStatusId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rEventDate,
			@rOrgId,
			@rStoreLocationId
		)
		SET @rNumber = @rNumber
		UPDATE sAssetManagement.tAssetMaster
			SET UsageStatusId = @rStatusId, UpdatedUserId = @rCreatedUserId			
		WHERE Id = @rAssetId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pRecordManualEventGet]
	@rOrgId [int],
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT RME.Id,
			Number,
			AssetId,
			RME.StatusId,
			Remark,
			RME.CreatedUserId,
			AM.Title AS AssetDescription,
			U.EmployeeName AS EventBy,
			RME.EventDate,
			AM.Code AS AssetCode,
			AM.Title AS AssetName,
			LM.Title AS LocationName,
			CM.Title AS CategoryName,
			AD.Title AS DepartmentName
			
	   FROM sAssetManagement.tRecordManualEvent RME
	   LEFT JOIN
	   sAssetManagement.tAssetMaster AM
	   ON RME.AssetId = AM.Id
	   INNER JOIN
		sFixedAsset.vExtLocationMaster LM
		ON
		AM.LocationId = LM.Id
		INNER JOIN sFixedAsset.tCategoryMaster CM
		ON CM.Id=AM.CategoryId 
		INNER JOIN sSetup.tDepartmentMaster AD
	ON	AD.Id=AM.DepartmentId
	   LEFT JOIN
			sSecurity.vExtUser U
		ON
			U.Id = RME.CreatedUserId
			
	  WHERE Number = @rNumber
	  AND RME.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pRecordManualEventModify]
	@rId [int],
	@rNumber [nvarchar](20),
	@rAssetId [int],
	@rStatusId [smallint],
	@rRemark [nvarchar](300)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sAssetManagement.tRecordManualEvent
		SET 
			Number = @rNumber,
			AssetId = @rAssetId,
			StatusId = @rStatusId,
			Remark = @rRemark
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pRptAssetAdjustmentGet]
	@rOrgId int,
	@rNumber [nvarchar](100) = 0,
	@rStoreLocationId int,
	@rFromDate date,
	@rToDate date
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
	  SELECT 
			@rNumber AS Number, 
			LM.Title AS StoreLocation,
			SIM.Code AS AssetTag,
			SIM.Title AS [Description],
			SIM.ModelNumber AS ModelNumber,
			SM1.Title AS OldStatus,
			SM.Title AS NewStatus,
			RM.Title AS Remark,			
			CM.Title AS Category,
			ODM.Title AS DepartmentTitle,
			@rFromDate AS FromDate,
			@rToDate AS ToDate,
			ASSTA.CreatedDateTime
			
	FROM sAssetManagement.tAssetAdjustmentDetail ASSTADJ	
	INNER JOIN sAssetManagement.tAssetAdjustment ASSTA
	ON 	ASSTADJ.AssetAdjustmentId = ASSTA.Id
	INNER JOIN sAssetManagement.tAssetAuditDetail AAD
	ON ASSTADJ.AssetAuditDetailId = AAD.Id
	INNER JOIN sAssetManagement.tAssetAudit AA
	ON  AAD.AssetAuditId = AA.Id
	INNER JOIN sFixedAsset.vExtLocationMaster LM
	ON  LM.Id = AA.LocationId
	INNER JOIN sAssetManagement.tAssetMaster SIM
	ON 	SIM.ID = AAD.AssetId
	INNER JOIN sCommon.tStatusMaster SM
	ON	SM.Id = ASSTADJ.StatusId
	INNER JOIN sCommon.tStatusMaster SM1
	ON	SM1.Id = AA.StatusId	
	LEFT JOIN sCommon.tReasonMaster RM
	ON	RM.Id = ASSTADJ.ReasonId
	INNER JOIN sFixedAsset.tCategoryMaster CM
	ON CM.Id = SIM.CategoryId
 --   INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
	--ON AD.DepartmentId = SIM.DepartmentID
	 	INNER JOIN sSetup.tDepartmentMaster ODM
	ON ODM.Id = SIM.DepartmentID
	
	WHERE
		ASSTA.Number = @rNumber 
		AND (ASSTA.OrgId = @rOrgId)
		AND (ASSTA.StoreLocationId=@rStoreLocationId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pRptAssetAuditListGet]
	@rAssetAuditId [int] = 0,
	@rOrgId int,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED BEGIN


                  
       SELECT 
                  AA.Number AS Number, 
                  LOC.Title AS Location,
                  Tas.CODE AS AssetTag,
                  Tas.Title AS AssetDescription,
                  Tas.ModelNumber,
                  AAD.AssetCheck AS AssetCheck,
                  STAT.title AS status,
                   Cat.Title AS Category,
                   AA.CreatedDateTime,
                   AA.AuditedBy,
            
                  (SELECT COUNT(*)FROM sAssetManagement.tAssetAudit AA
         INNER JOIN 
         sAssetManagement.tAssetAuditDetail AAD
         ON AA.Id = AAD.AssetAuditId WHERE  AA.Id = @rAssetAuditId AND AssetCheck = 0) AS MissingAssetsCount,
         ODM.Title AS DepartmentTitle
                  
         FROM sAssetManagement.tAssetAudit AA
         INNER JOIN 
         sAssetManagement.tAssetAuditDetail AAD
         ON AA.Id = AAD.AssetAuditId
         INNER JOIN
         sAssetManagement.tAssetMaster Tas ON AAD.AssetId = Tas.Id
         INNER JOIN  sFixedAsset.tCategoryMaster Cat
         ON TAS.CATEGORYID = CAT.ID
         INNER JOIN  sCommon.tStatusMaster STAT
         ON STAT.ID =  Tas.UsageStatusId 
         
          	INNER JOIN sSetup.tDepartmentMaster ODM
	     ON ODM.Id = Tas.DepartmentID
         
         --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
         --ON AD.DepartmentId = Tas.DepartmentID
         INNER JOIN  sFixedAsset.VextLocationMaster LOC
         ON LOC.ID = AA.LocationId
         
         WHERE (AA.Id = @rAssetAuditId) OR (@rAssetAuditId = 0)
         AND((AA.OrgId=@rOrgId) OR AA.OrgId=0)
         AND((AA.StoreLocationId=@rStoreLocationId) OR AA.StoreLocationId=0)
         
          
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssetManagement].[pRptAssetListCategoryWise]
	@rOrgId int,
	@rLocationId int = 0,
	@rCategoryId int = 0,
	@rStoreLocationId int,
	@rDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 
       SELECT 
				  DM.Title AS Department,
				  DM.Id AS DepartmentId,
				  LOC.Title AS Location,
				  LOC.Id AS LocationId,
                  CM.TITLE AS Category,
				  CM.Id AS CategoryId,
				  AM.Title AS AssetTitle,
				  AM.Code As AssetCode,
                  COUNT(AM.code) AS Quantity,
                  AM.Id AS AssetId
                  
            
         FROM sAssetManagement.tAssetMaster AM
			 INNER JOIN  sFixedAsset.tCategoryMaster CM ON AM.CATEGORYID = CM.ID
			 INNER JOIN  sCommon.tStatusMaster SM ON SM.ID =  AM.UsageStatusId 
			 INNER JOIN  sFixedAsset.VextLocationMaster LOC ON LOC.ID = AM.LocationId
			 INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = AM.DepartmentID
			 
        WHERE 
        AM.OrgId = @rOrgId 
        AND ((AM.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((AM.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((AM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) 
        AND((AM.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        
		Group By DM.Title,DM.Id,LOC.Title,LOC.Id,CM.TITLE,CM.Id,AM.Title,AM.Code,AM.Id
        ORDER BY  AM.Code  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAssetManagement].[pRptAssetMaintenanceListGet]
	@rOrgId [int] ,
	@rNumber nvarchar(100),
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	 SELECT 
			LOC.Title AS Location,
			AM.CODE AS AssetTag,
			AM.Title AS AssetDescription,
			STAT.title AS Status,
			Cat.TITLE AS Category,
			AMN.MaintenenceDate AS LastMaintenanceDate,
			AMN.NextMaintenenceDate AS NextMaintenanceDate,
			AM.IsCritical AS Critical,
			VM.Title AS Supplier,
			AD.Title AS DepartmentName,
			AMN.Number AS MaintenanceNumber,
			AMN.MaintenenceCost,
			AMN.MaintenenceBy,
			ISNULL(AM.AssetCode,'') AS AssetCode
			
	FROM
		sAssetManagement.tMaintenence AMN
	INNER JOIN
		sAssetManagement.tAssetMaster AM
	ON AMN.AssetId = AM.Id
	INNER JOIN sSetup.tDepartmentMaster AD
	ON AD.Id=AM.DepartmentId
	INNER JOIN  sFixedAsset.tCategoryMaster Cat
	ON AM.CategoryId = CAT.ID
	INNER JOIN  sCommon.tStatusMaster STAT
	ON STAT.ID =  AM.UsageStatusId 
	INNER JOIN  sFixedAsset.tLocationMaster LOC
	ON LOC.ID = AM.LocationId
	LEFT JOIN
	sProcurement.tVendorMaster VM
	ON VM.Id = AM.AmcVendorId
	
	WHERE (AMN.Number=@rNumber) OR (@rNumber = '')
	AND AMN.OrgId = @rOrgId
	AND AMN.StoreLocationId=@rStoreLocationId
	ORDER BY AMN.MaintenenceDate ASC
				 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pRptAssetMasterListGet]
	@rOrgId [int] ,
	@rAssetTag [int] = 0,
	@rAssetDescription [nvarchar](50) = '',
	@rModelNo [nvarchar](50) = '',
	@rManufacturer [nvarchar](50) = '',
	@rCategoryId [int] = 0,
	@rLocationId [int] = 0,
	@rCode [nvarchar](50) = '',
	@rStatusId [int] = 0,
	@rTag [int] = 0,
	@rFromDate [datetime] = '',
	@rToDate [datetime] = '',
	@rIscritical [bit] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DECLARE @lDepartmentId Int
SET @lDepartmentId = @rLocationId
BEGIN
      SELECT Tas.Id AS AssetTag,
                  Tas.CODE,
                  Tas.Title AS AssetDescription,
                  Tas.LocationId,
                  LOC.Title AS Location,
                  Tas.StatusId,
                  STAT.title AS status,
                  Tas.ModelNumber AS ModelNo,
                  Tas.CategoryId,
                  Cat.TITLE AS Category,
                  'AS' AS Manufacturer,
                  Tas.MaintenanceAlertPeriod,
                  day(Tas.NextMaintenanceDate) AS NextMaintenanceDate,
                  Tas.NextMaintenanceDate AS DueDate,
                  sCommon.fReportDateGet(CAST(ISNULL(Tas.NextMaintenanceDate, sCommon.fGetDate())AS DATETIME)) AS NextDate,
            sCommon.fReportDateGet(CAST(Tas.LastMaintenanceDate AS DATETIME)) AS lastDate,
            Tas.Iscritical,
             Cat.TITLE AS HCategory,             
                  STAT.title AS HTitle,
            sCommon.fReportDateGet(CAST(@rFromDate  AS DATETIME)) AS FromDate,
                  sCommon.fReportDateGet(CAST(@rToDate AS DATETIME)) AS ToDate,
                  @rModelNo AS ModelNo,
                  @rCode AS  HAssetTag,
                  @rAssetDescription AS HAssetDescription,
                  ODM.Title AS DeptName,
				  ISNULL(Tas.AssetCode,'') AS AssetCode
            
         FROM sAssetManagement.tAssetMaster Tas
         INNER JOIN  sFixedAsset.tCategoryMaster Cat
         ON TAS.CATEGORYID = CAT.ID
         INNER JOIN  sCommon.tStatusMaster STAT
         ON STAT.ID =  Tas.UsageStatusId 
         INNER JOIN  sFixedAsset.VextLocationMaster LOC
         ON LOC.ID = TAS.LocationId
         --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
         --ON AD.DepartmentId = Tas.DepartmentID
          	INNER JOIN sSetup.tDepartmentMaster ODM
      	ON ODM.Id = Tas.DepartmentID
         
        WHERE 
        Tas.OrgId = @rOrgId AND
        ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @lDepartmentId) OR (@lDepartmentId = 0)) 
        AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 0 AND Tas.UsageStatusId <> 124 )
        
        OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
        AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.Title = @rAssetDescription) OR (@rAssetDescription = '')) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))  
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.DepartmentId = @lDepartmentId) OR (@lDepartmentId = 0)) 
         AND  (CONVERT(NVARCHAR(10), DATEADD(DD,(- Tas.MaintenanceAlertPeriod), Tas.NextMaintenanceDate), 111)  <=  CONVERT(NVARCHAR(10), @rFromDate, 111) )  
        AND  (Tas.NextMaintenanceDate  >=  @rFromDate ) 
         AND((Tas.StoreLocationId=@rStoreLocationId) OR @rStoreLocationId=0)
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))) AND @rTag = 1 AND Tas.UsageStatusId <> 124  ) 
          OR ((((Tas.Id = @rAssetTag) OR (@rAssetTag = 0)) 
          AND ((Tas.Code = @rCode) OR (@rCode = '')) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0)) 
        AND ((Tas.ModelNumber = @rModelNo) OR (@rModelNo = '')) 
        AND ((Tas.DepartmentId = @lDepartmentId) OR (@lDepartmentId = 0)) 
        AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0)) 
        AND ((Tas.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((Tas.UsageStatusId = @rStatusId) OR (@rStatusId = 0))
        AND  (CONVERT(NVARCHAR(10), Tas.NextMaintenanceDate, 111)  >=  CONVERT(NVARCHAR(10), @rFromDate, 111) ) 
        AND (Tas.NextMaintenanceDate  <= (@rToDate + 1) )
        AND((Tas.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
        AND ((Iscritical = @rIscritical))) AND @rTag = 2 AND Tas.UsageStatusId <> 124 ) 

        ORDER BY  Tas.NextMaintenanceDate  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pRptAssetMissingListGet]
	@rOrgId [int],
	@rLocationId [int] = 0,
	@rCategoryId [int] = 0,
	@rReasonId [int] = 0,
	@rFromDate [datetime] = '',
	@rToDate [datetime] = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
      
       
            
            
       SELECT 
                  LOC.Title AS Location,
                  Tas.CODE AS AssetTag,
                  Tas.Title AS AssetDescription,
                  Tas.ModelNumber,
                  STAT.title AS status,
                  Cat.TITLE AS Category,
                  sCommon.fReportDateGet(CAST(@rFromDate AS DATETIME)) AS FromDate,
                  sCommon.fReportDateGet(CAST(@rToDate AS DATETIME)) AS ToDate,
                  RM.Title AS Notes,
                  Cat.Title AS Category,
                  ODM.Title AS DepartmentTitle,
                  AA.CreatedDateTime 
                  
                  
         FROM sAssetManagement.tAssetAudit AA
         INNER JOIN 
         sAssetManagement.tAssetAuditDetail AAD
         ON (AA.Id = AAD.AssetAuditId AND AAD.AssetCheck = 0)
         INNER JOIN
         sAssetManagement.tAssetAdjustmentDetail AAJD
         ON AAJD.AssetAuditDetailId = AAD.Id
         INNER JOIN
         sCommon.tReasonMaster RM
         ON RM.Id = AAJD.ReasonId
         INNER JOIN
         sAssetManagement.tAssetMaster Tas ON AAD.AssetId = Tas.Id
         INNER JOIN  sFixedAsset.tCategoryMaster Cat
         ON TAS.CATEGORYID = CAT.ID
         --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) AD
         --ON AD.DepartmentId = Tas.DepartmentID
          	INNER JOIN sSetup.tDepartmentMaster ODM
	    ON ODM.Id = Tas.DepartmentID
         INNER JOIN  sCommon.tStatusMaster STAT
         ON STAT.ID =  Tas.UsageStatusId 
         INNER JOIN  sFixedAsset.VextLocationMaster LOC
         ON LOC.ID = TAS.LocationId
         
         WHERE 
         AA.OrgId = @rOrgId 
         AND ((AA.StoreLocationId=@rStoreLocationId) OR(@rStoreLocationId=0))
         AND (sCommon.fReportDateGet(AA.CreatedDateTime) BETWEEN  sCommon.fReportDateGet(@rFromDate)  AND sCommon.fReportDateGet(@rToDate) 
         AND (TAS.LocationId = @rLocationId) OR (@rLocationId = 0))   
         AND ((AA.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((AA.CreatedDateTime < (@rToDate+1)) OR (ISNULL(@rToDate,'') = ''))     
		AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0))
		 AND ((RM.Id = @rReasonId) OR (@rReasonId = 0))
         --AND ((sCommon.fReportDateGet(AA.CreatedDateTime) BETWEEN sCommon.fReportDateGet(@rFromDate) AND sCommon.fReportDateGet(@rToDate)) AND ((Tas.CategoryId = @rCategoryId) OR (@rCategoryId = 0)))
         --AND ((sCommon.fReportDateGet(AA.CreatedDateTime) BETWEEN sCommon.fReportDateGet(@rFromDate) AND sCommon.fReportDateGet(@rToDate)) AND ((RM.Id = @rReasonId) OR (@rReasonId = 0)))
 
        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAssetManagement].[pValidateImportedAssetItem] 
	 @rXmlDoc nvarchar(MAX)
	,@rResult nvarchar(max)='' OUT
AS
BEGIN
	 
	SET NOCOUNT ON;
	SET @rXmlDoc=REPLACE(@rXmlDoc,'&','&amp;')
	DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lCount int = 0, @lValidationMsg nvarchar(max) = ''
DECLARE @lAssetTag nvarchar(50) = '',
			@lName nvarchar(100) = '',
			@lAssetCategory nvarchar(50) = '',
			@lModelNumber nvarchar(50) = '',
			@lSpecification nvarchar(300) = '',
			@lAccessories nvarchar(300) = '',
			@lIsMaintenance bit = null,
			@lServiceEntry date = null,
			@lMaitenancePeriod smallint = null,
			@lAlertPeriod smallint = null,
			@lCurrentDepartment nvarchar(50) ='',
			@lCurrentLocation nvarchar(50) ='',
			@lUsageStatus nvarchar(50) ='',
			@lLastServiceCost decimal(22,6) = null,
			@lTotalServiceCost decimal(22,6)  = null,
			@lLastMaintenanceDate datetime = null,
			@lNextMaintenanceDate datetime = null,
			@lIsCheckRequired bit = null,
			@lCheckFrequency nvarchar(50) = '',
			@lCheckList nvarchar(300) = null,
			@lCheckedLastDate date = null,
			--@lCheckedByUserId bigint = null,
			--@lCheckedStatus nvarchar(300) =  null,
			--@lCheckedRemark nvarchar(200) = null,
			@lIsRenewRequired bit = null,
			@lRenewLastDate date = null,
			@lRenewNextDate date = null,
			@lRenewRemark nvarchar(300) =  null,
			@lRenewCheckList nvarchar(300) = null,
			@lRenewAlertBeforeDays smallint = null,
			@lAssetCategoryId bigint = 0,
			@lCurrentDepartmentId bigint = 0,
			@lCurrentLocationId bigint = 0,
			@lUsageStatustId bigint = 0,
			@lCheckFrequencyId bigint = 0,
			@lCheckedStatusId bigint = 0,
			@lQuantity nvarchar = 0,
			@lValidateDate nvarchar(30) = '',
			--@lAssetCode nvarchar(50) = '',
			@lWarrantyDate date = null
	BEGIN TRY
			EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	CREATE TABLE #tempTable  
	(
			Id bigint identity,
			AssetTag nvarchar(50),
			Name nvarchar(100),
			AssetCategory nvarchar(50),
			ModelNumber nvarchar(50),
			Quantity nvarchar NOT null,
			Specification nvarchar(300),
			Accessories nvarchar(300),
			IsMaintenance bit null,
			ServiceEntry date null,
			MaitenancePeriod smallint null,
			AlertPeriod smallint null,
			CurrentDepartment nvarchar(50),
			CurrentLocation nvarchar(50),
			UsageStatus nvarchar(50),
			LastServiceCost decimal(22,6) null,
			TotalServiceCost decimal(22,6) null,
			LastMaintenanceDate datetime null,
			NextMaintenanceDate datetime null,
			IsCheckRequired bit null,
			CheckFrequency nvarchar(50),
			CheckList nvarchar(300) null,
			CheckedLastDate date null,
			--CheckedByUserId bigint null,
			--CheckedStatus nvarchar(300) null,
			--CheckedRemark nvarchar(200) null,
			IsRenewRequired bit null,
			RenewLastDate date null,
			RenewNextDate date null,
			RenewRemark nvarchar(300) null,
			RenewCheckList nvarchar(300) null,
			RenewAlertBeforeDays smallint null,
			--AssetCode nvarchar(50) null,
			WarrantyDate date null
	)

	INSERT INTO #tempTable
	(
			AssetTag,
			Name,
			AssetCategory,
			ModelNumber,
			Quantity,
			Specification,
			Accessories,
			IsMaintenance,
			ServiceEntry,
			MaitenancePeriod,
			AlertPeriod,
			CurrentDepartment,
			CurrentLocation,
			UsageStatus,
			LastServiceCost,
			TotalServiceCost,
			LastMaintenanceDate,
			NextMaintenanceDate,
			IsCheckRequired,
			CheckFrequency,
			CheckList,
			CheckedLastDate,
			--CheckedByUserId,
			--CheckedStatus,
			--CheckedRemark,
			IsRenewRequired,
			RenewLastDate,
			RenewNextDate,
			RenewRemark,
			RenewCheckList,
			RenewAlertBeforeDays,
			--AssetCode,
			WarrantyDate
	)

	SELECT *
			--A.AssetTag,
			--A.Name,
			--A.AssetCategory,
			--A.ModelNumber,
			--A.Quantity,
			--A.Specification,
			--A.Accessories,
			--A.IsMaintenance,
			--A.ServiceEntry,
			--A.MaitenancePeriod,
			--A.AlertPeriod,
			--A.CurrentDepartment,
			--A.CurrentLocation,
			--A.UsageStatus,
			--A.LastServiceCost,
			--A.TotalServiceCost,
			--A.LastMaintenanceDate,
			--A.NextMaintenanceDate,
			--A.IsCheckRequired,
			--A.CheckFrequency,
			--A.CheckList,
			--A.CheckedLastDate,
			--A.CheckedByUserId,
			--A.CheckedStatus,
			--A.CheckedRemark,
			--A.IsRenewRequired,
			--A.RenewLastDate,
			--A.RenewNextDate,
			--A.RenewRemark,
			--A.RenewCheckList,
			--A.RenewAlertBeforeDays
			

			FROM OPENXML (@intDoc, '/Table/ImportAsset', 1)
	WITH
	(						
			AssetTag nvarchar(50) '@AssetTag',
			Name nvarchar(100) '@Name',
			AssetCategory nvarchar(50) '@AssetCategory',
			ModelNumber nvarchar(50) '@ModelNumber',
			Quantity nvarchar '@Quantity',
			Specification nvarchar(300) '@Specification',
			Accessories nvarchar(300) '@Accessories',
			IsMaintenance bit '@IsMaintenance',
			ServiceEntry date '@ServiceEntry',
			MaitenancePeriod smallint '@MaintenancePeriod',
			AlertPeriod smallint '@AlertPeriod',
			CurrentDepartment nvarchar(50)'@CurrentDepartment',
			CurrentLocation nvarchar(50)'@CurrentLocation',
			UsageStatus nvarchar(50)'@UsageStatus',
			LastServiceCost decimal(22,6) '@LastServiceCost',
			TotalServiceCost decimal(22,6) '@TotalServiceCost',
			LastMaintenanceDate datetime '@LastMaintenanceDate',
			NextMaintenanceDate datetime '@NextMaintenanceDate',
			IsCheckRequired bit '@IsCheckRequired',
			CheckFrequency nvarchar(50)'@CheckFrequency',
			CheckList nvarchar(300) '@CheckList',
			CheckedLastDate date '@CheckedLastDate',
			--CheckedByUserId bigint '@CheckedByUserId',
			--CheckedStatus nvarchar(300) '@CheckedStatus',
			--CheckedRemark nvarchar(200) '@CheckedRemark',
			IsRenewRequired bit '@IsRenewRequired',
			RenewLastDate date '@RenewLastDate',
			RenewNextDate date '@RenewNextDate',
			RenewRemark nvarchar(300) '@RenewRemark',
			RenewCheckList nvarchar(300) '@RenewCheckList',
			RenewAlertBeforeDays smallint '@RenewAlertBeforeDays',
			--AssetCode nvarchar(50) '@AssetCode',
			WarrantyDate date '@WarrantyDate'
	) A 

	--SELECT * FROM #tempTable

	EXEC sp_xml_removedocument @intDoc

DECLARE @lTotal int = 0
DECLARE @lValidationMsgAll nvarchar(max) = ''
SELECT @lTotal = COUNT(Id) FROM #tempTable
SELECT @lCount = 1
WHILE @lCount <= @lTotal 
BEGIN
	SELECT 
	@lAssetTag = AssetTag,
	@lName = Name,
	@lAssetCategory = AssetCategory,
	@lModelNumber = ModelNumber,
	@lQuantity = Quantity,
	@lSpecification = Specification,
	@lAccessories = Accessories,
	@lIsMaintenance = IsMaintenance,
	@lServiceEntry = ServiceEntry,
	@lMaitenancePeriod = MaitenancePeriod,
	@lAlertPeriod = AlertPeriod,
	@lCurrentDepartment = CurrentDepartment,
	@lCurrentLocation = CurrentLocation,
	@lUsageStatus = UsageStatus,
	@lLastServiceCost = LastServiceCost,
	@lTotalServiceCost = TotalServiceCost,
	@lLastMaintenanceDate = LastMaintenanceDate,
	@lNextMaintenanceDate = NextMaintenanceDate,
	@lIsCheckRequired = IsCheckRequired,
	@lCheckFrequency = CheckFrequency,
	@lCheckList = CheckList,
	@lCheckedLastDate = CheckedLastDate,
	--@lCheckedByUserId = CheckedByUserId,
	--@lCheckedStatus = CheckedStatus,
	--@lCheckedRemark = CheckedRemark,
	@lIsRenewRequired = IsRenewRequired,
	@lRenewLastDate = RenewLastDate,
	@lRenewNextDate = RenewNextDate,
	@lRenewRemark = RenewRemark,
	@lRenewCheckList =RenewCheckList,
	@lRenewAlertBeforeDays = RenewAlertBeforeDays,
	--@lAssetCode = AssetCode,
	@lWarrantyDate = WarrantyDate


	FROM #tempTable WHERE Id = @lCount
	
			SET @lAssetCategoryId = '' SET @lCurrentDepartmentId = '' SET @lCurrentLocationId = ''
			SET @lUsageStatustId = ''  SET @lCheckFrequencyId =''     SET @lCheckedStatusId = ''

			SELECT @lAssetCategoryId = Id FROM sFixedAsset.tCategoryMaster WHERE  Title = @lAssetCategory
			SELECT @lCurrentDepartmentId = Id FROM sSetup.tDepartmentMaster WHERE  Title = @lCurrentDepartment
			SELECT @lCurrentLocationId = Id FROM sFixedAsset.tLocationMaster WHERE  Title = @lCurrentLocation
			--SELECT @lUsageStatustId = Id FROM sFixedAsset.tCategoryMaster WHERE  Title = @lAssetCategory
			SELECT @lCheckFrequencyId = Id FROM sCommon.tCheckFrequencyMaster WHERE  Title = @lCheckFrequency
			--SELECT @lCheckedStatusId = Id FROM sCommon.tStatusMaster WHERE  Title = @lCheckedStatus
			
			SET @lValidationMsg = ''
			
			IF((@lCheckFrequencyId = '' OR LEN(@lCheckFrequencyId) = 0 OR @lCheckFrequencyId is null) AND (@lCheckFrequency != '' OR LEN(@lCheckFrequency) != 0 OR @lCheckFrequency is NOT null ))
			BEGIN
				IF(@lCheckFrequencyId != 0)
				BEGIN
					SET @lValidationMsg = 'CheckFrequency Type does not Exist,'
				END
			END	
			--IF(@lCheckFrequencyId = 0)
			--BEGIN
				--SET @lValidationMsg = 'CheckFrequency Type does not Exist,'
			--END
			--IF(@lCheckedStatusId = '' OR LEN(@lCheckedStatusId) = 0 OR @lCheckedStatusId is null)
			--BEGIN
				--SET @lValidationMsg = 'CheckedStatus Type does not Exist,'
			--END
			--IF(@lCheckFrequency = '' OR LEN(@lCheckFrequency) = 0 OR @lCheckFrequency is null)
			--BEGIN
				--SET @lValidationMsg = 'CheckFrequency value can not be null,'
			--END
			--print(@lUsageStatus)
			--IF(@lUsageStatus != 'Spare' AND @lUsageStatus != 'Deployed' AND @lUsageStatus != 'Maintenance' AND @lUsageStatus != 'Retired' AND @lUsageStatus = 'Removed')
			--BEGIN	
				--SET  @lValidationMsg = 'UsageStatus Type does not Exist,'
			--END
			IF(@lUsageStatus != 'Spare')
			BEGIN
				IF(@lUsageStatus != 'Deployed')
					BEGIN
						IF(@lUsageStatus != 'Maintenance')
							BEGIN
								IF(@lUsageStatus != 'Retired')
									BEGIN
										IF(@lUsageStatus != 'Removed')
											SET @lValidationMsg = 'UsageStatus Type does not Exist,'
									END
							END
					END
			END
			--print(@lUsageStatus)
			IF(@lUsageStatus = '' OR LEN(@lUsageStatus) = 0 OR @lUsageStatus is null)
			BEGIN
				SET @lValidationMsg = 'UsageStatus value can not be null,'
			END
			IF((@lCurrentLocationId = '' OR LEN(@lCurrentLocationId) = 0 OR @lCurrentLocationId is null) AND (@lCurrentLocation != '' OR LEN(@lCurrentLocation) != 0 OR @lCurrentLocation is NOT null) )
			BEGIN
				SET @lValidationMsg = 'CurrentLocation Type does not Exist,'
			END	
			IF(@lCurrentLocation = '' OR LEN(@lCurrentLocation) = 0 OR @lCurrentLocation is null)
			BEGIN
				SET @lValidationMsg = 'CurrentLocation value can not be null,'
			END
			IF((@lCurrentDepartmentId = '' OR LEN(@lCurrentDepartmentId) = 0 OR @lCurrentDepartmentId is null) AND (@lAssetCategory != '' OR LEN(@lAssetCategory) != 0 OR @lAssetCategory is NOT null))
			BEGIN
				SET @lValidationMsg = 'CurrentDepartment Type does not Exist,'
			END	
			IF(@lCurrentDepartment = '' OR LEN(@lCurrentDepartment) = 0 OR @lCurrentDepartment is null)
			BEGIN
				SET @lValidationMsg = 'CurrentDepartment value can not be null,'
			END
			IF ((@lAlertPeriod) > (@lMaitenancePeriod))
			BEGIN
				SET  @lValidationMsg = 'Alert Period can not be greater than Maintenance Period,'
            END
			IF(@lAlertPeriod = '' OR LEN(@lAlertPeriod) = 0 OR @lAlertPeriod is null)
			BEGIN
				SET @lValidationMsg = 'AlertPeriod value can not be null,'
			END
			IF(@lMaitenancePeriod = '' OR LEN(@lMaitenancePeriod) = 0 OR @lMaitenancePeriod is null)
			BEGIN
				SET @lValidationMsg = 'Maintenance Period value can not be null,'
			END
			IF(@lQuantity = '0')
			BEGIN
				SET @lValidationMsg = 'Quantity value can not be Zero,'
			END
			--IF(@lQuantity = '' OR LEN(@lQuantity) = 0 OR @lQuantity is null)
			--BEGIN
				--SET @lValidationMsg = 'Quantity value can not be null,'
			--END
			--SET @lValidateDate = @lServiceEntry
			print(@lServiceEntry)
			SET @lValidateDate = (SELECT  CONVERT(nvarchar(20), @lServiceEntry, 101))
			print(@lValidateDate)
			IF(ISDATE(@lValidateDate) = 0)
			BEGIN
				SET @lValidationMsg = 'ServiceEntry value must be in Date Formate(MM/dd/yyyy),'
				Print('Hi')
			END
			IF(@lServiceEntry = '' OR LEN(@lServiceEntry) = 0 OR @lServiceEntry is null)
			BEGIN
				SET @lValidationMsg = 'ServiceEntry value can not be null,'
			END
			IF((@lAssetCategoryId = '' OR LEN(@lAssetCategoryId) = 0 OR @lAssetCategoryId is null) AND (@lAssetCategory != '' OR LEN(@lAssetCategory) != 0 OR @lAssetCategory is NOT null))
			BEGIN
				SET @lValidationMsg = 'AssetCategory Type does not Exist,'
			END
			IF(@lAssetCategory = '' OR LEN(@lAssetCategory) = 0 OR @lAssetCategory is null)
			BEGIN
				SET @lValidationMsg = 'AssetCategory value can not be null,'
			END
			IF(@lName = '' OR LEN(@lName) = 0 OR @lName is null)
			BEGIN
				SET @lValidationMsg = 'Name value can not be null,'
			END
			IF CHARINDEX(' ', @lAssetTag) > 0
			BEGIN
				SET @lValidationMsg = 'AssetTag value does not accept Space in it,'
			END
			--IF(@lAssetCode = '' OR LEN(@lAssetCode) = 0 OR @lAssetCode is null)
			--BEGIN
			--	SET @lValidationMsg = 'AssetCode value can not be null,'
			--END
			
		SET @lCount = @lCount + 1;

		SELECT @lValidationMsg AS ValidationMsg
		SET @rResult = @lValidationMsg
END
    END TRY 

	BEGIN CATCH 
	SELECT -1 AS Result,error_message(),ERROR_LINE()
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[MISStudentSubjectAttendanceDashboardGet]

@rOrgGroupId int = 0,
@rOrgId int = 0,
@rCommonOrgGroupBatchId int = 0,
@rTypeId int = 0,
@rIsPercent bit = 0,
@rPresentId int = 2,
@rGenderId tinyint = 0,
@rDivisionId int = 0,
@rSubjectId int = 0,
@rAcademicId bigint = 0,
@rFromDate date = '',
@rToDate date = ''



WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 

	--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;


WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;

IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

	IF(@rTypeId = 1)-------------LEVEL 1
	BEGIN
		IF(@rIsPercent = 0)
		BEGIN
		SELECT 
				OM.Id AS OrgId,
				OM.Title AS OrganizationName,
				COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)As PresentCount,
				COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)As AbsentCount,
				COUNT(SR.IsPresent) AS Total
			FROM 
				sAttendance.tStudentRegister SR
				INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
				--Changes for Mantis Id: 0037215
				INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
			WHERE OM.OrgGroupId = @rOrgGroupId AND COGBM.Id = @rCommonOrgGroupBatchId
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			-- IsInContext
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title
		END
		ELSE IF(@rIsPercent = 1)
		BEGIN
			SELECT 
				OM.Id AS OrgId,
				OM.Title AS OrganizationName,
				CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)AS DECIMAL) * 100 / CAST(COUNT(SA.AcademicId) AS DECIMAL)AS DECIMAL(5,2)) AS PresentPercentage,
				CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)AS DECIMAL) * 100 / CAST(COUNT(SA.AcademicId) AS DECIMAL)AS DECIMAL(5,2)) AS AbsentPercentage,
				'100' AS Total 
			FROM 
				sAttendance.tStudentRegister SR
				INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
				--Changes for Mantis Id: 0037215
				INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
			WHERE OM.OrgGroupId = @rOrgGroupId AND COGBM.Id = @rCommonOrgGroupBatchId 
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			-- IsInContext
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title
		END
	END
	ELSE IF(@rTypeId = 2)-------------LEVEL 2
	BEGIN
		SELECT		
		SA.DivisionId,
		SA.ClassName + '-' + SA.DivisionName AS ClassName,
		SM.Id AS SubjectId,
		SM.Title AS SubjectName,
		COUNT(SA.AcademicId) AS Total,
		COUNT(CASE WHEN SO.GenderId = 1 THEN SA.AcademicId END) AS Male,
		COUNT(CASE WHEN SO.GenderId = 2 THEN SA.AcademicId END) AS Female
		,SA.DivisionOrder
		,SA.ClassOrderIndex
	FROM		
		sAttendance.tStudentRegister SR
		INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
		INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
		INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
		
	WHERE 
		SA.OrgId = @rOrgId AND COGBM.Id = @rCommonOrgGroupBatchId 
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = @rPresentId OR @rPresentId = 2)
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP BY 
		SA.DivisionId,SA.ClassName,SA.DivisionName,SM.Id,SM.Title,SA.ClassOrderIndex,SA.DivisionOrder --SA.OrderIndex add for mantis : 0042058
	ORDER BY 
		--SA.ClassName,SA.DivisionName,SM.Id --comment for mantis : 0042058
		SA.ClassOrderIndex,SA.DivisionOrder  --add for mantis : 0042058
	END
	ELSE IF(@rTypeId = 3)-------------LEVEL 3
	BEGIN
		IF(@rPresentId = 0)
		BEGIN
			SELECT
			SA.AcademicId, 
			SA.Code,
			SA.Name AS StudentName,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			100.00 - CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)AS DECIMAL) * 100 / (SELECT CAST(COUNT(SA1.AcademicId) AS DECIMAL)
		FROM sAttendance.tStudentRegister SR
			INNER JOIN sStudent.vStudentAcademic SA1 ON SR.AcademicId = SA1.AcademicId 
			INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA1.ClassId = CS.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA1.StudentId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA1.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tBatchMaster BM ON SA1.BatchId = BM.Id
		WHERE 
			SA1.OrgId = @rOrgId AND SA1.DivisionId = @rDivisionId AND  CS.SubjectId = @rSubjectId AND COGBM.Id = @rCommonOrgGroupBatchId 
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SO.GenderId = @rGenderId OR @rGenderId = 0)
			AND (SA1.AcademicId = SA.AcademicId) 
			-- IsInContext
			AND BM.IsInContext = 1
			)AS DECIMAL(5,2)) AS PresentPercentage

		FROM sAttendance.tStudentRegister SR
			INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
			INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
		WHERE 
			SA.OrgId = @rOrgId AND SA.DivisionId = @rDivisionId AND  CS.SubjectId = @rSubjectId AND COGBM.Id = @rCommonOrgGroupBatchId 
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SO.GenderId = @rGenderId OR @rGenderId = 0)
			AND (SR.IsPresent = @rPresentId OR @rPresentId = 2)
			-- IsInContext
			AND BM.IsInContext = 1
		GROUP BY 
			SA.AcademicId,SA.Code,SA.Name,SA.ClassName,SC.ParentContactNo
		ORDER BY 
			SA.AcademicId,SA.Code,SA.Name,SA.ClassName,SC.ParentContactNo
		END
	ELSE
	BEGIN
		SELECT
			SA.AcademicId, 
			SA.Code,
			SA.Name AS StudentName,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)AS DECIMAL) * 100 / (SELECT CAST(COUNT(SA1.AcademicId) AS DECIMAL)
		FROM sAttendance.tStudentRegister SR
			INNER JOIN sStudent.vStudentAcademic SA1 ON SR.AcademicId = SA1.AcademicId 
			INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA1.ClassId = CS.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA1.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA1.StudentId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA1.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tBatchMaster BM ON SA1.BatchId = BM.Id
		WHERE 
			SA1.OrgId = @rOrgId AND SA1.DivisionId = @rDivisionId AND  CS.SubjectId = @rSubjectId AND COGBM.Id = @rCommonOrgGroupBatchId 
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SO.GenderId = @rGenderId OR @rGenderId = 0)
			AND (SA1.AcademicId = SA.AcademicId) 
			-- IsInContext
			AND BM.IsInContext = 1
			)AS DECIMAL(5,2)) AS PresentPercentage

		FROM sAttendance.tStudentRegister SR
			INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
			INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
		WHERE 
			SA.OrgId = @rOrgId AND SA.DivisionId = @rDivisionId AND  CS.SubjectId = @rSubjectId AND COGBM.Id = @rCommonOrgGroupBatchId 
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SO.GenderId = @rGenderId OR @rGenderId = 0)
			AND (SR.IsPresent = @rPresentId OR @rPresentId = 2)
			-- IsInContext
			AND BM.IsInContext = 1
		GROUP BY 
			SA.AcademicId,SA.Code,SA.Name,SA.ClassName,SC.ParentContactNo
		ORDER BY 
			SA.AcademicId,SA.Code,SA.Name,SA.ClassName,SC.ParentContactNo
		END
	END
	ELSE IF(@rTypeId = 4)-------------LEVEL 4
	BEGIN
	IF(@rIsPercent = 0)
		BEGIN
			SELECT
			SM.Id AS SubjectId,
			SM.Title AS SubjectName,
			COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)As PresentCount,
			COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)As AbsentCount,
			COUNT(SA.AcademicId) AS Total
		FROM sAttendance.tStudentRegister SR
			INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
			INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId		
			INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id	
		WHERE 
			SA.OrgId = @rOrgId AND COGBM.Id = @rCommonOrgGroupBatchId
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))		
			AND SA.AcademicId = @rAcademicId
			-- IsInContext
			AND BM.IsInContext = 1
		GROUP BY 
			SM.Id,SM.Title
		ORDER BY 
			SM.Id,SM.Title
		END
	ELSE IF(@rIsPercent = 1)
		BEGIN
			SELECT
			SM.Id AS SubjectId,
			SM.Title AS SubjectName,
			CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)AS DECIMAL) * 100 / CAST(COUNT(SA.AcademicId) AS DECIMAL)AS DECIMAL(5,2)) AS PresentPercentage,
			CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)AS DECIMAL) * 100 / CAST(COUNT(SA.AcademicId) AS DECIMAL)AS DECIMAL(5,2)) AS AbsentPercentage,
			'100' AS Total
		FROM sAttendance.tStudentRegister SR
			INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
			INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id	
		WHERE 
			SA.OrgId = @rOrgId AND COGBM.Id = @rCommonOrgGroupBatchId
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))		
			AND SA.AcademicId = @rAcademicId
			-- IsInContext
			AND BM.IsInContext = 1
		GROUP BY 
			SM.Id,SM.Title
		ORDER BY 
			SM.Id,SM.Title
		END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pAbsentStudentDashboardGet]
	 
	 @rOrgGroupId int=0,
	 @rConfigurationValue int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	DECLARE @rStartDate date
	DECLARE @rEndDate date
	SET @rStartDate = getdate()
	SET @rEndDate = getdate() - @rConfigurationValue
	
	SELECT
		OM.Id AS OrgId,
		vSA.Code AS Code,
		vSA.Name AS StudentName,
		COUNT(SR.AcademicId) AS StudentCount
	FROM
		sAttendance.tStudentRegister SR 
		INNER JOIN sStudent.vStudentAllDetail vSA ON vSA.AcademicId = SR.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
	WHERE 
		OM.OrgGroupId = @rOrgGroupId
		AND vSA.IsActiveBatch = 1
		AND SR.IsPresent = 0
		AND (SR.AttendanceDate >= @rEndDate) AND (SR.AttendanceDate <= @rStartDate)
	GROUP BY OM.Id,vSA.Code,vSA.Name
	HAVING COUNT(SR.AcademicId) >= @rConfigurationValue
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pApplicableAttendanceTypeAdd]
	 
	@rOrgId int,
	@rAttendanceTypeId tinyint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 INSERT INTO sAttendance.tApplicableAttendanceType
		(
			OrgId,
			AttendanceTypeId 
		)
		VALUES
		(
			@rOrgId,
			@rAttendanceTypeId
		)		
	 	            
		SELECT @rOrgId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pApplicableAttendanceTypeGet]
          
           @rOrgId int
           
AS
SET NOCOUNT ON

BEGIN
	SELECT  ATM.Id as AttendanceTypeId,
			ATM.Title as AttendanceType,
			CASE WHEN AAT.AttendanceTypeId Is Null THEN 'False' ELSE 'True' END AS IsObsolete
		
  FROM sAttendance.tAttendanceTypeMaster ATM
	LEFT JOIN sAttendance.tApplicableAttendanceType AAT ON AAT.AttendanceTypeId=ATM.Id AND OrgId=@rOrgId
	order by ATM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAttendance].[pApplicableAttendanceTypeRemove]
	 @rOrgId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
    Delete From sAttendance.tApplicableAttendanceType where OrgId=@rOrgId
	SELECT 1 AS Result
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

--Select * from sAttendance.tTempAttendance

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

SELECT  @lOrgId=RG.OrgId,
--@lSchoolRemark1 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark1,'')  ELSE RG.SchoolRemark1 END,
--@lSchoolRemark2= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark2,'')  ELSE RG.SchoolRemark2 END,
--@lSchoolRemark3 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark3,'')  ELSE RG.SchoolRemark3 END,
@lSchoolRequiredSignature= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRequiredSignature,'')  ELSE RG.SchoolRequiredSignature END 
 
FROM sCommon.tReportRemarkGroupMaster RGM LEFT JOIN sCommon.tReportRemarkGroupOrg RG ON RGM.Id = RG.ReportRemarkGroupId AND RG.OrgId = @rOrgId AND RG.ReportRemarkGroupId=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	Declare @Days int 
 	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(500),
	Code nvarchar(500),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(500),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(500),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(500),
	DivisionName nvarchar(500),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(500),
	DateOfBirth date,
	Religion nvarchar(500),
	MotherName nvarchar(500),
	FamilyCast nvarchar(100),
	Gender tinyint,
	CastCategory nvarchar(50)

)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName,
	DateOfBirth,
	Religion,
	MotherName,
	FamilyCast,
	Gender,
	CastCategory
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName,
	 SO.DateOfBirth,
	 RE.Title As Religion,
	 Sf.MotherName,
	 SO.FamilyCast,
	 --,
	 --SR.IsPresent
	 SO.GenderId,
	 ISNULL(CCM.Title,'') AS CastCategory
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId 
            INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN  sStudent.tStudentFamily SF ON Sf.StudentId=Sa.StudentID
            LEFT JOIN sCommon.tReligionMaster RE On RE.Id=SO.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))
	           AND ((SA.Code >= @rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	           AND ((SA.Code <= @rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
	           AND  ISNULL(EM.IsOtherUser,0) = 0 
				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

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

--Select * from #TempDaysTempTable
 

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

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

			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
		LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS AUCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 0	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

			GROUP BY A.Id
    ) ABU ON ABU.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS TotalPresent  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
	        AND
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

			GROUP BY A.Id
    ) AA ON AA.AcademicId = PivotTable.AcademicId
 
    --ORDER BY CASE When @rOrderBy = 0 then RollNo
	   --           When @rOrderBy = 1 then Code
				
			 -- End

 ORDER BY CASE WHEN @rOrderBy = 0 then RollNo END,
		  CASE WHEN @rOrderBy = 1 then (CASE ISNUMERIC(Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(Code)) + Code ELSE Code  END)
		  END
 

select * from #TempDaysTempTable
 				
drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	


	--SELECT  
	--		Convert(date,'') AS LastDate,
	--		Convert(date,'') AS LeftDate,
 --           '' AS Builder1,
	--		'' AS Builder2,
	--		Convert(bigint,0) AS AcademicId,
	--		'' AS ClassDivisionTitle,
	--		'' AS Code,
	--		0 as RollNo,
	--		'' AS Name,
	--		0 as AttendanceTypeId,
	--		0 as ForYear,
	--		0 as ForMonth,
	--		0 as ClassId,
	--		'' as ClassName,
	--		0 as DivisionId,
	--		'' as DivisionName,
	--		'' as ForMonthInWord,
	--		0 AS PresentCount,
	--		0 AS AbsentUpto,
	--		0 AS AttendanceCount,
	--	    0 As  AbsentCount,
	--	    0 As  PresentUpto,
	--	    0 as ClassOrderIndex,
	--	    0 as DivisionOrderIndex,
	--	    '' as FooterSignature,
	--		0 AS TotalPresent,
	--		'' AS P1,
	--		'' AS P2,
	--		'' AS P3,
	--		'' AS P4,
	--		'' AS P5,
	--		'' AS P6,
	--		'' AS P7,
	--		'' AS P8,
	--		'' AS P9,
	--		'' AS P10,
	--		'' AS P11,
	--		'' AS P12,
	--		'' AS P13,
	--		'' AS P14,
	--		'' AS P15,
	--		'' AS P16,
	--		'' AS P17,
	--		'' AS P18,
	--		'' AS P19,
	--		'' AS P20,
	--		'' AS P21,
	--		'' AS P22,
	--		'' AS P23,
	--		'' AS P24,
	--		'' AS P25,
	--		'' AS P26,
	--		'' AS P27,
	--		'' AS P28,
	--		'' AS P29,
	--		'' AS P30,
	--		'' AS P31,
	--		'' as EmployeeName ,
 --           0 AS DaysInMonth,
	--		Convert(date,'') AS DateOfBirth,
	--		'' as Religion,
	--		'' as MotherName,
	--		'' as FamilyCast,
	--		0 as Gender,
	--		'' as CastCategory



	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- prc_d 'sAttendance.pAttenanceRegisterGet_HTML'
-- exec sAttendance.pAttenanceRegisterGet_HTML '','',1,1001,4,2014,100100001,100100001
-- drop proc sAttendance.pAttenanceRegisterGet_HTML
CREATE OR ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet_HTML]
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='', 
@rAttendanceTypeId smallint,
@rOrgId int,
@rForMonth smallint,
@rForYear smallint,
@rClassId int=0,
@rDivisionId int=0,
@rBatchId int = 0,
@rStudentCode nvarchar(20)='',
@rDepartmentId int = 0,
@rAcademicId bigint = 0,
@rs varchar(max)
AS
BEGIN
DECLARE @lFirstDate Date
SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
DECLARE @AttendanceRegistertempTable table
(
	AID int identity(1,1),ClassDivisionTitle Nvarchar(50),Code nvarchar(50),RollNo int,AcademicId bigint,Name nvarchar(50),AttendanceTypeId int,
	ForYear int,ForMonth int,ForMonthInWord nvarchar(100),ClassId int,DivisionId int,ClassName nvarchar(50),DivisionName nvarchar(50),
	IsPresent int,DayPart int,LeftDate date,ClassOrderIndex int,DivisionOrderIndex int,FooterSignature nvarchar(500),StatusId int,
	AttendanceDate date,IsOnPresent int
)
Insert INTO @AttendanceRegistertempTable
(
	ClassDivisionTitle,Code,RollNo,AcademicId,Name,AttendanceTypeId,ForYear,ForMonth,ForMonthInWord,ClassId,DivisionId,ClassName,DivisionName,
	IsPresent,DayPart,LeftDate,ClassOrderIndex,DivisionOrderIndex,FooterSignature,StatusId,AttendanceDate,IsOnPresent 			
)
Select ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,SA.Code,SA.RollNo,SA.AcademicId,SA.Name,SR.AttendanceTypeId,
YEAR(SR.AttendanceDate) AS ForYear,MONTH(SR.AttendanceDate) AS ForMonth,DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,SA.ClassId,
SA.DivisionId,SA.ClassName,Sa.DivisionName,SR.IsPresent AS IsPresent,
day(SR.AttendanceDate) AS DayPart,A.LeftDate,CM.OrderIndex AS ClassOrderIndex,DM.OrderIndex As DivisionOrderIndex,OM.FooterSignature,
SA.StatusId,'' As AttendanceDate,SR.IsPresent
from sStudent.vStudentAcademic SA INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId 
INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId 
INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId 
INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
WHERE ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0)) AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
AND ((A.LeftDate >= @lFirstDate) OR ISNULL(A.LeftDate,'') = '')
AND  ISNULL(EM.IsOtherUser,0) = 0 	

DECLARE @lResult VARCHAR(max)='',@lweekoff varchar(max)='',@lHeader VARCHAR(MAX)='',@tblcnt int,@i int
SELECT @lweekoff = @lweekoff + WeekOffs + ',' from sSetup.tOrganizationMaster where id=@rOrgId

SELECT @lHeader = dbo.fgetResultinTD(sCommon.fGetDaysInMonth(@rForMonth,@rForYear),@lweekoff,@rs,0,0,2)
SELECT @tblcnt = Count(*),@i=1 from @AttendanceRegistertempTable
DECLARE @tblcnttmp TABLE(cid INT IDENTITY(1,1),studentid BIGINT,acnt INT,pcnt INT)
DECLARE @acid BIGINT,@pc int,@ac int
SELECT @pc=0,@ac=0

WHILE @i<=@tblcnt
BEGIN
	SELECT @acid=AcademicId,@pc = CASE WHEN IsPresent = 1 THEN (@pc + 1) ELSE @pc END,
	@ac = CASE WHEN IsPresent = 0 THEN (@ac + 1) ELSE @ac END
	FROM @AttendanceRegistertempTable WHERE AID=@i
	
	INSERT INTO @tblcnttmp(studentid,acnt,pcnt)
	SELECT @acid,@ac,@pc
	
	SELECT @ac=0,@pc=0
	
	SELECT @i=@i+1
END

SELECT @lResult = @lResult + '<tr><td>' + CONVERT(VARCHAR,RollNo) + '</td><td style="width:5%;">' + Code + '</td>
<td style="width:10%;">' + Name + '</td>'+ dbo.fgetResultinTD(sCommon.fGetDaysInMonth(@rForMonth,@rForYear),@lweekoff,@rs,pres,dt,1) +'
<td>' + CONVERT(varchar,acnt) + '</td><td>' + CONVERT(varchar,pcnt) + '</td><td></td><td></td></tr>'
FROM 
(
	Select ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,Code,RollNo,AcademicId,Name,AttendanceTypeId,
	YEAR(AttendanceDate) AS ForYear,MONTH(AttendanceDate) AS ForMonth,DATENAME(month, AttendanceDate) AS ForMonthInWord,
	ClassId,DivisionId,ClassName,DivisionName,IsPresent,day(AttendanceDate) AS DayPart,LeftDate,ClassOrderIndex,pcnt,acnt,
	DivisionOrderIndex,FooterSignature,IsPresent as pres,DayPart as dt FROM @AttendanceRegistertempTable,@tblcnttmp
	WHERE studentid = AcademicId
) AS SourceTable 
PIVOT
(	
	MIN(ispresent) FOR DayPart IN ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
LEFT JOIN
(
	Select AcademicId AS AcademicId,COUNT(1) AS TCount FROM @AttendanceRegistertempTable		    
	GROUP BY  AcademicId
) TC ON TC.AcademicId = PivotTable.AcademicId    
LEFT JOIN
(
	Select AcademicId AS AcademicId, COUNT(1) AS ACount FROM @AttendanceRegistertempTable 
	WHERE IsOnPresent = 0 AND ( StatusId = 1) GROUP BY  AcademicId
) AC ON AC.AcademicId = PivotTable.AcademicId
LEFT JOIN
(
	SELECT AcademicId AS AcademicId, COUNT(1) AS PCount from @AttendanceRegistertempTable
	WHERE AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
	AND  IsOnPresent = 1 GROUP BY AcademicId
) PC ON PC.AcademicId = PivotTable.AcademicId order by RollNo;

SELECT ISNULL(@lResult,'') as Grid,@lweekoff as [week],@lHeader as Header
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGetNew]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0
	WITH EXECUTE AS CALLER
AS	
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	Declare @Days int 
	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	
BEGIN 
CREATE Table #AttendanceRegistertempTable
(
	 
	ClassDivisionTitle Nvarchar(500),
	Code nvarchar(500),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(500),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(500),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(500),
	DivisionName nvarchar(500),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int,
	AdmissionDate date 
	 
 
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId ,
	AdmissionDate 
	 
  
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	 OM.FooterSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 A.AdmissionDate 
	 
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
			 
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			   AND  ISNULL(EM.IsOtherUser,0) = 0 
				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days 
BEGIN

INSERT INTO #TempDaysTempTable
(
	DayPart,
    Value
)
SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](@rForYear,@rForMonth,@li,@rBatchId,@rClassId,@rDivisionId,'',@rOrgId) 
 
 
SET @li = @li + 1

END
 
 
--DECLARE @TotalRecords int,@lpaging varchar(max)='',@PageSize int =100
--SELECT @TotalRecords = count(*)	 from #AttendanceRegistertempTable
--SELECT @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@PageIndex,@TotalRecords,@PageSize)

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
				
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ISNULL(AAC.AACount,0) As  AbsentUpto,
		       
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
	 			   sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),LeftDate,[1]) AS P1,
	 	 
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02'),LeftDate,[2]) AS P2,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03'),LeftDate,[3]) AS P3,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04'),LeftDate,[4]) AS P4,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05'),LeftDate,[5]) AS P5,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06'),LeftDate,[6]) AS P6,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07'),LeftDate,[7]) AS P7,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08'),LeftDate,[8]) AS P8,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09'),LeftDate,[9]) AS P9,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10'),LeftDate,[10]) AS P10,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11'),LeftDate,[11]) AS P11,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12'),LeftDate,[12]) AS P12,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13'),LeftDate,[13]) AS P13,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14'),LeftDate,[14]) AS P14,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15'),LeftDate,[15]) AS P15,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16'),LeftDate,[16]) AS P16,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17'),LeftDate,[17]) AS P17,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18'),LeftDate,[18]) AS P18,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19'),LeftDate,[19]) AS P19,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20'),LeftDate,[20]) AS P20,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21'),LeftDate,[21]) AS P21,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22'),LeftDate,[22]) AS P22,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23'),LeftDate,[23]) AS P23,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24'),LeftDate,[24]) AS P24,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25'),LeftDate,[25]) AS P25,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26'),LeftDate,[26]) AS P26,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27'),LeftDate,[27]) AS P27,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28'),LeftDate,[28]) AS P28,
			CASE WHEN @Days>=29 THEN  sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29'),LeftDate,[29])end AS P29,
			CASE WHEN @Days>=30 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30'),LeftDate,[30]) end AS P30,
		    CASE WHEN @Days>=31 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31'),LeftDate,[31]) end AS P31,
		 
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth
,0 Ispresent,
0 AS AttendanceTagId 
  
--,AttendanceTagId

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

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 -- exec [sAttendance].[pAttenanceRegisterGetNew] '','',1,1001,7,2016,100100001,100100001,100100114,0,0,1
CREATE OR ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGetNew1]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
BEGIN 
CREATE Table #AttendanceRegistertempTable
(
	 
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int 
 
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId 
  
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	 OM.FooterSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 NULL AS AttendanceTagId
	 
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			   AND  ISNULL(EM.IsOtherUser,0) = 0 
				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=31
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

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

--DECLARE @TotalRecords int,@lpaging varchar(max)='',@PageSize int =100
--SELECT @TotalRecords = count(*)	 from #AttendanceRegistertempTable
--SELECT @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@PageIndex,@TotalRecords,@PageSize)

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

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

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceDataVerifyGet]
	 	 
		@rClassId int,
		@rDivisionId int,
		@rYear int,
		@rMonth int,
		@rBatchId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SELECT 
			A.RollNo,
			A.Code,
			A.Name,
			A.AdmissionDate,
			A.LeftDate,
			A.Gender,
			[sAttendance].[fAttendanceTotalDayGet] (A.AcademicId,@rMonth,@rYear,1) + [sAttendance].[fAttendanceTotalDayGet] (A.AcademicId,@rMonth,@rYear,2) AS TotalDays,
			[sAttendance].[fAttendanceTotalDayGet] (A.AcademicId,@rMonth,@rYear,1) AS PresentDays,
			[sAttendance].[fAttendanceTotalDayGet] (A.AcademicId,@rMonth,@rYear,2) AS AbsentDays,
			[sAttendance].[fAbsentDaysGet](@rMonth,@rYear,1,0,A.AcademicId) AS AbsentDate,
			ISNULL(SS.WorkingDays,MS.WorkingDays) AS WorkingDays,
			[sAttendance].[fHolidayForMonthGet] (@rMonth,@rYear,A.BatchId,@rDivisionId) AS HolidayDate,
			LEN([sAttendance].[fHolidayForMonthGet] (@rMonth,@rYear,A.BatchId,@rDivisionId)) - LEN(REPLACE([sAttendance].[fHolidayForMonthGet] (@rMonth,@rYear,A.BatchId,@rDivisionId),',','')) AS  HolidayCount
		FROM 
			sStudent.vStudentAllDetail A
			LEFT JOIN [sAttendance].[tMonthlySetup] MS ON MS.BatchId = A.BatchId AND MS.ClassId = A.ClassId AND MS.ForMonth = @rMonth AND MS.ForYear = @rYear
			LEFT JOIN [sAttendance].[tStudentSetup] SS ON SS.AcademicId = A.AcademicId AND SS.ForMonth = @rMonth AND SS.ForYear = @rYear
		WHERE 
			A.ClassId=@rClassId AND A.DivisionId=@rDivisionId AND A.BatchId=@rBatchId
		ORDER BY A.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceFollowupDetailGet]
	 	 
	 	 @rClassId int=0,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rFollowupDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @rPresentStatus int,
		 @rCode nvarchar(20)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT
	SA.AcademicId, 
	SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
	SA.Code,
	SA.RollNo,
	SA.Name,
	SC.PresentContactNo,
	SC.PermanentContactNo,
	SC.EmergencyContactNo,
	SC.ParentContactNo,
	SC.StudentContactNo,
	--AF.Remark,
	CASE WHEN (ISNULL((SELECT 1 FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate),0)
	= 1 AND (AF.Remark IS NULL OR AF.Remark = '')) THEN (SELECT LeaveReason FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate)
	ELSE (
	replace (
	replace (
	replace (
	replace (
	replace (
	replace(AF.Remark,'\n','<br />'),
	'#amp;','&'),
	'#gt;','>'),
	'#quot;','\"'),
	'#lt;','<'),
	'#39;','''')) END AS Remark,
	ISNULL((SELECT 1 FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate),0) AS IsOnLeave
	,ISNULL(SA.StudentId, 0) AS StudentId
	FROM
	sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
	--AND (SR.AttendanceTypeId = @rAttendanceTypeId)
	--AND (SR.AttendanceDate = @rFollowupDate)
	LEFT JOIN sAttendance.tAttendanceFollowup AF ON AF.AcademicId = SA.AcademicId AND SR.AttendanceTypeId = AF.AttendanceTypeId AND SR.AttendanceDate  = AF.FollowupDate
	LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
 
	WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
		  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  AND (SA.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND SR.IsPresent = @rPresentStatus
		  AND (AD.AdmissionDate <= @rFollowupDate)
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
		  AND (SR.AttendanceTypeId = @rAttendanceTypeId)
		  AND (SR.AttendanceDate = @rFollowupDate)
	ORDER BY SA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceFollowupListGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rFromDate date,
		 @rToDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @rPresentStatus int,
		 @rCode nvarchar(20)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT
	SA.AcademicId, 
	SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
	SA.Code,
	SA.RollNo,
	SA.Name,
	SC.PresentContactNo,
	SC.PermanentContactNo,
	SC.EmergencyContactNo,
	SC.ParentContactNo,
	SC.StudentContactNo,
	AF.Remark,
	AF.AttendanceTypeId AS AttendanceTypeId,
	AF.FollowupDate,
	AF.IsPresent,
	--(Select ISNULL(AF.Remark,'') FROM sAttendance.tAttendanceFollowup AF WHERE SA.AcademicId = AF.AcademicId AND AF.AttendanceTypeId=1 AND (AF.FollowupDate=@rFollowupDate))AS Remark
	--AF.Remark
	(isnull(SC.PresentStreetOne,'')+' '+isnull(SC.PresentStreetTwo,'')+' '+isnull(SC.PresentStreetThree,'')+' '+isnull(SC.PresentCity,'')+' '+isnull(SC.PresentState,'')+' '+isnull(SC.PresentCountry,'')) as PresentAdress		--Mantis: 28987

	FROM
	sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
	INNER JOIN sAttendance.tAttendanceFollowup AF ON SA.AcademicId = AF.AcademicId
	LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
 
	WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
		  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  AND (SA.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND ((AF.IsPresent = @rPresentStatus) OR (@rPresentStatus= -1))
		  AND (AF.FollowupDate >= @rFromDate) AND (AF.FollowupDate <= @rToDate)
		  AND ((AF.AttendanceTypeId= @rAttendanceTypeId) OR (@rAttendanceTypeId = 0))
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceFollowupPortalGet]
	 	 @rClassId int=0,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rFollowupDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @rPresentStatus int,
		 @rCode nvarchar(20)='',
		 @rIsEditMode bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT
		SA.AcademicId, 
		SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
		SA.Code,
		SA.RollNo,
		SA.Name,
		SC.PresentContactNo,
		SC.PermanentContactNo,
		SC.EmergencyContactNo,
		SC.ParentContactNo,
		SC.StudentContactNo,
		--AF.Remark,
		CASE WHEN (ISNULL((SELECT 1 FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate),0)
		= 1 AND (AF.Remark IS NULL OR AF.Remark = '')) THEN (SELECT LeaveReason FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate)
		ELSE (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace(AF.Remark,'\n','<br />'),
		'#amp;','&'),
		'#gt;','>'),
		'#quot;','\"'),
		'#lt;','<'),
		'#39;','''')) END AS Remark,
		ISNULL((SELECT 1 FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId 
		AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate),0) AS IsOnLeave
		,ISNULL(SA.StudentId, 0) AS StudentId
	FROM
		sStudent.vStudentAcademic SA
		INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
		LEFT JOIN sAttendance.tAttendanceFollowup AF ON AF.AcademicId = SA.AcademicId 
		AND SR.AttendanceTypeId = AF.AttendanceTypeId AND SR.AttendanceDate  = AF.FollowupDate
		LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
 
	WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
		  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  AND (SA.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND ((@rIsEditMode = 1 AND AF.IsPresent = @rPresentStatus) OR (@rIsEditMode = 0 AND SR.IsPresent = @rPresentStatus))
		  AND (AD.AdmissionDate <= @rFollowupDate)
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
		  AND (SR.AttendanceTypeId = @rAttendanceTypeId)
		  AND (SR.AttendanceDate = @rFollowupDate)
	ORDER BY SA.RollNo
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceFollowupXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rAttendanceTypeId tinyint,
    @rFollowupDate date='',
    @rPresentStatus tinyint,
    @rCreatedUserId bigint
  
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION 
	  BEGIN
	  
		INSERT INTO sAttendance.tAttendanceFollowup 
			(
				AcademicId,
				AttendanceTypeId,
				FollowupDate,
				IsPresent,
				Remark,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime
				
				)
			SELECT	
				
				AcademicId,
				@rAttendanceTypeId,
				@rFollowupDate,
				@rPresentStatus,
				ISNULL(Remark,''),
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
				
			FROM OPENXML (@loDoc, '/Table/AttendanceFollowup', 1)
			WITH ( 
					AcademicId bigint,
					Remark nvarchar(500)
					
				)  
			WHERE AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tAttendanceFollowup 
			Where AttendanceTypeId = @rAttendanceTypeId
			AND FollowupDate = @rFollowupDate AND IsPresent = @rPresentStatus)

		UPDATE sAttendance.tAttendanceFollowup 
		SET Remark = A.Remark,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate()
		FROM
		(
		 SELECT
			AcademicId,
			Remark
	
		FROM OPENXML (@loDoc, '/Table/AttendanceFollowup', 1)
		WITH
		(
			AcademicId bigint,
			Remark nvarchar(500)
		)) A
		INNER JOIN sAttendance.tAttendanceFollowup AF ON A.AcademicId = AF.AcademicId 
		AND AF.AttendanceTypeId = @rAttendanceTypeId
		AND AF.FollowupDate = @rFollowupDate
		AND AF.IsPresent = @rPresentStatus
		
        SELECT 1 AS Result
	  END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceForStudentAdd]

	 @rAcademicId bigint,
	 @rAttendanceTypeId smallint,
	 @rAttendanceDate date,
	 @rIsPresent bit,
	 @rCreatedUserId bigint 
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
 
BEGIN
	
	 
		Insert into sAttendance.tStudentRegister  (AcademicId,AttendanceTypeId,AttendanceDate,CreatedUserId,CreatedDateTime,IsPresent)Values(
		@rAcademicId,1,@rAttendanceDate, @rCreatedUserId,sCommon.fGetDate(),@rIsPresent)
		Select 1 As Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceGroupAdd]
	 
        @rId int,
        @rTitle nvarchar(200),
        @rOrgId smallint,
        @rBatchId int,
        @rCreatedUserId bigint,
        @rAttendanceGroupStudentXml [nvarchar](max),
        @rSubjectId int=0,
        @rClassId int=0
        
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAttendanceGroupStudentXml

BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
	    IF EXISTS(SELECT Id FROM sAttendance.tAttendanceGroup WHERE Title=@rTitle AND BatchId=@rBatchId)
			BEGIN
				SELECT -101 AS RESULT
			RETURN
		END 
	END
	ELSE
	BEGIN
		 IF EXISTS(SELECT Id FROM sAttendance.tAttendanceGroup WHERE Title=@rTitle AND BatchId=@rBatchId AND Id<>@rid)
			BEGIN
				SELECT -101 AS RESULT
			RETURN
		 END 
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAttendance.tAttendanceGroup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO sAttendance.tAttendanceGroup
			(
				Id,
				Title,
				BatchId,
				CreatedUserId,
				CreatedDateTime,
				SubjectId,
				ClassId
			)
		VALUES
			(
				@lNextNumber,
				@rTitle,
				@rBatchId,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rSubjectId,
				@rClassId
			)
			
		INSERT INTO sAttendance.tAttendanceGroupStudent
			(
				AttendanceGroupId,
				AcademicId
			)
		SELECT  	
			@lNextNumber,
			AcademicId
		FROM OPENXML (@loDoc, '/Table/AttendanceGroupStudent', 1)
		WITH ( 
				AcademicId bigint
			  ) 	
			
		SELECT 1 AS RESULT
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    UPDATE sAttendance.tAttendanceGroup
	    SET
			Title=@rTitle,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			SubjectId = @rSubjectId,
			ClassId = @rClassId
			
	     WHERE Id = @rId
	     
	     DELETE sAttendance.tAttendanceGroupStudent WHERE AttendanceGroupId= @rId
	     
	     INSERT INTO sAttendance.tAttendanceGroupStudent
			(
				AttendanceGroupId,
				AcademicId
			)
		SELECT  	
			@lNextNumber,
			AcademicId
		FROM OPENXML (@loDoc, '/Table/AttendanceGroupStudent', 1)
		WITH ( 
				AcademicId bigint
			  )
	     
	     SELECT 11 AS RESULT
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceGroupDelete]
@rId int
AS
BEGIN
BEGIN TRY
	  BEGIN
	  
		IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE AttendanceGroupId=@rId)
			BEGIN
				SELECT -101 AS RESULT
			RETURN
		END
		DELETE FROM sAttendance.tAttendanceGroupStudent WHERE AttendanceGroupId IN (SELECT Id FROM sAttendance.tAttendanceGroup WHERE Id=@rId)
		DELETE	FROM sAttendance.tAttendanceGroup WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceGroupGet]

	 @rId int,
	 @rBatchId int,
	 @rTitle nvarchar(200)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			AG.Id,
			AG.Title,
		    AG.BatchId,
		    AG.CreatedUserId,
		    AG.CreatedDateTime,
		    ISNULL(AG.SubjectId,0) AS SubjectId,
		    ISNULL(AG.ClassId,0) AS ClassId
	FROM 
			sAttendance.tAttendanceGroup AG
	WHERE 
		(AG.BatchId = @rBatchId)
		AND	((AG.Id = @rId) OR (@rId = 0))
		AND ((AG.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceGroupStudentGet]
	 @rAttendanceGroupId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
		  AGS.AcademicId,
		  SA.Code,
		  SA.ClassName+' - '+SA.DivisionName AS Class,
		  SA.Name,
		  ISNULL(SA.RollNo,0) AS RollNo
	FROM 
		  sAttendance.tAttendanceGroupStudent AGS
		  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = AGS.AcademicId
	WHERE 
		  AGS.AttendanceGroupId=@rAttendanceGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceListGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rStudentCode nvarchar(20),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rRepeatCount tinyint,
	 	 @rPresent tinyint,
		 @rFromAttendanceDate date,
		 @rToAttendanceDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceTag smallint=0,
	 	 @rStatus int=0,
	 	 @rFromRollNo int=0,
	 	 @rToRollNo int=0,
	 	 @rAttendanceGroupId int=0,
	 	 @rPeriodNo int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			SA.AcademicId,
			SA.Code AS StudentCode,
			ISNULL(SA.RollNo,0) as StudentRollNo,
			SA.Name,
			SA.ClassName + '-' + SA.DivisionName AS ClassName,
			SR.AttendanceTypeId,
			ATM.Title AS AttendanceTypeName,
			SR.AttendanceDate,
			SR.SubjectId,
			CASE AttendanceTypeId WHEN 1 THEN '' ELSE SR.RepeatCount END AS RepeatCount,
			--SR.RepeatCount,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			ARM.Title AS AbsentReasonName,
			SM.Title As SubjectName,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			SR.AttendanceTagId,
			ISNULL(AG.Title,'') AS AttendanceGroupName,
			ISNULL(SO.UIDNumber,'') AS UIDNumber
	 FROM 
			sStudent.vStudentAcademic SA 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId= SA.StudentId
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			LEFT JOIN sAttendance.tAttendanceTypeMaster ATM ON ATM.Id=SR.AttendanceTypeId
			LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id=SR.AbsentReasonId
			LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			LEFT JOIN sAttendance.tAttendanceGroup AG ON AG.Id=SR.AttendanceGroupId
			
			
  WHERE 
	 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	  AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	  AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
	  AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
	  AND ((SR.RepeatCount=@rRepeatCount) OR (@rRepeatCount=0))
	  AND ((SR.IsPresent=@rPresent) OR (@rPresent=2))
	  AND ((SR.AttendanceDate >= @rFromAttendanceDate) OR (ISNULL(@rFromAttendanceDate,'') = ''))
	  AND ((SR.AttendanceDate <= @rToAttendanceDate) OR (ISNULL(@rToAttendanceDate,'') = ''))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      AND ((SR.AttendanceTagId =@rAttendanceTag)OR (@rAttendanceTag=0))
      AND ((SA.StatusId =@rStatus)OR (@rStatus=0))
      ANd ((SA.RollNo>=@rFromRollNo) OR (@rFromRollNo=0))
      AND ((SA.RollNo<=@rToRollNo) OR (@rToRollNo=0))
      AND ((SR.AttendanceGroupId =@rAttendanceGroupId)OR (@rAttendanceGroupId=0))
      AND ((SR.PeriodNo =@rPeriodNo)OR (@rPeriodNo=0))
      ORDER BY SA.DivisionOrder, SA.RollNo, SR.AttendanceDate DESC
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceNotAddedDashboardGet]
	 @rOrgGroupId int=0,
	 @rConfigurationValue int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT
		OM.Id AS OrgId,
		vEM.Code AS Code,
		vEM.EmployeeName,
		CM.Title +' - '+DM.Title AS Class,
		DATEDIFF(day, isnull(Max(SR.AttendanceDate),getdate()-@rConfigurationValue),getdate())  AS NotAddedCount
	FROM
		 sHrm.vExtEmployeeMaster vEM
		 INNER JOIN sSetup.tDivisionMaster DM ON DM.InchargeEmployeeId = vEM.EmployeeId
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
		 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
		 INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id AND BM.IsActive = 1
		 INNER JOIN sStudent.tAcademic SA ON SA.DivisionID=DM.Id AND SA.batchId=BM.Id
		 LEFT JOIN sAttendance.tStudentRegister SR ON SR.EmployeeId = vEM.EmployeeId AND SR.AcademicId=SA.Id
	WHERE 
		OM.OrgGroupId = @rOrgGroupId AND DATEDIFF(day, isnull(SR.AttendanceDate,getdate()-@rConfigurationValue),getdate()) >= @rConfigurationValue
	GROUP BY 
		OM.Id,vEM.Code,vEM.EmployeeName,DM.Title,CM.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rAttendanceDate date ='',
	@rClassId int=0,
	@rDepartmentId int =0,
	@rDivisionId int=0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'AttendanceList')
		BEGIN
			SELECT COUNT(SR.AcademicId)
					,ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
							 AND SR.AttendanceDate = @rAttendanceDate WHERE SR.IsPresent=1 AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS PresentCount,
					ISNULL((SELECT COUNT(SR.AcademicId)
					FROM sStudent.tAcademic A 
						INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id AND SR.AttendanceDate = @rAttendanceDate
						INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
						  WHERE SR.IsPresent=0 AND  ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0)) ),0) AS AbsentCount,
				ISNULL((SELECT COUNT(SLR.AcademicId)			-- Changed SR.AcademicId to SLR.AcademicId For MantisId : 0035067
				FROM  sStudent.tAcademic A 
				INNER JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=A.Id  AND SLR.LeaveFromDate = @rAttendanceDate AND  SLR.LeaveToDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
				WHERE ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS LeaveCount
				FROM sStudent.tAcademic A 
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
			WHERE ((A.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
		END
	ELSE IF(@rType = 'ClassWiseAttendance')
		BEGIN 
			SELECT CM.Id,CM.Title,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T1.AbsentCount,0) As AbsentCount,CM.OrderIndex
				FROM sSetup.tClassMaster CM
						LEFT JOIN sStudent.tAcademic A ON CM.Id = A.ClassId	
						LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
						LEFT JOIN 
							(SELECT COUNT(A.Id) AS PresentCount,A.ClassId FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
							WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
							GROUP BY A.ClassId 
						)T ON T.ClassId = A.ClassId
						
						LEFT JOIN 
							(SELECT COUNT(A.Id) AS AbsentCount,A.ClassId FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
							WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
							GROUP BY A.ClassId 
						)T1 ON T1.ClassId = A.ClassId 
						--AND T.ClassId = T1.ClassId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
			AND ((CM.Id =@rClassId)OR(@rClassId=0))
			AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
				GROUP BY CM.Title, CM.Id,T.PresentCount,T1.AbsentCount,CM.OrderIndex
				ORDER BY CM.OrderIndex
		END
	
	ELSE
		BEGIN
		--create temp table for 29257 mantis
			CREATE TABLE #tempPresentAbsentCount
					(PresentCount int,
					AbsentCount int,
					ClassId int,
					DivisionId int
					)

			INSERT INTO #tempPresentAbsentCount
					(PresentCount,
					AbsentCount,
					ClassId,
					DivisionId
					)
			SELECT COUNT(CASE WHEN SR.IsPresent=1 THEN 1 END),
					COUNT(CASE WHEN SR.IsPresent=0 THEN 1 END),
					A.ClassId,
					A.DivisionId
			FROM sStudent.tAcademic A
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
			WHERE AttendanceDate = @rAttendanceDate
			GROUP BY A.ClassId,A.DivisionId

			SELECT CM.Id,(CM.Title +' - '+ DM.Title) AS  Title ,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T.AbsentCount,0) As AbsentCount,DM.OrderIndex
			FROM sSetup.tClassMaster CM
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id
				LEFT JOIN sStudent.tAcademic A  ON CM.Id = A.ClassId AND DM.Id = A.DivisionId
				LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
				--comment for 29257 mantis and also add new left join for temp table, it will done for query time optimization
				--LEFT JOIN
				--	(SELECT COUNT(A.Id) AS PresentCount,A.ClassId,A.DivisionId FROM sStudent.tAcademic A
				--	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
				--	WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
				--	GROUP BY A.ClassId,A.DivisionId
				--)T ON T.ClassId = A.ClassId AND T.DivisionId = A.DivisionId

				--LEFT JOIN
				--	(SELECT COUNT(A.Id) AS AbsentCount,A.ClassId,A.DivisionId FROM sStudent.tAcademic A
				--	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
				--	WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
				--	GROUP BY A.ClassId,A.DivisionId
				--)T1 ON T1.ClassId = A.ClassId AND T1.DivisionId = A.DivisionId
				----AND T.ClassId = T1.ClassId
				LEFT JOIN #tempPresentAbsentCount T ON T.ClassId = A.ClassId AND T.DivisionId = A.DivisionId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
				AND ((CM.Id =@rClassId)OR(@rClassId=0))
				AND ((DM.Id =@rDivisionId)OR(@rDivisionId=0))
				AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
			GROUP BY CM.Title, CM.Id,T.PresentCount,T.AbsentCount,DM.OrderIndex,DM.Title
			ORDER BY DM.OrderIndex

			DROP TABLE #tempPresentAbsentCount
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---USE [NetVidyalaya]

CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceTagMasterAdd]
	 
	        @rId int	      
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)          
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAttendance.tAttendanceTagMaster where Code=@rCode)  
			BEGIN
			select -101 as Result
			RETURN
		END 		
		If Exists(select Id from sAttendance.tAttendanceTagMaster where Title=@rTitle) 
			BEGIN
			select -103 as Result
			RETURN
		END 		
	END
	ELSE
	BEGIN
		If Exists(select Id from sAttendance.tAttendanceTagMaster where Code=@rCode AND Id<>@rId) 
		Begin
			select -101 as Result
			RETURN
		End 		
		If  Exists(select Id from sAttendance.tAttendanceTagMaster where Title=@rTitle AND Id<>@rId) 
		Begin
			select -103 as Result
			RETURN
		End		
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN

	select @lNextNumber = ISNULL(max(ID +1),1) from sAttendance.tAttendanceTagMaster

	INSERT INTO [sAttendance].[tAttendanceTagMaster]
			   (
					[Id]			     
				   ,[Code]
				   ,[Title]			   
				   ,[IsObsolete]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]				  		   
			   )
		 VALUES
			   (
				@lNextNumber			   
			   ,@rCode
			   ,@rTitle			   
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()			   
			   )
	END	 
	 ELSE
	 BEGIN
		 SET @lNextNumber = @rId
			UPDATE  [sAttendance].[tAttendanceTagMaster]
			SET  
				  Code=@rCode
				 ,Title=@rTitle	         
				 ,[IsObsolete] = @rIsObsolete                          
				 ,[UpdatedUserId] = @rCreatedUserId
				 ,[UpdatedDateTime] = sCommon.fGetDate()             
			  WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
	      
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceTagMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),          
           @rIsWildCardSearch bit
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT ATM.Id 	  
      ,ATM.Code
      ,ATM.Title      
      ,ATM.IsObsolete     
  FROM [sAttendance].[tAttendanceTagMaster] ATM 
        
  WHERE 
		((ATM.Id = @rId) OR (@rId = 0))
	AND ((ATM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((ATM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))	
		order by ATM.Id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pAttendanceViewGet]
@rOrgId [int],  
@rDepartmentId [int], 
@rSetupId [int], 
@rMainTypeId [int], 
@rCode [nvarchar](20),  
@rName [nvarchar](50),  
@rDesignationId [int],
@rStatusId int = 0,
@rParticipantSourceTypeId int,
@rStoreLocationId int,
@rFromDate varchar(20) = '',
@rToDate varchar(20) = '',
@rEmployeeStoreLocationId int=0,
@PageIndex int
AS
BEGIN
	set @rCode = replace(@rCode,'\\','\')
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rName = sCommon.fSearchStringGet(@rName)
	
	select @rFromDate = CONVERT(VARCHAR(10), CONVERT(date, @rFromDate, 105), 23)
	select @rToDate = CONVERT(VARCHAR(10), CONVERT(date, @rToDate, 105), 23)
	
	DECLARE @lempgrid VARCHAR(max)='',@lpaging VARCHAR(MAX)='',@TotalRecords INT,@PageSize INT=10
	
	DECLARE @tbltmp TABLE(tid INT IDENTITY(1,1),Id BIGINT)
	INSERT INTO @tbltmp
	SELECT E.ExaminationId FROM sExamination.vExtAllExaminationDetail E 
	WHERE E.OrgId = @rOrgId	AND ((E.ParticipantCode Like @rCode + '%') OR (@rCode = ''))
	AND ((E.ParticipantName Like @rName  + '%') OR (@rName = ''))
	AND ((E.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0 OR @rDepartmentId = -1))
	AND ((E.EmployeeDesignationId = @rDesignationId) OR (@rDesignationId = 0 OR @rDesignationId = -1))
	AND (E.MainTypeId = @rMainTypeId)
	AND ((E.ParticipantSourceTypeId = @rParticipantSourceTypeId) OR (ISNULL(@rParticipantSourceTypeId,0)=0))
	AND ((E.SetupId = @rSetupId) OR (@rSetupId = 0))
	AND ((E.StatusId = @rStatusId) OR (@rStatusId = 0))
	AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)
	AND datediff(day,@rFromDate,ExaminationDate)>=0 and datediff(day,ExaminationDate,@rToDate)>=0	
	AND ((E.EmployeeStoreLocationId = @rEmployeeStoreLocationId) 
	OR (ISNULL(@rEmployeeStoreLocationId,0) = 0) OR (ISNULL(E.EmployeeStoreLocationId,0) = 0))
	ORDER BY ExaminationDate desc
		
	SELECT @TotalRecords = count(*)	 from @tbltmp
	SELECT @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@PageIndex,@TotalRecords,@PageSize)
	
	SELECT @lempgrid = @lempgrid + '<tr>
	<td align="left" scope="col">' + isnull(convert(varchar,[ExaminationDate]),'') + '</td>	
	<td align="left" scope="col">' + isnull([ParticipantCode],'') + '</td>
	<td align="left" scope="col">' + isnull([ParticipantName],'') + '</td>
	<td align="left" scope="col">' + isnull((select DisplayTitle from sSecurity.tUser where Id = E.CreatedUserId),'') + '</td>	
	<td align="left" scope="col">' + isnull([RelationName],'') + '</td>
	<td align="left" scope="col">' + isnull([DepartmentName],'') + '</td>
	<td align="left" scope="col">' + isnull(CM.Title,'') + '</td>
	<td align="left" scope="col">' + isnull(ETM.Title,'') + '</td>
	<td align="left" scope="col">' + isnull(StatusName,'') + '</td>
    <td scope="col"><a href="javascript:;" 
    onclick="SelectEmployee(this,' + convert(varchar,isnull(ExaminationId,0)) + ',
    ' + convert(varchar,isnull(E.ProcessTypeId,0)) + ',
    ' + convert(varchar,isnull(E.ParticipantSourceTypeId,0)) + ',
    ' + convert(varchar,isnull(E.ParticipantSourceId,0)) + ',
    ''' + isnull(convert(varchar,[ExaminationDate]),'') + ''',
    ''' + isnull([ParticipantCode],'') + ''',
    ''' + isnull([ParticipantName],'') + ''',
    ' + convert(varchar,isnull(E.DoctorEmployeeId,0)) + ',
    ' + convert(varchar,isnull(E.OrganizationDepartmentId,0)) + ',
    ' + convert(varchar,isnull(E.Age,0)) + ',
    ' + convert(varchar,isnull(E.EmployeeDesignationId,0)) + ',
    ''' + isnull(E.EmployeeDesignation,'') + ''',
    ' + convert(varchar,isnull(E.GenderId,0)) + ',
    ''' + isnull(convert(varchar,E.DateOfBirth),'') + ''');">Select</a></td></tr>'	
    FROM sExamination.vExtAllExaminationDetail E 
    inner join sExamination.tCauseMaster CM on CM.Id = E.CauseId
    left join sHrm.tEmployeeTypeMaster ETM on ETM.Id=E.EmployeeTypeId,
    @tbltmp t WHERE t.Id = E.ExaminationId AND t.tid
	BETWEEN ((@PageSize * (@PageIndex-1)) + 1) and (@PageSize * @PageIndex)
	ORDER BY t.tid
	
	select isnull(@lempgrid,'') as EmpGrid,@lpaging as paging
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pAverageAttendanceSubjectNameGet]
	 @rDivisionId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

SELECT 
	SubjectName   
FROM
		sSetup.tDivisionMaster DM
	INNER JOIN sSetup.vDivisionSubject V ON V.DivisionId = DM.Id 
Where (DM.Id=@rDivisionId OR @rDivisionId = 0 )
 	  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pCheckAttendanceEntry]
	 
	 @rStrDivisionId nvarchar(max),
	 @rAttendanceTypeId tinyint,
	 @rAttendanceDate date
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	Declare @lExistDivisionName nvarchar(max)
	Declare @lExistDivisionId nvarchar(max)
	Declare @lExistAcademicId nvarchar(max)
	BEGIN TRY
		BEGIN TRANSACTION
			Select 
				@lExistAcademicId  = COALESCE(@lExistAcademicId ,'') + CONVERT(VARCHAR(15),SA.AcademicId) + ' , '
			From
					sStudent.vStudentAcademic SA
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
					AND SR.AttendanceTypeId=@rAttendanceTypeId AND SR.AttendanceDate=@rAttendanceDate
			WHERE 
					(SA.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrDivisionId,',')) 
						OR @rStrDivisionId='')
			
			SET @lExistAcademicId = LEFT(@lExistAcademicId, LEN(@lExistAcademicId) - 1)
			
			SELECT 
					@lExistDivisionName  = COALESCE(@lExistDivisionName ,'') + ClassName+' - '+DivisionName + ' , ' 
			From
					sSetup.vBatchClassDivision
			WHERE
					DivisionId IN(SELECT distinct(DivisionId) fROM sStudent.vStudentName WHERE
					(AcademicId In( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@lExistAcademicId,',')) 
						OR @lExistAcademicId=''))
			GROUP BY DivisionId, ClassName, DivisionName
			SET @lExistDivisionName = LEFT(@lExistDivisionName, LEN(@lExistDivisionName) - 1)
						
			SELECT @lExistDivisionName AS RESULT
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pCheckHoliday]
	 
	@rDivisionId int,
	@rAttendanceDate date,
	@rBatchId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

 IF Exists(SELECT ES.Id FROM  
 sActivity.tEventSchedule ES INNER JOIN sActivity.tEventAssign EA
 ON ES.Id = EA.EventScheduleId 
 WHERE
 (@rAttendanceDate  >= ES.FromDate)
 AND (@rAttendanceDate <= ES.ToDate)
 AND SourceTypeId = 2005
 AND SourceId = @rDivisionId
 AND ES.IsHoliday = 1
 AND ES.BatchId = @rBatchId
 )
 SELECT 1 AS Result
 ELSE
 SELECT 0 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pDashletAttendanceStatusGet]	 	 
	   @rAcademicId bigint
	  
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE 
@lTotalAttendance bigint,
@lTotalAbsent bigint,
@lAbsentReason nvarchar(100),
@lAttendanceDate date
 

select @lTotalAttendance = ISNULL(COUNT(AcademicId),0) FROM sAttendance.tStudentRegister SR  
WHERE AcademicId = @rAcademicId  AND SR.AttendanceTypeId = 1
AND SR.IsPresent = 1 



select @lTotalAbsent = ISNULL(COUNT(AcademicId),0) FROM sAttendance.tStudentRegister SR  
WHERE AcademicId = @rAcademicId AND SR.AttendanceTypeId = 1
AND IsPresent = 0

SELECT TOP 1 @lAttendanceDate = AttendanceDate,@lAbsentReason = AR.Title  FROM sAttendance.tStudentRegister SR 
LEFT JOIN sAttendance.tAbsentReasonMaster AR
ON SR.AbsentReasonId = AR.Id 
WHERE SR.AcademicId = @rAcademicId AND SR.AttendanceTypeId = 1
AND IsPresent = 0 ORDER BY SR.AttendanceDate DESC
 
  SELECT
  @lTotalAttendance AS TotalAttendance,
  @lTotalAbsent AS TotalAbsent,
  ISNULL(@lAttendanceDate,'') AS AttendanceDate,
  ISNULL(@lAbsentReason,'') AS AbsentReason
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pDateWiseAttendanceStrengthGet]
	@rUserId bigint,
	@rMonth smallint,
	@rYear int,
	@rBatchId int,
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

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

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

	SELECT DISTINCT DM.Id AS DivisionId
		,CM.Id AS ClassId
		,OM.DisplayTitle + ' - ' + CM.Title + ' - ' + DM.Title AS ClassDivision
	INTO #TempData
	FROM sSetup.tClassMaster CM
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id
	WHERE U.SourceTypeId = 2005
		AND U.UserId = @rUserId

	DECLARE @li INT, @Days INT, @lOrgGroupBatchId int
	SELECT @lOrgGroupBatchId = (SELECT OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId)
	SET @li = 1
	SELECT @Days = sCommon.fGetDaysInMonth(@rMonth, @rYear)

	CREATE TABLE #TempDaysTempTable (
		DayPart INT
		,WHDate DATE
		,Value NVARCHAR(20)
		,ClassId INT
		,DivisionId INT
		,ClassDivision NVARCHAR(200)
	)

	WHILE @li <= @Days
	BEGIN
		INSERT INTO #TempDaysTempTable (
			DayPart
			,WHDate
			,Value
			,ClassId
			,DivisionId
			,ClassDivision
		)
		SELECT @li AS DayPart
			,CONVERT(DATE, (CONVERT(NVARCHAR(4), @rYear) + '/' + CONVERT(NVARCHAR(2), @rMonth) + '/' + CONVERT(NVARCHAR(2), @li)))
			,[sAttendance].[fWeekHOffGet](@rYear, @rMonth, @li, @rBatchId, ClassId, DivisionId, '', @rOrgId) AS STATUS
			,ClassId
			,DivisionId
			,ClassDivision
		FROM #TempData

		SET @li = @li + 1
	END

	CREATE TABLE #TempAttendanceData (
		AttendanceDate DATE
		,StudentCount INT
		,AttendanceType SMALLINT
		,DivisionId INT
	)

	INSERT INTO #TempAttendanceData
	SELECT SR.AttendanceDate
		,COUNT(DISTINCT (SR.AcademicId)) AS Present
		,1 -- For Present
		,T.DivisionId
	FROM sAttendance.tStudentRegister SR
	INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	INNER JOIN #TempData T ON T.DivisionId = A.DivisionId
		AND T.ClassId = A.ClassId
	WHERE IsPresent = 1
		AND MONTH(SR.AttendanceDate) = @rMonth
		AND BM.OrgGroupBatchId = @lOrgGroupBatchId
		AND AttendanceTypeId = 1
	GROUP BY SR.AttendanceDate
		,T.DivisionId
		,ClassDivision

	INSERT INTO #TempAttendanceData
	SELECT SR.AttendanceDate
		,COUNT(DISTINCT (SR.AcademicId)) AS Absent
		,2 -- For Absent
		,T.DivisionId
	FROM sAttendance.tStudentRegister SR
	INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	INNER JOIN #TempData T ON T.DivisionId = A.DivisionId
		AND T.ClassId = A.ClassId
	WHERE IsPresent = 0
		AND MONTH(SR.AttendanceDate) = @rMonth
		AND BM.OrgGroupBatchId = @lOrgGroupBatchId
		AND AttendanceTypeId = 1
	GROUP BY SR.AttendanceDate
		,T.DivisionId
		,ClassDivision

	-- Class Division List
	SELECT *
	FROM #TempData

	-- Attendance and WeekOff/Holiday Data
	
	SELECT AttendanceDate, SUM(Present) AS Present, SUM(Absent) AS Absent, SUM(Present) + SUM(Absent) AS Total, ISNULL(DivisionId, 0) AS DivisionId, ISNULL(ClassDivision, '') AS ClassDivision, MIN(STATUS) AS STATUS FROM 
	(SELECT AttendanceDate
		,SUM(Present) AS Present
		,SUM(Absent) AS Absent
		--,SUM(Present) + SUM(Absent) AS Total
		,T.DivisionId
		,T.ClassDivision
		,T.Value AS STATUS
	FROM (
		SELECT AttendanceDate
			,CASE 
				WHEN AttendanceType = 1
					THEN SUM(StudentCount)
				ELSE 0
				END AS Present
			,CASE 
				WHEN AttendanceType = 2
					THEN SUM(StudentCount)
				ELSE 0
				END AS Absent
			,DivisionId
		FROM #TempAttendanceData
		GROUP BY AttendanceDate
			,AttendanceType
			,StudentCount
			,DivisionId
		) AS A
	LEFT JOIN #TempDaysTempTable T ON T.WHDate = A.AttendanceDate
		AND T.DivisionId = A.DivisionId
	GROUP BY A.AttendanceDate
		,T.DivisionId
		,T.ClassDivision
		,T.Value

	UNION

	SELECT WHDate AS AttendanceDate
		,0 AS Present
		,0 AS Absent
		--,0 AS Total
		,DivisionId
		,ClassDivision
		,Value AS STATUS
	FROM #TempDaysTempTable
	WHERE ISNULL(Value, '') <> '' ) A 
	GROUP BY AttendanceDate, DivisionId, ClassDivision
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

BEGIN 	

IF (@rDeleteType = 'DayRegister')

BEGIN

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

IF(@rDeleteType = 'MonthlyRegister')

BEGIN

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

IF(@rDeleteType = 'StudentSetup')

BEGIN

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

SELECT 1 AS Result

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pEmployeeAttendanceRegisterXMLAdd]
	(
		@rXmlDoc nvarchar(MAX)
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	DECLARE @lBatchId int
	DECLARE @lOrgId int
	DECLARE @lAttendanceDate DateTime
	
	SELECT @lBatchId= BM.Id,@lOrgId=OM.Id From sSetup.tBatchMaster BM 
	INNER JOIN sSetup.tOrganizationMaster OM ON BM.OrgId = OM.Id And ISActive =1
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.OrgId = OM.Id AND ISNULL(EM.IsOtherUser,0) = 0 
	INNER JOIN (SELECT EmployeeId FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH
	(		
		EmployeeId BigINT '@EmployeeId'		
	))A ON  A.EmployeeId = EM.Id
		
		
		
	SELECT
		distinct @lAttendanceDate = AttendanceDate
	FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH
	(		
		AttendanceDate DateTime '@AttendanceDate'
	)A	
	-----------------------
	DELETE SA FROM sHrm.tEmployeeAttendanceRegister SA INNER JOIN 
	(SELECT EmployeeId,AttendanceDate FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH
	(		
		EmployeeId BigINT '@EmployeeId',
		AttendanceDate DateTime '@AttendanceDate'
	))A ON  SA.EmployeeId = A.EmployeeId AND SA.AttendanceDate=A.AttendanceDate 
		
	
	INSERT INTO sHrm.tEmployeeAttendanceRegister
	(
		EmployeeId,
		AttendanceDate,
		IsPresent,
		AbsentReasonId,
		UpdatedUserId,
		UpdatedDateTime,
		BatchId	
	)
	SELECT
		EmployeeId,
		AttendanceDate,
		IsPresent,
		1,
		1,
		sCommon.fGetDate(),
		@lBatchId
		
	FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH
	(		
		EmployeeId BigINT '@EmployeeId',
		AttendanceDate DateTime '@AttendanceDate',
		IsPresent Smallint '@IsPresent'
	)A
	
	
	-- Insert Absent Employee Entry 
	insert into sHrm.tEmployeeAttendanceRegister
	Select Id,@lAttendanceDate,0,0,0,sCommon.fGetDate(),@lBatchId,null,null,null from sHRM.tEmployeeMaster 
	Where Id not in (Select EmployeeId from sHrm.tEmployeeAttendanceRegister Where AttendanceDate=@lAttendanceDate)	
	AND OrgId =@lOrgId
	AND StatusId = 7
	AND ISNULL(IsOtherUser,0) = 0 
	
	
	--UPDATE EA SET EA.BatchId=BM.Id  from sHRM.tEmployeeMaster EM 
	--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
	--INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id AND BM.IsActive = 1
	--INNER JOIN sHrm.tEmployeeAttendanceRegister EA ON EA.EmployeeId=EM.Id 
	--INNER JOIN (SELECT EmployeeId,AttendanceDate FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	--WITH
	--(		
	--	EmployeeId BigINT '@EmployeeId',
	--	AttendanceDate DateTime '@AttendanceDate'
	--))A ON EA.EmployeeId = A.EmployeeId AND EA.AttendanceDate=A.AttendanceDate  
	
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pFilterCriteriaAdd]

		@rId int
		,@rCode nvarchar(20)
		,@rTitle nvarchar(100)
		,@rIsObsolete bit
		,@rCreatedUserId bigint
		,@rOrgId int


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

		IF(@rId = 0)
		BEGIN
			IF Exists(SELECT Id FROM sAttendance.tFilterCriteria WHERE Code=@rCode AND OrgId=@rOrgId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END

			IF Exists(SELECT Id FROM sAttendance.tFilterCriteria WHERE Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
		ELSE
		BEGIN
			IF Exists(SELECT Id FROM sAttendance.tFilterCriteria WHERE Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
			IF  Exists(SELECT Id FROM sAttendance.tFilterCriteria WHERE Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END

		BEGIN TRANSACTION
			DECLARE @lNextNumber BIGINT

			IF(@rId = 0)
			BEGIN

				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAttendance.tFilterCriteria', 0, 1, 1,@outNextNumber = @lNextNumber output

				INSERT INTO sAttendance.tFilterCriteria
				(
					[Id]
					,[Code]
					,[Title]
					,[IsObsolete]
					,[CreatedUserId]
					,[CreatedDateTime]
					,[UpdatedUserId]
					,[UpdatedDateTime]
					,[OrgId]
				)
				VALUES
				(
					@lNextNumber
					,@rCode
					,@rTitle
					,@rIsObsolete
					,@rCreatedUserId
					,sCommon.fGetDate()
					,0
					,sCommon.fGetDate()
					,@rOrgId
				)
				SELECT @lNextNumber AS Result

				--COMMIT TRANSACTION	--comment for migration issue by dhruvik
			END

			ELSE
			BEGIN
				SET @lNextNumber = @rId
				UPDATE  sAttendance.tFilterCriteria
				SET
					Code=@rCode
					,Title=@rTitle
					,[IsObsolete] = @rIsObsolete
					,[UpdatedUserId] = @rCreatedUserId
					,[UpdatedDateTime] = sCommon.fGetDate()

				WHERE Id = @rId
				SELECT @lNextNumber AS Result

				--COMMIT TRANSACTION	--comment for migration issue by dhruvik
			END

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pFilterCriteriaDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	--IF EXISTS (SELECT 1 FROM sAssessment.tExamMaster WHERE GradeSetId= @rId)	
	--	BEGIN
	--		SELECT -101 AS RESULT
	--		RETURN
	--	END
	--IF Exists (Select 1 From sAssessment.tCCECSGroupMaster Where GradeSetId = @rId) 
	--	BEGIN
	--		SELECT -101 AS RESULT
	--		RETURN
	--	END
	--IF EXISTS (SELECT 1 FROM sAssessment.tExamDetail WHERE GradeSetId= @rId)	
	--	BEGIN
	--		SELECT -101 AS RESULT
	--		RETURN
	--	END

	  BEGIN
		DELETE FROM sAttendance.tFilterCriteriaDetail WHERE FilterCriteriaId IN (SELECT ID FROM sAttendance.tFilterCriteria WHERE ID=@rId)
		DELETE	FROM sAttendance.tFilterCriteria WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAttendance].[pFilterCriteriaDetailAdd]
	 
	        @rId int
           ,@rFilterCriteriaId int
           ,@rMinimumScore decimal(12,2)
		   ,@rGradeCode nvarchar(20)
		   ,@rGradeTitle nvarchar(50)
		   ,@rGradePoint decimal(6,2)
		   ,@rOrgId int
		   ,@rHighlightColor nvarchar(50)
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAttendance.tFilterCriteriaDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAttendance.tFilterCriteriaDetail
			   (
			    [Id]
			   ,[FilterCriteriaId] 
			   ,[MinimumScore] 
			   ,[GradeCode]
			   ,[GradeTitle]
			   ,[GradePoint]
			  
			  ,[HighlightColor]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rFilterCriteriaId
			   ,@rMinimumScore
			   ,@rGradeCode
			   ,@rGradeTitle
			   ,@rGradePoint
			   ,@rHighlightColor
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAttendance.tFilterCriteriaDetail
	    SET
			  --Number=@rNumber
	         --,Code=@rCode
	          FilterCriteriaId=@rFilterCriteriaId
	         ,MinimumScore=@rMinimumScore
	         ,GradeCode=@rGradeCode
			 ,GradeTitle=@rGradeTitle
			 ,GradePoint =@rGradePoint		
			 ,HighlightColor=@rHighlightColor             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pFilterCriteriaDetailGet]
	 @rFilterCriteriaId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			FC.TITLE,
			FC.Code,
			FCD.FilterCriteriaId,
			FCD.Id,
			FCD.GradeCode,
			FCD.GradeTitle,
			FCD.MinimumScore,
			FCD.GradePoint,
			FC.IsObsolete,
			FCD.HighlightColor
			
  FROM 
			sAttendance.tFilterCriteria FC
			INNER JOIN sAttendance.tFilterCriteriaDetail FCD ON FCD.FilterCriteriaId=FC.id
WHERE 
			(FCD.FilterCriteriaId=@rFilterCriteriaId OR @rFilterCriteriaId=0)  order by FCD.MinimumScore Desc
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAttendance].[pFilterCriteriaGet]
          
           --@rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgId int           
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			Set @rCode = sCommon.fSearchStringGet(@rCode)
		--END

BEGIN
SELECT FC.Id as FilterCriteriaId
	  ,FC.Title as Title
	  ,FC.Code as Code
      ,FC.IsObsolete as IsObsolete
     
  FROM sAttendance.tFilterCriteria FC 
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((FC.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND OrgId = @rOrgId

	--AND  CCM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pFilterStudentGet]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		 @rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=0,
	     @rSubjectId int=0,
	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 ,
	 	---- @rIndicator nvarchar(20)='',
	 	 @rFilterxml nvarchar(max)='',
	 	 @rFilterCriteriaId int = 0,
	 	  @rFilterCriteriaDetailId int = 0,
		 @rStatus int=0,
		 @rIsChart int,
		 @rBuilder1 nvarchar(max)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rFilterxml

BEGIN 
 
			--select * from dbo.Attendance_Temp
 
		
	CREATE TABLE #tFilterStudent
	 (  
	 AcademicId  bigint,
	 PresentCount int,
	 AbsentCount int,
	 AveragePresence Decimal(10,2),
	 FilterStatus nvarchar(20),
	 FilterStatusCode nvarchar(20),	
	 StatusColor nvarchar(20),
	 FilterStatusPoint decimal(10,2),
	 FilterCriteriaDetailId int,
 
	 TotalCount int

	 )
	 
	
    
   INSERT INTO #tFilterStudent
   	SELECT 
   	SA.Id,			
			 (SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId				
		) AS PresentCount, 
	  (SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND SR.AcademicId = SA.Id
		AND SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId		
		) AS AbsentCount,
		0.0,
		'',
		'',
		'',
		0.0,
		0,
		 
		(SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId				
		)+(SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND SR.AcademicId = SA.Id
		AND SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId		
		) As TotalCount
			 
			
			
  FROM 
		 sStudent.tAcademic SA 
		  INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId         
		 
         WHERE ((SM.Code=@rStudentCode) OR (@rStudentCode=0))
         AND((SM.StatusId=@rStatus) OR (@rStatus=0))
        

 
	AND	((ClassId=@rClassId) OR (@rClassId=0))
	 AND ((DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
     AND  (SA.OrgId = @rOrgId)
      AND (BatchId = @rBatchId)
  
  
      UPDATE #tFilterStudent SET AveragePresence =     CAST(PresentCount AS float)/ (CAST(PresentCount AS float) + CAST(AbsentCount AS float)) * 100 
      WHERE  ((PresentCount + AbsentCount) > 0)
      
      
      	CREATE TABLE #tempGradeSetDetail
			(
				Id INT IDENTITY (1, 1),
				MinimumScore decimal(5,2),
				GradeCode nvarchar(20),				 
				GradeTitle nvarchar(100),
				GradePoint decimal(6,2),
				HighlightColor nvarchar(50),
				FilterCriteriaDetailId int, 	 			 
			) 
			INSERT INTO #tempGradeSetDetail
			SELECT MinimumScore,GradeCode,GradeTitle,GradePoint,HighlightColor,Id	
			FROM sAttendance.tFilterCriteriaDetail where FilterCriteriaId=@rFilterCriteriaId
			
			order by MinimumScore ASC
      
      	DECLARE @lCount int
      		DECLARE @MinimumScore decimal(5,2)
      		
      		DECLARE @GradeStatus nvarchar(10)
      		DECLARE @GradeColor nvarchar(10)
      		
      		
      		DECLARE @GradeCode nvarchar(10)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @FilterCriteriaDetailId int
      SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
		 
		
		 while (@lCount >0 )
	BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@GradeCode = GradeCode,
		
		@GradeStatus = GradeTitle,
		@GradeColor = HighlightColor,
		
		
		@GradeTitle=GradeTitle,
		@GradePoint=GradePoint,
		@FilterCriteriaDetailId = FilterCriteriaDetailId 
		FROM #tempGradeSetDetail WHERE Id = @lCount
		
	 UPDATE #tFilterStudent SET FilterStatus =  @GradeTitle,
	     FilterStatusCode =@GradeCode,
	     
	      FilterStatusPoint= @GradePoint,
	      StatusColor = @GradeColor,
	      
	      FilterCriteriaDetailId=@FilterCriteriaDetailId
      WHERE  AveragePresence >= @MinimumScore AND FilterStatus = ''
	
	SET @lCount = @lCount - 1
	END
	
	
        select 
			CM.Title + '-' + DM.Title AS Class,A.RollNo,
			 A.Id AS AcademicId,
			 SM.Code AS StudentCode,SM.FirstName + ' ' + SM.LastName AS Name,
		   
			FS.AveragePresence,
			FS.FilterStatus,FS.StatusColor,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisionOrderIndex,
			@rIsChart AS IsChart,
			 @rBuilder1 AS Builder1,
			FS.FilterStatusPoint ,
			FS.PresentCount,
			FS.TotalCount
		  
				
				
			
				
				 
	   from #tFilterStudent  FS 
        INNER JOIN sStudent.tAcademic A ON A.Id=FS.AcademicId 
      
        INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
         INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
         INNER JOIN sSetup.tDivisionMaster DM ON DM.Id= A.DivisionId
         WHERE 
         
         ((FilterCriteriaDetailId = @rFilterCriteriaDetailId) OR (@rFilterCriteriaDetailId=0))
		 
         
	 
    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pFilterStudentSubjectGet]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		 @rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=0,
	     @rSubjectId int=0,
	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 ,
	 	---- @rIndicator nvarchar(20)='',
	 	 @rFilterxml nvarchar(max)='',
	 	 @rFilterCriteriaId int = 0,
	 	 @rFilterCriteriaDetailId int = 0,
		 @rStatus int=0,
		 @rIsChart int,
		 @rBuilder1 nvarchar(max)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rFilterxml

BEGIN 
 --SELECT 
	--		'' AS Class,
	--		 0 AS RollNo,
			
	--		 '' AS StudentCode,
	--		 '' AS  Name,
		   
	--		 0 AS AveragePresence,
	--		 '' AS  FilterStatus,
	--		 '' AS StatusColor,
	--		 0 AS DivisionOrderIndex,
	--		 0 AS DivisionId,
	--		 0 AS AcademicId,
	--		 '' AS SubjectName,
	--		 ''  AS SubjectId,
	--		 '' AS SubjectOrder,
	--		'' AS SubjectCode,
	--		0 AS IsChart,
	--		'' AS Builder1
	
	CREATE TABLE #tFilterStudent
	 (  
	 AcademicId bigint,	
	 PresentCount int,
	 AbsentCount int,
	 AveragePresence Decimal(10,2),
	 FilterStatus nvarchar(20),
	 FilterStatusCode nvarchar(20),	
	 StatusColor nvarchar(20),
	 FilterStatusPoint decimal(10,2),
	 FilterCriteriaDetailId int,
	  SubjectId int
	 
	 
 
	 )
	 
	
    
   INSERT INTO #tFilterStudent
   	SELECT 
   	SA.Id,			
			 (SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = 5
		AND SR.SubjectId = CS.SubjectId 
		AND (SR.SubjectId = @rSubjectId OR @rSubjectId = 0)
		
		 	
		) AS PresentCount, 
	  (SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND SR.AcademicId = SA.Id
		AND SR.IsPresent = 0
		AND SR.AttendanceTypeId = 5
		AND SR.SubjectId = CS.SubjectId 
		AND (SR.SubjectId = @rSubjectId OR @rSubjectId = 0)	
	 
		) AS AbsentCount,
		0.0,
		'',
		'',
		'',
		0.0,
		0,
		CS.SubjectId
			 
			
			
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = SA.ClassId AND	((CS.ClassId=@rClassId) OR (@rClassId=0)) 
	     WHERE ((SM.Code=@rStudentCode) OR (@rStudentCode=0))
         AND((SM.StatusId=@rStatus) OR (@rStatus=0))
		AND	((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
		AND  (SA.OrgId = @rOrgId)
		AND (SA.BatchId = @rBatchId)
		AND (CS.SubjectId = @rSubjectId OR @rSubjectId = 0)
  

  
      UPDATE #tFilterStudent SET AveragePresence =     CAST(PresentCount AS float)/ (CAST(PresentCount AS float) + CAST(AbsentCount AS float)) * 100 
      WHERE  ((PresentCount + AbsentCount) > 0)
      
      
      	CREATE TABLE #tempGradeSetDetail
			(
				Id INT IDENTITY (1, 1),
				MinimumScore decimal(5,2),
				GradeCode nvarchar(20),				 
				GradeTitle nvarchar(100),
				GradePoint decimal(6,2),
				HighlightColor nvarchar(50),
				FilterCriteriaDetailId int, 	 			 
			) 
			INSERT INTO #tempGradeSetDetail
			SELECT MinimumScore,GradeCode,GradeTitle,GradePoint,HighlightColor,Id	
			FROM sAttendance.tFilterCriteriaDetail where FilterCriteriaId=@rFilterCriteriaId
			
			order by MinimumScore ASC
      
      	DECLARE @lCount int
      		DECLARE @MinimumScore decimal(5,2)
      		
      		DECLARE @GradeStatus nvarchar(10)
      		DECLARE @GradeColor nvarchar(10)
      		
      		
      		DECLARE @GradeCode nvarchar(10)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @FilterCriteriaDetailId int
      SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
		 
		
		 while (@lCount >0 )
	BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@GradeCode = GradeCode,
		
		--@GradeStatus = GradeTitle,
		@GradeColor = HighlightColor,
		
		
		@GradeTitle=GradeTitle,
		@GradePoint=GradePoint,
		@FilterCriteriaDetailId = FilterCriteriaDetailId 
		FROM #tempGradeSetDetail WHERE Id = @lCount
		
	 UPDATE #tFilterStudent SET FilterStatus =  @GradeTitle,
	     FilterStatusCode =@GradeCode,
	     
	      FilterStatusPoint= @GradePoint,
	      StatusColor = @GradeColor,
	      
	      FilterCriteriaDetailId=@FilterCriteriaDetailId
      WHERE  AveragePresence >= @MinimumScore AND FilterStatus = ''
	
	SET @lCount = @lCount - 1
	END
	
	 
 
	
        select 
			@rIsChart AS IsChart,
			CM.Title + '-' + DM.DisplayTitle AS Class,
			A.RollNo,
			SMS.Code AS StudentCode,
			SMS.FirstName + ' ' + SMS.LastName AS Name,		   
			FS.AveragePresence,
			FS.FilterStatus,
			FS.StatusColor,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisionOrderIndex,
			A.Id AS AcademicId,
			SM.Title AS SubjectName,
			SM.Id AS SubjectId,
			SM.Code AS SubjectCode,
			SM.OrderIndex AS SubjectOrder
			,FS.FilterStatusPoint ,
			@rBuilder1 AS Builder1
		
				
				
			
				
				 
	   from #tFilterStudent  FS 
        INNER JOIN sStudent.tAcademic A ON A.Id = FS.AcademicId      
        INNER JOIN sStudent.tStudentMaster SMS ON SMS.Id=A.StudentId
         INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
         INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
         INNER JOIN sSetup.tSubjectMaster SM ON FS.SubjectId = SM.Id
         WHERE 
         
         ((FilterCriteriaDetailId = @rFilterCriteriaDetailId) OR (@rFilterCriteriaDetailId=0))
        -- order by DM.Id
         --, FS.AcademicId ,FS.SubjectId
         
		 
         
         
--         DECLARE @cols AS NVARCHAR(MAX),
--    @query  AS NVARCHAR(MAX)

--select @cols = STUFF((SELECT  ',' + QUOTENAME(CS.SubjectId) 
--					  From sSetup.tClassSubject CS					   
--					  WHERE ClassId = @rClassId 
--            FOR XML PATH(''), TYPE
--            ).value('.', 'NVARCHAR(MAX)') 
--        ,1,1,'')

--set @query = 'SELECT 

--			 DM.Title AS Class,A.RollNo,
			
--		  SMS.LastName AS Name,
		   
--			FS.AveragePresence,
--			FS.FilterStatus,
--			FS.StatusColor,
--			SM.Title AS SubjectName,
--			SM.Code AS SubjectCode,
--			SM.OrderIndex AS SubjectOrder

--,' + @cols + ' from 
--             (
--                select AcademicId, SubjectId, AveragePresence
--                 from #tFilterStudent  FS 
--        INNER JOIN sStudent.tAcademic A ON A.Id=FS.AcademicId 
      
--        INNER JOIN sStudent.tStudentMaster SMS ON SMS.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.tSubjectMaster SM ON FS.SubjectId = SM.Id
--            ) x
--            pivot 
--            (
--                sum(AveragePresence)
--                for SubjectId in (' + @cols + ')
--            ) p '

--execute(@query);
	 
    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pHoliDayCountGet]
	
	@rMonth int=0,
	@rYear int=0,
	@rBatchId int=0,
	@rOrgId int=0,
	@rClassId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	CREATE table #Table1 (Id bigint identity,FromDate Date,ToDate Date,DivId int,IsExists bit)
	
	CREATE table #Table2 (Id bigint identity,FromDate Date,ToDate Date,DivId int)
	
	INSERT INTO #Table2 
	SELECT 
	ES.FromDate, 
	ES.ToDate,0
	from sActivity.tEventSchedule ES
	INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleId = ES.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = EA.SourceId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	Where (MONTH(FromDate)<= @rMonth AND MONTH(ToDate) >= @rMonth) AND ES.IsHoliDay =1 
	AND (YEAR(FromDate)=@rYear AND YEAR(ToDate) = @rYear)
	AND EA.SourceTypeId = 2005 AND CM.Id = @rClassId
	AND ((ES.BatchId = @rBatchId)OR(@rBatchId=0))
	GROUP BY ES.FromDate,ES.ToDate
	  
	INSERT INTO #Table1 
	select FromDate,ToDate,Max(DivId),0
	from
	( 
	SELECT case when MONTH(FromDate)=@rMonth then FromDate
				when MONTH(FromDate)<>@rMonth and MONTH(ToDate)=@rMonth then DATEADD(DD,-Day(ToDate)+1,ToDate)
				when MONTH(FromDate)<@rMonth and MONTH(ToDate)>@rMonth then cast(rtrim(@rYear *10000+ @rMonth *100+ 01) as date) --mantis:28433
				else FromDate end as FromDate,
				ToDate,
				DivId	
	From #Table2
	GROUP BY  FromDate,ToDate,DivId
	)As Tmp
	GROUP BY  Tmp.FromDate,Tmp.ToDate,Tmp.DivId
	
	DECLARE @lTempCount int=0
	SELECT @lTempCount = count(Id) from #Table1
	WHILE @lTempCount > 0 
	BEGIN
		DECLARE @lFromDate Date,@lToDate Date

		SELECT @lFromDate = FromDate, @lToDate = ToDate FROM #Table1 WHERE Id=@lTempCount
		IF EXISTS(SELECT 1 FROM #Table1 WHERE Id <> @lTempCount AND ((@lFromDate between FromDate and ToDate) AND (@lToDate between FromDate and ToDate)))
		BEGIN
			UPDATE #Table1 SET IsExists = 1 WHERE Id = @lTempCount	
		END
		SET @lTempCount = @lTempCount - 1
	END

	 
	DECLARE @lCount int
	SELECT @lCount = count(Id) from #Table1
	DECLARE @lStatus nvarchar(5),@lFromYear int,@lFromMonth int,@lFromDay int,@lDivision int,@lToYear int,@lToMonth int,@lToDay int
	DECLARE @lHoliDayCount int,@lBeginCount int ,@lEndCount int , @lTotalMonth int 
	SET @lHoliDayCount =0
	
		WHILE @lCount > 0 
					BEGIN
						SELECT
							@lFromYear = YEAR(FromDate),
							@lFromMonth = MONTH(FromDate),
							@lFromDay = DAY(FromDate),
							@lToYear = YEAR(ToDate),
							@lToMonth = MONTH(ToDate),
							@lToDay = DAY(ToDate),
							@lDivision = DivId,
							@lBeginCount = DAY(FromDate),
							@lEndCount = DAY(ToDate)
						FROM #Table1 T WHERE Id = @lCount AND IsExists = 0
					
						IF(@lFromDay = @lToDay  AND @lFromMonth = @lToMonth)
						BEGIN
							
							SELECT @lStatus = [sAttendance].[fWeekHOffGet]
							(@lFromYear,@lFromMonth,@lFromDay,@rBatchId,@rClassId,@lDivision,'',@rOrgId)
							IF(@lStatus = 'H')SET @lHoliDayCount=@lHoliDayCount+1
							
							
						END
						ELSE IF(@lFromDay != @lToDay)
						BEGIN
							IF(@lFromMonth = @lToMonth)
							BEGIN
								WHILE (@lBeginCount <= @lEndCount)
								BEGIN
								  
									SELECT @lStatus = [sAttendance].[fWeekHOffGet] 	(@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rClassId,@lDivision,'',@rOrgId)
									IF(@lStatus = 'H')
										SET @lHoliDayCount=@lHoliDayCount+1
									
									SET @lBeginCount = @lBeginCount +1	
							   END
							END
							ELSE
							BEGIN
								SET @lTotalMonth = @lToMonth - @lFromMonth
								 WHILE (@lTotalMonth > 0 AND @rMonth=@lFromMonth)
								 BEGIN
									 DECLARE @lDays int = 0
									 SELECT @lDays = sCommon.fGetDaysInMonth(@lFromMonth,@lFromYear)
									 WHILE (@lBeginCount  <= @lDays)
									 BEGIN
										
										SELECT @lStatus = [sAttendance].[fWeekHOffGet] 	(@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rClassId,@lDivision,'',@rOrgId)
										IF(@lStatus = 'H')
											SET @lHoliDayCount=@lHoliDayCount+1
											
										SET @lBeginCount = @lBeginCount +1
									END
									SET @lTotalMonth = @lTotalMonth-1
								 END
							END
						END
						SET @lCount = @lCount - 1
					END
	SELECT @lHoliDayCount
	DROP TABLE #Table1
	DROP TABLE #Table2
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlyAttenanceRegisterDateWiseGet]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint=0,
	 @rOrgId int,
	 @rFromDate date,
	 @rToDate date,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rSubjectId int = 0,
	 @rPeriodNo SmallInt = 0
	 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	 
BEGIN 

	IF(@rSubjectId > 0)	
		BEGIN
			DECLARE @lClassSubjectId int = 0;
			SELECT @lClassSubjectId = Id FROM sSetup.tClassSubject WHERE ClassId = @rClassId AND SubjectId = @rSubjectId

			SELECT	    
				ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
				SA.Code,
				SA.RollNo,
				SA.AcademicId,
				SA.Name,
				SA.ClassId,
				SA.DivisionId,
				SA.ClassName,Sa.DivisionName,	 
				A.LeftDate,
				SA.StatusId,
				A.AdmissionDate,
				ISNULL(sAttendance.fGetAbsentDatesDateWise(SA.AcademicId, @rAttendanceTypeId, @rFromDate, @rToDate, @rSubjectId,@rPeriodNo),'') AS AbsentDates
	 	 
			FROM
				sStudent.vStudentAcademic SA 
				INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
				INNER JOIN sSetup.tClassSubject CS ON CM.Id = CS.ClassId
				LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId= SA.AcademicId AND OS.ClassSubjectId = @lClassSubjectId
             
			WHERE  
	        
				SA.OrgId=@rOrgId  
				AND  (SA.BatchId=@rBatchId) AND  (SA.ClassId=@rClassId) 
				AND  (SA.DivisionId=@rDivisionId)
				AND  A.AdmissionDate <=  @rToDate
				AND ((A.LeftDate >= @rFromDate) OR ISNULL(A.LeftDate,'') = '')
				AND (CS.SubjectId = @rSubjectId)
				AND (CS.IsOptional = 0 OR OS.ClassSubjectId = @lClassSubjectId )
				Order By SA.RollNo
		END
	ELSE
		BEGIN
			SELECT	    
				ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
				SA.Code,
				SA.RollNo,
				SA.AcademicId,
				SA.Name,
				SA.ClassId,
				SA.DivisionId,
				SA.ClassName,Sa.DivisionName,	 
				A.LeftDate,
				SA.StatusId,
				A.AdmissionDate,
				ISNULL(sAttendance.fGetAbsentDatesDateWise(SA.AcademicId, @rAttendanceTypeId, @rFromDate, @rToDate, 0,0),'') AS AbsentDates
	 	 
			FROM
				sStudent.vStudentAcademic SA 
				INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
				--INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
				--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
             
			WHERE  
	        
				SA.OrgId=@rOrgId  
				AND  (SA.BatchId=@rBatchId) AND  (SA.ClassId=@rClassId) 
				AND  (SA.DivisionId=@rDivisionId)
				AND  A.AdmissionDate <=  @rToDate
				AND ((A.LeftDate >= @rFromDate) OR ISNULL(A.LeftDate,'') = '')
				Order By SA.RollNo
		END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlyAttenanceRegisterGet]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint=0,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0  
	 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date,@lLastDate date
	
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	SET @lLastDate = sCommon.fGetLastDateofMonth(@lFirstDate)
	Declare @Days int 
	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	--DECLARE @lAdmissionDate date 
	-- select @lAdmissionDate=Stud.AdmissionDate from    sStudent.tStudentAdmission Stud  inner join sStudent.vStudentAcademic A ON A.StudentId = Stud.StudentId
	--						Where AdmissionStandardId=@rClassId AND Stud.BatchId =@rBatchId  
	 
BEGIN 
 
CREATE Table #AttendanceRegistertempTable
(
	 
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(100),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	AdmissionDate date
 
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	AdmissionDate
  
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	 OM.FooterSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 A.AdmissionDate
	 
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND (YEAR(SR.AttendanceDate)=@rForYear) AND (MONTH(SR.AttendanceDate)=@rForMonth) AND (SR.AttendanceTypeId=@rAttendanceTypeId)
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
             
             WHERE  
	        
			  SA.OrgId=@rOrgId  
	          AND  (SA.BatchId=@rBatchId) AND  (SA.ClassId=@rClassId) 
	          AND  (SA.DivisionId=@rDivisionId)
	          AND  A.AdmissionDate <=  @lLastDate
	          AND ((A.LeftDate >= @lFirstDate) OR ISNULL(A.LeftDate,'') = '')
			  
				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](@rForYear,@rForMonth,@li,@rBatchId,@rClassId, @rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END
 
SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,isnull(ForYear,'') AS ForYear,
			isnull(ForMonth,'') AS ForMonth,ClassId,ClassName,DivisionId,
			DivisionName, 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
				
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
			 
	 		   sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),LeftDate,[1]) AS P1,
	 	 
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),LeftDate,[2]) AS P2,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),LeftDate,[3]) AS P3,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),LeftDate,[4]) AS P4,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),LeftDate,[5]) AS P5,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),LeftDate,[6]) AS P6,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),LeftDate,[7]) AS P7,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),LeftDate,[8]) AS P8,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),LeftDate,[9]) AS P9,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),LeftDate,[10]) AS P10,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),LeftDate,[11]) AS P11,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),LeftDate,[12]) AS P12,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),LeftDate,[13]) AS P13,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),LeftDate,[14]) AS P14,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),LeftDate,[15]) AS P15,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),LeftDate,[16]) AS P16,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),LeftDate,[17]) AS P17,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),LeftDate,[18]) AS P18,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),LeftDate,[19]) AS P19,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),LeftDate,[20]) AS P20,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),LeftDate,[21]) AS P21,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),LeftDate,[22]) AS P22,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),LeftDate,[23]) AS P23,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),LeftDate,[24]) AS P24,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),LeftDate,[25]) AS P25,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),LeftDate,[26]) AS P26,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),LeftDate,[27]) AS P27,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),LeftDate,[28]) AS P28,
			CASE WHEN @Days>=29 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),LeftDate,[29]) end AS P29,
			CASE WHEN @Days>=30 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),LeftDate,[30])end AS P30,
		    
			CASE WHEN @Days>=31 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),LeftDate,[31])end AS P31,
		 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth
,0 Ispresent,
0 AS AttendanceTagId,
AdmissionDate  
FROM
(
	Select  
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE 
			 WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate,		 
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,
		AdmissionDate

		 
		
	 FROM 
		#AttendanceRegistertempTable ST 
		LEFT JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		     GROUP BY  AcademicId  
    ) TC ON TC.AcademicId = PivotTable.AcademicId 
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 	 
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(
		SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sStudent.tAcademic A 
			LEFT JOIN  sAttendance.tStudentRegister SR ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE   
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			    		
            --AND (SA.StatusId = 1)
	        --AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND  ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        --AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	  --      AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			--AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
    ORDER BY RollNo; 
    
--select * from #TempDaysTempTable 
drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlyAttendaceImportAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rClassId int=0,
    @rDivisionId int,
    @rAcademicId bigint,
    @rAttendanceTypeId tinyint,
    @rCreatedUserId bigint,
    @rBatchId int=0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN

		CREATE TABLE #TmpMonthlyAttendance
		(
		 Id int IDENTITY(1,1),
		 AttendanceDate Date,
		 IsPresent Bit
		)
		 
		INSERT INTO #TmpMonthlyAttendance 
		SELECT	
		DISTINCT	
			AttendanceDate,
			IsPresent
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AttendanceDate DateTime,
				IsPresent bit
		   ) AS At

		    
		DECLARE @cnt INT = 1, @lAttendanceDateCount INT = 0
		SELECT @lAttendanceDateCount = COUNT(*) FROM #TmpMonthlyAttendance

		 
		WHILE @cnt < @lAttendanceDateCount + 1
		BEGIN
		     DECLARE @lIsPresent bit , @lAttendanceDate Date

			 SELECT @lIsPresent = IsPresent,@lAttendanceDate = AttendanceDate FROM #TmpMonthlyAttendance WHERE Id = @cnt

			 DELETE SR FROM sAttendance.tStudentRegister SR 
			 INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId
			 WHERE 
			 SR.AttendanceTypeId = @rAttendanceTypeId AND SR.AttendanceDate = @lAttendanceDate
			 AND SA.DivisionId=@rDivisionId AND SA.Id = @rAcademicId
			 AND SA.OrgId = @rOrgId AND SA.BatchId =@rBatchId

			 INSERT INTO sAttendance.tStudentRegister 
			 (
				AcademicId,
				EmployeeId,
				AttendanceTypeId,
				AttendanceDate,
				SubjectId,
				RepeatCount,
				IsPresent,
				AbsentReasonId,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				AttendanceTagId
			 )
			SELECT	
			DISTINCT	
				A.Id,
				NULL,
				@rAttendanceTypeId,
				@lAttendanceDate,
				0,
				0,
				@lIsPresent,
				0,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				0
			FROM   sStudent.tAcademic A  
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			WHERE A.Id = @rAcademicId AND SA.AdmissionDate <= @lAttendanceDate
			AND ((SA.LeftDate > @lAttendanceDate) OR  ISNULL(SA.LeftDate,'') = '') 

			 SET @cnt = @cnt + 1
		END

		 
		

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlyAttendaceImportDateWiseAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rClassId int=0,
    @rDivisionId int,
    @rAcademicId bigint,
    @rAttendanceTypeId tinyint,
    @rCreatedUserId bigint,
    @rBatchId int=0,
	@rSubjectId int = 0,
	@rPeriodNo int = 0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN

		CREATE TABLE #TmpMonthlyAttendance
		(
		 Id int IDENTITY(1,1),
		 AttendanceDate Date,
		 IsPresent Bit
		)
		 
		INSERT INTO #TmpMonthlyAttendance 
		SELECT	
		DISTINCT	
			AttendanceDate,
			IsPresent
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AttendanceDate DateTime,
				IsPresent bit
		   ) AS At

		    
		DECLARE @cnt INT = 1, @lAttendanceDateCount INT = 0
		SELECT @lAttendanceDateCount = COUNT(*) FROM #TmpMonthlyAttendance

		 
		WHILE @cnt < @lAttendanceDateCount + 1
		BEGIN
		     DECLARE @lIsPresent bit , @lAttendanceDate Date

			 SELECT @lIsPresent = IsPresent,@lAttendanceDate = AttendanceDate FROM #TmpMonthlyAttendance WHERE Id = @cnt

			 DELETE SR FROM sAttendance.tStudentRegister SR 
			 INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId
			 WHERE 
			 SR.AttendanceTypeId = @rAttendanceTypeId AND SR.AttendanceDate = @lAttendanceDate
			 AND SA.DivisionId=@rDivisionId AND SA.Id = @rAcademicId
			 AND SA.OrgId = @rOrgId AND SA.BatchId =@rBatchId
			 AND (SR.SubjectId = @rSubjectId OR @rSubjectId = 0)
			 AND (SR.PeriodNo = @rPeriodNo OR @rPeriodNo = 0)

			 INSERT INTO sAttendance.tStudentRegister 
			 (
				AcademicId,
				EmployeeId,
				AttendanceTypeId,
				AttendanceDate,
				SubjectId,
				RepeatCount,
				IsPresent,
				AbsentReasonId,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				AttendanceTagId,
				PeriodNo
			 )
			SELECT	
			DISTINCT	
				A.Id,
				NULL,
				@rAttendanceTypeId,
				@lAttendanceDate,
				@rSubjectId,
				@rPeriodNo,
				@lIsPresent,
				0,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				0,
				@rPeriodNo
			FROM   sStudent.tAcademic A  
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			WHERE A.Id = @rAcademicId AND SA.AdmissionDate <= @lAttendanceDate
			AND ((SA.LeftDate > @lAttendanceDate) OR  ISNULL(SA.LeftDate,'') = '') 

			 SET @cnt = @cnt + 1
		END

		 
		

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlyRegisterAdd]
	 
	@rAcademicId bigint,
	@rAttendanceTypeId tinyint,
	@rSubjectId int,
	@rForMonth tinyint,
	@rForYear smallint,
	@rTotalCount tinyint,
	@rAttendanceCount tinyint=0,
	@rPresentCount tinyint,
	@rAbsentCount tinyint,
	@rAveragePresence decimal(6,2),
	@rAbsentDays nvarchar(200),
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	 --BEGIN TRANSACTION	
	 IF(@rTotalCount != 0)
	 BEGIN
		SET @rAveragePresence=(convert(decimal(5,2),(convert(decimal(5,2),@rPresentCount)*100)/(convert(decimal(5,2),@rTotalCount))))
	 END
	 ELSE
	 BEGIN
	 DELETE from sAttendance.tMonthlyRegister WHERE AcademicId=@rAcademicId AND 
	 AttendanceTypeId=@rAttendanceTypeId AND SubjectId=@rSubjectId AND ForMonth=@rForMonth AND ForYear=@rForYear
	 SELECT @rAcademicId AS Result
	 RETURN
	 END
     
	 IF NOT EXISTS(SELECT * from sAttendance.tMonthlyRegister WHERE AcademicId=@rAcademicId AND 
	 AttendanceTypeId=@rAttendanceTypeId AND SubjectId=@rSubjectId AND ForMonth=@rForMonth AND ForYear=@rForYear)
	 BEGIN
	 INSERT INTO sAttendance.tMonthlyRegister
		(
			AcademicId,
			AttendanceTypeId,
			SubjectId,
			ForMonth,
			ForYear,
			TotalCount,
			AttendanceCount,
			PresentCount,
			AbsentCount,
			AveragePresence,
			AbsentDays,
			UpdatedUserId,
			UpdatedDateTime
		)
		VALUES
		(
			@rAcademicId,
			@rAttendanceTypeId,
			@rSubjectId,
			@rForMonth,
			@rForYear,
			@rTotalCount,
			@rAttendanceCount,
			@rPresentCount,
			@rAbsentCount,
			@rAveragePresence,
			@rAbsentDays,
			@rCreatedUserId,
			sCommon.fGetDate()
		)		
	 	            
	END
	ELSE
	BEGIN
	UPDATE sAttendance.tMonthlyRegister
	SET
		TotalCount=@rTotalCount,
		AttendanceCount=@rAttendanceCount,
		PresentCount=@rPresentCount,
		AbsentCount=@rAbsentCount,
		AveragePresence=@rAveragePresence,
		AbsentDays=@rAbsentDays,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=sCommon.fGetDate()
	WHERE
		AcademicId=@rAcademicId 
		AND AttendanceTypeId=@rAttendanceTypeId 
		AND SubjectId=@rSubjectId 
		AND ForMonth=@rForMonth 
		AND ForYear=@rForYear
	END
		SELECT @rAcademicId AS Result
	
	--	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlyRegisterDelete]
	 
	@rClassId int, 
	@rDivisionId int,
	@rBatchId int,
	@rAttendanceTypeId tinyint,
	@rSubjectId int,
	@rForYear int,
	@rForMonth int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	 BEGIN TRANSACTION	

			DELETE MR
			FROM sAttendance.tMonthlyRegister MR
				INNER JOIN sStudent.tAcademic A
				ON MR.AcademicId= A.Id
				
			WHERE
			
			((A.DivisionId = @rDivisionId) OR (@rDivisionId=0))
			AND ((A.ClassId = @rClassId) OR (@rClassId=0))
			AND A.BatchId = @rBatchId
			AND MR.AttendanceTypeId = @rAttendanceTypeId
			AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND MR.ForYear = @rForYear
			AND MR.ForMonth = @rForMonth
		
			SELECT 1 AS Result
		
	COMMIT TRANSACTION
END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
			SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlyRegisterGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int=0,
	 	 @rDivisionId int=0,
	 	 @rForMonth tinyint,
	 	 @rForYear smallint,
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rIsImport bit,
	 	 @rStatusId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if (@rIsImport = 1)
BEGIN
	Select 
		SN.AcademicId,
		SN.Code,
		SN.FirstName + ' ' + SN.MiddleName + ' ' + SN.LastName AS Name,
		SN.RollNo,
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
		ISNULL(MR.AveragePresence,0) AS AveragePresence,
		CASE WHEN SS.WorkingDays IS NOT NULL
			THEN ISNULL(SS.WorkingDays,0)			 
			ELSE ISNULL(MS.WorkingDays,0) END AS TotalCount,		
		ISNULL(MS.WorkingDays,0)  AS TotalCount,
		(Select COUNT(1) FROM sAttendance.tStudentRegister SR1 
			WHERE SR1.AcademicId=SN.AcademicId 
				AND SR1.IsPresent=1 
				AND SR1.AttendanceTypeId=@rAttendanceTypeId
				AND ((SR1.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
				AND DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth 
				AND DATENAME(YEAR,SR1.AttendanceDate)=@rForYear)  AS PresentCount,
		 (Select COUNT(1) FROM sAttendance.tStudentRegister SR2
			WHERE SR2.AcademicId=SN.AcademicId 
			AND SR2.IsPresent=0 
			AND SR2.AttendanceTypeId=@rAttendanceTypeId
			AND ((SR2.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
			AND DATEPART(MONTH,SR2.AttendanceDate)=@rForMonth 
			AND DATENAME(YEAR,SR2.AttendanceDate)=@rForYear)  AS AbsentCount,
		
		(SELECT [sAttendance].[fAbsentDaysGet](@rForMonth,@rForYear, @rAttendanceTypeId,@rSubjectId,SN.AcademicId) AS MyResult)  AS AbsentDays
		
		
	From 
		sStudent.vStudentName SN 
	LEFT JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId
		AND MY.MonthNumber=@rForMonth AND MY.YearNumber=@rForYear
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	INNER JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SN.ClassId
		AND MS.ForMonth=MY.MonthNumber AND MS.ForYear=MY.YearNumber
	LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SN.AcademicId
		AND SS.ForMonth=MY.MonthNumber AND SS.ForYear=MY.YearNumber
	WHERE
		(MY.BatchId=@rBatchId)
	AND (SN.ClassId=@rClassId)
	AND (SN.DivisionId=@rDivisionId)
	AND SN.BatchId = @rBatchId
	AND ((SN.StatusId = @rStatusId) OR (@rStatusId=0))
	 
					
	ORDER BY SN.RollNo
END
ELSE
BEGIN	
	Select 
		SN.AcademicId,
		SN.Code,
		SN.FirstName + ' ' + SN.MiddleName + ' ' + SN.LastName AS Name,
		SN.RollNo,
		MM.Title AS ForMonthInWord,
		MM.Id AS ForMonth, 
		MR.ForYear AS ForYear,
		ISNULL(MR.TotalCount,0) AS  TotalCount,
		ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
		ISNULL(MR.PresentCount,0) PresentCount,
		ISNULL(MR.AbsentCount,0) AS AbsentCount,		 
		ISNULL(MR.AbsentDays,'') AS AbsentDays,
		ISNULL(MR.AveragePresence,0) AS AveragePresence
	From 
		sStudent.vStudentName SN 
	--LEFT JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId
	--	AND MY.MonthNumber=@rForMonth AND MY.YearNumber=@rForYear
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		--AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
    INNER JOIN sCommon.tMonthMaster MM ON MR.ForMonth = MM.Id
	--LEFT JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SN.ClassId
	--	AND MS.ForMonth=MY.MonthNumber AND MS.ForYear=MY.YearNumber
	--LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SN.AcademicId
	--	AND SS.ForMonth=MY.MonthNumber AND SS.ForYear=MY.YearNumber
		
	WHERE
	--	(MY.BatchId=@rBatchId)
	--AND
	 (SN.ClassId=@rClassId)
	AND (SN.DivisionId=@rDivisionId)
	AND SN.BatchId = @rBatchId
	AND MR.ForYear = @rForYear AND MR.ForMonth = @rForMonth
	AND ((SN.StatusId = @rStatusId) OR (@rStatusId=0))
	ORDER BY SN.RollNo
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlyRegisterImportAll]
	 	 
	 	 @rBatchId int,
	 	 @rForMonth tinyint,
	 	 @rForYear smallint,
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rCreatedUserId bigint,
	 	 @rClassId int=0,
	 	 @rDivisionId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	
	BEGIN TRANSACTION



  --alter table sAttendance.tStudentRegister add  ID int identity(1,1)

  --  delete E
  --  from  sAttendance.tStudentRegister E
  --  inner join
  --  (select *,
  --  RANK() OVER ( PARTITION BY AcademicId,AttendanceTypeId ,AttendanceDate,subjectId ORDER BY ID DESC )rank
  --  From sAttendance.tStudentRegister SR1
  --     WHERE 		
		--	SR1.AttendanceTypeId=@rAttendanceTypeId
		--	AND ((SR1.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
		--	AND (DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth  )
		--	AND (DATENAME(YEAR,SR1.AttendanceDate)=@rForYear ) 		 
		--	--AND (A.BatchId=@rBatchId)			 
		--	--AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
		--	--AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
    
    
  --   )T on E.ID=t.Id
  --  where T.Rank>1

  --  alter table sAttendance.tStudentRegister 
  --  drop  column ID



--  alter table sAttendance.tStudentRegister add  Id int identity(1,1)  
--    WITH tblTemp as
--(
--SELECT ROW_NUMBER() Over(PARTITION BY AcademicId,AttendanceTypeId ,AttendanceDate,subjectId,RepeatCount ORDER BY Id)
--   As RowNumber,* FROM sAttendance.tStudentRegister
--)
--SELECT * FROM tblTemp where RowNumber >1


--  alter table sAttendance.tStudentRegister 
--    drop  column Id



	DELETE MR
	 
		FROM sAttendance.tMonthlyRegister MR 
		INNER JOIN sStudent.tAcademic A ON MR.AcademicId = A.Id
		
		WHERE  
		MR.ForMonth =  @rForMonth
		AND MR.ForYear =  @rForYear	
		AND MR.AttendanceTypeId = @rAttendanceTypeId
		AND	MR.SubjectId=@rSubjectId
		AND A.BatchId = @rBatchId
		AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))

	INSERT INTO sAttendance.tMonthlyRegister
	(
		AcademicId,
		AttendanceTypeId,
		SubjectId,
		ForMonth,
		ForYear,
		TotalCount,
		AttendanceCount,
		PresentCount,
		AbsentCount,
		AbsentDays,
		UpdatedUserId,
		UpdatedDateTime
	)
	Select 
		SN.AcademicId,
		@rAttendanceTypeId,
		@rSubjectId,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		CASE 
			WHEN SS.WorkingDays IS NOT NULL
			THEN ISNULL(SS.WorkingDays,0)
			ELSE ISNULL(MS.WorkingDays,0) END AS TotalCount,
	
			ISNULL(TC.TCount,0) AS AttendanceCount,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
		     ISNULL(AC.ACount,0) As  AbsentCount,

		'' AS AbsentDays,
		@rCreatedUserId,
		sCommon.fGetDate()
		

		
	From 
		sStudent.vStudentName SN 
	LEFT JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId
		AND MY.MonthNumber=@rForMonth AND MY.YearNumber=@rForYear
	LEFT JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SN.ClassId
		AND MS.ForMonth=MY.MonthNumber AND MS.ForYear=MY.YearNumber AND MS.BatchId=@rBatchID
	LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SN.AcademicId
		AND SS.ForMonth=MY.MonthNumber AND SS.ForYear=MY.YearNumber
	LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS TCount 
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 		
			SR1.AttendanceTypeId=@rAttendanceTypeId
			AND ((SR1.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
			AND (DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth  )
			AND (DATENAME(YEAR,SR1.AttendanceDate)=@rForYear ) 		 
			AND (A.BatchId=@rBatchId)			 
			AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			GROUP BY A.Id
    ) TC ON TC.AcademicId = SN.AcademicId
    LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS ACount  
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 
		   SR1.IsPresent = 0		
			AND SR1.AttendanceTypeId=@rAttendanceTypeId
			AND ((SR1.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0))
			AND (DATEPART(MONTH,SR1.AttendanceDate)=@rForMonth  )
			AND (DATENAME(YEAR,SR1.AttendanceDate)=@rForYear ) 		 
			AND (A.BatchId=@rBatchId)			 
			AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			GROUP BY A.Id
    ) AC ON AC.AcademicId = SN.AcademicId
	WHERE
	(MY.BatchId=@rBatchId) 
	 AND SN.BatchId = @rBatchId
	 AND ((SN.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((SN.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	
	UPDATE MR
	SET 
		MR.AveragePresence =   (convert(decimal(5,2),(convert(decimal(5,2),PresentCount)*100)/(convert(decimal(5,2),AttendanceCount)))) 
 		FROM sAttendance.tMonthlyRegister MR 
		INNER JOIN sStudent.tAcademic A ON MR.AcademicId = A.Id		
		WHERE 
		MR.ForMonth =  @rForMonth
		AND MR.ForYear =  @rForYear	
		AND MR.AttendanceTypeId = @rAttendanceTypeId
		AND	MR.SubjectId=@rSubjectId
		AND A.BatchId = @rBatchId
		AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ISNULL(MR.AttendanceCount,0) <> 0
		
		UPDATE MR
	SET 		 
		AbsentDays = [sAttendance].[fAbsentDaysGet](@rForMonth,@rForYear, @rAttendanceTypeId,@rSubjectId,MR.AcademicId )
		FROM sAttendance.tMonthlyRegister MR 
		INNER JOIN sStudent.tAcademic A ON MR.AcademicId = A.Id
		
		WHERE  MR.AbsentCount > 0
		AND MR.ForMonth =  @rForMonth
		AND MR.ForYear =  @rForYear	
		AND MR.AttendanceTypeId = @rAttendanceTypeId
		AND	MR.SubjectId=@rSubjectId
		AND A.BatchId = @rBatchId
		AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	
	SELECT 1 AS Result

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlyRegisterStudentGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

declare @lAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid1 nvarchar(max)=''

IF EXISTS (SELECT 1 FROM  sSetup.fMonthYearForBatchGET(@rBatchId) WHERE  YearNumber = Year(GETDATE()) AND MonthNumber = MONTH(GETDATE()))
--For Current Batch
BEGIN
IF NOT EXISTS(select 1 From sAttendance.tMonthlyRegister MR  where AcademicId=@rAcademicId and ForMonth=Month(GETDATE()) and ForYear=Year(GETDATE()))
--Current Month Count If Exists

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

		SET @YearNumber =Year(GETDATE())

		print @YearNumber

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

		SET @AttendanceCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		
		
		IF(@AttendanceCount<>0.00)		
		    SET @AveragePresence= (@PresentCount/@AttendanceCount)*100		
		ELSE
		 SET @AveragePresence= 0
		 print @AveragePresence
		 IF(@AttendanceCount<>0.00)		
		    SET @AverageAbsent= (@AbsentCount/@AttendanceCount)*100		
		ELSE
		 SET @AverageAbsent= 0

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

		ORDER BY AcademicId
		FOR XML PATH('')),2,200000) AS CSV
)
SELECT *  FROM (Select 
		SN.AcademicId,
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		ISNULL(MR.TotalCount,0) AS TotalCount,
		ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
		ISNULL(MR.PresentCount,0) AS PresentCount,
		ISNULL(MR.AbsentCount,0) AS AbsentCount,
		ISNULL(MR.AveragePresence,0) AS AveragePresence,
		ISNULL(MR.AbsentDays,'') AS AbsentDays,
		ISNULL(100.00-MR.AveragePresence,0) As AverageAbsent
		
		
	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) 
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND MR.ForMonth=MY.MonthNumber 
		AND MR.ForYear=MY.YearNumber
	WHERE
		(SN.AcademicId=@rAcademicId) 
		AND MY.MonthNumber <> Month(GetDate())

   UNION ALL
   
   SELECT 
           @rAcademicId AS AcademicId,
           Isnull(LEFT(DATENAME(MONTH,Getdate()),10),'') AS ForMonthInWord,
           MONTH(Getdate()) AS ForMonth,
           YEAR(Getdate()) AS ForYear,
           ISNULL(CAST(@AttendanceCount AS int),0) AS TotalCount,
           ISNULL(CAST(@AttendanceCount AS int),0) AS AttendanceCount,                    
           ISNULL(CAST(@PresentCount AS int),0) AS PresentCount,
           ISNULL(CAST(@AbsentCount AS int),0) AS AbsentCount,
           ISNULL(@AveragePresence,0) AS AveragePresence,
		   ISNULL(@AbsentDays,0) AS AbsentDays,
		   ISNULL(@AverageAbsent,0) AS AverageAbsent) AS TempStudentAttendance	
	ORDER BY ForYear,ForMonth
	END	
	ELSE  --Changes for Mantis Id :0032381
	BEGIN
		Select 
			SN.AcademicId,
			MY.MonthTitle AS ForMonthInWord,
			MY.MonthNumber AS ForMonth, 
			MY.YearNumber AS ForYear,
			ISNULL(MR.TotalCount,0) AS TotalCount,
			ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
			ISNULL(MR.PresentCount,0) AS PresentCount,
			ISNULL(MR.AbsentCount,0) AS AbsentCount,
			ISNULL(MR.AveragePresence,0) AS AveragePresence,
			ISNULL(MR.AbsentDays,'') AS AbsentDays,
			ISNULL(100.00-MR.AveragePresence,0) As AverageAbsent		
		From sStudent.vStudentName SN 
		INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
		LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
			AND (MR.AttendanceTypeId=@rAttendanceTypeId) 
			AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND MR.ForMonth=MY.MonthNumber 
			AND MR.ForYear=MY.YearNumber
		WHERE
			(SN.AcademicId=@rAcademicId) 
	END
END
ELSE --For Past Batch
	BEGIN
	Select 
		SN.AcademicId,
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		ISNULL(MR.TotalCount,0) AS TotalCount,
		ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
		ISNULL(MR.PresentCount,0) AS PresentCount,
		ISNULL(MR.AbsentCount,0) AS AbsentCount,
		ISNULL(MR.AveragePresence,0) AS AveragePresence,
		ISNULL(MR.AbsentDays,'') AS AbsentDays,
		ISNULL(100.00-MR.AveragePresence,0) As AverageAbsent
		
		
	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) 
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND MR.ForMonth=MY.MonthNumber 
		AND MR.ForYear=MY.YearNumber
	WHERE
		(SN.AcademicId=@rAcademicId) 
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

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

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

		SET @YearNumber =Year(GETDATE())



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

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


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

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

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

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


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


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


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

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlyRegisterVerifyAllDataGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int=0,
	 	 @rDivisionId int=0,
	 	 @rForMonth tinyint,
	 	 @rForYear smallint,
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rStatusId smallint=0,
	 	 @rFromAveragePresence decimal(6,2),
	 	 @rToAveragePresence decimal(6,2)
	 	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF (@rFromAveragePresence = 0 AND @rToAveragePresence = 0)
begin
	SELECT 
		MM.Title AS 'Month',
		MR.ForYear AS 'Year',
		CM.Title +' - '+ DM.Title AS 'Class',
		SN.RollNo AS 'Roll No',
		SN.FirstName + ' ' + SN.MiddleName + ' ' + SN.LastName AS Name,
		SN.Code,
		ISNULL(MR.TotalCount,0) AS  'Working Days',
		ISNULL(MR.AttendanceCount,0) AS 'Attendance Count',
		ISNULL(MR.PresentCount,0) 'Present Count',
		ISNULL(MR.AbsentCount,0) AS 'Absent Count',
		ISNULL(MR.AveragePresence,0) AS 'Average Presence',
		ISNULL(MR.AbsentDays,'') AS 'Absent Date'
	From 
		sStudent.vStudentName SN 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
    INNER JOIN sCommon.tMonthMaster MM ON MR.ForMonth = MM.Id
	INNER JOIN sSetup.tClassMaster CM ON SN.ClassId = CM.Id
	INNER JOIN sSetup.tDivisionMaster DM ON SN.DivisionId = DM.Id
	WHERE
	((SN.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SN.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND SN.BatchId = @rBatchId
	AND MR.ForYear = @rForYear AND MR.ForMonth = @rForMonth
	AND ((SN.StatusId = @rStatusId) OR (@rStatusId=0))
	--AND MR.TotalCount != MR.AttendanceCount	
	ORDER BY DM.OrderIndex, SN.RollNo
END
ELSE
BEGIN
	SELECT 
		MM.Title AS 'Month',
		MR.ForYear AS 'Year',
		CM.Title +' - '+ DM.Title AS 'Class',
		SN.RollNo AS 'Roll No',
		SN.FirstName + ' ' + SN.MiddleName + ' ' + SN.LastName AS Name,
		SN.Code,
		ISNULL(MR.TotalCount,0) AS  'Working Days',
		ISNULL(MR.AttendanceCount,0) AS 'Attendance Count',
		ISNULL(MR.PresentCount,0) 'Present Count',
		ISNULL(MR.AbsentCount,0) AS 'Absent Count',
		ISNULL(MR.AveragePresence,0) AS 'Average Presence',
		ISNULL(MR.AbsentDays,'') AS 'Absent Date'
	From 
		sStudent.vStudentName SN 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
    INNER JOIN sCommon.tMonthMaster MM ON MR.ForMonth = MM.Id
	INNER JOIN sSetup.tClassMaster CM ON SN.ClassId = CM.Id
	INNER JOIN sSetup.tDivisionMaster DM ON SN.DivisionId = DM.Id
	WHERE
	((SN.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SN.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND SN.BatchId = @rBatchId
	AND MR.ForYear = @rForYear AND MR.ForMonth = @rForMonth
	AND ((SN.StatusId = @rStatusId) OR (@rStatusId=0))
	--AND MR.TotalCount != MR.AttendanceCount	
	AND (MR.AveragePresence>=convert(Decimal(6,2),@rFromAveragePresence))
	AND (MR.AveragePresence<=convert(Decimal(6,2),@rToAveragePresence))
	ORDER BY DM.OrderIndex, SN.RollNo
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlySetupAdd]
	 
	@rBatchId int,
	@rClassId int,
	@rForMonth tinyint,
	@rForYear smallint,
	@rWorkingDays smallint,
	@rIsAllClass bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 IF(@rIsAllClass=1)
	 BEGIN
		DECLARE @lCount INT
		CREATE TABLE #tTable  
		(
			Id bigint identity,
			ClassId int
		)
		INSERT INTO #tTable
		(
			ClassId
		)
		SELECT ClassId FROM sSetup.tBatchClass WHERE BatchId=@rBatchId
		SELECT @lCount =  COUNT(Id) FROM #tTable
		WHILE @lCount > 0 
		BEGIN
			SELECT @rClassId=ClassId FROM #tTable WHERE Id = @lCount
			IF NOT EXISTS(SELECT * from sAttendance.tMonthlySetup WHERE BatchId=@rBatchId AND ClassId=@rClassId AND 
			 ForMonth=@rForMonth AND ForYear=@rForYear)
			 BEGIN
			 INSERT INTO sAttendance.tMonthlySetup
				(
					BatchId,
					ClassId,
					ForMonth,
					ForYear,
					WorkingDays
				)
				VALUES
				(
					@rBatchId,
					@rClassId,
					@rForMonth,
					@rForYear,
					@rWorkingDays
				)		
			 	            
			END
			ELSE
			BEGIN
			UPDATE sAttendance.tMonthlySetup
			SET
				WorkingDays=@rWorkingDays
			WHERE
				BatchId=@rBatchId 
				AND ClassId=@rClassId
				AND ForMonth=@rForMonth 
				AND ForYear=@rForYear
			END
				SELECT @rClassId AS Result
			SET @lCount = @lCount - 1
		END
	 END
	 ELSE
	 BEGIN
	 
	 IF NOT EXISTS(SELECT * from sAttendance.tMonthlySetup WHERE BatchId=@rBatchId AND ClassId=@rClassId AND 
	 ForMonth=@rForMonth AND ForYear=@rForYear)
	 BEGIN
	 INSERT INTO sAttendance.tMonthlySetup
		(
			BatchId,
			ClassId,
			ForMonth,
			ForYear,
			WorkingDays
		)
		VALUES
		(
			@rBatchId,
			@rClassId,
			@rForMonth,
			@rForYear,
			@rWorkingDays
		)		
	 	            
	END
	ELSE
	BEGIN
	UPDATE sAttendance.tMonthlySetup
	SET
		WorkingDays=@rWorkingDays
	WHERE
		BatchId=@rBatchId 
		AND ClassId=@rClassId
		AND ForMonth=@rForMonth 
		AND ForYear=@rForYear
	END
		SELECT @rClassId AS Result
	END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pMonthlySetupGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		ISNULL(MS.WorkingDays,0) AS WorkingDays
	From sSetup.fMonthYearForBatchGET(@rBatchId) AS MY
	LEFT JOIN sAttendance.tMonthlySetup MS ON MS.BatchId=MY.BatchId AND (MS.ClassId=@rClassId)
	AND MS.ForMonth = MY.MonthNumber AND MS.ForYear = MY.YearNumber
	WHERE
		(MY.BatchId=@rBatchId)
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pRepeatCountGet]
	 	 
	 	 @rAttendanceDate date,
		 @rSubjectId int,
		 @rClassId int=0,
		 @rDivsionId int=0,
		 @rBatchId int = 0,
		 @rSubjectBatchId int = 0
		 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 



	SELECT 
			ISNULL(MAX(RepeatCount),0) as RepeatCount
			
  FROM 
            sAttendance.tStudentRegister SR INNER JOIN sStudent.tAcademic A
            ON A.Id = SR.AcademicId
  WHERE 
      (SR.AttendanceDate=@rAttendanceDate)
	  AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
	  AND A.DivisionId = @rDivsionId AND A.BatchId = @rBatchId

	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAttendance].[pRptAbsentStudentContinueGet]
	 	 
		 @rBuilder1 nvarchar(max)='',
		 @rBuilder2 nvarchar(max)='', 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int = 0,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rIsPresent bit,
		 @rDays int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

CREATE TABLE #tmpData
(
AcademicId bigint,
Code nvarchar(20),
Name nvarchar(300),
MobileNo nvarchar(50),
SourceId bigint,
SourceTypeId int,
OrgId int,
OrgGroupId int,
ReceiverSourceId bigint,
ReceiverSourceTypeId int,
Class nvarchar(100),
Division nvarchar(100),
AbsentDates date,
AbsentReason nvarchar(100),
PresentDates date,
WhatsAppContactNo nvarchar(20),
ConsecDates date
)

INSERT INTO #tmpData
Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			SR.AttendanceDate AS AbsentDates,
			ISNULL(AR.Title,'') AS AbsentReason,
			SR.AttendanceDate AS PresentDates,
			SC.WhatsAppContactNo,
			 (
            select min(b.AttendanceDate) from sAttendance.tStudentRegister b where SR.AcademicId = b.AcademicId 
            and b.AttendanceDate >= SR.AttendanceDate
            and not exists ( 
                select 1 from sAttendance.tStudentRegister c where c.AcademicId = b.AcademicId and dateadd( dd, 1, b.AttendanceDate) = c.AttendanceDate  
            )
            ) ConsecDates

	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
			
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
   ORDER BY SR.AcademicId,SR.AttendanceDate asc

CREATE TABLE #tmp
(
AcademicId bigint ,
ConsecDates date ,
AbsentDays nvarchar(max),
FullAbsentDate nvarchar(max)
)
INSERT INTO #tmp
SELECT AcademicId,ConsecDates,
isnull(STUFF((SELECT ',' + CONVERT(nvarchar,DATEPART(day,d.AbsentDates)) from #tmpData d  
WHERE d.AcademicId=a.AcademicId AND d.ConsecDates = a.ConsecDates FOR XML PATH('')), 1, 1, ''),''),
isnull(STUFF((SELECT ', ' + CONVERT(nvarchar, d.AbsentDates,103) from #tmpData d  
WHERE d.AcademicId=a.AcademicId AND d.ConsecDates = a.ConsecDates FOR XML PATH('')), 1, 1, ''),'')
FROM #tmpData a

CREATE TABLE #Finaltmp
(
AcademicId bigint ,
ConsecDates date ,
AbsentDays nvarchar(max),
FullAbsentDate nvarchar(max)
)
INSERT INTO #Finaltmp
Select * from #tmp GROUP BY AcademicId,ConsecDates,AbsentDays,FullAbsentDate having COUNT(ConsecDates) >= @rDays
ORDER BY AcademicId,ConsecDates asc



ALTER TABLE #tmpData
DROP COLUMN AbsentDates,
 AbsentReason,
PresentDates;

Select Distinct
			tmp.AcademicId,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			tmp.Code,
			tmp.Name,
			tmp.MobileNo,	
			tmp.SourceId,
			tmp.SourceTypeId,
			tmp.OrgId,
			tmp.OrgGroupId,
			tmp.ReceiverSourceId,
			tmp.ReceiverSourceTypeId,
			tmp.Class,
			tmp.Division,
			tmp.WhatsAppContactNo,
			isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')AS AbsentDays,
			isnull(STUFF((SELECT ',' + f.FullAbsentDate from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')AS FullAbsentDate


	From 
		#tmpData tmp
	INNER JOIN #Finaltmp finaltmp ON tmp.AcademicId = finaltmp.AcademicId AND tmp.ConsecDates =finaltmp.ConsecDates
	
DROP TABLE #tmpData
DROP TABLE #tmp
DROP TABLE #Finaltmp

--SELECT

--			'' AS Builder1,
--			'' AS Builder2, 
--			CONVERT(BIGINT, 0) AS AcademicId,
--			'' As Code,
--			'' As Name,
--			'' AS MobileNo,	
--			--tmp.Subject,
--			CONVERT(BIGINT, 0) AS SourceId,
--			0 AS SourceTypeId,
--			0 AS OrgId,
--			0 AS OrgGroupId,
--			CONVERT(BIGINT, 0) AS ReceiverSourceId,
--			0 AS  ReceiverSourceTypeId,
--			'' AS Class ,
--			'' As Division,
--			'' AS WhatsAppContactNo,
--			'' AS AbsentDays,
--			'' AS FullAbsentDate
			

			
			

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pRptAbsentStudentContinueGetNew]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 --@rTemplate nvarchar(max) = '',
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int = 0,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rIsPresent bit,
	 	 --@rMailSubject nvarchar(500)='',
		 @rDays int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

CREATE TABLE #tmpData
(
AcademicId bigint,
Code nvarchar(20),
Name nvarchar(300),
MobileNo nvarchar(50),
--MsgText nvarchar(max),
--Subject nvarchar(max),
SourceId bigint,
SourceTypeId int,
OrgId int,
OrgGroupId int,
ReceiverSourceId bigint,
ReceiverSourceTypeId int,
Class nvarchar(100),
Division nvarchar(100),
AbsentDates date,
AbsentReason nvarchar(100),
PresentDates date,
WhatsAppContactNo nvarchar(20),
ConsecDates date
)

INSERT INTO #tmpData
Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			--'' AS MsgText,
			--@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			SR.AttendanceDate AS AbsentDates,
			ISNULL(AR.Title,'') AS AbsentReason,
			SR.AttendanceDate AS PresentDates,
			SC.WhatsAppContactNo,
			 (
            select min(b.AttendanceDate) from sAttendance.tStudentRegister b where SR.AcademicId = b.AcademicId 
            and b.AttendanceDate >= SR.AttendanceDate
            and not exists ( 
                select 1 from sAttendance.tStudentRegister c where c.AcademicId = b.AcademicId and dateadd( dd, 1, b.AttendanceDate) = c.AttendanceDate  
            )
            ) ConsecDates

	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
			
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
   ORDER BY SR.AcademicId,SR.AttendanceDate asc

CREATE TABLE #tmp
(
AcademicId bigint ,
ConsecDates date ,
AbsentDays nvarchar(max),
FullAbsentDate nvarchar(max)
)
INSERT INTO #tmp
SELECT AcademicId,ConsecDates,
isnull(STUFF((SELECT ',' + CONVERT(nvarchar,DATEPART(day,d.AbsentDates)) from #tmpData d  
WHERE d.AcademicId=a.AcademicId AND d.ConsecDates = a.ConsecDates FOR XML PATH('')), 1, 1, ''),''),
/**Added new field  for mantis : 29178**/
isnull(STUFF((SELECT ', ' + CONVERT(nvarchar, d.AbsentDates,103) from #tmpData d  
WHERE d.AcademicId=a.AcademicId AND d.ConsecDates = a.ConsecDates FOR XML PATH('')), 1, 1, ''),'')
FROM #tmpData a

CREATE TABLE #Finaltmp
(
AcademicId bigint ,
ConsecDates date ,
AbsentDays nvarchar(max),
FullAbsentDate nvarchar(max)
)
INSERT INTO #Finaltmp
Select * from #tmp GROUP BY AcademicId,ConsecDates,AbsentDays,FullAbsentDate having COUNT(ConsecDates) >= @rDays
ORDER BY AcademicId,ConsecDates asc



ALTER TABLE #tmpData
DROP COLUMN AbsentDates,
 AbsentReason,
PresentDates;

Select Distinct
			tmp.AcademicId,
			tmp.Code,
			tmp.Name,
			tmp.MobileNo,	
			--tmp.Subject,
			tmp.SourceId,
			tmp.SourceTypeId,
			tmp.OrgId,
			tmp.OrgGroupId,
			tmp.ReceiverSourceId,
			tmp.ReceiverSourceTypeId,
			tmp.Class +'-' + tmp.Division AS Class,
			tmp.Division,
			tmp.WhatsAppContactNo,
			isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')AS AbsentDays,
			isnull(STUFF((SELECT ',' + f.FullAbsentDate from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')AS FullAbsentDate --Added new field  for mantis : 29178


	From 
		#tmpData tmp
	INNER JOIN #Finaltmp finaltmp ON tmp.AcademicId = finaltmp.AcademicId AND tmp.ConsecDates =finaltmp.ConsecDates
	
DROP TABLE #tmpData
DROP TABLE #tmp
DROP TABLE #Finaltmp
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pRptAttendanceFollowupListGet]

		@rBuilder1 nvarchar(max),
	 	@rClassId int,
	 	@rDivisionId int,
	 	@rAttendanceTypeId tinyint,
		@rFromDate date,
		@rToDate date,
	 	@rBatchId int,
	 	@rOrgId int,
		@rPresentStatus int,
		@rCode nvarchar(20)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT
	@rBuilder1 AS Builder1,
	SA.AcademicId,
	SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
	SA.Code,
	SA.RollNo,
	SA.Name,
	SC.PresentContactNo,
	SC.PermanentContactNo,
	SC.EmergencyContactNo,
	SC.ParentContactNo,
	SC.StudentContactNo,
	AF.Remark,
	AF.AttendanceTypeId AS AttendanceTypeId,
	AF.FollowupDate,
	AF.IsPresent,
	(isnull(SC.PresentStreetOne,'')+' '+isnull(SC.PresentStreetTwo,'')+' '+isnull(SC.PresentStreetThree,'')+' '+isnull(SC.PresentCity,'')+' '+isnull(SC.PresentState,'')+' '+isnull(SC.PresentCountry,'')) as PresentAdress

	FROM
	sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sAttendance.tAttendanceFollowup AF ON SA.AcademicId = AF.AcademicId
	LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId

	WHERE
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
		  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  AND (SA.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND ((AF.IsPresent = @rPresentStatus) OR (@rPresentStatus= -1))
		  AND (AF.FollowupDate >= @rFromDate) AND (AF.FollowupDate <= @rToDate)
		  AND ((AF.AttendanceTypeId= @rAttendanceTypeId) OR (@rAttendanceTypeId = 0))
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sAttendance].[pRptAttendanceSubjectwiseGet]  
         
   @rBuilder1 nvarchar(max)='',  
   @rBuilder2 nvarchar(max)='',   
   @rOrgId smallint,  
   @rBatchId int,  
   @rClassId int,  
   @rDivisionId int,  
   @rSubjectId int,  
   @rFromDate date,  
   @rToDate date,  
   @rStudentCode nvarchar(20),  
   @rReportId int,  
   @rDepartmentId int,  
   @rStatusId int=0  
      
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
SET @rToDate = DATEADD (d,1,@rToDate)  
 Select   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  SA.AcademicId,  
  SA.Name,  
  SA.Code,  
  SA.RollNo,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SR.AttendanceDate,  
  --SA.TotalCount,  
  --SA.PresentCount,  
  --SA.AbsentDays,  
  --SA.AbsentCount,  
  ISNULL(SM.Id,0) AS SubjectId,  
  ISNULL(SM.Code,'') AS SubjectCode,  
  ISNULL(SM.Title,'') AS SubjectName,  
  ISNULL(SR.PeriodNo,'') As PeriodNo,
  --CAST(ISNULL(SR.IsPresent,'') as int) AS IsPresent
  
  case when SR.IsPresent = 1 then 1 when SR.IsPresent = 0 then 0 else '' end AS IsPresent,
  -- Commented for mantis : 38791
  --EMP.FirstName + ' ' + EMP.LastName  AS EmployeeNameSubjectwise--Added by dhananjay for mantis  - 37271
  ISNULL(U.DisplayTitle, '') AS EmployeeNameSubjectwise -- Added for mantis : 38791

 
   
 From   
 sAttendance.tStudentRegister SR    
 INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SR.AcademicId  
 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId 
 --Added by dhananjay for mantis start - 37271
 INNER JOIN sSecurity.tUser U ON U.Id = SR.CreatedUserId --AND SourceTypeId = 95
 --INNER JOIN sHrm.tEmployeeMaster EMP on EMP.Id = U.SourceId -- Commented for mantis : 38791
  --Added by dhananjay for mantis end - 37271

 WHERE  
  ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))  
  AND (SA.OrgId=@rOrgId)  
  AND (SA.BatchId = @rBatchId)   
  AND ((SA.ClassId=@rClassId) OR (@rClassId=0))  
  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
  ----AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))  
  AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
  AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))  
  --AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))  
  AND ((@rReportId = 20463 AND SR.IsPresent = 1) OR (@rReportId = 20466 AND SR.IsPresent = 0) 
  OR (@rReportId = 30718)
  OR (@rReportId = 30903)
  OR (@rReportId = 30924))  
  AND SR.AttendanceTypeId = 5  
  AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))  
  AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((SA.StatusID=@rStatusId) OR (@rStatusId=0))  
  --AND (SA.StatusId != 3)  
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pRptAttendanceSubjectwiseStatusGet]
	 	 	  
		 @rBuilder1 nvarchar(max)='',
	     @rBuilder2 nvarchar(max)='', 
		 @rOrgId smallint,
		 @rBatchId int,
		 @rClassId int,
		 @rDivisionId int,
		 @rSubjectId int,
		 @rFromDate date,
		 @rToDate date,
		 @rStudentCode nvarchar(20),
		 @rReportId int,
		 @rDepartmentId int,
		 @rSubject nvarchar(MAX)='',
		 @rStatusID int=0,
		 @rFromPercentage decimal(10,2)=0,
		 @rToPercentage decimal(10,2)=100
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rToDate = DATEADD (d,1,@rToDate)
 
SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.RollNo,		
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		R.SubjectId,
		R.Code AS SubjectCode,
		R.Title AS SubjectName,
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalPresentCount,
		
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND (SR.IsPresent = 0)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalAbsentCount,
		
		@rFromPercentage as FromPercentage,
		@rToPercentage as ToPercentage

		FROM sStudent.vStudentAcademic SA INNER JOIN
	(
	SELECT DISTINCT SR.SubjectId,SM.Code,SM.Title,SA.AcademicId FROM
		sAttendance.tStudentRegister SR INNER JOIN 
		sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId 
	WHERE
		((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND (SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		----AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		--AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		AND (ISNULL(SR.SubjectId,0) IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnSplit(@rSubject,',')) OR (@rSubject=''))
		)
			 R
		ON SA.AcademicId = R.AcademicId
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.StatusId  =@rStatusID) OR (@rStatusID=0))
	 
		




	--Select 
	--	@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2,
	--	SA.AcademicId,
	--	SA.Name,
	--	SA.Code,
	--	SA.RollNo,
		
	--	--SA.TotalCount,
	--	--SA.PresentCount,
	--	--SA.AbsentDays,
	--	--SA.AbsentCount,
	--	ISNULL(SM.Id,0) AS SubjectId,
	--	ISNULL(SM.Code,'') AS SubjectCode,
	--	ISNULL(SM.Title,'') AS SubjectName	
	--From 
	--sStudent.vStudentAcademic SA INNER JOIN 
	--(SELECT DISTINCT SR.SubjectId,SR.AcademicId FROM
	--sAttendance.tStudentRegister SR ) R ON R.AcademicId = SA.AcademicId
	
	-- ON SA.AcademicId=SR.AcademicId
	--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId
	--WHERE
	--	((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
	--	AND (SA.OrgId=@rOrgId)
	--	AND	(SA.BatchId = @rBatchId) 
	--	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	--	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	--	----AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
	--	AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--	AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--	AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	--	AND (SR.IsPresent = 1)
	--	AND SR.AttendanceTypeId = 5
	--	--AND (SA.StatusId != 3)
	
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pRptDailyAttendanceList]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		 @rBatchId int,
		@rClassId int,
		@rDivisionId int,
		@rDepartmentId int ,
		--@rOrgMainGroupId int,
		--@rOrgSubGroupId int,
		 @rOrgId smallint,
		 @rAttendanceTypeId int,
		 @rDate date,
		 
		 @rDivisionGroup bit=0
		--@rOrgGroupBatchId int,
		--@rFromDate Date,
		--@rToDate Date 
		--@rStrOrgMainGroupId nvarchar(max),
		--@rStrOrgSubGroupId nvarchar(max),
		--@rStrOrgId nvarchar(max),
		--@rStrDepartmentId nvarchar(max),
		--@rStrClassId nvarchar(max),
		--@rIsTestMainGroup bit =0,
		--@rIsTestSubGroup bit =0,
		--@rIsTestOrg bit=0,
		--@rIsTestClass bit=0,
		--@rIsTestDepartment bit=0,
		--@rOrgGroupId int,
		--@rIsDisplayOrgGroup bit=0
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			 
			@rDivisionGroup AS DivisionGroup,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex  ,
			DM.Id AS DivisionId,
			DM.Title AS DivisionName,
			DM.OrderIndex AS DivisionOrderIndex,
			
		 --   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			--ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			--WHERE BM.IsActive = 1 AND  SA.AdmissionDate= Convert(DATE,GETDATE()-1)
			--AND A.ClassId =CM.Id AND A.DivisionId = DM.Id  ) AS OpeningStrength,
			
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SA.AdmissionDate = @rDate 
			AND A.ClassId =CM.Id AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId  ) AS NewJoinedStudent,
			
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			 ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			 WHERE BM.IsActive = 1 AND SA.LeftDate = @rDate 
			 AND A.ClassId =CM.Id AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId ) AS LeftStudent,
			 
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId 
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SM.StatusId = 1
			AND A.ClassId =CM.Id AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId ) AS ClosingStrength,
			
			
			(SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			WHERE 
			 SA.AdmissionDate < @rDate
			 AND  ((SA.LeftDate >= @rDate) OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id  
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId ) AS PreviousDay,
			
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =1 AND A.OrgId = @rOrgId ) AS Present,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =1 AND A.OrgId = @rOrgId AND SO.GenderId=1 ) AS PresentBoys,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =1 AND A.OrgId = @rOrgId AND SO.GenderId=2 ) AS PresentGirls,
						
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =1 AND A.OrgId = @rOrgId ) AS TotalPresent,
		
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =0 AND A.OrgId = @rOrgId ) AS AbsentStudent,
			
			 (select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=1 ) AS AbsentBoys,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=2) AS AbsentGirls,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =0 AND A.OrgId = @rOrgId ) AS TotalAbsent,
			
			--Added
			 (select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND A.OrgId = @rOrgId AND SO.GenderId=1 ) AS TotalBoys,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND A.OrgId = @rOrgId AND SO.GenderId=2) AS TotalGirls,
			
			--end						
			
			0 as WithLeave,
			0 as SeekLeave,
			 0 AS TotalStudent,
			 '' AS Remark 
	FROM 
			sSetup.tDivisionMaster DM  
			 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			 INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
			--AND DM.Id=A.DivisionId AND CM.Id=A.ClassId
			--sSetup.tClassMaster CM			
			 
			--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
		 
	WHERE 
		  DM.OrgId=@rOrgId
	
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		AND DM.IsObsolete = 0
		AND CM.IsObsolete = 0
		AND Dept.IsObsolete = 0
		
		  -- ((CM.Id=@rClassId) OR (@rClassId=0))
			 --AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		 
			 
			ORDER BY CM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sAttendance].[pRptDailyStatusGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint = 0,
	 @rBatchId int = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0,
	 @rAttendanceTypeId tinyint = 1,	 
	 @rFromDate date = '',
	 @rToDate date = '',	 
	 @rDepartmentId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	-- *Start - for Report data set refresh do not delete
	--SELECT
	--'' AS AttendanceDate,
	--'' AS Builder1,
	--'' AS Builder2,
	--	'' AS ClassDivisionName,
	--	'' AS ClassTeacherName,
	--	'' AS WeekOffStatus,
	--	'' AS PresentStatus,
	--	0 AS TotalCount,
	--	0 AS PresentCount,
	--	0 AS AbsentCount,
	--	'' AS UpdatedDateTime
	--End  *
	
	DECLARE @lSearchDate date = ''
	DECLARE @lYear smallint = ''
	DECLARE @lMonth smallint = ''
	DECLARE @lDate smallint = ''

	CREATE TABLE #TempDates (AttendanceDate date, DivisionId int)
	WHILE @rFromDate <= @rToDate
	BEGIN 
		INSERT INTO #TempDates VALUES (@rFromDate, @rDivisionId)
		SET @rFromDate = DATEADD(DD, 1, @rFromDate)
	END

	SET @lYear = YEAR(@rFromDate)
	SET @lMonth = MONTH(@rFromDate)
	SET @lDate = DAY(@rFromDate)
	SET @lSearchDate = @rFromDate

	SELECT
			T.AttendanceDate, 			
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,	
			vCD.ClassDivisionName,
			ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
			[sAttendance].[fWeekHOffGet](YEAR(T.AttendanceDate),MONTH(T.AttendanceDate),DAY(T.AttendanceDate),@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId) AS WeekOffStatus, 
			CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,T.AttendanceDate,@rAttendanceTypeId,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus, 
            sCommon.fCountDivisionStudent(A.DivisionId,@rBatchId) AS TotalCount, 
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,T.AttendanceDate,@rAttendanceTypeId,1) AS PresentCount,
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,T.AttendanceDate,@rAttendanceTypeId,0) AS AbsentCount,
			ISNULL(MAX(SR.UpdatedDateTime),MAX(SR.CreatedDateTime)) as UpdatedDateTime
    FROM 
			#TempDates T
			INNER JOIN sStudent.tAcademic A ON A.DivisionId = T.DivisionId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			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.AttendanceDate=T.AttendanceDate 
            AND SR.AttendanceTypeId = @rAttendanceTypeId 
			AND SR.IsPresent=1 
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND (vCD.ClassId = @rClassId)
			AND (vCD.DivisionId = @rDivisionId)
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId,T.AttendanceDate
            ORDER BY vCD.OrderIndex		
			
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pRptDivisionWiseOverallLEctureList]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		 @rBatchId int,
		@rDivisionId int ,
		@rSubjectID int,
		@rOrgId int,
		@rStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		 
			 
			AB.SubjectId,
			 
			--Count(A.Id),
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			AB.NoOfLecture AS NoOfLecture ,
			TM.TItle+'-'+VM.Title As DivisionTitle,
			AB.DivisionId,
			SM.Code As SubjectTitle,
			Isnull((
				Select Distinct
					--Count( A.Id) ,
					isnull(count(ST.SubjectId),0)
				From sAttendance.tStudentRegister ST
				--INNER JOIN sStudent.tAcademic A On A.Id=ST.AcademiciD   
				Where A.BatchID=@rBatchId    AND A.DivisionId=@rDivisionId  AND A.Id=ST.AcademiciD   
				AND AB.SubjectId=ST.SubjectId 				
				group by ST.SubjectId
				 
			),0) AS TotalLEcture,
			ST.FirstName+' ' +MiddleName AS Name,
			ST.Code
			
	FROM 
			 sTimetable.tAnnualSubjectWorkLoad AB
			 INNER JOIN sSetup.tDivisionMaster VM ON VM.Id=AB.DivisionId
			 INNER JOIN sSetup.tClassMaster TM on TM.Id=Vm.CLassID
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=AB.SubjectID
			 INNER JOIN sStudent.tAcademic A On A.DivisionId=VM.Id AND A.BatchID=@rBatchId
			 INNER JOIN sStudent.tStudentMaster ST On ST.Id=A.StudentId
			--INNER JOIN  sAttendance.tStudentRegister SG  On SG.Academicid=A.Id
			--AND DM.Id=A.DivisionId AND CM.Id=A.ClassId
			--sSetup.tClassMaster CM			
			 
			--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
		 
	WHERE 
		 ((AB.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 AND ((AB.SubjectID=@rSubjectID) OR (@rSubjectID=0))
		 AND ST.OrgId=@rOrgId 
		 --AND AB.BatchID=@rBatchId ANd AB.DivisionId=@rDivisionId
	 AND AB.BatchID=@rBatchId  
	 AND ((ST.StatusID =@rStatusId) OR (@rStatusId=0))
END

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

BEGIN 
	declare @Count decimal(10,2)
	
	 
	
	 
	SELECT 
 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 
			 MS.ForYear,
				(select sum(ISNULL(MR.PresentCount,0)) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id --and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    --AND Month(SR.AttendanceDate) = MS.ForMonth
		    --AND YEar(Sr.AttendanceDate) = MS.ForYear
		    AND MR.ForMonth = MS.ForMonth
		    AND MR.ForYear = MS.ForYear		    
			AND MR.AttendanceTypeId =1 
			--AND SR.IsPresent =1 
			AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))) AS PresentBoys ,
			 
			 
		(select sum(ISNULL(MR.AttendanceCount,0)) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id --and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    --AND Month(SR.AttendanceDate) = MS.ForMonth
		    --AND YEar(Sr.AttendanceDate) = MS.ForYear
		    AND MR.ForMonth = MS.ForMonth
		    AND MR.ForYear = MS.ForYear
			AND MR.AttendanceTypeId =1 
			--AND SR.IsPresent =0 
			AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))) AS Absentboys,
			
			(select sum(ISNULL(MR.PresentCount,0)) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id --and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    --AND Month(SR.AttendanceDate) = MS.ForMonth
		    --AND YEar(Sr.AttendanceDate) = MS.ForYear
		    AND MR.ForMonth = MS.ForMonth
		    AND MR.ForYear = MS.ForYear
			AND MR.AttendanceTypeId =1 
			--AND SR.IsPresent =1 
			AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDIvisionID) OR (@rDivisionId=0))) AS PresentGirls,
			
			
			(select sum(ISNULL(MR.AbsentCount,0)) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id --and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
	        
		 --   AND Month(SR.AttendanceDate) = MS.ForMonth
		 --   AND YEar(Sr.AttendanceDate) = MS.ForYear
			--AND SR.AttendanceTypeId =1 
			--AND SR.IsPresent =0 AND 
			
			AND MR.ForMonth = MS.ForMonth
		    AND MR.ForYear = MS.ForYear
			AND MR.AttendanceTypeId =1 
			--AND SR.IsPresent =1 
			AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0))) AS AbsentGirls	,
			
			MS.WorkingDays,
			DateName(mm,Dateadd(mm,MS.ForMonth,-1)) AS Month_Title,ForMonth,
			 
		 
			(
			
			
			MS.workingdays
			--select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			--INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			--INNER JOIN sStudent.tStudentOther SO
			--ON SO.StudentId=A.StudentId
	  --      WHERE A.BatchId = @rBatchId   
	  --      AND A.ClassId =@rClassId 
		 --   AND Month(SR.AttendanceDate) = MS.ForMonth
		 --   AND YEar(Sr.AttendanceDate) = MS.ForYear
			--AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=1
			--AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			)as TotalAttendanceCount,
			
			CASE   
			(
			MS.WorkingDays
			--select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			--INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			--INNER JOIN sStudent.tStudentOther SO
			--ON SO.StudentId=A.StudentId
	  --      WHERE A.BatchId = @rBatchId   
	  --      AND A.ClassId =@rClassId 
		 --   AND Month(SR.AttendanceDate) = MS.ForMonth
		 --   AND YEar(Sr.AttendanceDate) = MS.ForYear
			--AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=1
			--AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			) WHen 0
			Then 
				 NULL
			 ELSE 
			   round(Cast(round((select sum(ISNULL(MR.PresentCount,0)) FROM sStudent.tAcademic A
				--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
				INNER JOIN sStudent.tStudentOther SO
				ON SO.StudentId=A.StudentId
				WHERE A.BatchId = @rBatchId   
				AND A.ClassId =@rClassId
				--AND Month(SR.AttendanceDate) = MS.ForMonth
				--AND YEar(Sr.AttendanceDate) = MS.ForYear
				AND MR.AttendanceTypeId =1 
				--AND SR.IsPresent =1 
				AND A.OrgId = @rOrgId AND SO.GenderId=1
				AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))),2) as numeric(38,2))    /
				(
				MS.WorkingDays
			--	select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			--INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			--INNER JOIN sStudent.tStudentOther SO
			--ON SO.StudentId=A.StudentId
	  --      WHERE A.BatchId = @rBatchId   
	  --      AND A.ClassId =@rClassId 
		 --   AND Month(SR.AttendanceDate) = MS.ForMonth
		 --   AND YEar(Sr.AttendanceDate) = MS.ForYear
			--AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=1
			--AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			) ,2)
			END AS TotalPresentBoys,
			
			CASE
			 (
			 MS.WorkingDays
			-- select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			--INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			--INNER JOIN sStudent.tStudentOther SO
			--ON SO.StudentId=A.StudentId
	  --      WHERE A.BatchId = @rBatchId   
	  --      AND A.ClassId =@rClassId 
		 --   AND Month(SR.AttendanceDate) = MS.ForMonth
		 --   AND YEar(Sr.AttendanceDate) = MS.ForYear
			--AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=1
			--AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0))
			)
			 WHen 0
			Then 
				 NULL
			 ELSE 
				 round(Cast(round((select sum(ISNULL(MR.AbsentCount,0)) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    --AND Month(SR.AttendanceDate) = MS.ForMonth
		    --AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND MR.AttendanceTypeId =1 
			--AND SR.IsPresent =0 
			AND A.OrgId = @rOrgId AND SO.GenderId=1
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))),2) as numeric(38,2)) /
			(
			MS.WorkingDays
			--select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			--INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			--INNER JOIN sStudent.tStudentOther SO
			--ON SO.StudentId=A.StudentId
	  --      WHERE A.BatchId = @rBatchId   
	  --      AND A.ClassId =@rClassId 
		 --   AND Month(SR.AttendanceDate) = MS.ForMonth
		 --   AND YEar(Sr.AttendanceDate) = MS.ForYear
			--AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=1
			--AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			) ,2)
			END AS TotalAbsentboys ,
			
			CASE
			 (
			 MS.WorkingDays
			-- select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			--INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			--INNER JOIN sStudent.tStudentOther SO
			--ON SO.StudentId=A.StudentId
	  --      WHERE A.BatchId = @rBatchId   
	  --      AND A.ClassId =@rClassId 
		 --   AND Month(SR.AttendanceDate) = MS.ForMonth
		 --   AND YEar(Sr.AttendanceDate) = MS.ForYear
			--AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=2
			--AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0))
			)
			 WHen 0
			Then 
				 NULL
			 ELSE 
			  round(Cast(round((select sum(ISNULL(MR.PresentCount,0)) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId
		    --AND Month(SR.AttendanceDate) = MS.ForMonth
		    --AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND MR.AttendanceTypeId =1 
			--AND SR.IsPresent =1 
			AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDIvisionID) OR (@rDivisionId=0))),2) as numeric(38,2)) /
			(
			MS.WorkingDays
			--select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			--INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			--INNER JOIN sStudent.tStudentOther SO
			--ON SO.StudentId=A.StudentId
	  --      WHERE A.BatchId = @rBatchId   
	  --      AND A.ClassId =@rClassId 
		 --   AND Month(SR.AttendanceDate) = MS.ForMonth
		 --   AND YEar(Sr.AttendanceDate) = MS.ForYear
			--AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=2
			--AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			),2)
			END AS TotalPresentgirls,
			
			CASE
				(
				MS.WorkingDays
			--	select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			--INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			--INNER JOIN sStudent.tStudentOther SO
			--ON SO.StudentId=A.StudentId
	  --      WHERE A.BatchId = @rBatchId   
	  --      AND A.ClassId =@rClassId 
		 --   AND Month(SR.AttendanceDate) = MS.ForMonth
		 --   AND YEar(Sr.AttendanceDate) = MS.ForYear
			--AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=2
			--AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0))
			)
			 WHen 0
			Then 
				 NULL
			 ELSE 
				round(Cast(round((select sum(ISNULL(MR.AbsentCount,0)) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId   
	        AND A.ClassId =@rClassId 
		    --AND Month(SR.AttendanceDate) = MS.ForMonth
		    --AND YEar(Sr.AttendanceDate) = MS.ForYear
			AND MR.AttendanceTypeId =1 
			--AND SR.IsPresent =0 
			AND A.OrgId = @rOrgId AND SO.GenderId=2
			AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0))),2) as numeric(38,2)) /   
			 (
			 MS.WorkingDays
			-- select COUNT(distinct  AttendanceDate) FROM sStudent.tAcademic A
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			--INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id and MR.ForMonth =MS.ForMonth AND MR.ForYear =MS.ForYear
			--INNER JOIN sStudent.tStudentOther SO
			--ON SO.StudentId=A.StudentId
	  --      WHERE A.BatchId = @rBatchId   
	  --      AND A.ClassId =@rClassId 
		 --   AND Month(SR.AttendanceDate) = MS.ForMonth
		 --   AND YEar(Sr.AttendanceDate) = MS.ForYear
			--AND SR.AttendanceTypeId =1  AND A.OrgId = @rOrgId AND SO.GenderId=2
			--AND ((A.DivisionId=@rDivisionID) OR (@rDivisionId=0)) 
			),2)
			END AS TotalAbsentgirls
			
	FROM 
	  sAttendance.tMonthlySetup MS  
	  INNER JOIN sSetup.tClassMaster CM On Cm.Id=MS.ClassId 
	  INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
		WHERE 
			(MS.BatchId=@rBatchId)
			AND (MS.ClassId=@rClassId)
			AND ((Dm.Id=@rDivisionId) OR (@rDivisionId=0))
	Order by MS.ForYear,MS.ForMonth	
		--AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		--AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		--AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		 
		--AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))	AND ((SV.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND ((MR.AveragePresence >= @rFromAverage) OR (@rFromAverage=0))
		--AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage=0))
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pRptMonthlyAttendanceStudentwise]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rDepartmentId int,
	@rClassId int,
	@rDivisionId int,
	@rAttendanceTagId int,
	--@rFromDate date,
	@rUpToDate date,
	@rBatchId int,
	@rOrgId int	 ,
	@rAdmissionCategoryId int,
	@rAttendanceTypeId int = 0,
	@rStatus int = 0	--mantis: 44417
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--mantis: 44417, start
	DECLARE @lOrgGroupId int=0, @lIDNoLabel nvarchar(500)='Id No'
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id=@rOrgId
	SELECT @lIDNoLabel=ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId=236 AND SourceTypeId=2010 AND SourceId=@lOrgGroupId
	--mantis: 44417, end

	DECLARE @lAttendanceDate nvarchar(MAX)
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		
		SA.AcademicId,
		ISNULL(SA.RollNo,0) as RollNo,
		SA.Name,
		SA.Code,
		CM.ID AS ClassId,
		CM.Title AS Class,
		CM.OrderIndex AS ClassOrderIndex,
		DM.Id AS DivisionId,
		DM.Title AS Division,
		DM.OrderIndex AS DivisionOrderIndex,

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

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

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

		STUFF(
         (SELECT DISTINCT  ', ' + CONVERT(NVARCHAR(MAX),SR.AttendanceDate,105)
           FROM
				sStudent.vStudentAcademic A INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId  
			WHERE 
				 A.AcademicId = SA.AcademicId
				--AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND (SR.AttendanceDate <= @rUpToDate)
				--AND SR.AttendanceTagId>0
				AND (SR.AttendanceTypeId =  @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				AND ((SR.AttendanceTagId =@rAttendanceTagId) OR (@rAttendanceTagId=0))
				AND ((SA.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			GROUP BY SR.AcademicId,AttendanceDate
          FOR XML PATH (''))
          , 1, 1, '')  AS UptoDate,

		  SA.Suid AS SUID,	--mantis: 44417
		  @lIDNoLabel AS IDLabel --mantis: 44417
		 
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		INNER JOIN sSetup.tDepartmentMaster DEM on DEM.Id = CM.DepartmentId
		
		--Inner JOIN sAttendance.tMonthlySetup MS on MS.ClassId = SA.ClassId And MS.BatchId = SA.BatchId
		--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		       
		LEFT JOIN
		(
			SELECT 
				SR.AcademicId,COUNT(SR.AttendanceTagId) AS AttendanceTagCount 
			FROM 
				sStudent.vStudentAcademic A
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId 
				INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			WHERE 
				((A.ClassId=@rClassId) OR (@rClassId=0))
				AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND (A.OrgId = @rOrgId)
				AND (A.BatchId = @rBatchID)
				--AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND (SR.AttendanceDate <= @rUpToDate)
				AND A.StatusId=1
				--AND SR.AttendanceTagId>0
				AND ((SR.AttendanceTagId =@rAttendanceTagId) OR (@rAttendanceTagId=0))
				AND ((A.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			GROUP BY SR.AcademicId
		) AR ON AR.AcademicId = SA.AcademicId
		
	WHERE 
		(SA.OrgId = @rOrgId)
		AND (SA.BatchId = @rBatchId)
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.AdmissionCategoryId =@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
		--AND (AD.AdmissionDate <= @rFromDate)
		AND ((SA.StatusId = @rStatus) OR (@rStatus = 0))	--mantis: 44417
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pRptMonthlyStrengthAttendanceSummary]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 --@rFromDate date='',
	 --@rToDate date='', 
	 @rDepartmentId int,
	 
	 @rOrgGroupBatchId int,
	 
	 @rAttendanceTypeId smallint=0,
	 @rYear int=0,
	 @rMonth int=0,
	 @rDivisionGroup bit=0
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	 DECLARE @lFirstDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+ '/'+CONVERT(NVARCHAR(2),@rMonth)+'/01'))
	 
	  
	SELECT 
			@rDivisionGroup  AS DivisionGroup,
			  Dept.Id AS DepartmentId,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 
			(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
			Year(SA.AdmissionDate) = @rYear 
			AND Month(SA.AdmissionDate) = @rMonth 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=2 
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId 
			)AS NewGirls,
			
		 
			
						(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId			 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
				Year(SA.AdmissionDate) = @rYear 
			AND Month(SA.AdmissionDate) = @rMonth 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=1 
			AND CM.DepartmentId=Dept.Id	AND A.BatchId = @rBatchId 
			) AS NewBoys,
			 
	
				(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
				Year(SA.LeftDate) = @rYear 
			AND Month(SA.LeftDate) = @rMonth 
			 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=2 
			AND CM.DepartmentId=Dept.Id AND A.BatchId = @rBatchId 
			) AS LeftGirls,
			
			 
	
				(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND 
			Year(SA.LeftDate) = @rYear 
			AND Month(SA.LeftDate) = @rMonth 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=1 
			AND CM.DepartmentId=Dept.Id AND A.BatchId = @rBatchId 
			) AS LeftBoys,		
		  
			
		 (
			select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 2 AND CM.DepartmentId = Dept.Id 
			) AS TotalGirls,
 
			(
				select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id AND SO.GenderId = 1 AND CM.DepartmentId = Dept.Id  
			) AS TotalBoys,	
			
			
			Dept.Title AS DepartmentName,
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			DM.Id AS DivId,
			DM.Title AS DivisionName, 
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			 
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id   AND CM.DepartmentId = Dept.Id AND SR.AttendanceTypeId =1 AND SR.IsPresent =1) AS TotalPresent,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			 
	        WHERE A.BatchId = @rBatchId  
	        AND ((YEAR(SR.AttendanceDate)=@rYear) OR (@rYear= 0))
	        AND ((MONTH(SR.AttendanceDate)=@rMonth) OR (@rMonth= 0))
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id   AND CM.DepartmentId = Dept.Id AND SR.AttendanceTypeId =1 AND SR.ISPresent =0) AS TotalAbsent,
			
			(SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 

			WHERE 
				
			 (( SA.AdmissionDate < @lFirstDate) OR (ISNULL(SA.AdmissionDate,'')= ''))
			 AND  (( SA.LeftDate >= @lFirstDate) OR (ISNULL(SA.LEFTdate,'')= ''))
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id  
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId AND A.DivisionId = DM.Id  AND GM.Id=1 ) AS PreviousBoys,
			
			(SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			WHERE 
				 ((SA.AdmissionDate< @lFirstDate) OR (ISNULL(SA.AdmissionDate,'')= ''))
			AND  (( SA.LeftDate >= @lFirstDate) OR (ISNULL(SA.LEFTdate,'')= ''))
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id  
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId AND A.DivisionId = DM.Id  AND GM.Id=2 ) AS PreviousGirls,
			
			(select WorkingDays FROM sAttendance.tMonthlySetup
			 
	        WHERE  BatchId = @rBatchId  
	        AND ((ForMonth=@rMonth) OR (@rMonth= 0))
	        AND (( ForYEAR=@rYear) OR (@rYear= 0))
	        AND ClassId =CM.Id )as WorkingDays 
			 
			FROM 
			
			 
			sSetup.tDivisionMaster DM  
		 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id
			
			
			 
			
	WHERE 
		 DM.OrgId=@rOrgId
		 
		
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		AND	BM.OrgGroupBatchId = @rOrgGroupBatchId 
		
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAttendance].[pRptStudentAttendanceLateCountList]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rDepartmentId int,
	@rClassId int,
	@rDivisionId int,
	@rAttendanceTagId int,
	@rFromDate date,
	@rToDate date,
	@rBatchId int,
	@rOrgId int	 
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lAttendanceDate nvarchar(MAX)
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		
		SA.AcademicId,
		ISNULL(SA.RollNo,0) as RollNo,
		SA.Name,
		SA.Code,
		CM.ID AS ClassId,
		CM.Title AS Class,
		CM.OrderIndex AS ClassOrderIndex,
		DM.Id AS DivisionId,
		DM.Title AS Division,
		SA.DepartmentName As Department,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.ClassName + '-'+ SA.DivisionName AS ClassDivision,
		ISNULL(AR.AttendanceTagCount,0) AS AttendanceTagCount,
		STUFF(
         (SELECT DISTINCT  ', ' + CONVERT(NVARCHAR(MAX),SR.AttendanceDate,105)
           FROM
				sStudent.vStudentAcademic A INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId  
			WHERE 
				 A.AcademicId = SA.AcademicId
				AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND SR.AttendanceTagId>0
				AND (SR.AttendanceTagId = @rAttendanceTagId OR @rAttendanceTagId=0)
			GROUP BY SR.AcademicId,AttendanceDate
          FOR XML PATH (''))
          , 1, 1, '')  AS DATE
		 
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		 
		LEFT JOIN
		(
			SELECT 
				SR.AcademicId,COUNT(SR.AttendanceTagId) AS AttendanceTagCount 
			FROM 
				sStudent.vStudentAcademic A
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId 
				INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			WHERE 
				((A.ClassId=@rClassId) OR (@rClassId=0))
				AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND (A.OrgId = @rOrgId)
				AND (A.BatchId = @rBatchID)
				AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND A.StatusId=1
				AND SR.AttendanceTagId>0
				AND (SR.AttendanceTagId = @rAttendanceTagId OR @rAttendanceTagId=0)
			GROUP BY SR.AcademicId
		) AR ON AR.AcademicId = SA.AcademicId
		
	WHERE 
		(SA.OrgId = @rOrgId)
		AND (SA.BatchId = @rBatchId)
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
		AND (AD.AdmissionDate <= @rFromDate)
		AND SA.StatusId=1
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

  
CREATE OR ALTER PROCEDURE [sAttendance].[pRptStudentAttendancewithStudentGroup]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rBatchId int,
		@rClassId int,
		@rDivisionId int,
		@rDepartmentId int,		
		@rOrgId smallint,
		@rAttendanceTypeId int,
		@rDate date,		 
		@rDivisionGroup bit=0
		,@rStudentGroupId int=0
		
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			 
			@rDivisionGroup AS DivisionGroup,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex  ,
			DM.Id AS DivisionId,
			DM.Title AS DivisionName,
			DM.OrderIndex AS DivisionOrderIndex
			,SO.GenderId 
			,ISNULL(SR.AttendanceTypeId,0) AS AttendanceTypeId
			,ISNULL(SR.IsPresent,0) AS IsPresent
			,ISNULL(SR.Academicid,0) AS Academicid	
			,ISNULL(SR.AttendanceDate,'') AS AttendanceDate
			,ATM.Title AS AttendanceType
			,ISNULL(SGM.Title,'Group Not Selected') AS StudentGroup
			,ISNULL(SGM.Id,0) AS StudentGroupId
			,ISNULL(SGM.Code,'') AS StudentGroupCode
		
	FROM 
			 sStudent.tAcademic A
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId				 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM  ON CM.Id = DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			 INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
			 INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
			 LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SM.StudentGroupId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id AND  SR.AttendanceDate=@rDate AND SR.AttendanceTypeId =@rAttendanceTypeId 
			LEFT JOIN sAttendance.tAttendanceTypeMaster ATM ON ATM.Id = SR.AttendanceTypeId
			
		 
	WHERE 
		  DM.OrgId=@rOrgId
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		AND DM.IsObsolete = 0
		AND CM.IsObsolete = 0
		AND Dept.IsObsolete = 0
		AND A.BatchId = @rBatchId  
	    
	    AND A.ClassId =CM.Id 
		AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
		
		--AND SR.IsPresent =1 
		AND A.OrgId = @rOrgId
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((SGM.Id=@rStudentGroupId) OR (@rStudentGroupId=0))
			 
			ORDER BY CM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pRptStudentMonthlyRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint=0,
	 @rSubjectId int=0,
	 @rForYear smallint,
	 @rForMonth tinyint,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int,
	 @rFromAverage decimal=0,
	 @rToAverage decimal=0,
	 @rIsDetail bit=0,
	 @rReportId int = 0,
	 @rStatus smallint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--Added ((@rReportId <> 31414))by dhananjay for mantis : 39584
	IF((@rReportId <> 10132) AND (@rReportId <> 10131) AND (@rReportId <> 31414))     --Mantis 30087
	BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			MR.ForMonth,
			MR.ForYear,
			M.Code +' - '+Convert(nvarchar(4),MR.ForYear) AS ForMonthYear,
			MR.TotalCount,
			ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
			MR.PresentCount,
			MR.AbsentCount,
			MR.AveragePresence,
			MR.AbsentDays,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SM.Title AS SubjectName,
			SA.DivisionOrder
			
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=MR.SubjectId
		INNER JOIN sCommon.tMonthMaster M ON MR.ForMonth = M.Id
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		AND (SA.StatusId != 3)
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((MR.AveragePresence >= @rFromAverage) OR (@rFromAverage=0))
		AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage=0))
	END
	ELSE 
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			MR.ForMonth,
			MR.ForYear,
			M.Code +' - '+Convert(nvarchar(4),MR.ForYear) AS ForMonthYear,
			MR.TotalCount,
			ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
			MR.PresentCount,
			MR.AbsentCount,
			MR.AveragePresence,
			MR.AbsentDays,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SM.Title AS SubjectName,
			SA.DivisionOrder
			
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=MR.SubjectId
		INNER JOIN sCommon.tMonthMaster M ON MR.ForMonth = M.Id
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		AND ((SA.StatusId = @rStatus) OR (@rStatus = 0))
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((MR.AveragePresence >= @rFromAverage) OR (@rFromAverage=0))
		AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage=0))
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAttendance].[pRptStudentRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rStatus int=0,
	 @rDepartmentId int = 0,
	 @rIsHolidayWeekoff bit= 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
IF(@rIsHolidayWeekoff = 1)
BEGIN
Declare @Days int 
select @Days=sCommon.fGetDaysInMonth(Month(GetDate()),Year(GetDate()))
--Select @Days
	
DECLARE @li int 
SET @li=1

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

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](YEAR(GetDate()),MONTH(GetDate()),@li,@rBatchId,@rClassId,@rDivisionId,'',@rOrgId)
SET @li = @li + 1
END
--Select * from #TempDaysTempTable
CREATE TABLE #TempDaysTempTable1
(
 [1] nvarchar(10),
 [2] nvarchar(10),
 [3] nvarchar(10),
 [4] nvarchar(10),
 [5] nvarchar(10),
 [6] nvarchar(10),
 [7] nvarchar(10),
 [8] nvarchar(10),
 [9] nvarchar(10),
 [10] nvarchar(10),
 [11] nvarchar(10),
 [12] nvarchar(10),
 [13] nvarchar(10),
 [14] nvarchar(10),
 [15] nvarchar(10),
 [16] nvarchar(10),
 [17] nvarchar(10),
 [18] nvarchar(10),
 [19] nvarchar(10),
 [20] nvarchar(10),
 [21] nvarchar(10),
 [22] nvarchar(10),
 [23] nvarchar(10),
 [24] nvarchar(10),
 [25] nvarchar(10),
 [26] nvarchar(10),
 [27] nvarchar(10),
 [28] nvarchar(10),
 [29] nvarchar(10),
 [30] nvarchar(10),
 [31] nvarchar(10)
  
 )
INSERT INTO #TempDaysTempTable1
select [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31]
from
(
  select DayPart, Value
  from #TempDaysTempTable
) d
pivot
(
  max(value)
  for DayPart in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) piv;
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SA.DivisionOrder,
			@rIsHolidayWeekoff AS IsHolidayWeekoff,
			(Select [1] from #TempDaysTempTable1)AS D1,
			(Select [2] from #TempDaysTempTable1)AS D2,
			(Select [3] from #TempDaysTempTable1)AS D3,
			(Select [4] from #TempDaysTempTable1)AS D4,
			(Select [5] from #TempDaysTempTable1)AS D5,
			(Select [6] from #TempDaysTempTable1)AS D6,
			(Select [7] from #TempDaysTempTable1)AS D7,
			(Select [8] from #TempDaysTempTable1)AS D8,
			(Select [9] from #TempDaysTempTable1)AS D9,
			(Select [10] from #TempDaysTempTable1)AS D10,
			(Select [11] from #TempDaysTempTable1)AS D11,
			(Select [12] from #TempDaysTempTable1)AS D12,
			(Select [13] from #TempDaysTempTable1)AS D13,
			(Select [14] from #TempDaysTempTable1)AS D14,
			(Select [15] from #TempDaysTempTable1)AS D15,
			(Select [16] from #TempDaysTempTable1)AS D16,
			(Select [17] from #TempDaysTempTable1)AS D17,
			(Select [18] from #TempDaysTempTable1)AS D18,
			(Select [19] from #TempDaysTempTable1)AS D19,
			(Select [20] from #TempDaysTempTable1)AS D20,
			(Select [21] from #TempDaysTempTable1)AS D21,
			(Select [22] from #TempDaysTempTable1)AS D22,
			(Select [23] from #TempDaysTempTable1)AS D23,
			(Select [24] from #TempDaysTempTable1)AS D24,
			(Select [25] from #TempDaysTempTable1)AS D25,
			(Select [26] from #TempDaysTempTable1)AS D26,
			(Select [27] from #TempDaysTempTable1)AS D27,
			(Select [28] from #TempDaysTempTable1)AS D28,
			(CASE WHEN @Days > = 29 THEN (Select [29] from #TempDaysTempTable1) ELSE '' END )AS D29,
			(CASE WHEN @Days > = 30 THEN (Select [30] from #TempDaysTempTable1) ELSE '' END )AS D30,
			(CASE WHEN @Days > = 31 THEN (Select [31] from #TempDaysTempTable1) ELSE '' END )AS D31
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StatusId=@rStatus) OR (@rStatus=0))
		AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))


		DROP TABLE #TempDaysTempTable
END
ELSE
BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SA.DivisionOrder
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StatusId=@rStatus) OR (@rStatus=0))
		AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
END
		--SELECT 
		--	'' AS Builder1,
		--	'' AS Builder2,
		--	0 AS AcademicId,
		--	0 AS ClassId,
		--	0 AS DivisionId,
		--	'' AS ClassName,
		--	'' AS DivisionName,
		--	'' AS ClassDivision,
		--	'' AS Code,
		--	0 AS RollNo,			
		--	'' AS Name,
		--	'' AS DateOfBirth,
		--	0 AS DivisionOrder,
		--	0 AS IsHolidayWeekoff,
		--	'' AS D1,
		--	'' AS D2,
		--	'' AS D3,
		--	'' AS D4,
		--	'' AS D5,
		--	'' AS D6,
		--	'' AS D7,
		--	'' AS D8,
		--	'' AS D9,
		--	'' AS D10,
		--	'' AS D11,
		--	'' AS D12,
		--	'' AS D13,
		--	'' AS D14,
		--	'' AS D15,
		--	'' AS D16,
		--	'' AS D17,
		--	'' AS D18,
		--	'' AS D19,
		--	'' AS D20,
		--	'' AS D21,
		--	'' AS D22,
		--	'' AS D23,
		--	'' AS D24,
		--	'' AS D25,
		--	'' AS D26,
		--	'' AS D27,
		--	'' AS D28,
		--	'' AS D29,
		--	'' AS D30,
		--	'' AS D31
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pRptStudentRegisterSubjectWiseGet]
	 	 	  
		 @rBuilder1 nvarchar(max)='',
	     @rBuilder2 nvarchar(max)='', 
		 @rOrgId smallint,
		 @rBatchId int,
		 @rClassId int,
		 @rDivisionId int,
		 @rSubjectId int,
		 @rFromDate date,
		 @rToDate date,
		 @rStudentCode nvarchar(20),
		 @rReportId int = 0,
		 @rDepartmentId int,
		 @rPeriodNo int,
		 @rStatusId int=0,
		 @rAttendanceGroupId int = 0,
		 @rFilter int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rToDate = DATEADD (d,1,@rToDate)

IF @rFilter = 1
	BEGIN
		Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.Name,
		SA.Code,
		SA.RollNo,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		R.AttendanceDate,
		ISNULL(SM.Id,0) AS SubjectId,
		ISNULL(SM.Code,'') AS SubjectCode,
		ISNULL(SM.Title,'') AS SubjectName,
		R.IsPresent,
		R.PeriodNo,
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalPresentCount,
		
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = 0)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalAbsentCount,
		ISNULL(AG.Id,0) AS AttendanceGroupId,
		ISNULL(AG.Title,'') AS AttendanceGroupTitle,
		@rFilter AS Filter
		
	From 
	sAttendance.tStudentRegister R	 
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=R.SubjectId
	LEFT JOIN sAttendance.tAttendanceGroup AG ON AG.Id = R.AttendanceGroupId
	WHERE
		((R.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND (SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((R.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((R.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND R.AttendanceTypeId = 5
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((R.PeriodNo=@rPeriodNo) OR (@rPeriodNo=0))
		AND ((SA.StatusId =@rStatusId ) OR (@rStatusId=0))

		ORDER BY SA.AcademicId, SM.OrderIndex
	END

ELSE
	BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.Name,
		SA.Code,
		SA.RollNo,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		R.AttendanceDate,
		ISNULL(SM.Id,0) AS SubjectId,
		ISNULL(SM.Code,'') AS SubjectCode,
		ISNULL(SM.Title,'') AS SubjectName,
		R.IsPresent,
		R.PeriodNo,
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalPresentCount,
		
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = 0)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalAbsentCount,
		ISNULL(AG.Id,0) AS AttendanceGroupId,
		ISNULL(AG.Title,'') AS AttendanceGroupTitle,
		@rFilter AS Filter
		
	FROM 
	sAttendance.tStudentRegister R	 
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=R.SubjectId
	INNER JOIN sAttendance.tAttendanceGroup AG ON AG.Id = R.AttendanceGroupId
	WHERE
		((R.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND (SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((R.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((R.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND R.AttendanceTypeId = 5
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((R.PeriodNo=@rPeriodNo) OR (@rPeriodNo=0))
		AND ((SA.StatusId =@rStatusId ) OR (@rStatusId=0))
		AND ((R.AttendanceGroupId = @rAttendanceGroupId ) OR (@rAttendanceGroupId=0))

		ORDER BY SA.AcademicId, SM.OrderIndex
	END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pRptStudentwiseAbsentDaysDetailsGet]	
 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rDepartmentId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint,
	 @rFromDate date,
	 @rToDate date,
	 @rStudentCode nvarchar(20),
	 @rSubjectId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN 
 
 

	SELECT 
		DISTINCT(SA.AcademicId),
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,			
			sAttendance.fAttendanceGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate) AS AttendanceDate,
		    SA.DivisionOrder,
		    SC.ParentContactNo,
		     (SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND SR1.IsPresent=0) AS AbsentCount,
		     (SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND SR1.IsPresent=1) AS PresentCount,
			(SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))) AS TotalWorkingDays
				 
	FROM 
			sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		--AND (SR.IsPresent = 0)
		AND (SA.StatusId != 3)
		AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		GROUP BY SA.AcademicId,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.Code,SA.RollNo,SA.Name,SA.DivisionOrder,SC.ParentContactNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pRptStudentwiseAbsentDaysGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint,
	 @rSubjectId int,
	 @rFromDate date,
	 @rToDate date,
	 @rStudentCode nvarchar(20),
	 @rDepartmentId int,
	 @rIsAbsentRemark bit = 0	--mantis: 30947
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
	SELECT 
			DISTINCT(SA.AcademicId),
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,
			SA.Name,		
			SA.FirstName,
			SA.MiddleName,
			SA.LastName,
			(case when @rIsAbsentRemark =0 then sAttendance.fAttendanceGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate)	-- remove for mantis: 30947
			else sAttendance.fAttendanceWithRemarkGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate) end) AS AttendanceDate,	-- add for mantis: 30947
			AbsentCount=(SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND SR1.IsPresent=0),
		    
		   SA.DivisionOrder,
		   SC.ParentContactNo
	FROM 
			sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = 0)
		AND (SA.StatusId != 3)
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		GROUP BY SA.AcademicId,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.Code,SA.RollNo,SA.Name,SA.FirstName,SA.MiddleName,SA.LastName,SA.DivisionOrder,SC.ParentContactNo,SR.AttendanceRemark;

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pRptSubjectAttendanceGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 --@rForMonth tinyint,
	 	 --@rForYear smallint,
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		SN.AcademicId,
		SN.Name,
		SN.Code,
		SN.RollNo,
		MR.TotalCount,
		MR.PresentCount,
		MR.AbsentDays,
		MR.AbsentCount,
		ISNULL(SM.Id,0) AS SubjectId,
		ISNULL(SM.Title,'') AS SubjectName,
		ATM.Title AS AttendanceType
		
		
		
	From 
	sAttendance.tMonthlyRegister MR
	INNER JOIN sStudent.vStudentName SN ON SN.AcademicId=MR.AcademicId
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=MR.SubjectId
	LEFT JOIN sAttendance.tAttendanceTypeMaster ATM ON ATM.Id=MR.AttendanceTypeId
	
	WHERE
		(MR.SubjectId=@rSubjectId)
		AND (MR.AttendanceTypeId=@rAttendanceTypeId)
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pRptSubjectAttendanceSummaryGet]  
         
   @rBuilder1 nvarchar(max)='',  
   @rBuilder2 nvarchar(max)='',   
   @rOrgId smallint,  
   @rBatchId int,  
   @rClassId int,  
   @rDivisionId int,  
   @rSubjectId int,  
   @rFromDate date,  
   @rToDate date,  
   @rStudentCode nvarchar(20),  
   @rReportId int,  
   @rDepartmentId int,  
   @rStatusId int=0  
      
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
SET @rToDate = DATEADD (d,1,@rToDate)  
 Select   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  SA.AcademicId,  
  SA.Name,  
  SA.Code,  
  SA.RollNo,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SR.AttendanceDate,  
  --SA.TotalCount,  
  --SA.PresentCount,  
  --SA.AbsentDays,  
  --SA.AbsentCount,  
  ISNULL(SM.Id,0) AS SubjectId,  
  ISNULL(SM.Code,'') AS SubjectCode,  
  ISNULL(SM.Title,'') AS SubjectName,  
  ISNULL(SR.PeriodNo,'') As PeriodNo,
  --CAST(ISNULL(SR.IsPresent,'') as int) AS IsPresent
  
  case when SR.IsPresent = 1 then 1 when SR.IsPresent = 0 then 0 else '' end AS IsPresent,
  SO.GenderId
 
   
 From   
 sAttendance.tStudentRegister SR    
 INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SR.AcademicId  
 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId 
 LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
 WHERE  
  ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))  
  AND (SA.OrgId=@rOrgId)  
  AND (SA.BatchId = @rBatchId)   
  AND ((SA.ClassId=@rClassId) OR (@rClassId=0))  
  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
  ----AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))  
  AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
  AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))  
  AND SR.AttendanceTypeId = 5  
  AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))  
  AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((SA.StatusID=@rStatusId) OR (@rStatusId=0))  
  --AND (SA.StatusId != 3)  
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pRptSubjectStudentRegisterGet]
	 	 	  
		 @rBuilder1 nvarchar(max)='',
	     @rBuilder2 nvarchar(max)='', 
		 @rOrgId smallint,
		 @rBatchId int,
		 @rClassId int,
		 @rDivisionId int,
		 @rSubjectId int,
		 @rFromDate date,
		 @rToDate date,
		 @rStudentCode nvarchar(20),
		 @rReportId int = 0,
		 @rDepartmentId int,
		 @rPeriodNo int,
		 @rStatusId int=0,
		 @rAttendanceGroupId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rToDate = DATEADD (d,1,@rToDate)

	IF(@rReportId <> 30872)
	BEGIN
	Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.Name,
		SA.Code,
		SA.RollNo,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		R.AttendanceDate,
		ISNULL(SM.Id,0) AS SubjectId,
		ISNULL(SM.Code,'') AS SubjectCode,
		ISNULL(SM.Title,'') AS SubjectName,
		R.IsPresent,
		R.PeriodNo,
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalPresentCount,
		
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND (SR.IsPresent = 0)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalAbsentCount
		
	From 
	sAttendance.tStudentRegister R	 
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=R.SubjectId
	WHERE
		((R.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND (SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((R.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((R.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND R.AttendanceTypeId = 5
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((R.PeriodNo=@rPeriodNo) OR (@rPeriodNo=0))
		AND ((SA.StatusId =@rStatusId ) OR (@rStatusId=0))
	END
	ELSE
	BEGIN
		Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.Name,
		SA.Code,
		SA.RollNo,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		R.AttendanceDate,
		ISNULL(SM.Id,0) AS SubjectId,
		ISNULL(SM.Code,'') AS SubjectCode,
		ISNULL(SM.Title,'') AS SubjectName,
		R.IsPresent,
		R.PeriodNo,
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalPresentCount,
		
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND (SR.IsPresent = 0)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalAbsentCount,
		ISNULL(AG.Id,0) AS AttendanceGroupId,
		ISNULL(AG.Title,'') AS AttendanceGroupTitle	
		
	From 
	sAttendance.tStudentRegister R	 
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=R.SubjectId
	INNER JOIN sAttendance.tAttendanceGroup AG ON AG.Id = R.AttendanceGroupId
	WHERE
		((R.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND (SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((R.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((R.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND R.AttendanceTypeId = 5
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((R.PeriodNo=@rPeriodNo) OR (@rPeriodNo=0))
		AND ((SA.StatusId =@rStatusId ) OR (@rStatusId=0))
		AND ((R.AttendanceGroupId = @rAttendanceGroupId ) OR (@rAttendanceGroupId=0))
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pRptYearlyAttendanceGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rDepartmentId int = 0,
	 @rStatus int=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


	DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))

	DECLARE @lOrgId  int
	DECLARE @lSchoolRequiredSignature  nvarchar(500)

	SELECT  @lOrgId=RG.OrgId,
			@lSchoolRequiredSignature= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRequiredSignature,'')  ELSE RG.SchoolRequiredSignature END

	FROM	sCommon.tReportRemarkGroupMaster RGM
			LEFT JOIN sCommon.tReportRemarkGroupOrg RG ON RGM.Id = RG.ReportRemarkGroupId AND RG.OrgId = @rOrgId AND RG.ReportRemarkGroupId=1

	WHERE	RGM.Id=1

	DECLARE @Days int
	SELECT @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)

BEGIN
	CREATE TABLE #AttendanceRegistertempTable
	(
		TID int identity(1,1),
		ClassDivisionTitle Nvarchar(500),
		AcademicId bigint,
		AttendanceTypeId int,
		ForYear int,
		ForMonth int,
		ForMonthInWord nvarchar(500),
		ClassId int,
		DivisionId int,
		ClassName nvarchar(500),
		DivisionName nvarchar(500),
		DayPart int,
		ClassOrderIndex int,
		DivisionOrderIndex int,
		StatusId int,
		AttendanceDate date,
		AttendanceTagId int,
		Gender tinyint,
		LeftDate date,
		IsPresent bit
	)

	INSERT INTO #AttendanceRegistertempTable
	(
		ClassDivisionTitle,
		AcademicId,
		AttendanceTypeId,
		ForYear,
		ForMonth,
		ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		DayPart,
		ClassOrderIndex,
		DivisionOrderIndex,
		StatusId,
		AttendanceDate,
		AttendanceTagId,
		Gender,
		LeftDate,
		IsPresent
	)

	SELECT
		ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
		SA.AcademicId,
		SR.AttendanceTypeId,
		YEAR(SR.AttendanceDate) AS ForYear,
		MONTH(SR.AttendanceDate) AS ForMonth,
		DATENAME(MONTH, SR.AttendanceDate) AS ForMonthInWord,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		DAY(SR.AttendanceDate) AS DayPart,
		CM.OrderIndex AS ClassOrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.StatusId,
		SR.AttendanceDate AS AttendanceDate,
		SR.AttendanceTagId,
		SO.GenderId,
		A.LeftDate,
		SR.IsPresent

    FROM
		sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
		--LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		--LEFT JOIN  sStudent.tStudentFamily SF ON Sf.StudentId=Sa.StudentID
		--LEFT JOIN sCommon.tReligionMaster RE On RE.Id=SO.ReligionId
		--LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId

	WHERE
		((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	    AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	    AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	    AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	    AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	    AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	    AND ((SA.StatusId=@rStatus)OR (@rStatus=0))
	    --AND  ISNULL(EM.IsOtherUser,0) = 0

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

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



	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		PivotTable.AcademicId,
		ClassDivisionTitle,
		isnull(AttendanceTypeId,0) AS AttendanceTypeId,
		ForYear,
		ForMonth,
		ClassId,
		ClassName,
		DivisionId,
		DivisionName,
		ForMonthInWord,
		(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
		ISNULL(ABU.AUCount,0) AS AbsentUpto,
		ISNULL(TC.TCount,0) AS AttendanceCount,
		ISNULL(AC.ACount,0) AS  AbsentCount,
		ISNULL(PC.PCount,0) AS  PresentUpto,
		ClassOrderIndex,
		DivisionOrderIndex,
		(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,0)) AS TotalPresent,
		sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,
		Gender

	FROM
	(
		SELECT
			ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
			AcademicId,
			AttendanceTypeId,
			YEAR(ST.AttendanceDate) AS ForYear,
			MONTH(ST.AttendanceDate) AS ForMonth,
			DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
			ClassId,
			DivisionId,
			ClassName,
			DivisionName,
			(CASE	WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC'
					WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL'
					WHEN IsPresent = 1 AND ST.AttendanceTagId = 3 THEN 'N'
					WHEN IsPresent = 1 AND ST.AttendanceTagId = 4 THEN 'G'
					WHEN IsPresent = 1  THEN 'P'
					WHEN IsPresent = 0 THEN 'A'
					ELSE  DT.Value END
			)AS  IsPresent,
			day(ST.AttendanceDate) AS DayPart,
			ClassOrderIndex,
			DivisionOrderIndex,
			Gender,
			LeftDate
		FROM
			#AttendanceRegistertempTable ST
			INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
		WHERE
			((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
	) AS SourceTable

	PIVOT
	(
		MIN(IsPresent)
		FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
	) AS PivotTable

	LEFT JOIN
	(
		Select	AcademicId AS AcademicId,
				COUNT(1) AS TCount
		FROM	#AttendanceRegistertempTable
		GROUP BY	AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId

	LEFT JOIN
	(
		Select	AcademicId AS AcademicId,
				COUNT(1) AS ACount
		FROM	#AttendanceRegistertempTable
		WHERE   IsPresent = 0
        GROUP BY	AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId

	LEFT JOIN
	(
		SELECT	A.Id AS AcademicId,
				COUNT(1) AS PCount
		FROM	sAttendance.tStudentRegister SR
				INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
				INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
		WHERE	SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
				AND SR.IsPresent = 1
				AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
		GROUP BY	A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId

	LEFT JOIN
	(
		SELECT	A.Id AS AcademicId,
				COUNT(1) AS AUCount
		FROM	sAttendance.tStudentRegister SR
				INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
				INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
		WHERE	SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
				AND SR.IsPresent = 0
				AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
		GROUP BY	A.Id
    ) ABU ON ABU.AcademicId = PivotTable.AcademicId

	LEFT JOIN
	(
		SELECT	A.Id AS AcademicId,
				COUNT(1) AS TotalPresent
		FROM	sAttendance.tStudentRegister SR
				INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
				INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
		WHERE	SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
				AND	((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
		GROUP BY	A.Id
    ) AA ON AA.AcademicId = PivotTable.AcademicId



SELECT * FROM #TempDaysTempTable

DROP TABLE #AttendanceRegistertempTable
DROP TABLE #TempDaysTempTable



	--SELECT
	--		'' AS Builder1,
	--		'' AS Builder2,
	--		Convert(bigint,0) AS AcademicId,
	--		'' AS ClassDivisionTitle,
	--		0 as AttendanceTypeId,
	--		0 as ForYear,
	--		0 as ForMonth,
	--		0 as ClassId,
	--		'' as ClassName,
	--		0 as DivisionId,
	--		'' as DivisionName,
	--		'' as ForMonthInWord,
	--		0 AS PresentCount,
	--		0 AS AbsentUpto,
	--		0 AS AttendanceCount,
	--	    0 As AbsentCount,
	--	    0 As PresentUpto,
	--	    0 as ClassOrderIndex,
	--	    0 as DivisionOrderIndex,
	--		0 AS TotalPresent,
	--		0 AS DaysInMonth,
	--		0 as Gender,
	--		Convert(date,'') AS LeftDate

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pSetupDelete]

@rSetupTypeId tinyint, 
@rClassId int,
@rBatchId int,	
@rAcademicId bigint
 
WITH EXECUTE AS CALLER

AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
	
	--@rSetupTypeId = 1 - Monthly Setup
	--@rSetupTypeId = 2 - Student Setup
	
BEGIN TRANSACTION	

IF @rSetupTypeId = 1 -- 
BEGIN
DELETE sAttendance.tMonthlySetup
WHERE BatchId = @rBatchId AND ClassId = @rClassId
SELECT 1 AS Result

END
ELSE IF @rSetupTypeId = 2
  BEGIN
  DELETE sAttendance.tStudentSetup
	WHERE AcademicId = @rAcademicId	 
 SELECT 1 AS Result 
 END
	COMMIT TRANSACTION			
	END TRY	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--Changes for Mantis Id: 0039838
DECLARE @lConfigValueDashboard nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValueDashboard = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValueDashboard, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValueDashboard <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValueDashboard <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

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

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

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

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

--Organization wise Attendance

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

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

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

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

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

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

      END
   
ELSE IF @rTypeId=24     
      BEGIN

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

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

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

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

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

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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 1,'2019-02-12'


--Exec [sAttendance].[pStudentAttendaceDashboardGet] 21,'2018-01-03',0,1101
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 1,'2018-11-27',1101,0,0

--Exec [sAttendance].[pStudentAttendaceDashboardGet] 12,'2018-11-27',1101 --For First 3
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 14,'2018-11-27',1101 --For First Middle 3
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 18,'2018-01-03',1101 --For Attnd Not Taken
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 16,'2018-01-03',1101 --For Leave Required
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 17,'2018-01-03',1101 --For Leave Required

--Exec [sAttendance].[pStudentAttendaceDashboardGet] 11,'2018-11-27',1101 --For First 3
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 21,'2018-11-27',0,1101 --For First 3
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 1110,'',100100001,0,100100001 --For First 3

--Create By MP At 05 Feb 2019
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentAttendaceDashboardGet_BackUp_13Feb2019]
	 
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDivisionId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--Comment
--@rTypeId=1 for Org Group
--@rTypeId=2 for Org
--rTypeId=11 for Org Group Nested Total Student
--rTypeId=12 for Org Group Nested Presnt Student
--rTypeId=13 for Org Group Nested Absent Student
--rTypeId=14 for Org Group Less Than 70% Student
--rTypeId=15 for Org Group Less Than 100% Student
--rTypeId=16 for Org Group Leave Required
--rTypeId=17 for Org Group Student Consicutive Last 3 Days Absent
--rTypeId=18 for Org Group Attendance Not Taken In the Class 


--rTypeId=21 for Org Group Nested Total Student
--rTypeId=22 for Org Group Nested Presnt Student
--rTypeId=23 for Org Group Nested Absent Student
--rTypeId=24 for Org Group Less Than 70% Student
--rTypeId=25 for Org Group Less Than 100% Student
--rTypeId=26 for Org Group Leave Required
--rTypeId=27 for Org Group Student Consicutive Last 3 Days Absent
--rTypeId=28 for Org Group Attendance Not Taken In the Class

---rTypeId=1110 for Org Group And ORG Both for Division Details for ALL
---rTypeId=1111 for Org Group And ORG Both for Division Details for male
---rTypeId=1112 for Org Group And ORG Both for Division Details for Female



	   
if @rTypeId=1
   BEGIN
	   
	   
	  
       --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
       --COUNT(SM.AcademicId) AS TotalStudent,
   SELECT 
    OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
       
    (select COUNT(SMT.AcademicId)
       FROM sAttendance.tStudentRegister SMT 
		 INNER JOIN sStudent.tAcademic A ON SMT.Academicid=A.id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGM.Id=OM.OrgGroupId
      
         where OGM.Id = OGMR.Id  and SMT.AttendanceDate=@rUptoDate) as Total,
       
       
       
       (select count(*) from sAttendance.tStudentRegister SME 
        INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
        where OGM.Id = OGME.Id and SME.IsPresent=1 
        and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)

        ) as PresentStudent,
       
       (select count(*) from sAttendance.tStudentRegister SME 
        INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
        where OGM.Id = OGMEA.Id and SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)) as AbsentStudent,
        
        
        
        
        
        
       
       
  --     (select count(*) from  (select AcademicId,count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage
		--from sAttendance.tStudentRegister SMEL
		--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--where OGM.Id = OGMEL.Id AND SMEL.IsPresent=1 AND
		----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		----and AcademicId=1101000002249
		--group by SMEL.AcademicId
		--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) < 70) as Temp) AS LessThen70,


      (select Count(*) AS LessThen70  from (
        select AcademicId,Count(AcademicId) Total, count(case when IsPresent=1 then 1 end) as PresentCount,

        convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100)) as Percentage

		from sAttendance.tStudentRegister SMEL
		INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		where OGM.Id = OGMEL.Id --AND AcademicID IN (9999000000775,9999000000781) 
		AND
		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		group by SMEL.AcademicId
		
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp) As LessThen70,





		--(select count(*) from  (select AcademicId,count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage
		--from sAttendance.tStudentRegister SMEL
		--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
	
		--where OGM.Id = OGMEL.Id AND SMEL.IsPresent=1 AND
		----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		----and AcademicId=1101000002249
		--group by SMEL.AcademicId
		--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) =100) as Temp) AS HundresPer,
        
        
        (select Count(*) AS HundresPer  from (
        select AcademicId,Count(AcademicId) Total, count(case when IsPresent=1 then 1 end) as PresentCount,

        convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100)) as Percentage

		from sAttendance.tStudentRegister SMEL
		INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		where OGM.Id = OGMEL.Id --AND AcademicID IN (9999000000775,9999000000781) 
		AND
		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		group by SMEL.AcademicId
		
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp) AS HundresPer,
        
        
        
        
  --     (select Count(rowno) from(
		--	select 
			    
		--		AcademicId,
		--		ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		--		StartDate   =   MIN(AttendanceDate),
		--		EndDate     =   MAX(AttendanceDate)--,
		--		--Days        =   DATEDIFF(DD, MIN(AttendanceDate), MAX(AttendanceDate)) + 1 
		--		--                - SUM((CASE WHEN IsPresent IN(0) THEN 1 ELSE 0 END))
		--	from (
		--	SELECT 
		--		AcademicId,AttendanceDate,IsPresent,
		--	DateGroup = DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
		--	FROM sAttendance.tStudentRegister  as d
			
		--	INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
		--	INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
		--	INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--	INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			
		--	WHERE
		--		--Status IN('A', 'WO', 'H')
		--		IsPresent IN(0) and OGM.Id = OGMEL.Id 
		--		--and AcademicId=AEL.Academicid
		--		--and AttendanceDate between '2018-01-01' AND '2018-01-10'
		--		and AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		--) AS GroupedDates 
		--GROUP BY 
		--	AcademicId, DateGroup
		--HAVING 
		--	SUM(CASE WHEN IsPresent IN(0) THEN 1 ELSE 0 END) >=3
		    
		--	) as FinalQuery 
		--	where rowno=1) AS AbsentCount,
			
		(select COUNT(AcademicId) from(
	     select ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,

		AcademicId,AttendanceDate--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
		FROM sAttendance.tStudentRegister d 
		
		 	INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		
        WHERE
        OGM.Id = OGMEL.Id AND
        --Status IN('A', 'WO', 'H')
        IsPresent IN(0) 
        --AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, @rUptoDate),126)) and CONVERT(char(10), @rUptoDate,126)        
        AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
        --and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
         --and AttendanceDate between '2018-01-01' and '2018-01-03'
         and IsPresent=0
        Group By AcademicId,AttendanceDate
        ) as sfsf
        where rowno=3) as AbsentCount,

	  -- (select COUNT(AcademicId) from (select STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
		 --Left join sAttendance.tStudentLeaveRequest STSL ON STS.AcademicId=STSL.AcademicId
		 --INNER JOIN sStudent.tAcademic AEL ON STS.Academicid=AEL.id
		 --INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		 --INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		 --INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		 --where OGM.Id = OGMEL.Id AND
		 
		 ----STSL.AcademicId is NOT null and STS.AttendanceDate between '2018-01-01' and '2018-01-03' --<= CONVERT(char(10), @rUptoDate,126)
		 --STSL.AcademicId is NOT null and STS.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
   --      ) as a) As LeaveRequest,
   
   
		   (select 
		Count(AcademicId) AS LeaveRequest
		From sAttendance.tStudentLeaveRequest STSL
		INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
								 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
								 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
								 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
								 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
								 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
								 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								  
		--AcademicId=1101000002534 and 
		where OGM.Id = OGMEL.Id AND
		--'2017-11-27' between LeaveFromDate AND LeaveToDate) As LeaveRequest,
		CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate) As LeaveRequest,
		  
		  
         (select Count(ClassID) from (select 
		  ClassId,
		  ATA.ID,
		   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		  from sStudent.tAcademic ATA 
		  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
			 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 where OGM.Id = OGMEL.Id 
		  
		  
		 ) As Temp 
		 where
			rowno=1 AND
			ID not in(select AcademicId from sAttendance.tStudentRegister Where
			--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
			AttendanceDate = CONVERT(char(10), @rUptoDate,126))) as AttnNotTakenClass
	 
        
         
			
	FROM sSetup.tOrgGroupMaster OGM 
	where OGM.Id<>1
	   	
    --FROM sAttendance.tStudentRegister SM 
    --INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
    --INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
    --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
    --INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
    --where AttendanceDate=CONVERT(char(10), @rUptoDate,126)--@rUptoDate
    --GROUP BY OGM.Id , OGM.Title
	
	
	END
ELSE IF @rTypeId=2
    BEGIN
		 
	   --SELECT 
    --   OM.Id AS OrgId, OM.Title AS OrgTitle,
    --   COUNT(SM.AcademicId) AS TotalStudent  ,
    
    SELECT 
    OM.Id AS OrgGroupId, OM.Title AS OrgTitle,
       
    (select COUNT(SMT.AcademicId)
       FROM sAttendance.tStudentRegister SMT 
		 INNER JOIN sStudent.tAcademic A ON SMT.Academicid=A.id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OMR ON OM.Id = BM.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
      
        -- where OGM.Id = 1101 and SMT.AttendanceDate=@rUptoDate) as Total,
         where OM.Id = OMR.Id and SMT.AttendanceDate=@rUptoDate) as Total,
         
         
       
       (select count(*) from sAttendance.tStudentRegister SME 
        INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
        where OM.Id = OME.Id and SME.IsPresent=1 
        and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)

        ) as PresentStudent,
        
        
        (select count(*) from sAttendance.tStudentRegister SME 
        INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
        where OM.Id = OME.Id and SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)) as AbsentStudent,
        
        
  --      (select count(*) from  (select AcademicId,count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage
		--from sAttendance.tStudentRegister SMEL
		--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--where OM.Id = OMEL.Id AND SMEL.IsPresent=1 AND
		----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		----and AcademicId=1101000002249
		--group by SMEL.AcademicId
		--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) < 70) as Temp) AS LessThen70,
		
		
		
		 (select Count(*) AS LessThen70  from (
        select AcademicId,Count(AcademicId) Total, count(case when IsPresent=1 then 1 end) as PresentCount,

        convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100)) as Percentage

		from sAttendance.tStudentRegister SMEL
		INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		where OM.Id = OMEL.Id --AND AcademicID IN (9999000000775,9999000000781) 
		AND
		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		group by SMEL.AcademicId
		
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp) AS LessThen70,
		
		
		--(select count(*) from  (select AcademicId,count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage
		--from sAttendance.tStudentRegister SMEL
		--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
	
		--where OM.Id = OMEL.Id AND SMEL.IsPresent=1 AND
		----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		----and AcademicId=1101000002249
		--group by SMEL.AcademicId
		--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) =100) as Temp) AS HundresPer,
		
		
		(select Count(*) AS HundresPer  from (
        select AcademicId,Count(AcademicId) Total, count(case when IsPresent=1 then 1 end) as PresentCount,

        convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100)) as Percentage

		from sAttendance.tStudentRegister SMEL
		INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		where OM.Id = OMEL.Id --AND AcademicID IN (9999000000775,9999000000781) 
		AND
		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		group by SMEL.AcademicId
		
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp) AS HundresPer,
		
		
		
		
		
		(select COUNT(AcademicId) from(
	     select ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,

		AcademicId,AttendanceDate--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
		FROM sAttendance.tStudentRegister d 
		
		 	INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		
        WHERE
        OM.Id = OMEL.Id AND
        --Status IN('A', 'WO', 'H')
        IsPresent IN(0) 
       -- AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, @rUptoDate),126)) and CONVERT(char(10), @rUptoDate,126)        
       AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
        --and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
         --and AttendanceDate between '2018-01-01' and '2018-01-03'
         and IsPresent=0
        Group By AcademicId,AttendanceDate
        ) as sfsf
        where rowno=3) as AbsentCountSecond,
        
        
   --     (select COUNT(AcademicId) from (select STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
		 --Left join sAttendance.tStudentLeaveRequest STSL ON STS.AcademicId=STSL.AcademicId
		 --INNER JOIN sStudent.tAcademic AEL ON STS.Academicid=AEL.id
		 --INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		 --INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		 --INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		 --where OM.Id = OMEL.Id AND
		 
		 ----STSL.AcademicId is NOT null and STS.AttendanceDate between '2018-01-01' and '2018-01-03' --<= CONVERT(char(10), @rUptoDate,126)
		 --STSL.AcademicId is NOT null and STS.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
   --      ) as a) As LeaveRequired,
         
         
         
          (select 
		Count(AcademicId) AS LeaveRequest
		From sAttendance.tStudentLeaveRequest STSL
		INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
								 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
								 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
								 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
								 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
								 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
								 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								  
		--AcademicId=1101000002534 and 
		where OM.Id = OMEL.Id AND
		--'2017-11-27' between LeaveFromDate AND LeaveToDate) As LeaveRequest,
		CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate) As LeaveRequest,
         
         
         
         
         (select Count(ClassID) from (select 
		  ClassId,
		  ATA.ID,
		   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		  from sStudent.tAcademic ATA 
		  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
			 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 where OM.Id = OMEL.Id 
		  
		  
		 ) As Temp 
		 where
			rowno=1 AND
			ID not in(select AcademicId from sAttendance.tStudentRegister Where
			--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
			AttendanceDate = CONVERT(char(10), @rUptoDate,126))) as AttnNotTakenClass

       
       
        FROM sSetup.tOrgGroupMaster OGMT 
        Inner join sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId 
        
        where OGMT.Id=@rOrgGroupId
        
  --      FROM sAttendance.tStudentRegister SM 
		--INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
		--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
		
		--AND SM.AttendanceDate= CONVERT(char(10), @rUptoDate,126)
		
		--where OM.OrgGroupId=@rOrgGroupId
		--GROUP BY OM.Id , OM.Title
		 
		 
		 
    END

ELSE IF @rTypeId=11

	BEGIN
        
          
     	SELECT (OGM.Title) As OrgGroupTile,DM.ID AS DivisionId,DM.Code AS DivisionCode,COUNT(A.StudentID) AS TotalStudents,
			 count(case when SOD.GenderID=1 then 1 end) as Male,
			 count(case when SOD.GenderID=2 then 1 end) as Female
  
			   --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
			   --SM.DivisionId
			   --COUNT(SM.AcademicId) AS TotalStudent
			
				FROM sAttendance.tStudentRegister SM 
				INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
				INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
			    --where OGM.Id=1101
			    where OGM.Id=@rOrgGroupId
			    AND SM.AttendanceDate<=CONVERT(char(10), @rUptoDate,126)--@rUptoDate
			   
			    
				--GROUP BY OGM.Id , OGM.Title
				GROUP BY OGM.Title,DM.ID,DM.Code
     
     
    END
    
ELSE IF @rTypeId=21
    BEGIN
         --select 1
         SELECT OM.Title As OrgTitle,DM.ID As DivisionId,DM.Code As DivisionCode,COUNT(A.StudentID) AS TotalStudent,
			 count(case when SOD.GenderID=1 then 1 end) as Male,
			 count(case when SOD.GenderID=2 then 1 end) as Female
  
			   --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
			   --SM.DivisionId
			   --COUNT(SM.AcademicId) AS TotalStudent
			
				FROM sAttendance.tStudentRegister SM 
				INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
				INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
			    where OM.Id=@rOrgId
			     AND SM.AttendanceDate<=CONVERT(char(10), @rUptoDate,126)--@rUptoDate
			    --where OM.Id=@rOrgId
			   
			    
				--GROUP BY OGM.Id , OGM.Title
				GROUP BY OM.Title,DM.ID,DM.Code
       
       
     END
    
    

ELSE IF @rTypeId=12
    
    BEGIN
         
         select 
				 OGME.Title As OrgGroupTitle,DM.ID As DivisionId,DM.Code As DivisionCode,COUNT(AE.StudentID) AS TotalStudent,
				 count(case when SOD.GenderID=1 then 1 end) as Male,
				 count(case when SOD.GenderID=2 then 1 end) as Female
				 
				  from sAttendance.tStudentRegister SME 
					INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
					INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
					INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
				    INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				    INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					
					where OGME.Id=@rOrgGroupId and SME.IsPresent=1 
					and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
					 GROUP BY OGME.Title,DM.ID,DM.Code
         
    END
   
ELSE IF @rTypeId=22
	BEGIN
     
      select 
				 OME.Title As OrgTitle,DM.ID As DivisionId,DM.Code As DivisionCode,COUNT(AE.StudentID) AS TotalStudent,
				 count(case when SOD.GenderID=1 then 1 end) as Male,
				 count(case when SOD.GenderID=2 then 1 end) as Female
				 
				  from sAttendance.tStudentRegister SME 
					INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
					INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
					INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
				    INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				    INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					
					where OME.Id=@rOrgId and SME.IsPresent=1 
					and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
					 GROUP BY OME.Title,DM.ID,DM.Code
     
     
	END
   
   
ELSE IF @rTypeId=13
      BEGIN
      
          (select 
					 OGMEA.Title As OrgGroupTitle,DM.ID As DivisionId,DM.Code As DivisionCode,COUNT(AE.StudentID) AS TotalStudent,
					 count(case when SOD.GenderID=1 then 1 end) as Male,
					 count(case when SOD.GenderID=2 then 1 end) as Female
					 
					
					 from sAttendance.tStudentRegister SME 
					INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
					INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
					INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
					INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					where OGMEA.Id=@rOrgGroupId and SME.IsPresent=0 
					and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEA.Title,DM.ID,DM.Code
	 
					)
    
       END
       
ELSE IF @rTypeId=23
       BEGIN
          --SELECT 23
          (select 
					 OGMEA.Title As OrgTitle,DM.ID As DivisionId,DM.Code As DivisionCode,COUNT(AE.StudentID) AS TotalStudent,
					 count(case when SOD.GenderID=1 then 1 end) as Male,
					 count(case when SOD.GenderID=2 then 1 end) as Female
					 
					
					 from sAttendance.tStudentRegister SME 
					INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
					INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
					INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
					INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					where OME.Id=@rOrgId 
					and SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEA.Title,DM.ID,DM.Code
	 
					)
    
       END       
       
ELSE IF @rTypeId=14
   
      BEGIN
          
      --    (select * from  (
						--select 
						----(SMEL.AcademicId) AcademicID,
						----count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
						--DM.Code,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						--,
						--(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
						--from sAttendance.tStudentRegister SMEL
						--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						--INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						----INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  ----      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						--INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						----INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						--INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
						--where OGMEL.Id=@rOrgGroupId AND
						----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
						--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						
						----and AcademicId=1101000002249
						----group by AEL.ID
						--GROUP BY SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
						--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) =100) as Temp
						--) 
						
						
						
						
  (select *from  (
        select  
         OGMEL.Title As OrgGroupTitle ,DM.Code As DivisionCode,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						,
						(SC.PresentContactNo) AS ContactNo
						from sAttendance.tStudentRegister SMEL
						INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	     
	     
		--where OGMEL.Id=1101 --AND AcademicID IN (9999000000775,9999000000781) 
		where OGMEL.Id=@rOrgGroupId AND

		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGMEL.Title ,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo)
		
		
	   HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	   ) AS Tmp) 
		
						
						
						
						
          
          
      END
   
ELSE IF @rTypeId=24
     
      BEGIN
          
      --    (select * from  (
						--select 
						----(SMEL.AcademicId) AcademicID,
						----count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
						--DM.Code,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						--,
						--(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
						--from sAttendance.tStudentRegister SMEL
						--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						--INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						----INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  ----      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						--INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						----INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						--INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
						--where OMEL.Id=@rOrgId AND
						----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
						--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						
						----and AcademicId=1101000002249
						----group by AEL.ID
						--GROUP BY SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
						--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) =100) as Temp
						--) 
          
          
          (select *from  (
            select  
            OGMEL.Title As OrgTitle ,DM.Code As DivisionCode,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						,
						(SC.PresentContactNo) AS ContactNo
						from sAttendance.tStudentRegister SMEL
						INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	     
	     
		--where OGMEL.Id=1101 --AND AcademicID IN (9999000000775,9999000000781) 
		where OMEL.Id=@rOrgId AND

		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGMEL.Title ,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo)
		
		
	   HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	   ) AS Tmp) 
		
          
          
          
          
          
      END   
   
ELSE IF @rTypeId=15
   
	   BEGIN
	   
	     -- (select * from  (
						--select 
						----(SMEL.AcademicId) AcademicID,
						----count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
						--DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						--,
						--(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
						--from sAttendance.tStudentRegister SMEL
						--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						--INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						----INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  ----      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						--INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						----INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						--INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
						--where OGMEL.Id=@rOrgGroupId AND
						----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
						--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						
						----and AcademicId=1101000002249
						----group by AEL.ID
						--GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
						--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) = 100) as Temp
						--)
						
						
						
						(select *from  (
                          select  
                            OGMEL.Title As OrgGroupTitle ,DM.Code As DivisionCode,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						,
						(SC.PresentContactNo) AS ContactNo
						from sAttendance.tStudentRegister SMEL
						INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	     
	     
		--where OGMEL.Id=1101 --AND AcademicID IN (9999000000775,9999000000781) 
					where OGMEL.Id=@rOrgGroupId AND

					--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
					SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEL.Title ,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo)
		
		
	                HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	           ) AS Tmp) 
		
	        
	   
	   END
	   
ELSE IF @rTypeId=25
   
	   BEGIN
	   
	     -- (select * from  (
						--select 
						----(SMEL.AcademicId) AcademicID,
						----count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
						--DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						--,
						--(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
						--from sAttendance.tStudentRegister SMEL
						--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						--INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						----INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  ----      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						--INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						----INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						--INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
						--where OMEL.Id=@rOrgId AND
						----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
						
						--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						----and AcademicId=1101000002249
						----group by AEL.ID
						--GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
						--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) = 100) as Temp
						--)
						
						
						
						(select *from  (
                          select  
                            OMEL.Title As OrgTitle,DM.Code As DivisionCode,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						,
						(SC.PresentContactNo) AS ContactNo
						from sAttendance.tStudentRegister SMEL
						INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	     
	     
		--where OGMEL.Id=1101 --AND AcademicID IN (9999000000775,9999000000781) 
					where OMEL.Id=@rOrgId AND

					--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
					SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY OMEL.Title  ,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo)
		
		
	                HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	           ) AS Tmp) 
	        
	   
	   END
	   
	   
ELSE IF @rTypeId=16
   
   BEGIN
        
        (select * from (select 
						--STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
						 --DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName from sAttendance.tStudentRegister STS
						 OGMEL.Title As OrgGroupTitle  ,DM.Code As DivisionCode,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
						 (SC.PresentContactNo) AS ContactNo
						 
						 from sAttendance.tStudentLeaveRequest STSL --ON STS.AcademicId=STSL.AcademicId
						 INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						 
						
						 --where OGMEL.Id=1101 AND
						 where OGMEL.Id=@rOrgGroupId AND
						 CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
						 --'2017-11-27' between LeaveFromDate AND LeaveToDate 
						 --STSL.AcademicId is NOT null and STS.AttendanceDate between '2018-01-01' and '2018-01-03' --<= CONVERT(char(10), @rUptoDate,126)
						
						 
						 --GROUP BY STS.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
						 ) as a) 
        
        
   END
   
   
ELSE IF @rTypeId=26
   
   BEGIN
      
        (select * from (select 
						--STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
						 --DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName from sAttendance.tStudentRegister STS
						 OGMEL.Title As OrgTitle,DM.Code As DivisionCode,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName 
						 from sAttendance.tStudentLeaveRequest STSL --ON STS.AcademicId=STSL.AcademicId
						 INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						 
						 
						 where OMEL.Id=@rOrgId AND
						  CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
						  --'2017-11-27' between LeaveFromDate AND LeaveToDate 
						 
						
						 --GROUP BY STS.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
						 ) as a) 
        
        
   END
   
ELSE IF @rTypeId=17
   
   BEGIN
       
        (select Title As OrgGroupTitle,Code As DivisionCode,StudentID,StudentName from(
							 select 
							 ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
							 

							AcademicId,AttendanceDate, DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OGMEL.Title--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
							FROM sAttendance.tStudentRegister d 
							
		 						INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
								INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
								INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
								INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
								INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
								INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
								INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
							
							
							WHERE
							OGMEL.Id=@rOrgGroupId AND
							--Status IN('A', 'WO', 'H')
							IsPresent IN(0) 
							--AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, @rUptoDate),126)) and CONVERT(char(10), @rUptoDate,126)
							AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate   
							--and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
							 and AttendanceDate between '2018-01-01' and '2018-01-03'
							 and IsPresent=0
							Group By OGMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName) 
							) as sfsf
							where rowno=3) 
        
   END
   
   
ELSE IF @rTypeId=27
   
   BEGIN
       
        (select Title As OrgTitle, Code As DivisionCode,StudentID,StudentName from(
							 select 
							 ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
							 

							AcademicId,AttendanceDate, DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OGMEL.Title--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
							FROM sAttendance.tStudentRegister d 
							
		 						INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
								INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
								INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
								INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
								INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
								INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
								INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
							
							
							WHERE
							OMEL.Id=@rOrgId AND
							--Status IN('A', 'WO', 'H')
							IsPresent IN(0) 
							--AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, '2018-01-03'),126)) and CONVERT(char(10), '2018-01-03',126)        
							AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
							--and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
							 --and AttendanceDate between '2018-01-01' and '2018-01-03'
							 --AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, @rUptoDate),126)) and CONVERT(char(10), @rUptoDate,126)
							 and IsPresent=0
							Group By OGMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName) 
							) as sfsf
							where rowno=3) 
        
   END
   
ELSE IF @rTypeId=18
   
   BEGIN
       
       (select 
         Temp.Title As OrgGroupTitle,
         DM.Code As DivisionCode,
         (EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.PresentContactNo) AS ContactNo  from (
         select OGMEL.Title,
		  ClassId,
		  ATA.ID,
		   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		  from sStudent.tAcademic ATA 
		  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
			 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId --lAND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 where OGMEL.Id =@rOrgGroupId
		  
		  
		 ) As Temp 
		  LEFT JOIN sSetup.tClassMaster CM ON CM.Id=Temp.ClassID
		  LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassID=CM.Id
		  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
		  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		 
		 where
			rowno=1 AND 
			   --AND ClassID=110100001 			  
			Temp.ID not in(select AcademicId from sAttendance.tStudentRegister Where
			--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
			AttendanceDate = CONVERT(char(10), @rUptoDate,126) 
			
			)
			
			) 
       
   END
   
   
ELSE IF @rTypeId=28
   
   BEGIN
       
       (select 
         Temp.Title As OrgTitle,
         DM.Code As DivisionCode,
         (EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.PresentContactNo) AS ContactNo  from (
         select OGMEL.Title,
		  ClassId,
		  ATA.ID,
		   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		  from sStudent.tAcademic ATA 
		  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
			 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId --lAND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 where OMEL.Id =@rOrgId
		  
		  
		 ) As Temp 
		  LEFT JOIN sSetup.tClassMaster CM ON CM.Id=Temp.ClassID
		  LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassID=CM.Id
		  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
		  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		 
		 where
			rowno=1 AND
			   --AND ClassID=110100001 			  
			Temp.ID not in(select AcademicId from sAttendance.tStudentRegister Where
			--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
			AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			 
			--AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			
			)
			
			) 
       
   END

ELSE IF @rTypeId=1110
   
   BEGIN
   --SELECT 1
     
     --Details Section individual Division wise(For Common)--Parameter(DivisionID,GenderID)
	
							select (DM.Id) AS DivisionId,SMD.Id As StudentId,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
							(SC.PresentContactNo) AS ContactNo
							
							 from sSetup.tDivisionMaster DM
							INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
							INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
							INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
							INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
							--where DM.ID='100100001' order by A.StudentID
							where DM.ID=@rDivisionId order by A.StudentID
							
     
     
   END

ELSE IF @rTypeId=1111

	BEGIN
      --SELECT 1
      select (DM.Id) AS DivisionId,SMD.Id As StudentId,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
								(SC.PresentContactNo) AS ContactNo
								
								 from sSetup.tDivisionMaster DM
								INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
								INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
								INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
								INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								
								--where DM.ID='100100001'
								where DM.ID=@rDivisionId 
								and SOD.GenderID=1 
								order by A.StudentID
      
      
	END
ELSE IF @rTypeId=1112
	BEGIN
	  
	  select (DM.Id) AS DivisionId,SMD.Id As StudentId,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
								(SC.PresentContactNo) AS ContactNo
								
								 from sSetup.tDivisionMaster DM
								INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
								INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
								INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
								INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								
								--where DM.ID='100100001' 
								where DM.ID=@rDivisionId 
								and SOD.GenderID=2 
								order by A.StudentID
	  
	   
	END


--END




-------------------------------------------------------------------------------------------------------------------------------




      -----------Attnd Not Taken For Org Group
      
  --       (select 
  --       Temp.Title,
  --       DM.Code,
  --       (EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.PresentContactNo) AS ContactNo  from (
  --       select OGMEL.Title,
		--  ClassId,
		--  ATA.ID,
		--   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		--  from sStudent.tAcademic ATA 
		--  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
		--	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId --lAND BMEL.IsActive = 1
		--	 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--	 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--	 where OGMEL.Id =1101
		  
		  
		-- ) As Temp 
		--  LEFT JOIN sSetup.tClassMaster CM ON CM.Id=Temp.ClassID
		--  LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassID=CM.Id
		--  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		 
		-- where
		--	rowno=1 AND
		--	   --AND ClassID=110100001 			  
		--	Temp.ID not in(select AcademicId from sAttendance.tStudentRegister Where
		--	--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
		--	AttendanceDate = CONVERT(char(10), '2018-01-03',126) 
		--	)
			
		--	) 
			
		--	------------------------------Attnd Not Taken For Org
			
			
		--	       (select 
  --       Temp.Title,
  --       DM.Code,
  --       (EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.PresentContactNo) AS ContactNo  from (
  --       select OMEL.Title,
		--  ClassId,
		--  ATA.ID,
		--   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		--  from sStudent.tAcademic ATA 
		--  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
		--	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId --lAND BMEL.IsActive = 1
		--	 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--	 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--	 where OMEL.Id =1101
		  
		  
		-- ) As Temp 
		--  LEFT JOIN sSetup.tClassMaster CM ON CM.Id=Temp.ClassID
		--  LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassID=CM.Id
		--  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		 
		-- where
		--	rowno=1 AND
		--	   --AND ClassID=110100001 			  
		--	Temp.ID not in(select AcademicId from sAttendance.tStudentRegister Where
		--	--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
		--	AttendanceDate = CONVERT(char(10), '2018-01-03',126) 
		--	)
			
		--	) 
			
		--	--as AttnNotTakenClass  
			
			
			
			
			
			
		-----------------------
		
		
		----------------------Total Student Details for ORG Group
		--	 --SELECT DM.ID,DM.Code,COUNT(A.StudentID) AS TotalStudent,
		--	 --count(case when SOD.GenderID=1 then 1 end) as Male,
		--	 --count(case when SOD.GenderID=2 then 1 end) as Female
  
		--	 --  --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
		--	 --  --SM.DivisionId
		--	 --  --COUNT(SM.AcademicId) AS TotalStudent
			
		--		--FROM sAttendance.tStudentRegister SM 
		--		--INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
		--		--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		--		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		--		--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
		--		--INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
		--		--INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--		--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
		--	 --   where OGM.Id=1101
		--		----GROUP BY OGM.Id , OGM.Title
		--		--GROUP BY DM.ID,DM.Code
			
			
		--	--Change after disucssion
			
		--	select ID,Code,Count(StudentID) TotalCount,count(case when GenderID=1 then 1 end) as Male,count(case when GenderID=2 then 1 end) as Female from (SELECT 
		--		 ROW_NUMBER() OVER ( PARTITION BY A.StudentID,A.DivisionID ORDER BY A.StudentID DESC) as rowno,
		--		 A.StudentID,DM.ID,DM.Code,SOD.GenderID
		--		 --DM.ID,DM.Code,COUNT(A.StudentID) AS TotalStudent,
		--		 --count(case when SOD.GenderID=1 then 1 end) as Male,
		--		 --count(case when SOD.GenderID=2 then 1 end) as Female
  
		--	   --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
		--	   --SM.DivisionId
		--	   --COUNT(SM.AcademicId) AS TotalStudent
			
		--		FROM sAttendance.tStudentRegister SM 
		--		INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
		--		INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--		INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
		--	    where OGM.Id=1101
		--	    --and SM.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--	    ) AS Temp 
		--	    where rowno=1
		--	    GROUP BY ID,Code
			
			
			
		----------------------Total Student Details for ORG 
		
		-- --SELECT DM.ID,DM.Code,COUNT(A.StudentID) AS TotalStudent,
		--	-- count(case when SOD.GenderID=1 then 1 end) as Male,
		--	-- count(case when SOD.GenderID=2 then 1 end) as Female
  
		--	--   --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
		--	--   --SM.DivisionId
		--	--   --COUNT(SM.AcademicId) AS TotalStudent
			
		--	--	FROM sAttendance.tStudentRegister SM 
		--	--	INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
		--	--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		--	--	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		--	--	INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
		--	--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
		--	--	INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--	--	INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
		--	--    where OM.Id=1101
		--	--	--GROUP BY OGM.Id , OGM.Title
		--	--	GROUP BY DM.ID,DM.Code
			
			
		--	--Change After Disucssion
			
			
		--	select ID,Code,Count(StudentID) TotalCount,count(case when GenderID=1 then 1 end) as Male,count(case when GenderID=2 then 1 end) as Female from (SELECT 
		--		 ROW_NUMBER() OVER ( PARTITION BY A.StudentID,A.DivisionID ORDER BY A.StudentID DESC) as rowno,
		--		 A.StudentID,DM.ID,DM.Code,SOD.GenderID
		--		 --DM.ID,DM.Code,COUNT(A.StudentID) AS TotalStudent,
		--		 --count(case when SOD.GenderID=1 then 1 end) as Male,
		--		 --count(case when SOD.GenderID=2 then 1 end) as Female
  
		--	   --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
		--	   --SM.DivisionId
		--	   --COUNT(SM.AcademicId) AS TotalStudent
			
		--		FROM sAttendance.tStudentRegister SM 
		--		INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
		--		INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--		INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
		--	    where OM.Id=1101
		--	    and SM.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--	    ) AS Temp 
		--	    where rowno=1
		--	    GROUP BY ID,Code
			
			
			
			
		--	--Present Student Details for ORG Group
			
		--	select 
		--		 DM.ID,DM.Code,COUNT(AE.StudentID) AS TotalStudent,
		--		 count(case when SOD.GenderID=1 then 1 end) as Male,
		--		 count(case when SOD.GenderID=2 then 1 end) as Female
				 
		--		  from sAttendance.tStudentRegister SME 
		--			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		--			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
		--			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		--			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		--			INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
		--		    INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
		--		    INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					
		--			where OGME.Id=1101 and SME.IsPresent=1 
		--			--and SME.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--			 GROUP BY DM.ID,DM.Code
					 
					 
					 
		--		--Present Student Details for ORG 
			
		--	  select 
		--		 DM.ID,DM.Code,COUNT(AE.StudentID) AS TotalStudent,
		--		 count(case when SOD.GenderID=1 then 1 end) as Male,
		--		 count(case when SOD.GenderID=2 then 1 end) as Female
				 
		--		  from sAttendance.tStudentRegister SME 
		--			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		--			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
		--			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		--			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		--			INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
		--		    INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
		--		    INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					
		--			where OME.Id=1101 and SME.IsPresent=1 
		--			and SME.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--			 GROUP BY DM.ID,DM.Code
					 
					 
					 
					 
		--			 ----Absent Student Details for ORG Group
					 
		--			 (select 
		--			 DM.ID,DM.Code,COUNT(AE.StudentID) AS TotalStudent,
		--			 count(case when SOD.GenderID=1 then 1 end) as Male,
		--			 count(case when SOD.GenderID=2 then 1 end) as Female
					 
					
		--			 from sAttendance.tStudentRegister SME 
		--			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		--			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
		--			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		--			INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
		--			INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
		--			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
		--			INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
		--			where OGMEA.Id=1101 and SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--			GROUP BY DM.ID,DM.Code
	 
		--			)
		--			--as AbsentStudent,
					
					
		--			 ----Absent Student Details for ORG
					 
					 
		--			  (select 
		--			 DM.ID,DM.Code,COUNT(AE.StudentID) AS TotalStudent,
		--			 count(case when SOD.GenderID=1 then 1 end) as Male,
		--			 count(case when SOD.GenderID=2 then 1 end) as Female
					 
					
		--			 from sAttendance.tStudentRegister SME 
		--			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		--			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
		--			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		--			INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
		--			INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
		--			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
		--			INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
		--			where OME.Id=1101 and SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--			GROUP BY DM.ID,DM.Code
	 
		--			)
					
					
					
					
		--			--Less Than Student Details According To ORG Group
					
					
		--			(select * from  (
		--				select 
		--				--(SMEL.AcademicId) AcademicID,
		--				--count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
		--				DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
		--				,
		--				(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
		--				from sAttendance.tStudentRegister SMEL
		--				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
		--				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
		--				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--		  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		--				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
		--				where OGMEL.Id=1101 AND
		--				--SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--				SMEL.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				--and AcademicId=1101000002249
		--				--group by AEL.ID
		--				GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
		--				HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) < 70) as Temp
		--				) 
				
					
		--			 ---------------
					 
					 
					 
		--			 --Less Than Student Details According To ORG
					 
					 
		--			 (select * from  (
		--				select 
		--				--(SMEL.AcademicId) AcademicID,
		--				--count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
		--				DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
		--				,
		--				(SC.PresentContactNo) AS ContactNo,OMEL.Title
		--				from sAttendance.tStudentRegister SMEL
		--				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
		--				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
		--				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--		  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		--				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
		--				where OMEL.Id=1101 AND
		--				--SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--				SMEL.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				--and AcademicId=1101000002249
		--				--group by AEL.ID
		--				GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
		--				HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) < 70) as Temp
		--				) 
				
				
				
				
		--		--100 Per Student Details According To ORG Group
					
					
		--			(select * from  (
		--				select 
		--				--(SMEL.AcademicId) AcademicID,
		--				--count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
		--				DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
		--				,
		--				(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
		--				from sAttendance.tStudentRegister SMEL
		--				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
		--				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
		--				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--		  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		--				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
		--				where OGMEL.Id=1101 AND
		--				--SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--				SMEL.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				--and AcademicId=1101000002249
		--				--group by AEL.ID
		--				GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
		--				HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) = 100) as Temp
		--				) 
				
					
		--			 ---------------
					 
					 
					 
		--			 --Less Than Student Details According To ORG
					 
					 
		--			 (select * from  (
		--				select 
		--				--(SMEL.AcademicId) AcademicID,
		--				--count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
		--				DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
		--				,
		--				(SC.PresentContactNo) AS ContactNo,OMEL.Title
		--				from sAttendance.tStudentRegister SMEL
		--				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
		--				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
		--				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--		  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		--				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
		--				where OMEL.Id=1101 AND
		--				--SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--				SMEL.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				--and AcademicId=1101000002249
		--				--group by AEL.ID
		--				GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
		--				HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) = 100) as Temp
		--				) 
						
						
		--				----Leave Required for ORG Group
						
						
		--				(select * from (select 
		--				--STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
		--				 --DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName from sAttendance.tStudentRegister STS
		--				 DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OGMEL.Title  
		--				 from sAttendance.tStudentRegister STS
						 
		--				 Left join sAttendance.tStudentLeaveRequest STSL ON STS.AcademicId=STSL.AcademicId
		--				 INNER JOIN sStudent.tAcademic AEL ON STS.Academicid=AEL.id
		--				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
		--				 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--				 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						 
						 
		--				 where OGMEL.Id=1101 AND
						 
		--				 --STSL.AcademicId is NOT null and STS.AttendanceDate between '2018-01-01' and '2018-01-03' --<= CONVERT(char(10), @rUptoDate,126)
		--				 STSL.AcademicId is NOT null and STS.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				 --GROUP BY STS.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
		--				 ) as a) 
						 
						 
						 
						 
						 
		--				 ----Leave Required for ORG 
						
						
		--				(select * from (select 
		--				--STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
		--				 --DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName from sAttendance.tStudentRegister STS
		--				 DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OMEL.Title 
		--				 from sAttendance.tStudentRegister STS
						 
		--				 Left join sAttendance.tStudentLeaveRequest STSL ON STS.AcademicId=STSL.AcademicId
		--				 INNER JOIN sStudent.tAcademic AEL ON STS.Academicid=AEL.id
		--				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
		--				 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--				 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						 
						 
		--				 where OMEL.Id=1101 AND
						 
		--				 --STSL.AcademicId is NOT null and STS.AttendanceDate between '2018-01-01' and '2018-01-03' --<= CONVERT(char(10), @rUptoDate,126)
		--				 STSL.AcademicId is NOT null and STS.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				 --GROUP BY STS.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
		--				 ) as a)
						 
						 
		--				 --Absent count consicutive last 3 days ACCORDING TO ORG group
						 
		--				  (select Code,StudentID,StudentName,Title from(
		--					 select 
		--					 ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
							 

		--					AcademicId,AttendanceDate, DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OGMEL.Title--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
		--					FROM sAttendance.tStudentRegister d 
							
		-- 						INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
		--						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
		--						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
							
							
		--					WHERE
		--					OGMEL.Id=1101 AND
		--					--Status IN('A', 'WO', 'H')
		--					IsPresent IN(0) 
		--					AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, '2018-01-03'),126)) and CONVERT(char(10), '2018-01-03',126)        
		--					--and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
		--					 and AttendanceDate between '2018-01-01' and '2018-01-03'
		--					 and IsPresent=0
		--					Group By AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName) ,OGMEL.Title
		--					) as sfsf
		--					where rowno=3) 
							
							
							
		--					--Absent count consicutive last 3 days ACCORDING TO ORG 
						 
		--				  (select Code,StudentID,StudentName,Title from(
		--					 select 
		--					 ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
							 

		--					AcademicId,AttendanceDate, DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OGMEL.Title--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
		--					FROM sAttendance.tStudentRegister d 
							
		-- 						INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
		--						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
		--						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
							
							
		--					WHERE
		--					OMEL.Id=1101 AND
		--					--Status IN('A', 'WO', 'H')
		--					IsPresent IN(0) 
		--					AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, '2018-01-03'),126)) and CONVERT(char(10), '2018-01-03',126)        
		--					--and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
		--					 and AttendanceDate between '2018-01-01' and '2018-01-03'
		--					 and IsPresent=0
		--					Group By AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName) ,OGMEL.Title
		--					) as sfsf
		--					where rowno=3) 
							
							
							
							
							
		--					--Details Section individual Division wise(For Common)--Parameter(DivisionID,GenderID)
							
							
		--					select (DM.Id) AS DivisionID,SMD.Id,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
		--					(SC.PresentContactNo) AS ContactNo
							
		--					 from sSetup.tDivisionMaster DM
		--					INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		--					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--					INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--					INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
		--					where DM.ID='100100001' order by A.StudentID
							
							
							
							
		--					--Details Section individual Division wise(For Male)--Parameter(DivisionID,GenderID)
		--						select (DM.Id) AS DivisionID,SMD.Id,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
		--						(SC.PresentContactNo) AS ContactNo
								
		--						 from sSetup.tDivisionMaster DM
		--						INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--						INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								
		--						where DM.ID='100100001' 
		--						and SOD.GenderID=1 
		--						order by A.StudentID
								
								
		--						--Details Section individual Division wise(For Female)--Parameter(DivisionID,GenderID)
		--						select (DM.Id) AS DivisionID,SMD.Id,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
		--						(SC.PresentContactNo) AS ContactNo
								
		--						 from sSetup.tDivisionMaster DM
		--						INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--						INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								
		--						where DM.ID='100100001' 
		--						and SOD.GenderID=2 
		--						order by A.StudentID








END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 1,'2019-02-12'


--Exec [sAttendance].[pStudentAttendaceDashboardGet] 21,'2018-01-03',0,1101
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 1,'2018-11-27',1101,0,0

--Exec [sAttendance].[pStudentAttendaceDashboardGet] 12,'2018-11-27',1101 --For First 3
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 14,'2018-11-27',1101 --For First Middle 3
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 18,'2018-01-03',1101 --For Attnd Not Taken
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 16,'2018-01-03',1101 --For Leave Required
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 17,'2018-01-03',1101 --For Leave Required

--Exec [sAttendance].[pStudentAttendaceDashboardGet] 11,'2018-11-27',1101 --For First 3
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 21,'2018-11-27',0,1101 --For First 3
--Exec [sAttendance].[pStudentAttendaceDashboardGet] 1110,'',100100001,0,100100001 --For First 3

--Create By MP At 05 Feb 2019
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentAttendaceDashboardGet_BackUp_14Feb2019]
	 
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDivisionId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--Comment
--@rTypeId=1 for Org Group
--@rTypeId=2 for Org
--rTypeId=11 for Org Group Nested Total Student
--rTypeId=12 for Org Group Nested Presnt Student
--rTypeId=13 for Org Group Nested Absent Student
--rTypeId=14 for Org Group Less Than 70% Student
--rTypeId=15 for Org Group Less Than 100% Student
--rTypeId=16 for Org Group Leave Required
--rTypeId=17 for Org Group Student Consicutive Last 3 Days Absent
--rTypeId=18 for Org Group Attendance Not Taken In the Class 


--rTypeId=21 for Org Group Nested Total Student
--rTypeId=22 for Org Group Nested Presnt Student
--rTypeId=23 for Org Group Nested Absent Student
--rTypeId=24 for Org Group Less Than 70% Student
--rTypeId=25 for Org Group Less Than 100% Student
--rTypeId=26 for Org Group Leave Required
--rTypeId=27 for Org Group Student Consicutive Last 3 Days Absent
--rTypeId=28 for Org Group Attendance Not Taken In the Class

---rTypeId=1110 for Org Group And ORG Both for Division Details for ALL
---rTypeId=1111 for Org Group And ORG Both for Division Details for male
---rTypeId=1112 for Org Group And ORG Both for Division Details for Female



	   
if @rTypeId=1
   BEGIN
	   
	   
	  
       --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
       --COUNT(SM.AcademicId) AS TotalStudent,
   SELECT 
    OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
       
    (select COUNT(SMT.AcademicId)
       FROM sAttendance.tStudentRegister SMT 
		 INNER JOIN sStudent.tAcademic A ON SMT.Academicid=A.id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGM.Id=OM.OrgGroupId
      
         where OGM.Id = OGMR.Id  and SMT.AttendanceDate=@rUptoDate) as Total,
       
       
       
       (select count(*) from sAttendance.tStudentRegister SME 
        INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
        where OGM.Id = OGME.Id and SME.IsPresent=1 
        and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)

        ) as PresentStudent,
       
       (select count(*) from sAttendance.tStudentRegister SME 
        INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
        where OGM.Id = OGMEA.Id and SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)) as AbsentStudent,
        
        
        
        
        
        
       
       
  --     (select count(*) from  (select AcademicId,count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage
		--from sAttendance.tStudentRegister SMEL
		--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--where OGM.Id = OGMEL.Id AND SMEL.IsPresent=1 AND
		----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		----and AcademicId=1101000002249
		--group by SMEL.AcademicId
		--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) < 70) as Temp) AS LessThen70,


      (select Count(*) AS LessThen70  from (
        select AcademicId,Count(AcademicId) Total, count(case when IsPresent=1 then 1 end) as PresentCount,

        convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100)) as Percentage

		from sAttendance.tStudentRegister SMEL
		INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		where OGM.Id = OGMEL.Id --AND AcademicID IN (9999000000775,9999000000781) 
		AND
		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		group by SMEL.AcademicId
		
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp) As LessThen70,





		--(select count(*) from  (select AcademicId,count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage
		--from sAttendance.tStudentRegister SMEL
		--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
	
		--where OGM.Id = OGMEL.Id AND SMEL.IsPresent=1 AND
		----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		----and AcademicId=1101000002249
		--group by SMEL.AcademicId
		--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) =100) as Temp) AS HundresPer,
        
        
        (select Count(*) AS HundresPer  from (
        select AcademicId,Count(AcademicId) Total, count(case when IsPresent=1 then 1 end) as PresentCount,

        convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100)) as Percentage

		from sAttendance.tStudentRegister SMEL
		INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		where OGM.Id = OGMEL.Id --AND AcademicID IN (9999000000775,9999000000781) 
		AND
		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		group by SMEL.AcademicId
		
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp) AS HundresPer,
        
        
        
        
  --     (select Count(rowno) from(
		--	select 
			    
		--		AcademicId,
		--		ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		--		StartDate   =   MIN(AttendanceDate),
		--		EndDate     =   MAX(AttendanceDate)--,
		--		--Days        =   DATEDIFF(DD, MIN(AttendanceDate), MAX(AttendanceDate)) + 1 
		--		--                - SUM((CASE WHEN IsPresent IN(0) THEN 1 ELSE 0 END))
		--	from (
		--	SELECT 
		--		AcademicId,AttendanceDate,IsPresent,
		--	DateGroup = DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
		--	FROM sAttendance.tStudentRegister  as d
			
		--	INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
		--	INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
		--	INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--	INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			
		--	WHERE
		--		--Status IN('A', 'WO', 'H')
		--		IsPresent IN(0) and OGM.Id = OGMEL.Id 
		--		--and AcademicId=AEL.Academicid
		--		--and AttendanceDate between '2018-01-01' AND '2018-01-10'
		--		and AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		--) AS GroupedDates 
		--GROUP BY 
		--	AcademicId, DateGroup
		--HAVING 
		--	SUM(CASE WHEN IsPresent IN(0) THEN 1 ELSE 0 END) >=3
		    
		--	) as FinalQuery 
		--	where rowno=1) AS AbsentCount,
			
		(select COUNT(AcademicId) from(
	     select ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,

		AcademicId,AttendanceDate--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
		FROM sAttendance.tStudentRegister d 
		
		 	INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		
        WHERE
        OGM.Id = OGMEL.Id AND
        --Status IN('A', 'WO', 'H')
        IsPresent IN(0) 
        --AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, @rUptoDate),126)) and CONVERT(char(10), @rUptoDate,126)        
        AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
        --and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
         --and AttendanceDate between '2018-01-01' and '2018-01-03'
         and IsPresent=0
        Group By AcademicId,AttendanceDate
        ) as sfsf
        where rowno=3) as AbsentCount,

	  -- (select COUNT(AcademicId) from (select STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
		 --Left join sAttendance.tStudentLeaveRequest STSL ON STS.AcademicId=STSL.AcademicId
		 --INNER JOIN sStudent.tAcademic AEL ON STS.Academicid=AEL.id
		 --INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		 --INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		 --INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		 --where OGM.Id = OGMEL.Id AND
		 
		 ----STSL.AcademicId is NOT null and STS.AttendanceDate between '2018-01-01' and '2018-01-03' --<= CONVERT(char(10), @rUptoDate,126)
		 --STSL.AcademicId is NOT null and STS.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
   --      ) as a) As LeaveRequest,
   
   
		   (select 
		Count(AcademicId) AS LeaveRequest
		From sAttendance.tStudentLeaveRequest STSL
		INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
								 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
								 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
								 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
								 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
								 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
								 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								  
		--AcademicId=1101000002534 and 
		where OGM.Id = OGMEL.Id AND
		--'2017-11-27' between LeaveFromDate AND LeaveToDate) As LeaveRequest,
		CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate) As LeaveRequest,
		  
		  
         (select Count(ClassID) from (select 
		  ClassId,
		  ATA.ID,
		   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		  from sStudent.tAcademic ATA 
		  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
			 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 where OGM.Id = OGMEL.Id 
		  
		  
		 ) As Temp 
		 where
			rowno=1 AND
			ID not in(select AcademicId from sAttendance.tStudentRegister Where
			--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
			AttendanceDate = CONVERT(char(10), @rUptoDate,126))) as AttnNotTakenClass
	 
        
         
			
	FROM sSetup.tOrgGroupMaster OGM 
	where OGM.Id<>1
	   	
    --FROM sAttendance.tStudentRegister SM 
    --INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
    --INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
    --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
    --INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
    --where AttendanceDate=CONVERT(char(10), @rUptoDate,126)--@rUptoDate
    --GROUP BY OGM.Id , OGM.Title
	
	
	END
ELSE IF @rTypeId=2
    BEGIN
		 
	   --SELECT 
    --   OM.Id AS OrgId, OM.Title AS OrgTitle,
    --   COUNT(SM.AcademicId) AS TotalStudent  ,
    
    SELECT 
    OM.Id AS OrgGroupId, OM.Title AS OrgTitle,
       
    (select COUNT(SMT.AcademicId)
       FROM sAttendance.tStudentRegister SMT 
		 INNER JOIN sStudent.tAcademic A ON SMT.Academicid=A.id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OMR ON OM.Id = BM.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
      
        -- where OGM.Id = 1101 and SMT.AttendanceDate=@rUptoDate) as Total,
         where OM.Id = OMR.Id and SMT.AttendanceDate=@rUptoDate) as Total,
         
         
       
       (select count(*) from sAttendance.tStudentRegister SME 
        INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
        where OM.Id = OME.Id and SME.IsPresent=1 
        and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)

        ) as PresentStudent,
        
        
        (select count(*) from sAttendance.tStudentRegister SME 
        INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
        where OM.Id = OME.Id and SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)) as AbsentStudent,
        
        
  --      (select count(*) from  (select AcademicId,count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage
		--from sAttendance.tStudentRegister SMEL
		--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--where OM.Id = OMEL.Id AND SMEL.IsPresent=1 AND
		----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		----and AcademicId=1101000002249
		--group by SMEL.AcademicId
		--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) < 70) as Temp) AS LessThen70,
		
		
		
		 (select Count(*) AS LessThen70  from (
        select AcademicId,Count(AcademicId) Total, count(case when IsPresent=1 then 1 end) as PresentCount,

        convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100)) as Percentage

		from sAttendance.tStudentRegister SMEL
		INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		where OM.Id = OMEL.Id --AND AcademicID IN (9999000000775,9999000000781) 
		AND
		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		group by SMEL.AcademicId
		
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp) AS LessThen70,
		
		
		--(select count(*) from  (select AcademicId,count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage
		--from sAttendance.tStudentRegister SMEL
		--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
	
		--where OM.Id = OMEL.Id AND SMEL.IsPresent=1 AND
		----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		----and AcademicId=1101000002249
		--group by SMEL.AcademicId
		--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) =100) as Temp) AS HundresPer,
		
		
		(select Count(*) AS HundresPer  from (
        select AcademicId,Count(AcademicId) Total, count(case when IsPresent=1 then 1 end) as PresentCount,

        convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100)) as Percentage

		from sAttendance.tStudentRegister SMEL
		INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		where OM.Id = OMEL.Id --AND AcademicID IN (9999000000775,9999000000781) 
		AND
		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		group by SMEL.AcademicId
		
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp) AS HundresPer,
		
		
		
		
		
		(select COUNT(AcademicId) from(
	     select ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,

		AcademicId,AttendanceDate--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
		FROM sAttendance.tStudentRegister d 
		
		 	INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		
        WHERE
        OM.Id = OMEL.Id AND
        --Status IN('A', 'WO', 'H')
        IsPresent IN(0) 
       -- AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, @rUptoDate),126)) and CONVERT(char(10), @rUptoDate,126)        
       AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
        --and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
         --and AttendanceDate between '2018-01-01' and '2018-01-03'
         and IsPresent=0
        Group By AcademicId,AttendanceDate
        ) as sfsf
        where rowno=3) as AbsentCountSecond,
        
        
   --     (select COUNT(AcademicId) from (select STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
		 --Left join sAttendance.tStudentLeaveRequest STSL ON STS.AcademicId=STSL.AcademicId
		 --INNER JOIN sStudent.tAcademic AEL ON STS.Academicid=AEL.id
		 --INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId AND BMEL.IsActive = 1
		 --INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		 --INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		 --where OM.Id = OMEL.Id AND
		 
		 ----STSL.AcademicId is NOT null and STS.AttendanceDate between '2018-01-01' and '2018-01-03' --<= CONVERT(char(10), @rUptoDate,126)
		 --STSL.AcademicId is NOT null and STS.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
   --      ) as a) As LeaveRequired,
         
         
         
          (select 
		Count(AcademicId) AS LeaveRequest
		From sAttendance.tStudentLeaveRequest STSL
		INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
								 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
								 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
								 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
								 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
								 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
								 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								  
		--AcademicId=1101000002534 and 
		where OM.Id = OMEL.Id AND
		--'2017-11-27' between LeaveFromDate AND LeaveToDate) As LeaveRequest,
		CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate) As LeaveRequest,
         
         
         
         
         (select Count(ClassID) from (select 
		  ClassId,
		  ATA.ID,
		   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		  from sStudent.tAcademic ATA 
		  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
			 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 where OM.Id = OMEL.Id 
		  
		  
		 ) As Temp 
		 where
			rowno=1 AND
			ID not in(select AcademicId from sAttendance.tStudentRegister Where
			--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
			AttendanceDate = CONVERT(char(10), @rUptoDate,126))) as AttnNotTakenClass

       
       
        FROM sSetup.tOrgGroupMaster OGMT 
        Inner join sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId 
        
        where OGMT.Id=@rOrgGroupId
        
  --      FROM sAttendance.tStudentRegister SM 
		--INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
		--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
		
		--AND SM.AttendanceDate= CONVERT(char(10), @rUptoDate,126)
		
		--where OM.OrgGroupId=@rOrgGroupId
		--GROUP BY OM.Id , OM.Title
		 
		 
		 
    END

ELSE IF @rTypeId=11

	BEGIN
        
          
     	SELECT (OGM.Title) As OrgGroupTile,DM.ID AS DivisionId,DM.Code AS DivisionCode,COUNT(A.StudentID) AS TotalStudents,
			 count(case when SOD.GenderID=1 then 1 end) as Male,
			 count(case when SOD.GenderID=2 then 1 end) as Female
  
			   --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
			   --SM.DivisionId
			   --COUNT(SM.AcademicId) AS TotalStudent
			
				FROM sAttendance.tStudentRegister SM 
				INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
				INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
			    --where OGM.Id=1101
			    where OGM.Id=@rOrgGroupId
			    AND SM.AttendanceDate<=CONVERT(char(10), @rUptoDate,126)--@rUptoDate
			   
			    
				--GROUP BY OGM.Id , OGM.Title
				GROUP BY OGM.Title,DM.ID,DM.Code
     
     
    END
    
ELSE IF @rTypeId=21
    BEGIN
         --select 1
         SELECT OM.Title As OrgTitle,DM.ID As DivisionId,DM.Code As DivisionCode,COUNT(A.StudentID) AS TotalStudent,
			 count(case when SOD.GenderID=1 then 1 end) as Male,
			 count(case when SOD.GenderID=2 then 1 end) as Female
  
			   --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
			   --SM.DivisionId
			   --COUNT(SM.AcademicId) AS TotalStudent
			
				FROM sAttendance.tStudentRegister SM 
				INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
				INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
			    where OM.Id=@rOrgId
			     AND SM.AttendanceDate<=CONVERT(char(10), @rUptoDate,126)--@rUptoDate
			    --where OM.Id=@rOrgId
			   
			    
				--GROUP BY OGM.Id , OGM.Title
				GROUP BY OM.Title,DM.ID,DM.Code
       
       
     END
    
    

ELSE IF @rTypeId=12
    
    BEGIN
         
         select 
				 OGME.Title As OrgGroupTitle,DM.ID As DivisionId,DM.Code As DivisionCode,COUNT(AE.StudentID) AS TotalStudent,
				 count(case when SOD.GenderID=1 then 1 end) as Male,
				 count(case when SOD.GenderID=2 then 1 end) as Female
				 
				  from sAttendance.tStudentRegister SME 
					INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
					INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
					INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
				    INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				    INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					
					where OGME.Id=@rOrgGroupId and SME.IsPresent=1 
					and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
					 GROUP BY OGME.Title,DM.ID,DM.Code
         
    END
   
ELSE IF @rTypeId=22
	BEGIN
     
      select 
				 OME.Title As OrgTitle,DM.ID As DivisionId,DM.Code As DivisionCode,COUNT(AE.StudentID) AS TotalStudent,
				 count(case when SOD.GenderID=1 then 1 end) as Male,
				 count(case when SOD.GenderID=2 then 1 end) as Female
				 
				  from sAttendance.tStudentRegister SME 
					INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
					INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
					INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
				    INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				    INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					
					where OME.Id=@rOrgId and SME.IsPresent=1 
					and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
					 GROUP BY OME.Title,DM.ID,DM.Code
     
     
	END
   
   
ELSE IF @rTypeId=13
      BEGIN
      
          (select 
					 OGMEA.Title As OrgGroupTitle,DM.ID As DivisionId,DM.Code As DivisionCode,COUNT(AE.StudentID) AS TotalStudent,
					 count(case when SOD.GenderID=1 then 1 end) as Male,
					 count(case when SOD.GenderID=2 then 1 end) as Female
					 
					
					 from sAttendance.tStudentRegister SME 
					INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
					INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
					INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
					INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					where OGMEA.Id=@rOrgGroupId and SME.IsPresent=0 
					and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEA.Title,DM.ID,DM.Code
	 
					)
    
       END
       
ELSE IF @rTypeId=23
       BEGIN
          --SELECT 23
          (select 
					 OGMEA.Title As OrgTitle,DM.ID As DivisionId,DM.Code As DivisionCode,COUNT(AE.StudentID) AS TotalStudent,
					 count(case when SOD.GenderID=1 then 1 end) as Male,
					 count(case when SOD.GenderID=2 then 1 end) as Female
					 
					
					 from sAttendance.tStudentRegister SME 
					INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
					INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
					INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
					INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					where OME.Id=@rOrgId 
					and SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEA.Title,DM.ID,DM.Code
	 
					)
    
       END       
       
ELSE IF @rTypeId=14
   
      BEGIN
          
      --    (select * from  (
						--select 
						----(SMEL.AcademicId) AcademicID,
						----count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
						--DM.Code,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						--,
						--(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
						--from sAttendance.tStudentRegister SMEL
						--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						--INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						----INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  ----      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						--INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						----INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						--INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
						--where OGMEL.Id=@rOrgGroupId AND
						----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
						--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						
						----and AcademicId=1101000002249
						----group by AEL.ID
						--GROUP BY SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
						--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) =100) as Temp
						--) 
						
						
						
						
  (select *from  (
        select  
         OGMEL.Title As OrgGroupTitle ,DM.Code As DivisionCode,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						,
						(SC.PresentContactNo) AS ContactNo
						from sAttendance.tStudentRegister SMEL
						INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	     
	     
		--where OGMEL.Id=1101 --AND AcademicID IN (9999000000775,9999000000781) 
		where OGMEL.Id=@rOrgGroupId AND

		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGMEL.Title ,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo)
		
		
	   HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	   ) AS Tmp) 
		
						
						
						
						
          
          
      END
   
ELSE IF @rTypeId=24
     
      BEGIN
          
      --    (select * from  (
						--select 
						----(SMEL.AcademicId) AcademicID,
						----count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
						--DM.Code,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						--,
						--(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
						--from sAttendance.tStudentRegister SMEL
						--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						--INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						----INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  ----      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						--INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						----INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						--INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
						--where OMEL.Id=@rOrgId AND
						----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
						--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						
						----and AcademicId=1101000002249
						----group by AEL.ID
						--GROUP BY SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
						--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) =100) as Temp
						--) 
          
          
          (select *from  (
            select  
            OGMEL.Title As OrgTitle ,DM.Code As DivisionCode,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						,
						(SC.PresentContactNo) AS ContactNo
						from sAttendance.tStudentRegister SMEL
						INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	     
	     
		--where OGMEL.Id=1101 --AND AcademicID IN (9999000000775,9999000000781) 
		where OMEL.Id=@rOrgId AND

		--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
		SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGMEL.Title ,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo)
		
		
	   HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	   ) AS Tmp) 
		
          
          
          
          
          
      END   
   
ELSE IF @rTypeId=15
   
	   BEGIN
	   
	     -- (select * from  (
						--select 
						----(SMEL.AcademicId) AcademicID,
						----count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
						--DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						--,
						--(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
						--from sAttendance.tStudentRegister SMEL
						--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						--INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						----INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  ----      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						--INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						----INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						--INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
						--where OGMEL.Id=@rOrgGroupId AND
						----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
						--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						
						----and AcademicId=1101000002249
						----group by AEL.ID
						--GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
						--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) = 100) as Temp
						--)
						
						
						
						(select *from  (
                          select  
                            OGMEL.Title As OrgGroupTitle ,DM.Code As DivisionCode,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						,
						(SC.PresentContactNo) AS ContactNo
						from sAttendance.tStudentRegister SMEL
						INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	     
	     
		--where OGMEL.Id=1101 --AND AcademicID IN (9999000000775,9999000000781) 
					where OGMEL.Id=@rOrgGroupId AND

					--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
					SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEL.Title ,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo)
		
		
	                HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	           ) AS Tmp) 
		
	        
	   
	   END
	   
ELSE IF @rTypeId=25
   
	   BEGIN
	   
	     -- (select * from  (
						--select 
						----(SMEL.AcademicId) AcademicID,
						----count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
						--DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						--,
						--(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
						--from sAttendance.tStudentRegister SMEL
						--INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						--INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						--INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						--INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						--INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						----INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  ----      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						--INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						----INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						--INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
						--where OMEL.Id=@rOrgId AND
						----SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
						
						--SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						----and AcademicId=1101000002249
						----group by AEL.ID
						--GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
						--HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) = 100) as Temp
						--)
						
						
						
						(select *from  (
                          select  
                            OMEL.Title As OrgTitle,DM.Code As DivisionCode,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
						,
						(SC.PresentContactNo) AS ContactNo
						from sAttendance.tStudentRegister SMEL
						INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	     
	     
		--where OGMEL.Id=1101 --AND AcademicID IN (9999000000775,9999000000781) 
					where OMEL.Id=@rOrgId AND

					--SMEL.AttendanceDate <= CONVERT(char(10), '02/12/2019',126)
					SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY OMEL.Title  ,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo)
		
		
	                HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	           ) AS Tmp) 
	        
	   
	   END
	   
	   
ELSE IF @rTypeId=16
   
   BEGIN
        
        (select * from (select 
						--STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
						 --DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName from sAttendance.tStudentRegister STS
						 OGMEL.Title As OrgGroupTitle  ,DM.Code As DivisionCode,(SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
						 (SC.PresentContactNo) AS ContactNo
						 
						 from sAttendance.tStudentLeaveRequest STSL --ON STS.AcademicId=STSL.AcademicId
						 INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						 
						
						 --where OGMEL.Id=1101 AND
						 where OGMEL.Id=@rOrgGroupId AND
						 CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
						 --'2017-11-27' between LeaveFromDate AND LeaveToDate 
						 --STSL.AcademicId is NOT null and STS.AttendanceDate between '2018-01-01' and '2018-01-03' --<= CONVERT(char(10), @rUptoDate,126)
						
						 
						 --GROUP BY STS.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
						 ) as a) 
        
        
   END
   
   
ELSE IF @rTypeId=26
   
   BEGIN
      
        (select * from (select 
						--STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
						 --DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName from sAttendance.tStudentRegister STS
						 OGMEL.Title As OrgTitle,DM.Code As DivisionCode,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName 
						 from sAttendance.tStudentLeaveRequest STSL --ON STS.AcademicId=STSL.AcademicId
						 INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
						 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						 
						 
						 where OMEL.Id=@rOrgId AND
						  CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
						  --'2017-11-27' between LeaveFromDate AND LeaveToDate 
						 
						
						 --GROUP BY STS.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
						 ) as a) 
        
        
   END
   
ELSE IF @rTypeId=17
   
   BEGIN
       
        (select Title As OrgGroupTitle,Code As DivisionCode,StudentID,StudentName from(
							 select 
							 ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
							 

							AcademicId,AttendanceDate, DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OGMEL.Title--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
							FROM sAttendance.tStudentRegister d 
							
		 						INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
								INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
								INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
								INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
								INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
								INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
								INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
							
							
							WHERE
							OGMEL.Id=@rOrgGroupId AND
							--Status IN('A', 'WO', 'H')
							IsPresent IN(0) 
							--AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, @rUptoDate),126)) and CONVERT(char(10), @rUptoDate,126)
							AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate   
							--and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
							 and AttendanceDate between '2018-01-01' and '2018-01-03'
							 and IsPresent=0
							Group By OGMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName) 
							) as sfsf
							where rowno=3) 
        
   END
   
   
ELSE IF @rTypeId=27
   
   BEGIN
       
        (select Title As OrgTitle, Code As DivisionCode,StudentID,StudentName from(
							 select 
							 ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
							 

							AcademicId,AttendanceDate, DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OGMEL.Title--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
							FROM sAttendance.tStudentRegister d 
							
		 						INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
								INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
								INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
								INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
								INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
								INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
								INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
							
							
							WHERE
							OMEL.Id=@rOrgId AND
							--Status IN('A', 'WO', 'H')
							IsPresent IN(0) 
							--AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, '2018-01-03'),126)) and CONVERT(char(10), '2018-01-03',126)        
							AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
							--and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
							 --and AttendanceDate between '2018-01-01' and '2018-01-03'
							 --AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, @rUptoDate),126)) and CONVERT(char(10), @rUptoDate,126)
							 and IsPresent=0
							Group By OGMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName) 
							) as sfsf
							where rowno=3) 
        
   END
   
ELSE IF @rTypeId=18
   
   BEGIN
       
       (select 
         Temp.Title As OrgGroupTitle,
         DM.Code As DivisionCode,
         (EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.PresentContactNo) AS ContactNo  from (
         select OGMEL.Title,
		  ClassId,
		  ATA.ID,
		   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		  from sStudent.tAcademic ATA 
		  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
			 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId --lAND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 where OGMEL.Id =@rOrgGroupId
		  
		  
		 ) As Temp 
		  LEFT JOIN sSetup.tClassMaster CM ON CM.Id=Temp.ClassID
		  LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassID=CM.Id
		  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
		  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		 
		 where
			rowno=1 AND
			   --AND ClassID=110100001 			  
			Temp.ID not in(select AcademicId from sAttendance.tStudentRegister Where
			--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
			AttendanceDate = CONVERT(char(10), @rUptoDate,126) 
			
			)
			
			) 
       
   END
   
   
ELSE IF @rTypeId=28
   
   BEGIN
       
       (select 
         Temp.Title As OrgTitle,
         DM.Code As DivisionCode,
         (EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.PresentContactNo) AS ContactNo  from (
         select OGMEL.Title,
		  ClassId,
		  ATA.ID,
		   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		  from sStudent.tAcademic ATA 
		  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
			 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId --lAND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 where OMEL.Id =@rOrgId
		  
		  
		 ) As Temp 
		  LEFT JOIN sSetup.tClassMaster CM ON CM.Id=Temp.ClassID
		  LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassID=CM.Id
		  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
		  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		 
		 where
			rowno=1 AND
			   --AND ClassID=110100001 			  
			Temp.ID not in(select AcademicId from sAttendance.tStudentRegister Where
			--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
			AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			 
			--AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			
			)
			
			) 
       
   END

ELSE IF @rTypeId=1110
   
   BEGIN
   --SELECT 1
     
     --Details Section individual Division wise(For Common)--Parameter(DivisionID,GenderID)
	
							select (DM.Id) AS DivisionId,SMD.Id As StudentId,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
							(SC.PresentContactNo) AS ContactNo
							
							 from sSetup.tDivisionMaster DM
							INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
							INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
							INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
							INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
							--where DM.ID='100100001' order by A.StudentID
							where DM.ID=@rDivisionId order by A.StudentID
							
     
     
   END

ELSE IF @rTypeId=1111

	BEGIN
      --SELECT 1
      select (DM.Id) AS DivisionId,SMD.Id As StudentId,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
								(SC.PresentContactNo) AS ContactNo
								
								 from sSetup.tDivisionMaster DM
								INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
								INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
								INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
								INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								
								--where DM.ID='100100001'
								where DM.ID=@rDivisionId 
								and SOD.GenderID=1 
								order by A.StudentID
      
      
	END
ELSE IF @rTypeId=1112
	BEGIN
	  
	  select (DM.Id) AS DivisionId,SMD.Id As StudentId,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
								(SC.PresentContactNo) AS ContactNo
								
								 from sSetup.tDivisionMaster DM
								INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
								INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
								INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
								INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								
								--where DM.ID='100100001' 
								where DM.ID=@rDivisionId 
								and SOD.GenderID=2 
								order by A.StudentID
	  
	   
	END


--END




-------------------------------------------------------------------------------------------------------------------------------




      -----------Attnd Not Taken For Org Group
      
  --       (select 
  --       Temp.Title,
  --       DM.Code,
  --       (EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.PresentContactNo) AS ContactNo  from (
  --       select OGMEL.Title,
		--  ClassId,
		--  ATA.ID,
		--   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		--  from sStudent.tAcademic ATA 
		--  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
		--	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId --lAND BMEL.IsActive = 1
		--	 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--	 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--	 where OGMEL.Id =1101
		  
		  
		-- ) As Temp 
		--  LEFT JOIN sSetup.tClassMaster CM ON CM.Id=Temp.ClassID
		--  LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassID=CM.Id
		--  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		 
		-- where
		--	rowno=1 AND
		--	   --AND ClassID=110100001 			  
		--	Temp.ID not in(select AcademicId from sAttendance.tStudentRegister Where
		--	--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
		--	AttendanceDate = CONVERT(char(10), '2018-01-03',126) 
		--	)
			
		--	) 
			
		--	------------------------------Attnd Not Taken For Org
			
			
		--	       (select 
  --       Temp.Title,
  --       DM.Code,
  --       (EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.PresentContactNo) AS ContactNo  from (
  --       select OMEL.Title,
		--  ClassId,
		--  ATA.ID,
		--   ROW_NUMBER() OVER ( PARTITION BY ATA.ClassId order by AcademicID) as rowno--,SM.AttendanceDate 
		--  from sStudent.tAcademic ATA 
		--  Left join sAttendance.tStudentRegister SM ON ATA.Id=SM.AcademicID
		  
		--	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = ATA.BatchId --lAND BMEL.IsActive = 1
		--	 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--	 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--	 where OMEL.Id =1101
		  
		  
		-- ) As Temp 
		--  LEFT JOIN sSetup.tClassMaster CM ON CM.Id=Temp.ClassID
		--  LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassID=CM.Id
		--  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		 
		-- where
		--	rowno=1 AND
		--	   --AND ClassID=110100001 			  
		--	Temp.ID not in(select AcademicId from sAttendance.tStudentRegister Where
		--	--AttendanceDate Between '2017-01-02' AND '2017-01-10')) as AttnNotTakenClass
		--	AttendanceDate = CONVERT(char(10), '2018-01-03',126) 
		--	)
			
		--	) 
			
		--	--as AttnNotTakenClass  
			
			
			
			
			
			
		-----------------------
		
		
		----------------------Total Student Details for ORG Group
		--	 --SELECT DM.ID,DM.Code,COUNT(A.StudentID) AS TotalStudent,
		--	 --count(case when SOD.GenderID=1 then 1 end) as Male,
		--	 --count(case when SOD.GenderID=2 then 1 end) as Female
  
		--	 --  --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
		--	 --  --SM.DivisionId
		--	 --  --COUNT(SM.AcademicId) AS TotalStudent
			
		--		--FROM sAttendance.tStudentRegister SM 
		--		--INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
		--		--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		--		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		--		--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
		--		--INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
		--		--INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--		--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
		--	 --   where OGM.Id=1101
		--		----GROUP BY OGM.Id , OGM.Title
		--		--GROUP BY DM.ID,DM.Code
			
			
		--	--Change after disucssion
			
		--	select ID,Code,Count(StudentID) TotalCount,count(case when GenderID=1 then 1 end) as Male,count(case when GenderID=2 then 1 end) as Female from (SELECT 
		--		 ROW_NUMBER() OVER ( PARTITION BY A.StudentID,A.DivisionID ORDER BY A.StudentID DESC) as rowno,
		--		 A.StudentID,DM.ID,DM.Code,SOD.GenderID
		--		 --DM.ID,DM.Code,COUNT(A.StudentID) AS TotalStudent,
		--		 --count(case when SOD.GenderID=1 then 1 end) as Male,
		--		 --count(case when SOD.GenderID=2 then 1 end) as Female
  
		--	   --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
		--	   --SM.DivisionId
		--	   --COUNT(SM.AcademicId) AS TotalStudent
			
		--		FROM sAttendance.tStudentRegister SM 
		--		INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
		--		INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--		INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
		--	    where OGM.Id=1101
		--	    --and SM.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--	    ) AS Temp 
		--	    where rowno=1
		--	    GROUP BY ID,Code
			
			
			
		----------------------Total Student Details for ORG 
		
		-- --SELECT DM.ID,DM.Code,COUNT(A.StudentID) AS TotalStudent,
		--	-- count(case when SOD.GenderID=1 then 1 end) as Male,
		--	-- count(case when SOD.GenderID=2 then 1 end) as Female
  
		--	--   --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
		--	--   --SM.DivisionId
		--	--   --COUNT(SM.AcademicId) AS TotalStudent
			
		--	--	FROM sAttendance.tStudentRegister SM 
		--	--	INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
		--	--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		--	--	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		--	--	INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
		--	--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
		--	--	INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--	--	INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
		--	--    where OM.Id=1101
		--	--	--GROUP BY OGM.Id , OGM.Title
		--	--	GROUP BY DM.ID,DM.Code
			
			
		--	--Change After Disucssion
			
			
		--	select ID,Code,Count(StudentID) TotalCount,count(case when GenderID=1 then 1 end) as Male,count(case when GenderID=2 then 1 end) as Female from (SELECT 
		--		 ROW_NUMBER() OVER ( PARTITION BY A.StudentID,A.DivisionID ORDER BY A.StudentID DESC) as rowno,
		--		 A.StudentID,DM.ID,DM.Code,SOD.GenderID
		--		 --DM.ID,DM.Code,COUNT(A.StudentID) AS TotalStudent,
		--		 --count(case when SOD.GenderID=1 then 1 end) as Male,
		--		 --count(case when SOD.GenderID=2 then 1 end) as Female
  
		--	   --OGM.Id AS OrgGroupId, OGM.Title AS OrgTitle,
		--	   --SM.DivisionId
		--	   --COUNT(SM.AcademicId) AS TotalStudent
			
		--		FROM sAttendance.tStudentRegister SM 
		--		INNER JOIN sStudent.tAcademic A ON SM.Academicid=A.id
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1
		--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
		--		INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--		INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				
		--	    where OM.Id=1101
		--	    and SM.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--	    ) AS Temp 
		--	    where rowno=1
		--	    GROUP BY ID,Code
			
			
			
			
		--	--Present Student Details for ORG Group
			
		--	select 
		--		 DM.ID,DM.Code,COUNT(AE.StudentID) AS TotalStudent,
		--		 count(case when SOD.GenderID=1 then 1 end) as Male,
		--		 count(case when SOD.GenderID=2 then 1 end) as Female
				 
		--		  from sAttendance.tStudentRegister SME 
		--			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		--			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId AND BME.IsActive = 1
		--			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		--			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		--			INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
		--		    INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
		--		    INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					
		--			where OGME.Id=1101 and SME.IsPresent=1 
		--			--and SME.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--			 GROUP BY DM.ID,DM.Code
					 
					 
					 
		--		--Present Student Details for ORG 
			
		--	  select 
		--		 DM.ID,DM.Code,COUNT(AE.StudentID) AS TotalStudent,
		--		 count(case when SOD.GenderID=1 then 1 end) as Male,
		--		 count(case when SOD.GenderID=2 then 1 end) as Female
				 
		--		  from sAttendance.tStudentRegister SME 
		--			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		--			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
		--			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		--			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		--			INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
		--		    INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
		--		    INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
					
		--			where OME.Id=1101 and SME.IsPresent=1 
		--			and SME.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--			 GROUP BY DM.ID,DM.Code
					 
					 
					 
					 
		--			 ----Absent Student Details for ORG Group
					 
		--			 (select 
		--			 DM.ID,DM.Code,COUNT(AE.StudentID) AS TotalStudent,
		--			 count(case when SOD.GenderID=1 then 1 end) as Male,
		--			 count(case when SOD.GenderID=2 then 1 end) as Female
					 
					
		--			 from sAttendance.tStudentRegister SME 
		--			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		--			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
		--			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		--			INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
		--			INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
		--			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
		--			INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
		--			where OGMEA.Id=1101 and SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--			GROUP BY DM.ID,DM.Code
	 
		--			)
		--			--as AbsentStudent,
					
					
		--			 ----Absent Student Details for ORG
					 
					 
		--			  (select 
		--			 DM.ID,DM.Code,COUNT(AE.StudentID) AS TotalStudent,
		--			 count(case when SOD.GenderID=1 then 1 end) as Male,
		--			 count(case when SOD.GenderID=2 then 1 end) as Female
					 
					
		--			 from sAttendance.tStudentRegister SME 
		--			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
		--			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
		--			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		--			INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
		--			INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
		--			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
		--			INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
					
		--			where OME.Id=1101 and SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), '2018-01-03',126)
		--			GROUP BY DM.ID,DM.Code
	 
		--			)
					
					
					
					
		--			--Less Than Student Details According To ORG Group
					
					
		--			(select * from  (
		--				select 
		--				--(SMEL.AcademicId) AcademicID,
		--				--count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
		--				DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
		--				,
		--				(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
		--				from sAttendance.tStudentRegister SMEL
		--				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
		--				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
		--				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--		  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		--				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
		--				where OGMEL.Id=1101 AND
		--				--SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--				SMEL.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				--and AcademicId=1101000002249
		--				--group by AEL.ID
		--				GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
		--				HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) < 70) as Temp
		--				) 
				
					
		--			 ---------------
					 
					 
					 
		--			 --Less Than Student Details According To ORG
					 
					 
		--			 (select * from  (
		--				select 
		--				--(SMEL.AcademicId) AcademicID,
		--				--count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
		--				DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
		--				,
		--				(SC.PresentContactNo) AS ContactNo,OMEL.Title
		--				from sAttendance.tStudentRegister SMEL
		--				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
		--				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
		--				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--		  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		--				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
		--				where OMEL.Id=1101 AND
		--				--SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--				SMEL.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				--and AcademicId=1101000002249
		--				--group by AEL.ID
		--				GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
		--				HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) < 70) as Temp
		--				) 
				
				
				
				
		--		--100 Per Student Details According To ORG Group
					
					
		--			(select * from  (
		--				select 
		--				--(SMEL.AcademicId) AcademicID,
		--				--count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
		--				DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
		--				,
		--				(SC.PresentContactNo) AS ContactNo,OGMEL.Title 
		--				from sAttendance.tStudentRegister SMEL
		--				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
		--				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
		--				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--		  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		--				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
		--				where OGMEL.Id=1101 AND
		--				--SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--				SMEL.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				--and AcademicId=1101000002249
		--				--group by AEL.ID
		--				GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OGMEL.Title 
		--				HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) = 100) as Temp
		--				) 
				
					
		--			 ---------------
					 
					 
					 
		--			 --Less Than Student Details According To ORG
					 
					 
		--			 (select * from  (
		--				select 
		--				--(SMEL.AcademicId) AcademicID,
		--				--count(IsPresent) as Presentcout,count(AcademicId) as TotalCount,((count(IsPresent)/count(AcademicId))*100) AS Percentage,
		--				DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName
		--				,
		--				(SC.PresentContactNo) AS ContactNo,OMEL.Title
		--				from sAttendance.tStudentRegister SMEL
		--				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
		--				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
		--				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						
		--				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				--INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
		--		  --      INNER JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		--				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				--INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						
		--				where OMEL.Id=1101 AND
		--				--SMEL.AttendanceDate between '2018-11-01' AND '2018-12-12' 
		--				SMEL.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				--and AcademicId=1101000002249
		--				--group by AEL.ID
		--				GROUP BY SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
		--				HAVING (((count(SMEL.IsPresent)/count(SMEL.AcademicId))*100)) = 100) as Temp
		--				) 
						
						
		--				----Leave Required for ORG Group
						
						
		--				(select * from (select 
		--				--STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
		--				 --DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName from sAttendance.tStudentRegister STS
		--				 DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OGMEL.Title  
		--				 from sAttendance.tStudentRegister STS
						 
		--				 Left join sAttendance.tStudentLeaveRequest STSL ON STS.AcademicId=STSL.AcademicId
		--				 INNER JOIN sStudent.tAcademic AEL ON STS.Academicid=AEL.id
		--				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
		--				 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--				 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						 
						 
		--				 where OGMEL.Id=1101 AND
						 
		--				 --STSL.AcademicId is NOT null and STS.AttendanceDate between '2018-01-01' and '2018-01-03' --<= CONVERT(char(10), @rUptoDate,126)
		--				 STSL.AcademicId is NOT null and STS.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				 --GROUP BY STS.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
		--				 ) as a) 
						 
						 
						 
						 
						 
		--				 ----Leave Required for ORG 
						
						
		--				(select * from (select 
		--				--STSL.AcademicId,STS.AttendanceDate from sAttendance.tStudentRegister STS
		--				 --DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName from sAttendance.tStudentRegister STS
		--				 DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OMEL.Title 
		--				 from sAttendance.tStudentRegister STS
						 
		--				 Left join sAttendance.tStudentLeaveRequest STSL ON STS.AcademicId=STSL.AcademicId
		--				 INNER JOIN sStudent.tAcademic AEL ON STS.Academicid=AEL.id
		--				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
		--				 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--				 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--				 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--				 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--				 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
						 
						 
		--				 where OMEL.Id=1101 AND
						 
		--				 --STSL.AcademicId is NOT null and STS.AttendanceDate between '2018-01-01' and '2018-01-03' --<= CONVERT(char(10), @rUptoDate,126)
		--				 STSL.AcademicId is NOT null and STS.AttendanceDate <= CONVERT(char(10), '2018-01-03',126)
		--				 --GROUP BY STS.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.PresentContactNo),OMEL.Title 
		--				 ) as a)
						 
						 
		--				 --Absent count consicutive last 3 days ACCORDING TO ORG group
						 
		--				  (select Code,StudentID,StudentName,Title from(
		--					 select 
		--					 ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
							 

		--					AcademicId,AttendanceDate, DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OGMEL.Title--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
		--					FROM sAttendance.tStudentRegister d 
							
		-- 						INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
		--						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
		--						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
							
							
		--					WHERE
		--					OGMEL.Id=1101 AND
		--					--Status IN('A', 'WO', 'H')
		--					IsPresent IN(0) 
		--					AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, '2018-01-03'),126)) and CONVERT(char(10), '2018-01-03',126)        
		--					--and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
		--					 and AttendanceDate between '2018-01-01' and '2018-01-03'
		--					 and IsPresent=0
		--					Group By AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName) ,OGMEL.Title
		--					) as sfsf
		--					where rowno=3) 
							
							
							
		--					--Absent count consicutive last 3 days ACCORDING TO ORG 
						 
		--				  (select Code,StudentID,StudentName,Title from(
		--					 select 
		--					 ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
							 

		--					AcademicId,AttendanceDate, DM.Code,(SMD.Code)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,OGMEL.Title--DATEADD(DD, - ROW_NUMBER() OVER (PARTITION BY AcademicId ORDER BY AttendanceDate), AttendanceDate)
		--					FROM sAttendance.tStudentRegister d 
							
		-- 						INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
		--						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --lAND BMEL.IsActive = 1
		--						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		--						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		--						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
		--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
		--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
							
							
		--					WHERE
		--					OMEL.Id=1101 AND
		--					--Status IN('A', 'WO', 'H')
		--					IsPresent IN(0) 
		--					AND AttendanceDate between (CONVERT(char(10), DATEADD(DAY, -3, '2018-01-03'),126)) and CONVERT(char(10), '2018-01-03',126)        
		--					--and AttendanceDate between GETDATE() and DATEADD(DAY, -2, GETDATE())
		--					 and AttendanceDate between '2018-01-01' and '2018-01-03'
		--					 and IsPresent=0
		--					Group By AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName) ,OGMEL.Title
		--					) as sfsf
		--					where rowno=3) 
							
							
							
							
							
		--					--Details Section individual Division wise(For Common)--Parameter(DivisionID,GenderID)
							
							
		--					select (DM.Id) AS DivisionID,SMD.Id,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
		--					(SC.PresentContactNo) AS ContactNo
							
		--					 from sSetup.tDivisionMaster DM
		--					INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		--					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--					INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--					INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
							
		--					where DM.ID='100100001' order by A.StudentID
							
							
							
							
		--					--Details Section individual Division wise(For Male)--Parameter(DivisionID,GenderID)
		--						select (DM.Id) AS DivisionID,SMD.Id,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
		--						(SC.PresentContactNo) AS ContactNo
								
		--						 from sSetup.tDivisionMaster DM
		--						INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--						INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								
		--						where DM.ID='100100001' 
		--						and SOD.GenderID=1 
		--						order by A.StudentID
								
								
		--						--Details Section individual Division wise(For Female)--Parameter(DivisionID,GenderID)
		--						select (DM.Id) AS DivisionID,SMD.Id,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
		--						(SC.PresentContactNo) AS ContactNo
								
		--						 from sSetup.tDivisionMaster DM
		--						INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		--						INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
								
		--						where DM.ID='100100001' 
		--						and SOD.GenderID=2 
		--						order by A.StudentID








END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentAttendaceDashboardNewGet]
	 
	 @rTypeId smallint,
	 @rFromDate date=NULL,
	 @rToDate date=NULL,
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDivisionId int=0,
	 @rClassId int =0,
	 @rGenderType int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId Bigint,
	 @rAttendanceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--Changes for Mantis Id: 0039838
DECLARE @lConfigValueDashboard nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValueDashboard = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValueDashboard, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValueDashboard <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValueDashboard <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

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

				--@rUptoDate,
				@rCommonOrgGroupBatchId,GetDate()
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0
				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
	END

--Organization wise Attendance

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

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

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

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

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

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

      END
   
ELSE IF @rTypeId=24     
      BEGIN

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

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

	   END
	   	   
ELSE IF @rTypeId=16   
   BEGIN
        
        (SELECT * FROM 
             (SELECT 
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
				DM.Code As DivisionCode,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
						 AEL.Id AS SourceId
						 ,CM.OrderIndex as ClassOrderIndex--add for mantis : 0042058
				,DM.OrderIndex AS DivisionOrderIndex	--add for mantis : 0042058
			  FROM sAttendance.tStudentLeaveRequest STSL
				INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
				 INNER JOIN sSetup.tClassMaster CM ON CM.ID=AEL.ClassId	--add for mantis : 0042058 
			  WHERE OGMEL.Id=@rOrgGroupId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				--AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				--AND LeaveToDate
				AND ((LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
				((LeaveToDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				-- IsInContext
				AND BMEL.IsInContext = 1
		) as a) 
		ORDER BY a.ClassOrderIndex, a.DivisionOrderIndex --add for mantis : 0042058
   END
      
ELSE IF @rTypeId=26   
   BEGIN
      
      (SELECT * FROM 
          (SELECT 
			  OGMEL.Id as OrgGroupId,
			  OGMEL.Title As OrgGroupTitle,
			  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
			  DM.Code As DivisionCode,(SMD.Code)StudentID,
			  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo,
			  AEL.Id AS SourceId
		   FROM sAttendance.tStudentLeaveRequest STSL 
			   INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		 
		   WHERE OMEL.Id=@rOrgId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				--AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				--AND LeaveToDate
				AND ((LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
				((LeaveToDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				-- IsInContext
				AND BMEL.IsInContext = 1
		) as a) 
   END
   
ELSE IF @rTypeId=17   
   BEGIN
       
       --(
	   SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,
                OrgTitle,
                Code As DivisionCode,
                StudentID,
                SourceId,
                StudentName,
                ContactNo FROM( SELECT ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				AcademicId AS SourceId,
				AttendanceDate, 
				DM.Code,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,(SC.ParentContactNo) As ContactNo
				 ,CM.OrderIndex as ClassOrderIndex--add for mantis : 0042058
				,DM.OrderIndex AS DivisionOrderIndex	--add for mantis : 0042058

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

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

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

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

  ELSE
    BEGIN

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


 CREATE OR ALTER PROCEDURE [sAttendance].[pStudentAttendance]
	 
	 
	 @rOrgId int,
	 @rOrgGroupBatchId int,
	 @rUserSourceId bigint
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN
 
	Select
		MR.TotalCount,
		MR.AbsentCount,
		MR.AttendanceCount, 
		MR.PresentCount, 		
		MR.AveragePresence
		
	From
		sStudent.vStudentAcademic SA		
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId		
		
	Where
		SA.OrgId = @rOrgId And SA.OrgGroupBatchId=@rOrgGroupBatchId
		And SA.InchargeEmployeeId = @rUserSourceId
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentAttendanceGet]
	 	 
	 	 @rUserSourceId bigint,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceTypeId int=1,
	 	  @rForMonth int=0,
	 	 @rForYear int=0
	 	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  
	 
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			SR.RepeatCount,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			Day(SR.AttendanceDate) AS AttendanceDay,
			MOnth(SR.AttendanceDate) AS AttendanceMonth,
			YEar(SR.AttendanceDate) AS AttendanceYear
  FROM   
			sStudent.vStudentAcademic SA 
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			 
			--AND (SR.AttendanceDate=@rAttendanceDate)
			--AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			--AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		 
  WHERE 
		 -- ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  --AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
        (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      AND SA.StudentId=@rUserSourceId
      AND SR.AttendanceTypeId=@rAttendanceTypeId
      AND Month(SR.AttendanceDate)=@rForMonth
      AND Year(SR.AttendanceDate)=@rForYear
      --AND (SA.StatusId != 3)
      --AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      --AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentAttendanceXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rClassId int=0,
    @rDivisionId int,
    @rAttendanceDate date='',
    @rAttendanceTypeId tinyint,
    @rCreatedUserId bigint,
    @rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rBatchId int=0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 
	 
	 DELETE SR FROM sAttendance.tStudentRegister SR 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId
	 --INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1)
	 --WITH
	 --(AcademicId bigint))A ON SR.AcademicId = A.AcademicId 
	    WHERE 
	    SR.AttendanceTypeId = @rAttendanceTypeId AND SR.AttendanceDate = @rAttendanceDate
	    --AND SA.ClassId = @rClassId 
	    AND SA.DivisionId=@rDivisionId 
	    AND SA.OrgId = @rOrgId 
	    AND ((ISNULL(SR.SubjectId,0) = ISNULL(@rSubjectId,0)) OR ( ISNULL(@rSubjectId,0)=0))
	    AND ((ISNULL(SR.RepeatCount,0) = ISNULL(@rRepeatCount,0)) OR (ISNULL(@rRepeatCount,0)=0))
	     AND SA.BatchId =@rBatchId
	 
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId
			)
		SELECT	
		DISTINCT	
			AcademicId,
			EmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			ISNULL(@rSubjectId,0),
			ISNULL(@rRepeatCount,0),
			IsPresent,
			ISNULL(AbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			ISNULL(AttendanceTagId,0)
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				EmployeeId bigint,
				IsPresent bit,
				AbsentReasonId int,
				AttendanceTagId smallint
		   ) AS At
		LEFT JOIN sStudent.tAcademic A ON A.Id=At.AcademicID
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
		 WHere SA.AdmissionDate <= @rAttendanceDate
		 AND ((SA.LeftDate > @rAttendanceDate) OR  ISNULL(SA.LeftDate,'') = '') 
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE OR ALTER PROCEDURE [sAttendance].[pStudentBatchGet]
	 @rSubjectBatchId int = 0,
	 --@rAffiliationId int,
	 --@rTitle nvarchar(200),
	 @rDivisionId int
	 --@rAcademicId bigint
	 --@rBatchId int

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			
	  --END
	 
	SELECT 
	VSF.AcademicId,
	--VSF.DivisionId,
	VSF.RollNo AS StudentRollNo,
	VSF.Name AS StudentName,
	VSF.Code AS StudentCode
	--VSF.BatchId,
	--ISNULL(SBS.SubjectBatchId,0)AS SubjectBatchId
	
      
  FROM 
       sStudent.vStudentFull VSF
       LEFT JOIN sAttendance.tSubjectBatchStudent SBS
       ON SBS.AcademicId=VSF.AcademicId
       
     
       
             
  WHERE 
		
      ((SBS.SubjectBatchId = @rSubjectBatchId) OR (@rSubjectBatchId = 0))
    AND ((VSF.DivisionId= @rDivisionId) OR (@rDivisionId=0)) 
        
     
      
        
	
		
END








GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentLeaveRequestAdd] 
	 
	 	@rAcademicId bigint,
        @rLeaveFromDate date,
        @rLeaveToDate date,
        @rLeaveReason nvarchar(200),
        @rCreatedUserId bigint 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	IF EXISTS(SELECT 1 FROM sAttendance.tStudentLeaveRequest WHERE AcademicId = @rAcademicId 
	   AND(( LeaveFromDate  BETWEEN @rLeaveFromDate AND @rLeaveToDate) OR (LeaveToDate BETWEEN @rLeaveFromDate AND @rLeaveToDate)
	   OR (@rLeaveFromDate  BETWEEN LeaveFromDate AND LeaveToDate) OR (@rLeaveToDate BETWEEN LeaveFromDate AND LeaveToDate)))
	BEGIN
		SELECT -11 AS RESULT
	END
	ELSE
	BEGIN
	 
	INSERT INTO sAttendance.tStudentLeaveRequest
		(
			AcademicId,
			LeaveFromDate,
			LeaveToDate,
			LeaveReason,
			CreatedUserId,
			CreatedDateTime 
		)
	VALUES
		(
			@rAcademicId,
			@rLeaveFromDate,
			@rLeaveToDate,
			@rLeaveReason, 
			@rCreatedUserId,
			sCommon.fGetDate()
		)
	Select 1 As Result	 
	END
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentLeaveRequestGet] 
	 
	 	@rAcademicId bigint,
        @rLeaveFromDate date='',
        @rLeaveToDate date='' ,
        @rOrgID int=0,
        @rBatchId int=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	Select
		SL.AcademicId,
		ISNULL(SL.LeaveFromDate,'')AS LeaveFromDate,
		ISNULL(SL.LeaveToDate,'')AS LeaveToDate,
		SL.LeaveReason,
		SM.Code As IdNo,
		SM.FirstName+' ' +SM.MiddleName+' ' +SM.LastName As Name,
		ISNULL(SL.StatusId,0) AS StatusId,  
      ISNULL(S.Title,'Pending') AS StatusName,  
      ISNULL(SL.StatusReason,'') AS  StatusReason
		
	from sAttendance.tStudentLeaveRequest SL
	INNER JOIN sStudent.tAcademic A ON A.Id=SL.AcademicId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
	LEFT JOIN sCommon.tStatusMaster S ON S.Id = SL.StatusId 
	Where ((AcademicId=@rAcademicId) OR (@rAcademicId=0))
	AND ((LeaveFromDate >= @rLeaveFromDate) OR (ISNULL(@rLeaveFromDate,'')=''))
	AND ((LeaveToDate <= @rLeaveToDate) OR (ISNULL(@rLeaveToDate,'')=''))
	AND ((SM.OrgId=@rOrgID)OR(@rOrgID=0))
	AND ((A.BatchId=@rBatchId)OR(@rBatchId=0))
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentPresenceDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 
	 @rOrgGroupId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rClassId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
  SELECT
	  ISNULL((
	   SELECT 
		ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId
		  WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE())
		   AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND 
		   (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND
		    (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId
		 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) 
		 AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) 
		 AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) 
		 AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) 
		FROM 
		sStudent.vStudentAllDetail A
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY OM.OrgGroupId
      ),0)
      AS DailyAverage,
       ISNULL((
	   SELECT 
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))+'/'+
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))AS B
		FROM 
		sStudent.vStudentAllDetail A
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY OM.OrgGroupId
      ),'0/0')
      AS DailyCount,
      
  ISNULL((
	   SELECT  
		ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  
		WHERE CONVERT(DATE,AttendanceDate) =  DATEADD(day, -1, convert(date, GETDATE())) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0))
		AND A.OrgGroupBatchId = @rOrgGroupBatchId AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) 
		HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A 
		ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  
		WHERE CONVERT(DATE,AttendanceDate) =  DATEADD(day, -1, convert(date, GETDATE())) AND AttendanceTypeId=1 AND OM.OrgGroupId=@rOrgGroupId
		AND A.OrgGroupBatchId = @rOrgGroupBatchId AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) 
		HAVING COUNT(SR.AcademicId) > 0)),0) 
		FROM 
		sStudent.vStudentAllDetail A
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY OM.OrgGroupId
       ),0)
      AS YesterdayAverage,
      
      ISNULL((
	   SELECT 
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  
		WHERE CONVERT(DATE,AttendanceDate) =  DATEADD(day, -1, convert(date, GETDATE())) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0))
		AND A.OrgGroupBatchId = @rOrgGroupBatchId AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) 
		HAVING COUNT(SR.AcademicId) > 0))+'/'+
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A 
		ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  
		WHERE CONVERT(DATE,AttendanceDate) =  DATEADD(day, -1, convert(date, GETDATE())) AND AttendanceTypeId=1 AND OM.OrgGroupId=@rOrgGroupId
		AND A.OrgGroupBatchId = @rOrgGroupBatchId AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) 
		HAVING COUNT(SR.AcademicId) > 0)) AS B 
		FROM 
		sStudent.vStudentAllDetail A
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY OM.OrgGroupId
      ),'0/0')
      AS YesterdayCount,
      ISNULL((
	   SELECT 
	   ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE  CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
	    /(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE  CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0)
	    FROM 
		sStudent.vStudentAllDetail A
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY OM.OrgGroupId
       ),0)
       AS WeeklyAverage,
        ISNULL((
	   SELECT 
	   CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE  CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))+'/'+
	   CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE  CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))AS B
	    FROM 
		sStudent.vStudentAllDetail A
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY OM.OrgGroupId
       ),'0/0')
       AS WeeklyCount,
	   
	  ISNULL((
	   SELECT 
	   ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE  CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
	    /(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE  CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0)
	    FROM 
		sStudent.vStudentAllDetail A
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY OM.OrgGroupId	
       ),0)
       AS MonthlyAverage,   
        ISNULL((
	   SELECT 
	   CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE  CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)) +'/'+
	    CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE  CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))AS B
	    FROM 
		sStudent.vStudentAllDetail A
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY OM.OrgGroupId	
       ),'0/0')
       AS MonthlyCount    
  END
  
  IF(@rType='Class')
  BEGIN
  	IF(@rDay=-1)
	BEGIN
		SELECT 
		vSA.ClassId,vSA.ClassName,ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A 
		ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
		 WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE())) 
		 AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) 
		 AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON 
		SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId
		 AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE()))  AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0))
		 AND A.OrgGroupBatchId = @rOrgGroupBatchId AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) 
		 HAVING COUNT(SR.AcademicId) > 0)),0) AS YesterdayAverage,
		ISNULL( CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A 
		ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
		 WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE())) 
		 AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) 
		 AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))+'/'+
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON 
		SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId
		 AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE()))  AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) 
		 AND A.OrgGroupBatchId = @rOrgGroupBatchId AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) 
		 HAVING COUNT(SR.AcademicId) > 0)),0) AS YesterdayCount
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0))AND (vSA.OrgId = @rOrgId OR @rOrgId=0) AND (vSA.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY vSA.ClassId,vSA.ClassName,OM.Id
	END
	IF(@rDay=1)
	BEGIN
		SELECT 
		vSA.ClassId,vSA.ClassName,ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS DailyAverage,
		ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))+'/'+
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS DailyCount
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0))AND (vSA.OrgId = @rOrgId OR @rOrgId=0) AND (vSA.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY vSA.ClassId,vSA.ClassName,OM.Id
	END
	IF(@rDay=7)
	BEGIN
		SELECT
		vSA.ClassId,vSA.ClassName,ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS WeeklyAverage,
		ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))+'/'+
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS WeeklyCount
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0)) AND (vSA.OrgId = @rOrgId OR @rOrgId=0) AND (vSA.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY vSA.ClassId,vSA.ClassName,OM.Id
	END
	IF(@rDay=30)
	BEGIN
		SELECT
		vSA.ClassId,vSA.ClassName,ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS MonthlyAverage,
		ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))+'/'+
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.ClassId=A.ClassId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS MonthlyCount
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0)) AND (vSA.OrgId = @rOrgId OR @rOrgId=0) AND (vSA.BatchId = @rBatchId OR @rBatchId=0)
		GROUP BY vSA.ClassId,vSA.ClassName,OM.Id
	END
  END	
  
  IF(@rType='Division')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT 
		vSA.DivisionId,vSA.ClassName +' - '+ vSA.DivisionName AS DivisionName ,ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR 
		INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  
		WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE()))  
		AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) 
		AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  
		WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE()))  
		AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) 
		AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS YesterdayAverage,
		ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR 
		INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  
		WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE()))  
		AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) 
		AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)) +'/'+
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  
		WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE()))  
		AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) 
		AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS YesterdayCount
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0)) AND (vSA.OrgId = @rOrgId OR @rOrgId=0) AND (vSA.BatchId = @rBatchId OR @rBatchId=0) AND vSA.ClassId = @rClassId
		GROUP BY vSA.DivisionId,vSA.ClassName,vSA.DivisionName,OM.Id
	End
	IF(@rDay=1)
	BEGIN
		SELECT 
		vSA.DivisionId,vSA.ClassName +' - '+ vSA.DivisionName AS DivisionName ,ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS DailyAverage,
		ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))+'/'+
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS DailyCount
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE OM.OrgGroupId=@rOrgGroupId AND vSA.OrgGroupBatchId = @rOrgGroupBatchId AND (vSA.OrgId = @rOrgId OR @rOrgId=0) AND (vSA.BatchId = @rBatchId OR @rBatchId=0) AND vSA.ClassId = @rClassId
		GROUP BY vSA.DivisionId,vSA.ClassName,vSA.DivisionName,OM.Id
	END
	IF(@rDay=7)
	BEGIN
		SELECT 
		vSA.DivisionId,vSA.ClassName +' - '+ vSA.DivisionName AS DivisionName ,ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS WeeklyAverage,
		ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))+'/'+
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS WeeklyCount
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0)) AND (vSA.OrgId = @rOrgId OR @rOrgId=0) AND (vSA.BatchId = @rBatchId OR @rBatchId=0) AND vSA.ClassId = @rClassId 
		GROUP BY vSA.DivisionId,vSA.ClassName,vSA.DivisionName,OM.Id
		
	END
	IF(@rDay=30)
	BEGIN
		SELECT 
		vSA.DivisionId,vSA.ClassName +' - '+ vSA.DivisionName AS DivisionName ,ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS MonthlyAverage,
		ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0))+'/'+
		CONVERT(nvarchar(30),(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.DivisionId=A.DivisionId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) AND (A.OrgId = @rOrgId OR @rOrgId=0) AND (A.BatchId = @rBatchId OR @rBatchId=0) HAVING COUNT(SR.AcademicId) > 0)),0) AS MonthlyCount
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0)) AND (vSA.OrgId = @rOrgId OR @rOrgId=0) AND (vSA.BatchId = @rBatchId OR @rBatchId=0) AND vSA.ClassId = @rClassId
		GROUP BY vSA.DivisionId,vSA.ClassName,vSA.DivisionName,OM.Id
	END
  END	
  
  IF(@rType='OrgGroup')
  BEGIN
	IF(@rDay=-1)
	BEGIN
		SELECT 
		OM.Id AS OrgId, OM.DisplayTitle AS Organization, ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR 
		INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.OrgId=A.OrgId AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE()))  AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)  HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A 
		ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  
		WHERE CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE()))  AND AttendanceTypeId=1 AND OM.OrgGroupId=@rOrgGroupId 
		AND A.OrgGroupBatchId = @rOrgGroupBatchId  HAVING COUNT(SR.AcademicId) > 0)),0) AS YesterdayCount
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0))
		GROUP BY vSA.OrgId,OM.Id,OM.DisplayTitle
	END
	IF(@rDay=1)
	BEGIN
		SELECT 
		OM.Id AS OrgId, OM.DisplayTitle AS Organization, ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.OrgId=A.OrgId AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)  HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)  HAVING COUNT(SR.AcademicId) > 0)),0) AS DailyAverage
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0))
		GROUP BY vSA.OrgId,OM.Id,OM.DisplayTitle
	END
	IF(@rDay=7)
	BEGIN
		SELECT 
		OM.Id AS OrgId, OM.DisplayTitle AS Organization, ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.OrgId=A.OrgId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)  HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)  HAVING COUNT(SR.AcademicId) > 0)),0) AS WeeklyAverage
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0)) 
		GROUP BY vSA.OrgId,OM.Id,OM.DisplayTitle
		
	END
	IF(@rDay=30)
	BEGIN
		SELECT 
		OM.Id AS OrgId, OM.DisplayTitle AS Organization,ISNULL(((SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE vSA.OrgId=A.OrgId AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND IsPresent=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0) HAVING COUNT(SR.AcademicId) > 0) * 100
		/(SELECT COUNT(SR.AcademicId) FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAllDetail A ON SR.AcademicId = A.AcademicId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId  WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND AttendanceTypeId=1 AND (OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0) AND (A.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)  HAVING COUNT(SR.AcademicId) > 0)),0) AS MonthlyAverage
		FROM 
		sStudent.vStudentAllDetail vSA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId 
		WHERE (OM.OrgGroupId=@rOrgGroupId  OR (@rOrgGroupId=0)) AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId  OR (@rOrgGroupbatchId =0))
		GROUP BY vSA.OrgId,OM.Id,OM.DisplayTitle
	END
  END	
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentRegisterAdd]
	 
	@rAcademicId bigint,
	@rEmployeeId bigint,
	@rAttendanceTypeId tinyint,
	@rAttendanceDate date,
	@rSubjectId int,
	@rRepeatCount tinyint,
	@rIsPresent bit,
	@rAbsentReasonId int,
	@rCreatedUserId bigint,
	@rIsDeleted bit,
	@rAttendanceTagId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
If(@rIsDeleted=1)
BEGIN
	Delete  from sAttendance.tStudentRegister where AcademicId=@rAcademicId and AttendanceTypeId=@rAttendanceTypeId 
	AND AttendanceDate=@rAttendanceDate AND ISNULL(SubjectId,0)=ISNULL(@rSubjectId,0) 
	AND ISNULL(RepeatCount,0)=ISNULL(@rRepeatCount,0)
	Select @rAcademicId as Result
	RETURN
END	
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	If Not Exists(select AcademicId from sAttendance.tStudentRegister where AcademicId=@rAcademicId 
	and AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate 
	AND ISNULL(SubjectId,0)=ISNULL(@rSubjectId,0) AND ISNULL(RepeatCount,0)=ISNULL(@rRepeatCount,0))
	BEGIN
		--Select @rRepeatCount=RepeatCount from sAttendance.tStudentRegister where AttendanceDate=@rAttendanceDate AND 
		--SubjectId=@rSubjectId
		--IF(@rRepeatCount IS NULL)
		--BEGIN
		--	SET @rRepeatCount=1
		--END
		--ELSE
		--BEGIN
		--	SET @rRepeatCount=@rRepeatCount+1
		--END
		INSERT INTO sAttendance.tStudentRegister
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AttendanceTagId,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@rAcademicId,
			@rEmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			@rSubjectId,
			@rRepeatCount,
			@rIsPresent,
			@rAttendanceTagId,
			@rAbsentReasonId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)		
	 	 SELECT @rAcademicId AS Result
	END	
ELSE
	 BEGIN
	   UPDATE  sAttendance.tStudentRegister
	    SET
			EmployeeId=@rEmployeeId,
			IsPresent=@rIsPresent,
			AttendanceTagId=@rAttendanceTagId,
			AbsentReasonId=@rAbsentReasonId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			
	      WHERE AcademicId = @rAcademicId 
			  AND AttendanceTypeId=@rAttendanceTypeId 
			  AND AttendanceDate=@rAttendanceDate 
			  AND ISNULL(SubjectId,0)=ISNULL(@rSubjectId,0)
			  AND ISNULL(RepeatCount,0)=ISNULL(@rRepeatCount,0)
	      SELECT @rAcademicId AS Result
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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


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


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

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pStudentRegisterDelete]
	 
	 
	@rDivisionId int,
	@rAttendanceTypeId tinyint,
	@rAttendanceDate date,
	@rSubjectId int,
	@rRepeatCount tinyint,
	@rAttendanceGroupId int=0 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
	
	 BEGIN TRANSACTION	

DELETE SR
FROM sAttendance.tStudentRegister SR
INNER JOIN sStudent.tAcademic A
ON SR.AcademicId= A.Id
WHERE ((A.DivisionId=@rDivisionId AND ISNULL(SR.AttendanceGroupId,0)=0) OR (@rDivisionId=0))
AND SR.AttendanceTypeId = @rAttendanceTypeId
AND SR.AttendanceDate=@rAttendanceDate
AND ISNULL(SubjectId,0)=ISNULL(@rSubjectId,0) 
AND ISNULL(RepeatCount,0)=ISNULL(@rRepeatCount,0) 
AND ((SR.AttendanceGroupId=@rAttendanceGroupId) OR (@rAttendanceGroupId=0))
	--Delete  from sAttendance.tStudentRegister where
	-- AcademicId=@rAcademicId and AttendanceTypeId=@rAttendanceTypeId 
	--AND AttendanceDate=@rAttendanceDate AND ISNULL(SubjectId,0)=ISNULL(@rSubjectId,0) 
	--AND ISNULL(RepeatCount,0)=ISNULL(@rRepeatCount,0)
	--Select @rAcademicId as Result
 SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentRegisterGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rAttendanceDate date,
		 @rSubjectId int,
		 @rSubjectBatchId int,
		 @rRepeatCount tinyint,
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
IF @rSubjectBatchId=0
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SO.GenderId,0) AS GenderId,
			ISNULL(GM.Title,'') AS Gender,
			ISNULL(SR.AttendanceRemark,'') AS AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply,
			ISNULL(SLR.LeaveReason,'') AS LeaveReason
			
  FROM 
            sStudent.vStudentAcademic SA 
            LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId
            LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId AND SLR.StatusId = 550 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN (2,3))
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SR.AttendanceRemark,'') AS AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply
  FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
		LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN(2,3))
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
ELSE
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SR.AttendanceRemark,'') AS AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply
  FROM 
            sStudent.vStudentAcademic SA
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
		LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN(2,3))
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SR.AttendanceRemark,'') AS AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply
  FROM 
            sStudent.vStudentAcademic SA 
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
		LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN(2,3))
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentRegisterMobileAppGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rAttendanceDate date,
		 @rSubjectId int,
		 @rSubjectBatchId int,
		 @rRepeatCount tinyint,
	 	 @rOrgGroupBatchId int,
	 	 @rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
IF @rSubjectBatchId=0
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			SA.StudentId,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.Id AS EmployeeId,
			EM.Code AS EmployeeCode,
			EM.FirstName +' '+EM.LastName AS EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS PresentTagId,
			ISNULL(SO.GenderId,0) AS GenderId,
			ISNULL(GM.Title,'') AS Gender,
			ATM.Title AS  AttendanceTag,
			ARM.Title AS AbsentReason,
			0x AS StudentPhoto,
			SA.BatchId,
			SR.AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN SLR.LeaveReason ELSE '' END) AS LeaveReason
  FROM 
            sStudent.vStudentAcademic SA 
            LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId
            LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
			LEFT JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId 
            LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId 
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.InchargeEmployeeId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
			LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate AND SLR.StatusId = 550
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
      --AND (SA.StatusId != 3)
	  AND (SA.StatusId != 2)
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.Id AS EmployeeId,
			EM.Code AS EmployeeCode,
			EM.FirstName +' '+EM.LastName AS EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS PresentTagId ,
			ATM.Title AS  AttendanceTag,
			ARM.Title AS AbsentReason,
			0x AS  StudentPhoto,
			SR.AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN SLR.LeaveReason ELSE '' END) AS LeaveReason
			
  FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
			LEFT JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId 
			LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId 
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.InchargeEmployeeId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
			LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
      --AND (SA.StatusId != 3)
	  AND (SA.StatusId != 2)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
       AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
ELSE
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.Id AS EmployeeId,
			EM.Code AS EmployeeCode,
			EM.FirstName +' '+EM.LastName AS EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS PresentTagId,
			ATM.Title AS  AttendanceTag,
			ARM.Title AS AbsentReason,
			0x AS StudentPhoto ,
			SR.AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply
			
  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
			LEFT JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId 
			LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId 
			INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SBS.BatchId 
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.InchargeEmployeeId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
			LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
      --AND (SA.StatusId != 3)
	  AND (SA.StatusId != 2)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.Id AS EmployeeId,
			EM.Code AS EmployeeCode,
			EM.FirstName +' '+EM.LastName AS EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS PresentTagId,
			ATM.Title AS  AttendanceTag,
			ARM.Title AS AbsentReason,
			0x AS  StudentPhoto,
			SR.AttendanceRemark,
			(CASE WHEN SLR.AcademicId IS NOT NULL THEN 'On Leave' ELSE '' END) AS LeaveApply
			
  FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
			LEFT JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId 
			LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId 
			INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SBS.BatchId 
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.InchargeEmployeeId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
			LEFT JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId 
			AND @rAttendanceDate >= SLR.LeaveFromDate AND @rAttendanceDate <=SLR.LeaveToDate
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
      --AND (SA.StatusId != 3)
	  AND (SA.StatusId != 2)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentRegisterXMLAdd]
	(
		@rXmlDoc nvarchar(MAX)
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	-----------------------
	DELETE SA FROM sAttendance.tStudentRegister SA INNER JOIN 
	(SELECT AcademicId,AttendanceDate FROM OPENXML (@intDoc, '/Table/StudentAttendace', 1)
	WITH
	(		
		AcademicId BigINT '@Id',
		AttendanceDate DateTime '@AttendanceDate'
	))A ON  SA.AcademicId = A.AcademicId AND SA.AttendanceDate=A.AttendanceDate AND SA.AttendanceTypeId = 1
		
	
	INSERT INTO sAttendance.tStudentRegister
	(
		AcademicId,
		AttendanceDate,
		IsPresent,
		AttendanceTypeId,
		CreatedUserId,
		CreatedDateTime	
	)
	SELECT
		AcademicId,
		AttendanceDate,
		IsPresent,
		1,
		3,		--they want Admin in created user id so put 3 insted of 1 because 1 stands for SysSuperAdmin and 3 stands for Admin. Mantis id 26812
		sCommon.fGetDate()	
		
	FROM OPENXML (@intDoc, '/Table/StudentAttendace', 1)
	WITH
	(		
		AcademicId BigINT '@Id',
		AttendanceDate DateTime '@AttendanceDate',
		IsPresent Smallint '@Present'
	)A
	
	
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentRegisterXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rClassId int=0,
    @rDivisionId int,
    @rAttendanceDate date='',
    @rAttendanceTypeId tinyint,
    @rCreatedUserId bigint,
    @rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rBatchId int=0,
    @rAttendanceGroupId int=0,
    @rPeriodNo int=0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 DECLARE @tmp varchar(1000)
	 IF @rDivisionId != 0
	 BEGIN 
		IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1) WITH (AcademicId bigint))A ON SR.AcademicId = A.AcademicId 
				 AND SR.SubjectId = @rSubjectId AND SR.AttendanceDate = @rAttendanceDate AND SR.PeriodNo = @rPeriodNo AND ISNULL(SR.AttendanceGroupId,0) > 0)
		BEGIN
		SET @tmp = ''
		SELECT @tmp = @tmp + SA.Code + ', ' FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = SR.AcademicId INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1) WITH (AcademicId bigint))A ON SR.AcademicId = A.AcademicId AND SR.SubjectId = @rSubjectId AND SR.AttendanceDate = @rAttendanceDate AND SR.PeriodNo = @rPeriodNo AND ISNULL(SR.AttendanceGroupId,0) > 0	-- Add ISNULL to AttendanceGroupId for mantis : 0034075
		SELECT -101 AS Result, SUBSTRING(@tmp, 0, LEN(@tmp)) AS ResultDetail
		RETURN
		END
	 END
	 ELSE
	 BEGIN 
		IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1) WITH (AcademicId bigint))A ON SR.AcademicId = A.AcademicId 
				 AND SR.SubjectId = @rSubjectId AND SR.AttendanceDate = @rAttendanceDate AND SR.PeriodNo = @rPeriodNo AND ISNULL(SR.AttendanceGroupId,0) = 0)
		BEGIN
		SET @tmp = ''
		SELECT @tmp = @tmp + SA.Code + ', ' FROM sAttendance.tStudentRegister SR INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = SR.AcademicId INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1) WITH (AcademicId bigint))A ON SR.AcademicId = A.AcademicId AND SR.SubjectId = @rSubjectId AND SR.AttendanceDate = @rAttendanceDate AND SR.PeriodNo = @rPeriodNo AND ISNULL(SR.AttendanceGroupId,0) = 0	-- Add ISNULL to AttendanceGroupId for mantis : 0034075
		SELECT -101 AS Result, SUBSTRING(@tmp, 0, LEN(@tmp)) AS ResultDetail
		RETURN
		END
	 END
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE SR FROM sAttendance.tStudentRegister SR 
	 INNER JOIN sStudent.tAcademic SA ON SA.Id = SR.AcademicId
	 --INNER JOIN (SELECT AcademicId FROM OPENXML(@loDoc, '/Table/RowData', 1)
	 --WITH
	 --(AcademicId bigint))A ON SR.AcademicId = A.AcademicId 
	    WHERE 
	    SR.AttendanceTypeId = @rAttendanceTypeId AND SR.AttendanceDate = @rAttendanceDate
	    --AND SA.ClassId = @rClassId 
	    AND ((SA.DivisionId=@rDivisionId AND ISNULL(SR.AttendanceGroupId,0)=0) OR (@rDivisionId=0))
	    AND SA.OrgId = @rOrgId 
	    AND ((ISNULL(SR.SubjectId,0) = ISNULL(@rSubjectId,0)) OR ( ISNULL(@rSubjectId,0)=0))
	    AND ((ISNULL(SR.RepeatCount,0) = ISNULL(@rRepeatCount,0)) OR (ISNULL(@rRepeatCount,0)=0))
	    AND ((ISNULL(SR.AttendanceGroupId,0)=@rAttendanceGroupId) OR (@rAttendanceGroupId=0))
	    AND SA.BatchId =@rBatchId
	 
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId,
			PeriodNo,
			AttendanceGroupId,
			AttendanceRemark
			)
		SELECT	
		DISTINCT	
			AcademicId,
			EmployeeId,
			@rAttendanceTypeId,
			@rAttendanceDate,
			ISNULL(@rSubjectId,0),
			ISNULL(@rRepeatCount,0),
			IsPresent,
			ISNULL(AbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			ISNULL(AttendanceTagId,0),
			@rPeriodNo,
			@rAttendanceGroupId,
			ISNULL(AttendanceRemark,'')
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				EmployeeId bigint,
				IsPresent bit,
				AbsentReasonId int,
				AttendanceTagId smallint,
				AttendanceRemark nvarchar(500)
			  )  
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentSetupAdd]
	 
	@rAcademicId bigint,
	@rForMonth tinyint,
	@rForYear smallint,
	@rWorkingDays smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION
	 IF NOT EXISTS(SELECT * from sAttendance.tStudentSetup WHERE AcademicId=@rAcademicId AND 
	 ForMonth=@rForMonth AND ForYear=@rForYear)
	 BEGIN	
	 INSERT INTO sAttendance.tStudentSetup
		(
			AcademicId,
			ForMonth,
			ForYear,
			WorkingDays
		)
		VALUES
		(
			@rAcademicId,
			@rForMonth,
			@rForYear,
			@rWorkingDays
		)		
	END
	ELSE
	BEGIN
	UPDATE sAttendance.tStudentSetup
	SET
		WorkingDays=@rWorkingDays
	WHERE
		AcademicId=@rAcademicId
		AND ForMonth=@rForMonth 
		AND ForYear=@rForYear
	END
		SELECT @rAcademicId AS Result
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentSetupGet]
	 	 @rBatchId int,
	 	 @rAcademicId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,		
		CASE WHEN SS.WorkingDays IS NOT NULL THEN
		ISNULL(SS.WorkingDays,0)
		ELSE ISNULL(MS.WorkingDays,0) END AS WorkingDays
	From 
	
	sSetup.fMonthYearForBatchGET(@rBatchId) AS MY
	INNER JOIN sStudent.vStudentAcademic SA ON SA.BatchId=MY.BatchId AND SA.AcademicId=@rAcademicId
	LEFT JOIN sAttendance.tMonthlySetup MS ON MS.ClassId=SA.ClassId
	AND MS.ForMonth = MY.MonthNumber AND MS.ForYear = MY.YearNumber and MS.BatchId=@rBatchId --Add a BatchId condition to handle duplicate data by Sahjanand.
	--LEFT JOIN 
	--(
	--SELECT A.batchId, ss.*
	--FROM sAttendance.tStudentSetup SS INNER JOIN sStudent.tAcademic A ON SS.academicId = a.Id AND A.Id = @rAcademicId
	
	--) AS BI
	--ON MY.BatchId = BI.BatchId AND MY.MonthNumber = BI.ForMonth AND MY.YearNumber = BI.ForYear 
	
	LEFT JOIN sAttendance.tStudentSetup SS ON SS.AcademicId=SA.AcademicId AND (SS.AcademicId=@rAcademicId)
	AND SS.ForMonth = MY.MonthNumber AND SS.ForYear = MY.YearNumber
	
	WHERE
		(MY.BatchId=@rBatchId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pStudentSubjectwiseAttendanceGet]
	 	  @rForMonth smallint,
	      @rForYear smallint,
	      @rAcademicId bigint,
	      @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
	
	        DAY(SR.AttendanceDate) AS DayNo,
			
			CASE  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 1 THEN 'LA' 
				  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 2 THEN 'ED' 
			      WHEN SR.IsPresent = 1  THEN 'P' 
				  WHEN SR.IsPresent = 0 THEN 'A'
				  ELSE  '' END AS  Presence,
			OM.WeekOffs,
			sAttendance.fHolidayForMonthGet(@rForMonth,@rForYear,@rBatchId,SA.DivisionId)  As Holidays,
			ISNULL(SM.Id,0) AS SubjectId,  
			ISNULL(SM.Code,'') AS SubjectCode,  
			ISNULL(SM.Title,'') AS SubjectName,  
			ISNULL(SR.PeriodNo,0) As PeriodNo,
			SR.AcademicId
			
			
		
	From  
			sStudent.vStudentAcademic SA
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId 
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	
	WHERE
			SR.AttendanceTypeId=5
		AND SR.AcademicId=@rAcademicId
		AND YEAR(SR.AttendanceDate)=@rForYear
		AND MONTH(SR.AttendanceDate)=@rForMonth
		AND SA.BatchId=@rBatchId
		
		ORDER BY DayNo ,SubjectName,PeriodNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pStudentSubjectwisePresenceGet]
	 	@rBatchId int,
	 	@rUserSourceId bigint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SELECT 
			sCommon.fGetMonthName(MONTH(SR.AttendanceDate)) AS MonthName,
			
			SM.Title AS SubjectName,
			
			ISNULL((SELECT COUNT(S.AcademicId) 
			FROM sAttendance.tStudentRegister S
			WHERE S.AcademicId = SR.AcademicId 
			AND S.AttendanceTypeId = 5 
			AND SR.SubjectId = S.SubjectId			
			GROUP BY MONTH(S.AttendanceDate) HAVING MONTH(S.AttendanceDate) = MONTH(SR.AttendanceDate)
			),0) AS Total,
			
			ISNULL((SELECT COUNT(S.AcademicId) 
			FROM sAttendance.tStudentRegister S
			WHERE S.AcademicId =SR.AcademicId 
			AND S.AttendanceTypeId = 5 AND S.IsPresent = 1
			AND SR.SubjectId = S.SubjectId			
			GROUP BY MONTH(S.AttendanceDate) HAVING MONTH(S.AttendanceDate) = MONTH(SR.AttendanceDate)
			),0) AS Attended
		
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND SR.AttendanceTypeId = 5 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = SR.SubjectId 
		WHERe
			SA.BatchId = @rBatchId 
			AND (SA.StudentId = @rUserSourceId OR @rUserSourceId = 0)
			GROUP BY YEAR(SR.AttendanceDate),Month(SR.AttendanceDate),SM.Title,SR.AcademicId,SR.SubjectId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pStudetntAttendanceGet]
	 	 
	 	  @rForMonth smallint,
	      @rForYear smallint,
	      @rAcademicId bigint,
	      @rAttendanceTypeId smallint,
	      @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
	
	        DAY(SR.AttendanceDate) AS DayNo,
			
			CASE  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 1 THEN 'LA' 
				  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 2 THEN 'ED' 
			      WHEN SR.IsPresent = 1  THEN 'P' 
				  WHEN SR.IsPresent = 0 THEN 'A'
				  ELSE  '' END AS  Presence,
			--(CASE SR.IsPresent WHEN 1 THEN 'P' 
			--	WHEN 0 THEN 'A'
			--	END )AS  Presence,
			OM.WeekOffs,
			sAttendance.fHolidayForMonthGet(@rForMonth,@rForYear,@rBatchId,SA.DivisionId)  As Holidays
			
			--DAY(SR.AttendanceDate) AS DayNo,
			--(CASE SR.IsPresent WHEN 1 THEN 'P' 
			--	WHEN 0 THEN 'A'
			--	END )AS  Presence,
			--OM.WeekOffs
			
		
	From  
			sStudent.vStudentAcademic SA
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	
	WHERE
			SR.AttendanceTypeId=@rAttendanceTypeId
		AND SR.AcademicId=@rAcademicId
		AND YEAR(SR.AttendanceDate)=@rForYear
		AND MONTH(SR.AttendanceDate)=@rForMonth
		AND SA.BatchId=@rBatchId
		
		ORDER BY DayNo ASC
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pStudetntAttendancev2Get]
	 	 
	 	  @rForMonth smallint,
	      @rForYear smallint,
	      @rAcademicId bigint,
	      @rAttendanceTypeId smallint,
	      @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
			DAY(SR.AttendanceDate) AS DayNo,
			
			CASE  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 1 THEN 'LA' 
				  WHEN SR.IsPresent = 1 AND SR.AttendanceTagId = 2 THEN 'ED' 
			      WHEN SR.IsPresent = 1  THEN 'P' 
				  WHEN SR.IsPresent = 0 THEN 'A'
				  ELSE  '' END AS  Presence,
			--(CASE SR.IsPresent WHEN 1 THEN 'P' 
			--	WHEN 0 THEN 'A'
			--	END )AS  Presence,
			OM.WeekOffs,
			'5,12,15,20,21,29' Holidays
			
		
	From  
			sStudent.vStudentAcademic SA
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	
	WHERE
			SR.AttendanceTypeId=@rAttendanceTypeId
		AND SR.AcademicId=@rAcademicId
		AND YEAR(SR.AttendanceDate)=@rForYear
		AND MONTH(SR.AttendanceDate)=@rForMonth
		AND SA.BatchId=@rBatchId
		
		ORDER BY DayNo ASC
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE OR ALTER PROCEDURE [sAttendance].[pSubjectBatchAdd]
	 
	@rId int,
	@rTitle nvarchar(100),
	@rDivisionId int,
	@rSubjectId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgId int,
	@rBatchId int
	
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT Id FROM sAttendance.tSubjectBatch WHERE Title=@rTitle AND BatchId=@rBatchId)
		BEGIN
			SELECT -101 AS RESULT
			RETURN
		END
	END
	ELSE
	BEGIN	
		IF EXISTS (SELECT Id FROM sAttendance.tSubjectBatch WHERE Title=@rTitle AND BatchId=@rBatchId AND Id!=@rId)
		BEGIN
			SELECT -102 AS RESULT
			RETURN
		END
	END	

	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAttendance.tSubjectBatch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sAttendance.tSubjectBatch
		(
			Id,
			DivisionId,
			SubjectId,
			Title,
			CreatedUserId,
			CreatedDateTime,
			BatchId
		)
	VALUES
		(
			@lNextNumber,
			@rDivisionId,
			@rSubjectId,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rBatchId
		)
		 SELECT 1 AS RESULT            
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAttendance.tSubjectBatch
	    SET
	      DivisionId=@rDivisionId,
	      SubjectId=@rSubjectId,
	      Title=@rTitle,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate(),
	      BatchId=@rBatchId
	     
	      
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE OR ALTER PROCEDURE [sAttendance].[pSubjectBatchGet]
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(200),
	 @rDivisionId int,
	 @rSubjectId int,
	 @rBatchId int

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN
	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			
	  END
	 
	SELECT 
	SB.Id,
	SB.Title,
	SB.DivisionId,
	SB.SubjectId,
	VBCD.ClassDivisionName AS DivisionTitle,
	SM.Title AS SubjectTitle
      
  FROM 
       sAttendance.tSubjectBatch SB
       INNER JOIN sSetup.vBatchClassDivision VBCD
       ON VBCD.DivisionId=SB.DivisionId AND VBCD.BatchId=@rBatchId
       INNER JOIN sSetup.tSubjectMaster SM
       ON SM.Id=SB.SubjectId
       
             
  WHERE 
		
      ((SB.Id = @rId) OR (@rId = 0))
       AND  ((SB.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      AND ((SB.BatchId = @rBatchId) OR (@rBatchId = 0))
        AND  ((SB.DivisionId= @rDivisionId) OR (@rDivisionId=0)) 
        AND  ((SB.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
     
     
      
        
	
		
END







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE OR ALTER PROCEDURE [sAttendance].[pSubjectBatchStudentAdd]
	 
	
	@rStudentBatchDetailXml [nvarchar](max),
	--@rAcademicId bigint,
	@rSubjectBatchId int
	--@rBatchId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStudentBatchDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	
	 DELETE FROM sAttendance.tSubjectBatchStudent 
				 WHERE SubjectBatchId=@rSubjectBatchId 
	
 
	 INSERT INTO sAttendance.tSubjectBatchStudent
		(
			SubjectBatchId,
			AcademicId,
			BatchId
			)
		SELECT
		
			SubjectBatchId,
			AcademicId,
			BatchId
		FROM OPENXML (@loDoc, '/Table/StudentBatchDetail', 1)
		WITH ( 
				SubjectBatchId int,
				AcademicId bigint,
				BatchId int
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO








CREATE OR ALTER PROCEDURE [sAttendance].[pSubjectBatchStudentGet]
	 @rSubjectBatchId int = 0,
	 --@rAffiliationId int,
	 --@rTitle nvarchar(200),
	 @rDivisionId int,
	 --@rAcademicId bigint
	 @rBatchId int=0

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			
	  --END
	 
	SELECT 
	VSF.AcademicId,
	--VSF.DivisionId,
	VSF.RollNo AS StudentRollNo,
	VSF.Name AS StudentName,
	VSF.Code AS StudentCode,
	ISNULL(SBS.SubjectBatchId,0) AS SubjectBatchId,
	ISNULL(SBS.AcademicId,0) AS SubjectBatchStudentAcademicId
	--VSF.BatchId,
	--ISNULL(SBS.SubjectBatchId,0)AS SubjectBatchId
	
      
  FROM 
       sStudent.vStudentFull VSF
       LEFT JOIN sAttendance.tSubjectBatchStudent SBS
       ON SBS.AcademicId=VSF.AcademicId AND SBS.SubjectBatchId=@rSubjectBatchId
       
       
     
       
             
  WHERE   
		
    
     ((VSF.DivisionId= @rDivisionId) OR (@rDivisionId=0)) 
     AND (VSF.StatusId != 3)
     AND VSF.BatchId = @rBatchId
     ORDER BY RollNo
      
        
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pSubjectRegisterStudentGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 --@rForMonth tinyint,
	 	 --@rForYear smallint,
	 	 --@rAttendanceTypeId tinyint,
	   @rSubjectId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		SN.AcademicId,
		--MY.MonthTitle AS ForMonthInWord,
		--MY.MonthNumber AS ForMonth, 
		--MY.YearNumber AS ForYear,
		(SELECT ISNULL(count(1),0) FROM sAttendance.tStudentRegister SR
		  WHERE  SR.AttendanceTypeId = 5 AND SR.IsPresent = 1  
		  AND SR.AcademicId = SN.AcademicId
		  AND SR.SubjectId = CS.SubjectId
		  )  AS PresentCount,
		(SELECT ISNULL(count(1),0) FROM sAttendance.tStudentRegister SR
		WHERE SR.AttendanceTypeId = 5 AND SR.IsPresent = 0	
		AND SR.AcademicId = SN.AcademicId
		 AND SR.SubjectId = CS.SubjectId
		)  AS AbsentCount,	 
		 
		 0  AS AveragePresence,
		0 AS AbsentDays,
		SM.Title AS SubjectName
		
	From sStudent.vStudentName SN
	INNER JOIN sSetup.tClassSubject CS
	ON SN.ClassId = CS.ClassId
	INNER JOIN sSetup.tSubjectMaster SM
	ON CS.SubjectId = SM.Id 
	--INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	--LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		--AND (MR.AttendanceTypeId=@rAttendanceTypeId) AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		--AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		(SN.AcademicId=@rAcademicId)
		AND SN.BatchId = @rBatchId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pSubjectRegisterStudentViewGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @rAttendanceTypeId tinyint
	   
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
declare @lSubjectGrid nvarchar(max)=''
	Select 
		@lSubjectGrid = @lSubjectGrid + '<tr>
	<td align="left" scope="col">' + isnull(SM.Title,'')  + '</td>
	<td align="left" scope="col">' +(SELECT convert(varchar,ISNULL(count(1),0) )FROM sAttendance.tStudentRegister SR  WHERE  SR.AttendanceTypeId = 5 AND SR.IsPresent = 1 AND SR.AcademicId = SN.AcademicId  AND SR.SubjectId = CS.SubjectId)+ '</td>
	<td align="left" scope="col">' + (SELECT convert(varchar,ISNULL(count(1),0)) FROM sAttendance.tStudentRegister SR WHERE SR.AttendanceTypeId = 5 AND SR.IsPresent = 0 AND SR.AcademicId = SN.AcademicId AND SR.SubjectId = CS.SubjectId)+ '</td>

	<tr>'
	From sStudent.vStudentName SN
	INNER JOIN sSetup.tClassSubject CS
	ON SN.ClassId = CS.ClassId
	INNER JOIN sSetup.tSubjectMaster SM
	ON CS.SubjectId = SM.Id 
	WHERE
		(SN.AcademicId=@rAcademicId)
		AND SN.BatchId = @rBatchId
		SELECT  isnull(@lSubjectGrid ,'') AS SubjectGrid
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 

CREATE OR ALTER PROCEDURE [sAttendance].[pSubjectwiseAttendanceGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
		 @rAttendanceDate date,
		 @rSubjectId int,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceGroupId int = 0,
	 	 @rPeriodNo int

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

    DECLARE @lIsOptional bit=0
	SELECT @lIsOptional = ISNULL(IsOptional,0) FROM sSetup.vClassSubject  WHERE SubjectId=@rSubjectId and classid = @rClassId
	IF (@lIsOptional=0)
	BEGIN
		IF(@rAttendanceGroupId=0)
		BEGIN
			SELECT 
				CASE WHEN SR.AcademicId > 0 THEN 'true' ELSE 'false' END AS AttendanceTaken, -- mantisid 0032631
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
				sStudent.vStudentAcademic SA 
				 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
				INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
				LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
					AND (SR.AttendanceTypeId=5)
					AND (SR.AttendanceDate=@rAttendanceDate)
					AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
					AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
					AND  ISNULL(SR.AttendanceGroupId,0) = @rAttendanceGroupId
				LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
				((SA.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA.OrgId = @rOrgId)
				AND (SA.BatchId = @rBatchID)
				AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
				AND (AD.AdmissionDate <= @rAttendanceDate)
				AND (SA.StatusId NOT IN(2,3))
				ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END
		ELSE
		BEGIN
			SELECT 
				CASE WHEN SR.AcademicId > 0 THEN 'true' ELSE 'false' END AS AttendanceTaken, -- mantisid 0032631
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
			sStudent.vStudentAcademic SA 
			 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
			INNER JOIN sAttendance.tAttendanceGroupStudent AGS ON AGS.AcademicId = SA.AcademicId 
				AND AGS.AttendanceGroupId=@rAttendanceGroupId
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
				AND (SR.AttendanceTypeId=5)
				AND (SR.AttendanceDate=@rAttendanceDate)
				AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
				AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
				AND SR.AttendanceGroupId=@rAttendanceGroupId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
			(SA.OrgId = @rOrgId)
			AND (SA.BatchId = @rBatchID)
			AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rAttendanceDate)
			AND (SA.StatusId NOT IN(2,3))
			ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END	
	END 
	ELSE 
	BEGIN
		IF(@rAttendanceGroupId=0)
		BEGIN
			SELECT 
				CASE WHEN SR.AcademicId > 0 THEN 'true' ELSE 'false' END AS AttendanceTaken, -- mantisid 0032631
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
				sStudent.vStudentAcademic SA 
				 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
				INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
				INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId= SA.AcademicId
				INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id= CS.SubjectId AND (SubjectId=@rSubjectId OR @rSubjectId=0)
				LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
					AND (SR.AttendanceTypeId=5)
					AND (SR.AttendanceDate=@rAttendanceDate)
					AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
					AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
					AND  ISNULL(SR.AttendanceGroupId,0) = @rAttendanceGroupId
				LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
				((SA.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA.OrgId = @rOrgId)
				AND (SA.BatchId = @rBatchID)
				AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
				AND (AD.AdmissionDate <= @rAttendanceDate)
				AND (SA.StatusId NOT IN(2,3))
				ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END
		ELSE
		BEGIN
			SELECT 
				CASE WHEN SR.AcademicId > 0 THEN 'true' ELSE 'false' END AS AttendanceTaken, -- mantisid 0032631
				SA.AcademicId,
				ISNULL(SA.RollNo,0) as RollNo,
				SA.Name,
				SA.Code,
				ISNULL(SR.IsPresent,'true') as IsPresent,
				ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
				case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
				SR.RepeatCount,
				EM.EmployeeId,
				EM.Code AS EmployeeCode,
				EM.EmployeeName,
				ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				SA.StudentId
			FROM 
			sStudent.vStudentAcademic SA 
			 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
			INNER JOIN sAttendance.tAttendanceGroupStudent AGS ON AGS.AcademicId = SA.AcademicId 
				AND AGS.AttendanceGroupId=@rAttendanceGroupId
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId= SA.AcademicId
				INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id= CS.SubjectId AND (SubjectId=@rSubjectId OR @rSubjectId=0)
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
				AND (SR.AttendanceTypeId=5)
				AND (SR.AttendanceDate=@rAttendanceDate)
				AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
				AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
				AND SR.AttendanceGroupId=@rAttendanceGroupId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
			(SA.OrgId = @rOrgId)
			AND (SA.BatchId = @rBatchID)
			AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rAttendanceDate)
			AND (SA.StatusId NOT IN(2,3))
			ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END 
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pTakeAttendanceList]

	@rOrgId int=0,
	@rOrgGroupId int=0,
	@rUserId bigint =0,
	@rUserSourceId bigint = 0,
	@rAttendanceEntry nvarchar(100),
	@rOrgGroupBatchId int =0,
	@rAttendanceDate Date = null,
	@rAttendanceTypeId int =0,
	@rAttendanceTagId int =0,
	@rAbsentReasonId int =0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rAttendanceEntry = 'Class Teacher')
	BEGIN
		SELECT DISTINCT CM.Id AS ClassId,DM.Id AS DivisionId,OM.Id AS OrgId,CM.DisplayTitle+'-'+DM.Title AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		CM.OrderIndex AS ClassOrderIndex,DM.OrderIndex AS DivisionOrderIndex,OM.OrderIndex AS OrganizationOrderIndex,
		convert(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND  BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=CM.Id AND A.DivisionId=DM.Id )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason
		FROM sSetup.tClassMaster CM 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM .Id
		WHERE DM.InchargeemployeeID= @rUserSourceId AND OM.OrgGroupId= @rOrgGroupId  AND CM.IsObsolete=0 AND DM.IsObsolete=0 
		ORDER BY OM.OrderIndex,CM.OrderIndex,DM.OrderIndex
	END
	ELSE IF(@rAttendanceEntry ='Academic Setup')
	BEGIN 
		SELECT DISTINCT TD.ClassId AS ClassId,TD.DivisionId AS DivisionId,OM.Id AS OrgId,TD.ClassTitle+'-'+TD.DivisionTitle AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		CONVERT(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND  BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=TD.ClassId AND A.DivisionId=TD.DivisionId )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason,
		TD.ClassOrderIndex AS ClassOrderIndex,OM.OrderIndex AS OrganizationOrderIndex 
		FROM sAcademic.vTeacherSubjectDivision TD
		INNER JOIN sSetup.tOrganizationMaster OM ON TD.OrgId = OM.Id
		WHERE TD.EmployeeId= @rUserSourceId  AND OM.OrgGroupId= @rOrgGroupId  AND CMIsObsolete=0  AND DMIsObsolete=0 
		ORDER BY OM.OrderIndex,TD.ClassOrderIndex
	END
	ELSE IF(@rAttendanceEntry ='User Access')
	BEGIN
		SELECT DISTINCT CM.Id AS ClassId,DM.Id AS DivisionId,OM.Id AS OrgId,CM.DisplayTitle+'-'+DM.Title AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		convert(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=CM.Id AND A.DivisionId=DM.Id )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason,
		CM.OrderIndex AS ClassOrderIndex,DM.OrderIndex AS DivisionOrderIndex,OM.OrderIndex AS OrganizationOrderIndex
		from sSetup.tClassMaster CM 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM.Id
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id 
		Where OM.OrgGroupId= @rOrgGroupId AND U.SourceTypeId=2005 AND U.UserId = @rUserId AND CM.IsObsolete=0 AND DM.IsObsolete=0 
		ORDER BY OM.OrderIndex,CM.OrderIndex,DM.OrderIndex
	END
	ELSE IF(@rAttendanceEntry = 'Class Teacher Batch')
	BEGIN
		SELECT DISTINCT CM.Id AS ClassId,DM.Id AS DivisionId,OM.Id AS OrgId,CM.DisplayTitle+'-'+DM.Title AS ClassDivision,OM.DisplayTitle AS OrganizationName,
		CM.OrderIndex AS ClassOrderIndex,DM.OrderIndex AS DivisionOrderIndex,OM.OrderIndex AS OrganizationOrderIndex,
		convert(bit,(SELECT CASE WHEN COUNT(*)>0 THEN 1 ELSE 0 END AS IsTakeAttendance  FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.tAcademic A ON A.Id = SR.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE AttendanceTypeId=@rAttendanceTypeId AND AttendanceDate=@rAttendanceDate AND  BM.OrgGroupBatchId = @rOrgGroupBatchId AND A.ClassId=CM.Id AND A.DivisionId=DM.Id )) AS IsTakeAttendance,
		(SELECT ATM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAttendanceTagMaster ATM ON ATM.Id = SR.AttendanceTagId WHere ATM.Id =@rAttendanceTagId GROUP BY ATM.Title) AS AttendanceTag,
		(SELECT ARM.Title FROM sAttendance.tStudentRegister SR INNER JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id =SR.AbsentReasonId  WHere  ARM.Id  =@rAbsentReasonId GROUP BY ARM.Title) AS AbsentReason
		FROM sSetup.tClassMaster CM 
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM .Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = DIE.BatchId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE DIE.EmployeeId= @rUserSourceId AND OM.OrgGroupId= @rOrgGroupId AND CM.IsObsolete=0 AND DM.IsObsolete=0 
		ORDER BY OM.OrderIndex,CM.OrderIndex,DM.OrderIndex
	END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pUpdateAttendance]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		-- @rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=1,	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rStudentId bigint=0
	 	-- @rExamId int,
	 	 --@rExamSubGroupId int=0
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
 

BEGIN 
 
	CREATE TABLE #tAcademicAttendance
	 (
	 AcademicId  bigint,	 
	 PresentCount int,
	 AbsentCount int 
	 )

   INSERT INTO #tAcademicAttendance
   (AcademicId,PresentCount,AbsentCount)
   	SELECT
   
   	SA.Id,
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND 
		SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId				
		) ,0)
		 AS PresentCount
		 , 
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate		
		AND 
		SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.AcademicId = SA.Id		
		),0)
		 AS AbsentCount 		
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 --INNER JOIN sAssessment.tExamMaster EM ON SA.BatchId = EM.BatchId AND SA.ClassId = EM.ClassId  AND EM.ExamSubGroupId = 	@rExamSubGroupId
		 --AND EM.BatchId = @rBatchId	 
         WHERE
 
		 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	     AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
         AND (SA.OrgId = @rOrgId)
         AND (SA.BatchId = @rBatchId)
        AND ((SA.Id =@rStudentId) OR (@rStudentId=0))
        
  
    INSERT INTO sStudent.tAcademicDetail
    (AcademicId,PresentDaysAnnual,TotalDaysAnnual,PercentageAttendance)
    SELECT RA.AcademicId,PresentCount,AbsentCount + PresentCount,(RA.PresentCount *100) / (RA.PresentCount + RA.AbsentCount) 
    --,SR.AcademicId,SR.ExamId
    FROM #tAcademicAttendance RA 
	LEFT JOIN sStudent.tAcademicDetail SR ON RA.AcademicId = SR.AcademicId 
	    WHERE SR.AcademicId IS NULL AND RA.PresentCount !=0
    
   
    
    UPDATE SR
    SET PresentDaysAnnual = RA.PresentCount,
         TotalDaysAnnual = RA.PresentCount + RA.AbsentCount,
         PercentageAttendance =(RA.PresentCount *100) / (RA.PresentCount + RA.AbsentCount) 
    FROM sStudent.tAcademicDetail SR INNER JOIN
    #tAcademicAttendance RA 
    ON  SR.AcademicId = RA.AcademicId
    WHERE (ISNULL(RA.PresentCount,0) + ISNULL(RA.AbsentCount,0)) > 0
    --INNER JOIN sAssessment.tExamMaster EM ON EM.Id = SR.ExamId
    --WHERE EM.ExamSubGroupId = @rExamSubGroupId
 
 SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pUpdateResultAttendance]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		 @rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=1,	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rExamId int,
	 	 @rExamSubGroupId int=0
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
 

BEGIN 
 
		
	CREATE TABLE #tResultAttendance
	 (
	 ExamId int,  
	 AcademicId  bigint,	 
	 PresentCount int,
	 AbsentCount int 
	 )

   INSERT INTO #tResultAttendance
   (ExamId,AcademicId,PresentCount,AbsentCount)
   	SELECT
   	EM.Id, 
   	SA.Id,
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND 
		SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId				
		) ,0)
		 AS PresentCount
		 , 
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate		
		AND 
		SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.AcademicId = SA.Id		
		),0)
		 AS AbsentCount 		
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 INNER JOIN sAssessment.tExamMaster EM ON SA.BatchId = EM.BatchId 
		 AND SA.ClassId = EM.ClassId
		 AND EM.ExamSubGroupId = 	@rExamSubGroupId
		 AND EM.BatchId = @rBatchId	 
		 --INNER JOIN sAssessment.tExamStatus ES ON ES.ExamId = EM.Id AND ES.DivisionId = SA.DivisionId -- commented by sarangi if new exam then attendance not Updated - mantisid - 0026854
         WHERE
   --       ((SM.Code=@rStudentCode) OR (@rStudentCode=''))         
		 --AND 
		 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	     AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
         AND (SA.OrgId = @rOrgId)
         AND (SA.BatchId = @rBatchId)
		 --AND ES.StatusId <> 504 -- commented by sarangi if result is generated then attendance not Updated - mantisid - 0026854
        
  
 -- Select * from #tResultAttendance
    INSERT INTO sAssessment.tStudentRemark
    (ExamId,AcademicId,PresentDays,TotalDays)
    SELECT RA.ExamId,RA.AcademicId,CONVERT(decimal(6, 2),PresentCount),CONVERT(decimal(6, 2),AbsentCount) + CONVERT(decimal(6, 2),PresentCount)
    --,SR.AcademicId,SR.ExamId
    FROM #tResultAttendance RA LEFT JOIN sAssessment.tStudentRemark SR
    ON RA.AcademicId = SR.AcademicId AND RA.ExamId = SR.ExamId
    WHERE SR.AcademicId IS NULL   AND SR.ExamId IS NULL
    
   
    
    UPDATE SR
    SET PresentDays = CONVERT(decimal(6, 2),RA.PresentCount),
         TotalDays = CONVERT(decimal(6, 2),RA.PresentCount) + CONVERT(decimal(6, 2),RA.AbsentCount)
    FROM sAssessment.tStudentRemark SR INNER JOIN
    #tResultAttendance RA 
    ON  SR.ExamId = RA.ExamId AND SR.AcademicId = RA.AcademicId
    --INNER JOIN sAssessment.tExamMaster EM ON EM.Id = SR.ExamId
    --WHERE EM.ExamSubGroupId = @rExamSubGroupId
 
 --Select * from sAssessment.tStudentRemark Order by UpdatedDateTime desc
 SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sAttendance].[pUpdateResultSubjectAttendance]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
	 	 @rAttendanceTypeId tinyint=5,	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rExamId int,
	 	 @rExamSubGroupId int=0,
		 @rClassSubjectId int=0
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN 
		
	CREATE TABLE #tResultSubjectAttendance
	 (
	 ExamId int,  
	 AcademicId  bigint,	 
	 ClassSubjectId int,
	 PresentCount int,
	 AbsentCount int 
	 )

   INSERT INTO #tResultSubjectAttendance
   (ExamId,AcademicId,ClassSubjectId,PresentCount,AbsentCount)
   	SELECT  DISTINCT
   	EM.Id, 
   	SA.Id,
	
		CS.Id AS ClassSubjectId,
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND 
		SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId	
		AND SR.SubjectId=@rClassSubjectId			
		) ,0)
		 AS PresentCount
		 , 
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate		
		AND 
		SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.AcademicId = SA.Id		
		AND SR.SubjectId=@rClassSubjectId
		),0)
		 AS AbsentCount 		
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 INNER JOIN sAssessment.tExamMaster EM ON SA.BatchId = EM.BatchId 
		 INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.Id
		 INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId=CS.SubjectId
		 AND SA.ClassId = EM.ClassId
		 AND EM.ExamSubGroupId = @rExamSubGroupId
		 AND EM.BatchId = @rBatchId	 
         WHERE
   		 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	     AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
         AND (SA.OrgId = @rOrgId)
         AND (SA.BatchId = @rBatchId)
        AND ((CS.Id=@rClassSubjectId) OR (@rClassSubjectId=0))
  
    --Select * from #tResultSubjectAttendance 
	--Where AcademicId=9999000001425
    INSERT INTO sAssessment.tResultDetailOther
    (ExamId,AcademicId,ClassSubjectId,Remark,TotalCount,PresentCount)
    SELECT RA.ExamId,RA.AcademicId,RA.ClassSubjectId,'',RA.AbsentCount + RA.PresentCount,RA.PresentCount
    FROM #tResultSubjectAttendance RA LEFT JOIN sAssessment.tResultDetailOther SR
    ON RA.AcademicId = SR.AcademicId AND RA.ExamId = SR.ExamId AND RA.ClassSubjectId=SR.ClassSubjectId
    WHERE SR.AcademicId IS NULL   
	--AND SR.ExamId IS NULL AND RA.ClassSubjectId IS NULL
  
    UPDATE RDO
    SET PresentCount = RA.PresentCount,
         TotalCount = RA.PresentCount + RA.AbsentCount
	--Select RA.PresentCount,RA.AcademicId,RA.PresentCount + RA.AbsentCount
    FROM sAssessment.tResultDetailOther RDO INNER JOIN
    #tResultSubjectAttendance RA 
    ON  
	RDO.ExamId = RA.ExamId 
	AND
	 RDO.AcademicId = RA.AcademicId 
	AND RDO.ClassSubjectId=RA.ClassSubjectId
   
 DROP TABLE #tResultSubjectAttendance
 SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pUpdateStudentAcademicAttendance]
	 	 
		 @rClassId int=0,
		 @rDivisionId int=0,
		 --@rStudentCode nvarchar(20)='',	
	 	 @rAttendanceTypeId tinyint=1,	 	 
		 @rFromAttendanceDate date='',
		 @rToAttendanceDate date='',
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 --@rExamId int,
	 	 --@rExamSubGroupId int=0,
	 	 @rTermScopeId int=0
	 	 
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
 

BEGIN 
 
		
	CREATE TABLE #tResultAttendance
	 (
	 ExamId int,  
	 AcademicId  bigint,	 
	 PresentCount int,
	 AbsentCount int 
	 )

   INSERT INTO #tResultAttendance
   (ExamId,AcademicId,PresentCount,AbsentCount)
   	SELECT
   	SA.BatchId, 
   	SA.Id,
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate
		AND 
		SR.AcademicId = SA.Id
		AND SR.IsPresent = 1
		AND SR.AttendanceTypeId = @rAttendanceTypeId				
		) ,0)
		 AS PresentCount
		 , 
	   ISNULL((SELECT count(AcademicId) FROM sAttendance.tStudentRegister SR	 
		WHERE		 
		 SR.AttendanceDate >= @rFromAttendanceDate
		AND SR.AttendanceDate <= @rToAttendanceDate		
		AND 
		SR.IsPresent = 0
		AND SR.AttendanceTypeId = @rAttendanceTypeId
		AND SR.AcademicId = SA.Id		
		),0)
		 AS AbsentCount 		
  FROM 
		 sStudent.tAcademic SA 
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SA.StudentId
		 AND SA.BatchId = @rBatchId	 
         WHERE
		 ((SA.ClassId=@rClassId) OR (@rClassId=0))
	     AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
         AND (SA.OrgId = @rOrgId)
         AND (SA.BatchId = @rBatchId)
        
  
  IF (@rTermScopeId = 1)
  BEGIN
    INSERT INTO sStudent.tAcademicDetail
    (AcademicId,TotalDaysTerm1,PresentDaysTerm1)
    SELECT RA.AcademicId,AbsentCount + PresentCount,PresentCount 
    FROM #tResultAttendance RA LEFT JOIN sStudent.tAcademicDetail SR
    ON RA.AcademicId = SR.AcademicId 
    WHERE SR.AcademicId IS NULL  
    
    UPDATE SR
    SET PresentDaysTerm1 = RA.PresentCount,
         TotalDaysTerm1 = RA.PresentCount + RA.AbsentCount
    FROM sStudent.tAcademicDetail SR INNER JOIN
    #tResultAttendance RA 
    ON 
    SR.AcademicId = RA.AcademicId
 END
 ELSE  IF (@rTermScopeId = 2)
  BEGIN
    INSERT INTO sStudent.tAcademicDetail
    (AcademicId,TotalDaysTerm2,PresentDaysTerm2)
    SELECT RA.AcademicId,AbsentCount + PresentCount,PresentCount 
    FROM #tResultAttendance RA LEFT JOIN sStudent.tAcademicDetail SR
    ON RA.AcademicId = SR.AcademicId 
    WHERE SR.AcademicId IS NULL  
    
    UPDATE SR
    SET PresentDaysTerm2 = RA.PresentCount,
         TotalDaysTerm2 = RA.PresentCount + RA.AbsentCount
    FROM sStudent.tAcademicDetail SR INNER JOIN
    #tResultAttendance RA 
    ON 
    SR.AcademicId = RA.AcademicId
 END
  ELSE  IF (@rTermScopeId = 5)
  BEGIN
    INSERT INTO sStudent.tAcademicDetail
    (AcademicId,TotalDaysAnnual,PresentDaysAnnual)
    SELECT RA.AcademicId,AbsentCount + PresentCount,PresentCount 
    FROM #tResultAttendance RA LEFT JOIN sStudent.tAcademicDetail SR
    ON RA.AcademicId = SR.AcademicId 
    WHERE SR.AcademicId IS NULL  
    
    UPDATE SR
    SET PresentDaysAnnual = RA.PresentCount,
         TotalDaysAnnual = RA.PresentCount + RA.AbsentCount
    FROM sStudent.tAcademicDetail SR INNER JOIN
    #tResultAttendance RA 
    ON 
    SR.AcademicId = RA.AcademicId
 END  
   
 
 SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pXMLDailyPresenceAdd]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int,
		@rPresentDate bigint,
		@rDivId int
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	----------------------- Exist Record Deleted
	--DELETE FROM sAttendance.tStudentRegister WHERE AcademicId IN (SELECT AcademicId FRom sStudent.tAcademic Where DivisionId =1) 
	--AND AttendanceDate = convert(date,Convert(nvarchar,@rPresentDate))
	
	DELETE SA FROM sAttendance.tStudentRegister SA INNER JOIN 
	(SELECT AcademicId FROM OPENXML (@intDoc, '/Table/DPR', 1)
	WITH
	(		
		AcademicId BigINT '@AcademicId'
	))A ON  SA.AcademicId = A.AcademicId AND SA.AttendanceDate=convert(date,Convert(nvarchar,@rPresentDate)) AND SA.AttendanceTypeId = 1
	
	-- New Record Entry	
	INSERT INTO sAttendance.tStudentRegister
	(
		AcademicId,
		EmployeeId,
		AttendanceTypeId,
		AttendanceDate,
		SubjectId,
		RepeatCount,
		IsPresent,
		AbsentReasonId,
		CreatedUserId,		
		CreatedDateTime
	)
	SELECT
		A.AcademicId,
		0,
		1,
		convert(date,Convert(nvarchar,@rPresentDate)),
		0,
		0,
		ISNULL(A.Present,0),
		0,
		9999000000003,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/DPR', 1)
	WITH
	(
		AcademicId bigint '@AcademicId',
		Present int '@Present'
	) A
	
	
	EXEC sp_xml_removedocument @intDoc
	--END
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pXMLPresenceAdd]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	----------------------- Exist Record Updated
		UPDATE sAttendance.tMonthlyRegister
		SET TotalCount = A.TotalCount,
			PresentCount = A.PresentCount,
			AbsentCount = A.AbsentCount,
			AveragePresence = A.AveragePresence,
			AbsentDays = A.AbsentDays
		FROM (SELECT AcademicId,TotalCount,PresentCount,AbsentCount,AveragePresence,AbsentDays,ForMonth,ForYear From
		OPENXML (@intDoc, '/Table/MPR',1) 
		WITH (
		AcademicId bigint,
		ForMonth smallint,
		ForYear smallint,
		TotalCount tinyint,
		PresentCount tinyint,
		AbsentCount tinyint,
		AveragePresence decimal(6,2),
		AbsentDays nvarchar(200))
		)A 
		WHERE A.AcademicId = sAttendance.tMonthlyRegister.AcademicId  AND
		A.ForMonth = sAttendance.tMonthlyRegister.ForMonth AND
		A.ForYear = sAttendance.tMonthlyRegister.ForYear
	
	-- New Record Entry	
	INSERT INTO sAttendance.tMonthlyRegister
	(
		AcademicId,
		AttendanceTypeId,
		SubjectId,
		ForMonth,
		ForYear,
		TotalCount,
		PresentCount,
		AbsentCount,
		AveragePresence,
		AbsentDays,
		UpdatedUserId,
		UpdatedDateTime
	)
	SELECT
		A.AcademicId,
		1,
		0,
		A.ForMonth,
		A.ForYear,
		A.TotalCount,
		A.PresentCount,
		A.AbsentCount,
		A.AveragePresence,
		A.AbsentDays,
		9999000000003,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/MPR', 1)
	WITH
	(
		AcademicId bigint '@AcademicId',
		ForMonth int '@ForMonth',
		ForYear int '@ForYear',
		TotalCount tinyint '@TotalCount',
		PresentCount tinyint '@PresentCount',
		AbsentCount tinyint '@AbsentCount',
		AveragePresence decimal(6,2) '@AveragePresence',
		AbsentDays nvarchar(200) '@AbsentDays'
	) A
	WHERE A.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tMonthlyRegister)
	
	
	EXEC sp_xml_removedocument @intDoc
	--END
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAttendance].[pYearlyRegisterGet]

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

	
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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

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


	((YR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	AND(A.BatchId=@rBatchId)
	AND((A.ClassId=@rClassId) OR (@rClassId=0))
	AND((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((SM.StatusId=@rStatus) OR (@rStatus=0))
	AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
	AND((YR.AttendanceTypeId = @rAttendanceTypeId) OR (@rAttendanceTypeId = 0))  -- MantisId : 0029240
	order by A.RollNo 
 
	 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sAttendance].[pYearlyRegisterStudentGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @rAttendanceTypeId tinyint = 1,
	 	 @rSubjectId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN
 
		DECLARE @PresentCount DECIMAL(10,2)
		DECLARE @AbsentCount DECIMAL(10,2)
		DECLARE @AveragePresence DECIMAL(10,2)
		DECLARE @AttendanceCount INT 
		DECLARE @AbsentDays nvarchar(max)
		DECLARE @AverageAbsent DECIMAL(10,2)

		SET @PresentCount = (select count(SR.AttendanceDate) AS TotalCount from sAttendance.tStudentRegister SR 
								INNER JOIN sStudent.tAcademic AC On AC.Id = SR.AcademicId AND AC.BatchId = @rBatchId 
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AC.BatchId	
							where SR.AcademicId=@rAcademicId AND SR.IsPresent = 1 AND (SR.AttendanceDate BETWEEN BM.FromDate AND BM.ToDate) AND SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)		
		
		SET @AbsentCount = (select count(SR.AttendanceDate) AS TotalCount from sAttendance.tStudentRegister SR 
								INNER JOIN sStudent.tAcademic AC On AC.Id = SR.AcademicId AND AC.BatchId = @rBatchId 
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AC.BatchId	
							where SR.AcademicId=@rAcademicId AND SR.IsPresent = 0 AND (SR.AttendanceDate BETWEEN BM.FromDate AND BM.ToDate) AND SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)		
		

		SET @AttendanceCount = (select count(SR.AttendanceDate) AS TotalCount from sAttendance.tStudentRegister SR 
								INNER JOIN sStudent.tAcademic AC On AC.Id = SR.AcademicId AND AC.BatchId = @rBatchId 
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AC.BatchId	
							where SR.AcademicId=@rAcademicId AND (SR.AttendanceDate BETWEEN BM.FromDate AND BM.ToDate) AND SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)		
		
		IF(@AttendanceCount<>0.00)		
		    SET @AveragePresence= (@PresentCount/@AttendanceCount)*100		
		ELSE
		 SET @AveragePresence= 0
		  
		 IF(@AttendanceCount<>0.00)		
		    SET @AverageAbsent= (@AbsentCount/@AttendanceCount)*100		
		ELSE
		 SET @AverageAbsent= 0


		 print @PresentCount
		 print @AbsentCount
		 print @AttendanceCount
		 print @AverageAbsent
END
	 Select 
		SN.AcademicId,
		ISNULL(CAST(@AttendanceCount AS int),0) AS TotalCount,
		ISNULL(CAST(@AttendanceCount AS int),0) AS AttendanceCount,
		ISNULL(CAST(@PresentCount AS int),0) AS PresentCount,
		ISNULL(CAST(@AbsentCount AS int),0) AS AbsentCount,
		ISNULL(@AveragePresence,0) AS AveragePresence,
		ISNULL(@AverageAbsent,0) As AverageAbsent
	From sStudent.vStudentName SN 
		--INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
		 
	WHERE
		(SN.AcademicId=@rAcademicId)  

    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sAttendance].[pYearlyRegisterUpdate]

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

BEGIN 

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

			SET @lQuery = 'UPDATE YR    
			SET Month' +   convert(nvarchar(15),@lCounter)+  ' = MM.Code,
			TotalDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.TotalCount,
			PresentDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.PresentCount 
			from sAttendance.tYearlyRegister YR
			INNER JOIN sAttendance.tMonthlyRegister MR
			ON YR.AcademicId = MR.AcademicId AND YR.AttendanceTypeId = MR.AttendanceTypeId
			AND MR.ForMonth = '  + convert(nvarchar(15),@lForMonth)  + ' AND MR.ForYear = ' + convert(nvarchar(15),@lForYear)  +
			' INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
			INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
			AND A.BatchId = ' +  convert(nvarchar(15),@rBatchId)  + ' AND A.ClassId = ' + convert(nvarchar(15),@lClassId) +
			+ ' AND ((A.DivisionId = ' + convert(nvarchar(15),@rDivisionId) + ') OR ( ' + convert(nvarchar(15),@rDivisionId) +' = 0)) ' +
			' INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id' +
			' WHERE YR.AttendanceTypeId = ' +  convert(nvarchar(5),@rAttendanceTypeId) + 
			' AND ((SM.StatusId = ' + convert(nvarchar(15),@rStatusId) + ') OR ( ' + convert(nvarchar(15),@rStatusId) + ' = 0 )) '
    
		print @lQuery
		execute(@lQuery)
	
	--IF 	(@lCounter = 1)
	--BEGIN
 
	--UPDATE YR    
 --   SET Month1  = MM.Title,TotalDays1 = MR.TotalCount,PresentDays1 = MR.PresentCount 
 --   from sAttendance.tYearlyRegister YR
 --   INNER JOIN sAttendance.tMonthlyRegister MR
 --   ON YR.AcademicId = MR.AcademicId
 --   AND MR.ForMonth = @lForMonth AND MR.ForYear = @lForYear
 --   INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
 --   INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
 --   AND A.BatchId = @rBatchId AND A.ClassId = @lClassId
    
	--END
	--ELSE IF (@lCounter = 2)
	--BEGIN

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

    UPDATE YR 
    SET TotalDays = (ISNULL(TotalDays1,0) + ISNULL(TotalDays2,0) + ISNULL(TotalDays3,0) + ISNULL(TotalDays4,0) + ISNULL(TotalDays5,0) + ISNULL(TotalDays6,0)
					+ ISNULL(TotalDays7,0) + ISNULL(TotalDays8,0) + ISNULL(TotalDays9,0) + ISNULL(TotalDays10,0) + ISNULL(TotalDays11,0) + ISNULL(TotalDays12,0)),
		PresentDays = ((ISNULL(PresentDays1,0) + ISNULL(PresentDays2,0) + ISNULL(PresentDays3,0) + ISNULL(PresentDays4,0) + ISNULL(PresentDays5,0) + ISNULL(PresentDays6,0)
					+ ISNULL(PresentDays7,0) + ISNULL(PresentDays8,0) + ISNULL(PresentDays9,0) + ISNULL(PresentDays10,0) + ISNULL(PresentDays11,0) + ISNULL(PresentDays12,0)))		
     FROM sAttendance.tYearlyRegister AS YR
    INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
    WHERE  A.BatchId = @rBatchId 
	AND YR.AttendanceTypeId = @rAttendanceTypeId -- MantisId : 0029240
	AND A.ClassId = @rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((SM.StatusId=@rStatusId) OR (@rStatusId=0))  
 
    UPDATE  YR SET YR.AvergeAttendance = (convert(decimal(5,2),(convert(decimal(5,2),YR.PresentDays)*100)/(convert(decimal(5,2),YR.TotalDays)))) 
    FROM sAttendance.tYearlyRegister AS YR
    INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id	
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
    WHERE YR.TotalDays <> 0 AND A.BatchId = @rBatchId 
	AND YR.AttendanceTypeId = @rAttendanceTypeId -- MantisId : 0029240
	AND A.ClassId = @rClassId AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
    AND ((SM.StatusId=@rStatusId) OR (@rStatusId=0))
		 
	DROP TABLE #tempClass
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pActivityLogAdd]
	 
		@rOrgGroupId int=0,
		@rOrgId int,
		@rUserId bigint,
		@rSessionId nvarchar(100),
		@rScreenId int,
		@rActivity nvarchar(500),
		@rRecordSourceId bigint,
		@rRecordDetail nvarchar(max),
		@rOSTypeId tinyint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO sAudit.tActivityLog
		(
			OrgGroupId,
			OrgId,
			UserId,
			SessionId,
			ScreenId,
			AuditDate,
			Activity,
			RecordSourceId,
			RecordDetail,
			OSTypeId
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgId,
			@rUserId,
			@rSessionId,
			@rScreenId,
			sCommon.fGetDate(),
			@rActivity,
			@rRecordSourceId,
			@rRecordDetail,
			@rOSTypeId
		)
		SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pActivityLogGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rUserName nvarchar(100),
	@rScreenName nvarchar(100),
	@rActivity nvarchar(500),
	@rFromDate date,
	@rToDate date,
	@rOSTypeId tinyint=0,
	@rIsHistory bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)
SET @rActivity = sCommon.fSearchStringGet(@rActivity)
SET @rToDate = DATEADD(day,1,@rToDate)

	IF(@rIsHistory = 1)
	BEGIN
       SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
				  WHEN AL.ScreenId=20745
				  THEN AL.Activity
				  WHEN AL.ScreenId=31257
				  THEN AL.Activity
				  WHEN AL.ScreenId IN (31341, 130)
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END)AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLogHistory AL
		   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
		   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
	END
	ELSE
	BEGIN
		SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
				  WHEN AL.ScreenId=20884
				  THEN AL.Activity
				  WHEN AL.ScreenId=20745
				  THEN AL.Activity
				  WHEN AL.ScreenId=31257
				  THEN AL.Activity
				  WHEN AL.ScreenId IN (31341, 130)
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END) AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLog AL
		   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
		   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pAuditAdd]
	@rTitle [nvarchar](100),
	@rAuditActionId [tinyint],
	@rDataId [bigint],
	@rCreatedUserId [bigint],
	@rAuditDate [datetime],
	@rTransactionId [bigint],
	@rAuditId [smallint] OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

    DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 'sAudit.tAudit', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAudit.tAudit
		(
			Id,
			Title,
			AuditActionId,			
			DataId,
			CreatedUserId,
			AuditDate,
			TransactionId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rAuditActionId,
			@rDataId,
			@rCreatedUserId,
			@rAuditDate,
			@rTransactionId
		)
		
		SET @rAuditId = @lNextNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pAuditHistoryDetailGet]
	@rUserId [int],
	@rAuditFromDate [datetime],
	@rAuditToDate [datetime],
	@rAuditTableId [int],
	@rDataId [int],
	@rAuditedFields [nvarchar](100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


SELECT TA.DataId AS DataID,
	   TAA.Title AS AuditAction,
	   ATF.FieldTitle AS FieldName,
       TA.AuditDate AS AuditDate,
       TU.LoginTitle AS UserName,
       AL.OldValue AS OldValue,
       AL.NewValue AS NewValue
 FROM sAudit.tAudit TA
 INNER JOIN sAudit.tAuditAction TAA ON TAA.Id = TA.AuditActionId 
 LEFT OUTER JOIN sSecurity.tUser TU ON TA.CreatedUserId = TU.Id 
 LEFT OUTER JOIN sAudit.tAuditLog AL ON AL.AuditId = TA.Id 
 LEFT OUTER JOIN sAudit.tAuditTableField ATF ON ATF.Id = AL.AuditTableFieldId 
 LEFT OUTER JOIN sAudit .tAuditTable  AT ON AT.Id = ATF.AuditTableId 
 WHERE   
 (AT.Id = @rAuditTableId AND TA.DataId = @rDataId AND  ATF.FieldTitle = @rAuditedFields)   
 AND (CAST(TA.AuditDate AS DATE) >= CAST(@rAuditFromDate AS DATE)  AND CAST(TA.AuditDate AS DATE) <= CAST(@rAuditToDate AS DATE)) 
 AND ((TA.CreatedUserId = @rUserId) OR (@rUserId = 0))


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pAuditTableAdd]
	@rSchemaName [nvarchar](20),
	@rTableName [nvarchar](100),
	@rCreatedUserId [bigint],
	@rAuditFieldDetailXml [nvarchar](max),
	@rIsDeleted [bit],
	@rId [int] OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--SELECT @rTableName
BEGIN
BEGIN TRAN

DECLARE @lStrLength Nvarchar(300)	
DECLARE @lTriggerName Nvarchar(300)
DECLARE @lTableFullName NVARCHAR(200)
SET @lTableFullName = @rSchemaName + '_' + @rTableName
SET @lTriggerName = 'gAudit_' + @lTableFullName + '_iud'


IF NOT EXISTS (SELECT Id FROM sAudit.tAuditTable WHERE TableTitle = @rTableName AND SchemaTitle = @rSchemaName)
BEGIN
	
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 'sAudit.tAuditTable', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAudit.tAuditTable
	(
		Id,
		SchemaTitle,
		TableTitle,
        IsObsolete,
		CreatedUserId,		
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime		
	)
	VALUES
	(
		@lNextNumber,
		@rSchemaName,
		@rTableName,
		0,
		@rCreatedUserId,
		sCommon.fGetDate(), 
		@rCreatedUserId,
		sCommon.fGetDate()
	)
	
	 IF NOT EXISTS (SELECT name FROM sysobjects
      WHERE name = @lTriggerName   AND type = 'TR')
		BEGIN
			EXEC sAudit.pAuditTableApplyTrigger @rSchemaName, @rTableName 
		END

END
ELSE
BEGIN
	
			
	 IF EXISTS (SELECT name FROM sysobjects
      WHERE name = @lTriggerName   AND type = 'TR')
		BEGIN
			SET @lStrLength =   'DROP TRIGGER ' + @rSchemaName + '.' + @lTriggerName
			EXEC sp_executesql @lStrLength
			--PRINT @lStrLength
			EXEC sAudit.pAuditTableApplyTrigger @rSchemaName, @rTableName
		END
	 ELSE
		BEGIN
			EXEC sAudit.pAuditTableApplyTrigger @rSchemaName, @rTableName 
		END

	 			
	IF (@rIsDeleted = 1)
		BEGIN
			UPDATE 	sAudit.tAuditTable
			SET IsObsolete = 1,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			WHERE TableTitle = @rTableName AND SchemaTitle = @rSchemaName
		    --PRINT @lTriggerName
			IF EXISTS (SELECT 1 FROM sys.objects WHERE name = @lTriggerName  AND type = 'TR')
				BEGIN
				    
					SET @lStrLength =   'ALTER TABLE ' + @rSchemaName + '.' + @rTableName + ' DISABLE TRIGGER ' + @lTriggerName 
					EXEC(@lStrLength)
					--PRINT @lStrLength
				END
		
		END
		
   ELSE
		BEGIN
			UPDATE 	sAudit.tAuditTable
			SET IsObsolete = 0,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			WHERE TableTitle = @rTableName AND SchemaTitle = @rSchemaName
			
			IF EXISTS (SELECT 1 FROM sys.objects WHERE name = @lTriggerName  AND type = 'TR')
				BEGIN
					SET @lStrLength =   'ALTER TABLE ' + @rSchemaName + '.' + @rTableName + ' ENABLE TRIGGER ' + @lTriggerName 
					EXEC sp_executesql @lStrLength
					--PRINT @lStrLength
				END
		
		END
   
   
END

SELECT  @rId = ID FROM sAudit.tAuditTable WHERE TableTitle = @rTableName AND SchemaTitle = @rSchemaName
EXEC [sAudit].[pAuditTableFieldAdd] @rId, @rAuditFieldDetailXml, @rCreatedUserId


COMMIT TRAN

	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pAuditTableApplyTrigger]
	@rSchemaName [nvarchar](20),
	@rTableName [nvarchar](100)
WITH EXECUTE AS CALLER
AS
BEGIN

DECLARE @lStrLengthOne NVARCHAR(MAX)
DECLARE @lStrLengthTwo NVARCHAR(MAX)
--ON [' + @rTableName + '] 
SET @lStrLengthOne = '
CREATE TRIGGER [gAudit_' + @rSchemaName + '_' + @rTableName + '_iud] 
 ON ' + @rSchemaName+ '.' + @rTableName + ' 
AFTER INSERT, UPDATE, DELETE AS 
SET NOCOUNT ON 
DECLARE @lAudId BIGINT, @lSqlQry  NVARCHAR(MAX), @lCount  TINYINT, @lC TINYINT, @lTblId SMALLINT, @lFldId INT, @lFldName NVARCHAR(100)
DECLARE @lTrnId  BIGINT, @lDataId dBigInt, @lUsrId dSmallInt, @lAudDt dDateTime, @lAuditId dSmallInt, @lNextNumber BIGINT, @lType NVARCHAR(5)
DECLARE @tFldRs TABLE
	(ID	INT IDENTITY(1, 1) PRIMARY KEY, TableID  SMALLINT, TableName NVARCHAR(100), FieldID INT, FieldName NVARCHAR(100))
INSERT INTO @tFldRs(TableID, TableName, FieldID, FieldName)
SELECT T.Id, T.TableTitle, F.Id, F.FieldTitle  FROM sAudit.tAuditTable T  INNER JOIN sAudit.tAuditTableField F ON T.Id = F.AuditTableId
WHERE F.IsObsolete = 0 AND T.TableTitle = ''' + @rTableName + ''' AND T.SchemaTitle = ''' + @rSchemaName + '''
IF NOT EXISTS(SELECT 1 FROM @tFldRs)
 BEGIN
  RETURN
 END
SET @lCount = SCOPE_IDENTITY()
SET @lC = 1
SELECT TOP 1 @lTblId = TableID FROM @tFldRs
SELECT  @lTrnId = transaction_id FROM sys.dm_tran_current_transaction
IF EXISTS (SELECT 1 FROM INSERTED)IF EXISTS (SELECT 1 FROM DELETED) SELECT @lType = ''U''ELSE SELECT @lType = ''I''ELSE SELECT @lType = ''D'' /*Inserted*/ IF @lType = ''I''
BEGIN
 SELECT @lDataId = I.ID, @lUsrId = I.CreatedUserId, @lAudDt = sCommon.fGetDate() FROM INSERTED I LEFT JOIN DELETED D ON I.ID = D.ID WHERE D.ID IS NULL 
EXECUTE sAudit.pAuditAdd ''Insertion'', 1, @lDataId, @lUsrId, @lAudDt, @lTrnId, @lAuditId OUT
IF @@ROWCOUNT > 0
  BEGIN
	SET @lAudId = @lAuditId
	SELECT * INTO #Inserted FROM INSERTED
	 WHILE(@lC <= @lCount)
		BEGIN
			SELECT @lFldId = FieldID, @lFldName = FieldName  FROM @tFldRs  WHERE ID = @lC			        
			EXECUTE sCommon.pTableRowIdGet ''sAudit.tAudit'', 0, 1, 1,@outNextNumber = @lNextNumber output
			SET @lSqlQry = '' INSERT INTO sAudit.tAuditLog(Id, AuditId, AuditTableFieldId, NewValue)
		    SELECT '' + CAST(@lNextNumber AS NVARCHAR(20)) + '', '' + CAST(@lAudId AS NVARCHAR(20)) + '', ''	+ CAST(@lFldId AS NVARCHAR(20)) + '', 
			  I.'' + @lFldName + ''  FROM #Inserted I''
	    	EXECUTE (@lSqlQry)
			SET @lC = @lC + 1
		END
	END
END
/*Updated*/
IF @lType = ''U''
BEGIN
SELECT @lDataId = I.ID, @lUsrId = I.CreatedUserId, @lAudDt = sCommon.fGetDate() FROM DELETED D INNER JOIN INSERTED I ON D.ID = I.ID	   
EXECUTE sAudit.pAuditAdd ''Updation'', 2, @lDataId, @lUsrId, @lAudDt, @lTrnId, @lAuditId OUT		   
IF @@ROWCOUNT > 0
	BEGIN
	 SET @lAudId = @lAuditId 
	 SELECT * INTO #UpdInserted FROM INSERTED
	 SELECT * INTO #UpdDeleted FROM DELETED
	 WHILE(@lC <= @lCount)
	 	BEGIN
	 		SELECT @lFldId = FieldID, @lFldName = FieldName FROM @tFldRs WHERE ID = @lC			        
			EXECUTE sCommon.pTableRowIdGet ''sAudit.tAudit'', 0, 1, 1,@outNextNumber = @lNextNumber output			     
			SET @lSqlQry = '' INSERT INTO sAudit.tAuditLog(Id, AuditId, AuditTableFieldId, OldValue, NewValue)
			   SELECT '' + CAST(@lNextNumber AS NVARCHAR(20)) + '', '' + CAST(@lAudId AS NVARCHAR(20)) + '', ''	+ CAST(@lFldId AS NVARCHAR(20)) + '', D.'' + @lFldName + '', I.'' + @lFldName +
				  ''  FROM #UpdInserted I FULL OUTER JOIN #UpdDeleted D ON I.ID = D.ID
					WHERE I.'' + @lFldName + '' <> D.'' + @lFldName + '' OR (I.''+ @lFldName + '' IS NULL AND D.'' + @lFldName + '' IS NOT NULL)'' + '' OR (I.''+ @lFldName + '' IS NOT NULL AND D.'' +  @lFldName + '' IS NULL)''
			EXECUTE (@lSqlQry)
			SET @lC = @lC + 1
			END
	END
END'
/*Deleted*/
SET @lStrLengthTwo =
' IF @lType = ''D''
BEGIN
SELECT @lDataId = D.ID, @lUsrId = D.CreatedUserId, @lAudDt = sCommon.fGetDate()FROM DELETED D LEFT JOIN INSERTED I ON D.ID = I.ID WHERE I.ID IS NULL
EXECUTE sAudit.pAuditAdd ''Deletion'', 3, @lDataId, @lUsrId, @lAudDt, @lTrnId, @lAuditId OUT
IF @@ROWCOUNT > 0
	BEGIN
		SET @lAudId = @lAuditId 
		SELECT * INTO #Deleted FROM DELETED
		WHILE(@lC <= @lCount)
			BEGIN
				SELECT @lFldId = FieldID, @lFldName = FieldName FROM @tFldRs WHERE ID = @lC			        
				EXECUTE  sCommon.pTableRowIdGet ''sAudit.tAudit'', 0, 1, 1,@outNextNumber = @lNextNumber output			     
				SET @lSqlQry = '' INSERT INTO sAudit.tAuditLog(Id, AuditId, AuditTableFieldId, OldValue)
							   SELECT '' + CAST(@lNextNumber AS NVARCHAR(20)) + '', 
							   '' + CAST(@lAudId AS NVARCHAR(20)) + '', 
									  ''	+ CAST(@lFldId AS NVARCHAR(20)) + '', 
									  D.'' + @lFldName + 
							  ''  FROM #Deleted D''
				EXECUTE (@lSqlQry)
				SET @lC = @lC + 1
			END
	END

DELETE sAudit.tAudit  
  FROM sAudit.tAudit A 
	   LEFT JOIN sAudit.tAuditLog V 
			  ON A.Id = V.AuditId 
 WHERE V.AuditId IS NULL
 END
' 
 

--SELECT @lStrLengthOne + @lStrLengthTwo
EXEC(@lStrLengthOne + @lStrLengthTwo)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pAuditTableDataIdGet]
	@rTableId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT DISTINCT AT.Id AS TableId, 
				A.DataId
FROM sAudit.tAuditTable  AT
LEFT OUTER JOIN sAudit.tAuditTableField ATF ON AT.Id = ATF.AuditTableId
LEFT OUTER JOIN sAudit.tAuditLog AL ON ATF.Id = AL.AuditTableFieldId
INNER JOIN sAudit.tAudit A ON AL.AuditId = A.Id
WHERE AT.Id = @rTableId
ORDER BY A.DataId


SELECT AT.Id AS TableId,        
       ATF.FieldTitle 
FROM sAudit.tAuditTable AT
INNER JOIN sAudit.tAuditTableField ATF ON AT.Id = ATF.AuditTableId
WHERE AT.Id = @rTableId
ORDER BY ATF.FieldTitle

      
       

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pAuditTableDropTrigger]
	@rSchemaName [nvarchar](20),
	@rTableName [nvarchar](100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
DECLARE @lStrLength Nvarchar(300)
DECLARE @lTriggerName Nvarchar(300)
DECLARE @lTableId Int

BEGIN TRY 
SELECT @lTableId = Id FROM sAudit.tAuditTable  WHERE SchemaTitle = @rSchemaName AND @rTableName = @rTableName

IF EXISTS (SELECT 1 FROM sAudit.tAuditTable WHERE SchemaTitle = @rSchemaName AND @rTableName = @rTableName)
BEGIN
	UPDATE sAudit.tAuditTable SET IsObsolete = 1 WHERE Id = @lTableId
	UPDATE sAudit.tAuditTableField  SET IsObsolete = 1 WHERE AuditTableId = @lTableId
END

SET @lTriggerName = 'gAudit_' + @rSchemaName + '_' + @rTableName + '_iud'

IF EXISTS (SELECT 1
		     FROM sys.objects 				  
			WHERE name = @lTriggerName  
				  AND type = 'TR')
	BEGIN
		SET @lStrLength =   'DROP TRIGGER ' + @rSchemaName + '.' + @lTriggerName
		EXEC sp_executesql @lStrLength
		
	END
SELECT  1
END TRY
BEGIN CATCH
 SELECT   -1
END CATCH


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pAuditTableFieldAdd]
	@rTableId [smallint],
	@rAuditFieldDetailXml [nvarchar](max),
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
   
 IF EXISTS (SELECT 1 FROM sAudit.tAuditTableField WHERE AuditTableId = @rTableId)
    BEGIN
	 UPDATE sAudit.tAuditTableField SET IsObsolete = 1 WHERE AuditTableId = @rTableId	     
    END
	
	DECLARE @lAuditTableFieldCurrentId BIGINT
	DECLARE @loIdoc INT
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rAuditFieldDetailXml
	EXECUTE sCommon.pTableRowIdGet 'sAudit.tAuditTableField', 0, 1, 1,@outNextNumber = @lAuditTableFieldCurrentId output
	DECLARE @lCount INT
	
	INSERT INTO sAudit.tAuditTableField
		(ID, AuditTableId, FieldTitle, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsObsolete)
	
		SELECT 
		@lAuditTableFieldCurrentId + ROW_NUMBER() OVER(ORDER BY FieldTitle),  
		@rTableId,
		FieldTitle, 				
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rCreatedUserId,
		sCommon.fGetDate(),
		IsObsolete
		FROM OPENXML (@loIdoc, '/AuditTable/AuditTableFieldData', 1)
		WITH 
		( 		
			FieldTitle  NVARCHAR(100), 
			IsObsolete  BIT			
		)
		
		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/AuditTable/AuditTableFieldData', 1)
				 WITH (FieldTitle NVARCHAR(100))
		SET @lAuditTableFieldCurrentId  = @lCount + @lAuditTableFieldCurrentId 
		
		EXECUTE sCommon.pTableRowIdModify @rTableTitle =  'sAudit.tAuditTableField', @rCurrentNumber = @lAuditTableFieldCurrentId 
				
		
		SELECT 1 AS Result

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pAuditTableGet]
	@rSchemaName [nvarchar](50),
	@rTableName [nvarchar](100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT Id AS TableId,
       TableTitle AS TableName, 
       SchemaTitle AS SchemaName,
       IsObsolete AS IsDeleted
FROM sAudit.tAuditTable 
       WHERE IsObsolete = 0
       AND SchemaTitle = @rSchemaName OR TableTitle  LIKE '%' + @rTableName + '%'
       ORDER BY TableTitle
       
       
SELECT AuditTableId AS TableId,
       ATF.Id AS FieldId,
       ATF.FieldTitle AS FieldTitle,
       ATF.IsObsolete AS IsDeletedField
FROM sAudit.tAuditTableField ATF
INNER JOIN sAudit.tAuditTable AT
ON AT.Id = ATF.AuditTableId 
WHERE AT.IsObsolete = 0 AND ATF.IsObsolete = 0
       AND AT.SchemaTitle = @rSchemaName AND AT.TableTitle  LIKE '%' + @rTableName + '%'
       ORDER BY ATF.FieldTitle 
      
       

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pChangeLogGet]
	 @rOrgGroupId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rScreenId nvarchar(50)='',
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rFromDate date='',
	 @rToDate date=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
		if @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
			SELECT S.Title AS ScreenName,'Employee' AS SourceType, CL.ChangeRemark,EM.FirstName + ' ' +EM.LastName AS SourceName,EM.Code AS SourceId,
			CONVERT(VARCHAR(20),CL.CreatedDateTime,103)+' '+CONVERT(VARCHAR(20),CONVERT(TIME,CL.CreatedDateTime),100) AS CreatedDateTime
		 FROM sAudit.ChangeLog CL 
			INNER JOIN sSecurity.tScreen S ON S.Id = CL.ScreenId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = CL.SourceId 
			WHERE ((S.Title Like '%'+ @rScreenId+'%')OR(ISNULL(@rScreenId,'') = '')) AND CL.SourceTypeId = 95 
			AND ((CL.SourceId  = @rUserSourceId)OR(@rUserSourceId=0)) AND ((EM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND (( convert(DATE,CL.CreatedDateTime,102) >= @rFromDate) OR (@rFromDate='')) 
			AND (( convert(DATE,CL.CreatedDateTime,102) <= @rToDate) OR (@rToDate='')) 
			AND ISNULL(EM.IsOtherUser,0) = 0 
			ORDER BY AutoId 
	END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 BEGIN
 
		SELECT S.Title AS ScreenName,'Student' AS SourceType, CL.ChangeRemark, SA.Name As SourceName,SA.Code AS SourceId,
		CONVERT(VARCHAR(20),CL.CreatedDateTime,103)+' '+CONVERT(VARCHAR(20),CONVERT(TIME,CL.CreatedDateTime),100) AS CreatedDateTime
		FROM sAudit.ChangeLog CL 
		INNER JOIN sSecurity.tScreen S ON S.Id = CL.ScreenId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = CL.SourceId 
		WHERE ((S.Title Like '%'+ @rScreenId+'%')OR(ISNULL(@rScreenId,'') = '')) AND CL.SourceTypeId = 2003 
		AND ((CL.SourceId  = @rUserSourceId)OR(@rUserSourceId=0))
		AND ((SA.OrgId = @rOrgId)OR(@rOrgId=0))
		AND ((SA.BatchId = @rBatchId)OR(@rBatchId=0))
		AND (( convert(DATE,CL.CreatedDateTime,102) >= @rFromDate) OR (@rFromDate='')) 
		AND (( convert(DATE,CL.CreatedDateTime,102) <= @rToDate) OR (@rToDate='')) 
		ORDER BY AutoId 

 END
  ELSE -- For All Record 
 BEGIN
 
		SELECT S.Title AS ScreenName,'Employee' AS SourceType, CL.ChangeRemark,EM.FirstName + ' ' +EM.LastName AS SourceName,EM.Code AS SourceId,
			CONVERT(VARCHAR(20),CL.CreatedDateTime,103)+' '+CONVERT(VARCHAR(20),CONVERT(TIME,CL.CreatedDateTime),100) AS CreatedDateTime
		 FROM sAudit.ChangeLog CL 
			INNER JOIN sSecurity.tScreen S ON S.Id = CL.ScreenId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = CL.SourceId 
			WHERE ((S.Title Like '%'+ @rScreenId+'%')OR(ISNULL(@rScreenId,'') = '')) AND CL.SourceTypeId = 95 
			AND ((CL.SourceId  = @rUserSourceId)OR(@rUserSourceId=0)) AND ((EM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND (( convert(DATE,CL.CreatedDateTime,102) >= @rFromDate) OR (@rFromDate='')) 
			AND (( convert(DATE,CL.CreatedDateTime,102) <= @rToDate) OR (@rToDate='')) 
			AND ISNULL(EM.IsOtherUser,0) = 0 
	 
	 UNION ALL 

		SELECT S.Title AS ScreenName,'Student' AS SourceType, CL.ChangeRemark, SA.Name As SourceName,SA.Code AS SourceId,
		CONVERT(VARCHAR(20),CL.CreatedDateTime,103)+' '+CONVERT(VARCHAR(20),CONVERT(TIME,CL.CreatedDateTime),100) AS CreatedDateTime
		FROM sAudit.ChangeLog CL 
		INNER JOIN sSecurity.tScreen S ON S.Id = CL.ScreenId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = CL.SourceId 
		WHERE ((S.Title Like '%'+ @rScreenId+'%')OR(ISNULL(@rScreenId,'') = '')) AND CL.SourceTypeId = 2003 
		AND ((CL.SourceId  = @rUserSourceId)OR(@rUserSourceId=0))
		AND ((SA.OrgId = @rOrgId)OR(@rOrgId=0))
		AND ((SA.BatchId = @rBatchId)OR(@rBatchId=0))
		AND (( convert(DATE,CL.CreatedDateTime,102) >= @rFromDate) OR (@rFromDate='')) 
		AND (( convert(DATE,CL.CreatedDateTime,102) <= @rToDate) OR (@rToDate='')) 
		
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pOperationLogAdd]
	
	@rScreenId int,
	@rSourceId int,
	@rSourceTypeId smallint,
	@rOperationId tinyint,
	@rOperationRemark nvarchar(max),
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	INSERT INTO sAudit.tOperationLog
		(
			ScreenId,
			OperationId,
			SourceTypeId,			
			SourceId,
			OperationRemark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rScreenId,
			@rOperationId,
			@rSourceTypeId,
			@rSourceId,
			@rOperationRemark,
			@rCreatedUserId,
			@rCreatedDateTime
		)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pOperationLogGet]
	
	@rScreenId int,
	@rSourceId int,
	@rOperationId tinyint,
	@rFromDate date,
	@rToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
		OL.OperationRemark,
		OM.Title AS Operation,
		U.DisplayTitle AS UserName,
		OL.CreatedDateTime,
		CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision
	From
		sAudit.tOperationLog OL
		INNER JOIN sAudit.tOperationMaster OM ON OM.Id = OL.OperationId
		INNER JOIN sSecurity.tUser U ON U.Id = OL.CreatedUserId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = OL.SourceId 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
	Where
		((OL.ScreenId = @rScreenId) OR (@rScreenId = 0)) 
		AND (CONVERT(Date,OL.CreatedDateTime) >= @rFromDate)
		AND (CONVERT(Date,OL.CreatedDateTime) <= @rToDate)
		AND ((OM.Id = @rOperationId) OR (@rOperationId = 0))
		AND ((DM.Id = @rSourceId) OR (@rSourceId = 0))
	ORDER BY
		OL.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pStockOperationLogAdd]
	
	@rScreenId int,
	@rSourceId int,
	@rSourceTypeId smallint,
	@rOperationId tinyint,
	@rOperationRemark nvarchar(max),
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	INSERT INTO sAudit.tStockOperationLog
		(
			ScreenId,
			OperationId,
			SourceTypeId,			
			SourceId,
			OperationRemark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rScreenId,
			@rOperationId,
			@rSourceTypeId,
			@rSourceId,
			@rOperationRemark,
			@rCreatedUserId,
			@rCreatedDateTime
		)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pStockOperationLogGet]
	
	@rScreenId int,
	@rItemCode nvarchar(max),
	@rFromDate date,
	@rToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rItemCode = sCommon.fSearchStringGet(@rItemCode)
	Select 
		OL.OperationRemark,
		U.DisplayTitle AS UserName,
		OL.CreatedDateTime,
		SIM.Code,
		SLM.Title
	From
		sAudit.tStockOperationLog OL
		--not used in this issue 26757 but added because in future want logs in other stock screens.
		--INNER JOIN sAudit.tOperationMaster OM ON OM.Id = OL.OperationId
		INNER JOIN sSecurity.tUser U ON U.Id = OL.CreatedUserId
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=OL.SourceId
		INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id=SIM.StoreLocationId
	Where
		((OL.ScreenId = @rScreenId) OR (@rScreenId = 0)) 
		AND ((SIM.Code like @rItemCode) OR (ISNULL(@rItemCode,'')=''))
		AND (CONVERT(Date,OL.CreatedDateTime) >= @rFromDate)
		AND (CONVERT(Date,OL.CreatedDateTime) <= @rToDate)
	ORDER BY
		OL.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pSysSuperAdminActivityLogGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rUserName nvarchar(100),
	@rScreenName nvarchar(100),
	@rActivity nvarchar(500),
	@rFromDate date,
	@rToDate date,
	@rOSTypeId tinyint=0,
	@rIsHistory bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)
	SET @rActivity = sCommon.fSearchStringGet(@rActivity)
	SET @rToDate = DATEADD(day,1,@rToDate)

	IF(@rIsHistory = 1)
	BEGIN
		SELECT 
		        AL.OrgGroupId,
		        AL.OrgId,
		        OM.Title AS OrganizationName,
		        AL.UserId,
				U.DisplayTitle AS UserName,
				U.LoginTitle,
				U.SessionId,
				S.Title AS ScreenName,
				AL.AuditDate,
				SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1)) AS Activity,
				ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
				ISNULL(AL.RecordDetail,'') AS RecordDetail,
				ISNULL(OS.Title,'') AS OSType
				
		   FROM 
			   sAudit.tActivityLogHistory AL
			   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
			   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
			   INNER JOIN sSecurity.tSysSuperScreen S ON S.Id = AL.ScreenId
			   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
		   WHERE AL.UserId = 1
			   AND AL.OrgGroupId = @rOrgGroupId
			   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
			   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
			   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
			   AND ((AL.Activity LIKE '%' + @rActivity) OR (@rActivity = ''))
			   AND (AL.AuditDate >= @rFromDate)
			   AND (AL.AuditDate <= @rToDate)
			   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
		   ORDER BY 
				AL.AuditDate DESC
	END

	ELSE
	BEGIN 
		SELECT 
		        AL.OrgGroupId,
		        AL.OrgId,
		        OM.Title AS OrganizationName,
		        AL.UserId,
				U.DisplayTitle AS UserName,
				U.LoginTitle,
				U.SessionId,
				S.Title AS ScreenName,
				S.Id As ScreenId,
				AL.AuditDate,
				SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1)) AS Activity,
				ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
				ISNULL(AL.RecordDetail,'') AS RecordDetail,
				ISNULL(OS.Title,'') AS OSType
				
		   FROM 
			   sAudit.tActivityLog AL
			   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
			   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
			   INNER JOIN sSecurity.tSysSuperScreen S ON S.Id = AL.ScreenId
			   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
		   WHERE AL.UserId = 1
			   AND AL.OrgGroupId = @rOrgGroupId
			   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
			   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
			   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
			   AND ((AL.Activity LIKE '%' + @rActivity) OR (@rActivity = ''))
			   AND (AL.AuditDate >= @rFromDate)
			   AND (AL.AuditDate <= @rToDate)
			   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
		   ORDER BY 
				AL.AuditDate DESC
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sAudit].[pTableFieldGet]
	@rSchemaName [nvarchar](100),
	@rTableName [nvarchar](100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


SELECT ORDINAL_POSITION AS Id, COLUMN_NAME AS FieldName 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = @rTableName
AND TABLE_SCHEMA = @rSchemaName

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pActionAdd]
	 
	        @rId bigint
	       ,@rNumber nvarchar(20)   
           ,@rDocumentSourceTypeId bigint 
           ,@rDocumentSourceId bigint 
           ,@rActionDetail nvarchar(200)
           ,@rActionTypeId int
           ,@rAssignedToEmployeeId bigint
           ,@rActionDueDate date
           ,@rActionStatusId int
           ,@rActionDate date
           ,@rCreatedUserId bigint  
           ,@rStoreLocationId int                    
           ,@rOrgId smallint 
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION
	 IF(@rId = 0)	
 BEGIN
  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1013,@rStoreLocationId = @rStoreLocationId, @rNextNumber  = @rNumber OUTPUT

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

		IF @rNumber = '-300'
	  BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	  END
	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sBi.tAction', 0, 1, 1,@outNextNumber = @lNextNumber output	

INSERT INTO [sBi].[tAction]
           ([Id]
           ,[Number]
           ,[DocumentSourceTypeId]
           ,[DocumentSourceId]
           ,[ActionDetail]
           ,[ActionTypeId]
           ,[AssignedToEmployeeId]
           ,[ActionDueDate]
           ,[ActionStatusId]
           ,[ActionDate]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[StoreLocationId]
           ,[OrgId])
     VALUES
           (
           @lNextNumber
           ,@rNumber
           ,@rDocumentSourceTypeId
           ,@rDocumentSourceId
           ,@rActionDetail
           ,@rActionTypeId
           ,@rAssignedToEmployeeId
           ,@rActionDueDate
           ,@rActionStatusId
           ,@rActionDate 
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,0 
           ,sCommon.fGetDate()
           ,@rStoreLocationId
           ,@rOrgId
           )


		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sBi].[tAction] 
	    SET
		   -- DocumentSourceTypeId=@rDocumentSourceTypeId
		   --,DocumentSourceId=@rDocumentSourceId
	       ActionDetail=@rActionDetail
	       ,ActionTypeId=@rActionTypeId
	       ,AssignedToEmployeeId=@rAssignedToEmployeeId
	       ,ActionDueDate=@rActionDueDate
	       ,ActionStatusId=@rActionStatusId
	       ,ActionDate=@rActionDate         				 
		   ,UpdatedUserId = @rCreatedUserId
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pActionDetailGet]

           @rOrgId smallint,
           @rDocumentSourceId bigint,
           @rDocumentSourceTypeId int,
           @rStoreLocationId int,
           @rIsView bit,
           @rAuditNumber nvarchar(50),
           @rAuditType nvarchar(50)
AS
SET NOCOUNT ON

BEGIN

IF(@rIsView = 0)
BEGIN
Declare @lAuditId bigint
IF(@rDocumentSourceTypeId = 1020)
SELECT @lAuditId = DocumentSourceId FROM sBi.tFinding WHERE Id = @rDocumentSourceId
 
SELECT ISNULL(A.Id,0) AS Id,
	   ISNULL(A.Number,'') AS Number,
	   A.ActionDetail,
	   ISNULL(ATM.Id,0) AS ActionTypeId,
	   ISNULL(ATM.Title,'') AS ActionType,
	   ISNULL(EM.Id,0) AS AssignedToEmployeeId,
	   ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
	   (ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'')) AS AssignedToEmployeeName,
	   ISNULL(A.ActionDueDate,'01-01-0001') AS ActionDueDate,
	   ISNULL(ASM.Id,0) AS ActionStatusId,
	   ISNULL(ASM.Title,'') AS ActionStatus, 
	   ISNULL(A.ActionDate,'01-01-0001') AS ActionDate,
	   ISNULL(F.Id,0) AS Id,
	   '' AS FindingType,
	   '' AS FindingDate,
	   '' AS FindingNumber,
	   @rAuditNumber AS AuditNumber,
	   @rAuditType AS AuditType,
	   A.DocumentSourceTypeId 
	   from sBi.tAction A 
LEFT JOIN sBi.tActionTypeMaster ATM ON ATM.Id=A.ActionTypeId
LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = A.AssignedToEmployeeId
LEFT JOIN sBi.tActionStatusMaster ASM ON ASM.Id=A.ActionStatusId
LEFT JOIN sBi.tFinding F ON F.Id = A.DocumentSourceId 
LEFT JOIN sBi.tFindingTypeMaster FTM ON FTM.Id=F.FindingTypeId 

WHERE (A.DocumentSourceId = @rDocumentSourceId AND A.DocumentSourceTypeId = 1018)
	AND A.OrgId = @rOrgId
	AND A.StoreLocationId=@rStoreLocationId
	AND ISNULL(EM.IsOtherUser,0) = 0 
	
	
UNION  
	
	SELECT ISNULL(A.Id,0) AS Id,
	   ISNULL(A.Number,'') AS Number,
	   A.ActionDetail,
	   ISNULL(ATM.Id,0) AS ActionTypeId,
	   ISNULL(ATM.Title,'') AS ActionType,
	   ISNULL(EM.Id,0) AS AssignedToEmployeeId,
	   ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
	   (ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'')) AS AssignedToEmployeeName,
	   ISNULL(A.ActionDueDate,'01-01-0001') AS ActionDueDate,
	   ISNULL(ASM.Id,0) AS ActionStatusId,
	   ISNULL(ASM.Title,'') AS ActionStatus, 
	   ISNULL(A.ActionDate,'01-01-0001') AS ActionDate,
	   ISNULL(F.Id,0) AS Id,
	   ISNULL(FTM.Title,'') AS FindingType,
	   ISNULL(F.FindingDate,'') AS FindingDate,
	    ISNULL(F.Number,'') AS FindingNumber,
	   @rAuditNumber AS AuditNumber,
	   @rAuditType AS AuditType ,
	   A.DocumentSourceTypeId
	   from sBi.tAction A 
LEFT JOIN sBi.tFinding F ON F.Id = A.DocumentSourceId  
LEFT JOIN sBi.tActionTypeMaster ATM ON ATM.Id=A.ActionTypeId
LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = A.AssignedToEmployeeId
LEFT JOIN sBi.tActionStatusMaster ASM ON ASM.Id=A.ActionStatusId
LEFT JOIN sBi.tFindingTypeMaster FTM ON FTM.Id=F.FindingTypeId 

WHERE 
--((F.Id = @rDocumentSourceId) AND (@rDocumentSourceTypeId = 1020) OR 
((F.Id IN (Select Id FROM sBi.tFinding WHERE DocumentSourceId = @rDocumentSourceId))AND A.DocumentSourceTypeId = 1020)
	AND A.OrgId = @rOrgId
	AND A.StoreLocationId=@rStoreLocationId
	AND ISNULL(EM.IsOtherUser,0) = 0 
	
	END
	ELSE
	BEGIN
	SELECT ISNULL(A.Id,0) AS Id,
	   ISNULL(A.Number,'') AS Number,
	   A.ActionDetail,
	   ISNULL(ATM.Id,0) AS ActionTypeId,
	   ISNULL(ATM.Title,'') AS ActionType,
	   ISNULL(EM.Id,0) AS AssignedToEmployeeId,
	   ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
	   (ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'')) AS AssignedToEmployeeName,
	   ISNULL(A.ActionDueDate,'01-01-0001') AS ActionDueDate,
	   ISNULL(ASM.Id,0) AS ActionStatusId,
	   ISNULL(ASM.Title,'') AS ActionStatus, 
	   ISNULL(A.ActionDate,'01-01-0001') AS ActionDate,
	   ISNULL(F.Id,0) AS Id,
	   ISNULL(FTM.Title,'') AS FindingType,
	   ISNULL(F.FindingDate,'') AS FindingDate,
	    ISNULL(F.Number,'') AS FindingNumber,
	   @rAuditNumber AS AuditNumber,
	   @rAuditType AS AuditType ,
	   A.DocumentSourceTypeId
	   from sBi.tAction A 
LEFT JOIN sBi.tActionTypeMaster ATM ON ATM.Id=A.ActionTypeId 
LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = A.AssignedToEmployeeId
LEFT JOIN sBi.tActionStatusMaster ASM ON ASM.Id=A.ActionStatusId
LEFT JOIN sBi.tFinding F ON F.Id = A.DocumentSourceId 
LEFT JOIN sBi.tFindingTypeMaster FTM ON FTM.Id=F.FindingTypeId 

WHERE (A.DocumentSourceId = @rDocumentSourceId AND A.DocumentSourceTypeId = 1020)
	AND A.OrgId = @rOrgId
	AND A.StoreLocationId=@rStoreLocationId
	AND ISNULL(EM.IsOtherUser,0) = 0 
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pActionGet]
          
            @rId bigint
           ,@rStoreLocationId int                    
           ,@rOrgId smallint
		   ,@rActionNumber nvarchar(20)
		   ,@rDocumentSourceId bigint
		   ,@rDocumentSourceTypeId int 
AS
SET NOCOUNT ON

BEGIN

SELECT A.[Id]
	  ,A.Number	
      ,[ActionDetail]
      ,Isnull([ActionTypeId],0) as ActionTypeId
      ,Isnull([AssignedToEmployeeId],0) as AssignedToEmployeeId
      ,ISNULL(Em.Code,'') AS AssignedToEmployeeCode
      ,ISNULL(Em.FirstName,'')+ ' ' + ISNULL(Em.MiddleName,'')+ ' ' + ISNULL(Em.LastName,'') AS AssignedToEmployeeName
      ,ISNULL(A.[ActionDueDate],'01-01-0001') AS ActionDueDate
      ,Isnull([ActionStatusId],0) as ActionStatusId
      ,ISNULL(A.[ActionDate],'01-01-0001') AS ActionDate
      ,ISNULL(F.Id,0) AS Id
      ,ISNULL(F.Number,'') AS FindingNumber
	  ,ISNULL(FTM.Title,'') AS FindingType
	  ,ISNULL(F.FindingDate,'') AS FindingDate
FROM [sBi].[tAction] A LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = A.AssignedToEmployeeId AND Em.IsObsolete = 0
LEFT JOIN sBi.tFinding F ON F.Id = A.DocumentSourceId AND A.DocumentSourceTypeId = 1020
LEFT JOIN sBi.tFindingTypeMaster FTM ON FTM.Id=F.FindingTypeId 
 
WHERE ((A.Id=@rId) OR (@rId=0))
   and ((A.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId= 0)) 
   and A.OrgId=@rOrgId
   AND ((A.Number=@rActionNumber) OR (@rActionNumber = ''))
   AND ISNULL(EM.IsOtherUser,0) = 0 
   AND ((A.DocumentSourceId IN (Select Id FROM sBi.tFinding where DocumentSourceId = @rDocumentSourceId) AND A.DocumentSourceTypeId = 1020) OR (A.DocumentSourceId = @rDocumentSourceId AND A.DocumentSourceTypeId = 1018))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pAuditAdd]
	 
	        @rId bigint 
           ,@rFunctionalityId int 
           ,@rNumber nvarchar(20)= ''
           ,@rAuditTypeId int 
           ,@rAuditStatusId int 
           ,@rStartDate date 
           ,@rEndDate date 
           ,@rAuditReasonId int 
           ,@rLeadAuditorEmployeeId bigint 
           ,@rGuestAuditor nvarchar(100) 
           ,@rBackupAuditorEmployeeId bigint 
           ,@rQuestionnairesId int 
           ,@rRemark nvarchar(200) 
           ,@rStoreLocationId int 
           ,@rIsObsolete bit 
           ,@rCreatedUserId bigint         
           ,@rOrgId smallint 
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
 IF(@rId = 0)	
 BEGIN
  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1011,@rStoreLocationId = 0, @rNextNumber  = @rNumber OUTPUT
 
SET @rNumber = ISNULL(@rNumber, '-300')

		IF @rNumber = '-300'
	  BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	  END
	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sBi.tAudit', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO  [sBi].[tAudit]
           ([Id]
           ,[Number]
           ,[FunctionalityId]
           ,[AuditTypeId]
           ,[AuditStatusId]
           ,[StartDate]
           ,[EndDate]
           ,[AuditReasonId]
           ,[LeadAuditorEmployeeId]
           ,[GuestAuditor]
           ,[BackupAuditorEmployeeId]
           ,[QuestionnairesId]
           ,[Remark] 
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgId])
     VALUES
           (
            @lNextNumber
           ,@rNumber
           ,@rFunctionalityId 
           ,@rAuditTypeId 
           ,@rAuditStatusId 
           ,@rStartDate 
           ,@rEndDate 
           ,@rAuditReasonId 
           ,@rLeadAuditorEmployeeId
           ,@rGuestAuditor 
           ,@rBackupAuditorEmployeeId
           ,@rQuestionnairesId 
           ,@rRemark  
           ,@rIsObsolete 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,0 
           ,sCommon.fGetDate()
           ,@rOrgId 
           )
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sBi].[tAudit]
	    SET
			FunctionalityId=@rFunctionalityId
            ,AuditTypeId=@rAuditTypeId
            ,AuditStatusId=@rAuditStatusId 
			,StartDate=@rStartDate 
			,EndDate=@rEndDate 
			,AuditReasonId=@rAuditReasonId 
			,LeadAuditorEmployeeId=@rLeadAuditorEmployeeId
			,GuestAuditor=@rGuestAuditor 
			,BackupAuditorEmployeeId=@rBackupAuditorEmployeeId
			,QuestionnairesId=@rQuestionnairesId 
			,Remark=@rRemark  				 
			,IsObsolete=@rIsObsolete
			,UpdatedUserId = @rCreatedUserId
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pAuditGet]
	
	@rId bigint,
	@rOrgId int,
	@rStoreLocationId int,
	@rAuditNumber nvarchar(20)

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 
	SELECT
	       A.Id
	      ,A.Number
		  ,A.[FunctionalityId]
		  ,[AuditTypeId]
		  ,[AuditStatusId]
		  ,ATM.[Title] as AuditType
		  ,StartDate
		  ,EndDate
		  ,ISNULL(AuditReasonId,0) AS AuditReasonId
		  ,ISNULL(LeadAuditorEmployeeId,0) AS LeadAudiotorEmployeeId
		  ,ISNULL(Em.Code,'') AS LeadAudiotorEmployeeCode
		  ,ISNULL(Em.FirstName,'')+ ' ' + ISNULL(Em.MiddleName,'')+ ' ' + ISNULL(Em.LastName,'') AS LeadEmployeeName
		  ,ISNULL(GuestAuditor,'') AS GuestAuditor
		  ,ISNULL(EM1.Code,'') AS BackupAuditorEmployeeCode
		  ,ISNULL(BackupAuditorEmployeeId,'') AS BackupAuditorEmployeeId
		  ,ISNULL(EM1.FirstName,'')+ ' ' + ISNULL(EM1.MiddleName,'')+ ' ' + ISNULL(EM1.LastName,'') AS BackupEmployeeName
		  ,ISNULL([QuestionnairesId],0) AS QuestionnairesId
		  ,FM.Title AS Functionality
		  ,ISNULL([Remark],'') AS Remark 
		  ,A.IsObsolete
		  ,AL.StoreLocationId
		  ,QM.Title AS Questionnaire
		  ,ASM.Title AS AuditStatus
		  ,ARM.Title AS AuditReason		  
		  
  FROM [sBi].[tAudit] A  INNER JOIN sBi.tAuditTypeMaster ATM on ATM.Id=A.AuditTypeId
						 INNER JOIN sBi.tFunctionalityMaster FM ON A.FunctionalityId=FM.Id
						 LEFT JOIN sBi.tAuditLocation AL ON AL.AuditId = A.Id AND AL.StoreLocationId = @rStoreLocationId
						 LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = A.LeadAuditorEmployeeId AND Em.IsObsolete = 0
					     LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = A.BackupAuditorEmployeeId AND EM1.IsObsolete = 0
					     LEFT JOIN sBi.tQuestionnairesMaster QM ON QM.Id=A.QuestionnairesId
					     LEFT JOIN sBi.tAuditStatusMaster ASM ON ASM.Id=A.AuditStatusId
					     LEFT JOIN sBi.tAuditReasonMaster ARM ON ARM.Id=A.AuditReasonId
	WHERE  
		   ((A.Id = @rId) OR (@rId = 0))
	       AND A.OrgId = @rOrgId 
	       --AND ((AL.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	       AND ((A.Number=@rAuditNumber) OR (@rAuditNumber = ''))
	    AND ISNULL(EM.IsOtherUser,0) = 0 
		AND ISNULL(EM1.IsOtherUser,0) = 0 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pAuditListGet]
	
	@rId int,
	@rOrgId int,
	@rStoreLocationId int,
	@rAuditStatusId int,
	@rAuditTypeId int,
	@rStartDate datetime,
	@rEndDate datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 
	SELECT
	       A.Id
	      ,A.Number
		  ,A.[FunctionalityId]
		  ,F.Title AS Functionality
		  ,[AuditTypeId]
		  ,ATM.Title AS AuditType
		  ,[AuditStatusId]
		  ,ASM.Title AS AuditStatus
		  ,StartDate
		  ,EndDate		  
		  ,ISNULL(AuditReasonId,0) AS AuditReasonId
		  ,ISNULL(ARM.Title,'') AS AuditReason
		  ,ISNULL(LeadAuditorEmployeeId,0) AS LeadAudiotorEmployeeId
		  ,ISNULL(Em.Code,'') AS LeadAudiotorEmployeeCode
		  ,ISNULL(Em.FirstName,'')+ ' ' + ISNULL(Em.MiddleName,'')+ ' ' + ISNULL(Em.LastName,'') AS LeadEmployeeName
		  ,ISNULL(GuestAuditor,'') AS GuestAuditor
		  ,ISNULL(EM1.Code,'') AS BackupAuditorEmployeeCode
		  ,ISNULL(BackupAuditorEmployeeId,'') AS BackupAuditorEmployeeId
		  ,ISNULL(EM1.FirstName,'')+ ' ' + ISNULL(EM1.MiddleName,'')+ ' ' + ISNULL(EM1.LastName,'') AS BackupEmployeeName
		  ,ISNULL([QuestionnairesId],0) AS QuestionnairesId
		  ,ISNULL(Qm.Title,'') AS Questionnaires
		  ,ISNULL([Remark],'') AS Remark 
		  ,A.IsObsolete		  
		  
  FROM [sBi].[tAudit] A INNER JOIN sBi.tFunctionalityMaster F ON F.Id = A.FunctionalityId AND F.IsObsolete = 0
					     INNER JOIN sBi.tAuditTypeMaster ATM ON ATM.Id = A.AuditTypeId AND ATM.IsObsolete = 0
					     INNER JOIN sBi.tAuditStatusMaster ASM ON ASM.Id = A.AuditStatusId AND ASM.Isobsolete = 0
					     INNER JOIN sBi.tAuditLocation AL ON AL.AuditId = A.Id
					     LEFT JOIN sBi.tAuditReasonMaster ARM ON ARM.Id = A.AuditReasonId AND ARM.IsObsolete = 0
					     LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = A.LeadAuditorEmployeeId AND Em.IsObsolete = 0
					     LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = A.BackupAuditorEmployeeId AND EM1.IsObsolete = 0
					     LEFT JOIN sBi.tQuestionnairesMaster Qm ON Qm.Id = A.QuestionnairesId AND Qm.IsObsolete = 0	  
					     
		  
	WHERE  
		   ((A.Id = @rId) OR (@rId = 0))
	       AND A.OrgId = @rOrgId 
	       AND ((AL.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	       AND ((A.AuditStatusId = @rAuditStatusId) OR (ISNULL(@rAuditStatusId,0) = 0))
	       AND ((A.AuditTypeId = @rAuditTypeId) OR (ISNULL(@rAuditTypeId,0) = 0))
	       AND ((A.StartDate = @rStartDate) OR (ISNULL(@rStartDate,'') = '')) 
	       AND ((A.EndDate = @rEndDate) OR (ISNULL(@rEndDate,'') = ''))
	          AND ISNULL(EM.IsOtherUser,0) = 0 
		AND ISNULL(EM1.IsOtherUser,0) = 0 
	       
	       order by A.Id desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pAuditLocationAdd]
          
            @rAuditId bigint 
           ,@rStoreLocationId int  
			,@rIsChecked bit 
 
AS
SET NOCOUNT ON

BEGIN  

	BEGIN TRY
	
	BEGIN TRANSACTION
	DECLARE @lNextNumber bigint
	
 
		IF EXISTS (SELECT 1 FROM sBi.tAuditLocation WHERE AuditId = @rAuditId AND StoreLocationId = @rStoreLocationId AND @rIsChecked = 0) 
  		   BEGIN
			DELETE FROM sBi.tAuditLocation 
			  WHERE AuditId = @rAuditId AND StoreLocationId = @rStoreLocationId
			 SELECT 1 AS Result	    
			END 
		ElSE IF NOT EXISTS (SELECT 1 FROM sBi.tAuditLocation WHERE AuditId = @rAuditId AND StoreLocationId = @rStoreLocationId)
		BEGIN  
		INSERT INTO sBi.tAuditLocation
			   ( 
					AuditId
					,StoreLocationId          
			   )
		 VALUES
			   ( 
					@rAuditId
					,@rStoreLocationId          
			   )
			   SELECT @rAuditId AS Result
		 END		   
	    ELSE SELECT 1 AS Result
	 
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pAuditLocationGet]
	 
	 @rNumber nvarchar(50)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
 Declare @lAuditId bigint
 Select @lAuditId =  Id  from sBi.tAudit where Number =@rNumber
 
 
 
 SELECT  
		StoreLocationId 
		from sBi.tAuditLocation
		
		where AuditId = @lAuditId  
       

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sBi].[pAuditLocationRemove]
	 
	 @rAuditId bigint,
	 @rStoreLocationId int,
	 @rCheck bit
	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
--BEGIN TRY

--	 BEGIN TRANSACTION	
	 
	 IF(@rCheck=1)
BEGIN 

If Exists(Select Id FROM sBi.tFinding Where DocumentSourceId = @rAuditId AND DocumentSourceTypeId = 1018 AND StoreLocationId = @rStoreLocationId)
	    BEGIN
			select -50 as Result
			RETURN
		END 
else If Exists(Select Id FROM sBi.tAction Where DocumentSourceId = @rAuditId AND DocumentSourceTypeId = 1018 AND StoreLocationId = @rStoreLocationId)
	    BEGIN
			select -51 as Result
			RETURN
		END 
else If Exists(Select Id FROM sBi.tDocument Where DocumentSourceId = @rAuditId AND DocumentSourceTypeId = 1018 AND StoreLocationId = @rStoreLocationId)
	    BEGIN
			select -52 as Result
			RETURN
		END 
else If Exists(Select Id FROM sBi.tQuestionResponse Where DocumentSourceId = @rAuditId AND DocumentSourceTypeId = 1018 AND StoreLocationId = @rStoreLocationId)
	    BEGIN
			select -53 as Result
			RETURN
		END 
		select 0 as Result	
END	
ELSE
BEGIN
	 
DELETE FROM sBi.tAuditLocation where AuditId=@rAuditId 
	
	SELECT 1 AS Result
END	
	
	--COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	

END








GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pDocumentAdd]
	 
	        @rId bigint 
	       ,@rNumber nvarchar(20) 
           ,@rDocumentSourceTypeId bigint 
           ,@rDocumentSourceId bigint 
           ,@rDocumentTypeId int 
           ,@rDocumentDate date 
           ,@rDocumentDetail nvarchar(200)
           ,@rFileName nvarchar(200)
           ,@rFilePath nvarchar(200)
           ,@rRemark nvarchar(200)
           ,@rCreatedUserId bigint  
           ,@rStoreLocationId int                    
           ,@rOrgId smallint 
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 IF(@rId = 0)	
 BEGIN
  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1014,@rStoreLocationId = @rStoreLocationId, @rNextNumber  = @rNumber OUTPUT

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

		IF @rNumber = '-300'
	  BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	  END
	
	DECLARE @lNextNumber BIGINT     
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sBi.tDocument', 0, 1, 1,@outNextNumber = @lNextNumber output

INSERT INTO [sBi].[tDocument]
           ([Id]
           ,[Number]
           ,[DocumentSourceTypeId]
           ,[DocumentSourceId]
           ,[DocumentTypeId]
           ,[DocumentDate] 
           ,[DocumentDetail] 
           ,[FileName] 
           ,[FilePath] 
           ,[Remark]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[StoreLocationId]
           ,[OrgId])
     VALUES
           (
           @lNextNumber
           ,@rNumber
           ,@rDocumentSourceTypeId
           ,@rDocumentSourceId
           ,@rDocumentTypeId 
           ,@rDocumentDate 
           ,@rDocumentDetail 
           ,@rFileName 
           ,@rFilePath 
           ,@rRemark 
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,0 
           ,sCommon.fGetDate()
           ,@rStoreLocationId
           ,@rOrgId
           )


		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sBi].[tDocument] 
	    SET
			 DocumentTypeId=@rDocumentTypeId
			,DocumentDate=@rDocumentDate
			,DocumentDetail=@rDocumentDetail 
	        ,FileName=@rFileName
	        ,FilePath=@rFilePath 
	        ,Remark=@rRemark           				 
		    ,UpdatedUserId = @rCreatedUserId
	      
	      WHERE Id=@rId 
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pDocumentDetailGet]

           @rOrgId smallint,
           @rAuditId bigint,
           @rStoreLocationId int,
           @rAuditNumber nvarchar(50),
           @rAuditType nvarchar(50)
AS
SET NOCOUNT ON

BEGIN

select ISNULL(D.Id,0) AS Id,
		ISNULL(D.Number,'') AS Number,
		ISNULL(D.DocumentTypeId,0) AS DocumentTypeId,
		ISNULL(D.DocumentDate,'') AS DocumentDate,
		ISNULL(DTM.Title,'') AS DocumentTypeName,
		D.DocumentDetail,
		D.FileName AS DocumentFileName,
		D.FilePath,
		D.Remark,
		@rAuditNumber AS AuditNumber,
		@rAuditType AS AuditType 
		from sBi.tDocument D 
LEFT JOIN sBi.tDocumentTypeMaster DTM ON DTM.Id =  D.DocumentTypeId

where ((D.DocumentSourceId = @rAuditId) OR (@rAuditId = 0))
	AND D.OrgId = @rOrgId
	AND D.StoreLocationId=@rStoreLocationId
	
	order by D.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pDocumentGet]
          
            @rId bigint
           ,@rStoreLocationId int                    
           ,@rOrgId smallint
           ,@rDocumentNumber nvarchar(20)
           ,@rDocumentSourceId bigint
     
AS
SET NOCOUNT ON

BEGIN

SELECT Id 
	  ,Number	
	  ,Isnull([DocumentTypeId],0) as DocumentTypeId  
      ,DocumentDate
      ,DocumentDetail
      ,FileName
      ,FilePath
      ,Remark
FROM [sBi].[tDocument] 

  WHERE ((Id=@rId) OR (@rId = 0))
   and ((StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId= 0)) 
   and OrgId=@rOrgId
   AND ((Number=@rDocumentNumber) OR (@rDocumentNumber = ''))
   AND (DocumentSourceId = @rDocumentSourceId)	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pFindingAdd]
	 
	        @rId bigint 
	       ,@rNumber nvarchar(20) 
           ,@rDocumentSourceTypeId bigint 
           ,@rDocumentSourceId bigint 
           ,@rFindingDate date 
           ,@rFindingDetail nvarchar(200)
           ,@rFindingTypeId int
           ,@rSeverityId int
           ,@rCreatedUserId bigint  
           ,@rStoreLocationId int                    
           ,@rOrgId smallint 
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 IF(@rId = 0)	
 BEGIN
  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1012,@rStoreLocationId = @rStoreLocationId, @rNextNumber  = @rNumber OUTPUT

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

		IF @rNumber = '-300'
	  BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	  END
	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sBi.tFinding', 0, 1, 1,@outNextNumber = @lNextNumber output

INSERT INTO [sBi].[tFinding]
           ([Id]
           ,[Number]
           ,[DocumentSourceTypeId]
           ,[DocumentSourceId]
           ,[FindingDate]
           ,[FindingDetail]
           ,[FindingTypeId]
           ,[SeverityId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[StoreLocationId]
           ,[OrgId])
     VALUES
           (
           @lNextNumber
           ,@rNumber
           ,@rDocumentSourceTypeId
           ,@rDocumentSourceId
           ,@rFindingDate
           ,@rFindingDetail
           ,@rFindingTypeId
           ,@rSeverityId
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,0 
           ,sCommon.fGetDate()
           ,@rStoreLocationId
           ,@rOrgId
           )


		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sBi].[tFinding]
	    SET

	        FindingDate=@rFindingDate
		   ,FindingDetail=@rFindingDetail
		   ,FindingTypeId=@rFindingTypeId
		   ,SeverityId=@rSeverityId        				 
		   ,UpdatedUserId = @rCreatedUserId
	      
	      WHERE Id=@rId 
	 END  
		SELECT 1 AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pFindingDetailGet]

           @rOrgId smallint,
           @rStoreLocationId int,
           @rAuditId bigint,
           @rAuditNumber nvarchar(50),
           @rAuditType nvarchar(50)
           
AS
SET NOCOUNT ON

BEGIN

SELECT ISNULL(F.Id,0) AS Id,
		ISNULL(F.Number,'') AS Number,
		ISNULL(F.FindingDate,'') AS FindingDate,
		F.FindingDetail,
		F.DocumentSourceId,
		ISNULL(FTM.Id,0) AS FindingTypeId,
		ISNULL(FTM.Title,'') AS FindingType,
		ISNULL(SM.Id,0) AS SeverityId,
		ISNULL(SM.Title,'') AS Severity,
		@rAuditNumber AS AuditNumber,
		@rAuditType AS AuditType 
		
	 from sBi.tFinding F  
LEFT JOIN sBi.tFindingTypeMaster FTM ON FTM.Id=F.FindingTypeId
LEFT JOIN sBi.tSeverityMaster SM ON SM.Id=F.SeverityId

WHERE ((F.DocumentSourceId = @rAuditId) OR (@rAuditId = 0))
	  AND F.OrgId = @rOrgId
	  AND F.StoreLocationId = @rStoreLocationId
	
	Order by F.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pFindingGet]
          
            @rId bigint
           ,@rStoreLocationId int                    
           ,@rOrgId smallint
           ,@rFindingNumber nvarchar(20)
		   ,@rDocumentSourceId bigint
AS
SET NOCOUNT ON

BEGIN

SELECT F.[Id] 
	  ,F.Number	 
      ,[FindingDate]
      ,[FindingDetail]
      ,Isnull([FindingTypeId],0) as FindingTypeId
      ,FTM.Title AS FindingType
      ,Isnull([SeverityId],0) as SeverityId
FROM [sBi].[tFinding] F left join sBi.tFindingTypeMaster FTM ON F.FindingTypeId=FTM.Id

  WHERE ((F.Id=@rId) OR (@rId = 0))
   and (F.StoreLocationId=@rStoreLocationId) 
   and F.OrgId=@rOrgId
   AND ((F.Number=@rFindingNumber) OR (@rFindingNumber = ''))
   AND F.DocumentSourceId = @rDocumentSourceId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionAnswerMasterAdd]
	 
	@rQuestionAnswerMasterId int,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rQuestionAnswerTypeId int,
	@rIsDelete bit,
	@rOrgId smallint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		--BEGIN TRY	
  --      BEGIN TRANSACTION
  
    
    IF(@rQuestionAnswerMasterId = 0 AND @rIsDelete=0)
    BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sBi.tQuestionAnswerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	INSERT INTO sBi.tQuestionAnswerMaster
		(
			Id,
			Code,
			Title,
			QuestionAnswerTypeId,			
			IsObsolete
			 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rQuestionAnswerTypeId,			 
			@rIsDelete
	 
		)	
	END
	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rQuestionAnswerMasterId
	 IF(@rIsDelete = 0)
		BEGIN
	    UPDATE  sBi.tQuestionAnswerMaster
	    SET
	      Code=@rCode, 
	      Title=@rTitle,
	      QuestionAnswerTypeId=@rQuestionAnswerTypeId,
	      IsObsolete = IsObsolete
	      
	      WHERE Id = @rQuestionAnswerMasterId 	  
	 END
	 ELSE 
	 DELETE FROM sBi.tQuestionAnswerMaster  WHERE Id =  @rQuestionAnswerMasterId	
	 END
	SELECT @lNextNumber AS Result
  
	 -- COMMIT TRANSACTION
  --       END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionAnswerMasterGet]
	
	@rId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
 

	 SELECT 
			 
			LVM.Id,
			LVM.Code,
			LVM.Title AS Name,
			LVM.QuestionAnswerTypeId			 
					 
	   FROM    sBi.tQuestionAnswerMaster LVM
		 
	    
	  WHERE  LVM.QuestionAnswerTypeId=@rId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionAnswerTypeMasterAdd]
	 
	@rId int,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rCreatedUserId bigint,
	@rQuestionAnswerGroupId int,
	@rIsObsolete bit,
	@rOrgId int
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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

	INSERT INTO sBi.tQuestionAnswerTypeMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			QuestionAnswerGroupId,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		 		 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rQuestionAnswerGroupId,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			0,
			sCommon.fGetDate()
	 
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sBi.tQuestionAnswerTypeMaster
	    SET
			  Code=@rCode, 
			  Title=@rTitle,
			  QuestionAnswerGroupId = @rQuestionAnswerGroupId,
			  IsObsolete=@rIsObsolete,
			  UpdatedUserId = @rCreatedUserId
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionAnswerTypeMasterGet]
	
	 
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rQuestionAnswerGroupId int,
	@rOrgId int = 1,
	@rWildCardSearch bit=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
if(@rWildCardSearch =1)
			BEGIN
				 SET @rCode = sCommon.fSearchStringGet(@rCode)
				 SET @rTitle=sCommon.fSearchStringGet(@rTitle)
			END

BEGIN
 

	 SELECT 
			QATM.Id AS QuestionAnswerTypeId,
			QATM.Code AS QuestionAnswerTypeCode,
			QATM.Title AS QuestionAnswerTypeName,
			QATM.IsObsolete AS IsObsolete,
			QATM.QuestionAnswerGroupId AS QuestionAnswerGroupId,
			QGM.Title AS QuestionAnswerGroup
			  
	   FROM  sBi.tQuestionAnswerTypeMaster QATM INNER JOIN sBi.tQuestionAnswerGroupMaster QGM ON QGM.Id = QATM.QuestionAnswerGroupId
	    
	   WHERE ((QATM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND	((QATM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((QATM.QuestionAnswerGroupId = @rQuestionAnswerGroupId) OR (@rQuestionAnswerGroupId = 0))
	   AND QATM.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionMainGroupMasterAdd]
	 
	        @rId int
           ,@rQuestionnaireId int                  
           ,@rTitle nvarchar(100)
           ,@rCode nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sBi.tQuestionMainGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sBi.tQuestionMainGroupMaster
			   (
			    [Id]
			   ,QuestionnaireId
			   ,[Title]
			   ,Code
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rQuestionnaireId
			   ,@rTitle
			   ,@rCode
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId
			   )
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sBi.tQuestionMainGroupMaster
	    SET
	          QuestionnaireId = @rQuestionnaireId		
	         ,Title = @rTitle	         
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,[OrgId] = @rOrgId
          
             
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionMainGroupMasterGet]
          
           @rId int,
           @rCode nvarchar(100),
           @rTitle nvarchar(100),
           @rOrgId smallint,
           @rQuestionnaireId int = 0,
           @rIsWildCardSearch bit           
          --@rSourceTypeId bigint 
 
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
			BEGIN
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END

BEGIN
SELECT MGM.Id 
      ,MGM.Code
      ,MGM.Title
      ,MGM.QuestionnaireId
      ,QNM.Title AS QuestionnaireName
      ,MGM.IsObsolete     
  FROM    
      sBi.tQuestionMainGroupMaster MGM INNER JOIN sBi.tQuestionnairesMaster QNM ON QNM.Id = MGM.QuestionnaireId           
  WHERE 
		 MGM.Id = @rId OR @rId = 0
	AND ((MGM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((MGM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((MGM.QuestionnaireId = @rQuestionnaireId) OR (@rQuestionnaireId = 0))
	AND MGM.OrgId = @rOrgId	 AND QNM.OrgId = @rOrgId
	--AND  QM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionMasterAdd]
	 
	        @rId int
           ,@rQuestionSubGroupId int
           ,@rQuestionAnswerTypeId int           
           ,@rTitle nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sBi.tQuestionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sBi].[tQuestionMaster]
			   (
			    [Id]
			   ,[QuestionSubGroupId]
			   ,[Title]
			   ,[QuestionAnswerTypeId]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rQuestionSubGroupId
			   ,@rTitle
			   ,@rQuestionAnswerTypeId
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId
			   )
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sBi].[tQuestionMaster]
	    SET
	          QuestionSubGroupId = @rQuestionSubGroupId		
	         ,QuestionAnswerTypeId = @rQuestionAnswerTypeId	 
             --,[Title] = @rTitle
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,[OrgId] = @rOrgId
          
             
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionMasterGet]
          
           @rId int,
           @rTitle nvarchar(100),
           @rOrgId int,
           @rQuestionSubGroupId int,
           @rIsWildCardSearch bit
           
          --@rSourceTypeId bigint 
 
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT QM.Id 
      ,QuestionSubGroupId
      ,MGM.Id AS MainGroupId
      ,MGM.Title AS MainGroup
      ,SGM.Title AS SubGroupMaster
      ,QM.Title AS QuestionMaster
      ,ATM.Title AS AnswerTypeMaster
      ,[QuestionAnswerTypeId]
      ,QM.IsObsolete
     
  FROM [sBi].[tQuestionMaster] QM INNER JOIN sBi.tQuestionSubGroupMaster SGM ON SGM.Id = QM.QuestionSubGroupId AND SGM.IsObsolete = 0
  INNER JOIN sBi.tQuestionMainGroupMaster MGM ON MGM.Id = SGM.QuestionMainGroupId AND MGM.IsObsolete = 0
  INNER JOIN sBi.tQuestionAnswerTypeMaster ATM ON ATM.Id = QM.QuestionAnswerTypeId 
        
  WHERE 
		 QM.Id = @rId OR @rId = 0
	AND ((QM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((QM.QuestionSubGroupId = @rQuestionSubGroupId) OR (@rQuestionSubGroupId = 0))	 
	AND  QM.OrgId = @rOrgId  
	--AND  QM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionnairesMasterAdd]
	 
	        @rId int
           ,@rFunctionalityId int                  
           ,@rQuestionnairePurposeId int
           ,@rTitle nvarchar(100)
           ,@rCode nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sBi.tQuestionnairesMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sBi.tQuestionnairesMaster
			   (
			    [Id]
			   ,FunctionalityId
			   ,QuestionnairePurposeId
			   ,[Title]
			   ,Code
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rFunctionalityId
			   ,@rQuestionnairePurposeId
			   ,@rTitle
			   ,@rCode
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId
			   )
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sBi.tQuestionnairesMaster
	    SET
	          FunctionalityId = @rFunctionalityId
	         ,QuestionnairePurposeId = @rQuestionnairePurposeId		
	         ,Title = @rTitle	         
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,[OrgId] = @rOrgId          
             
	      WHERE Id = @rId 	   	      
	 END	   
		SELECT @lNextNumber AS Result	
		COMMIT TRANSACTION				
	END TRY	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionnairesMasterGet]
          
           @rId int,
           @rCode nvarchar(100),
           @rTitle nvarchar(100),
           @rOrgId int,
           @rFunctionalityId int = 0,
           @rQuestionnairePurposeId int = 0,
           @rIsWildCardSearch bit           
          --@rSourceTypeId bigint 
 
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
			BEGIN
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END

BEGIN
SELECT 
       QNM.Id 
      ,QNM.Code
      ,QNM.Title
      ,QNM.FunctionalityId
      ,QNM.QuestionnairePurposeId      
      ,QNM.IsObsolete     
      ,QPM.Title AS QuestionnairePurpose
      ,FM.Title AS Functionality
  FROM    
       sBi.tQuestionnairesMaster QNM  INNER JOIN sBi.tQuestionnairePurposeMaster QPM ON QPM.Id = QNM.QuestionnairePurposeId 
       INNER JOIN sBi.tFunctionalityMaster FM ON FM.Id = QNM.FunctionalityId       
  WHERE 
		 QNM.Id = @rId OR @rId = 0
	AND ((QNM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((QNM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((QNM.FunctionalityId = @rFunctionalityId)OR(@rFunctionalityId = 0))
	AND ((QNM.QuestionnairePurposeId = @rQuestionnairePurposeId)OR(@rQuestionnairePurposeId = 0))
	AND QNM.OrgId = @rOrgId 
	--AND ((MGM.QuestionnaireId = @rQuestionMainGroupId) OR (@rQuestionMainGroupId = 0))	 
	--AND  QM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionResponseAdd]
	 
	        @rOrgId int
           ,@rId bigint
           ,@rQuestionId int           
           ,@rDocumentSourceId bigint
           ,@rDocumentSourceTypeId int
           ,@rResponseSourceId bigint           
           ,@rResponseSourceTypeId int
           ,@rQuestionAnswerListId int
           ,@rQuestionAnswerNumericValue decimal
           ,@rQuestionAnswerFreeText nvarchar(100) 
           ,@rCreatedUserId bigint
           ,@rStoreLocationId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
    BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sBi.tQuestionResponse', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO  [sBi].[tQuestionResponse]
           (
				[Id]
			   ,[QuestionId]
			   ,[DocumentSourceTypeId]
			   ,[DocumentSourceId]
			   ,[ResponseSourceTypeId]
			   ,[ResponseSourceId]
			   ,[QuestionAnswerListId]
			   ,[QuestionAnswerNumericValue]
			   ,[QuestionAnswerFreeText]
			   ,StoreLocationId 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId]
           )
     VALUES
           ( 
                @lNextNumber
			   ,@rQuestionId 
			   ,@rDocumentSourceTypeId
			   ,@rDocumentSourceId
			   ,@rResponseSourceTypeId
			   ,@rResponseSourceId			   
			   ,@rQuestionAnswerListId
			   ,@rQuestionAnswerNumericValue 
			   ,@rQuestionAnswerFreeText 
			   ,@rStoreLocationId 
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()			   
			   ,@rOrgId 
           )
     END
	 ELSE
	 BEGIN
	   SET @lNextNumber = @rId
	    UPDATE  [sBi].[tQuestionResponse]
		   SET   
			   [QuestionAnswerListId] =@rQuestionAnswerListId		 
			  ,[QuestionAnswerFreeText] =@rQuestionAnswerFreeText	
			  ,	[QuestionAnswerNumericValue] = @rQuestionAnswerNumericValue          
             
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionResponseDetailGet]
           
             @rQuestionnairesId int 
            ,@rAuditId bigint
            ,@rStoreLocationId int
            ,@rAuditNumber nvarchar(50)
            ,@rAuditType nvarchar(50)
            ,@rFunctionality nvarchar(50)
            ,@rQuestionnaires nvarchar(50)
		   --@rDocumentSourceId int         
		   --@rSourceTypeId bigint 
 
AS
SET NOCOUNT ON 

BEGIN
		
	       SELECT  
		   ISNULL(QR.Id,0) AS QuestionResponseId,
		   QNM.Id AS QuestionnaireId,
		   QNM.Title AS QueStionnaire,
		   QM.Title AS Question,       
		   QSG.Title AS subgroup,
		   QMG.Title AS MainGroup,
		   QAT.Title AS QuestionAnswerType,
		   QAT.Id AS QuestionAnswerTypeId,
		   QM.Id AS QuestionId,
		   QuestionAnswerGroupId,
		   QGM.Title  AS QuestionAnswerGroup,		   		  
		   CASE QuestionAnswerGroupId 
		        WHEN 1 THEN ISNULL(CONVERT(NVARCHAR(50),QR.QuestionAnswerListId),'')
		        WHEN 2 THEN ISNULL(CONVERT(NVARCHAR(50),QR.QuestionAnswerNumericValue),'')
		        WHEN 3 THEN ISNULL(QR.QuestionAnswerFreeText,'') 
		        END                     
            AS Answer,
            CASE QuestionAnswerGroupId 
		        WHEN 1 THEN ISNULL(CONVERT(NVARCHAR(50),QAM.Title),'')
		        WHEN 2 THEN ISNULL(CONVERT(NVARCHAR(50),QR.QuestionAnswerNumericValue),'')
		        WHEN 3 THEN ISNULL(QR.QuestionAnswerFreeText,'') 
		        END                     
            AS AnswerReport,
            @rAuditNumber AS AuditNumber,
			@rAuditType AS AuditType,
			@rFunctionality AS Functionallity,
			@rQuestionnaires AS Questionnaires
      
			from sBi.tQuestionnairesMaster QNM INNER JOIN sBi.tQuestionMainGroupMaster QMG ON QMG.QuestionnaireId = QNM.Id
			INNER JOIN sBi.tQuestionSubGroupMaster QSG ON QSG.QuestionMainGroupId = QMG.Id INNER JOIN sBi.tQuestionMaster QM 
			ON QM.QuestionSubGroupId = QSG.Id  INNER JOIN sBi.tQuestionAnswerTypeMaster QAT ON QAT.Id = QM.QuestionAnswerTypeId   
			INNER JOIN sBi.tQuestionAnswerGroupMaster QGM on QGM.Id = QAT.QuestionAnswerGroupId LEFT JOIN sBi.tQuestionResponse
			QR ON QR.QuestionId = QM.Id AND QR.DocumentSourceId = @rAuditId  AND QR.StoreLocationId = @rStoreLocationId
			LEFT JOIN sBi.tQuestionAnswerMaster QAM ON QAM.Id=QR.QuestionAnswerListId
			--AND QR.DocumentSourceId = @rDocumentSourceId
	
	WHERE  QNM.Id = @rQuestionnairesId AND QNM.IsObsolete = 0 AND QMG.IsObsolete = 0 AND QSG.IsObsolete = 0 AND QAT.IsObsolete = 0
	AND QGM.IsObsolete = 0 AND QM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sBi].[pQuestionResponseRemove]
	 
	 @rDocumentSourceId bigint,
	 @rStoreLocationId int
	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
 
	 
	 
BEGIN
	 
Delete From sBi.tQuestionResponse where DocumentSourceId = @rDocumentSourceId AND StoreLocationId = @rStoreLocationId

Select 1 AS Result
 
END








GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionSubGroupMasterAdd]
	 
	        @rId int
           ,@rQuestionMainGroupId int                  
           ,@rTitle nvarchar(100)
           ,@rCode nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sBi.tQuestionSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sBi.tQuestionSubGroupMaster
			   (
			    [Id]
			   ,[QuestionMainGroupId]
			   ,[Title]
			   ,Code
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rQuestionMainGroupId
			   ,@rTitle
			   ,@rCode
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgId
			   )
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sBi.tQuestionSubGroupMaster
	    SET
	          QuestionMainGroupId = @rQuestionMainGroupId		
	         ,Title = @rTitle	         
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,[OrgId] = @rOrgId
          
             
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pQuestionSubGroupMasterGet]
          
           @rId int,
           @rCode nvarchar(100),
           @rTitle nvarchar(100),
           @rOrgId int,
           @rQuestionMainGroupId int,
           @rIsWildCardSearch bit
           
          --@rSourceTypeId bigint 
 
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
			BEGIN
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END

BEGIN
SELECT SGM.Id 
      ,SGM.Code
      ,SGM.Title
      ,MGM.Id AS MainGroupId
      ,MGM.Title AS MainGroup       
      ,SGM.IsObsolete
     
  FROM   sBi.tQuestionSubGroupMaster SGM 
  INNER JOIN sBi.tQuestionMainGroupMaster MGM ON MGM.Id = SGM.QuestionMainGroupId 
   
      
         
  WHERE 
		 SGM.Id = @rId OR @rId = 0
	AND ((SGM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((SGM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((SGM.QuestionMainGroupId = @rQuestionMainGroupId) OR (@rQuestionMainGroupId = 0))
	AND SGM.OrgId = @rOrgId	 
	--AND  QM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pRptAuditAction]  
	@rAuditId bigint 
AS
BEGIN
 Select A.Number,
	   A.ActionDetail,
	   A.ActionDate,
	   ATM.Title AS ActionType,
	   EM.Code AS AssignEmployeeCode,
	   (EM.FirstName + ' ' + EM.LastName) AS AssignEmployeeName,
	   A.ActionDueDate,
	   ASM.Title AS ActionStatus
	    from sBi.tAction A
LEFT JOIN sBi.tActionTypeMaster ATM ON ATM.Id=A.ActionTypeId
LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = A.AssignedToEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
LEFT JOIN sBi.tActionStatusMaster ASM ON ASM.Id=A.ActionStatusId
 
where
((A.DocumentSourceId IN (Select Id FROM sBi.tFinding where DocumentSourceId = @rAuditId) AND A.DocumentSourceTypeId = 1020) OR (A.DocumentSourceId = @rAuditId AND A.DocumentSourceTypeId = 1018))
	   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pRptAuditDocument]  
	@rAuditId bigint 
AS
BEGIN
 Select D.Number,
	   DTM.Title AS DocumentType,
	   D.DocumentDate,
	   D.DocumentDetail,
	   D.FileName AS DocumentFileName,
	   D.FilePath,
	   D.Remark  from sBi.tDocument D 
LEFT JOIN sBi.tDocumentTypeMaster DTM ON DTM.Id =  D.DocumentTypeId
where (D.DocumentSourceId = @rAuditId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBi].[pRptAuditFinding]  
	@rAuditId bigint  
AS
BEGIN
 Select F.Number AS FindingNumber,
	   F.FindingDate,
	   F.FindingDetail,
	   FTM.Title AS FindingType,
	   SM.Title AS Severity from sBi.tFinding F
LEFT JOIN sBi.tFindingTypeMaster FTM ON FTM.Id= F.FindingTypeId
LEFT JOIN sBi.tSeverityMaster SM ON SM.Id=F.SeverityId

WHERE F.DocumentSourceId = @rAuditId AND DocumentSourceTypeId = 1018
	   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pAbsentReportGet]        
 @rFromDate Date,        
 @rToDate Date,        
 @rStatus nvarchar(10) = 'A',        
 @rOrgGroupId int =0,        
 @rBuilder1 nvarchar(max)='',        
 @rBuilder2 nvarchar(max)='',        
 @rOrgId int = 0,
 @rEmployeeStatusId int=0,
 @rEmployeeId bigint = 0
           
WITH EXECUTE AS CALLER        
AS        
SET NOCOUNT ON        
BEGIN         
  Select         
 @rBuilder1 AS Builder1,        
    @rBuilder2 AS Builder2,         
 Em.code,    
 P.AtdDate,    
 DM.[DisplayTitle],    
 EM.FirstName + ' ' + Em.MiddleName + ' ' + EM.LastName as EmployeeName,    
 isnull([Status],'A') as Status from sBiometric.tProcess P     
 inner join sHrm.tEmployeeMaster EM  on  P.Sourceid = Em.id    
 inner join [sHrm].[tEmployeeJobDetail] EJD on EM.id= EJD.EmployeeID      
 INNER JOIN [sSetup].[tDepartmentMaster] DM ON EJD.OrganizationDepartmentId = DM.id --AND P.SourceTypeId = 3       
 Where p.Status = 'A'
 AND (EM.Id = @rEmployeeId OR @rEmployeeId = 0)         
   AND ((P.AtdDate >= @rFromDate) OR (@rFromDate = ''))         
   AND ((P.AtdDate <= @rToDate) OR (@rToDate = '')) 
   AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)       
   AND ISNULL(EM.IsOtherUser,0) = 0     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sBiometric].[pBiometricCloudDetailMappingGet] 
	 @rOrgId INT,
	 @rSourceTypeId INT,
	 @rIsEmpCodeDuplicate BIT = 0,
	 @rIsPuchIdDuplicate BIT = 0,
	--@rIsBiometricIdDuplicate bit = 0,
	 @rIsSourceIdDuplicate BIT = 0,
	 @rIsEmpNameDuplicate BIT = 0,
	 @rClassId INT = 0,
	 @rDivisionId INT = 0,
	 @rBatchId INT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lQuery NVARCHAR(250)
	DECLARE @lTag NVARCHAR(MAX)
	DECLARE @lHavingQuery NVARCHAR(MAX)
	DECLARE @lHavingQuery1 NVARCHAR(MAX)
	DECLARE @lField NVARCHAR(MAX)
	DECLARE @lFinalQuery NVARCHAR(MAX)

	IF @rIsEmpCodeDuplicate = 1
	BEGIN
		SET @lQuery = 'Code'
		SET @lField = 'Code'
		SET @lTag = 'EmpId'
	END

	IF @rIsPuchIdDuplicate = 1
		AND LEN(@lField) > 1
	BEGIN
		SET @lQuery = @lQuery + ',PunchID'
		SET @lField = 'Punchid'
		SET @lTag = 'EmpPunchID'
	END

	IF @rIsPuchIdDuplicate = 1
		AND @lField IS NULL
	BEGIN
		SET @lQuery = 'PunchID'
		SET @lField = 'Punchid'
		SET @lTag = 'EmpPunchID'
	END

	--IF @rIsBiometricIdDuplicate = 1 AND 	LEN(@lHavingQuery)> 1		
	--BEGIN
	--	SET @lQuery = @lQuery + ',BiometricId'
	--	SET @lHavingQuery = 'BiometricId'
	--END
	--IF @rIsBiometricIdDuplicate = 1 AND 	@lHavingQuery Is Null
	--BEGIN
	--	SET @lQuery = 'BiometricId'
	--	SET @lHavingQuery = 'BiometricId'
	--END
	IF @rIsSourceIdDuplicate = 1
		AND LEN(@lField) > 1
	BEGIN
		SET @lQuery = @lQuery + ',Id'
		SET @lField = 'Id'
		SET @lTag = 'SourceId'
	END

	IF @rIsSourceIdDuplicate = 1
		AND @lField IS NULL
	BEGIN
		SET @lQuery = 'Id'
		SET @lField = 'Id'
		SET @lTag = 'SourceId'
	END

	IF @rIsEmpNameDuplicate = 1
		AND LEN(@lField) > 1
	BEGIN
		SET @lQuery = @lQuery + ',FirstName+ '' ''+LastName'
		SET @lField = 'FirstName+ '' ''+LastName'
		SET @lTag = 'EmpId'
	END

	IF @rIsEmpNameDuplicate = 1
		AND @lField IS NULL
	BEGIN
		SET @lQuery = 'FirstName+ '' ''+LastName'
		SET @lField = 'FirstName+ '' ''+LastName'
		SET @lTag = 'EmpName'
	END

	SET @lHavingQuery = ' AND SM.' + @lField + ' IN (Select ' + @lField + ' AS ' + @lTag + ' FROM sStudent.tStudentMaster   WHERE 
			((SM.OrgId = ' + CONVERT(NVARCHAR(10), @rOrgId) + ') OR (' + CONVERT(NVARCHAR(10), @rOrgId) + ' = 0))
			AND ((2001 = ' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ') OR (' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ' = 0))
			AND StatusId = 1
			AND PunchId is not null
			AND((A.ClassId=' + CONVERT(NVARCHAR(10), @rClassId) + ')OR(' + CONVERT(NVARCHAR(10), @rClassId) + '=0))
			AND((A.DivisionId=' + CONVERT(NVARCHAR(10), @rDivisionId) + ')OR(' + CONVERT(NVARCHAR(10), @rDivisionId) + '=0))
			AND(A.BatchId=' + CONVERT(NVARCHAR(10), @rBatchId) + ' or ' + CONVERT(NVARCHAR(10), @rBatchId) + ' = 0)
			GROUP BY ' + @lQuery + ' Having Count(' + @lField + ') >1'
	SET @lHavingQuery1 = ' AND EM.' + @lField + ' IN (Select ' + @lField + ' AS ' + @lTag + ' FROM sHrm.tEmployeeMaster   WHERE 
			((OrgId = ' + CONVERT(NVARCHAR(10), @rOrgId) + ') OR (' + CONVERT(NVARCHAR(10), @rOrgId) + ' = 0))
			AND ((3 = ' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ') OR (' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ' = 0)) 
			AND StatusId =7
			AND PunchId is not null
			GROUP BY ' + @lQuery + ' Having Count(' + @lField + ') >1'

	IF LEN(@lHavingQuery) > 0
	BEGIN
		SET @lFinalQuery = 'select 
				'''' as BiometricId,
				--SM.Id As EmpId,
				FirstName+ '' ''+LastName AS EmpName, 
				PunchId AS EmpPunchID,
				StatusId as ActiveStatus,
				SM.Id as SourceId,
				SM.OrgId as OrgId ,
				OM.DisplayTitle AS Organization,
				SM.Code AS EmpId,
				CM.DisplayTitle AS ClassName,
				DM.DisplayTitle AS DivisionName,
				'''' AS Dipartment
				
			from sStudent.tStudentMaster SM
			Inner Join sStudent.tAcademic A On SM.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 OM.Id = SM.OrgId 
			where StatusId = 1
				AND PunchId is not null
				AND((A.ClassId=' + CONVERT(NVARCHAR(10), @rClassId) + ')OR(' + CONVERT(NVARCHAR(10), @rClassId) + '=0))
				AND((A.DivisionId=' + CONVERT(NVARCHAR(10), @rDivisionId) + ')OR(' + CONVERT(NVARCHAR(10), @rDivisionId) + '=0))
				AND(A.BatchId=' + CONVERT(NVARCHAR(10), @rBatchId) + ' or ' + 
			CONVERT(NVARCHAR(10), @rBatchId) + ' = 0)
				AND ((SM.OrgId = ' + CONVERT(NVARCHAR(10), @rOrgId) + ') OR (' + CONVERT(NVARCHAR(10), @rOrgId) + ' = 0))
				AND ((2001 = ' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ') OR (' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ' = 0))
				' + @lHavingQuery + ') 
			Union ALL
			select 
				'''' AS BiometricId,
				--EM.Id AS EmpId,
				FirstName+ '' ''+LastName AS EmpName, 
				PunchId AS EmpPunchID,
				StatusId as ActiveStatus,
				EM.Id as SourceId,
				EM.OrgId as OrgId ,
				OM.DisplayTitle AS Organization,
				EM.Code AS EmpId,
				'''' AS ClassName,
				'''' AS DivisionName,
				DM.DisplayTitle AS Dipartment
			from sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId 
			where StatusId = 7
				AND PunchId is not null
				AND ((EM.OrgId = ' + CONVERT(
				NVARCHAR(10), @rOrgId) + ') OR (' + CONVERT(NVARCHAR(10), @rOrgId) + ' = 0))
					AND ((3 = ' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ') OR (' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ' = 0))
					' + @lHavingQuery1 + ') 
				Order By EmpId'

		PRINT (@lFinalQuery)

		EXECUTE (@lFinalQuery)
	END
	ELSE
	BEGIN
		SELECT '' AS BiometricId
			,
			--SM.Id As EmpId,
			FirstName + ' ' + LastName AS EmpName
			,PunchId AS EmpPunchID
			,StatusId AS ActiveStatus
			,SM.Id AS SourceId
			,SM.OrgId AS OrgId
			,OM.DisplayTitle AS Organization
			,SM.Code AS EmpId
			,CM.DisplayTitle AS ClassName
			,DM.DisplayTitle AS DivisionName
			,'' AS Dipartment
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON SM.Id = A.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		WHERE (
				(SM.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			AND (
				(@rSourceTypeId = 2001)
				OR (@rSourceTypeId = 0)
				)
			AND StatusId = 1
			AND PunchId IS NOT NULL
			AND (
				(A.ClassId = @rClassId)
				OR (@rClassId = 0)
				)
			AND (
				(A.DivisionId = @rDivisionId)
				OR (@rDivisionId = 0)
				)
			AND (
				A.BatchId = @rBatchId
				OR @rBatchId = 0
				)
		
		UNION ALL
		
		SELECT '' AS BiometricId
			,
			--EM.Id AS EmpId,
			FirstName + ' ' + LastName AS EmpName
			,PunchId AS EmpPunchID
			,StatusId AS ActiveStatus
			,EM.Id AS SourceId
			,EM.OrgId AS OrgId
			,OM.DisplayTitle AS Organization
			,EM.Code AS EmpId
			,'' AS ClassName
			,'' AS DivisionName
			,DM.DisplayTitle AS Dipartment
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		WHERE (
				(EM.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			AND (
				(@rSourceTypeId = 3)
				OR (@rSourceTypeId = 0)
				)
			AND StatusId = 7
			AND PunchId IS NOT NULL
		ORDER BY EmpID
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sBiometric].[pBiometricDailyReportGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,	
	 @rStatus nvarchar(max) = '',
	 @rEmployeeStatusId int=0,
	 @rOrderBy smallint = 0,
	 @rOrgGroupId int = 0,
	 @rUserId bigint = 0,
	 @rIsDetail bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE  @rToDate Date
SET @rToDate = @rFromDate

DECLARE @TableEmployee TABLE (Id int Identity,EmployeeID BigINT, OrganizationDepartmentId int, EmployeeTypeId Int)
INSERT INTO @TableEmployee
SELECT EM.Id AS EmployeeId,ED.OrganizationDepartmentId,ED.EmployeeTypeId from shrm.tEmployeeMaster EM 
LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id 
Where (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )
AND (ED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0 )
AND  EM.ORgId = @rOrgId 
AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 

DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lMonth as nvarchar(3)
DECLARE @lYear as nvarchar(4)

DECLARE @lBatchID int
DECLARE @lEmployeeId bigint
DECLARE @lEmpCount int

DECLARE @TempDate TABLE(Id int identity,Idate date)
insert into @TempDate
SELECT  TOP (DATEDIFF(DAY, @rFromDate, @rToDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @rFromDate)
FROM    sys.all_objects a CROSS JOIN sys.all_objects b;

CREATE TABLE #TempMonthTrans (Id int Identity,EmployeeId bigint,Attn_Date DateTime,DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20))


SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

Select @lCount = Max(Id) from @TempDate
Select @lEmpCount = Max(Id) from @TableEmployee
While (@lEmpCount > 0)
	BEGIN
		SELECT @lEmployeeId = EmployeeId From @TableEmployee Where Id = @lEmpCount	
	set @lCount1 = 1
	while (@lCount1 <= @lCount)
	begin			
		Select @lDate = Idate from @TempDate Where Id = @lCount1
		Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)
		Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@lDate) AS varchar(2)), 2)
		Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@lDate) AS varchar(4)), 4)
		
		set @lQuery = 'INSERT INTO #TempMonthTrans
						SELECT Distinct ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
											 

											 CASE When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', ' + convert(nvarchar(10),@lYear) + ',' + convert(nvarchar(10),@lMonth) + ',' + convert(nvarchar(15),@lDay)+',
											 ' + convert(nvarchar(15),@lBatchId) + ',' + Convert(nvarchar(10),@rOrganizationDepartmentId) + ',' + convert(nvarchar(10),@rOrgId) + ') <> ''-'' then 
											 [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', ' + convert(nvarchar(10),@lYear) + ',' + convert(nvarchar(10),@lMonth) + ',' + convert(nvarchar(15),@lDay)+',
											 ' + convert(nvarchar(15),@lBatchId) + ',' + Convert(nvarchar(10),@rOrganizationDepartmentId) + ',' + convert(nvarchar(10),@rOrgId) + ') 
											 When D'+ convert(nvarchar(15),@lDay) +' =''XX'' AND  (Cast(''' + convert(nvarchar(15),@lDate) + ''' as date)<GETDATE()) And (cast(ED.DateOfJoining as date)<= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfJoining,'''')='''')AND (ED.DateOfleaving>= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfleaving,'''')='''')  then ''A''
											 else D'+convert(nvarchar(15),@lDay)+' end AS D'+convert(nvarchar(15),@lDay)+',

											 D'+convert(nvarchar(15),@lDay)+'_IN,
											 D'+convert(nvarchar(15),@lDay)+'_OUT,
											 D'+convert(nvarchar(15),@lDay)+'_O,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T,D'+convert(nvarchar(15),@lDay)+'_E 
						FROM sBiometric.tMonthTrans T1 
						LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId	
						WHERE T1.EmployeeId =' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT >= cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) 
						AND ATTN_DT <= cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime)'
						--print @lQuery
			execute (@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1	
	END
	
	CREATE TABLE #TempMonthTransWitIoOutTime (EmployeeId bigint,Attn_Date DateTime,InTime nvarchar(20),OutTime nvarchar(20))
	if(@rIsDetail=1)
	BEGIN
	--mantis:28452 Start
		WITH CloudTransactionDataEntries AS (
		SELECT 
			SourceId,Attn_Dt,
			CONVERT(VARCHAR(10), In_Out_Time, 108) as In_Out_Time,
			ROW_NUMBER() OVER (PARTITION BY SourceId ORDER BY CONVERT(VARCHAR(10), In_Out_Time, 108)) AS In_Out_Time_number
		FROM 
			[sBiometric].[tCloudTransactionData]

		WHERE 
			SourceTypeid=95
				AND Attn_Dt>=@rFromDate
				AND Attn_Dt<=@rToDate
		)
		INSERT INTO #TempMonthTransWitIoOutTime
		SELECT 
			e1.SourceId,
			e1.Attn_Dt,
			e1.In_Out_Time AS in_time,
			e2.In_Out_Time AS out_time
		FROM 
			CloudTransactionDataEntries e1
		JOIN 
			CloudTransactionDataEntries e2 
		ON 
			e1.SourceId = e2.SourceId 
			AND e1.In_Out_Time_number = e2.In_Out_Time_number - 1
			ANd  e1.In_Out_Time_number%2=1
			AND e1.Attn_Dt=e2.Attn_Dt
		ORDER BY 
			e1.SourceId,e1.Attn_Dt, e1.In_Out_Time
	--INSERT INTO #TempMonthTransWitIoOutTime
	--	SELECT  SourceId,Attn_Dt,CONVERT(VARCHAR(10), I.In_Out_Time, 108),CONVERT(VARCHAR(10), O.In_Out_Time, 108)
	--       FROM [sBiometric].[tCloudTransactionData] I
	--	OUTER APPLY (
	--					SELECT TOP 1    In_Out_Time,
	--									Mode
	--					FROM [sBiometric].[tCloudTransactionData] t
	--					WHERE       t.SourceId = I.SourceId
	--							AND t.In_Out_Time > I.In_Out_Time
	--							AND SourceTypeid=95
	--							AND t.Attn_Dt =I.Attn_Dt
	--							AND Mode = 'OUT'
	--					ORDER BY t.In_Out_Time
	--				) O
	--	WHERE I.Mode = 'IN'
	--	AND SourceTypeid=95
	--	AND I.Attn_Dt>=@rFromDate
	--	AND I.Attn_Dt<=@rToDate
	--mantis:28452 End
	--	--select * from #TempMonthTransWitIoOutTime
	END
	--Select * from #TempMonthTrans
	--return
	
	IF(@rStatus = '(0)')
	BEGIN
		SET @strQuery = 'select Day(T.Attn_Date), T.*,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	convert(nvarchar(20),Emp.Code) AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,''' +CAST(@rOrderBy AS NVARCHAR(3)) + ''' AS OrderBy,
	DM.Title AS DeptName, Emp.Number AS Number,	OM.Id AS OrgId, OM.Title AS OrganizationTitle,CTD.*,'+Cast(@rIsDetail AS NVARCHAR(10))+' AS IsDetail
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	LEFT JOIN sSetup.vDepartment DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 	
	Left Join #TempMonthTransWitIoOutTime CTD ON  CTD.EmployeeId=T.EmployeeId AND CTD.Attn_Date=T.Attn_Date  	
	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
              
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId
	WHERE (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
	AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') AND DM.UserId = ' + convert(nvarchar(15),@rUserId) + ' Order By T.Attn_Date,T.EmployeeId'
	END
	ELSE
	BEGIN
	SET @strQuery = 'select Day(T.Attn_Date), T.*,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	convert(nvarchar(20),Emp.Code) AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,''' +CAST(@rOrderBy AS NVARCHAR(3)) + ''' AS OrderBy,
	DM.Title AS DeptName, Emp.Number AS Number,	OM.Id AS OrgId, OM.Title AS OrganizationTitle,CTD.*,'+Cast(@rIsDetail AS NVARCHAR(10))+' AS IsDetail
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	LEFT JOIN sSetup.vDepartment DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 
	Left Join #TempMonthTransWitIoOutTime CTD ON  CTD.EmployeeId=T.EmployeeId AND CTD.Attn_Date=T.Attn_Date
	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
              
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId
	WHERE PresentStatus IN ' + @rStatus + ' AND (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
	AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') AND DM.UserId = ' + convert(nvarchar(15),@rUserId) + ' Order By T.Attn_Date,T.EmployeeId'	
	END
	--WHERE (PresentStatus IN '+ '''' + @rStatus + '''' + ' OR (PresentStatus like ''%L%'')) Order By T.Attn_Date,T.EmployeeId' 


	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	
	
	--print (@strQuery)
	execute (@strQuery)
	

	
	DROP TABLE #TempMonthTrans
	--select  
	--@rBuilder1 as Builder1,
	--@rBuilder2 as Builder2,
	--@rIsDetail AS IsDetail,
	--'' as Attn_Date,
	--'' as EmployeeId,
	--'' as Attn_Date,
	--'' as DayNumber ,
	--'' as PresentStatus ,
	--'' as FirstIn,
	--'' as LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as TotPresent,
	--'' as TotWeekOff,
	--'' as TotHalfDay,
	--'' as TotHoliday,
	--'' AS TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrderBy,
	--'' as Number,
	--'' as OrgId,
	--'' as OrganizationTitle,
	--'' AS OutTime,
	--'' as InTime
END

	--CASE 
	--					When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',ED.OrganizationDepartmentId,' + convert(nvarchar(15),@rOrgId) + ') in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
	--					When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',' + CONVERT(nvarchar(13),@rOrganizationDepartmentId) + ',' + convert(nvarchar(15),@rOrgId) + ') Not in (''-'',''XX'') 
	--					Then [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',0,' + convert(nvarchar(15),@rOrgId) + ') 
	--					Else D'+convert(nvarchar(15),@lDay)+' End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pBiometricDetailMappingGet]
	
	@rOrgId int,
	@rSourceTypeId int,
	@rIsEmpCodeDuplicate bit = 0,
	@rIsPuchIdDuplicate bit = 0,
	@rIsBiometricIdDuplicate bit = 0,
	@rIsSourceIdDuplicate bit = 0,
	@rIsEmpNameDuplicate bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lQuery nvarchar(250)
	DECLARE @lHavingQuery nvarchar(MAX)
	DECLARE @lFinalQuery nvarchar(MAX)
	
	IF @rIsEmpCodeDuplicate = 1 
	BEGIN
		SET @lQuery = 'EmpId'
		SET @lHavingQuery = 'EmpId'
	END
	IF @rIsPuchIdDuplicate = 1 AND 	LEN(@lHavingQuery)> 1		
	BEGIN
		SET @lQuery = @lQuery + ',EmpPunchID'
		SET @lHavingQuery = 'EmpPunchID'
	END
	IF @rIsPuchIdDuplicate = 1 AND 	@lHavingQuery Is Null
	BEGIN
		SET @lQuery = 'EmpPunchID'
		SET @lHavingQuery = 'EmpPunchID'
	END
	IF @rIsBiometricIdDuplicate = 1 AND 	LEN(@lHavingQuery)> 1		
	BEGIN
		SET @lQuery = @lQuery + ',BiometricId'
		SET @lHavingQuery = 'BiometricId'
	END
	IF @rIsBiometricIdDuplicate = 1 AND 	@lHavingQuery Is Null
	BEGIN
		SET @lQuery = 'BiometricId'
		SET @lHavingQuery = 'BiometricId'
	END
	IF @rIsSourceIdDuplicate = 1 AND 	LEN(@lHavingQuery)> 1		
	BEGIN
		SET @lQuery = @lQuery + ',SourceId'
		SET @lHavingQuery = 'SourceId'
	END
	IF @rIsSourceIdDuplicate = 1 AND 	@lHavingQuery Is Null
	BEGIN
		SET @lQuery = 'SourceId'
		SET @lHavingQuery = 'SourceId'
	END
	IF @rIsEmpNameDuplicate = 1 AND 	LEN(@lHavingQuery)> 1
	BEGIN
	    SET @lQuery = @lQuery + ',EmpName'
		SET @lHavingQuery = 'EmpName'
	END
	IF @rIsEmpNameDuplicate = 1 AND 	@lHavingQuery Is Null
	BEGIN
		SET @lQuery = 'EmpName'
		SET @lHavingQuery = 'EmpName'
	END

	
	
       SET @lHavingQuery = ' AND ' + @lHavingQuery + ' IN (Select ' + @lHavingQuery + ' FROM sBiometric.BioDetailMapping   WHERE 
			((OrgId = ' + CONVERT(NVARCHAR(10),@rOrgId) + ') OR (' + CONVERT(NVARCHAR(10),@rOrgId) + ' = 0))
			AND ((SourceTypeId = ' + CONVERT(NVARCHAR(10),@rSourceTypeId) + ') OR (' + CONVERT(NVARCHAR(10),@rSourceTypeId) + ' = 0)) 
			GROUP BY ' + @lQuery + ' Having Count(' + @lHavingQuery + ') >1'
	
		
	
	IF LEN(@lHavingQuery) > 0
	BEGIN
	SET @lFinalQuery = 'SELECT
			BDM.*,
			OM.DisplayTitle AS Organization
		FROM 
			sBiometric.BioDetailMapping BDM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BDM.OrgId 
	    WHERE 
			((OrgId = ' + CONVERT(NVARCHAR(10),@rOrgId) + ') OR (' + CONVERT(NVARCHAR(10),@rOrgId) + ' = 0))
			AND ((SourceTypeId = ' + CONVERT(NVARCHAR(10),@rSourceTypeId) + ') OR (' + CONVERT(NVARCHAR(10),@rSourceTypeId) + ' = 0))
			' + @lHavingQuery + ') Order By EmpId'
		--PRINT(@lFinalQuery)
		EXECUTE(@lFinalQuery)
	END
	ELSE
	BEGIN			
	  SELECT
			BDM.*,
			OM.DisplayTitle AS Organization
       FROM 
            sBiometric.BioDetailMapping BDM
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BDM.OrgId 
       WHERE 
			((OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0))
       ORDER BY EmpID
	END
	return
	
	------------------------------------------------------------------------------------	
		
 --  -- Duplicate EmpCode Check
	--IF @rIsEmpCodeDuplicate = 1 
	--BEGIN
	--	SELECT
	--		BDM.*,
	--		OM.DisplayTitle AS Organization
	--	FROM 
	--		sBiometric.BioDetailMapping BDM
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BDM.OrgId 
	--    WHERE 
	--		((OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0))
	--		AND BDM.EmpID IN (Select EmpID FROM sBiometric.BioDetailMapping   WHERE 
	--		((OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0)) GROUP BY EmpID Having Count(EmpID) >1)
	--   ORDER BY EmpID
	--   return
	--END
	---- Ends Here
	
	---- Duplicate PunchId Check
	--IF @rIsPuchIdDuplicate = 1
	--BEGIN
	--	SELECT
	--		BDM.*,
	--		OM.DisplayTitle AS Organization
	--	FROM 
	--		sBiometric.BioDetailMapping BDM
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BDM.OrgId 
	--   WHERE 
	--		((OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0))
	--		AND BDM.EmpPunchID IN (Select EmpPunchID FROM sBiometric.BioDetailMapping   WHERE 
	--		((OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0)) GROUP BY EmpPunchID Having Count(EmpPunchID) >1)
	--   ORDER BY EmpID
	--   return
	--END
	---- Ends Here
	
	---- Duplicate BiometricId Check
	--IF @rIsBiometricIdDuplicate = 1
	--BEGIN
	--	SELECT
	--		BDM.*,
	--		OM.DisplayTitle AS Organization
	--	FROM 
	--		sBiometric.BioDetailMapping BDM
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BDM.OrgId 
	--   WHERE 
	--		((OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0))
	--		AND BDM.BiometricId IN (Select BiometricId FROM sBiometric.BioDetailMapping   WHERE 
	--		((OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0)) GROUP BY BiometricId Having Count(BiometricId) >1)
	--   ORDER BY BiometricId
	--   return
	--END
	---- Ends Here
	
	---- Duplicate SourceId Check
	--IF @rIsSourceIdDuplicate = 1
	--BEGIN
	--	SELECT
	--		BDM.*,
	--		OM.DisplayTitle AS Organization
	--	FROM 
	--		sBiometric.BioDetailMapping BDM
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BDM.OrgId 
	--   WHERE 
	--		((OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0))
	--		AND BDM.SourceId IN (Select SourceId FROM sBiometric.BioDetailMapping   WHERE 
	--		((OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0)) GROUP BY SourceId Having Count(SourceId) >1)
	--   ORDER BY EmpID
	--   return
	--END
	---- Ends Here
	
	---- Duplicate Emp Name Check
	--IF @rIsEmpNameDuplicate = 1
	--BEGIN
	--	SELECT
	--		BDM.*,
	--		OM.DisplayTitle AS Organization
	--	FROM 
	--		sBiometric.BioDetailMapping BDM
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BDM.OrgId 
	--	WHERE 
	--		((OrgId = 0) OR (0 = 0))
	--		AND ((SourceTypeId = 3) OR (3 = 0))
	--		AND BDM.EmpName IN (Select EmpName FROM sBiometric.BioDetailMapping  WHERE 
	--		((OrgId = 0) OR (0 = 0))
	--		AND ((SourceTypeId = 3) OR (3 = 0)) GROUP BY EmpName Having Count(EmpId) >1)
	--	ORDER BY EmpId,BDM.EmpName
	--	return
	--END
	---- Ends Here

	--ELSE
	-- BEGIN
 --      SELECT
	--		BDM.*,
	--		OM.DisplayTitle AS Organization
 --      FROM 
 --           sBiometric.BioDetailMapping BDM
 --           INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BDM.OrgId 
 --      WHERE 
	--		((OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0))
 --      ORDER BY EmpID
 --      return
	--END	


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pBiometricEmployeeAttendanceGet]
	 	 
	 	 @rDepartmentId int=0,
	 	 @rAttendanceDate date='',
	 	 @rCode nvarchar(20)='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0,
		 @TimeSheetStatusId nvarchar(10) = '0'
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lMonth as nvarchar(3)
DECLARE @lYear as nvarchar(4)
  BEGIN
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rAttendanceDate) AS varchar(2)), 2)
	Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@rAttendanceDate) AS varchar(2)), 2)
	Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@rAttendanceDate) AS varchar(4)), 4)
	
	
	
		set @strQuery ='Select EM.EmployeeId,EM.Code AS EmployeeCode,EM.EmployeeName,EM.DepartmentName,
			--change for 28927 mantis, add IsPresent column and add tBiometricTypeMaster table join
			Isnull(EAR.IsPresent,case when T1.D'+convert(nvarchar(15),@lDay)+'=''A'' or BTM.MainStatusId = -1 then ''false''
				when T1.D'+convert(nvarchar(15),@lDay)+'=''P'' then ''true''
				Else cast(ISNULL(BTM.MainStatusId,0) as bit) end) as IsPresent,
			ISNULL(EAR.AbsentReasonId,0) as AbsentReasonId,CASE WHEN EAR.UpdatedUserId IS NULL THEN cast(0 as bit) ELSE cast(1 as bit) END AS IsDeleted,
			ISNULL(EAR.AttendanceTagId,0) AS AttendanceTagId,ISNULL(EAR.LeaveTypeId,0) AS LeaveTypeId,ISNULL(EAR.LeavePeriodId,0) AS LeavePeriodId,
			ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') AS FirstIn,ISNULL(D'+convert(nvarchar(15),@lDay)+'_Out,''00:00'') AS LastOut,ISNULL(D'+convert(nvarchar(15),@lDay)+'_L,''00:00'') AS LateBy,ISNULL(D'+convert(nvarchar(15),@lDay)+'_E,''00:00'') AS EarlyBy, ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') AS Duration,
			ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') AS OldPresentStatus,
			CASE When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId, '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''H'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''PH''
			 When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''H'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')=''00:00'')) THEN ''H''  
			 When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''PW''
			 When (([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''W''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'')AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''P''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''PW'')AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00''))  then ''P''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'')AND ([sHrm].[fWeekHOffGetBio](EM.EmployeeId , '+convert(nvarchar(15),@lYear)+' ,'+convert(nvarchar(15),@lMonth)+' ,'+convert(nvarchar(15),@lDay)+' ,'+convert(nvarchar(15), @rBatchId)+' ,DepartmentId ,'+convert(nvarchar(15),@rOrgId)+' )!=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''A''
			 WHEN ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''W'') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') !=''00:00'')) THEN ''PW''
			 When ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'')=''XX'')AND (Cast('''+convert(nvarchar(15),@rAttendanceDate)+''' as date)<GETDATE()) And (cast(EM.DateOfJoining as date)<= Cast('''+convert(nvarchar(15),@rAttendanceDate)+''' as date) OR ISNULL(EM.DateOfJoining,'''')='''')AND (EM.DateOfleaving>= Cast('''+convert(nvarchar(15),@rAttendanceDate)+''' as date) OR ISNULL(EM.DateOfleaving,'''')='''') AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') =''00:00''))  then ''A''
			 ELSE
			 ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') END as PresentStatus
			 From 
		sHrm.vExtEmployeeMaster EM 
		LEFT JOIN sBiometric.tMonthTrans T1 ON EM.EmployeeId = T1.EmployeeId AND (ISNULL(T1.SourceTypeId,95) = 95 OR SourceTypeId = 0) AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *100+ 01) as datetime)
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=EM.EmployeeId AND EAR.AttendanceDate ='''+convert(nvarchar(15),@rAttendanceDate)+'''  AND (EAR.BatchId ='+convert(nvarchar(15), @rBatchId)+')
		Left JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id =EM.OrgId
		LEFT JOIN sBiometric.tBiometricTypeMaster BTM ON BTM.OrgGroupId=OM.OrgGroupId AND BTM.Status=REPLACE(T1.D'+convert(nvarchar(15),@lDay)+',''PW'',''PH'')
		WHERE 
			 ((EM.DepartmentId='+convert(nvarchar(15),@rDepartmentId)+') OR ('+convert(nvarchar(15),@rDepartmentId)+'=0))
		  AND ((EM.Code like '''+convert(nvarchar(15),@rCode)+''' ) OR (ISNULL('''+convert(nvarchar(15),@rCode)+''','''')=''''))
		  AND (EM.OrgId = '+convert(nvarchar(15),@rOrgId)+')
		  AND ((EM.DateOfleaving >= '''+convert(nvarchar(15),@rAttendanceDate)+''' ) OR ISNULL(EM.DateOfleaving,'''') = '''')
          AND ((EM.DateOfJoining <='''+convert(nvarchar(15),@rAttendanceDate)+''' ) OR ISNULL(EM.DateOfJoining,'''') = '''') 
		  AND (EM.StatusId = 7)
		  AND (EM.IsOtherUser = 0)
		  AND  (( '''+convert(nvarchar(15),@TimeSheetStatusId)+''' = ''1'' AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') < ''09:30'')) OR ( '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  != ''1'' AND ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') = '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  OR '''+convert(nvarchar(15),@TimeSheetStatusId)+''' =''0''))))
          ORDER BY EM.Number'
	--print @strQuery
	execute (@strQuery )
	--print @strQuery
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pBiometricLogGet]
	
	@rOrgId int,
	@rFromDate date,
	@rToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

       SELECT 
            Bl.Id,
            BL.LogDateTime,
            BL.LogTitle,
            BL.Remarks,
            OM.Id AS OrgId,
            OM.DisplayTitle AS Organization
       FROM 
            sBiometric.tLog BL
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId 
       WHERE 
			((OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((LogDateTime >= @rFromDate) OR (@rFromDate <= '')) 
			AND ((LogDateTime <= @rToDate) OR (@rToDate >= ''))
       ORDER BY LogDateTime DESC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pBiometricReportData]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rDeptId int,
	@rForYear int=0,
	@rForMonth int=0,
	@rIsFirstIn bit=0,
	@rIsLastOut bit=0,
	@rIsOT bit=0,
	@rIsLateBy	bit=0,
	@rIsEarlyBy bit=0,
	@rIsDuration  bit=0,
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0,
	@rOrgGroupId int = 0,
	@OrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lATTN_DATE nvarchar(20)
	DECLARE @lBatchID int
	DECLARE @Days int 
	SELECT @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1

	SET @lATTN_DATE = CONVERT(nvarchar(10),@rForYear) + '-' + Right('000000' + CONVERT(nvarchar, @rForMonth), 2) + '-01'
	
	DECLARE @lDN1 nvarchar(10),@lDN2 nvarchar(10),@lDN3 nvarchar(10),@lDN4 nvarchar(10),@lDN5 nvarchar(10),
	@lDN6 nvarchar(10),@lDN7 nvarchar(10),@lDN8 nvarchar(10),@lDN9 nvarchar(10),@lDN10 nvarchar(10),
	@lDN11 nvarchar(10),@lDN12 nvarchar(10),@lDN13 nvarchar(10),@lDN14 nvarchar(10),@lDN15 nvarchar(10),
	@lDN16 nvarchar(10),@lDN17 nvarchar(10),@lDN18 nvarchar(10),@lDN19 nvarchar(10),@lDN20 nvarchar(10),
	@lDN21 nvarchar(10),@lDN22 nvarchar(10),@lDN23 nvarchar(10),@lDN24 nvarchar(10),@lDN25 nvarchar(10),
	@lDN26 nvarchar(10),@lDN27 nvarchar(10),@lDN28 nvarchar(10),@lDN29 nvarchar(10),@lDN30 nvarchar(10),
	@lDN31 nvarchar(10)
	
	SET @lDN1 = '01 ' + substring(DATENAME( dw, convert( date, ( '01' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN2 = '02 ' + substring(DATENAME( dw, convert( date, ( '02' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN3 = '03 ' + substring(DATENAME( dw, convert( date, ( '03' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN4 = '04 ' + substring(DATENAME( dw, convert( date, ( '04' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN5 = '05 ' + substring(DATENAME( dw, convert( date, ( '05' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN6 = '06 ' + substring(DATENAME( dw, convert( date, ( '06' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN7 = '07 ' + substring(DATENAME( dw, convert( date, ( '07' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN8 = '08 ' + substring(DATENAME( dw, convert( date, ( '08' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN9 = '09 ' + substring(DATENAME( dw, convert( date, ( '09' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN10 = '10 ' + substring(DATENAME( dw, convert( date, ( '10' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN11 = '11 ' + substring(DATENAME( dw, convert( date, ( '11' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN12 = '12 ' + substring(DATENAME( dw, convert( date, ( '12' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN13 = '13 ' + substring(DATENAME( dw, convert( date, ( '13' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN14 = '14 ' + substring(DATENAME( dw, convert( date, ( '14' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN15 = '15 ' + substring(DATENAME( dw, convert( date, ( '15' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN16 = '16 ' + substring(DATENAME( dw, convert( date, ( '16' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN17 = '17 ' + substring(DATENAME( dw, convert( date, ( '17' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN18 = '18 ' + substring(DATENAME( dw, convert( date, ( '18' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN19 = '19 ' + substring(DATENAME( dw, convert( date, ( '19' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN20 = '20 ' + substring(DATENAME( dw, convert( date, ( '20' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN21 = '21 ' + substring(DATENAME( dw, convert( date, ( '21' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN22 = '22 ' + substring(DATENAME( dw, convert( date, ( '22' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN23 = '23 ' + substring(DATENAME( dw, convert( date, ( '23' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN24 = '24 ' + substring(DATENAME( dw, convert( date, ( '24' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN25 = '25 ' + substring(DATENAME( dw, convert( date, ( '25' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN26 = '26 ' + substring(DATENAME( dw, convert( date, ( '26' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN27 = '27 ' + substring(DATENAME( dw, convert( date, ( '27' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN28 = '28 ' + substring(DATENAME( dw, convert( date, ( '28' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN29 = case when @Days >= 29 then '29 ' + substring(DATENAME( dw, convert( date, ( '29' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end
	SET @lDN30 = case when @Days >= 30 then '30 ' + substring(DATENAME( dw, convert( date, ( '30' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end
	SET @lDN31 = case when @Days < 31 Then '' else '31 ' + substring(DATENAME( dw, convert( date, ( '31' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end

	SELECT 
		datediff(day, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE),
		dateadd(month, 1, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE))) AS DayCount,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		
		@lDN1 as DN1,@lDN2 as DN2,@lDN3 as DN3,@lDN4 as DN4,@lDN5 as DN5,@lDN6 as DN6,@lDN7 as DN7,@lDN8 as DN8,@lDN9 as DN9,@lDN10 as DN10,
		@lDN11 as DN11,@lDN12 as DN12,@lDN13 as DN13,@lDN14 as DN14,@lDN15 as DN15,@lDN16 as DN16,@lDN17 as DN17,@lDN18 as DN18,@lDN19 as DN19,
		@lDN20 as DN20,@lDN21 as DN21,@lDN22 as DN22,@lDN23 as DN23,@lDN24 as DN24,@lDN25 as DN25,@lDN26 as DN26,@lDN27 as DN27,@lDN28 as DN28,	@lDN29 as DN29,@lDN30 as DN30,@lDN31 AS DN31,
		
		E.Code,	
		E.ShortName,
		DM.Displaytitle DeptName,
		DM.Code AS DeptCode,
		E.OrgID,
		DM.Id AS DepartmentId,
		EDM.Title AS Designation,
		EDM.Code AS DesignationCode,
		@rIsFirstIn AS IsFirstIn,
		@rIsLastOut AS IsLastOut,
		@rIsOT AS IsOT,
		@rIsLateBy	AS IsLateBy,
		@rIsEarlyBy AS IsEarlyBy,
		@rIsDuration  AS IsDuration,
		E.FirstName +' ' + E.MiddleName +' '+ E.LastName AS Name,
		sBiometric.fEmployeeLeaveTypeGet(Attn_Dt,T.EmployeeId) AS LeaveStatus,
		ISNULL(sBiometric.fEmployeeCLTypeGet(@rForMonth,@rForYear,T.EmployeeId),'') AS CLeaveStatus,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,1,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D01,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,2,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D02,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,3,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D03,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,4,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D04,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,5,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D05,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,6,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D06,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,7,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D07,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,8,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D08,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,9,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D09,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,10,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D10,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,11,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D11,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,12,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D12,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,13,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D13,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,14,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D14,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,15,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D15,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,16,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D16,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,17,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D17,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,18,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D18,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,19,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D19,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,20,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D20,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,21,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D21,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,22,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D22,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,23,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D23,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,24,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D24,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,25,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D25,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,26,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D26,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,27,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D27,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,28,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D28,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D29,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D30,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D31,

		case when @Days >= 29 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D29,
		case when @Days >= 30 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D30,
		case when @Days >= 31 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D31,


		
		E.Code AS  EmpCode, Attn_Dt, D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, 
		D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, 
		D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, 
		D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, D30_OUT, D31_OUT, D01_O, D02_O, D03_O, 
		D04_O, D05_O, D06_O, D07_O, D08_O, D09_O, D10_O, D11_O, D12_O, D13_O, D14_O, D15_O, D16_O, D17_O, D18_O, D19_O, D20_O, D21_O, D22_O, D23_O, 
		D24_O, D25_O, D26_O, D27_O, D28_O, D29_O, D30_O, D31_O, D01_L, D02_L, D03_L, D04_L, D05_L, D06_L, D07_L, D08_L, D09_L, D10_L, D11_L, D12_L, D13_L, 
		D14_L, D15_L, D16_L, D17_L, D18_L, D19_L, D20_L, D21_L, D22_L, D23_L, D24_L, D25_L, D26_L, D27_L, D28_L, D29_L, D30_L, D31_L, D01_T, D02_T, D03_T, 
		D04_T, D05_T, D06_T, D07_T, D08_T, D09_T, D10_T, D11_T, D12_T, D13_T, D14_T, D15_T, D16_T, D17_T, D18_T, D19_T, D20_T, D21_T, D22_T, D23_T, D24_T, 
		D25_T, D26_T, D27_T, D28_T, D29_T, D30_T, D31_T, D01_E, D02_E, D03_E, D04_E, D05_E, D06_E, D07_E, D08_E, D09_E, D10_E, D11_E, D12_E, D13_E, D14_E, 
		D15_E, D16_E, D17_E, D18_E, D19_E, D20_E, D21_E, D22_E, D23_E, D24_E, D25_E, D26_E, D27_E, D28_E, D29_E, D30_E, D31_E, D01_S, D02_S, D03_S, D04_S, 
		D05_S, D06_S, D07_S, D08_S, D09_S, D10_S, D11_S, D12_S, D13_S, D14_S, D15_S, D16_S, D17_S, D18_S, D19_S, D20_S, D21_S, D22_S, D23_S, D24_S, D25_S, 
		D26_S, D27_S, D28_S, D29_S, D30_S, D31_S, Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, TotalHour, Tot_HD, Tot_Early, Tot_Late, Tot_OT, Tot_OD, Tot_Leave, 
		Count_Late, Count_Early, Count_OT, Tot_CL, Tot_SL, Tot_EL, Tot_SP, Tot_C, Tot_PL, Tot_ML, T.EmployeeId,OM.Title AS OrganizationTitle,
		ISNULL(E.PunchId,'') AS PunchId,
		E.Number as EMPNumber            --Mantis - 30977
	FROM 
		sBiometric.tMonthTrans T
		INNER JOIN sHRM.tEmployeeMaster E on E.Id = T.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = E.OrgID
		LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = E.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
		LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId
	WHERE 
		(E.OrgId=@rOrgId OR @rOrgId = 0) 		
		AND (DM.Id = @rDeptId OR @rDeptId = 0)		 
		AND(T.Attn_dt = @lATTN_DATE) --AND E.StatusID = 7
		AND (MONTH(ED.DateofLeaving) >= @rForMonth AND YEAR(ED.DateofLeaving) >= @rForYear OR ED.DateofLeaving Is null )
		AND (E.STatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
		AND ISNULL(E.IsOtherUser,0) = 0 
		AND (ISNULL(T.SourceTypeId,95) = 95 OR T.SourceTypeId = 0)
		AND (T.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 
	ORDER BY 
	E.Code,T.Attn_dt
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pBiometricReportDataDateWise]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rIsFirstIn bit=0,
	 @rIsLastOut bit=0,
	 @rIsOT bit=0,
	 @rIsLateBy	bit=0,
	 @rIsEarlyBy bit=0,
	 @rIsDuration  bit=0,
	 @rGradeId nvarchar(200) = '0',
	 @rEmployeeStatusId int=0,
	 @rOrgGroupId int = 0,
	 @OrgGroupDepartmentId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

DECLARE @TableEmployee TABLE (Id int Identity,EmployeeID BigINT, OrganizationDepartmentId int, EmployeeTypeId Int)
INSERT INTO @TableEmployee
SELECT EM.Id AS EmployeeId,ED.OrganizationDepartmentId,ED.EmployeeTypeId from shrm.tEmployeeMaster EM 
INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id 
Where (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )
AND (ED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0 )
AND  (EM.ORgId = @rOrgId OR @rOrgId = 0)
AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 
AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 


DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lBatchID int
DECLARE @lEmployeeId bigint
DECLARE @lEmpCount int
DECLARE @lEmpDepartmentID int

DECLARE @TempDate TABLE(Id int identity,Idate date)
insert into @TempDate
SELECT  TOP (DATEDIFF(DAY, @rFromDate, @rToDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @rFromDate)
FROM    sys.all_objects a CROSS JOIN sys.all_objects b;

CREATE TABLE #TempMonthTrans (Id int Identity,EmployeeId bigint,Attn_Date DateTime,DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20),Shift nvarchar(25))

truncate table #TempMonthTrans

SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

Select @lCount = Max(Id) from @TempDate
Select @lEmpCount = Max(Id) from @TableEmployee
While (@lEmpCount > 0)
	BEGIN
		SELECT @lEmployeeId = EmployeeId,@lEmpDepartmentID = OrganizationDepartmentId  From @TableEmployee Where Id = @lEmpCount	
	set @lCount1 = 1
	while (@lCount1 <= @lCount)
	begin			
		Select @lDate = Idate from @TempDate Where Id = @lCount1
		Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

		DECLARE @weekoffstatus nvarchar(20)

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@rEmployeeId , @rForYear ,@rForMonth ,@rDay ,@rBatchId ,@rDepartmentId ,@rOrgId , @rBiometricStatus )
		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)		
		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(''' + convert(nvarchar(15),@lDate) + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',ED.OrganizationDepartmentId,' + convert(nvarchar(15),@rOrgId) + ')
		PRINT(@weekoffstatus)

		DECLARE @lLeaveOnWeekOff nvarchar(50)=''
		SELECT @lLeaveOnWeekOff=LTM.Code + '/' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
		FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
		WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate

		set @lQuery =  ' INSERT INTO #TempMonthTrans
						SELECT  ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
						CAse 
						When ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' in (''W'') AND '''+@lLeaveOnWeekOff+'''<>'''' Then ''' +@lLeaveOnWeekOff +'''
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') Then ''' +@weekoffstatus +''' 
						When D'+ convert(nvarchar(15),@lDay) +' =''XX'' AND  (Cast(''' + convert(nvarchar(15),@lDate) + ''' as date)<GETDATE()) And (cast(ED.DateOfJoining as date)<= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfJoining,'''')='''')AND (ED.DateOfleaving>= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfleaving,'''')='''')  then ''A''
						Else D'+convert(nvarchar(15),@lDay)+' End AS D'+convert(nvarchar(15),@lDay)+',D'+convert(nvarchar(15),@lDay)+'_IN,D'+convert(nvarchar(15),@lDay)+'_OUT,D'+convert(nvarchar(15),@lDay)+'_O,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T,D'+convert(nvarchar(15),@lDay)+'_E,D'+convert(nvarchar(15),@lDay)+'_S 
						FROM sBiometric.tMonthTrans T1 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 ) AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 0 )
						WHERE T1.EmployeeId =' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) AND (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				
						
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END

	--SELECT * FROM #TempMonthTrans
	
	SET @strQuery = 'select  Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,isnull(TotPresent,0) AS TotPresent,A1.TotWeekOff,
	isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,isnull(CLLeave,0) AS CLLeave,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,isnull(TotEarly,0) AS TotEarly,
	DM.Displaytitle DeptName,
	' + convert(nvarchar(10),@rIsFirstIn) + ' AS IsFirstIn,
	' + convert(nvarchar(10),@rIsLastOut) + ' AS IsLastOut,
	' +  convert(nvarchar(10),@rIsOT) + ' AS IsOT,
	' +  convert(nvarchar(10),@rIsLateBy) + '	AS IsLateBy,
	' +  convert(nvarchar(10),@rIsEarlyBy) + ' AS IsEarlyBy,
	' +  convert(nvarchar(10),@rIsDuration) + '  AS IsDuration,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID 
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN (''P'',''PW'',''PH'') group by EmployeeId,PresentStatus) A4 ON A4.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotEarly,EmployeeId from #TempMonthTrans Where PresentStatus IN (''E'') group by EmployeeId,PresentStatus) A6 ON A6.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like ''A'' group by EmployeeId,PresentStatus) A ON A.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN (''W'',''PW'',''PHW'') group by EmployeeId) A1 ON A1.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId,PresentStatus) A3 ON A3.EmployeeId = T.employeeID
    LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId,PresentStatus) A5 ON A5.EmployeeId = T.employeeID		
	
	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId 
	WHERE  (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
	AND (Emp.OrgId = ' + convert(nvarchar(15),@rOrgId) + ' OR ' + convert(nvarchar(15),@rOrgId) + ' = 0)
	AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') AND (len((''' + @rGRadeId + '''))= 1 AND EmployeeGradeId > 0 ) Or
   (len((''' + @rGRadeId + ''')) > 1 AND EmployeeGradeId in(' + convert(nvarchar(100),@rGRadeId) + ')) Order By T.EmployeeId,T.Attn_Date' 
	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	
	execute (@strQuery)
	
	
	

	
	DROP TABLE #TempMonthTrans
	--select  
	--@rBuilder1 as Builder1,
	--@rBuilder2 as Builder2,
	--'' as Attn_Date,
	--'' as EmployeeId,
	--'' as Attn_Date,
	--'' as DayNumber ,
	--'' as PresentStatus ,
	--'' as FirstIn,
	--'' as LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as TotPresent,
	--'' as TotWeekOff,
	--'' as TotHalfDay,
	--'' as TotHoliday,
	--'' AS TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrgId,
	--'' as OrganizationTitle
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pBiometricStudentAttendanceGet]
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rAttendanceDate date,
		-- @rRepeatCount tinyint,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @TimeSheetStatusId nvarchar(10) = '0'
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lMonth as nvarchar(3)
DECLARE @lYear as nvarchar(4)
  BEGIN
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rAttendanceDate) AS varchar(2)), 2)
	Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@rAttendanceDate) AS varchar(2)), 2)
	Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@rAttendanceDate) AS varchar(4)), 4)

	set @strQuery ='Select SA.AcademicId AS AcademicId,SA.Code AS StudentCode,SA.Name AS StudentName,ISNULL(SA.RollNo,0) as RollNo,ISNULL(SR.IsPresent,''true'') as IsPresent,
					ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,SR.RepeatCount,CASE WHEN SR.CreatedUserId IS NULL THEN cast(0 as bit) ELSE cast(1 as bit) END AS IsDeleted,ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
					ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') AS FirstIn,ISNULL(D'+convert(nvarchar(15),@lDay)+'_Out,''00:00'') AS LastOut,ISNULL(D'+convert(nvarchar(15),@lDay)+'_L,''00:00'') AS LateBy,
					ISNULL(D'+convert(nvarchar(15),@lDay)+'_E,''00:00'') AS EarlyBy, ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') AS Duration,ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') AS PresentStatus 
					From sStudent.vStudentAcademic SA 
					--Mantis:32909, change in below left join, change from SA.StudentId to SA.AcademicId
					LEFT JOIN sBiometric.tMonthTrans T1 ON SA.AcademicId = T1.EmployeeId AND T1.SourceTypeId=2001 AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *100+ 01


)
 as datetime)
					LEFT JOIN sAttendance.tStudentRegister SR  ON SR.AcademicId=SA.AcademicId AND SR.AttendanceDate ='''+convert(nvarchar(15),@rAttendanceDate)+''' AND  (SR.AttendanceTypeId='+convert(nvarchar(15),@rAttendanceTypeId)+')
					INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
				WHERE 
					((SA.ClassId='+convert(nvarchar(15),@rClassId)+') OR ('+convert(nvarchar(15),@rClassId)+'=0))
					  AND ((SA.DivisionId='+convert(nvarchar(15),@rDivisionId)+') OR ('+convert(nvarchar(15),@rDivisionId)+'=0))
					  AND (SA.OrgId = '+convert(nvarchar(15),@rOrgId)+')
					  AND (SA.BatchId = '+convert(nvarchar(15),@rBatchId)+')
					  AND (SA.StatusId NOT IN (2,3))
					  AND (AD.LeftDate > '''+convert(nvarchar(15),@rAttendanceDate)+''' OR ISNULL(AD.LeftDate,'''')= '''')
					  AND (AD.AdmissionDate <= '''+convert(nvarchar(15),@rAttendanceDate)+''')
					AND  (( '''+convert(nvarchar(15),@TimeSheetStatusId)+''' = ''1'' AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') < ''09:30'')) OR ( '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  != ''1'' AND ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''X



X'') = '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  OR '''+convert(nvarchar(15),@TimeSheetStatusId)+''' =''0''))))
				ORDER BY SA.RollNo'
	execute (@strQuery )
	--print @strQuery
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pBiometricTypeMasterAdd]
		
		@rStatus nvarchar(10),
		@rMainStatusId int,
		@rOrgGroupId int,
		@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	if not exists (select 1 from [sBiometric].[tBiometricTypeMaster] WHERE OrgGroupId=@rOrgGroupId AND Status=@rStatus)
	BEGIN
		INSERT INTO [sBiometric].[tBiometricTypeMaster]
		(
			Status,
			MainStatusId,
			OrgGroupId,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@rStatus,
			@rMainStatusId,
			@rOrgGroupId,
			@rUserId,
			sCommon.fGetDate()
		)

		SELECT 1 as Result
	END

	ELSE
	BEGIN
		UPDATE [sBiometric].[tBiometricTypeMaster]
		SET MainStatusId=@rMainStatusId,
			UpdtaedUserId=@rUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE Status=@rStatus
			AND OrgGroupId=@rOrgGroupId

		SELECT 11 as Result
	END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pBiometricTypeMasterGet]
		
		@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT (case when Status='HD' then 'Half Day'
			when Status='E' then 'Error Case'
			when Status='H' then 'Holiday'
			when Status='XX' then 'Not Applicable'
			when Status='LH' then 'Less Hours'
			when Status='PH' then 'Present On WeekOff Holiday'
			when Status='W' then 'Week Offs' END) as TimeSheetStatus , 
			* 
	From [sBiometric].[tBiometricTypeMaster] 
	WHERE OrgGroupId=@rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sBiometric].[pDeviceMasterCloudAdd]
	
	@rId int = 0,
	@rDeviceCode nvarchar(50) = '',
	@rDeviceName nvarchar(50) = '',
	@rDeviceIP nvarchar(50) = '',
	@rDeviceID nvarchar(50) = '',
	@rPortNumber nvarchar(100) = '',
	@rMode nvarchar(50) = '',	
	@rDevicePassword nvarchar(50) = '',
	@rOrgId int = 0,
	@rDeviceSRNo nvarchar(50) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rId = 0)
	BEGIN
		INSERT INTO sBiometric.tDeviceMasterCloud 
		(
			DeviceCode,
			DeviceName,
			DeviceIP,
			DeviceID,
			DevicePort,
			DevicePassword,
			Mode,
			DeviceSrNo,
			OrgId
		)
		VALUES 
		(
			@rDeviceCode,
			@rDeviceName,
			@rDeviceIP,
			@rDeviceID,
			@rPortNumber,
			@rDevicePassword,
			@rMode,
			@rDeviceSRNo,
			@rOrgId
		)
	END
	ELSE
	BEGIN
		UPDATE sBiometric.tDeviceMasterCloud 
		SET 
		DeviceCode = @rDeviceCode,
		DeviceName = @rDeviceName,
		DeviceIP = @rDeviceIP,
		DeviceID = @rDeviceID,
		DevicePort = @rPortNumber,
		DevicePassword = @rDevicePassword,
		Mode = @rMode,
		DeviceSrNo = @rDeviceSRNo,
		OrgId = @rOrgId
		WHERE AutoId = @rId
	END

	SELECT 1 AS Reult
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sBiometric].[pDeviceMasterCloudGet]
	
	@rId int = 0,
	@rDeviceCode nvarchar(50) = '',
	@rOrgId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT
		AutoId,
		DeviceID,
		DeviceIP,
		DevicePort,
		DeviceName,
		Mode,
		DeviceCode,
		DevicePassword,
		DeviceSrNo
	FROM
		sBiometric.tDeviceMasterCloud
	WHERE
		OrgId = @rOrgId
		AND (DeviceCode = @rDeviceCode OR @rDeviceCode = '')
		AND (AutoId = @rId OR @rId = 0)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sBiometric].[pEarlyDepartureReportGet]
 @rFromDate Date,
 @rToDate Date,
 @rOrgGroupId int =0,
 @rBuilder1 nvarchar(max)='',
 @rBuilder2 nvarchar(max)='',
 @rOrgId int = 0 
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 Select 
	  @rBuilder1 AS Builder1,@rBuilder2 AS Builder2,
	  Em.code,P.AtdDate,EM.DepartmentName,EM.EmployeeName,p.[Status] as [Status],P.CheckOutTime,
	  Sh.PunchId , SFM.ShiftName as shiftName,p.EarlyLeaveTime
	  from sBiometric.tProcess P 
	 INNER JOIN sHrm.vExtEmployeeMaster EM ON P.SourceId= EM.EmployeeId AND P.SourceTypeId = 3
	 left join sHrm.tEmployeeMaster SH on SH.Id =  p.SourceId
	 left join sBiometric.tShiftMaster SFM on SFM.Id = SH.ShiftId
	 Where 
	  ((P.AtdDate >= @rFromDate) OR (@rFromDate <= '')) 
	  AND ((P.AtdDate <= @rToDate) OR (@rToDate >= ''))
	  and p.EarlyLeaveTime > '0.00'
	 
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

CREATE OR ALTER PROCEDURE [sBiometric].[pEmployeeCheckInAdd]
	 
	 	@rEmployeeId bigint,
        @rAttendanceDate Datetime='', 
        @rCheckInTime Datetime='',
		@rCheckOutTime Datetime='',
		@rEmployeePhoto varbinary(max)=null,
		@rId int=0,
		@rLatitude nvarchar(20) = '',
		@rLongitude nvarchar(20) = '',
		@rLocation nvarchar(200) = '' 
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	--IF(@rId = 0)	
	--BEGIN 
	IF EXISTS (SELECT 1 FROM sBiometric.tEmployeeCheckIn WHERE EmployeeId = @rEmployeeId AND CAST(AttendanceDate AS DATE) = CAST(@rAttendanceDate AS DATE))
	BEGIN 
		SELECT -1 AS RESULT
		RETURN
	END
	ELSE 
	BEGIN
	INSERT INTO sBiometric.tEmployeeCheckIn
		(
			
			EmployeeId,
			AttendanceDate,
			CheckInTime,
			EmployeePhoto,
			LatitudeAxis,
			LongitudeAxis,
			Location
		)
	VALUES
		( 
			@rEmployeeId,
			@rAttendanceDate,
			@rCheckInTime,
			@rEmployeePhoto,
			@rLatitude,
			@rLongitude,
			@rLocation
		)
	 SELECT 1  As result
	
	END	 

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

 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sBiometric].[pEmployeeCheckInGet]
	 
	 @rOrgId int = 0,
	 @rEmployeeId bigint=0,
	 @rFromDate date = '',
	 @rToDate date = ''
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 Select 
		U.LoginTitle,B.EmployeePhoto ,EMp.FirstName+' ' +ISNULL(EMp.MiddleName,'')+' '+emp.LastName AS Name,CONVERT(VARCHAR(10),B.CheckInTime,3) AS [DATE],CAST(B.CheckInTime AS TIME) AS CheckInTime,Emp.Id As EmployeeID ,CAST(B.CheckOutTime AS TIME) AS CheckOutTime,B.Id,emp.Code,
		ISNULL(LatitudeAxis,'') AS LatitudeAxis, ISNULL(LongitudeAxis,'') AS LongitudeAxis, ISNULL(Location,'') AS Location, EMp.Code
	 from sSecurity.tUser 
	 U INNER JOIN sHrm.tEmployeeMaster EMP ON  EMP.Id=U.SourceId
	 INNER JOIN sBiometric.tEmployeeCheckIn B ON B.EmployeeID=EMP.Id
	 WHere U.SourceTypeId =95 AND (U.OrgId=@rORgId OR @rORgId = 0)
	 AND ((B.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0)) AND  ISNULL(EMP.IsOtherUser,0) = 0 
	 AND ((CAST(B.AttendanceDate AS DATE) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 AND ((CAST(B.AttendanceDate AS DATE) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sBiometric].[pEmployeeCheckInUpdate]
	 
	 	@rEmployeeId bigint, 
		@rCheckOutTime Datetime='' ,
		@rId bigint=0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 
	    UPDATE sBiometric.tEmployeeCheckIn
	    SET
		 
			CheckOutTime=@rCheckOutTime 
			 
	      WHERE EmployeeId = @rEmployeeId AND ((Id=@rId) OR (@rId=0))
	   
	     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sBiometric].[pEmployeeConfigurationAdd]

@rXmlDoc nvarchar(max) = ''

AS
SET NOCOUNT ON

BEGIN
--SET @rXmlDoc=REPLACE(@rXmlDoc,'<','&lt;')
--SET @rXmlDoc=REPLACE(@rXmlDoc,'>','&gt;')
--SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
@intDoc INT,
@lEmployeeId bigint = 0,
@lEmployeeConfigurationMasterId int = 0,
@lValue nvarchar(100) = '',
@lCount int = 0
--BEGIN TRY
BEGIN TRANSACTION					
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	

	CREATE TABLE #tTable
	(
		Id bigint identity
		,EmployeeId bigint not null
		,EmployeeConfigurationMasterId int not null
		,Value nvarchar(100) not null
	)

	INSERT INTO #tTable
	(			    
		EmployeeId
		,EmployeeConfigurationMasterId
		,Value
	)
	SELECT
		A.EmployeeId,
		A.EmployeeConfigurationMasterId,			
		A.Value
	FROM OPENXML (@intDoc, '/Table/EmployeeConfiguration', 1)
	WITH
	(						
		EmployeeId bigint '@EmployeeId',
		EmployeeConfigurationMasterId int '@EmployeeConfigurationMasterId',
		Value nvarchar(100) '@Value'
	) A

	--SELECT * FROM #tTable

	EXEC sp_xml_removedocument @intDoc

SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 

BEGIN
	SELECT
		@lEmployeeId = EmployeeId,
		@lEmployeeConfigurationMasterId = EmployeeConfigurationMasterId,
		@lValue = Value
	FROM #tTable WHERE Id = @lCount

	IF EXISTS(SELECT 1 FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @lEmployeeId AND EmployeeConfigurationMasterId = @lEmployeeConfigurationMasterId)
	BEGIN
		DELETE FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @lEmployeeId AND EmployeeConfigurationMasterId = @lEmployeeConfigurationMasterId
	END

	INSERT INTO sBiometric.tEmployeeConfiguration 
	(
		EmployeeId
		,EmployeeConfigurationMasterId
		,Value
	)
	VALUES
	(
		@lEmployeeId,
		@lEmployeeConfigurationMasterId,
		@lValue
	)

	SET @lCount = @lCount - 1
END
SELECT 1 AS RESULT

		DROP TABLE #tTable
		COMMIT TRANSACTION

	--END TRY
	--BEGIN CATCH
	--ROLLBACK TRANSACTION
	--SELECT -1 AS RESULT
	--END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pEmployeeConfigurationGet]

@rEmployeeConfigurationMasterId int = 0,
@rEmployeeCode nvarchar(20) = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT
		EM.Code AS EmployeeCode,
		EC.EmployeeId AS EmployeeId,
		(EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ISNULL(' ' + EM.LastName, '')) AS EmployeeName, 
		EC.EmployeeConfigurationMasterId AS EmployeeConfigurationMasterId,
		ECM.Title AS EmployeeConfiguration,
		EC.Value AS Value
	FROM 
		sBiometric.tEmployeeConfiguration EC
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EC.EmployeeId
		INNER JOIN sBiometric.tEmployeeConfigurationMaster ECM ON ECM.Id = EC.EmployeeConfigurationMasterId
	WHERE
		(EM.Code = @rEmployeeCode OR @rEmployeeCode = '')
		AND (EC.EmployeeCOnfigurationMasterId = @rEmployeeConfigurationMasterId OR @rEmployeeConfigurationMasterId = 0)
		AND ISNULL(EM.IsOtherUser,0) = 0 AND EM.StatusId = 7 AND ECM.IsObsolete = 0

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pEmployeeImportCloudUpdate]

@rXmlDoc nvarchar(max) = ''

AS
SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT,
			@rEmployeeId BIGINT,
			@rDate VARCHAR(20),
			@rCode INT,
			@rTotalML INT = 0,
			@rTotalPL INT = 0			


--BEGIN TRY
BEGIN TRANSACTION					
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	
	CREATE TABLE #tTable  
	(
		EmployeeId bigint not null
		,PunchId varchar(50) null
		,ShiftId varchar(25) null
	)


	INSERT INTO #tTable
			   (			    
			   EmployeeId			  
			   ,PunchId			  
			   ,ShiftId	   		   
			   )
	SELECT		
		A.EmployeeId,
		PunchId,
		A.[ShiftId]		
		
	FROM OPENXML (@intDoc, '/Table/EmployeeImportCloudUpdate', 1)
	WITH
	(						
		EmployeeId bigint '@EmployeeId',
		PunchId varchar(50) '@PunchId',
		[ShiftId] varchar(25) '@ShiftId'
	)A 

	--SELECT * FROM #tTable		

	EXEC sp_xml_removedocument @intDoc
	Update EM SET
	PunchId=temp.PunchId,
	ShiftId=temp.ShiftId
	FROM sHrm.tEmployeeMaster EM INNER join #tTable temp ON temp.EmployeeId=EM.Id
	SELECT 1 AS RESULT

	DROP TABLE #tTable
COMMIT TRANSACTION

	--END TRY
	--BEGIN CATCH
	--ROLLBACK TRANSACTION
	--SELECT -1
	--END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pEmployeeLateTimeGet]
	 	 @rOrgId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay int = 0
	SET @lDay = DAY(sCommon.fGetDate())

	DECLARE @lColumnName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 398 AND SourceId = @rOrgId

	IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime)>0)
	BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query = 'SELECT
				EM.Id AS EmployeeId,
				EM.Code,
				ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS  EmployeeName,
				DT.Title As DepartmentTitle,
				 '+@lColumnName+' AS Time
		FROM 
				sHrm.tEmployeeMaster EM
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = EM.Id AND MT.SourceTypeId = 95
				INNER JOIN sHrm.tEmployeeJobDetail JD ON EM.Id=JD.EmployeeId
				INNER JOIN sSetup.tDepartmentMaster DT ON JD.OrganizationDepartmentId=DT.Id
		WHERE
				EM.OrgID = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND EM.StatusId = 7	'

		--print (@Query)
		execute (@Query)	
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pEmployeeLeaveVerifyGet]

	@rCode nvarchar(20)='',
	@rName nvarchar(100)='',
	@rDepartmentId int=0,
	@rEmployeeGroupId int=0,
	@rForYear int,
	@rForMonth int,
	@rOrgId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	BEGIN
		SET @rName= sCommon.fSearchStringGet(@rName)
	END
	
	
	DECLARE @lAttndanceDate nvarchar(20)
	DECLARE @lBatchId int = 0
	DECLARE @lDays int = 0
	
	SELECT @lBatchId = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
	SET @lAttndanceDate = convert(nvarchar(10),@rForYear) + '-' + convert(nvarchar(10),@rForMonth) + '-' + '01'
	
	DECLARE @rFromDate date
	DECLARE @rToDate date
	DECLARE @rEmployeeId bigint
	
	SELECT @lDays = sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	SET @rFromDate = convert(nvarchar(10),@rForYear) + '-' + convert(nvarchar(10),@rForMonth) + '-' + '01'
	SET @rToDate = convert(nvarchar(10),@rForYear) + '-' + convert(nvarchar(10),@rForMonth) + '-' + convert(nvarchar(10),@lDays)
	
	DECLARE @lMonthlyStatusUpdate TABLE(Id int identity, EmployeeId bigint,	AttndanceDate DateTime,PresentStatus nvarchar(50),FirstIn nvarchar(20),LastOut nvarchar(20))
	
	INSERT INTO @lMonthlyStatusUpdate 
	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 01) as datetime),D01,D01_IN,D01_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 02) as datetime),D02,D02_IN,D02_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 03) as datetime),D03,D03_IN,D03_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 04) as datetime),D04,D04_IN,D04_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 05) as datetime),D05,D05_IN,D05_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 06) as datetime),D06,D06_IN,D06_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 07) as datetime),D07,D07_IN,D07_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 08) as datetime),D08,D08_IN,D08_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 09) as datetime),D09,D09_IN,D09_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 10) as datetime),D10,D10_IN,D10_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 11) as datetime),D11,D11_IN,D11_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 12) as datetime),D12,D12_IN,D12_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 13) as datetime),D13,D13_IN,D13_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 14) as datetime),D14,D14_IN,D14_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 15) as datetime),D15,D15_IN,D15_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 16) as datetime),D16,D16_IN,D16_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 17) as datetime),D17,D17_IN,D17_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 18) as datetime),D18,D18_IN,D18_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 19) as datetime),D19,D19_IN,D19_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 20) as datetime),D20,D20_IN,D20_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 21) as datetime),D21,D21_IN,D21_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 22) as datetime),D22,D22_IN,D22_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 23) as datetime),D23,D23_IN,D23_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 24) as datetime),D24,D24_IN,D24_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 25) as datetime),D25,D25_IN,D25_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 26) as datetime),D26,D26_IN,D26_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 27) as datetime),D27,D27_IN,D27_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 28) as datetime),D28,D28_IN,D28_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO @lMonthlyStatusUpdate 
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 29) as datetime),D29,D29_IN,D29_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO @lMonthlyStatusUpdate 
	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 30) as datetime),D30,D30_IN,D30_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO @lMonthlyStatusUpdate 
	SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 31) as datetime),D31,D31_IN,D31_OUT FROM sBiometric.tMonthlyStatusUpdate WHERE --EmployeeId = @rEmployeeId
	AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	SELECT 
		MSU.EmployeeId,
		vEM.Code,
		vEM.EmployeeName,
		T.AttndanceDate,
		T.PresentStatus,
		[sBiometric].[fEmployeeOnLeaveGet](T.AttndanceDate , T.EmployeeId ) AS EmployeeOnLeave
	FROM 
		@lMonthlyStatusUpdate T
		INNER JOIN sBiometric.tMonthlyStatusUpdate MSU ON T.EmployeeId = MSU.EmployeeId
		INNER JOIN sHrm.vExtEmployeeMaster vEM ON MSU.EmployeeId = vEM.EmployeeId
	WHERE 
		(vEM.Code = @rCode OR ISNULL(@rCode,'') ='')
		AND (vEM.EmployeeName LIKE @rName OR ISNULL(@rName,'') = '') 
		AND (vEM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND (vEM.EmployeeGroupId = @rEmployeeGroupId OR @rEmployeeGroupId = 0)
		AND (vEM.OrgId=@rOrgId) 
		AND	(MSU.AttndanceDate = @lAttndanceDate) AND vEM.StatusID = 7
		AND (T.PresentStatus = 'A' OR T.PresentStatus = 'HD' OR T.PresentStatus = 'E')
    ORDER BY vEM.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sBiometric].[pEmployeeManualPunchToTimeSheetAdd]

@rXmlDoc nvarchar(max) = ''

AS
SET NOCOUNT ON

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

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

CREATE TABLE #tTable(
Id bigint identity
,EmployeeId bigint not null
,Attn_Date date not null
,FirstIn varchar(50) null
,LastOut varchar(50) null
)

INSERT INTO #tTable
(			    
EmployeeId
,Attn_Date
,FirstIn
,LastOut
)
SELECT
	A.EmployeeId,
	A.Attn_Date,			
	A.FirstIn,
	A.LastOut
FROM OPENXML (@intDoc, '/Table/TimeSheetUpdate', 1)
	WITH
	(						
		EmployeeId bigint '@EmployeeId',
		Attn_Date datetime '@Attn_Date',
		FirstIn varchar(50) '@FirstIn',
		LastOut varchar(50) '@LastOut'
	) A

EXEC sp_xml_removedocument @intDoc
SELECT * FROM #tTable

DECLARE @lCount int = 1
DECLARE @lTotal int = (SELECT COUNT(Id) FROM #tTable)	
WHILE @lCount <= @lTotal 
BEGIN

DECLARE @rEmployeeId bigint = (SELECT EmployeeId FROM #tTable WHERE Id = @lCount)
DECLARE @rInTime varchar(50) = (SELECT FirstIn FROM #tTable WHERE Id = @lCount)
DECLARE @rOutTime varchar(50) = (SELECT LastOut FROM #tTable WHERE Id = @lCount)
DECLARE @rDate date = (SELECT Attn_Date FROM #tTable WHERE Id = @lCount)


DECLARE @lFlag bit = 0
DECLARE @SQL NVARCHAR(MAX) = ''		
DECLARE @lCode int = 0
DECLARE @lTotalTime varchar(10) = ''
IF(@rOutTime <> '') 
BEGIN SET @lTotalTime = CONVERT(varchar(5),DATEADD(minute,DATEDIFF(minute,@rInTime,@rOutTime),0), 114) 
END
ELSE BEGIN SET @lTotalTime = '00:00' END
DECLARE @lTotalMOnthDays int = (select  day(dateadd(month, datediff(month, 0, @rDate) + 1, -1)))
DECLARE @lTotalAttnDays varchar(10) = ''
DECLARE @lTotalAbsDays varchar(10) = ''
DECLARE @lColumn NVARCHAR(10) = (SELECT DAY(@rInTime))
SET @lColumn = (SELECT CASE WHEN @lColumn BETWEEN 0 AND 9 THEN RIGHT('0' + CAST(@lColumn AS VARCHAR(2)), 2) ELSE CAST(@lColumn AS NVARCHAR(10)) END)

	IF EXISTS(SELECT 1 FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)
	BEGIN	
		SET @lCode = (SELECT EmpCode FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)
		SET @lTotalAttnDays = (SELECT Tot_Attn FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)
		SET @lTotalAbsDays = (SELECT Tot_Abs FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)

		SET @SQL = 'IF EXISTS(SELECT 1 FROM sBiometric.tMonthTrans WHERE D'+CAST(@lColumn AS VARCHAR)+' = ''A'' AND EmployeeId = '+CAST(@rEmployeeId AS VARCHAR) + ' AND Attn_Dt = ''' + CAST(@rDate AS VARCHAR) + ''' AND SourceTypeId = 95) BEGIN SET @lFlag = 1 END' 				
		EXEC sp_executesql @SQL, N'@lFlag bit OUTPUT',@lFlag =  @lFlag OUTPUT

		IF(@lFlag = 1) 
		BEGIN
			SET @lTotalAttnDays = @lTotalAttnDays + 1
			SET @lTotalAbsDays = @lTotalAbsDays - 1
		END			
	END
	ELSE
	BEGIN	
		SET @lTotalAttnDays = 1
		SET @lTotalAbsDays = @lTotalMOnthDays - 1
		SET @lCode = (SELECT ISNULL(MAX(EmpCode),0) + 1 FROM sBiometric.tMonthTrans WHERE SourceTypeId = 95)
		INSERT INTO sBiometric.tMonthTrans VALUES(
		@lCode,@rDate,
		'A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX',
		 0,0,0,0,'0',0,'00:00','00:00','00:00',0,0,0,0,0,0,0,0,0,0,0,0,@rEmployeeId,95)
	END		

		SET @SQL = 'UPDATE sBiometric.tMonthTrans
		SET D'+CAST(@lColumn AS VARCHAR)+'_IN = '''+CAST(CAST(@rInTime as time) AS VARCHAR(5))+''',
		D'+CAST(@lColumn AS VARCHAR)+'_OUT = '''+CAST(CAST(@rOutTime as time) AS VARCHAR(5))+''',		
		D'+CAST(@lColumn AS VARCHAR)+'_T = '''+CAST(@lTotalTime AS VARCHAR)+''',
		D'+CAST(@lColumn AS VARCHAR)+' = ''P'',Tot_Attn = '+CAST(@lTotalAttnDays AS VARCHAR)+',Tot_Abs = '+CAST(@lTotalAbsDays AS VARCHAR)+'
		WHERE EmployeeId = '+CAST(@rEmployeeId AS VARCHAR) + ' AND Attn_Dt = ''' + CAST(@rDate AS VARCHAR) + ''' AND SourceTypeId = 95'
		
		PRINT @SQL

		EXEC (@SQL)

		IF(@lTotalMOnthDays = 28) 
		BEGIN
			UPDATE sBiometric.tMonthTrans SET D29 = 'XX',D30 = 'XX',D31 = 'XX' WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95 
		END
		ELSE IF(@lTotalMOnthDays = 29) 
		BEGIN
			UPDATE sBiometric.tMonthTrans SET D30 = 'XX',D31 = 'XX' WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95
		END
		ELSE IF(@lTotalMOnthDays = 30) 
		BEGIN
			UPDATE sBiometric.tMonthTrans SET D31 = 'XX' WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95
		END
		
		SET @lCount = @lCount + 1
		END

		SELECT 1 AS RESULT
		DROP TABLE #tTable
		COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sBiometric].[pESSLCloudDataSync] @rToDate DATE
	,@rFromDate DATE
AS
SET NOCOUNT ON

BEGIN
	--Drop temp table for server issue(tempdb)
	IF object_id('tempdb..#tTable') IS NOT NULL
	BEGIN
		DROP TABLE #tTable
	END

	CREATE TABLE #tTable (
		Id BIGINT identity
		,[SourceId] [bigint] NOT NULL
		,[In_Out_Time] [datetime] NOT NULL
		,[ShiftCode] [int] NOT NULL
		,[Attn_Dt] [date] NOT NULL
		,[Mode] [nvarchar](10) NOT NULL
		,[CreatedDateTime] [datetime] NOT NULL
		,[DeviceIP] [nvarchar](20) NOT NULL
		,[EntryMode] [tinyint] NOT NULL
		,[PunchId] [nvarchar](50) NOT NULL
		,[TransactionId] [bigint] NOT NULL
		,[SourceTypeId] [smallint] NULL
		,[IsProcessed] [bit] NULL
		)

	DECLARE @lPrevAttn_Dt DATE = ''
	DECLARE @lPrevSourceId BIGINT = 0
	DECLARE @lPrevSourceTypeId SMALLINT = 0

	UPDATE [sBiometric].[tCloudTransactionData]
	SET IsProcessed = 0
	WHERE cast(In_Out_Time AS DATE) >= @rFromDate
		AND cast(In_Out_Time AS DATE) <= @rToDate

	INSERT INTO #tTable
	SELECT [SourceId]
		,[In_Out_Time]
		,[ShiftCode]
		,[Attn_Dt]
		,[Mode]
		,[CreatedDateTime]
		,[DeviceIP]
		,[EntryMode]
		,[PunchId]
		,[TransactionId]
		,[SourceTypeId]
		,[IsProcessed]
	FROM [sBiometric].[tCloudTransactionData]
	WHERE YEAR(Attn_Dt) = YEAR(sCommon.fGetDate())
		AND IsProcessed = 0

	SELECT *
	FROM #tTable

	DECLARE @lCount INT = 1
	DECLARE @lTotal INT = (
			SELECT COUNT(Id)
			FROM #tTable
			)

	WHILE @lCount <= @lTotal
	BEGIN
		DECLARE @lQuery NVARCHAR(max) = ''
		DECLARE @lAttn_Dt DATE = (
				SELECT Attn_Dt
				FROM #tTable
				WHERE Id = @lCount
				)
		DECLARE @lSourceId BIGINT = (
				SELECT SourceId
				FROM #tTable
				WHERE Id = @lCount
				)
		DECLARE @lSourceTypeId SMALLINT = (
				SELECT SourceTypeId
				FROM #tTable
				WHERE Id = @lCount
				)
		DECLARE @lTransactionId BIGINT = (
				SELECT TransactionId
				FROM #tTable
				WHERE Id = @lCount
				)

		IF (
				@lPrevAttn_Dt = @lAttn_Dt
				AND @lPrevSourceId = @lSourceId
				AND @lPrevSourceTypeId = @lSourceTypeId
				)
		BEGIN
			PRINT ('same employee')

			UPDATE sBiometric.tCloudTransactionData
			SET IsProcessed = 1
			WHERE TransactionId = @lTransactionId
		END
		ELSE
		BEGIN
			DECLARE @lCode INT = (
					SELECT ISNULL(MAX(EmpCode), 0) + 1
					FROM sBiometric.tMonthTrans
					)

			IF EXISTS (
					SELECT 1
					FROM sBiometric.tMonthTrans
					WHERE EmployeeId = @lSourceId
						AND SourceTypeId = @lSourceTypeId
					)
			BEGIN
				SET @lCode = (
						SELECT TOP 1 EmpCode
						FROM sBiometric.tMonthTrans
						WHERE EmployeeId = @lSourceId
							AND SourceTypeId = @lSourceTypeId
						)
			END

			DECLARE @lShift VARCHAR(25) = (
					SELECT ShiftName
					FROM sBiometric.tShiftMasterCloud
					WHERE ShiftCode IN (
							SELECT ShiftCode
							FROM #tTable
							WHERE Id = @lCount
							)
					)
			DECLARE @lShiftStartTime DATETIME = (
					SELECT StartTime
					FROM sBiometric.tShiftMasterCloud
					WHERE ShiftCode IN (
							SELECT ShiftCode
							FROM #tTable
							WHERE Id = @lCount
							)
					)
			DECLARE @lShiftEndTime DATETIME = (
					SELECT EndTime
					FROM sBiometric.tShiftMasterCloud
					WHERE ShiftCode IN (
							SELECT ShiftCode
							FROM #tTable
							WHERE Id = @lCount
							)
					)
			DECLARE @lMinHoursHalfDay TIME = CAST(CAST((
							SELECT MinHrsHalfDay
							FROM sBiometric.tShiftMasterCloud
							WHERE ShiftCode IN (
									SELECT ShiftCode
									FROM #tTable
									WHERE Id = @lCount
									)
							) AS NVARCHAR) AS TIME)
			DECLARE @lMinHoursFullDay TIME = CAST(CAST((
							SELECT MinHrsFullDay
							FROM sBiometric.tShiftMasterCloud
							WHERE ShiftCode IN (
									SELECT ShiftCode
									FROM #tTable
									WHERE Id = @lCount
									)
							) AS NVARCHAR) AS TIME)
			DECLARE @lIn TIME = CONVERT(TIME, (
						SELECT MIN(In_Out_Time)
						FROM sBiometric.tCloudTransactionData
						WHERE Attn_Dt = @lAttn_Dt
							AND SourceId = @lSourceId
							AND SourceTypeId = @lSourceTypeId
						))
			DECLARE @lOut TIME = CASE 
					WHEN (
							SELECT COUNT(In_Out_Time)
							FROM sBiometric.tCloudTransactionData
							WHERE Attn_Dt = @lAttn_Dt
								AND SourceId = @lSourceId
								AND SourceTypeId = @lSourceTypeId
							) > 1
						THEN CONVERT(TIME, (
									SELECT MAX(In_Out_Time)
									FROM #tTable
									WHERE Attn_Dt = @lAttn_Dt
										AND SourceId = @lSourceId
										AND SourceTypeId = @lSourceTypeId
									))
					ELSE '00:00'
					END
			DECLARE @lTotalTime VARCHAR(10) = CASE 
					WHEN @lOut <> '00:00'
						THEN (
								SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lIn, @lOut), 0), 114)
								)
					ELSE '00:00'
					END
			DECLARE @lEarlyBy VARCHAR(10) = '00:00'
			DECLARE @lLateBy VARCHAR(10) = '00:00'
			DECLARE @lOverTime VARCHAR(10) = ''
			DECLARE @lStatus VARCHAR(10) = ''

			--Add by Nimesh MantisId:0027752
			--Start
			IF (
					DATEDIFF(minute, @lShiftStartTime, @lIn) > 0
					AND @lIn <> '00:00'
					)
			BEGIN
				--SET @lLateBy = '00:00'
				SET @lLateBy = (
						SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lShiftStartTime, @lIn), 0), 114)
						)
			END

			IF (
					DATEDIFF(minute, @lShiftEndTime, @lOut) < 0
					AND @lOut <> '00:00'
					)
			BEGIN
				--SET @lEarlyBy = '00:00'
				SET @lEarlyBy = (
						SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lOut, @lShiftEndTime), 0), 114)
						)
			END

			--End
			IF (DATEDIFF(minute, @lShiftEndTime, @lOut) < 0)
			BEGIN
				SET @lOverTime = '00:00'
			END
			ELSE
			BEGIN
				SET @lOverTime = CASE 
						WHEN @lOut <> '00:00'
							THEN (
									SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lShiftEndTime, @lOut), 0), 114)
									)
						ELSE '00:00'
						END
			END

			IF (CAST(@lTotalTime AS TIME) >= @lMinHoursFullDay)
			BEGIN
				SET @lStatus = 'P'
			END

			IF (
					CAST(@lTotalTime AS TIME) >= @lMinHoursHalfDay
					AND CAST(@lTotalTime AS TIME) < @lMinHoursFullDay
					)
			BEGIN
				SET @lStatus = 'HD'
			END

			IF (CAST(@lTotalTime AS TIME) < @lMinHoursHalfDay)
			BEGIN
				SET @lStatus = 'LH'
			END

			IF (
					@lOut = '00:00'
					AND @lIn <> '00:00'
					)
			BEGIN
				SET @lStatus = 'E'
			END

			--Uncomment this for testing purposes
			--PRINT('In Time: ' + CONVERT(VARCHAR(5),@lIn,108))
			--PRINT('Out Time: ' + CONVERT(VARCHAR(5),@lOut,108))
			--PRINT('Total Time : ' + CONVERT(VARCHAR(5),@lTotalTime,108))
			--PRINT('Overtime : ' + CONVERT(VARCHAR(5),@lOverTime,108))
			--PRINT('Min Hours Half Day : ' + CONVERT(VARCHAR(5),@lMinHoursHalfDay,108))
			--PRINT('Min Hours Full Day : ' + CONVERT(VARCHAR(5),@lMinHoursFullDay,108))
			--PRINT('EarlyBy : ' + CONVERT(VARCHAR(5),@lEarlyBy,108))
			--PRINT('LateBy : ' + CONVERT(VARCHAR(5),@lLateBy,108))
			--PRINT('Status : ' + CONVERT(VARCHAR(5),@lStatus,108))
			--BREAK
			DECLARE @lDay NVARCHAR(10) = (
					SELECT DAY(IN_Out_Time)
					FROM #tTable
					WHERE Id = @lCount
					)

			SET @lDay = (
					SELECT CASE 
							WHEN @lDay BETWEEN 0
									AND 9
								THEN RIGHT('0' + CAST(@lDay AS VARCHAR(2)), 2)
							ELSE CAST(@lDay AS NVARCHAR(10))
							END
					)

			DECLARE @lMonthTransAttn_DtTemp DATETIME = (
					SELECT cast((cast(YEAR(@lAttn_Dt) AS VARCHAR(255)) + '-' + cast(MONTH(@lAttn_Dt) AS VARCHAR(255)) + '-' + '01') AS DATETIME)
					)
			DECLARE @lMonthTransAttn_Dt VARCHAR(20) = convert(VARCHAR(20), @lMonthTransAttn_DtTemp, 20)

			PRINT (@lMonthTransAttn_Dt)

			IF NOT EXISTS (
					SELECT 1
					FROM sBiometric.tMonthTrans
					WHERE EmployeeId = @lSourceId
						AND SourceTypeId = @lSourceTypeId
						AND Attn_Dt = @lMonthTransAttn_Dt
					)
			BEGIN
				--Insert 
				INSERT INTO sBiometric.tMonthTrans(EmpCode,EmployeeId,Attn_Dt,
				D01,D02,D03,D04,D05,D06,D07,D08,D09,D10,D11,D12,D13,D14,D15,D16,D17,D18,D19,D20,D21,D22,D23,D24,D25,D26,D27,D28,D29,D30,D31,
				D01_IN,D02_IN,D03_IN,D04_IN,D05_IN,D06_IN,D07_IN,D08_IN,D09_IN,D10_IN,D11_IN,D12_IN,D13_IN,D14_IN,D15_IN,D16_IN,D17_IN,D18_IN,D19_IN,D20_IN,D21_IN,D22_IN,D23_IN,D24_IN,D25_IN,D26_IN,D27_IN,D28_IN,D29_IN,D30_IN,D31_IN,
				D01_OUT,D02_OUT,D03_OUT,D04_OUT,D05_OUT,D06_OUT,D07_OUT,D08_OUT,D09_OUT,D10_OUT,D11_OUT,D12_OUT,D13_OUT,D14_OUT,D15_OUT,D16_OUT,D17_OUT,D18_OUT,D19_OUT,D20_OUT,D21_OUT,D22_OUT,D23_OUT,D24_OUT,D25_OUT,D26_OUT,D27_OUT,D28_OUT,D29_OUT,D30_OUT,D31_OUT,
				D01_O,D02_O,D03_O,D04_O,D05_O,D06_O,D07_O,D08_O,D09_O,D10_O,D11_O,D12_O,D13_O,D14_O,D15_O,D16_O,D17_O,D18_O,D19_O,D20_O,D21_O,D22_O,D23_O,D24_O,D25_O,D26_O,D27_O,D28_O,D29_O,D30_O,D31_O,
				D01_L,D02_L,D03_L,D04_L,D05_L,D06_L,D07_L,D08_L,D09_L,D10_L,D11_L,D12_L,D13_L,D14_L,D15_L,D16_L,D17_L,D18_L,D19_L,D20_L,D21_L,D22_L,D23_L,D24_L,D25_L,D26_L,D27_L,D28_L,D29_L,D30_L,D31_L,
				D01_T,D02_T,D03_T,D04_T,D05_T,D06_T,D07_T,D08_T,D09_T,D10_T,D11_T,D12_T,D13_T,D14_T,D15_T,D16_T,D17_T,D18_T,D19_T,D20_T,D21_T,D22_T,D23_T,D24_T,D25_T,D26_T,D27_T,D28_T,D29_T,D30_T,D31_T,
				D01_S,D02_S,D03_S,D04_S,D05_S,D06_S,D07_S,D08_S,D09_S,D10_S,D11_S,D12_S,D13_S,D14_S,D15_S,D16_S,D17_S,D18_S,D19_S,D20_S,D21_S,D22_S,D23_S,D24_S,D25_S,D26_S,D27_S,D28_S,D29_S,D30_S,D31_S,
				D01_E,D02_E,D03_E,D04_E,D05_E,D06_E,D07_E,D08_E,D09_E,D10_E,D11_E,D12_E,D13_E,D14_E,D15_E,D16_E,D17_E,D18_E,D19_E,D20_E,D21_E,D22_E,D23_E,D24_E,D25_E,D26_E,D27_E,D28_E,D29_E,D30_E,D31_E,
				[Tot_Attn],[Tot_Abs],[Tot_WeekOFF],[Tot_Holiday],[TotalHour],[Tot_HD],[Tot_Early],[Tot_Late],[Tot_OT],[Tot_OD],[Tot_Leave],[Count_Late],[Count_Early],[Count_OT],Tot_CL,Tot_SL,Tot_EL,Tot_SP,Tot_C,Tot_PL,Tot_ML,SourceTypeId
				) 
				VALUES(@lCode,@lSourceId,@lMonthTransAttn_Dt,
				'XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX',
				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
				'XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX',
				'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
				0,0,0,0,'',0,'','','',0,0,0,0,0,0,0,0,0,0,0,0,@lSourceTypeId)
			END

			--Update
			SET @lQuery = 'UPDATE sBiometric.tMonthTrans
			SET D' + CAST(@lDay AS VARCHAR) + '_IN = ''' + CONVERT(VARCHAR(5), @lIn, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_OUT = ''' + CONVERT(VARCHAR(5), @lOut, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_E = ''' + CONVERT(VARCHAR(5), @lEarlyBy, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_L = ''' + CONVERT(VARCHAR(5), @lLateBy, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_O = ''' + CONVERT(VARCHAR(5), @lOverTime, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_T = ''' + CONVERT(VARCHAR(5), @lTotalTime, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + ' = ''' + CONVERT(VARCHAR(5), @lStatus, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_S = ''' + CAST(@lShift AS VARCHAR) + '''
			WHERE EmployeeId = ' + CAST(@lSourceId AS VARCHAR) + ' AND Attn_Dt = ''' + CAST(@lMonthTransAttn_Dt AS VARCHAR) + ''' AND SourceTypeId = ' + CAST(@lSourceTypeId AS VARCHAR)

			PRINT ('Query : ' + @lQuery)

			EXEC (@lQuery)

			CREATE TABLE #tSummary (
				PresentStatus VARCHAR(10)
				,PresentStatusCount INT
				)

			INSERT INTO #tSummary
			SELECT [Status],COUNT(*)
			AS [Count] FROM (
				SELECT D01,D02,D03,D04,D05,D06,D07,D08,D09,D10,D11,D12,D13,D14,D15,D16,D17,D18,D19,D20,D21,D22,D23,D24,D25,D26,D27,D28,D29,D30,D31
				FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId ) as Temp
				UNPIVOT
				(
					[Status]   
				   for [Dd] in (D01,D02,D03,D04,D05,D06,D07,D08,D09,D10,D11,D12,D13,D14,D15,D16,D17,D18,D19,D20,D21,D22,D23,D24,D25,D26,D27,D28,D29,D30,D31)
				) as [unpivoted] 	
				GROUP BY
					[Status]
				HAVING 
					COUNT(*) > 0

			--SELECT * FROM #tSummary
			--BREAK
			DECLARE @lTotal_HalfDay INT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN ('HD')
					)
			DECLARE @lTotal_Present FLOAT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN ('P')
					) + @lTotal_HalfDay * 0.5
			DECLARE @lTotal_Absent FLOAT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN (
							'A'
							,'XX'
							,'LH'
							)
					) + @lTotal_HalfDay * 0.5
			DECLARE @lTotal_WeekOff INT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN (
							'W'
							,'PW'
							)
					)
			DECLARE @lTotal_Holiday INT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN (
							'H'
							,'PH'
							)
					)
			DECLARE @lTotal_Hours VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
													SELECT D01_T,D02_T,D03_T,D04_T,D05_T,D06_T,D07_T,D08_T,D09_T,D10_T,D11_T,D12_T,D13_T,D14_T,D15_T,D16_T,D17_T,D18_T,D19_T,D20_T,D21_T,D22_T,D23_T,D24_T,D25_T,D26_T,D27_T,D28_T,D29_T,D30_T,D31_T				
													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
													UNPIVOT
													(
														[Status]   
														for [Dd] in (D01_T,D02_T,D03_T,D04_T,D05_T,D06_T,D07_T,D08_T,D09_T,D10_T,D11_T,D12_T,D13_T,D14_T,D15_T,D16_T,D17_T,D18_T,D19_T,D20_T,D21_T,D22_T,D23_T,D24_T,D25_T,D26_T,D27_T,D28_T,D29_T,D30_T,D31_T)
													) as [unpivoted]				
												) t
					)
			DECLARE @lTotal_Early VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
													SELECT D01_E,D02_E,D03_E,D04_E,D05_E,D06_E,D07_E,D08_E,D09_E,D10_E,D11_E,D12_E,D13_E,D14_E,D15_E,D16_E,D17_E,D18_E,D19_E,D20_E,D21_E,D22_E,D23_E,D24_E,D25_E,D26_E,D27_E,D28_E,D29_E,D30_E,D31_E				
													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
													UNPIVOT
													(
														[Status]   
														for [Dd] in (D01_E,D02_E,D03_E,D04_E,D05_E,D06_E,D07_E,D08_E,D09_E,D10_E,D11_E,D12_E,D13_E,D14_E,D15_E,D16_E,D17_E,D18_E,D19_E,D20_E,D21_E,D22_E,D23_E,D24_E,D25_E,D26_E,D27_E,D28_E,D29_E,D30_E,D31_E)
													) as [unpivoted]				
												) t
					)
			DECLARE @lTotal_Late VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
													SELECT D01_L,D02_L,D03_L,D04_L,D05_L,D06_L,D07_L,D08_L,D09_L,D10_L,D11_L,D12_L,D13_L,D14_L,D15_L,D16_L,D17_L,D18_L,D19_L,D20_L,D21_L,D22_L,D23_L,D24_L,D25_L,D26_L,D27_L,D28_L,D29_L,D30_L,D31_L				
													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
													UNPIVOT
													(
														[Status]   
														for [Dd] in (D01_L,D02_L,D03_L,D04_L,D05_L,D06_L,D07_L,D08_L,D09_L,D10_L,D11_L,D12_L,D13_L,D14_L,D15_L,D16_L,D17_L,D18_L,D19_L,D20_L,D21_L,D22_L,D23_L,D24_L,D25_L,D26_L,D27_L,D28_L,D29_L,D30_L,D31_L)
													) as [unpivoted]				
												) t
					)
			DECLARE @lTotal_OverTime VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM(
													SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum FROM (
													SELECT D01_O,D02_O,D03_O,D04_O,D05_O,D06_O,D07_O,D08_O,D09_O,D10_O,D11_O,D12_O,D13_O,D14_O,D15_O,D16_O,D17_O,D18_O,D19_O,D20_O,D21_O,D22_O,D23_O,D24_O,D25_O,D26_O,D27_O,D28_O,D29_O,D30_O,D31_O				
													FROM sBiometric.tMonthTrans WHERE EmployeeId = @lSourceId AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt AND SourceTypeId = @lSourceTypeId) as Temp
													UNPIVOT
													(
														[Status]   
														for [Dd] in (D01_O,D02_O,D03_O,D04_O,D05_O,D06_O,D07_O,D08_O,D09_O,D10_O,D11_O,D12_O,D13_O,D14_O,D15_O,D16_O,D17_O,D18_O,D19_O,D20_O,D21_O,D22_O,D23_O,D24_O,D25_O,D26_O,D27_O,D28_O,D29_O,D30_O,D31_O)
													) as [unpivoted]				
												) t
					)

			UPDATE sBiometric.tMonthTrans
			SET [Tot_Attn] = @lTotal_Present
				,[Tot_Abs] = @lTotal_Absent
				,[Tot_WeekOFF] = @lTotal_WeekOff
				,[Tot_Holiday] = @lTotal_Holiday
				,[TotalHour] = @lTotal_Hours
				,[Tot_HD] = @lTotal_HalfDay
				,[Tot_Early] = @lTotal_Early
				,[Tot_Late] = @lTotal_Late
				,[Tot_OT] = @lTotal_OverTime
			WHERE EmployeeId = @lSourceId
				AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
				AND SourceTypeId = @lSourceTypeId

			UPDATE sBiometric.tCloudTransactionData
			SET IsProcessed = 1
			WHERE TransactionId = @lTransactionId

			DROP TABLE #tSummary
		END

		SET @lPrevAttn_Dt = @lAttn_Dt
		SET @lPrevSourceId = @lSourceId
		SET @lPrevSourceTypeId = @lSourceTypeId
		SET @lCount = @lCount + 1
	END

	--Drop temp table for server issue(tempdb)
	DROP TABLE #tTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pLateINRegisterGet]  
 @rFromDate Date,  
 @rToDate Date,  
 @rOrgGroupId int =0,  
 @rBuilder1 nvarchar(max)='',  
 @rBuilder2 nvarchar(max)='',  
 @rOrgId int = 0,
 @rEmployeeStatusId int=0,
 @rEmployeeId bigint = 0    
     
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  Select   
   @rBuilder1 AS Builder1,@rBuilder2 AS Builder2,  
   Em.code,P.AtdDate,EM.DepartmentName,EM.EmployeeName,p.[Status] as [Status],P.CheckInTime,  
   Sh.PunchId , SFM.ShiftName as shiftName,p.LateComeTime  
   from sBiometric.tProcess P   
  INNER JOIN sHrm.vExtEmployeeMaster EM ON P.SourceId= EM.EmployeeId --AND P.SourceTypeId = 3  
  left join sHrm.tEmployeeMaster SH on SH.Id =  p.SourceId  
  left join sBiometric.tShiftMaster SFM on SFM.Id = SH.ShiftId  
  Where   
   (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
  AND ((P.AtdDate >= @rFromDate) OR (@rFromDate = ''))   
   AND ((P.AtdDate <= @rToDate) OR (@rToDate = ''))  
   and p.LateComeTime != '00:00'  and p.LateComeTime != ''
   AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pLateTimeSheetGet]  
    
  @rEmployeeId bigint=0,  
  @rEmployeeManagerId bigint =0,   
  @rFromDate Date,  
  @rToDate Date,  
  @rStatus nvarchar(10) = '0',  
  @rEmployeeCode nvarchar(100)='',  
  @rEmployeeName nvarchar(100)='',  
  @rOrgGroupId int =0  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
 DECLARE @lItemValue nvarchar(20) = ''  
 SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END  
 FROM sConfig.tConfigurationMaster CM  
 LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId  
 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 227  
  
  
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(5),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20)  
 )  
   
 INSERT INTO #TempMonthTrans  
   
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 UNION ALL  
  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
  
 IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))   
 BEGIN  
  INSERT INTO #TempMonthTrans  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
 END  
   
 IF Month(@rFromDate) <> 2  
 BEGIN  
 INSERT INTO #TempMonthTrans  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
 END  
   
 IF Month(@rFromDate) NOT IN (2,4,6,9,11)  
 BEGIN  
 INSERT INTO #TempMonthTrans  
 SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
 END  
   
 SELECT   
 TM.*,  
 MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,  
 Tot_Abs AS TotalAbsent,  
 Tot_WeekOff AS TotalWeekOff,  
 Tot_Holiday AS Totalholiday,  
 Tot_Leave AS TotalLeave,  
 EM.FirstName + ' ' + EM.LastName AS Name,  
 EM.Code,  
 ISNULL(ELS.Id,0) AS EmployeeLateStatusId,  
 ISNULL(ELS.EarlyLeaveRemark,'') AS EarlyLeaveRemark,  
 ISNULL(ELS.FieldHrs,0) AS FieldHrs,
 ISNULL(SM.Id,0) AS StatusId,  
 ISNULL(SM.Title,'') AS Status,  
 convert(float,replace(LateBy,':','.')) + convert(float,replace(EarlyBy,':','.')) AS EarlyHrs,  
 'EL' AS PresentStatus1  
 FROM #TempMonthTrans TM   
 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
 INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = TM.EmployeeId  
 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = TM.EmployeeId  
 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId  
 WHERE   
 TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate    
 AND (EJD.EmployeeManagerId = @rEmployeeManagerId OR @rEmployeeManagerId = 0)  
 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)  
--AND (PresentStatus = @rStatus OR @rStatus='0') AND PresentStatus IN ('LH','HD')  
AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')  
AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')  
--AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) >= convert(decimal(10,2),SUBSTRING(@lItemValue,1,CHARINDEX ( ';',@lItemValue)-1))  
--AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) <= Convert(decimal(10,2),SUBSTRING(@lItemValue,CHARINDEX (';',@lItemValue)+1,4))  
 --AND ((Convert(decimal(10,2),Replace(TM.Duration,':','.')) >= convert(decimal(10,2),SUBSTRING(@lItemValue,1,CHARINDEX ( ';',@lItemValue)-1))
 --AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) <= Convert(decimal(10,2),SUBSTRING(@lItemValue,CHARINDEX (';',@lItemValue)+1,4)))
	--OR (Convert(decimal(10,2),Replace(TM.LateBy,':','.')) > 0 AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) < 9.30)
	--OR (TM.PresentStatus = 'P' AND (LateBy <> '00:00' Or EarlyBy <> '00:00')))


	
	--AND ((Convert(decimal(10,2),Replace(TM.Duration,':','.')) >= convert(decimal(10,2),SUBSTRING(@lItemValue,1,CHARINDEX ( ';',@lItemValue)-1))
	--AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) <= Convert(decimal(10,2),SUBSTRING(@lItemValue,CHARINDEX (';',@lItemValue)+1,4)))
	--OR (Convert(decimal(10,2),Replace(TM.LateBy,':','.')) > 0 AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) < 9.30)
	--OR (TM.PresentStatus = 'P' AND (LateBy <> '00:00' Or EarlyBy <> '00:00'))
	--OR TM.PresentStatus = 'A'  OR (TM.PresentStatus = 'HD' AND sBiometric.fcalcMINI(TM.FirstIn) > 720) Or TM.PresentStatus = 'HD'  Or TM.PresentStatus = 'LH')


 ORDER BY TM.EmployeeId,TM.Attn_Date  

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pLateTimeSheetListGet]
	 @rEmployeeId bigint=0,
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '0',
	  @rOrgGroupId int =0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	
	SELECT 
	TM.*,
	MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,
	Tot_Abs AS TotalAbsent,
	Tot_WeekOff AS TotalWeekOff,
	Tot_Holiday AS Totalholiday,
	Tot_Leave AS TotalLeave,
	EM.FirstName + ' ' + EM.LastName AS Name,
	EM.Code,
	ISNULL(ELS.Id,0) AS EmployeeLateStatusId,
	ISNULL(ELS.EarlyLeaveRemark,'') AS EarlyLeaveRemark,
	ISNULL(ELS.FieldHrs,0) AS FieldHrs,
	ISNULL(SM.Id,0) AS StatusId,
	ISNULL(SM.Title,'') AS Status,
	'EL' AS PresentStatus1
	FROM #TempMonthTrans TM 
	INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
	LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)
	LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId
	WHERE 
	TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate 	
	AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
--	AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) >= convert(decimal(10,2),SUBSTRING(@lItemValue,1,CHARINDEX ( ';',@lItemValue)-1))
--	AND Convert(decimal(10,2),Replace(TM.Duration,':','.')) <= Convert(decimal(10,2),SUBSTRING(@lItemValue,CHARINDEX (';',@lItemValue)+1,4))
	Order By TM.EmployeeId,TM.Attn_Date
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

CREATE OR ALTER PROCEDURE [sBiometric].[pMonthlyPresenceSummaryGet]    
  @rCode nvarchar(20)='',
  @rForYear int,
  @rForMonth int,
  @rOrgId int,
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @OrgGroupDepartmentId int = 0,
  @rBatchId int,
  @rEmployeeGroupId int=0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
  
BEGIN   
 DECLARE @rFromDate date  
 DECLARE @rToDate date  
 DECLARE @lXmlDoc nvarchar(max) = ''
   
 SET @rFromDate = CONVERT(date,CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01')  
 SET @rToDate = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rFromDate) + 1, 0))  
   


 --CREATE TABLE #TempMonthTrans_MonthlyPresence  
 --(  
 --Id int Identity,  
 --EmployeeId bigint,   
 --PresentStatus nvarchar(5),  
 --LateBy decimal(10,2),  
 --Duration decimal(10,2),  
 --EarlyBy nvarchar(10),  
 --Attn_dt date,  
 --FirstIn nvarchar(10),
 --Flag bit null ,
 --IsMobileSide bit null
 --)  
   
 --INSERT INTO #TempMonthTrans_MonthlyPresence  
   
 --SELECT EmployeeId,D01,Replace(D01_L,':','.'),Replace(D01_T,':','.'),D01_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),D01_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D02,Replace(D02_L,':','.'),Replace(D02_T,':','.'),D02_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 2) as datetime),D02_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D03,Replace(D03_L,':','.'),Replace(D03_T,':','.'),D03_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 3) as datetime),D03_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D04,Replace(D04_L,':','.'),Replace(D04_T,':','.'),D04_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 4) as datetime),D04_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D05,Replace(D05_L,':','.'),Replace(D05_T,':','.'),D05_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 5) as datetime),D05_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D06,Replace(D06_L,':','.'),Replace(D06_T,':','.'),D06_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 6) as datetime),D06_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D07,Replace(D07_L,':','.'),Replace(D07_T,':','.'),D07_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 7) as datetime),D07_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D08,Replace(D08_L,':','.'),Replace(D08_T,':','.'),D08_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 8) as datetime),D08_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D09,Replace(D09_L,':','.'),Replace(D09_T,':','.'),D09_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 9) as datetime),D09_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D10,Replace(D10_L,':','.'),Replace(D10_T,':','.'),D10_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D11,Replace(D11_L,':','.'),Replace(D11_T,':','.'),D11_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D12,Replace(D12_L,':','.'),Replace(D12_T,':','.'),D12_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D13,Replace(D13_L,':','.'),Replace(D13_T,':','.'),D13_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D14,Replace(D14_L,':','.'),Replace(D14_T,':','.'),D14_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D15,Replace(D15_L,':','.'),Replace(D15_T,':','.'),D15_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D16,Replace(D16_L,':','.'),Replace(D16_T,':','.'),D16_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D17,Replace(D17_L,':','.'),Replace(D17_T,':','.'),D17_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D18,Replace(D18_L,':','.'),Replace(D18_T,':','.'),D18_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D19,Replace(D19_L,':','.'),Replace(D19_T,':','.'),D19_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D20,Replace(D20_L,':','.'),Replace(D20_T,':','.'),D20_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D21,Replace(D21_L,':','.'),Replace(D21_T,':','.'),D21_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D22,Replace(D22_L,':','.'),Replace(D22_T,':','.'),D22_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D23,Replace(D23_L,':','.'),Replace(D23_T,':','.'),D23_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D24,Replace(D24_L,':','.'),Replace(D24_T,':','.'),D24_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D25,Replace(D25_L,':','.'),Replace(D25_T,':','.'),D25_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D26,Replace(D26_L,':','.'),Replace(D26_T,':','.'),D26_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D27,Replace(D27_L,':','.'),Replace(D27_T,':','.'),D27_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
 --SELECT EmployeeId,D28,Replace(D28_L,':','.'),Replace(D28_T,':','.'),D28_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))   
 --BEGIN  
 -- INSERT INTO #TempMonthTrans_MonthlyPresence  
 -- SELECT EmployeeId,D29,Replace(D29_L,':','.'),Replace(D29_T,':','.'),D29_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 -- AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) <> 2  
 --BEGIN  
 --INSERT INTO #TempMonthTrans_MonthlyPresence  
 --SELECT EmployeeId,D30,Replace(D30_L,':','.'),Replace(D30_T,':','.'),D30_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) NOT IN (2,4,6,9,11)  
 --BEGIN  
 --INSERT INTO #TempMonthTrans_MonthlyPresence  
 --SELECT EmployeeId,D31,Replace(D31_L,':','.'),Replace(D31_T,':','.'),D31_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31_IN,[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,1),[sHrm].[fEmployeePendingLeaveEntry](EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),Replace(D01_T,':','.'),D01,2) FROM sBiometric.tMonthTrans WHERE 1=1   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END       

  --select * from #TempMonthTrans_MonthlyPresence WHERE EmployeeId = 9901000000091
   
 DECLARE @lAttendanceDate AS nvarchar(20)  
 SET @lAttendanceDate = CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01'  
  
 DECLARE @lOrgGroupId int=0  
 SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId  
    
 DECLARE @lItemValue nvarchar(20) = ''  
 SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END  
 FROM sConfig.tConfigurationMaster CM  
 LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId  
 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 204  
  
 DECLARE @lItemValue1 nvarchar(20) = ''  
 SELECT @lItemValue1 = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END  
 FROM sConfig.tConfigurationMaster CM  
 LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId  
 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 227   
  
 --select * from #TempMonthTrans_MonthlyPresence  WHERE EmployeeID = 1101000000047
 -- return

     --select convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1)),Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4))-0.05
   

    --New Function to check Pending Leave Entry when Employee: Absent,LessHours,ErrorCase,EarlyLeave (Added By Jash: Date - 07/10/2021)    
	--DECLARE @lCount int = 1
	--DECLARE @lTotal int = (SELECT COUNT(Id) FROM #TempMonthTrans_MonthlyPresence)	
	--WHILE @lCount <= @lTotal 
	--BEGIN
	--	DECLARE @lEmployeeId bigint = (SELECT EmployeeId FROM #TempMonthTrans_MonthlyPresence WHERE Id = @lCount)
	--	DECLARE @lDate date = (SELECT Attn_dt FROM #TempMonthTrans_MonthlyPresence WHERE Id = @lCount)
	--	DECLARE @lPresentStatus nvarchar(5) = (SELECT PresentStatus FROM #TempMonthTrans_MonthlyPresence WHERE Id = @lCount)
	--	DECLARE @lDuration decimal(10,2) = (SELECT Duration FROM #TempMonthTrans_MonthlyPresence WHERE Id = @lCount)	
	--	DECLARE @lDeptId int = (SELECT OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @lEmployeeId)
	--	DECLARE @lLeavePeriodId smallint = (SELECT SUM(LeavePeriodId) FROM sHrm.tLeave WHERE EmployeeId = @lEmployeeId AND (@lDate BETWEEN FromDate AND ToDate) AND StatusId <> 551)	

	--	IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
	--					INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ((SourceId=@lDeptId) OR (@lDeptId=0)) 
	--					AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
	--		BEGIN
	--			SET @lPresentStatus = 'H'	
	--			--RETURN @lStatus		
	--		END
	--	--IF(([sHrm].[fWeekHOffHolidayGet](@lEmployeeId , YEAR(@lDate) ,MONTH(@lDate) ,DAY(@lDate) ,0 ,@lDeptId ,LEFT(@lEmployeeId,4))='H'))
	--	--BEGIN
	--	--	SET @lPresentStatus = 'H'
	--	--END
		
	--	IF((@lPresentStatus = 'A') OR (@lPresentStatus = 'HD' AND (@lDuration >= '04.00' AND @lDuration <= '07.29')) OR (@lPresentStatus = 'LH' AND (@lDuration >= '00.01' AND @lDuration <= '03.59')))
	--	BEGIN					
	--		IF NOT EXISTS(SELECT 1 FROM sHrm.tLeave WHERE EmployeeId = @lEmployeeId AND (@lDate BETWEEN FromDate AND ToDate) AND StatusId <> 551) AND NOT EXISTS (SELECT 1 FROM sBiometric.tEmployeeLateStatus WHERE LateDate = @lDate AND EmployeeId = @lEmployeeId AND StatusId <> 551) 
	--		OR ((@lPresentStatus = 'A' AND ISNULL(@lLeavePeriodId,0) = 2) OR (@lPresentStatus = 'LH' AND ISNULL(@lLeavePeriodId,0) = 2))
	--		BEGIN
	--			UPDATE #TempMonthTrans_MonthlyPresence SET Flag = 1 WHERE Id = @lCount
	--		END
	--	ELSE IF(@lPresentStatus = 'E')
	--		 UPDATE #TempMonthTrans_MonthlyPresence SET Flag = 1 WHERE Id = @lCount
	--	END

	--	DECLARE @lIsMobileSide bigint = 0
	--	SELECT @lIsMobileSide = EmployeeId FROM sErp.tTripLog WHERE EmployeeId = @lEmployeeId AND Cast(UpdatedDateTime AS Date) = @lDate
	--	IF(@lIsMobileSide > 0)
	--	BEGIN
	--	UPDATE #TempMonthTrans_MonthlyPresence SET IsMobileSide = 1 WHERE Id = @lCount
	--	END
	
	--	SET @lCount = @lCount + 1	
	--END
   --End


   --SELECT * FROM #TempMonthTrans_MonthlyPresence
   SELECT MT.Id,MT.EmployeeId,
    CASE WHEN (([sHrm].[fWeekHOffHolidayGet](MT.EmployeeId , YEAR(MT.Attn_Dt) ,MONTH(MT.Attn_Dt) ,DAY(MT.Attn_Dt) ,0 ,EJD.OrganizationDepartmentId ,LEFT(MT.EmployeeId,4) )='H') AND (MT.FirstIn !='00:00'))  then 'PH'
	--WHEN (([sHrm].[fWeekHOffHolidayGet](MT.EmployeeId , YEAR(MT.Attn_Dt) ,MONTH(MT.Attn_Dt) ,DAY(MT.Attn_Dt) ,0 ,EJD.OrganizationDepartmentId ,LEFT(MT.EmployeeId,4) )='H') AND (MT.FirstIn='00:00')) THEN 'H'  
	WHEN ((MT.PresentStatus='W') AND (MT.FirstIn !='00:00')) THEN 'PW'
	ELSE
   MT.PresentStatus END AS PresentStatus,
   MT.LateBy,MT.Duration,MT.EarlyBy,MT.Attn_Dt,MT.FirstIn,MT.Flag,MT.IsMobileSide,MT.LastOut,MT.OverTime INTO #TempMonthTrans_MonthlyPresence 
   FROM [sBiometric].[tMonthTransactions] MT LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = MT.EmployeeId
   WHERE MONTH(Attn_dt) = @rForMonth AND YEAR(Attn_dt) = @rForYear

   --SELECT * FROM #TempMonthTrans_MonthlyPresence

 SELECT    
	ROW_NUMBER() OVER (ORDER BY EM.Code ASC) AS SrNo,  
	CONVERT(nvarchar(20), DATENAME(MONTH,(MT.attn_dt))) +' - '+ CONVERT(nvarchar(100),YEAR(MT.attn_dt)) AS MonthYear,
	CAST(DATENAME(MONTH,@rFromDate )  AS CHAR(20))AS 'Month',
	EM.Id As EmployeeId,
	EM.Code,  
	EM.FirstName + ' ' + EM.Lastname AS Name,
	EJD.DateOfJoining,
	OGD.Title AS [Organization Group],       
	CAST(DATEDIFF(dd, @rFromDate, @rToDate)+1 AS NVARCHAR(10)) + ' (' +  CAST((MT.Tot_Attn + ISNULL(ELCount.ELCount,0) * 0.5) AS NVARCHAR(10)) + ')' as WorkingDay,

	case When (Tot_Abs - Isnull(A1.LateStatus,0)*.5 - isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0))> 0 then
	Tot_Abs - Isnull(A1.LateStatus,0)*.5 - isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0)
	else 0 end    AS NoPunch,      

	Isnull(LWP.NoOfLeave,0) - Isnull(LWP1.NoofLeave,0) AS CL ,  
	Isnull(LWP1.NoofLeave,0) AS LWPLeave,

	Case When (Tot_Abs -Isnull(A1.LateStatus,0)*.5- isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0) - isnull(LWP.NoofLeave,0) - isnull(A3.LateStatusApr,0) * 0.5) --- isnull(ServiceHoliday.serviceHoliday,0)
	>0 then
	Tot_Abs - isnull(A4.AbsentStatusApr,0) - Isnull(A1.LateStatus,0)*.5 - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0) - isnull(LWP.NoofLeave,0) - isnull(ServiceHoliday.serviceHoliday,0) -- isnull(A3.LateStatusApr,0) * 0.5
	else 0 end 	AS LeaveNotApply,

	Isnull(Comp.Compoff,0) AS CompOff,   
	@lItemValue As item,
	
	CASE 
		WHEN EJD.EmployeeTypeId = [sCommon].[fGetIntIdForOrg](4,@rOrgId) 
		THEN ISNULL((SELECT COUNT(Duration) FROM #TempMonthTrans_MonthlyPresence TMT
		WHERE Duration >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND (Attn_dt >=  DATEADD(month, 4, EJD.DateOfJoining)) AND EM.Id = EmployeeId AND EJD.OrgGroupDepartmentId <> [sCommon].[fGetIntIdForOrg](4,@rOrgId) AND IsMobileSide = 0 GROUP BY EmployeeId),0)
		ELSE
		ISNULL((SELECT COUNT(Duration) FROM #TempMonthTrans_MonthlyPresence WHERE Duration >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND EM.Id = EmployeeId AND EJD.OrgGroupDepartmentId <> [sCommon].[fGetIntIdForOrg](4,@rOrgId) AND IsMobileSide = 0 GROUP BY EmployeeId),0)
		END 
		 AS DinnerAllowance,
	
	--ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans  
	--UNPIVOT  
	--(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT  
	--WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,  
	
	ABS(LateCount.LateCount - ISNULL(LateValidCount.LateValid,0) - ISNULL(LateCountAprooved.LateAprooved,0)) AS Late,
	 
	Isnull(Late1030Count.Late1030Count,0)   - ISNULL(LateValid1030Count.LateValid1030Count,0) - isnull(Late1030CountAprooved.Late1030CountAprooved,0) AS Grt1030Cnt,

	sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':'))) AS Tot_OT,   
	Isnull(Valid_Cnt.Vstatuscount,0) AS Valid_Cnt,  
	sBiometric.fcalcHour(ISNULL(InvalidHrs.InvalidHrs,0))  AS InvalidHrs,  
	   
	sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':')) - ISNULL(InvalidHrs.InvalidHrs,0)) AS Tot_OT_IVH,  

	CASE When (convert(decimal(18,2),(Isnull(Valid_Cnt.Vstatuscount,0) + Isnull(InValid_Cnt.Vstatuscount,0) + ISNULL(LateStatusApr,0) + ISNULL(ELValidApproveCount,0)))) >  0
	Then
	Convert(decimal(18,2),     convert(decimal(18,2),(Isnull(MT.Tot_PL,0)+Isnull(MT.Tot_ML,0)))
	/(convert(decimal(18,2),(Isnull(Valid_Cnt.Vstatuscount,0) + Isnull(InValid_Cnt.Vstatuscount,0) + ISNULL(LateStatusApr,0) + ISNULL(ELValidApproveCount,0))))  
	) else 0 end AS MonthlyPunchAvg, --INModeCount,  

	ISNULL(PunchCnt.PunchCnt,0) AS Gt8PunchCnt,  

	ISNULL(EC.CompanyEmail,'')+','+ISNULL(vEM.CompanyEmail,'') AS CompanyEmail
	,ELCount.ELCount, ELCount.ELHrs, EJD.EmployeeTypeId,

	CASE WHEN EM.Id IN (SELECT EmployeeId FROM #TempMonthTrans_MonthlyPresence WHERE Flag = 1) THEN 1 ELSE 0 END AS Flag
	,CASE WHEN EM.Id IN (SELECT EmployeeId FROM #TempMonthTrans_MonthlyPresence WHERE Flag = 1) THEN (Select SUBSTRING((SELECT ',' + CAST(DAY(Attn_dt) AS nvarchar(5)) FROM #TempMonthTrans_MonthlyPresence tmt WHERE EmployeeId = EM.Id AND Flag = 1 FOR XML PATH('') ), 2 , 100)) ELSE '' END As PendingLeaveEntryDates

	  INTO #FInal
 FROM   
  sBiometric.tMonthTrans MT  
  right JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt = @lAttendanceDate  
  LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id  
  LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id    
  LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId
  INNER JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id  
  LEFT Join  
  (  
   SELECT ISNULL(SUM(NoOfLeave),0) NoOfLeave,L.EmployeeId FROM sHrm.tLeaveTypeMaster Lt   
   inner join sHrm.tLeave L ON L.LeaveTypeId = LT.Id --AND LT.IsLWP =  0  
   --inner jOIN #TempMonthTrans_MonthlyPresence TT on L.EmployeeId = TT.EmployeeId   
   --AND TT.PresentStatus NOT IN ('W','PW')   
   WHERE 1=1  --StatusId=550 --AND TT.attn_dt = L.FromDate  
   AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)) 
   AND StatusID <> 551
   Group By L.EmployeeId  
  )LWP ON LWP.EmployeeId = EM.ID  
    LEFT Join  
  (  
   SELECT ISNULL(SUM(NoOfLeave),0) NoOfLeave,L.EmployeeId FROM sHrm.tLeaveTypeMaster Lt   
   inner join sHrm.tLeave L ON L.LeaveTypeId = LT.Id AND LT.IsLWP =  1  
   WHERE StatusId=550 --AND TT.attn_dt = L.FromDate  
   AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))  
   Group By L.EmployeeId  
  )LWP1 ON LWP1.EmployeeId = EM.ID  
  LEFT JOIN
  (
	SELECT Count(*) AS serviceHoliday,EM.Id FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
	Inner join sHRM.tEmployeeJobDetail ED ON ED.OrganizationDepartmentId = EA.SourceID
	Inner join sHRM.tEmployeeMaster  EM ON EM.Id = ED.EmployeeId And EM.StatusId = @rStatusId
	WHERE  ((ES.BatchId=@rBatchId) OR (@rBatchId=0))  
	AND (ES.FromDate>= CONVERT(DATE,@lAttendanceDate) AND ES.ToDate <= DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)) ) 
	AND ES.IsHoliday=1 group by EM.Id
  )ServiceHoliday ON ServiceHoliday.Id = EM.Id
    
  LEFT JOIN  -- early or first half day early   
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid  
      From sBiometric.tMonthTrans MT  
   leFT jOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')  
   )      
   where MT.attn_dt = @lAttendanceDate  
   GRoup By TT.EmployeeId  
  )LateValidCount ON LateValidCount.EmployeeId = MT.EmployeeId  
    
  LEFT JOIN  -- Late Approve entry count Less then 30 min late  
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateAprooved  
      From sBiometric.tMonthTrans MT  
   INNER JOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId   AND TT.LateBy > 0   
   INNER JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TT.EmployeeId AND ELS.StatusId = 550   
   --and ELS.LateStatus='V'  
   AND CONVERT(DATE,ELS.LateDate) = TT.Attn_Dt  
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateCountAprooved ON LateCountAprooved.EmployeeId = MT.EmployeeId  
      
  LEFT JOIN  -- early or first half day early   
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid,0 AS EarlyBy,  --  
    sum(sBiometric.fcalcMINI(Replace(Isnull(Tt.lATEbY,0.0),'.',':'))) AS LateBy  
       From  
   sBiometric.tMonthTrans MT  
   INNER jOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')  
   Or (TT.LateBy > 0.30)) AND TT.PresentStatus <> 'E' AND TT.PresentStatus <> 'PW'   --AND TT.Duration <9.15  
     
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateValid ON LateValid.EmployeeId = MT.EmployeeId  
  LEFT JOIN  -- Duration <= 9.15  AND Late <= 30  
  ( Select TT.EmployeeID, 0  AS LateBy   --  SUM(sBiometric.fcalcMINI(Replace(Isnull(Tt.lATEbY,0.0),'.',':')))  
      From sBiometric.tMonthTrans MT  
   INNER jOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId    
   AND TT.LateBy <= 0.30    
   AND TT.Duration < 9.30 WHERE MT.attn_dt = @lAttendanceDate AND TT.PresentStatus <> 'LH'   
   GRoup By TT.EmployeeId  
  )ELLateValid ON ELLateValid.EmployeeId = MT.EmployeeId  
  LEFT JOIN  -- Late arrive and attain full day > 9.15  
  ( Select TT.EmployeeID, sum(sBiometric.fcalcMINI(isnull(Replace(TT.LateBy,'.',':'),'0:0'))) AS LateBy From  
   sBiometric.tMonthTrans MT  
   leFT jOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId  AND (TT.PresentStatus ='HD' AND TT.LateBy <= 0.30   
   AND TT.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))  
   AND TT.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)))     
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateNotEL ON LateNotEL.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Half Day Early  
  ( Select TT.EmployeeID, sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS EarlyBy From  
   sBiometric.tMonthTrans MT  
   inner jOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId    
   AND (((TT.PresentStatus ='HD' AND convert(decimal(10,2),Replace(TT.Duration,':','.')) > 4.0 AND convert(decimal(10,2),Replace(TT.Duration,':','.')) < 6.30)) Or TT.PresentStatus  in ('E') )  
   AND TT.Attn_Dt Not in (Select Latedate from sBiometric.tEmployeeLateStatus Where StatusId <> 550 AND LateStatus='EL' AND EmployeeId=MT.EmployeeId )  
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateValid1 ON LateValid1.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Less Hour  
  ( Select TT.EmployeeID, Count(TT.EmployeeID) LHCount, sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS EarlyBy ,sum(isnull(TT.Duration,0)) AS LHHrs From  
   sBiometric.tMonthTrans MT  
   inner jOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='LH'   
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LH ON LH.EmployeeId = MT.EmployeeId  

  LEFT JOIN -- Less Hour Approved  
  (   
  Select MT.EmployeeID, Count(MT.EmployeeID) LHCount,sBiometric.fcalcHour(sum(sBiometric.fcalcMINI(Replace(ISNULL(TT.Duration,0),'.',':'))))  
  AS LHHrs  From  sBiometric.tMonthTrans MT  
   INNER jOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='LH'   
   where MT.attn_dt = @lAttendanceDate AND  TT.Attn_DT   
   IN (select LateDate from sBiometric.tEmployeeLateStatus Where StatusId = 550 AND LateStatus='LH' AND EmployeeId=MT.EmployeeId )  
   GRoup By MT.EmployeeId  
  )LHApproved ON LHApproved.EmployeeId = MT.EmployeeId  

  Left Join (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) as LHCount FROM sBiometric.tEmployeeLateStatus ELS1  
  WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND ElS1.LateStatus = 'LH'  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )LHCountApproved ON LHCountApproved.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- PW  
  ( Select TT.EmployeeID,sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS PWHrs From  
   sBiometric.tMonthTrans MT  
   leFT jOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus like '%PW%'   
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )PW ON PW.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Aproved EL Time  
  (  
  SELECT   
  sBiometric.fcalcHour(sum(case when TM.LateBy <=0.30 then sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))-TM.lateBy*100  
  else sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))end ))  
  AS EarlyHrs,ELS.EmployeeId   
  FROM sBiometric.tEmployeeLateStatus ELS   
  INNER JOIN #TempMonthTrans_MonthlyPresence TM ON TM.EmployeeId = ELS.EmployeeId and TM.ATTN_DT = ELS.LateDate AND (TM.LateBy >.30 OR TM.EarlyBy <> '00:00' )  
  WHERE ELS.StatusId = 550 AND ELS.LateStatus <> 'HD' AND ELS.LateStatus <> 'LH' AND ELS.LateStatus <> 'V' AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)     AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS.EmployeeId  
  ) A ON A.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- Aproved EL Time  
  (  
  SELECT sum(sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))) AS EarlyLateMin,ELS.EmployeeId ,COUNT(ELS.EmployeeId ) VstatusLatecount  
  FROM sBiometric.tEmployeeLateStatus ELS   
  INNER JOIN #TempMonthTrans_MonthlyPresence TM ON TM.EmployeeId = ELS.EmployeeId and TM.ATTN_DT = ELS.LateDate   
  AND (TM.LateBy >.30 OR sBiometric.fcalcMINI(isnull(TM.EarlyBy,'0:0')) > 0  )  
  WHERE ELS.StatusId = 550 AND ELS.LateStatus = 'V' AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS.EmployeeId  
  ) V_Status ON V_Status.EMployeeId = MT.EMployeeId   
  LEFT JOIN  -- EL Approved Count  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatusApr FROM sBiometric.tEmployeeLateStatus ELS1  
  LEFT JOIN sHRM.tLeave L on L.EmployeeId = ELS1.EmployeeId AND L.LeavePeriodId = 2   
  AND L.StatusId = 550   
  AND L.FromDate = ELS1.LateDate   
  WHERE ELS1.StatusId = 550 AND L.Id IS NULL and  (LateStatus = 'EL') AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )A3 ON A3.EMployeeId = MT.EMployeeId   
  LEFT JOIN  -- EL Approved Count  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS ELValidApproveCount FROM sBiometric.tEmployeeLateStatus ELS1  
  INNER JOIN sHRM.tLeave L on L.EmployeeId = ELS1.EmployeeId AND L.LeavePeriodId = 1   
  AND L.StatusId = 550   
  AND L.FromDate = ELS1.LateDate   
  WHERE ELS1.StatusId = 550 AND L.Id IS NULL and  (LateStatus = 'V') AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )ELValidApproveCount ON ELValidApproveCount.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- EL Entry AND Approved  Absent Case  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS AbsentStatusApr FROM sBiometric.tEmployeeLateStatus ELS1  
  INNER JOIN #TempMonthTrans_MonthlyPresence TM ON TM.EmployeeId = ELS1.EmployeeId   
  AND ELS1.StatusId = 550  AND ELS1.LateDate = TM.Attn_dt  
  WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND ELS1.LateStatus IN ( 'A','E')  
  GROUP BY ELS1.EmployeeId  
  )A4 ON A4.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- EL Entry AND Approved  HD Case  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS HDStatusApr FROM sBiometric.tEmployeeLateStatus ELS1  
  WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND (ElS1.LateStatus IN ('HD','EL','L'))  -- OR ElS1.LateStatus = 'EL' -- Additional
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )A5 ON A5.EMployeeId = MT.EMployeeId  
  Left Join -- EL Case   
  (  
  SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS LateStatus FROM #TempMonthTrans_MonthlyPresence TM  
  WHERE 1=1   
  --AND TM.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))  
  --AND TM.Duration < 9.30 --Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)) ---0.05 
  AND TM.Duration >= 7.30  --Added By Dhruv
  AND TM.Duration <= 9.29  --Added By Dhruv
  AND TM.PresentStatus not like '%PW%' AND ( PresentStatus IN ('HD'))   --sBiometric.fcalcMINI(TM.FirstIn) < 720 AND
  AND TM.EmployeeID Not in (Select EmployeeId from sHrm.tLeave L Inner join sHRM.tLeaveTypeMaster LM ON LM.Id =L.LeaveTypeID Where FromDate=Tm.Attn_dt AND L.StatusID = 550 aND LM.ISLWP=0)
  AND TM.EmployeeID Not in (Select EmployeeId FRom sBiometric.tEmployeeLateStatus ELS Where ELS.LateDate=Tm.Attn_dt AND ELS.StatusId = 550)
  GROUP BY TM.EmployeeId  
  )A1 ON A1.EMployeeId = MT.EMployeeId   
  LEFT JOIN  
  (    
  SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS TotalLate FROM #TempMonthTrans_MonthlyPresence TM  
  LEFT JOIN sHRM.tLeave L on L.EmployeeId = TM.EmployeeId AND L.LeavePeriodId = 2   
  AND L.StatusId = 550   
  AND L.FromDate = TM.Attn_dt   
  WHERE 1=1 AND L.Id IS NULL  AND sBiometric.fcalcMINI(TM.FirstIn) < 720  AND (TM.LateBy > 0.30 or TM.EarlyBy <> '00:00')  
  AND TM.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))  
  AND TM.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)) 
  GROUP BY TM.EmployeeId  
  )A2 ON A2.EMployeeId = MT.EMployeeId   
  LEFT JOIN  
  (    
  SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS ELValidCount FROM #TempMonthTrans_MonthlyPresence TM  
  INNER JOIN sHRM.tLeave L on L.EmployeeId = TM.EmployeeId AND L.LeavePeriodId = 1   
  AND L.StatusId = 550   
  AND L.FromDate = TM.Attn_dt   
  WHERE 1=1 AND L.Id IS NULL  AND  (TM.LateBy > 0.30 or TM.EarlyBy <> '00:00')  
  GROUP BY TM.EmployeeId  
  ) ELValidCount ON ELValidCount.EMployeeId = MT.EMployeeId   
  LEFT Join  
  (  
  select Sum(isnull(AddRequestBalance,0)) AS Compoff,LV.EmployeeId from shrm.tLeaveBalanceAddRequest LV  
  inner join sHrm.tLeaveTypeMaster LT ON LV.LeaveTypeId=LT.Id AND MainLeaveTypeId = 3 AND ReportDate >= CONVERT(DATE,@lAttendanceDate)  
  AND ReportDate <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND LV.StatusId = 550  
  GRoup by LV.EmployeeId  
  )Comp ON Comp.EmployeeId = MT.EMployeeId   
  LEFT JOIN  -- EL and Late   
  ( Select TT.EmployeeID,sum(sBiometric.fcalcMINI(Replace(Isnull(Tt.LateBy,0.0),'.',':'))) AS LateBy  
       From sBiometric.tMonthTrans MT         
   INNER jOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId  and TT.LateBy > 0.30  
   --AND ((TT.PresentStatus ='HD' AND TT.Duration > '6.15')  
   AND (TT.PresentStatus IN ('EL','V','P')  
   OR (TT.PresentStatus ='HD' AND TT.LateBy < 2.30)  
   )  
   AND TT.LateBy > 0   
   LEFT JOIN sBiometric.tEmployeeLateStatus ELS1 ON TT.EmployeeId = ELS1.EmployeeId   
     
   AND ELS1.LateDate = TT.Attn_dt  
   and CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
   AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
   where MT.attn_dt = @lAttendanceDate AND ISNULL(ELS1.StatusId,0) <> 550    
   GRoup By TT.EmployeeId  
  )LateEL ON LateEL.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Aproved EL Time  
  (  
  SELECT COUNT(TM.EmployeeId ) VstatusLatecount,EMployeeId  
  FROM #TempMonthTrans_MonthlyPresence TM   
  WHERE (TM.LateBy >.30 OR sBiometric.fcalcMINI(isnull(TM.EarlyBy,'0:0')) > 0  ) AND TM.Duration >= 9.30   
  GROUP BY TM.EmployeeId  
  ) V_StatusApprove ON V_StatusApprove.EMployeeId = MT.EMployeeId AND MT.attn_dt = @lAttendanceDate    
   
     LEFT JOIN -- Valid Count  
  (  
  SELECT TM.EmployeeId ,COUNT(TM.EmployeeId ) Vstatuscount  
  FROM  #TempMonthTrans_MonthlyPresence TM   
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.Duration >= 9.30   
  GROUP BY TM.EmployeeId  
  ) Valid_Cnt ON Valid_Cnt.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- InValid Count  
  (  
  SELECT TM.EmployeeId ,COUNT(TM.EmployeeId ) Vstatuscount  
  FROM  #TempMonthTrans_MonthlyPresence TM   
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.Duration < 9.30 AND TM.PresentStatus Not in ('A','W','XX','H','WH','LH')  
  AND   
   ( TM.Attn_dt NOT IN   
   (SELECT FromDate FRom sHRM.tLeave L Where L.EmployeeId=TM.EmployeeId AND L.StatusId = 550  
   AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
   AND  
   TM.Attn_dt NOT IN   
   (SELECT LateDate FRom sBiometric.tEmployeeLateStatus ELS Where ELS.EmployeeId=TM.EmployeeId AND ELS.StatusId = 550  
    AND CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
   AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))))  
   )   
  GROUP BY TM.EmployeeId  
  ) InValid_Cnt ON InValid_Cnt.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- WeekOff Holiday Count  
  (  
  SELECT TM.EmployeeId ,COUNT(TM.EmployeeId ) WeekHolidayCount  
  FROM  #TempMonthTrans_MonthlyPresence TM   
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.PresentStatus in ('H','W','PW','PWH')  
  GROUP BY TM.EmployeeId  
  ) WeekHolidayCount ON WeekHolidayCount.EMployeeId = MT.EMployeeId  
    
  LEFT JOIN -- Invalid Hrs Count  
  (  
  SELECT TM.EmployeeId ,sum(570 - sBiometric.fcalcMINI(replace(TM.Duration,'.',':')))  AS  InvalidHrs  
  FROM  #TempMonthTrans_MonthlyPresence TM     
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.Duration < 9.30 AND TM.Duration > 0 --AND TM.PresentStatus in ('HD') --('A','W','XX','H','WH','PW','LH')  
  AND   
  ( TM.Attn_dt NOT IN   
  (SELECT FromDate FRom sHRM.tLeave L Where L.EmployeeId=TM.EmployeeId AND L.StatusId = 550  
  AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND  
  TM.Attn_dt NOT IN   
  (SELECT LateDate FRom sBiometric.tEmployeeLateStatus ELS Where ELS.EmployeeId=TM.EmployeeId AND ELS.StatusId = 550  
   AND CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))))  
  )  
  AND TM.PresentStatus NOT IN ('A','H','PW','PWH','PH')  
    
  GROUP BY TM.EmployeeId  
  ) InvalidHrs ON InvalidHrs.EMployeeId = MT.EMployeeId   
    
  LEft Join  
  (select distinct SourceId,COUNT(cnt) AS PunchCnt From (  
   select SourceId,Count(Attn_dt) AS cnt from sBiometric.tPunchCount Group by SourceId,Attn_dt having sum(Incnt+OutCnt)>8  
   AND month(Attn_dt)=@rForMonth AND YEAR(Attn_dt)=@rForYear   
   ) A   
   group by A.SourceId)PunchCnt ON  PunchCnt.SourceId = MT.EMployeeId
   
   LEFT JOIN  -- >10.30 Count  
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS Late1030Count,sBiometric.fcalcHour(sum(sBiometric.fcalcMINI(Replace(ISNULL(TT.FirstIn,0),'.',':')) - 630))  
  AS Late1030Hours 
      From sBiometric.tMonthTrans MT  
   INNER JOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId     
   LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = MT.EmployeeId
   where MT.attn_dt = @lAttendanceDate   AND sBiometric.fcalcMINI(TT.FirstIn) > 630
   GRoup By TT.EmployeeId  
  )Late1030Count ON Late1030Count.EmployeeId = MT.EmployeeId 
      
  LEFT JOIN  -- Late Approve entry count Less then 30 min late  
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS Late1030CountAprooved ,sBiometric.fcalcHour(sum(sBiometric.fcalcMINI(Replace(ISNULL(TT.FirstIn,0),'.',':')) - 630))  
  AS Late1030HoursApproved 
      From sBiometric.tMonthTrans MT  
	  LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = MT.EmployeeId
   INNER JOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId  AND sBiometric.fcalcMINI(TT.FirstIn) > 630
   INNER JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TT.EmployeeId AND ELS.StatusId = 550   
   AND CONVERT(DATE,ELS.LateDate) = TT.Attn_Dt  
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )Late1030CountAprooved ON Late1030CountAprooved.EmployeeId = MT.EmployeeId  

  LEFT JOIN  -- early or first half day early   
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid1030Count,sBiometric.fcalcHour(sum(sBiometric.fcalcMINI(Replace(ISNULL(TT.FirstIn,0),'.',':')) - 630))  
  AS Late1030HoursValid  
      From sBiometric.tMonthTrans MT  
	  INNER JOIN sHRM.tLeave L on L.EmployeeId = MT.EmployeeId AND L.StatusId = 550
      INNER jOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.FirstIn > '10:30')  
	   AND L.FromDate = TT.Attn_Dt
      AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))
  )      
   where MT.attn_dt = @lAttendanceDate  
   GRoup By TT.EmployeeId  
  )LateValid1030Count ON LateValid1030Count.EmployeeId = MT.EmployeeId  
   
   LEFT JOIN  -- Late Count  
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateCount 
    From sBiometric.tMonthTrans MT  
   INNER JOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId     
   LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = MT.EmployeeId
   where MT.attn_dt = @lAttendanceDate   AND sBiometric.fcalcMINI(TT.FirstIn) > sBiometric.fcalcMINI(CASE WHEN EJD.WorkStartTime = '' THEN '09:35' WHEN EJD.WorkStartTime IS NULL THEN '09:35' ELSE EJD.WorkStartTime END)
   GRoup By TT.EmployeeId  
  )LateCount ON LateCount.EmployeeId = MT.EmployeeId

    LEFT JOIN --Early Leave Count
  (Select TT.EmployeeID, Count(TT.EmployeeID) ELCount,
	sBiometric.fcalcHour(sum(570 - sBiometric.fcalcMINI(Replace(ISNULL(TT.Duration,0),'.',':')))) AS ELHrs
   From sBiometric.tMonthTrans MT  
   INNER JOIN #TempMonthTrans_MonthlyPresence TT on MT.EmployeeId = TT.EmployeeId   
   where MT.attn_dt = @lAttendanceDate AND TT.Duration >= 7.30 AND TT.Duration <= 9.29
   AND month(TT.[Attn_dt])=month(MT.Attn_dt) AND year(TT.[Attn_dt])=year(MT.Attn_dt)
   AND  TT.PresentStatus NOT IN ('A','H','PW','PWH','PH')  
   Group By TT.EmployeeId  
  )ELCount ON ELCount.EmployeeId = MT.EmployeeId  

   WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '') and (isnull(EJD.dateofleaving,'') ='' or EJD.dateofleaving  > @lAttendanceDate)  
   AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
   AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
   AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
   AND ((EJD.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 
   AND ((EJD.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
--   AND EM.Code not in (1101,1102,1106,1107)
   ORDER BY EM.Code
   --select * from #TempMonthTrans_MonthlyPresence  
   --TRUNCATE TABLE #TempMonthTrans_MonthlyPresence  
 
 --SELECT  * FROM #FInal
 
  SELECT 
   Id,
   ISNULL(Cast(TI.Late as nvarchar(50)),0.00) As SLate,
   Cast(ISNULL(TI.Grt1030Cnt,0) as nvarchar(50)) As SGrt1030Cnt,
   Cast(ISNULL(TI.Tot_OT_IVH,0) as nvarchar(50)) As STot_OT_IVH,
   Cast(ISNULL(TI.Gt8PunchCnt,0) as nvarchar(50)) As SGt8PunchCnt
   INTO #SUMfMonthTot_OT_IVH
   FROM
   #FInal F 
CROSS APPLY [sSetup].[fMonthTot_OT_IVH] (@rBatchId,F.EmployeeId,@rForYear,@rForMonth,@rOrgId) TI

SELECT F.SrNo,F.MonthYear,F.Month,F.EmployeeId,F.Code,F.Name,F.DateOfJoining,F.[Organization Group],F.NoPunch,
F.WorkingDay,F.Cl,F.LWPLeave,F.LeaveNotApply,F.CompOff,F.item,F.DinnerAllowance,
ISNULL(Cast(F.Late as nvarchar(50)),'') + ' (' + ISNULL(Cast(TI.SLate as nvarchar(50)),0.00) + ')' As Late,
ISNULL(Cast(F.Grt1030Cnt as nvarchar(50)),'') + ' (' + Cast(ISNULL(TI.SGrt1030Cnt,0) as nvarchar(50)) + ')' As Grt1030Cnt,
F.Tot_OT,	F.Valid_Cnt,	F.InvalidHrs,	
ISNULL(Cast(F.Tot_OT_IVH as nvarchar(50)),'') + ' (' + Cast(ISNULL(TI.STot_OT_IVH,0) as nvarchar(50)) + ')'  As Tot_OT_IVH,	
F.MonthlyPunchAvg,	ISNULL(Cast(F.Gt8PunchCnt as nvarchar(50)),'') + ' (' + Cast(ISNULL(TI.SGt8PunchCnt,0) as nvarchar(50)) +')' As Gt8PunchCnt,	
F.CompanyEmail, F.Grt1030Cnt As Grt1030Cnt1,ISNULL(F.Tot_OT_IVH,'') As Tot_OT_IVH1,
F.Gt8PunchCnt As Gt8PunchCnt1,
ISNULL(F.Late,0) As Late1
,Cast(ISNULL(F.ELCount, 0) AS nvarchar(50)) + '(-' + Cast(ISNULL(F.ELHrs,0.00) as nvarchar(50)) + ')' AS EL
,F.EmployeeTypeId,
Flag
,PendingLeaveEntryDates
,Replace(ISNULL(F.ELHrs,0.00),'.',':') AS EarlyLeave
--F.Late1,
--F.LateValidCount,
--F.LateCountAprooved ,
--F.Date
 FROM
#FInal F 
LEFT JOIN #SUMfMonthTot_OT_IVH TI ON F.EmployeeId = TI.Id
 

 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sBiometric].[pMonthlyStatus]  
    
 @rOrgId smallint,
     @rBatchId int,     
     @rYear smallint,
     @rMonth smallint,
	 @rDayOfMonth smallint,
	 @rAttendanceTypeId int = 1

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
 CREATE Table #temptable  
 ( 
 ClassId bigint , DivisionId bigint,ClassDivisionName nvarchar(50) , ClassTeacherName nvarchar(100) ,
  P1 nvarchar(5),P2 nvarchar(5),P3 nvarchar(5),P4 nvarchar(5),P5 nvarchar(5),P6 nvarchar(5),P7 nvarchar(5),P8 nvarchar(5),P9 nvarchar(5),  
  P10 nvarchar(5),P11 nvarchar(5),P12 nvarchar(5),P13 nvarchar(5),P14 nvarchar(5),P15 nvarchar(5),P16 nvarchar(5),P17 nvarchar(5),  
  P18 nvarchar(5),P19 nvarchar(5),P20 nvarchar(5),P21 nvarchar(5),P22 nvarchar(5),P23 nvarchar(5),P24 nvarchar(5),P25 nvarchar(5),  
  P26 nvarchar(5),P27 nvarchar(5),P28 nvarchar(5),P29 nvarchar(5),P30 nvarchar(5),P31 nvarchar(5)  
 )  

 Insert into #temptable  
 (  
  ClassId,DivisionId,ClassDivisionName,  ClassTeacherName,P1
 ) 
 
( SELECT 	A.ClassId ,A.DivisionId,	
			vCD.ClassDivisionName,
			ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
		    CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01')),@rAttendanceTypeId,0)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  AS P1
			   
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId
			AND SR.IsPresent=1 		 	
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId )
          
 DECLARE @intFlag INT
 DECLARE @DAY INT
SET @intFlag = 2
 DECLARE @COLFlag NVARCHAR(5)

WHILE (@intFlag <=@rDayOfMonth)
BEGIN
--    PRINT @intFlag; 
	
--	--SET @DAY=CASE WHEN LEN(@intFlag)=1 THEN CONCAT('0',@intFlag)  ELSE @intFlag END

	SET @COLFlag=   'P' + CAST(@intFlag AS varchar(12)); 

--	--update #temptable set @COLFlag= 
	
--UPDATE #temptable set P2= 

 --Insert into #temptable  
 --(  
 -- ClassDivisionName,  ClassTeacherName,P2
 --) 
UPDATE  T1 set @COLFlag= ( 
SELECT 				
			
		    CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,@intFlag,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,@intFlag,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-'+CONVERT(NVARCHAR(2),@intFlag))),@rAttendanceTypeId)) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END 
			   
    FROM 


			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            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  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-'+CONVERT(NVARCHAR(2),@intFlag)))		
            AND SR.AttendanceTypeId =@rAttendanceTypeId
			AND SR.IsPresent=1	 		
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId ) FROM #temptable T1
			INNER JOIN #temptable T2  ON T2.ClassId =T1.ClassId AND T2.DivisionId=T1.DivisionId 
   

    SET @intFlag = @intFlag + 1;
END 
 
 SELECT * FROM #temptable
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pMonthlyStatusUpdate]
    
    @rAttndanceDate date,
    @rIsDelete bit=0,
    @rOrgGroupId int=0,
    @rBatchId int=0,
    @rOrgId int=0,
    @rUserId bigint=0
    
AS
SET NOCOUNT ON
BEGIN

	IF OBJECT_ID('tempdb..#TempLateCountEntry') IS NOT NULL
		DROP TABLE #TempLateCountEntry
	
	IF(@rIsDelete = 0)
	BEGIN
		IF EXISTS(SELECT 1 FROM sBiometric.tMonthlyStatusUpdate WHERE CONVERT(date,AttndanceDate) = CONVERT(date,@rAttndanceDate) AND Left(EmployeeID,4) =@rOrgId)
		BEGIN
			SELECT -201 AS RESULT 
			RETURN
		END
	END
	--ELSE
	--BEGIN
	--	IF NOT EXISTS(SELECT 1 FROM sBiometric.tMonthlyStatusUpdate WHERE AttndanceDate=@rAttndanceDate)
	--	BEGIN
	--		SELECT -102 AS RESULT
	--		RETURN
	--	END
	--END

	BEGIN TRY
	BEGIN TRANSACTION
	
	IF(@rIsDelete = 0)
	BEGIN
		Declare @Days int 
		DECLARE @rMonth int
		DECLARE @rYear int
		Set @rMonth = MONTH(@rAttndanceDate)
		Set @rYear = Year(@rAttndanceDate)
		select @Days=sCommon.fGetDaysInMonth(@rMonth,@rYear)
		
		INSERT INTO 
		sBiometric.tMonthlyStatusUpdate 
		SELECT            			            
	 Attn_Dt, Mt.EmployeeId, CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,1,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,1,BM.Id,0,BM.OrgId) Else Mt.D01 End D01,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,2,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,2,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D02 End D02,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,3,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,3,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D03 End D03,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,4,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,4,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D04 End D04,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,5,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,5,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D05 End D05,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,6,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,6,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else Mt.D06 End D06,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,7,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,7,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D07 End D07,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,8,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,8,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D08 End D08,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,9,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,9,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D09 End D09,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,10,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,10,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D10 End D10,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,11,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,11,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D11 End D11,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,12,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,12,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D12 End D12,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,13,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,13,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D13 End D13,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,14,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,14,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D14 End D14,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,15,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,15,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D15 End D15,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,16,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,16,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D16 End D16,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,17,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,17,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D17 End D17,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,18,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,18,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D18 End D18,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,19,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,19,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D19 End D19,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,20,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,20,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D20 End D20,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,21,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,21,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D21 End D21,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,22,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,22,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D22 End D22,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,23,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,23,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D23 End D23,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,24,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,24,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D24 End D24,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,25,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,25,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D25 End D25,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,26,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,26,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D26 End D26,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,27,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,27,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D27 End D27,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,28,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,28,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D28 End D28,
	 CAse when @Days >= 29 AND [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,29,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,29,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D29 End D29,
	 CAse when @Days >= 30 AND [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,30,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,30,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D30 End D30,
	 CAse when @Days >= 31 AND [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,31,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,31,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D31 End D31, 
	 D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, 
			D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, 
			D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, 
			D30_OUT, D31_OUT, Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, Tot_HD, Tot_Leave
		FROM sBiometric.tMonthTrans Mt  LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Mt.EmployeeId 
		inner join sSetup.tBatchMaster BM ON BM.OrgId = ED.OrgId AND BM.IsActive = 1  AND ED.OrgId = @rOrgId
		WHERE CONVERT(date,Attn_Dt) = CONVERT(date,@rAttndanceDate) --AND Mt.EmployeeId = 9931000000051
		
	-- Leave Entry
	DECLARE @lIsErrorCaseAsAnAbsent bit=0	
	DECLARE @lErrorCaseAsAnAbsent nvarchar(50)
	
	SELECT @lErrorCaseAsAnAbsent = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 254 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF (@lErrorCaseAsAnAbsent IS NULL) OR (@lErrorCaseAsAnAbsent = 'False')
	SET @lIsErrorCaseAsAnAbsent = 0
	ELSE
	SET @lIsErrorCaseAsAnAbsent = 1	 
	
	DECLARE @lIsErrorCaseLeaveEntryDirectly bit=0	
	DECLARE @lErrorCaseLeaveEntryDirectly nvarchar(50)
	
	SELECT @lIsErrorCaseLeaveEntryDirectly = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 255 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF (@lIsErrorCaseLeaveEntryDirectly IS NULL) OR (@lIsErrorCaseLeaveEntryDirectly = 'False')
	SET @lErrorCaseLeaveEntryDirectly = 0
	ELSE
	SET @lErrorCaseLeaveEntryDirectly = 1	
	
	DECLARE @lIsAbsentAsLWP bit=0	
	DECLARE @lAbsentAsLWP nvarchar(50)
	
	SELECT @lAbsentAsLWP = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 258 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF (@lAbsentAsLWP IS NULL) OR (@lAbsentAsLWP = 'False')
	SET @lIsAbsentAsLWP = 0
	ELSE
	SET @lIsAbsentAsLWP = 1
	
	
	DECLARE @lErrorCaseLeaveDeduction nvarchar(50)
	SELECT @lErrorCaseLeaveDeduction = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 306 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	
	IF(@lIsErrorCaseLeaveEntryDirectly=1)
	BEGIN 		
		DECLARE @rFromDate date
		DECLARE @rToDate date
		
		SET @rFromDate = @rAttndanceDate		
		SET @rToDate = CONVERT(date, (CONVERT(nvarchar(4),YEAR(@rAttndanceDate)) +'-'+CONVERT(nvarchar(2),MONTH(@rAttndanceDate)) +'-'+ CONVERT(nvarchar(2),@Days)))
		
		CREATE TABLE #TempMonthlyStatusUpdate
		(
		Id int Identity,
		EmployeeId bigint,	
		AttendanceDate Date,
		PresentStatus nvarchar(50)
		)

		INSERT INTO #TempMonthlyStatusUpdate

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 01) as datetime),D01 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 02) as datetime),D02 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 03) as datetime),D03 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 04) as datetime),D04 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 05) as datetime),D05 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 06) as datetime),D06 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 07) as datetime),D07 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 08) as datetime),D08 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 09) as datetime),D09 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 10) as datetime),D10 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 11) as datetime),D11 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 12) as datetime),D12 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 13) as datetime),D13 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 14) as datetime),D14 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 15) as datetime),D15 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 16) as datetime),D16 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 17) as datetime),D17 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 18) as datetime),D18 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 19) as datetime),D19 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 20) as datetime),D20 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 21) as datetime),D21 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 22) as datetime),D22 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 23) as datetime),D23 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 24) as datetime),D24 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 25) as datetime),D25 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 26) as datetime),D26 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 27) as datetime),D27 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 28) as datetime),D28 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
		BEGIN
		INSERT INTO #TempMonthlyStatusUpdate
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 29) as datetime),D29 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID
		END

		IF Month(@rFromDate) <> 2
		BEGIN
		INSERT INTO #TempMonthlyStatusUpdate
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 30) as datetime),D30 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID
		END

		IF Month(@rFromDate) NOT IN (2,4,6,9,11)
		BEGIN
		INSERT INTO #TempMonthlyStatusUpdate
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 31) as datetime),D31 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID
		END
		
		DECLARE @lCount int = 0
		SELECT @lCount = COUNT(Id) FROM #TempMonthlyStatusUpdate				
	 --- 3 Late Count means Add 1 Leave START HERE

		DECLARE @lLateCountLeaveType nvarchar(50)
		SELECT @lLateCountLeaveType = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 351 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

		SELECT ROW_NUMBER() OVER(ORDER BY EMPLOYEEID ASC) AS RowNumber,EMPLOYEEID,ATTN_DT,count_late INTO #TempLateCountEntry FROM sBiometric.tMonthTrans 
		where EMPLOYEEID IN(SELECT EMPLOYEEID FROM  #TempMonthlyStatusUpdate WHERE MONTH(AttendanceDate)=@rMonth AND YEAR(AttendanceDate)=@rYear  GROUP BY EMPLOYEEID)
		AND MONTH(ATTN_DT)=@rMonth AND YEAR(ATTN_DT)=@rYear
		
		DECLARE @lMonthTransCount int=0		
		SELECT @lMonthTransCount = COUNT(RowNumber) FROM #TempLateCountEntry

		WHILE (@lMonthTransCount > 0)
		BEGIN 
			DECLARE @lLateCount int = 0
			DECLARE @rEmployeeId bigint = 0
			DECLARE @lAttnDt date
			DECLARE @rLeaveTypeId int = 0
			DECLARE @rTotalLeave int = 0
			DECLARE @FromDt date
			DECLARE @ToDt date
			DECLARE @lNextNumber bigint			

			IF(@lLateCountLeaveType IS NOT NULL)
				BEGIN
					SELECT @rEmployeeId=ISNULL(EmployeeId,0) FROM #TempLateCountEntry WHERE RowNumber = @lMonthTransCount 

					DECLARE @lIsErrorCaseAsAnAbsentEmployeeWise_ForLate nvarchar(100)
					DECLARE @lIsAbsentAsLWPEmployeeWise_ForLate nvarchar(100)

					SELECT @lIsErrorCaseAsAnAbsentEmployeeWise_ForLate = Value FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @rEmployeeId AND EmployeeConfigurationMasterId = 2
					SELECT @lIsAbsentAsLWPEmployeeWise_ForLate = Value FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @rEmployeeId AND EmployeeConfigurationMasterId = 1

					IF (@lIsErrorCaseAsAnAbsentEmployeeWise_ForLate IS NULL)
						SET @lIsErrorCaseAsAnAbsentEmployeeWise_ForLate = @lErrorCaseAsAnAbsent
					IF (@lIsAbsentAsLWPEmployeeWise_ForLate IS NULL)
						SET @lIsAbsentAsLWPEmployeeWise_ForLate = @lAbsentAsLWP
					

					IF(@lIsErrorCaseAsAnAbsentEmployeeWise_ForLate = 'True' OR @lIsAbsentAsLWPEmployeeWise_ForLate = 'True')
					BEGIN
					set @lLateCount= (SELECT ISNULL([sBiometric].[fEmployeeLateCountGet](@rEmployeeId, @rMonth,@rYear),0) AS LateCount)

					IF(@lLateCount >= 3)
					BEGIN
						SELECT @rLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND Code=@lLateCountLeaveType

						SET @rTotalLeave = (SELECT (@lLateCount/3) AS RESULT ) 

						IF(@rLeaveTypeId!=0)
							BEGIN
							SET @lAttnDt = GETDATE()
							
							SET @ToDt =  CONVERT(date, (CONVERT(nvarchar(4),@rYear) +'-'+CONVERT(nvarchar(2),@rMonth) +'-'+ CONVERT(nvarchar(2),@Days)))

							SET @FromDt = (select DATEADD(D,(-@rTotalLeave)+1 ,@ToDt))

							IF NOT EXISTS(SELECT 1 FROM sHrm.tLeave WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND BatchId = @rBatchId AND StatusId=550 and LeaveReason='Late Coming' AND ReportDate=@ToDt)

								BEGIN
								 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeave', 0, 1, 1,@outNextNumber = @lNextNumber output
							 
								INSERT INTO [sHrm].[tLeave]([Id],[EmployeeId],[ReportDate],[FromDate],[ToDate],[LeavePeriodId],[LeaveTypeId],[LeaveReason],NoOfLeave,BatchId,[OrgId],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime],[StatusId],[FromTime],[ToTime])
								 VALUES (@lNextNumber,@rEmployeeId,@ToDt,@FromDt,@ToDt ,1,@rLeaveTypeId,'Late Coming',@rTotalLeave,@rBatchId,@rOrgId,@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate(),550,NULL,NULL)	

								--EXEC [sHrm].[pLeaveAdd] 0,@rEmployeeId,@ToDt,@FromDt,@ToDt ,1,@rLeaveTypeId,'Late Coming',@rTotalLeave,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
								END
							END
					END
			END
		END

			SET @lMonthTransCount = @lMonthTransCount -1
		END
	--- END HERE
		
		WHILE (@lCount > 0)
		BEGIN		
			 DECLARE @lEmployeeId bigint = 0
			 DECLARE @lAttendanceDate date
			 DECLARE @lPresentStatus nvarchar(50) = ''
			 DECLARE @lLeaveTypeId int = 0
			 			 
				SELECT @lEmployeeId=ISNULL(EmployeeId,0),@lAttendanceDate=AttendanceDate,@lPresentStatus=PresentStatus FROM #TempMonthlyStatusUpdate WHERE Id = @lCount AND PresentStatus='E'
					IF(@lEmployeeId!=0)
					BEGIN
						DECLARE @lIsErrorCaseAsAnAbsentEmployeeWise nvarchar(100)	= @lErrorCaseAsAnAbsent					

					SELECT @lIsErrorCaseAsAnAbsentEmployeeWise = Value FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @lEmployeeId AND EmployeeConfigurationMasterId = 2
					

					IF (@lIsErrorCaseAsAnAbsentEmployeeWise IS NULL)
						SET @lIsErrorCaseAsAnAbsentEmployeeWise = @lErrorCaseAsAnAbsent
					
					--print(@lIsErrorCaseAsAnAbsentEmployeeWise)

					IF(@lIsErrorCaseAsAnAbsentEmployeeWise = 'True')
					BEGIN

						SELECT @lLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND IsLWP=1
						
						IF(@lLeaveTypeId!=0)
						BEGIN
							IF(@lErrorCaseLeaveDeduction='0' OR @lErrorCaseLeaveDeduction='1')
								EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,1,@lLeaveTypeId,'Error Case',1,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
							ELSE IF(@lErrorCaseLeaveDeduction='0.50')
								EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,1,@lLeaveTypeId,'Error Case',0.50,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
						END	
					END
			 END
			 			 
				SELECT @lEmployeeId=ISNULL(EmployeeId,0),@lAttendanceDate=AttendanceDate,@lPresentStatus=PresentStatus FROM #TempMonthlyStatusUpdate WHERE Id = @lCount AND (PresentStatus='A' OR PresentStatus = 'HD')
					IF(@lEmployeeId!=0)
					BEGIN					
					DECLARE @lIsAbsentAsLWPEmployeeWise nvarchar(100) = @lAbsentAsLWP
					SELECT @lIsAbsentAsLWPEmployeeWise = Value FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @lEmployeeId AND EmployeeConfigurationMasterId = 1
					IF (@lIsAbsentAsLWPEmployeeWise IS NULL)BEGIN					
						SET @lIsAbsentAsLWPEmployeeWise = @lAbsentAsLWP 
						END
										
					IF(@lIsAbsentAsLWPEmployeeWise = 'True')					
					SELECT @lLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND IsLWP=1
					IF(@lLeaveTypeId!=0)
					BEGIN										
						IF(@lPresentStatus = 'HD') BEGIN 
						EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,2,@lLeaveTypeId,'Error Case(Half Day)',0.50,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL 
						END
						ELSE BEGIN
						EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,1,@lLeaveTypeId,'Error Case(Full Day)',1,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
						END
				END
			 END
			 
			 SET @lCount = @lCount -1
		END
	END
	END
	ELSE
	BEGIN
		DELETE FROM sBiometric.tMonthlyStatusUpdate WHERE CONVERT(date,AttndanceDate) = CONVERT(date,@rAttndanceDate)
		AND Left(EmployeeID,4)=@rOrgId
	END
	
	SELECT 1 AS RESULT	
	   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pMonthlyStatusUpdateGet]

	@rCode nvarchar(20)='',
	@rName nvarchar(100)='',
	@rDepartmentId int=0,
	@rEmployeeGroupId int=0,
	@rForYear int,
	@rForMonth int,
	@rOrgId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	BEGIN
		SET @rName= sCommon.fSearchStringGet(@rName)
	END

	DECLARE @lAttndanceDate nvarchar(20)
	DECLARE @lBatchId int = 0
	DECLARE @lDays int = 0
	
	SELECT @lBatchId = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
	SELECT @lDays = sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	SET @lAttndanceDate = convert(nvarchar(10),@rForYear) + '-' + convert(nvarchar(10),@rForMonth) + '-' + '01'
	
	SELECT 
		MSU.EmployeeId,vEM.Code,vEM.EmployeeName,
		MSU.D01,MSU.D02,MSU.D03,MSU.D04,MSU.D05,MSU.D06,MSU.D07,MSU.D08,MSU.D09,MSU.D10,
		MSU.D11,MSU.D12,MSU.D13,MSU.D14,MSU.D15,MSU.D16,MSU.D17,MSU.D18,MSU.D19,MSU.D20,
		MSU.D21,MSU.D22,MSU.D23,MSU.D24,MSU.D25,MSU.D26,MSU.D27,MSU.D28,
		ISNULL(MSU.D29,'') AS D29,ISNULL(MSU.D30,'') AS D30,ISNULL(MSU.D31,'') AS D31,
		D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, 
		D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, 
		D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, 
		D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, D30_OUT, D31_OUT,
		TotalPresent,TotalAbsent,TotalWeekOFF,TotalHoliday,TotalHD,TotalLeave
	FROM 
		sBiometric.tMonthlyStatusUpdate MSU
		INNER JOIN sHrm.vExtEmployeeMaster vEM ON MSU.EmployeeId = vEM.EmployeeId
	WHERE 
		(vEM.Code = @rCode OR ISNULL(@rCode,'') ='')
		AND(vEM.EmployeeName LIKE @rName OR ISNULL(@rName,'') = '') 
		AND (vEM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND (vEM.EmployeeGroupId = @rEmployeeGroupId OR @rEmployeeGroupId = 0)
		AND (vEM.OrgId=@rOrgId) 
		AND	(MSU.AttndanceDate = @lAttndanceDate) AND vEM.StatusID = 7
    ORDER BY vEM.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pMonthTransProcess]
AS
SET NOCOUNT ON

BEGIN
	--Drop temp table for server issue(tempdb)
	IF object_id('tempdb..#tTable') IS NOT NULL
	BEGIN
		DROP TABLE #tTable
	END

	CREATE TABLE #tTable (
		Id BIGINT identity
		,[SourceId] [bigint] NOT NULL
		,[In_Out_Time] [datetime] NOT NULL
		,[ShiftCode] [int] NOT NULL
		,[Attn_Dt] [date] NOT NULL
		,[Mode] [nvarchar](10) NOT NULL
		,[CreatedDateTime] [datetime] NOT NULL
		,[DeviceIP] [nvarchar](20) NOT NULL
		,[EntryMode] [tinyint] NOT NULL
		,[PunchId] [nvarchar](50) NOT NULL
		,[TransactionId] [bigint] NOT NULL
		,[SourceTypeId] [smallint] NULL
		,[IsProcessed] [bit] NULL
		)

	DECLARE @lPrevAttn_Dt DATE = ''
	DECLARE @lPrevSourceId BIGINT = 0
	DECLARE @lPrevSourceTypeId SMALLINT = 0

	IF (DAY(sCommon.fGetDate()) > 10)
	BEGIN
		INSERT INTO #tTable
		SELECT [SourceId]
			,[In_Out_Time]
			,[ShiftCode]
			,[Attn_Dt]
			,[Mode]
			,[CreatedDateTime]
			,[DeviceIP]
			,[EntryMode]
			,[PunchId]
			,[TransactionId]
			,[SourceTypeId]
			,[IsProcessed]
		FROM [sBiometric].[tCloudTransactionData] WITH (NOLOCK)
		WHERE MONTH(Attn_Dt) = MONTH(sCommon.fGetDate())
			AND YEAR(Attn_Dt) = YEAR(sCommon.fGetDate())
			AND IsProcessed = 0
	END
	ELSE
	BEGIN
		INSERT INTO #tTable
		SELECT [SourceId]
			,[In_Out_Time]
			,[ShiftCode]
			,[Attn_Dt]
			,[Mode]
			,[CreatedDateTime]
			,[DeviceIP]
			,[EntryMode]
			,[PunchId]
			,[TransactionId]
			,[SourceTypeId]
			,[IsProcessed]
		FROM [sBiometric].[tCloudTransactionData] WITH (NOLOCK)
		WHERE YEAR(Attn_Dt) = YEAR(sCommon.fGetDate())
			AND MONTH(Attn_Dt) IN (
				MONTH(sCommon.fGetDate())
				,MONTH(sCommon.fGetDate()) - 1
				)
			AND IsProcessed = 0 --mantis: 34236, change (MONTH(sCommon.fGetDate()),MONTH(sCommon.fGetDate() - 1)) => (MONTH(sCommon.fGetDate()),MONTH(sCommon.fGetDate()) - 1)
	END

	SELECT *
	FROM #tTable

	DECLARE @lCount INT = 1
	DECLARE @lTotal INT = (
			SELECT COUNT(Id)
			FROM #tTable
			)

	WHILE @lCount <= @lTotal
	BEGIN
		DECLARE @lQuery NVARCHAR(max) = ''
		DECLARE @lAttn_Dt DATE = (
				SELECT Attn_Dt
				FROM #tTable
				WHERE Id = @lCount
				)
		DECLARE @lSourceId BIGINT = (
				SELECT SourceId
				FROM #tTable
				WHERE Id = @lCount
				)
		DECLARE @lSourceTypeId SMALLINT = (
				SELECT SourceTypeId
				FROM #tTable
				WHERE Id = @lCount
				)
		DECLARE @lTransactionId BIGINT = (
				SELECT TransactionId
				FROM #tTable
				WHERE Id = @lCount
				)

		IF (
				@lPrevAttn_Dt = @lAttn_Dt
				AND @lPrevSourceId = @lSourceId
				AND @lPrevSourceTypeId = @lSourceTypeId
				)
		BEGIN
			PRINT ('same employee')

			UPDATE sBiometric.tCloudTransactionData WITH (ROWLOCK)
			SET IsProcessed = 1
			WHERE TransactionId = @lTransactionId
		END
		ELSE
		BEGIN
			DECLARE @lCode INT = (
					SELECT ISNULL(MAX(EmpCode), 0) + 1
					FROM sBiometric.tMonthTrans WITH (NOLOCK)
					)

			IF EXISTS (
					SELECT 1
					FROM sBiometric.tMonthTrans WITH (NOLOCK)
					WHERE EmployeeId = @lSourceId
						AND SourceTypeId = @lSourceTypeId
					)
			BEGIN
				SET @lCode = (
						SELECT TOP 1 EmpCode
						FROM sBiometric.tMonthTrans WITH (NOLOCK)
						WHERE EmployeeId = @lSourceId
							AND SourceTypeId = @lSourceTypeId
						)
			END

			DECLARE @lShift VARCHAR(25) = (
					SELECT ShiftName
					FROM sBiometric.tShiftMasterCloud WITH (NOLOCK)
					WHERE ShiftCode IN (
							SELECT ShiftCode
							FROM #tTable
							WHERE Id = @lCount
							)
					)
			DECLARE @lShiftStartTime DATETIME = (
					SELECT StartTime
					FROM sBiometric.tShiftMasterCloud WITH (NOLOCK)
					WHERE ShiftCode IN (
							SELECT ShiftCode
							FROM #tTable
							WHERE Id = @lCount
							)
					)
			DECLARE @lShiftEndTime DATETIME = (
					SELECT EndTime
					FROM sBiometric.tShiftMasterCloud WITH (NOLOCK)
					WHERE ShiftCode IN (
							SELECT ShiftCode
							FROM #tTable
							WHERE Id = @lCount
							)
					)
			DECLARE @lMinHoursHalfDay TIME = CAST(CAST((
							SELECT MinHrsHalfDay
							FROM sBiometric.tShiftMasterCloud WITH (NOLOCK)
							WHERE ShiftCode IN (
									SELECT ShiftCode
									FROM #tTable
									WHERE Id = @lCount
									)
							) AS NVARCHAR) AS TIME)
			DECLARE @lMinHoursFullDay TIME = CAST(CAST((
							SELECT MinHrsFullDay
							FROM sBiometric.tShiftMasterCloud WITH (NOLOCK)
							WHERE ShiftCode IN (
									SELECT ShiftCode
									FROM #tTable
									WHERE Id = @lCount
									)
							) AS NVARCHAR) AS TIME)
			DECLARE @lIn TIME = CONVERT(TIME, (
						SELECT MIN(In_Out_Time)
						FROM sBiometric.tCloudTransactionData WITH (NOLOCK)
						WHERE Attn_Dt = @lAttn_Dt
							AND SourceId = @lSourceId
							AND SourceTypeId = @lSourceTypeId
						))
			DECLARE @lOut TIME = CASE 
					WHEN (
							SELECT COUNT(In_Out_Time)
							FROM sBiometric.tCloudTransactionData WITH (NOLOCK)
							WHERE Attn_Dt = @lAttn_Dt
								AND SourceId = @lSourceId
								AND SourceTypeId = @lSourceTypeId
							) > 1
						THEN CONVERT(TIME, (
									SELECT MAX(In_Out_Time)
									FROM #tTable
									WHERE Attn_Dt = @lAttn_Dt
										AND SourceId = @lSourceId
										AND SourceTypeId = @lSourceTypeId
									))
					ELSE '00:00'
					END
			DECLARE @lTotalTime VARCHAR(10) = CASE 
					WHEN @lOut <> '00:00'
						THEN (
								SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lIn, @lOut), 0), 114)
								)
					ELSE '00:00'
					END
			DECLARE @lEarlyBy VARCHAR(10) = '00:00'
			DECLARE @lLateBy VARCHAR(10) = '00:00'
			DECLARE @lOverTime VARCHAR(10) = ''
			DECLARE @lStatus VARCHAR(10) = ''

			--Add by Nimesh MantisId:0027752
			--Start
			IF (
					DATEDIFF(minute, @lShiftStartTime, @lIn) > 0
					AND @lIn <> '00:00'
					)
			BEGIN
				--SET @lLateBy = '00:00'
				SET @lLateBy = (
						SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lShiftStartTime, @lIn), 0), 114)
						)
			END

			IF (
					DATEDIFF(minute, @lShiftEndTime, @lOut) < 0
					AND @lOut <> '00:00'
					)
			BEGIN
				--SET @lEarlyBy = '00:00'
				SET @lEarlyBy = (
						SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lOut, @lShiftEndTime), 0), 114)
						)
			END

			--End
			IF (DATEDIFF(minute, @lShiftEndTime, @lOut) < 0)
			BEGIN
				SET @lOverTime = '00:00'
			END
			ELSE
			BEGIN
				SET @lOverTime = CASE 
						WHEN @lOut <> '00:00'
							THEN (
									SELECT CONVERT(VARCHAR(10), DATEADD(minute, DATEDIFF(minute, @lShiftEndTime, @lOut), 0), 114)
									)
						ELSE '00:00'
						END
			END

			IF (CAST(@lTotalTime AS TIME) >= @lMinHoursFullDay)
			BEGIN
				SET @lStatus = 'P'
			END

			IF (
					CAST(@lTotalTime AS TIME) >= @lMinHoursHalfDay
					AND CAST(@lTotalTime AS TIME) < @lMinHoursFullDay
					)
			BEGIN
				SET @lStatus = 'HD'
			END

			IF (CAST(@lTotalTime AS TIME) < @lMinHoursHalfDay)
			BEGIN
				SET @lStatus = 'LH'
			END

			IF (
					@lOut = '00:00'
					AND @lIn <> '00:00'
					)
			BEGIN
				SET @lStatus = 'E'
			END

			--Uncomment this for testing purposes
			--PRINT('In Time: ' + CONVERT(VARCHAR(5),@lIn,108))
			--PRINT('Out Time: ' + CONVERT(VARCHAR(5),@lOut,108))
			--PRINT('Total Time : ' + CONVERT(VARCHAR(5),@lTotalTime,108))
			--PRINT('Overtime : ' + CONVERT(VARCHAR(5),@lOverTime,108))
			--PRINT('Min Hours Half Day : ' + CONVERT(VARCHAR(5),@lMinHoursHalfDay,108))
			--PRINT('Min Hours Full Day : ' + CONVERT(VARCHAR(5),@lMinHoursFullDay,108))
			--PRINT('EarlyBy : ' + CONVERT(VARCHAR(5),@lEarlyBy,108))
			--PRINT('LateBy : ' + CONVERT(VARCHAR(5),@lLateBy,108))
			--PRINT('Status : ' + CONVERT(VARCHAR(5),@lStatus,108))
			--BREAK
			DECLARE @lDay NVARCHAR(10) = (
					SELECT DAY(IN_Out_Time)
					FROM #tTable
					WHERE Id = @lCount
					)

			SET @lDay = (
					SELECT CASE 
							WHEN @lDay BETWEEN 0
									AND 9
								THEN RIGHT('0' + CAST(@lDay AS VARCHAR(2)), 2)
							ELSE CAST(@lDay AS NVARCHAR(10))
							END
					)

			DECLARE @lMonthTransAttn_DtTemp DATETIME = (
					SELECT cast((cast(YEAR(@lAttn_Dt) AS VARCHAR(255)) + '-' + cast(MONTH(@lAttn_Dt) AS VARCHAR(255)) + '-' + '01') AS DATETIME)
					)
			DECLARE @lMonthTransAttn_Dt VARCHAR(20) = convert(VARCHAR(20), @lMonthTransAttn_DtTemp, 20)

			PRINT (@lMonthTransAttn_Dt)

			IF NOT EXISTS (
					SELECT 1
					FROM sBiometric.tMonthTrans WITH (NOLOCK)
					WHERE EmployeeId = @lSourceId
						AND SourceTypeId = @lSourceTypeId
						AND Attn_Dt = @lMonthTransAttn_Dt
					)
			BEGIN
				--Insert 
				INSERT INTO sBiometric.tMonthTrans
				WITH (ROWLOCK) (
					EmpCode
					,EmployeeId
					,Attn_Dt
					,D01
					,D02
					,D03
					,D04
					,D05
					,D06
					,D07
					,D08
					,D09
					,D10
					,D11
					,D12
					,D13
					,D14
					,D15
					,D16
					,D17
					,D18
					,D19
					,D20
					,D21
					,D22
					,D23
					,D24
					,D25
					,D26
					,D27
					,D28
					,D29
					,D30
					,D31
					,D01_IN
					,D02_IN
					,D03_IN
					,D04_IN
					,D05_IN
					,D06_IN
					,D07_IN
					,D08_IN
					,D09_IN
					,D10_IN
					,D11_IN
					,D12_IN
					,D13_IN
					,D14_IN
					,D15_IN
					,D16_IN
					,D17_IN
					,D18_IN
					,D19_IN
					,D20_IN
					,D21_IN
					,D22_IN
					,D23_IN
					,D24_IN
					,D25_IN
					,D26_IN
					,D27_IN
					,D28_IN
					,D29_IN
					,D30_IN
					,D31_IN
					,D01_OUT
					,D02_OUT
					,D03_OUT
					,D04_OUT
					,D05_OUT
					,D06_OUT
					,D07_OUT
					,D08_OUT
					,D09_OUT
					,D10_OUT
					,D11_OUT
					,D12_OUT
					,D13_OUT
					,D14_OUT
					,D15_OUT
					,D16_OUT
					,D17_OUT
					,D18_OUT
					,D19_OUT
					,D20_OUT
					,D21_OUT
					,D22_OUT
					,D23_OUT
					,D24_OUT
					,D25_OUT
					,D26_OUT
					,D27_OUT
					,D28_OUT
					,D29_OUT
					,D30_OUT
					,D31_OUT
					,D01_O
					,D02_O
					,D03_O
					,D04_O
					,D05_O
					,D06_O
					,D07_O
					,D08_O
					,D09_O
					,D10_O
					,D11_O
					,D12_O
					,D13_O
					,D14_O
					,D15_O
					,D16_O
					,D17_O
					,D18_O
					,D19_O
					,D20_O
					,D21_O
					,D22_O
					,D23_O
					,D24_O
					,D25_O
					,D26_O
					,D27_O
					,D28_O
					,D29_O
					,D30_O
					,D31_O
					,D01_L
					,D02_L
					,D03_L
					,D04_L
					,D05_L
					,D06_L
					,D07_L
					,D08_L
					,D09_L
					,D10_L
					,D11_L
					,D12_L
					,D13_L
					,D14_L
					,D15_L
					,D16_L
					,D17_L
					,D18_L
					,D19_L
					,D20_L
					,D21_L
					,D22_L
					,D23_L
					,D24_L
					,D25_L
					,D26_L
					,D27_L
					,D28_L
					,D29_L
					,D30_L
					,D31_L
					,D01_T
					,D02_T
					,D03_T
					,D04_T
					,D05_T
					,D06_T
					,D07_T
					,D08_T
					,D09_T
					,D10_T
					,D11_T
					,D12_T
					,D13_T
					,D14_T
					,D15_T
					,D16_T
					,D17_T
					,D18_T
					,D19_T
					,D20_T
					,D21_T
					,D22_T
					,D23_T
					,D24_T
					,D25_T
					,D26_T
					,D27_T
					,D28_T
					,D29_T
					,D30_T
					,D31_T
					,D01_S
					,D02_S
					,D03_S
					,D04_S
					,D05_S
					,D06_S
					,D07_S
					,D08_S
					,D09_S
					,D10_S
					,D11_S
					,D12_S
					,D13_S
					,D14_S
					,D15_S
					,D16_S
					,D17_S
					,D18_S
					,D19_S
					,D20_S
					,D21_S
					,D22_S
					,D23_S
					,D24_S
					,D25_S
					,D26_S
					,D27_S
					,D28_S
					,D29_S
					,D30_S
					,D31_S
					,D01_E
					,D02_E
					,D03_E
					,D04_E
					,D05_E
					,D06_E
					,D07_E
					,D08_E
					,D09_E
					,D10_E
					,D11_E
					,D12_E
					,D13_E
					,D14_E
					,D15_E
					,D16_E
					,D17_E
					,D18_E
					,D19_E
					,D20_E
					,D21_E
					,D22_E
					,D23_E
					,D24_E
					,D25_E
					,D26_E
					,D27_E
					,D28_E
					,D29_E
					,D30_E
					,D31_E
					,[Tot_Attn]
					,[Tot_Abs]
					,[Tot_WeekOFF]
					,[Tot_Holiday]
					,[TotalHour]
					,[Tot_HD]
					,[Tot_Early]
					,[Tot_Late]
					,[Tot_OT]
					,[Tot_OD]
					,[Tot_Leave]
					,[Count_Late]
					,[Count_Early]
					,[Count_OT]
					,Tot_CL
					,Tot_SL
					,Tot_EL
					,Tot_SP
					,Tot_C
					,Tot_PL
					,Tot_ML
					,SourceTypeId
					)
				VALUES (
					@lCode
					,@lSourceId
					,@lMonthTransAttn_Dt
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'XX'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,'00:00'
					,0
					,0
					,0
					,0
					,''
					,0
					,''
					,''
					,''
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,0
					,@lSourceTypeId
					)
			END

			--Update
			SET @lQuery = 'UPDATE sBiometric.tMonthTrans with (rowlock)
			SET D' + CAST(@lDay AS VARCHAR) + '_IN = ''' + CONVERT(VARCHAR(5), @lIn, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_OUT = ''' + CONVERT(VARCHAR(5), @lOut, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_E = ''' + CONVERT(VARCHAR(5), @lEarlyBy, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_L = ''' + CONVERT(VARCHAR(5), @lLateBy, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_O = ''' + CONVERT(VARCHAR(5), @lOverTime, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_T = ''' + CONVERT(VARCHAR(5), @lTotalTime, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + ' = ''' + CONVERT(VARCHAR(5), @lStatus, 108) + ''',
			D' + CAST(@lDay AS VARCHAR) + '_S = ''' + CAST(@lShift AS VARCHAR) + '''
			WHERE EmployeeId = ' + CAST(@lSourceId AS VARCHAR) + ' AND Attn_Dt = ''' + CAST(@lMonthTransAttn_Dt AS VARCHAR) + ''' AND SourceTypeId = ' + CAST(@lSourceTypeId AS VARCHAR)

			PRINT ('Query : ' + @lQuery)

			EXEC (@lQuery)

			CREATE TABLE #tSummary (
				PresentStatus VARCHAR(10)
				,PresentStatusCount INT
				)

			INSERT INTO #tSummary
			SELECT [Status]
				,COUNT(*) AS [Count]
			FROM (
				SELECT D01
					,D02
					,D03
					,D04
					,D05
					,D06
					,D07
					,D08
					,D09
					,D10
					,D11
					,D12
					,D13
					,D14
					,D15
					,D16
					,D17
					,D18
					,D19
					,D20
					,D21
					,D22
					,D23
					,D24
					,D25
					,D26
					,D27
					,D28
					,D29
					,D30
					,D31
				FROM sBiometric.tMonthTrans WITH (NOLOCK)
				WHERE EmployeeId = @lSourceId
					AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
					AND SourceTypeId = @lSourceTypeId
				) AS TEMP
			UNPIVOT([Status] FOR [Dd] IN (
						D01
						,D02
						,D03
						,D04
						,D05
						,D06
						,D07
						,D08
						,D09
						,D10
						,D11
						,D12
						,D13
						,D14
						,D15
						,D16
						,D17
						,D18
						,D19
						,D20
						,D21
						,D22
						,D23
						,D24
						,D25
						,D26
						,D27
						,D28
						,D29
						,D30
						,D31
						)) AS [unpivoted]
			GROUP BY [Status]
			HAVING COUNT(*) > 0

			--SELECT * FROM #tSummary
			--BREAK
			DECLARE @lTotal_HalfDay INT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN ('HD')
					)
			DECLARE @lTotal_Present FLOAT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN ('P')
					) + @lTotal_HalfDay * 0.5
			DECLARE @lTotal_Absent FLOAT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN (
							'A'
							,'XX'
							,'LH'
							)
					) + @lTotal_HalfDay * 0.5
			DECLARE @lTotal_WeekOff INT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN (
							'W'
							,'PW'
							)
					)
			DECLARE @lTotal_Holiday INT = (
					SELECT ISNULL(SUM(PresentStatusCount), 0)
					FROM #tSummary
					WHERE PresentStatus IN (
							'H'
							,'PH'
							)
					)
			DECLARE @lTotal_Hours VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
						SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum
						FROM (
							SELECT D01_T
								,D02_T
								,D03_T
								,D04_T
								,D05_T
								,D06_T
								,D07_T
								,D08_T
								,D09_T
								,D10_T
								,D11_T
								,D12_T
								,D13_T
								,D14_T
								,D15_T
								,D16_T
								,D17_T
								,D18_T
								,D19_T
								,D20_T
								,D21_T
								,D22_T
								,D23_T
								,D24_T
								,D25_T
								,D26_T
								,D27_T
								,D28_T
								,D29_T
								,D30_T
								,D31_T
							FROM sBiometric.tMonthTrans WITH (NOLOCK)
							WHERE EmployeeId = @lSourceId
								AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
								AND SourceTypeId = @lSourceTypeId
							) AS TEMP
						UNPIVOT([Status] FOR [Dd] IN (
									D01_T
									,D02_T
									,D03_T
									,D04_T
									,D05_T
									,D06_T
									,D07_T
									,D08_T
									,D09_T
									,D10_T
									,D11_T
									,D12_T
									,D13_T
									,D14_T
									,D15_T
									,D16_T
									,D17_T
									,D18_T
									,D19_T
									,D20_T
									,D21_T
									,D22_T
									,D23_T
									,D24_T
									,D25_T
									,D26_T
									,D27_T
									,D28_T
									,D29_T
									,D30_T
									,D31_T
									)) AS [unpivoted]
						) t
					)
			DECLARE @lTotal_Early VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
						SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum
						FROM (
							SELECT D01_E
								,D02_E
								,D03_E
								,D04_E
								,D05_E
								,D06_E
								,D07_E
								,D08_E
								,D09_E
								,D10_E
								,D11_E
								,D12_E
								,D13_E
								,D14_E
								,D15_E
								,D16_E
								,D17_E
								,D18_E
								,D19_E
								,D20_E
								,D21_E
								,D22_E
								,D23_E
								,D24_E
								,D25_E
								,D26_E
								,D27_E
								,D28_E
								,D29_E
								,D30_E
								,D31_E
							FROM sBiometric.tMonthTrans WITH (NOLOCK)
							WHERE EmployeeId = @lSourceId
								AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
								AND SourceTypeId = @lSourceTypeId
							) AS TEMP
						UNPIVOT([Status] FOR [Dd] IN (
									D01_E
									,D02_E
									,D03_E
									,D04_E
									,D05_E
									,D06_E
									,D07_E
									,D08_E
									,D09_E
									,D10_E
									,D11_E
									,D12_E
									,D13_E
									,D14_E
									,D15_E
									,D16_E
									,D17_E
									,D18_E
									,D19_E
									,D20_E
									,D21_E
									,D22_E
									,D23_E
									,D24_E
									,D25_E
									,D26_E
									,D27_E
									,D28_E
									,D29_E
									,D30_E
									,D31_E
									)) AS [unpivoted]
						) t
					)
			DECLARE @lTotal_Late VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
						SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum
						FROM (
							SELECT D01_L
								,D02_L
								,D03_L
								,D04_L
								,D05_L
								,D06_L
								,D07_L
								,D08_L
								,D09_L
								,D10_L
								,D11_L
								,D12_L
								,D13_L
								,D14_L
								,D15_L
								,D16_L
								,D17_L
								,D18_L
								,D19_L
								,D20_L
								,D21_L
								,D22_L
								,D23_L
								,D24_L
								,D25_L
								,D26_L
								,D27_L
								,D28_L
								,D29_L
								,D30_L
								,D31_L
							FROM sBiometric.tMonthTrans WITH (NOLOCK)
							WHERE EmployeeId = @lSourceId
								AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
								AND SourceTypeId = @lSourceTypeId
							) AS TEMP
						UNPIVOT([Status] FOR [Dd] IN (
									D01_L
									,D02_L
									,D03_L
									,D04_L
									,D05_L
									,D06_L
									,D07_L
									,D08_L
									,D09_L
									,D10_L
									,D11_L
									,D12_L
									,D13_L
									,D14_L
									,D15_L
									,D16_L
									,D17_L
									,D18_L
									,D19_L
									,D20_L
									,D21_L
									,D22_L
									,D23_L
									,D24_L
									,D25_L
									,D26_L
									,D27_L
									,D28_L
									,D29_L
									,D30_L
									,D31_L
									)) AS [unpivoted]
						) t
					)
			DECLARE @lTotal_OverTime VARCHAR(50) = (
					SELECT CAST(t.time_sum / 3600 AS VARCHAR(10)) + ':' + CAST(t.time_sum % 3600 / 60 AS VARCHAR(10))
					FROM (
						SELECT SUM(DATEDIFF(S, '00:00', [Status])) AS time_sum
						FROM (
							SELECT D01_O
								,D02_O
								,D03_O
								,D04_O
								,D05_O
								,D06_O
								,D07_O
								,D08_O
								,D09_O
								,D10_O
								,D11_O
								,D12_O
								,D13_O
								,D14_O
								,D15_O
								,D16_O
								,D17_O
								,D18_O
								,D19_O
								,D20_O
								,D21_O
								,D22_O
								,D23_O
								,D24_O
								,D25_O
								,D26_O
								,D27_O
								,D28_O
								,D29_O
								,D30_O
								,D31_O
							FROM sBiometric.tMonthTrans WITH (NOLOCK)
							WHERE EmployeeId = @lSourceId
								AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
								AND SourceTypeId = @lSourceTypeId
							) AS TEMP
						UNPIVOT([Status] FOR [Dd] IN (
									D01_O
									,D02_O
									,D03_O
									,D04_O
									,D05_O
									,D06_O
									,D07_O
									,D08_O
									,D09_O
									,D10_O
									,D11_O
									,D12_O
									,D13_O
									,D14_O
									,D15_O
									,D16_O
									,D17_O
									,D18_O
									,D19_O
									,D20_O
									,D21_O
									,D22_O
									,D23_O
									,D24_O
									,D25_O
									,D26_O
									,D27_O
									,D28_O
									,D29_O
									,D30_O
									,D31_O
									)) AS [unpivoted]
						) t
					)

			UPDATE sBiometric.tMonthTrans WITH (ROWLOCK)
			SET [Tot_Attn] = @lTotal_Present
				,[Tot_Abs] = @lTotal_Absent
				,[Tot_WeekOFF] = @lTotal_WeekOff
				,[Tot_Holiday] = @lTotal_Holiday
				,[TotalHour] = @lTotal_Hours
				,[Tot_HD] = @lTotal_HalfDay
				,[Tot_Early] = @lTotal_Early
				,[Tot_Late] = @lTotal_Late
				,[Tot_OT] = @lTotal_OverTime
			WHERE EmployeeId = @lSourceId
				AND CAST(Attn_Dt AS DATE) = @lMonthTransAttn_Dt
				AND SourceTypeId = @lSourceTypeId

			UPDATE sBiometric.tCloudTransactionData WITH (ROWLOCK)
			SET IsProcessed = 1
			WHERE TransactionId = @lTransactionId

			DROP TABLE #tSummary
		END

		SET @lPrevAttn_Dt = @lAttn_Dt
		SET @lPrevSourceId = @lSourceId
		SET @lPrevSourceTypeId = @lSourceTypeId
		SET @lCount = @lCount + 1
	END

	--add for mantis: 10346, start
	INSERT INTO sAudit.tActivityLog WITH (ROWLOCK)
	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-MonthTrans' AS Activity
			,0 AS RecordSourceId
			,'' AS RecordDetail
			,3 AS OSTypeId
		FROM sBiometric.tMonthTrans MT WITH (NOLOCK)
		INNER JOIN #tTable t ON t.SourceId = MT.EmployeeId
		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 MT.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-MonthTrans' AS Activity
			,0 AS RecordSourceId
			,'' AS RecordDetail
			,3 AS OSTypeId
		FROM sBiometric.tMonthTrans MT WITH (NOLOCK)
		INNER JOIN #tTable t ON t.SourceId = MT.EmployeeId
		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 MT.SourceTypeId = 2001
		) d

	--add for mantis: 10346, end
	--Drop temp table for server issue(tempdb)
	DROP TABLE #tTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pNewTimeSheetListGet]
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rEmployeeName nvarchar(50) = '',
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN  

CREATE TABLE #TempNewMonthTrans
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25)  
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lBatchID int
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)

		SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1

 INSERT INTO #TempNewMonthTrans  
   
	SELECT	EM.Id as EmployeeId,
			--MT.EmployeeId,
			isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(Mt.attn_dt) *100+ 01) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)),
			D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		--AND EJD.DateOfJoining<=cast(rtrim(YEAR('2024-01-01 00:00:00') *10000+ Month('2024-01-01 00:00:00') *100+ 01) as datetime) 
		AND (EJD.DateOfJoining<= @Lastdate)
		--AND (ejd.dateofleaving>=cast(rtrim(YEAR('2024-01-01 00:00:00') *10000+ Month('2024-01-01 00:00:00') *100+ 01) as datetime) or ejd.dateofleaving is null)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
		--AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 1
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 02) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 02) as datetime)),
	D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId 
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) 
		--AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 2
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 03) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 03) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 03) as datetime)),
	D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 3
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 04) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 04) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 04) as datetime)),
	D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 4
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 05) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 05) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 05) as datetime)),
	D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	--	(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 5
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 06) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 06) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 06) as datetime)),
	D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	--	(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 6
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 07) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 07) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 07) as datetime)),
	D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	--	(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 7
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 08) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 08) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 08) as datetime)),
	D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	--	(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 8
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 09) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 09) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 09) as datetime)),
	D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 9
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 10) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 10) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 10) as datetime)),
	D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 10

	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 11) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 11) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 11) as datetime)),
	D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 11

	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 12) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 12) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 12) as datetime)),
	D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 12
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 13) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 13) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 13) as datetime)),
	D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 13
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 14) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 14) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 14) as datetime)),
	D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 14
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 15) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 15) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 15) as datetime)),
	D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 15
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 16) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 16) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 16) as datetime)),
	D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 16
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 17) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 17) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 17) as datetime)),
	D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 17
	UNION ALL

	SELECT EM.Id as EmployeeId,
	-- MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 18) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 18) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 18) as datetime)),
	D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 18
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 19) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 19) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 19) as datetime)),
	D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 19
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 20) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 20) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 20) as datetime)),
	D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 20
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 21) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 21) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 21) as datetime)),
	D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 21
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 22) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 22) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 22) as datetime)),
	D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 22
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 23) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 23) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 23) as datetime)),
	D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 23
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 24) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 24) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 24) as datetime)),
	D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 24
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 25) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 25) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 25) as datetime)),
	D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 25
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 26) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 26) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 26) as datetime)),
	D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 26
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 27) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 27) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 27) as datetime)),
	D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 27
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 28) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 28) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 28) as datetime)),
	D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 28

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempNewMonthTrans
		SELECT EM.Id as EmployeeId, 
		--MT.EmployeeId,
		--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 29) as datetime),
		isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 29) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 29) as datetime)),
		D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 29
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempNewMonthTrans
	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 30) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 30) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 30) as datetime)),
	D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 30
	END
	--Mantis Id:28837 Start to check from amd to date month contain 31 days
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempNewMonthTrans
	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 31) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 31) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 31) as datetime)),
	D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_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(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 31
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	END

	IF NOT EXISTS (SELECT * FROM #TempNewMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND Attn_Date=@rToDate)	--Mantis Id 30042, only "if" condition will be added
	BEGIN
		IF Month(@rToDate) NOT IN (2,4,6,9,11)
		BEGIN
		INSERT INTO #TempNewMonthTrans
		SELECT EM.Id as EmployeeId, 
		--MT.EmployeeId,
		--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 31) as datetime),
		isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 31) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 31) as datetime)),
		D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_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(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 31
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND  MT.ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		END
	END

--select * from #TempNewMonthTrans

SELECT TM.Id,TM.EmployeeId,TM.Attn_Date,isnull(TM.PresentStatus,'XX') AS OldPresentStatus,OGD.Title AS [Organization Group Department],
 
 isnull(CASE 
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='PW')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW'
  When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(EJD.DateOfJoining as date)<= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfJoining,'')='')AND (EJD.DateOfleaving>= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfleaving,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
 ELSE
 TM.PresentStatus END,'A') as PresentStatus,

 isnull(TM.FirstIn,'00:00') as FirstIn ,isnull(TM.LastOut,'00:00') as LastOut,isnull(TM.OverTime,'00:00') as OverTime,isnull(TM.LateBy,'00:00') as LateBy, isnull(TM.Duration,'00:00') as Duration,isnull(TM.EarlyBy,'00:00') as EarlyBy,isnull(TM.ShiftName,'') as ShiftName, MT.Tot_Attn,
 MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,  
 Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode ,   
 [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,   
 [sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus,   
 [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,  
 ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
 ISNULL(SM.Id,0) AS StatusId,  
 ISNULL(SM.Title,'') AS Status  
 FROM #TempNewMonthTrans TM   
 LEFT JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId  
 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId
 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01') or TM.ATTN_DATE is null)
 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
 WHERE   
 ((TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate) or TM.ATTN_DATE is null)
 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --Change for mantis: 39830, comment this condition and make the new condition
 --AND (( @rStatus = '1' AND (TM.Duration < '09:30')) OR ( @rStatus != '1' AND ((PresentStatus = @rStatus OR @rStatus='0'))))
 AND (( @rStatus = '1' AND (TM.Duration < '09:30')) OR (@rStatus != '1' AND (isnull(CASE 
	 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
	 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
	 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
	 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
	 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
	 When ((TM.PresentStatus='PW')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
	 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
	 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW'
	  When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(EJD.DateOfJoining as date)<= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfJoining,'')='')AND (EJD.DateOfleaving>= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfleaving,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
	 ELSE
	 TM.PresentStatus END,'A') = @rStatus OR @rStatus='0')))
 AND EM.OrgId = @rOrgId 
 AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
 AND (EM.FirstName + ' ' + EM.LastName like '%' + @rEmployeeName + '%' or @rEmployeeName = '')
 AND  ISNULL(EM.IsOtherUser,0) = 0
 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
 Order By TM.EmployeeId,TM.Attn_Date


 
 --Drop table #TempNewMonthTrans

 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

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


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

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

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

END


--[sActivity].[tWeekOffSetting]

--[sCommon].[tWeekOffRules]

--[sHrm].[fEmployeeHolidayGet]

--SELECT ROUTINE_NAME, ROUTINE_TYPE, SPECIFIC_NAME
--FROM INFORMATION_SCHEMA.ROUTINES
--WHERE ROUTINE_DEFINITION LIKE '%fEmployeeHolidayGet%'

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptBiometricReportDataDateWiseWithWeekOffLeaveGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rIsFirstIn bit=0,
	 @rIsLastOut bit=0,
	 @rIsOT bit=0,
	 @rIsLateBy	bit=0,
	 @rIsEarlyBy bit=0,
	 @rIsDuration  bit=0,
	 @rGradeId nvarchar(200) = '0',
	 @rEmployeeStatusId int=0,
	 @rOrgGroupId int = 0,
	 @OrgGroupDepartmentId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

DECLARE @TableEmployee TABLE (Id int Identity,EmployeeID BigINT, OrganizationDepartmentId int, EmployeeTypeId Int)
INSERT INTO @TableEmployee
SELECT EM.Id AS EmployeeId,ED.OrganizationDepartmentId,ED.EmployeeTypeId from shrm.tEmployeeMaster EM 
INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id 
Where (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )
AND (ED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0 )
AND  (EM.ORgId = @rOrgId OR @rOrgId = 0)
AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 
AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 


DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lBatchID int
DECLARE @lEmployeeId bigint
DECLARE @lEmpCount int
DECLARE @lEmpDepartmentID int

DECLARE @TempDate TABLE(Id int identity,Idate date)
insert into @TempDate
SELECT  TOP (DATEDIFF(DAY, @rFromDate, @rToDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @rFromDate)
FROM    sys.all_objects a CROSS JOIN sys.all_objects b;

CREATE TABLE #TempMonthTrans (Id int Identity,EmployeeId bigint,Attn_Date DateTime,DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20),Shift nvarchar(25))

truncate table #TempMonthTrans

SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

Select @lCount = Max(Id) from @TempDate
Select @lEmpCount = Max(Id) from @TableEmployee
While (@lEmpCount > 0)
	BEGIN
		SELECT @lEmployeeId = EmployeeId,@lEmpDepartmentID = OrganizationDepartmentId  From @TableEmployee Where Id = @lEmpCount	
	set @lCount1 = 1
	while (@lCount1 <= @lCount)
	begin			
		Select @lDate = Idate from @TempDate Where Id = @lCount1
		Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

		DECLARE @weekoffstatus nvarchar(20)

		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)
		PRINT(@weekoffstatus)

		DECLARE @lLeaveOnWeekOff nvarchar(50)=''
		SELECT @lLeaveOnWeekOff=LTM.Code + '/' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
		FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
		WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate

		set @lQuery =  'INSERT INTO #TempMonthTrans
						SELECT  ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
						CAse 
						When ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' in (''W'') AND '''+@lLeaveOnWeekOff+'''<>'''' Then ''' +@lLeaveOnWeekOff +'''
						When ''' +@weekoffstatus +''' in (''H'') AND '''+@lLeaveOnWeekOff+'''<>'''' Then ''' +@lLeaveOnWeekOff +''' --mantis: 41397
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') Then ''' +@weekoffstatus +''' 
						When D'+ convert(nvarchar(15),@lDay) +' =''XX'' AND  (Cast(''' + convert(nvarchar(15),@lDate) + ''' as date)<GETDATE()) And (cast(ED.DateOfJoining as date)<= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfJoining,'''')='''')AND (ED.DateOfleaving>= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfleaving,'''')='''')  then ''A''
						Else D'+convert(nvarchar(15),@lDay)+' End AS D'+convert(nvarchar(15),@lDay)+',D'+convert(nvarchar(15),@lDay)+'_IN,D'+convert(nvarchar(15),@lDay)+'_OUT,D'+convert(nvarchar(15),@lDay)+'_O,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T,D'+convert(nvarchar(15),@lDay)+'_E,D'+convert(nvarchar(15),@lDay)+'_S 
						FROM sBiometric.tMonthTrans T1 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 ) AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 0 )
						WHERE T1.EmployeeId =' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) AND (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				
						
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END

	--SELECT * FROM #TempMonthTrans
	
	SET @strQuery = 'select Day(T.Attn_Date) AS Attn_Day, T.*,isnull(A.TotAbsent,0) AS TotAbsent,isnull(TotPresent,0) AS TotPresent,isnull(A1.TotWeekOff,0) AS TotWeekOff,
	isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,isnull(CLLeave,0) AS CLLeave,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,isnull(TotEarly,0) AS TotEarly,
	DM.Displaytitle AS DeptName,
	' + convert(nvarchar(10),@rIsFirstIn) + ' AS IsFirstIn,
	' + convert(nvarchar(10),@rIsLastOut) + ' AS IsLastOut,
	' +  convert(nvarchar(10),@rIsOT) + ' AS IsOT,
	' +  convert(nvarchar(10),@rIsLateBy) + '	AS IsLateBy,
	' +  convert(nvarchar(10),@rIsEarlyBy) + ' AS IsEarlyBy,
	' +  convert(nvarchar(10),@rIsDuration) + '  AS IsDuration,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID 
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN (''P'',''PW'',''PH'') group by EmployeeId,PresentStatus) A4 ON A4.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotEarly,EmployeeId from #TempMonthTrans Where PresentStatus IN (''E'') group by EmployeeId,PresentStatus) A6 ON A6.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like ''A'' group by EmployeeId,PresentStatus) A ON A.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN (''W'',''PW'',''PHW'') group by EmployeeId) A1 ON A1.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId,PresentStatus) A3 ON A3.EmployeeId = T.employeeID
    LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId,PresentStatus) A5 ON A5.EmployeeId = T.employeeID		
	
	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId 
	WHERE  (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
	AND (Emp.OrgId = ' + convert(nvarchar(15),@rOrgId) + ' OR ' + convert(nvarchar(15),@rOrgId) + ' = 0)
	AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') AND (len((''' + @rGRadeId + '''))= 1 AND EmployeeGradeId > 0 ) Or
   (len((''' + @rGRadeId + ''')) > 1 AND EmployeeGradeId in(' + convert(nvarchar(100),@rGRadeId) + ')) Order By T.EmployeeId,T.Attn_Date'
	
	execute (@strQuery)
	
	DROP TABLE #TempMonthTrans

	--select  
	--'' as Builder1,
	--'' as Builder2,
	--0 as Attn_Day,
	--CONVERT(bigint,0) as EmployeeId,
	--CONVERT(datetime,'') as Attn_Date,
	--'' as DayNumber ,
	--'' as PresentStatus ,
	--'' as FirstIn,
	--'' as LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as Shift,
	--0 as TotAbsent,
	--0 as TotPresent,
	--0 as TotWeekOff,
	--0 as TotHalfDay,
	--0 as TotHoliday,
	--0 as CLLeave,
	--'' as LeaveCode,
	--'' as LeaveCode1,
	--'' as EmpCode,
	--'' as EmpName,
	--0 AS TotEarly,	
	--'' as DeptName,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--0 as OrgId,
	--'' as OrganizationTitle
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptDateWiseTimeSheetSummary]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rIsFirstIn bit=0,
	 @rIsLastOut bit=0,
	 @rIsOT bit=0,
	 @rIsLateBy	bit=0,
	 @rIsEarlyBy bit=0,
	 @rIsDuration  bit=0,
	 @rGradeId nvarchar(200) = '0',
	 @rEmployeeStatusId int=0,
	 @rOrgGroupId int = 0,
	 @OrgGroupDepartmentId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

DECLARE @TableEmployee TABLE (Id int Identity,EmployeeID BigINT, OrganizationDepartmentId int, EmployeeTypeId Int)
INSERT INTO @TableEmployee
SELECT EM.Id AS EmployeeId,ED.OrganizationDepartmentId,ED.EmployeeTypeId from shrm.tEmployeeMaster EM 
INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id 
Where (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )
AND (ED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0 )
AND  EM.ORgId = @rOrgId 
AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 
AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 



DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lBatchID int
DECLARE @lEmployeeId bigint
DECLARE @lEmpCount int
DECLARE @lEmpDepartmentID int

DECLARE @TempDate TABLE(Id int identity,Idate date)
insert into @TempDate
SELECT  TOP (DATEDIFF(DAY, @rFromDate, @rToDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @rFromDate)
FROM    sys.all_objects a CROSS JOIN sys.all_objects b;

CREATE TABLE #TempMonthTrans (Id int Identity,EmployeeId bigint,Attn_Date DateTime,Leave nvarchar(100),DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20))

truncate table #TempMonthTrans

SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

Select @lCount = Max(Id) from @TempDate
Select @lEmpCount = Max(Id) from @TableEmployee
While (@lEmpCount > 0)
	BEGIN
		SELECT @lEmployeeId = EmployeeId,@lEmpDepartmentID = OrganizationDepartmentId  From @TableEmployee Where Id = @lEmpCount	
	set @lCount1 = 1
	while (@lCount1 <= @lCount)
	begin			
		Select @lDate = Idate from @TempDate Where Id = @lCount1
		Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

		DECLARE @weekoffstatus nvarchar(20)

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@rEmployeeId , @rForYear ,@rForMonth ,@rDay ,@rBatchId ,@rDepartmentId ,@rOrgId , @rBiometricStatus )
		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)		
		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(''' + convert(nvarchar(15),@lDate) + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',ED.OrganizationDepartmentId,' + convert(nvarchar(15),@rOrgId) + ')

		set @lQuery =  ' INSERT INTO #TempMonthTrans
						SELECT  ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						'''+''+''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
						CAse 
						When ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' in (''H'') AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' then ''PH''
						When ''' +@weekoffstatus +''' in (''W'')  AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' then ''PW''
						When ''' +@weekoffstatus +''' in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''PW'' AND D'+convert(nvarchar(15),@lDay)+'_IN = ''00:00'' then ''W''
						When ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''PW'' then ''P''
						When ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''W'' AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' then ''P''
						When ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' =''W'' AND D'+convert(nvarchar(15),@lDay)+'_IN = ''00:00'' then ''A''
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						When D'+ convert(nvarchar(15),@lDay) +' =''XX'' AND  (Cast(''' + convert(nvarchar(15),@lDate) + ''' as date)<GETDATE()) And (cast(ED.DateOfJoining as date)<= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfJoining,'''')='''')AND (ED.DateOfleaving>= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfleaving,'''')='''')  then ''A''
						Else D'+convert(nvarchar(15),@lDay)+' End D'+convert(nvarchar(15),@lDay)+',D'+convert(nvarchar(15),@lDay)+'_IN,D'+convert(nvarchar(15),@lDay)+'_OUT,D'+convert(nvarchar(15),@lDay)+'_O,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T,D'+convert(nvarchar(15),@lDay)+'_E 
						FROM sBiometric.tMonthTrans T1 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 0 )
						WHERE T1.EmployeeId =' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) AND (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				
		--print @lQuery				
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END
	--Select * from #TempMonthTrans
	
	UPDATE tmp 
	SET PresentStatus='A'
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate

	UPDATE tmp 
	SET Leave=LTM.Code + '/' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate


	--Select * from #TempMonthTrans

	--add builders in this for 27928 mantis
	SET @strQuery = 'select '''+@rBuilder1+''' AS Builder1, '''+@rBuilder2+''' AS Builder2, Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,isnull(TotPresent,0) AS TotPresent,A1.TotWeekOff,isnull(A6.TotEarly,0) as TotEarly,
	isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,isnull(CLLeave,0) AS CLLeave,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,isnull(TotEarly,0) AS TotEarly,
	DM.Displaytitle DeptName,
	' + convert(nvarchar(10),@rIsFirstIn) + ' AS IsFirstIn,
	' + convert(nvarchar(10),@rIsLastOut) + ' AS IsLastOut,
	' +  convert(nvarchar(10),@rIsOT) + ' AS IsOT,
	' +  convert(nvarchar(10),@rIsLateBy) + '	AS IsLateBy,
	' +  convert(nvarchar(10),@rIsEarlyBy) + ' AS IsEarlyBy,
	' +  convert(nvarchar(10),@rIsDuration) + '  AS IsDuration,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN (''P'',''PW'',''PH'') group by EmployeeId,PresentStatus) A4 ON A4.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotEarly,EmployeeId from #TempMonthTrans Where PresentStatus IN (''E'') group by EmployeeId,PresentStatus) A6 ON A6.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like ''A'' group by EmployeeId,PresentStatus) A ON A.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN (''W'',''PW'',''PHW'') group by EmployeeId) A1 ON A1.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId,PresentStatus) A3 ON A3.EmployeeId = T.employeeID
    LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId,PresentStatus) A5 ON A5.EmployeeId = T.employeeID		
	
	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId 
	WHERE (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0) AND (len((''' + @rGRadeId + '''))= 1 AND EmployeeGradeId > 0 ) Or
   (len((''' + @rGRadeId + ''')) > 1 AND EmployeeGradeId in(' + convert(nvarchar(100),@rGRadeId) + ')) AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') Order By T.EmployeeId,T.Attn_Date' 
	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	--print @strQuery
	execute (@strQuery)
	
	DROP TABLE #TempMonthTrans
	--select  
	--@rBuilder1 as Builder1,
	--@rBuilder2 as Builder2,
	--'' as Attn_Date,
	--'' as Leave,
	--'' as EmployeeId,	
	--'' as DayNumber ,
	--'' as PresentStatus ,
	--'' as FirstIn,
	--'' as LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as TotPresent,
	--'' as TotWeekOff,
	--'' as TotHalfDay,
	--'' as TotHoliday,
	--'' AS TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrgId,
	--'' as OrganizationTitle
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptDateWiseTimeSheetSummaryWithBiometricTypeMaster]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rIsFirstIn bit=0,
	 @rIsLastOut bit=0,
	 @rIsOT bit=0,
	 @rIsLateBy	bit=0,
	 @rIsEarlyBy bit=0,
	 @rIsDuration  bit=0,
	 @rGradeId nvarchar(200) = '0',
	 @rEmployeeStatusId int=0,
	 @rOrgGroupId int = 0,
	 @OrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @TableEmployee TABLE (Id int Identity,EmployeeID BigINT, OrganizationDepartmentId int, EmployeeTypeId Int)
	INSERT INTO @TableEmployee
	SELECT EM.Id AS EmployeeId,ED.OrganizationDepartmentId,ED.EmployeeTypeId
	FROM shrm.tEmployeeMaster EM
		INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id
	WHERE (ED.OrganizationDepartmentId = @rOrganizationDepartmentId OR @rOrganizationDepartmentId = 0)
		AND (ED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
		AND EM.ORgId = @rOrgId
		AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
		AND ISNULL(EM.IsOtherUser,0) = 0
		AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId = 0))



	DECLARE @lCount int
	DECLARE @lCount1 int
	Declare @lQuery nvarchar(Max)
	DECLARE @strQuery nvarchar(Max)
	DECLARE @lDate date
	DECLARE @lDay as nvarchar(3)
	DECLARE @lBatchID int
	DECLARE @lEmployeeId bigint
	DECLARE @lEmpCount int
	DECLARE @lEmpDepartmentID int

	DECLARE @TempDate TABLE(Id int identity,Idate date)
	INSERT INTO @TempDate
	SELECT	TOP (DATEDIFF(DAY, @rFromDate, @rToDate) + 1)
			Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @rFromDate)
	FROM sys.all_objects a CROSS JOIN sys.all_objects b;

	CREATE TABLE #TempMonthTrans (Id int Identity,EmployeeId bigint,Attn_Date DateTime,Leave nvarchar(100),DayNumber nvarchar(8),PresentStatus nvarchar(25),
			FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20))

	TRUNCATE TABLE #TempMonthTrans

	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1

	SELECT @lCount = Max(Id) FROM @TempDate
	SELECT @lEmpCount = Max(Id) FROM @TableEmployee
	WHILE (@lEmpCount > 0)
	BEGIN
		SELECT @lEmployeeId = EmployeeId,@lEmpDepartmentID = OrganizationDepartmentId FROM @TableEmployee WHERE Id = @lEmpCount
		SET @lCount1 = 1
		WHILE (@lCount1 <= @lCount)
		BEGIN
			SELECT @lDate = Idate FROM @TempDate WHERE Id = @lCount1
			SELECT @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

			DECLARE @weekoffstatus nvarchar(20)

			SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId, Year(@lDate), Month(@lDate), @lDay, @lBatchId, @lEmpDepartmentID, @rOrgId)

			SET @lQuery =  ' INSERT INTO #TempMonthTrans
							SELECT  ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
							'''+''+''',
							substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
							CASE 
							WHEN ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' THEN D'+convert(nvarchar(15),@lDay) +'
							WHEN ''' +@weekoffstatus +''' in (''H'') AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' THEN ''PH''
							WHEN ''' +@weekoffstatus +''' in (''W'')  AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' THEN ''PW''
							WHEN ''' +@weekoffstatus +''' in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''PW'' AND D'+convert(nvarchar(15),@lDay)+'_IN = ''00:00'' THEN ''W''
							WHEN ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''PW'' THEN ''P''
							WHEN ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' = ''W'' AND D'+convert(nvarchar(15),@lDay)+'_IN != ''00:00'' THEN ''P''
							WHEN ''' +@weekoffstatus +''' not in (''W'') AND D'+ convert(nvarchar(15),@lDay) +' =''W'' AND D'+convert(nvarchar(15),@lDay)+'_IN = ''00:00'' THEN ''A''
							WHEN ''' +@weekoffstatus +''' Not in (''-'',''XX'') THEN ''' +@weekoffstatus +''' 
							WHEN D'+ convert(nvarchar(15),@lDay) +' = ''XX'' AND (Cast(''' + convert(nvarchar(15),@lDate) + ''' as date)<GETDATE()) AND (cast(ED.DateOfJoining as date)<= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfJoining,'''')='''') AND (ED.DateOfleaving>= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfleaving,'''')='''') THEN ''A''
							ELSE D'+convert(nvarchar(15),@lDay)+' END D'+convert(nvarchar(15),@lDay)+',
							D'+convert(nvarchar(15),@lDay)+'_IN, D'+convert(nvarchar(15),@lDay)+'_OUT, D'+convert(nvarchar(15),@lDay)+'_O, D'+convert(nvarchar(15),@lDay)+'_L, D'+convert(nvarchar(15),@lDay)+'_T, D'+convert(nvarchar(15),@lDay)+'_E
							FROM sBiometric.tMonthTrans T1 
							INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' OR '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0) AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' OR '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 0)
							WHERE T1.EmployeeId = ' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) AND (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'
			--print @lQuery
			EXECUTE(@lQuery)
			SET @lCount1 = @lCount1 + 1
		END

		SET @lEmpCount = @lEmpCount - 1
	END
	--Select * from #TempMonthTrans

	UPDATE tmp
	SET PresentStatus='A'
	FROM #TempMonthTrans tmp
		INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
		INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate

	UPDATE tmp
	SET Leave=LTM.Code + '/' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate

	DECLARE @lStatus nvarchar(max);
	SELECT @lStatus=MainStatusId FROM sBiometric.tBiometricTypeMaster WHERE STATUS='PH'
	IF(@lStatus=1 or @lStatus=0)
	BEGIN
		UPDATE #TempMonthTrans SET PresentStatus='PH' WHERE PresentStatus IN ('PW','PHW')
	END
	UPDATE #TempMonthTrans SET PresentStatus='P' WHERE PresentStatus IN (SELECT Status FROM sBiometric.tBiometricTypeMaster WHERE MainStatusId=1)
	UPDATE #TempMonthTrans SET PresentStatus='A' WHERE PresentStatus IN (SELECT Status FROM sBiometric.tBiometricTypeMaster WHERE MainStatusId=0)

	--Select * from #TempMonthTrans

	SET @strQuery = 'SELECT '''+@rBuilder1+''' AS Builder1, '''+@rBuilder2+''' AS Builder2, Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,isnull(TotPresent,0) AS TotPresent,ISNULL(A1.TotWeekOff,0) AS TotWeekOff,isnull(A6.TotEarly,0) as TotEarly,
	isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,ISNULL(TotPresentOnWeekOffHoliday,0) AS TotPresentOnWeekOffHoliday,ISNULL(TotLessHours,0) AS TotLessHours,isnull(CLLeave,0) AS CLLeave,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,DM.Displaytitle DeptName,
	' + convert(nvarchar(10),@rIsFirstIn) + ' AS IsFirstIn,
	' + convert(nvarchar(10),@rIsLastOut) + ' AS IsLastOut,
	' +  convert(nvarchar(10),@rIsOT) + ' AS IsOT,
	' +  convert(nvarchar(10),@rIsLateBy) + '	AS IsLateBy,
	' +  convert(nvarchar(10),@rIsEarlyBy) + ' AS IsEarlyBy,
	' +  convert(nvarchar(10),@rIsDuration) + '  AS IsDuration,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN (''P'') group by EmployeeId,PresentStatus) A4 ON A4.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotEarly,EmployeeId from #TempMonthTrans Where PresentStatus IN (''E'') group by EmployeeId,PresentStatus) A6 ON A6.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like ''A'' group by EmployeeId,PresentStatus) A ON A.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN (''W'') group by EmployeeId) A1 ON A1.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId,PresentStatus) A3 ON A3.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId,PresentStatus) A5 ON A5.EmployeeId = T.employeeID
	LEFT JOIN (Select COUNT(*) AS TotPresentOnWeekOffHoliday,EmployeeId from #TempMonthTrans Where PresentStatus IN (''PHW'',''PH'',''PW'') group by EmployeeId) A7 ON A7.EmployeeId = T.employeeID
	LEFT JOIN (Select COUNT(*) AS TotLessHours,EmployeeId from #TempMonthTrans Where PresentStatus Like ''LH'' group by EmployeeId,PresentStatus) A8 ON A8.EmployeeId = T.employeeID

	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	LEFT Join (select distinct EmployeeId,
	ISNULL(stuff((
		select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave))
		from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
		where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')=''''))
		AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')=''''))
		AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
		group by LT.Code
		for xml path('''')
	),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId
	WHERE (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0) AND (len((''' + @rGRadeId + '''))= 1 AND EmployeeGradeId > 0 ) Or
	(len((''' + @rGRadeId + ''')) > 1 AND EmployeeGradeId in(' + convert(nvarchar(100),@rGRadeId) + ')) AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') Order By T.EmployeeId,T.Attn_Date'
	--print @strQuery
	execute (@strQuery)

	DROP TABLE #TempMonthTrans
	--select
	--@rBuilder1 as Builder1,
	--@rBuilder2 as Builder2,
	--convert(date,'') as Attn_Date,
	--'' as Leave,
	--'' as EmployeeId,
	--'' as DayNumber,
	--'' as PresentStatus,
	--'' as FirstIn,
	--'' as LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as TotPresent,
	--'' as TotWeekOff,
	--'' as TotHalfDay,
	--'' as TotHoliday,
	--'' AS TotEarly,
	--'' AS TotPresentOnWeekOffHoliday,
	--'' AS TotLessHours,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrgId,
	--'' as OrganizationTitle
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pRptEmployeeCheckInGet]    
      
   @rOrgId int ,    
   @rBuilder1 nvarchar(max)='',    
   @rBuilder2 nvarchar(max)='',    
   @rdate date='',
   @rEmployeeStatusId int=0,
   @rEmployeeId bigint = 0,
   @rOrgGroupId int = 0    
       
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN     
  Select     
   convert(binary,null,0) as EmployeePhoto ,    
   EMp.FirstName+' ' +EMp.MiddleName+' '+emp.LastName AS Name,    
   case B.CheckInTime when null then null when '' then null else B.CheckInTime end as CheckInTime,
   Emp.id As EmployeeID ,
   case B.CheckOutTime when null then null when '' then null else B.CheckOutTime end as CheckOutTime,   
   B.SourceId,    
   @rBuilder1 AS Builder1,    
   @rBuilder2 AS Builder2,
   OM.Id AS OrgId,
   OM.Title AS OrganizationTitle      
  from     
   sHrm.tEmployeeMaster EMP      
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EMP.OrgId
   --LEFT JOIN sBiometric.tEmployeeCheckIn B ON B.EmployeeID=EMP.Id    
   --and EMp.OrgId=@rORgId  ANd @rDate=convert(date,B.CheckInTime)    
   LEFT JOIN sBiometric.tProcess B ON B.SourceId=EMP.Id
   ANd @rDate=convert(date,B.AtdDate)
   WHERE (Emp.Id = @rEmployeeId OR @rEmployeeId = 0) AND (EMp.OrgId=@rORgId OR @rORgId = 0)
   AND OM.OrgGroupId = @rOrgGroupId AND(EMP.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)  AND  ISNULL(EMP.IsOtherUser,0) = 0     
   
    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptEmployeeMissigPunchIdGet]
 @rOrgId int,
 @rBuilder1 nvarchar(max)='',
 @rBuilder2 nvarchar(max)='',
 @rOrgGroupId int

 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
Begin
	select 
			@rBuilder1 as Builder1,
			@rBuilder2 as Builder2,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
			PunchId AS PunchID,
			EM.Id as EmployeeId,
			EM.Code AS EmployeeCode, 
			OM.Id AS OrganizationId,
			OM.DisplayTitle AS OrganizationTitle,
			OM.OrderIndex AS OrganizationOrderIndex,
			EM.Number AS EmployeeNumber,
			EM.OrgId as OrgId ,
			DM.Displaytitle AS DeptName,
			DM.Id As DeptId
		from sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		where
			OM.OrgGroupId=@rOrgGroupId
			AND (EM.OrgId=@rOrgId OR @rOrgId=0)
			AND EM.StatusId =  7
			AND EM.PunchId is null 
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptEmployeeTimesheetInOutListGet]
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rOrgId int,
		@rDepartmentId int,
		@rOrgGroupDepartmentId int,
		@rForYear int,
		@rForMonth int,
		@rEmployeeStatusId int,
		@rEmployeeId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int=0, @lFirstDate date='', @lLasteDate date='', @Query nvarchar(max)='', @lDay nvarchar(2)=''
	--SET @lFirstDate = DATEFROMPARTS(@rForYear, @rForMonth, 1)
	--SET @lLasteDate = EOMONTH(DATEFROMPARTS(@rForYear, @rForMonth, 1))
	--SET @lCount = DAY(EOMONTH(DATEFROMPARTS(@rForYear, @rForMonth, 1)))

	SET @lFirstDate = CONVERT(date, (CONVERT(varchar(4),@rForYear) + '-' + RIGHT('0' + CONVERT(varchar(2),@rForMonth), 2) + '-01'))
	SET @lLasteDate = DATEADD(DAY,-1,DATEADD(MONTH, 1,@lFirstDate))
	SET @lCount = DAY(@lLasteDate)

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

	CREATE TABLE #tmpBiometricData
	(
		EmployeeId bigint,
		EmployeeCode nvarchar(max),
		EmployeeName nvarchar(max),
		Attn_Date DateTime,
		PresentStatus nvarchar(15),
		FirstIn nvarchar(20),
		LastOut nvarchar(20),
		OverTime nvarchar(20),
		LateBy nvarchar(20),
		Duration nvarchar(20),
		EarlyBy nvarchar(20),
		ShiftName nvarchar(25),
		EmployeeDesignationId int,
		OrganizationDepartmentId int,
		OrgGroupDepartmentID int
	)

	WHILE (@lCount>0)
	BEGIN
		--SET @lDay = format(@lCount,'00')
		SET @lDay = RIGHT('0' + CONVERT(varchar(2),@lCount), 2)

		SET @Query = 
		'INSERT INTO #tmpBiometricData
		SELECT EM.Id AS EmployeeId, EM.Code AS EmployeeCode, ISNULL(EM.FirstName,'''') + '' '' + ISNULL(EM.MiddleName,'''') + '' '' + ISNULL(EM.LastName,'''') AS EmployeeName,
			ISNULL(CAST(RTRIM(YEAR(MT.Attn_Dt) *10000+ MONTH(MT.Attn_Dt) *100+ '+CONVERT(nvarchar(2),@lDay)+') AS datetime),CAST(RTRIM('+CONVERT(nvarchar(4),@rForYear)+' *10000+ '+CONVERT(nvarchar(2),@rForMonth)+' *100+ '+CONVERT(nvarchar(2),@lDay)+') AS datetime)) AS Attn_Date,
			D'+CONVERT(nvarchar(2),@lDay)+' AS PresentStatus,
			D'+CONVERT(nvarchar(2),@lDay)+'_IN AS FirstIn,
			D'+CONVERT(nvarchar(2),@lDay)+'_OUT AS LastOut,
			D'+CONVERT(nvarchar(2),@lDay)+'_O AS OverTime,
			D'+CONVERT(nvarchar(2),@lDay)+'_L AS LateBy,
			D'+CONVERT(nvarchar(2),@lDay)+'_T AS Duration,
			D'+CONVERT(nvarchar(2),@lDay)+'_E AS EarlyBy,
			D'+CONVERT(nvarchar(2),@lDay)+'_S AS ShiftName,
			EJD.EmployeeDesignationId,
			EJD.OrganizationDepartmentId, 
			EJD.OrgGroupDepartmentID
		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('+CONVERT(nvarchar(4),@rForYear)+' *10000+ '+CONVERT(nvarchar(2),@rForMonth)+' *100+ 01) AS datetime) AND MT.Attn_Dt <= CAST(RTRIM('+CONVERT(nvarchar(4),@rForYear)+' *10000+ '+CONVERT(nvarchar(2),@rForMonth)+' *100+ 01) AS datetime)
		WHERE (EM.Id = '+CONVERT(nvarchar(max),@rEmployeeId)+' OR '+CONVERT(nvarchar(max),@rEmployeeId)+' = 0)
			AND (EM.OrgId = '+CONVERT(nvarchar(4),@rOrgId)+' OR '+CONVERT(nvarchar(4),@rOrgId)+' = 0)
			AND (EJD.DateOfJoining<= '''+CONVERT(nvarchar(max),@lLasteDate)+''')
			AND ((EJD.DateOfleaving>= '''+CONVERT(nvarchar(max),@lFirstDate)+''') OR ISNULL(EJD.DateOfleaving,'''')='''')
			AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
			AND (EM.StatusId='+CONVERT(nvarchar(max),@rEmployeeStatusId)+' OR '+CONVERT(nvarchar(max),@rEmployeeStatusId)+'=0)'

		--print @Query
		EXEC(@Query)
		SET @lCount = @lCount-1
	END

	SELECT @rBuilder1 AS Builder1, @rBuilder2 AS Builder2, TMP.EmployeeId, TMP.EmployeeCode, TMP.EmployeeName, TMP.Attn_Date,
		ISNULL(CONVERT(varchar(5),SM.StartTime,114),'00:00') AS ShiftStartTime, ISNULL(CONVERT(varchar(5),SM.EndTime,114),'00:00') AS ShiftEndTime, 
		ISNULL(CONVERT(varchar(5),CONVERT(time,SM.ShiftDur),114),'00:00') AS ShiftHours, 
		ISNULL(TMP.FirstIn,'00:00') AS FirstIn, ISNULL(TMP.LastOut,'00:00')LastOut,
		CASE WHEN ISNULL(LastOut,'00:00')<>'00:00' THEN CONVERT(varchar(5), CAST(ISNULL(LastOut,'00:00') AS datetime) - CAST(ISNULL(FirstIn,'00:00') AS datetime), 114)
			ELSE '00:00' END AS Hours,
		[sBiometric].[fEmployeeLeaveTypeGet] (TMP.Attn_Date,TMP.EmployeeId) AS LeaveStatus,
		CASE WHEN ISNULL(FirstIn,'00:00')<>'00:00' AND ISNULL(SM.StartTime,'00:00')<>'00:00' AND ISNULL(FirstIn,'00:00')>ISNULL(SM.StartTime,'00:00') THEN CONVERT(varchar(5), CAST(ISNULL(FirstIn,'00:00') AS datetime) - CAST(ISNULL(SM.StartTime,'00:00') AS datetime), 114)
			ELSE '' END AS LateIn,
		CASE WHEN ISNULL(LastOut,'00:00')<>'00:00' AND ISNULL(SM.EndTime,'00:00')<>'00:00' AND ISNULL(LastOut,'00:00')>ISNULL(SM.EndTime,'00:00') THEN CONVERT(varchar(5), CAST(ISNULL(LastOut,'00:00') AS datetime) - CAST(ISNULL(SM.EndTime,'00:00') AS datetime), 114)
			ELSE '' END AS LateOut,
		CASE WHEN ISNULL(FirstIn,'00:00')<>'00:00' AND ISNULL(SM.StartTime,'00:00')<>'00:00' AND ISNULL(SM.StartTime,'00:00')>ISNULL(FirstIn,'00:00') THEN CONVERT(varchar(5), CAST(ISNULL(SM.StartTime,'00:00') AS datetime) - CAST(ISNULL(FirstIn,'00:00') AS datetime), 114)
			ELSE '' END AS EarlyIn,		
			CASE WHEN ISNULL(LastOut,'00:00')<>'00:00' AND ISNULL(SM.EndTime,'00:00')<>'00:00' AND ISNULL(SM.EndTime,'00:00')>ISNULL(LastOut,'00:00') THEN CONVERT(varchar(5), CAST(ISNULL(SM.EndTime,'00:00') AS DATETIME) - CAST(ISNULL(LastOut,'00:00') AS DATETIME), 114)
			ELSE '' END AS EarlyOut,
		EDM.Title AS EmployeeDesignation,
		DM.Title AS DepartmentName,
		OGD.Title AS OrgGroupDepartmentName
	FROM #tmpBiometricData TMP LEFT JOIN sBiometric.tShiftMasterCloud SM ON SM.ShiftName=TMP.ShiftName
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=TMP.OrganizationDepartmentId
		LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON OGD.Id=TMP.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=TMP.EmployeeDesignationId
	WHERE (DM.Id=@rDepartmentId OR @rDepartmentId=0)
		and (OGD.Id=@rOrgGroupDepartmentId OR @rOrgGroupDepartmentId=0)

	DROP TABLE #tmpBiometricData

	--SELECT 
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	CONVERT(bigint,0) AS EmployeeId,
	--	'' AS EmployeeCode,
	--	'' AS EmployeeName,
	--	CONVERT(date,'') AS Attn_Date,
	--	'' AS ShiftStartTime,
	--	'' AS ShiftEndTime,
	--	'' AS ShiftHours,
	--	'' AS FirstIn,
	--	'' AS LastOut,
	--	'' AS Hours,
	--	'' AS LeaveStatus,
	--	'' AS LateIn,
	--	'' AS LateOut,
	--	'' AS EarlyIn,
	--	'' AS EarlyOut,
	--	'' AS EmployeeDesignation,
	--	'' AS DepartmentName,
	--	'' AS OrgGroupDepartmentName

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sBiometric].[pRptEmployeeWiseMonthlyAttendanceGet]  
    
  @rOrgId int ,  
   @rBuilder1 nvarchar(max)='',  
   @rBuilder2 nvarchar(max)='' ,  
   @rFromMonth int=0,  
   @rFromyear int=0,
   @rEmployeeStatusId int=0  ,
   @rEmployeeId bigint = 0,
   @rOrgGroupId int = 0
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
 CREATE Table #temptable  
 (  
  EmployeeId bigint,  
  D1 nvarchar(5),D2 nvarchar(5),D3 nvarchar(5),D4 nvarchar(5),D5 nvarchar(5),D6 nvarchar(5),D7 nvarchar(5),D8 nvarchar(5),D9 nvarchar(5),  
  D10 nvarchar(5),D11 nvarchar(5),D12 nvarchar(5),D13 nvarchar(5),D14 nvarchar(5),D15 nvarchar(5),D16 nvarchar(5),D17 nvarchar(5),  
  D18 nvarchar(5),D19 nvarchar(5),D20 nvarchar(5),D21 nvarchar(5),D22 nvarchar(5),D23 nvarchar(5),D24 nvarchar(5),D25 nvarchar(5),  
  D26 nvarchar(5),D27 nvarchar(5),D28 nvarchar(5),D29 nvarchar(5),D30 nvarchar(5),D31 nvarchar(5)  
 )  

 Insert into #temptable  
 (  
  EmployeeId  
 )  
 --select * from sbiometric.tprocess
 Select Distinct B.Sourceid   
  from sHrm.tEmployeeMaster EMP    
  INNER JOIN sbiometric.tprocess B ON B.Sourceid=EMP.Id  
  WHere (EMp.OrgId=@rOrgId OR @rOrgId = 0)  AND MONTH(B.AtdDate)=@rFromMonth AND YEAR(B.AtdDate)=@rFromyear   AND  ISNULL(EMP.IsOtherUser,0) = 0
  AND (EMP.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)

  update #temptable set D1='-', D2='-', D3='-', D4='-', D5='-', D6='-', D7='-', D8='-', D9='-', D10='-', D11='-', D12='-', D13='-', D14='-', D15='-',  
   D16='-', D17='-', D18='-', D19='-', D20='-', D21='-', D22='-', D23='-', D24='-', D25='-', D26='-', D27='-', D28='-', D29='-', D30='-', D31='-'  
    
  Update t1 set t1.D1 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=1  
  Update t1 set t1.D2 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=2  
  Update t1 set t1.D3 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=3  
  Update t1 set t1.D4 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=4  
  Update t1 set t1.D5 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=5  
  Update t1 set t1.D6 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=6  
  Update t1 set t1.D7 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=7  
  Update t1 set t1.D8 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=8  
  Update t1 set t1.D9 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=9  
  Update t1 set t1.D10 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=10  
  Update t1 set t1.D11 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=11  
  Update t1 set t1.D12 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=12  
  Update t1 set t1.D13 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=13  
  Update t1 set t1.D14 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=14  
  Update t1 set t1.D15 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=15  
  Update t1 set t1.D16 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=16  
  Update t1 set t1.D17 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=17  
  Update t1 set t1.D18 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=18  
  Update t1 set t1.D19 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=19  
  Update t1 set t1.D20 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=20  
  Update t1 set t1.D21 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=21  
  Update t1 set t1.D22 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=22  
  Update t1 set t1.D23 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=23  
  Update t1 set t1.D24 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=24  
  Update t1 set t1.D25 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=25  
  Update t1 set t1.D26 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=26  
  Update t1 set t1.D27 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=27  
  Update t1 set t1.D28 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=28  
  Update t1 set t1.D29 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=29  
  Update t1 set t1.D30 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=30  
  Update t1 set t1.D31 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=31  
    
  Select   
   EMp.FirstName+' ' +EMp.MiddleName+' '+emp.LastName AS Name,  
   Emp.Id As EmployeeID ,  
    @rBuilder1 AS Builder1,  
    @rBuilder2 AS Builder2,  
    t1.*,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=1  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=1 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D1,  
      
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=2  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=2 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS  D2,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=3  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=3 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D3,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=4  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=4 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D4,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=5  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=5 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D5,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=6  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=6 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D6,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=7  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=7 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D7,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=8  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=8 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D8,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=9  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=9 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D9,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=10  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=10 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D10,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=11  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=11 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D11,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=12  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=12 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D12,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=13  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=13 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D13,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=14  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=14 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D14,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=15  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=15 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D15,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=16  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=16 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D16,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=17  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=17 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D17,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=18  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=18 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D18,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=19  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=19 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D19,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=20  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=20 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D20,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=21  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=21 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D21,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=22  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=22 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D22,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=23  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=23 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D23,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=24  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=24 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D24,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=25  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=25 And EmployeeId=Emp.Id Group by EmployeeId  )  
   --   ELSE  '-' END   
   -- )AS   D25,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=26  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=26 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D26,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=27  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=27 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D27,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=28  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=28 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D28,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=29  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=29  And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D29,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=30  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=30 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D30,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=31  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=31 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS   D31,  
    sCommon.fGetDaysInMonth(@rFromMonth,@rFromyear) As DaysInMonth ,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle 
       
      
  from sHrm.tEmployeeMaster EMP 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EMP.OrgID   
  INNER JOIN #temptable t1 On t1.EmployeeId =EMp.Id  AND  ISNULL(EMP.IsOtherUser,0) = 0
  WHERE (EMP.OrgId=@rOrgId OR @rOrgId = 0) AND (Emp.Id = @rEmployeeId OR @rEmployeeId = 0)  
  AND OM.OrgGroupId = @rOrgGroupId
END

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sBiometric].[pRptEmployeeWiseMonthlySummaryGet] 
     @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int ,
	@rDeptId int ,
	@rForYear int,
	@rForMonth int,	 
	@rEmployeeStatusId int,
	@rEmployeeId bigint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
declare @Days int
Declare @lFromDate datetime
Declare @lToDate datetime


CREATE TABLE #TempMonthTrans  
 (  
 Id int ,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 LateBy nvarchar(20),   
 EarlyBy nvarchar(20), 
 ) 
 select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
 set @lFromDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @lToDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), @Days)
 --select @lFromDate,@lToDate
  INSERT INTO #TempMonthTrans 
  select Id,EmployeeId ,Attn_Date,PresentStatus ,LateBy, EarlyBy 
   from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rDeptId ,@lFromDate,@lToDate,@rEmployeeId)

  SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		MT.EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
		OM.Id AS OrganizationId,
		OM.DisplayTitle AS OrganizationTitle,
		OM.OrderIndex AS OrganizationOrderIndex,
		EM.Number AS EmployeeNumber,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
		MT.Count_Late AS Count_Late,
		isnull(Absent.TotAbsent,0.00) AS TotalAbsentDays,
		isnull(WeekOff.TotWeekOff,0.00) AS TotalWeekOffs,
		isnull(Holidays.TotHoliday,0.00) AS TotalHolidays,
		isnull(Present.TotPresent,0.00) AS TotalPresentDays,
		isnull(HalfDay.TotHalfDay,0.00) AS TotalHalfDays,
		isnull(ErrorCase.TotalErrorCase,0.00) AS TotalErrorCase,
		ISNULL(EA.PaidLeave,0.00)  as PaidLeave,
		Isnull(EA.LWP,0.00)  AS UnPaidLeave,
		IsNull(MT.TotalHour,'00:00') as TotalHour,
		Isnull(MT.Tot_Early,'00:00') as Tot_Early,
		Isnull(MT.Tot_OT,'00:00') as Tot_OT,
		Isnull(MT.Tot_Late,'00:00') as Tot_Late,
		DM.Displaytitle AS DeptName,
		DM.Id As DeptId
	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId AND (SourceTypeId = 95 OR SourceTypeId=0)
	left join [sHrm].[tEmployeeAttendance] EA ON EA.EmployeeId=Mt.EmployeeId AND EA.ForYear=@rForYear AND EA.ForMonth=@rForMonth
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN ('P','PW','PH') group by EmployeeId) Present ON Present.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like 'A' group by EmployeeId) Absent ON Absent.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN ('W','PW','PHW') group by EmployeeId) WeekOff ON WeekOff.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like 'HD' group by EmployeeId) HalfDay ON HalfDay.EmployeeId = MT.employeeID
    LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like 'H' group by EmployeeId) Holidays ON Holidays.EmployeeId = MT.employeeID	
	LEFT Join (Select COUNT(*) AS TotalErrorCase,EmployeeId from #TempMonthTrans Where PresentStatus Like 'E' group by EmployeeId) ErrorCase ON ErrorCase.EmployeeId = MT.employeeID	

	WHERE
	(EM.OrgId = @rOrgId OR @rOrgId = 0)
	--AND YEAR(MT.Attn_Dt) = @rForYear
	--AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND MT.Attn_dt=cast(rtrim(@rForYear *10000+ @rForMonth *100+ 01) as datetime) --Mantis Id : 0028180
	AND (EJD.OrganizationDepartmentId = @rDeptId OR @rDeptId = 0)		 	
	AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	AND ISNULL(EM.IsOtherUser,0) = 0 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND (OM.OrgGroupId = @rOrgGroupId)
	order by MT.EmpCode

	DROP Table #TempMonthTrans	
 --select 
 --@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2,
	--	CAST(0 AS bigint) AS EmployeeId,
	--	0 AS EmpCode,
	--	'' AS EmployeeName,  
	--	0 AS OrganizationId,
	--	'' AS OrganizationTitle,
	--	0 AS OrganizationOrderIndex,
	--	CAST(0 AS bigint) AS EmployeeNumber,
	--	DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
	--	0.00 AS Count_Late,
	--	0.00 AS TotalAbsentDays,
	--	0.00 AS TotalWeekOffs,
	--	0.00 AS TotalHolidays,
	--	0.00 AS TotalPresentDays,
	--	0.00 AS TotalHalfDays,
	--	0.00 AS TotalErrorCase,
	--	0.00  as PaidLeave,
	--	0.00  AS UnPaidLeave,
	--	'00:00' as TotalHour,
	--	'00:00' as Tot_Early,
	--	'00:00' as Tot_OT,
	--	'00:00' as Tot_Late,
	--	'' AS DeptName,
	--	0 As DeptId

end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptEmployeeWiseStatusSummary]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rEmployeeStatusId int=0,
	 @rOrgGroupId int = 0,
	 @OrgGroupDepartmentId int = 0
AS
BEGIN
	SET NOCOUNT ON;
DECLARE @TableEmployee TABLE (Id int Identity,EmployeeID BigINT, OrganizationDepartmentId int, EmployeeTypeId Int)
INSERT INTO @TableEmployee
SELECT EM.Id AS EmployeeId,ED.OrganizationDepartmentId,ED.EmployeeTypeId from shrm.tEmployeeMaster EM 
INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id 
Where (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )
AND (ED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0 )
AND  EM.ORgId = @rOrgId 
AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 
AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 
    

DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lBatchID int
DECLARE @lEmployeeId bigint
DECLARE @lEmpCount int
DECLARE @lEmpDepartmentID int

DECLARE @TempDate TABLE(Id int identity,Idate date)
insert into @TempDate
SELECT  TOP (DATEDIFF(DAY, @rFromDate, @rToDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @rFromDate)
FROM    sys.all_objects a CROSS JOIN sys.all_objects b;

--CREATE TABLE #TempMonthTrans (Id int Identity,EmployeeId bigint,Attn_Date DateTime,DayNumber nvarchar(8),PresentStatus nvarchar(25),
		--OverTime nvarchar(20),EarlyBy nvarchar(20), LateBy nvarchar(20),Duration nvarchar(20))
CREATE TABLE #TempMonthTrans (Id int Identity,EmployeeId bigint,Attn_Date DateTime,Leave nvarchar(100),DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20))

truncate table #TempMonthTrans

SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

Select @lCount = Max(Id) from @TempDate
Select @lEmpCount = Max(Id) from @TableEmployee
While (@lEmpCount > 0)
	BEGIN
		SELECT @lEmployeeId = EmployeeId,@lEmpDepartmentID = OrganizationDepartmentId  From @TableEmployee Where Id = @lEmpCount	
	set @lCount1 = 1
	while (@lCount1 <= @lCount)
	begin			
		Select @lDate = Idate from @TempDate Where Id = @lCount1
		Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

DECLARE @weekoffstatus nvarchar(20)

SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)


--set @lQuery =  ' INSERT INTO #TempMonthTrans
						--SELECT  ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						--'''+''+''',
						--substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
						--Case 
						---When ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						--When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						--Then ''' +@weekoffstatus +''' 
						--Else D'+convert(nvarchar(15),@lDay)+' End D'+convert(nvarchar(15),@lDay)+'_O,D'+convert(nvarchar(15),@lDay)+'_E,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T 
						----FROM sBiometric.tMonthTrans T1 
						---INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 0 )
						--WHERE T1.EmployeeId =' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) AND (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				

set @lQuery =  ' INSERT INTO #TempMonthTrans
						SELECT  ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						'''+''+''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
						Case 
						When ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						When D'+ convert(nvarchar(15),@lDay) +' =''XX'' AND  (Cast(''' + convert(nvarchar(15),@lDate) + ''' as date)<GETDATE()) And (cast(ED.DateOfJoining as date)<= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfJoining,'''')='''')AND (ED.DateOfleaving>= Cast(''' + convert(nvarchar(15),@lDate) + ''' as date) OR ISNULL(ED.DateOfleaving,'''')='''')  then ''A''
						Else D'+convert(nvarchar(15),@lDay)+' End D'+convert(nvarchar(15),@lDay)+',D'+convert(nvarchar(15),@lDay)+'_IN,D'+convert(nvarchar(15),@lDay)+'_OUT,D'+convert(nvarchar(15),@lDay)+'_O,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T,D'+convert(nvarchar(15),@lDay)+'_E
						FROM sBiometric.tMonthTrans T1 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )AND (ED.OrgGroupDepartmentId ='''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@OrgGroupDepartmentId)+'''= 0 )
						WHERE T1.EmployeeId =' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) AND (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'
						
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END

	--Select * from #TempMonthTrans T

	--SELECT  EmployeeId,COUNT(PresentStatus) AS TotPresent FROM #TempMonthTrans WHERE PresentStatus IN ('P','PH','PW') GROUP BY EmployeeId 
			--(SELECT COUNT(PresentStatus) FROM #TempMonthTrans WHERE PresentStatus IN ('A') GROUP BY EmployeeId) AS TotAbsent			

	--SET @strQuery = 'select  Day(T.Attn_Date), T.EmployeeId, T.Attn_Date, SUM(convert(int, left(T.OverTime, 2))+0) AS TotHoursOverTime, SUM(convert(int, substring(T.OverTime, 4,2))+0) AS TotMinutesOverTime, SUM(convert(int, left(T.EarlyBy, 2))+0) AS TotHoursEarlyBy, SUM(convert(int, substring(T.EarlyBy, 4,2))+0) AS TotMinutesEarlyBy,SUM(convert(int, left(T.LateBy, 2))+0) AS TotHoursLateBy, SUM(convert(int, substring(T.LateBy, 4,2))+0) AS TotMinutesLateBy, SUM(convert(int, left(T.Duration, 2))+0) AS TotHoursDuration, SUM(convert(int, substring(T.Duration, 4,2))) AS TotMinutesDuration,
	--isnull(A4.TotPresent,0) AS TotPresent, isnull(A.TotAbsent,0) AS TotAbsent, isnull(A1.TotWeekOff,0) AS TotWeekOff, isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,
	--isnull(CLLeave,0) AS CLLeave,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	--Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,
	--DM.Displaytitle DeptName,
	--OM.Id AS OrgId,
	--OM.Title AS OrganizationTitle
	--from #TempMonthTrans T
	--INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	--LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	--LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	--LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 
	
	--LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN (''P'',''PW'',''PH'')  group by EmployeeId,PresentStatus) A4 ON A4.EmployeeId = T.employeeID
	--LEFT Join (Select COUNT(*) AS TotEarly,EmployeeId from #TempMonthTrans Where PresentStatus IN (''E'') group by EmployeeId,PresentStatus) A6 ON A6.EmployeeId = T.employeeID
	--LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like ''A'' group by EmployeeId,PresentStatus) A ON A.EmployeeId = T.employeeID
	--LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN (''W'',''PW'',''PHW'') group by EmployeeId,PresentStatus) A1 ON A1.EmployeeId = T.employeeID
	--LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId,PresentStatus) A3 ON A3.EmployeeId = T.employeeID
 --   LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId,PresentStatus) A5 ON A5.EmployeeId = T.employeeID


	--LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	--Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	--LEFT Join (select   distinct  EmployeeId,
 --   ISNULL( stuff((
 --       select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
 --       from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
 --       where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
 --       AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
 --       AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
 --       group by LT.Code
 --       for xml path('''')
 --   ),1,1,''''),'''') as LeaveCode1
	--from shrm.tLeave L1 
	--inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	--group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId 
	--WHERE (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
 --   AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') 
	--AND (T.Attn_Date >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''') )
	--AND (T.Attn_Date <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
	--GROUP BY T.EmployeeId, DM.Displaytitle, OM.Id, OM.Title, LV.CLLeave, LV.LeaveCode, LV1.LeaveCode1, Emp.Code, Emp.FirstName, Emp.MiddleName, Emp.LastName, T.Attn_Date
	--' 

	SET @strQuery = 'select  Day(T.Attn_Date), T.EmployeeId, T.Attn_Date, SUM(convert(int, left(T.OverTime, 2))) AS TotHoursOverTime, SUM(convert(int, substring(T.OverTime, 4,2))) AS TotMinutesOverTime, SUM(convert(int, left(T.EarlyBy, 2))) AS TotHoursEarlyBy, SUM(convert(int, substring(T.EarlyBy, 4,2))) AS TotMinutesEarlyBy,SUM(convert(int, left(T.LateBy, 2))) AS TotHoursLateBy, SUM(convert(int, substring(T.LateBy, 4,2))) AS TotMinutesLateBy, SUM(convert(int, left(T.Duration, 2))) AS TotHoursDuration, SUM(convert(int, substring(T.Duration, 4,2))) AS TotMinutesDuration,
	isnull(A13.TotPresent,0) AS TotPresent, isnull(A.TotAbsent,0) AS TotAbsent, isnull(A1.TotWeekOff,0) AS TotWeekOff, isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,Isnull(TotLateHours,0) AS TotLateHours,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,
	DM.Displaytitle DeptName,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	
	LEFT Join (Select COUNT(PresentStatus) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN (''P'',''PH'',''PW'')  group by EmployeeId) A13 ON A13.EmployeeId = T.employeeID 
	LEFT Join (Select COUNT(PresentStatus) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like ''A'' group by EmployeeId) A ON A.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(PresentStatus) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN (''W'',''PW'',''PHW'') group by EmployeeId) A1 ON A1.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(PresentStatus) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId) A3 ON A3.EmployeeId = T.employeeID
    LEFT Join (Select COUNT(PresentStatus) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId) A5 ON A5.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(PresentStatus) AS TotLateHours,EmployeeId from #TempMonthTrans Where PresentStatus Like ''LH'' group by EmployeeId) A14 ON A14.EmployeeId = T.employeeID


	


	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId 


	WHERE (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
    AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') 
	AND (T.Attn_Date >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''') )
	AND (T.Attn_Date <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
	GROUP BY T.EmployeeId, DM.Displaytitle, OM.Id, OM.Title, Emp.Code, Emp.FirstName, Emp.MiddleName, Emp.LastName, T.Attn_Date, A.TotAbsent, A13.TotPresent, A1.TotWeekOff, A3.TotHalfDay, A5.TotHoliday, A14.TotLateHours
	'
	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	
	execute (@strQuery)
	print(@strQuery)
	DROP TABLE #TempMonthTrans
	--select  
	--@rBuilder1 as Builder1,
	--@rBuilder2 as Builder2,
	--'' as Attn_Date,
	--'' as Leave,
	--'' as EmployeeId,	
	--'' as DayNumber ,
	--'' as PresentStatus ,
	--'' as FirstIn,
	--'' as LastOut,
	--'' as TotHalfDay,
	--'' as TotHoliday,
	--'' AS TotEarly,
	--'' AS TotLateHours,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as TotHoursOverTime,
	--'' as TotMinutesOverTime,
	--'' as TotHoursEarlyBy,
	--'' as TotMinutesEarlyBy,
	--'' as TotHoursLateBy,
	--'' as TotMinutesLateBy,
	--'' as TotHoursDuration,
	--'' as TotMinutesDuration,
	--'' as TotPresent,
	--'' as TotWeekOff,
	--'' as TotHoliday,
	--'' as LeaveCode1,
	--'' as OrgId,
	--'' as OrganizationTitle
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pRptManualPunchGet]    
             
   @rBuilder1 nvarchar(max)='',    
   @rBuilder2 nvarchar(max)='',    
   @rToDate date='',
   @rFromDate date='',
   @rEmployeeStatusId int=0,
   @rEmployeeId bigint = 0,
   @rOrganizationDepartmentId int = 0,
   @rLocationConfig nvarchar(50) = '',
   @rOrgId int = 0,
   @rOrgGroupId int = 0
       
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN     
  Select 
  EM.Code AS EmployeeCode,    
   ISNULL(ECI.EmployeePhoto,0) AS EmployeePhoto,
   EM.FirstName+' ' +EM.MiddleName+' '+EM.LastName AS Name,    
   ISNULL(ECI.CheckInTime,'') AS CheckInTime,
   ISNULL(ECI.CheckOutTime,'') AS CheckOutTime,
   EM.ID As EmployeeID ,      
   @rBuilder1 AS Builder1,    
   @rBuilder2 AS Builder2,
   ISNULL(LatitudeAxis,'') AS Latitude,
   ISNULL(LongitudeAxis,'') AS Longitude,
   ISNULL(Location,'') AS Location,
   @rLocationConfig AS LocationConfig,
   CAST(ECI.AttendanceDate AS DATE) AS AttendanceDate,
   OM.Id AS OrganizationId,
   OM.Title AS OrganizationName
   
  FROM
	   sBiometric.tEmployeeCheckIn ECI      
	   INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = ECI.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	   LEFT JOIN sHrm.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id     
   WHERE 
	   (EM.Id = @rEmployeeId OR @rEmployeeId = 0) 
	   AND (EM.OrgId = @rOrgId OR @rOrgId = 0)
	   AND (CAST(ECI.AttendanceDate AS DATE) >= @rFromDate OR (ISNULL(@rFromDate,'')=''))
       AND (CAST(ECI.AttendanceDate AS DATE) <= @rToDate OR (ISNULL(@rToDate,'')=''))
	   AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
	   AND (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )	
	   AND (OM.OrgGroupId = @rOrgGroupId)   
	   AND  ISNULL(EM.IsOtherUser,0) = 0	   	   
    
	ORDER BY ECI.AttendanceDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sBiometric].[pRptMonthlyLateInSummaryGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int ,
	@rOrganizationDepartmentId int ,
	@rFromDate Datetime,
	@rToDate Datetime,	 
	@rEmployeeStatusId int,
	@rEmployeeId bigint,
	@rOrgGroupId int,
	@rGradeId nvarchar(max)= '0',
	@rOrgGroupDepartmentId int =0,
	@rTimeSheetStatus nvarchar(50) ='0',
	@rOrderBy smallint = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
	CREATE TABLE #TempMonthTrans  
	 (  
	 Id int ,  
	 EmployeeId bigint,   
	 Attn_Date DateTime,  
	 PresentStatus nvarchar(15),  
	 LateBy nvarchar(20),   
	 EarlyBy nvarchar(20), 
	 FirstIn nvarchar(20),
	 ShiftName nvarchar(25) ,
	 Duration nvarchar(20),
	  LastOut nvarchar(20)
	 ) 
 
 ---select @rFromDate,@rToDate 
	  INSERT INTO #TempMonthTrans 
	  select Id,EmployeeId ,Attn_Date,PresentStatus ,LateBy, EarlyBy,FirstIn,ShiftName,Duration, LastOut
	  from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rOrganizationDepartmentId ,@rFromDate,@rToDate,@rEmployeeId)
	  --select * from #TempMonthTrans 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			MT.EmployeeId,
			MT.EmpCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
			OM.Id AS OrganizationId,
			OM.DisplayTitle AS OrganizationTitle,
			OM.OrderIndex AS OrganizationOrderIndex,
			EM.Number AS EmployeeNumber,
			IsNull(MT.TotalHour,'00:00') as TotalHour,
			Isnull(MT.Tot_Early,'00:00') as Tot_Early,
			Isnull(MT.Tot_OT,'00:00') as Tot_OT,
			Isnull(MT.Tot_Late,'00:00') as Tot_Late,
			Isnull(Mt.Count_Late, 0) as Count_Late,
			OM.Id AS OrgId,
			OM.Title AS OrganizationTitle,
			TM.Attn_Date as Attn_Date,
			TM.FirstIn as FirstIn,
			TM.LateBy AS LateBy,
			TM.PresentStatus as PresentStatus,
			TM.EarlyBy AS EarlyBy,
			TM.ShiftName AS ShiftName,
			DM.Displaytitle AS DeptName,
			DM.Id As DeptId,
			@rOrderBy AS OrderBy,
			TM.LastOut AS LastOut
		FROM #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId AND (SourceTypeId = 95 OR SourceTypeId=0)
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
	
		WHERE
		(EM.OrgId = @rOrgId OR @rOrgId = 0)
		 and TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate   
		 and  MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
		AND (EJD.OrganizationDepartmentId = @rOrganizationDepartmentId OR @rOrganizationDepartmentId = 0)		 	
		AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
		AND ISNULL(EM.IsOtherUser,0) = 0 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND (OM.OrgGroupId = @rOrgGroupId)
		AND (EmployeeGradeId in ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGradeId,',')) OR @rGradeId=0) 
		AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
		AND  ((PresentStatus in ( SELECT cast(item as nvarchar) FROM  sCommon.fnsplit(@rTimeSheetStatus,','))) OR (@rTimeSheetStatus='0')) 


		DROP Table #TempMonthTrans	

		--select
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	CAST(0 AS bigint) AS EmployeeId,
		--	'' as EmpCode,
		--	'' AS EmployeeName,  
		--	'' AS OrganizationId,
		--	'' AS OrganizationTitle,
		--	0 AS OrganizationOrderIndex,
		--	CAST(0 AS bigint) AS EmployeeNumber,
		--	'' as TotalHour,
		--	'' as Tot_Early,
		--	'' as Tot_OT,
		--	'' as Tot_Late,
		--	0 as Count_Late,
		--	0 AS OrgId,
		--	'' AS OrganizationTitle,
		--	CAST('1999-01-01 00:00:00' AS datetime) as Attn_Date,
		--	'' as FirstIn,
		--	'' AS LateBy,
		--	'' as PresentStatus,
		--	'' AS EarlyBy,
		--	'' AS ShiftName,
		--	'' AS DeptName,
		--	0 As DeptId,
		--	@rOrderBy AS OrderBy,
		-- '' as LastOut


End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptMonthlySummaryListDateWiseGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rFromDate DateTime,
	@rToDate DateTime, 
	@rStudentId bigint=0,
	@rClassId int=0,
	@rDivisionId int=0,
	--@rAttendanceTypeId tinyint,
	--@rAttendanceDate date=0,
	-- @rRepeatCount tinyint,
	@rOrgGroupBatchId int=0,
	@rTimeSheetStatus nvarchar(10) = '0',
	@rDepartmentId int=0,
	@rStatusId int=0,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit=0,
	@rAcademicId bigint=0		--Mantis: 34829, add by dhruvik
	
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
DECLARE @lBatchID int
CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20),
 ShiftName nvarchar(25) 
	
	)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId = 2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
		AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	CREATE TABLE #TempMonthTransWitIoOutTime (EmployeeId bigint,Attn_Date DateTime,InTime nvarchar(20),OutTime nvarchar(20))
	if(@rIsDetail=1)
	BEGIN
	INSERT INTO #TempMonthTransWitIoOutTime
		SELECT  SourceId,Attn_Dt,CONVERT(VARCHAR(10), I.In_Out_Time, 108),CONVERT(VARCHAR(10), O.In_Out_Time, 108)
        FROM [sBiometric].[tCloudTransactionData] I
		OUTER APPLY (
						SELECT TOP 1    In_Out_Time,
										Mode
						FROM [sBiometric].[tCloudTransactionData] t
						WHERE       t.SourceId = I.SourceId
								AND t.In_Out_Time > I.In_Out_Time
								AND SourceTypeid=2001		--Mantis: 34829, change by dhruvik, from 2003 => 2001
								AND t.Attn_Dt =I.Attn_Dt
								AND Mode = 'OUT'
						ORDER BY t.In_Out_Time
					) O
		WHERE I.Mode = 'IN'
		AND SourceTypeid=2001		--Mantis: 34829, change by dhruvik, from 2003 => 2001
		AND I.Attn_Dt>=@rFromDate
		AND I.Attn_Dt<=@rToDate
		--select * from #TempMonthTransWitIoOutTime
	END

	Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2 ,
		SA.AcademicId AS AcademicId,
		SA.StudentId AS StudentId,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		ISNULL(TM.FirstIn,'00:00') AS FirstIn,
		ISNULL(TM.LastOut,'00:00') AS LastOut,
		ISNULL(TM.LateBy,'00:00') AS LateBy,
		ISNULL(TM.EarlyBy,'00:00') AS EarlyBy,
		 ISNULL(TM.Duration,'00:00') AS Duration,
		 ISNULL(TM.PresentStatus,'XX') AS OldPresentStatus ,
		  CASE When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 ELSE
		TM.PresentStatus END as PresentStatus,
		TM.Attn_Date,
		OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId,
		TM.ShiftName,
		CTD.*,
		@rIsDetail AS IsDetail
				
		From #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND SourceTypeId = 2001		--Mantis: 34829, change by dhruvik, from 2003 => 2001  
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.AcademicId = TM.EmployeeId AND MT.SourceTypeId=2001 --AND MT.ATTN_DT = cast(rtrim(YEAR(@rAttendanceDate) *10000+ Month(@rAttendanceDate)  *100+ 01) as datetime)		--Mantis: 34829, change by dhruvik, from SA.StudentId => SA.AcademicId and 2003 => 2001
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	Left Join #TempMonthTransWitIoOutTime CTD ON  CTD.EmployeeId=TM.EmployeeId AND CTD.Attn_Date=TM.Attn_Date  
	INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id AND BM.OrgGroupBatchId=@rOrgGroupBatchId --AND BM.IsActive=1
	WHERE 
		((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND OM.OrgGroupId=@rOrgGroupId
			AND (SA.OrgId=@rOrgId OR @rOrgId=0)
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			--AND (SA.BatchId = @rBatchId)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
			AND (SA.OrgId = @rOrgId OR @rOrgId = 0)
			 AND((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			 AND(( SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			 AND (TM.Attn_Date>=@rFromDate )
			 AND (TM.Attn_Date<=@rToDate)
			AND (SA.AcademicId = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, add by dhruvik
	ORDER BY SA.RollNo

	DROP Table #TempMonthTrans	

	--Select 
	--	@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2 ,
	--	@rIsDetail AS IsDetail,
	--	CAST(0 AS bigint) AS AcademicId,
	--	'' AS StudentCode,
	--	'' AS StudentName,
	--	0 as RollNo,
	--	'' AS FirstIn,
	--	'' AS LastOut,
	--	'' AS LateBy,
	--	'' AS EarlyBy,
	--	 '' AS Duration,
	--	'' AS OldPresentStatus ,
	--	'' AS PresentStatus,
	--	CAST('' AS Date) AS Attn_Date, 
	--	'' AS Organization,
	--	'' AS ClassName,
	--	0 AS ClassId,
	--	'' AS DivisionName,
	--	0 AS DivisionId,
	--	'' AS Department,
	--	0 AS DepartmentId,
	--	'' As ClassDivision,
	--	0 AS OrderIndex,
	--	0 AS DivisionOrderIndex,
	--	0 AS OrgId,
	--	'' AS ShiftName,
	--	'' AS OutTime,
	--	'' as InTime

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptMonthlySummaryListGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int = 0,
	@rDeptId int = 0,
	@rForYear int=0,
	@rForMonth int=0,	 
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0,
	@rOrgGroupId int = 0,
	@OrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
 
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 LateBy nvarchar(20),   
 EarlyBy nvarchar(20), 
 )  
  INSERT INTO #TempMonthTrans  
   
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN = '00:00' THEN 'H'   
			 WHEN (D01 = 'W' OR D01 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN = '00:00' THEN 'A' 
			 WHEN (D01 = 'H' OR D01 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN = '00:00' THEN 'A' 
			 --WHEN  AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'  
			 --WHEN D01 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 When ((D01='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D01_IN ='00:00'))  then 'A'
			 ELSE D01 END ,	
	D01_L,D01_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	
	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN = '00:00' THEN 'H'   
			 WHEN (D02 = 'W' OR D02 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN = '00:00' THEN 'A' 
			 WHEN (D02 = 'H' OR D02 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN = '00:00' THEN 'A' 
			 --WHEN D02 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'  
			 --WHEN D02 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			  When ((D02='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D02_IN ='00:00'))  then 'A'
			 ELSE D02 END ,	
	D02_L,D02_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN = '00:00' THEN 'H'   
			 WHEN (D03 = 'W' OR D03 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN = '00:00' THEN 'A' 
			 WHEN (D03 = 'H' OR D03 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN = '00:00' THEN 'A' 
			 --WHEN D03 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'  
			 --WHEN D03 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 When ((D03='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D03_IN ='00:00'))  then 'A'
			 ELSE D03 END ,	
	D03_L,D03_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN = '00:00' THEN 'H'   
			 WHEN (D04 = 'W' OR D04 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN = '00:00' THEN 'A' 
			 WHEN (D04 = 'H' OR D04 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN = '00:00' THEN 'A' 
			 --WHEN D04 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'  
			 --WHEN D04 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 When ((D04='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D04_IN ='00:00'))  then 'A'
			 ELSE D04 END ,	
	D04_L,D04_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN = '00:00' THEN 'H'   
			 WHEN (D05 = 'W' OR D05 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN = '00:00' THEN 'A' 
			 WHEN (D05 = 'H' OR D05 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN = '00:00' THEN 'A' 
			 --WHEN D05 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'  
			 --WHEN D05 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			  When ((D05='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D05_IN ='00:00'))  then 'A'
			 ELSE D05 END ,	
	D05_L,D05_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN = '00:00' THEN 'H'   
			 WHEN (D06 = 'W' OR D06 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN = '00:00' THEN 'A' 
			 WHEN (D06 = 'H' OR D06 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN = '00:00' THEN 'A' 
			 --WHEN D06 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'  
			 --WHEN D06 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			  When ((D06='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D04_IN ='00:00'))  then 'A'
			 ELSE D06 END ,	
	D06_L,D06_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN = '00:00' THEN 'H'   
			 WHEN (D07 = 'W' OR D07 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN = '00:00' THEN 'A' 
			 WHEN (D07 = 'H' OR D07 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN = '00:00' THEN 'A' 
			 --WHEN D07 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'  
			 --WHEN D07 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			  When ((D07='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D07_IN ='00:00'))  then 'A'
			 ELSE D07 END ,	
	D07_L,D07_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN = '00:00' THEN 'H'   
			 WHEN (D08 = 'W' OR D08 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN = '00:00' THEN 'A' 
			 WHEN (D08 = 'H' OR D08 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN = '00:00' THEN 'A' 
			 --WHEN D08 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'  
			 --WHEN D08 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			  When ((D08='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D08_IN ='00:00'))  then 'A'
			 ELSE D08 END ,	
	D08_L,D08_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN = '00:00' THEN 'H'   
			 WHEN (D09 = 'W' OR D09 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN = '00:00' THEN 'A' 
			 WHEN (D09 = 'H' OR D09 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN = '00:00' THEN 'A' 
			 --WHEN D09 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'  
			 --WHEN D09 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			  When ((D09='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D09_IN ='00:00'))  then 'A'
			 ELSE D09 END ,	
	D09_L,D09_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN = '00:00' THEN 'H'   
			 WHEN (D10 = 'W' OR D10 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN = '00:00' THEN 'A' 
			 WHEN (D10 = 'H' OR D10 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN = '00:00' THEN 'A' 
			 --WHEN D10 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'  
			 --WHEN D10 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			  When ((D10='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D10_IN ='00:00'))  then 'A'
			 ELSE D10 END ,	
	D10_L,D10_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1	

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN = '00:00' THEN 'H'   
			 WHEN (D11 = 'W' OR D11 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN = '00:00' THEN 'A' 
			 WHEN (D11 = 'H' OR D11 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN = '00:00' THEN 'A' 
			 --WHEN D11 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'  
			 --WHEN D11 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			  When ((D11='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D11_IN ='00:00'))  then 'A'
			 ELSE D11 END ,
	D11_L,D11_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN = '00:00' THEN 'H'   
			 WHEN (D12 = 'W' OR D12 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN = '00:00' THEN 'A' 
			 WHEN (D12 = 'H' OR D12 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN = '00:00' THEN 'A' 
			 --WHEN D12 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'  
			 --WHEN D12 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			  When ((D12='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D12_IN ='00:00'))  then 'A'
			 ELSE D12 END ,	
	D12_L,D12_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN = '00:00' THEN 'H'   
			 WHEN (D13 = 'W' OR D13 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN = '00:00' THEN 'A' 
			 WHEN (D13 = 'H' OR D13 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN = '00:00' THEN 'A' 
			 --WHEN D13 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'  
			 --WHEN D13 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			  When ((D13='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D13_IN ='00:00'))  then 'A'
			 ELSE D13 END ,	
	D13_L,D13_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN = '00:00' THEN 'H'   
			 WHEN (D14 = 'W' OR D14 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN = '00:00' THEN 'A' 
			 WHEN (D14 = 'H' OR D14 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN = '00:00' THEN 'A' 
			 --WHEN D14 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'  
			 --WHEN D14 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			  When ((D14='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D14_IN ='00:00'))  then 'A'
			 ELSE D14 END ,	
	D14_L,D14_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN = '00:00' THEN 'H'   
			 WHEN (D15 = 'W' OR D15 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN = '00:00' THEN 'A' 
			 WHEN (D15 = 'H' OR D15 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN = '00:00' THEN 'A' 
			 --WHEN D15 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'  
			 --WHEN D15 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			  When ((D15='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D15_IN ='00:00'))  then 'A'
			 ELSE D15 END ,	
	D15_L,D15_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN = '00:00' THEN 'H'   
			 WHEN (D16 = 'W' OR D16 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN = '00:00' THEN 'A' 
			 WHEN (D16 = 'H' OR D16 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN = '00:00' THEN 'A' 
			 --WHEN D16 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'  
			 --WHEN D16 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			  When ((D16='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D16_IN ='00:00'))  then 'A'
			 ELSE D16 END ,	
	D16_L,D16_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN = '00:00' THEN 'H'   
			 WHEN (D17 = 'W' OR D17 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN = '00:00' THEN 'A' 
			 WHEN (D17 = 'H' OR D17 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN = '00:00' THEN 'A' 
			 --WHEN D17 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'  
			 --WHEN D17 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			  When ((D17='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D17_IN ='00:00'))  then 'A'
			 ELSE D17 END ,	
	D17_L,D17_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN = '00:00' THEN 'H'   
			 WHEN (D18 = 'W' OR D18 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN = '00:00' THEN 'A' 
			 WHEN (D18 = 'H' OR D18 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN = '00:00' THEN 'A' 
			 --WHEN D18 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'  
			 --WHEN D18 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			  When ((D18='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D18_IN ='00:00'))  then 'A'
			 ELSE D18 END ,	
	D18_L,D18_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN = '00:00' THEN 'H'   
			 WHEN (D19 = 'W' OR D19 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN = '00:00' THEN 'A' 
			 WHEN (D19 = 'H' OR D19 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN = '00:00' THEN 'A' 
			 --WHEN D19 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'  
			 --WHEN D19 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			  When ((D19='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D19_IN ='00:00'))  then 'A'
			 ELSE D19 END ,	
	D19_L,D19_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN = '00:00' THEN 'H'   
			 WHEN (D20 = 'W' OR D20 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN = '00:00' THEN 'A' 
			 WHEN (D20 = 'H' OR D20 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN = '00:00' THEN 'A' 
			 --WHEN D20 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'  
			 --WHEN D20 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			  When ((D20='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D20_IN ='00:00'))  then 'A'
			 ELSE D20 END ,		
	D20_L,D20_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN = '00:00' THEN 'H'   
			 WHEN (D21 = 'W' OR D21 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN = '00:00' THEN 'A' 
			 WHEN (D21 = 'H' OR D21 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN = '00:00' THEN 'A' 
			 --WHEN D21 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'  
			 --WHEN D21 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			  When ((D21='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D21_IN ='00:00'))  then 'A'
			 ELSE D21 END ,	
	D21_L,D21_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN = '00:00' THEN 'H'   
			 WHEN (D22 = 'W' OR D22 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN = '00:00' THEN 'A' 
			 WHEN (D22 = 'H' OR D22 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN = '00:00' THEN 'A' 
			 --WHEN D22 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'  
			 --WHEN D22 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			  When ((D22='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D22_IN ='00:00'))  then 'A'
			 ELSE D22 END ,		
	D22_L,D22_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN = '00:00' THEN 'H'   
			 WHEN (D23 = 'W' OR D23 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN = '00:00' THEN 'A' 
			 WHEN (D23 = 'H' OR D23 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN = '00:00' THEN 'A' 
			 --WHEN D23 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'  
			 --WHEN D23 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			  When ((D23='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D23_IN ='00:00'))  then 'A'
			 ELSE D23 END ,	
	D23_L,D23_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN = '00:00' THEN 'H'   
			 WHEN (D24 = 'W' OR D24 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN = '00:00' THEN 'A' 
			 WHEN (D24 = 'H' OR D24 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN = '00:00' THEN 'A' 
			 --WHEN D24 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'  
			 --WHEN D24 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			  When ((D24='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D24_IN ='00:00'))  then 'A'
			 ELSE D24 END ,	
	D24_L,D24_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN = '00:00' THEN 'H'   
			 WHEN (D25 = 'W' OR D25 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN = '00:00' THEN 'A' 
			 WHEN (D25 = 'H' OR D25 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN = '00:00' THEN 'A' 
			 --WHEN D25 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'  
			 --WHEN D25 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			  When ((D25='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D25_IN ='00:00'))  then 'A'
			 ELSE D25 END ,	
	D25_L,D25_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN = '00:00' THEN 'H'   
			 WHEN (D26 = 'W' OR D26 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN = '00:00' THEN 'A' 
			 WHEN (D26 = 'H' OR D26 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN = '00:00' THEN 'A' 
			 --WHEN D26 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'  
			 --WHEN D26 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			  When ((D26='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D26_IN ='00:00'))  then 'A'
			 ELSE D26 END ,	
	D26_L,D26_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN = '00:00' THEN 'H'   
			 WHEN (D27 = 'W' OR D27 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN = '00:00' THEN 'A' 
			 WHEN (D27 = 'H' OR D27 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN = '00:00' THEN 'A' 
			 --WHEN D27 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'  
			 --WHEN D27 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			  When ((D27='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D27_IN ='00:00'))  then 'A'
			 ELSE D27 END ,	
	D27_L,D27_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN = '00:00' THEN 'H'   
			 WHEN (D28 = 'W' OR D28 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN = '00:00' THEN 'A' 
			 WHEN (D28 = 'H' OR D28 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN = '00:00' THEN 'A' 
			 --WHEN D28 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'  
			 --WHEN D28 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			  When ((D28='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D28_IN ='00:00'))  then 'A'
			ELSE D28 END ,	D28_L,D28_E
			FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
			AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1


	IF  @rForMonth <> 2 or ((@rForYear % 4 = 0 AND @rForYear % 100 <> 0) OR @rForYear % 400 = 0 And @rForMonth  =2)
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN = '00:00' THEN 'H'   
			 WHEN (D29 = 'W' OR D29 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN = '00:00' THEN 'A' 
			 WHEN (D29 = 'H' OR D29 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN = '00:00' THEN 'A' 
			 --WHEN D29 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'  
			 --WHEN D29 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			  When ((D29='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D29_IN ='00:00'))  then 'A'
			 ELSE D29 END ,	
	D29_L,D29_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	
	IF @rForMonth <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN = '00:00' THEN 'H'   
			 WHEN (D30 = 'W' OR D30 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN = '00:00' THEN 'A' 
			 WHEN (D30 = 'H' OR D30 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN = '00:00' THEN 'A' 
			 --WHEN D30 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'  
			 --WHEN D30 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			  When ((D30='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D30_IN ='00:00'))  then 'A'
			 ELSE D30 END ,	
	D30_L,D30_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	
	IF @rForMonth NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN = '00:00' THEN 'H'   
			 WHEN (D31 = 'W' OR D31 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN = '00:00' THEN 'A' 
			 WHEN (D31 = 'H' OR D31 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN = '00:00' THEN 'A' 
			 --WHEN D31 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'  
			 --WHEN D31 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			  When ((D31='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D31_IN ='00:00'))  then 'A'
			 ELSE D31 END ,	
	D31_L,D31_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END


	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		MT.EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
		MT.Tot_Attn  AS TotalPresentDays,
		MT.Tot_Abs AS TotalAbsentDays,
		MT.Tot_WeekOFF AS TotalWeekOffs,
		MT.Tot_Holiday AS TotalHolidays,
		OM.Id AS OrganizationId,
		OM.DisplayTitle AS OrganizationTitle,
		OM.OrderIndex AS OrganizationOrderIndex,
		EM.Number AS EmployeeNumber,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
		MT.Count_Late AS Count_Late,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS WeekOffsWiseTotalAbsentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS WeekOffsWiseTotalWeekOffs,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS WeekOffsWiseTotalHolidays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS WeekOffsWiseTotalPresentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS WeekOffsWiseTotalHalfDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS WeekOffsWiseTotalLessHours,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS WeekOffsWiseTotalErrorCase

	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId --AND SourceTypeId = 95
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	WHERE
	(EM.OrgId = @rOrgId OR @rOrgId = 0)
	AND YEAR(MT.Attn_Dt) = @rForYear
	AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND (EJD.OrganizationDepartmentId = @rDeptId OR @rDeptId = 0)		 	
	AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	AND ISNULL(EM.IsOtherUser,0) = 0 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND (OM.OrgGroupId = @rOrgGroupId)
	AND ((EJD.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 

	DROP Table #TempMonthTrans
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptStudentBiometricReportData]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rDeptId int = 0,
	@rClassId int,
	@rDivisionId int,
	@rStatusId int = 0,
	@rStudentId bigint = 0,
	@rAcademicId bigint = 0,
	@rForYear int = 0,
	@rForMonth int = 0,
	@rOrgGroupId int = 0,
	@rOrgGroupBatchId int = 0


	
	
	--@rIsFirstIn bit=0,
	--@rIsLastOut bit=0,
	--@rIsOT bit=0,
	--@rIsLateBy	bit=0,
	--@rIsEarlyBy bit=0,
	--@rIsDuration  bit=0,
	--@OrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lATTN_DATE nvarchar(20)
	DECLARE @lBatchID int
	DECLARE @Days int 
	SELECT @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1

	SET @lATTN_DATE = CONVERT(nvarchar(10),@rForYear) + '-' + Right('000000' + CONVERT(nvarchar, @rForMonth), 2) + '-01'
	
	DECLARE @lDN1 nvarchar(10),@lDN2 nvarchar(10),@lDN3 nvarchar(10),@lDN4 nvarchar(10),@lDN5 nvarchar(10),
	@lDN6 nvarchar(10),@lDN7 nvarchar(10),@lDN8 nvarchar(10),@lDN9 nvarchar(10),@lDN10 nvarchar(10),
	@lDN11 nvarchar(10),@lDN12 nvarchar(10),@lDN13 nvarchar(10),@lDN14 nvarchar(10),@lDN15 nvarchar(10),
	@lDN16 nvarchar(10),@lDN17 nvarchar(10),@lDN18 nvarchar(10),@lDN19 nvarchar(10),@lDN20 nvarchar(10),
	@lDN21 nvarchar(10),@lDN22 nvarchar(10),@lDN23 nvarchar(10),@lDN24 nvarchar(10),@lDN25 nvarchar(10),
	@lDN26 nvarchar(10),@lDN27 nvarchar(10),@lDN28 nvarchar(10),@lDN29 nvarchar(10),@lDN30 nvarchar(10),
	@lDN31 nvarchar(10)
	
	SET @lDN1 = '01 ' + substring(DATENAME( dw, convert( date, ( '01' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN2 = '02 ' + substring(DATENAME( dw, convert( date, ( '02' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN3 = '03 ' + substring(DATENAME( dw, convert( date, ( '03' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN4 = '04 ' + substring(DATENAME( dw, convert( date, ( '04' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN5 = '05 ' + substring(DATENAME( dw, convert( date, ( '05' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN6 = '06 ' + substring(DATENAME( dw, convert( date, ( '06' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN7 = '07 ' + substring(DATENAME( dw, convert( date, ( '07' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN8 = '08 ' + substring(DATENAME( dw, convert( date, ( '08' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN9 = '09 ' + substring(DATENAME( dw, convert( date, ( '09' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN10 = '10 ' + substring(DATENAME( dw, convert( date, ( '10' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN11 = '11 ' + substring(DATENAME( dw, convert( date, ( '11' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN12 = '12 ' + substring(DATENAME( dw, convert( date, ( '12' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN13 = '13 ' + substring(DATENAME( dw, convert( date, ( '13' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN14 = '14 ' + substring(DATENAME( dw, convert( date, ( '14' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN15 = '15 ' + substring(DATENAME( dw, convert( date, ( '15' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN16 = '16 ' + substring(DATENAME( dw, convert( date, ( '16' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN17 = '17 ' + substring(DATENAME( dw, convert( date, ( '17' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN18 = '18 ' + substring(DATENAME( dw, convert( date, ( '18' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN19 = '19 ' + substring(DATENAME( dw, convert( date, ( '19' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN20 = '20 ' + substring(DATENAME( dw, convert( date, ( '20' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN21 = '21 ' + substring(DATENAME( dw, convert( date, ( '21' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN22 = '22 ' + substring(DATENAME( dw, convert( date, ( '22' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN23 = '23 ' + substring(DATENAME( dw, convert( date, ( '23' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN24 = '24 ' + substring(DATENAME( dw, convert( date, ( '24' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN25 = '25 ' + substring(DATENAME( dw, convert( date, ( '25' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN26 = '26 ' + substring(DATENAME( dw, convert( date, ( '26' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN27 = '27 ' + substring(DATENAME( dw, convert( date, ( '27' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN28 = '28 ' + substring(DATENAME( dw, convert( date, ( '28' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN29 = case when @Days >= 29 then '29 ' + substring(DATENAME( dw, convert( date, ( '29' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end
	SET @lDN30 = case when @Days >= 30 then '30 ' + substring(DATENAME( dw, convert( date, ( '30' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end
	SET @lDN31 = case when @Days < 31 Then '' else '31 ' + substring(DATENAME( dw, convert( date, ( '31' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end

	SELECT 
		datediff(day, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE),
		dateadd(month, 1, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE))) AS DayCount,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		
		@lDN1 as DN1,@lDN2 as DN2,@lDN3 as DN3,@lDN4 as DN4,@lDN5 as DN5,@lDN6 as DN6,@lDN7 as DN7,@lDN8 as DN8,@lDN9 as DN9,@lDN10 as DN10,
		@lDN11 as DN11,@lDN12 as DN12,@lDN13 as DN13,@lDN14 as DN14,@lDN15 as DN15,@lDN16 as DN16,@lDN17 as DN17,@lDN18 as DN18,@lDN19 as DN19,
		@lDN20 as DN20,@lDN21 as DN21,@lDN22 as DN22,@lDN23 as DN23,@lDN24 as DN24,@lDN25 as DN25,@lDN26 as DN26,@lDN27 as DN27,@lDN28 as DN28,	@lDN29 as DN29,@lDN30 as DN30,@lDN31 AS DN31,
		
		S.Code,	
		--E.ShortName,
		--DM.Displaytitle DeptName,
		--DM.Code AS DeptCode,
		S.OrgID,
		--DM.Id AS DepartmentId,
		--EDM.Title AS Designation,
		--EDM.Code AS DesignationCode,
		--@rIsFirstIn AS IsFirstIn,
		--@rIsLastOut AS IsLastOut,
		--@rIsOT AS IsOT,
		--@rIsLateBy	AS IsLateBy,
		--@rIsEarlyBy AS IsEarlyBy,
		--@rIsDuration  AS IsDuration,
		S.FirstName +' ' + S.MiddleName +' '+ S.LastName AS Name,
		--sBiometric.fEmployeeLeaveTypeGet(Attn_Dt,T.EmployeeId) AS LeaveStatus,
		--ISNULL(sBiometric.fEmployeeCLTypeGet(@rForMonth,@rForYear,T.EmployeeId),'') AS CLeaveStatus,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,1,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D01,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,2,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D02,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,3,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D03,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,4,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D04,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,5,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D05,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,6,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D06,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,7,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D07,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,8,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D08,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,9,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D09,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,10,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D10,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,11,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D11,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,12,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D12,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,13,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D13,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,14,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D14,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,15,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D15,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,16,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D16,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,17,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D17,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,18,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D18,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,19,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D19,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,20,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D20,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,21,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D21,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,22,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D22,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,23,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D23,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,24,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D24,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,25,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D25,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,26,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D26,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,27,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D27,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,28,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D28,
		--case when @Days >= 29 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D29,
		--case when @Days >= 30 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D30,
		--case when @Days >= 31 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D31,

		Attn_Dt, 
		
		D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, 
		D16_IN, D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, 
		D01_OUT, D02_OUT, D03_OUT, D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, D12_OUT, D13_OUT, D14_OUT, D15_OUT, 
		D16_OUT, D17_OUT, D18_OUT, D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, D30_OUT, D31_OUT, 
		D01_O, D02_O, D03_O, D04_O, D05_O, D06_O, D07_O, D08_O, D09_O, D10_O, D11_O, D12_O, D13_O, D14_O, D15_O, 
		D16_O, D17_O, D18_O, D19_O, D20_O, D21_O, D22_O, D23_O, D24_O, D25_O, D26_O, D27_O, D28_O, D29_O, D30_O, D31_O, 
		D01_L, D02_L, D03_L, D04_L, D05_L, D06_L, D07_L, D08_L, D09_L, D10_L, D11_L, D12_L, D13_L, D14_L, D15_L, 
		D16_L, D17_L, D18_L, D19_L, D20_L, D21_L, D22_L, D23_L, D24_L, D25_L, D26_L, D27_L, D28_L, D29_L, D30_L, D31_L, 
		D01_T, D02_T, D03_T, D04_T, D05_T, D06_T, D07_T, D08_T, D09_T, D10_T, D11_T, D12_T, D13_T, D14_T, D15_T, 
		D16_T, D17_T, D18_T, D19_T, D20_T, D21_T, D22_T, D23_T, D24_T, D25_T, D26_T, D27_T, D28_T, D29_T, D30_T, D31_T, 
		D01_E, D02_E, D03_E, D04_E, D05_E, D06_E, D07_E, D08_E, D09_E, D10_E, D11_E, D12_E, D13_E, D14_E, D15_E, 
		D16_E, D17_E, D18_E, D19_E, D20_E, D21_E, D22_E, D23_E, D24_E, D25_E, D26_E, D27_E, D28_E, D29_E, D30_E, D31_E, 
		D01_S, D02_S, D03_S, D04_S, D05_S, D06_S, D07_S, D08_S, D09_S, D10_S, D11_S, D12_S, D13_S, D14_S, D15_S, 
		D16_S, D17_S, D18_S, D19_S, D20_S, D21_S, D22_S, D23_S, D24_S, D25_S, D26_S, D27_S, D28_S, D29_S, D30_S, D31_S, 
		Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, TotalHour, Tot_HD, Tot_Early, Tot_Late, Tot_OT, Tot_OD, Tot_Leave, 
		Count_Late, Count_Early, Count_OT, Tot_CL, Tot_SL, Tot_EL, Tot_SP, Tot_C, Tot_PL, Tot_ML, T.EmployeeId,OM.Title AS OrganizationTitle,
		ISNULL(S.PunchId,'') AS PunchId
		--E.Number as EMPNumber            --Mantis - 30977
	FROM 
		sBiometric.tMonthTrans T
		INNER JOIN sStudent.tAcademic A ON A.Id = T.EmployeeId
		INNER JOIN sStudent.tStudentMaster S on S.Id = A.StudentId
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = S.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = S.OrgId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		--LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	WHERE 
		(S.OrgId=@rOrgId OR @rOrgId = 0)
		--AND (DM.Id = @rDeptId OR @rDeptId = 0)
		AND (T.Attn_dt = @lATTN_DATE)
		AND (MONTH(SA.LeftDate) >= @rForMonth AND YEAR(SA.LeftDate) >= @rForYear OR SA.LeftDate Is null)
		AND (S.StatusId = @rStatusId OR ISNULL(@rStatusId,0)=0)
		--AND ISNULL(E.IsOtherUser,0) = 0 
		AND ISNULL(T.SourceTypeId,2001) = 2001
		AND (T.EmployeeId = @rAcademicId OR @rAcademicId = 0)
		AND (CM.Id = @rClassId OR @rClassId = 0)
		AND (DM.Id = @rDivisionId OR @rDivisionId = 0)
		--AND OM.OrgGroupId = @rOrgGroupId
		--AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 
	ORDER BY 
	S.Code,T.Attn_dt
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptStudentMonthlySummaryListGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rForYear int,
	@rForMonth int, 
	@rStudentId bigint,
	@rClassId int,
	@rDivisionId int,
	--@rAttendanceTypeId tinyint,
	--@rAttendanceDate date=0,
	-- @rRepeatCount tinyint,
	@rOrgGroupBatchId int=0,
	@rTimeSheetStatus nvarchar(10) = '0',
	@rDepartmentId int=0,
	@rStatusId int=0,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rAcademicId bigint=0		--Mantis: 34829, add by dhruvik
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
DECLARE @lBatchID int
declare @Days int
Declare @rFromDate datetime
Declare @rToDate datetime
CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	
	)

	 select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
 set @rFromDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @rToDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), @Days)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId = 2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime))) 
		AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END

	Update TM set PresentStatus = CASE When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 ELSE TM.PresentStatus END
		From #TempMonthTrans TM
		INNER JOIN sStudent.vStudentAcademic SA  ON SA.AcademicId = TM.EmployeeId		--Mantis: 34829, change by dhruvik, from SA.StudentId => SA.AcademicId


	Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2 ,
		SA.AcademicId AS AcademicId,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS TotalAbsentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS TotalWeekOffs,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS TotalHolidays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS TotalPresentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS TotalHalfDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS TotalLessHours,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS TotalErrorCase,
		OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays
				
		From sBiometric.tMonthTrans MT  
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.AcademicId = MT.EmployeeId AND MT.SourceTypeId=2001 --AND MT.ATTN_DT = cast(rtrim(YEAR(@rAttendanceDate) *10000+ Month(@rAttendanceDate)  *100+ 01) as datetime)		--Mantis: 34829, change by dhruvik, from SA.StudentId => SA.AcademicId and 2003 => 2001
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id  AND BM.OrgGroupBatchId=@rOrgGroupBatchId --AND BM.IsActive=1
	WHERE 
		((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND OM.OrgGroupId=@rOrgGroupId
			AND (SA.OrgId=@rOrgId OR @rOrgId=0)
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 --AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
			AND (SA.OrgId = @rOrgId OR @rOrgId = 0)
			 AND((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (SA.AcademicId = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, add by dhruvik
	ORDER BY SA.RollNo

	DROP Table #TempMonthTrans	


	--Select
	--	@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2 , 
	--	CAST(0 AS bigint) AS AcademicId,
	--	'' AS StudentCode,
	--	'' AS StudentName,
	--	0 as RollNo,
	--	0 AS TotalAbsentDays,
	--	0 AS TotalWeekOffs,
	--	0 AS TotalHolidays,
	--	0 AS TotalPresentDays,
	--	0 AS TotalHalfDays,
	--	0 AS TotalLessHours,
	--	0 AS TotalErrorCase,
	--	'' AS ClassName,
	--	0 AS ClassId,
	--	'' AS DivisionName,
	--	0 AS DivisionId,
	--	'' AS Department,
	--	0 AS DepartmentId,
	--	'' As ClassDivision,
	--	0 AS OrderIndex,
	--	0 AS DivisionOrderIndex,
	--	'' AS Organization,
	--	0 AS OrgId,
	--	0 AS TotalDays
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sBiometric].[pRptStudentPunchIdGet]
 @rOrgId int ,
 @rBuilder1 nvarchar(max)='',
 @rBuilder2 nvarchar(max)='',
 @rStatusId int=1,
 @rDepartmentId int=0,
 @rClassId int=0,
 @rDivisionId int=0,
 @rIsAll bit=0,
 @rIsMissingPunch bit=0,
 @rOrgGroupId int,
 @rOrgGroupBatchId int=0

 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
Begin
	select 
			@rBuilder1 as Builder1,
			@rBuilder2 as Builder2,
			@rIsAll as IsAll,
			SA.Name AS Name, 
			PunchId AS PunchID,
			SM.StatusId as ActiveStatus,
			SM.Id as SourceId,
			SM.OrgId as OrgId ,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code,
			CM.DisplayTitle AS ClassName,
			CM.Id AS ClassId,
			DM.DisplayTitle AS DivisionName,
			DM.Id AS DivisionId,
			Dept.DisplayTitle AS Department,
			Dept.Id AS DepartmentId,
			CM.Title+'-'+DM.DisplayTitle As ClassDivision,
			SA.RollNo AS RollNo,
			Dept.OrderIndex AS OrderIndex,
			DM.OrderIndex AS DivisionOrderIndex,
			BM.OrgGroupBatchId
		from sStudent.tStudentMaster SM
			Inner Join sStudent.vStudentAcademic SA On SM.Id=SA.StudentId 
			INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			--AND DM.Id=A.DivisionId AND CM.Id=A.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id AND BM.OrgGroupBatchId=@rOrgGroupBatchId --AND BM.IsActive=1
		where
			OM.OrgGroupId=@rOrgGroupId
			AND (SM.OrgId=@rOrgId OR @rOrgId=0)
			AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
			AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
			AND ( (SM.StatusId =  @rStatusId) OR @rStatusId=0)
			AND(( SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((@rIsAll=0 AND ((@rIsMissingPunch=0 AND SM.PunchId Is not Null) or (@rIsMissingPunch=1 AND SM.PunchId is null))) OR  @rIsAll=1)


End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pRptTimeSheetListGet]
  @rBuilder1 nvarchar(max)='',
  @rBuilder2 nvarchar(max)='',
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rTimeSheetStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rOrgGroupId int,
  @rEmployeeStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0,
  @rGradeId nvarchar(max)= '0'

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 

CREATE TABLE #TempMonthTrans  
 (  
 Id int,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25)  
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lBatchID int
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)

 INSERT INTO #TempMonthTrans 
  select *
   from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rOrganizationDepartmentId ,@rFromDate,@rToDate,@rEmployeeId)  
 

		
	 SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 as Builder2,
		TM.Id,
		TM.EmployeeId,
		TM.Attn_Date,
		OGD.Title AS [OrganizationGroupDepartment],
		TM.PresentStatus as PresentStatus,
		TM.FirstIn,
		TM.LastOut,
		TM.OverTime,
		TM.LateBy,
		TM.Duration,
		TM.EarlyBy,
		TM.ShiftName,
		 MT.Tot_Attn,
		 EM.FirstName + ' ' + EM.LastName As ShortName,
		 EM.Code as EmpCode ,   
		[sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,  
		ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
		ISNULL(SM.Id,0) AS StatusId,  
		ISNULL(SM.Title,'') AS Status ,
		 OM.Id AS OrgId,
		OM.Title AS OrganizationTitle,
		LRM.Title as LeaveReason  --mantis - 35817 
	 FROM #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
	 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId  
	 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
	 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId  
	 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01'))
	 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
	 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	 LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=Tm.EmployeeId AND EAR.AttendanceDate=TM.Attn_Date			--mantis - 35817 
	 LEFT JOIN sHrm.tLeaveReasonMaster LRM ON LRM.Id = EAR.AbsentReasonId		--mantis - 35817 
	 WHERE   
	 TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate    
	 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
	 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
	 AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
	 AND (EM.OrgId = @rOrgId OR @rOrgId = 0)
	 AND (OM.OrgGroupId = @rOrgGroupId)
	 AND ((EM.StatusId = @rEmployeeStatusId) OR (@rEmployeeStatusId = 0))
	 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
	 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
	 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
	 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	 AND (EmployeeGradeId in ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGradeId,',')) OR @rGradeId=0) 
	 Order By TM.EmployeeId,TM.Attn_Date

 --SELECT  @rBuilder1 AS Builder1,
	--@rBuilder2 as Builder2,
	--0 as Id,
	--CAST(0 AS bigint) AS EmployeeId,
	--CAST('1999-01-01 00:00:00' AS datetime) as Attn_Date,
	--'' AS OldPresentStatus,
	--'' AS [OrganizationGroupDepartment],
	--'' as PresentStatus,
	--'' as FirstIn,
	--'' AS LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as ShiftName, 
	--'' As ShortName,
	--'' as EmpCode ,
	--'' AS LeaveStatus , 
	--'' AS LeavePendingStatus, 
	--'' AS EmployeeTravel,
	--0 AS EmployeeLateStatusId, 
	--0 AS StatusId, 
	--'' AS Status,
	--0 AS OrgId,
	--  '' AS OrganizationTitle,
	-- '' AS LeaveReason		--mantis - 35817 

 end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sBiometric].[pRptTimesheetSummaryListGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int = 0,
	@rDeptId int = 0,
	@rForYear int=0,
	@rForMonth int=0,	 
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0,
	@rOrgGroupId int = 0,
	@OrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
 
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 LateBy nvarchar(20),   
 EarlyBy nvarchar(20), 
 )  
  INSERT INTO #TempMonthTrans  
   
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN = '00:00' THEN 'H'   
			 WHEN (D01 = 'W' OR D01 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN = '00:00' THEN 'A' 
			 WHEN (D01 = 'H' OR D01 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN = '00:00' THEN 'A' 
			 --WHEN  AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'  
			 --WHEN D01 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 When ((D01='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D01_IN ='00:00'))  then 'A'
			 ELSE D01 END ,	
	D01_L,D01_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	
	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN = '00:00' THEN 'H'   
			 WHEN (D02 = 'W' OR D02 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN = '00:00' THEN 'A' 
			 WHEN (D02 = 'H' OR D02 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN = '00:00' THEN 'A' 
			 --WHEN D02 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'  
			 --WHEN D02 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			  When ((D02='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D02_IN ='00:00'))  then 'A'
			 ELSE D02 END ,	
	D02_L,D02_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN = '00:00' THEN 'H'   
			 WHEN (D03 = 'W' OR D03 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN = '00:00' THEN 'A' 
			 WHEN (D03 = 'H' OR D03 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN = '00:00' THEN 'A' 
			 --WHEN D03 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'  
			 --WHEN D03 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 When ((D03='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D03_IN ='00:00'))  then 'A'
			 ELSE D03 END ,	
	D03_L,D03_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN = '00:00' THEN 'H'   
			 WHEN (D04 = 'W' OR D04 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN = '00:00' THEN 'A' 
			 WHEN (D04 = 'H' OR D04 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN = '00:00' THEN 'A' 
			 --WHEN D04 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'  
			 --WHEN D04 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 When ((D04='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D04_IN ='00:00'))  then 'A'
			 ELSE D04 END ,	
	D04_L,D04_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN = '00:00' THEN 'H'   
			 WHEN (D05 = 'W' OR D05 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN = '00:00' THEN 'A' 
			 WHEN (D05 = 'H' OR D05 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN = '00:00' THEN 'A' 
			 --WHEN D05 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'  
			 --WHEN D05 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			  When ((D05='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D05_IN ='00:00'))  then 'A'
			 ELSE D05 END ,	
	D05_L,D05_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN = '00:00' THEN 'H'   
			 WHEN (D06 = 'W' OR D06 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN = '00:00' THEN 'A' 
			 WHEN (D06 = 'H' OR D06 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN = '00:00' THEN 'A' 
			 --WHEN D06 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'  
			 --WHEN D06 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			  When ((D06='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D04_IN ='00:00'))  then 'A'
			 ELSE D06 END ,	
	D06_L,D06_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN = '00:00' THEN 'H'   
			 WHEN (D07 = 'W' OR D07 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN = '00:00' THEN 'A' 
			 WHEN (D07 = 'H' OR D07 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN = '00:00' THEN 'A' 
			 --WHEN D07 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'  
			 --WHEN D07 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			  When ((D07='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D07_IN ='00:00'))  then 'A'
			 ELSE D07 END ,	
	D07_L,D07_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN = '00:00' THEN 'H'   
			 WHEN (D08 = 'W' OR D08 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN = '00:00' THEN 'A' 
			 WHEN (D08 = 'H' OR D08 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN = '00:00' THEN 'A' 
			 --WHEN D08 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'  
			 --WHEN D08 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			  When ((D08='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D08_IN ='00:00'))  then 'A'
			 ELSE D08 END ,	
	D08_L,D08_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN = '00:00' THEN 'H'   
			 WHEN (D09 = 'W' OR D09 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN = '00:00' THEN 'A' 
			 WHEN (D09 = 'H' OR D09 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN = '00:00' THEN 'A' 
			 --WHEN D09 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'  
			 --WHEN D09 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			  When ((D09='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D09_IN ='00:00'))  then 'A'
			 ELSE D09 END ,	
	D09_L,D09_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN = '00:00' THEN 'H'   
			 WHEN (D10 = 'W' OR D10 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN = '00:00' THEN 'A' 
			 WHEN (D10 = 'H' OR D10 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN = '00:00' THEN 'A' 
			 --WHEN D10 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'  
			 --WHEN D10 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			  When ((D10='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D10_IN ='00:00'))  then 'A'
			 ELSE D10 END ,	
	D10_L,D10_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1	

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN = '00:00' THEN 'H'   
			 WHEN (D11 = 'W' OR D11 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN = '00:00' THEN 'A' 
			 WHEN (D11 = 'H' OR D11 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN = '00:00' THEN 'A' 
			 --WHEN D11 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'  
			 --WHEN D11 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			  When ((D11='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D11_IN ='00:00'))  then 'A'
			 ELSE D11 END ,
	D11_L,D11_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN = '00:00' THEN 'H'   
			 WHEN (D12 = 'W' OR D12 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN = '00:00' THEN 'A' 
			 WHEN (D12 = 'H' OR D12 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN = '00:00' THEN 'A' 
			 --WHEN D12 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'  
			 --WHEN D12 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			  When ((D12='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D12_IN ='00:00'))  then 'A'
			 ELSE D12 END ,	
	D12_L,D12_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN = '00:00' THEN 'H'   
			 WHEN (D13 = 'W' OR D13 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN = '00:00' THEN 'A' 
			 WHEN (D13 = 'H' OR D13 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN = '00:00' THEN 'A' 
			 --WHEN D13 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'  
			 --WHEN D13 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			  When ((D13='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D13_IN ='00:00'))  then 'A'
			 ELSE D13 END ,	
	D13_L,D13_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN = '00:00' THEN 'H'   
			 WHEN (D14 = 'W' OR D14 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN = '00:00' THEN 'A' 
			 WHEN (D14 = 'H' OR D14 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN = '00:00' THEN 'A' 
			 --WHEN D14 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'  
			 --WHEN D14 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			  When ((D14='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D14_IN ='00:00'))  then 'A'
			 ELSE D14 END ,	
	D14_L,D14_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN = '00:00' THEN 'H'   
			 WHEN (D15 = 'W' OR D15 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN = '00:00' THEN 'A' 
			 WHEN (D15 = 'H' OR D15 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN = '00:00' THEN 'A' 
			 --WHEN D15 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'  
			 --WHEN D15 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			  When ((D15='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D15_IN ='00:00'))  then 'A'
			 ELSE D15 END ,	
	D15_L,D15_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN = '00:00' THEN 'H'   
			 WHEN (D16 = 'W' OR D16 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN = '00:00' THEN 'A' 
			 WHEN (D16 = 'H' OR D16 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN = '00:00' THEN 'A' 
			 --WHEN D16 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'  
			 --WHEN D16 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			  When ((D16='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D16_IN ='00:00'))  then 'A'
			 ELSE D16 END ,	
	D16_L,D16_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN = '00:00' THEN 'H'   
			 WHEN (D17 = 'W' OR D17 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN = '00:00' THEN 'A' 
			 WHEN (D17 = 'H' OR D17 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN = '00:00' THEN 'A' 
			 --WHEN D17 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'  
			 --WHEN D17 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			  When ((D17='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D17_IN ='00:00'))  then 'A'
			 ELSE D17 END ,	
	D17_L,D17_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN = '00:00' THEN 'H'   
			 WHEN (D18 = 'W' OR D18 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN = '00:00' THEN 'A' 
			 WHEN (D18 = 'H' OR D18 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN = '00:00' THEN 'A' 
			 --WHEN D18 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'  
			 --WHEN D18 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			  When ((D18='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D18_IN ='00:00'))  then 'A'
			 ELSE D18 END ,	
	D18_L,D18_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN = '00:00' THEN 'H'   
			 WHEN (D19 = 'W' OR D19 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN = '00:00' THEN 'A' 
			 WHEN (D19 = 'H' OR D19 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN = '00:00' THEN 'A' 
			 --WHEN D19 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'  
			 --WHEN D19 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			  When ((D19='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D19_IN ='00:00'))  then 'A'
			 ELSE D19 END ,	
	D19_L,D19_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN = '00:00' THEN 'H'   
			 WHEN (D20 = 'W' OR D20 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN = '00:00' THEN 'A' 
			 WHEN (D20 = 'H' OR D20 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN = '00:00' THEN 'A' 
			 --WHEN D20 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'  
			 --WHEN D20 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			  When ((D20='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D20_IN ='00:00'))  then 'A'
			 ELSE D20 END ,		
	D20_L,D20_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN = '00:00' THEN 'H'   
			 WHEN (D21 = 'W' OR D21 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN = '00:00' THEN 'A' 
			 WHEN (D21 = 'H' OR D21 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN = '00:00' THEN 'A' 
			 --WHEN D21 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'  
			 --WHEN D21 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			  When ((D21='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D21_IN ='00:00'))  then 'A'
			 ELSE D21 END ,	
	D21_L,D21_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN = '00:00' THEN 'H'   
			 WHEN (D22 = 'W' OR D22 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN = '00:00' THEN 'A' 
			 WHEN (D22 = 'H' OR D22 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN = '00:00' THEN 'A' 
			 --WHEN D22 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'  
			 --WHEN D22 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			  When ((D22='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D22_IN ='00:00'))  then 'A'
			 ELSE D22 END ,		
	D22_L,D22_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN = '00:00' THEN 'H'   
			 WHEN (D23 = 'W' OR D23 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN = '00:00' THEN 'A' 
			 WHEN (D23 = 'H' OR D23 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN = '00:00' THEN 'A' 
			 --WHEN D23 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'  
			 --WHEN D23 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			  When ((D23='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D23_IN ='00:00'))  then 'A'
			 ELSE D23 END ,	
	D23_L,D23_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN = '00:00' THEN 'H'   
			 WHEN (D24 = 'W' OR D24 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN = '00:00' THEN 'A' 
			 WHEN (D24 = 'H' OR D24 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN = '00:00' THEN 'A' 
			 --WHEN D24 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'  
			 --WHEN D24 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			  When ((D24='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D24_IN ='00:00'))  then 'A'
			 ELSE D24 END ,	
	D24_L,D24_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN = '00:00' THEN 'H'   
			 WHEN (D25 = 'W' OR D25 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN = '00:00' THEN 'A' 
			 WHEN (D25 = 'H' OR D25 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN = '00:00' THEN 'A' 
			 --WHEN D25 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'  
			 --WHEN D25 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			  When ((D25='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D25_IN ='00:00'))  then 'A'
			 ELSE D25 END ,	
	D25_L,D25_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN = '00:00' THEN 'H'   
			 WHEN (D26 = 'W' OR D26 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN = '00:00' THEN 'A' 
			 WHEN (D26 = 'H' OR D26 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN = '00:00' THEN 'A' 
			 --WHEN D26 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'  
			 --WHEN D26 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			  When ((D26='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D26_IN ='00:00'))  then 'A'
			 ELSE D26 END ,	
	D26_L,D26_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN = '00:00' THEN 'H'   
			 WHEN (D27 = 'W' OR D27 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN = '00:00' THEN 'A' 
			 WHEN (D27 = 'H' OR D27 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN = '00:00' THEN 'A' 
			 --WHEN D27 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'  
			 --WHEN D27 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			  When ((D27='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D27_IN ='00:00'))  then 'A'
			 ELSE D27 END ,	
	D27_L,D27_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN = '00:00' THEN 'H'   
			 WHEN (D28 = 'W' OR D28 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN = '00:00' THEN 'A' 
			 WHEN (D28 = 'H' OR D28 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN = '00:00' THEN 'A' 
			 --WHEN D28 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'  
			 --WHEN D28 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			  When ((D28='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D28_IN ='00:00'))  then 'A'
			ELSE D28 END ,	D28_L,D28_E
			FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
			AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1


	IF  @rForMonth <> 2 or ((@rForYear % 4 = 0 AND @rForYear % 100 <> 0) OR @rForYear % 400 = 0 And @rForMonth  =2)
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN = '00:00' THEN 'H'   
			 WHEN (D29 = 'W' OR D29 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN = '00:00' THEN 'A' 
			 WHEN (D29 = 'H' OR D29 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN = '00:00' THEN 'A' 
			 --WHEN D29 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'  
			 --WHEN D29 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			  When ((D29='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D29_IN ='00:00'))  then 'A'
			 ELSE D29 END ,	
	D29_L,D29_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	
	IF @rForMonth <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN = '00:00' THEN 'H'   
			 WHEN (D30 = 'W' OR D30 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN = '00:00' THEN 'A' 
			 WHEN (D30 = 'H' OR D30 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN = '00:00' THEN 'A' 
			 --WHEN D30 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'  
			 --WHEN D30 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			  When ((D30='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D30_IN ='00:00'))  then 'A'
			 ELSE D30 END ,	
	D30_L,D30_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	
	IF @rForMonth NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT TM.EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN = '00:00' THEN 'H'   
			 WHEN (D31 = 'W' OR D31 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN = '00:00' THEN 'A' 
			 WHEN (D31 = 'H' OR D31 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN = '00:00' THEN 'A' 
			 --WHEN D31 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'  
			 --WHEN D31 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			  When ((D31='XX')AND (Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date)<GETDATE()) 
								And (cast(EJD.DateOfJoining as date)<= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date) OR ISNULL(EJD.DateOfJoining,'')='')
								AND (EJD.DateOfleaving>= Cast(cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime) as date) OR ISNULL(EJD.DateOfleaving,'')='') 
					AND (D31_IN ='00:00'))  then 'A'
			 ELSE D31 END ,	
	D31_L,D31_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	            WHERE (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	--select * from #TempMonthTrans

	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		EM.Code as EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
		MT.Tot_Attn  AS TotalPresentDays,
		MT.Tot_Abs AS TotalAbsentDays,
		MT.Tot_WeekOFF AS TotalWeekOffs,
		MT.Tot_Holiday AS TotalHolidays,
		OM.Id AS OrganizationId,
		OM.DisplayTitle AS OrganizationTitle,
		OM.OrderIndex AS OrganizationOrderIndex,
		EM.Number AS EmployeeNumber,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
		MT.Count_Late AS Count_Late,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS WeekOffsWiseTotalAbsentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS WeekOffsWiseTotalWeekOffs,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS WeekOffsWiseTotalHolidays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS WeekOffsWiseTotalPresentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS WeekOffsWiseTotalHalfDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS WeekOffsWiseTotalLessHours,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS WeekOffsWiseTotalErrorCase

	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	WHERE
	(EM.OrgId = @rOrgId OR @rOrgId = 0)
	AND YEAR(MT.Attn_Dt) = @rForYear
	AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND (EJD.OrganizationDepartmentId = @rDeptId OR @rDeptId = 0)		 	
	AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	AND ISNULL(EM.IsOtherUser,0) = 0 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND (OM.OrgGroupId = @rOrgGroupId)
	AND ((EJD.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 

	DROP Table #TempMonthTrans

	--SELECT
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	cast(0 as bigint) as EmployeeId,
	--	'' as EmpCode,
	--	'' AS EmployeeName,  
	--	cast(0 as float)  AS TotalPresentDays,
	--	cast(0 as float) AS TotalAbsentDays,
	--	cast(0 as int) AS TotalWeekOffs,
	--	cast(0 as int) AS TotalHolidays,
	--	cast(0 as smallint) AS OrganizationId,
	--	'' AS OrganizationTitle,
	--	cast(0 as int) AS OrganizationOrderIndex,
	--	cast(0 as bigint) AS EmployeeNumber,
	--	cast(0 as int) AS TotalDays,
	--	cast(0 as int) AS Count_Late,
	--	cast(0 as int) AS WeekOffsWiseTotalAbsentDays,
	--	cast(0 as int) AS WeekOffsWiseTotalWeekOffs,
	--	cast(0 as int) AS WeekOffsWiseTotalHolidays,
	--	cast(0 as int) AS WeekOffsWiseTotalPresentDays,
	--	cast(0 as int) AS WeekOffsWiseTotalHalfDays,
	--	cast(0 as int) AS WeekOffsWiseTotalLessHours,
	--	cast(0 as int) AS WeekOffsWiseTotalErrorCase
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sBiometric].[pShiftAllocationCloudAdd] @rXmlDoc=''
CREATE OR ALTER PROCEDURE [sBiometric].[pShiftAllocationCloudAdd]
	
		@rXmlDoc nvarchar(MAX)
	
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT
			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	-----------------------
	CREATE TABLE #tTable  
	(
		SourceId bigint not null
		,SourceTypeId smallint null
		,ShiftCode int null
		,ShiftDay tinyint null		
		,FromShiftDate Datetime null
		,ToShiftDate DateTime null
		,ShiftAllocationId int null
	)

	INSERT INTO #tTable
			   (			    
				SourceId
				,SourceTypeId
				,ShiftCode 
				,ShiftDay 		
				,FromShiftDate 
				,ToShiftDate  
				,ShiftAllocationId 
			   )
	SELECT		
		
		A.SourceId,
		A.SourceTypeId,
		ShiftCode,
		ShiftDay,
		FromShiftDate,
		ToShiftDate,
		ShiftAllocationId
		
	FROM OPENXML (@intDoc, '/Table/ShiftAllocationCloud', 1)
	WITH
	(	
		SourceId bigint '@SourceId'
		,SourceTypeId smallint '@SourceTypeId'
		,ShiftCode int '@ShiftCode'
		,ShiftDay tinyint '@ShiftDay'	
		,FromShiftDate Datetime '@FromShiftDate'
		,ToShiftDate DateTime '@ToShiftDate'
		,ShiftAllocationId int	'@ShiftAllocationId'
	)A 
	select  @intDoc
	INSERT INTO sBiometric.tShiftAllocationCloud
	(
		SourceId,
		SourceTypeId,
		ShiftCode,
		ShiftDay,
		FromShiftDate,
		ToShiftDate
	)
	SELECT
		A.SourceId,
		A.SourceTypeId,
		A.ShiftCode,
		A.ShiftDay,
		A.FromShiftDate,
		A.ToShiftDate				
	FROM #tTable A 
	 WHERE A.SourceId Not in (SELECT SourceId From sBiometric.tShiftAllocationCloud  Where SourceId=A.SourceId  AND SourceTypeId=A.SourceTypeId AND (ShiftDay=A.ShiftDay AND FromShiftDate = A.FromShiftDate))
	 And A.ShiftAllocationId=0
	 --And A.SourceTypeId Not in (SELECT SourceTypeId From sBiometric.tShiftAllocationCloud Where SAC.ShiftDay=A.ShiftDay AND SAC.SourceId=A.SourceId AND SAC.FromShiftDate = A.FromShiftDate)
	
	
	--SELECT * From #tTable
	UPDATE SAC SET SAC.ShiftCode = A.ShiftCode,
				   SAC.ShiftDay=A.ShiftDay,
					SAC.FromShiftDate=A.FromShiftDate,
					SAC.ToShiftDate=A.ToShiftDate
	FROM 
	#tTable A 
	INNER JOIN sBiometric.tShiftAllocationCloud SAC ON SAC.SourceId = A.SourceId AND SAC.SourceTypeId = A.SourceTypeId and SAC.Id=A.ShiftAllocationId
	--WHERE A.Id  in (SELECT SourceId From sBiometric.tShiftAllocationCloud Where ShiftDay=A.ShiftDay AND SourceId=A.SourceId AND FromShiftDate = A.FromShiftDate)
	


	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
END TRY
	BEGIN CATCH
		SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sBiometric].[pShiftAllocationCloudGet]

@rOrgId int = 0,
@rSourceTypeId smallint = 0,
@rSerchBy int=1 --1 for ByDay, 2 For ByDate
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF (@rSourceTypeId=95)
	BEGIN
		SELECT 

			EM.Id AS EmployeeId,
			0 as StudentId,
			'' as StudentCode,
			'' as StudentName,
			EM.Code AS EmployeeCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,
			ISNULL(EM.ShiftId,0) AS CurrentShiftId,
			ISNULL(SA.ShiftCode,0) AS NewShiftId,
			ISNULL(SA.FromShiftDate,'') AS FromShiftDate,
			ISNULL(SA.ToShiftDate,'') AS ToShiftDate,
			ISNULL(SA.ShiftDay,0) AS ShiftDay,
			ISNULL(SA.Id,0) as ShiftAllocationId
		FROM 
			sHrm.tEmployeeMaster EM
			LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = EM.ShiftId
			Inner JOIN sBiometric.tShiftAllocationCloud SA ON SA.SourceId = EM.Id AND SA.SourceTypeId=95 
				AND ((@rSerchBy=1 And SA.ShiftDay<>0 ) or (@rSerchBy=2 And SA.ShiftDay=0))
		WHERE
			EM.OrgID = @rOrgId AND EM.StatusId=7
		Union All
			SELECT 

			EM.Id AS EmployeeId,
			0 as StudentId,
			'' as StudentCode,
			'' as StudentName,
			EM.Code AS EmployeeCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,
			ISNULL(EM.ShiftId,0) AS CurrentShiftId,
			0 AS NewShiftId,
			'' AS FromShiftDate,
			'' AS ToShiftDate,
			0 AS ShiftDay,
			0 as ShiftAllocationId
		FROM 
			sHrm.tEmployeeMaster EM
			LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = EM.ShiftId
			
		WHERE
			EM.OrgID = @rOrgId AND EM.StatusId=7

		Order by EmployeeId,ShiftAllocationId
			
	END
ELSE IF(@rSourceTypeId=2003)
	BEGIN
			SELECT 
				SM.Id AS StudentId,
				SM.Code AS StudentCode,
				SM.FirstName + ' ' + SM.LastName AS StudentName,
				ISNULL(SM.ShiftId,0) AS CurrentShiftId,
				ISNULL(SA.ShiftCode,0) AS NewShiftId,
				ISNULL(SA.FromShiftDate,'') AS FromShiftDate,
				ISNULL(SA.ToShiftDate,'') AS ToShiftDate,
				ISNULL(SA.ShiftDay,0) AS ShiftDay,
				0 as EmployeeId,
				'' as EmployeeCode,
				'' as EmployeeName,
				ISNULL(SA.Id,0) as ShiftAllocationId
			FROM 
				sStudent.tStudentMaster SM
				LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = SM.ShiftId
				Inner JOIN sBiometric.tShiftAllocationCloud SA ON SA.SourceId = SM.Id	AND SA.SourceTypeId=2003
					AND ((@rSerchBy=1 And SA.ShiftDay<>0 ) or (@rSerchBy=2 And SA.ShiftDay=0))
			WHERE
				SM.OrgID = @rOrgId AND SM.StatusId=1
		Union All
			SELECT 
				SM.Id AS StudentId,
				SM.Code AS StudentCode,
				SM.FirstName + ' ' + SM.LastName AS StudentName,
				ISNULL(SM.ShiftId,0) AS CurrentShiftId,
				0 AS NewShiftId,
				'' AS FromShiftDate,
				'' AS ToShiftDate,
				0 AS ShiftDay,
				0 as EmployeeId,
				'' as EmployeeCode,
				'' as EmployeeName,
				0 as ShiftAllocationId
			FROM 
				sStudent.tStudentMaster SM
				LEFT JOIN sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode = SM.ShiftId
				
			WHERE
				SM.OrgID = @rOrgId AND SM.StatusId=1	
			Order by StudentId,ShiftAllocationId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sBiometric].[pShiftMasterCloudAdd]
@rShiftCode int = 0,
@rShiftName nvarchar(50),
@rStartTime DateTime = null,
@rEndTime DateTime = null,
@rGraceBefore int = 0,
@rGraceAfter int = 0,
@rShiftDur nvarchar(16) = NULL,
@rMinHrsHalfDay  nvarchar(16) = null,
@rMinHrsFullDay nvarchar(16) = null,
@rAlterGraceTime int = 0,
@IsOutTimeAlertTime bit = 0,
@OutTimeAlertTime DateTime = null,
@rOrgGroupId int = 0,
@rLastOutAlertBasedOnId int=1,
@rIsStopInTimeAlertTime bit=0,
@rStopInTimeAlertTime DateTime=null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	IF(@rShiftcode = 0)	
		BEGIN
			If Exists(select ShiftCode from sBiometric.tShiftMasterCloud where ShiftName=@rShiftName and OrgGroupId = @rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
			END 
		END
	ELSE
		BEGIN
			If  Exists(select ShiftCode from sBiometric.tShiftMasterCloud where ShiftName=@rShiftName AND Shiftcode<>@rShiftcode and OrgGroupId = @rOrgGroupId)
			Begin
				select -103 as Result
				RETURN
			End
		END	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 IF EXISTS (SELECT 1 FROM sBiometric.tShiftMasterCloud)
	 BEGIN
		SELECT @lNextNumber = Max(ISNULL(ShiftCode,0)) + 1 FROM sBiometric.tShiftMasterCloud
	 END
	 ELSE
	 BEGIN
		SET @lNextNumber = 1
	 END
	 
	IF(@rShiftcode = 0)	
	BEGIN
	Insert into sBiometric.tShiftMasterCloud 
     (ShiftCode
     , ShiftName
     , StartTime
     , EndTime
     , GraceBefore
     , GraceAfter
     , ShiftDur
     , MinHrsHalfDay
     , MinHrsFullDay    
     , AlterGraceTime
     , IsOutTimeAlertTime
     , OutTimeAlertTime
     , OrgGroupId
	 ,LastOutAlertBasedOnId
	 ,IsStopInTimeAlertTime
	 ,StopInTimeAlertTime)
     Values
     (@lNextNumber
     ,@rShiftName
     ,@rStartTime
     ,@rEndTime
     ,@rGraceBefore
     ,@rGraceAfter
     ,@rShiftDur
     ,@rMinHrsHalfDay
     ,@rMinHrsFullDay
     ,@rAlterGraceTime
     ,@IsOutTimeAlertTime
     ,@OutTimeAlertTime
     ,@rOrgGroupId
     ,@rLastOutAlertBasedOnId
	 ,@rIsStopInTimeAlertTime 
	 ,@rStopInTimeAlertTime 
	 )
     
     SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	    UPDATE sBiometric.tShiftMasterCloud
	    SET
			ShiftName=@rShiftName,
			StartTime=@rStartTime,
			EndTime=@rEndTime,
			GraceBefore=@rGraceBefore,
			shiftDur=@rShiftDur,
			MinHrsHalfDay=@rMinHrsHalfDay,
			MinHrsFullDay=@rMinHrsFullDay,
			AlterGraceTime=@rAlterGraceTime,
		    IsOutTimeAlertTime = @IsOutTimeAlertTime,
			OutTimeAlertTime = @OutTimeAlertTime,
			LastOutAlertBasedOnId=@rLastOutAlertBasedOnId,
			IsStopInTimeAlertTime=@rIsStopInTimeAlertTime,
			StopInTimeAlertTime=@rStopInTimeAlertTime,
			GraceAfter=@rGraceAfter
		
	      WHERE ShiftCode = @rShiftcode and OrgGroupId = @rOrgGroupId
	      
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sBiometric].[pShiftMasterCloudDelete]
	@rShiftcode int,
	@rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
	 
  		IF EXISTS( SELECT 1 FROM sHrm.tEmployeeMaster WHERE ShiftId = @rShiftcode)	
		BEGIN
			SELECT 101 AS RESULT
		END	 
		ELSE
		BEGIN
			DELETE FROM sBiometric.tShiftMasterCloud WHERE ShiftCode = @rShiftcode and OrgGroupId = @rOrgGroupId
			SELECT 1 AS RESULT
		END


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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sBiometric].[pShiftMasterCloudGet]
@rShiftCode int = 0,
@rShiftName nvarchar(50) = '',
@rOrgGroupId int = 0

AS
BEGIN

	select [ShiftCode]
      ,[ShiftName]
      ,[StartTime]
      ,[EndTime]
      ,[GraceBefore]
      ,[GraceAfter]
      ,[ShiftDur]
      ,[MinHrsHalfDay]
      ,[MinHrsFullDay]
      ,[RecessDur]
      ,[AlterGraceTime]
      ,[SMSScheduleTime]
      ,[ShiftGroupCode]
      ,[IsOutTimeAlertTime]
      ,[OutTimeAlertTime]
      ,[OrgGroupId]
      ,isnull([LastOutAlertBasedOnId],1) as LastOutAlertBasedOnId
	  ,Isnull(IsStopInTimeAlertTime,0) as IsStopInTimeAlertTime
	 ,StopInTimeAlertTime 
	   from sBiometric.tShiftMasterCloud
	where 
	((ShiftCode = @rShiftCode) OR (@rShiftCode=0))     
	AND ((ShiftName = @rShiftName) OR (@rShiftName=''))     
	AND ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sBiometric].[pShiftMasterDelete]
	@rShiftcode int,
	@rOrgGroupId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
----
	BEGIN TRY
	 BEGIN TRANSACTION	
	 
  		IF EXISTS( SELECT 1 FROM sHrm.tEmployeeMaster WHERE ShiftId = @rShiftcode)	
		BEGIN
			SELECT 101 AS RESULT
		END	
		ELSE IF EXISTS( SELECT 1 FROM sStudent.tStudentMaster WHERE ShiftId = @rShiftcode)	
		BEGIN
			SELECT -102 AS RESULT
		END	
		ELSE IF EXISTS( SELECT 1 FROM  sBiometric.tShiftAllocationCloud WHERE ShiftCode = @rShiftcode)	
		BEGIN
			SELECT -103 AS RESULT
		END 
		ELSE
		BEGIN

			DELETE FROM sBiometric.tShiftMasterCloud WHERE ShiftCode = @rShiftcode and OrgGroupId = @rOrgGroupId
			SELECT 1 AS RESULT
		END


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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sBiometric].[pStudentImportCloudUpdate]

@rXmlDoc nvarchar(max) = ''

AS
SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT,
			@rEmployeeId BIGINT,
			@rDate VARCHAR(20),
			@rCode INT,
			@rTotalML INT = 0,
			@rTotalPL INT = 0			


BEGIN TRY
BEGIN TRANSACTION					
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	
	CREATE TABLE #tTable  
	(
		StudentId bigint not null
		,PunchId varchar(50) null
		,ShiftId varchar(25) null
	)


	INSERT INTO #tTable
			   (			    
			   StudentId			  
			   ,PunchId			  
			   ,ShiftId	   		   
			   )
	SELECT		
		A.StudentId,
		PunchId,
		A.[ShiftId]		
		
	FROM OPENXML (@intDoc, '/Table/StudentImportCloudUpdate', 1)
	WITH
	(						
		StudentId bigint '@StudentId',
		PunchId varchar(50) '@PunchId',
		[ShiftId] varchar(25) '@ShiftId'
	)A 

	--SELECT * FROM #tTable		

	EXEC sp_xml_removedocument @intDoc
	Update SM SET
	PunchId=temp.PunchId,
	ShiftId=temp.ShiftId
	FROM sStudent.tStudentMaster SM INNER join #tTable temp ON temp.StudentId=SM.Id
	SELECT 1 AS RESULT

	DROP TABLE #tTable
COMMIT TRANSACTION

END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pStudentTimeSheetListGe]
	@rOrgGroupId int,
	@rOrgId int,
	 @rFromDate DateTime,  
  @rToDate DateTime, 
	@rStudentId bigint,
	 @rClassId int,
	@rDivisionId int,
	@rOrgGroupBatchId int=0,
	@rTimeSheetStatus nvarchar(10) = '0',
	@rDepartmentId int=0,
	@rStatusId int=0,
	@rBatchId  int
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   

CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	
	)

	
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2003)

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime))) 
		AND ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2003)
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rStudentId OR @rStudentId = 0)
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2003)
	--END

	Update TM set PresentStatus = CASE When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 ELSE TM.PresentStatus END
		From #TempMonthTrans TM
		INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = TM.EmployeeId 


	Select 
		SA.AcademicId AS AcademicId,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS TotalAbsentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS TotalWeekOffs,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS TotalHolidays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS TotalPresentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS TotalHalfDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS TotalLessHours,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS TotalErrorCase,
		 OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId--,
		--DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays
				
		From sBiometric.tMonthTrans MT  
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.StudentId = MT.EmployeeId AND MT.SourceTypeId=2003 --AND MT.ATTN_DT = cast(rtrim(YEAR(@rAttendanceDate) *10000+ Month(@rAttendanceDate)  *100+ 01) as datetime)
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id  AND BM.OrgGroupBatchId=@rOrgGroupBatchId --AND BM.IsActive=1
	WHERE 
		((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND OM.OrgGroupId=@rOrgGroupId
			AND (SA.OrgId=@rOrgId OR @rOrgId=0)
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 --AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
			AND (SA.OrgId = @rOrgId OR @rOrgId = 0)
			 AND((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	ORDER BY SA.RollNo

	DROP Table #TempMonthTrans	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pTimeSheetGet]
	 @rEmployeeId bigint,
	 @rFromDate Date,
	 @rToDate Date,
	 @rStatus nvarchar(10) = '0'

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT @rEmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE EmployeeID = @rEmployeeId
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT @rEmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE EmployeeID = @rEmployeeId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT @rEmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE EmployeeID = @rEmployeeId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	
	
	SELECT TM.*,MT.Tot_Attn + (Tot_HD*0.5)+ Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,
	Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave FROM #TempMonthTrans TM INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	WHERE TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <= @rToDate AND TM.EmployeeId = @rEmployeeId AND MT.Attn_dt=@rFromDate
	AND (PresentStatus = @rStatus OR @rStatus='0')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pTimeSheetListGet]
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rEmployeeName nvarchar(50) = '',
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
  
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25)  
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lBatchID int
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)

		SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
   
 INSERT INTO #TempMonthTrans  
   
 	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	--Mantis Id:28837 Start to check from amd to date month contain 31 days
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END

	IF NOT EXISTS (SELECT * FROM #TempMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND Attn_Date=@rToDate)	--Mantis Id 30042, only "if" condition will be added
	BEGIN
		IF Month(@rToDate) NOT IN (2,4,6,9,11)
		BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND  ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
		END
	END
	--Mantis Id:28837 End


 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId) else D01 end as D01,  
 --D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId) else D02 end as D02,  
 --D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId) else D03 end as D03,  
 --D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId) else D04 end as D04,  
 --D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId) else D05 end as D05,  
 --D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId) else D06 end as D06,  
 --D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId) else D07 end as D07,  
 --D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId) else D08 end as D08,  
 --D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime), case When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId) else D09 end as D09,  
 --D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId) else D10 end as D10,  
 --D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId) else D11 end as D11,  
 --D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId) else D12 end as D12,  
 --D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId) else D13 end as D13,  
 --D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId) else D14 end as D14,  
 --D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId) else D15 end as D15,  
 --D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId) else D16 end as D16,  
 --D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId) else D17 end as D17,  
 --D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId) else D18 end as D18,  
 --D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId) else D19 end as D19,  
 --D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId) else D20 end as D20,  
 --D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId) else D21 end as D21,  
 --D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId) else D22 end as D22,  
 --D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId) else D23 end as D23,  
 --D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId) else D24 end as D24,  
 --D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId) else D25 end as D25,  
 --D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId) else D26 end as D26,  
 --D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId) else D27 end as D27,  
 --D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId) else D28 end as D28,  
 --D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))   
 --BEGIN  
 -- INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId) else D29 end as D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) <> 2  
 --BEGIN  
 --INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId) else D30 end as D30,  
 --D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) NOT IN (2,4,6,9,11)  
 --BEGIN  
 --INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId) else D31 end as D31,  
 --D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  

 --SELECT * FROM #TempMonthTrans
 --SELECT TM.*,
 
       
		
 SELECT TM.Id,TM.EmployeeId,TM.Attn_Date,TM.PresentStatus AS OldPresentStatus,OGD.Title AS [Organization Group Department],
 
 CASE When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='PW')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW'
  When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(EJD.DateOfJoining as date)<= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfJoining,'')='')AND (EJD.DateOfleaving>= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfleaving,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
 ELSE
 TM.PresentStatus END as PresentStatus,
 TM.FirstIn,TM.LastOut,TM.OverTime,TM.LateBy,TM.Duration,TM.EarlyBy,TM.ShiftName, MT.Tot_Attn,
 MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,  
 Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode ,   
 [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,   
 [sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus,   
 [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,  
 ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
 ISNULL(SM.Id,0) AS StatusId,  
 ISNULL(SM.Title,'') AS Status  
 FROM #TempMonthTrans TM   
 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId  
 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId  
 --INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(EJD.DateOfJoining,'1900/01/01'))
 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01'))
 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
 WHERE   
 TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate    
 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
 AND (( @rStatus = '1' AND (TM.Duration < '09:30')) OR ( @rStatus != '1' AND ((PresentStatus = @rStatus OR @rStatus='0'))))
 AND EM.OrgId = @rOrgId 
 AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
 AND (EM.FirstName + ' ' + EM.LastName like '%' + @rEmployeeName + '%' or @rEmployeeName = '')
 AND  ISNULL(EM.IsOtherUser,0) = 0
 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
 --AND (TM.Duration < '09:30')
 Order By TM.EmployeeId,TM.Attn_Date


 


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pTimeSheetListGetWithHoliday]
  @rEmployeeId bigint=0,  
  @rFromDate Date,  
  @rToDate Date,  
  @rStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rEmployeeName nvarchar(50) = '',
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
  
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20)  
 )  
   
 INSERT INTO #TempMonthTrans  
   
 --	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)


	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),
	CASE When [sHrm].[fWeekHOffHolidayGet](EmployeeId , YEAR(attn_dt) ,MONTH(attn_dt) ,01 ,0 ,0 ,@rOrgId )<>'-' then  
	
 [sHrm].[fWeekHOffHolidayGet](EmployeeId , YEAR(attn_dt) ,MONTH(attn_dt) ,01 ,0 ,0 ,@rOrgId ) else D01 end as D01,  
 D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	


 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId) else D01 end as D01,  
 --D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId) else D02 end as D02,  
 --D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId) else D03 end as D03,  
 --D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId) else D04 end as D04,  
 --D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId) else D05 end as D05,  
 --D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId) else D06 end as D06,  
 --D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId) else D07 end as D07,  
 --D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId) else D08 end as D08,  
 --D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime), case When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId) else D09 end as D09,  
 --D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId) else D10 end as D10,  
 --D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId) else D11 end as D11,  
 --D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId) else D12 end as D12,  
 --D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId) else D13 end as D13,  
 --D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId) else D14 end as D14,  
 --D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId) else D15 end as D15,  
 --D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId) else D16 end as D16,  
 --D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId) else D17 end as D17,  
 --D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId) else D18 end as D18,  
 --D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId) else D19 end as D19,  
 --D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId) else D20 end as D20,  
 --D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId) else D21 end as D21,  
 --D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId) else D22 end as D22,  
 --D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId) else D23 end as D23,  
 --D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId) else D24 end as D24,  
 --D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId) else D25 end as D25,  
 --D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId) else D26 end as D26,  
 --D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId) else D27 end as D27,  
 --D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId) else D28 end as D28,  
 --D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))   
 --BEGIN  
 -- INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId) else D29 end as D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) <> 2  
 --BEGIN  
 --INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId) else D30 end as D30,  
 --D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) NOT IN (2,4,6,9,11)  
 --BEGIN  
 --INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId) else D31 end as D31,  
 --D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
 
 SELECT TM.*,MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,  
 Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode ,   
 [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,   
 [sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus,   
 [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,  
 ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
 ISNULL(SM.Id,0) AS StatusId,  
 ISNULL(SM.Title,'') AS Status  
 FROM #TempMonthTrans TM   
 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId  
 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId  
 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
 WHERE   
 TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate    
 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)  
 AND (PresentStatus = @rStatus OR @rStatus='0')  
 AND EM.OrgId = @rOrgId 
 AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
 AND (EM.FirstName + ' ' + EM.LastName like '%' + @rEmployeeName + '%' or @rEmployeeName = '')
 AND  ISNULL(EM.IsOtherUser,0) = 0
 Order By TM.EmployeeId,TM.Attn_Date  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pTimeSheetListStudentGet]
	@rOrgId int,
	@rFromDate DateTime,  
    @rToDate DateTime, 
	@rStudentId bigint,
	@rClassId int=0,
	@rDivisionId int=0,
	@rStatusId int=0,
	@rBatchId  int,
	@rAcademicId bigint=0		--Mantis: 34829, add by dhruvik
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   

----
CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20),
    ShiftName nvarchar(25) 
	
	)

	
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId = 2001)	  --Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime))) 
		AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END

	Update TM set PresentStatus = CASE When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 --When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(AD.AdmissionDate as date)<= Cast(TM.Attn_Date as date) OR ISNULL(AD.AdmissionDate,'')='')AND (AD.LeftDate>= Cast(TM.Attn_Date as date) OR ISNULL(AD.LeftDate,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
		 ELSE TM.PresentStatus END
		From #TempMonthTrans TM
		INNER JOIN sStudent.vStudentAcademic SA  ON SA.AcademicId = TM.EmployeeId		--Mantis: 34829, change by dhruvik, from SA.StudentId => SA.AcademicId
		--INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId

--select * from #TempMonthTrans 
	Select 
		SA.AcademicId AS AcademicId,
		SA.StudentId AS StudentId,
		TM.Attn_Date AS  Attn_Date,
		TM.FirstIn,
		TM.LastOut,
		TM.OverTime,
		TM.LateBy,
		TM.Duration,
		TM.EarlyBy,
		TM.ShiftName,
		TM.PresentStatus as PresentStatus,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS TotalAbsentDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS TotalWeekOffs,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS TotalHolidays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS TotalPresentDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS TotalHalfDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS TotalLessHours,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS TotalErrorCase,
		 OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId--,
		--DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays
				
		 From #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND SourceTypeId = 2001		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.AcademicId = MT.EmployeeId AND MT.SourceTypeId=2001		--Mantis: 34829, change by dhruvik, from SA.StudentId => SA.AcademicId and 2003 => 2001
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	--INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	
	WHERE 
			SA.OrgId=@rOrgId 
			AND	((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			AND ((SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			AND SA.BatchId = @rBatchId
			AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			AND (SA.AcademicId = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, add by dhruvik
			 
	ORDER BY SA.RollNo



	DROP Table #TempMonthTrans	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pTimeSheetListSummaryGet]
  --@rEmployeeId bigint=0,  
  --@rFromDate Date,  
  --@rToDate Date,  
  --@rStatus nvarchar(10) = 'Pending',  
  @rOrgId int = 0,
  @rType varchar(1) 
  --@rEmployeeName nvarchar(50) = ''
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
  
Declare @queryPresent AS varchar(max)
Declare @queryAbsent AS varchar(max)
Declare @queryTotal AS varchar(max)

DECLARE @AttnDt AS varchar(20)  
 

 
IF(@rType='P')
   BEGIN
		
		SET @AttnDt=''+CONVERT(varchar(10),DATEPART(YYYY,getdate()-3))+'-'+CONVERT(varchar(10),DATEPART(mm,getdate()-3))+'-01'	

		IF(DAY(GetDate()) >= 10)
		 BEGIN
		 SET @queryPresent='SELECT Count(EmpCode) AS PresentCount FROM sBiometric.tMonthTrans MT LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=MT.EmployeeId WHERE EM.OrgId='+convert(varchar(20),@rOrgId)+' AND ATTN_DT = '+''''+@AttnDt+''''+' AND '+
		             CONVERT(varchar(5),'D'+CONVERT(varchar(10),DAY(CONVERT(char(10), GetDate(),126))))+' = '+'''P'''+''
		 --print @AttnDt
		 END
		 ELSE
		 BEGIN
		 SET @queryPresent='SELECT Count(EmpCode) AS PresentCount FROM sBiometric.tMonthTrans MT LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=MT.EmployeeId WHERE EM.OrgId='+convert(varchar(20),@rOrgId)+' AND ATTN_DT = '+''''+@AttnDt+''''+' AND '+
		             CONVERT(varchar(5),'D0'+CONVERT(varchar(10),DAY(CONVERT(char(10), GetDate(),126))))+' = '+'''P'''+''
		 END
		 Exec (@queryPresent)
 
   END
 
IF(@rType='A')
   BEGIN
         SET @AttnDt=''+CONVERT(varchar(10),DATEPART(YYYY,getdate()-3))+'-'+CONVERT(varchar(10),DATEPART(mm,getdate()-3))+'-01'	

		 IF(DAY(GetDate()) >= 10)
		 BEGIN
		 SET @queryAbsent='SELECT Count(EmpCode) AS AbsentCount FROM sBiometric.tMonthTrans MT LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=MT.EmployeeId WHERE EM.OrgId='+convert(varchar(20),@rOrgId)+' AND ATTN_DT = '+''''+@AttnDt+''''+' AND '+
		             CONVERT(varchar(5),'D'+CONVERT(varchar(10),DAY(CONVERT(char(10), GetDate(),126))))+' = '+'''A'''+''
		 END
		 ELSE
		 BEGIN
		 SET @queryAbsent='SELECT Count(EmpCode) AS AbsentCount FROM sBiometric.tMonthTrans MT LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=MT.EmployeeId WHERE EM.OrgId='+convert(varchar(20),@rOrgId)+' AND ATTN_DT = '+''''+@AttnDt+''''+' AND '+
		             CONVERT(varchar(5),'D0'+CONVERT(varchar(10),DAY(CONVERT(char(10), GetDate(),126))))+' = '+'''A'''+''
		 --print @queryAbsent
		 END
		 Exec (@queryAbsent)		 
   END 
   
IF(@rType='T')
   BEGIN 
   --print @rOrgId
         SET @AttnDt=''+CONVERT(varchar(10),DATEPART(YYYY,getdate()-3))+'-'+CONVERT(varchar(10),DATEPART(mm,getdate()-3))+'-01'	

		 SET @queryTotal='SELECT Count(EmpCode) AS TotalCount FROM sBiometric.tMonthTrans MT LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=MT.EmployeeId WHERE EM.OrgId='+convert(varchar(20),@rOrgId)+' AND ATTN_DT = '+''''+@AttnDt+''''+''
		 print @queryTotal
		 Exec (@queryTotal)
   
   END 
   
   
   
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
-- exec [sBiometric].[pTimeSheetSummaryGet] 2019,1,1101
CREATE OR ALTER PROCEDURE [sBiometric].[pTimeSheetSummaryGet]  
  @rForYear int,  
  @rForMonth int,  
  @rOrgId int  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
declare @lAttnDate as nvarchar(20)  
Set @lAttnDate = convert(nvarchar(10),@rForYear) + '-' + convert(nvarchar(10),@rForMonth) + '-' + '01'  
  
select em.Id,em.Code as EmpCode,em.FirstName + ' ' + em.Lastname As EmpName,Tot_WeekOFF,Tot_Holiday,Tot_Abs,((DateDiff(Day,attn_dt,DateAdd(month,1,attn_dt)))-Tot_WeekOFF-Tot_Holiday-Tot_Abs) AS Actual_attain_day,   
replace(TotalHour,':','.') AS totalAttainHr,  
((DateDiff(Day,attn_dt,DateAdd(month,1,attn_dt)))-Tot_WeekOFF-Tot_Holiday-Tot_Abs) *9.15 As TotalWorkingHrs,  
(case isnull(replace(TotalHour,':','.'),0) when '00.00' then 0 else
round(replace(TotalHour,':','.')-((DateDiff(Day,attn_dt,DateAdd(month,1,attn_dt)))-Tot_WeekOFF-Tot_Holiday-Tot_Abs)*9.15 ,2) end) AS OT,  
isnull((select count(value)  
from sBiometric.tMonthTrans  
unpivot  
(  
  value  
  for col in (d01,d02,d03,d04,d05,d06,d07,d08,d09,d10,d11,d12,d13,d14,d15,d16,d17,d18,d19,d20,d21,d22,d23,d24,d25,d26,d27,d28,d29,d30,d31)  
) un where value like 'E' and attn_dt = tm.attn_dt AND em.Id=un.EmployeeId group by empcode ),0) AS ErrorCase  
from sBiometric.tMonthTrans tm inner join sHrm.tEmployeeMaster em on tm.EmployeeId = em.Id  AND  ISNULL(EM.IsOtherUser,0) = 0
and tm.attn_dt = @lAttnDate
WHERE (ISNULL(tm.SourceTypeId,95) = 95  OR tm.SourceTypeId = 0)
order by ((DateDiff(Day,attn_dt,DateAdd(month,1,attn_dt)))-Tot_WeekOFF-Tot_Holiday-Tot_Abs)*9.15 - replace(TotalHour,':','.')   
desc  
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pTimeSheetUpdate]

@rXmlDoc nvarchar(max) = ''

AS
SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT,
			@rEmployeeId BIGINT,
			@rDate VARCHAR(20),
			@rCode INT,
			@rTotalML INT = 0,
			@rTotalPL INT = 0			


--BEGIN TRY
BEGIN TRANSACTION					
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	
	CREATE TABLE #tTable  
	(
		 Id bigint identity
		,EmployeeId bigint not null
		,Attn_Date datetime not null
		,FirstIn varchar(10) null
		,LastOut varchar(10) null
		,EarlyBy varchar(10) null
		,LateBy varchar(10) null
		,OverTime varchar(50) null		 
		,Duration varchar(50) null		 		
		,[Status] varchar(10) null
		,[Shift] varchar(25) null
		,MonthDate datetime not null
		,[Tot_Attn] float null
		,[Tot_Abs] float null
		,[Tot_WeekOFF] int null
		,[Tot_Holiday] int null
		,[TotalHour] varchar(50) null
		,[Tot_HD] int null
		,[Tot_Early] varchar(50) null
		,[Tot_Late] varchar(50) null
		,[Tot_OT] varchar(50) null		
		,[Count_Late] int null
		,[Count_Early] int null
		,[Count_OT] int null
	)


	INSERT INTO #tTable
			   (			    
			   EmployeeId
			   ,Attn_Date
			   ,FirstIn
			   ,LastOut
			   ,EarlyBy
			   ,LateBy
			   ,OverTime
			   ,Duration	    
			   ,[Status]
			   ,[Shift]
			   ,MonthDate
			   ,[Tot_Attn] 
			   ,[Tot_Abs] 
			   ,[Tot_WeekOFF]
			   ,[Tot_Holiday]
			   ,[TotalHour] 
			   ,[Tot_HD]  
			   ,[Tot_Early] 
			   ,[Tot_Late] 
			   ,[Tot_OT] 
			   ,[Count_Late] 
			   ,[Count_Early]
			   ,[Count_OT]		   		   
			   )
	SELECT		
		A.EmployeeId,
		A.Attn_Date,			
		A.FirstIn,
		A.LastOut,
		A.EarlyBy,
		A.LateBy,		 
		A.OverTime,				
		A.Duration,		
		A.[Status],
		A.[Shift],
		A.MonthDate,
		A.TotalAttain,
		A.TotalAbsent,
		A.TotalWeekOffs,
		A.TotalHoliday,
		A.TotalHour,
		A.TotalHalfDays,
		A.TotalEarly,
		A.TotalLate,
		A.TotalOverTime,
		A.CountLate,
		A.CountEarly,
		A.CountOverTime 		
		
	FROM OPENXML (@intDoc, '/Table/TimeSheetUpdate', 1)
	WITH
	(						
		EmployeeId bigint '@EmployeeId',
		Attn_Date datetime '@Attn_Date',
		FirstIn varchar(10) '@FirstIn',
		LastOut varchar(10) '@LastOut',		
		EarlyBy varchar(10) '@EarlyBy',
		LateBy varchar(10) '@LateBy',		 		
		OverTime varchar(50) '@OverTime',		
		Duration varchar(50) '@Duration',		
		[Status] varchar(10) '@Status',
		[Shift] varchar(25) '@Shift',
		MonthDate datetime '@MonthDate',
		TotalAttain float '@TotalAttain',
		TotalAbsent float '@TotalAbsent',
		TotalWeekOffs int '@TotalWeekOffs',
		TotalHoliday int '@TotalHoliday',
		TotalHour varchar(50) '@TotalHour',
		TotalHalfDays int '@TotalHalfDays',
		TotalEarly varchar(50) '@TotalEarly',
		TotalLate varchar(50) '@TotalLate',
		TotalOverTime varchar(50) '@TotalOverTime',
		CountLate int '@CountLate',
		CountEarly int '@CountEarly',
		CountOverTime int '@CountOverTime'
	)A 

	--SELECT * FROM #tTable		

	EXEC sp_xml_removedocument @intDoc

	SET @rEmployeeId = (SELECT TOP 1 EmployeeId FROM #tTable)
	SET @rDate = (SELECT TOP 1 MonthDate FROM #tTable)
	SET @rDate = (SELECT CONVERT(VARCHAR, CAST(@rDate AS DATETIME), 20))	

	
	IF EXISTS (SELECT 1 FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)
	BEGIN 
		SET @rTotalML = (SELECT Tot_ML FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)
		SET @rTotalPL = (SELECT Tot_PL FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)
		SET @rCode = (SELECT EmpCode FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)
		DELETE FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95		
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT 1 FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND SourceTypeId = 95)
		BEGIN
			SET @rCode = (SELECT TOP 1 EmpCode FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND SourceTypeId = 95)
		END
		ELSE
		BEGIN
			SET @rCode = (SELECT ISNULL(MAX(EmpCode),0) + 1 FROM sBiometric.tMonthTrans WHERE SourceTypeId = 95)
		END
	END

	INSERT INTO sBiometric.tMonthTrans(EmpCode,EmployeeId,Attn_Dt,Tot_CL,Tot_SL,Tot_EL,Tot_SP,Tot_C,Tot_PL,Tot_ML,SourceTypeId) VALUES(@rCode,@rEmployeeId,@rDate,0,0,0,0,0,@rTotalPL,@rTotalPL,95)

	DECLARE @lCount int = 1
	DECLARE @lTotal int = (SELECT COUNT(Id) FROM #tTable)	
	WHILE @lCount <= @lTotal 
	BEGIN
		DECLARE @lColumn NVARCHAR(10) = CAST(@lCount AS NVARCHAR(10))
		DECLARE @SQL NVARCHAR(MAX) = ''
		SET @lColumn = (SELECT CASE WHEN @lCount BETWEEN 0 AND 9 THEN RIGHT('0' + CAST(@lColumn AS VARCHAR(2)), 2) ELSE CAST(@lCount AS NVARCHAR(10)) END)

		SET @SQL = 'UPDATE sBiometric.tMonthTrans
		SET D'+CAST(@lColumn AS VARCHAR)+'_IN = (SELECT FirstIn FROM #tTable WHERE Id = '+CAST(@lCount AS VARCHAR)+'),
		D'+CAST(@lColumn AS VARCHAR)+'_OUT = (SELECT LastOut FROM #tTable WHERE Id = '+CAST(@lCount AS VARCHAR)+'),
		D'+CAST(@lColumn AS VARCHAR)+'_E = (SELECT EarlyBy FROM #tTable WHERE Id = '+CAST(@lCount AS VARCHAR)+'),
		D'+CAST(@lColumn AS VARCHAR)+'_L = (SELECT LateBy FROM #tTable WHERE Id = '+CAST(@lCount AS VARCHAR)+'),
		D'+CAST(@lColumn AS VARCHAR)+'_O = (SELECT OverTime FROM #tTable WHERE Id = '+CAST(@lCount AS VARCHAR)+'),
		D'+CAST(@lColumn AS VARCHAR)+'_T = (SELECT Duration FROM #tTable WHERE Id = '+CAST(@lCount AS VARCHAR)+'),
		D'+CAST(@lColumn AS VARCHAR)+' = (SELECT Status FROM #tTable WHERE Id = '+CAST(@lCount AS VARCHAR)+'),
		D'+CAST(@lColumn AS VARCHAR)+'_S = (SELECT Shift FROM #tTable WHERE Id = '+CAST(@lCount AS VARCHAR)+')
		WHERE EmployeeId = '+CAST(@rEmployeeId AS VARCHAR) + ' AND Attn_Dt = ''' + CAST(@rDate AS VARCHAR) + ''' AND SourceTypeId = 95'
		
		--PRINT @SQL

		EXEC (@SQL)

		SET @lCount = @lCount + 1	
	END	
	DECLARE @lMaxId int = (SELECT MAX(Id) FROM #tTable)
	UPDATE sBiometric.tMonthTrans SET 
	[Tot_Attn] = (SELECT [Tot_Attn] FROM #tTable WHERE Id = @lMaxId),
	[Tot_Abs] = (SELECT [Tot_Abs] FROM #tTable WHERE Id = @lMaxId),
	[Tot_WeekOFF] = (SELECT [Tot_WeekOFF] FROM #tTable WHERE Id = @lMaxId),
	[Tot_Holiday] = (SELECT [Tot_Holiday] FROM #tTable WHERE Id = @lMaxId),
	[TotalHour] = (SELECT [TotalHour] FROM #tTable WHERE Id = @lMaxId),
	[Tot_HD] = (SELECT [Tot_HD] FROM #tTable WHERE Id = @lMaxId),
	[Tot_Early] = (SELECT [Tot_Early] FROM #tTable WHERE Id = @lMaxId),
	[Tot_Late] = (SELECT [Tot_Late] FROM #tTable WHERE Id = @lMaxId),
	[Tot_OT] = (SELECT [Tot_OT] FROM #tTable WHERE Id = @lMaxId),
	[Count_Late] = (SELECT [Count_Late] FROM #tTable WHERE Id = @lMaxId),
	[Count_Early] = (SELECT [Count_Early] FROM #tTable WHERE Id = @lMaxId),
	[Count_OT] = (SELECT [Count_OT] FROM #tTable WHERE Id = @lMaxId),
	[Tot_OD] = 0,
	[Tot_Leave] = 0
	WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95	

	SELECT 1 AS RESULT

	DROP TABLE #tTable
	COMMIT TRANSACTION

	--END TRY
	--BEGIN CATCH
	--ROLLBACK TRANSACTION
	--SELECT -1
	--END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

CREATE OR ALTER PROCEDURE [sBiometric].[pTimeSheetUpdateListGet]
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,    
  @rOrgId int = 0  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
  
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 [Shift] nvarchar(30)
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)
		
   
 INSERT INTO #TempMonthTrans  
   
 	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END

	--SELECT * FROM #TempMonthTrans
		
 SELECT TM.Id,TM.EmployeeId,TM.Attn_Date,TM.PresentStatus AS OldPresentStatus,TM.[Shift],
 
 CASE When (([sHrm].[fWeekHOffHolidayGet](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,0 ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
 When (([sHrm].[fWeekHOffHolidayGet](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,0 ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW'
 ELSE
 TM.PresentStatus END as PresentStatus,
 TM.FirstIn,TM.LastOut,TM.OverTime,TM.LateBy,TM.Duration,TM.EarlyBy, MT.Tot_Attn,
 MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,  
 Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode ,   
 [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,   
 [sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus,   
 [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel  
 FROM #TempMonthTrans TM   
 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId   
 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01'))
 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
 WHERE   
 TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate    
 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) 
 AND EM.OrgId = @rOrgId  
 AND  ISNULL(EM.IsOtherUser,0) = 0
 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
 --AND (TM.Duration < '09:30')
 Order By TM.EmployeeId,TM.Attn_Date
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[pUHFReaderStatusUpdate]
	@rUpdatedDateTime datetime,
	@rDeviceIP nvarchar(20),
	@rDevicePort nvarchar(10),
	@rStatusId int
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 
	declare @lDeviceName as nvarchar(50)='',@lOrgId int,@lOrgGroupId int,@lStatus nvarchar(15)

	if(@rStatusId=1)
	BEGIN 
		set @lStatus='Connected'
	END
	else if (@rStatusId=2)
	BEGIN 
	set @lStatus='Disconnected'
	END
	  
	if exists(select 1 from [sBiometric].[tDeviceMasterCloud] where DeviceIP=@rDeviceIP AND DevicePort=@rDevicePort)
	BEGIN
		select top 1 @lDeviceName=DeviceName,@lOrgId=OrgId from [sBiometric].[tDeviceMasterCloud] where DeviceIP=@rDeviceIP AND DevicePort=@rDevicePort
	END

	if(@lDeviceName='')
	BEGIN
		select -101
		return
	END
	
	select @lOrgGroupId=OrgGroupId from [sSetup].[tOrganizationMaster] where id=@lOrgId

	IF EXISTS(SELECT 1 FROM sBiometric.tBiometricDeviceSyncDetail WHERE SUBSTRING(DeviceName,0,CHARINDEX('-',DeviceName,0))=@lDeviceName)
	BEGIN 
		
		UPDATE sBiometric.tBiometricDeviceSyncDetail 
		SET 
			SyncTime=@rUpdatedDateTime,
			DeviceName = @lDeviceName + '- ' + @lStatus

		Where  
			SUBSTRING(DeviceName,0,CHARINDEX('-',DeviceName,0))=@lDeviceName
		SELECT @lDeviceName AS DeviceName,@lOrgId as OrgId,@lOrgGroupId AS OrgGroupId
	END
	ELSE
	BEGIN 
	
		INSERT INTO sBiometric.tBiometricDeviceSyncDetail 
		VALUES ( @lDeviceName + '-' + @lStatus, @rUpdatedDateTime)
		SELECT @lDeviceName AS DeviceName,@lOrgId as OrgId,@lOrgGroupId AS OrgGroupId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sBiometric].[pYearlyPresenceSUMmaryGet]
	 
	 @rCode nvarchar(20)='',
	 @rOrgId int,
	 @rFromDate date,
	 @rToDate date,
	 @rIsMonthly bit=0,
	 @rStatusId int = 0,
	 @rOrganizationDepartmentId int=0,
	 @OrgGroupDepartmentId int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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


	IF(@rIsMonthly = 1)
	BEGIN
		SELECT
			ROW_NUMBER() OVER (ORDER BY EM.Code ASC) AS SrNo,
			EM.Code,
			EM.FirstName + ' ' + EM.Lastname AS Name,
			OGD.Title AS [Organization Group],
			DATEDIFF(dd, @rFromDate, @rToDate)+1 as WorkingDay,

			CONVERT(nvarchar(20), DATENAME(MONTH,(MT.attn_dt))) +' - '+ CONVERT(nvarchar(10),YEAR(MT.attn_dt)) AS MonthYear,

			--0  AS DinnerAllowance,
			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,

			--0 AS CompOff,

			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01, d02, d03, d04, d05, d06, d07, d08, d09, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19, d20, d21, d22, d23, d24, d25, d26, d27, d28, d29, d30, d31)) PT
			WHERE value LIKE 'PW' AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS CompOff,

			--0 AS EarlyLeave,

			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) + ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),Replace(value,':','.'))) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT 
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0)) AS EarlyLeave,

			--0 AS Tot_OT,
			SUM(CONVERT(float,REPLACE(Tot_OT,':','.'))) AS Tot_OT,		

			CASE WHEN (SUM(CONVERT(decimal(10,2),REPLACE(Tot_OT,':','.'))) - CONVERT(decimal(10,2),REPLACE((
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.'))) > 0 Then 
			Convert(nvarchar(20),SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))) - Convert(decimal(10,2),Replace((
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.')))
		
			ELSE

			'-' + Convert(nvarchar(10),Convert(decimal(10,2),Replace(
			(
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.')) - SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))))
			END	AS Tot_OT_EL,
		
			--0 AS OT_DinnerAllowance,

			--CONVERT(nvarchar(20), DATENAME(MONTH,(MT.attn_dt))) +' - '+ CONVERT(nvarchar(10),YEAR(MT.attn_dt)) AS MonthYear,
			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) > 09.15 AND CONVERT(FLOAT,REPLACE(value,':','.')) <= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS OT_DinnerAllowance,
			
			0 AS WorkingDay,
			0 AS NoPunch,
			--case When (Tot_Abs - Isnull(A1.LateStatus,0)*.5 - isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0))> 0 then
			--Tot_Abs - Isnull(A1.LateStatus,0)*.5 - isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0)
			--else 0 end  AS NoPunch,
			0 AS CL,
			0 AS LWPLeave,
			0 AS LeaveNotApply,
			0 AS Late,
			0 AS Grt1030Cnt,
			0 AS Valid_Cnt,
			0 AS InvalidHrs,
			0 AS Tot_OT_IVH,
			0 AS MonthlyPunchAvg,
			0 AS Gt8PunchCnt
		
		FROM 
			sBiometric.tMonthTrans MT
			INNER JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt >= @rFromDate  AND MT.attn_dt <= @rToDate AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
			LEFT JOIN
			(
			SELECT SUM(ISNULL(ELS.EarlyHrs,0)) AS EarlyHrs,ELS.EmployeeId FROM sBiometric.tEmployeeLateStatus ELS 
			WHERE ELS.StatusId = 550 AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS.EmployeeId
			) A ON A.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatus FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE ELS1.StatusId = 550 AND LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A1 ON A1.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS TotalLate FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A2 ON A2.EMployeeId = MT.EMployeeId 
	
		WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '')
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		AND ((EJD.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 
		GROUP BY EM.Id,EM.Code,EM.FirstName,EM.Lastname,MT.attn_dt,A1.LateStatus,OGD.Title
		ORDER BY EM.Code
	END

	ELSE

	BEGIN
		DECLARE @lYearlyPresence TABLE(Code nvarchar(20),Name nvarchar(100),DinnerAllowance decimal(8,2),CompOff decimal(8,2), 
		EarlyLeave decimal(8,2),Total_OT decimal(8,2),Total_OT_EL decimal(8,2),OT_DinnerAllowance decimal(8,2))

		INSERT INTO @lYearlyPresence
		SELECT
		    --ROW_NUMBER() OVER (ORDER BY EM.Code ASC) AS SrNo, 
			--DATEDIFF(dd, @rFromDate, @rToDate)+1 as WorkingDay,
			--CONVERT(nvarchar(20), DATENAME(MONTH,(MT.attn_dt))) +' - '+ CONVERT(nvarchar(10),YEAR(MT.attn_dt)) AS MonthYear,
			EM.Code,
			EM.FirstName + ' ' + EM.Lastname AS Name,
			--OGD.Title AS [Organization Group],

			0  AS DinnerAllowance,

			--CONVERT(nvarchar(20), DATENAME(MONTH,(MT.attn_dt))) +' - '+ CONVERT(nvarchar(10),YEAR(MT.attn_dt)) AS MonthYear,
			--ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			--UNPIVOT
			--(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			--WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,
		
			--0  AS CompOff,
			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01, d02, d03, d04, d05, d06, d07, d08, d09, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19, d20, d21, d22, d23, d24, d25, d26, d27, d28, d29, d30, d31)) PT
			WHERE value LIKE 'PW' AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS CompOff,
			
			--0 as EarlyLeave,
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) + ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),Replace(value,':','.'))) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT 
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0)) AS EarlyLeave,

			SUM(CONVERT(float,REPLACE(Tot_OT,':','.'))) AS Tot_OT,		
			--0 AS Tot_OT,
			--0 as Tot_OT_EL,
			--0 AS WorkingDay,
			--0 AS NoPunch,
			--0 AS CL,
			--0 AS LWPLeave,
			--0 AS LeaveNotApply,
			--0 AS Late,
			--0 AS Grt1030Cnt,
			--0 AS Valid_Cnt,
			--0 AS InvalidHrs,
			--0 AS Tot_OT_IVH,
			--0 AS MonthlyPunchAvg,
			--0 AS Gt8PunchCnt,
			
			CASE WHEN (SUM(CONVERT(decimal(10,2),REPLACE(Tot_OT,':','.'))) - CONVERT(decimal(10,2),REPLACE((
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.'))) > 0 Then 
			Convert(nvarchar(20),SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))) - Convert(decimal(10,2),Replace((
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.')))
		
			ELSE

			'-' + Convert(nvarchar(10),Convert(decimal(10,2),Replace(
			(
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.')) - SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))))
			END	AS Tot_OT_EL,
			--0 AS OT_DinnerAllowance
			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) > 09.15  AND CONVERT(FLOAT,REPLACE(value,':','.')) <= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS OT_DinnerAllowance
		FROM 
			sBiometric.tMonthTrans MT
			INNER JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt >= @rFromDate  AND MT.attn_dt <= @rToDate AND  ISNULL(EM.IsOtherUser,0) = 0
			LEFT JOIN
			(
			SELECT SUM(ISNULL(ELS.EarlyHrs,0)) AS EarlyHrs,ELS.EmployeeId FROM sBiometric.tEmployeeLateStatus ELS 
			WHERE ELS.StatusId = 550 AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS.EmployeeId
			) A ON A.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatus FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE ELS1.StatusId = 550 AND LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A1 ON A1.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS TotalLate FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A2 ON A2.EMployeeId = MT.EMployeeId 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
			INNER JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
	
		WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '')
		AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
		AND ((EJD.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		GROUP BY EM.Id,EM.Code,EM.FirstName,EM.Lastname,MT.attn_dt,A1.LateStatus,OGD.Title
		ORDER BY EM.Code
	
		SELECT ROW_NUMBER() OVER (ORDER BY Code ASC) AS SrNo,Code,Name,SUM(DinnerAllowance) AS DinnerAllowance,SUM(CompOff) AS CompOff,SUM(EarlyLeave) AS EarlyLeave,SUM(Total_OT) AS Tot_OT,SUM(Total_OT_EL) AS Tot_OT_EL,SUM(OT_DinnerAllowance) AS OT_DinnerAllowance FROM @lYearlyPresence GROUP BY Code,Name
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sBiometric].[tEmployeeLateTimeGet]
AS
BEGIN
DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()
select checkintime.D11_IN,deptmaster.Title,empmaster.Code,empmaster.EmployeeName from  sHrm.vEmployeeCommonDetail as empmaster inner join sSetup.tDepartmentMaster as deptmaster on empmaster.OrgID=deptmaster.OrgId 
inner join  sBiometric.tMonthTrans as checkintime on empmaster.EmployeeId=checkintime.EmployeeId where D11_IN>@lDate
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCanteen].[pAssignOrganizationAdd]

	@rAssignOrganizationXml [nvarchar](max),
	@rCanteenId int
	--@rOrgId smallint,
	--@rIsObsolete bit
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignOrganizationXml
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 DELETE FROM sCanteen.tAssignOrganization
				 WHERE  CanteenId=@rCanteenId
	--IF(@rIsObsolete = 0)
	--BEGIN
		--DELETE FROM sCanteen.tAssignOrganization WHERE CanteenId=@rCanteenId AND OrgId=@rOrgId
	--END
	--ELSE IF NOT EXISTS(SELECT 1 FROM sCanteen.tAssignOrganization WHERE CanteenId=@rCanteenId AND OrgId=@rOrgId)
	--BEGIN
		INSERT INTO sCanteen.tAssignOrganization
		(
			CanteenId,
			OrgId
		)
		SELECT
		
		   CanteenId,
		   OrgId
		FROM OPENXML (@loDoc, '/Table/AssignOrganization', 1)
		WITH ( 
				CanteenId int,
				OrgId Smallint
			  ) 
	--END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCanteen].[pAssignOrganizationGet]
	 
	@rCanteenId int,
	@rOrgGroupId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				CASE WHEN AO.CanteenId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sSetup.tOrganizationMaster OM
		LEFT JOIN sCanteen.tAssignOrganization AO ON AO.OrgId=OM.Id AND AO.CanteenId=@rCanteenId
	WHERE
		OM.OrgGroupId=@rOrgGroupId
	Order by OM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCanteen].[pAttendanceForBreakAdd]
	
	@rStrXml nvarchar(MAX),
    @rBreakDate date='',
    @rBreakTypeId int
   
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE AR FROM sCanteen.tAttendanceForBreak AR 
	 --INNER JOIN sHostel.tAssignRoom ASR ON ASR.SourceId = AR.StudentId AND ASR.SourceTypeId=2003   
	 --INNER JOIN sHostel.tRoomMaster RM ON RM.HostelId = AR.HostelId
	    WHERE 
	    AR.BreakDate = @rBreakDate
	   
	    AND AR.BreakTypeId = @rBreakTypeId
	 
	 INSERT INTO sCanteen.tAttendanceForBreak
		(
			BreakTypeId,
			SourceTypeId,
			SourceId,
			BreakDate
			)
		SELECT	
			@rBreakTypeId,
			SourceTypeId,
			SourceId,			
			@rBreakDate
						
		FROM OPENXML (@loDoc, '/Table/AttendanceForBreak', 1)
		WITH ( 
				SourceTypeId int,
				SourceId bigint				
			  )  
        SELECT 1 AS Result
	 END	
	
	--	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pAttendanceForBreakDelete]
	 
	@rBreakDate date,
	@rBreakTypeId int=0
  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	 BEGIN TRANSACTION	
DELETE AR
FROM sCanteen.tAttendanceForBreak  AR
 INNER JOIN sCanteen.tRegisterForBreak ASR ON ASR.SourceId = AR.SourceId AND ASR.SourceTypeId=2003  
 WHERE 
	    AR.BreakDate = @rBreakDate
	    AND  ASR.BreakTypeId=@rBreakTypeId
	   
	
 SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

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

	BEGIN
	SELECT 
			RB.SourceId ,
			VA.Code,
			VA.Name,
			VA.SUId,
			ATR.BreakDate,
			RB.SourceTypeId,
			RB.BreaktypeId,
			BTM.Title AS BreakType,
			CASE WHEN ATR.SourceId IS NULL THEN 'false' ELSE 'true' END AS IsDeleted,
			VA.ClassId,
			VA.ClassName,
			VA.DivisionId,
			VA.DivisionName,
			VA.RollNo
				
  FROM 
             sStudent.vStudentLastAcademic  VA 
           INNER JOIN sCanteen.tRegisterForBreak RB ON VA.StudentId = RB.SourceId AND RB.SourceTypeId = 2003 
           LEFT JOIN sCanteen.tAttendanceForBreak ATR ON ATR.SourceId=VA.StudentId AND (ATR.BreakDate=@rBreakDate) 
		   AND ATR.BreakTypeId=RB.BreakTypeId --add BreakTypeId for mantis : 0042074
		   LEFT JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId 
			
            --INNER JOIN sHostel.tAssignRoom AR ON VA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
            --INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
   --         LEFT JOIN sCanteen.tAttendanceForBreak ATR ON ATR.SourceId=VA.StudentId 
			--LEFT JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  ATR.BreakTypeId 
			
			
		  
  WHERE 
  --((VA.OrgId = @rOrgId) OR (@rOrgId = 0))AND  
  RB.BreakTypeId = @rBreakTypeId AND
  (VA.ClassId = @rClassId OR ISNULL(@rClassId,0)=0) AND
  (VA.DivisionId = @rDivisionId OR ISNULL(@rDivisionId,0)=0)	  
  ORDER BY VA.Code
  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pAttendanceForBreakListGet]
	 	 
	 	@rBreakTypeId int,	
		@rStudentCode nvarchar(20),
		@rFromAttendanceDate date,
		@rToAttendanceDate date,
	 	@rSuid nvarchar(50)
	 	--@rPresent int
	 	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			SA.StudentId As SourceId,
			SA.Code AS StudentCode,
			SA.Name,
			SA.SUId,
			ATR.BreakDate,
			BTM.Title AS BreakType			
			
	 FROM  
			sStudent.vStudentAcademic SA 
			INNER JOIN sCanteen.tRegisterForBreak RB ON SA.StudentId = RB.SourceId AND RB.SourceTypeId = 2003 
			 INNER JOIN sCanteen.tAttendanceForBreak ATR ON ATR.SourceId=SA.StudentId 
			 AND  RB.BreakTypeId =ATR.BreakTypeId--add for mantis : 0042074
		   INNER JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId 
			  
			
			--INNER JOIN sHostel.tAssignRoom AR ON SA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
		 --   INNER JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId = AR.SourceId 
			--LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id=ATR.AbsentReasonId
			--INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId 
	  --      INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	  --      INNER JOIN sHostel.tHostelAttendanceTypeMaster ATM ON ATM.Id=ATR.HostelAttendanceTypeId
	  --      LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
	    
			
  WHERE 
	 ((ATR.BreakTypeId=@rBreakTypeId) OR (@rBreakTypeId=0))
	 
	  AND ((SA.Code = @rStudentCode) OR (@rStudentCode=''))
	
	  AND ((ATR.BreakDate >= @rFromAttendanceDate) OR (ISNULL(@rFromAttendanceDate,'') = ''))
	  AND ((ATR.BreakDate <= @rToAttendanceDate) OR (ISNULL(@rToAttendanceDate,'') = ''))
	   AND ((SA.SUId=@rSuid) OR (@rSuid=''))
	   AND 	SA.IsActiveBatch=1	--add for mantis : 0042074
      ORDER BY ATR.BreakDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCanteen].[pBreakTypeMasterAdd]
	  
		@rOrgGroupId int,
        @rId int,
        @rCanteenId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rOrderIndex int,
		@rIsObsolete bit,		
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint
								
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		
		   IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE Code=@rCode AND CanteenId=@rCanteenId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE Title=@rTitle AND CanteenId=@rCanteenId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
			--mantis Start - 0033603
			IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE OrderIndex=@rOrderIndex AND CanteenId=@rCanteenId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			--mantis End - 0033603
	END
	ELSE
	BEGIN
	        IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE Code=@rCode AND CanteenId=@rCanteenId AND Id<>@rId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE Title=@rTitle AND CanteenId=@rCanteenId AND Id<>@rId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
			--mantis Start - 0033603
			IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE OrderIndex=@rOrderIndex AND CanteenId=@rCanteenId AND Id<>@rId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			--mantis End - 0033603

	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tBreakTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCanteen.tBreakTypeMaster
		( 
			OrgGroupId,
			Id,	
			CanteenId,			
			Code,
			Title,
			OrderIndex,
			IsObsolete,			
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			

		)
	VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
		    @rCanteenId,			
			@rCode,
			@rTitle,	
			@rOrderIndex,		
			@rIsObsolete,
			
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rUpdatedUserId,
			sCommon.fGetDate()
			
		)
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCanteen.tBreakTypeMaster
	    SET
	        CanteenId=@rCanteenId,
			Title=@rTitle,			
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			OrderIndex=@rOrderIndex
			
	      
	      WHERE Id = @rId
	      
	      SELECT @lNextNumber AS Result
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pBreakTypeMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100)='',
	 @rCode nvarchar(20)='',
	 @rCanteenId int,
	 @rIsSearch bit = 1
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
		END
	
	SELECT 
	
			ISNULL(FM.Id,0)AS Id,
			FM.Title,
		    FM.Code,		    
			FM.IsObsolete,
			FM.OrderIndex,
			FM.CanteenId
      
  FROM 
            sCanteen.tBreakTypeMaster FM
            
  WHERE   
           ((FM.Id = @rId) OR (@rId = 0))
	       AND ((FM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((FM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	       AND FM.CanteenId=@rCanteenId
	      order by OrderIndex  desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCanteen].[pCanteenDataDelete]
	 
	@rCanteenId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DELETE FROM sCanteen.tAssignOrganization  WHERE  CanteenId=@rCanteenId
	DELETE CS FROM sCanteen.tCanteenIssueDetail CS INNER JOIN  sCanteen.tCanteenIssue C ON C.Id=CS.CanteenIssueId  WHERE  C.CanteenId=@rCanteenId
	DELETE FROM sCanteen.tCanteenIssue  WHERE CanteenId=@rCanteenId
	DELETE FROM sCanteen.tFoodItemMaster  WHERE  CanteenId=@rCanteenId
    DELETE  FROM sCanteen.tDailyMenu WHERE  CanteenId=@rCanteenId
    DELETE  R FROM sCanteen.tRegisterForBreak R  INNER JOIN  sCanteen.tBreakTypeMaster BM ON BM.Id=R.BreakTypeId  WHERE  BM.CanteenId=@rCanteenId
    DELETE A FROM sCanteen.tAttendanceForBreak  A  INNER JOIN  sCanteen.tBreakTypeMaster BM ON BM.Id=A.BreakTypeId  WHERE  BM.CanteenId=@rCanteenId
	DELETE  FROM sCanteen.tBreakTypeMaster WHERE  CanteenId=@rCanteenId
    DELETE FROM sCanteen.tCanteenMaster  WHERE Id=@rCanteenId
  
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pCanteenIssueAdd]
	  
	  
        @rId bigint,
        @rCanteenId int,
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rIssueDate date,
		@rTotalAmount decimal(12,2),
		@rOrgGroupId int,
		@rCreatedUserId bigint,
		@rOtherName nvarchar(100),
		@rCanteenIssueXml nvarchar(max),
		@rStudentDailySpendLimit decimal(12,2)=0,
		--@rIdOut [bigint] OUTPUT
		--add by dhruvik for 25772 mantis issue
		@rPayTypeId tinyint,		--add
		@rChequeNo nvarchar(40),	--add
		@rBankName nvarchar(200),	--add
		@rChequeDate date			--add
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	--IF(@rId = 0)	
	--BEGIN
		
	--	If Exists(select 1 from sCanteen.tCanteenIssue where CanteenId=@rCanteenId AND Id=@rId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
		
	--	If  Exists(select 1 from sCanteen.tCanteenIssue where CanteenId=@rCanteenId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	IF (@rSourceTypeId=2003 AND @rStudentDailySpendLimit > 0 AND @rId = 0)
	BEGIN
	DECLARE @lSpendAmount Decimal(12,2)
	SELECT @lSpendAmount = ISNUll(SUM(TotalAmount),0) from sCanteen.tCanteenIssue where CanteenId=@rCanteenId AND SourceId=@rSourceId AND @rSourceTypeId=2003 AND IssueDate = @rIssueDate
	
	if (@lSpendAmount + @rTotalAmount > @rStudentDailySpendLimit )
	BEGIN
	SELECT -101 as Result 
	RETURN
	END
	END
	
	BEGIN TRANSACTION	
	
	 DECLARE @lNextNumber bigint

		IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenIssue', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCanteen.tCanteenIssue
		(
			CanteenId,
			Id,	
			SourceTypeId,
			SourceId,
			IssueDate,
			TotalAmount,
			CreatedUserId,
			CreatedDateTime,
			OtherName,
			--add by dhruvik for 25772 mantis issue
			PayTypeId,		--add
			ChequeNo,		--add
			BankName,		--add
			ChequeDate		--add
			
		)
	VALUES
		(
		    @rCanteenId,
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@rIssueDate,
			@rTotalAmount,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOtherName,
			--add by dhruvik for 25772 mantis issue
			@rPayTypeId,		--add
			@rChequeNo,			--add
			@rBankName,			--add
			@rChequeDate		--add
		)
		
		--SELECT 1 AS Result
		  SELECT @lNextNumber AS Result
		 END 
	ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCanteen.tCanteenIssue
	    SET
			TotalAmount=@rTotalAmount,
			--add by dhruvik for 25772 mantis issue
			PayTypeId=@rPayTypeId,		--add
			ChequeNo=@rChequeNo,		--add
			BankName=@rBankName,		--add
			ChequeDate=@rChequeDate		--add
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
		
	EXEC [sCanteen].[pCanteenIssueDetailAdd] @lNextNumber,@rCanteenIssueXml
	
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pCanteenIssueDetailAdd]
	
	@rCanteenIssueId [bigint],
	@rCanteenIssueXml [nvarchar](max)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loIdoc INT
	--DECLARE @lCanteenIssueDetailCurrentId BIGINT
	--DECLARE @lCount INT
	--DECLARE @lNextNumber int
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rCanteenIssueXml
 
	
  Delete from sCanteen.tCanteenIssueDetail where CanteenIssueId=@rCanteenIssueId 

	INSERT INTO sCanteen.tCanteenIssueDetail
		(
			CanteenIssueId,
			FoodItemId,
			Quantity,
			ItemPrice
			
		)
	SELECT  
		--@lStockIssueRequestDetailCurrentId + ROW_NUMBER() OVER(ORDER BY StockItemId) AS Id, 
		@rCanteenIssueId,
		FoodItemId,
		Quantity,
		ItemPrice
		
	FROM OPENXML (@loIdoc, '/CanteenIssue/CanteenIssueDetail', 1)
		WITH ( 
		        --CanteenIssueId bigint,
				FoodItemId INT, 
				Quantity DECIMAL(12,2), 		
				ItemPrice DECIMAL(12,2)
			  ) 
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pCanteenIssueDetailGet]
	
	@rCanteenIssueId bigint,
	@rCanteenId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT CID.CanteenIssueId,
			CID.FoodItemId,
			CID.Quantity,
			CID.ItemPrice,
			FM.Code AS  ItemCode,
			FM.Title As ItemTitle
			
 
	   FROM 
			sCanteen.tCanteenIssueDetail CID
	   INNER JOIN 
			sCanteen.tFoodItemMaster FM
       ON
			FM.Id = CID.FoodItemId
		
	  WHERE ((CID.CanteenIssueId = @rCanteenIssueId) OR (@rCanteenIssueId = 0))
	  AND FM.CanteenId=@rCanteenId
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pCanteenIssueGet]
	
	@rId bigint = 0,
	@rCanteenId int 
	--@rFromDate date,
	--@rToDate date,
	--@rOrgGroupBatchId int

	--@rCode nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
	        CI.Id,
			CI.CanteenId,
			CI.SourceTypeId,
			CI.SourceId,
			CI.IssueDate,
			CI.TotalAmount,
			CI.CreatedDateTime,
			(CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Code,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.Code, '') ElSE ''
			 END) AS Code,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Name,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.FirstName +' ' + EM.MiddleName + ' ' + EM.LastName ,'') ElSE ''
			 END) AS Name,
			 ISNULL(CI.OtherName,'') AS OtherName
		
	   FROM sCanteen.tCanteenIssue CI
	   LEFT JOIN sStudent.vStudentLastAcademic SMast ON SMast.StudentId = CI.SourceId AND CI.SourceTypeId = 2003 
	   -- AND SMast.OrgGroupBatchId=@rOrgGroupBatchId
       LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = CI.SourceId AND CI.SourceTypeId = 95
	  WHERE ((CI.Id = @rId) OR (@rId = 0))
	  AND CI.CanteenId = @rCanteenId
	--  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ISNULL(EM.IsOtherUser,0) = 0 
	  EXEC [sCanteen].[pCanteenIssueDetailGet] @rId,@rCanteenId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pCanteenIssueMasterGet]
	
	@rId bigint = 0,
	@rCanteenId int ,
	@rFromDate date,
	@rToDate date,
	@rSUID nvarchar(50)=''

	--@rCode nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
	        CI.Id,
			CI.CanteenId,
			CI.SourceTypeId,
			CI.SourceId,
			CI.IssueDate,
			CI.TotalAmount,
			CI.CreatedDateTime,
			(CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Code,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.Code, '') ElSE ''
			 END) AS Code,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Name,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.FirstName +' ' + EM.MiddleName + ' ' + EM.LastName ,'') ElSE CI.OtherName
			 END) AS Name,
			 ISNULL(CI.OtherName,'') AS OtherName,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.OrgId,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.OrgId, '') ElSE ''
			 END) AS OrgId,
			  (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.SUId,'')
			 ElSE ''
			 END) AS SUId,
			 --add by dhruvik for 25772 mantis issue
			 ISNULL(CI.PayTypeId,0) as PayTypeId,			--add
			 ISNULL(CI.ChequeNo,'') as ChequeNo,			--add
			 ISNULL(CI.BankName,'') as BankName,			--add
			 ISNULL(CI.ChequeDate,'') as ChequeDate			--add
		
	   FROM sCanteen.tCanteenIssue CI
	   LEFT JOIN  sStudent.vStudentLastAcademic SMast ON SMast.StudentId = CI.SourceId AND CI.SourceTypeId = 2003  
       LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = CI.SourceId AND CI.SourceTypeId = 95
     
      
	  
	  WHERE ((CI.Id = @rId) OR (@rId = 0))
		  AND CI.CanteenId = @rCanteenId
		  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		 AND ((SMast.SUID = @rSUID) OR (ISNULL(@rSUID,'')=''))
	 --  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 AND ISNULL(EM.IsOtherUser,0) = 0 
order by CI.IssueDate desc
	  --EXEC [sCanteen].[pCanteenIssueDetailGet] @rId,@rCanteenId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sCanteen].[pCanteenMasterAdd]
	 
        @rId int,
		@rNumber  int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rOrgGroupId smallint,
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rOrderIndex int,
		@rDepositHeadId bigint,
		@rDepositExpenseTypeId bigint
		
		
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sCanteen.tCanteenMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId )
		Begin
			select -102 as Result
			RETURN
		End
		If Exists(select 1 from sCanteen.tCanteenMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		--mantis Start - 0033603
		If Exists(select 1 from sCanteen.tCanteenMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
		If Exists(select 1 from sCanteen.tCanteenMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -105 as Result
			RETURN
		END 
		--mantis End - 0033603
	END
	ELSE
	BEGIN
	--mantis Start - 0033603
		If Exists(select 1 from sCanteen.tCanteenMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		--mantis End - 0033603
		If  Exists(select Id from sCanteen.tCanteenMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		--mantis Start - 0033603
		If Exists(select 1 from sCanteen.tCanteenMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -104 as Result
			RETURN
		END 
		If Exists(select 1 from sCanteen.tCanteenMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -105 as Result
			RETURN
		END 
		--mantis End - 0033603

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCanteen.tCanteenMaster
		(
			Id,
			Title,
			Number,
			Code,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId ,
			OrderIndex,
			DepositHeadId,
			DepositExpenseTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rNumber,
			@rCode,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rUpdatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rOrderIndex,
			@rDepositHeadId,
			@rDepositExpenseTypeId
		)
		
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2026
		   ,@lNextNumber
		   ,@rCreatedUserId
		   
		    SELECT @lNextNumber AS Result
		   
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCanteen.tCanteenMaster
	    SET
			Title=@rTitle,
			Number=@rNumber,
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			OrderIndex=@rOrderIndex,
			DepositHeadId=@rDepositHeadId,
			DepositExpenseTypeId=@rDepositExpenseTypeId
			
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pCanteenMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode varchar(20),
	 @rOrgGroupId smallint,
	 @rIsSearch bit = 1
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			CM.Id,
			CM.Title,
		    CM.Code,
		    CM.Number,
			CM.IsObsolete,
			CM.OrderIndex,
			ISNULL(CM.DepositHeadId,0)AS DepositHeadId,
			ISNULL(CM.DepositExpenseTypeId,0)AS DepositExpenseTypeId
      
  FROM 
            sCanteen.tCanteenMaster CM
            
  WHERE   
           ((CM.Id = @rId) OR (@rId = 0))
	       AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((CM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	       AND CM.OrgGroupId=@rOrgGroupId
	      order by OrderIndex desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCanteen].[pDailyMenuListADD]
	(
		@rOrgGroupId int,
		@rXml  nvarchar(MAX),
		@rCanteenId int,
		@rBreakTypeId int,		
		@rCreatedUserId bigint ,
		@rMenuMonth tinyint,
		@rMenuYear smallint,
		@rClassId int=0
		
	)
AS

SET NOCOUNT ON

BEGIN

 

DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	--IF(@rClassId <> 0)
	--BEGIN
	--DELETE FROM sCanteen.tDailyMenu WHERE BreakTypeId=@rBreakTypeId AND MenuMonth=@rMenuMonth AND MenuYear=@rMenuYear AND ClassId=@rClassId
	--END
	--ELSE
	--BEGIN
	DELETE FROM sCanteen.tDailyMenu WHERE BreakTypeId=@rBreakTypeId AND MenuMonth=@rMenuMonth AND MenuYear=@rMenuYear AND ClassId=@rClassId
	--END
	 
	
	 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tDailyMenu', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sCanteen.tDailyMenu
	(		
	CanteenId,
	Id,
	MenuDate,
	BreakTypeId,
	Title,
	MenuItems,
	CreatedUserId,
	CreatedDateTime,
	UpdatedUserId,
	UpdatedDateTime,
	MenuMonth,
	MenuYear,
	ClassId
		
			
	)
	SELECT	
			@rCanteenId,	
			@lNextNumber + ROW_NUMBER() OVER(ORDER BY Title ) ,
			A.MenuDate,
			@rBreakTypeId,
			A.Title,
			A.MenuItems,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate() ,
			@rMenuMonth ,
			@rMenuYear ,
			@rClassId

	FROM OPENXML (@intDoc, '/Table/DailyMenu', 1)
	WITH
	(
			 MenuDate date,
		   	Title nvarchar(100),
			MenuItems nvarchar(300)						 
	)A  
	

	EXEC sp_xml_removedocument @intDoc
	
	SELECT @lNextNumber = MAX(DM.ID) FROM sCanteen.tDailyMenu DM
	INNER JOIN sCanteen.tCanteenMaster CM ON DM.CanteenId=CM.Id Where CM.OrgGroupId=@rOrgGroupId
    EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sCanteen.tDailyMenu', @rCurrentNumber = @lNextNumber 

	SELECT 1 as Result
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCanteen].[pDailyMenuListGet]
		
	 	@rBreakTypeId int,
	 	@rCanteenId int,
	 	@rMenuYear smallint,
	 	@rMenuMonth int,
		@rMenuDate date ='',
		@rClassId int=0

			 		 		 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT 
			DM.Id AS MenuItemId,
			DM.MenuDate,
			Datename(weekday, DM.MenuDate) AS Days,
			Dm.BreakTypeId,
			BTM.Title AS BreakType,
			DM.Title AS Title,
			Dm.MenuItems,
			DM.MenuMonth,
			DM.MenuYear,
			DM.CanteenId,
			ISNULL(CM.Code,'') AS ClassName
	 FROM  
			sCanteen.tDailyMenu DM 
		
		   INNER JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  DM.BreakTypeId 
		   LEFT JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
						    			
  WHERE 
		((DM.BreakTypeId=@rBreakTypeId) OR (@rBreakTypeId=0))
		AND  ((DM.CanteenId=@rCanteenId) OR (@rCanteenId=0))
		AND ((DM.MenuYear = @rMenuYear) OR (@rMenuYear=''))
		AND ((DM.MenuMonth = @rMenuMonth) OR (@rMenuMonth=''))
		AND   ((DM.MenuDate>dateadd(d, - DATEPART(dw, @rMenuDate), @rMenuDate))  OR (@rMenuDate=''))
		AND  ((DM.MenuDate<=dateadd(d, 7-DATEPART(dw, @rMenuDate), @rMenuDate))  OR (@rMenuDate=''))
		AND ((ISNULL(DM.ClassId,0) = @rClassId))
		AND BTM.IsObsolete = 0 --Added for mantis : 35301 by Nilesh
	 	
      ORDER BY DM.MenuDate,BTM.OrderIndex ASC --Added for mantis : 35301 by Nilesh
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pFoodItemMasterAdd] @rId INT
	,@rCanteenId INT
	,@rCode NVARCHAR(20)
	,@rTitle NVARCHAR(100)
	,@rItemPrice DECIMAL(12, 2)
	,@rIsObsolete BIT
	,@rOrgGroupId INT
	,@rCreatedUserId BIGINT
	,@rUpdatedUserId BIGINT
	,@rOrderIndex INT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		IF (@rId = 0)
		BEGIN
			IF EXISTS ( SELECT 1 FROM sCanteen.tFoodItemMaster WHERE Code = @rCode AND CanteenId = @rCanteenId )
			BEGIN
				SELECT - 101 AS Result

				RETURN
			END

			--Mantis Start - 0033603
			IF EXISTS ( SELECT 1 FROM sCanteen.tFoodItemMaster WHERE OrderIndex = @rOrderIndex AND CanteenId = @rCanteenId )
			BEGIN
				SELECT - 102 AS Result

				RETURN
			END
					--Mantis End - 0033603
		END

		--ELSE
		--BEGIN
		--  If  Exists(select Id from sCanteen.tFoodItemMaster where CanteenId=@rCanteenId AND Id<>@rId)
		--	Begin
		--		select -103 as Result
		--		RETURN
		--	End
		--END
		BEGIN TRANSACTION

		DECLARE @lNextNumber INT

		IF (@rId = 0)
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId,'sCanteen.tFoodItemMaster',0,1,1,@outNextNumber = @lNextNumber OUTPUT

			INSERT INTO sCanteen.tFoodItemMaster (
				CanteenId
				,Id
				,Code
				,Title
				,ItemPrice
				,IsObsolete
				,OrderIndex
				,CreatedUserId
				,CreatedDateTime
				,UpdatedUserId
				,UpdatedDateTime
				)
			VALUES (
				@rCanteenId
				,@lNextNumber
				,@rCode
				,@rTitle
				,@rItemPrice
				,@rIsObsolete
				,@rOrderIndex
				,@rCreatedUserId
				,sCommon.fGetDate()
				,@rUpdatedUserId
				,sCommon.fGetDate()
				)

			SELECT @lNextNumber AS Result
		END
		ELSE
		BEGIN
			SET @lNextNumber = @rId

			IF EXISTS ( SELECT 1 FROM sCanteen.tFoodItemMaster WHERE Code = @rCode AND CanteenId = @rCanteenId AND Id <> @rId )
			BEGIN
				SELECT - 101 AS Result
				COMMIT TRANSACTION
				RETURN
			END

			--Mantis Start - 0033603
			IF EXISTS ( SELECT 1 FROM sCanteen.tFoodItemMaster WHERE OrderIndex = @rOrderIndex AND CanteenId = @rCanteenId AND Id <> @rId )
			BEGIN
				SELECT - 102 AS Result
				COMMIT TRANSACTION
				RETURN
			END

			--Mantis End - 0033603
			UPDATE sCanteen.tFoodItemMaster
			SET CanteenId = @rCanteenId
				,Title = @rTitle
				,ItemPrice = @rItemPrice
				,Code = @rCode
				,IsObsolete = @rIsObsolete
				,UpdatedUserId = @rCreatedUserId
				,UpdatedDateTime = sCommon.fGetDate()
				,OrderIndex = @rOrderIndex
			WHERE Id = @rId

			SELECT @lNextNumber AS Result
		END

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pFoodItemMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100)='',
	 @rCode nvarchar(20)='',
	 @rCanteenId int,
	 @rIsSearch bit = 1
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
		END
	
	SELECT 
	
			ISNULL(FM.Id,0)AS Id,
			FM.Title,
		    FM.Code,
		    FM.ItemPrice,
			FM.IsObsolete,
			FM.OrderIndex,
			FM.CanteenId
      
  FROM 
            sCanteen.tFoodItemMaster FM
            
  WHERE   
           ((FM.Id = @rId) OR (@rId = 0))
	       AND ((FM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((FM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	       AND FM.CanteenId=@rCanteenId
	      order by OrderIndex  desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCanteen].[pRegisterForBreakAdd]
	  
		@rBreakTypeId int,
		@rRegisterForBreakXml [nvarchar](max),
		@rSourceTypeId smallint,
		@rorgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rRegisterForBreakXml
BEGIN
	--BEGIN TRY
	
	
	-- BEGIN TRANSACTION	
	IF(@rSourceTypeId=2003)
	BEGIN
	DELETE  B FROM sCanteen.tRegisterForBreak B INNER JOIN   sStudent.vStudentLastAcademic SA   ON B.sourceId=SA.StudentId
				 WHERE  BreakTypeId=@rBreakTypeId AND SourceTypeId=@rSourceTypeId AND OrgId=@rorgId				 				 
	
	END
	ELSE
	BEGIN
	 DELETE  B FROM sCanteen.tRegisterForBreak B INNER JOIN    sCommon.vEmployeeMaster EM   ON B.sourceId=EM.Id
				 WHERE  BreakTypeId=@rBreakTypeId AND SourceTypeId=@rSourceTypeId AND OrgId=@rorgId
	END
	
				
	BEGIN

	INSERT INTO sCanteen.tRegisterForBreak
		( 
			BreakTypeId,
			SourceTypeId,
			SourceId

		)
	SELECT
		
		   @rBreakTypeId,
		   SourceTypeId,
		   SourceId
		 
		FROM OPENXML (@loDoc, '/Table/RegisterForBreak', 1)
		WITH ( 
				SourceTypeId int,
				SourceId bigint
				) 
		
		
		    SELECT 1 AS Result
	END	 

--ELSE
--	 BEGIN
--	 --SET @lNextNumber = @rId
--	    UPDATE  sCanteen.tRegisterForBreak
--	    SET
--	        BreakTypeId=@rBreakTypeId,
--			SourceTypeId=@rSourceTypeId,
--			SourceId=@rSourceId
			
	      
--	      WHERE SourceId=@rSourceId
	      
--	      SELECT 11 AS Result
--	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pRegisterForBreakGet]

@rSourceTypeId int=0,
@rOrgId int,
@rDepartmentId int,
@rClassId int,
@rDivisionId int,
@rBreakTypeId int,
 @rCanteenId int
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	IF(@rSourceTypeId=2003)
	BEGIN 		
		SELECT 		
		SA.Code,
		SA.Name,
		SA.OrganizationName,
		SA.DepartmentName,
		SA.ClassName+'-'+ SA.DivisionName As Div ,
		BTM.Title AS BreakType,
		SA.StudentId AS SourceId,
		'2003' AS SourceTypeId,
		CASE WHEN RB.SourceId is null THEN 'false' ELSE 'true' END AS Selected			      
    FROM 
    
	   sStudent.vStudentLastAcademic SA 
	   LEFT JOIN sCanteen.tRegisterForBreak RB ON SA.StudentId = RB.SourceId AND RB.SourceTypeId = 2003  AND   RB.BreakTypeId = @rBreakTypeId   
	   LEFT JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId    AND BTM.CanteenId=@rCanteenId	
	  LEFT JOIN sCanteen.tCanteenMaster  CM ON CM.Id=BTM.CanteenId             
  WHERE 
		 ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		  -- AND BTM.CanteenId=@rCanteenId
       END
       
    ELSE 
	BEGIN 
       
		SELECT 
		EM.Code,
		EM.FirstName +' '+ EM.MiddleName +' '+ EM.LastName AS Name,
		OM.Title AS OrganizationName,
		DM.Title As DepartmentName,
		'' As Div ,
		BTM.Title AS BreakType,
		EM.Id AS SourceId,
		'95' AS SourceTypeId,
	
		CASE WHEN RB.SourceId is null THEN 'false' ELSE 'true' END AS Selected
			
      
    FROM 
    --sCanteen.tCanteenIssue CI   LEFT JOIN
	 [sHrm].[tEmployeeMaster] EM 
	 INNER JOIN [sHrm].[tEmployeeJobDetail] EJD ON EJD.EmployeeId = EM.Id
	 INNER JOIN [sSetup].[tDepartmentMaster] DM ON DM.Id = EJD.OrganizationDepartmentId
	 LEFT JOIN sCanteen.tRegisterForBreak RB ON EM.Id = RB.SourceId AND RB.SourceTypeId = 95 AND   RB.BreakTypeId = @rBreakTypeId 
	 LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	  LEFT JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId 	 AND BTM.CanteenId=@rCanteenId  
      LEFT JOIN sCanteen.tCanteenMaster  CM ON CM.Id=BTM.CanteenId  	 
            
  WHERE   
  
   ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		--AND((RB.BreakTypeId = 11010006) OR (0 = 0))
		 
       END   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pRptCanteenIssueListDetailGet]
	 @rCanteenId int,
	 @rFromDate date='',
	 @rToDate date='',
	 @ItemCode nvarchar(20)='',
	 @rBuilder1 nvarchar(max)='',
	 @rId bigint=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
	        @rBuilder1 AS Builder1,
	        CI.IssueDate,
			CID.Quantity,
			CID.ItemPrice,
			CI.SourceTypeId,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Name,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.FirstName +' ' + EM.MiddleName + ' ' + EM.LastName ,'') ElSE CI.OtherName
			 END) AS Name,
			 FM.Code AS ItemCode,
			 FM.Title As ItemTitle,
			CID.CanteenIssueId,
			CID.FoodItemId				
  FROM 
  
            sCanteen.tCanteenIssueDetail CID
            INNER JOIN sCanteen.tCanteenIssue CI ON CI.Id=CID.CanteenIssueId AND CI.CanteenId=@rCanteenId
            INNER JOIN sCanteen.tFoodItemMaster FM ON FM.Id=CID.FoodItemId
            LEFT JOIN sStudent.vStudentLastAcademic SMast ON SMast.StudentId = CI.SourceId AND CI.SourceTypeId = 2003 
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = CI.SourceId AND CI.SourceTypeId = 95
  WHERE   ((CI.Id = @rId) OR (@rId = 0))
       AND CI.CanteenId = @rCanteenId 
		  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((FM.Code = @ItemCode) OR (ISNULL(@ItemCode,'')=''))
	AND  ISNULL(EM.IsOtherUser,0) = 0     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pRptCanteenIssueListGet]
	 @rCanteenId int,
	 @rFromDate date,
	 @rToDate date,
	 @ItemCode nvarchar(20),
	 @rBuilder1 nvarchar(max)=''
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
	        @rBuilder1 AS Builder1,
	        CI.IssueDate,
	        CI.SourceTypeId,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Name,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.FirstName +' ' + EM.MiddleName + ' ' + EM.LastName,'') ElSE CI.OtherName
			 END) AS Name,
			 CI.TotalAmount
					
  FROM 
          sCanteen.tCanteenIssue CI
         --INNER JOIN sCanteen.tCanteenIssueDetail CI ON CI.Id=CID.CanteenIssueId
          --INNER JOIN sCanteen.tFoodItemMaster FM ON FM.Id=CID.FoodItemId
          LEFT JOIN sStudent.vStudentLastAcademic SMast ON SMast.StudentId = CI.SourceId AND CI.SourceTypeId = 2003 
          LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = CI.SourceId AND CI.SourceTypeId = 95
           
            
            
  WHERE   
       ((CI.CanteenId = @rCanteenId) OR (@rCanteenId = 0))
		  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--AND ((FM.Code = @ItemCode) OR (ISNULL(@ItemCode,'')=''))
	  AND  ISNULL(EM.IsOtherUser,0) = 0   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCanteen].[pRptCanteenIssueSlipGet]
	 @rCanteenId int,
	 @rFromDate date='',
	 @rToDate date='',
	 @ItemCode nvarchar(20)='',
	 @rId bigint=0,
	 @rBuilder1 nvarchar(max)=''
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
DECLARE @lOrgGroupId int = 0

 SELECT @lOrgGroupId = OrgGroupId   FROM sCanteen.tCanteenMaster C
 WHERE C.Id = @rCanteenId
 
	SELECT 
	       
	        CI.IssueDate,
			CID.Quantity,
			CID.ItemPrice,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Name,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.FirstName +' ' + EM.MiddleName + ' ' + EM.LastName ,'') ElSE CI.OtherName
			 END) AS Name,
			 FM.Title As ItemTitle,
			CID.CanteenIssueId,
			CID.FoodItemId,
			sFinanceCommon.fNumberToWordsWithDecimal (ISNULL(CI.TotalAmount,0.00),1,2,@lOrgGroupId) AS TotalAmountInWords,
			CM.Title AS CanteenTitle,
			CI.Id AS Id,
			
			isnull(SMast.RollNo,'') AS RollNo,
			isnull(SMast.ClassName,'') AS ClassName,
			isnull(SMast.DivisionName,'') AS DivisionName,
			isnull(SMast.OrganizationName,'') AS OrganizationName,
			isnull(SMast.BatchName,'') AS BatchName,
			isnull(SMast.Code,'') AS Code,
			isnull(SA.AdmissionNumber,'') AS AdmissionNo,
			CI.SourceTypeId	
				
  FROM 
  
            sCanteen.tCanteenIssueDetail CID
            INNER JOIN sCanteen.tCanteenIssue CI ON CI.Id=CID.CanteenIssueId AND CI.CanteenId=@rCanteenId
            INNER JOIN sCanteen.tFoodItemMaster FM ON FM.Id=CID.FoodItemId
            LEFT JOIN sStudent.vStudentLastAcademic SMast ON SMast.StudentId = CI.SourceId AND CI.SourceTypeId = 2003 
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = CI.SourceId AND CI.SourceTypeId = 95
            LEFT JOIN sCanteen.tCanteenMaster CM ON CM.Id=@rCanteenId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SMast.StudentId
            
  WHERE   ((CI.Id = @rId) OR (@rId = 0))
       AND CI.CanteenId = @rCanteenId 
	   AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	   AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--AND ((FM.Code = @ItemCode) OR (ISNULL(@ItemCode,'')=''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pRptFoodItemListGet]
	 @rCanteenId int = 0,
	 @rFromDate date,
	 @rToDate date,
	 @rBuilder1 nvarchar(max)=''

	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
	
	        @rBuilder1 AS Builder1,
			FM.Title AS Title,
		    FM.Code AS Code,
		    CID.ItemPrice,
		    CID.Quantity,
		    CID.FoodItemId
		    
		    
      
  FROM 
           sCanteen.tCanteenIssueDetail CID 
           INNER JOIN sCanteen.tCanteenIssue  CI ON CI.Id=CID.CanteenIssueId
           INNER JOIN  sCanteen.tFoodItemMaster FM ON FM.Id=CID.FoodItemId
            
  WHERE   
       ((FM.CanteenId = @rCanteenId) OR (@rCanteenId = 0))
         AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	     AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pRptRegisterForBreakGet]



@rBreakTypeId int,
 @rCanteenId int
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	
	BEGIN 		
		SELECT 		
		SA.Code,
		SA.Name,
		SA.OrganizationName,
		SA.DepartmentName,
		SA.ClassName+'-'+ SA.DivisionName As Div ,
		RB.BreakTypeId,
		BTM.Title AS BreakType,
		SA.StudentId AS SourceId,
		'2003' AS SourceTypeId,
		CASE WHEN RB.SourceId is null THEN 'false' ELSE 'true' END AS Selected			      
    FROM 
		sCanteen.tRegisterForBreak RB
		Inner Join   sStudent.vStudentLastAcademic SA  ON SA.StudentId = RB.SourceId
		-- AND RB.SourceTypeId = 2003 
		-- AND   RB.BreakTypeId = @rBreakTypeId
		INNER JOIN   sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId 
    
	  -- sStudent.vStudentLastAcademic SA 
	  -- LEFT JOIN sCanteen.tRegisterForBreak RB ON SA.StudentId = RB.SourceId AND RB.SourceTypeId = 2003  AND   RB.BreakTypeId = @rBreakTypeId   
	  -- LEFT JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId    AND BTM.CanteenId=@rCanteenId	
	  --LEFT JOIN sCanteen.tCanteenMaster  CM ON CM.Id=BTM.CanteenId             
  WHERE 
		 ((RB.BreakTypeId = @rBreakTypeId) OR (@rBreakTypeId = 0))
		
     
       
   UNION 

       
		SELECT 
		EM.Code,
		EM.EmployeeName AS Name,
		OM.Title AS OrganizationName,					
		EM.DepartmentName,
		'' As Div ,
		RB.BreakTypeId,
		BTM.Title AS BreakType,
		EM.Id AS SourceId,
		'95' AS SourceTypeId,
	
		CASE WHEN RB.SourceId is null THEN 'false' ELSE 'true' END AS Selected
			
      
    FROM 
		sCanteen.tRegisterForBreak RB
		INNER JOIN   sCommon.vEmployeeMaster EM ON EM.Id = RB.SourceId 
		--AND RB.SourceTypeId = 95 
		--AND   RB.BreakTypeId = @rBreakTypeId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		INNER JOIN   sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId 
            
  WHERE   
  
  ((RB.BreakTypeId = @rBreakTypeId) OR (@rBreakTypeId = 0))
	
		 
       END   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCanteen].[pRptStudentWiseBreakGet]



@rBreakTypeId int,
 @rCanteenId int
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	
	BEGIN 		
		SELECT 		
		SA.Code,
		SA.Name,
		SA.OrganizationName,
		SA.DepartmentName,
		SA.ClassName+'-'+ SA.DivisionName As Div ,
		RB.BreakTypeId,
		BTM.Title AS BreakType,
		SA.StudentId AS SourceId,
		'2003' AS SourceTypeId,
		CASE WHEN RB.SourceId is null THEN 'false' ELSE 'true' END AS Selected			      
    FROM 
		 sCanteen.tBreakTypeMaster BTM
		 LEFT JOIN  sCanteen.tRegisterForBreak RB ON BTM.Id=  RB.BreakTypeId 
		 LEFt Join   sStudent.vStudentLastAcademic SA  ON SA.StudentId = RB.SourceId
	
    
	  -- sStudent.vStudentLastAcademic SA 
	  -- LEFT JOIN sCanteen.tRegisterForBreak RB ON SA.StudentId = RB.SourceId AND RB.SourceTypeId = 2003  AND   RB.BreakTypeId = @rBreakTypeId   
	  -- LEFT JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId    AND BTM.CanteenId=@rCanteenId	
	  --LEFT JOIN sCanteen.tCanteenMaster  CM ON CM.Id=BTM.CanteenId             
  WHERE 
		 ((RB.BreakTypeId = @rBreakTypeId) OR (@rBreakTypeId = 0))
		
     
       
   UNION 

       
		SELECT 
		EM.Code,
		EM.EmployeeName AS Name,
		OM.Title AS OrganizationName,					
		EM.DepartmentName,
		'' As Div ,
		RB.BreakTypeId,
		BTM.Title AS BreakType,
		EM.Id AS SourceId,
		'95' AS SourceTypeId,
	
		CASE WHEN RB.SourceId is null THEN 'false' ELSE 'true' END AS Selected
			
      
    FROM 
    
    sCanteen.tBreakTypeMaster BTM
		LEFT JOIN sCanteen.tRegisterForBreak RB 	ON BTM.Id=  RB.BreakTypeId 
		LEFT JOIN   sCommon.vEmployeeMaster EM ON EM.Id = RB.SourceId 
		--AND RB.SourceTypeId = 95 
		--AND   RB.BreakTypeId = @rBreakTypeId 
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		--INNER JOIN   	ON BTM.Id=  RB.BreakTypeId 
            
  WHERE   
  
  ((RB.BreakTypeId = @rBreakTypeId) OR (@rBreakTypeId = 0))
	
		 
       END   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCertificate].[pBonafideAdd]

	@rId bigint
   ,@rAcademicId bigint
   ,@rNumber int
   ,@rBonafideDate date
   ,@rCreatedUserId bigint
   ,@rOrgId int
   ,@rRemark nvarchar(MAX)
   ,@rBonafiedReason nvarchar(200)
   ,@rBatchId int
   ,@rIsNumberBatchWise bit = 0
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	--DECLARE @lOrgGroupId smallint
	--SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrganizationMaster Where Id = @rOrgId

	--DECLARE @lIsBonafideCertificateNumberBatchWise bit
	--SELECT @lIsBonafideCertificateNumberBatchWise = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM
	--	    LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	--	    WHERE CS.ConfigurationId = 290 

	BEGIN TRY	
	 BEGIN TRANSACTION	
	 
	 If(@rIsNumberBatchWise = 0)
	 BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tBonafide WHERE OrgId=@rOrgId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tBonafide WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				COMMIT TRANSACTION
				RETURN
			END
		END
	 END
	 
	 If(@rIsNumberBatchWise = 1)
	 BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tBonafide WHERE OrgId=@rOrgId AND BatchId = @rBatchId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tBonafide WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				COMMIT TRANSACTION
				RETURN
			END
		END
	 END
	
	  DECLARE @lNextNumber BIGINT
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tBonafide', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tBonafide
				(
					Id
				   ,AcademicId
				   ,Number
				   ,BonafideDate
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,Remark
				   ,BonafiedReason
				   ,BatchId
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rNumber
				   ,@rBonafideDate
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate()
				   ,@rRemark 
				   ,@rBonafiedReason
				   ,@rBatchId
				)
		END
		
		ELSE
		
		BEGIN
			SET @lNextNumber = @rId
				UPDATE  sCertificate.tBonafide
				SET
					AcademicId=@rAcademicId,
					BonafideDate=@rBonafideDate,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					Remark=@rRemark,
					BonafiedReason=@rBonafiedReason,
					BatchId = @rBatchId
				WHERE Id = @rId
		 END  	
		
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pBonafideGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rClassId int,
	 @rDivisionId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			BC.Id,
			BC.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			BC.Number,
			BC.BonafideDate,
			BC.Remark,
			ISNULL(BC.BonafiedReason,'') AS BonafiedReason
			
  FROM 
            sCertificate.tBonafide BC
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=BC.AcademicId AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
  
	((BC.Id = @rId) OR (@rId = 0))
	AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
	AND ((BC.Number >= @rFromNo) OR (@rFromNo=0))
	AND ((BC.Number <= @rToNo) OR (@rToNo=0))
	AND ((BC.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((BC.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND (SA.ClassId = @rClassId OR @rClassId = 0)
	AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
	ORDER BY BC.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pBulkGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Name,
			SA.Code
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId order by SA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCertificate].[pCharacterAdd]

	@rId bigint
   ,@rAcademicId bigint
   ,@rNumber int
   ,@rCharacterDate date
   ,@rCreatedUserId bigint
   ,@rOrgId int
   ,@rRemark nvarchar(200)
   ,@rBatchId int
   ,@rIsNumberBatchWise bit = 0
	       
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		
	
	If(@rIsNumberBatchWise = 1)	
	BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tCharacter WHERE OrgId=@rOrgId AND BatchId = @rBatchId
		END	
		
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tCharacter WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
	END
	ELSE
	BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tCharacter WHERE OrgId=@rOrgId 
		END	
		
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tCharacter WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
	END
		
	 DECLARE @lNextNumber BIGINT
	 BEGIN TRANSACTION
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tCharacter', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCertificate.tCharacter
			(
				Id
			   ,AcademicId
			   ,Number
			   ,characterDate
			   ,OrgId
			   ,CreatedUserId
			   ,CreatedDateTime
			   ,Remark
			   ,BatchId
			)
			VALUES
			(	@lNextNumber
			   ,@rAcademicId
			   ,@rNumber
			   ,@rCharacterDate
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate() 
			   ,@rRemark
			   ,@rBatchId
			)
		END
		ELSE
		BEGIN
			SET @lNextNumber = @rId
			UPDATE  sCertificate.tCharacter
			SET
				AcademicId=@rAcademicId,
				characterDate=@rCharacterDate,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate(),
				Remark=@rRemark,
				BatchId = @rBatchId
			  WHERE Id = @rId
		END  	
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		Select error_message()
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCertificate].[pCharacterBulkGet]
	 
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,			
			SA.Name,
			ISNULL(c.Id,0) AS Id,
			ISNULL(c.characterDate,'') AS characterDate			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT JOIN sCertificate.tCharacter c ON c.AcademicId=SA.AcademicId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId order by SA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCertificate].[pCharacterGet]
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rClassId int,
	 @rDivisionId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			 SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			CC.Id,
			CC.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			CC.Number,
			CC.characterDate,
			CC.Remark
  FROM 
			sCertificate.tCharacter CC
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CC.AcademicId AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
  
		((CC.Id = @rId) OR (@rId = 0))
		AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
		AND ((CC.Number >= @rFromNo) OR (@rFromNo=0))
		AND ((CC.Number <= @rToNo) OR (@rToNo=0))
		AND ((CC.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CC.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SA.ClassId = @rClassId OR @rClassId = 0)
		AND (SA.DivisionId =@rDivisionId OR @rDivisionId = 0)
		ORDER BY CC.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pClubHouseCommiteeBulkGet]  
  @rDepartmentId int= 0,  
  @rTypeId int = 0,
  @rTypeDetailId int = 0

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON   
    BEGIN  
	IF(@rTypeId = 1) -- Club	
	   BEGIN
			SELECT
				ISNULL(AC.ClubId,0) AS Id,
				ISNULL(EM.Id,0) AS EmployeeId,    
				(EM.FirstName+' '+EM.LastName) as Name,    
				EM.Code
			From  
				sHrm.tEmployeeMaster EM
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
				LEFT JOIN sHrm.tAssignClub AC ON AC.EmployeeId=EM.Id AND  ((AC.ClubId=@rTypeDetailId) OR (@rTypeDetailId = 0))
			WHERE 
				((EJD.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
				AND EM.StatusId = 7
		END	
	IF(@rTypeId = 2) -- House
		BEGIN
		 SELECT
		     ISNULL(AH.HouseId,0) AS Id,
		     ISNULL(EM.Id,0) AS EmployeeId,
             EM.FirstName+' '+EM.LastName as Name,    
             EM.Code
         From  
		    sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			LEFT JOIN sHrm.tAssignHouse AH ON AH.EmployeeId=EM.Id AND  ((AH.HouseId=@rTypeDetailId) OR (@rTypeDetailId = 0))   
		WHERE 
		      ((EJD.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
				AND EM.StatusId = 7
  END	
	IF(@rTypeId = 3) -- Commitee
		BEGIN
		 SELECT
		     ISNULL(ACMT.CommitteeId,0) AS Id,
		     ISNULL(EM.Id,0) AS EmployeeId,
             EM.FirstName+' '+EM.LastName as Name,    
             EM.Code
         From  
		    sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			LEFT JOIN sHrm.tAssignCommittee ACMT ON ACMT.EmployeeId=EM.Id AND  ((ACMT.CommitteeId=@rTypeDetailId) OR (@rTypeDetailId = 0))	
		  WHERE 
		     ((EJD.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
			 AND EM.StatusId = 7
		END	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCertificate].[pFirstTrialAdd]
			
		@rId bigint
       ,@rAcademicId bigint
       ,@rNumber int
       ,@rFirstTrialDate date
       ,@rExamYear nvarchar(20)
       ,@rExamCentre nvarchar(100)
       ,@rSeatNo nvarchar(50)
       ,@rTrial nvarchar(20)
       ,@rCreatedUserId bigint
       ,@rOrgId int
       ,@rRemark nvarchar(200)
       ,@rBatchId int
       ,@rIsNumberBatchWise bit = 0
	   ,@rLastExamName nvarchar(150) = '' -- Mantis : 0027927 #Start
	   ,@rObtainedMark nvarchar(100) = ''
	   ,@rAdditionalRemark nvarchar(max) = '' -- #End

           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	If(@rIsNumberBatchWise = 1)
	BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) FROM sCertificate.tFirstTrial WHERE OrgId=@rOrgId AND BatchId = @rBatchId
			SET @rNumber = @rNumber + 1
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tFirstTrial WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	 END
	 ELSE
	 BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) FROM sCertificate.tFirstTrial WHERE OrgId=@rOrgId AND BatchId = @rBatchId
			SET @rNumber = @rNumber + 1
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tFirstTrial WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	  END
	 
	  DECLARE @lNextNumber BIGINT
	  BEGIN TRY
	BEGIN TRANSACTION
	  IF(@rId = 0)	
		BEGIN
			
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tFirstTrial', 0, 1, 1,@outNextNumber = @lNextNumber output
			
			INSERT INTO sCertificate.tFirstTrial
			(
				Id
			   ,AcademicId
			   ,Number
			   ,FirstTrialDate
			   ,ExamYear
			   ,ExamCentre
			   ,SeatNo
			   ,Trial
			   ,OrgId
			   ,CreatedUserId
			   ,CreatedDateTime
			   ,Remark
			   ,BatchId
			   ,LastExamName -- Mantis : 0027927 #Start
			   ,ObtainedMark
			   ,AdditionalRemark -- #End
			)
			VALUES
			(	@lNextNumber
			   ,@rAcademicId
			   ,@rNumber
			   ,@rFirstTrialDate
			   ,@rExamYear
			   ,@rExamCentre
			   ,@rSeatNo
			   ,@rTrial
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rRemark 
			   ,@rBatchId
			   ,@rLastExamName  -- Mantis : 0027927 #Start
			   ,@rObtainedMark
			   ,@rAdditionalRemark  -- #End
			)		
			SELECT @lNextNumber AS Result
		END
		
		ELSE
		 BEGIN
		 IF  EXISTS(SELECT Id FROM sCertificate.tFirstTrial WHERE AcademicId=@rAcademicId AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			COMMIT TRANSACTION
			RETURN
		END
		 SET @lNextNumber = @rId
			UPDATE  sCertificate.tFirstTrial
			SET
				AcademicId=@rAcademicId,
				FirstTrialDate=@rFirstTrialDate,
				ExamYear=@rExamYear,
				ExamCentre=@rExamCentre,
				SeatNo=@rSeatNo,
				Trial=@rTrial,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate(),
				Remark=@rRemark,
				BatchId = @rBatchId,
				LastExamName = @rLastExamName, -- Mantis : 0027927 #Start
				ObtainedMark = @rObtainedMark,
				AdditionalRemark = @rAdditionalRemark -- #End
			  WHERE Id = @rId
			  SELECT @lNextNumber AS Result
		 END  	
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pFirstTrialBulkGet]
	 
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rStatusId int=0 --Mantis - 33375
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,			
			SA.Name,
			ISNULL(FT.Id,0) AS Id,
			ISNULL(FT.FirstTrialDate,'') AS FirstTrialDate,
			ISNULL(FT.Trial,'') AS Trial,
			ISNULL(FT.SeatNo,'') AS SeatNo,
			ISNULL(FT.ExamCentre,'') AS ExamCentre,
			ISNULL(FT.Remark,'') AS Remark,
			ISNULL(FT.LastExamName,'') AS LastExamName, -- Mantis : 0027927 #Start
			ISNULL(FT.ObtainedMark,'') AS ObtainedMark,
			ISNULL(FT.AdditionalRemark,'') AS AdditionalRemark -- #End
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT JOIN sCertificate.tFirstTrial FT ON FT.AcademicId=SA.AcademicId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId 
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)   --Mantis - 33375
			order by SA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pFirstTrialGet]
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rClassId int,
	 @rDivisionId int,
	 @rFromNo int,
	 @rToNo int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			FT.Id,
			FT.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			FT.Number,
			FT.FirstTrialDate,
			FT.ExamYear,
			FT.ExamCentre,
			FT.SeatNo,
			FT.Trial,
			FT.Remark,
			ISNULL(FT.LastExamName,'') AS LastExamName,   -- Mantis : 0027927 #Start
			ISNULL(FT.ObtainedMark,'') AS ObtainedMark,
			ISNULL(FT.AdditionalRemark,'') AS AdditionalRemark -- #End
  FROM 
            sCertificate.tFirstTrial FT
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=FT.AcademicId
			AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
  
      ((FT.Id = @rId) OR (@rId = 0))
     
      AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
      AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
       AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
    AND ((FT.FirstTrialDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((FT.FirstTrialDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((FT.Number >= @rFromNo) OR (@rFromNo=0))
	AND ((FT.Number <= @rToNo) OR (@rToNo = 0))
	
	ORDER BY FT.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pIncrementBulkGet]  
   @rId bigint = 0, 
  @rDesignationId int = 0,  
  @rDepartmentId int= 0,  
  @rOrgId int,  
  @rBatchId int,
  @rCertificateDate Date=''
    
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON   
    BEGIN   
  IF @rCertificateDate IS Null SET @rCertificateDate = ''
   --If @rFromDate IS Null Set @rFromDate = ''
 SELECT   
      
   isnull(CI.Id, 0)As Id,  
   EEM.EmployeeId,    
   EEM.FirstName+' '+EEM.LastName as Name,    
       
   isnull(CI.CertificateDate,'') AS CertificateDate ,    
   isnull(CI.Remark, '') As Remark,  
   EEM.Qualification As Qualification,   
   EEM.Code ,   
  CI.BatchId ,  
 isnull(CI.PayScale, 0)As PayScale, 
 isnull(CI.ExistingBasicPay, 0)As ExistingBasicPay, 
 isnull(CI.RevisedBasicPay,0)As RevisedBasicPay,   
 isnull(CI.RevisedBasicPayDate,'')As RevisedBasicPayDate,
 isnull(CI.GradePayInRevisedPayStructure,0)As GradePayInRevisedPayStructure,
 Isnull(CI.BasicPayInRevisedPayStructureBasicPayAndGradePay,0)As BasicPayInRevisedPayStructureBasicPayAndGradePay,  
 Isnull(CI.GrossSalaryAsPerExistingPayScale,0)As GrossSalaryAsPerExistingPayScale, 
 Isnull(CI.RevisedGrossSalaryAsOn,0)As RevisedGrossSalaryAsOn,   
 Isnull(CI.IncrementDate, '')As  IncrementDate,
 EEM.DepartmentId,
 EEM.DepartmentName as Department,  
 EEM.DesignationId ,
 EEM.Designation
     
  FROM   
  sHrm.vExtEmployeeMaster EEM 
  LEFT JOIN sHrm.tCertificateIncrement CI ON EEM.EmployeeId=CI.EmployeeId --AND EEM.OrgId=@rOrgId     
  AND ((CI.Id = @rId) OR (@rId = 0))    
  AND ((CI.CertificateDate = @rCertificateDate)OR(@rCertificateDate = ''))
  LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = CI.BatchId   AND ((BM.Id = @rBatchId) OR (@rBatchId = 0))       
  WHERE   
  ((EEM.DepartmentId = @rDepartmentId) OR ( @rDepartmentId=0))
  AND ((EEM.DesignationId = @rDesignationId) OR (@rDesignationId=0))
  AND ISNULL(EEM.IsOtherUser,0)=0
	
 ORDER BY CI.Number  DESC 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pIncrementCertificateBulkGet]
	 
	 @rDesignationId int,
	 @rDepartmentId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rEmployeeId bigint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			EEM.EmployeeId,
			EEM.DepartmentName,
			EEM.FirstName +' '+EEM.LastName AS EmployeeName,
			EEM.Code,
			EEM.Designation
			
  FROM 
			sHrm.vExtEmployeeMaster  EEM 
			
  WHERE 
			((EEM.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
			AND (EEM.DepartmentId=@rDepartmentId OR @rDepartmentId=0)
			AND EEM.OrgID=@rOrgId )
			order by EEM.Id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pLeavingAdd]
			
		@rId bigint
       ,@rAcademicId bigint
       ,@rLCNumber int
       ,@rLCDate date
       ,@rLeftDate date
       ,@rLCCopy tinyint
       ,@rLCRemark nvarchar(200)
       ,@rLCProgress nvarchar(200)
       ,@rLCConduct nvarchar(200)
       ,@rLCReason nvarchar(200)
       ,@rLCBookNumber nvarchar(20)
       ,@rCreatedUserId bigint
       ,@rOrgId int
       ,@rToCollege nvarchar(200)
	   ,@rToCollegeAddress nvarchar(200)
	   ,@rLastExamName nvarchar(200)
	   ,@rLastExamResult nvarchar(200)
	   ,@rRepeatDetail nvarchar(100)
	   ,@rSubjectStudied nvarchar(300)
	   ,@rPromoteToClass nvarchar(50)
	   ,@rFeeDetail nvarchar(100)
	   ,@rFeeConcessionDetail nvarchar(100)
	   ,@rExtraCurricularActivities nvarchar(200)
	   ,@rNCCScoutDetail nvarchar(100)
	   ,@rTermsInInstitute nvarchar(500)
	   ,@rBatchId int
	   ,@rIsNumberBatchWise bit = 0
	   ,@rTotalDays int=0
	   ,@rPresentDays int=0
	   ,@rProofOfDOB nvarchar(200)
	   ,@rLCCopyRemark nvarchar(max)
       ,@rLCDisplayName nvarchar(200)	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	DECLARE @lNextNumber BIGINT
	DECLARE @lStudentId bigint
	DECLARE @lClassId bigint
	DECLARE @lAdmissionDate Date
	 
	SELECT @lStudentId=StudentId,@lClassId=ClassId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	UPDATE sStudent.tAcademic SET BatchStatusId = 1 WHERE BatchStatusId is null
	 
	If(@rIsNumberBatchWise = 1)
	BEGIN
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId AND BatchId = @rBatchId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	END	--add this for mantis: 43914
	ELSE
 	BEGIN
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId)-- IN(SELECT Id FROM sStudent.tAcademic WHERE StudentId=@lStudentId))
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	END
			
	IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE AttendanceDate>@rLeftDate AND AcademicId=@rAcademicId)
	BEGIN
		SELECT -101 AS Result
		RETURN
	END
			
	SELECT @lAdmissionDate = AdmissionDate FROM sStudent.tStudentAdmission WHERE StudentId=@lStudentId
	IF (@lAdmissionDate > @rLCDate)
	BEGIN
		SELECT -105 AS Result
		RETURN
	END
		
	IF EXISTS(SELECT Id FROM sCertificate.tLeaving WHERE AcademicId=@rAcademicId AND Id<>@rId)
	BEGIN
		SELECT -103 AS Result
		RETURN
	END
		
		BEGIN TRANSACTION	
			
			IF(@rId = 0)	
			BEGIN
	
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tLeaving', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tLeaving
				(
					Id
				   ,AcademicId
				   ,LCNumber
				   ,LCDate
				   ,LeftDate
				   ,LCCopy
				   ,LCRemark
				   ,LCProgress
				   ,LCConduct
				   ,LCReason
				   ,LCBookNumber
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,ToCollege
				   ,ToCollegeAddress
				   ,LastExamName 
		           ,LastExamResult 
		           ,RepeatDetail 
		           ,SubjectStudied
		           ,PromoteToClass 
		           ,FeeDetail 
		           ,FeeConcessionDetail
		           ,ExtraCurricularActivities
		           ,NCCScoutDetail 
		           ,TermsInInstitute
		           ,BatchId
				   ,TotalDays
				   ,PresentDays
				   ,ProofOfDOB
				   ,LCCopyRemark
				   ,DisplayName
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rLCNumber
				   ,@rLCDate
				   ,@rLeftDate
				   ,@rLCCopy
				   ,@rLCRemark
				   ,@rLCProgress
				   ,@rLCConduct
				   ,@rLCReason
				   ,@rLCBookNumber
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate() 
				   ,@rToCollege
				   ,@rToCollegeAddress
				   ,@rLastExamName 
		           ,@rLastExamResult 
		           ,@rRepeatDetail 
		           ,@rSubjectStudied
		           ,@rPromoteToClass 
		           ,@rFeeDetail 
		           ,@rFeeConcessionDetail
		           ,@rExtraCurricularActivities
		           ,@rNCCScoutDetail 
		           ,@rTermsInInstitute
		           ,@rBatchId
				   ,@rTotalDays 
			       ,@rPresentDays 
				   ,@rProofOfDOB
				   ,@rLCCopyRemark
				   ,@rLCDisplayName
				)	
				SELECT @lNextNumber AS Result 
				 
			END
		
		ELSE
		
		BEGIN
		
			 select 111
			 SET @lNextNumber = @rId
				UPDATE  sCertificate.tLeaving
				SET
					AcademicId=@rAcademicId,
					LCDate=@rLCDate,
					LeftDate=@rLeftDate,
					LCCopy=@rLCCopy,
					LCRemark=@rLCRemark,
					LCProgress=@rLCProgress,
					LCConduct=@rLCConduct,
					LCReason=@rLCReason,
					LCBookNumber=@rLCBookNumber,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					ToCollege=@rToCollege,
				    ToCollegeAddress=@rToCollegeAddress,
				    LastExamName=@rLastExamName 
				    ,LastExamResult=@rLastExamResult 
				    ,RepeatDetail=@rRepeatDetail 
				    ,SubjectStudied=@rSubjectStudied
				    ,PromoteToClass=@rPromoteToClass 
				    ,FeeDetail=@rFeeDetail 
				    ,FeeConcessionDetail=@rFeeConcessionDetail
				    ,ExtraCurricularActivities=@rExtraCurricularActivities
				    ,NCCScoutDetail=@rNCCScoutDetail 
				    ,TermsInInstitute=@rTermsInInstitute
				    ,BatchId = @rBatchId
					,TotalDays = @rTotalDays 
			        ,PresentDays = @rPresentDays 
					,ProofOfDOB = @rProofOfDOB
					,LCCopyRemark = @rLCCopyRemark
					,DisplayName = @rLCDisplayName
				WHERE Id = @rId
				
		 
		END 
		
		
				UPDATE sStudent.tStudentAdmission
				SET
				  LeftStandardId=@lClassId,
				  LeftDate = @rLeftDate, 
				  LeftReason = @rLCReason, 
				  LCProgress = @rLCProgress,
				  LCConduct = @rLCConduct, 
				  LCBook = @rLCBookNumber, 
				  LCNumber = @rLCNumber,
				  LCDate = @rLCDate, 
				  LCRemark = @rLCRemark, 
				  LCCopy = @rLCCopy, 
				  LcId = @lNextNumber, 
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE StudentId = @lStudentId 
				
				UPDATE sStudent.tStudentMaster
				SET
				  StatusId=3,
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE Id = @lStudentId 
				
			  UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			   WHERE SourceTypeId=2003 AND Sourceid=@lStudentId
			   
		 COMMIT TRANSACTION		
		 
		  --Update Batch Status 
			UPDATE A
			SET BatchStatusId = 3 
			FROM sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
			WHERE SM.StatusId = 3 AND SM.Id = @lStudentId
		 --Ends

		   --Update Class Status 
			UPDATE A
			SET ClassStatusId = 3 ,
			 UpdatedUserId = @rCreatedUserId, 
		     UpdatedDateTime =sCommon.fGetDate()
			FROM sStudent.tAcademic A
			WHERE A.Id = @rAcademicId
		 --Ends
		 
		  SELECT @lNextNumber AS Result
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCertificate].[pLeavingBulkAdd]
			
		@rId bigint
       ,@rAcademicId bigint
       ,@rLCNumber int
       ,@rLCDate date
       ,@rLeftDate date
       ,@rLCCopy tinyint
       ,@rLCRemark nvarchar(200)
       ,@rLCProgress nvarchar(200)
       ,@rLCConduct nvarchar(200)
       ,@rLCReason nvarchar(200)
       ,@rLCBookNumber nvarchar(20)
       ,@rCreatedUserId bigint
       ,@rOrgId int
       ,@rToCollege nvarchar(200)
	   ,@rToCollegeAddress nvarchar(200)
	   ,@rLastExamName nvarchar(200)
	   ,@rLastExamResult nvarchar(200)
	   ,@rRepeatDetail nvarchar(100)
	   ,@rSubjectStudied nvarchar(300)
	   ,@rPromoteToClass nvarchar(50)
	   ,@rFeeDetail nvarchar(100)
	   ,@rFeeConcessionDetail nvarchar(100)
	   ,@rExtraCurricularActivities nvarchar(200)
	   ,@rNCCScoutDetail nvarchar(100)
	   ,@rTermsInInstitute nvarchar(500)
	   ,@rBatchId int
	   ,@rIsNumberBatchWise bit = 0
	   ,@rTotalDays int=0
	   ,@rPresentDays int=0
	   ,@rProofOfDOB nvarchar(200)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	 DECLARE @lNextNumber BIGINT
	 DECLARE @lStudentId bigint
	 DECLARE @lClassId bigint
	 DECLARE @lAdmissionDate Date
	 
	 SELECT @lStudentId=StudentId,@lClassId=ClassId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	 UPDATE sStudent.tAcademic SET BatchStatusId = 1 WHERE BatchStatusId is null
	 
	 If(@rIsNumberBatchWise = 1)
	 BEGIN
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId AND BatchId = @rBatchId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	 ELSE
 	 BEGIN
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId)-- IN(SELECT Id FROM sStudent.tAcademic WHERE StudentId=@lStudentId))
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	END
			
			IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE AttendanceDate>@rLeftDate AND AcademicId=@rAcademicId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			
			SELECT @lAdmissionDate = AdmissionDate FROM sStudent.tStudentAdmission WHERE StudentId=@lStudentId
			IF (@lAdmissionDate > @rLCDate)
			BEGIN
				SELECT -105 AS Result
				RETURN
			END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sCertificate.tLeaving WHERE AcademicId=@rAcademicId AND Id<>@rId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
		
		BEGIN TRANSACTION	
			
		IF(@rId = 0)	
		BEGIN
	
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tLeaving', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tLeaving
				(
					Id
				   ,AcademicId
				   ,LCNumber
				   ,LCDate
				   ,LeftDate
				   ,LCCopy
				   ,LCRemark
				   ,LCProgress
				   ,LCConduct
				   ,LCReason
				   ,LCBookNumber
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,ToCollege
				   ,ToCollegeAddress
				   ,LastExamName 
		           ,LastExamResult 
		           ,RepeatDetail 
		           ,SubjectStudied
		           ,PromoteToClass 
		           ,FeeDetail 
		           ,FeeConcessionDetail
		           ,ExtraCurricularActivities
		           ,NCCScoutDetail 
		           ,TermsInInstitute
		           ,BatchId
				   ,TotalDays
				   ,PresentDays
				   ,ProofOfDOB
				   
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rLCNumber
				   ,@rLCDate
				   ,@rLeftDate
				   ,@rLCCopy
				   ,@rLCRemark
				   ,@rLCProgress
				   ,@rLCConduct
				   ,@rLCReason
				   ,@rLCBookNumber
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate() 
				   ,@rToCollege
				   ,@rToCollegeAddress
				   ,@rLastExamName 
		           ,@rLastExamResult 
		           ,@rRepeatDetail 
		           ,@rSubjectStudied
		           ,@rPromoteToClass 
		           ,@rFeeDetail 
		           ,@rFeeConcessionDetail
		           ,@rExtraCurricularActivities
		           ,@rNCCScoutDetail 
		           ,@rTermsInInstitute
		           ,@rBatchId
				   ,@rTotalDays 
			       ,@rPresentDays 
				   ,@rProofOfDOB
				)	
				SELECT @lNextNumber AS Result 
				 
		END
		
		ELSE
		
		BEGIN
		
			 select 111
			 SET @lNextNumber = @rId
				UPDATE  sCertificate.tLeaving
				SET
					AcademicId=@rAcademicId,
					LCDate=@rLCDate,
					LeftDate=@rLeftDate,
					LCCopy=@rLCCopy,
					LCRemark=@rLCRemark,
					LCProgress=@rLCProgress,
					LCConduct=@rLCConduct,
					LCReason=@rLCReason,
					LCBookNumber=@rLCBookNumber,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					ToCollege=@rToCollege,
				    ToCollegeAddress=@rToCollegeAddress,
				    LastExamName=@rLastExamName 
				    ,LastExamResult=@rLastExamResult 
				    ,RepeatDetail=@rRepeatDetail 
				    ,SubjectStudied=@rSubjectStudied
				    ,PromoteToClass=@rPromoteToClass 
				    ,FeeDetail=@rFeeDetail 
				    ,FeeConcessionDetail=@rFeeConcessionDetail
				    ,ExtraCurricularActivities=@rExtraCurricularActivities
				    ,NCCScoutDetail=@rNCCScoutDetail 
				    ,TermsInInstitute=@rTermsInInstitute
				    ,BatchId = @rBatchId
					,TotalDays = @rTotalDays 
			        ,PresentDays = @rPresentDays 
				WHERE Id = @rId
				
		 
		END 
		
		
				UPDATE sStudent.tStudentAdmission
				SET
				  LeftStandardId=@lClassId,
				  LeftDate = @rLeftDate, 
				  LeftReason = @rLCReason, 
				  LCProgress = @rLCProgress,
				  LCConduct = @rLCConduct, 
				  LCBook = @rLCBookNumber, 
				  LCNumber = @rLCNumber,
				  LCDate = @rLCDate, 
				  LCRemark = @rLCRemark, 
				  LCCopy = @rLCCopy, 
				  LcId = @lNextNumber, 
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE StudentId = @lStudentId 
				
				UPDATE sStudent.tStudentMaster
				SET
				  StatusId=3,
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE Id = @lStudentId 
				
			  UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			   WHERE SourceTypeId=2003 AND Sourceid=@lStudentId
			   
		 COMMIT TRANSACTION		
		 
		  --Update Batch Status 
			UPDATE A
			SET BatchStatusId = 3 
			FROM sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
			WHERE SM.StatusId = 3 AND SM.Id = @lStudentId
		 --Ends

		   --Update Class Status 
			UPDATE A
			SET ClassStatusId = 3 ,
			 UpdatedUserId = @rCreatedUserId, 
		     UpdatedDateTime =sCommon.fGetDate()
			FROM sStudent.tAcademic A
			WHERE A.Id = @rAcademicId
		 --Ends

		 --Update TotalDays And presentDays
		 IF Exists(Select AcademicId from sStudent.tAcademicDetail Where AcademicId =@rAcademicId)
		 BEGIN
		 UPDATE sStudent.tAcademicDetail 
			SET TotalDaysAnnual=@rTotalDays  ,PresentDaysAnnual = @rPresentDays
			WHERE AcademicId =@rAcademicId
		 END
		 ELSE
		 BEGIN
			INSERT INTO sStudent.tAcademicDetail (AcademicId,TotalDaysAnnual,PresentDaysAnnual)VALUES(@rAcademicId,@rTotalDays,@rPresentDays)
		 END
		  SELECT @lNextNumber AS Result
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pLeavingBulkGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rStatusId smallint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,
			SA.Name,
			SA.Number,
			ISNULL(L.Id,0) AS Id,
			ISNULL(L.LCNumber,0) AS LCNumber,
			ISNULL(L.LCDate,'') AS LCDate,
			ISNULL(L.LCRemark,'')AS LCRemark,
			ISNULL(L.LastExamName,'')AS LastExamName,
			ISNULL(L.LastExamResult,'')AS LastExamResult,
			ISNULL(L.RepeatDetail,'')AS RepeatDetail,
			--ISNULL(L.SubjectStudied,'')AS SubjectStudied,
			ISNULL(L.PromoteToClass,'')AS PromoteToClass,
			ISNULL(L.ExtraCurricularActivities,'')As ExtraCurricularActivities,
			ISNULL(L.NCCScoutDetail,'')AS NCCScoutDetail,
			ISNULL(L.TermsInInstitute,'')As TermsInInstitute,
			ISNULL(L.FeeDetail,'')AS FeeDetail,
			ISNULL(L.FeeConcessionDetail,'')AS FeeConcessionDetail,
			ISNULL(AD.TotalDaysAnnual,0)AS TotalDays,
			ISNULL(AD.PresentDaysAnnual,0)AS PresentDays,
			ISNULL(StuA.ProofOfDOB,'')AS ProofOfDOB,
			CASE WHEN EXISTS(SELECT 1 FROM sSetup.tSubjectMaster S  INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
								WHERE S.OrgId=@rOrgId AND CS.IsOptional=0) THEN
			reverse(STUFF(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') + -- +',' + removed for mantis - 0044229
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 0, '')),'') -- Changed 1,1 to 1,0 for prevent to remove last character  - 0044229
						   ), 1, 0, ''))  -- Changed 1,1 to 1,0 for prevent to remove last character  - 0044229
						   
			ELSE

			STUFF(reverse(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') + -- +',' + removed for mantis - 0044229
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 0, '')),'')  -- Changed 1,1 to 1,0 for prevent to remove last character  - 0044229
						   )), 1, 0, '') END AS SubjectStudied,
			(SA.ClassName +'-'+SA.DivisionName)AS ClassDivision

  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT OUTER JOIN sCertificate.tLeaving L ON L.AcademicId=SA.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON SA.AcademicId=AD.AcademicId
			LEFT JOIN sStudent.tStudentAdmission StuA ON StuA.StudentId = SA.StudentId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId 
			AND L.Id IS NULL
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			--order by
			--CASE @rOrderBy WHEN 2 THEN (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code  END) END,
			--CASE @rOrderBy WHEN 1 THEN SA.RollNo END,
			--CASE @rOrderBy WHEN 0 THEN SA.RollNo END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--USE [NetVidyalaya]

CREATE OR ALTER PROCEDURE [sCertificate].[pLeavingGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
			
		END
	
	SELECT 
	
			L.Id,
			L.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			L.LCNumber,
			L.LCDate,
			L.LeftDate,
			L.LCCopy,
			L.LCRemark,
			L.LCProgress,
			L.LCConduct,
			L.LCReason,
			L.LCBookNumber,
			L.ToCollege,
			L.ToCollegeAddress
			,L.LastExamName 
		    ,L.LastExamResult 
		    ,L.RepeatDetail 
		    ,L.SubjectStudied
		    ,L.PromoteToClass 
		    ,L.FeeDetail 
		    ,L.FeeConcessionDetail
		    ,L.ExtraCurricularActivities
		    ,L.NCCScoutDetail 
		    ,L.TermsInInstitute
			,ISNULL(L.TotalDays,0)AS TotalDays
			,ISNULL(L.PresentDays,0) AS PresentDays
			,StuA.ProofOfDOB
			,ISNULL(L.LCCopyRemark,'') AS LCCopyRemark
			--Added by Dhananjay for mantis Start - 0034457
			,ISNULL(CM.ClassNameInWord,'') AS ClassNameInWord 
			, ISNULL(SA.BatchName,'') AS BatchName
			,ISNULL(AD.TotalDaysAnnual,0) As TotalDaysAnnual
			,ISNULL(AD.PresentDaysAnnual,0) As PresentDaysAnnual
			--Added by Dhananjay for mantis End - 0034457
			,SA.StatusId 
			,SA.StatusName  --Added by Nityanand for mantis End- 34985
			,ISNULL(L.DisplayName,'')  AS LCDisplayName --Added by Krunal Patel for mantis End- 0041217
  FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=L.AcademicId
			AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
			LEFT JOIN sStudent.tStudentAdmission StuA ON StuA.StudentId = SA.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId AND CM.OrgId = SA.OrgId   --mantis - 0034457
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = L.AcademicId --mantis - 0034457

			
  WHERE 
			((L.Id = @rId) OR (@rId = 0))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId =@rDivisionId) OR (@rDivisionId = 0))
			AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
			AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((L.LCNumber >= @rFromNo) OR (@rFromNo = 0))
			AND ((L.LCNumber <= @rToNo) OR (@rToNo = 0))
		
			ORDER BY L.LCNumber DESC --DESC for mantis : 0040575	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCertificate].[pOtherCertificateAdd]
	
	@rId bigint,
	@rCertificateTypeId smallint,
    @rAcademicId bigint,
    @rNumber int,
    @rCertificateDate date,
    @rCreatedUserId bigint,
    @rOrgId int,
    @rRemark nvarchar(200)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	 
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tOtherCertificate WHERE OrgId=@rOrgId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tOtherCertificate WHERE Number=@rNumber AND CertificateTypeId=@rCertificateTypeId
			AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			IF EXISTS(SELECT 1 FROM sCertificate.tOtherCertificate WHERE AcademicId=@rAcademicId AND CertificateTypeId=@rCertificateTypeId
			AND OrgId=@rOrgId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END

	  DECLARE @lNextNumber BIGINT
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tOtherCertificate', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tOtherCertificate
				(
					Id,
					CertificateTypeId,
				    AcademicId,
				    Number,
				    CertificateDate,
				    OrgId,
				    CreatedUserId,
				    CreatedDateTime,
				    Remark
				)
				VALUES
				(	@lNextNumber,
					@rCertificateTypeId,
				    @rAcademicId,
				    @rNumber,
				    @rCertificateDate,
				    @rOrgId,
				    @rCreatedUserId,
				    sCommon.fGetDate(),
				    @rRemark
				)
		END
		
		ELSE
		
		BEGIN
			SET @lNextNumber = @rId
				UPDATE  tOtherCertificate
				SET
					AcademicId=@rAcademicId,
					CertificateDate=@rCertificateDate,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					Remark=@rRemark
				WHERE Id = @rId
		 END  	
		
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pOtherCertificateGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rClassId int,
	 @rDivisionId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
			OC.Id,
			OC.CertificateTypeId,
			OC.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			OC.Number,
			OC.CertificateDate,
			OC.Remark,
			CTM.Title AS CertificateType
  FROM 
            sCertificate.tOtherCertificate OC
            INNER JOIN sCertificate.tCertificateTypeMaster CTM ON CTM.Id = OC.CertificateTypeId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=OC.AcademicId 
			AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
  WHERE 
			((OC.Id = @rId) OR (@rId = 0))
			AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
			AND ((OC.Number >= @rFromNo) OR (@rFromNo=0))
			AND ((OC.Number <= @rToNo) OR (@rToNo=0))
			AND ((OC.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OC.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			
  ORDER BY 
			CTM.Id,OC.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pOverallCertificateCountGet]
	 
	 @rTypeId smallint,
	 @rOrgId smallint,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	If @rTypeId = 0 --Overall Certificate Count
	BEGIN
	
		DECLARE @lBonafideCount int, @lLCCount int,@lCharacterCount int,@lFirstTrialCount int
		SELECT @lBonafideCount = COUNT(Number) from sCertificate.tBonafide 
							  Where OrgId = @rOrgId AND BatchId = @rBatchId 
		SELECT @lLCCount = COUNT(LCNumber) from sCertificate.tLeaving 
							  Where OrgId = @rOrgId AND BatchId = @rBatchId 
		SELECT @lCharacterCount = COUNT(Number) from sCertificate.tCharacter 
							  Where OrgId = @rOrgId AND BatchId = @rBatchId 
		SELECT @lFirstTrialCount = COUNT(Number) from sCertificate.tFirstTrial 
							  Where OrgId = @rOrgId AND BatchId = @rBatchId 
		
		SELECT @lBonafideCount AS BonafideCount, @lLCCount AS LCCount,@lCharacterCount AS CharacterCount,  
			   @lFirstTrialCount AS FirstTrialCount
	END
	
	If @rTypeId = 1  --Bonafide Month Wise Count
	BEGIN
		Select M.Id,M.Title AS MonthName , COUNT(Number) AS Count
		From sCommon.tMonthMaster M
		LEFT JOIN sCertificate.tBonafide B ON MONTH(BonafideDate) = M.Id 
		AND B.OrgId = @rOrgId AND B.BatchId = @rBatchId
		GROUP BY M.Id,M.Title
		ORDER BY M.Id 
	END
	
	If @rTypeId = 2  --Bonafide Class Wise Count
	BEGIN
		Select CM.Title AS ClassName, COUNT(Number) AS BonafiedCount, CM.OrderIndex
		From sSetup.tClassMaster CM
		LEFT JOIN sStudent.tAcademic A ON A.ClassId =CM.Id
		LEFT JOIN sCertificate.tBonafide B ON B.AcademicId = A.Id 
		AND B.OrgId = @rOrgId AND B.BatchId = @rBatchId
		Where CM.OrgId = @rOrgId 
		GROUP BY CM.Title , CM.OrderIndex
	END
	
	If @rTypeId = 3  --Leaving Month Wise Count
	BEGIN
		Select M.Id,M.Title AS MonthName , COUNT(LCNumber) AS Count
		From sCommon.tMonthMaster M
		LEFT JOIN sCertificate.tLeaving L ON MONTH(LCDate)  = M.Id 
		AND L.OrgId = @rOrgId AND L.BatchId = @rBatchId
		GROUP BY M.Id,M.Title
		ORDER BY M.Id 
	END
	
	If @rTypeId = 4  --Leaving Class Wise Count
	BEGIN
		Select CM.Title AS ClassName, COUNT(LCNumber) AS Count, CM.OrderIndex
		From sSetup.tClassMaster CM
		LEFT JOIN sStudent.tAcademic A ON A.ClassId =CM.Id
		LEFT JOIN sCertificate.tLeaving L ON L.AcademicId = A.Id  
		AND L.OrgId = @rOrgId AND L.BatchId = @rBatchId
		Where CM.OrgId = @rOrgId
		GROUP BY CM.Title , CM.OrderIndex
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pPrintTemplateAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rTemplate nvarchar(max),
        @rOrgId smallint,
        @rCreatedUserId bigint,
        @rTemplateSourceId tinyint,
        @rPrintTemplateFunctionalityId smallint=0

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

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tPrintTemplate', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCertificate.tPrintTemplate
		(
			Id,
			Title,
			Template,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			TemplateSourceId,
			PrintTemplateFunctionalityId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rTemplate,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rTemplateSourceId,
			@rPrintTemplateFunctionalityId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCertificate.tPrintTemplate
	    SET
			Title=@rTitle,
			Template=@rTemplate,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			PrintTemplateFunctionalityId=@rPrintTemplateFunctionalityId
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pPrintTemplateGet]

	 @rId int,
	 @rOrgId smallint,
	 @rTitle nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			PT.Id,
			PT.Title,
			PT.Template,
		    PT.OrgId,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PT.TemplateSourceId,
		    PT.PrintTemplateFunctionalityId
		    
	FROM 
			sCertificate.tPrintTemplate PT
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pPrintTemplateStudentAdd]
	 
        @rPrintTemplateId int,
        @rTemplate nvarchar(max),
        @rAcademicId bigint,
        @rPrintGroupNumber int,
        @rOrgId int,
        @rBatchId int,
        @rUserId	bigint
        
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tPrintTemplateStudent', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCertificate.tPrintTemplateStudent
		(
			Id,
			PrintTemplateId,
			Template,
			AcademicId,
			PrintGroupNumber,
			BatchId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rPrintTemplateId,
			@rTemplate,
			@rAcademicId,
			@rPrintGroupNumber,
			@rBatchId,
			@rUserId,
			sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pPrintTemplateStudentDelete]
	
	 @rClassId int,
	 @rDivisionId int,
	 @rPrintTemplateId int,
	 @rCode nvarchar(20),
	 @rBatchId int,
	 @rPrintGroupNumber int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DELETE sCertificate.tPrintTemplateStudent
		FROM sCertificate.tPrintTemplateStudent PTS
			INNER JOIN sCertificate.tPrintTemplate PT ON PT.Id=PTS.PrintTemplateId
			INNER JOIN sStudent.tAcademic A ON A.Id=PTS.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
	WHERE 
		(PTS.BatchId=@rBatchId)
		AND ((CM.Id = @rClassId) OR (@rClassId = 0))
		AND ((DivM.Id= @rDivisionId) OR (@rDivisionId = 0))
		AND ((PTS.PrintTemplateId = @rPrintTemplateId) OR (@rPrintTemplateId = 0))
		AND ((SM.Code = @rCode) OR (@rCode = ''))
		AND ((PTS.PrintGroupNumber = @rPrintGroupNumber) OR (@rPrintGroupNumber = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCertificate].[pPrintTemplateStudentGet]
	
	 @rClassId int,
	 @rDivisionId int,
	 @rPrintTemplateId int,
	 @rCode nvarchar(20),
	 @rBatchId int,
	 @rPrintGroupNumber int,
	 @rFromDate date='',
	 @rToDate date=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			PTS.Id,
			PTS.PrintTemplateId,
			PT.Title AS PrintTemplate,
			PTS.Template,
			PTS.AcademicId,
		    PTS.PrintGroupNumber,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivisionName,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName+' '+SM.LastName AS StudentName,
		    SM.Code,
		    A.RollNo
	FROM 
			sCertificate.tPrintTemplateStudent PTS
			INNER JOIN sCertificate.tPrintTemplate PT ON PT.Id=PTS.PrintTemplateId
			INNER JOIN sStudent.tAcademic A ON A.Id=PTS.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
	WHERE 
		(PTS.BatchId=@rBatchId)
		AND ((CM.Id = @rClassId) OR (@rClassId = 0))
		AND ((DivM.Id= @rDivisionId) OR (@rDivisionId = 0))
		AND ((PTS.PrintTemplateId = @rPrintTemplateId) OR (@rPrintTemplateId = 0))
		AND ((SM.Code = @rCode) OR (@rCode = ''))
		AND ((PTS.PrintGroupNumber = @rPrintGroupNumber) OR (@rPrintGroupNumber = 0))
		AND ((CONVERT(date, PTS.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
        AND ((CONVERT(date, PTS.CreatedDateTime)<= @rToDate) OR (ISNULL(@rToDate,'')=''))
		
		
		Order by PTS.PrintGroupNumber DESC, DivM.OrderIndex,SM.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pPrintTemplateStudentListGet]

	 @rDepartmentId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentCode nvarchar(max),
	 @rBatchId int,
	 @rStatusId int = 0,
	 @rAdmissionCategoryId int= 0,		--add
	 @rCastCategoryId int = 0			--add
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			A.Id AS AcademicId,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivisionName,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName+' '+SM.LastName AS StudentName,
		    SM.Code,
		    A.RollNo,
			A.AdmissionCategoryId,		--add
			SO.CastCategoryId			--add
	FROM 
			sStudent.tAcademic A
			RIGHT JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			LEFT JOIN	sStudent.tStudentOther SO ON SO.StudentId = A.StudentId		--add
	WHERE 
		(A.BatchId = @rBatchId)	
		AND ((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0))
		AND ((CM.Id = @rClassId) OR (@rClassId = 0))
		AND ((DivM.Id = @rDivisionId) OR (@rDivisionId = 0))
		AND (ISNULL(SM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
		AND ((SM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((A.AdmissionCategoryId=@rAdmissionCategoryId)OR(@rAdmissionCategoryId=0))		--add
		AND ((SO.CastCategoryId=@rCastCategoryId)OR(@rCastCategoryId=0))					--add
		Order by DivM.OrderIndex,SM.Number
END

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

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

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


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

			ISNULL(U.DisplayTitle,'') AS UserName ,
		
		    ISNULL(EM.FirstName,'') +' '+ISNULL(EM.LastName,'') AS PrincipalName,
			ISNULL(CM.ClassNameInWord,'') AS ClassNameInWord,
			CM2.Title AS LeftStandard,
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,			--add for 27638 mantis
			ISNULL(SI.QRCode,'') AS QRCode,							--add for 27638 mantis
			SA.LeftDate AS LeftDate,	
			SM.PENNumber, -- add for Mentis : 0033432
			ISNULL(SO.BirthCountry,'') AS BirthCountry,--added by dhananjay for mantis id : 0035561
			ISNULL(SM.LocalName,'')	AS LocalName,  -- add for mantis : 0035669
			B.Number as BonafideNumber,  --Mantis - 35686
			STM.Title AS Stream, -- Added by dhannajay for mantis - 36807
			B.CreatedDateTime, -- add for mantis : 0039370
			ISNULL(SA.PreviousStandard,'') AS PreviousStandard,  --Mantis - 40321
			ISNULL(SM.ApaarIdNumber,'') AS ApaarIdNumber		--Mantis - 40718
			,ISNULL(SO.MotherTongue,'') AS MotherTongue--mantis : 0042384	

	FROM 
			sCertificate.tBonafide B
			
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=6
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId 
			LEFT JOIN sSecurity.tUser U	ON U.Id=B.CreatedUserId

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

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCertificate].[pRptBonafiedCertificateTemplateWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)='',
     @rOrgGroupBatchId int,
	 @rPrintTemplateId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lTemplate nvarchar(max) = '' 
	SELECT @lTemplate = Template FROM sCertificate.tPrintTemplate WHERE PrintTemplateFunctionalityId = 2 AND Id = @rPrintTemplateId
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id AS BonafideId,
			A.Id AS Academic,
			[sCertificate].[fBonafideCertificateTemplate](A.Id, A.BatchId, @lTemplate) AS Template
		
	FROM 
			sCertificate.tBonafide B		
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCertificate].[pRptBonafiedCertificateWithPreviousDetail]

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

DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lIsDisplayImageHeader bit=0
--added by megha for 0027170
DECLARE @lIsDisplayReligion bit=0
DECLARE @lIsShowPhoto bit = 0

DECLARE @lConfigValue nvarchar(50)

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

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
--DECLARE @rStudentId bigint = 0
--SET @rStudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code = @rCode)

	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			B.Remark AS ReceiptNo,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			CT.Title AS Category,
			CM.DisplayTitle AS ClassName,
			OM.PrincipalSignature,
			DM.DisplayTitle AS Divisionname, 
			CM1.Title AS AdmissionStandard,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			SM.Id AS StudentId,
			SA.LeftDate AS LeftDate,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OM.SmallAddress1,
			OM.SmallAddress2,
			@lIsDisplayReligion AS IsDisplayReligion
	FROM 
			sStudent.tAcademic A
			
			
			LEFT JOIN sCertificate.tBonafide B ON B.AcademicId = A.Id 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id= A.ClassId
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId 
	WHERE 
			A.OrgId=@rOrgId
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			--AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))  
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'')=''))
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			ORDER BY B.BonafideDate DESC
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


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

DECLARE @lConfigValue nvarchar(50)

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

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

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

	--add for 27638 mantis start
	DECLARE @lIsShowPhoto bit = 0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	--add for 27638 mantis end
	
	SELECT 
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			C.Id,
			C.AcademicId,
			SM.Code,
		--	SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
		   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle AS ClassOnly,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			C.characterDate,
			C.Number,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgName,
			OM.StateName+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			SA.AdmissionDate,
			SF.FatherName,
			SF.MotherName,
			@lIDConfigValue AS ItemValue,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			A.Id,
			SA.LeftDate AS LCDate,
			C.Remark AS Remark,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature,
			SM.FirstName,
			SM.LastName,
			SM.MiddleName,
			SM.SUId As SUID,
			DM.DisplayTitle AS DivisionOnly,
			@lIsShowPhoto AS IsShowPhoto,		--add for 27638 mantis start
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
			ISNULL(SI.QRCode,'') AS QRCode,
			SC.PresentStreetOne,
			SC.PresentStreetTwo,
			SC.PresentStreetThree,
			SC.PresentCountry,
			SC.PresentState,
			SC.PresentCity,
			SC.PresentZipCode,
			SC.PresentContactNo,
			SC.PermanentStreetOne,
			SC.PermanentStreetTwo,
			SC.PermanentStreetThree,
			SC.PermanentCountry,
			SC.PermanentState,
			SC.PermanentCity,
			SC.PermanentZipCode,
			SC.PermanentContactNo,		--add for 27638 mantis end
			STM.Title AS Stream,--Added by dhananjay  for mantis : 36807
			ISNULL(CCM.Title,'') AS CastCategory -- add for mantis : 0039141
	FROM 
			sCertificate.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId			--add for 27638 mantis
			INNER JOIN sSetup.tStreamMaster STM On STM.Id = CM.StreamId --Added by dhananjay  for mantis : 36807
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId -- add for mantis : 0039141
	WHERE  
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By C.AcademicId,C.Number,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,C.characterDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,OM.OrgLogo,OM.Title,
		--OM.StreetOne,OM.StreetThree,OM.StreetTwo,OM.PhoneNo
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pRptCharacterCertificateTemplateWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)='',
	 @rPrintTemplateId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lTemplate nvarchar(max) = '' 
	SELECT @lTemplate = Template FROM sCertificate.tPrintTemplate WHERE PrintTemplateFunctionalityId = 3 AND Id = @rPrintTemplateId

	SELECT 
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			C.Id AS CharacterId,
			C.AcademicId,
			[sCertificate].[fCharacterCertificateTemplate](A.Id, A.BatchId, @lTemplate) AS Template

	FROM 
			sCertificate.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId

	WHERE  
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

DECLARE @lIsDisplayImageHeader bit = 0

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

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

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 179 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF(@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF(@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	--add for 28093 mantis start
	DECLARE @lIsShowPhoto bit = 0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	--add for 28093 mantis end

	SELECT
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			FT.Id,
			FT.Number,
			FT.AcademicId,
			FT.FirstTrialDate,
			FT.ExamCentre,
			FT.ExamYear,
			FT.SeatNo,
			FT.Trial,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SM.LastName as Surname,
			SO.GenderId,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SM.StatusId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle  AS ClassName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			(CASE WHEN CGM.Title='10' THEN  'SSC'
			WHEN  CGM.Title='12'  THEN 'HSC'  ElSE CGM.Title + ' '+'std'
			 END) AS Exam,
			 FT.Remark AS Remark,
			 ISNULL(SF.FatherName,'') As FatherName,
			 ISNULL(SF.MotherName,'') As MotherName,
			 SA.AdmissionDate,
			 SO.BirthDateInWord ,
			 SO.DateOfBirth,
			 SI.StudentPhoto,
			 @lIDConfigValue AS ItemValue,
			 SM.SUID ,
			 STM.Title as StreamName,
			 ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			 OM.ReportOrgTitle,
			--(CASE WHEN OI.CertificateHeaderA4Portrait IS NULL THEN
			--OI.CertificateHeaderA4
			--ELSE OI.CertificateHeaderA4Portrait END ) AS CertificateHeader
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			BM.Title AS Batch,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature,
			EI.EmployeeId,
			SC.PresentStreetOne AS PresentStreetOne,		--add for 28093 mantis start
			SC.PresentStreetTwo AS PresentStreetTwo,
			SC.PresentStreetThree AS PresentStreetThree,
			SC.PresentCountry AS PresentCountry,
			SC.PresentState AS PresentState,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			SC.PresentContactNo AS PresentContactNo,
			@lIsShowPhoto AS IsShowPhoto,
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
			ISNULL(SI.QRCode,'') AS QRCode,					--add for 28093 mantis end
			ISNULL(FT.LastExamName,'') AS LastExamName,   -- Mantis : 0027927 #Start
			ISNULL(FT.ObtainedMark,'') AS ObtainedMarkInLastExam,
			ISNULL(FT.AdditionalRemark,'') AS AdditionalRemark,
			DM.DisplayTitle AS DivisionName,
			BM.FromDate AS BatchStartDate,
			BM.ToDate AS BatchEndDate,
			ISNULL(SGM.Title,'') AS StudentGroup,  -- #End
			SA.AdmissionNumber, --Add for Mentis : 0033616
			ISNULL(SM.MiddleName,'') As MiddleName,--Add for Mentis : 0034319
			DPTM.Title AS Department  --added by dhananjay for mantis : 36835

	FROM
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN  sSetup.tStreamMaster STM ON STM.Id= CM.StreamId
			Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = CM.ClassGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id			--add for 28093 mantis
			LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SM.StudentGroupId -- Mantis : 0027927
			INNER JOIN sSetup.tDepartmentMaster DPTM ON DPTM.Id = CM.DepartmentId --added by dhananjay for mantis : 36835
			
	WHERE
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((FT.Number=@rNumber) OR (@rNumber=''))
			AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((FT.Number <= @rToNo) OR (@rToNo=''))
			--Group By FT.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,FT.SeatNo,FT.Trial,SM.Code,SM.FirstName,OM.StateName,SO.GenderId,
			--OM.CityName,OM.StateName,FT.FirstTrialDate,FT.ExamCentre,FT.ExamYear,SM.MiddleName,SM.LastName,OM.CityName,SM.StatusId
			--,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END

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

DECLARE @lTemplate nvarchar(max) = '' 
	SELECT @lTemplate = Template FROM sCertificate.tPrintTemplate WHERE PrintTemplateFunctionalityId = 4 AND Id = @rPrintTemplateId

	SELECT
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			FT.Id AS FirstTrialId,
			FT.AcademicId,
			[sCertificate].[fFirstTrialCertificateTemplate](A.Id, A.BatchId, @lTemplate) AS Template
	FROM
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			
	WHERE
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((FT.Number=@rNumber) OR (@rNumber=''))
			AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((FT.Number <= @rToNo) OR (@rToNo=''))
	END

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

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

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


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

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


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

	--add for 27638 mantis start
	DECLARE @lIsShowPhoto bit = 0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	--add for 27638 mantis end
	
	--Added by Krunal Patel for : mantis- 0041217 
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 598 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayName = 0
	ELSE
	SET @lIsDisplayName = 1	
	

	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			--Added by Krunal Patel for : mantis- 0041217 
			--[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,			
			CASE WHEN @lIsDisplayName=0
			THEN [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId )			
			WHEN @lIsDisplayName=1
			THEN ISNULL(L.displayName,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ))			
			END AS Name,

			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			SO.GenderId,
			
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(SC.PresentState,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			L.RepeatDetail as PromotedorNot,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			--'' AS PromotedorNot,
			ISNULL(L.PromoteToClass,'')  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CMS.ClassNameInWord,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
			,L.TermsInInstitute,
			@lIDConfigValue AS ItemValue 
			,L.LCCopy
			,DM.InchargeEmployeeId AS ClassTeacher
			,vSA.BatchName AS BatchName,
			CSM.Title As CasteCategory,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SI.StudentPhoto,
			SA.AdmissionFormNumber,
			BM.FromDate as BatchStartDate,
			BM.ToDate as BatchEndDate,
			SO.UIDNumber,
			SC.PresentStreetOne AS Address1,
			SC.PresentStreetTwo AS Address2,
			SC.PresentStreetThree AS Address3,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			L.TotalDays,
			L.PresentDays,
			ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
		@rUserName AS UserName,
		EI.EmployeeSign,
		EI1.EmployeeSign AS DivisionInchargeEmployeeSign,
		ISNULL(L.ProofOfDOB,'')AS ProofOfDOB,
		U.LoginTitle AS CreatedUserName,
		OM.PrincipalSignature,
		CM.ClassNameInWord AS AdmissionStandardInWord,
		LM.Title AS LanguageTitle,
		@lIsShowPhoto AS IsShowPhoto,		--add for 27638 mantis start
		CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
		ISNULL(SI.QRCode,'') AS QRCode		--add for 27638 mantis end 
		,ISNULL(L.LCCopyRemark,'') AS LCCopyRemark    --add for 28079 mantis end 
		,ISNULL(SH.IdentificationMark1,'') AS IdentificationMark1,
		ISNULL(L.LastExamName ,'') AS LastExamName,--Mantis - 0032104
		vSA.PENNumber,     --mantis - 0032285
		vSA.DepartmentName AS DepartmentName,  --add for mentis : 0033427
		IsNUll(BGM.Title,'') AS BloodGroup,--mantis - 0033572
		ISNULL(SM.LocalName,'') AS LocalName, -- added by dhananjay for mantis id - 0035713
        ISNULL(CMM.Title,'')	AS LeftStandard	  --added by dhananjay for mantis id - 35764 
		,ISNULL(SH.IdentificationMark2,'') AS IdentificationMark2  --added by dhananjay for mantis id - 36467                     
		,L.CreatedDateTime AS LCCreateDate --add for mantis : 0039190
		,ISNULL(CGM.Title,'') AS AdmissionClassGroup --add for mantis : 0039971
		,ISNULL(CGMS.Title,'') AS CurrentClassGroup --add for mantis : 0039971
		,ISNULL(SM.ApaarIdNumber,'') AS ApaarIdNumber--Added by dhananjay for mantis : 40247
		,ISNULL(ACM.Title ,'') AS FeeCategory		--Mantis - 40574			
		,L.DisplayName AS DisplayName    --Mantis -0041217 - Krunal
		,ISNULL(GM.Title,'')AS Gender	--Mantis - 42635
		,U.DisplayTitle AS CreatedUser		--Mantis - 44570
	
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			INNER JOIN sSecurity.tUser U ON U.Id = L.CreatedUserId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			--LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sSetup.tDivisionInchargeEmployee DIE ON vSA.DivisionId = DIE.DivisionId AND DIE.BatchId = vSA.BatchId
			AND DIE.Number = (SELECT MIN(Number) FROM sSetup.tDivisionInchargeEmployee WHERE  DIE.DivisionId = vSA.DivisionId AND DIE.BatchId = vSA.BatchId)
			LEFT JOIN sHrm.tEmployeeImages EI1 ON EI1.EmployeeId = DIE.EmployeeId
			INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId
			LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id =SO.BloodGroupId --mantis - 0033572
			LEFT JOIN  sSetup.tClassMaster CMM ON CMM.Id= SA.LeftStandardId   --added by dhananjay for mantis id - 35764
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id=CM.ClassGroupId --add for mantis : 0039971
			LEFT JOIN sSetup.tClassGroupMaster CGMS ON CGMS.Id=CMS.ClassGroupId --add for mantis : 0039971
			LEFT JOIN sStudent.tAdmissionCategoryMaster ACM on ACM.Id = vSA.AdmissionCategoryId --Mantis - 40574
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id = vSA.GenderId		--Mantis - 42635

	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCertificate].[pRptLeavingCertificateTemplateWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rLCNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)='',
	 @rUserName nvarchar(100)='',
	 @rPrintTemplateId Int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lTemplate nvarchar(max) = '' 
	SELECT @lTemplate = Template FROM sCertificate.tPrintTemplate WHERE PrintTemplateFunctionalityId = 5 AND Id = @rPrintTemplateId

	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			L.Id AS LeavingId,
			L.AcademicId,
			[sCertificate].[fLeavingCertificateTemplate](vSA.AcademicId, vSA.BatchId, @lTemplate) AS Template
		                                    
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			
	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
END

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

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


	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsShowPhoto = 0
	--ELSE
	--SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 181 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayReligion = 0
	--ELSE
	--SET @lIsDisplayReligion = 1
	
	SELECT @lOrgGroupId = OrgGroupId FROM  sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			OC.Id,
			OC.Number,
			OC.AcademicId,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CONVERT(nvarchar,BM.FromDate,103) AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			OC.CertificateDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			OC.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			SA.LeftDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin) AS LetterHeadMargin,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SA.PreviousStandard,
			SA.PreviousSchool, 
			SM.SUId,
			SO.AdhaarNumber,
			SO.UIDNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel,
			DM.DisplayTitle AS Divisionname,
			@lIDConfigValue AS ItemValue ,
			SM.RecordStatusId,
			SO.BirthState AS BirthState,
			CM1.DisplayTitle AS AdmissionStandard,
			CM2.DisplayTitle AS LeftStandard,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			SO.MotherTongue,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCNumber,
			CM.DisplayTitle AS CurrentStandard,
			BM.Title AS BatchTitle,
			ISNULL(SM.PENNumber,0) AS PENNumber  --add for mantis : 0035811	
	FROM 
			sCertificate.tOtherCertificate OC
			INNER JOIN sStudent.tAcademic A ON OC.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sHostel.tAssignRoom AR On AR.SourceId=A.StudentId AND AR.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id= SA.AdmissionStandardId
			--LEFT JOIN sStudent.tStudentAdmission SA1 ON SA1.AdmissionStandardId = CM1.Id
			LEFT JOIN sSetup.tClassMaster CM2 ON CM2.Id= SA.LeftStandardId
			--LEFT JOIN sStudent.tStudentAdmission SA2 ON SA2.LeftStandardId = CM2.Id
			LEFT JOIN sCertificate.tLeaving L ON L.AcademicId=A.Id
			
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((OC.Number=@rNumber) OR (@rNumber=''))
			AND ((OC.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((OC.Number <= @rToNo) OR (@rToNo=''))
			AND ((OC.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OC.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OC.CertificateTypeId = @rCertificateTypeId) OR (@rCertificateTypeId = 0))
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pRptPrintTemplateStudentGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int,
	 @rDivisionId int,
	 @rPrintTemplateId int,
	 @rCode nvarchar(20),
	 @rBatchId int,
	 @rPrintGroupNumber int,
	 --Mantis Start - 39951
	 @rFromDate date='',	
	 @rToDate date=''
	 --Mantis End - 39951
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PTS.Id,
			PTS.PrintTemplateId,
			PT.Template AS PrintTemplate,
			PTS.Template,
			PTS.AcademicId,
		    PTS.PrintGroupNumber,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivisionName,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName+' '+SM.LastName AS StudentName,
		    SM.Code
	FROM 
			sCertificate.tPrintTemplateStudent PTS
			INNER JOIN sCertificate.tPrintTemplate PT ON PT.Id=PTS.PrintTemplateId
			INNER JOIN sStudent.tAcademic A ON A.Id=PTS.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
	WHERE 
		(PTS.BatchId=@rBatchId)
		AND ((CM.Id = @rClassId) OR (@rClassId = 0))
		AND ((DivM.Id= @rDivisionId) OR (@rDivisionId = 0))
		AND ((PTS.PrintTemplateId = @rPrintTemplateId) OR (@rPrintTemplateId = 0))
		AND ((SM.Code = @rCode) OR (@rCode = ''))
		AND ((PTS.PrintGroupNumber = @rPrintGroupNumber) OR (@rPrintGroupNumber = 0))
		--Mantis Start - 39951
		AND ((CONVERT(date, PTS.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
        AND ((CONVERT(date, PTS.CreatedDateTime)<= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Mantis End - 39951
		Order by PTS.PrintGroupNumber DESC
END

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

BEGIN 
DECLARE @lIsOnPrePrinted bit = 0,@lIsDisplayReligion bit=0,@lConfigValue nvarchar(50),@lIsDisplayImageHeader bit = 0,@lOrgId smallint
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0
Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId

SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId

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

	--add for 27638 mantis start
	DECLARE @lIsShowPhoto bit = 0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	--add for 27638 mantis end

	SELECT  
		T.Number,
		T.TCDate AS TransferDate,
		T.ExamName,
		T.ExamSeatNo,
		T.ExamYear,
		T.ExamResult,
		T.PromotedClass,
		T.TransferConduct,
		T.OptionalSubject,
		T.Remark,
		A.Name,
		A.OrganiZationName,
	    SO.GenderId,
	    SO.DateOfBirth,
	    A.ClassName AS ClassName,
		A.DivisionName AS DivisionName,
		A.Code As StudentCode,
		SO.AdhaarNumber,
		T.SemesterDuration,
		A.StudentId,
		@lIsOnPrePrinted AS IsOnPrePrinted,
		@lIsDisplayImageHeader AS IsDisplayImageHeader,
		OM.OrgLogo,
		OM.ReportOrgTitle AS OrgTitle,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		--OI.CertificateHeaderA4,
		@lIDConfigValue AS ItemValue,
		OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
		ISNULL(SF.FatherName,'') As FatherName,			--add for 27638 mantis start
		ISNULL(SF.MotherName,'') As MotherName,
		A.StatusId,
		SI.StudentPhoto,
		@lIsShowPhoto AS IsShowPhoto,
		CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
		ISNULL(SI.QRCode,'') AS QRCode,
		SC.PresentStreetOne,
		SC.PresentStreetTwo,
		SC.PresentStreetThree,
		SC.PresentCountry,
		SC.PresentState,
		SC.PresentCity,
		SC.PresentZipCode,
		SC.PresentContactNo,
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		SC.PermanentCountry,
		SC.PermanentState,
		SC.PermanentCity,
		SC.PermanentZipCode,
		SC.PermanentContactNo,		--add for 27638 mantis end
		SO.UIDNumber,  --add for 0032936 mantis end
		ISNULL(SO.BirthDateInWord,'') AS DOBInWords,  --add for mantis : 0035007
		ISNULL(T.Reason,'') AS Reason, --Added  by dhananjay for mantis : 37560 
		T.CreatedDateTime, -- Add for mantis : 0038563
		SA.AdmissionDate, --add for mantis : 0039349
		--Mantis Start - 40515
		ISNULL(T.LeftDate,'') AS LeftDate,
		ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
		ISNULL(SA.PreviousStandard,'') AS PreviousStandard,
		ISNULL(A.PENNumber,'') AS PENNumber,
		ISNULL(SO.FamilyCast,'') AS Caste,
		ISNULL(CTM.Title,'') AS Nationality
		--Mantis End - 40515

	From sCertificate.tTransfer T 
	INNER JOIN sStudent.vStudentAcademic A On A.AcademicId=T.AcademicId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId 
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId		--add for 27638 mantis
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId			--add for 27638 mantis
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId		--add for 27638 mantis
	LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId     --add for mantis : 0039349
	LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId		--Mantis - 40515
	WHERE 
		T.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((A.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((T.TCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((T.TCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((A.ClassId=@rClassId) OR(@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((T.Number=@rNumber) OR (@rNumber=''))
		AND ((T.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((T.Number <= @rToNo) OR (@rToNo=''))
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

BEGIN 

DECLARE @lTemplate nvarchar(max) = '' 
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0
        SELECT @lTemplate = Template FROM sCertificate.tPrintTemplate
		 WHERE PrintTemplateFunctionalityId = 6 AND Id = @rPrintTemplateId
		 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			T.Id AS TransferId,
			T.AcademicId,
			[sCertificate].[fTransferCertificateTemplate](A.AcademicId, A.BatchId, @lTemplate) AS Template
			
			From sCertificate.tTransfer T 
			INNER JOIN sStudent.vStudentAcademic A On A.AcademicId=T.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId 
			WHERE 
				T.OrgId=@rOrgId
				AND	A.BatchId = @rBatchId 
				AND ((A.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((A.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				AND ((T.TCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((T.TCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND ((A.ClassId=@rClassId) OR(@rClassId=0))
				AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((T.Number=@rNumber) OR (@rNumber=''))
				AND ((T.Number >= @rFromNo) OR (@rFromNo=''))
				AND ((T.Number <= @rToNo) OR (@rToNo=''))
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pSummaryCountGet]
	 
	 @rTypeId smallint,
	 @rOrgId smallint,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	If @rTypeId = 0 --Overall Certificate Count
	BEGIN
	
		DECLARE @lBonafideCount int, @lLCCount int,@lCharacterCount int,@lFirstTrialCount int
		SELECT @lBonafideCount = COUNT(Number) from sCertificate.tBonafide 
							  Where OrgId = @rOrgId AND BatchId = @rBatchId 
		SELECT @lLCCount = COUNT(LCNumber) from sCertificate.tLeaving 
							  Where OrgId = @rOrgId AND BatchId = @rBatchId 
		SELECT @lCharacterCount = COUNT(Number) from sCertificate.tCharacter 
							  Where OrgId = @rOrgId AND BatchId = @rBatchId 
		SELECT @lFirstTrialCount = COUNT(Number) from sCertificate.tFirstTrial 
							  Where OrgId = @rOrgId AND BatchId = @rBatchId 
		
		SELECT @lBonafideCount AS BonafideCount, @lLCCount AS LCCount,@lCharacterCount AS CharacterCount,  
			   @lFirstTrialCount AS FirstTrialCount
	END
	
	If @rTypeId = 1  --Bonafide Month Wise Count
	BEGIN
		Select CONVERT(varchar,LEFT(M.Title,3)) + '-' + CONVERT(varchar,RIGHT(MY.YearNumber,2)) AS MonthName,COUNT(B.Id) AS Count,MY.MonthNumber
		FROM sSetup.fMonthYearForBatchGET(@rBatchId) MY
		LEFT JOIN sCommon.tMonthMaster M ON M.Id = MY.MonthNumber
		LEFT JOIN sCertificate.tBonafide B ON MONTH(BonafideDate) = M.Id AND YEAR(BonafideDate) = MY.YearNumber AND B.OrgId = @rOrgId AND B.BatchId = @rBatchId
		GROUP BY MY.YearNumber,MY.MonthNumber, M.Title
		ORDER BY  MY.YearNumber,MY.MonthNumber
	END
	
	If @rTypeId = 2  --Bonafide Class Wise Count
	BEGIN
		Select CM.Title AS ClassName, COUNT(Number) AS BonafiedCount, CM.OrderIndex
		From sSetup.tClassMaster CM
		LEFT JOIN sStudent.tAcademic A ON A.ClassId =CM.Id
		LEFT JOIN sCertificate.tBonafide B ON B.AcademicId = A.Id 
		AND B.OrgId = @rOrgId AND B.BatchId = @rBatchId
		LEFT JOIN sSetup.tBatchMaster BM On BM.Id = B.BatchId AND B.BonafideDate BETWEEN BM.FromDate AND BM.ToDate
		Where CM.OrgId = @rOrgId 
		GROUP BY CM.Title , CM.OrderIndex
	END
	
	If @rTypeId = 3  --Leaving Month Wise Count
	BEGIN
		Select CONVERT(varchar,LEFT(M.Title,3)) + '-' + CONVERT(varchar,RIGHT(MY.YearNumber,2)) AS MonthName,COUNT(L.Id) AS Count,MY.MonthNumber 
		FROM sSetup.fMonthYearForBatchGET(@rBatchId) MY
		LEFT JOIN sCommon.tMonthMaster M ON M.Id = MY.MonthNumber
		LEFT JOIN sCertificate.tLeaving L ON MONTH(LCDate)  = M.Id  AND YEAR(LCDate) = MY.YearNumber AND L.OrgId = @rOrgId AND L.BatchId = @rBatchId
		GROUP BY MY.YearNumber,MY.MonthNumber, M.Title
		ORDER BY  MY.YearNumber,MY.MonthNumber
	END
	
	If @rTypeId = 4  --Leaving Class Wise Count
	BEGIN
		Select CM.Title AS ClassName, COUNT(LCNumber) AS Count, CM.OrderIndex
		From sSetup.tClassMaster CM
		LEFT JOIN sStudent.tAcademic A ON A.ClassId =CM.Id
		LEFT JOIN sCertificate.tLeaving L ON L.AcademicId = A.Id  
		AND L.OrgId = @rOrgId AND L.BatchId = @rBatchId
		LEFT JOIN sSetup.tBatchMaster BM On BM.Id = L.BatchId AND L.LCDate BETWEEN BM.FromDate AND BM.ToDate
		Where CM.OrgId = @rOrgId
		GROUP BY CM.Title , CM.OrderIndex
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCertificate].[pTemplateFunctionalFieldsGet]
           @rPrintTemplateFuctionalId int           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		
BEGIN	 	
	       IF(@rPrintTemplateFuctionalId=1)
	         BEGIN	            
	   --         SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateStudentBasicDetails') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				select TOP 1  ColumnList
                  FROM [sCertificate].[vPrintTemplateStudentBasicDetails]		    
			 END   
		   IF(@rPrintTemplateFuctionalId=2)
		     BEGIN
		  --      SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateBonafideCertificate') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				
				select TOP 1  ColumnList
                  FROM [sCertificate].[vPrintTemplateBonafideCertificate]
				
				
				
		     END
		     IF(@rPrintTemplateFuctionalId=3)
		     BEGIN
		  --      SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateCharacterCertificate') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				
				
				select TOP 1 ColumnList
                  FROM [sCertificate].[vPrintTemplateCharacterCertificate]
		     END
		     IF(@rPrintTemplateFuctionalId=4)
		     BEGIN
		  --      SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateFirstTrialCertificate') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				
				select TOP 1 ColumnList
                  FROM [sCertificate].[vPrintTemplateFirstTrialCertificate]
		     END
		      IF(@rPrintTemplateFuctionalId=5)
		     BEGIN
		  --      SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateLeavingCertificate') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				select TOP 1 ColumnList
                  FROM [sCertificate].[vPrintTemplateLeavingCertificate]
				
		     END
		     IF(@rPrintTemplateFuctionalId=6)
		     BEGIN
		  --      SELECT SUBSTRING(
				--	(SELECT ',' + '['+ s.COLUMN_NAME +']'
				--	FROM (SELECT
				--		COLUMN_NAME
				--FROM
  		--			INFORMATION_SCHEMA.COLUMNS
				--WHERE
				--    TABLE_NAME = 'vPrintTemplateTransferCertificate') s
				--ORDER BY s.COLUMN_NAME
				--FOR XML PATH('')),2,200000) AS ColumnList	
				
				--Changes for mantis 0040777/0040865 :  By Krunal K Patel : for Transfer Certificate Options Added.
				select TOP 1 ColumnList
                  --FROM [sCertificate].[vPrintTemplateTransferCertificate]
				  FROM [sCertificate].[vPrintTemplateTransferCertificateReport]
		     END
		      IF(@rPrintTemplateFuctionalId=7)
		     BEGIN
		  
				select TOP 1 ColumnList
                 
				  FROM [sHrm].[vPrintTemplateJoiningCertificateGet]
		     END
		     	 			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCertificate].[pTransferAdd]
			
	@rId bigint
   ,@rAcademicId bigint
   ,@rNumber int
   ,@rTCDate date
   ,@rSemesterDuration nvarchar(100)
   ,@rExamName nvarchar(100)
   ,@rExamSeatNo nvarchar(50)
   ,@rExamYear nvarchar(50)
   ,@rExamResult nvarchar(50)
   ,@rPromotedClass nvarchar(50)
   ,@rTransferConduct nvarchar(200)
   ,@rOptionalSubject nvarchar(200)
   ,@rReason nvarchar(200)
   ,@rRemark nvarchar(200)
   ,@rOrgId int
   ,@rCreatedUserId bigint
   ,@rLeftDate date
   ,@rBatchId int
   ,@rIsNumberBatchWise bit
           
          	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 BEGIN TRY
	 DECLARE @lNextNumber BIGINT
	 DECLARE @lStudentId bigint
	 DECLARE @lClassId bigint
	 DECLARE @lAdmissionDate Date
	 
	 SELECT @lStudentId=StudentId,@lClassId=ClassId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	 If(@rIsNumberBatchWise = 1)
	 BEGIN
		IF(@rNumber = 0)
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tTransfer WHERE OrgId=@rOrgId AND BatchId=@rBatchId
		END
	 END
	 ELSE
	 BEGIN
		IF(@rNumber = 0)
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tTransfer WHERE OrgId=@rOrgId
		END
	 END	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tTransfer WHERE AcademicId = @rAcademicId AND BatchId=@rBatchId) 
						BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tTransfer WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId=@rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE AttendanceDate>@rLeftDate AND AcademicId=@rAcademicId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			
			SELECT @lAdmissionDate = AdmissionDate FROM sStudent.tStudentAdmission WHERE StudentId=@lStudentId
			IF (@lAdmissionDate > @rTCDate)
			BEGIN
				SELECT -105 AS Result
				RETURN
			END
			
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sCertificate.tTransfer WHERE AcademicId=@rAcademicId AND Id<>@rId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
		END
		
		BEGIN TRANSACTION	
			
		IF(@rId = 0)	
		BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tTransfer', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tTransfer
				(
					Id
				   ,AcademicId
				   ,Number
				   ,TCDate
				    ,LeftDate
				   ,SemesterDuration
				   ,ExamName
				   ,ExamSeatNo
				   ,ExamYear
				   ,ExamResult
				   ,PromotedClass
				   ,TransferConduct
				   ,OptionalSubject
				   ,Reason
				   ,Remark
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,BatchId
				)
				VALUES
				(	
					@lNextNumber
				   ,@rAcademicId
				   ,@rNumber 
				   ,@rTCDate 
				   ,@rLeftDate
				   ,@rSemesterDuration 
				   ,@rExamName 
				   ,@rExamSeatNo 
				   ,@rExamYear 
				   ,@rExamResult 
				   ,@rPromotedClass 
				   ,@rTransferConduct 
				   ,@rOptionalSubject 
				   ,@rReason 
				   ,@rRemark 
				   ,@rOrgId 
				   ,@rCreatedUserId 
				   ,sCommon.fGetDate()
				   ,@rBatchId
				)	
				SELECT @lNextNumber AS Result 
		END
		ELSE
		BEGIN
		
			 SET @lNextNumber = @rId
				UPDATE  sCertificate.tTransfer
				SET
					AcademicId=@rAcademicId,
					Number=@rNumber
				   ,TCDate=@rTCDate
				   ,LeftDate=@rLeftDate
				   ,SemesterDuration=@rSemesterDuration
				   ,ExamName=@rExamName
				   ,ExamSeatNo=@rExamSeatNo
				   ,ExamYear=@rExamYear
				   ,ExamResult=@rExamResult
				   ,PromotedClass=@rPromotedClass
				   ,TransferConduct=@rTransferConduct
				   ,OptionalSubject=@rOptionalSubject
				   ,Reason=@rReason
				   ,Remark=@rRemark
				   ,OrgId=@rOrgId
				   ,UpdatedUserId=@rCreatedUserId,
				   UpdatedDateTime=sCommon.fGetDate(),
				   BatchId = @rBatchId
				WHERE Id = @rId
				SELECT @lNextNumber AS Result
		END 
			UPDATE sStudent.tStudentAdmission
				SET
				  LeftStandardId=@lClassId,
				  LeftDate = @rLeftDate, 
				  LeftReason = @rReason, 
				  LCConduct = @rTransferConduct,
				  LCDate = @rTCDate, 
				  LCRemark = @rRemark, 
				  LcId = @lNextNumber, 
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE StudentId = @lStudentId 
				
				UPDATE sStudent.tStudentMaster
				SET
				  StatusId=3,
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE Id = @lStudentId 
					
		 COMMIT TRANSACTION		
		  
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCertificate].[pTransferGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
			
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision
			,L.Id
             ,L.AcademicId
             ,L.Number
             ,TCDate
			 ,[SemesterDuration]
			 ,[ExamName]
			 ,[ExamSeatNo]
			 ,[ExamYear]
			   ,[ExamResult]
			   ,[PromotedClass]
			   ,[TransferConduct]
			   ,[OptionalSubject]
			   ,[Reason]
			   ,[Remark]
			   ,L.OrgId
			   ,LeftDate
			
  FROM 
			sCertificate.tTransfer  L
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=L.AcademicId
			AND SA.OrgId=@rOrgId 
			AND SA.BatchId=@rBatchId
  WHERE 
			((L.Id = @rId) OR (@rId = 0))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId =@rDivisionId) OR (@rDivisionId = 0))
			AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
			AND ((L.TCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((L.TCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((L.Number >= @rFromNo) OR (@rFromNo = 0))
			AND ((L.Number <= @rToNo) OR (@rToNo = 0))
			ORDER BY L.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sChatbot].[pChatbotAuditLogAdd]
	   @rChannelId bigint,	
	   @rUserId bigint,
       @rQuestion nvarchar(max),
	   @rAnswer nvarchar(max)
	   

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION
	 DECLARE @lChannelId bigint, @lChatId bigint
	 IF(@rChannelId = 0)
	 BEGIN
		
		INSERT INTO sChatbot.tChatbotAuditLog
           (
		    UserId
           ,CreatedDateTime
           )
		VALUES
			(
			 @rUserId,
			 sCommon.fGetDate()
			 )

		SET @lChannelId = @@Identity

		INSERT INTO sChatbot.tChatbotAuditLogDetail
           (
		    ChannelId
           ,Question
           ,Answer
           ,CreatedDateTime
           )
     VALUES
           (
		    @lChannelId
           ,@rQuestion
           ,@rAnswer
           ,sCommon.fGetDate()
           )
		SET @lChatId = @@Identity

		SELECT @lChannelId AS ChannelId, @lChatId AS ChatId
	 END
	 
	 ELSE
	 BEGIN
		INSERT INTO sChatbot.tChatbotAuditLogDetail
           (
		    ChannelId
           ,Question
           ,Answer
           ,CreatedDateTime
           )
       VALUES
           (
		    @rChannelId
           ,@rQuestion
           ,@rAnswer
           ,sCommon.fGetDate()
           )
		SET @lChatId = @@Identity
		SELECT @rChannelId AS ChannelId, @lChatId AS ChatId
	 END	
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sChatbot].[pChatbotFeedbackUpdate]
	   @rChannelId bigint,
       @rChatId bigint,
	   @rFeedback bit,
	   @rAnsFeedback bit,
	   @rDescription nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF(@rChannelId > 0 AND @rChatId = 0)
BEGIN
	UPDATE sChatbot.tChatbotAuditLog SET Feedback = @rFeedback , Description = @rDescription , UpdatedDateTime = sCommon.fGetDate()
	WHERE ChannelId = @rChannelId

END
ELSE
BEGIN
	UPDATE sChatbot.tChatbotAuditLogDetail SET Feedback = @rAnsFeedback, UpdatedDateTime = sCommon.fGetDate()
	WHERE ChatId = @rChatId
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sClient].[pIshaDetailEmployeeModelGet]
	 
  @rEmployeeId bigint =0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 Em.Id AS EmployeeID,
		 Em.FirstName + ' ' + EM.LastName AS FullName,
		 Gm.Title As Gender,
		 EC.CompanyEmail As Email, 
		 EC.MobileNumber ,
		 EPD.DateOfBirth, 
		 EM.Code,
		 EM.FirstName,
		 EM.LastName,
		 SM.Title AS Status
  FROM 
		  sHrm.tEmployeeMaster EM 
		  INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tGenderMaster Gm ON GM.Id = EPD.Genderid
		  INNER JOIn sHrm.tEmployeeCommunications Ec ON Ec.EmployeeID = EM.Id
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId
	Where 
		((Em.id =@rEmployeeId) or (@rEmployeeId=0)) AND ISNULL(EM.IsOtherUser,0) = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sClient].[pIshaDetailStudentModelGet]
	  
	 @rClassId nvarchar(100)='',
	 @rDivisionId nvarchar(100)='',
	 @rHostelId nvarchar(100)='',  
	 @rStudentId nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Sm.Id AS StudentId,
		SM.FIrstName + ' ' + SM.LastName As FullName,
		ISNULL(HM.Id,0) AS HostelId,
		HM.Title AS HostelName,
		CM.title+ '/' +DM.Title AS ClassDivision,
		GM.Title AS Gender,
		SF.FatherName,
		SF.FatherMail,
		SF.FatherContactNo,
		SF.MotherName,
		SF.MotherMail,
		SF.MotherContactNo,
		SC.StudentEmail,
		SC.StudentContactNo,
		SC.ParentEmail AS ContactEmail,
		ISNULL(A.RollNo,0) AS RollNo,
		ISNULL(DM.Id,0) AS DivisionId,
		ISNULL(A.BatchId,0) AS BatchId,
		SM.FIrstName,
		SM.LastName,
		SO.DateOfBirth,
		S.Title AS Status,
		ISNULL(SA.LeftDate,'') AS LeftDate
  FROM
      sStudent.tStudentMaster SM 	
	INNER JOIN sStudent.tAcademic A ON A.StudentId = Sm.Id
    INNER JOIN sStudent.tStudentAdmission SA ON SM.Id = SA.StudentId  
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND IsActive = 1
	LEFT JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	LEFT JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderID 
	LEFT JOIN sStudent.tStudentFamily SF ON Sf.StudentId = Sm.Id 
	LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.Id AND AR.SourceTypeId =2003 AND BM.OrgGroupBatchId= AR.OrgGroupBatchId
	LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	LEFT JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
	LEFT JOIN sStudent.tStudentCommunication SC on SC.Studentid = Sm.Id 
	LEFT JOIN sStudent.tStatusMaster S ON S.Id = SM.StatusId 
	
  WHERE 
	 (ISNULL(Cm.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rClassId,',')) OR @rClassId='') 
	 AND   (ISNULL(DM.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rDivisionId,',')) OR @rDivisionId='') 
	 AND   (ISNULL(RM.hostelId,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rHostelId,',')) OR @rHostelId='') 
	 AND   (ISNULL(SM.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rStudentId,',')) OR @rStudentId='') 
	 ORDER BY DM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sClient].[pIshaDivisionModelGet]
	 
	@rDivisionId int=0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Dm.Id As DivisionId,
		Dm.Title As DivisionName,
		CM.Id as ClassId,
		Cm.Title As ClassName,
		CGm.Title As Grade
  FROM 
		   sSetup.tDivisionMaster DM
		   INNER JOIn sSetup.tClassMaster Cm ON cm.Id = Dm.ClassId
		   INNER JOIN sSetup.tClassGroupMaster CGM ON CGm.Id =Cm.ClassGroupID
 Where ((Dm.Id =@rDivisionId) OR (@rDivisionId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sClient].[pIshaGeneralEmployeeModelGet]
	  @rEmployeeId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 Em.Id AS EmployeeId,
		 Em.FirstName + ' ' + EM.LastName AS FullName,
		 Gm.Title As Gender,
		 EC.CompanyEmail AS Email, 
		 EC.MobileNumber,
		 EM.Code,
		 EM.FirstName,
		 EM.LastName,
		 SM.Title AS Status
		 
  FROM 
		  sHrm.tEmployeeMaster EM 
		  INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tGenderMaster Gm ON GM.Id = EPD.Genderid
		  INNER JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId= EM.Id
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId
 Where 
		((Em.id =@rEmployeeId) or (@remployeeId=0)) AND ISNULL(EM.IsOtherUser,0) = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sClient].[pIshaGeneralStudentModelGet]
	 
 
	 @rClassId nvarchar(100),
	 @rDivisionId nvarchar(100),
	 
	 @rHostelId nvarchar(100),
	 @rStudentId nvarchar(100) 
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		Sm.Id AS StudentId,
		SM.FIrstName + ' ' + SM.LastName As FullName,
		ISNULL(RM.HostelId,0) AS HostelId,
		CM.title+ '/' +DM.Title AS ClassDivision,
		GM.Title AS Gender,
		A.BatchId,
		A.Divisionid ,
		ISNULL(A.RollNo,0) AS RollNo,
		SM.FIrstName,
		SM.LastName,
		SO.DateOfBirth,
		S.Title AS Status
  FROM 
      sStudent.tStudentMaster SM 	
	LEFT JOIN sStudent.tStudentOther SO ON SO.studentid = SM.Id 
	INNER JOIN sStudent.tAcademic A ON A.StudentId = Sm.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND IsActive = 1 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.ID = SO.GenderID 
	LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.Id AND AR.SourceTypeId =2003 AND BM.OrgGroupBatchId= AR.OrgGroupBatchId
	LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
	LEFT JOIN sStudent.tStatusMaster S ON S.Id = SM.StatusId 
		    
  WHERE 
    (ISNULL(Cm.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rClassId,',')) OR @rClassId='') 
	 
	 AND  (ISNULL(DM.Id ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rDivisionId,',')) OR @rDivisionId='') 
	  
     AND (ISNULL(RM.HostelId ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rHostelId,',')) OR @rHostelId='') 
     
     ANd (ISNULL(SM.Id  ,0) IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rStudentId,',')) OR @rStudentId='') 
     
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sClient].[pIshaHostelModelGet]
	  @rHostelId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 HM.Id As HostelId,
		 Hm.Title AS HostelName,
		 HM.Title  As HostelType 
  FROM 
		   sHostel.tHostelMaster HM
		   INNER JOIN  sHostel.tHostelTypeMaster HTM ON HTM.Id = HM.HostelTypeId
 Where 
	((Hm.Id =@rHostelId) OR (@rHostelId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAgeGroupMasterAdd]

	 
	 @rOrgId int,
	 @rId int,
	 @rCode nvarchar(100),
	 @rTitle nvarchar(100),
	 @rAgeFrom int,
	 @rAgeTo int,
	 @rCreatedUserId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


--if exists ( SELECT 1 FROM sCommon.tAgeGroupMaster WHERE AgeFrom >= @rAgeFrom AND AgeFrom <=
	INSERT INTO sCommon.tAgeGroupMaster
		(
			Id,
			Code,
			Title,
			AgeFrom,
			AgeTo,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId 
			 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rAgeFrom,
			@rAgeTo,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId 
		)
		             
	END	 
	 ELSE
	 BEGIN
	  SET @lNextNumber = @rId
	 UPDATE sCommon.tAgeGroupMaster
		SET
			Code=@rCode,
			 Title=@rTitle,
			 AgeFrom=@rAgeFrom,
			 AgeTo=@rAgeTo
			WHERE Id=@rId
			END
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAgeGroupMasterDataCheckGet]
	 @rOrgId int,
	 @rId int  
	  
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
 

	 SELECT Id,
			Code,
			Title AS Name,
			AgeFrom,
			AgeTo 
			 
	   FROM  sCommon.tAgeGroupMaster
	    
	  WHERE  NOT Id IN (@rId)
	  AND  OrgId=@rOrgId
	   
	   order by Id desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAgeGroupMasterGet]
	 @rOrgId int,
	 @rId int,
	 @rCode nvarchar(100),
	 @rTitle nvarchar(100),
	 @rWildCardSearch bit =0
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
If(@rWildCardSearch = 1)
			BEGIN
				 
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END

BEGIN
 

	 SELECT Id,
			Code,
			Title AS Name,
			AgeFrom,
			AgeTo 
			 
	   FROM  sCommon.tAgeGroupMaster
	    
	  WHERE ((Id = @rId) OR (@rId = 0))	  
	   AND((Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND((Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND  OrgId=@rOrgId
	   
	   order by Id desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAnswerMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			Remark,
			TitleResourceKeyId,
			IsObsolete
	   FROM sCommon.tAnswerMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAnswerResultMasterAdd]
	@rTitle [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet 'sCommon.tAnswerResultMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tAnswerResultMaster
		(
			Id,
			Title
		)
	VALUES
		(
			@lNextNumber,
			@rTitle
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAnswerResultMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title
	   FROM sCommon.tAnswerResultMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAnswerResultMasterModify]
	@rId [tinyint],
	@rTitle [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tAnswerResultMaster
		SET 
			Title = @rTitle
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAnswerTypeForQuestionMasterGet]
	@rQuestionId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
		QAM.Id,
		QAM.Title,
		@rQuestionId AS QuestionId
	 FROM sCommon.tQuestionMaster QM 
		INNER JOIN sCommon.tAnswerTypeMaster ATM ON ATM.Id = QM.AnswerTypeId
		INNER JOIN sCommon.tQuestionAnswerMaster QAM ON ATM.Id = QAM.AnswerTypeId
		WHERE QM.Id = @rQuestionId AND QAM.IsObsolete = 0 AND 
		QAM.Id NOT IN (SELECT QuestionAnswerId FROM sCommon.tQuestionAnswerResultMapping WHERE QuestionId = @rQuestionId)

	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAnswerTypeMasterAdd]
	@rCode [nvarchar](20),
	@rTitle [nvarchar](50),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rQuestionAnswerMasterDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet 'sCommon.tAnswerTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tAnswerTypeMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		
		EXEC sCommon.pQuestionAnswerMasterAdd @lNextNumber, @rQuestionAnswerMasterDetailXml
		
		SELECT Result = @lNextNumber
		END TRY
		BEGIN CATCH
		SELECT Result = -1, ERROR_MESSAGE(), ERROR_LINE()
		END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAnswerTypeMasterGet]
	@rId [smallint] = 0,
	@rCode [nvarchar](20) = '',
	@rTitle [nvarchar](50) = '',
	@rIsWildCardSearch [bit] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lAnswerTypeId INT 

IF @rIsWildCardSearch = 1
BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
END

	 SELECT Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sCommon.tAnswerTypeMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
	  AND ((Code LIKE @rCode) OR (@rCode = ''))
	  AND ((Title LIKE @rTitle) OR (@rTitle = ''))
	  
	  
	  
	  IF @rIsWildCardSearch = 0
	  BEGIN
		  IF EXISTS(SELECT 1 FROM sCommon.tAnswerTypeMaster WHERE ((Id = @rId) OR (@rId = 0)) AND ((Code LIKE @rCode) OR (@rCode = '')))
		  BEGIN
			SELECT @lAnswerTypeId = Id FROM sCommon.tAnswerTypeMaster WHERE ((Id = @rId) OR (@rId = 0)) AND ((Code LIKE @rCode) OR (@rCode = ''))
			EXECUTE sCommon.pQuestionAnswerMasterGet 0, @lAnswerTypeId
		  END
	  END
	  ELSE
		
		EXECUTE sCommon.pQuestionAnswerMasterGet 0, @rId
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAnswerTypeMasterModify]
	@rId [smallint],
	@rTitle [nvarchar](50),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rQuestionAnswerMasterXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
	 UPDATE sCommon.tAnswerTypeMaster
		SET 
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  
	  IF @rQuestionAnswerMasterXml <> ''
	  BEGIN
		EXECUTE sCommon.pQuestionAnswerMasterModify @rId, @rQuestionAnswerMasterXml
	  END
	  
	  SELECT Result = @rId
	  END TRY
	  BEGIN CATCH
	  SELECT Result = -1
	  END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAnswerTypeMasterRemove]
	@rId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tAnswerTypeMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAreaMasterAdd]
	@rOrgId [int],
	@rOrgGroupId [int],
	@rTitle [nvarchar](100),
	@rCityId [int] = 0,
	@rCreatedUserID [bigint],
	@rIsShow [bit] = 0,
	@rZipCode nvarchar(10)=''
WITH EXECUTE AS CALLER
AS
--@rAreaId dInt = 0 OUTPUT
SET NOCOUNT ON

BEGIN
--SET @rOrgId = 0
 DECLARE @lId	Int
 DECLARE @lNextNumber INT     
IF(@rIsShow = 0)
		 BEGIN
			 IF(@rCityId = 0)
				 BEGIN
					 IF EXISTS(SELECT 1 FROM sCommon.tAreaMaster WHERE Title = @rTitle AND (CityId IS NULL OR (CityId = @rCityId))AND IsShow = 0 AND OrgGroupId = @rOrgGroupId)
							BEGIN
									SELECT CAST(Id AS Int) Id FROM sCommon.tAreaMaster WHERE Title = @rTitle AND IsShow = 0 AND CityId IS NULL  AND OrgGroupId = @rOrgGroupId
									RETURN

							END
				 END
			 ELSE
				 BEGIN
					 IF EXISTS(SELECT 1 FROM sCommon.tAreaMaster WHERE Title = @rTitle AND ((CityId = @rCityId)) AND IsShow = 0  AND OrgGroupId = @rOrgGroupId)
							BEGIN
									SELECT CAST(Id AS Int) Id FROM sCommon.tAreaMaster WHERE Title = @rTitle AND IsShow = 0 AND ((CityId = @rCityId)  AND OrgGroupId = @rOrgGroupId)
									RETURN
							END
				 END
		 END
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tAreaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output	--Mantis - 43779(@rOrgId to @rOrgGroupId)
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tAreaMaster', 0, 1, 1,@outNextNumber = @lId output
	
		IF(@rIsShow = NULL)
			 BEGIN
				SET @rIsShow = 1
			 END
		
		INSERT INTO sCommon.tAreaMaster
			(
				Id,
				Title,
				CityId,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				IsObsolete, 
				IsShow,
				OrgGroupId,
				ZipCode
			)
		VALUES
			(
				@lNextNumber,
				@rTitle,
				(CASE @rCityId WHEN 0 THEN NULL ELSE @rCityId END),
				@rCreatedUserID,
				sCommon.fGetDate(),
				@rCreatedUserID,
				sCommon.fGetDate(),
				0, 
				@rIsShow,
				@rOrgGroupId,
				@rZipCode
			)
	
		--SET @rAreaId = @lId
		SELECT @lNextNumber AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAreaMasterGet]
	@rOrgGroupId [int],
	@rId [int] = 0,
	@rCityId [int] = 0,
	@rAreaTitle [nvarchar](100) = '',
	@rWildCardSearch int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

IF(@rWildCardSearch = 1)
BEGIN
--SET @rId = sCommon.fSearchStringGet(@rId)
--SET @rCityId = sCommon.fSearchStringGet(@rCityId)
SET @rAreaTitle = sCommon.fSearchStringGet(@rAreaTitle)
END

BEGIN
--SET @rOrgId = 0
	 SELECT AM.Id,			
			AM.CityId,
			CM.StateId,
			SM.CountryId,
			AM.Title,
			AM.CreatedUserId,
			AM.CreatedDateTime,
			AM.UpdatedUserId,
			AM.UpdatedDateTime,
			CM.Title AS CityTitle,
			AM.IsObsolete,
			AM.ZipCode
	FROM sCommon.tAreaMaster AM
		INNER JOIN sCommon.tCityMaster CM ON (AM.CityId = CM.Id)
		INNER JOIN sCommon.tStateMaster SM ON (CM.StateId = SM.Id)
	WHERE ((AM.Id = @rId) OR (@rId = 0))
		AND ((AM.CityId = @rCityId) OR (@rCityId = 0))
		AND ((AM.Title LIKE @rAreaTitle) OR (@rAreaTitle = ''))
		AND (AM.IsShow = 1) /* Don't remove LIKE */
		AND AM.OrgGroupId = @rOrgGroupId
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAreaMasterModify]
	@rId [int],
	@rTitle [nvarchar](100),
	@rCityId [int],
	@rIsObsolete [bit],
	@rUpdatedUserID [bigint],
	@rZipCode nvarchar(10)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	 UPDATE sCommon.tAreaMaster
		SET 
			Title = @rTitle,
			CityId = (CASE @rCityId WHEN 0 THEN NULL ELSE @rCityId END),
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserID,
			UpdatedDateTime = sCommon.fGetDate(),
			ZipCode=@rZipcode
		WHERE Id = @rId		
		
SELECT 1 AS Result

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pAutoCompleteMasterGet]
	@rContextKey [nvarchar](100) = '',
	@rPrefixText [nvarchar](100) = '',
	@rSearchCondition [nvarchar](max) = '',
	@rObsoletedId [nvarchar](300) = '',
	@rExcludingIds [nvarchar](300) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lQueryString Nvarchar(Max)
	
	
	-- Excluding Id START
	DECLARE @lQueryStringTemp Nvarchar(Max)
	DECLARE @lIndexOfComma SmallInt
	DECLARE @lIndexOfDistinct SmallInt
	DECLARE @lLengthOfSelect SmallInt
	DECLARE @lIdColmnName Nvarchar(300)
			
	SELECT	@lQueryStringTemp = QueryString
	FROM	sCommon.tAutoCompleteMaster
	WHERE	((ContextKey = @rContextKey) OR (ISNULL(@rContextKey, '') = ''))
	
	
	-- Find Out the Id Column Name
	SELECT @lIndexOfComma = CHARINDEX(',', @lQueryStringTemp)
	SELECT @lIndexOfDistinct = CHARINDEX(' Distinct ', @lQueryStringTemp)
	IF @lIndexOfDistinct > 0 
		SELECT @lLengthOfSelect = LEN('SELECT DISTINCT')
	ELSE
		SELECT @lLengthOfSelect = LEN('SELECT')	

	--PRINT @lIndexOfComma - 1 - @lLengthOfSelect
	SELECT @lIdColmnName = SUBSTRING (@lQueryStringTemp, @lLengthOfSelect + 1, @lIndexOfComma - 1 - @lLengthOfSelect) 
	PRINT(@lIdColmnName)

		
	
	IF ISNULL(@rExcludingIds, '') ! = ''
	BEGIN
		SET @rSearchCondition = @rSearchCondition + ' AND ' + @lIdColmnName + ' NOT IN ' + @rExcludingIds
	END
	
	-- Excluding Id END
	
	
	
	IF ISNULL(@rObsoletedId, '') = ''
	SET @rObsoletedId = '0'
	
	IF @rObsoletedId = '0'
	BEGIN
	SELECT @lQueryString = QueryString
	FROM sCommon.tAutoCompleteMaster
	WHERE ((ContextKey = @rContextKey) OR (ISNULL(@rContextKey, '') = ''))
	
	--SELECT @lQueryString
	--want to search all words middle words also mantisid : 0034857
	SET @lQueryString = REPLACE(@lQueryString, '{0}', '''%' + @rPrefixText + '%''' + ISNULL(@rSearchCondition, ''))
	--SELECT @lQueryString
	END
	ELSE
	BEGIN
	
	PRINT (@lQueryString)

	DECLARE @lQueryStringMain	Nvarchar(Max)
	DECLARE @lOrderPos			Int
	DECLARE @lObsFrontAndPos	Int
	DECLARE @lObsBackAndPos		Int
	DECLARE @lObsPos			Int
	DECLARE @lDeleted			Bit


SELECT	@lQueryStringMain = QueryString
FROM	sCommon.tAutoCompleteMaster
WHERE	((ContextKey = @rContextKey) 
		OR (ISNULL(@rContextKey, '') = ''))
	
SET @lObsPos = (SELECT CHARINDEX('IsObsolete = 0', @lQueryStringMain))
SET @lObsBackAndPos = (SELECT CHARINDEX('IsObsolete = 0 AND', @lQueryStringMain))
SET @lObsFrontAndPos = (SELECT CHARINDEX('AND IsObsolete = 0', @lQueryStringMain))

SET @lDeleted = 0
IF @lObsBackAndPos > 0
BEGIN
SELECT @lQueryString = STUFF (@lQueryStringMain, @lObsBackAndPos, LEN('IsObsolete = 0 AND'), '')
SET @lDeleted = 1
END
PRINT (@lQueryString)
IF @lObsFrontAndPos > 0
BEGIN
IF @lDeleted = 0
SELECT @lQueryString = STUFF (@lQueryStringMain, @lObsFrontAndPos, LEN('AND IsObsolete = 0'), '') 
SET @lDeleted = 1
END
--PRINT (@lQueryString)
IF @lObsPos > 0
BEGIN
IF @lDeleted = 0
SELECT @lQueryString = STUFF (@lQueryStringMain, @lObsPos, LEN('IsObsolete = 0'), '') WHERE @lDeleted = 0
SET @lDeleted = 1
END

IF @lDeleted = 0
SET @lQueryString = @lQueryStringMain 

SET @lOrderPos = (SELECT CHARINDEX('ORDER BY', @lQueryStringMain))
SELECT @lQueryStringMain = SUBSTRING(@lQueryStringMain, 0, @lOrderPos )

--want to search all words middle words also mantisid : 0034857
SET @lQueryStringMain = REPLACE(@lQueryStringMain, '{0}', '''%' + @rPrefixText + '%''' + ISNULL(@rSearchCondition, ''))




IF ISNULL(@rObsoletedId, '') = ''
SET @rObsoletedId = '0'

--PRINT (@lQueryString)
--want to search all words middle words also mantisid : 0034857
SET @lQueryString = REPLACE(@lQueryString, '{0}', '''%' + @rPrefixText + '%''' + ISNULL(@rSearchCondition, '') + ' AND ID = ' + @rObsoletedId)

SELECT @lQueryString = @lQueryStringMain + ' UNION ' + @lQueryString 
	
	END
		
EXEC(@lQueryString)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAutoCompleteMasterTempGet]
	@rContextKey [nvarchar](100) = '',
	@rPrefixText [nvarchar](100) = '',
	@rSearchCondition [nvarchar](300) = '',
	@rObsoletedId [nvarchar](300) = '',
	@rExcludingIds [nvarchar](300) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lQueryString Nvarchar(Max)		
		
		-- Excluding Id START
		DECLARE @lQueryStringTemp Nvarchar(Max)
		DECLARE @lIndexOfComma SmallInt
		DECLARE @lIndexOfDistinct SmallInt
		DECLARE @lLengthOfSelect SmallInt
		DECLARE @lIdColmnName Nvarchar(300)
				
		SELECT	@lQueryStringTemp = QueryString
			FROM	sCommon.tAutoCompleteMaster
				WHERE	((ContextKey = @rContextKey) OR (ISNULL(@rContextKey,  '') = ''))
				
		-- Find Out the Id Column Name
		SELECT @lIndexOfComma = CHARINDEX(', ',  @lQueryStringTemp)
		SELECT @lIndexOfDistinct = CHARINDEX(' Distinct ',  @lQueryStringTemp)
		IF @lIndexOfDistinct > 0 
			SELECT @lLengthOfSelect = LEN('SELECT DISTINCT')
		ELSE
			SELECT @lLengthOfSelect = LEN('SELECT')

		SELECT @lIdColmnName = SUBSTRING (@lQueryStringTemp,  @lLengthOfSelect + 1,  @lIndexOfComma - 1 - @lLengthOfSelect) 

		IF ISNULL(@rExcludingIds,  '') ! = ''
			SET @rSearchCondition = @rSearchCondition + ' AND ' + @lIdColmnName + ' NOT IN ' + @rExcludingIds
	
	-- Excluding Id END
	
		IF ISNULL(@rObsoletedId,  '') = ''
			SET @rObsoletedId = '0'
	
		IF @rObsoletedId = '0'
			BEGIN
				SELECT @lQueryString = QueryString
					FROM sCommon.tAutoCompleteMaster
						WHERE ((ContextKey = @rContextKey) OR (ISNULL(@rContextKey,  '') = ''))
				
				--SELECT @lQueryString
				SET @lQueryString = REPLACE(@lQueryString,  '{0}',  '''' + @rPrefixText + '%''' + ISNULL(@rSearchCondition,  ''))
				--SELECT @lQueryString
			END
		ELSE
			BEGIN
		
				--PRINT (@lQueryString)

				DECLARE @lQueryStringMain	Nvarchar(Max)
				DECLARE @lOrderPos			Int
				DECLARE @lObsFrontAndPos	Int
				DECLARE @lObsBackAndPos		Int
				DECLARE @lObsPos			Int
				DECLARE @lDeleted			Bit

			SELECT	@lQueryStringMain = QueryString
				FROM	sCommon.tAutoCompleteMaster
					WHERE	((ContextKey = @rContextKey) 
						OR (ISNULL(@rContextKey,  '') = ''))
				
			SET @lObsPos = (SELECT CHARINDEX('IsObsolete = 0',  @lQueryStringMain))
			SET @lObsBackAndPos = (SELECT CHARINDEX('IsObsolete = 0 AND',  @lQueryStringMain))
			SET @lObsFrontAndPos = (SELECT CHARINDEX('AND IsObsolete = 0',  @lQueryStringMain))

			SET @lDeleted = 0
			IF @lObsBackAndPos > 0
			BEGIN
				SELECT @lQueryString = STUFF (@lQueryStringMain,  @lObsBackAndPos,  LEN('IsObsolete = 0 AND'),  '')
				SET @lDeleted = 1
			END
			--PRINT (@lQueryString)
			IF @lObsFrontAndPos > 0
			BEGIN
				IF @lDeleted = 0
					SELECT @lQueryString = STUFF (@lQueryStringMain,  @lObsFrontAndPos,  LEN('AND IsObsolete = 0'),  '') 
					SET @lDeleted = 1
			END
			--PRINT (@lQueryString)
			IF @lObsPos > 0
			BEGIN
				IF @lDeleted = 0
					SELECT @lQueryString = STUFF (@lQueryStringMain,  @lObsPos,  LEN('IsObsolete = 0'),  '') WHERE @lDeleted = 0
					SET @lDeleted = 1
			END

			IF @lDeleted = 0
				SET @lQueryString = @lQueryStringMain 

			SET @lOrderPos = (SELECT CHARINDEX('ORDER BY',  @lQueryStringMain))
			SELECT @lQueryStringMain = SUBSTRING(@lQueryStringMain,  0,  @lOrderPos )


			SET @lQueryStringMain = REPLACE(@lQueryStringMain,  '{0}',  '''' + @rPrefixText + '%''' + ISNULL(@rSearchCondition,  ''))

			IF ISNULL(@rObsoletedId,  '') = ''
				SET @rObsoletedId = '0'

			--PRINT (@lQueryString)

			SET @lQueryString = REPLACE(@lQueryString,  '{0}',  '''' + @rPrefixText + '%''' + ISNULL(@rSearchCondition,  '') + ' AND ID = ' + @rObsoletedId)

			SELECT @lQueryString = @lQueryStringMain + ' UNION ' + @lQueryString 
				
		END
	
	CREATE TABLE #tAbc
	(
		Abc NVARCHAR(500)
	)
	INSERT INTO #tAbc VALUES (@lQueryString)

	SELECT Abc FROM #tAbc

	--EXEC(@lQueryString)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pAutoCompleteMasterValidate]
	@rContextKey [nvarchar](100) = '',
	@rPrefixText [nvarchar](100) = '',
	@rSearchCondition [nvarchar](300) = '',
	@rObsoletedId [nvarchar](300) = '',
	@rExcludingIds [nvarchar](300) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lQueryString		Nvarchar(Max)

DECLARE @lQueryStringMain	Nvarchar(Max)
DECLARE @lOrderPos			Int
DECLARE @lObsFrontAndPos	Int
DECLARE @lObsBackAndPos		Int
DECLARE @lObsPos			Int
DECLARE @lDeleted			Bit

DECLARE @lIndexOfComma SmallInt
DECLARE @lIndexOfDistinct SmallInt
DECLARE @lLengthOfSelect SmallInt
DECLARE @lIdColmnName Nvarchar(300)


SELECT	@lQueryStringMain = QueryString
FROM	sCommon.tAutoCompleteMaster
WHERE	((ContextKey = @rContextKey) OR (ISNULL(@rContextKey, '') = ''))
	
	
-- Find Out the Id Column Name
SELECT @lIndexOfComma = CHARINDEX(',', @lQueryStringMain)
SELECT @lIndexOfDistinct = CHARINDEX(' Distinct ', @lQueryStringMain)
IF @lIndexOfDistinct > 0 
SELECT @lLengthOfSelect = LEN('SELECT DISTINCT')
ELSE
SELECT @lLengthOfSelect = LEN('SELECT')

--PRINT(@lLengthOfSelect)
----PRINT(@lQueryStringMain)
----PRINT(@lIndexOfComma)
SELECT @lIdColmnName = SUBSTRING (@lQueryStringMain, @lLengthOfSelect + 1, @lIndexOfComma - 1 - @lLengthOfSelect) 
--PRINT(@lIdColmnName)
----PRINT(@lQueryStringMain)
-- End
	
	
	-- START Excluding Ids
	IF ISNULL(@rExcludingIds, '') ! = ''
	BEGIN
		SET @rSearchCondition = @rSearchCondition + ' AND ' + @lIdColmnName + ' NOT IN ' + @rExcludingIds
	END
	-- END 
	
SET @lObsPos = (SELECT CHARINDEX('IsObsolete = 0', @lQueryStringMain))
SET @lObsBackAndPos = (SELECT CHARINDEX('IsObsolete = 0 AND', @lQueryStringMain))
SET @lObsFrontAndPos = (SELECT CHARINDEX('AND IsObsolete = 0', @lQueryStringMain))
--SELECT SUBSTRING(@lQueryStringMain, 0, @lOrderPos )
--SELECT SUBSTRING(@lQueryStringMain, 0, @lObsPos )

SET @lDeleted = 0
IF @lObsBackAndPos > 0
BEGIN
SELECT @lQueryString = STUFF (@lQueryStringMain, @lObsBackAndPos, LEN('IsObsolete = 0 AND'), '')
--SELECT 1
SET @lDeleted = 1
END

IF @lObsFrontAndPos > 0
BEGIN
IF @lDeleted = 0
SELECT @lQueryString = STUFF (@lQueryStringMain, @lObsFrontAndPos, LEN('AND IsObsolete = 0'), '') 
--SELECT 2
SET @lDeleted = 1
END

IF @lObsPos > 0
BEGIN
IF @lDeleted = 0
SELECT @lQueryString = STUFF (@lQueryStringMain, @lObsPos, LEN('IsObsolete = 0'), '') WHERE @lDeleted = 0
--SELECT 3
SET @lDeleted = 1
END

IF @lDeleted = 0
SET @lQueryString = @lQueryStringMain 
--SELECT @lQueryString

SET @lOrderPos = (SELECT CHARINDEX('ORDER BY', @lQueryStringMain))
SELECT @lQueryStringMain = SUBSTRING(@lQueryStringMain, 0, @lOrderPos )
----PRINT( @lQueryStringMain)
----PRINT( @lQueryString)
--SELECT @lQueryStringMain
--SELECT @lQueryString 


SET @lQueryStringMain = REPLACE(@lQueryStringMain, '{0}', '''' + @rPrefixText + '''' + ISNULL(@rSearchCondition, ''))

IF ISNULL(@rObsoletedId, '') = ''
SET @rObsoletedId = '0'

--PRINT( @lQueryStringMain )
--PRINT( @lQueryString)

IF(@rObsoletedId <> '0')
	SET @lQueryString = REPLACE(@lQueryString, '{0}', '''' + @rPrefixText + '''' + ISNULL(@rSearchCondition, '') + ' AND ' + @lIdColmnName + ' = ' + @rObsoletedId)
ELSE
	SET @lQueryString = REPLACE(@lQueryString, '{0}', '''' + @rPrefixText + '''' + ISNULL(@rSearchCondition, ''))

SET @lOrderPos = (SELECT CHARINDEX('ORDER BY', @lQueryString))
SELECT @lQueryString = SUBSTRING(@lQueryString, 0, @lOrderPos )

SELECT @lQueryString = @lQueryStringMain + ' UNION ' + @lQueryString 

--PRINT( @lQueryString )
--PRINT( @lQueryStringMain )
--PRINT( @lQueryString)
EXEC(@lQueryString)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pBirthPlaceMasterAdd]
	@rOrgGroupId int,
	@rOrgId int,
	@rBirthPlace nvarchar(100),
	@rBirthCity nvarchar(100),
	@rBirthDistrict nvarchar(100),
	@rBirthState nvarchar(100),
	@rCreatedUserID bigint
WITH EXECUTE AS CALLER
AS
--@rAreaId dInt = 0 OUTPUT
SET NOCOUNT ON

BEGIN
--SET @rOrgId = 0
 DECLARE @lNextNumber	Int
 
--IF(@rIsShow = 0)
--		 BEGIN
--			 IF(@rCityId = 0)
--				 BEGIN
--					 IF EXISTS(SELECT 1 FROM sCommon.tAreaMaster WHERE Title = @rTitle AND (CityId IS NULL OR (CityId = @rCityId))AND IsShow = 0 AND OrgId = @rOrgId)
--							BEGIN
--									SELECT CAST(Id AS BigInt) Id FROM sCommon.tAreaMaster WHERE Title = @rTitle AND IsShow = 0 AND CityId IS NULL  AND OrgId = @rOrgId
--									RETURN
--							END
--				 END
--			 ELSE
--				 BEGIN
--					 IF EXISTS(SELECT 1 FROM sCommon.tAreaMaster WHERE Title = @rTitle AND ((CityId = @rCityId)) AND IsShow = 0  AND OrgId = @rOrgId)
--							BEGIN
--									SELECT CAST(Id AS BigInt) Id FROM sCommon.tAreaMaster WHERE Title = @rTitle AND IsShow = 0 AND ((CityId = @rCityId)  AND OrgId = @rOrgId)
--									RETURN
--							END
--				 END
--		 END


 IF EXISTS(SELECT 1 FROM sCommon.tBirthPlaceMaster WHERE BirthPlace = @rBirthPlace AND OrgGroupId = @rOrgGroupId)
 		BEGIN
 			SELECT -101 AS RESULT	
 			RETURN
 		END

EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tBirthPlaceMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tBirthPlaceMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
		--IF(@rIsShow = NULL)
		--	 BEGIN
		--		SET @rIsShow = 1
		--	 END
		
		INSERT INTO sCommon.tBirthPlaceMaster
			(
				Id,
				BirthPlace,
				BirthCity,
				BirthDistrict,
				BirthState,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				IsObsolete,
				OrgGroupId
			)
		VALUES
			(
				@lNextNumber,
				@rBirthPlace,
				@rBirthCity,
				@rBirthDistrict,
				@rBirthState,
				@rCreatedUserID,
				sCommon.fGetDate(),
				@rCreatedUserID,
				sCommon.fGetDate(),
				0,
				@rOrgGroupId
			)
	
		--SET @rAreaId = @lId
		SELECT @lNextNumber AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pBirthPlaceMasterGet]
	@rOrgGroupId int,
	@rId int,
	@rBirthPlace nvarchar(100) = '',
	@rBirthCity nvarchar(100)='',
	@rBirthDistrict nvarchar(100) = '',
	@rBirthState nvarchar(100)=''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--SET @rId = sCommon.fSearchStringGet(@rId)
--SET @rCityId = sCommon.fSearchStringGet(@rCityId)
SET @rBirthPlace = sCommon.fSearchStringGet(@rBirthPlace)
SET @rBirthCity = sCommon.fSearchStringGet(@rBirthCity)
SET @rBirthDistrict = sCommon.fSearchStringGet(@rBirthDistrict)
SET @rBirthState = sCommon.fSearchStringGet(@rBirthState)

BEGIN
--SET @rOrgId = 0
	 SELECT AM.Id,			
			AM.BirthPlace,
			AM.BirthCity,
			AM.BirthDistrict,
			AM.BirthState,
			AM.CreatedUserId,
			AM.CreatedDateTime,
			AM.UpdatedUserId,
			AM.UpdatedDateTime,
			AM.IsObsolete
	FROM sCommon.tBirthPlaceMaster AM
		--INNER JOIN sCommon.tCityMaster CM ON (AM.CityId = CM.Id)
		--INNER JOIN sCommon.tStateMaster SM ON (CM.StateId = SM.Id)
	WHERE ((AM.Id = @rId) OR (@rId = 0))
		AND ((AM.BirthPlace LIKE @rBirthPlace) OR (@rBirthPlace = ''))
		AND ((AM.BirthCity LIKE @rBirthCity) OR (@rBirthCity = ''))
		AND ((AM.BirthDistrict LIKE @rBirthDistrict) OR (@rBirthDistrict = ''))
		AND ((AM.BirthState LIKE @rBirthState) OR (@rBirthState = ''))
		AND AM.OrgGroupId = @rOrgGroupId
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pBirthPlaceMasterModify]
	@rId int,
	@rBirthPlace nvarchar(100),
	@rBirthCity nvarchar(100),
	@rBirthDistrict nvarchar(100),
	@rBirthState nvarchar(100),
	@rIsObsolete bit,
	@rUpdatedUserId bigint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


 IF EXISTS(SELECT 1 FROM sCommon.tBirthPlaceMaster WHERE BirthPlace = @rBirthPlace AND OrgGroupId = @rOrgGroupId AND Id <> @rId)
 		BEGIN
 			SELECT -101 AS RESULT	
 			RETURN
 		END

	 UPDATE sCommon.tBirthPlaceMaster
		SET 
			BirthPlace=@rBirthPlace,
			BirthCity=@rBirthCity,
			BirthDistrict=@rBirthDistrict,
			BirthState=@rBirthState,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserID,
			UpdatedDateTime = sCommon.fGetDate()
		WHERE Id = @rId		
		
SELECT 1 AS Result

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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


	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sFee.tFeeMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tCastCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO sCommon.tCastCategoryMaster
			   (
			    [Id]
			   ,[Number]  
			   ,[Code]
			   ,[Title]
			   ,[MainCastCategoryId]
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rCode
			   ,@rTitle
			   ,@rMainCastCategoryId
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommon.tCastCategoryMaster
	    SET
			  Number=@rNumber
	         ,Code=@rCode
	         ,Title=@rTitle
	         ,MainCastCategoryId=@rMainCastCategoryId
	         ,OrderIndex=@rOrderIndex
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pCastCatagoryMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rMainCastCategoryId int,
           @rOrgGroupId smallint,
           @rIsWildCardSearch bit
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT CC.Id 
	  ,CC.Number
      ,CC.Code
      ,CC.Title
      ,CC.MainCastCategoryId
      ,MCC.Title AS MainCastCatagory
      ,ISNULL(CC.OrderIndex,0) AS OrderIndex
      ,CC.IsObsolete
     
  FROM sCommon.tCastCategoryMaster CC 
  INNER JOIN sCommon.tMainCastCategoryMaster MCC ON MCC.Id = CC.MainCastCategoryId 
        
  WHERE 
		((CC.Id = @rId) OR (@rId = 0))
	AND ((CC.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((CC.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((CC.MainCastCategoryId = @rMainCastCategoryId) OR (@rMainCastCategoryId = 0))
	AND (CC.OrgGroupId = @rOrgGroupId)
		order by CC.OrderIndex 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommon].[pCastMasterAdd]

	@rId int,
	@rOrgGroupId int,
	@rOrgId int,
    @rFamiliyCast [nvarchar](100) = '',
	@rReligionId int=0,
	@rFamiliySubCast [nvarchar](100) = '',
	@rCastCategoryId int =0,
	@rIsObsolete bit=0,
	@rCreatedUserId [bigint] = 1,
	@rOrderIndex int = null
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lNextNumber INT
 
 	BEGIN
IF(@rId = 0)	
		BEGIN
		If Exists(select 1 from sCommon.tFamiliyCastMaster where FamiliyCast=@rFamiliyCast AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		
		ELSE
		BEGIN
			
			 
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tFamiliyCastMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tFamiliyCastMaster
				(	
					Id,			
					FamiliyCast,
					ReligionId,	
					FamiliySubCast,
					CastCategoryId,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					OrgGroupId,
					OrderIndex	
					
				)
			VALUES
				(
					@lNextNumber,			
					@rFamiliyCast,
					@rReligionId,
					@rFamiliySubCast,			
					@rCastCategoryId,
					@rIsObsolete,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgGroupId,
					@rOrderIndex
				)
			SELECT @lNextNumber AS Result  
		END
		
		 
END	  
ELSE
		 BEGIN
		  SET @lNextNumber = @rId
			UPDATE sCommon.tFamiliyCastMaster
			SET 
				FamiliyCast =@rFamiliyCast,
				 ReligionId=@rReligionId,
				 FamiliySubCast=@rFamiliySubCast,
				 CastCategoryId=@rCastCategoryId,
				 IsObsolete=@rIsObsolete,
				 UpdatedUserId = @rCreatedUserId,
				 UpdatedDateTime = sCommon.fGetDate(),
				 OrgGroupId=@rOrgGroupId,
				 OrderIndex = @rOrderIndex
			 WHERE ID= @rId
		 END
		   SELECT @lNextNumber AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommon].[pCastMasterGet]
          
           @rId bigint,
           @rFamiliyCast nvarchar(20),
           @rFamiliySubCast nvarchar(100),
           @rCastCategoryId int,
           @rOrgGroupId smallint 
           
AS
SET NOCOUNT ON
 

BEGIN

SELECT 
		CM.Id,
		CM.FamiliyCast,
		CM.FamiliySubCast,
		CCM.Title AS CastCategory,
		CCM.IsObsolete,
		CM.OrgGroupId,
		CM.CastCategoryId,
		CM.ReligionId,
		ISNULL(CM.OrderIndex,0) AS OrderIndex
		
     
  FROM sCommon.tFamiliyCastMaster CM 
  INNER JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId 
  
        
  WHERE 
		((CM.Id = @rId) OR (@rId = 0))
	AND ((CM.FamiliyCast Like @rFamiliyCast)OR(ISNULL(@rFamiliyCast,'') = ''))
	AND ((CM.FamiliySubCast Like @rFamiliySubCast)OR(ISNULL(@rFamiliySubCast,'') = ''))
	AND ((CM.CastCategoryId = @rCastCategoryId) OR (@rCastCategoryId = 0))
	AND (CM.OrgGroupId = @rOrgGroupId)
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCautionaryMasterAdd]
	@rCode [nvarchar](10),
	@rTitle [nvarchar](50),
	@rIsShow [bit],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lId BIGINT

SET @lId = (SELECT ID FROM sCommon.tCautionaryMaster WHERE Title = @rTitle)

IF (ISNULL(@lId, 0) = 0)
BEGIN

	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 'sCommon.tCautionaryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tCautionaryMaster
		(
			Id,
			Code,
			Title,
			--IsShow,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			--@rIsShow,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		SET @lId = @lNextNumber
END
SELECT @lId AS ID
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCautionaryMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			---IsShow,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sCommon.tCautionaryMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCautionaryMasterModify]
	@rId [smallint],
	@rCode [nvarchar](10),
	@rTitle [nvarchar](50),
	@rIsShow [bit],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tCautionaryMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			---IsShow = @rIsShow,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCityMasterAdd]
	@rOrgId [int],
	@rOrgGroupId [int],
	@rStateId [int] = 0,
	@rTitle [nvarchar](100),
	@rIsShow [bit] = 0,
	@rCreatedUserId [bigint],
	@rZipCode nvarchar(10)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--SET @rOrgId = 0
	IF(@rIsShow = 0)
		 BEGIN
			 IF(@rStateId = 0)
				 BEGIN
					 IF EXISTS(SELECT 1 FROM sCommon.tCityMaster WHERE Title = @rTitle AND (StateId IS NULL OR (StateId = @rStateId))AND IsShow = 0 AND OrgGroupId = @rOrgGroupId)
							BEGIN
									SELECT CAST(Id AS Int) Id FROM sCommon.tCityMaster WHERE Title = @rTitle AND IsShow = 0 AND StateId IS NULL AND OrgGroupId = @rOrgGroupId
									RETURN
							END
				 END
			 ELSE
				 BEGIN
					 IF EXISTS(SELECT 1 FROM sCommon.tCityMaster WHERE Title = @rTitle AND ((StateId = @rStateId)) AND IsShow = 0 AND OrgGroupId = @rOrgGroupId)
							BEGIN
									SELECT CAST(Id AS Int) Id FROM sCommon.tCityMaster WHERE Title = @rTitle AND IsShow = 0 AND ((StateId = @rStateId) AND OrgGroupId = @rOrgGroupId)
									RETURN
							END
				 END
		 END
		
	 DECLARE @lId	Int
	 DECLARE @lNextNumber INT     
	 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tCityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	 --EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCityMaster', 0, 1, 1,@outNextNumber = @lId output
 
	IF(@rIsShow = NULL)
	 BEGIN
		SET @rIsShow = 1
	 END 
	 
	INSERT INTO sCommon.tCityMaster
		(
			Id,
			StateId,
			Title,			
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsShow,
			OrgGroupId,
			ZipCode
		)
	VALUES
		(
			@lNextNumber,
			(CASE @rStateId WHEN 0 THEN NULL ELSE @rStateId END),
			@rTitle,
			
			0,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsShow,
			@rOrgGroupId,
			@rZipCode
		)
		
		SELECT @lNextNumber AS Result

		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCityMasterGet]
	
	@rId [int] ,
	@rOrgGroupId [int],
	@rTitle [nvarchar](100) = '',
	@rIsShow [bit] = 1,
	@rStateId [int] = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN
--SET @rOrgId = 0
SET @rTitle = sCommon.fSearchStringGet(@rTitle)

	 SELECT CM.Id,
			CM.StateId,
			SM.CountryId,
			CM.Title,
			SM.Title AS StateTitle,
			CM.IsObsolete,
			CM.CreatedUserId,
			CM.CreatedDateTime,
			CM.UpdatedUserId,
			CM.UpdatedDateTime,
			CM.ZipCode
	   FROM sCommon.tCityMaster CM
		INNER JOIN sCommon.tStateMaster SM
			ON (CM.StateId = SM.Id) AND SM.OrgGroupId=@rOrgGroupId
	  WHERE ((CM.Id = @rId) OR (@rId = 0)) 
		AND ((CM.StateId = @rStateId) OR (@rStateId = 0))
		AND ((CM.Title LIKE @rTitle) OR (@rTitle = ''))
		AND (CM.IsShow = 1)
		AND CM.OrgGroupId = 	@rOrgGroupId
		  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCityMasterModify]
	@rId [int],
	@rTitle [nvarchar](100),
	@rStateId [int],
	@rIsShow [bit] = 1,
	@rIsObsolete [bit],
	@rUpdatedUserID [bigint],
	@rZipCode nvarchar(10)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 UPDATE sCommon.tCityMaster
		SET 
			Title = @rTitle,
			StateId = @rStateId,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserID,
			UpdatedDateTime = sCommon.fGetDate(),
			ZipCode=@rZipCode
		WHERE Id = @rId  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pClinicalDepartmentMasterAdd]
	@rTitle [nvarchar](100),
	@rRemark [nvarchar](300),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rNextNumber [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	--DECLARE @lNextNumber INT
	
	--IF EXISTS(SELECT 1 FROM sCommon.tClinicalDepartmentMaster WHERE Title = @rTitle)
	--	BEGIN
	--		RETURN
	--	END
		
	--EXECUTE @lNextNumber = sCommon.pTableRowIdGet 'sCommon.tClinicalDepartmentMaster', 0, 1, 1

	INSERT INTO sCommon.tClinicalDepartmentMaster
		(
			Title,
			Remark,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			Id
		)
	VALUES
		(
			@rTitle,
			@rRemark,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rNextNumber
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pClinicalDepartmentMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			Remark,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sCommon.tClinicalDepartmentMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pClinicalUomMasterAdd]
	@rCode [nvarchar](20),
	@rTitle [nvarchar](30),
	@rClinicalUomTypeId [smallint],
	@rDisplayText [nvarchar](20),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
DECLARE @lResult INT
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 0, 'sCommon.tClinicalUOMMaster', 0, 101, 1 ,@outNextNumber = @lNextNumber output
	
	DECLARE @lClinicalUomId INT
	SET @lClinicalUomId = 0

	SELECT @lClinicalUomId = Id
	FROM sCommon.tClinicalUOMMaster
	WHERE ((UPPER(Code) = UPPER(@rCode) 
				AND IsObsolete = 0) OR (UPPER(DisplayText) = UPPER(@rDisplayText)) OR (UPPER(Title) = UPPER(@rTitle)))
 
	IF (@lClinicalUomId = 0)
	BEGIN	
	INSERT INTO sCommon.tClinicalUomMaster
		(
			Id,
			Code,
			Title,
			ClinicalUomTypeId,
			DisplayText,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rClinicalUomTypeId,
			@rDisplayText,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			0
			
		)
			SET @lResult = 1
		END		
	ELSE		
		SET @lResult = 0	
END
SELECT @lResult AS Result

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pClinicalUomMasterGet]
	@rId [smallint] = 0,
	@rCode [nvarchar](20) = '',
	@rTitle [nvarchar](20) = '',
	@rIncludeObsolete [bit] = 1,
	@rIsSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF @rIsSearch = 1
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle) 
	END
	
--SELECT @rTitle

	 SELECT CUM.Id,
			CUM.Code,
			CUM.Title,
			CUM.ClinicalUomTypeId,
			CUM.DisplayText,
			CUM.IsObsolete,
			CUM.CreatedUserId,
			CUM.CreatedDateTime,
			CUM.UpdatedUserId,
			CUM.UpdatedDateTime,			
			CUTM.Title AS ClinicalUomType
	   FROM sCommon.tClinicalUomMaster CUM
	   INNER JOIN sCommon.tClinicalUomTypeMaster CUTM
	   ON CUM.ClinicalUomTypeId = CUTM.Id
	  WHERE ((CUM.Id = @rId) OR (@rId = 0))
		AND ((CUM.IsObsolete = @rIncludeObsolete) OR (@rIncludeObsolete = 1))
		AND ((CUM.Code LIKE  @rCode) OR (@rCode = ''))
		AND ((CUM.Title LIKE @rTitle) OR (@rTitle = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pClinicalUomMasterModify]
	@rId [smallint],
	@rTitle [nvarchar](30),
	@rClinicalUomTypeId [smallint],
	@rDisplayText [nvarchar](20),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
DECLARE @lClinicalUomId INT
SET @lClinicalUomId = 0
DECLARE @lResult INT
SET NOCOUNT ON

SELECT @lClinicalUomId = Id
	FROM sCommon.tClinicalUomMaster 
	WHERE (			
			(UPPER(DisplayText) = UPPER(@rDisplayText) OR (UPPER(Title) = UPPER(@rTitle)))
		  )  
		AND Id <> @rId
		AND IsObsolete = 0

IF @lClinicalUomId = 0
BEGIN
	 UPDATE sCommon.tClinicalUomMaster
		SET 			
			Title = @rTitle,
			ClinicalUomTypeId = @rClinicalUomTypeId,
			DisplayText = @rDisplayText,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
SET @lResult = 1
END
ELSE
SET @lResult = -9

SELECT @lResult AS Result

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pClinicalUOMMasterRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS(SELECT ID FROM sLaboratory.tTestParameterMaster WHERE ClinicalUOMId = @rId)
BEGIN
SELECT -101 AS RESULT
END
ELSE
BEGIN
DELETE FROM sCommon.tClinicalUOMMaster WHERE Id = @rId
SELECT 1 AS RESULT
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pClinicalUomTypeMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title
	   FROM sCommon.tClinicalUomTypeMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pClinicMasterAdd]
	@rId [int] = 0,
	@rClinicCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rDoctorName [nvarchar](100),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rStreetOne [nvarchar](50),
	@rStreetTwo [nvarchar](50),
	@rStreetThree [nvarchar](50),
	@rStreetFour [nvarchar](50),
	@rArea nvarchar(50),
	@rCity nvarchar(50),
	@rState nvarchar(50),
	@rCountry nvarchar(50),
	@rPinCode [nvarchar](20),
	@rPhoneNumberOffice [nvarchar](50),
	@rPhoneNumberMobile [nvarchar](50),
	@rEmailPrimary [nvarchar](300),
	@rEmailAlternative [nvarchar](300),
	@rLocationId int ,
	@rOrgId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lErrorId INT
SET @lErrorId = 0

SELECT @lErrorId = Id
FROM sCommon.tClinicMaster
WHERE Code = @rClinicCode AND IsObsolete = 0
IF @lErrorId > 0
SET @lErrorId = -1

IF @lErrorId = 0
BEGIN
	SELECT @lErrorId = Id
	FROM sCommon.tClinicMaster
	WHERE Title = @rTitle AND IsObsolete = 0
END

IF @lErrorId > 0
SET @lErrorId = -2
 
IF (@lErrorId = 0)	
BEGIN
	
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sCommon.tClinicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	--// Address Add
	--// Contact Add
	INSERT INTO sCommon.tClinicMaster
		(
			Id,
			Code,
			Title,
			DoctorName,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StreetOne,
			StreetTwo,
			StreetThree,
			StreetFour,
			Area,
			City,
			State,
			Country,
			ZipCode,
			PhoneNumberOffice,
			PhoneNumberMobile,
			EmailPrimary,
			EmailAlternative,
			LocationId,
			OrgId		
			
			)
	VALUES
		(
			@lNextNumber,
			@rClinicCode,
			@rTitle,
			@rDoctorName,
			0,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rStreetOne,
			@rStreetTwo,
		    @rStreetThree,
		    @rStreetFour,
		    @rArea,
			@rCity,
			@rState,
			@rCountry,
		    @rPinCode,
		    @rPhoneNumberOffice,
		    @rPhoneNumberMobile,
		    @rEmailPrimary,
		    @rEmailAlternative,
		    @rLocationId,
			@rOrgId 
		)
	SELECT 1 AS Result
END
ELSE		
	SELECT @lErrorId AS Result

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pClinicMasterGet]
	@rId [int],
	@rCode [nvarchar](20) = '',
	@rDescription [nvarchar](300) = '',
	@rIsAbsolute [bit] = 0,
	@rOrgId int,
	@rLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rCode			= ISNULL(@rCode, '') 
SET @rDescription	= ISNULL(@rDescription, '')  
IF @rIsAbsolute = 0
BEGIN
SET @rCode			= sCommon.fSearchStringGet(@rCode)
SET @rDescription	= sCommon.fSearchStringGet(@rDescription)
END

	SELECT	CM.Id, 
			CM.Code, 
			CM.Title, 
			StreetOne, 
			StreetTwo, 
			StreetThree, 
			StreetFour, 
			CM.Country			AS CountryName, 
			 
			CM.State			AS StateName, 
			 
			CM.City			AS City, 
			 
		 
			CM.Area				AS Area, 
			ZipCode				AS PinCode, 		
			PhoneNumberOffice	AS TelephoneNumber, 
			PhoneNumberMobile	AS MobilePhoneNumber, 
			EmailPrimary		AS PrimaryEmail, 
			EmailAlternative	AS SecondaryEmail, 
			DoctorName, 	 	 
			CM.IsObsolete, 
			CM.CreatedUserId, 
			CM.CreatedDateTime, 
			CM.UpdatedUserId, 
			CM.UpdatedDateTime,
			CASE CM.IsObsolete 
			WHEN 1 THEN 'Y' 
			ELSE
			'N'
			END AS InActive
FROM		sCommon.tClinicMaster CM
--LEFT JOIN	sCommon.tAreaMaster AM
--			ON AM.Id = CM.AreaId  
--LEFT JOIN	sCommon.tCityMaster CC
--			ON CC.Id = CM.CityId
--LEFT JOIN	sCommon.tStateMaster SM
--			ON CM.StateId = SM.Id
--LEFT JOIN	sCommon.tCountryMaster CMM
--			ON CM.CountryId = CMM.Id
WHERE	((CM.Id = @rId) OR (@rId = 0))
AND		((CM.Code LIKE @rCode ) OR (@rCode = ''))
AND		((CM.Title LIKE @rDescription ) OR (@rDescription = ''))
AND		 CM.OrgId = @rOrgId AND LocationId = @rLocationId 

ORDER BY CM.Id DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pClinicMasterModify]
	@rId [int],
	@rClinicCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rDoctorName [nvarchar](100),
	@rStreetOne [nvarchar](50),
	@rStreetTwo [nvarchar](50),
	@rStreetThree [nvarchar](50),
	@rStreetFour [nvarchar](50),
	@rArea nvarchar(50),
	@rCity nvarchar(50),
	@rState nvarchar(50),
	@rCountry nvarchar(50),
	@rPinCode [nvarchar](20),
	@rPhoneNumberOffice [nvarchar](50),
	@rPhoneNumberMobile [nvarchar](50),
	@rEmailPrimary [nvarchar](50),
	@rEmailAlternative [nvarchar](50),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rLocationId int,
	@rOrgId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
  

	 UPDATE sCommon.tClinicMaster
		SET 
			--Code = @rClinicCode,
			Title = @rTitle,
			DoctorName = @rDoctorName,
			StreetOne = @rStreetOne,
			StreetTwo = @rStreetTwo,
			StreetThree = @rStreetThree,
			StreetFour =    @rStreetFour,
            Area = @rArea,
			City = @rCity,
			State = @rState,
			Country = @rCountry,
			ZipCode = @rPinCode,
            PhoneNumberOffice = @rPhoneNumberOffice,
            PhoneNumberMobile = @rPhoneNumberMobile,
            EmailPrimary = @rEmailPrimary,
            EmailAlternative = @rEmailAlternative,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  
	  SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterCheckCode]
	@rCode [nvarchar](100),
	@rCodeField [nvarchar](100),
	@rTableName [nvarchar](100),
	@rIdField [nvarchar](100),
	@rOrgId int	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 

    DECLARE @lSelectClause Nvarchar(2000)
    DECLARE @lId Nvarchar(20)
	SET @lId = '0'

	SET @lSelectClause = 'SELECT SUM(Id) AS Result
							 FROM(SELECT ' + @rIdField + ' Id, 0 Cnt
									FROM ' + @rTableName + '
								   WHERE ' + @rCodeField + ' = ''' + @rCode + '''
								   AND OrgId = ' + CONVERT(Nvarchar(5),@rOrgId) + '
								   UNION ALL
								  SELECT 0 Id, COUNT(' + @rIdField + ') Cnt
									FROM ' + @rTableName + ' 
								   WHERE ' + @rCodeField + ' = ''' + @rCode + '''
								    AND OrgId = ' + CONVERT(Nvarchar(5),@rOrgId) + '
							) AS TBL1'

--SELECT @lSelectClause
	EXECUTE sp_executesql @lSelectClause      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterCheckDescription]
	@rDescription [nvarchar](50),
	@rDescriptionField [nvarchar](50),
	@rTableName [nvarchar](50),
	@rIdField [nvarchar](50),
	@rId [nvarchar](20),
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 



BEGIN 

    DECLARE @lSelectClause Nvarchar(2000)
    DECLARE @lId Nvarchar(20)
	SET @lId = '0'
	

	SET @lSelectClause = 'SELECT SUM(Id) AS Result
							 FROM(SELECT ' + @rIdField + ' Id, 0 Cnt
									FROM ' + @rTableName + '
								   WHERE ' + @rDescriptionField + ' = ''' + @rDescription + ''''
								  + ' AND ' + @rIdField + ' ! = ''' + @rId + '''
								      AND + OrgId = ' + CONVERT(NVARCHAR(5), @rOrgId) + '
								   UNION ALL
								  SELECT 0 Id, COUNT(' + @rIdField + ') Cnt
									FROM ' + @rTableName + ' 
								   WHERE ' + @rDescriptionField + ' = ''' + @rDescription + ''''
								 + ' AND ' + @rIdField + ' ! = ''' + @rId  + '''
								  AND + OrgId = ' + CONVERT(NVARCHAR(5), @rOrgId) + '
							) AS TBL1'
							
							
							
		--SET @lSelectClause =	'SELECT ' + @rIdField + ' AS Result
		--							FROM ' + @rTableName + '
		--						   WHERE ' + @rDescriptionField + ' = ''' + @rDescription + ''''
		--						  + ' AND ' + @rIdField + ' ! = ''' + @rId + ''''				
						
print @lSelectClause
--SELECT @lSelectClause
	EXECUTE sp_executesql @lSelectClause   
	
END
--BEGIN 

--    DECLARE @lSelectClause Nvarchar(2000)
--    DECLARE @lId Nvarchar(20)
--	SET @lId = '0'

--	SET @lSelectClause = 'SELECT SUM(Id) AS Result
--							 FROM(SELECT ' + @rIdField + ' Id, 0 Cnt
--									FROM ' + @rTableName + '
--								   WHERE ' + @rDescriptionField + ' = ' + @rDescription + '' + 'AND' +
--								              @rIdField + ' ! = ' + @rId + '
--								   UNION ALL
--								  SELECT 0 Id, COUNT(' + @rIdField + ') Cnt
--									FROM ' + @rTableName + ' 
--								   WHERE ' + @rDescriptionField + ' = ' + @rDescription + '' + 'AND' +
--								    @rIdField + ' ! = ''' + @rId + '''
--							) AS TBL1'

----SELECT @lSelectClause
--	EXECUTE sp_executesql @lSelectClause      
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterCodeAdd]
	@rOrgId int,
	@rTableName [nvarchar](300),
	@rIDField [nvarchar](300),

	@rCodeField [nvarchar](300),
	@rDescriptionField [nvarchar](300),

	@rCode [nvarchar](300),

	@rDescription [nvarchar](300),

	@rIsObsolete [nvarchar](10),
	@rCreatedUserId [bigint],
	@rIsStatic [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--BEGIN TRY

	DECLARE @lSelectClause Nvarchar(2000)
	DECLARE @lIsShow Nchar(1)
	DECLARE @lNextNumber BigInt
	DECLARE @lSchemaName Nvarchar(50)
	DECLARE @lTableName	Nvarchar(100)
	DECLARE @lSeed INT
	
	SET @lSeed = (CASE WHEN @rIsStatic = 1 THEN 101 ELSE 1 END)
	EXECUTE sCommon.pTableRowIdGet @rOrgId, @rTableName, 0, @lSeed, 1,@outNextNumber = @lNextNumber output
	SET @lNextNumber = @lNextNumber
	
	--SELECT @lNextNumber, @lSeed
	
	SET @lIsShow = '0'
	SET @lSchemaName = SUBSTRING(@rTableName, 1, CHARINDEX('.', @rTableName, 1) - 1)
	SET @lTableName =  SUBSTRING(@rTableName, CHARINDEX('.', @rTableName, 1) + 1, LEN(@rTableName))
	
	--SELECT @lSchemaName, @lTableName
	
	IF EXISTS(SELECT 1
			--SELECT s.name, t.name, c.name 
				FROM sys.tables t
					 INNER JOIN sys.schemas s
							 ON t.schema_id = s.schema_id
					 INNER JOIN sys.columns c
							 ON T.object_id = C.object_id
			   WHERE t.name = @lTableName
					 AND s.name = @lSchemaName
					 AND c.name = 'IsShow')
				BEGIN
					SET @lIsShow = '1'
				END
	SET @lSelectClause =      'IF EXISTS(SELECT  ' + @rCodeField + ' FROM ' + @rTableName + 
										' WHERE OrgId = ' + CONVERT(NVARCHAR(20), @rOrgId)  + ' AND ' +  @rCodeField + '	= ''' + @rCode + ''' ) 
     							BEGIN
									SELECT -101 AS Result
									RETURN
								END ' + 
								
 
								
							   '
							  				 
							   INSERT INTO ' + @rTableName
								  + '(Id ' 
								     
									   + ', ' + @rCodeField 
									   + ', ' + @rDescriptionField 									   
                                       + ', ' + 'UpdatedUserId ' 
									   + ', ' + 'UpdatedDateTime ' 
									   + ', ' + 'CreatedUserId ' 
									   + ', ' + 'CreatedDateTime ' 
									    + ', ' + 'OrgId' 
                                       + ', ' + 'IsObsolete' 
                                      
                                       + (CASE WHEN @lIsShow = '1' THEN ', ' + 'IsShow' ELSE '' END) +
									 ')  
							   VALUES (' + CAST(@lNextNumber  AS NVARCHAR(20)) + ', ''' 
										
										 + @rCode + ''', ''' 
										 + @rDescription +  ''', '''
									    
                                         + CONVERT(NVARCHAR(20), @rCreatedUserId) + ''', ''' 
										 + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', '''
                                         + CONVERT(NVARCHAR(20), @rCreatedUserId) + ''', ''' 
										 + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', ''' 
										  + CONVERT(NVARCHAR(20), @rOrgId) + ''', ''' 
										 + @rIsObsolete  										
										 + (CASE WHEN @lIsShow = '1' THEN ''', ''' + '1' ELSE '' END) +
										 
								 + ''')
								 
								SELECT 1 AS Result'		
								
 

	EXECUTE sp_executesql @lSelectClause
--END TRY
--BEGIN CATCH
--SELECT ERROR_MESSAGE()
--SELECT ERROR_LINE()
--SELECT ERROR_NUMBER()
--END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterDataModify]
	@rOrgId int,
	@rTableName [nvarchar](100),
	@rIDField [nvarchar](100),	
	@rCodeField [nvarchar](100),	
	@rDescriptionField [nvarchar](100),	
	@rId [int],
	@rCode [nvarchar](100),	
	@rDescription [nvarchar](100),
--	@rOrderIndex int,
	@rIsObsolete [smallint],
	@rUpdatedUserId [bigint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


    
      DECLARE @lSelectClause Nvarchar(2000)
      SET @lSelectClause = 
      
			-- 'IF EXISTS(SELECT ' + @rCodeNoField + ' FROM ' + @rTableName + 
			--		' WHERE OrgId = ' + CONVERT(NVARCHAR(5), @rOrgId)  + ' AND ' +  @rCodeNoField + '	= ' + CONVERT(NVARCHAR(10), @rCodeNo )  + ' 
			--		AND ' + @rIDField + ' <> ' + CONVERT(NVARCHAR(10), @rId )  + ') 
			--BEGIN
			--	SELECT -102 AS Result
			--	RETURN
			--END ' + 
      
             ' UPDATE ' + @rTableName + 
                                             ' SET ' +  @rDescriptionField + ' = ''' + @rDescription + ''',																											   
                                                            IsObsolete = ' + CONVERT(NVARCHAR(20), @rIsObsolete) + ',         
                                                            UpdatedUserId = ' + CONVERT(NVARCHAR(20), @rUpdatedUserId) + ',  
                                                            UpdatedDateTime = ''' + CONVERT(NVARCHAR(24), sCommon.fGetDate() )  + ''' 
                                                            WHERE OrgId = ' + CONVERT(NVARCHAR(20), @rOrgId) + ' AND ' + @rIDField + ' = ' + CONVERT(NVARCHAR(20), @rId )  +

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






      EXECUTE sp_executesql @lSelectClause

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterDataWithValueModify]
	@rTableName [nvarchar](100),
	@rIDField [nvarchar](100),
	@rValueField [nvarchar](100),
	@rDescriptionField [nvarchar](100),
	@rId [int],
	@rValue [decimal](22, 6),
	@rDescription [nvarchar](100),
	@rIsObsolete [smallint],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN
	DECLARE @lSelectClause Nvarchar(2000)
	SET @lSelectClause =     ' UPDATE ' + 	@rTableName + 
							   ' SET ' +   @rValueField + ' = ' +  CONVERT(NVARCHAR(20), @rValue) + ' ,' + 	
									      @rDescriptionField + ' = ''' + @rDescription + ''' ,
										  IsObsolete = ' + CONVERT(NVARCHAR(7), @rIsObsolete) + ' ,  		
									      UpdatedUserId = ' + CONVERT(NVARCHAR(5), @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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterDetailsGet]
	@rMenuId [int],
	@rUserId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--- Temp table for Getting Localized value*********************************
            CREATE TABLE #tGlobalizationTableResource
            (
              UiCultureId INT, 
              UiResourceKeyId SMALLINT, 
              UiResourceKeyValue NVARCHAR (300), 
              Remark NVARCHAR (300)
            ) 

--INSERT INTO #tGlobalizationTableResource
--EXECUTE sConfig.pGlobalizationTableResource @rUserId = @rUserId
--*******************************************************************************

	
SELECT   tCM.Id,  
         tCM.ScreenTitle,      
         tCM.ScreenTitleResourceKeyId, 
         tCM.TableTitle, 
         tCM.IdField, 
         --tCM.CodeNoField, 
         --tCM.CodeNoFieldLabel, 
         tCM.CodeField, 
         tCM.CodeFieldLabel, 
         tCM.RemarkField, 
         tCM.RemarkFieldLabel,
         --tCM.OrderIndexField, 
         --tCM.OrderIndexFieldLabel, 
         tCM.CodeContentPrecision, 
         tCM.CodeContentScale, 
         tCM.CodeFieldResourceKeyId,    
       --ISNULL(tCMVGTR.UiResourceKeyValue,  '###Unable to Localize###') AS ScreenTitle, 
       --ISNULL(tCMVGTRCode.UiResourceKeyValue,  '###Unable to Localize###') AS CodeFieldLabel,          
       --ISNULL(tCMVGTRRemark.UiResourceKeyValue,  '###Unable to Localize###') AS RemarkFieldLabel, 
         tCM.RemarkContentLength, 
         tCM.RemarkFieldResourceKeyId, 
         tCM.IsRemarkNumeric, 
         tCM.ScreenId AS MenuID, 
         tCM.IsStatic1to100,
         SS.TaskId AS TaskId,
         tCM.VisibilityField
       
        
 FROM tCommonMaster AS tCM
	     --LEFT JOIN #tGlobalizationTableResource tCMVGTR
      --         ON tCM.ScreenTitleResourceKeyId = tCMVGTR.UiResourceKeyId 
      --  LEFT JOIN #tGlobalizationTableResource tCMVGTRCode
      --         ON tCM.CodeFieldResourceKeyId = tCMVGTRCode.UiResourceKeyId 
      --  LEFT JOIN #tGlobalizationTableResource tCMVGTRRemark
      --         ON tCM.RemarkFieldResourceKeyId = tCMVGTRRemark.UiResourceKeyId      
      LEFT JOIN sSecurity.tScreen SS
       ON ((tCM.ScreenId = SS.Id) AND (SS.IsObsolete = 0))
 WHERE (ScreenId = @rMenuId) 
                   
DROP TABLE #tGlobalizationTableResource

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterGetCodeAndDescription]
	  @rOrgId		     Nvarchar(20),	
	  @rTableName		 Nvarchar(100),
	  @rIsStatic1To100	 bit,
	  @rCodeField		 Nvarchar(100) = '',
	  @rCode			 Nvarchar(100) = '',
	  @rDescriptionField  Nvarchar(100) = '',
	  @rDescription	     Nvarchar(100) = '',
	  @rValueField       Nvarchar(100) = '',      
      @rIsDescriptionValue Bit
 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--	DECLARE @lIsStatic int = 0

--IF ( @rTableName = 'sIp.tItemMainGroupMaster' or @rTableName = 'sIp.tStoreLocationMaster' or @rTableName = 'sHrm.tEmployeeJobTitleMaster' or @rTableName =  'sOrderEntry.tServiceItemTypeMaster')
--SET @lIsStatic = 1
--ELSE
--SET @lIsStatic = 0

	DECLARE @lSelectClause Nvarchar(2000)
	IF (@rIsDescriptionValue = 1)
	  BEGIN
	       SET @lSelectClause =   ' SELECT ' + @rValueField + ' AS Result, Id, IsObsolete  FROM ' + @rTableName + 
										' WHERE ' +  @rDescriptionField + '	= ''' + @rDescription + '''  AND OrgId = ' + @rOrgId +  '' 
       END
       
     ELSE
     BEGIN
     
     IF ( @rIsStatic1To100 = 1)
     BEGIN
        SET @lSelectClause =   'SELECT  ' + @rDescriptionField + '  AS Result, ' + @rCodeField + ' AS ResultCode ' + ', Id, 0 AS StaticId, IsObsolete  FROM  ' + @rTableName + 
										' WHERE ' +  @rCodeField + '	= ''' + @rCode + '''  AND OrgId = ' + @rOrgId +  '' 
	 END
	 ELSE
	 BEGIN
        SET @lSelectClause =   'SELECT  ' + @rDescriptionField + '  AS Result, ' + @rCodeField + ' AS ResultCode ' + ', Id, 0 As StaticId,  IsObsolete  FROM  ' + @rTableName + 
										' WHERE ' +  @rCodeField + '	= ''' + @rCode + '''  AND OrgId = ' + @rOrgId +  '' 
	 
	 END										
     END  
				
--SELECT @lSelectClause
	EXECUTE sp_executesql @lSelectClause
	



END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterNumaricCheckDescription]
	@rDescription [nvarchar](50),
	@rDescriptionField [nvarchar](50),
	@rTableName [nvarchar](50),
	@rIdField [nvarchar](50),
	@rId [nvarchar](20),
	@rOrgId [nvarchar](20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 



BEGIN 

    DECLARE @lSelectClause Nvarchar(2000)
    DECLARE @lId Nvarchar(20)
	SET @lId = '0'
	

	SET @lSelectClause = 'SELECT SUM(Id) AS Result
							 FROM(SELECT ' + @rIdField + ' Id, 0 Cnt
									FROM ' + @rTableName + '
								   WHERE ' + @rDescriptionField + ' = ''' + @rDescription + ''''
								  + ' AND ' + @rIdField + '  = ' + @rId 
								  + ' AND  OrgId = ' + @rOrgId + '
								   UNION ALL
								  SELECT 0 Id, COUNT(' + @rIdField + ') Cnt
									FROM ' + @rTableName + ' 
								   WHERE ' + @rDescriptionField + ' = ''' + @rDescription + ''''
								 + ' AND ' + @rIdField + '  = ' + @rId 
								  + ' AND  OrgId = ' +  @rOrgId + '
							) AS TBL1'
							
							
							
		--SET @lSelectClause =	'SELECT ' + @rIdField + ' AS Result
		--							FROM ' + @rTableName + '
		--						   WHERE ' + @rDescriptionField + ' = ''' + @rDescription + ''''
		--						  + ' AND ' + @rIdField + ' ! = ''' + @rId + ''''				
						
print @lSelectClause
--SELECT @lSelectClause
	EXECUTE sp_executesql @lSelectClause   
	
END
--BEGIN 

--    DECLARE @lSelectClause Nvarchar(2000)
--    DECLARE @lId Nvarchar(20)
--	SET @lId = '0'

--	SET @lSelectClause = 'SELECT SUM(Id) AS Result
--							 FROM(SELECT ' + @rIdField + ' Id, 0 Cnt
--									FROM ' + @rTableName + '
--								   WHERE ' + @rDescriptionField + ' = ' + @rDescription + '' + 'AND' +
--								              @rIdField + ' ! = ' + @rId + '
--								   UNION ALL
--								  SELECT 0 Id, COUNT(' + @rIdField + ') Cnt
--									FROM ' + @rTableName + ' 
--								   WHERE ' + @rDescriptionField + ' = ' + @rDescription + '' + 'AND' +
--								    @rIdField + ' ! = ''' + @rId + '''
--							) AS TBL1'

----SELECT @lSelectClause
--	EXECUTE sp_executesql @lSelectClause      
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterPageListGet]
	@rQueryString [nvarchar](2000)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lQueryString Nvarchar(2000)

SET @lQueryString  = @rQueryString


EXEC(@lQueryString)


SELECT @lQueryString

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterScreensGet]
	@rOrgId nvarchar(20),
	@rScreenId [int] = 0,
	@rId [int] = 0,
 
	@rCode [nvarchar](100) = '',
	@rTitle [nvarchar](500) = ''
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


DECLARE @lId	Nvarchar(200)
DECLARE @lCode	Nvarchar(200)
 
DECLARE @lTitle Nvarchar(200)
 
DECLARE @lTableName Nvarchar(200)
DECLARE @lQueryString Nvarchar(MAX)



SELECT	@lId		= IdField, 
	 
		@lCode		= CodeField, 
		@lTitle 	= RemarkField, 
		 
		@lTableName =  TableTitle 
FROM	sCommon.tCommonMaster 
WHERE	Id = @rScreenId



SET @lQueryString = 'SELECT'
SET @lQueryString = @lQueryString + ' ' + @lId + ', ' +   ', ' + @lCode + ', ' + @lTitle   + ' FROM ' + @lTableName
SET @lQueryString = @lQueryString + ' ' + 'WHERE	((' + @lId + ' = ' + CAST(@rId AS NVARCHAR(30)) + ') OR (' + CAST(@rId AS NVARCHAR(30)) + ' = 0))
											AND		((' + @lCode + ' = ''' + ISNULL(@rCode, '') + ''') OR (''' + ISNULL(@rCode, '') + ''' = ''''))
											AND		((' + @lTitle + ' = ''' + ISNULL(@rTitle, '') + ''') OR (''' + ISNULL(@rTitle, '') + ''' = ''''))
										    AND OrgId = ' + @rOrgId +  '' 


--PRINT(@lQueryString )
EXEC(@lQueryString)


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonMasterWithValueAdd]
	@rTableName [nvarchar](100),
	@rValueField [nvarchar](100),
	@rDescriptionField [nvarchar](100),
	@rValue [nvarchar](50),
	@rDescription [nvarchar](100),
	@rIsObsolete [nvarchar](10),
	@rCreatedUserId [bigint],
	@rIsStatic1to100 [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--DECLARE @lSelectClause Nvarchar(2000)
	--DECLARE @lNextNumber BIGINT
	--EXECUTE @lNextNumber = sCommon.pTableRowIdGet @rTableName, 0, 1, 1
	DECLARE @lSelectClause Nvarchar(2000)
	DECLARE @lIsShow Nchar(1)
	DECLARE @lNextNumber BigInt
	DECLARE @lSchemaName Nvarchar(50)
	DECLARE @lTableName	Nvarchar(100)
	DECLARE @lSeed INT
	SET @lSeed = (CASE WHEN @rIsStatic1to100 = 1 THEN 101 ELSE 1 END)
	EXECUTE sCommon.pTableRowIdGet @rTableName, 0, @lSeed, 1,@outNextNumber = @lNextNumber output
	SET @lNextNumber = @lNextNumber
	SET @lIsShow = '0'
	SET @lSchemaName = SUBSTRING(@rTableName, 1, CHARINDEX('.', @rTableName, 1) - 1)
	SET @lTableName =  SUBSTRING(@rTableName, CHARINDEX('.', @rTableName, 1) + 1, LEN(@rTableName))
	
	--SELECT @lSchemaName, @lTableName
	
	IF EXISTS(SELECT 1
			--SELECT s.name, t.name, c.name 
				FROM sys.tables t
					 INNER JOIN sys.schemas s
							 ON t.schema_id = s.schema_id
					 INNER JOIN sys.columns c
							 ON T.object_id = C.object_id
			   WHERE t.name = @lTableName
					 AND s.name = @lSchemaName
					 AND c.name = 'IsShow')
				BEGIN
					SET @lIsShow = '1'
				END
	
	SET @lSelectClause =     'IF EXISTS(SELECT ' + @rDescriptionField + ' FROM ' + @rTableName + 
										' WHERE ' +  @rDescriptionField + '	= ''' + @rDescription + ''' ) 
     							BEGIN
									SELECT -102 AS Result
									RETURN
								END ' + 
							   'INSERT INTO ' + @rTableName 
								  + '(Id, ' + @rValueField 
										   + ', ' + @rDescriptionField 
										     + ', ' + ' UpdatedUserId ' 
										   + ', ' + ' UpdatedDateTime ' 
										   + ', ' + ' CreatedUserId ' 
										   + ', ' + ' CreatedDateTime ' 
                                           + ', ' + 'IsObsolete' + + (CASE WHEN @lIsShow = '1' THEN ', ' + 'IsShow' ELSE '' END) +
									 ')
                               VALUES(' + CAST(@lNextNumber AS NVARCHAR(15)) + ', ''' + @rValue + ''', ''' 
							     		   + @rDescription +  ''', '''
                                           + CONVERT(NVARCHAR(5), @rCreatedUserId) + ''', ''' 
										   + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', '''
                                           + CONVERT(NVARCHAR(5), @rCreatedUserId) + ''', ''' 
										   + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', ''' + @rIsObsolete
								 + (CASE WHEN @lIsShow = '1' THEN ''', ''' + '1' ELSE '' END) +
										 
								 + ''')
								 
								SELECT 1 AS Result'						
--SELECT @lSelectClause
	EXECUTE sp_executesql @lSelectClause

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonSearchGetHeaderList]
	@rTableTitle [nvarchar](300)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
   DECLARE @lTableName Nvarchar(300)
   DECLARE @lTableSchema Nvarchar(300)
   SET @lTableName = PARSENAME(@rTableTitle, 1)
   SET @lTableSchema = PARSENAME(@rTableTitle, 2)
  
  PRINT @lTableName

   SELECT COLUMN_NAME AS ColumnName,
          DATA_TYPE AS ColDataType
          FROM INFORMATION_SCHEMA.COLUMNS 
          WHERE TABLE_NAME = @lTableName
	        	AND TABLE_SCHEMA = @lTableSchema 
				AND COLUMN_NAME !='BookImage'
				AND COLUMN_NAME !='AssetImage'

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCommonSearchPageListGet]
	@rQueryString [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lQueryString Nvarchar(Max)

SET @lQueryString  = @rQueryString

print @lQueryString
EXEC(@lQueryString)


SELECT @lQueryString

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCompanyInformationAdd]
    @rId int,    
	@rCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rParentCompanyName [nvarchar](300),
	@rStreetOne [nvarchar](50),
	@rStreetTwo [nvarchar](50),
	@rStreetThree [nvarchar](50),
	@rStreetFour [nvarchar](50),
	@rCityName [nvarchar](100),
	@rStateName [nvarchar](100),
	@rCountryName [nvarchar](100),
	@rZipCode [nvarchar](20),
	@rHomePage [nvarchar](100),	  
	@rPhoneNo [nvarchar](100),
	@rFaxNo [nvarchar](100),
	@rSmallAddress1 [nvarchar](100),
	@rSmallAddress2 [nvarchar](100),
	@rIsShowCompanyName bit,
	@rCompanyNameAlignment int,
	@rIsShowCompanyAddress bit,
	@rCompanyAddressAlignment int		
	--@rContactPerson [nvarchar](300),
	--@rPhoneNumberHome [nvarchar](50),
	--@rPhoneNumberOffice [nvarchar](50),
	--@rPhoneNumberMobile [nvarchar](50),
	--@rEmailPrimary [nvarchar](300),
	--@rEmailAlternative [nvarchar](300),
	--@rHomePage [nvarchar](100),
	--@rBaseCalendarId [smallint],
	--@rCustomsPermitNumber [nvarchar](30),
	--@rCustomsPermitDate [datetime],
	--@rRegistrationNumber [nvarchar](50),
	--@rRegistrationExpiryDate [datetime],
	--@rTinNumber [nvarchar](50),
	--@rTinExpiryDate [datetime],
	--@rExciseRegistrationNumber [nvarchar](30),
	--@rExicseExpiryDate [datetime],
	--@rLstNumber [nvarchar](50),
	--@rLstExpiryDate [datetime],
	--@rCstNumber [nvarchar](50),
	--@rCstExpiryDate [datetime],
	--@rLtegNumber [nvarchar](50),
	--@rEccNumber [nvarchar](50),
	--@rCeRegdNumber [nvarchar](50),
	--@rCeRange [nvarchar](50),
	--@rCeCommissioneRate [decimal](22, 6),
	--@rIecCode [nvarchar](50),
	--@rEsi [nvarchar](50),
	--@rEProvIdentFund [nvarchar](50),
	--@rCeDivision [nvarchar](50),
	--@rDrugLicenceNumber [nvarchar](50),
	--@rDrugLicenceExpiryDate [datetime],
	--@rBloodBankRegistrationNumber [nvarchar](50),
	--@rBloodBankRegistrationExpiryDate [datetime],
	--@rDrugLicenceNumberOne [nvarchar](50),
	--@rDrugLicenceExpiryDateOne [datetime],
	--@rDrugLicenceNumberTwo [nvarchar](50),
	--@rDrugLicenceExpiryDateTwo [datetime],
	--@rDrugLicenceNumberThree [nvarchar](50),
	--@rDrugLicenceExpiryDateThree [datetime],
	--@rDrugLicenceNumberFour [nvarchar](50),
	--@rDrugLicenceExpiryDateFour [datetime],
	--@rDrugLicenceNumberFive [nvarchar](50),
	--@rDrugLicenceExpiryDateFive [datetime],
	--@rReportingCurrencyId [int],
	--@rAccountingCurrencyId [int],
	--@rForeignCurrencyId [int],
	--@rChequeFavouring [nvarchar](300),
	--@rIsPfApplicable [bit],
	--@rIsEsiApplicable [bit],
	--@rIsGratuityApplicable [bit]
	--@rIsWhtApplicable [bit],
	--@rMinimumAge [int],
	--@rMaximumAge [int],
	--@rSalaryDaysId [int],
	--@rTanNumber [nvarchar](50),
	--@rPanNumber [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS (SELECT 1 FROM sCommon.tCompanyInformation WHERE (Title) = (@rTitle) or Id = @rId)
BEGIN 
	--SELECT @lNextNumber
	--DECLARE @lUserId INT
	--SET @lUserId = 0

	--SELECT @lUserId = Id
	--FROM sCommon.tCompanyInformation 	 
 
	INSERT INTO sCommon.tCompanyInformation
		(
			Id,
			Code,
			Title,
			ParentCompanyName,
			StreetOne,
			StreetTwo,
			StreetThree,
			StreetFour,
			CityName,
			StateName,
			CountryName,
			ZipCode,		 
			HomePage,			 
			PhoneNo,
			FaxNo,
			SmallAddress1,
			SmallAddress2,
			IsShowCompanyName,
			CompanyNameAlignment,
			IsShowCompanyAddress,
			CompanyAddressAlignment
		)
	VALUES
		(
		    @rId,
			@rCode,
			@rTitle,
			@rParentCompanyName,
			@rStreetOne,
			@rStreetTwo,
			@rStreetThree,
			@rStreetFour,
			@rCityName,
			@rStateName,
			@rCountryName,
			@rZipCode,	 
			@rHomePage,			 
			@rPhoneNo,
			@rFaxNo,
			@rSmallAddress1,
			@rSmallAddress2,
			@rIsShowCompanyName,
			@rCompanyNameAlignment,
			@rIsShowCompanyAddress,
			@rCompanyAddressAlignment		
		)
		
	 exec  [sCommon].[pCompanySetupAdd] @rId
	SELECT @rId AS RESULT
 END
 ELSE
	BEGIN
		SELECT -100 AS RESULT
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCompanyInformationCommonGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT TOP 1 Id, 
			Code,
			Title			
	   FROM sCommon.tCompanyInformation
	  WHERE ((Id = @rId) OR (ISNULL(@rId, 0) = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCompanyInformationDetailAdd]
    @rId int,
	@rRegistrationNumber nvarchar(50), 
	@rLicenceNumber nvarchar(50),
	@rEsicNumber nvarchar(50),
	@rEsicAddress1 nvarchar(100),
	@rEsicAddress2 nvarchar(100),
	@rNatureOfIndustry nvarchar(100),
	@rByProduct nvarchar(100),
	@rDangerousOperation nvarchar(100),
	@rNatureOfTest nvarchar(100),
	@rRowMaterialUsed nvarchar(100),
	@rHazardousProcess nvarchar(100),
	@rCmo nvarchar(50),
	@rNicNumber nvarchar(50)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS (SELECT 1 FROM sCommon.tCompanyInformationDetail WHERE  OrgId=@rId )
 BEGIN 
--  SELECT @lNextNumber
--	DECLARE @lUserId INT
--	SET @lUserId = 0

--	SELECT @lUserId = Id
--	FROM sCommon.tCompanyInformation 
 
	INSERT INTO sCommon.tCompanyInformationDetail
		(
		     OrgId
			,RegistrationNumber  
			,LicenceNumber 
			,EsicNumber  
			,EsicAddress1 
			,EsicAddress2  
			,NatureOfIndustry  
			,ByProduct 
			,DangerousOperation  
			,NatureOfTest  
			,RowMaterialUsed  
			,HazardousProcess  
			,Cmo  
			,NicNumber  
		)
	VALUES
		(
		    @rId,    
			@rRegistrationNumber, 
			@rLicenceNumber ,
			@rEsicNumber ,
			@rEsicAddress1 , 
			@rEsicAddress2,  
			@rNatureOfIndustry , 
			@rByProduct , 
			@rDangerousOperation, 
			@rNatureOfTest,  
			@rRowMaterialUsed,  
			@rHazardousProcess , 
			@rCmo,  
			@rNicNumber  			
		)
		SELECT @rId AS RESULT
  END
 ELSE
	BEGIN
		SELECT -100 AS RESULT
	END
 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCompanyInformationDetailModify]
	@rId int,
	@rRegistrationNumber nvarchar(50), 
	@rLicenceNumber nvarchar(50),
	@rEsicNumber nvarchar(50),
	@rEsicAddress1 nvarchar(100),
	@rEsicAddress2 nvarchar(100),
	@rNatureOfIndustry nvarchar(100),
	@rByProduct nvarchar(100),
	@rDangerousOperation nvarchar(100),
	@rNatureOfTest nvarchar(100),
	@rRowMaterialUsed nvarchar(100),
	@rHazardousProcess nvarchar(100),
	@rCmo nvarchar(50),
	@rNicNumber nvarchar(50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tCompanyInformationDetail
		SET 
			 OrgId = @rId
			,RegistrationNumber = @rRegistrationNumber   
			,LicenceNumber = @rLicenceNumber 
			,EsicNumber = @rEsicNumber  
			,EsicAddress1 = @rEsicAddress1 
			,EsicAddress2  = @rEsicAddress2  
			,NatureOfIndustry  = @rNatureOfIndustry  
			,ByProduct = @rByProduct 
			,DangerousOperation  = @rDangerousOperation  
			,NatureOfTest  = @rNatureOfTest  
			,RowMaterialUsed  = @rRowMaterialUsed  
			,HazardousProcess  = @rHazardousProcess  
			,Cmo = @rCmo
			,NicNumber = @rNicNumber  
			 
			
	  WHERE OrgId =  @rId
	  
	  SELECT @rId AS RESULT
	  
	  
	 --	IF @rIsPfApplicable = 1
		--	UPDATE sSecurity.tMenu SET IsObsolete = 0 WHERE ID = 221111
		--ELSE
		--	UPDATE sSecurity.tMenu SET IsObsolete = 1 WHERE ID = 221111
	
		--IF @rIsEsiApplicable = 1
		--	UPDATE sSecurity.tMenu SET IsObsolete = 0 WHERE ID = 221114
		--ELSE
		--	UPDATE sSecurity.tMenu SET IsObsolete = 1 WHERE ID = 221114
			
		--IF @rIsGratuityApplicable = 1
		--	UPDATE sSecurity.tMenu SET IsObsolete = 0 WHERE ID = 221117
		--ELSE
		--	UPDATE sSecurity.tMenu SET IsObsolete = 1 WHERE ID = 221117
	  
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCompanyInformationGet]
	@rOrgId [smallint] = 0,
	@rId [smallint] = 0,
    @rCode [nvarchar](20) = '', 
	@rTitle [nvarchar](100) = '',	 
	@rIsWildCardSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

   BEGIN
		IF @rIsWildCardSearch = 1
			BEGIN
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END
	END
	 SELECT CI.Id,
			ISNULL(CI.Code,'') AS Code,
			ISNULL(CI.Title,'') AS Title,
			ISNULL(CI.ParentCompanyName,'') AS ParentCompanyName,
			ISNULL(CI.StreetOne,'') AS StreetOne,
			ISNULL(CI.StreetTwo,'') AS StreetTwo,
			ISNULL(CI.StreetThree,'') AS StreetThree,
			ISNULL(CI.StreetFour,'') AS StreetFour,
			ISNULL(CI.CityName,'') AS CityName,
			ISNULL(CI.StateName,'') AS StateName,
			ISNULL(CI.CountryName,'') AS CountryName,
			ISNULL(CI.ZipCode,'') AS ZipCode,
			ISNULL(CI.HomePage,'') AS HomePage,
			--ISNULL(CI.CityName,'') + ' ' + ISNULL(StateName,'') AS CityState,
			--ISNULL(CI.CountryName,'')  + ' ' + ISNULL(ZipCode,'') AS CountryZip,
			ISNULL(CI.PhoneNo,'') AS PhoneNo,
			ISNULL(CI.FaxNo,'') AS FaxNo,
			ISNULL(CI.SmallAddress1,'') AS SmallAddress1,
			ISNULL(CI.SmallAddress2,'') AS SmallAddress2,
			ISNULL(CI.IsShowCompanyName,0) AS IsShowCompanyName, 
			ISNULL(CI.CompanyNameAlignment,0) AS CompanyNameAlignment,
			ISNULL(CI.IsShowCompanyAddress,0) AS IsShowCompanyAddress,
			ISNULL(CI.CompanyAddressAlignment,0) AS CompanyAddressAlignment,
			ISNULL(CID.RegistrationNumber,'')   AS RegistrationNumber
			,ISNULL(CID.LicenceNumber,'')AS LicenceNumber
			,ISNULL(CID.EsicNumber,'')AS EsicNumber 
			,ISNULL(CID.EsicAddress1,'')AS EsicAddress1
			,ISNULL(CID.EsicAddress2,'') AS EsicAddress2 
			,ISNULL(CID.NatureOfIndustry,'') AS NatureOfIndustry
			,ISNULL(CID.ByProduct,'') AS ByProduct
			,ISNULL(CID.DangerousOperation,'') AS DangerousOperation 
			,ISNULL(CID.NatureOfTest,'') AS NatureOfTest 
			,ISNULL(CID.RowMaterialUsed,'') AS RowMaterialUsed  
			,ISNULL(CID.HazardousProcess,'') AS HazardousProcess  
			,ISNULL(CID.Cmo,'') AS Cmo 
			,ISNULL(CID.NicNumber,'') AS NicNumber
			--ContactPerson,
			--PhoneNumberHome,
			--PhoneNumberOffice,
			--PhoneNumberMobile,
			--EmailPrimary,
			--EmailAlternative,
			--HomePage,
			--BaseCalendarId,
			--BankName,
			--BankAccountNumber,
			--BankGlAccountNumber,
			--RbiCode,
			--PaymentRoutingNumber,
			--SwiftCode,
			--BankStreetOne,
			--BankStreetTwo,
			--BankStreetThree,
			--BankStreetFour,
			--BankCityName,
			--BankStateName,
			--BankCountryName,
			--BankZipCode,
			--BankContactPerson,
			--BankPhoneNumberHome,
			--BankPhoneNumberOffice,
			--BankPhoneNumberMobile,
			--BankEmailPrimary,
			--BankEmailAlternative,
			--CustomsPermitNumber,
			--CustomsPermitDate,
			--RegistrationNumber,
			--RegistrationExpiryDate,
			--TinNumber,
			--TinExpiryDate,
			--ExciseRegistrationNumber,
			--ExicseExpiryDate,
			--LstNumber,
			--LstExpiryDate,
			--CstNumber,
			--CstExpiryDate,
			--PanNumber,
			--LtegNumber,
			--EccNumber,
			--TanNumber,
			--CeRegdNumber,
			--CeRange,
			--CeCommissioneRate,
			--IecCode,
			--Esi,
			--EProvIdentFund,
			--CeDivision,
			--DrugLicenceNumber,
			--DrugLicenceExpiryDate,
			--BloodBankRegistrationNumber,
			--BloodBankRegistrationExpiryDate,
			--CreatedDateTime,
			--DrugLicenceNumberOne,
			--DrugLicenceExpiryDateOne,
			--DrugLicenceNumberTwo,
			--DrugLicenceExpiryDateTwo,
			--DrugLicenceNumberThree,
			--DrugLicenceExpiryDateThree,
			--DrugLicenceNumberFour,
			--DrugLicenceExpiryDateFour,
			--DrugLicenceNumberFive,
			--DrugLicenceExpiryDateFive,
			--AccountYearStartDate,
			--TdsYearStartDate,
			--TdsCircle,
			--TdsAuthorisedSignatoryName,
			--Designation,
			--TaxDepreciationMinimumMonths,
			--TaxDepreciationMinimumPercentage,
			--ReportingCurrencyId,
			--AccountingCurrencyId,
			--ForeignCurrencyId,
			--ChequeFavouring,
			--IsPfApplicable,
			--IsEsiApplicable,
			--IsGratuityApplicable,
			--IsWhtApplicable,
			--MinimumAge,
			--MaximumAge,
			--SalaryDaysId,
			--TanNumber,
			--PanNumber,  
			--(CASE SalaryDaysId WHEN 1 THEN 30 ELSE  DAY(DATEADD(d, -DAY(DATEADD(m, 1, sCommon.fGetDate())), DATEADD(m, 1, sCommon.fGetDate()))) END) AS SalaryDays
	  FROM sCommon.tCompanyInformation CI INNER JOIN sCommon.tCompanyInformationDetail CID ON CI.Id = CID.OrgId
	  WHERE ((CI.Id = @rId) OR (@rId = 0))
	  AND	((CI.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	  AND	((CI.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = '')) 
	  AND   ((CI.Id = @rOrgId) OR (@rOrgId = 0))
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCompanyInformationModify]
	@rId [smallint],
	@rCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rParentCompanyName [nvarchar](300),
	@rStreetOne [nvarchar](50),
	@rStreetTwo [nvarchar](50),
	@rStreetThree [nvarchar](50),
	@rStreetFour [nvarchar](50),
	@rCityName [nvarchar](100),
	@rStateName [nvarchar](100),
	@rCountryName [nvarchar](100),
	@rZipCode [nvarchar](20),
	@rHomePage [nvarchar](100),	  
	@rPhoneNo [nvarchar](100),
	@rFaxNo [nvarchar](100),
	@rSmallAddress1 [nvarchar](100),
	@rSmallAddress2 [nvarchar](100),
	@rIsShowCompanyName bit,
	@rCompanyNameAlignment int,
	@rIsShowCompanyAddress bit,
	@rCompanyAddressAlignment int 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tCompanyInformation
		SET 
			Code = @rCode,
			Title = @rTitle,
			ParentCompanyName = @rParentCompanyName,
			StreetOne = @rStreetOne,
			StreetTwo = @rStreetTwo,
			StreetThree = @rStreetThree,
			StreetFour = @rStreetFour,
			CityName = @rCityName,
			StateName = @rStateName,
			CountryName = @rCountryName,
			ZipCode = @rZipCode,
			HomePage = @rHomePage,		 
			PhoneNo = @rPhoneNo,
			FaxNo = @rFaxNo,
			SmallAddress1 = @rSmallAddress1,
			SmallAddress2 = @rSmallAddress2,
			IsShowCompanyName = @rIsShowCompanyName,
			CompanyNameAlignment = @rCompanyNameAlignment,
			IsShowCompanyAddress = @rIsShowCompanyAddress,
			CompanyAddressAlignment = @rCompanyAddressAlignment
			--ContactPerson = @rContactPerson,
			--PhoneNumberHome = @rPhoneNumberHome,
			--PhoneNumberOffice = @rPhoneNumberOffice,
			--PhoneNumberMobile = @rPhoneNumberMobile,
			--EmailPrimary = @rEmailPrimary,
			--EmailAlternative = @rEmailAlternative,
			--HomePage = @rHomePage,
			--BaseCalendarId = @rBaseCalendarId,			
			--CustomsPermitNumber = @rCustomsPermitNumber,
			--CustomsPermitDate = @rCustomsPermitDate,
			--RegistrationNumber = @rRegistrationNumber,
			--RegistrationExpiryDate = @rRegistrationExpiryDate,
			--TinNumber = @rTinNumber,
			--TinExpiryDate = @rTinExpiryDate,
			--ExciseRegistrationNumber = @rExciseRegistrationNumber,
			--ExicseExpiryDate = @rExicseExpiryDate,
			--LstNumber = @rLstNumber,
			--LstExpiryDate = @rLstExpiryDate,
			--CstNumber = @rCstNumber,
			--CstExpiryDate = @rCstExpiryDate,
			--LtegNumber = @rLtegNumber,
			--EccNumber = @rEccNumber,			
			--CeRegdNumber = @rCeRegdNumber,
			--CeRange = @rCeRange,
			--CeCommissioneRate = @rCeCommissioneRate,
			--IecCode = @rIecCode,
			--Esi = @rEsi,
			--EProvIdentFund = @rEProvIdentFund,
			--CeDivision = @rCeDivision,
			--DrugLicenceNumber = @rDrugLicenceNumber,
			--DrugLicenceExpiryDate = @rDrugLicenceExpiryDate,
			--BloodBankRegistrationNumber = @rBloodBankRegistrationNumber,
			--BloodBankRegistrationExpiryDate = @rBloodBankRegistrationExpiryDate,
			--DrugLicenceNumberOne = @rDrugLicenceNumberOne,
			--DrugLicenceExpiryDateOne = @rDrugLicenceExpiryDateOne,
			--DrugLicenceNumberTwo = @rDrugLicenceNumberTwo,
			--DrugLicenceExpiryDateTwo = @rDrugLicenceExpiryDateTwo,
			--DrugLicenceNumberThree = @rDrugLicenceNumberThree,
			--DrugLicenceExpiryDateThree = @rDrugLicenceExpiryDateThree,
			--DrugLicenceNumberFour = @rDrugLicenceNumberFour,
			--DrugLicenceExpiryDateFour = @rDrugLicenceExpiryDateFour,
			--DrugLicenceNumberFive = @rDrugLicenceNumberFive,
			--DrugLicenceExpiryDateFive = @rDrugLicenceExpiryDateFive,
			--ReportingCurrencyId = (CASE @rReportingCurrencyId WHEN 0 THEN NULL ELSE @rReportingCurrencyId END),
			--AccountingCurrencyId = (CASE @rAccountingCurrencyId WHEN 0 THEN NULL ELSE @rAccountingCurrencyId END),
			--ForeignCurrencyId = (CASE @rForeignCurrencyId WHEN 0 THEN NULL ELSE @rForeignCurrencyId END),
			--ChequeFavouring = @rChequeFavouring,
			
			--IsPfApplicable = @rIsPfApplicable,
			--IsEsiApplicable = @rIsEsiApplicable,
			--IsGratuityApplicable = @rIsGratuityApplicable,
			--IsWhtApplicable = @rIsWhtApplicable, 
			--MinimumAge = @rMinimumAge,
			--MaximumAge = @rMaximumAge,
			--SalaryDaysId  = @rSalaryDaysId, 
			--TanNumber =   @rTanNumber,
			--PanNumber = @rPanNumber
			
	  WHERE Id = @rId
	  
	   SELECT @rId AS RESULT
	   
	 --	IF @rIsPfApplicable = 1
		--	UPDATE sSecurity.tMenu SET IsObsolete = 0 WHERE ID = 221111
		--ELSE
		--	UPDATE sSecurity.tMenu SET IsObsolete = 1 WHERE ID = 221111
	
		--IF @rIsEsiApplicable = 1
		--	UPDATE sSecurity.tMenu SET IsObsolete = 0 WHERE ID = 221114
		--ELSE
		--	UPDATE sSecurity.tMenu SET IsObsolete = 1 WHERE ID = 221114
			
		--IF @rIsGratuityApplicable = 1
		--	UPDATE sSecurity.tMenu SET IsObsolete = 0 WHERE ID = 221117
		--ELSE
		--	UPDATE sSecurity.tMenu SET IsObsolete = 1 WHERE ID = 221117
	  
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCountryIdByStateIdGet]
    @rOrgGroupId [int],
	@rStateId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--SET @rOrgId = 0
	SELECT ISNULL(SM.CountryId, 0) AS CountryId,
	 ISNULL(CM.Title, '') AS CityTitle,
	 ISNULL(CM.Title, '') AS CountryTitle
	  FROM sCommon.tStateMaster SM
	 LEFT JOIN sCommon.tCountryMaster CM ON CM.Id = SM.CountryId
	 WHERE SM.Id = @rStateId AND SM.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCountryMasterAdd]
	@rOrgGroupId int,
	@rOrgId int,
	@rTitle [nvarchar](100) = '',
	@rNationality [nvarchar](50) = '',
	@rIsObsolete [bit] = 0,
	@rCreatedUserId [bigint] = 1,
	@rIsShow [bit] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lNextNumber INT
--SET @rOrgId = 0

IF @rNationality <> ''
	BEGIN
		IF NOT EXISTS (SELECT Id
						FROM sCommon.tCountryMaster
						WHERE (UPPER(Title) = UPPER(@rTitle) OR UPPER(Nationality) = UPPER(@rNationality)) 
							  AND IsShow = 1 AND OrgGroupId=@rOrgGroupId)		
		BEGIN
			
			/************************************Change to 101***************************/
			--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tCountryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tCountryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCommon.tCountryMaster
				(	
					Id,			
					Title,
					Nationality,	
					IsObsolete,		
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime,
					IsShow,
					OrgGroupId	
					
				)
			VALUES
				(
					@lNextNumber,			
					@rTitle,
					@rNationality,
					@rIsObsolete,			
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rIsShow,
					@rOrgGroupId
				)
			SELECT 1 AS Result, @lNextNumber AS CountryId
		END
		ELSE
			BEGIN
				SELECT -1 AS Result, -1 AS CountryId
			END
	END
ELSE IF @rNationality = ''
	BEGIN
		SET @lNextNumber = 0
		SELECT @lNextNumber = Id FROM sCommon.tCountryMaster WHERE Title = @rTitle
		IF @lNextNumber <= 0
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tCountryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCommon.tCountryMaster
					(	
						Id,			
						Title,
						Nationality,	
						IsObsolete,		
						CreatedUserId,
						CreatedDateTime,
						UpdatedUserId,
						UpdatedDateTime,
						IsShow,
						OrgGroupId	
						
					)
				VALUES
					(
						@lNextNumber,			
						@rTitle,
						@rNationality,
						@rIsObsolete,			
						@rCreatedUserId,
						sCommon.fGetDate(),
						@rCreatedUserId,
						sCommon.fGetDate(),
						@rIsShow,
						@rOrgGroupId
					)
				SELECT 1 AS Result, @lNextNumber AS CountryId
			END
		ELSE IF @lNextNumber > 0
			BEGIN
				SELECT 1 AS Result, @lNextNumber AS CountryId
			END
		ELSE
			BEGIN
				SELECT -1 AS Result, -1 AS CountryId
			END	
END	
	ELSE
		BEGIN
			SELECT -1 AS Result, -1 AS CountryId
		END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCountryMasterGet]
	@rOrgGroupId [int],
	@rId [int] = 0,
	@rTitle [nvarchar](100) = '',
	@rIsSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--SET @rOrgId = 0
IF @rIsSearch = 1
	BEGIN
		--SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	 SELECT 
			Id,			
			Title,
			Nationality,
			IsObsolete,			
			CASE WHEN IsObsolete = 1 THEN 'Y'
					ELSE 'N'
			END AS ObsoleteDisplay				          
          
	   FROM sCommon.tCountryMaster
	  WHERE (
				((Id = @rId) OR (@rId = 0)) 			    	
						AND ((Title LIKE @rTitle) OR (@rTitle = ''))
							AND IsShow = 1
		    )AND OrgGroupId = @rOrgGroupId
	Order BY Title				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCountryMasterModify]
	@rId [int],
	@rNationality [nvarchar](50) = '',
	@rIsObsolete [bit] = 0,
	@rUpdatedUserId [bigint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

IF NOT EXISTS (SELECT Id
	FROM sCommon.tCountryMaster
	WHERE (
			UPPER(Nationality) = UPPER(@rNationality) 
		  )  
		AND Id <> @rId
		AND IsObsolete = 0)
BEGIN
	 UPDATE sCommon.tCountryMaster
		SET 			
			
			Nationality = @rNationality,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = 	sCommon.fGetDate()
			
	  WHERE Id = @rId
	SELECT 1 AS Result
END
ELSE
SELECT -1 AS Result

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCustomReportAdd]


	 @rReportId smallint,
	 @rOrgGroupId smallint,
	 @rIsObsolete bit=0
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	if exists(Select 1 from sCommon.tReportClient where ReportId =@rReportID and OrgGroupId=@rOrgGroupId AND @rIsObsolete=0)
	BEGIN
		 delete from sCommon.tReportClient where ReportId =@rReportID  and OrgGroupId=@rOrgGroupId 
	END
	ELSE
	BEGIN
	IF exists(Select 1 from sCommon.tReportClient where ReportId =@rReportID and OrgGroupId=@rOrgGroupId AND @rIsObsolete=1)
	BEGIN
	Return
	ENd
	Else
	BEGIN
	if @rIsObsolete=1
	Begin
	 INSERT INTO sCommon.tReportClient
	 (
		ReportId,
		OrgGroupId,
		ReportPath
	 )
	 Values
	 (
		@rReportId,
		@rOrgGroupId,
		''
	 )
	 END
	 END
	 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pCustomReportGet]


	 @rModule int,
	 @rOrgGroupId smallint,
	  @rReport nvarchar(50)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	 
	SELECT 
			R.Id AS ReportId,
			R.Title AS ReportName,
			CAST(CASE WHEN RL.ReportId IS NULL   THEN 'false' ELSE 'true' END AS BIT) AS IsObsolete,
			M.TItle AS MOduleName,
			R.ReportPath
			
			
	FROM 
			sCommon.tReport R 
			
			LEFT JOIN sCommon.tReportClient RL ON R.Id = RL.ReportId ANd RL.OrgGroupId=@rOrgGroupId
			inner join  sSecurity.tTask T ON T.Id = R.TaskId 	 
			INNER JOIN sCommon.tModuleMaster M ON M.Id=T.ModuleId
			WHERE 
			 ((T.ModuleId=@rModule) OR (@rModule=0))
			AND R.IsObsolete = 0
				AND R.Title like  '%'+@rReport+'%'
			ORDER BY R.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pDataMasterAdd]
	@rOrgId int,
    @rCommonMasterId as int,
	@rVisibilityFieldId as int,	
	@rCode as nvarchar(300),
	@rTitle as nvarchar(300),
	@rIsObsolete [nvarchar](10),
	@rCreatedUserId [bigint]
	
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--BEGIN TRY

	DECLARE @lVisibilityField nvarchar(200)
	DECLARE @lIdField nvarchar(200)
	DECLARE @lCodeField nvarchar(200)
	DECLARE @lTitleField nvarchar(200)
	DECLARE @lTableName nvarchar(200)
	DECLARE @lIsStatic bit
	DECLARE @lNextNumber BigInt
	
	
	SELECT @lVisibilityField = VisibilityField,
	       @lIdField = IdField,
	       @lCodeField = CodeField,
	       @lTitleField = RemarkField,
	       @lTableName = TableTitle,
	       @lIsStatic = IsStatic1to100	       
	       FROM sCommon.tCommonMaster WHERE Id = @rCommonMasterId
	       
	
	DECLARE @lSeed INT
	
	SET @lSeed = (CASE WHEN @lIsStatic = 1 THEN 101 ELSE 1 END)
	EXECUTE sCommon.pTableRowIdGet @rOrgId, @lTableName, 0, @lSeed, 1,@outNextNumber = @lNextNumber output
	SET @lNextNumber = @lNextNumber
	

	DECLARE @lSelectClause Nvarchar(2000)
	DECLARE @lIsShow Nchar(1)
	
	SET @lSelectClause =      'IF EXISTS(SELECT  ' + @lCodeField + ' FROM ' + @lTableName + 
										' WHERE ' + @lVisibilityField + ' = ' + CONVERT(NVARCHAR(20), @lVisibilityField)  + ' AND ' +  @lCodeField + '	= ''' + @rCode + ''' ) 
     							BEGIN
									SELECT -101 AS Result
									RETURN
								END ' + 
								
 
								'IF EXISTS(SELECT  ' + @lTitleField + ' FROM ' + @lTableName + 
										' WHERE ' + @lVisibilityField + ' = ' + CONVERT(NVARCHAR(20), @lVisibilityField)  + ' AND ' +  @lTitleField + '	= ''' + @rTitle + ''' ) 
     							BEGIN
									SELECT -102 AS Result
									RETURN
								END '
								
								+
								
							   '
							  				 
							   INSERT INTO ' + @lTableName
								  + '(Id ' 
								     
									   + ', ' + @lCodeField 
									   + ', ' + @lTitleField 									   
                                       + ', ' + 'UpdatedUserId ' 
									   + ', ' + 'UpdatedDateTime ' 
									   + ', ' + 'CreatedUserId ' 
									   + ', ' + 'CreatedDateTime ' 
									    + ', ' + @lVisibilityField 
                                       + ', ' + 'IsObsolete' 
                                      
                                       + 
									 ')  
							   VALUES (' + CAST(@lNextNumber  AS NVARCHAR(20)) + ', ''' 
										
										 + @rCode + ''', ''' 
										 + @rTitle +  ''', '''
									    
                                         + CONVERT(NVARCHAR(20), @rCreatedUserId) + ''', ''' 
										 + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', '''
                                         + CONVERT(NVARCHAR(20), @rCreatedUserId) + ''', ''' 
										 + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', ''' 
										  + CONVERT(NVARCHAR(20), @rVisibilityFieldId) + ''', ''' 
										 + @rIsObsolete  										
										 +  
										 
								 + ''')
								 
								SELECT 1 AS Result'		
								
 

	EXECUTE sp_executesql @lSelectClause
--END TRY
--BEGIN CATCH
--SELECT ERROR_MESSAGE()
--SELECT ERROR_LINE()
--SELECT ERROR_NUMBER()
--END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pDataMasterListGet] 
	@rOrgId int,
    @rCommonMasterId as int,
	@rVisibilityFieldId as int,	 
	@rId nvarchar(10) = '0',	 
	@rCode [nvarchar](100) = '*',
	@rTitle [nvarchar](500) = '*'	 
	 
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
 
 
 	DECLARE @lVisibilityField nvarchar(200)
	DECLARE @lIdField nvarchar(200)
	DECLARE @lCodeField nvarchar(200)
	DECLARE @lTitleField nvarchar(200)
	DECLARE @lTableName nvarchar(200)
	DECLARE @lIsStatic bit
	DECLARE @lNextNumber BigInt
	
	
	SELECT @lVisibilityField = VisibilityField,
	       @lIdField = IdField,
	       @lCodeField = CodeField,
	       @lTitleField = RemarkField,
	       @lTableName = TableTitle,
	       @lIsStatic = IsStatic1to100	       
	       FROM sCommon.tCommonMaster WHERE Id = @rCommonMasterId
 
 
DECLARE @lQueryString Nvarchar(MAX)



 



SET @lQueryString = 'SELECT'
SET @lQueryString = @lQueryString + ' ' + @lIdField + '  AS Id ' + ', ' + @lCodeField + '  AS Code ' + ', ' + @lTitleField  + ' AS Title,' + 'IsObsolete' + ' FROM ' + @lTableName

--select @lQueryString

SET @lQueryString = @lQueryString + ' ' + 'WHERE	((' + @lIdField + ' = ' + CAST(@rId AS NVARCHAR(30)) + ') OR (' + CAST(@rId AS NVARCHAR(30)) + ' = 0))
											AND		((' + @lCodeField + ' LIKE '''+ @rCode +'%'+ ''') OR (''' + ISNULL(@rCode, '') + ''' = ''''))
											AND		((' + @lTitleField + ' LIKE '''+ @rTitle +'%'+ ''') OR (''' + ISNULL(@rTitle, '') + ''' = ''''))
											AND     ((' + @lVisibilityField + ' = ' + CAST(@rVisibilityFieldId AS NVARCHAR(30)) + ') OR (' + CAST(@rVisibilityFieldId AS NVARCHAR(30)) + ' = 0))'
										

--select @lQueryString
--EXEC(@lQueryString)
EXECUTE sp_executesql @lQueryString

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pDataMasterModify]
	@rOrgId int,
    @rCommonMasterId as int,
	@rVisibilityFieldId as int,
	@rId as int,	
	@rCode as nvarchar(300),
	@rTitle as nvarchar(300),
	@rIsObsolete [nvarchar](10),
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN

	DECLARE @lVisibilityField nvarchar(200)
	DECLARE @lIdField nvarchar(200)
	DECLARE @lCodeField nvarchar(200)
	DECLARE @lTitleField nvarchar(200)
	DECLARE @lTableName nvarchar(200)
	DECLARE @lIsStatic bit
	DECLARE @lNextNumber BigInt
	
	
	SELECT @lVisibilityField = VisibilityField,
	       @lIdField = IdField,
	       @lCodeField = CodeField,
	       @lTitleField = RemarkField,
	       @lTableName = TableTitle,
	       @lIsStatic = IsStatic1to100	       
	       FROM sCommon.tCommonMaster WHERE Id = @rCommonMasterId



	DECLARE @lSelectClause Nvarchar(2000)
	DECLARE @lIsShow Nchar(1)
	
	SET @lSelectClause =       'IF EXISTS(SELECT  ' + @lCodeField + ' FROM ' + @lTableName + 
										' WHERE ' + @lVisibilityField + ' = ' + CONVERT(NVARCHAR(20), @lVisibilityField)  + ' AND ' +  @lCodeField + '	= ''' + @rCode + ''' 
										  AND ' + @lIdField + ' <> ' + CONVERT(NVARCHAR(20), @rId) + ' )  
     							BEGIN
									SELECT -101 AS Result
									RETURN
								END ' + 
								
 
								'IF EXISTS(SELECT  ' + @lTitleField + ' FROM ' + @lTableName + 
										' WHERE ' + @lVisibilityField + ' = ' + CONVERT(NVARCHAR(20), @lVisibilityField)  + ' AND ' +  @lTitleField + '	= ''' + @rTitle + '''  
										  AND ' + @lIdField + ' <> ' + CONVERT(NVARCHAR(20), @rId) + ' )  
     							BEGIN
									SELECT -102 AS Result
									RETURN
								END '
								
								+

							   ' UPDATE ' + 	@lTableName + 
							   ' SET ' +  	
										  @lCodeField + ' = ''' + @rCode + ''' ' + ',' +
									      @lTitleField + ' = ''' + @rTitle + ''' ,
										  IsObsolete = ' + CONVERT(NVARCHAR(7), @rIsObsolete) + ' ,  		
									      UpdatedUserId = ' + CONVERT(NVARCHAR(25), @rCreatedUserId) + ' ,  
										  UpdatedDateTime = ''' + CONVERT(NVARCHAR(32), sCommon.fGetDate() )  + ''' 
										  WHERE ' + @lIdField + ' = ' + 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommon].[pDeleteOldBatchData]
	 
	@rBatchId int=0,
	@rType int=0,
	@rId bigint  = 0
		 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	IF(@rId = 0)
	BEGIN
		BEGIN TRY
		 BEGIN TRANSACTION 
		 BEGIN

			-- Classwork & Homework Tables
			IF(@rType=1)
			BEGIN		
				DELETE CV FROM sAcademic.tClassworkView CV INNER JOIN sAcademic.tClasswork C ON C.Id = CV.ClassworkId 
				WHERE C.BatchId=@rBatchId
				
				DELETE HC FROM sAcademic.tHomeworkCheck HC INNER JOIN sAcademic.tClasswork C ON C.Id = HC.ClassworkId 
				WHERE C.BatchId=@rBatchId	
				
				DELETE FROM sAcademic.tClasswork WHERE BatchId=@rBatchId		
					
			END
			
			-- Assignment Tables
			ELSE IF(@rType=2)
			BEGIN
			
				DELETE tAS FROM sCommunication.tAssignmentScope tAS INNER JOIN sCommunication.tAssignment A ON A.Id = tAS.AssignmentId 
				WHERE A.BatchId=@rBatchId
				
				DELETE AV FROM sCommunication.tAssignmentView AV INNER JOIN sCommunication.tAssignment A ON A.Id = AV.AssignmentId 
				WHERE A.BatchId=@rBatchId	
				
				DELETE FROM sCommunication.tAssignment WHERE BatchId=@rBatchId
			END
			
			--Circular Tables
			
			ELSE IF(@rType=3)
			BEGIN
				DELETE CS FROM sCommunication.tCircularScope CS INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId INNER JOIN sSetup.tBatchMaster BM 
				ON BM.OrgGroupBatchId = C.OrgGroupBatchId WHERE BM.Id=@rBatchId
				
				DELETE CV FROM sCommunication.tCircularView CV INNER JOIN sCommunication.tCircular C ON C.Id = CV.CircularId INNER JOIN sSetup.tBatchMaster BM 
				ON BM.OrgGroupBatchId = C.OrgGroupBatchId WHERE BM.Id=@rBatchId
				
				DELETE C FROM sSetup.tBatchMaster BM INNER JOIN [sCommunication].[tCircular] C ON C.OrgGroupBatchId=BM.OrgGroupBatchId WHERE BM.Id=@rBatchId
			END	
			
			--Notification Tables
			
			ELSE IF(@rType=4)
			BEGIN
				DELETE NL From sAlert.tNotificationLog NL INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=NL.SourceId AND NL.SourceTypeId=2003
				WHERE SA.BatchId=@rBatchId
			END

			-- Alert

			ELSE IF(@rType=5)
			BEGIN
				DELETE AL From sAlert.tAlertLog AL INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=2003
				WHERE SA.BatchId=@rBatchId
			END
			SELECT 1 AS Result
		END
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
	

	ELSE
		BEGIN
		BEGIN TRY
		 BEGIN TRANSACTION 
		 BEGIN

			-- Classwork & Homework Tables
			IF(@rType=1)
			BEGIN		
				DELETE FROM sAcademic.tClassworkView WHERE ClassworkId = @rId
				
				DELETE FROM sAcademic.tHomeworkCheck WHERE ClassworkId = @rId
				
				DELETE FROM sAcademic.tClasswork WHERE Id = @rId	
					
			END
			
			-- Assignment Tables
			ELSE IF(@rType=2)
			BEGIN
			
				DELETE FROM sCommunication.tAssignmentScope WHERE AssignmentId = @rId
				
				DELETE FROM sCommunication.tAssignmentView WHERE AssignmentId = @rId
				
				DELETE FROM sCommunication.tAssignment WHERE Id=@rId
			END
			
			--Circular Tables
			
			ELSE IF(@rType=3)
			BEGIN
				DELETE FROM sCommunication.tCircularScope WHERE CircularId = @rId 
				
				DELETE FROM sCommunication.tCircularView WHERE CircularId = @rId
				
				DELETE FROM [sCommunication].[tCircular] WHERE Id=@rId
			END	
			
			--Notification Tables
			
			ELSE IF(@rType=4)
			BEGIN
				DELETE FROM sAlert.tNotificationLog WHERE Id = @rId
			END

			--Alert

			ELSE IF(@rType=5)
			BEGIN
				DELETE FROM sAlert.tAlertLog WHERE Id = @rId
			END
			SELECT 1 AS Result
		END
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To add records to sOrderEntry.tServiceCategoryMaster table
	Created date     : 22 Apr 2009
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Changed By and Date
	Test script      : EXECUTE sOrderEntry.pServiceCategoryMasterAdd @rServiceItemTypeId = 0, @rCode = 0, @rTitle = 0, @rIsObsolete = 0, @rCreatedUserId = 0
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sCommon].[pDepartmentGroupMasterAdd]
	(   
		@rId int,
	    @rOrgId int,
		@rFunctionId Int,
		@rCode Nvarchar(10),
		@rTitle Nvarchar(50),
		@rIsObsolete Bit,
		@rCreatedUserId BigInt
		 
	)
AS

SET NOCOUNT ON

BEGIN

DECLARE @lNextNumber bigint	
IF(@rId = 0)
  BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tDepartmentGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommon.tDepartmentGroupMaster
		(
			Id,		 
			FunctionId,
			Code,
			Title,
			IsObsolete,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,			 
			@rFunctionId,
			@rCode,
			@rTitle,
			@rIsObsolete, 
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
	END
	
	ELSE
  BEGIN	
	SET @lNextNumber = @rId
	UPDATE sCommon.tDepartmentGroupMaster
	SET  
	       FunctionId = @rFunctionId,
			Code = @rCode,
			Title = @rTitle,
			UpdatedUserId = @rCreatedUserId,
			IsObsolete = @rIsObsolete, 
			UpdatedDateTime = sCommon.fGetDate()
			
	WHERE Id = @rId		
	END		
	SELECT @lNextNumber AS StatusCode
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To get records from sOrderEntry.tServiceCategoryMaster table
	Created date     : 22 Apr 2009
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Added IsObsoleteYN filed
	Test script      : EXECUTE sOrderEntry.pServiceCategoryMasterGet @rId = 0, @rCode = '', @rTitle = ''
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sCommon].[pDepartmentGroupMasterGet]
	(
		@rId SmallInt = 0,
		@rCode Nvarchar(10) = '',
		@rTitle Nvarchar(50) = '',
		@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN

SET @rCode = sCommon.fSearchStringGet(@rCode)
SET @rTitle = sCommon.fSearchStringGet(@rTitle)

	 SELECT DGM.Id,			
			DGM.Code,
			DGM.Title,	
			DGM.FunctionId,		 
			FM.Title AS FunctionName, 
			DGM.IsObsolete, 
			(CASE DGM.IsObsolete WHEN '0' THEN 'N' ELSE 'Y' END) AS IsObsoleteYN
	   FROM sCommon.tDepartmentGroupMaster DGM	
	   INNER JOIN sCommon.tFunctionMaster FM	
	   ON DGM.FunctionId = FM.Id
	  WHERE ((DGM.Id = @rId) OR (@rId = 0))
	        AND ((DGM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	        AND ((DGM.Title LIKE @rTitle ) OR (ISNULL(@rTitle, '') = ''))
	        AND DGM.OrgId=@rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pDependsGet]
	@rParentTable [nvarchar](300) = '',
	@rFunctionalityType [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT D.Id,
			ParentTable,
			DependentTable,
			SourceTypeFieldName,
			SourceTypeId,
			FunctionalityType,
		    S.Title AS ScreeName
			
	   FROM sCommon.tDepends D INNER JOIN sSecurity.tScreen S ON D.ScreenId = S.Id
	  WHERE ((ParentTable = @rParentTable) OR (@rParentTable = ''))
			AND ((FunctionalityType & 0 = @rFunctionalityType)
				 OR (FunctionalityType & 1 = @rFunctionalityType)
				 OR (FunctionalityType & 2 = @rFunctionalityType))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pDosageMasterAdd]
	@rCode [nvarchar](10),
	@rTitle [nvarchar](50),
	@rIsShow [bit],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lId BIGINT

SET @lId = (SELECT ID FROM sCommon.tDosageMaster WHERE Title = @rTitle)

IF (ISNULL(@lId, 0) = 0)
BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 'sCommon.tDosageMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tDosageMaster
		(
			Id,
			Code,
			Title,
			--IsShow,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			--@rIsShow,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		SET @lId = @lNextNumber
END
SELECT @lId AS ID
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pDosageMasterModify]
	@rId [smallint],
	@rCode [nvarchar](10),
	@rTitle [nvarchar](50),
	@rIsShow [bit],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tDosageMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			--IsShow = @rIsShow,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pDurationMasterAdd]
	@rCode [nvarchar](10),
	@rTitle [nvarchar](50),
	@rIsShow [bit],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lId BIGINT

SET @lId = (SELECT ID FROM sCommon.tDurationMaster WHERE Title = @rTitle)

IF (ISNULL(@lId, 0) = 0)
BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 'sCommon.tDurationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tDurationMaster
		(
			Id,
			Code,
			Title,
			--IsShow,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			--@rIsShow,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		SET @lId = @lNextNumber
END
SELECT @lId AS ID
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pDurationMasterForPrescriptionGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,		 
			Title
		 
	   FROM sCommon.tDurationUnitMaster
	  WHERE Id IN(5,6,4)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pDurationMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			---IsShow,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sCommon.tDurationMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pDurationMasterModify]
	@rId [smallint],
	@rCode [nvarchar](10),
	@rTitle [nvarchar](50),
	@rIsShow [bit],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tDurationMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			---IsShow = @rIsShow,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pEmployeeSearchGet]
	@rOrgId [int],
	@rEmployeeCode [nvarchar](20) = '',
	@rFirstName [nvarchar](30) = '',
	@rMobileNumber [nvarchar](20) = '',
	@rDOB [datetime] = '1/1/1900',
	--@rEmployeeLocationId int,
	@rLastName [nvarchar](30) = '',
	@rParticipantSourceTypeId int = 0,
	@rDepartmentId int = 0,
	@rEmployeeId bigint = 0,
	@rStatusId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 --SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
IF(@rParticipantSourceTypeId = 95 OR @rParticipantSourceTypeId = 0 )
BEGIN
SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
SET @rLastName = sCommon.fSearchStringGet(@rLastName)
 SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber) 
 
 	 SELECT OrgID,
			Id,
			EmployeeId,
			Code,
			FirstName,
			MiddleName,
			LastName,
		    EmployeeName,	 			
			GenderId,
			ISNULL(DateOfBirth,'1900/01/01') AS DateOfBirth,
			ISNULL(DateOfJoining,'1900/01/01') AS DateOfJoining,
			'' AS Gender,
			--PermanentAddressId,
			--PresentAddressId AS CommunicationAddressId,
			--PresentContactId AS CommunicationContactId,
			StatusId,
			EM.IsObsolete,
			PhoneNoCompany,
			CompanyEmail,
			ExtensionNo,			
			DepartmentId,  
			DepartmentCode,  
			DepartmentName,
		    ISNULL (MobileNumber,0) AS MobileNumber,
			--EmployeeJobTitleId,
			--EmployeeTypeId,
			--EmployeeJobTitle,
			--EmployeeLocationId,
			ISNULL(DATEDIFF(yy,DateOfBirth,sCommon.fGetDate()),0) AS Age,
			DesignationId,
			--ProcessTypeId,
			ParticipantSourceTypeId
			
 
	 FROM sHrm.vExtEmployeeMaster EM
	 
		 WHERE 
		    
		      ((EM.Code = @rEmployeeCode) OR (ISNULL(@rEmployeeCode ,'')=''))
			  AND ((EM.FirstName Like  @rFirstName)  OR (ISNULL(@rFirstName,'') = ''))
			  AND ((EM.LastName Like  @rLastName)  OR (ISNULL(@rLastName,'') = ''))
			  AND ((EM.MobileNumber Like @rMobileNumber) OR(ISNULL(@rMobileNumber,'') = ''))				 
			  AND EM.IsObsolete = 0
			  --AND EM.EmployeeGroupId=1
			  AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			  --AND ((EM.EmployeeLocationId = @rEmployeeLocationId) OR (ISNULL(@rEmployeeLocationId,0) = 0) )		  			  
			  AND ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0) )	
			  AND ((EM.StatusId=@rStatusId) OR (@rStatusId=0))
			  AND ISNULL(EM.IsOtherUser,0) = 0 	 
		END
		
   ELSE IF(@rParticipantSourceTypeId = 1001) 
	  BEGIN
	  SELECT
		 OrgId,
	     DependentId,
	     EmployeeCode AS Code,
	     EmployeeId AS Id,
	     Name AS EmployeeName,
	     DateOfBirth,
	     AGE,
	     0 AS GenderId,
	     DepartmentId,
	     DepartmentName,
	     0 AS MobileNumber,
	     DesignationId,
	     '' AS FirstName,
	     '' AS LastName,
	     1001 AS ParticipantSourceTypeId
	     
	     FROM sHrm.vExtEmployeeFamilyDetail  Where 
	      (EmployeeCode Like @rEmployeeCode) AND DependentId = @rEmployeeId 
			   	AND OrgId = @rOrgId  AND ISNULL(IsOtherUser,0) = 0 	 
			 
			   	--AND EmployeeLocationId = @rEmployeeLocationId 
	      
	  END	
		
   --ELSE IF(@rParticipantSourceTypeId = 1009)       
   --    BEGIN 
   --      SELECT 
	  --      OrgId,
	  --      EmployeeId AS Id,     
	  --      EmployeeId,
			--Code,
			--FirstName,	 
			--LastName,
			--EmployeeName,
			--GenderId,
			--ISNULL(DateOfBirth,'') AS DateOfBirth, 
			--'' AS DepartmentName,
			--1009 AS ParticipantSourceTypeId,		 			 
			--0 AS  DepartmentId,	 
			--0 AS DesignationId,	 		
			--ISNULL(DATEDIFF(yy,DateOfBirth,GETDATE()),0) AS Age
			----0 AS ProcessTypeId
			--,OrgId
			----,LocationId
			--,'' AS MobileNumber 
	       
			
	  --FROM  sHrm.vExtCsrBenefiterMaster          
   --     WHERE   (Code Like @rEmployeeCode)
			--   	AND OrgId = @rOrgId 
			--   	--AND LocationId = @rEmployeeLocationId
 		-- END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pExceptionsAdd]
	@rExceptionType [nvarchar](100),
	@rMachineName [nvarchar](100),
	@rExceptionFullName [nvarchar](100),
	@rExceptionNumber [int],
	@rSeverityLevel [nvarchar](50),
	@rAppDomainName [nvarchar](50),
	@rThreadIdentityName [nvarchar](max),
	@rWindowsIdentityName [nvarchar](max),
	@rHelpLink [nvarchar](300),
	@rStackTrace [nvarchar](max),
	@rRawExceptionPatternString [nvarchar](300),
	@rRawExceptionParmsTSV [nvarchar](max),
	@rExceptionMessage [nvarchar](max),
	@rParentExceptionTyped [nvarchar](100),
	@rParentMachineName [nvarchar](100),
	@rParentExceptionMessage [nvarchar](max)
WITH EXECUTE AS CALLER
AS
BEGIN
		SET NOCOUNT ON
		INSERT INTO  sCommon.tExceptions
				(
					ExceptionType,	
					CreationDateTime,	
					MachineName, 
					ExceptionFullName,
					ExceptionNumber,
					SeverityLevel,
					AppDomainName,
					ThreadIdentityName,
					WindowsIdentityName,
					HelpLink,
					StackTrace,
					RawExceptionPatternString,
					RawExceptionParmsTSV,
					ExceptionMessage,
					ParentExceptionType,
					ParentCreationDateTime,
					ParentMachineName,
					ParentExceptionMessage
				)
			VALUES
				(	@rExceptionType,	
					sCommon.fGetDate(),	
					@rMachineName, 
					@rExceptionFullName,
					@rExceptionNumber,
					@rSeverityLevel,
					@rAppDomainName,
					@rThreadIdentityName,
					@rWindowsIdentityName,
					@rHelpLink,
					@rStackTrace,
					@rRawExceptionPatternString,
					@rRawExceptionParmsTSV,
					@rExceptionMessage,
					@rParentExceptionTyped,
					sCommon.fGetDate(),
					@rParentMachineName,
					@rParentExceptionMessage)
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFileCountGet]
	@rOrgId [int],
	@rSourceTypeId int,
	@rSourceId bigint	
AS 
BEGIN


					SELECT COUNT(Id) AS TotalFile
					FROM sCommon.tFileUpload
						WHERE  OrgId = @rOrgId
						AND SourceTypeId = @rSourceTypeId
						AND SourceId = @rSourceId
						 
						
						
	 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFilePathAdd]
	@rSourceId [bigint],
	@rSourceTypeId [smallint],
	@rOrgId [smallint],
	@rFileName [nvarchar](300)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
  BEGIN TRY	
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sCommon.tFileUpload', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommon.tFileUpload
		(
			Id,
			OrgId,
			SourceTypeId,
			SourceId,
			FileName
		)
	VALUES
		(
			@lNextNumber,
			@rOrgId,
			@rSourceTypeId,
			@rSourceId,
			@rFileName
		)
		
		SELECT 1 AS RESULT
        END TRY
        BEGIN CATCH
		SELECT -1 AS RESULT
	    END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFilePathDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
		DELETE	FROM tFileUpload 
		WHERE Id=@rId
		
		SELECT 1 AS RESULT
	END TRY
	BEGIN CATCH
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFilePathget]
@rSourceTypeId smallint,
@rOrgId int

AS
BEGIN

	SELECT FilePath
	FROM sCommon.tFilePath 
	WHERE SourceTypeId=@rSourceTypeId  AND OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFirstAidMasterAdd]
	@rTitle [nvarchar](100),
	@rCreatedUserId [bigint],
	@rIsObsolete [bit],
	@rCode [nvarchar](100),
	@rOrganizationDepartmentId [int],
	@rOrgId int,
	@rStoreLocationId int,
	@rCustodianEmployeeId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sCommon.tFirstAidMaster WHERE UPPER(Code) = UPPER(@rCode) AND OrganizationDepartmentId = @rOrganizationDepartmentId AND OrgId = @rOrgId)

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

	INSERT INTO sCommon.tFirstAidMaster
		(
			Id,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime,
			Code,
			OrganizationDepartmentId,
			OrgId,
			StoreLocationId,
			CustodianEmployeeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCode,
			@rOrganizationDepartmentId,
			@rOrgId,
			@rStoreLocationId,
			@rCustodianEmployeeId
		)
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFirstAidMasterGet]
	@rId [int] = 0,
	@rTitle [nvarchar](20) = '',
	@rCode [nvarchar](100) = '',
	@rOrganizationDepartmentId [int] = 0,
	@rOrgId int,
	@rIsWildCardSearch [bit] = 1,
	@rLocationId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	IF @rIsWildCardSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
		
	SET @rCode = sCommon.fSearchStringGet(@rCode)


	 SELECT M.Id,
			M.Title,
			M.CreatedUserId,
			M.CreatedDateTime,
			M.IsObsolete,
			M.UpdatedUserId,
			M.UpdatedDateTime,
			M.Code,
			M.OrganizationDepartmentId,
			C.Title AS OrganizationDepartmentName,
			ISNULL(M.CustodianEmployeeId,'')AS CustodianEmployeeId,
			ISNULL(EM.Code,'') AS EmployeeCode,
			ISNULL(EM.FirstName +  ' ' + EM.LastName,'') AS EmployeeName
			
	   FROM sCommon.tFirstAidMaster M 
	   INNER JOIN sSetup.tDepartmentMaster C
	   ON M.OrganizationDepartmentId = c.Id 
	   INNER JOIN sIp.tStoreLocationMaster SLM 
	   ON SLM.Id = M.StoreLocationId
	   LEFT JOIN sHrm.tEmployeeMaster EM
	   ON EM.Id=M.CustodianEmployeeId
	   
	  WHERE ((M.Id = @rId) OR (@rId = 0))
	   AND ((M.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((M.Code LIKE @rCode ) OR (ISNULL(@rCode, '') = ''))
	   AND ((M.OrganizationDepartmentId = @rOrganizationDepartmentId) OR (@rOrganizationDepartmentId = 0))
	   AND 	M.OrgId = 	@rOrgId 
	   AND SLM.LocationId = @rLocationId
	   AND ISNULL(EM.IsOtherUser,0) = 0 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFirstAidMasterModify]
	@rId [int],
	@rTitle [nvarchar](100),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rCode [nvarchar](100),
	@rOrganizationDepartmentId [int],
	@rOrgId int,
	@rStoreLocationId int,
	@rCustodianEmployeeId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF NOT EXISTS (SELECT 1 FROM sCommon.tFirstAidMaster WHERE UPPER(Code) = UPPER(@rCode) AND OrganizationDepartmentId = @rOrganizationDepartmentId AND Id  <> @rId AND OrgId = @rOrgId )
BEGIN

	 UPDATE sCommon.tFirstAidMaster
		SET 
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			Code = @rCode,
			OrganizationDepartmentId = @rOrganizationDepartmentId,
			StoreLocationId = @rStoreLocationId,
			CustodianEmployeeId=@rCustodianEmployeeId
	  WHERE Id = @rId AND OrgId = @rOrgId
	  
	  
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFirstAidMasterRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tFirstAidMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFrequencyMasterAdd]
	@rCode [nvarchar](10),
	@rTitle [nvarchar](50),
	@rIsShow [bit],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lId BIGINT

SET @lId = (SELECT ID FROM sCommon.tFrequencyMaster WHERE Title = @rTitle)

IF (ISNULL(@lId, 0) = 0)
BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 'sCommon.tFrequencyMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tFrequencyMaster
		(
			Id,
			Code,
			Title,
			--IsShow,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			--@rIsShow,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		SET @lId = @lNextNumber
END
SELECT @lId AS ID

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFrequencyMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			---IsShow,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sCommon.tFrequencyMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pFrequencyMasterModify]
	@rId [smallint],
	@rCode [nvarchar](10),
	@rTitle [nvarchar](50),
	@rIsShow [bit],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tFrequencyMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			--IsShow = @rIsShow,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pGenderMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			TitleResourceKeyId
	   FROM sCommon.tGenderMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pGeneralMasterCheckCode]  
 @rCode [nvarchar](100),  
 @rCodeField [nvarchar](100),  
 @rTableName [nvarchar](100),  
 @rIdField [nvarchar](100),  
 @rVisibilityField nvarchar(100) = '',  
 @rVisibilityId    nvarchar(10) = '0'   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON   
  
BEGIN   
  
    DECLARE @lSelectClause Nvarchar(2000)  
    DECLARE @lId Nvarchar(20)  
 SET @lId = '0'  
  
 SET @lSelectClause = 'SELECT SUM(Id) AS Result  
        FROM(SELECT ' + @rIdField + ' Id, 0 Cnt  
         FROM ' + @rTableName + '  
           WHERE ' + @rCodeField + ' = N''' + @rCode + ''''                              -- Unicode compatibility By Krishna
           + ' AND ' + @rVisibilityField + '  = ''' + @rVisibilityId +'''  
           UNION ALL  
          SELECT 0 Id, COUNT(' + @rIdField + ') Cnt  
         FROM ' + @rTableName + '   
           WHERE ' + @rCodeField + ' = N''' + @rCode + ''''                              -- Unicode compatibility By Krishna  
           + ' AND ' + @rVisibilityField + '  = ''' + @rVisibilityId +'''  
       ) AS TBL1'  
  
--SELECT @lSelectClause  
 EXECUTE sp_executesql @lSelectClause        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pGeneralMasterCheckDescription]  
 @rDescription [nvarchar](50),  
 @rDescriptionField [nvarchar](50),  
 @rTableName [nvarchar](50),  
 @rIdField [nvarchar](50),  
 @rId [nvarchar](20),  
 @rVisibilityField nvarchar(100) = '',  
 @rVisibilityId    nvarchar(10) = '0'   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON   
  
  
  
BEGIN   
  
    DECLARE @lSelectClause Nvarchar(2000)  
    DECLARE @lId Nvarchar(20)  
 SET @lId = '0'  
   
  
 SET @lSelectClause = 'SELECT SUM(Id) AS Result  
        FROM(SELECT ' + @rIdField + ' Id, 0 Cnt  
         FROM ' + @rTableName + '  
           WHERE ' + @rDescriptionField + ' = N''' + @rDescription + ''''  -- Unicode compatibility By Krishna
          + ' AND ' + @rIdField + ' ! = ''' + @rId + ''''  
          + ' AND ' + @rVisibilityField + '  = ''' + @rVisibilityId +'''  
           UNION ALL  
          SELECT 0 Id, COUNT(' + @rIdField + ') Cnt  
         FROM ' + @rTableName + '   
            WHERE ' + @rDescriptionField + ' = N''' + @rDescription + ''''  -- Unicode compatibility By Krishna
         + ' AND ' + @rIdField + ' ! = ''' + @rId  + ''''  
         + ' AND ' + @rVisibilityField + '  = ''' + @rVisibilityId +'''  
       ) AS TBL1'  
         
         
         
  --SET @lSelectClause = 'SELECT ' + @rIdField + ' AS Result  
  --       FROM ' + @rTableName + '  
  --         WHERE ' + @rDescriptionField + ' = ''' + @rDescription + ''''  
  --        + ' AND ' + @rIdField + ' ! = ''' + @rId + ''''      
        
print @lSelectClause  
--SELECT @lSelectClause  
 EXECUTE sp_executesql @lSelectClause     
   
END  
--BEGIN   
  
--    DECLARE @lSelectClause Nvarchar(2000)  
--    DECLARE @lId Nvarchar(20)  
-- SET @lId = '0'  
  
-- SET @lSelectClause = 'SELECT SUM(Id) AS Result  
--        FROM(SELECT ' + @rIdField + ' Id, 0 Cnt  
--         FROM ' + @rTableName + '  
--           WHERE ' + @rDescriptionField + ' = ' + @rDescription + '' + 'AND' +  
--                      @rIdField + ' ! = ' + @rId + '  
--           UNION ALL  
--          SELECT 0 Id, COUNT(' + @rIdField + ') Cnt  
--         FROM ' + @rTableName + '   
--           WHERE ' + @rDescriptionField + ' = ' + @rDescription + '' + 'AND' +  
--            @rIdField + ' ! = ''' + @rId + '''  
--       ) AS TBL1'  
  
----SELECT @lSelectClause  
-- EXECUTE sp_executesql @lSelectClause        
--END  

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pGeneralMasterDataWithValueModify]
	@rTableName [nvarchar](100),
	@rIDField [nvarchar](100),
	@rCodeField [nvarchar](100),
	@rRemarkField [nvarchar](100),
	@rId [int],
	@rCode [nvarchar](100),
	@rRemark [nvarchar](100),
	@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(100),@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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pGeneralmasterGetCodeAndDescription]
	  --@rOrgId		     Nvarchar(20),	
	  @rTableName		 Nvarchar(100),
	  @rIsStatic1To100	 bit,
	  @rCodeField		 Nvarchar(100) = '',
	  @rCode			 Nvarchar(100) = '',
	  @rRemarkField	     Nvarchar(100) = '',
	  @rVisibilityField nvarchar(100) = '',
	  @rVisibilityId    nvarchar(10) = '0'
	 
 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--	DECLARE @lIsStatic int = 0

--IF ( @rTableName = 'sIp.tItemMainGroupMaster' or @rTableName = 'sIp.tStoreLocationMaster' or @rTableName = 'sHrm.tEmployeeJobTitleMaster' or @rTableName =  'sOrderEntry.tServiceItemTypeMaster')
--SET @lIsStatic = 1
--ELSE
--SET @lIsStatic = 0

	DECLARE @lSelectClause Nvarchar(2000)	 
     
  --   IF ( @rIsStatic1To100 = 1)
  --   BEGIN
  --      SET @lSelectClause =   'SELECT  ' + @rRemarkField + '  AS Result, ' + @rCodeField + ' AS ResultCode ' + ', Id, 0 AS StaticId, IsObsolete  FROM  ' + @rTableName + 
		--								' WHERE ' +  @rCodeField + ' LIKE '''+'%'+ @rCode +'%'+ '''  AND OrgId = ' + @rOrgId +  '' 
	 --END
	 --ELSE
	 BEGIN
        SET @lSelectClause =   'SELECT  ' + @rRemarkField + '  AS Result, ' + @rCodeField + ' AS ResultCode ' + ', Id, 0 As StaticId,  IsObsolete  FROM  ' + @rTableName + 
										' WHERE ' +  @rCodeField + ' = N''' + @rCode + ''' 
											AND     ((' + @rVisibilityField  + ' = ' + CAST(@rVisibilityId AS NVARCHAR(30)) + ') OR (' + CAST(@rVisibilityId AS NVARCHAR(30)) + ' = 0))' 
	 
	 END
				
	--SELECT @lSelectClause
	EXECUTE sp_executesql @lSelectClause
	



END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pGeneralMasterListGet]
	--@rOrgId nvarchar(20),	
	@rIdField nvarchar(20),
	@rCodeField nvarchar(20),
	@rRemarkField nvarchar(20),
	@rTableName nvarchar(200),
	@rId nvarchar(10) = '0',	 
	@rCode [nvarchar](100) = '*',
	@rRemark [nvarchar](500) = '*',
	@rVisibilityField nvarchar(100),
	@rVisibilityId nvarchar(10) = '0'
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rRemark = sCommon.fSearchStringGet(@rRemark)

--DECLARE @lId	Nvarchar(200)
--DECLARE @lCode	Nvarchar(200)
 
--DECLARE @lTitle Nvarchar(200)
 
--DECLARE @lTableName Nvarchar(200)
DECLARE @lQueryString Nvarchar(MAX)



--SELECT	@lId		= IdField, 
	 
--		@lCode		= CodeField, 
--		@lTitle 	= RemarkField, 
		 
--		@lTableName =  TableTitle 
--FROM	sCommon.tCommonMaster 
--WHERE	Id = @rScreenId



SET @lQueryString = 'SELECT'
SET @lQueryString = @lQueryString + ' ' + @rIdField + '  AS Id ' + ', ' + @rCodeField + '  AS Code ' + ', ' + @rRemarkField  + ' AS Remark,' + 'IsObsolete' + ' FROM ' + @rTableName

--select @lQueryString

SET @lQueryString = @lQueryString + ' ' + 'WHERE	((' + @rIdField + ' = ' + CAST(@rId AS NVARCHAR(30)) + ') OR (' + CAST(@rId AS NVARCHAR(30)) + ' = 0))
											AND		((' + @rCodeField + ' LIKE '''+ @rCode +'%'+ ''') OR (''' + ISNULL(@rCode, '') + ''' = ''''))
											AND		((' + @rRemarkField + ' LIKE '''+ @rRemark +'%'+ ''') OR (''' + ISNULL(@rRemark, '') + ''' = ''''))
											AND     ((' + @rVisibilityField + ' = ' + CAST(@rVisibilityId AS NVARCHAR(30)) + ') OR (' + CAST(@rVisibilityId AS NVARCHAR(30)) + ' = 0))'
										

--select @lQueryString
--EXEC(@lQueryString)
EXECUTE sp_executesql @lQueryString

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pGeneralMasterNumaricCheckDescription]
	@rDescription [nvarchar](50),
	@rDescriptionField [nvarchar](50),
	@rTableName [nvarchar](50),
	@rIdField [nvarchar](50),
	@rId [nvarchar](20),
	@rVisibilityField nvarchar(100) = '',
	@rVisibilityId    nvarchar(10) = '0' 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 



BEGIN 

    DECLARE @lSelectClause Nvarchar(2000)
    DECLARE @lId Nvarchar(20)
	SET @lId = '0'
	

	SET @lSelectClause = 'SELECT SUM(Id) AS Result
							 FROM(SELECT ' + @rIdField + ' Id, 0 Cnt
									FROM ' + @rTableName + '
								   WHERE ' + @rDescriptionField + ' = ''' + @rDescription + ''''
								  + ' AND ' + @rIdField + '  = ' + @rId +''''
								  + ' AND ' + @rVisibilityField + '  = ''' + @rVisibilityId +'''
								   UNION ALL
								  SELECT 0 Id, COUNT(' + @rIdField + ') Cnt
									FROM ' + @rTableName + ' 
								   WHERE ' + @rDescriptionField + ' = ''' + @rDescription + ''''
								 + ' AND ' + @rIdField + '  = ' + @rId +''''
								 + ' AND ' + @rVisibilityField + '  = ''' + @rVisibilityId +'''
							) AS TBL1'
							
							
							
		--SET @lSelectClause =	'SELECT ' + @rIdField + ' AS Result
		--							FROM ' + @rTableName + '
		--						   WHERE ' + @rDescriptionField + ' = ''' + @rDescription + ''''
		--						  + ' AND ' + @rIdField + ' ! = ''' + @rId + ''''				
						
print @lSelectClause
--SELECT @lSelectClause
	EXECUTE sp_executesql @lSelectClause   
	
END
--BEGIN 

--    DECLARE @lSelectClause Nvarchar(2000)
--    DECLARE @lId Nvarchar(20)
--	SET @lId = '0'

--	SET @lSelectClause = 'SELECT SUM(Id) AS Result
--							 FROM(SELECT ' + @rIdField + ' Id, 0 Cnt
--									FROM ' + @rTableName + '
--								   WHERE ' + @rDescriptionField + ' = ' + @rDescription + '' + 'AND' +
--								              @rIdField + ' ! = ' + @rId + '
--								   UNION ALL
--								  SELECT 0 Id, COUNT(' + @rIdField + ') Cnt
--									FROM ' + @rTableName + ' 
--								   WHERE ' + @rDescriptionField + ' = ' + @rDescription + '' + 'AND' +
--								    @rIdField + ' ! = ''' + @rId + '''
--							) AS TBL1'

----SELECT @lSelectClause
--	EXECUTE sp_executesql @lSelectClause      
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pGeneralMasterWithValueAdd]  
 @rTableName [nvarchar](100),  
 @rCodeField [nvarchar](100),  
 @rRemarkField [nvarchar](100),  
 @rCode [nvarchar](50),  
 @rRemark [nvarchar](100),  
 @rIsObsolete [nvarchar](10),  
 @rCreatedUserId [bigint],  
 @rIsStatic1to100 [bit],  
 @rOrgId int,  
 @rVisibilityField nvarchar(100),  
 @rVisibilityId int  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON   
BEGIN  
  
 --DECLARE @lSelectClause Nvarchar(2000)  
 --DECLARE @lNextNumber BIGINT  
 --EXECUTE @lNextNumber = sCommon.pTableRowIdGet @rTableName, 0, 1, 1  
 DECLARE @lSelectClause Nvarchar(2000)  
 DECLARE @lIsShow Nchar(1)  
 DECLARE @lNextNumber BigInt  
 DECLARE @lSchemaName Nvarchar(50)  
 DECLARE @lTableName Nvarchar(100)  
 DECLARE @lSeed int  
   
 SET @lSeed = (CASE WHEN @rIsStatic1to100 = 1 THEN 101 ELSE 1 END)  
 EXECUTE  sCommon.pTableRowIdGet  @rOrgId,@rTableName, 0, @lSeed, 1,@outNextNumber = @lNextNumber output  
 SET @lNextNumber = @lNextNumber  
 SET @lIsShow = '0'  
 SET @lSchemaName = SUBSTRING(@rTableName, 1, CHARINDEX('.', @rTableName, 1) - 1)  
 SET @lTableName =  SUBSTRING(@rTableName, CHARINDEX('.', @rTableName, 1) + 1, LEN(@rTableName))  
       
 --SELECT @lSchemaName, @lTableName  
   
 SET @lSelectClause =     'IF EXISTS(SELECT ' + @rRemarkField + ' FROM ' + @rTableName +   
          ' WHERE ' +  @rRemarkField + ' = N''' + @rRemark + ''' AND                                 -- Unicode compatibility By Krishna
            ' +  @rVisibilityField + ' = ' + CONVERT(NVARCHAR(20), @rVisibilityId) + ')   
            BEGIN  
         SELECT -102 AS Result  
         RETURN  
        END ' +   
          'INSERT INTO ' + @rTableName   
          + '(Id, ' + @rCodeField   
             + ', ' + @rRemarkField   
             + ', ' + ' UpdatedUserId '   
             + ', ' + ' UpdatedDateTime '   
             + ', ' + ' CreatedUserId '   
             + ', ' + ' CreatedDateTime '   
                                           + ', ' + 'IsObsolete' +                                           
                                           --+' , ' +  'StoreLocationId' +  
                                          ', ' + @rVisibilityField +  
                 
          ')  
                               VALUES(' + CAST(@lNextNumber AS NVARCHAR(15)) + ', N''' + @rCode + ''', N'''   
                 + @rRemark +  ''', '''  
                                           + CONVERT(NVARCHAR(25), @rCreatedUserId) + ''', '''   
             + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', '''  
                                           + CONVERT(NVARCHAR(25), @rCreatedUserId) + ''', '''   
             + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', ''' + @rIsObsolete + ''','''               
             + CONVERT(NVARCHAR(20), @rVisibilityId)   
             
         + ''')  
           
        SELECT 1 AS Result'     
   
           
           
  PRINT @lSelectClause  
 EXECUTE sp_executesql @lSelectClause  
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pGetIntMaxIdForOrgGroup]
	@rOrgGroupId int,
	@rTableName nvarchar(100),
	@lNextNumber bigint OUTPUT  
WITH EXECUTE AS CALLER
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @rSql nvarchar(max)
	
	 SET @rSql = 'SELECT @lNextNumber=ISNULL(MAX(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@rOrgGroupId))+''00000'')) + 1
	 FROM '+@rTableName+' WHERE OrgGroupId=Convert(nvarchar(10),@rOrgGroupId)'
	 EXECUTE sp_executesql @rSql, N'@rOrgGroupId int,@lNextNumber bigint OUTPUT',
	 @rOrgGroupId=@rOrgGroupId,@lNextNumber=@lNextNumber OUTPUT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pGetIntMaxIdForOrgGroupBatch]
	@rOrgGroupId int,
	@rTableName nvarchar(100),
	@lNextNumber bigint OUTPUT  
WITH EXECUTE AS CALLER
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @rSql nvarchar(max)
	
	SET @rSql = 'SELECT @lNextNumber=ISNULL(MAX(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@rOrgGroupId))+''00000'')) + 1
	 FROM '+@rTableName+' WHERE OrgGroupBatchId=Convert(nvarchar(10),@rOrgGroupId)'
		EXECUTE sp_executesql @rSql, N'@rOrgGroupId int,@lNextNumber int OUTPUT',
									@rOrgGroupId=@rOrgGroupId,@lNextNumber=@lNextNumber OUTPUT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pIdProofTypeMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			TitleResourceKeyId
	   FROM sCommon.tIdProofTypeMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pLocationMasterAdd]
	
	@rCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rStreetOne [nvarchar](50),
	@rStreetTwo [nvarchar](50),
	@rStreetThree [nvarchar](50),
	@rCityName [nvarchar](100),
	@rStateName [nvarchar](100),
	@rCountryName [nvarchar](100),
	@rZipCode [nvarchar](20),
	@rPhoneNo [nvarchar](50),
    @rFaxNo [nvarchar](50),
    @rNameOfOccupier nvarchar(50),
    @rAddressOfOccupier nvarchar(200),
    @rSmallAddress1 [nvarchar](100),
    @rSmallAddress2 [nvarchar](100),
    @rRegistrationNumber [nvarchar](50),
    @rLicenceNumber [nvarchar](50),
    @rEsicNumber [nvarchar](50),
    @rEsicAddress1 [nvarchar](100),
    @rEsicAddress2 [nvarchar](100),
    @rNatureOfIndustry [nvarchar](100),
    @rByProduct [nvarchar](100),
    @rDangerousOperation [nvarchar](100),
    @rNatureOfTest [nvarchar](100),
    @rRowMaterialUsed [nvarchar](100),
    @rHazardousProcess [nvarchar](100),
    @rCmo [nvarchar](50),
    @rNicNumber [nvarchar](50),
    @rIsObsolete [bit],
    @rOrgid [int],
    @rCreatedUserId [bigint],
    @rUpdatedUserId [bigint],
    @rCountryId int,
    @rStateId int,
    @rNatureofTestNonHazardous [nvarchar](100)

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sCommon.tLocationMaster WHERE UPPER(Title) = UPPER(@rTitle) AND  OrgId = @rOrgId)

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

  print @lNextNumber

	INSERT INTO sCommon.tLocationMaster
		(			
           Id,
           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
           ,OrgId
           ,CreatedUserId
           ,[UpdatedUserId]
           ,CreatedDateTime
           ,UpdatedDateTime
           ,CountryId
           ,StateId
          
           )
		
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,	
			@rStreetOne,
			@rStreetTwo,
			@rStreetThree,
			@rCityName,
			@rStateName,
			@rCountryName,
			@rZipCode,
			@rPhoneNo,
			@rNameOfOccupier,
			@rAddressOfOccupier,
			@rFaxNo,
			@rSmallAddress1,
			@rSmallAddress2,
			@rRegistrationNumber,
			@rLicenceNumber,			
			@rEsicNumber,
			@rEsicAddress1,
			@rEsicAddress2,
			@rNatureOfIndustry,
			@rByProduct,
			@rDangerousOperation,
			@rNatureOfTest,
			@rNatureofTestNonHazardous,
			@rRowMaterialUsed,
			@rHazardousProcess,
			@rCmo,
			@rNicNumber,
			@rIsObsolete,
			@rOrgId,
			@rCreatedUserId,
			@rUpdatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate(),
			@rCountryId,
			@rStateId			
		)
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pLocationMasterGet]
	@rId [int] = 0,
	@rTitle [nvarchar](20) = '',
	@rCode [nvarchar](20) = '',
	@rOrgId int,
	@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	IF @rIsWildCardSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
		END
		
	


	SELECT LM.[Id]    
      ,LM.[Code]
      ,LM.[Title]
      ,LM.[StreetOne]
      ,LM.[StreetTwo]
      ,LM.[StreetThree]
      ,LM.[CityName]
      ,LM.[StateName]
      ,LM.[CountryName]
      ,LM.[ZipCode]
      ,LM.[PhoneNo]
      ,LM.NameOfOccupier
      ,LM.AddressOfOccupier
      ,LM.[FaxNo]
      ,LM.[SmallAddress1]
      ,LM.[SmallAddress2]
      ,LM.[RegistrationNumber]
      ,LM.[LicenceNumber]
      ,LM.[EsicNumber]
      ,LM.[EsicAddress1]
      ,LM.[EsicAddress2]
      ,LM.[NatureOfIndustry]
      ,LM.[ByProduct]
      ,LM.[DangerousOperation]
      ,LM.[NatureOfTest]
      ,LM.[NatureOfTestNonHazardous]
      ,LM.[RowMaterialUsed]
      ,LM.[HazardousProcess]
      ,LM.[Cmo]
      ,LM.[NicNumber]
      ,LM.[IsObsolete]
      ,LM.CountryId
      ,LM.StateId
      ,LM.OrgId
      ,OM.Title AS OrgName
      

  FROM [sCommon].[tLocationMaster] LM
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LM.OrgId
	   
	  WHERE ((LM.Id = @rId) OR (@rId = 0))
	   AND ((LM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((LM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))	   
	   AND ((LM.OrgId = @rOrgId) OR (@rOrgId = 0))
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pLocationMasterModify]
	@rId [int],	
	@rTitle [nvarchar](100),
	@rCode [nvarchar](20),
	@rNameOfOccupier nvarchar(50),
    @rAddressOfOccupier nvarchar(200),
	@rStreetOne [nvarchar](50),
	@rStreetTwo [nvarchar](50),
	@rStreetThree [nvarchar](50),
	@rCityName [nvarchar](100),
	@rStateName [nvarchar](100),
	@rCountryName [nvarchar](100),
	@rZipCode [nvarchar](20),
	@rPhoneNo [nvarchar](50),
    @rFaxNo [nvarchar](50),
    @rSmallAddress1 [nvarchar](100),
    @rSmallAddress2 [nvarchar](100),
    @rRegistrationNumber [nvarchar](50),
    @rLicenceNumber [nvarchar](50),
    @rEsicNumber [nvarchar](50),
    @rEsicAddress1 [nvarchar](100),
    @rEsicAddress2 [nvarchar](100),
    @rNatureOfIndustry [nvarchar](100),
    @rByProduct [nvarchar](100),
    @rDangerousOperation [nvarchar](100),
    @rNatureOfTest [nvarchar](100),
    @rRowMaterialUsed [nvarchar](100),
    @rHazardousProcess [nvarchar](100),
    @rCmo [nvarchar](50),
    @rNicNumber [nvarchar](50),
    @rIsObsolete [bit],
    @rOrgid [int],
    @rCreatedUserId [bigint],
    @rUpdatedUserId [bigint],
    @rCountryId int,
    @rStateId int,
    @rNatureofTestNonHazardous [nvarchar](100)
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF NOT EXISTS (SELECT 1 FROM sCommon.tLocationMaster WHERE UPPER(Title) = UPPER(@rTitle) AND  Id  <> @rId AND OrgId = @rOrgId )
BEGIN

	 UPDATE sCommon.tLocationMaster
		SET 
			Title = @rTitle,
			Code = @rCode,
			IsObsolete = @rIsObsolete,			 
			StreetOne = @rStreetOne,
           StreetTwo = @rStreetTwo,
           StreetThree = @rStreetThree,
           CityName =@rCityName,
           StateName =@rStateName,
           CountryName =@rCountryName,
           ZipCode = @rZipCode
           ,PhoneNo=@rPhoneNo
           ,NameOfOccupier=@rNameOfOccupier
           ,AddressOfOccupier=@rAddressOfOccupier
           ,FaxNo=@rFaxNo
           ,SmallAddress1  = @rSmallAddress1
           ,SmallAddress2 = @rSmallAddress2
           ,RegistrationNumber =@rRegistrationNumber
           ,LicenceNumber = @rLicenceNumber
           ,EsicNumber=@rEsicNumber
           ,EsicAddress1 = @rEsicAddress1
          ,EsicAddress2 = @rEsicAddress2
           ,NatureOfIndustry= @rNatureOfIndustry
           ,ByProduct= @rByProduct
           ,DangerousOperation = @rDangerousOperation
           ,NatureOfTest= @rNatureOfTest
           ,NatureOfTestNonHazardous=@rNatureofTestNonHazardous
           ,RowMaterialUsed= @rRowMaterialUsed
           ,HazardousProcess= @rHazardousProcess
           ,Cmo= @rCmo
           ,NicNumber= @rNicNumber
           ,CountryId = @rCountryId
           ,StateId = @rStateId
			
			
	  WHERE Id = @rId AND OrgId = @rOrgId
	  
	  
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pLocationMasterRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 DELETE FROM sCommon.tLocationMaster
	      
	  WHERE Id = @rId
	  
	  SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pMaritalStatusMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			TitleResourceKeyId
	   FROM sCommon.tMaritalStatusMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pMasterDataAdd]
	 
        
		@rTitle nvarchar(100)='',
		@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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE OR ALTER PROCEDURE [sCommon].[pMaxAdmissionInquiryNumberWithPrefixGet]
	 
	 @rPrefixFunctionalityId smallint,
	 @rOrgId smallint,
	 @rOrgGroupId int,
	 @rOrgGroupBatchId int=0,
	 @rBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
BEGIN TRY
	
	DECLARE @lSourceTypeId int
	DECLARE @lOutCode nvarchar(20)
	DECLARE @lPrefix nvarchar(10)
	DECLARE @lNumberLength tinyint
	
	DECLARE @lOrgGroupBatchId int=0
	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster BM WHERE BM.Id = @rBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	IF @rPrefixFunctionalityId=2013 -- Admission Inquiry
	BEGIN
		SELECT @lSourceTypeId=SourceTypeId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND OrgId =@rOrgId
		IF @lSourceTypeId IS NOT NULL
		BEGIN
			IF @lSourceTypeId = 2021 -- Organization
			BEGIN
				SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
			END

			IF(@lConfigValue='OrgGroupBatch')
			BEGIN
				SELECT @lOutCode = (MAX(Number)) FROM sAdmission.tAdmissionInquiry AI
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
				WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId AND Number LIKE @lPrefix+'%'
			END
			ELSE IF(@lConfigValue='Batch')
			BEGIN
				SELECT @lOutCode = MAX(Number) FROM sAdmission.tAdmissionInquiry AI
				WHERE AI.ForBatchId = @rBatchId AND Number LIKE @lPrefix+'%'
			END
			ELSE IF (@lConfigValue = 'Continuous')
			BEGIN
				SELECT @lOutCode =MAX(Number) FROM sAdmission.tAdmissionInquiry  
				WHERE OrgGroupId = @rOrgGroupId AND Number LIKE @lPrefix+'%'
			END

			IF CHARINDEX(@lPrefix,@lOutCode) > 0
			BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			ELSE
			BEGIN
				SELECT @lOutCode = 1
				IF @lNumberLength != 0
				BEGIN
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
				END
				SELECT @lOutCode = @lPrefix + @lOutCode
			END
		END
		ELSE 
		BEGIN
			IF(@lConfigValue='OrgGroupBatch')
			BEGIN
				SELECT @lOutCode = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
				WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId 
			END
			ELSE IF(@lConfigValue='Batch')
			BEGIN
				SELECT @lOutCode = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI
				WHERE AI.ForBatchId = @rBatchId
			END
			ELSE IF (@lConfigValue = 'Continuous')
			BEGIN
				SELECT @lOutCode = (ISNULL(MAX(InquiryNumber),0) + 1) FROM sAdmission.tAdmissionInquiry AI 
				WHERE OrgGroupId = @rOrgGroupId 
			END
		END
	END
	
	END TRY
	BEGIN CATCH
		SET @lOutCode = ''
	END CATCH
	
	SELECT @lOutCode Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommon].[pMaxCodeWithPrefixGet]
	 
	 @rPrefixFunctionalityId smallint,
	 @rOrgId smallint,
	 @rDepartmentId int,
	 @rEmployeeTypeId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
BEGIN TRY
	
	DECLARE @lSourceTypeId int
	DECLARE @lOutCode nvarchar(20)
	DECLARE @lPrefix nvarchar(10)
	DECLARE @lNumberLength tinyint
	
	IF @rPrefixFunctionalityId=2007 -- Student
	BEGIN
	--select 111
		SELECT @lSourceTypeId=SourceTypeId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND OrgId =@rOrgId
			IF @lSourceTypeId IS NOT NULL
			BEGIN
				IF @lSourceTypeId = 2021 -- Organization
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
					SELECT @lOutCode=MAX(Code) FROM sStudent.tStudentMaster WHERE OrgId = @rOrgId
				END
				IF @lSourceTypeId = 2017 -- Department
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rDepartmentId
					SELECT @lOutCode=MAX(SM.Code) FROM sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId WHERE SM.OrgId = @rOrgId AND CM.DepartmentId = @rDepartmentId
				END
				
				IF CHARINDEX(@lPrefix,@lOutCode) > 0
				BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
				ELSE
				BEGIN
					SELECT @lOutCode = 1
					IF @lNumberLength != 0
					BEGIN
						SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					END
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			END
	END
	IF @rPrefixFunctionalityId=2008 -- Employee
	BEGIN
		SELECT @lSourceTypeId=SourceTypeId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND OrgId =@rOrgId
			IF @lSourceTypeId IS NOT NULL
			BEGIN
				IF @lSourceTypeId = 2021 -- Organization
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
					SELECT @lOutCode=MAX(Code) FROM sHrm.tEmployeeMaster WHERE OrgId = @rOrgId AND ISNULL(IsOtherUser,0) = 0
				END
				
				IF @lSourceTypeId = 2017 -- Department
				BEGIN
					SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rDepartmentId
					SELECT @lOutCode=MAX(EM.Code) FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
					WHERE EM.OrgId = @rOrgId AND EJD.OrganizationDepartmentId = @rDepartmentId AND ISNULL(EM.IsOtherUser,0) = 0
				END
				
				IF CHARINDEX(@lPrefix,@lOutCode) > 0
				BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
				ELSE
				BEGIN
					SELECT @lOutCode = 1
					IF @lNumberLength != 0
					BEGIN
						SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					END
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			END
	END
	
	IF @rPrefixFunctionalityId=2009 -- Organization
	BEGIN
		DECLARE @lOrgGroupId smallint
		DECLARE @lScopeSourceTypeId smallint
		SELECT @lSourceTypeId=SourceTypeId,@lScopeSourceTypeId=ISNULL(ScopeSourceTypeId,0),@lOrgGroupId=OrgId FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId =@rOrgId
			IF @lSourceTypeId IS NOT NULL
			BEGIN
				IF @lSourceTypeId = 2021 -- Organization
				BEGIN
					IF(@lScopeSourceTypeId=2010)
						BEGIN
							SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
							SELECT @lOutCode=MAX(SUId) FROM sStudent.tStudentMaster SM
							INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
							 WHERE OM.OrgGroupId = @lOrgGroupId
						END
					ELSE
						BEGIN
							SELECT @lPrefix=Prefix,@lNumberLength=NumberLength FROM sCommon.tPrefixConfig WHERE PrefixFunctionalityId = @rPrefixFunctionalityId AND SourceId = @rOrgId
							SELECT @lOutCode=MAX(SUId) FROM sStudent.tStudentMaster WHERE OrgId = @rOrgId
						END	
				END
				
				IF CHARINDEX(@lPrefix,@lOutCode) > 0
				BEGIN
					SELECT @lOutCode = RIGHT(@lOutCode, LEN(@lOutCode)-LEN(@lPrefix))
					SELECT @lOutCode = (CONVERT(bigint, @lOutCode)+1)
					SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
				ELSE
				BEGIN
					SELECT @lOutCode = 1
					IF @lNumberLength != 0
					BEGIN
						SELECT @lOutCode = RIGHT(REPLICATE('0', @lNumberLength), @lNumberLength-LEN(@lPrefix)-LEN(@lOutCode))+@lOutCode
					END
					SELECT @lOutCode = @lPrefix + @lOutCode
				END
			END
	END
	END TRY
	BEGIN CATCH
	SET @lOutCode = ''
	END CATCH
	SELECT @lOutCode Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pModuleMasterGet]
	@rId [tinyint] = 0,
	@rTypeId [tinyint] = 0,
	@rOrgGroupId smallint=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT Id,
		Title
		--Remark,
		--TypeId,
		--IsObsolete
	FROM sCommon.tModuleMaster MM
		INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = MM.Id AND MP.OrgGroupId = @rOrgGroupId
	WHERE (Id = @rId OR @rId = 0)
		AND (ModuleTypeId = @rTypeId OR @rTypeId = 0)
		--AND (IsObsolete = 0) 
	ORDER BY Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pNumberOrderIndexGet]
          
           
           @rTableName nvarchar(100),
           @rScopeTypeId int,
           @rScope nvarchar(100),
           @rScopeId bigint
          
 
AS
SET NOCOUNT ON

BEGIN

 --ScopeTypeId = 1 Number and OrderIndex
 --ScopeTypeId = 2 Number
 --ScopeTypeId = 3 OrderIndex
  
 
DECLARE @lNumber as bigint
DECLARE @lOrderIndex as bigint
DECLARE @lNumberString as nvarchar(1000)
 DECLARE @lOrderIndexString as nvarchar(1000)

 SET @lNumberString = 'SELECT @lNumber = max(Number) + 1 FROM ' +  @rTableName + ' WHERE ' + @rScope  + ' = ' +  CONVERT(NVARCHAR(20), @rScopeId) 
SET @lOrderIndexString = 'SELECT @lOrderIndex = max(OrderIndex) + 1 FROM ' +  @rTableName + ' WHERE ' + @rScope + ' = ' +  CONVERT(NVARCHAR(20), @rScopeId) 

If @rScopeTypeId = 1
BEGIN
 EXECUTE sp_executesql @lNumberString,N' @lNumber bigint Output', @lNumber output
 EXECUTE sp_executesql @lOrderIndexString,N' @lOrderIndex bigint Output', @lOrderIndex output
END
ELSE IF  @rScopeTypeId = 2
BEGIN
 EXECUTE sp_executesql @lNumberString,N' @lNumber bigint Output', @lNumber output
 
END
 ELSE IF  @rScopeTypeId = 3
BEGIN
 
 EXECUTE sp_executesql @lOrderIndexString,N' @lOrderIndex bigint Output', @lOrderIndex output
END


--declare @dynsql varchar(500)   
--declare @params nvarchar(500)
--declare @salary money
--declare @username varchar(50)
--@dynsql='Select @sal=Salary,@usernm=Username from employee where EmployeeId=@empID'   
--@params='@empID int, @sal money OUTPUT, @usernm varchar(50) OUTPUT'
--exec sp_executesql @dynsql, @params, @empID=@EmployeeID, @sal=@salary OUTPUT, @usernm = @username OUTPUT
--SELECT @salary, @username

SELECT ISNULL(@lNumber,1) AS Number,ISNULL(@lOrderIndex,1) AS OrderIndex

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationDepartmentGroupMasterAdd]
	@rTitle [nvarchar](50),
	@rTitleResourceKeyId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet 'sCommon.tOrganizationDepartmentGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tOrganizationDepartmentGroupMaster
		(
			Id,
			Title,
			TitleResourceKeyId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rTitleResourceKeyId
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationDepartmentGroupMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			TitleResourceKeyId
	   FROM sCommon.tOrganizationDepartmentGroupMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationDepartmentGroupMasterModify]
	@rId [smallint],
	@rTitle [nvarchar](50),
	@rTitleResourceKeyId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tOrganizationDepartmentGroupMaster
		SET 
			Title = @rTitle,
			TitleResourceKeyId = @rTitleResourceKeyId
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationDepartmentMappingAdd]
	@rOrganizationDepartmentGroupId [smallint],
	@rOrganizationDepartmentId [smallint],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	IF NOT EXISTS (SELECT 1 FROM sCommon.tOrganizationDepartmentMapping WHERE OrganizationDepartmentId = @rOrganizationDepartmentId )

	BEGIN

		DECLARE @lNextNumber INT
		EXECUTE  sCommon.pTableRowIdGet 'sCommon.tOrganizationDepartmentMapping', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sCommon.tOrganizationDepartmentMapping
			(
				Id,
				OrganizationDepartmentGroupId,
				OrganizationDepartmentId,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime
			)
		VALUES
			(
				@lNextNumber,
				@rOrganizationDepartmentGroupId,
				@rOrganizationDepartmentId,
				@rIsObsolete,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate()
			)
	SELECT 1 AS RESULT
	END
	ELSE
	BEGIN
	 SELECT -100 AS RESULT
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationDepartmentMappingGet]
	@rId [int] = 0,
	@rOrganizationDepartmentId [int] = 0,
	@rOrganizationDepartmentGroupId [int] = 0,
	@rOrganizationDepartmentTitle [nvarchar](100) = '',
	@rOrganizationDepartmentGroupTitle [nvarchar](100) = '',
	@rIsWildCardSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	IF @rIsWildCardSearch = 1
	BEGIN
		  SET @rOrganizationDepartmentTitle = sCommon.fSearchStringGet(@rOrganizationDepartmentTitle)
		  SET @rOrganizationDepartmentGroupTitle = sCommon.fSearchStringGet(@rOrganizationDepartmentGroupTitle)
	END

	SELECT ORDPMAP.Id,
			ORDPM.Id		AS OrganizationDepartmentId,
			ORDPM.Title		AS OrganizationDepartmentTitle,
			''		AS OrganizationDepartmentCode,
			ORDPGRM.Id		AS OrganizationDepartmentGroupId,
			ORDPGRM.Title	AS OrganizationDepartmentGroupTitle,
			ORDPMAP.IsObsolete,
			ORDPMAP.CreatedUserId,
			ORDPMAP.CreatedDateTime,
			ORDPMAP.UpdatedUserId,
			ORDPMAP.UpdatedDateTime			

	FROM sCommon.tOrganizationDepartmentMapping ORDPMAP
	INNER JOIN sSetup.tDepartmentMaster ORDPM
	ON ORDPMAP.OrganizationDepartmentId = ORDPM.Id
	INNER JOIN sCommon.tOrganizationDepartmentGroupMaster ORDPGRM
	ON ORDPMAP.OrganizationDepartmentGroupId = ORDPGRM.Id

	WHERE ((ORDPMAP.Id = @rId) OR (@rId = 0))
		AND ((ORDPM.Id = @rOrganizationDepartmentId) OR (@rOrganizationDepartmentId = 0))
		AND ((ORDPGRM.Id = @rOrganizationDepartmentGroupId) OR (@rOrganizationDepartmentGroupId = 0))
		AND ((ORDPM.Title LIKE @rOrganizationDepartmentTitle) OR (ISNULL(@rOrganizationDepartmentTitle, '') = ''))
		AND ((ORDPGRM.Title LIKE @rOrganizationDepartmentGroupTitle) OR (ISNULL(@rOrganizationDepartmentGroupTitle, '') = ''))
		AND ORDPMAP.IsObsolete = 0

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationDepartmentMappingModify]
	@rId [int],
	@rOrganizationDepartmentGroupId [smallint],
	@rOrganizationDepartmentId [smallint],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF NOT EXISTS (SELECT 1 FROM sCommon.tOrganizationDepartmentMapping WHERE OrganizationDepartmentGroupId = @rOrganizationDepartmentGroupId AND OrganizationDepartmentId = @rOrganizationDepartmentId  AND Id  <> @rId)
	BEGIN
	 UPDATE sCommon.tOrganizationDepartmentMapping
		SET 
			OrganizationDepartmentGroupId = @rOrganizationDepartmentGroupId,
			OrganizationDepartmentId = @rOrganizationDepartmentId,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	 SELECT 1 AS RESULT
	END

	ELSE

	 BEGIN
		 SELECT -100 AS RESULT
	 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationDepartmentMappingRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
      IF EXISTS (SELECT Id FROM sCommon.tOrganizationDepartmentMapping WHERE Id = @rId)
      BEGIN
            UPDATE sCommon.tOrganizationDepartmentMapping
                  SET IsObsolete = 1
            WHERE Id = @rId
            SELECT 1 AS Result
      END
      ELSE
      BEGIN
            SELECT -100 AS Result
      END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationDepartmentMasterAdd]
	@rOrgId int,
	@rTitle [nvarchar](50),
	@rCode [nvarchar](300),
	@rIsObsolete [bit],
	--@rPhoneNo [nvarchar](50),
	@rCreatedUserId [bigint],
	--@rDepartmentGroupId int,
	--@rExtensionPhoneNumber [nvarchar](50),
	--@rPhoneNumberMobile [nvarchar](50),
	--@rEmailId [nvarchar](300),
	--@rIsClinical [bit]
	@OutDepartmentId INT = NULL OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

    DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sSetup.tDepartmentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
		INSERT INTO sSetup.tDepartmentMaster
			(
				Id,
				OrgId,
				Title,
				Code,
				IsObsolete,	
				--DepartmentGroupId,			
			--	PhoneNo,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime
				--ExtensionPhoneNumber,
				--PhoneNumberMobile,
				--EmailId
			)
		VALUES
			(
				@lNextNumber,
				@rOrgId,
				@rTitle,
				@rCode,
				@rIsObsolete,
				--@rDepartmentGroupId,				
		--		@rPhoneNo,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate()
				--@rExtensionPhoneNumber,
				--@rPhoneNumberMobile,
				--@rEmailId
			)	
	--IF (@rIsClinical = 1)
	--	BEGIN		
	--		EXECUTE sCommon.pClinicalDepartmentMasterAdd @rTitle,
	--														@rRemark,
	--														@rIsObsolete,
	--														@rCreatedUserId,
	--														@lNextNumber 															
			
		--END
	SET @OutDepartmentId = @lNextNumber
				
	SELECT 1 AS RESULT
	
END TRY

BEGIN CATCH
		--PRINT   CAST(@@ERROR AS VARCHAR) 
		SELECT 0 AS RESULT
END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationDepartmentMasterGet]
	@rOrgId [int],
	@rId [int] = 0,
	@rCode [nvarchar](20) = '',
	@rTitle [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
SET @rCode = sCommon.fSearchStringGet(@rCode)
SET @rTitle = sCommon.fSearchStringGet(@rTitle)

	 SELECT ODM.Id,
			ODM.Title,
			ODM.Code,
			ISNULL(ODM.Title, '') AS Remark,
			ODM.IsObsolete,
			ODM.CreatedUserId,
			ODM.CreatedDateTime,
			ODM.UpdatedUserId,
			ODM.UpdatedDateTime
			--ODM.DepartmentGroupId,
			--DGM.Title As DepartmentGroup
			
			--ISNULL(ODM.Code, '') AS Code,
			--ISNULL(ODM.PhoneNo, '') AS PhoneNo,
			--ISNULL(ODM.ExtensionPhoneNumber, '') AS ExtensionPhoneNumber,
		 --   ISNULL(ODM.PhoneNumberMobile, '') AS PhoneNumberMobile,
		 --   ISNULL(ODM.EmailId, '') AS EmailId,
		 --   (CASE ISNULL(OCM.ID, 0)  WHEN 0 THEN 0 ELSE 1 END) AS IsClinical
	  FROM sSetup.tDepartmentMaster ODM 
		--LEFT OUTER JOIN sCommon.tClinicalDepartmentMaster OCM
		--	ON ODM.Id = OCM.Id 
			--INNER JOIN sCommon.tDepartmentGroupMaster DGM ON DGM.Id = ODM.DepartmentGroupId
	  WHERE ((ODM.Id = @rId) OR (@rId = 0))
		AND ((ODM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
		AND ((ODM.Title LIKE @rTitle ) OR (ISNULL(@rTitle, '') = ''))
		AND  ODM.OrgId = @rOrgId
		--AND ODM.IsObsolete = 0
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationDepartmentMasterModify]
	@rId [int],
	@rTitle [nvarchar](50),
	@rCode [nvarchar](300),
	@rIsObsolete [bit],
	@rUpdateBy [bigint]
	--@rDepartmentGroupId int
	--@rPhoneNo [nvarchar](50),
	--@rExtensionPhoneNumber [nvarchar](50),
	--@rPhoneNumberMobile [nvarchar](50),
	--@rEmailId [nvarchar](300),
	--@rIsClinical [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 
	 UPDATE sSetup.tDepartmentMaster
		SET Code = @rCode,
			Title = @rTitle,
			--DepartmentGroupId = @rDepartmentGroupId,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdateBy,
			UpdatedDateTime = sCommon.fGetDate()			
		--    PhoneNo = @rPhoneNo,
		 --   ExtensionPhoneNumber = @rExtensionPhoneNumber,
		 --   PhoneNumberMobile = @rPhoneNumberMobile,
		  --  EmailId = @rEmailId
			
	  WHERE Id = @rId

 
	  SELECT 1 AS RESULT
	  
	 -- IF (@rIsClinical = 1)
		--BEGIN
		--	UPDATE sCommon.tClinicalDepartmentMaster
		--		SET Title = @rTitle,
		--			Remark = @rRemark,
		--			IsObsolete = @rIsObsolete,
		--			UpdatedUserId = @rUpdateBy,
		--			UpdatedDateTime = sCommon.fGetDate()
		--	WHERE Id = @rId
		--END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommon].[pOrganizationSetupAdd]
    @rOrgId int,
    @rIsSync bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rOrgId = @rOrgId
DECLARE @lCreatedDateTime DATETIME
SET @lCreatedDateTime =  sCommon.fGetDate()

DECLARE @lCreatedUserId Int
SET @lCreatedUserId = 1
DECLARE @lOrgGroupId smallint
DECLARE @lOrgGroupBatchId int 
BEGIN TRY
BEGIN TRANSACTION


 SELECT @lOrgGroupId=OrgGroupId from sSetup.tOrganizationMaster where Id=@rOrgId
 
 IF ( @rIsSync = 0)
 BEGIN
 SELECT @lOrgGroupBatchId=ISNULL(MAX(Id),(Convert(nvarchar(10),Convert(nvarchar(10),@lOrgGroupId))+'00000')+1) 
	FROM sSetup.tOrgGroupBatchMaster WHERE OrgGroupId=@lOrgGroupId
 
 
 INSERT INTO [sSetup].[tBatchMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[OrgId]
           ,[IsHistory]
           ,[IsActive]
           ,[IsObsolete]
           ,[OrderIndex]
           ,[FromDate]
           ,[ToDate]
           ,[OrgGroupBatchId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,IsInContext)
     
      SELECT sCommon.fGetIntIdForOrg(1,@rOrgId)
           ,Code
           ,Title
           ,@rOrgId
           ,0
           ,1
           ,0
           ,1
           ,FromDate
           ,ToDate
           ,@lOrgGroupBatchId
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,1
           FROM [sSetup].[tOrgGroupBatchMaster] WHERE  Id =  @lOrgGroupBatchId
END


INSERT INTO [sCommon].[tTableRowId]
           ([OrgId]
           ,[TableTitle]
           ,[CurrentNumber]
           ,[Seed]
           ,[Increment])
SELECT
		   @rOrgId
		  ,[TableTitle]
		  
		  ,CASE 
      WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId) 
      WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId )
		END 
		
		  ,CASE 
      WHEN IdDataType = 'int' THEN sCommon.fGetIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId) 
      WHEN IdDataType = 'bigint' THEN sCommon.fGetbigIntIdForOrg(ISNULL(CurrentNumber,0),@rOrgId )
		END  
		   ,1
	  FROM [sCommon].[tTableRowIdMaster] where 
	  (tableType = 'Non Static' or tableType = '100Static' )
	  AND iddatatype <> '' AND IdScope <> 'OrgGroup'

 IF (  @lOrgGroupId = @rOrgId)
 BEGIN
	  INSERT INTO sSecurity.tUser 
		   ([Id]
           ,[DisplayTitle]
           ,[LoginTitle]
           ,[LoginPassword]
           ,[LastLockOutDate]
           ,[NumberOfLogonAttempt]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           --,[EmployeeId]
           ,[SessionId]
           ,[OrgId]
           ,[IsCommon])		  
	SELECT 
		   sCommon.fGetBigIntIdForOrg(Id,@rOrgId)
		  ,[DisplayTitle]
		  ,[LoginTitle]
		  ,[LoginPassword]
		  ,@lCreatedDateTime
		  ,[NumberOfLogonAttempt]
		  ,[IsObsolete]
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  --,sCommon.fGetIntIdForOrg(1,@rOrgId)
		  ,[SessionId]
		  ,@rOrgId
		  ,1
	  FROM [sSecurity].[tUser] WHERE Id < 5 AND OrgId=1
	  --for Online pay user add condition < 5 instead of < 4
	  
	  --OrgId is not used
INSERT INTO [sSecurity].[tUserRole]
           (
            [RoleId]
           ,[UserId]
           ,[IsObsolete]
           ,[IsPrimary]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           )
SELECT 
		   sCommon.fGetIntIdForOrg(2,@lOrgGroupId)
		  ,sCommon.fGetBigIntIdForOrg(3,@lOrgGroupId)
		  ,0
		  ,1
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
		  ,@lCreatedUserId
		  ,@lCreatedDateTime
	  
END
  
	
 
 

	  --OrgId is not used
INSERT INTO sSecurity.tUserOrganization
           (
            [OrgId]
           ,[UserId]
           
           )
SELECT 
		   @rOrgId
		  ,sCommon.fGetBigIntIdForOrg(3,@lOrgGroupId)
		   


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







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

           
 
           
  INSERT INTO [sSetup].[tDepartmentMaster]
           (
					[ID]
				   ,[Code]
				   ,[Title]
				   ,[DisplayTitle]
				   ,[OrgId]
				   ,[IsObsolete]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
				   ,[UpdatedUserId]
				   ,[UpdatedDateTime]
           )     
           SELECT  sCommon.fGetIntIdForOrg(1,@rOrgId)
				  ,'Common'
				  ,'Common'
				  ,'Common'
				  ,@rOrgId
				  ,0
				  ,@lCreatedUserId
				  ,@lCreatedDateTime
				  ,@lCreatedUserId
				  ,@lCreatedDateTime

 INSERT INTO sAttendance.tApplicableAttendanceType
           (
            		OrgId
				   ,AttendanceTypeId				   
           )     
           SELECT  @rOrgId
				   ,1			  

-- Event Template
INSERT INTO sAlert.tEventTemplate
(OrgId,EventId,Template,AlertModeId,IsAutoSend,MailSubject)			
SELECT @rOrgId,Id,Template,1,0,MailSubject
FROM sAlert.tEventMaster
UNION ALL 		  
SELECT @rOrgId,Id,Template,2,0,MailSubject
FROM sAlert.tEventMaster
UNION ALL 	
SELECT @rOrgId,Id,Template,3,0,MailSubject
FROM sAlert.tEventMaster

-- Report Format Group Org
INSERT INTO sCommon.tReportFormatGroupOrg
(OrgId,ReportId,ReportFormatGroupId)			
SELECT @rOrgId,R.Id,R.ReportFormatGroupId
FROM sCommon.tReportFormatGroupMaster RGM
INNER JOIN sCommon.tReport R ON RGM.Id = R.ReportFormatGroupId
WHERE RGM.IsObsolete = 0 AND R.IsObsolete = 0 AND R.Id IN (20877,10155,20435,10156,20399,20880,20879,10197)

   
COMMIT TRANSACTION	 
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT ERROR_MESSAGE()
END CATCH
END

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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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


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

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

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

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

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

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

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

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


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


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

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

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

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

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


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

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


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

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


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

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


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

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

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

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


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

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

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


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

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

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

DELETE FROM sFee.tFeeAllocationHistory WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tUploadDocument WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId

DELETE FROM sFee.tFeeAllocationStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeClassBatchStatus WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeBatch WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tEmployeeDocumentUpload WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tEmployeeCustomFieldData] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommunication].[tDailyThoughtAssign] WHERE OrgId= @rOrgId
DELETE FROM [sFee].[tEMandate] WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM [sAdmission].[tAdmissionInquiryCriteria] WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId
DELETE FROM [sCommon].[tSubmitDocumentScope] WHERE CAST(LEFT([SubmitDocumentId], 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningRecording WHERE CAST(LEFT([OnlineLearningId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommon].[tUserToken] WHERE CAST(LEFT([UserId], 4) AS bigint) = @rOrgId

DELETE FROM [sBiometric].[tEmployeeConfiguration] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tWhatsAppConfiguration WHERE OrgId= @rOrgId
DELETE FROM sFee.tDepositSetup WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningHistoryLog WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrack] WHERE OrgId = @rOrgId
DELETE FROM sTally.tJVPosting WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId

DELETE FROM [sHrm].[tLeavePeriod] WHERE OrgId = @rOrgId
DELETE FROM [sRecruitment].[tAssignOrganization] WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCustomSearch WHERE OrgId = @rOrgId

DELETE FROM[sCommunication].[tTempQueryCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId


DELETE FROM [sStudent].[tOnlineRegistrationStudentAdmission] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCommunication] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCustomFieldData] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentDocument] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentFamily] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentImages] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOther] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCollegeDetail] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationDisplayField]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaDocument]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaForm]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentMaster] WHERE OrgId = @rOrgId

DELETE FROM [sBiometric].[tShiftAllocationCloud] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tCloudTransactionData] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM [sTransport].[tAssignRouteLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sAttendance].[tAttendanceFollowup] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tAssessmentLabelSetup WHERE OrgId = @rOrgId
DELETE FROM [sAssessment].[tStudentExamRemark] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tDeviceMasterCloud] WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tDigitalForm] WHERE OrgId = @rOrgId
DELETE FROM [sHrm].[tDigitalFormField] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormScope] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormEmployee] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionOptionalSubject] WHERE CAST(LEFT([AdmissionFormId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOptionalSubject] WHERE CAST(LEFT([OnlineRegistrationStudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteria] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrackHistory] WHERE OrgId = @rOrgId
DELETE FROM [sActivity].[tEventInchargeAssign] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sLibrary].[tNewspaperLog] WHERE CAST(LEFT([NewspaperId], 4) AS int) = @rOrgId
DELETE FROM sSetup.tClassContentSetup WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId

DELETE FROM[sHrm].[tCertificateJoining] WHERE [OrgId] = @rOrgId
DELETE FROM[sCommunication].[tTempMultiPhotoCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM[sStudent].[tDigitalFormStudentStatus] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM[sHrm].[tDigitalFormEmployeeStatus] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM[sHrm].[tLeaveHierarchyLevel] WHERE CAST(LEFT([LeaveId], 4) AS bigint) = @rOrgId

DELETE FROM [sAudit].[tChargeDeleted] WHERE [OrgId] = @rOrgId
DELETE FROM [sAudit].[tChargeDetailDelete] WHERE CAST(LEFT([ChargeReceiptId], 4) AS bigint) = @rOrgId

DELETE FROM sFee.tLateFeeRuleMaster WHERE OrgId = @rOrgId
DELETE FROM sAlert.tAlertQueueLog WHERE OrgId = @rOrgId

DELETE FROM sFee.tDepositDefaultSetup WHERE OrgId = @rOrgId

--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

	SELECT 1 AS Result
 
-- COMMIT TRANSACTION
		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
		
--	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pOrgGroupSetupRemove]
	 
	 @rOrgGroupId smallint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	
	IF EXISTS(SELECT TOP 1 1 FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END
	
	
	BEGIN TRANSACTION
	 
	EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    




DELETE FROM sAccounting.tAccountingYearMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tAccountMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerGroupMaster  WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransaction WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sActivity.tActivityTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tClubMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tImmunizationChart WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryReferenceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAttendance.tAbsentReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingConductMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingProgressMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingRemarkMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAreaMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tBirthPlaceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCountryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tDistrictMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHobbyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tMotherTongueMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tNationalityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tOccupationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tPreviousSchoolMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tReligionMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tStateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tSurnameMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBehaviourTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlogComment WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogFavorite WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogScope WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircular WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCircularScope WHERE CAST(LEFT(CircularId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularView WHERE CAST(LEFT(CircularId, 4) AS BIGINT) =@rOrgGroupId
DELETE FROM sCommunication.tNews WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tNewsComment WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tNewsScope WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPhotoCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPoll WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPollAnswer WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollMember WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollResult WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQuery WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE CAST(LEFT(QueryCategoryId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryComment WHERE CAST(LEFT(QueryId, 4) AS BIGINT) =  @rOrgGroupId
DELETE FROM sEExam.tDataBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataSubjectMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateQuestion WHERE CAST(LEFT(TestTemplateId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tStockUomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sGSEB.tActivityGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tRoomCategoryMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tRoomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tQualificationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tItemMainGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tItemSubGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemCategoryMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tStoreLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAgeGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAuthorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLanguageMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLocationMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookPublisherMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSupplierMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookTagMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tLibraryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tProfessionalTaxRange WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sProcurement.tVendorCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrganizationTask WHERE CAST(LEFT(OrgGroupId, 4) AS SMALLINT) = @rOrgGroupId
DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

 
DELETE FROM sStudent.tAdmissionCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTax.tTaxGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteDestinationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tFamiliyCastMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sScholarship.tScholarshipTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgMainGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgSubGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tVisitorGatePass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollYearMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sActivity.tEventTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRoleDashlet WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId


DELETE FROM sCommon.tFrequencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tRangeDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tRangeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFinanceCommon.tCurrencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierDispatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierReceive WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tBuildingMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tChangeRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelAdmission WHERE CAST(LEFT(Hosteld, 4) AS INT) = @rOrgGroupId

DELETE FROM sLibrary.tLibraryAttendance WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineReceive WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tFuelLogs WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tFuelTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleDocumentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTransport.tVehicleDocuments WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenance WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenanceDetail WHERE CAST(LEFT(VehicleMaintenanceId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleTypeMaster WHERE OrgGroupId = @rOrgGroupId

--DELETE FROM sTimetable.tAssignSchoolRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tDivisionTimeOff WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolBuildingMaster WHERE  OrgGroupId = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomMaster WHERE  CAST(LEFT(SchoolBuildingId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tTeacherTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

DELETE FROM sCommunication.tEbook WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tEbookScope WHERE  CAST(LEFT(EbookId, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sActivity.tClubTypeMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tHouseGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryStatusMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroup WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroupMember WHERE  CAST(LEFT(CustomGroupId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sTally.tFeeLedgerMapping WHERE CAST(LEFT(FeeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptBookCompanyMapping WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptPosting WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoomTimeOff WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tSchoolBuilding WHERE  OrgGroupId = @rOrgGroupId
 DELETE FROM sCommon.tCastCategoryMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tTransportMaster WHERE  OrgGroupId = @rOrgGroupId

DELETE FROM sAlert.tOtherGroupDetail WHERE  CAST(LEFT(OtherGroupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tOtherGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAdmissionQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tCollectionGroupMaster WHERE  CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId

DELETE FROM sHrm.tWorkAreaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItem WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItemSize WHERE  CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sIp.tUniformStock WHERE  CAST(LEFT(UniformSizeId, 4) AS INT) = @rOrgGroupId

DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tReportOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayConfiguration WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sTimetable.tDivisionClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tSubjectClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tTimeTableDetail WHERE CAST(LEFT(TimetableId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeDetail WHERE CAST(LEFT(ExemptionTypeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSecurity.tRoleModulePermission WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId

/* -- Date : 13/06/2016 -- */
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenIssueDetail WHERE CAST(LEFT(CanteenIssueId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tFoodItemMaster WHERE CAST(LEFT(CanteenId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFrontOffice.tLostFoundRegister WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tAssetTypeMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tAssignRoomAsset WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tRoomAssetMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tLeaveReasonMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupSetting WHERE OrgGroupId = @rOrgGroupId
 
DELETE FROM sStudent.tSUIdConfig WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTimetable.tAssignDivision WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

/* -- Date : 12/08/2016 -- */
DELETE FROM sHostel.tHostelDepositAdd WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositAdjustment WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositRefund WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSystem.tExceptionLog WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 17/09/2016 -- */
DELETE FROM sCommon.tReportClient WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tTempCircularScope WHERE CAST(LEFT(SourceID, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 05/10/2016 -- */
DELETE FROM sHostel.tAttendanceRegister WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateCommunications WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateImages WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateQualification WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateVacancyCriteriaScore WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tInterviewCriteria WHERE CAST(LEFT(VacancyId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentStatusLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancy WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 24/11/2016 -- */

DELETE FROM siTax.tAssessmentYear WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16 WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16Detail WHERE CAST(LEFT(Form16Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxChallan WHERE CAST(LEFT(AssesmentYearId, 4) AS INT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSlab WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSubGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tPlacementCompanyMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAppraisal.tConductTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sErp.tCustomerActivationLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicyDetail WHERE  CAST(LEFT(IpPolicyId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tTimePolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserPolicy WHERE  CAST(LEFT(TimePolicyId, 4) AS int) = @rOrgGroupId


DELETE FROM sAppraisal.tKPATemplateDetail WHERE CAST(LEFT(KPATemplateId, 4) AS int) = @rOrgGroupId
DELETE FROM sAppraisal.tKPATemplateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayProduct WHERE CAST(LEFT(GatewayConfigurationId, 4) AS int) = @rOrgGroupId
DELETE FROM sOp.tGatewayProductReceiptBookMapping WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tSstockIssueTypeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeDepositExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelAttendanceTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseSubTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelGatePassReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformOrderItem WHERE CAST(LEFT(StockItemId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturn WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturnBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentOtherGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentUIdMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAssetManagement.tAssetCheck WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetInchargeUser WHERE CAST(LEFT(AssetId, 4) AS int) = @rOrgGroupId
DELETE FROM sCanteen.tBreakTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tDailyMenu WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId

DELETE FROM sAlert.tAdVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeAccountMapping WHERE CAST(LEFT(ChargeId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tChargeAccountPosting WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountMapping WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountPosting WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tFeedback WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeDetail WHERE CAST(LEFT(FeedbackAnswerTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAssign WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackFor WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackQuestionResponse WHERE CAST(LEFT(FeedbackResponseId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackResponse WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplate WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplateQuestion WHERE CAST(LEFT(FeedbackTemplateId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tStockReset WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockResetBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tBackupLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSystem.tPortalSync WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sAccounting.tBudget WHERE CAST(LEFT(LedgerId, 4) AS int) = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApprove WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApproveDetail WHERE CAST(LEFT(LedgerId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSetup.tScreenMandatoryFeild WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sCommunication.tPhotoCategoryScope WHERE CAST(LEFT(PhotoCategoryId, 4) AS int) = @rOrgGroupId
DELETE FROM sTool.tTestCase WHERE CAST(LEFT(Id, 4) AS int) = @rOrgGroupId

DELETE FROM sLibrary.tMagazineTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrgGroupMobileAppDetail WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookSubCategoryMaster WHERE OrgGroupId = @rOrgGroupId


/*============================================*/

	-- special case will come orgwise and orggroupwise

DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@rOrgGroupId


DELETE FROM sCanteen.tGuestRequest WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tLimitLog WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sProcurement.tOtherStockBatch WHERE CAST(LEFT(StockBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssue WHERE CAST(LEFT(StoreLocationId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssueBatch WHERE CAST(LEFT(OtherStockBatchId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sVts.tvtsOrgGroupMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookGroup1Master WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookGroup2Master WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tHostelEventAssign WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventAttendance WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId

DELETE FROM sHostel.tHostelEventSchedule WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventTypeMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @rOrgGroupId



DELETE FROM sCommon.tOrgGroupDepartmentMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupEIS WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripLog WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripTemplate WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId


DELETE FROM sCommunication.tCircularTypeAssignedTo WHERE CAST(LEFT(CircularTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sErp.tSupportTicket WHERE OrgGroupId= @rOrgGroupId
DELETE FROM siTax.tTaxPlanning WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sStudent.tStudentCustomFieldMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tScreenFunctionalityTraining WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommon.tPhysicalDisabilityCategoryMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM siTax.tForm16SubDetail WHERE CAST(LEFT(Form16Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSecurity.tAssignSubRole WHERE CAST(LEFT(RoleId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tChatGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tChatGroupScope WHERE CAST(LEFT(ChatGroupId, 4) AS int) = @rOrgGroupId


DELETE FROM sAcademic.tOnlineMeetingAccount WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommunication.teContentTypeMaster WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommunication.teContent WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sPayroll.tPayElementHistory WHERE CAST(LEFT([PayrollId], 4) AS int) = @rOrgGroupId

DELETE FROM [sHrm].[tEmployeeCustomFieldMaster] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM [sCommunication].[tDailyThoughtMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tDailyThoughtSubjectMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tDailyThoughtTemp] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM [sErp].[tCustomerMessage] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM[sCommunication].[tPlaylistMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tPlaylistDetails] WHERE CAST(LEFT(PlaylistId, 4) AS int) =  @rOrgGroupId

DELETE FROM sRecruitment.tRecruitmentCriteriaDocument WHERE CAST(LEFT([VacancyId], 4) AS bigint) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentRecruiterDocument WHERE CAST(LEFT([RecruitmentId], 4) AS bigint) =  @rOrgGroupId
DELETE FROM [sCommon].[tPublishDocumentMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM [sFee].[tApplicablePayType] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateFamilyDetails WHERE OrgGroupId = @rOrgGroupId

DELETE FROM[sCommunication].[tQueryCategoryScope] WHERE CAST(LEFT([QueryCategoryId], 4) AS int) = @rOrgGroupId
DELETE FROM [sTransport].[tVehicleLog] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sIp.tStockChargeMapping  WHERE CAST(LEFT([ChargeId], 4) AS int) = @rOrgGroupId

DELETE FROM [sCommon].[tFamiliySubCasteMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM [sSetup].[tOnlineFormSetup] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sLibrary].[tNewspaperMaster] WHERE CAST(LEFT([Id], 4) AS int) = @rOrgGroupId

DELETE FROM [sHrm].[tCommitteeMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sHrm].[tHouseMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sHrm].[tClubMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHrm.tAssignClub WHERE CAST(LEFT([ClubId], 4) AS int) = @rOrgGroupId
DELETE FROM sHrm.tAssignHouse WHERE CAST(LEFT([HouseId], 4) AS int) = @rOrgGroupId
DELETE FROM sHrm.tAssignCommittee WHERE CAST(LEFT([CommitteeId], 4) AS int) = @rOrgGroupId
DELETE FROM sIp.tStockDefectiveItemMaster WHERE OrgGroupId = @rOrgGroupId
	
DELETE FROM sCommon.tTribeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM[sCommunication].[tMultiPhotoCategoryMaster] WHERE [OrgGroupId] = @rOrgGroupId
DELETE FROMsCommunication.tMultiPhotoCategoryScope WHERE CAST(LEFT([MultiPhotoCategoryId], 4) AS bigint) = @rOrgGroupId


DELETE FROM [sAssetManagement].[tAssetCustomFieldMaster] WHERE [OrgGroupId] = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetCustomFieldData WHERE CAST(LEFT([AssetCustomFieldId], 4) AS int) = @rOrgGroupId

--remove from VitorTypeMaster
DELETE FROM [sFrontOffice].[tVisitorTypeMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sProcurement.tStockKitMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tCustomFieldMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancyCustomFieldMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSecurity.tMigrationModulePermission WHERE OrgGroupId = @rOrgGroupId -- For Migration Redirection Entry Remove

EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

	SELECT 1 AS Result
 
 COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPatientSearchAllIpGet]
	@rPId [nvarchar](20) = '',
	@rPatientName [nvarchar](30) = '',
	@rMobileNumber [nvarchar](20) = '',
	@rProofIdType [nvarchar](20) = '',
	@rProofIdNumber [nvarchar](20) = '',
	@rPatientType [smallint],
	@rDOB [datetime] = '1/1/1900',
	@rStartIndex [int] = 0,
	@rPageSize [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lDatePresent Int 

DECLARE @lUpperBound Int
IF @rStartIndex  < 1 SET @rStartIndex = 1 
IF @rPageSize < 1 SET @rPageSize = 1 

SET @lUpperBound = @rStartIndex + @rPageSize 

SET @rPId = sCommon.fSearchStringGet(@rPId)
SET @rPatientName = sCommon.fSearchStringGet(@rPatientName)
SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber)
SET @rProofIdType = sCommon.fSearchStringGet(@rProofIdType)
SET @rProofIdNumber = sCommon.fSearchStringGet(@rProofIdNumber)

CREATE TABLE #tempNpatient 
	( 
		PatientNumber VARCHAR(300) 
	)
     
     INSERT INTO #tempNpatient SELECT MAX(Id) FROM sRegistration.vExtRegistration GROUP BY PatientId

IF (CAST(CONVERT(NVARCHAR(12),  @rDOB,  101) AS DATETIME) =  CAST(CONVERT(NVARCHAR(12), '1/1/1900',  101) AS DATETIME))
BEGIN
  SET  @lDatePresent = 0
END
ELSE
BEGIN
  SET  @lDatePresent = 1
END


SELECT 
	RowNumber,
	Id,
	PId,
	PatientName,
	FirstName,
	MiddleName,
	LastName,
	IdProofType,
	IdProofNumber,
	DateOfBirth,
	DOB,
	MobileNumber,
	LandLine,
	EmailId,
	StreetOne,
	StreetTwo,
	StreetThree,
	StreetFour,
	ZipCode, 
	AreaId, 
	Area, 
	CityId, 
	CityTitle, 
	StateId, 
	StateTitle, 
	CountryId, 
	CountryTitle, 
	GenderId, 
	Gender, 
	MaritalStatusId, 
	MaritalStatus, 
	SalutationId, 
	Salutation,
	VisitType,
	PatientType,
	VisitNumber,
	RegPatientType,
	CreatedDateTime,
	RegId,
	TotalRecords
 FROM (
		SELECT 
		Row_Number() OVER(ORDER BY PM.Id) AS RowNumber,
		PM.Id  AS Id,
		ISNULL(PM.PatientNumber, '') AS PId,
		ISNULL(PatientName, '') AS PatientName,
		PM.FirstName AS FirstName,
		PM.MiddleName AS MiddleName,
		PM.LastName AS LastName,
		ISNULL(IdM.Title, '') AS IdProofType,
		ISNULL(IdProofNumber, '') AS IdProofNumber,
		ISNULL(DateOfBirth, '')  AS DateOfBirth,
		(CASE DateOfBirth 
		          WHEN '1900-01-01 00:00:00.000' THEN NULL
				  ELSE  ISNULL(DateOfBirth, NULL)
		END) DOB,
		ISNULL(PC.PhoneNumberMobile, '') AS MobileNumber,
		PC.PhoneNumberHome AS LandLine,
		PC.EmailPrimary AS EmailId,
		PA.StreetOne AS StreetOne,
		PA.StreetTwo AS StreetTwo,
		PA.StreetThree AS StreetThree,
		PA.StreetFour AS StreetFour,
		PA.ZipCode AS ZipCode,
		PA.AreaId AS AreaId,
		AM.Title AS Area,
		AM.CityId AS CityId,
		CM.Title AS CityTitle,
		CM.StateId AS StateId,
		SM.Title AS StateTitle,
		SM.CountryId AS CountryId,
		CountryMaster.Title AS CountryTitle,
		PM.GenderId AS GenderId,
		GM.Title AS Gender,
		PM.MaritalStatusId AS MaritalStatusId,
		MM.Title AS MaritalStatus,
		PM.SalutationId AS SalutationId,
		SalutationMaster.Title AS Salutation,
		REG.RegStatus AS VisitType,
		REG.ServiceChargeTypeId AS PatientType,
		REG.VisitNumber AS VisitNumber,
		@rPatientType AS RegPatientType,
		REG.CreatedDateTime,
		REG.Id AS RegId,
		COUNT(1) over() AS TotalRecords

		 FROM sRegistration.vExtPatientMaster PM
		 LEFT JOIN sRegistration.vExtRegistration REG
		 ON PM.Id = REG.PatientId
		 LEFT  JOIN sCommon.tIdProofTypeMaster IdM
		 ON PM.IdProofTypeId = IdM.Id
		 LEFT JOIN sRegistration.vExtPatientContact PC
		 ON PM.CommunicationContactId = PC.Id
		 LEFT JOIN sRegistration.vExtPatientAddress PA
		 ON PM.CommunicationAddressId = PA.Id
		 LEFT JOIN sCommon.tAreaMaster AM
		 ON PA.AreaId = AM.Id
		 LEFT JOIN sCommon.tCityMaster CM
		 ON AM.CityId = CM.Id
		 LEFT JOIN sCommon.tStateMaster SM
		 ON CM.StateId = SM.Id
		 LEFT JOIN sCommon.tCountryMaster CountryMaster
		 ON SM.CountryId = CountryMaster.Id
		 LEFT JOIN sCommon.tGenderMaster GM
		 ON PM.GenderId = GM.Id
		 LEFT JOIN sCommon.tMaritalStatusMaster MM
		 ON PM.MaritalStatusId = MM.Id
		 LEFT JOIN sCommon.tSalutationMaster SalutationMaster
		 ON PM.SalutationId =  SalutationMaster.Id
		 
		 
		 WHERE 
		     
		     ((PM.PatientNumber Like @rPId) OR(@rPId = ''))
			AND ((PM.PatientName Like  @rPatientName)  OR (@rPatientName = ''))
			AND ((PC.PhoneNumberMobile Like @rMobileNumber) OR(@rMobileNumber = ''))
			AND (
			        ((PM.IdProofTypeId Like @rProofIdType )  AND (PM.IdProofNumber Like @rProofIdNumber ) )
			          OR ((@rProofIdType = '') AND (@rProofIdNumber = '' ))
			 
      )
			
			AND PM.IsObsolete = 0
			AND 
			      (
			     ( CAST(CONVERT(NVARCHAR(12), PM.DateOfBirth, 101) AS DATETIME) =  CAST(CONVERT(NVARCHAR(12),  @rDOB, 101) AS DATETIME) AND (@lDatePresent = 1))
			     OR
			     ( CAST(CONVERT(NVARCHAR(12),
 ISNULL(PM.DateOfBirth, '1900-01-01'), 101) AS DATETIME) > =  CAST(CONVERT(NVARCHAR(12), '1900-01-01', 101) AS DATETIME) AND (@lDatePresent = 0))
			      )
	        AND
	     	(
				(( REG.ServiceChargeTypeId IN (1, 2)) AND (@rPatientType = 2) AND (REG.RegStatusId = 1)) 
				    OR
				((REG.ServiceChargeTypeId = 2)AND (@rPatientType = 3) AND (REG.RegStatusId = 1))
				   OR
				((REG.ServiceChargeTypeId = 2)AND (@rPatientType = 4) AND (REG.RegStatusId IN (1, 2)))
			 )
		 AND REG.ID IN (SELECT PatientNumber FROM #tempNpatient)) PS
		WHERE
--	   PS.RowNumber >= CONVERT(varchar(9), @rStartIndex) AND PS.RowNumber <  CONVERT(varchar(9), @lUpperBound) 
	   PS.RowNumber >= @rStartIndex AND PS.RowNumber <  @lUpperBound
	   ORDER BY  PS.Id DESC
   		       
		--ORDER BY  PM.Id DESC, REG.VisitNumber DESC, REG.Id DESC, REG.CreatedDateTime DESC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPatientSearchConditionalGet]
	@rPId [nvarchar](20) = '',
	@rPatientName [nvarchar](30) = '',
	@rMobileNumber [nvarchar](20) = '',
	@rProofIdType [nvarchar](20) = '',
	@rProofIdNumber [nvarchar](20) = '',
	@rPatientType [smallint],
	@rDOB [datetime] = '1/1/1900',
	@rStartIndex [int] = 0,
	@rPageSize [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lDatePresent Int 

--Page Optimization Starts
DECLARE @lUpperBound Int
IF @rStartIndex  < 1 SET @rStartIndex = 1 
IF @rPageSize < 1 SET @rPageSize = 1 
SET @lUpperBound = @rStartIndex + @rPageSize 
--Page Optimization Ends
SET @rPId = sCommon.fSearchStringGet(@rPId)
SET @rPatientName = sCommon.fSearchStringGet(@rPatientName)
SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber)
SET @rProofIdType = sCommon.fSearchStringGet(@rProofIdType)
SET @rProofIdNumber = sCommon.fSearchStringGet(@rProofIdNumber)


IF (CAST(CONVERT(NVARCHAR(12),  @rDOB,  101) AS DATETIME) =  CAST(CONVERT(NVARCHAR(12), '1/1/1900',  101) AS DATETIME))
BEGIN
  SET  @lDatePresent = 0
END
ELSE
BEGIN
  SET  @lDatePresent = 1
END


SELECT 
	RowNumber,
	Id,
	PId,
	PatientName,
	FirstName,
	MiddleName,
	LastName,
	IdProofType,
	IdProofNumber,
	DateOfBirth,
	DOB,
	MobileNumber,
	LandLine,
	EmailId,
	StreetOne,
	StreetTwo,
	StreetThree,
	StreetFour,
	ZipCode, 
	AreaId, 
	Area, 
	CityId, 
	CityTitle, 
	StateId, 
	StateTitle, 
	CountryId, 
	CountryTitle, 
	GenderId, 
	Gender, 
	MaritalStatusId, 
	MaritalStatus, 
	SalutationId, 
	Salutation,
	VisitType,
	PatientType,	
	RegPatientType,	
	TotalRecords
 FROM (
		SELECT 
			Row_Number() OVER(ORDER BY PM.Id) AS RowNumber,
			PM.Id  AS Id,
			ISNULL(PM.PatientNumber, '') AS PId,
			ISNULL(PM.PatientName, '') AS PatientName,
			PM.FirstName AS FirstName,
			PM.MiddleName AS MiddleName,
			PM.LastName AS LastName,
			ISNULL(IdM.Title, '') AS IdProofType,
			ISNULL(IdProofNumber, '') AS IdProofNumber,
			ISNULL(DateOfBirth, '')  AS DateOfBirth,
			(CASE DateOfBirth 
					  WHEN '1900-01-01 00:00:00.000' THEN NULL
					  ELSE  ISNULL(DateOfBirth, NULL)
			END) DOB,
			ISNULL(PC.PhoneNumberMobile, '') AS MobileNumber,
			PC.PhoneNumberHome AS LandLine,
			PC.EmailPrimary AS EmailId,
			PA.StreetOne AS StreetOne,
			PA.StreetTwo AS StreetTwo,
			PA.StreetThree AS StreetThree,
			PA.StreetFour AS StreetFour,
			PA.ZipCode AS ZipCode,
			PA.AreaId AS AreaId,
			AM.Title AS Area,
			AM.CityId AS CityId,
			CM.Title AS CityTitle,
			CM.StateId AS StateId,
			SM.Title AS StateTitle,
			SM.CountryId AS CountryId,
			CountryMaster.Title AS CountryTitle,
			PM.GenderId AS GenderId,
			GM.Title AS Gender,
			PM.MaritalStatusId AS MaritalStatusId,
			MM.Title AS MaritalStatus,
			PM.SalutationId AS SalutationId,
			SalutationMaster.Title AS Salutation,
			REG.RegStatus AS VisitType,
			REG.ServiceChargeTypeId AS PatientType,
			@rPatientType AS RegPatientType,
			COUNT(*) over() AS TotalRecords

		 FROM sRegistration.vExtPatientMaster PM
		 LEFT JOIN sRegistration.vExtRegistration REG
		 ON PM.Id = REG.PatientId
		 LEFT  JOIN sCommon.tIdProofTypeMaster IdM
		 ON PM.IdProofTypeId = IdM.Id
		 LEFT JOIN sRegistration.vExtPatientContact PC
		 ON PM.CommunicationContactId = PC.Id
		 LEFT JOIN sRegistration.vExtPatientAddress PA
		 ON PM.CommunicationAddressId = PA.Id
		 LEFT JOIN sCommon.tAreaMaster AM
		 ON PA.AreaId = AM.Id
		 LEFT JOIN sCommon.tCityMaster CM
		 ON AM.CityId = CM.Id
		 LEFT JOIN sCommon.tStateMaster SM
		 ON CM.StateId = SM.Id
		 LEFT JOIN sCommon.tCountryMaster CountryMaster
		 ON SM.CountryId = CountryMaster.Id
		 LEFT JOIN sCommon.tGenderMaster GM
		 ON PM.GenderId = GM.Id
		 LEFT JOIN sCommon.tMaritalStatusMaster MM
		 ON PM.MaritalStatusId = MM.Id
		 LEFT JOIN sCommon.tSalutationMaster SalutationMaster
		 ON PM.SalutationId =  SalutationMaster.Id
		 
		 
		 WHERE 
		      --((PM.PatientNumber Like  '%' + @rPId + '%' )OR(@rPId = ''))
		      ((PM.PatientNumber Like @rPId) OR(@rPId = ''))
			AND ((PM.PatientName Like  @rPatientName)  OR (@rPatientName = ''))
			AND ((PC.PhoneNumberMobile Like @rMobileNumber) OR(@rMobileNumber = ''))
			AND (
			        ((PM.IdProofTypeId Like @rProofIdType )  AND (PM.IdProofNumber Like @rProofIdNumber ) )
			          OR ((@rProofIdType = '') AND (@rProofIdNumber = '' ))
			       )
			--AND REG.RegStatus = 'Open'
			AND PM.IsObsolete = 0
	        AND
	     	(
				(( REG.ServiceChargeTypeId IN (1, 2)) AND (@rPatientType = 2) AND (REG.RegStatusId = 1)) 
				    OR
				((REG.ServiceChargeTypeId = 2)AND (@rPatientType = 3) AND (REG.RegStatusId = 1))
				   OR
				((REG.ServiceChargeTypeId = 2)AND (@rPatientType = 4) AND (REG.RegStatusId IN (1, 2)))
			 )
			
      AND 
			      (
			     ( CAST(CONVERT(NVARCHAR(12), PM.DateOfBirth, 101) AS DATETIME) =  CAST(CONVERT(NVARCHAR(12),  @rDOB, 101) AS DATETIME) AND (@lDatePresent = 1))
			     OR
			     ( CAST(CONVERT(NVARCHAR(12), ISNULL(PM.DateOfBirth, '1900-01-01'), 101) AS DATETIME) > =  CAST(CONVERT(NVARCHAR(12), '1900-01-01', 101) AS DATETIME) AND (@lDatePresent = 0))
			      )) PS
		WHERE
	   PS.RowNumber >= CONVERT(varchar(9), @rStartIndex) AND PS.RowNumber <  CONVERT(varchar(9), @lUpperBound) 
	   ORDER BY  PS.Id DESC
 		  
			       
		--ORDER BY  PM.Id DESC
		
---		SELECT sCommon.fSearchStringGet('shaiju')
--SELECT sCommon.fSearchStringGet('shaiju*')
--SELECT sCommon.fSearchStringGet('*shaiju')
--SELECT sCommon.fSearchStringGet('*shaiju*')


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPatientSearchGet]
	@rPId [nvarchar](20) = '',
	@rPatientName [nvarchar](30) = '',
	@rMobileNumber [nvarchar](20) = '',
	@rProofIdType [nvarchar](20) = '',
	@rProofIdNumber [nvarchar](20) = '',
	@rDOB [datetime] = '1/1/1900',
	@rStartIndex [int] = 0,
	@rPageSize [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lDatePresent Int 

DECLARE @lUpperBound Int
IF @rStartIndex  < 1 SET @rStartIndex = 1 
IF @rPageSize < 1 SET @rPageSize = 1 

SET @lUpperBound = @rStartIndex + @rPageSize 


SET @rPId = sCommon.fSearchStringGet(@rPId)
SET @rPatientName = sCommon.fSearchStringGet(@rPatientName)
SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber)
SET @rProofIdType = sCommon.fSearchStringGet(@rProofIdType)
SET @rProofIdNumber = sCommon.fSearchStringGet(@rProofIdNumber)

IF (CAST(CONVERT(NVARCHAR(12),  @rDOB,  101) AS DATETIME) =  CAST(CONVERT(NVARCHAR(12), '1/1/1900',  101) AS DATETIME))
BEGIN
  SET  @lDatePresent = 0
END
ELSE
BEGIN
  SET  @lDatePresent = 1
END


SELECT 
	RowNumber,
	Id,
	PId,
	PatientName,
	FirstName,
	MiddleName,
	LastName,
	IdProofType,
	IdProofNumber,
	DateOfBirth,
	DOB,
	MobileNumber,
	LandLine,
	EmailId,
	StreetOne,
	StreetTwo,
	StreetThree,
	StreetFour,
	ZipCode, 
	AreaId, 
	Area, 
	CityId, 
	CityTitle, 
	StateId, 
	StateTitle, 
	CountryId, 
	CountryTitle, 
	GenderId, 
	Gender, 
	MaritalStatusId, 
	MaritalStatus, 
	SalutationId, 
	Salutation,
	TotalRecords
 FROM (
	SELECT 
		Row_Number() OVER(ORDER BY PM.Id) AS RowNumber,
		PM.Id  AS Id, 
		ISNULL(PatientNumber,  '') AS PId, 
		ISNULL(PatientName,  '') AS PatientName, 
		PM.FirstName AS FirstName, 
		PM.MiddleName AS MiddleName, 
		PM.LastName AS LastName, 
		ISNULL(IdM.Title,  '') AS IdProofType, 
		ISNULL(IdProofNumber,  '') AS IdProofNumber, 
		ISNULL(DateOfBirth,  '')  AS DateOfBirth, 
		--(CASE DateOfBirth 
		--          WHEN '1900-01-01 00:00:00.000' THEN ''
		--		  ELSE  ISNULL(DateOfBirth,  '')
		--END) DOB, 
		(CASE DateOfBirth 
		          WHEN '1900-01-01 00:00:00.000' THEN NULL
				  ELSE  ISNULL(DateOfBirth,  NULL)
		END) DOB,		
		ISNULL(PC.PhoneNumberMobile,  '') AS MobileNumber, 
		PC.PhoneNumberHome AS LandLine, 
		PC.EmailPrimary AS EmailId, 
		PA.StreetOne AS StreetOne, 
		PA.StreetTwo AS StreetTwo, 
		PA.StreetThree AS StreetThree, 
		PA.StreetFour AS StreetFour, 
		PA.ZipCode AS ZipCode, 
		PA.AreaId AS AreaId, 
		AM.Title AS Area, 
		AM.CityId AS CityId, 
		CM.Title AS CityTitle, 
		CM.StateId AS StateId, 
		SM.Title AS StateTitle, 
		SM.CountryId AS CountryId, 
		CountryMaster.Title AS CountryTitle, 
		PM.GenderId AS GenderId, 
		GM.Title AS Gender, 
		PM.MaritalStatusId AS MaritalStatusId, 
		MM.Title AS MaritalStatus, 
		PM.SalutationId AS SalutationId, 
		SalutationMaster.Title AS Salutation,
		COUNT(*) over() AS TotalRecords
		
		 FROM sRegistration.vExtPatientMaster PM
		 LEFT  JOIN sCommon.tIdProofTypeMaster IdM
		 ON PM.IdProofTypeId = IdM.Id
		 LEFT JOIN sRegistration.vExtPatientContact PC
		 ON PM.CommunicationContactId = PC.Id
		 LEFT JOIN sRegistration.vExtPatientAddress PA
		 ON PM.CommunicationAddressId = PA.Id
		 LEFT JOIN sCommon.tAreaMaster AM
		 ON PA.AreaId = AM.Id
		 LEFT JOIN sCommon.tCityMaster CM
		 ON AM.CityId = CM.Id
		 LEFT JOIN sCommon.tStateMaster SM
		 ON CM.StateId = SM.Id
		 LEFT JOIN sCommon.tCountryMaster CountryMaster
		 ON SM.CountryId = CountryMaster.Id
		 LEFT JOIN sCommon.tGenderMaster GM
		 ON PM.GenderId = GM.Id
		 LEFT JOIN sCommon.tMaritalStatusMaster MM
		 ON PM.MaritalStatusId = MM.Id
		 LEFT JOIN sCommon.tSalutationMaster SalutationMaster
		 ON PM.SalutationId =  SalutationMaster.Id
		 
		 
		 WHERE 
		    
		      ((PM.PatientNumber Like @rPId) OR (@rPId = ''))
			  AND ((PM.PatientName Like  @rPatientName)  OR (@rPatientName = ''))
			  AND ((PC.PhoneNumberMobile Like @rMobileNumber) OR(@rMobileNumber = ''))
			  AND (  
			        ((PM.IdProofTypeId Like @rProofIdType ) AND (PM.IdProofNumber Like @rProofIdNumber ))
			          OR ((@rProofIdType = '') AND (@rProofIdNumber = '' ))
			           OR ((PM.IdProofTypeId  Like @rProofIdType) AND (@rProofIdNumber = '' ))
			          )
			 
			  AND PM.IsObsolete = 0
			  
			  AND 
			      (
			     ( CAST(CONVERT(VARCHAR(10), PM.DateOfBirth, 101) AS DATETIME) =  CAST(CONVERT(VARCHAR(10),  @rDOB, 101) AS DATETIME) AND (@lDatePresent = 1))
			     OR
			     ( CAST(CONVERT(VARCHAR(10), ISNULL(PM.DateOfBirth, '1900-01-01'), 101) AS DATETIME) > =  CAST(CONVERT(VARCHAR(10), '1900-01-01', 101) AS DATETIME) AND (@lDatePresent = 0))
			      )
 		  
			  
			  
		) PS
		WHERE
	   PS.RowNumber >= CONVERT(varchar(9), @rStartIndex) AND PS.RowNumber <  CONVERT(varchar(9), @lUpperBound) 
	   ORDER BY  PS.Id DESC

--SELECT @lDatePresent

	--SELECT Top 1000 PM.Id  AS Id, 
	--	ISNULL(PatientNumber,  '') AS PId, 
	--	ISNULL(PatientName,  '') AS PatientName, 
	--	PM.FirstName AS FirstName, 
	--	PM.MiddleName AS MiddleName, 
	--	PM.LastName AS LastName, 
	--	ISNULL(IdM.Title,  '') AS IdProofType, 
	--	ISNULL(IdProofNumber,  '') AS IdProofNumber, 
	--	ISNULL(DateOfBirth,  '')  AS DateOfBirth, 
	--	--(CASE DateOfBirth 
	--	--          WHEN '1900-01-01 00:00:00.000' THEN ''
	--	--		  ELSE  ISNULL(DateOfBirth,  '')
	--	--END) DOB, 
	--	(CASE DateOfBirth 
	--	          WHEN '1900-01-01 00:00:00.000' THEN NULL
	--			  ELSE  ISNULL(DateOfBirth,  NULL)
	--	END) DOB, 
		
	--	ISNULL(PC.PhoneNumberMobile,  '') AS MobileNumber, 
	--	PC.PhoneNumberHome AS LandLine, 
	--	PC.EmailPrimary AS EmailId, 
	--	PA.StreetOne AS StreetOne, 
	--	PA.StreetTwo AS StreetTwo, 
	--	PA.StreetThree AS StreetThree, 
	--	PA.StreetFour AS StreetFour, 
	--	PA.ZipCode AS ZipCode, 
	--	PA.AreaId AS AreaId, 
	--	AM.Title AS Area, 
	--	AM.CityId AS CityId, 
	--	CM.Title AS CityTitle, 
	--	CM.StateId AS StateId, 
	--	SM.Title AS StateTitle, 
	--	SM.CountryId AS CountryId, 
	--	CountryMaster.Title AS CountryTitle, 
	--	PM.GenderId AS GenderId, 
	--	GM.Title AS Gender, 
	--	PM.MaritalStatusId AS MaritalStatusId, 
	--	MM.Title AS MaritalStatus, 
	--	PM.SalutationId AS SalutationId, 
	--	SalutationMaster.Title AS Salutation
		
	--	 FROM sRegistration.vExtPatientMaster PM
	--	 LEFT  JOIN sCommon.tIdProofTypeMaster IdM
	--	 ON PM.IdProofTypeId = IdM.Id
	--	 LEFT JOIN sRegistration.vExtPatientContact PC
	--	 ON PM.CommunicationContactId = PC.Id
	--	 LEFT JOIN sRegistration.vExtPatientAddress PA
	--	 ON PM.CommunicationAddressId = PA.Id
	--	 LEFT JOIN sCommon.tAreaMaster AM
	--	 ON PA.AreaId = AM.Id
	--	 LEFT JOIN sCommon.tCityMaster CM
	--	 ON AM.CityId = CM.Id
	--	 LEFT JOIN sCommon.tStateMaster SM
	--	 ON CM.StateId = SM.Id
	--	 LEFT JOIN sCommon.tCountryMaster CountryMaster
	--	 ON SM.CountryId = CountryMaster.Id
	--	 LEFT JOIN sCommon.tGenderMaster GM
	--	 ON PM.GenderId = GM.Id
	--	 LEFT JOIN sCommon.tMaritalStatusMaster MM
	--	 ON PM.MaritalStatusId = MM.Id
	--	 LEFT JOIN sCommon.tSalutationMaster SalutationMaster
	--	 ON PM.SalutationId =  SalutationMaster.Id
		 
		 
	--	 WHERE 
		    
	--	      ((PM.PatientNumber Like @rPId) OR (@rPId = ''))
	--		  AND ((PM.PatientName Like  @rPatientName)  OR (@rPatientName = ''))
	--		  AND ((PC.PhoneNumberMobile Like @rMobileNumber) OR(@rMobileNumber = ''))
	--		  AND (  
	--		        ((PM.IdProofTypeId Like @rProofIdType ) AND (PM.IdProofNumber Like @rProofIdNumber ))
	--		          OR ((@rProofIdType = '') AND (@rProofIdNumber = '' ))
	--		           OR ((PM.IdProofTypeId  Like @rProofIdType) AND (@rProofIdNumber = '' ))
	--		          )
			 
	--		  AND PM.IsObsolete = 0
			  
	--		  AND 
	--		      (
	--		     ( CAST(CONVERT(VARCHAR(10), PM.DateOfBirth, 101) AS DATETIME) =  CAST(CONVERT(VARCHAR(10),  @rDOB, 101) AS DATETIME) AND (@lDatePresent = 1))
	--		     OR
	--		     ( CAST(CONVERT(VARCHAR(10), ISNULL(PM.DateOfBirth, '1900-01-01'), 101) AS DATETIME) > =  CAST(CONVERT(VARCHAR(10), '1900-01-01', 101) AS DATETIME) AND (@lDatePresent = 0))
	--		      )
 		  
			  
			  
	--	ORDER BY  PM.Id DESC
		-- 00:00:00.000
		-- 00:00:00.000
---		SELECT sCommon.fSearchStringGet('shaiju')
--SELECT sCommon.fSearchStringGet('shaiju*')
--SELECT sCommon.fSearchStringGet('*shaiju')
--SELECT sCommon.fSearchStringGet('*shaiju*')


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPatientSearchLaboratoryGet]
	@rPId [nvarchar](20) = '',
	@rPatientName [nvarchar](30) = '',
	@rMobileNumber [nvarchar](20) = '',
	@rProofIdType [nvarchar](20) = '',
	@rProofIdNumber [nvarchar](20) = '',
	@rDOB [datetime] = '1/1/1900'
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lDatePresent Int 

SET @rPId = sCommon.fSearchStringGet(@rPId)
SET @rPatientName = sCommon.fSearchStringGet(@rPatientName)
SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber)
SET @rProofIdType = sCommon.fSearchStringGet(@rProofIdType)
SET @rProofIdNumber = sCommon.fSearchStringGet(@rProofIdNumber)


IF (CAST(@rDOB  AS DATE) =  CAST('1/1/1900' AS DATE))
BEGIN
  SET  @lDatePresent = 0
END
ELSE
BEGIN
  SET  @lDatePresent = 1
END

		SELECT DISTINCT PM.Id  AS Id,
		ISNULL(PM.PatientNumber, '') AS PId,
		ISNULL(PatientName, '') AS PatientName,
		PM.FirstName AS FirstName,
		PM.MiddleName AS MiddleName,
		PM.LastName AS LastName,
		ISNULL(IdM.Title, '') AS IdProofType,
		ISNULL(IdProofNumber, '') AS IdProofNumber,
		ISNULL(DateOfBirth, '')  AS DateOfBirth,
		(CASE DateOfBirth 
		          WHEN '1900-01-01 00:00:00.000' THEN NULL
				  ELSE  ISNULL(DateOfBirth, NULL)
		END) DOB,
		ISNULL(PC.PhoneNumberMobile, '') AS MobileNumber,
		PC.PhoneNumberHome AS LandLine,
		PC.EmailPrimary AS EmailId,
		PA.StreetOne AS StreetOne,
		PA.StreetTwo AS StreetTwo,
		PA.StreetThree AS StreetThree,
		PA.StreetFour AS StreetFour,
		PA.ZipCode AS ZipCode,
		PA.AreaId AS AreaId,
		AM.Title AS Area,
		AM.CityId AS CityId,
		CM.Title AS CityTitle,
		CM.StateId AS StateId,
		SM.Title AS StateTitle,
		SM.CountryId AS CountryId,
		CountryMaster.Title AS CountryTitle,
		PM.GenderId AS GenderId,
		GM.Title AS Gender,
		PM.MaritalStatusId AS MaritalStatusId,
		MM.Title AS MaritalStatus,
		PM.SalutationId AS SalutationId,
		SalutationMaster.Title AS Salutation,
		REG.RegStatus AS VisitType,
		REG.ServiceChargeTypeId AS PatientType
		

		 FROM sRegistration.vExtPatientMaster PM
		 LEFT JOIN sRegistration.vExtRegistration REG
		 ON PM.Id = REG.PatientId
		 LEFT  JOIN sCommon.tIdProofTypeMaster IdM
		 ON PM.IdProofTypeId = IdM.Id
		 LEFT JOIN sRegistration.vExtPatientContact PC
		 ON PM.CommunicationContactId = PC.Id
		 LEFT JOIN sRegistration.vExtPatientAddress PA
		 ON PM.CommunicationAddressId = PA.Id
		 LEFT JOIN sCommon.tAreaMaster AM
		 ON PA.AreaId = AM.Id
		 LEFT JOIN sCommon.tCityMaster CM
		 ON AM.CityId = CM.Id
		 LEFT JOIN sCommon.tStateMaster SM
		 ON CM.StateId = SM.Id
		 LEFT JOIN sCommon.tCountryMaster CountryMaster
		 ON SM.CountryId = CountryMaster.Id
		 LEFT JOIN sCommon.tGenderMaster GM
		 ON PM.GenderId = GM.Id
		 LEFT JOIN sCommon.tMaritalStatusMaster MM
		 ON PM.MaritalStatusId = MM.Id
		 LEFT JOIN sCommon.tSalutationMaster SalutationMaster
		 ON PM.SalutationId =  SalutationMaster.Id
		 INNER JOIN (SELECT DISTINCT PatientId, O.RegistrationId FROM  sRegistration.vExtRegistration R
								INNER JOIN sLaboratory.vExtOrder O
									ON  O.RegistrationId = R.Id) L
		 ON L.PatientId = PM.Id AND L.RegistrationId = REG.Id
		 
		 WHERE 
		       ((PM.PatientNumber Like @rPId) OR(@rPId = ''))
			AND ((PM.PatientName Like  @rPatientName)  OR (@rPatientName = ''))
			AND ((PC.PhoneNumberMobile Like @rMobileNumber) OR(@rMobileNumber = ''))
			AND (
			        ((PM.IdProofTypeId Like @rProofIdType )  AND (PM.IdProofNumber Like @rProofIdNumber ) )
			          OR ((@rProofIdType = '') AND (@rProofIdNumber = '' ))
			       )
	
			AND PM.IsObsolete = 0
	       
			
      AND 
			     
 		   (
			     ( CAST(PM.DateOfBirth AS DATE) =  CAST(@rDOB AS DATE) AND (@lDatePresent = 1))
			     OR
			     ( CAST(ISNULL(PM.DateOfBirth, '1900-01-01') AS DATE) > =  CAST('1900-01-01' AS DATE) AND (@lDatePresent = 0))
			      )
			       
		ORDER BY  PM.Id DESC



END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPatientSearchWithPatientTypeGet]
	@rPatientType [int] = 0,
	@rPatientNumber [nvarchar](100),
	@rIsNumeric [bit] = 0
WITH EXECUTE AS CALLER
AS
BEGIN
      SET NOCOUNT ON;
      
      
IF @rIsNumeric = 1
     BEGIN
     
     CREATE TABLE #tempPatient 
	( 
		PatientNumber VARCHAR(300) 
	)
     
     INSERT INTO #tempPatient SELECT PatientNumber FROM sRegistration.vExtPatientMaster WHERE 
		CONVERT(int, ([sCommon].[fGetExactSearch](PatientNumber)) ) = CONVERT(int, @rPatientNumber) AND (CHARINDEX('-', PatientNumber) > 0)
	SELECT 
			TOP 100 PM.Id  AS Id, 
            ISNULL(PM.PatientNumber, '') AS PId, 
            PM.PatientName,
            REG.Id AS RegId, 
            REG.RegStatus, 
            Reg.VisitCloseDate, 
            REG.VisitNumber, 
            REG.RegStatusId, 
            REG.ServiceChargeTypeId
    FROM sRegistration.vExtPatientMaster PM
	LEFT JOIN sRegistration.vExtRegistration REG ON PM.Id  =  REG.PatientId
    WHERE  PM.IsObsolete  =  0
			AND 
			(
			((@rPatientType  =  1 OR @rPatientType  =  0) AND (REG.ServiceChargeTypeId IN (1, 2) AND REG.RegStatusId IN (1, 2)))
				OR 
			(@rPatientType  =  2 AND (REG.ServiceChargeTypeId = 2 AND REG.RegStatusId = 1))
				OR 
			(@rPatientType  =  3 AND (REG.ServiceChargeTypeId  =  2 AND REG.RegStatusId IN (1, 2)))
				OR 
			(@rPatientType  =  4 AND (REG.ServiceChargeTypeId  =  2 AND REG.RegStatusId = 1))
			)
		AND REG.ID IN (SELECT MAX(Id) FROM sRegistration.vExtRegistration GROUP BY PatientId)
		AND PM.PatientNumber IN (SELECT PatientNumber FROM #tempPatient)
		
		DROP TABLE #tempPatient
END
ELSE
BEGIN

	CREATE TABLE #tempNpatient 
	( 
		PatientNumber VARCHAR(300) 
	)
     
     INSERT INTO #tempNpatient SELECT PatientNumber FROM sRegistration.vExtPatientMaster WHERE 
		PatientNumber = @rPatientNumber
	SELECT 
			TOP 100 PM.Id  AS Id, 
            ISNULL(PM.PatientNumber, '') AS PId, 
            PM.PatientName,
            REG.Id AS RegId, 
            REG.RegStatus, 
            Reg.VisitCloseDate, 
            REG.VisitNumber, 
            REG.RegStatusId, 
            REG.ServiceChargeTypeId
    FROM sRegistration.vExtPatientMaster PM
	LEFT JOIN sRegistration.vExtRegistration REG ON PM.Id  =  REG.PatientId
    WHERE  PM.IsObsolete  =  0
			AND 
			(
			((@rPatientType  =  1 OR @rPatientType  =  0) AND (REG.ServiceChargeTypeId IN (1, 2) AND REG.RegStatusId IN (1, 2)))
				OR 
			(@rPatientType  =  2 AND (REG.ServiceChargeTypeId = 2 AND REG.RegStatusId = 1))
				OR 
			(@rPatientType  =  3 AND (REG.ServiceChargeTypeId  =  2 AND REG.RegStatusId IN (1, 2)))
				OR 
			(@rPatientType  =  4 AND (REG.ServiceChargeTypeId  =  2 AND REG.RegStatusId = 1))
			)
		AND REG.ID IN (SELECT MAX(Id) FROM sRegistration.vExtRegistration GROUP BY PatientId)
		AND PM.PatientNumber IN (SELECT PatientNumber FROM #tempNpatient)
		
		DROP TABLE #tempNpatient
END




END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pPortalBatchSetupRemove]
     @rOrgGroupId int,
	 @rOrgGroupBatchId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lGroupBatchCount int
 SELECT @lGroupBatchCount = ISNULL(COUNT(id),0) FROM sSetup.tOrgGroupBatchMaster WHERE OrgGroupId = @rOrgGroupId

IF EXISTS (SELECT 1 FROM sSetup.tOrgGroupBatchMaster WHERE Id = @rOrgGroupBatchId AND IsActive = 1)
BEGIN
SELECT -101 AS Result -- Active Org Group Batch Can not be deleted
RETURN
END

IF EXISTS (SELECT 1 FROM sSetup.tOrgGroupBatchMaster OB INNER JOIN sSetup.tBatchMaster BM
ON OB.Id = BM.OrgGroupBatchId WHERE OB.Id = @rOrgGroupBatchId AND BM.IsActive = 1)
BEGIN
SELECT -102 AS Result -- Active Batch Can not be deleted
RETURN
END

IF (@lGroupBatchCount <= 1)
BEGIN
SELECT -103 AS Result -- Create new org group batch to delete old
RETURN
END


BEGIN

DELETE YR FROM sAttendance.tYearlyRegister YR
INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId

DELETE MR FROM sAttendance.tMonthlyRegister MR
INNER JOIN sStudent.tAcademic A ON MR.AcademicId = A.Id
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId

DELETE SR FROM sAttendance.tStudentRegister SR
INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId


DELETE CW FROM sAcademic.tClasswork CW
INNER JOIN sSetup.tBatchMaster BM ON CW.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId

DELETE AX FROM sActivity.tActivityParticipant AX
INNER JOIN sActivity.tActivity A ON AX.ActivityId = A.Id
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId

DELETE A  FROM sActivity.tActivity A
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId


DELETE EX FROM sActivity.tEventEnrollment  EX
INNER JOIN sActivity.tEventSchedule E ON EX.EventScheduleId = E.Id
INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId

DELETE EX FROM sActivity.tEventAssign  EX
INNER JOIN sActivity.tEventSchedule E ON EX.EventScheduleId = E.Id
INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId

DELETE ES FROM sActivity.tEventSchedule ES
INNER JOIN sSetup.tBatchMaster BM ON ES.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId


DELETE PX FROM sActivity.tPlacementInvite  PX
INNER JOIN sActivity.tPlacement P ON PX.PlacementId = P.Id
INNER JOIN sSetup.tBatchMaster BM ON P.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId

DELETE  P FROM sActivity.tPlacement P
INNER JOIN sSetup.tBatchMaster BM ON P.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId

DELETE AC FROM sActivity.tAssignClub AC
INNER JOIN sStudent.tAcademic  A ON AC.AcademicId = A.Id
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId


DELETE AX FROM sCommunication.tAssignmentScope AX
INNER JOIN sCommunication.tAssignment A ON AX.AssignmentId = A.Id
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId

DELETE AX FROM sCommunication.tAssignmentView AX
INNER JOIN sCommunication.tAssignment A ON AX.AssignmentId = A.Id
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId

DELETE A FROM sCommunication.tAssignment A
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId


DELETE B FROM sCommunication.tBehaviour B
INNER JOIN sStudent.tAcademic A ON B.AcademicId = A.Id
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId
 
DELETE BX FROM sCommunication.tBlogScope BX
INNER JOIN sCommunication.tBlog B ON BX.BlogId = B.Id
WHERE B.OrgGroupBatchId = @rOrgGroupBatchId

DELETE BX FROM sCommunication.tBlogComment BX
INNER JOIN sCommunication.tBlog B ON BX.BlogId = B.Id
WHERE B.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE BX FROM sCommunication.tBlogFavorite BX
INNER JOIN sCommunication.tBlog B ON BX.BlogId = B.Id
WHERE B.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE   FROM sCommunication.tBlog  WHERE  OrgGroupBatchId = @rOrgGroupBatchId 

DELETE CX FROM sCommunication.tCircularView CX
INNER JOIN sCommunication.tCircular C ON CX.CircularId = C.Id
WHERE C.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE CX FROM sCommunication.tCircularScope CX
INNER JOIN sCommunication.tCircular C ON CX.CircularId = C.Id
WHERE C.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE   FROM sCommunication.tCircular  WHERE  OrgGroupBatchId = @rOrgGroupBatchId


DELETE DX FROM sCommunication.tDiscussionComment DX
INNER JOIN sCommunication.tDiscussion D ON DX.DiscussionId = D.Id
INNER JOIN sSetup.tBatchMaster BM ON D.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId 


DELETE D  FROM   sCommunication.tDiscussion D
INNER JOIN sSetup.tBatchMaster BM ON D.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE NX FROM sCommunication.tNewsComment NX
INNER JOIN sCommunication.tNews N ON NX.NewsId = N.Id
WHERE N.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE NX FROM sCommunication.tNewsScope NX
INNER JOIN sCommunication.tNews N ON NX.NewsId = N.Id
WHERE N.OrgGroupBatchId = @rOrgGroupBatchId 


DELETE  FROM  sCommunication.tNews WHERE OrgGroupBatchId = @rOrgGroupBatchId



DELETE PX FROM sCommunication.tPollResult PX
INNER JOIN sCommunication.tPoll P ON PX.PollId = P.Id
WHERE P.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE PX FROM sCommunication.tPollMember PX
INNER JOIN sCommunication.tPoll P ON PX.PollId = P.Id
WHERE P.OrgGroupBatchId = @rOrgGroupBatchId 


DELETE PX FROM sCommunication.tPollAnswer PX
INNER JOIN sCommunication.tPoll P ON PX.PollId = P.Id
WHERE P.OrgGroupBatchId = @rOrgGroupBatchId 


DELETE FROM sCommunication.tPoll WHERE OrgGroupBatchId = @rOrgGroupBatchId 


DELETE QC FROM sCommunication.tQueryComment QC
INNER JOIN sCommunication.tQuery Q ON QC.QueryId = Q.Id
WHERE Q.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE  FROM sCommunication.tQuery WHERE OrgGroupBatchId = @rOrgGroupBatchId 


DELETE U FROM sCommunication.tUploadResult U
INNER JOIN sSetup.tBatchMaster BM ON U.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE U FROM sCommunication.tUploadBookLog U
INNER JOIN sSetup.tBatchMaster BM ON U.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE A FROM sStudent.tAcademic A
INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId 



DELETE BC FROM sSetup.tBatchClass BC INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id 
WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId 

DELETE FROM sSetup.tBatchMaster WHERE OrgGroupBatchId = @rOrgGroupBatchId

DELETE FROM sSetup.tOrgGroupBatchMaster WHERE Id = @rOrgGroupBatchId

SELECT 1 AS Result 

END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pPortalLeftStudentSetupRemove]
  
	 @rOrgGroupBatchId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN



IF EXISTS (SELECT 1 FROM sSetup.tOrgGroupBatchMaster WHERE Id = @rOrgGroupBatchId AND IsActive = 1)
BEGIN
RETURN -101 -- Active Org Group Batch Can not be deleted
END

IF EXISTS (SELECT 1 FROM sSetup.tOrgGroupBatchMaster OB INNER JOIN sSetup.tBatchMaster BM
ON OB.Id = BM.OrgGroupBatchId WHERE OB.Id = @rOrgGroupBatchId AND BM.IsActive = 1)
BEGIN
RETURN -102 -- Active Batch Can not be deleted
END

 --DELETE from sStudent.tStudentMaster WHERE OrgId = @rOrgId AND Id NOT IN
--(SELECT StudentId FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
--WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId)


-- DELETE FROM sSecurity.tUser WHERE OrgId = @rOrgId AND  SourceTypeId = 2003 AND SourceId
-- NOT IN (SELECT Id FROM sStudent.tStudentMaster WHERE OrgId = @rOrgId)

-- DELETE FROM sSecurity.tUserRole WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId AND UserId 
-- NOT IN (SELECT Id FROM sSecurity.tUser WHERE OrgId = @rOrgId)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPrefixConfigAdd]
	
	@rPrefixFunctionalityId int,
	@rSourceTypeId int,
	@rSourceId bigint,
	@rPrefix nvarchar(10),
	@rNumberLength int,
	@rOrgId smallint,
	@rScopeSourceTypeId smallint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO sCommon.tPrefixConfig
		(
			PrefixFunctionalityId,
			SourceTypeId,
			SourceId,
			Prefix,
			NumberLength,
			OrgId,
			ScopeSourceTypeId
		)
	VALUES
		(
			@rPrefixFunctionalityId,
			@rSourceTypeId,
			@rSourceId,
			@rPrefix,
			@rNumberLength,
			@rOrgId,
			@rScopeSourceTypeId
		)
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPrefixConfigGet]
	
	@rOrgId int,
	@rPrefixFunctionalityId int,
	@rSourceTypeId int,
	@rOrgGroupId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
	  IF @rPrefixFunctionalityId = 2007 -- Student
	  BEGIN
		IF @rSourceTypeId = 2021 -- Organization
		BEGIN
			 SELECT 
				SourceId,
				ISNULL(Prefix,'') AS Prefix,
				ISNULL(NumberLength,0) AS NumberLength
			 FROM 
			 sCommon.tPrefixConfig
			 WHERE SourceId = @rOrgId AND SourceTypeId = 2021 AND PrefixFunctionalityId = @rPrefixFunctionalityId
		END
		
		IF @rSourceTypeId = 2017 -- Department
		BEGIN
			 SELECT 
				DM.Title AS DepartmentName,
				DM.Id AS DepartmentId,				
				ISNULL(PC.Prefix,'') AS Prefix,
				ISNULL(PC.NumberLength,0) AS NumberLength
			 FROM 
			 sSetup.tDepartmentMaster DM
			 LEFT JOIN sCommon.tPrefixConfig PC ON DM.Id = PC.SourceId AND PC.SourceTypeId = 2017 AND PrefixFunctionalityId = @rPrefixFunctionalityId
			 WHERE DM.OrgId = @rOrgId
		END
	  END
	  
	  IF @rPrefixFunctionalityId = 2008 -- Employee
	  BEGIN
	    IF @rSourceTypeId = 2021 -- Organization
		BEGIN
			 SELECT 
				SourceId,
				ISNULL(Prefix,'') AS Prefix,
				ISNULL(NumberLength,0) AS NumberLength
			 FROM 
			 sCommon.tPrefixConfig
			WHERE SourceId = @rOrgId AND SourceTypeId = 2021 AND PrefixFunctionalityId = @rPrefixFunctionalityId
		END
		
		IF @rSourceTypeId = 2017 -- Department
		BEGIN
			 SELECT 
				DM.Title AS DepartmentName,
		
		DM.Id AS DepartmentId,
				ISNULL(PC.Prefix,'') AS Prefix,
				ISNULL(PC.NumberLength,0) AS NumberLength
			 FROM 
			 sSetup.tDepartmentMaster DM
			 LEFT JOIN sCommon.tPrefixConfig PC ON DM.Id = PC.SourceId AND PC.SourceTypeId = 2017 AND PrefixFunctionalityId = @rPrefixFunctionalityId
			 WHERE DM.OrgId = @rOrgId
		END
	  
		--IF @rSourceTypeId = 2025 -- Employee Type
		--BEGIN
		--	 SELECT 
		--		ETM.Title AS EmployeeTypeName,
		--		ETM.Id AS EmployeeTypeId,
		--		ISNULL(PC.Prefix,'') AS Prefix,
		--		ISNULL(PC.NumberLength,0) AS NumberLength
		--	 FROM 
		--	 sHrm.tEmployeeTypeMaster ETM
		--	 LEFT JOIN sCommon.tPrefixConfig PC ON ETM.Id = PC.SourceId AND PC.SourceTypeId = 2025 AND PrefixFunctionalityId = @rPrefixFunctionalityId
		--	 WHERE ETM.OrgId = @rOrgId
		--END
	  END
	  
	  IF @rPrefixFunctionalityId = 2009 -- Organization
	  BEGIN
		IF @rSourceTypeId = 2021 -- Organization
		BEGIN
			 SELECT 
				OM.Title AS OrgName,
				OM.Id AS OrgId,
				ISNULL(PC.Prefix,'') AS Prefix,
				ISNULL(PC.NumberLength,0) AS NumberLength,
				ISNULL(PC.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
				'' AS LastSUIdNo
			 FROM 
			 sSetup.tOrganizationMaster OM
			 LEFT JOIN sCommon.tPrefixConfig PC ON OM.Id = PC.SourceId AND PC.SourceTypeId = 2021 AND PrefixFunctionalityId = @rPrefixFunctionalityId
			 WHERE OM.OrgGroupId = @rOrgGroupId
		END
	  END


	   IF @rPrefixFunctionalityId = 2013 -- Admission Inquiry
		BEGIN
		IF @rSourceTypeId = 2021 -- Organization
		BEGIN
			 SELECT 
				SourceId,
				ISNULL(Prefix,'') AS Prefix,
				ISNULL(NumberLength,0) AS NumberLength
			 FROM 
			 sCommon.tPrefixConfig
			 WHERE SourceId = @rOrgId AND SourceTypeId = 2021 AND PrefixFunctionalityId = @rPrefixFunctionalityId
		END
	  END
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPrefixFunctionalityGet]
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			TitleResourceKeyId,
			Remark
	   FROM sCommon.tPrefixFunctionality
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommon].[pPrefixSetupAdd]
	@rOrgId [smallint],
	@rPrefixFunctionalityId [int],
	@rPrefix [nvarchar](10),
	@rEffectiveDate [datetime],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rSpecifiedPrefixLength [int],
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

    DECLARE @rSeriesTypeId INT
		
   select  @rSeriesTypeId = SeriesTypeId From sCommon.tPrefixFunctionality Where Id =  @rPrefixFunctionalityId

	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tPrefixSetup', 0, 1, 1,@outNextNumber = @lNextNumber output

	IF NOT EXISTS (SELECT 1 FROM sCommon.tPrefixSetup WHERE StoreLocationId = @rStoreLocationId AND Prefix = @rPrefix AND OrgId = @rOrgId AND PrefixFunctionalityId = @rPrefixFunctionalityId)
	BEGIN
	INSERT INTO sCommon.tPrefixSetup
		(
			OrgId,
			Id,		
			PrefixFunctionalityId,			
			Prefix,
			EffectiveDate,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime, 
			NumberLength,
			StoreLocationId
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rPrefixFunctionalityId,
			@rPrefix,
			@rEffectiveDate,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rSpecifiedPrefixLength,
			CASE @rSeriesTypeId 
			   WHEN 3 THEN @rStoreLocationId
			   WHEN 2 THEN 0
			   WHEN 1 THEN 0
			  END
		)
		END
		SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPrefixSetupCurrentNumberModify]
	@rId [int],
	@rNextNumber [int] OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

UPDATE sCommon.tPrefixSetup
SET @rNextNumber = CurrentNumber 
				 = (CASE WHEN CurrentNumber IS NULL OR CurrentNumber = 0
					    THEN ISNULL(Seed, 1)
				   ELSE CurrentNumber + 1 END),
	Seed = ISNULL(Seed, 1),
	NumberLength = ISNULL(NumberLength, 7)
WHERE Id = @rId

RETURN ISNULL(@rNextNumber, 0)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPrefixSetupGet]
	@rOrgId [smallint] = 0,
	@rId [int] = 0,
	@rPrefix [nvarchar](10) = '',
	@rPrefixFunctionalityId [int] = 0,
	@rIsIncludeObsoleted [bit] = 1,
	@rStoreLocationId int  = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rPrefix = sCommon.fSearchStringGet(@rPrefix)

	 SELECT ISNULL(PS.Id,0) AS Id, 
			ISNULL(PF.Id,0) AS PrefixFunctionalityId, 
			ISNULL(PS.Prefix,'') AS Prefix, 
			--(CONVERT(NVARCHAR(12), PS.EffectiveDate, 101)) AS EffectiveDate, 
			ISNULL(PS.EffectiveDate,sCommon.fGetDate()) AS EffectiveDate,
			ISNULL(PS.IsObsolete,0) AS IsObsolete, 
			ISNULL(PF.Title,'') AS Title, 
			ISNULL(PS.NumberLength,0) AS SpecifiedPrefixLength, 
			ISNULL(PF.NumberMaxLength,0) AS MaxPrefixLength, 
			ISNULL(PS.Prefix +  CONVERT(NVARCHAR(10), ISNULL(PS.CurrentNumber, 0)),'') AS CurrentPrefix
	   FROM sCommon.tPrefixFunctionality PF		
	   LEFT JOIN sCommon.tPrefixSetup   PS	  
	   ON PS.PrefixFunctionalityId = PF.Id AND (PS.StoreLocationId = @rStoreLocationId OR PS.StoreLocationId=0) AND PS.OrgId = @rOrgId AND PF.IsObsolete=0
	   
	   WHERE  PF.IsObsolete = 0 AND	   
	         ISNULL(PS.IsObsolete,0) = (CASE WHEN @rIsIncludeObsoleted = 1 THEN PS.IsObsolete ELSE 0 END)
			 AND ((PS.Id = @rId) OR (@rId = 0)) 
	         AND ((PS.Prefix LIKE @rPrefix) OR (@rPrefix = '')) 
	         AND ((PS.PrefixFunctionalityId = @rPrefixFunctionalityId) OR (@rPrefixFunctionalityId = 0)) 
	         AND (ISNULL(PS.EffectiveDate,sCommon.fGetDate()) <= (CASE WHEN @rPrefixFunctionalityId > 0 THEN (sCommon.fGetDate()) ELSE (ISNULL(PS.EffectiveDate,sCommon.fGetDate())) END)) 
	         AND PF.Id not in (27,1005,1004,1006,26,52,53,1007)
	          --AND PS.OrgId = @rOrgId
	         --AND (PS.StoreLocationid = @rStoreLocationId )OR (@rStoreLocationId = 0)
	         order by PF.Title
	         
	         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommon].[pPrefixSetupModify]
	@rId [int],
	@rPrefixFunctionalityId [int],
	@rPrefix [nvarchar](10),
	@rEffectiveDate [datetime],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rSpecifiedPrefixLength [int],
	@rStoreLocationId int=0,
	@rOrgId smallint=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tPrefixSetup
		SET 
			PrefixFunctionalityId = @rPrefixFunctionalityId,
			Prefix = @rPrefix,
			EffectiveDate = @rEffectiveDate,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(), 
			NumberLength = @rSpecifiedPrefixLength,
			StoreLocationId = @rStoreLocationId,
			OrgId = @rOrgId
	  WHERE Id = @rId
	  SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPrefixSetupNextNumberForPatientMasterGet]
	@rPrefixFunctionalityId [smallint],
	@rPatientId [int],
	@rNextNumber [nvarchar](100) OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
DECLARE @lPrefixSetupId SmallInt
DECLARE @lPrefix Nvarchar(10)
DECLARE @loNextId Int
DECLARE @lNumberLength TinyInt
DECLARE @lServiceChargeTypeId TinyInt

SELECT @lPrefixSetupId = Id, 
	   @lPrefix = Prefix, 
	   @lNumberLength = ISNULL(NumberLength, 7)
  FROM sCommon.tPrefixSetup
 WHERE PrefixFunctionalityId = @rPrefixFunctionalityId
	   AND IsObsolete = 0
	   AND EffectiveDate = (SELECT MAX(EffectiveDate)
							  FROM sCommon.tPrefixSetup
							 WHERE PrefixFunctionalityId = @rPrefixFunctionalityId
								   AND IsObsolete = 0
								   AND EffectiveDate <= sCommon.fGetDate())
								   
--EXECUTE sCommon.pPrefixSetupCurrentNumberModify @rId = @lPrefixSetupId, @rNextNumber = @loNextId OUTPUT
SET @lServiceChargeTypeId = (CASE @rPrefixFunctionalityId 
							  WHEN 4 THEN 2 
							  WHEN 6 THEN 1
						 END)
EXECUTE sRegistration.pPatientMasterCurrentNumberModify @rId = @rPatientId, 
		@rServiceChargeTypeId = @lServiceChargeTypeId, 
		@rNextNumber = @loNextId OUTPUT
				     		   
SET @loNextId = ISNULL(@loNextId, 1)
SET @rNextNumber = sCommon.fNumberStringGet(@lPrefix, @lNumberLength, @loNextId)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPrefixSetupNextNumberGet]
	@rOrgId smallint=0,
	@rPrefixFunctionalityId [int],
	@rStoreLocationId [int],
	@rNextNumber [nvarchar](100) OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
   
DECLARE @lPrefixSetupId bigint  
DECLARE @lPrefix Nvarchar(10)  
DECLARE @loNextId bigint  
DECLARE @lNumberLength TinyInt  
  
SELECT @lPrefixSetupId = PS.Id,   
    @lPrefix = Prefix,   
    @lNumberLength = ISNULL(NumberLength, 7)  
  FROM sCommon.tPrefixSetup PS 
   
 WHERE PrefixFunctionalityId = @rPrefixFunctionalityId  
    AND PS.IsObsolete = 0 
    --AND Ps.OrgId =  @rOrgId
    AND PS.StoreLocationId = @rStoreLocationId
    AND EffectiveDate = (SELECT MAX(EffectiveDate)  
         FROM sCommon.tPrefixSetup  
        WHERE PrefixFunctionalityId = @rPrefixFunctionalityId 
           --AND OrgId =  @rOrgId 
           AND IsObsolete = 0  
           AND StoreLocationId=@rStoreLocationId
           AND EffectiveDate <= sCommon.fGetDate()
           )  
 
             
EXECUTE sCommon.pPrefixSetupCurrentNumberModify @rId = @lPrefixSetupId, @rNextNumber = @loNextId OUTPUT  
   
--SELECT @lPrefix, @lNumberLength, @loNextId  
SET @rNextNumber = sCommon.fNumberStringGet(@lPrefix, @lNumberLength, @loNextId)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPriorityMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			TitleResourceKeyId
	   FROM sCommon.tPriorityMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPublicHolidayGet]
	@rHolidayDate [date] = '1/1/1900'
WITH EXECUTE AS CALLER
AS
BEGIN

SET NOCOUNT ON

IF Exists(SELECT Id FROM sCommon.tPublicHolidayMaster WHERE HolidayDate = @rHolidayDate)
	SELECT Result = 1
ELSE
	SELECT Result = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPublicHolIdayMasterAdd]
	@rHolidayTypeId [smallint],
	@rTitle [nvarchar](100),
	@rHolidayDate [datetime],
	@rReason [nvarchar](50),
	@rIsObsolete [bit],
	@rCreatedBy [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 'sCommon.tPublicHolIdayMaster', 0, 101, 1,@outNextNumber = @lNextNumber output
	--SELECT @lNextNumber
	DECLARE @lUserId INT
	SET @lUserId = 0

	SELECT @lUserId = Id
	FROM sCommon.tPublicHolIdayMaster
	WHERE IsObsolete = 0
	INSERT INTO sCommon.tPublicHolIdayMaster
		(
			Id,
			HolidayTypeId,
			Title,
			HolidayDate,
			Reason,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rHolidayTypeId,
			@rTitle,
			@rHolidayDate,
			@rReason,
			@rIsObsolete,
			@rCreatedBy,
			sCommon.fGetDate(),
			@rCreatedBy,
			sCommon.fGetDate()
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPublicHolIdayMasterGet]
	@rId [int] = 0,
	@rHolName [nvarchar](100) = '',
	@rTypeId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
SET @rHolName = sCommon.fSearchStringGet(@rHolName)

	 SELECT A.Id AS Id,
			A.HolidayTypeId AS HolidayTypeId,
			A.Title AS Title,
			A.HolidayDate AS HolidayDate,
			A.Reason AS Reason,
			A.IsObsolete AS IsObsolete,
			A.CreatedUserId AS CreatedBy,
			A.CreatedDateTime AS CreatedDate,
			A.UpdatedUserId AS UpdatedBy,
			A.UpdatedDateTime AS UpdatedDate,
			 M.Title AS TypeTitle
	   FROM sCommon.tPublicHolIdayMaster AS A INNER JOIN
       sCommon.tPublicHolIdayTypeMaster M ON 
       A.HolidayTypeId = M.Id
	  WHERE ((A.Id = @rId) OR (@rId = 0)) AND ((M.Id = @rTypeId) OR (@rTypeId = 0)) AND ((A.Title LIKE @rHolName) OR (@rHolName = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPublicHolIdayMasterModify]
	@rId [int],
	@rHolidayTypeId [smallint],
	@rTitle [nvarchar](100),
	@rHolidayDate [datetime],
	@rReason [nvarchar](50),
	@rIsObsolete [bit],
	@rUpdatedBy [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tPublicHolIdayMaster
		SET 
			HolidayTypeId = @rHolidayTypeId,
			Title = @rTitle,
			HolidayDate = @rHolidayDate,
			Reason = @rReason,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedBy,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pPublicHolIdayTypeMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title
	   FROM sCommon.tPublicHolIdayTypeMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pPublishDocumentMasterAdd] 
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select 1 from sCommon.tPublishDocumentMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select 1 from sCommon.tPublishDocumentMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
	
	END
	ELSE
	BEGIN
		If Exists(select 1 from sCommon.tPublishDocumentMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If Exists(select 1 from sCommon.tPublishDocumentMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END
		

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tPublishDocumentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO sCommon.tPublishDocumentMaster
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommon.tPublishDocumentMaster
	    SET
	          Code=@rCode
	         ,Title=@rTitle
             ,IsObsolete = @rIsObsolete                          
             ,UpdatedUserId = @rCreatedUserId
             ,UpdatedDateTime = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pPublishDocumentMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId smallint
AS
SET NOCOUNT ON

	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN

	SELECT PDM.Id 
		  ,PDM.Code
		  ,PDM.Title AS Name
		  ,PDM.IsObsolete
		  ,OrgGroupId
     
	  FROM sCommon.tPublishDocumentMaster PDM
     
	  WHERE 
			((PDM.Id = @rId) OR (@rId = 0))
		AND ((PDM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
		AND ((PDM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND (PDM.OrgGroupId = @rOrgGroupId)

	UNION

	SELECT PDM.Id 
		  ,PDM.Code
		  ,PDM.Title AS Name
		  ,PDM.IsObsolete
		  ,OrgGroupId
     
	  FROM sCommon.tPublishDocumentMaster PDM
     
	  WHERE 
			((PDM.Id = @rId) OR (@rId = 0))
		AND ((PDM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
		AND ((PDM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND (PDM.OrgGroupId IS NULL)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionAnswerMasterAdd]
	@rAnswerTypeId [smallint],
	@rQuestionAnswerMasterDetailXml [nvarchar](max),
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
	DECLARE @loIdoc INT
	DECLARE @lQuestionAnswerMasterCurrentId INT
	DECLARE @lCount INT
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rQuestionAnswerMasterDetailXml
	EXEC sCommon.pTableRowIdGet  'sCommon.tQuestionAnswerMaster', 1, 1, 1,@outNextNumber = @lQuestionAnswerMasterCurrentId output
	
	INSERT INTO sCommon.tQuestionAnswerMaster
		(
			Id,
			AnswerTypeId,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	SELECT  
		@lQuestionAnswerMasterCurrentId + ROW_NUMBER() OVER(ORDER BY AnswerTypeId) AS Id, 
		@rAnswerTypeId,
		Title,
		IsObsolete,
		CreatedUserId,
		sCommon.fGetDate(),
		CreatedUserId,
		sCommon.fGetDate()
	FROM OPENXML (@loIdoc, '/AnswerType/QuestionAnswerDetail', 1)
		WITH ( 
				
				AnswerTypeId INT, 
				Title NVARCHAR(200),
				IsObsolete BIT,
				CreatedUserId BIGINT
			  ) 
		
		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/AnswerType/QuestionAnswerDetail', 1)
				 WITH ( AnswerTypeId INT)
		SET @lQuestionAnswerMasterCurrentId  = @lCount + @lQuestionAnswerMasterCurrentId 
		
		EXECUTE sCommon.pTableRowIdModify @rTableTitle = 'sCommon.tQuestionAnswerMaster', @rCurrentNumber = @lQuestionAnswerMasterCurrentId 
		SELECT Result = @rAnswerTypeId
		END TRY
		BEGIN CATCH
		SELECT Result = -1, ERROR_MESSAGE(), ERROR_LINE()
		END CATCH
	
END


--DECLARE @lNextNumber INT
	--EXECUTE @lNextNumber = sCommon.pTableRowIdGet 'sCommon.tQuestionAnswerMaster', 0, 1, 1

	--INSERT INTO sCommon.tQuestionAnswerMaster
	--	(
	--		Id,
	--		AnswerTypeId,
	--		Title,
	--		IsObsolete,
	--		CreatedUserId,
	--		CreatedDateTime,
	--		UpdatedUserId,
	--		UpdatedDateTime
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		@rAnswerTypeId,
	--		@rTitle,
	--		@rIsObsolete,
	--		@rCreatedUserId,
	--		sCommon.fGetDate(),
	--		@rCreatedUserId,
	--		sCommon.fGetDate()
	--	)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionAnswerMasterGet]
	@rId [smallint] = 0,
	@rAnswerTypeId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			AnswerTypeId,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sCommon.tQuestionAnswerMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
	  AND ((AnswerTypeId = @rAnswerTypeId) OR (@rAnswerTypeId = 0))
	  AND IsObsolete = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionAnswerMasterModify]
	@rAnswerTypeId [smallint],
	@rQuestionAnswerMasterXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @loIdoc INT
	
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rQuestionAnswerMasterXml

	  UPDATE sCommon.tQuestionAnswerMaster
		SET 
			IsObsolete = XmlTable.IsObsolete,
			UpdatedUserId = XmlTable.UpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()			
		FROM OPENXML (@loIdoc, '/AnswerType/QuestionAnswerDetail', 1)
				 WITH ( 
						IsObsolete BIT,
						UpdatedUserId BIGINT,
						Id INT
					  ) XmlTable
			INNER JOIN sCommon.tQuestionAnswerMaster QAM
				ON	QAM.Id = XmlTable.Id 
			 WHERE XmlTable.Id > 0 
	 
END

--UPDATE sCommon.tQuestionAnswerMaster
		--SET 
		--	AnswerTypeId = @rAnswerTypeId,
		--	Title = @rTitle,
		--	IsObsolete = @rIsObsolete,
		--	UpdatedUserId = @rUpdatedUserId,
		--	UpdatedDateTime = sCommon.fGetDate()
	 -- WHERE Id = @rId

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionAnswerMasterRemove]
	@rId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tQuestionAnswerMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionAnswerResultMappingAdd]
	@rQuestionId [smallint],
	@rQuestionAnswerResultMappingDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
	DECLARE @loIdoc INT
	DECLARE @lQuestionAnswerResultMappingCurrentId INT
	DECLARE @lCount INT
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rQuestionAnswerResultMappingDetailXml
	EXEC sCommon.pTableRowIdGet  'sCommon.tQuestionAnswerResultMapping', 1, 1, 1,@outNextNumber = @lQuestionAnswerResultMappingCurrentId output
	
	INSERT INTO sCommon.tQuestionAnswerResultMapping
		(
			Id,
			QuestionId,
			QuestionAnswerId,
			AnswerResultId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	SELECT  
		@lQuestionAnswerResultMappingCurrentId + ROW_NUMBER() OVER(ORDER BY QuestionAnswerId) AS Id, 
		@rQuestionId,
		QuestionAnswerId,
		AnswerResultId,
		IsObsolete,
		CreatedUserId,
		sCommon.fGetDate(),
		CreatedUserId,
		sCommon.fGetDate()
	FROM OPENXML (@loIdoc, '/QuestionMaster/QuestionAnswerResultMapping', 1)
		WITH ( 
				QuestionAnswerId INT,
				AnswerResultId INT, 
				IsObsolete BIT,
				CreatedUserId BIGINT
			  ) 
		
		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/QuestionMaster/QuestionAnswerResultMapping', 1)
				 WITH ( QuestionAnswerId INT)
		SET @lQuestionAnswerResultMappingCurrentId  = @lCount + @lQuestionAnswerResultMappingCurrentId 
		
		EXECUTE sCommon.pTableRowIdModify @rTableTitle = 'sCommon.tQuestionAnswerResultMapping', @rCurrentNumber = @lQuestionAnswerResultMappingCurrentId 
		SELECT Result = @rQuestionId
		END TRY
		BEGIN CATCH
		SELECT Result = -1, ERROR_MESSAGE(), ERROR_LINE()
		END CATCH
	
END


--DECLARE @lNextNumber INT
--	EXECUTE @lNextNumber = sCommon.pTableRowIdGet 'sCommon.tQuestionAnswerResultMapping', 0, 1, 1

--	INSERT INTO sCommon.tQuestionAnswerResultMapping
--		(
--			Id,
--			QuestionId,
--			QuestionAnswerId,
--			AnswerResultId,
--			IsObsolete,
--			CreatedUserId,
--			CreatedDateTime,
--			UpdatedUserId,
--			UpdatedDateTime
--		)
--	VALUES
--		(
--			@lNextNumber,
--			@rQuestionId,
--			@rQuestionAnswerId,
--			@rAnswerResultId,
--			@rIsObsolete,
--			@rCreatedUserId,
--			sCommon.fGetDate(),
--			@rCreatedUserId,
--			sCommon.fGetDate()
--		)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionAnswerResultMappingGet]
	@rId [smallint] = 0,
	@rQuestionId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT QARM.Id,
			QARM.QuestionId,
			QARM.QuestionAnswerId,
			QAM.Title AS QuestionAnswerMasterTitle,
			QARM.AnswerResultId,
			ARM.Title AS AnswerResultMasterTitle,
			QARM.IsObsolete,
			QARM.CreatedUserId,
			QARM.CreatedDateTime,
			QARM.UpdatedUserId,
			QARM.UpdatedDateTime
	   FROM sCommon.tQuestionAnswerResultMapping QARM
	   INNER JOIN sCommon.tQuestionAnswerMaster QAM ON QAM.Id = QARM.QuestionAnswerId
	   INNER JOIN sCommon.tAnswerResultMaster ARM ON ARM.Id = QARM.AnswerResultId
	  WHERE ((QARM.Id = @rId) OR (@rId = 0))
	  AND ((QARM.QuestionId = @rQuestionId) OR (@rQuestionId = 0))
	  AND QARM.IsObsolete = 0 AND QAM.IsObsolete = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionAnswerResultMappingModify]
	@rQuestionId [smallint],
	@rQuestionAnswerResultMappingXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @loIdoc INT
	
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rQuestionAnswerResultMappingXml

	  UPDATE sCommon.tQuestionAnswerResultMapping
		SET 
			AnswerResultId = XmlTable.AnswerResultId,
			UpdatedUserId = XmlTable.UpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()			
		FROM OPENXML (@loIdoc, '/QuestionMaster/QuestionAnswerResultMapping', 1)
				 WITH ( 
						AnswerResultId INT,
						UpdatedUserId BIGINT,
						Id INT
					  ) XmlTable
			INNER JOIN sCommon.tQuestionAnswerResultMapping QAM
				ON	QAM.Id = XmlTable.Id 
			 WHERE XmlTable.Id > 0 
	 
END

--UPDATE sCommon.tQuestionAnswerResultMapping
		--SET 
		--	QuestionId = @rQuestionId,
		--	QuestionAnswerId = @rQuestionAnswerId,
		--	AnswerResultId = @rAnswerResultId,
		--	IsObsolete = @rIsObsolete,
		--	UpdatedUserId = @rUpdatedUserId,
		--	UpdatedDateTime = sCommon.fGetDate()
	 -- WHERE Id = @rId

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionAnswerResultMappingRemove]
	@rId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tQuestionAnswerResultMapping
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionFunctionalityMasterAdd]
	@rTitle [nvarchar](20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet 'sCommon.tQuestionFunctionalityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tQuestionFunctionalityMaster
		(
			Id,
			Title
		)
	VALUES
		(
			@lNextNumber,
			@rTitle
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionFunctionalityMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title
	   FROM sCommon.tQuestionFunctionalityMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionFunctionalityMasterModify]
	@rId [tinyint],
	@rTitle [nvarchar](20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tQuestionFunctionalityMaster
		SET 
			Title = @rTitle
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionMasterAdd]
	@rQuestionFunctionalityId [tinyint],
	@rRemark [nvarchar](300),
	@rAnswerTypeId [smallint],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rQuestionAnswerResultMappingDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet 'sCommon.tQuestionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tQuestionMaster
		(
			Id,
			QuestionFunctionalityId,
			Remark,
			AnswerTypeId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rQuestionFunctionalityId,
			@rRemark,
			@rAnswerTypeId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		
		EXECUTE sCommon.pQuestionAnswerResultMappingAdd @lNextNumber, @rQuestionAnswerResultMappingDetailXml
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionMasterGet]
	@rId [smallint] = 0,
	@rQuestionFunctionalityId [smallint] = 0,
	@rRemark [nvarchar](300) = '',
	@rIsWildCardSearch [bit] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lQuestionMasterId INT 

	 SELECT QM.Id,
			QM.QuestionFunctionalityId,
			QM.Remark,
			QM.AnswerTypeId,
			ATM.Title AS AnswerTypeTitle,
			QM.IsObsolete,
			QM.CreatedUserId,
			QM.CreatedDateTime,
			QM.UpdatedUserId,
			QM.UpdatedDateTime
	   FROM sCommon.tQuestionMaster QM
	   INNER JOIN sCommon.tAnswerTypeMaster ATM ON ATM.Id = QM.AnswerTypeId
	  WHERE ((QM.Id = @rId) OR (@rId = 0))
	  --AND QM.IsObsolete = 0
	  AND ((QM.Remark LIKE @rRemark) OR (@rRemark = ''))
	  AND ((QM.QuestionFunctionalityId = @rQuestionFunctionalityId) OR (@rQuestionFunctionalityId = 0))
	  
	  IF @rIsWildCardSearch = 0
	  BEGIN
		  IF EXISTS(SELECT 1 FROM sCommon.tQuestionMaster WHERE ((Id = @rId) OR (@rId = 0)) AND ((Remark LIKE @rRemark) OR (@rRemark = '')))
		  BEGIN
			SELECT @lQuestionMasterId = Id FROM sCommon.tQuestionMaster WHERE ((Id = @rId) OR (@rId = 0)) AND ((Remark LIKE @rRemark) OR (@rRemark = ''))
			EXECUTE sCommon.pQuestionAnswerResultMappingGet 0, @lQuestionMasterId
			EXECUTE sCommon.pAnswerTypeForQuestionMasterGet @lQuestionMasterId 
		  END
	  END
	  ELSE
	  BEGIN
		EXECUTE sCommon.pQuestionAnswerResultMappingGet 0, @rId
		
		EXECUTE sCommon.pAnswerTypeForQuestionMasterGet @rId 
		END
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionMasterModify]
	@rId [smallint],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rQuestionAnswerResultMappingXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
	 UPDATE sCommon.tQuestionMaster
		SET 
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  
	  IF @rQuestionAnswerResultMappingXml <> ''
	  BEGIN
		EXECUTE sCommon.pQuestionAnswerResultMappingModify @rId, @rQuestionAnswerResultMappingXml
	  END
	  SELECT Result = @rId
	  END TRY
	  
	  BEGIN CATCH
	  SELECT Result = -1
	  END CATCH
	  
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pQuestionMasterRemove]
	@rId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tQuestionMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReasonMasterAdd]
	@rTitle [nvarchar](100),
	@rCreatedUserId [bigint],
	@rIsObsolete [bit],
	@rRemark [nvarchar](100),
	@rReasonCategoryId [tinyint],
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sCommon.tReasonMaster WHERE UPPER(Title) = UPPER(@rTitle) AND ReasonCategoryId = @rReasonCategoryId AND OrgGroupId = @rOrgGroupId )

BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tReasonMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tReasonMaster
		(
			Id,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime,
			Remark,
			ReasonCategoryId,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rRemark,
			@rReasonCategoryId,
			@rOrgGroupId
		)
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReasonMasterGet]
	@rId [int] = 0,
	@rTitle [nvarchar](20) = '',
	@rRemark [nvarchar](100) = '',
	@rReasonCategoryId [int] = 0,
	@rOrgGroupId int,
	@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	IF @rIsWildCardSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
		
	SET @rRemark = sCommon.fSearchStringGet(@rRemark)


	 SELECT M.Id,
			M.Title,
			M.CreatedUserId,
			M.CreatedDateTime,
			M.IsObsolete,
			M.UpdatedUserId,
			M.UpdatedDateTime,
			M.Remark,
			M.ReasonCategoryId,
			C.Title AS ReasonCategory
	   FROM sCommon.tReasonMaster M INNER JOIN sCommon.tReasonCategoryMaster C
	   ON M.ReasonCategoryId = c.Id
	  WHERE ((M.Id = @rId) OR (@rId = 0))
	   AND ((M.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((M.Remark LIKE @rRemark ) OR (ISNULL(@rRemark, '') = ''))
	   AND ((M.ReasonCategoryId = @rReasonCategoryId) OR (@rReasonCategoryId = 0))
	   AND 	M.OrgGroupId = 	@rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReasonMasterModify]
	@rId [int],
	@rTitle [nvarchar](100),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rRemark [nvarchar](100),
	@rReasonCategoryId [tinyint],
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF NOT EXISTS (SELECT 1 FROM sCommon.tReasonMaster WHERE UPPER(Title) = UPPER(@rTitle) AND ReasonCategoryId = @rReasonCategoryId AND Id  <> @rId AND OrgGroupId = @rOrgGroupId )
BEGIN

	 UPDATE sCommon.tReasonMaster
		SET 
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			Remark = @rRemark,
			ReasonCategoryId = @rReasonCategoryId
	  WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	  
	  
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReasonMasterRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tReasonMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRecordRemove]
	@rTableName [nvarchar](300),
	@rId [bigint],
	@rOrgId smallint = 0,
	@rFieldName [nvarchar](100) = '',
	@rRaiseError [bit] = 0	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lSqlStr NVARCHAR(MAX)
DECLARE @lErrorMessage NVARCHAR(MAX)
DECLARE @lCounter SMALLINT
DECLARE @lCount SMALLINT
DECLARE @lDepedentSchema NVARCHAR(50)
DECLARE @lDepedentTable NVARCHAR(100)
DECLARE @lDepedentField NVARCHAR(100)
DECLARE @lSourceTypeId SMALLINT
DECLARE @lSourceTypeFieldName NVARCHAR(100)

SET @lDepedentSchema = PARSENAME(@rTableName, 2)
SET @lDepedentTable = PARSENAME(@rTableName, 1)

CREATE TABLE #tTableRelationList
      (
            Id int IDENTITY(1, 1) PRIMARY KEY,
            TableId SMALLINT,
            ParentTable NVARCHAR(100),
            DependentTable NVARCHAR(100),
            SourceTypeId int,
            SourceTypeFieldName NVARCHAR(100),
            FunctionalityType TINYINT,
            ScreenName nvarchar(200)
      )

CREATE TABLE #tHasExists
      (
            Id bigint
      )
--INSERT INTO #tTableRelationList(TableId, ParentTable, DependentTable, SourceTypeId, SourceTypeFieldName, FunctionalityType)
--EXECUTE sCommon.pDependsGet @rTableName, 1
INSERT INTO #tTableRelationList(TableId, ParentTable, DependentTable, SourceTypeFieldName, SourceTypeId, FunctionalityType,ScreenName)
EXECUTE sCommon.pDependsGet @rTableName, 0
----  END

--select * FROM #tTableRelationList

SELECT @lCount = MAX(Id) FROM #tTableRelationList
SET @lCounter = 1
 
BEGIN TRY
      IF @rFieldName = ''
            BEGIN
                  IF EXISTS(SELECT 1 FROM #tTableRelationList)
                  BEGIN
                        WHILE(@lCounter <= @lCount)
                              BEGIN
	                                  SELECT @lDepedentSchema = PARSENAME(DependentTable, 3),
                                             @lDepedentTable = PARSENAME(DependentTable, 2),
                                             @lDepedentField = PARSENAME(DependentTable, 1),
                                             @lSourceTypeId = SourceTypeId,
                                             @lSourceTypeFieldName = SourceTypeFieldName
                                      FROM #tTableRelationList
                                     WHERE Id = @lCounter
                                                        
                                    SET @lSqlStr = 'INSERT INTO #tHasExists(Id) 
                                                            SELECT Top 1 1 FROM ' + @lDepedentSchema + '.' + @lDepedentTable + 
                                                         ' WHERE ' + @lDepedentField + ' = ' + CAST(@rId AS NVARCHAR(20))
                                                         --+ ' ANd OrgId = ' +  CAST(@rOrgId AS NVARCHAR(5)) 
                                            
                                    IF @lSourceTypeFieldName IS NOT NULL AND @lSourceTypeId IS NOT NULL
                                          BEGIN                                                    
                                                SET @lSqlStr = @lSqlStr + ' AND ' + @lSourceTypeFieldName + ' = ' + CAST(@lSourceTypeId AS NVARCHAR(10))
                                          END
                                    
                                    EXEC sp_executesql @lSqlStr
                                   
                                   --Select * from #tHasExists
                                    
                                    IF EXISTS(SELECT 1 FROM #tHasExists)                                       
                                          BEGIN
                                                SET @lErrorMessage = 'The DELETE statement conflicted with the REFERENCE data.'
                                                 --The conflict occurred in database- "' + DB_NAME() + '", table- "sAppointment.tAppointment", column- ''PatientSourceId'''
                                                RAISERROR(@lErrorMessage, 15, 1)    
                                                
                                                 --SELECT -101 Result
                                                 --Return
                                          END
                                    SET @lCounter = @lCounter + 1
                              END
                  END
            END
            
			 
            SET @lSqlStr = 'DELETE ' + @rTableName 
                         + ' WHERE ' + (CASE WHEN @rFieldName <> '' THEN @rFieldName ELSE 'Id' END) + ' = ' 
                         + CAST(@rId AS NVARCHAR(20)) 
                         --+ ' ANd OrgId = ' +  CAST(@rOrgId AS NVARCHAR(5)) 
            
                         
                         --PRINT @lSqlStr
            EXEC sp_executesql @lSqlStr
            
      
            SELECT 1 Result
      
END TRY
BEGIN CATCH
  IF @rRaiseError = 1
        BEGIN
                  SELECT ERROR_MESSAGE()
            END
      ELSE
        BEGIN
                  SELECT -101 Result
            END
      
END CATCH
 
DROP TABLE #tTableRelationList
DROP TABLE #tHasExists

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRecordRemoveWithMessage]
	@rTableName [nvarchar](300),
	@rId [bigint],
	@rOrgId smallint = 0,
	@rUserId bigint = 0,
	@rFieldName [nvarchar](100) = '',
	@rRaiseError [bit] = 0,
	@rDeleteSp [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lSqlStr NVARCHAR(MAX)
DECLARE @lErrorMessage NVARCHAR(MAX)
DECLARE @lCounter SMALLINT
DECLARE @lCount SMALLINT
DECLARE @lDepedentSchema NVARCHAR(50)
DECLARE @lDepedentTable NVARCHAR(100)
DECLARE @lDepedentField NVARCHAR(100)
DECLARE @lSourceTypeId SMALLINT
DECLARE @lSourceTypeFieldName NVARCHAR(100)
DECLARE @lScreenName NVARCHAR(200)
SET @lDepedentSchema = PARSENAME(@rTableName, 2)
SET @lDepedentTable = PARSENAME(@rTableName, 1)

CREATE TABLE #tTableRelationList
      (
            Id int IDENTITY(1, 1) PRIMARY KEY,
            TableId SMALLINT,
            ParentTable NVARCHAR(100),
            DependentTable NVARCHAR(100),
            SourceTypeId int,
            SourceTypeFieldName NVARCHAR(100),
            FunctionalityType TINYINT,
            ScreenName nvarchar(200)
      )

CREATE TABLE #tHasExists
      (
            Id bigint
      )
--INSERT INTO #tTableRelationList(TableId, ParentTable, DependentTable, SourceTypeId, SourceTypeFieldName, FunctionalityType)
--EXECUTE sCommon.pDependsGet @rTableName, 1
INSERT INTO #tTableRelationList(TableId, ParentTable, DependentTable, SourceTypeFieldName, SourceTypeId, FunctionalityType,ScreenName)
EXECUTE sCommon.pDependsGet @rTableName, 0
----  END
SELECT @lCount = MAX(Id) FROM #tTableRelationList
SET @lCounter = 1

BEGIN TRY
      IF @rFieldName = ''
            BEGIN
                  IF EXISTS(SELECT 1 FROM #tTableRelationList)
                  BEGIN
                        WHILE(@lCounter <= @lCount)
                              BEGIN
	                                  SELECT @lDepedentSchema = PARSENAME(DependentTable, 3),
                                             @lDepedentTable = PARSENAME(DependentTable, 2),
                                             @lDepedentField = PARSENAME(DependentTable, 1),
                                             @lSourceTypeId = SourceTypeId,
                                             @lSourceTypeFieldName = SourceTypeFieldName,
                                             @lScreenName = ScreenName
                                      FROM #tTableRelationList
                                     WHERE Id = @lCounter
                                                           
                                    SET @lSqlStr = 'INSERT INTO #tHasExists(Id) 
                                                            SELECT Top 1 1 AS Id FROM ' + @lDepedentSchema + '.' + @lDepedentTable + 
                                                         ' WHERE ' + @lDepedentField + ' = ' + CAST(@rId AS NVARCHAR(20))
                                                         --+ ' ANd OrgId = ' +  CAST(@rOrgId AS NVARCHAR(5)) 
                                                   
                                    IF @lSourceTypeFieldName IS NOT NULL AND @lSourceTypeId IS NOT NULL
                                          BEGIN                                                    
                                                SET @lSqlStr = @lSqlStr + ' AND ' + @lSourceTypeFieldName + ' = ' + CAST(@lSourceTypeId AS NVARCHAR(10))
                                          END
                                        
                                    EXEC sp_executesql @lSqlStr
                                   
                                    
                                    IF EXISTS(SELECT 1 FROM #tHasExists)                                       
                                          BEGIN
                                                SET @lErrorMessage = 'The DELETE statement conflicted with the REFERENCE data in ' + @lScreenName + '.'
                                                 --The conflict occurred in database- "' + DB_NAME() + '", table- "sAppointment.tAppointment", column- ''PatientSourceId'''
                                                RAISERROR(@lErrorMessage, 15, 1)    
                                                
                                                 --SELECT -101 Result
                                                 --Return
                                          END
                                    SET @lCounter = @lCounter + 1
                              END
                  END
            END
            
            if @rDeleteSp = ''
            BEGIN
            SET @lSqlStr = 'DELETE ' + @rTableName 
                         + ' WHERE ' + (CASE WHEN @rFieldName <> '' THEN @rFieldName ELSE 'Id' END) + ' = ' 
                         + CAST(@rId AS NVARCHAR(20)) 
                         --+ ' ANd OrgId = ' +  CAST(@rOrgId AS NVARCHAR(5)) 
            END
            ELSE
            BEGIN
            declare @sql varchar(512);
            
            IF(@rDeleteSp='sStudent.pAcademicDelete')
			 set @sql = 'exec ' + @rDeleteSp +  ' @rId = ' + CAST(@rId AS NVARCHAR(100)) + ', @UserId = ' + CAST(@rUserId AS NVARCHAR(100))  ;
			ELSE
			 set @sql = 'exec ' + @rDeleteSp +  ' @rId = ' + CAST(@rId AS NVARCHAR(100));
		    --PRINT @sql
				EXEC (@sql);
				
				 --PRINT @lSqlStr
            END
                         
                         
            EXEC sp_executesql @lSqlStr
            
      
            SELECT 1 Result,'Deleted Successfully' AS ResultText
      
END TRY
BEGIN CATCH
  IF @rRaiseError = 1
        BEGIN
                  SELECT -101 Result,ERROR_MESSAGE()AS ResultText
            END
      ELSE
        BEGIN
                  SELECT -101 Result,ERROR_MESSAGE() AS ResultText
            END
      
END CATCH
 
DROP TABLE #tTableRelationList
DROP TABLE #tHasExists

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReferentialIntegrityCheck]
	@rTableName [nvarchar](300),
	@rId int,
	@rOrgId int,
	@rFieldName [nvarchar](100) = '',
	@rIsReturnScreenName [bit] = 0,
	@rSourceCodeName [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lSqlStr			  NVARCHAR(MAX)
DECLARE @lErrorNumber		  NVARCHAR(MAX)
DECLARE @lCounter			  SMALLINT
DECLARE @lCount				  SMALLINT
DECLARE @lDepedentSchema	  NVARCHAR(50)
DECLARE @lDepedentTable		  NVARCHAR(100)
DECLARE @lDepedentField		  NVARCHAR(100)
DECLARE @lDepedentTableWithField NVARCHAR(100)
DECLARE @lSourceTypeId			 SMALLINT
DECLARE @lSourceTypeFieldName NVARCHAR(100)

SET @lDepedentSchema = PARSENAME(@rTableName, 2)
SET @lDepedentTable = PARSENAME(@rTableName, 1)
SET @rSourceCodeName = (SELECT S.Title  FROM sSystem.vExtTable T 
			INNER JOIN sSecurity.tScreen S ON T.ScreenId = S.Id AND T.TableName  = @rTableName ) 



CREATE TABLE #tTableRelationList
	(
		Id					SMALLINT IDENTITY(1, 1) PRIMARY KEY,
		TableId				SMALLINT,
		ParentTable			NVARCHAR(100),
		DependentTable		NVARCHAR(100),
		SourceTypeId		SMALLINT,
		SourceTypeFieldName NVARCHAR(100),
		FunctionalityType	TINYINT,
		ScreenName          NVARCHAR(100)
	)
CREATE TABLE #tHasExists
	(
		Id SMALLINT
	)
--CREATE TABLE ##tReferredScreens
CREATE TABLE #tReferredScreens
	(
		Id SMALLINT IDENTITY(1, 1),
		ScreenName NVARCHAR(100)
	)
INSERT INTO #tTableRelationList(TableId, ParentTable, DependentTable, SourceTypeFieldName, SourceTypeId,  FunctionalityType,ScreenName)
EXECUTE sCommon.pDependsGet @rTablename, 2


SELECT @lCount = MAX(Id) FROM #tTableRelationList
SET @lCounter = 1

BEGIN TRY
	--IF @rFieldName = ''
	--	BEGIN
			IF EXISTS(SELECT 1 FROM #tTableRelationList)
			BEGIN
				WHILE(@lCounter <= @lCount)
					BEGIN
						SELECT @lDepedentSchema = PARSENAME(DependentTable, 3),
							   @lDepedentTable = PARSENAME(DependentTable, 2),
							   @lDepedentField = PARSENAME(DependentTable, 1),
							   @lDepedentTableWithField = DependentTable,
							   @lSourceTypeId = SourceTypeId,
							   @lSourceTypeFieldName = SourceTypeFieldName
						  FROM #tTableRelationList
						 WHERE Id = @lCounter
						 				 
						SET @lSqlStr = 'INSERT INTO #tHasExists(Id) 
										SELECT 1 FROM ' + @lDepedentSchema + '.' + @lDepedentTable + 
									   ' WHERE ' + @lDepedentField + ' = ' + CAST(@rId AS NVARCHAR(20))
									  -- +  ' AND OrgId = ' + CAST(@rId AS NVARCHAR(5))
									   
						IF EXISTS(SELECT 1
								    FROM sys.schemas s
									     INNER JOIN sys.tables t
											     ON s.schema_id = t.schema_id
									     INNER JOIN sys.columns c
											     ON t.object_id = c.object_id
								   WHERE s.name = @lDepedentSchema
									     AND t.name = @lDepedentTable
									     AND c.name = 'IsObsolete') 
							BEGIN
								SET @lSqlStr = @lSqlStr + ' AND IsObsolete = 0'
							END
								   
						IF @lSourceTypeFieldName IS NOT NULL AND @lSourceTypeId IS NOT NULL
							BEGIN									   
								SET @lSqlStr = @lSqlStr + ' AND ' + @lSourceTypeFieldName + ' = ' + CAST(@lSourceTypeId AS NVARCHAR(10))
							END
						EXEC sp_executesql @lSqlStr
						print @lSqlStr
						IF @rIsReturnScreenName = 1
							BEGIN
								IF EXISTS(SELECT 1 FROM #tHasExists)						   
									BEGIN
										INSERT INTO ##tReferredScreens(ScreenName)
										SELECT S.Title--, D.ParentTable, D.DependentTable
										  FROM sSecurity.tScreen S
											   INNER JOIN sCommon.tDepends D
													   ON S.Id = D.ScreenId
										 WHERE D.ParentTable = @rTableName
											   AND D.DependentTable = @lDepedentTableWithField
											   
										IF @lCounter = @lCount
											BEGIN
												SET @lErrorNumber = '50001'
												RAISERROR(@lErrorNumber, 15, 1)	
											END
									END
									
							END
						ELSE
							BEGIN
								IF EXISTS(SELECT 1 FROM #tHasExists)						   
									BEGIN
										SET @lErrorNumber = '50001'
										RAISERROR(@lErrorNumber, 15, 1)	
									END
							END
						SET @lCounter = @lCounter + 1
					END
			END
		--END
		SELECT 0 Result --// False = Not referred
	
END TRY
BEGIN CATCH
	IF @lErrorNumber = '50001'
	
		BEGIN
			IF @rIsReturnScreenName = 1
				BEGIN
					SELECT DISTINCT ScreenName, 'The ' + @rSourceCodeName + ' is referred in the following screen(s)' SourceCodeName FROM ##tReferredScreens
				END
			ELSE
				BEGIN
					SELECT 1 Result --// True = Referred
					
					
			END
		END
	ELSE
		BEGIN
			SELECT ERROR_NUMBER() Result --// Error other than referred error.
			SELECT ERROR_NUMBER(), ERROR_MESSAGE() Result
		END
END CATCH
DROP TABLE #tTableRelationList
DROP TABLE #tHasExists
DROP TABLE #tReferredScreens

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReferentialIntegrityWithTableIdCheck]
	@rTableId [int],
	@rId [bigint],
	@rOrgId int = 0,
	@rFieldName [nvarchar](100) = '',
	@rIsReturnScreenName [bit] = 0,
	@rSourceCodeName [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lTableName NVARCHAR(300)
SET @lTableName = (SELECT t.TableName FROM sSystem.vExtTable t WHERE t.Id = @rTableId)

EXECUTE sCommon.pReferentialIntegrityCheck @rTableName = @lTableName, @rId = @rId, @rOrgId = @rOrgId, @rFieldName = @rFieldName, @rIsReturnScreenName = @rIsReturnScreenName, @rSourceCodeName = @rSourceCodeName


SELECT S.Title AS ScreenTitle FROM sSystem.vExtTable  T INNER JOIN 
sSecurity.tScreen S ON T.ScreenId = S.id AND T.Id = @rTableId

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReferredTypeMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			TitleResourceKey
	   FROM sRegistration.tReferredTypeMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRefferedTableForObsoleteCheckGet]
	@rReferenceSchema [nvarchar](50) = '',
	@rReferenceTable [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			ReferenceSchema,
			ReferenceTable,
			ParentSchema,
			ParentTable,
			ParentField
	   FROM sCommon.tRefferedTableForObsoleteCheck
	  WHERE ((ReferenceSchema = @rReferenceSchema) OR (@rReferenceSchema = ''))
		    AND ((ReferenceTable = @rReferenceTable) OR (@rReferenceTable = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRefferedTableWithoutForeignKeyGet]
	@rParentSchema [nvarchar](50) = '',
	@rParentTable [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			ParentSchema,
			ParentTable,
			ReferenceSchema,
			ReferenceTable,
			ReferenceField,
			SourceTypeId,
			SourceTypeFieldName
	   FROM sCommon.tRefferedTableWithoutForeignKey
	  WHERE ((ParentSchema = @rParentSchema) OR (@rParentSchema = ''))
			AND ((ParentTable = @rParentTable) OR (@rParentTable = ''))	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRelationshipMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			TitleResourceKeyId
	   FROM sCommon.tRelationshipMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReligionMasterAdd]
	 
	@rId int,
	@rCode nvarchar(50),
	@rTitle nvarchar(50),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rOrgGroupId int,
	@OutReligionId INT = NULL OUTPUT
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet rOrgGroupId, 'sCommon.tReligionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tReligionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sSetup.tReligionMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommon.tReligionMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
	        UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
			
	      
	      WHERE Id = @rId 	   
	 END  
		SET @OutReligionId = @lNextNumber
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReligionMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title
			
			--TitleResourceKeyId
	   FROM sCommon.tReligionMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReportFormatGet]
	 
	 @rOrgId smallint,
	 @rReportFormatGroupId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
DECLARE @lReportId smallint

BEGIN 
	SELECT 
			@lReportId=RFGO.ReportId
  FROM 
            sCommon.tReport R
        INNER JOIN sCommon.tReportFormatGroupOrg RFGO ON RFGO.ReportId=R.Id AND RFGO.OrgId=@rOrgId
  WHERE 
			(R.ReportFormatGroupId=@rReportFormatGroupId)
IF(@lReportId IS NULL)
BEGIN
	SELECT 
			@lReportId=Min(Id)
	FROM 
            sCommon.tReport
	WHERE 
			(ReportFormatGroupId=@rReportFormatGroupId)
END

	SELECT @lReportId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReportFormatGroupMasterGet]
	 
	 @rOrgGroupId smallint,
	 @rReportFormatGroupId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			DISTINCT(OM.Id) AS OrgId,
			OM.DisplayTitle AS Organization,
			CASE WHEN RFGO.OrgId IS NULL OR RFGO.ReportFormatGroupId!=@rReportFormatGroupId THEN 'False' ELSE 'True' END AS IsObsolete,
			CASE WHEN RFGO.OrgId IS NULL OR RFGO.ReportFormatGroupId!=@rReportFormatGroupId THEN 0 ELSE RFGO.ReportId END AS ReportId,
			CASE WHEN RFGO.OrgId IS NULL OR RFGO.ReportFormatGroupId!=@rReportFormatGroupId THEN '0-0' ELSE Convert(Nvarchar(50),RFGO.ReportId) + '-' + Convert(Nvarchar(50),IsNull(RFGO.PrintTemplateId, 0)) END AS ReportPrintTemplate
  FROM 
            sSetup.tOrganizationMaster OM
       LEFT JOIN sCommon.tReportFormatGroupOrg RFGO ON RFGO.OrgId=OM.Id AND (RFGO.ReportFormatGroupId=@rReportFormatGroupId)
       
  WHERE 
			(OM.OrgGroupId=@rOrgGroupId)
		ORDER BY OM.DisplayTitle
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pReportFormatGroupOrgAdd]
    
    @rReportFormatGroupId smallint,
	@rXmldoc [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lOrgId SMALLINT,
		@lReportId SMALLINT,
		@lPrintTemplateId INT
		
BEGIN TRANSACTION
			
	DELETE FROM sCommon.tReportFormatGroupOrg WHERE ReportFormatGroupId=@rReportFormatGroupId	
			
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
		
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		OrgId smallint,
		ReportId smallint,
		PrintTemplateId Int
	)
		
	INSERT INTO #tTable
	(
		OrgId,
		ReportId,
		PrintTemplateId
	)
	SELECT
		OrgId,
		ReportId,
		PrintTemplateId
	FROM OPENXML (@intDoc, '/Table/ReportFormatGroup', 1)
	WITH
	( 
		OrgId smallint '@OrgId',			
		ReportId smallint '@ReportId',
		PrintTemplateId Int '@PrintTemplateId'
	)
		
	EXEC sp_xml_removedocument @intDoc
				
	SELECT @lCount =  COUNT(Id) FROM #tTable

	WHILE @lCount > 0 
	BEGIN
		SELECT		
				@lOrgId=OrgId,
				@lReportId=ReportId,
				@lPrintTemplateId=PrintTemplateId
													 	 
		FROM #tTable WHERE Id = @lCount  

		INSERT INTO sCommon.tReportFormatGroupOrg
		(
			OrgId,
			ReportId,
			ReportFormatGroupId,
			PrintTemplateId
		)
		VALUES
		(
			@lOrgId,
			@lReportId,
			@rReportFormatGroupId,
			@lPrintTemplateId
		)
		SET @lCount = @lCount - 1
	END			
COMMIT TRANSACTION			
	
SELECT 1
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT -1 
END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReportFormatOtherGet]

	 @rReportFormatGroupId smallint,
	 @rSourceId bigint,
	 @rSourceTypeId smallint
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
DECLARE @lReportId smallint = 0

BEGIN 
 
 IF (@rReportFormatGroupId = 2 ) 
 SELECT @lReportId = ReportId FROM sFee.tReceiptBookMaster WHERE ID = @rSourceId
 ELSE IF (@rReportFormatGroupId = 45 )
 SELECT @lReportId = ReportId FROM sAssessment.tExamMaster WHERE ID = @rSourceId
 
	SELECT @lReportId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReportGet]
	@rId [int] = 0,
	@rOrgId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	 SELECT Id,
			
			--R.Title,
			R.ReportName AS Title,
			CASE ISNULL(RC.ReportId,0) WHEN  0
			THEN R.ReportPath
			ELSE
			REPLACE(REPLACE(R.ReportPath,'RDLCReports','zReportClient'),'ReportCustom','zReportClient')
			END AS ReportPath,
						
			R.IsElectronicSignatureRequired,
		    R.IsDirectPrint AS IsDirectPrint ,
			R.NoOfCopies  AS NoOfCopies
	   FROM sCommon.tReport R LEFT JOIN sCommon.tReportClient RC ON R.ID = RC.ReportId AND RC.OrgGroupId = (SELECT OrgGroupId FROM sSetup.tOrganizationMaster where Id = @rOrgId)
	   --LEFT JOIN sSetup.tReportSetting S
	   --ON R.Id = s.ReportId AND S.OrgId = @rOrgId
	  WHERE ((R.Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pReportGet_Migration]
	@rId [int] = 0,
	@rOrgId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 Declare @rOrgGroupId int = 0
	 SELECT @rOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster where Id = @rOrgId
	 SELECT Id,
			--R.Title,
			R.ReportName AS Title,
			CASE ISNULL(RC.ReportId,0) WHEN  0
			THEN R.ReportPath
			ELSE
			REPLACE(REPLACE(R.ReportPath,'RDLCReports',('zReportClient\'+CAST(@rOrgGroupId AS NVARCHAR(10)))),'ReportCustom','zReportClient')
			END AS ReportPath,
			R.IsElectronicSignatureRequired,
		    R.IsDirectPrint AS IsDirectPrint ,
			R.NoOfCopies  AS NoOfCopies
	   FROM sCommon.tReport R LEFT JOIN sCommon.tReportClient RC ON R.ID = RC.ReportId AND RC.OrgGroupId = @rOrgGroupId
	   --LEFT JOIN sSetup.tReportSetting S
	   --ON R.Id = s.ReportId AND S.OrgId = @rOrgId
	  WHERE ((R.Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pReportHistoryAdd]
	 
	        --@rId int,
	        @rScreenId int,
	        @rReportName nvarchar(max),
            @rStatusId int,
            @rUserId bigint

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	INSERT INTO [sCommon].[tReportHistory]
           (
		    ScreenId
           ,ReportName
           ,StatusId
           ,CreatedUserId
           ,CreatedDateTime
			)
     VALUES
           (
		    @rScreenId
           ,@rReportName
           ,@rStatusId
           ,@rUserId
           ,sCommon.fGetDate()
           )
	--Select 1 AS Result

	SELECT @@Identity AS Result
	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS RESULT
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pReportHistoryGet]
	 
	        @rUserId bigint,
	        @rScreenId int
	  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			Id,
			ReportName,
		   (CASE WHEN StatusId = 1 THEN 'Completed' 
				 WHEN StatusId = 2 THEN 'No Record'
				 WHEN StatusId = 3 THEN 'Error'
				 WHEN StatusId = 5 THEN 'Out Of Memmory'
				 ELSE 'Canceled' END) AS Status,
		   CreatedDateTime,
		   UpdatedDateTime,
		   ISNULL(Guid,'') AS ReportPath,
		   StatusId
	FROM
			 sCommon.tReportHistory
	WHERE 
	ScreenId = @rScreenId
	AND CreatedUserId = @rUserId
	AND CAST(CreatedDateTime AS Date) > CAST(DATEADD(day, -2, GETDATE()) AS DATE)
	Order By CreatedDateTime DESC
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pReportMasterAdd]

	@rId int,
	@rTitle nvarchar(100),
	@rTaskId int,
	@rOrderIndex int,
	@rReportGroupId int,
	@rReportFormatGroup int,
	@rReportName nvarchar(100),
	@rReportPath nvarchar(500),
	@rIsObsolete bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF(@rId=0)
BEGIN
	IF EXISTS(Select 1 from sCommon.tReport WHERE Title = @rTitle)
	BEGIN
			SELECT -103 AS Result
			RETURN
	END
END
ELSE
BEGIN
	IF EXISTS(Select 1 from sCommon.tReport WHERE Id<>@rId AND Title = @rTitle)
	BEGIN
			SELECT -103 AS Result
			RETURN
	END
END

BEGIN TRY
BEGIN TRANSACTION

IF EXISTS(SELECT 1 FROM sCommon.tReport WHERE Id = @rId)
BEGIN
	UPDATE sCommon.tReport
	SET 
		Title = @rTitle,
		TaskId = @rTaskId,
		ReportPath = @rReportPath,
		IsObsolete = @rIsObsolete,
		ReportGroup = @rReportGroupId,
		ReportFormatGroupId = @rReportFormatGroup,
		ReportName = @rReportName,
		OrderIndex = @rOrderIndex
		WHERE Id = @rId
		SELECT 2 AS RESULT
END
ELSE
BEGIN
	INSERT INTO sCommon.tReport
	VALUES(
	@rId,
	@rTitle,
	@rReportPath,
	1,
	0,
	0,
	1,
	@rReportGroupId,
	NULL,
	@rOrderIndex,
	@rTaskId,
	@rReportFormatGroup,
	@rReportName,
	NULL,
	@rIsObsolete,
	NULL,
	NULL,
	NULL,
	NULL)
SELECT 1 AS Result
END
COMMIT TRANSACTION		
END TRY
BEGIN CATCH 
ROLLBACK TRANSACTION
		SELECT -1 AS Result
		RETURN
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReportMasterGet]
	
	@rTaskId int = 0,
	@rModuleId int = 0,
	@rTitle nvarchar(100) = '',
	@rIsObsolete int = -1,
	@rId int = 0	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT
		M.Id AS ModuleId,
		T.Id AS TaskId, 
		R.Id AS ReportId,
		M.Title AS ModuleTitle,
		T.Title AS TaskTitle,
		R.Title AS ReportTitle,
		R.ReportPath AS ReportPath,
		ISNULL(R.OrderIndex,'') AS OrderIndex,
		R.IsObsolete AS InActive,
		R.ReportGroup AS ReportGroup,
		R.ReportFormatGroupId AS ReportFormatGroup,
		R.ReportName AS ReportName
	FROM
		[sCommon].[tReport] R
		INNER JOIN sSecurity.tTask T ON R.TaskId = T.Id
		INNER JOIN [sCommon].[tModuleMaster] M ON T.ModuleId = M.Id
	WHERE
		((@rTitle='' AND 0=0) OR (R.Title LIKE '%'+@rTitle+'%'))
		AND  (M.Id = @rModuleId OR @rModuleId=0)
		AND (T.Id = @rTaskId OR @rTaskId=0)
		AND (R.Id = @rId OR @rId=0)
		AND (R.IsObsolete = @rIsObsolete OR @rIsObsolete= -1)
	ORDER BY M.Id,T.Id,R.Id,R.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReportOrgAdd]
    
    @rReportGroup int,
    @rOrgId smallint,
	@rXmldoc [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @loDoc INT
BEGIN TRY
BEGIN TRANSACTION
			
	DELETE RG FROM sCommon.tReportOrg RG
		INNER JOIN sCommon.tReport R ON R.Id = RG.ReportId 
	WHERE R.ReportGroup=@rReportGroup AND ScopeSourceId=@rOrgId
			
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXmldoc
		
	INSERT INTO sCommon.tReportOrg
	(
		ReportId,
		ScopeSourceId,
		ScopeSourceTypeId
	)
	SELECT
		ReportId,
		@rOrgId,
		ScopeSourceTypeId
	FROM OPENXML (@loDoc, '/Table/ReportOrg', 1)
	WITH
	( 
		ReportId smallint,
		ScopeSourceTypeId smallint 
	)
	SELECT 1 AS Result	
	EXEC sp_xml_removedocument @loDoc
		
COMMIT TRANSACTION			

END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT -1 Result
END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReportOrgGet]


	 @rReportGroup int,
	 @rOrgId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			R.Id AS ReportId,
			R.Title AS ReportName,
			ISNULL(RG.ReportId,0) AS RGReportId,
			ISNULL(RG.ScopeSourceId,0) AS OrgId,
			ISNULL(RG.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
			CAST(CASE WHEN RG.ReportId IS NULL AND RG.ScopeSourceId IS NULL THEN 'false' ELSE 'true' END AS BIT) AS IsObsolete
	FROM 
			sCommon.tReport R 
			LEFT JOIN sCommon.tReportOrg RG ON R.Id = RG.ReportId 
			AND (RG.ScopeSourceId=@rOrgId)
			WHERE 
			(R.ReportGroup=@rReportGroup)
			AND IsObsolete = 0
			ORDER BY R.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReportRemarkGroupMasterGet]
	 
	 @rOrgGroupId smallint,
	 @rReportRemarkGroupId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			DISTINCT(OM.Id) AS OrgId,
			OM.DisplayTitle AS Organization,
			ISNULL(RGO.SchoolRemark1,'') AS SchoolRemark1,
			ISNULL(RGO.SchoolRemark2,'') AS SchoolRemark2,
			ISNULL(RGO.SchoolRemark3,'') AS SchoolRemark3,
		    ISNULL(RGO.SchoolRequiredSignature,'') AS SchoolRequiredSignature,
			CASE WHEN RGO.OrgId IS NULL OR RGO.ReportRemarkGroupId!=@rReportRemarkGroupId THEN 'False' ELSE 'True' END AS IsObsolete
			--CASE WHEN RGO.OrgId IS NULL OR RGO.ReportRemarkGroupId!=@rReportRemarkGroupId THEN 0 ELSE RGO.ReportId END AS ReportId
  FROM 
            sSetup.tOrganizationMaster OM
       LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId=OM.Id AND (RGO.ReportRemarkGroupId=@rReportRemarkGroupId)
       
  WHERE 
			(OM.OrgGroupId=@rOrgGroupId)
		ORDER BY OM.DisplayTitle
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pReportRemarkGroupOrgAdd]
    
    @rReportRemarkGroupId smallint,
	@rXmldoc [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lOrgId smallint,
		@lReportId int,
		@lSchoolRemark1 nvarchar(500),
		@lSchoolRemark2 nvarchar(500),
		@lSchoolRemark3 nvarchar(500),
		@lSchoolRequiredSignature nvarchar(500)
		
BEGIN TRANSACTION
			
	DELETE FROM sCommon.tReportRemarkGroupOrg WHERE ReportRemarkGroupId=@rReportRemarkGroupId	
			
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
		
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		OrgId smallint,
		ReportId int,
		SchoolRemark1 nvarchar(500),
		SchoolRemark2 nvarchar(500),
		SchoolRemark3 nvarchar(500),
		SchoolRequiredSignature nvarchar(500)
	)
		
	INSERT INTO #tTable
	(
		OrgId,
		ReportId,
		SchoolRemark1,
		SchoolRemark2,
		SchoolRemark3,
		SchoolRequiredSignature
	)
	SELECT
		OrgId,
		ReportId,
		SchoolRemark1,
		SchoolRemark2,
		SchoolRemark3,
		SchoolRequiredSignature
	FROM OPENXML (@intDoc, '/Table/ReportRemarkGroup', 1)
	WITH
	( 
		OrgId smallint '@OrgId',			
		ReportId int '@ReportId',
		SchoolRemark1 nvarchar(500) '@SchoolRemark1',
		SchoolRemark2 nvarchar(500) '@SchoolRemark2',
		SchoolRemark3 nvarchar(500) '@SchoolRemark3',
		SchoolRequiredSignature nvarchar(500) '@SchoolRequiredSignature'
	)
		
	EXEC sp_xml_removedocument @intDoc
				
	SELECT @lCount =  COUNT(Id) FROM #tTable

	WHILE @lCount > 0 
	BEGIN
		SELECT		
				@lOrgId=OrgId,
				@lReportId=ReportId,
				@lSchoolRemark1=SchoolRemark1,
			    @lSchoolRemark2=SchoolRemark2,
			    @lSchoolRemark3=SchoolRemark3,
			    @lSchoolRequiredSignature=SchoolRequiredSignature
													 	 
		FROM #tTable WHERE Id = @lCount  

		INSERT INTO sCommon.tReportRemarkGroupOrg
		(
			OrgId,
			ReportId,
			ReportRemarkGroupId,
			SchoolRemark1,
			SchoolRemark2,
			SchoolRemark3,
			SchoolRequiredSignature
			
		)
		VALUES
		(
			@lOrgId,
			@lReportId,
			@rReportRemarkGroupId,
			@lSchoolRemark1,
			@lSchoolRemark2,
			@lSchoolRemark3,
			@lSchoolRequiredSignature
		)
		SET @lCount = @lCount - 1
	END			
COMMIT TRANSACTION			
	
SELECT 1
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT -1 
END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sCommon].[pReportTemplateAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rTemplate nvarchar(max),
        @rOrgId smallint,
        @rCreatedUserId bigint,
        @rTemplateSourceId tinyint,
        @rReportId int=0

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sCommon.tReportTemplate where (Title=@rTitle OR ReportId=@rReportId) AND OrgId=@rOrgId)
			BEGIN
			select DisplayTitle As OrganizationName FROM [sSetup].[tOrganizationMaster] Where Id = @rOrgId
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sCommon.tReportTemplate where (Title=@rTitle OR ReportId=@rReportId) AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select DisplayTitle As OrganizationName FROM [sSetup].[tOrganizationMaster] Where Id = @rOrgId
			select -103 as Result
			RETURN 
		End

	END
	
	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tReportTemplate', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommon.tReportTemplate
		(
			Id,
			ReportId,
			Title,
			Template,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			TemplateSourceId
		)
	VALUES
		(
			@lNextNumber,
			@rReportId,
			@rTitle,
			@rTemplate,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rTemplateSourceId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommon.tReportTemplate
	    SET
			ReportId=@rReportId,
			Title=@rTitle,
			Template=@rTemplate,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			TemplateSourceId=@rTemplateSourceId
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommon].[pReportTemplateGet]

	 @rId int,
	 @rOrgId smallint,
	 @rTitle nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			RT.Id,
			RT.Title,
			RT.Template,
		    RT.OrgId,
		    RT.CreatedUserId,
		    RT.CreatedDateTime,
		    RT.TemplateSourceId,
			RT.ReportId
		    
	FROM 
			sCommon.tReportTemplate RT
	WHERE 
		(RT.OrgId = @rOrgId)
		AND	((RT.Id = @rId) OR (@rId = 0))
		AND ((RT.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRouteMasterAdd]
	@rCode [nvarchar](10),
	@rTitle [nvarchar](20),
	@rIsShow [bit],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lId BIGINT

SET @lId = (SELECT ID FROM sCommon.tRouteMaster WHERE Title = @rTitle)

IF (ISNULL(@lId, 0) = 0)
BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE  sCommon.pTableRowIdGet 'sCommon.tRouteMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommon.tRouteMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		SET @lId = @lNextNumber
END
SELECT @lId AS ID
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRouteMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			IsObsolete,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	   FROM sHedp.tRouteMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRouteMasterModify]
	@rId [tinyint],
	@rCode [nvarchar](10),
	@rTitle [nvarchar](20),
	@rIsObsolete [bit],
	@rUpdatedBy [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sHedp.tRouteMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedBy = @rUpdatedBy,
			UpdatedDate = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRptCompanyInformationExternalGet]
	@rReportId [int] = 0,
	@rStoreLocationId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
		SELECT	Id,
				Code,
				Title,
				ParentCompanyName,
				StreetOne + ', ' + CityName		AS FirstLine,
				--StateName + ', ' + 
			--	CountryName + ', TIN No: ' + TinNumber AS SecondLine,
			--	'Tel: ' + PhoneNumberOffice AS ThirdLine,
				'Website: ' + HomePage AS FourthLine,
				StreetOne,
				StreetTwo,
				StreetThree,
				StreetFour,
				CityName,
				StateName,
				--CountryName,
				--ZipCode,
				--CityName + ' ' + StateName AS CityState,
				--CountryName + ' ' + ZipCode AS CountryZip,
				----'' AS ContactPerson,
				--ContactPerson,
				--PhoneNumberHome,
				--PhoneNumberOffice,
				--PhoneNumberMobile,
				--EmailPrimary,
				--EmailAlternative,
				--HomePage,
				(SELECT Title FROM sCommon.tReport WHERE ((Id = @rReportId) OR (@rReportId = 0))) AS ReportTitle,
				Logo
				--'Report Name' AS ReportTitle
		FROM sCommon.tCompanyInformation CI INNER JOIN sCommon.tCompanyInformationDetail  CD
		ON CI.Id = CD.OrgId
		WHERE ((CI.Id = @rStoreLocationId) OR (ISNULL(@rStoreLocationId, 0) = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRptCompanyInformationInternalGet]	
	@rReportId [int] = 0,
	@rStoreLocationId [int] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
		SELECT
			    CI.Id,
				LM.Title AS LocationName,
				LM.SmallAddress1,
				LM.SmallAddress2,
				CI.Code,
				CI.Title,
				CI.ParentCompanyName,
				CI.StreetOne + ', ' + CI.CityName AS FirstLine,
				--  StateName + ', ' + 
				--	CountryName + ', TIN No: ' + TinNumber AS SecondLine,
				--	'Tel: ' + PhoneNumberOffice AS ThirdLine,
				'Website: ' + CI.HomePage AS FourthLine,
				CI.StreetOne,
				CI.StreetTwo,
				CI.StreetThree,
				CI.StreetFour,
				CI.CityName,
				CI.StateName,
				--CountryName,
				--ZipCode,
				--CityName + ' ' + StateName AS CityState,
				--CountryName  + ' ' + ZipCode AS CountryZip,
				--ContactPerson,
				--PhoneNumberHome,
				--PhoneNumberOffice,
				--PhoneNumberMobile,
				--EmailPrimary,
				--EmailAlternative,
				--HomePage,
			    (SELECT (ISNULL(RS.Title,R.Title)) FROM sCommon.tReport R LEFT JOIN sCommon.tReportStateTitle RS On R.Id = RS.ReportId 				
				     LEFT JOIN
				     	(SELECT StateId FROM  sCommon.tLocationMaster LM 
					 INNER JOIN sIp.tStoreLocationMaster SL ON SL.LocationId = LM.id WHERE SL.Id = @rStoreLocationId
					) SLM  
					ON SLM.StateId = RS.StateId
					          
			WHERE ((R.Id = @rReportId) OR (@rReportId = 0))) AS ReportTitle,
				 CID.logo as Logo 
				 
			FROM sIp.tStoreLocationMaster SL INNER JOIN sCommon.tLocationMaster LM					  			
			ON SL.LocationId = LM.Id INNER JOIN sCommon.tCompanyInformation CI 
			ON LM.OrgId = CI.Id	INNER JOIN sCommon.tCompanyInformationDetail CID
			on ci.ID = CID.orgid
			WHERE ((SL.Id = @rStoreLocationId) OR (ISNULL(@rStoreLocationId, 0) = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRptElectronicSignatureGet]
	@rUserId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
		
SELECT	ElectronicSignature AS ElectronicSignature, UserId AS CreatedUserId
FROM	sSecurity.tUserProfile
WHERE	(UserId = @rUserId OR @rUserId = 0)
					 
													
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRptFooterGet]
	@rUserId [bigint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
		
SELECT	DisplayTitle AS PrintedBy, 
sCommon.fReportDateGet(sCommon.fGetDate()) AS PrintedOn
FROM	sSecurity.tUser 
WHERE	(Id = @rUserId OR @rUserId = 0)
					 
													
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pRptTelephoneDirectory]
	@rDeptId [int] = 20,
	@rRoleId [int] = 0,
	@rEmpId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

DECLARE @lDeptName VARCHAR(100)
DECLARE @lRoleName VARCHAR(100)
DECLARE @lEmpName VARCHAR(100)

SELECT @lDeptName = ODM.Title FROM sSetup.tDepartmentMaster ODM WHERE ODM.Id = @rDeptId
SELECT @lRoleName = R.Title FROM sSecurity.tRole R WHERE R.Id = @rRoleId
-- Commented For Employee Migration
--SELECT @lEmpName = EM.FirstName FROM sCommon.tEmployeeMaster EM WHERE EM.Id  = @rEmpId
-- End of comment for Employee Migration
-- Added for Employee Migration
SELECT @lEmpName = EM.FirstName FROM sHrm.vExtEmployeeMaster EM WHERE EM.Id  = @rEmpId
-- End of addition for Employee Migration



IF(@rEmpId IS NULL)
	BEGIN
		SET @rEmpId = 0
	END

BEGIN

	SELECT  DISTINCT
	        ISNULL(EM.FirstName, '')						AS Name,
	        ISNULL(EM.Code, '')								AS EmpId,
	        -- Commented For Employee Migration
	        --ISNULL(EC.PhoneNumberOffice, '')				AS TelNo,
	        -- END of comment for Employee Migration
	        -- Added for Employee Migration
	        ISNULL(ECOM.PhoneNoCompany, '')				AS TelNo,
	        ISNULL(ECOM.ExtensionNo, '')				AS Extn,
			ISNULL(EC.MobileNumber, '')				AS MobNo,
			ISNULL(ECOM.CompanyEmail, '')						AS EmailId,
	        -- END of addition for Employee Migration
	        -- Commented For Employee Migration
	        --ISNULL(EC.ExtensionPhoneNumber, '')				AS Extn,
			--ISNULL(EC.PhoneNumberMobile, '')				AS MobNo,
			--ISNULL(EC.EmailPrimary, '')						AS EmailId,
			-- END of comment for Employee Migration
			ISNULL(ODM.Title, '')							AS DepartmentName,
			ISNULL(R.Title, '')								AS RoleName,
			ISNULL(EM.FirstName, '')						AS EmpName,	
		
			(CASE 
					WHEN (@rDeptId <> 0) THEN
						@lDeptName
					ELSE
						'ALL'															 
					END
			)									AS InputDepartmentName,
			(CASE 
					WHEN (@rRoleId <> 0) THEN
						R.Title
					ELSE
						'ALL'															 
					END
			)									AS InputRoleName,
			(CASE 
					WHEN (@rEmpId <> 0) THEN
						@lEmpName
					ELSE
						'ALL'															 
					END
			)									AS InputEmpName,
			
			sCommon.fReportDateGet(sCommon.fGetDate()) AS ReportDate
					
	FROM 
	-- Commented For Employee Migration
	--sCommon.tEmployeeMaster EM
	-- END of comment for Employee Migration
	-- Added for Employee Migration
	   sHrm.vExtEmployeeMaster EM
	   INNER JOIN sHrm.vExtEmployeeJobDetail EJD
	   ON EM.Id = EJD.EmployeeId
	   INNER JOIN sHrm.vExtEmployeeCommunication ECOM
	   ON ECOM.EmployeeId = EM.Id
	   INNER JOIN sHrm.vExtEmployeeContact EC
	   ON ECOM.PresentContactId = EC.Id
	-- End of addition for Employee Migration
    
		LEFT JOIN sSecurity.tUser U
			ON U.EmployeeId = EM.Id
		LEFT JOIN sSetup.tDepartmentMaster ODM
			ON ODM.Id = EJD.OrganizationDepartmentId
		LEFT JOIN sSecurity.tUserRole UR
					ON UR.UserId = U.Id	
		-- Commented For Employee Migration			
		--LEFT JOIN sCommon.tEmployeeContact EC
		--	ON EC.Id = EM.CommunicationContactId
		LEFT JOIN sSecurity.tRole R
					ON UR.RoleId = R.Id
	WHERE ((ODM.Id = @rDeptId) OR (@rDeptId = 0))
		-- AND ((EJD.JobTitleId = @rRoleId) OR (@rRoleId = 0))
		 AND ((EM.Id  = @rEmpId ) OR (@rEmpId = 0))
		 ORDER BY 
			DepartmentName,
			RoleName,
			EmpName

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pSalutationMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			TitleResourceKeyId
	   FROM sCommon.tSalutationMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pScreenGroupDataListGet]          
           @rScreenGroupId int,
           @rUserId bigint   
AS
SET NOCOUNT ON
 
	BEGIN
	
	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WITH (NOLOCK) WHERE UserId = @rUserId)
	BEGIN
		Select 
			S.Id AS Id, LEFT(S.Title,40) AS Title, S.IconPath,
			 CASE WHEN S.Id = 20020 THEN Page+'?MenuID=5310'
			      WHEN S.Id = 20033 THEN Page+'?MenuID=5410'
			      WHEN S.Id = 20037 THEN Page+'?MenuID=5111'
			      WHEN S.Id = 20038 THEN Page+'?MenuID=5112'
			      WHEN S.Id = 9018 THEN Page+'?MenuID=331111'
			      --WHEN S.Id = 297 THEN Page+'?MenuID=181115'
			      --WHEN S.Id = 296 THEN Page+'?MenuID=181116'
			      WHEN S.Id = 449 THEN Page+'?MenuID=221214'
			      WHEN S.Id = 5 THEN Page+'?MenuID=161014'
			      WHEN S.Id = 191 THEN Page+'?MenuID=15101015'
			      WHEN S.Id = 32 THEN Page+'?MenuID=141112'			         
			      --WHEN S.Id = 57 THEN Page+'?MenuID=312052'
			   ELSE Page 
			   END AS Page,
			   S.OrderIndex	,			   
			   ISNULL(S.ScreenGroupId,0) AS  ScreenGroupId,
			   T.ResourceTypeId,
			   RTM.Title AS ResourceTypeTitle			  		  
		 From sSecurity.tScreen S WITH (NOLOCK)  
		     INNER JOIN sSecurity.tPermissionUser P WITH (NOLOCK) ON P.TaskId=S.TaskId
		     --INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		     INNER JOIN sSecurity.tTask T WITH (NOLOCK) ON T.ID = p.TaskId
		     INNER JOIN sSecurity.tResourceTypeMaster RTM WITH (NOLOCK) ON RTM.ID = T.ResourceTypeId
		     INNER JOIN sSecurity.tOrganizationTask OT WITH (NOLOCK) ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		     INNER JOIN sSecurity.tModulePermission MP WITH (NOLOCK) ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId	 
		WHERE (P.Permission & 2) =2
		     AND (ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		     -- AND U.IsObsolete=0
		     AND P.UserId=@rUserId 
		     AND T.IsObsolete = 0
		     AND S.IsObsolete = 0
		     AND S.IsHideInScreenGroup = 0	
		--GROUP By S.Title,S.Id,Page,S.OrderIndex,S.IconPath
		Order by RTM.OrderIndex,S.OrderIndex,S.Title 
	END
	ELSE
	BEGIN
		Select 
			S.Id AS Id,
			LEFT(S.Title,40) AS Title, S.IconPath,
			 CASE WHEN S.Id = 20020 THEN Page+'?MenuID=5310'
			      WHEN S.Id = 20033 THEN Page+'?MenuID=5410'
			      WHEN S.Id = 20037 THEN Page+'?MenuID=5111'
			      WHEN S.Id = 20038 THEN Page+'?MenuID=5112'
			      WHEN S.Id = 9018 THEN Page+'?MenuID=331111'
			      --WHEN S.Id = 297 THEN Page+'?MenuID=181115'
			      --WHEN S.Id = 296 THEN Page+'?MenuID=181116'
			      WHEN S.Id = 449 THEN Page+'?MenuID=221214'
			      WHEN S.Id = 5 THEN Page+'?MenuID=161014'  			      
                  WHEN S.Id = 191 THEN Page+'?MenuID=15101015'
			      WHEN S.Id = 32 THEN Page+'?MenuID=141112'
                 --WHEN S.Id = 57 THEN Page+'?MenuID=312052'
			   ELSE Page 
			   END AS Page,
			   S.OrderIndex	,
			   ISNULL( S.ScreenGroupId,0) AS  ScreenGroupId,
			   T.ResourceTypeId,
			   RTM.Title AS ResourceTypeTitle		  
	    From sSecurity.tScreen S WITH (NOLOCK)    
		      INNER JOIN sSecurity.tPermission P WITH (NOLOCK) ON P.TaskId=S.TaskId
		      INNER JOIN sSecurity.tUserRole U WITH (NOLOCK) ON U.RoleId=P.RoleId


		      INNER JOIN sSecurity.tTask T WITH (NOLOCK) ON T.ID = p.TaskId
		      INNER JOIN sSecurity.tResourceTypeMaster RTM WITH (NOLOCK) ON RTM.ID = T.ResourceTypeId
		      INNER JOIN sSecurity.tOrganizationTask OT WITH (NOLOCK) ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		      INNER JOIN sSecurity.tModulePermission MP WITH (NOLOCK) ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId	 
		WHERE (P.Permission & 2) =2
		  AND (ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		  AND U.IsObsolete=0
		  AND U.UserId=@rUserId 
		  AND T.IsObsolete = 0
		  AND S.IsObsolete = 0
		  AND S.IsHideInScreenGroup = 0		
		  --GROUP By S.Title,S.Id,Page,S.OrderIndex,S.IconPath
		Order by RTM.OrderIndex,S.OrderIndex,S.Title
	END
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pSearchOperatorGet]
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title
	   FROM sCommon.tSearchOperator
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pServiceChargeTypeMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			TitleResourceKeyId
	   FROM sOrderEntry.tServiceChargeTypeMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pServiceTypeMasterGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			TitleResourceKeyId
	   FROM sCommon.tServiceTypeMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pStateIdByCityIdGet]
	@rOrgGroupId int,
	@rCityId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--SET @rOrgId = 0
	SELECT ISNULL(CM.StateId, 0) AS StateId, ISNULL(SM.Title, '') AS State,ISNULL(SM.CountryId,0) AS CountryId,ISNULL(COM.Title,'') AS Country,ISNULL(CM.ZipCode, '') AS ZipCode  
	
	FROM sCommon.tCityMaster CM
	LEFT JOIN sCommon.tStateMaster SM ON SM.Id = CM.StateId LEFT JOIN sCommon.tCountryMaster COM ON COM.Id = SM.CountryId
	WHERE CM.Id = @rCityId
	 AND CM.OrgGroupId =  @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pStateMasterAdd]
	@rOrgId [int] = 0,
	@rOrgGroupId int,
	@rCountryId [int] = 0,
	@rTitle [nvarchar](100),
	@rIsShow [bit] = 0,
	@rCreatedUserID [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--SET @rOrgId = 0
	 --DECLARE @lId	BigInt
	 DECLARE @lNextNumber INT     
	 IF(@rIsShow = 0)
		 BEGIN
			 IF(@rCountryId = 0)
				 BEGIN
					 IF EXISTS(SELECT 1 FROM sCommon.tStateMaster WHERE Title = @rTitle AND (CountryId IS NULL OR (CountryId = @rCountryId))AND IsShow = 0 AND OrgGroupId = @rOrgGroupId)
							BEGIN
									SELECT CAST(Id AS BigInt) Id FROM sCommon.tStateMaster WHERE Title = @rTitle AND IsShow = 0 AND CountryId IS NULL AND OrgGroupId = @rOrgGroupId
									RETURN
							END
				 END
			 ELSE
				 BEGIN
					 IF EXISTS(SELECT 1 FROM sCommon.tStateMaster WHERE Title = @rTitle AND ((CountryId = @rCountryId)) AND IsShow = 0 AND OrgGroupId = @rOrgGroupId)
							BEGIN
									SELECT CAST(Id AS BigInt) Id FROM sCommon.tStateMaster WHERE Title = @rTitle AND IsShow = 0 AND ((CountryId = @rCountryId)) AND OrgGroupId = @rOrgGroupId
									RETURN
							END
				 END
		 END
		 
	 	
		
	 --IF NOT EXISTS(SELECT 1 FROM sCommon.tStateMaster WHERE Title = @rTitle)
		BEGIN
			 --EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tStateMaster', 0, 1, 1,@outNextNumber = @lId output
			 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tStateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		 Select @lNextNumber
			 
			 IF(@rIsShow = NULL)
			 BEGIN
				SET @rIsShow = 1
			 END
			 
			INSERT INTO sCommon.tStateMaster
				(
					Id,
					CountryId,
					Title,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime,
					IsObsolete,
					IsShow,
					OrgGroupId
				)
			VALUES
				(
					@lNextNumber,
					(CASE @rCountryId WHEN 0 THEN NULL ELSE @rCountryId END),
					@rTitle,
					@rCreatedUserID,
					sCommon.fGetDate(),
					@rCreatedUserID,
					sCommon.fGetDate(),
					0, 
					@rIsShow,
					@rOrgGroupId
				)
		END
	
		SELECT @lNextNumber AS RESULT
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pStateMasterGet]
	@rOrgGroupId [int],
	@rId [int],
	@rTitle [nvarchar](100) = '',
	@rCountryId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--SET @rOrgId = 0
SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN
	 SELECT SM.Id,
			SM.CountryId,
			SM.Title,
			ISNULL(CM.Title,'') AS CountryTitle,
			
			SM.IsObsolete,
			SM.CreatedUserId,
			SM.CreatedDateTime,
			SM.UpdatedUserId,
			SM.UpdatedDateTime			
	   FROM sCommon.tStateMaster SM
		LEFT JOIN sCommon.tCountryMaster CM
			ON (SM.CountryId = CM.Id)
	  WHERE ((SM.Id = @rId) OR (@rId = 0)) 
		AND ((SM.CountryId = @rCountryId) OR (@rCountryId = 0))
		AND ((SM.Title LIKE @rTitle) OR (@rTitle = ''))
		AND (SM.IsShow = 1)
		AND SM.OrgGroupId = @rOrgGroupId
		
		order by Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pStateMasterList]
	@rCountryId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title
	   FROM sCommon.tStateMaster
	  WHERE CountryId = @rCountryId AND IsObsolete = 0
	  
	  Order BY Title
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pStateMasterModify]
	@rId [int],
	@rTitle [nvarchar](100),
	@rCountryId [int],
	@rIsShow [bit] = 1,
	@rIsObsolete [bit],
	@rUpdatedUserID [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	 UPDATE sCommon.tStateMaster
		SET 
			Title = @rTitle,
			CountryId = @rCountryId,
			
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserID,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pStateMasterSearch]
	@rStateTitle [nvarchar](100) = '',
	@rCountryId [int] = 0,
	@rFlag [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;

IF(@rFlag = 1)
	BEGIN
			SELECT	
				SM.Title Title, 
				SM.ID AS Id, 
				SM.CountryId, 
				SM.IsObsolete, 
				CM.Title CountryName
			FROM sCommon.tCountryMaster CM
				INNER JOIN sCommon.tStateMaster SM
					ON SM.CountryId = CM.Id
			WHERE 
				SM.Title LIKE @rStateTitle
			AND CM.ID = @rCountryId
	END
ELSE
	BEGIN
		IF(@rCountryId <= 0)
			BEGIN
				SELECT	
					SM.Title Title, 
					SM.ID AS Id, 
					SM.CountryId, 
					SM.IsObsolete, 
					CM.Title CountryName
				FROM sCommon.tCountryMaster CM
					INNER JOIN sCommon.tStateMaster  SM
						ON SM.CountryId = CM.Id	
				WHERE
					SM.Title LIKE @rStateTitle + '%'
			END
		ELSE
			BEGIN
				SELECT	
						SM.Title Title, 
						SM.ID AS Id, 
						SM.CountryId, 
						SM.IsObsolete, 
						CM.Title CountryName
					FROM sCommon.tCountryMaster CM
						INNER JOIN sCommon.tStateMaster  SM
							ON SM.CountryId = CM.Id
					WHERE 
						SM.Title LIKE @rStateTitle 
					OR CM.ID = @rCountryId
			END
			
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pStatusMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			StatusTypeId,
		--	Code,
			Title
			 
	   FROM sCommon.tStatusMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pStockItemUpdate] 
	@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

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	
	IF(@rSubCategoryField = 'ItemSubGroup' OR @rSubCategoryField = 'IssueStockUom' OR @rSubCategoryField = 'StockItemCategory' or @rSubCategoryField = 'Bin')
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	
	IF OBJECT_ID('tempdb..ListofData') IS NOT NULL
	DROP TABLE ListofData
	
	CREATE TABLE ListofData(StockItemId bigint,SubCategory nvarchar(200),UpdatedUserId bigint);
		BEGIN
		insert into ListofData
		select E.StockItemId,E.SubCategory,E.UpdatedUserId
		from
		(
				SELECT StockItemId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/StockItem/StockItem', 2)
				WITH (
						StockItemId BIGINT, 
						SubCategory nvarchar(200),
						UpdatedUserId bigint)	
						)E
						
					
	
		set @sql='UPDATE sIp.tStockItemMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sIp.tStockItemMaster EC 
					INNER JOIN ListofData LD ON EC.Id=LD.StockItemId'
		
		Exec sp_executesql @sql
		
		
			 Drop Table ListofData
			 SELECT 1 AS StatusId
	    END    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pStockItemUpdateGet]
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rLocationId bigint,
	 @rIsBlank bit,
	 @rStockItemCategoryId bigint,
	 @rItemSubGroupId bigint,
	 @rItemMainGroupId bigint
	
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		
		IF(@rSubCategory = 'ItemSubGroup' OR @rSubCategory = 'IssueStockUom' OR @rSubCategory = 'StockItemCategory' OR @rSubCategory = 'Bin')
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id' 
		END
		
		 Declare @Sql nvarchar(max)=''
		 
		 SET @Sql = 'Select SA.Id,SA.Code,SA.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SA.'+@rSubCategory+',0) 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SA.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SA.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SA.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SA.'+@rSubCategory+',''0'') 
						END AS SubCategory
							FROM 
							sIp.tStockItemMaster  SA
							inner join sIp.tItemSubGroupMaster ISGM on ISGM.id = SA.ItemSubGroupId
							Where SA.OrgGroupId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.LocationId='+CAST(@rLocationId AS nvarchar(15))+')
							AND (ISGM.ItemMainGroupId = ' + convert(varchar,@rItemMainGroupId) + ' or ' + convert(varchar,@rItemMainGroupId) + '= 0)
							AND (ISGM.Id = ' + convert(varchar,@rItemSubGroupId) + ' or ' + convert(varchar,@rItemSubGroupId) + '= 0)
							AND (SA.StockItemCategoryId = ' + convert(varchar,@rStockItemCategoryId) + ' or ' + convert(varchar,@rStockItemCategoryId) + '= 0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SA.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SA.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SA.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SA.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'	
								
									
	 
	   Exec sp_executesql @sql
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommon].[pStockPrefixSetupGet]
	@rOrgId [smallint] = 0,
	@rId [int] = 0,
	@rPrefix [nvarchar](10) = '',
	@rPrefixFunctionalityId [int] = 0,
	@rIsIncludeObsoleted [bit] = 1,
	@rStoreLocationId int  = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rPrefix = sCommon.fSearchStringGet(@rPrefix)

	 SELECT  ISNULL(PS.Id,0) AS Id, 
			ISNULL(PF.Id,0) AS PrefixFunctionalityId, 
			ISNULL(PS.Prefix,'') AS Prefix, 
			--(CONVERT(NVARCHAR(12), PS.EffectiveDate, 101)) AS EffectiveDate, 
			ISNULL(PS.EffectiveDate,sCommon.fGetDate()) AS EffectiveDate,
			ISNULL(PS.IsObsolete,0) AS IsObsolete, 
			ISNULL(PF.Title,'') AS Title, 
			ISNULL(PS.NumberLength,0) AS SpecifiedPrefixLength, 
			ISNULL(PF.NumberMaxLength,0) AS MaxPrefixLength, 
			ISNULL(PS.Prefix +  CONVERT(NVARCHAR(10), ISNULL(PS.CurrentNumber, 0)),'') AS CurrentPrefix,
			ISNULL(PS.Prefix+SUBSTRING(Convert(Varchar(4),getdate(),121),3,2) +'-'+  CONVERT(NVARCHAR(10), ISNULL(PS.CurrentNumber, 0)),'') as 'CurrentNumber'
			
	   FROM sCommon.tPrefixFunctionality PF		
	   LEFT JOIN sCommon.tPrefixSetup   PS	  
	   ON PS.PrefixFunctionalityId = PF.Id AND (PS.StoreLocationId = @rStoreLocationId OR PS.StoreLocationId=0) 
	   AND PS.OrgId = @rOrgId AND PF.IsObsolete=0
	   
	   WHERE  PF.IsObsolete = 0 AND	   
	         ISNULL(PS.IsObsolete,0) = (CASE WHEN @rIsIncludeObsoleted = 1 THEN PS.IsObsolete ELSE 0 END)
			 AND ((PS.Id = @rId) OR (@rId = 0)) 
	         AND ((PS.Prefix LIKE @rPrefix) OR (@rPrefix = '')) 
	         AND ((PS.PrefixFunctionalityId = @rPrefixFunctionalityId) OR (@rPrefixFunctionalityId = 0)) 
	         AND (ISNULL(PS.EffectiveDate,sCommon.fGetDate()) <= (CASE WHEN @rPrefixFunctionalityId > 0 
	         THEN (sCommon.fGetDate()) ELSE (ISNULL(PS.EffectiveDate,sCommon.fGetDate())) END)) 
	         AND PF.Id in (27,1005,1004,1006,26,52,53,1007,2010) 
	        -- AND PS.OrgId = @rOrgId
	         --AND (PS.StoreLocationid = @rStoreLocationId )OR (@rStoreLocationId = 0)
	          order by PF.Title
	         
	         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pStreetAddressParse]
	@rAddress [nvarchar](max),
	@rStreetOne [nvarchar](50) OUTPUT,
	@rStreetTwo [nvarchar](50) OUTPUT,
	@rStreetThree [nvarchar](50) OUTPUT,
	@rStreetFour [nvarchar](50) OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON	
--SET @rAddress = '1, Global Village, Tanzania, Africa'

DECLARE @lCounter TinyInt
DECLARE @lIndexBegin SmallInt
DECLARE @lIndexEnd SmallInt

DECLARE @lStrLength SmallInt

SET @lCounter = 1 
SET @lStrLength = LEN(@rAddress) + 1
SET @lIndexBegin = 0
WHILE(@lCounter <= 4)
	BEGIN
		SET @lIndexEnd = CHARINDEX(',', @rAddress, @lIndexBegin)
			IF @lCounter = 1 
				BEGIN
				--SELECT 1
				IF @lIndexEnd > @lIndexBegin
					BEGIN
						SET @rStreetOne = LTRIM(RTRIM(SUBSTRING(@rAddress, @lIndexBegin, @lIndexEnd)))
					END
				ELSE
					BEGIN
						SET @rStreetOne = LTRIM(RTRIM(SUBSTRING(@rAddress, @lIndexBegin, @lStrLength)))
						SELECT @lIndexBegin = @lIndexBegin + LEN(@rStreetOne)
					END
				END
				IF @lCounter = 2 AND @rStreetOne IS NOT NULL AND @rStreetOne <> ''
					BEGIN
						IF @lIndexEnd > @lIndexBegin
							BEGIN
								SET @rStreetTwo = LTRIM(RTRIM(SUBSTRING(@rAddress, @lIndexBegin, (@lIndexEnd - @lIndexBegin))))
							END
						ELSE
							BEGIN
								SET @rStreetTwo = LTRIM(RTRIM(SUBSTRING(@rAddress, @lIndexBegin, @lStrLength)))						
								SELECT @lIndexBegin = @lIndexBegin + LEN(@rStreetTwo)
							END
					END
				IF @lCounter = 3 AND @rStreetTwo IS NOT NULL AND @rStreetTwo <> ''
					BEGIN
						IF @lIndexEnd > @lIndexBegin
							BEGIN
								SET @rStreetThree = LTRIM(RTRIM(SUBSTRING(@rAddress, @lIndexBegin, (@lIndexEnd - @lIndexBegin))))
							END
						ELSE
							BEGIN
								SET @rStreetThree = LTRIM(RTRIM(SUBSTRING(@rAddress, @lIndexBegin, @lStrLength)))						
								SELECT @lIndexBegin = @lIndexBegin + LEN(@rStreetThree)
							END					
					END
				
				IF @lCounter = 4 AND @rStreetThree IS NOT NULL AND @rStreetThree <> ''
					BEGIN
						IF @lIndexBegin < @lStrLength SET @lStrLength = @lIndexBegin
						SET @rStreetFour = LTRIM(RTRIM(SUBSTRING(@rAddress, @lIndexBegin, @lStrLength)))						
					END
					
			SET @lIndexBegin = (CASE WHEN @lIndexEnd = 0 THEN @lIndexBegin ELSE @lIndexEnd END) + 1
			SET @lCounter = @lCounter + 1
		END
		--SELECT @rStreetOne, @rStreetTwo, @rStreetThree, @rStreetFour

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pStudentRecord]
	 
	 
	 @rOrgId int,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int
	 

	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT  Name,StudentId,Code  FROM sStudent.vStudentAllDetail WHERE OrgId =@rOrgId 
AND ClassId=@rClassId 
 AND BatchId = @rBatchId  AND DivisionId=@rDivisionId

	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pSubmitDocumentMasterAdd]
	 
	@rId int,
	@rSubmitDocumentFunctionalityId smallint,
	@rDocumentName nvarchar(100),
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sCommon.tSubmitDocumentMaster where DocumentName=@rDocumentName AND OrgId=@rOrgId AND SubmitDocumentFunctionalityId=@rSubmitDocumentFunctionalityId )
		Begin
			select -102 as Result
			RETURN
		End
	END
	ELSE
	BEGIN
		If  Exists(select 1  from sCommon.tSubmitDocumentMaster where DocumentName=@rDocumentName AND OrgId=@rOrgId AND SubmitDocumentFunctionalityId=@rSubmitDocumentFunctionalityId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End

	END
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tSubmitDocumentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sCommon.tSubmitDocumentMaster
		(
			Id,
			SubmitDocumentFunctionalityId,
			DocumentName,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rSubmitDocumentFunctionalityId,
			@rDocumentName,
			@rOrgId
			
		)
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommon.tSubmitDocumentMaster
	    SET
			SubmitDocumentFunctionalityId=@rSubmitDocumentFunctionalityId,
			DocumentName=@rDocumentName,
			OrgId=@rOrgId
	      WHERE Id = @rId    
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pSubmitDocumentMasterGet]
	 @rId int = 0,
	 @rDocumentName nvarchar(100),
	 @rOrgId int,
	 @rIsSearch bit,
	 @rSubmitDocumentFunctionalityId Smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsSearch=1)
		BEGIN
			
			SET @rDocumentName = sCommon.fSearchStringGet(@rDocumentName)
		END
	SELECT 
	
			DM.Id,
			DM.SubmitDocumentFunctionalityId,
			DM.DocumentName,
			FM.Title AS DocumentFunctionalityType
  FROM 
          sCommon.tSubmitDocumentMaster DM
          INNER JOIN sCommon.tSubmitDocumentFunctionalityMaster FM ON FM.Id=DM.SubmitDocumentFunctionalityId
             
  WHERE 
  
       ((DM.Id = @rId) OR (@rId = 0))
		AND  ((DM.DocumentName like @rDocumentName) OR (ISNULL(@rDocumentName,'') = '')) 
		AND(DM.OrgId=@rOrgId)
		AND ((FM.Id = @rSubmitDocumentFunctionalityId) OR (@rSubmitDocumentFunctionalityId = 0))
  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pSubmitDocumentScopeAdd]

	 @rSubmitDocumentId bigint = 0
	,@rSourceTypeId smallint = 0
	,@rSourceId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		INSERT INTO [sCommon].[tSubmitDocumentScope]
		(
			SubmitDocumentId
		   ,SourceTypeId
		   ,SourceId
		)
		VALUES
		(
		    @rSubmitDocumentId
		   ,@rSourceTypeId
		   ,@rSourceId
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pSurnameMasterAdd]
	@rOrgGroupId int,
	@rSurname nvarchar(100),
	@rReligionId int,
	@rFamiliyCast nvarchar(100),
	@rFamiliySubCast nvarchar(100),
	@rCastCategoryId int,
	@rCreatedUserId bigint	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
		IF Exists(select Id from sCommon.tSurnameMaster where Surname=@rSurname AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 

 DECLARE @lNextNumber	Int
 

EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tSurnameMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sCommon.tSurnameMaster
			(	
				Id,
				OrgGroupId,
				Surname,
				ReligionId,
				FamiliyCast,
				FamiliySubCast,
				CastCategoryId,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime
			
			)
		VALUES
			(	
				@lNextNumber,
				@rOrgGroupId,
				@rSurname,
				@rReligionId,
				@rFamiliyCast,
				@rFamiliySubCast,
				@rCastCategoryId,
				0,
				@rCreatedUserId,
				sCommon.fGetDate()
				
	
			)
	
		--SET @rAreaId = @lId
		SELECT @lNextNumber AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pSurnameMasterGet]
	
	@rOrgGroupId int,
	@rId int,
	@rSurname nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 
		BEGIN
			SET @rSurname = sCommon.fSearchStringGet(@rSurname)
			 
		END

BEGIN
	 SELECT SM.Id,			
			SM.Surname,
			SM.ReligionId,
			SM.CastCategoryId,
			ISNULL(RM.Title,'') AS ReligionName,
			ISNULL(CCM.Title,'') AS CastCategoryName,
			SM.FamiliyCast,
			SM.FamiliySubCast,
			SM.IsObsolete
			
	FROM sCommon.tSurnameMaster SM
		LEFT JOIN  sCommon.tReligionMaster RM ON SM.ReligionId=RM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON SM.CastCategoryId= CCM.Id
	WHERE ((SM.Id = @rId) OR (@rId = 0))
		AND((SM.Surname LIKE @rSurname) OR (@rSurname=''))
		AND SM.OrgGroupId = @rOrgGroupId			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pSurnameMasterModify]
	@rId int,
	@rSurname nvarchar(100),
	@rReligionId int,
	@rFamiliyCast nvarchar(100),
	@rFamiliySubCast nvarchar(100),
	@rCastCategoryId int,
	@rIsObsolete bit,
	@rUpdatedUserId bigint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		IF Exists(select Id from sCommon.tSurnameMaster where Surname=@rSurname AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			select -101 as Result
			RETURN
		END 
	 UPDATE sCommon.tSurnameMaster
		SET 
			Surname=@rSurname,
			FamiliyCast=@rFamiliyCast,
			ReligionId=@rReligionId,
			FamiliySubCast=@rFamiliySubCast,
			CastCategoryId=@rCastCategoryId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE Id = @rId		
SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pTableRowIdAdd]
	@rOrgId [smallint],
	@rTableTitle [nvarchar](100),
	@rCurrentNumber [bigint],
	@rSeed [smallint],
	@rIncrement [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	INSERT INTO sCommon.tTableRowId
		(	
			OrgId,
			TableTitle,
			CurrentNumber,
			Seed,
			Increment
		)
	VALUES
		(	
			@rOrgId,
			@rTableTitle,
			@rCurrentNumber,
			@rSeed,
			@rIncrement
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pTableRowIdCurrentNumberModify]
	@rTableName [nvarchar](500) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lCounter SMALLINT
DECLARE @lCount SMALLINT
DECLARE @lMaxId INT
DECLARE @lCurrentNumber INT
DECLARE @lTableType NVARCHAR(100)
DECLARE @lSqlQry NVARCHAR(MAX)

--BEGIN TRY
CREATE TABLE #tRowIdTable
(
	Id SMALLINT IDENTITY(1, 1) PRIMARY KEY,
	TableName NVARCHAR(100),
	TableType NVARCHAR(100)
)

CREATE TABLE #tIsExists
	(
		MaxId INT,
		CurrentNumber INT
	)

INSERT INTO #tRowIdTable(TableName, TableType)

SELECT A.TableTitle, TableType
  FROM (SELECT SchemaName + '.' + TableName TableTitle, 'Static_Conditional' TableType
		  FROM sTool.tObjects 
		 WHERE ConditionString IS NOT NULL
		UNION ALL
		SELECT SchemaName + '.' + TableName TableTitle, 'Static_1To100' TableType
		  FROM sTool.tObjects 
		 WHERE FromID IS NOT NULL
		UNION ALL
		SELECT SchemaName + '.' + TableName TableTitle, 'Transaction' TableType
		  FROM sTool.tObjects 
		 WHERE ConditionString IS NULL
			   AND FromID IS NULL
			   AND IsStatic <> 1
			   AND SchemaName <> 'dbo') AS A
		INNER JOIN (SELECT S.name + '.' + T.name TableTitle
					  FROM sys.schemas S
						   INNER JOIN sys.tables T
								   ON S.schema_id = T.schema_id
						   INNER JOIN sys.columns C
								   ON T.object_id = C.object_id
								  AND C.name = 'Id') IdFieldTables
			   ON A.TableTitle = IdFieldTables.TableTitle
 WHERE (A.TableTitle = @rTableName) OR (@rTableName = '')
 AND A.TableTitle <> 'sIpo.tPatientNurseAssignmentDetail'
 ORDER BY A.TableTitle
 
 --SELECT * FROM sTool.tObjects WHERE TableName = 'tStoreLocationMaster' AND Id = 9419
 --SELECT TableName, TableType FROM #tRowIdTable WHERE TableName = 'sIp.tStoreLocationMaster'
 
SELECT @lCount = MAX(Id) FROM #tRowIdTable
SET @lCounter = 1
	
WHILE(@lCounter <= @lCount)
	BEGIN
		SELECT @rTableName = TableName,
			   @lTableType = TableType
		  FROM #tRowIdTable
		 WHERE Id = @lCounter
		 
		 TRUNCATE TABLE #tIsExists
		 
		 IF @lTableType = 'Static_1To100'
			BEGIN
				--print 'a'
				SET @lSqlQry = 'INSERT INTO #tIsExists(MaxId, CurrentNumber) 
								 SELECT (CASE WHEN A.MaxId > C.MaxId THEN A.MaxId ELSE C.MaxId END) MaxId, B.CurrentNumber
								   FROM (SELECT ToId + 1 MaxId, SchemaName + ''.'' + TableName TableTitle
										   FROM sTool.tObjects 
										   WHERE FromID IS NOT NULL
										         AND SchemaName + ''.'' + TableName = ''' + @rTableName + ''') A
										 INNER JOIN (SELECT MAX(Id) MaxId, ''' + @rTableName + ''' TableTitle
										   FROM ' + @rTableName + ') C
											     ON A.TableTitle = C.TableTitle
										LEFT JOIN sCommon.tTableRowId B
											   ON B.TableTitle = ''' + @rTableName + ''''
				IF @rTableName = '@@sIp.tStoreLocationMaster'
					BEGIN
						SELECT 'a', @lSqlQry
					END
			END
		 ELSE
			BEGIN
				--print 'b'
				 SET @lSqlQry = 'INSERT INTO #tIsExists(MaxId, CurrentNumber) 
								 SELECT MaxId, B.CurrentNumber
								   FROM (SELECT MAX(Id) MaxId
										   FROM ' + @rTableName + ') A
										LEFT JOIN sCommon.tTableRowId B
											   ON B.TableTitle = ''' + @rTableName + ''''
			END 
		 EXEC sp_executesql @lSqlQry
		 
		 SET @lMaxId = 0 
		 SET @lCurrentNumber = 0
		 SELECT @lMaxId = ISNULL(MaxId, 0), @lCurrentNumber = ISNULL(CurrentNumber, 0) FROM #tIsExists
		 
		 --IF @rTableName = 'sCommon.tClinicalDepartmentMaster'
			--begin
		 --SELECT @lSqlQry
		 --SELECT @lMaxId, @lCurrentNumber
			--end
		 
		 
		 --IF (@lMaxId > 0) AND (@lMaxId <> @lCurrentNumber)
		 IF (@lMaxId <> @lCurrentNumber)
			BEGIN
				 EXEC sCommon.pTableRowIdGet @rTableName, 1, 1, 1
				 SELECT @lCurrentNumber = T.CurrentNumber
				   FROM sCommon.tTableRowId T 
				  WHERE T.TableTitle = @rTableName 
				 
				 --SET @lSqlQry = 'UPDATE sCommon.tTableRowId
					--			 SET CurrentNumber = (SELECT ISNULL(MAX(ISNULL(Id, 0)), 0) FROM ' + @rTableName + ') 
					--			 WHERE TableTitle = ''' + @rTableName + ''''

				 IF ISNULL(@lMaxId, 0) = 0 
					BEGIN
						SET @lSqlQry = 'DELETE sCommon.tTableRowId
										 WHERE TableTitle = ''' + @rTableName + ''''
					END
				 ELSE
					BEGIN	
						 SET @lSqlQry = 'UPDATE sCommon.tTableRowId
										 SET CurrentNumber =  ' + CAST(@lMaxId AS NVARCHAR(10)) + '
										 WHERE TableTitle = ''' + @rTableName + ''''
					END								 
				--SELECT @lSqlQry
				EXEC sp_executesql @lSqlQry
				SELECT T.TableTitle, @lCurrentNumber PrevCurrentNumber, T.CurrentNumber, T.Seed, T.Increment FROM sCommon.tTableRowId T WHERE T.TableTitle = @rTableName 
			END
		SET @lCounter = @lCounter + 1
	END
	
DROP TABLE #tRowIdTable	
DROP TABLE #tIsExists
--END TRY
--BEGIN CATCH
--	SELECT ERROR_MESSAGE(), @rTableName, @lSqlQry
--END CATCH

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pTableRowIdGet]
	@rOrgId [bigint],
	@rTableTitle [nvarchar](100),
	@rIsCurrentNumber [bit] = 0,
	@rSeed [bigint] = 1,
	@rIncrement [bigint] = 1,
	@outNextNumber [bigint] OUTPUT  
WITH EXECUTE AS CALLER
AS
BEGIN
	SET NOCOUNT ON;

	-- Check if record exists
	IF NOT EXISTS(SELECT 1
				    FROM sCommon.tTableRowId WITH (NOLOCK) --(ROWLOCK)
			        WHERE TableTitle = @rTableTitle AND OrgId = @rOrgId)
	BEGIN
		RAISERROR('Add Table RowId detail in table-Row for TableTitle [%s] and OrgId [%d] not found in tTableRowId.',16, 1, @rTableTitle, @rOrgId);
	END

	-- Call the modify procedure
	EXECUTE sCommon.pTableRowIdModify
		@rOrgId,
		@rTableTitle = @rTableTitle,
		@rIsCurrentNumber = @rIsCurrentNumber,
		@rSeed = @rSeed,
		@rIncrement = @rIncrement,
		@rNextNumber = @outNextNumber OUTPUT;
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pTableRowIdOrgGroupAdd]
	@rOrgGroupId [smallint],
	@rTableTitle [nvarchar](100),
	@rCurrentNumber [bigint],
	@rSeed [smallint],
	@rIncrement [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	INSERT INTO sCommon.tTableRowId
		(	
			OrgId,
			TableTitle,
			CurrentNumber,
			Seed,
			Increment
		)
	VALUES
		(	
			@rOrgGroupId,
			@rTableTitle,
			@rCurrentNumber,
			@rSeed,
			@rIncrement
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pTableRowIdOrgGroupGet]
	@rOrgGroupId [bigint],
	@rTableTitle [nvarchar](100),
	@rIsCurrentNumber [bit] = 0,
	@rSeed [bigint] = 1,
	@rIncrement [bigint] = 1
	,@outNextNumber [bigint] OUTPUT  
WITH EXECUTE AS CALLER
AS
BEGIN
	SET NOCOUNT ON
	DECLARE	@loNextNumber BigInt
	DECLARE @lSqlStr NVARCHAR(1000)
	DECLARE @lSchemaName NVARCHAR(100)
	DECLARE @lTableName NVARCHAR(100)


	--SET @lSchemaName = SUBSTRING(@rTableTitle, 1, CHARINDEX('.', @rTableTitle, 1) - 1)
	--SET @lTableName = SUBSTRING(@rTableTitle, CHARINDEX('.', @rTableTitle, 1) + 1, LEN(@rTableTitle))


	IF NOT EXISTS(SELECT 1
				    FROM sCommon.tTableRowId WITH (ROWLOCK)
			       WHERE TableTitle = @rTableTitle AND OrgId = @rOrgGroupId)
		BEGIN
		
			SET @lSqlStr = 'Add Table RowId detail in table'
			RAISERROR(@lSqlStr, 16, 1)
					
		    --  commented to avoid SCHEMA TABLE check at DB level 
			--IF EXISTS(SELECT 1 
			--		    FROM (SELECT schema_id, name 
			--					FROM sys.objects
			--				   WHERE name = @lTableName
			--						 AND Type = 'U') O
			--			     INNER JOIN (SELECT schema_id, name 
			--							   FROM sys.schemas 
			--							  WHERE name = @lSchemaName) S
			--					     ON O.schema_id = S.schema_id)
			--	BEGIN
			--  commented to avoid Identity check since it 
			--		IF NOT EXISTS(SELECT 1
			--						FROM (SELECT schema_id, object_id, name
			--								FROM sys.objects
			--							   WHERE name = @lTableName
			--									 AND Type = 'U') O
			--						INNER JOIN (SELECT schema_id, name 
			--									  FROM sys.schemas 
			--									 WHERE name = @lSchemaName) S
			--								ON O.schema_id = S.schema_id
			--						INNER JOIN (SELECT object_id, name 
			--									  FROM sys.columns
			--									 WHERE is_identity = 1) C
			--								ON O.object_id = C.object_id
			--						WHERE O.name = @lTableName)
			--			BEGIN
			--				--// Inserting new row.
			-- 			EXECUTE sCommon.pTableRowIdAdd @rOrgId, @rTableTitle, 0, @rSeed, @rIncrement
			--			END
			--		ELSE
			--			BEGIN
			--				SET @lSqlStr = 'Table has an auto generated identity field. To get current number use IDENT_CURRENT(''' + @rTableTitle + ''').'
			--				RAISERROR(@lSqlStr, 16, 1)
			--			END
			--	END
			--ELSE
			--	BEGIN
			--		SET @lSqlStr = 'Invalid object name "' + @rTableTitle + '".'
			--		RAISERROR(@lSqlStr, 16, 1)
			--	END
		END
		
	--	print 'pass before'
	--// If @rIsCurrentNumber is true, getting the current number otherwise updating and getting next number. 
	EXECUTE sCommon.pTableRowIdModify  @rOrgGroupId, @rTableTitle = @rTableTitle, @rIsCurrentNumber = @rIsCurrentNumber,@rSeed =@rSeed,@rIncrement = @rIncrement, @rNextNumber = @outNextNumber OUTPUT
  --  print 'pass after'
 
	--@outNextNumber
	--ISNULL(@loNextNumber, 0)
	-- print 'pass after'
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pTableRowIdOrgGroupModify]
	@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
	IF @rCurrentNumber > 0
		BEGIN
			UPDATE sCommon.tTableRowId 
			   SET CurrentNumber = @rCurrentNumber,
			   UpdatedDateTime = sCommon.fGetDate()
			 WHERE TableTitle = @rTableTitle AND
					OrgId = @rOrgGroupId
			 
		END
	ELSE
		BEGIN
			--SELECT CurrentNumber, 
			--		@rSeed, Seed,
			--		@rIncrement, Increment
			-- FROM sCommon.tTableRowId
			--  WHERE TableTitle = @rTableTitle
			  
			 UPDATE sCommon.tTableRowId
				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
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pTelephoneDirectoryGet]
	@rDeptId [int] = 0,
	@rRoleId [int] = 0,
	@rEmpId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

DECLARE @lDeptName VARCHAR(100)
DECLARE @lRoleName VARCHAR(100)
DECLARE @lEmpName VARCHAR(100)

--SELECT @lDeptName = ODM.Title FROM sSetup.tDepartmentMaster ODM WHERE ODM.Id = @rDeptId
--SELECT @lRoleName = R.Title FROM sSecurity.tRole R WHERE R.Id = @rRoleId
-- Commented For Employee Migration
--SELECT @lEmpName = EM.FirstName + '' + EM.MiddleName + '' + EM.LastName  FROM sCommon.tEmployeeMaster EM WHERE EM.Id   = @rEmpId
-- End of comment for Employee Migration
-- Added for Employee Migration
SELECT @lEmpName = EM.FirstName + '' + EM.MiddleName + '' + EM.LastName  FROM sHrm.vExtEmployeeMaster EM WHERE EM.Id   = @rEmpId
-- End of addition for Employee Migration
IF(@rEmpId IS NULL)
	BEGIN
		SET @rEmpId = 0
	END

BEGIN

	SELECT  DISTINCT
			ISNULL(ODM.Title, '')							AS InputDepartmentName,
		--	ISNULL(EJD.JobTitle, '')								AS InputRoleName,
			ISNULL(EM.EmployeeName, '')AS Name,
			ISNULL(EM.Code, '')								AS Empcode,
			-- Added for Employee Migration
			ISNULL(ECOM.PhoneNoCompany, '')				AS TelNo,
			ISNULL(ECOM.ExtensionNo, '')				AS Extn,
			ISNULL(EC.MobileNumber, '')				AS MobNo,
			ISNULL(ECOM.CompanyEmail, '')						AS EmailId,
			-- End of addition for Employee Migration
			-- Commented For Employee Migration
			--ISNULL(EC.PhoneNumberOffice, '')				AS TelNo,
			--ISNULL(EC.ExtensionPhoneNumber, '')				AS Extn,
			--ISNULL(EC.PhoneNumberMobile, '')				AS MobNo,
			--ISNULL(EC.EmailPrimary, '')						AS EmailId,
			-- End of comment for Employee Migration
			ISNULL(EM.FirstName + '' + EM.MiddleName + '' + EM.LastName, '')AS InputEmpName						
	FROM 
        -- Commented For Employee Migration
   	    --sCommon.tEmployeeMaster EM
	    -- END of comment for Employee Migration
 	    -- Added for Employee Migration
	    sHrm.vExtEmployeeMaster EM
	    INNER JOIN sHrm.vExtEmployeeJobDetail EJD
	    ON EM.Id = EJD.EmployeeId
	    INNER JOIN sHrm.vExtEmployeeCommunication ECOM
	    ON ECOM.EmployeeId = EM.Id
	    INNER JOIN sHrm.vExtEmployeeContact EC
	    ON ECOM.PresentContactId = EC.Id
	    -- END of addition for Employee Migration
		LEFT JOIN sSecurity.tUser U
			ON U.EmployeeId = EM.Id
		LEFT JOIN sSetup.tDepartmentMaster ODM
			ON ODM.Id = EJD.OrganizationDepartmentId
		LEFT JOIN sSecurity.tUserRole UR
					ON UR.UserId = U.Id	
		-- Commented For Employee Migration			
		--LEFT JOIN sCommon.tEmployeeContact EC
		--	ON EC.Id = EM.CommunicationContactId
		-- END of comment for Employee Migration
		LEFT JOIN sSecurity.tRole R
					ON UR.RoleId = R.Id
	WHERE ((ODM.Id = @rDeptId) OR (@rDeptId = 0))
	--	 AND ((EJD.JobTitleId = @rRoleId) OR (@rRoleId = 0))
		 AND ((EM.Id   = @rEmpId) OR (@rEmpId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pTestCodeForTestIdGet]
	@rId [int] = 0,
	@rSeviceCategoryId [int] OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	SET @rSeviceCategoryId = 0
	SELECT SM.ServiceCode
		FROM sOrderEntry.vExtServiceMaster SM WHERE (ID = @rId )
	SELECT @rSeviceCategoryId = SM.ServiceCategoryId
		FROM sOrderEntry.vExtServiceMaster SM WHERE (ID = @rId )
		
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pTestResultMasterModify]
	@rId [tinyint],
	@rCode [nvarchar](10),
	@rTitle [nvarchar](20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tTestResultMaster
		SET 
			Code = @rCode,
			Title = @rTitle
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pUpdateCurruntIdForOrgGroup]
	@rOrgGroupId int	 
WITH EXECUTE AS CALLER
AS
BEGIN
	 
	 Declare @1Count int
Declare @1TableName nvarchar(100)
Declare @1IdScope nvarchar(30)
DECLARE @rSql nvarchar(max)
DECLARE @1MaxTableId bigint
 
 

	CREATE TABLE #TempLedgerGroupMaster
	(
		Id bigint identity,	 
		TableTitle nvarchar(100),
		IdScope nvarchar(10)	   
	)
	Insert Into #TempLedgerGroupMaster
	Select TableTitle,IdScope from sCommon.tTableRowIdMaster Where IdScope != 'Static'
	select @1Count = COUNT(*) from #TempLedgerGroupMaster

	--select @1Count = 1
	--SET @rOrgGroupId = 1001

	While @1Count > 0
	   BEGIN      
		  Select @1TableName = TableTitle,
		  @1IdScope = IdScope From #TempLedgerGroupMaster Where Id = @1Count    
	      
		  SET @rSql =  'Select @1MaxTableId = ISNULL(MAX(Id),(Convert(nvarchar(10),'+Convert(nvarchar(10),@rOrgGroupId)+')+''00000''))
		  FROM '+@1TableName+' Where '+@1IdScope+'Id='+Convert(nvarchar(10),@rOrgGroupId)+''	     
			
		  EXECUTE sp_executesql @rSql, N'@1MaxTableId bigint OUTPUT', @1MaxTableId = @1MaxTableId OUTPUT
	     
		  Update sCommon.tTableRowId set CurrentNumber = @1MaxTableId Where TableTitle = @1TableName ANd OrgId = @rOrgGroupId
	     
		  SET @1Count = @1Count - 1  
	   END  
	   
	DROP TABLE #TempLedgerGroupMaster
	 
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 
CREATE OR ALTER PROCEDURE [sCommon].[pUploadDocumentAdd]
	 
	@rUploadFunctionalityId smallint,
	@rUserSourceTypeId smallint,
	@rUserSourceId bigint,
	@rDocumentId bigint,
	@rDocumentName nvarchar(200),
	@rCreatedUserId bigint,
	@rDocumentSize decimal (12,2) = 0.00,
	@rOrgGroupBatchId int = 0   
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	--if not not exists then record add
	IF ((@rUserSourceTypeId = 95 OR @rUserSourceTypeId = 2003) AND @rUserSourceId <> 0)
	BEGIN 
	IF NOT EXISTS (SELECT 1 FROM sCommon.tUploadDocument WHERE UploadFunctionalityId = @rUploadFunctionalityId AND DocumentId = @rDocumentId AND DocumentName = @rDocumentName AND OrgGroupBatchId = @rOrgGroupBatchId AND UserSourceId = @rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId)
	BEGIN		
	INSERT INTO sCommon.tUploadDocument
		(
		UploadFunctionalityId,
		UserSourceTypeId,
		UserSourceId,
		DocumentId,
		DocumentName,
		CreatedUserId,
		CreatedDateTime,
		DocumentSize,
		OrgGroupBatchId
		)
	VALUES
		(
		@rUploadFunctionalityId,
		@rUserSourceTypeId,
		@rUserSourceId,
		@rDocumentId,
		@rDocumentName,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rDocumentSize,
		@rOrgGroupBatchId
		)
	 END
	END
	ELSE
	BEGIN
	IF NOT EXISTS (SELECT 1 FROM sCommon.tUploadDocument WHERE UploadFunctionalityId = @rUploadFunctionalityId AND DocumentId = @rDocumentId AND DocumentName = @rDocumentName AND OrgGroupBatchId = @rOrgGroupBatchId)
	BEGIN
	INSERT INTO sCommon.tUploadDocument
		(
		UploadFunctionalityId,
		UserSourceTypeId,
		UserSourceId,
		DocumentId,
		DocumentName,
		CreatedUserId,
		CreatedDateTime,
		DocumentSize,
		OrgGroupBatchId
		)
	VALUES
		(
		@rUploadFunctionalityId,
		@rUserSourceTypeId,
		@rUserSourceId,
		@rDocumentId,
		@rDocumentName,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rDocumentSize,
		@rOrgGroupBatchId
		)
	 END
	 END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommon].[pUploadDocumentDelete]
	 
	@rUploadFunctionalityId smallint,
	@rDocumentId bigint,
	@rDocumentName nvarchar(200),
	@rUserSourceId bigint = 0,
	@rUserSourceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

	DELETE FROM sCommon.tUploadDocument WHERE DocumentId = @rDocumentId AND UploadFunctionalityId = @rUploadFunctionalityId	AND DocumentName = @rDocumentName 
	AND ((UserSourceId = @rUserSourceId) OR (@rUserSourceId = 0)) AND ((UserSourceTypeId = @rUserSourceTypeId) OR (@rUserSourceTypeId = 0))
	 
	SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommon].[pUploadDocumentGet]
	 
	@rUploadFunctionalityId smallint,
	@rDocumentId bigint,
	@rUserSourceTypeId smallint = 0,
	@rUserSourceId bigint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

	SELECT 
		DocumentId,
		DocumentName
	FROM 
		sCommon.tUploadDocument
	WHERE 
		DocumentId = @rDocumentId
		AND UploadFunctionalityId = @rUploadFunctionalityId	 
		AND ((UserSourceTypeId = @rUserSourceTypeId) OR (@rUserSourceTypeId = 0))
		AND ((UserSourceId = @rUserSourceId) OR (@rUserSourceId = 0))
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommon].[pUploadedDocumentDetailsGet]
	 
	@rUploadFunctionalityId smallint,
	@rDocumentId bigint,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

	SELECT 
		DocumentId,
		DocumentName
	FROM 
		sCommon.tUploadDocument
	WHERE 
		DocumentId = @rDocumentId
		AND UploadFunctionalityId = @rUploadFunctionalityId	 
		AND ((OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pUploadedFilePathget]
@rSourceId bigint,
@rSourceTypeId smallint,
@rOrgId smallint

AS
BEGIN

	DECLARE @FilePath nvarchar(300)
	SET @FilePath=(SELECT FilePath FROM sCommon.tFilePath WHERE SourceTypeId=@rSourceTypeId AND OrgId = @rOrgId )
	SELECT FU.Id,	
		   FU.FileName,
		   (@FilePath + '/' + FU.FileName) AS FilePath
	FROM sCommon.tFileUpload FU 
	WHERE FU.SourceTypeId=@rSourceTypeId AND
		  FU.SourceId=@rSourceId And
		  FU.OrgId=@rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pUserPreferenceModuleGet]
	  
	  @rUserId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	  select DISTINCT ModuleId,M.Title AS ModuleName from sSecurity.tPermission P
INNER JOIN sSecurity.tUserRole R ON R.RoleId=P.RoleId AND R.IsObsolete = 0
INNER JOIN sSecurity.tTask T ON T.Id=P.TaskId
INNER JOIN sCommon.tModuleMaster M ON M.Id=T.ModuleId

WHERE R.UserId = @rUserId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommon].[pUserPreferenceModuleScreenGet]
	  
	  @rUserId bigint,
	  @rModuleId int,
	  @rResourceTypeId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	  select DISTINCT S.Id AS ScreenId,T.Title AS ScreenName
	   from sSecurity.tPermission P
INNER JOIN sSecurity.tUserRole R ON R.RoleId=P.RoleId AND R.IsObsolete = 0
INNER JOIN sSecurity.tTask T ON T.Id=P.TaskId AND T.IsObsolete=0
INNER JOIN sCommon.tModuleMaster M ON M.Id=T.ModuleId AND T.IsObsolete = 0
INNER JOIN sSecurity.tScreen S ON S.TaskId=T.Id AND S.IsObsolete = 0
LEFT JOIN sSecurity.tMenu ME On ME.ScreenId = S.Id AND ME.IsObsolete =0

WHERE R.UserId = @rUserId
AND T.ModuleId = @rModuleId
AND ((T.ResourceTypeId = @rResourceTypeId) OR @rResourceTypeId = 0)
AND (P.Permission & 2) =2

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pValidationExprGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			ISNULL(RegularExpression,0) AS RegEx
	   FROM sCommon.tValidationType
	  WHERE (Id = @rId)
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pValidationTypeGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			Remark,
			DisplayText,
			DisplayTextResourceKeyId,
			RegularExpression,
			IsObsolete
	   FROM sCommon.tValidationType
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pValidationTypeModify]
	@rId [tinyint],
	@rTitle [nvarchar](50),
	@rRemark [nvarchar](300),
	@rDisplayText [nvarchar](50),
	@rDisplayTextResourceKeyId [smallint],
	@rRegularExpression [nvarchar](300),
	@rIsObsolete [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sCommon.tValidationType
		SET 
			Title = @rTitle,
			Remark = @rRemark,
			DisplayText = @rDisplayText,
			DisplayTextResourceKeyId = @rDisplayTextResourceKeyId,
			RegularExpression = @rRegularExpression,
			IsObsolete = @rIsObsolete
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pVendorDetails]
	@rVendorCategoryId [int] = 0,
	@rVendorCategoryTitle [nvarchar](50) = '',
	@rVendorCategoryCode [nvarchar](50) = '',
	@rVendorId [int] = 0,
	@rVendorCode [nvarchar](50) = '',
	@rVendorTitle [nvarchar](50) = '',
	@rIsWildCardSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF @rIsWildCardSearch = 1
		BEGIN
			SET @rVendorCategoryCode = sCommon.fSearchStringGet(@rVendorCategoryCode)
			SET @rVendorTitle = sCommon.fSearchStringGet(@rVendorTitle)			
		END
	 
	 SELECT VCM.Id AS VendorCategoryId,
			VCM.Code AS VendorCategoryCode,
			VCM.Title AS VendorCategoryTitle,
			VM.Id AS VendorID,
			VM.Code AS VendorCode,
			VM.Title AS VendorTitle		
	FROM sProcurement.vExtVendorCategoryMaster VCM 
	INNER JOIN sProcurement.vExtVendorMaster VM
	ON VCM.Id  = VM.VendorCategoryId 
    WHERE VCM.IsObsolete = 0	  
	   AND ((VCM.Id = @rVendorCategoryId) OR (@rVendorCategoryId = 0))
	   AND ((VCM.Code LIKE @rVendorCategoryCode) OR (ISNULL(@rVendorCategoryCode, '') = ''))
	   AND ((VCM.Title LIKE @rVendorCategoryTitle) OR (ISNULL(@rVendorCategoryTitle, '') = ''))
	   AND ((VM.Id LIKE @rVendorId) OR (@rVendorId = 0))
	   AND ((VM.Code LIKE @rVendorCode) OR (ISNULL(@rVendorCode, '') = ''))
	   AND ((VM.Title LIKE @rVendorTitle) OR (ISNULL(@rVendorTitle, '') = ''))	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommon].[pXMLDesignationMasterAdd]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN

DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
BEGIN TRY
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	
	-----------------------
	UPDATE sHrm.tEmployeeDesignationMaster
	SET
		Code =A1.Code,
		Title =A1.Title,
		UpdatedDateTime = sCommon.fGetDate()
	FROM
	(
		SELECT					
			Id,
			Code,
			Title
			FROM OPENXML (@intDoc, '/Table/DesignationMaster', 1)
			WITH
			(
					Id int '@Id',
					Code nvarchar(100) '@Code',
					Title nvarchar(100) '@Title',
					OrgId int '@OrgId'	
			))A1 INNER JOIN sHrm.tEmployeeDesignationMaster E ON E.Id = sCommon.fGetIntIdForOrg(A1.Id,@rOrgId)
	
	
	INSERT INTO sHrm.tEmployeeDesignationMaster
	(		Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
	)
	SELECT	
			sCommon.fGetIntIdForOrg(A.Id,A.OrgId),
			A.Code,
			A.Title,
			0,
			9999000000003,
			sCommon.fGetDate(),
			9999000000003,
			sCommon.fGetDate(),
			A.OrgId
			
	FROM OPENXML (@intDoc, '/Table/DesignationMaster', 1)
	WITH
	(
			Id int '@Id',
			Code nvarchar(100) '@Code',
			Title nvarchar(100) '@Title',
			OrgId int '@OrgId'
	)A LEFT JOIN sHrm.tEmployeeDesignationMaster EM ON EM.ID = sCommon.fGetIntIdForOrg(A.Id,@rOrgId)
	WHERE EM.Id IS NULL
	

	EXEC sp_xml_removedocument @intDoc
	
	SELECT @lNextNumber = MAX(ID) FROM sHrm.tEmployeeDesignationMaster Where OrgId=@rOrgId
    EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeDesignationMaster', @rCurrentNumber = @lNextNumber 

	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommonService].[GetStudentProfile]
	@racademicId bigint,
	@rbatchId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT A.OrgId, BatchId, StudentId, A.Id AS AcademicId, SM.Code, A.RollNo, (FirstName +' '+MiddleName+' '+LastName) AS StudentName,
                            SM.FirstName, SM.MiddleName, SM.LastName, A.ClassId, A.DivisionId, (CM.DisplayTitle +'-'+ DM.DisplayTitle) AS ClassDivision,
                            DPM.Id AS DepartmentId, DPM.DisplayTitle AS DepartmentName, SM.SUID, B.Title as BatchName
                             FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
                            INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
                            INNER JOIN sSetup.tDepartmentMaster DPM ON DPM.Id = CM.DepartmentId
                            INNER JOIN sSetup.tBatchMaster B ON b.Id = A.BatchId
							WHERE A.Id=@racademicId AND BatchId = @rbatchId



END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommonService].[pClassGet]
	@rDepartmentId int,
	@rOrgId int,
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		SELECT DISTINCT CM.Id,CM.DisplayTitle AS Title FROM sSetup.tDivisionMaster DM
                               INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=  @rOrgId 
                               INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
                               WHERE  CM.DepartmentId= @rDepartmentId  AND U.UserId = @rUserId
	END TRY

	BEGIN CATCH
	 SELECT -1 as Result
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sCommonService].[pDepartmentGet]
		@rOrgId int,
		@rUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT 
		DM.Id, 
		DM.DisplayTitle AS Title 
		FROM sSetup.tDepartmentMaster DM 
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id 
		AND U.SourceTypeId=2017
        WHERE IsObsolete = 0 
		AND OrgId = @rOrgId  
		AND UserId = @rUserId
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommonService].[pDivisionGet]
	 
	 @rClassId int,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rOrgId int,
	 @rUserId bigint,
	 @rBatchId int,
	 @rAttendanceEntryBasedOn nvarchar
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	set @rAttendanceEntryBasedOn = 'User Access'
	BEGIN TRY
        if (@rAttendanceEntryBasedOn = 'Class Teacher' AND @rUserSourceTypeId = 95)
			BEGIN
				SELECT DISTINCT DM.Id AS Id, DM.DisplayTitle AS Title
					   FROM sSetup.tClassMaster CM 
					   INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
                       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
                       WHERE DM.InchargeemployeeID= @rUserSourceId  
					   AND CM.OrgId= @rOrgId 
					   AND CM.Id = @rClassId
			END	 
		else if (@rAttendanceEntryBasedOn = 'Academic Setup' AND @rUserSourceTypeId = 95)
				BEGIN
					SELECT DISTINCT DivisionId AS Id, DivisionTitle, DivisionOrderIndex AS Title 
                        FROM sAcademic.vTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=TSD.OrgId 
						WHERE  TSD.EmployeeId= @rUserSourceId 
						AND TSD.ClassId = @rClassId
                        ORDER BY DivisionOrderIndex
				END
		else
					BEGIN
						SELECT DM.Id,DM.DisplayTitle AS Title 
							   FROM sSetup.tDivisionMaster DM 
                               INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId= @rOrgId 
                               INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005 
                               WHERE  CM.Id = @rClassId 
							   AND UserId = @rUserId 
							   Order by DM.OrderIndex
					END
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommonService].[pEmployeeDivisionClassDepartmentGet]
	 
	 @rEmployeeIds nvarchar(max),
	 @rClassIds nvarchar(max),
	 @rDepartmentIds nvarchar(max),
	 @rDivisionIds nvarchar(max),
	 @rOrgId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
		
		SET @rEmployeeIds = REPLACE(@rEmployeeIds, ',', ''',''');
		SET @rDepartmentIds = REPLACE(@rDepartmentIds, ',', ''',''');
		SET @rClassIds = REPLACE(@rClassIds, ',', ''',''');
		SET @rDivisionIds = REPLACE(@rDivisionIds, ',', ''',''');
		DECLARE @sql NVARCHAR(MAX),
		@OrgId NVARCHAR(10);
		SET @OrgId = CONVERT(NVARCHAR(50), @rOrgId);
		SET @sql = 'SELECT EmployeeId AS Id,
				EmployeeName AS Title ,
				Code
				FROM sHrm.vEmployeeCommunication 
				WHERE ISNULL(IsOtherUser,0) = 0 
				AND StatusId=7 
				AND Id in (''' + @rEmployeeIds + ''')
				AND OrgId='''+ @OrgId + ''' ORDER BY Code
	
				SELECT 
				Distinct DM.Id, 
				DM.DisplayTitle AS Title 
				FROM sSetup.tDepartmentMaster DM 
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id 
				AND U.SourceTypeId=2017
				WHERE DM.IsObsolete = 0 
				AND OrgId = '''+ @OrgId + '''  
				AND DM.Id in (''' + @rDepartmentIds + ''')
		
				SELECT DISTINCT 
				CM.Id,
				CM.DisplayTitle AS Title 
				FROM sSetup.tDivisionMaster DM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=  '''+ @OrgId + ''' 
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
				WHERE  CM.Id in (''' + @rClassIds + ''') AND DM.IsObsolete = 0 

				SELECT DM.Id,DM.DisplayTitle AS Title 
				FROM sSetup.tDivisionMaster DM 
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
				WHERE DM.Id in (''' + @rDivisionIds + ''') and DM.OrgId = '''+ @OrgId + '''';

		EXEC sp_executesql @sql;
	END TRY
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommonService].[pEmployeeGet]
	 
	 @rDepartmentId int,
	 @rOrgId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
	SELECT EmployeeId AS Id,
	EmployeeName AS Title ,
	Code
	FROM sHrm.vEmployeeCommunication 
	WHERE ISNULL(IsOtherUser,0) = 0 
	AND StatusId=7 
	AND DepartmentId=@rDepartmentId 
	AND OrgId=@rOrgId ORDER BY Code
	END TRY

	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommonService].[pGetStudentDetail]
	@StudentDetail [sCommonService].[GetStudentDetailType] READONLY,
	@AssigneeToId tinyint = 2

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		SELECT
			2003 as SourceTypeId,
			SM.Id as SourceId,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			'Student' AS SourceType,
			SA.RollNo,
			SA.Code,
			SA.ClassName,
			SA.ClassId,
			SA.DivisionId,
			SA.DivisionName,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ClassName+' - '+ SA.DivisionName AS ClassDepartment,
			OM.DisplayTitle AS OrgName,
			AM.Id as AssigneeToId,
			AM.Title As AssignedTo
			FROM sStudent.tStudentMaster SM 
			INNER JOIN  sStudent.vStudentAcademic SA ON SM.Id=SA.StudentId AND SA.IsActiveBatch= 1 AND SA.StatusId= 1 AND SA.OrgID IN (SELECT OrgId FROM @StudentDetail) 
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
			left JOIN sCommon.tAssigneeMaster AM ON AM.Id = @AssigneeToId where SM.Id IN (SELECT AcademicId FROM @StudentDetail)
	END TRY

	BEGIN CATCH
	 SELECT -1 as Result
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommonService].[pGetUserByMeetingWith]
    @rMeetingWithId INT,
    @rMeetingWithName VARCHAR(255),
	@rOrgId smallint,
	@rBatchId int
AS
BEGIN
    IF @rMeetingWithName = 'SubjectTeacher' and @rMeetingWithId = 2
    BEGIN
        -- Select data based on meetingID
        SELECT DISTINCT EM.ID AS Id, EM.FirstName + ' ' + EM.LastName AS Name 
        FROM sAcademic.tTeacherSubjectDivision TSD
		INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = TSD.DivisionId and SA.BatchId = @rBatchId
        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TSD.SubjectId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD.EmployeeId and EM.StatusId = 7 and EM.OrgID = @rOrgId 
    END
    ELSE IF @rMeetingWithName = 'ClassTeacher' and @rMeetingWithId = 1
    BEGIN
        -- Select data for principal
        	 SELECT DISTINCT EMT.ID AS Id, EMT.FirstName + ' ' + EMT.LastName AS Name
			 FROM sStudent.vStudentAcademic SA
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = SA.ClassId 
			 INNER JOIN sHrm.tEmployeeMaster EMT ON EMT.Id = DM.InchargeEmployeeId and ISNULL(EMT.IsOtherUser, 0) = 0 and EMT.StatusId = 7 and EMT.OrgID = @rOrgId
			 WHERE SA.BatchId = @rBatchId 
	END
	ELSE IF @rMeetingWithName = 'Principal' and @rMeetingWithId = 3
    BEGIN
        -- Select data for principal
     SELECT Emp.ID AS Id, Emp.FirstName + ' ' + Emp.LastName AS Name FROM sSecurity.tUser Users			
			INNER JOIN sHrm.vExtEmployeeMaster Emp			
			ON Emp.Id = Users.SourceId AND Users.SourceTypeId = 95	and Users.OrgId = @rOrgId						
			INNER JOIN sSecurity.tUserRole UR ON UR.UserId=Users.Id AND UR.IsObsolete=0 
			AND UR.IsPrimary=1  
			INNER JOIN sSecurity.tRole R ON R.Id=UR.RoleId  and R.OrgGroupId= @rOrgId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Users.OrgId
			INNER JOIN sSetup.tAffiliationMaster AT ON OM.AffiliationId = AT.Id
			LEFT JOIN sSecurity.tUserProfile Uprof ON Users.Id = Uprof.UserId
        WHERE 
		  Emp.Designation = 'Principal' 
		  and Emp.StatusId = 7
    END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec sCommonService.pMenuGet 9911000000270,19184029,0,1,98
-- exec sCommonService.pMenuGet 9911000000270,19184030,0,1,97
-- exec sCommonService.pMenuGet 9911000000270,19184031,0,1,99
CREATE OR ALTER PROCEDURE [sCommonService].[pMenuGet]
 @rUserId [bigint],    
 @rMenuId int = 0,    
 @rResourceTypeId int= 0,    
 @rIsCoreMenu bit = 0,
 @rModuleId int = 0   
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
 IF(@rIsCoreMenu=0)    
 BEGIN    
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
    PageURL  AS PagePath,    
    IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermissionUser P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
       WHERE    
        T.IsObsolete = 0 AND P.UserId = @rUserId    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 ELSE     
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
     PageURL  AS PagePath,    
     IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermission P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
        INNER JOIN    
        (    
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0    
        ) B ON B.RoleId = P.RoleId    
       WHERE    
        T.IsObsolete = 0    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0 AND TBL2.PermissionValue > 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 END    
 ELSE    
 BEGIN     
 SELECT    
   MenuID,    
   ModuleId,    
   ParentMenuID,    
   MenuTitle,      
   ScreenTitle,       
   PageURL,    
   ScreenId,    
   Permission,    
   OrderNumber,      
   TaskId,      
   PageURL  AS PagePath,    
   MenuIsObsolete,    
   Icon     
  FROM    
  (    

SELECT    
   ISNULL(Menu.Id,0) AS MenuID,     
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
   ISNULL(Menu.Title,'') AS MenuTitle,       
   ISNULL(Screen.Title, '') AS ScreenTitle,        
   ISNULL(Screen.Page, '') AS PageURL,    
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen.Id, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen.IconPath,'') AS Icon,
   ISNULL(Screen.OrderIndex,0) As OrderIndex     
  FROM     
  sSecurity.tMenu Menu     
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
  LEFT OUTER JOIN     
  (    
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId      
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id AND  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id        
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId     
  GROUP BY P.TaskId    
  ) TBL2 ON Screen.TaskId = TBL2.TaskId     
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
  WHERE 
  --(Menu.IsObsolete = 0)    
  --AND 
  ISNULL(Screen.IsObsolete, 0) = 0    
  AND (Menu.Id  IN (@rMenuId))   
  --OR ParentMenuID  in (24,2711))     
  --AND (
  ----Menu.Id IN (19184027)  
  ----OR ParentMenuID IN (55)
  --)  

  UNION
  

  SELECT     
  
   ISNULL(Menu.Id, 0) AS MenuID,     
   ISNULL(Menu.Id, 0) AS ParentMenuID,     
   ISNULL(Screen1.Title,'') AS MenuTitle,       
   ISNULL(Screen1.Title, '') AS ScreenTitle,        
   ISNULL(Screen1.Page, '')  AS PageURL,    
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen1.Id, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen1.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen1.IconPath,'') AS Icon,
   ISNULL(Screen1.OrderIndex,0) As OrderIndex    
  FROM     
   sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId     
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId    
   LEFT OUTER JOIN (     
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId        
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id       
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId    
            
  GROUP BY P.TaskId    
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId    
  WHERE 
  --(Menu.IsObsolete = 0) AND 
  ISNULL(Screen1.IsObsolete, 0) = 0    
  --AND (Menu.ParentMenuID  in (24,2711)   
  --OR Menu.Id  in (24,2711))   
  AND TBL2.PermissionValue > 0
  AND Screen1.Id Not In(31358,31376)
  --AND Screen1.Id IN (31336,31337,31338,31339,31340)
  ) MenuTable      
  WHERE     
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)
  --AND   
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
  --AND MenuIsObsolete = 0    
  AND MenuTable.MenuId IN (@rMenuId)   
  AND ModuleId IN (@rModuleId)
  ORDER BY MenuTable.OrderIndex, ParentMenuID
 END    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec sCommonService.pPermissionGet 9911,9911000000270
CREATE OR ALTER PROCEDURE [sCommonService].[pPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint],
	@rModuleId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)
BEGIN
	SELECT		TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
	FROM
	(
		SELECT 	
			P.TaskId					AS	TaskID,
			(Permission & 1) 		AS	C, --[Create],
			(Permission & 2)/2		AS	R, --[Read],
			(Permission & 4)/4		AS	U, --[Update],
			(Permission & 8)/8		AS	D, --[Delete],
			(Permission & 16)/16 	AS	S, --[Search],
			(Permission & 32)/32 	AS	P, --[Print],
			(Permission & 64)/64 	AS	X --[Execute]
		FROM sSecurity.tPermissionUser P
		INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
		INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
		INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
		WHERE
		P.OrgGroupId = @rOrgGroupId AND P.UserId = @rUserId  AND MP.ModuleId = @rModuleId
	) TP 
	GROUP BY TP.TaskId
END
ELSE
BEGIN
	SELECT		TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
	FROM
	(
		SELECT 	
			P.TaskId					AS	TaskID,
			(Permission & 1) 		AS	C, --[Create],
			(Permission & 2)/2		AS	R, --[Read],
			(Permission & 4)/4		AS	U, --[Update],
			(Permission & 8)/8		AS	D, --[Delete],
			(Permission & 16)/16 	AS	S, --[Search],
			(Permission & 32)/32 	AS	P, --[Print],
			(Permission & 64)/64 	AS	X --[Execute]
		FROM sSecurity.tPermission P
		INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
		INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
		INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
		INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
		ON R.RoleId = P.RoleId 
		WHERE
		P.OrgGroupId = @rOrgGroupId AND MP.ModuleId = @rModuleId
		--AND
	--RoleId 
	
	--IN
	-- (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId )
	) TP 
	GROUP BY TP.TaskId
	
	--SELECT	CAST(MAX(TP.C) AS BIT) AS [Create],
	--		CAST(MAX(TP.R) AS BIT) AS [Read],
	--		CAST(MAX(TP.U) AS BIT) AS [Update],
	--		CAST(MAX(TP.D) AS BIT) AS [Delete],
	--		CAST(MAX(TP.S) AS BIT) AS [Search],
	--		CAST(MAX(TP.P) AS BIT) AS [Print],
	--		CAST(MAX(TP.X) AS BIT) AS [Execute]
	--FROM
	--(
	--	SELECT 	(Permission & 1) AS C,
	--			(Permission & 2)/2 AS R,
	--			(Permission & 4)/4 AS U,
	--			(Permission & 8)/8 AS D,
	--			(Permission & 16)/16 AS S,
	--			(Permission & 32)/32 AS P,
	--			(Permission & 64)/64 AS X
	--	FROM sSecurity.tPermission
	--	WHERE TaskId = @rTaskId AND 
	--		  RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId)
	--) TP
END


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec sCommonService.pScreenGet 245
CREATE OR ALTER PROCEDURE [sCommonService].[pScreenGet]
	@rModuleId [int]
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
	BEGIN TRY
		SELECT
			S.Id			AS ScreenId,
			S.Title		AS ScreenTitle,
			S.TaskId		AS TaskId,
			S.Page		As PageUrl,
			S.IsObsolete	AS ScreenIsObsolete,
			S.Title,
			S.Page,
			SG.Id AS ScreenGroupId,
			ISNULL(SG.Title,'') AS ScreenGroupName

		FROM
			sSecurity.tScreen S (nolock)
		LEFT JOIN sSecurity.tScreenGroupMaster SG ON SG.Id=S.ScreenGroupId
		INNER JOIN sSecurity.tTask ST ON S.TaskId = ST.Id
		WHERE
			S.IsObsolete = 0 and ST.ModuleId = @rModuleId and S.Id NOT IN (30039,30047,30075,30076,30077,30078,30097)
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
end



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommonService].[pUpdateZoomMeetingAccountToken]
	@rAccessToken nvarchar(max),
	@rZoomMeetingAccountId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			UPDATE sAcademic.tOnlineMeetingAccount SET JWTToken = @rAccessToken Where Id = @rZoomMeetingAccountId AND MeetingProviderId = 1
			SELECT 1 as Result
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--exec [sCommonService].[pUserDetailsGet] 9911, '9911000000545, 9911000000003, 9911000000270'
CREATE OR ALTER PROCEDURE [sCommonService].[pUserDetailsGet]
	@rOrgId smallint,
	@rUserId nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		SET @rUserId = REPLACE(@rUserId, ',', ''',''');
		DECLARE @sql NVARCHAR(MAX),
		@OrgId NVARCHAR(10);
		SET @OrgId = CONVERT(NVARCHAR(50), @rOrgId);
		SET @sql = 'SELECT distinct
		UserTbl.Id AS Id, 		
		UserTbl.LoginTitle,
		UserTbl.DisplayTitle as Title,		 
		UserTbl.SourceId AS UserSourceId,
		UserTbl.SourceTypeId AS UserSourceTypeId
		--,
		--CASE WHEN UserTbl.SourceTypeId = 95 THEN
		--	(EM.FirstName +'' ''+ ISNULL(EM.MiddleName,'') + '' '' + EM.LastName)
		--ELSE
		--	SA.Name
		--END   AS EmployeeFullName,
		--CASE WHEN UserTbl.SourceTypeId = 95 THEN
		--	(EM.FirstName + ISNULL('' '' + EM.MiddleName, '') + '' '' + EM.LastName)
		--ELSE
		--	SA.Name
		--END   AS UserFullName
					
		FROM sSecurity.tUser UserTbl
			INNER JOIN sSecurity.tUserRole UR
				ON UR.UserId=UserTbl.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND UR.UserId=UserTbl.Id	
			LEFT JOIN sHrm.vExtEmployeeMaster EM
				ON EM.Id = UserTbl.SourceId 
				--AND UserTbl.OrgId = EM.OrgId 
				AND UserTbl.SourceTypeId = 95 
				--AND EM.StatusId !=9
			LEFT JOIN sStudent.vStudentAcademic SA
				ON SA.StudentId = UserTbl.SourceId 
				--AND UserTbl.OrgId = SA.OrgId 
				--AND SA.BatchId=@rBatchId 
				AND UserTbl.SourceTypeId = 2003	
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		WHERE 
			UserTbl.Id in ('''+ @rUserId +''')
			AND UserTbl.IsObsolete=0
			AND ((EM.StatusId = 7 AND UserTbl.SourceTypeId = 95) OR (SA.StatusId = 1 AND UserTbl.SourceTypeId = 2003) OR (UserTbl.SourceTypeId=1) OR (ISNULL(UserTbl.SourceTypeId,0) = 0))'

		EXEC sp_executesql @sql;
	END TRY

	BEGIN CATCH
	 SELECT -1 as Result
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommonService].[pZoomEmployeeSearchGet]
    @rOrgId [int],
    @rEmployeeCode [nvarchar](20) = '',
    @rFirstName [nvarchar](30) = '',
    @rMobileNumber [nvarchar](20) = '',
    @rDOB [datetime] = '1/1/1900',
    @rLastName [nvarchar](30) = '',
    @rParticipantSourceTypeId int = 0,
    @rDepartmentId int = 0,
    @rEmployeeId bigint = 0,
    @rStatusId smallint,
    @rMeetingMode int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    IF (@rMeetingMode = 1)
    BEGIN
        SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
        SET @rLastName = sCommon.fSearchStringGet(@rLastName)
        SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber)

        SELECT OrgID,
               EM.Id,
               EM.EmployeeId,
               Code,
               FirstName,
               MiddleName,
               LastName,
               EmployeeName,
               GenderId,
               ISNULL(DateOfBirth, '1900/01/01') AS DateOfBirth,
               ISNULL(DateOfJoining, '1900/01/01') AS DateOfJoining,
               '' AS Gender,
               StatusId,
               EM.IsObsolete,
               PhoneNoCompany,
               CompanyEmail,
               ExtensionNo,
               DepartmentId,
               DepartmentCode,
               DepartmentName,
               ISNULL(MobileNumber, 0) AS MobileNumber,
               ISNULL(DATEDIFF(yy, DateOfBirth, sCommon.fGetDate()), 0) AS Age,
               DesignationId,
               ParticipantSourceTypeId
        FROM sHrm.vExtEmployeeMaster EM
            INNER JOIN sAcademic.tOnlineMeetingAccount OA
                On OA.EmployeeId = EM.EmployeeId
        WHERE (
                  (EM.Code = @rEmployeeCode)
                  OR (ISNULL(@rEmployeeCode, '') = '')
              )
              AND (
                      (EM.FirstName Like @rFirstName)
                      OR (ISNULL(@rFirstName, '') = '')
                  )
              AND (
                      (EM.LastName Like @rLastName)
                      OR (ISNULL(@rLastName, '') = '')
                  )
              AND (
                      (EM.MobileNumber Like @rMobileNumber)
                      OR (ISNULL(@rMobileNumber, '') = '')
                  )
              AND EM.IsObsolete = 0
              AND (
                      (EM.OrgId = @rOrgId)
                      OR (@rOrgId = 0)
                  )
              AND (
                      (EM.DepartmentId = @rDepartmentId)
                      OR (@rDepartmentId = 0)
                  )
              AND (
                      (EM.StatusId = @rStatusId)
                      OR (@rStatusId = 0)
                  )
              AND ISNULL(EM.IsOtherUser, 0) = 0
    END
    ELSE IF (@rMeetingMode = 0 or @rMeetingMode = 2)
    BEGIN
        SELECT OrgID,
               EM.Id,
               EM.EmployeeId,
               Code,
               FirstName,
               MiddleName,
               LastName,
               EmployeeName,
               GenderId,
               ISNULL(DateOfBirth, '1900/01/01') AS DateOfBirth,
               ISNULL(DateOfJoining, '1900/01/01') AS DateOfJoining,
               '' AS Gender,
               StatusId,
               EM.IsObsolete,
               PhoneNoCompany,
               CompanyEmail,
               ExtensionNo,
               DepartmentId,
               DepartmentCode,
               DepartmentName,
               ISNULL(MobileNumber, 0) AS MobileNumber,
               ISNULL(DATEDIFF(yy, DateOfBirth, sCommon.fGetDate()), 0) AS Age,
               DesignationId,
               ParticipantSourceTypeId
        FROM sHrm.vExtEmployeeMaster EM
        WHERE (
                  (EM.Code = @rEmployeeCode)
                  OR (ISNULL(@rEmployeeCode, '') = '')
              )
              AND (
                      (EM.FirstName Like @rFirstName)
                      OR (ISNULL(@rFirstName, '') = '')
                  )
              AND (
                      (EM.LastName Like @rLastName)
                      OR (ISNULL(@rLastName, '') = '')
                  )
              AND (
                      (EM.MobileNumber Like @rMobileNumber)
                      OR (ISNULL(@rMobileNumber, '') = '')
                  )
              AND EM.IsObsolete = 0
              AND (
                      (EM.OrgId = @rOrgId)
                      OR (@rOrgId = 0)
                  )
              AND (
                      (EM.DepartmentId = @rDepartmentId)
                      OR (@rDepartmentId = 0)
                  )
              AND (
                      (EM.StatusId = @rStatusId)
                      OR (@rStatusId = 0)
                  )
              AND ISNULL(EM.IsOtherUser, 0) = 0
    END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommonService].[pZoomMeetingAccountDetailsGet]
	@rEmployeeId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT Id,EmployeeId, APIKey, APISecret,OAuthAccountId,OAuthClientId,OAuthClientSecret,AccountEmailId,JWTToken FROM sAcademic.tOnlineMeetingAccount WHERE EmployeeId = @rEmployeeId AND ISNULL(IsObsolete,0) = 0
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pAllGalleryCategory_Get]
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rBatchId int,
	 @rIsDivisionWise bit=true,
	 @rBatchYear int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
    DECLARE @lOrgGroupId smallint,@lOrgGroupBatchId int,@lOrgId smallint
    
	SELECT @lOrgGroupId=OM.OrgGRoupId,@lOrgGroupBatchId=OrgGroupBatchId,@lOrgId=OM.Id FROM sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	WHERE Bm.Id=@rBatchId
	
	SELECT  
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(PCM.CreatedDateTime,'')) AS CreatedDateTime,
			--CASE WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2003 THEN 'Student'
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 95 THEN 'Employee'
			--END  AS ScopeSourceType,
			AM.Title AS ScopeSourceType,
			U.DisplayTitle AS UserName,
			ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
		FROM    
			[sCommunication].[tMultiPhotoCategoryMaster]  PCM 
			INNER JOIN sCommon.tAssigneeMaster AM ON PCM.ScopeSourceTypeId = AM.Id
			--INNER JOIN [sCommunication].[tMultiPhotoCategoryScope] MPCS ON MPCS.MultiPhotoCategoryId = PCM.Id
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			--AND PCM.IsObsolete =0
			AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
			AND (PCM.OrgGroupBatchId = @lOrgGroupBatchId OR ISNULL(PCM.OrgGroupBatchId,0)=0)
		ORDER BY 
			PCM.CreatedDateTime DESC
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  

CREATE OR ALTER PROCEDURE [sCommunication].[pAllPhotoCategory_Get]
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rBatchId int,
	 @rIsDivisionWise bit=true,
	 @rBatchYear int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
    DECLARE @lOrgGroupId smallint,@lOrgGroupBatchId int,@lOrgId smallint
    
	SELECT @lOrgGroupId=OM.OrgGRoupId,@lOrgGroupBatchId=OrgGroupBatchId,@lOrgId=OM.Id FROM sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	WHERE Bm.Id=@rBatchId
	
    IF(@rIsDivisionWise=0)
    BEGIN
		SELECT   
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(PCM.CreatedDateTime,'')) AS CreatedDateTime,
			CASE WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			END +' - '+ [sCommunication].[fPhotoCategoryScopeGet](PCM.Id,PCM.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName,
			ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
		FROM    
			[sCommunication].[tPhotoCategoryMaster]  PCM 
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND PCM.IsObsolete =0
			AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
			AND (PCM.OrgGroupBatchId = @lOrgGroupBatchId OR ISNULL(PCM.OrgGroupBatchId,0)=0)
		ORDER BY 
			PCM.CreatedDateTime DESC
	END		
	ELSE
	
	 BEGIN
		SELECT   
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(PCM.CreatedDateTime,'')) AS CreatedDateTime,
			CASE WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			END +' - '+ [sCommunication].[fPhotoCategoryScopeGet](PCM.Id,PCM.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName,
			ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
		FROM    
			[sCommunication].[tPhotoCategoryMaster]  PCM 
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND ScopeSourceTypeId=2005
			AND PCM.IsObsolete =0
			AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
			AND (PCM.OrgGroupBatchId = @lOrgGroupBatchId OR ISNULL(PCM.OrgGroupBatchId,0)=0)
		ORDER BY 
			PCM.CreatedDateTime DESC
	END		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignedQueryCategoryListGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId smallint,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			QCA.QueryCategoryId,
			QCM.Title AS QueryCategoryTitle
	FROM 
			sCommunication.tQueryCategoryAssignedTo QCA
			INNER JOIN sCommunication.tQueryCategoryMaster QCM 
				ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
	WHERE 
			(QCA.SourceTypeId = @rSourceTypeId) 
			AND (QCA.SourceId = @rSourceId) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignedQueryListGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgGroupBatchId int,
	 @rSourceId bigint,
	 @rSourceTypeId smallint,
	 @rStatusId int,
	 @rFromDate datetime = NULL,
	 @rToDate datetime = NULL
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			 Q.Id AS QueryId,
			 Q.Title AS QueryTitle,
			 Q.Remark AS QueryRemark,
			 SM.Id AS QueryStatusId,
			 SM.Title AS QueryStatus,
			 QCM.Title AS QueryCategoryTitle,
			 QCA.QueryCategoryId,
			 (CONVERT(VARCHAR(25),Q.CreatedDateTime, 100)) AS QueryCreatedDateTime,
			 (CASE WHEN U.SourceTypeId = 95 THEN 	'Employee'
			 WHEN U.SourceTypeId = 2003 THEN	'Student' END ) AS SourceType,
			 (CASE WHEN U.SourceTypeId = 95 THEN (SELECT EmployeeName FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentAcademic SA WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1)  END ) AS SourceName, --Added SA.IsActiveBatch = 1 for mantis : 41517
			  (CASE WHEN U.SourceTypeId = 95 THEN (SELECT DepartmentName FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT ClassName +' - ' + DivisionName FROM sStudent.vStudentAcademic SA WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1)  END ) AS ClasDivOrDept, --Added SA.IsActiveBatch = 1 for mantis : 41517
			 (CASE WHEN U.SourceTypeId = 95 THEN (SELECT OM.Title FROM sHrm.vEmployeeCommonDetail vECD INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vECD.OrgID WHERE vECD.EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT OrganizationName FROM sStudent.vStudentAcademic SA WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1)  END ) AS OrgTitle, --Added SA.IsActiveBatch = 1 for mantis : 41517
			 ISNULL(Q.Number,0) AS QueryNumber
	FROM 
				sCommunication.tQueryCategoryAssignedTo QCA
			INNER JOIN sCommunication.tQuery Q ON Q.QueryCategoryId = QCA.QueryCategoryId AND ((Q.StatusId=@rStatusId) OR (@rStatusId = 0)) -- ADD @rStatusId = 0 because in App Side only Opened status Query redirect - mantisid - 0029535 
			INNER JOIN sSecurity.tUser U ON U.Id = Q.CreatedUserId
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = Q.StatusId
	WHERE 
			(QCA.SourceTypeId = @rSourceTypeId) 
			AND (QCA.SourceId = @rSourceId) 
			AND ((Q.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((Q.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (Q.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
	ORDER BY Q.CreatedDateTime Asc	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignLocalVideoPlaylistGet]
	@rAssignId int = 0,
	@rOrgGroupId int = 0,
	@rSourceTypeId smallint = 0,
	@rSourceId bigint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
		SELECT * FROM (SELECT	 VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,'' AS ClassDepartment, 'Organization' AS SourceType,OM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId WHERE VP.SourceTypeId=2021

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,DM.Title AS ClassDepartment, 'Department' AS SourceType,DM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
WHERE VP.SourceTypeId=2017

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,DM.Title AS ClassDepartment, 'Class' AS SourceType,CM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sSetup.tClassMaster CM ON VP.SourceId=CM.Id
INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
WHERE VP.SourceTypeId=2016

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,DMast.Title AS ClassDepartment, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sSetup.tDivisionMaster DM ON VP.SourceId=DM.Id
INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId		
WHERE VP.SourceTypeId=2005

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,SA.ClassName+' - '+SA.DivisionName AS ClassDepartment, 'Student' AS SourceType,
[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sStudent.tStudentMaster SM ON VP.SourceId=SM.Id
INNER JOIN  sStudent.vStudentAcademic SA ON VP.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId		
WHERE VP.SourceTypeId=2003

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,'Student' AS SourceType,SA.Name AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sStudent.vStudentAcademic SA	ON VP.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId			
WHERE VP.SourceTypeId=2001 

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,vEC.DepartmentName AS ClassDepartment,'Employee' AS SourceType,vEC.FirstName +' '+ vEC.LastName AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sHrm.vEmployeeCommunication vEC ON VP.SourceId=vEC.EmployeeId AND vEC.StatusId=7
INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId					
WHERE VP.SourceTypeId=95
) tmp
where (tmp.AssignedToId=@rAssignId OR (@rAssignId=0))
AND tmp.OrgGroupId = @rOrgGroupId
AND (tmp.SourceTypeId =@rSourceTypeId OR (@rSourceTypeId=0))
AND (tmp.SourceId = @rSourceId OR (@rSourceId=0))
AND (tmp.PlaylistName IN(Select Convert (varchar,Id) FROM [sCommunication].[tPlaylistMaster]))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentAdd]
	 
        @rId bigint,
        @rSubjectId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(max),
		@rStartDate date,
		@rEndDate date,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int,
		@rIsAssignmentDocumentUpload bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tAssignment where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tAssignment where Title=@rTitle AND BatchId=@rBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tAssignment where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tAssignment where Title=@rTitle AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tAssignment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tAssignment
		(
			Id,
			SubjectId,
			Title,
			Remark,
			StartDate,
			EndDate,
			CreatedUserId,
			CreatedDateTime,
			BatchId,
			IsAssignmentDocumentUpload
		)
	VALUES
		(
			@lNextNumber,
			@rSubjectId,
			@rTitle,
			@rRemark,
			@rStartDate,
			@rEndDate,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rBatchId,
			@rIsAssignmentDocumentUpload
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tAssignment
	    SET
			SubjectId=@rSubjectId,
			Title=@rTitle,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			Remark=@rRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			IsAssignmentDocumentUpload = @rIsAssignmentDocumentUpload
	      
	      WHERE Id = @rId
	      
	      --DELETE FROM sCommunication.tAssignmentView WHERE AssignmentId=@rId
	      
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sCommunication.tAssignmentView where AssignmentId=@rId
			Delete from sCommunication.tAssignmentScope where AssignmentId=@rId
			Delete from sCommunication.tAssignment where Id=@rId
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentGet]
	 @rId bigint = 0,
	 @rSubjectId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rCreatedUserId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			ISNULL(IsAssignmentDocumentUpload,0) AS IsAssignmentDocumentUpload
			--ISNULL(AV.Remark,'') AS ViewRemark
		    
  FROM 
   --         sCommunication.tAssignment A
			--INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
   --         INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
   --         INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			--INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id	
			--LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CS.ClassId = Dm.classId 
			--LEFT JOIN sCommunication.tAssignmentView AV ON A.Id = AV.AssignmentId
			 sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId AND CAS.SourceTypeId = 2005
			--LEFT JOIN sCommunication.tAssignmentView AV ON A.Id = AV.AssignmentId  -- Comment for duplicate data in mobile side for MantisId: 0027677
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND A.BatchId=@rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentGetOld]
	 @rId bigint = 0,
	 @rSubjectId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rCreatedUserId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			ISNULL(IsAssignmentDocumentUpload,0) AS IsAssignmentDocumentUpload,
			ISNULL(AV.Remark,'') AS ViewRemark
		    
  FROM 
            sCommunication.tAssignment A
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			LEFT JOIN sCommunication.tAssignmentView AV ON A.Id = AV.AssignmentId
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND A.BatchId=@rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentGetWithScope]
	 @rId bigint = 0,
	 @rSubjectId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rCreatedUserId bigint=0,
	 @rClassId int = 0,
	 @rDivisionId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	DECLARE @lIsOptional int 
	SET @lIsOptional = (Select TOP 1 1 from sSetup.tSubjectMaster AS SM INNER JOIN [sSetup].[tClassSubject] As CS ON CS.SubjectId = SM.Id INNER JOIN sSetup.tDivisionMaster AS DM ON DM.ClassId = CS.ClassId WHERE CS.IsOptional = 1 AND SubjectId = @rSubjectId AND DM.Id = @rDivisionId Order by CS.ClassId)

	SELECT 
		DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			CASE WHEN @lIsOptional = 1
			THEN
			STUFF((			  
			SELECT ',' + SM.Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sStudent.tStudentMaster SM ON CAS.SourceId = SM.Id Where CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2003		  
			FOR XML PATH ('')), 1, 1, '') --Added for mantis : 42198
			ELSE
			STUFF((
			SELECT ',' + DM.Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDivisionMaster DM ON CAS.SourceId = DM.Id Where  CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2005 
			FOR XML PATH ('')), 1, 1, '') END as StudentSource ,			 
			STUFF((			  
			SELECT ',' + Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDepartmentMaster CM ON CAS.SourceId = CM.Id Where CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2017			  
			FOR XML PATH ('')), 1, 1, '') as EmployeeSource,			
			A.CreatedDateTime
		    
  FROM 
   --         sCommunication.tAssignment A
			--INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
   --         INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
   --         INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			--INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id												
			--LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CS.ClassId = Dm.classId 

			 sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId AND CAS.SourceTypeId = 2005
			LEFT JOIN sStudent.vStudentAcademic AS SA ON SA.StudentId = CAS.SourceId AND CAS.SourceTypeId = 2003 AND SA.IsActiveBatch = 1
  WHERE  
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((DM.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((DM.Id = @rDivisionId) OR (@rDivisionId = 0))
	AND A.BatchId=@rBatchId
	ORDER BY A.StartDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentGetWithScopeOld]
	 @rId bigint = 0,
	 @rSubjectId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rCreatedUserId bigint=0,
	 @rClassId int = 0,
	 @rDivisionId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
		DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			STUFF((
			SELECT ',' + DM.Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDivisionMaster DM ON CAS.SourceId = DM.Id Where  CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2005 
			FOR XML PATH ('')), 1, 1, '') as StudentSource ,			 
			STUFF((			  
			SELECT ',' + Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDepartmentMaster CM ON CAS.SourceId = CM.Id Where CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2017			  
			FOR XML PATH ('')), 1, 1, '') as EmployeeSource
		    
  FROM 
            sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id												
			LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CS.ClassId = Dm.classId 
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((CS.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((DM.Id = @rDivisionId) OR (@rDivisionId = 0))
	AND A.BatchId=@rBatchId
	ORDER BY A.StartDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
			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.ClassSubjectId
		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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentListGet_OGOLD] 
	@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
		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 A.DivisionId
			FROM sStudent.tAcademic A
			WHERE A.StudentId = @rUserSourceId
				AND A.BatchId = @rBatchId
			) D ON D.DivisionId = AS1.SourceId
			AND AS1.SourceTypeId = 2005
		INNER JOIN sSecurity.tUser U ON U.Id = A1.CreatedUserId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AS1.SourceId --Added for mantis : 42198
		INNER JOIN [sSetup].[tClassSubject] CS ON CS.SubjectId = A1.SubjectId AND DM.ClassId = CS.ClassId --Added for mantis : 42198
		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 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 A.DivisionId
			FROM sStudent.tAcademic A
			WHERE A.StudentId = @rUserSourceId
				AND A.BatchId = @rBatchId
			) D ON D.DivisionId = AS1.SourceId
			AND AS1.SourceTypeId = 2005
		INNER JOIN sSecurity.tUser U ON U.Id = A1.CreatedUserId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AS1.SourceId 
		INNER JOIN [sSetup].[tClassSubject] CS ON CS.SubjectId = A1.SubjectId AND DM.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
		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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentNotificationListGet] 
@rSourceId bigint,
@rSubjectId int,
@rBatchId int,
@rSourceTypeId int,
@rIsObsolete bit,
@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

Select DISTINCT SA.StudentId AS SourceId from [sSetup].[tClassSubject] AS CS 
INNER JOIN sSetup.tDivisionMaster AS DM ON DM.ClassId = CS.ClassId
INNER JOIN sStudent.vStudentAcademic AS SA ON SA.ClassId = CS.ClassId AND SA.DivisionId = DM.Id
INNER JOIN [sAssessment].[tOptionalSubject] As OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = CS.Id
where CS.IsOptional = 1 AND CS.SubjectId = @rSubjectId 
AND DM.Id = @rSourceId AND SA.IsActiveBatch = 1 AND SA.OrgId = @rOrgId AND SA.BatchId = @rBatchId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentQueueGet]
	 @rId bigint = 0,
	 @rSubjectId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rCreatedUserId bigint=0,
	 @rStatusId int=0,
	 @rUserId bigint = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
		
DECLARE @rSourceId bigint
DECLARE @rSourceTypeId int
DECLARE @rAssignmentCount int

set @rSourceId = ( SELECT SourceId FROM sSecurity.tUser where Id=@rCreatedUserId)
set @rSourceTypeId = ( SELECT SourceTypeId FROM sSecurity.tUser where Id=@rCreatedUserId)

IF(@rSourceTypeId = 95)

BEGIN 
	IF @rIsSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END

	SET @rAssignmentCount=	(select ISNULL(COUNT(1),0) FROM sCommunication.tAssignment WHERE CreatedUserId=@rCreatedUserId)

	IF(@rAssignmentCount=0)
	BEGIN
		SET @rCreatedUserId=0
	END
	ELSE
	BEGIN
		SET @rCreatedUserId = @rCreatedUserId
	END
	
	SELECT DISTINCT
		A.Id as AssignmentId,
		A.SubjectId,
		SM.Title as SubjectName,
		A.Title,
		A.Remark,
		A.StartDate,
		A.EndDate,
		U.DisplayTitle as CreatedUserName,
		ISNULL(A.StatusId,549) as StatusId,
		CASE WHEN ISNULL(A.StatusId,549)=549 THEN 'Pending' WHEN A.StatusId=550 THEN 'Approve' ELSE 'Reject' END AS Status		    
	FROM 
		sCommunication.tAssignment A
        LEFT JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
		INNER JOIN sCommunication.tAssignmentScope ASS ON ASS.AssignmentId=A.ID
		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = SM.Id 
		--AND vTSD.ClassId=ASS.SourceId --comment for mantis Id :0030424
		AND vTSD.DivisionId=ASS.SourceId
			
	WHERE ((A.Id = @rId) OR (@rId = 0))
		AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((A.EndDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0)) --comment for mantis Id :0030424
		AND ((A.CreatedUserId != @rCreatedUserId) OR (@rCreatedUserId = 0))
		AND A.BatchId=@rBatchId
		AND ((ISNULL(A.StatusId,549) = @rStatusId) OR (@rStatusId = 0))	 
		AND((ISNULL(vTSD.SubjectCordinatorEmployeeId,0) = @rUserId)OR(@rUserId=0))
	 
	 --Add union for mantis Id :0030424

	UNION 

	SELECT DISTINCT
		A.Id as AssignmentId,
		A.SubjectId,
		SM.Title as SubjectName,
		A.Title,
		A.Remark,
		A.StartDate,
		A.EndDate,
		U.DisplayTitle as CreatedUserName,
		ISNULL(A.StatusId,549) as StatusId,
		CASE WHEN ISNULL(A.StatusId,549)=549 THEN 'Pending' WHEN A.StatusId=550 THEN 'Approve' ELSE 'Reject' END AS Status
	FROM 
		sCommunication.tAssignment A
		LEFT JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
		INNER JOIN sCommunication.tAssignmentScope ASS ON ASS.AssignmentId=A.ID AND ASS.SourceTypeId = 2017
			
	WHERE ((A.Id = @rId) OR (@rId = 0))
		AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((A.EndDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((A.CreatedUserId != @rCreatedUserId) OR (@rCreatedUserId = 0))
		AND A.BatchId=@rBatchId
		AND ((ISNULL(A.StatusId,549) = @rStatusId) OR (@rStatusId = 0))	 

END

ELSE
BEGIN
 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			ISNULL(A.StatusId,549) as StatusId,
			CASE WHEN ISNULL(A.StatusId,549)=549 THEN 'Pending' WHEN A.StatusId=550 THEN 'Approve' ELSE 'Reject' END AS Status
		    
  FROM 
            sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId and CAS.SourceTypeId = 2005 
            LEFT JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = SM.Id
			INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id
			INNER JOIN [sSetup].[tClassMaster] CM on Cs.ClassId = CM.Id									
			INNER JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CM.Id = Dm.classId 
			
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.EndDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND A.BatchId=@rBatchId
	AND ((ISNULL(A.StatusId,549) = @rStatusId) OR (@rStatusId = 0))	
	AND ((CM.Id = @rClassId) OR (@rClassId = 0))
	AND ((DM.Id = @rDivisionId) OR (@rDivisionId = 0)) 
	--AND((ISNULL(vTSD.SubjectCordinatorEmployeeId,0) = @rSubjectCordinatorId)OR(@rSubjectCordinatorId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentQueueUpdate]
	 
	 	
        @rId bigint,        
		@rStatusId int,
		@rLoginUserId bigint
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	 BEGIN TRY
		
	    UPDATE  sCommunication.tAssignment
	    SET
			StatusId=@rStatusId,ApprovedByEmployeeId=@rLoginUserId WHERE Id = @rId

	      SELECT 11 AS Result

	END TRY	
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
		END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentScopeAdd]
			@rAssignmentId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tAssignmentScope where AssignmentId=@rAssignmentId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 

		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select AssignmentId from sCommunication.tAssignmentScope where AssignmentId=@rAssignmentId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			--RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tAssignmentScope
			(
				AssignmentId
			   ,SourceTypeId
			   ,SourceId
			)
			VALUES
			(	
				@rAssignmentId
			   ,@rSourceTypeId
			   ,@rSourceId
			)		
			SELECT @rAssignmentId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentScopeGet]
	 @rAssignmentId bigint,
	 @rOrgId smallint,
	 @rUserId bigint=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lOrgGroupId int = 0
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	
	DECLARE @lAssignmentEntryBasedOn nvarchar(100)
	SELECT @lAssignmentEntryBasedOn = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 256 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
	
	IF (@lAssignmentEntryBasedOn IS NULL)
	BEGIN
		
		SELECT 
			DISTINCT DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as ClassDept,
			2005 as SourceTypeId,
			CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
			CM.OrderIndex+DM.OrderIndex AS OrderIndex
		FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
			LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=DM.Id AND CS.SourceTypeId=2005 AND CS.AssignmentId=@rAssignmentId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
		WHERE DM.OrgId=@rOrgId
		AND (U.UserId = @rUserId OR @rUserId =0)
		
		UNION ALL
		
		SELECT 
			DISTINCT ODM.Id  as SourceId,
			ODM.Title as ClassDept,
			2017 as SourceTypeId,
			CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
			0 AS OrderIndex
		FROM 
			sSetup.tDepartmentMaster ODM  
			LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=ODM.Id AND CS.SourceTypeId=2017 AND CS.AssignmentId=@rAssignmentId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = ODM.Id AND U.SourceTypeId=2017
		WHERE ODM.OrgId=@rOrgId
		AND (U.UserId = @rUserId OR @rUserId =0)
	END
	ELSE 
	BEGIN
		IF(@lAssignmentEntryBasedOn='Common')
		BEGIN
			
			SELECT 
				DISTINCT DM.Id  as SourceId,
				CM.Title+'-'+DM.Title as ClassDept,
				2005 as SourceTypeId,
				CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
				CM.OrderIndex+DM.OrderIndex AS OrderIndex
			FROM 
				sSetup.tDivisionMaster DM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
				LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=DM.Id AND CS.SourceTypeId=2005 AND CS.AssignmentId=@rAssignmentId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND (U.SourceTypeId=2005)
			WHERE DM.OrgId=@rOrgId
			AND (U.UserId = @rUserId OR @rUserId =0)
			
			UNION ALL
			
			SELECT 
				DISTINCT ODM.Id  as SourceId,
				ODM.Title as ClassDept,
				2017 as SourceTypeId,
				CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
				0 AS OrderIndex
			FROM 
				sSetup.tDepartmentMaster ODM  
				LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=ODM.Id AND CS.SourceTypeId=2017 AND CS.AssignmentId=@rAssignmentId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = ODM.Id AND U.SourceTypeId=2017
			WHERE ODM.OrgId=@rOrgId
			AND (U.UserId = @rUserId OR @rUserId =0)
		END
		ELSE
		BEGIN
			DECLARE @lEmployeeId bigint  = 0
			SELECT @lEmployeeId=SourceId FROM sSecurity.tUser WHERE Id=@rUserId
			
			SELECT 
				DISTINCT DM.Id  as SourceId,
				CM.Title+'-'+DM.Title as ClassDept,
				2005 as SourceTypeId,
				CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
				CM.OrderIndex+DM.OrderIndex AS OrderIndex
			FROM 
				sSetup.tDivisionMaster DM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
				LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=DM.Id AND CS.SourceTypeId=2005 AND CS.AssignmentId=@rAssignmentId
				INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id 
			WHERE DM.OrgId=@rOrgId  AND (TSD.EmployeeId = @lEmployeeId or ISNULL(@lEmployeeId,0)=0)
			
			UNION ALL
			
			SELECT 
				DISTINCT ODM.Id  as SourceId,
				ODM.Title as ClassDept,
				2017 as SourceTypeId,
				CASE WHEN CS.SourceId IS NULL OR CS.AssignmentId!=@rAssignmentId THEN 0 ELSE 1 END AS IsObsolete,
				0 AS OrderIndex
			FROM 
				sSetup.tDepartmentMaster ODM  
				LEFT JOIN sCommunication.tAssignmentScope CS ON CS.SourceId=ODM.Id AND CS.SourceTypeId=2017 AND CS.AssignmentId=@rAssignmentId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = ODM.Id AND U.SourceTypeId=2017
			WHERE ODM.OrgId=@rOrgId
			AND (U.UserId = @rUserId OR @rUserId =0)
		END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentViewAdd]
			@rAssignmentId bigint
           ,@rUserId bigint
		   ,@rSourceTypeId int = 0
		   ,@rSourceId bigint = 0
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY

		BEGIN TRANSACTION	   
		If Exists(select AssignmentId from sCommunication.tAssignmentView where AssignmentId=@rAssignmentId AND UserId=@rUserId AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId)
			BEGIN
				SELECT @rAssignmentId AS Result
			END 
		ELSE
			BEGIN
				INSERT INTO sCommunication.tAssignmentView
				(
					AssignmentId
				   ,UserId
				   ,SourceTypeId
				   ,SourceId
				   ,ViewByDateTime
				)
				VALUES
				(	
					@rAssignmentId
				   ,@rUserId
				   ,@rSourceTypeId
				   ,@rSourceId
				   ,sCommon.fGetDate()
				)		
				SELECT @rAssignmentId AS Result
			END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignmentViewGet]
	 
	@rAssignmentId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	 BEGIN TRANSACTION	
		 BEGIN
		 SELECT 
			 CASE WHEN AV.SourceTypeId = 2003 THEN  SM.Code WHEN AV.SourceTypeId = 95 THEN EM.Code END as Code,
			 CASE WHEN AV.SourceTypeId = 2003 THEN  SM.FirstName +' '+ SM.LastName WHEN AV.SourceTypeId = 95 THEN EM.FirstName +' '+ EM.LastName END as Name,
			 AV.ViewByDateTime
		 FROM
			 sCommunication.tAssignmentView as AV
			 LEFT JOIN sStudent.tStudentMaster SM on SM.Id = AV.SourceId AND AV.SourceTypeId = 2003
			 LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = AV.SourceId AND AV.SourceTypeId = 95
		 WHERE
		 AssignmentId = @rAssignmentId AND AV.SourceId != ''
		SELECT 1 AS RESULT
        END  
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignTaskAdd]
	 
	@rId bigint,
	@rAssignedDate date,
	@rDueDate date,
	@rAssignedToSourceTypeId smallint,
	@rAssignedToSourceId bigint,
	@rRemark nvarchar(300),
	@rIsCompleted bit,
	@rIsClosed bit,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rDueReasonRemark nvarchar(500)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
  
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tAssignTask', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommunication.tAssignTask
		(
			Id,
			AssignedDate,
			DueDate,
			AssignedToSourceTypeId,
			AssignedToSourceId,
			Remark,
			IsCompleted,
			IsClosed,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			IsDeleted,
			DueReasonRemark
		)
	VALUES
		(
			@lNextNumber,
			@rAssignedDate,
			@rDueDate,
			@rAssignedToSourceTypeId,
			@rAssignedToSourceId,
			@rRemark,
			@rIsCompleted,
			@rIsClosed,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			0,
			@rDueReasonRemark
		)
		             
	END	 
	 ELSE
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tAssignTask
	    SET
			AssignedDate=@rAssignedDate,
			DueDate=@rDueDate,
			AssignedToSourceTypeId=@rAssignedToSourceTypeId,
			AssignedToSourceId=@rAssignedToSourceId,
			Remark=@rRemark,
			IsCompleted=@rIsCompleted,
			IsClosed=@rIsClosed,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			DueReasonRemark=@rDueReasonRemark
	      WHERE Id = @rId 	   
	 	 
		  SELECT @lNextNumber AS Result	   
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignTaskByMeGet]
	 
	 @rOrgId int,
	 @rUserId bigint,
	 @rSyncedDateTime datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		AT.Id,
		AT.AssignedDate,
		AT.DueDate,
		AT.Remark,
		AT.IsCompleted,
		AT.IsClosed,
		AT.IsDeleted,
		   AT.AssignedToSourceId AS AssignedToSourceId,
		AT.AssignedToSourceTypeId AS AssignedToSourceTypeId,
		(CASE 
		WHEN AT.AssignedToSourceTypeId=95 
		THEN (SELECT FirstName +' '+LastName FROM sHrm.tEmployeeMaster WHERE Id=AT.AssignedToSourceId AND  ISNULL(IsOtherUser,0) = 0 )
		WHEN AT.AssignedToSourceTypeId=2003
		THEN (SELECT FirstName +' '+LastName FROM sStudent.tStudentMaster WHERE Id=AT.AssignedToSourceId)
		END)AS AssignedToName,
		(CASE 
		WHEN AT.AssignedToSourceTypeId=95 
		THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id=AT.AssignedToSourceId AND ISNULL(IsOtherUser,0) = 0 )
		WHEN AT.AssignedToSourceTypeId=2003
		THEN (SELECT Code FROM sStudent.tStudentMaster WHERE Id=AT.AssignedToSourceId)
		END)AS AssignedToCode,
		AT.OrgId AS OrgId,
		AT.DueReasonRemark						
	FROM 
		sCommunication.tAssignTask AT
	WHERE 
		AT.CreatedUserId=@rUserId
		AND (AT.OrgId=@rOrgId OR @rOrgId=0)
		AND (AT.UpdatedDateTime > @rSyncedDateTime OR @rSyncedDateTime IS NULL)			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignTaskComplete]
	 
	@rId bigint,
	@rIsCompleted bit,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 
	    UPDATE sCommunication.tAssignTask
	    SET
			IsCompleted=@rIsCompleted,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId 	   
	 	 
		  SELECT 1 AS Result	   
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignTaskDelete]
	 
	@rId bigint,
	@rCreatedUserId bigint,
	@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 
	    UPDATE sCommunication.tAssignTask
	    SET
			IsDeleted=1,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId AND OrgId=@rOrgId	   
	 	 
		  SELECT 1 AS Result	   
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignTaskGet]
	 
	 @rId bigint,
	 @rOrgId int,
	 @rCreatedUserId bigint,
	 @rIsAssignTaskToMe bit,
	 @rStatus tinyint,
	 @rIsSearch bit,
	 @rSyncedAssignTaskId bigint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON	
BEGIN 
DECLARE @lSourceId bigint = 0
DECLARE @lSourceTypeId smallint = 0

SELECT @lSourceId = SourceId, @lSourceTypeId = SourceTypeId FROM sSecurity.tUser WHERE Id = @rCreatedUserId
IF(@rIsAssignTaskToMe = 1)
BEGIN
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			CASE WHEN @rIsSearch = 1 THEN EM1.Code ELSE EM.Code END AS SourceCode,
			CASE WHEN @rIsSearch = 1 THEN ISNULL(EM1.FirstName, '') + ' ' + ISNULL(EM1.LastName, '') ELSE ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') END AS SourceName,
			CONVERT(varchar,AT.AssignedDate ,105) AS AssignedDate,
			CONVERT(varchar,AT.DueDate ,105) AS DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed,
			AT.DueReasonRemark
	FROM 
			sCommunication.tAssignTask AT
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
			INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
			LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id=U.SourceId			
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.AssignedToSourceId=@lSourceId)
		AND (AT.AssignedToSourceTypeId = @lSourceTypeId)
		AND (AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END) OR @rStatus = 2)
		AND (AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END) OR @rStatus = 1)
		AND AT.OrgId=@rOrgId
		AND ( AT.Id > @rSyncedAssignTaskId OR @rSyncedAssignTaskId = 0)
		AND AT.IsDeleted=0
			
	UNION ALL
	
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			CASE WHEN @rIsSearch = 0 THEN SN.Code WHEN SN1.Id IS NOT NULL THEN SN1.Code ELSE EM1.Code END AS SourceCode,
			CASE WHEN @rIsSearch = 0 THEN SN.Name WHEN SN1.Id IS NOT NULL THEN SN1.FirstName + ' ' + SN1.LastName ELSE ISNULL(EM1.FirstName, '') + ' ' + ISNULL(EM1.LastName, '') END AS SourceName,
			CONVERT(varchar,AT.AssignedDate,105) AS AssignedDate,
			CONVERT(varchar,AT.DueDate,105) AS DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed,
			AT.DueReasonRemark
	FROM 
			sCommunication.tAssignTask AT
			INNER JOIN sStudent.vStudentName SN ON SN.StudentId=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
			INNER JOIN sSetup.tBatchMaster BM ON SN.BatchId = BM.Id 
			AND BM.IsActive = 1
			INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
			LEFT JOIN sStudent.tStudentMaster SN1 ON SN1.Id=U.SourceId AND U.SourceTypeId=2003
			LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id=U.SourceId AND U.SourceTypeId=95
		
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.AssignedToSourceId=@lSourceId)
		AND (AT.AssignedToSourceTypeId = @lSourceTypeId)
		AND (AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END) OR @rStatus = 2)
		AND (AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END) OR @rStatus = 1)
		AND AT.OrgId=@rOrgId
		AND ( AT.Id > @rSyncedAssignTaskId OR @rSyncedAssignTaskId = 0)
		AND AT.IsDeleted=0
END
ELSE
BEGIN
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			EM1.Code AS SourceCode,
			ISNULL(EM1.FirstName, '') + ' ' + ISNULL(EM1.LastName, '') AS SourceName,
			CONVERT(varchar,AT.AssignedDate,105) AS AssignedDate,
			CONVERT(varchar,AT.DueDate,105) AS DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed,
			AT.DueReasonRemark
	FROM 
			sCommunication.tAssignTask AT
			INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
			INNER JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.CreatedUserId=@rCreatedUserId OR @rCreatedUserId=0)
		AND (AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END) OR @rStatus = 2)
		AND (AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END) OR @rStatus = 1)
		AND AT.OrgId=@rOrgId
		AND ( AT.Id > @rSyncedAssignTaskId OR @rSyncedAssignTaskId = 0)
		AND AT.IsDeleted=0
			
	UNION ALL
	
	SELECT 
			AT.Id,
			AT.AssignedToSourceTypeId,
			AT.AssignedToSourceId,
			SN1.Code AS SourceCode,
			SN1.FirstName + ' ' + SN1.LastName AS SourceName,
			CONVERT(varchar,AT.AssignedDate,105) AS AssignedDate,
			CONVERT(varchar,AT.DueDate,105) AS DueDate,
			AT.Remark,
			AT.IsCompleted,
			AT.IsClosed,
			AT.DueReasonRemark
	FROM 
			sCommunication.tAssignTask AT
			INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
			INNER JOIN sStudent.tStudentMaster SN1 ON SN1.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
		--INNER JOIN sStudent.vStudentName SN1 ON SN1.StudentId=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
	WHERE 
			((AT.Id=@rId) OR (@rId=0))
		AND (AT.CreatedUserId=@rCreatedUserId OR @rCreatedUserId=0)
		AND (AT.IsCompleted=(CASE 
			WHEN @rStatus=0 THEN 0
			WHEN @rStatus=1 THEN 1
			WHEN @rStatus=2 THEN 0
		END) OR @rStatus = 2)
		AND (AT.IsClosed=(CASE 
			WHEN @rStatus=2 THEN 1
			WHEN @rStatus=1 THEN 0
			WHEN @rStatus=0 THEN 0
		END) OR @rStatus = 1)
		AND AT.OrgId=@rOrgId
		AND ( AT.Id > @rSyncedAssignTaskId OR @rSyncedAssignTaskId = 0)
		AND AT.IsDeleted=0
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignTaskSearchGet]

	 @rId bigint,
	 @rOrgId int,
	 @rFromStartDate DateTime,
	 @rToStartDate DateTime,
	 @rFromDueDate DateTime,
	 @rToDueDate DateTime,
	 @rSourceTypeId int,
	 @rIsComplete bit,
	 @rIsClosed bit,
	 @rCreatedUserId bigint,
	 @rCode nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF(@rSourceTypeId = 95)
	BEGIN
	
		SELECT 
				DISTINCT AT.Id,
				AT.AssignedToSourceTypeId,
				AT.AssignedToSourceId,
				EM.Code AS SourceCode,
				EM.EmployeeName AS SourceName,
				CONVERT(varchar,AT.AssignedDate ,105) AS AssignedDate,
				CONVERT(varchar,AT.DueDate ,105) AS DueDate,
				AT.Remark,
				AT.IsCompleted,
				AT.IsClosed,
				OM.DisplayTitle AS Organization,
				ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
				ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'') AS AssignedBy,
				ISNULL(AT.DueReasonRemark,'') AS DueReasonRemark
				--ISNULL((SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId),'') AS AssignedBy
		FROM 
				sCommunication.tAssignTask AT
				INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
				INNER JOIN sSetup.tOrganizationMaster OM ON AT.OrgId=OM.Id
		WHERE 
				((AT.Id=@rId) OR (ISNULL(@rId,0) = 0))
			AND ((AT.AssignedDate >= @rFromStartDate) OR (ISNULL(@rFromStartDate,0) = 0))
			AND ((AT.AssignedDate <= @rToStartDate) OR (ISNULL(@rToStartDate,0) = 0)) 
			AND ((AT.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,0) = 0))
			AND ((AT.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,0) = 0))
			AND ((AT.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId=0))
			AND ((AT.IsCompleted= @rIsComplete))
			AND (AT.IsClosed= @rIsClosed)
			AND (AT.OrgId=@rOrgId OR @rOrgId = 0)
			AND AT.IsDeleted=0
			AND ((EM.Code =@rCode) OR ISNULL(@rCode,'')='')
	END			
ELSE
	BEGIN
	print 'Yes'
		SELECT 
				DISTINCT AT.Id,
				AT.AssignedToSourceTypeId,
				AT.AssignedToSourceId,
				SN.Code AS SourceCode,
				SN.Name AS SourceName,
				CONVERT(varchar,AT.AssignedDate,105) AS AssignedDate,
				CONVERT(varchar,AT.DueDate,105) AS DueDate,
				AT.Remark,
				AT.IsCompleted,
				AT.IsClosed,
				OM.DisplayTitle AS Organization,
				ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) FROM sStudent.tStudentMaster SM 
				 INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id WHERE SM.Id = U.SourceId)
				 ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'') AS AssignedBy
		FROM 
				sCommunication.tAssignTask AT
				INNER JOIN sStudent.vStudentName SN ON SN.StudentId=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId
				INNER JOIN sSetup.tOrganizationMaster OM ON AT.OrgId=OM.Id
		WHERE 
				((AT.Id=@rId) OR (ISNULL(@rId,0) = 0))
				AND ((AT.AssignedDate >= @rFromStartDate) OR (ISNULL(@rFromStartDate,0) = 0))
				AND ((AT.AssignedDate <= @rToStartDate) OR (ISNULL(@rToStartDate,0) = 0)) 
				AND ((AT.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,0) = 0))
				AND ((AT.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,0) = 0))
				AND ((AT.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId=0))
				AND ((AT.IsCompleted= @rIsComplete))
				AND (AT.IsClosed= @rIsClosed)
				AND (AT.OrgId=@rOrgId OR @rOrgId = 0)
				AND AT.IsDeleted=0
				AND ((SN.Code =@rCode) OR ISNULL(@rCode,'')='') 
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignTaskToMeGet]
	 
	 @rOrgId int,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId smallint,
	 @rSyncedDateTime datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

IF(@rUserSourceTypeId=95)
BEGIN

	SELECT 
		AT.Id,
		AT.AssignedDate,
		AT.DueDate,
		AT.Remark,
		AT.IsCompleted,
		AT.IsClosed,
		AT.IsDeleted,
		ISNULL((CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Id FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0 )
		WHEN U.SourceTypeId=2003
		THEN (SELECT Id FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END),0)AS AssignedBySourceId,
		ISNULL((CASE 
		WHEN U.SourceTypeId=95 
		THEN 95
		WHEN U.SourceTypeId=2003
		THEN 2003
		END),0)AS AssignedBySourceTypeId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT FirstName +' '+LastName FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT FirstName +' '+LastName FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByName,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Code FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByCode,
		AT.DueReasonRemark  
						
	FROM 
		sCommunication.tAssignTask AT
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=95
		INNER JOIN sSecurity.tUser U ON AT.CreatedUserId=U.Id
		
	WHERE 
		AT.AssignedToSourceId=@rUserSourceId
		AND (AT.OrgId=@rOrgId OR @rOrgId=0)
		AND (AT.UpdatedDateTime > @rSyncedDateTime OR @rSyncedDateTime IS NULL)
		AND ISNULL(EM.IsOtherUser,0) = 0 
	ORDER BY AT.DueDate
END
ELSE
BEGIN
	
	SELECT 
		AT.Id,
		AT.AssignedDate,
		AT.DueDate,
		AT.Remark,
		AT.IsCompleted,
		AT.IsClosed,
		AT.IsDeleted,
		ISNULL((CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Id FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Id FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END),0)AS AssignedBySourceId,
		ISNULL((CASE 
		WHEN U.SourceTypeId=95 
		THEN 95
		WHEN U.SourceTypeId=2003
		THEN 2003
		END),0)AS AssignedBySourceTypeId,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT FirstName +' '+LastName FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT FirstName +' '+LastName FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByName,
		(CASE 
		WHEN U.SourceTypeId=95 
		THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id=U.SourceId AND ISNULL(IsOtherUser,0) = 0)
		WHEN U.SourceTypeId=2003
		THEN (SELECT Code FROM sStudent.tStudentMaster WHERE Id=U.SourceId)
		END)AS AssignedByCode,
		'' as DueReasonRemark --DueReasonRemark need only in Employee Side
					
	FROM 
		sCommunication.tAssignTask AT
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=AT.AssignedToSourceId AND AT.AssignedToSourceTypeId=2003
		INNER JOIN sSecurity.tUser U ON AT.CreatedUserId=U.Id
		
	WHERE 
		AT.AssignedToSourceId=@rUserSourceId
		AND (AT.OrgId=@rOrgId OR @rOrgId=0)
		AND (AT.UpdatedDateTime > @rSyncedDateTime OR @rSyncedDateTime IS NULL)
	ORDER BY AT.DueDate
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignVideoAdd]
			
           @rSourceTypeId smallint
           ,@rSourceId bigint 
		   ,@rVideoId nvarchar(500)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount int
BEGIN 

set @lCount =  ( select ISNULL(COUNT(1),0) from sCommunication.tVideoSpecific where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND VideoId=@rVideoId)
   
	If (@lCount <> 0)
		BEGIN
			UPDATE sCommunication.tVideoSpecific SET SourceTypeId=@rSourceTypeId , SourceId=@rSourceId , VideoId=@rVideoId  where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId  AND VideoId=@rVideoId
			SELECT 1 AS Result
	  END 
	ELSE
			
			INSERT INTO sCommunication.tVideoSpecific
			(
				SourceTypeId
			   ,SourceId			   
			   ,VideoId
			)
			VALUES
			(	@rSourceTypeId
			   ,@rSourceId			   
			   ,@rVideoId
			)		
			SELECT 1 AS Result
	END
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignVideoGet]
	@rOrgId int = 0,
	@rSourceTypeId int = 0,
	@rDepartmentId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
SELECT * FROM (

SELECT DISTINCT VP.SourceTypeId, VP.SourceId, OM.DisplayTitle AS OrgName,SA.ClassName+' - '+SA.DivisionName AS ClassDepartment, 'Student' AS SourceType,
[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
VP.VideoId,OM.Id as OrgId,SA.DepartmentId
FROM sCommunication.tVideoSpecific VP
INNER JOIN sStudent.tStudentMaster SM ON VP.SourceId=SM.Id
INNER JOIN  sStudent.vStudentAcademic SA ON VP.SourceId=SA.StudentId 
--AND SA.IsActiveBatch=1 
AND SA.StatusId=1		
INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
WHERE VP.SourceTypeId=2003

UNION ALL

SELECT DISTINCT VP.SourceTypeId, VP.SourceId, OM.DisplayTitle AS OrgName,vEC.DepartmentName AS ClassDepartment,'Employee' AS SourceType,vEC.FirstName +' '+ vEC.LastName AS Source,
VP.VideoId,OM.Id as OrgId,vEC.DepartmentId
FROM sCommunication.tVideoSpecific VP
INNER JOIN sHrm.vEmployeeCommunication vEC ON VP.SourceId=vEC.EmployeeId AND vEC.StatusId=7
INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id					
WHERE VP.SourceTypeId=95

--UNION ALL
		
--SELECT	 VP.SourceTypeId, VP.SourceId, OM.DisplayTitle AS OrgName,'' AS ClassDepartment, 'Organization' AS SourceType,OM.DisplayTitle AS Source,
--VP.VideoId,OM.Id as OrgId
--FROM sCommunication.tVideoSpecific VP
--INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id WHERE VP.SourceTypeId=2021

--UNION ALL

--SELECT VP.SourceTypeId, VP.SourceId, OM.DisplayTitle AS OrgName,DM.Title AS ClassDepartment, 'Department' AS SourceType,DM.DisplayTitle AS Source,
--VP.VideoId,OM.Id as OrgId
--FROM sCommunication.tVideoSpecific VP
--INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
--INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
--WHERE VP.SourceTypeId=2017

--UNION ALL

--SELECT VP.SourceTypeId, VP.SourceId, OM.DisplayTitle AS OrgName,DM.Title AS ClassDepartment, 'Class' AS SourceType,CM.DisplayTitle AS Source,
--VP.VideoId,OM.Id as OrgId
--FROM sCommunication.tVideoSpecific VP
--INNER JOIN sSetup.tClassMaster CM ON VP.SourceId=CM.Id
--INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
--INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
--WHERE VP.SourceTypeId=2016

--UNION ALL

--SELECT VP.SourceTypeId, VP.SourceId, OM.DisplayTitle AS OrgName,DMast.Title AS ClassDepartment, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,
--VP.VideoId,OM.Id as OrgId
--FROM sCommunication.tVideoSpecific VP
--INNER JOIN sSetup.tDivisionMaster DM ON VP.SourceId=DM.Id
--INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
--INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
--INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
--WHERE VP.SourceTypeId=2005

--UNION ALL

--SELECT VP.SourceTypeId, VP.SourceId, OM.DisplayTitle AS OrgName,SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,'Student' AS SourceType,SA.Name AS Source,
--VP.VideoId,OM.Id as OrgId
--FROM sCommunication.tVideoSpecific VP
--INNER JOIN sStudent.vStudentAcademic SA	ON VP.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
--INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
--WHERE VP.SourceTypeId=2001

) tmp

WHERE ((tmp.OrgId=@rOrgId) or @rOrgId=0)
AND ((tmp.SourceTypeId=@rSourceTypeId) or @rSourceTypeId=0)
AND ((tmp.DepartmentId=@rDepartmentId) or @rDepartmentId=0)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignVideoPlaylistAdd]
			
           @rSourceTypeId smallint
           ,@rSourceId bigint           
           ,@rAssignId int,
		   @rPlaylistName nvarchar(500)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount int
BEGIN 

set @lCount =  ( select ISNULL(COUNT(1),0) from sCommunication.tVideoPlaylist where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND AssignedToId=@rAssignId AND PlaylistName=@rPlaylistName)
   
	If (@lCount <> 0)
		BEGIN 
			SELECT 1 AS Result
	  END 
	ELSE
			
			INSERT INTO sCommunication.tVideoPlaylist
			(
				SourceTypeId
			   ,SourceId
			   ,AssignedToId
			   ,PlaylistName
			)
			VALUES
			(	@rSourceTypeId
			   ,@rSourceId
			   ,@rAssignId
			   ,@rPlaylistName
			)		
			SELECT 11 AS Result
	END
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sCommunication].[pAssignVideoPlaylistGet]
	@rAssignId int = 0,
	@rOrgGroupId int = 0,
	@rSourceTypeId smallint = 0,
	@rSourceId bigint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
		SELECT * FROM (SELECT	 VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,'' AS ClassDepartment, 'Organization' AS SourceType,OM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId WHERE VP.SourceTypeId=2021

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,DM.Title AS ClassDepartment, 'Department' AS SourceType,DM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
WHERE VP.SourceTypeId=2017

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,DM.Title AS ClassDepartment, 'Class' AS SourceType,CM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sSetup.tClassMaster CM ON VP.SourceId=CM.Id
INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
WHERE VP.SourceTypeId=2016

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,DMast.Title AS ClassDepartment, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sSetup.tDivisionMaster DM ON VP.SourceId=DM.Id
INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId		
WHERE VP.SourceTypeId=2005

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,SA.ClassName+' - '+SA.DivisionName AS ClassDepartment, 'Student' AS SourceType,
[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sStudent.tStudentMaster SM ON VP.SourceId=SM.Id
INNER JOIN  sStudent.vStudentAcademic SA ON VP.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId		
WHERE VP.SourceTypeId=2003

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,'Student' AS SourceType,SA.Name AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sStudent.vStudentAcademic SA	ON VP.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId			
WHERE VP.SourceTypeId=2001 

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,OM.DisplayTitle AS OrgName,vEC.DepartmentName AS ClassDepartment,'Employee' AS SourceType,vEC.FirstName +' '+ vEC.LastName AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PlaylistName,OGM.Id AS OrgGroupId
FROM sCommunication.tVideoPlaylist VP
INNER JOIN sHrm.vEmployeeCommunication vEC ON VP.SourceId=vEC.EmployeeId AND vEC.StatusId=7
INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId					
WHERE VP.SourceTypeId=95
) tmp
where (tmp.AssignedToId=@rAssignId OR (@rAssignId=0))
AND tmp.OrgGroupId = @rOrgGroupId
AND (tmp.SourceTypeId =@rSourceTypeId OR (@rSourceTypeId=0))
AND (tmp.SourceId = @rSourceId OR (@rSourceId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignVideoPlaylistRemove]
			
           @rSourceTypeId smallint
           ,@rSourceId bigint           
           ,@rAssignId int,
		   @rPlaylistName nvarchar(500)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN 

	DELETE FROM sCommunication.tVideoPlaylist where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND AssignedToId=@rAssignId AND PlaylistName = @rPlaylistName


			SELECT 1 AS Result
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pAssignVideoRemove]
			
           @rSourceTypeId smallint
           ,@rSourceId bigint 
		   ,@rVideoId nvarchar(500)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN 

	DELETE FROM sCommunication.tVideoSpecific where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND VideoId=@rVideoId 


			SELECT 1 AS Result
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pBehaviourEntryAdd]
	 
	@rId bigint,
	@rBehaviourDate date,
	@rAcademicId  bigint,
	@rBehaviourTypeId int,
	@rTitle nvarchar(100),
	@rRemark nvarchar(1000), --length 500 to 1000 add for mantis : 0043364
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		--IF(@rId = 0)	
--	IF Exists(Select @rCode from	sLibrary.tBookMaster where Code=@rCode)
--BEGIN
--Select -103 AS Result
--RETURN
--END	
BEGIN TRANSACTION

IF(@rId = 0)

    BEGIN
DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tBehaviour', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommunication.tBehaviour
		(
			Id,
			BehaviourDate,
			AcademicId,
			BehaviourTypeId,
			Title,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rBehaviourDate,
			@rAcademicId,
			@rBehaviourTypeId,
			@rTitle,
			ISNULL(@rRemark,''),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		   Select @lNextNumber AS Result
	END
	ELSE
	
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tBehaviour
	    SET
			BehaviourDate=@rBehaviourDate,
			AcademicId=@rAcademicId,
			BehaviourTypeId=@rBehaviourTypeId,
			Title=@rTitle,
			Remark=ISNULL(@rRemark,'')
	--		BehaviourIndicatorId=@rBehaviourIndicatorId,
	--		OrgId=@rOrgId,
	--		IsObsolete=@rIsObsolete,
	--		UpdatedUserId=@rUpdatedUserId,
	--		UpdatedDateTime= sCommon.fGetDate()
			
	      
	      WHERE Id = @rId 
     SELECT @lNextNumber AS Result
	
END	
	
	COMMIT TRANSACTION
END TRY

	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pBehaviourGet]
		
		@rId bigint,
		@rBehaviourTypeId int,
		@rOrgGroupBatchId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rFromDate date='',
		@rToDate date='',
		@rCreatedUserId bigint=0,
		@rBatchId int,
		@rOrgId int = 0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
	B.Id AS BehaviourId,
	B.BehaviourDate,
	B.Title,
	BTM.Title AS BehaviourType,
	SA.Name,
	SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
	SA.Code,
	B.Remark,
	B.BehaviourTypeId,
	B.AcademicId,
	U.DisplayTitle AS UserName,
	SA.OrgId,
	SA.BatchId
  FROM 
        sCommunication.tBehaviour B
        INNER JOIN sCommunication.tBehaviourTypeMaster BTM ON B.BehaviourTypeId=BTM.Id
        INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=B.AcademicId
        INNER JOIN sSecurity.tUser U ON U.Id = B.CreatedUserId
         --INNER JOIN sStudent.tStudentMaster SM ON SM.Id=B.AcademicId
  WHERE 
	((B.Id=@rId) OR (ISNULL(@rId,0)=0))
    AND ((B.BehaviourTypeId= @rBehaviourTypeId) OR (ISNULL(@rBehaviourTypeId,0) = 0)) 
    --AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId))
    AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((B.Title=@rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((B.BehaviourDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND((B.BehaviourDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((B.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pBehaviourListGet]
		
		@rOrgGroupBatchId int,
		@rStudentId bigint,
		@rBehaviourTypeId int,
		@rBehaviourIndicatorId int
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	 
	SELECT 
	B.Id,
	B.BehaviourDate,
	B.Title,
	BTM.Title AS BehaviourType,
	--SA.FirstName+' '+SA.LastName AS Name,
	--SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
	--SA.Code,
	B.Remark,
	BTM.BehaviourIndicatorId,
	BIM.Title AS BehaviourIndicatorTitle
	--B.BehaviourTypeId,
	--B.AcademicId
	
  FROM 
        sCommunication.tBehaviour B
         INNER JOIN sCommunication.tBehaviourTypeMaster BTM
         ON B.BehaviourTypeId=BTM.Id
         INNER JOIN sCommunication.tBehaviourIndicatorMaster BIM
         ON BTM.BehaviourIndicatorId=BIM.Id
         INNER JOIN sStudent.vStudentAcademic  SA
         ON SA.AcademicId=B.AcademicId AND SA.StudentId = @rStudentId AND SA.OrgGroupBatchId = @rOrgGroupBatchId
WHERE
         ((B.BehaviourTypeId= @rBehaviourTypeId) OR (ISNULL(@rBehaviourTypeId,0) = 0))  
         AND ((BTM.BehaviourIndicatorId=@rBehaviourIndicatorId) OR (ISNULL(@rBehaviourIndicatorId,0)=0)) 
        
         
        ORDER BY B.Id DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pBehaviourNotificationUserGet]
		
		@rBehaviourId bigint
				
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
			SElECT 	
				A.StudentId,
				BTM.Title AS BehaviourTypeTitle
			
			FROM 
			sCommunication.tBehaviour B
			INNER JOIN sCommunication.tBehaviourTypeMaster BTM 
				ON BTM.Id=B.BehaviourTypeId
			INNER JOIN sStudent.tAcademic A 
				ON B.AcademicId=A.Id 
				
			WHERE B.Id=@rBehaviourId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pBehaviourTypeMasterAdd]
	 
	@rId int,
	--@rCode nvarchar(25),
	@rTitle nvarchar(100),
	@rRemark nvarchar(200),
	@rBehaviourIndicatorId int,
	@rIsObsolete bit,
	@rOrgGroupId smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		--IF(@rId = 0)	
--	IF Exists(Select @rCode from	sLibrary.tBookMaster where Code=@rCode)
--BEGIN
--Select -103 AS Result
--RETURN
--END
		
BEGIN TRANSACTION

IF(@rId = 0)

    BEGIN
DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tBehaviourTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommunication.tBehaviourTypeMaster
		(
			Id,
			Title,
			Remark,
			BehaviourIndicatorId,
			OrgGroupId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rBehaviourIndicatorId,
			@rOrgGroupId,
			@rIsObsolete,
		    @rCreatedUserId,
			sCommon.fGetDate()
		)
		   Select @lNextNumber AS Result
	END
	ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tBehaviourTypeMaster
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			BehaviourIndicatorId=@rBehaviourIndicatorId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime= sCommon.fGetDate()
	      WHERE Id = @rId 
     SELECT @lNextNumber AS Result
END	
	
	COMMIT TRANSACTION
END TRY
	
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pBehaviourTypeMasterGet]
	 
	 @rId int,
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint,
	 @rBehaviourIndicatorId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  --BEGIN
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	 
	SELECT 
	BTM.Id,
	BTM.Title,
	BTM.Remark,
	BTM.BehaviourIndicatorId,
	BIM.Title AS BehaviourIndicatorTitle,
	BTM.OrgGroupId,
	BTM.IsObsolete,
	BTM.CreatedUserId,
	BIM.Title AS BehaviourType
  FROM 
        sCommunication.tBehaviourTypeMaster BTM
         INNER JOIN sCommunication.tBehaviourIndicatorMaster BIM
         ON BTM.BehaviourIndicatorId=BIM.Id
  WHERE 
      ((BTM.Id = @rId) OR (@rId = 0))
      AND  ((BTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	  AND BTM.OrgGroupId = @rOrgGroupId	
	  AND ((BIM.Id = @rBehaviourIndicatorId) OR (@rBehaviourIndicatorId = 0))
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pBehaviourViewGet]
		
		@rOrgGroupBatchId int,
		@rAcademicId bigint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
declare @lBehaviourGrid nvarchar(max)=''
	SELECT  @lBehaviourGrid = @lBehaviourGrid + '<tr>
	<td align="left" scope="col">' + convert(varchar,isnull(B.BehaviourDate,''),103) + '</td>
	<td align="left" scope="col">' + isnull (BTM.Title,'')  + '</td>
	<td align="left" scope="col">' + isnull( B.Title,'')+ '</td>	
	<td align="left" scope="col">' + isnull(B.Remark,'') + '</td>
	<tr>'
  FROM 
        sCommunication.tBehaviour B
         INNER JOIN sCommunication.tBehaviourTypeMaster BTM
         ON B.BehaviourTypeId=BTM.Id
         INNER JOIN sStudent.vStudentAcademic SA
         ON SA.AcademicId=B.AcademicId
      
  WHERE 
     ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	
	select isnull(@lBehaviourGrid,'') as behaviourgrid
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pBlogActivitiesGet]
	 @rCreatedUserId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			B.Id,
			BC.Remark,
			U.DisplayTitle AS CommentCreatedUserName,
			BC.CreatedDateTime AS CommentCreatedDateTime
  FROM 
            sCommunication.tBlogComment BC
            INNER JOIN sCommunication.tBlog B ON B.Id=BC.BlogId AND B.CreatedUserId=@rCreatedUserId
            INNER JOIN sSecurity.tUser U ON U.Id=BC.CreatedUserId
  WHERE 
	(BC.CreatedUserId!=@rCreatedUserId)
	order by BC.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pBlogAdd]
	 
        @rId bigint,
		@rOrgGroupBatchId int,
		@rOrgGroupId smallint,
		@rTitle nvarchar(200),
		@rRemark nvarchar(max),
		@rIsPublish bit,
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tBlog where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tBlog where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tBlog where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tBlog where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tBlog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tBlog
		(
			Id,
			OrgGroupBatchId,
			OrgGroupId,
			Title,
			Remark,
			IsPublish,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupBatchId,
			@rOrgGroupId,
			@rTitle,
			@rRemark,
			@rIsPublish,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tBlog
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			IsPublish=@rIsPublish,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pBlogCommentAdd]
	 
        --@rId bigint,
		@rBlogId bigint,
		@rRemark nvarchar(500),
		@rCreatedUserId bigint,
		@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	--IF(@rId = 0)	
	--BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tBlogComment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tBlogComment
		(
			Id,
			BlogId,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rBlogId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	--END	 

--ELSE
--	 BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  sCommunication.tBlogComment
--	    SET
--			BlogId=@rBlogId,
--			Remark=@rRemark,
--			UpdatedUserId=@rCreatedUserId,
--			UpdatedDateTime=sCommon.fGetDate()
	      
--	      WHERE Id = @rId
--	      SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION
--	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pBlogCommentDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tBlogComment where Id=@rId
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pBlogCommentGet]
	   
	   @rBlogId bigint,
	 --@rBatchId bigint
	   --@rSyncedBlogCommentId bigint=0,
	   @rOrgGroupBatchId int=0,
	   @rOrgId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	 
IF(@rOrgId>0)	 
BEGIN
	SELECT 
			BC.Id,
			BC.BlogId,
			B.Title,
			B.Remark AS BlogRemark,
			--B.BatchId,
		 --   BM.Title AS Batch,
		    BC.Remark,
		    U1.DisplayTitle as BlogCreatedUserName,
		    B.CreatedDateTime as BlogCreatedDateTime,
		    U2.DisplayTitle as CommentCreatedUserName,
		    BC.CreatedDateTime as CommentCreatedDateTime,
		    TotalBlogFavorite=(Select Count(*) from sCommunication.tBlogFavorite where BlogId=@rBlogId),
		    B.CreatedUserId AS BlogCreatedUserId,
		    BC.CreatedUserId AS CommentCreatedUserId
  FROM 
            sCommunication.tBlogComment BC
            INNER JOIN sCommunication.tBlog B ON B.Id=BC.BlogId
            INNER JOIN sSecurity.tUser U1 ON U1.Id=B.CreatedUserId
            INNER JOIN sSecurity.tUser U2 ON U2.Id=BC.CreatedUserId
            INNER JOIN sCommunication.tBlogScope BS ON BS.BlogId=B.Id AND ((BS.SourceId=@rOrgId)OR (@rOrgId=0))
  WHERE 
  
       ((B.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
       AND (( BC.BlogId = @rBlogId) OR (@rBlogId = 0))
	--AND ( BC.Id > @rSyncedBlogCommentId OR @rSyncedBlogCommentId = 0)
	Order by BC.CreatedDateTime DESC

END
ELSE IF(@rOrgId=0)
BEGIN
	SELECT 
			BC.Id,
			BC.BlogId,
			B.Title,
			B.Remark AS BlogRemark,
			--B.BatchId,
		 --   BM.Title AS Batch,
		    BC.Remark,
		    U1.DisplayTitle as BlogCreatedUserName,
		    B.CreatedDateTime as BlogCreatedDateTime,
		    U2.DisplayTitle as CommentCreatedUserName,
		    BC.CreatedDateTime as CommentCreatedDateTime,
		    TotalBlogFavorite=(Select Count(*) from sCommunication.tBlogFavorite where BlogId=@rBlogId),
		    B.CreatedUserId AS BlogCreatedUserId,
		    BC.CreatedUserId AS CommentCreatedUserId
  FROM 
            sCommunication.tBlogComment BC
            INNER JOIN sCommunication.tBlog B ON B.Id=BC.BlogId
            INNER JOIN sSecurity.tUser U1 ON U1.Id=B.CreatedUserId
            INNER JOIN sSecurity.tUser U2 ON U2.Id=BC.CreatedUserId
  WHERE 
  
      ((BC.BlogId = @rBlogId) OR (@rBlogId = 0))
	--AND ((B.BatchId=@rBatchId) OR (@rBatchId=0)) 
	Order by BC.CreatedDateTime DESC
END	 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pBlogDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sCommunication.tBlogFavorite where BlogId=@rId
			Delete from sCommunication.tBlogComment where BlogId=@rId
			Delete from sCommunication.tBlogScope where BlogId=@rId
			Delete from sCommunication.tBlog where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pBlogFavoriteAdd]
	 
        @rBlogId bigint,
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	If Exists(Select * from sCommunication.tBlogFavorite where BlogId=@rBlogId AND UserId=@rCreatedUserId)
	BEGIN
		SELECT @rBlogId AS Result
		RETURN
	END
	INSERT INTO sCommunication.tBlogFavorite
		(
			BlogId,
			UserId
		)
	VALUES
		(
			@rBlogId,
			@rCreatedUserId
		)
		    SELECT @rBlogId AS Result
	
		--COMMIT TRANSACTION         
	--END	 

--ELSE
--	 BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  sCommunication.tBlogFavorite
--	    SET
--			BlogId=@rBlogId,
--			Remark=@rRemark,
--			UpdatedUserId=@rCreatedUserId,
--			UpdatedDateTime=sCommon.fGetDate()
	      
--	      WHERE Id = @rId
--	      SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION
--	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pBlogGet]
	 
	 @rId bigint,
	 @rOrgGroupBatchId int,
	 @rTitle nvarchar(200),
	 @rCreatedUserId bigint,
	 @rIsSearch bit = 1,
	 @rOrgId smallint,
	 @rSyncedBlogId bigint=0,
	 @rCreatedDateTime Date='',
	 @rFromDate date='',
	 @rToDate date=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			Distinct(B.Id),
			B.OrgGroupBatchId,
		    OGBM.Title AS OrgGroupBatch,
		    B.Title,
		    B.Remark,
		    B.IsPublish,
		    U.DisplayTitle AS BlogCreatedUserName,
		    B.CreatedDateTime AS BlogCreatedDateTime,		 
		    (SELECT  ISNULL(Count(1),0) FROM sCommunication.tBlogFavorite BF WHERE BF.BlogId = B.Id) AS TotalBlogFavorite,
		    (SELECT ISNULL( Count(1),0) FROM sCommunication.tBlogComment BC WHERE BC.BlogId = B.Id) AS TotalBlogComment
		    
  FROM 
            sCommunication.tBlog B
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=B.OrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
			INNER JOIN sCommunication.tBlogScope BS ON BS.BlogId=B.Id AND ((BS.SourceId=@rOrgId)OR (@rOrgId=0))
  WHERE 
  
		((B.Id = @rId) OR (@rId = 0))
	AND ((B.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((B.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	AND ((B.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ( B.Id > @rSyncedBlogId OR @rSyncedBlogId = 0)
	AND ((convert(date,B.CreatedDateTime) = convert(date,@rCreatedDateTime)) OR (ISNULL(@rCreatedDateTime,'') = ''))
	AND (CONVERT(date,B.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
	AND (CONVERT(date,B.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pBlogScopeAdd] 
     @rBlogId BIGINT,
	 @rSourceTypeId SMALLINT,
	 @rSourceId BIGINT,
	 @rIsDeleted BIT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF (@rIsDeleted = 1)
	BEGIN
		DELETE
		FROM sCommunication.tBlogScope
		WHERE BlogId = @rBlogId
			AND SourceTypeId = @rSourceTypeId
			AND SourceId = @rSourceId

		SELECT @rSourceId AS Result
	END
	ELSE
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION

			IF EXISTS (
					SELECT BlogId
					FROM sCommunication.tBlogScope
					WHERE BlogId = @rBlogId
						AND SourceTypeId = @rSourceTypeId
						AND SourceId = @rSourceId
					)
			BEGIN
				SELECT @rSourceId AS Result
				COMMIT TRANSACTION
				RETURN
			END
			ELSE
			BEGIN
				INSERT INTO sCommunication.tBlogScope (
					BlogId
					,SourceTypeId
					,SourceId
					)
				VALUES (
					@rBlogId
					,@rSourceTypeId
					,@rSourceId
					)

				SELECT @rBlogId AS Result
			END

			COMMIT TRANSACTION
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION

			SELECT - 1 AS Result
		END CATCH
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pBlogScopeGet]
	 
	 @rBlogId bigint,
	 @rOrgGroupId smallint,
	 @rUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OM.Id  as SourceId,
			OM.DisplayTitle as Organization,
			2021 as SourceTypeId,
			CASE WHEN BS.SourceId IS NULL OR BS.BlogId!=@rBlogId THEN 0 ELSE 1 END AS IsObsolete
  FROM 
			sSetup.tOrganizationMaster OM
			INNER JOIN sSetup.vUserOrganization UO ON UO.Id=OM.Id AND UO.OrgGroupId=@rOrgGroupId AND UO.UserId=@rUserId
			LEFT JOIN sCommunication.tBlogScope BS ON BS.SourceId=OM.Id AND BS.SourceTypeId=2021 AND BS.BlogId=@rBlogId
	Order BY OM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exe [sCommunication].[pChatDetailsGet] 1001,1001000000001
CREATE OR ALTER PROCEDURE [sCommunication].[pChatApproveSet]
	 
	 @rOrgGroupId INT= 0,	 
	 @rChatGroupId INT = 0,	
	 @rMessageId BIGINT = 0 ,
	 @rChatStatusId Int = 0	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id =@rOrgGroupId)
	BEGIN
		SELECT -201 AS Result
		RETURN
	END
	IF NOT EXISTS (SELECT 1 FROM [sCommunication].[tChatGroupMaster] WHERE Id =@rChatGroupId)
	BEGIN
		SELECT -202 AS Result
		RETURN
	END
	IF NOT EXISTS (SELECT 1 FROM [sCommunication].[tChat] WHERE AutoId =@rMessageId and ToSourceId = @rChatGroupId)
	BEGIN
		SELECT -203 AS Result
		RETURN
	END
	
	
	UPDATE [sCommunication].[tChat]
	SET  ChatStatusId = @rChatStatusId
	WHERE AutoId = @rMessageId and ToSourceId = @rChatGroupId
	
	SELECT 200 AS Result
	RETURN
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
--exec [sCommunication].[pChatDetails] 95,9935000000046 ,95,9935000000027
CREATE OR ALTER PROCEDURE [sCommunication].[pChatDetails]
	 
	 @rFromSourceTypeId int ,
	 @rFromSourceId bigint ,
	 @rToSourceTypeId int,
	 @rToSourceId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @FromSourceName nvarchar(200)
	IF (@rToSourceTypeId = 2035)
	SELECT
		ISNULL(CC.ChatDetail,'') As ChatDetail,
		ISNULL(CC.ContentPath,'') As ContentPath,
		CC.CreatedDateTime,
		CC.FromSourceId,
		CASE WHEN CC.FromSourceTypeId=95 THEN (SELECT FirstName +' '+ MiddleName +' '+ LastName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId) 
		WHEN  CC.FromSourceTypeId = 2001 THEN (SELECT SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId WHERE A.Id = CC.FromSourceId) END As FromSourceName,
		CCGM.IsDisplayOnApproval,
		CASE WHEN CC.FromSourceId = @rFromSourceId THEN 2 ELSE CC.ChatStatusId END AS ChatStatusId,
		CC.AutoId As ChatId,
		CCGM.CreatedUserId ,
		(SELECT  (Case when ( ISNULL(CC.ChatDetail,'') != '') then 0 else 
		(Case when ( ISNULL(CC.ContentPath,'') = '') then 0 else
		(Case WHEN ( Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='pdf') Then 1 else 
		(CASE WHEN (Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mp4' OR Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mov') THEN 2 else
		(CASE WHEN (Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='ppt' OR 
		Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='pptx') THEN 3 else 
		4
		end)end )end)end)end)) As Type 
		
	FROM
		[sCommunication].[tChat] CC	
		INNER JOIN [sCommunication].[tChatGroupMaster] CCGM ON CC.ToSourceId = CCGM.Id		
	WHERE 
		
		CC.ToSourceId = @rToSourceId
		AND CC.ToSourceTypeId = @rToSourceTypeId

	ELSE IF(@rToSourceTypeId = 2036)
	BEGIN
		SELECT
		ISNULL(CC.ChatDetail,'') As ChatDetail,
		ISNULL(CC.ContentPath,'') As ContentPath,
		CC.CreatedDateTime,
		CC.FromSourceId,
		CASE WHEN CC.FromSourceTypeId=95 THEN (SELECT FirstName +' '+ MiddleName +' '+ LastName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId) 
		WHEN  CC.FromSourceTypeId = 2001 THEN (SELECT SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId WHERE A.Id = CC.FromSourceId) END As FromSourceName,
		'false' AS IsDisplayOnApproval,
		CASE WHEN CC.FromSourceId = @rFromSourceId THEN 2 ELSE CC.ChatStatusId END AS ChatStatusId,
		CC.AutoId As ChatId,
		OL.CreatedUserId ,
		(SELECT  (Case when ( ISNULL(CC.ChatDetail,'') != '') then 0 else 
		(Case when ( ISNULL(CC.ContentPath,'') = '') then 0 else
		(Case WHEN ( Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='pdf') Then 1 else 
		(CASE WHEN (Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mp4' OR Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mov') THEN 2 else
		(CASE WHEN (Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='ppt' OR 
		Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='pptx') THEN 3 else 
		4
		end)end )end)end)end)) As Type 
		
	FROM
		[sCommunication].[tChat] CC	
		INNER JOIN [sAcademic].[tOnlineLearning] OL ON CC.ToSourceId = OL.Id		
	WHERE 
		
		CC.ToSourceId = @rToSourceId
		AND CC.ToSourceTypeId = @rToSourceTypeId
	END
		
	ELSE

		SELECT
		ISNULL(CC.ChatDetail,'') As ChatDetail,
		ISNULL(CC.ContentPath,'') As ContentPath,
		CC.CreatedDateTime,
		(CASE WHEN (@rFromSourceId = CC.FromSourceId AND @rFromSourceTypeId = CC.FromSourceTypeId) then CC.FromSourceId 
			 WHEN (@rFromSourceId = CC.ToSourceId AND @rFromSourceTypeId = CC.ToSourceTypeId) then CC.FromSourceId END) AS FromSourceId ,
		CASE WHEN (@rFromSourceTypeId=95 AND @rFromSourceId = CC.FromSourceId) THEN (SELECT FirstName +' '+ MiddleName +' '+ LastName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId) 
			 WHEN ( @rFromSourceTypeId = 2001 AND @rFromSourceId = CC.FromSourceId) THEN (SELECT SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId WHERE A.Id = CC.FromSourceId) 
			 WHEN (@rFromSourceTypeId=95 AND @rFromSourceId = CC.ToSourceId AND CC.FromSourceTypeId = 95) THEN (SELECT FirstName +' '+ MiddleName +' '+ LastName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId) 
			 WHEN (@rFromSourceTypeId=95 AND @rFromSourceId = CC.ToSourceId AND CC.FromSourceTypeId = 2001) THEN (SELECT SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId WHERE A.Id = CC.FromSourceId) 
			 WHEN ( @rFromSourceTypeId = 2001 AND @rFromSourceId = CC.ToSourceId AND CC.FromSourceTypeId = 2001) THEN (SELECT SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId WHERE A.Id = CC.FromSourceId) 
			 WHEN ( @rFromSourceTypeId = 2001 AND @rFromSourceId = CC.ToSourceId AND CC.FromSourceTypeId = 95) THEN (SELECT FirstName +' '+ MiddleName +' '+ LastName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId) 
		END As FromSourceName,
		'false' AS IsDisplayOnApproval,
		CC.ChatStatusId,
		CC.AutoId As ChatId,
		CC.CreatedUserId AS CreatedUserId ,

		(SELECT  (Case when ( ISNULL(CC.ChatDetail,'') != '') then 0 else 
		(Case when ( ISNULL(CC.ContentPath,'') = '') then 0 else
		(Case WHEN ( Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='pdf') Then 1 else 
		(CASE WHEN (Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mp4' OR Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mov') THEN 2 else
		(CASE WHEN (Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='ppt' OR 
		Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='pptx') THEN 3 else 
		4
		end)end )end)end)end)) As Type  
		
	FROM
		 [sCommunication].[tChat] CC	
		---INNER JOIN [sCommunication].[tChatGroupMaster] CCGM ON CC.ToSourceId = CCGM.Id		
	WHERE 
		--CC.FromSourceId = @rFromSourceId
		--AND 
		((CC.FromSourceTypeId = @rFromSourceTypeId AND CC.FromSourceId = @rFromSourceId AND CC.ToSourceTypeId = @rToSourceTypeId AND CC.ToSourceId = @rToSourceId)
		 OR (CC.ToSourceTypeId = @rFromSourceTypeId AND CC.ToSourceId = @rFromSourceId AND CC.FromSourceTypeId = @rToSourceTypeId AND CC.FromSourceId = @rToSourceId)) 
		--AND CC.ToSourceTypeId = @rToSourceTypeId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 --exec [sCommunication].[pChatDetailsCreate] 'new group',1001,'1',Cast(<Table><UsersourceDetails UserSourceId='1001000000001' UserSourceTypeId='2003' /><UsersourceDetails UserSourceId='1001000000012' UserSourceTypeId='95' /></Table>),'1','07/05/2020'
CREATE OR ALTER PROCEDURE  [sCommunication].[pChatDetailsCreate]  
 @rChatGroupName nvarchar(200) = '',  
 @rOrggroupId INT= 0,
 @rOrgId INT= 0,
 @rUserId nvarchar(50) = '',
 @rStr nvarchar(max) = '',  
 @rChatTypeId nvarchar(5) = '',  
-- @rCreatedDateTime nvarchar(10) = '',
 @rIsApprove bit =0,
 @rChatDetail nvarchar(1000) = '',
 @rAssigneeToId int = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN  
	DECLARE @ChatId BIGINT= 0;
	DECLARE @lNextNumber BIGINT --= (SELECT (ISNULL(Max(Id),0) + 1) as Id FROM [sCommunication].[tChatGroupMaster]);
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tChatGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber

	DECLARE @StrXML XML  
    SET @StrXML = CAST(@rStr AS XML)  
   
	DECLARE @tChatGroupScope TABLE  
	(  
	Id Int IDENTITY(1, 1),  
	UserSourceId BIGINT,  
	UserSourceTypeId  INT		
	)   
    INSERT INTO @tChatGroupScope  
    SELECT           
              
            T.c.value('@UserSourceId','bigint') AS UserSourceId,  
            T.c.value('@UserSourceTypeId','int') AS [UserSourceTypeId]             
    FROM   
            @StrXML.nodes('/Table/UsersourceDetails')T(c)  

 --Creating Group or Broadcast
	INSERT 
	INTO
	[sCommunication].[tChatGroupMaster](Id,OrgGroupId,ChatTypeId,Title,IsDisplayOnApproval,ChatAdminEmployeeId,CreatedUserId,
	CreatedDateTime)
	ValUES
	(@lNextNumber,@rOrggroupId,CONVERT(tinyint,@rChatTypeId), @rChatGroupName, @rIsApprove,(SELECT SourceId FROM [sSecurity].[tUser] WHERE Id = @rUserId), CONVERT(bigint,@rUserId),GetDate())

  --set @ChatId = @@identity 
  Declare @count int=1             
  Declare @intstatus int = 1               
            
  WHILE(@count <= (select count(*) from @tChatGroupScope))                
  Begin
	Declare @userSourceId bigint = (SELECT UserSourceId FROM @tChatGroupScope WHERE Id = @count);
	IF(@rAssigneeToId =1)
	BEGIN
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2021)
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select @lNextNumber,
			2001 ,
			SA.Id,
			@rAssigneeToId 
			FROM  [sStudent].[tAcademic] SA 
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SA.OrgId = OM.Id 
			WHERE   OM.OrgGroupId = @rOrgGroupId and OM.Id = @userSourceId
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2017)
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select distinct @lNextNumber,
			2001 ,
			SA.Id 
			,@rAssigneeToId
			FROM
			 [sStudent].[tAcademic] SA 
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SA.OrgId = OM.Id
			INNER JOIN [sSetup].[tClassMaster] CM ON SA.ClassId = CM.Id
			INNER JOIN [sSetup].[tDepartmentMaster] DM ON DM.Id = CM.DepartmentId
			WHERE   OM.OrgGroupId = @rOrgGroupId and DM.Id = @userSourceId
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2016)
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select distinct @lNextNumber,
			2001 ,
			SA.Id 
			,@rAssigneeToId
			FROM  
			[sStudent].[tAcademic] SA   
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SA.OrgId = OM.Id
			INNER JOIN [sSetup].[tClassMaster] CM ON SA.ClassId = CM.Id		
			WHERE   OM.OrgGroupId = @rOrgGroupId and CM.Id = @userSourceId
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2005)
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select distinct @lNextNumber,
			2001 ,
			SA.Id 
			,@rAssigneeToId
			FROM  
			[sStudent].[tAcademic] SA  
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SA.OrgId = OM.Id
			INNER JOIN [sSetup].[tClassMaster] CM ON SA.ClassId = CM.Id
			INNER JOIN [sSetup].[tDivisionMaster] DM ON DM.ClassId = CM.Id		
			WHERE   OM.OrgGroupId = @rOrgGroupId and DM.Id = @userSourceId
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2001)
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			VAlues( @lNextNumber, 2001 ,@userSourceId,@rAssigneeToId )
		
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2021) --For Organization
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select @lNextNumber,
			SU.SourceTypeId ,
			SU.SourceId
			,@rAssigneeToId 
			FROM  [sSecurity].[tUser] SU 
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SU.OrgId = OM.Id  and SU.SourceTypeId = 95
			WHERE   OM.OrgGroupId = @rOrgGroupId and OM.Id = @userSourceId
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2017) --For Department wise
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select distinct @lNextNumber,
			SU.SourceTypeId ,
			SU.SourceId 
			,@rAssigneeToId
			FROM  [sSecurity].[tUser] SU
			INNER JOIN sHrm.tEmployeeMaster EM ON SU.SourceId = EM.Id and SU.SourceTypeId = 95
			INNER JOIN [sHrm].[tEmployeeJobDetail] EJD ON EJD.EmployeeId = EM.Id  
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SU.OrgId = OM.Id		
			INNER JOIN [sSetup].[tDepartmentMaster] DM ON DM.Id = EJD.OrganizationDepartmentId
			WHERE   OM.OrgGroupId = @rOrgGroupId and DM.Id = @userSourceId
		END
	
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 95) -- As per EmployeeId
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			VAlues( @lNextNumber, 95 ,@userSourceId,@rAssigneeToId )
		
		END
	END
	IF(@rAssigneeToId =2)
	BEGIN
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2021)
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select @lNextNumber,
			2001 ,
			SA.Id,
			@rAssigneeToId 
			FROM  [sStudent].[tAcademic] SA 
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SA.OrgId = OM.Id 
			WHERE   OM.OrgGroupId = @rOrgGroupId and OM.Id = @userSourceId
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2017)
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select distinct @lNextNumber,
			2001 ,
			SA.Id 
			,@rAssigneeToId
			FROM
			 [sStudent].[tAcademic] SA 
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SA.OrgId = OM.Id
			INNER JOIN [sSetup].[tClassMaster] CM ON SA.ClassId = CM.Id
			INNER JOIN [sSetup].[tDepartmentMaster] DM ON DM.Id = CM.DepartmentId
			WHERE   OM.OrgGroupId = @rOrgGroupId and DM.Id = @userSourceId
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2016)
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select distinct @lNextNumber,
			2001 ,
			SA.Id 
			,@rAssigneeToId
			FROM  
			[sStudent].[tAcademic] SA   
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SA.OrgId = OM.Id
			INNER JOIN [sSetup].[tClassMaster] CM ON SA.ClassId = CM.Id		
			WHERE   OM.OrgGroupId = @rOrgGroupId and CM.Id = @userSourceId
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2005)
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select distinct @lNextNumber,
			2001 ,
			SA.Id 
			,@rAssigneeToId
			FROM  
			[sStudent].[tAcademic] SA  
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SA.OrgId = OM.Id
			INNER JOIN [sSetup].[tClassMaster] CM ON SA.ClassId = CM.Id
			INNER JOIN [sSetup].[tDivisionMaster] DM ON DM.ClassId = CM.Id		
			WHERE   OM.OrgGroupId = @rOrgGroupId and DM.Id = @userSourceId
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2001)
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			VAlues( @lNextNumber, 2001 ,@userSourceId,@rAssigneeToId )
		
		END
	END
	IF(@rAssigneeToId = 3) ---check AssigneeToId
	BEGIN
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2021) --For Organization
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select @lNextNumber,
			SU.SourceTypeId ,
			SU.SourceId
			,@rAssigneeToId 
			FROM  [sSecurity].[tUser] SU 
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SU.OrgId = OM.Id  and SU.SourceTypeId = 95
			WHERE   OM.OrgGroupId = @rOrgGroupId and OM.Id = @userSourceId
		END
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 2017) --For Department wise
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			Select distinct @lNextNumber,
			SU.SourceTypeId ,
			SU.SourceId 
			,@rAssigneeToId
			FROM  [sSecurity].[tUser] SU
			INNER JOIN sHrm.tEmployeeMaster EM ON SU.SourceId = EM.Id and SU.SourceTypeId = 95
			INNER JOIN [sHrm].[tEmployeeJobDetail] EJD ON EJD.EmployeeId = EM.Id  
			INNER JOIN [sSetup].[tOrganizationMaster] OM ON SU.OrgId = OM.Id		
			INNER JOIN [sSetup].[tDepartmentMaster] DM ON DM.Id = EJD.OrganizationDepartmentId
			WHERE   OM.OrgGroupId = @rOrgGroupId and DM.Id = @userSourceId
		END
	
		IF((SELECT UserSourceTypeId FROM @tChatGroupScope WHERE Id = @count) = 95) -- As per EmployeeId
		BEGIN

			INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
			VAlues( @lNextNumber, 95 ,@userSourceId,@rAssigneeToId )
		
		END
	END
	SET @count = @count + 1 
End
--Adding GroupCreator Into Broadcast/group

	IF Not Exists (Select 1 from [sCommunication].[tChatGroupScope] WHERE ChatGroupId = @lNextNumber and MemberSourceTypeId = (SELECT SourceTypeId FROM [sSecurity].[tUser] WHERE Id = @rUserId) and MemberSourceId = (SELECT SourceId FROM [sSecurity].[tUser] WHERE Id = @rUserId) )
	BEGIN
	INSERT INTO [sCommunication].[tChatGroupScope](ChatGroupId,MemberSourceTypeId, MemberSourceId,AssigneeToId)
	VALUES(
	@lNextNumber,
	(SELECT (CASE WHEN (SourceTypeId = 2003)THEN 2001 ELSE 95 END) FROM [sSecurity].[tUser] WHERE Id = @rUserId) ,
	(SELECT SourceId FROM [sSecurity].[tUser] WHERE Id = @rUserId),@rAssigneeToId 
	)
	END

	--inserting Chat Message to Chat table
	INSERT INTO [sCommunication].[tChat] (ToSourceTypeId,ToSourceId,FromSourceTypeId,FromSourceId,ChatDetail,ChatStatusId,CreatedUserId,CreatedDateTime) 
	VALUES(2035,@lNextNumber,(SELECT (CASE WHEN (SourceTypeId = 2003)THEN 2001 ELSE 95 END) FROM [sSecurity].[tUser] WHERE Id = @rUserId),
	(SELECT SourceId FROM [sSecurity].[tUser] WHERE Id = @rUserId),@rChatDetail,2,@rUserId,GETDATE())
   
	SELECT @lNextNumber AS Result
	RETURN   
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
--exec [sCommunication].[pChatDetailsGet] @rOrgGroupId=1101,@rUserSourceId = 1101000000274,@rUserSourceTypeId = 95,@rSyncedDateTime ='2020-06-22 17:46:30.920'
CREATE OR ALTER PROCEDURE [sCommunication].[pChatDetailsGet]
	 
	 @rOrgGroupId nvarchar(10)='',
	 @rUserSourceId nvarchar(20)='',
	 @rUserSourceTypeId nvarchar(5)= '',
	 @rSyncedDateTime nvarchar(25) = ''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	--SET @rSyncedDateTime = convert(varchar, @rSyncedDateTime, 121);
	IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id =CONVERT(int,@rOrgGroupId))
	BEGIN
		SELECT -201 AS Result
		RETURN
	END
	--IF NOT EXISTS (SELECT 1 FROM [sSecurity].[tUser] WHERE SourceId =CONVERT(bigint,@rUserSourceId))
	--BEGIN
	--	SELECT -202 AS Result
	--	RETURN
	--END
	 
	DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	IF(@rUserSourceTypeId = 2001)
	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 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
	    WHERE A.Id = @rUserSourceId
	SELECT *
	FROM(
	SELECT 
	DISTINCT
		OGM.Id,
		'' as ProfileImage,
		CCGM.Id as GroupId,
		CCGM.Title as ChatGroupName,
		CCGM.ChatTypeId as ChatGroupTypeId,
		
		(SELECT Top 1 (Case when (CC.ChatDetail != Null or CC.ChatDetail != '') then CC.ChatDetail else 
		(Case WHEN ( Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='jpg' Or 
		Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='png'  OR
		Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='jpeg') Then 'Photo' else 
		(CASE WHEN (Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mp4' OR 
		Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mp4') THEN 'Video' else
		(CASE WHEN (Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mp3') THEN 'Audio' else
		'Document'
		end)end )end)end)
		 FROM [sCommunication].[tChat] cc where cc.ToSourceId = CCGM.Id AND (cc.ChatStatusId =
		  (CASE WHEN (CCGM.ChatAdminEmployeeId != @rUserSourceId) THEN 2  END) OR 
		  cc.ChatStatusId !=
		  (CASE WHEN (CCGM.ChatAdminEmployeeId = @rUserSourceId) THEN 3  END) OR
		  cc.ChatStatusId !=
		  (CASE WHEN (cc.FromSourceId = @rUserSourceId) THEN 3  END)
		  )
		  Order by AutoId DESC) as LastMessage,

		(SELECT Top 1 cc.CreatedDateTime FrOM [sCommunication].[tChat] cc where cc.ToSourceId = CCGM.Id AND (cc.ChatStatusId =
		  (CASE WHEN (CCGM.ChatAdminEmployeeId != @rUserSourceId) THEN 2  END) OR 
		  cc.ChatStatusId !=
		  (CASE WHEN (CCGM.ChatAdminEmployeeId = @rUserSourceId) THEN 3  END) OR
		  cc.ChatStatusId !=
		  (CASE WHEN (cc.FromSourceId = @rUserSourceId) THEN 3  END)
		  ) Order by AutoId DESC )as Time,

		(SELECT Count(sCC.AutoId) FROM [sCommunication].[tChat] as sCC WHERE sCC.CreatedDateTime >= @rSyncedDateTime and sCC.CreatedDateTime <= GetDate() and (sCC.ToSourceId = CCGM.Id AND sCC.FromSourceId <> @rUserSourceId) AND (sCC.ChatStatusId =
		  (CASE WHEN (CCGM.ChatAdminEmployeeId != @rUserSourceId) THEN 2  END) OR 
		  sCC.ChatStatusId !=
		  (CASE WHEN (CCGM.ChatAdminEmployeeId = @rUserSourceId) THEN 3  END) OR
		  sCC.ChatStatusId !=
		  (CASE WHEN (sCC.FromSourceId = @rUserSourceId) THEN 3  END)
		  ) )  as MessageCount,
		  CC.ToSourceTypeId,
		  CC.ToSourceId
	FROM
		[sCommunication].[tChatGroupScope] CCGS
		INNER JOIN [sCommunication].[tChatGroupMaster] CCGM ON CCGS.ChatGroupId = CCGM.Id		
		LEFT JOIN [sCommunication].[tChat] CC ON CC.ToSourceId = 	CCGM.Id	
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = CCGM.OrgGroupId
		--INNER JOIN [sStudent].[tAcademic] SA ON SA.Id =CCGS.MemberSourceId 
	WHERE 
		OGM.Id = CONVERT(int,@rOrgGroupId)
		AND
		(((CCGS.MemberSourceTypeId = 2021 AND CCGS.MemberSourceId =@lOrgId) OR
		(CCGS.MemberSourceTypeId = 2017 AND CCGS.MemberSourceId =@lDepartmentId) OR
		(CCGS.MemberSourceTypeId = 2016 AND CCGS.MemberSourceId =@lClassId) OR
		(CCGS.MemberSourceTypeId = 2005 AND CCGS.MemberSourceId =@lDivisionId) OR
		(CCGS.MemberSourceTypeId = 2003 AND CCGS.MemberSourceId =@lStudentId) OR
		(CCGS.MemberSourceTypeId = 2001 AND CCGS.MemberSourceId =@lAcademicId) AND (CCGS.AssigneeToId = 2 OR CCGS.AssigneeToId = 1)) OR (CCGM.ChatAdminEmployeeId = @rUserSourceId))
		
		Group By OGM.Id,CCGM.Id,CCGM.Title,CCGM.ChatTypeId,CC.ChatStatusId,CCGM.ChatAdminEmployeeId,CC.ToSourceTypeId,CC.ToSourceId
	UNION ALL
	SELECT
	Distinct 
		OM.OrgGroupId as Id,
		'' as ProfileImage,
		0 as GroupId,
		--(Select (Firstname + ' ' + MiddleName +' ' + LastName) From					
		--			[sStudent].[tStudentMaster] SM Where  SM.Id = SA.StudentId) as ChatGroupName,
		(Case When (@rUserSourceId = CC.ToSourceId) then 
		CASE WHEN CC.FromSourceTypeId = 95 THEN (Select HEM.Firstname + ' ' + HEM.MiddleName +' ' + HEM.LastName from [sHrm].[tEmployeeMaster] HEM 
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = HEM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId where HEM.Id = CC.FromSourceId) 
		WHEN CC.FromSourceTypeId = 2001 THEN (Select HEM.Firstname + ' ' + HEM.MiddleName +' ' + HEM.LastName from [sStudent].[tStudentMaster] HEM
		INNER JOIN [sStudent].[tAcademic] SA ON SA.StudentId =HEM.Id 
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = HEM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId where SA.Id = CC.FromSourceId) END
		Else 
		CASE WHEN CC.ToSourceTypeId = 95 THEN 
		(Select HEM.Firstname + ' ' + HEM.MiddleName +' ' + HEM.LastName from [sHrm].[tEmployeeMaster] HEM 
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = HEM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId where HEM.Id = CC.ToSourceId)
		WHEN CC.ToSourceTypeId = 2001 THEN
		(Select HEM.Firstname + ' ' + HEM.MiddleName +' ' + HEM.LastName from [sStudent].[tStudentMaster] HEM
		INNER JOIN [sStudent].[tAcademic] SA ON SA.StudentId =HEM.Id 
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = HEM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId where SA.Id = CC.ToSourceId)END
		 END)  as ChatGroupName,
		2 as ChatGroupTypeId,
		
		(SELECT Top 1 (Case when (tcc.ChatDetail != Null or tcc.ChatDetail != '') then tcc.ChatDetail else 
		(Case WHEN ( Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='jpg' Or 
		Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='png'  OR
		Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='jpeg') Then 'Photo' else 
		(CASE WHEN (Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='mp4' OR 
		Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='mp4') THEN 'Video' else
		(CASE WHEN (Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='mp3') THEN 'Audio' else
		'Document'
		end)end )end)end)
		 FROM [sCommunication].[tChat] tcc where ((tcc.ToSourceId = CC.ToSourceId AND tcc.FromSourceId = CC.FromSourceId) OR (tcc.ToSourceId = CC.FromSourceId AND tcc.FromSourceId = CC.ToSourceId)) Order by AutoId DESC) as LastMessage,

		(SELECT Top 1 tcc.CreatedDateTime FrOM [sCommunication].[tChat] tcc where ((tcc.ToSourceId = CC.ToSourceId AND tcc.FromSourceId = CC.FromSourceId) OR (tcc.ToSourceId = CC.FromSourceId AND tcc.FromSourceId = CC.ToSourceId)) Order by AutoId DESC )as Time,
		(SELECT Count(sCC.AutoId) FROM [sCommunication].[tChat] as sCC WHERE sCC.CreatedDateTime >= @rSyncedDateTime and sCC.CreatedDateTime <= GetDate() and ((sCC.ToSourceId = CC.ToSourceId AND sCC.FromSourceId = CC.FromSourceId) OR (sCC.ToSourceId = CC.FromSourceId AND sCC.FromSourceId = CC.ToSourceId))  and (sCC.FromSourceId <> @rUserSourceId) ) as MessageCount,
		(Case WHEN (@rUserSourceId = CC.ToSourceId) then CC.FromSourceTypeId else CC.ToSourceTypeId END) as ToSourceTypeId,
		(Case WHEN (@rUserSourceId = CC.ToSourceId) then CC.FromSourceId else CC.ToSourceId END) as ToSourceId
	From
		[sCommunication].[tChat] CC
		LEFT JOIN [sStudent].[tAcademic] SA ON SA.Id =CC.ToSourceId
		LEFT JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = SA.OrgId
		LEFT JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
		Where
		OGM.Id  = @rOrgGroupId AND
		((FromSourceId =CONVERT(bigint,@rUserSourceId) AND FromSourceTypeId = CONVERT(int,@rUserSourceTypeId) ) OR 
		( ToSourceId =CONVERT(bigint,@rUserSourceId) AND ToSourceTypeId = CONVERT(int,@rUserSourceTypeId))) and
		ToSourceTypeId != 2035
	--Group By OM.OrgGroupId,CC.ToSourceId,SA.StudentId,CC.ToSourceTypeId,CC.ToSourceId,CC.FromSourceTypeId,CC.FromSourceId
	) A
	ORDER BY A.Time DESC
	END

	IF(@rUserSourceTypeId = 95)
	BEGIN
--UNION ALL
SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
	
	SELECT * 
	FROM
	(
	SELECT 
	DISTINCT
		OGM.Id,
		'' as ProfileImage,
		CCGM.Id as GroupId,
		CCGM.Title as ChatGroupName,
		CCGM.ChatTypeId as ChatGroupTypeId,
		
		(SELECT Top 1 (Case when (CC.ChatDetail != Null or CC.ChatDetail != '') then CC.ChatDetail else 
		(Case WHEN ( Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='jpg' Or 
		Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='png'  OR
		Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='jpeg') Then 'Photo' else 
		(CASE WHEN (Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mp4' OR 
		Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mp4') THEN 'Video' else
		(CASE WHEN (Lower(reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1))) ='mp3') THEN 'Audio' else
		'Document'
		end)end )end)end)
		FROM [sCommunication].[tChat] cc where cc.ToSourceId = CCGM.Id AND (cc.ChatStatusId =
		  (CASE WHEN (CCGM.ChatAdminEmployeeId != @rUserSourceId) THEN 2  END) OR 
		  cc.ChatStatusId !=
		  (CASE WHEN (CCGM.ChatAdminEmployeeId = @rUserSourceId) THEN 3  END) OR
		  cc.ChatStatusId !=
		  (CASE WHEN (cc.FromSourceId = @rUserSourceId) THEN 3  END)
		  )
		  Order by AutoId DESC) as LastMessage,

		(SELECT Top 1 cc.CreatedDateTime FrOM [sCommunication].[tChat] cc where cc.ToSourceId = CCGM.Id AND (cc.ChatStatusId =
		  (CASE WHEN (CCGM.ChatAdminEmployeeId != @rUserSourceId) THEN 2  END) OR 
		  cc.ChatStatusId !=
		  (CASE WHEN (CCGM.ChatAdminEmployeeId = @rUserSourceId) THEN 3  END) OR
		  cc.ChatStatusId !=
		  (CASE WHEN (cc.FromSourceId = @rUserSourceId) THEN 3  END)
		  ) Order by AutoId DESC )as Time,

		(SELECT Count(sCC.AutoId) FROM [sCommunication].[tChat] as sCC WHERE sCC.CreatedDateTime >= @rSyncedDateTime  and sCC.CreatedDateTime <= GetDate() and (sCC.ToSourceId = CCGM.Id AND sCC.FromSourceId <> @rUserSourceId) AND (sCC.ChatStatusId =
		  (CASE WHEN (CCGM.ChatAdminEmployeeId != @rUserSourceId) THEN 2  END) OR 
		  sCC.ChatStatusId !=
		  (CASE WHEN (CCGM.ChatAdminEmployeeId = @rUserSourceId) THEN 3  END) OR
		  sCC.ChatStatusId !=
		  (CASE WHEN (sCC.FromSourceId = @rUserSourceId) THEN 3  END)
		  ) )  as MessageCount,
		  '2035' as ToSourceTypeId,
		  CCGM.Id as ToSourceId
		--CCGC.UpdatedDateTime as LastMessageTime
	FROM
		[sCommunication].[tChatGroupScope] CCGS
		INNER JOIN [sCommunication].[tChatGroupMaster] CCGM ON CCGS.ChatGroupId = CCGM.Id		
		--LEFT JOIN [sCommunication].[tChat] CC ON CC.ToSourceId = 	CCGM.Id		
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = CCGM.OrgGroupId
		--INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id =CCGS.MemberSourceId
	WHERE 
		OGM.Id = CONVERT(int,@rOrgGroupId)
		AND
		(((CCGS.MemberSourceTypeId = 2021 AND CCGS.MemberSourceId =@lOrgId) OR
            (CCGS.MemberSourceTypeId = 2017 AND CCGS.MemberSourceId =@lDepartmentId) OR
            (CCGS.MemberSourceTypeId = 95 AND CCGS.MemberSourceId =@lEmployeeId ) AND (CCGS.AssigneeToId=3 OR CCGS.AssigneeToId=1)) OR (CCGM.ChatAdminEmployeeId = @rUserSourceId)) 
		Group By OGM.Id,CCGM.Id,CCGM.Title,CCGM.ChatTypeId,CCGM.ChatAdminEmployeeId
	
UNION ALL
	SELECT
	Distinct 
		@rOrgGroupId as Id,
		'' as ProfileImage,
		0 as GroupId,
		--(EM.Firstname + ' ' + EM.MiddleName +' ' + EM.LastName) as ChatGroupName,
		(Case When (@rUserSourceId = CC.ToSourceId) then 
		CASE WHEN CC.FromSourceTypeId = 95 THEN (Select HEM.Firstname + ' ' + HEM.MiddleName +' ' + HEM.LastName from [sHrm].[tEmployeeMaster] HEM 
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = HEM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId where HEM.Id = CC.FromSourceId) 
		WHEN CC.FromSourceTypeId = 2001 THEN (Select HEM.Firstname + ' ' + HEM.MiddleName +' ' + HEM.LastName from [sStudent].[tStudentMaster] HEM
		INNER JOIN [sStudent].[tAcademic] SA ON SA.StudentId =HEM.Id 
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = HEM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId where SA.Id = CC.FromSourceId) END
		Else 
		CASE WHEN CC.ToSourceTypeId = 95 THEN 
		(Select HEM.Firstname + ' ' + HEM.MiddleName +' ' + HEM.LastName from [sHrm].[tEmployeeMaster] HEM 
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = HEM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId where HEM.Id = CC.ToSourceId)
		WHEN CC.ToSourceTypeId = 2001 THEN
		(Select HEM.Firstname + ' ' + HEM.MiddleName +' ' + HEM.LastName from [sStudent].[tStudentMaster] HEM
		INNER JOIN [sStudent].[tAcademic] SA ON SA.StudentId =HEM.Id 
		INNER JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = HEM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId where SA.Id = CC.ToSourceId)END
		 END)  as ChatGroupName,

		2 as ChatGroupTypeId,
		
		(SELECT Top 1 (Case when (tcc.ChatDetail != Null or tcc.ChatDetail != '') then tcc.ChatDetail else 
		(Case WHEN ( Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='jpg' Or 
		Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='png'  OR
		Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='jpeg') Then 'Photo' else 
		(CASE WHEN (Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='mp4' OR 
		Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='mp4') THEN 'Video' else
		(CASE WHEN (Lower(reverse(left(reverse(tcc.ContentPath),charindex('.',reverse(tcc.ContentPath))-1))) ='mp3') THEN 'Audio' else
		'Document'
		end)end )end)end)
		 FROM [sCommunication].[tChat] tcc where ((tcc.ToSourceId = CC.ToSourceId AND tcc.FromSourceId = CC.FromSourceId) OR (tcc.ToSourceId = CC.FromSourceId AND tcc.FromSourceId = CC.ToSourceId)) Order by AutoId DESC) as LastMessage,

		(SELECT Top 1 tcc.CreatedDateTime FrOM [sCommunication].[tChat] tcc where ((tcc.ToSourceId = CC.ToSourceId AND tcc.FromSourceId = CC.FromSourceId) OR (tcc.ToSourceId = CC.FromSourceId AND tcc.FromSourceId = CC.ToSourceId)) Order by AutoId DESC )as Time,
		(SELECT Count(sCC.AutoId) FROM [sCommunication].[tChat] as sCC WHERE sCC.CreatedDateTime >= @rSyncedDateTime and sCC.CreatedDateTime <= GetDate() and ((sCC.ToSourceId = CC.ToSourceId AND sCC.FromSourceId = CC.FromSourceId) OR (sCC.ToSourceId = CC.FromSourceId AND sCC.FromSourceId = CC.ToSourceId))  and (sCC.FromSourceId <> @rUserSourceId)  )  as MessageCount,
		(Case WHEN (@rUserSourceId = CC.ToSourceId) then CC.FromSourceTypeId else CC.ToSourceTypeId END) as ToSourceTypeId,
		(Case WHEN (@rUserSourceId = CC.ToSourceId) then CC.FromSourceId else CC.ToSourceId END) as ToSourceId
		
	From
		[sCommunication].[tChat] CC
		LEFT JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id =CC.ToSourceId
		LEFT JOIN [sSetup].[tOrganizationMaster] OM ON OM.Id = EM.OrgId
		LEFT JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
		Where
		--OGM.Id  = @rOrgGroupId AND
		((FromSourceId =CONVERT(bigint,@rUserSourceId) AND FromSourceTypeId = CONVERT(int,@rUserSourceTypeId) ) OR 
		( ToSourceId =CONVERT(bigint,@rUserSourceId) AND ToSourceTypeId = CONVERT(int,@rUserSourceTypeId))) and
		ToSourceTypeId != 2035
		Group By CC.ToSourceId,CC.ToSourceTypeId,CC.ToSourceId,CC.FromSourceTypeId,CC.FromSourceId
	) A 
	ORDER By A.Time Desc
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[pChatGet]
	 
	 @rFromSourceTypeId int ,
	 @rFromSourceId bigint ,
	 @rToSourceTypeId int,
	 @rToSourceId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF(@rToSourceTypeId = 2035)
	BEGIN
		 IF EXISTS(SELECT 1 FROM sCommunication.tChatGroupMaster WHERE Id = @rToSourceId AND ChatAdminEmployeeId = @rFromSourceId)
	   BEGIN
			SELECT
				CCGM.Title as Title,
				ISNULL(CC.ChatDetail,'') As ChatDetail,
				ISNULL(CC.ContentPath,'') As ContentPath,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
				FromSourceId,
				FromSourceTypeId,
				@rFromSourceId as RequestedUserId,
				CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2001 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE AcademicId = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
				CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
				ChatStatusId,
				IsDisplayOnApproval,
				AutoId as Id,
				CCGM.ChatAdminEmployeeId

			FROM
				[sCommunication].[tChat] CC 	
				INNER JOIN [sCommunication].[tChatGroupMaster] CCGM ON CC.ToSourceId = CCGM.Id		
			WHERE 
		
				CC.ToSourceId = @rToSourceId
				AND CC.ToSourceTypeId = @rToSourceTypeId
			Order By CC.CreatedDateTime asc
		END
		ELSE
		BEGIN
			SELECT 
			*
			FROM
			(
			SELECT
				CCGM.Title as Title,
				ISNULL(CC.ChatDetail,'') As ChatDetail,
				ISNULL(CC.ContentPath,'') As ContentPath,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
				FromSourceId,
				FromSourceTypeId,
				@rFromSourceId as RequestedUserId,
				CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2001 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE AcademicId = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
				CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
				ChatStatusId,
				IsDisplayOnApproval,
				AutoId as Id,
				CCGM.ChatAdminEmployeeId,
				CC.CreatedDateTime
			FROM
				[sCommunication].[tChat] CC 	
				INNER JOIN [sCommunication].[tChatGroupMaster] CCGM ON CC.ToSourceId = CCGM.Id		
			WHERE 
				CC.ToSourceId = @rToSourceId
				AND CC.ToSourceTypeId = @rToSourceTypeId AND CC.ChatStatusId = 2

			UNION 

			SELECT
				CCGM.Title as Title,
				ISNULL(CC.ChatDetail,'') As ChatDetail,
				ISNULL(CC.ContentPath,'') As ContentPath,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
				FromSourceId,
				FromSourceTypeId,
				@rFromSourceId as RequestedUserId,
				CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2001 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE AcademicId = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
				CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
				ChatStatusId,
				IsDisplayOnApproval,
				AutoId as Id,
				CCGM.ChatAdminEmployeeId,
				CC.CreatedDateTime
			FROM
				[sCommunication].[tChat] CC 	
				INNER JOIN [sCommunication].[tChatGroupMaster] CCGM ON CC.ToSourceId = CCGM.Id		
			WHERE 
				CC.ToSourceId = @rToSourceId
				AND CC.ToSourceTypeId = @rToSourceTypeId AND CC.FromSourceId = @rFromSourceId
			)A
			Order By A.CreatedDateTime asc
		END
	END
	ELSE IF(@rToSourceTypeId = 2036)
	BEGIN
		SELECT
				OL.Title as Title,
				ISNULL(CC.ChatDetail,'') As ChatDetail,
				ISNULL(CC.ContentPath,'') As ContentPath,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
				FromSourceId,
				FromSourceTypeId,
				@rFromSourceId as RequestedUserId,
				CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId) WHEN FromSourceTypeId = 2001 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE AcademicId = CC.FromSourceId)   WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
				CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
				ChatStatusId,
				AutoId as Id

			FROM
				[sCommunication].[tChat] CC 	
				INNER JOIN [sAcademic].[tOnlineLearning] OL ON CC.ToSourceId = OL.Id		
			WHERE 
				CC.ToSourceId = @rToSourceId AND CC.ToSourceTypeId = @rToSourceTypeId 
			Order By CC.CreatedDateTime asc
	END
	ELSE IF(@rToSourceTypeId = 0)
	BEGIN
	  SELECT * 
	  FROM(
		SELECT
				'Admin' as Title,
				ISNULL(CC.ChatDetail,'') As ChatDetail,
				ISNULL(CC.ContentPath,'') As ContentPath,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
				FromSourceId,
				FromSourceTypeId,
				@rFromSourceId as RequestedUserId,
				CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2001 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE AcademicId = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) WHEN FromSourceTypeId = 0 THEN 'Admin' ELSE '' END AS SenderName,
				CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
				ChatStatusId,
				AutoId as Id,
				CC.CreatedDateTime
			FROM
				[sCommunication].[tChat] CC 	
			WHERE 
				CC.ToSourceId = @rToSourceId AND CC.ToSourceTypeId = @rToSourceTypeId AND CC.FromSourceId = @rFromSourceId AND CC.FromSourceTypeId = @rFromSourceTypeId
			 
		UNION

		SELECT
				'Admin' as Title,
				ISNULL(CC.ChatDetail,'') As ChatDetail,
				ISNULL(CC.ContentPath,'') As ContentPath,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
				FromSourceId,
				FromSourceTypeId,
				@rFromSourceId as RequestedUserId,
				CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2001 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE AcademicId = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) WHEN FromSourceTypeId =  0 THEN 'Admin' ELSE '' END AS SenderName,
				CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
				ChatStatusId,
				AutoId as Id,
				CC.CreatedDateTime

			FROM
				[sCommunication].[tChat] CC 	
			WHERE 
				CC.ToSourceId = @rFromSourceId AND CC.ToSourceTypeId = @rFromSourceTypeId AND CC.FromSourceId = @rToSourceId AND CC.FromSourceTypeId = @rToSourceTypeId
				)a
			Order By  a.CreatedDateTime asc
	END
	ELSE
	BEGIN
	SELECT * 
	FROM(
		SELECT
				CASE WHEN @rToSourceTypeId = 95 THEN (SELECT EmployeeName FROM [sHrm].[vExtEmployeeMaster] WHERE EmployeeId = @rToSourceId)  
				WHEN @rToSourceTypeId = 2001 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE AcademicId = @rToSourceId)
				WHEN @rToSourceTypeId = 2003 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE StudentId = @rToSourceId AND IsActiveBatch = 1) WHEN @rToSourceTypeId = 0 THEN 'Admin'  ELSE '' END AS Title,
				ISNULL(CC.ChatDetail,'') As ChatDetail,
				ISNULL(CC.ContentPath,'') As ContentPath,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
				FromSourceId,
				FromSourceTypeId,
				@rFromSourceId as RequestedUserId,
				CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId) WHEN FromSourceTypeId = 2001 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE AcademicId = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
				CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
				ChatStatusId,
				AutoId as Id,
				CC.CreatedDateTime 
			FROM
				[sCommunication].[tChat] CC 	
			WHERE 
				CC.ToSourceId = @rToSourceId AND CC.ToSourceTypeId = @rToSourceTypeId AND CC.FromSourceId = @rFromSourceId AND CC.FromSourceTypeId = @rFromSourceTypeId
		UNION
		SELECT
				CASE WHEN @rToSourceTypeId = 95 THEN (SELECT EmployeeName FROM [sHrm].[vExtEmployeeMaster] WHERE EmployeeId = @rToSourceId) 
				WHEN @rToSourceTypeId = 2001 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE AcademicId = @rToSourceId)
				 WHEN @rToSourceTypeId = 2003 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE StudentId = @rToSourceId AND IsActiveBatch = 1) WHEN @rToSourceTypeId = 0 THEN 'Admin'  ELSE '' END AS Title,
				ISNULL(CC.ChatDetail,'') As ChatDetail,
				ISNULL(CC.ContentPath,'') As ContentPath,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
				CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
				FromSourceId,
				FromSourceTypeId,
				@rFromSourceId as RequestedUserId,
				CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2001 THEN (SELECT Name FROM [sStudent].[vStudentAcademic] WHERE AcademicId = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
				CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
				ChatStatusId,
				AutoId as Id,
				CC.CreatedDateTime

			FROM
				[sCommunication].[tChat] CC 	
			WHERE 
				CC.ToSourceId = @rFromSourceId AND CC.ToSourceTypeId = @rFromSourceTypeId AND CC.FromSourceId = @rToSourceId AND CC.FromSourceTypeId = @rToSourceTypeId
			)a
			Order By a.CreatedDateTime asc
	END
	--ELSE IF(@rToSourceTypeId = 2003)
	--BEGIN
	--SELECT * 
	--FROM(
	--	SELECT
	--			SA.Name as Title,
	--			ISNULL(CC.ChatDetail,'') As ChatDetail,
	--			ISNULL(CC.ContentPath,'') As ContentPath,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
	--			FromSourceId,
	--			FromSourceTypeId,
	--			@rFromSourceId as RequestedUserId,
	--			CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
	--			CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
	--			ChatStatusId,
	--			AutoId as Id

	--		FROM
	--			[sCommunication].[tChat] CC 	
	--			INNER JOIN [sStudent].[vStudentAcademic] SA ON CC.ToSourceId = SA.StudentId		
	--		WHERE 
	--			CC.ToSourceId = @rToSourceId AND CC.ToSourceTypeId = @rToSourceTypeId AND CC.FromSourceId = @rFromSourceId AND CC.FromSourceTypeId = @rFromSourceTypeId
	--	UNION
	--	SELECT
	--			SA.Name as Title,
	--			ISNULL(CC.ChatDetail,'') As ChatDetail,
	--			ISNULL(CC.ContentPath,'') As ContentPath,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
	--			FromSourceId,
	--			FromSourceTypeId,
	--			@rFromSourceId as RequestedUserId,
	--			CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
	--			CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
	--			ChatStatusId,
	--			AutoId as Id

	--		FROM
	--			[sCommunication].[tChat] CC 	
	--			INNER JOIN [sStudent].[vStudentAcademic] SA ON CC.ToSourceId = SA.StudentId		
	--		WHERE 
	--			CC.ToSourceId = @rFromSourceId AND CC.ToSourceTypeId = @rFromSourceTypeId AND CC.FromSourceId = @rToSourceId AND CC.FromSourceTypeId = @rToSourceTypeId
	--		)a
	--		Order By a.DateTime asc
	--END
 -- ELSE IF(@rToSourceTypeId = 2001)
	--BEGIN
	--SELECT * 
	--FROM(
	--	SELECT
	--			SA.Name as Title,
	--			ISNULL(CC.ChatDetail,'') As ChatDetail,
	--			ISNULL(CC.ContentPath,'') As ContentPath,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
	--			FromSourceId,
	--			FromSourceTypeId,
	--			@rFromSourceId as RequestedUserId,
	--			CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
	--			CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
	--			ChatStatusId,
	--			AutoId as Id

	--		FROM
	--			[sCommunication].[tChat] CC 	
	--			INNER JOIN [sStudent].[vStudentAcademic] SA ON CC.FromSourceId = SA.AcademicId		
	--		WHERE 
	--			CC.ToSourceId = @rToSourceId AND CC.ToSourceTypeId = @rToSourceTypeId AND CC.FromSourceId = @rFromSourceId AND CC.FromSourceTypeId = @rFromSourceTypeId
	--	UNION
	--	SELECT
	--			SA.Name as Title,
	--			ISNULL(CC.ChatDetail,'') As ChatDetail,
	--			ISNULL(CC.ContentPath,'') As ContentPath,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
	--			FromSourceId,
	--			FromSourceTypeId,
	--			@rFromSourceId as RequestedUserId,
	--			CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
	--			CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
	--			ChatStatusId,
	--			AutoId as Id

	--		FROM
	--			[sCommunication].[tChat] CC 	
	--			INNER JOIN [sStudent].[vStudentAcademic] SA ON CC.FromSourceId = SA.AcademicId		
	--		WHERE 
	--			CC.ToSourceId = @rFromSourceId AND CC.ToSourceTypeId = @rFromSourceTypeId AND CC.FromSourceId = @rToSourceId AND CC.FromSourceTypeId = @rToSourceTypeId
	--	)a
	--	Order By a.DateTime asc
	--END
 -- ELSE IF(@rToSourceTypeId = 95)
	--BEGIN
	--  SELECT * 
	--  FROM(
	--	SELECT
	--			EM.EmployeeName as Title,
	--			ISNULL(CC.ChatDetail,'') As ChatDetail,
	--			ISNULL(CC.ContentPath,'') As ContentPath,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
	--			FromSourceId,
	--			FromSourceTypeId,
	--			@rFromSourceId as RequestedUserId,
	--			CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
	--			CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
	--			ChatStatusId,
	--			AutoId as Id

	--		FROM
	--			[sCommunication].[tChat] CC 	
	--			INNER JOIN [sHrm].[vExtEmployeeMaster] EM ON CC.ToSourceId = EM.EmployeeId		
	--		WHERE 
	--			CC.ToSourceId = @rToSourceId AND CC.ToSourceTypeId = @rToSourceTypeId AND CC.FromSourceId = @rFromSourceId AND CC.FromSourceTypeId = @rFromSourceTypeId
			 
	--	UNION

	--	SELECT
	--			EM.EmployeeName as Title,
	--			ISNULL(CC.ChatDetail,'') As ChatDetail,
	--			ISNULL(CC.ContentPath,'') As ContentPath,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE RIGHT(CC.ContentPath,Charindex('/', Reverse(CC.ContentPath))-1) END AS FileName,
	--			CASE WHEN ISNULL(CC.ContentPath,'') = '' THEN '' ELSE reverse(left(reverse(CC.ContentPath),charindex('.',reverse(CC.ContentPath))-1)) END AS Extension,
	--			FromSourceId,
	--			FromSourceTypeId,
	--			@rFromSourceId as RequestedUserId,
	--			CASE WHEN FromSourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = CC.FromSourceId)  WHEN FromSourceTypeId = 2003 THEN (SELECT FirstName FROM sStudent.tStudentMaster WHERE Id = CC.FromSourceId) ELSE '' END AS SenderName,
	--			CASE WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) THEN 'Today'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) WHEN CONVERT(NVARCHAR,CC.CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate()-1,105) THEN 'Yesterday'+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20), CC.CreatedDateTime, 100), 7)) ELSE  CONVERT(NVARCHAR,CC.CreatedDateTime) END AS DateTime,
	--			ChatStatusId,
	--			AutoId as Id

	--		FROM
	--			[sCommunication].[tChat] CC 	
	--			INNER JOIN [sHrm].[vExtEmployeeMaster] EM ON CC.FromSourceId = EM.EmployeeId		
	--		WHERE 
	--			CC.ToSourceId = @rFromSourceId AND CC.ToSourceTypeId = @rFromSourceTypeId AND CC.FromSourceId = @rToSourceId AND CC.FromSourceTypeId = @rToSourceTypeId
	--			)a
	--		Order By  a.DateTime asc
	--END
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pChatGroupDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			
			Delete from sCommunication.tChatGroupMaster where Id=@rId
			Delete from sCommunication.tChatGroupScope where ChatGroupId=@rId
			Delete from sCommunication.tChat WHERE ToSourceId = @rId AND ToSourceTypeId = 2035
		COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION		
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pChatGroupDetailGet]
	@rChatGroupId bigint,
	@rChatTypeId int,
	@rBatchId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF(@rChatTypeId = 2036)
BEGIN
	SELECT * FROM
	(
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = OLS.SourceId WHERE OLS.OnlineLearningId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2003
		UNION ALL
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OLS.SourceId WHERE OLS.OnlineLearningId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2001
		UNION ALL
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OLS.SourceId WHERE OLS.OnlineLearningId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND  OLS.SourceTypeId = 2017
		UNION ALL
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OLS.SourceId WHERE OLS.OnlineLearningId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2016
		UNION ALL
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OLS.SourceId WHERE OLS.OnlineLearningId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2005
		UNION ALL
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OLS.SourceId WHERE  OLS.OnlineLearningId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2021
		UNION ALL
		SELECT ISNULL(EM.DepartmentName+'-'+EM.FirstName+' '+EM.LastName,'')as MemberName,'95' as SourceTypeId,'' as DivisionOrder FROM sAcademic.tOnlineLearning OL INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId WHERE  OL.Id = @rChatGroupId AND EM.StatusId = 7
	) as A
	Order BY A.DivisionOrder
END
ELSE 
BEGIN
	SELECT * FROM 
	(
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sCommunication.tChatGroupScope CGS INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = CGS.MemberSourceId WHERE AssigneeToId IN (1,2) AND CGS.ChatGroupId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND CGS.MemberSourceTypeId = 2003
		UNION ALL
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sCommunication.tChatGroupScope CGS INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = CGS.MemberSourceId WHERE AssigneeToId IN (1,2) AND CGS.ChatGroupId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND CGS.MemberSourceTypeId = 2001
		UNION ALL
		SELECT ISNULL(EM.DepartmentName+'-'+EM.FirstName+' '+EM.LastName,'')as MemberName,'95' as SourceTypeId,'' as DivisionOrder FROM sCommunication.tChatGroupScope CGS INNER JOIN sCommon.vEmployeeMaster EM ON EM.Id = CGS.MemberSourceId WHERE CGS.AssigneeToId IN (1,3) AND CGS.ChatGroupId = @rChatGroupId AND EM.StatusId = 7 AND CGS.MemberSourceTypeId = 95
		UNION ALL
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sCommunication.tChatGroupScope CGS INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = CGS.MemberSourceId WHERE AssigneeToId IN (1,2) AND CGS.ChatGroupId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND  CGS.MemberSourceTypeId = 2017
		UNION ALL
		SELECT ISNULL(EM.DepartmentName+'-'+EM.FirstName+' '+EM.LastName,'')as MemberName,'95' as SourceTypeId,'' as DivisionOrder FROM sCommunication.tChatGroupScope CGS INNER JOIN sCommon.vEmployeeMaster EM ON EM.DepartmentId = CGS.MemberSourceId WHERE AssigneeToId IN (1,3) AND CGS.ChatGroupId = @rChatGroupId AND EM.StatusId = 7  AND CGS.MemberSourceTypeId = 2017
		UNION ALL
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sCommunication.tChatGroupScope CGS INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = CGS.MemberSourceId WHERE AssigneeToId IN (1,2) AND CGS.ChatGroupId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND CGS.MemberSourceTypeId = 2016
		UNION ALL
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sCommunication.tChatGroupScope CGS INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = CGS.MemberSourceId WHERE AssigneeToId IN (1,2) AND CGS.ChatGroupId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND CGS.MemberSourceTypeId = 2005
		UNION ALL
		SELECT ISNULL(SD.ClassName+'-'+SD.DivisionName+' '+SD.FirstName+' '+SD.LastName,'')as MemberName,'2003' as SourceTypeId,DivisionOrder FROM sCommunication.tChatGroupScope CGS INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = CGS.MemberSourceId WHERE AssigneeToId IN (1,2) AND CGS.ChatGroupId = @rChatGroupId AND BatchId=@rBatchId AND SD.StatusId = 1 AND CGS.MemberSourceTypeId = 2021
		UNION ALL
		SELECT ISNULL(EM.DepartmentName+'-'+EM.FirstName+' '+EM.LastName,'')as MemberName,'95' as SourceTypeId,'' as DivisionOrder FROM sCommunication.tChatGroupScope CGS INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.OrgId = CGS.MemberSourceId WHERE CGS.AssigneeToId IN (1,3) AND CGS.ChatGroupId = @rChatGroupId AND EM.StatusId = 7 AND CGS.MemberSourceTypeId = 2021
	) AS A
	Order BY A.DivisionOrder
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[pChatGroupListGet]
		@rOrgGroupBatchId int,
		@rUserSourceId bigint,
		@rUserSourceTypeId int,
		@rOrgGroupId int

  WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

if(@rUserSourceId = 0)
BEGIN
	  SELECT 
			CGM.Id,
			CGM.Title,
			'2035' as SourceTypeId,
			CGM.ChatTypeId,
			CGM.ChatAdminEmployeeId
		FROM 
			  sCommunication.tChatGroupMaster CGM  
	   WHERE 
			CGM.OrgGroupId = @rOrgGroupId AND ChatTypeId = 1

		UNION

		SELECT 
			CGM.Id,
			CGM.Title,
			'2035' as SourceTypeId,
			CGM.ChatTypeId,
			CGM.ChatAdminEmployeeId
		FROM 
			  sCommunication.tChatGroupMaster CGM  
	   WHERE 
			CGM.OrgGroupId = @rOrgGroupId AND ChatTypeId = 2

		--UNION


		--SELECT 
		--A.FromSourceId as Id,
		--CASE WHEN A.FromSourceTypeId = 2003 THEN (Select Name FROM [sStudent].[vStudentAcademic] Where StudentId = A.FromSourceId) 
		--	 WHEN A.FromSourceTypeId = 95 THEN (Select EmployeeName FROM [sHrm].[vExtEmployeeMaster] Where EmployeeId = A.FromSourceId) 
		--	 ELSE 'Admin' End as Title,
		--A.FromSourceTypeId as SourceTypeId,
		--'' as ChatTypeId
		--FROM
		--(SELECT 
		--	Distinct(FromSourceId),FromSourceTypeId
		--FROM 
		--	  sCommunication.tChat CC  
	 --  WHERE 
		--	ToSourceId = @rUserSourceId AND ToSourceTypeId = @rUserSourceTypeId) A

		--UNION


		--SELECT 
		--A.ToSourceId as Id,
		--CASE WHEN A.ToSourceTypeId = 2003 THEN (Select Name FROM [sStudent].[vStudentAcademic] SA INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id Where StudentId = A.ToSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId) 
		--	 WHEN A.ToSourceTypeId = 95 THEN (Select EmployeeName FROM [sHrm].[vExtEmployeeMaster] Where EmployeeId = A.ToSourceId) 
		--	 ELSE 'Admin' End as Title,
		--A.ToSourceTypeId as SourceTypeId,
		--'' as ChatTypeId
		--FROM
		--(SELECT 
		--	Distinct(ToSourceId),ToSourceTypeId
		--FROM 
		--	  sCommunication.tChat CC  
	 --  WHERE 
		--	FromSourceId = @rUserSourceId AND ToSourceTypeId != 2035 AND FromSourceTypeId = @rUserSourceTypeId) A
		
END
ELSE
BEGIN
	DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	IF @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN

		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId

	    SELECT 
			 CS.ChatGroupId as Id,
			 CGM.Title,
			 '2035' as SourceTypeId,
			 CGM.ChatTypeId,
			CGM.ChatAdminEmployeeId
		FROM 
			sCommunication.tChatGroupScope CS
			INNER JOIN  sCommunication.tChatGroupMaster CGM ON CGM.Id = CS.ChatGroupId
        WHERE 
			(((CS.MemberSourceTypeId = 2021 AND CS.MemberSourceId =@lOrgId) OR
            (CS.MemberSourceTypeId = 2017 AND CS.MemberSourceId =@lDepartmentId) OR
            (CS.MemberSourceTypeId = 95 AND CS.MemberSourceId =@lEmployeeId )) AND CS.AssigneeToId IN (1,3))
			AND CGM.OrgGroupId = @rOrgGroupId AND CGM.ChatTypeId = 1 

	   UNION
	    
		SELECT 
			 CS.ChatGroupId as Id,
			 CGM.Title,
			 '2035' as SourceTypeId,
			 CGM.ChatTypeId,
			CGM.ChatAdminEmployeeId
		FROM 
			sCommunication.tChatGroupScope CS
			INNER JOIN  sCommunication.tChatGroupMaster CGM ON CGM.Id = CS.ChatGroupId
        WHERE 
			(((CS.MemberSourceTypeId = 2021 AND CS.MemberSourceId =@lOrgId) OR
            (CS.MemberSourceTypeId = 2017 AND CS.MemberSourceId =@lDepartmentId) OR
            (CS.MemberSourceTypeId = 95 AND CS.MemberSourceId =@lEmployeeId )) AND CS.AssigneeToId IN (1,3))
			AND CGM.OrgGroupId = @rOrgGroupId AND CGM.ChatTypeId = 2

	   UNION


		SELECT 
		A.FromSourceId as Id,
		CASE WHEN A.FromSourceTypeId = 2003 THEN (Select ISNULL(Name,'')as Title FROM [sStudent].[vStudentAcademic] Where StudentId = A.FromSourceId AND IsActiveBatch = 1) 
			 WHEN A.FromSourceTypeId = 2001 THEN (Select ISNULL(Name,'')as Title FROM [sStudent].[vStudentAcademic] Where AcademicId = A.FromSourceId)
			 WHEN A.FromSourceTypeId = 95 THEN (Select ISNULL(EmployeeName,'')as Title FROM [sHrm].[vExtEmployeeMaster] Where EmployeeId = A.FromSourceId) 
			 ELSE 'Admin' End as Title,
		A.FromSourceTypeId as SourceTypeId,
		'' as ChatTypeId,
		0 as ChatAdminEmployeeId
		FROM
		(SELECT 
			Distinct(FromSourceId),FromSourceTypeId
		FROM 
			  sCommunication.tChat CC  
	   WHERE 
			ToSourceId = @rUserSourceId AND FromSourceTypeId != 2035 AND FromSourceTypeId != 2036 AND ToSourceTypeId = @rUserSourceTypeId) A

		UNION


		SELECT 
		A.ToSourceId as Id,
		CASE WHEN A.ToSourceTypeId = 2003 THEN (Select ISNULL(Name,'')as Title FROM [sStudent].[vStudentAcademic] Where StudentId = A.ToSourceId AND IsActiveBatch = 1) 
			 WHEN A.ToSourceTypeId = 2001 THEN (Select ISNULL(Name,'')as Title FROM [sStudent].[vStudentAcademic] Where AcademicId = A.ToSourceId)
			 WHEN A.ToSourceTypeId = 95 THEN (Select ISNULL(EmployeeName,'')as Title FROM [sHrm].[vExtEmployeeMaster] Where EmployeeId = A.ToSourceId) 
			 ELSE 'Admin' End as Title,
		A.ToSourceTypeId as SourceTypeId,
		'' as ChatTypeId,
		0 as ChatAdminEmployeeId
		FROM
		(SELECT 
			Distinct(ToSourceId),ToSourceTypeId
		FROM 
			  sCommunication.tChat CC  
	   WHERE 
			FromSourceId = @rUserSourceId AND ToSourceTypeId != 2035 AND ToSourceTypeId != 2036 AND FromSourceTypeId = @rUserSourceTypeId) A
         
	   UNION
	   
	   SELECT 
			OL.Id as Id,
			OL.Title as Title,
			'2036' as SourceTypeId,
			'' as ChatTypeId,
		0 as ChatAdminEmployeeId
		FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
		WHERE
			((OL.LearningTypeId = 2))
			AND (OL.TeacherEmployeeId = @rUserSourceId)
		
	END

	ELSE IF @rUserSourceTypeId = 2001

	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 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
	    WHERE A.Id = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

		SELECT 
			CS.ChatGroupId as Id,
			CGM.Title,
			'2035' as SourceTypeId,
			CGM.ChatTypeId,
			CGM.ChatAdminEmployeeId
		FROM 
			sCommunication.tChatGroupScope CS
			INNER JOIN  sCommunication.tChatGroupMaster CGM ON CGM.Id = CS.ChatGroupId
        WHERE 
			((CS.MemberSourceTypeId = 2021 AND CS.MemberSourceId =@lOrgId) OR
			(CS.MemberSourceTypeId = 2017 AND CS.MemberSourceId =@lDepartmentId) OR
			(CS.MemberSourceTypeId = 2016 AND CS.MemberSourceId =@lClassId) OR
			(CS.MemberSourceTypeId = 2005 AND CS.MemberSourceId =@lDivisionId) OR
			(CS.MemberSourceTypeId = 2003 AND CS.MemberSourceId =@lStudentId) OR
			(CS.MemberSourceTypeId = 2001 AND CS.MemberSourceId =@lAcademicId))
			AND ((CS.AssigneeToId IN (1,2))) AND CGM.OrgGroupId = @rOrgGroupId AND CGM.ChatTypeId = 1 

		UNION

		SELECT 
			CS.ChatGroupId as Id,
			CGM.Title,
			'2035' as SourceTypeId,
			CGM.ChatTypeId,
			CGM.ChatAdminEmployeeId
		FROM 
			sCommunication.tChatGroupScope CS
			INNER JOIN  sCommunication.tChatGroupMaster CGM ON CGM.Id = CS.ChatGroupId
        WHERE 
			((CS.MemberSourceTypeId = 2021 AND CS.MemberSourceId =@lOrgId) OR
			(CS.MemberSourceTypeId = 2017 AND CS.MemberSourceId =@lDepartmentId) OR
			(CS.MemberSourceTypeId = 2016 AND CS.MemberSourceId =@lClassId) OR
			(CS.MemberSourceTypeId = 2005 AND CS.MemberSourceId =@lDivisionId) OR
			(CS.MemberSourceTypeId = 2003 AND CS.MemberSourceId =@lStudentId) OR
			(CS.MemberSourceTypeId = 2001 AND CS.MemberSourceId =@lAcademicId))
			AND ((CS.AssigneeToId IN (1,2))) AND CGM.OrgGroupId = @rOrgGroupId AND CGM.ChatTypeId = 2

		UNION


		SELECT 
		A.FromSourceId as Id,
		CASE WHEN A.FromSourceTypeId = 2003 THEN (Select ISNULL(Name,'')as Title FROM [sStudent].[vStudentAcademic] Where StudentId = A.FromSourceId  AND IsActiveBatch = 1) 
			 WHEN A.FromSourceTypeId = 2001 THEN (Select ISNULL(Name,'')as Title FROM [sStudent].[vStudentAcademic] Where AcademicId = A.FromSourceId  AND IsActiveBatch = 1) 
			 WHEN A.FromSourceTypeId = 95 THEN (Select ISNULL(EmployeeName,'')as Title FROM [sHrm].[vExtEmployeeMaster] Where EmployeeId = A.FromSourceId) 
			 ELSE 'Admin' End as Title,
		A.FromSourceTypeId as SourceTypeId,
		'' as ChatTypeId,
		0 as ChatAdminEmployeeId
		FROM
		(SELECT 
			Distinct(FromSourceId),FromSourceTypeId
		FROM 
			  sCommunication.tChat CC  
	   WHERE 
			ToSourceId = @rUserSourceId AND FromSourceTypeId != 2035 AND FromSourceTypeId != 2036 AND ToSourceTypeId = @rUserSourceTypeId) A

		UNION


		SELECT 
		A.ToSourceId as Id,
		CASE WHEN A.ToSourceTypeId = 2003 THEN (Select ISNULL(Name,'')as Title FROM [sStudent].[vStudentAcademic] Where StudentId = A.ToSourceId  AND IsActiveBatch = 1) 
			 WHEN A.ToSourceTypeId = 2001 THEN (Select ISNULL(Name,'')as Title FROM [sStudent].[vStudentAcademic] Where AcademicId = A.ToSourceId  AND IsActiveBatch = 1) 
			 WHEN A.ToSourceTypeId = 95 THEN (Select ISNULL(EmployeeName,'')as Title FROM [sHrm].[vExtEmployeeMaster] Where EmployeeId = A.ToSourceId) 
			 ELSE 'Admin' End as Title,
		A.ToSourceTypeId as SourceTypeId,
		'' as ChatTypeId,
		0 as ChatAdminEmployeeId
		FROM
		(SELECT 
			Distinct(ToSourceId),ToSourceTypeId
		FROM 
			  sCommunication.tChat CC  
	   WHERE 
			FromSourceId = @rUserSourceId AND ToSourceTypeId != 2035 AND ToSourceTypeId != 2036  AND FromSourceTypeId = @rUserSourceTypeId) A

	   UNION

	   SELECT 
			OL.Id as Id,
			OL.Title as Title,
			'2036' as SourceTypeId,
			'' as ChatTypeId,
		0 as ChatAdminEmployeeId
	   FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
			WHERE (
			( 
			(OLS.SourceTypeId = 2021 AND OLS.SourceId =@lOrgId) 
			OR
			(OLS.SourceTypeId = 2017 AND OLS.SourceId =@lDepartmentId) OR
			(OLS.SourceTypeId = 2016 AND OLS.SourceId =@lClassId) OR
			(OLS.SourceTypeId = 2005 AND OLS.SourceId =@lDivisionId) OR
			(OLS.SourceTypeId = 2003 AND OLS.SourceId =@lStudentId) OR
			(OLS.SourceTypeId = 2001 AND OLS.SourceId =@lAcademicId)
				))
			) D
			ON D.OnlineLearningId= OL.Id
      
     
	END
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[pChatGroupMasterAdd]
	 
        @rId bigint = 0,
		@rChatTypeId int,
		@rTitle nvarchar(100) = '',
		@rIsDisplayOnApproval bit = 0,
		@rChatAdminEmployeeId bigint,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgGroupId int,
		@rOrgId int,
		@rTempChatGroupMasterId nvarchar(100)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tChatGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sCommunication.tChatGroupMaster
		(
			Id
           ,OrgGroupId
           ,ChatTypeId
           ,Title
           ,IsDisplayOnApproval
           ,ChatAdminEmployeeId
           ,CreatedUserId
           ,CreatedDateTime
            
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rChatTypeId,
			@rTitle,
			@rIsDisplayOnApproval, 
			@rChatAdminEmployeeId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result

		IF EXISTS (SELECT 1 FROM sCommunication.tTempChatGroupScope WHERE TempChatGroupId = @rTempChatGroupMasterId)
	   BEGIN
			INSERT INTO sCommunication.tChatGroupScope
			SELECT @lNextNumber,MemberSourceTypeId,MemberSourceId,AssigneeToId
			FROM sCommunication.tTempChatGroupScope 
			WHERE TempChatGroupId = @rTempChatGroupMasterId
		
			DELETE FROM sCommunication.tTempChatGroupScope WHERE TempChatGroupId = @rTempChatGroupMasterId
		--COMMIT TRANSACTION 
		END 
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tChatGroupMaster
	    SET
			 
        	Id = @rId
           ,OrgGroupId = @rOrgGroupId
           ,ChatTypeId = @rChatTypeId
           ,Title = @rTitle
           ,IsDisplayOnApproval = @rIsDisplayOnApproval
           ,ChatAdminEmployeeId = @rChatAdminEmployeeId
           ,CreatedUserId = @rCreatedUserId
           ,CreatedDateTime = sCommon.fGetDate()
        
	      WHERE Id = @rId
	      
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[pChatGroupMasterGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rChatTypeId int = 0,
	 @rOrgGroupId int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	if(@rId = 0)
	BEGIN 
	
	SELECT 
			CM.Id,
			CM.ChatTypeId,
			DM.Title as ChatType,
			CM.Title,
			CM.IsDisplayOnApproval as DisplayOnApproval,
			CM.CreatedDateTime
		    
	  FROM 
			sCommunication.tChatGroupMaster CM
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = CM.ChatTypeId AND DM.DataTypeId = 6
	  WHERE 
  
				((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((CM.ChatTypeId = @rChatTypeId) OR (@rChatTypeId = 0))
			AND ((CM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			 
	 ORDER BY
			CM.CreatedDateTime desc
		
	END
	ELSE
	BEGIN

	SELECT 
			 
			CM.ChatTypeId,
			CM.Title,
			CM.IsDisplayOnApproval as DisplayOnApproval
			 
	  FROM 
			sCommunication.tChatGroupMaster CM
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = CM.ChatTypeId AND DM.DataTypeId = 6
	  WHERE 
			CM.Id = @rId			
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pChatGroupScopeGet]
	 @rChatGroupId bigint
	  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON CS.MemberSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2021

			UNION ALL

			SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId  as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.MemberSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId 
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2017

			UNION ALL

			SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.MemberSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId 
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2016

			UNION ALL

			SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.MemberSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId 
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.MemberSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.MemberSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId 
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tChatGroupScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.MemberSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			 LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.ChatGroupId,
			 CS.MemberSourceTypeId as SourceTypeId,
			 CS.MemberSourceId as SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName ,
			  CS.AssigneeToId ,
             AM.Title As AssignedTo 
			
			FROM sCommunication.tChatGroupScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON CS.MemberSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			 LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE 
			CS.ChatGroupId=@rChatGroupId AND CS.MemberSourceTypeId=95


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 --exec [sCommunication].[pChatListCreate] 1101,9999000001785,2001,'hello...','',0,1101000000005,95,1101000000108
CREATE OR ALTER PROCEDURE [sCommunication].[pChatListCreate]
	 
	 @rOrgGroupId INT= 0,
	 @rFromSourceId BIGINT=0,
	 @rFromSourceTypeId INT= 0,
	-- @rCreatedDateTime nvarchar(10) = '',
	 @rChatDetail nvarchar(200) = '',
	 @rChatFile nvarchar(500) = '',
	 @rChatGroupId INT = 0,	
	 @rToSourceId BigInt = 0,
	 @rToSourceTypeId INT = 0, 
	 @rUserId BIGINT = 0,
	 @rChatTypeId INT = 0,
	 @rUserSourceTypeId INT = 2035,
	 @rChatStatusId INT = 2
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
          --- ChatGroupId is equalsTo ToSourceId in [sCommunication].[tChat] -----

	IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id =@rOrgGroupId)
	BEGIN
		SELECT -201 AS Result
		RETURN
	END
	--IF NOT EXISTS (SELECT 1 FROM [sSecurity].[tUser] WHERE SourceId =@rFromSourceId)
	--BEGIN
	--	SELECT -202 AS Result
	--	RETURN
	--END
	--IF NOT EXISTS (SELECT 1 FROM [sCommunication].[tChatGroupMaster] WHERE Id =(SELECT SourceId FROM [sSecurity].[tUser] WHERE Id =@rUserId))
	--BEGIN
	--	SELECT -203 AS Result
	--	RETURN
	--END
	DECLARE @lIsApprove bit = (SELECT IsDisplayOnApproval FROM sCommunication.tChatGroupMaster WHERE Id = @rChatGroupId);
	IF(@rChatGroupId != 0)
	BEGIN
	DECLARE @lGroupAdminId BigInt
	SELECT @lGroupAdminId=ChatAdminEmployeeId FROM sCommunication.tChatGroupMaster WHERE Id=@rChatGroupId

  IF(@lGroupAdminId = @rFromSourceId)
		BEGIN
	 IF(@rChatFile = '')
		BEGIN
		INSERT
		INTO
		[sCommunication].[tChat] (ToSourceTypeId,ToSourceId,FromSourceTypeId,FromSourceId,ChatDetail,ChatStatusId,ReferenceChatAutoId,CreatedUserId,CreatedDateTime)
		VALUES
		(
		@rUserSourceTypeId,
		@rChatGroupId,
		@rFromSourceTypeId, @rFromSourceId,@rChatDetail,2,0,@rUserId,sCommon.fGetDate()
		)
		SELECT 200 As Result
		RETURN
	    END
	 ELSE
	 BEGIN
		INSERT
		INTO
		[sCommunication].[tChat] (ToSourceTypeId,ToSourceId,FromSourceTypeId,FromSourceId,ContentPath,ChatStatusId,ReferenceChatAutoId,CreatedUserId,CreatedDateTime)
		VALUES
		(
		@rUserSourceTypeId,
		@rChatGroupId,
		@rFromSourceTypeId, @rFromSourceId,@rChatFile,2,0,@rUserId,sCommon.fGetDate()
		)
		SELECT 200 As Result
		RETURN
	 END
  END
  ELSE
  BEGIN
	IF(@rChatFile = '')
	  BEGIN
		INSERT
		INTO
		[sCommunication].[tChat] (ToSourceTypeId,ToSourceId,FromSourceTypeId,FromSourceId,ChatDetail,ChatStatusId,ReferenceChatAutoId,CreatedUserId,CreatedDateTime)
		VALUES
		(
		@rUserSourceTypeId,
		@rChatGroupId,
		@rFromSourceTypeId, @rFromSourceId,@rChatDetail,(CASE WHEN @lIsApprove = 1 THEN 1 ELSE @rChatStatusId END),0,@rUserId,sCommon.fGetDate()
		)
		SELECT 200 As Result
		RETURN
	 END
	 ELSE
	 BEGIN
		INSERT
		INTO
		[sCommunication].[tChat] (ToSourceTypeId,ToSourceId,FromSourceTypeId,FromSourceId,ContentPath,ChatStatusId,ReferenceChatAutoId,CreatedUserId,CreatedDateTime)
		VALUES
		(
		@rUserSourceTypeId,
		@rChatGroupId,
		@rFromSourceTypeId, @rFromSourceId,@rChatFile,(CASE WHEN @lIsApprove = 1 THEN 1 ELSE @rChatStatusId END),0,@rUserId,sCommon.fGetDate()
		)
		SELECT 200 As Result
		RETURN
	 END
  END
  END
  IF(@rToSourceId != 0 AND @rToSourceTypeId != 0)
  BEGIN
  IF(@rChatFile = '')
	  BEGIN
		INSERT
		INTO
		[sCommunication].[tChat] (ToSourceTypeId,ToSourceId,FromSourceTypeId,FromSourceId,ChatDetail,ChatStatusId,ReferenceChatAutoId,CreatedUserId,CreatedDateTime)
		VALUES
		(
		@rToSourceTypeId,
		@rToSourceId,
		@rFromSourceTypeId, @rFromSourceId,@rChatDetail,2,0,@rUserId,sCommon.fGetDate()
		)
		SELECT 200 As Result
		RETURN
	 END
	 ELSE
	 BEGIN
		INSERT
		INTO
		[sCommunication].[tChat] (ToSourceTypeId,ToSourceId,FromSourceTypeId,FromSourceId,ContentPath,ChatStatusId,ReferenceChatAutoId,CreatedUserId,CreatedDateTime)
		VALUES
		(
		@rToSourceTypeId,
		@rToSourceId,
		@rFromSourceTypeId, @rFromSourceId,@rChatFile,2,0,@rUserId,sCommon.fGetDate()
		)
		SELECT 200 As Result
		RETURN
	 END
  END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pCircularAdd]
	 
        @rId bigint,
		@rTitle nvarchar(200),
		@rRemark nvarchar(max),
		@rStartDate date,
		@rCreatedUserId bigint,
        @rOrgGroupId smallint,
        @rOrgGroupBatchId int,
        @rAssigneeId tinyint,
        @rCircularTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	--IF(@rId = 0)	
	--BEGIN
	--	--If Exists(select Id from sCommunication.tCircular where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
	--	--	BEGIN
	--	--	select -102 as Result
	--	--	RETURN
	--	--END 
	
	--	--If Exists(select Id from sCommunication.tCircular where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId)
	--	--	BEGIN
	--	--	select -103 as Result
	--	--	RETURN
	--	--END 
	--END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sCommunication.tCircular where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	--If  Exists(select Id from sCommunication.tCircular where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -103 as Result
	--	--	RETURN
	--	--End

	--END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			CircularTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rStartDate,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rAssigneeId,
			@rCircularTypeId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tCircular
	    SET
			Title=@rTitle,
			StartDate=@rStartDate,
			Remark=@rRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			AssigneeId=@rAssigneeId,
			CircularTypeId=@rCircularTypeId
	      
	      WHERE Id = @rId
	      
	      DELETE FROM sCommunication.tCircularView WHERE CircularId=@rId
	      
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularApprove]
	 
        @rId bigint,
		@rStatusId smallint,
		@rSourceId bigint
	


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	--If Exists(select CircularId from sCommunication.tCircularView where CircularId=@rCircularId AND UserId=@rUserId)
	--	BEGIN
	--		SELECT @rCircularId AS Result
	--		RETURN
	--  END 
	--ELSE
			BEGIN
				UPDATE sCommunication.tCircular
				SET
					StatusId=@rStatusId,
					ApprovedByEmployeeId=@rSourceId,
					UpdatedUserId=@rSourceId,
					UpdatedDateTime=getdate()
			      
				  WHERE Id = @rId
			      	
				  SELECT @rId AS Result
			
	         END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pCircularConsentAdd]
	 
        @rCircularId bigint,
		@rQuestionDescription nvarchar(max),
		@rAnsFieldTypeId int,
		@rAnsFieldList nvarchar(max)
	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO [sCommunication].[tCircularConsent]
		(
			CircularId,
			QuestionDescription,
			AnsFieldTypeId,
			AnsFieldList
		)
	VALUES
		(
			@rCircularId,
			@rQuestionDescription,
			@rAnsFieldTypeId,
			@rAnsFieldList
		)

	 
	 SELECT 1 AS Result

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pCircularConsentGet]
	 
        @rCircularId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT
		CC.Id AS CircularConsentId,
		ISNULL(CC.QuestionDescription,'')AS QuestionDescription,
		ISNULL(CC.AnsFieldTypeId,0)AS AnsFieldTypeId,
		ISNULL(CC.AnsFieldList,'') AS AnsFieldList
	FROM [sCommunication].[tCircularConsent] CC
	WHERE CircularId = @rCircularId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pCircularConsentResultAdd]
	 
		@rSourceId bigint,
        @rCircularConsentId bigint,
		@rCircularConsentAns nvarchar(max)
	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO [sCommunication].[tCircularConsentResult]
		(
			SourceId,
			CircularConsentId,
			CircularConsentAns
		)
	VALUES
		(
			@rSourceId,
			@rCircularConsentId,
			@rCircularConsentAns
		)

	 
	 SELECT 1 AS Result

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pCircularConsentResultGet]
	 	 
		 @rCircularId bigint,
	 	 @rOrgId int
	 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
 
			A.Code,
			A.Name,
			A.CircularConsentAns,
			A.ClassDept
	From 
			sCommunication.tCircular CR
			
			INNER JOIN (
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2003

			UNION ALL

			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2001
			
			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				vEC.DepartmentName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = CS.SourceId 
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = vEC.EmployeeId
			WHERE 
				vEC.StatusId = 7 
				AND CS.SourceTypeId = 95
				
			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DepartmentId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND  CS.SourceTypeId = 2017 AND CS.AssigneeToId = 2
				

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				vEC.DepartmentName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.DepartmentId = CS.SourceId 
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = vEC.EmployeeId
			WHERE 
				vEC.StatusId = 7 
				AND CS.SourceTypeId = 2017 AND CS.AssigneeToId = 3 

			UNION ALL	
		
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.ClassId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2016 AND CS.AssigneeToId = 2 
				

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND  CS.SourceTypeId = 2005 AND CS.AssigneeToId = 2 
				
			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				SC.ClassName + '-' + SC.DivisionName AS ClassDept
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.OrgId = CS.SourceId AND SC.IsActiveBatch = 1
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = SC.StudentId
				 
			WHERE 
				SC.StatusId = 1 
				AND CS.SourceTypeId = 2021 AND CS.AssigneeToId = 2 

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo,
				(CASE WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 1 THEN 'YES'
					 WHEN CC.AnsFieldTypeId = 1 AND  CCR.CircularConsentAns = 2 THEN 'NO'
					 ELSE CCR.CircularConsentAns END ) AS CircularConsentAns,
				vEC.DepartmentName AS ClassDept
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.OrgID = CS.SourceId 
				INNER JOIN sCommunication.tCircularConsent CC ON C.Id = CC.CircularId
				LEFT JOIN sCommunication.tCircularConsentResult CCR ON CC.Id = CCR.CircularConsentId AND CCR.SourceId = vEC.EmployeeId
			WHERE 
				vEC.StatusId = 7 
				AND CS.SourceTypeId = 2021 AND CS.AssigneeToId = 3 
			
		) as A ON A.CircularId = CR.Id 
	WHERE
			A.OrgId = @rOrgId AND A.CircularId = @rCircularId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rCircularId bigint =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lCircularTypeId int
  IF(@rType='Organization' AND @rOrgId=0 AND @rBatchId=0)
  BEGIN
	  SELECT
	      (SELECT COUNT(Id) FROM sCommunication.tCircular WHERE (OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)  AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) AND CONVERT(DATE,CreatedDateTime)= DATEADD(day, -1, convert(date, GETDATE()))) AS YesterdayCount,
		  (SELECT COUNT(Id) FROM sCommunication.tCircular WHERE (OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)  AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) AND CONVERT(DATE,CreatedDateTime)=CONVERT(DATE,GETDATE())) AS DailyCount,
		  (SELECT COUNT(Id) FROM sCommunication.tCircular WHERE (OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)  AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)AND CONVERT(DATE,CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())) AS WeeklyCount,
		  (SELECT COUNT(Id) FROM sCommunication.tCircular WHERE (OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)  AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0) AND CONVERT(DATE,CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()))  AS MonthlyCount
  END
  IF(@rType='Organization' AND @rOrgId!=0)
  BEGIN
  
         
         
        DECLARE @lYesterdayCircular TABLE (
		YesterdayCount int
		)
		
		INSERT INTO @lYesterdayCircular

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sSetup.tOrganizationMaster OM ON CS.SourceId=OM.Id
		WHERE CS.SourceTypeId=2021 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sSetup.tDepartmentMaster DM ON CS.SourceId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
		WHERE CS.SourceTypeId=2017 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN  sSetup.tClassMaster CM ON CS.SourceId=CM.Id
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
		WHERE CS.SourceTypeId=2016 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN   sSetup.tDivisionMaster DM ON CS.SourceId=DM.Id
		INNER JOIN 	sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
		WHERE CS.SourceTypeId=2005 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))


		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sStudent.tStudentMaster SM ON CS.SourceId=SM.Id
		INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
		INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
		WHERE CS.SourceTypeId=2003 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id	
		WHERE CS.SourceTypeId=2001 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sHrm.vEmployeeCommunication vEC ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
		INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id		
		WHERE CS.SourceTypeId=95 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))
		
		-----------
  
  
	    DECLARE @lDailyCircular TABLE (
		CircularCount int
		)
		
		INSERT INTO @lDailyCircular

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sSetup.tOrganizationMaster OM ON CS.SourceId=OM.Id
		WHERE CS.SourceTypeId=2021 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sSetup.tDepartmentMaster DM ON CS.SourceId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
		WHERE CS.SourceTypeId=2017 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN  sSetup.tClassMaster CM ON CS.SourceId=CM.Id
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
		WHERE CS.SourceTypeId=2016 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN   sSetup.tDivisionMaster DM ON CS.SourceId=DM.Id
		INNER JOIN 	sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
		WHERE CS.SourceTypeId=2005 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=CONVERT(DATE,GETDATE())


		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sStudent.tStudentMaster SM ON CS.SourceId=SM.Id
		INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
		INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
		WHERE CS.SourceTypeId=2003 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id	
		WHERE CS.SourceTypeId=2001 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sHrm.vEmployeeCommunication vEC ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
		INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id		
		WHERE CS.SourceTypeId=95 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime)=CONVERT(DATE,GETDATE())
		
		DECLARE @lWeeklyCircular TABLE (
		CircularCount int
		)
		
		INSERT INTO @lWeeklyCircular

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sSetup.tOrganizationMaster OM ON CS.SourceId=OM.Id
		WHERE CS.SourceTypeId=2021 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sSetup.tDepartmentMaster DM ON CS.SourceId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
		WHERE CS.SourceTypeId=2017 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN  sSetup.tClassMaster CM ON CS.SourceId=CM.Id
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
		WHERE CS.SourceTypeId=2016 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN   sSetup.tDivisionMaster DM ON CS.SourceId=DM.Id
		INNER JOIN 	sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
		WHERE CS.SourceTypeId=2005 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())


		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sStudent.tStudentMaster SM ON CS.SourceId=SM.Id
		INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
		INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
		WHERE CS.SourceTypeId=2003 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id	
		WHERE CS.SourceTypeId=2001 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sHrm.vEmployeeCommunication vEC ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
		INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id		
		WHERE CS.SourceTypeId=95 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
		
		DECLARE @lMonthlyCircular TABLE (
		CircularCount int
		)
		
		INSERT INTO @lMonthlyCircular

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sSetup.tOrganizationMaster OM ON CS.SourceId=OM.Id
		WHERE CS.SourceTypeId=2021 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sSetup.tDepartmentMaster DM ON CS.SourceId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
		WHERE CS.SourceTypeId=2017 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN  sSetup.tClassMaster CM ON CS.SourceId=CM.Id
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
		WHERE CS.SourceTypeId=2016 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN   sSetup.tDivisionMaster DM ON CS.SourceId=DM.Id
		INNER JOIN 	sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
		WHERE CS.SourceTypeId=2005 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())


		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sStudent.tStudentMaster SM ON CS.SourceId=SM.Id
		INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
		INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
		WHERE CS.SourceTypeId=2003 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id	
		WHERE CS.SourceTypeId=2001 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())

		UNION ALL

		SELECT COUNT(*) FROM sCommunication.tCircular C
		INNER JOIN sCommunication.tCircularScope CS ON C.Id = CS.CircularId
		INNER JOIN sHrm.vEmployeeCommunication vEC ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
		INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id		
		WHERE CS.SourceTypeId=95 AND OM.Id = @rOrgId AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		
		SELECT
			(SELECT SUM(YesterdayCount) FROM @lYesterdayCircular) AS YesterdayCount,
			(SELECT SUM(CircularCount) FROM @lDailyCircular) AS DailyCount,
			(SELECT SUM(CircularCount) FROM @lWeeklyCircular) AS WeeklyCount,
			(SELECT SUM(CircularCount) FROM @lMonthlyCircular) AS MonthlyCount
		
  END
   IF(@rType='CircularEvent' AND @rOrgId!=0)
  BEGIN
  SELECT @lCircularTypeId=Id FROM sCommunication.tCircularTypeMaster WHERE IsObsolete = 0 AND OrgGroupId=@rOrgGroupId AND Title = 'Circular'
   
	IF(@rDay=-1)
	BEGIN
		SELECT 
			ISNULL(C.Id,0) as CircularId,
			ISNULL(C.Title,'')AS CircularTitle,
			convert(varchar(20),ISNULL(C.StartDate,'01/01/0001'),103) AS StartDate,
			ISNULL(U.DisplayTitle,'') as CreatedUserName			
		 FROM 
			sCommunication.tCircular C
			INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
			INNER JOIN sSetup.vUserOrganization UO ON UO.OrgGroupId = C.OrgGroupId
			WHERE ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
			AND ((C.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND ((UO.Id = @rOrgId) OR (@rOrgId=0))
			AND ((C.CircularTypeId=@lCircularTypeId)OR (@lCircularTypeId=0))
			AND CONVERT(DATE,C.CreatedDateTime)=DATEADD(day, -1, convert(date, GETDATE()))
			GROUP BY C.Id,C.Title,C.StartDate,U.DisplayTitle
	END
	IF(@rDay=1)
	BEGIN
		SELECT 
			ISNULL(C.Id,0) as CircularId,
			ISNULL(C.Title,'')AS CircularTitle,
			convert(varchar(20),ISNULL(C.StartDate,'01/01/0001'),103) AS StartDate,
			ISNULL(U.DisplayTitle,'') as CreatedUserName			
		FROM 
			sCommunication.tCircular C
			INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
			INNER JOIN sSetup.vUserOrganization UO ON UO.OrgGroupId = C.OrgGroupId
			WHERE ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
			AND ((C.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND ((UO.Id = @rOrgId) OR (@rOrgId=0))
			AND ((C.CircularTypeId=@lCircularTypeId)OR (@lCircularTypeId=0))
			AND CONVERT(DATE,C.CreatedDateTime)=CONVERT(DATE,GETDATE())
			 GROUP BY C.Id,C.Title,C.StartDate,U.DisplayTitle
	END
	IF(@rDay=7)
		BEGIN
			SELECT 
				ISNULL(C.Id,0) as CircularId,
				ISNULL(C.Title,'')AS CircularTitle,
				convert(varchar(20),ISNULL(C.StartDate,'01/01/0001'),103) AS StartDate,
				ISNULL(U.DisplayTitle,'') as CreatedUserName			
			FROM 
				sCommunication.tCircular C
				INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
				INNER JOIN sSetup.vUserOrganization UO ON UO.OrgGroupId = C.OrgGroupId
				WHERE ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
				AND ((C.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((UO.Id = @rOrgId) OR (@rOrgId=0))
				AND ((C.CircularTypeId=@lCircularTypeId)OR (@lCircularTypeId=0))
				AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
				 GROUP BY C.Id,C.Title,C.StartDate,U.DisplayTitle
		END
	IF(@rDay=30)
		BEGIN
			SELECT 
				ISNULL(C.Id,0) as CircularId,
				ISNULL(C.Title,'')AS CircularTitle,
				convert(varchar(20),ISNULL(C.StartDate,'01/01/0001'),103) AS StartDate,
				ISNULL(U.DisplayTitle,'') as CreatedUserName			
			FROM 
				sCommunication.tCircular C
				INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
				INNER JOIN sSetup.vUserOrganization UO ON UO.OrgGroupId = C.OrgGroupId
				WHERE ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
				AND ((C.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((UO.Id = @rOrgId) OR (@rOrgId=0))
				AND ((C.CircularTypeId=@lCircularTypeId)OR (@lCircularTypeId=0))
				AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
				 GROUP BY C.Id,C.Title,C.StartDate,U.DisplayTitle	
		END
  END
	 IF(@rType='OrgGroup')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		 SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization,COUNT(C.Id) AS YesterdayCount FROM  sCommunication.tCircular C
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = C.OrgGroupId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)		
			AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-1) AND CONVERT(DATE,GETDATE())
		GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=1)
	BEGIN
		 SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization,COUNT(C.Id) AS DailyCount FROM  sCommunication.tCircular C
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = C.OrgGroupId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)		
			AND CONVERT(DATE,C.CreatedDateTime)=CONVERT(DATE,GETDATE())
		GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=7)
	BEGIN
		 SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization,COUNT(C.Id) AS WeeklyCount FROM  sCommunication.tCircular C
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = C.OrgGroupId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)		
			AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
		GROUP BY OM.Id,OM.DisplayTitle
	END
	IF(@rDay=30)
	BEGIN
		 SELECT 
			OM.Id AS OrgId, OM.DisplayTitle AS Organization,COUNT(C.Id) AS MonthlyCount FROM  sCommunication.tCircular C
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = C.OrgGroupId
		WHERE 
			(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId =0)		
			AND CONVERT(DATE,C.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		GROUP BY OM.Id,OM.DisplayTitle
	END
  END
  IF(@rType='CircularRemark' AND @rOrgId!=0)
	BEGIN
	SELECT @lCircularTypeId=Id FROM sCommunication.tCircularTypeMaster WHERE IsObsolete = 0 AND OrgGroupId=@rOrgGroupId AND Title = 'Circular'
		SELECT 
			C.Remark,
			AM.Title AS Assignee
		FROM 
			sCommunication.tCircular C
			INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=C.AssigneeId
			INNER JOIN sSetup.vUserOrganization UO ON UO.OrgGroupId = C.OrgGroupId
			WHERE ((C.Id = @rCircularId) OR(@rCircularId=0))
			AND((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
			AND ((C.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND ((UO.Id = @rOrgId) OR (@rOrgId=0))
			AND C.CircularTypeId=@lCircularTypeId
			GROUP BY C.Remark,AM.Title	
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sCommunication.tCircularView where CircularId=@rId
			Delete from sCommunication.tCircularScope where CircularId=@rId
			Delete from sCommunication.tCircular where Id=@rId
		COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION		
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rOrgGroupBatchId int,
	 @rIsSearch bit = 1,
	 @rAssigneeId tinyint,
	 @rCircularTypeId int,
	 @rCreatedUserId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--DECLARE @lTimeZoneConfigValue nvarchar(max)
	--SELECT @lTimeZoneConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 234
	--SELECT @lTimeZoneConfigValue
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			U.DisplayTitle as CreatedUserName,
			C.AssigneeId,
			AM.Title AS Assignee,
			CTM.Title AS CircularTypeTitle,
			CTM.HighlightColor,
			C.CircularTypeId,
			C.CreatedUserId,
			C.CreatedDateTime,
			ISNULL(C.StatusId,549) AS StatusId,
			ISNULL(C.PublishDateTime,'') as PublishDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(C.PublishDateTime,'')) AS PublishDateTime,
			--CASE WHEN ISNULL(C.StatusId,549) =549 then 'Pending' WHEN C.StatusId=550 then 'Approve' ELSE 'Reject' END AS Status
			ISNULL(C.IsPublishInFuture,0) as PublishInFuture,
			ISNULL(C.IsConsent,0) AS IsConsent
  FROM 
            sCommunication.tCircular C
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=C.AssigneeId
            INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id = C.CircularTypeId
  WHERE 
  
		((C.Id = @rId) OR (@rId = 0))
	AND ((C.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((C.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((C.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((C.AssigneeId IN (1,2,3) AND @rAssigneeId=1)  OR
		 (C.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2,3)) OR
		  @rIsSearch = 0)
     AND (C.CircularTypeId=@rCircularTypeId OR @rIsSearch = 0)
    AND (C.CreatedUserId = @rCreatedUserId OR @rCreatedUserId = 0)
	ORDER BY C.StartDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pCircularListAPPGet]
	 
	 @rOrgGroupBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rSyncedCircularId bigint = 0,
	 @rStartDate date='',
	 @rName nvarchar(200)='',
	 @rFromDate date='',
	 @rToDate date='',
	 @rCircularId bigint
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	
	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	 DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
	 
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsCircularBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsCircularBasedOnApproval = 0
	ELSE
	SET @lIsCircularBasedOnApproval = 1	
	
	
	if @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
	
		--DECLARE @lDepartmentId int,@lOrgId int,@lDepartmentId int
		
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
		
	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			  
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId           
            INNER JOIN 
			(SELECT CS.CircularId FROM sCommunication.tCircularScope CS
             WHERE (((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 95 AND CS.SourceId =@lEmployeeId )) AND ((CS.AssigneeToId=3) OR (CS.AssigneeToId IS NULL) OR (ISNULL(CS.AssigneeToId,0)=0)))
              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
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,3) 
            AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
            AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			AND (C.Title like @rName OR ISNULL(@rName,'')='')			
			AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
			AND (ISNULL(C.PublishDateTime,'1900-01-01') <= GETDATE())
			AND ((C.Id = @rCircularId) OR (@rCircularId = ''))
           	ORDER BY C.StartDate DESC
			
	
 END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 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 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId      
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
            WHERE (((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 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))AND ((CS.AssigneeToId=2) OR (CS.AssigneeToId IS NULL) OR (ISNULL(CS.AssigneeToId,0)=0))) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,2) 
             AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
             AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			 AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			 AND (C.Title like @rName OR ISNULL(@rName,'')='')
			 AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
			 AND (ISNULL(C.PublishDateTime,'1900-01-01') <= GETDATE())
			 AND ((C.Id = @rCircularId) OR (@rCircularId = ''))
            ORDER BY C.StartDate DESC

 END
 ELSE
  --For Other Users
 BEGIN
 
 SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			
	 FROM 
            sCommunication.tCircular C     
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId  
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
             AND C.AssigneeId IN (1,2,3)
             AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
             AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
		     AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
		     AND (C.Title like @rName OR ISNULL(@rName,'')='')
		     AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
			 AND ((C.Id = @rCircularId) OR (@rCircularId = ''))
            ORDER BY C.StartDate DESC

 
 	--SELECT 	
		--	C.Id as CircularId,
		--	C.Title,
		--	C.Remark,
		--	C.StartDate,
		--	CV.UserId,
		--	U.DisplayTitle as CreatedUserName	    
	 --FROM 
  --          sCommunication.tCircular C       
  --          LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
  --          INNER JOIN sCommunication.tCircularScope CS ON CS.CircularId=C.Id 
  --          INNER JOIN ( SELECT A.DivisionId FROM sStudent.tAcademic A            
  --           WHERE A.StudentId = @rUserSourceId ) D
  --          ON D.DivisionId =  CS.SourceId AND CS.SourceTypeId = 2005
  --          INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
  --          INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
  --          WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
  --          Order by C.CreatedDateTime DESC


 END
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularListGet]
	 
	 @rOrgGroupBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rSyncedCircularId bigint = 0,
	 @rStartDate date='',
	 @rName nvarchar(200)='',
	 @rFromDate date='',
	 @rToDate date=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	
	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	 DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
	 
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsCircularBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsCircularBasedOnApproval = 0
	ELSE
	SET @lIsCircularBasedOnApproval = 1	
	
	
	if @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
	
		--DECLARE @lDepartmentId int,@lOrgId int,@lDepartmentId int
		
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
		
	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			  
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId           
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
             WHERE (((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 95 AND CS.SourceId =@lEmployeeId )) AND ((CS.AssigneeToId=3) OR (CS.AssigneeToId IS NULL) OR (ISNULL(CS.AssigneeToId,0)=0)))
              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
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,3) 
            AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
            AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			AND (C.Title like @rName OR ISNULL(@rName,'')='')			
			AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
			AND (ISNULL(C.PublishDateTime,'1900-01-01') <= GETDATE())
           	ORDER BY C.StartDate DESC
			
	
 END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 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 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId      
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
            WHERE (((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 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))AND ((CS.AssigneeToId=2) OR (CS.AssigneeToId IS NULL) OR (ISNULL(CS.AssigneeToId,0)=0))) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,2) 
             AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
             AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			 AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			 AND (C.Title like @rName OR ISNULL(@rName,'')='')
			 AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
			 AND (ISNULL(C.PublishDateTime,'1900-01-01') <= GETDATE())
            ORDER BY C.StartDate DESC

 END
 ELSE
  --For Other Users
 BEGIN
 
 SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			
	 FROM 
            sCommunication.tCircular C     
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId  
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
             AND C.AssigneeId IN (1,2,3)
             AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
             AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
		     AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
		     AND (C.Title like @rName OR ISNULL(@rName,'')='')
		     AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
            ORDER BY C.StartDate DESC

 
 	--SELECT 	
		--	C.Id as CircularId,
		--	C.Title,
		--	C.Remark,
		--	C.StartDate,
		--	CV.UserId,
		--	U.DisplayTitle as CreatedUserName	    
	 --FROM 
  --          sCommunication.tCircular C       
  --          LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
  --          INNER JOIN sCommunication.tCircularScope CS ON CS.CircularId=C.Id 
  --          INNER JOIN ( SELECT A.DivisionId FROM sStudent.tAcademic A            
  --           WHERE A.StudentId = @rUserSourceId ) D
  --          ON D.DivisionId =  CS.SourceId AND CS.SourceTypeId = 2005
  --          INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
  --          INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
  --          WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
  --          Order by C.CreatedDateTime DESC


 END
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularMasterGet]
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	
	SELECT 
			Id,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime,
			HighlightColor
		    
  FROM 
            sCommunication.tCircularTypeMaster
  WHERE 
  
		((Id = @rId) OR (@rId = 0))
		AND (((Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') = '')))
	
	
	AND ((OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))
	
	
	ORDER BY CreatedDateTime DESC
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularQueueGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100)='',
	 @rFromDate date,
	 @rToDate date,
	 @rOrgGroupBatchId int,
	 @rIsSearch bit = 1,
	 @rAssigneeId tinyint,
	 @rCircularTypeId int,
	 @rCreatedUserId bigint=0,
	 @rStatusId int=0,
	 @rSourceId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

    DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsCircularBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsCircularBasedOnApproval = 0
	ELSE
	SET @lIsCircularBasedOnApproval = 1	


	 IF (@rIsSearch = 1)
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	IF(@lIsCircularBasedOnApproval = 0)
	BEGIN
		SELECT 
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			U.DisplayTitle as CreatedUserName,
			C.AssigneeId,
			AM.Title AS Assignee,
			CTM.Title AS CircularTypeTitle,
			CTM.HighlightColor,
			C.CircularTypeId,
			C.CreatedUserId,
			C.CreatedDateTime,
			ISNULL(C.StatusId,549) AS StatusId,
			CASE WHEN ISNULL(C.StatusId,549) =549 then 'Pending' WHEN C.StatusId=550 then 'Approved' ELSE 'Reject' END AS Status
		FROM 
			sCommunication.tCircular C
			INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
			INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=C.AssigneeId
			INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id = C.CircularTypeId
		WHERE 
			((C.Id = @rId) OR (@rId = 0))
			AND ((C.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((C.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((C.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((C.AssigneeId IN (1,2,3) AND @rAssigneeId=1)  OR
				(C.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2,3)) OR
				@rIsSearch = 0)
		  --AND (C.CircularTypeId=@rCircularTypeId OR @rIsSearch = 0)
			AND (C.CircularTypeId=@rCircularTypeId OR @rCircularTypeId = 0)
			AND (C.CreatedUserId = @rCreatedUserId OR @rCreatedUserId = 0)
			AND (C.StatusId = @rStatusId OR (@rStatusId = 0))
		  --AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
		ORDER BY C.StartDate DESC
	END
	ELSE IF(@lIsCircularBasedOnApproval = 1)
	BEGIN
		SELECT 
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			U.DisplayTitle as CreatedUserName,
			C.AssigneeId,
			AM.Title AS Assignee,
			CTM.Title AS CircularTypeTitle,
			CTM.HighlightColor,
			C.CircularTypeId,
			C.CreatedUserId,
			C.CreatedDateTime,
			ISNULL(C.StatusId,549) AS StatusId,
			CASE WHEN ISNULL(C.StatusId,549) =549 then 'Pending' WHEN C.StatusId=550 then 'Approved' ELSE 'Reject' END AS Status
		FROM 
			sCommunication.tCircular C
			INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
			INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=C.AssigneeId
			INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id = C.CircularTypeId
			INNER JOIN sCommunication.tCircularTypeAssignedTo CTAT ON CTAT.CircularTypeId = CTM.Id
		WHERE 
  
			((C.Id = @rId) OR (@rId = 0))
			AND ((C.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((C.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((C.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((C.AssigneeId IN (1,2,3) AND @rAssigneeId=1)  OR
				(C.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2,3)) OR
				@rIsSearch = 0)
		  --AND (C.CircularTypeId=@rCircularTypeId OR @rIsSearch = 0)
			AND (C.CircularTypeId=@rCircularTypeId OR @rCircularTypeId = 0)
		  --AND (C.CreatedUserId = @rCreatedUserId OR @rCreatedUserId = 0)
			AND (C.StatusId = @rStatusId OR (@rStatusId = 0))
		  --AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
			AND (CTAT.SourceId = @rSourceId AND CTAT.SourceTypeId = 95)
		ORDER BY C.StartDate DESC
	END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pCircularScopeAdd]
			@rCircularId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 

If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tCircularScope where CircularId=@rCircularId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select CircularId from sCommunication.tCircularScope where CircularId=@rCircularId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tCircularScope
			(
				CircularId
			   ,SourceTypeId
			   ,SourceId
			)
			VALUES
			(	
				@rCircularId
			   ,@rSourceTypeId
			   ,@rSourceId
			)		
			SELECT @rCircularId AS Result
		 
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pCircularScopeGet]
	 @rCircularId bigint
	 --@rBatchId int
	 --@rOrgId smallint,
	 --@rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 ISNULL(CS.AssigneeToId, 0) AS AssigneeToId
			 
			FROM sCommunication.tCircularScope CS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON CS.SourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2021

			UNION ALL

			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 ISNULL(CS.AssigneeToId, 0) AS AssigneeToId

			FROM sCommunication.tCircularScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2017

			UNION ALL

			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 ISNULL(CS.AssigneeToId, 0) AS AssigneeToId
			 
			FROM sCommunication.tCircularScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2016

			UNION ALL

			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			ISNULL(CS.AssigneeToId, 0) AS AssigneeToId
			 
			FROM sCommunication.tCircularScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId	
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 ISNULL(CS.AssigneeToId, 0) AS AssigneeToId
			 
			FROM sCommunication.tCircularScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 ISNULL(CS.AssigneeToId, 0) AS AssigneeToId
			 
			FROM sCommunication.tCircularScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 ISNULL(CS.AssigneeToId, 0) AS AssigneeToId
			
			FROM sCommunication.tCircularScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId	
			WHERE 
			CS.CircularId=@rCircularId AND CS.SourceTypeId=95


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pCircularScopeRemove]
			@rCircularId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	Delete from sCommunication.tCircularScope where CircularId=@rCircularId AND SourceTypeId=@rSourceTypeId
      AND SourceId=@rSourceId
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
             
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pCircularScopeValidate]
	 
        @rCircularId bigint,
		@rSourceTypeId smallint,
		@rSourceId bigint
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tCircularScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.CircularId=@rCircularId)
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2004
				where DM.OrgId=@rSourceId  AND CS.CircularId=@rCircularId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tCircularScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.CircularId=@rCircularId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.CircularId=@rCircularId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tCircularScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.CircularId=@rCircularId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.CircularId=@rCircularId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tCircularScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.CircularId=@rCircularId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.CircularId=@rCircularId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tCircularScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.CircularId=@rCircularId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 			
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2004
			where CM.Id=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tCircularScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2004
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tCircularScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tCircularScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2004
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tCircularScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tCircularScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.CircularId=@rCircularId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
			select 1 as Result,'' AS Msg
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularTypeAssignedToDelete]
	 
	 @rSourceId bigint,
	 @rCircularTypeId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			DELETE FROM sCommunication.tCircularTypeAssignedTo WHERE SourceId=@rSourceId AND CircularTypeId = @rCircularTypeId
			SELECT 1 AS Result
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
			SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularTypeAssignedToGet]
	 
	 @rCircularTypeId int,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			CTM.Id AS CircularTypeId,
			CTA.SourceTypeId,
			'Functional Rolewise' AS SourceType,
			CTA.SourceId,
			'' AS SourceCode,
			R.Title AS SourceName
	FROM 
			sCommunication.tCircularTypeAssignedTo CTA
		INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id=CTA.CircularTypeId AND (CTM.OrgGroupId = @rOrgGroupId)	
		INNER JOIN sSecurity.tRole R ON R.Id=CTA.SourceId AND CTA.SourceTypeId=2015
	WHERE 
			(CTA.CircularTypeId = @rCircularTypeId)
			
	UNION ALL
	
	SELECT 
			CTM.Id AS CircularTypeId,
			CTA.SourceTypeId,
			'Specific Employeewise' AS SourceType,
			CTA.SourceId,
			EM.EmployeeCode AS SourceCode,
			EM.EmployeeName AS SourceName
	FROM 
			sCommunication.tCircularTypeAssignedTo CTA
		INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id=CTA.CircularTypeId AND (CTM.OrgGroupId = @rOrgGroupId)
		INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId=CTA.SourceId AND CTA.SourceTypeId=95
	WHERE 
			(CTA.CircularTypeId = @rCircularTypeId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pCircularTypeMasterAdd]
	 
		@rOrgGroupId smallint,
		@rId  int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rCreatedUserId bigint,
		@rCreatedDateTime date,
		@rIsObsolete bit,
		@rUpdateduserId bigint=0,
		@rUpdatedDateTime date='',
		@rHighlightColor nvarchar(20)
		
      
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tCircularTypeMaster where Title=@rTitle AND Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tCircularTypeMaster where Title=@rTitle AND Code=@rCode AND Id<>@rId AND OrgGroupId=@rOrgGroupId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tCircularTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tCircularTypeMaster
		(
		OrgGroupId,
		Id,
		Code,
		Title,
		CreatedUserId,
		CreatedDateTime,
		IsObsolete,
		UpdatedUserId,
		UpdatedDateTime,
		HighlightColor
			
		)
	VALUES
		(
		@rOrgGroupId,
		@lNextNumber,
		@rCode,
		@rTitle,
		@rCreatedUserId,
		@rCreatedDateTime,
		@rIsObsolete,
		@rCreatedUserId,
		@rCreatedDateTime,
		@rHighlightColor
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tCircularTypeMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			HighlightColor=@rHighlightColor
			
	      
	      
	      WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularTypeMasterDelete]

	 @rId int,
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		IF NOT EXISTS (SELECT Id FROM sCommunication.tCircular WHERE CircularTypeId = @rId)	
		BEGIN	
			Delete from sCommunication.tCircularTypeMaster where Id=@rId AND OrgGroupId=@rOrgGroupId
			Select 1 AS RESULT
		END
		ELSE
			BEGIN
				SELECT -101 AS RESULT
			END
			
		
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularViewAdd]
			@rCircularId bigint
           ,@rUserId bigint
		   ,@rSourceTypeId int = 0
		   ,@rSourceId bigint = 0
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select CircularId from sCommunication.tCircularView where CircularId=@rCircularId AND UserId=@rUserId AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId)
		BEGIN
			SELECT @rCircularId AS Result
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tCircularView
			(
				CircularId
			   ,UserId
			   ,SourceTypeId
			   ,SourceId
			   ,ViewByDateTime
			)
			VALUES
			(	
				@rCircularId
			   ,@rUserId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,sCommon.fGetDate()
			)		
			SELECT @rCircularId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCircularViewGet]
	@rCircularId bigint,
	@rClassId int=0,
	@rDivisionId int=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;

BEGIN

	BEGIN TRY
	 BEGIN TRANSACTION	
		 BEGIN
		 SELECT 
			 CASE WHEN CV.SourceTypeId = 2003 THEN  SM.Code WHEN CV.SourceTypeId = 95 THEN EM.Code END as Code,
			 CASE WHEN CV.SourceTypeId = 2003 THEN  SM.FirstName +' '+ SM.LastName WHEN CV.SourceTypeId = 95 THEN EM.FirstName +' '+ EM.LastName END as Name,
			 CV.ViewByDateTime			 
		 FROM
			 sCommunication.tCircularView as CV
			 LEFT JOIN sStudent.tStudentMaster SM on SM.Id = CV.SourceId AND CV.SourceTypeId = 2003
			 LEFT JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND CV.SourceTypeId = 2003
			 LEFT JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId AND CV.SourceTypeId = 2003
			 LEFT JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId AND CV.SourceTypeId = 2003
			 LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = CV.SourceId AND CV.SourceTypeId = 95
		 WHERE
			CircularId = @rCircularId AND CV.SourceId != ''
			AND ((CM.Id=@rClassId)OR(@rClassId=0))
			AND((DM.Id=@rDivisionId)OR(@rDivisionId=0))
		 GROUP BY CV.CircularId, CV.ViewByDateTime,CV.SourceTypeId,SM.Code,SM.FirstName,SM.LastName,EM.Code,EM.FirstName,EM.LastName

		SELECT 1 AS RESULT
        END  
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCirculaTypeAssignedToAdd]
	 
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rCircularTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION
	 IF EXISTS(SELECT 1 FROM sCommunication.tCircularTypeAssignedTo WHERE SourceTypeId=@rSourceTypeId 
	 AND SourceId=@rSourceId AND CircularTypeId=@rCircularTypeId)
	 BEGIN
			SELECT @rCircularTypeId AS Result
			RETURN
	 END
	INSERT INTO sCommunication.tCircularTypeAssignedTo
		(
			SourceTypeId,
			SourceId,
			CircularTypeId
		)
	VALUES
		(
			@rSourceTypeId,
			@rSourceId,
			@rCircularTypeId
		) 
		
		SELECT @rCircularTypeId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCommunicationQueryQueueDelete]
    
   
    @rOrgGroupId bigint,
	@rXmldoc [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @loDoc INT
BEGIN TRY
BEGIN TRANSACTION
	
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXmldoc
	
	DELETE FROM sCommunication.tQueryComment
		WHERE 
		QueryId IN (
	SELECT
		QueryId
	FROM OPENXML (@loDoc, '/Table/Query', 1)
	WITH
			( 
				QueryId bigint
			)
		)	

	DELETE FROM sCommunication.tQuery 
		WHERE OrgGroupId=@rOrgGroupId 
		AND Id IN (
	SELECT
		QueryId
	FROM OPENXML (@loDoc, '/Table/Query', 1)
	WITH
			( 
				QueryId bigint
			)
		)


	
		
	
	EXEC sp_xml_removedocument @loDoc
		
COMMIT TRANSACTION			

END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT -1 Result
END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sCommunication].[pCommunicationQueryQueueGet]
	 
	 @rQueryCategoryId int = 0,
	 --@rCreatedUserId bigint,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint,
	 @rQueryId bigint,
	 @rUserSourceId bigint,
	 @rMyList bit,
	 @rStatusId int = 0,
	 @rSourceId bigint = 0,
	 @rSubjectId int = 0,
	 @rFromDate DateTime ='',
	 @rToDate DateTime =''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
IF(@rMyList=0)
BEGIN
	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code AS Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
        
	WHERE 
  
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId) 
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND ((EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		AND ((CONVERT(NVARCHAR,QM.CreatedDateTime,23) >= CONVERT(NVARCHAR,@rFromDate,23)) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(NVARCHAR,QM.CreatedDateTime,23) <= CONVERT(NVARCHAR,@rToDate,23)) OR (ISNULL(@rToDate,'')=''))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			
	FROM 
			sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((CONVERT(NVARCHAR,QM.CreatedDateTime,23) >= CONVERT(NVARCHAR,@rFromDate,23)) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(NVARCHAR,QM.CreatedDateTime,23) <= CONVERT(NVARCHAR,@rToDate,23)) OR (ISNULL(@rToDate,'')=''))
		
	
		UNION
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND SA.IsActiveBatch = 1 --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((CONVERT(NVARCHAR,QM.CreatedDateTime,23) >= CONVERT(NVARCHAR,@rFromDate,23)) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(NVARCHAR,QM.CreatedDateTime,23) <= CONVERT(NVARCHAR,@rToDate,23)) OR (ISNULL(@rToDate,'')=''))
		
		UNION
		
		
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 AND ISNULL(EM.IsOtherUser,0) = 0
	 AND ((CONVERT(NVARCHAR,QM.CreatedDateTime,23) >= CONVERT(NVARCHAR,@rFromDate,23)) OR (ISNULL(@rFromDate,'')=''))
	 AND ((CONVERT(NVARCHAR,QM.CreatedDateTime,23) <= CONVERT(NVARCHAR,@rToDate,23)) OR (ISNULL(@rToDate,'')=''))
	 ORDER BY QM.CreatedDateTime DESC
	 --and QM.FromSourceTypeId=95
		
		
END
--ELSE IF(@rMyList=1)
--BEGIN

--	SELECT 
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.Id AS QueryId,
--			QM.IsUserView,
--			QM.IsAssigneeView,
--			ODM.Title AS Department,
--			U.DisplayTitle AS SourceName, 
--			U.SourceTypeId, 
--			'Employee' AS SourceType,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			OM.DisplayTitle AS OrgName,
--			EM.Code,
--			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
--			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
--	FROM 
--			sCommunication.tQuery QM
--		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
--        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
--        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
--        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
--        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
--	WHERE 
--			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
--		AND (QCM.OrgGroupId = @rOrgGroupId)
--		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
--	    --AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId)
--	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--	    AND (( EJD.EmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
--		AND ISNULL(EM.IsOtherUser,0) = 0
--	UNION 

--	SELECT 
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.Id AS QueryId,
--			QM.IsUserView,
--			QM.IsAssigneeView,
--			SA.ClassName + ' ' + SA.DivisionName  AS Department,
--			U.DisplayTitle AS SourceName,
--			U.SourceTypeId,
--			'Student' AS SourceType,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			OM.DisplayTitle AS OrgName,
--			SA.Code,
--			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
--			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
--	FROM 
--		sCommunication.tQuery QM
--        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
--        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
--        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
--	WHERE 
--			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
--		AND (QCM.OrgGroupId=@rOrgGroupId)  
--		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
--		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId AND SourceTypeId <> 2015)
--		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
--	UNION 

--	SELECT 
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.Id AS QueryId,
--			QM.IsUserView,
--			QM.IsAssigneeView,
--			SA.ClassName + ' ' + SA.DivisionName  AS Department,
--			U.DisplayTitle AS SourceName,
--			U.SourceTypeId,
--			'Student' AS SourceType,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			OM.DisplayTitle AS OrgName,
--			SA.Code,
--			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
--			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
--	FROM 
--		sCommunication.tQuery QM
--        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
--        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
--					AND SA.DivisionId IN (SELECT Id FROM sSetup.tDivisionMaster WHERE InchargeEmployeeId=@rUserSourceId)
--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId			
--	WHERE 
--			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
--		AND (QCM.OrgGroupId=@rOrgGroupId)  
--		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
--		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 24 AND SourceTypeId = 2015)
--		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
--	UNION 

--	SELECT 
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.Id AS QueryId,
--			QM.IsUserView,
--			QM.IsAssigneeView,
--			SA.ClassName + ' ' + SA.DivisionName  AS Department,
--			U.DisplayTitle AS SourceName,
--			U.SourceTypeId,
--			'Student' AS SourceType,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			OM.DisplayTitle AS OrgName,
--			SA.Code,
--			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
--			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
--	FROM 
--		sCommunication.tQuery QM
--        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
--        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
--        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
--	WHERE 
--			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
--		AND (QCM.OrgGroupId=@rOrgGroupId)  
--		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
--		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
--		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		
		
		
--		UNION 

--	SELECT 
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.Id AS QueryId,
--			QM.IsUserView,
--			QM.IsAssigneeView,
--			SA.ClassName + ' ' + SA.DivisionName  AS Department,
--			U.DisplayTitle AS SourceName,
--			U.SourceTypeId,
--			'Student' AS SourceType,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			OM.DisplayTitle AS OrgName,
--			SA.Code,
--			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
--			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
--	FROM 
--		sCommunication.tQuery QM
--        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
--        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND SA.IsActiveBatch = 1 --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
--        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
--	WHERE 
--	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
--			AND (QCM.OrgGroupId=@rOrgGroupId)  
--			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
--			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
--			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
--			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
		
		
--   UNION
    
    
    
    
    
--    SELECT 
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.Id AS QueryId,
--			QM.IsUserView,
--			QM.IsAssigneeView,
--			SA.ClassName + ' ' + SA.DivisionName  AS Department,
--			U.DisplayTitle AS SourceName, 
--			U.SourceTypeId, 
--			'Employee' AS SourceType,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			OM.DisplayTitle AS OrgName,
--			SA.Code,
--			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
--			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			
--	FROM 
--		sCommunication.tQuery QM
--        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId AND U.SourceTypeId = 95
--        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
--        INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = SA.DivisionId AND (( TSD.EmployeeId = @rUserSourceId) OR (@rUserSourceId=0)) AND QM.SubjectId= TSD.SubjectId                  
--        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
        
--  WHERE 
--	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
--			AND (QM.OrgGroupId=@rOrgGroupId)  
--			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
--			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
--			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
--			AND ((TSD.SubjectId=@rSubjectId) OR (@rSubjectId=0))
--			--AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId      
        
	 
--	 UNION
    
--    SELECT 
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.Id AS QueryId,
--			QM.IsUserView,
--			QM.IsAssigneeView,
--			ODM.Title AS Department,
--			U.DisplayTitle AS SourceName, 
--			U.SourceTypeId, 
--			'Employee' AS SourceType,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			OM.DisplayTitle AS OrgName,
--			EM.Code,
--			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
--			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
--	FROM 	
		
--		sCommunication.tQuery QM
--		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
--        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
--        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
--        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
--        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
--	 WHERE 
	 
--	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
--	 AND (QCM.OrgGroupId=@rOrgGroupId)  
--	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
--	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
--	 AND ISNULL(EM.IsOtherUser,0) = 0
--	 ORDER BY QM.CreatedDateTime DESC	
	
		
--END
END


--SELECT Q.CreatedUserId FROM sCommunication.tQueryCategoryMaster QCM INNER JOIN sCommunication.tQuery Q ON Q.QueryCategoryId = QCM.Id

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pCustomGroupAdd]
	 
        @rOrgGroupId smallint,
        @rId int,
        @rCode nvarchar(200),
		@rTitle nvarchar(200),
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM sCommunication.tCustomGroup WHERE Code=@rCode AND OrgGroupId=@rOrgGroupId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM sCommunication.tCustomGroup WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM sCommunication.tCustomGroup WHERE Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
		
		IF EXISTS(SELECT Id FROM sCommunication.tCustomGroup WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
	END
	BEGIN TRANSACTION	
	DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tCustomGroup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tCustomGroup
		(
			OrgGroupId,
			Id,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		
	SELECT @lNextNumber AS Result
	
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tCustomGroup
	    SET
			Code=@rCode,
			Title=@rTitle,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      
	      SELECT @lNextNumber AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCustomGroupDelete]
	 
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			DELETE FROM sCommunication.tCustomGroupMember WHERE CustomGroupId=@rId
			DELETE FROM sCommunication.tCustomGroup WHERE Id=@rId
		COMMIT TRANSACTION			 
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION		
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCustomGroupGet]
	 
	 @rId int = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(200),
	 @rOrgGroupId int,
	 @rIsSearch bit
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			CG.Id as CustomGroupId,
			CG.Code,
			CG.Title
	FROM 
            sCommunication.tCustomGroup CG
    WHERE 
  
	(CG.OrgGroupId = @rOrgGroupId)
	AND	((CG.Id = @rId) OR (@rId = 0))
	AND ((CG.Code LIKE @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((CG.Title LIKE @rTitle) OR (ISNULL(@rTitle,'') = ''))
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pCustomGroupMemberAdd]

			@rCustomGroupId int,
            @rSourceTypeId smallint,
            @rSourceId bigint
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		IF EXISTS (SELECT CustomGroupId FROM sCommunication.tCustomGroupMember WHERE CustomGroupId=@rCustomGroupId AND SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId)
			BEGIN
				SELECT @rSourceId AS Result
				RETURN
			END 
		ELSE
			BEGIN
				INSERT INTO sCommunication.tCustomGroupMember
				(
					CustomGroupId,
					SourceTypeId,
					SourceId
				)
				VALUES
				(	
					@rCustomGroupId,
					@rSourceTypeId,
					@rSourceId
				)		
				SELECT @rCustomGroupId AS Result
			END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pCustomGroupMemberGet]
	 
	 @rCustomGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
			SELECT
				CGM.CustomGroupId,
				CGM.SourceTypeId,
				CGM.SourceId,
				vSA.Code,
				vSA.FirstName +' '+ vSA.LastName AS Source,
				VSA.ClassName +' - '+ VSA.DivisionName AS ClassDepartment,
				'Student' AS SourceType 
			FROM sCommunication.tCustomGroupMember CGM
			INNER JOIN sStudent.vStudentAcademic vSA
				ON CGM.SourceId=vSA.AcademicId AND vSA.StatusId=1
			WHERE 
			CGM.CustomGroupId=@rCustomGroupId AND CGM.SourceTypeId=2001
			
			
			UNION ALL
			
			SELECT
				CGM.CustomGroupId,
				CGM.SourceTypeId,
				CGM.SourceId,
				vEC.Code,
				vEC.FirstName +' '+ vEC.LastName AS Source,
				vEC.DepartmentName AS ClassDepartment,
				'Employee' AS SourceType 
			FROM sCommunication.tCustomGroupMember CGM
			INNER JOIN sHrm.vEmployeeCommunication vEC
				ON CGM.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			WHERE 
			CGM.CustomGroupId=@rCustomGroupId AND CGM.SourceTypeId=95
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pCustomGroupMemberRemove]
			
			@rCustomGroupId int,
            @rSourceTypeId smallint,
            @rSourceId bigint
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
		DELETE FROM sCommunication.tCustomGroupMember 
		WHERE CustomGroupId=@rCustomGroupId 
		AND SourceTypeId=@rSourceTypeId
		AND SourceId=@rSourceId
		SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pDailyFeedGet]
	 
@rUserId bigint=0,
@rOrgGroupId int=0,
@rOrgGroupBatchId int=0,
@rOrgId int=0,	 
@rBatchId int=0,
@rFeedDate date=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @lSourceId bigint=0,@lSourceTypeId smallint=0,@lAcademicId bigint,@lClassId int,@lDivisionId int,@lDepartmentId int
    SELECT @lSourceId=SourceId,@lSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE Id = @rUserId

	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1	


	DECLARE @lConfigValue1 nvarchar(50)
	DECLARE @lIsAssignmentBasedOnApproval bit=0
	SELECT @lConfigValue1 = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 329 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue1 IS NULL) OR (@lConfigValue1 = 'False')
	SET @lIsAssignmentBasedOnApproval = 0
	ELSE
	SET @lIsAssignmentBasedOnApproval = 1	
    
    -- Student
	IF(@lSourceTypeId = 2003)	
	BEGIN
		SELECT @lAcademicId = A.Id,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lDepartmentId=CM.DepartmentId 
		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 = @lSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
	END
	-- Employee
	ELSE
	BEGIN
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId 
		FROM sHrm.tEmployeeMaster EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		WHERE EM.Id=@lSourceId AND ISNULL(EM.IsOtherUser,0) = 0 
	END
	
	
	-- Student
	IF(@lSourceTypeId = 2003)	
	BEGIN
		-- Circular
		--print @rOrgId
		--print @lDepartmentId
		--print @lClassId
		--print @lDivisionId
		--print @lSourceId
		--print @lAcademicId
		--print @rFeedDate
		
		--print @lSourceTypeId
		SELECT C.Id,C.Title,C.Remark,20085 AS ScreenId,C.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tCircular C INNER JOIN 
		(SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE
		(
			(CS.SourceTypeId = 2021 AND CS.SourceId =@rOrgId) 
			OR (CS.SourceTypeId = 2017 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 =@lSourceId)
			OR (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId)
		)
		AND (CS.AssigneeToId = 2)
		) D ON D.CircularId= C.Id
		INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
		WHERE CONVERT(DATE,C.StartDate) = @rFeedDate AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId AND StatusId=550
		
		UNION ALL
		
		-- Assignment
		SELECT A.Id,A.Title,A.Remark,20093 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignment A INNER JOIN 
		(SELECT ASO.AssignmentId FROM sCommunication.tAssignmentScope ASO WHERE
		(
		(ASO.SourceTypeId = 2005 AND ASO.SourceId =@lDivisionId)
		)
		) D ON D.AssignmentId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.StartDate) = @rFeedDate AND  A.BatchId=@rBatchId
		AND ((@lIsAssignmentBasedOnApproval=0) OR (@lIsAssignmentBasedOnApproval=1 AND A.StatusId=550))
		
		UNION ALL
		
		-- Poll
		SELECT P.Id,P.Title,P.Remark,20204 AS ScreenId,P.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPoll P INNER JOIN 
		(SELECT PM.PollId FROM sCommunication.tPollMember PM  WHERE
		(
		(PM.SourceTypeId = 2005 AND PM.SourceId =@lDivisionId)
		)
		) D ON D.PollId= P.Id
		INNER JOIN sSecurity.tUser U ON U.Id=P.CreatedUserId
		WHERE CONVERT(DATE,P.CreatedDateTime) = @rFeedDate AND  P.OrgGroupBatchId=@rOrgGroupBatchId
		
		UNION ALL
		
		-- Blog
		SELECT B.Id,B.Title,B.Remark,20099 AS ScreenId,B.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tBlog B INNER JOIN 
		(SELECT BS.BlogId FROM sCommunication.tBlogScope BS  WHERE
		(
		(BS.SourceTypeId = 2021 AND BS.SourceId =@rOrgId)
		)
		) D ON D.BlogId= B.Id
		INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
		WHERE CONVERT(DATE,B.CreatedDateTime) = @rFeedDate AND  B.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- News
		SELECT N.Id,N.Title,N.Remark,20104 AS ScreenId,N.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tNews N INNER JOIN 
		(SELECT NS.NewsId FROM sCommunication.tNewsScope NS  WHERE
		(
		(NS.SourceTypeId = 2021 AND NS.SourceId =@rOrgId)
		)
		) D ON D.NewsId= N.Id
		INNER JOIN sSecurity.tUser U ON U.Id=N.CreatedUserId
		WHERE CONVERT(DATE,N.CreatedDateTime) = @rFeedDate AND  N.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- Gallery
		SELECT PCM.Id,PCM.Title,PCM.Remark,20183 AS ScreenId,PCM.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPhotoCategoryMaster PCM INNER JOIN 
		(SELECT PCS.PhotoCategoryId FROM sCommunication.tPhotoCategoryMaster PCM
		INNER JOIN sCommunication.tPhotoCategoryScope PCS ON PCM.Id = PCS.PhotoCategoryId
		WHERE
		((PCM.ScopeSourceTypeId = 2021 AND PCS.ScopeSourceId =@rOrgId))
		OR ((PCM.ScopeSourceTypeId = 2017 AND PCS.ScopeSourceId =@lDepartmentId))
		OR ((PCM.ScopeSourceTypeId = 2016 AND PCS.ScopeSourceId =@lClassId))
		OR ((PCM.ScopeSourceTypeId = 2005 AND PCS.ScopeSourceId =@lDivisionId))
		) D ON D.PhotoCategoryId= PCM.Id
		INNER JOIN sSecurity.tUser U ON U.Id=PCM.CreatedUserId
		WHERE CONVERT(DATE,PCM.CreatedDateTime) = @rFeedDate AND  PCM.OrgGroupId=@rOrgGroupId 
		
		UNION ALL
		
		-- Classwork | Homework
		SELECT C.Id,'Classwork' AS Title,Classwork AS Remark,20563 AS ScreenId,C.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sAcademic.tClasswork C
		INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
		WHERE CONVERT(DATE,C.CreatedDateTime) = @rFeedDate AND  BatchId=@rBatchId AND DivisionId = @lDivisionId AND ClassId = @lClassId 
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND C.StatusId=550))
		
		UNION ALL
		
		-- Behaviour
		SELECT B.Id,Title,Remark,20130 AS ScreenId,B.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle FROM sCommunication.tBehaviour B
		INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
		WHERE CONVERT(DATE,B.CreatedDateTime) = @rFeedDate AND  AcademicId=@lAcademicId
		
		UNION ALL
		
		-- Activity
		SELECT A.Id,A.Title,A.Remark,20209 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sActivity.tActivity A INNER JOIN 
		(SELECT AP.ActivityId FROM sActivity.tActivityParticipant AP  WHERE
		(
		(AP.SourceTypeId = 2003 AND AP.SourceId =@lSourceId)
		)
		) D ON D.ActivityId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.CreatedDateTime) = @rFeedDate AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Task
		SELECT T.Id,'Task' AS Title,Remark,20172 AS ScreenId,T.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignTask T
		INNER JOIN sSecurity.tUser U ON U.Id=T.CreatedUserId
		WHERE CONVERT(DATE,T.CreatedDateTime) = @rFeedDate AND  T.OrgId=@rOrgId AND AssignedToSourceTypeId = 2003 AND AssignedToSourceId=@lSourceId
		
		UNION ALL
		
		-- Birthday
		SELECT SM.Id,'Birthday' AS Title,FirstName+' '+LastName AS Remark,20577 AS ScreenId,SO.DateOfBirth AS CreatedDateTime,0 AS CreatedUserId,'' AS CreatedUser FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tStudentOther SO ON SM.Id = SO.StudentId 
		WHERE CONVERT(DATE,SO.DateOfBirth) = @rFeedDate AND  SM.OrgId=@rOrgId AND SM.Id=@lSourceId

		UNION ALL

		-- Alert
		SELECT AL.Id,AL.AlertSubject as Title,AL.AlertMessage as Remark,0 AS ScreenId,AL.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle FROM sAlert.tAlertLog AL
		INNER JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		WHERE CONVERT(DATE,AL.CreatedDateTime) = @rFeedDate AND  AL.ReceiverSourceId=@lSourceId AND AL.ReceiverSourceTypeId = @lSourceTypeId
		
		UNION ALL

		-- Notification
		SELECT NF.Id,NF.MessageTitle as Title,NF.NotificationMessage as Remark,0 AS ScreenId,NF.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle FROM sAlert.tNotificationLog NF
		INNER JOIN sSecurity.tUser U ON U.Id=NF.CreatedUserId
		WHERE CONVERT(DATE,NF.CreatedDateTime) = @rFeedDate AND  NF.SourceId=@lAcademicId AND NF.SourceTypeId = 2001
	END 
	-- Employee
	ELSE
	BEGIN
		-- Circular
		SELECT C.Id,C.Title,C.Remark,20085 AS ScreenId,C.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
		WHERE (
			  (CS.SourceTypeId = 2021 AND CS.SourceId =@rOrgId) 
 			  OR (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId)
 			  OR (CS.SourceTypeId = 95 AND CS.SourceId =@lSourceId)
			  )AND (CS.AssigneeToId = 3)) D ON D.CircularId= C.Id
		INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId	  
		WHERE CONVERT(DATE,C.StartDate) = @rFeedDate AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId AND StatusId=550
		
		UNION ALL
		
		-- Assignment
		SELECT A.Id,A.Title,A.Remark,20093 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignment A INNER JOIN (SELECT ASO.AssignmentId FROM sCommunication.tAssignmentScope ASO
		WHERE (
			  (ASO.SourceTypeId = 2017 AND ASO.SourceId =@lDepartmentId)
			  )) D ON D.AssignmentId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId		  
		WHERE CONVERT(DATE,A.StartDate) = @rFeedDate AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Poll
		SELECT P.Id,P.Title,P.Remark,20204 AS ScreenId,P.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPoll P INNER JOIN 
		(SELECT PM.PollId FROM sCommunication.tPollMember PM  WHERE
		(
		(PM.SourceTypeId = 2017 AND PM.SourceId =@lDepartmentId)
		)
		) D ON D.PollId= P.Id
		INNER JOIN sSecurity.tUser U ON U.Id=P.CreatedUserId		  
		WHERE CONVERT(DATE,P.CreatedDateTime) = @rFeedDate AND  P.OrgGroupBatchId=@rOrgGroupBatchId
		
		UNION ALL
		
		-- Blog
		SELECT B.Id,B.Title,B.Remark,20099 AS ScreenId,B.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tBlog B INNER JOIN 
		(SELECT BS.BlogId FROM sCommunication.tBlogScope BS  WHERE
		(
		(BS.SourceTypeId = 2021 AND BS.SourceId =@rOrgId)
		)
		) D ON D.BlogId= B.Id
		INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
		WHERE CONVERT(DATE,B.CreatedDateTime) = @rFeedDate AND  B.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- News
		SELECT N.Id,N.Title,N.Remark,20104 AS ScreenId,N.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tNews N INNER JOIN 
		(SELECT NS.NewsId FROM sCommunication.tNewsScope NS  WHERE
		(
		(NS.SourceTypeId = 2021 AND NS.SourceId =@rOrgId)
		)
		) D ON D.NewsId= N.Id
		INNER JOIN sSecurity.tUser U ON U.Id=N.CreatedUserId
		WHERE CONVERT(DATE,N.CreatedDateTime) = @rFeedDate AND  N.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- Gallery
		SELECT PCM.Id,PCM.Title,PCM.Remark,20183 AS ScreenId,PCM.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPhotoCategoryMaster PCM INNER JOIN 
		(SELECT PCS.PhotoCategoryId FROM sCommunication.tPhotoCategoryMaster PCM
		INNER JOIN sCommunication.tPhotoCategoryScope PCS ON PCM.Id = PCS.PhotoCategoryId
		WHERE
		((PCM.ScopeSourceTypeId = 2021 AND PCS.ScopeSourceId =@rOrgId))
		OR ((PCM.ScopeSourceTypeId = 2017 AND PCS.ScopeSourceId =@lDepartmentId))
		) D ON D.PhotoCategoryId= PCM.Id
		INNER JOIN sSecurity.tUser U ON U.Id=PCM.CreatedUserId
		WHERE CONVERT(DATE,PCM.CreatedDateTime) = @rFeedDate AND  PCM.OrgGroupId=@rOrgGroupId 
		
		UNION ALL
		
		-- Activity
		SELECT A.Id,A.Title,A.Remark,20209 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sActivity.tActivity A INNER JOIN 
		(SELECT AP.ActivityId FROM sActivity.tActivityParticipant AP  WHERE
		(
		(AP.SourceTypeId = 95 AND AP.SourceId =@lSourceId)
		)
		) D ON D.ActivityId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.CreatedDateTime) = @rFeedDate AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Task
		SELECT A.Id,'Task' AS Title,Remark,20172 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignTask A
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.CreatedDateTime) = @rFeedDate AND  A.OrgId=@rOrgId AND AssignedToSourceTypeId = 95 AND AssignedToSourceId=@lSourceId
		
		UNION ALL
		
		-- Birthday
		SELECT EM.Id,'Birthday' AS Title,FirstName+' '+LastName AS Remark,20577 AS ScreenId,EPD.DateOfBirth AS CreatedDateTime,0 AS CreatedUserId,'' AS CreatedUser FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId 
		WHERE CONVERT(DATE,EPD.DateOfBirth) = @rFeedDate AND  EM.OrgId=@rOrgId AND EM.Id=@lSourceId AND ISNULL(EM.IsOtherUser,0) = 0 

		UNION ALL

		-- Alert
		SELECT AL.Id,AL.AlertSubject as Title,AL.AlertMessage as Remark,0 AS ScreenId,AL.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle FROM sAlert.tAlertLog AL
		INNER JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		WHERE CONVERT(DATE,AL.CreatedDateTime) = @rFeedDate AND  AL.ReceiverSourceId=@lSourceId AND AL.ReceiverSourceTypeId = @lSourceTypeId

		UNION ALL

		-- Notification
		SELECT NF.Id,NF.MessageTitle as Title,NF.NotificationMessage as Remark,0 AS ScreenId,NF.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle FROM sAlert.tNotificationLog NF
		INNER JOIN sSecurity.tUser U ON U.Id=NF.CreatedUserId
		WHERE CONVERT(DATE,NF.CreatedDateTime) = @rFeedDate AND  NF.SourceId=@lSourceId AND NF.SourceTypeId = @lSourceTypeId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pDailyThoughtAssignAdd]
	 @rOrgId int,
	 @rMonth smallint,
	 @rXml nvarchar(MAX),
	 @rSourceId bigint = 0,
	 @rSourceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @StrXML XML  
    SET @StrXML = CAST(@rXml AS XML)  
   
	DECLARE @tDailyThoughtAssign TABLE  
	(  
		Id INT IDENTITY(1, 1),  
		Day SMALLINT,
		DailyThoughtId nvarchar(1000),  
		IsSelect  SMALLINT
	)   
    INSERT INTO @tDailyThoughtAssign  
    SELECT           
            T.c.value('@Day','smallint') AS Day,  
            T.c.value('@DailyThoughtId','nvarchar(1000)') AS DailyThoughtId,  
            T.c.value('@IsSelect','smallint') AS IsSelect             
    FROM   
            @StrXML.nodes('/Table/DailyThought')T(c)  

	Declare @lCount int=1
	WHILE(@lCount <= (SELECT count(*) FROM @tDailyThoughtAssign))                
	BEGIN
		DECLARE @lIsSelect SmallInt,@lDay SmallInt
		DECLARE @lDailyThoughtId nvarchar(1000)

		SELECT @lIsSelect = IsSelect , @lDailyThoughtId = DailyThoughtId,@lDay = Day FROM @tDailyThoughtAssign WHERE Id = @lCount

		IF(@lIsSelect = 1)
		BEGIN
			--IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE DailyThoughtId = @lDailyThoughtId AND Month = @rMonth AND OrgId = @rOrgId AND Day <> @lDay)
			--BEGIN
			--	SELECT -101 AS Result

			--	COMMIT TRANSACTION
			--	RETURN
			--END
			IF NOT EXISTS(SELECT 1 FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](@lDailyThoughtId, ',')))
			BEGIN
				SELECT -102 AS Result

				COMMIT TRANSACTION
				RETURN
			END
			
			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId)
			BEGIN
				UPDATE sCommunication.tDailyThoughtAssign
				SET
				DailyThoughtId = @lDailyThoughtId
				WHERE
				Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId
			END
			ELSE IF NOT EXISTS(SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId)
			BEGIN
				INSERT INTO sCommunication.tDailyThoughtAssign
				(
					DailyThoughtId,
					Day,
					Month,
					OrgId,
					SourceId,
					SourceTypeId	
				)
				VALUES
				(
					@lDailyThoughtId,
					@lDay,
					@rMonth,
					@rOrgId,
					@rSourceId,
					@rSourceTypeId
				)
			END
		END
		ELSE
		BEGIN
			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE  Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId)
			BEGIN
				DELETE FROM sCommunication.tDailyThoughtAssign WHERE Day = @lDay AND Month = @rMonth AND OrgId = @rOrgId AND ISNULL(SourceId,0) = @rSourceId AND ISNULL(SourceTypeId,0) = @rSourceTypeId
			END
		END
		SET @lCount = @lCount + 1
	END
		SELECT 1 AS RESULT
	COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
		SELECT ERROR_MESSAGE() as result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pDailyThoughtAssignGet]
	 @rOrgGroupId int,
	 @rOrgId int,
	 @rDay smallint,
	 @rMonth smallint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	 SELECT 
			DTM.Id,
			DTM.Title,
			DTM.Remark,
			CASE WHEN EXISTS(SELECT AutoId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND DailyThoughtId = DTM.Id) THEN '1' ELSE '0' END AS IsAssign
	  FROM 
			sCommunication.tDailyThoughtMaster DTM
	  WHERE 
            (DTM.OrgGroupId = @rOrgGroupId)
			AND DTM.IsObsolete = 0
	  ORDER BY DTM.Number ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pDailyThoughtAssignSearchGet]
	 @rOrgId int,
	 @rDay smallint,
	 @rMonth smallint,
	 @rDivisionId int = 0,
	 @rClassId int = 0,
	 @rDepartmentId int = 0,
	 @rSourceTypeId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rSourceTypeId = 2003)
	BEGIN
		IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND SourceTypeId = 2005 AND SourceId = @rDivisionId)
		BEGIN
			SELECT
				DTA.DailyThoughtId AS Id,
				STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
				STUFF ((SELECT ', '+ Title
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
				STUFF ((SELECT ', '+ Remark
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
			FROM 
				sCommunication.tDailyThoughtAssign DTA 
			WHERE DTA.OrgId = @rOrgId 
				AND DTA.Day = @rDay AND DTA.Month = @rMonth 
				AND DTA.SourceTypeId = 2005 
				AND DTA.SourceId = @rDivisionId
			ORDER BY DTA.AutoId DESC
		END

		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND SourceTypeId = 2016 AND SourceId = @rClassId)
		BEGIN
			SELECT
				DTA.DailyThoughtId AS Id,
				STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
				STUFF ((SELECT ', '+ Title
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
				STUFF ((SELECT ', '+ Remark
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
			FROM 
				sCommunication.tDailyThoughtAssign DTA 
			WHERE DTA.OrgId = @rOrgId 
				AND DTA.Day = @rDay AND DTA.Month = @rMonth 
				AND DTA.SourceTypeId = 2016 
				AND DTA.SourceId = @rClassId
			ORDER BY DTA.AutoId DESC
		END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND SourceTypeId = 2021 AND SourceId = @rOrgId)
		BEGIN
			SELECT
				DTA.DailyThoughtId AS Id,
				STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
				STUFF ((SELECT ', '+ Title
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
				STUFF ((SELECT ', '+ Remark
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
			FROM 
				sCommunication.tDailyThoughtAssign DTA 
			WHERE DTA.OrgId = @rOrgId 
				AND DTA.Day = @rDay AND DTA.Month = @rMonth 
				AND DTA.SourceTypeId = 2021 
				AND DTA.SourceId = @rOrgId
			ORDER BY DTA.AutoId DESC
		END
	END

	IF(@rSourceTypeId = 95)
	BEGIN
		IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND SourceTypeId = 2017 AND SourceId = @rDepartmentId)
		BEGIN
			SELECT
				DTA.DailyThoughtId AS Id,
				STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
				STUFF ((SELECT ', '+ Title
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
				STUFF ((SELECT ', '+ Remark
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
			FROM 
				sCommunication.tDailyThoughtAssign DTA 
			WHERE DTA.OrgId = @rOrgId 
				AND DTA.Day = @rDay AND DTA.Month = @rMonth 
				AND DTA.SourceTypeId = 2017 
				AND DTA.SourceId = @rDepartmentId
			ORDER BY DTA.AutoId DESC
		END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @rDay AND Month = @rMonth AND SourceTypeId = 2021 AND SourceId = @rOrgId)
		BEGIN
			SELECT
				DTA.DailyThoughtId AS Id,
				STUFF ((SELECT ','+ CAST(Number AS nvarchar(20))
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Number,
				STUFF ((SELECT ', '+ Title
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Title,
				STUFF ((SELECT ', '+ Remark
				FROM sCommunication.tDailyThoughtMaster WHERE Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ',')) 
				FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'), 1,1,SPACE(0)) AS Remark 
			FROM 
				sCommunication.tDailyThoughtAssign DTA 
			WHERE DTA.OrgId = @rOrgId 
				AND DTA.Day = @rDay AND DTA.Month = @rMonth 
				AND DTA.SourceTypeId = 2021 
				AND DTA.SourceId = @rOrgId
			ORDER BY DTA.AutoId DESC
		END
	END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pDailyThoughtGet]

	@rOrgId int,
	@rSourceId bigint = 0,
	@rSourceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @lDay smallint , @lMonth smallint
	DECLARE @lOrgGroupId Int
	DECLARE @lDailyThoughtId nvarchar(100)
	DECLARE @lFinalDailyThoughtId nvarchar(100) = ''

	SET @lDay = DAY(sCommon.fGetDate())
	SET @lMonth = MONTH(sCommon.fGetDate())
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

	IF(@rSourceTypeId = 2001)
	BEGIN
		DECLARE @lClassId int,@lDivisionId int,@lOrgId int

		SELECT @lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId
		 FROM sStudent.tAcademic A 
		 WHERE A.Id = @rSourceId  

		 IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2005 AND SourceId = @lDivisionId)
			BEGIN --Check If DailyThought Assign to particular day
				SELECT 
					DTM.Id,
					DTM.Number,
					DTM.Title,
					DTM.Remark,
					DTS.Title As [Subject]
				FROM
					sCommunication.tDailyThoughtAssign DTA
					INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
				WHERE
					DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND SourceTypeId = 2005 AND SourceId = @lDivisionId

				SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2005 AND SourceId = @lDivisionId
			END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2016 AND SourceId = @lClassId)
			BEGIN --Check If DailyThought Assign to particular day
					SELECT 
						DTM.Id,
						DTM.Number,
						DTM.Title,
						DTM.Remark,
						DTS.Title As [Subject]
					FROM
						sCommunication.tDailyThoughtAssign DTA
						INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
						INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
					WHERE
						DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND SourceTypeId = 2016 AND SourceId = @lClassId

					SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2016 AND SourceId = @lClassId
				END
		ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND (SourceTypeId = 2021 AND SourceId = @lOrgId))
			BEGIN --Check If DailyThought Assign to particular day

					SELECT 
						DTM.Id,
						DTM.Number,
						DTM.Title,
						DTM.Remark,
						DTS.Title As [Subject]
					FROM
						sCommunication.tDailyThoughtAssign DTA
						INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
						INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
					WHERE
						DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND (SourceTypeId = 2021 AND SourceId = @lOrgId)

					SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND (SourceTypeId = 2021 AND SourceId = @lOrgId)
			END
	END
	
	IF(@rSourceTypeId = 95)
	BEGIN

		DECLARE @lDepartmentId int
		SELECT @lDepartmentId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rSourceId 

		-- Added IF block for Department wise assigned data to employee for Mantis: 0029003 by Foram
		IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2017 AND SourceId = @lDepartmentId)
		BEGIN --Check If DailyThought Assign to particular day Departmentwise
			SELECT 
				DTM.Id,
				DTM.Number,
				DTM.Title,
				DTM.Remark,
				DTS.Title As [Subject]
			FROM
				sCommunication.tDailyThoughtAssign DTA
				INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
				INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
			WHERE
				DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND SourceTypeId = 2017 AND SourceId = @lDepartmentId

			SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND SourceTypeId = 2017 AND SourceId = @lDepartmentId
		END

		IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0)))
		BEGIN --Check If DailyThought Assign to particular day
			SELECT 
				DTM.Id,
				DTM.Number,
				DTM.Title,
				DTM.Remark,
				DTS.Title As [Subject]
			FROM
				sCommunication.tDailyThoughtAssign DTA
				INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
				INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
			WHERE
				DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))

			SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))
		END
	END
	 
	IF(@lFinalDailyThoughtId = '')
	BEGIN 
		IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0)))
			BEGIN --Check If DailyThought Assign to particular day
			     
				SELECT 
					DTM.Id,
					DTM.Number,
					DTM.Title,
					DTM.Remark,
					DTS.Title As [Subject]
				FROM
					sCommunication.tDailyThoughtAssign DTA
					INNER JOIN sCommunication.tDailyThoughtMaster DTM ON DTM.Id IN (SELECT item FROM [sCommon].[fnSplit](DTA.DailyThoughtId, ','))
					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
				WHERE
					DTA.OrgId = @rOrgId AND DTA.Day = @lDay AND DTA.Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))

				SELECT @lFinalDailyThoughtId = DailyThoughtId FROM sCommunication.tDailyThoughtAssign WHERE OrgId = @rOrgId AND Day = @lDay AND Month = @lMonth AND ((SourceTypeId = 2021 AND SourceId = @rOrgId) OR (ISNULL(SourceId,0)=0 AND ISNULL(SourceTypeId,0) = 0))


			END
		--Added for mantis 0029003: 3rd point by Foram (Reason: If Daily Thought Master is not there then no need it in temp table also)
		--ELSE IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtTemp WHERE CONVERT(NVARCHAR,CreatedDateTime,105) = CONVERT(NVARCHAR,sCommon.fGetDate(),105) AND OrgGroupId = @lOrgGroupId)
		--BEGIN --If DailyThought loaded in temp table for particular day 
		--	SELECT 
		--		DTM.Id,
		--		DTM.Number,
		--		DTM.Title,
		--		DTM.Remark,
		--		DTS.Title As [Subject]
		--	FROM
		--		sCommunication.tDailyThoughtTemp DTM 
		--		INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
		--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = DTM.OrgGroupId
		--		INNER JOIN sCommunication.tDailyThoughtMaster DM ON DM.Id = DTM.Id   -- Added Join for mantis 0029003: 3rd point by Foram
		--	WHERE
		--		OM.Id = @rOrgId

		--	-- Added for mantis 0029003: 3rd point by Foram (Reason: If Daily Thought Master is not there then no need it in temp table also)
		--	DELETE DTM 
		--	FROM
		--		sCommunication.tDailyThoughtTemp DTM 
		--		INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
		--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = DTM.OrgGroupId
		--		LEFT JOIN sCommunication.tDailyThoughtMaster DM ON DM.Id = DTM.Id   -- Added Join for mantis 0029003: 3rd point by Foram
		--	WHERE
		--		OM.Id = @rOrgId AND DM.Id IS NULL

		--END
		--ELSE
		--BEGIN --If DailyThought not Assign to particular day than insert into temp table and select from that
		--	DELETE FROM sCommunication.tDailyThoughtTemp WHERE OrgGroupId = @lOrgGroupId

		--	IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0)
		--	BEGIN
				
		--		SELECT Top 1 @lDailyThoughtId = Id FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0 ORDER BY CreatedDateTime ASC

		--		INSERT INTO sCommunication.tDailyThoughtTemp 
		--		  (
		--			Id,
		--			DailyThoughtSubjectId,
		--			Title,
		--			Remark,
		--			IsObsolete,
		--			Number,
		--			OrgGroupId,
		--			IsRead,
		--			CreatedUserId,
		--			CreatedDateTime,
		--			UpdatedUserId,
		--			UpdatedDateTime
		--		  )
		--		  SELECT
		--			Id,
		--			DailyThoughtSubjectId,
		--			Title,
		--			Remark,
		--			IsObsolete,
		--			Number,
		--			OrgGroupId,
		--			IsRead,
		--			CreatedUserId,
		--			sCommon.fGetDate(),
		--			UpdatedUserId,
		--			UpdatedDateTime
		--		  FROM 
		--			sCommunication.tDailyThoughtMaster
		--		  WHERE 
		--			Id = @lDailyThoughtId

		--		  UPDATE 
		--			sCommunication.tDailyThoughtMaster 
		--		  SET 
		--			IsRead = 1 
		--		  WHERE 
		--			Id = @lDailyThoughtId

		--		  SELECT 
		--			DTM.Id,
		--			DTM.Number,
		--			DTM.Title,
		--			DTM.Remark,
		--			DTS.Title As [Subject]	
		--		  FROM
		--			sCommunication.tDailyThoughtTemp DTM 
		--			INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
		--		  WHERE
		--			DTM.OrgGroupId = @lOrgGroupId
		--	END
		--	ELSE
		--	BEGIN --If All thought read than change flag IsRead to false in all thought and than assign in temp table
		--			UPDATE sCommunication.tDailyThoughtMaster SET IsRead = 0 WHERE OrgGroupId = @lOrgGroupId
					
		--			IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0)
		--			BEGIN
						
		--				SELECT Top 1 @lDailyThoughtId =(Id) FROM sCommunication.tDailyThoughtMaster WHERE OrgGroupId = @lOrgGroupId AND IsObsolete = 0 AND IsRead = 0 ORDER By CreatedDateTime ASC
				
		--				INSERT INTO sCommunication.tDailyThoughtTemp 
		--				  (
		--					Id,
		--					DailyThoughtSubjectId,
		--					Title,
		--					Remark,
		--					IsObsolete,
		--					Number,
		--					OrgGroupId,
		--					IsRead,
		--					CreatedUserId,
		--					CreatedDateTime,
		--					UpdatedUserId,
		--					UpdatedDateTime
		--				  )
		--				  SELECT
		--					Id,
		--					DailyThoughtSubjectId,
		--					Title,
		--					Remark,
		--					IsObsolete,
		--					Number,
		--					OrgGroupId,
		--					IsRead,
		--					CreatedUserId,
		--					sCommon.fGetDate(),
		--					UpdatedUserId,
		--					UpdatedDateTime
		--				  FROM 
		--					sCommunication.tDailyThoughtMaster
		--				  WHERE 
		--					Id = @lDailyThoughtId

		--				  UPDATE 
		--					sCommunication.tDailyThoughtMaster 
		--				  SET 
		--					IsRead = 1 
		--				  WHERE 
		--					Id IN (@lDailyThoughtId)

		--				  SELECT 
		--					DTM.Id,
		--					DTM.Number,
		--					DTM.Title,
		--					DTM.Remark,
		--					DTS.Title As [Subject]
		--				  FROM
		--					sCommunication.tDailyThoughtTemp DTM 
		--					INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTS ON DTM.DailyThoughtSubjectId = DTS.Id
		--				  WHERE
		--					DTM.OrgGroupId = @lOrgGroupId
		--			END
		--	END
		--END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[pDailyThoughtMasterAdd]
	 
        @rId bigint = 0,
		@rDailyThoughtSubjectId int = 0,
		@rTitle nvarchar(100),
		@rRemark nvarchar(max),
		@rDailyThoughtDate date = '',
		@rNumber int = 0,
		@rIsObsolete bit =0,
		@rCreatedUserId bigint,
		@rOrgGroupId int,
		@rIsRead bit = 0 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	 IF EXISTS (SELECT 1 FROM sCommunication.tDailyThoughtMaster WHERE Number = @rNumber AND OrgGroupId = @rOrgGroupId AND Id != @rId)
	 BEGIN
		SELECT -11 AS Result
	 END
	 ELSE
	 BEGIN

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tDailyThoughtMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sCommunication.tDailyThoughtMaster
		(
			Id
		   ,DailyThoughtSubjectId
		   ,Title
		   ,Remark
		   ,Number
		   ,IsObsolete
		   ,IsRead
		   ,CreatedUserId
           ,CreatedDateTime
           ,OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rDailyThoughtSubjectId,
			@rTitle,
			@rRemark,
			@rNumber,
			@rIsObsolete,
			@rIsRead,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tDailyThoughtMaster
	    SET
		    Title = @rTitle
		   ,DailyThoughtSubjectId=@rDailyThoughtSubjectId
		   ,Remark=@rRemark
		   ,Number=@rNumber		   
		   ,IsObsolete = @rIsObsolete
		   ,UpdatedUserId = @rCreatedUserId
           ,UpdatedDateTime = sCommon.fGetDate()

	      WHERE Id = @rId
	      
	      SELECT 1 AS Result
	 END  	
	END
	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pDailyThoughtMasterGet]
	 @rTitle nvarchar(100) ='',
	 @rDailyThoughtSubjectId int = 0,
	 @rOrgGroupId int,
	 @rId bigint = 0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
			DTM.Id as Id,
			DTM.DailyThoughtSubjectId,
			DTM.Title,
			DTM.CreatedDateTime,
			DTM.IsObsolete as IsObsolete,
			DTM.Remark,
			DTM.Number,
			DTSM.Title AS DailyThoughtSubject
	  FROM 
			sCommunication.tDailyThoughtMaster DTM
			INNER JOIN sCommunication.tDailyThoughtSubjectMaster DTSM ON DTSM.Id = DTM.DailyThoughtSubjectId
	  WHERE 
				((DTM.Title like '%' + @rTitle + '%') OR (ISNULL(@rTitle,'') = ''))
			AND ((DTM.DailyThoughtSubjectId = @rDailyThoughtSubjectId) OR (ISNULL(@rDailyThoughtSubjectId,0) = 0))
			AND ((DTM.OrgGroupId = @rOrgGroupId))
			AND ((DTM.Id = @rId) OR (@rId = 0))
	 ORDER BY
			DTM.CreatedDateTime DESC
		
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pDailyThoughtSubjectMasterAdd]
	 
	@rId int = 0,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rOrgGroupId int,
	@rIsObsolete bit,
	@rOrderIndex smallint,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sCommunication.tDailyThoughtSubjectMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sCommunication.tDailyThoughtSubjectMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		 
		If Exists(select Id from sCommunication.tDailyThoughtSubjectMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -105 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sCommunication.tDailyThoughtSubjectMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sCommunication.tDailyThoughtSubjectMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		 
		If Exists(select Id from sCommunication.tDailyThoughtSubjectMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -105 as Result
			RETURN
		END 
	END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tDailyThoughtSubjectMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommunication.tDailyThoughtSubjectMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rOrderIndex,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tDailyThoughtSubjectMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			OrgGroupId =@rOrgGroupId
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result

		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pDailyThoughtSubjectMasterGet]
	 @rId int = 0,
	 @rCode nvarchar(20)='',
	 @rTitle nvarchar(100)='',
	 @rOrgGroupId int,
	 @rIsSearch int = 1

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	IF(@rIsSearch = 1)
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	

	SELECT 
			DSM.Id,
			DSM.Code,
			DSM.Title,
			DSM.OrgGroupId,
			DSM.IsObsolete,
			DSM.OrderIndex,
			DSM.CreatedUserId,
			DSM.CreatedDateTime,
			DSM.UpdatedUserId,
			DSM.UpdatedDateTime
	  FROM 
			sCommunication.tDailyThoughtSubjectMaster DSM 
	  WHERE 
            ((DSM.Id = @rId) OR (@rId = 0))
			AND ((DSM.Code LIKE @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND ((DSM.Title LIKE @rTitle) OR (ISNULL(@rTitle,'') = '')) 
			AND (DSM.OrgGroupId=@rOrgGroupId)
	  ORDER BY DSM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionActivitiesGet]
	 --@rCreatedUserId bigint
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			D.Id,
			D.DiscussionGroupId,
			D.Title,
			DC.Remark,
			U.DisplayTitle AS CommentCreatedUserName,
			DC.CreatedDateTime AS CommentCreatedDateTime
  FROM 
            sCommunication.tDiscussionComment DC
            INNER JOIN sCommunication.tDiscussion D ON D.Id=DC.DiscussionId 
            --AND B.CreatedUserId=@rCreatedUserId
            INNER JOIN sSecurity.tUser U ON U.Id=DC.CreatedUserId
 -- WHERE 
	--	((D.BatchId=@rBatchId) OR (@rBatchId=0))
	----(BC.CreatedUserId!=@rCreatedUserId)
	--order by DC.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionAdd]
	 
        @rId bigint,
        @rDiscussionGroupId bigint,
		@rTitle nvarchar(200),
		@rRemark nvarchar(500),
		@rCreatedUserId bigint,
		@rOrgId smallint,
		@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tDiscussion where Code=@rCode AND DiscussionGroupId=@rDiscussionGroupId AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tDiscussion where Title=@rTitle AND DiscussionGroupId=@rDiscussionGroupId AND BatchId=@rBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tDiscussion where Code=@rCode AND DiscussionGroupId=@rDiscussionGroupId AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tDiscussion where Title=@rTitle AND DiscussionGroupId=@rDiscussionGroupId AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tDiscussion', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tDiscussion
		(
			Id,
			DiscussionGroupId,
			Title,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			BatchId
		)
	VALUES
		(
			@lNextNumber,
			@rDiscussionGroupId,
			@rTitle,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rBatchId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tDiscussion
	    SET
			DiscussionGroupId=@rDiscussionGroupId,
			Title=@rTitle,
			Remark=@rRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionCommentAdd]
	 
        --@rId bigint,
		@rDiscussionId bigint,
		@rRemark nvarchar(500),
		@rCreatedUserId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	--IF(@rId = 0)	
	--BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tDiscussionComment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tDiscussionComment
		(
			Id,
			DiscussionId,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rDiscussionId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	--END	 

--ELSE
--	 BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  sCommunication.tDiscussionComment
--	    SET
--			DiscussionId=@rDiscussionId,
--			Remark=@rRemark,
--			UpdatedUserId=@rCreatedUserId,
--			UpdatedDateTime=sCommon.fGetDate()
	      
--	      WHERE Id = @rId
--	      SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION
--	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionCommentDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tDiscussionComment where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionCommentGet]
	   @rDiscussionId bigint
	 --@rBatchId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	 
	SELECT 
			DC.Id,
			DC.DiscussionId,
			D.Title,
			D.Remark AS DiscussionRemark,
			--D.BatchId,
		 --   BM.Title AS Batch,
		    DC.Remark,
		    U1.DisplayTitle as DiscussionCreatedUserName,
		    D.CreatedDateTime as DiscussionCreatedDateTime,
		    U2.DisplayTitle as CommentCreatedUserName,
		    DC.CreatedDateTime as CommentCreatedDateTime,
		    D.CreatedUserId AS DiscussionCreatedUserId,
		    DC.CreatedUserId AS CommentCreatedUserId
  FROM 
            sCommunication.tDiscussionComment DC
            INNER JOIN sCommunication.tDiscussion D ON D.Id=DC.DiscussionId
            INNER JOIN sSecurity.tUser U1 ON U1.Id=D.CreatedUserId
            INNER JOIN sSecurity.tUser U2 ON U2.Id=DC.CreatedUserId
  WHERE 
  
      ((DC.DiscussionId = @rDiscussionId) OR (@rDiscussionId = 0))
	--AND ((D.BatchId=@rBatchId) OR (@rBatchId=0)) 
	Order by DC.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionGet]
	 @rId bigint,
	 @rBatchId int,
	 @rDiscussionGroupId bigint,
	 @rTitle nvarchar(200),
	 @rIsSearch bit = 1,
	 @rSourceId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			D.Id,
			D.DiscussionGroupId,
			DG.Title AS DiscussionGroup,
			D.BatchId,
			BM.Title AS Batch,
			D.Title,
		    D.Remark,
		    U.DisplayTitle AS DiscussionCreatedUserName,
		    D.CreatedDateTime AS DiscussionCreatedDateTime,
		    (SELECT ISNULL( Count(1),0) FROM sCommunication.tDiscussionComment DC WHERE DC.DiscussionId = D.Id) AS TotalDiscussionComment
		    
  FROM 
            sCommunication.tDiscussion D
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id=D.BatchId
            INNER JOIN sCommunication.tDiscussionGroup DG ON DG.Id=D.DiscussionGroupId
            INNER JOIN sCommunication.tDiscussionGroupMember DGM ON DGM.DiscussionGroupId=DG.Id AND DGM.SourceTypeId=95 
						AND (DGM.SourceId=@rSourceId)
            INNER JOIN sSecurity.tUser U ON U.Id=D.CreatedUserId
  WHERE 
  
      ((D.Id = @rId) OR (@rId = 0))
	AND ((D.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((D.DiscussionGroupId=@rDiscussionGroupId) OR (@rDiscussionGroupId=0))
	AND ((D.BatchId=@rBatchId) OR (@rBatchId=0))
	
	UNION 
	
	SELECT 
			D.Id,
			D.DiscussionGroupId,
			DG.Title AS DiscussionGroup,
			D.BatchId,
			BM.Title AS Batch,
			D.Title,
		    D.Remark,
		    U.DisplayTitle AS DiscussionCreatedUserName,
		    D.CreatedDateTime AS DiscussionCreatedDateTime,
		    (SELECT ISNULL( Count(1),0) FROM sCommunication.tDiscussionComment DC WHERE DC.DiscussionId = D.Id) AS TotalDiscussionComment
		    
  FROM 
            sCommunication.tDiscussion D
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id=D.BatchId
            INNER JOIN sCommunication.tDiscussionGroup DG ON DG.Id=D.DiscussionGroupId
            INNER JOIN sCommunication.tDiscussionGroupMember DGM ON DGM.DiscussionGroupId=DG.Id AND DGM.SourceTypeId=2001 
						AND (DGM.SourceId=(SELECT AcademicId FROM sStudent.vStudentName WHERE StudentId=@rSourceId AND BatchId = @rBatchId))
            INNER JOIN sSecurity.tUser U ON U.Id=D.CreatedUserId
  WHERE 
  
      ((D.Id = @rId) OR (@rId = 0))
	AND ((D.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((D.DiscussionGroupId=@rDiscussionGroupId) OR (@rDiscussionGroupId=0))
	AND ((D.BatchId=@rBatchId) OR (@rBatchId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionGroupAdd]
	 
        @rId bigint,
		@rTitle nvarchar(100),
		@rCreatedUserId bigint,
		@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tDiscussionGroup where Code=@rCode AND OrgId=@rOrgId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tDiscussionGroup where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tDiscussionGroup where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tDiscussionGroup where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tDiscussionGroup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tDiscussionGroup
		(
			Id,
			Title,
			CreatedUserId,
			CreatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tDiscussionGroup
	    SET
			Title=@rTitle,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionGroupDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tDiscussionComment where 
				DiscussionId IN(Select Id from sCommunication.tDiscussion WHERE DiscussionGroupId=@rId)
			Delete from sCommunication.tDiscussion where DiscussionGroupId=@rId
			Delete from sCommunication.tDiscussionGroupMember where DiscussionGroupId=@rId
			Delete from sCommunication.tDiscussionGroup where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionGroupGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100),
	 @rOrgId smallint,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			DG.Id as DiscussionGroupId,
			DG.Title
  FROM 
            sCommunication.tDiscussionGroup DG
  WHERE 
  
      ((DG.Id = @rId) OR (@rId = 0))
	AND ((DG.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND DG.OrgId=@rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionGroupMemberAdd]
			@rDiscussionGroupId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tDiscussionGroupMember where DiscussionGroupId=@rDiscussionGroupId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 

		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select DiscussionGroupId from sCommunication.tDiscussionGroupMember where 
	DiscussionGroupId=@rDiscussionGroupId AND SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tDiscussionGroupMember
			(
				DiscussionGroupId
			   ,SourceTypeId
			   ,SourceId
			)
			VALUES
			(	
				@rDiscussionGroupId
			   ,@rSourceTypeId
			   ,@rSourceId
			)		
			SELECT @rDiscussionGroupId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pDiscussionGroupMemberGet]
	 
	 @rDiscussionGroupId bigint,
	 @rClassId int,
	 @rDepartmentId int,
	 @rOrgId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT   
		--DGM.DiscussionGroupId,
		--'Student' AS SourceType,
		2001 AS SourceTypeId,
		SA.AcademicId as SourceId,
		SA.Code as SourceCode,
		SA.Name as SourceName,
		--SA.ClassName+'-'+SA.DivisionName as DivDept,
		CASE WHEN DGM.SourceId IS NULL OR DGM.DiscussionGroupId!=@rDiscussionGroupId THEN 0 ELSE 1 END AS IsObsolete
		
  FROM sStudent.vStudentAcademic SA
	LEFT JOIN sCommunication.tDiscussionGroupMember DGM ON DGM.SourceId=SA.AcademicId AND DGM.SourceTypeId=2001 AND DGM.DiscussionGroupId=@rDiscussionGroupId
  where 
		(SA.ClassId=@rClassId OR @rClassId=0)
	AND (SA.OrgId=@rOrgId)
	AND SA.IsActiveBatch=1
  
  
	UNION ALL
	
	SELECT  
		--DGM.DiscussionGroupId,
		--'Employee' AS SourceType,
		95 AS SourceTypeId,
		EM.Id as SourceId,
		EM.Code as SourceCode,
		EM.FirstName+' '+EM.LastName as SourceName,
		--ODM.Title as DivDept,
		CASE WHEN DGM.SourceId IS NULL OR DGM.DiscussionGroupId!=@rDiscussionGroupId THEN 0 ELSE 1 END AS IsObsolete
		
  FROM sHrm.tEmployeeMaster EM 
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
    INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId AND (ODM.Id = @rDepartmentId OR @rDepartmentId=0) AND ODM.OrgId=@rOrgId
    LEFT JOIN sCommunication.tDiscussionGroupMember DGM ON DGM.SourceId=EM.Id AND DGM.SourceTypeId=95 AND DGM.DiscussionGroupId=@rDiscussionGroupId
	WHERE ISNULL(EM.IsOtherUser,0) = 0 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pEbookAdd]
	 
        @rId bigint,
		@rTitle nvarchar(100),
		@rRemark nvarchar(200),
		@rOrgGroupId smallint,
		@rOrgGroupBatchId int,
		@rCreatedUserId bigint,
		@rCreatedDateTime date,
		@rUpdateduserId bigint=0,
		@rUpdatedDateTime date=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tCircular where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tEbook where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tCircular where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tEbook where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tEbook', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tEbook
		(
			Id,
			Title,
			Remark,
			OrgGroupId,
			OrgGroupBatchId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			@rCreatedDateTime
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tEbook
	    SET
			Title=@rTitle,
			
			Remark=@rRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			
	      
	      WHERE Id = @rId
	      
	      --DELETE FROM sCommunication.tCircularView WHERE CircularId=@rId
	      
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	
	
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pEbookDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			--Delete from sCommunication.tCircularView where CircularId=@rId
			--Delete from sCommunication.tCircularScope where CircularId=@rId
			Delete from sCommunication.tEbook where Id=@rId
		COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION		
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pEbookGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100),
	 @rOrgGroupBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			Id,
			Title,
			Remark,
			OrgGroupId,
			OrgGroupBatchId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		    
  FROM 
            sCommunication.tEbook
            
  WHERE 
  
		((Id = @rId) OR (@rId = 0))
	AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	ORDER BY CreatedDateTime DESC
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pEbookListGet]
	 
	 @rOrgGroupBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int
	 --@rSyncedCircularId bigint = 0
	 	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	 DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	
	if @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
	
		--DECLARE @lDepartmentId int,@lOrgId int,@lDepartmentId int
		
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id 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 	
			C.Id as EbookId,
			C.Title,
			C.Remark,
			C.CreatedDateTime,
			C.UpdatedDateTime
			  
	 FROM 
            sCommunication.tEbook C 
            INNER JOIN (SELECT CS.EbookId FROM sCommunication.tEbookScope CS
             WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 95 AND CS.SourceId =@lEmployeeId)))D
				ON D.EbookId= C.Id
             
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            
           	ORDER BY C.UpdatedDateTime DESC
			
	
 END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 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 	
			C.Id as EbookId,
			C.Title,
			C.Remark,
			C.CreatedDateTime,
			C.UpdatedDateTime
	 FROM 
            sCommunication.tEbook C   
            INNER JOIN (SELECT CS.EbookId FROM sCommunication.tEbookScope 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) ))D
				ON D.EbookId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
			ORDER BY C.UpdatedDateTime DESC

 END
 ELSE
  --For Other Users
 BEGIN
 
 SELECT 	
			C.Id as EbookId,
			C.Title,
			C.Remark,
			C.CreatedDateTime,
			C.UpdatedDateTime 
	 FROM 
            sCommunication.tEbook C     
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
           
           ORDER BY C.UpdatedDateTime DESC

 
 	--SELECT 	
		--	C.Id as CircularId,
		--	C.Title,
		--	C.Remark,
		--	C.StartDate,
		--	CV.UserId,
		--	U.DisplayTitle as CreatedUserName	    
	 --FROM 
  --          sCommunication.tCircular C       
  --          LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
  --          INNER JOIN sCommunication.tCircularScope CS ON CS.CircularId=C.Id 
  --          INNER JOIN ( SELECT A.DivisionId FROM sStudent.tAcademic A            
  --           WHERE A.StudentId = @rUserSourceId ) D
  --          ON D.DivisionId =  CS.SourceId AND CS.SourceTypeId = 2005
  --          INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
  --          INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
  --          WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
  --          Order by C.CreatedDateTime DESC


 END
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pEbookScopeAdd]
			@rEbookId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tEbookScope where EbookId=@rEbookId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 

		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select EbookId from sCommunication.tEbookScope where EbookId=@rEbookId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tEbookScope
			(
				EbookId
			   ,SourceTypeId
			   ,SourceId
			)
			VALUES
			(	
				@rEbookId
			   ,@rSourceTypeId
			   ,@rSourceId
			)		
			SELECT @rEbookId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pEbookScopeGet]
	 @rEbookId bigint
	 --@rBatchId int
	 --@rOrgId smallint,
	 --@rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
				SELECT
			 CS.EbookId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType
			 
			FROM sCommunication.tEbookScope CS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON CS.SourceId=OM.Id
			WHERE CS.EbookId=@rEbookId AND CS.SourceTypeId=2021

			UNION ALL

			SELECT
			 CS.EbookId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType
			 
			FROM sCommunication.tEbookScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.Id
			WHERE CS.EbookId=@rEbookId AND CS.SourceTypeId=2004

			UNION ALL

			SELECT
			 CS.EbookId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType
			 
			FROM sCommunication.tEbookScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id
			WHERE CS.EbookId=@rEbookId AND CS.SourceTypeId=2016

			UNION ALL

			SELECT
			 CS.EbookId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle +'-'+ DM.DisplayTitle AS Source,
			 'Division' AS SourceType
			 
			FROM sCommunication.tEbookScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.SourceId=DM.Id
			--Add by Dhananjay Mantis 0034410
			Inner JOIN sSetup.tClassMaster CM 
				ON DM.ClassId=CM.Id
			--Add by Dhananjay Mantis 0034410
			WHERE CS.EbookId=@rEbookId AND CS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.EbookId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType
			 
			FROM sCommunication.tEbookScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id	
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			WHERE CS.EbookId=@rEbookId AND CS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.EbookId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType
			 
			FROM sCommunication.tEbookScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1
			WHERE CS.EbookId=@rEbookId AND CS.SourceTypeId=2001
			
			

			--SELECT
			-- CS.CircularId,
			-- CS.SourceTypeId,
			-- CS.SourceId,
			-- SA.Name AS Source,
			-- 'Student' AS SourceType
			 
			--FROM sCommunication.tCircularScope CS
			--INNER JOIN  sStudent.vStudentAcademic SA
			--	ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1
			--WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2003
				





	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pEbookScopeRemove]
			@rEbookId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	Delete from sCommunication.tEbookScope where EbookId=@rEbookId AND SourceTypeId=@rSourceTypeId
      AND SourceId=@rSourceId
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
             
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pEbookScopeValidate]
	 
        @rEbookId bigint,
		@rSourceTypeId smallint,
		@rSourceId bigint
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2004 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tEbookScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.EbookId=@rEbookId)
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tEbookScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2004
				where DM.OrgId=@rSourceId  AND CS.EbookId=@rEbookId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tEbookScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.EbookId=@rEbookId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tEbookScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.EbookId=@rEbookId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tEbookScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.EbookId=@rEbookId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2004) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tEbookScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.EbookId=@rEbookId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tEbookScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.EbookId=@rEbookId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tEbookScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.EbookId=@rEbookId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tEbookScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.EbookId=@rEbookId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 			
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tEbookScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tEbookScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2004
			where CM.Id=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tEbookScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tEbookScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tEbookScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tEbookScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2004
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tEbookScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tEbookScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tEbookScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tEbookScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2004
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tEbookScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tEbookScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.EbookId=@rEbookId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
			select 1 as Result,'' AS Msg
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[peContentAdd] 
			
           @rSourceTypeId smallint
           ,@rSourceId bigint           
           ,@rAssignId int,
		   @rPathName nvarchar(500),
		   @reContentTypeId int,
		   @rTitle nvarchar(200) = '',
		   @rRemark nvarchar(500) = '',
		   @rOrgGroupBatchId int = 0,
		   @rIsBatchIndependent bit = 0,
		   @rContentSourceId int = 0,
		   @rCreatedUserId bigint = 0
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount int
BEGIN 

set @lCount =  ( select ISNULL(COUNT(1),0) from sCommunication.teContent where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND AssignedToId=@rAssignId AND  [PathName]= @rPathName)
   
	If (@lCount <> 0)
		BEGIN
			SELECT -11 AS RESULT
			--UPDATE sCommunication.teContent SET SourceTypeId=@rSourceTypeId , SourceId=@rSourceId , [PathName]=@rPathName,AssignedToId=@rAssignId,eContentTypeId = @reContentTypeId			   
			--,ContentTypeSourcetId=  @rContentSourceId,Title=@rTitle,Remark=@rRemark,IsBatchIndependent=@rIsBatchIndependent
			--where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND AssignedToId=@rAssignId AND  [PathName]= @rPathName
			--SELECT 1 AS Result
	  END 
	ELSE
			
			INSERT INTO sCommunication.teContent
			(
				SourceTypeId
			   ,SourceId
			   ,AssignedToId
			   ,eContentTypeId
			   ,ContentTypeSourcetId
			   ,PathName
			   ,Title
			   ,Remark
			   ,IsBatchIndependent
			   ,OrgGroupBatchId
			   ,CreatedUserId
			   ,CreatedDateTime
			)
			VALUES
			(	@rSourceTypeId
			   ,@rSourceId
			   ,@rAssignId
			   ,@reContentTypeId
			   ,@rContentSourceId
			   ,@rPathName
			   ,@rTitle
			   ,@rRemark
			   ,@rIsBatchIndependent
			   ,@rOrgGroupBatchId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			)		
			SELECT 1 AS Result
	END
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[peContentGet] 
	@rAssignId int = 0,
	@rOrgGroupId int = 0,
	@reContentType int = 0,
	@rTitle nvarchar(200) = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
		SELECT * FROM (SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CM.Title AS eContentType,OM.DisplayTitle AS OrgName,'' AS ClassDepartment, 'Organization' AS SourceType,OM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId INNER JOIN sCommunication.teContentTypeMaster CM ON VP.eContentTypeId = CM.Id WHERE VP.SourceTypeId=2021 

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CM.Title AS eContentType,OM.DisplayTitle AS OrgName,DM.Title AS ClassDepartment, 'Department' AS SourceType,DM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CM ON VP.eContentTypeId = CM.Id
WHERE VP.SourceTypeId=2017

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CTM.Title AS eContentType,OM.DisplayTitle AS OrgName,DM.Title AS ClassDepartment, 'Class' AS SourceType,CM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sSetup.tClassMaster CM ON VP.SourceId=CM.Id
INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CTM ON VP.eContentTypeId = CTM.Id
WHERE VP.SourceTypeId=2016

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CTM.Title AS eContentType,OM.DisplayTitle AS OrgName,DMast.Title AS ClassDepartment, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sSetup.tDivisionMaster DM ON VP.SourceId=DM.Id
INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CTM ON VP.eContentTypeId = CTM.Id	
WHERE VP.SourceTypeId=2005

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CM.Title AS eContentType,OM.DisplayTitle AS OrgName,SA.ClassName+' - '+SA.DivisionName AS ClassDepartment, 'Student' AS SourceType,
[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sStudent.tStudentMaster SM ON VP.SourceId=SM.Id
INNER JOIN  sStudent.vStudentAcademic SA ON VP.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CM ON VP.eContentTypeId = CM.Id		
WHERE VP.SourceTypeId=2003

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CM.Title AS eContentType,OM.DisplayTitle AS OrgName,SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,'Student' AS SourceType,SA.Name AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sStudent.vStudentAcademic SA	ON VP.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CM ON VP.eContentTypeId = CM.Id			
WHERE VP.SourceTypeId=2001 

UNION ALL

SELECT VP.SourceTypeId, VP.SourceId, VP.AssignedToId,VP.eContentTypeId,VP.Title AS Title,VP.Remark AS Remark,VP.IsBatchIndependent AS BatchIndependent,CM.Title AS eContentType,OM.DisplayTitle AS OrgName,vEC.DepartmentName AS ClassDepartment,'Employee' AS SourceType,vEC.FirstName +' '+ vEC.LastName AS Source,
CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,VP.PathName,OGM.Id AS OrgGroupId,VP.CreatedDateTime
FROM sCommunication.teContent VP
INNER JOIN sHrm.vEmployeeCommunication vEC ON VP.SourceId=vEC.EmployeeId AND vEC.StatusId=7
INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id
INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
INNER JOIN sCommunication.teContentTypeMaster CM ON VP.eContentTypeId = CM.Id					
WHERE VP.SourceTypeId=95
) tmp
where (tmp.AssignedToId=@rAssignId OR (@rAssignId=0))
AND tmp.OrgGroupId = @rOrgGroupId
AND (tmp.eContentTypeId = @reContentType OR (@reContentType=0))
AND (tmp.Title = @rTitle OR (@rTitle=''))
ORDER BY tmp.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
--exec [sCommunication].[peContentMobileAppGet] 1101,0,2003,1101000000003
CREATE OR ALTER PROCEDURE [sCommunication].[peContentMobileAppGet]
	@rOrgId int=0,
	@rUserId bigint=0,
	@rSourceTypeId int=0,
	@rSourceId bigint =0,
	@reContentTypeId int = 0,
	@rTitle nvarchar(200) = '',
	 @rOrgGroupBatchId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
BEGIN

	if (@rSourceTypeId = 95)
		BEGIN
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id 
		FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD	 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId


		BEGIN

			SELECT * FROM (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName  ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Employee' AS SourceType,EM.FirstName +' '+ EM.LastName AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN [sHrm].[tEmployeeMaster] EM ON CEC.SourceId=EM.Id AND EM.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id					
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  ) econtentList				

				WHERE ((econtentList.SourceTypeId = 2021 AND econtentList.SourceId =@lOrgId) OR
					   (econtentList.SourceTypeId = 2017 AND econtentList.SourceId =@lDepartmentId) OR
					   (econtentList.SourceTypeId = 95 AND econtentList.SourceId =@lEmployeeId))  
					   AND (econtentList.OrgGroupBatchId = @rOrgGroupBatchId OR  @rOrgGroupBatchId = 0)

		UNION

				SELECT * FROM (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName  ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Employee' AS SourceType,EM.FirstName +' '+ EM.LastName AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN [sHrm].[tEmployeeMaster] EM ON CEC.SourceId=EM.Id AND EM.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id					
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND (CEC.IsBatchIndependent = 0)  ) econtentList				
				WHERE ((econtentList.SourceTypeId = 2021 AND econtentList.SourceId =@lOrgId) OR
					   (econtentList.SourceTypeId = 2017 AND econtentList.SourceId =@lDepartmentId) OR
					   (econtentList.SourceTypeId = 95 AND econtentList.SourceId =@lEmployeeId))

				ORDER BY econtentList.CreatedDateTime DESC
					  
			END

		END
	ELSE IF (@rSourceTypeId = 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 = @rSourceId AND A.OrgId=@rOrgId
				--AND BM.OrgGroupBatchId = @rOrgGroupBatchId
        -- Select @lClassId
			BEGIN 		
		
				SELECT * FROM (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Class' AS SourceType,CM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId, 
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tClassMaster CM ON CEC.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDivisionMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,CEC.PathName,
				CEC.AssignedToId,CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.tStudentMaster SM ON CEC.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON CEC.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,SA.Name AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.vStudentAcademic SA	ON CEC.SourceId=SA.StudentId  AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 
				 ) econtentList

				

				WHERE ((econtentList.SourceTypeId = 2021 AND econtentList.SourceId =@lOrgId) OR
					   (econtentList.SourceTypeId = 2017 AND econtentList.SourceId =@lDepartmentId) OR
                       (econtentList.SourceTypeId = 2016 AND econtentList.SourceId =@lClassId) OR
                       (econtentList.SourceTypeId = 2005 AND econtentList.SourceId =@lDivisionId) OR
                       (econtentList.SourceTypeId = 2003 AND econtentList.SourceId =@lStudentId) OR
                       (econtentList.SourceTypeId = 2001 AND econtentList.SourceId =@lAcademicId) AND (econtentList.OrgGroupBatchId = @rOrgGroupBatchId OR  @rOrgGroupBatchId = 0))
					   


		UNION


			SELECT * FROM (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Class' AS SourceType,CM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId, 
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tClassMaster CM ON CEC.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDivisionMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				UNION 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,CEC.PathName,
				CEC.AssignedToId,CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.tStudentMaster SM ON CEC.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON CEC.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				UNION
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,SA.Name AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName, CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.vStudentAcademic SA	ON CEC.SourceId=SA.StudentId  AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='')  AND CEC.IsBatchIndependent = 0
				 ) econtentList

				

				WHERE ((econtentList.SourceTypeId = 2021 AND econtentList.SourceId =@lOrgId) OR
					   (econtentList.SourceTypeId = 2017 AND econtentList.SourceId =@lDepartmentId) OR
                       (econtentList.SourceTypeId = 2016 AND econtentList.SourceId =@lClassId) OR
                       (econtentList.SourceTypeId = 2005 AND econtentList.SourceId =@lDivisionId) OR
                       (econtentList.SourceTypeId = 2003 AND econtentList.SourceId =@lStudentId) OR
                       (econtentList.SourceTypeId = 2001 AND econtentList.SourceId =@lAcademicId) )

				ORDER BY econtentList.CreatedDateTime DESC

			END

		END
		ELSE IF (@rSourceTypeId = 0)
		BEGIN
				SELECT * FROM  (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION
				 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Class' AS SourceType,CM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId, 
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tClassMaster CM ON CEC.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDivisionMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION
				 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,CEC.PathName,
				CEC.AssignedToId,CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.tStudentMaster SM ON CEC.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON CEC.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,SA.Name AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.vStudentAcademic SA	ON CEC.SourceId=SA.StudentId  AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') 

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Employee' AS SourceType,EM.FirstName +' '+ EM.LastName AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN [sHrm].[tEmployeeMaster] EM ON CEC.SourceId=EM.Id AND EM.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id					
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') ) econtentList
				WHERE (econtentList.OrgGroupBatchId = @rOrgGroupBatchId OR  @rOrgGroupBatchId = 0)

		UNION


				SELECT * FROM  (SELECT CEC.SourceTypeId, CEC.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON CEC.SourceId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION
				 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,CEC.PathName ,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND CEC.AssignedToId IN (1,2,3) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Class' AS SourceType,CM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId, 
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tClassMaster CM ON CEC.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sSetup.tDivisionMaster DM ON CEC.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION
				 
				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,CEC.PathName,
				CEC.AssignedToId,CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.tStudentMaster SM ON CEC.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON CEC.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Student' AS SourceType,SA.Name AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN sStudent.vStudentAcademic SA	ON CEC.SourceId=SA.StudentId  AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0

				UNION

				SELECT CEC.SourceTypeId, CEC.SourceId, 'Employee' AS SourceType,EM.FirstName +' '+ EM.LastName AS Source,CEC.PathName,CEC.AssignedToId,
				CASE WHEN CEC.AssignedToId=2 THEN 'Student' WHEN CEC.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee,
				CCTM.Title AS eContentType, CCTM.Id AS eContentTypeId,CEC.Title as eContentTitle, CEC.Remark AS eContentRemark,tSM.Id AS SubjectId,tSM.Title As SubjectName,CEC.OrgGroupBatchId,CEC.CreatedDateTime
				FROM [sCommunication].[teContent] CEC
				INNER JOIN [sCommunication].[teContentTypeMaster] CCTM on CEC.eContentTypeId = CCTM.Id
				INNER JOIN [sHrm].[tEmployeeMaster] EM ON CEC.SourceId=EM.Id AND EM.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id					
				LEFT JOIN [sSetup].[tSubjectMaster] tSM ON tSM.Id = CEC.ContentTypeSourcetId
				WHERE CEC.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) AND ((CEC.eContentTypeId=@reContentTypeId) OR @reContentTypeId=0) AND ((CEC.Title LIKE @rTitle) OR @rTitle='') AND CEC.IsBatchIndependent = 0 ) econtentList
				ORDER BY econtentList.CreatedDateTime DESC
				
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[peContentRemove] 
			
           @rSourceTypeId smallint
           ,@rSourceId bigint           
           ,@rAssignId int,
		   @rPathName nvarchar(500)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN 

	DELETE FROM sCommunication.teContent where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND PathName=@rPathName AND AssignedToId=@rAssignId 


			SELECT 1 AS Result
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sCommunication].[peContentTypeMasterAdd]
	 
        @rId bigint = 0,
		@rCode nvarchar(100), 
		@rTitle nvarchar(100),
		@rIsObsolete bit =0,
		@rCreatedUserId bigint,
		@rOrgGroupId int 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.teContentTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sCommunication.teContentTypeMaster
		(
			Id
		   ,Code
		   ,Title
		   ,IsObsolete
		   ,CreatedUserId
           ,CreatedDateTime
           ,OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.teContentTypeMaster
	    SET
			 
        	 Id = @lNextNumber
		   ,Code = @rCode
		   ,Title = @rTitle
		   ,IsObsolete = @rIsObsolete
		   ,CreatedUserId = @rCreatedUserId
           ,CreatedDateTime = sCommon.fGetDate()

	      WHERE Id = @rId
	      
	      SELECT 1 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[peContentTypeMasterGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rCode nvarchar(100) ='',
	 @rOrgGroupId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	
	SELECT 
			CTM.Id as Id,
			CTM.Code as Code,
			CTM.Title as Title,
			CTM.IsObsolete as IsObsolete
	  FROM 
			[sCommunication].[teContentTypeMaster] CTM
	  WHERE 
				((CTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((CTM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((CTM.OrgGroupId = @rOrgGroupId))
			AND ((CTM.Id = @rId) OR (@rId = 0))
	 ORDER BY
			CTM.Id
		
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

CREATE OR ALTER PROCEDURE [sCommunication].[pEmployeeDocumentUploadAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rDocumentUploadDate date,
		--@rDivisionId int,
		@rIsObsolete bit,
		@rOrgGroupBatchId int,
		@rOrgId int,
		@rCreatedUserId bigint,
		@rEmployeeDocumentTypeId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM sCommunication.tEmployeeDocumentUpload WHERE Title=@rTitle AND EmployeeDocumentTypeId=@rEmployeeDocumentTypeId 
		AND OrgGroupBatchId=@rOrgGroupBatchId AND OrgId=@rOrgId)
		BEGIN
			SELECT -103 AS Result
		RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM sCommunication.tEmployeeDocumentUpload WHERE Title=@rTitle AND EmployeeDocumentTypeId=@rEmployeeDocumentTypeId AND Id<>@rId
		AND OrgGroupBatchId=@rOrgGroupBatchId AND OrgId=@rOrgId)
		BEGIN
			SELECT -103 AS Result
		RETURN
		END
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tEmployeeDocumentUpload', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO [sCommunication].[tEmployeeDocumentUpload]
           ([Id]
           ,[Title]
           ,[DocumentUploadDate]
           ,[EmployeeDocumentTypeId]
           ,[IsObsolete]
           ,[OrgGroupBatchId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
		   ,OrgId)
     VALUES
           (@lNextNumber
           ,@rTitle
           ,@rDocumentUploadDate
           ,@rEmployeeDocumentTypeId
           ,@rIsObsolete
           ,@rOrgGroupBatchId
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate()
		   ,@rOrgId)
	
	END	 
	ELSE
	BEGIN
		SET @lNextNumber = @rId		 

		UPDATE [sCommunication].[tEmployeeDocumentUpload]
		SET [Title] = @rTitle
		  ,[DocumentUploadDate] = @rDocumentUploadDate
		  ,[EmployeeDocumentTypeId] = @rEmployeeDocumentTypeId
		  ,[IsObsolete] = @rIsObsolete
		  ,[OrgGroupBatchId] = @rOrgGroupBatchId
		  --,[CreatedUserId] = <CreatedUserId, bigint,>
		  --,[CreatedDateTime] = <CreatedDateTime, datetime,>
		  ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] = sCommon.fGetDate()
		  ,OrgId=@rOrgId
		WHERE Id = @rId			    
	 
	 END
	   	
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pEmployeeUploadedDocumentGet]
	 @rId int = 0,
	 @rTitle nvarchar(100) = '',
	 @rFromDate date = '',
	 @rToDate date = '',
	 --@rDivisionId int = '',
	 @rOrgGroupBatchId int = 0,
	 @rOrgId int = 0,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF @rIsSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			EDU.Id,
			EDU.Title,			
			EDU.DocumentUploadDate,
			EDU.EmployeeDocumentTypeId,
			EDU.IsObsolete,
			EDU.OrgGroupBatchId
	FROM 
            sCommunication.tEmployeeDocumentUpload EDU
	WHERE 
		((EDU.Id = @rId) OR (@rId = 0))
	AND ((EDU.Title LIKE '%'+@rTitle+'%') OR (ISNULL(@rTitle,'') = ''))
	AND ((EDU.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((EDU.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND EDU.DocumentUploadDate BETWEEN @rFromDate AND @rToDate
	AND ((EDU.DocumentUploadDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((EDU.DocumentUploadDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	ORDER BY EDU.DocumentUploadDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackAdd]
	 
	 	@rOrgGroupBatchId  int,
        @rId bigint=0,
        @rTitle nvarchar(200), 
		@rCreatedUserId bigint ,
		@rIsPublish bit,
		@rIsClose bit,
		@rFeedbackTemplateId bigint ,
		@rOrgGroupId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 DECLARE @lNextNumber BIGINT 

	 
	
	IF(@rId = 0)	
	BEGIN
		if exists(Select 1 from sCommunication.tFeedback where Title=@rTitle AND FeedbackTemplateId=@rFeedbackTemplateId  AND OrgGroupBatchId =@rOrgGroupBatchId )
	BEGIn
		Select -101 As Result
		Return
	END  
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedback', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedback
		(
			Id,
			Title,
			FeedbackTemplateId ,
			IsPublish,
			IsClose,			
			OrgGroupBatchId,
			CreatedUserId,
			CreatedDateTime 
			 
		)
	VALUES
		(
			@lNextNumber,
			@rTitle, 
			@rFeedbackTemplateId,
			@rIsPublish,
			@rIsClose,
			@rOrgGroupBatchId,
			@rCreatedUserId,
			sCommon.fGetDate() 
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sCommunication.tFeedback
	    SET 
			Title = @rTitle, -- Added field for mantis : 31215
			IsPublish=@rIsPublish,
			IsClose=@rIsClose,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackAnalysisDataGet]
	 
	 
	 
	 @rUserSourceId bigint,
	 --@rUserSourceTypeId int ,
	 @rOrgGroupBatchId int,
	 --@rOrgGroupId smallint,
	 @rFeedbackId bigint ,
	  @rFeedbackForId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 SELECT	
		FQ.Id As TempateQuestionId,
					FQ.QuestionNumber,
					FQ.Question ,
					FQ.FeedbackAnswerTypeID,			 
					ISNULL(FQR. FeedbackAnswerTypeDetailId,0) AS FeedbackAnswerTypeDetailId,
					FR.SourceId ,
					 
					case  ISNULL(FATD.Title,'')
					when 
						''
					Then
						ISNULL(FQR.FeedbackAnswerDescription,'')
					Else
						ISNULL(FATD.Title,'') 
					END
					AS FeedbackAnswerDescription
		from sCommunication.tFeedback FB 
		INNER JOIN	sCommunication.tFeedbackTemplateQuestion FQ ON FQ.FeedbackTemplateId = FB.FeedbackTemplateId
		LEFT JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND FR.FeedbackForId =@rFeedbackForId   ANd FR.SourceId=@rUserSourceId
		Left Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id 
		AND FQR.FeedbackTemplateQuestionID = FQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
		LEFT JOIN sCommunication.tFeedbackAnswerTypeMaster FAT ON FAT.Id=FATD.FeedbackAnswerTypeId
		
		--AND FQR.FeedBackResponseId = 1001000000001
		--LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FA ON FA.ID=FQR.FeedbackAnswerTypeDetailId
		WHERE FB.Id = @rFeedbackId ANd OrgGroupBatchId=@rOrgGroupBatchId
	  
		 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackAnalysisGet] 
    @rOrgGroupBatchId INT
	--,@rOrgGroupId smallint
	,@rFeedbackId BIGINT
	,@rFeedbackForId BIGINT
	,@rOrgId INT
	,@rBatchId INT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT
		--A.Id As AcademicId,
		CASE FR.SourceTypeId
			WHEN 2001
				THEN A.Id
			WHEN 95
				THEN EM.Id
			END AS Id
		,CASE FR.SourceTypeId
			WHEN 2001
				THEN SM.Code
			WHEN 95
				THEN EM.Code
			END AS Code
		,CASE FR.SourceTypeId
			WHEN 2001
				THEN SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName
			WHEN 95
				THEN EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName
			END AS Name
		,SM.ID AS StudentID
	FROM sCommunication.tFeedback FB
	INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id
		AND FR.FeedbackForId = @rFeedbackForId
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = FR.SourceId
		AND FR.SourceTypeId = 95
		--AND EM.OrgId = @rOrgId -- Commented for Mantis 0029364 By Foram
	LEFT JOIN sStudent.tAcademic A ON A.Id = FR.SourceId
		AND FR.SourceTypeId = 2001
		--AND A.BatchId = @rBatchId -- Commented for Mantis 0029364 By Foram
	LEFT JOIN sStudent.tStudentMaster SM ON SM.ID = A.StudentID
	WHERE OrgGroupBatchId = @rOrgGroupBatchId
		AND FB.Id = @rFeedbackId
		AND ISNULL(EM.IsOtherUser, 0) = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackAnswerTemplateQuestionGet]
	  
        @rFeedbackTemplateId bigint=0,
        @rId bigint=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		Id,
		QuestionNumber,
		Question ,
		FeedbackTemplateId,
		ISNULL(FeedbackAnswerTypeId,0) AS FeedbackAnswerTypeId ,
		CreatedUserId,
		CreatedDateTime
		
	from sCommunication.tFeedbackTemplateQuestion
	Where  ((FeedbackTemplateId=@rFeedbackTemplateId) OR (@rFeedbackTemplateId=0))
	AND ((Id=@rId) OR (@rId=0))
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackAnswerTypeDetailAdd]
	 
	 	 
         
        @rTitle nvarchar(200),
        @rFeedbackPoint int,
        @rFeedbackAnswerTypeId bigint,
        @rOrgGroupId int,
        @rIsDelete bit,
        @rFeedbackAnswerTypeDetailId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	  
	 IF (@rFeedbackAnswerTypeDetailId=0)
	 BEGIN
	 Declare @lNextNumber bigint
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackAnswerTypeDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	 
	 INSERT INTO sCommunication.tFeedbackAnswerTypeDetail
	 (
		Id,
		FeedbackAnswerTypeId,
		Title,
		FeedbackPoint
	 )
	 Values
	 (
		@lNextNumber,
		@rFeedbackAnswerTypeId,
		@rTitle,
		@rFeedbackPoint
	 )
	  
	 END
	 ELse 
	 BEGIN
	 SET @lNextNumber = @rFeedbackAnswerTypeDetailId
	 IF(@rIsDelete = 0)
	 BEGIN
	 UPDATE sCommunication.tFeedbackAnswerTypeDetail
	 SET
		Title=@rTitle,
		FeedbackPoint = @rFeedbackPoint,
		FeedbackAnswerTypeId=@rFeedbackAnswerTypeId
		WHERE Id=@rFeedbackAnswerTypeDetailId
	 END
	 ELSE 
		DELETE FROM sCommunication.tFeedbackAnswerTypeDetail  WHERE Id =  @rFeedbackAnswerTypeDetailId	
	END
	Select 1 As Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackAnswerTypeDetailGet]
	  
        @rFeedbackAnswerTypeId bigint=0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		Id,
		Title,
		FeedbackAnswerTypeId,
		ISNULL(FeedbackPoint,0) AS FeedbackPoint
		 
		
	from sCommunication.tFeedbackAnswerTypeDetail 
	Where  FeedbackAnswerTypeId=@rFeedbackAnswerTypeId 
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackAnswerTypeMasterAdd]
	 
	 	@rOrgGroupId smallint,
        @rId bigint=0,
        @rCode nvarchar(200),
        @rTitle nvarchar(200),
        @rIsObsolete bit,
		@rCreatedUserId bigint,
		@rFeedBackAnswerGroupMasterId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 DECLARE @lNextNumber BIGINT 

 
	
	
	IF(@rId = 0)	
	BEGIN
		
			if exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Code=@rCode AND ORggroupId=@rOrgGroupId)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Title =@rTitle AND ORggroupId=@rOrgGroupId)
	BEGIN
		Select -102 As Result
		Return
	END
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackAnswerTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedbackAnswerTypeMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			OrgGroupId,
			CreatedUserId,
			CreatedDateTime,
			FeedBackAnswerGroupMasterId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rOrgGroupId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rFeedBackAnswerGroupMasterId
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 
	 if exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Code=@rCode AND ORggroupId=@rOrgGroupId AND Id<>@rId)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackAnswerTypeMaster where Title =@rTitle AND ORggroupId=@rOrgGroupId AND Id<>@rId)
	BEGIN
		Select -102 As Result
		Return
	END
	
	 --SET @lNextNumber = @rId
	    UPDATE  sCommunication.tFeedbackAnswerTypeMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			OrgGroupId=@rOrgGroupId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() ,
			FeedBackAnswerGroupMasterId=@rFeedBackAnswerGroupMasterId,
			IsObsolete = @rIsObsolete
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackAnswerTypeMasterGet]
	 
	 	 
        @rCode nvarchar(200),
        @rTitle nvarchar(200),
        @rId bigint=0,
        @rOrgGroupId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		FT.Id,
		FT.Code,
		FT.Title,
		FT.IsObsolete,
		CreatedUserId,
		CreatedDateTime,
		FeedBackAnswerGroupMasterId,
		AG.Title As FeedBackAnswerGroupMaster
		
	from sCommunication.tFeedbackAnswerTypeMaster FT
	INNER JOIN sCommunication.tFeedBackAnswerGroupMaster AG ON Ag.Id =FT.FeedBackAnswerGroupMasterId
	Where ((FT.Code=@rCode) OR (ISNULL(@rCode,'')=''))
	AND ((FT.Title=@rTitle) OR (ISNULL(@rTitle,'')=''))
	AND ((FT.Id=@rId) OR (@rId=0))
	AND OrgGroupId=@rOrgGroupId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackAssignAdd]
	 
	 	 
        --@rId bigint=0,
        --@rAssignSourceTypeId smallint, 
		--@rAssignSourceId bigint ,
		@rFeedbackId bigint,
		@rDetail nvarchar(max)='',
		@rBatchId int,
		@rOrgId smallint,
		@rAssignToSourceTypeId smallint
		--@rForName nvarchar(200) ,
		--@rIsDelete bit
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 DECLARE @loDoc INT
SET @rDetail=REPLACE(@rDetail,'&','AND')
EXEC sp_xml_preparedocument @loDoc OUTPUT  ,@rDetail
Declare @lCount int
BEGIN
	
	DELETE FROM sCommunication.tFeedbackAssign WHERE FeedbackId = @rFeedbackId
		CREATE Table #temp
		(
			Id int Identity(1,1),
			AssignToSourceTypeId smallint,
			AssignToSourceId bigint,
			FeedbackId bigint,
			ForName nvarchar(200)
		)
		Insert Into #temp
		Select AssignToSourceTypeId,AssignToSourceId ,FeedbackId,ForName
					From Openxml(@loDoc,'Table/Feedback',1)
					With
					(
						AssignToSourceTypeId smallint,
						AssignToSourceId bigint ,
						FeedbackId bigint,
						ForName nvarchar(200)
					)
		Select @lCount=count(*) from #temp
	 
	 INSERT INTO sCommunication.tFeedbackAssign
	 (
		 
		AssignToSourceTypeId,
		AssignToSourceId,
		FeedbackId,
		ForName
	 )
	  Select AssignToSourceTypeId,AssignToSourceId,@rFeedbackId,ForName
	From Openxml(@loDoc,'Table/Feedback',1)
		With
		(
			AssignToSourceTypeId smallint,
			AssignToSourceId bigint ,
			FeedbackId bigint,
			ForName nvarchar(200)
		)
	 
	  
	 --Values
	 --(
		 
		--@rAssignSourceTypeId,
		--@rAssignSourceId,
		--@rFeedbackId,
		--@rForName
	 --)
	  
	 --END
	-- ELse 
	-- BEGIN
	-- SET @lNextNumber = @rId
	-- IF(@rIsDelete = 0)
	-- BEGIN
	--	 UPDATE sCommunication.tFeedbackAssign
	--	 SET
	--		AssignToSourceTypeId=@rAssignSourceTypeId,
	--		AssignToSourceId=@rAssignSourceId,
	--		FeedbackId=@rFeedbackId,
	--		ForName=@rForName
	--		WHERE Id=@rId
	--	 END 
	--	  ELSE 
	--	DELETE FROM sCommunication.tFeedbackAssign  WHERE Id =  @rId	
	--END
		Select 1 As Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackAssignGet]   
	  
        @rFeedbackId bigint=0,
        @rId bigint=0,
        @rAssignToSourceTypeId smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--if(@rAssignToSourceTypeId=2001)
	--BEGIN
	--SELECT
		 
	--	 FA.Id,
	--	 SM.ID AS SourceId,
	--	 FeedbackId,
	--	 AssignToSourceTypeId,
	--	 ForName,
		 
	--	 Isnull(A.DivisionId,0) AS DivisionId,
	--	 Firstname+' '+MiddleName+' ' +LastName AS Name,  AssignToSourceId ,
	--	 SM.Code
	--	 FROM  sCommunication.tFeedbackAssign FA
	--	 INNER JOIN sStudent.tAcademic A  ON FA.AssignToSourceId=A.ID 
	--	 INNER  JOIN sStudent.tStudentMaster SM ON SM.ID=A.StudentID
		 
	--	 WHERE  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))  AND AssignToSourceTypeId=2001
	--END
	
	--else if(@rAssignToSourceTypeId=95)
	--BEGIN
	--	SELECT
		 
	--	 FA.Id,
	--	 Em.ID AS SourceId,
	--	 FeedbackId,
	--	 AssignToSourceTypeId,
	--	 ForName,
	--	 Code,
	--	 --Isnull(A.DivisionId,0) AS DivisionId,
	--	 Firstname+' '+MiddleName+' ' +LastName AS Name,  AssignToSourceId 
	--	 FROM  sCommunication.tFeedbackAssign FA
	--	 INNER JOIN sHrm.tEmployeeMaster Em ON FA.AssignToSourceId=Em.ID 
		 
	--	 WHERE  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))  AND AssignToSourceTypeId=95
	--END
	--else
	--BEGIN
	--	SELECT
		 
	--	 FA.Id,
	--	 --Em.ID AS SourceId,
	--	 FeedbackId,
	--	 ISNULL(AssignToSourceTypeId,0) AS AssignToSourceTypeId,
	--	 ForName ,
	--	 '' AS Code,
	--	 --Isnull(A.DivisionId,0) AS DivisionId,
	--	  '' AS Name,
	--	  ISNULL(AssignToSourceId,0) AS AssignToSourceId
	--	 FROM  sCommunication.tFeedbackAssign FA
		 
	--	 WHERE  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0)) 
	--END
WITH CTE 
AS 
  (
	Select 
		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			   
			From sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 Else
			ForName
		 END) AS Name,
		 
		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 Code
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 Code
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 Else
			ForName
		 END) AS Code,
		 
		  (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 Id
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 A.Id
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 Else
			ForName
		 END) AS SourceId,
		 
		 
		FB.Id,
		Isnull(AssignToSourceTypeId,0) AS AssignToSourceTypeId,
		Isnull(AssignToSourceId,0)AS AssignToSourceId,
		FeedbackId,
		ForName 
	  
		
	from sCommunication.tFeedbackAssign FB
	 
	Where  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))
	AND ((FB.Id=@rId) OR (@rId=0))
)
--Added by dhananjay for mantis : 42594
SELECT 
        Name,
        Code,
        SourceId,
        Id,
        ISNULL(AssignToSourceTypeId, 0) AS AssignToSourceTypeId,
        ISNULL(AssignToSourceId, 0) AS AssignToSourceId,
        FeedbackId,
        ForName
From CTE
ORDER BY	
    CASE 
        WHEN ISNUMERIC(Code) = 1 THEN TRY_CAST(Code AS DECIMAL(38, 0))
        ELSE NULL
    END,    
Code;
--Added by dhananjay for mantis : 42594
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackDataGet]
	  
        --@rFeedbackId bigint=0 ,
        @rOrgId int=0,
        @rBatchId int,
        @rOrgGroupBatchId int ,
        @rSourceId bigint=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	--Declare @lSourceTypeId smallint,@lFeedbackId  bigint=0 
	--SELECT @lFeedbackId=FB.Id FROM sCommunication.tFeedback FB
 --   INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
 --   WHERE OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  AND AssignToSourceId =@rSourceId ORDER BY Title
 
	--Select @lSourceTypeId=ForSourceTypeId from sCommunication.tFeedbackFor where FeedbackId=@lFeedbackId
	
	Select 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FF.ForSourceId And FF.ForSourceTypeId=95 And  --OrgId=@rOrgId AND -- Commented for Mantis 0029364 By Foram
			ISNULL(IsOtherUser,0) = 0  )
		 WHEN  2001
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FF.ForSourceId ANd FF.ForSourceTypeId=2001)
		 Else
			FF.ForName
		 END) AS Name, 
		 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 Code
			From sHrm.tEmployeeMaster Where  Id=FF.ForSourceId And FF.ForSourceTypeId=95 And  --OrgId=@rOrgId AND -- Commented for Mantis 0029364 By Foram
			ISNULL(IsOtherUser,0) = 0  )
		 WHEN  2001
		 THEN
			(Select
			 SM.Code
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FF.ForSourceId ANd FF.ForSourceTypeId=2001)
		 Else
			FF.ForName
		 END) AS Code, 
		 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 Id
			From sHrm.tEmployeeMaster Where  Id=FF.ForSourceId And FF.ForSourceTypeId=95 And  --OrgId=@rOrgId AND -- Commented for Mantis 0029364 By Foram
			 ISNULL(IsOtherUser,0) = 0  )
		 WHEN  2001
		 THEN
			(Select
			 A.Id
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FF.ForSourceId ANd FF.ForSourceTypeId=2001)
		 Else
			0  
		 END) AS Id, 
		 FF.Id AS FeedbackForId,
		FB.Id AS FeedbackId,FB.Title ,
		FB.FeedbackTemplateId
	 FROM sCommunication.tFeedbackFor FF 
	 INNER JOIN sCommunication.tFeedback FB ON FB.Id=FF.FeedbackId
	 INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id
	 Where FB.OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  AND AssignToSourceId =@rSourceId 
	 
	--If @lSourceTypeId=2001
	--BEGIN
	--	SELECT FB.Id AS FeedbackId,FB.Title,A.Id,Code+' - '+FirstName+' '+MiddleName+' '+LastName AS name 
	--	 FROM sCommunication.tFeedback FB
	--	--INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
	--	INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id
	--	INNER JOIN sCommunication.tFeedbackFor FO ON FO.FeedbackId=FB.ID
	--	INNER JOIN sStudent.tAcademic A  on FO.ForSourceId=A.Id
	--	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
	--	Where SM.OrgId=@rOrgId   And A.BatchId=@rBatchId
	--	And FB.OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  AND AssignToSourceId =@rSourceId 
	
	-- END
	
	--else if  @lSourceTypeId=95
	--BEGIN
	--	SELECT FB.Id AS FeedbackId,FB.Title,EM.Id,Code+' - '+FirstName+' '+MiddleName+' '+LastName AS name 
	--	 FROM sCommunication.tFeedback FB
	--	--INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
	--	INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id
	--	INNER JOIN sCommunication.tFeedbackFor FO ON FO.FeedbackId=FB.ID
	--	INNER JOIN sHrm.tEmployeeMaster EM  on FO.ForSourceId=EM.Id
	--	Where EM.OrgId=@rOrgId  and  OrgGroupBatchId=@rOrgGroupBatchId And IsClose=0 and IsPublish=1 and AssignToSourceId =@rSourceId
	--END
	
	--else
	--BEGIN
		 
	--	SELECT FB.Id AS FeedbackId,FB.Title,FO.ForName AS name,0 AS Id
	--	 FROM sCommunication.tFeedback FB
	--	INNER JOIN sCommunication.tFeedbackAssign FA ON Fa.FeedbackId=FB.Id 
	--	LEFT JOIN sCommunication.tFeedbackFor FO ON FO.FeedbackId=FB.ID  
	--	where   OrgGroupBatchId=@rOrgGroupBatchId and IsClose=0 and IsPublish=1  
	--	AND ISNULL(AssignToSourceId,0) =0 AND ISNULL(ASSIgntosourcetypeid,0)=0
		  
	--END  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackForAdd]
	 
	 	 
        @rId bigint=0,
        @rForSourceTypeId smallint, 
		@rForSourceId bigint ,
		@rFeedbackId bigint,
		@rForName nvarchar(200),
		@rOrgGroupId int=0,
		@rIsDelete bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rId=0)
	 BEGIN
	 Declare @lNextNumber bigint
	 
	 INSERT INTO sCommunication.tFeedbackFor
	 (
		 
		ForSourceTypeId,
		ForSourceId,
		FeedbackId,
		ForName
	 )
	 Values
	 (
		 
		@rForSourceTypeId,
		@rForSourceId,
		@rFeedbackId,
		@rForName
	 )
	  
	 END
	 ELse 
	 BEGIN
	 SET @lNextNumber = @rId
	 IF(@rIsDelete = 0)
	 BEGIN
		 UPDATE sCommunication.tFeedbackFor
		 SET
			ForSourceTypeId=@rForSourceTypeId,
			ForSourceId=@rForSourceId,
			FeedbackId=@rFeedbackId,
			ForName=@rForName
			WHERE Id=@rId
		 END 
		  ELSE 
		DELETE FROM sCommunication.tFeedbackFor WHERE Id =  @rId	
	 
		 END
		Select 1 As Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackForDelete]
	    
        @rId bigint=0,
		@rOrgGroupbatchId bigint=0 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Delete from sCommunication.tFeedback where OrgGroupBatchId=@rOrgGroupbatchId ANd Id =@rId
	Delete from sCommunication.tFeedbackFor Where FeedbackId=@rId
	Delete from sCommunication.tFeedbackAssign Where FeedbackId=@rId
	Select 1 As Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackForGet]
	  
        @rFeedbackId bigint=0,
        @rId bigint=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FB.ForSourceId And FB.ForSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.ForSourceId ANd FB.ForSourceTypeId=2001)
		 Else
			ForName
		 END) AS Name,
		 (CASE ForSourceTypeId WHen  95
		 THEN
			(Select 
			 Code
			From sHrm.tEmployeeMaster Where  Id=FB.ForSourceId And FB.ForSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 Code
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.ForSourceId ANd FB.ForSourceTypeId=2001)
		 Else
			ForName
		 END) AS StudentIdNo,
		FB.Id,
		ForSourceTypeId,
		ForSourceId,
		FeedbackId,
		ForName
		
	from sCommunication.tFeedbackFor FB
	 
	 
	Where  ((FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))
	AND ((FB.Id=@rId) OR (@rId=0))
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackGet]
	 
	 	 
        
        @rTitle nvarchar(200),
        @rId bigint=0,
        @rOrgGroupBatchId int,
        @rFeedbackTemplateId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		 FB.Id,
		 FB.Title,
		 FeedbackTemplateId, 
		 IsPublish,
		IsClose,
		FB.OrgGroupBatchId,
		FB.CreatedUserId,
		FT.Title AS Template
		
	from sCommunication.tFeedback FB 
	INNER JOIN sCommunication.tFeedbackTemplate FT ON FT.Id=FB.FeedbackTemplateId
	Where  
	(( FB.Title=@rTitle) OR (ISNULL(@rTitle,'')=''))
	AND (( FB.Id=@rId) OR (@rId=0))
	AND FB.OrgGroupBatchId=@rOrgGroupBatchId
	--AND ((FeedbackTemplateId=@rFeedbackTemplateId) OR (@rFeedbackTemplateId=0))
	ORDER BY FB.CreatedDateTime DESC	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackQuestionDataGet]
	  
	 
	 @rOrgGroupBatchId int,
	 @rFeedbackId bigint ,
	 @rFeedbackForId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	  
	 SELECT	
			count(*) CountData,
			FQ.ID,
			FQ.QuestionNumber,
			FQ.Question,
			FQ.FeedbackTemplateId
					
		from sCommunication.tFeedback FB 
		INNER JOIN	sCommunication.tFeedbackTemplateQuestion FQ ON FQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FQR ON FQR.FeedbackID = FB.Id
		INNER JOIN sCommunication.tFeedbackQuestionResponse FA ON  FA.FeedBackResponseId = FQR.Id and FA.FeedbackTemplateQuestionId = FQ.Id 
						and ((ISNULL(FA.FeedbackAnswerDescription,'')!='') Or (FA.FeedbackAnswerTypeDetailId!=0))
	 
		WHERE FB.Id = @rFeedbackId ANd OrgGroupBatchId=@rOrgGroupBatchId  And FQR.FeedbackForId = @rFeedbackForId  
		Group by  FQ.Id,FQ.QuestionNumber,FQ.Question,FQ.FeedbackTemplateId 
		 
		 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackQuestionResponseAdd]
	  
        @rFeedbackResponseId bigint=0,
        @rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
	INSERT INTO sCommunication.tFeedbackQuestionResponse
	(
		FeedbackResponseId,
		FeedbackTemplateQuestionId,
		FeedbackAnswerTypeDetailId,
		FeedbackAnswerDescription
	)
	Select
		@rFeedbackResponseId,FeedbackTemplateQuestionId,FeedbackAnswerTypeDetailId,FeedbackAnswerDescription
	From
		OPENXML (@loDoc, '/Table/MyFeedback', 1)WITH ( 
		FeedbackTemplateQuestionId bigint,
		FeedbackAnswerTypeDetailId bigint,
		FeedbackAnswerDescription nvarchar(200)
	 )
		
	 --if not exists(Select 1 from sCommunication.tFeedbackQuestionResponse where FeedbackResponseId=@rFeedbackResponseId
	 --AND FeedbackTemplateQuestionId=@rFeedbackTemplateQuestionId)
	 --BEGIN
		--Insert Into sCommunication.tFeedbackQuestionResponse
		-- (
		--	FeedbackResponseId,
		--	FeedbackTemplateQuestionId,
		--	FeedbackAnswerTypeDetailId,
		--	FeedbackAnswerDescription 
			 
		-- )
		-- Values
		-- (
		--	@rFeedbackResponseId,
		--	@rFeedbackTemplateQuestionId,
		--	@rFeedbackAnswerTypeDetailId,
		--	@rFeedbackAnswerDescription 
			 
		-- )
		-- Select 1 As Result
	 --END
	 Select 1 As Result
	 END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackResponseAdd]
	  
        @rFeedbackId bigint=0,
        @rSourceTypeId smallint,
        @rSourceId bigint,
        @rCreatedUserId bigint,
        @rOrgGroupId bigint,
        @rFeedbackForId bigint,
        @rIsCompleted bit 
        
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 IF Not Exists(Select 1 from sCommunication.tFeedbackResponse where FeedbackId=@rFeedbackId ANd SourceId=@rSourceId and SourceTypeId=@rSourceTypeId
	 and FeedbackForId=@rFeedbackForId  )
	 BEGIN
	  Declare @lNextNumber bigint
	  EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackResponse', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 Insert Into sCommunication.tFeedbackResponse
	 (
		Id,
		FeedbackId,
		SourceTypeId,
		SourceId,
		CreatedUserId,
		CreatedDateTime,
		FeedbackForId,
		IsCompleted
	 )
	 Values
	 (
		@lNextNumber,
		@rFeedbackId,
		@rSourceTypeId,
		@rSourceId,
		@rCreatedUserId,
		sCommon.fGetDate() ,
		@rFeedbackForId,
		@rIsCompleted
	 )
	Select @lNextNumber As Result
	 END
	ELse
	BEGIN
		Select Id from sCommunication.tFeedbackResponse
		Where FeedbackId=@rFeedbackId And SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId and FeedbackForId=@rFeedbackForId
			
	END

	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackResponseGet]
	 
	 
	 
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int ,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint,
	 @rFeedbackId bigint ,
	  @rFeedbackForId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 SELECT	
		FQ.Id As TempateQuestionId,
					FQ.QuestionNumber,
					FQ.Question ,
					FQ.FeedbackAnswerTypeID,			 
					ISNULL(FQR. FeedbackAnswerTypeDetailId,0) AS FeedbackAnswerTypeDetailId,
					FR.SourceId ,
					ISNULL(FQR.FeedbackAnswerDescription,'') AS FeedbackAnswerDescription,
					FR.Id 
					--FB.FeedbackTemplateId
		from sCommunication.tFeedback FB 
		INNER JOIN	sCommunication.tFeedbackTemplateQuestion FQ ON FQ.FeedbackTemplateId = FB.FeedbackTemplateId
		LEFT JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND FR.FeedbackForId =@rFeedbackForId  AND  SourceId = @rUserSourceId 		
				    AND SourceTypeId=@rUserSourceTypeId 
		Left Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id 
		AND FQR.FeedbackTemplateQuestionID = FQ.Id
		--AND FQR.FeedBackResponseId = 1001000000001
		--LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FA ON FA.ID=FQR.FeedbackAnswerTypeDetailId
		WHERE FB.Id = @rFeedbackId ANd OrgGroupBatchId=@rOrgGroupBatchId
	 
		 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackTemplateAdd]
	 
	 	@rOrgGroupId smallint,
        @rId bigint=0,
        @rCode nvarchar(200),
        @rTitle nvarchar(200), 
		@rCreatedUserId bigint ,
		@rOrgGroupBatchId int ,
		@rIsAllAnsRequired bit = 0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 DECLARE @lNextNumber BIGINT 

	 
	IF(@rId = 0)	
	BEGIN
		 
		if exists(Select 1 from sCommunication.tFeedbackTemplate where Code=@rCode AND OrgGroupId=@rOrgGroupId)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackTemplate where Title =@rTitle AND OrgGroupId=@rOrgGroupId)
	BEGIN
		Select -102 As Result
		Return
	END
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackTemplate', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedbackTemplate
		(
			Id,
			Code,
			Title, 
			OrgGroupId,
			CreatedUserId,
			CreatedDateTime,
			IsAllAnsRequired 
			 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle, 
			@rOrgGroupId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsAllAnsRequired 
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
		if exists(Select 1 from sCommunication.tFeedbackTemplate where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
	BEGIn
		Select -101 As Result
		Return
	END
	
	If exists(Select 1 from sCommunication.tFeedbackTemplate where Title =@rTitle AND OrgGroupId=@rOrgGroupId AND ID<>@rId)
	BEGIN
		Select -102 As Result
		Return
	END
	
	 if exists(Select 1 from sCommunication.tFeedback where OrgGroupBatchId =@rOrgGroupBatchId and FeedbackTemplateId=@rId)
	 BEGIN
		select -111 As Result
		return
	 
	 END
	
	    UPDATE  sCommunication.tFeedbackTemplate
	    SET
			Code=@rCode,
			Title=@rTitle, 
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			IsAllAnsRequired  = @rIsAllAnsRequired
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackTemplateGet]
	 
	 	 
        @rCode nvarchar(200),
        @rTitle nvarchar(200),
        @rId bigint=0,
        @rOrgGroupId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		 Id,
		 Code,
		 Title, 
		 OrgGroupId,
		CreatedUserId,
		CreatedDateTime,
		ISNULL(IsAllAnsRequired,0) AS IsAllAnsRequired
		
	from sCommunication.tFeedbackTemplate  
	Where (( Code=@rCode) OR (ISNULL(@rCode,'')=''))
	AND (( Title=@rTitle) OR (ISNULL(@rTitle,'')=''))
	AND (( Id=@rId) OR (@rId=0))
	AND OrgGroupId=@rOrgGroupId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackTemplateQuestionAdd]
	 
	 	 
         
         
        @rQuestionNumber  int,
        @rQuestion nvarchar(200),
        @rFeedbackTemplateId bigint,
        @rFeedbackAnswerTypeId bigint,
		@rCreatedUserId bigint,
		@rFeedbackTemplateQuestionId bigint,
		@rOrgGroupId int,
		@rIsDelete bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	  
	 IF (@rFeedbackTemplateQuestionId=0)
	 BEGIN
	 Declare @lNextNumber bigint
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedbackTemplateQuestion', 0, 1, 1,@outNextNumber = @lNextNumber output
	 
	 INSERT INTO sCommunication.tFeedbackTemplateQuestion
	 (
		Id,
		QuestionNumber,
		Question,
		FeedbackTemplateId,
		FeedbackAnswerTypeId,
		CreatedUserId,
		CreatedDateTime 
	 )
	 Values
	 (
		@lNextNumber,
		@rQuestionNumber,
		@rQuestion,
		@rFeedbackTemplateId,
		@rFeedbackAnswerTypeId,
		@rCreatedUserId,
		sCommon.fGetDate()
	 )
	  
	 END
	 ELse 
	 BEGIN
	 SET @lNextNumber = @rFeedbackTemplateQuestionId
	 IF(@rIsDelete = 0)
	 BEGIN
	 UPDATE sCommunication.tFeedbackTemplateQuestion
	 SET
		QuestionNumber=@rQuestionNumber,
		Question=@rQuestion,
		FeedbackAnswerTypeId=@rFeedbackAnswerTypeId,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=sCommon.fGetDate()
		WHERE Id=@rFeedbackTemplateQuestionId
	 END
	 ELSE 
		DELETE FROM sCommunication.tFeedbackTemplateQuestion  WHERE Id =  @rFeedbackTemplateQuestionId	
	END
	Select 1 As Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackTypeMasterDelete]

	 @rId bigint,
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		--IF NOT EXISTS (SELECT Id FROM sCommunication.tCircular WHERE CircularTypeId = @rId)	
		--BEGIN	
			Delete from sCommunication.tFeedbackAnswerTypeMaster where Id=@rId AND OrgGroupId=@rOrgGroupId
			  
			Delete from sCommunication.tFeedbackAnswerTypeDetail where FeedbackAnswerTypeId=@rId
			Select 1 AS RESULT
		--END
		--ELSE
		--	BEGIN
		--		SELECT -101 AS RESULT
		--	END
			
		
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFeedbackTypeTemplateDelete]

	 @rId bigint,
	 @rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		--IF NOT EXISTS (SELECT Id FROM sCommunication.tCircular WHERE CircularTypeId = @rId)	
		--BEGIN	
			Delete from sCommunication.tFeedbackTemplate where Id=@rId AND OrgGroupId=@rOrgGroupId
			  
			Delete from sCommunication.tFeedbackTemplateQuestion where FeedbackTemplateId=@rId
			Select 1 AS RESULT
		--END
		--ELSE
		--	BEGIN
		--		SELECT -101 AS RESULT
		--	END
			
		
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFollowup]
		@rAutoId bigint,
		@rFollowupNumber int,
		@rFollowupTypeId bigint,
		@rFollowupDate date,
		@rFollowupTime time(7),
		@rFollowupDuration int,
		@rRelationId tinyint,
		@rAcademicId bigint,
		@rFollowupRemark nvarchar(500),
		@rFollowupOtherRemark nvarchar(500)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
	BEGIN TRANSACTION	
	
	IF(@rAutoId = 0)	
		BEGIN
			INSERT INTO [sCommunication].[tFollowup]
			   ([FollowupNumber]
			   ,[FollowupTypeId]
			   ,[FollowupDate]
			   ,[FollowupTime]
			   ,[FollowupDuration]
			   ,[RelationId]
			   ,[AcademicId]
			   ,[FollowupRemark]
			   ,[FollowupOtherRemark])
			VALUES	
				(@rFollowupNumber,
				@rFollowupTypeId,
				@rFollowupDate,
				@rFollowupTime,
				@rFollowupDuration,
				@rRelationId,
				@rAcademicId,
				@rFollowupRemark,
				@rFollowupOtherRemark)
		SELECT 1 AS Result
		END	 
	ELSE
		 BEGIN
			UPDATE [sCommunication].[tFollowup]
			SET [FollowupNumber] = @rFollowupNumber,
				[FollowupTypeId] = 	@rFollowupTypeId,
				[FollowupDate] = 	@rFollowupDate,
				[FollowupTime] = 	@rFollowupTime,
				[FollowupDuration] = 	@rFollowupDuration,
				[RelationId] = 	@rRelationId,
				[AcademicId] = 	@rAcademicId,
				[FollowupRemark] = 	@rFollowupRemark,
				[FollowupOtherRemark] = 	@rFollowupOtherRemark
			WHERE AutoId = @rAutoId
			  SELECT 11 AS Result
		 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFollowupAdd]
		@rAutoId bigint=0,
		@rFollowupNumber int=0,
		@rFollowupTypeId bigint,
		@rFollowupDate date,
		@rFollowupTime time(7),
		@rFollowupDuration int,
		@rRelationId tinyint,
		@rAcademicId bigint,
		@rFollowupRemark nvarchar(500),
		@rFollowupOtherRemark nvarchar(500),
		@rFollowupRelationRemark nvarchar(500),
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
	BEGIN TRANSACTION	
	
	IF(@rAutoId = 0)	
		BEGIN
		set @rFollowupNumber = (select (ISNULL(max(FollowupNumber), 0) + 1) from [sCommunication].[tFollowup] where AcademicId = @rAcademicId and FollowupTypeId = @rFollowupTypeId)
			INSERT INTO [sCommunication].[tFollowup]
			   ([FollowupNumber]
			   ,[FollowupTypeId]
			   ,[FollowupDate]
			   ,[FollowupTime]
			   ,[FollowupDuration]
			   ,[RelationId]
			   ,[AcademicId]
			   ,[FollowupRemark]
			   ,[FollowupOtherRemark]
			   ,[FollowupRelationRemark]
			   ,[CreatedUserId]
			   ,[CreatedDateTime])
			VALUES	
				(@rFollowupNumber,
				@rFollowupTypeId,
				@rFollowupDate,
				@rFollowupTime,
				@rFollowupDuration,
				@rRelationId,
				@rAcademicId,
				@rFollowupRemark,
				@rFollowupOtherRemark,
				@rFollowupRelationRemark,
				@rCreatedUserId,
				getdate())
		SELECT 1 AS Result
		END	 
	ELSE
		
		 BEGIN
			UPDATE [sCommunication].[tFollowup]
			SET [FollowupTypeId] = 	@rFollowupTypeId,
				[FollowupDate] = 	@rFollowupDate,
				[FollowupTime] = 	@rFollowupTime,
				[FollowupDuration] = 	@rFollowupDuration,
				[RelationId] = 	@rRelationId,
				[AcademicId] = 	@rAcademicId,
				[FollowupRemark] = 	@rFollowupRemark,
				[FollowupOtherRemark] = @rFollowupOtherRemark,
				[FollowupRelationRemark] = @rFollowupRelationRemark,
				[UpdatedUserId] = @rCreatedUserId,
				[UpdatedDateTime] = getdate()
			WHERE AutoId = @rAutoId
			  SELECT 11 AS Result
		 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFollowupDelete]
	 
	 @rAutoId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		
			DELETE FROM [sCommunication].[tFollowup] WHERE AutoId=@rAutoId
			SELECT 1 AS Result
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pFollowupGet]
	@rAutoId bigint=0,
	@rFollowupNumber int=0,
	@rFollowupTypeId bigint=0,
	@rCode nvarchar(20)='',
	@rName nvarchar = '',
	@rFromDate date='',
    @rToDate date=''


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rCode= sCommon.fSearchStringGet(@rCode)
SELECT F.[AutoId]
      ,F.[FollowupNumber]
      ,F.[FollowupTypeId]
      ,F.[FollowupDate]
      ,F.[FollowupTime]
      ,F.[FollowupDuration]
      ,F.[RelationId]
      ,F.[AcademicId]
      ,F.[FollowupRemark]
      ,F.[FollowupOtherRemark]
	  ,F.[FollowupRelationRemark]
	  ,FTM.[Title]
	  ,(SM.FirstName+' '+SM.MiddleName+' '+SM.LastName) AS Name
	  ,SM.Code
	  ,RM.[Title] as RelationName
	  --,CONVERT(datetime,((convert(nvarchar(10), convert(date,F.[FollowupDate])) +' '+  convert(nvarchar(10),convert(time,F.FollowupTime))))) AS FollowupDateTime
	FROM [sCommunication].[tFollowup] F 
	INNER JOIN [sCommunication].[tFollowupTypeMaster] FTM
	ON FTM.Id = F.FollowupTypeId
	INNER JOIN [sStudent].[tAcademic] SA
	ON SA.Id = F.AcademicId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId 
	INNER JOIN sCommon.tRelationshipMaster RM ON F.RelationId = RM.Id
	where ((F.AutoId = @rAutoId) OR (ISNULL(@rAutoId,0) = 0))
		AND ((F.FollowupNumber = @rFollowupNumber) OR (ISNULL(@rFollowupNumber,0) = 0))
		AND ((F.FollowupTypeId = @rFollowupTypeId) OR (ISNULL(@rFollowupTypeId,0) = 0))
		AND ((SM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND ((SM.FirstName LIKE ''+@rName+'%') OR (ISNULL(@rName, '') = ''))
		AND (F.FollowupDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (F.FollowupDate<=@rToDate OR ISNULL(@rToDate,'')='')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pFollowupHistoryGet]
	@rAutoId bigint,
	@rFollowupTypeId bigint,
	@rAcademicId bigint


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT F.[AutoId]
      ,F.[FollowupNumber]
      ,F.[FollowupTypeId]
      ,F.[FollowupDate]
      ,F.[FollowupTime]
      ,F.[FollowupDuration]
      ,F.[RelationId]
      ,F.[AcademicId]
      ,F.[FollowupRemark]
      ,F.[FollowupOtherRemark]
	  ,F.[FollowupRelationRemark]
	  ,FTM.[Title]
	  ,(SM.FirstName+' '+SM.MiddleName+' '+SM.LastName) AS Name
	  ,SM.Code
	  ,RM.[Title] as RelationName
	FROM [sCommunication].[tFollowup] F 
	INNER JOIN [sCommunication].[tFollowupTypeMaster] FTM
	ON FTM.Id = F.FollowupTypeId
	INNER JOIN [sStudent].[tAcademic] SA
	ON SA.Id = F.AcademicId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId 
	INNER JOIN sCommon.tRelationshipMaster RM ON F.RelationId = RM.Id
	where F.AutoId <> @rAutoId
		AND F.FollowupTypeId = @rFollowupTypeId 
		AND SA.Id = @rAcademicId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFollowupTypeAssignedToAdd]
		@rSourceTypeId smallint,
		@rSourceId bigint = 0,
		@rFollowupTypeId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
	BEGIN TRANSACTION	
		BEGIN
			INSERT INTO [sCommunication].[tFollowupTypeAssignedTo]
			   ([SourceTypeId]
			   ,[SourceId]
			   ,[FollowupTypeId])
			VALUES
			   (@rSourceTypeId,
			   @rSourceId,
			   @rFollowupTypeId)
		SELECT 1 AS Result
		END	 
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFollowupTypeAssignedToGet]
		@rFollowupTypeId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
	BEGIN TRANSACTION	
		BEGIN
			SELECT  followupAssig.SourceTypeId
				,followupAssig.SourceId
				,followupAssig.FollowupTypeId
				,emp.ID
				,emp.Code
				,emp.FirstName
				,emp.MiddleName
				,emp.LastName

			FROM [NetVidyalaya].[sCommunication].[tFollowupTypeAssignedTo] as followupAssig
			INNER JOIN [sHrm].[tEmployeeMaster] as emp
			ON followupAssig.SourceId = emp.id
			where followupAssig.FollowupTypeId = @rFollowupTypeId

			SELECT 1 AS Result
		END	 
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFollowupTypeMasterAdd]
	 
		@rId bigint,
		@rCode nvarchar(100),
		@rTitle nvarchar(200),
		@rOrderIndex int,
		@rIsPublish bit,
		@rIsObsolete bit = 0,
		@rOrgGroupId smallint,
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Code=@rCode AND OrgGroupId=@rOrgGroupId)
		BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		BEGIN
			select -103 as Result
			RETURN
		END
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
		BEGIN
			select -1003 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Code=@rCode AND Id<>@rId AND OrgGroupId=@rOrgGroupId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Title=@rTitle AND Id<>@rId AND OrgGroupId=@rOrgGroupId)
		Begin
			select -103 as Result
			RETURN
		End
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where OrderIndex=@rOrderIndex  AND Id<>@rId AND OrgGroupId=@rOrgGroupId)
		BEGIN
			select -1003 as Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
		BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFollowupTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO [sCommunication].[tFollowupTypeMaster]
			   ([Id]
			   ,[Code]
			   ,[Title]
			   ,[OrderIndex]
			   ,[IsPublish]
			   ,[IsObsolete]
			   ,[OrgGroupId]
			   ,[CreatedUserId]
			   ,[CreatedDateTime])
		 VALUES
			   (@lNextNumber,
			    @rCode ,
				@rTitle ,
				@rOrderIndex ,
				@rIsPublish ,
				@rIsObsolete ,
				@rOrgGroupId ,
				@rCreatedUserId ,
				sCommon.fGetDate())

		SELECT 1 AS Result
		SELECT @lNextNumber AS Id
		END	 
	ELSE
		 BEGIN
		 SET @lNextNumber = @rId
			UPDATE [sCommunication].[tFollowupTypeMaster]
				SET 
				  [Code] = @rCode ,
				  [Title] = @rTitle ,
				  [OrderIndex] = @rOrderIndex ,
				  [IsPublish] = @rIsPublish ,
				  [IsObsolete] = @rIsObsolete ,
				  [OrgGroupId] = @rOrgGroupId ,
				  [UpdatedUserId] = @rCreatedUserId ,
				  [UpdatedDateTime] = sCommon.fGetDate()  
				WHERE [Id] = @rId
			  
			  SELECT 11 AS Result
		SELECT @lNextNumber AS Id
		 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pFollowupTypeMasterDelete]
	 
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
If  Exists(select AutoId from [sCommunication].[tFollowup] where FollowupTypeId = @rId)
		Begin
			select -102 as Result
			RETURN
		End
BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		
			DELETE FROM [sCommunication].[tFollowupTypeAssignedTo] WHERE FollowupTypeId=@rId
			DELETE FROM [sCommunication].[tFollowupTypeMaster] WHERE Id=@rId
			SELECT 1 AS Result
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pFollowupTypeMasterGet]
	@rCode nvarchar(100),
	@rTitle nvarchar(200),
	@rOrgGroupId int,
	@rId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 	 SELECT 
			Id,
			Code,
			Title,
			OrderIndex,
			ISNULL(IsPublish,0) As IsPublish,
			IsObsolete,
			OrgGroupId,
			CreatedUserId,
			ISNULL(UpdatedUserId,0) AS UpdatedUserId
			  
	   FROM  [sCommunication].[tFollowupTypeMaster]
	    
	   WHERE ((Code LIKE '%'+@rCode+'%') OR (ISNULL(@rCode, '') = ''))
	   AND	((Title LIKE @rTitle+'%') OR (ISNULL(@rTitle, '') = ''))
	   AND ((id = @rId) OR (ISNULL(@rId,0) = 0))
	   AND OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pGroupMemberGet]
	 @rDiscussionGroupId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	
	SELECT 
			'Student' AS SourceType,
			SA.Code as SourceCode,
			SA.Name as SourceName,
			SA.ClassName+'-'+SA.DivisionName as ClassDept
  FROM 
            sCommunication.tDiscussionGroupMember DGM
        INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=DGM.SourceId AND DGM.SourceTypeId=2001
  WHERE 
  
      ((DGM.DiscussionGroupId = @rDiscussionGroupId) OR (@rDiscussionGroupId = 0))
      
      UNION ALL
      
  SELECT 
			'Employee' AS SourceType,
			EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as SourceName,
			ODM.Title as ClassDept
  FROM 
            sCommunication.tDiscussionGroupMember DGM	
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=DGM.SourceId AND DGM.SourceTypeId=95
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
  WHERE 
  
      ((DGM.DiscussionGroupId = @rDiscussionGroupId) OR (@rDiscussionGroupId = 0))
	  AND ISNULL(EM.IsOtherUser,0) = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pMultiAllPhotoCategory_Get]
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rBatchId int,
	 @rIsDivisionWise bit=true,
	 @rBatchYear int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
    DECLARE @lOrgGroupId smallint,@lOrgGroupBatchId int,@lOrgId smallint
    
	SELECT @lOrgGroupId=OM.OrgGRoupId,@lOrgGroupBatchId=OrgGroupBatchId,@lOrgId=OM.Id FROM sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	WHERE Bm.Id=@rBatchId
	
    IF(@rIsDivisionWise=0)
    BEGIN
		SELECT   
			MPCM.[Id]
			,MPCM.[Title]
			,MPCM.[IsObsolete]
			--,ISNULL(PC.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(MPCM.Remark,'') AS Remark,
			MPCM.CreatedDateTime,
			--CASE WHEN ISNULL(MPCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2003 THEN 'Student' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 95 THEN 'Employee'
			--END +' - '+ [sCommunication].[fMultiPhotoCategoryScopeGet](MPCM.Id,PC.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName,
			ISNULL(MPCM.OrgGroupBatchId,0) AS OrgGroupBatchId,
			MPCM.ScopeSourceTypeId AS AssigneeId
		FROM    
			[sCommunication].[tMultiPhotoCategoryMaster]  MPCM 
			--INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON MPCM.Id =PC.MultiPhotoCategoryId
			INNER JOIN sCommon.tAssigneeMaster AM ON MPCM.ScopeSourceTypeId = AM.Id  -- Add Join for Mantis Id :0033360
			INNER JOIN sSecurity.tUser U ON MPCM.CreatedUserId = U.Id
		WHERE   
			((MPCM.Id = @rId) OR (@rId = 0))
			AND ((MPCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND ((YEAR(MPCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
			AND (MPCM.OrgGroupBatchId = @lOrgGroupBatchId OR ISNULL(MPCM.OrgGroupBatchId,0)=0)
		ORDER BY 
			MPCM.CreatedDateTime DESC
	END		
	ELSE
	
	 BEGIN
		SELECT   
			MPCM.[Id]
			,MPCM.[Title]
			,MPCM.[IsObsolete]
			--,ISNULL(PC.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(MPCM.Remark,'') AS Remark,
			MPCM.CreatedDateTime,
			--CASE WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 2003 THEN 'Student' 
			--WHEN ISNULL(PC.ScopeSourceTypeId,0) = 95 THEN 'Employee'
			--END +' - '+ [sCommunication].[fMultiPhotoCategoryScopeGet](MPCM.Id,PC.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName,
			ISNULL(MPCM.OrgGroupBatchId,0) AS OrgGroupBatchId,
			MPCM.ScopeSourceTypeId AS AssigneeId
		FROM    
			[sCommunication].[tMultiPhotoCategoryMaster]  MPCM 
			--INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON MPCM.Id =PC.MultiPhotoCategoryId
			INNER JOIN sCommon.tAssigneeMaster AM ON MPCM.ScopeSourceTypeId = AM.Id -- Add Join for Mantis Id :0033360
			INNER JOIN sSecurity.tUser U ON MPCM.CreatedUserId = U.Id
		WHERE   
			((MPCM.Id = @rId) OR (@rId = 0))
			AND ((MPCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND ((YEAR(MPCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
			AND (MPCM.OrgGroupBatchId = @lOrgGroupBatchId OR ISNULL(MPCM.OrgGroupBatchId,0)=0)
		ORDER BY 
			MPCM.CreatedDateTime DESC
	END		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pMultiPhotoCategoryDelete]
	 
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete From sCommunication.tMultiPhotoCategoryScope Where MultiPhotoCategoryId=@rId
			Delete from sCommunication.tMultiPhotoCategoryMaster where Id=@rId
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pMultiPhotoCategoryGet]


 
	 @rSourceTypeId smallint ,
	 @rOrgGroupId int=0,
	 @rOrgId smallint=0,
	 @rPhotoCategoryId bigint=0,
	 @rUserId bigint 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lConfigValue nvarchar(50)
DECLARE @rOrgGroupBatchId int

SELECT @rOrgGroupBatchId  = Id from  sSetup.tOrgGroupBatchMaster Where OrgGroupId=@rOrgGroupId
--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 337 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)


BEGIN 		
	if @rSourceTypeId=2021
	BEGIN
		Select 
			OM.Id,DisplayTitle AS Title ,
			CASE WHEN  PC.ScopeSourceId IS  NOT NULL AND PC.ScopeSourceTypeId=@rSourceTypeId THEN 1 ELSE 0 END  AS IsObsolete
		from  sSetup.tOrganizationMaster OM
		LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
		LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId
		INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id AND ((UO.UserId=@rUserId) OR (@rUserId=0))
		
		where OM.OrgGroupId=@rOrgGroupId   
		
	END
	
	if @rSourceTypeId=2017
	BEGIN
		Select OM.Id,DisplayTitle AS Title ,
		 
		CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PC.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END AS IsObsolete
		 from  sSetup.tDepartmentMaster OM
		LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
		LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId 
		INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=OM.Id AND UA.SourceTypeId=2017 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
		  where OrgId=@rOrgId   
	END
	
	if @rSourceTypeId=2016
	BEGIN
		Select OM.Id,DisplayTitle AS Title,
		CASE WHEN PC.ScopeSourceId IS NOT NULL AND PC.ScopeSourceTypeId=@rSourceTypeId   THEN 1 ELSE 0 END  AS IsObsolete
		
		 from  sSetup.tClassMaster OM
		 LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
		LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId 
		 where OrgId=@rOrgId  
	END
	
	if @rSourceTypeId=2005
	BEGIN

			--if((@lConfigValue='Class Teacher' ) OR (@lConfigValue='Class Teacher Batch' ))
			--BEGIN
			--	 Select  OM.Id,CM.DisplayTitle+'-'+OM.DisplayTitle AS Title,
			--	 CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PC.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END  AS IsObsolete		
			--	 from  sSetup.tDivisionMaster OM
			--	 INNER JOIN sSetup.tClassMaster CM ON CM.Id=OM.ClassId
			--	 INNER JOIN sSetup.tOrganizationMaster ORM ON ORM.Id=CM.OrgId
			--	 LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
			--	 LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId
			--	 where OM.OrgId=@rOrgId AND OM.InchargeemployeeID= (SELECT ISNULL(SourceId,0) FROM sSecurity.tUser WHERE Id=@rUserId AND OrgId= @rOrgId) AND  CM.OrgId=@rOrgId
			--	 ORDER BY CM.OrderIndex
			--END
			--ELSE IF(@lConfigValue='Academic Setup')
			--BEGIN			

			--	 Select DISTINCT OM.Id,CM.DisplayTitle+'-'+OM.DisplayTitle +'('+tOM.DisplayTitle+')' AS Title,
			--	 CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PC.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END  AS IsObsolete		
			--	 from  sSetup.tDivisionMaster OM
			--	 INNER JOIN sSetup.tClassMaster CM ON CM.Id=OM.ClassId
			--	 INNER JOIN sSetup.tOrganizationMaster tOM ON tOM.Id = CM.OrgId
			--	 INNER JOIN sAcademic.vTeacherSubjectDivision TSD ON TSD.OrgId=OM.OrgId AND TSD.DivisionId= OM.Id
			--	 LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
			--	 LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId 
			--	 where TSD.EmployeeId= (SELECT ISNULL(SourceId,0) FROM sSecurity.tUser WHERE Id=@rUserId)					 
				
			--END
			--ELSE IF(@lConfigValue='User Access')
			--BEGIN
			--	 Select OM.Id,CM.DisplayTitle+'-'+OM.DisplayTitle AS Title,
			--	 CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PC.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END  AS IsObsolete		
			--	 from  sSetup.tDivisionMaster OM
			--	 INNER JOIN sSetup.tClassMaster CM ON CM.Id=OM.ClassId
			--	 INNER JOIN sSecurity.tUserAccess U ON U.SourceId = OM.Id AND U.SourceTypeId= 2005
			--	 LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
			--	 LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId 
			--	 where OM.OrgId=@rOrgId  AND  U.UserId =(SELECT ISNULL(ID,0) FROM sSecurity.tUser WHERE Id=@rUserId AND OrgId= @rOrgId)
			--	 ORDER BY CM.OrderIndex
			--END
			--ELSE
			--BEGIN
				 Select OM.Id,CM.DisplayTitle+'-'+OM.DisplayTitle AS Title,
				 CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PC.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END  AS IsObsolete		
				 from  sSetup.tDivisionMaster OM
				 INNER JOIN sSetup.tClassMaster CM ON CM.Id=OM.ClassId
				 INNER JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id 
				 INNER JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId 
				 where OM.OrgId=@rOrgId  AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
				 ORDER BY CM.OrderIndex
			--END
	END
	
	if @rSourceTypeId=2014
	BEGIN
		Select OM.Id,OM.Title AS Title,
		CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PC.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END AS IsObsolete
		
		 from  sHostel.tHostelMaster OM
		 LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
		LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId 
		inner join  sSecurity.tUserAccess UA ON UA.SourceId=OM.Id AND UA.SourceTypeId=2014 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
		 where OM.OrgGroupId=@rOrgGroupId  
	END 
	
	if @rSourceTypeId=2029
	BEGIN
		Select OM.Id,OM.Title As Title,
		CASE WHEN PC.ScopeSourceId IS  NOT NULL AND PC.ScopeSourceTypeId=@rSourceTypeId   THEN 1 ELSE 0 END  AS IsObsolete
		
		
		 from  sActivity.tHouseMaster OM
		 LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
		LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId 
		 where OM.OrgId=@rOrgId  
	END
	IF (@rSourceTypeId = 2003)
	BEGIN
	
		SELECT OM.Id,
			  (SA.Code+' - '+CONVERT(NVARCHAR(10),SA.RollNo)+' - '+SA.Name) AS Title,
			  CASE WHEN PC.ScopeSourceId IS  NOT NULL AND PC.ScopeSourceTypeId=@rSourceTypeId   THEN 1 ELSE 0 END  AS IsObsolete
	
		FROM  sStudent.tStudentMaster OM
			  INNER JOIN  sStudent.vStudentAcademic SA ON OM.Id=SA.StudentId 
			  LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id  AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
			  LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId 
		WHERE SA.OrgId = @rOrgId AND SA.IsActiveBatch=1 AND SA.StatusId=1
	END
	IF (@rSourceTypeId = 95)
	BEGIN
	
		SELECT OM.EmployeeId AS Id,
			  OM.EmployeeName AS Title,
			  CASE WHEN PC.ScopeSourceId IS  NOT NULL AND PC.ScopeSourceTypeId=@rSourceTypeId   THEN 1 ELSE 0 END  AS IsObsolete
	
		FROM  sHrm.vEmployeeCommunication OM
			  LEFT JOIN sCommunication.tMultiPhotoCategoryScope PC ON PC.ScopeSourceId =OM.EmployeeId AND MultiPhotoCategoryId=@rPhotoCategoryId and PC.ScopeSourceTypeId=@rSourceTypeId
			  LEFT JOIN sCommunication.tMultiPhotoCategoryMaster PM ON PM.Id = PC.MultiPhotoCategoryId 
		WHERE OM.OrgId = @rOrgId
	END
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pMultiPhotoCategoryMaster_Get]
	 
	 @rScopeSourceId bigint=0,
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rSourcetypeId smallint,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
  
	IF @rSourcetypeId=2003
	BEGIN
		SELECT @lOrgGroupId=Om.OrgGroupId,@lOrgId=OM.Id ,@lOrgGroupBatchID=BM.OrgGroupBatchId  
		FROM sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId=OM.Id
		INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId 
		WHERE A.BatchId= @rBatchId AND A.Id=@rScopeSourceId 
	END
	ELSE IF @rSourcetypeId=95
	BEGIN
		SELECT @lOrgGroupId=Om.OrgGroupId, @lOrgId=OrgId 
		FROM sSetup.tOrganizationMaster OM INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgID=OM.Id 
		WHERE Em.Id=@rScopeSourceId AND ISNULL(EM.IsOtherUser,0) = 0
	END
	ELSE
	BEGIN
		SELECT @lOrgGroupId=OM.OrgGRoupId 
		FROM sSetup.tOrganizationMaster OM INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id 
		WHERE Bm.Id=@rBatchId
	END
 
	IF @rSourcetypeId=2003
	BEGIN
	SELECT DISTINCT
		PCM.[Id],
  		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCS.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId,
		PCM.ScopeSourceTypeId AS AssigneeId
		--PCS.AssigneeToId AS AssigneeId
	FROM 
		[sCommunication].[tMultiPhotoCategoryMaster] PCM 
		LEFT JOIN sCommunication.tMultiPhotoCategoryScope PCS  ON PCM.Id = PCS.MultiPhotoCategoryId 
		--comment for mantis Id:0030339
		--AND (PCS.ScopeSourceId = CASE WHEN PCS.ScopeSourceTypeId = 2005 THEN
		--(SELECT DivisionId FROM sStudent.tAcademic WHERE DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
		--WHEN PCS.ScopeSourceTypeId = 2016 THEN
		--(SELECT ClassId FROM sStudent.tAcademic WHERE DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
		--WHEN PCS.ScopeSourceTypeId = 2017 THEN
		--(SELECT D.Id FROM sSetup.tDepartmentMaster D INNER JOIN sSetup.tClassMaster CA ON CA.DepartmentId=D.Id 
		--INNER JOIN sStudent.tAcademic A ON A.ClassID=CA.Id WHERE A.Id =@rScopeSourceId)
		--WHEN PCS.ScopeSourceTypeId =2021 THEN
		--(SELECT OM.Id FROM sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId =OM.Id WHERE A.Id=@rScopeSourceId)
		--WHEN PCS.ScopeSourceTypeId =2014 THEN
		--(SELECT Hm.Id FROM sHostel.tHostelMaster Hm INNER JOIN  sHostel.tRoomMaster RA ON RA.HostelId=HM.Id 
		--INNER JOIN sHostel.tAssignRoom AR ON AR.RoomId=RA.Id
		--INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId 
		--WHERE AR.OrgGroupBatchId = @lOrgGroupBatchID AND HM.OrgGroupId=@lOrgGroupId AND A.Id=@rScopeSourceId)
		--WHEN PCS.ScopeSourceTypeId =2029 THEN
		--(SELECT HO.Id FROM sActivity.tHouseMaster HO
		--INNER JOIN sStudent.tStudentOther SO ON SO.HouseId=HO.Id 
		--INNER JOIN sStudent.tAcademic A ON A.StudentId=SO.StudentId
		--WHERE HO.OrgId=@lOrgId AND A.Id=@rScopeSourceId)
		--When PCS.ScopeSourceTypeId =2003 Then
		--(select StudentId from sStudent.tAcademic  Where StudentId = PCS.ScopeSourceId AND Id = @rScopeSourceId)
		--ENd)
		--LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = PCM.ScopeSourceTypeId	
		
	WHERE 
		--PCM.IsObsolete=0	
		(PCM.Id=@rId OR @rId=0) 
		AND PCM.OrgGroupId = @lOrgGroupId
	--ORDER BY PCM.CreatedDateTime DESC
	END
	ELSE IF @rSourcetypeId=95
	BEGIN 
	SELECT DISTINCT
		PCM.[Id],
		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCS.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId,
		PCM.ScopeSourceTypeId AS AssigneeId
		--PCS.AssigneeToId AS AssigneeId
	FROM 
		[sCommunication].[tMultiPhotoCategoryMaster] PCM 
		LEFT join sCommunication.tMultiPhotoCategoryScope PCS  ON PCM.Id = PCS.MultiPhotoCategoryId 
		--comment for mantis Id:0030339
		--AND
		--(PCS.ScopeSourceId = Case WHEN PCS.ScopeSourceTypeId = 2017 THEN
		--(SELECT D.Id FROM sSetup.tDepartmentMaster D 
		--INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.OrganizationDepartmentId=D.Id
		--WHERE EJ.EmployeeId=@rScopeSourceId AND EJ.OrgId=@lOrgId)
		--WHEN PCS.ScopeSourceTypeId=2021 THEN
		--(SELECT OM.Id FROM sSetup.tOrganizationMaster OM 
		--INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgId=OM.Id
		--WHERE EM.OrgId=@lOrgId and Em.Id=@rScopeSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
		--When PCS.ScopeSourceTypeId = 95 Then
		--(select Id from sHrm.tEmployeeMaster  Where Id = @rScopeSourceId)
		--END)
		--LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = PCM.ScopeSourceTypeId	

	WHERE 
		--PCM.IsObsolete=0 
		((PCM.Id = @rId) OR (@rId=0)) 
		AND PCM.OrgGroupId = @lOrgGroupId
		--ORDER BY PCM.CreatedDateTime DESC
	END
	ELSE
	BEGIN
	SELECT  DISTINCT
		PCM.[Id],
  		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCS.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId,
		PCM.ScopeSourceTypeId AS AssigneeId
		--PCS.AssigneeToId AS AssigneeId
	FROM    
		[sCommunication].[tMultiPhotoCategoryMaster]  PCM 
		INNER JOIN sCommunication.tMultiPhotoCategoryScope PCS  ON PCM.Id = PCS.MultiPhotoCategoryId 
		--LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = PCM.ScopeSourceTypeId
	WHERE   
		--PCM.IsObsolete = 0
		((PCM.Id = @rId) OR (@rId = 0))
		AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
		AND OrgGroupId=@lOrgGroupId
		--ORDER BY PCM.CreatedDateTime DESC
	END   
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pMultiPhotoCategoryMasterAdd]
	 
	 @rId int,
	 @rOrgGroupId int,
	 @rTitle nvarchar(100),
	 @rIsObsolete bit,
	 @rCreatedUserId bigint,
	 --@rScopeSourceTypeId is AssigneeId
	 @rScopeSourceTypeId smallint=0,
	 @rRemark nvarchar(300)='',
	 @rOrgGroupBatchId int = 0,
	 @rEventScheduleId int = 0,
	 @rTempPhotoCategoryId nvarchar(100)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
IF(@rId = 0)	
BEGIN
	IF EXISTS(Select 1 FROM sCommunication.tMultiPhotoCategoryMaster Where Title = @rTitle AND IsObsolete = 0 AND OrgGroupId=@rOrgGroupId AND OrgGroupBatchId=@rOrgGroupBatchId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END 
END
ELSE 
BEGIN 
	IF EXISTS(Select 1 FROM sCommunication.tMultiPhotoCategoryMaster Where Title = @rTitle AND OrgGroupId=@rOrgGroupId AND IsObsolete = 0  AND OrgGroupBatchId=@rOrgGroupBatchId AND Id!=@rId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END 
END
	
BEGIN TRY

BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN
  
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tMultiPhotoCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sCommunication].[tMultiPhotoCategoryMaster]
           (
            [Id]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId]
           ,ScopeSourceTypeId
           ,Remark
		   ,OrgGroupBatchId
		   ,EventScheduleId)
     VALUES
		(
			@lNextNumber,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
		    sCommon.fGetDate(),
			@rCreatedUserId,	 
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rScopeSourceTypeId,
			@rRemark,
			@rOrgGroupBatchId,
			@rEventScheduleId
		)
		             
END	 
ELSE
BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sCommunication].[tMultiPhotoCategoryMaster]
	    SET
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ScopeSourceTypeId=@rScopeSourceTypeId,
			Remark=@rRemark
			--OrgGroupBatchId = @rOrgGroupBatchId
	      
	      WHERE Id = @rId 	 
END

	 	INSERT INTO [sCommunication].[tMultiPhotoCategoryScope]
		SELECT @lNextNumber,SourceTypeId,SourceId,AssigneeToId
		FROM [sCommunication].[tTempMultiPhotoCategoryScope]
		WHERE TempMultiPhotoCategoryId = @rTempPhotoCategoryId
		
		DELETE FROM [sCommunication].[tTempMultiPhotoCategoryScope] WHERE TempMultiPhotoCategoryId = @rTempPhotoCategoryId

		SELECT @lNextNumber AS Result	   
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION

		--SELECT ERROR_MESSAGE()
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pMultiPhotoCategoryMasterDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		

		BEGIN
			DELETE FROM [sCommunication].[tMultiPhotoCategoryMaster] WHERE Id=@rId 
			SELECT 1 AS Result
		END		
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


 CREATE OR ALTER PROCEDURE [sCommunication].[pMultiPhotoCategoryScopeAdd]
			
		@rPhotoCategoryId int,
        @rScopeSourceId bigint,
		@rScopeSourceTypeId int,
        @rIsDeleted bit
          
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
 
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tMultiPhotoCategoryScope where MultiPhotoCategoryId=@rPhotoCategoryId AND ScopeSourceId=@rScopeSourceId AND ScopeSourceTypeId=@rScopeSourceTypeId
	Select @rScopeSourceId as Result
END	
ELSE
BEGIN 

	BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select MultiPhotoCategoryId from sCommunication.tMultiPhotoCategoryScope where MultiPhotoCategoryId=@rPhotoCategoryId AND ScopeSourceId=@rScopeSourceId AND ScopeSourceTypeId=@rScopeSourceTypeId)
		BEGIN
			SELECT @rScopeSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tMultiPhotoCategoryScope
			(
				MultiPhotoCategoryId,
				ScopeSourceTypeId,
			    ScopeSourceId
			)
			VALUES
			(	
				@rPhotoCategoryId,
				@rScopeSourceTypeId,
			    @rScopeSourceId
			)		
			SELECT @rPhotoCategoryId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END 	             
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pMultiPhotoCategoryScopeFromEventAdd]
			
@rMultiPhotoCategoryId int,
@rScopeSourceId bigint,
@rScopeSourceTypeId int
--@rIsDeleted bit
          
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
--If(@rIsDeleted=1)
--BEGIN
--	Delete from sCommunication.tPhotoCategoryScope where PhotoCategoryId=@rPhotoCategoryId AND ScopeSourceId=@rScopeSourceId
--	Select @rScopeSourceId as Result
--END	
--ELSE
--BEGIN 

	BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select MultiPhotoCategoryId from sCommunication.tMultiPhotoCategoryScope where MultiPhotoCategoryId=@rMultiPhotoCategoryId AND ScopeSourceId=@rScopeSourceId)
		BEGIN
			SELECT @rScopeSourceId AS Result
			RETURN
		END 
	ELSE
		BEGIN
			INSERT INTO sCommunication.tMultiPhotoCategoryScope
			(
				MultiPhotoCategoryId,
				ScopeSourceTypeId,
			    ScopeSourceId,
				AssigneeToId
			)
			VALUES
			(	
				@rMultiPhotoCategoryId,
				@rScopeSourceTypeId,
			    @rScopeSourceId,
				2
			)
			INSERT INTO sCommunication.tMultiPhotoCategoryScope
			(
				MultiPhotoCategoryId,
				ScopeSourceTypeId,
			    ScopeSourceId,
				AssigneeToId
			)
			VALUES
			(	
				@rMultiPhotoCategoryId,
				@rScopeSourceTypeId,
			    @rScopeSourceId,
				3
			)		
			SELECT @rMultiPhotoCategoryId AS Result
		END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
--END 	             
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pMultiPhotoCategoryScopeGet]
	 @rPhotoCategoryId bigint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.MultiPhotoCategoryId AS PhotoCategoryId,
			 CS.ScopeSourceTypeId,
			 CS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS ScopeSourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 --PCM.ScopeSourceTypeId AS AssigneeToId,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tMultiPhotoCategoryScope CS
			INNER JOIN sCommunication.tMultiPhotoCategoryMaster PCM ON PCM.Id = CS.MultiPhotoCategoryId
			INNER JOIN sSetup.tOrganizationMaster OM ON CS.ScopeSourceId=OM.Id
			--LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = PCM.ScopeSourceTypeId
			LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = CS.AssigneeToId
			WHERE CS.MultiPhotoCategoryId=@rPhotoCategoryId AND CS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 CS.MultiPhotoCategoryId AS PhotoCategoryId,
			 CS.ScopeSourceTypeId,
			 CS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS ScopeSourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 --PCM.ScopeSourceTypeId AS AssigneeToId,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tMultiPhotoCategoryScope CS
			INNER JOIN sCommunication.tMultiPhotoCategoryMaster PCM ON PCM.Id = CS.MultiPhotoCategoryId
			INNER JOIN sSetup.tDepartmentMaster DM ON CS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
			--LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = PCM.ScopeSourceTypeId
			LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = CS.AssigneeToId
			WHERE CS.MultiPhotoCategoryId=@rPhotoCategoryId AND CS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 CS.MultiPhotoCategoryId AS PhotoCategoryId,
			 CS.ScopeSourceTypeId,
			 CS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS ScopeSourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 --PCM.ScopeSourceTypeId AS AssigneeToId,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tMultiPhotoCategoryScope CS
			INNER JOIN sCommunication.tMultiPhotoCategoryMaster PCM ON PCM.Id = CS.MultiPhotoCategoryId
			INNER JOIN  sSetup.tClassMaster CM ON CS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
			--LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = PCM.ScopeSourceTypeId
			LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = CS.AssigneeToId
			WHERE CS.MultiPhotoCategoryId=@rPhotoCategoryId AND CS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 CS.MultiPhotoCategoryId AS PhotoCategoryId,
			 CS.ScopeSourceTypeId,
			 CS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS ScopeSourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 --PCM.ScopeSourceTypeId AS AssigneeToId,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tMultiPhotoCategoryScope CS
			INNER JOIN sCommunication.tMultiPhotoCategoryMaster PCM ON PCM.Id = CS.MultiPhotoCategoryId
			INNER JOIN   sSetup.tDivisionMaster DM ON CS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
			--LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = PCM.ScopeSourceTypeId
			LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = CS.AssigneeToId
			WHERE CS.MultiPhotoCategoryId=@rPhotoCategoryId AND CS.ScopeSourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.MultiPhotoCategoryId AS PhotoCategoryId,
			 CS.ScopeSourceTypeId,
			 CS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS ScopeSourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 --PCM.ScopeSourceTypeId AS AssigneeToId,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tMultiPhotoCategoryScope CS
			INNER JOIN sCommunication.tMultiPhotoCategoryMaster PCM ON PCM.Id = CS.MultiPhotoCategoryId
		    INNER JOIN sStudent.tStudentMaster SM ON CS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA ON CS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
			--LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = PCM.ScopeSourceTypeId
			LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = CS.AssigneeToId
			WHERE CS.MultiPhotoCategoryId=@rPhotoCategoryId AND CS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.MultiPhotoCategoryId AS PhotoCategoryId,
			 CS.ScopeSourceTypeId,
			 CS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS ScopeSourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 --PCM.ScopeSourceTypeId AS AssigneeToId,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tMultiPhotoCategoryScope CS
			INNER JOIN sCommunication.tMultiPhotoCategoryMaster PCM ON PCM.Id = CS.MultiPhotoCategoryId
		   	INNER JOIN  sStudent.vStudentAcademic SA ON CS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id	
			--LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = PCM.ScopeSourceTypeId
			LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = CS.AssigneeToId
			WHERE CS.MultiPhotoCategoryId=@rPhotoCategoryId AND CS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.MultiPhotoCategoryId AS PhotoCategoryId,
			 CS.ScopeSourceTypeId,
			 CS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS ScopeSourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 --PCM.ScopeSourceTypeId AS AssigneeToId,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			
			FROM sCommunication.tMultiPhotoCategoryScope CS
			INNER JOIN sCommunication.tMultiPhotoCategoryMaster PCM ON PCM.Id = CS.MultiPhotoCategoryId
			INNER JOIN sHrm.vEmployeeCommunication vEC  ON CS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id	
			--LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = PCM.ScopeSourceTypeId	
			LEFT JOIN sCommon.tAssigneeMaster AM  ON AM.Id = CS.AssigneeToId
			WHERE 
			CS.MultiPhotoCategoryId=@rPhotoCategoryId AND CS.ScopeSourceTypeId=95


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pMultiPhotoCategoryScopeRemove]
			
			@rTempPhotoCategoryId nvarchar(100),
			@rPhotoCategoryId int,
			@rSourceTypeId smallint,
			@rSourceId bigint,
			@rAssigneeToId tinyint,
			@rIsTempFlag int
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	IF(@rIsTempFlag = 1)
	BEGIN
		Delete from [sCommunication].[tTempMultiPhotoCategoryScope] where TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND SourceTypeId=@rSourceTypeId And AssigneeToId=@rAssigneeToId AND SourceId=@rSourceId
	END
	ELSE
	BEGIN
		Delete from [sCommunication].[tMultiPhotoCategoryScope] where MultiPhotoCategoryId=@rPhotoCategoryId AND ScopeSourceTypeId=@rSourceTypeId AND ScopeSourceId=@rSourceId
	END
	
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pMyAdmitCardGet]
	 
	 --@rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rDivisionId int,
	 @rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF (@rSourceId!=0)
	BEGIN
		SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
		 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	END
		SELECT 
			@rSourceId AS SourceId,
			UR.Id,
			UR.Title,
			UR.ExamDate,
			S.Code ,
			BM.OrgId
			 
		FROM 
			sCommunication.tUploadResult UR  
			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = UR.DivisionId AND UR.BatchId = S.BatchId 
			AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
		WHERE 
			UR.DivisionId=@rDivisionId
			AND UR.BatchId=@rBatchId
			AND UR.IsObsolete=0
			AND ( UR.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
			and UR.ExamDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
			AND ISNULL(UR.UploadTypeId,1) = 2
				order by UR.ExamDate,S.RollNo,S.Code DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pMyBlogGet]
	 @rId bigint,
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
	
			B.Id,
			B.OrgGroupBatchId,
		    OGBM.Title AS OrgGroupBatch,
		    B.Title,
		    B.Remark,
		    B.CreatedDateTime AS BlogCreatedDateTime,
		    TotalBlogFavorite=(Select count(*) from sCommunication.tBlogFavorite where UserId=@rCreatedUserId),
		    TotalBlogComment=(Select count(*) from sCommunication.tBlogComment where BlogId=@rId)
  FROM 
            sCommunication.tBlog B
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=B.OrgGroupBatchId
  WHERE 
  
      ((B.Id = @rId) OR (@rId = 0))
    AND ((B.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0)) 
	AND ((B.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pMyBookGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rBatchId int,
	 @rStatusId int=0,
	 @rLibraryId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 



	select 
		BL.Id AS BookLogId,
		BM.Title AS BookTitle,
		BL.LogDate AS IssueDate,
		--BL.IsCurrentStatus AS IsReturnPending,
		BL.StatusId AS StatusId,
		CASE WHEN SM.Title = 'Available' THEN 'Return' ELSE SM.Title END AS StatusName,
		--due to status not display properly
		--(CASE WHEN (ISNULL(BL.ReturnDate,'')!='' OR BL.BookActionStatusId=1) THEN 'Return'
		--	 WHEN BL.BookActionStatusId=2 THEN 'Release'
		--	 ELSE SM.Title END) AS StatusName,
		CASE WHEN BL.IsCurrentStatus = 1 THEN 'Pending' ELSE 'Return' END AS IsReturnPending,
		BL.DueDate,
		BL.LibraryId ,
		ISNULL(BM.Author,'')AS Author,
	--CASE WHEN BL.IsCurrentStatus = 0 THEN BL.DueDate ELSE '' END AS DueDate
		ISNULL(BM.Code, '') AS Code --Added for mantis : 36170 by Nilesh

	  from 
		  sLibrary.tBookLog BL 
		  INNER JOIN sLibrary.tBookMaster BM
		  ON BL.ResourceSourceId = BM.Id AND BL.ResourceSourceTypeId = 2009  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = BL.StatusId AND SM.statusTypeId = 106
	  WHERE 
		  --BL.statusId = 523
		  BL.ReaderSourceId = @rReaderSourceId
		  AND BL.ReaderSourceTypeId = @rReaderSourceTypeId
		  AND (BL.StatusId = @rStatusId OR @rStatusId=0)
		  AND (BL.LibraryId= @rLibraryId OR @rLibraryId=0)
		  AND (SM.Id!=521 OR ISNULL(BL.BookActionStatusId,0)!=0)
		  AND (BL.BatchId = @rBatchId OR @rBatchId = 0)
	  
	  ORDER BY BL.LogDate DESC,BL.CreatedDateTime DESC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pMyDashboardNotificationGet]

@rOrgId int,	 
@rBatchId int,
@rOrgGroupBatchId int,
@rUserId bigint,
@rUserSourceId bigint,
@rUserSourceTypeId int,
@rSyncedAssignmentId bigint= null,
@rSyncedCircularId bigint= null,
@rSyncedPollId bigint= null,
@rSyncedQueryCommentId bigint= null,
@rSyncedNewsId bigint= null,
@rSyncedBlogId bigint= null,
@rSyncedBehaviourId bigint= null,
@rSyncedActivityId bigint= null,
@rSyncedResultId bigint= null,
@rSyncedAssignTaskId bigint= null,
@rSyncedPhotoCategoryId int= null


	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		 

BEGIN 
	DECLARE
	@rSyncedAssignmentDateTime DateTime = null,
	@rSyncedCircularDateTime DateTime= null,
	@rSyncedPollDateTime DateTime= null,
	@rSyncedQueryCommentDateTime DateTime= null,
	@rSyncedNewsDateTime DateTime= null,
	@rSyncedBlogDateTime DateTime= null,
	@rSyncedBehaviourDateTime DateTime= null,
	@rSyncedActivityDateTime DateTime= null,
	@rSyncedResultDateTime DateTime= null,
	@rSyncedAssignTaskDateTime DateTime= null,
	@rSyncedPhotoCategoryDateTime DateTime= null,
	@rSyncedClassworkDateTime DateTime= null,
	 @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,
	 @lClassworkStatus bit=0
	 
	 SELECT @rSyncedAssignmentDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20780
	 SELECT @rSyncedCircularDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20762
	 SELECT @rSyncedPollDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20782
	 SELECT @rSyncedQueryCommentDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20770
	 SELECT @rSyncedNewsDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20777
	 SELECT @rSyncedBlogDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20774
	 SELECT @rSyncedBehaviourDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20808
	 SELECT @rSyncedActivityDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20784
	 SELECT @rSyncedResultDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20805
	 SELECT @rSyncedAssignTaskDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20795
	 SELECT @rSyncedPhotoCategoryDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20787
	 SELECT @rSyncedClassworkDateTime = LastAccessDateTime FROM sSecurity.tUserDashboardNotification WHERE UserId =@rUserId AND ScreenId = 20802 
	

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 A.CreatedDateTime > @rSyncedAssignmentDateTime 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.CreatedDateTime > @rSyncedCircularDateTime)
        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.CreatedDateTime > @rSyncedCircularDateTime)
       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 (SELECT PM.PollId FROM sCommunication.tPollMember PM WHERE
      (
      (PM.SourceTypeId = 2021 AND PM.SourceId =@lOrgId) 
      OR (PM.SourceTypeId = 2004 AND PM.SourceId =@lDepartmentId)
      OR (PM.SourceTypeId = 2016 AND PM.SourceId =@lClassId)
      OR (PM.SourceTypeId = 2005 AND PM.SourceId =@lDivisionId)
       OR (PM.SourceTypeId = 2003 AND PM.SourceId =@lStudentId)
        --OR (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId)
        
      )
        ) D ON D.PollId = P.Id 
	WHERE P.CreatedDateTime > @rSyncedPollDateTime 
	--AND PM.SourceTypeId = @lScopeSourceTypeId 
	--AND PM.SourceId = @lScopeSourceId AND 
	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 B.CreatedDateTime > @rSyncedBlogDateTime AND BS.SourceTypeId = 1016 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 N.CreatedDateTime > @rSyncedNewsDateTime AND NS.SourceTypeId = 1016 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 CreatedDateTime > @rSyncedResultDateTime AND DivisionId = @lScopeSourceId AND BatchId=@rBatchId AND IsObsolete=0 )
--SET @lResultStatus = 1

IF EXISTS(SELECT 1 FROM  
sCommunication.tPhotoCategoryMaster PCM
INNER JOIN sCommunication.tPhotoCategoryOrg PCO 
ON PCM.Id=PCO.PhotoCategoryId WHERE PCM.CreatedDateTime > @rSyncedPhotoCategoryDateTime AND PCO.OrgId = @rOrgId  AND PCM.IsObsolete=0 )
SET @lPhotoCategoryStatus = 1


IF EXISTS(SELECT 1 FROM sCommunication.tAssignTask WHERE  CreatedDateTime > @rSyncedAssignTaskDateTime 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 A.CreatedDateTime > @rSyncedActivityDateTime AND 
	AP.SourceTypeId = @rUserSourceTypeId AND AP.SourceId = @rUserSourceId AND A.BatchId=@rBatchId)
SET @lActivityStatus = 1



IF EXISTS(SELECT 1 FROM sCommunication.tBehaviour WHERE CreatedDateTime > @rSyncedBehaviourDateTime 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.CreatedDateTime > @rSyncedQueryCommentDateTime AND QC.CreatedUserId <> @rUserSourceId AND Q.OrgGroupBatchId=@rOrgGroupBatchId)
SET @lQueryStatus = 1
 
 
 IF EXISTS(SELECT 1 FROM sAcademic.tClasswork CW  
WHERE CW.CreatedDateTime > @rSyncedClassworkDateTime  AND CW.DivisionId = @lDivisionId AND CW.BatchId=@rBatchId)
SET @lClassworkStatus = 1
 
 
CREATE TABLE #Module (
Id int,
Title nvarchar(20),
IsNew bit )
--INSERT INTO #Module VALUES (20762,'Circular',@lCircularStatus)
INSERT INTO #Module VALUES (20762,'Circular',@lCircularStatus)
INSERT INTO #Module VALUES (20770,'Query',@lQueryStatus)
INSERT INTO #Module VALUES (20774,'Blog',@lBlogStatus)
INSERT INTO #Module VALUES (20777,'News',@lNewsStatus)
INSERT INTO #Module VALUES (20795,'AssignTask',@lAssignTaskStatus)
INSERT INTO #Module VALUES (20787,'Gallery',@lPhotoCategoryStatus)
INSERT INTO #Module VALUES (20782,'Poll',@lPollStatus)
INSERT INTO #Module VALUES (20780,'Assignment',@lAssignmentStatus)
INSERT INTO #Module VALUES (20784,'Activity',@lActivityStatus)
INSERT INTO #Module VALUES (20808,'Behaviour',@lBehaviourStatus)
--INSERT INTO #Module VALUES (20805,'Result',@lResultStatus)
INSERT INTO #Module VALUES (20802,'Classwork',@lClassworkStatus)

 
-- INSERT INTO #Module VALUES (20762,'Circular',1)
--INSERT INTO #Module VALUES (20770,'Query',0)
--INSERT INTO #Module VALUES (20102,'Blog',1)
--INSERT INTO #Module VALUES (20104,'News',1)
--INSERT INTO #Module VALUES (20777,'AssignTask',0)
--INSERT INTO #Module VALUES (20787,'Gallery',1)
--INSERT INTO #Module VALUES (20782,'Poll',0)
--INSERT INTO #Module VALUES (20780,'Assignment',1)
--INSERT INTO #Module VALUES (20784,'Activity',1)
--INSERT INTO #Module VALUES (20808,'Behaviour',1)
--INSERT INTO #Module VALUES (20805,'Result',1)
 
 SELECT * FROM #Module
 
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pMyGroupGet]
	 @rCreatedUserId bigint,
	 @rSourceTypeId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF(@rSourceTypeId = 95)
	BEGIN
	SELECT 
	
			DGM.DiscussionGroupId,
			DG.Title AS DiscussionGroup
  FROM 
            sCommunication.tDiscussionGroupMember DGM
		INNER JOIN sCommunication.tDiscussionGroup DG ON DG.Id=DGM.DiscussionGroupId
		INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=DGM.SourceId AND DGM.SourceTypeId=95
		INNER JOIN sSecurity.tUser U ON U.SourceId=EM.Id		
  WHERE 
  
      ((U.Id = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((U.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0)) AND ISNULL(EM.IsOtherUser,0) = 0
	order by DG.Title
	END
	ELSE
	BEGIN
	SELECT 
	
			DGM.DiscussionGroupId,
			DG.Title AS DiscussionGroup
  FROM 
            sCommunication.tDiscussionGroupMember DGM
		INNER JOIN sCommunication.tDiscussionGroup DG ON DG.Id=DGM.DiscussionGroupId
		INNER JOIN sStudent.vStudentName SN ON SN.AcademicId=DGM.SourceId AND DGM.SourceTypeId=2001
		INNER JOIN sSecurity.tUser U ON U.SourceId=SN.StudentId		
  WHERE 
  
      ((U.Id = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((U.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0))
	order by DG.Title
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pMyMessagesGet]
	
	@rMobileNumber nvarchar(50),
	@rEmail nvarchar(50),
	@rFromDate date,
	@rToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
SET @rToDate = DATEADD(day,1,@rToDate)
	SELECT 
		AL.ContactId,
		AL.AlertMessage,
		EM.Title AS EventName,
		AL.CreatedDateTime,
		CASE 
			WHEN AL.AlertModeId = 1 THEN 'Email' 
			WHEN AL.AlertModeId = 2 THEN 'SMS' 
		END AS AlertMode
	FROM
		sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
	WHERE 
		((AL.CreatedDateTime >= @rFromDate)  OR (ISNULL(@rFromDate,'') = ''))
	    AND ((AL.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		AND ((AL.ContactId = @rMobileNumber) OR (AL.ContactId = @rEmail))
		ORDER BY AL.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sCommunication].[pMyQueryListGet]	 
	 @rQueryCategoryId int = 0,
	 --@rTitle nvarchar(100),
	 @rOrgGroupBatchId int,
	 @rId bigint = 0 ,  -- Add Initially 0 mantis : 0028594	
	 @rCreatedUserId bigint=0,
	 @rSyncedQueryId bigint = 0,
	 @rStatusId int = 0,
	 @rCreatedFromDate date=NULL,
	 @rCreatedToDate date=NULL, 
	 @rFromResolutionDate date=NULL,
	 @rToResolutionDate date=NULL,
	 @rFromSourceTypeId smallint=0,  
	 @rTitle nvarchar(100)='',  
	 @rNumber smallint=0,
	 @rQueryStatus varchar(25)=NULL ,
	 @rAssignedToEmployeeId bigint=0,
	 @rSourceId bigint=0,
	 @FromPage varchar(50)='',
	 @rAssignedToId smallint = 0,
	 @rUserSourceTypeId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	  BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  END
	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
		
		IF @rUserSourceTypeId   = 95 -- For Employee Login
		BEGIN
			 SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId


			SELECT 
					QM.Id AS QueryId,
					QCM.Id AS QueryCategoryId,
					ISNULL(QCM.Title,'') AS QueryCategoryMaster,
					QM.Title,
					QM.Remark,
					QM.CreatedDateTime,
					QM.StatusId,
					ISNULL(sm.Title,'') AS StatusMaster,
					QM.IsAssigneeView,
					QM.IsUserView,
					QM.CreatedUserId AS QueryCreatedUserId,
					ISNULL(QM.SubjectId,0) AS SubjectId,
					ISNULL(SubM.Title,'') AS SubjectName,
					ISNULL(QM.Number,0) AS Number,
					ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
					ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
					ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
					ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
					--ISNULL(QM.FromSourceId,0) AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
					   ELSE ''
					END AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
					   ELSE ''
					END AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
																			DM.Title
																	   FROM 
																			[sStudent].[vStudentAcademic] A 
																			 INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
																			 INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
																	   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
																	   )
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
																			DM.Title
																	   FROM 
																			sHrm.tEmployeeJobDetail EJD
																			 INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
																	   WHERE EmployeeId=QM.FromSourceId
																	   )			                                                   
			  
					   ELSE ''
					END AS Code,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
																			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
																	   FROM 
																			sStudent.tStudentMaster SM			                                                       
																	   WHERE Id=QM.FromSourceId 
																	   )
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
																			EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
																	   FROM 
																			sHrm.tEmployeeMaster EM
																	   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
																	   )			                                                   
			  
					   ELSE ''
					END AS Name,
					ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate ,
					(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
		  FROM 
					sCommunication.tQuery QM
				INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
				INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
				LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
				INNER JOIN 
				(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				 WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))
				 ) D
				ON D.QueryCategoryId= QCM.Id
		  WHERE 
					((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
				AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
				AND ((QM.Id=@rId) OR (@rId=0))
				AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
				AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
				AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
				AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
				AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
				AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
				AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
				AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
				AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
				AND ((QM.Number=@rNumber) OR (@rNumber=0))
				AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
				AND ISNULL(EM.IsOtherUser,0) = 0
				--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
				AND QCM.AssignedToId IN (1,3) 
        
			  UNION 
		SELECT 
					QM.Id AS QueryId,
					QCM.Id AS QueryCategoryId,
					ISNULL(QCM.Title,'') AS QueryCategoryMaster,
					QM.Title,
					QM.Remark,
					QM.CreatedDateTime,
					QM.StatusId,
					ISNULL(sm.Title,'') AS StatusMaster,
					QM.IsAssigneeView,
					QM.IsUserView,
					QM.CreatedUserId AS QueryCreatedUserId,
					ISNULL(QM.SubjectId,0) AS SubjectId,
					ISNULL(SubM.Title,'') AS SubjectName,
					ISNULL(QM.Number,0) AS Number,
					ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
					ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
					ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
					ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
					--ISNULL(QM.FromSourceId,0) AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
					   ELSE ''
					END AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
					   ELSE ''
					END AS FromSourceId,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
																			DM.Title
																	   FROM 
																			[sStudent].[vStudentAcademic] A 
																			 INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
																			 INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
																	   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
																	   )
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
																			DM.Title
																	   FROM 
																			sHrm.tEmployeeJobDetail EJD
																			 INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
																	   WHERE EmployeeId=QM.FromSourceId
																	   )			                                                   
			  
					   ELSE ''
					END AS Code  ,
					CASE 
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
																			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
																	   FROM 
																			sStudent.tStudentMaster SM			                                                       
																	   WHERE Id=QM.FromSourceId 
																	   )
					   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
																			EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
																	   FROM 
																			sHrm.tEmployeeMaster EM
																	   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
																	   )			                                                   
			  
					   ELSE ''
					END AS Name,
					ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate,
					(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
		  FROM 
					sCommunication.tQuery QM
				INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
				INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
			   -- INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 --AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
				LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
				INNER JOIN 
				(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				 WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))
				 ) D
				ON D.QueryCategoryId= QCM.Id
		  WHERE 
					((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
				AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
				AND ((QM.Id=@rId) OR (@rId=0))
				--AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
				--AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
				AND ((QM.FromSourceId=@rSourceId) OR (@rSourceId=0))
        
        
				AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
				AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
				AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
				AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
				AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
				AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
				AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
				AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
				AND ((QM.Number=@rNumber) OR (@rNumber=0))
				AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
				AND ISNULL(EM.IsOtherUser,0) = 0
				--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
				AND QCM.AssignedToId IN (1,3) 
				ORDER BY QM.CreatedDateTime DESC



		END

		ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
		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 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
			WHERE StudentId = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

			SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN (SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
            WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
            (QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
            (QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
            (QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
            (QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
            (QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
            )AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D
			ON	D.QueryCategoryId= QCM.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,2) 
        
      UNION 
SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code  ,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
       -- INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 --AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN (SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
            WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
            (QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
            (QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
            (QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
            (QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
            (QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
            )AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D
			ON	D.QueryCategoryId= QCM.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        --AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
        AND ((QM.FromSourceId=@rSourceId) OR (@rSourceId=0))
        
        
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,2) 
        ORDER BY QM.CreatedDateTime DESC
		END
		
		 ELSE --For Other Users
		 BEGIN
			
			SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ISNULL(EM.IsOtherUser,0) = 0
		AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
        
      UNION 
SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code  ,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
       -- INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 --AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        --AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
        AND ((QM.FromSourceId=@rSourceId) OR (@rSourceId=0))
        
        
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ISNULL(EM.IsOtherUser,0) = 0
		AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
        ORDER BY QM.CreatedDateTime DESC
		 END
		 

--	SELECT 
--			QM.Id AS QueryId,
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.IsAssigneeView,
--			QM.IsUserView,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			ISNULL(QM.SubjectId,0) AS SubjectId,
--			ISNULL(SubM.Title,'') AS SubjectName,
--			ISNULL(QM.Number,0) AS Number,
--			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
--			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
--			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
--			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
--			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        [sStudent].[vStudentAcademic] A 
--			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
--			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
--			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        sHrm.tEmployeeJobDetail EJD
--			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
--			                                                   WHERE EmployeeId=QM.FromSourceId
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Code,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
--			                                                   FROM 
--			                                                        sStudent.tStudentMaster SM			                                                       
--			                                                   WHERE Id=QM.FromSourceId 
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
--			                                                   FROM 
--			                                                        sHrm.tEmployeeMaster EM
--			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Name,
--			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate ,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
--  FROM 
--			sCommunication.tQuery QM
--		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
--        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
--        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
--  WHERE 
--			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
--        AND ((QM.Id=@rId) OR (@rId=0))
--        AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
--        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
--        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
--        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
--        AND ((QM.Number=@rNumber) OR (@rNumber=0))
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--        AND ISNULL(EM.IsOtherUser,0) = 0
--		AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
        
--      UNION 
--SELECT 
--			QM.Id AS QueryId,
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.IsAssigneeView,
--			QM.IsUserView,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			ISNULL(QM.SubjectId,0) AS SubjectId,
--			ISNULL(SubM.Title,'') AS SubjectName,
--			ISNULL(QM.Number,0) AS Number,
--			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
--			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
--			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
--			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
--			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        [sStudent].[vStudentAcademic] A 
--			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
--			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
--			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        sHrm.tEmployeeJobDetail EJD
--			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
--			                                                   WHERE EmployeeId=QM.FromSourceId
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Code  ,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
--			                                                   FROM 
--			                                                        sStudent.tStudentMaster SM			                                                       
--			                                                   WHERE Id=QM.FromSourceId 
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
--			                                                   FROM 
--			                                                        sHrm.tEmployeeMaster EM
--			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Name,
--			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate,
--			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
--  FROM 
--			sCommunication.tQuery QM
--		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
--        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
--       -- INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 --AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
--        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
--  WHERE 
--			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
--        AND ((QM.Id=@rId) OR (@rId=0))
--        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
--        --AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
--        AND ((QM.FromSourceId=@rSourceId) OR (@rSourceId=0))
        
        
--        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
--        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
--        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
--        AND ((QM.Number=@rNumber) OR (@rNumber=0))
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
--        AND ISNULL(EM.IsOtherUser,0) = 0
--		AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
--        ORDER BY QM.CreatedDateTime DESC
        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pMyResultViewDetailGet]
	 
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0,
	@rResultId bigint=0,
	@rExamId int=0,
	@rExamTypeId tinyint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
SELECT
		VR.ResultId, 
		VR.ExamId,
		0 AS ReportId,
		VR.ExamName AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		VR.TotalMarks,
		VR.TotalObtain,
		ISNULL(VR.ResultStatus,'') AS ResultStatus,
		VR.ResultGrade,
		VR.RankNumber,
		VR.Percentage,
		VR.Percentile,	
		0 AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName,
		VRD.Maximum,
		VRD.Minimum,
		VRD.Obtain,
		VRD.SubjectCode AS SubjectCode, 
		VRD.SubjectName AS SubjectName, 
		CASE WHEN (ISNULL(VRD.SubjectGrade,'') = '') THEN '-' ELSE VRD.SubjectGrade END AS SubjectGrade,
		--ISNULL(VRD.SubjectGrade,'-') AS SubjectGrade,
		VRD.ExamTypeId,
		VRD.IsPresent
FROM 
		sCommunication.tViewResult VR 
		INNER JOIN sCommunication.tViewResultDetail VRD ON VRD.ResultId=VR.ResultId 
		AND VR.ExamId = VRD.ExamId AND VR.ExamTypeId=VRD.ExamTypeId AND VR.ResultId = VRD.ResultId
		INNER JOIN sStudent.tAcademic A ON A.Id=VR.AcademicId
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	WHERE 	
		((StuM.Id = @rStudentId) or(@rStudentId=0))
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND ((VR.ResultId=@rResultId)OR(@rResultId=0))
		AND ((VR.ExamId=@rExamId)OR(@rExamId=0))
		AND ((VRD.ExamTypeId=@rExamTypeId)OR(@rExamTypeId=0))
	    ORDER BY VRD.SubjectOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pMyResultViewGet]
	 
	@rExamSubGroupId int = 0,
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
SELECT
		VR.ResultId, 
		VR.ExamId,
		0 AS ReportId,
		VR.ExamName AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		VR.TotalMarks,
		VR.TotalObtain AS Obtain,
		VR.ResultStatus,
		VR.ResultGrade,
		VR.RankNumber,
		VR.Percentage,
		VR.Percentile,	
		0 AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName,
		VR.ExamTypeId
FROM 
		sCommunication.tViewResult VR
		INNER JOIN sStudent.tAcademic A ON A.Id=VR.AcademicId
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--INNER JOIN sAssessment.tExamMaster E ON VR.ExamId = E.Id
		--INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	WHERE 
		--(ESGM.Id=@rExamSubGroupId OR @rExamSubGroupId=0)
		--AND 
		StuM.Id = @rStudentId 
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		--AND (E.IsPublished = 1)
		--AND ISNULL(E.ReportId,0)  > 0
		ORDER BY VR.ResultOrder DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pMyTeacherGet]

	
	 @rOrgId int,
	 @rDivisionId bigint 
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
 
SELECT
		Em.FirstName+' ' +EM.MiddleName+' ' +EM.LastName As Name,
		SB.Title AS SubjectName,
		ISNULL(EI.EmployeePhoto,CONVERT(VARBINARY(MAX), 0)) As EmployeePhoto,
		 
		EM.Id As EmployeeID
		From
		sHrm.tEmployeeMaster EM
		INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.EmployeeId =EM.Id
		INNER JOIN sSetup.tSubjectMaster SB ON SB.Id=TS.SubjectId AND SB.OrgId=@rOrgId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id
		Where EM.OrgID=@rOrgId AND TS.DivisionId=@rDivisionId AND ISNULL(EM.IsOtherUser,0) = 0
		

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--------------------
CREATE OR 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
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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pNewsAdd]
	 
        @rId bigint,
        @rOrgGroupId smallint,
        @rOrgGroupBatchId int,
		@rTitle nvarchar(200),
		@rRemark nvarchar(max),
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tNews where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tNews where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tNews', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tNews
		(
			Id,
			Title,
			Remark,
			OrgGroupId,
			OrgGroupBatchId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tNews
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pNewsCommentAdd]
	 
        --@rId bigint,
		@rNewsId bigint,
		@rRemark nvarchar(500),
		@rCreatedUserId bigint,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	--IF(@rId = 0)	
	--BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tNewsComment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tNewsComment
		(
			Id,
			NewsId,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rNewsId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	--END	 

--ELSE
--	 BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  sCommunication.tNewsComment
--	    SET
--			NewsId=@rNewsId,
--			Remark=@rRemark,
--			UpdatedUserId=@rCreatedUserId,
--			UpdatedDateTime=sCommon.fGetDate()
	      
--	      WHERE Id = @rId
--	      SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION
--	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pNewsCommentDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tNewsComment where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pNewsCommentGet]
	   @rNewsId bigint,
	 --@rBatchId bigint
	   --@rSyncedNewsCommentId bigint=0,
	   @rOrgGroupBatchId int=0,
	   @rOrgId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	 
IF(@rOrgId>0)	 
BEGIN
	SELECT 
			NC.Id,
			NC.NewsId,
			N.Title,
			N.Remark AS NewsRemark,
			--N.BatchId,
		 --   BM.Title AS Batch,
		    NC.Remark,
		    U1.DisplayTitle as NewsCreatedUserName,
		    N.CreatedDateTime as NewsCreatedDateTime,
		    U2.DisplayTitle as CommentCreatedUserName,
		    NC.CreatedDateTime as CommentCreatedDateTime,
		    N.CreatedUserId AS NewsCreatedUserId,
		    NC.CreatedUserId AS CommentCreatedUserId
  FROM 
            sCommunication.tNewsComment NC
            INNER JOIN sCommunication.tNews N ON N.Id=NC.NewsId
            INNER JOIN sSecurity.tUser U1 ON U1.Id=N.CreatedUserId
            INNER JOIN sSecurity.tUser U2 ON U2.Id=NC.CreatedUserId
            INNER JOIN sCommunication.tNewsScope NS ON NS.NewsId=N.Id AND ((NS.SourceId=@rOrgId)OR (@rOrgId=0))
  WHERE 
  
     ((N.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
     AND (( NC.NewsId = @rNewsId) OR (@rNewsId = 0))
	--AND ( NC.Id > @rSyncedNewsCommentId OR @rSyncedNewsCommentId = 0)
	Order by NC.CreatedDateTime DESC
END

ELSE IF(@rOrgId=0)	
BEGIN

SELECT 
			NC.Id,
			NC.NewsId,
			N.Title,
			N.Remark AS NewsRemark,
			--N.BatchId,
		 --   BM.Title AS Batch,
		    NC.Remark,
		    U1.DisplayTitle as NewsCreatedUserName,
		    N.CreatedDateTime as NewsCreatedDateTime,
		    U2.DisplayTitle as CommentCreatedUserName,
		    NC.CreatedDateTime as CommentCreatedDateTime,
		    N.CreatedUserId AS NewsCreatedUserId,
		    NC.CreatedUserId AS CommentCreatedUserId
  FROM 
            sCommunication.tNewsComment NC
            INNER JOIN sCommunication.tNews N ON N.Id=NC.NewsId
            INNER JOIN sSecurity.tUser U1 ON U1.Id=N.CreatedUserId
            INNER JOIN sSecurity.tUser U2 ON U2.Id=NC.CreatedUserId
  WHERE 
  
      ((NC.NewsId = @rNewsId) OR (@rNewsId = 0))
	Order by NC.CreatedDateTime DESC
END
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pNewsDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tNewsComment where NewsId=@rId
			Delete From sCommunication.tNewsScope Where NewsId=@rId
			Delete from sCommunication.tNews where Id=@rId
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pNewsGet]
	 
	 @rId bigint=0,
	 @rOrgGroupBatchId int,
	 @rTitle nvarchar(200),
	 @rIsSearch bit = 1,
	 @rOrgId smallint,
	 @rSyncedNewsId bigint = 0,
	 @rFromDate date='',
	 @rToDate date=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF @rIsSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			DISTINCT(N.Id),
			N.OrgGroupBatchId,
		    OGBM.Title AS OrgGroupBatch,
		    N.Title,
		    N.Remark,
		    U.DisplayTitle AS NewsCreatedUserName,
		    N.CreatedDateTime AS NewsCreatedDateTime,
		    (SELECT ISNULL( Count(1),0) FROM sCommunication.tNewsComment NC WHERE NC.NewsId = N.Id) AS TotalNewsComment
		    
	FROM 
			sCommunication.tNews N
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=N.OrgGroupBatchId
			INNER JOIN sSecurity.tUser U ON U.Id=N.CreatedUserId
			INNER JOIN sCommunication.tNewsScope NS ON NS.NewsId=N.Id AND ((NS.SourceId=@rOrgId)OR (@rOrgId=0))
	WHERE 
	  
			((N.Id = @rId) OR (@rId = 0))
		AND ((N.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((N.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND ( N.Id > @rSyncedNewsId OR @rSyncedNewsId = 0)
		AND (CONVERT(date,N.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (CONVERT(date,N.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='')
		
		order by N.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pNewsScopeAdd] @rNewsId BIGINT
	,@rSourceTypeId SMALLINT
	,@rSourceId BIGINT
	,@rIsDeleted BIT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF (@rIsDeleted = 1)
	BEGIN
		DELETE
		FROM sCommunication.tNewsScope
		WHERE NewsId = @rNewsId
			AND SourceTypeId = @rSourceTypeId
			AND SourceId = @rSourceId

		SELECT @rSourceId AS Result
	END
	ELSE
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION

			IF EXISTS (
					SELECT NewsId
					FROM sCommunication.tNewsScope
					WHERE NewsId = @rNewsId
						AND SourceTypeId = @rSourceTypeId
						AND SourceId = @rSourceId
					)
			BEGIN
				SELECT @rSourceId AS Result
				COMMIT TRANSACTION
				RETURN
			END
			ELSE
			BEGIN
				INSERT INTO sCommunication.tNewsScope (
					NewsId
					,SourceTypeId
					,SourceId
					)
				VALUES (
					@rNewsId
					,@rSourceTypeId
					,@rSourceId
					)

				SELECT @rNewsId AS Result
			END

			COMMIT TRANSACTION
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION

			SELECT - 1 AS Result
		END CATCH
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pNewsScopeGet]
	 @rNewsId bigint,
	 @rOrgGroupId smallint,
	 @rUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OM.Id  as SourceId,
			OM.DisplayTitle as Organization,
			1016 as SourceTypeId,
			CASE WHEN NS.SourceId IS NULL OR NS.NewsId!=@rNewsId THEN 0 ELSE 1 END AS IsObsolete
  FROM 
			sSetup.tOrganizationMaster OM
			INNER JOIN sSetup.vUserOrganization UO ON UO.Id=OM.Id AND UO.OrgGroupId=@rOrgGroupId AND UO.UserId=@rUserId
			LEFT JOIN sCommunication.tNewsScope NS ON NS.SourceId=OM.Id AND NS.SourceTypeId=2021 AND NS.NewsId=@rNewsId
	Order BY OM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pOnlineLearningAttendance]
	 @rOnlineLearningId bigint ,
	 @rSourceId bigint,
	 @rOrgId int,
	 @rAttendanceTypeId int,
	 @rIsMultiLogInAllowed bit 
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
IF(@rAttendanceTypeId= 1) 
BEGIN
	IF(@rIsMultiLogInAllowed =0)
	BEGIN
		IF((SELECT ISNULL(IsLoggedIn,0) FROM sAcademic.tOnlineLearningAttendance WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)= 1)
		BEGIN
		SELECT -1 AS Result
		END
		ELSE 
			BEGIN
	 
			IF NOT EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningAttendance WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
			BEGIN
			INSERT  INTO sAcademic.tOnlineLearningAttendance 
			(OnlineLearningId,AcademicId, IsPresent ,FirstInDateTime,IsLoggedIn)
			VALUES 
			(@rOnlineLearningId,@rSourceId,1,GetDate(),'true')
			END
				
			INSERT  INTO sAcademic.tOnlineLearningAttendanceLog 
			(OnlineLearningId,AcademicId,ActivityId,CreatedDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rAttendanceTypeId,GetDate())
			SELECT 1 AS Result	
			END
		END
		ELSE IF (@rIsMultiLogInAllowed = 1)
		BEGIN
	 
			IF NOT EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningAttendance WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
			BEGIN
			INSERT  INTO sAcademic.tOnlineLearningAttendance 
			(OnlineLearningId,AcademicId, IsPresent ,FirstInDateTime,IsLoggedIn)
			VALUES 
			(@rOnlineLearningId,@rSourceId,1,GetDate(),'true')
			END
				
			INSERT  INTO sAcademic.tOnlineLearningAttendanceLog 
			(OnlineLearningId,AcademicId,ActivityId,CreatedDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rAttendanceTypeId,GetDate())
			SELECT 1 AS Result	
		END
END	
			
		
IF (@rAttendanceTypeId= 2)
		BEGIN
		IF EXISTS (SELECT 1 FROM sAcademic.tOnlineLearningAttendance WHERE OnlineLearningId = @rOnlineLearningId AND AcademicId = @rSourceId)
			BEGIN
			UPDATE  sAcademic.tOnlineLearningAttendance 
			SET LastOutDateTime = GetDate(),
			IsLoggedIn = 'false'
			Where AcademicId= @rSourceId AND OnlineLearningId= @rOnlineLearningId
			
			INSERT  INTO sAcademic.tOnlineLearningAttendanceLog 
			(OnlineLearningId,AcademicId,ActivityId,CreatedDateTime)
			VALUES 
			(@rOnlineLearningId,@rSourceId,@rAttendanceTypeId,GetDate())
			SELECT 1 AS Result
			END

		ELSE 
		SELECT -1 AS Result
			
		
	
END
			
	--SELECT -1 AS Result			
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pOnlineLearningAttendanceListGet]
	@rOnlineLearningId bigint 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 


CREATE TABLE #SourceTypeId
	(
		Id int IDENTITY,
		SourceTypeId bigint
	)
	CREATE TABLE #StudentData
	(
	StudentName nvarchar(200),
	LoggedInStatus int,
	IsPresent nvarchar(100),
	InCount int,
	StudentId bigint,
	AcademicId bigint,
	RollNo int,
	ClassName nvarchar(200),
	Code nvarchar(20)
	)


DECLARE @rClassId bigint , @rBatchId bigint
--Select Distinct @lSourceTypeId= SourceTypeId from [sAcademic].[tOnlineLearningScope] Where OnlineLearningId=@rOnlineLearningId
SELECT @rClassId = ClassId, @rBatchId= BatchId FROM sAcademic.tOnlineLearning WHERE Id = @rOnlineLearningId

INSERT INTO #SourceTypeId
Select Distinct  SourceTypeId from [sAcademic].[tOnlineLearningScope] Where OnlineLearningId=@rOnlineLearningId

--Select @lSourceTypeId
DECLARE @lCountSourceTypeId int,@lSourceTypeId int,@lId int

SELECT @lCountSourceTypeId=COUNT(SourceTypeId) FROM #SourceTypeId
	SELECT Top 1 @lId=Id FROM #SourceTypeId

	
	WHILE @lId <= @lCountSourceTypeId
			BEGIN
			SELECT @lSourceTypeId=SourceTypeId FROM #SourceTypeId WHERE Id=@lId

--StudentId
	IF(@lSourceTypeId=2003)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+'-'+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.StudentId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--AcademicId
	ELSE IF(@lSourceTypeId=2001)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+' - '+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.AcademicId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--ClassId
	ELSE IF(@lSourceTypeId=2016)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+' - '+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.ClassId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId			
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--DeparmentId
	ELSE IF(@lSourceTypeId=2017)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+' - '+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.DepartmentId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId			
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--OrgId
	ELSE IF(@lSourceTypeId=2021)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+' - '+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.OrgId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId			
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	
	--Division
	ELSE IF(@lSourceTypeId=2005)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT ISNULL(IsLoggedIn,0)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),0)AS LoggedInStatus,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'true' ELSE 'false' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@rOnlineLearningId),'false')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @rOnlineLearningId  
			)As InCount ,
			SA.StudentId ,
			SA.Academicid ,
			SA.RollNo,
			(SA.ClassName+' - '+SA.DivisionName) as ClassName,
			SA.Code
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.DivisionId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@rOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END

	SET @lId=@lId+1
	END
	Select * from #StudentData
	DROP TABLE #SourceTypeId
	DROP TABLE #StudentData

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pOnlineLearningLectureListDetailsGet]

	 @rOnlineLearningId bigint ,
	 @rSourceId bigint,
	 @rOrgId int,
	 @rSourceTypeId int,
	 @rIsAdmin bit 
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
		
	IF (@rSourceTypeId = 2001)
	BEGIN 
	DECLARE @lStudentName nvarchar(100), @lClassDivisionName nvarchar(50),@lStudentId bigint
	SELECT @lStudentId= A.StudentId, @lStudentName = [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ), @lClassDivisionName = CM.Title +' ' +DM.Title
	FROM sStudent.tAcademic A 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
	WHERE A.Id = @rSourceId 
		SELECT 
			OL.Id As OnlineLearningId,
			ISNULL(OL.Title,'') As Title,
			CONVERT(NVARCHAR,OL.StartTime,108) as FromTime,
			CONVERT(NVARCHAR,OL.EndTime,108) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			@lClassDivisionName AS ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.IsTrackAttendance AS IsTrackAttendance,
			ISNULL(OL.MeetingId ,'') As MeetingId,
			ISNULL(OL.MeetingPassword,'') As MeetingPassword,
			ISNULL(OL.IsAssignment,0) As IsAssignment,
			ISNULL(OL.IsReference,0)AS IsReference,
			ISNULL(OL.IsResource,0) As IsResource,
			ISNULL(OL.IsMeetingStarted,0) AS IsMeetingStarted,
			ISNULL(OL.LecturePath,'')AS LecturePath,
			ISNULL(OL.IsDisplayMeetingId,'') AS IsDisplayMeetingId,
			ISNULL(DM.Title,'') As LearningType,
			@lStudentName As StudentName,
			ISNULL(OL.IsSubmitAssignment,0) As IsSubmitAssignment,
			ISNULL(OL.IsTakeTest ,0) As IsTakeTest,
			ISNULL(OL.TestId ,0) As TestId,
			--ISNULL((SELECT sTP.Id FROM sEExam.tTestParticipant sTP Where sTP.SourceId = @lStudentId and sTP.TestId = OL.TestId 
			--),0) AS TestParticipantId,
			0 AS TestParticipantId,
			--ISNULL((SELECT CASE WHEN sTp.TestStatusId=545 THEN 'True' ELSE 'False' END FROM sEExam.tTestParticipant sTP Where sTP.SourceId = @lStudentId and sTP.TestId = OL.TestId),'false') As IsTestCompleted,
			'False' As IsTestCompleted,
			--ISNULL(sTM.Title,'') AS TestName,
			'' AS TestName,
			--[sEExam].[fCheckIsHTMLGet] (sTM.Id) AS IsHtml,
			'False' AS IsHtml,
			ISNULL(OMS.IsOnParticipantVideo ,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) As IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) As IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) As IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) As IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) As IsOnHostscreenShare,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			ISNULL(OL.IsMeetingCreated,0) As IsMeetingCreated,
			ISNULL(OMS.APIKey ,'') As APIKey,
			ISNULL(OMS.APISecret ,'') As APISecret,
			'' As AccountEmailId,
			'' As AccountPassword,
			ISNULL(OL.AssignmentRemark,'') As AssignmentRemark,
			ISNULL(OL.IsTrackAssignmentView,0) As IsTrackAssignmentView,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId1),'') as CoTeacher1Name,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId2),'') as CoTeacher2Name,
			--ISNULL(sTM.IsAllowReview,0) As IsAllowReview,
			'False' As IsAllowReview,
			ISNULL(OLV.AssignmentTeacherRemark,'') AS TeacherAssignmentRemark,
			OL.BatchId,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.ClassId,
			OL.SubjectId,
			ISNULL(OL.IsRecording,0) As IsRecording,
			OL.EndDateTime
	 FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId			 			
            INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			--LEFT JOIN sEExam.tTestMaster sTM ON sTM.Id = OL.TestId
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id
			LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = @rSourceId
            
	 WHERE
			 OL.Id = @rOnlineLearningId
			AND OL.IsCompleted <> 721
			 
			 
			
			ORDER BY OL.CreatedDateTime
	
		END
		
		IF(@rSourceTypeId = 95)
		BEGIN
		DECLARE @lAdminName nvarchar(200)
			IF (@rIsAdmin = 1)
			SELECT @lAdminName = ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') 
			FROM sHrm.tEmployeeMaster EM WHERE EM.Id = @rSourceId
			
		SELECT 
			OL.Id As OnlineLearningId,
			ISNULL(OL.Title,'') As Title,
			CONVERT(NVARCHAR,OL.StartTime,108) as FromTime,
			CONVERT(NVARCHAR,OL.EndTime,108) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			CASE WHEN @rIsAdmin = 0 THEN ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') 
			WHEN @rIsAdmin = 1 THEN @lAdminName END As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.IsTrackAttendance AS IsTrackAttendance,
			ISNULL(OL.MeetingId ,'') As MeetingId,
			ISNULL(OL.MeetingPassword,'') As MeetingPassword,
			ISNULL(OL.IsAssignment,0) As IsAssignment,
			ISNULL(OL.IsReference,0)AS IsReference,
			ISNULL(OL.IsResource,0) As IsResource,
			ISNULL(OL.IsMeetingStarted,0) AS IsMeetingStarted,
			ISNULL(OL.LecturePath,'')AS LecturePath,
			ISNULL(OL.IsDisplayMeetingId,'') AS IsDisplayMeetingId,
			ISNULL(DM.Title,'') As LearningType,
			'' As StudentName,
			ISNULL(OL.IsSubmitAssignment,0) As IsSubmitAssignment,
			ISNULL(OL.IsTakeTest ,0) As IsTakeTest,
			ISNULL(OL.TestId ,0) As TestId,
			0 As TestParticipantId,
			'False' As IsHtml,
			ISNULL(OMS.IsOnParticipantVideo ,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) As IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) As IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) As IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) As IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) As IsOnHostscreenShare,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			ISNULL(OL.IsMeetingCreated,0) As IsMeetingCreated,
			ISNULL(OMS.APIKey ,'') As APIKey,
			ISNULL(OMS.APISecret ,'') As APISecret,
			ISNULL(OMS.APIKey ,'') As APIKey,
			ISNULL(OMS.APISecret ,'') As APISecret,
			CASE WHEN @rIsAdmin = 0 THEN ISNULL(OMS.AccountEmailId ,'') 
			WHEN @rIsAdmin = 1 THEN '' END As AccountEmailId,
			CASE WHEN @rIsAdmin = 0 THEN ISNULL(OMS.AccountPassword,'') 
			WHEN @rIsAdmin = 1 THEN '' END As AccountPassword,
			'' as AssignmentRemark,
			--,
			--ISNULL(TP.Id, 0) AS TestParticipantId,
			--ISNULL(sTM.Title,'') AS TestName,
			--[sEExam].[fCheckIsHTMLGet] (sTM.Id) AS IsHtml
			ISNULL(OL.IsTrackAssignmentView,0) As IsTrackAssignmentView,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId1),'') as CoTeacher1Name,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId2),'') as CoTeacher2Name,
			--ISNULL(sTM.IsAllowReview,0) As IsAllowReview,
			'False' As IsAllowReview,
			OL.BatchId,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.ClassId,
			OL.SubjectId,
			ISNULL(OL.IsRecording,0) As IsRecording,
			OL.EndDateTime
		FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId 
            --INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId AND SA.OrgId = @rOrgId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            --LEFT JOIN sEExam.tTestMaster sTM ON sTM.Id = OL.TestId
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			--LEFT JOIN sE sEExam.tTestParticipant TP ON sTM.Id=TP.TestId
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id
            
		WHERE
			 OL.Id = @rOnlineLearningId
			-- AND OL.TeacherEmployeeId = @rSourceId
			 AND OL.IsCompleted <> 721
			
			ORDER BY OL.CreatedDateTime
			
			END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sCommunication].[pOnlineLearningLectureListGet] '2020-06-04','2020-07-06',1101000000111,95,1101,0,0,0,0,0,'','',0
CREATE OR ALTER PROCEDURE [sCommunication].[pOnlineLearningLectureListGet]
	@rFromDate date,
	@rToDate date,
	@rSourceId bigint,
	@rSourceTypeId int,
	@rOrgId int,
	@rClassId int=0,
	@rTopicId int= 0,
	@rSubjectId int = 0,
	@rLearningtypeId tinyint = 0,
	@rTeacherEmployeeId bigint = 0,
	@rTitle nvarchar(200) = '',
	@rDescription nvarchar(1000) = '',
	@rIsAdmin bit = 0,
	@rBatchId int = 0
	
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @lOrgGroupId int,@lOrgGroupBatchId int = 0

	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

	SELECT @lOrgGroupBatchId = ISNULL(OrgGroupBatchId,0) FROM sSetup.tBatchMaster WHERE Id = @rBatchId

	 

	DECLARE @lConfigValue nvarchar(50)=''

	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 375 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId

	 IF @lConfigValue = ''
		SET @lConfigValue = 'False'

	IF(@lConfigValue = 'False')
	BEGIN
	DECLARE @lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint, @lClassDivisionName nvarchar(50),@lUserId bigint
	 If (@rSourceTypeId = 2001) -- For Student LogIn
	 BEGIN
		
			SELECT @lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
			@lClassDivisionName = CM.Title +' ' +DM.Title
				FROM sStudent.tAcademic A 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
				WHERE A.Id = @rSourceId 
	 
		SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			@lClassDivisionName AS ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName
		FROM 
			sAcademic.tOnlineLearning OL	
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
			--LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
			WHERE (((OLS.SourceTypeId = 2021 AND OLS.SourceId =@lOrgId) OR
			(OLS.SourceTypeId = 2017 AND OLS.SourceId =@lDepartmentId) OR
			(OLS.SourceTypeId = 2016 AND OLS.SourceId =@lClassId) OR
			(OLS.SourceTypeId = 2005 AND OLS.SourceId =@lDivisionId) OR
			(OLS.SourceTypeId = 2003 AND OLS.SourceId =@lStudentId) OR
			(OLS.SourceTypeId = 2001 AND OLS.SourceId =@rSourceId)))) D ON D.OnlineLearningId = OL.Id
      
		WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND ((SA.AcademicId = @rSourceId))
			--AND SA.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rTeacherEmployeeId)OR (ISNULL(@rTeacherEmployeeId,0)=0))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((OL.BatchId = @rBatchId ) OR (@rBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	END
		
		IF (@rSourceTypeId = 95 AND @rIsAdmin = 0) --For Employee LogIn
		BEGIN
			SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as AssignedTo
			
			FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON (EM.Id = OL.TeacherEmployeeId OR EM.Id = ISNULL(OL.CoTeacherEmployeeId1,0) OR EM.Id = ISNULL(OL.CoTeacherEmployeeId2,0))
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = OL.BatchId
			WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND ((SA.AcademicId = @rSourceId))
			AND (EM.Id = @rSourceId)
			--AND SA.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rSourceId) OR (ISNULL(OL.CoTeacherEmployeeId1,0)= @rSourceId) OR (ISNULL(OL.CoTeacherEmployeeId2,0)= @rSourceId))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((BM.OrgGroupBatchId = @lOrgGroupBatchId ) OR (@lOrgGroupBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	
		END
		
		
		IF (@rSourceTypeId = 95 AND @rIsAdmin = 1) --For Admin LogIn
		
		BEGIN
		SELECT @lUserId= Id FROM sSecurity.tUser Where SourceId = @rSourceId AND  SourceTypeId  =95 
			SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			TM.Title As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as AssignedTo
			
			FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            --INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId AND CM.OrgId = @rOrgId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = OL.BatchId
			INNER JOIN (SELECT EM.Id FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.vUserOrganization OM ON EM.OrgID = OM.Id 
			AND ((OM.UserId = @lUserId) OR (@lUserId = 0)) ) A ON OL.TeacherEmployeeId = A.Id
   --         INNER JOIN 
			--(SELECT  distinct CM.Id As ClassId, TSD.SubjectId FROM
			--sSetup.tClassMaster CM
			--INNER JOIN sSetup.tDivisionMaster DM1  ON CM.Id = DM1.ClassId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			--INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM1.Id
   --         INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM1.Id AND UA.SourceTypeId=2005 AND ((UA.UserId=@lUserId) OR (@lUserId=0)) ) A ON A.ClassId = OL.ClassId  AND A.SubjectId = OL.SubjectId
            
			WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND ((SA.AcademicId = @rSourceId))
			--AND (EM.Id = @rSourceId)
			--AND CM.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rTeacherEmployeeId)OR (ISNULL(@rTeacherEmployeeId,0)=0))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((BM.OrgGroupBatchId = @lOrgGroupBatchId ) OR (@lOrgGroupBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	
		END
				
	END
	ELSE IF(@lConfigValue = 'True')
	BEGIN
	
	 If (@rSourceTypeId = 2001) -- For Student LogIn
	 BEGIN
		
			SELECT @lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
			@lClassDivisionName = CM.Title +' ' +DM.Title
				FROM sStudent.tAcademic A 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
				WHERE A.Id = @rSourceId 
	 
		SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			@lClassDivisionName AS ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName
		FROM 
			sAcademic.tOnlineLearning OL	
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
			--LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
			WHERE (((OLS.SourceTypeId = 2021 AND OLS.SourceId =@lOrgId) OR
			(OLS.SourceTypeId = 2017 AND OLS.SourceId =@lDepartmentId) OR
			(OLS.SourceTypeId = 2016 AND OLS.SourceId =@lClassId) OR
			(OLS.SourceTypeId = 2005 AND OLS.SourceId =@lDivisionId) OR
			(OLS.SourceTypeId = 2003 AND OLS.SourceId =@lStudentId) OR
			(OLS.SourceTypeId = 2001 AND OLS.SourceId =@rSourceId)))) D ON D.OnlineLearningId = OL.Id
      
		WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.EndDate >= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '1900-01-01' END)) 
			AND ((OL.StartDate <= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '9999-01-01' END))
			AND ((OL.StartTime <= CASE WHEN OL.LearningTypeId = 1 AND OL.StartDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.StartTime END)) 
			AND ((OL.EndTime >= CASE WHEN OL.LearningTypeId = 1 AND OL.EndDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.EndTime END))
			--AND ((SA.AcademicId = @rSourceId))
			--AND SA.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rTeacherEmployeeId)OR (ISNULL(@rTeacherEmployeeId,0)=0))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((OL.BatchId = @rBatchId ) OR (@rBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	END
		
		IF (@rSourceTypeId = 95 AND @rIsAdmin = 0) --For Employee LogIn
		BEGIN
			SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as AssignedTo
			
			FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON (EM.Id = OL.TeacherEmployeeId OR EM.Id = ISNULL(OL.CoTeacherEmployeeId1,0) OR EM.Id = ISNULL(OL.CoTeacherEmployeeId2,0))
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = OL.BatchId
			WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.EndDate >= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '1900-01-01' END)) 
			AND ((OL.StartDate <= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '9999-01-01' END))
			AND ((OL.StartTime <= CASE WHEN OL.LearningTypeId = 1 AND OL.StartDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.StartTime END)) 
			AND ((OL.EndTime >= CASE WHEN OL.LearningTypeId = 1 AND OL.EndDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.EndTime END))
			--AND ((SA.AcademicId = @rSourceId))
			AND (EM.Id = @rSourceId)
			--AND SA.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rSourceId) OR (ISNULL(OL.CoTeacherEmployeeId1,0)= @rSourceId) OR (ISNULL(OL.CoTeacherEmployeeId2,0)= @rSourceId))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((BM.OrgGroupBatchId = @lOrgGroupBatchId ) OR (@lOrgGroupBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	
		END
		
		
		IF (@rSourceTypeId = 95 AND @rIsAdmin = 1) --For Admin LogIn
		
		BEGIN
		SELECT @lUserId= Id FROM sSecurity.tUser Where SourceId = @rSourceId AND  SourceTypeId  =95 
			SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			TM.Title As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as AssignedTo
			
			FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            --INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId AND CM.OrgId = @rOrgId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = OL.BatchId
			INNER JOIN (SELECT EM.Id FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.vUserOrganization OM ON EM.OrgID = OM.Id 
			AND ((OM.UserId = @lUserId) OR (@lUserId = 0)) ) A ON OL.TeacherEmployeeId = A.Id
   --         INNER JOIN 
			--(SELECT  distinct CM.Id As ClassId, TSD.SubjectId FROM
			--sSetup.tClassMaster CM
			--INNER JOIN sSetup.tDivisionMaster DM1  ON CM.Id = DM1.ClassId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			--INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM1.Id
   --         INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM1.Id AND UA.SourceTypeId=2005 AND ((UA.UserId=@lUserId) OR (@lUserId=0)) ) A ON A.ClassId = OL.ClassId  AND A.SubjectId = OL.SubjectId
            
			WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND ((SA.AcademicId = @rSourceId))
			--AND (EM.Id = @rSourceId)
			--AND CM.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rTeacherEmployeeId)OR (ISNULL(@rTeacherEmployeeId,0)=0))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((BM.OrgGroupBatchId = @lOrgGroupBatchId ) OR (@lOrgGroupBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	
		END
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pOrgInfoAdd] 
	(
		@rXmlDoc nvarchar(MAX),	
		@rOrgId smallint
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
 DECLARE @lNextNumber smallint
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	--DECLARE @lOrgId smallint
	if exists (select OrgId from sSetup.tOrgInfo where OrgId=@rOrgId)
	begin
		delete from sSetup.tOrgInfo where OrgId=@rOrgId
	
		INSERT INTO sSetup.tOrgInfo
		(
			 OrgId,
			 Title,
			 Detail
		)
		SELECT
			@rOrgId,
			Title,
			Detail
			
		FROM OPENXML (@intDoc, '/Table/OrgInfo', 1)
		WITH
		(
			OrgId smallint '@rOrgId' ,
			Title nvarchar(200) '@Title',
			Detail nvarchar(1000) '@Detail'
			 
		) 
	 
		
		EXEC sp_xml_removedocument @intDoc
		SELECT 1 as result
	end
else
	 begin
			INSERT INTO sSetup.tOrgInfo
		(
			 OrgId,
			 Title,
			 Detail
		)
		SELECT
			OrgId,
			Title,
			Detail
			
		FROM OPENXML (@intDoc, '/Table/OrgInfo', 1)
		WITH
		(
			OrgId smallint '@OrgId' ,
			Title nvarchar(200) '@Title',
			Detail nvarchar(200) '@Detail'
			 
		) 
	 
		
		SELECT @lNextNumber = OrgId FROM sSetup.tOrgInfo Where OrgId=@rOrgId
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sSetup.tOrgInfo', @rCurrentNumber = @lNextNumber 
		SELECT 2 as result
	 end
	 
	
	COMMIT TRANSACTION
 
 
	 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pOrgInfoGet]
	 
	 --@rSourceTypeId smallint,
	 @rOrgId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 
		SELECT 
			 OI.OrgId,
			 OI.Title,
			 OI.Detail
		FROM 
			sSetup.tOrgInfo OI 
			 
		WHERE 
				 OI.OrgId=@rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPhotoCategoryDelete]
	 
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete From sCommunication.tPhotoCategoryScope Where PhotoCategoryId=@rId
			Delete from sCommunication.tPhotoCategoryMaster where Id=@rId
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pPhotoCategoryGet]
	 
	 @rSourceTypeId smallint ,
	 @rOrgGroupId int=0,
	 @rOrgId smallint=0,
	 @rPhotoCategoryId bigint=0,
	 @rUserId bigint 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lConfigValue nvarchar(50)
DECLARE @rOrgGroupBatchId int

SELECT @rOrgGroupBatchId  = Id from  sSetup.tOrgGroupBatchMaster Where OrgGroupId=@rOrgGroupId
SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 337 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)


BEGIN 		
	if @rSourceTypeId=2021
	BEGIN
		Select 
			OM.Id,DisplayTitle AS Title ,
			CASE WHEN  PC.ScopeSourceId IS  NOT NULL AND PM.ScopeSourceTypeId=@rSourceTypeId THEN 1 ELSE 0 END  AS IsObsolete
		from  sSetup.tOrganizationMaster OM
		LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
		LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId
		INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id AND ((UO.UserId=@rUserId) OR (@rUserId=0))
		
		where OM.OrgGroupId=@rOrgGroupId   
		
	END
	
	if @rSourceTypeId=2017
	BEGIN
		Select OM.Id,DisplayTitle AS Title ,
		 
		CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PM.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END AS IsObsolete
		 from  sSetup.tDepartmentMaster OM
		LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
		LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId  and PM.ScopeSourceTypeId=@rSourceTypeId
		INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=OM.Id AND UA.SourceTypeId=2017 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
		  where OrgId=@rOrgId   
	END
	
	if @rSourceTypeId=2016
	BEGIN
		Select OM.Id,DisplayTitle AS Title,
		CASE WHEN PC.ScopeSourceId IS NOT NULL AND PM.ScopeSourceTypeId=@rSourceTypeId   THEN 1 ELSE 0 END  AS IsObsolete
		
		 from  sSetup.tClassMaster OM
		 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
		LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
		 where OrgId=@rOrgId  
	END
	
	if @rSourceTypeId=2005
	BEGIN

			if((@lConfigValue='Class Teacher' ) OR (@lConfigValue='Class Teacher Batch' ))
			BEGIN
				 Select  OM.Id,CM.DisplayTitle+'-'+OM.DisplayTitle AS Title,
				 CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PM.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END  AS IsObsolete		
				 from  sSetup.tDivisionMaster OM
				 INNER JOIN sSetup.tClassMaster CM ON CM.Id=OM.ClassId
				 INNER JOIN sSetup.tOrganizationMaster ORM ON ORM.Id=CM.OrgId
				 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
				 LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
				 where OM.OrgId=@rOrgId AND OM.InchargeemployeeID= (SELECT ISNULL(SourceId,0) FROM sSecurity.tUser WHERE Id=@rUserId AND OrgId= @rOrgId) AND  CM.OrgId=@rOrgId
				 ORDER BY CM.OrderIndex
			END
			ELSE IF(@lConfigValue='Academic Setup')
			BEGIN			

				 Select DISTINCT OM.Id,CM.DisplayTitle+'-'+OM.DisplayTitle +'('+tOM.DisplayTitle+')' AS Title,
				 CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PM.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END  AS IsObsolete		
				 from  sSetup.tDivisionMaster OM
				 INNER JOIN sSetup.tClassMaster CM ON CM.Id=OM.ClassId
				 INNER JOIN sSetup.tOrganizationMaster tOM ON tOM.Id = CM.OrgId
				 INNER JOIN sAcademic.vTeacherSubjectDivision TSD ON TSD.OrgId=OM.OrgId AND TSD.DivisionId= OM.Id
				 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
				 LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
				 where TSD.EmployeeId= (SELECT ISNULL(SourceId,0) FROM sSecurity.tUser WHERE Id=@rUserId)					 
				
			END
			ELSE IF(@lConfigValue='User Access')
			BEGIN
				 Select OM.Id,CM.DisplayTitle+'-'+OM.DisplayTitle AS Title,
				 CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PM.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END  AS IsObsolete		
				 from  sSetup.tDivisionMaster OM
				 INNER JOIN sSetup.tClassMaster CM ON CM.Id=OM.ClassId
				 INNER JOIN sSecurity.tUserAccess U ON U.SourceId = OM.Id AND U.SourceTypeId= 2005
				 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
				 LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
				 where OM.OrgId=@rOrgId  AND  U.UserId =(SELECT ISNULL(ID,0) FROM sSecurity.tUser WHERE Id=@rUserId AND OrgId= @rOrgId)
				 ORDER BY CM.OrderIndex
			END
			ELSE
			BEGIN
				 Select OM.Id,CM.DisplayTitle+'-'+OM.DisplayTitle AS Title,
				 CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PM.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END  AS IsObsolete		
				 from  sSetup.tDivisionMaster OM
				 INNER JOIN sSetup.tClassMaster CM ON CM.Id=OM.ClassId
				 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
				 LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
				 where OM.OrgId=@rOrgId  
				 ORDER BY CM.OrderIndex
			END
	END
	
	if @rSourceTypeId=2014
	BEGIN
		Select OM.Id,OM.Title AS Title,
		CASE WHEN PC.ScopeSourceId IS NOT NULL  AND PM.ScopeSourceTypeId=@rSourceTypeId  THEN 1 ELSE 0 END AS IsObsolete
		
		 from  sHostel.tHostelMaster OM
		 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
		LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
		inner join  sSecurity.tUserAccess UA ON UA.SourceId=OM.Id AND UA.SourceTypeId=2014 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
		 where OM.OrgGroupId=@rOrgGroupId  
	END 
	
	if @rSourceTypeId=2029
	BEGIN
		Select OM.Id,OM.Title As Title,
		CASE WHEN PC.ScopeSourceId IS  NOT NULL AND PM.ScopeSourceTypeId=@rSourceTypeId   THEN 1 ELSE 0 END  AS IsObsolete
		
		
		 from  sActivity.tHouseMaster OM
		 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
		LEFT JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId and PM.ScopeSourceTypeId=@rSourceTypeId
		 where OM.OrgId=@rOrgId  
	END
	IF (@rSourceTypeId = 2003)
	BEGIN
	
		SELECT OM.Id,
			  (SA.Code+' - '+CONVERT(NVARCHAR(10),SA.RollNo)+' - '+SA.Name) AS Title,
			  1 AS IsObsolete
	
		FROM  sStudent.tStudentMaster OM
			  INNER JOIN  sStudent.vStudentAcademic SA ON OM.Id=SA.StudentId 
			  INNER JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id 
			  INNER JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId 
		WHERE SA.OrgId = @rOrgId AND SA.IsActiveBatch=1 AND SA.StatusId=1	AND PM.ScopeSourceTypeId = 2003 AND PhotoCategoryId = @rPhotoCategoryId
	END
	IF (@rSourceTypeId = 95)
	BEGIN
	
		SELECT OM.EmployeeId AS Id,
			  OM.EmployeeName AS Title,
			  1 AS IsObsolete
	
		FROM  sHrm.vEmployeeCommunication OM
			  INNER JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.EmployeeId 
			  INNER JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId 
		WHERE OM.OrgId = @rOrgId AND PM.ScopeSourceTypeId = 95 AND PhotoCategoryId = @rPhotoCategoryId
	END
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPhotoCategoryMaster_Get]
	 
	 @rScopeSourceId bigint=0,
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rSourcetypeId smallint,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
  
	IF @rSourcetypeId=2003
	BEGIN
		SELECT @lOrgGroupId=Om.OrgGroupId,@lOrgId=OM.Id ,@lOrgGroupBatchID=BM.OrgGroupBatchId  
		FROM sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId=OM.Id
		INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId 
		WHERE A.BatchId= @rBatchId AND A.Id=@rScopeSourceId 
	END
	ELSE IF @rSourcetypeId=95
	BEGIN
		SELECT @lOrgGroupId=Om.OrgGroupId, @lOrgId=OrgId 
		FROM sSetup.tOrganizationMaster OM INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgID=OM.Id 
		WHERE Em.Id=@rScopeSourceId AND ISNULL(EM.IsOtherUser,0) = 0
	END
	ELSE
	BEGIN
		SELECT @lOrgGroupId=OM.OrgGRoupId 
		FROM sSetup.tOrganizationMaster OM INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id 
		WHERE Bm.Id=@rBatchId
	END
 
	IF @rSourcetypeId=2003
	BEGIN
	SELECT   
		PCM.[Id],
  		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
	FROM 
		[sCommunication].[tPhotoCategoryMaster] PCM 
		LEFT JOIN sCommunication.tPhotoCategoryScope PCS  ON PCM.Id = PCS.PhotoCateGoryId 
		AND (PCS.ScopeSourceId = CASE WHEN PCM.ScopeSourceTypeId = 2005 THEN
		(SELECT DivisionId FROM sStudent.tAcademic WHERE DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
		WHEN PCM.ScopeSourceTypeId = 2016 THEN
		(SELECT ClassId FROM sStudent.tAcademic WHERE DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
		WHEN PCM.ScopeSourceTypeId = 2017 THEN
		(SELECT D.Id FROM sSetup.tDepartmentMaster D INNER JOIN sSetup.tClassMaster CA ON CA.DepartmentId=D.Id 
		INNER JOIN sStudent.tAcademic A ON A.ClassID=CA.Id WHERE A.Id =@rScopeSourceId)
		WHEN PCM.ScopeSourceTypeId =2021 THEN
		(SELECT OM.Id FROM sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId =OM.Id WHERE A.Id=@rScopeSourceId)
		WHEN PCM.ScopeSourceTypeId =2014 THEN
		(SELECT Hm.Id FROM sHostel.tHostelMaster Hm INNER JOIN  sHostel.tRoomMaster RA ON RA.HostelId=HM.Id 
		INNER JOIN sHostel.tAssignRoom AR ON AR.RoomId=RA.Id
		INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId 
		WHERE AR.OrgGroupBatchId = @lOrgGroupBatchID AND HM.OrgGroupId=@lOrgGroupId AND A.Id=@rScopeSourceId)
		WHEN PCM.ScopeSourceTypeId =2029 THEN
		(SELECT HO.Id FROM sActivity.tHouseMaster HO
		INNER JOIN sStudent.tStudentOther SO ON SO.HouseId=HO.Id 
		INNER JOIN sStudent.tAcademic A ON A.StudentId=SO.StudentId
		WHERE HO.OrgId=@lOrgId AND A.Id=@rScopeSourceId)
		ENd)
	WHERE 
		PCM.IsObsolete=0	
		AND (PCM.Id=@rId OR @rId=0) 
		AND PCM.OrgGroupId = @lOrgGroupId
	ORDER BY PCM.CreatedDateTime DESC
	END
	ELSE IF @rSourcetypeId=95
	BEGIN 
	SELECT
		PCM.[Id],
		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
	FROM 
		[sCommunication].[tPhotoCategoryMaster] PCM 
		LEFT join sCommunication.tPhotoCategoryScope PCS  ON PCM.Id = PCS.PhotoCateGoryId AND
		(PCS.ScopeSourceId = Case WHEN PCM.ScopeSourceTypeId = 2017 THEN
		(SELECT D.Id FROM sSetup.tDepartmentMaster D 
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.OrganizationDepartmentId=D.Id
		WHERE EJ.EmployeeId=@rScopeSourceId AND EJ.OrgId=@lOrgId)
		WHEN PCM.ScopeSourceTypeId=2021 THEN
		(SELECT OM.Id FROM sSetup.tOrganizationMaster OM 
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgId=OM.Id
		WHERE EM.OrgId=@lOrgId and Em.Id=@rScopeSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
		END)
	WHERE 
		PCM.IsObsolete=0 
		AND ((PCM.Id = @rId) OR (@rId=0)) 
		AND PCM.OrgGroupId = @lOrgGroupId
		ORDER BY PCM.CreatedDateTime DESC
	END
	ELSE
	BEGIN
	SELECT   
		PCM.[Id],
  		PCM.[Title],
		PCM.[IsObsolete],
		ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
		ISNULL(Remark,'') AS Remark,
		ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
	FROM    
		[sCommunication].[tPhotoCategoryMaster]  PCM 
	WHERE   
		PCM.IsObsolete = 0
		AND ((PCM.Id = @rId) OR (@rId = 0))
		AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
		AND OrgGroupId=@lOrgGroupId
		ORDER BY PCM.CreatedDateTime DESC
	END   
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPhotoCategoryMasterAdd]
	 
	 @rId int,
	 @rOrgGroupId int,
	 @rTitle nvarchar(100),
	 @rIsObsolete bit,
	 @rCreatedUserId bigint,
	 @rScopeSourceTypeId smallint=0,
	 @rRemark nvarchar(300)='',
	 @rOrgGroupBatchId int = 0,
	 @rEventScheduleId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
IF(@rId = 0)	
BEGIN
	IF EXISTS(Select 1 FROM sCommunication.tPhotoCategoryMaster Where Title = @rTitle AND IsObsolete = 0 AND OrgGroupId=@rOrgGroupId AND OrgGroupBatchId=@rOrgGroupBatchId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END 
END
ELSE 
BEGIN 
	IF EXISTS(Select 1 FROM sCommunication.tPhotoCategoryMaster Where Title = @rTitle AND OrgGroupId=@rOrgGroupId AND IsObsolete = 0  AND OrgGroupBatchId=@rOrgGroupBatchId AND Id!=@rId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END 
END
	
BEGIN TRY

BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
  
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPhotoCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sCommunication].[tPhotoCategoryMaster]
           (
            [Id]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId]
           ,ScopeSourceTypeId
           ,Remark
		   ,OrgGroupBatchId
		   ,EventScheduleId)
     VALUES
		(
			@lNextNumber,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
		    sCommon.fGetDate(),
			@rCreatedUserId,	 
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rScopeSourceTypeId,
			@rRemark,
			@rOrgGroupBatchId,
			@rEventScheduleId
		)
		             
	END	 
	 ELSE
	  BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sCommunication].[tPhotoCategoryMaster]
	    SET
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ScopeSourceTypeId=@rScopeSourceTypeId,
			Remark=@rRemark
			--OrgGroupBatchId = @rOrgGroupBatchId
	      
	      WHERE Id = @rId 	 
		END
		SELECT @lNextNumber AS Result	   
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPhotoCategoryMasterDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		

		BEGIN
			DELETE FROM [sCommunication].[tPhotoCategoryMaster] WHERE Id=@rId 
			SELECT 1 AS Result
		END		
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPhotoCategoryMasterGet]
	 
	 @rOrgId int,
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete]
          
  FROM    [sCommunication].[tPhotoCategoryMaster]  PCM
  INNER JOIN sCommunication.tPhotoCategoryOrg PCO ON PCO.PhotoCategoryId=PCM.Id AND PCO.OrgId=@rOrgId
            
  WHERE   
      PCM.IsObsolete = 0
      AND (PCM.Id = @rId OR @rId = 0)
      AND (PCM.Id > @rSyncedPhotoCategoryId OR @rSyncedPhotoCategoryId = 0)
      ORDER BY PCM.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPhotoCategoryOrgAdd]
			
			@rPhotoCategoryId int
           ,@rOrgId smallint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tPhotoCategoryOrg where PhotoCategoryId=@rPhotoCategoryId AND OrgId=@rOrgId
	Select @rOrgId as Result
END	
ELSE
BEGIN 

		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select PhotoCategoryId from sCommunication.tPhotoCategoryOrg where PhotoCategoryId=@rPhotoCategoryId AND OrgId=@rOrgId)
		BEGIN
			SELECT @rOrgId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tPhotoCategoryOrg
			(
				PhotoCategoryId
			   ,OrgId
			)
			VALUES
			(	
				@rPhotoCategoryId
			   ,@rOrgId
			)		
			SELECT @rPhotoCategoryId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END 	             
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPhotoCategoryOrgGet]
	 
	 @rPhotoCategoryId int,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OM.Id AS OrgId,
			OM.DisplayTitle as Organization,
			CASE WHEN PCO.OrgId IS NULL OR PCO.PhotoCategoryId!=@rPhotoCategoryId THEN 0 ELSE 1 END AS IsObsolete
	FROM 
			sSetup.tOrganizationMaster OM
			LEFT JOIN sCommunication.tPhotoCategoryOrg PCO ON PCO.OrgId=OM.Id AND PCO.PhotoCategoryId=@rPhotoCategoryId
	WHERE (OM.OrgGroupId=@rOrgGroupId)
	Order BY OM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPhotoCategoryScopeAdd]
			
			@rPhotoCategoryId int
           ,@rScopeSourceId bigint,
           @rIsDeleted bit
          
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tPhotoCategoryScope where PhotoCategoryId=@rPhotoCategoryId AND ScopeSourceId=@rScopeSourceId
	Select @rScopeSourceId as Result
END	
ELSE
BEGIN 

		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select PhotoCategoryId from sCommunication.tPhotoCategoryScope where PhotoCategoryId=@rPhotoCategoryId AND ScopeSourceId=@rScopeSourceId)
		BEGIN
			SELECT @rScopeSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tPhotoCategoryScope
			(
				PhotoCategoryId
			   ,ScopeSourceId
			)
			VALUES
			(	
				@rPhotoCategoryId
			   ,@rScopeSourceId
			)		
			SELECT @rPhotoCategoryId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END 	             
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPhotoCategoryScopeGet]
	 
	 @rPhotoCategoryId int,
	 @rSourceTypeId smallint,
	 @rOrgGroupId int=0,
	 @rOrgId smallint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	if @rSourceTypeId=2021
	BEGIN
		Select 
			Id,DisplayTitle AS Title ,
			CASE WHEN PC.ScopeSourceId IS NULL   THEN 0 ELSE 1 END  AS IsObsolete
		from  sSetup.tOrganizationMaster OM
		LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId
		where OrgGroupId=@rOrgGroupId
	END
	
	if @rSourceTypeId=2017
	BEGIN
		Select Id,DisplayTitle AS Title ,
		 
		CASE WHEN PC.ScopeSourceId IS NULL   THEN 0 ELSE 1 END AS IsObsolete
		 from  sSetup.tDepartmentMaster OM
		LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId

		  where OrgId=@rOrgId
	END
	if @rSourceTypeId=2016
	BEGIN
		Select Id,DisplayTitle AS Title,
		CASE WHEN PC.ScopeSourceId IS NULL   THEN 0 ELSE 1 END AS IsObsolete
		
		 from  sSetup.tClassMaster OM
		 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId

		 where OrgId=@rOrgId
	
	END
	if @rSourceTypeId=2005
	BEGIN
		Select OM.Id,CM.DisplayTitle+'-'+OM.DisplayTitle AS Title,
		CASE WHEN PC.ScopeSourceId IS NULL   THEN 0 ELSE 1 END  AS IsObsolete
		
		 from  sSetup.tDivisionMaster OM
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id=OM.ClassId
		 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId

		  where OM.OrgId=@rOrgId
	END
	
	if @rSourceTypeId=2014
	BEGIN
		Select Id,Title AS Title,
		CASE WHEN PC.ScopeSourceId IS NULL   THEN 0 ELSE 1 END  AS IsObsolete
		
		 from  sHostel.tHostelMaster OM
		 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId

		 where OrgGroupId=@rOrgGroupId
	END
	if @rSourceTypeId=2029
	BEGIN
		Select Id,Title As Title,
		CASE WHEN PC.ScopeSourceId IS NULL   THEN 0 ELSE 1 END  AS IsObsolete
		
		
		 from  sActivity.tHouseMaster OM
		 LEFT JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id AND PhotoCategoryId=@rPhotoCategoryId

		 where OrgId=@rOrgId
	END

	IF (@rSourceTypeId = 2003)
	BEGIN
	
		SELECT OM.Id,
			  (SA.Code+' - '+CONVERT(NVARCHAR(10),SA.RollNo)+' - '+SA.Name) AS Title,
			  1 AS IsObsolete
	
		FROM  sStudent.tStudentMaster OM
			  INNER JOIN  sStudent.vStudentAcademic SA ON OM.Id=SA.StudentId 
			  INNER JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.Id 
			  INNER JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId 
		WHERE SA.OrgId = @rOrgId AND SA.IsActiveBatch=1 AND SA.StatusId=1	AND PM.ScopeSourceTypeId = 2003 AND PhotoCategoryId = @rPhotoCategoryId
	END
	IF (@rSourceTypeId = 95)
	BEGIN
	
		SELECT OM.EmployeeId AS Id,
			  OM.EmployeeName AS Title,
			  1 AS IsObsolete
	
		FROM  sHrm.vEmployeeCommunication OM
			  INNER JOIN sCommunication.tPhotoCategoryScope PC ON PC.ScopeSourceId =OM.EmployeeId 
			  INNER JOIN sCommunication.tPhotoCategoryMaster PM ON PM.Id = PC.PhotoCategoryId 
		WHERE OM.OrgId = @rOrgId AND PM.ScopeSourceTypeId = 95 AND PhotoCategoryId = @rPhotoCategoryId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPlaylistDetailAdd]
	 
	        @rId int
	       ,@rPlaylistId int
	       ,@rTitle nvarchar(100)
		   ,@rURL nvarchar(500)
		   ,@rOrderIndex smallint
		   ,@rRemark nvarchar(1000)
           ,@rIsObsolete bit
		   ,@rOrgGroupId int
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	 DECLARE @lNextNumber INT 

IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sTransport.tBusRouteDestinationMaster',@lNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPlaylistDetails', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sCommunication].[tPlaylistDetails]
			   (
			    --[AutoId]
			    [PlaylistId]
			   ,[Title]
			   ,[URL]
			   ,[OrderIndex]
			   ,[Remark]
			   ,[IsObsolete]
			   )
		 VALUES
			   (
			    --@lNextNumber
			    @rPlaylistId
			   ,@rTitle
			   ,@rURL
			   ,@rOrderIndex
			   ,@rRemark
			   ,@rIsObsolete
			   )
			   Select @lNextNumber=Max(AutoId) from [sCommunication].[tPlaylistDetails]
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 --Select 111
	 SET @lNextNumber = @rId
	    UPDATE  [sCommunication].[tPlaylistDetails]
	    SET
			  PlaylistId=@rPlaylistId
			 ,Title=@rTitle
			 ,URL=@rURL
	         ,OrderIndex=@rOrderIndex
			 ,Remark=@rRemark
			 ,IsObsolete=@rIsObsolete

	      WHERE AutoId = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPlaylistDetailGet]
	 @rPlaylistId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	
	SELECT 
			PM.Id AS PlaylistId,
			PD.AutoId,
			PD.Title,
			PD.URL,
			PD.OrderIndex,
			PD.Remark,
			PD.IsObsolete

			
  FROM 
			[sCommunication].[tPlaylistDetails]  PD
			INNER JOIN [sCommunication].[tPlaylistMaster] PM ON PM.Id=PD.PlaylistId  
WHERE 
			(PD.PlaylistId=@rPlaylistId OR @rPlaylistId=0)
			order by PD.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPlayListGet]
	@rOrgId int=0,
	@rUserId bigint=0,
	@rSourceTypeId int=0,
	@rSourceId bigint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

if (@rSourceTypeId = 95)

	BEGIN

		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id 
		FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD	 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId

			BEGIN 		
		
				SELECT * FROM (SELECT * FROM (SELECT VP.SourceTypeId, VP.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,VP.PlaylistName as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id 
				WHERE VP.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,VP.PlaylistName  as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				WHERE VP.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Employee' AS SourceType,vEC.FirstName +' '+ vEC.LastName AS Source,VP.PlaylistName  as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sHrm.vEmployeeCommunication vEC ON VP.SourceId=vEC.EmployeeId AND vEC.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id					
				WHERE VP.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) ) TempVideoPlaylist

				UNION ALL

				SELECT * FROM (SELECT	 VP.SourceTypeId, VP.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id 
				WHERE VP.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId,'Department' AS SourceType,DM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				WHERE VP.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId, 'Employee' AS SourceType,vEC.FirstName +' '+ vEC.LastName AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sHrm.vEmployeeCommunication vEC ON VP.SourceId=vEC.EmployeeId AND vEC.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id					
				WHERE VP.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) ) TempVideolist ) TempYouTubeVideoList

				WHERE ((TempYouTubeVideoList.SourceTypeId = 2021 AND TempYouTubeVideoList.SourceId =@lOrgId) OR
					   (TempYouTubeVideoList.SourceTypeId = 2017 AND TempYouTubeVideoList.SourceId =@lDepartmentId) OR
					   (TempYouTubeVideoList.SourceTypeId = 95 AND TempYouTubeVideoList.SourceId =@lEmployeeId))
					    AND  Detail IN(Select Convert (varchar,Id) FROM [sCommunication].[tPlaylistMaster])
			END
	END

ELSE

	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 = @rSourceId AND A.OrgId=@rOrgId
				--AND BM.OrgGroupBatchId = @rOrgGroupBatchId

			BEGIN 		
		
				SELECT * FROM (SELECT * FROM (SELECT VP.SourceTypeId, VP.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,VP.PlaylistName as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id 
				WHERE VP.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,VP.PlaylistName  as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				WHERE VP.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId, 'Class' AS SourceType,CM.DisplayTitle AS Source,VP.PlaylistName  as Detail,VP.AssignedToId, 
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tClassMaster CM ON VP.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				WHERE VP.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,VP.PlaylistName as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tDivisionMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				WHERE VP.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,VP.PlaylistName as Detail,
				VP.AssignedToId,CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sStudent.tStudentMaster SM ON VP.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON VP.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				WHERE VP.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId, 'Student' AS SourceType,SA.Name AS Source,VP.PlaylistName as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sStudent.vStudentAcademic SA	ON VP.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				WHERE VP.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0)) TempVideoPlaylist

				UNION ALL

				SELECT * FROM (SELECT	 VP.SourceTypeId, VP.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id 
				WHERE VP.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId,'Department' AS SourceType,DM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				WHERE VP.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId,'Class' AS SourceType,CM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tClassMaster CM ON VP.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				WHERE VP.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tDivisionMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				WHERE VP.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
				VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sStudent.tStudentMaster SM ON VP.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON VP.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				WHERE VP.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId, 'Student' AS SourceType,SA.Name AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sStudent.vStudentAcademic SA	ON VP.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				WHERE VP.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) ) TempVideolist ) TempYouTubeVideoList

				WHERE ((TempYouTubeVideoList.SourceTypeId = 2021 AND TempYouTubeVideoList.SourceId =@lOrgId) OR
					   (TempYouTubeVideoList.SourceTypeId = 2017 AND TempYouTubeVideoList.SourceId =@lDepartmentId) OR
                       (TempYouTubeVideoList.SourceTypeId = 2016 AND TempYouTubeVideoList.SourceId =@lClassId) OR
                       (TempYouTubeVideoList.SourceTypeId = 2005 AND TempYouTubeVideoList.SourceId =@lDivisionId) OR
                       (TempYouTubeVideoList.SourceTypeId = 2003 AND TempYouTubeVideoList.SourceId =@lStudentId) OR
                       (TempYouTubeVideoList.SourceTypeId = 2001 AND TempYouTubeVideoList.SourceId =@lAcademicId) )
				 AND  Detail IN(Select Convert (varchar,Id) FROM [sCommunication].[tPlaylistMaster])

			END
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPlaylistMasterAdd]
	 
	        @rId int
	       ,@rTitle nvarchar(100)
		   ,@rOrderIndex smallint
		   ,@rRemark nvarchar(1000)
	       ,@rIsObsolete bit
		   ,@rOrgGroupId int
		   ,@rCreatedUserId bigint   

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		
		If Exists(select Id from sCommunication.tPlaylistMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
	
		If  Exists(select Id from sCommunication.tPlaylistMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 
	

IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sTransport.tBusRouteMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPlaylistMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sCommunication].[tPlaylistMaster]
			   (
			    [Id]
			   ,[Title]
			   ,[OrderIndex]
			   ,[Remark]
			   ,[IsObsolete]
			   ,[OrgGroupId]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rTitle
			   ,@rOrderIndex
			   ,@rRemark
			   ,@rIsObsolete
			   ,@rOrgGroupId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sCommunication].[tPlaylistMaster]
	    SET
			  Title=@rTitle
			 ,OrderIndex=@rOrderIndex
			 ,Remark=@rRemark
			 ,IsObsolete = @rIsObsolete 
			 ,OrgGroupId = @rOrgGroupId    
             ,UpdatedUserId = @rCreatedUserId
             ,UpdatedDateTime = sCommon.fGetDate()    
             
	      WHERE Id = @rId 	    
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPlayListMasterDataGet]
          
           @rTitle nvarchar(100),
		   @rOrgGroupId int
        
          
AS
SET NOCOUNT ON
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
BEGIN
SELECT 
	   PLM.Id as PlayListId
	  ,PLM.Title
	  ,PLM.OrderIndex 
	  ,PLM.Remark
	  ,PLM.IsObsolete 
	  ,U.DisplayTitle as CreatedUserName
	  ,PLM.CreatedDateTime
	  --comment above line due to mantisid - 0029607 - for different time zone
	  --,[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(PLM.CreatedDateTime,'')) AS CreatedDateTime
  FROM sCommunication.tPlaylistMaster PLM
       INNER JOIN sSecurity.tUser U ON U.Id=PLM.CreatedUserId
  WHERE 
	PLM.OrgGroupId=@rOrgGroupId
	AND 
	((PLM.Title Like @rTitle) OR (ISNULL(@rTitle,'') = ''))
    order by PLM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPlaylistMasterDelete]
	 
	 @rId bigint
	 --@UserId bigint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
IF EXISTS (SELECT 1 FROM  sCommunication.tVideoPlaylist WHERE PlaylistName=CONVERT(nvarchar,@rId))
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	BEGIN TRY
		BEGIN TRANSACTION	
		
			Delete from sCommunication.tPlaylistDetails where PlaylistId=@rId
			Delete from sCommunication.tPlaylistMaster where Id=@rId
			SELECT 1 AS RESULT
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPlaylistMasterGet]
	 @rPlaylistId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	
	SELECT 
			PM.Id,
			PM.Title,
			PM.OrderIndex,
			PM.Remark,
			PM.IsObsolete
			
  FROM 
			[sCommunication].[tPlaylistDetails]  PD
			INNER JOIN [sCommunication].[tPlaylistMaster] PM ON PM.Id=PD.PlaylistId  
WHERE 
			(PM.Id=@rPlaylistId OR @rPlaylistId=0)
			order by PM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPollAdd]
	 
        @rId bigint,
        @rTitle nvarchar(200),
		@rRemark nvarchar(500),
		@rIsOwnAnswer bit,
		@rIsOpen bit,
		@rCreatedUserId bigint,
		@rOrgGroupId smallint,
		@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tPoll where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tPoll where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tPoll where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tPoll where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPoll', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tPoll
		(
			Id,
			Title,
			Remark,
			IsOwnAnswer,
			IsOpen,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rIsOwnAnswer,
			@rIsOpen,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rOrgGroupBatchId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tPoll
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			IsOwnAnswer=@rIsOwnAnswer,
			IsOpen=@rIsOpen,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPollAnswerAdd]
	 
        @rId bigint
       ,@rPollId bigint
       ,@rTitle nvarchar(200)
       ,@rIsDeleted bit
       ,@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tPollAnswer where Id=@rId
	Select @rId as Result
END	
ELSE
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tPollAnswer where Code=@rCode AND PollId=@rPollId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tPollAnswer where Title=@rTitle AND PollId=@rPollId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tPollAnswer where Code=@rCode AND PollId=@rPollId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tPollAnswer where Title=@rTitle AND PollId=@rPollId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPollAnswer', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tPollAnswer
		(
			Id,
			PollId,
			Title
		)
	VALUES
		(
			@lNextNumber,
			@rPollId,
			@rTitle
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tPollAnswer
	    SET
			PollId=@rPollId,
			Title=@rTitle
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPollAnswerGet]
	   @rPollId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	 
	SELECT 
			PA.Id AS PollAnswerId,
			PA.Title AS PollAnswer,
			PA.PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollAnswerId=PA.Id ) AS TotalPollAnswerVote,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote,
			
			CAST((((SELECT  CAST(ISNULL(Count(1),0) AS decimal(12,2)) FROM sCommunication.tPollResult PR WHERE PR.PollAnswerId=PA.Id ) * 100) / 
			(SELECT  CAST(NULLIF(Count(1),0) AS decimal(12,2)) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id)) AS decimal(12,2)) AS PercentagePollAnswerVote
			
			
  FROM 
            sCommunication.tPollAnswer PA
            INNER JOIN sCommunication.tPoll P ON P.Id=PA.PollId
  WHERE 
  
      ((PA.PollId = @rPollId) OR (@rPollId = 0))
      
      UNION ALL
      
      SELECT 
			Distinct(0) AS PollAnswerId,
			'Other' AS PollAnswer,
			ISNULL(PR.PollId,0) AS PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id AND PR.PollAnswerId=0) AS TotalPollAnswerVote,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote,
			
			CAST((((SELECT  CAST(ISNULL(Count(1),0) AS decimal(12,2)) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id AND PR.PollAnswerId=0) * 100) / 
			(SELECT  CAST(NULLIF(Count(1),0) AS decimal(12,2)) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id)) AS decimal(12,2)) AS PercentagePollAnswerVote
			
			
  FROM 
					sCommunication.tPoll P 
            LEFT JOIN sCommunication.tPollResult PR ON P.Id=PR.PollId 
  WHERE 
		P.IsOwnAnswer=1
		AND ((P.Id = @rPollId) OR (@rPollId = 0))
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPollDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tPollResult where 
				PollAnswerId IN(Select Id from sCommunication.tPollAnswer where PollId=@rId)
			Delete from sCommunication.tPollMember where PollId=@rId
			Delete from sCommunication.tPollAnswer where PollId=@rId
			Delete from sCommunication.tPoll where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPollGet]
	 @rId bigint = 0,
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint,
	 @rSourceTypeId smallint,
	 @rCreatedDateTime datetime=''
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
If(@rSourceTypeId = 95)
BEGIN	 
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
         INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2017 
         INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=PM.SourceId
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.OrganizationDepartmentId=ODM.Id
         INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=EJD.EmployeeId
         INNER JOIN sSecurity.tUser U ON U.SourceId=EM.Id AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	AND ISNULL(EM.IsOtherUser,0) = 0
	--UNION
	
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
 -- FROM 
 --           sCommunication.tPoll P
 --           LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
 --   AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
END
ELSE IF(@rSourceTypeId = 2003)
BEGIN
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
		
  FROM 
            sCommunication.tPoll P
         INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2005
         INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId AND SA.IsActiveBatch = 1
         INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
         
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
	
	--UNION
	
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
 -- FROM 
 --           sCommunication.tPoll P
 --            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
 --    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
END

ELSE 

BEGIN
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
			
 -- FROM 
 --           sCommunication.tPoll P
 --        INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2005
 --        INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId
 --        INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
 --         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	--UNION
	
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
  FROM 
            sCommunication.tPoll P
            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
END


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPollListGet]
	 @rId bigint = 0,
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint,
	 @rSourceTypeId smallint,
	 @rCreatedDateTime datetime=''
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
If(@rSourceTypeId = 95)
BEGIN	 
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote,
			(SELECT U.DisplayTitle FROM sSecurity.tUser U WHERE U.Id = P.CreatedUserId) AS DisplayTitle			
  FROM 
            sCommunication.tPoll P			
            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
  WHERE 
  
			((P.Id = @rId) OR (@rId = 0)) 
			AND P.CreatedUSerId = @rCreatedUserId
			AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
	--UNION
	
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
 -- FROM 
 --           sCommunication.tPoll P
 --           LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
 --   AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
END
ELSE IF(@rSourceTypeId = 2003)
BEGIN
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote,
			U.DisplayTitle			
		
  FROM 
            sCommunication.tPoll P
         INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2005
         INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId AND SA.IsActiveBatch = 1
         INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
         
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
	
	--UNION
	
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
 -- FROM 
 --           sCommunication.tPoll P
 --            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
 --    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
END

ELSE 

BEGIN
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
			
 -- FROM 
 --           sCommunication.tPoll P
 --        INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2005
 --        INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId
 --        INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
 --         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	--UNION
	
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote,
			(SELECT U.DisplayTitle FROM sSecurity.tUser U WHERE U.Id = P.CreatedUserId) AS DisplayTitle			
  FROM 
            sCommunication.tPoll P			
            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
END


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPollListTaskPermissionwiseGet]
	 @rId bigint = 0,
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint,
	 @rSourceTypeId smallint,
	 @rCreatedDateTime datetime=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote,
			(SELECT U.DisplayTitle FROM sSecurity.tUser U WHERE U.Id = P.CreatedUserId) AS DisplayTitle			
  FROM 
            sCommunication.tPoll P			
            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUserId = @rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPollMemberAdd]
			@rPollId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tPollMember where PollId=@rPollId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 

	BEGIN TRY
	
	    
	If Exists(select PollId from sCommunication.tPollMember where 
	PollId=@rPollId AND SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
		END 
	ELSE
		BEGIN
			BEGIN TRANSACTION	 
				INSERT INTO sCommunication.tPollMember
				(
					PollId
				   ,SourceTypeId
				   ,SourceId
				)
				VALUES
				(	
					@rPollId
				   ,@rSourceTypeId
				   ,@rSourceId
				)		
				SELECT @rPollId AS Result
			
			COMMIT TRANSACTION
		END
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pPollMemberGet]
	 
	 @rPollId bigint,
	 @rOrgId smallint,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 		
		
	SELECT 
			DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as ClassDept,
			2005 as SourceTypeId,
			CASE WHEN PM.SourceId IS NULL OR PM.PollId!=@rPollId THEN 0 ELSE 1 END AS IsObsolete,
			OM.DisplayTitle AS Organization,
			--CM.OrderIndex+DM.OrderIndex AS OrderIndex --Commented for mantis : 35038
			/******Added for mantis : 35038 by Nilesh******/
			CM.OrderIndex AS OrderIndex,
			DM.OrderIndex As DivisionOrderIndex
  FROM 
			sSetup.tDivisionMaster DM
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId --Commented for mantis : 35038 by Nilesh
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND DM.IsObsolete = 0 --Added for mantis : 35038 by Nilesh
			LEFT JOIN sCommunication.tPollMember PM ON PM.SourceId=DM.Id AND PM.SourceTypeId=2005 AND PM.PollId=@rPollId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId AND OM.OrgGroupId=@rOrgGroupId
	 WHERE
		((DM.OrgId=@rOrgId) OR (@rOrgId=0))
		UNION
	SELECT 
			ODM.Id  as SourceId,
			ODM.Title as ClassDept,
			2004 as SourceTypeId,
			CASE WHEN PM.SourceId IS NULL OR PM.PollId!=@rPollId THEN 0 ELSE 1 END AS IsObsolete,
			OM.DisplayTitle AS Organization,
			/******Added for mantis : 35038 by Nilesh******/
			0 AS OrderIndex,
			0 As OrderIndexDivision
  FROM 
			sSetup.tDepartmentMaster ODM
			LEFT JOIN sCommunication.tPollMember PM ON PM.SourceId=ODM.Id AND PM.SourceTypeId=2017 AND PM.PollId=@rPollId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ODM.OrgId AND OM.OrgGroupId=@rOrgGroupId
	WHERE
		((ODM.OrgId=@rOrgId) OR (@rOrgId=0))

		Order By OrderIndex,DivisionOrderIndex --Added for mantis : 35038 by Nilesh
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pPollResultAdd]
	 
        @rPollAnswerId bigint,
        @rPollId bigint,
		@rRemark nvarchar(500),
		@rCreatedUserId bigint,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	--Edited by Parth -13/07/2016
	----START----
	IF EXISTS(SELECT 1 FROM sCommunication.tPollResult WHERE PollId=@rPollId AND CreatedUserId=@rCreatedUserId)
	BEGIN
		SELECT Id as Result FROM sCommunication.tPollResult WHERE PollId=@rPollId AND CreatedUserId=@rCreatedUserId 
		RETURN
	END
	----END----
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPollResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tPollResult
		(
			Id,
			PollId,
			PollAnswerId,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rPollId,
			@rPollAnswerId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPollUserGet]
	 @rPollId bigint,
	 @rCreatedUserId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT PR.CreatedUserId from 
	        sCommunication.tPollResult PR 
  WHERE 
      ((PR.CreatedUSerId = @rCreatedUserId) OR (@rCreatedUserId = 0))
    AND ((PR.PollId = @rPollId) OR (@rPollId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pPortalBookUploadGet]
	 
	 @rOrgId int,
	 @rBatchId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	 
BEGIN 	
	SELECT	BL.Id,
		    Replace(BM.Title,CHAR(39),'') as Title,
			LogDate, 
			ISNULL(ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(ReaderSourceId,0) AS ReaderSourceId,
			BatchId 
	FROM	sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId 
	
	WHERE	BL.Id NOT IN (SELECT BookLogId FROM sCommunication.tUploadBookLog) 
			AND BL.OrgId = @rOrgId             
			AND BL.BatchId=@rBatchId   
    END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pQueryAdd]
	 
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int,
	@rQueryCategoryId int,
	@rId AS bigint,
	@rTitle nvarchar(100),
	@rRemark nvarchar(1000),
	@rIsUserView bit,
	@rIsAssigneeView bit,
	@rStatusId smallint,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rSubjectId int=0,
	@rAssignedToEmployeeId bigint=0,
	@rAssignedToRemark nvarchar(500)='',
	@rIsOfflineEntry bit=0,
	@rFromSourceTypeId smallInt=0,
	@rFromSourceId bigint=0,
	@rTargetResolutionDate datetime=null    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId = 0)
BEGIN
DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQuery', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	DECLARE @lNumber int=0
	SELECT @lNumber=ISNULL(MAX(Number),0)+1 FROM sCommunication.tQuery WHERE OrgGroupBatchId = @rOrgGroupBatchId
	
	
	INSERT INTO sCommunication.tQuery
		(
			OrgGroupId,
			OrgGroupBatchId,
			QueryCategoryId,
			Id,
			Title,
			Number,
			Remark,
			IsUserView,
			IsAssigneeView,
			StatusId,
			CreatedUserId,
			CreatedDateTime,
			SubjectId,
			AssignedToEmployeeId,
			AssignedToRemark,
			IsOfflineEntry,
			FromSourceTypeId,
			FromSourceId,
			TargetResolutionDate
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rQueryCategoryId,
			@lNextNumber,
			@rTitle,
			@lNumber,
			@rRemark,
			@rIsUserView,
			@rIsAssigneeView,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSubjectId,
			@rAssignedToEmployeeId,
			@rAssignedToRemark,
			@rIsOfflineEntry,
			@rFromSourceTypeId,
			@rFromSourceId,
			@rTargetResolutionDate
		)
		select @lNextNumber,1 as result
		--select @lNextNumber,@lNextNumber as result
END
ELSE
BEGIN
		UPDATE sCommunication.tQuery 
		SET IsUserView = @rIsUserView,
		IsAssigneeView=@rIsAssigneeView,
		AssignedToEmployeeId=@rAssignedToEmployeeId,
		AssignedToRemark=@rAssignedToRemark,
		IsOfflineEntry=@rIsOfflineEntry,
		FromSourceTypeId=@rFromSourceTypeId,
		FromSourceId=@rFromSourceId,
		TargetResolutionDate=@rTargetResolutionDate,
		Remark=@rRemark
		
		 WHERE Id = @rId
		select 0,11 as result
END
	
	COMMIT TRANSACTION
	
END TRY

	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryAssignedToAdd]
	 
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rQueryCategoryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION
	 IF EXISTS(SELECT 1 FROM sCommunication.tQueryCategoryAssignedTo WHERE SourceTypeId=@rSourceTypeId 
	 AND SourceId=@rSourceId AND QueryCategoryId=@rQueryCategoryId)
	 BEGIN
			SELECT @rQueryCategoryId AS Result
			RETURN
	 END
	INSERT INTO sCommunication.tQueryCategoryAssignedTo
		(
			SourceTypeId,
			SourceId,
			QueryCategoryId
		)
	VALUES
		(
			@rSourceTypeId,
			@rSourceId,
			@rQueryCategoryId
		) 
		
		SELECT @rQueryCategoryId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryAssignedToDelete]
	 
	 @rSourceId bigint,
	 @rQueryCategoryId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE SourceId=@rSourceId AND QueryCategoryId = @rQueryCategoryId
			SELECT 1 AS Result
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
			SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryAssignedToGet]
	 
	 @rQueryCategoryId int,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			QCM.Id AS QueryCategoryId,
			QCA.SourceTypeId,
			'Functional Rolewise' AS SourceType,
			QCA.SourceId,
			'' AS SourceCode,
			R.Title AS SourceName
	FROM 
			sCommunication.tQueryCategoryAssignedTo QCA
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
		INNER JOIN sSecurity.tRole R ON R.Id=QCA.SourceId AND QCA.SourceTypeId=2015
	WHERE 
			(QCA.QueryCategoryId = @rQueryCategoryId)
			
	UNION ALL
	
	SELECT 
			QCM.Id,
			QCA.SourceTypeId,
			'Specific Employeewise' AS SourceType,
			QCA.SourceId,
			EM.EmployeeCode AS SourceCode,
			EM.EmployeeName AS SourceName
	FROM 
			sCommunication.tQueryCategoryAssignedTo QCA
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
		INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId=QCA.SourceId AND QCA.SourceTypeId=95
	WHERE 
			(QCA.QueryCategoryId = @rQueryCategoryId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryDropdownGet]
	@rOrgGroupBatchId int,
	@rUserSourceId bigint,
	@rUserSourceTypeId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	IF @rUserSourceTypeId = 95 -- For Employee Login
	BEGIN
		SELECT 
			@lDepartmentId=EJD.OrganizationDepartmentId,
			@lOrgId = EM.OrgId,
			@lEmployeeId = EM.Id 
		FROM 
			sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		WHERE 
			EM.Id=@rUserSourceId
		
		SELECT Distinct	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM           
			INNER JOIN 
			(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) 
				AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))) D
				ON D.QueryCategoryId= QCM.Id
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=QCM.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
			--INNER JOIN sSecurity.tUser U ON U.Id=QCM.CreatedUserId
		WHERE 
			QCM.AssignedToId IN (1,3) 
			AND QCM.IsObsolete = 0

		UNION

		SELECT Distinct	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM           
			INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCM.Id = QCA.QueryCategoryId
			AND QCA.SourceTypeId = 95 AND QCA.SourceId =@lEmployeeId
	
		WHERE 
			---QCM.AssignedToId IN (1,3) 
			QCM.IsObsolete = 0

	END
	ELSE IF @rUserSourceTypeId = 2003 -- For Student Login
	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 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
  
		SELECT 	Distinct
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM
			INNER JOIN (SELECT QCS.QueryCategoryId 
				FROM sCommunication.tQueryCategoryScope QCS
				WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
				(QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
				(QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
				(QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
				)AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D ON D.QueryCategoryId= QCM.Id 
		WHERE
			QCM.AssignedToId IN (1,2) 
			AND QCM.IsObsolete = 0
	END
	ELSE
	--For Other Users
	BEGIN
		SELECT 	
			QCM.Id,
			QCM.Title
		FROM 
			sCommunication.tQueryCategoryMaster QCM
		WHERE 
			QCM.AssignedToId IN (1,2,3)
			AND QCM.IsObsolete = 0
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryMasterAdd]
	 
	@rId int,
	@rTitle nvarchar(100),
	@rRemark nvarchar(200),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupId smallint,
	@rAssignToId smallint,
	@rTempQueryCategoryId nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	
		IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
 
	END
	ELSE
	BEGIN
 
		If  Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgGroupId =@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQueryCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommunication.tQueryCategoryMaster
		(
			Id,
			Title,
			Remark,
			OrgGroupId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			AssignedToId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rOrgGroupId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rAssignToId
		)        
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tQueryCategoryMaster
	    SET
	      Title=@rTitle,
	      Remark=@rRemark,
	      IsObsolete=@rIsObsolete,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate(),
	      AssignedToId = @rAssignToId
	      WHERE Id = @rId 	   
	 END  
		-- #Start MantisId : 0030903
		IF(@rId <> 0)
		BEGIN
			DELETE FROM sCommunication.tQueryCategoryScope WHERE QueryCategoryId = @rTempQueryCategoryId	
		END
		-- #End MantisId : 0030903
	 	INSERT INTO sCommunication.tQueryCategoryScope
		SELECT @lNextNumber,SourceTypeId,SourceId,AssigneeToId
		FROM sCommunication.tTempQueryCategoryScope
		WHERE TempQueryCategoryId = @rTempQueryCategoryId
		
		DELETE FROM sCommunication.tTempQueryCategoryScope WHERE TempQueryCategoryId = @rTempQueryCategoryId

		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryMasterDelete]
	 
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tQueryCategoryAssignedTo where QueryCategoryId=@rId
			Delete from sCommunication.tQueryCategoryOrg where QueryCategoryId=@rId
			Delete from sCommunication.tQueryCategoryMaster where Id=@rId
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
  BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
  END
	 
	SELECT 
			QM.Id,
			QM.Title,
			QM.Remark,
			QM.IsObsolete,
			ISNULL(QM.AssignedToId,1) as AssignedToId
  FROM 
         sCommunication.tQueryCategoryMaster QM
  WHERE 
			((QM.Id = @rId) OR (@rId = 0))
		AND ((QM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
		AND (QM.OrgGroupId = @rOrgGroupId)	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryOrgAdd]
			
			@rQueryCategoryId int
           ,@rOrgId smallint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tQueryCategoryOrg where QueryCategoryId=@rQueryCategoryId AND OrgId=@rOrgId
	Select @rOrgId as Result
END	
ELSE
BEGIN 

		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select QueryCategoryId from sCommunication.tQueryCategoryOrg where QueryCategoryId=@rQueryCategoryId AND OrgId=@rOrgId)
		BEGIN
			SELECT @rOrgId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tQueryCategoryOrg
			(
				QueryCategoryId
			   ,OrgId
			)
			VALUES
			(	
				@rQueryCategoryId
			   ,@rOrgId
			)		
			SELECT @rQueryCategoryId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END 	             
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryOrgGet]
	 
	 @rQueryCategoryId int,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			OM.Id AS OrgId,
			OM.DisplayTitle as Organization,
			CASE WHEN QCO.OrgId IS NULL OR QCO.QueryCategoryId!=@rQueryCategoryId THEN 0 ELSE 1 END AS IsObsolete
	FROM 
			sSetup.tOrganizationMaster OM
			LEFT JOIN sCommunication.tQueryCategoryOrg QCO ON QCO.OrgId=OM.Id AND QCO.QueryCategoryId=@rQueryCategoryId
	WHERE (OM.OrgGroupId=@rOrgGroupId)
	Order BY OM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryScopeGet]
	 @rQueryCategoryId bigint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.QueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tQueryCategoryScope CS
			INNER JOIN sSetup.tOrganizationMaster OM ON CS.SourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.QueryCategoryId=@rQueryCategoryId AND CS.SourceTypeId=2021

			UNION ALL

			SELECT
			 CS.QueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tQueryCategoryScope CS
			INNER JOIN sSetup.tDepartmentMaster DM ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.QueryCategoryId=@rQueryCategoryId AND CS.SourceTypeId=2017

			UNION ALL

			SELECT
			 CS.QueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tQueryCategoryScope CS
			INNER JOIN  sSetup.tClassMaster CM ON CS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.QueryCategoryId=@rQueryCategoryId AND CS.SourceTypeId=2016

			UNION ALL

			SELECT
			 CS.QueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tQueryCategoryScope CS
			INNER JOIN   sSetup.tDivisionMaster DM ON CS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId	
			WHERE CS.QueryCategoryId=@rQueryCategoryId AND CS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.QueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tQueryCategoryScope CS
		    INNER JOIN sStudent.tStudentMaster SM ON CS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.QueryCategoryId=@rQueryCategoryId AND CS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.QueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			 
			FROM sCommunication.tQueryCategoryScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.QueryCategoryId=@rQueryCategoryId AND CS.SourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.QueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 CS.AssigneeToId,
			 0 AS IsTempFlag
			
			FROM sCommunication.tQueryCategoryScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId	
			WHERE 
			CS.QueryCategoryId=@rQueryCategoryId AND CS.SourceTypeId=95

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCategoryScopeRemove]
			
			@rTempQueryCategoryId nvarchar(100)
		   ,@rQueryCategoryId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rAssigneeToId tinyint
		   ,@rIsTempFlag int
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	IF(@rIsTempFlag = 1)
	BEGIN
		Delete from sCommunication.tTempQueryCategoryScope where TempQueryCategoryId=@rTempQueryCategoryId AND SourceTypeId=@rSourceTypeId And AssigneeToId=@rAssigneeToId
		 AND SourceId=@rSourceId
	END
	ELSE
	BEGIN
		Delete from sCommunication.tQueryCategoryScope where QueryCategoryId=@rQueryCategoryId AND SourceTypeId=@rSourceTypeId And AssigneeToId=@rAssigneeToId
		 AND SourceId=@rSourceId
	END

	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCloseUpdate]
	 
	@rQueryId bigint,
	@rStatusId tinyint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
		UPDATE sCommunication.tQuery SET StatusId=@rStatusId WHERE Id=@rQueryId
		SELECT 1 Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryCommentDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tQueryComment where Id=@rId
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pQueryDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sCommunication.tQuery where Id=@rId		
			SELECT 1
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pQueryListAdd]

     @rId int=0,
     @rParentMenuId int=0,
     @rTitle nvarchar(100)='', 
     @rTitleResourceKeyid int=0, 
     @rScreenId int=0,
     @rIsObsolete bit=0,
     @rOrderNumber smallint=0,
     @rShortcutKey nvarchar(50)='',
     @rStatus varchar(1)
      	       	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY

IF(@rStatus = 'A')	
	BEGIN
	
	IF NOT EXISTS (SELECT Id from sSecurity.tMenu where Title =@rTitle)	
	
	BEGIN	
		
		Declare @MaxId Int 
		SET @MaxId=(SELECT MAX(id) as Id FROM sSecurity.tMenu)
		SET @MaxId=@MaxId + 1
		
		INSERT INTO sSecurity.tMenu
			(			
				 Id,
				 ParentMenuId,
				 Title,
				 TitleResourceKeyId,
				 ScreenId,
				 IsObsolete,
				 OrderNumber,
				 ShortcutKey

			)
		VALUES
			(			 
				 @MaxId, 
				 @rParentMenuId , 
				 @rTitle , 
				 @rTitleResourceKeyid , 
				 @rScreenId , 
				 @rIsObsolete,
				 @rOrderNumber ,			  
				 @rShortcutKey
			)
		SELECT 1 AS Result
	  END
	  ELSE
	  BEGIN
	    SELECT -103 AS Result
	  END
	  
	END	 

ELSE IF (@rStatus = 'U')
	 BEGIN
	 --SET @lNextNumber = @rId
	 IF NOT EXISTS (SELECT Id from sSecurity.tMenu where Title =@rTitle and Id<>@rId)	
	  BEGIN

	    UPDATE  sSecurity.tMenu
	    SET
	        ParentMenuId=@rParentMenuId,	        
			Title=@rTitle,
			TitleResourceKeyid=@rTitleResourceKeyid,
			ScreenId=@rScreenId,
			IsObsolete=@rIsObsolete,			
			OrderNumber=@rOrderNumber,
			ShortcutKey=@rShortcutKey
	      WHERE Id = @rId
	    SELECT 2 AS Result
	 
	   END
	  ELSE
	  BEGIN
	   SELECT -103 AS Result
	  END 
	 END 

ELSE IF (@rStatus = 'D')
	 BEGIN
	  DELETE 
	    FROM 
	       sSecurity.tMenu 
	  WHERE Id=@rId
	  
	  SELECT 3 AS Result
	  	  
	 END

	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryListGet]
     @rQueryCategoryId int = 0,
	 --@rTitle nvarchar(100),
	 @rOrgGroupBatchId int,
	 --@rOrgId int,
	 @rOrgGroupId int=0,
	 @rId bigint,
	 @rCreatedUserId bigint=0,
	 @rSyncedQueryId bigint = 0,
	 @rStatusId int = 0,
	 @rCreatedFromDate date=NULL,
	 @rCreatedToDate date=NULL, 
	 @rFromResolutionDate date=NULL,
	 @rToResolutionDate date=NULL,
	 @rFromSourceTypeId smallint=0,  
	 @rTitle nvarchar(100)='',  
	 @rNumber smallint=0,
	 @rQueryStatus varchar(25)=NULL ,
	 @rAssignedToEmployeeId bigint=0,
	 @rSourceId bigint=0,
	 @FromPage varchar(50)='',
	 @rAssignedToId smallint = 0,
	 @rUserSourceTypeId int= 0 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
------
 --Added A.IsActiveBatch = 1 for mantis : 41517 for vStudentAcademic
------
	  BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  END
	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
	  IF @rUserSourceTypeId   = 95 -- For Employee Login
	  BEGIN
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
				 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId


		SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			--VQCM.OrgId As OrgId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(U.SourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId and A.IsActiveBatch = 1
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
		--INNER JOIN sCommunication.vOrgwiseQueryCategory VQCM ON QM.QueryCategoryId=VQCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN 
				(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				 WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))
				 ) D
				ON D.QueryCategoryId= QCM.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(VQCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,3) 
        ORDER BY QM.CreatedDateTime DESC

	  END
	  ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
	  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 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE StudentId = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

		SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			--VQCM.OrgId As OrgId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(U.SourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId and A.IsActiveBatch = 1
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
		--INNER JOIN sCommunication.vOrgwiseQueryCategory VQCM ON QM.QueryCategoryId=VQCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN (SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
            WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
            (QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
            (QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
            (QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
            (QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
            (QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
            )AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D
			ON	D.QueryCategoryId= QCM.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
      AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(VQCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,2) 
        ORDER BY QM.CreatedDateTime DESC

	  END
	  ELSE --For Other Login
	  BEGIN
			SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			--VQCM.OrgId As OrgId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			--ISNULL(U.SourceTypeId,0) AS FromSourceTypeId,
			--comment above FromSourceTypeId because in admin login we get 0 FromSourceTypeId - mantisid -- 0030521
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId and A.IsActiveBatch = 1
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT 
			                                                        U.DisplayTitle
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
		--INNER JOIN sCommunication.vOrgwiseQueryCategory VQCM ON QM.QueryCategoryId=VQCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(QCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
        ORDER BY QM.CreatedDateTime DESC
	  END

        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pQueryListGetNew]
	 @rQueryCategoryId int = 0,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId int=0,
	 @rId bigint,
	 @rCreatedUserId bigint=0,
	 @rSyncedQueryId bigint = 0,
	 @rStatusId int = 0,
	 @rCreatedFromDate date=NULL,
	 @rCreatedToDate date=NULL, 
	 @rFromResolutionDate date=NULL,
	 @rToResolutionDate date=NULL,
	 @rFromSourceTypeId smallint=0,  
	 @rTitle nvarchar(100)='',  
	 @rNumber smallint=0,
	 @rQueryStatus varchar(25)=NULL ,
	 @rAssignedToEmployeeId bigint=0,
	 @rSourceId bigint=0,
	 @FromPage varchar(50)='',
	 @rAssignedToId smallint = 0,
	 @rUserSourceTypeId int= 0 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
------
 --Added A.IsActiveBatch = 1 for mantis : 41517 for vStudentAcademic
------
	  BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  END

	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	  IF @rUserSourceTypeId   = 95 -- For Employee Login
	  BEGIN
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
				 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId


		SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(U.SourceTypeId,0) AS FromSourceTypeId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId 
			   AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT DM.Title  FROM [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId and A.IsActiveBatch = 1)
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT DM.Title FROM sHrm.tEmployeeJobDetail EJD
											  INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
											  WHERE EmployeeId=QM.FromSourceId)
				ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT U.DisplayTitle )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT U.DisplayTitle)
			   ELSE U.DisplayTitle
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN 
				(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				 WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))
				 ) D
				ON D.QueryCategoryId= QCM.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(VQCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,3) 
        ORDER BY QM.CreatedDateTime DESC

	  END

	  ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
	  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 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE StudentId = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

		SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			--VQCM.OrgId As OrgId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(U.SourceTypeId,0) AS FromSourceTypeId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT DM.Title FROM [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId and A.IsActiveBatch = 1)
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT DM.Title FROM sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId)	
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT U.DisplayTitle)
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT U.DisplayTitle)
			   ELSE '' END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
		FROM sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN (SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
            WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
            (QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
            (QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
            (QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
            (QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
            (QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
            )AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D
			ON	D.QueryCategoryId= QCM.Id
	
	WHERE ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		AND QCM.AssignedToId IN (1,2) 
        ORDER BY QM.CreatedDateTime DESC

	  END

	  ELSE --For Other Login
	  BEGIN
		SELECT 
		QM.Id AS QueryId,
		QCM.Id AS QueryCategoryId,
		ISNULL(QCM.Title,'') AS QueryCategoryMaster,
		QM.Title,
		QM.Remark,
		QM.CreatedDateTime,
		QM.StatusId,
		ISNULL(sm.Title,'') AS StatusMaster,
		QM.IsAssigneeView,
		QM.IsUserView,
		QM.CreatedUserId AS QueryCreatedUserId,
		ISNULL(QM.SubjectId,0) AS SubjectId,
		ISNULL(SubM.Title,'') AS SubjectName,
		ISNULL(QM.Number,0) AS Number,
		ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
		ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
		ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
		ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
		CASE 
			WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			ELSE ''
		END AS FromSourceId,
		CASE 
			WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT  DM.Title FROM [sStudent].[vStudentAcademic] A 
			                                                INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId and A.IsActiveBatch = 1)
            WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT DM.Title FROM  sHrm.tEmployeeJobDetail EJD
														INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                            WHERE EmployeeId=QM.FromSourceId)
			ELSE ''
		END AS Code,
		CASE 
			WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT U.DisplayTitle)
            WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT U.DisplayTitle)
			ELSE U.DisplayTitle
		END AS Name,
		ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
		(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName			  
			
	FROM sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
	
	WHERE ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
        ORDER BY QM.CreatedDateTime DESC
	END        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pQueryListSummaryDetailsGet]
	 @rQueryCategoryId int = 0,
	 @rFromSourceTypeId int=0,
	 @rOrgGroupBatchId int,
	 @rQueryStatus varchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			
BEGIN 

    IF(@rQueryStatus='TodayNewOpenTickitDiv')	  
    BEGIN
    
     SELECT 
           
              QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate 
           
           
		FROM                           
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
			  INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
			  INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
			  LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
			  LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
	    WHERE ((QM.QueryCategoryId=@rQueryCategoryId )OR(@rQueryCategoryId =0))
				AND QM.StatusId=209 					
				AND CONVERT(DATE,QM.CreatedDateTime)=CONVERT(DATE,GETDATE())
				AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))	
				AND ISNULL(EM.IsOtherUser,0) = 0    	  		        
	 
	END 
	
	ELSE IF(@rQueryStatus='CloseTicketOfTodayDiv')	
	BEGIN
	  
	  SELECT 
           
              QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate 
           
           
		FROM                           
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
			  INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
			  INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
			  LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
			  LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
	    WHERE ((QM.QueryCategoryId=@rQueryCategoryId)OR(@rQueryCategoryId=0))--QueryCategoryId=QCM.QueryCategoryId					
					AND QM.StatusId=210 					
					AND CONVERT(DATE,QM.CreatedDateTime)=CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)										
			        AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))
					AND ISNULL(EM.IsOtherUser,0) = 0  
	  
	END
	
	ELSE IF(@rQueryStatus='HoldTicketOfTodayDiv')	
	BEGIN
	  
	  SELECT 
           
            QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate 
           
           
		FROM                           
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
			  INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
			  INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
			  LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
			  LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
	    WHERE ((QM.QueryCategoryId=@rQueryCategoryId)OR(@rQueryCategoryId=0))--QueryCategoryId=QCM.QueryCategoryId					
					AND QM.StatusId=709 		
					AND CONVERT(DATE,QM.CreatedDateTime)=CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)										
				    AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))	
					AND ISNULL(EM.IsOtherUser,0) = 0    	  
	  
	END
	
	
	ELSE IF(@rQueryStatus='OverdueTicketOfTodayDiv')	
	BEGIN
	  
	  SELECT 
           
            QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate 
           
           
		FROM                           
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
			  INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
			  INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
			  LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
			  LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
	    WHERE  ((QM.QueryCategoryId=@rQueryCategoryId)OR(@rQueryCategoryId=0))--QueryCategoryId=QCM.QueryCategoryId					
					AND QM.StatusId<>210 		
					AND CONVERT(DATE,QM.TargetResolutionDate)<CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)										
				    AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))   
					AND ISNULL(EM.IsOtherUser,0) = 0	  
	  
	END
	
	
	ELSE IF(@rQueryStatus='PendingTicketOfTodayDiv')	
	BEGIN
	  
	  SELECT 
           
            QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate 
           
           
		FROM                           
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
			  INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
			  INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
			  LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
			  LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
	    WHERE  ((QM.QueryCategoryId=@rQueryCategoryId)OR(@rQueryCategoryId=0))--QueryCategoryId=QCM.QueryCategoryId					
					AND QM.StatusId=209 		
					AND CONVERT(DATE,QM.TargetResolutionDate)=CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)					
				    AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0)) 
					AND ISNULL(EM.IsOtherUser,0) = 0	  
	  
	END
	
	
	ELSE IF(@rQueryStatus='PendingTicketOnTodayDiv')	
	BEGIN
	  
	  SELECT 
           
            QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate 
           
           
		FROM                           
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
			  INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
			  INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
			  LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
			  LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
	    WHERE   ((QM.QueryCategoryId=@rQueryCategoryId)OR(@rQueryCategoryId=0))--QueryCategoryId=QCM.QueryCategoryId					
					AND QM.StatusId=209 		
					AND CONVERT(DATE,QM.TargetResolutionDate)<=CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)				
				    AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))	
					AND ISNULL(EM.IsOtherUser,0) = 0 
	  
	END
	                         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryListSummaryGet]
	 @rQueryCategoryId int = 0,
	 @rFromSourceTypeId int=0,
	 @rOrgGroupBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			
BEGIN 	  
           SELECT 
                     Count(QCM1.Id) AS NewOpenTicketsTodayCount,
                     Count(QCM2.Id) AS CloseTicketsTodayCount,
                     Count(QCM3.Id) AS HoldTicketsTodayCount,
                     Count(QCM4.Id) AS OverdueTicketOfTodayCount,
                     Count(QCM5.Id) AS PendingTicketOfTodayCount,
                     Count(QCM6.Id) AS PendingTicketOnTodayCount						
	       FROM
	          sCommunication.tQuery QCM
	          INNER JOIN sCommunication.tQueryCategoryMaster QCMM ON QCM.QueryCategoryId=QCMM.Id
			  INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QCM.StatusId
			  INNER JOIN sSecurity.tUser U ON QCM.CreatedUserId = U.Id
			  LEFT JOIN sHrm.tEmployeeMaster EM ON QCM.AssignedToEmployeeId=EM.Id AND ISNULL(EM.IsOtherUser,0) = 0
			  LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QCM.SubjectId
	          
	          LEFT JOIN
	          (
				SELECT QueryCategoryId,Id
				 FROM                           
				 sCommunication.tQuery QM
			   WHERE ((QM.QueryCategoryId=@rQueryCategoryId )OR(@rQueryCategoryId =0))--QueryCategoryId=QCM.QueryCategoryId					
					AND StatusId=209 					
					AND CONVERT(DATE,CreatedDateTime)=CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)
			        AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))	
			    	   					
				)QCM1 ON QCM1.Id = QCM.Id
	          
	          LEFT JOIN
	          (
				SELECT QueryCategoryId,Id
				 FROM                           
				  sCommunication.tQuery QM
				  
			   WHERE ((QM.QueryCategoryId=@rQueryCategoryId)OR(@rQueryCategoryId=0))--QueryCategoryId=QCM.QueryCategoryId					
					AND StatusId=210 					
					AND CONVERT(DATE,CreatedDateTime)=CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)										
			        AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))	   								
	          )QCM2 ON QCM2.Id = QCM.Id
	          
	          
	          LEFT JOIN
	          (
				SELECT QueryCategoryId,Id
				 FROM                           
				 sCommunication.tQuery QM
			   WHERE ((QM.QueryCategoryId=@rQueryCategoryId)OR(@rQueryCategoryId=0))--QueryCategoryId=QCM.QueryCategoryId					
					AND StatusId=709 		
					AND CONVERT(DATE,CreatedDateTime)=CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)										
				    AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))	   			 										
	          )QCM3 ON QCM3.Id = QCM.Id
	          
	          
	          LEFT JOIN
	          (
				SELECT QueryCategoryId,Id
				 FROM                           
				 sCommunication.tQuery QM
			   WHERE ((QM.QueryCategoryId=@rQueryCategoryId)OR(@rQueryCategoryId=0))--QueryCategoryId=QCM.QueryCategoryId					
					AND StatusId<>210 		
					AND CONVERT(DATE,TargetResolutionDate)<CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)										
				    AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))	   											
	          )QCM4 ON QCM4.Id = QCM.Id
	          
	          LEFT JOIN
	          (
				SELECT QueryCategoryId,Id
				 FROM                           
				 sCommunication.tQuery QM
			   WHERE ((QM.QueryCategoryId=@rQueryCategoryId)OR(@rQueryCategoryId=0))--QueryCategoryId=QCM.QueryCategoryId					
					AND StatusId=209 		
					AND CONVERT(DATE,TargetResolutionDate)=CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)					
				    AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))
				
	          )QCM5 ON QCM5.Id = QCM.Id
	          
	          
	            LEFT JOIN
	          (
				SELECT QueryCategoryId,Id
				 FROM                           
				 sCommunication.tQuery QM
			   WHERE ((QM.QueryCategoryId=@rQueryCategoryId)OR(@rQueryCategoryId=0))--QueryCategoryId=QCM.QueryCategoryId					
					AND StatusId=209 		
					AND CONVERT(DATE,TargetResolutionDate)<=CONVERT(DATE,GETDATE())
					AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId)				
				    AND ((QM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))	
				
	          )QCM6 ON QCM6.Id = QCM.Id
	          	          	      
	       WHERE ((QCM.QueryCategoryId = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	       AND 	((QCM.FromSourceTypeId = @rFromSourceTypeId) OR (@rFromSourceTypeId = 0))	       	  		        
	       
	                         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pQueryListSummaryGet1]
	 @rQueryCategoryId int = 0,
	 @rFromSourceTypeId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			
BEGIN 	  
           SELECT QCM.QueryCategoryId,
	          (SELECT COUNT (Id) AS  NewOpenTicketsTodayCount
				 FROM                           
				 sCommunication.tQuery QM
			   WHERE ((QueryCategoryId=0)OR(0=0))--QueryCategoryId=QCM.QueryCategoryId
					AND ((FromSourceTypeId=2003 )OR(0=0))--ISNULL(QM.FromSourceTypeId,0)=@rFromSourceTypeId 
					AND StatusId=209 					
					AND CONVERT(DATE,CreatedDateTime)=CONVERT(DATE,GETDATE()-2)
					) AS NewOpenTicketsTodayCount
					
			  --(SELECT COUNT (Id) AS  CloseTicketsTodayCount
				 --FROM                           
				 --sCommunication.tQuery QM
			  -- WHERE QueryCategoryId=@rQueryCategoryId 
					--AND ISNULL(QM.FromSourceTypeId,0)=@rFromSourceTypeId AND StatusId=210 
					--AND CONVERT(DATE,CreatedDateTime)=CONVERT(DATE,GETDATE())) AS CloseTicketsTodayCount,
					
					
			  -- (SELECT COUNT (Id) AS  HoldTicketsTodayCount
				 --FROM                           
				 --sCommunication.tQuery QM
			  -- WHERE QueryCategoryId=@rQueryCategoryId 
					--AND ISNULL(QM.FromSourceTypeId,0)=@rFromSourceTypeId AND StatusId<>709 
					--AND CONVERT(DATE,CreatedDateTime)=CONVERT(DATE,GETDATE())) AS HoldTicketsTodayCount,
					
					
			  -- (SELECT COUNT (Id) AS  OverdueTicketsOnTodayCount
				 --FROM                           
				 --sCommunication.tQuery QM
			  -- WHERE QueryCategoryId=@rQueryCategoryId 
					--AND ISNULL(QM.FromSourceTypeId,0)=@rFromSourceTypeId AND StatusId<>210 
					--AND CONVERT(DATE,TargetResolutionDate)<CONVERT(DATE,GETDATE())) AS 	OverdueTicketsOnTodayCount	
	       FROM
	       
	          sCommunication.tQuery QCM
	      
	       --WHERE ((QCM.QueryCategoryId = @rQueryCategoryId) OR (@rQueryCategoryId = 0)) 
	        WHERE 0=0
	       
	       Group by QueryCategoryId
	       
	                         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryListv2Get]
	 
	 
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint,
	 @rSourceId bigint=0,
	 @rUserSourceTypeId int	
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
		DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
	 	
		IF @rUserSourceTypeId   = 95 -- For Employee Login
		BEGIN
		 SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId

		SELECT 
				QM.Id AS QueryId,
				QCM.Id AS QueryCategoryId,
				ISNULL(QCM.Title,'') AS QueryCategoryMaster,
				QM.Title,
				QM.Remark,
				CONVERT(VARCHAR,QM.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,QM.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,QM.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), QM.CreatedDateTime, 100) AS CreatedDateTime,
				QM.StatusId,
				ISNULL(sm.Title,'') AS StatusMaster,
				QM.IsAssigneeView,
				QM.IsUserView,
				QM.CreatedUserId AS QueryCreatedUserId,
				ISNULL(QM.Number,0) AS QueryNumber
	   FROM 
				sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
			INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
			INNER JOIN 
				(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				 WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))
				 ) D
				ON D.QueryCategoryId= QCM.Id
	   WHERE 
				QM.OrgGroupBatchId=@rOrgGroupBatchId
			AND QM.CreatedUserId=@rCreatedUserId
			AND QCM.AssignedToId IN (1,3) 
			order by QM.Id desc


		END
		ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
		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 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				WHERE StudentId = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

			SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			CONVERT(VARCHAR,QM.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,QM.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,QM.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
			--CONVERT(VARCHAR(25), QM.CreatedDateTime, 100) AS CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.Number,0) AS QueryNumber
			FROM 
					sCommunication.tQuery QM
				INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
				INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
				INNER JOIN (SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
					WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
					(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
					(QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
					(QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
					(QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
					(QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
					)AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D
					ON	D.QueryCategoryId= QCM.Id
			WHERE 
					QM.OrgGroupBatchId=@rOrgGroupBatchId
				AND QM.CreatedUserId=@rCreatedUserId
				AND QCM.AssignedToId IN (1,2)
		
				order by QM.Id desc
		END
		ELSE --For Other Users
		BEGIN
				SELECT 
					QM.Id AS QueryId,
					QCM.Id AS QueryCategoryId,
					ISNULL(QCM.Title,'') AS QueryCategoryMaster,
					QM.Title,
					QM.Remark,
					CONVERT(VARCHAR,QM.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,QM.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,QM.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
					--CONVERT(VARCHAR(25), QM.CreatedDateTime, 100) AS CreatedDateTime,
					QM.StatusId,
					ISNULL(sm.Title,'') AS StatusMaster,
					QM.IsAssigneeView,
					QM.IsUserView,
					QM.CreatedUserId AS QueryCreatedUserId,
					ISNULL(QM.Number,0) AS QueryNumber
		  FROM 
					sCommunication.tQuery QM
				INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
				INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
		  WHERE 
					QM.OrgGroupBatchId=@rOrgGroupBatchId
				AND QM.CreatedUserId=@rCreatedUserId
		
				order by QM.Id desc
		END
	  
	
        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryNotificationUserGet]

		@rQueryId bigint,
		@rIsQueryQueue bit = 0
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	IF(@rIsQueryQueue=0)
	BEGIN
	
	DECLARE @lQueryCategoryId int
	
	SELECT @lQueryCategoryId = QueryCategoryId FROM sCommunication.tQuery Q WHERE Q.Id=@rQueryId
	
	SELECT 
		U.Id AS UserId,
		U.SourceId,
		U.SourceTypeId
	FROM sCommunication.tQueryCategoryAssignedTo QC 
		INNER JOIN  sSecurity.tUser U ON U.SourceId=QC.SourceId AND U.SourceTypeId=QC.SourceTypeId
		WHERE QC.QueryCategoryId=@lQueryCategoryId
	
	END
	ELSE
	BEGIN
	
	SELECT
		U.Id AS UserId,
		U.SourceId,
		U.SourceTypeId
	FROM  sCommunication.tQuery Q 
		  INNER JOIN sSecurity.tUser U ON Q.CreatedUserId=U.Id 
			WHERE Q.Id=@rQueryId
	
	END
	
	
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sCommunication].[pQueryQueueGet]
	 
	 @rQueryCategoryId int = 0,
	 --@rCreatedUserId bigint,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint,
	 @rQueryId bigint,
	 @rUserSourceId bigint,
	 @rMyList bit,
	 @rStatusId int = 0,
	 @rSourceId bigint = 0,
	 @rSubjectId int = 0,
	 @rFromDate date ='',
	 @rToDate date =''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
IF(@rMyList=0)
BEGIN
	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code AS Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
        
	WHERE 
  
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId) 
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND ((EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		AND ISNULL(EM.IsOtherUser,0) = 0
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			
	FROM 
			sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		
		
	
		UNION
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND SA.IsActiveBatch = 1 --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		    AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		
		UNION
		
		
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 AND ISNULL(EM.IsOtherUser,0) = 0
	 AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
	 AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
	 ORDER BY QM.CreatedDateTime DESC
	 --and QM.FromSourceTypeId=95
		
		
END
ELSE IF(@rMyList=1)
BEGIN

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId)
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    --AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND (( EJD.EmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		AND ISNULL(EM.IsOtherUser,0) = 0
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId AND SourceTypeId <> 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
					AND SA.DivisionId IN (SELECT Id FROM sSetup.tDivisionMaster WHERE InchargeEmployeeId=@rUserSourceId)
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId			
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 24 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		
		
		UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND SA.IsActiveBatch = 1 --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		    AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
		
   UNION
    
    
    
    
    
    SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId AND U.SourceTypeId = 95
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId AND SA.IsActiveBatch = 1
        INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = SA.DivisionId AND (( TSD.EmployeeId = @rUserSourceId) OR (@rUserSourceId=0)) AND QM.SubjectId= TSD.SubjectId                  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
        
  WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((TSD.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			--AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId      
			AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
		    AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
	 
	 UNION
    
    SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 	
		
		sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 AND ISNULL(EM.IsOtherUser,0) = 0
	 AND ((CAST(QM.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(CAST(@rFromDate AS DATE),'')=''))
	 AND ((CAST(QM.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(CAST(@rToDate AS DATE),'')=''))
	 ORDER BY QM.CreatedDateTime DESC	
	 
	 
	 
	 
	 
	 
	 
		
END
END


--SELECT Q.CreatedUserId FROM sCommunication.tQueryCategoryMaster QCM INNER JOIN sCommunication.tQuery Q ON Q.QueryCategoryId = QCM.Id

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryRemarkCommentAdd]
	 
	@rOrgGroupId smallint,
	@rId AS bigint,
	@rQueryId as bigint,
	@rRemark nvarchar(1000),
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rIsUserView bit
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 		
BEGIN TRANSACTION
IF(@rId = 0)
DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQueryComment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
    BEGIN
	
	INSERT INTO sCommunication.tQueryComment
		(
			Id,
			QueryId,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rQueryId,
			@rRemark,
		    @rCreatedUserId,
			sCommon.fGetDate()
		)
		   
	END	
	--queue
	if(@rIsUserView = 1) 
	UPDATE sCommunication.tQuery SET IsAssigneeView = 0 WHERE Id = @rQueryId
	else	 
	UPDATE sCommunication.tQuery SET  IsUserView = 0 WHERE Id = @rQueryId
	 
	Select @lNextNumber AS Result
	COMMIT TRANSACTION
END TRY
	
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pQueryStatusUpdate]
	 
	@rQueryId bigint,
	@rStatusId tinyint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
		UPDATE sCommunication.tQuery SET StatusId=@rStatusId WHERE Id=@rQueryId
		SELECT 1 Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pRegisteredUsersAdd]
	 
        @rOrgId int,
        @rUserId bigint,
        @rUserSourceId bigint,
        @rUserSourceTypeId smallint,
        @rDeviceToken nvarchar(200),
        @rOSTypeId tinyint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	DECLARE @lIsLogEnable bit = 0

	IF(@lIsLogEnable = 1)
	BEGIN
		INSERT INTO [sSystem].[tTraceLog]
		(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
		VALUES
		('sCommunication.pRegisteredUsersAdd Start', 
		'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
		+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', DeviceToken : ' +  CAST(@rDeviceToken AS nvarchar(100)), 
		'', '', GETDATE(), 'sCommunication.pRegisteredUsersAdd')
	END
	
	DECLARE @lOrgGroupId int =0 
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WITH (NOLOCK) WHERE Id = @rOrgId
	
	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 374 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId

	 IF @lConfigValue IS NULL 
		SET @lConfigValue = 'False'
	
	 IF @lConfigValue = 'True'
	 BEGIN
		DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId
	 END
	
	
	IF EXISTS(SELECT 1 FROM sCommunication.tRegisteredUsers WITH (NOLOCK)
	WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId 
	AND UserSourceTypeId = @rUserSourceTypeId AND DeviceToken=@rDeviceToken 
	AND OSTypeId = @rOSTypeId)
	BEGIN
		SELECT 1 AS Result
		RETURN
	END

	IF EXISTS(SELECT 1 FROM sCommunication.tRegisteredUsers WITH (NOLOCK) WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId 
	AND UserSourceTypeId = @rUserSourceTypeId AND DeviceToken <> '' AND DeviceToken IS NOT NULL)
	BEGIN
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 468 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
		IF @lConfigValue IS NULL   
			SET @lConfigValue = 'False'  
		IF @lConfigValue = 'True'  
		BEGIN  
			SELECT -101 AS Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	

	INSERT INTO sCommunication.tRegisteredUsers WITH (ROWLOCK)
		(
			OrgId,
			UserId,
			UserSourceId,
			UserSourceTypeId,
			DeviceToken,
			OSTypeId,
			CreatedDateTime
		)
	VALUES
		(
			@rOrgId,
			@rUserId,
			@rUserSourceId,
			@rUserSourceTypeId,
			@rDeviceToken,
			@rOSTypeId,
			sCommon.fGetDate()
		)
	
	SELECT 1 AS Result

	COMMIT TRANSACTION		

	IF(@lIsLogEnable = 1)
	BEGIN
		INSERT INTO [sSystem].[tTraceLog]
		(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
		VALUES
		('sCommunication.pRegisteredUsersAdd End', 
		'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
		+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', DeviceToken : ' +  CAST(@rDeviceToken AS nvarchar(100)), 
		'', '', GETDATE(), 'sCommunication.pRegisteredUsersAdd')
	END

	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		IF(@lIsLogEnable = 1)
		BEGIN
			INSERT INTO [sSystem].[tTraceLog]
			(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
			VALUES
			('sCommunication.pRegisteredUsersAdd Error', 
			'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
			+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', DeviceToken : ' +  CAST(@rDeviceToken AS nvarchar(100)), 
			ERROR_MESSAGE(), '', GETDATE(), 'sCommunication.pRegisteredUsersAdd')
		END
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pRegisteredUsersDelete]

	 @rDeviceToken nvarchar(200),
	 @rUserId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	BEGIN TRY
			DELETE FROM sCommunication.tRegisteredUsers WHERE DeviceToken=@rDeviceToken AND UserId=@rUserId
			SELECT 1 AS RESULT
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pRegisteredUsersGet]

		@rSourceTypeId smallint = 0,
		@rSourceId bigint = 0,
		@rOSTypeId tinyint = 0,
		@rUserSourceTypeId smallint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 		ISNULL(DeviceToken,'') AS DeviceToken
	FROM 
		sCommunication.tRegisteredUsers RU 
		INNER JOIN sStudent.tAcademic SA ON RU.UserSourceId = SA.StudentId AND RU.UserSourceTypeId=2003 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND BM.IsActive=1		
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId AND ISNULL(SC.IsBlockAllAlert,0) = 0
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId -- For House
		LEFT JOIN sHostel.tHostelAdmission HA ON HA.SourceId = SA.StudentId AND HA.SourceTypeId=2003 AND BM.OrgGroupBatchId = HA.OrgGroupBatchId  -- For Hostel
	WHERE 
		(
		(SA.Id=@rSourceId) AND (@rSourceTypeId=2001)
		OR (SA.StudentId=@rSourceId) AND (@rSourceTypeId=2003)
		OR (SA.DivisionId=@rSourceId) AND (@rSourceTypeId=2005)
		OR (SA.ClassId=@rSourceId) AND (@rSourceTypeId=2016)
		OR (CM.DepartmentId=@rSourceId) AND (@rSourceTypeId=2017)
		OR (SA.OrgId=@rSourceId) AND (@rSourceTypeId=2021)	
		OR (HA.Hosteld=@rSourceId) AND (@rSourceTypeId=2014) -- For Hostel
		OR (SO.HouseId=@rSourceId) AND (@rSourceTypeId=2029) -- For House	
		) 
		AND RU.OSTypeId=@rOSTypeId AND RU.DeviceToken	IS NOT NULL AND RU.DeviceToken != '' 	
		AND ((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))
		AND CHARINDEX(':', DeviceToken) > 0 --(Add condition for remove old Device token for ios)
	UNION ALL		
		
	SELECT 			ISNULL(DeviceToken,'') AS DeviceToken
	FROM 
		sCommunication.tRegisteredUsers RU
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON RU.UserSourceId = EJD.EmployeeId AND RU.UserSourceTypeId=95
	WHERE 
		(
		(EJD.EmployeeId=@rSourceId) AND (@rSourceTypeId=95)
		OR (EJD.OrganizationDepartmentId=@rSourceId) AND (@rSourceTypeId=2017)
		OR (EJD.OrgId=@rSourceId) AND (@rSourceTypeId=2021)	
		) AND RU.OSTypeId=@rOSTypeId AND RU.DeviceToken	IS NOT NULL AND RU.DeviceToken != '' 
		AND ((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))
		AND CHARINDEX(':', DeviceToken) > 0		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pResultSheetUploadResultAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rExamDate date,
		@rDivisionId int,
		@rIsObsolete bit,
		@rBatchId int,
		@rOrgId int,
		@rCreatedUserId bigint,
		@rExamId int=null,
		@rUploadTypeId int = 1
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tUploadResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tUploadResult
		(
			Id,
			Title,
			ExamDate,
			DivisionId,
			IsObsolete,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			ExamId,
			UploadTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rExamDate,
			@rDivisionId,
			@rIsObsolete, 
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rExamId ,
			@rUploadTypeId
		)
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tUploadResult
	    SET
			Title=@rTitle,
			ExamDate=@rExamDate,
			DivisionId=@rDivisionId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ExamId= @rExamId,
			UploadTypeId = @rUploadTypeId
	      WHERE Id = @rId
	 END  	
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pRptFeedbackAnalysistReport]
	  @rOrgGroupBatchId bigint = 0,
	  @rFeedbackId bigint = 0 ,
	  @rFeedbackForId bigint = 0,
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='',
	  @rReportId int = 0	
	-- @rUserSourceId bigint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
DECLARE @lFeedBackTemplateId bigint
DECLARE @lMaxFeedBackPoint Decimal(10,2)
DECLARE @lSourceTypeId int
select @lFeedBackTemplateId = FeedbackTemplateId from sCommunication.tFeedback F WHERE F.Id = @rFeedbackId
--SELECT * FROM sCommunication.tFeedbackFor WHERE Id= @lSourceTypeId

SELECT  @lMaxFeedBackPoint = ISNULL(MAX(FeedbackPoint),0) FROM sCommunication.tFeedbackTemplateQuestion TQ
INNER  JOIN sCommunication.tFeedbackAnswerTypeMaster FAT ON FAT.Id = TQ.FeedbackAnswerTypeId 
INNER JOIN  sCommunication.tFeedbackAnswerTypeDetail FATD ON FAT.Id = FATD.FeedbackAnswerTypeId
 WHERE TQ.FeedbackTemplateId = @lFeedBackTemplateId

 IF(@rReportId = 30927)
 BEGIN
	SELECT	
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		FQ.Id As TempateQuestionId,
		FQ.QuestionNumber,
		FQ.Question ,
		FQ.FeedbackAnswerTypeID,			 
		ISNULL(FQR. FeedbackAnswerTypeDetailId,0) AS FeedbackAnswerTypeDetailId,
		FR.SourceId ,
		 
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FATD.FeedbackPoint,
		@lMaxFeedBackPoint AS FeedbackPointMax
					
					
		from sCommunication.tFeedback FB 
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id 
		INNER JOIN	sCommunication.tFeedbackTemplateQuestion FQ ON FQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id 
		AND FQR.FeedbackTemplateQuestionID = FQ.Id
		INNER JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
		INNER JOIN sCommunication.tFeedbackAnswerTypeMaster FAT ON FAT.Id=FATD.FeedbackAnswerTypeId
		
		--AND FQR.FeedBackResponseId = 1001000000001
		--LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FA ON FA.ID=FQR.FeedbackAnswerTypeDetailId
		WHERE ((FB.Id = @rFeedbackId) OR (@rFeedbackId = 0))
			  AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0)) 
		      ANd ((OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 END
 ELSE
 BEGIN
	SELECT	
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		FQ.Id As TempateQuestionId,
		FQ.QuestionNumber,
		FQ.Question ,
		FQ.FeedbackAnswerTypeID,			 
		ISNULL(FQR. FeedbackAnswerTypeDetailId,0) AS FeedbackAnswerTypeDetailId,
		FR.SourceId ,
		 
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FATD.FeedbackPoint,
		@lMaxFeedBackPoint AS FeedbackPointMax
					
					
		from sCommunication.tFeedback FB 
		INNER JOIN	sCommunication.tFeedbackTemplateQuestion FQ ON FQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0)) 
		INNER Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id 
		AND FQR.FeedbackTemplateQuestionID = FQ.Id
		INNER JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
		INNER JOIN sCommunication.tFeedbackAnswerTypeMaster FAT ON FAT.Id=FATD.FeedbackAnswerTypeId
		
		--AND FQR.FeedBackResponseId = 1001000000001
		--LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FA ON FA.ID=FQR.FeedbackAnswerTypeDetailId
		--WHERE ((FB.Id = @rFeedbackId) OR (@rFeedbackForId = 0))--Commented by dhananjay for mantis : 40830
		WHERE ((FB.Id = @rFeedbackId) OR (@rFeedbackId = 0)) --Added by dhananjay for mantis : 40830
		 ANd ((OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 END
		
	  
		 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pRptFeedbackAnswerReviewReport]
	  @rOrgGroupBatchId bigint = 0,
	  @rFeedbackId bigint = 0 ,
	  @rFeedbackForId bigint = 0,
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='',
	  @rSourceType nvarchar(20) ='',
	   @rOrgId int =0,
	  @rBatchId int =0
	-- @rUserSourceId bigint=0
	

	 
AS
BEGIN 
 
IF(@rSourceType='Student')
BEGIN
	SELECT @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, OM.DisplayTitle  AS Title,SA.AcademicId AS SourceId,SA.Name AS Name,FBTQ.Question As Question
		,SA.Code AS Code,ISNULL(CM.Title,'') As Class, ISNULL(GM.Title,'') AS Gender,
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id,
		ISNULL(FR.CreatedDateTime,'') AS ResponseDateTime
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id-- AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FBA.AssignToSourceId
		INNER JOIN sCommon.tGenderMaster Gm ON Gm.Id=SA.GenderId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id   AND FR.SourceId = SA.AcademicId AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0))
		LEFT Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId =2001)
	AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
	AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
	Order By FBTQ.QuestionNumber Asc
END

ELSE IF(@rSourceType='Employee')
BEGIN
	SELECT @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,OM.DisplayTitle  AS Title,EM.Id AS SourceId,EM.FirstName+' '+EM.LastName  AS Name
		,FBTQ.Question As Question,EM.Code AS Code,'' AS Class,ISNULL(GM.Title,'') AS Gender,
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id,
		ISNULL(FR.CreatedDateTime,'') AS ResponseDateTime
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id --AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = FBA.AssignToSourceId
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id  AND FR.SourceId = EM.Id AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0))
		LEFT Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId =95)
		AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		--AND((SA.BatchId = @rBatchId)OR(@rBatchId=0))
		AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
		AND  ISNULL(EM.IsOtherUser,0) = 0
	Order By FBTQ.QuestionNumber Asc
END

IF(@rSourceType='Other')
BEGIN
	
	
	SELECT  @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,''  AS Title,0 AS SourceId,FBA.ForName  AS Name,FBTQ.Question As Question,'' Code,'' AS Class,'' AS Gender,
	case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id,
		ISNULL(FR.CreatedDateTime,'') AS ResponseDateTime
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id --AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0)) 
		LEFT Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId =0)
	AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
	Order By FBTQ.QuestionNumber Asc
END 

ELSE IF(@rSourceType='-ALL-')
BEGIN
	SELECT *
	FROM(
	SELECT @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, OM.DisplayTitle  AS Title,SA.AcademicId AS SourceId,SA.Name AS Name,FBTQ.Question As Question,SA.Code AS Code,
		ISNULL(CM.Title,'') As Class, ISNULL(GM.Title,'') AS Gender,
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id,
		ISNULL(FR.CreatedDateTime,'') AS ResponseDateTime
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id --AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FBA.AssignToSourceId
		INNER JOIN sCommon.tGenderMaster Gm ON Gm.Id=SA.GenderId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND FR.SourceId = SA.AcademicId AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0))
		LEFT Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId =2001)
	AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
	AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
	
UNION ALL

	SELECT @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,OM.DisplayTitle  AS Title,EM.Id AS SourceId,EM.FirstName+' '+EM.LastName  AS Name,FBTQ.Question As Question,EM.Code AS Code,
		'' AS Class,ISNULL(GM.Title,'') AS Gender,
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id,
		ISNULL(FR.CreatedDateTime,'') AS ResponseDateTime
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id --AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = FBA.AssignToSourceId
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND FR.SourceId = EM.Id AND ((FR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		LEFT Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId =95)
		AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		--AND((SA.BatchId = @rBatchId)OR(@rBatchId=0))
		AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
		AND  ISNULL(EM.IsOtherUser,0) = 0

UNION ALL 

	SELECT  @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,''  AS Title,0 AS SourceId,FBA.ForName  AS Name,FBTQ.Question As Question,'' Code, '' AS Class,'' As Gender,
	case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id,
		ISNULL(FR.CreatedDateTime,'') AS ResponseDateTime
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id --AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0)) 
		LEFT JOIN sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId = 0)
	AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
	) as a
	Order By a.QuestionNumber Asc
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pRptPollAnalysisGet]
@rPollId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT 
		PR.PollId,
		PR.CreatedUserId,
		PR.CreatedDateTime,
		U.DisplayTitle,
		CASE WHEN U.SourceTypeId = 95 THEN 'Employee' ELSE 'Student' END AS [Source],
		P.Title AS Poll,
		CASE WHEN U.SourceTypeId = 95 THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id = U.SourceId) ELSE (SELECT Code FROM sStudent.tStudentMaster WHERE Id = U.SourceId) END AS Code,
		PA.Title AS PollAnswer,
		CASE WHEN U.SourceTypeId = 95 THEN ISNULL(EC.MobileNumber,'') ELSE ISNULL(SC.StudentContactNo,'') END AS ContactNo	--Mantis 40947
	FROM 
		sCommunication.tPollResult PR
		INNER JOIN sSecurity.tUser U ON U.Id = PR.CreatedUserId
		INNER JOIN sCommunication.tPoll P ON P.Id = PR.PollId		
		INNER JOIN sCommunication.tPollAnswer PA ON PA.Id = PR.PollAnswerId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = U.SourceId AND U.SourceTypeId = 2003	--Mantis 40947
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = U.SourceId AND U.SourceTypeId = 95	--Mantis 40947
	WHERE
		PR.PollId = @rPollId AND P.IsOpen = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pSearchChatUserGet]
	 
	 
	@rOrgId int,
	@rCode nvarchar(20),
	@rName nvarchar(100)='',
	@rClassId bigint = 0,
	@rDivisionId bigint = 0,
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rUserId bigint=0,
	@rSourceTypeId int,
	@rOrgGroupId int = 0,
	@rPageIndex int = null
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rName = sCommon.fSearchStringGet(@rName)

		DECLARE @Sql nvarchar(MAX)
		declare @lTotalRecords int,@lPageSize int = 10,@lResult nvarchar(max) = '',@lPaging nvarchar(max) = ''

	IF(@rSourceTypeId = 2003)
		BEGIN
		    SELECT * INTO #TmpUser
			FROM
			(
			SELECT 
						SA.AcademicId,
						SA.StudentId,
						SA.FirstName,
						SA.MiddleName,
						SA.LastName,
						SA.Name,
						SA.Code,
						SA.ClassId,
						SA.ClassName,
						SA.DivisionName,
						SA.DivisionOrder
			  FROM 
						sStudent.vStudentAcademic SA
			  WHERE 
						((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
						AND((SA.FirstName like @rName) OR (ISNULL(@rName,'') = '')) 
						AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
						AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
						AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
						AND (OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
						AND(SA.BatchId=@rBatchId or @rBatchId = 0)
						AND SA.StatusId = 1
						AND SA.StudentId <> (SELECT SourceId FROM sSecurity.tUser WHERE Id = @rUserId)
			) as T

			create table #STUDENTTEMP
			(
				tid int identity(1,1),t_StudentId bigint
			)
			select @Sql = 'insert into #STUDENTTEMP
			SELECT StudentId FROM #TmpUser Order By DivisionOrder'

			exec (@Sql)

			select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
			
	
			select @lTotalRecords = COUNT(*) FROM #STUDENTTEMP
			select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
			select @lResult = @lResult + '<tr><td><a style="cursor:pointer;color:Blue;" onclick="SelectStudent(' + convert(varchar,AcademicId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
			<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
			<td>' + isnull(ClassName,'') + '-' + isnull(DivisionName,'') + '</td></tr>'	
			from #TmpUser,#STUDENTTEMP
			where t_StudentId = StudentId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
			order by tid
	
			select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords

		END
	ELSE IF(@rSourceTypeId = 95)
		BEGIN
		    SELECT * INTO #TmpUserEmp
			FROM
			(
			SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				EM.Number
			FROM 
					sHrm.tEmployeeMaster EM
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			WHERE 
					((EM.OrgId = @rOrgId) OR (@rOrgId=0))
				AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((EM.Code Like @rCode + '%') OR (@rCode = ''))
				AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 
				AND EM.Id <> (SELECT SourceId FROM sSecurity.tUser WHERE Id = @rUserId)			 
			) as T

			create table #EmployeeTEMP
			(
				tid int identity(1,1),t_EmployeeId bigint
			)
			select @Sql = 'insert into #EmployeeTEMP
			SELECT EmployeeId FROM #TmpUserEmp Order By Number'

			exec (@Sql)

			select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
			
	
			select @lTotalRecords = COUNT(*) FROM #EmployeeTEMP
			select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
			select @lResult = @lResult + '<tr><td><a style="cursor:pointer;color:Blue;" onclick="SelectStudent(' + convert(varchar,EmployeeId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
			<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td></tr>'	
			from #TmpUserEmp,#EmployeeTEMP
			where t_EmployeeId = EmployeeId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
			order by tid
	
			select @lResult as EmployeeList,@lPaging as Paging,@lTotalRecords as TotalRecords
		END     
   END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

CREATE OR ALTER PROCEDURE [sCommunication].[pStudentDocumentUploadAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rDocumentUploadDate date,
		@rDivisionId int,
		@rIsObsolete bit,
		@rBatchId int,
		@rOrgId int,
		@rCreatedUserId bigint,
		@rStudentDocumentType int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sCommunication.tStudentDocumentUpload where Title=@rTitle AND DivisionId=@rDivisionId
		 AND BatchId=@rBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sCommunication.tStudentDocumentUpload where Title=@rTitle AND DivisionId=@rDivisionId 
		AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tStudentDocumentUpload', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tStudentDocumentUpload
		(
			Id,
			Title,
			DocumentUploadDate,
			DivisionId,
			IsObsolete,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			StudentDocumentTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rDocumentUploadDate,
			@rDivisionId,
			@rIsObsolete, 
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rStudentDocumentType 
		)
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tStudentDocumentUpload
	    SET
			Title=@rTitle,
			DocumentUploadDate=@rDocumentUploadDate,
			DivisionId=@rDivisionId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			StudentDocumentTypeId=@rStudentDocumentType
	      WHERE Id = @rId
	 END  	
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pStudentPresenceGet]	 	 
	   @rUserSourceId bigint,
	   @rBatchId int,
	   @rMonth int=0,
	   @rYear int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 IF @rUserSourceId <> 0
 Begin	
	Select 
		MR.AcademicId,
		ForMonth,
		DATENAME(m,STR(ForMonth) + '/1/2014') + '-' + Convert(NVarchar(5),ForYear) AS ForMonthInWord,
		ForYear,
		TotalCount,
		PresentCount,
		AbsentCount,
		ISNULL(AveragePresence,0) AS AveragePresence,
		AbsentDays		
	From 
		sAttendance.tMonthlyRegister MR  INNER JOIN sStudent.tAcademic SA 
		ON SA.Id = MR.AcademicId AND (SA.StudentId  = @rUserSourceId)
		INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON
		MR.ForMonth = MY.MonthNumber AND MR.ForYear = MY.YearNumber
		Where MR.ForMonth = @rMonth AND MR.ForYear=@rYear and SA.BatchId = @rBatchId
	ORDER BY
	MR.AcademicId
	 ,MY.YearNumber ,MY.MonthNumber
END
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pStudentResultGet]
	 
	 @rSourceId bigint,
	 @rDivisionId int,
	 @rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF (@rSourceId!=0)
	BEGIN
		SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
		 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	END
		SELECT 
			@rSourceId AS SourceId,
			UR.Id,
			UR.Title,
			UR.ExamDate,
			S.Code ,
			BM.OrgId
			 
		FROM 
			sCommunication.tUploadResult UR  
			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = UR.DivisionId AND UR.BatchId = S.BatchId 
			AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
		WHERE 
			UR.DivisionId=@rDivisionId
			AND UR.BatchId=@rBatchId
			AND UR.IsObsolete=0
			AND ( UR.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
			and UR.ExamDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
			AND ISNULL(UR.UploadTypeId,1) = 1
				order by UR.ExamDate,S.RollNo,S.Code DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pStudentUploadedDocumentGet]
	 @rId int = 0,
	 @rTitle nvarchar(100) = '',
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rDivisionId int = '',
	 @rBatchId int = '',
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			SDU.Id,
			SDU.Title,
			SDU.StudentDocumentTypeId,
			SDU.DocumentUploadDate,
			SDU.DivisionId,
			BCD.ClassDivisionName AS Division,
			SDU.IsObsolete
  FROM 
            sCommunication.tStudentDocumentUpload SDU
        INNER JOIN sSetup.vBatchClassDivision BCD ON BCD.DivisionId=SDU.DivisionId AND BCD.BatchId=@rBatchId
  WHERE 
		((SDU.Id = @rId) OR (@rId = 0))
	AND ((SDU.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((SDU.DocumentUploadDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((SDU.DocumentUploadDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((SDU.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((SDU.BatchId=@rBatchId) OR (@rBatchId=0))
	order by SDU.DocumentUploadDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pStudentUploadedDocumentListGet]
	 
	 @rSourceId bigint,
	 @rDivisionId int = 0,
	 @rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF (@rSourceId!=0)
	BEGIN
		SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
		 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	END
		--SELECT 
		--	@rSourceId AS SourceId,
		--	SDU.Id,
		--	SDU.Title,
		--	SDTM.Title AS DocumentType,
		--	S.Code,
		--	SDU.DocumentUploadDate,
		--	BM.OrgId,
		--	S.RollNo
		--FROM 
		--	sCommunication.tStudentDocumentUpload SDU  
		--	INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = SDU.DivisionId AND SDU.BatchId = S.BatchId 
		--	AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
		--	INNER JOIN sCommunication.tStudentDocumentTypeMaster SDTM ON SDTM.Id = SDU.StudentDocumentTypeId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
		--WHERE 
		--	SDU.DivisionId=@rDivisionId
		--	AND SDU.BatchId=@rBatchId
		--	AND SDU.IsObsolete=0
		--	AND ( SDU.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
		
		--	and SDU.DocumentUploadDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
		--		--order by SDU.DocumentUploadDate,S.RollNo,S.Code DESC

		--UNION

		SELECT 
			@rSourceId AS SourceId,
			SDU.Id,
			SDU.Title,
			PDM.Title AS DocumentType,
			S.Code,
			SDU.DocumentUploadDate,
			BM.OrgId,
			S.RollNo
		FROM 
			sCommunication.tStudentDocumentUpload SDU  
			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = SDU.DivisionId AND SDU.BatchId = S.BatchId 
			AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
			INNER JOIN sCommon.tPublishDocumentMaster PDM ON PDM.Id = SDU.StudentDocumentTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
		WHERE 
			SDU.DivisionId=@rDivisionId
			AND SDU.BatchId=@rBatchId
			AND SDU.IsObsolete=0
			AND ( SDU.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
		
			and SDU.DocumentUploadDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
		    order by SDU.DocumentUploadDate,S.RollNo,S.Code DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pTempChatGroupScopeAdd]
			@rTempChatGroupMasterId NVARCHAR(MAX)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
            ,@rIsDeleted bit
           	,@rIsAssigneeToId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tTempChatGroupScope where TempChatGroupId=@rTempChatGroupMasterId AND MemberSourceTypeId=@rSourceTypeId AND AssigneeToId= @rIsAssigneeToId
AND MemberSourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select TempChatGroupId from sCommunication.tTempChatGroupScope where TempChatGroupId=@rTempChatGroupMasterId AND MemberSourceTypeId=@rSourceTypeId
	AND MemberSourceId=@rSourceId AND AssigneeToId= @rIsAssigneeToId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tTempChatGroupScope
			(
				TempChatGroupId
			   ,MemberSourceTypeId
			   ,MemberSourceId
			   ,AssigneeToId
			)
			VALUES
			(	
				@rTempChatGroupMasterId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,@rIsAssigneeToId
			)		
			SELECT 1 AS Result
		 
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pTempChatGroupScopeGet]
	 @rTempChatGroupMasterId nvarchar(100)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId ,
             AM.Title As AssignedTo

			FROM sCommunication.tTempChatGroupScope LS
			INNER JOIN sSetup.tOrganizationMaster OM ON LS.MemberSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2021

			UNION ALL

			SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId  as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId,
             AM.Title As AssignedTo 

			FROM sCommunication.tTempChatGroupScope LS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON LS.MemberSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2017

			UNION ALL

			SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tTempChatGroupScope LS
			INNER JOIN  sSetup.tClassMaster CM
				ON LS.MemberSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2016

			UNION ALL

			SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 --DM.DisplayTitle AS Source,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tTempChatGroupScope LS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON LS.MemberSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId		
			WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2005


			UNION ALL
			
			SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId,
             AM.Title As AssignedTo 
			 
			FROM sCommunication.tTempChatGroupScope LS
		    INNER JOIN sStudent.tStudentMaster SM
				ON LS.MemberSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON LS.MemberSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			 WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId ,
             AM.Title As AssignedTo

			FROM  sCommunication.tTempChatGroupScope LS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON LS.MemberSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			 LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			 WHERE LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=2001
			 
			 UNION ALL
			 SELECT
			
			 LS.TempChatGroupId,
			 LS.MemberSourceTypeId as SourceTypeId,
			 LS.MemberSourceId as SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			  LS.AssigneeToId,
             AM.Title As AssignedTo  

			FROM sCommunication.tTempChatGroupScope LS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON LS.MemberSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = LS.AssigneeToId
			 WHERE 
			LS.TempChatGroupId=@rTempChatGroupMasterId AND LS.MemberSourceTypeId=95

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sCommunication].[pTempChatGroupScopeRemove]
			
			@rTempChatGroupMasterId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rAssigneeToId tinyint
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	Delete from sCommunication.tTempChatGroupScope where TempChatGroupId=@rTempChatGroupMasterId AND MemberSourceTypeId=@rSourceTypeId And AssigneeToId=@rAssigneeToId
      AND MemberSourceId=@rSourceId
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pTempChatGroupScopeValidate]
	 
        @rTempChatGroupMasterId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS where CS.MemberSourceId=@rSourceId AND
					CS.MemberSourceTypeId=@rSourceTypeId AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.MemberSourceId=DM.Id AND CS.MemberSourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.MemberSourceId=CM.Id AND CS.MemberSourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.MemberSourceId=DM.Id AND CS.MemberSourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.MemberSourceId=SM.Id AND CS.MemberSourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.MemberSourceId=DM.OrgId AND CS.MemberSourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.MemberSourceId=CM.Id AND CS.MemberSourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.MemberSourceId=DM.Id AND CS.MemberSourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.StudentId AND CS.MemberSourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 			
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.MemberSourceId=CM.OrgId AND CS.MemberSourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.MemberSourceId=CM.DepartmentId AND CS.MemberSourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.MemberSourceId=DM.Id AND CS.MemberSourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.StudentId AND CS.MemberSourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.MemberSourceId=DM.OrgId AND CS.MemberSourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.MemberSourceId=CM.DepartmentId AND CS.MemberSourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.MemberSourceId=DM.ClassId AND CS.MemberSourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.StudentId AND CS.MemberSourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.DivisionId AND CS.MemberSourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.MemberSourceId=SM.OrgId AND CS.MemberSourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.MemberSourceId=CM.DepartmentId AND CS.MemberSourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.ClassId AND CS.MemberSourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.DivisionId AND CS.MemberSourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.MemberSourceId=EM.OrgId AND CS.MemberSourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempChatGroupScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.MemberSourceId=EJD.OrganizationDepartmentId AND CS.MemberSourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempChatGroupScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.MemberSourceId=SA.DivisionId AND CS.MemberSourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempChatGroupId=@rTempChatGroupMasterId AND AssigneeToId=@rAssigneeToId )
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pTempCircularAdd]
	 
        @rId bigint,
		@rTitle nvarchar(200),
		@rRemark nvarchar(max),
		@rStartDate date,
		@rCreatedUserId bigint,
        @rOrgGroupId smallint,
        @rOrgGroupBatchId int,
        @rAssigneeId tinyint,
        @rCircularTypeId int,
        @rTempCircularId nvarchar(100),
		@rPublishDateTime DateTime = '',
		@rPublishInFuture bit = 0,
		@rIsConsent bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsCircularBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsCircularBasedOnApproval = 0
	ELSE
	SET @lIsCircularBasedOnApproval = 1	
	
	Declare @StatusId smallint
	IF(@lIsCircularBasedOnApproval=0)
	SET @StatusId=550
	ELSE
	SET @StatusId=549
	
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			CircularTypeId,
			StatusId,
			PublishDateTime,
			IsPublishInFuture,
			IsConsent
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rStartDate,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rAssigneeId,
			@rCircularTypeId,
			@StatusId,
			@rPublishDateTime,
			@rPublishInFuture,
			@rIsConsent
		)
		
		SELECT @lNextNumber AS Result  
		    
		INSERT INTO sCommunication.tCircularScope
		SELECT @lNextNumber,SourceTypeId,SourceId,AssigneeToId
		FROM sCommunication.tTempCircularScope 
		WHERE TempCircularId = @rTempCircularId
		
		DELETE FROM sCommunication.tTempCircularScope WHERE TempCircularId = @rTempCircularId
		
		
	END	 

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pTempCircularScopeAdd]

			@rTempCircularId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
          ,@rIsAssigneeToId int 
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 

If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tTempCircularScope where TempCircularId=@rTempCircularId AND SourceTypeId=@rSourceTypeId AND AssigneeToId= @rIsAssigneeToId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select TempCircularId from sCommunication.tTempCircularScope where TempCircularId=@rTempCircularId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId AND AssigneeToId= @rIsAssigneeToId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tTempCircularScope
			(
				TempCircularId
			   ,SourceTypeId
			   ,SourceId
			   ,AssigneeToId
			)
			VALUES
			(	
				@rTempCircularId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,@rIsAssigneeToId
			)		
			SELECT 1 AS Result
		 
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pTempCircularScopeGet]
	 @rTempCircularId nvarchar(100)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             CS.AssigneeToId,
             AM.Title As AssignedTo
			 
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN sSetup.tOrganizationMaster OM ON CS.SourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2021

			UNION ALL

			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
			  AM.Title As AssignedTo
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2017

			UNION ALL

			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo
			 
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2016

			UNION ALL

			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 --DM.DisplayTitle AS Source,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo
			 
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo
			 
			FROM sCommunication.tTempCircularScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo
			 
			FROM sCommunication.tTempCircularScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo
			
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId		
			WHERE 
			CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=95


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pTempCircularScopeRemove]
			
			@rTempCircularId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rAssigneeToId tinyint
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	Delete from sCommunication.tTempCircularScope where TempCircularId=@rTempCircularId AND SourceTypeId=@rSourceTypeId And AssigneeToId=@rAssigneeToId
      AND SourceId=@rSourceId
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pTempCircularScopeValidate]
	 
        @rTempCircularId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempCircularScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		

			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 	
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 	
			
			If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END 
		
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pTempMultiPhotoCategoryScopeAdd]

			@rTempPhotoCategoryId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
           ,@rIsAssigneeToId int 
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 

--If(@rIsDeleted=1)
--BEGIN
--	Delete from sCommunication.tTempMultiPhotoCategoryScope where TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND SourceTypeId=@rSourceTypeId AND AssigneeToId= @rIsAssigneeToId
--AND SourceId=@rSourceId
--	Select @rSourceId as Result
--END	
--ELSE
--BEGIN 
 
	If Exists(select TempMultiPhotoCategoryId from sCommunication.tTempMultiPhotoCategoryScope where TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId AND AssigneeToId= @rIsAssigneeToId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tTempMultiPhotoCategoryScope
			(
				TempMultiPhotoCategoryId
			   ,SourceTypeId
			   ,SourceId
			   ,AssigneeToId
			)
			VALUES
			(	
				@rTempPhotoCategoryId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,@rIsAssigneeToId
			)		
			SELECT 1 AS Result
		 
	--END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pTempMultiPhotoCategoryScopeGet]
	 @rTempPhotoCategoryId nvarchar(100)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.TempMultiPhotoCategoryId AS TempPhotoCategoryId,
			 CS.SourceTypeId AS ScopeSourceTypeId,
			 CS.SourceId AS ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS ScopeSourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             CS.AssigneeToId,
             AM.Title As AssignedTo,
			 1 AS IsTempFlag
			 
			FROM sCommunication.tTempMultiPhotoCategoryScope CS
			INNER JOIN sSetup.tOrganizationMaster OM ON CS.SourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempMultiPhotoCategoryId=@rTempPhotocategoryId AND CS.SourceTypeId=2021

			UNION ALL

			SELECT
			 CS.TempMultiPhotoCategoryId AS TempPhotoCategoryId,
			 CS.SourceTypeId AS ScopeSourceTypeId,
			 CS.SourceId AS ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS ScopeSourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
			  AM.Title As AssignedTo,
			  1 AS IsTempFlag
			FROM sCommunication.tTempMultiPhotoCategoryScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempMultiPhotoCategoryId=@rTempPhotocategoryId AND CS.SourceTypeId=2017

			UNION ALL

			SELECT
			 CS.TempMultiPhotoCategoryId AS TempPhotoCategoryId,
			 CS.SourceTypeId AS ScopeSourceTypeId,
			 CS.SourceId AS ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS ScopeSourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo,
			   1 AS IsTempFlag
			 
			FROM sCommunication.tTempMultiPhotoCategoryScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempMultiPhotoCategoryId=@rTempPhotocategoryId AND CS.SourceTypeId=2016

			UNION ALL

			SELECT
			 CS.TempMultiPhotoCategoryId AS TempPhotoCategoryId,
			 CS.SourceTypeId AS ScopeSourceTypeId,
			 CS.SourceId AS ScopeSourceId,
			 --DM.DisplayTitle AS Source,
			 DM.Code AS Source,
			 'Division' AS ScopeSourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo,
			   1 AS IsTempFlag
			 
			FROM sCommunication.tTempMultiPhotoCategoryScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempMultiPhotoCategoryId=@rTempPhotocategoryId AND CS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.TempMultiPhotoCategoryId AS TempPhotoCategoryId,
			 CS.SourceTypeId AS ScopeSourceTypeId,
			 CS.SourceId AS ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS ScopeSourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo,
			   1 AS IsTempFlag
			 
			FROM sCommunication.tTempMultiPhotoCategoryScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempMultiPhotoCategoryId=@rTempPhotocategoryId AND CS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.TempMultiPhotoCategoryId AS TempPhotoCategoryId,
			 CS.SourceTypeId AS ScopeSourceTypeId,
			 CS.SourceId AS ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS ScopeSourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo,
			   1 AS IsTempFlag
			 
			FROM sCommunication.tTempMultiPhotoCategoryScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempMultiPhotoCategoryId=@rTempPhotocategoryId AND CS.SourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.TempMultiPhotoCategoryId AS TempPhotoCategoryId,
			 CS.SourceTypeId AS ScopeSourceTypeId,
			 CS.SourceId AS ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS ScopeSourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo,
			   1 AS IsTempFlag
			
			FROM sCommunication.tTempMultiPhotoCategoryScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId		
			WHERE 
			CS.TempMultiPhotoCategoryId=@rTempPhotocategoryId AND CS.SourceTypeId=95


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pTempMultiPhotoCategoryScopeRemove]
			
			@rTempPhotoCategoryId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rAssigneeToId tinyint
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	Delete from [sCommunication].[tTempMultiPhotoCategoryScope] where TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND SourceTypeId=@rSourceTypeId And AssigneeToId=@rAssigneeToId
      AND SourceId=@rSourceId
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pTempMultiPhotoCategoryScopeValidate]
	 
        @rTempPhotoCategoryId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int,
		@rPhotoCategoryId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		IF(@rPhotoCategoryId > 0)
		BEGIN
			If EXISTS(select 1 from sCommunication.tMultiPhotoCategoryScope CS where CS.ScopeSourceId=@rSourceId AND
				CS.ScopeSourceTypeId=@rSourceTypeId AND CS.MultiPhotoCategoryId=@rPhotoCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		END
	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempMultiPhotoCategoryScope CS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END
					
			If EXISTS(select 1 from sCommunication.tTempMultiPhotoCategoryScope CS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END 			
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from [sCommunication].[tTempMultiPhotoCategoryScope] CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  [sCommunication].[tTempMultiPhotoCategoryScope] CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempMultiPhotoCategoryId=@rTempPhotoCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pTempQueryCategoryScopeAdd]

			@rTempQueryCategoryId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           --,@rIsDeleted bit
           ,@rIsAssigneeToId int 
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 

--If(@rIsDeleted=1)
--BEGIN
--	Delete from sCommunication.tTempQueryCategoryScope where TempQueryCategoryId=@rTempQueryCategoryId AND SourceTypeId=@rSourceTypeId AND AssigneeToId= @rIsAssigneeToId
--    AND SourceId=@rSourceId
--	Select @rSourceId as Result
--END	
--ELSE
--BEGIN 
 
If Exists(select TempQueryCategoryId from sCommunication.tTempQueryCategoryScope where TempQueryCategoryId=@rTempQueryCategoryId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId AND AssigneeToId= @rIsAssigneeToId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	    END 
	ELSE
	BEGIN
			INSERT INTO sCommunication.tTempQueryCategoryScope
			(
				TempQueryCategoryId
			   ,SourceTypeId
			   ,SourceId
			   ,AssigneeToId
			)
			VALUES
			(	
				@rTempQueryCategoryId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,@rIsAssigneeToId
			)		
			SELECT 1 AS Result
		 
	END	
	
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pTempQueryCategoryScopeGet]
	 @rTempQueryCategoryId nvarchar(100)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.TempQueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             CS.AssigneeToId,
             AM.Title As AssignedTo,
			 1 AS IsTempFlag
			 
			FROM sCommunication.tTempQueryCategoryScope CS
			INNER JOIN sSetup.tOrganizationMaster OM ON CS.SourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempQueryCategoryId = @rTempQueryCategoryId AND CS.SourceTypeId=2021

			UNION ALL

			SELECT
			 CS.TempQueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             CS.AssigneeToId,
			 AM.Title As AssignedTo,
			 1 AS IsTempFlag

			FROM sCommunication.tTempQueryCategoryScope CS
			INNER JOIN sSetup.tDepartmentMaster DM ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempQueryCategoryId = @rTempQueryCategoryId AND CS.SourceTypeId=2017

			UNION ALL

			SELECT
			 CS.TempQueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             CS.AssigneeToId,
             AM.Title As AssignedTo,
			 1 AS IsTempFlag
			 
			FROM sCommunication.tTempQueryCategoryScope CS
			INNER JOIN  sSetup.tClassMaster CM ON CS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempQueryCategoryId = @rTempQueryCategoryId AND CS.SourceTypeId=2016

			UNION ALL

			SELECT
			 CS.TempQueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 --DM.DisplayTitle AS Source,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             CS.AssigneeToId,
             AM.Title As AssignedTo,
			 1 AS IsTempFlag
			 
			FROM sCommunication.tTempQueryCategoryScope CS
			INNER JOIN   sSetup.tDivisionMaster DM ON CS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempQueryCategoryId = @rTempQueryCategoryId AND CS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.TempQueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             CS.AssigneeToId,
             AM.Title As AssignedTo,
			 1 AS IsTempFlag
			 
			FROM sCommunication.tTempQueryCategoryScope CS
		    INNER JOIN sStudent.tStudentMaster SM ON CS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempQueryCategoryId = @rTempQueryCategoryId AND CS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.TempQueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             CS.AssigneeToId,
             AM.Title As AssignedTo,
			 1 AS IsTempFlag
			 
			FROM sCommunication.tTempQueryCategoryScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempQueryCategoryId = @rTempQueryCategoryId AND CS.SourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.TempQueryCategoryId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             CS.AssigneeToId,
             AM.Title As AssignedTo,
			 1 AS IsTempFlag
			
			FROM sCommunication.tTempQueryCategoryScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId		
			WHERE 
			CS.TempQueryCategoryId = @rTempQueryCategoryId AND CS.SourceTypeId=95


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pTempQueryCategoryScopeRemove]
			
			@rTempQueryCategoryId nvarchar(100)
		   --@rQueryCategoryId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rAssigneeToId tinyint
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
		Delete from sCommunication.tTempQueryCategoryScope where TempQueryCategoryId=@rTempQueryCategoryId AND SourceTypeId=@rSourceTypeId And AssigneeToId=@rAssigneeToId
		 AND SourceId=@rSourceId
	      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pTempQueryCategoryScopeValidate]
	 
        @rTempQueryCategoryId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int,
		@rQueryCategoryId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		-- #Start : Committed by MantisId : 0030903
		--IF(@rQueryCategoryId > 0)
		--BEGIN
		--	If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS where CS.SourceId=@rSourceId AND
		--		CS.SourceTypeId=@rSourceTypeId AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId) 
		--	BEGIN
		--		select -101 as Result,'Item Already Exists' AS Msg
		--		RETURN
		--	END 
		--END
		-- #End Committed by MantisId : 0030903
			
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
			
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 
		
		-- #Start : Committed by MantisId : 0030903		
		--IF(@rQueryCategoryId > 0)	
		--BEGIN
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		--	 INNER JOIN  sSetup.tDepartmentMaster DM 
		--		ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
		--		where DM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Department already Exists' AS Msg
		--				RETURN
		--			END 
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--	 INNER JOIN  sSetup.tClassMaster CM 
		--		ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
		--		where CM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Class already Exists' AS Msg
		--				RETURN
		--			END 
					
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--	 INNER JOIN  sSetup.tDivisionMaster DM 
		--		ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
		--		where DM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Division already Exists' AS Msg
		--				RETURN
		--			END 
					
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--	 INNER JOIN  sStudent.tStudentMaster SM
		--		ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
		--		where SM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Student already Exists' AS Msg
		--				RETURN
		--			END 

		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--			INNER JOIN  sHrm.tEmployeeMaster EM
		--		ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
		--		where EM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Employee already Exists' AS Msg
		--				RETURN
		--			END 
		--END
		-- #End Committed by MantisId : 0030903
							
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END
			
			-- #Start : Committed by MantisId : 0030903			
			--IF(@rQueryCategoryId > 0)
			--BEGIN
			--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
			--	 INNER JOIN  sSetup.tDepartmentMaster DM
			--		ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			--		where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
			--			BEGIN
			--				select -102 as Result,'Organization already Exists' AS Msg
			--				RETURN
			--			END 
			--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
			--	 INNER JOIN sSetup.tClassMaster CM
			--		ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
			--		where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
			--			BEGIN
			--				select -103 as Result,'Class already Exists' AS Msg
			--				RETURN
			--			END 
					
			--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			--	 INNER JOIN  sSetup.tDivisionMaster DM 
			--		ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			--	 INNER JOIN sSetup.tClassMaster CM
			--		ON CM.Id=DM.ClassId
			--		where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
			--			BEGIN
			--				select -103 as Result,'Division already Exists' AS Msg
			--				RETURN
			--			END 
					
			--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			--	 INNER JOIN sStudent.tAcademic SA 
			--		ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			--	 INNER JOIN sSetup.tClassMaster CM
			--		ON CM.Id=SA.ClassId
   --				 INNER JOIN sSetup.tBatchMaster BM 
   --					ON BM.Id = SA.BatchId AND BM.IsActive=1
			--		where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
			--			BEGIN
			--				select -103 as Result,'Student already Exists' AS Msg
			--				RETURN
			--			END 
			
			--If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
			--	INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			--	INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			--	where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
			--	BEGIN
			--		select -103 as Result,'Employee already Exists' AS Msg
			--		RETURN
			--	END	
			--END	
			-- #End Committed by MantisId : 0030903	
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 		
		
		-- #Start : Committed by MantisId : 0030903		
		--IF(@rQueryCategoryId > 0)
		--BEGIN	
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--	 INNER JOIN  sSetup.tClassMaster CM
		--		ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
		--		where CM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -102 as Result,'Organization already Exists' AS Msg
		--				RETURN
		--			END 
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--	 INNER JOIN  sSetup.tClassMaster CM
		--		ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		--		where CM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -102 as Result,'Department already Exists' AS Msg
		--				RETURN
		--			END 
				
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		--	 INNER JOIN  sSetup.tDivisionMaster DM 
		--		ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
		--		where DM.ClassId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Division already Exists' AS Msg
		--				RETURN
		--			END 
				
		--	If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		--	  INNER JOIN sStudent.tAcademic SA 
		--			ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		--	  INNER JOIN sSetup.tBatchMaster BM 
  -- 					ON BM.Id = SA.BatchId AND BM.IsActive=1
		--		where SA.ClassId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Student already Exists' AS Msg
		--				RETURN
		--			END 
		--END
		-- #End Committed by MantisId : 0030903
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 

		-- #Start : Committed by MantisId : 0030903
		--IF(@rQueryCategoryId > 0)
		--BEGIN
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		-- INNER JOIN  sSetup.tDivisionMaster DM 
		--	ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
		--	where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Organization already Exists' AS Msg
		--			RETURN
		--		END 
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		-- INNER JOIN sSetup.tClassMaster CM 
		--	ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		-- INNER JOIN  sSetup.tDivisionMaster DM 
		--	ON DM.ClassId=CM.Id
		--	where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Department already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN  sSetup.tDivisionMaster DM 
		--	ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
		--	where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Class already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		--  INNER JOIN sStudent.tAcademic SA 
		--		ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		--  INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.DivisionId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -103 as Result,'Student already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		--  INNER JOIN sStudent.tAcademic SA 
		--		ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		--  INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.DivisionId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -103 as Result,'Student already Exists' AS Msg
		--			RETURN
		--		END 
		--END	
		-- #End Committed by MantisId : 0030903
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
				
		-- #Start : Committed by MantisId : 0030903
		--IF(@rQueryCategoryId > 0)
		--BEGIN	

		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN  sStudent.tStudentMaster SM 
		--	ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
		--	where SM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Organization already Exists' AS Msg
		--			RETURN
		--		END 
		--If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN  sSetup.tClassMaster CM 
		--	ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		-- INNER JOIN sStudent.tAcademic SA 
		--		ON CM.Id=SA.ClassId 
		-- INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Department already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN sStudent.tAcademic SA 
		--		ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		-- INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Class already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		-- INNER JOIN sStudent.tAcademic SA 
		--		ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		-- INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Division already Exists' AS Msg
		--			RETURN
		--		END 	
		--END	
		-- #End Committed by MantisId : 0030903
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		-- #Start : Committed by MantisId : 0030903
		--IF(@rQueryCategoryId > 0)
		--BEGIN	
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN  sHrm.tEmployeeMaster EM 
		--	ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
		--	where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Organization already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN  sHrm.tEmployeeJobDetail EJD
		--	ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
		--	where  EJD.EmployeeId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Department already Exists' AS Msg
		--			RETURN
		--		END 
		--END
		-- #End Committed by MantisId : 0030903
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 
		-- #Start : Committed by MantisId : 0030903	
		--IF(@rQueryCategoryId > 0)
		--BEGIN
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		-- INNER JOIN sStudent.tAcademic SA 
		--		ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		-- INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Division already Exists' AS Msg
		--			RETURN
		--		END 	
		--END	
		-- #End Committed by MantisId : 0030903
	END
			select 1 as Result,'' AS Msg
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pUpdateQuery]
	 
	
	@rQueryId bigint,	
	@rIsUserView bit
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
		


BEGIN

if @rIsUserView = 1 
		
		UPDATE sCommunication.tQuery 
		SET IsUserView = 1		
		 WHERE Id = @rQueryId
		 
		 else
		 
		 UPDATE sCommunication.tQuery 
		SET IsAssigneeView = 1		
		 WHERE Id = @rQueryId
		 
		 
	select 11 as result
END
	

	
	
END TRY

		
	
	BEGIN CATCH
	    
		SELECT -1 AS Result
	END CATCH  
END        
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pUploadBookLogGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			UBL.BookLogId,
			UBL.BookTitle,
			UBL.IssueDate
  FROM 
            sCommunication.tUploadBookLog UBL
  WHERE 
		(UBL.ReaderSourceTypeId = @rReaderSourceTypeId)
	AND	(UBL.ReaderSourceId = @rReaderSourceId)
	AND (UBL.BatchId=@rBatchId)
	ORDER BY UBL.IssueDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sCommunication].[pUploadResultAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rExamDate date,
		@rDivisionId int,
		@rIsObsolete bit,
		@rBatchId int,
		@rOrgId int,
		@rCreatedUserId bigint,
		@rExamId int=null,
		@rUploadTypeId int = 1
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sCommunication.tUploadResult where Title=@rTitle AND DivisionId=@rDivisionId AND ISNULL(UploadTypeId,1) = @rUploadTypeId
		 AND BatchId=@rBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sCommunication.tUploadResult where Title=@rTitle AND DivisionId=@rDivisionId AND ISNULL(UploadTypeId,1) = @rUploadTypeId
		AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tUploadResult', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tUploadResult
		(
			Id,
			Title,
			ExamDate,
			DivisionId,
			IsObsolete,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			ExamId,
			UploadTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rExamDate,
			@rDivisionId,
			@rIsObsolete, 
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rExamId,
			@rUploadTypeId 
		)
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tUploadResult
	    SET
			Title=@rTitle,
			ExamDate=@rExamDate,
			DivisionId=@rDivisionId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			UploadTypeId = @rUploadTypeId
			--ExamId= @rExamId
	      WHERE Id = @rId
	 END  	
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pUploadResultGet]
	 @rId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rDivisionId int,
	 @rBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			UR.Id,
			UR.Title,
			UR.ExamDate,
			UR.DivisionId,
			BCD.ClassDivisionName AS Division,
			UR.IsObsolete,
			ISNULL(UR.UploadTypeId,1) AS UploadTypeId
  FROM 
            sCommunication.tUploadResult UR
        INNER JOIN sSetup.vBatchClassDivision BCD ON BCD.DivisionId=UR.DivisionId AND BCD.BatchId=@rBatchId
  WHERE 
		((UR.Id = @rId) OR (@rId = 0))
	AND ((UR.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((UR.ExamDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((UR.ExamDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((UR.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((UR.BatchId=@rBatchId) OR (@rBatchId=0))
	order by UR.ExamDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sCommunication].[pUserWiseQueryCategoryGet]
	 
	 @rOrgGroupBatchId int,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
	IF @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
		
		SELECT Distinct	
				QCM.Id,
				QCM.Title
			  
		 FROM 
           sCommunication.tQueryCategoryMaster QCM           
            INNER JOIN 
			(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
             WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
            (QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
            (QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))
             ) D
			ON D.QueryCategoryId= QCM.Id
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=QCM.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            --INNER JOIN sSecurity.tUser U ON U.Id=QCM.CreatedUserId
            WHERE 
            QCM.AssignedToId IN (1,3) 
			AND QCM.IsObsolete = 0
 END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 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 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
    WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
  
 	SELECT 	Distinct
			QCM.Id,
	    	QCM.Title
	 FROM 
            sCommunication.tQueryCategoryMaster QCM 
          
            INNER JOIN (SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
            WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
            (QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
            (QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
            (QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
            (QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
            (QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
            )AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D
			ON	D.QueryCategoryId= QCM.Id
            WHERE 
            QCM.AssignedToId IN (1,2) 
            AND QCM.IsObsolete = 0

 END
 ELSE
  --For Other Users
 BEGIN
 
 SELECT 	
		QCM.Id,
	    QCM.Title
			
	    FROM 
           sCommunication.tQueryCategoryMaster QCM
           WHERE 
           QCM.AssignedToId IN (1,2,3)
		   AND QCM.IsObsolete = 0
 END
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pViewMultiPhotoCategoryMaster_Get]
	 
	 @rScopeSourceId bigint=0,
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 --@rOrgGroupId smallint,
	 @rSourcetypeId smallint,
	 --@rOrgGroupBatchID int,
	 @rBatchId int,
	 @rBatchYear int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

  declare @lOrgGroupId smallint,@lOrgGroupBatchId int,@lOrgId smallint
  
  if @rSourcetypeId=2003
  BEGIN
  
	  Select @lOrgGroupId=Om.OrgGroupId,@lOrgId=OM.Id ,@lOrgGroupBatchID=BM.OrgGroupBatchId  from 
	  sSetup.tOrganizationMaster OM
	  INNER JOIN sStudent.tAcademic A ON A.OrgId=OM.Id
	  INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId
	  where A.BatchId= @rBatchId AND A.Id=@rScopeSourceId 
	  
  END
  
 else if @rSourcetypeId=95
  BEGIN
	 Select @lOrgId=OrgId From 
	 sSetup.tOrganizationMaster OM
	 INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgID=OM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	 Where Em.Id=@rScopeSourceId

	 Select @lOrgGroupBatchID = OrgGroupBatchId from sSetup.tBatchMaster Where Id = @rBatchId
  END
  else
  BEGIN
	Select @lOrgGroupId=OM.OrgGRoupId ,@lOrgGroupBatchID=BM.OrgGroupBatchId  from sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	Where Bm.Id=@rBatchId
  END
 
 --Select   @lOrgGroupId ,@lOrgGroupBatchId ,@lOrgId 
  if @rSourcetypeId=2003
  BEGIN
		
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
         -- ISNULL(PCS.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
          ISNULL(Remark,'') AS Remark,
		  PCM.CreatedDateTime,
		  ISNULL(PCM.OrgGroupBatchId,0)AS OrgGroupBatchId
		            
  from [sCommunication].[tMultiPhotoCategoryMaster] PCM 
	INNER join sCommunication.tMultiPhotoCategoryScope PCS  ON PCM.Id = PCS.MultiPhotoCategoryId AND
	(PCS.ScopeSourceId = Case  When PCS.ScopeSourceTypeId = 2005 Then
	(Select DivisionId From sStudent.tAcademic Where DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
	When PCS.ScopeSourceTypeId = 2016 Then
    (Select ClassId From sStudent.tAcademic Where ClassId = PCS.ScopeSourceId And Id = @rScopeSourceId)
	when PCS.ScopeSourceTypeId = 2017 Then
	(select D.Id from sSetup.tDepartmentMaster D INNER JOIN sSetup.tClassMaster CA ON CA.DepartmentId=D.Id 
	INNER JOIN sStudent.tAcademic A ON A.ClassID=CA.Id Where A.Id =@rScopeSourceId)
	When PCS.ScopeSourceTypeId =2021 Then
	(Select OM.Id from sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId =OM.Id Where A.Id=@rScopeSourceId)
	When PCS.ScopeSourceTypeId =2014 Then
	(Select Hm.Id from sHostel.tHostelMaster Hm INNER JOIN  sHostel.tRoomMaster RA ON RA.HostelId=HM.Id 
	INNER JOIN sHostel.tAssignRoom AR ON AR.RoomId=RA.Id
	INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId 
	Where AR.OrgGroupBatchId = @lOrgGroupBatchID AND HM.OrgGroupId=@lOrgGroupId AND A.Id=@rScopeSourceId)
	When PCS.ScopeSourceTypeId =2029 Then
	(select HO.Id from sActivity.tHouseMaster HO
	INNER JOIN sStudent.tStudentOther SO ON SO.HouseId=HO.Id 
	INNER JOIN sStudent.tAcademic A ON A.StudentId=SO.StudentId
	Where HO.OrgId=@lOrgId AND A.Id=@rScopeSourceId)
	When PCS.ScopeSourceTypeId =2003 Then
	(select StudentId from sStudent.tAcademic  Where StudentId = PCS.ScopeSourceId AND Id = @rScopeSourceId)
	ENd)
	where ((PCM.Id=@rId) OR (@rId=0))  AND PCM.IsObsolete=0
	AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
	AND PCM.OrgGroupBatchId = @lOrgGroupBatchId
	AND PCS.AssigneeToId = 2
	 
      END
  else if @rSourcetypeId=95
  BEGIN 
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          --ISNULL(PCS.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
          ISNULL(Remark,'') AS Remark,
		  PCM.CreatedDateTime,
		  ISNULL(PCM.OrgGroupBatchId,0)AS OrgGroupBatchId
        From [sCommunication].[tMultiPhotoCategoryMaster] PCM 
        INNER join sCommunication.tMultiPhotoCategoryScope PCS  ON PCM.Id = PCS.MultiPhotoCategoryId AND
        (PCS.ScopeSourceId = Case when PCS.ScopeSourceTypeId = 2017 Then
        (Select D.Id from sSetup.tDepartmentMaster D 
        INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.OrganizationDepartmentId=D.Id
        Where EJ.EmployeeId=@rScopeSourceId AND EJ.OrgId=@lOrgId)
        when PCS.ScopeSourceTypeId=2021 Then
        (Select OM.Id from sSetup.tOrganizationMaster OM 
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgId=OM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
        Where EM.OrgId=@lOrgId and Em.Id=@rScopeSourceId)
		When PCS.ScopeSourceTypeId = 95 Then
		(select Id from sHrm.tEmployeeMaster  Where Id = @rScopeSourceId)
        END)
        where ((PCM.Id = @rId) OR (@rId=0))  AND PCM.IsObsolete=0
		AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
		AND PCM.OrgGroupBatchId = @lOrgGroupBatchId
		AND PCS.AssigneeToId = 3
        
  END
  else
  BEGIN
  SELECT  
		  PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          --ISNULL(PCS.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
          ISNULL(Remark,'') AS Remark,
		  PCM.CreatedDateTime,
		  ISNULL(PCM.OrgGroupBatchId,0)AS OrgGroupBatchId
          
  FROM    [sCommunication].[tMultiPhotoCategoryMaster]  PCM 
		  --INNER JOIN sCommunication.tMultiPhotoCategoryScope PCS  ON PCM.Id = PCS.MultiPhotoCategoryId
            
  WHERE   
      PCM.IsObsolete = 0
      AND  ((PCM.Id = @rId) OR (@rId = 0))
      AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
      --AND PCM.ScopeSourceTypeId=@rScopeSourceId
      AND OrgGroupId=@lOrgGroupId
	  AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
	  AND PCM.OrgGroupBatchId = @lOrgGroupBatchId
      ORDER BY PCM.CreatedDateTime DESC
   END   
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sCommunication].[pViewPhotoCategoryMaster_Get]
	 
	 @rScopeSourceId bigint=0,
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 --@rOrgGroupId smallint,
	 @rSourcetypeId smallint,
	 --@rOrgGroupBatchID int,
	 @rBatchId int,
	 @rBatchYear int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

  declare @lOrgGroupId smallint,@lOrgGroupBatchId int,@lOrgId smallint
  
  if @rSourcetypeId=2003
  BEGIN
  
	  Select @lOrgGroupId=Om.OrgGroupId,@lOrgId=OM.Id ,@lOrgGroupBatchID=BM.OrgGroupBatchId  from 
	  sSetup.tOrganizationMaster OM
	  INNER JOIN sStudent.tAcademic A ON A.OrgId=OM.Id
	  INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId
	  where A.BatchId= @rBatchId AND A.Id=@rScopeSourceId 
	  
  END
  
 else if @rSourcetypeId=95
  BEGIN
	 Select @lOrgId=OrgId From 
	 sSetup.tOrganizationMaster OM
	 INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgID=OM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	 Where Em.Id=@rScopeSourceId

	 Select @lOrgGroupBatchID = OrgGroupBatchId from sSetup.tBatchMaster Where Id = @rBatchId
  END
  else
  BEGIN
	Select @lOrgGroupId=OM.OrgGRoupId ,@lOrgGroupBatchID=BM.OrgGroupBatchId  from sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	Where Bm.Id=@rBatchId
  END
 
  if @rSourcetypeId=2003
  BEGIN
		
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
          ISNULL(Remark,'') AS Remark,
		  PCM.CreatedDateTime,
		  ISNULL(PCM.OrgGroupBatchId,0)AS OrgGroupBatchId
          
  from [sCommunication].[tPhotoCategoryMaster] PCM 
	INNER join sCommunication.tPhotoCategoryScope PCS  ON PCM.Id = PCS.PhotoCateGoryId AND
	(PCS.ScopeSourceId = Case  When PCM.ScopeSourceTypeId = 2005 Then
	(Select DivisionId From sStudent.tAcademic Where DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
	When PCM.ScopeSourceTypeId = 2016 Then
    (Select ClassId From sStudent.tAcademic Where ClassId = PCS.ScopeSourceId And Id = @rScopeSourceId)
	when PCM.ScopeSourceTypeId = 2017 Then
	(select D.Id from sSetup.tDepartmentMaster D INNER JOIN sSetup.tClassMaster CA ON CA.DepartmentId=D.Id 
	INNER JOIN sStudent.tAcademic A ON A.ClassID=CA.Id Where A.Id =@rScopeSourceId)
	When PCM.ScopeSourceTypeId =2021 Then
	(Select OM.Id from sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId =OM.Id Where A.Id=@rScopeSourceId)
	When PCM.ScopeSourceTypeId =2014 Then
	(Select Hm.Id from sHostel.tHostelMaster Hm INNER JOIN  sHostel.tRoomMaster RA ON RA.HostelId=HM.Id 
	INNER JOIN sHostel.tAssignRoom AR ON AR.RoomId=RA.Id
	INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId 
	Where AR.OrgGroupBatchId = @lOrgGroupBatchID AND HM.OrgGroupId=@lOrgGroupId AND A.Id=@rScopeSourceId)
	When PCM.ScopeSourceTypeId =2029 Then
	(select HO.Id from sActivity.tHouseMaster HO
	INNER JOIN sStudent.tStudentOther SO ON SO.HouseId=HO.Id 
	INNER JOIN sStudent.tAcademic A ON A.StudentId=SO.StudentId
	Where HO.OrgId=@lOrgId AND A.Id=@rScopeSourceId)
	ENd)
	where ((PCM.Id=@rId) OR (@rId=0))  AND PCM.IsObsolete=0
	AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
	AND PCM.OrgGroupBatchId = @lOrgGroupBatchId
	 
      END
  else if @rSourcetypeId=95
  BEGIN 
		SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
          ISNULL(Remark,'') AS Remark,
		  PCM.CreatedDateTime,
		  ISNULL(PCM.OrgGroupBatchId,0)AS OrgGroupBatchId
        From [sCommunication].[tPhotoCategoryMaster] PCM 
        INNER join sCommunication.tPhotoCategoryScope PCS  ON PCM.Id = PCS.PhotoCateGoryId AND
        (PCS.ScopeSourceId = Case when PCM.ScopeSourceTypeId = 2017 Then
        (Select D.Id from sSetup.tDepartmentMaster D 
        INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.OrganizationDepartmentId=D.Id
        Where EJ.EmployeeId=@rScopeSourceId AND EJ.OrgId=@lOrgId)
        when PCM.ScopeSourceTypeId=2021 Then
        (Select OM.Id from sSetup.tOrganizationMaster OM 
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgId=OM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
        Where EM.OrgId=@lOrgId and Em.Id=@rScopeSourceId)
        END)
        where ((PCM.Id = @rId) OR (@rId=0))  AND PCM.IsObsolete=0
		AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
		AND PCM.OrgGroupBatchId = @lOrgGroupBatchId
        
  END
  else
  BEGIN
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,
          ISNULL(Remark,'') AS Remark,
		  PCM.CreatedDateTime,
		  ISNULL(PCM.OrgGroupBatchId,0)AS OrgGroupBatchId
          
  FROM    [sCommunication].[tPhotoCategoryMaster]  PCM 
            
  WHERE   
      PCM.IsObsolete = 0
      AND  ((PCM.Id = @rId) OR (@rId = 0))
      AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
      --AND PCM.ScopeSourceTypeId=@rScopeSourceId
      AND OrgGroupId=@lOrgGroupId
	  AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
	  AND PCM.OrgGroupBatchId = @lOrgGroupBatchId
      ORDER BY PCM.CreatedDateTime DESC
   END   
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sCommunication].[pViewQueryRemarkGet]
	 
	 @rQueryId bigint = 0,
	 --@rTitle nvarchar(100),
	 @rId bigint,
	 --@rQueryCategoryId int
	 @rSyncedQueryCommentId bigint = 0,
	 @rUserId bigint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	  --BEGIN
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	SELECT 
			QC.Id,
			QC.QueryId,
			QC.Remark,
			U.DisplayTitle AS UserName,
			QC.CreatedDateTime,
			QC.CreatedUserId AS CommentCreatedUserId,
			Q.CreatedUserId AS QueryCreatedUserId
	FROM 
			sCommunication.tQueryComment QC
		INNER JOIN sCommunication.tQuery Q ON Q.Id=QC.QueryId
		INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId
	WHERE 
			((QC.QueryId = @rQueryId) OR (@rQueryId = 0)) 
			AND ( QC.Id > @rSyncedQueryCommentId OR @rSyncedQueryCommentId = 0)
			AND ( Q.CreatedUserId = @rUserId OR @rUserId = 0)
			order by QC.CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sCommunication].[pViewQueryRemarkv2Get]
	 
	 @rQueryId bigint,
	 @rUserId bigint
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	
	DECLARE	@lUserSourceTypeId smallint

	SELECT  @lUserSourceTypeId = SourceTypeId FROM sSecurity.tUser WHERE Id = @rUserId

		
	IF @lUserSourceTypeId = 2003
	 BEGIN
	  UPDATE sCommunication.tQuery SET IsUserView = 1	WHERE Id = @rQueryId
	 END
	ELSE IF @lUserSourceTypeId = 95
	 BEGIN
	  UPDATE sCommunication.tQuery SET IsAssigneeView = 1	WHERE Id = @rQueryId
	 END
	 
	SELECT 
			QC.Id,
			QC.QueryId,
			QC.Remark,
			U.DisplayTitle AS UserName,
			CONVERT(VARCHAR,QC.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,QC.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,QC.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
			--CONVERT(VARCHAR(25), QC.CreatedDateTime, 100) AS CreatedDateTime,
			QC.CreatedUserId AS CommentCreatedUserId,
			Q.CreatedUserId AS QueryCreatedUserId
	FROM 
			sCommunication.tQueryComment QC
		INNER JOIN sCommunication.tQuery Q ON Q.Id=QC.QueryId
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON Q.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
		INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId
		
	WHERE 
			QC.QueryId = @rQueryId
			--AND Q.CreatedUserId = @rUserId 
			order by QC.Id desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pViewResultDelete]

	@rOrgId int,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,
	@rCode nvarchar(20)='',
	@rName nvarchar(100)='',
	@rExamName nvarchar(150),
	@rAcademicId bigint,
	@rExamId int,
	@rExamTypeId tinyint,
	@rResultId bigint
	
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		
		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rExamName = sCommon.fSearchStringGet(@rExamName)
	
		DELETE VRD
		FROM sCommunication.tViewResultDetail VRD
		INNER JOIN sCommunication.tViewResult VR ON VR.ExamId=VRD.ExamId
		AND VR.ResultId=VRD.ResultId AND VR.ExamTypeId=VRD.ExamTypeId
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId = VR.AcademicId
		WHERE 
		(vSA.OrgId=@rOrgId)	
		AND (vSA.BatchId=@rBatchId)
		AND (VR.AcademicId=@rAcademicId)
		AND (VR.ExamId=@rExamId)
		AND (VR.ExamTypeId=@rExamTypeId)
		AND (VR.ResultId=@rResultId)
		
		
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((VR.ExamName Like @rExamName) OR (ISNULL(@rExamName,'')=''))
		AND ((vSA.Name Like @rName) OR (ISNULL(@rName,'')=''))
	    AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))

		
		DELETE VR
		FROM sCommunication.tViewResult VR
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId = VR.AcademicId
		WHERE 
		(vSA.OrgId=@rOrgId)	
		AND (vSA.BatchId=@rBatchId)
		AND (VR.AcademicId=@rAcademicId)
		AND (VR.ExamId=@rExamId)
		AND (VR.ExamTypeId=@rExamTypeId)
		AND (VR.ResultId=@rResultId)
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((VR.ExamName Like @rExamName) OR (ISNULL(@rExamName,'')=''))
		AND ((vSA.Name Like @rName) OR (ISNULL(@rName,'')=''))
	    AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))

		SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sCommunication].[pViewResultGet]
          
           @rOrgId int,
           @rClassId int,
           @rDivisionId int,
           @rCode nvarchar(20)='',
           @rName nvarchar(100)='',
           @rExamTypeId tinyint,
           @rExamName nvarchar(150)
           
AS
SET NOCOUNT ON
BEGIN

		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rExamName = sCommon.fSearchStringGet(@rExamName)

		SELECT  
			vSA.Code,
			vSA.Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			VR.AcademicId,
			VR.ExamId,
			VR.ExamTypeId,
			(CASE WHEN VR.ExamTypeId = 1 THEN 'Exam' ELSE 'Result' END) AS ExamType,
			VR.ExamName,
			VR.ResultId,
			VR.TotalMarks,
			VR.TotalObtain,
			VR.ResultStatus,
			VR.ResultGrade,
			VR.ResultGradePoint,
			VR.RankNumber,
			VR.Percentage,
			VR.Percentile,
			VR.ResultRemark,
			VR.OtherRemark1,
			VR.ResultOrder
		FROM 
			sCommunication.tViewResult VR
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId = VR.AcademicId
		WHERE 
			(vSA.OrgId=@rOrgId)
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((VR.ExamTypeId=@rExamTypeId) OR (@rExamTypeId=0))
			AND ((VR.ExamName Like @rExamName) OR (ISNULL(@rExamName,'')=''))
			AND ((vSA.Name Like @rName) OR (ISNULL(@rName,'')=''))
		    AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			ORDER BY VR.ResultOrder,vSA.DivisionOrder,vSA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pVoiceRecognitionGet]
	 
@rUserId bigint=0,
@rOrgGroupId int=0,
@rOrgGroupBatchId int=0,
@rOrgId int=0,	 
@rBatchId int=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @lSourceId bigint=0,@lSourceTypeId smallint=0,@lAcademicId bigint,@lClassId int,@lDivisionId int,@lDepartmentId int
    SELECT @lSourceId=SourceId,@lSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE Id = @rUserId
    
    -- Student
	IF(@lSourceTypeId = 2003)	
	BEGIN
		SELECT @lAcademicId = A.Id,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lDepartmentId=CM.DepartmentId 
		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 = @lSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
	END
	-- Employee
	ELSE
	BEGIN
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId 
		FROM sHrm.tEmployeeMaster EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		WHERE EM.Id=@lSourceId AND  ISNULL(EM.IsOtherUser,0) = 0
	END
	
	
	-- Student
	IF(@lSourceTypeId = 2003)	
	BEGIN
		-- Circular
		SELECT C.Id,C.Title,C.Remark,20085 AS ScreenId,C.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tCircular C INNER JOIN 
		(SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE
		(
			(CS.SourceTypeId = 2021 AND CS.SourceId =@rOrgId) 
			OR (CS.SourceTypeId = 2017 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 =@lSourceId)
			OR (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId)
		)
		) D ON D.CircularId= C.Id
		INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
		WHERE CONVERT(DATE,C.StartDate) = CONVERT(DATE,GETDATE()) AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId
		
		UNION ALL
		
		-- Assignment
		SELECT A.Id,A.Title,A.Remark,20093 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignment A INNER JOIN 
		(SELECT ASO.AssignmentId FROM sCommunication.tAssignmentScope ASO WHERE
		(
		(ASO.SourceTypeId = 2005 AND ASO.SourceId =@lDivisionId)
		)
		) D ON D.AssignmentId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.StartDate) = CONVERT(DATE,GETDATE()) AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Poll
		SELECT P.Id,P.Title,P.Remark,20204 AS ScreenId,P.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPoll P INNER JOIN 
		(SELECT PM.PollId FROM sCommunication.tPollMember PM  WHERE
		(
		(PM.SourceTypeId = 2005 AND PM.SourceId =@lDivisionId)
		)
		) D ON D.PollId= P.Id
		INNER JOIN sSecurity.tUser U ON U.Id=P.CreatedUserId
		WHERE CONVERT(DATE,P.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  P.OrgGroupBatchId=@rOrgGroupBatchId
		
		UNION ALL
		
		-- Blog
		SELECT B.Id,B.Title,B.Remark,20099 AS ScreenId,B.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tBlog B INNER JOIN 
		(SELECT BS.BlogId FROM sCommunication.tBlogScope BS  WHERE
		(
		(BS.SourceTypeId = 2021 AND BS.SourceId =@rOrgId)
		)
		) D ON D.BlogId= B.Id
		INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
		WHERE CONVERT(DATE,B.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  B.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- News
		SELECT N.Id,N.Title,N.Remark,20104 AS ScreenId,N.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tNews N INNER JOIN 
		(SELECT NS.NewsId FROM sCommunication.tNewsScope NS  WHERE
		(
		(NS.SourceTypeId = 2021 AND NS.SourceId =@rOrgId)
		)
		) D ON D.NewsId= N.Id
		INNER JOIN sSecurity.tUser U ON U.Id=N.CreatedUserId
		WHERE CONVERT(DATE,N.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  N.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- Gallery
		SELECT PCM.Id,PCM.Title,PCM.Remark,20183 AS ScreenId,PCM.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPhotoCategoryMaster PCM INNER JOIN 
		(SELECT PCS.PhotoCategoryId FROM sCommunication.tPhotoCategoryMaster PCM
		INNER JOIN sCommunication.tPhotoCategoryScope PCS ON PCM.Id = PCS.PhotoCategoryId
		WHERE
		((PCM.ScopeSourceTypeId = 2021 AND PCS.ScopeSourceId =@rOrgId))
		OR ((PCM.ScopeSourceTypeId = 2017 AND PCS.ScopeSourceId =@lDepartmentId))
		OR ((PCM.ScopeSourceTypeId = 2016 AND PCS.ScopeSourceId =@lClassId))
		OR ((PCM.ScopeSourceTypeId = 2005 AND PCS.ScopeSourceId =@lDivisionId))
		) D ON D.PhotoCategoryId= PCM.Id
		INNER JOIN sSecurity.tUser U ON U.Id=PCM.CreatedUserId
		WHERE CONVERT(DATE,PCM.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  PCM.OrgGroupId=@rOrgGroupId 
		
		UNION ALL
		
		-- Classwork | Homework
		SELECT C.Id,'Classwork' AS Title,Classwork AS Remark,20563 AS ScreenId,C.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sAcademic.tClasswork C
		INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
		WHERE CONVERT(DATE,C.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  BatchId=@rBatchId AND DivisionId = @lDivisionId AND ClassId = @lClassId
		
		UNION ALL
		
		-- Behaviour
		SELECT B.Id,Title,Remark,20130 AS ScreenId,B.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle FROM sCommunication.tBehaviour B
		INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
		WHERE CONVERT(DATE,B.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  AcademicId=@lAcademicId
		
		UNION ALL
		
		-- Activity
		SELECT A.Id,A.Title,A.Remark,20209 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sActivity.tActivity A INNER JOIN 
		(SELECT AP.ActivityId FROM sActivity.tActivityParticipant AP  WHERE
		(
		(AP.SourceTypeId = 2003 AND AP.SourceId =@lSourceId)
		)
		) D ON D.ActivityId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Task
		SELECT T.Id,'Task' AS Title,Remark,20172 AS ScreenId,T.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignTask T
		INNER JOIN sSecurity.tUser U ON U.Id=T.CreatedUserId
		WHERE CONVERT(DATE,T.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  T.OrgId=@rOrgId AND AssignedToSourceTypeId = 2003 AND AssignedToSourceId=@lSourceId
		
		UNION ALL
		
		-- Birthday
		SELECT SM.Id,'Birthday' AS Title,FirstName+' '+LastName AS Remark,20577 AS ScreenId,SO.DateOfBirth AS CreatedDateTime,0 AS CreatedUserId,'' AS CreatedUser FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tStudentOther SO ON SM.Id = SO.StudentId 
		WHERE CONVERT(DATE,SO.DateOfBirth) = CONVERT(DATE,GETDATE()) AND  SM.OrgId=@rOrgId AND SM.Id=@lSourceId
		
	END 
	-- Employee
	ELSE
	BEGIN
		-- Circular
		SELECT C.Id,C.Title,C.Remark,20085 AS ScreenId,C.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
		WHERE (
			  (CS.SourceTypeId = 2021 AND CS.SourceId =@rOrgId) 
 			  OR (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId)
 			  OR (CS.SourceTypeId = 95 AND CS.SourceId =@lSourceId)
			  )) D ON D.CircularId= C.Id
		INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId	  
		WHERE CONVERT(DATE,C.StartDate) = CONVERT(DATE,GETDATE()) AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId
		
		UNION ALL
		
		-- Assignment
		SELECT A.Id,A.Title,A.Remark,20093 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignment A INNER JOIN (SELECT ASO.AssignmentId FROM sCommunication.tAssignmentScope ASO
		WHERE (
			  (ASO.SourceTypeId = 2017 AND ASO.SourceId =@lDepartmentId)
			  )) D ON D.AssignmentId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId		  
		WHERE CONVERT(DATE,A.StartDate) = CONVERT(DATE,GETDATE()) AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Poll
		SELECT P.Id,P.Title,P.Remark,20204 AS ScreenId,P.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPoll P INNER JOIN 
		(SELECT PM.PollId FROM sCommunication.tPollMember PM  WHERE
		(
		(PM.SourceTypeId = 2017 AND PM.SourceId =@lDepartmentId)
		)
		) D ON D.PollId= P.Id
		INNER JOIN sSecurity.tUser U ON U.Id=P.CreatedUserId		  
		WHERE CONVERT(DATE,P.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  P.OrgGroupBatchId=@rOrgGroupBatchId
		
		UNION ALL
		
		-- Blog
		SELECT B.Id,B.Title,B.Remark,20099 AS ScreenId,B.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tBlog B INNER JOIN 
		(SELECT BS.BlogId FROM sCommunication.tBlogScope BS  WHERE
		(
		(BS.SourceTypeId = 2021 AND BS.SourceId =@rOrgId)
		)
		) D ON D.BlogId= B.Id
		INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
		WHERE CONVERT(DATE,B.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  B.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- News
		SELECT N.Id,N.Title,N.Remark,20104 AS ScreenId,N.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tNews N INNER JOIN 
		(SELECT NS.NewsId FROM sCommunication.tNewsScope NS  WHERE
		(
		(NS.SourceTypeId = 2021 AND NS.SourceId =@rOrgId)
		)
		) D ON D.NewsId= N.Id
		INNER JOIN sSecurity.tUser U ON U.Id=N.CreatedUserId
		WHERE CONVERT(DATE,N.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  N.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- Gallery
		SELECT PCM.Id,PCM.Title,PCM.Remark,20183 AS ScreenId,PCM.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPhotoCategoryMaster PCM INNER JOIN 
		(SELECT PCS.PhotoCategoryId FROM sCommunication.tPhotoCategoryMaster PCM
		INNER JOIN sCommunication.tPhotoCategoryScope PCS ON PCM.Id = PCS.PhotoCategoryId
		WHERE
		((PCM.ScopeSourceTypeId = 2021 AND PCS.ScopeSourceId =@rOrgId))
		OR ((PCM.ScopeSourceTypeId = 2017 AND PCS.ScopeSourceId =@lDepartmentId))
		) D ON D.PhotoCategoryId= PCM.Id
		INNER JOIN sSecurity.tUser U ON U.Id=PCM.CreatedUserId
		WHERE CONVERT(DATE,PCM.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  PCM.OrgGroupId=@rOrgGroupId 
		
		UNION ALL
		
		-- Activity
		SELECT A.Id,A.Title,A.Remark,20209 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sActivity.tActivity A INNER JOIN 
		(SELECT AP.ActivityId FROM sActivity.tActivityParticipant AP  WHERE
		(
		(AP.SourceTypeId = 95 AND AP.SourceId =@lSourceId)
		)
		) D ON D.ActivityId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Task
		SELECT A.Id,'Task' AS Title,Remark,20172 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignTask A
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.CreatedDateTime) = CONVERT(DATE,GETDATE()) AND  A.OrgId=@rOrgId AND AssignedToSourceTypeId = 95 AND AssignedToSourceId=@lSourceId
		
		UNION ALL
		
		-- Birthday
		SELECT EM.Id,'Birthday' AS Title,FirstName+' '+LastName AS Remark,20577 AS ScreenId,EPD.DateOfBirth AS CreatedDateTime,0 AS CreatedUserId,'' AS CreatedUser FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId 
		WHERE CONVERT(DATE,EPD.DateOfBirth) = CONVERT(DATE,GETDATE()) AND  EM.OrgId=@rOrgId AND EM.Id=@lSourceId AND  ISNULL(EM.IsOtherUser,0) = 0
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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(100) 'Title',
		Remark nvarchar(200) 'Remark',
		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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pXMLUploadBookLogAdd]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	
	-----------------------
	
	INSERT INTO sCommunication.tUploadBookLog
	(
		BookLogId,
		BookTitle,
		IssueDate,
		ReaderSourceTypeId,
		ReaderSourceId,
		BatchId
	)
	SELECT
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(BookLogId,5)),OrgId),
		BookTitle,
		CASE WHEN IssueDate = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(IssueDate, 8)) END,
		CASE WHEN ReaderSourceTypeId = 1 THEN 2003 ELSE 95 END,
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(ReaderSourceId,5)),OrgId),
		BatchId
		
	FROM OPENXML (@intDoc, '/Table/UploadBookLog', 1)
	WITH
	(
		BookLogId int '@BookLogId',
		BookTitle nvarchar(100) '@BookTitle',
		IssueDate int '@IssueDate',
		ReaderSourceTypeId bigint '@ReaderSourceTypeId',
		ReaderSourceId bigint '@ReaderSourceId',
		OrgId int '@OrgId',
		BatchId int '@BatchId'
	)

	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sCommunication].[pYoutubeVideoListGet]
	@rOrgId int=0,
	@rUserId bigint=0,
	@rSourceTypeId int=0,
	@rSourceId bigint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

if (@rSourceTypeId = 95)

	BEGIN

		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id 
		FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD	 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId

			BEGIN 		
		
				SELECT * FROM (SELECT * FROM (SELECT VP.SourceTypeId, VP.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,VP.PlaylistName as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id 
				WHERE VP.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,VP.PlaylistName  as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				WHERE VP.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Employee' AS SourceType,vEC.FirstName +' '+ vEC.LastName AS Source,VP.PlaylistName  as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sHrm.vEmployeeCommunication vEC ON VP.SourceId=vEC.EmployeeId AND vEC.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id					
				WHERE VP.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) ) TempVideoPlaylist

				UNION ALL

				SELECT * FROM (SELECT	 VP.SourceTypeId, VP.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id 
				WHERE VP.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId,'Department' AS SourceType,DM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				WHERE VP.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId, 'Employee' AS SourceType,vEC.FirstName +' '+ vEC.LastName AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sHrm.vEmployeeCommunication vEC ON VP.SourceId=vEC.EmployeeId AND vEC.StatusId=7
				INNER JOIN sSetup.tOrganizationMaster OM ON vEC.OrgId = OM.Id					
				WHERE VP.SourceTypeId=95 AND ((OM.Id=@rOrgId) OR @rOrgId=0) ) TempVideolist ) TempYouTubeVideoList

				WHERE ((TempYouTubeVideoList.SourceTypeId = 2021 AND TempYouTubeVideoList.SourceId =@lOrgId) OR
					   (TempYouTubeVideoList.SourceTypeId = 2017 AND TempYouTubeVideoList.SourceId =@lDepartmentId) OR
					   (TempYouTubeVideoList.SourceTypeId = 95 AND TempYouTubeVideoList.SourceId =@lEmployeeId))
			END
	END

ELSE

	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 = @rSourceId AND A.OrgId=@rOrgId
				--AND BM.OrgGroupBatchId = @rOrgGroupBatchId

			BEGIN 		
		
				SELECT * FROM (SELECT * FROM (SELECT VP.SourceTypeId, VP.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,VP.PlaylistName as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id 
				WHERE VP.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Department' AS SourceType,DM.DisplayTitle AS Source,VP.PlaylistName  as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				WHERE VP.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId, 'Class' AS SourceType,CM.DisplayTitle AS Source,VP.PlaylistName  as Detail,VP.AssignedToId, 
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tClassMaster CM ON VP.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				WHERE VP.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,VP.PlaylistName as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sSetup.tDivisionMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				WHERE VP.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,VP.PlaylistName as Detail,
				VP.AssignedToId,CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sStudent.tStudentMaster SM ON VP.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON VP.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				WHERE VP.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId, 'Student' AS SourceType,SA.Name AS Source,VP.PlaylistName as Detail,VP.AssignedToId,
				CASE WHEN VP.AssignedToId=2 THEN 'Student' WHEN VP.AssignedToId=3 THEN 'Employee' ELSE 'Both' END AS Assignee
				FROM sCommunication.tVideoPlaylist VP
				INNER JOIN sStudent.vStudentAcademic SA	ON VP.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				WHERE VP.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) ) TempVideoPlaylist

				UNION ALL

				SELECT * FROM (SELECT	 VP.SourceTypeId, VP.SourceId, 'Organization' AS SourceType,OM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tOrganizationMaster OM ON VP.SourceId=OM.Id 
				WHERE VP.SourceTypeId=2021 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId,'Department' AS SourceType,DM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tDepartmentMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
				WHERE VP.SourceTypeId=2017 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId,'Class' AS SourceType,CM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tClassMaster CM ON VP.SourceId=CM.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON CM.DepartmentId =DM.Id		
				INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id
				WHERE VP.SourceTypeId=2016 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Division' AS SourceType,CM.DisplayTitle+'-'+DM.DisplayTitle AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sSetup.tDivisionMaster DM ON VP.SourceId=DM.Id
				INNER JOIN sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
				INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id		
				WHERE VP.SourceTypeId=2005 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION 
				SELECT VP.SourceTypeId, VP.SourceId, 'Student' AS SourceType,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
				VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sStudent.tStudentMaster SM ON VP.SourceId=SM.Id
				INNER JOIN  sStudent.vStudentAcademic SA ON VP.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id		
				WHERE VP.SourceTypeId=2003 AND ((OM.Id=@rOrgId) OR @rOrgId=0)
				UNION
				SELECT VP.SourceTypeId, VP.SourceId, 'Student' AS SourceType,SA.Name AS Source,VP.VideoId AS Detail,0 as AssignedToId,'' as Assignee
				FROM sCommunication.tVideoSpecific VP
				INNER JOIN sStudent.vStudentAcademic SA	ON VP.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id			
				WHERE VP.SourceTypeId=2001 AND ((OM.Id=@rOrgId) OR @rOrgId=0) ) TempVideolist ) TempYouTubeVideoList

				WHERE ((TempYouTubeVideoList.SourceTypeId = 2021 AND TempYouTubeVideoList.SourceId =@lOrgId) OR
					   (TempYouTubeVideoList.SourceTypeId = 2017 AND TempYouTubeVideoList.SourceId =@lDepartmentId) OR
                       (TempYouTubeVideoList.SourceTypeId = 2016 AND TempYouTubeVideoList.SourceId =@lClassId) OR
                       (TempYouTubeVideoList.SourceTypeId = 2005 AND TempYouTubeVideoList.SourceId =@lDivisionId) OR
                       (TempYouTubeVideoList.SourceTypeId = 2003 AND TempYouTubeVideoList.SourceId =@lStudentId) OR
                       (TempYouTubeVideoList.SourceTypeId = 2001 AND TempYouTubeVideoList.SourceId =@lAcademicId) )

			END
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pBackupDetailAdd]
	 
	@rId bigint,
	@rDatabaseId tinyint,
	@rDatabaseName nvarchar(100),
	@rBackupPath nvarchar(200),
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
-- IF(@rId = 0)	
--BEGIN

	DECLARE @lNextNumber BIGINT     
--	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSetup.tBatchMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


--	INSERT INTO sSetup.tBatchMaster
--		(
--			Id,
--			Code,
--			Title,
--			OrgId,
--			IsHistory,
--			IsObsolete,
--			OrderIndex,
--			FromDate,
--			ToDate,
--			CreatedUserId,
--			CreatedDateTime
			
--		)
--	VALUES
--		(
--			@lNextNumber,
--			@rCode,
--			@rTitle,
--			@rOrgId,
--			@rIsHistory,
--			@rIsObsolete,
--			@rOrderIndex,
--			@rFromDate,
--			@rToDate,
--			@rCreatedUserId,
--			sCommon.fGetDate()
			
--		)
		             
--	END	 
--	 ELSE
--	 BEGIN
	 SET @lNextNumber = @rId
	 
		UPDATE  sConfig.tDatabaseSetting
	    SET
			BackupPath=@rBackupPath,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
	        Backupdatetime=sCommon.fGetDate()
	      WHERE Id = @rDatabaseId 	  
		
	    UPDATE  sConfig.tDatabase
	    SET
			Title=@rDatabaseName
			
	      WHERE Id = @rDatabaseId 	   
	 --END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pBackupDetailGet]
	 @rId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
			DS.Id,
			D.Id AS DatabaseId,
			D.Title AS DatabaseName,
			DS.BackupPath
  FROM 
            sConfig.tDatabaseSetting DS
        INNER JOIN sConfig.tDatabase D ON D.Id=DS.DatabaseId
             
  WHERE 
		DS.Id=@rId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pCallScriptFile]
	 
	 @rFilePath nvarchar(200)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	SET NOCOUNT ON  
EXEC master.dbo.sp_configure 'show advanced options', 1 
RECONFIGURE 
EXEC master.dbo.sp_configure 'xp_cmdshell', 1 
RECONFIGURE 

DECLARE @lSql nvarchar(200)
DECLARE @lDBFileName nvarchar(30)
DECLARE @lCount INT

	--SELECT ROW_NUMBER() OVER(ORDER BY Id) AS Id,DBFileName INTO sSystem.tTempVersion FROM sSyestem.tVersion V
	--	LEFT JOIN sSystem.tDatabaseInfo DI ON DI.VersionId=V.Id 
	--WHERE
	--	V.Id > DI.VersionId 

	--SELECT @lCount =  COUNT(Id) FROM sSystem.tTempVersion

	--WHILE @lCount > 0 

	--BEGIN

	--	SELECT @lDBFileName=DBFileName FROM sSystem.tTempVersion WHERE Id = @lCount  
		
		SET FMTONLY ON  -- Without Display OutPut
		SET @lSql='sqlcmd -S '+@@SERVERNAME+' -d '+DB_NAME()+' -i ' + @rFilePath
		EXEC xp_cmdshell @lSql
		SET FMTONLY OFF  -- Without Display OutPut
		
	--	SET @lCount = @lCount - 1				
	--END

	--DROP TABLE sSystem.tTempVersion

EXEC master.dbo.sp_configure 'xp_cmdshell', 0 
RECONFIGURE 
EXEC master.dbo.sp_configure 'show advanced options', 0 
RECONFIGURE  
SET NOCOUNT OFF
	SELECT 1 AS Result
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pConfigurationDirectValueGet] 
            @rOrgGroupId int,
            @rOrgId int,            
			@rUserId bigint,			
			@rKey nvarchar(100)
		
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT CM.ItemKey AS ItemKey,ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue
	   FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=1016 AND SourceId = @rOrgId 
	   Where CM.ConfigurationLevelId = 1 AND CM.ItemKey = @rKey
	
	--UNION ALL
	
	--   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	--   ON CS.ConfigurationId = CM.Id AND SourceId = @rLocationId  Where CM.ConfigurationLevelId = 2 AND CM.ItemKey = @rKey
	   
	--UNION ALL
	
	--   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	--   ON CS.ConfigurationId = CM.Id AND SourceId = @rStoreLocationId  Where CM.ConfigurationLevelId = 3 AND CM.ItemKey = @rKey
	
	UNION ALL
	
	   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	   ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=95 AND SourceId = @rUserId  Where CM.ConfigurationLevelId = 4 AND CM.ItemKey = @rKey
	   
	UNION ALL
	
	   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	   ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=2010 AND SourceId = @rOrgGroupId  Where CM.ConfigurationLevelId = 5 AND CM.ItemKey = @rKey
	  		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pConfigurationLevelMasterGet] 
  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT  4 AS ConfigurationLevelId,'User Configuration' AS LevelName
	 UNION ALL
	 SELECT  1,'Organization Configuration'
	 UNION ALL
	 SELECT  2,'Location Configuration'
	 UNION ALL
	 SELECT  3,'Sub Location Configuration'
	 UNION ALL
	 
	 SELECT  5,'Org Group Configuration'
	 
	  UNION ALL
	 SELECT  6,'Application Configuration'
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pConfigurationMasterGet] 
 
	@rConfigurationLevelId [tinyint] = 0,
	@rSourceId bigint,
	@rSourceTypeId int,
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
	        CM.Id AS ID,
			MM.Title,
			CM.ItemKey,
			CM.ItemValue AS DefaultValue,
			ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue,
			CM.Remark AS VDescription,
			CM.ValidationTypeId AS ValidationType,
			CM.ConfigurationLevelId	
			--Remark,
			--TypeId,
			--MM.TitleResourceKeyId
			--IsObsolete
	   FROM sCommon.tModuleMaster MM
	   INNER JOIN sConfig.tConfigurationMaster CM ON CM.ModuleId = MM.Id
	   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=CM.ModuleId AND MP.OrgGroupId=@rOrgGroupId
	   LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceId = @rSourceId AND CS.SourceTypeId = @rSourceTypeId
	   
	  WHERE  
			 (CM.ConfigurationLevelId = @rConfigurationLevelId)
			AND (CM.IsObsolete = 0) 
			
			ORDER BY MM.Title,CM.ItemKey			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pConfigurationSessionValueGet] 
			@rUserId bigint,
			@rLocationId int,
			@rStoreLocationId int,
			@rOrgId int,
			@rOrgGroupId int
		
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
      SELECT CM.ItemKey AS ItemKey,ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue
	   FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id 
	   AND CS.SourceTypeId=1016 AND SourceId = @rOrgId 
	   Where CM.ConfigurationLevelId = 1
	
	--UNION ALL
	
	--   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	--   ON CS.ConfigurationId = CM.Id AND SourceId = @rLocationId  Where CM.ConfigurationLevelId = 2
	   
	--UNION ALL
	
	--   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	--   ON CS.ConfigurationId = CM.Id AND SourceId = @rStoreLocationId  Where CM.ConfigurationLevelId = 3
	
	UNION ALL
	
	   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	   ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=95 AND SourceId = @rUserId  Where CM.ConfigurationLevelId = 4
	   
	UNION ALL
	
	   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	   ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=2010 AND SourceId = @rOrgGroupId  Where CM.ConfigurationLevelId = 5
	UNION ALL
	
	   SELECT CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS 
	   ON CS.ConfigurationId = CM.Id    Where CM.ConfigurationLevelId = 6
	  		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
 
CREATE OR ALTER PROCEDURE [sConfig].[pConfigurationSetupAdd]
	 
	@rConfigurationId [int],
	@rItemValue nvarchar(500),
	@rSourceTypeId [int],
	@rSourceId [bigint],
	@rCreatedUserId [bigint],
	@rOrgId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	 DELETE FROM sConfig.tConfigurationSetup 
     WHERE 
     ConfigurationId  = @rConfigurationId 
     AND SourceId=@rSourceId 
     AND SourceTypeId=@rSourceTypeId
 
	DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sConfig.tConfigurationSetup', 0, 1, 1,@outNextNumber = @lNextNumber output

 IF NOT EXISTS(Select 1 From sConfig.tConfigurationSetup Where ConfigurationId = @rConfigurationId AND SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId)
  
   BEGIN
	
	IF(@rItemValue!='')
	BEGIN
	INSERT INTO [sConfig].[tConfigurationSetup]
           ([Id]
           ,[ConfigurationId]
           ,[ItemValue]
           ,[sourceTypeId]
           ,[SourceId]
           ,[CreatedUserId]
           ,[CreatedDateTime]        
            )
     VALUES
           (
            @lNextNumber,
            @rConfigurationId,
            @rItemValue,
            @rSourceTypeId,
            @rSourceId,
            @rCreatedUserId,
            sCommon.fGetDate()
            )
      END      
          select 1 as result
   END
  ELSE
   BEGIN
      UPDATE sConfig.tConfigurationSetup 
          SET ItemValue = @rItemValue,
          UpdatedUserId = @rCreatedUserId,
          UpdatedDateTime =  sCommon.fGetDate()
          
       Where ConfigurationId  = @rConfigurationId AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId
		Select 11 as result
   END       
           
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sConfig].[pConfigurationSetupValidate]
	 
	@rConfigurationId [int],
	@rItemValue nvarchar(500),
	@rSourceTypeId [int],
	@rSourceId [bigint]
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rConfigurationId = 553)	--Fee.IsCollectionGroupMandatory
	BEGIN
		DECLARE @lIsFeeByCollectionGroupItemValue nvarchar(500) = ''
		Select @lIsFeeByCollectionGroupItemValue = ItemValue From sConfig.tConfigurationSetup Where ConfigurationId = 150 AND SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId --Fee.IsFeeByCollectionGroup

		IF(@rItemValue = 'True' AND @lIsFeeByCollectionGroupItemValue = 'False')
		BEGIN
			SELECT -1 AS Result, 'Kindly change configuration - Fee.IsFeeByCollectionGroup to True' AS Message
		END

		--DECLARE @lIsGenerateMultipleFeeReceiptItemValue nvarchar(500) = ''
		--Select @lIsGenerateMultipleFeeReceiptItemValue = ItemValue From sConfig.tConfigurationSetup Where ConfigurationId = 116 AND SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId --Fee.IsGenerateMultipleFeeReceipt

		--IF(@rItemValue = 'True' AND @lIsGenerateMultipleFeeReceiptItemValue = 'True')
		--BEGIN
		--	SELECT -1 AS Result, 'Kindly change configuration - Fee.IsGenerateMultipleFeeReceipt to False' AS Message
		--END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sConfig].[pConfigurationValueGet] 
			
			@rOrgGroupId int,
			@rOrgId int,
			@rUserId bigint
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lSourceTypeId smallint=0
	SELECT @lSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE Id = @rUserId

BEGIN
	SELECT 
		CM.ItemKey AS ItemKey,ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=1016 AND SourceId = @rOrgId 
	WHERE 
		CM.ConfigurationLevelId = 1

	UNION ALL

	SELECT 
		CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=95 AND SourceId = @rUserId  
	WHERE 
		CM.ConfigurationLevelId = 4

	UNION ALL

	SELECT 
		CM.ItemKey, (CASE WHEN CM.Id=247 AND @lSourceTypeId=2003 THEN  'True' ELSE  ISNULL(CS.ItemValue,CM.ItemValue)  END) AS ItemValue
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=2010 AND SourceId = @rOrgGroupId  
	WHERE 
		CM.ConfigurationLevelId = 5
	
	UNION ALL

	SELECT 
		CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue  
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id 
	WHERE 
		CM.ConfigurationLevelId = 6
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pControlShortcutKeyGet]
	@rID [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT ID,
			FunctionalityShortcutKeyId,
			ControlName,
			ScreenId
	   FROM sConfig.tControlShortcutKey
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pCreateBackup]

	@rSql nvarchar(500)
	
WITH EXECUTE AS CALLER
AS
BEGIN
	SET NOCOUNT ON;
	
	BEGIN TRY
	
	 --BEGIN TRANSACTION
	EXEC(@rSql)
    
    SELECT 1 AS Result,'Sucess' AS ResultText
	
		--COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
	--	--ROLLBACK TRANSACTION
		SELECT -1 AS Result,ERROR_MESSAGE() AS ResultText
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pCultureMasterGet]
	@rCulture [nvarchar](5)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
		Id,
		DateSeparator,		
		Culture,
		LongDatePattern,
		LongTimePattern,
		NumberGroupSeparator,
		NumberGroupSizes,
		NumberNegativePattern,
		ShortDatePattern,
		ShortTimePattern
	  FROM 
		sConfig.tCultureMaster
	  WHERE 
		Culture = @rCulture
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pCultureMasterModify]
	@rDateSeparator [nchar](1),
	@rUpdatedUserId [bigint] = 0,
	@rCulture [nvarchar](5),
	@rLongDatePattern [nvarchar](20),
	@rLongTimePattern [nvarchar](20),
	@rNumberGroupSeparator [nchar](1),
	@rNumberGroupSizes [tinyint],
	@rNumberNegativePattern [tinyint],
	@rShortDatePattern [nvarchar](20),
	@rShortTimePattern [nvarchar](20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN



	 UPDATE sConfig.tCultureMaster
	   SET	   	 
			DateSeparator = @rDateSeparator,			
			Culture = @rCulture,
			LongDatePattern = @rLongDatePattern,
			LongTimePattern = @rLongTimePattern,
			NumberGroupSeparator = @rNumberGroupSeparator,
			NumberGroupSizes = @rNumberGroupSizes,
			NumberNegativePattern = @rNumberNegativePattern,
			ShortDatePattern = @rShortDatePattern,
			ShortTimePattern = @rShortTimePattern,			
			UpdatedUserId = CASE @rUpdatedUserId WHEN 0 THEN NULL ELSE @rUpdatedUserId END,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE 
		Culture = @rCulture
		
		SELECT Id FROM sConfig.tCultureMaster WHERE Culture = @rCulture
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pDeleteImportData]
     @rImportId int,
     @rImportTypeId int
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @1StatusCode INT,
        @1SourceId bigint
         
 
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
		ExaminationID bigint,
        ImportId int
  
        --Id1 bigint NULL,
        --departmentId int NULL
 
  )
  INSERT INTO #tTable1
	(
	    ExaminationID,ImportId   
    ) 
   SELECT Id,ISNULL(ImportId,0)
        From sExamination.tExamination Where ImportId = @rImportId
     
     IF(@rImportId > 0)
       DELETE From sConfig.tImport where Id = @rImportId   
        
			
SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 
  BEGIN 
		
          BEGIN
  			  SET  @1SourceId =(select ExaminationID from #tTable1 Where Id = @lCount)  			  
  			  Execute [sExamination].[pExaminationRecordRemove]  @1SourceId 
  			   
  			 SET @1StatusCode = 1 
	       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
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pDeviceTypeMasterGet]
	@rId [tinyint] = 0,
	@rUserId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


CREATE TABLE #tmpGlobalizationTableResource
	(
		  UiCultureId INT,
		  UiResourceKeyId SMALLINT,
		  UiResourceKeyValue NVARCHAR(300),
		  Remark NVARCHAR(300)
	) 

INSERT INTO #tmpGlobalizationTableResource
EXECUTE sConfig.pGlobalizationTableResource @rUserId = @rUserId


	 SELECT DISTINCT D.Id AS Id,
			SGTR.UiResourceKeyValue AS Title,
			D.TitleResourceKeyId AS TitleResourceKeyId,
			D.IsObsolete 
	   FROM sConfig.tDeviceTypeMaster AS D
	   LEFT JOIN #tmpGlobalizationTableResource AS SGTR
			ON D.TitleResourceKeyId = SGTR.UiResourceKeyId
			INNER JOIN sConfig.tDeviceMaster DM ON DM.DeviceTypeId = D.Id
	  WHERE ((D.Id = @rId) OR (@rId = 0))
	  DROP TABLE #tmpGlobalizationTableResource
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pDisplayFieldOrgAdd]
	@rDisplayFieldOrgDetailXml [nvarchar](max),
	@rOrgId smallint,
	@rFieldSource nvarchar(100)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDisplayFieldOrgDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	

	 Delete D FROM sConfig.tDisplayFieldOrg D  INNER  JOIN [sConfig].[tDisplayFieldMaster] DF
     ON DF.id=D.DisplayFieldId and FieldSource=@rFieldSource
				 WHERE OrgId=@rOrgId 
			
	 --DELETE FROM sConfig.tDisplayFieldOrg
		--		 WHERE OrgId=@rOrgId 
	 
	 INSERT INTO sConfig.tDisplayFieldOrg
		(
			DisplayFieldId,
			OrgId,
			IsFieldMandatory
			
			)
		SELECT
		
			DisplayFieldId,
			OrgId,
			IsFieldMandatory 
		FROM OPENXML (@loDoc, '/Table/DisplayFieldOrgDetail', 1)
		WITH ( 
				DisplayFieldId smallint,
				OrgId smallint,
				IsFieldMandatory bit
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sConfig].[pDisplayFieldOrgListGet]
          
           @rOrgId smallint,
           @rFieldSource  nvarchar(100)
 
AS
SET NOCOUNT ON

BEGIN

SELECT 
     
	   ISNULL(DM.Id,0) AS DisplayFieldId
	  ,ISNULL(DM.Name,'') AS Name
	 -- ,ISNULL(DM.FieldSource,'') AS FieldSource 
   ,(CASE WHEN DO.DisplayFieldId Is Null THEN 'False'  ELSE 'True' END) AS Selected 
    ,(CASE WHEN DO.IsFieldMandatory Is Null THEN 'False' WHEN DO.IsFieldMandatory = 1 THEN 'True' ELSE 'False' END) AS IsMandatory 
      
 
FROM sConfig.tDisplayFieldMaster DM
      LEFT JOIN sConfig.tDisplayFieldOrg DO ON DM.Id=DO.DisplayFieldId
	  AND DO.OrgId=@rOrgId
WHERE (DM.FieldSource=@rFieldSource) 
ORDER by DM.Id -- Changed for mantis : 33583 by Nilesh
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pFunctionalityShortcutKeyGet]
	@rID [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT ID,
			FunctionalityName,
			AccessKeyCode,
			IsActive
	   FROM sConfig.tFunctionalityShortcutKey
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pGlobalizationSettingGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			CultureTitle,
			CultureRemark,
			NumberDecimalSymbol,
			NumberDigitGroupingSymbol,
			NumberDigitGroup,
			NumberNegativeFormat,
			CurrencySymbol,
			CurrencyPositiveFormat,
			CurrencyNegativeFormat,
			TimeFormat,
			TimeSeparator,
			TimeAmSymbol,
			TimePmSymbol,
			DateShortFormat,
			DateSeparator,
			DateLongFormat,
			IsObsolete,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	   FROM sConfig.tGlobalizationSetting
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pGlobalizationTableResource]
	@rUserId [smallint]
WITH EXECUTE AS CALLER
AS
BEGIN
SET NOCOUNT ON 
	SELECT 
		UCRK.UiCultureId,
		UCRK.UiResourceKeyId,
		UCRK.UiResourceKeyValue,
		UCRK.Remark
	FROM (SELECT DISTINCT UiCultureId FROM sSecurity.tUserLog WHERE IsOnline = 1
														AND UserId = @rUserId )UL
		INNER JOIN sConfig.tUiCultureResourceKey UCRK
			ON UCRK.UiCultureId = UL.UiCultureId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pGridPageSizeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN   
		SELECT    
		  PS.Id,
		  PS.ScreenId,
		  PS.ControlRemark,
		  PS.ControlName,
		  PS.NumberOfRows       
		FROM   
		sConfig.tGridPageSize PS  
		   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pImportAdd]
	@rOrgId [smallint],	
	@rImportTypeId int,
	@rRemark nvarchar(500),
	@rCreatedUserId bigint,
	@rResult int = 0 OUTPUT
	
WITH EXECUTE AS CALLER
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sConfig.tImport', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sConfig.tImport
	(
		Id,
		ImportTypeId, 
		Remark,
		CreatedUserId,
		CreatedDateTime,
		OrgId
	)
	VALUES
	(
		@lNextNumber,
		@rImportTypeId,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rOrgId
	)
	
	SET @rResult = @lNextNumber
	SELECT @lNextNumber AS Result
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pimportGet]
           
 
AS
SET NOCOUNT ON

BEGIN

 SELECT  
         I.Id As ImportId,
         ISNULL(I.Remark,'') AS Remark, 
         ISNULL(Title,'') AS ImportType,
         I.ImportTypeId

  FROM  sConfig.tImport I INNER JOIN sConfig.tImportTypeMaster ITM
  ON ITM.Id = I.ImportTypeId
  
  
  ORDER BY I.Id
   
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pLocalDeviceSettingAdd]
	@rOrgId [smallint],
	@rId [smallint],
	@rDeviceId [smallint],
	@rMachineTitle [nvarchar](50),
	@rPath [nvarchar](300),
	@rIsObsolete [bit]
WITH EXECUTE AS CALLER
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sConfig.tLocalDeviceSetting', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sConfig.tLocalDeviceSetting
	(
		Id,
		DeviceId,
		MachineTitle,
		Path,
		IsObsolete,
		OrgId
	)
	VALUES
	(
		@lNextNumber,
		@rDeviceId,
		@rMachineTitle,
		@rPath,
		@rIsObsolete,
		@rOrgId
	)
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pLocalDeviceSettingGetByDevice]
    @rOrgId [smallint],
	@rId [smallint] = 0,
	@rUId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rUId = 0

CREATE TABLE #tmpGlobalizationTableResource
	(
		  UiCultureId INT,
		  UiResourceKeyId SMALLINT,
		  UiResourceKeyValue NVARCHAR(300),
		  Remark NVARCHAR(300)
	) 

INSERT INTO #tmpGlobalizationTableResource
EXECUTE sConfig.pGlobalizationTableResource @rUserId = @rUId


SELECT   SGTR.UiResourceKeyValue AS Title, sConfig.tLocalDeviceSetting.Path, 
sConfig.tLocalDeviceSetting.MachineTitle, 
sConfig.tDeviceMaster.Id AS DeviceId, 
ISNULL(sConfig.tLocalDeviceSetting.Id, 0) AS Id,
sConfig.tDeviceMaster.TitleResourceKeyId AS ItemResourceKey 
FROM     sConfig.tLocalDeviceSetting RIGHT OUTER JOIN
         sConfig.tDeviceMaster ON sConfig.tLocalDeviceSetting.DeviceId = sConfig.tDeviceMaster.Id INNER JOIN
         sConfig.tDeviceTypeMaster ON sConfig.tDeviceMaster.DeviceTypeId = sConfig.tDeviceTypeMaster.Id
         LEFT JOIN #tmpGlobalizationTableResource AS SGTR
			ON sConfig.tDeviceMaster.TitleResourceKeyId = SGTR.UiResourceKeyId
         
WHERE     ((sConfig.tDeviceTypeMaster.Id  = @rId) OR (@rId = 0))
		   AND sConfig.tLocalDeviceSetting.OrgId = @rOrgId

DROP TABLE #tmpGlobalizationTableResource
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pLocalDeviceSettingModify]
	@rOrgId [smallint],
	@rId [smallint],
	@rDeviceId [smallint],
	@rMachineTitle [nvarchar](50),
	@rPath [nvarchar](300),
	@rIsObsolete [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sConfig.tLocalDeviceSetting
		SET 
			DeviceId = @rDeviceId,
			MachineTitle = @rMachineTitle,
			Path = @rPath,
			IsObsolete = @rIsObsolete
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pMachinePrinterMappingAdd]
	@rOrgId [smallint],
	@rMachineId [int],
	@rPrinterId [int],
	@rCreatedUserId [bigint],
	@rIsObsolete [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sConfig.tMachinePrinterMapping WHERE MachineId = @rMachineId AND PrinterId = @rPrinterId AND orgId = @rOrgId)

BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sConfig.tMachinePrinterMapping', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sConfig.tMachinePrinterMapping
		(
			Id,
			MachineId,
			PrinterId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,			
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rMachineId,
			@rPrinterId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),			
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pMachinePrinterMappingGet]
	@rOrgId [smallint],
	@rId [int] = 0,
	@rMachineId [int] = 0,
	@rPrinterId [int] = 0,
	@rMachineName [nvarchar](100) = '',
	@rPrinterName [nvarchar](100) = '',
	@rIsWildCardSearch [bit] = 1,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

      IF @rIsWildCardSearch = 1
            BEGIN
                  SET @rMachineName = sCommon.fSearchStringGet(@rMachineName)
                  SET @rPrinterName = sCommon.fSearchStringGet(@rPrinterName)
            END
            
      

      SELECT MPM.Id,
                  MPM.MachineId,
                  MM.Name AS MachineName,
                  MM.Path AS MachineIP,
                  MPM.PrinterId,
                  PM.Name AS PrinterName,
                  PM.Path AS PrinterPath,
                  MPM.IsObsolete,
                  MPM.CreatedUserId,
                  MPM.CreatedDateTime,
                  MPM.UpdatedUserId,
                  MPM.UpdatedDateTime     
                  
      FROM sConfig.tMachinePrinterMapping MPM
            INNER JOIN sConfig.tMachineMaster MM 
            ON MPM.MachineId = MM.Id AND MM.StoreLocationId=@rStoreLocationId
            INNER JOIN sConfig.tPrinterMaster PM
            ON MPM.PrinterId = PM.Id AND PM.StoreLocationId=@rStoreLocationId
            
      WHERE ((MPM.Id = @rId) OR @rId = 0)
            AND ((MPM.MachineId = @rMachineId) OR @rMachineId = 0)
            AND ((MPM.PrinterId = @rPrinterId) OR @rPrinterId =  0)
            AND ((MM.Name LIKE @rMachineName) OR (ISNULL(@rMachineName, '') = ''))
            AND ((PM.Name LIKE @rPrinterName) OR (ISNULL(@rPrinterName, '') = ''))
            AND MPM.OrgId = @rOrgId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pMachinePrinterMappingModify]
	@rOrgId [smallint],
	@rId [int],
	@rMachineId [int],
	@rPrinterId [int],
	@rUpdatedUserId [bigint],
	@rIsObsolete [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sConfig.tMachinePrinterMapping WHERE MachineId = @rMachineId AND PrinterId = @rPrinterId AND OrgId = @rOrgId  AND Id  <> @rId)

BEGIN
	UPDATE sConfig.tMachinePrinterMapping
		SET 
			MachineId = @rMachineId,
			PrinterId = @rPrinterId,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	WHERE Id = @rId
	AND OrgId = @rOrgId
	  
	  
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pMachinePrinterMappingRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
      IF EXISTS (SELECT Id FROM sConfig.tMachinePrinterMapping WHERE Id = @rId)
      BEGIN
            UPDATE sConfig.tMachinePrinterMapping
                  SET IsObsolete = 1
            WHERE Id = @rId
            SELECT 1 AS Result
      END
      ELSE
      BEGIN
            SELECT -100 AS Result
      END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pMenuShortcutKeyGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id AS MenuId, 
			ParentMenuId, 
			Title, 
			ShortCutKey
	   FROM sSecurity.tMenu
	   WHERE ShortCutKey is not null
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pResourceKeyValueAdd]
	@rTableName [nvarchar](500),
	@rKeyColumnName [nvarchar](500),
	@rValueColumnName [nvarchar](500),
	@rRowID [int],
	@rResourceValue [nvarchar](500),
	@rRemark [nvarchar](500)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 DECLARE @lTitle							NVARCHAR(500)
 DECLARE @lUiCultureResourceKeyId			INT
 DECLARE @lUiCultureResourceKeyIdNextNumber	BIGINT
 DECLARE @lUiCultureId						SMALLINT
 DECLARE @lSqlQry							NVARCHAR(4000)
 DECLARE @lIsError							BIT
 
BEGIN

BEGIN TRY
    EXEC sp_executesql @lSqlQry 
    
	CREATE TABLE #tExists
		(
		IsExist BIT
		)
		
    SET @lSqlQry = ' IF NOT EXISTS (SELECT ' + @rKeyColumnName + ' , ' +  @rValueColumnName + ' FROM ' + @rTableName + ' WHERE ID = ' + CAST(@rRowID AS NVARCHAR(10)) + ' ) ' + 
				  ' BEGIN 					
						INSERT INTO #tExists VALUES(1)
				    END '	
    EXEC sp_executesql @lSqlQry 
    IF EXISTS(SELECT 1 FROM #tExists)
		BEGIN		
			SET @lIsError = 1
			SELECT 'ROWID Does not Exixts'
			GOTO ENDLABEL
		END
    
END TRY
BEGIN CATCH
	SET @lIsError = 1
    SELECT 		
        ERROR_NUMBER() AS ErrorNumber
        , ERROR_MESSAGE() AS ErrorMessage;
    GOTO ENDLABEL
END CATCH
 

 
 SET @lUiCultureId	=	1 
 SET @lTitle			=	@rTableName + '_' + @rValueColumnName + '_' + CAST(@rRowID AS NVARCHAR(3)) 
 SET @lUiCultureResourceKeyId = (SELECT Id FROM sConfig.tUiResourceKeyMaster WHERE Title = @lTitle) 
   
 IF(@lUiCultureResourceKeyId IS NULL)
 BEGIN

	EXECUTE sCommon.pTableRowIdGet @rTableTitle = 'sConfig.tUiResourceKeyMaster', 
											@rIsCurrentNumber = 0, @rSeed = 1, @rIncrement = 1,@outNextNumber = @lUiCultureResourceKeyIdNextNumber output

	INSERT INTO sConfig.tUiResourceKeyMaster
	(	ID,
		Title
	)
	VALUES
	(	@lUiCultureResourceKeyIdNextNumber,
		@lTitle
	)
		
	SET @lUiCultureResourceKeyId = @lUiCultureResourceKeyIdNextNumber
	
	---SELECT @lUiCultureResourceKeyIdNextNumber
	
 END
 
 IF EXISTS(SELECT 1 FROM sConfig.tUiCultureResourceKey WHERE UiCultureId = @lUiCultureId AND UiResourceKeyId = @lUiCultureResourceKeyId)
 BEGIN
	UPDATE sConfig.tUiCultureResourceKey
	SET
		UiResourceKeyValue = @rResourceValue,
		Remark = @rRemark
	WHERE 
		UiCultureId = @lUiCultureId AND UiResourceKeyId = @lUiCultureResourceKeyId
 END
 ELSE
 BEGIN
	INSERT INTO sConfig.tUiCultureResourceKey
	(	
		UiCultureId,
		UiResourceKeyId,
		UiResourceKeyValue,
		Remark
	)
	VALUES	
	(	@lUiCultureId,
		@lUiCultureResourceKeyId,
		@rResourceValue,
		@rRemark
	)
 END
   
 SET @lSqlQry = 'UPDATE ' + @rTableName +
					' SET ' + @rKeyColumnName + ' = ' + CAST(@lUiCultureResourceKeyId AS NVARCHAR(10)) +
			   ' WHERE ID = ' + CAST(@rRowID AS NVARCHAR(10)) + 
		   
		   ' SELECT ' + @rKeyColumnName + ' , ' + @rValueColumnName + ' FROM ' + @rTableName + ' WHERE ID = ' + CAST(@rRowID AS NVARCHAR(10))
			
  EXEC sp_executesql @lSqlQry 
  
  --SELECT 1 FROM sConfig.tUiCulture 
  SELECT Id , Title FROM sConfig.tUiResourceKeyMaster WHERE ID = @lUiCultureResourceKeyId
  SELECT UiCultureId , UiResourceKeyId , UiResourceKeyValue , Remark FROM sConfig.tUiCultureResourceKey WHERE UiResourceKeyId = @lUiCultureResourceKeyId
  
  ENDLABEL:
	DROP TABLE #tExists
	IF (@lIsError = 1)
	  SELECT 'ERROR OCCURED'	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pSettingColorLegendValueGet]
	@rOrgId [int] = 0,
	@rScreenId [int] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--DECLARE @lScreenName dNvarchar300
--SELECT @lScreenName = Replace(Title, ' ', '') FROM sSecurity.tScreen WHERE Id = @rScreenId

	--SELECT 
	--	 Id,
	--	 Title,
	--	 ItemKey,
	--	 ItemValue
	--	 FROM sConfig.tSetting 
	--	 WHERE 
	--		ItemKey like @lScreenName + '%' AND ValidationTypeId = 4
	
	SELECT 
		CLM.Id,
		CLD.Title,
		CS.ItemKey,
		CS.ItemValue
   FROM sConfig.tColorLegendMaster CLM
	INNER JOIN sConfig.tColorLegendDetail CLD ON CLD.ColorLegendId = CLM.Id
	INNER JOIN sConfig.tConfigurationMaster CS ON CS.Id = CLD.configSettingId 
	WHERE CLM.Id = @rScreenId AND CS.ValidationTypeId = 4
	AND CLD.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pSettingModifyKeyValue_old]
	@rId [smallint],
	@rItemValue [nvarchar](100),
	@rUpdatedUserId [bigint],
	@rUpdatedDateTime [datetime]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
       UPDATE sConfig.tSetting
            SET               
                  ItemValue = @rItemValue,
                  UpdatedUserId = @rUpdatedUserId,
                  UpdatedDateTime  = @rUpdatedDateTime
        WHERE Id = @rId
        
        
        DECLARE @lStatus Bit
        
        IF @rId = 22
        BEGIN
            IF @rItemValue = 'True' 
            SET @lStatus = 0
            ELSE
            SET @lStatus = 1
            
            UPDATE sSecurity.tMenu SET IsObsolete = @lStatus WHERE Id = 181610
        END
        
        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pSettingValueForKeyGet]
	@rItemKey [nvarchar](100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			ItemKey,	
			ItemValue					
	   FROM sConfig.tSetting
	  WHERE  ItemKey = @rItemKey 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pSettingValueGet]
	@rId [smallint] = 0,
	@rSettingId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			ItemValue,
			ConfigurationId,
			IsObsolete			
	   FROM sConfig.tConfigurationValue
	  WHERE ((Id = @rId) OR (ConfigurationId = @rSettingId))
		AND (IsObsolete = 0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pShortcutKeyGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		SELECT  
			FS.ID,
			FS.FunctionalityName,
			FS.AccessKeyCode,			
			CS.ControlName,
			CS.ScreenId,
			CS.AssociatedControlName
		
		FROM 
			sConfig.tFunctionalityShortcutKey FS
		INNER JOIN 
			sConfig.tControlShortcutKey CS ON FS.ID = CS.FunctionalityShortcutKeyId
		WHERE FS.IsActive = 1
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pUiCultureGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title,
			DisplayTitle,
			EnglishTitle
	   FROM sConfig.tUiCulture
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sConfig].[pUiResourceKeyGet]
	@rId [tinyint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Title
	   FROM sConfig.tUiResourceKey
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sConfig].[pWebNotificationConfigGet]
	@rOrgGroupId int
	
AS
BEGIN
CREATE TABLE #tmp
(
apiKey nvarchar(max),
authDomain nvarchar(max),
projectId nvarchar(max),
storageBucket nvarchar(max),
messagingSenderId nvarchar(max),
appId nvarchar(max),
measurementId nvarchar(max)
)

INSERT INTO #tmp
(apiKey,authDomain,projectId,storageBucket,messagingSenderId,appId,measurementId)
VALUES
(
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (499) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (500) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (501) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (502) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (503) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (504) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (505) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId)
)
SELECT * FROM #tmp
DROP TABLE #tmp
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sCRM].[pOrgGroupSetting]

		@rPaymentDueDate Date =null,
		@rIsPaymentReminder bit=0,
		@rPaymentRemainderRemark nvarchar(300) = '',
		@rstudentExtraCap int=0,
		@rLastStudentCapReminderDate date = null,
		@rStudentCapReminderCount smallint=0,
		@rStudentCapReminderDate date =null,
		@rIsStopServiceReminder bit=0,
		@rServiceStopRemark nvarchar(300)='',
		@rServiceStopDate date=null,
		@rOrgGroupId int =0,
		@rNumberOfStudent int = 0
		
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	UPDATE sSetup.tOrgGroupSetting
	SET 
		PaymentDueDate=@rPaymentDueDate,
		IsPaymentReminder=@rIsPaymentReminder ,
		PaymentReminderRemark=@rPaymentRemainderRemark,
		--StudentExtraCap=@rstudentExtraCap,
		LastStudentCapReminderDate=@rLastStudentCapReminderDate,
		StudentCapReminderCount=@rStudentCapReminderCount,
		StudentCapReminderDate=@rStudentCapReminderDate,
		IsStopServiceReminder=@rIsStopServiceReminder,
		ServiceStopRemark=@rServiceStopRemark,
		ServiceStopDate=@rServiceStopDate,
		UpdatedDate=sCommon.fGetDate()
		--NoOfStudent=@rNumberOfStudent
	WHERE 
		OrgGroupId = @rOrgGroupId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pAutoGenerateQuestionGet]
	
	@rTopicId nvarchar(max)
 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  
	SELECT Id,Marks,TopicId,DifficultyLevelId,ISNULL(GroupQuestionId,0) AS  GroupQuestionId
	FROM sEExam.tQuestionMaster Where TopicId IN (select item from [sCommon].[fnSplit](@rTopicId,',')) 	 
	--Order By RAND(Id)  
	 --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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pAvailableCheckingTestsGet]

		--@rUserSourceTypeId smallint,
		--@rUserSourceId bigint,
		@rBatchId int,
		@rFromDate date=NULL,
		@rToDate date=NULL,
		@rTestId int
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN  
	
  SELECT  
		TP.Id AS TestParticipantId,		
		TM.Title AS Test,
		VCS.SubjectName,
		TM.Id AS TestId,
		TM.TotalMarks,
		ISNULL(SM.Title,'')AS TestStatus,
		TP.TestStatusId,
		[sEExam].[fCheckIsHTMLGet](TM.Id) AS IsHtml,
		TM.IsDisplayResultOnComplete,
		TM.IsAllowReview,
		ISNULL(TM.TestStartupRemark,'') AS TestStartupRemark,
		ISNULL(TM.TestDuration,0) AS TestDuration,
		ISNULL(TM.AlertDuration,0) AS AlertDuration,
		TM.FromTime,
		TM.ToTime,
		ISNULL(TM.FromDate,'')AS FromDate,
		ISNULL(TM.ToDate,'')AS ToDate,
		ISNULL(((CAST(TM.FromDate as DATETIME) + CAST(TM.FromTime as TIME))),'')AS FromDateTime,
		ISNULL(((CAST(TM.ToDate as DATETIME) + CAST(TM.ToTime as TIME))),'')AS ToDateTime,
		VSA.Name,
		VSA.RollNo,
		VSA.Code,
		ISNULL(TP.ScoredMarks,0)AS ScoredMarks,
		(VSA.ClassName+'-'+VSA.DivisionName)AS ClassDivisionName
		

  FROM 
	    sEExam.tTestParticipant TP 
		INNER JOIN sEExam.tTestMaster TM ON TM.Id=TP.TestId 
		INNER JOIN sSetup.vClassSubject VCS ON VCS.ClassSubjectId=TM.ClassSubjectId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id=TP.TestStatusId
		INNER JOIN sStudent.vStudentAcademic VSA ON VSA.StudentId = TP.SourceId AND TP.SourceTypeId=2003 AND TM.BatchId= VSA.BatchId
		
WHERE 
		--TP.SourceId=@rUserSourceId 
		--AND TP.SourceTypeId = @rUserSourceTypeId 
	    TM.BatchId = @rBatchId
		AND IsTestLock = 1
		AND ((TM.TestDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((TM.TestDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND TP.TestStatusId !=0 
		--AND TP.TestStatusId=724
		AND TM.Id=@rTestId
		--AND SM.Id=724
	    ORDER BY TP.TestStatusId,TP.TestId DESC 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pAvailableTestsGet]

		@rUserSourceTypeId smallint,
		@rUserSourceId bigint,
		@rBatchId int,
		@rFromDate date=NULL,
		@rToDate date=NULL
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN  
	
  SELECT  
		TP.Id AS TestParticipantId,		
		TM.Title AS Test,
		VCS.SubjectName,
		TM.Id AS TestId,
		TM.TotalMarks,
		ISNULL(SM.Title,'')AS TestStatus,
		TP.TestStatusId,
		[sEExam].[fCheckIsHTMLGet](TM.Id) AS IsHtml,
		TM.IsDisplayResultOnComplete,
		TM.IsAllowReview,
		ISNULL(TM.TestStartupRemark,'') AS TestStartupRemark,
		ISNULL(TM.TestDuration,0) AS TestDuration,
		ISNULL(TM.AlertDuration,0) AS AlertDuration,
		TM.FromTime,
		TM.ToTime,
		ISNULL(TM.FromDate,'')AS FromDate,
		ISNULL(TM.ToDate,'')AS ToDate,
		ISNULL(((CAST(TM.FromDate as DATETIME) + CAST(TM.FromTime as TIME))),'')AS FromDateTime,
		ISNULL(((CAST(TM.ToDate as DATETIME) + CAST(TM.ToTime as TIME))),'')AS ToDateTime,
		(CASE WHEN TM.TestTypeId=726 THEN 'Subjective' ELSE 'Objective' END)AS TestType,
		TM.TestDate,
		ISNULL(TM.NegativeMarkPerAnswer,0.00) AS NegativeMarkPerAnswer,
		ISNULL(TM.IsUploadImage,0)AS IsUploadImage,
		ISNULL(TM.IsQuestionRemark,0)AS IsQuestionRemark,
		ISNULL(TP.TimeTaken, '') AS TimeTaken
  FROM 
	    sEExam.tTestParticipant TP 
		INNER JOIN sEExam.tTestMaster TM ON TM.Id=TP.TestId 
		INNER JOIN sSetup.vClassSubject VCS ON VCS.ClassSubjectId=TM.ClassSubjectId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=TP.TestStatusId
WHERE 
		TP.SourceId=@rUserSourceId 
		AND TP.SourceTypeId = @rUserSourceTypeId 
		AND TM.BatchId = @rBatchId
		AND IsTestLock = 1
		AND ((TM.TestDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((TM.TestDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND TP.TestStatusId !=0
	    ORDER BY TP.TestStatusId,TP.TestId DESC 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sEExam].[pAvailableTestsReviewGet]
	 	 
	 @rTestId int,
	 @rTestParticipantId bigint
	 	 
     WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 

BEGIN 
DECLARE @lTestTypeId int
Select @lTestTypeId=TestTypeId from sEExam.tTestMaster Where Id=@rTestId

IF(@lTestTypeId = 725)
BEGIN
	SELECT 
		ROW_NUMBER() OVER(ORDER BY TQ.OrderIndex) AS RowIndex,
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.QuestionDescription2,
		TQ.Marks AS QuestionMarks,
		QM.IsObsolete,
		ISNULL(TQ.OrderIndex,0) AS OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId  ,
		ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParagraphDescription,
		ISNULL(QM.QuestionParagraphId,0) AS QuestionParagraphId,
		TP.Id AS TestParticipantId,
		TP.TestId,
		TP.SourceTypeId,
		TP.SourceId,
		TP.TestDate,
		TP.StartTime,
		TP.EndTime,
		TP.TestStatusId,
		CASE WHEN TP.TestStatusId = 543 THEN 'Not Started' WHEN TP.TestStatusId = 544 THEN 'Started' WHEN TP.TestStatusId = 545 THEN 'Completed' ELSE '' END AS TestStatus,
		TP.TotalMarks,
		TP.ScoredMarks,
		TP.TotalQuestions,
		TP.RightQuestions,
		TP.WrongQuestions,
		TP.SkippQuestions,
		TP.NotAttemptedQuestions,
		ISNULL(TPA.QuestionOptionId,0) AS QuestionOptionId,
		ISNULL(TPA.AnswerStatusId,0) AS AnswerStatusId,
		CASE WHEN TPA.AnswerStatusId = 531 THEN 'Attempted' WHEN TPA.AnswerStatusId = 532 THEN 'Not Attempted' WHEN  TPA.AnswerStatusId = 533 THEN 'Skipped' ELSE '' END AS  AnswerStatus,
		ISNULL(TPA.ScoredMark,0) AS QuestionScoredMark,
		QO.Id AS QuestionOptionKeyId,
		ISNULL(NegativeMarkPerAnswer,0) AS NegativeMarkPerAnswer,TMT.Title AS ExamTitle,VCS.SubjectName,
		ISNULL(TPA.QuestionAnswerRemark,'')AS QuestionAnswerRemark,
		ISNULL(TPA.QuestionAnswer,'') AS QuestionAnswer
	
 	FROM 
		sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
		ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
		ON DLM.Id=QM.DifficultyLevelId
		INNER JOIN sEExam.tTestQuestion TQ
		ON TQ.QuestionId=QM.Id      
		INNER JOIN sEExam.tTestParticipant TP
		ON TP.TestId = TQ.TestId
		LEFT JOIN sEExam.tQuestionParagraph QP ON QP.Id=QM.QuestionParagraphId
		LEFT JOIN sEExam.tTestParticipantAnswer TPA ON TPA.TestParticipantId=TP.Id AND TPA.QuestionId = QM.Id
		INNER JOIN sEExam.tQuestionOption QO ON QO.QuestionId = QM.Id AND QO.IsKey = 1
	    INNER JOIN sEExam.tTestMaster TMT ON TMT.Id = TP.TestId
		INNER JOIN sSetup.vClassSubject VCS	ON VCS.ClassSubjectId=TMT.ClassSubjectId
		
	WHERE 
		TQ.TestId=@rTestId AND TP.Id = @rTestParticipantId
	    ORDER BY TQ.OrderIndex
END
ELSE
BEGIN
SELECT 
		ROW_NUMBER() OVER(ORDER BY TQ.OrderIndex) AS RowIndex,
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.QuestionDescription2,
		TQ.Marks AS QuestionMarks,
		QM.IsObsolete,
		ISNULL(TQ.OrderIndex,0) AS OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId  ,
		ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParagraphDescription,
		ISNULL(QM.QuestionParagraphId,0) AS QuestionParagraphId,
		TP.Id AS TestParticipantId,
		TP.TestId,
		TP.SourceTypeId,
		TP.SourceId,
		TP.TestDate,
		TP.StartTime,
		TP.EndTime,
		TP.TestStatusId,
		CASE WHEN TP.TestStatusId = 543 THEN 'Not Started' WHEN TP.TestStatusId = 544 THEN 'Started' WHEN TP.TestStatusId = 545 THEN 'Completed' ELSE '' END AS TestStatus,
		TP.TotalMarks,
		TP.ScoredMarks,
		TP.TotalQuestions,
		TP.RightQuestions,
		TP.WrongQuestions,
		TP.SkippQuestions,
		TP.NotAttemptedQuestions,
		ISNULL(TPA.QuestionOptionId,0) AS QuestionOptionId,
		ISNULL(TPA.AnswerStatusId,0) AS AnswerStatusId,
		CASE WHEN TPA.AnswerStatusId = 531 THEN 'Attempted' WHEN TPA.AnswerStatusId = 532 THEN 'Not Attempted' WHEN  TPA.AnswerStatusId = 533 THEN 'Skipped' ELSE '' END AS  AnswerStatus,
		ISNULL(TPA.ScoredMark,0) AS QuestionScoredMark,
		QO.Id AS QuestionOptionKeyId,
		ISNULL(NegativeMarkPerAnswer,0) AS NegativeMarkPerAnswer,TMT.Title AS ExamTitle,VCS.SubjectName,
		ISNULL(TPA.QuestionAnswerRemark,'')AS QuestionAnswerRemark,
		ISNULL(TPA.QuestionAnswer,'') AS QuestionAnswer
	
 	FROM 
		sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
		ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
		ON DLM.Id=QM.DifficultyLevelId
		INNER JOIN sEExam.tTestQuestion TQ
		ON TQ.QuestionId=QM.Id      
		INNER JOIN sEExam.tTestParticipant TP
		ON TP.TestId = TQ.TestId
		LEFT JOIN sEExam.tQuestionParagraph QP ON QP.Id=QM.QuestionParagraphId
		LEFT JOIN sEExam.tTestParticipantAnswer TPA ON TPA.TestParticipantId=TP.Id AND TPA.QuestionId = QM.Id
		INNER JOIN sEExam.tQuestionOption QO ON QO.QuestionId = QM.Id 
	    INNER JOIN sEExam.tTestMaster TMT ON TMT.Id = TP.TestId
		INNER JOIN sSetup.vClassSubject VCS	ON VCS.ClassSubjectId=TMT.ClassSubjectId
		
	WHERE 
		TQ.TestId=@rTestId AND TP.Id = @rTestParticipantId
	    ORDER BY TQ.OrderIndex
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pAvailableTestsReviewOptionListGet]

	 @rTestParticipantId bigint 
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT
		ISNULL(TP.Id,0) AS TestParticipantId, 
		TP.TestId,
		TP.SourceId,
		TP.SourceTypeId,
		QM.Id AS QuestionId,
		QO.Id AS QuestionOptionId,		
		QM.QuestionDescription AS QuestionDescription,
		ISNULL(QM.QuestionDescription2,'') AS QuestionDescription2,
		QO.ChoiceDescription AS ChoiceDescription,
		ISNULL(QO.ChoiceDescription2,'') AS ChoiceDescription2,		
		QM.Marks AS QuestionMarks,
		QO.IsKey,
		ISNULL(Qp.QuestionParagraphDescription,'') AS QuestionParagraphDescription ,
		TM.TestDuration,
		ISNULL(TM.IsDisplayResultOnComplete,0) AS IsDisplayResultOnComplete,
		ISNULL(TM.IsAutoFinishOnTime,0) AS IsAutoFinishOnTime,
		ISNULL(TPA.QuestionOptionId,0) AS AnweredQuestionOptionId,
		TPA.AnswerStatusId,
		ISNULL(TPA.OrderIndex,0)AS OrderIndex,		
		CASE
		WHEN (TPA.QuestionOptionId = QO.Id AND QO.IsKey = 1 ) THEN 'Right'
		WHEN (TPA.QuestionOptionId = QO.Id AND QO.IsKey = 0) THEN 'Wrong'
		WHEN (QO.IsKey = 1) THEN 'Right' 
		ELSE '' END AS QuestionStatus,
		convert(bit,0) as SelectOption,
		ISNULL(AlertDuration,0) AS AlertDuration,
		ISNULL(NegativeMarkPerAnswer,0) AS NegativeMarkPerAnswer,
		ISNULL(TPA.QuestionAnswerRemark,'')AS QuestionAnswerRemark
		
FROM 
		sEExam.tTestParticipant TP 
		INNER JOIN sEExam.tTestMaster TM ON TP.TestId = TM.Id
		INNER JOIN sEExam.tTestQuestion TQ ON  TQ.TestId = TP.TestId
		INNER JOIN sEExam.tQuestionMaster QM ON TQ.QuestionId = QM.Id 		
		INNER JOIN sEExam.tQuestionOption QO ON QO.QuestionId=QM.Id 
	    LEFT JOIN sEExam.tTestParticipantAnswer TPA ON TP.Id = TPA.TestParticipantId AND TPA.QuestionId = TQ.QuestionId AND TPA.TestId = TQ.TestId	  
		LEFT JOIN sEExam.tQuestionParagraph QP ON Qp.Id = QM.QuestionParagraphId
		
WHERE  
        TP.Id = @rTestParticipantId
	    ORDER BY QO.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pCreateQuestionGroup]
     
      @rQuestionIdGroup nvarchar(max),
      @rQuestionGroupId bigint,
      @rIsCreate bit
     
AS 

BEGIN TRY
BEGIN TRANSACTION	

 IF(@rIsCreate=1)
 
  BEGIN   
     
     UPDATE sEExam.tQuestionMaster    
     SET GroupQuestionId = @rQuestionGroupId    
     Where Id IN (select item from [sCommon].[fnSplit](@rQuestionIdGroup,',')) 
     
     Select 1 AS Result
     
  END
  ELSE
   BEGIN
      UPDATE sEExam.tQuestionMaster
      SET GroupQuestionId = NULL
      Where Id IN (select item from [sCommon].[fnSplit](@rQuestionIdGroup,','))    
      
      Select 1 AS Result
      
   END
   
  COMMIT TRANSACTION
	
	END TRY
	BEGIN CATCH
	SELECT -1 AS Result
	END CATCH

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pDataBankMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(50)
           ,@rTitle nvarchar(50)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint        
           ,@rOrgGroupId smallint
           ,@rAffiliationId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sEExam.tDataBankMaster where Code=@rCode AND OrgGroupId = @rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END  
	END
	ELSE
	BEGIN
 
		If  Exists(select Id from sEExam.tDataBankMaster where Code=@rCode AND Id<>@rId AND OrgGroupId = @rOrgGroupId)
		Begin
			select -103 as Result
			RETURN
		End

	END
		
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tDataBankMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO [sEExam].[tDataBankMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId]
           ,[AffiliationId])
     VALUES
           (
            @lNextNumber 
           ,@rCode
           ,@rTitle
           ,@rIsObsolete
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rOrgGroupId
           ,@rAffiliationId
           )
           
           INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2012
		   ,@lNextNumber
		   ,@rCreatedUserId			
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
		UPDATE [sEExam].[tDataBankMaster]
		   SET  
			   [Code] = @rCode 
			  ,[Title] = @rTitle 
			  ,[IsObsolete] = @rIsObsolete  
			  ,[UpdatedUserId] = @rCreatedUserId 
			  ,[UpdatedDateTime] = sCommon.fGetDate()	      
			  ,[AffiliationId] = @rAffiliationId 	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pDataBankMasterGet]
	 @rId int = 0,
	 @rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20), 
	 @rOrgGroupId smallint = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
  SELECT   
		  DSM.[Id]
		  ,DSM.[Code]
		  ,DSM.[Title]     
		  ,[CreatedUserId]
		  ,[CreatedDateTime]
		  ,[UpdatedUserId]
		  ,[UpdatedDateTime]
		  ,[OrgGroupId]
		  ,[AffiliationId]
		  ,AM.Title AS AffiliationName
		  ,DSM.IsObsolete
      
  FROM    
	      [sEExam].[tDataBankMaster] DSM
		  INNER JOIN sSetup.tAffiliationMaster AM ON DSM.AffiliationId= AM.Id 
  WHERE		
          ((DSM.Id = @rId) OR (@rId = 0))
          AND  ((DSM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
          AND  ((DSM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
          AND  (DSM.AffiliationId = @rAffiliationId OR @rAffiliationId = 0) 
          AND DSM.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sEExam].[pDataSubjectMasterAdd]
	 
	@rId int,
	@rDataBankId int,
	@rCode nvarchar(20),
	@rNumber int,
	@rTitle nvarchar(100),
	@rIsObsolete bit,
	@rOrderIndex int,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	
		IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sEExam.tDataSubjectMaster where Code=@rCode AND DataBankId = @rDataBankId )
			BEGIN
			select -103 as Result
			RETURN
		END 
 
	END
	ELSE
	BEGIN
 
		If  Exists(select Id from sEExam.tDataSubjectMaster where Code=@rCode AND Id<>@rId AND DataBankId = @rDataBankId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	
	 --BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tDataSubjectMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sEExam.tDataSubjectMaster
		(
			Id,
			DataBankId,
			Code,
			Number,
			Title,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rDataBankId,
			@rCode,
			@rNumber,
			@rTitle,
			@rIsObsolete,
			@rOrderIndex,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sEExam.tDataSubjectMaster
	    SET
	      --AffiliationId=@rAffiliationId,
	      Code=@rCode,
	      Number=@rNumber,
	      Title=@rTitle,
	      IsObsolete=@rIsObsolete,
	      OrderIndex=@rOrderIndex,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate() 
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
	--	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sEExam].[pDataSubjectMasterGet]
	 @rId int = 0,
	 @rDataBankId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
	DSM.Id, 
	DSM.Code,
	DSM.Number,
	DSM.Title,
	DSM.IsObsolete,
	DSM.OrderIndex 
      
  FROM sEExam.tDataSubjectMaster DSM         
             
  WHERE 		
      ((DSM.Id = @rId) OR (@rId = 0))
      AND  ((DSM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      AND  ((DSM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))    
      AND DataBankId = @rDataBankId  
     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sEExam].[pDataTopicMasterAdd]
	 
	@rId int,
	--@rAffiliationId int,
	--@rCode nvarchar(20),
	@rCode nvarchar(100),
	@rNumber int,
	@rTitle nvarchar(100), 
	@rClassGroupId int,
	@rDataTopicTypeId int, 
	@rIsObsolete bit,
	--@rOrderIndex int,
	@rCreatedUserId bigint,  
	@rOrgGroupId int,
	@rDataSubjectId int,
	@rDataBankId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	
		IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sEExam.tDataTopicMaster where Code=@rCode AND DataBankId  = @rDataBankId AND DataSubjectId = @rDataSubjectId AND ClassGroupId =@rClassGroupId )
			BEGIN
			select -103 as Result
			RETURN
		END 
 
	END
	ELSE
	BEGIN
 
		If  Exists(select Id from sEExam.tDataTopicMaster where Code=@rCode AND DataBankId  = @rDataBankId AND DataSubjectId = @rDataSubjectId AND ClassGroupId =@rClassGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tDataTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sEExam.tDataTopicMaster
		(
			Id,
			--AffiliationId,
			Code,
			Number,
			Title,
			DataSubjectId,
			ClassGroupId,
			DataTopicTypeId,
			IsObsolete,
			OrgGroupId,
	 		DataBankId,
			--OrderIndex,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			--@rAffiliationId,
			@rCode,
			@rNumber,
			@rTitle,	
			@rDataSubjectId,	
			@rClassGroupId,
			@rDataTopicTypeId,
			@rIsObsolete,
			@rOrgGroupId,
			@rDataBankId,
			--@rOrderIndex,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sEExam.tDataTopicMaster
	    SET
	      --AffiliationId=@rAffiliationId,
	      Code=@rCode,
	      Number=@rNumber,
	      Title=@rTitle,
	      ClassGroupId=@rClassGroupId,
	      DataSubjectId = @rDataSubjectId,
	      DataTopicTypeId = @rDataTopicTypeId,
	      IsObsolete = @rIsObsolete,
	      --OrderIndex=@rOrderIndex,
	      UpdatedUserId = @rCreatedUserId,
	      UpdatedDateTime = sCommon.fGetDate()
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sEExam].[pDataTopicMasterGet]
	 
	 @rId int = 0,
	 @rDataBankId int,
	 @rDataSubjectId int,
	 @rTitle nvarchar(100), 
	 @rCode nvarchar(120),
	 @rClassGroupId int,
	 @rAffiliationId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	  BEGIN	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  END
	 
	SELECT 
	DTM.Id,
	--DSM.AffiliationId,
	DTM.Code   AS Code,
	DTM.Number,
	DTM.Title  AS DataTopicName,
	DTM.IsObsolete,
    DCGS.Title AS DataSubject,
    DCGS.Id    AS DataSubjectId,    
	--TTM.OrderIndex,	 
	TTM.Title  AS TopicTypeName,
	TTM.Id     AS TopicTypeId,
	CGM.Title  AS ClassGroupTitle,
	CGM.Id     AS ClassGroupId
	 
  FROM 
		sEExam.tDataTopicMaster DTM
        INNER JOIN sEExam.tDataSubjectMaster DCGS
        ON DTM.DataSubjectId=DCGS.Id         
        INNER JOIN sEExam.tDataTopicTypeMaster TTM
        ON TTM.Id=DTM.DataTopicTypeId
        INNER JOIN sSetup.vAffiliationClassGroup CGM
        ON DTM.ClassGroupId=CGM.ClassGroupId 
        
  WHERE 		
       ((DTM.Id = @rId) OR (@rId = 0))
       AND ((DTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
       AND ((DTM.Code like @rCode) OR ISNULL(@rCode,'') = '')
       AND (TTM.DataBankId = @rDataBankId OR @rDataBankId = 0)
       AND (TTM.DataSubjectId = @rDataSubjectId OR @rDataSubjectId = 0)
       AND (DTM.ClassGroupId = @rClassGroupId OR @rClassGroupId = 0)
        --AND  ((TTM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
       AND CGM.AffiliationId = @rAffiliationId 
       ORDER BY DTM.Number 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sEExam].[pDataTopicTypeMasterAdd]
	 
	@rId int,
	--@rAffiliationId int,	
	@rDataSubjectId int,
	@rCode nvarchar(20),
	@rNumber int,
	@rTitle nvarchar(100),
	@rIsObsolete bit,
	@rOrderIndex int,
	@rCreatedUserId bigint, 
	@rOrgGroupId int,
	@rDataBankId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sEExam.tDataTopicTypeMaster where Code=@rCode AND DataBankId  = @rDataBankId AND DataSubjectId = @rDataSubjectId  )
			BEGIN
			  Select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
			If Exists(select Id from sEExam.tDataTopicTypeMaster where Code=@rCode AND DataBankId  = @rDataBankId AND DataSubjectId = @rDataSubjectId AND ID <> @rId )
			BEGIN
			  Select -103 as Result
			RETURN
		END 
	END
	BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tDataTopicTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sEExam.tDataTopicTypeMaster
		(
			Id,
			--AffiliationId,
			Code,
			Number,
			Title,
			DataSubjectId,
			OrgGroupId,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			DataBankId
		)
	VALUES
		(
			@lNextNumber,
			--@rAffiliationId,
			@rCode,
			@rNumber,
			@rTitle,
			@rDataSubjectId,
			@rOrgGroupId,
			@rIsObsolete,
			@rOrderIndex,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rDataBankId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sEExam.tDataTopicTypeMaster
	    SET
	      --AffiliationId=@rAffiliationId,
	      --Code=@rCode,
	      Number=@rNumber,
	      Title=@rTitle,
	      DataSubjectId=@rDataSubjectId, 
	      IsObsolete=@rIsObsolete,
	      OrderIndex=@rOrderIndex,
	      UpdatedUserId=@rCreatedUserId,
	      UpdatedDateTime= sCommon.fGetDate() 
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pDataTopicTypeMasterGet]
	 
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rDataBankId int,
	 @rDataSubjectId int	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	  BEGIN	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END	 
	SELECT 
	TTM.Id,
	--DSM.AffiliationId,
	TTM.Code,
	TTM.Number,
	TTM.Title,
	TTM.IsObsolete,
	TTM.OrderIndex,
	TTM.OrgGroupId,
	SM.Id AS DataSubjectId,
	SM.Title AS DataSubjectName
      
  FROM  sEExam.tDataTopicTypeMaster TTM
        INNER JOIN  sEExam.tDataSubjectMaster SM  
        ON SM.Id=TTM.DataSubjectId
        
  WHERE 
        ((TTM.Id = @rId) OR (@rId = 0))
        AND  ((TTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((TTM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
        AND  (TTM.DataSubjectId = @rDataSubjectId OR @rDataSubjectId = 0)
        AND   TTM.DataBankId = @rDataBankId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pDeactiveALLTestParticipant]
	 
	 @rTestId bigint,	 
	 @rMode int	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION			   	   
		   
		  --IF(@rMode = 1)  --Activate All Participant
		  --  BEGIN
		    
				--CREATE Table #TempTestParticipant
				--(
				--   Id Int Identity(1,1), 
				--   SourceId bigint,
				--   SourceTypeId int,
				--   TestDate Date, 
				--   TotalMarks decimal(6,2)				   
				--)
		  --    SELECT StudentId FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId  
		     
		  --    UPDATE sEExam.tTestParticipant SET TestStatusId = 543 WHERE TestId = @rTestId  
		  -- 	  AND ISNULL(TestStatusId,0) NOT IN (544,545) 		   	   
			 --    -- When I Deactive Div Then Also Deactive Student Which Is Active 	   
			  
			 -- UPDATE sEExam.tTestAssign SET TestStatusId = 543 Where TestId = @rTestId 
			 -- AND ISNULL(TestStatusId,0) NOT IN (544,545) 
			  			  
			 -- SELECT 1 AS Result 			  
		  --  END	   	   
		   	    
		  -- ELSE 
		   IF(@rMode = 0) --DeActivate All Participant 
		   	 BEGIN 
		   	  UPDATE sEExam.tTestParticipant SET TestStatusId = 0 WHERE TestId = @rTestId  
		   	  AND ISNULL(TestStatusId,0) NOT IN (544,545)		   	   
			     -- When I Deactive Div Then Also Deactive Student Which Is Active 	   
			  UPDATE sEExam.tTestAssign SET TestStatusId = 0 Where TestId = @rTestId 
			  AND ISNULL(TestStatusId,0)  NOT IN (544,545) 

			  ----Delete Participant Answer
			  --DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
			  --INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
			  --WHERE TPA.TestId= @rTestId 

			  SELECT 1 AS Result  
		     END		    
		   ELSE   -- Delete All Participant
		     BEGIN
		           
		         Delete from  sEExam.tTestParticipant   WHERE TestId = @rTestId  
		   	     AND ISNULL(TestStatusId,0) NOT IN (544,545)	
		   	      		        		        
				 DELETE FROM sEExam.tTestAssign   Where TestId = @rTestId 
				 AND ISNULL(TestStatusId,0)  NOT IN (544,545) 

			   ----Delete Participant Answer
				  --DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
				  --INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
				  --WHERE TPA.TestId= @rTestId 
				  
				 SELECT 1 AS Result 
		     END 	
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pDeactiveTestParticipant]
	 
	 @rTestId bigint,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rBatchId int	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION			
		    IF(@rSourceTypeId = 2005)
			   BEGIN           
					 UPDATE  TP 
					 SET TP.TestStatusId = 0
					 FROM sEExam.tTestParticipant TP INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TP.SourceId = VSA.StudentId 
					 Where DivisionId = @rSourceId  AND TP.TestId = @rTestId AND VSA.BatchId = @rBatchId
					 --INSERT INTO sEExam.tTestParticipant
					 --Select @rTestId,2003,StudentId,@rTestDate,@rStartTime,@rEndTime,1,@rTotalMarks,@rScoredMarks,@rTotalQuestions,@rRightQuestions,@rWrongQuestions,@rNotAttemptedQuestions
					 --FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId  
			           
			         UPDATE  TA 
					 SET TA.TestStatusId = 0
					 FROM sEExam.tTestAssign TA INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TA.SourceId = VSA.StudentId 
					 Where DivisionId = @rSourceId AND TA.TestId = @rTestId AND VSA.BatchId = @rBatchId
				     
				  --   UPDATE  TP 
					 --SET TA.TestStatusId = 0
					 --FROM sEExam.tTestParticipant TP INNER JOIN sEExam.tTestAssign TA ON TP.SourceId = TA.SourceId					  
					 --WHERE  TP.SourceTypeId = 2003 AND TA.TestStatusId = 1 

					 ----Delete Participant Answer
					 --DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
					 --INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
					 --INNER JOIN sStudent.vStudentAcademic VSA ON TP.SourceId = VSA.StudentId 
					 --WHERE TPA.TestId= @rTestId  
					 --AND VSA.DivisionId = @rSourceId  AND VSA.BatchId = @rBatchId
			          
					SELECT 1 AS Result 
               END 
			ELSE 
			   BEGIN
			      UPDATE sEExam.tTestParticipant SET TestStatusId = 0 WHERE   SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
			   END			   
			   -- When I Deactive Div Then Also Deactive Student Which Is Active 
			    UPDATE sEExam.tTestAssign SET TestStatusId = 0 Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId

				----Delete Participant Answer
				--DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
				--INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
				--INNER JOIN sStudent.vStudentAcademic VSA ON TP.SourceId = VSA.StudentId 
				--WHERE TPA.TestId= @rTestId AND  TP.SourceId = @rSourceId AND TP.SourceTypeId = @rSourceTypeId
		  
			SELECT 1 AS Result 
			
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pDeleteAllTestDetail]
	 
		@rTestId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		

DELETE  sEExam.tTestQuestion
		FROM  sEExam.tTestQuestion TQ
		WHERE TQ.TestId=@rTestId
		
DELETE  sEExam.tTestAssign
		FROM  sEExam.tTestAssign TA
		WHERE TA.TestId=@rTestId		
		
DELETE  sEExam.tTestParticipantAnswer
		FROM sEExam.tTestParticipantAnswer TPA
		WHERE TPA.TestId=@rTestId
		
DELETE  sEExam.tTestParticipant
		FROM sEExam.tTestParticipant TP
		WHERE TP.TestId=@rTestId
		
DELETE  sEExam.tTestMaster
		FROM  sEExam.tTestMaster TM
		WHERE TM.Id=@rTestId				
		
			SELECT 1 AS Result
		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pDeleteAllTestParticipant]
	 
	 @rTestId bigint,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rBatchId int	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION			
		    IF(@rSourceTypeId = 2005)
			   BEGIN           
					IF EXISTS(SELECT 1  FROM sEExam.tTestParticipantAnswer WHERE TestId=@rTestId)
					BEGIN
			         DELETE TPA
					 FROM sEExam.tTestParticipantAnswer TPA
					 INNER JOIN sEExam.tTestParticipant TP  ON TP.Id = TPA.TestParticipantId
					 INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TP.SourceId = VSA.StudentId 
					 Where DivisionId = @rSourceId  AND TP.TestId = @rTestId AND VSA.BatchId = @rBatchId

					 END
					SELECT 1 AS Result 
               END 
			ELSE 
			   BEGIN
				IF EXISTS(SELECT 1  FROM sEExam.tTestParticipantAnswer WHERE TestId=@rTestId)
					BEGIN
			         DELETE TPA
					 FROM sEExam.tTestParticipantAnswer TPA
					 INNER JOIN sEExam.tTestParticipant TP  ON TP.Id = TPA.TestParticipantId
					 INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TP.SourceId = VSA.StudentId 
					 Where TP.SourceId = @rSourceId  AND TP.TestId = @rTestId AND VSA.BatchId = @rBatchId

					 END 
			   END			   
			   
		  
			SELECT 1 AS Result 
			
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pDeleteTestParticipant]
	 
		@rTestParticipantId bigint	 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		
		
DELETE  sEExam.tTestParticipantAnswer
		FROM sEExam.tTestParticipantAnswer TPA
		WHERE TPA.TestParticipantId=@rTestParticipantId
		
DELETE  sEExam.tTestParticipant
		FROM sEExam.tTestParticipant TP
		WHERE TP.Id=@rTestParticipantId
		
		SELECT 1 AS Result
		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pDeleteTestQuestion]

	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			
				IF NOT EXISTS (Select 1 FROM sEExam.tTestQuestion Where QuestionId = @rId)				   
				AND NOT EXISTS(Select 1 FROM sEExam.tTestParticipantAnswer Where QuestionId  = @rId)			   
				AND NOT EXISTS(Select 1 from sEExam.tTestTemplateQuestion where QuestionId = @rId)				
				BEGIN				   
				        
				       DELETE FROM sEExam.tQuestionMaster Where Id = @rId
				       Delete From sEExam.tQuestionOption Where QuestionId = @rId
				 	   SELECT 1 AS RESULT		
				END				   
				ELSE
					  SELECT -101 AS RESULT
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
	    SELECT 0 AS RESULT
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pDeleteTestQuestionOption]

	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			
				IF NOT EXISTS(Select 1 FROM sEExam.tTestParticipantAnswer Where QuestionOptionId  = @rId)			 				
				BEGIN	
				      DELETE FROM sEExam.tQuestionOption Where Id = @rId	 
				 	  SELECT 1 AS RESULT		
				END				   
				ELSE
					  SELECT -101 AS RESULT
					  
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
	    SELECT 0 AS RESULT
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sEExam].[pDsTestParticipantAnswerAdd]
	 
	@rTestParticipantId bigint,
	@rTestId int,
	@rQuestionDetailXml [nvarchar](max),
	@rQuestionOptionDetailXml [nvarchar](max)
	--@rQuestionAnswer nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @loQuestionDoc INT
	EXEC sp_xml_preparedocument @loQuestionDoc OUTPUT, @rQuestionDetailXml
	
	DECLARE @loQuestionOptionDoc INT
	EXEC sp_xml_preparedocument @loQuestionOptionDoc OUTPUT, @rQuestionOptionDetailXml
	
BEGIN

	BEGIN TRY	
	--BEGIN TRANSACTION
	DECLARE @lOrgGroupId int = 0
	Declare @lIDConfigValue nvarchar(50)=''

	SELECT @lOrgGroupId = OM.OrgGroupId FROM sEExam.tTestMaster TM
	INNER JOIN sSetup.tOrganizationMaster OM ON TM.OrgId = OM.Id
	WHERE TM.Id = @rTestId

	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 140 AND SourceId = @lOrgGroupId	

	IF(@lIDConfigValue = 'False')
	BEGIN
	
		DELETE FROM sEExam.tTestParticipantAnswer WHERE TestParticipantId=@rTestParticipantId AND TestId=@rTestId
	
		UPDATE sEExam.tTestParticipant
			SET
				TestDate = A.TestDate,
				StartTime = A.StartTime,
				EndTime = A.EndTime,
				TestStatusId = A.TestStatusId,
				TotalMarks = A.TotalMarks,
				ScoredMarks = A.ScoredMarks,
				TotalQuestions = A.TotalQuestions,
				RightQuestions = A.RightQuestions,
				WrongQuestions = A.WrongQuestions,
				SkippQuestions = A.SkippQuestions,
				NotAttemptedQuestions = A.NotAttemptedQuestions
				FROM
			 (
		  SELECT TOP 1
				@rTestParticipantId AS TestParticipantId,
				@rTestId AS TestId,
				TestDate,
				StartTime,
				EndTime,
				TestStatusId,
				TotalMarks,
				ScoredMarks,
				TotalQuestions,
				RightQuestions,
				WrongQuestions,
				SkippQuestions,
				NotAttemptedQuestions
			FROM OPENXML (@loQuestionDoc, '/Table/QuestionDetail', 1)
			WITH ( 
					SourceTypeId smallint,
					SourceId bigint,
					TestDate date,
					StartTime time,
					EndTime time,
					TestStatusId smallint,
					TotalMarks decimal(6,2),
					ScoredMarks decimal(6,2),
					TotalQuestions int,
					RightQuestions int,
					WrongQuestions int,
					SkippQuestions int,
					NotAttemptedQuestions int
				  ))A	
					WHERE 
					--A.TestParticipantId = @rTestParticipantId AND A.TestId = @rTestId
					--AND 
					sEExam.tTestParticipant.Id = A.TestParticipantId
			    
		INSERT INTO sEExam.tTestParticipantAnswer
			(
				TestId,
				QuestionId,
				QuestionOptionId,
				ScoredMark,
				AnswerStatusId,
				OrderIndex,
				TestParticipantId,
				QuestionAnswer
			)
		  SELECT 
				@rTestId,
				QuestionId,
				QuestionOptionId,
				ScoredMark,
				AnswerStatusId,
				OrderIndex,
				@rTestParticipantId,
				sSetup.fPortalXMLTagsReplaceReverse(QuestionAnswer)
			
			FROM OPENXML (@loQuestionOptionDoc, '/Table/QuestionOptionDetail', 1)
			WITH ( 
					TestId Int,
					QuestionId bigint,
					QuestionOptionId bigint,
					ScoredMark decimal(6,2),
					AnswerStatusId smallint,
					OrderIndex smallint,
					QuestionAnswer nvarchar(max)
				  ) 
			SELECT 1 AS Result   
		END
		SELECT IsDisplayResultOnComplete FROM sEExam.tTestMaster WHERE Id =@rTestId
		
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
		--COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		--ROLLBACK TRANSACTION
		SELECT -1 AS Result
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
	END CATCH	 
	 
	
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pDsTestParticipantQuestionAdd]
	 
	@rTestId bigint,
	@rTestParticipantId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
		IF NOT EXISTS(SELECT 1 FROM sEExam.tTestParticipantAnswer WHERE TestId = @rTestId AND TestParticipantId = @rTestParticipantId)
		BEGIN
			INSERT INTO sEExam.tTestParticipantAnswer
			(
				TestId,
				QuestionId,
				QuestionOptionId,
				ScoredMark,
				AnswerStatusId,
				OrderIndex,
				TestParticipantId,
				QuestionAnswer
			)
			SELECT 
				TestId, 
				QuestionId, 
				0,
				0,
				532,
				0,
				@rTestParticipantId,
				0
			FROM
				sEExam.tTestQuestion 
			WHERE 
				TestId = @rTestId
		END
		SELECT 1 AS Result
		COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pDsTestQuestionListGet]
	 	 
	 @rTestId int,
	 @rTestParticipantId bigint
	 	 
     WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 

BEGIN 

DECLARE @lTestTypeId int
SELECT @lTestTypeId = TestTypeId FROM sEExam.tTestMaster Where Id=@rTestId
--SELECT @lTestTypeId 
IF(@lTestTypeId = 726)
BEGIN
	SELECT 
		ROW_NUMBER() OVER(ORDER BY TQ.OrderIndex) AS RowIndex,
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.QuestionDescription2,
		TQ.Marks,
		QM.IsObsolete,
		ISNULL(TQ.OrderIndex,0) AS OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId  ,
		ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParagraphDescription2,
		ISNULL(QM.QuestionParagraphId,0) AS QuestionParagraphId,
		TP.Id AS TestParticipantId,
		TP.TestId,
		TP.SourceTypeId,
		TP.SourceId,
		TP.TestDate,
		TP.StartTime,
		TP.EndTime,
		TP.TestStatusId,
		TP.TotalMarks,
		TP.ScoredMarks,
		TP.TotalQuestions,
		TP.RightQuestions,
		TP.WrongQuestions,
		TP.SkippQuestions,
		TP.NotAttemptedQuestions,
		ISNULL(TPA.QuestionOptionId,0) AS QuestionOptionId,
		ISNULL(TPA.AnswerStatusId,0) AS AnswerStatusId,
		ISNULL(TPA.ScoredMark,0) AS QuestionScoredMark,
		QO.Id AS QuestionOptionKeyId,
		ISNULL(NegativeMarkPerAnswer,0) AS NegativeMarkPerAnswer,
		ISNULL(TPA.QuestionAnswer,'')AS QuestionAnswer,
		ISNULL(QM.QuestionTypeId,0) AS QuestionTypeId
 	FROM 
		sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
		ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
		ON DLM.Id=QM.DifficultyLevelId
		INNER JOIN sEExam.tTestQuestion TQ
		ON TQ.QuestionId=QM.Id      
		INNER JOIN sEExam.tTestParticipant TP
		ON TP.TestId = TQ.TestId
		LEFT JOIN sEExam.tQuestionParagraph QP ON QP.Id=QM.QuestionParagraphId
		LEFT JOIN sEExam.tTestParticipantAnswer TPA ON TPA.TestParticipantId=TP.Id AND TPA.QuestionId = QM.Id
		INNER JOIN sEExam.tQuestionOption QO ON QO.QuestionId = QM.Id AND  QO.IsKey=0
	    INNER JOIN sEExam.tTestMaster TMT ON TMT.Id = TP.TestId
		
	WHERE 
		TQ.TestId=@rTestId AND TP.Id = @rTestParticipantId
	    ORDER BY TQ.OrderIndex
END
ELSE
BEGIN
	SELECT 
		ROW_NUMBER() OVER(ORDER BY TQ.OrderIndex) AS RowIndex,
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.QuestionDescription2,
		TQ.Marks,
		QM.IsObsolete,
		ISNULL(TQ.OrderIndex,0) AS OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId  ,
		ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParagraphDescription2,
		ISNULL(QM.QuestionParagraphId,0) AS QuestionParagraphId,
		TP.Id AS TestParticipantId,
		TP.TestId,
		TP.SourceTypeId,
		TP.SourceId,
		TP.TestDate,
		TP.StartTime,
		TP.EndTime,
		TP.TestStatusId,
		TP.TotalMarks,
		TP.ScoredMarks,
		TP.TotalQuestions,
		TP.RightQuestions,
		TP.WrongQuestions,
		TP.SkippQuestions,
		TP.NotAttemptedQuestions,
		ISNULL(TPA.QuestionOptionId,0) AS QuestionOptionId,
		ISNULL(TPA.AnswerStatusId,0) AS AnswerStatusId,
		ISNULL(TPA.ScoredMark,0) AS QuestionScoredMark,
		QO.Id AS QuestionOptionKeyId,
		ISNULL(NegativeMarkPerAnswer,0) AS NegativeMarkPerAnswer,
		ISNULL(TPA.QuestionAnswer,'')AS QuestionAnswer,
		ISNULL(QM.QuestionTypeId,0) AS QuestionTypeId
 	FROM 
		sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
		ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
		ON DLM.Id=QM.DifficultyLevelId
		INNER JOIN sEExam.tTestQuestion TQ
		ON TQ.QuestionId=QM.Id      
		INNER JOIN sEExam.tTestParticipant TP
		ON TP.TestId = TQ.TestId
		LEFT JOIN sEExam.tQuestionParagraph QP ON QP.Id=QM.QuestionParagraphId
		LEFT JOIN sEExam.tTestParticipantAnswer TPA ON TPA.TestParticipantId=TP.Id AND TPA.QuestionId = QM.Id
		INNER JOIN sEExam.tQuestionOption QO ON QO.QuestionId = QM.Id AND  QO.IsKey=1
	    INNER JOIN sEExam.tTestMaster TMT ON TMT.Id = TP.TestId
		
	WHERE 
		TQ.TestId=@rTestId AND TP.Id = @rTestParticipantId
	    ORDER BY TQ.OrderIndex
END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pDsTestQuestionOptionListGet]

	 @rTestParticipantId bigint 
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT
		ISNULL(TP.Id,0) AS TestParticipantId, 
		TP.TestId,
		TP.SourceId,
		TP.SourceTypeId,
		QM.Id AS QuestionId,
		QO.Id AS QuestionOptionId,		
		QM.QuestionDescription AS QuestionDescription,
		ISNULL(QM.QuestionDescription2,'') AS QuestionDescription2,
		QO.ChoiceDescription AS ChoiceDescription,
		ISNULL(QO.ChoiceDescription2,'') AS ChoiceDescription2,		
		QM.Marks AS QuestionMarks,
		QO.IsKey,
		ISNULL(Qp.QuestionParagraphDescription,'') AS QuestionParagraphDescription ,
		TM.TestDuration,
		ISNULL(TM.IsDisplayResultOnComplete,0) AS IsDisplayResultOnComplete,
		ISNULL(TM.IsAutoFinishOnTime,0) AS IsAutoFinishOnTime,
		ISNULL(TPA.QuestionOptionId,0) AS AnweredQuestionOptionId,
		TPA.AnswerStatusId,
		ISNULL(TPA.OrderIndex,0)AS OrderIndex,		
		CASE
		WHEN (TPA.QuestionOptionId = QO.Id AND QO.IsKey = 1 ) THEN 'Right'
		WHEN (TPA.QuestionOptionId = QO.Id AND QO.IsKey = 0) THEN 'Wrong'
		WHEN (QO.IsKey = 1) THEN 'Right' 
		ELSE '' END AS QuestionStatus,
		convert(bit,0) as SelectOption,
		ISNULL(AlertDuration,0) AS AlertDuration,
		ISNULL(NegativeMarkPerAnswer,0) AS NegativeMarkPerAnswer
		
FROM 
		sEExam.tTestParticipant TP  
		INNER JOIN sEExam.tTestMaster TM ON TP.TestId = TM.Id
		INNER JOIN sEExam.tTestQuestion TQ ON  TQ.TestId = TP.TestId
		INNER JOIN sEExam.tQuestionMaster QM ON TQ.QuestionId = QM.Id 		
		INNER JOIN sEExam.tQuestionOption QO ON QO.QuestionId=QM.Id 
	    LEFT JOIN sEExam.tTestParticipantAnswer TPA WITH (NOLOCK) ON TP.Id = TPA.TestParticipantId AND TPA.QuestionId = TQ.QuestionId AND TPA.TestId = TQ.TestId	  
		LEFT JOIN sEExam.tQuestionParagraph QP ON Qp.Id = QM.QuestionParagraphId
WHERE  
        TP.Id = @rTestParticipantId
	    ORDER BY QO.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pOnlineLearningResultGet]
 
			@rTestId int,		 
			@rOnlineLearningId bigint = 0,
			@rBatchId int=0,
			@rSourceId bigint=0

           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN   

--DECLARE @1TestAssignStatusId int

 SELECT  
		 VSA.RollNo,
		 VSA.Name,
		 VSA.Code,
		 P.SourceId,
		 P.SourceTypeId,	
	     ISNULL(P.TotalMarks,0) AS TotalMarks,
		 ISNULL(P.ScoredMarks,0) AS ScoredMarks,
		 ISNULL(P.TotalQuestions,0) AS TotalQuestions,
		 ISNULL(P.RightQuestions,0) AS RightQuestions,
		 (ISNULL(P.WrongQuestions,0) - (ISNULL(P.NotAttemptedQuestions,0)+ ISNULL(P.SkippQuestions,0))) AS WrongQuestions,
		 ISNULL(P.NotAttemptedQuestions,0) AS NotAttemptedQuestions,
		 ISNULL(P.SkippQuestions,0) AS SkippQuestions,
		 'Student' AS TypeName,
		 VSA.ClassName+'-'+VSA.DivisionName As ClassName,
		 ISNULL(TM.IsMarkInDecimal,0) AS IsMarkInDecimal,
		 P.Id AS TestParticipantId,
		 VSA.AcademicId,
		 TM.Title As TestName,
		 (VSA.FirstName+''+VSA.MiddleName+''+VSA.LastName)AS StudentName
		 --TM.IsMarkInDecimal
		 ,p.SourceId
		 FROM sEExam.tTestParticipant P INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
		 INNER JOIN sStudent.vStudentAcademic VSA ON VSA.StudentId = P.SourceId AND P.SourceTypeId=2003
		 --INNER JOIN sAcademic.tOnlineLearning OL
		 INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.TestId=TM.Id  AND OL.TeacherEmployeeId=@rSourceId
		 --INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
		 --INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId=OL.Id
			--	WHERE (
			--	( 
			--	(OLS.SourceTypeId = 2021 AND OLS.SourceId =@lOrgId) 
			--	OR
			--	(OLS.SourceTypeId = 2017 AND OLS.SourceId =@lDepartmentId) OR
			--	(OLS.SourceTypeId = 2016 AND OLS.SourceId =@lClassId) OR
			--	(OLS.SourceTypeId = 2005 AND OLS.SourceId =@lDivisionId) OR
			--	(OLS.SourceTypeId = 2003 AND OLS.SourceId =@lStudentId) OR
			--	(OLS.SourceTypeId = 2001 AND OLS.SourceId =@lAcademicId)
			--	 )AND (OL.BatchId=@rBatchId)
			--	 )
			--	) D
		  
		 ---INNER JOIN [sAcademic].[tOnlineLearningScope] OLS ON OLS.SourceTypeId=P.SourceTypeId AND OLS.SourceId=P.SourceId
		 Where 
		 --(P.SourceTypeId = 2003 OR 2003 = 0) 
		 --AND 
		 P.TestId = @rTestId
		 AND TestStatusId != 0 
		 AND (OL.Id = @rOnlineLearningId or @rOnlineLearningId = 0)
		 AND TM.BatchId=@rBatchId 
		 AND VSA.BatchId=@rBatchId
		
		ORDER BY DivisionId, VSA.RollNo ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sEExam].[pQuestionListGet]
	 
	 @rId bigint = 0,
	 @rTopicId int,
	 @rClassSubjectId int,
	 @rClassId int,
	 @rDifficultyLevelId int,
	 @rDataBankId int,
	 @rQuestionTypeId int=0

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 	 
	
	SELECT 
		
		QM.Id,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		ISNULL(QM.QuestionParagraphId,0)AS QuestionParagraphId,
		QM.QuestionDescription  AS QuestionDescription,
		--''''+QM.QuestionDescription+''''  AS QuestionDescription,
		ISNULL(QM.QuestionDescription2,'')AS QuestionDescription2,
		ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParegraphDescription,	
		ISNULL(QP.QuestionParagraphDescription2,'') AS QuestionParegraphDescription2,												  
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		CM.Title AS Class,
		VCS.Title AS SubjectName,
		TM.Title AS Topic,
		ISNULL(QM.GroupQuestionId,0) AS QuestionGroupId,
		ISNULL(QM.EntryModeId,0) AS EntryModeId,
		CASE WHEN QuestionParagraphId<>0 then 'With Para' else '' end AS WithPara,
		QM.Id,
		ISNULL(QM.QuestionTypeId,0)AS QuestionTypeId,
		SM.Title AS QuestionTypeTitle
		      
	FROM 
			sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDataSubjectMaster VCS
			ON TM.DataSubjectId=VCS.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
		INNER JOIN sSetup.tClassGroupMaster CM ON CM.Id = TM.ClassGroupId	
		--INNER JOIN sSetup.vAffiliationClassGroup CM
		--	ON CM.Id=TM.ClassGroupId 
		LEFT JOIN sEExam.tQuestionParagraph QP ON Qp.Id = QM.QuestionParagraphId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = QM.QuestionTypeId AND SM.StatusTypeId = 658
             
	WHERE  
			((QM.Id = @rId) OR (@rId = 0))
		 AND((QM.DataBankId = @rDataBankId) OR (@rDataBankId = 0))
		 AND((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
         AND((VCS.Id = @rClassSubjectId) OR (@rClassSubjectId = 0)) 
         AND((TM.ClassGroupId = @rClassId) OR (@rClassId = 0)) 
         AND((DLM.Id = @rDifficultyLevelId) OR (@rDifficultyLevelId = 0)) 
		 AND ((ISNULL(QM.QuestionTypeId,727) = @rQuestionTypeId) OR (@rQuestionTypeId = 0))
         --AND CM.AffiliationId = 3
      
        Order By QM.TopicId,OrderIndex,QP.Id
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pQuestionMasterAdd]
	 
	@rId bigint,
	@rTopicId int,
	@rDifficultyLevelId tinyint,
	@rQuestionParagraphId bigint,
	@rQuestionDescription nvarchar(max),
	@rQuestionDescription2 nvarchar(max),
	@rMarks decimal(6,2),
	@rIsObsolete bit,
	@rOrderIndex smallint,	
	@rCreatedUserId bigint,
	@rDataBankId int,
	@rOrgGroupId int,
	@rEntryModeId smallint,
	@rQuestionTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
BEGIN TRANSACTION	
IF(@rQuestionTypeId = 0)
BEGIN
	SET @rQuestionTypeId=727;
END
IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT   
	DECLARE @1NextOrderIndex int  
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tQuestionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	IF EXISTS(SELECT OrderIndex From sEExam.tQuestionMaster Where TopicId = @rTopicId AND OrderIndex=@rOrderIndex)
	BEGIN
	 Select -101 as Result
	 return;
	END
	IF(@rOrderIndex = 0)
	BEGIN
    Select @rOrderIndex = ISNULL(Max(OrderIndex),0) From sEExam.tQuestionMaster Where TopicId = @rTopicId
    SET @rOrderIndex = @rOrderIndex + 1;
    END
    
	INSERT INTO sEExam.tQuestionMaster
		(
			Id,
			TopicId,
			DifficultyLevelId,
			QuestionParagraphId,
			QuestionDescription,
			QuestionDescription2,
			Marks,
			IsObsolete,
			OrderIndex,			
			CreatedUserId,
			CreatedDateTime,
			DataBankId,
			EntryModeId,
			QuestionTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTopicId,
			@rDifficultyLevelId,
			@rQuestionParagraphId,
			@rQuestionDescription,
			@rQuestionDescription2,
			@rMarks,
			@rIsObsolete,
			@rOrderIndex,			
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rDataBankId,
			@rEntryModeId,
			@rQuestionTypeId
		)
		   SELECT @lNextNumber AS Result          
	END	 
	 ELSE
	 SET @lNextNumber = @rId 
	 
	    UPDATE  sEExam.tQuestionMaster
	    SET
			TopicId=@rTopicId,
			DifficultyLevelId=@rDifficultyLevelId,
			QuestionParagraphId=@rQuestionParagraphId,
			QuestionDescription=@rQuestionDescription,
			QuestionDescription2=@rQuestionDescription2,
			Marks=@rMarks,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			EntryModeId= @rEntryModeId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() ,
			QuestionTypeId=@rQuestionTypeId
			 
	      WHERE Id = @rId 	   
	 	 
		  SELECT @lNextNumber AS Result  
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sEExam].[pQuestionMasterGet]
	 @rId bigint = 0,
	 @rTopicId int,
	 @rSubjectId int,
	 @rClassId int,
	 @rDifficultyLevelId int,
	 @rOrgId int

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  --BEGIN
	  
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  --END
	 
	SELECT 
	QM.Id,
	QM.QuestionDescription,
	QM.Marks,
	QM.EntryModeId,
	--VDSM.SubjectId,
	
	--TM.Title AS TopicTitle,
	DLM.Title AS DifficultyLevel
	
	--DSM.Number,
	--DSM.Title,
	--DSM.IsObsolete,
	--DSM.OrderIndex,
	--AM.Title AS AffiliationName
	
	
      
  FROM 
       sEExam.tQuestionMaster QM
        INNER JOIN sEExam.tTopicMaster TM
        ON QM.TopicId= TM.Id
        INNER JOIN sSetup.vClassSubject VCS
        ON TM.ClassSubjectId=VCS.ClassSubjectId
        --INNER JOIN sSetup.vBatchClass VBC
        --ON VBC.ClassId=VCS.ClassId
        INNER JOIN sEExam.tDifficultyLevelMaster DLM
        ON DLM.Id=QM.DifficultyLevelId
            
             
  WHERE 
		
      ((QM.Id = @rId) OR (@rId = 0))
     AND ((QM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND   ((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
        AND   ((VCS.SubjectId = @rSubjectId) OR (@rSubjectId = 0)) 
      AND   ((VCS.ClassId = @rClassId) OR (@rClassId = 0)) 
      AND   ((DLM.Id = @rDifficultyLevelId) OR (@rDifficultyLevelId = 0)) 
      
        
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pQuestionMasterRemove]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sEExam.tQuestionMaster where Id=@rId
			Delete from sEExam.tQuestionOption where QuestionId=@rId
			select 1 as Result
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		select -1 as Result
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pQuestionOptionAdd]
	 
	@rId bigint,
	@rQuestionId bigint,
	@rChoiceDescription nvarchar(max),
	@rChoiceDescription2 nvarchar(max),
	@rIsKey bit,
	@rOrderIndex smallint,
	@rOrgGroupId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tQuestionOption', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sEExam.tQuestionOption
		(
			Id,
			QuestionId,
			ChoiceDescription,
			ChoiceDescription2,
			IsKey,
			OrderIndex
			 
		)
	VALUES
		(
			@lNextNumber,
			@rQuestionId,
			@rChoiceDescription,
			@rChoiceDescription2,
			@rIsKey,
			@rOrderIndex 
		)
		   SELECT 1 AS Result          
	END	 
	 ELSE
	 SET @lNextNumber = @rId
	    UPDATE  sEExam.tQuestionOption
	    SET
			ChoiceDescription=@rChoiceDescription,
			ChoiceDescription2=@rChoiceDescription2,
			IsKey=@rIsKey,
			OrderIndex=@rOrderIndex
	      
	      WHERE Id = @rId 	   
	 	 
		  SELECT 11 AS Result    
		
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pQuestionOptionGet]
		
		@rQuestionId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
	
	QO.Id,
	QO.ChoiceDescription,
	ISNULL(QO.ChoiceDescription2,'')AS ChoiceDescription2,
	QO.IsKey,
	QO.OrderIndex
	
	
      
  FROM 
            sEExam.tQuestionOption QO
             
  WHERE 
		QO.QuestionId=@rQuestionId	
	Order By OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pQuestionOptionPreviewGet]
		
		 @rQuestionId bigint
		,@rIsKey bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
   
	SELECT 
	
	QO.Id,
	CASE  WHEN QO.OrderIndex = 1 AND QO.IsKey = 1 AND @rIsKey = 1 AND QO.OrderIndex =1  THEN '*(A)' 		
		  WHEN QO.OrderIndex = 1 THEN '  (A)'  	
		  
		  WHEN QO.OrderIndex = 2 AND QO.IsKey = 1 AND @rIsKey = 1 AND QO.OrderIndex =2 THEN '*(B)'  	
		  WHEN QO.OrderIndex = 2 THEN '  (B)'  	
		  
		  WHEN QO.OrderIndex = 3 AND QO.IsKey = 1 AND @rIsKey = 1 AND QO.OrderIndex =3 THEN '*(C)'  	
		  WHEN QO.OrderIndex = 3 THEN '  (C)'  	
		  
		  WHEN QO.OrderIndex = 4 AND QO.IsKey = 1 AND @rIsKey = 1 AND QO.OrderIndex =4 THEN '*(D)'  	
		  WHEN QO.OrderIndex = 4 THEN '  (D)'  			  
		  
		  WHEN QO.OrderIndex = 5 AND QO.IsKey = 1 AND @rIsKey = 1 AND QO.OrderIndex =5 THEN '*(E)'  	
		  WHEN QO.OrderIndex = 5 THEN '  (E)' END ChoiceLetter, 
		  QO.ChoiceDescription AS ChoiceDescription,
	ISNULL(QO.ChoiceDescription2,'')AS ChoiceDescription2,
	QO.IsKey,
	QO.OrderIndex
	
	
 
  FROM 
            sEExam.tQuestionOption QO
             
  WHERE 
		QO.QuestionId=@rQuestionId	
	Order By OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pQuestionParagraphAdd]
 
		@rId bigint,
		@rFigure varbinary(max),
		@rQuestionParagraphDescription nvarchar(max),
		@rQuestionParagraphDescription2 nvarchar(max),
		@rOrgGroupId int,
		@rCreatedUserId bigint
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 
    IF(@rId = 0)
	  BEGIN
		
		EXECUTE sCommon.pTableRowIdGet  @rOrgGroupId, 'sEExam.tQuestionParagraph', 0, 1, 1,@outNextNumber = @lNextNumber output
    
		 INSERT INTO [sEExam].[tQuestionParagraph]
			   (
				[Id]
			   ,[Figure]
			   ,[QuestionParagraphDescription]
			   ,[QuestionParagraphDescription2]			   
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rFigure
			   ,@rQuestionParagraphDescription
			   ,@rQuestionParagraphDescription2			  
			   ,@rCreatedUserId 
			   ,sCommon.fGetDate()           
			   )  
     END
     ELSE
      BEGIN
         SET @lNextNumber = @rId
         UPDATE sEExam.tQuestionParagraph
          SET 
            Figure = @rFigure,
            QuestionParagraphDescription = @rQuestionParagraphDescription,
            QuestionParagraphDescription2 = @rQuestionParagraphDescription2,            
            UpdatedUserId = @rCreatedUserId,
            UpdatedDateTime = sCommon.fGetDate()
            
            Where Id = @rId            
     END  
     
     Select @lNextNumber AS Result
     
    COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
       
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pRptQuestionListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',	 
	 @rTopicId int,
	 @rClassSubjectId int,
	 @rClassId int,
	 @rDifficultyLevelId int,
	 @rOrgId int,
	 @rDataBankId int,
	 @rAffilationId int,
	 @rIsKey bit
	  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		QM.Id,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		ISNULL(QM.QuestionParagraphId,0)AS QuestionParagraphId,
		QM.QuestionDescription,
		ISNULL(QM.QuestionDescription2,'')AS QuestionDescription2,
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		CM.Title AS Class,
		VCS.Title AS SubjectName,
		TM.Title AS Topic ,
		QO.ChoiceDescription,
		QO.Id AS ChoiceDescriptionId,
		QM.Marks AS QuestionMArks,		 
		TM.Id AS TestId,
		VCS.Title As Subject,
		QO.OrderIndex AS OptNo, 
		--TestM.IsMarkInDecimal,
		convert(bit,(CASE @rIsKey  WHEN 1 THEN QO.IsKey ELSE 0 END)) AS IsKey,
		ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParagraph
	FROM  
		--		sEExam.tTestQuestion TQ  
		--INNER JOIN 
		sEExam.tQuestionMaster QM 
			 
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDataSubjectMaster VCS
			ON TM.DataSubjectId=VCS.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
		--INNER JOIN sSetup.vAffiliationClassGroup CM
		--	ON CM.Id=TM.ClassGroupId
			INNER JOIN sSetup.tClassGroupMaster CM ON CM.Id = TM.ClassGroupId	
		INNER JOIN sEExam.tQuestionOption QO 
			ON QO.QuestionId=QM.Id 
	    LEFT JOIN sEExam.tQuestionParagraph QP
		ON QM.QuestionParagraphId = QP.Id 
	 
             
	WHERE  
 
		 ((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
         AND
         ((VCS.Id = @rClassSubjectId) OR (@rClassSubjectId = 0)) 
         AND((TM.ClassGroupId = @rClassId) OR (@rClassId = 0)) 
         AND((DLM.Id = @rDifficultyLevelId) OR (@rDifficultyLevelId = 0)) 
         --AND  CM.AffiliationId = @rAffilationId 
         AND QM.DataBankId = @rDataBankId
          
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pRptStudentTestQuestionListGet]
	 
	 @rTestId int,
	 @rTestParticipantId bigint,
	 @rBatchId int  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 
	 
	SELECT 
	
		QM.Id,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		ISNULL(QM.QuestionParagraphId,0)AS QuestionParagraphId,
		QM.QuestionDescription,
		ISNULL(QM.QuestionDescription2,'')AS QuestionDescription2,
		QM.Marks,
		QM.IsObsolete,
		TQ.OrderIndex,
		DLM.Title AS DifficultyLevel,
		--CM.Title AS Class,
		VCS.Title AS SubjectName,
		TM.Title AS Topic,
		QO.ChoiceDescription,
		QO.Id AS ChoiceDescriptionId,
		QM.Marks AS QuestionMarks,		 
		TM.Id AS TestId,
		QO.OrderIndex AS OptNo,
		QO.IsKey,
		TestM.Title AS TestName,
		--TestM.TotalMarks,
		TestM.IsMarkInDecimal,
	    (CASE TP.SourceTypeId WHEN 2003 THEN SA.Name
		ElSE EM.EmployeeName END) AS Name,
		(CASE TP.SourceTypeId WHEN 2003 THEN SA.RollNo
		ElSE EM.Code END) AS RollNo,
		(CASE TP.SourceTypeId WHEN 2003 THEN SA.Code
		ElSE EM.Code END) AS Code,
		(CASE TP.SourceTypeId WHEN 2003 THEN SA.ClassName+' - '+SA.DivisionName
		ElSE EM.DepartmentName END) AS CDName,
		TP.SourceTypeId,
		ISNULL(TA.QuestionOptionId,0) AS AnswerOptionId,
		SM.Title AS AttemptStaus,
		TP.RightQuestions,
		TP.ScoredMarks,
		TP.SkippQuestions,
		TP.WrongQuestions,
		TP.TotalMarks,
		TP.TotalQuestions,
		TP.NotAttemptedQuestions,
		ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParagraph
	 
	FROM  
	
	    sEExam.tTestParticipant TP
	    INNER JOIN sEExam.tTestMaster TestM 
	    ON TP.TestId = TestM.Id  		
	    INNER JOIN sEExam.tTestQuestion TQ 
			ON TestM.Id=TQ.TestId	 
		INNER JOIN sEExam.tQuestionMaster QM 
			ON TQ.QuestionId = QM.Id			
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tQuestionOption QO 
			ON QO.QuestionId=QM.Id 			
		INNER JOIN sEExam.tDataSubjectMaster VCS
			ON TM.DataSubjectId=VCS.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
		--INNER JOIN sSetup.vAffiliationClassGroup CM
		--	ON CM.Id=TM.ClassGroupId		
		LEFT JOIN  sEExam.tTestParticipantAnswer TA
			ON TA.TestId = TP.TestId  AND TA.QuestionId = TQ.QuestionId AND TA.TestParticipantId = TP.Id
		LEFT JOIN sStudent.vStudentAcademic SA
			ON SA.StudentId = TP.SourceId AND SourceTypeId = 2003 AND SA.BatchId = @rBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM
			ON EM.EmployeeId = TP.SourceId AND SourceTypeId = 95
		LEFT JOIN sCommon.tStatusMaster SM
		    ON TA.AnswerStatusId = SM.Id
		LEFT JOIN sEExam.tQuestionParagraph QP
		ON QM.QuestionParagraphId = QP.Id  	
			
	WHERE  
			TP.Id  = @rTestParticipantId
			ORDER BY TQ.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sEExam].[pRptStudentWiseQuestionListGet]
 
			@rTestId int,		 
			@rBatchId int=0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN   

DECLARE @1TestAssignStatusId int

 SELECT  
		
		 TQ.QuestionDescription,
		 P.SourceId,
		 TPA.AnswerStatusId,
		 ISNULL(QO.IsKey,0)IsKey,
		 (CASE WHEN TPA.AnswerStatusId=533 THEN 'Skipp' 
		       WHEN TPA.AnswerStatusId=532 THEN 'Not Attempted' 
			   WHEN (TPA.AnswerStatusId=531 AND (QO.IsKey=0 OR QO.IsKey IS NULL))THEN 'Wrong'
			   WHEN (TPA.AnswerStatusId=531 AND QO.IsKey=1)THEN 'Right'
			   END)AS AnswerStatus,
		 QO.ChoiceDescription,
		 (Select ChoiceDescription from sEExam.tQuestionOption QO1 Where QO1.QuestionId=TQ.Id And QO1.IsKey=1)AS RightAnswer,
		 VSA.Name,
		 TQ.Id,
		 ISNULL(TPA.TestParticipantId,0)AS TestParticipantId,
		 DTM.Title AS TopicName,
		 TM.TestDate
		 
		 FROM sEExam.tTestParticipant P 
		 INNER JOIN sEExam.tTestParticipantAnswer TPA ON P.Id = TPA.TestParticipantId
		 INNER JOIN sEExam.tTestQuestion TQM ON TQM.QuestionId = TPA.QuestionId AND P.TestId = TQM.TestId
		 INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
		 INNER JOIN sEExam.tQuestionMaster TQ  ON TPA.QuestionId=TQ.Id AND TQM.QuestionId = TQ.Id
		 LEFT JOIN sEExam.tQuestionOption QO ON  QO.Id= TPA.QuestionOptionId AND  QO.QuestionId=TQM.QuestionId 
		 INNER JOIN sStudent.vStudentAcademic VSA ON VSA.StudentId = P.SourceId AND P.SourceTypeId=2003
		 INNER JOIN sEExam.tDataTopicMaster DTM ON DTM.Id = TQ.TopicId
		 Where (SourceTypeId = 2003) 
		 AND P.TestId = @rTestId
		 AND TestStatusId != 0 
		 --AND (P.SourceId = @rSourceId or @rSourceId = 0)
		 AND TM.BatchId=@rBatchId AND VSA.BatchId=@rBatchId
		
		ORDER BY DivisionId, VSA.RollNo,P.SourceId ASC

	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pRptTestQuestionListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rTestId int,
	 @rTopicId int,
	 @rClassSubjectId int,
	 @rClassId int,
	 @rDifficultyLevelId int,
	 @rOrgId int,
	 @rDataBankId int,
	 @rAffilationId int,
	 @rIsKey bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		QM.Id,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		ISNULL(QM.QuestionParagraphId,0)AS QuestionParagraphId,
		QM.QuestionDescription,
		ISNULL(QM.QuestionDescription2,'')AS QuestionDescription2,
		QM.Marks,
		QM.IsObsolete,
		TQ.OrderIndex,
		DLM.Title AS DifficultyLevel,
		CM.Title AS Class,
		VCS.Title AS SubjectName,
		TM.Title AS Topic ,
		QO.ChoiceDescription,
		QO.Id AS ChoiceDescriptionId,
		QM.Marks AS QuestionMArks,		 
		TM.Id AS TestId,
		VCS.Title As Subject,
		QO.OrderIndex AS OptNo,
		TestM.Title AS TestName,
		TestM.TotalMarks,
		TestM.IsMarkInDecimal,
		convert(bit,(CASE @rIsKey  WHEN 1 THEN QO.IsKey ELSE 0 END)) AS IsKey,
		ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParagraph
		
	FROM  
			sEExam.tTestQuestion TQ 
		INNER JOIN sEExam.tQuestionMaster QM 
			ON TQ.QuestionId = QM.Id AND TQ.TestId = @rTestId 
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDataSubjectMaster VCS
			ON TM.DataSubjectId=VCS.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
		INNER JOIN sSetup.vAffiliationClassGroup CM
			ON CM.Id=TM.ClassGroupId
		INNER JOIN sEExam.tQuestionOption QO 
			ON QO.QuestionId=QM.Id 
		INNER JOIN sEExam.tTestMaster TestM 
			ON TestM.Id=TQ.TestId
		LEFT JOIN sEExam.tQuestionParagraph QP
		ON QM.QuestionParagraphId = QP.Id 
		--	sEExam.tQuestionMaster QM
		--INNER JOIN sEExam.tQuestionOption QO 
		--	ON QO.QuestionId=QM.Id
		--INNER JOIN sEExam.tDataTopicMaster TM
		--	ON QM.TopicId= TM.Id
		
		--INNER JOIN sEExam.tDataSubjectMaster VCS
		--	ON TM.DataSubjectId=VCS.Id
		--INNER JOIN sEExam.tDifficultyLevelMaster DLM
		--	ON DLM.Id=QM.DifficultyLevelId
		--INNER JOIN sSetup.vAffiliationClassGroup CM
		--	ON CM.Id=TM.ClassGroupId 
		----INNER JOIN sEExam.tTestQuestion TQ ON TQ.QuestionId=QM.Id AND (TQ.TestId=@rTestId OR @rTestId=0)
		----INNER JOIN sEExam.tTestMaster TestM ON TestM.Id=TQ.TestId
		--INNER JOIN [sSetup].[vClassSubject] CS ON CS.ClassSubjectId =  TM.DataSubjectId
             
	WHERE  
		 
		  --((QM.OrgId = @rOrgId) OR (@rOrgId = 0))
		 --AND
		 ((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
         AND((VCS.Id = @rClassSubjectId) OR (@rClassSubjectId = 0)) 
         AND((CM.ClassGroupId = @rClassId) OR (@rClassId = 0)) 
         AND((DLM.Id = @rDifficultyLevelId) OR (@rDifficultyLevelId = 0)) 
         AND (CM.AffiliationId = @rAffilationId AND (TQ.TestId = @rTestId OR @rTestId=0) )
         AND (TQ.TestId=@rTestId OR @rTestId=0) 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pStudentQuestionListWithAnswerGet]
	 
	 @rTestId bigint,
	 @rTestParticipantId bigint,
	 @rBatchId bigint  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 
	 
	SELECT 
	
		QM.Id,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		ISNULL(QM.QuestionParagraphId,0)AS QuestionParagraphId,
		QM.QuestionDescription,
		ISNULL(QM.QuestionDescription2,'')AS QuestionDescription2,
		QM.Marks,
		QM.IsObsolete,
		TQ.OrderIndex,
		DLM.Title AS DifficultyLevel,
		--CM.Title AS Class,
		VCS.Title AS SubjectName,
		TM.Title AS Topic,
		--QO.ChoiceDescription,
		--QO.Id AS ChoiceDescriptionId,
		QM.Marks AS QuestionMarks,		 
		TM.Id AS TestId,
		--QO.OrderIndex AS OptNo,
		--QO.IsKey,
		TestM.Title AS TestName,
		--TestM.TotalMarks,
		TestM.IsMarkInDecimal,
	    (CASE TP.SourceTypeId WHEN 2003 THEN SA.Name
		ElSE EM.EmployeeName END) AS Name,
		(CASE TP.SourceTypeId WHEN 2003 THEN SA.RollNo
		ElSE EM.Code END) AS RollNo,
		(CASE TP.SourceTypeId WHEN 2003 THEN SA.Code
		ElSE EM.Code END) AS Code,
		(CASE TP.SourceTypeId WHEN 2003 THEN SA.ClassName+' - '+SA.DivisionName
		ElSE EM.DepartmentName END) AS CDName,
		TP.SourceTypeId,
		--ISNULL(TA.QuestionOptionId,0) AS AnswerOptionId,
		--SM.Title AS AttemptStaus,
		TP.RightQuestions,
		TP.ScoredMarks,
		TP.SkippQuestions,
		TP.WrongQuestions,
		TP.TotalMarks,
		TP.TotalQuestions,
		TP.NotAttemptedQuestions,
		ISNULL(SA.BatchId,0)AS BatchId,
		TP.Id AS TestParticipantId
		--,
		--ISNULL(TPA.QuestionOptionId,0) AS QuestionOptionId,
		--ISNULL(TPA.AnswerStatusId,0) AS AnswerStatusId,
		--ISNULL(TPA.QuestionId,0) AS QuestionId
		
		
		
		
		
		
	 
	FROM  
	
	    sEExam.tTestParticipant TP
	    INNER JOIN sEExam.tTestMaster TestM 
	    ON TP.TestId = TestM.Id  		
	    INNER JOIN sEExam.tTestQuestion TQ 
			ON TestM.Id=TQ.TestId	 
		INNER JOIN sEExam.tQuestionMaster QM 
			ON TQ.QuestionId = QM.Id			
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		--INNER JOIN sEExam.tQuestionOption QO 
		--	ON QO.QuestionId=QM.Id 			
		INNER JOIN sEExam.tDataSubjectMaster VCS
			ON TM.DataSubjectId=VCS.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
		--INNER JOIN sSetup.vAffiliationClassGroup CM
		--	ON CM.Id=TM.ClassGroupId		
		--LEFT JOIN  sEExam.tTestParticipantAnswer TA
		--	ON TA.TestId = TP.TestId  AND TA.QuestionId = TQ.QuestionId AND TA.TestParticipantId = TP.Id
		LEFT JOIN sStudent.vStudentAcademic SA
			ON SA.StudentId = TP.SourceId AND SourceTypeId = 2003 AND SA.BatchId = @rBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM
			ON EM.EmployeeId = TP.SourceId AND SourceTypeId = 95
		--LEFT JOIN sEExam.tTestParticipantAnswer TPA ON 
		----TPA.TestId = TP.TestId 
		----AND 
		--TPA.TestParticipantId = TP.Id 
		--AND TPA.QuestionId = TQ.QuestionId 
		
		--LEFT JOIN sCommon.tStatusMaster SM
		--    ON TA.AnswerStatusId = SM.Id 	
			
	WHERE  
			TP.Id  = @rTestParticipantId
			ORDER BY TQ.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pStudentTestQuestionListGet]
	 
	 @rTestId bigint,
	 @rTestParticipantId bigint,
	 @rBatchId bigint  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN 
	 
	SELECT 
	
		QM.Id,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		ISNULL(QM.QuestionParagraphId,0)AS QuestionParagraphId,
		QM.QuestionDescription,
		ISNULL(QM.QuestionDescription2,'')AS QuestionDescription2,
		QM.Marks,
		QM.IsObsolete,
		TQ.OrderIndex,
		DLM.Title AS DifficultyLevel,
		--CM.Title AS Class,
		VCS.Title AS SubjectName,
		TM.Title AS Topic,
		--QO.ChoiceDescription,
		--QO.Id AS ChoiceDescriptionId,
		QM.Marks AS QuestionMarks,		 
		TM.Id AS TestId,
		--QO.OrderIndex AS OptNo,
		--QO.IsKey,
		TestM.Title AS TestName,
		--TestM.TotalMarks,
		TestM.IsMarkInDecimal,
	    (CASE TP.SourceTypeId WHEN 2003 THEN SA.Name
		ElSE EM.EmployeeName END) AS Name,
		(CASE TP.SourceTypeId WHEN 2003 THEN SA.RollNo
		ElSE EM.Code END) AS RollNo,
		(CASE TP.SourceTypeId WHEN 2003 THEN SA.Code
		ElSE EM.Code END) AS Code,
		(CASE TP.SourceTypeId WHEN 2003 THEN SA.ClassName+' - '+SA.DivisionName
		ElSE EM.DepartmentName END) AS CDName,
		TP.SourceTypeId,
		--ISNULL(TA.QuestionOptionId,0) AS AnswerOptionId,
		--SM.Title AS AttemptStaus,
		TP.RightQuestions,
		TP.ScoredMarks,
		TP.SkippQuestions,
		TP.WrongQuestions,
		TP.TotalMarks,
		TP.TotalQuestions,
		TP.NotAttemptedQuestions,
		ISNULL(SA.BatchId,0)AS BatchId,
		TP.Id AS TestParticipantId
	 
	FROM  
	
	    sEExam.tTestParticipant TP
	    INNER JOIN sEExam.tTestMaster TestM 
	    ON TP.TestId = TestM.Id  		
	    INNER JOIN sEExam.tTestQuestion TQ 
			ON TestM.Id=TQ.TestId	 
		INNER JOIN sEExam.tQuestionMaster QM 
			ON TQ.QuestionId = QM.Id			
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		--INNER JOIN sEExam.tQuestionOption QO 
		--	ON QO.QuestionId=QM.Id 			
		INNER JOIN sEExam.tDataSubjectMaster VCS
			ON TM.DataSubjectId=VCS.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
		--INNER JOIN sSetup.vAffiliationClassGroup CM
		--	ON CM.Id=TM.ClassGroupId		
		--LEFT JOIN  sEExam.tTestParticipantAnswer TA
		--	ON TA.TestId = TP.TestId  AND TA.QuestionId = TQ.QuestionId AND TA.TestParticipantId = TP.Id
		LEFT JOIN sStudent.vStudentAcademic SA
			ON SA.StudentId = TP.SourceId AND SourceTypeId = 2003 AND SA.BatchId = @rBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM
			ON EM.EmployeeId = TP.SourceId AND SourceTypeId = 95
		--LEFT JOIN sCommon.tStatusMaster SM
		--    ON TA.AnswerStatusId = SM.Id 	
			
	WHERE  
			TP.Id  = @rTestParticipantId
			ORDER BY TQ.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pStudentWiseQuestionListGet]
 
			@rTestId int,		 
			--@rSourceTypeID int = 0,
			--@rSourceId bigint = 0,
			@rBatchId int=0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN   

DECLARE @1TestAssignStatusId int

 SELECT  
		
		 TQ.QuestionDescription,
		 P.SourceId,
		 TPA.AnswerStatusId,
		 ISNULL(QO.IsKey,0)IsKey,
		 (CASE WHEN TPA.AnswerStatusId=533 THEN 'Skipp' 
		       WHEN TPA.AnswerStatusId=532 THEN 'Not Attempted' 
			   WHEN (TPA.AnswerStatusId=531 AND (QO.IsKey=0 OR QO.IsKey IS NULL))THEN 'Wrong'
			   WHEN (TPA.AnswerStatusId=531 AND QO.IsKey=1)THEN 'Right'
			   END)AS AnswerStatus,
		 QO.ChoiceDescription AS SelectedAnswer,
		 (Select ChoiceDescription from sEExam.tQuestionOption QO1 Where QO1.QuestionId=TQ.Id And QO1.IsKey=1)AS RightAnswer,
		 TPA.ScoredMark AS ScoredMark
		 
		 FROM sEExam.tTestParticipant P 
		 INNER JOIN sEExam.tTestParticipantAnswer TPA ON P.Id = TPA.TestParticipantId
		 INNER JOIN sEExam.tTestQuestion TQM ON TQM.QuestionId = TPA.QuestionId AND P.TestId = TQM.TestId
		 INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
		 INNER JOIN sEExam.tQuestionMaster TQ  ON TPA.QuestionId=TQ.Id AND TQM.QuestionId = TQ.Id
		 LEFT JOIN sEExam.tQuestionOption QO ON  QO.Id= TPA.QuestionOptionId AND  QO.QuestionId=TQM.QuestionId 
		 INNER JOIN sStudent.vStudentAcademic VSA ON VSA.StudentId = P.SourceId AND P.SourceTypeId=2003
		 Where (SourceTypeId = 2003) 
		 AND p.TestId = @rTestId
		 AND TestStatusId != 0 
		 --AND (P.SourceId = @rSourceId or @rSourceId = 0)
		 AND TM.BatchId=@rBatchId AND VSA.BatchId=@rBatchId
		
		ORDER BY DivisionId, VSA.RollNo ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pTakeTestGet]

	 @rTestParticipantId bigint 
	 
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--DECLARE @lScoremark decimal(6,2)
--SET @lScoremark =(SELECT SUM(TPAT.ScoredMark) FROM sEExam.tTestParticipantAnswer TPAT WHERE TPAT.TestParticipantId=9999000000567)
	  
	SELECT
		
		ISNULL(TP.Id,0) AS TestParticipantId, 
		TP.TestId,
		TP.SourceId,
		TP.SourceTypeId,
		QM.Id AS QuestionId,
		QO.Id AS QuestionOptionId,		
		QM.QuestionDescription AS QuestionDescription,
		ISNULL(QM.QuestionDescription2,'') AS QuestionDescription2,
		QO.ChoiceDescription AS ChoiceDescription,
		ISNULL(QO.ChoiceDescription2,'') AS ChoiceDescription2,		
		QM.Marks AS QuestionMarks,
		QO.IsKey,
				
		ISNULL(Qp.QuestionParagraphDescription,'') AS QuestionParagraphDescription ,
		TM.TestDuration,
		ISNULL(TM.IsAutoFinishOnTime,0) AS IsAutoFinishOnTime,
		ISNULL(TPA.QuestionOptionId,0) AS AnweredQuestionOptionId,
		ISNULL(TPA.AnswerStatusId,0)AS AnswerStatusId,
		ISNULL(TPA.OrderIndex,0)AS OrderIndex,		
		CASE
		WHEN (TPA.QuestionOptionId = QO.Id AND QO.IsKey = 1 ) THEN 'Right'
		WHEN (TPA.QuestionOptionId = QO.Id AND QO.IsKey = 0) THEN 'Wrong'
		WHEN (QO.IsKey = 1) THEN 'Right' 
		ELSE '' END AS QuestionStatus,
		QM.QuestionTypeId
		 
FROM 
		sEExam.tTestParticipant TP 
		INNER JOIN sEExam.tTestMaster TM ON TP.TestId = TM.Id
		INNER JOIN sEExam.tTestQuestion TQ ON  TQ.TestId = TP.TestId
		INNER JOIN sEExam.tQuestionMaster QM ON TQ.QuestionId = QM.Id 		
		INNER JOIN sEExam.tQuestionOption QO ON QO.QuestionId=QM.Id 
	    LEFT JOIN sEExam.tTestParticipantAnswer TPA ON TP.Id = TPA.TestParticipantId AND TPA.QuestionId = TQ.QuestionId AND TPA.TestId = TQ.TestId	  
		LEFT JOIN sEExam.tQuestionParagraph QP ON Qp.Id = QM.QuestionParagraphId
		
WHERE  

        TP.Id = @rTestParticipantId
         
		--TPA.TestId=@rTestId AND 
		--SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId 
		
	ORDER BY TQ.OrderIndex ASC,ISNULL(Qp.QuestionParagraphDescription,'') ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pTestAnalysisGet]
			
			@rTestId int
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
Select 
     
     OrderIndex,
     QuestionDescription,
     Topic,
     TopicId,
     QuestionId,
     COUNT(Pvt.[0]) AS Wrong,
     COUNT(Pvt.[1]) AS RightA,
     COUNT(pvt.[2]) AS NotAttempt,
     COUNT(Pvt.[3]) AS SKIP
    
     --Pvt.[0] AS Wrong,
     --Pvt.[1] AS true
     --Pvt.[-1] AS Skip, 
 from
 (
    SELECT  
	TPA.TestId,
	TopicId,
	TPA.TestParticipantId AS  TestParticipantId,
	TPA.QuestionId AS QuestionId,
	TPA.QuestionOptionId AS TPAQuestionOptionId,
	TQM.Marks AS QuestionMarks,
	TPA.ScoredMark AS ScoredMarks,
	TPA.AnswerStatusId,
	TQM.OrderIndex AS OrderIndex,
	CASE When tpa.AnswerStatusId = 533 Then 3
	WHEN tpa.AnswerStatusId = 532 Then 2
	When tpa.AnswerStatusId = 531 AND Qo.IsKey = 1 THEN 1
	ELSE 0 END AS IsKey123,
	
	--CASE WHEN QO.IsKey IS NULL THEN 2
 --   WHEN QO.IsKey =1 THEN 1
	-- WHEN QO.IsKey = 0 THEN 0
	-- END	
	--AS IsKey123,
    TQ.QuestionDescription,
    DTM.Title AS Topic 
FROM  
	sEExam.tTestParticipantAnswer TPA
	INNER JOIN sEExam.tTestParticipant TP ON TP.Id = TPA.TestParticipantId
	INNER JOIN sEExam.tTestQuestion TQM ON TQM.QuestionId = TPA.QuestionId AND TP.TestId = TQM.TestId
	INNER JOIN sEExam.tQuestionMaster TQ  ON TPA.QuestionId=TQ.Id AND TQM.QuestionId = TQ.Id
	INNER JOIN sEExam.tDataTopicMaster DTM ON DTM.Id = TQ.TopicId
	LEFT JOIN sEExam.tQuestionOption QO   ON QO.Id=TPA.QuestionOptionId AND QO.QuestionId = TPA.QuestionId	
    where TP.TestId = @rTestId 
 ) t
 pivot (min(TestId) FOR IsKey123 IN ([3],[2],[1],[0])) AS Pvt
 
 Group By  OrderIndex,QuestionDescription,QuestionId,Topic,TopicId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pTestAssignAdd]
	  
	@rTestId int,
	@rSourceId bigint,
	@rSourceTypeId int, 
	@rTestDate date=NULL,
	@rStartTime datetime=NULL,
	@rEndTime datetime=NULL,
	@rTestStatusId smallint=NULL
	--@rOrgId int
	--@rMode smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	BEGIN TRANSACTION
		

 
 
 --IF EXISTS( SELECT 1 FROM sEExam.tTestAssign Where TestId = @rTestId AND SourceTypeId = @rSourceTypeId AND SourceId=@rSourceId )
 --BEGIN
 --  DELETE FROM sEExam.tTestAssign Where TestId = @rTestId AND SourceTypeId = @rSourceTypeId AND SourceId=@rSourceId
 --END
 
BEGIN

	--DECLARE @lNextNumber bigint     
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tTestParticipant', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	INSERT INTO sEExam.tTestAssign
		(
			--Id,
			TestId,
			SourceId,
			SourceTypeId,
			TestDate,
			StartTime,
			EndTime,
			TestStatusId 			
		)
	VALUES
		(
			--@lNextNumber,
			@rTestId,
			@rSourceId,
			@rSourceTypeId,
			@rTestDate,
			CONVERT(CHAR(7),@rStartTime,108),
			--@rStartTime,
			@rEndTime,
			NULL		 
		)
		SELECT 1 AS Result             
	END	 
	 --ELSE
	 --BEGIN
	 ----SET @lNextNumber = @rId
	 --IF(@rMode=1)
	 --BEGIN
	 --   UPDATE sEExam.tTestParticipant
	 --   SET
	 --    TestDate=@rTestDate,
	 --    StartTime=@rStartTime,
	 --    TestStatusId=@rTestStatusId,
	 --    TotalMarks=@rTotalMarks
	 --     WHERE TestId = @rTestId AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId
	 --     SELECT 11 AS Result 	
	 --END
	 --ELSE IF(@rMode=2)
	 --BEGIN
	 -- UPDATE sEExam.tTestParticipant
	 --   SET
	 --    EndTime=@rEndTime,
	 --    TestStatusId=@rTestStatusId,
	 --    ScoredMarks=@rScoredMarks,
	 --    TotalQuestions=@rTotalQuestions,
	 --    RightQuestions=@rRightQuestions,
	 --    WrongQuestions=@rWrongQuestions,
	 --    NotAttemptedQuestions=@rNotAttemptedQuestions
	      
	 --     WHERE TestId = @rTestId AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId
	 --     SELECT 11 AS Result 
	 -- END  	     
	 --END  
	    COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pTestAssignGet]

			--@rClassId int,
			@rDivisionId int,
			@rTestId int,
			@rBatchId int,			 
			@rSourceTypeID int,
			@rOrgId int,
			@rClassId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN    

    SELECT  
			--VSA.AcademicId,
			VSA.RollNo,
			VSA.StudentId AS SourceId,
			VSA.Name AS StudentName,			
			'Student' AS ParticipantType,
			2003 AS SourceTypeId,
			VSA.DivisionId, 
			VSA.Code,	   
			CASE WHEN ISNULL(A.TestId,0) != 0 THEN 1 ELSE 0 END AS IsSelected,
			ISNULL(A.TestStatusId,0) AS TestStatusId,
			--VSA.DivisionName AS DivisionName
			DM.Code AS DivisionName    
    
    FROM 
			 sStudent.vStudentAcademic VSA
			 LEFT JOIN sEExam.tTestAssign A ON A.SourceId = VSA.StudentId AND A.SourceTypeId = 2003 AND A.TestId = @rTestId
			 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = A.TestStatusID
			 LEFT JOIN sSetup.tDivisionMaster DM ON VSA.DivisionId=DM.Id
	WHERE 
		--VSA.DivisionId=@rDivisionId
	 --   AND 
	    VSA.BatchId=@rBatchId  
		AND VSA.StatusId=1
		 
    --ORDER BY VSA.RollNo ASC 
	
--UNION ALL
  
--      SELECT 
--          0 AS RollNo,
--          EM.EmployeeId AS  SourceId,
--          EM.EmployeeName AS StudentName,
--	      'Employee' AS ParticipantType,
--		  95 AS SourceTypeId,
--		  0 AS DivisionId,
--          EM.Code,
--		  CASE WHEN ISNULL(A.TestId,0) != 0 THEN 1 ELSE 0 END AS IsSelected,
--          ISNULL(A.TestStatusId,0) AS TestStatusId,
--          EM.DepartmentName AS DivisionName
         
--      FROM sHrm.vEmployeeCommonDetail EM LEFT JOIN sEExam.tTestAssign A ON A.SourceId = EM.EmployeeId AND A.SourceTypeId = 95 AND A.TestId = @rTestId
--      LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = A.TestStatusID 
	        
--      WHERE OrgID = @rOrgId
  
 UNION ALL
     SELECT 
          0 AS RollNo,
          DM.Id AS  SourceId,
          DM.Title AS StudentName,
		  'Division' AS ParticipantType,
		  2005 AS SourceTypeId,
		  DM.Id AS DivisonId, 
          DM.Code,
		  CASE WHEN ISNULL(A.TestId,0) != 0 THEN 1 ELSE 0 END AS IsSelected,
          ISNULL(A.TestStatusId,0) AS TestStatusId,
          --DM.Title AS DivisionName    
		  DM.Code AS DivisionName    
         
      FROM sSetup.tDivisionMaster DM  LEFT JOIN sEExam.tTestAssign A ON A.SourceId = DM.Id AND A.TestId = @rTestId
      LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = A.TestStatusID 
      
      WHERE 
          ClassId = @rClassId AND DM.IsObsolete = 0 

		  ORDER By Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTestAssignRemove]
	 
	@rTestId bigint,
	@rSourceId bigint,
	@rSourceTypeId int 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION
	 
	 
	 
	--DECLARE @lNextNumber BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tTestQuestion', 0, 1, 1,@outNextNumber = @lNextNumber output
 

	   
	 
	  
		 IF(@rSourceTypeId = 2005)
		   BEGIN  
		   
		   
		   	    Delete TPA from sEExam.tTestParticipantAnswer TPA INNER JOIN sEExam.tTestParticipant TP 
				 ON TP.Id = TPA.TestParticipantId
				 INNER JOIN sStudent.vStudentAcademic VSA 
				 ON TP.SourceId = VSA.StudentId AND TP.SourceTypeId = 2003 
				 Where VSA.DivisionId = @rSourceId
				 AND TP.TestId = @rTestId
		   
				 DELETE  TP FROM sEExam.tTestParticipant TP INNER JOIN sStudent.vStudentAcademic VSA 
				 ON TP.SourceId = VSA.StudentId AND TP.SourceTypeId = 2003 
				 Where DivisionId = @rSourceId
				 AND TP.TestId = @rTestId
				 
				 

				    
				 
		   END
		 ELSE 
		 BEGIN
		 
		 	Delete TPA from sEExam.tTestParticipantAnswer TPA INNER JOIN sEExam.tTestParticipant TP 
			ON TP.Id = TPA.TestParticipantId				   
			Where 	TP.TestId = @rTestId	AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId
		 
		    DELETE TP FROM sEExam.tTestParticipant TP WHERE 
		    SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId 
		    AND TestID = @rTestId	
		    

		    
		 END
		 
	   Delete From sEExam.tTestAssign Where TestId = @rTestId AND SourceId = @rSourceId 
	   AND SourceTypeId = @rSourceTypeId
		 				
					
	  SELECT 1 AS Result     
	
	  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -101 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pTestAssignValidate]
	 
        @rTestId bigint,
		@rSourceTypeId smallint,
		@rSourceId bigint
		--@rAssigneeToId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		--If EXISTS(select 1 from sCommunication.tTempCircularScope CS where CS.SourceId=@rSourceId AND
		--			CS.SourceTypeId=@rSourceTypeId AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId) 
		--	BEGIN
		--		select -101 as Result,'Item Already Exists' AS Msg
		--		RETURN
		--	END 

	
	
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		
				
		If EXISTS(select 1 from sEExam.tTestAssign TA 
		  INNER JOIN sStudent.tAcademic SA 
				ON TA.SourceId=SA.StudentId AND TA.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND TA.TestId=@rTestId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from sEExam.tTestAssign TA 
		  INNER JOIN sStudent.tAcademic SA 
				ON TA.SourceId=SA.DivisionId AND TA.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND TA.TestId=@rTestId  )
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		
		If EXISTS(select 1 from  sEExam.tTestAssign TA
		 INNER JOIN sStudent.tAcademic SA 
				ON TA.SourceId=SA.DivisionId AND TA.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND TA.TestId=@rTestId  )
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
  
   select 1 as Result,'' AS Msg
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pTestMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rDataSubjectId int,
	@rDataBankId int,
	@rClassGroupId int,	
	@rTestDate date,
	@rFromTime datetime='',
	@rToTime datetime='',
	@rIsDisplayResultOnComplete bit,
	@rIsSMSResultOnComplete bit,
	@rIsAllowReview bit,
	@rIsAutoPostResultToExam bit,
	@rTotalMarks decimal(6,2),
	@rIsObsolete bit,
	@rOrderIndex int,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rOrgId int,
	@rClassId int,
	@rClassSubjectId int,
	@rTestTemplateId int,
	@rAssignedSourceTypeId int,
	@rTestDuration int,
	@rIsTestLock bit,
	@rTestQuestion int,
	@rIsMarkInDecimal bit,
	@rIsAutoFinishOnTime bit,
	@rBatchId int,
	@rTestStartupRemark nvarchar(2000)='',
	@rAlertDuration smallint=0,
	@rNegativeMarkPerAnswer decimal(5,2)=NULL,
	@rFromDate date='',
	@rToDate date='',
	@rTestTypeId int=0,
	@rAssignEmployeeId bigint=0,
	@rIsUploadImage bit,
	@rIsQuestionRemark bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
		IF(@rId = 0)	
	BEGIN
		IF Exists(select Id from sEExam.tTestMaster where Code=@rCode AND DataBankId=@rDataBankId AND OrgId=@rOrgId)
			BEGIN
			  Select -103 as Result
			RETURN
		END  
	END
	ELSE
	BEGIN 
		IF  Exists(select Id from sEExam.tTestMaster where Code=@rCode AND DataBankId=@rDataBankId AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			select -103 as Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tTestMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sEExam.tTestMaster
		(
			Id,
			Code,
			Title,
			DataSubjectId,
			TestDate,
			FromTime,
			ToTime,
			IsDisplayResultOnComplete,
			IsSMSResultOnComplete,
			IsAllowReview,
			IsAutoPostResultToExam,
			IsObsolete,
			TotalMarks,
			CreatedUserId,
			CreatedDateTime,
			OrgId,
			DataBankId,
			ClassGroupId,
			ClassId,
			ClassSubjectId,
			TestTemplateId,
			AssignedSourceTypeId,
			TestDuration,
			IsTestLock,
			TestQuestion,
			IsMarkInDecimal,
			IsAutoFinishOnTime,
			BatchId,
			TestStartupRemark,
			AlertDuration,
			NegativeMarkPerAnswer,
			FromDate,
			ToDate,
			TestTypeId,
			AssignEmployeeId,
			IsUploadImage,
			IsQuestionRemark
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rDataSubjectId,
			@rTestDate,
			@rFromTime,
			@rToTime,
			@rIsDisplayResultOnComplete,
			@rIsSMSResultOnComplete,
			@rIsAllowReview,
			@rIsAutoPostResultToExam,
			@rIsObsolete,
			@rTotalMarks,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rDataBankId,
			@rClassGroupId,
			@rClassId,
			@rClassSubjectId,
			@rTestTemplateId,
			@rAssignedSourceTypeId,
			@rTestDuration,
			0,
			@rTestQuestion,
			@rIsMarkInDecimal,
			@rIsAutoFinishOnTime,
			@rBatchId,
			@rTestStartupRemark,
			@rAlertDuration,
			@rNegativeMarkPerAnswer,
			@rFromDate,
			@rToDate,
			@rTestTypeId,
			@rAssignEmployeeId,
			@rIsUploadImage,
			@rIsQuestionRemark
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sEExam.tTestMaster
	    SET
	      Code=@rCode,
	      Title=@rTitle,
	      DataSubjectId=@rDataSubjectId,
	      ClassGroupId = @rClassGroupId,
	      TestDate=@rTestDate,
	      FromTime=@rFromTime,
	      ToTime=@rToTime,
	      IsDisplayResultOnComplete=@rIsDisplayResultOnComplete,
	      IsSMSResultOnComplete=@rIsSMSResultOnComplete,
	      IsAllowReview=@rIsAllowReview,
	      IsAutoPostResultToExam=@rIsAutoPostResultToExam,
	      IsObsolete=@rIsObsolete,
	      TotalMarks =@rTotalMarks,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate(),
	      classId = @rClassId,
	      ClassSubjectId = @rClassSubjectId,
	      TestTemplateId = @rTestTemplateId,
	      AssignedSourceTypeId = @rAssignedSourceTypeId,
	      TestDuration = @rTestDuration,
	      IsTestLock = @rIsTestLock,
	      TestQuestion = @rTestQuestion,
	      IsMarkInDecimal=@rIsMarkInDecimal,
	      IsAutoFinishOnTime=@rIsAutoFinishOnTime,      
	      BatchId=@rBatchId,
	      TestStartupRemark=@rTestStartupRemark,
	      AlertDuration=@rAlertDuration,
	      NegativeMarkPerAnswer=@rNegativeMarkPerAnswer,
		  FromDate=@rFromDate,
		  ToDate=@rToDate,
		  TestTypeId=@rTestTypeId,
		  AssignEmployeeId=@rAssignEmployeeId,
		  IsUploadImage=@rIsUploadImage,
		  IsQuestionRemark=@rIsQuestionRemark
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sEExam].[pTestMasterGet]
	 
	 @rId int = 0,
	 --@rAffiliationId int,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rDataSubjectId int,
	 @rClassGroupId int,
	 @rDataBankId int,
	 @rOrgId int,
	 @rClassId int,
	 @rClassSubjectId int,
	 @rTestTemplateId int,
	 @rIsObsolete bit,
	 @rBatchId int,
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rTestTypeId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 

BEGIN 
	  BEGIN	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	SELECT 
		TM.Id,
		TM.Code,
		TM.Title,
		TM.TestDate,
		TM.DataSubjectId,
		TM.FromTime,
		TM.ToTime,
		TM.IsDisplayResultOnComplete,
		tm.IsSMSResultOnComplete,
		TM.IsAllowReview,
		TM.IsAutoPostResultToExam,
		TM.IsObsolete,
		TM.TotalMarks,
		DSM.Title AS DataSubjectTitle,
		TM.ClassGroupId,
		CGM.Title AS ClassGroupTitle,
		TM.DataBankId,
		DBM.Title AS DataBank,
		TM.ClassId,
		TM.ClassSubjectId,
		TM.TestTemplateId,
		CM.Title AS ClassName,
		CS.SubjectName AS ClassSubjectName,	
		'' AS TestTemplateName,
		ISNULL(AssignedSourceTypeId,0) AS AssignSourceTypeId,
		ISNULL(TestDuration,0) AS TestDuration,
		ISNULL(IsTestLock,0) AS IsTestLock,
		ISNULL(TestQuestion,0) AS TestQuestion,
		ISNULL(TM.IsMarkInDecimal,0) AS IsMarkInDecimal,
		ISNULL(TM.IsAutoFinishOnTime,0) AS IsAutoFinishOnTime,
		ISNULL(TM.TestStartupRemark,'') AS TestStartupRemark,
		ISNULL(TM.AlertDuration,0) AS AlertDuration,
		ISNULL(NegativeMarkPerAnswer,0) AS NegativeMarkPerAnswer,
		ISNULL(TM.FromDate,'')AS FromDate,
		ISNULL(TM.ToDate,'')AS ToDate,
		ISNULL(TM.TestTypeId,725) AS TestTypeId,
		ISNULL(TM.AssignEmployeeId,0) AS AssignEmployeeId,
		(CASE WHEN TM.TestTypeId=726 THEN 'Subjective' ELSE 'Objective' END) AS TestType,
		ISNULL(TM.IsUploadImage,0) AS IsUploadImage,
		ISNULL(TM.IsQuestionRemark,0) AS IsQuestionRemark
		--TM.IsMarkInDecimal
									   
	    --VBC.ClassName      
  FROM 
        sEExam.tTestMaster TM
        INNER JOIN  sEExam.tDataSubjectMaster DSM
        ON DSM.Id = TM.DataSubjectId
        INNER JOIN sEExam.tDataBankMaster DBM ON DBM.Id = TM.DataBankId
        INNER JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = TM.ClassGroupId
        INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
        INNER JOIN [sSetup].[vClassSubject] CS ON CS.ClassSubjectId = TM.ClassSubjectId  
        
  WHERE  
		   ((TM.Id = @rId) OR (@rId = 0))
      AND  ((TM.OrgId = @rOrgId) OR (@rOrgId = 0))
      AND  ((TM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      AND  ((TM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
      AND  (TM.ClassGroupId = @rClassGroupId OR @rClassGroupId = 0) 
      AND  (TM.DataSubjectId = @rDataSubjectId OR @rDataSubjectId = 0)
      AND  (TM.ClassId = @rClassId OR @rClassId = 0)
      AND  (TM.ClassSubjectId = @rClassSubjectId OR @rClassSubjectId = 0)
      AND  (TM.TestTemplateId = @rTestTemplateId OR @rTestTemplateId = 0)
      AND  (TM.DataBankId = @rDataBankId OR @rDataBankId = 0)
      AND  (TM.IsObsolete = @rIsObsolete)
      AND  TM.BatchId = @rBatchId
	  AND ((TM.TestDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	  AND ((TM.TestDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND  (ISNULL(TM.TestTypeId,725) = @rTestTypeId OR @rTestTypeId = 0)

	ORDER BY TM.TestDate DESC
      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTestMasterRemove]
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	

			IF  EXISTS (Select 1 FROM sEExam.tTestquestion Where TestId = @rId)	
			BEGIN
			 SELECT -101 AS RESULT
			 RETURN
			END

			
			IF  EXISTS (Select 1 FROM sEExam.tTestParticipant Where TestId = @rId)	
			BEGIN
			 SELECT -102 AS RESULT
			 RETURN
			END
			
			IF EXISTS(Select 1 from sEExam.tTestAssign Where TestId = @rId)	
			BEGIN
			 SELECT -103 AS RESULT
			 RETURN
			END
			
			
		  IF EXISTS(Select 1 from sEExam.tTestParticipantAnswer Where TestId = @rId)	
			BEGIN
			 SELECT -104 AS RESULT
			 RETURN
			END
			
		BEGIN TRY
		BEGIN TRANSACTION			 	   
				    Delete FROM sEExam.tTestMaster Where Id = @rId	
				    DELETE FROM sEExam.tTestquestion Where TestId = @rId
				 	SELECT 1 AS RESULT		
				 
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
	    SELECT 0 AS RESULT
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTestParticipantAdd]
	  
	@rId bigint,
	@rTestId int,
	@rSourceId bigint,
	@rSourceTypeId int, 
	@rTestDate date=NULL,
	@rStartTime time(7)=NULL,
	@rEndTime time(7)=NULL,
	@rTestStatusId smallint=NULL,
	@rTotalMarks decimal(6,2)=NULL,
	@rScoredMarks decimal(6,2)=NULL,
	@rTotalQuestions int=NULL,
	@rRightQuestions int=NULL,
	@rWrongQuestions int=NULL,
	@rNotAttemptedQuestions int=NULL,
	@rSkippQuestion int=NULL,
	@rOrgId int,
	@rMode smallint,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF(@rId = 0)
	BEGIN 
	DECLARE @lNextNumber bigint     
	EXECUTE sCommon.pTableRowIdGet  @rOrgId, 'sEExam.tTestParticipant', 0, 1, 1,@outNextNumber = @lNextNumber output
	END 

	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	
 IF(@rSourceTypeId = 2005)
   BEGIN   
		 DELETE TP FROM sEExam.tTestParticipant TP INNER JOIN sStudent.vStudentAcademic VSA 
		 ON TP.SourceId = VSA.StudentId 
		 Where DivisionId = @rSourceId  AND TestId = @rTestId AND VSA.BatchId=@rBatchId
		 

		  --Delete Participant Answer
			--DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
			--INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
			--INNER JOIN sStudent.vStudentAcademic VSA ON TP.SourceId = VSA.StudentId 
			--WHERE TPA.TestId= @rTestId  
			--AND VSA.DivisionId = @rSourceId  AND VSA.BatchId = @rBatchId

		    --IF(@rId = 0)
		     BEGIN
			 INSERT INTO sEExam.tTestParticipant
			 SELECT @rTestId,2003,StudentId,@rTestDate,@rStartTime,@rEndTime,543,
			 @rTotalMarks,@rScoredMarks,@rTotalQuestions,@rRightQuestions,@rWrongQuestions,@rNotAttemptedQuestions,@rSkippQuestion,@lNextNumber + ROW_NUMBER() over(order by StudentId desc),''
			 FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId AND VSA.BatchId=@rBatchId
			  
			 SELECT @lNextNumber = MAX(Id) from sEExam.tTestParticipant where Id like  CONVERT(nvarchar(50),@rOrgId) + '%'
             EXECUTE sCommon.pTableRowIdModify  @rOrgId,'sEExam.tTestParticipant',@lNextNumber,0,0,0,@lNextNumber output 
			  
			 UPDATE  TA 
			 SET TA.TestStatusId = 543
			 FROM sEExam.tTestAssign TA INNER JOIN sStudent.vStudentAcademic VSA 
			 ON TA.SourceId = VSA.StudentId 
			 Where DivisionId = @rSourceId AND TA.TestId = @rTestId  AND VSA.BatchId=@rBatchId
			 END
           
         SELECT 1 AS Result 
   END 
    --EXECUTE sCommon.pTableRowIdModify   @rOrgId,'sEExam.tTestParticipant',@lNextNumber,0,0,0,@lNextNumber output 
   
ELSE
	 
   IF NOT EXISTS(SELECT 1 FROM sEExam.tTestParticipant Where  TestId = @rTestId 
   AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId)	
   BEGIN
  
	INSERT INTO sEExam.tTestParticipant
		(
			Id,
			TestId,
			SourceId,
			SourceTypeId,
			TestDate,
			StartTime,
			EndTime,
			TestStatusId,
			TotalMarks,
			ScoredMarks,
			TotalQuestions,
			RightQuestions,
			WrongQuestions,
			NotAttemptedQuestions,
			SkippQuestions			
		)
	VALUES
		(
			@lNextNumber,
			@rTestId,
			@rSourceId,
			@rSourceTypeId,
			@rTestDate,
			CONVERT(CHAR(7),@rStartTime,108),
			--@rStartTime,
			@rEndTime,
			@rTestStatusId,
			@rTotalMarks,
			@rScoredMarks,
			@rTotalQuestions,
			@rRightQuestions,
			@rWrongQuestions,
			@rNotAttemptedQuestions,
			@rSkippQuestion
			
		)    
	--UPDATE sEExam.tTestParticipant SET TestStatusId = 1 WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 --1 For Activated ,0 For Deactivated
	--SELECT 1 AS Result  
	END
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	 IF(@rMode=1)
	 BEGIN
	  
	    UPDATE sEExam.tTestParticipant
	    SET
	     TestDate=@rTestDate,
	     StartTime=@rStartTime,
	     TestStatusId=@rTestStatusId,
	     TotalMarks=@rTotalMarks
	     WHERE Id = @rId
 	     --TestId = @rTestId AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId
	     --SELECT 11 AS Result 	
	 END
	 ELSE IF(@rMode=2)
	 BEGIN
	 
	 UPDATE sEExam.tTestParticipant
	    SET
	     
	     --EndTime=@rEndTime,
	     TestStatusId=@rTestStatusId,
	     ScoredMarks=@rScoredMarks,
	     TotalQuestions=@rTotalQuestions,
	     RightQuestions=@rRightQuestions,
	     WrongQuestions=@rWrongQuestions,
	     NotAttemptedQuestions=@rNotAttemptedQuestions,
	     SkippQuestions = @rSkippQuestion
	      
	     WHERE Id = @rId 
	     --TestId = @rTestId AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId
	     --SELECT 11 AS Result 
	  END    
	 END
	 
	 UPDATE sEExam.tTestParticipant SET TestStatusId = @rTestStatusId WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 --UPDATE sEExam.tTestParticipant SET TestStatusId = @rTestStatusId , ScoredMarks = 0 ,RightQuestions =0 , WrongQuestions =0 ,SkippQuestions =0 ,NotAttemptedQuestions =0 WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 --UPDATE sEExam.tTestAssign SET TestStatusId = @rTestStatusId Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 UPDATE sEExam.tTestAssign SET TestStatusId = @rTestStatusId Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 
    --Delete Participant Answer
		--DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
		--INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
		--INNER JOIN sStudent.vStudentAcademic VSA ON TP.SourceId = VSA.StudentId 
		--WHERE TPA.TestId= @rTestId  
		--AND TP.SourceId = @rSourceId  AND TP.SourceTypeId = @rSourceTypeId

	 SELECT 1 AS Result
	 	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sEExam].[pTestParticipantAnswerAdd]
	 
	--@rId bigint,
	@rTestParticipantId bigint,
	@rTestId int,
	@rQuestionId bigint,
	@rQuestionOptionId bigint=NULL,
	@rScoredMarks decimal(6,2)=NULL,
	@rAnswerStatusId smallint,
	@rOrgId int,
	@rDetailXml [nvarchar](max),
	@rIsXml bit,
	@rSourceId bigint = 0,
	@rSourceTypeID int = 0,
	--@rTestTypeId int,
	@rQuestionAnswer nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION
--IF(@rTestTypeId = 725)
--BEGIN
IF NOT EXISTS (SELECT 1 FROM sEExam.tTestParticipantAnswer TPA WHERE TPA.TestParticipantId = @rTestParticipantId)
AND (@rIsXml = 1)	
BEGIN

	DECLARE @loDoc INT
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDetailXml
	BEGIN TRY	
	
	--BEGIN TRANSACTION
	
	--DECLARE @lNextNumber bigint     
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tTestParticipantAnswer', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sEExam.tTestParticipantAnswer
		(
			TestParticipantId,
			TestId,
			QuestionId,
			AnswerStatusId,
			OrderIndex,
			QuestionAnswer
		)
	  SELECT 
			TestParticipantId,
			TestId,
			QuestionId,
			AnswerStatusId,
			OrderIndex,
			sSetup.fPortalXMLTagsReplaceReverse(QuestionAnswer)
			
			
		FROM OPENXML (@loDoc, '/Table/Detail', 1)
		WITH ( 
		        TestParticipantId bigint,
 				TestId Int,
				QuestionId bigint,
				AnswerStatusId smallint,
				OrderIndex smallint,
				QuestionAnswer nvarchar(max)
			  ) 
		SELECT 1 AS Result   
		 
		--COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		--ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	 
	 
	EXEC sp_xml_removedocument @loDoc
       
	END	
	 
	 ELSE
	 BEGIN
	 BEGIN TRY
	
	    --BEGIN TRANSACTION
	    --SET @lNextNumber = @rId
	    UPDATE sEExam.tTestParticipantAnswer
	    SET
	    QuestionOptionId=@rQuestionOptionId,
	    ScoredMark=@rScoredMarks,
	    AnswerStatusId=@rAnswerStatusId,
		QuestionAnswer=sSetup.fPortalXMLTagsReplaceReverse(@rQuestionAnswer)
	      
        WHERE TestParticipantId = @rTestParticipantId AND QuestionId = @rQuestionId
        SELECT 11 AS Result  
		--COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		--ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	END
--END

--ELSE IF(@rTestTypeId = 726)	
--BEGIN
	
--	IF NOT EXISTS (SELECT 1 FROM sEExam.tTestParticipantAnswer TPA WHERE TPA.TestParticipantId = @rTestParticipantId)
--AND (@rIsXml = 1)	
--BEGIN

--	DECLARE @lDoc INT
--	EXEC sp_xml_preparedocument @lDoc OUTPUT, @rDetailXml
--	BEGIN TRY	
	
--	INSERT INTO sEExam.tTestParticipantAnswer
--		(
--			TestParticipantId,
--			TestId,
--			QuestionId,
--			AnswerStatusId,
--			OrderIndex,
--			QuestionAnswer
--		)
--	  SELECT 
--			TestParticipantId,
--			TestId,
--			QuestionId,
--			AnswerStatusId,
--			OrderIndex,
--			QuestionAnswer
			
--		FROM OPENXML (@lDoc, '/Table/Detail', 1)
--		WITH ( 
--		        TestParticipantId bigint,
-- 				TestId Int,
--				QuestionId bigint,
--				AnswerStatusId smallint,
--				OrderIndex smallint,
--				QuestionAnswer nvarchar(max)
--			  ) 
--		SELECT 1 AS Result   
	
--	END TRY
	
--	BEGIN CATCH 
		
--		SELECT -1 AS Result
--	END CATCH	 
	 
--	EXEC sp_xml_removedocument @lDoc
       
--	END	
	 
--	 ELSE
--	 BEGIN
--	 BEGIN TRY
	
--	    UPDATE sEExam.tTestParticipantAnswer
--	    SET
--	    QuestionOptionId=@rQuestionOptionId,
--	    ScoredMark=@rScoredMarks,
--	    AnswerStatusId=@rAnswerStatusId,
--		QuestionAnswer=@rQuestionAnswer
	      
--        WHERE TestParticipantId = @rTestParticipantId AND QuestionId = @rQuestionId
--        SELECT 11 AS Result  
	
--	END TRY
	
--	BEGIN CATCH 
		
--		SELECT -1 AS Result
--	END CATCH	
	
--	END

--END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTestParticipantAnswerDetailAdd]
			@rTestId int
           ,@rQuestionId bigint
           ,@rQuestionOptionId bigint
           ,@rScoredMark decimal(6,2)
           ,@rAnswerStatusId smallint
           ,@rOrderIndex smallint
           ,@rTestParticipantId bigint
           ,@rQuestionAnswer nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 IF EXISTS (SELECT 1 FROM sEExam.tTestParticipantAnswer WHERE TestId = @rTestId AND TestParticipantId = @rTestParticipantId)
	 BEGIN
		UPDATE sEExam.tTestParticipantAnswer 
		SET
            [TestId] = @rTestId
           ,[QuestionId] = @rQuestionId
           ,[QuestionOptionId] = @rQuestionOptionId
           ,[ScoredMark] = @rScoredMark
           ,[AnswerStatusId] = @rAnswerStatusId
           ,[OrderIndex] = @rOrderIndex
           ,[TestParticipantId] = @rTestParticipantId
           ,[QuestionAnswer] = @rQuestionAnswer
		WHERE TestId = @rTestId AND TestParticipantId = @rTestParticipantId
	 END
	 ELSE
	 BEGIN
		INSERT INTO sEExam.tTestParticipantAnswer  
		(
			[TestId]
           ,[QuestionId]
           ,[QuestionOptionId]
           ,[ScoredMark]
           ,[AnswerStatusId]
           ,[OrderIndex]
           ,[TestParticipantId]
           ,[QuestionAnswer]
		)
		Values
		(
			@rTestId 
           ,@rQuestionId 
           ,@rQuestionOptionId 
           ,@rScoredMark 
           ,@rAnswerStatusId 
           ,@rOrderIndex 
           ,@rTestParticipantId 
           ,@rQuestionAnswer 
		)
	 END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pTestParticipantAnswerGet]

		 @rTestParticipantId bigint
			
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
SELECT  
	--0 AS  TestParticipantId,
	TPA.TestParticipantId AS  TestParticipantId,
	ISNULL(TPA.QuestionId,0) AS QuestionId,
	ISNULL(TPA.QuestionOptionId,0) AS QuestionOptionId,
	ISNULL(TQM.Marks,0)AS QuestionMarks,
	ISNULL(TPA.ScoredMark,0)AS ScoredMarks,
	TPA.AnswerStatusId,
	ISNULL(TPA.OrderIndex,0)AS OrderIndex,
	ISNULL(QO.IsKey,0)AS IsKey,
	TPA.TestId
	
FROM  
	sEExam.tTestParticipantAnswer TPA
	INNER JOIN sEExam.tTestParticipant TP ON TP.Id = TPA.TestParticipantId
	INNER JOIN sEExam.tTestQuestion TQM ON TQM.QuestionId = TPA.QuestionId AND TP.TestId = TQM.TestId
	--INNER JOIN sEExam.tQuestionMaster TQ  ON TPA.QuestionId=TQ.Id
	LEFT JOIN sEExam.tQuestionOption  QO  ON QO.Id=TPA.QuestionOptionId AND QO.QuestionId = TPA.QuestionId
	
WHERE 
 
	TPA.TestParticipantId = @rTestParticipantId 
	  
	 --TQ.TestId=@rTestId
	 --AND 
	 --TPA.TestId=@rTestId  AND TP.SourceId = @rSourceId AND TP.SourceTypeId = @rSourceTypeId
	 --AND TPA.QuestionId = @rQuestionId
		
	ORDER BY TPA.OrderIndex,QO.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sEExam].[pTestParticipantDetailAdd]
	
		@rTestParticipantDetailXml nvarchar(max),
		@rTestparticipantAnswerDetailXml nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
	
	BEGIN TRANSACTION

	--TestParticipant

	DECLARE @TestParticipantDetail XML  
    SET @TestParticipantDetail = CAST(@rTestParticipantDetailXml AS XML) 
	 
	CREATE TABLE #TempTestParticipant 
	(  
	RowIndex INT IDENTITY(1, 1), 
	TestId int,
    SourceTypeId smallint,
    SourceId bigint,
    TestDate date,
    StartTime time(7),
    EndTime time(7),
    TestStatusId smallint,
    TotalMarks decimal(6,2),
    ScoredMarks decimal(6,2),
    TotalQuestions int,
    RightQuestions int,
    WrongQuestions int,
    SkippQuestions int,
    NotAttemptedQuestions int,
    Id bigint,
    TimeTaken time(7)
	)
	 
	INSERT INTO #TempTestParticipant  
    SELECT           
            T.c.value('@TestId', 'int') AS TestId,
            T.c.value('@SourceTypeId', 'smallint') AS SourceTypeId, 
            T.c.value('@SourceId', 'bigint') AS SourceId,
			Convert(DateTime,T.c.value('@TestDate', 'NVARCHAR(MAX)'),103) AS TestDate,
			Convert(Time(7),T.c.value('@StartTime', 'NVARCHAR(MAX)'),24) AS StartTime,
			Convert(Time(7),T.c.value('@EndTime', 'NVARCHAR(MAX)'),24) AS EndTime,
			T.c.value('@TestStatusId', 'smallint') AS TestStatusId,
			T.c.value('@TotalMarks', 'decimal(6,2)') AS TotalMarks,
			T.c.value('@ScoredMarks', 'decimal(6,2)') AS ScoredMarks,
			T.c.value('@TotalQuestions', 'int') AS TotalQuestions,
			T.c.value('@RightQuestions', 'int') AS RightQuestions,
			T.c.value('@WrongQuestions', 'int') AS WrongQuestions,
			T.c.value('@SkippQuestions', 'int') AS SkippQuestions,
			T.c.value('@NotAttemptedQuestions', 'int') AS NotAttemptedQuestions,
			T.c.value('@Id', 'bigint') AS Id,
			T.c.value('@TimeTaken', 'time(7)') AS TimeTaken
    FROM   
            @TestParticipantDetail.nodes('/Table/TestParticipantDetail')T(c)  
	
	Declare @lCount int=1
	WHILE(@lCount <= (SELECT count(*) FROM #TempTestParticipant))                
	BEGIN
		DECLARE @TestId int,@Id bigint

		SELECT @TestId = TestId , @Id = Id FROM #TempTestParticipant WHERE RowIndex = @lCount

		IF EXISTS (SELECT 1 FROM sEExam.tTestParticipant WHERE TestId = @TestId AND Id = @Id)
		 BEGIN
			UPDATE sEExam.tTestParticipant 
			SET
			    [SourceTypeId] = A.SourceTypeId
			   ,[SourceId] = A.SourceId
			   ,[TestDate] = A.TestDate
			   ,[StartTime] = A.StartTime
			   ,[EndTime] = A.EndTime
			   ,[TestStatusId] = A.TestStatusId
			   ,[TotalMarks] = A.TotalMarks
			   ,[ScoredMarks] = A.ScoredMarks
			   ,[TotalQuestions] = A.TotalQuestions
			   ,[RightQuestions] = A.RightQuestions
			   ,[WrongQuestions] = A.WrongQuestions
			   ,[SkippQuestions] = A.SkippQuestions
			   ,[NotAttemptedQuestions] = A.NotAttemptedQuestions
			   ,[TimeTaken] = A.TimeTaken
			FROM
			#TempTestParticipant A
			WHERE sEExam.tTestParticipant.Id = A.Id AND sEExam.tTestParticipant.TestId = A.TestId AND A.Id = @Id AND A.TestId = @TestId
		 END
		 ELSE
		 BEGIN
			INSERT INTO sEExam.tTestParticipant  
			(
				[TestId]
			   ,[SourceTypeId]
			   ,[SourceId]
			   ,[TestDate]
			   ,[StartTime]
			   ,[EndTime]
			   ,[TestStatusId]
			   ,[TotalMarks]
			   ,[ScoredMarks]
			   ,[TotalQuestions]
			   ,[RightQuestions]
			   ,[WrongQuestions]
			   ,[SkippQuestions]
			   ,[NotAttemptedQuestions]
			   ,[Id]
			   ,[TimeTaken]
			)
			SELECT 
				[TestId]
			   ,[SourceTypeId]
			   ,[SourceId]
			   ,[TestDate]
			   ,[StartTime]
			   ,[EndTime]
			   ,[TestStatusId]
			   ,[TotalMarks]
			   ,[ScoredMarks]
			   ,[TotalQuestions]
			   ,[RightQuestions]
			   ,[WrongQuestions]
			   ,[SkippQuestions]
			   ,[NotAttemptedQuestions]
			   ,[Id]
			   ,[TimeTaken]
			 FROM #TempTestParticipant WHERE Id = @Id AND TestId = @TestId 
		 END

		 SET @lCount = @lCount + 1
	END
  
  --TestParticipantAnswer

	  DECLARE @TestParticipantAnswerDetail XML  
	  SET @TestParticipantAnswerDetail = CAST(@rTestParticipantAnswerDetailXml AS XML) 

	  CREATE TABLE  #TempTestParticipantAnswer 
	  (  
		RowIndex INT IDENTITY(1, 1), 
		TestId int,
		QuestionId bigint,
		QuestionOptionId bigint,
		ScoredMark decimal(6,2),
		AnswerStatusId smallint,
		OrderIndex smallint,
		TestParticipantId bigint,
		QuestionAnswer nvarchar(max)
	  )

	INSERT INTO #TempTestParticipantAnswer
    SELECT           
            T.c.value('@TestId', 'int') AS TestId,
            T.c.value('@QuestionId', 'bigint') AS QuestionId,
            T.c.value('@QuestionOptionId', 'bigint') AS QuestionOptionId,
			T.c.value('@ScoredMark', 'decimal(6,2)') AS ScoredMark,          
			T.c.value('@AnswerStatusId', 'smallint') AS AnswerStatusId,
			T.c.value('@OrderIndex', 'smallint') AS OrderIndex,
			T.c.value('@TestParticipantId', 'bigint') AS TestParticipantId,
			T.c.value('@QuestionAnswer', 'nvarchar(max)') AS QuestionAnswer
    FROM   
            @TestParticipantAnswerDetail.nodes('/Table/TestParticipantAnswerDetail')T(c)  

	SET @lCount = 1
	WHILE(@lCount <= (SELECT count(*) FROM #TempTestParticipantAnswer))                
	BEGIN

		DECLARE @TestParticipantId bigint , @QuestionId  bigint

		SELECT @TestId = TestId , @TestParticipantId = TestParticipantId , @QuestionId = QuestionId FROM #TempTestParticipantAnswer WHERE RowIndex = @lCount

		IF EXISTS (SELECT 1 FROM sEExam.tTestParticipantAnswer WHERE TestId = @TestId AND TestParticipantId = @TestParticipantId AND QuestionId = @QuestionId)
		 BEGIN
			UPDATE sEExam.tTestParticipantAnswer
			SET
			    [TestId] = A.TestId
			   ,[QuestionId] = A.QuestionId
			   ,[QuestionOptionId] = A.QuestionOptionId
			   ,[ScoredMark] = A.ScoredMark
			   ,[AnswerStatusId] = A.AnswerStatusId
			   ,[OrderIndex] = A.OrderIndex
			   ,[TestParticipantId] = A.TestParticipantId
			   ,[QuestionAnswer] = A.QuestionAnswer
			FROM
				#TempTestParticipantAnswer A
			WHERE sEExam.tTestParticipantAnswer.TestParticipantId = A.TestParticipantId AND sEExam.tTestParticipantAnswer.TestId = A.TestId AND sEExam.tTestParticipantAnswer.QuestionId = A.QuestionId
			AND A.TestParticipantId = @TestParticipantId AND A.TestId = @TestId AND A.QuestionId = @QuestionId
		 END
		 ELSE
		 BEGIN
			INSERT INTO sEExam.tTestParticipantAnswer
			(
				[TestId]
			   ,[QuestionId]
			   ,[QuestionOptionId]
			   ,[ScoredMark]
			   ,[AnswerStatusId]
			   ,[OrderIndex]
			   ,[TestParticipantId]
			   ,[QuestionAnswer]
			)
			SELECT 
				[TestId]
			   ,[QuestionId]
			   ,[QuestionOptionId]
			   ,[ScoredMark]
			   ,[AnswerStatusId]
			   ,[OrderIndex]
			   ,[TestParticipantId]
			   ,[QuestionAnswer]
			 FROM #TempTestParticipantAnswer WHERE TestParticipantId = @TestParticipantId AND TestId = @TestId AND QuestionId = @QuestionId
		 END
		 SET @lCount = @lCount + 1
	END

	DROP TABLE #TempTestParticipant
	DROP TABLE #TempTestParticipantAnswer

	SELECT 1 AS RESULT
COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pTestParticipantGet]

			--@rClassId int,
			@rDivisionId int,
			@rTestId int,
			@rBatchId int,
			@rSourceId bigint,
			@rSourceTypeID int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN   
    SELECT  
			--VSA.AcademicId,
			VSA.RollNo,
			VSA.Name AS StudentName,
			VSA.Code,
		    ISNULL(TP.Id,0) AS TestParticipantId,
			ISNULL(TP.TestStatusId,0) AS TestStatusId       
    FROM 
			sStudent.vStudentAcademic VSA
		LEFT JOIN sEExam.tTestParticipant TP
			ON TP.SourceID=VSA.StudentId AND (TP.TestId=@rTestId)
		LEFT JOIN sCommon.tStatusMaster SM
			ON SM.Id=TP.TestStatusId 
	WHERE 
			VSA.DivisionId=@rDivisionId
			AND VSA.BatchId=@rBatchId 
		
ORDER BY VSA.RollNo ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sEExam].[pTestParticipantIndividualAnswerAdd]
	 
	@rTestParticipantId bigint,
	@rTestId int,
	@rQuestionDetailXml [nvarchar](max),
	@rQuestionOptionDetailXml [nvarchar](max),
	@rQuestionId bigint=0, 
	@rQuestionOptionId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @loQuestionDoc INT
	EXEC sp_xml_preparedocument @loQuestionDoc OUTPUT, @rQuestionDetailXml
	
	DECLARE @loQuestionOptionDoc INT
	EXEC sp_xml_preparedocument @loQuestionOptionDoc OUTPUT, @rQuestionOptionDetailXml
	
BEGIN

	BEGIN TRY	
	BEGIN TRANSACTION
	
	--SELECT * FROM sEExam.tTestParticipantAnswer WHERE TestParticipantId=@rTestParticipantId AND TestId=@rTestId AND QuestionId=@rQuestionId 
	DELETE FROM sEExam.tTestParticipantAnswer WHERE TestParticipantId=@rTestParticipantId AND TestId=@rTestId AND QuestionId=@rQuestionId 
	--AND QuestionOptionId=@rQuestionOptionId
	
	UPDATE sEExam.tTestParticipant
	    SET
			TestDate = A.TestDate,
			StartTime = A.StartTime,
			EndTime = A.EndTime,
			TestStatusId = A.TestStatusId,
			TotalMarks = A.TotalMarks,
			ScoredMarks = A.ScoredMarks,
			TotalQuestions = A.TotalQuestions,
			RightQuestions = A.RightQuestions,
			WrongQuestions = A.WrongQuestions,
			SkippQuestions = A.SkippQuestions,
			NotAttemptedQuestions = A.NotAttemptedQuestions
			FROM
		 (
	  SELECT TOP 1
	        @rTestParticipantId AS TestParticipantId,
	        @rTestId AS TestId,
			TestDate,
			StartTime,
			EndTime,
			TestStatusId,
			TotalMarks,
			ScoredMarks,
			TotalQuestions,
			RightQuestions,
			WrongQuestions,
			SkippQuestions,
			NotAttemptedQuestions
		FROM OPENXML (@loQuestionDoc, '/Table/QuestionDetail', 1)
		WITH ( 
		        SourceTypeId smallint,
			    SourceId bigint,
			    TestDate date,
			    StartTime time,
			    EndTime time,
			    TestStatusId smallint,
				TotalMarks decimal(6,2),
				ScoredMarks decimal(6,2),
				TotalQuestions int,
				RightQuestions int,
				WrongQuestions int,
				SkippQuestions int,
				NotAttemptedQuestions int
			  ))A	
			    WHERE A.TestParticipantId = @rTestParticipantId AND A.TestId = @rTestId
			    AND sEExam.tTestParticipant.Id = A.TestParticipantId
			    
	INSERT INTO sEExam.tTestParticipantAnswer
		(
			TestId,
			QuestionId,
			QuestionOptionId,
			ScoredMark,
			AnswerStatusId,
			OrderIndex,
			TestParticipantId
		)
	  SELECT 
			@rTestId,
			QuestionId,
			QuestionOptionId,
			ScoredMark,
			AnswerStatusId,
			OrderIndex,
			@rTestParticipantId
			
		FROM OPENXML (@loQuestionOptionDoc, '/Table/QuestionOptionDetail', 1)
		WITH ( 
		        TestId Int,
				QuestionId bigint,
				QuestionOptionId bigint,
				ScoredMark decimal(6,2),
				AnswerStatusId smallint,
				OrderIndex smallint
			  ) 
		SELECT 1 AS Result   
		
		SELECT IsDisplayResultOnComplete FROM sEExam.tTestMaster WHERE Id =@rTestId
		
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		EXEC sp_xml_removedocument @loQuestionDoc
		EXEC sp_xml_removedocument @loQuestionOptionDoc
	END CATCH	 
	 
	
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTestParticipantRemove]
	 
	 @rTestId bigint,
	 @rSourceId bigint,
	 @rSourceTypeId int	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sEExam.tTestParticipant where TestId=@rTestId 
			AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId
			SELECT 11 AS Result
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTestParticipantResultGet]
 
			@rBuilder1 nvarchar(max)='',
			@rTestId int,		 
			@rSourceTypeID int = 0,
			@rSourceId bigint = 0,
			@rBatchId int=0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN   

DECLARE @1TestAssignStatusId int

 
IF(@rSourceTypeID = 2003)
   BEGIN
	 SELECT  
	     @rBuilder1 AS Builder1,
		 VSA.RollNo,
		 VSA.Name,
		 VSA.Code,
		 P.SourceId,
		 P.SourceTypeId,	
	     ISNULL(P.TotalMarks,0) AS TotalMarks,
		 ISNULL(P.ScoredMarks,0) AS ScoredMarks,
		 ISNULL(P.TotalQuestions,0) AS TotalQuestions,
		 ISNULL(P.RightQuestions,0) AS RightQuestions,
		 ISNULL(P.WrongQuestions,0) AS WrongQuestions,
		 --(ISNULL(P.WrongQuestions,0) - (ISNULL(P.NotAttemptedQuestions,0)+ ISNULL(P.SkippQuestions,0))) AS WrongQuestions,
		 ISNULL(P.NotAttemptedQuestions,0) AS NotAttemptedQuestions,
		 ISNULL(P.SkippQuestions,0) AS SkippQuestions,
		 'Student' AS TypeName,
		 VSA.ClassName+'-'+VSA.DivisionName As ClassName,
		 ISNULL(TM.IsMarkInDecimal,0) AS IsMarkInDecimal,
		 P.Id AS TestParticipantId,
		 VSA.AcademicId,
		 TM.Title As TestName,
		 P.TestStatusId
		 --TM.IsMarkInDecimal
		 FROM sEExam.tTestParticipant P INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
		 INNER JOIN sStudent.vStudentAcademic VSA ON VSA.StudentId = P.SourceId AND P.SourceTypeId=2003
		 Where (SourceTypeId = @rSourceTypeID OR @rSourceTypeID = 0) AND TestId = @rTestId
		 AND TestStatusId != 0 AND (P.SourceId = @rSourceId or @rSourceId = 0)
		 AND TM.BatchId=@rBatchId AND VSA.BatchId=@rBatchId
		
		ORDER BY DivisionId, VSA.RollNo ASC
		END
		ELSE 
		     Select 	
			 @rBuilder1 AS Builder1,		
			 ECD.Code AS RollNo,
			 ECD.EmployeeName AS Name,
			 ECD.Code,
			 P.SourceId,
			 P.SourceTypeId,			
			 ISNULL(P.TotalMarks,0) AS TotalMarks,
			 ISNULL(P.ScoredMarks,0) AS ScoredMarks,
			 ISNULL(P.TotalQuestions,0) AS TotalQuestions,
			 ISNULL(P.RightQuestions,0) AS RightQuestions,
			 ISNULL(P.WrongQuestions,0) AS WrongQuestions,
			 ISNULL(P.SkippQuestions,0) AS SkippQuestions,
			 ISNULL(P.NotAttemptedQuestions,0) AS NotAttemptedQuestions,
		     'Employee' AS TypeName,
		     ECD.DepartmentName AS ClassName,
		     ISNULL(TM.IsMarkInDecimal,0) AS IsMarkInDecimal,
		     P.Id AS TestParticipantId,
			 P.TestStatusId
		     --TM.IsMarkInDecimal
			 
			 FROM sEExam.tTestParticipant P INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
			 INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = P.SourceId 
			 AND TestStatusId != 0 
 
			 Where (SourceTypeId = @rSourceTypeID OR @rSourceTypeID = 0) AND TestId = @rTestId   
			  AND TestStatusId != 0  AND (P.SourceId = @rSourceId or @rSourceId = 0)
			  AND TM.BatchId=@rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTestQuestionAdd]
	
	 
	@rTestId bigint,
	@rQuestionId bigint,
	@rMarks decimal(6,2),
	@rOrgId int,
	@rOrderIndex int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
    
    DECLARE @1LastOrderIndex int

	--DECLARE @lNextNumber BIGINT     
	
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tTestQuestion', 0, 1, 1,@outNextNumber = @lNextNumber output
  
IF NOT EXISTS (SELECT 1 FROM sEExam.tTestQuestion Where TestId = @rTestId AND QuestionId = @rQuestionId)
  BEGIN
     
    SELECT @1LastOrderIndex =  ISNULL(MAX(OrderIndex),0) + 1 From sEExam.tTestQuestion where TestId = @rTestId   
  
	INSERT INTO sEExam.tTestQuestion
		(  
			TestId,
			QuestionId,
			Marks,
			OrderIndex
		)
	VALUES
		( 
			@rTestId,
			@rQuestionId,
			@rMarks,
			@1LastOrderIndex
		)		
	END
	ELSE
	BEGIN
		   
	   UPDATE sEExam.tTestQuestion
	   
	   SET   OrderIndex = @rOrderIndex,
	         Marks = @rMarks	
	                  	   
	   Where TestId = @rTestId AND QuestionId = @rQuestionId       
	   
	END	  
		   SELECT 1 AS Result
		   COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pTestQuestionListGet]
	 	 
	 @rTopicId int,
	 @rTestId int,
	 @rIsQuestionBank bit,
	 @rQuestionTypeId int=0
	 	 
     WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 

BEGIN 

IF(@rQuestionTypeId =727 )
BEGIN
	IF(@rIsQuestionBank=1)
	BEGIN 
	SELECT 		
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.QuestionDescription2,
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId,
		QP.QuestionParagraphDescription2,
		ISNULL(QP.Id,0) AS QuestionParagraphId,
		0 AS TestQuestions			 
      
 FROM   sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
		ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
		ON DLM.Id=QM.DifficultyLevelId 
		LEFT JOIN sEExam.tQuestionParagraph QP ON QP.Id=QM.QuestionParagraphId 
	          
 WHERE 		
		((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
		AND (QM.Id not in (SELECT QuestionId from sEExam.tTestQuestion WHERE TestId=@rTestId )OR (@rTestId=0))
		AND ((ISNULL(QM.QuestionTypeId,727) = @rQuestionTypeId) OR (@rQuestionTypeId = 0))
		AND QM.IsObsolete = 0

		
ORDER BY QuestionDescription2 ASC

 END	
	ELSE	
BEGIN
	SELECT 
	       QM.Id AS QuestionId,
		   QM.TopicId,
		   DLM.Id AS DifficultyLevelId,
		   QM.QuestionDescription,
		   QM.QuestionDescription2,
		   TQ.Marks,
		   QM.IsObsolete,
		   ISNULL(TQ.OrderIndex,0) AS OrderIndex,
		   DLM.Title AS DifficultyLevel,
		   TM.Title AS Topic,
		   ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId  ,
		   ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParagraphDescription2,
		   ISNULL(QP.Id,0) AS QuestionParagraphId
	FROM 
			sEExam.tQuestionMaster QM
		    INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		    INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
            INNER JOIN sEExam.tTestQuestion TQ
			ON TQ.QuestionId=QM.Id      
			LEFT JOIN sEExam.tQuestionParagraph QP ON QP.Id=QM.QuestionParagraphId       
	WHERE 
			TQ.TestId=@rTestId
			AND ((ISNULL(QM.QuestionTypeId,727) = @rQuestionTypeId) OR (@rQuestionTypeId = 0))
			
	order by QuestionDescription2 desc,TQ.OrderIndex
END
END
ELSE
BEGIN
	IF(@rIsQuestionBank=1)
	BEGIN 
	SELECT 		
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.QuestionDescription2,
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId,
		QP.QuestionParagraphDescription2,
		ISNULL(QP.Id,0) AS QuestionParagraphId,
		0 AS TestQuestions			 
      
 FROM   sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
		ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
		ON DLM.Id=QM.DifficultyLevelId 
		LEFT JOIN sEExam.tQuestionParagraph QP ON QP.Id=QM.QuestionParagraphId 
	          
 WHERE 		
		((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
		AND (QM.Id not in (SELECT QuestionId from sEExam.tTestQuestion WHERE TestId=@rTestId )OR (@rTestId=0))
		AND QM.IsObsolete = 0
		AND ((QM.QuestionTypeId = @rQuestionTypeId) OR (@rQuestionTypeId = 0))
		
		
ORDER BY QuestionDescription2 ASC

 END	
	ELSE	
BEGIN
	SELECT 
	       QM.Id AS QuestionId,
		   QM.TopicId,
		   DLM.Id AS DifficultyLevelId,
		   QM.QuestionDescription,
		   QM.QuestionDescription2,
		   TQ.Marks,
		   QM.IsObsolete,
		   ISNULL(TQ.OrderIndex,0) AS OrderIndex,
		   DLM.Title AS DifficultyLevel,
		   TM.Title AS Topic,
		   ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId  ,
		   ISNULL(QP.QuestionParagraphDescription,'') AS QuestionParagraphDescription2,
		   ISNULL(QP.Id,0) AS QuestionParagraphId
	FROM 
			sEExam.tQuestionMaster QM
		    INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		    INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
            INNER JOIN sEExam.tTestQuestion TQ
			ON TQ.QuestionId=QM.Id      
			LEFT JOIN sEExam.tQuestionParagraph QP ON QP.Id=QM.QuestionParagraphId       
	WHERE 
			TQ.TestId=@rTestId
			AND ((QM.QuestionTypeId = @rQuestionTypeId) OR (@rQuestionTypeId = 0))
			
	order by QuestionDescription2 desc,TQ.OrderIndex
END
END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTestQuestionRemove]
	 
	@rTestId bigint,
	@rQuestionId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION
	--DECLARE @lNextNumber BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tTestQuestion', 0, 1, 1,@outNextNumber = @lNextNumber output

      DELETE FROM sEExam.tTestQuestion Where TestId = @rTestId AND QuestionId = @rQuestionId
  
	  SELECT 1 AS Result          
	
	
	  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -101 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pTestTemplateMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rDataBankId int,
	@rClassGroupId int,
	@rDataSubjectId int,	
	@rClassId int,
	@rSubjectId int,	
	@rTotalMarks decimal(6,2),	
	@rIsObsolete bit,
	@rOrderIndex int,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rOrgGroupId int
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	
		IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sEExam.tTestTemplateMaster where Code=@rCode)
			BEGIN
			select -103 as Result
			RETURN
		END 
 
	END
	--ELSE
	--BEGIN
 
	--	If  Exists(select Id from sEExam.tTopicTypeMaster where Code=@rCode AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	
	
	
	 --BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tTestTemplateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
 


	INSERT INTO sEExam.tTestTemplateMaster
		(
			Id,
			--AffiliationId,
			Code,
			Title,
			ClassId,
			SubjectId,
			TotalMarks,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			DataBankId,
			OrgGroupId,
			ClassGroupId,
			DataSubjectId
		)
	VALUES
		(
			@lNextNumber,
			--@rAffiliationId,
			@rCode,
			@rTitle,
			@rClassId,
			@rSubjectId,
			@rTotalMarks,			
			@rIsObsolete,
			@rOrderIndex,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rDataBankId,
			@rOrgGroupId,
			@rClassGroupId,
			@rDataSubjectId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sEExam.tTestTemplateMaster
	    SET
	      --AffiliationId=@rAffiliationId,
	      Code=@rCode,	     
	      Title=@rTitle,
	      ClassId=@rClassId,
	      SubjectId=@rSubjectId,
	      TotalMarks=@rTotalMarks,
	      IsObsolete=@rIsObsolete,
	      OrderIndex=@rOrderIndex,
	      ClassGroupId = @rClassGroupId,
	      DataSubjectId = @rDataSubjectId,	         
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate()
	   
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
	--	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pTestTemplateMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rDataSubjectId int,
	 @rClassGroupId int,
	 @rDataBankId int,
	 @rOrgId int,
	 @rClassId int,
	 @rClassSubjectId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	 
	SELECT 
	TTM.Id,
	TTM.Code,
	TTM.Title,
	TTM.ClassId,
	TTM.SubjectId,
	TTM.TotalMarks,
	TTM.IsObsolete,
	TTM.OrderIndex,
	TTM.ClassGroupId,
	TTM.DataSubjectId,
	TTM.DataBankId,
	DBM.Title AS DataBank,
	DSM.Title AS DataSubjectTitle,
	CGM.Title AS ClassGroupTitle,
	CM.Title AS ClassName,
	CS.SubjectName AS ClassSubjectName 
      
  FROM 
       sEExam.tTestTemplateMaster TTM 
        INNER JOIN  sEExam.tDataSubjectMaster DSM
        ON DSM.Id = TTM.DataSubjectId
        INNER JOIN sEExam.tDataBankMaster DBM ON DBM.Id = TTM.DataBankId
        INNER JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = TTM.ClassGroupId
        INNER JOIN sSetup.tClassMaster CM ON CM.Id = TTM.ClassId
        INNER JOIN [sSetup].[vClassSubject] CS ON CS.ClassSubjectId = TTM.SubjectId
             
  WHERE 
		
      ((TTM.Id = @rId) OR (@rId = 0)) 
      AND  ((TTM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
      AND  (TTM.OrgGroupId = @rOrgId)
      AND  ((TTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      AND  (TTM.ClassGroupId = @rClassGroupId OR @rClassGroupId = 0) 
      AND  (TTM.DataSubjectId = @rDataSubjectId OR @rDataSubjectId = 0)
      AND  (TTM.ClassId = @rClassId OR @rClassId = 0)
      AND  (TTM.SubjectId = @rClassSubjectId OR @rClassSubjectId = 0) 
      AND  (TTM.DataBankId = @rDataBankId OR @rDataBankId = 0)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTestTemplateQuestionAdd]
	 
	@rTestTemplateId bigint,
	@rQuestionId bigint,
	@rMarks decimal,
	@rOrgGroupId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
 

	DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tTestTemplateQuestion', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sEExam.tTestTemplateQuestion
		(
			 
			TestTemplateId,
			QuestionId,
			Marks
		)
	VALUES
		(
		 
			@rTestTemplateId,
			@rQuestionId,
			@rMarks
		)
     
     SELECT 1 AS Result          
	
	
	-- COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pTestTemplateQuestionListGet]
	 
	 @rTopicId int,
	 @rTestTemplateId int,
	 @rIsQuestionBank bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF(@rIsQuestionBank=1)
	BEGIN 
	SELECT 
		0 AS TestQuestionId,
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId
      
	FROM 
			sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
             
	WHERE 
		
		((QM.TopicId = @rTopicId) OR (@rTopicId = 0))
	AND (QM.Id not in (SELECT QuestionId from sEExam.tTestTemplateQuestion WHERE TestTemplateId=@rTestTemplateId )OR(@rTestTemplateId=0))
	AND Qm.IsObsolete = 0
ORDER BY QM.OrderIndex ASC

 END
	ELSE
BEGIN

SELECT 
		0 AS TestQuestionId,
		QM.Id AS QuestionId,
		QM.TopicId,
		DLM.Id AS DifficultyLevelId,
		QM.QuestionDescription,
		QM.Marks,
		QM.IsObsolete,
		QM.OrderIndex,
		DLM.Title AS DifficultyLevel,
		TM.Title AS Topic,
		ISNULL(Qm.GroupQuestionId,0) AS QuestionGroupId
      
	FROM 
			sEExam.tQuestionMaster QM
		INNER JOIN sEExam.tDataTopicMaster TM
			ON QM.TopicId= TM.Id
		INNER JOIN sEExam.tDifficultyLevelMaster DLM
			ON DLM.Id=QM.DifficultyLevelId
        INNER JOIN sEExam.tTestTemplateQuestion TQ
			ON TQ.QuestionId=QM.Id
             
	WHERE 
		
	TQ.TestTemplateId=@rTestTemplateId


END
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTestTemplateQuestionRemove]
	 
	@rTestTemplateId bigint,
	@rQuestionId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION
	--DECLARE @lNextNumber BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sEExam.tTestQuestion', 0, 1, 1,@outNextNumber = @lNextNumber output

      DELETE FROM sEExam.tTestTemplateQuestion Where TestTemplateId = @rTestTemplateId AND QuestionId = @rQuestionId
  
	  SELECT 1 AS Result          
	
	
	  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -101 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pTestTopicAnalysisGet]
			
			@rTestId int
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
Select 
     
    Topic,
    TopicId,
    COUNT(Skipp) AS SKIP,
    COUNT(NotAttemted) AS NotAttempt,
    COUNT(Wrong) AS Wrong,
    COUNT(True) AS RightA
    
     --Pvt.[0] AS Wrong,
     --Pvt.[1] AS true
     --Pvt.[-1] AS Skip, 
 from
 (
    SELECT  
	TPA.TestId,
	TopicId,
    DTM.Title AS Topic, 
	CASE When tpa.AnswerStatusId = 533 Then 'Skipp' END AS Skipp,
	CASE WHEN tpa.AnswerStatusId = 532 Then 'NotAtt' END AS NotAttemted,
	CASE When tpa.AnswerStatusId = 531 AND ISNULL(Qo.IsKey,0) = 1 THEN 'True' END AS True,
	CASE When tpa.AnswerStatusId = 531 AND ISNULL(Qo.IsKey,0) = 0 THEN 'Wrong' END AS Wrong
	 
	--CASE When tpa.AnswerStatusId = 533 Then 'Skipp'
	--WHEN tpa.AnswerStatusId = 532 Then 'NotAttemted'
	--When tpa.AnswerStatusId = 531 AND ISNULL(Qo.IsKey,0) = 1 THEN 'True'
	--ELSE 'Wrong' END AS IsKey123 ,
 --   TQ.QuestionDescription,
 --   DTM.Title AS Topic,  
 --   tpa.AnswerStatusId 
	
FROM  
	sEExam.tTestParticipantAnswer TPA
	INNER JOIN sEExam.tTestParticipant TP ON TP.Id = TPA.TestParticipantId
	INNER JOIN sEExam.tTestQuestion TQM ON TQM.QuestionId = TPA.QuestionId AND TP.TestId = TQM.TestId
	INNER JOIN sEExam.tQuestionMaster TQ  ON TPA.QuestionId=TQ.Id AND TQM.QuestionId = TQ.Id
	INNER JOIN sEExam.tDataTopicMaster DTM ON DTM.Id = TQ.TopicId
	LEFT JOIN sEExam.tQuestionOption QO   ON QO.Id=TPA.QuestionOptionId AND QO.QuestionId = TPA.QuestionId	
    where TP.TestId = @rTestId  
 ) t
 
 
 Group By Topic,TopicId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/


CREATE OR ALTER PROCEDURE [sEExam].[pTopicMasterAdd]
	 
		   @rId int,
		   @rNumber smallint,
		   @rDataSubjectId int,
		   @rTitle nvarchar(100),		 
		   @rTopicTypeId int,
		   @rOrgGroupId int,
		   @rIsObsolete bit,
		   @rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEExam.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sEExam.tTopicMaster
		(
		   Id,
		   Number,
		   Title,
		   DatasubjectId,
		   TopicTypeId,
		   OrgGroupId,
		   IsObsolete,
		   CreatedUserId,
		   CreatedDateTime
        )
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rTitle,
			@rDataSubjectId,
			@rTopicTypeId,
			@rOrgGroupId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate()
			
		)
		SELECT 1 AS Result
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sEExam.tTopicMaster
	    SET
			Number=@rNumber,
			Title=@rTitle,
			TopicTypeId=@rTopicTypeId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			DataSubjectId = @rDataSubjectId
             
		
	      WHERE (Id = @rId) 
	      SELECT 11 AS Result   
	 END  
		
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEExam].[pTopicMasterGet]
	 
		@rDataSubjectId int,
		@rOrgGroupId int
		
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			  --TTM.Title AS TopicType,
			  --TTM.Id AS TopicTypeId,
			  TM.Id,
			  TM.Number,
			  TM.Title,
			  TM.TopicTypeId,
			  TM.IsObsolete,
			  DSM.Title AS DataSubject,
			  Tm.DataSubjectId
			  --ISNULL(TM.IsObsolete,0)AS IsObsolete,
			  --ISNULL(TM.OrderIndex,0)AS OrderIndex 
  FROM 
		sEExam.tTopicMaster TM INNER JOIN sEExam.tDataSubjectMaster DSM
		ON DSM.Id = TM.DataSubjectId
		
		--	sEExam.tTopicTypeMaster TTM
		--INNER JOIN sSetup.vClassSubject VCS
		--	ON VCS.SubjectId=TTM.SubjectId
		--LEFT JOIN sEExam.tTopicMaster TM
		--	ON TM.ClassSubjectId=VCS.ClassSubjectId
		
WHERE 
	TM.DataSubjectId=@rDataSubjectId
	AND TM.OrgGroupId=@rOrgGroupId
	--VCS.ClassSubjectId=@rClassSubjectId
	--AND (TTM.OrgId=@rOrgId)
	
ORDER BY TM.Number ASC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEExam].[pTopicMasterRemove]
	
		@rClassSubjectId int,
		@rOrgId int
	 
	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	 BEGIN TRANSACTION	
	 
	
	BEGIN
	 
	 Delete From sEExam.tTopicMaster where ClassSubjectId=@rClassSubjectId AND OrgId=@rOrgId
		SELECT 11 AS Result
	END	
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END








GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEExam].[pXMLDataBankImport] 
    @rXMLDoc nvarchar(Max),
	@rOrgGroupId int,
	@rDataBankId int,
	@rDBName nvarchar(100)
AS
SET NOCOUNT ON
BEGIN
--	  SET @rXMLDoc = REPLACE(@rXMLDoc,'&','AND')
	  DECLARE @lXMLDoc INT, @intDoc INT 	
	
	BEGIN TRY
		BEGIN TRANSACTION	
			  EXECUTE @lXMLDoc = sp_xml_preparedocument @intDoc OUTPUT, @rXMLDoc	

			-- DataSubject Master	
				IF @rDBName = 'DataSubject'
				BEGIN			
					INSERT INTO sEExam.tDataSubjectMaster
					(Id,DataBankId,Code,Number,Title,IsObsolete,OrderIndex,CreatedUserId,CreatedDateTime)
					SELECT
						[sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId),@rDataBankId,Code,Number,Title,IsObsolete,OrderIndex,CreatedUserId,sCommon.fGetDate()			
					FROM OPENXML (@intDoc, '/Table/DataSubjectMaster', 1)
					WITH
					(
							Id int '@Id',Code nvarchar(20) '@Code',Number smallint '@Number',
							Title nvarchar(100) '@Title',IsObsolete bit '@IsObsolete',OrderIndex smallint '@OrderIndex',
							CreatedUserId bigint '@CreatedUserId'
					) A
					WHERE [sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tDataSubjectMaster)
				END
			-- Data Topic Master
				ELSE IF @rDBName = 'TopicMaster'
				BEGIN					
					INSERT INTO sEExam.tDataTopicMaster
					(Id,Code,Number,Title,DataSubjectId,ClassGroupId,DataTopicTypeId,IsObsolete,OrgGroupId,DataBankId,CreatedUserId,CreatedDateTime)	
					SELECT
						[sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId),Code,Number,Title,[sCommon].[fGetIntIdForOrg] (DataSubjectId %100000,@rOrgGroupId),
						ClassGroupId,[sCommon].[fGetIntIdForOrg] (DataTopicTypeId %100000,@rOrgGroupId),IsObsolete,
						@rOrgGroupId,@rDataBankId,CreatedUserId,sCommon.fGetDate()				
					FROM OPENXML (@intDoc, '/Table/DataTopicMaster', 1)
					WITH
					(
							Id int '@Id',Code nvarchar(20) '@Code',Number smallint '@Number',Title nvarchar(100) '@Title',
							DataSubjectId int '@DataSubjectId',ClassGroupId int '@ClassGroupId',IsObsolete bit '@IsObsolete',
							OrderIndex smallint '@OrderIndex',CreatedUserId bigint '@CreatedUserId',
							DataTopicTypeId int '@DataTopicTypeId'
					) A
					WHERE [sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tDataTopicMaster)
				END
			-- Data Topic Type Master	
				ELSE IF @rDBName = 'TopicType'
					BEGIN
					INSERT INTO sEExam.tDataTopicTypeMaster
					(Id,Code,Number,Title,DataSubjectId,OrgGroupId,IsObsolete,OrderIndex,DataBankId,CreatedUserId,CreatedDateTime)	
					SELECT
						[sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId),Code,Number,Title,[sCommon].[fGetIntIdForOrg] (DataSubjectId %100000,@rOrgGroupId),OrgGroupId,IsObsolete,OrderIndex,
						@rDataBankId,CreatedUserId,sCommon.fGetDate()			
					FROM OPENXML (@intDoc, '/Table/DataTopicTypeMaster', 1)
					WITH
					(
							Id int '@Id',Code nvarchar(20) '@Code',Number smallint '@Number',Title nvarchar(100) '@Title',
							DataSubjectId int '@DataSubjectId',IsObsolete bit '@IsObsolete',OrgGroupId int '@OrgGroupId',
							OrderIndex smallint '@OrderIndex',CreatedUserId bigint '@CreatedUserId'
					) A
					WHERE [sCommon].[fGetIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tDataTopicTypeMaster)
				END
			-- Question Master	
				ELSE IF @rDBName = 'Question'
				BEGIN
					INSERT INTO sEExam.tQuestionMaster
					(Id,TopicId,DifficultyLevelId,QuestionParagraphId,QuestionDescription,QuestionDescription2,Marks,
					 IsObsolete,OrderIndex,CreatedUserId,CreatedDateTime,DataBankId,EntryModeId)	
					SELECT
						[sCommon].[fGetBigIntIdForOrg] (Id %1000000000,@rOrgGroupId),[sCommon].[fGetIntIdForOrg] (TopicId %100000,@rOrgGroupId),
						DifficultyLevelId,[sCommon].[fGetBigIntIdForOrg] (QuestionParagraphId %1000000000,@rOrgGroupId),QuestionDescription,QuestionDescription2,Marks,
						IsObsolete,OrderIndex,CreatedUserId,sCommon.fGetDate(),@rDataBankId,EntryModeId				
					FROM OPENXML (@intDoc, '/Table/QuestionMaster', 1)
					WITH
					(
							Id bigint '@Id',TopicId int '@TopicId',DifficultyLevelId tinyint '@DifficultyLevelId',
							QuestionParagraphId bigint '@QuestionParagraphId',QuestionDescription nvarchar(max) '@QuestionDescription',
							QuestionDescription2 nvarchar(max) '@QuestionDescription2',Marks Decimal(6,2) '@Marks',IsObsolete bit '@IsObsolete',
							OrderIndex smallint '@OrderIndex',CreatedUserId bigint '@CreatedUserId',
							EntryModeId tinyint '@EntryModeId'
					) A
					WHERE [sCommon].[fGetBigIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tQuestionMaster)	
				END
			-- Question Option	
				ELSE IF @rDBName = 'QuestionOption'
				BEGIN
					INSERT INTO sEExam.tQuestionOption
					(Id,QuestionId,ChoiceDescription,ChoiceDescription2,IsKey,OrderIndex)
					SELECT
						[sCommon].[fGetBigIntIdForOrg] (Id %1000000000,@rOrgGroupId),[sCommon].[fGetBigIntIdForOrg] (QuestionId %1000000000,@rOrgGroupId),
						ChoiceDescription,ChoiceDescription2,IsKey,OrderIndex
					FROM OPENXML (@intDoc, '/Table/QuestionOption', 1)
					WITH
					(
							Id bigint '@Id',QuestionId bigint '@QuestionId',IsKey bit '@IsKey',OrderIndex smallint '@OrderIndex',
							ChoiceDescription nvarchar(max) '@ChoiceDescription',ChoiceDescription2 nvarchar(max) '@ChoiceDescription2'						
					) A
					WHERE [sCommon].[fGetBigIntIdForOrg] (Id %1000000000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tQuestionOption)	
				END
			-- Question Paragraph	
				ELSE IF @rDBName = 'QuestionPara'
				BEGIN
					INSERT INTO sEExam.tQuestionParagraph
					(Id,QuestionParagraphDescription,QuestionParagraphDescription2,UpdatedUserId,UpdatedDateTime,DataBankId)
					SELECT
						[sCommon].[fGetBigIntIdForOrg] (Id %1000000000,@rOrgGroupId),QuestionParagraphDescription,QuestionParagraphDescription2,
						UpdatedUserId,sCommon.fGetDate(),@rDataBankId
					FROM OPENXML (@intDoc, '/Table/QuestionParagraph', 1)
					WITH
					(
							Id bigint '@Id',QuestionId bigint '@QuestionId',UpdatedUserId bigint '@UpdatedUserId',
							QuestionParagraphDescription nvarchar(max) '@QuestionParagraphDescription',QuestionParagraphDescription2 nvarchar(max) '@QuestionParagraphDescription2'
													
					) A
					WHERE [sCommon].[fGetBigIntIdForOrg] (Id %100000,@rOrgGroupId) NOT IN (SELECT Id FROM sEExam.tQuestionParagraph)	
				END
			
			  EXEC sp_xml_removedocument @intDoc	
			
		COMMIT TRANSACTION
		SELECT 1
	END TRY
	BEGIN CATCH
		SELECT -1
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEis].[pClusterBatchGroupMappingAdd]

	@rStrXml [nvarchar](max),
	@rClusterBatchGroupId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN 	
 
	BEGIN TRY
	 BEGIN TRANSACTION	

	 DELETE FROM sEis.tClusterBatchGroupMapping WHERE  ClusterBatchGroupId=@rClusterBatchGroupId

		INSERT INTO sEis.tClusterBatchGroupMapping
		(
			ClusterBatchGroupId,
			OrgGroupBatchId
		)
		SELECT
		   @rClusterBatchGroupId,
		   OrgGroupBatchId
		FROM OPENXML (@loDoc, '/Table/ClusterBatchGroupMapping', 1)
		WITH ( 
			 OrgGroupBatchId int
			  ) 
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterBatchGroupMappingGet]
	 
	 @rClusterBatchGroupId int=0,
	 @rClusterId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	 
	SELECT 
			OM.Title AS OrgGroupName,
			OM.Id AS OrgGroupId,
		    Isnull(A.OrgGroupBatchId,0) AS OrgGroupBatchId,
			CASE WHEN A.OrgGroupBatchId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
			
  FROM 
            sSetup.tOrgGroupMaster OM 
			INNER JOIN sEis.tClusterOrgGroup CO ON OM.Id=CO.OrgGroupId
		    LEFT JOIN 
			(
			 SELECT ISNULL(CB.OrgGroupBatchId,0) As OrgGroupBatchId,B.OrgGroupId  FRoM  [sSetup].[tOrgGroupBatchMaster] B 
			 INNER JOIN sEis.tClusterBatchGroupMapping CB ON  CB.OrgGroupBatchId=B.Id AND CB.ClusterBatchGroupId=@rClusterBatchGroupId )  A ON A.OrgGroupId=CO.OrgGroupId
		
	WHERE
			CO.ClusterId=@rClusterId
  
ORDER BY TITLE ASC
  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterBatchGroupMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rClusterId int,
	@rIsHistory bit,
	@rIsActive bit,
	@rIsObsolete bit,
	@rOrderIndex smallint,
	@rFromDate date,
	@rToDate date,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterBatchGroupMaster] WHERE Code=@rCode  AND  ClusterId = @rClusterId )
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM [sEis].[tClusterBatchGroupMaster] WHERE Title=@rTitle  AND  ClusterId = @rClusterId )
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterBatchGroupMaster] WHERE Code=@rCode AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM [sEis].[tClusterBatchGroupMaster] WHERE Title=@rTitle  AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END

	 BEGIN TRANSACTION	
 IF(@rId = 0)
 	
BEGIN

	DECLARE @lNextNumber INT 
	SEt @lNextNumber=(Select Isnull(Max(Id),0)+1 From sEis.tClusterBatchGroupMaster)
	
	INSERT INTO sEis.tClusterBatchGroupMaster
		(
			Id,
			Code,
			Title,
			ClusterId,
			IsHistory,
			IsActive,
			IsObsolete,
			OrderIndex,
			FromDate,
			ToDate,
			CreatedUserId,
			UpdatedUserId,
			CreatedDateTime,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rClusterId,
			@rIsHistory,
			@rIsActive,
			@rIsObsolete,
			@rOrderIndex,
			@rFromDate,
			@rToDate,
			@rCreatedUserId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate()
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sEis.tClusterBatchGroupMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsHistory=@rIsHistory,
			IsActive=@rIsActive,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			FromDate=@rFromDate,
			ToDate=@rToDate,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterBatchGroupMasterGet]
	 
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rClusterId int,
	 @rIsObsolete bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsObsolete=0)
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			BM.Id,
			BM.Code,
			BM.Title,
			BM.ClusterId,
			BM.IsHistory,
			BM.IsActive,
			BM.IsObsolete,
			BM.OrderIndex,
			BM.FromDate,
			BM.ToDate
      
  FROM 
            sEis.tClusterBatchGroupMaster BM
             
  WHERE 
  
      ((BM.Id = @rId) OR (@rId = 0))
	AND  ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND(BM.ClusterId=@rClusterId)

ORDER BY BM.OrderIndex ASC
  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterMainGroupGet]
	 
        @rId int,
        @rCode nvarchar(50),
        @rTitle nvarchar(100),
		@rClusterId  int
        	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END

	SELECT 
			CM.Id ,
			CM.Code,
			CM.Title,
			CM.IsObsolete,
			CM.ClusterId
	FROM 
			[sEis].[tClusterOrgMainGroupMaster]  CM
	WHERE 
			((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND  CM.ClusterId = @rClusterId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterMasterAdd]
	 
        @rId int,
        @rCode nvarchar(50),
        @rTitle nvarchar(100),
        @rIsObsolete bit,
        @rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterMaster] WHERE Code=@rCode )
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM [sEis].[tClusterMaster] WHERE Title=@rTitle )
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterMaster] WHERE Code=@rCode AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM [sEis].[tClusterMaster] WHERE Title=@rTitle  AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN
		
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEis.tClusterMaster', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT
	SEt @lNextNumber=(SElect Isnull(Max(Id),0)+1 From sEis.tClusterMaster)
	INSERT INTO sEis.tClusterMaster
		(
			
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	
	    UPDATE  sEis.tClusterMaster
	    SET
			
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterMasterDelete]
	 
		@rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	Delete 
	FROM 
			[sEis].[tClusterMaster]  
	WHERE 
	Id = @rId 

	Select 1 as result
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterMasterGet]
	 
		@rId int,
		@rCode nvarchar(50),
		@rTitle nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			CM.Id AS Id,
			CM.Code,
			CM.Title,
			CM.IsObsolete
	FROM 
			[sEis].[tClusterMaster]  CM
	WHERE 
			((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEis].[pClusterOrgGroupAdd]
	 
	@rClusterId int=0,
	@rOrgGroupId smallint=0,
	@rIsObsolete bit
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	IF(@rIsObsolete = 0)
	BEGIN
		DELETE FROM [sEis].[tClusterOrgGroup] WHERE ClusterId=@rClusterId AND OrgGroupId=@rOrgGroupId
	END
	ELSE IF NOT EXISTS(SELECT 1 FROM [sEis].[tClusterOrgGroup] WHERE ClusterId=@rClusterId AND OrgGroupId=@rOrgGroupId)
	BEGIN
		INSERT INTO [sEis].[tClusterOrgGroup]
		(
			ClusterId,
			OrgGroupId
		)
		VALUES
		(
			@rClusterId,
			@rOrgGroupId
		)
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEis].[pClusterOrgGroupGet]
	 
	@rClusterId int=0
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				OM.Id AS OrgGroupId,
				OM.Title AS OrgGroupName,

				CASE WHEN AO.ClusterId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			[sSetup].[tOrgGroupMaster] OM
		LEFT JOIN [sEis].[tClusterOrgGroup] AO ON AO.OrgGroupId=OM.Id
		 AND AO.ClusterId=@rClusterId
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterOrgMainGroupMasterAdd]
	 
        @rId int,
        @rCode nvarchar(50),
        @rTitle nvarchar(100),
        @rIsObsolete bit,
        @rCreatedUserId bigint,
		@rClusterId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgMainGroupMaster] WHERE Code=@rCode  AND  ClusterId = @rClusterId )
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgMainGroupMaster] WHERE Title=@rTitle  AND  ClusterId = @rClusterId )
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgMainGroupMaster] WHERE Code=@rCode AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM [sEis].[tClusterOrgMainGroupMaster] WHERE Title=@rTitle  AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN
		
	SEt @lNextNumber=(SElect Isnull(Max(Id),0)+1 From sEis.tClusterOrgMainGroupMaster)
	INSERT INTO sEis.tClusterOrgMainGroupMaster
		(
			
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ClusterId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClusterId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	
	    UPDATE  sEis.tClusterOrgMainGroupMaster
	    SET
			
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()

		
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEis].[pClusterOrgSubGroupMappingAdd]

	@rStrXml [nvarchar](max),
	@rClusterId Int 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN 	
 
	BEGIN TRY
	 BEGIN TRANSACTION	

	 DELETE  CS FROM [sEis].[tClusterOrgSubGroupMapping] CS
	 INNER JOIN  [sEis].[tClusterOrgSubGroupMaster]  CM ON CS.ClusterOrgSubGroupId=CM.Id 
	 WHERE  ClusterId=@rClusterId

			INSERT INTO [sEis].[tClusterOrgSubGroupMapping]
			(
			OrgId, 
			ClusterOrgSubGroupId
			
			)
			SELECT
			OrgId, 
			ClusterOrgSubGroupId
			FROM OPENXML (@loDoc, '/Table/SubGroupMapping', 1)
			WITH ( 
			OrgId int,
			ClusterOrgSubGroupId int
			) 
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterOrgSubGroupMappingGet]
	 
		 @rClusterId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	 
	SELECT 
			  OGM.Title AS OrgGroupName,
			 OM.Code AS OrgCode,
			 OM.DisplayTitle As OrgName,
			 ISNULL(A.ClusterOrgSubGroupId,0) AS ClusterOrgSubGroupId,
		     OM.Id AS OrgId,
			 cASE WHEN A.ClusterOrgSubGroupId is null THEN 'False' ElSE 'TRUE' END AS IsObsolete
			
  FROM 
           sEis.tClusterOrgGroup CD
			INNER JOIN   sSetup.tOrgGroupMaster OGM  ON CD.OrgGroupId=OGM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OGM.Id
		LEFT JOIN (
			 
			 SELECT CG.*,CB.* FROM [sEis].[tClusterOrgSubGroupMapping] CB INNER JOIN sSetup.tOrganizationMaster OM
			 ON CB.OrgId = OM.Id INNER JOIN [sEis].[tClusterOrgSubGroupMaster] SM ON sM.Id=CB.ClusterOrgSubGroupId
			  Inner JOIN   sEis.tClusterOrgGroup CG ON CG.OrgGroupId=OM.OrgGroupId 
			  Where CG.ClusterId=@rClusterId AND SM.ClusterId = @rClusterId 
			) A On A.OrgGroupId=CD.OrgGroupId AND CD.ClusterId=@rClusterId AND A.OrgId = OM.Id

WHERE 
		 CD.ClusterId=@rClusterId

ORDER BY OGM.TITLE ASC
  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterOrgSubGroupMasterAdd]
	 
        @rId int,
        @rCode nvarchar(50),
        @rTitle nvarchar(100),
        @rIsObsolete bit,
        @rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rCreatedDateTime datetime,
		@rUpdatedDateTime datetime,
		@rClusterId int,
		@rEisOrgMainGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgSubGroupMaster] WHERE Code=@rCode  AND  ClusterId = @rClusterId )
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgSubGroupMaster] WHERE Title=@rTitle  AND  ClusterId = @rClusterId)
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM [sEis].[tClusterOrgSubGroupMaster] WHERE Code=@rCode AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM [sEis].[tClusterOrgSubGroupMaster] WHERE Title=@rTitle  AND Id<>@rId  AND  ClusterId = @rClusterId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN
		SEt @lNextNumber=(SElect Isnull(Max(Id),0)+1 From sEis.tClusterOrgSubGroupMaster)
	INSERT INTO sEis.tClusterOrgSubGroupMaster
		(
			
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ClusterId,
			EisOrgMainGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClusterId,
			@rEisOrgMainGroupId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	
	    UPDATE  sEis.tClusterOrgSubGroupMaster
	    SET
			
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			EisOrgMainGroupId=@rEisOrgMainGroupId
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEis].[pClusterSubGroupGet]
	 
        @rId int,
        @rCode nvarchar(50),
        @rTitle nvarchar(100),
    	@rEisOrgMainGroupId int,
		@rClusterId  int
		
        	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
	END

	SELECT 
			CM.Id ,
			CM.Code,
			CM.Title,
			CM.IsObsolete,
			CM.ClusterId,
			CM.EisOrgMainGroupId,
			CN.Title AS EisMainGroupName
		
	FROM 
			[sEis].[tClusterOrgSubGroupMaster]  CM
			INNER JOIN 	[sEis].[tClusterOrgMainGroupMaster] CN ON CN.Id=CM.EisOrgMainGroupId
	WHERE 
			((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((CM.EisOrgMainGroupId = @rEisOrgMainGroupId) OR (@rEisOrgMainGroupId = 0))
		AND  (CM.ClusterId = @rClusterId)
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEis].[pRptCastCategorywiseStudentGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rClassId int,
	@rDivisionId int=0,
	@rDepartmentId int=0,
	@rOrgMainGroupId int=0,
	@rOrgSubGroupId int=0,
	@rOrgId smallint=0,
	@rStrOrgMainGroupId nvarchar(max)='',
	@rStrOrgSubGroupId nvarchar(max)='',
	@rStrOrgId nvarchar(max)='',
	@rStrDepartmentId nvarchar(max)='',
	@rStrClassId nvarchar(max)='',
	@rClusterId int=0,
	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rReportId int =0,
	@rIsDisplayOrgGroup bit=0,
	@rIsDisplayGender bit=0,
	@rBatchGroupId int=0 ,
	@rStatusId int=0,
	@rStudentStatusId int=0,
	@rClusterOrgGroupId int=0,
	@rClusterOrgMainGroupId int=0,
	@rClusterOrgSubGroupId int=0,
	@rClusterBatchGroupId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsTestDivision AS IsTestDivision ,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			@rIsDisplayGender AS IsDisplayGender,
			DV.Id AS DivisionId,
			CM.Id AS ClassId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Department,
			CM.DisplayTitle+' '+DV.DisplayTitle AS ClassDivision,
			
			ISNULL(GM.Title,'') As Gender,
			A.Id AS AcademicId,
			DV.DisplayTitle AS Division,
		
			COM.Id AS ClusterMainGroupId,
			COM.Title AS ClusterMainGroupTitle,
			COSG.Id AS ClusterSubGroupId,
			COSG.Title AS ClusterSubGroupTitle,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			CASE WHEN  @rReportId=30358	 -- Caste Category wise Summary
			THEN ISNULL(CCM.Title,'') 
		    WHEN  @rReportId=30360 -- Religionwise Summary
			THEN ISNULL(RM.Title,'')
			 WHEN  @rReportId=30359 -- Gender Summary
			THEN ISNULL(GM.Title,'')
			END AS Head,
			DV.OrderIndex AS DivisionOrder,
			OG.Id AS OrgGroupId,
			OG.Title AS OrgGroupDisplayTitle

			
			FROM 
				sStudent.tAcademic A	
				INNER JOIN	sSetup.tClassMaster CM	ON CM.Id=A.ClassId	
				INNER JOIN sSetup.tDivisionMaster DV ON DV.Id=A.DivisionId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
				LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
				INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
				LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
				LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId		
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
				INNER JOIN sEis.tClusterOrgSubGroupMapping CO ON CO.OrgId=DM.OrgId
				INNER JOIN sEis.tClusterOrgSubGroupMaster COSG ON COSG.Id = CO.ClusterOrgSubGroupId
				INNER JOIN sEis.tClusterOrgMainGroupMaster COM ON COM.Id=COSG.EisOrgMainGroupId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CO.OrgId
				INNER JOIN sEis.tClusterOrgGroup CG ON CG.OrgGroupId= OM.OrgGroupId
				INNER JOIN sEis.tClusterMaster CMM ON CMM.Id=COM.ClusterId
				INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.ClusterId=CMM.Id
				INNER JOIn sEis.tClusterBatchGroupMapping CBM ON CBM.ClusterBatchGroupId=CBGM.Id
				INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
				INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
				INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id = CBM.OrgGroupBatchId
				INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId 
				AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
				AND BM.OrgGroupBatchId=OBM.Id
				INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId 	
				AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
	WHERE 
			CG.ClusterId = @rClusterId AND	COM.ClusterId = @rClusterId AND	COSG.ClusterId = @rClusterId AND CMM.ID = @rClusterId AND CBGM.ClusterId = @rClusterId
			AND CBGM.Id=@rClusterBatchGroupId
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((BGM.Id=@rBatchGroupId) OR @rBatchGroupId=0)
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))	
			AND ((SM.StatusId=@rStudentStatusId) OR (@rStudentStatusId=0))
			 AND((COM.Id=@rClusterOrgMainGroupId) OR @rClusterOrgMainGroupId=0)
			AND ((CG.OrgGroupId=@rClusterOrgGroupId) OR @rClusterOrgGroupId=0)
			AND ((COSG.Id=@rClusterOrgSubGroupId) OR @rClusterOrgSubGroupId=0)
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
		 	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEis].[pRptInquiryAdmissionGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rClassId int=0,
	@rDivisionId int=0,
	@rDepartmentId int=0,
	@rOrgMainGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgSubGroupId int=0,
	@rOrgId smallint=0,
	@rStrOrgMainGroupId nvarchar(max)='',
	@rStrOrgSubGroupId nvarchar(max)='',
	@rStrOrgId nvarchar(max)='',
	@rStrDepartmentId nvarchar(max)='',
	@rStrClassId nvarchar(max)='',
	@rClusterId int ,
	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rReportId int =0,
	@rIsDisplayOrgGroup bit=0,
	@rIsDisplayGender bit=0,
	@rBatchGroupId int =0,
	@rStatusId int=0,
	@rStudentStatusId int=0,
	@rClusterOrgGroupId int=0,
	@rClusterOrgMainGroupId int=0,
	@rClusterOrgSubGroupId int=0,
	@rToDate datetime='',
	@rFromDate datetime='',
	@rClusterBatchGroupId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			COM.Id AS ClusterMainGroupId,
			COM.Title AS ClusterMainGroupTitle,
			COSG.Id AS ClusterSubGroupId,
			COSG.Title AS ClusterSubGroupTitle,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			(select COUNT(AI.Id) FROM sAdmission.tAdmissionInquiry AI 
			 INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			 INNER JOIN sEis.tClusterBatchGroupMapping CBM ON CBM.OrgGroupBatchId=BM.OrgGroupBatchId
			 INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.Id=CBM.ClusterBatchGroupId
			 INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId   AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			  WHERE CBGM.ClusterId=@rClusterId 
			  AND  (CBM.ClusterBatchGroupId = @rClusterBatchGroupId)
			  AND AI.InquiryDate >= @rFromDate 
			  AND AI.InquiryDate <= @rToDate AND AI.ForClassId = CM.Id
			 AND  BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 ) NoOfInquiry, 

		    (select COUNT(A.Id) FROM sStudent.tStudentAdmission SA 
			INNER JOIN sStudent.tAcademic A ON SA.StudentId = A.StudentId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			AND SA.AdmissionStandardId = A.ClassId
			INNER JOIN sEis.tClusterBatchGroupMapping CBM ON CBM.OrgGroupBatchId=BM.OrgGroupBatchId
			INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.Id=CBM.ClusterBatchGroupId
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId   AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			WHERE  CBGM.ClusterId=@rClusterId  
		    AND  CBM.ClusterBatchGroupId = @rClusterBatchGroupId
			AND SA.AdmissionDate >= @rFromDate 
			AND SA.AdmissionDate <= @rToDate 
			AND BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND A.ClassId =CM.Id  ) AS NoOfAdmission
 
	FROM 
			sSetup.tClassMaster CM						
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sEis.tClusterOrgSubGroupMapping CO ON CO.OrgId=DM.OrgId
			INNER JOIN sEis.tClusterOrgSubGroupMaster COSG ON COSG.Id = CO.ClusterOrgSubGroupId
			INNER JOIN sEis.tClusterOrgMainGroupMaster COM ON COM.Id=COSG.EisOrgMainGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CO.OrgId
			INNER JOIN sEis.tClusterOrgGroup CG ON CG.OrgGroupId= OM.OrgGroupId
			INNER JOIN sEis.tClusterMaster CMM ON CMM.Id=COM.ClusterId
			INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.ClusterId=CMM.Id
			INNER JOIn sEis.tClusterBatchGroupMapping CBM ON CBM.ClusterBatchGroupId=CBGM.Id
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id = CBM.OrgGroupBatchId AND OG.Id=OBM.OrgGroupId
			
	WHERE 
	        ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
		    AND	CG.ClusterId = @rClusterId AND	COM.ClusterId = @rClusterId AND	COSG.ClusterId = @rClusterId AND CMM.ID = @rClusterId AND CBGM.ClusterId = @rClusterId
			AND CBGM.Id=@rClusterBatchGroupId
			AND((COM.Id=@rClusterOrgMainGroupId) OR @rClusterOrgMainGroupId=0)
			AND ((CG.OrgGroupId=@rClusterOrgGroupId) OR @rClusterOrgGroupId=0)
			AND ((COSG.Id=@rClusterOrgSubGroupId) OR @rClusterOrgSubGroupId=0)
			ORDER BY CM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[GetStudentProfile] 
	@racademicId bigint,
	@rbatchId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT A.OrgId, BatchId, StudentId, A.Id AS AcademicId, SM.Code, A.RollNo, (FirstName +' '+MiddleName+' '+LastName) AS StudentName,
                            SM.FirstName, SM.MiddleName, SM.LastName, A.ClassId, A.DivisionId, (CM.DisplayTitle +'-'+ DM.DisplayTitle) AS ClassDivision,
                            DPM.Id AS DepartmentId, DPM.DisplayTitle AS DepartmentName, SM.SUID, B.Title as BatchName
                             FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
                            INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
                            INNER JOIN sSetup.tDepartmentMaster DPM ON DPM.Id = CM.DepartmentId
                            INNER JOIN sSetup.tBatchMaster B ON b.Id = A.BatchId
							WHERE A.Id=@racademicId AND BatchId = @rbatchId



END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pAttachmentLogAdd]
		@rMessageId nvarchar(max),
		@rAttachment nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			INSERT INTO sAlert.tAlertAttachmentLog VALUES (@rMessageId, @rAttachment)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pBatchLockGet]
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	Select ISNULL(IsLock,0) as IsLock FROM sSetup.tBatchMaster WHERE Id = @rBatchId

	END TRY

	BEGIN CATCH
	SELECT -1 as Result
	END CATCH

END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEMeeting].[pCancelMeeting]
	@rId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			
			IF EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeeting WHERE IsCompleted = 550 AND Id = @rId)
			BEGIN
				SELECT -1 as Result
			END
			IF EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeeting WHERE StartDate >= GetUtcDate() AND Id = @rId)
			BEGIN
				SELECT -102 as Result
			END
			ELSE
			BEGIN
				Update sEMeeting.tOnlineMeeting SET IsCompleted = 551 WHERE StartDate < GetUtcDate() AND IsCompleted = 549 AND Id = @rId
				SELECT 1 as Result
			END
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -101 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pCreateSMSStatus]
		@rResultMessage nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			Insert Into sAlert.tSMSStatus VALUES (CONVERT(DateTime,GetUtcDate(),103), @rResultMessage)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pEmployeeMasterIdGet]
		@rMobileNotificationCode nvarchar(max),
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT Id FROM sHrm.tEmployeeMaster WHERE Code = @rMobileNotificationCode AND OrgId= @rOrgId AND  ISNULL(IsOtherUser,0) = 0 
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pEventSMSTemplateIdGet]
		@rOrgId int,
		@rEventId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			Select SMSTemplateID FROM sAlert.tEventTemplate WHERE EventId = @rOrgId AND OrgId=@rOrgId AND AlertModeId = 2
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEMeeting].[pEventTemplateGet]
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT EventId,Template FROM sAlert.tEventTemplate WHERE IsAutoSend = 1 AND OrgId =@rOrgId AND EventId = 160
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEMeeting].[pEventTemplateGetForAttendance]
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT EventId,Template FROM sAlert.tEventTemplate WHERE IsAutoSend = 1 AND OrgId =@rOrgId AND EventId = 161
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pMeetingAccountGet]
		@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT
		OMA.Id,
		OMA.AccountName AS Title
		FROM sAcademic.tOnlineMeetingAccount OMA
		WHERE ISNULL(OMA.IsObsolete,0) = 0 AND OMA.OrgGroupId =  @rOrgGroupId
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pMeetingAccountNameGet]
		@rEmployeeId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
	SELECT OMA.Id,
	OMA.AccountName as Title
	FROM sAcademic.tOnlineMeetingAccount OMA 
	WHERE EmployeeId = @rEmployeeId 
	AND ISNULL(OMA.IsObsolete,0) = 0
	END TRY
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEMeeting].[pMeetingTypeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			Select OM.AutoId as Id, 
			OM.Title
			from sEMeeting.tMeetingTypeMaster OM 
			where IsObsolete = 0 
			order by OrderIndex 
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEMeeting].[pMeetingTypeMasterAdd]
	@rAutoId smallint,
	@rTitle nvarchar(100),
	@rOrgGroupId smallint,
	@rIsObsolete bit = 0,
	@rCreatedUserId bigint,
	@rCode nvarchar(10),
	@rOrderIndex int = 0,
	@rDescription nvarchar(max) 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	IF (@rAutoId = 0)
	BEGIN
	 
	IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where Code = @rCode)
		BEGIN
			SELECT -101 as Result
			Return
		END
	IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where OrderIndex = @rOrderIndex)
		BEGIN
			SELECT -102 as Result
			Return
		END
	END
	ELSE
	    BEGIN
		IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where Code = @rCode AND AutoId<>@rAutoId)
		BEGIN
			SELECT -101 as Result
			Return
		END
		IF EXISTS (select 1 from sEMeeting.tMeetingTypeMaster where OrderIndex = @rOrderIndex AND AutoId<>@rAutoId)
		BEGIN
			SELECT -102 as Result
			Return
		END
		END

	BEGIN TRANSACTION	
	IF (@rAutoId = 0)
	BEGIN
			INSERT INTO sEMeeting.tMeetingTypeMaster
			(
				Title,
				OrgGroupId,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				Code,
				OrderIndex,
				Description
			)
			VALUES
			(
				@rTitle,
				@rOrgGroupId,
				@rIsObsolete,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCode,
				@rOrderIndex,
				@rDescription
			)
				SELECT 1 AS Result
	END
	ELSE
	BEGIN
			UPDATE sEMeeting.tMeetingTypeMaster
			SET 
					Title = @rTitle,
					IsObsolete = @rIsObsolete,
					UpdatedUserId = @rCreatedUserId,
					UpdatedDateTime = GETUTCDATE(),
					OrderIndex = @rOrderIndex,
					Code = @rCode,
					Description = @rDescription
				WHERE AutoId = @rAutoId;
				SELECT 11 AS Result;
	END

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pMeetingTypeMasterDelete]
	 @rId smallint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	IF EXISTS (SELECT 1 from sEMeeting.tOnlineMeeting where MeetingTypeId = @rId)
	BEGIN
		SELECT -101 As Result
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT 1 from sEMeeting.tMeetingTypeMaster where AutoId = @rId)
		BEGIN 
			Delete sEMeeting.tMeetingTypeMaster WHERE AutoId = @rId
			SELECT 1 As Result
		END
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sEMeeting].[pMeetingTypeMasterDetailGet]
	 @rId smallint = 0,
	 @rTitle nvarchar(20) = ''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	If(@rId = 0) 
	BEGIN 
		 SELECT AutoId, Title, Code, OrderIndex, Description, IsObsolete
			from [sEMeeting].[tMeetingTypeMaster] MTM 
			 where (MTM.Title LIKE '%' + @rTitle + '%' OR (ISNULL(@rTitle,'') = '') OR @rTitle = '*')
			 Order By MTM.OrderIndex
	END
	ELSE
	BEGIN
		SELECT AutoId, Title, Code, OrderIndex, Description, IsObsolete
			from [sEMeeting].[tMeetingTypeMaster] where AutoId = @rId
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec sEMeeting.pMenuGet 9911000000270,0,0,1
-- exec sEMeeting.pMenuGet 9911000000545,0,0,1
CREATE OR ALTER PROCEDURE [sEMeeting].[pMenuGet]
 @rUserId [bigint],    
 @rMenuId int = 0,    
 @rResourceTypeId int= 0,    
 @rIsCoreMenu bit = 0     
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
 IF(@rIsCoreMenu=0)    
 BEGIN    
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
    PageURL  AS PagePath,    
    IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermissionUser P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
       WHERE    
        T.IsObsolete = 0 AND P.UserId = @rUserId    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 ELSE     
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
     PageURL  AS PagePath,    
     IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermission P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
        INNER JOIN    
        (    
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0    
        ) B ON B.RoleId = P.RoleId    
       WHERE    
        T.IsObsolete = 0    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0 AND TBL2.PermissionValue > 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 END    
 ELSE    
 BEGIN     
 SELECT    
   MenuID,    
   ModuleId,    
   ParentMenuID,    
   MenuTitle,      
   ScreenTitle,       
   PageURL,    
   ScreenId,    
   Permission,    
   OrderNumber,      
   TaskId,      
   PageURL  AS PagePath,    
   MenuIsObsolete,    
   Icon      
  FROM    
  (    

SELECT    
   ISNULL(Menu.Id,0) AS MenuID,     
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
   ISNULL(Menu.Title,'') AS MenuTitle,       
   ISNULL(Screen.Title, '') AS ScreenTitle,        
   ISNULL(Screen.Page, '') AS PageURL,    
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen.Id, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen.IconPath,'') AS Icon    
  FROM     
  sSecurity.tMenu Menu     
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
  LEFT OUTER JOIN     
  (    
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId      
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id        
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId     
  GROUP BY P.TaskId    
  ) TBL2 ON Screen.TaskId = TBL2.TaskId     
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
  WHERE (Menu.IsObsolete = 0)    
  AND ISNULL(Screen.IsObsolete, 0) = 0    
  AND (Menu.Id  in (19184027,2411))   
  --Or ParentMenuID  in (24,2711))     
  --AND (
  ----Menu.Id IN (19184027)  
  ----OR ParentMenuID IN (55)
  --)  
  

  UNION
  

  SELECT     
  
   ISNULL(Menu.Id, 0) AS MenuID,     
   ISNULL(Menu.Id, 0) AS ParentMenuID,     
   ISNULL(Screen1.Title,'') AS MenuTitle,       
   ISNULL(Screen1.Title, '') AS ScreenTitle,        
   ISNULL(Screen1.Page, '')  AS PageURL,    
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen1.Id, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen1.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen1.IconPath,'') AS Icon    
  FROM     
   sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId     
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId    
   LEFT OUTER JOIN (     
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId        
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id       
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId    
            
  GROUP BY P.TaskId    
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId    
  WHERE (Menu.IsObsolete = 0) AND ISNULL(Screen1.IsObsolete, 0) = 0    
  --AND (Menu.ParentMenuID  in (24,2711)   
  --or Menu.Id  in (24,2711))   
    AND TBL2.PermissionValue > 0
  AND Screen1.Id IN (31295 , 31293,31304)

  ) MenuTable      
  WHERE     
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)  
  --AND   
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
  AND MenuIsObsolete = 0    
  AND MenuTable.MenuId IN (19184027,2411)   
  AND ModuleId IN (95,235)
  ORDER BY ParentMenuID  
 END    
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pMobileNotitficationTitleGet]
		@rEventId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			SELECT Title FROM sAlert.tEventMaster WHERE Id= @rEventId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pNotitficationLogIdGet]
		@rFromId bigint,
		@rToId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			SELECT Id AS NotificationId FROM sAlert.tNotificationLog WHERE (Id>=@rFromId) AND (Id<=@rToId)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
	

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAbsentStudentListGet]
	@rOnlineMeetingId bigint,
	@rTemplate nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		 SELECT 
			A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[MeetingType]',OMT.Title),
			'[Name]',A.Name),
			'[StartDate]',CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103)),
			'[EndDate]',CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103)),
			'[Teacher]',EE.EmployeeName),
			'[Title]',OM.Title),
			'[StartTime]',CONVERT(varchar(11),ISNULL(OM.StartTime,'') ,8)),
			'[EndTime]',CONVERT(varchar(11),ISNULL(OM.EndTime,'') ,8))
			AS MsgText,
			'' AS Subject,
			 2003 AS ReceiverSourceTypeId,
			 A.OrgId AS OrgId,
			 (SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			 A.AcademicId AS ReceiverSourceId,
			 A.AcademicId AS SourceId,
			 2003 AS SourceTypeId,
			 OMT.Title AS MeetingType,
			 CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 EE.EmployeeName AS Teacher,
			 OM.Title AS Title,
			 CONVERT(varchar(11),ISNULL(OM.StartTime,'') ,8) AS StartTime,
			 CONVERT(varchar(11),ISNULL(OM.EndTime,'') ,8) AS EndTime,
			 A.WhatsAppContactNo
	FROM 
		sEMeeting.tOnlineMeeting OM
		INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
		INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = OM.HostEmployeeId
		INNER JOIN (
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2003

			UNION ALL	
																			 			  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
				 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND  OMS.ScopeSourceTypeId = 2017

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OMS.ScopeSourceId  
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2021
			
		) as A ON A.OnlineMeetingId = OM.Id 
		LEFT JOIN sEMeeting.tOnlineMeetingAttendance OMA ON OMA.OnlineMeetingId = OM.Id AND OMA.ParticipantSourceId = A.AcademicId
	WHERE
		OM.Id = @rOnlineMeetingId AND ISNULL(OMA.IsPresent,0) <> 1
END





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAccountDetailsGet]
	@rMeetingAccountId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT OAuthAccountId,OAuthClientId,OAuthClientSecret,AccountEmailId,JWTToken FROM sAcademic.tOnlineMeetingAccount WHERE Id = @rMeetingAccountId AND ISNULL(IsObsolete,0) = 0
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAccounts]
	@rOnlineMeetingAccountId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT STUFF((SELECT ','+ CONVERT(varchar,OM.Id) FROM sEMeeting.tOnlineMeeting OM WHERE MeetingAccountId =  @rOnlineMeetingAccountId AND IsCompleted = 0								FOR XML PATH('')), 1, 1, '') AS Ids
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAdd]
	 
        @rId bigint = 0,
		@rOrgGroupId smallint,
		@rMeetingTypeId smallint,
		@rHostEmployeeId bigint,
		@rStartDate datetime,
		@rStartTime datetime,
		@rEndDate datetime,
		@rEndTime datetime,
		@rTitle nvarchar(100) = '',
		@rDescription nvarchar(max) = '',
		@rIsDisplayMeetingId bit = 0,
		@rMeetingId nvarchar(50) = '',
		@rMeetingPass nvarchar(50) = '',
		@rIsReference bit = 0,
		@rIsResource bit=0,
		@rIsCompleted bit = 0,
		@rIsMeetingStarted bit = 0,
		@rMeetingAccountId int = 0,
		@rIsMeetingCreated bit=0,
		@rIsObsolete bit = 0,
		@rCreatedUserId bigint,
		@rIsOnParticipantVideo bit = 0,
		@rIsOnParticipantAudio bit = 0,
		@rIsOnHostVideo bit = 0,
		@rIsOnHostAudio bit = 0,
		@rIsOnParticipantScreenShare bit = 0,
		@rIsOnHostscreenShare bit = 0,
		@rAssigneeId tinyint,
		@rIsTrackAttendance bit = 0,
		@rTempOnlineMeetingId nvarchar(100) = '',
		@rOnlineMeetingScopeList sEMeeting.OnlineMeetingScopeDetailType READONLY,
		@rOnlineMeetingReferenceList sEMeeting.OnlineMeetingReferenceDetailType READONLY
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	 DECLARE @lAccountEmailId NVARCHAR(200),@lAccountPassword NVARCHAR(200),@lAPIKey NVARCHAR(100),@lAPISecret NVARCHAR(100),@lWebAPIKey NVARCHAR(100),
	         @lWebAPISecret NVARCHAR(100),@lMeetingProviderId NVARCHAR(100),@lJWTToken NVARCHAR(MAX),@lOAuthAccountId NVARCHAR(MAX), @lOAuthClientId NVARCHAR(MAX),@lOAuthClientSecret NVARCHAR(MAX)

	SELECT @lAccountEmailId = AccountEmailId,@lAccountPassword = AccountPassword,@lAPIKey = APIKey,@lAPISecret = APISecret,@lWebAPIKey = WebAPIKey,@lWebAPISecret = WebAPISecret,@lMeetingProviderId = MeetingProviderId,
	@lJWTToken = JWTToken, @lOAuthAccountId = OAuthAccountId , @lOAuthClientId = OAuthClientId , @lOAuthClientSecret = OAuthClientSecret
	    FROM sAcademic.tOnlineMeetingAccount
		WHERE Id = @rMeetingAccountId

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sEMeeting.tOnlineMeeting', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sEMeeting.tOnlineMeeting
		(
			Id,
			OrgGroupId,
			MeetingTypeId,
			HostEmployeeId,
			StartDate,
			StartTime,
			EndDate,
			EndTime,
			Title,
			Description,
			IsDisplayMeetingId,
			MeetingId,
			MeetingPassword,
			IsReference,
			IsResource,
			IsCompleted,
			IsMeetingStarted,
			MeetingAccountId,
			IsMeetingCreated,
			IsObsolete,
			AssigneeId,
			IsTrackAttendance,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rMeetingTypeId,
			@rHostEmployeeId,
			@rStartDate,
			@rStartTime,
			@rEndDate, 
			@rEndTime,
			@rTitle,
			@rDescription,
			@rIsDisplayMeetingId,
			@rMeetingId,
			@rMeetingPass,
			@rIsReference,
			@rIsResource,
			CASE WHEN @rIsCompleted = 0 THEN 549 ELSE 0 END,
			@rIsMeetingStarted,
			@rMeetingAccountId,
			@rIsMeetingCreated,
			@rIsObsolete,
			@rAssigneeId,
			@rIsTrackAttendance,
			@rCreatedUserId,
			GetUtcDate()
		)
		    
	INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			AssigneeId,
			CreatedUserId,
			CreatedDateTime
			)
			SELECT 
			@lNextNumber,
			ScopeSourceTypeId,
			ScopeSourceId,
			@rIsObsolete,
			AssigneeId,
			@rCreatedUserId,
			GetUtcDate()
			from @rOnlineMeetingScopeList
	if(@rTempOnlineMeetingId <> NULL OR @rTempOnlineMeetingId <> '')
	BEGIN
	DELETE FROM [sEMeeting].[tTempOnlineMeetingScope] WHERE TempOnlineMeetingId = @rTempOnlineMeetingId
	END
	IF (@rIsReference = 'true')
	BEGIN
	INSERT INTO sEMeeting.tOnlineMeetingReference
	(
	OnlineMeetingId,
	ReferencePath
	)
	SELECT
	@lNextNumber,
	ReferencePath
	from @rOnlineMeetingReferenceList
		
	END

	INSERT INTO sEMeeting.tOnlineMeetingSettings
		(
			OnlineMeetingId,
			IsOnParticipantVideo,
			IsOnParticipantAudio,
			IsOnHostVideo,
			IsOnHostAudio,
			IsOnParticipantScreenShare,
			IsOnHostscreenShare,
			AccountEmailId,
			AccountPassword,
			APIKey,
			APISecret,
			WebAPIKey,
			WebAPISecret,
			MeetingProviderId,
			JWTToken,
			OAuthAccountId,
			OAuthClientId,
			OAuthClientSecret
		)
		VALUES
		(
			@lNextNumber,
			@rIsOnParticipantVideo,
			@rIsOnParticipantAudio,
			@rIsOnHostVideo,
			@rIsOnHostAudio,
			@rIsOnParticipantScreenShare,
			@rIsOnHostscreenShare,
			@lAccountEmailId,
			@lAccountPassword,
			@lAPIKey,
			@lAPISecret,
			@lWebAPIKey,
			@lWebAPISecret,
			@lMeetingProviderId,
			@lJWTToken,
			@lOAuthAccountId,
			@lOAuthClientId,
			@lOAuthClientSecret
		)

	SELECT @lNextNumber as Result
	END	 

ELSE
	 BEGIN
	    UPDATE sEMeeting.tOnlineMeeting
	    SET
		   OrgGroupId = @rOrgGroupId,
		   MeetingTypeId = @rMeetingTypeId,
		   HostEmployeeId = @rHostEmployeeId,
		   StartDate = @rStartDate,
		   StartTime = @rStartTime,
		   EndDate = @rEndDate,
		   EndTime = @rEndTime,
		   Title = @rTitle,
		   Description = @rDescription,
		   IsDisplayMeetingId = @rIsDisplayMeetingId,
		   MeetingId = @rMeetingId,
		   MeetingPassword = @rMeetingPass,
		   IsReference = @rIsReference,
		   IsResource = @rIsResource,
		   IsCompleted = CASE WHEN @rIsCompleted = 1 THEN 550 ELSE 549 END,
		   IsMeetingStarted = @rIsMeetingStarted,
		   MeetingAccountId = @rMeetingAccountId,
		   IsMeetingCreated = @rIsMeetingCreated,
		   IsObsolete = @rIsObsolete,
		   UpdatedUserId = @rCreatedUserId,
		   UpdatedDateTime = GetUtcDate(),
		   IsTrackAttendance = @rIsTrackAttendance

	      WHERE Id = @rId
		  
		delete from sEMeeting.tOnlineMeetingScope where OnlineMeetingId = @rId

		INSERT INTO sEMeeting.tOnlineMeetingScope
			(
			OnlineMeetingId,
			ScopeSourceTypeId,
			ScopeSourceId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			AssigneeId
			)
			SELECT 
			@rId,
			ScopeSourceTypeId,
			ScopeSourceId,
			@rIsObsolete,
			@rCreatedUserId,
			GetUtcDate(),
			AssigneeId
			from @rOnlineMeetingScopeList
		
		delete from sEMeeting.tOnlineMeetingReference where OnlineMeetingId = @rId

		IF (@rIsReference = 'true')
		BEGIN
			INSERT INTO sEMeeting.tOnlineMeetingReference
			(
			OnlineMeetingId,
			ReferencePath
			)
			SELECT
			@rId,
			ReferencePath
			from @rOnlineMeetingReferenceList
		END

	    SELECT 11 AS Result
	
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAssigneeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT Id,
			Title 
			FROM sCommon.tAssigneeMaster
			WHERE IsObsolete=0 ORDER BY Id
		END TRY
		BEGIN CATCH 
		SELECT -1 AS Result
		END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAttendanceAdd]
	 @rOnlineMeetingId bigint ,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rAttendanceType bit
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 
	 IF(@rAttendanceType= 1) 
	   BEGIN
	   IF NOT EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeetingAttendance WHERE OnlineMeetingId = @rOnlineMeetingId AND ParticipantSourceId = @rSourceId AND ParticipantSourceTypeId = @rSourceTypeId)
			BEGIN
			INSERT  INTO sEMeeting.tOnlineMeetingAttendance
			(OnlineMeetingId,ParticipantSourceTypeId, ParticipantSourceId, IsPresent ,FirstInDateTime, IsLoggedIn)
			VALUES 
			(@rOnlineMeetingId, @rSourceTypeId, @rSourceId,1,GetDate(), 1)
			END
		SELECT 1 AS Result	
		END
		
		ELSE IF (@rAttendanceType= 0)
		BEGIN
		IF EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeetingAttendance WHERE OnlineMeetingId = @rOnlineMeetingId AND ParticipantSourceId = @rSourceId AND ParticipantSourceTypeId = @rSourceTypeId)
			BEGIN
			UPDATE sEMeeting.tOnlineMeetingAttendance 
			SET LastOutDateTime = GetDate(),
			IsLoggedIn = 0
			Where ParticipantSourceId= @rSourceId AND OnlineMeetingId= @rOnlineMeetingId And ParticipantSourceTypeId = @rSourceTypeId
			SELECT 11 AS Result
			END
			
		ELSE 
		SELECT -1 AS Result
	
END
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingAttendanceGet]
	@rOnlineMeetingId bigint
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	CREATE TABLE #ScopeSourceTypeId
	(
		Id int IDENTITY,
		ScopeSourceTypeId bigint
	)
	CREATE TABLE #StudentData
	(
	Class nvarchar(200),
	Code nvarchar(200),
	RollNo bigint,
	StudentName nvarchar(200),
	IsPresent nvarchar(100),
	ClassID bigint,
	DivisionId bigint,
	AcademicId bigint,
	IsLoggedIn nvarchar(100),
	FirstInDateTime datetime,
	LastOutDateTime datetime,
	IsPresentAbsent nvarchar(100)
	)

	INSERT INTO #ScopeSourceTypeId
	Select Distinct  ScopeSourceTypeId from [sEMeeting].[tOnlineMeetingScope] Where OnlineMeetingId=@rOnlineMeetingId

DECLARE @lCountScopeSourceTypeId int,@lScopeSourceTypeId int,@lId int

SELECT @lCountScopeSourceTypeId=COUNT(ScopeSourceTypeId) FROM #ScopeSourceTypeId
	SELECT Top 1 @lId=Id FROM #ScopeSourceTypeId

	WHILE @lId <= @lCountScopeSourceTypeId
			BEGIN
			SELECT @lScopeSourceTypeId=ScopeSourceTypeId FROM #ScopeSourceTypeId WHERE Id=@lId
	--AcademicId
	IF(@lScopeSourceTypeId=2003)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND  OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT  OMA.FirstInDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.AcademicId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--ClassId
	ELSE IF(@lScopeSourceTypeId=2016)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.ParticipantSourceTypeId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.ParticipantSourceTypeId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.ClassId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--DeparmentId
	ELSE IF(@lScopeSourceTypeId=2017)
	BEGIN
	INSERT INTO #StudentData
	SELECT 

			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND  OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.DepartmentId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--OrgId
	ELSE IF(@lScopeSourceTypeId=2021)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND  OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.OrgId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--Division
	ELSE IF(@lScopeSourceTypeId=2005)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OMA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'N')AS IsPresent,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OMA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE OMA.ParticipantSourceId = SA.AcademicId AND OMA.OnlineMeetingId=@rOnlineMeetingId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OMA.FirstInDateTime  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),OM.StartDate)AS FirstInDateTime,
			(SELECT  OMA.LastOutDateTime FROM sEMeeting.tOnlineMeetingAttendance OMA WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId ) as LastOutDateTime,
			ISNULL((SELECT  OMA.IsPresent  FROM sEMeeting.tOnlineMeetingAttendance OMA 
			WHERE  OMA.OnlineMeetingId=@rOnlineMeetingId),0)AS IsPresentAbsent
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON SA.DivisionId=OMS.ScopeSourceId
			INNER JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.Id=OMS.OnlineMeetingId 
			WHERE 
			OMS.OnlineMeetingId=@rOnlineMeetingId
			AND SA.StatusId = 1
			GROUP BY 
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OM.StartDate
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END

	SET @lId=@lId+1
	END
	Select * from #StudentData
	DROP TABLE #ScopeSourceTypeId
	DROP TABLE #StudentData
				
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingBatchGet]
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT 
		Id,
		Title 
		FROM sSetup.tBatchMaster 
		WHERE IsObsolete = 0  
		AND IsHistory = 0  
		AND OrgId = @rOrgId 
		ORDER BY OrderIndex DESC
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingClassGet]
	@rDepartmentId int,
	@rOrgId int,
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		SELECT DISTINCT CM.Id,CM.DisplayTitle AS Title FROM sSetup.tDivisionMaster DM
                               INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=  @rOrgId 
                               INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
                               WHERE  CM.DepartmentId= @rDepartmentId  AND U.UserId = @rUserId
	END TRY

	BEGIN CATCH
	 SELECT -1 as Result
	END CATCH

END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION
			Delete from sEMeeting.tOnlineMeetingResource where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingReference where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingAttendance where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingScope where OnlineMeetingId=@rId
			Delete from sEMeeting.tOnlineMeetingSettings Where OnlineMeetingId = @rId
			Delete from sEMeeting.tOnlineMeeting where Id=@rId
			select 1 as Result
		COMMIT TRANSACTION			 
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		select -1 as Result		
	END CATCH	
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingDepartmentGet]
		@rOrgId int,
		@rUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT 
		DM.Id, 
		DM.DisplayTitle AS Title 
		FROM sSetup.tDepartmentMaster DM 
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id 
		AND U.SourceTypeId=2017
        WHERE IsObsolete = 0 
		AND OrgId = @rOrgId  
		AND UserId = @rUserId
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingDivisionGet]
	 
	 @rClassId int,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rOrgId int,
	 @rUserId bigint,
	 @rBatchId int,
	 @rAttendanceEntryBasedOn nvarchar
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
        if (@rAttendanceEntryBasedOn = 'Class Teacher' AND @rUserSourceTypeId = 95)
			BEGIN
				SELECT DISTINCT DM.Id AS Id, DM.DisplayTitle AS Title
					   FROM sSetup.tClassMaster CM 
					   INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
                       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
                       WHERE DM.InchargeemployeeID= @rUserSourceId  
					   AND CM.OrgId= @rOrgId 
					   AND CM.Id = @rClassId
			END	 
		else if (@rAttendanceEntryBasedOn = 'Academic Setup' AND @rUserSourceTypeId = 95)
				BEGIN
					SELECT DISTINCT DivisionId AS Id, DivisionTitle, DivisionOrderIndex AS Title 
                        FROM sAcademic.vTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=TSD.OrgId 
						WHERE  TSD.EmployeeId= @rUserSourceId 
						AND TSD.ClassId = @rClassId
                        ORDER BY DivisionOrderIndex
				END
		else
					BEGIN
						SELECT DM.Id,DM.DisplayTitle AS Title 
							   FROM sSetup.tDivisionMaster DM 
                               INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId= @rOrgId 
                               INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005 
                               WHERE  CM.Id = @rClassId 
							   AND UserId = @rUserId 
							   Order by DM.OrderIndex
					END
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingEmployeeGet]
	 
	 @rDepartmentId int,
	 @rOrgId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
	SELECT EmployeeId AS Id,
	EmployeeName AS Title ,
	Code
	FROM sHrm.vEmployeeCommunication 
	WHERE ISNULL(IsOtherUser,0) = 0 
	AND StatusId=7 
	AND DepartmentId=@rDepartmentId 
	AND OrgId=@rOrgId ORDER BY Code
	END TRY

	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rEmployeeId bigint = 0,
	 @rMeetingTypeId smallint = 0,
	 @rIsCompleted int = 0,
	 @rAssigneeId tinyint,
	 @rUserId bigint = 0,
	 @rOnlineMeetingAccountId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	if(@rId = 0)
	BEGIN 
	SELECT 
			OM.Id,
			EM.FirstName +' '+ EM.LastName as Teacher,
			OMT.Title as MeetingType,
			CONVERT(NVARCHAR,OM.StartDate,3)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,3)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			OM.IsCompleted as StatusId,
		    ISNULL(OM.Title,'') as Title,
			OM.StartDate AS TeacherStartDate,
			OM.EndDate AS TeacherEndDate,
			OM.AssigneeId,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tClassMaster CM ON OMS.ScopeSourceId = CM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tDivisionMaster DM ON OMS.ScopeSourceId = DM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2005
			  UNION ALL
			  SELECT Title FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tOrganizationMaster DM ON OMS.ScopeSourceId = DM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2021
			  UNION ALL
			  SELECT Code FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sSetup.tDepartmentMaster DM ON OMS.ScopeSourceId = DM.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2017
			  UNION ALL
			  SELECT distinct ClassName + '-' + DivisionName FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sStudent.vStudentAcademic SA ON OMS.ScopeSourceId = SA.AcademicId Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 2003
			  UNION ALL
			  SELECT distinct OMG.DisplayTitle + '-' + vEC.DepartmentName FROM sEMeeting.tOnlineMeetingScope OMS INNER JOIN sHrm.vEmployeeCommunication vEC ON OMS.ScopeSourceId = vEC.Id LEFT JOIN sSetup.tOrganizationMaster OMG
				ON vEC.OrgId = OMG.Id Where  OnlineMeetingId = OM.Id AND OMS.ScopeSourceTypeId = 95
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as Assignee 
	  FROM 
			sEMeeting.tOnlineMeeting OM
			
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
			INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
			INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=OM.AssigneeId
	  WHERE 
    (
        (OM.Title LIKE @rTitle OR ISNULL(@rTitle, '') = '')
        AND (
            (OM.StartDate >= @rFromDate OR ISNULL(@rFromDate, '') = '')
            AND (OM.StartDate <= @rToDate OR ISNULL(@rToDate, '') = '')
            OR
            (OM.EndDate >= @rFromDate OR ISNULL(@rFromDate, '') = '')
            AND (OM.EndDate <= @rToDate OR ISNULL(@rToDate, '') = '')
        )
        AND (OM.HostEmployeeId = @rEmployeeId OR @rEmployeeId = 0)
        AND (OM.MeetingTypeId = @rMeetingTypeId OR @rMeetingTypeId = 0)
        AND (OM.MeetingAccountId = @rOnlineMeetingAccountId OR @rOnlineMeetingAccountId = 0)
        AND (
            (OM.IsCompleted IN (549, 550, 551, 0) AND @rIsCompleted = 0)
            OR (OM.IsCompleted = @rIsCompleted AND @rIsCompleted IN (549, 550, 551))
        )
        AND (
            (OM.AssigneeId IN (1, 2, 3) AND @rAssigneeId = 1)
            OR (OM.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2, 3))
        )
    )

ORDER BY
    OM.StartDate, OM.StartTime DESC
	SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2001
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
	SELECT
		OnlineMeetingId, 
		ReferencePath 
		from sEMeeting.tOnlineMeetingReference OMR
		where OMR.OnlineMeetingId = @rId
	END
	ELSE
	BEGIN
		SELECT 
			OM.Id,
			EM.EmployeeName as Teacher,
			Em.EmployeeId as TeacherId,
			OMT.Title as MeetingType,
			OMT.AutoId as MeetingTypeId,
			CONVERT(NVARCHAR,OM.StartDate) as StartDate,
			CONVERT(NVARCHAR,OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate) as EndDate,
			CONVERT(NVARCHAR,OM.EndTime,108) as EndTime,
			OM.IsCompleted as StatusId,
			OM.Title as MeetingTitle,
			OM.Description,
			OM.IsDisplayMeetingId,
			OM.MeetingId,
			OM.MeetingPassword,
			ISNULL(OM.IsReference,0) as IsReference,
			ISNULL(OM.IsResource,0) as IsResource,
			ISNULL(OM.IsCompleted,0) as IsCompleted,
			ISNULL(OM.IsMeetingStarted,0) as IsMeetingStarted,
			ISNULL(OMS.IsOnParticipantVideo,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) AS IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) AS IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) AS IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) AS IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) AS IsOnHostscreenShare,
			ISNULL(OM.MeetingAccountId,0) AS MeetingAccountId,
			ISNULL(OM.IsMeetingCreated,0) AS IsMeetingCreated,
			ISNULL(OM.IsTrackAttendance,0) AS IsTrackAttendance,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			OM.AssigneeId,
			OM.StartDate AS TeacherStartDate,
			OM.EndDate AS TeacherEndDate
	  FROM 
			sEMeeting.tOnlineMeeting OM
			
			INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OM.HostEmployeeId 
			INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
			LEFT JOIN sEMeeting.tOnlineMeetingSettings OMS ON OMS.OnlineMeetingId = OM.Id
			INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=OM.AssigneeId
	  WHERE 
			(OM.Id = @rId)
	  ORDER BY
			OM.StartDate, OM.StartTime DESC
		SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id	
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
				LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
		SELECT
		OnlineMeetingId, 
		ReferencePath 
		from sEMeeting.tOnlineMeetingReference OMR
		where OMR.OnlineMeetingId = @rId
	END
END TRY
BEGIN CATCH 
		SELECT -1 AS Result
END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingOrganizationGet]
		@rOrgGroupId int,
		@rUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT 
		UO.Id, 
		UO.DisplayTitle AS Title 
		FROM sSetup.vUserOrganization UO
        WHERE IsObsolete = 0 
		AND OrgGroupId = @rOrgGroupId  
		AND UserId = @rUserId
		ORDER BY OrderIndex
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingProviderGet]
	@rMeetingAccountId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		SELECT MeetingProviderId FROM sAcademic.tOnlineMeetingAccount WHERE Id = @rMeetingAccountId AND ISNULL(IsObsolete,0) = 0
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingReferenceDelete]

        @rOnlineMeetingId bigint,
		@rReferencePath nvarchar(Max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF NOT EXISTS (SELECT 1 FROM sEMeeting.tOnlineMeetingReference WHERE OnlineMeetingId = @rOnlineMeetingId AND ReferencePath = @rReferencePath)
	BEGIN 
		SELECT -1 AS Result
	END
	ELSE
	BEGIN
		DELETE FROM sEMeeting.tOnlineMeetingReference
		WHERE OnlineMeetingId = @rOnlineMeetingId 
		AND ReferencePath = @rReferencePath
		SELECT 1 AS Result
	END
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 
CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingResourceAdd]
	 
	@rOnlineMeetingId bigint,
	@rResourceTypeId smallint,
	@rResourcePath nvarchar(max),	
	@rIsObsolete bit = 0,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

	IF NOT EXISTS (SELECT 1 FROM [sEMeeting].[tOnlineMeetingResource] WHERE OnlineMeetingId = @rOnlineMeetingId AND ResourcePath = @rResourcePath)
	BEGIN		
	INSERT INTO [sEMeeting].[tOnlineMeetingResource]	
		(
		OnlineMeetingId,
		ResourceTypeId,
		ResourcePath,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime
		)
	VALUES
		(
		@rOnlineMeetingId,
		@rResourceTypeId,
		@rResourcePath,
		@rIsObsolete,
		@rCreatedUserId,
		GetUtcDate()
		)
	END
	COMMIT TRANSACTION
		SELECT 1 AS Result		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

	

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingScopeListGet]
	
		 @rOnlineMeetingId bigint,
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,	
			A.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[MeetingType]',OMT.Title),
			'[StartDate]',CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103)),
			'[EndDate]',CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103)),
			'[Title]',OM.Title),
			'[StartTime]',CONVERT(varchar(11),ISNULL(OM.StartTime,'') ,8)),
			'[EndTime]',CONVERT(varchar(11),ISNULL(OM.EndTime,'') ,8))
			AS MsgText,
			'' AS Subject,
			 A.SourceTypeId AS ReceiverSourceTypeId,
			 A.OrgId AS OrgId,
			 (SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			 A.AcademicId AS ReceiverSourceId,
			 A.AcademicId AS SourceId,
			 A.SourceTypeId AS SourceTypeId,
			 OMT.Title AS MeetingType,
			 CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 EE.EmployeeName AS Teacher,
			 OM.Title AS Title,
			 A.WhatsAppContactNo
	FROM 
		sEMeeting.tOnlineMeeting OM
		INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
		INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = OM.HostEmployeeId
		INNER JOIN (
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
			    sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
			    OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2003

			UNION ALL	
																			 			  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OMS.ScopeSourceId
				 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND  OMS.ScopeSourceTypeId = 2017 AND OMS.AssigneeId = 2

				UNION ALL	
																			 			  
			SELECT 
				OM.Id as OnlineMeetingId,
				vEC.EmployeeId as AcademicId,
				vEC.EmployeeName as Name,
				vEC.Code,
				vEC.MobileNumber as ParentContactNo,
				vEC.CompanyEmail as ParentEmail,
				vEC.OrgId,
				95 As SourceTypeId,
				ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.DepartmentId = OMS.ScopeSourceId 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND vEC.StatusId = 7 AND  OMS.ScopeSourceTypeId = 2017 AND OMS.AssigneeId = 3

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				SD.AcademicId,
				SD.Name,
				SD.Code,
				SD.ParentContactNo,	
				SD.ParentEmail,
				SD.OrgId,
				2003 As SourceTypeId,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OMS.ScopeSourceId
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND SD.StatusId = 1 AND OMS.ScopeSourceTypeId = 2021 AND OMS.AssigneeId = 2

				UNION ALL		
															 			 				  
			SELECT 
				OM.Id as OnlineMeetingId,
				vEC.EmployeeId as AcademicId,
				vEC.EmployeeName as Name,
				vEC.Code,
				vEC.MobileNumber as ParentContactNo,
				vEC.CompanyEmail as ParentEmail,
				vEC.OrgId,
				95 As SourceTypeId,
				ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.OrgID = OMS.ScopeSourceId 
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND vEC.StatusId = 7 AND OMS.ScopeSourceTypeId = 2021 AND OMS.AssigneeId = 3

			UNION ALL

				SELECT Distinct
				OM.Id as OnlineMeetingId,
				vEC.EmployeeId as AcademicId,
				vEC.EmployeeName as Name,
				vEC.Code,
				vEC.MobileNumber as ParentContactNo,
				vEC.CompanyEmail as ParentEmail,
				vEC.OrgId,
				95 As SourceTypeId,
				ISNULL(vEC.WhatsAppContactNo,'') AS WhatsAppContactNo
			FROM 
				sEMeeting.tOnlineMeetingScope OMS 
				INNER JOIN sEMeeting.tOnlineMeeting OM ON OMS.OnlineMeetingId = OM.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON (vEC.EmployeeId = OMS.ScopeSourceId) 
				OR (vEC.EmployeeId = OM.HostEmployeeId)
			WHERE 
				OMS.OnlineMeetingId = @rOnlineMeetingId AND vEC.StatusId = 7 AND OMS.ScopeSourceTypeId = 95
			
		) as A ON A.OnlineMeetingId = OM.Id
	WHERE
		OM.Id = @rOnlineMeetingId
END







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingScopeValidate]
	 
        @rTempOnlineMeetingId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sEMeeting.tTempOnlineMeetingScope OMS where OMS.SourceId=@rSourceId AND
					OMS.SourceTypeId=@rSourceTypeId AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON OMS.SourceId=DM.Id AND OMS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON OMS.SourceId=CM.Id AND OMS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON OMS.SourceId=DM.Id AND OMS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.SourceId=SA.AcademicId AND OMS.SourceTypeId= 2003
				where SA.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		

			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON OMS.SourceId=EM.Id AND OMS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 	
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON OMS.SourceId=DM.OrgId AND OMS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS
			 INNER JOIN sSetup.tClassMaster CM
				ON OMS.SourceId=CM.Id AND OMS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON OMS.SourceId=DM.Id AND OMS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN sStudent.tAcademic SA 
				ON OMS.SourceId=SA.Id AND OMS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 	
			
			If EXISTS(select 1 from sEMeeting.tTempOnlineMeetingScope OMS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =OMS.SourceID AND OMS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END 
		
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON OMS.SourceId=CM.OrgId AND OMS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON OMS.SourceId=CM.DepartmentId AND OMS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON OMS.SourceId=DM.Id AND OMS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sEMeeting.tTempOnlineMeetingScope OMS 
		  INNER JOIN sStudent.tAcademic SA 
				ON OMS.SourceId=SA.Id AND OMS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON OMS.SourceId=DM.OrgId AND OMS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS
		 INNER JOIN sSetup.tClassMaster CM 
			ON OMS.SourceId=CM.DepartmentId AND OMS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON OMS.SourceId=DM.ClassId AND OMS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sEMeeting.tTempOnlineMeetingScope OMS 
		  INNER JOIN sStudent.tAcademic SA 
				ON OMS.SourceId=SA.Id AND OMS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from sEMeeting.tTempOnlineMeetingScope OMS 
		  INNER JOIN sStudent.tAcademic SA 
				ON OMS.SourceId=SA.DivisionId AND OMS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
		 INNER JOIN  sStudent.tAcademic SA 
			ON OMS.SourceId=SA.OrgId AND OMS.SourceTypeId= 2021
			where SA.Id=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sEMeeting.tTempOnlineMeetingScope OMS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON OMS.SourceId=CM.DepartmentId AND OMS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
		 INNER JOIN sStudent.tAcademic SA 
				ON OMS.SourceId=SA.ClassId AND OMS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS
		 INNER JOIN sStudent.tAcademic SA 
				ON OMS.SourceId=SA.DivisionId AND OMS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sEMeeting.tTempOnlineMeetingScope OMS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON OMS.SourceId=EM.OrgId AND OMS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sEMeeting.tTempOnlineMeetingScope OMS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON OMS.SourceId=EJD.OrganizationDepartmentId AND OMS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND OMS.TempOnlineMeetingId=@rTempOnlineMeetingId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 

    END
			select 1 as Result,'' AS Msg
	
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingSettingsGet]
		@rOnlineMeetingId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT APIKey, APISecret, AccountEmailId, OAuthAccountId, OAuthClientId, OAuthClientSecret FROM [sEMeeting].[tOnlineMeetingSettings] WHERE @rOnlineMeetingId = OnlineMeetingId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingStatusTypeGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
	SELECT 
	SM.Id,
	SM.Title 
	FROM sCommon.tStatusMaster SM 
	WHERE StatusTypeId = 113 ORDER BY Id
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingStudentGet]
	@rDivisionId int,
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY

	BEGIN
		
		SELECT AcademicId as Id,(Code+' - '+CONVERT(NVARCHAR(10),RollNo)+' - '+Name) AS Title from sStudent.vStudentAcademic WHERE StatusId=1 AND DivisionId=@rDivisionId AND					OrgId=@rOrgId AND	IsActiveBatch=1 ORDER BY RollNo 
	END 
	END TRY
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingTeacherGet]
	 
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rOrgGroupId int,
	 @rOrgId int,
	 @rUserId bigint,
	 @rIsOnlineMeetingAdmin bit
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	BEGIN TRY
	If (@rSourceTypeId = 2003)
		BEGIN
		 SELECT DISTINCT EM.Id ,ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As Title FROM [sHrm].[tEmployeeMaster] EM
		  INNER	JOIN [sEMeeting].[tOnlineMeeting] OM ON OM.HostEmployeeId=EM.Id
		END
	else if(@rOrgId = 0)
	 BEGIN
		If (@rSourceTypeId = 95)
		BEGIN
			If(@rIsOnlineMeetingAdmin = 1)
			BEGIN
				SELECT EM.EmployeeId as Id, 
				[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title 
				FROM sHrm.vExtEmployee EM 
				INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM 
				ON OrgM.Id=EM.OrgId 
				WHERE ISNULL(IsOtherUser,0) = 0 AND  StatusId = 7 AND EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND
				 OM.UserId = @rUserId
				ORDER BY Title
			END
			else
			BEGIN
				SELECT EM.EmployeeId as Id, 
				[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title 
				FROM sHrm.vExtEmployee EM 
				INNER JOIN sSetup.tOrganizationMaster OrgM 
				ON OrgM.Id=EM.OrgId 
				WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId = 7 AND EM.EmployeeGroupId = 1 AND  EM.EmployeeId = @rSourceId 
				ORDER BY Title
			END
		END
		else
		BEGIN
			SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM 
			INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM ON OrgM.Id = EM.OrgId 
            WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND OM.UserId = @rUserId 
			ORDER BY Title
		END
	 END
	else
		BEGIN
		If (@rSourceTypeId = 95)
		BEGIN
		if(@rIsOnlineMeetingAdmin = 1)
			BEGIN
				SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId WHERE ISNULL(IsOtherUser,0) = 0 AND  StatusId =7  AND EmployeeGroupId = 1 
				AND OM.OrgGroupId =	@rOrgGroupId AND OM.Id = @rOrgId ORDER BY Title	
			END
		else
			BEGIN
			SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1
			AND EM.EmployeeId =	@rSourceId	ORDER BY Title
			END
		END
		else
		BEGIN
			SELECT EM.EmployeeId as Id, [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OrgM.EmployeeNameFormatId,1)) AS Title FROM sHrm.vExtEmployee EM				INNER JOIN sSetup.vUserOrganization OM ON OM.Id = EM.OrgId INNER JOIN sSetup.tOrganizationMaster OrgM ON OrgM.Id = EM.OrgId 
			WHERE ISNULL(EM.IsOtherUser,0) = 0 AND  EM.StatusId =7  AND EM.EmployeeGroupId = 1 AND OM.OrgGroupId = @rOrgGroupId AND OM.UserId = @rUserId AND OM.Id = @rOrgId 
			ORDER BY Title
		END
		END
	END TRY

	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEMeeting].[pOnlineMeetingTeacherStudentListGet]
	 @rId bigint = 0,	 
	 @rScopeSourceId bigint,
	 @rScopeSourceTypeId int,
	 @rMeetingTypeId int = 0,
	 @rStartDate date = '',
	 @rEndDate date = '',
	 @rIsCompleted int= 0,
	 @rTitle nvarchar(100) ='',
	 @rOrgGroupBatchId int,
	 @rEmployeeId bigint = 0
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	if (@rId = 0)
		BEGIN
	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint,
	 @lClassName nvarchar(100)


	 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
		@lClassName=CM.Title,@lCLassId=CM.Id
     FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
	 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
	 WHERE A.Id = @rScopeSourceId 
	 --AND BM.OrgGroupBatchId = @rOrgGroupBatchId

	 If (@rScopeSourceTypeId = 2003)
	 BEGIN
	
	  SELECT 
			OM.Id,
			OMT.Title AS MeetingType,
			OMT.AutoId AS MeetingTypeId,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,3)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,3)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			(CASE WHEN OM.IsCompleted=549 THEN 'Pending' WHEN OM.IsCompleted=550 THEN 'Completed'  WHEN OM.IsCompleted=551 THEN 'Cancel' END) AS Status,
			ISNULL(OM.Title,'') AS Title
			
		FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
				--INNER JOIN sCommon.tDataMaster DM ON DM.Id = OM.MeetingTypeId
				INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
				INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON OMS.OnlineMeetingId = OM.Id
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId AND OMS.AssigneeId = 2) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2016 AND OMS.ScopeSourceId =@lClassId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2005 AND OMS.ScopeSourceId =@lDivisionId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2003 AND OMS.ScopeSourceId =@lAcademicId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2001 AND OMS.ScopeSourceId =@lAcademicId AND OMS.AssigneeId = 2)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id

			WHERE
				(
				(OM.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
				AND (
						(OM.StartDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
						AND (OM.StartDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
						OR
						(OM.EndDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
						AND (OM.EndDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
					)
				AND ((OM.MeetingTypeId = @rMeetingTypeId)OR (ISNULL(@rMeetingTypeId,0)=0))
				AND ((Convert(int,OM.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = 0))
				AND (OM.HostEmployeeId = @rEmployeeId OR @rEmployeeId = 0)
				ORDER BY OM.StartDate, OM.StartTime DESC
			END
		
	IF (@rScopeSourceTypeId = 95)
	BEGIN 
	DECLARE @lOrgId1 int,@lDepartmentId1 int,@lEmployeeId1 bigint
	 SELECT @lOrgId1 = EC.OrgId, @lDepartmentId1 =EC.DepartmentId, @lEmployeeId1 = EC.EmployeeId
     FROM sHrm.vEmployeeCommunication EC
	 WHERE EC.Id = @rScopeSourceId
		SELECT 
			OM.Id,
			OMT.Title AS MeetingType,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartDate,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndDate,
			(CASE WHEN OM.IsCompleted=549 THEN 'Pending' WHEN OM.IsCompleted=550 THEN 'Completed'  WHEN OM.IsCompleted=551 THEN 'Cancel' END) AS Status,
			ISNULL(OM.Title,'') As Title,
			OM.StartDate AS TeacherStartDateTime,
			OM.EndDate AS TeacherEndDateTime
			FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId
				INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId1 AND OMS.AssigneeId = 3) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId1 AND OMS.AssigneeId = 3)
				OR
				(OMS.ScopeSourceTypeId = 95 AND OMS.ScopeSourceId =@lEmployeeId1 AND OMS.AssigneeId = 3)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id or (OM.HostEmployeeId = @rScopeSourceId)
			WHERE
			(
			    (OM.MeetingTypeId = @rMeetingTypeId OR @rMeetingTypeId = 0)
			    AND (
			        (OM.StartDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
			        AND (OM.StartDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
			        OR
			        (OM.EndDate >= @rStartDate OR ISNULL(@rStartDate, '') = '')
			        AND (OM.EndDate <= @rEndDate OR ISNULL(@rEndDate, '') = '')
			    )
			    AND (Convert(int, OM.IsCompleted) = @rIsCompleted OR @rIsCompleted = 0)
			    AND (OM.Title LIKE '%' + @rTitle + '%' OR ISNULL(@rTitle, '') = '')
			)
			ORDER BY
			    OM.StartDate, OM.StartTime desc;

		END
		END
	ELSE
	IF (@rScopeSourceTypeId = 2003)
	BEGIN 

	 DECLARE @lAcademicId2 bigint,@lStudentId2 bigint,@lClassId2 int,@lDivisionId2 int,@lOrgId2 int,@lDepartmentId2 int,@lEmployeeId2 bigint,
	 @lClassName2 nvarchar(100)


	 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
	 @lClassName=CM.Title,@lCLassId=CM.Id
     FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	 ON A.BatchId = BM.Id 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
 WHERE A.Id = @rScopeSourceId 
 --AND BM.OrgGroupBatchId = @rOrgGroupBatchId



	SELECT
			OM.Id,
			OMT.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndTime,
			(CASE WHEN OM.IsCompleted=549 THEN 'Pending' WHEN OM.IsCompleted=550 THEN 'Completed'  WHEN OM.IsCompleted=551 THEN 'Cancel' END) AS Status,
			OM.MeetingTypeId AS MeetingTypeId,
			OM.IsDisplayMeetingId AS IsDisplayMeetingId,
			OM.MeetingId AS MeetingId,
			OM.MeetingPassword AS MeetingPassword,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsCompleted AS IsCompleted,
			ISNULL(OM.Description,'')AS Description,
			ISNULL(OM.Title,'') AS Title,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsMeetingCreated AS IsMeetingCreated,
			OM.IsReference,
			OM.IsResource
          FROM 
				sEMeeting.tOnlineMeeting OM
				
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId 
				INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
				INNER JOIN (SELECT OMS.OnlineMeetingId FROM sEMeeting.tOnlineMeetingScope OMS
				WHERE (
				( 
				(OMS.ScopeSourceTypeId = 2021 AND OMS.ScopeSourceId =@lOrgId AND OMS.AssigneeId = 2) 
				OR
				(OMS.ScopeSourceTypeId = 2017 AND OMS.ScopeSourceId =@lDepartmentId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2016 AND OMS.ScopeSourceId =@lClassId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2005 AND OMS.ScopeSourceId =@lDivisionId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2003 AND OMS.ScopeSourceId =@lAcademicId AND OMS.AssigneeId = 2) OR
				(OMS.ScopeSourceTypeId = 2001 AND OMS.ScopeSourceId =@lAcademicId AND OMS.AssigneeId = 2)
				 ))
				) D
				ON D.OnlineMeetingId= OM.Id

            
            WHERE
				 OM.Id = @rId

				ORDER BY OM.StartDate,OM.StartTime desc
				SELECT 1 from sEMeeting.tOnlineMeetingScope where OnlineMeetingId = @rId
				SELECT
				OnlineMeetingId, 
				ReferencePath 
				from sEMeeting.tOnlineMeetingReference OMR
				where OMR.OnlineMeetingId = @rId
		END
		
		IF(@rScopeSourceTypeId = 95)
		BEGIN
		SELECT 
			OM.Id,
			OMT.Title AS MeetingType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			CONVERT(NVARCHAR,OM.StartDate,103)+' '+CONVERT(NVARCHAR(5),OM.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OM.EndDate,103)+' '+CONVERT(NVARCHAR(5),OM.EndTime,108) as EndTime,
			(CASE WHEN OM.IsCompleted=549 THEN 'Pending' WHEN OM.IsCompleted=550 THEN 'Completed'  WHEN OM.IsCompleted=551 THEN 'Cancel' END) AS Status,
			OM.MeetingTypeId AS MeetingTypeId,
			OM.IsDisplayMeetingId AS IsDisplayMeetingId,
			OM.MeetingId AS MeetingId,
			OM.MeetingPassword AS MeetingPassword,
			OM.IsCompleted AS IsCompleted,
			ISNULL(OM.Title,'') AS Title,
			ISNULL(OM.Description,'')AS Description,
			ISNULL(OM.IsMeetingStarted,'') AS IsMeetingStarted,
			OM.IsMeetingCreated AS IsMeetingCreated,
			OM.IsTrackAttendance AS IsTrackAttendance,
			OM.IsReference,
			OM.IsResource,
			OM.HostEmployeeId
		FROM 
				sEMeeting.tOnlineMeeting OM
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OM.HostEmployeeId
				INNER JOIN sEMeeting.tMeetingTypeMaster OMT ON OMT.AutoId = OM.MeetingTypeId
				INNER JOIN sEMeeting.tOnlineMeetingScope OMS ON OMS.OnlineMeetingId = OM.Id
		WHERE
			 OM.Id = @rId
			ORDER BY OM.StartDate, OM.StartTime DESC
		SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OMS.ScopeSourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2021

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId 
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2017

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN  sSetup.tClassMaster CM
				ON OMS.ScopeSourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2016

			UNION ALL

			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS ROllNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON OMS.ScopeSourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId	
				WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2005

			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		    INNER JOIN sStudent.tStudentMaster SM
				ON OMS.ScopeSourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.ROllNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON OMS.ScopeSourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId	
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 OMS.OnlineMeetingId,
			 OMS.ScopeSourceTypeId,
			 OMS.ScopeSourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS ROllNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
			 OMS.AssigneeId
			FROM sEMeeting.tOnlineMeetingScope OMS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON OMS.ScopeSourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = OMS.AssigneeId
			WHERE OMS.OnlineMeetingId=@rId AND OMS.ScopeSourceTypeId=95
		SELECT
		OnlineMeetingId, 
		ReferencePath 
		from sEMeeting.tOnlineMeetingReference OMR
		where OMR.OnlineMeetingId = @rId
			END
		
END





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOrderIndexMeetingTypeMasterGet]
@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT ISNULL(MAX(OrderIndex),0)+1 AS Result FROM sEMeeting.tMeetingTypeMaster WHERE OrgGroupId = @rOrgGroupId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pOrgGroupIdGet]
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec sEMeeting.pPermissionGet 9911,9911000000270
CREATE OR ALTER PROCEDURE [sEMeeting].[pPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)
BEGIN
	SELECT		TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
	FROM
	(
		SELECT 	
			P.TaskId					AS	TaskID,
			(Permission & 1) 		AS	C, --[Create],
			(Permission & 2)/2		AS	R, --[Read],
			(Permission & 4)/4		AS	U, --[Update],
			(Permission & 8)/8		AS	D, --[Delete],
			(Permission & 16)/16 	AS	S, --[Search],
			(Permission & 32)/32 	AS	P, --[Print],
			(Permission & 64)/64 	AS	X --[Execute]
		FROM sSecurity.tPermissionUser P
		INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
		INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
		INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
		WHERE
		P.OrgGroupId = @rOrgGroupId AND P.UserId = @rUserId 
	) TP 
	GROUP BY TP.TaskId
END
ELSE
BEGIN
	SELECT		TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
	FROM
	(
		SELECT 	
			P.TaskId					AS	TaskID,
			(Permission & 1) 		AS	C, --[Create],
			(Permission & 2)/2		AS	R, --[Read],
			(Permission & 4)/4		AS	U, --[Update],
			(Permission & 8)/8		AS	D, --[Delete],
			(Permission & 16)/16 	AS	S, --[Search],
			(Permission & 32)/32 	AS	P, --[Print],
			(Permission & 64)/64 	AS	X --[Execute]
		FROM sSecurity.tPermission P
		INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
		INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
		INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
		INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
		ON R.RoleId = P.RoleId 
		WHERE
		P.OrgGroupId = @rOrgGroupId 
		--AND
	--RoleId 
	
	--IN
	-- (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId )
	) TP 
	GROUP BY TP.TaskId
	
	--SELECT	CAST(MAX(TP.C) AS BIT) AS [Create],
	--		CAST(MAX(TP.R) AS BIT) AS [Read],
	--		CAST(MAX(TP.U) AS BIT) AS [Update],
	--		CAST(MAX(TP.D) AS BIT) AS [Delete],
	--		CAST(MAX(TP.S) AS BIT) AS [Search],
	--		CAST(MAX(TP.P) AS BIT) AS [Print],
	--		CAST(MAX(TP.X) AS BIT) AS [Execute]
	--FROM
	--(
	--	SELECT 	(Permission & 1) AS C,
	--			(Permission & 2)/2 AS R,
	--			(Permission & 4)/4 AS U,
	--			(Permission & 8)/8 AS D,
	--			(Permission & 16)/16 AS S,
	--			(Permission & 32)/32 AS P,
	--			(Permission & 64)/64 AS X
	--	FROM sSecurity.tPermission
	--	WHERE TaskId = @rTaskId AND 
	--		  RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId)
	--) TP
END


END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec sEMeeting.pScreenGet 
CREATE OR ALTER PROCEDURE [sEMeeting].[pScreenGet] 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
	BEGIN TRY
		SELECT	
			S.Id			AS ScreenId,
			S.Title		AS ScreenTitle,
			S.TaskId		AS TaskId,	
			S.Page		As PageUrl,
			S.IsObsolete	AS ScreenIsObsolete,	
			S.Title,		
			S.Page,
			SG.Id AS ScreenGroupId,
			ISNULL(SG.Title,'') AS ScreenGroupName
		
		FROM 
			sSecurity.tScreen S (nolock)
		LEFT JOIN sSecurity.tScreenGroupMaster SG ON SG.Id=S.ScreenGroupId
		WHERE 
			S.IsObsolete = 0 and S.ScreenGroupID IN (253) OR S.Id = 31293
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
end


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pSMSTemplateIdGet]
		@rOrgId int,
		@rCustomEventId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT SMSTemplateID FROM sAlert.tCustomTemplateMaster WHERE Id = @rCustomEventId AND OrgId = @rOrgId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pStudentProfileGet]
		@rAcademicId bigint,
		@rBatchId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT A.OrgId, BatchId, StudentId, A.Id AS AcademicId, SM.Code, A.RollNo, (FirstName +' '+MiddleName+' '+LastName) AS StudentName,
                           SM.FirstName, SM.MiddleName, SM.LastName, A.ClassId, A.DivisionId, (CM.DisplayTitle + '-' + DM.DisplayTitle) AS ClassDivision,
                            DPM.Id AS DepartmentId, DPM.DisplayTitle AS DepartmentName, SM.SUID, B.Title as BatchName 
                            FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
                            INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
                            INNER JOIN sSetup.tDepartmentMaster DPM ON DPM.Id = CM.DepartmentId
                            INNER JOIN sSetup.tBatchMaster B ON b.Id = A.BatchId 
                            WHERE A.Id= @rAcademicId  AND BatchId = @rBatchId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEMeeting].[pTempOnlineMeetingScopeAdd]

			@rTempOnlineMeetingId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
          ,@rAssigneeToId int 
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 

If(@rIsDeleted=1)
BEGIN
	Delete from sEMeeting.tTempOnlineMeetingScope where TempOnlineMeetingId=@rTempOnlineMeetingId AND SourceTypeId=@rSourceTypeId AND AssigneeToId= @rAssigneeToId
	AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select TempOnlineMeetingId from sEMeeting.tTempOnlineMeetingScope where TempOnlineMeetingId=@rTempOnlineMeetingId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId AND AssigneeToId= @rAssigneeToId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sEMeeting.tTempOnlineMeetingScope
			(
				TempOnlineMeetingId
			   ,SourceTypeId
			   ,SourceId
			   ,AssigneeToId
			)
			VALUES
			(	
				@rTempOnlineMeetingId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,@rAssigneeToId
			)		
			SELECT 1 AS Result
		 
	END	
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sEMeeting].[pUpdateMeetingDetails]
	@rId bigint,
	@rType nvarchar(20)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
 
	IF EXISTS (SELECT 1 from [sEMeeting].[tOnlineMeeting] where Id = @rId AND @rType IN ('Join', 'Start Again', 'Complete'))
	BEGIN
	IF (@rType = 'Join')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsMeetingStarted=1, StartDateTime = GetUtcDate() WHERE Id= @rId

	ELSE IF (@rType = 'Start Again')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsCompleted=549,IsMeetingStarted=1 WHERE Id= @rId	

	ELSE IF (@rType = 'Complete')
		UPDATE [sEMeeting].[tOnlineMeeting] SET IsCompleted=550,IsMeetingStarted=0,EndDateTime = GetUtcDate() WHERE Id= @rId

	SELECT 1 as Result
	END 
	ELSE
	BEGIN
		SELECT -101 as Result
	END
	END TRY

	BEGIN CATCH
	SELECT -1 as Result
	END CATCH

END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pUpdateOnlineMeetingAccountToken]
	@rAccessToken nvarchar(max),
	@rOnlineMeetingAccountId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			UPDATE sAcademic.tOnlineMeetingAccount SET JWTToken = @rAccessToken Where Id = @rOnlineMeetingAccountId AND MeetingProviderId = 1
			SELECT 11 as Result
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pUpdateOnlineMeetingSettingsToken]
	@rAccessToken nvarchar(max),
	@rOnlineMeetingIds nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			UPDATE sEMeeting.tOnlineMeetingSettings SET JWTToken = @rAccessToken WHERE OnlineMeetingId IN (SELECT CAST(Nodes.node.value('.', 'BIGINT') AS INT) AS id
			FROM (
			SELECT CAST('<x>' + REPLACE(@rOnlineMeetingIds, ',', '</x><x>') + '</x>' AS XML) AS xmlcol
			) AS t
			CROSS APPLY xmlcol.nodes('/x') AS Nodes(node))
		SELECT 11 as Result
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sEMeeting].[pValidateOnlineMeetingAccount]
@rId bigint = 0,
@rStartDate nvarchar(50),
@rStartTime nvarchar(50),
@rEndDate nvarchar(50),
@rEndTime nvarchar(50),
@rMeetingAccountId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
		if(@rId = 0)
		BEGIN
			SELECT 1 
			FROM sEMeeting.tOnlineMeeting 
			WHERE (((StartDate <= @rStartDate) 
			AND (EndDate >= @rEndDate)) 
			OR ((StartDate >= @rStartDate) 
			AND (EndDate <= @rEndDate)))
            AND (((StartTime <= @rStartTime) 
			AND (EndTime >= @rEndTime)) 
			OR ((StartTime <=  @rStartTime) 
			AND (EndTime >= @rEndTime))) 
			AND MeetingAccountId = @rMeetingAccountId
		END
		ELSE
		BEGIN
			SELECT 1 
			FROM sEMeeting.tOnlineMeeting OM
			WHERE (((StartDate <= @rStartDate) 
			AND (EndDate >= @rEndDate)) 
			OR ((StartDate >= @rStartDate) 
			AND (EndDate <= @rEndDate)))
            AND (((StartTime <= @rStartTime) 
			AND (EndTime >= @rEndTime)) 
			OR ((StartTime <= @rEndTime) 
			AND (EndTime >= @rStartTime))) 
			AND @rId = OM.Id
			AND MeetingAccountId = @rMeetingAccountId
		END
		END TRY
		BEGIN CATCH
		SELECT -101 AS Result
		END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pValidateOnlineMeetingTeacher]
@rOnlineMeetingId bigint = 0,
@rId bigint = 0,
@rStartDate nvarchar(50),
@rStartTime nvarchar(50),
@rEndDate nvarchar(50),
@rEndTime nvarchar(50),
@rMeetingAccountId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
		BEGIN
		if(@rOnlineMeetingId = 0)
		BEGIN
			SELECT 1 
			FROM sEMeeting.tOnlineMeeting OM
			WHERE HostEmployeeId = @rId
        AND (
            (@rStartDate BETWEEN StartDate AND EndDate OR @rEndDate BETWEEN StartDate AND EndDate)
            OR
            (StartDate BETWEEN @rStartDate AND @rEndDate OR EndDate BETWEEN @rStartDate AND @rEndDate)
        )
        AND (
            (@rStartTime BETWEEN StartTime AND EndTime OR @rEndTime BETWEEN StartTime AND EndTime)
            OR
            (StartTime BETWEEN @rStartTime AND @rEndTime OR EndTime BETWEEN @rStartTime AND @rEndTime)
        )
		AND OM.IsCompleted <> 551
		END
		ELSE
		BEGIN
		SELECT 1 
			FROM sEMeeting.tOnlineMeeting OM
			WHERE HostEmployeeId = @rId
        AND (
            (@rStartDate BETWEEN StartDate AND EndDate OR @rEndDate BETWEEN StartDate AND EndDate)
            OR
            (StartDate BETWEEN @rStartDate AND @rEndDate OR EndDate BETWEEN @rStartDate AND @rEndDate)
        )
        AND (
            (@rStartTime BETWEEN StartTime AND EndTime OR @rEndTime BETWEEN StartTime AND EndTime)
            OR
            (StartTime BETWEEN @rStartTime AND @rEndTime OR EndTime BETWEEN @rStartTime AND @rEndTime)
        ) AND @rOnlineMeetingId <> OM.Id
		END
		END
		END TRY
		BEGIN CATCH
		SELECT -101 AS Result
		END CATCH
	END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sEMeeting].[pWhatsAppTemplateGet]
		@rEventId int,
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			SELECT Template,WhatsAppTemplate,WhatsAppTemplateLanguage FROM sAlert.tEventTemplate WHERE EventId = @rEventId AND OrgId = @rOrgId AND AlertModeId = 4
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pActivityPlanStatusRemove]

	 	@rRemarkId int,
	 	@rFlag int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			IF(@rFlag =0)
				BEGIN
					 DELETE From  sErp.tMarketingActivityPlanDetail Where  	AutoId=	@rRemarkId
					SELECT 1 AS Result
				END
			ELSE
				BEGIN
				 DELETE From  sErp.tMarketingActivityStatusDetail Where  	AutoId=	@rRemarkId
					SELECT 1 AS Result
				END
				  COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pBaseLatlongAdd]	
		@rEmployeeId bigint,
		@rBaseLatitudeAxis nvarchar(20),
		@rBaseLongitudeAxis nvarchar(20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF Exists (SELECT 1 FROM sErp.tEmployeeERPDetail Where EmployeeId = @rEmployeeId )
	BEGIN
		UPDATE sErp.tEmployeeERPDetail
				SET
					BaseLatitudeAxis = @rBaseLatitudeAxis,
					BaseLongitudeAxis = @rBaseLongitudeAxis
					WHERE EmployeeId = @rEmployeeId
					SELECT @rEmployeeId AS Result		 
					return
	END
	
	ELSE
	
		BEGIN
			INSERT INTO sErp.tEmployeeERPDetail
			(EmployeeId,BaseLatitudeAxis,BaseLongitudeAxis)
			Values 
			(@rEmployeeId,@rBaseLatitudeAxis,@rBaseLongitudeAxis)
			SELECT @rEmployeeId AS Result
			return
		END 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pBaseLatlongGet]	
		@rEmployeeId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

			SELECT  
				BaseLatitudeAxis,
				BaseLongitudeAxis 
			FROM 
				sErp.tEmployeeERPDetail
				WHERE EmployeeId = @rEmployeeId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pCallLogAdd]    
	@rEmployeeId bigint,
	@rLeadId int=0, 
	@rContactNumber bigint=0,
	@rCallDuration smallint=0,
	@rCallPerson nvarchar(200)='',
	@rCallSchool nvarchar(200)='',
	@rUpdatedDateTime DATETIME='',
	@rUpdatedUserId bigint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		INSERT INTO [sErp].[tCallLog]
			([EmployeeId],[LeadId],[ContactNumber],[CallDuration],
			[CallPerson],[CallSchool],[UpdatedDateTime],[UpdatedUserId])
		VALUES
			(@rEmployeeId,
			@rLeadId,
			@rContactNumber,
			@rCallDuration,
			@rCallPerson,
			@rCallSchool,
			sCommon.fGetDate(),
			@rUpdatedUserId)

		SELECT 1 AS Result 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pCallLogGet]
	@rEmployeeId bigint = 0,
	@rFromUpdatedDateTime DATETIME='',
		@rToUpdatedDateTime DATETIME=''
	--@rUpdatedUserId bigint=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 
SELECT AutoId,CL.EmployeeId,LeadId,ContactNumber,CallDuration,CallPerson,CallSchool,
ISNULL(CL.UpdatedDateTime,'0001/01/01') AS UpdatedDateTime,
CL.UpdatedUserId
FROM sErp.tCallLog CL
WHERE 
   ((CL.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
  AND (( convert(DATE, CL.UpdatedDateTime,102) >= @rFromUpdatedDateTime) OR (@rFromUpdatedDateTime=''))
   AND (( convert(DATE, CL.UpdatedDateTime,102) <= @rToUpdatedDateTime) OR (@rToUpdatedDateTime=''))
   
Order by CL.AutoId  Desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pChannelMasterAdd]
	 @rOrgId smallint,
	 @rId int, 
	 @rCode nvarchar(100), 
	 @rTitle nvarchar(100), 
	 @rIsObsolete bit, 
	 @rCreatedUserId bigint, 
	 @rUpdatedUserId bigint        	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sErp.tChannelMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sErp.tChannelMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tChannelMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tChannelMaster
		(
			 OrgId,
			 Id,
			 Code,
			 Title,
			 IsObsolete,
			 CreatedUserId,
			 CreatedDateTime,
			 UpdatedUserId, 
			 UpdatedDateTime

		)
	VALUES
		(
			 @rOrgId ,
			 @lNextNumber, 
			 @rCode , 
			 @rTitle , 
			 @rIsObsolete , 
			 @rCreatedUserId , 
			 sCommon.fGetDate(),
			 @rUpdatedUserId  ,			  
			 sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tChannelMaster
	    SET
			Title=@rTitle,
			Code=@rCode,
			IsObsolete=@rIsObsolete,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pChannelMasterGet]

	 @rId int,
	  @rOrgId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100),
	 @rIsWildCardSearch bit
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF @rIsWildCardSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			CM.Id,
			CM.Code	,	
			CM.Title,
			
		    CM.OrgId,
		    CM.CreatedUserId,
		    CM.CreatedDateTime,
		    CM.IsObsolete
		    
	FROM 
			sErp.tChannelMaster CM
	WHERE 
		(CM.OrgId = @rOrgId)
		AND	((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((CM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
			
	
		
		ORDER BY CM.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pContactBookMasterAdd]	
		@rId int=0,
		@rOrgId smallint,
		@rContactPerson nvarchar(100),
		@rContactMobileNo nvarchar(50),
		@rContactEmail nvarchar(100),
		@rContactCompany nvarchar(200),
		@rContactDesignation nvarchar(100),
		@rAddress1 nvarchar(500),
		@rAddress2 nvarchar(500),
		@rAreaName nvarchar(100),
		@rCityName nvarchar(100),
		@rStateName nvarchar(100),
		@rCountryname nvarchar(100),
		@rZipCode nvarchar(20),
		@rWebsite nvarchar(100),
		@rLeadSourceId tinyint,
		@rLeadOwnerEmployeeId bigint,
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint =0,
		@rRemark nvarchar(500)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tContactBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sErp.tContactBookMaster
			(
				Id,
				OrgId,
				ContactPerson,
				ContactMobileNo,
				ContactEmail,
				ContactCompany,
				ContactDesignation,
				Address1,
				Address2,
				AreaName,
				CityName,
				StateName,
				CountryName,
				ZipCode,
				Website,
				LeadSourceId,
				LeadOwnerEmployeeId,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				Remark
			)
			VALUES
			(
				@lNextNumber,
				@rOrgId,
				@rContactPerson,
				@rContactMobileNo,
				@rContactEmail,
				@rContactCompany,
				@rContactDesignation,
				@rAddress1,
				@rAddress2,
				@rAreaName,
				@rCityName,
				@rStateName,
				@rCountryName,
				@rZipCode,
				@rWebsite,
				@rLeadSourceId,
				@rLeadOwnerEmployeeId,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rUpdatedUserId,
				sCommon.fGetDate(),
				@rRemark
			)
			 SELECT 1 AS Result
	    select @lNextNumber as ContactBookMasterId
	    print 1
	END	 
	ELSE
	 BEGIN
	 SET @lNextNumber = @rId

		UPDATE sErp.tContactBookMaster
				SET
					OrgId=@rOrgId ,
					ContactPerson=@rContactPerson ,
					ContactMobileNo=@rContactMobileNo ,
					ContactEmail=@rContactEmail ,
					ContactCompany=@rContactCompany ,
					ContactDesignation=@rContactDesignation ,
					Address1=@rAddress1 ,
					Address2=@rAddress2 ,
					AreaName=@rAreaName ,
					CityName=@rCityName ,
					StateName=@rStateName ,
					CountryName=@rCountryName ,
					ZipCode=@rZipCode ,
					Website=@rWebsite ,
					LeadSourceId=@rLeadSourceId ,
					LeadOwnerEmployeeId=@rLeadOwnerEmployeeId ,
					--CreatedUserId=@rCreatedUserId ,
					--CreatedDateTime= sCommon.fGetDate(),
					UpdatedUserId=@rUpdatedUserId ,
					UpdatedDateTime = sCommon.fGetDate(),
					Remark = @rRemark
					
					WHERE Id = @rId
					SELECT 11 AS Result
					 END  	

					COMMIT TRANSACTION		
					END TRY
	
				BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pContactBookMasterGet]	
		@rLeadOwnerEmployeeId bigint

		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		CBM.Id,
		CBM.OrgId,
		CBM.ContactPerson,
		CBM.ContactMobileNo,
		CBM.ContactEmail,
		CBM.ContactCompany,
		CBM.ContactDesignation,
		CBM.Address1,
		CBM.Address2,
		CBM.AreaName,
		CBM.CityName,
		CBM.StateName,
		CBM.CountryName,
		CBM.ZipCode,
		CBM.Website,
		CBM.LeadSourceId,
		CBM.LeadOwnerEmployeeId,
		CBM.CreatedUserId,
		CBM.CreatedDateTime,
		CBM.UpdatedUserId,
		CBM.UpdatedDateTime,
		CBM.Remark,
		LSM.Title As LeadSourceName
		FROM 
		sErp.tContactBookMaster CBM
		INNER JOIN  sErp.tLeadSourceMaster LSM ON LSM.Id = CBM.LeadSourceId
		WHERE CBM.LeadOwnerEmployeeId = @rLeadOwnerEmployeeId
		
		ORDER BY Id DESC
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sErp].[pCurrentStudentStrengthDetailGet]
	 	 
		@rOrgGroupId smallint=0,
		@rOrgGroupBatchId bigint = 0,
		@rCommonOrgGroupBatchId int = 0,
		@rFlag int = 0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

Declare @strStudentCount VarChar (MAX)
Declare @strEmployeeCount VarChar(MAX)
Declare @strFeeReceiptDate VarChar (MAX)
Declare @strExamStatusDate VarChar (MAX)
Declare @strBonafiesCertificateDate VarChar (MAX)
Declare @strLCCertificateDate VarChar (MAX)
Declare @strAttendanceDate VarChar (MAX)
Declare @strEmployeeDate VarChar (MAX)
Declare @strAlertDate VarChar (MAX)
DECLARE @strMobileUserCount varchar(MAX)
DECLARE @rstrStudentUser VARCHAR(MAX)
DECLARE @rstrEmployeeUser VARCHAR(MAX)
DECLARE @strAppModuleSummary VARCHAR(MAX)
DECLARE @strAppUserSummary VARCHAR(MAX)

--SET @strSQL = 'SELECT * FROM ' + @rDatabaseName+ '.sSetup.tOrgGroupSetting WHERE OrgGroupId = '+ convert (nvarchar,@rOrgGroupId)

			SET @strStudentCount =  'SELECT ISNULL(NoOfStudent,0) As NoOfStudent,ISNULL(StudentExtraCap,0) As StudentExtraCap FROM sSetup.tOrgGroupSetting OS'+
			+' WHERE '+ 
			+' OS.OrgGroupId ='+ convert (nvarchar,@rOrgGroupId)
			+' SELECT COUNT(SM.AcademicId) AS ActiveStudent FROM sStudent.vStudentAcademic SM '+ 
			--+'INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId '+
			--+'INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SM.BatchId  '+
			+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SM.OrgGroupBatchId'
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId'
			+' WHERE OGBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+ ' and SM.StatusID=1 AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)
			--AND BM.IsActive = 1 
			+' SELECT COUNT(SM.AcademicId) as TotalStudent FROM sStudent.vStudentAcademic SM '+ 
			--+'INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId '+
			--+'INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SM.BatchId '+
			+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SM.OrgGroupBatchId'+
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId'+
			+' WHERE OGBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+'AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			--AND BM.IsActive = 1'		
			print @strStudentCount 

			SET @strFeeReceiptDate = 'SELECT DATEDIFF(DAY,MAX(FR.CreatedDateTime),sCommon.fGetDate())AS FeeDays,MAX(FR.CreatedDateTime)AS LastFeeDate FROM sFee.tReceipt FR 
			INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=FR.OrgGroupBatchId 
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId 
			WHERE OBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+'AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			--print @strFeeReceiptDate
			SET @strExamStatusDate= 'SELECT DATEDIFF(DAY,MAX(ES.UpdatedDateTime),sCommon.fGetDate())AS ExamDays,MAX(ES.UpdatedDateTime)AS LastExamDate FROM sAssessment.tResult ES'+
			--+' INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=ES.DivisionId'+
			--+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)
			+' INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId =ES.AcademicId '+
			+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId '+
			+' INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+' WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId) +'AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			--print @strExamStatusDate
			SET @strAttendanceDate ='SELECT  DATEDIFF(DAY,MAX(SR.AttendanceDate),sCommon.fGetDate())AS AttendancDays,MAX(SR.AttendanceDate)AS LastAttendanceDate FROM sAttendance.tStudentRegister SR '+ 
			+'INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId =  SR.AcademicId '+
			+'INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId '+
			+'INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+'INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+'WHERE OBM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+' and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 

			--WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)
			print @strAttendanceDate

			SET @strEmployeeDate ='SELECT DATEDIFF(DAY,MAX(EM.CreatedDateTime),sCommon.fGetDate())AS EmployeeDays,MAX(EM.CreatedDateTime)AS LastEmployeeDate FROM sHrm.tEmployeeMaster EM'+
			+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId '+
			+'INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+'INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+'WHERE OBM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+' and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			

			SET @strAlertDate= 'SELECT DATEDIFF(DAY,MAX(AL.CreatedDateTime),sCommon.fGetDate())AS AlertDays,MAX(AL.CreatedDateTime)AS LastAlertDate FROM sAlert.tAlertLog AL'+
			+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId '+
			+'INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+'INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+'WHERE OBM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+' and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			
			--WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)

			SET @strBonafiesCertificateDate = 'SELECT DATEDIFF(DAY,MAX(B.CreatedDateTime),sCommon.fGetDate())AS BonafiedDays,MAX(B.CreatedDateTime)AS BonafiedDate FROM sCertificate.tBonafide  B'+
			+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=B.OrgId '+
			+'INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+'INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+'WHERE OBM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+' and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			
			--WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)


			SET @strLCCertificateDate = 'SELECT DATEDIFF(DAY,MAX(L.CreatedDateTime),sCommon.fGetDate())AS LCDays,MAX(L.CreatedDateTime)AS LCDate FROM sCertificate.tLeaving  L'+
			+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=L.OrgId '+
			+'INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+'INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+'WHERE OBM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+' and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			
			--WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)


			SET @strMobileUserCount = 'SELECT  
				
				ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU 
				INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND((O1.Id = '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SC.BatchId 
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM1.OrgGroupId 
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId 
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND SC.StatusId = 1 AND BM.IsActive =1 and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+'),0) +
				
				ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU 
				INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM1.OrgGroupId 
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId 
				AND(OM1.Id !=1) AND((O1.Id =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+') 
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 95),0) AS Registered,
				
				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SC.BatchId 
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId
				WHERE U1.IsObsolete = 0 AND((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0))
				and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' 
				AND(OM.Id !=1) AND SC.StatusId = 1 AND U1.SourceTypeId= 2003 AND A.UserId IS NULL),0)+ 
				
				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId 
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+'
				LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				WHERE U1.IsObsolete = 0 AND((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				AND(OM.Id !=1) AND U1.SourceTypeId = 95 AND A.UserId IS NULL ),0)
				AS NotRegistered
				FROM
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId 
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM1.OrgGroupId 
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+'
				AND(OM1.Id !=1) 
				AND((O1.Id ='+convert (nvarchar,@rOrgGroupId) +')OR('+convert (nvarchar,@rOrgGroupId)+'=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				 
				WHERE U.IsObsolete = 0
				--AND((OM.Id =  1101)OR(1101=0))
				AND((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				AND(OM.Id !=1)
				AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+'
				GROUP BY OM.OrgGroupId'
				

			SET @strEmployeeCount = 'SELECT COUNT(EM.Id) as ActiveEmployeeCount FROM sHrm.tEmployeeMaster EM '+ 
			+'INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id '+
			+'INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId '+
			+'INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id '+
			+'INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId '+
			+'INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 '+
			+'INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId '+
			--+'INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id  '+
			--+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId'
			--+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '
			--+'INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017'
			+' WHERE OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+ ' and EM.StatusId=7 AND EM.IsOtherUser = 0 '+

			+' SELECT COUNT(EM.Id) as EmployeeCount FROM sHrm.tEmployeeMaster EM '+ 
			+'INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id '+
			+'INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId '+
			+'INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id '+
			+'INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId '+
			+'INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 '+
			+'INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId '+
			--+'INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id  '+
			--+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId'
			--+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '
			--+'INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017'
			+' WHERE OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+ ' AND EM.IsOtherUser = 0 '

			
			
			SET @rstrStudentUser = 'SELECT ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
				+'LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId '+
				+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SC.OrgGroupBatchId '+
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) AS StudentCreatedUsers'

			+' SELECT ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
				+'LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId '+
				+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SC.OrgGroupBatchId '+
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) AS StudentRegisteredUsers'

			+' SELECT ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id '+
				+'LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId '+
				+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SC.OrgGroupBatchId '+
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' AND SC.StatusId = 1 AND U1.SourceTypeId=2003 AND A.UserId IS NULL),0) AS StudentNotRegisteredUsers'



			SET @rstrEmployeeUser = 'SELECT ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
			--	+' INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id  '+
			--	+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId '+
			--+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND U1.SourceTypeId=95),0) AS EmployeeCreatedUsers'

			+' SELECT ISNULL((SELECT COUNT(RU.UserId) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
			+' INNER JOIN (SELECT RU.UserId AS  UserId FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U2 ON RU.UserId = U2.Id '+
				+' INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U2.OrgId '+
				+'WHERE U2.IsObsolete = 0 AND OM1.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM1.Id !=1) AND U2.IsObsolete = 0 AND U2.SourceTypeId= 95 GROUP BY RU.UserId ) RU ON RU.UserId = U1.Id '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND U1.SourceTypeId=95),0) AS EmployeeRegisteredUsers'


			+
				' SELECT ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND U1.SourceTypeId=95),0) '
				+' - (SELECT ISNULL((SELECT COUNT(RU.UserId) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
			+' INNER JOIN (SELECT RU.UserId AS  UserId FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U2 ON RU.UserId = U2.Id '+
				+' INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U2.OrgId '+
				+'WHERE U2.IsObsolete = 0 AND OM1.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM1.Id !=1) AND U2.IsObsolete = 0 AND U2.SourceTypeId= 95 GROUP BY RU.UserId ) RU ON RU.UserId = U1.Id '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND U1.SourceTypeId=95),0)) AS EmployeeNotRegisteredUsers'



			SET @strAppModuleSummary = 
			'SELECT ''Circular'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(C.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sCommunication.tCircular C WHERE OrgGroupId = '+convert (nvarchar,@rOrgGroupId)
			
			+' SELECT ''Assignment'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(A.CreatedDateTime),sCommon.fGetDate()),0))AS Summary,MAX(A.CreatedDateTime) as LastUsed,CASE  WHEN DATEDIFF(DAY,MAX(A.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(A.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sCommunication.tAssignment A INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=BM.OrgGroupBatchId INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId WHERE COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' AND OBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)
			
			+' SELECT ''CW/HW'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(C.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sAcademic.tClasswork C INNER JOIN sSetup.tBatchMaster BM ON BM.Id = C.BatchId INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=BM.OrgGroupBatchId INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId WHERE COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' AND OBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)
			
			+' SELECT ''Query'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(Q.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(Q.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(Q.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(Q.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sCommunication.tQuery Q WHERE OrgGroupId = '+convert (nvarchar,@rOrgGroupId)
			
			+' SELECT ''Video'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(V.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(V.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(V.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(V.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sSupport.tVideoMaster V INNER JOIN sSetup.tOrganizationMaster OM ON V.OrgId = OM.Id WHERE OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)
			
			+' SELECT ''Event'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(E.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(E.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(E.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(E.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sActivity.tEventSchedule E INNER JOIN sSetup.tBatchMaster BM ON BM.Id = E.BatchId INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=BM.OrgGroupBatchId INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId WHERE OBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+ ' AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)
			
			+' SELECT ''Gallery'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(P.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(P.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(P.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(P.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sCommunication.tPhotoCategoryMaster P  WHERE P.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)

			SET @strAppUserSummary = 'SELECT 
				OM2.ID AS OrgId,
				OM2.DisplayTitle AS OrgName,
				OM2.Code, 
				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND OM.Id = OM2.Id  AND((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				AND(OM.Id !=1) AND ((SC.OrgGroupBatchId ='+convert (nvarchar,@rOrgGroupBatchId)+') OR ('+convert (nvarchar,@rOrgGroupBatchId)+' = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) AS ''StudentCreatedUser'',

				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0))
				 AND(OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0) AS ''EmployeeCreatedUser'',
 
				ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND OM1.Id = OM2.Id AND((O1.Id =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.OrgGroupBatchId = '+convert (nvarchar,@rOrgGroupBatchId)+') OR ('+convert (nvarchar,@rOrgGroupBatchId)+' = 0)) AND SC.StatusId = 1),0) AS ''StudentRegister'',

				ISNULL((SELECT COUNT(RU.UserId) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId INNER JOIN (SELECT RU.UserId AS  UserId FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U2 ON RU.UserId = U2.Id
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U2.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId AND (OM1.Id !=1) AND((O1.Id =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) WHERE U2.IsObsolete = 0 AND U2.SourceTypeId= 95 GROUP BY RU.UserId ) RU ON RU.UserId = U1.Id
				WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) AND (OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0) AS ''EmployeeRegister'',

				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND OM.Id = OM2.Id AND((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				AND(OM.Id !=1) AND ((SC.OrgGroupBatchId = '+convert (nvarchar,@rOrgGroupBatchId)+') OR ('+convert (nvarchar,@rOrgGroupBatchId)+' = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003 AND A.UserId IS NULL),0) AS ''StudentNotRegister'',

				ISNULL((ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0))
				 AND(OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0) - ISNULL((SELECT COUNT(RU.UserId) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId INNER JOIN (SELECT RU.UserId AS  UserId FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U2 ON RU.UserId = U2.Id
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U2.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId AND (OM1.Id !=1) AND((O1.Id =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) WHERE U2.IsObsolete = 0 AND U2.SourceTypeId= 95 GROUP BY RU.UserId ) RU ON RU.UserId = U1.Id
				WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) AND (OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0)),0) ''EmployeeNotRegister''
				 
				FROM
				 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM2 ON OM2.Id = U.OrgId 
				LEFT JOIN (
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1)
				AND((O1.Id =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				 
				WHERE U.IsObsolete = 0
				AND((OM2.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				AND(OM2.Id !=1)
				GROUP BY OM2.Id,OM2.DisplayTitle,OM2.Code'
				



			
			exec (@strStudentCount)
			exec (@strMobileUserCount)
			exec (@strEmployeeCount)
			

			IF(@rFlag > 0 AND @rFlag < 4)
			BEGIN
				exec (@strFeeReceiptDate)
				exec (@strExamStatusDate)
				exec (@strBonafiesCertificateDate)
				exec (@strLCCertificateDate)
				exec (@strAttendanceDate)
				exec (@strEmployeeDate)
				exec (@strAlertDate)
				exec (@rstrStudentUser)
				exec (@rstrEmployeeUser)
				exec (@strAppModuleSummary)
			END
			ELSE IF(@rFlag = 4)
			BEGIN
				exec (@strAppUserSummary)
			END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pCustomerActivationLogAdd]    
	@rOrgGroupID int, 
	@rLogDate Date,
	@rStatusRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rCustomerStatusId tinyint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	--IF EXISTS(SELECT Id FROM sRecruitment.tCandidateMaster WHERE CandidateNumber=@rCandidateNumber AND OrgGroupID=@rOrgGroupID)
	--	BEGIN
	--	SELECT -101 as Result
	--	RETURN
	--END 
	
    
	BEGIN TRY
 	BEGIN TRANSACTION							
		INSERT INTO sErp.tCustomerActivationLog
			(
				OrgGroupID, 
				LogDate,
				StatusRemark,
				CreatedUserId,
				CreatedDateTime	,
				CustomerStatusId		
			)
		VALUES
			(
			
				@rOrgGroupID, 
				@rLogDate,
				@rStatusRemark,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCustomerStatusId	
			
			
				
			)
		
		UPDATE sErp.tCustomerMaster SET CustomerStatusId=@rCustomerStatusId Where OrgGroupId=@rOrgGroupId
		SELECT 1 AS RESULT
	

		COMMIT TRANSACTION
	 
		END TRY
		
		BEGIN CATCH
		ROLLBACK TRANSACTION 
 SELECT -1 AS RESULT
			--RAISERROR ('Error saving employee Master', -- Message text.
   --            16, -- Severity.
   --            1 -- State.
   --            );           
		 
 
		END CATCH			
 
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pCustomerActivationLogGet] 
(		
		@rAutoId int,
		@rOrgId smallint,
		@rOrgGroupId smallint, 					
		@rCustomerStatusId tinyint=0,	
		@rFromDate datetime,
		@rToDate datetime	
	
 )
AS
SET NOCOUNT ON

BEGIN

		
		SELECT 
		CL.AutoId AS ActivationLogId,
				CM.Id AS CustomerId,
				CM.OrgGroupId,
				CM.CRMLicenceId,
				CM.Title AS CustomerName,
				CL.LogDate,
				CL.StatusRemark,
				CL.CreatedUserId,
				CL.CreatedDateTime,
				CL.CustomerStatusId,
				CS.Title AS CustomerStatusTitle
			
		FROM sErp.tCustomerActivationLog  CL
		
			LEFT JOIN sErp.tCustomerMaster CM ON CL.OrgGroupId=CM.OrgGroupId			
			LEFT JOIN sErp.tCustomerStatusMaster CS on CS.Id=CL.CustomerStatusId						
		WHERE 
			((CL.AutoId = @rAutoId) OR (@rAutoId = 0))
		
			AND((CM.OrgId = @rOrgId)OR (@rOrgId=0))
			AND ((CL.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))		 
		    AND ((CL.CustomerStatusId =@rCustomerStatusId) OR (@rCustomerStatusId = 0))		  
		    AND ((CL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
			AND ((CL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
            order by CL.CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sErp].[pCustomerMasterAdd]  	 	 
			@rId int, 
			@rOrgId smallint, 
			@rOrgGroupId smallint, 
			@rCRMLicenceId int, 
			@rTitle nvarchar(200), 
			@rShortTitle nvarchar(100), 
			@rStreetOne nvarchar(50), 
			@rStreetTwo nvarchar(50), 
			@rStreetThree nvarchar(50), 
			@rCityName nvarchar(100), 
			@rZipCode nvarchar(20),	
			@rHomePage nvarchar(100), 
			@rPhoneNo nvarchar(50), 
			@rMobileNo nvarchar(50), 
			@rContactPerson nvarchar(100),
			@rCreatedUserId bigint,       
			--@rUpdatedUserId bigint, 
			@rIsObsolete bit,
			@rCustomerStatusId tinyint,
			@rChannelId int, 
			@rInstallationTypeId tinyint,
			@rStateId int, 
			@rCountryId int, 
			@rDomain  nvarchar(200),
			@rDb nvarchar(100), 
			@rInstallationDate date,
			@rEmail nvarchar(100),
			@rAbsolutePath nvarchar(300)='',
			@rCampusType  int=0,
			--Remainder Perameter.--
			@rPaymentDueDate Date =null,
			@rIsPaymentReminder bit=0,
			@rPaymentRemainderRemark nvarchar(300) = '',
			@rstudentExtraCap int=0,
			@rLastStudentCapReminderDate date = null,
			@rStudentCapReminderCount smallint=0,
			@rStudentCapReminderDate date =null,
			@rIsStopServiceReminder bit=0,
			@rServiceStopRemark nvarchar(300)='',
			@rServiceStopDate date=null,
			@rIsAutoStopService bit=0,
			@rNoOfStudent int =0,
			@rPlugin nvarchar(200) = '',
			@rTag nvarchar(200) = ''
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--BEGIN
--	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sErp.tCustomerMaster where OrgGroupId=@rOrgGroupId AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	
		If Exists(select Id from sErp.tCustomerMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where ShortTitle=@rShortTitle AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where CRMLicenceId=@rCRMLicenceId AND OrgId=@rOrgId)
			BEGIN
			select -101 as Result
			RETURN
		END 
			If Exists(select Id from sErp.tCustomerMaster where Domain=@rDomain AND OrgId=@rOrgId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
			BEGIN
			select -105 as Result
			RETURN
		--END 
		--If Exists(select Id from sErp.tCustomerMaster where Db=@rDb AND OrgId=@rOrgId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
		--	BEGIN
		--	select -106 as Result
		--	RETURN
		END 
		
	END
	ELSE
	BEGIN
		If Exists(select Id from sErp.tCustomerMaster where OrgGroupId=@rOrgGroupId AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
		If  Exists(select Id from sErp.tCustomerMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
        If Exists(select Id from sErp.tCustomerMaster where ShortTitle=@rShortTitle AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where CRMLicenceId=@rCRMLicenceId AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where Domain=@rDomain AND OrgId=@rOrgId AND Id<>@rId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
			BEGIN
			select -105 as Result
			RETURN
		--END 
		--If Exists(select Id from sErp.tCustomerMaster where Db=@rDb AND OrgId=@rOrgId AND Id<>@rId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
		--	BEGIN
		--	select -106 as Result
		--	RETURN
		END 
	END
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tCustomerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tCustomerMaster
		(
			Id ,
			OrgId ,
			OrgGroupId ,
			CRMLicenceId ,
			Title ,
			ShortTitle ,
			StreetOne,
			StreetTwo ,
			StreetThree ,
			CityName ,
			ZipCode,
			HomePage ,
			PhoneNo ,
			MobileNo ,
			ContactPerson ,
			CreatedUserId , 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			IsObsolete,
			CustomerStatusId ,
			ChannelId ,
			InstallationTypeId,
			StateId ,
			CountryId ,
			Domain ,
			Db ,
			InstallationDate ,
			Email,
			AbsolutePath,
			CampusTypeId,
			PaymentDueDate,
			IsPaymentReminder,
			PaymentReminderRemark,
			StudentExtraCap,
			LastStudentCapReminderDate,
			StudentCapReminderCount,
			StudentCapReminderDate,
			IsStopServiceReminder,
			ServiceStopRemark,
			ServiceStopDate,
			IsAutoStopService,
			PlugIn,
			Tag
			
        )
	VALUES
		(
			@lNextNumber , 
			@rOrgId,
			@rOrgGroupId , 
			@rCRMLicenceId , 
			@rTitle , 
			@rShortTitle, 
			@rStreetOne , 
			@rStreetTwo , 
			@rStreetThree , 
			@rCityName,
			@rZipCode,
			@rHomePage,
			@rPhoneNo,
			@rMobileNo,
			@rContactPerson,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rCustomerStatusId,
			@rChannelId,
			@rInstallationTypeId,
			@rStateId,
			@rCountryId,
			@rDomain,
			@rDb,
			@rInstallationDate,
			@rEmail,
			@rAbsolutePath,
			@rCampusType,
			@rPaymentDueDate,
			@rIsPaymentReminder,
			@rPaymentRemainderRemark,
			@rstudentExtraCap,	
			@rLastStudentCapReminderDate,
			@rStudentCapReminderCount	,
			@rStudentCapReminderDate,
			@rIsStopServiceReminder,
			@rServiceStopRemark,
			@rServiceStopDate,
			@rIsAutoStopService,
			@rPlugin,
			@rTag		
		)
			INSERT INTO sSetup.tOrgGroupSetting
		(OrgGroupId,NoOfStudent,PaymentDueDate,IsPaymentReminder,PaymentReminderRemark,StudentExtraCap,
		LastStudentCapReminderDate,
		StudentCapReminderCount,StudentCapReminderDate,IsStopServiceReminder,ServiceStopRemark,ServiceStopDate,
		IsAutoStopService)
		VALUES
		(@rOrgGroupId ,@rNoOfStudent,@rPaymentDueDate,
			@rIsPaymentReminder,
			@rPaymentRemainderRemark,
			@rstudentExtraCap,	
			@rLastStudentCapReminderDate,
			@rStudentCapReminderCount	,
			@rStudentCapReminderDate,
			@rIsStopServiceReminder,
			@rServiceStopRemark,
			@rServiceStopDate,
			@rIsAutoStopService )
		INSERT INTO sErp.tCustomerActivationLog
			(
			OrgGroupId,
			LogDate,
			StatusRemark,
			CreatedUserId,
			CreatedDateTime,
			CustomerStatusId
			)
			VALUES
			(
			@rOrgGroupID , 
			sCommon.fGetDate(),
			'',
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCustomerStatusId
			
			)
		
		
		    SELECT 1 AS Result
	END	 
	

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tCustomerMaster
	    SET		
			OrgGroupId= @rOrgGroupId,
			CRMLicenceId =@rCRMLicenceId,
			Title=@rTitle ,
			ShortTitle=@rShortTitle ,
			StreetOne=@rStreetOne,
			StreetTwo=@rStreetTwo ,
			StreetThree=@rStreetThree ,
			CityName= @rCityName,
			ZipCode=@rZipCode,
			HomePage= @rHomePage,
			PhoneNo=@rPhoneNo ,
			MobileNo= @rMobileNo,
			ContactPerson =@rContactPerson,

			UpdatedUserId=@rCreatedUserId, 
			UpdatedDateTime=sCommon.fGetDate(),
			IsObsolete=@rIsObsolete,
			CustomerStatusId= @rCustomerStatusId,
			ChannelId=@rChannelId ,
			InstallationTypeId=@rInstallationTypeId,
			StateId=@rStateId ,
			CountryId =@rCountryId,
			Domain =@rDomain,
			Db =@rDb,
			InstallationDate =@rInstallationDate,
			Email=@rEmail,
			AbsolutePath=@rAbsolutePath,
			CampusTypeId=@rCampusType,
			PaymentDueDate=@rPaymentDueDate,
			IsPaymentReminder=@rIsPaymentReminder,
			PaymentReminderRemark=@rPaymentRemainderRemark,
			StudentExtraCap=@rstudentExtraCap,	
			LastStudentCapReminderDate=@rLastStudentCapReminderDate,
			StudentCapReminderCount=@rStudentCapReminderCount	,
			StudentCapReminderDate=@rStudentCapReminderDate,
			IsStopServiceReminder=@rIsStopServiceReminder,
			ServiceStopRemark=@rServiceStopRemark,
			ServiceStopDate=@rServiceStopDate,
			IsAutoStopService=@rIsAutoStopService,
			PlugIn=@rPlugin,
			Tag=@rTag
	      WHERE Id = @rId
		  
		
	      SELECT 11 AS Result
	 --END  	

	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pCustomerMasterDelete]
	 @rOrgGroupId smallint, 
	  @rCustomerId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	IF EXISTS (SELECT  CustomerId  FROM sErp.tCustomerOrg WHERE  CustomerId=  @rCustomerId)
	BEGIN 
		SELECT -101 AS Result
	END
	IF EXISTS (SELECT  OrgGroupId   FROM sSecurity.tOrgGroupMobileApp WHERE  OrgGroupId =  @rOrgGroupId  )
	BEGIN 
		SELECT -102 AS Result
	END
	ELSE
		BEGIN 		
			DELETE  FROM sErp.tCustomerMaster WHERE Id = @rCustomerId AND OrgGroupId = @rOrgGroupId

			DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId = @rOrgGroupId
			SELECT 1 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pCustomerMasterGet]

	  @rId int,
	  @rOrgId smallint=0,
	  @rOrgGroupId smallint=0,
	  @rTitle nvarchar(100),
	  @rShortTitle nvarchar(100),
	  @rCRMLicenceId int=0, 
	  @rCustomerStatusId tinyint,
      @rChannelId int, 
      @rInstallationTypeId nvarchar(max)='',
	  @rPlugIn int=0,
	  @rTag int=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rShortTitle = sCommon.fSearchStringGet(@rShortTitle)
	END
	
	IF (RIGHT(@rInstallationTypeId, 1) = ',')
        SET @rInstallationTypeId = LEFT(@rInstallationTypeId, LEN(@rInstallationTypeId) - 1)
	
	SELECT 
			CM.Id,
			CM.OrgId,
			CM.OrgGroupId,				
			CM.Title,
			CM.ShortTitle,
			CM.CRMLicenceId,
			CM.StreetOne,
			CM.StreetTwo,
			CM.StreetThree,
			ISNULL(CM.CountryId,0) AS CountryId,
			CM.StateId,
			CM.CityName,
			CM.ZipCode,
			CM.HomePage,
			CM.MobileNo,
			CM.PhoneNo,
			CM.ContactPerson,
			CM.CustomerStatusId AS CustomerStatusTypeId,
			CS.Title AS CustomerStatus,
			CM.ChannelId AS ChannelTypeId,
			CC.Title AS ChannelName,
			CM.InstallationTypeId AS InstallationId,
			IT.Title AS InstallationType,	
			CM.Domain,
			CM.Db,
			CM.InstallationDate,
			--CS.Id AS CustomerStatusTypeId,
			--CS.Title AS CustomerStatus,
			--CC.Id AS ChannelTypeId,
			--CC.Title AS ChannelName,
			--IT.Id AS InstallationId,
			--IT.Title AS InstallationType,	
			CM.IsObsolete ,
			Isnull(CM.Email,'') As Email,
			ISNULL(AbsolutePath,'') AS AbsolutePath,
			ISNULL(CampusTypeID,0) As CampusTypeID,
			ISNULL(CA.Title,'') As CampusType,
			PaymentDueDate,
			IsPaymentReminder,
			PaymentReminderRemark,
			StudentExtraCap,
			LastStudentCapReminderDate,
			StudentCapReminderCount,
			StudentCapReminderDate,
			IsStopServiceReminder,
			ServiceStopRemark,
			ServiceStopDate
	FROM 
			 sErp.tCustomerMaster CM
			 LEFT JOIN  sErp.tCustomerStatusMaster CS ON CM.CustomerStatusId=CS.Id
			 LEFT JOIN sErp.tChannelMaster CC ON CM.ChannelId=CC.Id
			 LEFT JOIN sErp.tInstallationTypeMaster IT ON CM.InstallationTypeId=IT.Id
			 LEFT JOIN sErp.tCampusTypeMaster CA ON CA.Id= CM.CampusTypeId
	WHERE 
	    ((CM.OrgId = @rOrgId)OR (@rOrgId=0))
		AND((CM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId=0))
		AND	((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))		
		AND	((CM.CRMLicenceId = @rCRMLicenceId) OR (@rCRMLicenceId = 0))
		AND ((CM.ShortTitle like @rShortTitle) OR (ISNULL(@rShortTitle,'') = ''))
		AND ((CM.CustomerStatusId like @rCustomerStatusId) OR (@rCustomerStatusId=0))
		AND ((CM.ChannelId like @rChannelId) OR (@rChannelId=0))
		--AND ((CM.InstallationTypeId like @rInstallationTypeId) OR (@rInstallationTypeId=0))
		AND ((CM.InstallationTypeId IN (SELECT item from sCommon.fnSplit(@rInstallationTypeId,',')))  OR (ISNULL(@rInstallationTypeId,'') = ''))
		AND ((CM.PlugIn like @rPlugIn) OR (@rPlugIn=0))
		AND ((CM.Tag like @rTag) OR (@rTag=0))
		ORDER BY CM.OrgGroupId DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pCustomerOrgAdd]
	@rOrgId smallint,
	@rCustomerId int,
    @rOrgNumber int,
    @rOrgName nvarchar(200),
    @rActivationDate date,
    @rInActiveDate date,
    @rCreatedUserId [bigint],   
    @rCustomerStatusId tinyint ,
    @rIsActive bit  ,
    @rIsSave bit   	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	
	
	IF (@rIsSave=1)
	BEGIN
		If Exists(select CO.CustomerId from sErp.tCustomerOrg CO 
		LEFT JOIN sErp.tCustomerMaster CM ON CO.CustomerId=CM.Id 
		where CO.OrgNumber=@rOrgNumber AND CM.OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		--If Exists(select CustomerId from sErp.tCustomerOrg where OrgName=@rOrgName)
		--	BEGIN
		--	select -103 as Result
		--	RETURN
		--END 
	END
	ELSE
	-- IF NOT EXISTS(SELECT 1 FROM sErp.tCustomerOrg Where  OrgNumber = @rOrgNumber)
	BEGIN
		If  Exists(select CO.CustomerId from sErp.tCustomerOrg CO
		LEFT JOIN sErp.tCustomerMaster CM ON CO.CustomerId=CM.Id 
		where CO.OrgNumber=@rOrgNumber AND CO.CustomerId <> @rCustomerId 
		--AND CO.OrgNumber<>OrgNumber 
		AND CM.OrgId=@rOrgId)
		Begin
			select -102 as Result
			RETURN
		End
		--If   Exists(select CustomerId from sErp.tCustomerOrg where OrgName=@rOrgName AND CustomerId <> CustomerId)
		--Begin
		--	select -103 as Result
		--	RETURN
		--End

	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

--IF NOT EXISTS(SELECT 1 FROM sErp.tCustomerOrg Where CustomerId = @rCustomerId AND OrgNumber = @rOrgNumber)
IF(@rIsSave=1)
	BEGIN
		 
		 
	INSERT INTO sErp.tCustomerOrg
		(CustomerId,
			OrgNumber,
			OrgName,
			ActivationDate,
			InActiveDate,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			CustomerStatusId,
			IsActive	

		)
	VALUES
		(
			 @rCustomerId ,
				 @rOrgNumber,
				 @rOrgName,
				 @rActivationDate ,
				 @rInActiveDate ,
				 @rCreatedUserId,
				 sCommon.fGetDate(),
				 @rCreatedUserId,
				 sCommon.fGetDate(),
			     @rCustomerStatusId,
			     @rIsActive
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
		 
	    UPDATE  sErp.tCustomerOrg
	    SET 
			 --OrgNumber=@rOrgNumber
			  OrgName=@rOrgName,
			 CustomerStatusId=@rCustomerStatusId,
				UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
	      IsActive=@rIsActive,
	      ActivationDate=@rActivationDate,
	      InActiveDate=@rInActiveDate
	      WHERE 	CustomerId = @rCustomerId
		AND OrgNumber = @rOrgNumber
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pCustomerOrgGet]

	 @rCustomerId int,
	 @rOrgId smallint,
	 @rOrgNumber int=0
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	
	SELECT 
			CM.CustomerId,
			CM.OrgNumber ,
			CM.OrgNumber AS RowIndex,
			CM.OrgName,
			CM.ActivationDate,
		   CM.InActiveDate,
		   CM.CustomerStatusId,
		    CS.Title AS CustomerStatus,
		    COM.Title AS CustomerName,
		    CM.IsActive,
		    COM.OrgGroupId
	FROM 
			 sErp.tCustomerOrg CM
			 LEFT JOIN sErp.tCustomerStatusMaster CS ON CS.Id=CM.CustomerStatusId
			 LEFT JOIN sErp.tCustomerMaster COM ON COM.Id=CM.CustomerId
	WHERE 
	
			((CM.CustomerId = @rCustomerId) OR (@rCustomerId = 0))
			AND((COM.OrgId = @rOrgId)OR (@rOrgId=0))
			AND ((CM.OrgNumber = @rOrgNumber) OR (@rOrgNumber = 0))
		
		ORDER BY CM.OrgNumber DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pCustomerOrgListGet]
	 
	 @rOrgId smallint,
	 @rOrgGroupId smallint,
	 @rCustomerId int=0,
	 @rOrgNumber int=0,
	 @rOrgName nvarchar(200),
	 @rCustomerStatusId tinyint=0,
	 @rChannelId int=0,
	 @rInstallationTypeId tinyint=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rOrgName = sCommon.fSearchStringGet(@rOrgName)
	
	END
	
	SELECT 
			CM.CustomerId,
			COM.Title AS CustomerName,
			CM.OrgNumber,
			CM.OrgName,
			CM.ActivationDate,
		   CM.InActiveDate,
		   COM.CustomerStatusId,
		    CS.Title AS CustomerStatus,
		    COM.Title AS CustomerName,
		    CM.IsActive,
		    COM.OrgGroupId,
		    COM.ChannelId,
		    CC.Title AS ChannelName,
		    COM.InstallationTypeId,
		    IM.Title AS InstallationType
	FROM 
			 sErp.tCustomerOrg CM
			
			 LEFT JOIN sErp.tCustomerMaster COM ON COM.Id=CM.CustomerId
			  LEFT JOIN sErp.tCustomerStatusMaster CS ON CS.Id=COM.CustomerStatusId
			 LEFT JOIN sErp.tInstallationTypeMaster IM ON IM.Id= COM.InstallationTypeId
			 LEFT JOIN sErp.tChannelMaster CC ON CC.Id= COM.ChannelId
	WHERE 
	
			((CM.CustomerId = @rCustomerId) OR (@rCustomerId = 0))
			AND((COM.OrgId = @rOrgId)OR (@rOrgId=0))
			AND((COM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId=0))
				AND ((CM.OrgName like @rOrgName) OR (ISNULL(@rOrgName,'') = ''))
			AND ((CM.OrgNumber = @rOrgNumber) OR (@rOrgNumber = 0))
			AND((COM.ChannelId = @rChannelId)OR (@rChannelId=0))
			AND((COM.InstallationTypeId = @rInstallationTypeId)OR (@rInstallationTypeId=0))
			AND((COM.CustomerStatusId = @rCustomerStatusId)OR (@rCustomerStatusId=0))
		
		ORDER BY CM.OrgNumber desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pCustomerOrgRemove]

	 	@rCustomerId int,
	 	@rOrgNumber int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			
				     DELETE From  sErp.tCustomerOrg Where  	CustomerId=	@rCustomerId
				     AND OrgNumber=@rOrgNumber
					SELECT 1 AS Result
				  COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sErp].[pDSRBluckAdd]
    @rOrgId int,
	@rUserId bigint ,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
--BEGIN TRY
DECLARE @loXML XML
SET @loXML = CAST(@rXmldoc AS XML)

DECLARE @lCount INT
DECLARE     @lSuptype [nvarchar](200) = '',
			@lWorkDec [nvarchar](Max) = '',
			@lReportDate  date ,
		    @lProjectId  int = 0, 
		    @lWorkTypeId int = 0,
		    @lHoursWorked Decimal(5,2)
			
 
  CREATE TABLE #tTable1 
 (
			Id int identity(1,1),
			OrgId smallint,
		    ReportDate Date,
			ProjectId int,
			SubType	nvarchar(200),
			WorkTypeID	int,
			WorkDescription nvarchar(Max),
			HoursWorked Decimal(5,2),
			CreatedUserId bigint,
			CreatedDateTime datetime,
			UpdatedUserId bigint,
			UpdatedDateTime  datetime
  )
  INSERT INTO #tTable1
	(
			OrgId,
			ReportDate,
			ProjectId,
			SubType,
			WorkTypeID,
			WorkDescription,
			HoursWorked,
			CreatedUserId,
			CreatedDateTime ,
			UpdatedUserId ,
			UpdatedDateTime  
     )      
   SELECT
		 @rOrgId,
         T.c.value('@DSRDate','Date') AS ReportDate,
         T.c.value('@ProjectId','Int') AS ProjectId,
		 T.c.value('@SubType','nvarchar(200)') AS SubType,
		 T.c.value('@WorkTypeID','Int') AS WorkTypeID,
		 T.c.value('@WorkDescription','nvarchar(Max)') AS WorkDescription,
		 T.c.value('@HoursWorked','Decimal(5,2)') AS HoursWorked,
		 @rUserId,
		 getdate(),
		 @rUserId,
		 Getdate()
		 
   FROM
     @loXML.nodes('/Table/ImportDSR')T(c)
     
    
BEGIN

SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 

BEGIN		
		
	SELECT         
          
		    @lSuptype = sSetup.fPortalXMLTagsReplaceReverse(SubType),
			@lWorkDec = sSetup.fPortalXMLTagsReplaceReverse(WorkDescription),
			@lReportDate = ReportDate,
			@lProjectId = ProjectId,
			@lWorkTypeId = WorkTypeID,
			@lHoursWorked = HoursWorked
			
			FROM #tTable1 WHERE Id = @lCount    
     
	BEGIN
	
		DECLARE @rNoOfRecords int
		
		SET @rNoOfRecords = ISNULL(@rNoOfRecords, 1)

		DECLARE @lFirstCode Nvarchar(300)
		DECLARE @lLastCode Nvarchar(300)
		DECLARE @lTotalRecords Int
		SET @lTotalRecords = @rNoOfRecords
		
		BEGIN
			DECLARE @lNextNumber INT
					
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tDSR', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
			INSERT INTO sErp.tDSR
				(
					Id, 
					ReportDate, 
					ProjectId, 
					Module, 
					DSRWorkTypeId, 
					WorkDescription, 
					HoursWorked, 
					OrgId,
					CreatedUserId, 
					CreatedDateTime, 
					UpdatedDateTime ,
					UpdatedUserId      
				)
			VALUES
				(
					@lNextNumber,
					@lReportDate,
					@lProjectId,
					@lSuptype,
					@lWorkTypeId,
					@lWorkDec,
					@lHoursWorked,
					@rOrgId,
					@rUserId,
					sCommon.fGetDate(),
					sCommon.fGetDate(),
					@rUserId
				)			

	     END
	   SET @lCount = @lCount - 1
     END
   END
 END
    SELECT 1 AS Result, '' AS ResultDetail
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pDSRMasterAdd]

        @rId int,
        @rReportDate date,
        @rProjectId int,
        @rModule nvarchar(max),
        @rWorkTypeId int,
        @rWorkDescription nvarchar(max),
        @rHoursWorked decimal(5, 2),
        @rOrgId smallint,
        @rCreatedUserId bigint ,
		@rMinuteWorked    smallint    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tDSR', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tDSR
		(
		    Id, 
		    ReportDate, 
		    ProjectId, 
		    Module, 
		    DSRWorkTypeId, 
		    WorkDescription, 
		    HoursWorked, 
			MinuteWorked,
		    OrgId,
		    CreatedUserId, 
		    CreatedDateTime, 
		    UpdatedDateTime ,
		    UpdatedUserId      
		)
	VALUES
		(
			@lNextNumber,
			@rReportDate,
			@rProjectId,
			@rModule,
			@rWorkTypeId,
			@rWorkDescription,
			@rHoursWorked,
			@rMinuteWorked,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate(),
			@rCreatedUserId
		)
		    SELECT 1 AS Result,@lNextNumber As DsrId
	END	 
  ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tDSR
	    SET
			ReportDate = @rReportDate,
			ProjectId = @rProjectId,
			Module = @rModule,
			DSRWorkTypeId = @rWorkTypeId,
			WorkDescription = @rWorkDescription,
			HoursWorked = @rHoursWorked,
			MinuteWorked=@rMinuteWorked,
			OrgId = @rOrgId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result,@lNextNumber As DsrId
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pDSRMasterGet]

	 @rId int,
	 @rUserId bigint,
	 @rFromDate Date,
	 @rTillDate Date,
	 @rOrgId smallint,
	 @rModule nvarchar(100),
	 @rProjectId int ,
	 @rWorkTypeId int 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rModule = sCommon.fSearchStringGet(@rModule)
	END
	
	SELECT 
			PT.Id,
			PT.ReportDate,
			PT.ProjectId,
		    PT.Module,
		    PT.DSRWorkTypeId,
		    PT.WorkDescription,
		    convert(int,PT.HoursWorked) As HoursWorked,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PM.Title as Project,
		    Dwt.Title as DSRWorkType,
			CASE WHEN PT.MinuteWorked IS NULL THEN 	PARSENAME(PT.HoursWorked,1)  ELSE ISNUll(PT.MinuteWorked,0) END  AS  MinuteWorked,
			CONVERT(nvarchar(10),CONVERT(int,PT.HoursWorked)) +':'+ CONVERT(nvarchar(10),ISNUll(PT.MinuteWorked,0)) AS HoursWork
		FROM 
			sErp.tDSR  PT
			inner join sErp.tDSRWorkTypeMaster Dwt on Dwt.Id = PT.DSRWorkTypeId
			inner join sErp.tProjectMaster PM on PM.Id = PT.ProjectId
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Module like @rModule) OR (ISNULL(@rModule,'') = ''))
		AND	((PT.ProjectId = @rProjectId) OR (@rProjectId = 0))
		AND	((PT.DSRWorkTypeId = @rWorkTypeId) OR (@rWorkTypeId = 0))
		AND ((PT.CreatedUserId = @rUserId) OR (@rUserId = 0))
		AND ((PT.ReportDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	    AND ((PT.ReportDate <= @rTillDate) OR (ISNULL(@rTillDate,'') = ''))
	    
	    order by ReportDate desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sErp].[pDSRMasterGetForAllList]

	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	
	SELECT 
			PT.Id,
			PT.ReportDate,
			PT.ProjectId,
		    PT.Module,
		    PT.DSRWorkTypeId,
		    PT.WorkDescription,
		    PT.HoursWorked,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PM.Title as Project,
		    Dwt.Title as DSRWorkType
		 
		
	FROM 
			sErp.tDSR  PT
			inner join sErp.tDSRWorkTypeMaster Dwt on Dwt.Id = PT.DSRWorkTypeId
			inner join sErp.tProjectMaster PM on PM.Id = PT.ProjectId
	WHERE 
		
		((PT.Id = @rId) OR (@rId = 0))
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pDSRMasterSearchGet]

	 @rId int,
	 @rUserId bigint,
	 @rFromDate Date,
	 @rTillDate Date,
	 @rOrgId smallint,
	 @rModule nvarchar(100),
	 @rProjectId int ,
	 @rWorkTypeId int ,
	 @rActive bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rModule = sCommon.fSearchStringGet(@rModule)
	END
	
	SELECT 
			PT.Id,
			PT.ReportDate,
			PT.ProjectId,
		    PT.Module,
		    PT.DSRWorkTypeId,
		    PT.WorkDescription,
		    ISNULL(PT.HoursWorked,0) AS HoursWorked,
		    ISNULL(PT.MinuteWorked,0) AS MinuteWorked,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PM.Title as Project,
		    Dwt.Title as DSRWorkType,
		    u.DisplayTitle,
		    CONVERT(nvarchar(10),CONVERT(int,PT.HoursWorked)) +':'+ CONVERT(nvarchar(10),ISNUll(PT.MinuteWorked,0)) AS HoursWork
		 
		
	FROM 
			sErp.tDSR  PT
			inner join sErp.tDSRWorkTypeMaster Dwt on Dwt.Id = PT.DSRWorkTypeId
			inner join sErp.tProjectMaster PM on PM.Id = PT.ProjectId
			inner join sSecurity.tUser u on u.Id = PT.CreatedUserId
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Module like @rModule) OR (ISNULL(@rModule,'') = ''))
		AND	((PT.ProjectId = @rProjectId) OR (@rProjectId = 0))
		AND	((PT.DSRWorkTypeId = @rWorkTypeId) OR (@rWorkTypeId = 0))
		AND ((u.id = @rUserId) OR (@rUserId = 0))
		AND ((PT.ReportDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	    AND ((PT.ReportDate <= @rTillDate) OR (ISNULL(@rTillDate,'') = ''))
	    and PM.IsActive =@rActive
	    
	    order by ReportDate desc
	    
	
		
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pDSRWorkTypeMasterAdd]

        @rId int,
        @rTitle nvarchar(100),
        @rCode nvarchar(100),
        @rInActive bit = 0,
        @rOrgId smallint,
        @rCreatedUserId bigint        
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		
		If Exists(select Id from sErp.tDSRWorkTypeMaster  where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
		If Exists(select Id from sErp.tDSRWorkTypeMaster  where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		
		If  Exists(select Id from sErp.tDSRWorkTypeMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
			If  Exists(select Id from sErp.tDSRWorkTypeMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tDSRWorkTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tDSRWorkTypeMaster

		(
			Id,
			Code,
			Title,			
			OrgId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedDateTime,
			UpdatedUserId			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rOrgId,
			@rInActive,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate(),
			@rCreatedUserId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tDSRWorkTypeMaster
	    SET
			Code = @rCode,
			Title=@rTitle,
			IsObsolete=@rInActive,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pDSRWorkTypeMasterGet]

	 @rId int,
	 @rOrgId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			PT.Id,
			PT.Title,
			PT.Code,
		    PT.OrgId,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PT.IsObsolete
		    
	FROM 
			sErp.tDSRWorkTypeMaster  PT
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((PT.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pEmployeeListGet]
(
	@rOrgId smallint,
	@rOrgGroupId smallint,
    @rEmployeeManagerId  bigint=0,      
    @rIsSearchHierarchyWise smallint = 0
 )
 
AS
SET NOCOUNT ON
BEGIN
	
	IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='#TempEmployeeId')
	BEGIN		
		DROP Table #TempEmployeeId
	END
	
	CREATE TABLE #TempEmployeeId
	(
		EmployeeId bigint
	)
	 
	IF @rIsSearchHierarchyWise = 0
	BEGIN		  
		SELECT EM.Id AS EmployeeId,EM.Code AS EmployeeCode, EM.FirstName +' '+ EM.LastName AS EmployeeName,EI.EmployeePhoto
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId 
		AND (OGDM.Code = '01' OR OGDM.Code = '04')
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
		WHERE ( EJD.EmployeeManagerId = @rEmployeeManagerId OR EM.Id = @rEmployeeManagerId)  AND EM.StatusId = 7
		AND ((EM.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) AND ISNULL(EM.IsOtherUser,0) = 0 

		ORDER BY  EM.Code
	END
	IF @rIsSearchHierarchyWise = 1
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EJD.OrgId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND  (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rEmployeeManagerId) OR (@rEmployeeManagerId = 0))
			 AND ((EJD.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			 AND ((OM.OrgGroupId=@rOrgGroupId ) OR (@rOrgGroupId=0))
			 
			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			)
			
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT EmployeeID FROM EmployeeCTE
		
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT @rEmployeeManagerId
		
		SELECT EM.Id  AS EmployeeId,EM.Code AS EmployeeCode, EM.FirstName+' '+ EM.LastName AS EmployeeName,EI.EmployeePhoto
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD On EJD.EmployeeId = EM.Id
		INNER JOIN #TempEmployeeId Temp ON Temp.EmployeeId = EJD.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EJD.OrgId 
		INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId  AND (OGDM.Code = '01' OR OGDM.Code = '04')
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
		WHERE EM.StatusId = 7
	    AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
	    AND ((OM.OrgGroupId=@rOrgGroupId ) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0 
	   
	    ORDER BY   EM.Code
	END
	
	IF @rIsSearchHierarchyWise = 2
	BEGIN
		SELECT EM.Id  AS EmployeeId,EM.Code AS EmployeeCode, EM.FirstName +' '+ EM.LastName AS EmployeeName,EI.EmployeePhoto
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD On EJD.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EJD.OrgId 
		INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code= '01' OR OGDM.Code =  '04')
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
		WHERE EM.StatusId = 7
		AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
	    AND ((OM.OrgGroupId=@rOrgGroupId ) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0 
	    
	    ORDER BY   EM.Code
	END
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pEmployeeManagerGet]
	@rOrgId smallint=0,
	@rEmployeeId bigint =0
AS
SET NOCOUNT ON
BEGIN 


    IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='#TempEmployeeId')
	BEGIN		
		DROP Table #TempEmployeeId
	END
	
	CREATE TABLE #TempEmployeeId
	(
		EmployeeId bigint
	)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeManagerId
			-- EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE  ((EmployeeID = @rEmployeeId) OR (@rEmployeeId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
			-- AND EM.FirstName like '%'+@rEmpName+'%'
			 	
			 UNION ALL

			 SELECT
			  E.EmployeeManagerId
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeManagerId = E.EmployeeId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.* FROM EmployeeCTE E
   
   END
 
		SELECT 
		EM.Id AS EmployeeId ,EM.FirstName +' ' +EM.LastName  AS EmployeeName
	FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN #TempEmployeeId TE ON TE.EmployeeId = EM.Id AND ISNULL(EM.IsOtherUser,0) = 0 

		DROP Table #TempEmployeeId
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pEmployeeStatusFollowupSummaryGet]
	 @rLeadOwnerEmployeeId bigint=0,
	@rFromDate DATETIME=null ,
	@rToDate DATETIME=null,
	@rType nvarchar(20)='FollowupCount',
	@rLeadStatusId int=0
	--@rEmployeeManagerId bigint = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
If @rFromDate IS Null Set @rFromDate = ''
  If @rToDate IS Null Set @rToDate = ''
	
		if(@rType = 'FollowupCount')
			BEGIN
				DECLARE  @lTemp Table( LeadStatusId int,  LeadStatusTitle nvarchar(50),  LeadCount int)
				INSERT INTO @lTemp(LeadStatusId,LeadStatusTitle,LeadCount)
				SELECT LSM.Id AS LeadStatusId,LSM.Title AS LeadStatusTitle,COUNT(*) AS LeadCount FROM sErp.tLeadFollowup LF		
						INNER JOIN sErp.tLeadStatusMaster  LSM	ON LSM.Id = LF.LeadStatusId
					WHERE  ((LF.FollowupEmployeeId=@rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId=0))
						--AND LF.FollowupTypeId =1 
						AND (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
						AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY LSM.Id,LSM.Title
					 
					UNION ALL
					
			     SELECT 110  AS LeadStatusId,'Repeat Count' AS LeadStatusTitle, ISNULL(Sum(A.LeadCount),0) AS LeadCount
			     FROM
			     (		SELECT 110  AS LeadStatusId,'Repeat Count' AS LeadStatusTitle,
			          count(Id) AS LeadCount 
					FROM sErp.tLeadFollowup LF		
						WHERE  ((LF.FollowupEmployeeId=@rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId=0))
							AND LF.FollowupTypeId =1 AND (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
							AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate=''))
						GROUP BY LeadId 
					HAVING COUNT(LF.LeadId) >1) A
						
				Select * from @lTemp
			END
		ELSE IF (@rType ='FollowupDetails')
			BEGIN
				SELECT LM.Title AS LeadName,LM.AreaName AS AreaName 
				FROM sErp.tLeadFollowup LF
				INNER JOIN sErp.tLeadMaster LM	 ON LM.Id = LF.LeadId
				INNER JOIN sErp.tLeadStatusMaster  LSM	ON LSM.Id = LF.LeadStatusId
				WHERE  ((LF.FollowupEmployeeId=@rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId=0))
				AND(( LSM.Id = @rLeadStatusId)OR (@rLeadStatusId=0))
				 AND (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
				AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate=''))
			END
	
			
--Select LeadStatusId,LeadStatusTitle,LeadCount  from @lTemp
--	GROUP BY LeadStatusId,LeadStatusTitle,LeadCount 		
		
			--SELECT LSM.Id AS LeadStatusId,LSM.Title AS LeadStatusTitle,COUNT(T.LeadStatusId) AS LeadCount,
			--	ISNULL(T.EmployeeId,0) AS EmployeeId,ISNULL(T.EmployeeName,'') AS EmployeeName
			--	FROM sErp.tLeadStatusMaster  LSM
			--	LEFT JOIN (
			--	SELECT ISNULL(LF.LeadStatusId,0)AS LeadStatusId ,EM.Id AS EmployeeId,EM.FirstName + SPACE(1) + EM.LastName AS EmployeeName FROM sErp.tLeadFollowup LF
			--	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LF.FollowupEmployeeId
			--	WHERE EM.StatusId =7 AND ((FollowupEmployeeId=@rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId=0))
			--	AND (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
			--			AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate='')) )T
			--	ON T.LeadStatusId = LSM.Id
			--	GROUP BY LSM.Id,LSM.Title,T.EmployeeId,T.EmployeeName, LSM.OrderIndex
			--	HAVING COUNT(T.LeadStatusId) > 0
			--UNION ALL
			
			--SELECT 110 AS LeadStatusId,
			--	'Repeat Count' AS LeadStatusTitle,
			--	(SELECT COUNT(*) FROM sErp.tLeadFollowup LF			
			--	WHERE  ((LF.FollowupEmployeeId=@rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId=0))
			--	AND LF.FollowupTypeId =1 AND (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
			--	AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate=''))
			--	--AND ( SELECt LeadId from sErp.tLeadFollowup   having COUNT(LF.LeadId) > 1 )
			--	HAVING COUNT(LF.LeadId) >1 
			--	) AS LeadCount,
			--	ISNULL(T.EmployeeId,0) AS EmployeeId,
			--	ISNULL(T.EmployeeName,'') AS EmployeeName
			--	FROM sErp.tLeadStatusMaster  LSM
			--	LEFT JOIN (
			--	SELECT ISNULL(LF.LeadStatusId,0)AS LeadStatusId ,EM.Id AS EmployeeId,EM.FirstName + SPACE(1) + EM.LastName AS EmployeeName FROM sErp.tLeadFollowup LF
			--	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LF.FollowupEmployeeId
			--	WHERE EM.StatusId =7 AND ((FollowupEmployeeId=@rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId=0))
			--	AND (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
			--	AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate='')) )T
			--	ON T.LeadStatusId = LSM.Id
			--	GROUP BY LSM.Id,LSM.Title,T.EmployeeId,T.EmployeeName, LSM.OrderIndex
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pEmployeeStatusSummaryGet]
	 @rLeadOwnerEmployeeId bigint=0,
	@rOrgId smallint=0,
	@rType nvarchar(20)='',
	@rIsSearchHierarchyWise smallint = 0
	--@rEmployeeManagerId bigint = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='#TempEmployeeId')
	BEGIN		
		DROP Table #TempEmployeeId
	END
	
	CREATE TABLE #TempEmployeeId
	(
		EmployeeId bigint
	)
	
	IF(@rIsSearchHierarchyWise = 0)
	BEGIN
		 INSERT INTO #TempEmployeeId(EmployeeId)
         SELECT
		 EJD.EmployeeID
		 FROM sHrm.tEmployeeJobDetail EJD
		 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		 WHERE ((EmployeeManagerId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
	END
	
	IF(@rIsSearchHierarchyWise = 1)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
			 	
			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E
    END
    
    IF(@rIsSearchHierarchyWise = 2)
    BEGIN
		INSERT INTO #TempEmployeeId(EmployeeId)
		SELECT EJD.EmployeeId FROM sHrm.tEmployeeJobDetail EJD 
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
    END
	IF(@rType = 'WithoutEmployee')
		BEGIN
			DECLARE @cols NVARCHAR(MAX),@query  NVARCHAR(MAX),@col1s NVARCHAR(MAX);
					SET @cols = STUFF((SELECT ',ISNULL([' +  (Title) + '],0)as [' +  (Title)+ ']'
						FROM sErp.tLeadStatusMaster
						ORDER BY OrderIndex
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
			        
					SET @col1s = STUFF((SELECT ',' +  QUOTENAME(Title)
						FROM sErp.tLeadStatusMaster
						ORDER BY OrderIndex
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					print @col1s
					--return
			set @query = 'SELECT EmployeeId,EmployeeName,EmployeeCode,TotalCount, ' + @cols + ' from 
						(
			  SELECT EM.Id AS EmployeeId,EM.FirstName + SPACE(1) + EM.LastName AS EmployeeName,EM.Code AS EmployeeCode,COUNT(T.LeadStatusCount)AS TotalCount,T.LeadStatusTitle AS LeadStatusTitle,ISNULL(T.LeadStatusCount,0) AS LeadStatusCount
			  FROM sErp.tLeadMaster LM
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LM.LeadOwnerEmployeeId
		 	  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			  INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.Id
			  LEFT JOIN
			 (SELECT LM.LeadOwnerEmployeeId AS LeadOwnerEmployeeId,COUNT(LSM.Id) AS LeadStatusCount,LSM.Title AS LeadStatusTitle FROM sErp.tLeadStatusMaster LSM
			  INNER JOIN sErp.tLeadMaster LM ON LSM.Id = LM.LeadStatusId
			  GROUP BY LM.LeadOwnerEmployeeId,LSM.Title ) T ON T.LeadOwnerEmployeeId = LM.LeadOwnerEmployeeId  
			  WHERE  EM.StatusId =7 AND ISNULL(EM.IsOtherUser,0) = 0 
			  GROUP BY EM.Id,EM.FirstName,EM.LastName,EM.Code,T.LeadStatusTitle,T.LeadStatusCount
					   ) x
						pivot 
						(
							SUM(LeadStatusCount)
							for LeadStatusTitle in (' + @col1s + ')
						) p '       
			EXECUTE (@query)
		END
	ELSE IF (@rType = 'WithEmployee')
		BEGIN
					SELECT LSM.Id AS LeadStatusId,LSM.Title AS LeadStatusTitle,COUNT(T.LeadStatusId) AS LeadCount,ISNULL(T.EmployeeId,0) AS EmployeeId,ISNULL(T.EmployeeName,'') AS EmployeeName
			FROM sErp.tLeadStatusMaster  LSM
			LEFT JOIN (
			SELECT LeadStatusId,EM.Id AS EmployeeId,EM.FirstName + SPACE(1) + EM.LastName AS EmployeeName FROM sErp.tLeadMaster LM
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LM.LeadOwnerEmployeeId
			INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			WHERE EM.StatusId =7 AND ISNULL(EM.IsOtherUser,0) = 0  AND ((LeadOwnerEmployeeId=@rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId=0)) )T
			ON T.LeadStatusId = LSM.Id
			GROUP BY LSM.Id,LSM.Title,T.EmployeeId,T.EmployeeName, LSM.OrderIndex
			HAVING COUNT(T.LeadStatusId) > 0
			ORDER BY LSM.OrderIndex
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pFollowupSummaryGet]
	--@rEmployeeId   BIGINT = 0, 
	@rFromDate DATETIME=null ,
	@rToDate DATETIME=null ,
	@rOrgId smallint=0,
	@rType nvarchar(20)='',
	@rIsSearchHierarchyWise smallint = 0,
	@rEmployeeManagerId bigint = 0
AS 
    SET nocount ON 

  BEGIN 
 -- If @rEmployeeId IS Null Set @rEmployeeId = 0
  If @rFromDate IS Null Set @rFromDate = ''
  If @rToDate IS Null Set @rToDate = ''
  IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='#TempEmployeeId')
	BEGIN		
		DROP Table #TempEmployeeId
	END
	
	CREATE TABLE #TempEmployeeId
	(
		EmployeeId bigint
	)
	
	IF(@rIsSearchHierarchyWise = 0)
	BEGIN
		 INSERT INTO #TempEmployeeId(EmployeeId)
         SELECT
		 EJD.EmployeeID
		 FROM sHrm.tEmployeeJobDetail EJD
		 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		 WHERE ((EmployeeManagerId = @rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
	END
	
	IF(@rIsSearchHierarchyWise = 1)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
			 	
			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E
    END
    
    IF(@rIsSearchHierarchyWise = 2)
    BEGIN
		INSERT INTO #TempEmployeeId(EmployeeId)
		SELECT EJD.EmployeeId FROM sHrm.tEmployeeJobDetail EJD 
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
    END
    
	IF(@rType = 'WithoutEmployee')
		BEGIN
			SELECT EM.Id AS EmployeeId,EM.FirstName +' '+ EM.LastName AS EmployeeName,ISNULL(T.CallCount,0)AS CallCount,
			ISNULL(T1.FollowupCount,0)AS FollowupCount,ISNULL(T2.PhysicalCount ,0)AS PhysicalCount,ISNULL(T3.MailCount,0)AS MailCount
			FROM sHrm.tEmployeeMaster EM
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND ISNULL(EM.IsOtherUser,0) = 0 
				INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.Id
			LEFT JOIN (
			SELECT COUNT(*)AS CallCount,LF.FollowupEmployeeId  FROM sErp.tLeadFollowup LF
			WHERE (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
			AND LF.FollowupTypeId=2  
			AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate=''))
			GROUP BY FollowupEmployeeId) T ON T.FollowupEmployeeId = EM.Id
			LEFT JOIN (
			SELECT COUNT(*)AS FollowupCount,FollowupEmployeeId FROM sErp.tLeadFollowup
			WHERE (( convert(DATE, FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
			AND (( convert(DATE, FollowupDate,102) <= @rToDate) OR (@rToDate=''))
			GROUP BY  FollowupEmployeeId)T1 ON T1.FollowupEmployeeId = EM.Id
			LEFT JOIN(
			SELECT COUNT(*)AS PhysicalCount,LF.FollowupEmployeeId  FROM sErp.tLeadFollowup LF
			WHERE (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
			AND LF.FollowupTypeId=1  
			AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate=''))
			GROUP BY  FollowupEmployeeId)T2 ON T2.FollowupEmployeeId = EM.Id
			LEFT JOIN (
			SELECT COUNT(*)AS MailCount,LF.FollowupEmployeeId  FROM sErp.tLeadFollowup LF
			WHERE (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
			AND LF.FollowupTypeId=3  
			AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate=''))
			GROUP BY FollowupEmployeeId) T3 ON T3.FollowupEmployeeId = EM.Id
			GROUP BY  EM.Id,EM.FirstName,EM.LastName,T.CallCount,T1.FollowupCount,T2.PhysicalCount,T3.MailCount
		END
	ELSE IF (@rType = 'WithEmployee')
		BEGIN
			SELECT LM.Title AS LeadTitle,ISNULL(T.CallCount,0)AS CallCount,ISNULL(T1.FollowupCount,0)AS FollowupCount,
			ISNULL(T2.PhysicalCount ,0)AS PhysicalCount,ISNULL(T3.MailCount ,0)AS MailCount
				FROM sErp.tLeadMaster LM
				LEFT JOIN(
					SELECT COUNT(*) AS CallCount,LF.LeadId 
					FROM  sErp.tLeadFollowup LF
					WHERE((LF.FollowupEmployeeId=@rEmployeeManagerId)OR(@rEmployeeManagerId=0)) AND LF.FollowupTypeId=2 
					AND (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY LeadId
				)T ON T.LeadId = LM.Id
				LEFT JOIN
				(
					SELECT COUNT(*)AS FollowupCount,LeadId FROM sErp.tLeadFollowup
					WHERE ((FollowupEmployeeId=@rEmployeeManagerId)OR(@rEmployeeManagerId=0))
					AND (( convert(DATE, FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, FollowupDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY  LeadId
				)T1 ON T1.LeadId = LM.Id
				LEFT JOIN
				(
					SELECT COUNT(*)AS PhysicalCount,LeadId  FROM sErp.tLeadFollowup LF
					WHERE((FollowupEmployeeId=@rEmployeeManagerId)OR(@rEmployeeManagerId=0))AND LF.FollowupTypeId=1 
					AND (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY  LeadId
				)T2 ON T2.LeadId=LM.Id
				LEFT JOIN
				(
					SELECT COUNT(*)AS MailCount,LeadId  FROM sErp.tLeadFollowup LF
					WHERE((FollowupEmployeeId=@rEmployeeManagerId)OR(@rEmployeeManagerId=0)) AND LF.FollowupTypeId=3 
					AND (( convert(DATE, LF.FollowupDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, LF.FollowupDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY  LeadId
				)T3 ON T3.LeadId=LM.Id
				--WHERE LM.LeadOwnerEmployeeId = @rEmployeeManagerId
		END
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pImportLeadMasterAdd]
	(	
		@rStrXml nvarchar(MAX),
		@rOrgId int,
		@rUserId bigint 
	)
AS

SET NOCOUNT ON

BEGIN

SET @rStrXml=REPLACE(@rStrXml,'&','AND') 
DECLARE @lInterrorCode INT,	@intDoc INT
DECLARE @lNextNumber BIGINT
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml
	 
	-- Lead Master Temp Table
	CREATE TABLE #TempLeadMaster
	(
		[AutoId] int identity,
		[OrgId] [smallint] NULL,
		[LeadAffiliationId] [smallint] NULL,
		[Title] [nvarchar](200) NOT NULL,
		[StreetDetail] [nvarchar](300) NULL,
		[AreaName] [nvarchar](100) NULL,
		[CityName] [nvarchar](100) NULL,
		[StateId] [int] NULL,
		[CountryId] [int] NULL,
		[ZipCode] [nvarchar](20) NULL,
		[ContactPerson] [nvarchar](100) NULL,
		[ContactMobileNo] [nvarchar](50) NULL,
		[ContactDesignation] [nvarchar](100) NULL,
		[ContactEmail] [nvarchar](100) NULL,
		[LeadStatusId] [tinyint] NULL,
		[LeadSourceId] [tinyint] NULL,
		[LeadOwnerEmployeeId] [bigint] NULL,
		[NextFollowupDate] [date] NULL,
		[NextFollowupRemark] [nvarchar](max) NULL,
		[district] [nvarchar](50) NULL,
		[ContactPerson2] [nvarchar](100) NULL,
		[ContactMobileNo2] [nvarchar](50) NULL,
		[ContactDesignation2] [nvarchar](100) NULL,
		[ContactEmail2] [nvarchar](100) NULL,
		[ContactPerson3] [nvarchar](100) NULL,
		[ContactMobileNo3] [nvarchar](50) NULL,
		[ContactDesignation3] [nvarchar](100) NULL,
		[ContactEmail3] [nvarchar](100) NULL,
		[ContactPerson4] [nvarchar](100) NULL,
		[ContactMobileNo4] [nvarchar](50) NULL,
		[ContactDesignation4] [nvarchar](100) NULL,
		[ContactEmail4] [nvarchar](100) NULL,
		[ContactPerson5] [nvarchar](100) NULL,
		[ContactMobileNo5] [nvarchar](50) NULL,
		[ContactDesignation5] [nvarchar](100) NULL,
		[ContactEmail5] [nvarchar](100) NULL,
		[LeadDate] [date] NULL,
		[LatitudeAxis] [nvarchar](20) NULL,
		[LongitudeAxis] [nvarchar](20) NULL
	)
	
	INSERT INTO #TempLeadMaster 
	SELECT @rOrgId,* FROM OPENXML (@intDoc, '/Table/Import', 1)
	WITH(
			LeadAffiliationId int '@LeadAffiliationId',
			Title nvarchar(200) '@Title',
			StreetDetail nvarchar(300) '@StreetDetail',
			AreaName nvarchar(100) '@Area',
			CityName nvarchar(100) '@City',
			StateId int '@StateId',
			CountryId int '@CountryId',
			ZipCode nvarchar(20) '@ZipCode',
			ContactPerson nvarchar(100) '@ContactPerson1',
			ContactMobileNo nvarchar(50) '@ContactMobileNo1',
			ContactDesignation nvarchar(100) '@ContactDesignation1',
			ContactEmail   nvarchar(100) '@ContactEmail1',
			LeadStatusId smallint '@LeadStatusId',
			LeadSourceId smallint '@LeadSourceId',
			LeadOwnerEmployeeId bigint '@LeadOwnerEmployeeId',
			NextFollowUpDate date '@NextFollowUpDate',
			NextFollowupRemark nvarchar(200) '@NextFollowupRemark',
			district nvarchar(100) '@district',
			ContactPerson2 nvarchar(100) '@ContactPerson2',
			ContactMobileNo2 nvarchar(50) '@ContactMobileNo2',
			ContactDesignation2 nvarchar(100) '@ContactDesignation2',
			ContactEmail2   nvarchar(100) '@ContactEmail2',
			ContactPerson3 nvarchar(100) '@ContactPerson3',
			ContactMobileNo3 nvarchar(50) '@ContactMobileNo3',
			ContactDesignation3 nvarchar(100) '@ContactDesignation3',
			ContactEmail3   nvarchar(100) '@ContactEmail3',
			ContactPerson4 nvarchar(100) '@ContactPerson4',
			ContactMobileNo4 nvarchar(50) '@ContactMobileNo4',
			ContactDesignation4 nvarchar(100) '@ContactDesignation4',
			ContactEmail4   nvarchar(100) '@ContactEmail4',
			ContactPerson5 nvarchar(100) '@ContactPerson5',
			ContactMobileNo5 nvarchar(50) '@ContactMobileNo5',
			ContactDesignation5 nvarchar(100) '@ContactDesignation5',
			ContactEmail5   nvarchar(100) '@ContactEmail5',
			LeadDate date '@LeadDate',
			LatitudeAxis  nvarchar(20) '@LatitudeAxis',
			LongitudeAxis  nvarchar(20) '@LongitudeAxis'
		)
		
		
		DECLARE @lTempLeadCount int
		SELECT @lTempLeadCount = COUNT(AutoId) FROM #TempLeadMaster
		WHILE (@lTempLeadCount > 0)
		BEGIN
			
			 
		
			 DECLARE @lTitle nvarchar(200)
			 DECLARE @lContactPerson nvarchar(100)
			 DECLARE @lAreaName nvarchar(100)
			 
			 SELECT @lTitle=Title,@lAreaName=AreaName FROM #TempLeadMaster WHERE AutoId = @lTempLeadCount
			 IF NOT EXISTS (SELECT 1 FROM sErp.tLeadMaster WHERE Title=@lTitle AND AreaName=@lAreaName)
			 BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tLeadMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				
				INSERT INTO sErp.tLeadMaster
				(
					Id,
					OrgId,
					LeadDate,
					LeadOwnerEmployeeId,
					Title,
					LeadAffiliationId,
					StreetDetail,
					AreaName,
					CityName,
					district,
					StateId,
					CountryId,
					ContactPerson,
					ContactDesignation ,
					ContactMobileNo ,
					ContactEmail ,
					ContactPerson2,
					ContactDesignation2,
					ContactMobileNo2,
					ContactEmail2,
					LeadSourceId,
					LeadStatusId,
					NextFollowupDate,
					NextFollowupRemark,
					ZipCode,
					ContactPerson3,
					ContactDesignation3,
					ContactMobileNo3,
					ContactEmail3,
					ContactPerson4,
					ContactDesignation4,
					ContactMobileNo4,
					ContactEmail4,
					ContactPerson5,
					ContactDesignation5,
					ContactMobileNo5,
					ContactEmail5,
					LatitudeAxis,
					LongitudeAxis,
					CreatedUserId,
					CreatedDateTime
				) 
				SELECT
					@lNextNumber,
					@rOrgId,
					LeadDate,
					LeadOwnerEmployeeId,
					sSetup.fPortalXMLTagsReplaceReverse(Title) AS Title,		
					LeadAffiliationId,
					sSetup.fPortalXMLTagsReplaceReverse(StreetDetail) AS StreetDetail ,
					sSetup.fPortalXMLTagsReplaceReverse(AreaName) AS AreaName,
					sSetup.fPortalXMLTagsReplaceReverse(CityName) AS CityName,
					sSetup.fPortalXMLTagsReplaceReverse(district) AS district,
					StateId,
					CountryId,
					sSetup.fPortalXMLTagsReplaceReverse(ContactPerson) AS ContactPerson,
					sSetup.fPortalXMLTagsReplaceReverse(ContactDesignation) AS ContactDesignation,
					sSetup.fPortalXMLTagsReplaceReverse( ContactMobileNo) AS ContactMobileNo1,
					sSetup.fPortalXMLTagsReplaceReverse(ContactEmail) AS ContactEmail1,
					sSetup.fPortalXMLTagsReplaceReverse(ContactPerson2) AS ContactPerson2,
					sSetup.fPortalXMLTagsReplaceReverse(ContactDesignation2)AS ContactDesignation2,
					sSetup.fPortalXMLTagsReplaceReverse(ContactMobileNo2)AS ContactMobileNo2,
					sSetup.fPortalXMLTagsReplaceReverse(ContactEmail2)AS ContactEmail2,
					LeadSourceId, 
					LeadStatusId,
					NULLIF(NextFollowUpDate,'') AS NextFollowUpDate,
					sSetup.fPortalXMLTagsReplaceReverse(NextFollowupRemark)AS NextFollowupRemark,
					sSetup.fPortalXMLTagsReplaceReverse(ZipCode) AS ZipCode,
					sSetup.fPortalXMLTagsReplaceReverse(ContactPerson3)AS ContactPerson3,
					sSetup.fPortalXMLTagsReplaceReverse(ContactDesignation3) AS ContactDesignation3,
					sSetup.fPortalXMLTagsReplaceReverse(ContactDesignation4) AS ContactMobileNo3,
					sSetup.fPortalXMLTagsReplaceReverse(ContactEmail3) AS ContactEmail3,
					sSetup.fPortalXMLTagsReplaceReverse(ContactPerson4) AS ContactPerson4,
					sSetup.fPortalXMLTagsReplaceReverse(ContactDesignation4) AS ContactDesignation4,
					sSetup.fPortalXMLTagsReplaceReverse(ContactMobileNo4) AS ContactMobileNo4,
					sSetup.fPortalXMLTagsReplaceReverse( ContactEmail4) ASContactEmail4,
					sSetup.fPortalXMLTagsReplaceReverse( ContactPerson5) AS ContactPerson5,
					sSetup.fPortalXMLTagsReplaceReverse(ContactDesignation5)AS  ContactDesignation5,
					sSetup.fPortalXMLTagsReplaceReverse(ContactMobileNo5)AS ContactMobileNo5,
					sSetup.fPortalXMLTagsReplaceReverse(ContactEmail5) AS ContactEmail5,
					sSetup.fPortalXMLTagsReplaceReverse(LatitudeAxis) AS LatitudeAxis,
					sSetup.fPortalXMLTagsReplaceReverse(LongitudeAxis) AS LongitudeAxis,
					@rUserId AS UserId,
					sCommon.fGetDate()
					FROM #TempLeadMaster WHERE AutoId = @lTempLeadCount
					
					
					DECLARE @lNextNumberFollowup BIGINT
					DECLARE @lLastNumberFollowup BIGINT
					DECLARE @lCount1 INT
					
					EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tLeadFollowup', 0, 1, 1,@outNextNumber = @lNextNumberFollowup output
					INSERT INTO sErp.tLeadFollowup(Id,LeadId,FollowupDate,FollowupRemark,FollowupEmployeeId,CreatedUserId,CreatedDateTime)
					SELECT   
						@lNextNumberFollowup,
						@lNextNumber,
						NULLIF(NextFollowupDate,'') AS NextFollowupDate,
						NextFollowupRemark,
						LeadOwnerEmployeeId,
						@rUserId AS UserId,
						sCommon.fGetDate() AS CreateDate 
					FROM 
						sErp.tLeadMaster 
					WHERE 
						Id = @lNextNumber
			 END
			 ELSE
			 BEGIN
					DECLARE @lLeadId bigint=0
					SELECT @lLeadId=Id FROM sErp.tLeadMaster WHERE Title = @lTitle AND AreaName = @lAreaName
					
					UPDATE LM
					SET
						LeadDate=TLM.LeadDate,
						LeadOwnerEmployeeId=TLM.LeadOwnerEmployeeId,
						Title=sSetup.fPortalXMLTagsReplaceReverse(TLM.Title),
						LeadAffiliationId=TLM.LeadAffiliationId,
						StreetDetail=sSetup.fPortalXMLTagsReplaceReverse(TLM.StreetDetail),
						AreaName=sSetup.fPortalXMLTagsReplaceReverse(TLM.AreaName),
						CityName=sSetup.fPortalXMLTagsReplaceReverse(TLM.CityName),
						district=sSetup.fPortalXMLTagsReplaceReverse(TLM.district),
						StateId=TLM.StateId,
						CountryId=TLM.CountryId,
						ContactPerson=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactPerson),
						ContactDesignation=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactDesignation) ,
						ContactMobileNo =sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactMobileNo),
						ContactEmail =sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactEmail),
						ContactPerson2=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactPerson2),
						ContactDesignation2=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactDesignation2),
						ContactMobileNo2=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactMobileNo2),
						ContactEmail2=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactEmail2),
						LeadSourceId=TLM.LeadSourceId,
						LeadStatusId=TLM.LeadStatusId,
						NextFollowupDate=TLM.NextFollowupDate,
						NextFollowupRemark=sSetup.fPortalXMLTagsReplaceReverse(TLM.NextFollowupRemark),
						ZipCode=TLM.ZipCode,
						ContactPerson3=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactPerson3),
						ContactDesignation3=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactDesignation3),
						ContactMobileNo3=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactMobileNo3),
						ContactEmail3=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactEmail3),
						ContactPerson4=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactPerson4),
						ContactDesignation4=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactDesignation4),
						ContactMobileNo4=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactMobileNo4),
						ContactEmail4=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactEmail4),
						ContactPerson5=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactPerson5),
						ContactDesignation5=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactDesignation5),
						ContactMobileNo5=sSetup.fPortalXMLTagsReplaceReverse(TLM.ContactMobileNo5),
						ContactEmail5=sSetup.fPortalXMLTagsReplaceReverse(LM.ContactEmail5),
						LatitudeAxis = sSetup.fPortalXMLTagsReplaceReverse(LM.LatitudeAxis),
						LongitudeAxis = sSetup.fPortalXMLTagsReplaceReverse(LM.LongitudeAxis),
						UpdatedUserId = @rUserId, 
						UpdatedDateTime = sCommon.fGetDate()
					FROM
						 sErp.tLeadMaster LM 
						 INNER JOIN #TempLeadMaster TLM ON TLM.Title COLLATE DATABASE_DEFAULT = LM.Title COLLATE DATABASE_DEFAULT AND TLM.ContactPerson COLLATE DATABASE_DEFAULT = LM.ContactPerson COLLATE DATABASE_DEFAULT
					WHERE LM.Id = @lLeadId
					
					UPDATE LF
					SET
						LF.FollowupDate= L.NextFollowupDate,
						LF.FollowupRemark = L.NextFollowupRemark,
						LF.FollowupEmployeeId =  L.LeadOwnerEmployeeId
					FROM sErp.tLeadMaster L
					INNER JOIN sErp.tLeadFollowup LF ON L.Id = LF.LeadId 
					WHERE LF.LeadId = @lLeadId
			 END
			 SET @lTempLeadCount = @lTempLeadCount -1
		END 
	  
	   SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sErp].[pLeadFollowup_Get]
	
	
	 @rId bigint = 0,
	 @rFromDate date='',
	 @rToDate date='',
	 @rOrgId Smallint=0,	
	 @rLeadId int=0,
	 @rEmployeeId bigint=0,
	 @rFollowupTypeId Smallint=0,
	 @rLeadStatusId smallint=0,
	 @rManagerFlag smallint =0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
	ISNULL(LF.Id,'') AS Id,
	LF.LeadId,
	ISNULL(LF.FollowupDate,'') AS  FollowupDate,
	ISNULL(LF.FollowupRemark,'') AS FollowupRemark,
	ISNULL(LF.FollowupEmployeeId,0) AS FollowupEmployeeId,
	ISNULL(LM.Title,'') AS Lead,
	ISNULl( LM.StateId,0) AS StateId,
	ISNULL(LF.FollowupNextDate,'0001/01/01') AS NextFollowupDate,
	LM.OrgId,
	OM.DisplayTitle AS OrgName,
	EM.FirstName +' '+ MiddleName +' '+ LastName AS EmployeeName,
	ISNULL(LM.ContactPerson,'') AS ContactPerson,
	ISNULL(LM.ContactMobileNo,'')AS ContactMobileNo,
	ISNULL(LM.MobileNo,'') AS MobileNo,
	LM.ContactEmail,
	ISNULL(LF.LeadStatusId,0) AS LeadStatusId,
	LSM.Title,
	ISNULL(LF.IsPhysical,'False') AS IsPhysical,
	ISNULL(LF.LatitudeAxis,'') AS LatitudeAxis,
	ISNULL(LF.LongitudeAxis,'')AS LongitudeAxis,
	ISNULL(FTM.Title,'') AS FollowupType,
	ISNULL(LF.FollowupTypeId,0) AS FollowupTypeId,
	LF.CreatedDateTime,
	ISNULL(LM.CityName,'') AS CityName,
	ISNULL(LF.FollowupLocation,'') AS FollowupLocation,
	ISNULL(LF.NonEffective,0) AS NonEffective,
	ISNULL(LF.WithManagerEmployeeId,0)As WithManagerEmployeeId

  FROM 
	sErp.tLeadMaster LM
    INNER JOIN  sErp.tLeadFollowup LF ON LM.Id=LF.LeadId  AND ((LM.OrgId=@rOrgId) OR (@rOrgId=0))
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LM.OrgId
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LF.FollowupEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
	INNER JOIN sErp.tLeadStatusMaster LSM ON LSM.Id = LF.LeadStatusId
	INNER JOIN sErp.tFollowupTypeMaster FTM ON FTM.Id = LF.FollowupTypeId
  WHERE  
     ((LF.Id = @rId) OR (@rId = 0))
      AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	  AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))	
	  AND ((LM.Id = @rLeadId) OR (@rLeadId = 0))
	  AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	  AND((LF.FollowupTypeId = @rFollowupTypeId)OR(@rFollowupTypeId=0))
	  AND((LF.LeadStatusId = @rLeadStatusId)OR(@rLeadStatusId=0))	
	  AND ((ISNULL(LF.WithManagerEmployeeId,0) > 100 AND @rManagerFlag = 1) OR (@rManagerFlag in (0,2) ))
	  AND ((LF.WithManagerEmployeeId <> LM.LeadOwnerEmployeeId AND @rManagerFlag = 2 AND ISNULL(LF.WithManagerEmployeeId,0) > 100) OR (@rManagerFlag in (0,1)))
	 -- AND  ((( (ISNULL(LF.WithManagerEmployeeId,0) > 100) OR (LF.WithManagerEmployeeId <> LM.LeadOwnerEmployeeId AND ISNULL(LF.WithManagerEmployeeId,0) > 100 ) ) AND (@rManagerFlag = 0)) OR  (@rManagerFlag in (1,2)) )
	  Order by LF.FollowupDate desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sErp].[pLeadFollowupAdd]
		@rId	bigint,	
		@rLeadId int,
		@rFollowupDate	date,
		@rFollowupRemark	nvarchar(max),
		@rFollowupEmployeeId bigint,							
		@rCreatedUserId	bigint,
		@rOrgId smallint,
		@statusId int,
		@rNextFollowupDate date='',
		@rIsPhysical bit=0,
		@rLatitudeAxis nvarchar(20)='',
		@rLongitudeAxis nvarchar(20)='',
		@rFollowupType smallint=0,
		@rFollowupLocation nvarchar(200)='',
		@rNonEffective tinyint = 0,
		@rWithManagerEmployeeId bigint = 0,
		@rDisplacement decimal(10,2) =0.00
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN



	DECLARE @lFollowId BIGINT 
	IF Exists(select Id from sErp.tLeadFollowup where LeadId = @rLeadId AND FollowupTypeId=@rFollowupType AND FollowupEmployeeId=@rFollowupEmployeeId   AND CONVERT(date,FollowupDate) =  CONVERT(date,getdate(),102))
				BEGIN
				SELECT @lFollowId = Id from sErp.tLeadFollowup where LeadId = @rLeadId  AND FollowupTypeId=@rFollowupType  AND CONVERT(date,FollowupDate) =  CONVERT(date,getdate(),102)
				IF Exists(select 1  from sErp.tLeadFollowup where LeadId = @rLeadId  AND FollowupTypeId=@rFollowupType  AND CONVERT(date,FollowupDate) =  CONVERT(date,getdate(),102) AND (LatitudeAxis IS NOT NULL OR LongitudeAxis IS NOT NULL ))
					BEGIN
						UPDATE  sErp.tLeadFollowup
						SET
						LeadId=@rLeadId,
						FollowupDate=@rFollowupDate,
						FollowupRemark=@rFollowupRemark,
						FollowupEmployeeId=@rFollowupEmployeeId,
						IsPhysical = @rIsPhysical,
						--LatitudeAxis = @rLatitudeAxis,
						--LongitudeAxis = @rLongitudeAxis,
						FollowupNextDate=@rNextFollowupDate,
						LeadStatusId = @statusId,
						FollowupTypeId=@rFollowupType,
						--FollowupLocation=@rFollowupLocation,
						NonEffective=@rNonEffective, 
						WithManagerEmployeeId = @rWithManagerEmployeeId
						WHERE Id = @lFollowId 	   	
						
							UPDATE  sErp.tLeadMaster
							SET LeadStatusId = @statusId,
							NextFollowupDate=@rNextFollowupDate
							WHERE Id = @rLeadId 

						SELECT @lFollowId AS Result    
						SELECT 11 AS Operation  
						return
					END 
				ELSE 
					BEGIN
						UPDATE  sErp.tLeadFollowup
						SET
						LeadId=@rLeadId,
						FollowupDate=@rFollowupDate,
						FollowupRemark=@rFollowupRemark,
						FollowupEmployeeId=@rFollowupEmployeeId,
						IsPhysical = @rIsPhysical,
						--LatitudeAxis = @rLatitudeAxis,
						--LongitudeAxis = @rLongitudeAxis,
						FollowupNextDate=@rNextFollowupDate,
						LeadStatusId = @statusId,
						FollowupTypeId=@rFollowupType,
						NonEffective=@rNonEffective,
						WithManagerEmployeeId = @rWithManagerEmployeeId
						WHERE Id = @lFollowId 	   	



							UPDATE  sErp.tLeadMaster
							SET LeadStatusId = @statusId,
							NextFollowupDate=@rNextFollowupDate
							WHERE Id = @rLeadId 

						SELECT @lFollowId AS Result    
						SELECT 11 AS Operation  
						return
					END
					
				END
			ELSE
			BEGIN
				IF(@rId = 0)	
					BEGIN
						DECLARE @lNextNumber BIGINT 
						EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tLeadFollowup', 0, 1, 1,@outNextNumber = @lNextNumber output
						INSERT INTO sErp.tLeadFollowup
						(Id,LeadId,FollowupDate,FollowupRemark,FollowupEmployeeId,CreatedUserId,CreatedDateTime,IsPhysical,LatitudeAxis,LongitudeAxis,FollowupNextDate,LeadStatusId,FollowupTypeId,FollowupLocation,NonEffective,WithManagerEmployeeId, Displacement)
						VALUES
						(@lNextNumber,@rLeadId,@rFollowupDate,@rFollowupRemark,@rFollowupEmployeeId,@rCreatedUserId,sCommon.fGetDate(),@rIsPhysical,@rLatitudeAxis,@rLongitudeAxis,@rNextFollowupDate,@statusId,@rFollowupType,	@rFollowupLocation,@rNonEffective, @rWithManagerEmployeeId, @rDisplacement)
						UPDATE sErp.tLeadMaster
						SET LeadStatusId = @statusId,
						NextFollowupDate = @rNextFollowupDate
						WHERE ID =@rLeadId
						SELECT @lNextNumber AS Result    
						SELECT 1 AS Operation     
					END	 
					ELSE
						BEGIN
							SET @lNextNumber = @rId
							UPDATE  sErp.tLeadFollowup
							SET
								LeadId=@rLeadId,
								FollowupDate=@rFollowupDate,
								FollowupRemark=@rFollowupRemark,
								FollowupEmployeeId=@rFollowupEmployeeId,
								IsPhysical = @rIsPhysical,
								--LatitudeAxis = @rLatitudeAxis,
								--LongitudeAxis = @rLongitudeAxis,
								FollowupNextDate=@rNextFollowupDate,
								LeadStatusId = @statusId,
								FollowupTypeId=@rFollowupType,
								--FollowupLocation=@rFollowupLocation,
								NonEffective=@rNonEffective,
								WithManagerEmployeeId=@rWithManagerEmployeeId
							WHERE Id = @rId 	   

							UPDATE  sErp.tLeadMaster
							SET LeadStatusId = @statusId,
							NextFollowupDate=@rNextFollowupDate
							WHERE Id = @rLeadId 	  

							SELECT @rId AS Result 
							SELECT 11 AS Operation
						END  
					END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pLeadFollowupGet]
	
	
	 @rId bigint = 0,
	 @rFromDate date='',
	 @rToDate date='',
	 @rOrgId bigint=0,	
	 @rLeadName nvarchar(200)='',
	 @rEmpId bigint =0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
		LF.Id,
		LF.LeadId,
		ISNULL(LF.FollowupDate,'') AS  FollowupDate,
		LF.FollowupRemark,
		LF.FollowupEmployeeId,
		LM.Title AS Lead,
		ISNULl( LF.LeadStatusId,0) AS StateId,
		ISNULL(LF.FollowupNextDate,'0001/01/01') AS NextFollowupDate,
		LM.OrgId,
		OM.DisplayTitle AS OrgName,
		EM.FirstName +' '+ MiddleName +' '+ LastName AS EmployeeName,
		ISNULL(LF.IsPhysical,'False') AS IsPhysical,
		ISNULL(LF.LatitudeAxis,'') AS LatitudeAxis,
		ISNULL(LF.LongitudeAxis,'')AS LongitudeAxis,
		ISNULL(LM.ContactPerson,'') AS ContactPerson,
		ISNULL(LM.ContactMobileNo,'')AS ContactMobileNo,
		ISNULL(LM.MobileNo,'') AS MobileNo,
		ISNULL(LF.LeadStatusId,0) AS LeadStatusId,
		LM.ContactEmail,
		ISNULL(LF.FollowupTypeId,0) AS FollowupTypeId,
		ISNULL(LF.NonEffective,0) AS NonEffective
	
  FROM 
    sErp.tLeadFollowup LF
    INNER JOIN sErp.tLeadMaster LM ON LM.Id=LF.LeadId  --AND ((LM.OrgId=@rOrgId) OR (@rOrgId=0))
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LM.OrgId
	INNer JOIN sHrm.tEmployeeMaster EM ON EM.Id=LF.FollowupEmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
  WHERE  
      ((LF.Id = @rId) OR (@rId = 0))
      AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	  AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))	
	 -- AND ((LF.Title = @rLeadName) OR (@rLeadId = 0))
	   AND ((LM.Title Like '%'+ @rLeadName+'%')OR(ISNULL(@rLeadName,'') = ''))
	  AND ((LF.FollowupEmployeeId = @rEmpId) OR (@rEmpId = 0))
	  --AND ((LF.LeadId = @rLeadId) OR (@rLeadId = 0))
	  Order by LF.FollowupDate  desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pLeadMasterAdd]
	 @rOrgId smallint,
	 @rId int, 
	 @rLeadAffiliationId smallint,
	 @rTitle nvarchar(200),	
	 @rStreetDetail nvarchar(300),
	 @rAreaName nvarchar(100),
	 @rCityName nvarchar(100),
	 @rStateId int,
	 @rCountryId int,
	 @rVcpId int,
	 @rLeadInfrastructureId int,
	 @rdistrict nvarchar(50),
	 @rZipCode nvarchar(20),
	 @rWebsite nvarchar(100),
	 @rPhoneNo nvarchar(50),
	-- @rMobileNo nvarchar(50) =null,
	 @rContactPerson nvarchar(100),
	 @rContactMobileNo nvarchar(50),
	 @rContactDesignation nvarchar(100),
	 @rLeadStatusId tinyint,
	 @rLeadSourceId tinyint,
	 @rLeadOwnerEmployeeId bigint,
	 @rCreatedUserId bigint, 
	 @rUpdatedUserId bigint ,
	 @rNextFollowupDate date,
	 @rNextFollowupRemark  nvarchar(max),
	-- @rEmail nvarchar(100) =null,
	 @rContactEmail nvarchar(100),
	 @rContactPerson2 nvarchar(100),
	 @rContactMobileNo2 nvarchar(50),
	 @rContactDesignation2 nvarchar(100),
	 @rContactEmail2 nvarchar(100),
	   @rContactPerson3 nvarchar(100),
	 @rContactMobileNo3 nvarchar(50),
	 @rContactDesignation3 nvarchar(100),
	 @rContactEmail3 nvarchar(100),
	   @rContactPerson4 nvarchar(100),
	 @rContactMobileNo4 nvarchar(50),
	 @rContactDesignation4 nvarchar(100),
	 @rContactEmail4 nvarchar(100),
	   @rContactPerson5 nvarchar(100),
	 @rContactMobileNo5 nvarchar(50),
	 @rContactDesignation5 nvarchar(100),
	 @rContactEmail5 nvarchar(100),
	 @rLeadDate date,
	 @rPlannedDate date='',
	 @rLatitudeAxis nvarchar(20)='',
	 @rLongitudeAxis nvarchar(20)=''
	      	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	--IF(@rId = 0)	
	--BEGIN
	--	--If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgId=@rOrgId)
	--	--	BEGIN
	--	--	select -102 as Result
	--	--	RETURN
	--	--END 
	
	--	If Exists(select Id from sErp.tLeadMaster where Title=@rTitle AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sErp.tLeadMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF(@rId = 0)	
BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tLeadMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tLeadMaster
		(
		Id
		,OrgId
		,LeadAffiliationId
		,Title
		,StreetDetail
		,AreaName
		,CityName
		,StateId
		,CountryId
		,ZipCode
		,district
		,Website
		,PhoneNo
		--,MobileNo
		--,Email
		,ContactPerson
		,ContactMobileNo
		,	ContactEmail
		,ContactDesignation
		,LeadStatusId
		,LeadSourceId
		,LeadOwnerEmployeeId
		,CreatedUserId
		,CreatedDateTime
		,UpdatedUserId
		,UpdatedDateTime
		,NextFollowupDate
		,NextFollowupRemark
		,ContactPerson2
		,ContactMobileNo2
		,ContactDesignation2
		,ContactEmail2
		,ContactPerson3
		,ContactMobileNo3
		,ContactDesignation3
		,ContactEmail3
		,ContactPerson4
		,ContactMobileNo4
		,ContactDesignation4
		,ContactEmail4
		,ContactPerson5
		,ContactMobileNo5
		,ContactDesignation5
		,ContactEmail5
		,LeadChannelPartnerId
		,LeadInfrastructureId
		,LeadDate
		,PlannedDate
		,LatitudeAxis
		,LongitudeAxis
		)
	VALUES
		(
		  @lNextNumber
		, @rOrgId 
		, @rLeadAffiliationId
		, @rTitle
		, @rStreetDetail
		, @rAreaName
		, @rCityName
		, @rStateId
		, @rCountryId
		, @rZipCode
		, @rdistrict
		, @rWebsite
		, @rPhoneNo
		--, @rMobileNo
		--, @rEmail
		, @rContactPerson
		, @rContactMobileNo
		, @rContactEmail
		, @rContactDesignation
		, @rLeadStatusId
		, @rLeadSourceId
		, @rLeadOwnerEmployeeId
		, @rCreatedUserId
		, sCommon.fGetDate()
		, @rUpdatedUserId
		, sCommon.fGetDate()
		, @rNextFollowupDate
		, @rNextFollowupRemark
		, @rContactPerson2
		, @rContactMobileNo2
		, @rContactDesignation2
		, @rContactEmail2
		, @rContactPerson3
		, @rContactMobileNo3
		, @rContactDesignation3
		, @rContactEmail3
		, @rContactPerson4
		, @rContactMobileNo4
		, @rContactDesignation4
		, @rContactEmail4
		, @rContactPerson5
		, @rContactMobileNo5
		, @rContactDesignation5
		, @rContactEmail5
		, @rVcpId
		, @rLeadInfrastructureId
		, @rLeadDate
		,@rPlannedDate
		,@rLatitudeAxis
		,@rLongitudeAxis
		
		)
	    SELECT 1 AS Result
	    select @lNextNumber as LeadId
	    
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
		
	    UPDATE  sErp.tLeadMaster
	    SET
	    
		LeadAffiliationId=@rLeadAffiliationId
		,Title=@rTitle
		,StreetDetail=@rStreetDetail
		,AreaName=@rAreaName
		,CityName=@rCityName
		,StateId=@rStateId
		,CountryId=@rCountryId
		,ZipCode=@rZipCode
		,district =@rdistrict
		,Website=@rWebsite
		,PhoneNo=@rPhoneNo
		--,MobileNo=@rMobileNo
		--,EMail=@rEmail
		,ContactPerson=@rContactPerson
		,ContactMobileNo=@rContactMobileNo
		,ContactDesignation=@rContactDesignation
		,ContactEmail = @rContactEmail
		,LeadStatusId=@rLeadStatusId
		,LeadSourceId=@rLeadSourceId
		,LeadOwnerEmployeeId=@rLeadOwnerEmployeeId      
		,UpdatedUserId=@rUpdatedUserId
		,UpdatedDateTime=sCommon.fGetDate()
		,NextFollowupDate=@rNextFollowupDate
		,NextFollowupRemark=@rNextFollowupRemark
		,ContactPerson2=@rContactPerson2
		,ContactMobileNo2=@rContactMobileNo2
		,ContactDesignation2=@rContactDesignation2
		,ContactEmail2 = @rContactEmail2
		,ContactPerson3=@rContactPerson3
		,ContactMobileNo3=@rContactMobileNo3
		,ContactDesignation3=@rContactDesignation3
		,ContactEmail3 = @rContactEmail3
		,ContactPerson4=@rContactPerson4
		,ContactMobileNo4=@rContactMobileNo4
		,ContactDesignation4=@rContactDesignation4
		,ContactEmail4 = @rContactEmail4
		,ContactPerson5=@rContactPerson5
		,ContactMobileNo5=@rContactMobileNo5
		,ContactDesignation5=@rContactDesignation5
		,ContactEmail5 = @rContactEmail5
		,LeadChannelPartnerId = @rVcpId  
		,LeadInfrastructureId = @rLeadInfrastructureId
		,LeadDate=@rLeadDate
		,PlannedDate=@rPlannedDate
		,LatitudeAxis=@rLatitudeAxis
		,LongitudeAxis=@rLongitudeAxis
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pLeadMasterGet]
	
	@rId int=0,
	@rOrgId smallint=0,
	@rLeadAffiliationId smallint =0,
	@rTitle nvarchar(200) =null,
	@rAreaName nvarchar(100) =null,
	@rCityName nvarchar(100) =null,
	@rDistrict nvarchar(50) = null,
	@rStateId int =0,
	@rCountryId int=0,
	@rLeadStatusId tinyint =0,
	@rLeadSourceId tinyint =0,
	@rLeadOwnerEmployeeId bigint =0,
	@rFromDate date='',
	@rToDate date='',
	@rIsWildCardSearch bit=0,
	@rVcpId int =0,
	@rLeadInfrastructureId int =0,
	@rFromLeadDate date =NULL,
	@rToLeadDate date =NULL,
	@rContactPerson nvarchar(100) =NULL,
	@rContactMobileNo nvarchar(50)=NULL,
	@rIsSearchHierarchyWise smallint=0,
	@rPlanFromDate date =NULL,
	@rPlanToDate date =NULL,
	@rEmployeeId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
  If @rFromDate IS Null Set @rFromDate = ''
  If @rToDate IS Null Set @rToDate = ''
  
  If @rFromLeadDate IS Null Set @rFromLeadDate = ''
  If @rToLeadDate IS Null Set @rToLeadDate = ''
  
  If @rPlanFromDate IS Null Set @rPlanFromDate = ''
  If @rPlanToDate IS Null Set @rPlanToDate = ''
    IF @rIsSearchHierarchyWise = 2 Set @rLeadOwnerEmployeeId = 0

	CREATE TABLE #TempEmployeeId
    (
		EmployeeId bigint
    )
    
    IF(@rIsSearchHierarchyWise = 1)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0))
					
					AND ((OrgId = @rOrgId) OR (@rOrgId = 0))

			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E
		WHERE((E.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
    END
    
    ELSE
    BEGIN
		INSERT INTO #TempEmployeeId(EmployeeId)
		SELECT EJD.EmployeeId FROM sHrm.tEmployeeJobDetail EJD 
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		WHERE ((EJD.EmployeeManagerId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0))
			   AND ((OrgId = @rOrgId) OR (@rOrgId = 0))
			   AND((EJD.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
    END

--select * from #TempEmployeeId

	IF @rIsWildCardSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
If	@rIsSearchHierarchyWise = 0
BEGIN
	SELECT 
	      LM.Id,
	      LM.OrgId,
	      ISNULL(LM.LeadAffiliationId,0) As LeadAffiliationId,
	      LAM.Title AS Affiliation,
	      LM.Title,
	      LM.StreetDetail,
	      LM.AreaName,
	      LM.CityName,
	      ISNULl( LM.StateId,0) AS StateId,
	      SM.Title AS StateName,
	      ISNULl(  LM.CountryId,0) AS CountryId,
	      CM.Title AS Country,
	      LM.Website,
	      ISNULl(LM.LeadStatusId,0)AS LeadStatusId ,
	      LSM.Title AS LeadStatus,
	      ISNULL(LM.LeadSourceId,0) As LeadSourceId,
	      LS.Title AS LeadSource,
	      ISNULl(LM.LeadOwnerEmployeeId,0) AS LeadOwnerEmployeeId,
	      EM.FirstName +' '+ MiddleName +' '+ LastName AS LeadOwner,
	      ISNULL(LM.NextFollowupDate,'0001/01/01') AS NextFollowupDate,
	      LM.NextFollowupRemark,
	      LM.ContactPerson,
	      LM.ContactMobileNo,
	      LM.ContactDesignation,
	      LM.ContactEmail,
	      LM.ZipCode,
	      LM.PhoneNo,
	      LM.MobileNo,
	      LM.Email AS EMail,
	      LM.district,
	      LM.ContactPerson2,
	      LM.ContactMobileNo2,
	      LM.ContactDesignation2,
		  LM.ContactEmail2,
		   LM.ContactPerson3,
	      LM.ContactMobileNo3,
	      LM.ContactDesignation3,
		  LM.ContactEmail3,
		  LM.ContactPerson4,
	      LM.ContactMobileNo4,
	      LM.ContactDesignation4,
		  LM.ContactEmail4,
		  LM.ContactPerson5,
	      LM.ContactMobileNo5,
	      LM.ContactDesignation5,
		  LM.ContactEmail5,
		  ISNULL(LM.LeadDate,'0001/01/01') AS LeadDate,
		  ISNULl(LM.LeadChannelPartnerId,0) AS LeadChannelPartnerId,
		  ISNULl(LM.LeadInfrastructureId,0) AS LeadInfrastructureId,
		  LM.StreetDetail++LM.AreaName+' '+LM.CityName+' '+SM.Title+' '+ CM.Title AS Address,
		  LM.CreatedUserId,
		  LM.CreatedDateTime,
		  ISNULL(LM.UpdatedUserId,0) AS UpdatedUserId,
		  ISNULL(LM.UpdatedDateTime,'') AS UpdatedDateTime,
		  ISNULL(LM.PlannedDate,'0001/01/01') AS PlannedDate,
		  ISNULL(LM.LatitudeAxis,0) AS LatitudeAxis,
		  ISNULL(LM.LongitudeAxis,0) AS LongitudeAxis
	FROM 
		  sErp.tLeadMaster LM
		  LEFT JOIN sErp.tLeadAffiliationMaster LAM ON LAM.Id=LM.LeadAffiliationId
		  LEFT JOIN sErp.tLeadSourceMaster LS ON  LS.Id=LM.LeadSourceId
		  LEFT JOIN sErp.tLeadStatusMaster LSM ON LSM.Id=LM.LeadStatusId
		  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LM.LeadOwnerEmployeeId
		  LEFT JOIN sCommon.tCountryMaster CM ON  CM.Id = LM.CountryId
		  LEFT JOIN sCommon.tStateMaster SM ON SM.Id=LM.StateId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		--LEFT JOIN sSecurity.tUser U ON U.SourceId =LM.LeadOwnerEmployeeId AND SourceTypeId = 95
	WHERE 
		  ((LM.Id = @rId) OR (@rId=0))
		  AND((LM.OrgId = @rOrgId) OR(@rOrgId=0))
		  AND ((LM.Title Like '%'+ @rTitle+'%')OR(ISNULL(@rTitle,'') = ''))
		  AND ((LM.AreaName Like '%'+@rAreaName+'%')OR(ISNULL(@rAreaName,'') = ''))
		  AND ((LM.CityName Like '%'+@rCityName+'%')OR(ISNULL(@rCityName,'') = ''))
		  AND	((LM.StateId = @rStateId) OR (@rStateId = 0))
		  AND ((LM.district Like '%'+@rDistrict+'%') OR (ISNULL(@rDistrict,'') = ''))
		  AND	((LM.CountryId = @rCountryId) OR (@rCountryId = 0))
		  AND	((LM.LeadChannelPartnerId = @rVcpId) OR (@rVcpId = 0))
		  AND((LM.LeadInfrastructureId = @rLeadInfrastructureId) OR (@rLeadInfrastructureId =0))
		  AND	((LM.LeadAffiliationId = @rLeadAffiliationId) OR (@rLeadAffiliationId = 0))
		  AND	((LM.LeadStatusId = @rLeadStatusId) OR (@rLeadStatusId = 0))
		  AND	((LM.LeadSourceId = @rLeadSourceId) OR (@rLeadSourceId = 0))
		  AND	((LM.LeadOwnerEmployeeId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0))
		  AND ((LM.NextFollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		  AND ((LM.NextFollowupDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		  AND ((LM.LeadDate >= @rFromLeadDate) OR (ISNULL(@rFromLeadDate,'') = ''))
		   AND ((LM.LeadDate <= @rToLeadDate) OR (ISNULL(@rToLeadDate,'') = ''))
		  AND ((LM.ContactPerson Like'%'+ @rContactPerson+'%') OR (ISNULL(@rContactPerson,'') = ''))
		  AND ((LM.ContactMobileNo Like'%'+ @rContactMobileNo+'%') OR (ISNULL(@rContactMobileNo,'') = ''))
		  -- AND ((LM.PlannedDate = @rPlanDate ) OR (ISNULL(@rPlanDate,'') = ''))
		    AND ((LM.PlannedDate >= @rPlanFromDate) OR (ISNULL(@rPlanFromDate,'') = ''))
		   AND ((LM.PlannedDate <= @rPlanToDate) OR (ISNULL(@rPlanToDate,'') = ''))
		   AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY 
		  LM.NextFollowupDate DESC

END

If	@rIsSearchHierarchyWise != 0
BEGIN
	SELECT 
	      LM.Id,
	      LM.OrgId,
	      ISNULL(LM.LeadAffiliationId,0) As LeadAffiliationId,
	      LAM.Title AS Affiliation,
	      LM.Title,
	      LM.StreetDetail,
	      LM.AreaName,
	      LM.CityName,
	      ISNULl( LM.StateId,0) AS StateId,
	      SM.Title AS StateName,
	      ISNULl(  LM.CountryId,0) AS CountryId,
	      CM.Title AS Country,
	      LM.Website,
	      ISNULl(LM.LeadStatusId,0)AS LeadStatusId ,
	      LSM.Title AS LeadStatus,
	      ISNULL(LM.LeadSourceId,0) As LeadSourceId,
	      LS.Title AS LeadSource,
	      ISNULl(LM.LeadOwnerEmployeeId,0) AS LeadOwnerEmployeeId,
	      EM.FirstName +' '+ MiddleName +' '+ LastName AS LeadOwner,
	      ISNULL(LM.NextFollowupDate,'0001/01/01') AS NextFollowupDate,
	      LM.NextFollowupRemark,
	      LM.ContactPerson,
	      LM.ContactMobileNo,
	      LM.ContactDesignation,
	      LM.ContactEmail,
	      LM.ZipCode,
	      LM.PhoneNo,
	      LM.MobileNo,
	      LM.Email AS EMail,
	      LM.district,
	      LM.ContactPerson2,
	      LM.ContactMobileNo2,
	      LM.ContactDesignation2,
		  LM.ContactEmail2,
		   LM.ContactPerson3,
	      LM.ContactMobileNo3,
	      LM.ContactDesignation3,
		  LM.ContactEmail3,
		  LM.ContactPerson4,
	      LM.ContactMobileNo4,
	      LM.ContactDesignation4,
		  LM.ContactEmail4,
		  LM.ContactPerson5,
	      LM.ContactMobileNo5,
	      LM.ContactDesignation5,
		  LM.ContactEmail5,
		  ISNULL(LM.LeadDate,'0001/01/01') AS LeadDate,
		  ISNULl(LM.LeadChannelPartnerId,0) AS LeadChannelPartnerId,
		  ISNULl(LM.LeadInfrastructureId,0) AS LeadInfrastructureId,
		  LM.StreetDetail++LM.AreaName+' '+LM.CityName+' '+SM.Title+' '+ CM.Title AS Address,
		  LM.CreatedUserId,
		  LM.CreatedDateTime,
		  ISNULL(LM.UpdatedUserId,0) AS UpdatedUserId,
		  ISNULL(LM.UpdatedDateTime,'') AS UpdatedDateTime,
		  ISNULL(LM.PlannedDate,'0001/01/01') AS PlannedDate,
		    ISNULL(LM.LatitudeAxis,0) AS LatitudeAxis,
		  ISNULL(LM.LongitudeAxis,0) AS LongitudeAxis
	FROM 
		  sErp.tLeadMaster LM
		  LEFT JOIN sErp.tLeadAffiliationMaster LAM ON LAM.Id=LM.LeadAffiliationId
		  LEFT JOIN sErp.tLeadSourceMaster LS ON  LS.Id=LM.LeadSourceId
		  LEFT JOIN sErp.tLeadStatusMaster LSM ON LSM.Id=LM.LeadStatusId
		  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LM.LeadOwnerEmployeeId
		  LEFT JOIN sCommon.tCountryMaster CM ON  CM.Id = LM.CountryId
		  LEFT JOIN sCommon.tStateMaster SM ON SM.Id=LM.StateId
		  INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.Id
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		--LEFT JOIN sSecurity.tUser U ON U.SourceId =LM.LeadOwnerEmployeeId AND SourceTypeId = 95
	WHERE 
		  ((LM.Id = @rId) OR (@rId=0))
		  AND((LM.OrgId = @rOrgId) OR(@rOrgId=0))
		  AND ((LM.Title Like '%'+ @rTitle+'%')OR(ISNULL(@rTitle,'') = ''))
		  AND ((LM.AreaName Like '%'+@rAreaName+'%')OR(ISNULL(@rAreaName,'') = ''))
		  AND ((LM.CityName Like '%'+@rCityName+'%')OR(ISNULL(@rCityName,'') = ''))
		  AND	((LM.StateId = @rStateId) OR (@rStateId = 0))
		  AND ((LM.district Like '%'+@rDistrict+'%') OR (ISNULL(@rDistrict,'') = ''))
		  AND	((LM.CountryId = @rCountryId) OR (@rCountryId = 0))
		  AND	((LM.LeadChannelPartnerId = @rVcpId) OR (@rVcpId = 0))
		  AND((LM.LeadInfrastructureId = @rLeadInfrastructureId) OR (@rLeadInfrastructureId =0))
		  AND	((LM.LeadAffiliationId = @rLeadAffiliationId) OR (@rLeadAffiliationId = 0))
		  AND	((LM.LeadStatusId = @rLeadStatusId) OR (@rLeadStatusId = 0))
		  AND	((LM.LeadSourceId = @rLeadSourceId) OR (@rLeadSourceId = 0))
		 --AND	((LM.LeadOwnerEmployeeId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0))
		  AND ((LM.NextFollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		  AND ((LM.NextFollowupDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		  AND ((LM.LeadDate >= @rFromLeadDate) OR (ISNULL(@rFromLeadDate,'') = ''))
		   AND ((LM.LeadDate <= @rToLeadDate) OR (ISNULL(@rToLeadDate,'') = ''))
		  AND ((LM.ContactPerson Like'%'+ @rContactPerson+'%') OR (ISNULL(@rContactPerson,'') = ''))
		  AND ((LM.ContactMobileNo Like'%'+ @rContactMobileNo+'%') OR (ISNULL(@rContactMobileNo,'') = ''))
		   AND ((LM.PlannedDate >= @rPlanFromDate) OR (ISNULL(@rPlanFromDate,'') = ''))
		   AND ((LM.PlannedDate <= @rPlanToDate) OR (ISNULL(@rPlanToDate,'') = ''))
		   AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY 
		  LM.NextFollowupDate DESC
END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pLeadPlanGet]
	@rType nvarchar(20)='',
	@rEmployeeId bigint = 0,
	@rLeadId bigint=0,
	@rLeadtitle nvarchar(50)='',
	@rPlannedDate DATETIME='',
	@rLatitudeAxis nvarchar(20)='',
	@rLongitudeAxis nvarchar(20)='',
	@rFromPlanDate DATETIME='',
	@rToPlanDate DATETIME=''
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 
	IF(@rType = 'GetLeadPlanList')
	BEGIN
			SELECT
				ISNULL(LM.Id,0)AS LeadId,
				ISNULL(LM.Title,'') AS LeadTitle,
				ISNULL(LM.PlannedDate,'01/01/0001') AS PlannedDate,
				ISNULL(LM.LatitudeAxis,'') AS LatitudeAxis,
				ISNULL(LM.LongitudeAxis,'') As LongitudeAxis				
		FROM sErp.tLeadMaster LM
			WHERE(( LM.Id = @rLeadId) OR (@rLeadId=''))
	END
	ELSE IF (@rType = 'UpdateLeadPlan')
		BEGIN
			UPDATE sErp.tLeadMaster
			SET PlannedDate =@rPlannedDate, LatitudeAxis = @rLatitudeAxis,LongitudeAxis = @rLongitudeAxis
            WHERE ((Id = @rLeadId) OR (@rLeadId=''))
			select 1
		END
	ELSE IF (@rType = 'GetPlanDetails')
		BEGIN
			SELECT
				ISNULL(LM.Id,0)AS LeadId,
				ISNULL(LM.Title,'') AS LeadTitle,
				ISNULL(LM.PlannedDate,'01/01/0001') AS PlannedDate,
				ISNULL(LM.LatitudeAxis,'') AS LatitudeAxis,
				ISNULL(LM.LongitudeAxis,'') As LongitudeAxis				
			FROM sErp.tLeadMaster LM
				WHERE(( convert(DATE, LM.PlannedDate,102) >= @rFromPlanDate) OR (@rFromPlanDate=''))
				AND(( convert(DATE, LM.PlannedDate,102) <= @rToPlanDate) OR (@rToPlanDate=''))
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pLeaveStatusGet] 
	@rEmployeeId bigint,
	@rFromDate DATETIME='',
	@rToDate DATETIME=''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT LPM.Code AS LeaveStatus
	FROM sHrm.tLeave L
	INNER JOIN sHrm.tLeavePeriodMaster LPM ON L.LeavePeriodId = LPM.Id
	WHERE  ((L.EmployeeId = @rEmployeeId) OR (@rEmployeeId  =0))
	AND @rFromDate BEtWEEN L.FromDate AND L.ToDate 
	--AND L.ReportDate BEtWEEN @rFromDate AND @rToDate 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pMarketingActivityMasterGet] 
	@rFlag int,
	@rEmployeeId bigint,
	@rCommonDate DATETIME=''
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rFlag = 0)
		BEGIN
		SELECT MAM.Id AS ActivityId,MAM.Title AS ActivityTitle,MASM.Id AS SubActivityId,MASM.Title AS SubActivityTitle  
            ,ISNULL(MAP.Id,0) AS CommonId, ISNULL(MAP.DurationHr,0) AS CommonDuration
            ,ISNULL(MAP.DurationMin,0) AS CommonDurationMin,ISNULL(MAP.Nos,0) AS CommonNos
            --,ISNULL(MAPD.Item,'') AS Item ,ISNULL(MAPD.Remark,'') AS Remark
            FROM sErp.tMarketingActivityMaster MAM   
            INNER JOIN sErp.tMarketingSubActivityMaster MASM  ON MASM.MarketingSubActivityId = MAM.Id 
            LEFT JOIN sErp.tMarketingActivityPlan MAP ON MAP.MarketingSubActivityId = MASM.Id  
            AND ((MAP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))  
            AND ((MAP.PlanDate =@rCommonDate) OR (@rCommonDate=''))
           -- LEFT JOIN sErp.tMarketingActivityPlanDetail MAPD ON MAPD.MarketingActivityPlanId=MAP.Id
		END
	ELSE
		BEGIN
			SELECT MAM.Id AS ActivityId,MAM.Title AS ActivityTitle,MASM.Id AS SubActivityId,MASM.Title AS SubActivityTitle  
              ,ISNULL(MAS.Id,0) AS CommonId, ISNULL(MAS.DurationHr,0) AS CommonDuration
              ,ISNULL(MAS.DurationMin,0) AS CommonDurationMin,ISNULL(MAS.Nos,0) AS CommonNos 
              ,ISNULL(MAS.FromTime,'') As FromTime
			,ISNULL(MAS.ToTime,'') As ToTime
             -- ,ISNULL(MASD.Item,'') AS Item ,ISNULL(MASD.Remark,'') AS Remark
              FROM sErp.tMarketingActivityMaster MAM   
              INNER JOIN sErp.tMarketingSubActivityMaster MASM  ON MASM.MarketingSubActivityId = MAM.Id 
              LEFT JOIN sErp.tMarketingActivityStatus MAS ON MAS.MarketingSubActivityId = MASM.Id 
              --LEFT JOIN sErp.tMarketingActivityPlan MAP ON MAP.MarketingSubActivityId = MASM.Id  
              AND ((MAS.EmployeeId = @rEmployeeId) OR (@rEmployeeId  =0))  
              AND ((MAS.ReportDate =@rCommonDate) OR (@rCommonDate=''))
             -- LEFT JOIN sErp.tMarketingActivityPlanDetail MASD ON MASD.MarketingActivityPlanId=MAS.Id
		END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sErp].[pMarketingActivityPlanStatusAdd] 
	@rFlag INT,
	@rActivityCommonId INT=0,
	@rEmployeeId BIGINT,
	@rCommonDate DATETIME='',
	@rMarketingSubActivityId SMALLINT =0,
	@rNos SMALLINT =0,
	@rDuration SMALLINT =0,
	@rDurationMin SMALLINT =0,
	@rUpdatedUserId BIGINT=0,
	--@rItem nvarchar(200) ='',
	--@rRemark nvarchar(500)='',
	@rXmldoc [nvarchar](max)='',
	@rFromTime nvarchar(10) ='',
	@rToTime nvarchar(10) =''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lCommonId bigint,
			@lItem nvarchar(100),	
			@lRemark nvarchar(100)
	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 
	(
		Id bigint identity,
		CommonId bigint,
		Item nvarchar(100),
		Remark nvarchar(100)
	)
	
	INSERT INTO #tTable1
	(
		CommonId,
		Item,
		Remark
	)
	
	SELECT
		 T.c.value('@CommonId','bigint') AS CommonId,
		 T.c.value('@Item','nvarchar(100)') AS Item,
		 T.c.value('@Remark','nvarchar(100)') AS Remark
		 
	FROM @loXML.nodes('/Table/Remark')T(c)
	
	IF(@rFlag =0)
		BEGIN
			IF(@rActivityCommonId = 0)
			BEGIN
				INSERT INTO [sErp].[tMarketingActivityPlan]
				(EmployeeId,PlanDate,MarketingSubActivityId,Nos,DurationHr,DurationMin,UpdatedUserId,UpdatedDateTime)
				VALUES
				(@rEmployeeId,@rCommonDate,@rMarketingSubActivityId,@rNos,@rDuration,@rDurationMin,@rUpdatedUserId,sCommon.fGetDate())
				DECLARE @lActivityPlanId bigint=0
					SELECT @lActivityPlanId=max(Id) FROM sErp.tMarketingActivityPlan 
					--WHERE EmployeeId = @rEmployeeId AND MarketingSubActivityId = @rMarketingSubActivityId
					
					SELECT @lCount =  COUNT(Id) FROM #tTable1
					WHILE @lCount > 0 
						BEGIN
							
							SELECT	
								@lCommonId = CommonId,
								@lItem = Item,
								@lRemark = Remark	 
							FROM #tTable1 WHERE Id = @lCount 
							
							SELECT @lCommonId = CASE WHEN ISNULL(@lCommonId,0) =0 THEN @lActivityPlanId ELSE @lCommonId END
							INSERT INTO sErp.tMarketingActivityPlanDetail
							(MarketingActivityPlanId,Item,Remark)
							VALUES
							(@lCommonId,@lItem,@lRemark)
							SET @lCount = @lCount - 1
						END
					
				SELECT 1 AS Result 
			END
		ELSE
			BEGIN
				UPDATE [sErp].[tMarketingActivityPlan]
				   SET EmployeeId = @rEmployeeId,
					  PlanDate = @rCommonDate,
					  MarketingSubActivityId = @rMarketingSubActivityId,
					  Nos = @rNos,
					  DurationHr = @rDuration,
					  DurationMin=@rDurationMin,
					  UpdatedUserId = @rUpdatedUserId,
					  UpdatedDateTime = sCommon.fGetDate()
					  WHERE Id = @rActivityCommonId
					--DECLARE @lActivityPlanId bigint=0
					SELECT @lActivityPlanId=MAX(Id) FROM sErp.tMarketingActivityPlan 
					--WHERE EmployeeId = @rEmployeeId AND MarketingSubActivityId = @rMarketingSubActivityId
					
					SELECT @lCount =  COUNT(Id) FROM #tTable1
					WHILE @lCount > 0 
						BEGIN
							SELECT	
								@lCommonId = CommonId,
								@lItem = Item,
								@lRemark = Remark	 
							FROM #tTable1 WHERE Id = @lCount 
							SELECT @lCommonId = CASE WHEN ISNULL(@lCommonId,0) =0 THEN @lActivityPlanId ELSE @lCommonId END
							INSERT INTO sErp.tMarketingActivityPlanDetail
							(MarketingActivityPlanId,Item,Remark)
							VALUES
							(@lCommonId,@lItem,@lRemark)
							
							SET @lCount = @lCount - 1
						END
					  SELECT 11 AS Result
			END
		END
	ELSE
		BEGIN
			IF(@rActivityCommonId = 0)
		BEGIN
			INSERT INTO sErp.tMarketingActivityStatus
			(EmployeeId,ReportDate,MarketingSubActivityId,Nos,DurationHr,DurationMin,UpdatedUserId,UpdatedDateTime,FromTime,ToTime)
			VALUES
			(@rEmployeeId,@rCommonDate,@rMarketingSubActivityId,@rNos,@rDuration,@rDurationMin,@rUpdatedUserId,sCommon.fGetDate(),@rFromTime,@rToTime)
			
			DECLARE @lActivityStatusId bigint=0
			SELECT @lActivityStatusId=MAX(Id) FROM sErp.tMarketingActivityStatus --WHERE EmployeeId = @rEmployeeId AND MarketingSubActivityId = @rMarketingSubActivityId
			
			SELECT @lCount =  COUNT(Id) FROM #tTable1
					WHILE @lCount > 0 
						BEGIN
							SELECT	
								@lCommonId = CommonId,
								@lItem = Item,
								@lRemark = Remark	 
							FROM #tTable1 WHERE Id = @lCount 
							
							SELECT @lCommonId = CASE WHEN ISNULL(@lCommonId,0) = 0 THEN @lActivityStatusId ELSE @lCommonId END
							INSERT INTO sErp.tMarketingActivityStatusDetail
							(MarketingActivityStatusId,Item,Remark1)
							VALUES
							(@lCommonId,@lItem,@lRemark)
							
							
							SET @lCount = @lCount - 1
						END
			
			SELECT 1 AS Result 
		END
	ELSE
		BEGIN
			UPDATE sErp.tMarketingActivityStatus
			   SET EmployeeId = @rEmployeeId,
				  ReportDate = @rCommonDate,
				  MarketingSubActivityId = @rMarketingSubActivityId,
				  Nos = @rNos,
				  DurationHr = @rDuration,
				  DurationMin=@rDurationMin,
				  UpdatedUserId = @rUpdatedUserId,
				  UpdatedDateTime = sCommon.fGetDate(),
				  FromTime= @rFromTime,
				  ToTime = @rToTime
				  WHERE Id = @rActivityCommonId
				  
				  --DECLARE @lActivityStatusId bigint=0
				  SELECT @lActivityStatusId=MAX(Id) FROM sErp.tMarketingActivityStatus
				  
				  SELECT @lCommonId = CASE WHEN ISNULL(@lCommonId,0) =0 THEN @lActivityStatusId ELSE @lCommonId END
				  SELECT @lCount =  COUNT(Id) FROM #tTable1
					WHILE @lCount > 0 
						BEGIN
							INSERT INTO sErp.tMarketingActivityStatusDetail
							SELECT	
								CommonId,
								Item,
								 Remark	 
							FROM #tTable1 WHERE Id = @lCount 
							
							--INSERT INTO sErp.tMarketingActivityStatusDetail
							--(MarketingActivityStatusId,Item,Remark1)
							--VALUES
							--(@lCommonId,@lItem,@lRemark)
							
							SET @lCount = @lCount - 1
						END
				  SELECT 11 AS Result
		END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sErp].[pMarketingActivityReviweGet] 
	@rEmployeeId bigint,
	@rFromDate DATETIME='',
	@rToDate DATETIME=''
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN



	CREATE TABLE #TempDate
	(
		Id smallint Identity,
		FromDate date
	)

	DECLARE @StartDate date = @rFromDate
		   ,@EndDate   date = @rToDate

	BEGIN	 
	WITH theDates AS
		 (SELECT @StartDate as theDate
		  UNION ALL
		  SELECT DATEADD(day, 1, CONVERT(date,theDate))
			FROM theDates
		   WHERE DATEADD(day, 1,  CONVERT(date,theDate)) <= @EndDate
		 )
	insert into #TempDate(FromDate)
	SELECT CONVERT(date,theDate) AS FromDate
	  FROM theDates
	OPTION (MAXRECURSION 0)
	END

	DECLARE @lCount Smallint = 0
	SELECT @lCount = Count(*) From #TempDate

	

	SELECT 
		MASM.Id AS SubActivityId,
		MAM.Title AS ActivityTitle,
		MASM.Title AS SubActivityTitle,		 
		ISNULL(SUM(P.DurationHr),0) AS  PlanDuration,
		ISNULL(SUM(P.DurationMin),0) AS  PlanDurationMin,
		ISNULL(SUM(P.Nos),0) AS  PlanNos, 
		ISNULL(SUM(M.DurationHr),0) AS StatusDuration,
		ISNULL(SUM(M.DurationMin),0) AS StatusDurationMin,
		ISNULL(SUM(M.Nos),0) AS StatusNos
	FROM sErp.tMarketingActivityMaster MAM   
		INNER JOIN sErp.tMarketingSubActivityMaster MASM  ON MASM.MarketingSubActivityId = MAM.Id
		CROSS JOIN #TempDate TD		
		LEFT JOIN (
		 SELECT * FROM sErp.tMarketingActivityStatus MAS		 
		WHERE ((MAS.EmployeeId = @rEmployeeId) OR (@rEmployeeId  =0))
		AND (( convert(DATE,MAS.ReportDate,102)  >=@rFromDate) OR (@rFromDate='')) 
		AND (( convert(DATE,MAS.ReportDate,102) <=@rToDate) OR (@rToDate='')) 
		) M  ON M.MarketingSubActivityId = MASM.Id AND TD.FromDate = M.ReportDate
		 
		LEFT JOIN
		(
		 SELECT * FROM  sErp.tMarketingActivityPlan MAP 		 
		WHERE ((MAP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0)) 
			AND (( convert(DATE,MAP.PlanDate,102)  >=@rFromDate) OR (@rFromDate='')) 
		AND (( convert(DATE,MAP.PlanDate,102) <=@rToDate) OR (@rToDate='')) 
		) P ON P.MarketingSubActivityId = MASM.Id AND TD.FromDate = P.PlanDate
		GROUP BY MAM.Title,MASM.Title,MASM.Id
		
--SELECT * FROM 	#TempDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pMarketingActivityStatusRemarkGet] 
	@rEmployeeId bigint,
	@rFromDate DATETIME='',
	@rToDate DATETIME='',
	@rSubActivityId int =0,
	@rFlag int
	

WITH EXECUTE AS CALLER	
AS
SET NOCOUNT ON
BEGIN
	IF(@rFlag = 0)
		BEGIN
			SELECT 
				ISNULL(MAPD.AutoId,0) As RemarkId,
				MAM.Title AS ActivityTitle,
				MASM.Title AS SubActivityTitle,
				ISNULL(MAP.PlanDate,'01/01/0001') AS ReportDate,
				ISNULL(MAPD.Item,'') As StatusItem,
				ISNULL(MAPD.Remark,'') AS StatusRemark
			FROM sErp.tMarketingActivityMaster MAM   
				INNER JOIN sErp.tMarketingSubActivityMaster MASM  ON MASM.MarketingSubActivityId = MAM.Id 
				LEFT JOIN sErp.tMarketingActivityPlan MAP ON MAP.MarketingSubActivityId = MASM.Id 
				AND ((MAP.EmployeeId = @rEmployeeId) OR (@rEmployeeId  =0))
				AND ((MAP.PlanDate >=@rFromDate) OR (@rFromDate='')) 
				AND ((MAP.PlanDate <=@rToDate) OR (@rToDate=''))
				LEFT JOIN sErp.tMarketingActivityPlanDetail MAPD ON MAPD.MarketingActivityPlanId=MAP.Id 
				WHERE ((MASM.Id = @rSubActivityId)OR(@rSubActivityId=0))
				--GROUP BY MAM.Title,MASM.Title,MAP.PlanDate,MAPD.Item,MAPD.Remark,MAPD.AutoId 
		END
	ELSE
		BEGIN
			SELECT 
				ISNULL(MASD.AutoId,0) As RemarkId,
				MAM.Title AS ActivityTitle,
				MASM.Title AS SubActivityTitle,
				ISNULL(MAS.ReportDate,'01/01/0001') AS ReportDate,
				ISNULL(MASD.Item,'') As StatusItem,
				ISNULL(MASD.Remark1,'') AS StatusRemark
			FROM sErp.tMarketingActivityMaster MAM   
				INNER JOIN sErp.tMarketingSubActivityMaster MASM  ON MASM.MarketingSubActivityId = MAM.Id 
				LEFT JOIN sErp.tMarketingActivityStatus MAS ON MAS.MarketingSubActivityId = MASM.Id 
				AND ((MAS.EmployeeId = @rEmployeeId) OR (@rEmployeeId  =0))
				AND ((MAS.ReportDate >=@rFromDate) OR (@rFromDate='')) 
				AND ((MAS.ReportDate <=@rToDate) OR (@rToDate=''))
				LEFT JOIN sErp.tMarketingActivityStatusDetail MASD ON MASD.MarketingActivityStatusId=MAS.Id 
				WHERE ((MASM.Id = @rSubActivityId)OR(@rSubActivityId=0))
				--GROUP BY MAM.Title,MASM.Title,MAS.ReportDate,MASD.Item,MASD.Remark1,MASD.AutoId 
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sErp].[pOrgGroupAppUserSummaryGet]
(
	@rOrgGroupId int,
	@rOrgGroupBatchId int
 )
AS
SET NOCOUNT ON

BEGIN
		 SELECT 
				OM2.ID AS OrgId,
				OM2.DisplayTitle AS OrgName,
				OM2.Code, 
				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND OM.Id = OM2.Id  AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) AS 'StudentCreatedUser',

				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0))
				 AND(OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0) AS 'EmployeeCreatedUser',
 
				ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND OM1.Id = OM2.Id AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND SC.StatusId = 1),0) AS 'StudentRegister',

				ISNULL((SELECT COUNT(RU.UserId) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId INNER JOIN (SELECT RU.UserId AS  UserId FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U2 ON RU.UserId = U2.Id
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U2.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId AND (OM1.Id !=1) AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) WHERE U2.IsObsolete = 0 AND U2.SourceTypeId= 95 GROUP BY RU.UserId ) RU ON RU.UserId = U1.Id
				WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) AND (OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0) AS 'EmployeeRegister',

				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND OM.Id = OM2.Id AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003 AND A.UserId IS NULL),0) AS 'StudentNotRegister',

				ISNULL((ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0))
				 AND(OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0) - ISNULL((SELECT COUNT(RU.UserId) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId INNER JOIN (SELECT RU.UserId AS  UserId FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U2 ON RU.UserId = U2.Id
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U2.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId AND (OM1.Id !=1) AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) WHERE U2.IsObsolete = 0 AND U2.SourceTypeId= 95 GROUP BY RU.UserId ) RU ON RU.UserId = U1.Id
				WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) AND (OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0)),0) 'EmployeeNotRegister'
				 
				FROM
				 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM2 ON OM2.Id = U.OrgId 
				LEFT JOIN (
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1)
				AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				 
				WHERE U.IsObsolete = 0
				AND((OM2.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM2.Id !=1)
				GROUP BY OM2.Id,OM2.DisplayTitle,OM2.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sErp].[pOrgGroupCountlistGet]
(
	@rOrgGroupId int,
	@rOrgGroupBatchId int
 )
AS
SET NOCOUNT ON

BEGIN
		 Select 
				COUNT(SM.Id) As StudentCount,
				(SELECT COUNT(EM.Id) FROM  sHrm.tEmployeeMaster EM 
				 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
				 INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
				 INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
				 INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
				 INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
				 WHERE EM.OrgID = OM.Id AND IsOtherUser = 0 AND StatusId = 7) as EmployeeCount,
				(SELECT COUNT(EM.Id) FROM  sHrm.tEmployeeMaster EM 
				 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
				 INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
				 INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
				 INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
				 INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
				 WHERE EM.OrgID = OM.Id AND IsOtherUser = 0 ) as TotalEmployeeCount,
				 OM.ID AS OrgId,
				 OM.DisplayTitle AS OrgName,
				 OM.Code, 
				(Select count(SM1.ID) from sStudent.tStudentMaster SM1 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON SM1.OrgId=OM1.Id 
				INNER JOIN sStudent.tAcademic A1 ON A1.StudentId= SM1.ID 
				INNER JOIN sSetup.tBatchMaster BM1 ON BM1.Id = A1.BatchId 
				Where SM1.Orgid =OM.Id And BM1.OrgGroupBatchId = Bm.OrgGroupBatchId 
				And OM1.OrgGroupId =Om.OrgGroupId and BM.IsInContext=BM1.IsInContext) As TotalCount 
 		From 
				sStudent.tStudentMaster SM 
				INNER JOIN  sSetup.tOrganizationMaster OM ON SM.OrgId=OM.Id 
				INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		Where   
				Om.OrgGroupId = @rOrgGroupId And SM.StatusId=1 And BM.OrgGroupBatchId = @rOrgGroupBatchId and BM.IsInContext=1 
		Group BY 
				OM.ID,OM.DisplayTitle,OM.Code ,Om.OrgGroupId , Bm.OrgGroupBatchId, BM.IsInContext
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sErp].[pOrgGroupModuleSummaryGet]
(
	@rOrgGroupId int,
	@rOrgGroupBatchId int,
	@rType int
 )
AS
SET NOCOUNT ON

BEGIN

	IF(@rType = 1)
	BEGIN
	 
		SELECT 
			*
		FROM
			(
			SELECT 'Circular' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' as Details,MAX(C.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sCommunication.tCircular C WHERE OrgGroupId = @rOrgGroupId
			UNION ALL
			SELECT 'Assignment' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(A.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' as Details,MAX(A.CreatedDateTime) as 'LastUsed',CASE  WHEN DATEDIFF(DAY,MAX(A.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(A.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sCommunication.tAssignment A INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=BM.OrgGroupBatchId WHERE OBM.OrgGroupId = @rOrgGroupId AND OBM.Id = @rOrgGroupBatchId
			UNION ALL
			SELECT 'CW/HW' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' as Details,MAX(C.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sAcademic.tClasswork C INNER JOIN sSetup.tBatchMaster BM ON BM.Id = C.BatchId INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=BM.OrgGroupBatchId WHERE OBM.OrgGroupId = @rOrgGroupId AND OBM.Id = @rOrgGroupBatchId
			UNION ALL
			SELECT 'Query' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(Q.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' as Details,MAX(Q.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(Q.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(Q.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sCommunication.tQuery Q WHERE OrgGroupId = @rOrgGroupId
			UNION ALL
			SELECT 'Video' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(V.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' as Details,MAX(V.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(V.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(V.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sSupport.tVideoMaster V INNER JOIN sSetup.tOrganizationMaster OM ON V.OrgId = OM.Id WHERE OM.OrgGroupId = 1101
			UNION ALL
			SELECT 'Event' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(E.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' as Details,MAX(E.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(E.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(E.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sActivity.tEventSchedule E INNER JOIN sSetup.tBatchMaster BM ON BM.Id = E.BatchId INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=BM.OrgGroupBatchId WHERE OBM.OrgGroupId = @rOrgGroupId AND OBM.Id = @rOrgGroupBatchId
			UNION ALL
			SELECT 'Gallery' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(P.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' as Details,MAX(P.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(P.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(P.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sCommunication.tPhotoCategoryMaster P  WHERE P.OrgGroupId = @rOrgGroupId
			) as A
			
	 END
	 ELSE IF(@rType = 2)
	 BEGIN
			SELECT 
				*
			FROM
				(
				  --mantis id: 0040333
				  --SELECT 'Student' as Module,CONVERT(NVARCHAR,ISNULL(COUNT(SM.Id),0)) AS Summary,'Active Student Count' As Details,MAX(SM.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(SM.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(SM.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sStudent.tStudentMaster SM INNER JOIN sStudent.vStudentAcademic A ON A.StudentId = SM.Id INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId 
				  --INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId  WHERE OM.OrgGroupId = @rOrgGroupId AND  BM.IsInContext=1  AND BM.OrgGroupBatchId = @rOrgGroupBatchId and A.StatusID=1  

				  SELECT 'Student' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' As Details,MAX(AL.AuditDate) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status'
				  FROM sAudit.tActivityLog AL INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId WHERE OM.OrgGroupId = @rOrgGroupId 
				  AND AL.ScreenId IN (20009,20539,20016,20010,20014,20013,20269) 

				  UNION ALL

				  --mantis id: 0040333
				  --SELECT 'Employee' as Module,CONVERT(NVARCHAR,ISNULL(COUNT(EM.Id),0)) AS Summary,'Active Employee Count' As Details,MAX(EM.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(EM.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(EM.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId 
				  --WHERE OM.OrgGroupId = @rOrgGroupId AND EM.StatusID=7 
				  SELECT 'Employee' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' As Details,MAX(AL.AuditDate) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status'
				  FROM sAudit.tActivityLog AL INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId WHERE OM.OrgGroupId = @rOrgGroupId 
				  AND AL.ScreenId IN (20035,20586,20270,20573,20402)

				  UNION ALL

				  SELECT 'Attendance' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(SR.AttendanceDate),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Attendance Taken Before' as Details,MAX(SR.AttendanceDate) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(SR.AttendanceDate),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(SR.AttendanceDate),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sAttendance.tStudentRegister SR  INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId =  SR.AcademicId 
			      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId WHERE OM.OrgGroupId= @rOrgGroupId

				  UNION ALL

				  --mantis id: 0040333
				  --SELECT 'Certificate' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(L.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' as Details,MAX(L.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(L.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(L.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sCertificate.tLeaving  L 
				  --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=L.OrgId WHERE OM.OrgGroupId = @rOrgGroupId
				  SELECT 'Certificate' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' As Details,MAX(AL.AuditDate) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status'
				  FROM sAudit.tActivityLog AL INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId WHERE OM.OrgGroupId = @rOrgGroupId 
				  AND AL.ScreenId IN (20061,20063,20064,20065,20066,20067,20389,20390,30227,20557)

				  UNION ALL

				  SELECT 'Fee' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(FR.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' as Details,MAX(FR.CreatedDateTime) as 'LastUsed',CASE  WHEN DATEDIFF(DAY,MAX(FR.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(FR.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sFee.tReceipt FR 
				  INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=FR.OrgGroupBatchId WHERE OBM.OrgGroupId = @rOrgGroupId AND OBM.Id = @rOrgGroupBatchId

				  UNION ALL

				  --mantis id: 0040333
				  --SELECT 'Exam' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(ES.UpdatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' as Details,MAX(ES.UpdatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(ES.UpdatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sAssessment.tResult ES 
				  --INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId =ES.AcademicId 
				  --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId WHERE OM.OrgGroupId= @rOrgGroupId
				  SELECT 'Exam' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' As Details,MAX(AL.AuditDate) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status'
				  FROM  sAudit.tActivityLog AL INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId WHERE OM.OrgGroupId = @rOrgGroupId 
				  AND AL.ScreenId IN (20057,20060,20271,20427) 
				) as A
	 END
	 ELSE IF(@rType = 3)
	 BEGIN
			SELECT 
				*
			FROM
				(
				  --mantis id: 0040333
				  --SELECT 'Library' as Module,CONVERT(NVARCHAR,ISNULL(COUNT(BM.Id),0)) AS Summary,'Book Count' As Details,MAX(BM.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(BM.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(BM.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sLibrary.tLibraryMaster LM INNER JOIN sLibrary.tBookMaster BM ON BM.LibraryId = LM.Id
				  --WHERE LM.OrgGroupId = @rOrgGroupId  
				  SELECT 'Library' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' As Details,MAX(AL.AuditDate) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status'
				  FROM sAudit.tActivityLog AL INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId WHERE OM.OrgGroupId = @rOrgGroupId 
				  AND AL.ScreenId IN (30041,20119,30777,20194,20122)

				  UNION ALL

				  SELECT 'Transport' as Module,CONVERT(NVARCHAR,ISNULL(COUNT(AR.SourceId),0)) AS Summary,'Bus route assign students' As Details,MAX(SM.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(SM.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(SM.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sTransport.tAssignRoute AR INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId
				  INNER JOIN sStudent.tStudentMaster SM ON SD.StudentId = SM.Id INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=SD.OrgGroupBatchId
				  WHERE OBM.OrgGroupId = @rOrgGroupId  AND OBM.Id = @rOrgGroupBatchId

				  UNION ALL

				  SELECT 'Hostel' as Module,CONVERT(NVARCHAR,ISNULL(COUNT(AR.SourceId),0)) AS Summary,'Hostel students' As Details,MAX(SM.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(SM.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(SM.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sHostel.tAssignRoom AR INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId
				  INNER JOIN sStudent.tStudentMaster SM ON SD.StudentId = SM.Id INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=SD.OrgGroupBatchId
				  WHERE OBM.OrgGroupId = @rOrgGroupId AND OBM.Id = @rOrgGroupBatchId
				  
				  UNION ALL
				  
				  --mantis id: 0040333
				  --SELECT 'Payroll' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(PR.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Payroll Process' As Details,MAX(PR.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(PR.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(PR.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sPayroll.tPayProcess PR INNER JOIN sPayroll.tPayrollYearMaster PY ON PY.Id = PR.PayrollYearId
				  --WHERE PY.OrgGroupId = @rOrgGroupId  
				  SELECT 'Payroll' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' As Details,MAX(AL.AuditDate) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status'
				  FROM sAudit.tActivityLog AL INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId WHERE OM.OrgGroupId = @rOrgGroupId 
				  AND AL.ScreenId IN (20267,20255,20994)

				  UNION ALL

				  --mantis id: 0040333
				  --SELECT 'TimeTable' as Module,CONVERT(NVARCHAR,ISNULL(COUNT(Distinct(TD.EmployeeId)),0)) AS Summary,'TimeTable Allocated' As Details,MAX(TS.UpdatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(TS.UpdatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(TS.UpdatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sTimetable.tTimeTableDetail TD INNER JOIN sTimeTable.tTimeTable TT ON TD.TimeTableId = TT.Id INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId
				  --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=TS.OrgGroupBatchId
				  --WHERE OBM.OrgGroupId = @rOrgGroupId AND OBM.Id = @rOrgGroupBatchId
				  SELECT 'TimeTable' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Used Before' As Details,MAX(AL.AuditDate) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(AL.AuditDate),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status'
				  FROM  sAudit.tActivityLog AL INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId WHERE OM.OrgGroupId = @rOrgGroupId 
				  AND AL.ScreenId IN (20238,20928,20242,20177,20857) 

				  UNION ALL

				  SELECT 'Stock' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(SI.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Stock Issue' As Details,MAX(SI.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(SI.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(SI.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sProcurement.tStockIssue SI
				  WHERE SI.OrgGroupId = @rOrgGroupId 

				  UNION ALL

				  SELECT 'Asset' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(AA.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Asset Adjustment' As Details,MAX(AA.CreatedDateTime) as 'LastUsed',CASE  WHEN DATEDIFF(DAY,MAX(AA.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(AA.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sAssetManagement.tAssetAdjustment AA
				  INNER JOIN sSetup.tOrganizationMaster OM ON AA.OrgId = OM.Id
				  WHERE OM.OrgGroupId = @rOrgGroupId
				) as A
	 END
	ELSE IF(@rType = 4)
	 BEGIN
			SELECT 
				*
			FROM
				(
				  SELECT 'Alert' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(AL.CreatedDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Alert' As Details,MAX(AL.CreatedDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(AL.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN DATEDIFF(DAY,MAX(AL.CreatedDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sAlert.tAlertLog AL INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
				  WHERE OM.OrgGroupId = @rOrgGroupId  

				  UNION ALL

				  SELECT 'Online Payment' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(PT.PayDateTime),sCommon.fGetDate()),0))+' '+'Days' AS Summary,'Last Transaction' As Details,MAX(PT.PayDateTime) as 'LastUsed',CASE WHEN DATEDIFF(DAY,MAX(PT.PayDateTime),sCommon.fGetDate()) IS NULL THEN 'In Active' WHEN  DATEDIFF(DAY,MAX(PT.PayDateTime),sCommon.fGetDate()) > 30 THEN 'In Active' ELSE 'Active' End as 'Status' FROM sOp.tPaymentTransaction PT INNER JOIN sFee.tOnlineFee OL ON OL.Id = PT.TransactionSourceId
				  INNER JOIN sFee.tReceiptBookMaster RM ON RM.Id = OL.ReceiptBookId
				  WHERE RM.OrgGroupId = @rOrgGroupId 
				) as A
		
	 END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE OR ALTER PROCEDURE [sErp].[pPluginLogAdd]    
	@rOrgGroupID int, 
	@rPlugin int,
	@rStatusRemark nvarchar(200) = 'Active',
	@rCreatedUserId bigint,
	@rPlugInStatusId tinyint,
	@rPluginDate DateTime = null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
   
	BEGIN TRY
 	BEGIN TRANSACTION
	 
		BEGIN	
		IF NOT EXISTS(SELECT * FROM sErp.tCustomerPlugInLog WHERE PlugInId = @rPlugin AND PlugInStatusId = @rPluginStatusId AND OrgGroupId = @rOrgGroupID)		
		INSERT INTO sErp.tCustomerPlugInLog
			(
			
			OrgGroupId,
			PlugInId,
			LogDate,
			StatusRemark,
			CreatedUserId,
			CreatedDateTime,
			PlugInStatusId
			)
			VALUES
			(
			
			@rOrgGroupID ,
			@rPlugin ,
			ISNULL(@rPluginDate,sCommon.fGetDate()),
			@rStatusRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rPluginStatusId
			)
		
		
		SELECT 1 AS RESULT
		END

		COMMIT TRANSACTION
	 
		END TRY
		
		BEGIN CATCH
		ROLLBACK TRANSACTION 
				 SELECT -1 AS RESULT
		END CATCH			
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pProjectAdd]

        @rId int,
        @rTitle nvarchar(100),
        @rCode nvarchar(100),
        @rInActive bit = 0,
        @rOrgId smallint,
        @rCreatedUserId bigint,
        @rEstimatedHours nvarchar(100), 
        @rStrtDate date, 
        @rEndDate date, 
        @rEmployeeId bigint,
        @rIsclose bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		
		If Exists(select Id from sErp.tProjectMaster  where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
		If Exists(select Id from sErp.tProjectMaster  where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		
		If  Exists(select Id from sErp.tProjectMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
			If  Exists(select Id from sErp.tProjectMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tProjectMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tProjectMaster
		(
			Id,
			Code,
			Title,			
			OrgId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedDateTime,
			UpdatedUserId,
			EstimatedHours,
			IsActive,
			StartDate,
			EndDate,
			PMEmployeeId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rOrgId,
			@rInActive,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate(),
			@rCreatedUserId,
			@rEstimatedHours , 
		    @rIsclose,
            @rStrtDate , 
            @rEndDate, 
            @rEmployeeId 
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tProjectMaster
	    SET
			Code = @rCode,
			Title=@rTitle,
			IsObsolete=@rInActive,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			EstimatedHours = @rEstimatedHours,
			IsActive = @rIsclose,
			StartDate = @rStrtDate,
			EndDate = @rEndDate,
			PMEmployeeId = @rEmployeeId
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pProjectGet]

	 @rId int,
	 @rOrgId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			PT.Id,
			PT.Title,
			PT.Code,
		    PT.OrgId,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PT.IsObsolete,
		    PT.EstimatedHours,
		    isnull(PT.IsActive,0) as IsActive,
		    PT.StartDate,
		    PT.EndDate,
		    PT.PMEmployeeId,
		    EM.Code as 'EmployeeCode',
		   (isnull(EM.FirstName,'') + isnull(EM.LastName,'')) as 'EmployeeName'
		    
		   
	FROM 
			sErp.tProjectMaster PT
			left join sHrm.tEmployeeMaster EM on EM.Id = PT.PMEmployeeId
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((PT.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ISNULL(EM.IsOtherUser,0) = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sErp].[pProjectWiseDSRDetsailGet]

	 @rId int,
	 @rUserId bigint,
	 @rFromDate Date,
	 @rTillDate Date,
	 @rOrgId smallint,
	 @rModule nvarchar(100),
	 @rProjectId int ,
	 @rWorkTypeId int ,
	 @rActive bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rModule = sCommon.fSearchStringGet(@rModule)
	END
	
	
	SELECT 
			PT.Id,
			PT.ReportDate,
			PT.ProjectId,
		    PT.Module,
		    PT.DSRWorkTypeId,
		    PT.WorkDescription,
		    ISNULL(PT.HoursWorked,0) AS HoursWorked,
		    ISNULL(PT.MinuteWorked,0) AS MinuteWorked,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PM.Title as Project,
		    Dwt.Title as DSRWorkType,
		    u.DisplayTitle
		 
		
	FROM 
			sErp.tDSR  PT
			inner join sErp.tDSRWorkTypeMaster Dwt on Dwt.Id = PT.DSRWorkTypeId
			inner join sErp.tProjectMaster PM on PM.Id = PT.ProjectId
			inner join sSecurity.tUser u on u.Id = PT.CreatedUserId
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Module like @rModule) OR (ISNULL(@rModule,'') = ''))
		AND	((PT.ProjectId = @rProjectId) OR (@rProjectId = 0))
		AND	((PT.DSRWorkTypeId = @rWorkTypeId) OR (@rWorkTypeId = 0))
		AND ((u.id = @rUserId) OR (@rUserId = 0))
		AND ((PT.ReportDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	    AND ((PT.ReportDate <= @rTillDate) OR (ISNULL(@rTillDate,'') = ''))
	     and PM.IsActive =@rActive
	    
	    order by ReportDate desc
	    
	
		
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pReleaseNoteDetailAdd]
			
	        @rReleaseNoteId int
	       ,@rReleaseDate Date
           ,@rVersionNumber nvarchar(30)
		   ,@rVersionId bigint
         	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF(@rReleaseNoteId !=0)
	BEGIN
		IF EXISTS (SELECT * FROM [sErp].[tReleaseNote] WHERE Id = @rReleaseNoteId)
			BEGIN
					UPDATE [sErp].[tReleaseNote] SET ReleaseDate=@rReleaseDate ,VersionNumber=@rVersionNumber,VersionId=@rVersionId Where Id=@rReleaseNoteId OR  @rReleaseNoteId=0
					SELECT 11 As Result
			END	

	END
	ELSE 
		BEGIN
				SELECT  Top 1 @rReleaseNoteId=Id  FROM [sErp].[tReleaseNote] ORDER BY ID DESC
					Set @rReleaseNoteId = @rReleaseNoteId + 1;

					INSERT INTO [sErp].[tReleaseNote]
					   (
						[Id]
					   ,[ReleaseDate] 
					   ,[VersionNumber]
					   ,[VersionId] 
					   )
				 VALUES
					   (
						@rReleaseNoteId
					   ,@rReleaseDate
					   ,@rVersionNumber
					   ,@rVersionId
					   )
				SELECT @rReleaseNoteId AS RESULT
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[sErp].[pReleaseNoteDetailGet]
CREATE OR ALTER PROCEDURE [sErp].[pReleaseNoteDetailGet]
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		Select 
		RND.AutoId,
		RN.ReleaseDate,
		RN.VersionNumber,
		RN.VersionId,
		M.Title As ModuleName,
		RND.IssueDescription,
		IT.Title As IssueType
		from 
		sErp.tReleaseNote RN 
		INNER JOIN sErp.tReleaseNoteDetail RND on RN.id=RND.ReleaseNoteId
		INNER JOIN sCommon.tModuleMaster M on RND.ModuleId=M.Id
		INNER JOIN sErp.tIssueTypeMaster IT on RND.IssueTypeId=IT.Id

		ORDER BY RN.VersionId DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pReleaseNoteGet]
@rFromDate Date='',
@rToDate Date='',
@rVersionNumber nvarchar(max)='',
@rFromVersionId int=0,
@rToVersionId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
  Set @rFromDate= Cast(@rFromDate AS DATE)
  Set @rToDate=Cast(@rToDate AS DATE)
		Select 
		RN.Id,
		RN.ReleaseDate,
		RN.VersionId,
		RN.VersionNumber
		from [sErp].[tReleaseNote] RN
		Where 
		((RN.ReleaseDate >= @rFromDate) OR (ISNULL(@rFromDate,'')='')) 
		AND ((RN.ReleaseDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((RN.VersionNumber LIKE @rVersionNumber) OR (ISNULL(@rVersionNumber,'') LIKE ''))
		AND ((RN.VersionId >= @rFromVersionId) OR (ISNULL(@rFromVersionId,0)=0)) 
		AND ((RN.VersionId <= @rToVersionId)OR (ISNULL(@rToVersionId,0)=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sErp].[pReleaseNoteListAdd]
	 
	        @rAutoId nvarchar(50)
           ,@rModuleId smallint
           ,@rIssueDescription nvarchar(2000)
           ,@rIssueTypeId tinyint           
           ,@rPlatForm nvarchar(10)
		   ,@rReleaseNoteId int
         
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
BEGIN TRANSACTION	
	IF(@rReleaseNoteId !=0)
	BEGIN
	IF EXISTS (SELECT * FROM [sErp].[tReleaseNoteDetail] WHERE (ReleaseNoteId = @rReleaseNoteId) AND (AutoId=@rAutoId OR @rAutoId=''))
	BEGIN
			UPDATE [sErp].[tReleaseNoteDetail] SET ModuleId=@rModuleId,IssueDescription=@rIssueDescription,IssueTypeId=@rIssueTypeId,Platform=@rPlatForm
			WHERE (ReleaseNoteId = @rReleaseNoteId OR @rReleaseNoteId=0) AND AutoId=@rAutoId OR @rAutoId=''
		SELECT 11 As Result
	END
	ELSE IF (@rAutoId = 0)
	BEGIN
			INSERT INTO [sErp].[tReleaseNoteDetail]
			   (
			    [ReleaseNoteId]
			   ,[ModuleId] 
			   ,[IssueDescription]
			   ,[IssueTypeId] 
			   ,[Platform]
			   )
		  VALUES
			   (
				@rReleaseNoteId
			   ,@rModuleId
			   ,@rIssueDescription
			   ,@rIssueTypeId
			   ,@rPlatForm
			   )
			SELECT 1 AS Result
	END
	END
	ELSE 
	BEGIN
			SELECT 2 AS Result 
	END 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pRouteOrderGet]
	@rType nvarchar(20)='',
	@rEmployeeId bigint = 0,
	@rPlannedDate DATETIME='',
	@rRouteOrder int =0,
	@rLeadId bigint =0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 
	IF(@rType = 'GetRouteOrderList')
	BEGIN
			SELECT
				ISNULL(LM.Id,0)AS LeadId,
				ISNULL(LM.Title,'') AS LeadTitle,
				ISNULL(LM.ContactPerson,'') AS ContactPerson,
				ISNULL(LM.ContactMobileNo,'') AS ContactMobileNo,
				LM.StreetDetail+' '+LM.AreaName+' '+LM.CityName+' '+SM.Title+' '+ CM.Title AS Address,
				ISNULL(LM.LatitudeAxis,'') AS LatitudeAxis,
				ISNULL(LM.LongitudeAxis,'') As LongitudeAxis,
				ISNUll(LM.RouteOrder,0)AS RouteOrder
		FROM sErp.tLeadMaster LM
			LEFT JOIN sCommon.tCountryMaster CM ON  CM.Id = LM.CountryId
			LEFT JOIN sCommon.tStateMaster SM ON SM.Id=LM.StateId
			WHERE(( convert(DATE, LM.PlannedDate,102) = @rPlannedDate) OR (@rPlannedDate=''))
			AND ((LM.LeadOwnerEmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		ORDER BY LM.RouteOrder
	END
	ELSE IF (@rType = 'UpdateRouteOrder')
		BEGIN
			UPDATE sErp.tLeadMaster
			SET RouteOrder = @rRouteOrder
			WHERE Id = @rLeadId
			
			select 1
		END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pScreenFunctionalityBulkEntryAdd]

@rId int,
@rScreenId int,
@rFunctionality nvarchar (2000)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRANSACTION

	IF(@rId = 0)
		BEGIN
			DECLARE @lMaxId int=0
			SELECT @lMaxId=MAX(ISNULL(Id,0))+1 from sErp.tScreenFunctionalityMaster
			
			INSERT INTO sErp.tScreenFunctionalityMaster
			(
				Id,
				ScreeId,
				ScreenFunctionality
			)
			VALUES
			(
				@lMaxId,
				@rScreenId,
				@rFunctionality
			)
		 
			 SELECT 1 AS Result
		 END
	ELSE
	BEGIN
		UPDATE sErp.tScreenFunctionalityMaster 
		SET 
			ScreeId = @rScreenId,
			ScreenFunctionality = @rFunctionality 
		WHERE 
			Id = @rId
		
		SELECT 2 AS Result
	END

COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sErp].[pScreenFunctionalityBulkEntryGet]

	@rModuleId int = 0,
	@rId int =0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SELECT  
			ISNULL(SF.Id,0) AS Id,
			M.Title As Module,
			M.Id As ModuleId,
			S.Id AS ScreenId,
			S.Title As ScreenTitle,
			isnull(SF.ScreenFunctionality,'') as Screenfunctionality
		FROM 
			sSecurity.tScreen S 
			INNER join [sSecurity].[tTask] T on S.TaskId = T.Id 
			INNER join [sCommon].[tModuleMaster] M on T.ModuleId = M.Id 
			LEFT JOIN sErp.tScreenFunctionalityMaster SF on SF.ScreeId = S.Id 
		WHERE 
			S.IsObsolete = 0 
			AND (M.Id = @rModuleId OR @rModuleId=0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pScreenFunctionalityMasterAdd]

@rId int,
@rScreenId int,
@rFunctionality nvarchar (2000)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF EXISTS(Select 1 from sErp.tScreenFunctionalityMaster WHERE ScreeId = @rScreenId AND ScreenFunctionality = @rFunctionality)
BEGIN
	    SELECT -103 AS Result
		RETURN
END

BEGIN TRY
BEGIN TRANSACTION



IF EXISTS(Select 1 from sErp.tScreenFunctionalityMaster WHERE @rId = Id)
BEGIN
		UPDATE 
		sErp.tScreenFunctionalityMaster 
		SET 
		ScreeId = @rScreenId,
		ScreenFunctionality = @rFunctionality 
		WHERE Id = @rId
        SELECT 2 AS Result
END
ELSE
BEGIN
		INSERT INTO 
		sErp.tScreenFunctionalityMaster 
		VALUES
		(@rId,
		@rScreenId,
		@rFunctionality)
        SELECT 1 AS Result
END
COMMIT TRANSACTION		
END TRY
BEGIN CATCH 
ROLLBACK TRANSACTION
		SELECT -1 AS Result
		RETURN
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pScreenFunctionalityMasterGet]

	@rModuleId int = 0,
	@rScreenId int = 0,
	@rScreenfunctionalityId int = 0

-- EXEC [sErp].[pScreenFunctionalityMasterGet] 3,0,0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		SF.Id,  
		M.Title As Module,
		M.Id As ModuleId,
		S.Id AS ScreenId,
		S.Title As ScreenTitle,
		--SF.ScreenFunctionality As Screenfunctionality	
		--case when	isnull(SF.ScreenFunctionality,'') then '' else SF.ScreenFunctionality end as Screenfunctionality
		isnull(SF.ScreenFunctionality,'') as Screenfunctionality
    FROM
		sErp.tScreenFunctionalityMaster SF
		LEFT JOIN sSecurity.tScreen S on SF.ScreeId = S.Id
		LEFT JOIN sSecurity.tTask T on T.Id = S.TaskId
		LEFT JOIN sCommon.tModuleMaster M on M.Id = T.ModuleId
	WHERE (M.Id = @rModuleId OR @rModuleId=0)
		--AND  (S.Id = @rScreenId OR @rScreenId=0)
		--AND  (SF.Id = @rScreenfunctionalityId OR @rScreenfunctionalityId=0)
	ORDER BY M.Id,S.Id


--	SELECT  
--		M.Title As Module,
--		M.Id As ModuleId,
--		S.Id AS ScreenId,
--		S.Title As ScreenTitle,
--		isnull(SF.ScreenFunctionality,'') as Screenfunctionality
--		 FROM sSecurity.tScreen S 
--INNER join [sSecurity].[tTask] T on S.TaskId = T.Id 
--INNER join [sCommon].[tModuleMaster] M on T.ModuleId = M.Id 
--LEFT JOIN sErp.tScreenFunctionalityMaster SF on SF.ScreeId = S.Id 
-- WHERE S.IsObsolete = 0 
-- AND
--(M.Id = @rModuleId OR @rModuleId=0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sErp].[pScreenFunctionalityTrainingAdd]
	 @rId int,
	 @rOrgGroupId int,
	 @rScreenFunctionalityId int,
	 @rTrainingRemark nvarchar(max),
	 @rUserName nvarchar(100)
	
	     	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
BEGIN TRANSACTION	

IF(@rId = 0)	
	BEGIN
		INSERT INTO sErp.tScreenFunctionalityTraining
		(
		OrgGroupId,
		ScreenFunctionalityId,
		TrainingRemark,
		UserName
	
		)
		VALUES
		(
		@rOrgGroupId,
		@rScreenFunctionalityId,
		@rTrainingRemark,
		@rUserName
	
		)
		SELECT 1 AS Result
END
ELSE 
BEGIN
		UPDATE  sErp.tScreenFunctionalityTraining
		SET
		OrgGroupId=@rOrgGroupId,
		ScreenFunctionalityId=@rScreenFunctionalityId,	
		TrainingRemark=@rTrainingRemark,
		UserName=@rUserName		
		WHERE AutoId = @rId
		
		SELECT 11 AS Result
END
	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
	ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sErp].[pStudentImagesUpdate]
	@QRcodeImage image,
	@id bigint 
AS
BEGIN 	
	DECLARE @CNT INT
	set @CNT =  (SELECT count(*) from sStudent.tStudentImages where StudentId = @id)
	select @CNT
	if(@CNT = 0)
	BEGIN
	Insert into sStudent.tStudentImages (StudentId,UpdatedDateTime,QRCode)values(@id,Getdate(),@QRcodeImage)
	END
	ELSE
	BEGIN
	Update  sStudent.tStudentImages set QRCode = @QRcodeImage where StudentId = @id
	
	END



END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pStudentStrengthDetailGet]
	 	 
		@rDatabaseName nvarchar(max)='',
		@rOrgGroupId smallint=0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

Declare @strStudentCount VarChar (MAX)
Declare @strFeeReceiptDate VarChar (MAX)
Declare @strExamStatusDate VarChar (MAX)
Declare @strBonafiesCertificateDate VarChar (MAX)
Declare @strLCCertificateDate VarChar (MAX)
Declare @strAttendanceDate VarChar (MAX)
Declare @strEmployeeDate VarChar (MAX)
Declare @strAlertDate VarChar (MAX)
DECLARE @strMobileUserCount varchar(MAX)
--SET @strSQL = 'SELECT * FROM ' + @rDatabaseName+ '.sSetup.tOrgGroupSetting WHERE OrgGroupId = '+ convert (nvarchar,@rOrgGroupId)

			SET @strStudentCount =  'SELECT NoOfStudent FROM '+ @rDatabaseName+'.sSetup.tOrgGroupSetting WHERE '+ 
			+' OrgGroupId ='+ convert (nvarchar,@rOrgGroupId)+' SELECT COUNT(SM.AcademicId) AS ActiveStudent FROM '+ @rDatabaseName+'.sStudent.vStudentAcademic SM '+ 
			+'INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId '+
			+'INNER JOIN '+@rDatabaseName+'.sSetup.tBatchMaster BM ON BM.Id=SM.BatchId  '+
			+'WHERE OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+ ' AND BM.IsActive = 1 and SM.StatusID=1 SELECT COUNT(SM.AcademicId) as TotalStudent FROM '+@rDatabaseName+'.sStudent.vStudentAcademic SM '+ 
			+'INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId '+
			+'INNER JOIN '+@rDatabaseName+'.sSetup.tBatchMaster BM ON BM.Id=SM.BatchId '+
			+' WHERE OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND BM.IsActive = 1'	
			print @strStudentCount	



			SET @strFeeReceiptDate = 'SELECT DATEDIFF(DAY,MAX(FR.CreatedDateTime),sCommon.fGetDate())AS FeeDays,MAX(FR.CreatedDateTime)AS LastFeeDate FROM '+@rDatabaseName+'.sFee.tReceipt FR 
			INNER JOIN '+@rDatabaseName+'.sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=FR.OrgGroupBatchId WHERE OBM.OrgGroupId = '++convert (nvarchar,@rOrgGroupId)

			SET @strExamStatusDate= 'SELECT DATEDIFF(DAY,MAX(ES.UpdatedDateTime),sCommon.fGetDate())AS ExamDays,MAX(ES.UpdatedDateTime)AS LastExamDate FROM '+@rDatabaseName+'.sAssessment.tResult ES'+
			--+' INNER JOIN '+@rDatabaseName+'.sSetup.tDivisionMaster DM ON DM.Id=ES.DivisionId'+
			--+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)
			+' INNER JOIN '+@rDatabaseName+'.sStudent.vStudentAcademic vSA ON vSA.AcademicId =ES.AcademicId '+
			+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)

			SET @strAttendanceDate ='SELECT  DATEDIFF(DAY,MAX(SR.AttendanceDate),sCommon.fGetDate())AS AttendancDays,MAX(SR.AttendanceDate)AS LastAttendanceDate FROM '+@rDatabaseName+'.sAttendance.tStudentRegister SR '+ 
			+'INNER JOIN '+@rDatabaseName+'.sStudent.vStudentAcademic vSA ON vSA.AcademicId =  SR.AcademicId '+
			+'INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)


			SET @strEmployeeDate ='SELECT DATEDIFF(DAY,MAX(EM.CreatedDateTime),sCommon.fGetDate())AS EmployeeDays,MAX(EM.CreatedDateTime)AS LastEmployeeDate FROM '+@rDatabaseName+'.sHrm.tEmployeeMaster EM'+
			+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)

			SET @strAlertDate= 'SELECT DATEDIFF(DAY,MAX(AL.CreatedDateTime),sCommon.fGetDate())AS AlertDays,MAX(AL.CreatedDateTime)AS LastAlertDate FROM '+@rDatabaseName+'.sAlert.tAlertLog AL'+
			+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)

			SET @strBonafiesCertificateDate = 'SELECT DATEDIFF(DAY,MAX(B.CreatedDateTime),sCommon.fGetDate())AS BonafiedDays,MAX(B.CreatedDateTime)AS BonafiedDate FROM '+@rDatabaseName+'.sCertificate.tBonafide  B'+
			+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=B.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)


			SET @strLCCertificateDate = 'SELECT DATEDIFF(DAY,MAX(L.CreatedDateTime),sCommon.fGetDate())AS LCDays,MAX(L.CreatedDateTime)AS LCDate FROM '+@rDatabaseName+'.sCertificate.tLeaving  L'+
			+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=L.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)


			SET @strMobileUserCount = 'SELECT SUM(Registerdcount)as Registerdcount
			FROM(SELECT COUNT (DISTINCT UserId) AS Registerdcount FROM '+@rDatabaseName+'.sCommunication.tRegisteredUsers  RU'+
			+' INNER JOIN '+@rDatabaseName+'.sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId ' + 
			+' INNER JOIN '+@rDatabaseName+'.sSecurity.tUser U ON U.Id=RU.UserId WHERE DeviceToken IS NOT NULL AND U.IsObsolete=0  AND UserSourceTypeId=2003 AND OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+'  Group by RU.OrgId) a'  

			exec (@strStudentCount)
			exec (@strFeeReceiptDate)
			exec (@strExamStatusDate)
			exec (@strBonafiesCertificateDate)
			exec (@strLCCertificateDate)
			exec (@strAttendanceDate)
			exec (@strEmployeeDate)
			exec (@strAlertDate)
			exec (@strMobileUserCount)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pStudentStrengthGet]
	 	
	 	@rOrgId smallint,
		@rCRMLicenceId int,
		@rOrgGroupId smallint,
		@rOrgGroupName nvarchar(200),
		@rCustomerStatusId tinyint,
		@rInstallationTypeId nvarchar(max)='',
		@rChannelId int
		
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		IF (RIGHT(@rInstallationTypeId, 1) = ',')
        SET @rInstallationTypeId = LEFT(@rInstallationTypeId, LEN(@rInstallationTypeId) - 1)

		BEGIN
			SET @rOrgGroupName = sCommon.fSearchStringGet(@rOrgGroupName)
		END
		SELECT 
			CM.CRMLicenceId,
			CSM.Title AS CustomerStatus,
			CM.OrgGroupId,
			CM.Title AS OrgGroupName,
			CM.Db AS DatabaseName,
			CM.InstallationTypeId,
			IM.Title AS InstallationType,
			CM.ChannelId,
			HM.Title AS Channel,
			ISNULL(CA.Title,'') As CampusType
		FROM 
			sErp.tCustomerMaster CM
			INNER JOIN sErp.tCustomerStatusMaster CSM ON CSM.Id = CM.CustomerStatusId AND CM.InstallationTypeId NOT IN (3,5)
			INNER JOIN sErp.tInstallationTypeMaster IM ON IM.Id = CM.InstallationTypeId
			INNER JOIN sErp.tChannelMaster HM ON HM.Id = CM.ChannelId
			LEFT JOIN sErp.tCampusTypeMaster CA ON CA.Id=CM.CampusTypeId
		WHERE 
			(CM.CRMLicenceId = @rCRMLicenceId OR @rCRMLicenceId=0)
			AND (CM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (CM.Title LIKE @rOrgGroupName OR ISNULL(@rOrgGroupName,'') = '')		
			AND (CM.CustomerStatusId = @rCustomerStatusId OR @rCustomerStatusId=0)
			--AND (CM.InstallationTypeId = @rInstallationTypeId OR @rInstallationTypeId=0)
			AND ((CM.InstallationTypeId IN (SELECT item from sCommon.fnSplit(@rInstallationTypeId,',')))  OR  (@rInstallationTypeId = ''))
			AND (CM.ChannelId = @rChannelId OR @rChannelId=0)
			AND((CM.OrgId = @rOrgId)OR (@rOrgId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sErp].[pSupportTicketAdd]

	 @rId int,
	 @rProductId smallint,
	 @rLicenseNo nvarchar(10),
	 @rOrgGroupId int,
	 @rOrgId int,
	 @rModuleId int,
	 @rSupportCategoryId int,
	 @rSupportPriorityId int,
	-- @rDeadlineDate date,
	 --@rDeadlineHour tinyint,
	 --@rDeadlineMinute tinyint,
	 @rIssueDescription nvarchar(max),
	 @rContactName nvarchar(100),
	 @rContactNo nvarchar(50),
	 @rAlternateContactNo nvarchar(50) = '',
	 @rSupportTicketStatusId tinyint,
	 @rUserName nvarchar(100),
	 @rUserId bigint,
	 @rIssueSteps nvarchar(max) = '',
	 @rConvenientStartTime time,
	 @rConvenientEndTime time
	     	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
BEGIN TRANSACTION	

IF(@rId = 0)	
	BEGIN
		INSERT INTO sErp.tSupportTicket
		(
		ProductId,
		OrgGroupId,
		OrgId,
		ModuleId,
		SupportCategoryId,
		SupportPriorityId,
		--DeadlineDate,
		--DeadlineHour, 
		--DeadlineMinute,
		IssueDescription,
		ContactName,
		ContactNo,		
		SupportTicketStatusId,
		UserName,
		CreatedUserId,
		CreatedDateTime,
		LicenseNo,
		AlternateContactNo,
		IssueSteps,
		FromConvenientTime,
		ToConvenientTime
		)
		VALUES
		(
		@rProductId,
		@rOrgGroupId,
		@rOrgId,
		@rModuleId,
		@rSupportCategoryId,
		@rSupportPriorityId,
		--@rDeadlineDate,
		--@rDeadlineHour, 
		--@rDeadlineMinute,
		@rIssueDescription,
		@rContactName,
		@rContactNo,
		@rSupportTicketStatusId,
		@rUserName,
		@rUserId,
		sCommon.fGetDate(),
		@rLicenseNo,
		@rAlternateContactNo,
		@rIssueSteps,
		@rConvenientStartTime,
		@rConvenientEndTime
		)
		
		SELECT @@Identity AS Result
	END	 
ELSE
	BEGIN
		UPDATE  sErp.tSupportTicket
		SET
		ModuleId=@rModuleId,
		SupportCategoryId=@rSupportCategoryId,
		SupportPriorityId=@rSupportPriorityId,			
		--DeadlineDate=@rDeadlineDate,
		--DeadlineHour=@rDeadlineHour,
		--DeadlineMinute=@rDeadlineMinute,
		IssueDescription=@rIssueDescription,			
		ContactName=@rContactName,
		ContactNo=@rContactNo,
		SupportTicketStatusId=@rSupportTicketStatusId,
		UserName=@rUserName,
		UpdatedUserId=@rUserId,
		UpdatedDateTime=sCommon.fGetDate(),
		LicenseNo = @rLicenseNo,
		AlternateContactNo = @rAlternateContactNo,
		IssueSteps = @rIssueSteps,
		FromConvenientTime = @rConvenientStartTime,
		ToConvenientTime = @rConvenientEndTime
		WHERE AutoId = @rId
		
		SELECT -11 AS Result
	END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
	ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sErp].[pSupportTicketGet]

    @rId int=0,
	@rOrgGroupId int=0,
	@rOrgId int=0,
	@rModuleId int=0,
	@rSupportCategoryId int=0,
	@rSupportPriorityId int=0,
	@rSupportTicketStatusId int=0,
	@rFromDeadlineDate date=null,
	@rToDeadlineDate date=null,
	@rVidyalayaTicketNo bigint = 0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			ST.AutoId AS Id,
			ST.ProductId,
			ST.OrgGroupId,
			ST.OrgId,
			ST.ModuleId,
			ST.SupportCategoryId,
			ST.SupportPriorityId,
			ST.DeadlineDate,
			ISNULL(ST.DeadlineHour,0) AS DeadlineHour,
			ISNULL(ST.DeadlineMinute,0) AS DeadlineMinute,
			ISNULL(ST.IssueDescription,'') AS IssueDescription,
			ST.ContactName,
			ISNULL(ST.ContactNo,'') AS ContactNo,
			ST.SupportTicketStatusId,
			ST.UserName,
			ST.CreatedDateTime,
			MM.Title AS Module,
			SCM.Title AS SupportCategory,
			SPM.Title AS SupportPriority,
			STSM.Title AS SupportTicketStatus,
			ISNULL(ST.IssueSteps,'') AS IssueSteps,
			ISNULL(ST.AlternateContactNo,'') AS AlternateContactNo,
			ISNULL(ST.LicenseNo,0) AS LicenseNo,
			ISNULL(ST.FromConvenientTime,'') as FromConvenientTime,
			ISNULL(ST.ToConvenientTime,'') as ToConvenientTime,
			ISNULL(ST.VidyalayaTicketNumber,0) as VidyalayaTicketNumber,
			ISNULL(ST.VidyalayaExecutiveName,'') as VidyalayaExecutiveName,
			ST.TicketClosingDateTime as TicketClosingDateTime
			
	FROM 
			sErp.tSupportTicket ST
			INNER JOIN sCommon.tModuleMaster MM ON MM.Id = ST.ModuleId
			INNER JOIN sErp.tSupportCategoryMaster SCM ON SCM.Id = ST.SupportCategoryId
			INNER JOIN sErp.tSupportPriorityMaster SPM ON SPM.Id = ST.SupportPriorityId
			INNER JOIN sErp.tSupportTicketStatusMaster STSM ON STSM.Id = ST.SupportTicketStatusId
	WHERE
		(ST.AutoId = @rId OR @rId=0)
		AND (ST.OrgGroupId = @rOrgGroupId or @rOrgGroupId = 0)
		AND (ST.OrgId = @rOrgId or @rOrgId = 0)
		AND (ST.ModuleId = @rModuleId OR @rModuleId=0)
		AND (ST.SupportCategoryId = @rSupportCategoryId OR @rSupportCategoryId=0)
		AND (ST.SupportPriorityId = @rSupportPriorityId OR @rSupportPriorityId=0)
		AND (ST.SupportTicketStatusId = @rSupportTicketStatusId OR @rSupportTicketStatusId=0)
		AND ((ST.CreatedDateTime >= @rFromDeadlineDate) OR (ISNULL(@rFromDeadlineDate,'') = ''))
		AND ((ST.CreatedDateTime <=  DATEADD(Day,1,@rToDeadlineDate)) OR (ISNULL(@rToDeadlineDate,'') = ''))
		AND (ST.VidyalayaTicketNumber = @rVidyalayaTicketNo OR @rVidyalayaTicketNo=0)
	ORDER BY ST.AutoId DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pSupportTicketLogAdd]
	 
		
		@rUserId bigint = 0,				
		@rActivity nvarchar(100),
		@rTicketId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	INSERT INTO sErp.tSupportTicketLog
		(			
			CreatedUserId,			
			CreatedDateTime,
			Activity,
			TicketId
		)
	VALUES
		(			
			@rUserId,			
			sCommon.fGetDate(),
			@rActivity,
			@rTicketId
		)
		SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pTripLogGet]
	@rEmployeeId bigint = 0,
	@rUpdatedDateTime DATETIME=''
AS
SET NOCOUNT ON
BEGIN 
SELECT AutoId,EmployeeId,LatitudeAxis,LongitudeAxis,
ISNULL(UpdatedDateTime,'0001/01/01') AS UpdatedDateTime,
UpdatedUserId,FollowupLocation
FROM sErp.tTripLog TL
  WHERE 
      ((TL.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
      AND (( convert(DATE,TL.UpdatedDateTime,102) = @rUpdatedDateTime) OR (@rUpdatedDateTime='')) 
	  Order by TL.AutoId  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sErp].[pTripSummaryEmployeeWiseCheckinCheckout]
	
	@rEmployeeManagerId bigint = 0,
	@rOrgId smallint=0,
    @rIsSearchHierarchyWise smallint = 0,
    @rEmpName nvarchar(30)='',
	@rEmployeeId bigint =0,
	@rFromDate DATETIME='',
	@rToDate DATETIME=''
	
AS
SET NOCOUNT ON
BEGIN 

  CREATE TABLE #TblFinalRecord
		(
			PassingDate date,
			EmployeeId bigint,
			EmployeeCode nvarchar(20),
			EmployeeName nvarchar(50),
			TripStatus nvarchar(20),
			UpdatedDateTime datetime,
			FollowupLocation nvarchar(200),
		)

    IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='#TempEmployeeId')
	BEGIN		
		DROP Table #TempEmployeeId
		 
		DROP TABLE #TblFinalRecord
	END
	
	CREATE TABLE #TempEmployeeId
	(
		EmployeeId bigint
	)
	
	IF(@rIsSearchHierarchyWise = 0)
	BEGIN
	
		 INSERT INTO #TempEmployeeId(EmployeeId)
		 SELECT @rEmployeeManagerId
	
		 INSERT INTO #TempEmployeeId(EmployeeId)
         SELECT
		 EJD.EmployeeID
		 FROM sHrm.tEmployeeJobDetail EJD
		 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		 WHERE ((EmployeeManagerId = @rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
		 

		  
	END
	
	IF(@rIsSearchHierarchyWise = 1)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
			  
			-- AND EM.FirstName like '%'+@rEmpName+'%'
			 	
			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E
    END
    
    IF(@rIsSearchHierarchyWise = 2)
    BEGIN
		INSERT INTO #TempEmployeeId(EmployeeId)
		SELECT EJD.EmployeeId FROM sHrm.tEmployeeJobDetail EJD 
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
		AND((EM.FirstName like '%'+@rEmpName+'%')or(ISNULL(@rEmpName,'')='')) 
    END


INSERT INTO #TblFinalRecord(PassingDate,EmployeeId,EmployeeCode,EmployeeName,TripStatus,FollowupLocation,UpdatedDateTime)
 
		SELECT 
		TL.UpdatedDateTime AS PassingDate,
		EM.Id AS EmployeeId,
		EM.Code AS EmployeeCode, 
		EM.FirstName +' '+ EM.LastName AS EmployeeName,
		CASE 
		WHEN  ISNULL((TL.TripLogStatusId),0)= 4 THEN 'Check In'
		WHEN  ISNULL((TL.TripLogStatusId),0)= 5 THEN 'Check Out'
		ELSE 'NONE'
		END As TripStatus,
		--ISNULL((TL.TripLogStatusId),0) AS TripStatus,
		Isnull(TL.FollowupLocation,'') AS FollowupLocation,
		TL.UpdatedDateTime As TripLogUpdatedDateTime
		
	FROM 
		sErp.tTripLog TL	
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TL.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.Id
		WHERE CONVERT(date,TL.UpdatedDateTime,103) >= @rFromDate 
		AND CONVERT(date,TL.UpdatedDateTime,103) <= @rToDate 
		AND((EM.Id=@rEmployeeId)OR(@rEmployeeId=0))  
		AND  ISNULL(EM.IsOtherUser,0) = 0
		--AND (TL.TripLogStatusId = 4 OR TL.TripLogStatusId = 5)
		AND TL.TripLogStatusId IN(4,5)
		
		ORDER BY EM.Id , TL.UpdatedDateTime 
	 

	SELECT * FROM #TblFinalRecord
	DROP Table #TempEmployeeId
DROP TABLE #TblFinalRecord
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sErp].[pTripSummaryEmployeeWiseDetailsGet]
	
	@rEmployeeManagerId bigint = 0,
	@rFromDate DATETIME='',
	@rToDate DATETIME='',
	@rOrgId smallint=0,
	@rOrgGroupId smallint=0,
    @rIsSearchHierarchyWise smallint = 0,
    @rEmpName nvarchar(30)='',
	@rEmployeeId bigint =0
	
AS
SET NOCOUNT ON
BEGIN 

		CREATE TABLE #TblFinalRecord
		(
			PassingDate date,
			EmployeeId bigint,
			EmployeeCode nvarchar(20),
			EmployeeName nvarchar(50),
			TripDate datetime,
			TripStartTime datetime,
			TripEndTime	datetime ,
			TripStatus int,
			TripDistance decimal(12,2),
			UpdatedDateTime datetime,
			MobileNumber bigint,
			SchoolName nvarchar(200),
			FollowupLocation nvarchar(200),
			WithManager nvarchar(20)
		)

    IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='#TempEmployeeId')
	BEGIN		
		DROP Table #TempEmployeeId
		DROP Table #TempDate
		DROP TABLE #TblFinalRecord
	END
	
	CREATE TABLE #TempEmployeeId
	(
		EmployeeId bigint
	)
	
	IF(@rIsSearchHierarchyWise = 0)
	BEGIN
	
		 INSERT INTO #TempEmployeeId(EmployeeId)
		 SELECT @rEmployeeManagerId
	
		 INSERT INTO #TempEmployeeId(EmployeeId)
         SELECT
		 EJD.EmployeeID
		 FROM sHrm.tEmployeeJobDetail EJD
		 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		 WHERE ((EmployeeManagerId = @rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
		 

		  
	END
	
	IF(@rIsSearchHierarchyWise = 1)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
			  
			-- AND EM.FirstName like '%'+@rEmpName+'%'
			 	
			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E
    END
    
    IF(@rIsSearchHierarchyWise = 2)
    BEGIN
		INSERT INTO #TempEmployeeId(EmployeeId)
		SELECT EJD.EmployeeId FROM sHrm.tEmployeeJobDetail EJD 
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
		AND((EM.FirstName like '%'+@rEmpName+'%')or(ISNULL(@rEmpName,'')='')) 
    END
	CREATE TABLE #TempDate
	(
		Id smallint Identity,
		FromDate date
	)

	DECLARE @StartDate date = @rFromDate
		   ,@EndDate   date = @rToDate

	BEGIN	 
	WITH theDates AS
		 (SELECT @StartDate as theDate
		  UNION ALL
		  SELECT DATEADD(day, 1, CONVERT(date,theDate))
			FROM theDates
		   WHERE DATEADD(day, 1,  CONVERT(date,theDate)) <= @EndDate
		 )
	insert into #TempDate(FromDate)
	SELECT CONVERT(date,theDate) AS FromDate
	  FROM theDates
	OPTION (MAXRECURSION 0)
	END

	DECLARE @lCount Smallint = 0
	SELECT @lCount = Count(*) From #TempDate


CREATE TABLE #TempTable(
Id int identity ,
AutoId int,
EmployeeId bigint,
LatitudeAxis nvarchar(50),
LongitudeAxis nvarchar(50),
UpdatedDateTime datetime,
UpdatedUserId bigint,
FollowupId bigint,
TripLogStatusId int,
TripDistance decimal(10,2),
FollowupLocation nvarchar(max)
)
INSERT INTO #TempTable(AutoId,EmployeeId,LatitudeAxis,LongitudeAxis,UpdatedDateTime,UpdatedUserId,FollowupId,TripLogStatusId,TripDistance,FollowupLocation)
SELECT TL.AutoId,TL.EmployeeId,TL.LatitudeAxis,TL.LongitudeAxis,TL.UpdatedDateTime,TL.UpdatedUserId,TL.FollowupId,TL.TripLogStatusId,TL.TripDistance,TL.FollowupLocation FROM 
sErp.tTripLog TL
INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = TL.EmployeeId
		--INNER JOIN sErp.tLeadFollowup LF on LF.Id = TL.FollowupId 
		WHERE CONVERT(date,TL.UpdatedDateTime) >= @rFromDate AND CONVERT(date,TL.UpdatedDateTime) <= @rToDate
		ORDER BY  TL.AutoId
		
		DECLARE @lTableCount int =0,@lResetCount int =1,@lTripLogStatusId int =0 ,@lFollowupId bigint =0,
		@rTripDistance decimal(12,2)=0,@rTripDistanceSum decimal(10,2)=0,@lTripDate datetime = null,@lTripLogId bigint =0
		SELECT @lTableCount = COUNT(Id) FROM #TempTable;
		
		 
		CREATE TABLE #Distance(
		    TripLogId bigint,
			DistanceSum decimal(10,2),
			FollowupId bigint,
			TripDate datetime
		)
	Declare @lLoopCount int
	
     SET @lLoopCount = 1
		
	 While (@lLoopCount <=  @lTableCount)
	BEGIN
	
	SELECT @lTripLogId = AutoId, @lFollowupId = FollowupId , @lTripLogStatusId =  TripLogStatusId,@rTripDistance=TripDistance,@lTripDate = UpdatedDateTime FROM #TempTable WHERE Id= @lLoopCount 
	AND CONVERT(date,UpdatedDateTime) >= @rFromDate AND CONVERT(date,UpdatedDateTime) <= @rToDate
	
	SET @rTripDistanceSum = @rTripDistanceSum+@rTripDistance
	
	    IF(@lFollowupId > 0 OR @lTripLogStatusId = 1 OR @lTripLogStatusId = 3    )
		 	BEGIN
		 		INSERT INTO #Distance
		 		SELECT @lTripLogId, @rTripDistanceSum,@lFollowupId,@lTripDate
		 		SET @lFollowupId=0
		 		SET @rTripDistanceSum=0
		 		SET @rTripDistance = 0
		 		SET @lTripLogId=0
		 	END
		 				 
		Set @lLoopCount = @lLoopCount + 1
	END
	
		
		
		--WHILE @lTableCount >= @lResetCount
		--BEGIN
		--	SELECT @lFollowupId = FollowupId , @lTripLogStatusId =  TripLogStatusId,@rTripDistance=TripDistance,@lTripDate = UpdatedDateTime FROM #TempTable WHERE Id= @lResetCount 
		--	AND CONVERT(date,UpdatedDateTime) >= @rFromDate AND CONVERT(date,UpdatedDateTime) <= @rToDate
		-- 	IF(@lFollowupId>0)
		-- 	BEGIN
		-- 		INSERT INTO #Distance
		-- 		SELECT @rTripDistanceSum,@lFollowupId,@lTripDate
		-- 		SET @lFollowupId=0
		-- 		SET @rTripDistanceSum=0
		-- 	END
			 
		--		SET @rTripDistanceSum = @rTripDistanceSum+@rTripDistance
			 
			
		--	SET @lResetCount = @lResetCount+1
		--END
		
		--SELECT * FROM #Distance






--While(@lCount > 0)
--	BEGIN 
--DECLARE @lTempFromDate date, @lTempToDate date

--Select @lTempFromDate = FromDate, @lTempToDate = FromDate From #TempDate Where Id = @lCount

--SET @rFromDate = @lTempFromDate 
--SET @rToDate = @lTempToDate
INSERT INTO #TblFinalRecord(PassingDate,EmployeeId,EmployeeCode,EmployeeName,TripDate,TripStartTime
,TripEndTime,TripStatus,TripDistance,UpdatedDateTime,MobileNumber,SchoolName,FollowupLocation,WithManager)
 
		SELECT 
		TL.UpdatedDateTime AS PassingDate,
		EM.Id AS EmployeeId,
		EM.Code AS EmployeeCode, 
		EM.FirstName +' '+ EM.LastName AS EmployeeName,
		( SELECT MAX(UpdatedDateTime) FROM sErp.tTripLog TL  WHERE TL.EmployeeId = EM.Id 
		AND CONVERT(date,UpdatedDateTime) >= @rFromDate AND CONVERT(date,UpdatedDateTime) <= @rToDate) AS TripDate,
		
		( SELECT ISNULL(MIN(TL.UpdatedDateTime),0) FROM sErp.tTripLog TL WHERE TL.EmployeeId = EM.Id 
		  AND CONVERT(date,UpdatedDateTime) >= @rFromDate AND CONVERT(date,UpdatedDateTime) <= @rToDate
		  ) AS TripStartTime,
		  
		( SELECT ISNULL(MAX(TL.UpdatedDateTime),0) FROM sErp.tTripLog TL WHERE TL.EmployeeId = EM.Id
		  AND CONVERT(date,UpdatedDateTime) >= @rFromDate AND CONVERT(date,UpdatedDateTime) <= @rToDate
		  ) AS TripEndTime,
		  
			ISNULL((TL.TripLogStatusId),0) AS TripStatus,  
		   
		ISNULL(D.DistanceSum,0) AS TripDistance,
		(LF.CreatedDateTime)  AS UpdatedDateTime,
		  (SELECT ISNULL(EC.MobileNumber,'') FROM sHrm.tEmployeeCommunications EC WHERE EC.EmployeeId = EM.Id) AS MobileNumber,
		  ISNULL(LM.Title,'')+ ' , '+ + ISNULL(LM.AreaName,'') + ' , ' + ISNULL(LM.CityName,'')  AS SchoolName,
		  Isnull(TL.FollowupLocation,'') AS FollowupLocation
    ,
     CASE
    WHEN ISNULL(LF.WithManagerEmployeeId,0) = 0  THEN 'NO'
    WHEN ISNULL(LF.WithManagerEmployeeId,0) != 0 THEN 'YES'
    ELSE 'NO'
    END AS WithManager
		  --ISNULL((SELECT COUNT(LF.Id)  FROM sErp.tLeadFollowup WHERE LF.FollowupEmployeeId =EM.Id 
		  --AND CONVERT(date,FollowupDate) >= @rFromDate AND CONVERT(date,FollowupDate) <= @rToDate  
		  --AND LF.IsPhysical = 0),0) AS OtherCount
	FROM 
		sErp.tTripLog TL
		INNER JOIN sErp.tLeadFollowup LF on LF.Id = TL.FollowupId  --and LF.FollowupDate=@rFromDate
		INNER JOIN sErp.tLeadMaster LM ON LM.Id = LF.LeadId	
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = LF.FollowupEmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.Id
		INNER JOIN #Distance D ON D.FollowupId = LF.Id
		WHERE ((EM.Id=@rEmployeeId)OR(@rEmployeeId=0)) AND LF.FollowupTypeId = 1 AND  ISNULL(EM.IsOtherUser,0) = 0
		AND CONVERT(date,LF.CreatedDateTime) >= @rFromDate 
		AND CONVERT(date,LF.CreatedDateTime) <= @rToDate
	--ORDER BY  EM.Code,TL.AutoId	
		ORDER BY EM.Id , TL.UpdatedDateTime 
	 

	SET @lCount = @lCount - 1
	--END
	SELECT * FROM #TblFinalRecord
	DROP Table #TempEmployeeId
DROP Table #TempDate
DROP TABLE #TblFinalRecord
DROP TABLE #TempTable
DROP TABLE  #Distance
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sErp].[pTripSummaryEmployeeWiseGet]
	
	@rEmployeeManagerId bigint = 0,
	@rFromDate DATETIME='',
	@rToDate DATETIME='',
	@rOrgId smallint=0,
	@rOrgGroupId smallint=0,
    @rIsSearchHierarchyWise smallint = 0,
    @rEmpName nvarchar(30)='',
	@rEmployeeId bigint =0
	
AS
SET NOCOUNT ON
BEGIN 

		CREATE TABLE #TblFinalRecord
		(
			PassingDate date,
			EmployeeId bigint,
			EmployeeCode nvarchar(20),
			EmployeeName nvarchar(50),
			TripDate datetime,
			TripStartTime datetime,
			TripEndTime	datetime ,
			TripStatus int,
			TripDistance decimal(12,2),
			UpdatedDateTime datetime,
			MobileNumber bigint,
			PhysicalCount int,
			CallCount int,
			MailCount int
		)

    IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='#TempEmployeeId')
	BEGIN		
		DROP Table #TempEmployeeId
		DROP Table #TempDate
		DROP TABLE #TblFinalRecord
	END
	
	CREATE TABLE #TempEmployeeId
	(
		EmployeeId bigint
	)
	
	IF(@rIsSearchHierarchyWise = 0)
	BEGIN
	
		 INSERT INTO #TempEmployeeId(EmployeeId)
		 SELECT @rEmployeeManagerId
	
		 INSERT INTO #TempEmployeeId(EmployeeId)
         SELECT
		 EJD.EmployeeID
		 FROM sHrm.tEmployeeJobDetail EJD
		 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		 WHERE ((EmployeeManagerId = @rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
		 

		  
	END
	
	IF(@rIsSearchHierarchyWise = 1)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rEmployeeManagerId) OR (@rEmployeeManagerId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
			-- AND EM.FirstName like '%'+@rEmpName+'%'
			 	
			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E
    END
    
    IF(@rIsSearchHierarchyWise = 2)
    BEGIN
		INSERT INTO #TempEmployeeId(EmployeeId)
		SELECT EJD.EmployeeId FROM sHrm.tEmployeeJobDetail EJD 
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
		AND((EM.FirstName like '%'+@rEmpName+'%')or(ISNULL(@rEmpName,'')='')) 
    END
	CREATE TABLE #TempDate
	(
		Id smallint Identity,
		FromDate date
	)

	DECLARE @StartDate date = @rFromDate
		   ,@EndDate   date = @rToDate

	BEGIN	 
	WITH theDates AS
		 (SELECT @StartDate as theDate
		  UNION ALL
		  SELECT DATEADD(day, 1, CONVERT(date,theDate))
			FROM theDates
		   WHERE DATEADD(day, 1,  CONVERT(date,theDate)) <= @EndDate
		 )
	insert into #TempDate(FromDate)
	SELECT CONVERT(date,theDate) AS FromDate
	  FROM theDates
	OPTION (MAXRECURSION 0)
	END

	DECLARE @lCount Smallint = 0
	SELECT @lCount = Count(*) From #TempDate


While(@lCount > 0)
	BEGIN 
DECLARE @lTempFromDate date, @lTempToDate date

Select @lTempFromDate = FromDate, @lTempToDate = FromDate From #TempDate Where Id = @lCount

SET @rFromDate = @lTempFromDate 
SET @rToDate = @lTempToDate

INSERT INTO #TblFinalRecord(PassingDate,EmployeeId,EmployeeCode,EmployeeName,TripDate,TripStartTime
,TripEndTime,TripStatus,TripDistance,UpdatedDateTime,MobileNumber,PhysicalCount,CallCount,MailCount)
 
		SELECT 
		@rFromDate AS PassingDate,
		EM.Id AS EmployeeId,
		EM.Code AS EmployeeCode, 
		EM.FirstName +' '+ EM.LastName AS EmployeeName,
		( SELECT MAX(UpdatedDateTime) FROM sErp.tTripLog TL  WHERE TL.EmployeeId = EM.Id 
		AND CONVERT(date,UpdatedDateTime) >= @rFromDate AND CONVERT(date,UpdatedDateTime) <= @rToDate) AS TripDate,
		
		( SELECT ISNULL(MIN(TL.UpdatedDateTime),0) FROM sErp.tTripLog TL WHERE TL.EmployeeId = EM.Id 
		  AND CONVERT(date,UpdatedDateTime) >= @rFromDate AND CONVERT(date,UpdatedDateTime) <= @rToDate
		  ) AS TripStartTime,
		  
		( SELECT ISNULL(MAX(TL.UpdatedDateTime),0) FROM sErp.tTripLog TL WHERE TL.EmployeeId = EM.Id
		  AND CONVERT(date,UpdatedDateTime) >= @rFromDate AND CONVERT(date,UpdatedDateTime) <= @rToDate
		  ) AS TripEndTime,
		  
			ISNULL(( SELECT TOP(1) TripLogStatusId FROM sErp.tTripLog TL WHERE EmployeeId = EM.Id 
		  AND TripLogStatusId NOT IN(0) 
		  AND CONVERT(date,UpdatedDateTime) >= @rFromDate AND CONVERT(date,UpdatedDateTime) <= @rToDate
		  ORDER BY UpdatedDateTime DESC,AutoId DESC
		  ),0) AS TripStatus,  
		   
		( SELECT SUM(ISNULL(TL.TripDistance,0)) FROM sErp.tTripLog TL 
			 WHERE TL.EmployeeId = EM.Id AND CONVERT(date,UpdatedDateTime) >= @rFromDate 
			 AND CONVERT(date,UpdatedDateTime) <= @rToDate
		  ) AS TripDistance,
		( SELECT MAX(UpdatedDateTime) FROM sErp.tTripLog TL  WHERE TL.EmployeeId = EM.Id AND TripLogStatusId = 2 
		  AND CONVERT(date,UpdatedDateTime) >= @rFromDate AND CONVERT(date,UpdatedDateTime) <= @rToDate
		  ) AS UpdatedDateTime,
		  (SELECT ISNULL(EC.MobileNumber,'') FROM sHrm.tEmployeeCommunications EC WHERE EC.EmployeeId = EM.Id) AS MobileNumber,
		  
		  ISNULL((SELECT COUNT(LF.Id)  FROM sErp.tLeadFollowup LF  
		  WHERE LF.FollowupEmployeeId =EM.Id AND  LF.FollowupTypeId=1  
		  AND CONVERT(date,LF.FollowupDate) >= @rFromDate AND CONVERT(date,LF.FollowupDate) <= @rToDate),0) 
		  AS PhysicalCount,
		  
		   ISNULL((SELECT COUNT(LF.Id)  FROM sErp.tLeadFollowup LF  
		  WHERE LF.FollowupEmployeeId =EM.Id AND  LF.FollowupTypeId=2 
		  AND CONVERT(date,LF.FollowupDate) >= @rFromDate AND CONVERT(date,LF.FollowupDate) <= @rToDate),0)
		   AS CallCount,
		  
		   ISNULL((SELECT COUNT(LF.Id)  FROM sErp.tLeadFollowup LF  
		  WHERE LF.FollowupEmployeeId =EM.Id AND  LF.FollowupTypeId=3 
		   AND CONVERT(date,LF.FollowupDate) >= @rFromDate AND CONVERT(date,LF.FollowupDate) <= @rToDate),0) 
		   AS MailCount
		  -- ,
		  
		  --ISNULL((SELECT COUNT(LF.Id)  FROM sErp.tLeadFollowup WHERE LF.FollowupEmployeeId =EM.Id 
		  --AND CONVERT(date,FollowupDate) >= @rFromDate AND CONVERT(date,FollowupDate) <= @rToDate  
		  --AND LF.IsPhysical = 0),0) AS OtherCount
	FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.Id
		WHERE ((EM.Id=@rEmployeeId)OR(@rEmployeeId=0)) AND  ISNULL(EM.IsOtherUser,0) = 0

	ORDER BY  EM.Code 
	SET @lCount = @lCount - 1
	END
	SELECT * FROM #TblFinalRecord
	DROP Table #TempEmployeeId
DROP Table #TempDate
DROP TABLE #TblFinalRecord
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sErp].[ptTripLogAdd]    
	
	@rEmployeeId bigint,
	@rLatitudeAxis nvarchar(20)='',
	@rLongitudeAxis nvarchar(20)='',
	@rUpdatedDateTime DATETIME='',
	@rUpdatedUserId bigint=0,
	@rFollowupId bigint = 0,
	@rTripLogStatusId tinyint = 0,
	@rTripDistance decimal(10,2)= 0.00,
	@rFollowupLocation nvarchar(200)='',
	@rBaseDisplacement decimal(10,2) =0.00,
	@rIsManual bit =0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		INSERT INTO [sErp].[tTripLog]
           ([EmployeeId],[LatitudeAxis],[LongitudeAxis],[UpdatedDateTime],[UpdatedUserId],[FollowupId],[TripLogStatusId],[TripDistance],[FollowupLocation],[BaseDisplacement] ,[IsManual])
     VALUES
           (@rEmployeeId,
           @rLatitudeAxis,
           @rLongitudeAxis,
           CASE WHEN @rIsManual = 1 THEN @rUpdatedDateTime ELSE sCommon.fGetDate()END,
           @rUpdatedUserId,
           @rFollowupId,
           @rTripLogStatusId,
           @rTripDistance,
           @rFollowupLocation,
           @rBaseDisplacement,
           @rIsManual)
		SELECT 1 AS Result 
		SELECT EM.FirstName +' '+ EM.LastName AS EmployeeName,CASE WHEN @rIsManual = 1 THEN @rUpdatedDateTime ELSE sCommon.fGetDate()END As CheckInTime FROM sHrm.tEmployeeMaster EM WHERE Id = @rEmployeeId
		SELECT Id As UserId FROM [sSecurity].[tUser] WHERE SourceId = @rEmployeeId AND SourceTypeId = 95
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pVcpMasterAdd]
	 @rOrgId smallint,
	 @rId int, 
	 @rTitle nvarchar(200),	
	 @rAssignedTerritory nvarchar(500),
	 @rCreatedUserId bigint, 
	 @rUpdatedUserId bigint ,
	 @rIsActive bit = 0
	      	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgId=@rOrgId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sErp.tLeadChannelPartnerMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sErp.tLeadChannelPartnerMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tLeadChannelPartnerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tLeadChannelPartnerMaster
		(
			Id
      ,OrgId
      ,Title
      ,IsActive
      ,AssignedTerritory
      ,CreatedUserId
      ,CreatedDateTime
      ,UpdatedUserId
      ,UpdatedDateTime
      
		)
	VALUES
		(
		 @lNextNumber
      , @rOrgId
      , @rTitle
      , @rIsActive
      ,@rAssignedTerritory
      , @rCreatedUserId
      , sCommon.fGetDate()
      , @rUpdatedUserId
      , sCommon.fGetDate()
      
		)
		    SELECT 1 AS Result
	END	 
	
	ELSE
	
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tLeadChannelPartnerMaster
	    SET
      Title=@rTitle
      ,IsActive = @rIsActive
      ,AssignedTerritory = @rAssignedTerritory
      ,UpdatedUserId=@rUpdatedUserId
      ,UpdatedDateTime=sCommon.fGetDate()
     
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sErp].[pVcpMasterGet]
@rId int,
		@rOrgId smallint=0,
		@rTitle nvarchar(200) =null,
		@rAssignedTerritory nvarchar(500) = null,
		@rIsWildCardSearch bit

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF @rIsWildCardSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
	      LCM.Id,
	      LCM.OrgId,
	      LCM.Title,	  
	      LCM.IsActive,
	      LCM.AssignedTerritory
	FROM 
			sErp.tLeadChannelPartnerMaster LCM
	WHERE 
	(LCM.OrgId = @rOrgId)	
		AND	((LCM.Id = @rId) OR (@rId = 0))	
	AND ((LCM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((LCM.Title Like @rAssignedTerritory)OR(ISNULL(@rAssignedTerritory,'') = ''))
		ORDER BY LCM.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pVersionCurrentNoGet]
	 	 
		@rDatabaseName nvarchar(max)=''
		--@rOrgGroupId smallint=0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 


Declare @strVersionNumber VarChar (MAX)
	
 SET  @strVersionNumber='SELECT VersionNumber FROM '+@rDatabaseName+'.sSystem.tDatabaseInfo WHERE ApplicationId=1'


		exec (@strVersionNumber)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pVersionDetailGet]
	 		   @rOrgId smallint,
		@rCRMLicenceId int,
		@rOrgGroupId smallint,
		@rOrgGroupName nvarchar(200),
		@rCustomerStatusId tinyint,
		@rInstallationTypeId tinyint,
		@rChannelId int
		
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

		BEGIN
			SET @rOrgGroupName = sCommon.fSearchStringGet(@rOrgGroupName)
		END
		SELECT 
			CM.CRMLicenceId,
			CSM.Title AS CustomerStatus,
			CM.OrgGroupId,
			CM.Title AS OrgGroupName,
			CM.Db AS DatabaseName,
			CM.InstallationTypeId,
			IM.Title AS InstallationType,
			CM.ChannelId,
			HM.Title AS Channel
		FROM 
			sErp.tCustomerMaster CM
			INNER JOIN sErp.tCustomerStatusMaster CSM ON CSM.Id = CM.CustomerStatusId AND CM.InstallationTypeId NOT IN (3,5)
			INNER JOIN sErp.tInstallationTypeMaster IM ON IM.Id = CM.InstallationTypeId
			INNER JOIN sErp.tChannelMaster HM ON HM.Id = CM.ChannelId
		WHERE 
			(CM.CRMLicenceId = @rCRMLicenceId OR @rCRMLicenceId=0)
			AND (CM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (CM.Title LIKE @rOrgGroupName OR ISNULL(@rOrgGroupName,'') = '')		
			AND (CM.CustomerStatusId = @rCustomerStatusId OR @rCustomerStatusId=0)
			AND (CM.InstallationTypeId = @rInstallationTypeId OR @rInstallationTypeId=0)
			AND (CM.ChannelId = @rChannelId OR @rChannelId=0)
			 AND((CM.OrgId = @rOrgId)OR (@rOrgId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pVersionUpdate]
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
DECLARE @lCurrentVersionId int , @lReleaseDate Date
SELECT @lCurrentVersionId = VersionId FROM sSystem.tDatabaseInfo

--concat 20 for fullYear (like replace 23 to 2023)
DECLARE @lVersionId int = CONVERT(nvarchar,20)+CONVERT(nvarchar,@lCurrentVersionId)

SELECT @lReleaseDate = ReleaseDate FROM SapphireERP.sErp.tReleaseNote WHERE VersionId = @lVersionId
SELECT 
	Id,
	ReleaseDate,
	VersionNumber,
	VersionId

FROM SapphireERP.sErp.tReleaseNote WHERE ReleaseDate > @lReleaseDate AND IsObsolete = 0  Order By ReleaseDate


--Select * from [sSystem].[tVersionUpdate]
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sErp].[pVersionUpdateDetailsGet]
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
DECLARE @lCurrentVersionId int , @lReleaseDate Date
SELECT @lCurrentVersionId = VersionId FROM sSystem.tDatabaseInfo

--concat 20 for fullYear (like replace 23 to 2023)
DECLARE @lVersionId int = CONVERT(nvarchar,20)+CONVERT(nvarchar,@lCurrentVersionId)

SELECT @lReleaseDate = ReleaseDate FROM SapphireERP.sErp.tReleaseNote WHERE VersionId = @lVersionId
SELECT 
	Id,
	ReleaseDate,
	VersionNumber,
	VersionId

FROM SapphireERP.sErp.tReleaseNote WHERE ReleaseDate > @lReleaseDate AND IsObsolete = 0  Order By ReleaseDate


--Select * from [sSystem].[tVersionUpdate]
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec  [sErp].[pWindowsSupportTicketGet] 47 , '2020-06-22'
CREATE OR ALTER PROCEDURE [sErp].[pWindowsSupportTicketGet]

    @rId int=0,
	--@rOrgGroupId int=0,
	--@rOrgId int=0,
	--@rModuleId int=0,
	--@rSupportCategoryId int=0,
	--@rSupportPriorityId int=0,
	--@rSupportTicketStatusId int=0,
	--@rFromDeadlineDate date=null,
	--@rToDeadlineDate date=null,
	@rUpdatedDate datetime = null
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			ST.AutoId AS Id,
			ST.ProductId,
			ST.OrgGroupId,
			ST.OrgId,
			ST.ModuleId,
			ST.SupportCategoryId,
			ST.SupportPriorityId,
			ST.DeadlineDate,
			ISNULL(ST.DeadlineHour,0) AS DeadlineHour,
			ISNULL(ST.DeadlineMinute,0) AS DeadlineMinute,
			ISNULL(ST.IssueDescription,'') AS IssueDescription,
			ST.ContactName,
			ISNULL(ST.ContactNo,'') AS ContactNo,
			ST.SupportTicketStatusId,
			ST.UserName,
			ST.CreatedDateTime,
			MM.Title AS Module,
			SCM.Title AS SupportCategory,
			SPM.Title AS SupportPriority,
			STSM.Title AS SupportTicketStatus,
			ISNULL(ST.IssueSteps,'') AS IssueSteps,
			ISNULL(ST.AlternateContactNo,'') AS AlternateContactNo,
			ISNULL(ST.LicenseNo,0) AS LicenseNo,
			ISNULL(ST.FromConvenientTime,'') as FromConvenientTime,
			ISNULL(ST.ToConvenientTime,'') as ToConvenientTime,
			1 as Flag,
			ST.UpdatedDateTime
	FROM 
			sErp.tSupportTicket ST
			INNER JOIN sCommon.tModuleMaster MM ON MM.Id = ST.ModuleId
			INNER JOIN sErp.tSupportCategoryMaster SCM ON SCM.Id = ST.SupportCategoryId
			INNER JOIN sErp.tSupportPriorityMaster SPM ON SPM.Id = ST.SupportPriorityId
			INNER JOIN sErp.tSupportTicketStatusMaster STSM ON STSM.Id = ST.SupportTicketStatusId
	WHERE
		(ST.AutoId >= @rId OR @rId=0)
		--AND (ST.OrgGroupId = @rOrgGroupId or @rOrgGroupId = 0)
		--AND (ST.OrgId = @rOrgId or @rOrgId = 0)
		--AND (ST.ModuleId = @rModuleId OR @rModuleId=0)
		--AND (ST.SupportCategoryId = @rSupportCategoryId OR @rSupportCategoryId=0)
		--AND (ST.SupportPriorityId = @rSupportPriorityId OR @rSupportPriorityId=0)
		--AND (ST.SupportTicketStatusId = @rSupportTicketStatusId OR @rSupportTicketStatusId=0)
		--AND ((ST.CreatedDateTime >= @rFromDeadlineDate) OR (ISNULL(@rFromDeadlineDate,'') = ''))
		--AND ((ST.CreatedDateTime <=  DATEADD(Day,1,@rToDeadlineDate)) OR (ISNULL(@rToDeadlineDate,'') = ''))
		--AND ((ST.UpdatedDateTime >=  @rUpdatedDate) OR (ISNULL(@rUpdatedDate,'') = ''))
	--ORDER BY ST.AutoId DESC
UNION ALL
	SELECT 
			ST.AutoId AS Id,
			ST.ProductId,
			ST.OrgGroupId,
			ST.OrgId,
			ST.ModuleId,
			ST.SupportCategoryId,
			ST.SupportPriorityId,
			ST.DeadlineDate,
			ISNULL(ST.DeadlineHour,0) AS DeadlineHour,
			ISNULL(ST.DeadlineMinute,0) AS DeadlineMinute,
			ISNULL(ST.IssueDescription,'') AS IssueDescription,
			ST.ContactName,
			ISNULL(ST.ContactNo,'') AS ContactNo,
			ST.SupportTicketStatusId,
			ST.UserName,
			ST.CreatedDateTime,
			MM.Title AS Module,
			SCM.Title AS SupportCategory,
			SPM.Title AS SupportPriority,
			STSM.Title AS SupportTicketStatus,
			ISNULL(ST.IssueSteps,'') AS IssueSteps,
			ISNULL(ST.AlternateContactNo,'') AS AlternateContactNo,
			ISNULL(ST.LicenseNo,0) AS LicenseNo,
			ISNULL(ST.FromConvenientTime,'') as FromConvenientTime,
			ISNULL(ST.ToConvenientTime,'') as ToConvenientTime,
			2 as Flag,
			ST.UpdatedDateTime
	FROM 
			sErp.tSupportTicket ST
			INNER JOIN sCommon.tModuleMaster MM ON MM.Id = ST.ModuleId
			INNER JOIN sErp.tSupportCategoryMaster SCM ON SCM.Id = ST.SupportCategoryId
			INNER JOIN sErp.tSupportPriorityMaster SPM ON SPM.Id = ST.SupportPriorityId
			INNER JOIN sErp.tSupportTicketStatusMaster STSM ON STSM.Id = ST.SupportTicketStatusId
	WHERE
		(ST.AutoId < @rId OR @rId=0)
		--AND 
		--(ST.OrgGroupId = @rOrgGroupId or @rOrgGroupId = 0)
		--AND (ST.OrgId = @rOrgId or @rOrgId = 0)
		--AND (ST.ModuleId = @rModuleId OR @rModuleId=0)
		--AND (ST.SupportCategoryId = @rSupportCategoryId OR @rSupportCategoryId=0)
		--AND (ST.SupportPriorityId = @rSupportPriorityId OR @rSupportPriorityId=0)
		--AND (ST.SupportTicketStatusId = @rSupportTicketStatusId OR @rSupportTicketStatusId=0)
		--AND ((ST.CreatedDateTime >= @rFromDeadlineDate) OR (ISNULL(@rFromDeadlineDate,'') = ''))
		--AND ((ST.CreatedDateTime <=  DATEADD(Day,1,@rToDeadlineDate)) OR (ISNULL(@rToDeadlineDate,'') = ''))
		AND ((ST.UpdatedDateTime >=  @rUpdatedDate) OR (ISNULL(@rUpdatedDate,'') = ''))
	ORDER BY ST.AutoId DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
CREATE OR ALTER PROCEDURE   [sErp].[pWorkStatusGet]

	@rEmployeeId bigint =0, 
	@rFromDate DATETIME='',
	@rToDate DATETIME='',
	@rOrgId smallint=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

------------- For Visit Type ---------------------------
		
	DECLARE @lTypeTotal table(
		FollowupTypeId int,
		FollowupCount int
		)
	DECLARE @lTypeEffective table(
		FollowupTypeId int,
		FollowupCount int
		)
	DECLARE @lTypeSchool table(
		FollowupTypeId int,
		FollowupCount int
		)
		DECLARE @lTypeNewSchool table(
		FollowupTypeId int,
		FollowupCount int
		)
		
		INSERT INTO @lTypeTotal		
		SELECT  LF.FollowupTypeId, ISNULL(count(LF.Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
		Group By FollowupTypeId
		 
		 
		INSERT INTO @lTypeEffective
				SELECT  LF.FollowupTypeId, ISNULL(count(LF.Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     AND NonEffective = 1
		Group By FollowupTypeId
		
				
 		INSERT INTO @lTypeSchool
		SELECT  LF.FollowupTypeId, ISNULL(count(Distinct LF.LeadId),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     AND NonEffective = 1
		Group By FollowupTypeId
	
	
INSERT INTO @lTypeNewSchool

SELECT LF.FollowupTypeId,ISNULL(Count(LF.LeadId),0) FROM sErp.tLeadFollowup LF INNER JOIN
(

	SELECT LF.LeadId FROM sErp.tLeadFollowup LF
	INNER JOIN
	(
	
	SELECT DISTINCT LF.LeadId
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		 (( LF.FollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))	  
		  AND (( LF.FollowupDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     ) L ON LF.LeadId = L.LeadId 
	     WHERE 
		 (( LF.FollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))	  
		  AND (( LF.FollowupDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     GROUP BY LF.LeadId Having count(LF.LeadId) = 1
	     )
	       A ON LF.LeadId = A.LeadId
	  WHERE 
		 (( LF.FollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))	  
		  AND (( LF.FollowupDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))     
	       GROUP BY LF.FollowupTypeId
	
	 	
 SELECT Id AS FollowupTypeId, Title AS FollowupType,
 ISNULL(TT.FollowupCount,0) AS TypeTotal,
 ISNULL(TE.FollowupCount,0) AS TypeEffective,
 ISNULL(TS.FollowupCount,0) AS TypeSchool,
 ISNULL(TN.FollowupCount,0) AS TypenewSchool
 FROM sErp.tFollowupTypeMaster FTM
 LEFT JOIN @lTypeTotal TT ON  FTM.Id = 	TT.FollowupTypeId
 LEFT JOIN @lTypeEffective TE ON FTM.Id = 	TE.FollowupTypeId
 LEFT JOIN @lTypeSchool TS ON FTM.Id = 	TS.FollowupTypeId
 LEFT JOIN @lTypeNewSchool TN ON FTM.Id = 	TN.FollowupTypeId
 
 ------------- For Lead Status ---------------------------

	DECLARE @lStatusTotal table(
		LeadStatusId int,
		FollowupCount int
		)
		
	--DECLARE @lStatusDistinct table(
	--	LeadStatusId int,
	--	FollowupCount int
	--	)
		
	DECLARE @lStatusSchool table(
		LeadStatusId int,
		FollowupCount int
		)

		INSERT INTO @lStatusTotal		
		SELECT  LF.LeadStatusId, ISNULL(count(LF.Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
		Group By LeadStatusId



		INSERT INTO @lStatusSchool		
		SELECT  LF.LeadStatusId, ISNULL(count( DISTINCT  LF.LeadId),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
		Group By LeadStatusId

		--INSERT INTO @lStatusSchool
		
		--SELECT  LM.LeadStatusId, ISNULL(count(LM.Id),0) FROM
		--(	
	
		--SELECT DISTINCT LF.LeadId
		--FROM		
		--sErp.tLeadFollowup LF
		--WHERE 
		--(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 --   AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 --    AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	 --    ) A INNER JOIN sErp.tLeadMaster LM on A.LeadId = LM.Id
	 --    Group By LM.LeadStatusId
	     


SELECT * FROM
(	
 SELECT Id AS LeadStatusId, Title AS LeadStatusType,
 ISNULL(TT.FollowupCount,0) AS StatusTotal, 
 ISNULL(TS.FollowupCount,0) AS StatusSchool
 
 FROM sErp.tLeadStatusMaster FTM
 LEFT JOIN @lStatusTotal TT ON  FTM.Id = 	TT.LeadStatusId  
 LEFT JOIN @lStatusSchool TS ON FTM.Id = 	TS.LeadStatusId
 ) A WHERE A.StatusTotal > 0
  

------------- For Leave ---------------------------
	    
	 SELECT  L.FromDate AS LeaveFromDate, L.ToDate AS LeaveToDate ,LPM.Title AS LeaveType
	 
	 FROM sHrm.tLeave L INNER JOIN sHrm.tLeavePeriodMaster LPM
	 ON L.LeavePeriodId = LPM.Id
	 WHERE
	 (( L.FromDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( L.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND((L.EmployeeId = @rEmployeeId)OR(@rEmployeeId=0))

------------- For Manager ---------------------------

	CREATE TABLE #TempEmployeeId
	(
		EmployeeId bigint
	);
	
 
			WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rEmployeeId) OR (@rEmployeeId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
			-- AND EM.FirstName like '%'+@rEmpName+'%'
			 	
			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 AND EM.StatusId = 7 AND  ISNULL(EM.IsOtherUser,0) = 0
			) 
			INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E	    
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT @rEmployeeId
		
 
	    SELECT
	    EM.Id AS EmployeeId,
	    EM.FirstName + ' ' + EM.LastName AS EmployeeName,
	    EM.Code AS EmployeeCode,
	   (SELECT  ISNULL(count(Id),0) 
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		EM.Id = LF.FollowupEmployeeId
		AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND LF.WithManagerEmployeeId > 100
	    AND LF.FollowupTypeId = 1		 
	     ) AS PhysicalWithManager,
	     
	    (SELECT  ISNULL(count(Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		EM.Id = LF.FollowupEmployeeId
		AND(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND LF.WithManagerEmployeeId > 100
	    AND LF.FollowupTypeId = 2		 
	     ) AS CallWithManager,	     
	     
	 --  	(SELECT  ISNULL(count(Id),0)
		--FROM		
		--sErp.tLeadFollowup LF
		--WHERE 
		--EM.Id = LF.FollowupEmployeeId
		--AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 --   AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 --   AND LF.WithManagerEmployeeId IS NOT NULL
	 --   AND LF.FollowupTypeId = 3		 
	 --    ) AS MailWithManager,
	     
	   	(SELECT  ISNULL(count(LF.Id),0) 
		FROM		
		sErp.tLeadFollowup LF INNER JOIN sErp.tLeadMaster LM
		ON LF.LeadId = LM.Id
		WHERE 
		EM.Id = LM.LeadOwnerEmployeeId
		AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND LF.FollowupEmployeeId <> LM.LeadOwnerEmployeeId AND LF.FollowupEmployeeId > 100
	    AND LF.FollowupTypeId = 1		 
	     ) AS PhysicalManager ,
	     
	    (SELECT  ISNULL(count(LF.Id),0) 
		FROM		
		sErp.tLeadFollowup LF INNER JOIN sErp.tLeadMaster LM
		ON LF.LeadId = LM.Id
		WHERE 
		EM.Id = LM.LeadOwnerEmployeeId
		AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND LF.FollowupEmployeeId <> LM.LeadOwnerEmployeeId AND LF.FollowupEmployeeId > 100
	    AND LF.FollowupTypeId = 2		 
	     ) AS CallManager 
	     --,
	     
	 --   (SELECT  ISNULL(count(LF.Id),0) 
		--FROM		
		--sErp.tLeadFollowup LF INNER JOIN sErp.tLeadMaster LM
		--ON LF.LeadId = LM.Id
		--WHERE 
		--EM.Id = LM.LeadOwnerEmployeeId
		--AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 --   AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 --   AND LF.FollowupEmployeeId <> LM.LeadOwnerEmployeeId
	 --   AND LF.FollowupTypeId = 3		 
	 --    ) AS MailManager	     
	    FROM
	    sHrm.tEmployeeMaster EM INNER JOIN #TempEmployeeId TE ON EM.Id = TE.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
	   

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pAccountMappingAdd]
	 
		   @rFeeSetupId int,
		   @rAccountingYearId int,
           @rCreditLedgerId int,
           @rDebitLedgerId int,
           @rPayTypeId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DELETE FROM sFee.tAccountMapping WHERE FeeSetupId=@rFeeSetupId AND PayTypeId=@rPayTypeId
	
--IF NOT EXISTS (SELECT 1 FROM sFee.tAccountMapping WHERE FeeSetupId=@rFeeSetupId)		
	BEGIN
	INSERT INTO sFee.tAccountMapping
		(
		   FeeSetupId,
		   AccountingYearId,
		   CreditLedgerId,
		   DebitLedgerId,
		   PayTypeId
		   
		)
	VALUES
		(
			@rFeeSetupId,
			@rAccountingYearId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rPayTypeId
		)
		SELECT 1 AS Result
		             
	END	 
	
	--ELSE
	
	--BEGIN
	--UPDATE  sFee.tAccountMapping
	--SET
	--     AccountingYearId=@rAccountingYearId,
	--     CreditLedgerId=@rCreditLedgerId,
	--     DebitLedgerId=@rDebitLedgerId,
	--	 PayTypeId=@rPayTypeId
		
	--  WHERE (FeeSetupId = @rFeeSetupId)
	--  SELECT 11 AS Result   
	--END  
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pAccountMappingGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptBookId int,
		   @rPayTypeId int = 0,
		   @rFeeId int = 0,
		   @rFeeHeadId int = 0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS FeeSetupId,
			ISNULL(AM.FeeSetupId,0)AS AMFeeSetupId,
			ISNULL(FS.ClassId,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FM.Title,'') AS FeeTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(AYM.AccountId,0) AS AccountId,
			ISNULL(AM.CreditLedgerId,0) AS CreditLedgerId,
			ISNULL(AM.DebitLedgerId,0) AS DebitLedgerId,
			ISNULL(AM.AccountingYearId,0) AS AccountingYearId,
			ISNULL(AM.PayTypeId,0) AS AMPayTypeId,
			ISNULL(PTM.Id,0) AS PayTypeId,
			ISNULL(PTM.Title,'') AS PayTypeName
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId AND (RBM.Id = @rReceiptBookId OR @rReceiptBookId=0)
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId		
		CROSS JOIN (SELECT PTM.Id,PTM.Title FROM sFinanceCommon.tPayTypeMaster PTM WHERE (PTM.Id = @rPayTypeId OR @rPayTypeId = 0)) PTM
		INNER JOIN sFee.tApplicablePayType APT ON APT.PayTypeId=PTM.Id -- Mentis Id : 0033089 by Vishruti
		LEFT JOIN sFee.tAccountMapping AM ON AM.FeeSetupId=FS.Id AND AM.PayTypeId=PTM.Id
		LEFT JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=CLM.AccountingYearId AND AYM.Id=DLM.AccountingYearId
WHERE 
		FM.OrgGroupId=@rOrgGroupId	
		AND (FM.Id = @rFeeId OR @rFeeId=0)	
		AND (FHM.Id = @rFeeHeadId OR @rFeeHeadId = 0)
ORDER BY FM.OrderIndex,PTM.Id

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAccountMappingImport]

	@rOldAccountingYearId int=0,
	@rNewAccountingYearId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	IF EXISTS (SELECT 1 FROM sFee.tAccountMapping WHERE AccountingYearId = @rNewAccountingYearId)
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END

	BEGIN TRY 
	BEGIN TRANSACTION
	
	DECLARE @lCount int
	
	--  Account Mapping Temp Table
	CREATE TABLE #TempAccountMapping(
	[AutoId] int identity,
	[FeeSetupId] [int] NOT NULL,
	[AccountingYearId] [int] NOT NULL,
	[CreditLedgerId] [int] NULL,
	[DebitLedgerId] [int] NULL,
	[PayTypeId] [tinyint] NULL
	)
	-- End Create Table
	
	INSERT INTO #TempAccountMapping SELECT * FROM sFee.tAccountMapping WHERE AccountingYearId=@rOldAccountingYearId
	
	SELECT @lCount = COUNT(AutoId) FROM #TempAccountMapping
	WHILE (@lCount > 0)
	BEGIN
		-- Account Mapping Entry
		
		DECLARE @lNewFeeSetupId int = 0,@lOldFeeSetupId int=0
		
		SELECT @lOldFeeSetupId=ISNULL(FeeSetupId,0) FROM #TempAccountMapping WHERE AutoId = @lCount
		SELECT @lNewFeeSetupId=ISNULL(Id,0) FROM sFee.tFeeSetup WHERE OldFeeSetupId = @lOldFeeSetupId



		IF(@lOldFeeSetupId>0 AND @lNewFeeSetupId>0)
		BEGIN
			INSERT INTO sFee.tAccountMapping
			SELECT @lNewFeeSetupId,@rNewAccountingYearId,CreditLedgerId,DebitLedgerId,PayTypeId
			FROM #TempAccountMapping Where AutoId = @lCount
		END
		
		-- End of Account Mapping Entry
		
		SET @lCount = @lCount -1
		
	END

	DROP TABLE #TempAccountMapping 
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
DROP TABLE #TempAccountMapping 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pAccountMappingRemove]

	 @rFeeSetupId int,
	 @rPayTypeId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	 BEGIN TRANSACTION	
BEGIN
	 
	DELETE 
	FROM sFee.tAccountMapping 
	WHERE FeeSetupId=@rFeeSetupId AND PayTypeId = @rPayTypeId
	
	SELECT 1 AS Result
END	
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAdditionalFeeDashBoardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rFeeHeadId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @rStudentCountStatus TABLE (  
			AcademicId bigint,  
			ReceiptBookId int,
			OrgName nvarchar(30), 
			OrgId int, 
			DepartmentId int, 
			ClassId int, 
			DivisionId int, 
			Amount decimal(12,0),  
			FAAmount decimal(12,0),  
			DiscountAmount decimal(12,0),  
			AdditionalAmount decimal(12,0),  
			NotApplicableAmount decimal(12,0),  
			PaidAmount decimal(12,0),  
			PendingAmount decimal(12,0),
			AdmissionDate Date,
			LeftDate date
		)  
   
		INSERT INTO @rStudentCountStatus  
			SELECT   
			SA.AcademicId,  
			FS.ReceiptBookId,
			SA.OrganizationName,
			SA.OrgId,
			SA.DepartmentId,
			SA.ClassId,
			SA.DivisionId,  
			ISNULL(FS.Amount,0)AS Amount,  
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,  
			ISNULL(R.PaidAmount,0) AS PaidAmount,  
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount  ,
			A.AdmissionDate,
			A.LeftDate
		FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN sStudent.tStudentAdmission A ON A.StudentId = SA.StudentId
		INNER JOIN   
		(  
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
		FROM sFee.tFeeSetup FS1  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=0) OR (0=0))  
			AND ((SA1.AdmissionCategoryId=0) OR (0=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
		WHERE   
			((FS1.ClassId=0) OR (0=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=0) OR (0=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.IsOptional=0)  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			
		UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
			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 FS1.BatchId = SA1.BatchId  
			AND ((SA1.ClassId=0) OR (0=0))   
			AND ((SA1.AdmissionCategoryId=0) OR (0=0))  
		WHERE  
			((FS1.ClassId=0) OR (0=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=0) OR (0=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (0=0))  
			AND (FS1.IsOptional=1)  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			) FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN  
		(  
		SELECT   
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
		FROM  
			sFee.tReceipt R   
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.ClassId=0 OR 0=0)   
			AND (SA1.DivisionId=0 OR 0=0)  
		WHERE    
			(R.SourceTypeId = 2001)  
			AND (R.IsObsolete = 0)   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)  
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND (R.ReceiptDate <= getdate())  
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
		GROUP BY FeeSetupId,R.SourceId  
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id  
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId   
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId  
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = 110100101) OR (110100101 = 0))   
		LEFT JOIN 
		(  
		SELECT   
			AT.SourceId   
		FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		) RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		WHERE   
			((0 = 0 AND  1 = 1) OR (0 = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))  
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))     
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))     
			AND (SA.StatusId=0 OR 0=0)  
			AND ((SA.RollNo >= 0) OR (0=0))  
			AND ((SA.RollNo <= 0) OR (0=0))  
			AND ((SA.Code='') OR (''=''))  
			AND ((SA.DepartmentId=0) OR (0=0))    
			AND ((SA.ExemptionTypeId=0) OR (0=0))    
			AND ((SA.ClassId=0) OR (0=0))  
			AND ((SA.DivisionId=0) OR (0=0))     
		--GROUP BY SA.AcademicId,  
		--	FS.ReceiptBookId,
		--	SA.OrganizationName,
		--	SA.OrgId,
		--	SA.DepartmentId,
		--	SA.ClassId,
		--	SA.DivisionId,  
		--	SA.ClassName,
		--	SA.DivisionName, FS.Amount,FA.VariableAmount,FA.AdditionalAmount,FA.DiscountAmount,FA.NotApplicableAmount,R.PaidAmount,A.AdmissionDate,
		--	A.LeftDate
		ORDER BY SA.AcademicId   
  IF(@rType='Organization')
  BEGIN
  
    SELECT ISNULL(SUM(SCS.AdditionalAmount),0) AS  AdditionalAmount FROM  @rStudentCountStatus SCS
  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
  where
	 LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	--SELECT ISNULL(SUM(FA.AdditionalAmount),0) AS  AdditionalAmount FROM sFee.tReceipt R
	--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	--INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	--LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	--LEFT JOIN sFee.tFeeAllocation FA ON  FA.SourceId = SA.AcademicId 
	--WHERE R.SourceTypeId = 2001
 --   AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	--AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	--AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--AND (R.IsObsolete = 0) 
	
  END
  
  IF(@rType='ReceiptBook')
  BEGIN

		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(SCS.AdditionalAmount),0) AS  AdditionalAmount 
		FROM  @rStudentCountStatus SCS
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=SCS.ReceiptBookId
		WHERE 
		LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--AND (R.IsObsolete = 0) 
		GROUP BY RBM.Id,RBM.Title
		--SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(FA.AdditionalAmount),0) AS  AdditionalAmount FROM sFee.tReceipt R
		--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		--LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		--LEFT JOIN sFee.tFeeAllocation FA ON  FA.SourceId = SA.AcademicId 
		--WHERE R.SourceTypeId = 2001
		--AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		--AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		--AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--AND (R.IsObsolete = 0) 
		--GROUP BY RBM.Id,RBM.Title
  END
  
  IF(@rType='FeeHead')
  BEGIN
		SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,ISNULL(SUM(SCS.AdditionalAmount),0) AS  AdditionalAmount FROM  @rStudentCountStatus SCS
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=SCS.ReceiptBookId
		INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		WHERE  LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--AND (R.IsObsolete = 0) 
		AND (SCS.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title

	--SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,ISNULL(SUM(FA.AdditionalAmount),0) AS  AdditionalAmount
	--FROM sFee.tReceipt R
	--	INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
	--	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	--	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	--	INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
	--	INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	--	INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
	--	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	--	LEFT JOIN sFee.tFeeAllocation FA ON  FA.SourceId = SA.AcademicId AND FA.FeeSetupId = FS.Id
	--	WHERE R.SourceTypeId = 2001
	--	AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	--	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	--	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	--	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--	AND (R.IsObsolete = 0) 
	--	AND (R.ReceiptBookId = @rReceiptBookId) 
	--	GROUP BY FHM.Id,FHM.Title
  END
  
  IF(@rType='FeeMaster')
  BEGIN

		SELECT  FM.Id AS FeeHeadId,FM.Title AS FeeMaster,ISNULL(SUM(SCS.AdditionalAmount),0) AS  AdditionalAmount FROM  @rStudentCountStatus SCS
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=SCS.ReceiptBookId
		INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		WHERE  LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SCS.ReceiptBookId = @rReceiptBookId)  
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	--	SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,ISNULL(SUM(FA.AdditionalAmount),0) AS  AdditionalAmount
	--	FROM sFee.tReceipt R
	--INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
	--	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	--	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	--	INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
	--	INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	--	INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
	--	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	--	LEFT JOIN sFee.tFeeAllocation FA ON  FA.SourceId = SA.AcademicId AND FA.FeeSetupId = FS.Id
	--	WHERE R.SourceTypeId = 2001
	--	AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	--	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	--	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	--	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--	AND (R.IsObsolete = 0) 	 
	--	AND (R.ReceiptBookId = @rReceiptBookId) 
	--	AND (FHM.Id = @rFeeHeadId) 
	--	GROUP BY FM.Id,FM.Title
END
 
  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAllocatedFeeGet]
	 
		@rOrgId int,
		@rBatchId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rFeeHeadId int,
		@rFeeId int,
		@rOrgGroupBatchId int,
		@rDepartmentId int=0,
		@rExemptionTypeId int=0,
		@rIsExportToAll bit = 0,
		@rIsOptional bit = 0,
		@rIsVariable bit = 0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	IF(@rIsExportToAll=0)
	BEGIN
		SELECT 
				SA.AcademicId AS SourceId,
				SA.Name,
				SA.Code,
				SA.RollNo,
				SA.ClassId,
				SA.DivisionId,
				SA.OrgId,
				SA.ClassName+' - '+SA.DivisionName AS ClassName,
				FS.Id AS FeeSetupId,
				ISNULL(FS.IsOptional,0)AS IsOptional,
				ISNULL(FS.IsVariable,0)AS IsVariable,
				ISNULL(FS.Amount,0)AS Amount,
				ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FA.VariableAmount,0.00)AS FAAmount,
				ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
				ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
				ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
				ISNULL(R.PaidAmount,0) AS PaidAmount,
				ISNULL(FS.Amount,0.00) + ISNULL(FA.VariableAmount,0.00) + ISNULL(FA.AdditionalAmount,0.00) - ISNULL(FA.DiscountAmount,0.00) - ISNULL(FA.NotApplicableAmount,0.00) - ISNULL(R.PaidAmount,0.00) AS PendingAmount,
				ISNULL(FA.Remark,'') AS Remark,
				FM.Title AS FeeName,
				FS.AdmissionCategoryId,
				ISNULL(EM.Title,'') AS ExemptionFeeType
				
		FROM 
				sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId 
				INNER JOIN sFee.tFeeSetup FS ON FS.ClassId=SA.ClassId AND FS.AdmissionCategoryId = SA.AdmissionCategoryId AND FS.BatchId = SA.BatchId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId = SA.AcademicId
				LEFT JOIN  sFee.tExemptionTypeMaster EM ON EM.Id = SA.ExemptionTypeId
				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 FS.Id = RD.FeeSetupId
						INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId AND R.SourceTypeId = 2001				
						AND (SA1.ClassId=@rClassId OR @rClassId=0) AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					WHERE			 		
						(R.IsObsolete = 0) 
						AND ((R.BatchId = @rBatchId) OR (@rBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId 
		WHERE 
					SA.OrgGroupBatchId = @rOrgGroupBatchId
					AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
					AND ((SA.BatchId = @rBatchId) OR (@rBatchId=0))
					AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((SA.ClassId = @rClassId) OR (@rClassId=0))
					AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId=0))
					AND ((FM.FeeHeadId = @rFeeHeadId) OR (@rFeeHeadId=0))
					AND ((FS.FeeId = @rFeeId) OR (@rFeeId=0))
					AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId =0))
					AND ((SA.ExemptionTypeId =@rExemptionTypeId) OR (@rExemptionTypeId=0))
					
		ORDER BY SA.DivisionOrder,SA.RollNo
	END
	 
	IF(@rIsExportToAll=1)
	BEGIN
		SELECT 
				SA.AcademicId AS SourceId,
				SA.Name,
				SA.Code,
				SA.RollNo,
				SA.ClassId,
				SA.DivisionId,
				SA.OrgId,
				SA.ClassName+' - '+SA.DivisionName AS ClassName,
				FS.Id AS FeeSetupId,
				ISNULL(FS.IsOptional,0)AS IsOptional,
				ISNULL(FS.IsVariable,0)AS IsVariable,
				ISNULL(FS.Amount,0)AS Amount,
				ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FA.VariableAmount,0.00)AS FAAmount,
				ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
				ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
				ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
				ISNULL(R.PaidAmount,0) AS PaidAmount,
				ISNULL(FS.Amount,0.00) + ISNULL(FA.VariableAmount,0.00) + ISNULL(FA.AdditionalAmount,0.00) - ISNULL(FA.DiscountAmount,0.00) - ISNULL(FA.NotApplicableAmount,0.00) - ISNULL(R.PaidAmount,0.00) AS PendingAmount,
				ISNULL(FA.Remark,'') AS Remark,
				FM.Title AS FeeName,
				FS.AdmissionCategoryId,
				ISNULL(EM.Title,'') AS ExemptionFeeType
				
		FROM 
				sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId 
				INNER JOIN sFee.tFeeSetup FS ON FS.ClassId=SA.ClassId AND FS.AdmissionCategoryId = SA.AdmissionCategoryId AND FS.BatchId = SA.BatchId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId = SA.AcademicId
				LEFT JOIN  sFee.tExemptionTypeMaster EM ON EM.Id = SA.ExemptionTypeId
				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 FS.Id = RD.FeeSetupId
						INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId AND R.SourceTypeId = 2001				
						AND (SA1.ClassId=@rClassId OR @rClassId=0) AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					WHERE			 		
						(R.IsObsolete = 0) 
						AND ((R.BatchId = @rBatchId) OR (@rBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId 
		WHERE 
					SA.OrgGroupBatchId = @rOrgGroupBatchId
					AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
					AND ((SA.BatchId = @rBatchId) OR (@rBatchId=0))
					AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((SA.ClassId = @rClassId) OR (@rClassId=0))
					AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId=0))
					AND ((FM.FeeHeadId = @rFeeHeadId) OR (@rFeeHeadId=0))
					AND ((FS.FeeId = @rFeeId) OR (@rFeeId=0))
					AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId =0))
					AND ((SA.ExemptionTypeId =@rExemptionTypeId) OR (@rExemptionTypeId=0))
					AND ((FS.IsOptional = @rIsOptional) OR (@rIsOptional = 0))
					AND ((FS.IsVariable = @rIsVariable) OR (@rIsVariable = 0))
		ORDER BY SA.DivisionOrder,SA.RollNo
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pApplicablePayTypeAdd]
	-- Add the parameters for the stored procedure here
	@rOrgGroupId int,
	@rPayTypeId tinyint
AS
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 INSERT INTO sFee.tApplicablePayType
		(
			OrgGroupId,
			PayTypeId 
		)
		VALUES
		(
			@rOrgGroupId,
			@rPayTypeId
		)		
	 	            
		SELECT @rOrgGroupId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pApplicablePayTypeGet]
	   @rOrgGroupId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT  FPT.Id as PayTypeId,
			FPT.Title as PayType,
			CASE WHEN APT.PayTypeId Is Null THEN 'False' ELSE 'True' END AS IsObsolete
		
  FROM sFinanceCommon.tPayTypeMaster FPT
	LEFT JOIN sFee.tApplicablePayType APT ON APT.PayTypeId=FPT.Id AND OrgGroupId=@rOrgGroupId
	Where FPT.Id not in (12,13,14)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pApplyExemptionType]
	
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rExemptionTypeId int,
	@rAcademicId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	DECLARE @lClassId int
	DECLARE @lDivisionId int
	DECLARE @lAdmissionCategoryId int
	DECLARE @lExemptionTypeId int
	DECLARE @lCalculationTypeId tinyint
	
	SELECT @lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId,@lExemptionTypeId=ExemptionTypeId 
	FROM sStudent.vStudentAcademic 
	WHERE AcademicId = @rAcademicId AND BatchId=@rBatchId AND OrgId = @rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId
	
	SELECT @lCalculationTypeId=ISNULL(CalculationTypeId,0) FROM sFee.tExemptionTypeMaster WHERE Id = @lExemptionTypeId
	
	-- Exemption Type Temp Table
	CREATE TABLE #TempExemptionType
	(
		[AutoId] int identity,
		[AcademicId] bigint NULL,
		[RollNo] int NULL,
		[Name] nvarchar(500) NULL,
		[Code] nvarchar(20) NULL,
		[ClassId] int NULL,
		[DivisionId] int NULL,
		[ClassName] nvarchar(100) NULL,
		[DivisionName] nvarchar(100) NULL,
		[DivisionOrder] int NULL,
		[ClassDivision] nvarchar(200) NULL,
		[FeeSetupId] int NULL,
		[IsVariable] bit NULL,
		[Amount] decimal(12,2) NULL,
		[StartDate] date NULL,
		[EndDate] date NULL,
		[FAAmount] decimal(12,2) NULL,
		[DiscountAmount] decimal(12,2) NULL,
		[AdditionalAmount] decimal(12,2) NULL,
		[PaidAmount] decimal(12,2) NULL,
		[PendingAmount] decimal(12,2) NULL,
		[Remark] nvarchar(200) NULL,
		[FeeId] int NULL,
		[FeeName] nvarchar(100) NULL,
		[OrgId] int NULL,
		[OrgName] nvarchar(100) NULL,
		[OrgOrderIndex] int NULL,
		[ReceiptBookId] int NULL,
		[ReceiptBookTitle] nvarchar(100) NULL,
		[ReceiptOrderIndex] int NULL,
		[OrgGroupBatchId] int NULL,
		[DepartmentId] int NULL,
		[DepartmentName] nvarchar(100) NULL,
		[ParentContactNo] nvarchar(100) NULL,
		[ExemptionTypeId] int NULL,
	)
	-- End Exemption Type Temp Table
	
	
	
	INSERT INTO #TempExemptionType 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0) + ISNULL(FA.VariableAmount,0.00) AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeId,
		FS.FeeName,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		FS.ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		@lExemptionTypeId
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgId = @rOrgId 
			AND SA.BatchId=@rBatchId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			
			
		DECLARE @lCode nvarchar(20)
		SELECT @lCode=A.Code FROM #TempExemptionType A
		INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
		WHERE AcademicId = @rAcademicId 
		AND ((@lCalculationTypeId=1 AND A.PendingAmount < (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND A.PendingAmount < ISNULL(ETD.ExemptionPercentage,0)))
		IF @lCode IS NOT NULL
		BEGIN
				SELECT -101 AS Result,@lCode AS Code
			    RETURN
		END 
		
	BEGIN TRY 
	BEGIN TRANSACTION
	BEGIN -- Update Fee Allocation
		UPDATE AL 
		SET
		    DiscountAmount = R.Result,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM
		(
		SELECT		
			 CASE
             WHEN @lCalculationTypeId= 1 THEN (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)
             WHEN @lCalculationTypeId = 2 THEN ISNULL(ETD.ExemptionPercentage,0)
             END AS Result,
			 ISNULL(A.Amount,0) AS Amount,
			 ISNULL(ETD.ExemptionPercentage,0) AS ExemptionPercentage,
			 A.ExemptionTypeId,
			 A.PendingAmount,
			 A.AcademicId,
			 A.FeeSetupId
		FROM #TempExemptionType A
	    INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
		) 
		R  INNER JOIN	sFee.tFeeAllocation AL ON AL.SourceId = R.AcademicId AND AL.FeeSetupId = R.FeeSetupId
		WHERE
		((@lCalculationTypeId=1 AND R.Amount >= (((ISNULL(R.Amount,0)) * (ISNULL(R.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND R.Amount >= ISNULL(R.ExemptionPercentage,0)))
	END	

	BEGIN -- Insert Fee Allocation
		INSERT INTO sFee.tFeeAllocation
		(
		SourceTypeId,
		SourceId,
		FeeSetupId,
		VariableAmount,
		DiscountAmount,
		CreatedUserId,
		CreatedDateTime
		)
		SELECT		
			 2001,
			 A.AcademicId,
			 A.FeeSetupId,
			 A.FAAmount,
			 CASE
             WHEN @lCalculationTypeId= 1 THEN  (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)
             WHEN @lCalculationTypeId = 2 THEN ROUND(ISNULL(ETD.ExemptionPercentage,0),0)
             END,
			 @rCreatedUserId,
			 sCommon.fGetDate()
		FROM #TempExemptionType A 
	    INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = A.AcademicId AND FA.FeeSetupId = A.FeeSetupId 
		WHERE FA.SourceId IS NULL AND FA.FeeSetupId IS NULL
		AND 
		((@lCalculationTypeId=1 AND A.Amount >= (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND A.Amount >= ISNULL(ETD.ExemptionPercentage,0)))
	END

	-- For Fee Process Added By Foram 2025-01-23
	UPDATE FAS 
	SET
		FAS.DiscountAmount = AL.DiscountAmount,
		FAS.ToPayAmount = (FAS.FeeAmount + FAS.VariableAmount + FAS.AdditionalAmount - AL.DiscountAmount - FAS.NotApplicableAmount - FAS.PaidAmount),
		FAS.UpdatedUserId = @rCreatedUserId,
		FAS.UpdatedDateTime = sCommon.fGetDate()
	FROM
	(
		SELECT		
				CASE
				WHEN @lCalculationTypeId= 1 THEN (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)
				WHEN @lCalculationTypeId = 2 THEN ISNULL(ETD.ExemptionPercentage,0)
				END AS Result,
				ISNULL(A.Amount,0) AS Amount,
				ISNULL(ETD.ExemptionPercentage,0) AS ExemptionPercentage,
				A.ExemptionTypeId,
				A.PendingAmount,
				A.AcademicId,
				A.FeeSetupId
		FROM #TempExemptionType A
		INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
	) R  
	INNER JOIN sFee.tFeeAllocation AL ON AL.SourceId = R.AcademicId AND AL.FeeSetupId = R.FeeSetupId
	INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = R.AcademicId AND FAS.FeeSetupId = R.FeeSetupId AND AL.SourceId = FAS.AcademicId AND FAS.FeeSetupId = R.FeeSetupId
	WHERE
		((@lCalculationTypeId=1 AND R.Amount >= (((ISNULL(R.Amount,0)) * (ISNULL(R.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND R.Amount >= ISNULL(R.ExemptionPercentage,0)))
	-- For Fee Process Added By Foram 2025-01-23

	DROP TABLE #TempExemptionType
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY
BEGIN CATCH 
		DROP TABLE #TempExemptionType
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pApplyFeeStructure]
	
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rFeeStructureId int,
	@rAcademicId bigint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	DECLARE @lClassId int
	DECLARE @lDivisionId int
	DECLARE @lAdmissionCategoryId int
	DECLARE @lFeeStructureId int
	
	SELECT @lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId,@lFeeStructureId=FeeStructureId 
	FROM sStudent.vStudentAcademic 
	WHERE AcademicId = @rAcademicId AND BatchId=@rBatchId AND OrgId = @rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId
	
	-- Fee Structure Temp Table
	CREATE TABLE #TempFeeStructureMaster
	(
		[AutoId] int identity,
		[AcademicId] bigint NULL,
		[RollNo] int NULL,
		[Name] nvarchar(500) NULL,
		[Code] nvarchar(20) NULL,
		[ClassId] int NULL,
		[DivisionId] int NULL,
		[ClassName] nvarchar(100) NULL,
		[DivisionName] nvarchar(100) NULL,
		[DivisionOrder] int NULL,
		[ClassDivision] nvarchar(200) NULL,
		[FeeSetupId] int NULL,
		[IsVariable] bit NULL,
		[Amount] decimal(12,2) NULL,
		[StartDate] date NULL,
		[EndDate] date NULL,
		[FAAmount] decimal(12,2) NULL,
		[DiscountAmount] decimal(12,2) NULL,
		[AdditionalAmount] decimal(12,2) NULL,
		[PaidAmount] decimal(12,2) NULL,
		[PendingAmount] decimal(12,2) NULL,
		[Remark] nvarchar(200) NULL,
		[FeeId] int NULL,
		[FeeName] nvarchar(100) NULL,
		[OrgId] int NULL,
		[OrgName] nvarchar(100) NULL,
		[OrgOrderIndex] int NULL,
		[ReceiptBookId] int NULL,
		[ReceiptBookTitle] nvarchar(100) NULL,
		[ReceiptOrderIndex] int NULL,
		[OrgGroupBatchId] int NULL,
		[DepartmentId] int NULL,
		[DepartmentName] nvarchar(100) NULL,
		[ParentContactNo] nvarchar(100) NULL,
		[FeeStructureId] int NULL
	)
	-- End Fee Structure Temp Table
	
	
	INSERT INTO #TempFeeStructureMaster 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0) + ISNULL(FA.VariableAmount,0.00) AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeId,
		FS.FeeName,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		FS.ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		@lFeeStructureId
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsVariable=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgId = @rOrgId 
			AND SA.BatchId=@rBatchId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.FeeStructureId=@rFeeStructureId) OR (@rFeeStructureId=0))
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			
		DECLARE @lCode nvarchar(20)
		SELECT @lCode=A.Code FROM #TempFeeStructureMaster A
		INNER JOIN sFee.tFeeStructureDetail FSD ON FSD.FeeId = A.FeeId AND FSD.FeeStructureId = @lFeeStructureId
		WHERE AcademicId = @rAcademicId 
		AND ((A.PendingAmount >  FSD.FeeAmount)) 
		IF @lCode IS NOT NULL
		BEGIN
				SELECT -101 AS Result,@lCode AS Code
			    RETURN
		END 
		
	BEGIN TRY 
	BEGIN TRANSACTION
	BEGIN 
		-- Update Fee Allocation
		UPDATE AL 
		SET
		    VariableAmount = ROUND(R.Result, 0),
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM
		(
		SELECT	
			 FSD.FeeAmount AS Result,
			 ISNULL(A.Amount,0) AS Amount,
			 ISNULL(FSD.FeeAmount,0) AS FeeAmount,
			 A.FeeStructureId,
			 A.PendingAmount,
			 A.AcademicId,
			 A.FeeSetupId
		FROM #TempFeeStructureMaster A
	    INNER JOIN sFee.tFeeStructureDetail FSD ON FSD.FeeId = A.FeeId AND FSD.FeeStructureId = @lFeeStructureId
		) 
		R  INNER JOIN	sFee.tFeeAllocation AL ON AL.SourceId = R.AcademicId AND AL.FeeSetupId = R.FeeSetupId
		--WHERE
		--(R.Amount > R.Result)
	END	
	
	BEGIN 

 
		-- Insert Fee Allocation
		INSERT INTO sFee.tFeeAllocation
		SELECT		
			 2001,
			 A.AcademicId,
			 A.FeeSetupId,
			 FeeAmount,
			 0,
			 NULL,
			 NULL,
			 NULL,
			 NULL,
			 NULL,
			 @rCreatedUserId,
			 sCommon.fGetDate(),
			 NULL,
			 NULL,
			 NULL,
			 NULL,
			 NULL
		FROM #TempFeeStructureMaster A 
	    INNER JOIN sFee.tFeeStructureDetail FSD ON FSD.FeeId = A.FeeId AND FSD.FeeStructureId = @lFeeStructureId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = A.AcademicId AND FA.FeeSetupId = A.FeeSetupId 
		WHERE FA.SourceId IS NULL AND FA.FeeSetupId IS NULL
		--AND (A.PendingAmount >  FSD.FeeAmount) 
		 
	END
	DROP TABLE #TempFeeStructureMaster
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY
BEGIN CATCH 
		DROP TABLE #TempFeeStructureMaster
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pAssignExemptionTypeGet]
	 
		@rOrgId int,
		@rBatchId int,
		@rExemptionTypeId int,
		@rClassId int,
		@rDivisionId int,
		@rCode nvarchar(max)='',
		@rGenderId tinyint = 0,
		@rCasteCategoryId int = 0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
		SELECT 
			SA.AcademicId,
			SA.ClassName +' - '+SA.DivisionName AS Class,
			SA.RollNo,
			SA.Code,
			SA.Name,
			SA.ExemptionTypeId
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		WHERE
			(SA.OrgId=@rOrgId)
			AND (SA.BatchId = @rBatchId)
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
			AND (SA.StatusId = 1)
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
			AND (SO.CastCategoryId = @rCasteCategoryId OR @rCasteCategoryId=0)
		ORDER BY SA.DivisionOrder,SA.RollNo
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pAssignFeeOptionalCheck]
	 
	@rSourceId bigint,
	@rSourceTypeId int,
	@rFeeSetupId int
    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 IF NOT EXISTS(SELECT FS.FeeId FROM sFee.tFeeOptional FO 
						INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id 
							AND SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId 
							AND FS.FeeId IN (SELECT FS.FeeId FROM sFee.tFeeSetup FS where Id=@rFeeSetupId))
	BEGIN
		SELECT 1 AS Result
	END
	ELSE
		SELECT -1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAssignFeeStructureGet]
	 
		@rOrgId int,
		@rBatchId int,
		@rFeeStructureId int,
		@rClassId int,
		@rDivisionId int,
		@rCode nvarchar(max)='',
		@rGenderId tinyint = 0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
		SELECT 
			SA.AcademicId,
			SA.ClassName +' - '+SA.DivisionName AS Class,
			SA.RollNo,
			SA.Code,
			SA.Name,
			SA.FeeStructureId
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		WHERE
			(SA.OrgId=@rOrgId)
			AND (SA.BatchId = @rBatchId)
			AND ((SA.FeeStructureId=@rFeeStructureId) OR (@rFeeStructureId=0))
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
			AND (SA.StatusId = 1)
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
		ORDER BY SA.DivisionOrder,SA.RollNo
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sFee].[pAssignOptionalFeeAdd]
	 
		   @rFeeSetupId int,
           @rSourceTypeId int,
           @rSourceId bigint,
           @rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
IF EXISTS (SELECT 1 FROM [sFee].[tFeeSetup] where Id=@rFeeSetupId AND IsOptional=1)
BEGIN
IF NOT EXISTS(SELECT 1 FROM sFee.tFeeOptional WHERE FeeSetupId=@rFeeSetupId AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId AND BatchId=@rBatchId )	
BEGIN

	INSERT INTO sFee.tFeeOptional
		(
		   FeeSetupId,
		   SourceTypeId,
		   SourceId,
		   BatchId
		)
	VALUES
		(
			@rFeeSetupId,
			@rSourceTypeId,
			@rSourceId,
			@rBatchId
		)

		DECLARE @lOrgId NVARCHAR(10) = SUBSTRING(CAST(@rBatchId AS NVARCHAR(10)),1,4)

		EXEC sFee.pFeeProcessGenerateFeeOptionalAdd 0,@rFeeSetupId,@lOrgId,@rBatchId,0,0,3,@rSourceId,@rSourceTypeId

		SELECT 1 AS Result
		             
	END	 
	 ELSE
	 BEGIN

	      SELECT 11 AS Result   
	 END 
END
ELSE 
BEGIN

	      SELECT 11 AS Result   
END  
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAssignOptionalFeeGet]
	 
		@rClassId int,
		@rDivisionId int,
		@rAdmissionCategoryId int,
		@rFeeSetupId int,
		@rBatchId int,
		@rOrgId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			SA.AcademicId AS SourceId,
			SA.Code,
			SA.Name,
			SA.RollNo,
			ISNULL(FO.FeeSetupId,0) AS FeeSetupId,
			CASE WHEN ISNULL(FO.FeeSetupId,0) = 0 THEN 'False' ELSE 'True' END AS IsCheck 
	FROM 
			sStudent.vStudentAcademic SA
		LEFT JOIN sFee.tFeeOptional FO ON FO.SourceId=SA.AcademicId
			AND FO.SourceTypeId=2001 AND ((FO.FeeSetupId=@rFeeSetupId) OR (@rFeeSetupId=0))		
	WHERE 
			(SA.OrgId=@rOrgId)
		AND (SA.BatchId=@rBatchId)
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		AND (SA.StatusId=1)
		ORDER BY SA.RollNo

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAssignOptionalFeeHeadAdd] 
	@rSourceTypeId INT
	,@rSourceId BIGINT
	,@rBatchId INT
	,@rClassId INT
	,@rAdmissionCategoryId INT
	,@rFeeHeadId INT
	,@rFeeId INT = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		IF (@rClassId = 0)
		BEGIN
			SELECT @rClassId = ClassId
			FROM sStudent.vStudentAcademic SA
			WHERE AcademicId = @rSourceId
		END

		IF (@rFeeId = 0)
		BEGIN
			DELETE FO
			FROM SFee.tFeeOptional FO
			INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id
				AND FO.BatchId = FS.BatchId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
			WHERE FHM.Id = @rFeeHeadId
				AND FS.BatchId = @rBatchId
				AND FS.ClassId = @rClassId
				AND FS.AdmissionCategoryId = @rAdmissionCategoryId
				AND FS.IsOptional = 1
				AND FO.SourceId = @rSourceId
				AND FO.SourceTypeId = @rSourceTypeId
				AND FO.BatchId = @rBatchId

			INSERT INTO sFee.tFeeOptional (
				FeeSetupId
				,SourceTypeId
				,SourceId
				,BatchId
				)
			SELECT FS.Id
				,@rSourceTypeId
				,@rSourceId
				,@rBatchId
			FROM sFee.tFeeSetup FS
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
			WHERE FHM.Id = @rFeeHeadId
				AND FS.BatchId = @rBatchId
				AND FS.ClassId = @rClassId
				AND FS.AdmissionCategoryId = @rAdmissionCategoryId
				AND FS.IsOptional = 1

			DECLARE @lOrgId NVARCHAR(10) = SUBSTRING(CAST(@rBatchId AS NVARCHAR(10)), 1, 4)

			EXEC sFee.pFeeProcessGenerateFeeOptionalAdd @rFeeHeadId
				,0
				,@lOrgId
				,@rBatchId
				,@rClassId
				,@rAdmissionCategoryId
				,3
				,@rSourceId
				,@rSourceTypeId
		END
		ELSE
		BEGIN
			DELETE FO
			FROM SFee.tFeeOptional FO
			INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id
				AND FO.BatchId = FS.BatchId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			WHERE FM.Id = @rFeeId
				AND FS.BatchId = @rBatchId
				AND FS.ClassId = @rClassId
				AND FS.AdmissionCategoryId = @rAdmissionCategoryId
				AND FS.IsOptional = 1
				AND FO.SourceId = @rSourceId
				AND FO.SourceTypeId = @rSourceTypeId
				AND FO.BatchId = @rBatchId

			INSERT INTO sFee.tFeeOptional (
				FeeSetupId
				,SourceTypeId
				,SourceId
				,BatchId
				)
			SELECT FS.Id
				,@rSourceTypeId
				,@rSourceId
				,@rBatchId
			FROM sFee.tFeeSetup FS
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			WHERE FM.Id = @rFeeId
				AND FS.BatchId = @rBatchId
				AND FS.ClassId = @rClassId
				AND FS.AdmissionCategoryId = @rAdmissionCategoryId
				AND FS.IsOptional = 1

			-- For Fee Process Added By Foram on 2025-01-31 Start
			DECLARE @lFeeHeadId int 
			SELECT @lFeeHeadId = FeeHeadId FROM sFee.tFeeMaster WHERE Id = @rFeeId

			EXEC sFee.pFeeProcessGenerateFeeOptionalAdd @lFeeHeadId
				,0
				,@lOrgId
				,@rBatchId
				,@rClassId
				,@rAdmissionCategoryId
				,3
				,@rSourceId
				,@rSourceTypeId
			-- For Fee Process Added By Foram on 2025-01-31 End
		END

		SELECT 1 AS Result

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sFee].[pAssignOptionalFeeHeadHistoryAdd]
		  
           @rSourceTypeId int,
           @rSourceId bigint,
           @rBatchId int,
           @rClassId int,
           @rAdmissionCategoryId int,
           @rFeeHeadId int,
		   @rCreatedUserId bigint,
		   @rHistoryTypeId tinyint,
		   @rIsOptional bit,
		   @rFeeId int =  0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 IF(@rClassId=0)
	 BEGIN 
		SELECT @rClassId = ClassId FROM sStudent.vStudentAcademic SA WHERE AcademicId = @rSourceId
	 END 

	 IF(@rFeeId = 0)
	 BEGIN
	INSERT INTO sFee.tFeeAllocationHistory
		(
		   FeeSetupId,
		   SourceTypeId,
		   SourceId,
		   VariableAmount,
		   DiscountAmount,
		   UserId,
		   LogDateTime,
		   HistoryTypeId,
		   IsOptional
		)
	 
			SELECT
				FS.Id,  
				@rSourceTypeId,
				@rSourceId,	
				0,
				0,	
				@rCreatedUserId,
				sCommon.fGetDate(),
			    @rHistoryTypeId,
			    @rIsOptional
			FROM 
				sFee.tFeeSetup FS
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id	 
				
	WHERE
		FHM.Id = @rFeeHeadId
		AND FS.BatchId = @rBatchId
		AND FS.ClassId = @rClassId
		AND FS.AdmissionCategoryId =@rAdmissionCategoryId 
		AND FS.IsOptional=1
		
	END
	ELSE
	BEGIN
		INSERT INTO sFee.tFeeAllocationHistory
		(
		   FeeSetupId,
		   SourceTypeId,
		   SourceId,
		   VariableAmount,
		   DiscountAmount,
		   UserId,
		   LogDateTime,
		   HistoryTypeId,
		   IsOptional
		)
	 
			SELECT
				FS.Id,  
				@rSourceTypeId,
				@rSourceId,	
				0,
				0,	
				@rCreatedUserId,
				sCommon.fGetDate(),
			    @rHistoryTypeId,
			    @rIsOptional
			FROM 
				sFee.tFeeSetup FS
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId				
				
	WHERE
		FM.Id = @rFeeId
		AND FS.BatchId = @rBatchId
		AND FS.ClassId = @rClassId
		AND FS.AdmissionCategoryId =@rAdmissionCategoryId 
		AND FS.IsOptional=1
	END
		SELECT 1 AS Result
		
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAssignOptionalFeeHistoryAdd]
	 
		   @rFeeSetupId int,
           @rSourceTypeId int,
           @rSourceId bigint,
		   @rCreatedUserId bigint,
		   @rHistoryTypeId tinyint,
		   @rIsOptional bit,
		   @rRemark nvarchar(200) = '' --Changes for Mantis ID:0042052 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 
  BEGIN
	INSERT INTO sFee.tFeeAllocationHistory
		(
		   FeeSetupId,
		   SourceTypeId,
		   SourceId,
		   VariableAmount,
		   DiscountAmount,
		   UserId,
		   LogDateTime,
		   HistoryTypeId,
		   IsOptional,
		   Remark--Changes for Mantis ID:0042052
		)
	VALUES
		(
			@rFeeSetupId,
			@rSourceTypeId,
			@rSourceId,
			0,
			0,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rHistoryTypeId,
			@rIsOptional
			,@rRemark--Changes for Mantis ID:0042052
		)
		SELECT 1 AS Result
		             
	END	 
	 
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAssignOptionalFeeRemove] @rFeeSetupId INT
	,@rCheck BIT
	,@rSourceId BIGINT
	,@rSourceTypeId INT
	,@rBatchId INT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		IF (@rCheck = 1)
		BEGIN
			IF EXISTS (
					SELECT FS.Id
					FROM sFee.tFeeAllocation FA
					INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id
					WHERE FS.Id = @rFeeSetupId
						AND FA.SourceId = @rSourceId
						AND FA.SourceTypeId = @rSourceTypeId
						AND FS.BatchId = @rBatchId
					)
			BEGIN
				SELECT - 50 AS Result
					 COMMIT TRANSACTION
				RETURN
			END
			ELSE IF EXISTS (
					SELECT FS.Id
					FROM sFee.tReceipt R
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					WHERE FS.Id = @rFeeSetupId
						AND R.SourceId = @rSourceId
						AND R.SourceTypeId = @rSourceTypeId
						AND FS.BatchId = @rBatchId
					)
			BEGIN
				SELECT - 51 AS Result
				     COMMIT TRANSACTION
				RETURN
			END

			SELECT 0 AS Result
		END
		ELSE
		BEGIN
			DELETE
			FROM sFee.tFeeOptional
			WHERE SourceId = @rSourceId
				AND SourceTypeId = @rSourceTypeId
				AND BatchId = @rBatchId
				AND (
					(FeeSetupId = @rFeeSetupId)
					OR (@rFeeSetupId = 0)
					)

			DELETE
			FROM sFee.tFeeAllocationStudent
			WHERE AcademicId = @rSourceId
				AND FeeSetupId = @rFeeSetupId

			SELECT 11 AS Result
		END

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAssignOptionalTransportFee]

	@rStudentId bigint=0,
	@rBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lOrgGroupId int=0, @lAcademicId bigint=0,
	@lClassId int= 0,
	@lAdmissionCategoryId int=0, 
	@lFeeHeadId int=0,
	@1Count int=0,
	@lOrgId int=0
	
	SELECT @lOrgGroupId=OM.OrgGroupId,@lAcademicId=A.Id,@lClassId=A.ClassId,@lAdmissionCategoryId=A.AdmissionCategoryId,@lOrgId = A.OrgId FROM sStudent.tAcademic A 
	INNER JOIN sSetup.tOrganizationMaster OM ON A.OrgId = OM.Id
	WHERE StudentId = @rStudentId AND BatchId=@rBatchId
	
	DECLARE @lTempFeeMaster TABLE(Id smallint identity, FeeId int)
	SELECT @lFeeHeadId=Id FROM sFee.tFeeHeadMaster WHERE Number=1001 AND OrgGroupId = @lOrgGroupId
	
	INSERT INTO @lTempFeeMaster 
	SELECT Id FROM sFee.tFeeMaster WHERE FeeHeadId = @lFeeHeadId
	
	SELECT @1Count = COUNT(*) FROM @lTempFeeMaster
	
    WHILE @1Count > 0 
    BEGIN
		DECLARE @lFeeId int=0,@lFeeSetupId int=0
		SELECT @lFeeId = FeeId FROM @lTempFeeMaster WHERE Id=@1Count
		SELECT @lFeeSetupId=Id FROM sFee.tFeeSetup WHERE ClassId=@lClassId AND AdmissionCategoryId=@lAdmissionCategoryId AND BatchId=@rBatchId AND FeeId=@lFeeId AND IsOptional=1
		
		IF(@lFeeSetupId!=0)
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM sFee.tFeeOptional WHERE FeeSetupId=@lFeeSetupId AND SourceTypeId=2001 AND SourceId=@lAcademicId AND BatchId=@rBatchId )
			BEGIN 
				INSERT INTO sFee.tFeeOptional 
				SELECT @lFeeSetupId,2001,@lAcademicId,@rBatchId
				
				-- For Fee Process Added By Foram on 2025-01-31 Start
				EXEC sFee.pFeeProcessGenerateFeeOptionalAdd 0,@lFeeSetupId,@lOrgId,@rBatchId,0,0,3,@lAcademicId,2001
				-- For Fee Process Added By Foram on 2025-01-31 Start
			END
		END
		SET @1Count = @1Count - 1	
    END   
	SELECT 1 AS Result
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAssignOtherFeeGet]
	 
		@rOrgId int,
		@rBatchId int,
		@rAdmissionCategoryId int,
		@rDepartmentId int,
		@rClassId int,
		@rDivisionId int,
		@rFilterId tinyint,
		@rOrgGroupBatchId int,
		@rCode nvarchar(max)=''
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			SA.AcademicId AS SourceId,
			SA.ClassName +' - '+SA.DivisionName AS Class,
			SA.Code,
			SA.Name,
			SA.RollNo
	FROM 
			sStudent.vStudentAcademic SA
			LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND AR.OrgGroupBatchId=SA.OrgGroupBatchId 
			--LEFT JOIN sTransport.tAssignRoute AT ON  AT.SourceId=SA.StudentId AND AT.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			LEFT JOIN (
				select AT.SourceId,BRDM.Id,AT.SourceTypeId,isnull(BRM.id,0) as PickupDestinationRoutId,isnull(BRM2.id,0) as DropDestinationRoutId From sTransport.tAssignRoute AT 
				Left JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AT.PickupDestinationId
				Left JOIN sTransport.tBusRouteMaster BRM On BRm.id=BRDM.BusRouteId  --AnD BRM.OrgGroupBatchId=@rOrgGroupBatchId
				LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AT.DropDestinationId	
			    LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BRDM2.BusRouteId  --AND BRM2.OrgGroupBatchId=@rOrgGroupBatchId
				where  BRM.OrgGroupBatchId=@rOrgGroupBatchId or BRM2.OrgGroupBatchId=@rOrgGroupBatchId
			) A ON  A.SourceId=SA.StudentId AND A.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE 
		(SA.OrgId=@rOrgId) 
		AND (SA.BatchId=@rBatchId)
		AND ((SA.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SA.StatusId=1)
		AND (
		(@rFilterId = 0) -- All
		OR (@rFilterId = 2 AND ISNULL(AR.SourceId,0)!=0) -- Hostel
		--OR (@rFilterId = 3 AND ISNULL(AT.SourceId,0)!=0) -- Transport
		OR (@rFilterId = 3 AND ISNULL(A.SourceId,0)!=0) -- Transport
		--OR ((@rFilterId =1) AND ((ISNULL(AR.SourceId,0)=0) AND (ISNULL(AT.SourceId,0)=0))) -- School
		OR ((@rFilterId =1) AND ((ISNULL(AR.SourceId,0)=0) AND (ISNULL(A.SourceId,0)=0))) -- School
		)
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
		ORDER BY SA.ClassOrderIndex, SA.DivisionOrder, SA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pAutoAssignAdmissionFee]
	
	@rAcademicId bigint,	
	@rClassId int,	 
	@rCreatedUserId bigint,
	@rOrgId int,
	@rOrgGroupId int,
	@rBatchId int,	 
	@rAdmissionCategoryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lItemValue nvarchar(20) = ''
	
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 222

	IF(@lItemValue='Fee Head')
	BEGIN
		DECLARE @lIsOtherOptional bit 
		DECLARE @lOtherHeadId int 
		SELECT @lOtherHeadId = FeeHeadId FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId AND FeeMainGroupId = 1
		IF (@lOtherHeadId > 0)
		BEGIN
				SELECT  @lIsOtherOptional =  FS.IsOptional  
				FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				WHERE FM.FeeHeadId = @lOtherHeadId
				AND FS.BatchId = @rBatchId AND FS.ClassId = @rClassId AND FS.AdmissionCategoryId = @rAdmissionCategoryId

			IF (@lIsOtherOptional = 1)
			BEGIN
				IF NOT EXISTS (SELECT 1  
				FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
				INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				WHERE FM.FeeHeadId = @lOtherHeadId
				AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
				AND FS.AdmissionCategoryId = @rAdmissionCategoryId
				--AND FS.IsOptional = 1 
				AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
					BEGIN
						INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
						SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
						FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						WHERE FM.FeeHeadId = @lOtherHeadId
						AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
						AND AdmissionCategoryId = @rAdmissionCategoryId
						AND FS.IsOptional = 1
					END
			END
		END
	END
	ELSE IF(@lItemValue='Fee')
	BEGIN
		DECLARE @lCount int=0
		DECLARE @lIsOptional bit=0
		CREATE TABLE #TempFeeMainGroupOptionalFee
		(
			[AutoId] int identity,
			[OrgId] [int] NOT NULL,
			[FeeMainGroupId] [int] NOT NULL,
			[FeeId] [int] NOT NULL
		) 	
		INSERT INTO #TempFeeMainGroupOptionalFee SELECT * FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId AND FeeMainGroupId = 1
		SELECT @lCount = COUNT(AutoId) From #TempFeeMainGroupOptionalFee
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lFeeId int=0
			SELECT @lFeeId=FeeId FROM #TempFeeMainGroupOptionalFee WHERE AutoId = @lCount
			
			IF (@lFeeId > 0)
			BEGIN
				SELECT  @lIsOptional =  FS.IsOptional  
				FROM sFee.tFeeSetup FS 
				WHERE FS.FeeId = @lFeeId
				AND FS.BatchId = @rBatchId AND FS.ClassId = @rClassId AND FS.AdmissionCategoryId = @rAdmissionCategoryId

				IF (@lIsOptional = 1)
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM sFee.tFeeOptional FO 
					INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
					WHERE FS.FeeId = @lFeeId AND FS.BatchId = @rBatchId 
					AND ClassId = @rClassId  AND FS.AdmissionCategoryId = @rAdmissionCategoryId
					AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
						BEGIN
							INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
							SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
							FROM sFee.tFeeSetup FS  WHERE FS.FeeId = @lFeeId
							AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
							AND AdmissionCategoryId = @rAdmissionCategoryId
							AND FS.IsOptional = 1
						END
				END
			END
			SET @lCount = @lCount -1
		END	
	END
COMMIT TRANSACTION
IF OBJECT_ID('#TempFeeMainGroupOptionalFee') IS NOT NULL
	DROP TABLE #TempFeeMainGroupOptionalFee
SELECT 1 AS Result
	END TRY
	BEGIN CATCH 
    	IF OBJECT_ID('#TempFeeMainGroupOptionalFee') IS NOT NULL
			DROP TABLE #TempFeeMainGroupOptionalFee
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pAutoAssignOptinalFee]
	@rAcademicId bigint,	
	@rClassId int, 
	--@rFeeHeadId int,
	@rCreatedUserId bigint,
	@rOrgId int,
	@rOrgGroupId int,
	@rBatchId int,
	@rRoomId int=0,
	@rPickupPointId int=0,	 
	@rAdmissionCategoryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lItemValue nvarchar(20) = ''
	
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 222

	DECLARE @lRoomCharge   decimal(10,2),@lBusCharge   decimal(10,2)
	DECLARE @lIsTranportOptional bit,@lIsTransportVariable  bit,@lIsHostelOptional  bit,@lIsHostelVariable  bit
	DECLARE @lTransportHeadId int, @lHostelHeadId int
	
IF(@lItemValue='Fee Head')
BEGIN
	IF (@rPickupPointId > 0)
	BEGIN
		SELECT @lBusCharge = RDM.Amount FROM sTransport.tBusRouteMaster RM INNER JOIN sTransport.tBusRouteDestinationMaster RDM
		ON RM.Id = RDM.BusRouteId WHERE RDM.Id = @rPickupPointId

		SELECT @lTransportHeadId = FeeHeadId FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId AND FeeMainGroupId = 4
		SELECT  @lIsTranportOptional =  FS.IsOptional ,@lIsTransportVariable = FS.IsVariable 
		FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		WHERE FM.FeeHeadId = @lTransportHeadId
		AND FS.BatchId = @rBatchId AND FS.ClassId = @rClassId AND FS.AdmissionCategoryId = @rAdmissionCategoryId
		
		IF (@lIsTranportOptional = 1)
		BEGIN
			IF NOT EXISTS (SELECT 1  
			FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
			INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			WHERE FM.FeeHeadId = @lTransportHeadId
			AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
			AND FS.AdmissionCategoryId = @rAdmissionCategoryId
			--AND FS.IsOptional = 1 
			AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
			BEGIN
				INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
				SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
				FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				WHERE FM.FeeHeadId = @lTransportHeadId
				AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
				AND AdmissionCategoryId = @rAdmissionCategoryId
				AND FS.IsOptional = 1
			END		
		END
		IF (@lIsTransportVariable = 1)
		BEGIN	
			IF NOT EXISTS (SELECT 1  
			FROM sFee.tFeeAllocation FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
			INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			WHERE FM.FeeHeadId = @lTransportHeadId
			AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
			AND FS.AdmissionCategoryId = @rAdmissionCategoryId
			--AND FS.IsOptional = 1 
			AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
			BEGIN
				INSERT INTO sFee.tFeeAllocation
				SELECT  2001,@rAcademicId,FS.Id,@lBusCharge,0,0,0,'',NULL,NULL,@rCreatedUserId,sCommon.fGetDate(),NULL,NULL,'','',''
				FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				WHERE FM.FeeHeadId = @lTransportHeadId
				AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
				AND AdmissionCategoryId = @rAdmissionCategoryId
				AND FS.IsVariable = 1
			END
		END
	END

	IF (@rRoomId > 0)
	BEGIN
		SELECT @lRoomCharge = RCM.RoomCharge FROM sHostel.tRoomMaster RM INNER JOIN sHostel.tRoomCategoryMaster RCM
		ON RM.RoomCategoryId = RCM.Id WHERE RM.Id = @rRoomId

		SELECT @lHostelHeadId = FeeHeadId FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId AND FeeMainGroupId = 5
		SELECT  @lIsHostelOptional = FS.IsOptional,@lIsHostelVariable = FS.IsVariable  
		FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		WHERE FM.FeeHeadId = @lHostelHeadId
		AND FS.BatchId = @rBatchId AND ClassId = @rClassId AND AdmissionCategoryId = @rAdmissionCategoryId
	IF (@lIsHostelOptional = 1)
	BEGIN
		IF NOT EXISTS (SELECT 1  
		FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
		INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		WHERE FM.FeeHeadId = @lHostelHeadId
		AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
		AND FS.AdmissionCategoryId = @rAdmissionCategoryId
		--AND FS.IsOptional = 1 
		AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
		BEGIN
			INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
			SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
			FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			WHERE FM.FeeHeadId = @lHostelHeadId
			AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
			AND AdmissionCategoryId = @rAdmissionCategoryId
			AND FS.IsOptional = 1
		END
	END
	IF (@lIsHostelVariable = 1)
	BEGIN
		IF NOT EXISTS (SELECT 1  
		FROM sFee.tFeeAllocation FA INNER JOIN sFee.tFeeSetup FS  ON FA.FeeSetupId = FS.Id  
		INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		WHERE FM.FeeHeadId = @lHostelHeadId
		AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
		AND FS.AdmissionCategoryId = @rAdmissionCategoryId
		--AND FS.IsVariable = 1 
		AND FA.SourceTypeId = 2001 AND FA.SourceId = @rAcademicId )
		BEGIN
			INSERT INTO sFee.tFeeAllocation
			SELECT  2001,@rAcademicId,FS.Id,@lRoomCharge,0,0,0,'',NULL,NULL,@rCreatedUserId,sCommon.fGetDate(),NULL,NULL,'','',''
			FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			WHERE FM.FeeHeadId = @lHostelHeadId
			AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
			AND AdmissionCategoryId = @rAdmissionCategoryId
			AND FS.IsVariable = 1
		END
	END
END
END

ELSE IF(@lItemValue='Fee')
BEGIN
	DECLARE @lCount int=0
	DECLARE @lIsOptionalTranportFee bit=0
	DECLARE @lIsVariableTransportFee bit=0
	
	CREATE TABLE #TempFeeMainGroupOptionalFee
	(
		[AutoId] int identity,
		[OrgId] [int] NOT NULL,
		[FeeMainGroupId] [int] NOT NULL,
		[FeeId] [int] NOT NULL
	)
	
	INSERT INTO #TempFeeMainGroupOptionalFee SELECT * FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId AND FeeMainGroupId = 4
		
	SELECT @lCount = COUNT(AutoId) From #TempFeeMainGroupOptionalFee
	
	IF (@rPickupPointId > 0)
	BEGIN
		SELECT @lBusCharge = RDM.Amount FROM sTransport.tBusRouteMaster RM INNER JOIN sTransport.tBusRouteDestinationMaster RDM
		ON RM.Id = RDM.BusRouteId WHERE RDM.Id = @rPickupPointId
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lTransportFeeId int=0
			SELECT @lTransportFeeId=FeeId FROM #TempFeeMainGroupOptionalFee WHERE AutoId = @lCount
			
			SELECT  @lIsOptionalTranportFee =  FS.IsOptional ,@lIsVariableTransportFee = FS.IsVariable 
			FROM sFee.tFeeSetup FS WHERE FS.FeeId = @lTransportFeeId
			AND FS.BatchId = @rBatchId AND FS.ClassId = @rClassId AND FS.AdmissionCategoryId = @rAdmissionCategoryId
			
			IF(@lTransportFeeId > 0)
			BEGIN 
				IF (@lIsOptionalTranportFee = 1)
				BEGIN
					IF NOT EXISTS (SELECT 1  
					FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
					WHERE FS.FeeId = @lTransportFeeId
					AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
					AND FS.AdmissionCategoryId = @rAdmissionCategoryId
					AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
					BEGIN
						INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
						SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
						FROM sFee.tFeeSetup FS WHERE FS.FeeId = @lTransportFeeId
						AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
						AND AdmissionCategoryId = @rAdmissionCategoryId
						AND FS.IsOptional = 1
					END		
				END
				IF (@lIsVariableTransportFee = 1)
				BEGIN	
					IF NOT EXISTS (SELECT 1  
					FROM sFee.tFeeAllocation FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
					WHERE FS.FeeId = @lTransportFeeId
					AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
					AND FS.AdmissionCategoryId = @rAdmissionCategoryId
					AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
					BEGIN
						INSERT INTO sFee.tFeeAllocation
						SELECT  2001,@rAcademicId,FS.Id,@lBusCharge,0,0,0,'',NULL,NULL,@rCreatedUserId,sCommon.fGetDate(),NULL,NULL,'','',''
						FROM sFee.tFeeSetup FS WHERE FS.FeeId = @lTransportFeeId
						AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
						AND AdmissionCategoryId = @rAdmissionCategoryId
						AND FS.IsVariable = 1
					END
				END
			END
			SET @lCount = @lCount -1
		END
	END
	
	TRUNCATE TABLE #TempFeeMainGroupOptionalFee 
	INSERT INTO #TempFeeMainGroupOptionalFee SELECT * FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId AND FeeMainGroupId = 5
	
	SET @lCount = 0
	DECLARE @lIsOptionalHostelFee bit=0
	DECLARE @lIsVariableHostelFee bit=0
	SELECT @lCount = COUNT(AutoId) From #TempFeeMainGroupOptionalFee
	
	IF (@rRoomId > 0)
	BEGIN
		
		SELECT @lRoomCharge = RCM.RoomCharge FROM sHostel.tRoomMaster RM INNER JOIN sHostel.tRoomCategoryMaster RCM
		ON RM.RoomCategoryId = RCM.Id WHERE RM.Id = @rRoomId
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lHostelFeeId int=0
			SELECT @lHostelFeeId=FeeId FROM #TempFeeMainGroupOptionalFee WHERE AutoId = @lCount
			
			SELECT  @lIsOptionalHostelFee = FS.IsOptional,@lIsVariableHostelFee = FS.IsVariable  
			FROM sFee.tFeeSetup FS WHERE FS.FeeId = @lHostelFeeId
			AND FS.BatchId = @rBatchId AND ClassId = @rClassId AND AdmissionCategoryId = @rAdmissionCategoryId
			
			IF(@lHostelFeeId > 0)
			BEGIN
				 
				IF (@lIsOptionalHostelFee = 1)
				BEGIN
					
					IF NOT EXISTS (SELECT 1  
					FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
					WHERE FS.FeeId = @lHostelFeeId
					AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
					AND FS.AdmissionCategoryId = @rAdmissionCategoryId
					AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
					BEGIN
						INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
						SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
						FROM sFee.tFeeSetup FS
						WHERE FS.FeeId = @lHostelFeeId
						AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
						AND AdmissionCategoryId = @rAdmissionCategoryId
						AND FS.IsOptional = 1
					END
				END
				IF (@lIsVariableHostelFee = 1)
				BEGIN
				
					IF NOT EXISTS (SELECT 1  
					FROM sFee.tFeeAllocation FA INNER JOIN sFee.tFeeSetup FS  ON FA.FeeSetupId = FS.Id  
					WHERE FS.FeeId = @lHostelFeeId
					AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
					AND FS.AdmissionCategoryId = @rAdmissionCategoryId
					AND FA.SourceTypeId = 2001 AND FA.SourceId = @rAcademicId )
					BEGIN
						INSERT INTO sFee.tFeeAllocation
						SELECT  2001,@rAcademicId,FS.Id,@lRoomCharge,0,0,0,'',NULL,NULL,@rCreatedUserId,sCommon.fGetDate(),NULL,NULL,'','',''
						FROM sFee.tFeeSetup FS
						WHERE FS.FeeId = @lHostelFeeId
						AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
						AND AdmissionCategoryId = @rAdmissionCategoryId
						AND FS.IsVariable = 1
					END
				END
			END
			SET @lCount = @lCount -1
		END	
	END		
END	
SELECT 1 AS Result    
COMMIT TRANSACTION
IF OBJECT_ID('#TempFeeMainGroupOptionalFee') IS NOT NULL
DROP TABLE #TempFeeMainGroupOptionalFee
	END TRY
	BEGIN CATCH
		IF OBJECT_ID('#TempFeeMainGroupOptionalFee') IS NOT NULL
		DROP TABLE #TempFeeMainGroupOptionalFee 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 

CREATE OR ALTER PROCEDURE [sFee].[pAutoAssignOtherFee]
	@rAcademicId bigint,	
	@rClassId int,	 
	@rCreatedUserId bigint,
	@rOrgId int,
	@rOrgGroupId int,
	@rBatchId int,	 
	@rAdmissionCategoryId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lItemValue nvarchar(20) = ''
	
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 222

	IF(@lItemValue='Fee Head')
	BEGIN
		DECLARE @lIsOtherOptional bit 
		DECLARE @lOtherHeadId int 
		SELECT @lOtherHeadId = FeeHeadId FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId AND FeeMainGroupId = 6
		IF (@lOtherHeadId > 0)
		BEGIN
				SELECT  @lIsOtherOptional =  FS.IsOptional  
				FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				WHERE FM.FeeHeadId = @lOtherHeadId
				AND FS.BatchId = @rBatchId AND FS.ClassId = @rClassId AND FS.AdmissionCategoryId = @rAdmissionCategoryId

			IF (@lIsOtherOptional = 1)
			BEGIN
				IF NOT EXISTS (SELECT 1  
				FROM sFee.tFeeOptional FO INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
				INNER JOIN  sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				WHERE FM.FeeHeadId = @lOtherHeadId
				AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
				AND FS.AdmissionCategoryId = @rAdmissionCategoryId
				--AND FS.IsOptional = 1 
				AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
					BEGIN
						INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
						SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
						FROM sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						WHERE FM.FeeHeadId = @lOtherHeadId
						AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
						AND AdmissionCategoryId = @rAdmissionCategoryId
						AND FS.IsOptional = 1
					END
			END
		END
	END
	ELSE IF(@lItemValue='Fee')
	BEGIN
		DECLARE @lCount int=0
		
		DECLARE @lIsOptional bit=0
		CREATE TABLE #TempFeeMainGroupOptionalFee
		(
			[AutoId] int identity,
			[OrgId] [int] NOT NULL,
			[FeeMainGroupId] [int] NOT NULL,
			[FeeId] [int] NOT NULL
		) 	
		INSERT INTO #TempFeeMainGroupOptionalFee SELECT * FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId AND FeeMainGroupId = 6
		SELECT @lCount = COUNT(AutoId) From #TempFeeMainGroupOptionalFee
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lFeeId int=0
			SELECT @lFeeId=FeeId FROM #TempFeeMainGroupOptionalFee WHERE AutoId = @lCount
			IF (@lFeeId > 0)
			BEGIN
				SELECT  @lIsOptional =  FS.IsOptional  
				FROM sFee.tFeeSetup FS 
				WHERE FS.FeeId = @lFeeId
				AND FS.BatchId = @rBatchId AND FS.ClassId = @rClassId AND FS.AdmissionCategoryId = @rAdmissionCategoryId

				IF (@lIsOptional = 1)
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM sFee.tFeeOptional FO 
					INNER JOIN sFee.tFeeSetup FS  ON FO.FeeSetupId = FS.Id  
					WHERE FS.FeeId = @lFeeId AND FS.BatchId = @rBatchId 
					AND ClassId = @rClassId  AND FS.AdmissionCategoryId = @rAdmissionCategoryId
					AND FO.SourceTypeId = 2001 AND FO.SourceId = @rAcademicId )
						BEGIN
							INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
							SELECT FS.Id AS FeeSetupId,2001 AS SourceTypeId,@rAcademicId AS SourceId,@rBatchId AS BatchId 
							FROM sFee.tFeeSetup FS  WHERE FS.FeeId = @lFeeId
							AND FS.BatchId = @rBatchId AND ClassId = @rClassId 
							AND AdmissionCategoryId = @rAdmissionCategoryId
							AND FS.IsOptional = 1
						END
				END
			END
			SET @lCount = @lCount -1
		END	
	END
COMMIT TRANSACTION
IF OBJECT_ID('#TempFeeMainGroupOptionalFee') IS NOT NULL
DROP TABLE #TempFeeMainGroupOptionalFee
SELECT 1 AS Result
	END TRY
	BEGIN CATCH 
		IF OBJECT_ID('#TempFeeMainGroupOptionalFee') IS NOT NULL
		DROP TABLE #TempFeeMainGroupOptionalFee
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pCancelReceiptDashBoardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rFeeHeadId int=0,
	 @rPayTypeId int =0,
	 @rDivisionId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN

	SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	WHERE R.SourceTypeId = 2001
    AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 1) 
	
  END
  
  IF(@rType='ReceiptBook')
  BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 1) 
		GROUP BY RBM.Id,RBM.Title

  END
  
   IF(@rType='OrganizationList')
  BEGIN
		SELECT SA.OrgId AS OrgId,SA.OrganizationName AS OrganizationName,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 1) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY SA.OrgId,SA.OrganizationName

  END
  
   IF(@rType='ClassDivisionName')
  BEGIN
		SELECT SA.DivisionId, SA.ClassName +' - '+ SA.DivisionName AS DivisionName,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 1) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY SA.DivisionId,SA.ClassName,SA.DivisionName
  END
  
   IF(@rType='StudentList')
  BEGIN
		SELECT SA.Code,SA.Name,R.ReceiptNumber,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 1) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId=0)
		GROUP BY SA.Code,SA.Name,R.ReceiptNumber
  END
  
  
  IF(@rType='FeeHead')
  BEGIN
	IF(@rDay=1)
	BEGIN
	SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount  
	FROM sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
	IF(@rDay=30)
	BEGIN
		SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
	IF(@rDay=365)
	BEGIN
		SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
	INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
  END
  
  IF(@rType='FeeMaster')
  BEGIN
	IF(@rDay=1)
	BEGIN
	
		SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
	INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
				AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
	IF(@rDay=30)
	BEGIN
		
		SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
	IF(@rDay=365)
	BEGIN
		
		SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
END
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pCanteenDepositAdjustmentAdd]
	
	@rId bigint, 
	@rAdjustmentId bigint,
	@rDepositHeadId int,
	--@rStudentId bigint,
	@rAmount decimal(12,2),
	@rAdjustmentDate date,
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	--@rBatchId int,
	@rOrgGroupId smallint,
	@rAcademicId bigint,
	@rFeeDepositExpenseTypeId int,
	--@rAdjustmentNumber Int,
	@rOrgGroupBatchId int,
	@rReferenceSourceId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	
 DECLARE @rAdjustmentNumber Int
 Select @rAdjustmentNumber=(MAX(AdjustmentNumber) +1) from sFee.tDepositAdjustment

 --IF(@rId = 0)	
	--BEGIN  
		
	--	If Exists(select 1 from sFee.tDepositAdjustment  where OrgGroupBatchId=@rOrgGroupBatchId AND  AdjustmentNumber=@rAdjustmentNumber)
	--	Begin
	--		select -102 as Result
	--		RETURN
	--	End
	--		END
	--ELSE
	--BEGIN
		
	--	If  Exists(select Id from sFee.tDepositAdjustment where  OrgGroupBatchId=@rOrgGroupBatchId AND  AdjustmentNumber=@rAdjustmentNumber AND Id<>@rId)
	--	Begin
	--		select -102 as Result
	--		RETURN
	--	End

	--END
DECLARE @lNextNumber bigint 
IF NOT EXISTS(Select Id From sFee.tDepositAdjustment Where ReferenceSourceId=@rReferenceSourceId)
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output 
	INSERT INTO sFee.tDepositAdjustment
		(
		Id,
		DepositHeadId,
		--StudentId,
		Amount,
		AdjustmentDate,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		AcademicId,
		FeeDepositExpenseTypeId,
		AdjustmentNumber,
		OrgGroupBatchId,
		ReferenceSourceTypeId,
		ReferenceSourceId
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		--@lStudentId,
		@rAmount,
		@rAdjustmentDate,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rAcademicId,
		@rFeeDepositExpenseTypeId,
		@rAdjustmentNumber,
		@rOrgGroupBatchId,
		2037 ,
		@rReferenceSourceId 
		) 
		SELECT @lNextNumber  AS Result   
	END	
ELSE
    BEGIN
    --SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdjustment
	    SET
	    DepositHeadId=@rDepositHeadId,
		Amount=@rAmount,
		AdjustmentDate=@rAdjustmentDate,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    AcademicId=@rAcademicId,
	    FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId,
		AdjustmentNumber=@rAdjustmentNumber,
		OrgGroupBatchId=@rOrgGroupBatchId,
		ReferenceSourceTypeId=2037,
		ReferenceSourceId=@rReferenceSourceId
	    WHERE ReferenceSourceId = @rAdjustmentId 
	    SELECT 11 AS Result
	 END  
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pChangeClassFeeReceiptDetailUpdate]
	
	@rAcademicId bigint,
	@rOldClassId int,
	@rOldDivisionId int,
	@rNewClassId int,
	@rNewDivisionId int,	 
	@rBatchId int,
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @rAdmissionCategoryId int
DECLARE @rOldFeeSetupCount int
DECLARE @rNewFeeSetupCount int
DECLARE @rFinalFeeSetupCount int
	


	
		--IF Exists (SELECT R.SourceId FROM sFee.tReceipt R WHERE R.SourceId = @rAcademicId)
		--BEGIN
		--SELECT -111 AS Result
		--RETURN		
		--END
		--IF Exists (SELECT R.SourceId FROM sFee.tFeeOptional R WHERE R.SourceId = @rAcademicId)
		--BEGIN
		--SELECT -112 AS Result
		--RETURN		
		--END
		--IF Exists (SELECT R.SourceId FROM sFee.tFeeAllocation R WHERE R.SourceId = @rAcademicId)
		--BEGIN
		--SELECT -113 AS Result
		--RETURN		
		--END

		IF Exists (SELECT 1 FROM sAssessment.tOptionalSubject R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -114 AS Result
		RETURN		
		END


		IF Exists (SELECT 1 FROM sAssessment.tResult R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -115 AS Result
		RETURN		
		END
		
		IF Exists (SELECT 1 FROM sAssessment.tCCECSExamScore R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -116 AS Result
		RETURN		
		END
		
		IF Exists (SELECT 1 FROM sAssessment.tGradeSujbectExamScore R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -117 AS Result
		RETURN		
		END

		BEGIN

			SELECT DISTINCT FS.AdmissionCategoryId,FS.FeeId,FS.Amount,RD.ReceiptId,RD.FeeSetupId INTO #OldFeeSteupTempTable 
			FROM sFee.tFeeSetup FS INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = FS.ID INNER JOIN sFee.tReceipt FR ON FR.ID = RD.RECEIPTID 
			INNER JOIN sStudent.tAcademic A ON  A.Id = FR.SourceId 
			where A.Id=@rAcademicId and FS.ClassId=@rOldClassId AND A.BatchId=@rBatchId order by FS.FeeId

			SET @rOldFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #OldFeeSteupTempTable)
		IF(@rOldFeeSetupCount > 0)
			BEGIN			 
			 SET @rAdmissionCategoryId = (SELECT TOP 1 AdmissionCategoryId  FROM #OldFeeSteupTempTable)

				SELECT Id AS NewFeeSetupId,FS.FeeId,FS.Amount,OFS.ReceiptId INTO #NewFeeSteupTempTable  FROM sFee.tFeeSetup FS 
				LEFT JOIN #OldFeeSteupTempTable OFS ON OFS.FeeId = FS.FeeId
				WHERE ClassId=@rNewClassId and BatchId=@rBatchId and FS.AdmissionCategoryId=@rAdmissionCategoryId 
				And FS.FeeId IN (SELECT FeeId from #OldFeeSteupTempTable)
				order by FeeId

				SET @rNewFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #NewFeeSteupTempTable)
				 
					IF(@rOldFeeSetupCount > @rNewFeeSetupCount)
				BEGIN
				SELECT -103 AS Result
				RETURN
				END

				IF(@rNewFeeSetupCount > 0)
					BEGIN

					SELECT OldFee.ReceiptId,OldFee.FeeSetupId AS OldFeeSetupId,NewFee.NewFeeSetupId INTO #FinalFeeSteupTempTable  FROM #OldFeeSteupTempTable OldFee
					INNER JOIN #NewFeeSteupTempTable NewFee on NewFee.FeeId = OldFee.FeeId
					WHERE OldFee.Amount <= NewFee.Amount order by OldFee.FeeId

					SET @rFinalFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #FinalFeeSteupTempTable)
						IF(@rFinalFeeSetupCount > 0)
							BEGIN
								BEGIN TRY
								BEGIN TRANSACTION							 
									BEGIN
										BEGIN										
										      --SELECT 1
											UPDATE RD SET FeeSetupId =FS.NewFeeSetupId from sFee.tReceiptDetail RD 
											INNER JOIN #FinalFeeSteupTempTable FS ON FS.ReceiptId = RD.ReceiptId AND FS.OldFeeSetupId=RD.FeeSetupId

											UPDATE sStudent.tAcademic set ClassId=@rNewClassId,DivisionId=@rNewDivisionId WHERE Id=@rAcademicId AND ClassId=@rOldClassId AND DivisionId=@rOldDivisionId AND BatchId=@rBatchId AND OrgId=@rOrgId  
										END		
										SELECT 1 AS RESULT
									END 
									COMMIT TRANSACTION
								END TRY
								BEGIN CATCH 
									ROLLBACK TRANSACTION
									SELECT -104 AS Result
								END CATCH	
							END
						ELSE
							BEGIN
								SELECT -103 AS Result
							END
					END
				ELSE
					BEGIN
					SELECT -102 AS Result
					END
			END
		ELSE
			BEGIN
			SELECT -101 AS Result
			END
			END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChangeFeeCategoryFeeReceiptUpdate]
	
	@rAcademicId bigint,
	@rClassId int,
	@rDivisionId int,	
	@rOldCategoryId int,	
	@rNewCategoryId int,	 
	@rBatchId int,
	@rOrgId int,
	@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


DECLARE @rOldFeeSetupCount int
DECLARE @rNewFeeSetupCount int
DECLARE @rOldFeeSetupOptionalCount int
DECLARE @rNewFeeSetupOptionalCount int
DECLARE @rFinalFeeSetupCount int
DECLARE @rOldFeeSetupAmount int
DECLARE @rOldFeeSteupTempTableSum int
DECLARE @rFeeAllocationCount int
DECLARE @rFeeOptionalCount int

		BEGIN

		IF OBJECT_ID('tempdb..#OldFeeSteupTempTable') IS NOT NULL
		DROP TABLE #OldFeeSteupTempTable

		IF OBJECT_ID('tempdb..#NewFeeSteupTempTable') IS NOT NULL
		DROP TABLE #NewFeeSteupTempTable

		IF OBJECT_ID('tempdb..#NewFeeSteupOptionalTempTable') IS NOT NULL
		DROP TABLE #NewFeeSteupOptionalTempTable

		IF OBJECT_ID('tempdb..#FinalFeeSteupTempTable') IS NOT NULL
		DROP TABLE #FinalFeeSteupTempTable

		IF OBJECT_ID('tempdb..#OldFeeSteupTempTableSum') IS NOT NULL
		DROP TABLE #OldFeeSteupTempTableSum

		IF OBJECT_ID('tempdb..#FinalFeeSteupTempTableCount') IS NOT NULL
	    DROP TABLE #FinalFeeSteupTempTableCount

		IF OBJECT_ID('tempdb..#FinalFeeAllocation') IS NOT NULL
	    DROP TABLE #FinalFeeAllocation

		IF OBJECT_ID('tempdb..#FinalFeeOptional') IS NOT NULL
	    DROP TABLE #FinalFeeOptional	

		IF OBJECT_ID('tempdb..#tempFeeAllocation') IS NOT NULL
	    DROP TABLE #tempFeeAllocation
		
			SELECT DISTINCT A.AdmissionCategoryId,A.BatchId,FS.ClassId,FS.FeeId,FS.ReceiptBookId as OldFeeReceiptBookId,
			FS.AMOUNT AS OldSetUpAmount,
			RD.Amount AS OldAmount,
			RD.ReceiptId,RD.FeeSetupId,FS.IsOptional,FS.IsVariable INTO #OldFeeSteupTempTable 
			FROM sFee.tFeeSetup FS 
			INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = FS.ID 
			INNER JOIN sFee.tReceipt FR ON FR.ID = RD.RECEIPTID AND FR.IsObsolete=0
			INNER JOIN sStudent.tAcademic A ON  A.Id = FR.SourceId AND A.AdmissionCategoryId=FS.AdmissionCategoryId
			where A.Id=@rAcademicId and FS.ClassId=@rClassId AND A.BatchId=@rBatchId AND A.AdmissionCategoryId=@rOldCategoryId AND FS.AdmissionCategoryId=@rOldCategoryId order by FS.FeeId

			SET @rOldFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #OldFeeSteupTempTable )				
		
		   (SELECT FeeId, SUM(OldAmount) AS Amount,SUM(OldSetUpAmount) AS OldSetUpAmount INTO #OldFeeSteupTempTableSum FROM #OldFeeSteupTempTable WHERE OldSetUpAmount !=0   GROUP BY FeeId)

		   SET @rOldFeeSteupTempTableSum= (SELECT ISNULL(COUNT(1),0) FROM #OldFeeSteupTempTableSum )		

		IF(@rOldFeeSetupCount != 0)
			BEGIN	

				--SELECT Id AS NewFeeSetupId,FeeId,Amount as NewAmount,AdmissionCategoryId,IsOptional,IsVariable,ReceiptBookId AS NewFeeReceiptBookId INTO #NewFeeSteupTempTable  FROM sFee.tFeeSetup 
				--WHERE ClassId=@rClassId and BatchId=@rBatchId and AdmissionCategoryId=@rNewCategoryId 
				--And FeeId IN (SELECT FeeId from #OldFeeSteupTempTable WHERE ClassId=@rClassId AND BatchId=@rBatchId AND AdmissionCategoryId=@rOldCategoryId)				
				--order by FeeId

				SELECT NFS.Id AS NewFeeSetupId,NFS.FeeId,NFS.Amount as NewAmount,NFS.AdmissionCategoryId,NFS.IsOptional,NFS.IsVariable,NFS.ReceiptBookId AS NewFeeReceiptBookId 
				INTO #NewFeeSteupTempTable  
				FROM sFee.tFeeSetup NFS
				INNER JOIN #OldFeeSteupTempTable OST ON  OST.OldFeeReceiptBookId=NFS.ReceiptBookId AND OST.FeeId=NFS.FeeId
				WHERE NFS.ClassId=@rClassId and NFS.BatchId=@rBatchId and NFS.AdmissionCategoryId=@rNewCategoryId 
				order by NFS.FeeId

				SET @rNewFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #NewFeeSteupTempTable)	

				IF((@rOldFeeSetupCount != @rNewFeeSetupCount) AND (@rNewFeeSetupCount < @rOldFeeSetupCount)) 
				BEGIN

				SELECT -103 AS RESULT
				RETURN
				END

				SET @rOldFeeSetupOptionalCount = ( SELECT ISNULL(COUNT(1),0) FROM (SELECT FeeId from #OldFeeSteupTempTable WHERE    (IsOptional=1) OR (IsVariable=1) 	 GROUP BY FeeId) OldTemp )

				SET @rNewFeeSetupOptionalCount = (SELECT ISNULL(COUNT(1),0) FROM ( SELECT FeeId FROM #NewFeeSteupTempTable WHERE (IsOptional=1) OR (IsVariable=1)   GROUP BY FeeId) NewTemp)
			
				IF((  @rNewFeeSetupOptionalCount < @rOldFeeSetupOptionalCount))
				BEGIN

				SELECT -105 AS RESULT
									
				RETURN
				END

				IF((@rNewFeeSetupOptionalCount > 0) OR (@rOldFeeSetupOptionalCount=0))
				BEGIN

					IF(@rNewFeeSetupCount > 0)
						BEGIN

							SELECT OldFee.FeeId,sum(OldFee.Amount ) as Amount INTO #FinalFeeSteupTempTableSum 
							FROM #OldFeeSteupTempTableSum OldFee
							INNER JOIN #NewFeeSteupTempTable NewFee on NewFee.FeeId = OldFee.FeeId 	AND NewFee.AdmissionCategoryId=@rNewCategoryId
							WHERE OldFee.Amount <= NewFee.NewAmount  AND OldFee.OldSetUpAmount !=0 AND  NewFee.NewAmount !=0
							GROUP BY OldFee.FeeId 
							order by OldFee.FeeId
						
							SET @rFinalFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #FinalFeeSteupTempTableSum)

							IF( (@rFinalFeeSetupCount = @rOldFeeSteupTempTableSum))
								BEGIN
									BEGIN TRY
										BEGIN TRANSACTION							 
											BEGIN
												BEGIN
												
												SELECT OldFee.ReceiptId,OldFee.FeeSetupId AS OldFeeSetupId,NewFee.NewFeeSetupId,NewFee.FeeId as NewFeeId
												,OldFee.FeeId as OldFeeId,NewFee.NewAmount,OldFee.OldAmount,NewFee.AdmissionCategoryId,
												NewFee.IsOptional , NewFee.IsVariable
												INTO #FinalFeeSteupTempTable 
												FROM #OldFeeSteupTempTable OldFee
												INNER JOIN #NewFeeSteupTempTable NewFee on NewFee.FeeId = OldFee.FeeId 	AND NewFee.AdmissionCategoryId=@rNewCategoryId
												--WHERE OldFee.OldAmount <= NewFee.NewAmount   
												order by OldFee.FeeId

												set @rFeeAllocationCount= (SELECT ISNULL(COUNT(1),0) FROM sFee.tFeeAllocation  
																		  where SourceId=@rAcademicId 
																		  AND FeeSetupId IN(SELECT OldFeeSetupId FROM #FinalFeeSteupTempTable																		  
																		  where	IsVariable=1																
																		  AND OldAmount !=0 ))

																		set  @rFeeOptionalCount=
																		(SELECT ISNULL(COUNT(1),0) FROM sFee.tFeeOptional
																		  where SourceId=@rAcademicId 
																		  AND FeeSetupId IN(SELECT OldFeeSetupId FROM #FinalFeeSteupTempTable																		  
																		  where	IsOptional=1																
																		  AND OldAmount !=0 ))

													IF(@rFeeAllocationCount = 0 AND @rFeeOptionalCount=0)
														BEGIN										
															INSERT INTO sFee.tFeeAllocation	(SourceTypeId,SourceId,FeeSetupId,VariableAmount,DiscountAmount,CreatedUserId,CreatedDateTime)
															SELECT 2001,@rAcademicId,NewFeeSetupId,OldAmount,0,@rCreatedUserId,GETDATE() FROM #FinalFeeSteupTempTable
															--WHERE  (IsOptional=1) OR (IsVariable=1) 
															 where	IsVariable=1															
															AND OldAmount !=0 

															-- For Fee Process Added By Hemali 2025-01-31
															INSERT INTO sFee.tFeeAllocationStudent (AcademicId,FeeSetupId,FeeAmount,VariableAmount,DiscountAmount,
																	AdditionalAmount, NotApplicableAmount,ToPayAmount,PaidAmount,CreatedUserId,CreatedDateTime)
															SELECT @rAcademicId,NewFeeSetupId,NewAmount,OldAmount,0,0,0,(NewAmount+OldAmount),0,@rCreatedUserId,GETDATE() FROM #FinalFeeSteupTempTable
															 where	IsVariable=1															
															AND OldAmount !=0 
															-- For Fee Process Added By Hemali 2025-01-31

															INSERT INTO sFee.tFeeOptional	(FeeSetupId,SourceTypeId,SourceId,BatchId)
															SELECT NewFeeSetupId,2001,@rAcademicId,@rBatchId FROM #FinalFeeSteupTempTable
															--WHERE ((IsOptional=1 AND IsVariable=0 ) OR (IsOptional=1 AND IsVariable=1))	
															where	IsOptional=1													
															AND OldAmount !=0 

														END
													ELSE
														BEGIN															

															SELECT * INTO #tempFeeAllocation FROM sFee.tFeeAllocation WHERE SourceId=@rAcademicId AND SourceTypeId=2001 
															AND FeeSetupId IN(SELECT FeeSetupId FROM sFee.tFeeOptional WHERE SourceId=@rAcademicId AND SourceTypeId=2001 AND BatchId=@rBatchId)

															DELETE FROM sFee.tFeeAllocation WHERE SourceId=@rAcademicId AND SourceTypeId=2001 
															AND FeeSetupId IN(SELECT FeeSetupId FROM sFee.tFeeOptional WHERE SourceId=@rAcademicId AND SourceTypeId=2001 AND BatchId=@rBatchId)
															
															DELETE FROM sFee.tFeeAllocationStudent WHERE AcademicId=@rAcademicId 
															AND FeeSetupId IN(SELECT FeeSetupId FROM sFee.tFeeOptional WHERE SourceId=@rAcademicId AND SourceTypeId=2001 AND BatchId=@rBatchId)
															
															DELETE FROM sFee.tFeeOptional WHERE SourceId=@rAcademicId AND SourceTypeId=2001 AND BatchId=@rBatchId
															
															SELECT NewFeeSetupId,SUM(OldAmount) as OldAmount,NewAmount INTO #FinalFeeAllocation FROM #FinalFeeSteupTempTable
															WHERE   IsVariable=1															
															AND OldAmount !=0 															
															GROUP BY NewFeeSetupId,NewAmount

															SELECT NewFeeSetupId INTO #FinalFeeOptional FROM #FinalFeeSteupTempTable
															WHERE  IsOptional=1														
															AND OldAmount !=0 														
															GROUP BY NewFeeSetupId															


															INSERT INTO sFee.tFeeAllocation	(SourceTypeId,SourceId,FeeSetupId,VariableAmount,DiscountAmount,CreatedUserId,CreatedDateTime)
															SELECT 2001,@rAcademicId,NewFeeSetupId,OldAmount,0,@rCreatedUserId,GETDATE() FROM #FinalFeeAllocation															

															-- For Fee Process Added By Hemali 2025-01-31
															INSERT INTO sFee.tFeeAllocationStudent (AcademicId,FeeSetupId,FeeAmount,VariableAmount,DiscountAmount,
																	AdditionalAmount, NotApplicableAmount,ToPayAmount,PaidAmount,CreatedUserId,CreatedDateTime)
															SELECT @rAcademicId,NewFeeSetupId,NewAmount,OldAmount,0,0,0,(NewAmount+OldAmount),0,@rCreatedUserId,GETDATE() 
															FROM #FinalFeeAllocation															
															-- For Fee Process Added By Hemali 2025-01-31

															INSERT INTO sFee.tFeeOptional (FeeSetupId,SourceTypeId,SourceId,BatchId)
															SELECT NewFeeSetupId,2001,@rAcademicId,@rBatchId FROM #FinalFeeOptional															

														END
																						
													UPDATE RD SET FeeSetupId =FS.NewFeeSetupId from sFee.tReceiptDetail RD 
													INNER JOIN #FinalFeeSteupTempTable FS ON FS.ReceiptId = RD.ReceiptId 
													AND FS.OldFeeSetupId=RD.FeeSetupId

													UPDATE sStudent.tAcademic set AdmissionCategoryId=@rNewCategoryId 
													WHERE Id=@rAcademicId AND ClassId=@rClassId AND DivisionId=@rDivisionId AND BatchId=@rBatchId AND OrgId=@rOrgId 
													AND AdmissionCategoryId=@rOldCategoryId
												END	
													
												SELECT 1 AS RESULT	
																																																						
											END 
										COMMIT TRANSACTION
									END TRY
									BEGIN CATCH 
										ROLLBACK TRANSACTION
										SELECT -104 AS Result										
										RETURN
									END CATCH	
								END
							ELSE
								BEGIN
									SELECT -103 AS RESULT																
									RETURN
								END
						END
					ELSE
						BEGIN
							SELECT -102 AS Result							
							RETURN
						END
				END
				ELSE
					SELECT -105 AS Result				
					RETURN
				END			
		ELSE
			BEGIN
					UPDATE sStudent.tAcademic set AdmissionCategoryId=@rNewCategoryId 
					WHERE Id=@rAcademicId AND ClassId=@rClassId AND DivisionId=@rDivisionId AND BatchId=@rBatchId AND OrgId=@rOrgId  
				SELECT 1 AS Result
				RETURN
			END
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pChargeAccountMappingAdd]
	 
		   @rChargeId int,
		   @rAccountingYearId int,
           @rCreditLedgerId int,
           @rDebitLedgerId int,
           @rPayTypeId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DELETE FROM sFee.tChargeAccountMapping WHERE ChargeId=@rChargeId AND PayTypeId=@rPayTypeId
	
--IF NOT EXISTS (SELECT 1 FROM sFee.tAccountMapping WHERE FeeSetupId=@rFeeSetupId)		
	BEGIN
	INSERT INTO sFee.tChargeAccountMapping
		(
		   ChargeId,
		   AccountingYearId,
		   CreditLedgerId,
		   DebitLedgerId,
		   PayTypeId
		   
		)
	VALUES
		(
			@rChargeId,
			@rAccountingYearId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rPayTypeId
		)
		SELECT 1 AS Result
		             
	END	 
	
	--ELSE
	
	--BEGIN
	--UPDATE  sFee.tAccountMapping
	--SET
	--     AccountingYearId=@rAccountingYearId,
	--     CreditLedgerId=@rCreditLedgerId,
	--     DebitLedgerId=@rDebitLedgerId,
	--	 PayTypeId=@rPayTypeId
		
	--  WHERE (FeeSetupId = @rFeeSetupId)
	--  SELECT 11 AS Result   
	--END  
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargeAccountMappingGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		 
           --@rChargeCategoryId int,
		   --@rBatchId int,
		   @rOrgGroupId int, 
		   @rChargeCategoryId int,
		   @rPayTypeId int=0			--add for 27383 mantis
		   
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 ISNULL(CM.Id,0)AS ChargeId,
			ISNULL(AM.ChargeId,0)AS AMChargeId,
			--ISNULL(FS.ClassId,0)AS ClassId,
			 
			ISNULL(CM.ChargeCategoryId,0) AS ChargeCategoryId,
			--ISNULL(CR.BatchId,0)AS BatchId,
			 
			ISNULL(AYM.AccountId,0) AS AccountId,
			ISNULL(AM.CreditLedgerId,0) AS CreditLedgerId,
			ISNULL(AM.DebitLedgerId,0) AS DebitLedgerId,
			ISNULL(AM.AccountingYearId,0) AS AccountingYearId,
			ISNULL(AM.PayTypeId,0) AS AMPayTypeId,
			ISNULL(PTM.Id,0) AS PayTypeId,
			ISNULL(PTM.Title,'') AS PayTypeName,
			ISNULL(RB.TItle,'') AS ReceiptBookTitle,
			ISNULL(RB.Id,0) AS ReceiptBookId ,
			CM.Title AS ChargeTitle
  FROM 
		  sFee.tChargeMaster CM
		  inner join  sFee.tChargeCategoryMaster CCM ON CCM.Id = CM.ChargeCategoryId AND CM.ChargeCategoryId=@rChargeCategoryId
		 --INNER JOIN sFee.tChargeReceiptDetail CE ON CE.ChargeId = CM.Id AND CM.ChargeCategoryId=@rChargeCategoryId
		 --INNER JOIN sFee.tChargeReceipt CR ON CR.Id=CE.ChargeReceiptId
		INNER JOIN  sFee.tChargeReceiptBookMaster RB ON CCM.ChargeReceiptBookId = RB.Id
		Cross JOIN sFinanceCommon.tPayTypeMaster PTM
		LEFT JOIN sFee.tChargeAccountMapping AM ON AM.ChargeId=CM.Id AND AM.PayTypeId=PTM.Id	
		LEFT JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=CLM.AccountingYearId AND AYM.Id=DLM.AccountingYearId
WHERE 
		CM.OrgGroupId=@rOrgGroupId
		AND ((PTM.Id=@rPayTypeId) or (@rPayTypeId=0))		--add for 27383 mantis

ORDER BY  PTM.Id

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pChargeCategoryMasterAdd]
	 
	        @rId int
	       --,@rCode nvarchar(20)
	       ,@rReceiptBookId int
           ,@rTitle nvarchar(100)
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 
	
If Exists(select top(1)* from sFee.tChargeCategoryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
BEGIN
	If NOT Exists(select top(1)* from sFee.tChargeCategoryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id=@rId)
	BEGIN
		select -101 as Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tChargeCategoryMaster]
	    SET
			  --Number=@rNumber
	         --,Code=@rCode
	          ChargeReceiptBookId=@rReceiptBookId
	         ,Title=@rTitle
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	 
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION  
	 END  
END
ELSE
BEGIN
IF(@rId = 0)	
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tChargeCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sFee.tChargeCategoryMaster',@lNextNumber = @lNextNumber output
	INSERT INTO [sFee].[tChargeCategoryMaster]
			   (
			    [Id]
			   --,[Code]
			   ,[ChargeReceiptBookId] 
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId] 
			   )
		 VALUES
			   (
				@lNextNumber
			   --,@rCode
			   ,@rReceiptBookId
			   ,@rTitle
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tChargeCategoryMaster]
	    SET
			  --,Code=@rCode
			  ChargeReceiptBookId=@rReceiptBookId
	         ,Title=@rTitle
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	END
	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pChargeCategoryMasterGet]
          
           --@rId bigint,
           @rTitle nvarchar(100),
           @rReceiptBookId int,
           @rOrgGroupId int
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END

BEGIN
SELECT
	   CCM.ChargeReceiptBookId AS ReceiptBookId
	  ,RBM.Title AS ReceiptBook
	  ,CCM.Id as ChargeCategoryId
	  ,CCM.Title as ChargeCategory
      ,CCM.IsObsolete as ChargeCategoryIsObsolete
      ,CCM.OrgGroupId
     
  FROM 
		[sFee].[tChargeCategoryMaster] CCM 
  INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CCM.ChargeReceiptBookId
        
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
		((CCM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((CCM.ChargeReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	AND (CCM.OrgGroupId = @rOrgGroupId)
	--AND  CCM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pChargeMasterAdd]
	 
	        @rId int
	       --,@rNumber int
	       --,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rChargeCategoryId int
           ,@rChargeAmount decimal(12,2)
           ,@rOrderIndex int
           ,@rIsObsolete bit
           --,@rIsDeleted bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 
--If(@rIsDeleted=1)
--BEGIN
--	Delete from sFee.tChargeMaster where Id=@rId
--	Select @rId as Result
--END	
--ELSE
--BEGIN     
	
--If Exists(select top(1)* from sFee.tChargeMaster where Title=@rTitle AND OrgId=@rOrgId)
--BEGIN
--	If NOT Exists(select top(1)* from sFee.tChargeMaster where Title=@rTitle AND OrgId=@rOrgId AND Id=@rId)
--	BEGIN
--		select -101 as Result
--	END
--	ELSE
--	BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  [sFee].[tChargeMaster]
--	    SET
--			  --Number=@rNumber
--	         --,Code=@rCode
--	         Title=@rTitle
--	         ,ChargeCategoryId=@rChargeCategoryId
--	         ,ChargeAmount=@rChargeAmount
--	         ,OrderIndex=@rOrderIndex
--             ,[IsObsolete] = @rIsObsolete                          
--             ,[UpdatedUserId] = @rCreatedUserId
--             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
--	      WHERE Id = @rId 	 
--	      SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION  
--	 END  
--END
--ELSE
--BEGIN
IF(@rId = 0)	
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tChargeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sFee.tChargeMaster',@lNextNumber = @lNextNumber output
	INSERT INTO [sFee].[tChargeMaster]
			   (
			    [Id]
			   --,[Number]  
			   --,[Code]
			   ,[Title]
			   ,[ChargeCategoryId] 
			   ,[ChargeAmount] 
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId] 
			   )
		 VALUES
			   (
				@lNextNumber
			   --,@rNumber
			   --,@rCode
			   ,@rTitle
			   ,@rChargeCategoryId
			   ,@rChargeAmount
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId 
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tChargeMaster]
	    SET
			  --Number=@rNumber
	         --,Code=@rCode
	         Title=@rTitle
	         ,ChargeCategoryId=@rChargeCategoryId
	         ,ChargeAmount=@rChargeAmount
	         ,OrderIndex=@rOrderIndex
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargeMasterGet]
	 @rChargeCategoryId int,
	 --@rCode nvarchar(20),
	 @rOrgGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	 --IF(@rIsSearch=1)
		--BEGIN
			--SET @rGRNo = sCommon.fSearchStringGet(@rGRNo)
			--SET @rLastName = sCommon.fSearchStringGet(@rLastName)
			--SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		--END
	
	SELECT 
			CM.Id,
			--CM.Code,
			--CM.Number,
			CCM.ChargeReceiptBookId AS ReceiptBookId,
			CM.Title,
			CM.ChargeCategoryId,
			CCM.Title as ChargeCategory,
			CM.ChargeAmount,
			CM.OrderIndex,
			CM.IsObsolete
			
  FROM 
			[sFee].[tChargeMaster] CM
			INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
WHERE 
			--((CM.Code=@rCode) OR (ISNULL(@rCode,'') = ''))
			(CM.ChargeCategoryId=@rChargeCategoryId OR @rChargeCategoryId=0)
			AND CM.OrgGroupID=@rOrgGroupId order by CM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            @rTransactionDate date,
            @rNarration nvarchar(1000),  --Change by dhannajay from 150->1000 size for mantis id - 0035082
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rReceiptBookId int,
            @rChequeNo nvarchar(10),
			@rBankName nvarchar(50),
			@rChequeDate datetime,
			@rPayTypeId int,
			@rSourceTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.tChargeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId AND SourceTypeId=@rSourceTypeId)
    BEGIN
		 
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tChargeAccountPosting
		INSERT INTO sFee.tChargeAccountPosting
		(
			Id,
			AccountYearId,
			AccountId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			ReceiptBookId,
			SourceTypeId
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountYearId,
			@1AccountId,
			@rTransactionDate,
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rReceiptBookId,
			@rSourceTypeId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.tChargeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId AND SourceTypeId=@rSourceTypeId
  
 
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting and Narration like '%Charge Receipt%')
	BEGIN
		delete from [sAccounting].[tTransactionDetail] Where TransactionId in (Select Id From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=2 )
		Select Id as result From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=2
		COMMIT TRANSACTION				
		RETURN 
		--SELECT 101 AS Result
		--COMMIT TRANSACTION				
		--RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output		
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    2,
			    @lNextNumberPosting,
			    @rChequeNo,
			    @rBankName,
			    @rChequeDate,
			    '',
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pChargePostingDetailAdd]
	 
            @rTransactionId bigint,
            @rNumber bigint,
		    @rLedgerId bigint,
		    @rAmount decimal(12,2),
		    @rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @1TransactionTypeId int 
		
	 SELECT @1TransactionTypeId = LedgerTypeId FROM sAccounting.tLedgerMaster
	 WHERE Id=@rLedgerId

    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
    
	INSERT INTO [sAccounting].[tTransactionDetail]
			   (
			    [Id],
			    [TransactionId],
			    [Number],
			    [TransactionTypeId],
			    [LedgerId],
			    [Amount]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rTransactionId,
			    @rNumber,
			    @1TransactionTypeId,
			    @rLedgerId,
			    @rAmount
			   )
		    SELECT @lNextNumber AS Result
	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pChargePostingDetailGet]
				
		  -- @rClassId int, 
		   
		   @rOrgGroupId int,
		   @rReceiptDate date,
           @rReceiptDateTo date
            
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			
			--AM.FeeSetupId,
			AMast.Id AS AccountId,
			AMast.Title AS AccountName,
			AM.AccountingYearId,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			AM.PayTypeId,
			PTM.Title AS PayTypeName,
			FM.Id AS ChargeId,
			FM.Title AS ChargeTitle,
			--FHM.Id AS FeeHeadId,
			--FHM.Title AS FeeHeadName,
			--FS.ReceiptBookId AS ReceiptBookId,
			RBM.Title AS ReceiptBookTitle,
			SUM(RD.Amount) AS ReceiptAmount,
			R.ChargeReceiptBookId
			
  FROM 
			sFee.tChargeAccountMapping AM
			INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate
				AND R.ReceiptDate <= @rReceiptDateTo				
			INNER JOIN sFee.tChargeMaster FM ON FM.Id=AM.ChargeId 
		    INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=R.ChargeReceiptBookId	
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = AM.PayTypeId
WHERE 
			FM.OrgGroupId=@rOrgGroupId
			
			GROUP BY 
			AMast.Id,AMast.Title, AM.AccountingYearId,AYM.Title,AM.CreditLedgerId,CLM.Title,
			AM.DebitLedgerId,DLM.Title,AM.PayTypeId,PTM.Title,FM.Id,FM.Title ,ChargeReceiptBookId,
			RBM.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargePostingGet]
				
		   --@rClassId int,
           @rReceiptBookId int=0,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
		   @rReceiptDateTo date,
		   @rChequePosting nvarchar(50),
		   @rOrgGroupBatchID int=0,
		   @rSourceTypeId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	IF @rChequePosting = 'Single'
	BEGIN
			SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					SUM(RD.Amount) AS ReceiptAmount,
					'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,0 AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked	,R.SourceTypeId,	
					--ISNULL(CASE WHEN R.SourceTypeId = 2001 Then 'Student' END,0) AS SourceName,
					--ISNULL(CASE WHEN R.SourceTypeId = 95 Then 'Employee' END,0) AS SourceName,
					CASE WHEN R.SourceTypeId = 2001 Then 'Student' WHEN R.SourceTypeId = 3 then 'Other'
					ELSE 'Employee' END AS Name,
					CRB.Title AS ChargeReceiptBook
					 		
			FROM 
					sFee.tChargeAccountMapping AM
					INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
					INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
						AND R.PayTypeId = AM.PayTypeId 
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
					--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
					----AND (FS.ClassId=@rClassId) 
					AND (R.ChargeReceiptBookId=@rReceiptBookId) 
					--	AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sFee.tChargeMaster FM ON FM.Id=AM.ChargeId 
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId					
					LEFT JOIN sStudent.tAcademic A On A.Id=R.SourceId  AND (R.SourceTypeId = 2001  OR @rSourceTypeId=0)
					LEFT JOIN sHrm.tEmployeeMaster EM On EM.Id=R.SourceId AND (R.SourceTypeId = 95  OR @rSourceTypeId=0)
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.BatchId  
					INNER JOIN sFee.tChargeReceiptBookMaster CRB ON CRB.Id = R.ChargeReceiptBookId
				WHERE 	(R.SourceTypeId =@rSourceTypeId OR @rSourceTypeId=0) AND			    
					AMast.OrgGroupId=@rOrgGroupId	AND BM.OrgGroupBatchId=@rOrgGroupBatchID	
					AND ISNULL(EM.IsOtherUser,0) = 0 	 
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.SourceTypeId,CRB.Title
	 END
	 ELSE
		BEGIN		
		SELECT  
			R.ReceiptDate,
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			SUM(RD.Amount) AS ReceiptAmount,
			'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,0 AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked	,R.SourceTypeId,
			CASE WHEN R.SourceTypeId = 2001 Then 'Student' WHEN R.SourceTypeId = 3 then 'Other' ELSE 'Employee' END AS Name,
			CRB.Title AS ChargeReceiptBook			
		FROM 
			sFee.tChargeAccountMapping AM
			INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate 
				AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
			--AND (FS.ClassId=@rClassId) 
			AND (R.ChargeReceiptBookId=@rReceiptBookId) 
				--AND (R.OrgGroupBatchId=@rBatchId)
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
             LEFT JOIN sStudent.tAcademic A On A.Id=R.SourceId AND (R.SourceTypeId = 2001  OR @rSourceTypeId=0)
             LEFT JOIN sHrm.tEmployeeMaster EM On EM.Id=R.SourceId AND (R.SourceTypeId = 95  OR @rSourceTypeId=0)
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.BatchId  
            INNER JOIN sFee.tChargeReceiptBookMaster CRB ON CRB.Id = R.ChargeReceiptBookId
		WHERE (R.SourceTypeId =@rSourceTypeId OR @rSourceTypeId=0) AND
			AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1 AND BM.OrgGroupBatchId=@rOrgGroupBatchID
			AND ISNULL(EM.IsOtherUser,0) = 0 
			GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.SourceTypeId,CRB.Title
			
		UNION ALL
		
		SELECT  
			R.ReceiptDate,
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			Sum(RD.Amount) AS ReceiptAmount,
			R.ChequeNo,R.ChequeDate,R.BankName,R.PayTypeId AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked,
			R.SourceTypeId,
			CASE WHEN R.SourceTypeId = 2001 Then 'Student' WHEN R.SourceTypeId = 3 then 'Other'	ELSE 'Employee' END AS Name,
			CRB.Title AS ChargeReceiptBook
				
						
		FROM 
			sFee.tChargeAccountMapping AM
			INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate  
				AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
			AND (R.ChargeReceiptBookId=@rReceiptBookId) 
			--	AND (R.OrgGroupBatchId=@rBatchId)
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
            LEFT JOIN sStudent.tAcademic A On A.Id=R.SourceId AND (R.SourceTypeId = 2001  OR @rSourceTypeId=0)
			LEFT JOIN sHrm.tEmployeeMaster EM On EM.Id=R.SourceId AND (R.SourceTypeId = 95  OR @rSourceTypeId=0)
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.BatchId  
            INNER JOIN sFee.tChargeReceiptBookMaster CRB ON CRB.Id = R.ChargeReceiptBookId
		WHERE (R.SourceTypeId =@rSourceTypeId OR @rSourceTypeId=0) AND R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId	  AND BM.OrgGroupBatchId=@rOrgGroupBatchID		
		AND ISNULL(EM.IsOtherUser,0) = 0 
		GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ChequeNo,R.ChequeDate,R.BankName,R.PayTypeId,R.SourceTypeId,CRB.Title
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptAdd] 
	@rId BIGINT
	,@rSourceTypeId SMALLINT
	,@rSourceId BIGINT
	,@rGuestName NVARCHAR(200)
	,@rReceiptBookId INT
	,@rRemark NVARCHAR(200)
	,@rReceiptNumber INT
	,@rReceiptDate DATE
	,@rPayTypeId TINYINT
	,@rChequeNo NVARCHAR(20)
	,@rBankName NVARCHAR(200)
	,@rIsObsolete BIT
	,@rOrgId INT
	,@rBatchId INT
	,@rOrgGroupBatchId INT
	,@rCreatedUserId BIGINT
	,@rReceiptAmount DECIMAL(12, 2)
	,@rChequeDate DATE = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		IF (@rId = 0)
		BEGIN
			--  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2002,@rStoreLocationId = 0, @rNextNumber  = @rReceiptNumber OUTPUT
			--SET @rReceiptNumber = ISNULL(@rReceiptNumber, '-300')
			--		IF @rReceiptNumber = '-300'
			--	  BEGIN
			--		SELECT -300 AS Result, '' AS ReceiptNumber, 0 AS Id 
			--		RETURN
			--	  END
			SELECT @rOrgGroupBatchId = OrgGroupBatchId
			FROM sSetup.tBatchMaster
			WHERE Id = @rBatchId

			IF (@rReceiptNumber <> 0)
			BEGIN
				IF EXISTS (
						SELECT 1
						FROM sFee.tChargeReceipt
						WHERE ReceiptNumber = @rReceiptNumber
							AND ChargeReceiptBookId = @rReceiptBookId
							AND OrgGroupBatchId = @rOrgGroupBatchId
						)
				BEGIN
					SELECT - 102 AS Result
					RETURN
				END
			END
			ELSE
				SET @rReceiptNumber = sFee.fChargeReceiptNumberGet(@rReceiptBookId, @rOrgGroupBatchId)

			BEGIN TRANSACTION

			DECLARE @lNextNumber BIGINT

			EXECUTE sCommon.pTableRowIdGet @rOrgId
				,'sFee.tChargeReceipt'
				,0
				,1
				,1
				,@outNextNumber = @lNextNumber OUTPUT

			INSERT INTO sFee.tChargeReceipt (
				Id
				,SourceTypeId
				,SourceId
				,GuestName
				,ChargeReceiptBookId
				,Remark
				,ReceiptNumber
				,ReceiptDate
				,PayTypeId
				,ChequeNo
				,BankName
				,IsObsolete
				,CreatedUserId
				,CreatedDateTime
				,OrgId
				,BatchId
				,OrgGroupBatchId
				,ReceiptAmount
				,ChequeDate
				)
			VALUES (
				@lNextNumber
				,@rSourceTypeId
				,@rSourceId
				,@rGuestName
				,@rReceiptBookId
				,@rRemark
				,@rReceiptNumber
				,@rReceiptDate
				,@rPayTypeId
				,@rChequeNo
				,@rBankName
				,@rIsObsolete
				,@rCreatedUserId
				,sCommon.fGetDate()
				,@rOrgId
				,@rBatchId
				,@rOrgGroupBatchId
				,@rReceiptAmount
				,@rChequeDate
				)
			
			COMMIT TRANSACTION
		END
		ELSE
		BEGIN
			BEGIN TRANSACTION
			SET @lNextNumber = @rId

			UPDATE sFee.tChargeReceipt
			SET SourceTypeId = @rSourceTypeId
				,SourceId = @rSourceId
				,GuestName = @rGuestName
				,ChargeReceiptBookId = @rReceiptBookId
				,Remark = @rRemark
				,ReceiptNumber = @rReceiptNumber
				,ReceiptDate = @rReceiptDate
				,PayTypeId = @rPayTypeId
				,ChequeNo = @rChequeNo
				,BankName = @rBankName
				,IsObsolete = @rIsObsolete
				,UpdatedUserId = @rCreatedUserId
				,UpdatedDateTime = sCommon.fGetDate()
				,ReceiptAmount = @rReceiptAmount
				,ChequeDate = @rChequeDate
			WHERE Id = @rId
			
			COMMIT TRANSACTION
		END
		SELECT @lNextNumber AS Result
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptBookMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFullTitle nvarchar(200)
           ,@rAddress1 nvarchar(200)
           ,@rAddress2 nvarchar(200)
           ,@rBankAccountNumber nvarchar(50)
           ,@rIsObsolete bit
           ,@rRemark1 nvarchar(500)
           ,@rRemark2 nvarchar(500)
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rIsOnPrePrinted bit
           ,@rReportId int
           ,@rIsSupressLogo bit
           ,@rOrderIndex int
           ,@rIsDisplaySchoolName bit
           ,@rBankName nvarchar(150)=''
           ,@rGroupTitle nvarchar(200)=''
		    ,@rHeaderDisplayId tinyint
		   ,@rReceiptBookHeader varbinary(max)=NULL
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
If Exists(select top(1)* from sFee.tChargeReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId) 
BEGIN
	If NOT Exists(select top(1)* from sFee.tChargeReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id=@rId)
	BEGIN
		select -101 as Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tChargeReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete      
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo   
             ,OrderIndex=@rOrderIndex       
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
              ,BankName=@rBankName
              ,GroupTitle =@rGroupTitle
			   ,ReceiptBookHeader=@rReceiptBookHeader
			 ,HeaderDisplayId=@rHeaderDisplayId
             
	      WHERE Id = @rId 	 
	      SELECT @lNextNumber AS Result
	 END  
END
ELSE
BEGIN
IF(@rId = 0)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tChargeReceiptBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tChargeReceiptBookMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[FullTitle]
			   ,[Address1] 
			   ,[Address2] 
			   ,[BankAccountNumber] 
			   ,[IsObsolete]
			   ,[Remark1] 
			   ,[Remark2] 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,IsOnPrePrinted
			   ,ReportId
			   ,IsSupressLogo
			   ,OrderIndex
			   ,IsDisplaySchoolName
			   ,BankName
			   ,GroupTitle
			    ,HeaderDisplayId
			   ,ReceiptBookHeader
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   ,@rBankName
			   ,@rGroupTitle
			    ,@rHeaderDisplayId
			   ,@rReceiptBookHeader
			   )
			   
			   
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2018
		   ,@lNextNumber
		   ,@rCreatedUserId
			   
			   
		    SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tChargeReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete          
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2                     
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()   
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo
             ,OrderIndex=@rOrderIndex              
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,BankName=@rBankName
             ,GroupTitle =@rGroupTitle
			  ,HeaderDisplayId=@rHeaderDisplayId
			 ,ReceiptBookHeader=@rReceiptBookHeader
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  
		
	END
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptBookMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int,
           @rIsWildCardSearch bit
 
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT CRBM.Id 
	  ,CRBM.Code
      ,CRBM.Title
      ,CRBM.FullTitle
      ,CRBM.Address1
      ,CRBM.Address2
      ,CRBM.BankAccountNumber
      ,CRBM.IsObsolete
      ,CRBM.Remark1
      ,CRBM.Remark2
      ,ISNULL(CRBM.IsOnPrePrinted ,0) AS IsOnPrePrinted
      ,ISNULL(CRBM.IsSupressLogo,0) AS IsSupressLogo
      ,CRBM.ReportId  
       --,CRBM.OrderIndex  
      ,ISNULL(CRBM.OrderIndex,0) AS OrderIndex
      ,ISNULL(CRBM.IsDisplaySchoolName ,0) AS IsDisplaySchoolName
      ,ISNULL(CRBM.BankName,'') AS BankName
      ,ISNULL(CRBM.GroupTitle,'') AS GroupTitle
        ,ISNULL(CRBM.HeaderDisplayId,1) AS HeaderDisplayId
	  ,CRBM.ReceiptBookHeader
     
  FROM [sFee].[tChargeReceiptBookMaster] CRBM  
        
  WHERE 
		 CRBM.Id = @rId OR @rId = 0
	AND ((CRBM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((CRBM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND  CRBM.OrgGroupId = @rOrgGroupId 
	--AND  QM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptDashBoardGet]
	
	@rOrgId int  =0,
	@rOrgGroupId int=0,
	@rOrgGroupBatchId bigint  =0,
	@rCommonOrgGroupBatchId int=0,
	@rFromDate varchar(10)='',
	@rToDate varchar(10)='',
	@rChargeType nvarchar(100)='',
	@rChargeReceiptBookId int=0,
	@rUserId Bigint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
		--Changes for Mantis Id: 0039838
	DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;
		
	WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
	    FROM sCommon.fnsplit(@lConfigValue, '-')
	)
	SELECT 
	    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
	    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
	FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

	IF OBJECT_ID('tempdb..#tempReceiptOrganizationSync') IS NOT NULL DROP TABLE #tempReceiptOrganizationSync
	IF OBJECT_ID('tempdb..#tempReceiptOrgSync') IS NOT NULL DROP TABLE #tempReceiptOrgSync
	IF OBJECT_ID('tempdb..#tempReceiptUserSync') IS NOT NULL DROP TABLE #tempReceiptUserSync
	IF OBJECT_ID('tempdb..#tempReceiptBookWise') IS NOT NULL DROP TABLE #tempReceiptBookWise
	IF OBJECT_ID('tempdb..#tempReceiptUserWise') IS NOT NULL DROP TABLE #tempReceiptUserWise
	IF OBJECT_ID('tempdb..#tempReceiptOrgWise') IS NOT NULL DROP TABLE #tempReceiptOrgWise
	IF OBJECT_ID('tempdb..#tempReceiptOrgCountWise') IS NOT NULL DROP TABLE #tempReceiptOrgCountWise
	IF OBJECT_ID('tempdb..#tempReceiptOrgwiseSync') IS NOT NULL DROP TABLE #tempReceiptOrgwiseSync
	
	IF(@rChargeType='ReceiptBookwise' OR @rChargeType='ReceiptCountwise' OR @rChargeType='ReceiptAmountwise' OR @rChargeType='ReceiptCancelAmountwise')
	BEGIN
		CREATE TABLE #tempReceiptOrganizationSync
		(
			OrgGroupId int,
			OrgGroupName nvarchar(500),
			ReceiptId bigint,
			TotalReceiptAmount DECIMAL(12,2),
			IsObsolete bit,
			ChargeReceiptBookId int,
			ReceiptBookName nvarchar(100)
		)
		
		INSERT INTO #tempReceiptOrganizationSync
		SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,CR.Id AS ReceiptId,CR.ReceiptAmount,CR.IsObsolete
			  ,CR.ChargeReceiptBookId,RBM.Title As ReceiptBookName
		FROM  sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE COGBM.Id=@rCommonOrgGroupBatchId AND CR.SourceTypeId = 2001
			  AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
			  AND ( (OM.Id= @rOrgId) OR  (@rOrgId=0) )
			  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			  AND (COGBM.Id=@rCommonOrgGroupBatchId ) AND ISNULL(O.IsObsolete,0) = 0 
			  AND (CR.ReceiptDate between @rFromDate and @rToDate)
			  -- IsInContext
			  AND BM.IsInContext = 1    

		CREATE TABLE #tempReceiptBookWise
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptCount int,
			TotalReceiptAmount DECIMAL(12,2),
			CancelAmount DECIMAL(12,2),
			ReceiptDate datetime,
			CommonOrgGroupBatchId int,
			UpdateDate datetime,
			ChargeReceiptBookId int,
			ReceiptBookName nvarchar(100)
		)

		INSERT INTO #tempReceiptBookWise
		SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00) AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate(),T.ChargeReceiptBookId,T.ReceiptBookName
		FROM #tempReceiptOrganizationSync T  
		LEFT JOIN (
		SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganizationSync WHERE IsObsolete = 1
		GROUP BY OrgGroupId,OrgGroupName
		) A ON A.OrgGroupId=t.OrgGroupId
		WHERE IsObsolete = 0
		GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount,T.ChargeReceiptBookId,T.ReceiptBookName
		ORDER BY OrgGroupId

		SELECT TR.OrgGroupId,TR.OrgGroupName,TR.ReceiptCount,TR.TotalReceiptAmount AS ReceiptAmount,TR.CancelAmount,TR.ReceiptDate 
			  ,TR.CommonOrgGroupBatchId,TR.UpdateDate ,TR.ChargeReceiptBookId,TR.ReceiptBookName  
		FROM #tempReceiptBookWise TR
		WHERE TR.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((TR.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			  AND ((TR.ChargeReceiptBookId=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
	END	

	ELSE IF(@rChargeType='Userwise' OR @rChargeType='UserReceiptCountwise' OR @rChargeType='UserReceiptAmountwise' OR @rChargeType='UserReceiptCancelAmountwise')
	BEGIN
		CREATE TABLE #tempReceiptUserSync
		(
			OrgGroupId int,
			OrgGroupName nvarchar(500),
			ReceiptId bigint,
			TotalReceiptAmount DECIMAL(12,2),
			IsObsolete bit,
			CreatedUserId Bigint,
			UserId Bigint,
			UserName nvarchar(50)
		)
		
		INSERT INTO #tempReceiptUserSync
		SELECT OMM.Id AS OrgGroupId,OMM.Title AS OrgGroupName,CR.Id AS ReceiptId,CR.ReceiptAmount,CR.IsObsolete
			  ,CR.CreatedUserId,U.Id As UserId,U.DisplayTitle AS UserName
		FROM  sFee.tChargeReceipt CR		
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=CR.CreatedUserId
		WHERE CR.SourceTypeId = 2001 AND (COGBM.Id=@rCommonOrgGroupBatchId )
			  AND ((OMM.Id= @rOrgGroupId) OR (@rOrgGroupId=0) )
			  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			  AND ((OM.Id= @rOrgId) OR (@rOrgId=0)) AND ISNULL(OMM.IsObsolete,0) = 0 
			  AND (CR.ReceiptDate between @rFromDate AND @rToDate) 
			  -- IsInContext
			  AND BM.IsInContext = 1    

		CREATE TABLE #tempReceiptUserWise
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptCount int,
			TotalReceiptAmount DECIMAL(12,2),
			CancelAmount DECIMAL(12,2),
			ReceiptDate datetime,
			CommonOrgGroupBatchId int,
			UpdateDate datetime,
			UserId Bigint,
			UserName nvarchar(50)
		)
		INSERT INTO #tempReceiptUserWise
		SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00) AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate(),T.UserId,T.UserName
		FROM #tempReceiptUserSync T  
		LEFT JOIN (
		SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptUserSync WHERE IsObsolete = 1
		GROUP BY OrgGroupId,OrgGroupName
		) A ON A.OrgGroupId=t.OrgGroupId
		WHERE IsObsolete = 0
		GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount,T.CreatedUserId,T.UserId,T.UserName
		ORDER BY OrgGroupId

		SELECT TR.OrgGroupId,TR.OrgGroupName, TR.ReceiptCount,TR.TotalReceiptAmount AS ReceiptAmount,TR.CancelAmount,
			   TR.ReceiptDate,TR.CommonOrgGroupBatchId,TR.UpdateDate,TR.UserId,TR.UserName 
		FROM #tempReceiptUserWise TR
		WHERE TR.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((TR.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			AND ((TR.UserId=@rUserId) OR (@rUserId=0))
	END

	ELSE IF(@rChargeType='Organizationwise')
	BEGIN
		CREATE TABLE #tempReceiptOrgSync
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptId bigint,
			TotalReceiptAmount DECIMAL(12,2),
			IsObsolete bit
		)
		
		INSERT INTO #tempReceiptOrgSync
		SELECT OM.Id AS OrgGroupId ,OM.DisplayTitle AS OrgGroupName,CR.Id AS ReceiptId,CR.ReceiptAmount AS TotalReceiptAmount,CR.IsObsolete
		FROM  sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster CRBM ON CRBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CR.OrgId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OM.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=CR.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId	
		WHERE CR.SourceTypeId = 2001
			  AND ((O.Id= @rOrgGroupId) OR (@rOrgGroupId=0) )
			  AND ((OGBM.Id = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			  AND (COGBM.Id=@rCommonOrgGroupBatchId) AND ISNULL(O.IsObsolete,0) = 0 
			  AND (CR.ReceiptDate between @rFromDate AND @rToDate) 
			  AND BM.IsInContext = 1 

		CREATE TABLE #tempReceiptOrgWise
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptCount int,
			TotalReceiptAmount DECIMAL(12,2),
			CancelAmount DECIMAL(12,2),
			ReceiptDate datetime,
			CommonOrgGroupBatchId int,
			UpdateDate datetime
		)
		INSERT INTO #tempReceiptOrgWise
		SELECT  T.OrgGroupId,T.OrgGroupName
			,ISNULL((Select Count(ReceiptId) from #tempReceiptOrgSync where IsObsolete=0 AND OrgGroupId=T.OrgGroupId),0) AS ReceiptCount
			,ISNULL((Select SUM(TotalReceiptAmount) from #tempReceiptOrgSync where IsObsolete=0 AND OrgGroupId=T.OrgGroupId),0.00) AS TotalReceiptAmount 
			,ISNULL((Select SUM(TotalReceiptAmount) from #tempReceiptOrgSync where IsObsolete=1 AND OrgGroupId=T.OrgGroupId),0.00) AS CancelAmount
			,@rFromDate,@rCommonOrgGroupBatchId,GetDate()
		FROM #tempReceiptOrgSync T  
		--LEFT JOIN (
		--SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrgSync 
		--WHERE IsObsolete = 1
		--GROUP BY OrgGroupId,OrgGroupName
		--) A ON A.OrgGroupId=t.OrgGroupId
		--WHERE IsObsolete = 0
		GROUP BY T.OrgGroupId,T.OrgGroupName--,A.CancelReceiptCount
		ORDER BY OrgGroupId

		SELECT ISNULL(TR.OrgGroupId,0) AS OrgGroupId,ISNULL(TR.OrgGroupName,'') AS OrgGroupName,ISNULL(TR.ReceiptCount,0) AS ReceiptCount
			,ISNULL(TR.TotalReceiptAmount,0.00) AS ReceiptAmount,ISNULL(TR.CancelAmount,0.00) AS CancelAmount,ISNULL(TR.ReceiptDate,'') AS ReceiptDate
			,ISNULL(TR.CommonOrgGroupBatchId,0) AS CommonOrgGroupBatchId,ISNULL(TR.UpdateDate,'') AS UpdateDate
		FROM #tempReceiptOrgWise TR
		GROUP BY TR.OrgGroupId,TR.OrgGroupName,TR.ReceiptCount,TR.TotalReceiptAmount,TR.CancelAmount ,
			TR.ReceiptDate ,TR.CommonOrgGroupBatchId ,TR.UpdateDate
	END

	ELSE IF(@rChargeType='OrganizationCountwise' OR @rChargeType='OrganizationAmountwise' OR @rChargeType='OrganizationCancelAmountwise')
	BEGIN
		CREATE TABLE #tempReceiptOrgwiseSync
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptId bigint,
			TotalReceiptAmount DECIMAL(12,2),
			IsObsolete bit
		)
		
		INSERT INTO #tempReceiptOrgwiseSync
		SELECT OM.Id AS OrgGroupId ,OM.DisplayTitle AS OrgGroupName,CR.Id AS ReceiptId,CR.ReceiptAmount AS TotalReceiptAmount,CR.IsObsolete
		FROM  sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster CRBM ON CRBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CR.OrgId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OM.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=CR.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
		WHERE CR.SourceTypeId = 2001
			  AND ((OM.Id= @rOrgId) OR (@rOrgId=0) )
			  AND ((OGBM.Id = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			  AND (COGBM.Id=@rCommonOrgGroupBatchId) AND ISNULL(O.IsObsolete,0) = 0 
			  AND (CR.ReceiptDate between @rFromDate AND @rToDate)   
			  -- IsInContext
			  AND BM.IsInContext = 1 

		CREATE TABLE #tempReceiptOrgCountWise
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptCount int,
			TotalReceiptAmount DECIMAL(12,2),
			CancelAmount DECIMAL(12,2),
			ReceiptDate datetime,
			CommonOrgGroupBatchId int,
			UpdateDate datetime
		)
		INSERT INTO #tempReceiptOrgCountWise
		SELECT  T.OrgGroupId,T.OrgGroupName
		,ISNULL((Select Count(ReceiptId) from #tempReceiptOrgwiseSync where IsObsolete=0 AND OrgGroupId=T.OrgGroupId),0) AS ReceiptCount
		,ISNULL((Select SUM(TotalReceiptAmount) from #tempReceiptOrgwiseSync where IsObsolete=0 AND OrgGroupId=T.OrgGroupId),0.00) AS TotalReceiptAmount 
		,ISNULL((Select SUM(TotalReceiptAmount) from #tempReceiptOrgwiseSync where IsObsolete=1 AND OrgGroupId=T.OrgGroupId),0.00) AS CancelAmount
		,@rFromDate,@rCommonOrgGroupBatchId,GetDate()
		FROM #tempReceiptOrgwiseSync T  
		--LEFT JOIN (
		--SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrgwiseSync WHERE IsObsolete = 1
		--GROUP BY OrgGroupId,OrgGroupName
		--) A ON A.OrgGroupId=t.OrgGroupId
		--WHERE IsObsolete = 0
		GROUP BY T.OrgGroupId,T.OrgGroupName--,A.CancelReceiptCount
		ORDER BY OrgGroupId

		SELECT ISNULL(TR.OrgGroupId,0) AS OrgGroupId,ISNULL(TR.OrgGroupName,'') AS OrgGroupName, ISNULL(TR.ReceiptCount,0) AS ReceiptCount
			,ISNULL(TR.TotalReceiptAmount,0.00) AS ReceiptAmount,ISNULL(TR.CancelAmount,0.00) AS CancelAmount,ISNULL(TR.ReceiptDate,'') AS ReceiptDate
			,ISNULL(TR.CommonOrgGroupBatchId,0) AS CommonOrgGroupBatchId,ISNULL(TR.UpdateDate,'') AS UpdateDate
		FROM #tempReceiptOrgCountWise TR
		GROUP BY TR.OrgGroupId,TR.OrgGroupName,TR.ReceiptCount,TR.TotalReceiptAmount,TR.CancelAmount ,
			TR.ReceiptDate ,TR.CommonOrgGroupBatchId ,TR.UpdateDate
	END

	ELSE IF(@rChargeType='OrganizationReceiptCountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CR.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=CR.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
		WHERE   COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 AND CR.IsObsolete=0						 
				AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((OM.Id= @rOrgId) OR (@rOrgId=0) )AND OMM.IsObsolete = 0
				AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
				AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
				AND ((CR.ChargeReceiptBookId=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
				-- IsInContext
			    AND BM.IsInContext = 1
		Order By CR.ReceiptNumber
	END

	ELSE IF(@rChargeType='OrganizationReceiptAmountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CR.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=CR.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
		WHERE   COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 AND CR.IsObsolete=0					 
				AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((OM.Id= @rOrgId) OR (@rOrgId=0) )AND OMM.IsObsolete = 0
				AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
				AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
				AND ((CR.ChargeReceiptBookId=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
				-- IsInContext
			    AND BM.IsInContext = 1
		Order By CR.ReceiptNumber
	END

	ELSE IF(@rChargeType='OrganizationReceiptCancelAmountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount AS CancelAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CR.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=CR.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
		WHERE COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 AND CR.IsObsolete=1				 
			  AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
			  AND ((OM.Id= @rOrgId) OR (@rOrgId=0) ) AND OMM.IsObsolete = 0
			  AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
			  AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
			  -- IsInContext
			  AND BM.IsInContext = 1
	END
	
	ELSE IF(@rChargeType='ReceiptBookAmountwise' OR @rChargeType='ReceiptBookCountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 					 
			 AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
			 AND ((OM.Id= @rOrgId) OR (@rOrgId=0)) AND OMM.IsObsolete = 0
			 AND ((RBM.Id=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
			 AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
			 AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
			 -- IsInContext
			 AND BM.IsInContext = 1
	END

	ELSE IF(@rChargeType='ReceiptBookCancelAmountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount AS CancelAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 					 
			   AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
			   AND ((RBM.Id=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
			   AND ((OM.Id= @rOrgId) OR (@rOrgId=0)) AND OMM.IsObsolete = 1
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
			   -- IsInContext
			   AND BM.IsInContext = 1
	END

	ELSE IF(@rChargeType='UserAmountwise' OR @rChargeType='UserCountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=CR.CreatedUserId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 					 
			   AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
			   AND ((U.Id=@rUserId) OR (@rUserId=0))
			   AND ((OM.Id= @rOrgId) OR (@rOrgId=0)) AND OMM.IsObsolete = 0
			   AND ((RBM.Id=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
			   -- IsInContext
			   AND BM.IsInContext = 1
	END

	ELSE IF(@rChargeType='UserCancelAmountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount AS CancelAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=CR.CreatedUserId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 					 
			   AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
			   AND ((U.Id=@rUserId) OR (@rUserId=0))
			   AND ((OM.Id= @rOrgId) OR (@rOrgId=0)) AND OMM.IsObsolete = 1
			   AND ((RBM.Id=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
			   -- IsInContext
			   AND BM.IsInContext = 1
	END

	END TRY 

	BEGIN CATCH
	SELECT -1 AS Result,ERROR_LINE(),ERROR_MESSAGE()
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sFee.tChargeReceiptDetail where ChargeReceiptId=@rId
			Delete from sFee.tChargeReceipt where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptDeletedLog]

	 @rChargeReceiptId bigint,
	 @rUserId bigint=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
	BEGIN TRANSACTION	
		--Charge Receipt Delete
		INSERT INTO 
			sAudit.tChargeDeleted 
		SELECT 
			CR.OrgId,
			Id,
			SA.Code,
			SourceTypeId,
			SourceId,
			SA.FirstName + ' ' + SA.MiddleName + ' ' + SA.LastName AS SourceName,
			Remark,
			ReceiptNumber,
			ReceiptDate,
			PayTypeId,
			ChequeNo,
			BankName,
			IsObsolete,
			CR.BatchId,
			(select Title from sFee.tChargeReceiptBookMaster CB where CB.Id=CR.ChargeReceiptBookId) AS ChargeReceiptBookName,			
			CR.OrgGroupBatchId,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=CR.CreatedUserId),
			CreatedDateTime,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=CR.CreatedUserId),
			UpdatedDateTime,		
			ReceiptAmount,
			ChequeDate,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=@rUserId),
			sCommon.fGetDate(),
			CR.DeleteRemark,
			CR.CancelRemark
		FROM 
			sFee.tChargeReceipt CR
			INNER join sStudent.vStudentAcademic SA ON CR.SourceId=SA.AcademicId
		WHERE 
			Id=@rChargeReceiptId 
		
		-- Charge Receipt Detail Delete
		INSERT INTO 
			sAudit.tChargeDetailDelete 
		SELECT
			ChargeReceiptId,
			CM.Title,
			Amount
		FROM
			sFee.tChargeReceipt CR 
			INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id 
			INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId 
			INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		WHERE 
			ChargeReceiptId=@rChargeReceiptId
		
		SELECT 1 AS Result
		
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, Error_message(),Error_line()
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptDetailAdd]
	 
	@rChargeReceiptId bigint,
	@rChargeId int,
	@rRemark nvarchar(100),
	@rAmount decimal(12,2),
	@rIsObsolete bit,
	@rIsDeleted bit,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rStockIssueId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 IF(@rIsDeleted=1)
	 BEGIN
		DELETE FROM sFee.tChargeReceiptDetail WHERE ChargeReceiptId=@rChargeReceiptId AND ChargeId=@rChargeId
	 END
	 ELSE
	 BEGIN
	 IF NOT EXISTS(SELECT 1 FROM sFee.tChargeReceiptDetail WHERE ChargeReceiptId=@rChargeReceiptId AND ChargeId=@rChargeId)	
	 BEGIN
		INSERT INTO sFee.tChargeReceiptDetail
			(
				ChargeReceiptId,
				ChargeId,
				Remark,
				Amount,
				IsObsolete,
				UpdatedUserId,
				UpdatedDateTime,
				StockIssueId
			)
		VALUES
			(
				@rChargeReceiptId,
				@rChargeId,
				@rRemark,
				@rAmount,
				@rIsObsolete,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rStockIssueId
			)
			             
		END	 
		ELSE
	    UPDATE  sFee.tChargeReceiptDetail
	    SET
			Remark=@rRemark,
			Amount=@rAmount,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			StockIssueId=@rStockIssueId
			
	      
	      WHERE ChargeReceiptId=@rChargeReceiptId
			AND ChargeId=@rChargeId
	END	 	
		SELECT 1 AS Result
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptDetailGet]
	 
	 @rId bigint,
	 @rReceiptNumber int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
IF(@rChargeCategoryId=0)
BEGIN		
	SELECT 
			--CR.Id,
			--CR.SourceTypeId,
			--CR.SourceId,
			--CR.GuestName,
			--CR.Remark,
			--CR.ReceiptNumber,
			--CR.ReceiptDate,
			--CR.PayTypeId,
			--CR.ChequeNo,
			--CR.BankName,
			--CR.IsObsolete
			CRD.ChargeReceiptId,
			CRD.ChargeId,
			CRD.Remark as DetailRemark,
			CRD.Amount as amount,
			--CM.Code,
			CM.Title,
			CM.OrderIndex
			--CM.ChargeCategoryId,
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId AND CM.OrgGroupId=@rOrgGroupId
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
  WHERE 
  
			((CR.Id=@rId OR @rId=0))
			AND ((CR.ReceiptNumber=@rReceiptNumber) OR (@rReceiptNumber=''))
			--AND (CR.IsObsolete=0)
			AND (CCM.ChargeReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
			AND (CM.ChargeCategoryId=@rChargeCategoryId OR @rChargeCategoryId=0)
			AND (CRD.IsObsolete=0)
			order by CM.OrderIndex
END
ELSE
BEGIN
		SELECT 
			0 as ChargeReceiptId,
			CM.Id as ChargeId,
			--CM.Code,
			CM.Title,
			CM.ChargeCategoryId,
			'' as DetailRemark,
			CM.ChargeAmount as Amount,
			CM.OrderIndex
  FROM 
			[sFee].[tChargeMaster] CM
       INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
WHERE		
			(CCM.ChargeReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
			AND (CM.ChargeCategoryId=@rChargeCategoryId OR @rChargeCategoryId=0)
			AND (CM.IsObsolete=0)
			AND CM.OrgGroupId=@rOrgGroupId order by CM.OrderIndex
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptDetailXMLAdd]
	
	@rChargeReceiptDetail nvarchar(max),
	@rSourceTypeId int,
	@rOrgId int,
	@rBatchId int,
	@rReceiptBookId int,
	@rOrgGroupBatchId int,
	@rUserId bigint,
	--@rIsChargeAmountEditable bit
	@rIsObsolete bit =0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--DECLARE @loDoc INT
--EXEC sp_xml_preparedocument @loDoc OUTPUT, @rCandidateApplicationEmployementXml
	
	DECLARE @rChargeReceiptDetailXML XML
	SET @rChargeReceiptDetailXML = CAST(@rChargeReceiptDetail AS XML)
	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT
	DECLARE @lReceiptDetailXML XML
	DECLARE @lReceiptAmount	DECIMAL(12,2)	
 
	--EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rChargeReceiptDetailXML
		
	BEGIN TRY
	
		IF OBJECT_ID('tempdb..#TempChargeReceipt') IS NOT NULL
			BEGIN
				-- If the table exists, drop it
				DROP TABLE #TempChargeReceipt;
			END

		CREATE TABLE #TempChargeReceipt  
		(
			Id bigint identity,
			OrgId int ,
			SourceTypeId int ,
			SourceId bigint,
			GuestName nvarchar(300),
			ReceiptDate Date,
			PayTypeId int,
			ChequeNo nvarchar(20),
			BankName nvarchar(200),
			BatchId int,
			ReceiptBookId int,
			OrgGroupBatchId int,
			CreatedUserId bigint,
			ChequeDate date,
			ReceiptDetailXML XML
		)
		INSERT INTO #TempChargeReceipt(
			OrgId ,
			SourceTypeId ,
			SourceId ,
			GuestName ,
			ReceiptDate ,
			PayTypeId ,
			ChequeNo ,
			BankName ,
			BatchId ,
			ReceiptBookId ,
			OrgGroupBatchId ,
			CreatedUserId ,
			ChequeDate ,
			ReceiptDetailXML
			)
			SELECT
				@rOrgId,
				@rSourceTypeId,
				cr.value('@SourceId', 'BIGINT'),
				cr.value('@GuestName', 'NVARCHAR(200)'),
				sCommon.fGetDate(),
				cr.value('@PayTypeId', 'INT'),
				cr.value('@ChequeNo', 'NVARCHAR(20)'),
				cr.value('@BankName', 'NVARCHAR(200)'),
				@rBatchId,
				@rReceiptBookId,
				@rOrgGroupBatchId,
				@rUserId,
				cr.value('@ChequeDate', 'DATE'),
				cr.query('ReceiptDetail') -- Extracting ReceiptDetailXML
			FROM
				@rChargeReceiptDetailXML.nodes('/Table/ChargeReceipt') AS t(cr);

		--Select * from #tempTable
		--SELECT 1 AS Result
		DECLARE @lCount int,@lId int
		SELECT @lCount = COUNT(Id) FROM #TempChargeReceipt
		SELECT Top 1 @lId=Id FROM #TempChargeReceipt

		WHILE @lId <= @lCount 
		BEGIN
			--DECLARE @lNextNumber BIGINT
			SET @lReceiptDetailXML = NULL     
			SELECT @lReceiptDetailXML = ReceiptDetailXML FROM  #TempChargeReceipt WHERE  Id = @lId

			SET @lReceiptDetailXML = (
			SELECT CAST('<ReceiptDetailList>' + CAST(@lReceiptDetailXML AS NVARCHAR(MAX)) + '</ReceiptDetailList>' AS XML)
			)

			EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @lReceiptDetailXML

			IF OBJECT_ID('tempdb..#TempChargeReceiptDetail') IS NOT NULL
			BEGIN
				-- If the table exists, drop it
				DROP TABLE #TempChargeReceiptDetail;
			END

			CREATE TABLE #TempChargeReceiptDetail  
			(
				Id bigint identity,
				ChargeId int,
				Remark nvarchar(100),
				Amount decimal(12,2)
			)

			INSERT INTO #TempChargeReceiptDetail
				(ChargeId,
				Remark,
				Amount
				)
				SELECT
				ChargeId,
				Remark,
				Amount

				FROM OPENXML (@intDoc, '/ReceiptDetailList/ReceiptDetail', 1)
				WITH (
				ChargeId INT,
				Remark NVARCHAR(100),
				Amount DECIMAL(12,2)
				)

			SELECT @lReceiptAmount = SUM(Amount) FROM #TempChargeReceiptDetail

			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tChargeReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO sFee.tChargeReceipt
			(
				OrgId,
				Id,
				SourceTypeId,
				SourceId,
				GuestName,
				Remark,
				ReceiptNumber,
				ReceiptDate,
				PayTypeId,
				ChequeNo,
				BankName,
				BatchId,
				ChargeReceiptBookId,
				OrgGroupBatchId,
				CreatedUserId,
				CreatedDateTime,
				ReceiptAmount,
				ChequeDate,
				IsObsolete
			)
			Select
				OrgId,
				@lNextNumber,
				SourceTypeId,
				tmp.SourceId,
				tmp.GuestName,
				'',
				sFee.fChargeReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId),
				tmp.ReceiptDate,
				tmp.PayTypeId,
				tmp.ChequeNo,
				tmp.BankName,
				tmp.BatchId,
				tmp.ReceiptBookId,
				tmp.OrgGroupBatchId,
				tmp.CreatedUserId,
				sCommon.fGetDate(),
				@lReceiptAmount,
				tmp.ChequeDate,
				@rIsObsolete

			FROM  #TempChargeReceipt tmp 
			where  Id = @lId

			DECLARE @lCount1 int,@lId1 int
			SELECT @lCount1 = COUNT(Id) FROM #TempChargeReceiptDetail
			SELECT Top 1 @lId1=Id FROM #TempChargeReceiptDetail

			WHILE @lId1 <= @lCount1 
			BEGIN

				INSERT INTO sFee.tChargeReceiptDetail
				(
					ChargeReceiptId,
					ChargeId,
					Remark,
					Amount,
					UpdatedUserId,
					UpdatedDateTime,
					IsObsolete
				)
				Select
					@lNextNumber,
					ChargeId,
					Remark,
					Amount,
					@rUserId,
					sCommon.fGetDate(),
					@rIsObsolete
					FROM  #TempChargeReceiptDetail TCR 
					where  Id = @lId1

				SET @lId1=@lId1+1
			END

		SET @lId=@lId+1

	END

	EXEC sp_xml_removedocument @intDoc
	SELECT 1 as Result
	--DROP Table #TempChargeReceipt
	END TRY	

	BEGIN CATCH 
	SELECT -1 AS Result,error_message() AS MSG
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptGet]
	 @rId bigint,
	 @rReceiptNumber int,
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		Declare @rSourceTypeId smallint
		select @rSourceTypeId=SourceTypeId from sFee.tChargeReceipt where (ReceiptNumber=@rReceiptNumber OR Id=@rId) and OrgId=@rOrgId
		--END
		--print @rSourceTypeId
IF @rSourceTypeId=95
BEGIN
		SELECT 
			distinct(CR.Id),
			CR.SourceTypeId,
			CR.SourceId,
			EM.EmployeeCode as SourceCode,
			EM.EmployeeName as GuestName,
			EM.DepartmentName AS ClassDiv,
			CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			--CRD.Amount,
			--CM.Code,
			--CM.Title,
			CM.ChargeCategoryId,
			CR.ChargeReceiptBookId AS ReceiptBookId,
			ISNULL(CR.ReceiptAmount,0) AS ReceiptAmount,
			CR.OrgId,
			CR.BatchId,
			isnull(CR.ChequeDate,'') AS ChequeDate,
			--CRD.IsObsolete
			ISNULL(CR.CancelRemark, '') AS CancelRemark
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sHRM.vExtEmployeeJobDetail EM ON EM.EmployeeId=CR.SourceId AND CR.SourceTypeId=95
  WHERE 
			((CR.Id=@rId OR @rId=0))
			AND ((CR.ReceiptNumber=@rReceiptNumber) OR (@rReceiptNumber=''))
			--AND (CR.IsObsolete=0)
			AND (CR.OrgId=@rOrgId)
			AND (CR.BatchId=@rBatchId)
			--AND (CRD.IsObsolete=0)
END
ELSE IF @rSourceTypeId=2001
BEGIN
		SELECT 
			distinct(CR.Id),
			CR.SourceTypeId,
			CR.SourceId,
			SA.Code as SourceCode,
			SA.Name as GuestName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
			CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			--CRD.Amount,
			--CM.Code,
			--CM.Title,
			CM.ChargeCategoryId,
			CR.ChargeReceiptBookId AS ReceiptBookId,
			ISNULL(CR.ReceiptAmount,0) AS ReceiptAmount,
			CR.OrgId,
			CR.BatchId,
			isnull(CR.ChequeDate,'01/01/0001') AS ChequeDate,
			--CRD.IsObsolete
			ISNULL(CR.CancelRemark, '') AS CancelRemark
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
       INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 
       --AND SA.StatusId=1
  WHERE 
			((CR.Id=@rId OR @rId=0))
			AND ((CR.ReceiptNumber=@rReceiptNumber) OR (@rReceiptNumber=''))
			--AND (CR.IsObsolete=0)
			AND (CR.OrgId=@rOrgId)
			AND (CR.BatchId=@rBatchId)
			--AND (CRD.IsObsolete=0)
END
ELSE
BEGIN
	SELECT 
			distinct(CR.Id),
			3 as SourceTypeId,
			0 as SourceId,
			'' as SourceCode,
			CR.GuestName,
			'' AS ClassDiv,
			CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			--CRD.Amount,
			--CM.Code,
			--CM.Title,
			CM.ChargeCategoryId,
			CR.ChargeReceiptBookId AS ReceiptBookId,
			ISNULL(CR.ReceiptAmount,0) AS ReceiptAmount,
			CR.OrgId,
			CR.BatchId,
			isnull(CR.ChequeDate,'01/01/0001') AS ChequeDate,
			--CRD.IsObsolete
			ISNULL(CR.CancelRemark, '') AS CancelRemark
  FROM 
           sFee.tChargeReceipt CR
       INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id --AND ISNULL(CR.SourceTypeId,0)=0
       INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
  WHERE 
			((CR.Id=@rId OR @rId=0))
			AND ((CR.ReceiptNumber=@rReceiptNumber) OR (@rReceiptNumber=''))
			--AND (CR.IsObsolete=0)
			AND (CR.OrgId=@rOrgId)
			AND (CR.BatchId=@rBatchId)
			--AND (CRD.IsObsolete=0)
END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pChargeReceiptListGet]
	 
	 --@rReceiptNumber int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSourceTypeId smallint,
	 @rSourceCode nvarchar(20),
	 @rGuestName nvarchar(200),
	 @rFromDate date,
	 @rToDate date,
	 @rFromNo int,
	 @rToNo int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrgGroupBatchId int,
	 @rDepartmentId int = 0,
	 @rStudentCode nvarchar(20) = '',
	 @rOrgGroupId int=0,
	 @rStatusId int=0,
	 @rFromReceiptNumber int=0,    
	 @rToReceiptNumber int=0,
	 @rIsObsolete bit = 0,
	 @rPayTypeId int=0     -- Mantis - 32487
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 
BEGIN 
		--select 
		--		'' AS Builder1,
		--		'' AS Builder2,
		--		'' AS Id,
		--		'' AS SourceType,
		--		'' AS SourceTypeId
		--		,'' AS GuestName
		--		,'' AS ReceiptNumber
		--		,'' AS ReceiptDate
		--		,'' AS Amount
		--		,'' AS ChargeCategory
		--		,'' AS ReceiptBook
		--		,'' AS ChargeCategoryId
		--		,'' As ReceiptBookId
		--		,'' AS OrgId
		--		,'' AS School
		--		,'' AS OrgGroupId
		--		,'' AS ChargeId

	    ----IF(@rIsSearch=1)
		----BEGIN
			SET @rSourceCode = sCommon.fSearchStringGet(@rSourceCode)
			SET @rGuestName = sCommon.fSearchStringGet(@rGuestName)

			print @rSourceCode
		--Declare @rSourceTypeId smallint
		--select @rSourceTypeId=SourceTypeId from sFee.tChargeReceipt where ReceiptNumber=@rReceiptNumber and OrgId=@rOrgId
		--END
IF @rSourceTypeId=95
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			ISNULL(EM.Code,'') AS Code,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			DM.DisplayTitle AS ClassName,
			CR.Remark ,
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			CR.CreatedDateTime AS CreatedDateTime ,
			U.DisplayTitle As CreatedUser ,
			ISNULL(CR.CancelRemark,'') As CancelRemark ,
			'' As SUId ,
			BM.Title As Batch ,
			ISNULL(CR.ChequeDate,'') As ChequeDate,
			NULL AS ClassDivision --Added for mantis : 36498

  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = @rSourceTypeId)
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		   INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		   --AND EM.StatusId=7
		    INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
		   Inner JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=@rIsObsolete)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((EM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
GROUP BY 
			CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,
			CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,EM.Code,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle,CR.CancelRemark
			,BM.Title ,CR.ChequeDate
END
ELSE IF @rSourceTypeId=2001
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			ISNULL(SA.Code,'') as Code,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			CMM.DisplayTitle + '-' + DM.DisplayTitle AS ClassName ,
			CR.Remark,
			U.DisplayTitle As CreatedUser,
			CR.CreatedDateTime ,U.DisplayTitle,
			SA.SUId As SUId ,
			ISNULL(CR.CancelRemark,'') As CancelRemark ,
			SA.BatchName As Batch ,
			ISNULL(CR.ChequeDate,'') As ChequeDate,
			--CLM.Id AS ClassId,
			--CLM.DisplayTitle AS ClassName,
			--DM.Id AS DivisionId,
			--DM.DisplayTitle AS DivisionName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			NULL AS ClassDivision --Added for mantis : 36498
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 --AND SA.StatusId=1
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tClassMaster CMM ON CMM.Id = SA.ClassId
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		    INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
		   --INNER JOIN sSetup.tClassMaster CLM ON CLM.Id = SA.ClassId
		   --INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=@rIsObsolete)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))			-- MantisId : 0032573
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))				-- MantisId : 0032573
 GROUP BY   CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,
            CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle, CMM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,SA.Code ,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle ,SA.SUId ,CR.CancelRemark
            --CLM.Id,CLM.DisplayTitle, DM.Id, DM.DisplayTitle
			,SA.BatchName ,CR.ChequeDate
END
ELSE IF @rSourceTypeId=3
BEGIN
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CR.Id,
		'Other' as SourceType,
		'' AS Code,
		CR.SourceTypeId,
		--EM.Code as SourceCode,
		CR.GuestName as GuestName,
		--CR.Remark,
		CR.ReceiptNumber,
		CR.ReceiptDate,
		  PTM.Title AS PayType,  
		--CR.PayTypeId,
		CR.ChequeNo,
		CR.BankName,
		--CR.IsObsolete,
		--CRD.Id as DetailId,
		--CRD.ChargeId,
		--CRD.Remark as DetailRemark,
		sum(CRD.Amount) as Amount,
		--CM.Code,
		--CM.Title,
		CCM.Title as ChargeCategory,
		CM.ChargeCategoryId,
		CR.OrgId,
		CR.BatchId,
		RBM.Title AS ReceiptBook,
		CR.ChargeReceiptBookId,
		OM.DisplayTitle AS OrganizationName,
		'' AS ClassName ,
		CR.Remark ,
		U.DisplayTitle As CreatedUser,
		CR.CreatedDateTime AS CreatedDateTime ,
		'' As SUId ,
		ISNULL(CR.CancelRemark,'') As CancelRemark,
		BM.Title As Batch ,
		ISNULL(CR.ChequeDate,'') As ChequeDate,
		--OM.DisplayTitle AS School,
		--OM.OrgGroupId,
		--CM.Id AS ChargeId
		--CRD.IsObsolete
		NULL AS ClassDivision --Added for mantis : 36498
  FROM  
       sFee.tChargeReceipt CR
	   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
	   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
	   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
	   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
	   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
	    INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
		 Inner JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
	   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
	   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
		--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
		--AND 
		(ISNULL(CR.SourceTypeId,0)=3)
		AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
		--AND (ISNULL(@rSourceCode,'') = '')
		AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
		AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
		AND (CR.IsObsolete=@rIsObsolete)
		AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (CRD.IsObsolete=0) 
		AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
		And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
		AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
		AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))			-- MantisId : 0032573
		AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))				-- MantisId : 0032573
		group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
		,PTM.Title,CR.ChequeNo,CR.BankName ,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle ,CR.CancelRemark
		,BM.Title ,CR.ChequeDate
END	
ELSE
BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			ISNULL(EM.Code,'') as Code,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			DM.DisplayTitle AS ClassName,
			CR.Remark ,
			U.DisplayTitle As CreatedUser ,
			CR.CreatedDateTime AS CreatedDateTime ,
				'' As SUId,
            ISNULL(CR.CancelRemark,'') As CancelRemark ,
			BM.Title As Batch ,
			ISNULL(CR.ChequeDate,'') As ChequeDate,
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
			NULL AS ClassDivision --Added for mantis : 36498
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = 95) 
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		   INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		   --AND EM.StatusId=7
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		    INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
			 Inner JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=@rIsObsolete)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND (CR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)             -- Mantis - 32487
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))		-- MantisId : 0032573
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))			-- MantisId : 0032573
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,
			CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,EM.Code ,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle ,CR.CancelRemark
			,BM.Title ,CR.ChequeDate
			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			ISNULL(SA.Code,'') as Code,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			CMM.DisplayTitle + '-' + DM.DisplayTitle AS ClassName ,
			CR.Remark ,
			U.DisplayTitle As CreatedUser,
			CR.CreatedDateTime AS CreatedDateTime ,
				'' As SUId ,
			ISNULL(CR.CancelRemark,'') As CancelRemark,
			SA.BatchName as Batch ,
			ISNULL(CR.ChequeDate,'') As ChequeDate,
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision --Added for mantis : 36498
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001
		   INNER JOIN sSetup.tClassMaster CMM ON CMM.Id = SA.ClassId
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId 
		   --AND SA.StatusId=1
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId   --Mantis - 32487
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=@rIsObsolete)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))
			AND (CR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)               -- Mantis - 32487
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,
			RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle, CMM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,SA.Code,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle ,CR.CancelRemark
			,SA.BatchName ,CR.ChequeDate,SA.ClassName,SA.DivisionName
			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			'' AS Code,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			'' AS ClassName ,
			CR.Remark ,
			U.DisplayTitle As CreatedUser ,
			CR.CreatedDateTime AS CreatedDateTime ,
				'' As SUId ,
				ISNULL(CR.CancelRemark,'') As CancelRemark ,
				BM.Title As Batch ,
				ISNULL(CR.ChequeDate,'') As ChequeDate,
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
			NULL AS ClassDivision --Added for mantis : 36498
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   INNER JOIN sSecurity.tUser U ON U.Id = CR.CreatedUserId
		    Inner JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			(ISNULL(CR.SourceTypeId,0)=3)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=@rIsObsolete)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
			AND ((CR.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0)) 
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,0)=0))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,0)=0))
			AND (CR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)          -- Mantis - 32487
			--AND ((ISNULL(@rSourceCode,'%') = '%'))
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName ,CR.Remark ,CR.CreatedDateTime ,U.DisplayTitle ,CR.CancelRemark
			,BM.Title ,CR.ChequeDate
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pChargeSummaryDashboard]
	@rType nvarchar(40)='',
	@rOrgGroupId int =0,
	@rOrgGroupBatchId int=0,
	@rDepositHeadId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'ChargePayTypeList')
		BEGIN
		DECLARE @cols NVARCHAR(MAX),@query  NVARCHAR(MAX),@cols1 NVARCHAR(MAX);
					
					
					SET @cols = STUFF((SELECT ',ISNULL([' +  (Title) + '],0)as [' +  (Title)+ ']'
					FROM  sFinanceCommon.tPayTypeMaster PTM
							 INNER JOIN
							 (
							 SELECT CR.PayTypeId AS PayTypeId   FROM
							 sFee.tChargeReceipt CR
								INNER JOIN sFee.tChargeReceiptBookMaster CRBM ON CRBM.Id = CR.ChargeReceiptBookId
								WHERE ((CRBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))
								AND ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
								GROUP BY CR.PayTypeId
							 )T ON T.PayTypeId = PTM.Id
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					
					SET @cols1 = STUFF((SELECT ',' +  QUOTENAME(Title)
						FROM  sFinanceCommon.tPayTypeMaster PTM
							 INNER JOIN
							 (
							 SELECT CR.PayTypeId AS PayTypeId   FROM
							 sFee.tChargeReceipt CR
								INNER JOIN sFee.tChargeReceiptBookMaster CRBM ON CRBM.Id = CR.ChargeReceiptBookId
								WHERE ((CRBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))
								AND ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
								GROUP BY CR.PayTypeId
							 )T ON T.PayTypeId = PTM.Id
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					--print @col1s
					--return
			set @query = 'SELECT ChargeReceiptBook, ' + @cols + ' from 
						(
								SELECT SUM(CR.ReceiptAmount) AS ReceiptAmount ,CRBM.Title AS ChargeReceiptBook,T.PayType
								FROM sFee.tChargeReceipt CR
								INNER JOIN sFee.tChargeReceiptBookMaster CRBM ON CRBM.Id = CR.ChargeReceiptBookId
								INNER JOIN
								(
									SELECT Id AS PayTypeId,Title AS PayType FROM sFinanceCommon.tPayTypeMaster
								) T ON T.PayTypeId = CR.PayTypeId AND CR.ReceiptAmount >0
								WHERE ((CRBM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
								AND ((CR.OrgGroupBatchId='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupBatchId)+'=0))
								GROUP BY CRBM.Title,T.PayType
							-- GROUP BY PTM.Title,T.ChargeReceiptBook
							 HAVING SUM(CR.ReceiptAmount) >0
						) x
							pivot 
							(
							SUM(ReceiptAmount)
							for PayType in (' + @cols1 + ')
							) p '   
							--print ( @query)   
			EXECUTE (@query)
		END
	ELSE IF(@rType = 'ChargeAmount')
		BEGIN
		SELECT 
			ISNULL((SELECT SUM(CR.ReceiptAmount) FROM sFee.tChargeReceipt CR INNER JOIN sFee.tChargeReceiptBookMaster CRBM ON CRBM.Id = CR.ChargeReceiptBookId WHERE((CR.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))  AND ((CRBM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))),0) AS TotalChargeAmount,
			ISNULL((SELECT SUM(CR.ReceiptAmount) FROM sFee.tChargeReceipt CR INNER JOIN sFee.tChargeReceiptBookMaster CRBM ON CRBM.Id = CR.ChargeReceiptBookId  WHERE ((CR.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))  AND CONVERT(DATE,ReceiptDate) = CONVERT(DATE,GETDATE()) AND ((CRBM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))),0) AS TodayChargeAmount
		END
	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pClearedPaymentHistoryGet]
	@rId bigint = 0,
	@rOrgGroupBatchId int = 0,
	@rOrgId int = 0,
	@rBatchId int = 0,
	@rAdmissionCategoryId int = 0,
	@rIdNo nvarchar(20) = NULL,
	@rDepartmentId int = 0,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rReceiptBookId int = 0,
	@rCollectionGroupId int = 0,
	@rPayTypeId int = 0,
	@rStatusId int = 0,
	@rFirstName nvarchar(50) = NULL,
	@rFromReceiptNumber nvarchar(50) = NULL,
	@rToReceiptNumber nvarchar(50) = NULL,
	@rChequeNo nvarchar(50) = NULL,
	@rFromPaymentClearanceDate date = NULL,
	@rToPaymentClearanceDate date = NULL,
	@rOrgGroupId int = 0,
	@rSourceId bigint =0,
	@rSourceTypeId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT 	 
		 PDP.Id
		,PDP.OrgId
		,PDP.BatchId
		,PDP.OrgGroupBatchId
		,PDP.SourceTypeId
		,PDP.SourceId
		,PDP.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(R.ReceiptDate, '') AS ReceiptDate
		,ISNULL(PTM.Title, '') AS PayType
		,ISNULL(SA.Code, '') AS IdNo
		,ISNULL(SA.ClassDivision, '') AS ClassDivision
		,ISNULL(SA.Name, '') AS StudentName
	FROM
		sFee.tPostDatePayment PDP
		INNER JOIN sFee.tReceipt R ON R.Id = PDP.ReceiptId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PDP.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = PDP.ReceiptBookId
		INNER JOIN sStudent.vStudentAllDetail SA ON SA.AcademicId = PDP.SourceId AND PDP.SourceTypeId = 2001
	WHERE 
		(PDP.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND (PDP.OrgId = @rOrgId OR PDP.OrgId = 0)
		AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		AND (PDP.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (PDP.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
		AND (PDP.StatusId = @rStatusId OR @rStatusId = 0)
		AND (PaymentClearanceDate >= @rFromPaymentClearanceDate OR ISNULL(@rFromPaymentClearanceDate, '') = '')
		AND (PDP.PaymentClearanceDate <= @rToPaymentClearanceDate OR ISNULL(@rToPaymentClearanceDate, '') = '')
		AND (PDP.SourceId = @rSourceId OR @rSourceId = 0)
		AND (PDP.SourceTypeId = @rSourceTypeId OR @rSourceTypeId = 0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pCollectionGroupGet]
		
	@rSourceId bigint,
	@rSourceTypeId int=0,
	@rReceiptBookId int=0,
	@rReceiptId bigint=0,
	@rBatchId int,
	@rCollectionGroupId int =0 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	DECLARE @lClassId int
	DECLARE @lAdmissionCategoryId int,@lOrgId int,@lOrgGorupId int
	SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lOrgId = OrgId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId	
	
	Select @lOrgGorupId = OrgGroupId from sSetup.tOrganizationMaster Where Id = @lOrgId
				
	DECLARE @lConfigValue nvarchar(50)
	--,@lOrgGroupBatchId int
	--SELECT @lOrgGroupBatchId = OrgGroupBatchId FROM [sSetup].[tBatchMaster] WHERE Id = @rBatchId
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 487 AND SourceTypeId = 2010 AND SourceId = @lOrgGorupId


	IF(@lConfigValue = 'True')
	BEGIN
		SELECT 
			SUM(CG.PayableAmount) AS PendingAmount 
			,CollectionGroupId
			,StartDate
			,EndDate
			,CollectionGroupName
			,ReceiptBookId
			,ReceiptBook
			,CollectionGroupCode -- added for mantis 0026962 by Foram
			,ReceiptBookOrderIndex -- added for mantis 0028666 by Foram
		FROM
			(SELECT 
				FM.Id AS FeeId,
				FM.Title AS FeeName,
				FS.Id AS FeeSetupId,			 
				FS.ReceiptBookId,
				RBM.Title AS ReceiptBook,
				ISNULL(R.PaidAmount,0) AS PaidAmount,
				ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) -  ISNULL(FA.NotApplicableAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0)AS PayableAmount,
				--FM.OrderIndex,
				FS.CollectionGroupId,
				CGM.StartDate,
				CGM.EndDate,
				CGM.Title AS CollectionGroupName,
				CGM.OrderIndex,
				CGM.Code AS CollectionGroupCode, -- added for mantis 0026962 by Foram
				RBM.OrderIndex AS ReceiptBookOrderIndex -- added for mantis 0028666 by Foram
			FROM 
				sFee.tFeeMaster FM
				INNER JOIN 
				(
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
					WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
						AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
						UNION ALL
				
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
					ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
				WHERE
						FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
				) FS ON FS.FeeId=FM.Id
				INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
				INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId FROM
					sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 	
					INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
					WHERE						
					(R.ReceiptBookId = @rReceiptBookId	OR @rReceiptBookId = 0)	
					AND ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
					AND R.SourceId= @rSourceId
					AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
					AND R.IsObsolete = 0 			 
					 GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id 
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			where 
				((FS.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
				AND (((ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.NotApplicableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0))>0) AND(@rReceiptId=0) OR(@rReceiptId<>0))
				AND(FS.BatchId=@rBatchId)
				AND CAST(sCommon.fGetDate() AS DATE) <= CAST(CGM.EndDate AS DATE)
				AND CGM.IsObsolete = 0
			) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,CollectionGroupCode,OrderIndex,ReceiptBookId,ReceiptBook,ReceiptBookOrderIndex
		ORDER BY CG.StartDate,CG.OrderIndex
	END
	ELSE
	BEGIN
		SELECT 
			SUM(CG.PayableAmount) AS PendingAmount 
			,CollectionGroupId
			,StartDate
			,EndDate
			,CollectionGroupName
			,ReceiptBookId
			,ReceiptBook
			,CollectionGroupCode -- added for mantis 0026962 by Foram
			,ReceiptBookOrderIndex -- added for mantis 0028666 by Foram
		FROM
			(SELECT 
				FM.Id AS FeeId,
				FM.Title AS FeeName,
				FS.Id AS FeeSetupId,			 
				FS.ReceiptBookId,
				RBM.Title AS ReceiptBook,
				ISNULL(R.PaidAmount,0) AS PaidAmount,
				ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) -  ISNULL(FA.NotApplicableAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0)AS PayableAmount,
				--FM.OrderIndex,
				FS.CollectionGroupId,
				CGM.StartDate,
				CGM.EndDate,
				CGM.Title AS CollectionGroupName,
				CGM.OrderIndex,
				CGM.Code AS CollectionGroupCode, -- added for mantis 0026962 by Foram
				RBM.OrderIndex AS ReceiptBookOrderIndex -- added for mantis 0028666 by Foram
			FROM 
				sFee.tFeeMaster FM
				INNER JOIN 
				(
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
						WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
						AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
					UNION ALL
				
					SELECT 
						FS1.FeeId,
						FS1.Id,
						ISNULL(FS1.IsOptional,0)AS IsOptional,
						ISNULL(FS1.IsVariable,0)AS IsVariable,
						ISNULL(FS1.Amount,0)AS Amount,
						ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
						ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
						FS1.BatchId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
					FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
					ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
				WHERE
						FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
						AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
				) FS ON FS.FeeId=FM.Id
				INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
				INNER JOIN sFee.tReceiptBookMaster RBM
					ON RBM.Id=FS.ReceiptBookId
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId FROM
					sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 	
					INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
					WHERE						
					 (R.ReceiptBookId = @rReceiptBookId	OR @rReceiptBookId = 0)	
					 AND ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
					AND R.SourceId= @rSourceId
					AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
					AND R.IsObsolete = 0 			 
					 GROUP BY FeeSetupId
		
				) R ON R.FeeSetupId = FS.Id 
				LEFT JOIN sFee.tFeeAllocation FA
					ON FA.FeeSetupId=FS.Id AND 
					(FA.SourceId=@rSourceId) AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			where 
				((FS.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
				AND (((ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.NotApplicableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0))>0) AND(@rReceiptId=0) OR(@rReceiptId<>0))
				AND(FS.BatchId=@rBatchId)
				AND CGM.IsObsolete = 0
		  ) AS CG
		GROUP BY CollectionGroupId,StartDate,EndDate,CollectionGroupName,CollectionGroupCode,OrderIndex,ReceiptBookId,ReceiptBook,ReceiptBookOrderIndex
		ORDER BY CG.StartDate,CG.OrderIndex
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pCollectionGroupMasterAdd]
	 
	 
		@rOrgGroupBatchId int,
        @rId int,
        @rCode nvarchar(20),
        @rTitle nvarchar(100),
        @rStartDate date,
        @rEndDate date,
        @rRemark nvarchar(500),
        @rIsObsolete bit,
        @rOrderIndex smallint,
        @rOrgGroupId int,
        @rReceiptBookId int=0,
        @rFooterRemark1 nvarchar(1500)='',
        @rFooterRemark2 nvarchar(1800)='',
        @rFeePeriod nvarchar(200)='',
        @rIsDisplayCashDetailInFolio bit=0,
        @rReportId int=0,
        @rIsOnPrePrinted bit=0
        
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
			BEGIN
			SELECT -101 as Result
			RETURN
		END 
	
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
			BEGIN
			SELECT -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE  Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		BEGIN
			SELECT -101 as Result
			RETURN
		END	
		IF EXISTS (SELECT Id FROM sFee.tCollectionGroupMaster WHERE  Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		BEGIN
			SELECT -102 as Result
			RETURN
		END 

	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tCollectionGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	PRint @lNextNumber
	
	INSERT INTO sFee.tCollectionGroupMaster
		(
			OrgGroupBatchId,
			Id,
			Code,
			Title,
			StartDate,
			EndDate,
			Remark,
			IsObsolete,
			OrderIndex,
			ReceiptBookId,
			FooterRemark1,
			FooterRemark2,
			FeePeriod,
			IsDisplayCashDetailInFolio,
			ReportId,
			IsOnPrePrinted
		)
	VALUES
		(
			@rOrgGroupBatchId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rStartDate,
			@rEndDate,
			@rRemark,
			@rIsObsolete,
			@rOrderIndex,
			@rReceiptBookId,
			@rFooterRemark1,
			@rFooterRemark2,
			@rFeePeriod,
			@rIsDisplayCashDetailInFolio,
			@rReportId,
			@rIsOnPrePrinted
		)
		    SELECT 1 AS Result
		 
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tCollectionGroupMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			Remark=@rRemark,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			ReceiptBookId=@rReceiptBookId,
			FooterRemark1=@rFooterRemark1,
			FooterRemark2=@rFooterRemark2,
			FeePeriod=@rFeePeriod,
			IsDisplayCashDetailInFolio=@rIsDisplayCashDetailInFolio,
	        ReportId=@rReportId,
	        IsOnPrePrinted=@rIsOnPrePrinted
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
	if not exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGroupId)
	BEGIN
		INsert Into sSystem.tPortalSync
		(
			OrgGroupId,
			FeeChange
		)
		Values
		(
			@rOrgGroupId,1
		)
	END
	ELse
	BEGIN
		Update sSystem.tPortalSync
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	
	END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [sFee].[pCollectionGroupMasterGet] 
CREATE OR ALTER PROCEDURE [sFee].[pCollectionGroupMasterGet]
	 
	 @rOrgGroupBatchId int,
	 @rId int,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rReceiptBookId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			CGM.Id,
			CGM.Code,
			CGM.Title,
			CGM.StartDate,
			CGM.EndDate,
			CGM.Remark,
			CGM.IsObsolete,
			CGM.OrderIndex,
			CGM.OrgGroupBatchId,
			ISNULL(CGM.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBook,
			ISNULL(CGM.FooterRemark1,'') AS FooterRemark1,
			ISNULL(CGM.FooterRemark2,'') AS FooterRemark2,
			ISNULL(CGM.FeePeriod,'') AS FeePeriod,
			ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
			ISNULL(CGM.ReportId,0) AS ReportId,
			ISNULL(CGM.IsOnPrePrinted,0) AS IsOnPrePrinted
	FROM 
			sFee.tCollectionGroupMaster CGM
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = CGM.ReceiptBookId
	WHERE 
			(CGM.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((CGM.Id = @rId) OR (@rId = 0))
			AND ((CGM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((CGM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND	((CGM.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	ORDER BY CGM.OrderIndex		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pCollectionPaytypeFeeDashBoardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rFeeHeadId int=0,
	 @rPayTypeId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
  SELECT
  (
	SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
	FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
	WHERE R.SourceTypeId = 2001
	AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
	AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS YesterdayAmount,
	(
	SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS DailyAmount,
	
	(
		SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS MonthlyAmount,
	
	(
		SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS YearlyAmount
  END
  
  IF(@rType='PayType')
  BEGIN
  IF(@rDay=-1)
	BEGIN
	SELECT PTM.Id AS PayTypeId,PTM.Title AS PayTypeTitle,ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	WHERE R.SourceTypeId = 2001
	AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
	AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
		--AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY PTM.Id,PTM.Title
	END
	IF(@rDay=1)
	BEGIN
	SELECT PTM.Id AS PayTypeId,PTM.Title AS PayTypeTitle,ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	WHERE R.SourceTypeId = 2001
	AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
	AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
		--AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY PTM.Id,PTM.Title
	END
	IF(@rDay=30)
	BEGIN
		SELECT PTM.Id AS PayTypeId,PTM.Title AS PayTypeTitle,ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		--AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY PTM.Id,PTM.Title
	END
	IF(@rDay=365)
	BEGIN
		SELECT PTM.Id AS PayTypeId,PTM.Title AS PayTypeTitle,ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		--AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY PTM.Id,PTM.Title
	END
  END

  IF(@rType='ReceiptBook')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND(PTM.Id=@rPayTypeId)
		GROUP BY RBM.Id,RBM.Title
	END
	IF(@rDay=1)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND(PTM.Id=@rPayTypeId)
		GROUP BY RBM.Id,RBM.Title
	END
	IF(@rDay=30)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0)
		AND(PTM.Id=@rPayTypeId) 	 
		GROUP BY RBM.Id,RBM.Title
	END
	IF(@rDay=365)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND(PTM.Id=@rPayTypeId)
		GROUP BY RBM.Id,RBM.Title
	END
  END
  
  IF(@rType='FeeHead')
  BEGIN
  IF(@rDay=-1)
	BEGIN
	SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount  
	FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND(PTM.Id=@rPayTypeId)
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
	IF(@rDay=1)
	BEGIN
	SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount  
	FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND(PTM.Id=@rPayTypeId)
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
	IF(@rDay=30)
	BEGIN
		SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND(PTM.Id=@rPayTypeId)
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
	IF(@rDay=365)
	BEGIN
		SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND(PTM.Id=@rPayTypeId)
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
  END
  
  IF(@rType='FeeMaster')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT FM.Id AS FeeMasterId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND(PTM.Id=@rPayTypeId)
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
	IF(@rDay=1)
	BEGIN
		SELECT FM.Id AS FeeMasterId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
				AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND(PTM.Id=@rPayTypeId)
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
	IF(@rDay=30)
	BEGIN
		
		SELECT FM.Id AS FeeMasterId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND(PTM.Id=@rPayTypeId)
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
	IF(@rDay=365)
	BEGIN
		
		SELECT FM.Id AS FeeMasterId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	
		AND(PTM.Id=@rPayTypeId) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
END
 
  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pConsolidateFeeStatusDashboardGet]
	@rType int =0,
	@rCommonOrgGroupBatchId int=0,
	@rOrgGroupId smallint=0,
	@rReceiptBookId int =0,
	@rOrgId int  =0,
	@rFeeHeadId int =0,
	@rFeeId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN

	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('Type: ' + CAST(@rType AS nvarchar(100)), 
	+ '@rCommonOrgGroupBatchId = ' +  CAST(@rCommonOrgGroupBatchId AS nvarchar(100)) 
	+ ', @rOrgGroupId = ' +  CAST(@rOrgGroupId AS nvarchar(100))
	+ ', @rReceiptBookId = ' +  CAST(@rReceiptBookId AS nvarchar(100))
	+ ', @rOrgId = ' +  CAST(@rOrgId AS nvarchar(100))   
	+ ', @rFeeHeadId = ' +  CAST(@rFeeHeadId AS nvarchar(100))  
	+ ', @rFeeId = ' +  CAST(@rFeeId AS nvarchar(100)), 
	'',
	'', 
	GETDATE(), 
	'[sFee].[pConsolidateFeeStatusDashboardGet]')
END

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

	IF OBJECT_ID('tempdb..#TempFeeSetupData') IS NOT NULL DROP TABLE #TempFeeSetupData
	
	SELECT * 
	INTO #TempFeeSetupData
	FROM 
	(
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			FM.Title AS FeeName,
			FM.Id AS FeeMasterId,
			SA1.AcademicId,
			FM.FeeHeadId,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		WHERE FS1.IsOptional=0

		UNION ALL
				
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			FM.Title AS FeeName,
			FM.Id AS FeeMasterId,
			SA1.AcademicId,
			FM.FeeHeadId,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE FS1.IsOptional=1
	) AS A

	IF (@rType = 1)
	BEGIN
		
		SELECT 
			RBM.Id AS ReceiptBookId,
			RBM.Title AS ReceiptBook,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			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,
			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)) AS Total,
			RBM.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
					INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA1.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA1.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE		
					(R.SourceTypeId = 2001) AND (R.IsObsolete = 0) 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
				GROUP BY FeeSetupId,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			LEFT JOIN sHostel.tAssignRoom AR  WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
			LEFT JOIN (
				SELECT AT.SourceId FROM sTransport.tAssignRoute AT  WITH (NOLOCK)
				INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				WHERE COGBM.Id = @rCommonOrgGroupBatchId
			) RT ON RT.SourceId = SA.StudentId 
			INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
			INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
			INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY RBM.Title,RBM.Id,RBM.OrderIndex
		Order By RBM.OrderIndex, RBM.Id
	END
	ELSE IF (@rType = 11)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 12)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			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,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having 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)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 13)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			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)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+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
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF(@rType = 2)
	BEGIN
		SELECT 
			OM.Id AS OrgId,
			OM.Title AS Organization,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			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,
			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)) AS Total,
			OM.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY OM.Title,OM.Id,OM.OrderIndex
		Order BY OM.OrderIndex
	END
	ELSE IF (@rType = 21)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 22)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			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,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having 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)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 23)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			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)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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  WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+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
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 24)
	BEGIN
		SELECT 
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			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,
			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)) AS Total,
			SA.DivisionOrder
			,SA.ClassOrderIndex -- add for mantis : 0042058
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT  WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((O.Id = @rOrgId) OR (@rOrgId = 0))
		GROUP BY  SA.ClassName,SA.DivisionName,SA.DivisionId,SA.DivisionOrder,SA.ClassOrderIndex --add class division order index for mantis : 0042058
		Order BY SA.ClassOrderIndex,SA.DivisionOrder--add for mantis : 0042058
	END
	ELSE IF(@rType = 3)
	BEGIN
		SELECT 
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadTitle,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			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,
			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)) AS Total,
			FHM.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData FS ON FS.AcademicId=SA.AcademicI
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY FHM.Title,FHM.Id,FHM.OrderIndex
		Order By FHM.OrderIndex
	END
	ELSE IF (@rType = 31)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT  WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FHM.Id = @rFeeHeadId) OR (@rFeeHeadId =0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 32)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			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,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FHM.Id = @rFeeHeadId) OR (@rFeeHeadId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having 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)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 33)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			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)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FHM.Id = @rFeeHeadId) OR (@rFeeHeadId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+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
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF(@rType = 4)
	BEGIN
		SELECT 
			FS.FeeMasterId AS FeeId,
			FS.FeeName AS FeeName,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(FA.DiscountAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,		-- Add -ISNULL(FA.DiscountAmount,0.00) for MantisId : 0036887
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(FA.DiscountAmount,0.00)) AS Total,										-- Add -ISNULL(FA.DiscountAmount,0.00) for MantisId : 0036887
			FS.OrderIndex
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			INNER JOIN #TempFeeSetupData FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT  WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM  WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
		GROUP BY FS.FeeName,FS.FeeMasterId,FS.OrderIndex
		Order By FS.OrderIndex 
	END
	ELSE IF (@rType = 41)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT  WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FS.FeeMasterId = @rFeeId) OR (@rFeeId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 42)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			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,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FS.FeeMasterId = @rFeeId) OR (@rFeeId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having 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)) >0
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END
	ELSE IF (@rType = 43)
	BEGIN
		SELECT 
			ISNULL(SA.AcademicId,0) AS SourceId,
			ISNULL(SA.ClassName,'') AS ClassName,
			ISNULL(SA.DivisionId,0) AS DivisionId,
			ISNULL(SA.DivisionName,'') AS DivisionName,
			ISNULL(SA.ClassName+'-'+SA.DivisionName,'') AS ClassDivision,
			ISNULL(SA.Code,'') As Code,
			ISNULL(SA.Name,'') AS Name,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			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)) AS TotalAmount,
			SA.ClassOrderIndex,  
			SA.DivisionOrder,
			SA.RollNo 
		FROM 
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		
				WHERE 
					(FS1.IsOptional=0)

				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					FM.Title AS FeeName,
					FM.Id AS FeeMasterId,
					SA1.AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
				AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					 (FS1.IsOptional=1)
			
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=R.SourceId 
						INNER JOIN sStudent.tStudentAdmission tSA WITH (NOLOCK) ON tSA.StudentId = SA1.StudentId
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
					GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  
				LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=B.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id = @rCommonOrgGroupBatchId) RT ON RT.SourceId = SA.StudentId 
				 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FS.FeeHeadId
				 INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM  WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id = @rCommonOrgGroupBatchId
			AND((OMM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FS.FeeMasterId = @rFeeId) OR (@rFeeId = 0))
		GROUP by SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(R.PaidAmount,0)+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
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
	END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pDeleteAccountMapping]

	 @rChargeId int,
	 @rPayTypeId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	 BEGIN TRANSACTION	
BEGIN
	 
	DELETE 
	FROM sFee.tChargeAccountMapping
	WHERE ChargeId=@rChargeId AND PayTypeId = @rPayTypeId
	
	SELECT 1 AS Result
END	
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDeletedRecieptFeeProcessGenerate]
		@rOrgId int,
		@rBatchId int,
	    @rAcademicId bigint,
		@rReceiptId bigint,
		@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		  SELECT ROW_NUMBER() OVER (ORDER BY FS.Id) as RowNumberFeeSetup,FS.Id AS FeeSetupId,PaidAmount AS PaidAmount,ToPayAmount AS PendingAmount 
		  INTO  #temptFeeSetup 
		  FROM [sFee].[tFeeAllocationStudent] FAS
		  INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId 
		  INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId 
		  AND FS.ClassId = A.ClassId
		  WHERE FAS.AcademicId = @rAcademicId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId

		  DECLARE @rowcountFeesetup BIGINT=0
		  SELECT @rowcountFeesetup = COUNT(RowNumberFeeSetup) FROM #temptFeeSetup

		  WHILE (@rowcountFeesetup!=0)
		  BEGIN	
				DECLARE @FeeSetupId BIGINT=0
				DECLARE @PaidAmount DECIMAL(12,2) = 0.00
				DECLARE @PendingAmount DECIMAL(12,2) = 0.00
				DECLARE @ReceiptPaidAmount DECIMAL(12,2) = 0.00

				SELECT @FeeSetupId=FeeSetupId,@PaidAmount=PaidAmount,@PendingAmount=PendingAmount FROM #temptFeeSetup WHERE RowNumberFeeSetup=@rowcountFeesetup

				SELECT @ReceiptPaidAmount = Amount FROM sFee.tReceiptDetail RD INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId WHERE ReceiptId = @rReceiptId AND FeeSetupId = @FeeSetupId AND R.SourceId = @rAcademicId

				SET @PaidAmount = @PaidAmount - @ReceiptPaidAmount
				SET @PendingAmount = @PendingAmount + @ReceiptPaidAmount

				UPDATE [sFee].[tFeeAllocationStudent] 
				SET 
					ToPayAmount = @PendingAmount,
					PaidAmount = @PaidAmount,
					UpdatedUserId = @rCreatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 
					AcademicId = @rAcademicId
					AND FeeSetupId = @FeeSetupId

				SET @rowcountFeesetup=@rowcountFeesetup-1
		  END

		  DROP TABLE #temptFeeSetup
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDeleteExemptionType]
	
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rExemptionTypeId int,
	@rAcademicId bigint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	DECLARE @lClassId int
	DECLARE @lDivisionId int
	DECLARE @lAdmissionCategoryId int
	DECLARE @lExemptionTypeId int
	DECLARE @lCalculationTypeId tinyint
	
	SELECT @lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId,@lExemptionTypeId=ExemptionTypeId 
	FROM sStudent.vStudentAcademic 
	WHERE AcademicId = @rAcademicId AND BatchId=@rBatchId AND OrgId = @rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId
	
	SELECT @lCalculationTypeId=ISNULL(CalculationTypeId,0) FROM sFee.tExemptionTypeMaster WHERE Id = @lExemptionTypeId
	
	-- Exemption Type Temp Table
	CREATE TABLE #TempExemptionType
	(
		[AutoId] int identity,
		[AcademicId] bigint NULL,
		[RollNo] int NULL,
		[Name] nvarchar(500) NULL,
		[Code] nvarchar(20) NULL,
		[ClassId] int NULL,
		[DivisionId] int NULL,
		[ClassName] nvarchar(100) NULL,
		[DivisionName] nvarchar(100) NULL,
		[DivisionOrder] int NULL,
		[ClassDivision] nvarchar(200) NULL,
		[FeeSetupId] int NULL,
		[IsVariable] bit NULL,
		[Amount] decimal(12,2) NULL,
		[StartDate] date NULL,
		[EndDate] date NULL,
		[FAAmount] decimal(12,2) NULL,
		[DiscountAmount] decimal(12,2) NULL,
		[AdditionalAmount] decimal(12,2) NULL,
		[PaidAmount] decimal(12,2) NULL,
		[PendingAmount] decimal(12,2) NULL,
		[Remark] nvarchar(200) NULL,
		[FeeId] int NULL,
		[FeeName] nvarchar(100) NULL,
		[OrgId] int NULL,
		[OrgName] nvarchar(100) NULL,
		[OrgOrderIndex] int NULL,
		[ReceiptBookId] int NULL,
		[ReceiptBookTitle] nvarchar(100) NULL,
		[ReceiptOrderIndex] int NULL,
		[OrgGroupBatchId] int NULL,
		[DepartmentId] int NULL,
		[DepartmentName] nvarchar(100) NULL,
		[ParentContactNo] nvarchar(100) NULL,
		[ExemptionTypeId] int NULL,
	)
	-- End Exemption Type Temp Table
	
	
	
	INSERT INTO #TempExemptionType 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0) + ISNULL(FA.VariableAmount,0.00) AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeId,
		FS.FeeName,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		FS.ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		@lExemptionTypeId
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgId = @rOrgId 
			AND SA.BatchId=@rBatchId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
	 
		
	BEGIN TRY 
	BEGIN TRANSACTION
	BEGIN -- Update Fee Allocation
		
		UPDATE AL 
		SET
		    DiscountAmount = 0,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM
		(
		SELECT		
			 CASE
             WHEN @lCalculationTypeId= 1 THEN (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)
             WHEN @lCalculationTypeId = 2 THEN ISNULL(ETD.ExemptionPercentage,0)
             END AS Result,
			 ISNULL(A.Amount,0) AS Amount,
			 ISNULL(ETD.ExemptionPercentage,0) AS ExemptionPercentage,
			 A.ExemptionTypeId,
			 A.PendingAmount,
			 A.AcademicId,
			 A.FeeSetupId
		FROM #TempExemptionType A
	    INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
		) 
		R  INNER JOIN	sFee.tFeeAllocation AL ON AL.SourceId = R.AcademicId AND AL.FeeSetupId = R.FeeSetupId
		WHERE
		((@lCalculationTypeId=1 AND R.Amount >= (((ISNULL(R.Amount,0)) * (ISNULL(R.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND R.Amount >= ISNULL(R.ExemptionPercentage,0)))
		
		UPDATE sStudent.tAcademic SET ExemptionTypeId=NULL WHERE Id=@rAcademicId AND OrgId=@rOrgId AND BatchId=@rBatchId
	END	
	
	DROP TABLE #TempExemptionType
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY
BEGIN CATCH 
		DROP TABLE #TempExemptionType
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDeleteFee]
	 
		@rReceiptBookId int=0,	 
		@rClassId int=0,
		@rDivisionId int=0,	 
		@rBatchId int=0,	 
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0, 
	    @rCode nvarchar(20)='',
	    @rSourceId bigint,
	    @rDeleteType nvarchar(20)='',
	    @rSourceTypeId smallint=0,
	    @rFromReceiptNo int,
	    @rToReceiptNo int,
		@rMultiReceiptNo nvarchar(max) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

IF (@rDeleteType = 'Receipt')
BEGIN
DELETE sFee.tReceiptDetail 
		FROM sFee.tReceiptDetail RD
		INNER JOIN sFee.tReceipt R  
		ON R.Id=RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=R.SourceId
	WHERE 
		R.ReceiptBookId=@rReceiptBookId
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (R.ReceiptNumber IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMultiReceiptNo,',')) OR @rMultiReceiptNo='')

	-- For Mantis 0023321 By Foram on 14/03/2024 START
	SELECT ROW_NUMBER() OVER (ORDER BY R.Id) AS row_num, R.Id, vSA.AcademicId, vSA.OrgId, vSA.BatchId INTO #TempReceiptId
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=R.SourceId
	WHERE 
		R.ReceiptBookId=@rReceiptBookId
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (R.ReceiptNumber IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rMultiReceiptNo,',')) OR @rMultiReceiptNo='')
	-- For Mantis 0023321 By Foram on 14/03/2024 END
	
	DELETE sFee.tReceipt 
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=R.SourceId
	WHERE 
		R.ReceiptBookId=@rReceiptBookId
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (R.ReceiptNumber IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMultiReceiptNo,',')) OR @rMultiReceiptNo='')

	-- For Mantis 0023321 By Foram on 14/03/2024 START
	UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END
	WHERE ReceiptId IN (SELECT Id FROM #TempReceiptId)
	-- For Mantis 0023321 By Foram on 14/03/2024 END

	-- For Fee Process Added By Hemali 2025-01-30
	DECLARE @lcount int = 0
	SELECT @lCount =  COUNT(Id) FROM #TempReceiptId
	WHILE @lCount > 0 
	BEGIN
		Declare @lReceiptId bigint=0, @lAcademicId bigint = 0, @lBatchId int = 0, @lOrgId int
		SELECT @lReceiptId = Id, @lAcademicId = AcademicId, @lBatchId = BatchId, @lOrgId = OrgId 
		FROM #TempReceiptId WHERE row_num = @lCount 
		
		EXEC [sFee].[pDeletedRecieptFeeProcessGenerate] @lOrgId,@lBatchId,@lAcademicId,@lReceiptId,3
		
		SET @lCount = @lCount - 1
	END
	-- For Fee Process Added By Hemali 2025-01-30
	SELECT 1 AS Result
END

IF(@rDeleteType = 'FeeAllocation')
BEGIN

	IF EXISTS
	(
	SELECT 1 FROM 
	    sFee.tFeeAllocation FA
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FA.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FA.SourceId
		INNER JOIN sFee.tReceipt R 
		ON FA.SourceId = R.SourceId AND FA.SourceTypeId = R.SourceTypeId
	WHERE 
		((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
    )
    BEGIN
		SELECT -101 AS Result
		RETURN
	END 

	-- For Fee Process Added By Hemali 2025-01-30
	Update FAS SET FAS.VariableAmount = FA.VariableAmount, FAS.DiscountAmount = FA.DiscountAmount
		, FAS.AdditionalAmount =FA.AdditionalAmount, FAS.NotApplicableAmount= FA.NotApplicableAMount, 
		FAS.TopayAmount =  (FAS.FeeAmount+FA.VariableAmount+FA.AdditionalAmount)-(FA.NotApplicableAmount+FA.DiscountAmount+FAS.PaidAmount)
	FROM sFee.tFeeAllocationStudent FAS
	INNER JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId = FAS.FeeSetupId AND FA.SourceId = FAS.AcademicId
	INNER JOIN sFee.tFeeSetup FS ON FS.Id=FA.FeeSetupId
	INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=FA.SourceId
	WHERE 
		((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FA.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
	-- For Fee Process Added By Hemali 2025-01-30

    DELETE sFee.tFeeAllocation
		FROM sFee.tFeeAllocation FA
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FA.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FA.SourceId
	WHERE 
		((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FA.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))

SELECT 2 AS Result
END	
		
IF(@rDeleteType = 'FeeOptional')
BEGIN
	
	IF EXISTS
	( 
    SELECT 1 FROM
        sFee.tFeeOptional FO
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FO.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FO.SourceId
		INNER JOIN sFee.tReceipt R 
		ON FO.SourceId = R.SourceId AND FO.SourceTypeId = R.SourceTypeId
	WHERE 
		((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
    )
    BEGIN
		SELECT -102 AS Result
		RETURN
	END 

    DELETE sFee.tFeeOptional
		FROM sFee.tFeeOptional FO
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FO.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FO.SourceId
	WHERE 
		((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FO.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))		

	-- For Fee Process Added By Hemali 2025-01-30
	DELETE FAS
		FROM sFee.tFeeAllocationStudent FAS
		INNER JOIN sFee.tFeeOptional FO ON FAS.FeeSetupId = FO.FeeSetupId AND FAS.AcademicId = FO.SourceId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id=FO.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=FO.SourceId
	WHERE 
		((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FO.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
	-- For Fee Process Added By Hemali 2025-01-30
SELECT 3 AS Result
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositAccountMappingGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		 
           --@rChargeCategoryId int,
		   --@rBatchId int,
		   @rOrgGroupId int 
		   
		   
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 ISNULL(CM.Id,0)AS DepositeHeadId,
			ISNULL(AM.DepositeHeadId,0)AS DepositeId,
			--ISNULL(FS.ClassId,0)AS ClassId,
			 
			--ISNULL(CM.ChargeCategoryId,0) AS ChargeCategoryId,
			--ISNULL(CR.BatchId,0)AS BatchId,
			 
			ISNULL(AYM.AccountId,0) AS AccountId,
			ISNULL(AM.CreditLedgerId,0) AS CreditLedgerId,
			ISNULL(AM.DebitLedgerId,0) AS DebitLedgerId,
			ISNULL(AM.AccountingYearId,0) AS AccountingYearId,
			ISNULL(AM.PayTypeId,0) AS AMPayTypeId,
			ISNULL(PTM.Id,0) AS PayTypeId,
			ISNULL(PTM.Title,'') AS PayTypeName 
			 
  FROM 
		  sFee.tDepositHeadMaster CM
		
		Cross JOIN sFinanceCommon.tPayTypeMaster PTM 
		LEFT JOIN sFee.tDepositeAccountMapping AM ON AM.DepositeHeadId=CM.Id AND AM.PayTypeId=PTM.Id	
		LEFT JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=CLM.AccountingYearId AND AYM.Id=DLM.AccountingYearId
WHERE 
		CM.OrgGroupId=@rOrgGroupId

ORDER BY  PTM.Id

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pDepositAddAdd]
	 
	@rId bigint,
	@rDepositHeadId int,
	--@rStudentId bigint,
	@rAmount decimal(12,2),
	@rDepositDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	--@rBatchId int,
	@rOrgGroupId smallint,
	@rAcademicId bigint,
	@rNumber int=0,
	@rOrgGroupBatchId int,
	@rReferenceSourceTypeId smallInt = 0,		-- Mantis Id : 0034851	
	@rReferenceSourceId BigInt = 0				-- Mantis Id : 0034851	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint
DECLARE @lClassId int

BEGIN	
--BEGIN TRY
--BEGIN TRANSACTION	

    SELECT @lStudentId= StudentId From sStudent.vStudentAcademic  Where AcademicId=@rAcademicId 
-- SELECT @lClassId= ClassId From sStudent.vStudentAcademic Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId

	-- AMOUNT VALIDATION
	--If EXISTS
	--(SELECT DB.BalanceAmount FROM sFee.tDepositBalance DB WHERE DB.DepositHeadId = @rDepositHeadId AND DB.ClassId=@lClassId AND BalanceAmount 
	-- < (SELECT  ISNULL(SUM(DA.Amount),0) + @rAmount AS TotalAmount FROM sFee.tDepositAdd DA 
	--	WHERE DepositHeadId = @rDepositHeadId AND StudentId=@lStudentId AND Id <> @rId)) 				
	--BEGIN
	--	SELECT -102 as Result
	--	RETURN
	--END 
	DECLARE @lConfigValue nvarchar(50)

	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 215 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF(@lConfigValue='True')
	BEGIN
	 IF EXISTS(SELECT 1 From sStudent.vStudentAcademic VA INNER JOIN  sFee.tDepositAdd  D ON  D.AcademicId=VA.AcademicId  WHERE VA.StudentId=@lStudentId)
	    BEGIN
		SELECT -105 as Result
		RETURN
		END
	END


	
	IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sFee.tDepositAdd  where OrgGroupBatchId=@rOrgGroupBatchId AND  DepositNumber=@rNumber)
		Begin
			select -102 as Result
			RETURN
		End
			END
	ELSE
	BEGIN
		
		If  Exists(select Id from sFee.tDepositAdd where  OrgGroupBatchId=@rOrgGroupBatchId AND  DepositNumber=@rNumber AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End

	END
	

 DECLARE @lNextNumber bigint 
 IF(@rId = 0)	    
 BEGIN
 
    IF(@rNumber=0 OR @rNumber IS NULL)
	BEGIN
		SELECT @rNumber=DepositNumber FROM sFee.tDepositAdd  WHERE OrgGroupBatchId=@rOrgGroupBatchId
	END 

   
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositAdd', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sFee.tDepositAdd
		(
		Id,
		DepositHeadId,
		--StudentId,
		Amount,
		DepositDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		OrgGroupBatchId,
		AcademicId,
		DepositNumber,
		ReferenceSourceTypeId,		-- Mantis Id : 0034851	
		ReferenceSourceId			-- Mantis Id : 0034851	
		
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		--@lStudentId,
		@rAmount,
		@rDepositDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rOrgGroupBatchId,
		@rAcademicId,
		@rNumber,
		@rReferenceSourceTypeId,
		@rReferenceSourceId
		) 
		SELECT @lNextNumber AS Result   
	END	
ELSE

    BEGIN 
    SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdd
	    SET
	    DepositHeadId=@rDepositHeadId,
	    --StudentId=@lStudentId,
		Amount=@rAmount,
		DepositDate=@rDepositDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    AcademicId=@rAcademicId,
		DepositNumber=@rNumber,
		OrgGroupBatchId=@rOrgGroupBatchId,
		ReferenceSourceTypeId = @rReferenceSourceTypeId,		-- Mantis Id : 0034851	
		ReferenceSourceId = @rReferenceSourceId					-- Mantis Id : 0034851	
	    WHERE Id = @rId 
	    SELECT @lNextNumber AS Result
	 END  
	
--	COMMIT TRANSACTION
		
--END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositAddBulkGet]
           @rOrgId int,    
           @rCode nvarchar(max),
           @rStrSuid nvarchar(max)='',
           @rBatchId int,
           @rClassId int,
           @rDivisionId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
			vSA.OrgId,
			vSA.Code,
			vSA.Name AS StudentName,        
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
			ISNULL(vSA.SUId,'') AS SUId,
			VSA.AcademicId,
			VSA.OrganiZationName
  FROM 		
			sStudent.vStudentAcademic vSA
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
	    AND vSA.BatchID=@rBatchId
	    AND VSA.StatusId=1
	    AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
	    AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
	    AND (vSA.ClassId=@rClassId OR @rClassId=0)
	    AND (vSA.DivisionId=@rDivisionId OR @rDivisionId=0)
		Order By VSA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pDepositAddDelete]
	 
		@rId bigint,
		@rAcademicId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lStudentId bigint
BEGIN 



	BEGIN TRY
		BEGIN TRANSACTION	
			
	IF EXISTS (SELECT 1 FROM  sFee.tDepositAdjustment DA1 INNER JOIN sFee.tDepositAdd DA2 
							  ON DA1.AcademicId=DA2.AcademicId AND DA1.DepositHeadId=DA2.DepositHeadId WHERE DA2.Id=@rId AND DA2.AcademicId=@rAcademicId)
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE 
	
	BEGIN
		DELETE  sFee.tDepositAdd
		FROM sFee.tDepositAdd DA
		WHERE DA.Id=@rId AND DA.AcademicId=@rAcademicId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositAddGet]
          
		   @rOrgId int =0,          
           @rDepositHeadId int =0,
           @rFromAmount decimal(12,2) =0,
           @rToAmount decimal(12,2) =0,
           @rFromDepositDate date ='',
           @rToDepositDate date='',
           @rBatchId int =0,
           @rCode nvarchar(20) = '',
           @rOrgGroupBatchId int =0,
           @rClassId int=0,
           @rDivisionId int=0
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		vSA.OrganizationName,
		DA.Id,
		DA.DepositHeadId,
		--DA.StudentId AS StudentId,
		DA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(VSA.SUID,'') AS SUID,
        vSA.BatchId,
		vSA.BatchName,
		Isnull(DA.DepositNumber,0) As DepositNumber,
		US.DisplayTitle As CreatedUserName
     
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdd DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId 
		LEFT JOIN sSecurity.tUser US ON US.Id = DA.CreatedUserId
  WHERE  
		--vSA.BatchId = @rBatchId
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND((vSA.ClassId = @rClassId)OR(@rClassId=0))
		AND((vSA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
	--	AND DA.OrgGRoupBatchId=@rOrgGroupBatchId
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		Order By DA.DepositDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositAdjustmentAdd]
	
	@rId bigint, 
	@rDepositHeadId int,
	--@rStudentId bigint,
	@rAmount decimal(12,2),
	@rAdjustmentDate date,
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	--@rBatchId int,
	@rOrgGroupId smallint,
	@rAcademicId bigint,
	@rFeeDepositExpenseTypeId int,
	@rAdjustmentNumber Int,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

--SELECT @lStudentId= StudentId From sStudent.vStudentAcademic  Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId
 	
	-- DATE VALIDATION
	--BEGIN
	--	IF EXISTS	(SELECT 1 FROM  sFee.tDepositAdd D  INNER JOIN sFee.tDepositAdjustment DA ON D.DepositHeadId = DA.DepositHeadId 
	--								AND D.AcademicId=@rAcademicId AND D.DepositDate > @rAdjustmentDate  )
	--	BEGIN
	--		SELECT -101 as Result
	--		RETURN
	--	END 
	--END 
 
	-- AMOUNT VALIDATIEON
	--BEGIN
	--	 If EXISTS
	--		(SELECT ISNULL(SUM(D.Amount),0),DepositHeadId,StudentId FROM sFee.tDepositAdd D 
	--		WHERE D.DepositHeadId = @rDepositHeadId AND D.StudentId=@lStudentId Group by StudentId,DepositHeadId Having Sum(D.Amount) 
	--	 < (SELECT ISNULL(SUM(Amount),0)+ @rAmount AS TotalAmount FROM sFee.tDepositAdjustment DA 
	--		WHERE DA.DepositHeadId = @rDepositHeadId AND DA.StudentId=@lStudentId AND Id <> @rId )) 	
	--	BEGIN
	--		SELECT -102 as Result
	--		RETURN
	--	END 
	--END				
 IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sFee.tDepositAdjustment  where OrgGroupBatchId=@rOrgGroupBatchId AND  AdjustmentNumber=@rAdjustmentNumber)
		Begin
			select -102 as Result
			RETURN
		End
			END
	ELSE
	BEGIN
		
		If  Exists(select Id from sFee.tDepositAdjustment where  OrgGroupBatchId=@rOrgGroupBatchId AND  AdjustmentNumber=@rAdjustmentNumber AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End

	END
DECLARE @lNextNumber bigint 
IF(@rId = 0)
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output 
	INSERT INTO sFee.tDepositAdjustment
		(
		Id,
		DepositHeadId,
		--StudentId,
		Amount,
		AdjustmentDate,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		AcademicId,
		FeeDepositExpenseTypeId,
		AdjustmentNumber,
		OrgGroupBatchId
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		--@lStudentId,
		@rAmount,
		@rAdjustmentDate,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rAcademicId,
		@rFeeDepositExpenseTypeId,
		@rAdjustmentNumber,
		@rOrgGroupBatchId
		) 
		SELECT @lNextNumber  AS Result   
	END	
ELSE
    BEGIN
    SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdjustment
	    SET
	    DepositHeadId=@rDepositHeadId,
	   -- StudentId=@lStudentId,
		Amount=@rAmount,
		AdjustmentDate=@rAdjustmentDate,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    AcademicId=@rAcademicId,
	    FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId,
		AdjustmentNumber=@rAdjustmentNumber,
		OrgGroupBatchId=@rOrgGroupBatchId
	    WHERE Id = @rId 
	    SELECT 11 AS Result
	 END  
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositAdjustmentBulkGet]
           @rOrgId int,    
           @rCode nvarchar(max),
           @rStrSuid nvarchar(max)='',
           @rBatchId int,
           @rClassId int,
           @rDivisionId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
			vSA.OrgId,
			vSA.Code,
			vSA.Name AS StudentName,        
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
			ISNULL(vSA.SUId,'') AS SUId,
			VSA.AcademicId,
			VSA.OrganiZationName,
			(
			(SELECT 
			ISnull (SUM(DAJ.Amount),0)
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			Where (DAJ.DepositHeadId = DA.DepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 			
			AND VA.StudentId =  vSA.StudentId )
			+ 
				(SELECT ISnull (SUM(DR.RefundAmount),0)  AS Debit
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where (DR.DepositHeadId = DA.DepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 			
			AND VA.StudentId =  vSA.StudentId)
			) AS AdjustmentAmount
  FROM 		
			sStudent.vStudentAcademic vSA
			LEFT JOIN [sFee].[tDepositAdjustment] DA ON DA.AcademicId = vSA.AcademicId
  WHERE  
			(vSA.OrgId=@rOrgId OR @rOrgId=0)
			AND vSA.BatchID=@rBatchId
			AND VSA.StatusId=1
			AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
			AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='')
			AND (vSA.ClassId=@rClassId OR @rClassId=0)
			AND (vSA.DivisionId=@rDivisionId OR @rDivisionId=0) 
			GROUP BY vSA.OrgId,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName,vSA.SUId,VSA.AcademicId,VSA.OrganiZationName, DA.DepositHeadId, vSA.StudentId,VSA.RollNo
			Order By VSA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pDepositAdjustmentDelete]
	 
		@rId bigint,
		@rAcademicId bigint
	
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		

	IF EXISTS (SELECT 1 FROM  sFee.tDepositRefund DR INNER JOIN sFee.tDepositAdjustment DA1 
							  ON DA1.AcademicId=DR.AcademicId AND DA1.DepositHeadId=DR.DepositHeadId )
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE 
	BEGIN
		DELETE  sFee.tDepositAdjustment
		FROM sFee.tDepositAdjustment DA
		WHERE DA.Id=@rId AND DA.AcademicId=@rAcademicId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositAdjustmentGet]
          
		   @rOrgId int=0,          
           @rDepositHeadId int=0,
           @rFromAmount decimal(12,2)=0,
           @rToAmount decimal(12,2)=0,
           @rFromAdjustmentDate date='',
           @rToAdjustmentDate date='',
           @rBatchId int=0,
           @rCode nvarchar(20)='',
           @rOrgGroupBatchId int=0,
           @rFeeDepositExpenseTypeId int=0,
           @rClassId int=0,
           @rDivisionId int=0
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.DepositHeadId,
	--	DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(VSA.SUID,'') AS SUID,
        VSA.BatchId,
        Isnull(DA.FeeDepositExpenseTypeId,0) AS FeeDepositExpenseTypeId,
        ISNULL(EM.Title,'') As FeeDepositExpenseType,
        vSA.StudentId,
		ISNULL(AdjustmentNumber,0) AS AdjustmentNumber,
		vSA.BatchName,				-- MantisId : 0030328
		vSA.OrganizationName
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		LEFT JOIN  sFee.tFeeDepositExpenseTypeMaster EM ON EM.Id=DA.FeeDepositExpenseTypeId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
	    AND VSA.OrgGroupBatchId=@rOrgGroupBatchId
	    AND (DA.FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId OR @rFeeDepositExpenseTypeId=0)
	    AND((vSA.ClassId = @rClassId)OR(@rClassId=0))
		AND((vSA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
		Order By DA.AdjustmentDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositBalanceAdd]
	 
	@rDepositHeadId int,
	@rClassId int,
	@rBalanceAmount decimal(12,2),
	@rNegativeBalance decimal(12,2) = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		---- FOR DELETE 
		--IF(@rIsDeleted=1)
		--BEGIN
		--	DELETE FROM sScholarship.tScholarshipStudentPaid WHERE ScholarshipReceiveId=@rScholarshipReceiveId AND AcademicId=@rAcademicId
		--			SELECT @rScholarshipReceiveId AS Result
		--END	
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

		---- DATE VALIDATION
		
		--	IF NOT EXISTS (SELECT 1 FROM sScholarship.tScholarshipStudentPaid WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId=@rScholarshipReceiveId)
		--	BEGIN
		--		IF EXISTS (SELECT 1 FROM sScholarship.tScholarshipReceive WHERE ReceiveDate > @rPaidDate )
		--		BEGIN
		--			SELECT -101 AS Result
		--			RETURN
		--		END
		--	END 
		--	ELSE
		--	BEGIN
		--		IF EXISTS	(SELECT 1 FROM sScholarship.tScholarshipStudentPaid SSP INNER JOIN sScholarship.tScholarshipReceive SR ON SR.Id = SSP.ScholarshipReceiveId
		--						AND ScholarshipReceiveId=@rScholarshipReceiveId  AND SR.ReceiveDate > @rPaidDate)
		--		BEGIN
		--			SELECT -101 as Result
		--			RETURN
		--		END 
		--	END 
			
		--	-- AMOUNT VALIDATIEON
			
		--	IF EXISTS (SELECT 1 FROM sScholarship.tScholarshipStudentPaid WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId = @rScholarshipReceiveId)
		--	BEGIN
		--		If EXISTS
		--			(SELECT 1 FROM sScholarship.tScholarshipReceive SR
		--			WHERE SR.Id = @rScholarshipReceiveId AND SR.TotalAmount 
		--			< (SELECT  ISNULL(SUM(SSP.PaidAmount),0) + @rPaidAmount - (SELECT ISNULL(PaidAmount,0) FROM sScholarship.tScholarshipStudentPaid 
		--			WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId = @rScholarshipReceiveId) 
		--			AS TotalPaidAmount FROM sScholarship.tScholarshipStudentPaid SSP 
		--			WHERE ScholarshipReceiveId = @rScholarshipReceiveId)) 				
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END 
		--		END
		--	ELSE
		--		BEGIN
		--			If EXISTS
		--			(SELECT SR.TotalAmount FROM sScholarship.tScholarshipReceive SR WHERE SR.Id = @rScholarshipReceiveId AND SR.TotalAmount 
		--			 < (SELECT  ISNULL(SUM(SSP.PaidAmount),0) + @rPaidAmount AS TotalPaidAmount FROM sScholarship.tScholarshipStudentPaid SSP 
		--				WHERE ScholarshipReceiveId = @rScholarshipReceiveId)) 				
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END 
		--		END			
			
 IF NOT EXISTS (SELECT 1 FROM sFee.tDepositBalance WHERE DepositHeadId=@rDepositHeadId AND ClassId=@rClassId)	
   BEGIN
		INSERT INTO sFee.tDepositBalance
			(
				DepositHeadId,
				ClassId,
				BalanceAmount,
				NegativeBalance
			)
		VALUES
			(
				@rDepositHeadId,
				@rClassId,
				@rBalanceAmount,
				@rNegativeBalance
			)   
	END	 
ELSE
     BEGIN
     
	    UPDATE sFee.tDepositBalance
	    SET
			  BalanceAmount=@rBalanceAmount,
			  NegativeBalance = @rNegativeBalance
	    WHERE DepositHeadId=@rDepositHeadId AND ClassId=@rClassId
	    
	 END  
		SELECT @rDepositHeadId AS Result
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pDepositBalanceDelete]
	 
		@rDepositHeadId int  
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		

	IF EXISTS (SELECT 1 FROM  tDepositAdd WHERE DepositHeadId=@rDepositHeadId)
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE 
	BEGIN
		DELETE  sFee.tDepositBalance
		FROM sFee.tDepositBalance DB
		WHERE DB.DepositHeadId=@rDepositHeadId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositBalanceGet]
          
           @rDepositHeadId int,
           @rBatchId int
AS
SET NOCOUNT ON
BEGIN
SELECT   
		ISNULL(vBC.ClassId,0) AS ClassId,
        ISNULL(vBC.ClassName,'') AS ClassName,
        ISNULL(DB.DepositHeadId,0) AS DepositHeadId,
        ISNULL(DB.BalanceAmount,0.00)AS BalanceAmount,
		ISNULL(DB.NegativeBalance,0.00)AS NegativeBalance
  FROM 		
	  	sSetup.vBatchClass vBC
		LEFT JOIN sFee.tDepositBalance DB ON DB.ClassId =vBC.ClassId AND (DB.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
  WHERE 
		vBC.BatchId=@rBatchId
		order by vBC.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositDefaultSetupAdd]	 
	@rDepositHeadId INT,
	@rOrgId INT,
	@rBatchId INT,
	@rSetupAmount DECIMAL(12,2)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF NOT EXISTS (select 1 from sFee.tDepositDefaultSetup where DepositHeadId = @rDepositHeadId AND OrgId = @rOrgId AND BatchId = @rBatchId)
	BEGIN
		INSERT INTO sFee.tDepositDefaultSetup
		(
			 DepositHeadId
			,OrgId
			,BatchId
			,Amount			
		)
		VALUES
		(
			 @rDepositHeadId
			,@rOrgId
			,@rBatchId
			,@rSetupAmount
			
		)
 
		SELECT 1 AS StatusCode	 
	END
	ELSE
	BEGIN
		
		UPDATE sFee.tDepositDefaultSetup
		SET Amount = @rSetupAmount
		WHERE 
			DepositHeadId = @rDepositHeadId 
			AND OrgId = @rOrgId 
			AND BatchId = @rBatchId

		SELECT 11 AS StatusCode	
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositDefaultSetupAmountGet] 
	 @rOrgId INT
	,@rOrgGroupId INT 
	,@rBatchId INT
	,@rCode nvarchar(100) = ''
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lDepositHeadId int

	SET @lDepositHeadId = (select top 1 Id from sFee.tDepositHeadMaster 
		WHERE OrgGroupId = @rOrgGroupId and IsObsolete = 0 order by OrderIndex)

	IF(@lDepositHeadId > 0)
	BEGIN
		SELECT 
			 DFS.DepositHeadId AS DepositHeadId
			,DFS.Amount AS SetupAmount
		FROM  sFee.tDepositDefaultSetup DFS 
		WHERE 
			DFS.DepositHeadId = @lDepositHeadId
			AND DFS.OrgId = @rOrgId
			AND DFS.BatchId = @rBatchId
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositDefaultSetupGet] 
	 @rOrgId INT
	,@rBatchId INT
	,@rOrgGroupId INT
	,@rDepositHeadId INT = 0
AS
SET NOCOUNT ON

BEGIN
	IF EXISTS(SELECT 1 FROM sFee.tDepositDefaultSetup Where OrgId =@rOrgId AND BatchId = @rBatchId)
	BEGIN
		SELECT 
			 DHM.Title AS DepositHead
			,DHM.Id AS DepositHeadId
			,DFS.Amount AS SetupAmount
		FROM [sFee].[tDepositHeadMaster] DHM
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = DHM.OrgGroupId
			LEFT JOIN sFee.tDepositDefaultSetup DFS ON DFS.DepositHeadId = DHM.Id AND DFS.OrgId = @rOrgId AND DFS.BatchId = @rBatchId
		WHERE 
			DHM.IsObsolete = 0 AND DHM.OrgGroupId = @rOrgGroupId
			AND (DHM.Id = @rDepositHeadId OR @rDepositHeadId = 0)
			AND	(((ISNULL(DFS.DepositHeadId, 0) > 0) AND (ISNULL(DFS.OrgId,0) = @rOrgId OR ISNULL(@rOrgId,0) = 0)) OR DFS.DepositHeadId IS NULL)
			AND	(((ISNULL(DFS.DepositHeadId, 0) > 0) AND (ISNULL(DFS.BatchId,0) = @rBatchId OR ISNULL(@rBatchId,0) = 0)) OR DFS.DepositHeadId IS NULL)

		Order by DHM.Title
	END
	
	ELSE
	BEGIN
		SELECT
			 DHM.Title AS DepositHead
			,DHM.Id AS DepositHeadId
			,OM.Id
			,'' AS SetupAmount
		FROM [sFee].[tDepositHeadMaster] DHM
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = DHM.OrgGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id AND OM.Id = @rOrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.OrgID = OM.Id
		WHERE 
			DHM.IsObsolete = 0 AND DHM.OrgGroupId = @rOrgGroupId
			AND (DHM.Id = @rDepositHeadId OR @rDepositHeadId = 0)
			AND (ISNULL(BM.Id,0) = @rBatchId OR ISNULL(@rBatchId,0) = 0)
			AND (ISNULL(OM.Id,0) = @rOrgId OR ISNULL(@rOrgId,0) = 0)
		Order by DHM.Title
	END		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositeAccountMappingAdd]
	 
		   @rDepositeHeadId int,
		   @rAccountingYearId int,
           @rCreditLedgerId int,
           @rDebitLedgerId int,
           @rPayTypeId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DELETE FROM sFee.tDepositeAccountMapping WHERE DepositeHeadId=@rDepositeHeadId AND PayTypeId=@rPayTypeId
	
--IF NOT EXISTS (SELECT 1 FROM sFee.tAccountMapping WHERE FeeSetupId=@rFeeSetupId)		
	BEGIN
	INSERT INTO sFee.tDepositeAccountMapping
		(
		   DepositeHeadId,
		   AccountingYearId,
		   CreditLedgerId,
		   DebitLedgerId,
		   PayTypeId
		   
		)
	VALUES
		(
			@rDepositeHeadId,
			@rAccountingYearId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rPayTypeId
		)
		SELECT 1 AS Result
		             
	END	 
	
	--ELSE
	
	--BEGIN
	--UPDATE  sFee.tAccountMapping
	--SET
	--     AccountingYearId=@rAccountingYearId,
	--     CreditLedgerId=@rCreditLedgerId,
	--     DebitLedgerId=@rDebitLedgerId,
	--	 PayTypeId=@rPayTypeId
		
	--  WHERE (FeeSetupId = @rFeeSetupId)
	--  SELECT 11 AS Result   
	--END  
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pDepositeAccountMappingRemove]

	 @rDepositeHeadId int,
	 @rPayTypeId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	 BEGIN TRANSACTION	
BEGIN
	 
	DELETE 
	FROM sFee.tDepositeAccountMapping
	WHERE DepositeHeadId=@rDepositeHeadId AND PayTypeId = @rPayTypeId
	
	SELECT 1 AS Result
END	
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pDepositePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            
            @rNarration nvarchar(1000), --Change by dhananjay 150->1000 size for mantis id - 0035082
            @rTransactionDate date,
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rDepositeHeadId int ,
            
			@rPayTypeId int,
			@rSourceId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.tDepositeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate= @rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND DepositeHeadId=@rDepositeHeadId)
    BEGIN
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tDepositeAccountPosting
		INSERT INTO sFee.tDepositeAccountPosting
		(
			Id,
			AccountYearId,
			AccountId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			DepositeHeadId
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountYearId,
			@1AccountId,
			 sCommon.fGetDate(),
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rDepositeHeadId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.tDepositeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=  @rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND DepositeHeadId=@rDepositeHeadId
  
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting and Narration='Deposite Receipt' AND SourceTypeId=3)
	BEGIN
		--SELECT 101 AS Result
		--COMMIT TRANSACTION				
		--RETURN 
		Delete from [sAccounting].[tTransactionDetail] Where TransactionId in (Select Id From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=3 )
		Select Id as result From sAccounting.tTransaction Where SourceId =@lNextNumberPosting
		COMMIT TRANSACTION				
		RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    3,
			    @rSourceId,
			    '',
			    '',
			    '',
			    '',
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositePostingDetailAdd]
	 
            @rTransactionId bigint,
            @rNumber bigint,
		    @rLedgerId bigint,
		    @rAmount decimal(12,2),
		    @rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @1TransactionTypeId int 
		
	 SELECT @1TransactionTypeId = LedgerTypeId FROM sAccounting.tLedgerMaster
	 WHERE Id=@rLedgerId

    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
    
	INSERT INTO [sAccounting].[tTransactionDetail]
			   (
			    [Id],
			    [TransactionId],
			    [Number],
			    [TransactionTypeId],
			    [LedgerId],
			    [Amount]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rTransactionId,
			    @rNumber,
			    @1TransactionTypeId,
			    @rLedgerId,
			    @rAmount
			   )
		    SELECT @lNextNumber AS Result
	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositePostingDetailGet]
				
		  -- @rClassId int, 
		   
		   @rOrgGroupId int,
		   @rReceiptDate date='',
           @rReceiptDateTo date='',
           @rAcademicId Bigint
            
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
SELECT  
			 
			AMast.Id AS AccountId,
			AMast.Title AS AccountName,
			AM.AccountingYearId,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			HM.Id AS ChargeId,
			HM.Title AS ChargeTitle ,
			PTM.Title AS PayTypeName,
			AM.PayTypeId ,
			 DA.Amount AS Amount
		FROM 
			sFee.tDepositeAccountMapping AM
			--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.DepositeHeadId  
			--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
			--	AND R.PayTypeId = AM.PayTypeId
			--	AND R.ReceiptDate >= @rReceiptDate 
			--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			
			--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
			--AND (FS.ClassId=@rClassId) 
			--	AND (FS.ReceiptBookId=@rReceiptBookId) 
				--AND (R.OrgGroupBatchId=@rBatchId)
				
			INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId   
					
			INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = HM.Id AND DA.PayTypeId = AM.PayTypeId
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = AM.PayTypeId
		WHERE 
			HM.OrgGroupId=@rOrgGroupId and AcademicId=@rAcademicId
				--GROUP BY AMast.Id,AMast.Title,AM.AccountingYearId,AYM.Title,AM.CreditLedgerId,CLM.Title,DLM.Title,AM.DebitLedgerId,HM.Id,HM.Title,PTM.Title,AM.PayTypeId
--	SELECT  
			
--			--AM.FeeSetupId,
--			AMast.Id AS AccountId,
--			AMast.Title AS AccountName,
--			AM.AccountingYearId,
--			AYM.Title AS AccountingYearName,
--			AM.CreditLedgerId,
--			CLM.Title AS CreditLedgerName,
--			AM.DebitLedgerId,
--			DLM.Title AS DebitLedgerName,
			  
--			FM.Id AS ChargeId,
--			FM.Title AS ChargeTitle ,
--			PTM.Title AS PayTypeName,
--			AM.PayTypeId ,
--			--FHM.Id AS FeeHeadId,
--			--FHM.Title AS FeeHeadName,
--			--FS.ReceiptBookId AS ReceiptBookId,
--			--RBM.Title AS ReceiptBookTitle,
--			--SUM(RD.Amount) AS ReceiptAmount,
--			--R.ChargeReceiptBookId
--			  SUM(DA.Amount) AS Amount
--  FROM 
--			sFee.tDepositeAccountMapping AM
--			--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
--			--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
--			--	AND R.PayTypeId = AM.PayTypeId
--			--	AND R.ReceiptDate >= @rReceiptDate
--			--	AND R.ReceiptDate <= @rReceiptDateTo				
--			INNER JOIN sFee.tDepositHeadMaster FM ON FM.Id=AM.DepositeHeadId 
--			INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = FM.Id AND DA.PayTypeId = AM.PayTypeId	
--		    --INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=R.ChargeReceiptBookId	
--            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
--            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
--            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
--            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
--			 INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = AM.PayTypeId
--WHERE 
--			FM.OrgGroupId=@rOrgGroupId
			
--			GROUP BY 
--			AMast.Id,AMast.Title, AM.AccountingYearId,AYM.Title,AM.CreditLedgerId,CLM.Title,
--			AM.DebitLedgerId,DLM.Title,FM.Id,FM.Title,PTM.Title ,AM.PayTypeId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositHeadMasterAdd]
	 
	        @rId int
	       ,@rNumber int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rOrderIndex int
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sFee.tDepositHeadMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tDepositHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from sFee.tDepositHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tDepositHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sFee.tDepositHeadMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If Exists(select Id from sFee.tDepositHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If  Exists(select Id from sFee.tDepositHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sFee.tDepositHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositHeadMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sFee].[tDepositHeadMaster]
			   (
			    [Id]
			   ,[Number]  
			   ,[Code]
			   ,[Title]
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rCode
			   ,@rTitle
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
			   SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tDepositHeadMaster]
	    SET
			  Number=@rNumber
	         ,Code=@rCode
	         ,Title=@rTitle
	         ,OrderIndex=@rOrderIndex
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositHeadMasterDelete]
     
		@rId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION		

	IF EXISTS (SELECT 1 FROM  sFee.tDepositAdd WHERE DepositHeadId=@rId)
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE IF EXISTS (SELECT 1 FROM  sFee.tDepositAdjustment WHERE DepositHeadId=@rId )
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE IF EXISTS (SELECT 1 FROM  sFee.tDepositRefund WHERE DepositHeadId=@rId )
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE IF EXISTS (SELECT 1 FROM  sFee.tDepositBalance WHERE DepositHeadId=@rId )
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE 
	BEGIN
		DELETE  sFee.tDepositHeadMaster
		FROM sFee.tDepositHeadMaster DHM
		WHERE DHM.Id=@rId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositHeadMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId smallint,
           @rIsWildCardSearch bit
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT DHM.Id 
	  ,DHM.Number
      ,DHM.Code
      ,DHM.Title
      ,DHM.OrderIndex
      ,DHM.IsObsolete
     
  FROM sFee.tDepositHeadMaster DHM 
        
  WHERE 
		((DHM.Id = @rId) OR (@rId = 0))
	AND ((DHM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((DHM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND (DHM.OrgGroupId = @rOrgGroupId)
		order by DHM.OrderIndex 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pdepositPostingDetailAdd]
	 
            @rTransactionId bigint,
            @rNumber bigint,
		    @rLedgerId bigint,
		    @rAmount decimal(12,2),
		    @rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @1TransactionTypeId int 
		
	 SELECT @1TransactionTypeId = LedgerTypeId FROM sAccounting.tLedgerMaster
	 WHERE Id=@rLedgerId

    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
    
	INSERT INTO [sAccounting].[tTransactionDetail]
			   (
			    [Id],
			    [TransactionId],
			    [Number],
			    [TransactionTypeId],
			    [LedgerId],
			    [Amount]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rTransactionId,
			    @rNumber,
			    @1TransactionTypeId,
			    @rLedgerId,
			    @rAmount
			   )
		    SELECT @lNextNumber AS Result
	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositPostingGet]
				
		   --@rClassId int,
           --@rReceiptBookId int,
           @rDepositHead int,
		   --@rBatchId int,
		   @rOrgGroupId int,
		   @rFromDate date='',
		   @rToDate date='',
		   @rDepositePosting nvarchar(50),
		   @rOrgGroupBatchID int=0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

	IF @rDepositePosting = 'Single'
	BEGIN
			SELECT  
					 
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId AS CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					--AM.CreditLedgerId As DebitLedgerId,
					DLM.Title AS DebitLedgerName ,
					 
					--'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,
					AM.PayTypeId AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked	,	
					SUM(DA.Amount) AS Amount,
					DA.DepositDate AS DepositDate,
					'' AS ChequeNo  	 ,
					AcademicId,
					SM.FirstName+' ' +MiddleName+' ' +LastName As Name
			FROM 
					sFee.tDepositeAccountMapping AM
					--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
					--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
					--	AND R.PayTypeId = AM.PayTypeId
					--	AND R.ReceiptDate >= @rReceiptDate 
					--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
					 
					INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId AND AM.DepositeHeadId=@rDepositHead	
					INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = HM.Id AND DA.PayTypeId = AM.PayTypeId	
						 
						AND DA.DepositDate >= @rFromDate 
						AND DA.DepositDate <= @rToDate  
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sStudent.tAcademic A On A.Id=DA.AcademicId
					INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId	   AND BM.OrgGroupBatchId=@rOrgGroupBatchID
					GROUP BY  AMast.Title,AYM.Title,AM.CreditLedgerId,CLM.Title, DLM.Title,AM.PayTypeId,AYM.ISLocked,DA.DepositDate,AcademicId,
					SM.FirstName,MiddleName,LastName
	 END
	 ELSE
		BEGIN		
		SELECT  
			 
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			 AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName ,
			--SUM(RD.Amount) AS ReceiptAmount,
			--'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,
			AM.PayTypeId AS PayTypeId,	
			ISNULL(AYM.ISLocked,0) AS ISLocked	,
			SUM(DA.Amount) Amount,
			DA.DepositDate,
			DA.ChequeNo ,
			AcademicId,
			SM.FirstName+' ' +MiddleName+' ' +LastName As Name
		FROM 
			sFee.tDepositeAccountMapping AM
			--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.DepositeHeadId  
			--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
			--	AND R.PayTypeId = AM.PayTypeId
			--	AND R.ReceiptDate >= @rReceiptDate 
			--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			
			--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
			--AND (FS.ClassId=@rClassId) 
			--	AND (FS.ReceiptBookId=@rReceiptBookId) 
				--AND (R.OrgGroupBatchId=@rBatchId)
				
			INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId   
					AND AM.DepositeHeadId=@rDepositHead		
			INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = HM.Id AND DA.PayTypeId = AM.PayTypeId
					AND DA.DepositDate >=@rFromDate
					AND DA.DepositDate <=@rToDate
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sStudent.tAcademic A On A.Id=DA.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE 
			AMast.OrgGroupId=@rOrgGroupId AND DA.PayTypeId=1  AND BM.OrgGroupBatchId=@rOrgGroupBatchID
			 GROUP BY AMast.Title,AYM.Title,AM.CreditLedgerId,CLM.Title,AM.DebitLedgerId,DLM.Title,AM.PayTypeId,AYM.ISLocked,DA.DepositDate,DA.ChequeNo,AcademicId,
					SM.FirstName,MiddleName,LastName
			
		UNION ALL
		
		SELECT  
			 
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			 AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName ,
			 
			--R.ChequeNo,R.ChequeDate,R.BankName,
			AM.PayTypeId AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked	,
			
			 	SUM(DA.Amount) Amount,
			DA.DepositDate,
			DA.ChequeNo,
			AcademicId,
			SM.FirstName+' ' +MiddleName+' ' +LastName As Name
						
		FROM 
			sFee.tDepositeAccountMapping AM
			--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeId 
			--	AND R.PayTypeId = AM.PayTypeId
			--	AND R.ReceiptDate >= @rReceiptDate  
			--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			 INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId AND AM.DepositeHeadId=@rDepositHead	
			 INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = HM.Id AND DA.PayTypeId = AM.PayTypeId	
					AND DA.DepositDate >= @rFromDate
					AND DA.DepositDate <= @rToDate
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sStudent.tAcademic A On A.Id=DA.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  
		WHERE    AMast.OrgGroupId=@rOrgGroupId AND DA.PayTypeId=2   AND BM.OrgGroupBatchId=@rOrgGroupBatchID
		 GROUP BY AMast.Title,AYM.Title,AM.CreditLedgerId,CLM.Title, AM.DebitLedgerId,AM.PayTypeId,AYM.ISLocked,DA.DepositDate,DA.ChequeNo,AcademicId,
					SM.FirstName,MiddleName,LastName,DLM.Title 
			
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositRefundAdd]
	 
	@rDepositHeadId int,
	--@rStudentId bigint,
	@rRefundAmount decimal(12,2),
	@rRefundDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	--@rBatchId int,
	@rId Bigint,
	@rOrgGroupId smallint,
	@rAcademicId bigint,
	@rRefundNumber int,
    @rOrgGroupBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint
Declare @lRefundAmount decimal(12,2)
BEGIN	
BEGIN TRY
 IF(@rId = 0)
  BEGIN
				DECLARE @lDepositAdd decimal(12,2)=0
				DECLARE @lAdjustmentAdd decimal(12,2)=0
				DECLARE @lRefundAdd decimal(12,2)=0
				SELECT @lStudentId= StudentId From sStudent.vStudentAcademic  Where AcademicId=@rAcademicId 
				SELECT @lDepositAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D  INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=D.AcademicId
				WHERE VA.StudentId = @lStudentId AND D.DepositHeadId = @rDepositHeadId )
				SELECT @lAdjustmentAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdjustment D  INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=D.AcademicId
				WHERE VA.StudentId = @lStudentId  AND D.DepositHeadId = @rDepositHeadId  )
				SELECT @lRefundAdd = (SELECT ISNULL(SUM(R.RefundAmount),0) FROM sFee.tDepositRefund R  INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=R.AcademicId
				WHERE VA.StudentId = @lStudentId AND R.DepositHeadId = @rDepositHeadId  )
				IF ( @lDepositAdd - @lAdjustmentAdd - @lRefundAdd < @rRefundAmount )
					BEGIN
					SELECT -101 AS RESULT -- Less then 0 amount re
					RETURN
					END
				END

 
 -- AMOUNT VALIDATIEON
 --IF EXISTS (SELECT 1 FROM sFee.tDepositRefund DR WHERE StudentId= @lStudentId AND DepositHeadId = @rDepositHeadId AND DR.OrgGroupBatchId=@rOrgGroupBatchId)
 --BEGIN
	--SELECT @lRefundAmount = (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
	--INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = @lStudentId
	--WHERE D.DepositHeadId = DR1.DepositHeadId AND D.StudentId=DR1.StudentId AND DR1.OrgGroupBatchId=@rOrgGroupBatchId AND D.OrgGroupBatchId =@rOrgGroupBatchId)

	-- - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
	-- INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.StudentId=DA.StudentId AND DA.StudentId = @lStudentId
	-- WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.StudentId=DR2.StudentId  AND DR2.OrgGroupBatchId=@rOrgGroupBatchId AND DA.OrgGroupBatchId=@rOrgGroupBatchId)  
	 
	--IF @lRefundAmount < @rRefundAmount
	--	BEGIN
	--		SELECT -101 AS RESULT
	--		RETURN
	--	END		 
	--END	 
	
 -- DATE VALIDATION
 
	--BEGIN
	--	IF EXISTS	(SELECT 1 FROM  sFee.tDepositAdd D  INNER JOIN sFee.tDepositRefund DR ON D.DepositHeadId = DR.DepositHeadId 
	--								AND D.StudentId=@lStudentId  AND D.DepositDate > @rRefundDate AND DR.OrgGroupBatchId=@rOrgGroupBatchId)
	--	BEGIN
	--		SELECT -102 as Result
	--		RETURN
	--	END 
	--END 
 
 --IF NOT EXISTS (SELECT 1 FROM sFee.tDepositRefund DR INNER JOIN sStudent.vStudentAcademic A ON A.StudentId = DR.StudentId 
	--		    AND A.StudentId=@lStudentId AND A.BatchId=@rBatchId AND DR.DepositHeadId=@rDepositHeadId AND DR.OrgGroupBatchId=@rOrgGroupBatchId AND A.OrgGroupBatchId=@rOrgGroupBatchId)
  
  
  IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sFee.tDepositRefund  where OrgGroupBatchId=@rOrgGroupBatchId AND  RefundNumber=@rRefundNumber)
		Begin
			select -102 as Result
			RETURN
		End
			END
	ELSE
	BEGIN
		
		If  Exists(select  1 from sFee.tDepositRefund where  OrgGroupBatchId=@rOrgGroupBatchId AND  RefundNumber=@rRefundNumber AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End

	END
  BEGIN TRANSACTION	
  DECLARE @lNextNumber bigint 
 IF(@rId = 0)
 BEGIN   
 	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositRefund', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sFee.tDepositRefund
		(
		Id,
		DepositHeadId,
	--	StudentId,
		RefundAmount,
		RefundDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		AcademicId,
		RefundNumber,
		OrgGroupBatchId
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		--@lStudentId,
		@rRefundAmount,
		@rRefundDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rAcademicId,
		@rRefundNumber,
		@rOrgGroupBatchId
	
		) 
		SELECT @lNextNumber AS Result  
	END	
	
ELSE
    BEGIN
	    UPDATE sFee.tDepositRefund
	    SET
		RefundAmount=@rRefundAmount,
		RefundDate=@rRefundDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate() ,
		RefundNumber=@rRefundNumber,
		OrgGroupBatchId=@rOrgGroupBatchId  
	    WHERE 
	     DepositHeadId=@rDepositHeadId
	     AND Id = @rId  
	     AND  AcademicId=@rAcademicId
	    SELECT @rAcademicId  AS Result
	 END  
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositRefundAmountGet]
	 
	@rDepositHeadId int,
	--@rStudentId bigint,
	@rAcademicId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lStudentId bigint
BEGIN	
--BEGIN TRY
--BEGIN TRANSACTION	

 SELECT @lStudentId= StudentId From sStudent.vStudentAcademic  Where AcademicId=@rAcademicId 
 
 -- AMOUNT VALIDATIEON
 IF EXISTS (SELECT 1 FROM sFee.tDepositRefund DR  INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=DR.AcademicId
 WHERE VA.StudentId = @lStudentId AND DepositHeadId = @rDepositHeadId )
  BEGIN
		SELECT ISNULL((SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
	    INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=D.AcademicId
	    WHERE VA.StudentId = @lStudentId AND DepositHeadId = @rDepositHeadId)

		 -(SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		  INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=DA.AcademicId
	    WHERE VA.StudentId = @lStudentId AND DepositHeadId = @rDepositHeadId)
		
		 - (select ISNULL(SUM(DR.RefundAmount),0) FROM sFee.tDepositRefund DR 
		   INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=DR.AcademicId
	       WHERE VA.StudentId = @lStudentId AND DepositHeadId = @rDepositHeadId  )
	  ,0) As RefundAmount
   END	
ELSE
BEGIN
		SELECT ISNULL((SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
		INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=D.AcademicId
	       WHERE VA.StudentId = @lStudentId AND DepositHeadId = @rDepositHeadId)

		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		 INNER JOIN  sStudent.vStudentAcademic VA ON VA.AcademicId=DA.AcademicId
	       WHERE VA.StudentId = @lStudentId AND DepositHeadId = @rDepositHeadId),0) As RefundAmount
     END
--	COMMIT TRANSACTION
--END TRY
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositRefundBulkGet]
           @rOrgId int,    
           @rCode nvarchar(max),
           @rStrSuid nvarchar(max)='',
           @rBatchId int,
           @rClassId int,
           @rDivisionId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
			vSA.OrgId,
			vSA.Code,
			vSA.Name AS StudentName,        
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
			ISNULL(vSA.SUId,'') AS SUId,
			VSA.AcademicId,
			VSA.OrganiZationName
  FROM 		
			sStudent.vStudentAcademic vSA
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
	    AND vSA.BatchID=@rBatchId
	    AND VSA.StatusId=1
	    AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
	    AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
	    AND (vSA.ClassId=@rClassId OR @rClassId=0)
	    AND (vSA.DivisionId=@rDivisionId OR @rDivisionId=0)
		Order By VSA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pDepositRefundDelete]
	 
		--@rStudentId bigint,
		@rDepositHeadId int ,
		@rAcademicId bigint,
		@rId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		

	--IF EXISTS (SELECT 1 FROM  sScholarship.tScholarshipEligibleStudent WHERE ScholarshipId=@rId)
	--BEGIN
	--	SELECT -101 AS RESULT
	--END
	
	--IF EXISTS (SELECT 1 FROM  sScholarship.tScholarshipReceive WHERE ScholarshipId=@rId )
	--BEGIN
	--	SELECT -101 AS RESULT
	--END
	
	--ELSE 
	BEGIN
		DELETE  sFee.tDepositRefund
		FROM sFee.tDepositRefund DR
		WHERE DR.AcademicId=@rAcademicId AND DR.DepositHeadId=@rDepositHeadId AND DR.Id=@rId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pDepositRefundGet]
          
		   @rOrgId int=0,          
           @rDepositHeadId int=0,
           @rFromRefundAmount decimal(12,2)=0,
           @rToRefundAmount decimal(12,2)=0,
           @rFromRefundDate date='',
           @rToRefundDate date='',
           --@rBatchId int,
           @rCode nvarchar(20)='',
           @rOrgGroupBatchId int =0,
           @rId bigint =0,
           @rClassId int=0,
           @rDivisionId int=0
           
AS
SET NOCOUNT ON

BEGIN
SELECT 
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		vSA.OrganizationName,
		DR.DepositHeadId,
		--DR.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DR.RefundDate,
		DR.PayTypeId,
		DR.ChequeNo,
		DR.BankName,
		DR.Remark,
		DR.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName, 
        DR.Id ,       
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
        (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
        INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.AcademicId=D.AcademicId AND D.AcademicId = DR.AcademicId
        WHERE D.DepositHeadId = DR1.DepositHeadId AND D.AcademicId=DR1.AcademicId )         
		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		 INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.AcademicId=DA.AcademicId AND DA.AcademicId= DR.AcademicId
		 WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.AcademicId=DR2.AcademicId ) END AS RefundAmount,
        ISNULL(VSA.SUID,'') AS SUID,
        vSA.BatchId,
		vSA.BatchName,
		Isnull(RefundNumber,0) AS RefundNumber,
		US.DisplayTitle As CreatedUserName
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DR.DepositHeadId
		LEFT JOIN sSecurity.tUser US ON US.Id = DR.CreatedUserId
  WHERE  
		--vSA.BatchId = @rBatchId 
	   (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DR.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND VSA.OrgGroupBatchId=@rOrgGroupBatchId
		AND( DR.Id=@rId OR @rId=0)
		AND((vSA.ClassId = @rClassId)OR(@rClassId=0))
		AND((vSA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
		--GROUP BY
		
		--DHM.Title,vSA.OrgId,DR.DepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		--DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName  
		Order By DR.RefundDate     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pDepositSetupAdd]	 
	@rDepositHeadId int,
	@rXML nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT


EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
		
	CREATE TABLE #ListofData(DepositHeadId bigint,StudentId bigint,Amount decimal(12,2),IsExist bit);
	
		insert into #ListofData
		select @rDepositHeadId,E.StudentId,E.Amount,0
		from
		(
				SELECT StudentId,Amount FROM
				OPENXML (@loDoc, '/Students/DepositSetup')
				WITH (
						StudentId BIGINT, 
						Amount decimal(12,2))	
						)E 	

				
		UPDATE #ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sFee.tDepositSetup Where DepositHeadId=@rDepositHeadId) 
		
		set @sql='INSERT INTO sFee.tDepositSetup 
					(DepositHeadId,StudentId,Amount)
					SELECT
						LD.DepositHeadId,LD.StudentId,LD.Amount
					FROM
						#ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
				
		set @sql='UPDATE sFee.tDepositSetup set Amount = LD.Amount
					from sFee.tDepositSetup DS 
					INNER JOIN #ListofData LD ON DS.StudentId=LD.StudentId AND DS.DepositHeadId = LD.DepositHeadId AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table #ListofData
			 SELECT 1 AS StatusCode
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositSetupGet]
          
		   @rOrgId int =0,  
		   @rBatchId int =0,        
           @rDepositHeadId int =0,
		   @rDepartmentId int=0,
		   @rClassId int=0,
		   @rDivisionId int =0,
		   @rCode nvarchar(20) = '',
		   @rIsPending Bit = 0 --Added by dhananjay for mantis : 39748

AS
SET NOCOUNT ON

BEGIN
SELECT  
		vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
		vSA.Code,
		vSA.RollNo,
		vSA.Name AS StudentName, 
		DS.Amount AS SetupAmount ,
		vSA.StudentId,
		CM.Title AS AdmissionStandard,
		BM.Title AS AdmissionBatch
			
  FROM 	
  
		sStudent.vStudentAcademic vSA
		LEFT JOIN sFee.tDepositSetup DS ON DS.StudentId = vSA.StudentId
		AND (DS.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
		LEFT JOIN sSetup.tClassMaster CM ON SA.AdmissionStandardId=CM.Id
		INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=SA.BatchId

  WHERE  
		
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (vSA.BatchId=@rBatchId OR @rBatchId=0)
		AND vSA.StatusId =1
		AND (vSA.DepartmentId=@rDepartmentId OR @rDepartmentId=0)
		AND((vSA.ClassId = @rClassId)OR(@rClassId=0))
		AND((vSA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (ISNULL(DS.Amount,0.00) <= 0 OR  @rIsPending = 0)--Added by dhananjay for mantis : 39748
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pDepositSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rOrgGroupBatchId int=0,
	@rDepositHeadId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'DepositPayTypeList')
		BEGIN
			SELECT PTM.Title AS PayType,ISNULL(SUM(T.DepositAddAmount),0) AS DepositAddAmount,
			ISNULL(SUM(T1.RefundAmount),0) AS RefundAmount
			FROM sFinanceCommon.tPayTypeMaster PTM 
			LEFT JOIN 
			(
				SELECT SUM(Amount) AS DepositAddAmount,PayTypeId 
				FROM sFee.tDepositAdd 
				WHERE ((OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
				 AND ((DepositHeadId=@rDepositHeadId)OR(@rDepositHeadId=0))
				GROUP BY PayTypeId
			)T ON T.PayTypeId  = PTM.Id
			LEFT JOIN 
			(
				SELECT SUM(RefundAmount) AS RefundAmount,PayTypeId 
				FROM sFee.tDepositRefund 
				WHERE ((OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
				 AND ((DepositHeadId=@rDepositHeadId)OR(@rDepositHeadId=0))
				GROUP BY PayTypeId
			)T1 ON T1.PayTypeId  = PTM.Id
			GROUP BY PTM.Title
			HAVING SUM(T.DepositAddAmount) >0 OR SUM(T1.RefundAmount) >0
		END
	ELSE IF(@rType = 'DepositAmount')
		BEGIN
		SELECT 
			ISNULL((SELECT SUM(Amount) FROM sFee.tDepositAdd WHERE ((OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0)) AND ((DepositHeadId=@rDepositHeadId)OR(@rDepositHeadId=0))),0) AS TotalDepositAmount,
			ISNULL((SELECT SUM(Amount) FROM sFee.tDepositAdd WHERE CONVERT(DATE,DepositDate) = CONVERT(DATE,GETDATE()) AND ((OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0)) AND ((DepositHeadId=@rDepositHeadId)OR(@rDepositHeadId=0))),0) AS TodayDepositAmount,
			ISNULL((SELECT SUM(Amount) FROM sFee.tDepositAdjustment WHERE ((OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0)) AND ((DepositHeadId=@rDepositHeadId)OR(@rDepositHeadId=0))),0) AS TotalAdjustmentAmount,
			ISNULL((SELECT SUM(Amount) FROM sFee.tDepositAdjustment WHERE CONVERT(DATE,AdjustmentDate) = CONVERT(DATE,GETDATE()) AND ((OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0)) AND ((DepositHeadId=@rDepositHeadId)OR(@rDepositHeadId=0))),0) AS TodayAdjustmentAmount,
			ISNULL((SELECT SUM(RefundAmount) FROM sFee.tDepositRefund WHERE ((OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0)) AND ((DepositHeadId=@rDepositHeadId)OR(@rDepositHeadId=0))),0) AS TotalRefundAmount,
			ISNULL((SELECT SUM(RefundAmount) FROM sFee.tDepositRefund WHERE CONVERT(DATE,RefundDate) = CONVERT(DATE,GETDATE()) AND ((OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0)) AND ((DepositHeadId=@rDepositHeadId)OR(@rDepositHeadId=0))),0) AS TodayRefundAmount



		END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sFee].[pEmandateRequestAdd]
			
			@rAcademicId BIGINT=0,
			@rCheckSum NVARCHAR(500),
			@rMsgId NVARCHAR(50),
			@rCustomer_Name NVARCHAR(40),
			@rCustomer_MobileNo NVARCHAR(34),
			@rCustomer_EmailId NVARCHAR(50),
			@rCustomer_AccountNo NVARCHAR(35),
			@rCustomer_StartDate NVARCHAR(10),
			@rCustomer_ExpiryDate NVARCHAR(10),
			@rCustomer_DebitAmount DECIMAL(15,2) = 0,
			@rCustomer_MaxAmount DECIMAL(15,2) = 0,
			@rCustomer_DebitFrequency NVARCHAR(4),
			@rCustomer_InstructedMemberId NVARCHAR(11),
			@rShort_code NVARCHAR(10),
			@rCustomer_SequenceType NVARCHAR(4),
			@rMerchant_Category_Code NVARCHAR(4),
			@rCustomer_Reference1 NVARCHAR(50),
			@rCustomer_Reference2 NVARCHAR(50),
			@rChannel NVARCHAR(6),
			@rUtilCode NVARCHAR(18),
			@rFiller1 NVARCHAR(50),
			@rFiller2 NVARCHAR(50),
			@rFiller3 NVARCHAR(50),
			@rFiller4 NVARCHAR(50),
			@rFiller5 NVARCHAR(50),
			@rFiller6 NVARCHAR(50),
			@rFiller7 NVARCHAR(50),
			@rFiller8 NVARCHAR(50),
			@rFiller9 NVARCHAR(50),
			@rFiller10 NVARCHAR(50),
			@rCreatedUserId BIGINT,
			@rOrgId int
			

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tEMandate', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tEMandate
			(
				Id
			   ,AcademicId
			   ,CheckSum
			   ,Msgid
			   ,Customer_Name
			   ,Customer_Mobile
			   ,Customer_EmailId
			   ,Customer_AccountNo
			   ,Customer_StartDate
			   ,Customer_ExpiryDate
			   ,Customer_DebitAmount
			   ,Customer_MaxAmount
			   ,Customer_DebitFrequency
			   ,Customer_InstructedMemberId
			   ,Short_code
			   ,Customer_SequenceType
			   ,Merchant_Category_Code
			   ,Customer_Reference1
			   ,Customer_Reference2
			   ,Channel
			   ,UtilCode
			   ,Filler1
			   ,Filler2
			   ,Filler3
			   ,Filler4
			   ,Filler5
			   ,Filler6
			   ,Filler7
			   ,Filler8
			   ,Filler9
			   ,Filler10
			   ,CreatedUserId
			   ,CreatedDateTime
			)
		VALUES
			(
				@lNextNumber,
				@rAcademicId,
				@rCheckSum,
				@rMsgId,
				@rCustomer_Name,
				@rCustomer_MobileNo,
				@rCustomer_EmailId,
				@rCustomer_AccountNo,
				@rCustomer_StartDate,
				@rCustomer_ExpiryDate,
				@rCustomer_DebitAmount,
				@rCustomer_MaxAmount,
				@rCustomer_DebitFrequency,
				@rCustomer_InstructedMemberId,
				@rShort_code,
				@rCustomer_SequenceType,
				@rMerchant_Category_Code,
				@rCustomer_Reference1,
				@rCustomer_Reference2,
				@rChannel,
				@rUtilCode,
				@rFiller1,
				@rFiller2,
				@rFiller3,
				@rFiller4,
				@rFiller5,
				@rFiller6,
				@rFiller7,
				@rFiller8,
				@rFiller9,
				@rFiller10,
				@rCreatedUserId,
				sCommon.fGetDate()
			)

	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sFee].[pEMandateTransactionGet]
	@rAcademicId bigint = 0,
	@rFromDate nvarchar(10) = '',
	@rToDate nvarchar(10) = '',
	@rOrgGroupId smallint=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rReferenceNo bigint=0
AS
SET NOCOUNT ON

BEGIN
	 SELECT  
		ISNULL(EM.ResponseStatus,'Pending') as ResponseStatus,
		EM.Customer_DebitAmount,
		EM.Customer_MaxAmount,
		EM.Customer_StartDate,
		EM.Customer_ExpiryDate,
		CONVERT(nvarchar(20),SM.Code) AS Code,
		SM.FirstName + ' ' + SM.LastName AS Name,
		CM.DisplayTitle +' - '+ DM.DisplayTitle AS ClassName,
		EM.Id AS EMandateId
	
	FROM 
		sFee.tEmandate EM
		INNER JOIN sStudent.tAcademic A ON A.Id = EM.AcademicId
		INNER JOIN sStudent.tStudentMaster SM ON SM.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 OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		
	WHERE 
		 ((EM.Customer_StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((EM.Customer_StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		 AND ((EM.AcademicId = @rAcademicId) OR (@rAcademicId=0))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (EM.Id= @rReferenceNo OR @rReferenceNo=0)
		 ORDER BY EM.Customer_StartDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pExamptionFeeDashBoardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rFeeHeadId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @rStudentCountStatus TABLE (  
			AcademicId bigint,  
			ReceiptBookId int,
			OrgName nvarchar(30), 
			OrgId int, 
			DepartmentId int, 
			ClassId int, 
			DivisionId int, 
			Amount decimal(12,0),  
			FAAmount decimal(12,0),  
			DiscountAmount decimal(12,0),  
			AdditionalAmount decimal(12,0),  
			NotApplicableAmount decimal(12,0),  
			PaidAmount decimal(12,0),  
			PendingAmount decimal(12,0),
			AdmissionDate Date,
			LeftDate date
		)  
   
		INSERT INTO @rStudentCountStatus  
			SELECT   
			SA.AcademicId,  
			FS.ReceiptBookId,
			SA.OrganizationName,
			SA.OrgId,
			SA.DepartmentId,
			SA.ClassId,
			SA.DivisionId,  
			ISNULL(FS.Amount,0)AS Amount,  
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,  
			ISNULL(R.PaidAmount,0) AS PaidAmount,  
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount  ,
			A.AdmissionDate,
			A.LeftDate
		FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN sStudent.tStudentAdmission A ON A.StudentId = SA.StudentId
		INNER JOIN   
		(  
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
		FROM sFee.tFeeSetup FS1  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=0) OR (0=0))  
			AND ((SA1.AdmissionCategoryId=0) OR (0=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
		WHERE   
			((FS1.ClassId=0) OR (0=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=0) OR (0=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.IsOptional=0)  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			
		UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
			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 FS1.BatchId = SA1.BatchId  
			AND ((SA1.ClassId=0) OR (0=0))   
			AND ((SA1.AdmissionCategoryId=0) OR (0=0))  
		WHERE  
			((FS1.ClassId=0) OR (0=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=0) OR (0=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (0=0))  
			AND (FS1.IsOptional=1)  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			) FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN  
		(  
		SELECT   
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
		FROM  
			sFee.tReceipt R   
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.ClassId=0 OR 0=0)   
			AND (SA1.DivisionId=0 OR 0=0)  
		WHERE    
			(R.SourceTypeId = 2001)  
			AND (R.IsObsolete = 0)   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)  
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND (R.ReceiptDate <= getdate())  
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
		GROUP BY FeeSetupId,R.SourceId  
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id  
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId   
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId  
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = 110100101) OR (110100101 = 0))   
		LEFT JOIN 
		(  
		SELECT   
			AT.SourceId   
		FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		) RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		WHERE   
			((0 = 0 AND  1 = 1) OR (0 = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))  
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))     
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))     
			AND (SA.StatusId=0 OR 0=0)  
			AND ((SA.RollNo >= 0) OR (0=0))  
			AND ((SA.RollNo <= 0) OR (0=0))  
			AND ((SA.Code='') OR (''=''))  
			AND ((SA.DepartmentId=0) OR (0=0))    
			AND ((SA.ExemptionTypeId=0) OR (0=0))    
			AND ((SA.ClassId=0) OR (0=0))  
			AND ((SA.DivisionId=0) OR (0=0))     
		--GROUP BY SA.AcademicId,  
		--	FS.ReceiptBookId,
		--	SA.OrganizationName,
		--	SA.OrgId,
		--	SA.DepartmentId,
		--	SA.ClassId,
		--	SA.DivisionId,  
		--	SA.ClassName,
		--	SA.DivisionName, FS.Amount,FA.VariableAmount,FA.AdditionalAmount,FA.DiscountAmount,FA.NotApplicableAmount,R.PaidAmount,A.AdmissionDate,
		--	A.LeftDate
		ORDER BY SA.AcademicId   

 
  IF(@rType='Organization')
  BEGIN
  SELECT ISNULL(SUM(SCS.DiscountAmount),0) AS  ExamptionAmount FROM  @rStudentCountStatus SCS
  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
  where
	 LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	--AND ((SA.CreatedUserId=@rUserId) OR (@rUserId=0))
	--AND (SA.IsObsolete = 0) 
	
  END
  
  IF(@rType='ReceiptBook')
  BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(SCS.DiscountAmount),0) AS  ExamptionAmount 
		FROM  @rStudentCountStatus SCS
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=SCS.ReceiptBookId
		WHERE 
		LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--AND (R.IsObsolete = 0) 
		GROUP BY RBM.Id,RBM.Title
  END
  
  IF(@rType='FeeHead')
  BEGIN

SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,ISNULL(SUM(SCS.DiscountAmount),0) AS  ExamptionAmount FROM  @rStudentCountStatus SCS
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=SCS.ReceiptBookId
	INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
	INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
	INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		WHERE  LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--AND (R.IsObsolete = 0) 
		AND (SCS.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
  END
  
  IF(@rType='FeeMaster')
  BEGIN

	
				SELECT  FM.Id AS FeeHeadId,FM.Title AS FeeMaster,ISNULL(SUM(SCS.DiscountAmount),0) AS  ExamptionAmount FROM  @rStudentCountStatus SCS
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=SCS.ReceiptBookId
	INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
	INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
	INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		WHERE  LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SCS.ReceiptBookId = @rReceiptBookId)  
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
END
 
  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pExemptionTypeDetailAdd]

           @rExemptionTypeId int,
           @rStrXml nvarchar(MAX),
			@rOrgGroupId int=0
		  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	

BEGIN
	
	DELETE FROM sFee.tExemptionTypeDetail WHERE ExemptionTypeId = @rExemptionTypeId
	
	INSERT INTO sFee.tExemptionTypeDetail
		(
			ExemptionTypeId,
		    FeeId,
		    ExemptionPercentage
		)
		
		SELECT		
			
			@rExemptionTypeId,
			FeeId,
			ExemptionPercentage
						
		FROM OPENXML (@loDoc, '/Table/ExemptionTypeDetail', 1)
		WITH 
			 ( 
			    FeeId int,
			    ExemptionPercentage decimal(8,2)
			  ) 
		
        SELECT 1 AS Result
	END	 
	
	If NOt Exists(Select 1 from sSystem.tPortalSync Where OrgGroupId=@rOrgGroupId)
	BEGIN
	Insert Into sSystem.tPortalSync
		(
			OrgGroupId,
			FeeChange
		)
		Values
		(
			@rOrgGroupId,
			1
		)
	END
	ELse
	BEGIN
		Update sSystem.tPortalSync
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	
	END
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pExemptionTypeDetailGet]
	 
	 @rExemptionTypeId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
	SELECT 
			ETM.Code,
			ISNULL(ETM.Number,0) AS Number,
			ETM.Title,
			ETM.IsObsolete,
			ISNULL(ETM.OrderIndex,0) AS OrderIndex,
			ISNULL(ETD.ExemptionTypeId,0) AS ExemptionTypeId,
			ISNULL(ETD.ExemptionPercentage,0) AS ExemptionPercentage,
			ISNULL(FM.FeeHeadId,0) AS FeeHeadId,
			ISNULL(ETD.FeeId,0) AS FeeId,
			ISNULL(FM.Title,'') AS Fee,
			ISNULL(ETM.CalculationTypeId,0) AS CalculationTypeId,
            ISNULL(CTM.Title,'') AS CalculationType,
			ISNULL(FM.Code,'') AS FeeCode,
			ISNULL(ETM.Remark,'') AS Remark
	FROM 
			sFee.tExemptionTypeMaster ETM
			INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.ExemptionTypeId=ETM.Id
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = ETD.FeeId
			LEFT JOIN sCommon.tCalculationTypeMaster CTM ON CTM.Id = ETM.CalculationTypeId
WHERE 
			ETD.ExemptionTypeId=@rExemptionTypeId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pExemptionTypeMasterAdd]
	 
	        @rId int,
	        @rCode nvarchar(20),
	        @rNumber smallint,
            @rTitle nvarchar(100),
            @rOrgGroupId int,
            @rIsObsolete bit,
            @rOrderIndex smallint,
            @rCreatedUserId bigint,
            @rCalculationTypeId tinyint=0,
            @rRemark nvarchar(500) = ''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM sFee.tExemptionTypeMaster WHERE Code=@rCode AND OrgGroupId=@rOrgGroupId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM sFee.tExemptionTypeMaster WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM sFee.tExemptionTypeMaster WHERE Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF EXISTS(SELECT Id FROM sFee.tExemptionTypeMaster WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END

	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tExemptionTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFee.tExemptionTypeMaster
			   (
			    Id,
			    Code,
			    Number,
			    Title,
			    OrgGroupId,
			    IsObsolete,
			    OrderIndex,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime,
			    CalculationTypeId,
				Remark
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rCode,
			    @rNumber,
			    @rTitle,
			    @rOrgGroupId,
			    @rIsObsolete,
			    @rOrderIndex,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    0,
			    sCommon.fGetDate(),
			    @rCalculationTypeId,
				@rRemark
			   )
		    SELECT @lNextNumber AS Result
       
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sFee.tExemptionTypeMaster
	    SET
			  Code=@rCode,
			  Number=@rNumber,
	          Title=@rTitle,
	          IsObsolete=@rIsObsolete,
	          OrderIndex=@rOrderIndex,
              UpdatedUserId=@rCreatedUserId,
              UpdatedDateTime = sCommon.fGetDate(),
              CalculationTypeId=@rCalculationTypeId,
			  Remark = @rRemark
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result

	 END  	
	
	If Not exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrggroupId)
	BEGIN
	Insert INto sSystem.tPortalSync
	(
		OrgGroupId,
		FeeChange
	)
	Values
	(
		@rORgGRoupId,
		1
	)
	END
	Else
	BEGIN
		Update sSystem.tPortalSync
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pExemptionTypeMasterDelete]
@rId int
AS
BEGIN
BEGIN TRY
	  BEGIN
		
		IF EXISTS(SELECT Id FROM sStudent.tAcademic WHERE ExemptionTypeId=@rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	  
		DELETE FROM sFee.tExemptionTypeDetail WHERE ExemptionTypeId IN (SELECT Id FROM sFee.tExemptionTypeMaster  WHERE Id=@rId)
		DELETE	FROM sFee.tExemptionTypeMaster  WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pExemptionTypeMasterGet]
          
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int,
           @rCalculationTypeId tinyint=0          
          
AS
SET NOCOUNT ON

			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			Set @rCode = sCommon.fSearchStringGet(@rCode)

BEGIN
SELECT 
	   ETM.Id AS ExemptionTypeId,
	   ETM.Code,
	   ISNULL(ETM.Number,0) AS Number,
	   ETM.Title,
       ETM.IsObsolete,
       ISNULL(ETM.OrderIndex,0) AS OrderIndex,
       ISNULL(ETM.CalculationTypeId,0) AS CalculationTypeId,
       ISNULL(CTM.Title,'') AS CalculationType
  FROM sFee.tExemptionTypeMaster ETM
  LEFT JOIN sCommon.tCalculationTypeMaster CTM ON CTM.Id = ETM.CalculationTypeId
  WHERE 
	((ETM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((ETM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ETM.OrgGroupId = @rOrgGroupId
	AND ((ETM.CalculationTypeId = @rCalculationTypeId) OR (@rCalculationTypeId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pExpenseDetailsGet]	 
	 @rTypeId smallint,
	 @rAcademicId Bigint,
	 @rFeeSetupId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if @rTypeId=1
BEGIN    
   SELECT        
        FS.Id,
        FM.Title
   FROM sFee.tFeeSetup FS 
		INNER JOIN sFee.tFeeMaster FM ON  FS.FeeId = FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId AND FHM.Number = 1003  
		INNER JOIN sStudent.tAcademic A ON FS.ClassId = A.ClassId AND FS.BatchId=A.BatchId AND FS.AdmissionCategoryId=A.AdmissionCategoryId 					
   WHERE A.Id = @rAcademicId
END
  
ELSE IF @rTypeId=2  
 BEGIN
   
SELECT ISNULL(( 
   SELECT  
       FO.OpeningAmount
   FROM 
      sFee.tFeeOpening FO     	    
   WHERE     
      FO.AcademicId = @rAcademicId AND FO.FeeSetupId=@rFeeSetupId ),0) AS OpeningAmount
   

  SELECT  
      FET.Code AS FeeExpenseType,
      FE.ExpenseDate,
      FE.ExpenseAmount,
      FE.ExpenseRemark
  FROM  
      sFee.tFeeExpense FE
      INNER JOIN sFee.tFeeExpenseTypeMaster FET ON FET.Id=FE.FeeExpenseTypeId     	  
  WHERE 
      FE.AcademicId = @rAcademicId AND FE.FeeSetupId=@rFeeSetupId 
      
     
      
SELECT ISNULL((       
  SELECT 
       ISNULL(SUM(RD.Amount),0) AS PaidAmount 
  FROM sFee.tReceipt R
       INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
       INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.BatchId = R.BatchId
  WHERE 
       R.SourceTypeId= 2001 AND FS.Id = @rFeeSetupId
       AND R.IsObsolete=0 AND R.SourceId = @rAcademicId),0) AS PaidAmount
   
 END
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pExpenseTypeMasterAdd]
	 
	    @rId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rOrgGroupId int,
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select 1 from sFee.tFeeDepositExpenseTypeMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId  )
		Begin
			select -102 as Result
			RETURN
		End
		If Exists(select 1 from sFee.tFeeDepositExpenseTypeMaster   where Title=@rTitle AND OrgGroupId=@rOrgGroupId )
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
	If Exists(select 1 from sFee.tFeeDepositExpenseTypeMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId )
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sFee.tFeeDepositExpenseTypeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tFeeDepositExpenseTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFee.tFeeDepositExpenseTypeMaster
		(
			
			Id, 
			Code, 
			Title, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			OrgGroupId
		)
	VALUES
		(  
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId
		)
		 SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tFeeDepositExpenseTypeMaster
	    SET
			Title=@rTitle,
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pExpenseTypeMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode varchar(20),
	 @rOrgGroupId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			Id,
			Title,
		    Code,
			IsObsolete
  FROM 
         sFee.tFeeDepositExpenseTypeMaster
  WHERE   
           ((Id = @rId) OR (@rId = 0))
	       AND ((Title like @rTitle+ '%') OR (ISNULL(@rTitle,'') = ''))
	       AND ((Code like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
	       AND OrgGroupId=@rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pExportChargeReceiptDeletedLog]

	 @rOrgGroupBatchId bigint,
	 @rOrgId bigint=0,
	 @rFromDate date=NULL,
	 @rToDate date=NULL
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		CD.Code,
		GuestName As SourceName,
		ReceiptNumber,			
		convert(varchar(10), ReceiptDate, 103) As ReceiptDate,
		ReceiptAmount,
		PayTypeId As PayType,
		ChequeNo,
		BankName,
		ChargeReceiptBookName,
		Remark,
		CreatedUser,				
           convert(varchar(10),CreatedDateTime, 103) + right(convert(varchar(32),CreatedDateTime,100),8) As CreatedDateTime,	 		
		DeletededUser,			
		convert(varchar(10),DeletedDateTime, 103) + right(convert(varchar(32),DeletedDateTime,100),8) As DeletedDateTime,	 
		(SELECT DISTINCT
		 STUFF((SELECT ',' + U.ChargeName + '-' + CONVERT(varchar(10), U.Amount) 
				FROM sAudit.tChargeDetailDelete U
				WHERE U.ChargeName = ChargeName And  ChargeReceiptId=CD.Id
				ORDER BY U.ChargeName FOR XML PATH('')),1,1,''
				) AS ChargeReceiptDetailDeletelist
	     FROM sAudit.tChargeDetailDelete GROUP BY ChargeReceiptId
	     ) AS DeletedChargeReceiptDetail,
		 ISNULL(DeleteRemark,'') AS DeleteRemark
	FROM 
	   sAudit.tChargeDeleted  CD
	   INNER JOIN sStudent.vStudentAcademic SA ON CD.SourceId=SA.AcademicId
	WHERE 
	   SA.OrgGroupBatchId =@rOrgGroupBatchId
	   AND ((SA.OrgId=@rOrgId) OR (@rOrgId = 0))
	   AND ((CD.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	   AND ((CD.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	ORDER BY CD.ReceiptDate DESC    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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,
			SourceName,
			ReceiptNumber,			
			convert(varchar(10), ReceiptDate, 103) As ReceiptDate,
			ReceiptAmount,
			PayType,
			ChequeNo,
			BankName,
			ReceiptBookName,
			Remark,
			CreatedUser,				
            convert(varchar(10),CreatedDateTime, 103) + right(convert(varchar(32),CreatedDateTime,100),8) As CreatedDateTime,	 		
			CollectionGroupName,
			DeletededUser,			
			convert(varchar(10),DeletedDateTime, 103) + right(convert(varchar(32),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
		FROM 
		   sAudit.tReceiptDelete R
		   INNER JOIN sStudent.vStudentAcademic SA ON R.SourceId=SA.AcademicId
		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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pExportPaymentTransactionDeletedLog]

	 @rOrgGroupBatchId bigint,
	 @rOrgId bigint=0,
	 @rFromDate date=NULL,
	 @rToDate date=NULL
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SELECT 
			PTH.Id AS TransactionId,
			SA.Code,
			SA.Name,
			PTH.PayDateTime,
			PTH.PayAmount,
			TSM.Code AS TransactionStatus,
			PTH.MerchantTransactionId,
			PTH.BankTransactionId,
			PTH.BankName,
			PTH.PaymentType,
			PTH.CardNumber,
			PTH.TransactionResponse,
			PTH.TransactionRequest,
			OST.Code AS OSType,
			SUBSTRING(PTH.DeletededUser,CHARINDEX('-',PTH.DeletededUser)+1,LEN(PTH.DeletededUser))AS DeletededUser,
			SUBSTRING(DeletededUser,0,CHARINDEX('-',DeletededUser,0)) AS DeletedUserId,
			PTH.DeletedDateTime
			
		FROM
		   sOp.tPaymentTransactionHistory PTH
		   INNER JOIN sStudent.vStudentAcademic SA ON PTH.PayerSourceId=SA.AcademicId
		   INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.Id=PTH.TransactionStatusId
		   LEFT JOIN sAlert.tOSType OST ON OST.Id=PTH.OSTypeId
		   LEFT JOIN sSecurity.tUser U ON PTH.DeletededUser=U.Id
		WHERE 
		   SA.OrgGroupBatchId =@rOrgGroupBatchId
		   AND ((SA.OrgId=@rOrgId) OR (@rOrgId = 0))
		   AND ((CAST(PTH.PayDateTime AS DATE) >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		   AND ((CAST(PTH.PayDateTime AS DATE) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		ORDER BY PTH.PayDateTime DESC    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeAllocationAdd]
	
	@rXmlDoc nvarchar(MAX),
	@rClassId int,
	@rDivisionId int,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rFeeSetupId int,
	@rCreatedUserId bigint,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	IF(@rFeeSetupId=0 AND @rClassId=0 AND @rSourceTypeId!=0 AND @rSourceId!=0)
	BEGIN
		DELETE FROM sFee.tFeeAllocation WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId
	END
	ELSE IF(@rFeeSetupId!=0 AND @rClassId!=0 AND @rSourceTypeId=0 AND @rSourceId=0)
	BEGIN
		DELETE sFee.tFeeAllocation FROM sFee.tFeeAllocation FA
		INNER JOIN (
			SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId
			 
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId'
		 
	) )TEMP ON Temp.SourceId=FA.SourceId AND Temp.SourceTypeId=FA.SourceTypeId AND FA.FeeSetupId = Temp.FeeSetupId AND FA.FeeSetupId=@rFeeSetupId
		--)
		--INNER JOIN 
		--(
		--	SELECT
		--			2001 AS SourceTypeId,
		--			AcademicId 
		--	FROM 
		--			sStudent.vStudentAcademic WHERE ClassId=@rClassId AND DivisionId=@rDivisionId
		--) Temp ON Temp.AcademicId=FA.SourceId AND Temp.SourceTypeId=FA.SourceTypeId AND FeeSetupId=@rFeeSetupId
	END
	
	INSERT INTO sFee.tFeeAllocation
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
		)
	SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	) 
		  
   DELETE FROM  sFee.tFeeAllocation WHERE ISNULL(VariableAmount,0) = 0 AND ISNULL(DiscountAmount,0) = 0 AND ISNULL(AdditionalAmount,0) = 0 AND ISNULL(NotApplicableAmount,0) = 0 AND ISNULL(Remark,'') = '' -- Add Remark condition for mantis Id : 0034345
   
    IF(@rFeeSetupId=0 AND @rClassId=0 AND @rSourceTypeId!=0 AND @rSourceId!=0)
	BEGIN
		EXEC [sFee].[pFeeProcessGenerateStudentFeeAllocationAdd] @rXmlDoc,@rOrgId,@rCreatedUserId,@rClassId,@rDivisionId,@rSourceTypeId,@rSourceId,@rFeeSetupId
	END
	ELSE IF(@rFeeSetupId!=0 AND @rClassId!=0 AND @rSourceTypeId=0 AND @rSourceId=0)
	BEGIN
		EXEC [sFee].[pFeeProcessGenerateFeeAllocationAdd] @rXmlDoc,@rOrgId,@rCreatedUserId
	END

   SELECT 1 AS Result 
	
 --   UPDATE sFee.tFeeAllocation
 --   SET
	--	VariableAmount=Temp.VariableAmount,
	--	DiscountAmount=Temp.DiscountAmount,
	--	NotApplicableAmount=Temp.NotApplicableAmount,
	--	AdditionalAmount=Temp.AdditionalAmount,
	--	Remark=Temp.Remark,
	--	UpdatedUserId=@rCreatedUserId,
	--	UpdatedDateTime=sCommon.fGetDate() 
	--FROM sFee.tFeeAllocation FA 
	--INNER JOIN 
	--(SELECT
	--		SourceTypeId,
	--		SourceId,
	--		FeeSetupId,
	--		VariableAmount,
	--		DiscountAmount,
	--		NotApplicableAmount,
	--		AdditionalAmount,
	--		Remark
		
	--FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	--WITH
	--(
	--	SourceTypeId smallint '@SourceTypeId',
	--	SourceId bigint '@SourceId',
	--	FeeSetupId int '@FeeSetupId',
	--	VariableAmount decimal(12,2) '@VariableAmount',
	--	DiscountAmount decimal(12,2) '@DiscountAmount',
	--	NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
	--	AdditionalAmount decimal(12,2) '@AdditionalAmount',
	--	Remark nvarchar(200) '@Remark',
	--	IsRecordExist bit '@IsRecordExist'
	--) 
	--WHERE IsRecordExist=1) Temp ON Temp.SourceTypeId=FA.SourceTypeId 
	--	AND Temp.SourceId=FA.SourceId
	--	AND Temp.FeeSetupId=FA.FeeSetupId
 	 
	--	SELECT 11 AS Result    
		
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pFeeAllocationClassGet]
	 
		@rFeeSetupId int,
		@rDivisionId int,
		@rClassId int,
		@rAdmissionCategoryId int,
		@rExemptionTypeId int=0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

DECLARE @rBatchId int

SELECT @rBatchId = BatchId FROM sFee.tFeeSetup WHERE id = @rFeeSetupId	
	
	SELECT 
			SA.AcademicId AS SourceId,
			SA.Name,
			SA.Code,
			SA.RollNo,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00) + ISNULL(FA.VariableAmount,0.00) + ISNULL(FA.AdditionalAmount,0.00) - ISNULL(FA.DiscountAmount,0.00) - ISNULL(FA.NotApplicableAmount,0.00) - ISNULL(R.PaidAmount,0.00) AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			ISNULL(EM.Title,'') AS ExemptionFeeType
			
	  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
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId
				WHERE FS1.ClassId=@rClassId AND 
				FS1.AdmissionCategoryId=@rAdmissionCategoryId AND 
				FS1.Id=@rFeeSetupId AND IsOptional=0 AND
				SA1.BatchId = @rBatchId AND
				FS1.BatchId = @rBatchId
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND 
		SA1.ClassId=@rClassId  AND SA1.AdmissionCategoryId=@rAdmissionCategoryId AND SA1.BatchId = @rBatchId
		
		WHERE
		 FS1.Id=@rFeeSetupId AND
		 FS1.ClassId=@rClassId AND FS1.AdmissionCategoryId=@rAdmissionCategoryId 
		 AND IsOptional=1
		 AND FS1.BatchId = @rBatchId
		 
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tExemptionTypeMaster EM ON EM.Id = SA.ExemptionTypeId
		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 sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId AND R.SourceTypeId = 2001				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE			 		
				 (R.IsObsolete = 0) 
				AND RD.FeeSetupId = @rFeeSetupId
				AND (R.BatchId = @rBatchId) 
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId 
		--AND SA.StatusId=1	
		WHERE
				(SA.ClassId=@rClassId)
			AND (SA.DivisionId=@rDivisionId)
			AND (SA.AdmissionCategoryId=@rAdmissionCategoryId)
			AND (FS.Id=@rFeeSetupId)	
			AND SA.BatchId = @rBatchId
			AND ((SA.ExemptionTypeId =@rExemptionTypeId) OR (@rExemptionTypeId=0))
ORDER BY SA.RollNo
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeAllocationDivisionwiseHistoryAdd]
	
	@rXmlDoc nvarchar(MAX),
	@rClassId int,
	@rDivisionId int,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rFeeSetupId int,
	@rCreatedUserId bigint,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	
	--BEGIN TRANSACTION
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	Declare @lSourceId bigint
	
	CREATE TABLE #TEMP_TABLE
	(
	    [SourceTypeId] smallint,
		[SourceId] bigint,
		[FeeSetupId] int,
		[VariableAmount] decimal(12,2),
		[DiscountAmount] decimal(12,2),
		[AdditionalAmount] decimal (12,2),
		[NotApplicableAmount] decimal (12,2),
		[Remark] nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS,
		[DiscountRemark] nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS ,
		[AdditionalRemark] nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS,
		[NotApplicableRemark] nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS
	)
	
	INSERT INTO #TEMP_TABLE
		SELECT
		    SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	)
	
	--Select * from  #TEMP_TABLE

	Declare @ldata int

	CREATE TABLE #FeeSetup
	(
		SourceId bigint
	)
	
	DELETE FROM  #TEMP_TABLE WHERE ISNULL(VariableAmount,0) = 0 AND ISNULL(DiscountAmount,0) = 0 AND ISNULL(AdditionalAmount,0) = 0 AND ISNULL(NotApplicableAmount,0) = 0

	--Select * from  #TEMP_TABLE
	INSERT INTO #FeeSetup(SourceId)
	SELECT tmp.SourceId
	FROM #TEMP_TABLE tmp
		INNER JOIN  sFee.tFeeAllocation FA ON FA.SourceTypeId=tmp.SourceTypeId AND FA.SourceId =tmp.SourceId
			AND FA.FeeSetupId=tmp.FeeSetupId
			AND ISNULL(FA.VariableAmount,0)=ISNULL(tmp.VariableAmount,0) AND ISNULL(FA.DiscountAmount,0)=ISNULL(tmp.DiscountAmount,0)
			AND ISNULL(FA.AdditionalAmount,0)=ISNULL(tmp.AdditionalAmount,0) AND ISNULL(FA.NotApplicableAmount,0)=ISNULL(tmp.NotApplicableAmount,0) AND ISNULL(FA.Remark,'')=ISNULL(tmp.Remark,'')
			AND ISNULL(FA.DiscountRemark,'')=ISNULL(tmp.DiscountRemark,'') AND ISNULL(FA.AdditionalRemark,'')=ISNULL(tmp.AdditionalRemark,'') AND ISNULL(FA.NotApplicableRemark,'')=ISNULL(tmp.NotApplicableRemark,'')
	--WHERE ISNULL(tmp.VariableAmount,0) <> 0 AND ISNULL(tmp.DiscountAmount,0) <> 0 AND ISNULL(tmp.AdditionalAmount,0) <> 0 AND ISNULL(tmp.NotApplicableAmount,0) <> 0


	--Select * from #FeeSetup
	
	INSERT INTO sFee.tFeeAllocationHistory
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			UserId,
			LogDateTime,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
		)
	SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
			
	FROM #TEMP_TABLE tmp

	WHERE tmp.SourceId NOT IN(SELECT SourceId FROM #FeeSetup)


	--Second Condition
	INSERT INTO #TEMP_TABLE
		SELECT
		    SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark

		FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
		WITH
		(
			SourceTypeId smallint '@SourceTypeId',
			SourceId bigint '@SourceId',
			FeeSetupId int '@FeeSetupId',
			VariableAmount decimal(12,2) '@VariableAmount',
			DiscountAmount decimal(12,2) '@DiscountAmount',
			AdditionalAmount decimal(12,2) '@AdditionalAmount',
			NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
			Remark nvarchar(200) '@Remark',
			DiscountRemark nvarchar(200) '@DiscountRemark',
			AdditionalRemark nvarchar(200) '@AdditionalRemark',
			NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
		)

	CREATE TABLE #FeeSetup1
	(
		SourceId bigint
	)
	
	INSERT INTO #FeeSetup1(SourceId)
	SELECT tmp.SourceId		--mantis: 36671, change tmp.FeeSetupId => tmp.SourceId
	FROM #TEMP_TABLE tmp
		INNER JOIN  sFee.tFeeAllocation FA ON FA.SourceTypeId=tmp.SourceTypeId AND FA.SourceId =tmp.SourceId
			AND FA.FeeSetupId=tmp.FeeSetupId
			AND tmp.VariableAmount=0 AND tmp.DiscountAmount=0
			AND tmp.AdditionalAmount=0 AND tmp.NotApplicableAmount=0
	
	INSERT INTO sFee.tFeeAllocationHistory
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			UserId,
			LogDateTime,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
		)
	SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark

	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	) H
	WHERE H.SourceId  IN(SELECT SourceId FROM #FeeSetup1)


	SELECT 1 AS Result
	

	EXEC sp_xml_removedocument @intDoc
	--COMMIT TRANSACTION

	DROP TABLE #TEMP_TABLE
	DROP TABLE #FeeSetup
	--DROP TABLE #FeeSetup1
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeAllocationGet]
	 
		
		@rSourceId bigint ,
		@rSourceTypeId int,
		@rBatchId int,
		@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	if (@rStudentId <> 0)
	SELECT @rSourceId = Id, @rSourceTypeId = 2001 FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		-- Added
		DECLARE @lExemptionTypeId int = 0
		DECLARE @lExemptionType nvarchar(100) = ''
		
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId, @lExemptionTypeId = ExemptionTypeId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId
		
		-- Added
		SELECT @lExemptionType = Title FROM [sFee].[tExemptionTypeMaster] WHERE Id = @lExemptionTypeId
SELECT 
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount,
			ISNULL(FA.Remark,'') AS Remark,
			ISNULL(FA.NotApplicableRemark,'') AS NotApplicableRemark,
			ISNULL(FA.AdditionalRemark,'') AS AdditionalRemark,
			ISNULL(FA.DiscountRemark,'') AS ExemptionRemark,
			FM.OrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId,
			FM.FeeHeadId,
			FS.FeeDuration,
			ISNULL(FM.Code,'') AS FeeCode,
			CASE 
			      WHEN (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			          AND (ISNULL(FS.StartDate,'1900-01-01') > GETDATE()) AND (ISNULL(FS.Amount,0) > 0 OR ISNULL(FA.VariableAmount,0.00)>0) THEN 'To Pay' 
                  WHEN (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
				      AND (GETDATE() > ISNULL(FS.StartDate,'1900-01-01')) AND (ISNULL(FS.Amount,0) > 0 OR ISNULL(FA.VariableAmount,0.00)>0) THEN 'Unpaid' 
				  WHEN (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) <= 0)
				      AND (ISNULL(FS.Amount,0) > 0 OR ISNULL(FA.VariableAmount,0.00)>0) THEN 'Paid'
				 ELSE
				 '' END AS Status,
			@lExemptionType AS ExemptionType,
			@lExemptionTypeId AS ExemptionTypeId
			,ISNULL(R.RefundAmount,0) AS RefundAmount--add for mantis : 0041008	
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				ISNULL(FS1.FeeDuration,'')  AS FeeDuration
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
				ISNULL(FS1.FeeDuration,'') AS FeeDuration
				 
			FROM sFee.tFeeSetup FS1
			 
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
			,ISNULL(SUM(RRD.Amount),0) AS RefundAmount--add for mantis : 0041008	
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 
			LEFT JOIN sFee.tReceiptRefund	RR ON RR.ReceiptId	= R.Id 	--add for mantis : 0041008	
			LEFT JOIN sFee.tReceiptRefundDetail RRD ON RRD.ReceiptRefundId = RR.Id AND RRD.FeeSetupId = RD.FeeSetupId--add for mantis : 0041008	
			WHERE						
			 R.SourceId= @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY RD.FeeSetupId --RD add for mantis : 0041008	
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sFee].[pFeeAllocationHistoryAdd]
	
	@rXmlDoc nvarchar(MAX),
	@rClassId int,
	@rDivisionId int,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rFeeSetupId int,
	@rCreatedUserId bigint,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	
	 BEGIN TRANSACTION	
	 EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	Declare @lSourceId bigint

	
	CREATE TABLE #TEMP_TABLE
	(
	    [SourceTypeId] smallint,
		[SourceId] bigint,
		[FeeSetupId] int,
		[VariableAmount] decimal(12,2),
		[DiscountAmount] decimal(12,2),
		[AdditionalAmount] decimal (12,2),
		[NotApplicableAmount] decimal (12,2),
		[Remark] nvarchar(200),
		[DiscountRemark] nvarchar(200) ,
		[AdditionalRemark] nvarchar(200) ,
		[NotApplicableRemark] nvarchar(200) 
	)
	
	      INSERT INTO #TEMP_TABLE
		  SELECT
		    SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
		
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	) 
	
	--Select * from  #TEMP_TABLE

	Declare @ldata int

	CREATE TABLE #FeeSetup
	(
	FeeSetupId nvarchar(50)
	)
	
	DELETE FROM  #TEMP_TABLE WHERE ISNULL(VariableAmount,0) = 0 AND ISNULL(DiscountAmount,0) = 0 AND ISNULL(AdditionalAmount,0) = 0 AND ISNULL(NotApplicableAmount,0) = 0 

	--Select * from  #TEMP_TABLE
	INSERT INTO #FeeSetup(FeeSetupId)
	SELECT tmp.FeeSetupId 
	FROM #TEMP_TABLE tmp
	INNER JOIN  sFee.tFeeAllocation FA ON FA.SourceTypeId=tmp.SourceTypeId AND FA.SourceId =tmp.SourceId 
	AND FA.FeeSetupId=tmp.FeeSetupId 
	AND ISNULL(FA.VariableAmount,0)=ISNULL(tmp.VariableAmount,0) AND ISNULL(FA.DiscountAmount,0)=ISNULL(tmp.DiscountAmount,0)
	AND ISNULL(FA.AdditionalAmount,0)=ISNULL(tmp.AdditionalAmount,0) AND ISNULL(FA.NotApplicableAmount,0)=ISNULL(tmp.NotApplicableAmount,0) AND ISNULL(FA.Remark COLLATE SQL_Latin1_General_CP1_CI_AI,'')=ISNULL(tmp.Remark COLLATE SQL_Latin1_General_CP1_CI_AI,'')
	AND ISNULL(FA.DiscountRemark COLLATE SQL_Latin1_General_CP1_CI_AI,'')  =ISNULL(tmp.DiscountRemark COLLATE SQL_Latin1_General_CP1_CI_AI,'') AND ISNULL(FA.AdditionalRemark COLLATE SQL_Latin1_General_CP1_CI_AI,'') =ISNULL(tmp.AdditionalRemark COLLATE SQL_Latin1_General_CP1_CI_AI,'') AND ISNULL(FA.NotApplicableRemark COLLATE SQL_Latin1_General_CP1_CI_AI,'') COLLATE SQL_Latin1_General_CP1_CI_AI=ISNULL(tmp.NotApplicableRemark COLLATE SQL_Latin1_General_CP1_CI_AI,'') 
	--WHERE ISNULL(tmp.VariableAmount,0) <> 0 AND ISNULL(tmp.DiscountAmount,0) <> 0 AND ISNULL(tmp.AdditionalAmount,0) <> 0 AND ISNULL(tmp.NotApplicableAmount,0) <> 0 


	--Select * from #FeeSetup
	
	INSERT INTO sFee.tFeeAllocationHistory
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			UserId,
			LogDateTime,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
		)
	SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
			FROM #TEMP_TABLE tmp
			WHERE 
			tmp.FeeSetupId NOT IN(SELECT FeeSetupId FROM #FeeSetup)
		
	
	--Second Condition
	  INSERT INTO #TEMP_TABLE
		  SELECT
		    SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
		
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	) 

	CREATE TABLE #FeeSetup1
	(
	FeeSetupId nvarchar(50)
	)
	
	INSERT INTO #FeeSetup1(FeeSetupId)
	SELECT tmp.FeeSetupId 
	FROM #TEMP_TABLE tmp
	INNER JOIN  sFee.tFeeAllocation FA ON FA.SourceTypeId=tmp.SourceTypeId AND FA.SourceId =tmp.SourceId 
	AND FA.FeeSetupId=tmp.FeeSetupId 
	AND tmp.VariableAmount=0 AND tmp.DiscountAmount=0
	AND tmp.AdditionalAmount=0 AND tmp.NotApplicableAmount=0
	
	INSERT INTO sFee.tFeeAllocationHistory
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			UserId,
			LogDateTime,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
		)
	SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	) H
	WHERE H.FeeSetupId  IN(SELECT FeeSetupId FROM #FeeSetup1)


   SELECT 1 AS Result 
	
 
		
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION

		DROP TABLE #TEMP_TABLE
		DROP TABLE #FeeSetup
		--DROP TABLE #FeeSetup1
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pFeeAllocationHistoryGet]

	@rOrgId int,
	@rBatchId bigint,
	@rSourceId bigint,
	@rUserId bigint=0,
	@rFromDate date=NULL,
	@rToDate date=NULL,
	@rHistoryTypeId tinyint=null

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT 
	   
	  (SM.FirstName + ' '+ SM.MiddleName + ' '+ SM.LastName) AS StudentName
	  ,ISNULL(SM.Code, '') AS StudentCode
	  ,FAH.SourceId
	  ,FM.Code AS FeeName
      ,FAH.VariableAmount
      ,FAH.DiscountAmount
      ,FAH.AdditionalAmount
      ,FAH.NotApplicableAmount
      ,FAH.Remark
      ,FAH.ReferenceTypeId
      ,FAH.ReferenceSourceId
      ,FAH.UserId
	  ,U.DisplayTitle AS UserName
      ,FAH.LogDateTime
      ,FAH.DiscountRemark
      ,FAH.AdditionalRemark
      ,FAH.NotApplicableRemark
	FROM sFee.tFeeAllocationHistory FAH
	INNER JOIN sStudent.tAcademic A ON FAH.SourceId=A.Id
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
	LEFT JOIN sFee.tFeeSetup FS ON FS.Id=FAH.FeeSetupId
	INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
	INNER JOIN sSecurity.tUser U ON U.Id=FAH.UserId
  Where 
		((FAH.SourceId=@rSourceId )OR(@rSourceId=0))
		AND ((FAH.UserId=@rUserId) OR (@rUserId=0))
		AND SM.OrgId=@rOrgId
		AND A.BatchId=@rBatchId
		AND ((CAST(FAH.LogDateTime AS DATE) >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((CAST(FAH.LogDateTime AS DATE) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		AND ((ISNULL(FAH.HistoryTypeId,1) = @rHistoryTypeId) OR (ISNULL(@rHistoryTypeId, 0) = 0))
	ORDER BY FAH.LogDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pFeeAllocationRemove]
	
	@rXmlDoc nvarchar(MAX)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	DECLARE @lInterrorCode INT,
			@intDoc INT

	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
    Delete sFee.tFeeAllocation From sFee.tFeeAllocation FA 
    INNER JOIN 
    (SELECT
			SourceTypeId,
			SourceId
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		IsRecordExist bit '@IsRecordExist'
	) 
	WHERE IsRecordExist=0) Temp ON 
    FA.SourceId=Temp.SourceId AND FA.SourceTypeId=Temp.SourceTypeId 
    
	SELECT 1 AS Result
	EXEC sp_xml_removedocument @intDoc
	
COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeAllocationViewGet]
	 
		
		@rSourceId bigint ,
		@rSourceTypeId int,
		@rBatchId int
		--@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	--if (@rStudentId <> 0)
	--SELECT @rSourceId = Id FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId

SELECT 
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			--CASE WHEN FA.VariableAmount > 0 THEN FA.VariableAmount ELSE ISNULL(FS.Amount,0) END AS Amount,
			ISNULL(FS.Amount,0) AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FM.OrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId,
			FM.FeeHeadId
			
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				 
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId 
				 
			FROM sFee.tFeeSetup FS1
			 
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pFeeAsNotApplicableAdd]
	 	 
		@rClassId int=0,
		@rBatchId int=0,	 
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		--@rStatusId int=0, 
	 --   @rCode nvarchar(20)='',
	    @rStudentId bigint,
		@rAdmissionDate date
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
		DECLARE @rAcademicId bigint 
		Select @rAcademicId = Id From [sStudent].[tAcademic] WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		CREATE TABLE #TempFeeUpdate
		(
			AcademicId bigint,
			FeeSetupId int,
			PendingAmount Decimal(12,2)
		)
		INSERT INTO #TempFeeUpdate
		Select 
		SA.AcademicId,
		FS.Id,
		ISNULL(FS.Amount,0)AS PendingAmount
		from sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeSetup FS ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
		Where SA.ClassId = @rClassId AND SA.BatchId = @rBatchId AND FS.EndDate < @rAdmissionDate
		--AND Month(FS.EndDate) < Month(@rAdmissionDate) AND Year(FS.EndDate) <= Year(@rAdmissionDate) 
		AND SA.AcademicId = @rAcademicId
		AND SA.OrgId = @rOrgId AND SA.OrgGroupBatchId  = @rOrgGroupBatchId
		
	SELECT * FROM #TempFeeUpdate
	MERGE sFee.tFeeAllocation FA
	USING #TempFeeUpdate TU
	ON FA.FeeSetupId = TU.FeeSetupId AND FA.SourceTypeId = 2001 AND FA.SourceId = TU.AcademicId
		
	WHEN NOT MATCHED BY TARGET THEN
	  INSERT (SourceTypeId, SourceId, FeeSetupId,VariableAmount,DiscountAmount,AdditionalAmount,NotApplicableAmount,Remark,ReferenceTypeId,ReferenceSourceId,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,NotApplicableRemark)
	  VALUES (2001, TU.AcademicId,TU.FeeSetupId,0,0,0,TU.PendingAmount,'',0,0,0,sCommon.fGetDate(),0,sCommon.fGetDate(),'Updated NA Amount');

-- For Fee Process Added By Hemali 2025-01-30
MERGE sFee.tFeeAllocationStudent FAS
	USING #TempFeeUpdate TU ON FAS.FeeSetupId = TU.FeeSetupId AND FAS.AcademicId = TU.AcademicId
	WHEN NOT MATCHED BY TARGET
		THEN
			INSERT (
				AcademicId
				,FeeSetupId
				,FeeAmount
				,VariableAmount
				,DiscountAmount
				,AdditionalAmount
				,NotApplicableAmount
				,ToPayAmount
				,PaidAmount
				,Remark
				,CreatedUserId
				,CreatedDateTime
				,UpdatedUserId
				,UpdatedDateTime
			)
			VALUES (
				TU.AcademicId
				,TU.FeeSetupId
				,(SELECT Amount FROM sFee.tFeeSetup WHERE Id = TU.FeeSetupId)
				,0
				,0
				,0
				,TU.PendingAmount
				,((SELECT Amount FROM sFee.tFeeSetup WHERE Id = TU.FeeSetupId) - TU.PendingAmount) 
				,0
				,''
				,0
				,sCommon.fGetDate()
				,0
				,sCommon.fGetDate()
			);
-- For Fee Process Added By Hemali 2025-01-30

DROP TABLE	#TempFeeUpdate

SELECT 1 AS Result
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeCancelReceipt] 
	@rReceiptId BIGINT
	,@rRemark NVARCHAR(300) = ''
	,@rUserId BIGINT = 0
	,@rCancelStatusId INT
	,@rCancelRemark NVARCHAR(300) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		IF EXISTS (SELECT 1 FROM sFee.tReceipt WHERE Id = @rReceiptId AND IsObsolete = 0)
		BEGIN
			DECLARE @lFeeSetupId INT
				,@rCharge DECIMAL(12, 2) = 0
				,@lSourceId BIGINT
				,@lSourceTypeId INT

			SELECT @lFeeSetupId = FS.ID
				,@rCharge = RD.Amount
				,@lSourceId = R.SourceId
				,@lSourceTypeId = SourceTypeId
			FROM sFee.tReceiptDetail RD
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId
			WHERE RD.ReceiptId = @rReceiptId
				AND FH.Number = 100
				AND FS.IsVariable = 1

			IF @lFeeSetupId IS NOT NULL
			BEGIN
				UPDATE sFee.tFeeAllocation
				SET VariableAmount = VariableAmount - @rCharge
				WHERE FeeSetupId = @lFeeSetupId
					AND SourceTypeId = @lSourceTypeId
					AND SourceId = @lSourceId

				DELETE
				FROM sFee.tFeeAllocation
				WHERE FeeSetupId = @lFeeSetupId
					AND SourceTypeId = @lSourceTypeId
					AND SourceId = @lSourceId
					AND (VariableAmount - DiscountAmount - NotApplicableAmount + AdditionalAmount <= 0)
			END
		END

		DECLARE @lBatchId int, @lOrgId int
		SELECT @lSourceId = SourceId, @lBatchId = BatchId from sFee.tReceipt where Id=@rReceiptId 
		Select @lOrgId = OrgId from sSetup.tBatchMaster where Id = @lBatchId
		
		-- For Fee Process Added By Hemali 2025-01-23
		EXEC [sFee].[pDeletedRecieptFeeProcessGenerate] @lOrgId,@lBatchId,@lSourceId,@rReceiptId,@rUserId
		-- For Fee Process Added By Hemali 2025-01-23

		BEGIN
			UPDATE sFee.tReceipt
			SET IsObsolete = 1
				,Remark = @rRemark
				,CancelStatusId = @rCancelStatusId
				,CancelStatusRemark = @rCancelRemark
			WHERE Id = @rReceiptId

			UPDATE sFee.tPostDatePayment
			SET ReceiptId = 0
				,StatusId = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END
			WHERE ReceiptId = @rReceiptId

			SELECT 1 AS Result
		END

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeecancelReceiptListviewGet]
		
		@rOrgId smallint,
		@rBatchId int,
		@rAcademicId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
			
BEGIN 	
DECLARE @lcancellist nvarchar(max)	=''
	SELECT @lcancellist=@lcancellist+'<tr>
	<td align="left" scope="col">'+ convert(varchar,Isnull(R.ReceiptNumber,0)) +'</td>
	<td align="left" scope="col">'+convert(varchar,ISNULL(R.ReceiptDate,'01/01/0001'),103)+'</td>
    <td align="left" scope="col">'+Convert(varchar,ISNULL(R.ReceiptAmount,0))+'</td>
    <td align="left" scope="col">'+ISNULL(PTM.Title,'')+'</td>
    <td align="left" scope="col">'+ISNULL(R.ChequeNo,'')+'</td>
    <td align="left" scope="col">'+ISNULL(R.BankName,'')+'</td>
    <td align="left" scope="col">'+ISNULL(RBM.Title,'')+'</td>
    <td align="left" scope="col">'+convert(varchar,ISNULL(FI.InvoiceNumber,0))+'</td>
     <td align="left" scope="col">'+convert(varchar,ISNULL(R.Remark,''))+'</td>
    <tr>'
  FROM 
		sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic A
			ON A.AcademicId=R.SourceId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
		ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId
WHERE 
	    R.SourceTypeId=2001 AND R.IsObsolete=1
		AND A.OrgId=@rOrgId AND R.BatchId=@rBatchId
		AND A.AcademicId=@rAcademicId
	   ORDER BY R.ReceiptNumber DESC
	   
		SELECT ISNULL(@lcancellist,'') AS cancellist
END

--
--    
--    
--    
--    
--    
--    

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeCollectionConsolidatedDashboardGet]

     @rOrgGroupId smallint=0,
     @rTypeId int=0,
     @rType nvarchar(20)='',
     @rCommonOrgGroupBatchId int=0,
	 @rFromDate date =null,
	 @rToDate date = null,
	 @rReceiptBookId int =0,
	 @rUserId bigint=0,
	 @rOrgId int =0,
	 @rCommonFeeId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN

	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('TypeId: ' + CAST(@rTypeId AS nvarchar(100)), 
	'@rOrgGroupId = ' + CAST(@rOrgGroupId AS nvarchar(100)) + ', @rTypeId = ' + CAST(@rTypeId AS nvarchar(100)) 
	+ ', @rType = ' +  CAST(@rType AS nvarchar(100))  + ', @rCommonOrgGroupBatchId = ' +  CAST(@rCommonOrgGroupBatchId AS nvarchar(100))
	+ ', @rFromDate = ' +  CAST(@rFromDate AS nvarchar(100))  + ', @rToDate = ' +  CAST(@rToDate AS nvarchar(100))
	+ ', @rReceiptBookId = ' +  CAST(@rReceiptBookId AS nvarchar(100))  + ', @rUserId = ' +  CAST(@rUserId AS nvarchar(100))
	+ ', @rOrgId = ' +  CAST(@rOrgId AS nvarchar(100))  + ', @rCommonFeeId = ' +  CAST(@rCommonFeeId AS nvarchar(100)), 
	'@rType: ' + CAST(@rType AS nvarchar(100)), 
	'', 
	GETDATE(), 
	'[sFee].[pFeeCollectionConsolidatedDashboardGet]')
END

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;


WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

--If @rFromDate= NULL Set @rFromDate = ''
--  If @rToDate =NULL Set @rToDate = ''
 DECLARE @cols NVARCHAR(MAX),@query  NVARCHAR(MAX),@cols1 NVARCHAR(MAX), @cols2 NVARCHAR(MAX); 
	---Fee Collection Wise  
			IF(@rTypeId=1)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')					

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' 
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')	

					set @query = 'SELECT OrgGroupId,OrgGroupName,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  OMM.Id AS OrgGroupId ,OMM.Title AS OrgGroupName,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN  sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1 
					GROUP BY OMM.Title,OMM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY OrgGroupId,OrgGroupName  ORDER BY OrgGroupId'
					--print(@query)
					execute(@query)
				END
			ELSE IF( @rTypeId=11)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' 
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT ReceiptBookId,ReceiptBook,'+@cols2+' AS Total, ' + @cols1 + ' from 
					(
					SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1
					GROUP BY RBM.Title,RBM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY ReceiptBookId,ReceiptBook ORDER BY ReceiptBookId'					
					print(@query)
					execute(@query)
				 END
			ELSE IF( @rTypeId=12)
				BEGIN
						SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT UserId,UserName,SourceTypeId,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  U.Id As UserId,U.DisplayTitle AS UserName,ISNULL(U.SourceTypeId,0) AS SourceTypeId,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					LEFT JOIN sSecurity.tUser U WITH (NOLOCK) ON U.Id=R.CreatedUserId
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND BM.IsInContext = 1
					GROUP BY U.id,U.DisplayTitle,PTM.Title,U.SourceTypeId
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY UserId,UserName,SourceTypeId ORDER BY UserId'
					print(@query)
					execute(@query)
				END
			ELSE IF (@rTypeId=13)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT OrgGroupId,OrgGroupName,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  OM.Id AS OrgGroupId ,OM.DisplayTitle AS OrgGroupName,SUM(R.ReceiptAmount) AS Total,PTM.Title AS PayTypeName, COALESCE(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND BM.IsInContext = 1
					GROUP BY OM.DisplayTitle,OM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY OrgGroupId,OrgGroupName ORDER BY OrgGroupId '
					print(@query)
					execute(@query)
				END
			ELSE IF (@rTypeId=14)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT FeeHeadId,FeeHead,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS total,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
					AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
					AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
					AND BM.IsInContext = 1
					GROUP BY FHM.Id,FHM.Title,PTM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY FeeHeadId,FeeHead ORDER BY FeeHeadId'
					
					execute(@query)
				END
			ELSE IF (@rTypeId=15)
				BEGIN
					SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols1 = STUFF((SELECT ', SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) ' + QUOTENAME(PTM.Title) 
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					--INNER JOIN  sFee.tReceipt R  ON PTM.Id=R.PayTypeId
					--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					SET @cols2 = STUFF((SELECT '+ SUM(ISNULL(' + QUOTENAME(PTM.Title) + ', ''0'')) '
					FROM sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK)
					GROUP BY PTM.Title
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')

					set @query = 'SELECT FeeHeadId,FeeMaster,' + @cols2 + ' AS Total, ' + @cols1 + ' from 
					(
					SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS total,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R WITH (NOLOCK)
						INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
						INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
						INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
						INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = RD.FeeSetupId
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
						INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId
						INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
						WHERE  COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+' AND R.SourceTypeId = 2001 
						AND((OMM.Id='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0))
						AND (( convert(DATE, R.ReceiptDate,102) >= '''+CONVERT(nvarchar(20),@rFromDate)+''') OR ('''+CONVERT(nvarchar(20),@rFromDate)+'''=''1900-01-01''))
						AND (( convert(DATE, R.ReceiptDate,102) <= '''+CONVERT(nvarchar(20),@rToDate)+''') OR ('''+CONVERT(nvarchar(20),@rToDate)+'''=''1900-01-01''))
						AND BM.IsInContext = 1
						GROUP BY FM.Id,FM.Title,PTM.Id,PTM.Title
					) x
					pivot 
					(
					Sum(ReceiptAmount) 
					for PayTypeName in (' + @cols + ')
					) p GROUP BY FeeHeadId,FeeMaster  ORDER BY FeeHeadId'
					execute(@query)
				END

			ELSE IF(@rTypeId =21)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((R.ReceiptBookId =@rReceiptBookId )OR(@rReceiptBookId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1
					ORDER BY R.ReceiptNumber -- Added By Foram - 02/08/2023 - Mantis Issue: 0026499
				END
				ELSE
				BEGIN
				SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sFee.tApplicablePayType PTM WITH (NOLOCK) ON PTM.PayTypeId=R.PayTypeId AND PTM.OrgGroupId = OM.OrgGroupId -- OrgGroupId add for mantis : 0040346
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId					
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((R.ReceiptBookId =@rReceiptBookId )OR(@rReceiptBookId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND R.IsObsolete = 0
					And ISNULL(OMM.IsObsolete,0) = 0
					AND BM.IsInContext = 1
					ORDER BY R.ReceiptNumber -- Added By Foram - 02/08/2023 - Mantis Issue: 0026499
				END
				END
			ELSE IF(@rTypeId =22)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WITH (NOLOCK) WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN sSecurity.tUser U WITH (NOLOCK) ON U.Id=R.CreatedUserId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					--AND ((U.Id =@rUserId )OR(@rUserId=0))
					AND ((U.Id = CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END)OR(CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END=0))
					AND ((U.SourceTypeId = CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END)OR(CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sFee.tApplicablePayType PTM WITH (NOLOCK) ON PTM.PayTypeId=R.PayTypeId AND PTM.OrgGroupId = OM.OrgGroupId -- OrgGroupId add for mantis : 0040346
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId					
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN sSecurity.tUser U WITH (NOLOCK) ON U.Id=R.CreatedUserId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					--AND ((U.Id =@rUserId )OR(@rUserId=0))
					AND ((U.Id = CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END)OR(CASE WHEN @rUserId = 2003 THEN 0 ELSE @rUserId END=0))
					AND ((U.SourceTypeId = CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END)OR(CASE WHEN @rUserId = 2003 THEN 2003 ELSE 0 END=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				END
			ELSE IF(@rTypeId =23)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WITH (NOLOCK) WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((OM.Id =@rOrgId )OR(@rOrgId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,R.ReceiptAmount AS Amount
					FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sFee.tApplicablePayType PTM WITH (NOLOCK) ON PTM.PayTypeId=R.PayTypeId AND PTM.OrgGroupId = OM.OrgGroupId -- OrgGroupId add for mantis : 0040346
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId					
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((OM.Id =@rOrgId )OR(@rOrgId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
				END
				END
			ELSE IF(@rTypeId =24)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WITH (NOLOCK) WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FHM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name 
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sFee.tApplicablePayType PTM WITH (NOLOCK) ON PTM.PayTypeId=R.PayTypeId AND PTM.OrgGroupId = OM.OrgGroupId -- OrgGroupId add for mantis : 0040346
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FHM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name
				END
				END
			ELSE IF(@rTypeId =25)
				BEGIN
				IF NOT EXISTS(SELECT 1 FROM sFee.tApplicablePayType WITH (NOLOCK) WHERE OrgGroupId = @rOrgGroupId)
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId
					AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name 
				END
				ELSE
				BEGIN
					SELECT  R.ReceiptNumber AS ReceiptNumber,R.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name,SUM(RD.Amount) AS Amount
					FROM sFee.tReceipt R WITH (NOLOCK)
					INNER JOIN sStudent.vStudentAcademic SA WITH (NOLOCK) ON SA.AcademicId=R.SourceId 
					INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SA.OrgId
					INNER JOIN sFee.tApplicablePayType PTM WITH (NOLOCK) ON PTM.PayTypeId=R.PayTypeId AND PTM.OrgGroupId = OM.OrgGroupId -- OrgGroupId add for mantis : 0040346
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = RD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId					
					INNER JOIN sSetup.tOrgGroupMaster OMM WITH (NOLOCK) ON OMM.Id = OM.OrgGroupId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=SA.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
					WHERE  
					COGBM.Id=@rCommonOrgGroupBatchId
					AND R.SourceTypeId = 2001 					 
					AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
					AND ((FM.Id =@rCommonFeeId)OR(@rCommonFeeId=0))
					AND (( convert(DATE, R.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
					AND (( convert(DATE, R.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
					AND BM.IsInContext = 1
					GROUP BY  R.ReceiptNumber,R.ReceiptDate,SA.Code, SA.Name
				END
				END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeeCollectionDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rDivisionId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
  SELECT
	(
	SELECT ISNULL(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	WHERE R.SourceTypeId = 2001
    AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
    AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS DailyAmount,
	
		(
	SELECT ISNULL(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	WHERE R.SourceTypeId = 2001
    AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
    AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS YesterdayCount,
	
	
	(
	SELECT ISNULL(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	WHERE R.SourceTypeId = 2001
    AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
	AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS WeeklyAmount,
	
	(
	SELECT ISNULL(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	WHERE R.SourceTypeId = 2001
    AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
	AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS MonthlyAmount
  END
  
  IF(@rType='ReceiptBook')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		GROUP BY RBM.Id,RBM.Title
	END
	IF(@rDay=1)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		GROUP BY RBM.Id,RBM.Title
	END
	IF(@rDay=7)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
		AND(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		GROUP BY RBM.Id,RBM.Title
	END
	IF(@rDay=30)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(R.ReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		GROUP BY RBM.Id,RBM.Title
	END
  END
  
  IF(@rType='Division')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT SA.DivisionId,SA.ClassName +' - '+ SA.DivisionName AS DivisionClass,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) =  DATEADD(day, -1, convert(date, GETDATE()))
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY SA.DivisionId,SA.ClassName,SA.DivisionName
	END
	IF(@rDay=1)
	BEGIN
		SELECT SA.DivisionId,SA.ClassName +' - '+ SA.DivisionName AS DivisionClass,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY SA.DivisionId,SA.ClassName,SA.DivisionName
	END
	IF(@rDay=7)
	BEGIN
		SELECT SA.DivisionId,SA.ClassName +' - '+ SA.DivisionName AS DivisionClass,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY SA.DivisionId,SA.ClassName,SA.DivisionName
	END
	IF(@rDay=30)
	BEGIN
		SELECT SA.DivisionId,SA.ClassName +' - '+ SA.DivisionName AS DivisionClass,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY SA.DivisionId,SA.ClassName,SA.DivisionName
	END
  END
  
  IF(@rType='Student')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT SA.Code,SA.Name,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND SA.DivisionId = @rDivisionId
		GROUP BY SA.Code,SA.Name
	END
	IF(@rDay=1)
	BEGIN
		SELECT SA.Code,SA.Name,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND SA.DivisionId = @rDivisionId
		GROUP BY SA.Code,SA.Name
	END
	IF(@rDay=7)
	BEGIN
		SELECT SA.Code,SA.Name,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND SA.DivisionId = @rDivisionId
		GROUP BY SA.Code,SA.Name
	END
	IF(@rDay=30)
	BEGIN
		SELECT SA.Code,SA.Name,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND SA.DivisionId = @rDivisionId
		GROUP BY SA.Code,SA.Name
	END
END
  IF(@rType='OrgGroup')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT SA.OrgId,SA.OrganizationName,SUM(R.ReceiptAmount) AS YesterdayCount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		--AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		--AND (R.ReceiptBookId = @rReceiptBookId) 
		--AND SA.DivisionId = @rDivisionId
		GROUP BY SA.OrgId,SA.OrganizationName
	END
	IF(@rDay=1)
	BEGIN
		SELECT SA.OrgId,SA.OrganizationName,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		--AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		--AND (R.ReceiptBookId = @rReceiptBookId) 
		--AND SA.DivisionId = @rDivisionId
		GROUP BY SA.OrgId,SA.OrganizationName
	END
	IF(@rDay=7)
	BEGIN
		SELECT SA.OrgId,SA.OrganizationName,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		--AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		--AND (R.ReceiptBookId = @rReceiptBookId) 
		--AND SA.DivisionId = @rDivisionId
		GROUP BY SA.OrgId,SA.OrganizationName
	END
	IF(@rDay=30)
	BEGIN
		SELECT SA.OrgId,SA.OrganizationName,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)
		--AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		--AND (R.ReceiptBookId = @rReceiptBookId) 
		--AND SA.DivisionId = @rDivisionId
		GROUP BY SA.OrgId,SA.OrganizationName
	END
	END
  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeCollectionDashBoardNewGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rFeeHeadId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
  SELECT
  (
	SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	WHERE R.SourceTypeId = 2001
    AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
	AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS YesterdayAmount,
	(
	SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	WHERE R.SourceTypeId = 2001
    AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
    AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS DailyAmount,
	
	(
	SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	WHERE R.SourceTypeId = 2001
    AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
	AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS MonthlyAmount,
	
	(
	SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	WHERE R.SourceTypeId = 2001
    AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
	AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS YearlyAmount
  END
  
  IF(@rType='ReceiptBook')
  BEGIN
  IF(@rDay=-1)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		GROUP BY RBM.Id,RBM.Title
	END
	IF(@rDay=1)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		GROUP BY RBM.Id,RBM.Title
	END
	IF(@rDay=30)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		GROUP BY RBM.Id,RBM.Title
	END
	IF(@rDay=365)
	BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		GROUP BY RBM.Id,RBM.Title
	END
  END
  
  IF(@rType='FeeHead')
  BEGIN
  IF(@rDay=-1)
	BEGIN
	SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount  
	FROM sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
	IF(@rDay=1)
	BEGIN
	SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount  
	FROM sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
	IF(@rDay=30)
	BEGIN
		SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
	IF(@rDay=365)
	BEGIN
		SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
	INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
  END
  
  IF(@rType='FeeMaster')
  BEGIN
  IF(@rDay=-1)
	BEGIN
	
		SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
	INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
	IF(@rDay=1)
	BEGIN
	
		SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
	INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
				AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
	IF(@rDay=30)
	BEGIN
		
		SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
	IF(@rDay=365)
	BEGIN
		
		SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
END
 
  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeColumnNameGet]

AS
SET NOCOUNT ON

BEGIN
		Select COLUMN_NAME AS ColumnName from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sFee' AND TABLE_NAME='vFeeColumnName'
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeConsolidateDashBoardGet]
		
	@rType nvarchar(100)='',
	@rCount int =0 ,
	@rDivisionId int  =0,
	@rClassId int  =0,
	@rOrgId int  =0,
	@rOrgGroupId int=0,
	@rOrgGroupBatchId int  =0,
	@rCollectionGroupId int =0,
	@rReceiptBookId int =0,
	@rDays int=0,
	@rCommonOrgGroupBatchId int=0,
	@rFromDate varchar(10)='',
	@rToDate varchar(10)='',
	@rMonth int =0,
	@rSyncDate int =0,
	@rUserId bigint = 0,
	@rOsTypeId int = 0,
	@rPagePath nvarchar(500) = ''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN

	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('Type: ' + CAST(@rType AS nvarchar(100)), 
	'@rCount = ' + CAST(@rCount AS nvarchar(100)) + ', @rDivisionId = ' + CAST(@rDivisionId AS nvarchar(100)) 
	+ ', @rClassId = ' +  CAST(@rClassId AS nvarchar(100))  + ', @rOrgId = ' +  CAST(@rOrgId AS nvarchar(100))
	+ ', @rOrgGroupId = ' +  CAST(@rOrgGroupId AS nvarchar(100))  + ', @rOrgGroupBatchId = ' +  CAST(@rOrgGroupBatchId AS nvarchar(100))
	+ ', @rCollectionGroupId = ' +  CAST(@rCollectionGroupId AS nvarchar(100))  + ', @rReceiptBookId = ' +  CAST(@rReceiptBookId AS nvarchar(100))
	+ ', @rDays = ' +  CAST(@rDays AS nvarchar(100))  + ', @rCommonOrgGroupBatchId = ' +  CAST(@rCommonOrgGroupBatchId AS nvarchar(100))
	+ ', @rFromDate = ' +  CAST(@rFromDate AS nvarchar(100))  + ', @rToDate = ' +  CAST(@rToDate AS nvarchar(100))
	+ ', @rMonth = ' +  CAST(@rMonth AS nvarchar(100))  + ', @rSyncDate = ' +  CAST(@rSyncDate AS nvarchar(100)), 
	'@rUserId = ' + CAST(@rUserId AS nvarchar(100)) + ', @rOsTypeId = ' +  CAST(@rOsTypeId AS nvarchar(100)),
	'@rPagePath = ' + CAST(@rPagePath AS nvarchar(500)), 
	GETDATE(), 
	'[sFee].[pFeeConsolidateDashBoardGet]')
END

--Update sSetup.tOrgGroupMaster Set IsObsolete=0 WHERE IsObsolete IS NULL 

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;

IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

IF(@rType ='FeeStatusOrganization')
	BEGIN 
	IF(@rSyncDate =1)
		BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				CREATE TABLE #tempOrganizationSync(
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
				INSERT INTO #tempOrganizationSync
					SELECT 
						SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA  WITH (NOLOCK)
						INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
						INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.ID = SA.OrgId
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  --And ISNULL(O.IsObsolete,0) = 0
						  And O.IsObsolete <> 1
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
						  AND FAS.PaidAmount >= 0		-- Added for Mantis : 0039379 By Dhananjay
						  AND FAS.ToPayAmount >= 0.00	-- Added for Mantis : 0039379 By Dhananjay
						  --AND SM.StatusId=1
						  -- IsInContext
						  AND BM.IsInContext = 1
					GROUP BY  o.Id,o.Title

					IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId)
						BEGIN							
						IF(@rOrgGroupId !=0)
							INSERT INTO sFee.tTempOrgGroupFeeStatus
							SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
							ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
							SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
					ELSE
						BEGIN						
						INSERT INTO sFee.tTempOrgGroupFeeStatus
							SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
							ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
							SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
				
				DROP TABLE #tempOrganizationSync			
		END
	ELSE
		BEGIN

			IF  Exists(select 1 from sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) where CONVERT(date,UpdatedDateTime) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))) 
			BEGIN
	
				SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempOrganization(
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
			INSERT INTO #tempOrganization
					SELECT 
						SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA WITH (NOLOCK)
						INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
						INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId -- Added AdmissionCategoryId Condition on join for Mantis : 0039379 By Dhananjay
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.ID = SA.OrgId
						
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  --And ISNULL(O.IsObsolete,0) = 0
						  And O.IsObsolete <> 1
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
						  AND FAS.PaidAmount >= 0		-- Added for Mantis : 0039379 By Dhananjay
						  AND FAS.ToPayAmount >= 0.00	-- Added for Mantis : 0039379 By Dhananjay
						  -- IsInContext
						  AND BM.IsInContext = 1
					GROUP BY  o.Id,o.Title

						
				IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId)
					BEGIN
						
					IF(@rOrgGroupId !=0)
						INSERT INTO sFee.tTempOrgGroupFeeStatus
						SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
						SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END
				ELSE
					BEGIN
					
					INSERT INTO sFee.tTempOrgGroupFeeStatus
						SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
						SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END 
					
				DROP TABLE #tempOrganization
			END
		END
	END
ELSE IF(@rType = 'FeeStatusPaid&UnpaidDetilsClassWise')
	BEGIN 
	IF(@rCount = 1)
	BEGIN

	CREATE TABLE #tempPaidDetailsClassWise(
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId int,
	ClassName nvarchar(50),
	PaidAmount DECIMAL(12,0),
	StudentCount int
	,ClassOrderIndex INT,--add for mantis : 0042058
	DivisionOrder INT --add for mantis : 0042058
	)
  
	INSERT INTO #tempPaidDetailsClassWise
	SELECT 
		 ISNULL(O.Id,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 COUNT(Distinct(SA.AcademicId)) as StudentCount
		 ,SA.ClassOrderIndex,--add for mantis : 0042058
		SA.DivisionOrder --add for mantis : 0042058
	FROM 		
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId -- Added AdmissionCategoryId Condition on join for Mantis : 0039379 By Dhananjay
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND
		((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0 
		And O.IsObsolete <> 1
		AND FAS.PaidAmount >= 0		-- Added = for Mantis : 0039379 By Dhananjay
		AND FAS.ToPayAmount >= 0.00	-- Added for Mantis : 0039379 By Dhananjay
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName
	 ,SA.ClassOrderIndex,SA.DivisionOrder -- class division order index add for mantis : 0042058
	ORDER BY O.Id
		,SA.ClassOrderIndex
		,SA.DivisionOrder --add for mantis : 0042058

		SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount,T.StudentCount
		,T.ClassOrderIndex
		,T.DivisionOrder
		FROM #tempPaidDetailsClassWise T
		WHERE T.PaidAmount > 0
		ORDER BY T.OrgGroupId
			,T.ClassOrderIndex
			,T.DivisionOrder --add for mantis : 0042058
			 
	DROP TABLE #tempPaidDetailsClassWise
 
	END
	ELSE IF(@rCount = 2)
	BEGIN

	CREATE TABLE #tempPendingDetailsClassWise(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId int,
	ClassName nvarchar(50),
	PendingAmount DECIMAL(12,0) 
	,ClassOrderIndex INT,--add for mantis : 0042058
	DivisionOrder INT --add for mantis : 0042058
	)
 
	INSERT INTO #tempPendingDetailsClassWise
	SELECT 
		 ISNULL(SA.AcademicId,0) AS AcademicId,
		 ISNULL(O.Id,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
		 ,SA.ClassOrderIndex,--add for mantis : 0042058
		 SA.DivisionOrder --add for mantis : 0042058
	FROM 		
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--nd ISNULL(O.IsObsolete,0) = 0 
		And O.IsObsolete <> 1
		AND FAS.ToPayAmount >= 0.00 --AND SA.StatusId=1 -- Added = for Mantis : 0039379 By Dhananjay
		AND FAS.PaidAmount >= 0		-- Added for Mantis : 0039379 By Dhananjay
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName,SA.AcademicId,SA.ClassOrderIndex,SA.DivisionOrder --add for mantis : 0042058

		SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS UnPaidAmount,COUNT(T.PendingAmount)AS StudentCount
		,T.ClassOrderIndex,T.DivisionOrder --add for mantis : 0042058
		FROM #tempPendingDetailsClassWise T
		--WHERE T.PendingAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.ClassId,T.OrgGroupName,T.ClassOrderIndex,T.DivisionOrder
		HAVING ISNULL(SUM(T.PendingAmount),0) > 0
		ORDER BY T.ClassOrderIndex,T.DivisionOrder -- remove classid add for mantis : 0042058
	 
	DROP TABLE #tempPendingDetailsClassWise
 
	END
	END
ELSE IF(@rType ='FeeStatusPaid&UnpaidDetils')
BEGIN 

	IF(@rCount = 1)
	BEGIN
		CREATE TABLE #tempPaidDetails(
			SourceId bigint,
			OrgGroupId int,
			ClassName nvarchar(50),
			DivisionId int,
			DivisionName nvarchar(50),
			Code nvarchar(20),
			Name nvarchar(200),
			ParentContactNo nvarchar(50),
			PaidAmount DECIMAL(12,0),
			ClassOrderIndex int,
			DivisionOrder int,
			RollNo int
		)
		INSERT INTO #tempPaidDetails
		SELECT 
				ISNULL(SA.AcademicId,0) AS SourceId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As Code,
				ISNULL(SA.Name,'') AS Name,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
				 SA.ClassOrderIndex,  
				 SA.DivisionOrder,
				 SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA WITH (NOLOCK)
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
		 WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				--And ISNULL(O.IsObsolete,0) = 0
				And O.IsObsolete <> 1
				AND FAS.PaidAmount > 0
				-- IsInContext
				AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FAS.PaidAmount,0)) >0
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo

		SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
			T.ParentContactNo AS ParentContactNo,T.PaidAmount AS PaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
		FROM #tempPaidDetails T
		WHERE T.PaidAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PaidAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
		HAVING T.PaidAmount > 0
		ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END
	ELSE IF(@rCount = 2)
	BEGIN
		CREATE TABLE #tempPendingDetails(
			SourceId bigint,
			OrgGroupId int,
			ClassName nvarchar(50),
			DivisionId int,
			DivisionName nvarchar(50),
			Code nvarchar(20),
			Name nvarchar(200),
			ParentContactNo nvarchar(50),
			PendingAmount DECIMAL(12,0),
			ClassOrderIndex int,
			DivisionOrder int,
			RollNo int
		)
		INSERT INTO #tempPendingDetails
		SELECT 
				ISNULL(SA.AcademicId,0) AS SourceId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As Code,
				ISNULL(SA.Name,'') AS Name,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
				SA.ClassOrderIndex,  
				SA.DivisionOrder,
				SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA WITH (NOLOCK)
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
			    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
		 WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				--And ISNULL(O.IsObsolete,0) = 0 
				And O.IsObsolete <> 1
				AND FAS.ToPayAmount > 0.00 --AND SA.StatusId=1
				-- IsInContext
				AND BM.IsInContext = 1
				
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo

		SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
			T.ParentContactNo AS ParentContactNo,T.PendingAmount AS UnPaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
		FROM #tempPendingDetails T
		WHERE T.PendingAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PendingAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
		HAVING T.PendingAmount > 0
		ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END
END

ELSE IF(@rType ='FeeStatusTotalHeadwiseAmount')
BEGIN 
	IF(@rSyncDate =1)
		BEGIN
		DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempTotalPaidDetailsSync (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrderIndex int
			)
			 
			INSERT INTO #tempTotalPaidDetailsSync
			SELECT 
				ISNULL(FHM.Id,0) AS FeeHeadId,
				ISNULL(FHM.code,'') AS FeeHeadName,
				ISNULL(CGM.Id,0) AS CollectionGroupId,
				ISNULL(CGM.Code,'') AS CollectionGroup,
				ISNULL(RBM.Id,'')  AS ReceiptBookId,
				ISNULL(RBM.Title,'')  AS ReceiptTitle,
				SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
				SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
				FHM.OrderIndex
			FROM 
				sStudent.tAcademic SA WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 -- IsInContext
			AND FAS.PaidAmount >= 0	-- Added for Mantis : 0039379 By Hemali
			AND FAS.ToPayAmount >= 0.00  -- Added for Mantis : 0039379 By Hemali
				AND BM.IsInContext = 1
			GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

			INSERT INTO sFee.tTempTotalPaidDetails
			SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
						ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
						T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
						ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
						T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE() from #tempTotalPaidDetailsSync T
			GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
			ORDER BY T.OrderIndex

			SELECT * FROM sFee.tTempTotalPaidDetails WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))		

		--New Temp Table Create-------------
			CREATE TABLE #tempTotalStudentCountSync (
			AcademicId bigint,
			CollectionGroupId bigint,
			CollectionGroup nvarchar(200),
			RecepitTitle nvarchar(100),
			ReceiptBookId bigint,
			EndDate date,
			PaidAmount DECIMAL(12,0),
			PendingAmount DECIMAL(12,0)
			)
	
			--Test
			--Added for query optimization - TRIS Loading issue - 10 Jan 2025
			DECLARE @lTopReceiptDate datetime = (SELECT TOP 1 ReceiptDate 
					FROM sFee.tReceipt R  WITH (NOLOCK)
					INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					ORDER BY ReceiptDate DESC)
			--Added for query optimization - TRIS Loading issue - 10 Jan 2025

			INSERT INTO #tempTotalStudentCountSync
			SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					--(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					--INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
					--INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					--INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					--WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					-- ORDER BY ReceiptDate DESC) EndDate,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					@lTopReceiptDate AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
		        INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId   -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 AND COGBM.Id=@rCommonOrgGroupBatchId 
			 -- IsInContext
				AND FAS.PaidAmount >= 0	  -- Added for Mantis : 0039379 By Hemali
				AND FAS.ToPayAmount >= 0.00  -- Added for Mantis : 0039379 By Hemali
				AND BM.IsInContext = 1
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
					ISNULL(E.EndDate,'1900-01-01')AS EndDate,
					--E.EndDate AS EndDate,
					SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,
					@rCommonOrgGroupBatchId,GETDATE() 
			FROM (
				SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
						ISNULL(T.CollectionGroup,'') As CollectionGroup,
						ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
						ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,
						CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate 
						from #tempTotalStudentCountSync T
						LEFT JOIN 
						(
							SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCountSync --CollectionGroupId,CollectionGroup,
							WHERE PendingAmount  = 0
							GROUP BY CollectionGroupId,ReceiptBookId
						) A ON A.CollectionGroupId = T.CollectionGroupId
						LEFT JOIN 
						(
							SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCountSync
							WHERE PendingAmount !=0
							GROUP BY CollectionGroupId,ReceiptBookId
						)B ON B.CollectionGroupId = T.CollectionGroupId 
						GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
						)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
		
		 SELECT * FROM sFee.tTempTotalStudentCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	


		-------------Create a New Temp Table For Pending date-----------------
			CREATE TABLE #tempPendingCountSync(
			AcademicId bigint,
			CollectionGroupId bigint,
			CollectionGroup nvarchar(200),
			RecepitTitle nvarchar(100),
			ReceiptBookId bigint,
			EndDate date,
			PaidAmount DECIMAL(12,0),
			PendingAmount DECIMAL(12,0)
			)
	 
			DECLARE @lLastReceiptDate datetime
			SET @lLastReceiptDate = (SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R WITH (NOLOCK)
							INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
							INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
							INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=R.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id 
							INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  
							(LEFT(R.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
							AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
							--And ISNULL(O.IsObsolete,0) = 0
							And O.IsObsolete <> 1
							-- IsInContext
						AND BM.IsInContext = 1
					ORDER BY ReceiptDate DESC)

			INSERT INTO #tempPendingCountSync
			SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					@lLastReceiptDate AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId  -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			 -- IsInContext
				AND FAS.PaidAmount >= 0	  -- Added for Mantis : 0039379 By Hemali
				AND FAS.ToPayAmount >= 0.00  -- Added for Mantis : 0039379 By Hemali
				AND BM.IsInContext = 1
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate

			INSERT INTO sFee.tTempPendingCount
			SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
						T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
			FROM   #tempPendingCountSync T
			WHERE PendingAmount !=0
			 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
			GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup

			SELECT * FROM sFee.tTempPendingCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	 
			DROP TABLE #tempTotalPaidDetailsSync
			DROP TABLE #tempTotalStudentCountSync
			DROP TABLE #tempPendingCountSync

		END
	ELSE
		BEGIN
		IF  Exists(select 1 from sFee.tTempTotalPaidDetails WITH (NOLOCK) where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sFee.tTempTotalPaidDetails WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempTotalStudentCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempPendingCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN

			DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempTotalPaidDetails (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrderIndex int
				)
			
				INSERT INTO #tempTotalPaidDetails
				SELECT 
					ISNULL(FHM.Id,0) AS FeeHeadId,
					ISNULL(FHM.code,'') AS FeeHeadName,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Id,'')  AS ReceiptBookId,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
					FHM.OrderIndex
				FROM 
					sStudent.tAcademic SA WITH (NOLOCK)
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId   -- Added for Mantis : 0039379 By Hemali
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				 --And ISNULL(O.IsObsolete,0) = 0
				 And O.IsObsolete <> 1
				 -- IsInContext

				 -- Added for Mantis : 0039379 By Hemali
				AND FAS.PaidAmount >= 0	  
				AND FAS.ToPayAmount >= 0.00
				AND BM.IsInContext = 1
				GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

			INSERT INTO sFee.tTempTotalPaidDetails
				SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
				ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
				ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
				T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE()from #tempTotalPaidDetails T
				GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
				ORDER BY T.OrderIndex

			SELECT * FROM sFee.tTempTotalPaidDetails WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	

					--New Temp Table Create-------------
				CREATE TABLE #tempTotalStudentCount (
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0)
				)
	
				--Test
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025
				DECLARE @lTopReceiptDate1 datetime = (SELECT TOP 1 ReceiptDate 
					FROM sFee.tReceipt R WITH (NOLOCK) 
					INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					ORDER BY ReceiptDate DESC)
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025
	
				INSERT INTO #tempTotalStudentCount
				SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					--(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					--INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
					--INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					--INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					--WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					-- ORDER BY ReceiptDate DESC) EndDate,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					@lTopReceiptDate1 AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
				FROM 
					sStudent.tAcademic SA WITH (NOLOCK)
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId  -- Added for Mantis : 0039379 By Hemali
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 --And ISNULL(O.IsObsolete,0) = 0
				 And O.IsObsolete <> 1
				 AND COGBM.Id=@rCommonOrgGroupBatchId 
				 -- IsInContext
				 -- Added for Mantis : 0039379 By Hemali
				AND FAS.PaidAmount >= 0	
				AND FAS.ToPayAmount >= 0.00
				AND BM.IsInContext = 1
				GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,
			E.ReceiptCollection AS ReceiptCollection,
					ISNULL(E.EndDate,'1900-01-01')AS EndDate,
					--E.EndDate AS EndDate,
					SUM(E.TotalStudentCount) AS TotalStudentCount,
					SUM(E.PaidStudentCount) AS PaidStudentCount,
					SUM(E.PendingStudentCount) AS PendingStudentCount,
					@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
			ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,
				CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCount T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCount --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCount
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
				 
				 SELECT * FROM sFee.tTempTotalStudentCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

					-------------Create a New Temp Table For Pending date-----------------
				CREATE TABLE #tempPendingCount(
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0)
				)
				
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025
				DECLARE @lTopReceiptDate2 datetime = (SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id 
					INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					  WHERE  
							(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
							AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
							And O.IsObsolete <> 1
						AND BM.IsInContext = 1
					  ORDER BY ReceiptDate DESC)
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025

				INSERT INTO #tempPendingCount
				SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					--(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					--INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
					--INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					--INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 
					--INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					--  WHERE  
					--		(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
					--		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					--		--And ISNULL(O.IsObsolete,0) = 0
					--		And O.IsObsolete <> 1
					--		-- IsInContext
					--	AND BM.IsInContext = 1
					--  ORDER BY ReceiptDate DESC) EndDate,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					@lTopReceiptDate2 AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId  -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			 -- IsInContext

			 -- Added for Mantis : 0039379 By Hemali
			AND FAS.PaidAmount >= 0	
			AND FAS.ToPayAmount >= 0.00
				AND BM.IsInContext = 1
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
		
		INSERT INTO sFee.tTempPendingCount
				SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
				FROM   #tempPendingCount T
				WHERE PendingAmount !=0
				 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
				 GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup
		SELECT * FROM sFee.tTempPendingCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	
				DROP TABLE #tempTotalPaidDetails
				DROP TABLE #tempTotalStudentCount
				DROP TABLE #tempPendingCount
			END
		END
END

ELSE IF(@rType ='FeeStatusPaidSubPartAmount')
BEGIN 
	CREATE TABLE #tempPaidSubPart (
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId bigint,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	ClassOrderIndex int,
	StudentCount int
	,DivisionOrder int
	)
    
IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPart
	SELECT 
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 ISNULL(CGM.Id,0) AS CollectionGroupId,
		 ISNULL(CGM.Code,'') AS CollectionGroup,
		 ISNULL(RBM.Title,'')  AS ReceiptTitle,
		 ISNULL(RBM.Id,0) As ReceiptBookId,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,
		 COUNT(Distinct(FAS.AcademicId)) as StudentCount
		 ,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	    	
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		AND FAS.PaidAmount > 0
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,SA.DivisionOrder
	HAVING ISNULL(SUM(FAS.PaidAmount),0) > 0
	ORDER BY SA.ClassOrderIndex,SA.DivisionOrder --add for mantis : 0042058

		select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount, T.StudentCount AS StudentCount,
			ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,
			'' as MonthName ,T.ClassOrderIndex,T.DivisionOrder --add for mantis : 0042058
		from #tempPaidSubPart T
		 

	END 
	ELSE 
	BEGIN
	INSERT INTO #tempPaidSubPart
		
	SELECT 
		 SA.OrgId AS OrgGroupId,SA.OrganizationName As OrgGroupName,
		 SA.ClassId As ClassId,
		 SA.ClassName AS ClassName,
		 ISNULL(CGM.Id,0) AS CollectionGroupId,
		 ISNULL(CGM.Code,'') AS CollectionGroup,
		 ISNULL(RBM.Title,'')  AS ReceiptTitle,
		 ISNULL(RBM.Id,0) As ReceiptBookId,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,
		 COUNT(Distinct(FAS.AcademicId)) as StudentCount
		 ,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
		 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
		 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
		 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		 --And ISNULL(O.IsObsolete,0) = 0
		 And O.IsObsolete <> 1
		 AND FAS.PaidAmount > 0
		 -- IsInContext
		AND BM.IsInContext = 1
    GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,SA.DivisionOrder
	HAVING ISNULL(SUM(FAS.PaidAmount),0) > 0
	ORDER BY SA.ClassOrderIndex,SA.DivisionOrder

	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount,T.StudentCount As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,
		'' as MonthName ,T.DivisionOrder
		from #tempPaidSubPart T
	END
	
	DROP TABLE #tempPaidSubPart

END

ELSE IF(@rType ='FeeStatusPaidSubPartAmountMonthWise')
BEGIN 
	CREATE TABLE #tempPaidSubPartMonthWise (
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	MonthName nvarchar(15),
	)
   
    CREATE TABLE #tempPFSMonthWise (
Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )

    INSERT INTO #tempPFSMonthWise	
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
	WHERE 
	   (FS1.IsOptional=0)
	   --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		-- IsInContext
		AND BM.IsInContext = 1
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))


     CREATE TABLE #tempPRMonthWise (
         PaidAmount DECIMAL(12,0),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise	
     SELECT 
		  ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		  sFee.tReceipt R WITH (NOLOCK) 
		  INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		  INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		  INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		  INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId 
		  INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		  INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
		  INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
		  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		  INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		 
	WHERE		
		  (R.SourceTypeId = 2001)
		   AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		   AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		   AND COGBM.Id=@rCommonOrgGroupBatchId 
		   --And ISNULL(O.IsObsolete,0) = 0
		   And O.IsObsolete <> 1
		   -- IsInContext
		AND BM.IsInContext = 1
		   --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		   --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
 

IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPartMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR.PaidAmount,0.00))AS PendingAmount,
		TPR.ReceiptDate		 
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN #tempPFSMonthWise TPFS ON TPFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=TPFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise TPR ON TPR.FeeSetupId = TPFS.Id AND SA.AcademicId = TPR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TPFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TPFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=TPFS.FeeHeadId	    	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	--And ISNULL(O.IsObsolete,0) = 0
	And O.IsObsolete <> 1
	-- IsInContext
	AND BM.IsInContext = 1  
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.PaidAmount,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPFSMonthWise1 (
       Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
      CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
 )
    INSERT INTO #tempPFSMonthWise1
    SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		 INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		 INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	     INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	     INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	     INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			 
		 INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
	   
		 INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		 --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		 --And ISNULL(O.IsObsolete,0) = 0
		 And O.IsObsolete <> 1
		 -- IsInContext
	AND BM.IsInContext = 1  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		 --AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	  INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		
	WHERE
				
		(FS1.IsOptional=1) AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
	AND BM.IsInContext = 1  
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
    
    CREATE TABLE #tempPRMonthWise1(
         PaidAmount DECIMAL(12,0),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise1
     SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		sFee.tReceipt R WITH (NOLOCK) 
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		AND (R.IsObsolete = 0) 
		-- IsInContext
	AND BM.IsInContext = 1  
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate  
   
	
	INSERT INTO #tempPaidSubPartMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,		
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR1.PaidAmount,0.00))AS PendingAmount,
		TPR1.ReceiptDate
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		 LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFSMonthWise1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK)
			ON FA.FeeSetupId=TPFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise1 TPR1 ON TPR1.FeeSetupId = TPFS1.Id AND SA.AcademicId = TPR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TPFS1.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=TPFS1.FeeHeadId
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	--And ISNULL(O.IsObsolete,0) = 0
	And O.IsObsolete <> 1
	-- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR1.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.AcademicId) As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END
	
	DROP TABLE #tempPaidSubPartMonthWise
	DROP TABLE #tempPFSMonthWise
	DROP TABLE #tempPRMonthWise
	DROP TABLE #tempPFSMonthWise1
	DROP TABLE #tempPRMonthWise1
	
END

ELSE IF(@rType ='FeeStatusPendingSubPartAmount')
BEGIN 
CREATE TABLE #tempPendingSubPart(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId bigint ,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	ClassOrderIndex int
	,DivisionOrder int
	)

IF(@rCollectionGroupId = 0)
	BEGIN

	INSERT INTO #tempPendingSubPart
    SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId  AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
		,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
		(FS.IsOptional=0)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId = 0))
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,SA.DivisionOrder
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,COUNT(T.AcademicId)AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex 
		,T.DivisionOrder ----add for mantis : 0042058
		from #tempPendingSubPart T
		WHERE T.PendingAmount >0
     group by T.OrgGroupId,T.OrgGroupName,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex,T.DivisionOrder
		ORDER BY T.ClassOrderIndex,T.DivisionOrder
		
DROP TABLE #tempPendingSubPart
		
	END 
	ELSE 
	BEGIN
	
	INSERT INTO #tempPendingSubPart
	SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex  
		,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
		(FS.IsOptional=0)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId = 0))
		-- IsInContext
		AND BM.IsInContext = 1
	 GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	 ,SA.DivisionOrder --add division for mantis :0042058
	
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex 
		,T.DivisionOrder
		from #tempPendingSubPart T
	WHERE T.PendingAmount >0
	GROUP BY T.OrgGroupId,T.ClassName,T.OrgGroupName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex,T.DivisionOrder
	--HAVING ISNULL(SUM(T.PendingAmount),0) > 0
	ORDER BY T.ClassOrderIndex,T.DivisionOrder --DivisionOrder add for mantis : 0042058	
		
   
	   DROP TABLE #tempPendingSubPart
		
	END
	END

ELSE IF(@rType ='FeeStatusPendingSubPartDetails')
BEGIN 
CREATE TABLE #tempPendingSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
,DivisionOrder INT --mantis : 0042058
)

IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPendingSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		,SA.DivisionOrder --mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 -- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
		,SA.DivisionOrder --mantis :0042058 	
		select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
			ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo 
			,T.DivisionOrder --mantis : 0042058
			from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.DivisionOrder,T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempPendingSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex
		,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex
	,SA.DivisionOrder	

		select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo 
		,T.DivisionOrder --mantis : 0042058
		from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex
		,T.DivisionOrder 
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.DivisionOrder
				,T.RollNo --mantis : 0042058
		 
	END
	
	DROP TABLE #tempPendingSubPartDetails
	 
END	
	
ELSE IF(@rType ='FeeStatusTotalSubPartAmount')
BEGIN 
CREATE TABLE #tempTotalSubPart (
AcademicId bigint,
OrgGroupId int,
OrgGroupName nvarchar(100),
ClassId bigint,
ClassName nvarchar(50),
--DivisionId bigint,
--DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
ClassOrderIndex int
,DivisionOrder int
)

IF(@rCollectionGroupId = 0)
	BEGIN

	INSERT INTO #tempTotalSubPart
	SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		SA.OrgId AS OrgGroupId,
		SA.OrganizationName AS OrgGroupName,
		SA.ClassId AS ClassId,
		SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
		,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--And ISNULL(O.IsObsolete,0) = 0
			And O.IsObsolete <> 1
			AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			-- IsInContext
		AND BM.IsInContext = 1
	GROUP by SA.OrgId,SA.OrganizationName, SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId 
		,T.ClassOrderIndex
		,T.DivisionOrder
		from #tempTotalSubPart T
	group by T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex,T.DivisionOrder
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.ClassOrderIndex
				,T.DivisionOrder --add for mantis : 0042058
		
	END 
	ELSE 
	BEGIN
	
	INSERT INTO #tempTotalSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		  SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex--,SA.DivisionOrder
		,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--And ISNULL(O.IsObsolete,0) = 0
			And O.IsObsolete <> 1
			AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			-- IsInContext
		AND BM.IsInContext = 1

	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,SA.DivisionOrder

		 
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId 
		,T.ClassOrderIndex
		,T.DivisionOrder
		from #tempTotalSubPart T
	GROUP BY T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,T.ClassOrderIndex,T.DivisionOrder
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.ClassOrderIndex,T.DivisionOrder
		
	END
	
	DROP TABLE #tempTotalSubPart
	
  END	
ELSE IF(@rType ='FeeStatusTotalSubPartDetails')
BEGIN 
CREATE TABLE #tempTotalSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
,ClassOrderIndex INT --add for mantis : 0042058
,DivisionOrder INT --add for mantis : 0042058
)

 
IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempTotalSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		,SA.ClassOrderIndex --add for mantis : 0042058
		,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND  ISNULL(CGM.Id,0)=0
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo,SA.ClassOrderIndex
				,SA.DivisionOrder
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo 
		,T.ClassOrderIndex
		,T.DivisionOrder
		from #tempTotalSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId,T.ClassOrderIndex
				,T.DivisionOrder
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempTotalSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		,SA.ClassOrderIndex --add for mantis : 0042058
		,SA.DivisionOrder --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo 
		,T.ClassOrderIndex,T.DivisionOrder
		from #tempTotalSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId,T.ClassOrderIndex,T.DivisionOrder 
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.ClassOrderIndex,T.DivisionOrder ,T.RollNo
		
	 
	END
	
	DROP TABLE #tempTotalSubPartDetails
	
END
  
ELSE IF(@rType ='FeeStatusPaidSubPartDetails')
BEGIN 
CREATE TABLE #tempPaidSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
,ClassOrderIndex INT --add for mantis : 0042058
,DivisionOrder INT --add for mantis : 0042058
)

 
IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetails
	SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		,SA.ClassOrderIndex INT --add for mantis : 0042058
		,SA.DivisionOrder INT --add for mantis : 0042058
		
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND  ISNULL(CGM.Id,0)=0
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo,SA.ClassOrderIndex
				,SA.DivisionOrder --0042058
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo 
		,T.ClassOrderIndex --add for mantis : 0042058
				,T.DivisionOrder --add for mantis : 0042058
		from #tempPaidSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId,T.ClassOrderIndex
				,T.DivisionOrder
	HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
	ORDER BY T.ClassOrderIndex
				,T.DivisionOrder,T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempPaidSubPartDetails
	SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		,SA.ClassOrderIndex INT --add for mantis : 0042058
		,SA.DivisionOrder INT --add for mantis : 0042058
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 --And ISNULL(O.IsObsolete,0) = 0
	 And O.IsObsolete <> 1
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code
	,SA.RollNo,SA.ClassOrderIndex,SA.DivisionOrder

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo
		,T.ClassOrderIndex --add for mantis : 0042058
		,T.DivisionOrder --add for mantis : 0042058
		from #tempPaidSubPartDetails T
		
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.ClassOrderIndex
				,T.DivisionOrder
				,T.RollNo --0042058
		
	END
	
	DROP TABLE #tempPaidSubPartDetails
END

ELSE IF(@rType ='FeeStatusPaidSubPartDetailsMonthWise')
BEGIN 
CREATE TABLE #tempPaidSubPartDetailsMonthWise(
AcademicId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

CREATE TABLE #tempDFSMonthWise(
     Id INT,
     Amount DECIMAL(12,0),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempDFSMonthWise
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   --And ISNULL(O.IsObsolete,0) = 0
	   And O.IsObsolete <> 1
	   -- IsInContext
		AND BM.IsInContext = 1
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempDRMonthWise(
       PaidAmount DECIMAL(12,0),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
		,R.ReceiptDate
	FROM
		sFee.tReceipt R WITH (NOLOCK)
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetailsMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TDFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND((DATEPART(M, TDR.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	--And ISNULL(O.IsObsolete,0) = 0
	And O.IsObsolete <> 1
	-- IsInContext
		AND BM.IsInContext = 1
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempDFSMonthWise1(
     Id INT,
     Amount DECIMAL(12,0),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempDFSMonthWise1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- IsInContext
		AND BM.IsInContext = 1
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempDRMonthWise1(
       PaidAmount DECIMAL(12,0),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise1
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId,
		R.ReceiptDate
	FROM
		sFee.tReceipt R WITH (NOLOCK)
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId
		-- IsInContext
		AND BM.IsInContext = 1
		 --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
	
	
	
	insert into #tempPaidSubPartDetailsMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA WITH (NOLOCK)
		 LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise1 TDFS1 WITH (NOLOCK) ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK)
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TDFS1.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND((DATEPART(M, TDR1.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	--And ISNULL(O.IsObsolete,0) = 0
	And O.IsObsolete <> 1
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
		
		DROP TABLE #tempDFSMonthWise1
	DROP TABLE #tempDRMonthWise1
	END
	
	DROP TABLE #tempPaidSubPartDetailsMonthWise
	DROP TABLE #tempDFSMonthWise
	DROP TABLE #tempDRMonthWise
	
	
	
END

ELSE IF(@rType='ReceiptOrganization')
  BEGIN
	IF(@rSyncDate =1)
		BEGIN
				DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganizationSync(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,0),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganizationSync
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.ReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId )
				--And ISNULL(O.IsObsolete,0) = 0 
				And O.IsObsolete <> 1
				AND (R.ReceiptDate between @rFromDate and @rToDate)   
				-- IsInContext
				AND BM.IsInContext = 1 
			
			INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganizationSync T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganizationSync WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				DROP TABLE #tempReceiptOrganizationSync
		END 
	ELSE
		BEGIN
			IF  Exists(select 1 from sFee.tTempReceiptOrganization WITH (NOLOCK) 
			where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND CONVERT(date,ReceiptDate) =@rFromDate AND CONVERT(date,ReceiptDate) =@rToDate)
			BEGIN
				SELECT * FROM sFee.tTempReceiptOrganization WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
			ELSE
			BEGIN 
			DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganization(
					OrgGroupId int,
					OrgGroupName nvarchar(500),
					ReceiptId bigint,
					TotalReceiptAmount DECIMAL(12,0),
					IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganization
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.TotalReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId ) 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
				-- IsInContext
				AND BM.IsInContext = 1
			
				INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganization T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganization WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DROP TABLE #tempReceiptOrganization
			END
		END
  END
ELSE IF(@rType='ReceiptBookCollectionGroup')
  BEGIN
	CREATE TABLE #tempReceiptBookCollection (
	RecepitTitle nvarchar(200),
	--CollectionTitle nvarchar(200),
	ReceiptCount int,
	ReceiptAmount DECIMAL(12,0),
	ReceiptId bigint,
	--CollectionGroupId bigint,
	IsObsolete bit
)

INSERT INTO #tempReceiptBookCollection
 SELECT ISNULL(RBM.Title,'')  AS RecepitTitle ,
			--ISNULL(CGM.Code,'') AS CollectionTitle,
			ISNULL(COUNT(DISTINCT R.Id),0) AS ReceiptCount,CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
			ISNULL(RBM.Id,0) AS ReceiptId,
			--ISNULL(CGM.Id,0) AS CollectionGroupId,
			R.IsObsolete
		FROM  sFee.tReceipt R WITH (NOLOCK)
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id 			
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=FS.ReceiptBookId
			--LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id 
			--AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (R.IsObsolete = 1) 
			--AND(BM.IsActive =1) 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))AND R.ReceiptDate between @rFromDate and @rToDate 
			--And ISNULL(O.IsObsolete,0) = 0   
			And O.IsObsolete <> 1
			-- IsInContext
		AND BM.IsInContext = 1
			GROUP BY RBM.Title,RBM.Id,R.ReceiptBookId,R.IsObsolete,R.Id,R.ReceiptAmount
			
			--SELECT  TRC.RecepitTitle +'-'+ TRC.CollectionTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,TRC.CollectionGroupId AS CollectionGroupId,ISNULL(COUNT(TRC.ReceiptCount),0) AS ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			--ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			--LEFT JOIN (
			--SELECT ReceiptId,CollectionGroupId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			--GROUP BY ReceiptId,CollectionGroupId
			--) A ON A.ReceiptId=TRC.ReceiptId AND A.CollectionGroupId=TRC.CollectionGroupId
			
			--WHERE IsObsolete = 0
			--GROUP BY TRC.RecepitTitle,TRC.CollectionTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.CollectionGroupId,TRC.ReceiptCount 

			SELECT  TRC.RecepitTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,0 AS CollectionGroupId,ISNULL(COUNT(TRC.ReceiptCount),0) AS ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			LEFT JOIN (
			SELECT ReceiptId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			GROUP BY ReceiptId
			) A ON A.ReceiptId=TRC.ReceiptId
			WHERE IsObsolete = 0
			GROUP BY TRC.RecepitTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.ReceiptCount 
		DROP TABLE #tempReceiptBookCollection
  END
ELSE IF(@rType='ReceiptBookCollectionGroupDetail')
  BEGIN
  CREATE TABLE #tempReceiptBookCollectionDetail(
  SourceId bigint,
Code nvarchar(200),
Name nvarchar(200),
ReceiptNumber bigint,
ReceiptAmount DECIMAL(12,0),
ReceiptId bigint,
IsObsolete bit
)
  
	INSERT INTO #tempReceiptBookCollectionDetail
		 SELECT ISNULL(SA.Id,0) AS SourceId,SM.Code AS Code,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) As Name, R.ReceiptNumber AS ReceiptNumber,
		 CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) = 1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
		 R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R WITH (NOLOCK)
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
			--INNER JOIN sStudent.tStudentMaster SM1 ON SA.StudentId = SM1.Id
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id AND SM.OrgId = OM.Id
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			--INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
			--INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId=SM.Id	
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId --AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND (R.IsObsolete = 0) 
			--AND(BM.IsActive =1) 
			--And ISNULL(O.IsObsolete,0) = 0 -- remove isnull because it will take more time to execute in all above conditions mantisid : 0038978
			--And O.IsObsolete = 0	
			And O.IsObsolete <> 1		
			AND COGBM.Id=@rCommonOrgGroupBatchId AND R.ReceiptDate between @rFromDate and @rToDate    
			-- IsInContext
			AND BM.IsInContext = 1
			GROUP BY SA.Id,SM.Code,R.ReceiptNumber,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId), R.ReceiptBookId,R.Id,R.IsObsolete,R.ReceiptAmount 
			--ORDER BY 
	 
  SELECT *  FROM #tempReceiptBookCollectionDetail ORDER BY ReceiptNumber
  
  DROP TABLE #tempReceiptBookCollectionDetail
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeConsolidateDashBoardTraceGet]
		@rType nvarchar(100)='',
		@rCount int =0 ,
		@rDivisionId int  =0,
		@rOrgId int  =0,
		@rOrgGroupId int=0,
		@rOrgGroupBatchId int  =0,
		@rCollectionGroupId int =0,
		@rReceiptBookId int =0,
		@rDays int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	IF(@rType ='FeeStatusOrganization')
	BEGIN 
	CREATE TABLE #tempFeeSetupDetails (
	FeeId int,
	Id int,
	IsOptional bit,
	IsVariable bit,
	Amount decimal(12,2),
	StartDate date,
	EndDate date,
	BatchId int,
	ReceiptBookId int,
	AcademicId bigint,
	FeeName nvarchar(200),
	FeeHeadId int
	)
	INSERT INTO #tempFeeSetupDetails
	SELECT 
		FS1.FeeId,
		FS1.Id,
		ISNULL(FS1.IsOptional,0)AS IsOptional,
		ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount,0)AS Amount,
		ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId,
		FM.Title AS FeeName,
		FM.FeeHeadId
	FROM 
		sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON BM.ID = SA1.BatchId
	WHERE 
		((FS1.IsOptional=0))
		AND (BM.IsActive =1) 
		
	UNION ALL

	SELECT 
		FS1.FeeId,
		FS1.Id,
		ISNULL(FS1.IsOptional,0)AS IsOptional,
		ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount,0)AS Amount,
		ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId,
		FM.Title AS FeeName,
		FM.FeeHeadId
	FROM 
		sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId
		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sSetup.tBatchMaster BM ON BM.ID = SA1.BatchId
	WHERE
		((FS1.IsOptional=1))
		AND (BM.IsActive =1) 
	
	SELECT 'FeeSetupDetails',GETDATE()	 
	
	CREATE TABLE #tempFeeReceipt (
	PaidAmount decimal(12,2),
	FeeSetupId int,
	SourceId bigint
	)
	INSERT INTO #tempFeeReceipt
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	WHERE		
		(R.SourceTypeId = 2001)
		AND (R.IsObsolete = 0) 
	GROUP BY FeeSetupId,R.SourceId
	
	SELECT 'FeeReceipt',GETDATE()	 
	
	CREATE TABLE #tempOrganization (
	--AcademicId bigint,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	OrgGroupName nvarchar(200),
	OrgGroupId int
	)
	INSERT INTO #tempOrganization
	SELECT 
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			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,
			OGM.Title AS OrgGroupName,
			OGM.Id AS OrgGroupId
		FROM 
			sStudent.tAcademic SA
			INNER JOIN #tempFeeSetupDetails FS ON FS.AcademicId=SA.Id
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
			LEFT JOIN #tempFeeReceipt R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.ID = SA.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.ID = SA.BatchId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			WHERE	
			(BM.IsActive =1) 
			GROUP BY  OGM.Id,OGM.Title
		
	SELECT 'Organization',GETDATE()	 		
		
	SELECT T.OrgGroupId,T.OrgGroupName,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
	ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount from #tempOrganization T ORDER BY OrgGroupId
	
	SELECT 'Final Result',GETDATE()	 	

	DROP TABLE #tempFeeSetupDetails
	DROP TABLE #tempFeeReceipt
	DROP TABLE #tempOrganization
	
	END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeCustomReportListGet]
	@rCreatedUserId bigint
	--@rOrgId smallint
AS
SET NOCOUNT ON

BEGIN
		SELECT 
			FCS.Id,
			FCS.Title,
			FCS.ColumnName,
			U.DisplayTitle AS CreatedUserName,
			CASE WHEN FCS.CreatedUserId = @rCreatedUserId THEN 'true' ELSE 'false' END AS IsDelete
		FROM sFee.tFeeCustomSearch FCS
		INNER JOIN sSecurity.tUser U ON U.Id=FCS.CreatedUserId
		WHERE 
			    ((FCS.CreatedUserId = @rCreatedUserId) OR (FCS.IsCommon = 1))
			--AND FCS.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeeCustomSearchGet]
(
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',	
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int,
	@rDepartmentId int=0,
	@rPageIndex int = null,
	@rAdmissionCategoryId int = 0
 )
AS
SET NOCOUNT ON
BEGIN
	create table #TEMPFee
	(
		tid int identity(1,1),t_AcedemicId bigint,t_ReceiptId bigint
	)
	
	DECLARE @Sql nvarchar(MAX)
	IF(@rFromReceiptDate IS NULL)
		SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'

		
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	
	SELECT FCS.AcademicId,FCS.ClassId,FCS.DivisionId,FCS.RollNo,FCS.OrgGroupBatchId,
	FCS.OrgId,FCS.BatchId,FCS.OrgGroupBatch,FCS.Organization,FCS.Batch,FCS.StudentId,
	FCS.Code,FCS.Number,FCS.FirstName,FCS.LastName,FCS.Name,FCS.StatusId,FCS.ClassName,
	FCS.DivisionName,FCS.StatusName,FCS.ReceiptId,FCS.ReceiptNumber,FCS.ReceiptDate,
	FCS.ReceiptAmount,FCS.ChequeNo,FCS.BankName,FCS.Remark,FCS.IsObsolete,FCS.FeeReceiptBookId,
	FCS.ReceiptBookCode,FCS.ReceiptBookName,FCS.Address1,FCS.Address2,FCS.BankAccountNumber,
	FCS.PayTypeId,FCS.PayType,FCS.CreatedUserId,FCS.CreatedUserName, FCS.ParentContactNo
	into sFee.tTempFee1
	FROM sFee.vFeeCustomSearch FCS
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = FCS.ClassId
	WHERE (FCS.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
	AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
	AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo =0))
	AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
	AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
	AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
	AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')
	AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	AND (FCS.IsObsolete=@rIsObsolete)
	AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
	AND ((Cm.DepartmentId =@rDepartmentId ) OR (@rDepartmentId=0))
	AND ((FCS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	
	SET @sql='SELECT Code AS Code,Name,ReceiptNumber,ReceiptDate,ReceiptAmount,
	PayType,ChequeNo,BankName,ReceiptBookName,Remark,OrgId,BatchId
	FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	SET @sql='INSERT INTO #TEMPFee SELECT AcademicId, ReceiptId
	FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',
			@lResult nvarchar(max)=''	--change varchar to nvarchar for mantis: 32993
	select @lTotalRecords = count(*) from #TEMPFee
	
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr attrId="' + convert(varchar,isnull(t_AcedemicId,0)) 
	+ '"attrCode="' + isnull(Code,'') 
	+ '"attrReceiptNo="' + isnull(convert(varchar,ReceiptNumber),'') 
	+ '"attrBatchId="' + convert(varchar,@rBatchId) 
	+ '"attrOrgId="' + convert(varchar,@rOrgId) 
	+ '"attrOrgGroupBatchId="' + convert(varchar,@rOrgGroupBatchId) + '">
	<td><a style="cursor:pointer;" onclick="SecectThisRecord(this);">Select</a></td><td>' + isnull(Code,'') + '</td>
	<td>' + isnull(Name,'') + '</td><td>' + isnull(convert(varchar,ReceiptNumber),'') + '</td>
	<td>' + isnull(convert(varchar,ReceiptDate,103),'') + '</td>
	<td>' + isnull(convert(varchar,ReceiptAmount),'') + '</td><td>' + isnull(PayType,'') + '</td>
	<td>' + isnull(ChequeNo,'') + '</td><td>' + isnull(BankName,'') + '</td>
	<td>' + isnull(ReceiptBookName,'') + '</td><td>' + isnull(Remark,'') + '</td></tr>'
	from sFee.tTempFee1,#TEMPFee where t_AcedemicId = AcademicId AND t_ReceiptId = ReceiptId
	and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lPaging as UserPaging,@lResult as UserResult,@lTotalRecords as UserTotal
			
	DROP Table sFee.tTempFee1
	drop Table #TEMPFee
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeDetailsStatusGet]
		
	@rType nvarchar(100)='',
	@rCount int = 0 ,
	@rDivisionId int  = 0,
	@rClassId int  = 0,
	@rOrgId int  = 0,
	@rOrgGroupId int = 0,		
	@rCommonOrgGroupBatchId int = 0,	
	@rSyncDate int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

	IF(@rType = 'FeeDetailsStatusOrgGroupwise')
	BEGIN
	IF(@rSyncDate =1)
		BEGIN	
		DELETE  sFee.tTempOrgGroupFeeDetailsStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		INSERT INTO sFee.tTempOrgGroupFeeDetailsStatus
		SELECT 
			@rCommonOrgGroupBatchId AS CommonOrgGroupBatchId,
			O.Title AS OrgGroupName,
			O.Id AS OrgGroupId,
			SUM(ISNULL(FAS.DiscountAmount,0)) AS ExemptionAmount,
			SUM(ISNULL(FAS.AdditionalAmount,0.00))AS AdditionalAmount,
			SUM(ISNULL(FAS.NotApplicableAmount,0.00))AS AdditionalAmount,			
			sCommon.fGetDate()
		FROM 
			sStudent.tAcademic SA
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.ID = SA.OrgId						
		WHERE	
				COGBM.Id=@rCommonOrgGroupBatchId 
				And ISNULL(O.IsObsolete,0) = 0
				AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
		GROUP BY  o.Id,o.Title

		SELECT ExemptionAmount,AdditionalAmount,NotApplicableAmount,OrgGroupId,OrgGroupName 
		FROM sFee.tTempOrgGroupFeeDetailsStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		END
	ELSE
		BEGIN
			SELECT ExemptionAmount,AdditionalAmount,NotApplicableAmount,OrgGroupId,OrgGroupName 
			FROM sFee.tTempOrgGroupFeeDetailsStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		END
	END
	ELSE IF(@rType = 'FeeDetailsStatusClasswise')
	BEGIN
		-- Exemption
		IF(@rCount = 1)
		BEGIN
			SELECT 
				SA.OrgId AS OrgId,
				SA.OrganizationName AS OrgName,
				ISNULL(SA.ClassId,0)AS ClassId,
				ISNULL(SA.ClassName,'') AS ClassName,
				SUM(ISNULL(FAS.DiscountAmount,0)) AS Amount,
				COUNT(Distinct(SA.AcademicId)) as StudentCount
			FROM 		
				sStudent.vStudentAcademic SA
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
			WHERE
				(O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND
				((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0 AND FAS.DiscountAmount > 0
			GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName
		END
		--Additional
		ELSE IF(@rCount = 2)
		BEGIN
			SELECT 
				SA.OrgId AS OrgId,
				SA.OrganizationName AS OrgName,
				ISNULL(SA.ClassId,0)AS ClassId,
				ISNULL(SA.ClassName,'') AS ClassName,
				SUM(ISNULL(FAS.AdditionalAmount,0)) AS Amount,
				COUNT(Distinct(SA.AcademicId)) as StudentCount
			FROM 		
				sStudent.vStudentAcademic SA
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
			WHERE
				(O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND
				((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0 AND FAS.AdditionalAmount > 0
			GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName
		END
		--NotApplicable
		ELSE IF(@rCount = 3)
		BEGIN
			SELECT 
				SA.OrgId AS OrgId,
				SA.OrganizationName AS OrgName,
				ISNULL(SA.ClassId,0)AS ClassId,
				ISNULL(SA.ClassName,'') AS ClassName,
				SUM(ISNULL(FAS.NotApplicableAmount,0)) AS Amount,
				COUNT(Distinct(SA.AcademicId)) as StudentCount
			FROM 		
				sStudent.vStudentAcademic SA
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
			WHERE
				(O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND
				((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0 AND FAS.NotApplicableAmount > 0
			GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName
		END
	END
	ELSE IF(@rType = 'FeeDetailsStatusStudentwise')
	BEGIN
		-- Exemption
		IF(@rCount = 1)
		BEGIN
			SELECT 
				ISNULL(SA.AcademicId,0) AS AcademicId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassId,'') AS ClassId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As StudentCode,
				ISNULL(SA.[Name],'') AS StudentName,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				SUM(ISNULL(FAS.DiscountAmount,0)) AS Amount,
				 SA.ClassOrderIndex,  
				 SA.DivisionOrder,
				 SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
			WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0
				AND FAS.DiscountAmount > 0
		GROUP by O.Id,SA.ClassId,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FAS.DiscountAmount,0)) >0
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
		END
		-- Additional
		IF(@rCount = 2)
		BEGIN
			SELECT 
				ISNULL(SA.AcademicId,0) AS AcademicId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassId,'') AS ClassId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As StudentCode,
				ISNULL(SA.[Name],'') AS StudentName,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				SUM(ISNULL(FAS.AdditionalAmount,0)) AS Amount,
				 SA.ClassOrderIndex,  
				 SA.DivisionOrder,
				 SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
			WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0
				AND FAS.AdditionalAmount > 0
		GROUP by O.Id,SA.ClassId,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FAS.AdditionalAmount,0)) >0
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
		END
		-- NotApplicable
		IF(@rCount = 3)
		BEGIN
			SELECT 
				ISNULL(SA.AcademicId,0) AS AcademicId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassId,'') AS ClassId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As StudentCode,
				ISNULL(SA.[Name],'') AS StudentName,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				SUM(ISNULL(FAS.NotApplicableAmount,0)) AS Amount,
				 SA.ClassOrderIndex,  
				 SA.DivisionOrder,
				 SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
			WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0
				AND FAS.NotApplicableAmount > 0
		GROUP by O.Id,SA.ClassId,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FAS.NotApplicableAmount,0)) >0
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo
		END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pFeeDiscountAdd]

	 
	@rSourceTypeId int,
	 
	@rSourceId bigint,
	 
	@rXmlString nvarchar(max),
	@rCreatedUserId  bigint 
	  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rXmlString=REPLACE(@rXmlString,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	 BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlString
	 
	DECLARE @lNextNumber bigint     
	  
	if exists(Select 1 from sFee.tFeeDiscount FD INNER JOIN( 
				Select FeeSetupId from OPENXML (@intDoc, '/Table/FeeAllocation', 1)
				WITH
				(
					FeeSetupId int '@FeeSetupId',
					RequestedDiscountAmount decimal(12,2) '@RequestedDiscountAmount',
					RequestedRemark nvarchar(200) '@RequestedRemark',
					ApprovedDiscountAmount decimal(12,2) '@ApprovedDiscountAmount',
					ApprovedRemark nvarchar(200) '@ApprovedRemark'
				))A ON A.FeeSetupId = FD.FeeSetupId
				where  SourceId =@rSourceId and SourceTypeId=@rSourceTypeId and FD.FeeSetupId = A.FeeSetupId ANd ApprovedDiscountAmount !=0 )
	BEGIN
		Select 11 As Result
	END
	
	
	else if exists(Select 1 from sFee.tFeeDiscount FD INNER JOIN( 
				Select FeeSetupId from OPENXML (@intDoc, '/Table/FeeAllocation', 1)
				WITH
				(
					 
					FeeSetupId int '@FeeSetupId',
					RequestedDiscountAmount decimal(12,2) '@RequestedDiscountAmount',
					RequestedRemark nvarchar(200) '@RequestedRemark',
					ApprovedDiscountAmount decimal(12,2) '@ApprovedDiscountAmount',
					ApprovedRemark nvarchar(200) '@ApprovedRemark'
				))A ON A.FeeSetupId = FD.FeeSetupId
				where  SourceId =@rSourceId and SourceTypeId=@rSourceTypeId and FD.FeeSetupId = A.FeeSetupId)
	BEGIN
		 Update   sFee.tFeeDiscount  set RequestedDiscountAmount = A.RequestedDiscountAmount,RequestedRemark =A.RequestedRemark,
										CreatedUserId= @rCreatedUserId, CreatedDateTime=sCommon.fGetDate()  from (
				Select RequestedDiscountAmount,RequestedRemark,FeeSetupId from OPENXML (@intDoc, '/Table/FeeAllocation', 1)
				WITH
				(
					 
					FeeSetupId int '@FeeSetupId',
					RequestedDiscountAmount decimal(12,2) '@RequestedDiscountAmount',
					RequestedRemark nvarchar(200) '@RequestedRemark',
					ApprovedDiscountAmount decimal(12,2) '@ApprovedDiscountAmount',
					ApprovedRemark nvarchar(200) '@ApprovedRemark'
				))A
			where  SourceId =@rSourceId and SourceTypeId=@rSourceTypeId and  sFee.tFeeDiscount.FeeSetupId = A.FeeSetupId ANd ApprovedDiscountAmount =0 
					EXEC sp_xml_removedocument @intDoc
		SELECT 1 AS Result
	 
		
	END
	Else
	BEGIN
	INSERT INTO sFee.tFeeDiscount
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			RequestedDiscountAmount,
			RequestedRemark,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ApprovedByUserId,
			ApprovedDiscountAmount,
			ApprovedRemark 
		 
		)
	Select 
			@rSourceTypeId,
			@rSourceId,
			A.FeeSetupId,
			A.RequestedDiscountAmount,
			A.RequestedRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			NULL,
			NULL,
			@rCreatedUserId,
			A.ApprovedDiscountAmount,
			A.ApprovedRemark
			
	from OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		 
		FeeSetupId int '@FeeSetupId',
		RequestedDiscountAmount decimal(12,2) '@RequestedDiscountAmount',
		RequestedRemark nvarchar(200) '@RequestedRemark',
		ApprovedDiscountAmount decimal(12,2) '@ApprovedDiscountAmount',
		ApprovedRemark nvarchar(200) '@ApprovedRemark'
	)A 
	 	EXEC sp_xml_removedocument @intDoc
		SELECT 1 AS Result
	 
		
		 
		END
		COMMIT TRANSACTION
	----END TRY	
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeDiscountAprooved]

	 
	@rSourceTypeId int,
	 
	@rSourceId bigint,
	 
	@rXmlString nvarchar(max),
	@rCreatedUserId  bigint 
	  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rXmlString=REPLACE(@rXmlString,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	 BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlString
	 
	DECLARE @lNextNumber bigint     
	  
 
	if exists(Select 1 from sFee.tFeeDiscount FD INNER JOIN( 
				Select FeeSetupId from OPENXML (@intDoc, '/Table/FeeAllocation', 1)
				WITH
				(
					 
					FeeSetupId int '@FeeSetupId',
					RequestedDiscountAmount decimal(12,2) '@RequestedDiscountAmount',
					RequestedRemark nvarchar(200) '@RequestedRemark',
					ApprovedDiscountAmount decimal(12,2) '@ApprovedDiscountAmount',
					ApprovedRemark nvarchar(200) '@ApprovedRemark'
				))A ON A.FeeSetupId = FD.FeeSetupId
				where  SourceId =@rSourceId and SourceTypeId=@rSourceTypeId and FD.FeeSetupId = A.FeeSetupId)
	BEGIN
		 Update   sFee.tFeeDiscount  set ApprovedDiscountAmount = A.ApprovedDiscountAmount,ApprovedRemark =A.ApprovedRemark ,
										UpdatedUserId =@rCreatedUserId,UpdatedDateTime =  sCommon.fGetDate()    from (
				Select ApprovedDiscountAmount,ApprovedRemark,FeeSetupId from OPENXML (@intDoc, '/Table/FeeAllocation', 1)
				WITH
				(
					 
					FeeSetupId int '@FeeSetupId',
					RequestedDiscountAmount decimal(12,2) '@RequestedDiscountAmount',
					RequestedRemark nvarchar(200) '@RequestedRemark',
					ApprovedDiscountAmount decimal(12,2) '@ApprovedDiscountAmount',
					ApprovedRemark nvarchar(200) '@ApprovedRemark'
				))A
			where  SourceId =@rSourceId and SourceTypeId=@rSourceTypeId and  sFee.tFeeDiscount.FeeSetupId = A.FeeSetupId
					 
					
		Update sFee.tFeeAllocation	Set DiscountAmount =A.ApprovedDiscountAmount
		 from (
				Select ApprovedDiscountAmount ,FeeSetupId from OPENXML (@intDoc, '/Table/FeeAllocation', 1)
				WITH
				(
					FeeSetupId int '@FeeSetupId',
					RequestedDiscountAmount decimal(12,2) '@RequestedDiscountAmount',
					RequestedRemark nvarchar(200) '@RequestedRemark',
					ApprovedDiscountAmount decimal(12,2) '@ApprovedDiscountAmount',
					ApprovedRemark nvarchar(200) '@ApprovedRemark'
				))A
				where  SourceId =@rSourceId and SourceTypeId=@rSourceTypeId and  sFee.tFeeAllocation.FeeSetupId = A.FeeSetupId
		
		-- For Fee Process Added By Foram 2025-01-27
		Update sFee.tFeeAllocationStudent 
		Set DiscountAmount =A.ApprovedDiscountAmount,
		ToPayAmount = (FeeAmount + VariableAmount + AdditionalAmount - A.ApprovedDiscountAmount - NotApplicableAmount - PaidAmount)
		from 
		 (
				Select ApprovedDiscountAmount ,FeeSetupId from OPENXML (@intDoc, '/Table/FeeAllocation', 1)
				WITH
				(
					FeeSetupId int '@FeeSetupId',
					RequestedDiscountAmount decimal(12,2) '@RequestedDiscountAmount',
					RequestedRemark nvarchar(200) '@RequestedRemark',
					ApprovedDiscountAmount decimal(12,2) '@ApprovedDiscountAmount',
					ApprovedRemark nvarchar(200) '@ApprovedRemark'
				))A
				where  AcademicId=@rSourceId and sFee.tFeeAllocationStudent.FeeSetupId = A.FeeSetupId
		
		-- For Fee Process Added By Foram 2025-01-27
		
		EXEC sp_xml_removedocument @intDoc	
		SELECT 1 AS Result
	 
		
	END
	 
		COMMIT TRANSACTION
	----END TRY	
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeDiscountGet]
	 
		
		@rSourceId bigint ,
		@rSourceTypeId int,
		@rBatchId int,
		@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	if (@rStudentId <> 0)
	SELECT @rSourceId = Id FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId

SELECT 
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
		 
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			 
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FD.RequestedDiscountAmount,0.00) AS RequestedDiscountAmount,
			 ISNULL(FD.RequestedRemark,'') As RequestedRemark,
			ISNULL(FD.ApprovedDiscountAmount,0.00) As ApprovedDiscountAmount,
			ISNULL(FD.ApprovedRemark,'') AS ApprovedRemark,
			ISNULL(FA.Remark,'') AS Remark,
			FM.OrderIndex
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				 
				FS1.BatchId,
				 
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				 
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
			 
				FS1.BatchId,
			 
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId 
				 
			FROM sFee.tFeeSetup FS1
			 
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		Left Join 	sFee.tFeeDiscount FD ON FD.FeeSetupId = FS.Id AND (FD.SourceId=@rSourceId) AND(FD.SourceTypeId=@rSourceTypeId)

		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId
ORDER BY  FM.OrderIndex ASC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeDiscountReceiptListGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(20)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='' 

 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       
 SELECT 
  A.StatusId,    
  R.Id AS ReceiptId,    
  R.SourceId AS SourceId,    
  R.SourceTypeId AS SourceTypeId,    
  CASE WHEN R.SourceTypeId=2001 THEN 'Student'    
  ELSE  'Employee' END AS SourceType,    
  --STM.Title     
  A.Code AS Code,    
  A.Name,    
  R.ReceiptNumber,    
  R.ReceiptDate,    
  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
  R.PayTypeId,    
  PTM.Title AS PayType,    
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
  --R.ChequeNo,    
  R.BankName,    
  R.ReceiptBookId,    
  RBM.Title AS ReceiptBook,    
  R.IsObsolete,    
  A.OrgId,    
  OM.DisplayTitle AS Organization,    
  R.BatchId,    
  BM.Title AS Batch,    
  R.Remark,    
  ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,    
  ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,    
  ISNULL(R.ChequeDate,'') AS ChequeDate,    
  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,    
  Cm.title,    
  CM.Id,    
  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
  CM.Title +' - '+ DM.Title AS Class,    
  A.SUId,    
  ISNULL(R.AmountAfterDiscount,0)AS AmountAfterDiscount,    
  ISNULL(R.CGSTPercentage,0)AS CGSTPercentage,    
  ISNULL(R.SGSTPercentage,0)AS SGSTPercentage,    
  ISNULL(R.CGSTAmount,0)AS CGSTAmount,    
  ISNULL(R.SGSTAmount,0)AS SGSTAmount,    
  ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId,    
  R.CreatedDateTime AS ReceiptCreatedDateTime,
  ISNULL(R.ReceiptPrintGroupId,'') AS ReceiptPrintGroupId    
  FROM     
   sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND (R.IsDiscountCoupon = 1)

 ORDER BY R.ReceiptNumber DESC    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeDueAlertGet]
	 
		
		@rSourceId bigint ,
		@rSourceTypeId int,
		@rBatchId int,
		@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	if (@rStudentId <> 0)
	SELECT @rSourceId = Id FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId

SELECT 
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FM.OrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId,
			FM.FeeHeadId
			
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				 
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId 
				 
			FROM sFee.tFeeSetup FS1
			 
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId 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)
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeExpenseAdd]
	 
		@rId bigint,
		@rAcademicId bigint,
		@rExpenseAmount decimal(10,2),
		@rExpenseDate date,
		@rExpenseRemark nvarchar(20),
		@rCreatedUserId bigint,
		@rFeeExpenseTypeId int=0,
		@rFeeSetupId int=0
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	IF(@rId = 0)	
	BEGIN
		INSERT INTO sFee.tFeeExpense
			(
				AcademicId,
				ExpenseAmount,
				ExpenseDate,
				ExpenseRemark,
				CreatedUserId,
				CreatedDateTime,
				FeeExpenseTypeId,
				FeeSetupId
			)
		VALUES
			(
				@rAcademicId,
				@rExpenseAmount,
				@rExpenseDate,
				@rExpenseRemark,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rFeeExpenseTypeId,
				@rFeeSetupId
			)
		SELECT 1 AS Result
	END	 

ELSE
	BEGIN
	    UPDATE  sFee.tFeeExpense
	    SET
			AcademicId=@rAcademicId,
			ExpenseAmount=@rExpenseAmount,
			ExpenseDate=@rExpenseDate,
			ExpenseRemark=@rExpenseRemark,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			FeeExpenseTypeId=@rFeeExpenseTypeId,
			FeeSetupId=@rFeeSetupId
	    WHERE AutoId = @rId
		SELECT 11 AS Result
	END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeExpenseBulkAdd]
	
	@rFeeExpenseXml [nvarchar](max),
	@rUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rFeeExpenseXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
		INSERT INTO sFee.tFeeExpense
		(
			AcademicId,
			FeeSetupId,
			ExpenseAmount,
			ExpenseDate,
			ExpenseRemark,
			FeeExpenseTypeId,
			CreatedUserId,
			CreatedDateTime
			)
		SELECT
			AcademicId,
			FeeSetupId,
			ExpenseAmount,
			ExpenseDate,
			ExpenseRemark,
			FeeExpenseTypeId,
			@rUserId,
			sCommon.fGetDate()
		FROM OPENXML (@loDoc, '/Table/FeeExpense', 1)
		WITH ( 
				AcademicId bigint,
				FeeSetupId int,
				ExpenseAmount decimal(10,2),
				ExpenseDate date,
				ExpenseRemark nvarchar(200),
				FeeExpenseTypeId int
			  ) 
		
	   SELECT 1 AS Result
	    
	   EXEC sp_xml_removedocument @loDoc
	   
	   COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeExpenseBulkGet]
	 
	 @rOrgId int,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFeeSetupId int,
	 @rAdmissionCategory int =0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			vSA.AcademicId,
			vSA.Code,
			vSA.Name,
			vSA.ClassName +' - '+vSA.DivisionName AS ClassDivision,
			ISNULL((SELECT ISNULL(OpeningAmount,0) AS OpeningAmount FROM sFee.tFeeOpening FO WHERE AcademicId=vSA.AcademicId AND FeeSetupId=@rFeeSetupId),0) AS FeeOpeningAmount,
			ISNULL((SELECT ISNULL(SUM(RD.Amount),0) AS FeeAmount FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
             INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.BatchId = R.BatchId 
             WHERE R.SourceTypeId= 2001 AND R.IsObsolete=0 AND FS.Id = @rFeeSetupId AND R.SourceId = vSA.AcademicId AND R.BatchId = @rBatchId),0) AS PaidAmount,
            ISNULL((SELECT ISNULL(SUM(ExpenseAmount),0) AS ExpenseAmount FROM sFee.tFeeExpense WHERE AcademicId = vSA.AcademicId AND FeeSetupId = @rFeeSetupId),0) AS PreviousTotalExpenseAmount,
          ISNULL( ((SELECT ISNULL(SUM(RD.Amount),0) AS FeeAmount FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
             INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.BatchId = R.BatchId 
             WHERE R.SourceTypeId= 2001 AND R.IsObsolete=0  AND FS.Id = @rFeeSetupId AND R.SourceId = vSA.AcademicId AND R.BatchId = @rBatchId)
             +(SELECT ISNULL(OpeningAmount,0) AS OpeningAmount FROM sFee.tFeeOpening FO WHERE AcademicId=vSA.AcademicId AND FeeSetupId=@rFeeSetupId))
             - 
            (SELECT ISNULL(SUM(ExpenseAmount),0) AS ExpenseAmount FROM sFee.tFeeExpense WHERE AcademicId = vSA.AcademicId AND FeeSetupId = @rFeeSetupId),0) AS PendingAmount
	FROM			
			sStudent.vStudentAcademic vSA
	WHERE 
			vSA.OrgId= @rOrgId 
			AND vSA.BatchId = @rBatchId 
			AND	(vSA.ClassId = @rClassId)
			AND	(vSA.DivisionId = @rDivisionId)
			AND vSA.AdmissionCategoryId = @rAdmissionCategory
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeExpenseGet]
	 
	 @rId bigint,
	 @rOrgId int,
	 @rBatchId int,
	 @rCode nvarchar(20),
	 @rClassId int,
	 @rDivisionId int,
	 @rFeeSetupId int,
	 @rFromDate date,
	 @rTodate date,
	 @rFeeExpenseTypeId int=0,
	 @rFeeCategory int=0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			FE.AutoId AS Id,
			FE.AcademicId,
			vSA.Code,
			vSA.Name,
			vSA.ClassName +' - '+vSA.DivisionName AS ClassDivision,
			FM.Title AS FeeName,
			FE.ExpenseAmount,
			FE.ExpenseDate,
			FE.ExpenseRemark,
			ISNULL(FE.FeeExpenseTypeId,0) AS FeeExpenseTypeId,
			ISNULL(FETM.Title,'') AS FeeExpenseType,
			ISNULL(FE.FeeSetupId,0) AS FeeSetupId
	FROM
			sFee.tFeeExpense FE
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = FE.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sStudent.vStudentAcademic vSA ON FE.AcademicId = vSA.AcademicId
			INNER JOIN sFee.tFeeExpenseTypeMaster FETM ON FETM.Id = FE.FeeExpenseTypeId
	WHERE
			((FE.AutoId = @rId) OR (@rId=0))
			AND vSA.OrgId= @rOrgId
			AND vSA.BatchId = @rBatchId 
			AND ((vSA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND	((vSA.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vSA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND	((FE.FeeSetupId = @rFeeSetupId) OR (@rFeeSetupId = 0))
			AND ((FE.ExpenseDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		    AND ((FE.ExpenseDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		    AND	((FE.FeeExpenseTypeId = @rFeeExpenseTypeId) OR (@rFeeExpenseTypeId = 0))
		    AND ((FS.AdmissionCategoryId = @rFeeCategory) OR (@rFeeCategory = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeExpenseTypeMasterAdd]

	 @rOrgGroupId int,
	 @rId int, 
	 @rCode nvarchar(100), 
	 @rTitle nvarchar(100), 
	 @rIsObsolete bit, 
	 @rCreatedUserId bigint, 
	 @rUpdatedUserId bigint  
	       	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sFee.tFeeExpenseTypeMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sFee.tFeeExpenseTypeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sFee.tFeeExpenseTypeMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sFee.tFeeExpenseTypeMaster where Title=@rTitle  AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tFeeExpenseTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFee.tFeeExpenseTypeMaster
		(
			 OrgGroupId,
			 Id,
			 Code,
			 Title,
			 IsObsolete,
			 CreatedUserId,
			 CreatedDateTime,
			 UpdatedUserId, 
			 UpdatedDateTime

		)
	VALUES
		(
			 @rOrgGroupId ,
			 @lNextNumber, 
			 @rCode , 
			 @rTitle , 
			 @rIsObsolete , 
			 @rCreatedUserId , 
			 sCommon.fGetDate(),
			 @rUpdatedUserId  ,			  
			 sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tFeeExpenseTypeMaster
	    SET
			Title=@rTitle,
			Code=@rCode,
			IsObsolete=@rIsObsolete,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pFeeExpenseTypeMasterGet]

	 @rId int,
	 @rOrgGroupId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100),
	 @rIsWildCardSearch bit
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF @rIsWildCardSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			FETM.Id,
			FETM.Code	,	
			FETM.Title,
			
		    FETM.OrgGroupId,
		    FETM.CreatedUserId,
		    FETM.CreatedDateTime,
		    FETM.IsObsolete
		    
	FROM 
			sFee.tFeeExpenseTypeMaster FETM
	WHERE 
		(FETM.OrgGroupId = @rOrgGroupId)
		AND	((FETM.Id = @rId) OR (@rId = 0))
		AND ((FETM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((FETM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
			
	
		
		ORDER BY FETM.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sFee].[pFeeExportDetailsGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(40)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       

CREATE Table #FeeReceiptDetail
		(
		StatusId bigint,
		ReceiptId bigint,
		FeeCode nvarchar(100),
		FeeAmount decimal(12,2),
		Organization nvarchar(max),
		Batch nvarchar(100),
		BatchId bigint,
		Code nvarchar(20),
		ClassDiv nvarchar(200),
		Name nvarchar(300),
		ReceiptNumber nvarchar(200),
		ReceiptDate nvarchar(50),
		ReceiptAmount decimal(12,2),
		PayType nvarchar(300),
		ChequeNo nvarchar(40),
		Remark nvarchar(max),
		ChequeDate nvarchar(50),
		InvoiceNumber int,
		ReceiptCreatedDateTime datetime,
		BankName nvarchar(200),
		ReceiptBookName nvarchar(100),
		TotalReceiptAmount decimal(12,2),
		DiscountAmount decimal(12,2),
		VariableAmount decimal(12,2),
		ExemptionAmount decimal(12,2),
		AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2),
		SUId nvarchar(50),
		CancelDateTime DateTime, --Added for mantis : 36672 by Dhananjay
		CancelRemark nvarchar(500)--Added for mantis : 35507 by Nilesh
		
		)


INSERT INTO #FeeReceiptDetail
 SELECT 
    A.StatusId,    
	R.Id AS ReceiptId,
	FM.Code,
	RD.Amount,
	OM.DisplayTitle AS Organization,  
	BM.Title AS Batch,
	BM.Id AS BatchId,
	A.Code AS Code, 
	CM.Title +' - '+ DM.Title AS ClassDiv,
	A.Name,    
	R.ReceiptNumber,   
	--change by megha for mentis 0027171 start
	--R.ReceiptDate,   
	CONVERT(VARCHAR(10), R.ReceiptDate, 103) AS ReceiptDate, 
   --end
	ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
	PTM.Title AS PayType,    
	CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	R.Remark,
	CONVERT(VARCHAR(10), R.ChequeDate, 103)AS ChequeDate, 
	--ISNULL(CAST(R.ChequeDate AS Date),'') AS ChequeDate, 
	ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	R.CreatedDateTime AS ReceiptCreatedDateTime,
	R.BankName,    
	RBM.Title AS ReceiptBook,    
    ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
    ISNULL(R.DiscountAmount,0)AS DiscountAmount,
	FA.VariableAmount,
	FA.DiscountAmount AS ExemptionAmount,
	FA.AdditionalAmount,
	FA.NotApplicableAmount,
	ISNULL(A.SUId,'') As SUId,
	ISNULL(R.CancelDateTime,'')AS CancelDateTime, --Added for mantis : 36672 by Dhananjay
	ISNULL(R.CancelStatusRemark,'')AS CancelRemark --Added for mantis : 35507 by Nilesh
	
  
  FROM     
  
     sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
  
  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
  LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=A.AcademicId
  
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
 ORDER BY R.ReceiptNumber DESC   
 
 --Select * from #FeeReceiptDetail
 DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT  DISTINCT ',' + QUOTENAME(ID.FeeCode)
                       FROM #FeeReceiptDetail ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')   
 
    SELECT @query = --added (ID.CancelDateTime) & CancelDateTime in left join  by dhanannjay for mantis - 36672
    'SELECT  
			P.*,
            ID.VariableAmount,
            ID.ExemptionAmount,
            ID.AdditionalAmount,
            ID.NotApplicableAmount ,
			ID.DiscountAmount,
			ID.CancelDateTime,
			ID.CancelRemark
			
			
     FROM
    (SELECT  
	
		ReceiptId ,
		Organization ,
		Batch ,
		Code ,
		SUId,
		ClassDiv ,
		Name ,
		ReceiptNumber ,
		ReceiptDate ,
		ReceiptAmount ,
		Remark,
		PayType ,
		ChequeNo ,
		ChequeDate, 
		BankName ,
		ReceiptBookName ,
		InvoiceNumber,    
		ReceiptCreatedDateTime,
		TotalReceiptAmount ,
		FeeCode, 
        FeeAmount
		
				    		
    FROM #FeeReceiptDetail)X
    PIVOT 
    (
         SUM(FeeAmount) 
         FOR [FeeCode] IN (' +  @cols + ')
    ) P
    LEFT JOIN
	(
		SELECT
		    ReceiptId,
			SUM(VariableAmount) AS VariableAmount,
			SUM(ExemptionAmount) AS ExemptionAmount,
			SUM(AdditionalAmount) AS AdditionalAmount,
			SUM(NotApplicableAmount) AS NotApplicableAmount,
			(DiscountAmount) AS DiscountAmount,
			(CancelDateTime) AS CancelDateTime,
			(CancelRemark) AS CancelRemark
			
			
		FROM  
			#FeeReceiptDetail
			GROUP BY ReceiptId,DiscountAmount,CancelDateTime,CancelRemark
    ) ID ON ID.ReceiptId = P.ReceiptId
	Order By P.ReceiptNumber DESC
    '
	EXECUTE(@query) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeFollowupAdd]
		
		@rId	bigint,	
		@rReceiptBookId	int,
		@rAcademicId bigint,
		@rFollowupDate	date=NULL,
		@rFollowupRemark	nvarchar(150),
		@rCreatedUserId	bigint,
		@rHandledBy	nvarchar(100),	
		@rOrgId smallint,
		@rNextFollowupDate date=NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	
		IF(@rId = 0)	
		BEGIN
			DECLARE @lNextNumber BIGINT 
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeFollowup', 0, 1, 1,@outNextNumber = @lNextNumber output
				
			INSERT INTO sFee.tFeeFollowup
			(
				Id,
				ReceiptBookId,
				AcademicId,
				FollowupDate,
				FollowupRemark,
				CreatedUserId,
				CreatedDateTime,
				HandledBy,
				NextFollowupDate
			)
			VALUES
			(
				@lNextNumber,
				@rReceiptBookId,
				@rAcademicId,
				@rFollowupDate,
				@rFollowupRemark,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rHandledBy,
				@rNextFollowupDate
			)
			
			SELECT 1 AS Result, @lNextNumber AS  FeeFollowupId   --FeeFollowupId add for mantis : 0039557
			     
		END	 
		ELSE
		BEGIN
			SET @lNextNumber = @rId
			UPDATE  sFee.tFeeFollowup
			SET
				 ReceiptBookId=@rReceiptBookId,
				 AcademicId = @rAcademicId,
				 FollowupDate=@rFollowupDate,
				 FollowupRemark=@rFollowupRemark,
				 UpdatedUserId=@rCreatedUserId,
				 HandledBy=@rHandledBy,
				 UpdatedDateTime=sCommon.fGetDate(),
				 NextFollowupDate=@rNextFollowupDate
			WHERE Id = @rId 	   
			
			SELECT 11 AS Result, @lNextNumber AS  FeeFollowupId      
		END 
		 
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pFeeFollowupGet]
	
	@rId bigint = 0,
	@rFromDate date='',
	@rToDate date='',
	@rOrgId Smallint=0,
	@rOrgGroupBatchId int = 0,
	@rReceiptBookId int=0,
	@rCode nvarchar(20)='',
	@rFromNextFollowupDate date = '',
	@rToNextFollowupDate date = ''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
		FF.Id,
		vSA.Code,
		FF.ReceiptBookId,
		ISNULL(FF.FollowupDate,'') AS  FollowupDate,
		FF.FollowupRemark,
		FF.HandledBy,
		vSA.Name,
		ISNULL(FF.NextFollowupDate,'') AS NextFollowupDate,
		vSA.OrgId,
		OM.DisplayTitle AS OrgName,
		vSA.RollNo,
		vSA.ParentContactNo,
		ClassDivision,
		DM.OrderIndex  AS DivisionOrderIndex,
		vSA.AcademicId
	FROM 
		sFee.tFeeFollowup FF
		INNER JOIN sStudent.vStudentAllDetail vSA ON  vSA.AcademicId = FF.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
	WHERE  
		(FF.Id = @rId OR @rId = 0)
		AND (FF.FollowupDate>= @rFromDate OR ISNULL(@rFromDate,'')='')
		AND (FF.FollowupDate<= @rToDate OR ISNULL(@rToDate,'')='')
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (FF.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (FF.NextFollowupDate>= @rFromNextFollowupDate OR ISNULL(@rFromNextFollowupDate,'')='')
		AND (FF.NextFollowupDate<= @rToNextFollowupDate OR ISNULL(@rToNextFollowupDate,'')='')
	ORDER BY FF.FollowupDate  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeGenerateReport]
	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rCurrentOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rIsObsolete bit,
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rInsertUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int,
	@rIsCommonForOrg bit,
	@rAdmissionCategoryId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rFromReceiptDate IS NULL)
			SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rCurrentOrgId, 'sFee.tFeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tFeeCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgGroupBatchId,
			OrgId,
			BatchId,
			Code,
			FirstName,	
			LastName,
			DivisionId,
			ReceiptBookId,
			FromReceiptDate,
			ToReceiptDate,
			FromReceiptNo,
			ToReceiptNo,
			IsObsolete,
			IsCommon,
			UserId,
			CreatedUserId,
			CreatedDateTime,
			IsCommonForOrg
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgGroupBatchId,
			@rOrgId,
			@rBatchId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rDivisionId,
			@rReceiptBookId,
			@rFromReceiptDate,
			@rToReceiptDate,
			@rFromReceiptNo,
			@rToReceiptNo,
			@rIsObsolete,
			@rIsCommon,
			@rCreatedUserId,
			@rInsertUserId,
			sCommon.fGetDate(),
			@rIsCommonForOrg
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgGroupBatchId=OrgGroupBatchId,
				@rOrgId=OrgId,
				@rBatchId=BatchId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rDivisionId=DivisionId,
				@rReceiptBookId=ReceiptBookId,
				@rFromReceiptDate=FromReceiptDate,
				@rToReceiptDate=ToReceiptDate,
				@rFromReceiptNo=FromReceiptNo,
				@rToReceiptNo=ToReceiptNo,
				@rIsObsolete=IsObsolete,
				@rCreatedUserId=UserId
		FROM
			sFee.tFeeCustomSearch
		WHERE
			Id=@rId
	END
	 
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	  
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	 
		DECLARE @Sql nvarchar(MAX)
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	
		SELECT 
				*
		INTO sFee.tTempFee
		FROM sFee.vFeeCustomSearch FCS
		WHERE 
				(FCS.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
				AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
				AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
				AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
				AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
				AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
				AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
				AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
				AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
				--AND ((ISNULL(FCS.EndDate,'9999-12-31') <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
			    
				AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
			         	          
				AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')	
				AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
				AND (FCS.IsObsolete=@rIsObsolete)
				AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
				AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
				AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
				AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
				AND ((FCS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	     
	     
		SET @rColumnName=Replace(@rColumnName,',ID No',',Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
    
		SET @rColumnName=Replace(@rColumnName,',GR No',',Code')
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
		
		SET @rColumnName=Replace(@rColumnName,'Fees Category','[Fees Category]') --mantis: 42471, add
		SET @rOrderBy=Replace(@rOrderBy,'Fees Category','[Fees Category]') --mantis: 42471, add
			
		 
		--SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')    
		
		
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sFee.tTempFee ORDER BY '+@rOrderBy
			 
		 --print @sql;
		exec(@Sql)
		
		DROP Table sFee.tTempFee
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---
--exec [sFee].[pFeeGeneration] @rOrgId=1101,@rBatchId=110100101,@rClassId=110100002,@rDivisionId=110100003,@rCreatedUserId=1101000000003
---
CREATE OR ALTER PROCEDURE [sFee].[pFeeGeneration]
	 
		   @rOrgId int,
		   @rBatchId int,
           @rClassId int,
           @rDivisionId int,
		   @rCreatedUserId bigint
						 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT batchid,classid,id AS academicid,admissioncategoryid,rownumAcademic 
INTO #temptAcademic 
FROM 
(SELECT batchid,classid,id,admissioncategoryid,ROW_NUMBER() OVER (ORDER BY id) rownumAcademic FROM sStudent.tacademic WHERE orgid=@rOrgId AND batchid=@rBatchId AND classid=@rClassId AND divisionid=@rDivisionId) AS tStudentAcademic

DECLARE @rowcountAcademic BIGINT=0

SELECT @rowcountAcademic = COUNT(rownumAcademic) FROM #temptAcademic

	WHILE (@rowcountAcademic!=0)
	BEGIN

		DECLARE @academicid BIGINT=0
		DECLARE @admissioncategoryid BIGINT=0
		
		SELECT @academicid=academicid,@admissioncategoryid=admissioncategoryid FROM #temptAcademic WHERE rownumAcademic=@rowcountAcademic

		SELECT rownumFeesetup,id AS feesetupid,amount AS feeamount 
		INTO  #temptfeesetup 
		FROM
		(SELECT ROW_NUMBER() OVER (ORDER BY id) rownumFeesetup,id,amount FROM sFee.tfeesetup WHERE batchid=@rBatchId AND classid=@rClassId AND admissioncategoryid=@admissioncategoryid) AS tFeeSetup
		
		DECLARE @rowcountFeesetup BIGINT=0

		SELECT @rowcountFeesetup = COUNT(rownumFeesetup) FROM #temptfeesetup

		WHILE (@rowcountFeesetup!=0)
		BEGIN
		
		BEGIN TRY

			DECLARE @feesetupid BIGINT=0
			DECLARE @feeAmount DECIMAL(12,2)=0.00
			DECLARE @toPayamount NCHAR(10)=0
			DECLARE @paidAmount DECIMAL(12,2)=0.00
			DECLARE @VariableAmount DECIMAL(12,2)=0.00
			DECLARE @DiscountAmount DECIMAL(12,2)=0.00
			DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
			DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
					
			SELECT @feesetupid=feesetupid,@feeAmount=feeamount FROM #temptfeesetup WHERE rownumFeesetup=@rowcountFeesetup
			
			BEGIN TRANSACTION
			
			SELECT @paidAmount=a.amount FROM sFee.treceiptdetail a 
			JOIN sFee.treceipt  b 
			ON b.id=a.receiptid 
			WHERE b.sourceid=@academicid AND a.feesetupid=@feesetupid
						
			SELECT @VariableAmount=FA.[VariableAmount],@DiscountAmount=FA.[DiscountAmount],@AdditionalAmount=FA.[AdditionalAmount],@NotApplicableAmount=FA.[NotApplicableAmount]

			--,@paidamount=FA.PaidAmount
			--,RD.Amount PaidAmount,@rCreatedUserId CreatedUserId,sCommon.fGetDate()CreatedDateTime,@rCreatedUserId UpdatedUserId,sCommon.fGetDate() UpdatedDateTime
			
			FROM [sFee].[tFeeAllocation] AS FA					  
			
			--					LEFT JOIN 					  
			--				  (select a.amount,b.sourceid,a.feesetupid from sFee.treceiptdetail a join sFee.treceipt b on b.id=a.receiptid) AS RD
			--				  on FA.SourceId=RD.sourceid and FA.[FeeSetupId]=RD.feesetupid					  
			
			WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid

			--PRINT @academicid
			--PRINT @feesetupid
			
			IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
			BEGIN

			PRINT 'update'
			--SELECT FA.[SourceId]
			--					  ,FA.[FeeSetupId]
			--					  ,@feeAmount Amount
			--					  ,FA.[VariableAmount]
			--					  ,FA.[DiscountAmount]
			--					  ,FA.[AdditionalAmount]
			--					  ,FA.[NotApplicableAmount]
			--					  ,@toPayamount ToPayment
			--					  ,@paidamount PaidAmount
			--					  --,RD.Amount PaidAmount
			--					  ,@rCreatedUserId CreatedUserId 
			--					  ,sCommon.fGetDate() CreatedDateTime
			--					  ,@rCreatedUserId UpdatedUserId
			--					  ,sCommon.fGetDate() UpdatedDateTime
			--				  FROM [sFee].[tFeeAllocation] as FA					  
			----					LEFT JOIN 					  
			----				  (select a.amount,b.sourceid,a.feesetupid from sFee.treceiptdetail a join sFee.treceipt b on b.id=a.receiptid) AS RD
			----				  on FA.SourceId=RD.sourceid and FA.[FeeSetupId]=RD.feesetupid					  
			--				  where FA.sourceid=@academicid and FA.feesetupid=@feesetupid

				UPDATE [sFee].[tFeeAllocationStudent] 
				SET
					[FeeAmount]=@feeAmount
					,[VariableAmount]=@VariableAmount
					,[DiscountAmount]=@DiscountAmount
					,[AdditionalAmount]=@AdditionalAmount
					,[NotApplicableAmount]=@NotApplicableAmount
					--,[ToPayAmount]=@toPayamount
					,[PaidAmount]=@paidamount
					,[UpdatedUserId]=@rCreatedUserId
					,[UpdatedDateTime]=sCommon.fGetDate()									  
				WHERE academicid=@academicid AND feesetupid=@feesetupid
						
			END
			ELSE
			BEGIN

			PRINT 'insert'

				INSERT INTO [sFee].[tFeeAllocationStudent]
					   ([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
					   ,[PaidAmount],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
				VALUES
					(@academicid,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@toPayamount
					,@paidamount,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())	
				
				--(
				--SELECT FA.[SourceId],FA.[FeeSetupId],@feeAmount,FA.[VariableAmount],FA.[DiscountAmount],FA.[AdditionalAmount],FA.[NotApplicableAmount],@toPayamount
				--		--,@paidamount
				--		,RD.amount,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate()
				--FROM [sFee].[tFeeAllocation] as FA					  
				--LEFT JOIN 					  
				--(select a.amount,b.sourceid,a.feesetupid from sFee.treceiptdetail a join sFee.treceipt b on b.id=a.receiptid) AS RD
				--on FA.SourceId=RD.sourceid and FA.[FeeSetupId]=RD.feesetupid					  
				--where FA.sourceid=@academicid and FA.feesetupid=@feesetupid
				--)

			END
			
				SET @rowcountFeesetup=@rowcountFeesetup-1

			COMMIT TRANSACTION			
			--Success
		END TRY
		BEGIN CATCH 		
				ROLLBACK TRANSACTION
				PRINT @rowcountFeesetup
				PRINT 'fail'
		END CATCH
			
		END
		--drop table #temptfeesetup
		IF OBJECT_ID(N'tempdb..#temptfeesetup') IS NOT NULL
		BEGIN
			DROP TABLE #temptfeesetup
		END

		PRINT @rowcountAcademic

		SET @rowcountAcademic=@rowcountAcademic-1
	END
	
	--drop table #temptAcademic
	PRINT 'success'
	IF OBJECT_ID(N'tempdb..#temptAcademic') IS NOT NULL
	BEGIN
		DROP TABLE #temptAcademic
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeeHeadMasterAdd]
	 
	        @rId int
	       ,@rNumber int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rOrderIndex int
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sFee.tFeeHeadMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from sFee.tFeeHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sFee.tFeeHeadMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If Exists(select Id from sFee.tFeeHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If  Exists(select Id from sFee.tFeeHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sFee.tFeeHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sFee.tFeeHeadMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tFeeHeadMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sFee].[tFeeHeadMaster]
			   (
			    [Id]
			   ,[Number]  
			   ,[Code]
			   ,[Title]
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rCode
			   ,@rTitle
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tFeeHeadMaster]
	    SET
			  Number=@rNumber
	         ,Code=@rCode
	         ,Title=@rTitle
	         ,OrderIndex=@rOrderIndex
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
	      
	      If Not Exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGroupId)
	      BEGIN
			Insert Into sSystem.tPortalSync
			(
				OrgGroupId,
				FeeChange
			)
			Values
			(
				@rOrgGroupId,
				1
			)
	      END
	      Else
	      BEGIN
			Update sSystem.tPortalSync
			Set
				FeeChange=1
			Where OrgGroupId=@rOrgGroupId
	      END
	      
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeeHeadMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId smallint,
           @rIsWildCardSearch bit
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT FHM.Id 
	  ,FHM.Number
      ,FHM.Code
      ,FHM.Title
      ,FHM.OrderIndex
      ,FHM.IsObsolete
     
  FROM [sFee].[tFeeHeadMaster] FHM 
        
  WHERE 
		((FHM.Id = @rId) OR (@rId = 0))
	AND ((FHM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((FHM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND (FHM.OrgGroupId = @rOrgGroupId)
		order by FHM.OrderIndex 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeImportAdd]
	
	@rClassId int=0,
	@rFromBatchId int,
	@rToBatchId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rAddMonthInDate int = 0,
	@rOrgGroupId int =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

	IF EXISTS (SELECT 1 FROM sFee.tFeeSetup WHERE BatchId = @rToBatchId AND ((ClassId = @rClassId) OR (@rClassId=0)))
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	
	BEGIN TRANSACTION
	Declare @lCount int
	DECLARE @lNextNumber INT
	-- Fee Setup Temp Table
	CREATE TABLE #TempFeeMaster(
	[AutoId] int identity,
	[Id] [int] NOT NULL,
	[ClassId] [int] NULL,
	[AdmissionCategoryId] [int] NULL,
	[BatchId] [int] NOT NULL,
	[FeeId] [int] NOT NULL,
	[IsVariable] [bit] NOT NULL,
	[IsOptional] [bit] NULL,
	[Amount] [decimal](12, 2) NOT NULL,
	[StartDate] [date] NOT NULL,
	[EndDate] [date] NOT NULL,
	[ReceiptBookId] [int] NULL,
	[CreatedUserId] [bigint] NOT NULL,
	[CreatedDateTime] [datetime] NOT NULL,
	[UpdatedUserId] [bigint] NULL,
	[UpdatedDateTime] [datetime] NULL,
	[IsServiceTax] [bit] NULL,
	[CollectionGroupId] [int] NULL,
	[FeeDuration] [nvarchar](100),
	[OldFeeSetupId]	[int],		
	[LevelAmount] [decimal](12,2),
	[LateFeeRuleId] [int]
	)
	-- End Create Table
	
	INSERT INTO #TempFeeMaster SELECT * FROM sFee.tFeeSetup WHERE BatchId=@rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
	
	Select @lCount = COUNT(Id) From #TempFeeMaster
	
	While (@lCount > 0)
	BEGIN
		-- Collection Group Entry
		
		DECLARE @lOrgGroupBatchId int =0
		DECLARE @lCollectionGroupId int=0 
		DECLARE @lReceiptBookId int=0
		DECLARE @lCode nvarchar(20)=''
		DECLARE @lTitle nvarchar(100)=''
		
		SELECT @lReceiptBookId=ReceiptBookId,@lCollectionGroupId=CollectionGroupId FROM #TempFeeMaster WHERE AutoId = @lCount
		SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rToBatchId
		SELECT @lCode=Code,@lTitle=Title FROM sFee.tCollectionGroupMaster WHERE Id = @lCollectionGroupId
		
		IF NOT EXISTS (SELECT 1 FROM sFee.tCollectionGroupMaster WHERE Code=@lCode AND Title=@lTitle AND OrgGroupBatchId=@lOrgGroupBatchId AND ReceiptBookId=@lReceiptBookId)
		BEGIN
			DECLARE @lNumber int=0
			DECLARE @lOrderIndex smallint=0 
			SELECT @lOrderIndex=MAX(OrderIndex) FROM sFee.tCollectionGroupMaster WHERE OrgGroupBatchId = @lOrgGroupBatchId
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tCollectionGroupMaster', 0, 1, 1,@outNextNumber = @lNumber output
			INSERT INTO sFee.tCollectionGroupMaster
			SELECT 
				@lOrgGroupBatchId,@lNumber,Code,Title,DATEADD(MONTH,@rAddMonthInDate,StartDate),DATEADD(MONTH,@rAddMonthInDate,EndDate),
				Remark,IsObsolete,@lOrderIndex,ReceiptBookId,FooterRemark1,FooterRemark2,FeePeriod,IsDisplayCashDetailInFolio,ReportId,IsOnPrePrinted
			FROM sFee.tCollectionGroupMaster Where Id = @lCollectionGroupId
		END 
		
		SELECT @lCollectionGroupId=Id FROM sFee.tCollectionGroupMaster WHERE Code = @lCode AND Title=@lTitle AND OrgGroupBatchId=@lOrgGroupBatchId AND ReceiptBookId=@lReceiptBookId
		
		-- END Collection Group Entry
		
		-- Fee Setup Entry
		
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sFee.tFeeSetup 
		SELECT 
				@lNextNumber,ClassId,AdmissionCategoryId,@rToBatchId,FeeId,ISNULL(IsVariable,0),ISNULL(IsOptional,0),Amount,
				DATEADD(MONTH,@rAddMonthInDate,StartDate),DATEADD(MONTH,@rAddMonthInDate,EndDate),ReceiptBookId,@rCreatedUserId,sCommon.fGetDate(),NULL,NULL,IsServiceTax,@lCollectionGroupId,FeeDuration,Id,LevelAmount,LateFeeRuleId
		FROM #TempFeeMaster Where AutoId = @lCount
		
		-- END Fee Setup Entry
		Set @lCount = @lCount -1
	END

	Drop Table #TempFeeMaster 
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
Drop Table #TempFeeMaster 
		ROLLBACK TRANSACTION
		
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pFeeInvoiceDelete]
	 
		@rFeeInvoiceIds nvarchar(max)='',
		@rOrgId int=0,
		@rBatchId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rOrgGroupBatchId int=0,
		@rCollectionGroupId int=0,
		@rClassId int = 0,
		@rDivisionId int = 0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
BEGIN TRY 
		
		IF(@rFeeInvoiceIds='')
		BEGIN
		
			IF EXISTS(SELECT 1 FROM sFee.tReceipt R 
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=R.SourceId AND R.SourceTypeId = 2001
			WHERE 
			(vSA.OrgId = @rOrgId) AND (vSA.BatchId = @rBatchId)
			AND (R.ReceiptBookId = @rReceiptBookId) AND (vSA.AdmissionCategoryId = @rAdmissionCategoryId)
			AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId) AND ((vSA.ClassId = @rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId=0)) AND FeeInvoiceId IS NOT NULL)
			BEGIN
				SELECT -101 as Result
				RETURN
			END
		
			-- for delete Fee Invoice Detail
			DELETE FID 
				FROM sFee.tFeeInvoiceDetail FID 
				INNER JOIN sFee.tFeeInvoice FI ON FI.Id = FID.FeeInvoiceId
				INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=FI.SourceId AND SourceTypeId = 2001
			WHERE 
				 
				(vSA.OrgId = @rOrgId)
				AND (vSA.BatchId = @rBatchId)
				AND (FI.ReceiptBookId = @rReceiptBookId)
				AND (vSA.AdmissionCategoryId = @rAdmissionCategoryId)
				AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (FI.CollectionGroupId = @rCollectionGroupId)
				AND ((vSA.ClassId = @rClassId) OR (@rClassId=0))
				AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId=0))

			-- for delete Fee Invoice
			DELETE FI 
				FROM sFee.tFeeInvoice FI
				INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=FI.SourceId AND SourceTypeId = 2001
			WHERE 
				(vSA.OrgId = @rOrgId)
				AND (vSA.BatchId = @rBatchId)
				AND (FI.ReceiptBookId = @rReceiptBookId)
				AND (vSA.AdmissionCategoryId = @rAdmissionCategoryId)
				AND (vSA.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (FI.CollectionGroupId = @rCollectionGroupId)
				AND ((vSA.ClassId = @rClassId) OR (@rClassId=0))
				AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId=0))
		END
		ELSE
		BEGIN
			
			IF EXISTS(SELECT 1 FROM sFee.tReceipt R WHERE FeeInvoiceId IN (SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rFeeInvoiceIds,',')))
			BEGIN
				SELECT -101 as Result
				RETURN
			END
			
			-- for delete Fee Invoice Detail
			DELETE FID 
				FROM sFee.tFeeInvoiceDetail FID 
				INNER JOIN sFee.tFeeInvoice FI ON FI.Id = FID.FeeInvoiceId
			WHERE FI.Id IN (SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rFeeInvoiceIds,','))
			
			-- for delete Fee Invoice
			DELETE FI 
				FROM sFee.tFeeInvoice FI
			WHERE FI.Id IN (SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rFeeInvoiceIds,','))
			
		END
		SELECT 1 AS Result
END TRY
BEGIN CATCH
		SELECT -1 AS Result
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sFee].[pFeeInvoiceGenerate]
	
	@rOrgId int,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,
	@rAcademicId bigint,
	@rReceiptBookId int,
	@rCollectionGroupId int,
	@rAdmissionCategoryId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rFeeInvoiceNumber int = 0,
	@rInvoiceDate Date = null
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 
	
	
	
	
	IF EXISTS (
			   SELECT 1 FROM sFee.tFeeInvoice FI INNER JOIN sStudent.vStudentAcademic SA 
			   ON SA.AcademicId = FI.SourceId AND SA.OrgId =@rOrgId AND SA.BatchId=@rBatchId 
			   AND SA.AdmissionCategoryId =@rAdmissionCategoryId AND SA.OrgGroupBatchId =@rOrgGroupBatchId
			   WHERE 
			   FI.BatchId = @rBatchId 
			   AND FI.ReceiptBookId=@rReceiptBookId 
			   AND FI.CollectionGroupId=@rCollectionGroupId 
			   AND FI.OrgGroupBatchId=@rOrgGroupBatchId
			   AND ((SA.AcademicId =@rAcademicId) OR (@rAcademicId=0))
			   AND ((SA.ClassId =@rClassId) OR (@rClassId=0))
			   AND ((SA.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			   )
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	
	

	BEGIN TRANSACTION
	DECLARE @lCount int
	DECLARE @lNextNumber bigint
	
	-- Invoice Student Temp Table
	CREATE TABLE #TempInvoiceStudent
	(
		[AutoId] int identity,
		[SourceId] [bigint] NULL,
		[ClassId] [int] NULL,
		[DivisionId] [int] NULL,
		[BatchId] [int] NULL,
		[AdmissionCategoryId] [int] NULL,
		[OrgGroupBatchId] [int] NULL,
		[PendingAmount] [decimal](12, 2) NULL
	)
	-- End Fee Setup Temp Table
	
	INSERT INTO #TempInvoiceStudent 
	SELECT SA.AcademicId,SA.ClassId,SA.DivisionId,SA.BatchId,SA.AdmissionCategoryId,SA.OrgGroupBatchId,D.PendingAmount
	FROM sStudent.vStudentAcademic SA 
	INNER JOIN 
	(
	SELECT 
		SA.AcademicId,
		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,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA1.AcademicId,
				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=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
			    AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			    AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND ((FS1.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND	((SA1.AcademicId=@rAcademicId) OR (@rAcademicId=0))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA1.AcademicId,
				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=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
		        AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		        AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		        AND ((FS1.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))	
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND	((SA1.AcademicId=@rAcademicId) OR (@rAcademicId=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=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND	((SA1.AcademicId=@rAcademicId) OR (@rAcademicId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	WHERE	
			SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND SA.OrgId = @rOrgId 
			AND SA.BatchId=@rBatchId
			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.AcademicId
	)D ON D.AcademicId=SA.AcademicId
	WHERE SA.BatchId = @rBatchId 
	AND ((SA.AcademicId = @rAcademicId) OR (@rAcademicId=0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId=0))
	AND SA.AdmissionCategoryId=@rAdmissionCategoryId 
	AND SA.OrgGroupBatchId=@rOrgGroupBatchId 
	AND SA.OrgId=@rOrgId AND SA.StatusId = 1
	AND D.PendingAmount > 0
	ORDER BY SA.DivisionOrder,SA.RollNo
	
	SELECT @lCount = COUNT(AutoId) FROM #TempInvoiceStudent

	SET @rFeeInvoiceNumber = @rFeeInvoiceNumber - 1
	
	WHILE (@lCount > 0)
	BEGIN
		SET @rFeeInvoiceNumber = @rFeeInvoiceNumber + 1
		-- Fee Invoice Entry
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeInvoice', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		DECLARE @lInvoiceNumber int
		DECLARE @lAdmissionCategoryId int
		DECLARE @lClassId int
		DECLARE @lSourceId bigint
		DECLARE @lAmount decimal(12,2)
		
		IF(@rFeeInvoiceNumber = 0)
		BEGIN
			SELECT @lInvoiceNumber= ISNULL(max(InvoiceNumber),0)+1 FROM sFee.tFeeInvoice WHERE OrgGroupBatchId = @rOrgGroupBatchId
		END
		ELSE
		BEGIN
		
			SELECT @lInvoiceNumber= ISNULL(max(InvoiceNumber),0)+1 FROM sFee.tFeeInvoice WHERE OrgGroupBatchId = @rOrgGroupBatchId
			
			IF(@lInvoiceNumber > @rFeeInvoiceNumber)
			BEGIN
				SET @lInvoiceNumber = @lInvoiceNumber
			END
			ELSE
			BEGIN
				SET @lInvoiceNumber = @rFeeInvoiceNumber
			END
		END
		
		
		
		SELECT @lAdmissionCategoryId = AdmissionCategoryId,@lClassId=ClassId,@lSourceId=SourceId,@lAmount=PendingAmount FROM #TempInvoiceStudent WHERE AutoId = @lCount
		
		INSERT INTO sFee.tFeeInvoice
		SELECT 
				@lNextNumber,
				2001,
				SourceId, 
				@lInvoiceNumber,
				ISNULL(@rInvoiceDate,sCommon.fGetDate()),
				@lAmount,
				BatchId,
				OrgGroupBatchId,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rReceiptBookId,
				@rCollectionGroupId
		FROM #TempInvoiceStudent 
			Where AutoId = @lCount
		-- END Fee Invoice Entry
		
		-- Fee Invoice Detail Entry
		INSERT INTO sFee.tFeeInvoiceDetail
		SELECT
		    @lNextNumber,
			FS.Id AS FeeSetupId,
			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 
			sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
			FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId AND FS1.ReceiptBookId = @rReceiptBookId AND FS1.CollectionGroupId = @rCollectionGroupId
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lSourceId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = @rBatchId AND FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1 
			AND FS1.ReceiptBookId = @rReceiptBookId AND FS1.CollectionGroupId = @rCollectionGroupId
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lSourceId) AND(FA.SourceTypeId=2001)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId 
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @lSourceId
			AND (R.SourceTypeId = 2001)
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId 
		) R ON R.FeeSetupId = FS.Id	 
		
		WHERE 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
		
		-- END Fee Invoice Detail Entry
		
		-- For Update Invoice Amount
		--DECLARE @lInvoiceAmount decimal(12,2)
		--SELECT @lInvoiceAmount = SUM(Amount) FROM sFee.tFeeInvoiceDetail WHERE FeeInvoiceId=@lNextNumber GROUP BY FeeInvoiceId
		
		--IF(ISNULL(@lInvoiceAmount,0)=0)
		--BEGIN
		--	DELETE FROM sFee.tFeeInvoice WHERE Id=@lNextNumber
		--END
		--ELSE
		--BEGIN
		--	UPDATE sFee.tFeeInvoice SET InvoiceAmount = @lInvoiceAmount WHERE Id=@lNextNumber
		--END
		
		SET @lCount = @lCount -1
	END
	DROP TABLE #TempInvoiceStudent
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY
BEGIN CATCH 
		DROP TABLE #TempInvoiceStudent
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeeInvoiceGet]
		 
		@rOrgGroupBatchId int,
		@rOrgId int=0,
		@rBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rIdNo nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rReceiptBookId int=0,
		@rFromInvoiceNumber int=0,
		@rToInvoiceNumber int=0,
		--@rCreatedUserName nvarchar(100)='',
		@rFromDate date='',
		@rToDate date='',
		@rOrgGroupId int,
		--@rCreatedUserId bigint=0,
		@rCollectionGroupId int = 0,
		@rDepartmentId int=0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			--SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)
		END
BEGIN 		
	SELECT 
		FI.Id AS FeeInvoiceId,
		FI.SourceTypeId AS SourceTypeId,
		SA.Code AS Code,
		SA.RollNo,
		SA.ClassName+' - '+ SA.DivisionName AS Class,
		SA.Name,
		FI.InvoiceNumber,
		FI.InvoiceDate,
		ISNULL(FI.InvoiceAmount,0)AS InvoiceAmount,
		FI.ReceiptBookId,
		RBM.Title AS ReceiptBook,
		OM.DisplayTitle AS Organization,
		FI.BatchId,
		BM.Title AS Batch,
		SA.AcademicId AS SourceId,
		SA.OrgId,
		SA.BatchId,
		CASE WHEN (ISNULL(R.FeeInvoiceId,0) > 0) THEN 'Generated' ELSE 'Pending' END AS ReceiptStatus,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'' ) AS CollectionGroupName,
		ISNULL(R.DepositedLedgerId,0) DepositedLedgerId
		
  FROM 
			sFee.tFeeInvoice FI
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=FI.SourceId	AND (SA.ClassId=@rClassId OR @rClassId=0) 
				AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (SA.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		INNER JOIN sSetup.tClassMaster Cm ON Cm.Id = SA.ClassId
		INNER JOIN sCommon.tSourceTypeMaster STM
			ON STM.Id=FI.SourceTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=FI.ReceiptBookId
		INNER JOIN sFee.tCollectionGroupMaster CGM
			ON CGM.Id = FI.CollectionGroupId
		INNER JOIN sSetup.tOrganizationMaster OM
			ON OM.Id=SA.OrgId AND OM.OrgGroupId=@rOrgGroupId
		INNER JOIN sSetup.tBatchMaster BM
			ON BM.Id=FI.BatchId AND BM.OrgGroupBatchId=@rOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=FI.CreatedUserId
		--INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId
		LEFT JOIN sFee.tReceipt R ON R.SourceTypeId = 2001 AND R.SourceId = FI.SourceId AND R.ReceiptBookId=FI.ReceiptBookId AND R.BatchId = FI.BatchId AND R.OrgGroupBatchId = FI.OrgGroupBatchId
		AND R.FeeInvoiceId = FI.Id
WHERE 
	((SA.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
	AND (FI.SourceTypeId=2001)
	AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
	AND ((FI.InvoiceNumber>=@rFromInvoiceNumber)OR(@rFromInvoiceNumber=0))
	AND ((FI.InvoiceNumber<=@rToInvoiceNumber)OR(@rToInvoiceNumber=0))
	AND ((FI.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
	AND ((FI.CollectionGroupId=@rCollectionGroupId)OR(@rCollectionGroupId=0))
	AND ((FI.InvoiceDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))
	AND ((FI.InvoiceDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))
	AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((FI.BatchId=@rBatchId) OR (@rBatchId=0))
	--AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	ORDER BY FI.InvoiceNumber DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeLeavingToNAAdd]
		@rAcademicId bigint=0,
		@rPendingAmount decimal(18,2)=0,
		@rFeeSetupId int=0,
		@rCreatedUserId bigint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
		IF Exists(SELECT SourceId,FeeSetupId FROM sFee.tFeeAllocation WHERE SourceId = @rAcademicId  AND FeeSetupId = @rFeeSetupId)
			BEGIN
				 UPDATE sFee.tFeeAllocation
				 SET NotApplicableAmount =@rPendingAmount,UpdatedUserId = @rCreatedUserId,UpdatedDateTime=sCommon.fGetDate()
				 WHERE SourceId =@rAcademicId  AND FeeSetupId =@rFeeSetupId
				  SELECT 11 AS Result
			END
		ELSE
		BEGIN 
			INSERT INTO sFee.tFeeAllocation
				(SourceTypeId,SourceId,FeeSetupId,VariableAmount,DiscountAmount,NotApplicableAmount,AdditionalAmount,Remark,CreatedUserId,CreatedDateTime)
			VALUES
			(2001,@rAcademicId,@rFeeSetupId,0,0,@rPendingAmount,0,'',@rCreatedUserId,sCommon.fGetDate())
			 SELECT 1 AS Result 
		END

		-- For Fee Process Added By Hemali 2025-01-31
		IF Exists(SELECT AcademicId,FeeSetupId FROM sFee.tFeeAllocationStudent WHERE AcademicId =@rAcademicId  AND FeeSetupId =@rFeeSetupId)
			BEGIN
				 UPDATE sFee.tFeeAllocationStudent
				 SET NotApplicableAmount =@rPendingAmount,ToPayAmount = 0, UpdatedUserId = @rCreatedUserId,UpdatedDateTime=sCommon.fGetDate()
				 WHERE AcademicId =@rAcademicId  AND FeeSetupId =@rFeeSetupId
				  SELECT 11 AS Result
			END
		ELSE
		BEGIN 
			INSERT INTO sFee.tFeeAllocationStudent
				(AcademicId,FeeSetupId,FeeAmount,VariableAmount,DiscountAmount,AdditionalAmount,NotApplicableAmount,ToPayAmount, 
				PaidAmount,Remark,CreatedUserId,CreatedDateTime)
			VALUES
			(@rAcademicId,@rFeeSetupId,(select Amount from sFee.tFeeSetup where Id = @rFeeSetupId),0,0,0,@rPendingAmount,0,0,'',@rCreatedUserId,sCommon.fGetDate())
			 SELECT 1 AS Result 
		END
		-- For Fee Process Added By Hemali 2025-01-31

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeeMainGroupOrgGroupwiseAdd]
	
	@rMainGroupOrgGroupwiseImpXml [nvarchar](max),
	@rOrgGroupId int
	--,
	--@rFeeMainGroupId int,
	--@rFeeHeadId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rMainGroupOrgGroupwiseImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId=@rOrgGroupId
	
	 INSERT INTO sFee.tFeeMainGroupOrgGroupwise
		(
			OrgGroupId,
			FeeMainGroupId,
			FeeHeadId
			)
		SELECT
			OrgGroupId,
			FeeMainGroupId,
			FeeHeadId
		FROM OPENXML (@loDoc, '/Table/FeeMainGroupOrgGroupwise', 1)
		WITH ( 
				OrgGroupId int,
				FeeMainGroupId int,
				FeeHeadId int
			  ) 
		
	   SELECT 1 AS Result
	   
	   if Not Exists(Select 1 from sSystem.tPortalSync Where OrgGRoupId=@rOrgGRoupId)
	   BEGIN
		Insert into sSystem.tPortalSync
		(
			OrgGroupId,
			FeeChange
		)
		Values
		(
			@rOrgGroupId,
			1
		)
		END
		Else
		BEGIN
			Update sSystem.tPortalSync
			Set
				FeeChange=1
			Where OrgGroupId=@rOrgGroupId
		END
	    
	   EXEC sp_xml_removedocument @loDoc
	   
	   COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeMainGroupOrgGroupwiseGet]

         @rOrgGroupId int
		 
    WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SELECT   
		FGM.Id AS FeeMainGroupId,
		FGM.Title AS FeeMainGroupName,
		FGM.IsObsolete,
		ISNULL(FMGOG.OrgGroupId,0) AS OrgGroupId,
		--ISNULL(FMGOG.FeeMainGroupId,0) AS FeeMainGroupId,
		ISNULL(FMGOG.FeeHeadId,0) AS FeeHeadId
  FROM 			
	  	sFee.tFeeMainGroupMaster FGM
	  	LEFT JOIN sFee.tFeeMainGroupOrgGroupwise FMGOG ON FGM.Id=FMGOG.FeeMainGroupId
	  	AND FMGOG.OrgGroupId=@rOrgGroupId
		WHERE FGM.IsObsolete=0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeMasterAdd]
	 
	        @rId int
	       ,@rNumber int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFeeHeadId int
           ,@rOrderIndex int
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
		   ,@rDepositHeadId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sFee.tFeeMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from sFee.tFeeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sFee.tFeeMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If Exists(select Id from sFee.tFeeMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If  Exists(select Id from sFee.tFeeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sFee.tFeeMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End


	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sFee.tFeeMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tFeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tFeeMaster]
			   (
			    [Id]
			   ,[Number]  
			   ,[Code]
			   ,[Title]
			   ,[FeeHeadId]
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   ,[DepositHeadId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFeeHeadId
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rDepositHeadId
			   )
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tFeeMaster]
	    SET
			  Number=@rNumber
	         ,Code=@rCode
	         ,Title=@rTitle
	         ,FeeHeadId=@rFeeHeadId
	         ,OrderIndex=@rOrderIndex
             ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate() 
			 ,[DepositHeadId] = @rDepositHeadId
             
	      WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
	      
	      if NOT Exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGroupId)
	      BEGIN
			insert into sSystem.tPortalSync
			(
				OrgGroupId,
				FeeChange
			)
			Values
			(
				@rOrgGroupId,
				1
			)
	      END
	      Else
	      BEGIN
			Update sSystem.tPortalSync
			Set
				FeeChange=1
			Where ORgGroupId=@rOrgGRoupId
	      END
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeMasterBulkAdd]
    
    @rOrgGroupId smallint,
    @rCreatedUserId bigint,
	@rXmldoc [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lFeeId int,
		@lCode nvarchar(20),
		@lNumber int,
		@lTitle nvarchar(100),
		@lFeeHeadId int,
		@lOrderIndex int
		
BEGIN TRANSACTION
			
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
		
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		FeeId int,
		Code nvarchar(20),
		Number int,
		Title nvarchar(100),
		FeeHeadId int,
		OrderIndex int
	)
		
	INSERT INTO #tTable
	(
		FeeId,
		Code,
		Number,
		Title,
		FeeHeadId,
		OrderIndex
	)
	SELECT
		FeeId,
		Code,
		Number,
		Title,
		FeeHeadId,
		OrderIndex
	FROM OPENXML (@intDoc, '/Table/FeeMaster', 1)
	WITH
	( 		
		FeeId int '@FeeId',
		Code nvarchar(20) '@Code',
		Number int '@Number',
		Title nvarchar(100) '@Title',
		FeeHeadId int '@FeeHeadId',
		OrderIndex int '@OrderIndex'
	) WHERE FeeId=0
		
	--EXEC sp_xml_removedocument @intDoc
				
	SELECT @lCount =  COUNT(Id) FROM #tTable

	WHILE @lCount > 0 
	BEGIN
		SELECT		
				@lFeeId=FeeId,
				@lCode=Code,
				@lNumber=Number,
				@lTitle=Title,
				@lFeeHeadId=FeeHeadId,
				@lOrderIndex=OrderIndex
													 	 
		FROM #tTable WHERE Id = @lCount  
		
		DECLARE @lNextNumber BIGINT 
	
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tFeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sFee.tFeeMaster
		(
			OrgGroupId,
			Id,
			Code,
			Number,
			Title,
			FeeHeadId,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete
		)
		VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
			@lCode,
			@lNumber,
			@lTitle,
			@lFeeHeadId,
			@lOrderIndex,
			@rCreatedUserId,
			sCommon.fGetDate(),
			0
		)
		SET @lCount = @lCount - 1
	END	
	
	DELETE FROM #tTable
	
	INSERT INTO #tTable
	(
		FeeId,
		Code,
		Number,
		Title,
		FeeHeadId,
		OrderIndex
	)
	SELECT
		FeeId,
		Code,
		Number,
		Title,
		FeeHeadId,
		OrderIndex
	FROM OPENXML (@intDoc, '/Table/FeeMaster', 1)
	WITH
	( 		
		FeeId int '@FeeId',
		Code nvarchar(20) '@Code',
		Number int '@Number',
		Title nvarchar(100) '@Title',
		FeeHeadId int '@FeeHeadId',
		OrderIndex int '@OrderIndex'
	) WHERE FeeId!=0
		
	EXEC sp_xml_removedocument @intDoc
				
	SELECT @lCount =  COUNT(Id) FROM #tTable

	WHILE @lCount > 0 
	BEGIN
		SELECT		
				@lFeeId=FeeId,
				@lCode=Code,
				@lNumber=Number,
				@lTitle=Title,
				@lFeeHeadId=FeeHeadId,
				@lOrderIndex=OrderIndex
													 	 
		FROM #tTable WHERE Id = @lCount  

		UPDATE sFee.tFeeMaster
		SET
			Code=@lCode,
			Number=@lNumber,
			Title=@lTitle,
			FeeHeadId=@lFeeHeadId,
			OrderIndex=@lOrderIndex
		WHERE Id=@lFeeId
		
		SET @lCount = @lCount - 1
	END	
			
COMMIT TRANSACTION			
	
SELECT 1
--END TRY
--BEGIN CATCH
--ROLLBACK TRANSACTION
--SELECT -1 
--END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeMasterBulkGet]
	 
	 @rOrgGroupId smallint,
	 @rFeeHeadId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			FM.Id,
			FM.Code,
			FM.Number,
			FM.Title,
			FM.FeeHeadId,
			FM.OrderIndex,
			CASE WHEN (SELECT COUNT(*) FROM sFee.tFeeSetup FS WHERE FS.FeeId=FM.Id) <= 0 THEN 'True' ELSE 'False' END AS IsObsolete
  FROM 
            sFee.tFeeMaster FM
       
  WHERE 
			(FM.OrgGroupId=@rOrgGroupId)
		AND ((FM.FeeHeadId=@rFeeHeadId) OR (@rFeeHeadId=0))
		ORDER BY FM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pFeeMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rFeeHeadId int,
           @rOrgGroupId smallint,
           @rIsWildCardSearch bit
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT FM.Id 
	  ,FM.Number
      ,FM.Code
      ,FM.Title
      ,FM.FeeHeadId
      ,FHM.Title AS FeeHead
      ,FM.OrderIndex
      ,FM.IsObsolete
	  ,ISNULL(FM.DepositHeadId,0) AS DepositHeadId
     
  FROM [sFee].[tFeeMaster] FM 
  INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
 
        
  WHERE 
		((FM.Id = @rId) OR (@rId = 0))
	AND ((FM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((FM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((FM.FeeHeadId = @rFeeHeadId) OR (@rFeeHeadId = 0))
	AND (FM.OrgGroupId = @rOrgGroupId)
		order by FM.OrderIndex 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeOpeningAdd]
	
	@rId bigint,
	@rAcademicId bigint,
	@rFeeSetupId int,
	@rOpeningAmount decimal(10,2),
	@rUserId bigint,
	@rIsDelete bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	IF (@rIsDelete = 1)
	BEGIN
		DELETE FROM sFee.tFeeOpening WHERE AcademicId = @rAcademicId AND FeeSetupId=@rFeeSetupId AND AutoId = @rId
	END
	ELSE
	BEGIN
		IF(@rId = 0)	
		BEGIN
			INSERT INTO sFee.tFeeOpening
			(
				AcademicId,
				FeeSetupId,
				OpeningAmount,
				CreatedUserId,
				CreatedDateTime
			)
			VALUES
			(
				@rAcademicId,
				@rFeeSetupId,
				@rOpeningAmount,
				@rUserId,
				sCommon.fGetDate()
			)
			
			SELECT 1 AS Result
		END	 
		ELSE
		BEGIN
			UPDATE sFee.tFeeOpening
			SET
			AcademicId=@rAcademicId,
			FeeSetupId=@rFeeSetupId,
			OpeningAmount=@rOpeningAmount,
			UpdatedUserId=@rUserId,
			UpdatedDateTime=sCommon.fGetDate()
			WHERE AutoId = @rId
			
			SELECT 11 AS Result
		END  			
	END
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeOpeningGet]
	 
	 @rOrgId int,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFeeSetupId int,
	 @rAdmissionCategory int =0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			vSA.AcademicId,
			vSA.Code,
			vSA.Name,
			vSA.ClassName +' - '+vSA.DivisionName AS ClassDivision,
			ISNULL(FO.AutoId,0) AS FeeOpeningId,
			ISNULL(FO.FeeSetupId,0) AS FeeSetupId,
			ISNULL(FO.OpeningAmount,0) AS OpeningAmount,
			CONVERT(BIT,CASE WHEN FO.AutoId IS NOT NULL THEN 1 ELSE 0 END) AS IsChecked
	FROM			
			sStudent.vStudentAcademic vSA
			LEFT JOIN sFee.tFeeOpening FO ON FO.AcademicId = vSA.AcademicId
			AND FO.FeeSetupId = @rFeeSetupId
	WHERE 
			vSA.OrgId= @rOrgId 
			AND vSA.BatchId = @rBatchId 
			AND	vSA.ClassId = @rClassId
			AND	vSA.DivisionId = @rDivisionId
			AND vSA.AdmissionCategoryId = @rAdmissionCategory
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeOpeningImport] 
	@rFeeId INT
	,@rFromBatchId INT
	,@rToBatchId INT
	,@rCreatedUserId BIGINT
	,@rOrgGroupId INT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--IF EXISTS (SELECT 1 FROM sStudent.tAcademic A INNER JOIN sFee.tFeeOpening FO ON A.Id = FO.AcademicId AND A.BatchId = @rToBatchId)
	--BEGIN
	--	SELECT -101 AS RESULT
	--	RETURN
	--END
	BEGIN TRY
		BEGIN TRANSACTION

		DECLARE @lTempFeeOpening TABLE (
			AcademicId BIGINT
			,FeeSetupId INT
			,OpeningAmount DECIMAL(12, 2)
			,LevelAmount DECIMAL(12, 2)
			)

		INSERT INTO @lTempFeeOpening
		SELECT A.Id AS AcademicId
			,FS.Id AS FeeSetupId
			,((ISNULL(R.ReceiptAmount, 0) + ISNULL(FO.OpeningAmount, 0)) - (ISNULL(FE.ExpenseAmount, 0))) AS OpeningAmount
			,ISNULL(FS.LevelAmount, 0) AS LevelAmount
		FROM sStudent.tAcademic A
		INNER JOIN sFee.tFeeSetup FS ON FS.ClassId = A.ClassId
			AND FS.AdmissionCategoryId = A.AdmissionCategoryId
			AND FS.BatchId = A.BatchId
			AND FS.FeeId = @rFeeId
			AND A.BatchId = @rToBatchId
		LEFT JOIN (
			SELECT SUM(ISNULL(RD.Amount, 0)) AS ReceiptAmount
				,A.StudentId
			FROM sStudent.tAcademic A
			INNER JOIN sFee.tReceipt R ON A.Id = R.SourceId
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			WHERE A.BatchId = @rFromBatchId
				AND FS.FeeId = @rFeeId
			GROUP BY A.StudentId
		) R ON R.StudentId = A.StudentId
		LEFT JOIN (
			SELECT SUM(ISNULL(FO.OpeningAmount, 0)) AS OpeningAmount
				,A.StudentId
			FROM sStudent.tAcademic A
			INNER JOIN sFee.tFeeOpening FO ON A.Id = FO.AcademicId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = FO.FeeSetupId
			WHERE A.BatchId = @rFromBatchId
				AND FS.FeeId = @rFeeId
			GROUP BY A.StudentId
		) FO ON FO.StudentId = A.StudentId
		LEFT JOIN (
			SELECT SUM(ISNULL(FE.ExpenseAmount, 0)) AS ExpenseAmount
				,A.StudentId
			FROM sStudent.tAcademic A
			INNER JOIN sFee.tFeeExpense FE ON A.Id = FE.AcademicId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = FE.FeeSetupId
			WHERE A.BatchId = @rFromBatchId
				AND FS.FeeId = @rFeeId
			GROUP BY A.StudentId
		) FE ON FE.StudentId = A.StudentId

		-- Fee Opening	
		UPDATE sFee.tFeeOpening
		SET OpeningAmount = A.OpeningAmount
			,UpdatedUserId = @rCreatedUserId
			,UpdatedDateTime = sCommon.fGetDate()
		FROM (
			SELECT AcademicId
				,FeeSetupId
				,OpeningAmount
			FROM @lTempFeeOpening
			) A
		WHERE sFee.tFeeOpening.AcademicId = A.AcademicId
			AND sFee.tFeeOpening.FeeSetupId = A.FeeSetupId

		INSERT INTO sFee.tFeeOpening (
			AcademicId
			,FeeSetupId
			,OpeningAmount
			,CreatedUserId
			,CreatedDateTime
			)
		SELECT T.AcademicId
			,T.FeeSetupId
			,T.OpeningAmount
			,@rCreatedUserId
			,sCommon.fGetDate()
		FROM @lTempFeeOpening T
		LEFT JOIN sFee.tFeeOpening FO ON FO.AcademicId = T.AcademicId
			AND FO.FeeSetupId = T.FeeSetupId
		WHERE T.OpeningAmount > 0
			AND FO.AcademicId IS NULL
			AND FO.FeeSetupId IS NULL

		-- Fee Allocation
		UPDATE sFee.tFeeAllocation
		SET VariableAmount = A.LevelAmount - A.OpeningAmount
			,UpdatedUserId = @rCreatedUserId
			,UpdatedDateTime = sCommon.fGetDate()
		FROM (
			SELECT AcademicId
				,FeeSetupId
				,LevelAmount
				,OpeningAmount
			FROM @lTempFeeOpening
			) A
		WHERE sFee.tFeeAllocation.SourceId = A.AcademicId
			AND sFee.tFeeAllocation.FeeSetupId = A.FeeSetupId

		INSERT INTO sFee.tFeeAllocation (
			SourceTypeId
			,SourceId
			,FeeSetupId
			,VariableAmount
			,DiscountAmount
			,CreatedUserId
			,CreatedDateTime
			)
		SELECT 2001
			,T.AcademicId
			,T.FeeSetupId
			,T.LevelAmount - T.OpeningAmount
			,0
			,@rCreatedUserId
			,sCommon.fGetDate()
		FROM @lTempFeeOpening T
		LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = T.AcademicId
			AND FA.FeeSetupId = T.FeeSetupId
		WHERE T.OpeningAmount > 0
			AND FA.SourceId IS NULL
			AND FA.FeeSetupId IS NULL

		-- For Fee Process Added By Foram on 2025-01-31
		UPDATE FAS
		SET FAS.VariableAmount = A.LevelAmount - A.OpeningAmount
			,FAS.ToPayAmount = (FAS.FeeAmount + (A.LevelAmount - A.OpeningAmount) + FAS.AdditionalAmount - FAS.DiscountAmount - FAS.NotApplicableAmount - FAS.PaidAmount)
			,FAS.UpdatedUserId = @rCreatedUserId
			,FAS.UpdatedDateTime = sCommon.fGetDate()
		FROM sFee.tFeeAllocationStudent FAS
		INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = FAS.AcademicId AND FA.SourceTypeId = 2001
		INNER JOIN (SELECT AcademicId,FeeSetupId,LevelAmount,OpeningAmount FROM @lTempFeeOpening) A ON FA.SourceId = A.AcademicId AND FA.FeeSetupId = A.FeeSetupId
		WHERE FA.SourceId = A.AcademicId 
			AND FA.SourceId = FAS.AcademicId
			AND FA.FeeSetupId = A.FeeSetupId 
			AND FA.FeeSetupId = FAS.FeeSetupId

		INSERT INTO sFee.tFeeAllocationStudent (
			AcademicId
			,FeeSetupId
			,FeeAmount
			,VariableAmount
			,DiscountAmount
			,AdditionalAmount
			,NotApplicableAmount
			,ToPayAmount
			,PaidAmount
			,Remark
			,CreatedUserId
			,CreatedDateTime
			)
		SELECT
			T.AcademicId
			,T.FeeSetupId
			,(SELECT ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = T.FeeSetupId)
			,T.LevelAmount - T.OpeningAmount
			,0
			,0
			,0
			,((SELECT ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = T.FeeSetupId) + (T.LevelAmount - T.OpeningAmount))
			,0
			,''
			,@rCreatedUserId
			,sCommon.fGetDate()
		FROM @lTempFeeOpening T
		INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = T.AcademicId AND FA.FeeSetupId = T.FeeSetupId
		LEFT JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = T.AcademicId AND FAS.FeeSetupId = T.FeeSetupId
		WHERE T.OpeningAmount > 0
			AND FAS.AcademicId IS NULL
			AND FAS.FeeSetupId IS NULL
		-- For Fee Process Added By Foram on 2025-01-31

		SELECT 1 AS Result

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeePaidAllBatchGet]    
      
     
  @rOrgId smallint,    
  @rCode nvarchar(20),
  @rIsObsolete bit = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
      
	BEGIN  
	     
	 SELECT 
		  BM.Title As BatchName,
		  CM.Title +' - '+ DM.Title AS Class ,
		  RBM.Title AS ReceiptBook,
		  R.ReceiptNumber,    
		  R.ReceiptDate,  
		  PTM.Title AS PayType,
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  R.BankName,
		  STUFF((SELECT ', ' + CAST(FM.Title AS VARCHAR(100))  FROM sFee.tReceiptDetail RD INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		   WHERE RD.ReceiptId = R.Id  FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,2,' ') FeeDetail,
		  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
		  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
		  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
		  R.Remark 
	 FROM     
		   sFee.tReceipt R    
		  INNER JOIN sStudent.vStudentAcademic A    
		   ON A.AcademicId=R.SourceId 
   
		  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
		  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
		  INNER JOIN sCommon.tSourceTypeMaster STM    
		   ON STM.Id=R.SourceTypeId    
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
		   ON PTM.Id=R.PayTypeId    
		  INNER JOIN sFee.tReceiptBookMaster RBM    
		   ON RBM.Id=R.ReceiptBookId    
		  INNER JOIN sSetup.tOrganizationMaster OM    
		   ON OM.Id=A.OrgId    

		  INNER JOIN sSetup.tBatchMaster BM    
		   ON BM.Id=R.BatchId     
        
	WHERE     
		 ((A.Code like @rCode) OR (ISNULL(@rCode,'')=''))    
		 AND (R.SourceTypeId=2001)    
		 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
		 AND (R.IsObsolete=@rIsObsolete) 

	ORDER BY R.ReceiptNumber DESC    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeePendingAllOldBatchGet] 
	@rOrgGroupBatchId INT = 0
	,@rBatchId INT = ''
	,@rOrgId INT = 0
	,@rCode NVARCHAR(20) = ''
	,@rUserId BIGINT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT SA.AcademicId
		,SA.RollNo
		,SA.Name
		,SA.Code
		,SA.ClassId
		,SA.DivisionId
		,SA.ClassName
		,SA.DivisionName
		,SA.ClassName + ' - ' + SA.DivisionName AS ClassDivision
		,FS.Id AS FeeSetupId
		,ISNULL(FS.IsVariable, 0) AS IsVariable
		,ISNULL(FS.Amount, 0) AS Amount
		,ISNULL(FS.StartDate, '1900-01-01') AS StartDate
		,ISNULL(FS.EndDate, '1900-01-01') AS EndDate
		,ISNULL(FA.VariableAmount, 0.00) AS FAAmount
		,ISNULL(FA.DiscountAmount, 0.00) AS DiscountAmount
		,ISNULL(FA.AdditionalAmount, 0.00) AS AdditionalAmount
		,ISNULL(R.PaidAmount, 0) AS PaidAmount
		,ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) AS PendingAmount
		,ISNULL(FA.Remark, '') AS Remark
		,FS.ReceiptBookId
		,FS.FeeName
		,FS.FeeCode
		,SA.OrgId
		,O.Title AS OrgName
		,O.OrderIndex AS OrgOrderIndex
		,ISNULL(RBM.Title, '') AS ReceiptBookTitle
		,ISNULL(RBM.OrderIndex, 0) AS ReceiptOrderIndex
		,SA.BatchId
		,BM.Title AS BatchName
		,RT.Pickup AS Pickup
		,RT.DRoppoint AS DRoppoint
		,SC.PresentContactNo
		,ISNULL(SA.SUID, '') AS SUID
		,SA.ClassOrderIndex
		,SA.DivisionOrder AS DivisionOrderIndex
		,FS.OrderIndex AS FeeOrderIndex
	INTO #TempAllPendingFeeBatch
	FROM sStudent.vStudentAcademic SA
	LEFT JOIN [sStudent].[tStudentCommunication] SC ON SC.studentId = SA.studentId
	INNER JOIN (
		SELECT FS1.FeeId
			,FS1.Id
			,ISNULL(FS1.IsOptional, 0) AS IsOptional
			,ISNULL(FS1.IsVariable, 0) AS IsVariable
			,ISNULL(FS1.Amount, 0) AS Amount
			,ISNULL(FS1.StartDate, '1900-01-01') AS StartDate
			,ISNULL(FS1.EndDate, '1900-01-01') AS EndDate
			,FS1.BatchId
			,ISNULL(FS1.ReceiptBookId, 0) AS ReceiptBookId
			,SA1.AcademicId
			,FM.Title AS FeeName
			,FM.Code AS FeeCode
			,FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId = FS1.ClassId
			AND FS1.BatchId = SA1.BatchId
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
		WHERE ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((SA1.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND (FS1.IsOptional = 0)	
			--AND ((FS1.BatchId = @rBatchId) OR (@rBatchId = 0))
			--AND ((SA1.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((SA1.Code = @rCode) OR (@rCode = ''))
		
		
		UNION ALL
		
		SELECT FS1.FeeId
			,FS1.Id
			,ISNULL(FS1.IsOptional, 0) AS IsOptional
			,ISNULL(FS1.IsVariable, 0) AS IsVariable
			,ISNULL(FS1.Amount, 0) AS Amount
			,ISNULL(FS1.StartDate, '1900-01-01') AS StartDate
			,ISNULL(FS1.EndDate, '1900-01-01') AS EndDate
			,FS1.BatchId
			,ISNULL(FS1.ReceiptBookId, 0) AS ReceiptBookId
			,SA1.AcademicId
			,FM.Title AS FeeName
			,FM.Code AS FeeCode
			,FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId = FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FO.SourceId
			AND SA1.BatchId = FS1.BatchId
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND SA1.ClassId = FS1.ClassId
		WHERE 
			((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((SA1.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND (FS1.IsOptional = 1)
			--AND ((FS1.BatchId = @rBatchId) OR (@rBatchId = 0))
			--AND ((SA1.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((SA1.Code = @rCode) OR (@rCode = ''))
			
		) 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 = @rOrgId) OR (@rOrgId = 0))
			AND (R.IsObsolete = 0)
			AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			--AND ((R.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((R.CreatedUserId = @rUserId) OR (@rUserId = 0))
			AND ((SA1.Code = @rCode) OR (@rCode = ''))
		GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id
		AND SA.AcademicId = R.SourceId
	INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
	INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId = RBM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SA.StudentId
		AND AR.SourceTypeId = 2003
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))
	LEFT JOIN (
		SELECT AT.SourceId
			,B.OrgGroupBatchId
			,B.Title AS Pickup
			,B1.Title AS DRoppoint
		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)
				)
		LEFT JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id = AT.DropDestinationId
		LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id = BM1.BusRouteId
			AND AT.SourceTypeId = 2003
			AND (
				(B1.OrgGroupBatchId = @rOrgGroupBatchId)
				OR (@rOrgGroupBatchId = 0)
				)
		) RT ON RT.SourceId = SA.StudentId
		AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
		AND (
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			OR (@rOrgGroupBatchId = 0)
			)
	WHERE (
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			OR (@rOrgGroupBatchId = 0)
			)
		--AND (
		--	(SA.BatchId = @rBatchId)
		--	OR (@rBatchId = 0)
		--	)
		AND (
			(SA.Code = @rCode)
			OR (@rCode = '')
			)
		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)
	ORDER BY SA.RollNo

	DECLARE @lBatchOrderIdex smallint = 0
	SET @lBatchOrderIdex = (SELECT OrderIndex FROM sSetup.tBatchMaster WHERE Id = @rBatchId) 

	SELECT T.OrgId
		,T.ReceiptBookId
		,T.AcademicId
		,T.DivisionId
		,T.ClassDivision
		,T.RollNo
		,T.Name
		,T.Code
		,T.ReceiptBookTitle
		,T.OrgName
		,SUM(T.PendingAmount) AS PendingAmount
		,(SELECT STUFF((
				SELECT ', ' + FeeCode
				FROM 
				(SELECT FeeCode, FeeOrderIndex FROM 
				#TempAllPendingFeeBatch
				WHERE T.AcademicId = AcademicId 
				AND T.ReceiptBookId = ReceiptBookId
				AND T.BatchId = BatchId
				GROUP BY FeeCode, FeeOrderIndex)
				AS A
				ORDER BY FeeOrderIndex
				FOR XML PATH('')
				), 1, 1, '')) AS PendingFeeName 
		--'[sFee].[fPendingFeeNamesGet]'(AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
		,T.ReceiptOrderIndex
		,T.BatchId
		,T.BatchName
		,T.Pickup
		,T.DRoppoint
		,T.PresentContactNo
		,T.SUID
		,T.ClassOrderIndex
		,T.DivisionOrderIndex
		,BM.OrderIndex AS BatchOrderIndex
	FROM #TempAllPendingFeeBatch T
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = T.BatchId 
	WHERE BM.OrderIndex < @lBatchOrderIdex
	GROUP BY T.OrgId
			,T.AcademicId
			,T.ReceiptBookId
			,T.DivisionId
			,T.BatchId
			,T.ClassDivision
			,T.RollNo
			,T.Name
			,T.Code
			,T.ReceiptBookTitle
			,T.OrgName
			,T.ReceiptOrderIndex
			,T.BatchName
			,T.Pickup
			,T.DRoppoint
			,T.PresentContactNo
			,T.SUID
			,T.ClassOrderIndex
			,T.DivisionOrderIndex
			,BM.OrderIndex
	
	ORDER BY AcademicId DESC 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pFeePendingAmountGet]
	 
	 @rAcademicId bigint,
	 @rReceiptBookId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  SELECT
	ISNULL((
	SELECT 
		ISNULL(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)),0) AS PendingAmount
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE (SA1.Id=@rAcademicId) 
			AND FS1.ReceiptBookId = @rReceiptBookId
				 				
			
			UNION ALL
			
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			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
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id  
		WHERE (SA1.AcademicId=@rAcademicId) 			
		AND FS1.ReceiptBookId = @rReceiptBookId
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceId = @rAcademicId)
				AND FS.ReceiptBookId = @rReceiptBookId
				AND R.IsObsolete = 0
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	WHERE	
			SA.AcademicId  = @rAcademicId
	GROUP BY SA.AcademicId		
	),0) AS PendingAmount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeePendingDashboardGet]
	 
	 @rType nvarchar(100)='',
	 
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId bigint=0,
	 @rDivisionId int=0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
  SELECT
	(
	SELECT 
		ISNULL(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)),0) AS PendingAmount
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND( BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)
			WHERE 
			    (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
			    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
			
			UNION ALL
			
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			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
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)
		WHERE
		        (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
			    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((LEFT( BM.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0))
			    AND (( BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId=0)
			    AND LEFT( R.OrgGroupBatchId,4) = @rOrgGroupId
			    AND ( R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= CONVERT(DATE,Getdate()))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO 
			ON SO.StudentId = SA.StudentId
		 INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	WHERE	
			(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0 )
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND ((FS.StartDate <= CONVERT(DATE,Getdate())))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
			AND SA.StatusId = 1
	) AS PendingAmount
  END
  
  IF(@rType='ReceiptBook')
  BEGIN
	SELECT 
		RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)
			WHERE 
			    (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId =0)
			    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
			
			UNION ALL
			
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			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
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)
		WHERE
		        (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
			    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0)) 
			    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
			    AND (LEFT(R.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
			    AND ((R.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
				AND (R.ReceiptDate <= CONVERT(DATE,Getdate()))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO 
			ON SO.StudentId = SA.StudentId
		 INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	WHERE	
			(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
			AND ((sA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((FS.StartDate <= CONVERT(DATE,Getdate())))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
			AND SA.StatusId = 1
	GROUP BY RBM.Id,RBM.Title
  END
  
  IF(@rType='Division')
  BEGIN
	SELECT 
		SA.DivisionId,SA.ClassName +' - '+ SA.DivisionName AS DivisionClass,
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)
			WHERE 
			    (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
			    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
			    AND ((FS1.ReceiptBookId = @rReceiptBookId)  OR(@rReceiptBookId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
			
			UNION ALL
			
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			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
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)
		WHERE
		        (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId = 0))
			    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId)OR (@rOrgGroupBatchId = 0))
		        AND ((FS1.ReceiptBookId = @rReceiptBookId)  OR(@rReceiptBookId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR( @rOrgGroupId =0))
			    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR( @rOrgGroupBatchId =0))
			    AND (LEFT(R.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
			    AND ((R.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
				AND (R.ReceiptDate <= CONVERT(DATE,Getdate()))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO 
			ON SO.StudentId = SA.StudentId
		 INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	WHERE	
			(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((FS.StartDate <= CONVERT(DATE,Getdate())))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
			AND SA.StatusId = 1
	GROUP BY SA.DivisionId,SA.ClassName,SA.DivisionName
  END
  
  IF(@rType='Student')
  BEGIN
	SELECT 
		SA.Code,SA.Name,
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			WHERE 
			    (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
			     AND ((FS1.ReceiptBookId = @rReceiptBookId)  OR(@rReceiptBookId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND ((SA1.DivisionId = @rDivisionId)OR (@rDivisionId=0))
			
			UNION ALL
			
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			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
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)
		WHERE
		        (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
		        AND ((FS1.ReceiptBookId = @rReceiptBookId)  OR(@rReceiptBookId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND ((SA1.DivisionId = @rDivisionId)OR (@rDivisionId=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.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
				AND (LEFT(R.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
				AND ((R.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId =0))
				AND (R.ReceiptDate <= CONVERT(DATE,Getdate()))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND SA1.DivisionId = @rDivisionId
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO 
			ON SO.StudentId = SA.StudentId
		 INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	WHERE	
			(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId =0))
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR( @rOrgGroupBatchId =0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((FS.StartDate <= CONVERT(DATE,Getdate())))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
			AND SA.DivisionId = @rDivisionId
			AND SA.StatusId = 1
	GROUP BY SA.Code,SA.Name
  END
  
  IF(@rType='OrgGroup')
  BEGIN
	SELECT 
		SA.OrgId,SA.OrganizationName,
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)
			WHERE 
			    (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR  (@rOrgGroupId =0 ))
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId =0))
			   -- AND FS1.ReceiptBookId = @rReceiptBookId
				--AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=0)
				--AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				--AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				--AND SA1.DivisionId = @rDivisionId
			
			UNION ALL
			
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			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
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId =0)
		WHERE
		        (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR(@rOrgGroupId=0))
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId =0))
		       -- AND FS1.ReceiptBookId = @rReceiptBookId
				--AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=1)
				--AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				--AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				--AND SA1.DivisionId = @rDivisionId
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				--AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR(@rOrgGroupId=0))
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
				AND (LEFT(R.OrgGroupBatchId,4) = @rOrgGroupId OR(@rOrgGroupId=0))
				AND ((R.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId =0))
				AND (R.ReceiptDate <= CONVERT(DATE,Getdate()))
				--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				--AND SA1.DivisionId = @rDivisionId
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO 
			ON SO.StudentId = SA.StudentId
		 INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	WHERE	
			(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR(@rOrgGroupId=0))
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			--AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((FS.StartDate <= CONVERT(DATE,Getdate())))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
			--AND SA.DivisionId = @rDivisionId
			AND SA.StatusId = 1
	GROUP BY SA.OrgId,SA.OrganizationName
  END
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeePendingListGet]
		
		@rOrgGroupBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rCode nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rLastName nvarchar(100) = '',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rSUId nvarchar(50) = '',
		@rUptoDate date='',
		@rFromNextFollowupDate date='',
		@rToNextFollowupDate date=''
		,@rClassStatusId int=0 --add for mantis : 0042127
		,@rStatusId int=0--add for mantis : 0042127
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END		 
BEGIN 	
	
	DECLARE @p AS TempPendingFee
	
	INSERT INTO @p 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		--change by megha for 0027384
	    '' AS FatherContactNo,
		'' AS MotherContactNo,
		'' AS WhatsAppContactNo --added by dhananjay for : 37272

  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (SA1.StatusId=@rStatusId OR @rStatusId=0)  --add for mantis : 0042127
				AND (SA1.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) --add for mantis : 0042127
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (SA1.StatusId=@rStatusId OR @rStatusId=0)  --add for mantis : 0042127
				AND (SA1.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) --add for mantis : 0042127
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (SA1.StatusId=@rStatusId OR @rStatusId=0)  --add for mantis : 0042127
				AND (SA1.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) --add for mantis : 0042127
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId 
		AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.Code=@rSUId) OR (@rSUId=''))
			AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
			AND ((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			--AND SA.	StatusId = 1 --comment for mantis : 0042127
			AND (SA.StatusId=@rStatusId OR @rStatusId=0) --add for mantis : 0042127
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))			
			AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) --add for mantis : 0042127
			
			ORDER BY SA.RollNo
 
			SELECT
				Temp.OrgId,			 
				Temp.ReceiptBookId,
				Temp.AcademicId,
				Temp.DivisionId,
				Temp.ClassDivision,
				Temp.RollNo, 
				Temp.Name,
				Temp.Code,
				Temp.ReceiptBookTitle,
				Temp.OrgName,
				SUM(Temp.PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](Temp.AcademicId,Temp.ReceiptBookId,	@p) AS PendingFeeName,
				Temp.ReceiptOrderIndex,
				Temp.BatchId,
				Temp.BatchName,
				SA.SUId AS SUId,
				FF.NextFollowupDate,
				ISNULL(SC.IsStopApplicationAccess,0) as IsStopApplicationAccess,
				ISNULL(SC.StudentCustomAlert,'') as StudentCustomAlert,
				ISNULL(SC.ParentContactNo,'')AS ParentContactNo,
				ISNULL(SC.StudentContactNo,'')AS StudentContactNo,
				ISNULL(SC.WhatsAppContactNo,'')AS WhatsAppContactNo,
				Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex,
				'' AS FatherContactNo,
		        '' AS MotherContactNo
			FROM @p Temp
			LEFT JOIN 
			(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate 
				FROM 
				(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate, 
				ROW_NUMBER() OVER(PARTITION BY AcademicId,ReceiptBookId ORDER BY NextFollowupDate DESC) AS RowNumber
				FROM sFee.tFeeFollowup FF 
				) AS T
				WHERE RowNumber = 1 
			) FF ON FF.AcademicId = Temp.AcademicId AND FF.ReceiptBookId = Temp.ReceiptBookId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = Temp.AcademicId AND SA.OrgId = Temp.OrgId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
			--change by megha for 0027384
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		WHERE 
			((FF.NextFollowupDate >= @rFromNextFollowupDate) OR (ISNULL(@rFromNextFollowupDate,'') = ''))
			AND ((FF.NextFollowupDate <= @rToNextFollowupDate) OR (ISNULL(@rToNextFollowupDate,'') = ''))
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)  --add for mantis : 0042127
			AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) --add for mantis : 0042127
		GROUP BY 
			Temp.OrgId,Temp.AcademicId,Temp.ReceiptBookId,Temp.DivisionId,Temp.BatchId,
			Temp.ClassDivision,Temp.RollNo, Temp.Name,Temp.Code,Temp.ReceiptBookTitle,
			Temp.OrgName,Temp.ReceiptOrderIndex,Temp.BatchName,FF.NextFollowupDate,
			SC.IsStopApplicationAccess,SC.StudentCustomAlert,SC.ParentContactNo,SC.StudentContactNo,SC.WhatsAppContactNo,SA.SUId,Temp.ClassOrderIndex,
			Temp.DivisionOrderIndex
			ORDER BY Temp.AcademicId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeePendingUserAccessWiseGet]
(
	@rBatchId int,
	@rUserId Bigint,
	@rOrgId smallint,
	@rClassId int =0,
	@rDivissionId int=0
)
AS
SET NOCOUNT ON
	
BEGIN 

DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

CREATE TABLE #DivisionTemp
(
DivisionId int
)
INSERT INTO #DivisionTemp
SELECT 
	DM.Id 
	FROM sSetup.tClassMaster CM
		INNER JOIN sSetup.tDivisionMaster DM  ON CM.Id = DM.ClassId
		INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id = DM.OrgId
		Inner JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM.Id AND UA.SourceTypeId=2005 AND (UA.UserId=@rUserId) 
	WHERE   (CM.Id=@rClassId or @rClassId=0) AND (DM.Id=@rDivissionId Or @rDivissionId=0)
--select * from #DivisionTemp
SELECT 
		SA.StudentId,SA.RollNo,SA.Code,SA.Name,FS.FeeName,Isnull(SC.StudentContactNo,'') AS StudentContactNo,
		Sum(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount,FS.OrderIndex
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE 
			    (LEFT(BM.OrgGroupBatchId,4) = @lOrgGroupId OR (@lOrgGroupId=0))
				--AND ((BM.OrgGroupBatchId = 0) OR (0 =0))
			     --AND ((FS1.ReceiptBookId = 0)  OR(0=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND ((SA1.DivisionId in (SELECT * FROM #DivisionTemp)))
			
			UNION ALL
			
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id 
		WHERE
		        (LEFT(BM.OrgGroupBatchId,4) = @lOrgGroupId OR (@lOrgGroupId =0))
				--AND ((BM.OrgGroupBatchId = 0) OR (0 =0))
		        --AND ((FS1.ReceiptBookId = 0)  OR(0=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND ((SA1.DivisionId in (select * from #DivisionTemp)))
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND (LEFT(BM.OrgGroupBatchId,4) = @lOrgGroupId OR (@lOrgGroupId =0))
				--AND ((BM.OrgGroupBatchId = 0) OR (0 =0))
				AND (LEFT(R.OrgGroupBatchId,4) = @lOrgGroupId OR (@lOrgGroupId =0))
				--AND ((R.OrgGroupBatchId = 0) OR (0 =0))
				AND (R.ReceiptDate <= CONVERT(DATE,Getdate()))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND SA1.DivisionId In (SELECT * FROM #DivisionTemp)
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO 
			ON SO.StudentId = SA.StudentId
		 INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId
			
	WHERE	
			(LEFT(SA.OrgGroupBatchId,4) = @lOrgGroupId OR (@lOrgGroupId =0))
			--AND ((SA.OrgGroupBatchId = 0) OR( 0 =0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((FS.StartDate <= CONVERT(DATE,Getdate())))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			AND SA.DivisionId in (SELECT * FROM #DivisionTemp)
			AND SA.StatusId = 1
	GROUP BY SA.Code,SA.Name,Fs.FeeName,SA.RollNo,SC.StudentContactNo,SA.StudentId,FS.OrderIndex
	DROP TABLE #DivisionTemp

End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

            CREATE OR ALTER PROCEDURE [sFee].[pFeePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            @rTransactionDate date,
            @rNarration nvarchar(1000),  --Change by dhananjay 150->1000 size for mantis id - 0035082
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rReceiptBookId int,
            @rChequeNo nvarchar(10),
			@rBankName nvarchar(50),
			@rChequeDate datetime,
			@rChequeClearDate datetime=NULL,
			@rPayTypeId int,
			@rSourceTypeId smallint = 0,
			@rSourceId bigint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId And ChequeNo=@rChequeNo AND BankName=@rBankName AND ChequeDate=@rChequeDate
    AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId
    )
    BEGIN
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tAccountPosting
		INSERT INTO [sFee].[tAccountPosting]
		(
			Id,
			AccountId,
			AccountYearId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			ReceiptBookId,
			ChequeNo,
			BankName,
			ChequeDate,
			SourceTypeId,
			SourceId
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountId,
			@1AccountYearId,
			@rTransactionDate,
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rReceiptBookId,
			@rChequeNo,
			@rBankName,
			@rChequeDate,
			@rSourceTypeId,
			@rSourceId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId
	
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting)
	BEGIN
		Delete from [sAccounting].[tTransactionDetail] Where TransactionId in (Select Id From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=1)
		Select Id as result From sAccounting.tTransaction Where SourceId =@lNextNumberPosting
		COMMIT TRANSACTION				
		RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output   
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    1,
			    @lNextNumberPosting,
			    @rChequeNo,
			    @rBankName,
			    @rChequeDate,
			    @rChequeClearDate,
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeePostingDelete]
				
		   --@rClassId int,
           @rTransactionId bigint
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	DELETE FROM sFee.tAccountPosting WHERE Id IN (
	SELECT SourceId FROM sAccounting.tTransaction WHERE ID =@rTransactionId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeePostingDetailAdd]
	 
            @rTransactionId bigint,
            @rNumber bigint,
		    @rLedgerId bigint,
		    @rAmount decimal(12,2),
		    @rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @1TransactionTypeId int 
		
	 SELECT @1TransactionTypeId = LedgerTypeId FROM sAccounting.tLedgerMaster
	 WHERE Id=@rLedgerId

    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tTransactionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
    
	INSERT INTO [sAccounting].[tTransactionDetail]
			   (
			    [Id],
			    [TransactionId],
			    [Number],
			    [TransactionTypeId],
			    [LedgerId],
			    [Amount]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rTransactionId,
			    @rNumber,
			    @1TransactionTypeId,
			    @rLedgerId,
			    @rAmount
			   )
		    SELECT @lNextNumber AS Result
	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeePostingDetailGet]
				
		  -- @rClassId int,
           @rAdmissionCategoryId int=0,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
           @rReceiptDateTo date
            
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	--Mantis Start - 38546
		Declare @IsFeePostingWithoutDiscount nvarchar(50)=''
		SELECT @IsFeePostingWithoutDiscount =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 589 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	--Mantis End - 38546
	SELECT  
			
			AM.FeeSetupId,
			AMast.Id AS AccountId,
			AMast.Title AS AccountName,
			AM.AccountingYearId,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			AM.PayTypeId,
			PTM.Title AS PayTypeName,
			FM.Id AS FeeId,
			FM.Title AS FeeTitle,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FS.ReceiptBookId AS ReceiptBookId,
			RBM.Title AS ReceiptBookTitle,
			--Mantis Start - 38546
					CASE 
					WHEN 
						@IsFeePostingWithoutDiscount = 'True' 
					THEN 
					SUM(ISNULL(R.ReceiptAmount, 0.00))				
					ELSE 
						SUM(ISNULL(RD.Amount, 0.00))
					END AS ReceiptAmount,
			--Mantis End - 38546
			R.ReceiptNumber
			
  FROM 
			sFee.tAccountMapping AM
			INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
			INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate
				AND R.ReceiptDate <= @rReceiptDateTo				
			INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
			--AND (FS.ClassId=@rClassId) 
				AND (FS.AdmissionCategoryId=@rAdmissionCategoryId Or @rAdmissionCategoryId = 0) 
				AND (R.OrgGroupBatchId=@rBatchId)
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId 
		    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		    INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId	
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = AM.PayTypeId
WHERE 
			FM.OrgGroupId=@rOrgGroupId
			
			GROUP BY 
			AMast.Id,AMast.Title,AM.FeeSetupId,AM.AccountingYearId,AYM.Title,AM.CreditLedgerId,CLM.Title,
			AM.DebitLedgerId,DLM.Title,AM.PayTypeId,PTM.Title,FM.Id,FM.Title,FHM.Id,FHM.Title,FS.ReceiptBookId,
			RBM.Title,R.ReceiptNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeePostingGet]
				
	--@rClassId int,
    @rReceiptBookId int,
	@rBatchId int,
	@rOrgGroupId int,
	@rReceiptDate date,
	@rReceiptDateTo date,
	@rChequePosting nvarchar(50),
	@rPayTypeId int = 0 -- mantisid -- 0034607
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

	--Mantis Start - 38660
		Declare @IsFeePostingWithoutDiscount nvarchar(50)=''
		SELECT @IsFeePostingWithoutDiscount =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 589 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	--Mantis End - 38660
	IF @rChequePosting = 'Single'
	BEGIN
			SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					--Mantis Start - 38660
					CASE 
					WHEN 
						@IsFeePostingWithoutDiscount = 'True' 
					THEN 
					SUM(ISNULL(R.ReceiptAmount, 0.00))				
					ELSE 
						SUM(ISNULL(RD.Amount, 0.00))
					END AS ReceiptAmount,
					--Mantis End - 38660

					CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
					R.ChequeDate AS ChequeDate, 
					ISNULL(R.BankName, '') AS BankName,
					R.ChequeClearDate AS ChequeClearDate,R.PayTypeId AS PayTypeId	, 
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					R.ReceiptNumber,
					ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId,  -- Added for mantis 0035150 by Foram
					--Mantis Start - 37360
					ISNULL(R.ChequeNo, '') AS ChequeNo,
					ISNULL(vSA.Name, '') AS Name,
					ISNULL(vSA.Code, '') AS Code,
					ISNULL(PTM.Title, 0) AS PayType
					--Mantis End - 37360
					

			FROM 
					sFee.tAccountMapping AM
					INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
					INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
						AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
					--AND (FS.ClassId=@rClassId) 
						AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0) -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
						AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					LEFT JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId = R.SourceId AND R.SourceTypeId = 2001
					LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.id = R.PayTypeId
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId			
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptNumber	
					,R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,R.PayTypeId,R.ReceiptBookId,R.BankName,R.ChequeNo,vSA.Name,vSA.Code,PTM.Title,ChequeNo,PaymentTransactionId -- Add for kenya client for check details
	 END
	 ELSE
		BEGIN		
		
			
		DECLARE @lConfigValue nvarchar(50)
		DECLARE @lIsAccountPostingBankNameWise bit=0

		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 244 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
		SET @lIsAccountPostingBankNameWise = 0
		ELSE
		SET @lIsAccountPostingBankNameWise = 1	
		
		IF @lIsAccountPostingBankNameWise = 1	
			BEGIN
				  SELECT  
						R.ReceiptDate,
						AMast.Title AS AccountName,
						AYM.Title AS AccountingYearName,
						AM.CreditLedgerId,
						CLM.Title AS CreditLedgerName,
						AM.DebitLedgerId,
						DLM.Title AS DebitLedgerName,
					--Mantis Start - 38546
					CASE 
					WHEN 
						@IsFeePostingWithoutDiscount = 'True' 
					THEN 
					SUM(ISNULL(R.ReceiptAmount, 0.00))				
					ELSE 
						SUM(ISNULL(RD.Amount, 0.00))
					END AS ReceiptAmount,
					--Mantis End - 38546
						'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	,
						ISNULL(AYM.ISLocked,0) AS ISLocked,
						0 as ReceiptNumber,
						ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId,	 -- Added for mantis 0035150 by Foram
						'' AS BankName,
						'' AS ChequeNo,
						'' AS Name,
						'' AS Code,
						0 AS PayType
					FROM 
						sFee.tAccountMapping AM
						INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
						INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
							AND R.PayTypeId = AM.PayTypeId
							AND R.ReceiptDate >= @rReceiptDate 
							AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
							AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
						INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
						--AND (FS.ClassId=@rClassId) 
							AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0) -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
							AND (R.OrgGroupBatchId=@rBatchId)
						INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
						INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
						INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
						INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					WHERE 
						AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptBookId
						
					UNION ALL
					
					SELECT  
						R.ReceiptDate,
						AMast.Title AS AccountName,
						AYM.Title AS AccountingYearName,
						AM.CreditLedgerId,
						CLM.Title AS CreditLedgerName,
						R.DepositedLedgerId AS DebitLedgerId, 
						DLM.Title AS DebitLedgerName,
					--Mantis Start - 38546
						CASE 
						WHEN 
							@IsFeePostingWithoutDiscount = 'True' 
						THEN 
						SUM(ISNULL(R.ReceiptAmount, 0.00))				
						ELSE 
							SUM(ISNULL(RD.Amount, 0.00))
						END AS ReceiptAmount,
					--Mantis End - 38546
						R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,2 AS PayTypeId,
						ISNULL(AYM.ISLocked,0) AS ISLocked,			
						R.ReceiptNumber,
						ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId, -- Added for mantis 0035150 by Foram
						'' AS BankName,
						'' AS ChequeNo,
						'' AS Name,
						'' AS Code,
						0 AS PayType
					FROM 
						sFee.tAccountMapping AM
						INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
						INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
							AND R.PayTypeId = AM.PayTypeId
							AND R.ReceiptDate >= @rReceiptDate 
							AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
							AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
						INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
							AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0)  -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
							AND (R.OrgGroupBatchId=@rBatchId)
						INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
						INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
						INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
						INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=R.DepositedLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					WHERE  R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId			
					Group By R.ReceiptDate,AMast.Title,AYM.Title,AM.CreditLedgerId,
						CLM.Title,R.DepositedLedgerId,DLM.Title,R.ChequeNo,R.ChequeDate,R.BankName,
						R.ChequeClearDate,AYM.IsLocked,R.ReceiptNumber,R.ReceiptBookId
				END
		ELSE
		BEGIN				
				SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					--Mantis Start - 38546
						CASE 
						WHEN 
							@IsFeePostingWithoutDiscount = 'True' 
						THEN 
						SUM(ISNULL(R.ReceiptAmount, 0.00))				
						ELSE 
							SUM(ISNULL(RD.Amount, 0.00))
						END AS ReceiptAmount,
					--Mantis End - 38546
					'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	,
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					0 as ReceiptNumber,
					ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId, -- Added for mantis 0035150 by Foram
					'' AS BankName,
						'' AS ChequeNo,
						'' AS Name,
						'' AS Code,
						0 AS PayType
				FROM  
					sFee.tAccountMapping AM
					INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
					INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
						AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
					--AND (FS.ClassId=@rClassId) 
						AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0)  -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
						AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1
				GROUP BY R.ReceiptDate,AM.CreditLedgerId,AM.DebitLedgerId,
				AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptBookId
					
				UNION ALL
				
				SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					--Mantis Start - 38546
						CASE 
						WHEN 
							@IsFeePostingWithoutDiscount = 'True' 
						THEN 
						SUM(ISNULL(R.ReceiptAmount, 0.00))				
						ELSE 
							SUM(ISNULL(RD.Amount, 0.00))
						END AS ReceiptAmount,
					--Mantis End - 38546
					R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,2 AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					R.ReceiptNumber,
					ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId, -- Added for mantis 0035150 by Foram
					'' AS BankName,
						'' AS ChequeNo,
						'' AS Name,
						'' AS Code,
						0 AS PayType
				FROM 
					sFee.tAccountMapping AM
					INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
					INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
						AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
						AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0)  -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
						AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
				WHERE  R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId			
				Group By R.ReceiptDate,AMast.Title,AYM.Title,AM.CreditLedgerId,
					CLM.Title,AM.DebitLedgerId,DLM.Title,
					R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,AYM.IsLocked,R.ReceiptNumber,R.ReceiptBookId
			END
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
---
--exec [sFee].[pFeeProcessGenerate] @rOrgId=1961,@rBatchId=196100101,@rClassId=196100001,@rCreatedUserId=1961000000003
--,@rDivisionId=110100003,@rAcademicId=1101000000003

CREATE OR ALTER PROCEDURE [sFee].[pFeeProcessGenerate]
	 
		   @rOrgId int,
		   @rBatchId int,
           @rClassId int,
           @rDivisionId int=NULL,
		   @rAcademicId bigint=NULL,
		   @rCreatedUserId bigint,
		   @rFeeSetupId bigint = 0					 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


DELETE FAS FROM [sFee].[tFeeAllocationStudent] FAS 
				JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId
				JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId
WHERE FAS.academicid = ISNULL(@rAcademicId,FAS.academicid) AND A.orgid=@rOrgId AND A.batchid=@rBatchId AND A.classid=@rClassId AND A.divisionid=ISNULL(@rDivisionId,A.divisionid) AND ((FS.Id = @rFeeSetupId) OR (@rFeeSetupId = 0))
		
--PRINT 'DELETED Fee Alloc Student, Academic=='+CAST(@academicid AS VARCHAR)+' Fee Setup=='+CAST(@feesetupid AS VARCHAR)


SELECT batchid,classid,id AS academicid,admissioncategoryid,rownumAcademic 
INTO #temptAcademic 
FROM 
(
	SELECT A.batchid,A.classid,A.id,A.admissioncategoryid,ROW_NUMBER() OVER (ORDER BY A.id) rownumAcademic 
	FROM sStudent.tAcademic  A
	--JOIN [sStudent].[tStudentMaster] SM ON SM.Id=A.StudentId AND SM.StatusId=1
	WHERE A.id=ISNULL(@rAcademicId,A.id) AND A.orgid=@rOrgId AND A.batchid=@rBatchId 
	AND A.classid=@rClassId AND A.divisionid=ISNULL(@rDivisionId,A.divisionid)	
	
) AS tStudentAcademic


DECLARE @rowcountAcademic BIGINT=0
SELECT @rowcountAcademic = COUNT(rownumAcademic) FROM #temptAcademic


WHILE (@rowcountAcademic!=0)
BEGIN

	DECLARE @academicid BIGINT=0
	DECLARE @admissioncategoryid BIGINT=0		
	SELECT @academicid=academicid,@admissioncategoryid=admissioncategoryid FROM #temptAcademic WHERE rownumAcademic=@rowcountAcademic


	SELECT rownumFeesetup,id AS feesetupid,amount AS feeamount,IsOptional,IsVariable 
	INTO  #temptFeeSetup 
	FROM
	(SELECT ROW_NUMBER() OVER (ORDER BY FS.id) rownumFeesetup,FS.id,FS.amount,FS.isoptional,FS.isvariable FROM sFee.tFeeSetup FS
	--LEFT JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId AND FM.IsObsolete=0
	--LEFT JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId AND FHM.IsObsolete=0
	WHERE FS.batchid=@rBatchId AND FS.classid=@rClassId AND FS.admissioncategoryid=@admissioncategoryid
	AND FS.FeeId IN (SELECT Id FROM sFee.tFeeMaster WHERE IsObsolete=0) AND 
	FS.ReceiptBookId IN (SELECT Id FROM sFee.tReceiptBookMaster WHERE IsObsolete=0)
	AND ((FS.Id = @rFeeSetupId) OR (@rFeeSetupId = 0))
	) AS tFeeSetup
	
		
	DECLARE @rowcountFeesetup BIGINT=0
	SELECT @rowcountFeesetup = COUNT(rownumFeesetup) FROM #temptFeeSetup


	WHILE (@rowcountFeesetup!=0)
	BEGIN		
		BEGIN TRY

		DECLARE @feesetupid BIGINT=0
		DECLARE @feeAmount DECIMAL(12,2)=0.00			
		DECLARE @IsOptional Bit=0
		DECLARE @IsVariable Bit=0					
		SELECT @IsOptional=isoptional,@IsVariable=isvariable,@feesetupid=feesetupid,@feeAmount=ISNULL(feeamount,0) FROM #temptFeeSetup WHERE rownumFeesetup=@rowcountFeesetup
		
			
		--PRINT 'RowCountAcademic=='+CAST(@rowcountAcademic AS VARCHAR)+' RowCountFeeSetup=='+CAST(@rowcountFeesetup AS VARCHAR)
		--PRINT 'Is Optional=='+CAST(@IsOptional AS VARCHAR)
		--PRINT 'Is Variable=='+CAST(@IsVariable AS VARCHAR)			
						
			
		DECLARE @toPayamount DECIMAL(12,2)=0.00
		DECLARE @paidAmount DECIMAL(12,2)=0.00
		DECLARE @VariableAmount DECIMAL(12,2)=0.00
		DECLARE @DiscountAmount DECIMAL(12,2)=0.00
		DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
		DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
		DECLARE @Remark NVARCHAR(400)=''


		SELECT @paidAmount=ISNULL(SUM(RD.amount),0) FROM sFee.treceipt  R
		JOIN sFee.tReceiptDetail RD ON RD.receiptid = R.id AND R.IsObsolete = 0
		WHERE R.sourceid=@academicid AND RD.feesetupid=@feesetupid 
		GROUP BY R.sourceid,RD.feesetupid
						
		IF(@IsOptional=1 AND @IsVariable=1)
		BEGIN
				
			--variable amt = var amount from tfeeall and var amt >0 then fee amt = 0				
			SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
			,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')						
			FROM [sFee].[tFeeAllocation] AS FA					  			
			WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid
				
			IF(@VariableAmount>0)BEGIN SET @feeAmount=0 END											
						 
		END
			
		IF(@IsOptional=1 AND @IsVariable=0)
		BEGIN

			--Normal with variable amt 0
			SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
			,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
			FROM [sFee].[tFeeAllocation] AS FA					  			
			WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid

			IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END							

		END

		IF(@IsOptional=0 AND @IsVariable=1)
		BEGIN
				
			--variable amt =0 check isoptional in tfeeoptional with fee set up id and academic id, if 0 no insert else insert

			SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
			,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
			FROM [sFee].[tFeeAllocation] AS FA					  			
			WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid
				
			IF(@VariableAmount>0)BEGIN SET @feeAmount=0 END				

		END

		IF(@IsOptional=0 AND @IsVariable=0)
		BEGIN
				
			--variable amt =0 check isoptional in tfeeoptional with fee set up id and academic id, if 0 no insert else insert

			SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
			,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
			FROM [sFee].[tFeeAllocation] AS FA					  			
			WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid
				
			IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END			

		END

		--Set pending amount
		SET @toPayamount=(@feeAmount+@VariableAmount+@AdditionalAmount)-(@NotApplicableAmount+@DiscountAmount+@paidamount)
			
			
		--PRINT '@feeAmount Amount==' +CAST(@feeAmount AS VARCHAR)
		--PRINT '@VariableAmount Amount==' +CAST(@VariableAmount AS VARCHAR)
		--PRINT '@AdditionalAmount Amount==' +CAST(@AdditionalAmount AS VARCHAR)
		--PRINT '@NotApplicableAmount Amount==' +CAST(@NotApplicableAmount AS VARCHAR)
		--PRINT '@DiscountAmount Amount==' +CAST(@DiscountAmount AS VARCHAR)			
		--PRINT '@paidamount Amount==' +CAST(@paidamount AS VARCHAR)
		--PRINT 'Pending Amount==' +CAST(@toPayamount AS VARCHAR)
		
			
		--Code to insert based on is optional
		IF(@IsOptional=0)
		BEGIN				
			IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
			BEGIN
				IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeClassBatchStatus] WHERE ClassId=@rClassId AND BatchId=@rBatchId)
				BEGIN
					INSERT INTO [sFee].[tFeeClassBatchStatus]
					([ClassId]
					,[BatchId]
					,[StatusId]
					,[UpdatedDateTime])
				VALUES
					(@rClassId
					,@rBatchId 
					,723
					,sCommon.fGetDate())

					--PRINT 'Fee class batch status insert' + CAST(@rowcountFeesetup AS VARCHAR)

				END

				INSERT INTO [sFee].[tFeeAllocationStudent]
						([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
						,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
				VALUES
					(@academicid,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@toPayamount
					,@paidamount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
				--PRINT 'Fee allocation student insert' + CAST(@rowcountFeesetup AS VARCHAR)
			END
		END

		IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@feesetupid AND SourceId=@academicid AND BatchId=@rBatchId AND (@IsOptional=1))
			BEGIN
			IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
			BEGIN
				IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeClassBatchStatus] WHERE ClassId=@rClassId AND BatchId=@rBatchId)
				BEGIN
					INSERT INTO [sFee].[tFeeClassBatchStatus]
					([ClassId]
					,[BatchId]
					,[StatusId]
					,[UpdatedDateTime])
				VALUES
					(@rClassId
					,@rBatchId 
					,723
					,sCommon.fGetDate())

					--PRINT 'Fee class batch status insert' + CAST(@rowcountFeesetup AS VARCHAR)

				END

				INSERT INTO [sFee].[tFeeAllocationStudent]
						([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
						,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
				VALUES
					(@academicid,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@toPayamount
					,@paidamount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
				--PRINT 'Fee allocation student insert' + CAST(@rowcountFeesetup AS VARCHAR)
			END
		END

			
		--PRINT 'Variable Amount=='+CAST(@VariableAmount AS VARCHAR)
		--PRINT 'Fee Amount=='+CAST(@feeAmount AS VARCHAR)					
									
		SET @rowcountFeesetup=@rowcountFeesetup-1

	END TRY
	BEGIN CATCH 		
			PRINT 'fail'+CAST(@rowcountFeesetup AS VARCHAR)
			PRINT 'Academic Id=='+CAST(@academicid AS VARCHAR)
			PRINT 'Fee Setup Id=='+CAST(@feesetupid AS VARCHAR)
			PRINT ERROR_MESSAGE()
			BREAK
	END CATCH			
	END

	--drop table #temptfeesetup
	IF OBJECT_ID(N'tempdb..#temptfeesetup') IS NOT NULL
	BEGIN
		DROP TABLE #temptfeesetup
	END

	--PRINT @rowcountAcademic

	SET @rowcountAcademic=@rowcountAcademic-1
END
	
--drop table #temptAcademic	
IF OBJECT_ID(N'tempdb..#temptAcademic') IS NOT NULL
BEGIN
	DROP TABLE #temptAcademic
END

PRINT 'success'

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
--@rOrgId = 9911@lBatchId=991100101,@rAcademicId = 9911000000366,@rReceiptId=,@rCreatedUserId=
CREATE OR ALTER PROCEDURE [sFee].[pFeeProcessGenerateFeeAllocationAdd]

		@rXmlDoc nvarchar(MAX),
		@rOrgId int,
		@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	
	BEGIN TRANSACTION	
	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	SELECT
			ROW_NUMBER() OVER (ORDER BY SourceId) as RowNumberFeeAllocation,
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark
	INTO #TmpFeeAllocation		 
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		Remark nvarchar(200) '@Remark'
	) 

	DECLARE @RowCountFeeAllocation BIGINT=0
	SELECT @RowCountFeeAllocation = COUNT(RowNumberFeeAllocation) FROM #TmpFeeAllocation

	WHILE (@RowCountFeeAllocation!=0)
	BEGIN	
		DECLARE @lSourceId bigint,@lSourceTypeId int,@lFeeSetupId int,@lVariableAmount decimal(12,2),@lDiscountAmount decimal(12,2),@lNotApplicableAmount decimal(12,2)
		DECLARE @lAdditionalAmount decimal(12,2),@lRemark nvarchar(200),@lBatchId bigint

		SELECT @lSourceId = SourceId,@lSourceTypeId = SourceTypeId,@lFeeSetupId = FeeSetupId,
			   @lVariableAmount = VariableAmount,@lDiscountAmount = DiscountAmount,
			   @lNotApplicableAmount = NotApplicableAmount,@lAdditionalAmount = AdditionalAmount,
			   @lRemark = Remark
	    FROM #TmpFeeAllocation 
		WHERE RowNumberFeeAllocation = @RowCountFeeAllocation

		SELECT @lBatchId = BatchId FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

		IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @lSourceId AND A.OrgId=@rOrgId AND A.BatchId=@lBatchId)
		BEGIN
		    
				DECLARE @lFeeAmount decimal(12,2),@lPaidAmount decimal(12,2),@lToPayAmount decimal(12,2)

				SELECT @lFeeAmount = Amount FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId
				SELECT @lPaidAmount = PaidAmount FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lSourceId AND FeeSetupId = @lFeeSetupId
				 
				SET @lToPayAmount = (@lFeeAmount+@lVariableAmount+@lAdditionalAmount)-(@lNotApplicableAmount+@lDiscountAmount+@lPaidAmount)
				 
				UPDATE [sFee].[tFeeAllocationStudent] 
				SET 
				    FeeAmount = @lFeeAmount,
					VariableAmount = @lVariableAmount,
					DiscountAmount = @lDiscountAmount,
					NotApplicableAmount = @lNotApplicableAmount,
					AdditionalAmount = @lAdditionalAmount,
					ToPayAmount = @lToPayAmount,
					Remark = @lRemark,
					UpdatedUserId = @rCreatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 
					AcademicId = @lSourceId
					AND FeeSetupId = @lFeeSetupId
		END
		ELSE
		BEGIN
				SELECT RowNumFeeSetup,Id AS FeeSetupId,Amount AS FeeAmount,IsOptional,IsVariable 
				INTO  #tempFeeSetup 
				FROM
				(SELECT ROW_NUMBER() OVER (ORDER BY FS.id) RowNumFeeSetup,FS.Id,FS.Amount,FS.IsOptional,FS.IsVariable FROM sFee.tFeeSetup FS
				INNER JOIN sStudent.tAcademic A ON FS.ClassId = A.ClassId AND FS.AdmissionCategoryId = A.AdmissionCategoryId
				WHERE FS.BatchId=@lBatchId  AND A.Id= @lSourceId
				AND FS.FeeId IN (SELECT Id FROM sFee.tFeeMaster WHERE IsObsolete=0) AND 
				FS.ReceiptBookId IN (SELECT Id FROM sFee.tReceiptBookMaster WHERE IsObsolete=0)
				) AS tFeeSetup
		  
		  
				DECLARE @RowFeesetup BIGINT=0
				SELECT @RowFeesetup = COUNT(RowNumFeeSetup) FROM #tempFeeSetup

				WHILE (@RowFeesetup!=0)
				BEGIN
					DECLARE @FPFeeSetupId BIGINT=0
					DECLARE @FeeAmount DECIMAL(12,2)=0.00			
					DECLARE @IsOptional Bit=0
					DECLARE @IsVariable Bit=0					
					SELECT @IsOptional=IsOptional,@IsVariable=IsVariable,@FPFeeSetupId=FeeSetupId,@FeeAmount=ISNULL(FeeAmount,0) FROM #tempFeeSetup WHERE RowNumFeeSetup=@RowFeesetup

					DECLARE @ToPayAmount DECIMAL(12,2)=0.00
					DECLARE @FPPaidAmount DECIMAL(12,2)=0.00
					DECLARE @VariableAmount DECIMAL(12,2)=0.00
					DECLARE @DiscountAmount DECIMAL(12,2)=0.00
					DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
					DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
					DECLARE @Remark NVARCHAR(400)=''

					SELECT @FPPaidAmount=ISNULL(SUM(RD.Amount),0) FROM sFee.tReceipt  R
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.IsObsolete = 0
					WHERE R.SourceId=@lSourceId AND RD.FeeSetupId=@FPFeeSetupId 
					GROUP BY R.sourceid,RD.feesetupid

					IF(@IsOptional=1 AND @IsVariable=1)
					BEGIN
				
						SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')						
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@lSourceId AND FA.feesetupid=@FPFeeSetupId
				
						IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END											
						 
					END
			
					IF(@IsOptional=1 AND @IsVariable=0)
					BEGIN

						SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@lSourceId AND FA.feesetupid=@FPFeeSetupId

						IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END							

					END

					IF(@IsOptional=0 AND @IsVariable=1)
					BEGIN
				
						SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@lSourceId AND FA.feesetupid=@FPFeeSetupId
				
						IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END				

					END

					IF(@IsOptional=0 AND @IsVariable=0)
					BEGIN
				
						SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@lSourceId AND FA.feesetupid=@FPFeeSetupId
				
						IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END			

					END

					SET @ToPayAmount=(@FeeAmount+@VariableAmount+@AdditionalAmount)-(@NotApplicableAmount+@DiscountAmount+@FPPaidAmount)

					IF(@IsOptional=0)
					BEGIN
						IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.AcademicId=@lSourceId AND FAS.FeeSetupId=@FPFeeSetupId)
						BEGIN
						 
							INSERT INTO [sFee].[tFeeAllocationStudent]
									([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
									,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
							VALUES
								(@lSourceId,@FPFeeSetupId,@FeeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@ToPayAmount
								,@FPPaidAmount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
						END
					END

					IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@lFeeSetupId AND SourceId=@lSourceId AND BatchId=@lBatchId AND (@IsOptional=1))
					BEGIN
						IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@lSourceId AND FAS.feesetupid=@FPFeeSetupId)
						BEGIN
						
							INSERT INTO [sFee].[tFeeAllocationStudent]
									([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
									,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
							VALUES
								(@lSourceId,@FPFeeSetupId,@FeeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@ToPayAmount
								,@FPPaidAmount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())
						END 
					END 
					SET @RowFeesetup=@RowFeesetup-1
				END

				DROP TABLE #tempFeeSetup
		END
		SET @RowCountFeeAllocation=@RowCountFeeAllocation-1
	END
	 
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
--@rOrgId = 9911@lBatchId=991100101,@rAcademicId = 9911000000366,@rReceiptId=,@rCreatedUserId=
CREATE OR ALTER PROCEDURE [sFee].[pFeeProcessGenerateFeeOptionalAdd]
		
		@rFeeHeadId bigint = 0,
		@rFeeSetupId bigint = 0,
		@rOrgId int,
		@rBatchId int,
		@rClassId bigint = 0,
		@rAdmissionCategoryId bigint = 0,
		@rCreatedUserId bigint,
		@rSourceId bigint,
		@rSourceTypeId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRANSACTION

	IF (@rFeeSetupId != 0 AND @rFeeHeadId = 0)
	BEGIN
		print 1
		IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @rSourceId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId)
		BEGIN
		
		IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @rSourceId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND FeeSetupId = @rFeeSetupId)
		BEGIN
			DECLARE @feesetupid BIGINT=0
			DECLARE @feeAmount DECIMAL(12,2)=0.00			
			DECLARE @IsOptional Bit=0
			DECLARE @IsVariable Bit=0					
			SELECT @IsOptional=isoptional,@IsVariable=isvariable,@feesetupid=Id,@feeAmount=ISNULL(Amount,0) FROM sFee.tFeeSetup WHERE Id = @rFeeSetupId
		
			DECLARE @toPayamount DECIMAL(12,2)=0.00
			DECLARE @paidAmount DECIMAL(12,2)=0.00
			DECLARE @VariableAmount DECIMAL(12,2)=0.00
			DECLARE @DiscountAmount DECIMAL(12,2)=0.00
			DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
			DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
			DECLARE @Remark NVARCHAR(400)=''


			SELECT @paidAmount=ISNULL(SUM(RD.amount),0) FROM sFee.treceipt  R
			JOIN sFee.tReceiptDetail RD ON RD.receiptid = R.id AND R.IsObsolete = 0
			WHERE R.sourceid=@rSourceId AND RD.feesetupid=@feesetupid 
			GROUP BY R.sourceid,RD.feesetupid
						
			IF(@IsOptional=1 AND @IsVariable=1)
			BEGIN
				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
				,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')						
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@feesetupid
				
				IF(@VariableAmount>0)BEGIN SET @feeAmount=0 END											
			END
			
			IF(@IsOptional=1 AND @IsVariable=0)
			BEGIN

				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
				,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@feesetupid

				IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END							
			END

			IF(@IsOptional=0 AND @IsVariable=1)
			BEGIN
				
				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
				,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@feesetupid
				
				IF(@VariableAmount>0)BEGIN SET @feeAmount=0 END				
			END

			IF(@IsOptional=0 AND @IsVariable=0)
			BEGIN
				
				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
				,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@feesetupid
				
				IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END			
			END
			
			SET @toPayamount=(@feeAmount+@VariableAmount+@AdditionalAmount)-(@NotApplicableAmount+@DiscountAmount+@paidamount)
			
			IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@feesetupid AND SourceId=@rSourceId AND BatchId=@rBatchId AND (@IsOptional=1))
				BEGIN
				IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@rSourceId AND FAS.feesetupid=@feesetupid)
				BEGIN
					INSERT INTO [sFee].[tFeeAllocationStudent]
							([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
							,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
					VALUES
						(@rSourceId,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@toPayamount
						,@paidamount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
				END
			END
		END
		
	END
	END
	ELSE IF(@rFeeHeadId != 0 AND @rFeeSetupId = 0)
	BEGIN
	    
		IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @rSourceId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId)
		BEGIN

			SELECT
				ROW_NUMBER() OVER (ORDER BY FS.Id) as ROWId,
				FS.Id as FeeSetupId
			INTO #TempFeeSetup
			FROM 
				sFee.tFeeSetup FS
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id	 
			WHERE
				FHM.Id = @rFeeHeadId
				AND FS.BatchId = @rBatchId
				AND FS.ClassId = @rClassId
				AND FS.AdmissionCategoryId =@rAdmissionCategoryId 
				AND FS.IsOptional=1
		     
			 
			 DECLARE @Counter int

			 SELECT @Counter = COUNT(ROWId) FROM #TempFeeSetup

			 WHILE (@Counter != 0)
			 BEGIN
				
				DECLARE @lFeeSetupId bigint
				
				SELECT @lFeeSetupId = FeeSetupId FROM #TempFeeSetup WHERE ROWId = @Counter
				 
				IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @rSourceId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND FeeSetupId = @lFeeSetupId)
				BEGIN
					DECLARE @fhfeesetupid BIGINT=0
					DECLARE @fhfeeAmount DECIMAL(12,2)=0.00			
					DECLARE @fhIsOptional Bit=0
					DECLARE @fhIsVariable Bit=0					
					SELECT @fhIsOptional=isoptional,@fhIsVariable=isvariable,@fhfeesetupid=Id,@fhfeeAmount=ISNULL(Amount,0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId
		
					DECLARE @fhtoPayamount DECIMAL(12,2)=0.00
					DECLARE @fhpaidAmount DECIMAL(12,2)=0.00
					DECLARE @fhVariableAmount DECIMAL(12,2)=0.00
					DECLARE @fhDiscountAmount DECIMAL(12,2)=0.00
					DECLARE @fhAdditionalAmount DECIMAL(12,2)=0.00
					DECLARE @fhNotApplicableAmount DECIMAL(12,2)=0.00
					DECLARE @fhRemark NVARCHAR(400)=''


					SELECT @fhpaidAmount=ISNULL(SUM(RD.amount),0) FROM sFee.treceipt  R
					JOIN sFee.tReceiptDetail RD ON RD.receiptid = R.id AND R.IsObsolete = 0
					WHERE R.sourceid=@rSourceId AND RD.feesetupid=@fhfeesetupid 
					GROUP BY R.sourceid,RD.feesetupid
						
					IF(@fhIsOptional=1 AND @fhIsVariable=1)
					BEGIN
						SELECT @fhVariableAmount=ISNULL(FA.[VariableAmount],0),@fhDiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@fhAdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@fhNotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@fhRemark=ISNULL(FA.Remark,'')						
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@fhfeesetupid
				
						IF(@fhVariableAmount>0)BEGIN SET @fhfeeAmount=0 END											
					END
			
					IF(@fhIsOptional=1 AND @fhIsVariable=0)
					BEGIN

						SELECT @fhVariableAmount=ISNULL(FA.[VariableAmount],0),@fhDiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@fhAdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@fhNotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@fhRemark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@fhfeesetupid

						IF(@fhVariableAmount>0)BEGIN SET @fhVariableAmount=0 END							
					END

					IF(@fhIsOptional=0 AND @fhIsVariable=1)
					BEGIN
				
						SELECT @fhVariableAmount=ISNULL(FA.[VariableAmount],0),@fhDiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@fhAdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@fhNotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@fhRemark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@fhfeesetupid
				
						IF(@fhVariableAmount>0)BEGIN SET @fhfeeAmount=0 END				
					END

					IF(@fhIsOptional=0 AND @fhIsVariable=0)
					BEGIN
				
						SELECT @fhVariableAmount=ISNULL(FA.[VariableAmount],0),@fhDiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@fhAdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@fhNotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@fhRemark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@fhfeesetupid
				
						IF(@fhVariableAmount>0)BEGIN SET @fhVariableAmount=0 END			
					END

					SET @fhtoPayamount=(@fhfeeAmount+@fhVariableAmount+@fhAdditionalAmount)-(@fhNotApplicableAmount+@fhDiscountAmount+@fhpaidAmount)
					 
					IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@fhfeesetupid AND SourceId=@rSourceId AND BatchId=@rBatchId AND (@fhIsOptional=1))
						BEGIN
						 
						IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@rSourceId AND FAS.feesetupid=@fhfeesetupid)
						BEGIN
							INSERT INTO [sFee].[tFeeAllocationStudent]
									([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
									,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
							VALUES
								(@rSourceId,@fhfeesetupid,@fhfeeAmount,@fhVariableAmount,@fhDiscountAmount,@fhAdditionalAmount,@fhNotApplicableAmount,@fhtoPayamount
								,@fhpaidAmount,@fhRemark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
						END
					END
				END
				SET @Counter = @Counter - 1
			 END

		END
	END
	COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [sFee].[pFeeProcessGenerateGet] @rOrgId=1101,@rBatchId=110100001
--,@rClassId=110100010
--,@rDivisionId=110100003
--,@rAcademicId=1101000002336
--
CREATE OR ALTER PROCEDURE [sFee].[pFeeProcessGenerateGet]
	 
		   @rOrgId int,
		   @rBatchId int,
           @rClassId int=NULL,
           @rDivisionId int=NULL,
		   @rAcademicId bigint=NULL						 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT CM.Id ClassId,CM.Title,CM.DisplayTitle,
ISNULL(SM.Title,'Pending') AS ClassFeeStatus,
ISNULL(FCBS.Id,0) AS FeeClassBactchStatusId

FROM sSetup.tClassMaster CM 
JOIN sStudent.tAcademic A ON CM.Id=A.ClassId
LEFT JOIN sFee.tFeeClassBatchStatus FCBS ON FCBS.ClassId=CM.Id AND FCBS.BatchId=A.BatchId
LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=FCBS.StatusId AND SM.StatusTypeId=656			

WHERE CM.OrgId=@rOrgId AND A.BatchId=@rBatchId 

AND A.ClassId=ISNULL(@rClassId,A.ClassId) 
AND A.DivisionId=ISNULL(@rDivisionId,A.DivisionId)
AND A.Id=ISNULL(@rAcademicId,A.Id)

GROUP BY CM.Id,CM.Title,CM.Displaytitle,SM.Title,FCBS.Id

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--@rOrgId = 9911@rBatchId=991100101,@rAcademicId = 9911000000366,@rReceiptId=,@rCreatedUserId=
CREATE OR ALTER PROCEDURE [sFee].[pFeeProcessGeneratePaidFeeAdd]
		@rOrgId int,
		@rBatchId int,
	    @rAcademicId bigint,
		@rReceiptId bigint,
		@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WITH (NOLOCK) INNER JOIN sStudent.tAcademic A WITH (NOLOCK) ON A.Id =FAS.AcademicId 
	INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId 
	WHERE FAS.AcademicId = @rAcademicId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId)
	BEGIN
		  SELECT ROW_NUMBER() OVER (ORDER BY FS.Id) as RowNumberFeeSetup,FS.Id AS FeeSetupId,PaidAmount AS PaidAmount,ToPayAmount AS PendingAmount 
		  INTO  #temptFeeSetup 
		  FROM [sFee].[tFeeAllocationStudent] FAS WITH (NOLOCK)
		  INNER JOIN sStudent.tAcademic A WITH (NOLOCK) ON A.Id =FAS.AcademicId 
		  INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId 
		  AND FS.ClassId = A.ClassId
		  WHERE FAS.AcademicId = @rAcademicId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId

		  DECLARE @rowcountFeesetup BIGINT=0
		  SELECT @rowcountFeesetup = COUNT(RowNumberFeeSetup) FROM #temptFeeSetup

		  WHILE (@rowcountFeesetup!=0)
		  BEGIN	
				DECLARE @FeeSetupId BIGINT=0
				DECLARE @PaidAmount DECIMAL(12,2) = 0.00
				DECLARE @PendingAmount DECIMAL(12,2) = 0.00
				DECLARE @ReceiptPaidAmount DECIMAL(12,2) = 0.00

				SELECT @FeeSetupId=FeeSetupId,@PaidAmount=PaidAmount,@PendingAmount=PendingAmount FROM #temptFeeSetup WHERE RowNumberFeeSetup=@rowcountFeesetup

				SELECT @ReceiptPaidAmount = Amount FROM sFee.tReceiptDetail RD WITH (NOLOCK) INNER JOIN sFee.tReceipt R WITH (NOLOCK) ON R.Id = RD.ReceiptId 
				WHERE ReceiptId = @rReceiptId AND FeeSetupId = @FeeSetupId AND R.SourceId = @rAcademicId

				SET @PaidAmount = @PaidAmount + @ReceiptPaidAmount
				SET @PendingAmount = @PendingAmount - @ReceiptPaidAmount

				UPDATE [sFee].[tFeeAllocationStudent] 
				SET 
					ToPayAmount = @PendingAmount,
					PaidAmount = @PaidAmount,
					UpdatedUserId = @rCreatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 
					AcademicId = @rAcademicId
					AND FeeSetupId = @FeeSetupId

				SET @rowcountFeesetup=@rowcountFeesetup-1
		  END

		  DROP TABLE #temptFeeSetup
	END
	ELSE 
	BEGIN
		  SELECT RowNumFeeSetup,Id AS FeeSetupId,Amount AS FeeAmount,IsOptional,IsVariable 
		  INTO  #tempFeeSetup 
		  FROM
		  (SELECT ROW_NUMBER() OVER (ORDER BY FS.id) RowNumFeeSetup,FS.Id,FS.Amount,FS.IsOptional,FS.IsVariable 
		  FROM sFee.tFeeSetup FS WITH (NOLOCK)
		  INNER JOIN sStudent.tAcademic A WITH (NOLOCK) ON FS.ClassId = A.ClassId AND FS.AdmissionCategoryId = A.AdmissionCategoryId
		  WHERE FS.BatchId=@rBatchId  AND A.Id= @rAcademicId
		  AND FS.FeeId IN (SELECT Id FROM sFee.tFeeMaster WHERE IsObsolete=0) AND 
		  FS.ReceiptBookId IN (SELECT Id FROM sFee.tReceiptBookMaster WHERE IsObsolete=0)
		  ) AS tFeeSetup
		  
		  
		  DECLARE @RowFeesetup BIGINT=0
		  SELECT @RowFeesetup = COUNT(RowNumFeeSetup) FROM #tempFeeSetup

		  WHILE (@RowFeesetup!=0)
		  BEGIN
				DECLARE @FPFeeSetupId BIGINT=0
				DECLARE @FeeAmount DECIMAL(12,2)=0.00			
				DECLARE @IsOptional Bit=0
				DECLARE @IsVariable Bit=0					
				SELECT @IsOptional=IsOptional,@IsVariable=IsVariable,@FPFeeSetupId=FeeSetupId,@FeeAmount=ISNULL(FeeAmount,0) FROM #tempFeeSetup WHERE RowNumFeeSetup=@RowFeesetup

				DECLARE @ToPayAmount DECIMAL(12,2)=0.00
				DECLARE @FPPaidAmount DECIMAL(12,2)=0.00
				DECLARE @VariableAmount DECIMAL(12,2)=0.00
				DECLARE @DiscountAmount DECIMAL(12,2)=0.00
				DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
				DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
				DECLARE @Remark NVARCHAR(400)=''

				SELECT @FPPaidAmount=ISNULL(SUM(RD.Amount),0) 
				FROM sFee.tReceipt  R WITH (NOLOCK)
				INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id AND R.IsObsolete = 0
				WHERE R.SourceId=@rAcademicId AND RD.FeeSetupId=@FPFeeSetupId 
				GROUP BY R.sourceid,RD.feesetupid

				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
					,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
					FROM [sFee].[tFeeAllocation] AS FA WITH (NOLOCK)					  			
					WHERE FA.sourceid=@rAcademicId AND FA.feesetupid=@FPFeeSetupId

				IF(@IsOptional=1 AND @IsVariable=1)
				BEGIN
					IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END
				END
			
				IF(@IsOptional=1 AND @IsVariable=0)
				BEGIN
					IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END
				END

				IF(@IsOptional=0 AND @IsVariable=1)
				BEGIN
					IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END
				END

				IF(@IsOptional=0 AND @IsVariable=0)
				BEGIN
					IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END
				END

				SET @ToPayAmount=(@FeeAmount+@VariableAmount+@AdditionalAmount)-(@NotApplicableAmount+@DiscountAmount+@FPPaidAmount)

				IF(@IsOptional=0)
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WITH (NOLOCK) WHERE FAS.AcademicId=@rAcademicId AND FAS.FeeSetupId=@FPFeeSetupId)
					BEGIN
						 
						INSERT INTO [sFee].[tFeeAllocationStudent]
								([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
								,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
						VALUES
							(@rAcademicId,@FPFeeSetupId,@FeeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@ToPayAmount
							,@FPPaidAmount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
					END
				END

				IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WITH (NOLOCK) WHERE FeeSetupId=@feesetupid AND SourceId=@rAcademicId AND BatchId=@rBatchId AND (@IsOptional=1))
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WITH (NOLOCK) WHERE FAS.academicid=@rAcademicId AND FAS.feesetupid=@FPFeeSetupId)
					BEGIN
						
						INSERT INTO [sFee].[tFeeAllocationStudent]
								([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
								,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
						VALUES
							(@rAcademicId,@FPFeeSetupId,@FeeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@ToPayAmount
							,@FPPaidAmount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())
					END 
				END 
			 SET @RowFeesetup=@RowFeesetup-1
		  END

		  DROP TABLE #tempFeeSetup
	END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeProcessGenerateStudentFeeAllocationAdd] 
	@rXmlDoc NVARCHAR(MAX)
	,@rOrgId INT
	,@rCreatedUserId BIGINT
	,@rClassId INT
	,@rDivisionId INT
	,@rSourceTypeId SMALLINT
	,@rSourceId BIGINT
	,@rFeeSetupId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRANSACTION

	CREATE TABLE #TmpFeeAllocation (
		RowNumberFeeAllocation INT
		,SourceTypeId SMALLINT
		,SourceId BIGINT
		,FeeSetupId INT
		,VariableAmount DECIMAL(12, 2)
		,DiscountAmount DECIMAL(12, 2)
		,NotApplicableAmount DECIMAL(12, 2)
		,AdditionalAmount DECIMAL(12, 2)
		,Remark NVARCHAR(200)
		)

	IF (@rFeeSetupId = 0 AND @rClassId = 0 AND @rSourceTypeId != 0 AND @rSourceId != 0) -- Student Fee
	BEGIN
		INSERT INTO #TmpFeeAllocation
		SELECT ROW_NUMBER() OVER (
				ORDER BY SourceId
				) AS RowNumberFeeAllocation
			,FA.SourceTypeId
			,FA.SourceId
			,FA.FeeSetupId
			,FA.VariableAmount
			,FA.DiscountAmount
			,FA.NotApplicableAmount
			,FA.AdditionalAmount
			,FA.Remark
		FROM sFee.tFeeAllocation FA
		WHERE SourceId = @rSourceId
			AND SourceTypeId = @rSourceTypeId

		DECLARE @RowCountFeeAllocation BIGINT = 0
		SELECT @RowCountFeeAllocation = COUNT(RowNumberFeeAllocation) FROM #TmpFeeAllocation

		IF(@RowCountFeeAllocation > 0)
		BEGIN
			WHILE (@RowCountFeeAllocation != 0)
			BEGIN
				DECLARE @lSourceId BIGINT
					,@lSourceTypeId INT
					,@lFeeSetupId INT
					,@lVariableAmount DECIMAL(12, 2)
					,@lDiscountAmount DECIMAL(12, 2)
					,@lNotApplicableAmount DECIMAL(12, 2)
				DECLARE @lAdditionalAmount DECIMAL(12, 2)
					,@lRemark NVARCHAR(200)
					,@lBatchId BIGINT

				SELECT @lSourceId = SourceId
					,@lSourceTypeId = SourceTypeId
					,@lFeeSetupId = FeeSetupId
					,@lVariableAmount = VariableAmount
					,@lDiscountAmount = DiscountAmount
					,@lNotApplicableAmount = NotApplicableAmount
					,@lAdditionalAmount = AdditionalAmount
					,@lRemark = Remark
				FROM #TmpFeeAllocation
				WHERE RowNumberFeeAllocation = @RowCountFeeAllocation

				SELECT @lBatchId = BatchId
				FROM sFee.tFeeSetup
				WHERE Id = @lFeeSetupId

				IF EXISTS (
						SELECT 1
						FROM [sFee].[tFeeAllocationStudent] FAS
						INNER JOIN sStudent.tAcademic A ON A.Id = FAS.AcademicId
						INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.feesetupid
							AND FS.AdmissionCategoryId = A.AdmissionCategoryId
							AND FS.ClassId = A.ClassId
						WHERE FAS.AcademicId = @lSourceId
							AND A.OrgId = @rOrgId
							AND A.BatchId = @lBatchId
						)
				BEGIN
					DECLARE @lFeeAmount DECIMAL(12, 2)
						,@lPaidAmount DECIMAL(12, 2)
						,@lToPayAmount DECIMAL(12, 2)

					SELECT @lFeeAmount = Amount
					FROM sFee.tFeeSetup
					WHERE Id = @lFeeSetupId

					SELECT @lPaidAmount = PaidAmount
					FROM sFee.tFeeAllocationStudent
					WHERE AcademicId = @lSourceId
						AND FeeSetupId = @lFeeSetupId

					SET @lToPayAmount = (@lFeeAmount + @lVariableAmount + @lAdditionalAmount) - (@lNotApplicableAmount + @lDiscountAmount + @lPaidAmount)

					UPDATE [sFee].[tFeeAllocationStudent]
					SET FeeAmount = @lFeeAmount
						,VariableAmount = @lVariableAmount
						,DiscountAmount = @lDiscountAmount
						,NotApplicableAmount = @lNotApplicableAmount
						,AdditionalAmount = @lAdditionalAmount
						,ToPayAmount = @lToPayAmount
						,Remark = @lRemark
						,UpdatedUserId = @rCreatedUserId
						,UpdatedDateTime = sCommon.fGetDate()
					WHERE AcademicId = @lSourceId
						AND FeeSetupId = @lFeeSetupId

					IF (@rFeeSetupId = 0 AND @rClassId = 0 AND @rSourceTypeId != 0 AND @rSourceId != 0) -- Student Fee -- Update other fee which is not include in Fee Allocation
					BEGIN
						
						UPDATE FAS 
						SET VariableAmount = 0, DiscountAmount = 0, NotApplicableAmount = 0, AdditionalAmount = 0, 
							ToPayAmount = FeeAmount - PaidAmount
							,UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
						FROM
							[sFee].[tFeeAllocationStudent] FAS 
						LEFT JOIN #TmpFeeAllocation TFA ON TFA.SourceId = FAS.AcademicId AND TFA.FeeSetupId = FAS.FeeSetupId
						WHERE FAS.AcademicId = @rSourceId AND TFA.FeeSetupId IS NULL
					END
				END
				ELSE
				BEGIN
					SELECT RowNumFeeSetup
						,Id AS FeeSetupId
						,Amount AS FeeAmount
						,IsOptional
						,IsVariable
					INTO #tempFeeSetup
					FROM (
						SELECT ROW_NUMBER() OVER (
								ORDER BY FS.id
								) RowNumFeeSetup
							,FS.Id
							,FS.Amount
							,FS.IsOptional
							,FS.IsVariable
						FROM sFee.tFeeSetup FS
						INNER JOIN sStudent.tAcademic A ON FS.ClassId = A.ClassId
							AND FS.AdmissionCategoryId = A.AdmissionCategoryId
						WHERE FS.BatchId = @lBatchId
							AND A.Id = @lSourceId
							AND FS.FeeId IN (
								SELECT Id
								FROM sFee.tFeeMaster
								WHERE IsObsolete = 0
								)
							AND FS.ReceiptBookId IN (
								SELECT Id
								FROM sFee.tReceiptBookMaster
								WHERE IsObsolete = 0
								)
						) AS tFeeSetup

					DECLARE @RowFeesetup BIGINT = 0

					SELECT @RowFeesetup = COUNT(RowNumFeeSetup)
					FROM #tempFeeSetup

					WHILE (@RowFeesetup != 0)
					BEGIN
						DECLARE @FPFeeSetupId BIGINT = 0
						DECLARE @FeeAmount DECIMAL(12, 2) = 0.00
						DECLARE @IsOptional BIT = 0
						DECLARE @IsVariable BIT = 0

						SELECT @IsOptional = IsOptional
							,@IsVariable = IsVariable
							,@FPFeeSetupId = FeeSetupId
							,@FeeAmount = ISNULL(FeeAmount, 0)
						FROM #tempFeeSetup
						WHERE RowNumFeeSetup = @RowFeesetup

						DECLARE @ToPayAmount DECIMAL(12, 2) = 0.00
						DECLARE @FPPaidAmount DECIMAL(12, 2) = 0.00
						DECLARE @VariableAmount DECIMAL(12, 2) = 0.00
						DECLARE @DiscountAmount DECIMAL(12, 2) = 0.00
						DECLARE @AdditionalAmount DECIMAL(12, 2) = 0.00
						DECLARE @NotApplicableAmount DECIMAL(12, 2) = 0.00
						DECLARE @Remark NVARCHAR(400) = ''

						SELECT @FPPaidAmount = ISNULL(SUM(RD.Amount), 0)
						FROM sFee.tReceipt R
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
							AND R.IsObsolete = 0
						WHERE R.SourceId = @lSourceId
							AND RD.FeeSetupId = @FPFeeSetupId
						GROUP BY R.sourceid
							,RD.feesetupid

						SELECT @VariableAmount = ISNULL(FA.[VariableAmount], 0)
							,@DiscountAmount = ISNULL(FA.[DiscountAmount], 0)
							,@AdditionalAmount = ISNULL(FA.[AdditionalAmount], 0)
							,@NotApplicableAmount = ISNULL(FA.[NotApplicableAmount], 0)
							,@Remark = ISNULL(FA.Remark, '')
						FROM [sFee].[tFeeAllocation] AS FA
						WHERE FA.sourceid = @lSourceId
							AND FA.feesetupid = @FPFeeSetupId

						IF (
								@IsOptional = 1
								AND @IsVariable = 1
								)
						BEGIN
							IF (@VariableAmount > 0)
							BEGIN
								SET @FeeAmount = 0
							END
						END

						IF (
								@IsOptional = 1
								AND @IsVariable = 0
								)
						BEGIN
							IF (@VariableAmount > 0)
							BEGIN
								SET @FeeAmount = 0
							END
						END

						IF (
								@IsOptional = 0
								AND @IsVariable = 1
								)
						BEGIN
							IF (@VariableAmount > 0)
							BEGIN
								SET @FeeAmount = 0
							END
						END

						IF (
								@IsOptional = 0
								AND @IsVariable = 0
								)
						BEGIN
							IF (@VariableAmount > 0)
							BEGIN
								SET @VariableAmount = 0
							END
						END

						SET @ToPayAmount = (@FeeAmount + @VariableAmount + @AdditionalAmount) - (@NotApplicableAmount + @DiscountAmount + @FPPaidAmount)

						IF (@IsOptional = 0)
						BEGIN
							IF NOT EXISTS (
									SELECT 1
									FROM [sFee].[tFeeAllocationStudent] FAS
									WHERE FAS.AcademicId = @lSourceId
										AND FAS.FeeSetupId = @FPFeeSetupId
									)
							BEGIN
								INSERT INTO [sFee].[tFeeAllocationStudent] (
									[AcademicId]
									,[FeeSetupId]
									,[FeeAmount]
									,[VariableAmount]
									,[DiscountAmount]
									,[AdditionalAmount]
									,[NotApplicableAmount]
									,[ToPayAmount]
									,[PaidAmount]
									,[Remark]
									,[CreatedUserId]
									,[CreatedDateTime]
									,[UpdatedUserId]
									,[UpdatedDateTime]
									)
								VALUES (
									@lSourceId
									,@FPFeeSetupId
									,@FeeAmount
									,@VariableAmount
									,@DiscountAmount
									,@AdditionalAmount
									,@NotApplicableAmount
									,@ToPayAmount
									,@FPPaidAmount
									,@Remark
									,@rCreatedUserId
									,sCommon.fGetDate()
									,@rCreatedUserId
									,sCommon.fGetDate()
									)
							END
						END

						IF EXISTS (
								SELECT 1
								FROM [sFee].[tFeeOptional]
								WHERE FeeSetupId = @lFeeSetupId
									AND SourceId = @lSourceId
									AND BatchId = @lBatchId
									AND (@IsOptional = 1)
								)
						BEGIN
							IF NOT EXISTS (
									SELECT 1
									FROM [sFee].[tFeeAllocationStudent] FAS
									WHERE FAS.academicid = @lSourceId
										AND FAS.feesetupid = @FPFeeSetupId
									)
							BEGIN
								INSERT INTO [sFee].[tFeeAllocationStudent] (
									[AcademicId]
									,[FeeSetupId]
									,[FeeAmount]
									,[VariableAmount]
									,[DiscountAmount]
									,[AdditionalAmount]
									,[NotApplicableAmount]
									,[ToPayAmount]
									,[PaidAmount]
									,[Remark]
									,[CreatedUserId]
									,[CreatedDateTime]
									,[UpdatedUserId]
									,[UpdatedDateTime]
									)
								VALUES (
									@lSourceId
									,@FPFeeSetupId
									,@FeeAmount
									,@VariableAmount
									,@DiscountAmount
									,@AdditionalAmount
									,@NotApplicableAmount
									,@ToPayAmount
									,@FPPaidAmount
									,@Remark
									,@rCreatedUserId
									,sCommon.fGetDate()
									,@rCreatedUserId
									,sCommon.fGetDate()
									)
							END
						END

						SET @RowFeesetup = @RowFeesetup - 1
					END

					DROP TABLE #tempFeeSetup
				END

				SET @RowCountFeeAllocation = @RowCountFeeAllocation - 1
			END
		END
		ElSE
		BEGIN
			IF (@rFeeSetupId = 0 AND @rClassId = 0 AND @rSourceTypeId != 0 AND @rSourceId != 0) -- Student Fee -- Update all fee which is not include in Fee Allocation
			BEGIN
				UPDATE [sFee].[tFeeAllocationStudent] 
				SET VariableAmount = 0, DiscountAmount = 0, NotApplicableAmount = 0, AdditionalAmount = 0,
				ToPayAmount = FeeAmount - PaidAmount
				,UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
				WHERE AcademicId = @rSourceId
			END
		END
	END
	
	COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeProcessGenerateVariableFeeAdd]
	@rOrgId int,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,
	@rDepartmentId int,	
	@rExemptionTypeId int,
	@rAdmissionCategoryId int,
	@rFeeId int,
	@rVariableAmount decimal(12,2),
	@rCreatedUserId bigint			 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT BatchId, ClassId, Id AS AcademicId, AdmissionCategoryId, FeeSetupId, rownumAcademic 
INTO #temptAcademic 
FROM
(
	SELECT
		A.BatchId,
		A.ClassId,
		A.Id,
		A.AdmissionCategoryId,
		(SELECT Id FROM sFee.tFeeSetup FS WHERE FS.ClassId = A.ClassId AND FS.BatchId = @rBatchId AND FS.FeeId = @rFeeId AND FS.AdmissionCategoryId = @rAdmissionCategoryId AND IsVariable = 1) AS FeeSetupId,
		ROW_NUMBER() OVER (ORDER BY A.id) rownumAcademic
		FROM sStudent.tAcademic A
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
		INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
		LEFT JOIN (SELECT SourceId FROM  sFee.tFeeAllocation FA 
			INNER JOIN sStudent.tAcademic AC ON FA.SourceId = AC.Id
			INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id
			AND FS.BatchId = @rBatchId AND FS.FeeId = @rFeeId 
			AND FS.AdmissionCategoryId = @rAdmissionCategoryId
			AND FS.IsVariable = 1
			AND ((AC.ClassId=@rClassId) OR (@rClassId=0))
			AND ((AC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((AC.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))
			 WHERE AC.BatchId = @rBatchId  
		 )AL ON AL.SourceId = A.Id 
        WHERE  
			 AL.SourceId IS NULL
  			AND ((A.BatchId=@rBatchId) OR (@rBatchId=0))		 
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((A.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))
			AND ((A.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	
) AS tStudentAcademic

DECLARE @rowcountAcademic BIGINT=0
SELECT @rowcountAcademic = COUNT(rownumAcademic) FROM #temptAcademic

WHILE (@rowcountAcademic!=0)
BEGIN

	DECLARE @academicid BIGINT=0, @admissioncategoryid BIGINT=0, @lFeeSetupId BIGINT=0		
	SELECT @academicid=AcademicId,@admissioncategoryid=AdmissionCategoryId,@lFeeSetupId=FeeSetupId FROM #temptAcademic WHERE rownumAcademic=@rowcountAcademic

	SELECT rownumFeesetup,Id AS FeeSetupId,Amount AS FeeAmount,IsOptional,IsVariable 
	INTO #temptFeeSetup 
	FROM
	(SELECT ROW_NUMBER() OVER (ORDER BY FS.Id) rownumFeesetup,FS.Id,FS.Amount,FS.IsOptional,FS.IsVariable FROM sFee.tFeeSetup FS
	WHERE FS.batchid=@rBatchId AND FS.classid=@rClassId AND FS.admissioncategoryid=@admissioncategoryid
	AND FS.FeeId IN (SELECT Id FROM sFee.tFeeMaster WHERE IsObsolete=0) 
	AND FS.ReceiptBookId IN (SELECT Id FROM sFee.tReceiptBookMaster WHERE IsObsolete=0)
	AND FS.Id = @lFeeSetupId
	) AS tFeeSetup
	
	DECLARE @rowcountFeesetup BIGINT=0
	SELECT @rowcountFeesetup = COUNT(rownumFeesetup) FROM #temptFeeSetup

	WHILE (@rowcountFeesetup!=0)
	BEGIN		
		BEGIN TRY

		DECLARE @feesetupid BIGINT=0, @feeAmount DECIMAL(12,2)=0.00, @IsOptional Bit=0, @IsVariable Bit=0					
		SELECT @IsOptional=IsOptional,@IsVariable=IsVariable,@feesetupid=FeeSetupId,@feeAmount=ISNULL(FeeAmount,0) FROM #temptFeeSetup WHERE rownumFeesetup=@rowcountFeesetup
		
		DECLARE @toPayamount DECIMAL(12,2)=0.00, @paidAmount DECIMAL(12,2)=0.00
		DECLARE @VariableAmount DECIMAL(12,2)=0.00, @DiscountAmount DECIMAL(12,2)=0.00
		DECLARE @AdditionalAmount DECIMAL(12,2)=0.00, @NotApplicableAmount DECIMAL(12,2)=0.00
		DECLARE @Remark NVARCHAR(400)=''

		SELECT @paidAmount=ISNULL(SUM(RD.amount),0) FROM sFee.treceipt  R
		JOIN sFee.tReceiptDetail RD ON RD.receiptid = R.id AND R.IsObsolete = 0
		WHERE R.sourceid=@academicid AND RD.feesetupid=@feesetupid 
		GROUP BY R.sourceid,RD.feesetupid
						
		SELECT 
			@VariableAmount=ISNULL(FA.[VariableAmount],0),
			@DiscountAmount=ISNULL(FA.[DiscountAmount],0),
			@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),
			@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),
			@Remark=ISNULL(FA.Remark,'')						
		FROM [sFee].[tFeeAllocation] AS FA					  			
		WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid

		IF(@IsOptional=1 AND @IsVariable=1)
		BEGIN
			--variable amt = var amount from tfeeall and var amt >0 then fee amt = 0				
			IF(@VariableAmount>0)BEGIN SET @feeAmount=0 END											
		END
			
		IF(@IsOptional=1 AND @IsVariable=0)
		BEGIN
			--Normal with variable amt 0
			IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END							
		END

		IF(@IsOptional=0 AND @IsVariable=1)
		BEGIN
			--variable amt =0 check isoptional in tfeeoptional with fee set up id and academic id, if 0 no insert else insert
			IF(@VariableAmount>0)BEGIN SET @feeAmount=0 END				
		END

		IF(@IsOptional=0 AND @IsVariable=0)
		BEGIN
			--variable amt =0 check isoptional in tfeeoptional with fee set up id and academic id, if 0 no insert else insert
			IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END			
		END

		--Set pending amount
		SET @toPayamount=(@feeAmount+@VariableAmount+@AdditionalAmount)-(@NotApplicableAmount+@DiscountAmount+@paidamount)
	
		--Code to insert based on is optional
		IF(@IsOptional=0)
		BEGIN				
			IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
			BEGIN
				INSERT INTO [sFee].[tFeeAllocationStudent]
						([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
						,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
				VALUES
					(@academicid,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@toPayamount
					,@paidamount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())			
				
			END
		END

		IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@feesetupid AND SourceId=@academicid AND BatchId=@rBatchId AND (@IsOptional=1))
			BEGIN
			IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
			BEGIN
				INSERT INTO [sFee].[tFeeAllocationStudent]
						([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
						,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
				VALUES
					(@academicid,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@toPayamount
					,@paidamount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
			END
		END

		SET @rowcountFeesetup=@rowcountFeesetup-1

	END TRY
	BEGIN CATCH 		
		BREAK
	END CATCH			
	END

	IF OBJECT_ID(N'tempdb..#temptfeesetup') IS NOT NULL
	BEGIN
		DROP TABLE #temptfeesetup
	END

	SET @rowcountAcademic=@rowcountAcademic-1
END
	
IF OBJECT_ID(N'tempdb..#temptAcademic') IS NOT NULL
BEGIN
	DROP TABLE #temptAcademic
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeReceiptCancelPostingDetailGet]
				
           @rReceiptId bigint
            
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			AM.FeeSetupId,
			AMast.Id AS AccountId,
			AMast.Title AS AccountName,
			AM.AccountingYearId,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			AM.PayTypeId,
			PTM.Title AS PayTypeName,
			FM.Id AS FeeId,
			FM.Title AS FeeTitle,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FS.ReceiptBookId AS ReceiptBookId,
			RBM.Title AS ReceiptBookTitle,
			SUM(RD.Amount) AS ReceiptAmount
  FROM 
			sFee.tAccountMapping AM
			INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
			INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
				AND R.PayTypeId = AM.PayTypeId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId 
		    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		    INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId	
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = AM.PayTypeId
WHERE 
			R.Id = @rReceiptId
			
			GROUP BY 
			AMast.Id,AMast.Title,AM.FeeSetupId,AM.AccountingYearId,AYM.Title,AM.CreditLedgerId,CLM.Title,
			AM.DebitLedgerId,DLM.Title,AM.PayTypeId,PTM.Title,FM.Id,FM.Title,FHM.Id,FHM.Title,FS.ReceiptBookId,
			RBM.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pFeeReceiptChequePendingListGet]
		
		@rOrgId smallint,
		@rBatchId int,
		@rAcademicId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
			
BEGIN 	
DECLARE @lChequePendinglist nvarchar(max)	=''
	SELECT @lChequePendinglist=@lChequePendinglist + '<tr>
		<td align="left" scope="col">'+ convert(varchar,Isnull(R.ReceiptNumber,0)) +'</td>
		<td align="left" scope="col">'+convert(varchar,ISNULL(R.ReceiptDate,'01/01/0001'),103)+'</td>
		<td align="left" scope="col">'+Convert(varchar,ISNULL(R.ReceiptAmount,0))+'</td>
		<td align="left" scope="col">'+ISNULL(PTM.Title,'')+'</td>
		<td align="left" scope="col">'+ISNULL(R.ChequeNo,'')+'</td>
		<td align="left" scope="col">'+convert(varchar,ISNULL(R.ChequeDate,'01/01/0001'),103)+'</td>
		<td align="left" scope="col">'+ISNULL(R.BankName,'')+'</td>
		<td align="left" scope="col">'+ISNULL(RBM.Title,'')+'</td>
		<tr>'
   FROM 
		sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.SourceId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId
   WHERE 
	    R.SourceTypeId=2001 AND PTM.Id = 2
		AND A.OrgId=@rOrgId AND R.BatchId=@rBatchId
		AND A.AcademicId=@rAcademicId
		AND (ISNULL(R.IsChequeCleared,0)= 0)
		AND R.IsObsolete = 0
   ORDER BY R.ReceiptNumber DESC
	   
   SELECT ISNULL(@lChequePendinglist,'') AS cancellist
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeReceiptDeletedLog]

	 @rReceiptId bigint,
	 @rUserId bigint=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
BEGIN TRY
BEGIN TRANSACTION	
		-- Receipt Delete
		INSERT INTO 
			sAudit.tReceiptDelete 
		SELECT 
			Id,
			SourceTypeId,
			SourceId,
			SA.Code,
			SA.Name,
			ReceiptNumber,
			ReceiptDate,
			ReceiptAmount,
			PayTypeId,
			ChequeNo,
			BankName,
			(select Title from sFee.tReceiptBookMaster RB where RB.Id=R.ReceiptBookId) AS ReceiptBookName,
			Remark,
			IsObsolete,
			R.BatchId,
			R.OrgGroupBatchId,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=R.CreatedUserId),
			CreatedDateTime,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=R.CreatedUserId),
			CreatedDateTime,		
			TotalReceiptAmount,
			DiscountAmount,
			IsChequeCleared,
			ChequeClearDate,
			ChequeDate,
			FeeInvoiceId,
			(SELECT Title FROM sFee.tCollectionGroupMaster CG WHERE CG.Id=R.CollectionGroupId) AS CollectionGroupName,
			AmountAfterDiscount,
			CGSTPercentage,
			SGSTPercentage,
			CGSTAmount,
			SGSTAmount,
			DepositedLedgerId,
			PaymentTransactionId,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=@rUserId),
			sCommon.fGetDate()
		FROM 
			sFee.tReceipt R 
			INNER join sStudent.vStudentAcademic SA ON R.SourceId=SA.AcademicId
		WHERE 
			Id=@rReceiptId 
		
		-- Receipt Detail Delete
		INSERT INTO 
			sAudit.tReceiptDetailDelete 
		SELECT
			ReceiptId,
			(SELECT FM.Title from sFee.tFeeSetup FS INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId WHERE FS.Id=FeeSetupId),
			Amount
		FROM
			sFee.tReceiptDetail 
		WHERE 
			ReceiptId=@rReceiptId 
	
		SELECT 1 AS Result
	
COMMIT TRANSACTION
END TRY
BEGIN CATCH 
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeReceiptGet]
	 
		@rSourceId bigint,
		@rSourceTypeId int,
		@rReceiptBookId int,
		@rReceiptId bigint=0,
		@rBatchId int,
		@rCollectionGroupId int =0,
		@rUserId bigint=0
		--@rClassId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		 
	DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId	
	SELECT 
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,			 
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,		    
			FS.ReceiptBookId,
			RBM.Title AS ReceiptBook,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) -  ISNULL(FA.NotApplicableAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0)AS PayableAmount,
			FM.OrderIndex,
			FS.CollectionGroupId
  FROM 
		sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
			FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.BatchId = @rBatchId  
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
		WHERE
				FS1.ClassId=@lClassId AND FS1.BatchId =@rBatchId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.vUserReceiptBook RBM
			ON RBM.Id=FS.ReceiptBookId
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 	
		    INNER JOIN sFee.tFeeSetup FSR ON FSR.Id = RD.FeeSetupId 	
			WHERE						
			 (R.ReceiptBookId = @rReceiptBookId	OR @rReceiptBookId = 0)	
			 AND ((FSR.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND R.SourceId= @rSourceId
			AND R.SourceTypeId = @rSourceTypeId
			AND R.IsObsolete = 0 			 
			 GROUP BY FeeSetupId
		
		) R ON R.FeeSetupId = FS.Id 
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND 
			(FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
			
where 

((FS.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
AND (((ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.NotApplicableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0))>0) AND(@rReceiptId=0) OR(@rReceiptId<>0))
AND FS.BatchId=@rBatchId
AND RBM.UserId = @rUserId
 
			

ORDER BY FS.StartDate ASC, FM.OrderIndex ASC


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeReceiptGet_old]
	 
		@rSourceId bigint,
		@rSourceTypeId int,
		@rReceiptBookId int,
		@rReceiptId bigint=0,
		@rBatchId int
		--@rClassId int
		
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		--DECLARE @RAmount Decimal(12,2)
		
	SELECT 
			ISNULL(FA.Id,0)AS Id,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			--ISNULL(FS.Amount,0)AS FSAmount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		     --ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)AS Amount,
			--FM.OrderIndex,
			FCM.FeeReceiptBookId AS ReceiptBookId,
			RBM.Title AS ReceiptBook,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0)AS PayableAmount,
			FM.OrderIndex
			--CASE WHEN ISNULL(FA.VariableAmount-FA.DiscountAmount+ISNULL(FA.AdditionalAmount,0.00),0.00) = 0 THEN FS.Amount
			--ELSE ISNULL(FA.VariableAmount-FA.DiscountAmount+ISNULL(FA.AdditionalAmount,0.00),0.00) END AS Amount,
			
			
			--ISNULL(((select SUM(Amount) from sFee.tReceipt R
			--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id 
			--WHERE R.ReceiptBookId = RBM.Id AND RD.FeeId = FM.Id AND (R.SourceId=@rSourceId) AND(R.SourceTypeId=@rSourceTypeId)
			--group by FeeId)),0) AS PaidAmount,

			--@RAmount=ISNULL(((ISNULL(FA.VariableAmount-FA.DiscountAmount+ISNULL(FA.AdditionalAmount,0.00),0.00)) - (select SUM(Amount) from sFee.tReceipt R
			--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id 
			--WHERE R.ReceiptBookId = RBM.Id AND RD.FeeId = FM.Id AND (R.SourceId=@rSourceId) AND(R.SourceTypeId=@rSourceTypeId)
			--group by FeeId)),0) 
			----AS RAmount
			
			
		
			
		
      
  FROM 
		sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS
			ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeCategoryAssign FCA
			ON FCA.FeeCategoryId=FS.FeeCategoryId AND (FCA.SourceId=@rSourceId) AND(FCA.SourceTypeId=@rSourceTypeId)
		INNER JOIN sFee.tFeeCategoryMaster FCM
			ON FCM.Id=FCA.FeeCategoryId	
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=FCM.FeeReceiptBookId
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 (R.ReceiptBookId = @rReceiptBookId	OR @rReceiptBookId = 0)	
			AND R.SourceId= @rSourceId
			AND R.SourceTypeId = @rSourceTypeId
			AND R.IsObsolete = 0 
			--AND R.Id = @rReceiptId
			--(@rReceiptId =0 )OR(@rReceiptId <> 0))
			 GROUP BY FeeSetupId
		
		) R ON R.FeeSetupId = FS.Id
			
			
		--LEFT JOIN sFee.tReceipt FR
		--	ON FR.ReceiptBookId=RBM.Id AND (FR.SourceId=@rSourceId) AND(FR.SourceTypeId=@rSourceTypeId)
		--LEFT JOIN sFee.tReceiptDetail FRD
		--	ON FR.Id=FRD.ReceiptId 
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND 
			(FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
			
where 

((FCM.FeeReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
AND (((ISNULL(FS.Amount,0) +  ISNULL(FA.VariableAmount,0) -  ISNULL(FA.DiscountAmount,0) + ISNULL(FA.AdditionalAmount,0.00)-ISNULL(R.PaidAmount,0))>0) AND(@rReceiptId=0) OR(@rReceiptId<>0))
AND(FS.BatchId=@rBatchId)
--AND((R.ReceiptId=@rReceiptId)OR(@rReceiptId=0))
--AND  R.PaidAmount > 0
--AND (FS.StartDate<=sCommon.fGetDate())
			

ORDER BY FM.OrderIndex ASC


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeReceiptImportValidate]
	
	@rReceiptNumber int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rReceiptBookId int,
	@rSourceId bigint,
	@rReceiptDetailXml [nvarchar](max),
	@rChequeNoValidate nvarchar(40) = '',  --Mantis - 0030695
	@rPayTypeId int = 0 --Mantis Id:0036117

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
DECLARE @lIsCreated INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

BEGIN

	DECLARE @lValidatioCode TABLE(Id int identity, Result nvarchar(10))

	SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			INSERT @lValidatioCode SELECT ('-101')
		END
	END
	--Mantis Start - 0030695
	 DECLARE @lConfigValue1 nvarchar(50)=''
	 SELECT @lConfigValue1 = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 543 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	If(@rChequeNoValidate <> '' AND @lConfigValue1 = 'True')
	BEGIN
		IF EXISTS(SELECT 1 FROM SFee.tReceipt where ChequeNo = @rChequeNoValidate  AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			 INSERT @lValidatioCode SELECT ('-103')
		END
	END
	--Mantis End - 0030695
	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml, @rPayTypeId, 0, @rReceiptBookId,@rChequeNoValidate,@rIsCreated = @lIsCreated OUTPUT -- Added @rChequeNo,@rPayTypeId for mantis 0035484 By Foram
 	IF(@lIsCreated = 1)
	BEGIN
		INSERT @lValidatioCode SELECT ('-102')
	END
	IF(@lIsCreated = -1) -- For Mantis 0032370 by Foram
 	BEGIN
		INSERT @lValidatioCode SELECT ('-502')
	END
	IF(@lIsCreated = -2) -- For Mantis 0035484 by Foram
 	BEGIN
		INSERT @lValidatioCode SELECT ('-503')
	END
	
	EXEC sp_xml_removedocument @loDoc
	
	SELECT * FROM @lValidatioCode 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeeReceiptListGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(20)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0,
  @rFromChequeClearDate date = '',
  @rToChequeClearDate date = ''
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
		SET @rChequeNo = sCommon.fSearchStringGet(@rChequeNo)  
    END 
	
BEGIN       
 SELECT 
  A.StatusId,    
  R.Id AS ReceiptId,    
  R.SourceId AS SourceId,    
  R.SourceTypeId AS SourceTypeId,    
  CASE WHEN R.SourceTypeId=2001 THEN 'Student'    
  ELSE  'Employee' END AS SourceType,    
  --STM.Title     
  A.Code AS Code,    
  A.Name,    
  R.ReceiptNumber,    
  R.ReceiptDate,    
  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
  R.PayTypeId,    
  PTM.Title AS PayType,    
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
  --R.ChequeNo,    
  R.BankName,    
  R.ReceiptBookId,    
  RBM.Title AS ReceiptBook,    
  R.IsObsolete,    
  A.OrgId,    
  OM.DisplayTitle AS Organization,    
  R.BatchId,    
  BM.Title AS Batch,    
  R.Remark,    
  ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,    
  ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,    
  ISNULL(R.ChequeDate,'') AS ChequeDate,    
  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,    
  Cm.title,    
  CM.Id,    
  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
  CM.Title +' - '+ DM.Title AS Class,    
  A.SUId,    
  ISNULL(R.AmountAfterDiscount,0)AS AmountAfterDiscount,    
  ISNULL(R.CGSTPercentage,0)AS CGSTPercentage,    
  ISNULL(R.SGSTPercentage,0)AS SGSTPercentage,    
  ISNULL(R.CGSTAmount,0)AS CGSTAmount,    
  ISNULL(R.SGSTAmount,0)AS SGSTAmount,    
  ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId,    
  R.CreatedDateTime AS ReceiptCreatedDateTime,
  ISNULL(R.ReceiptPrintGroupId,'') AS ReceiptPrintGroupId   ,
  R.CancelStatusRemark AS  CancelStatusRemark,
  ISNULL(U.DisplayTitle,'') AS UserName,
  ISNULL(R.CancelStatusRemark,'')AS CancelRemark, --Added for mantis : 35507 by Nilesh
  ISNULL(R.CancelDateTime,'')AS CancelDateTime --Added for mantis : 36672 by Dhananjay

  FROM     
   sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR (CONVERT(nvarchar(20),R.PaymentTransactionId) like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))     
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))
 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))    
 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
ORDER BY R.ReceiptNumber DESC    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

		CREATE OR ALTER PROCEDURE [sFee].[pFeeReceiptListViewGet]
		
		
		@rAcademicId bigint,
		@rOrgId int
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	DECLARE @Receiptgrid NVARCHAR(max)=''
	SELECT  @Receiptgrid = @Receiptgrid + '<tr>
	<td align="left" scope="col">' + ISNULL(RBM.Title,'') + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(R.ReceiptNumber,'')) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptDate,'01/01/0001'),103) + '</td>
	<td align="left" scope="col">' +  ISNULL(PTM.Title,'') + '</td>
	<td align="left" scope="col">' +  isnull(R.ChequeNo,'') + '</td>
	<td align="left" scope="col">' + isnull(R.BankName,'') + '</td>
	<td align="left" scope="col">' +  ISNULL([sFee].[fReceiptFeeDetailGet](R.Id),'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptAmount,0)) + '</td>
	</tr>'	
			
  FROM 
			sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
			
WHERE 
	R.SourceTypeId = 2001
	AND SA.AcademicId=@rAcademicId
	--AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))
	ORDER BY R.ReceiptNumber
		select isnull(@Receiptgrid,'') as Receiptgrid

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeReceiptRemove]
	 @rReceiptId bigint,
	 @rIsDelete bit,
	 @rCancelRemark nvarchar(300)='',
	 @rUserId bigint=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY
	
BEGIN TRANSACTION	

	IF EXISTS (SELECT 1 FROM sFee.tReceipt WHERE Id = @rReceiptId AND IsObsolete = 0)
	BEGIN
		DECLARE  @lFeeSetupId int,@rCharge decimal(12,2)=0,
		@lSourceId bigint,@lSourceTypeId int 
		
		SELECT  @lFeeSetupId = FS.ID,@rCharge = RD.Amount,
		@lSourceId = R.SourceId ,@lSourceTypeId =SourceTypeId 
		FROM sFee.tReceiptDetail RD 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 
		INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId
		WHERE RD.ReceiptId = @rReceiptId AND FH.Number = 100 AND FS.IsVariable = 1
		
		
		 IF @lFeeSetupId IS NOT NULL
		 BEGIN
		 UPDATE sFee.tFeeAllocation SET VariableAmount = VariableAmount - @rCharge WHERE FeeSetupId = @lFeeSetupId
		 AND SourceTypeId = @lSourceTypeId AND SourceId = @lSourceId
		 
		 DELETE FROM sFee.tFeeAllocation WHERE FeeSetupId = @lFeeSetupId
		 AND SourceTypeId = @lSourceTypeId AND SourceId = @lSourceId
		 AND (VariableAmount - DiscountAmount-NotApplicableAmount+AdditionalAmount <= 0)
		 
		 END
	END
	 
	 DECLARE @lBatchId int, @lOrgId int
	 SELECT @lSourceId = SourceId, @lBatchId = BatchId from sFee.tReceipt where Id=@rReceiptId 
	 Select @lOrgId = OrgId from sSetup.tBatchMaster where Id = @lBatchId
	
	 -- For Fee Process Added By Hemali 2025-01-23
	 EXEC [sFee].[pDeletedRecieptFeeProcessGenerate] @lOrgId,@lBatchId,@lSourceId,@rReceiptId,@rUserId
	 -- For Fee Process Added By Hemali 2025-01-23

	 IF(@rIsDelete=1)
	 BEGIN
		 
		Insert into sFee.tReceiptDeleted 
		Select Id,SourceTypeId,SourceId,ReceiptNumber,ReceiptDate,ReceiptAmount,PayTypeId,ChequeNo,BankName,
		ReceiptBookId,Remark,IsObsolete,BatchId,OrgGroupBatchId,CreatedUserId,
		CreatedDateTime,TotalReceiptAmount,DiscountAmount,
		IsChequeCleared,ChequeClearDate,ChequeDate,FeeInvoiceId,CollectionGroupId,
		AmountAfterDiscount,CGSTPercentage,SGSTPercentage,CGSTAmount,SGSTAmount,
		DepositedLedgerId,PaymentTransactionId,@rUserId,sCommon.fGetDate()
		From sFee.tReceipt where Id=@rReceiptId 
		
		Insert INTO sFee.tReceiptDetailDeleted Select
		ReceiptId,FeeSetupId,Amount
		From sFee.tReceiptDetail Where ReceiptId=@rReceiptId 

	    Delete From sFee.tReceiptDetail where ReceiptId=@rReceiptId 
		Delete From sFee.tReceipt where Id=@rReceiptId 
		
		SELECT 1 AS Result
	 END
	 ELSE
	 BEGIN 

		UPDATE  sFee.tReceipt
	    SET
			IsObsolete=1,
			CancelStatusRemark = @rCancelRemark,
			CancelDateTime = sCommon.fGetDate()--added for mantis : 36672

		WHERE Id=@rReceiptId
		SELECT 1 AS Result
	 END
	
	COMMIT TRANSACTION
		
	END TRY	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeReceiptView]
	 
		@rReceiptId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT 
			--FM.Id AS FeeId,
			FM.Title AS FeeName,
			--FS.Id AS FeeSetupId,
			--FRD.ReceiptId,
			FRD.Amount AS PaidAmount,
			FS.Id AS FeeSetupId
			--FR.ReceiptAmount
      
  FROM 
		sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS
			ON FS.FeeId=FM.Id
		INNER JOIN sFee.tReceiptDetail FRD
			ON FRD.FeeSetupId=FS.Id
		INNER JOIN sFee.tReceipt FR
			ON FR.Id=FRD.ReceiptId
			
where 

FRD.ReceiptId=@rReceiptId


ORDER BY FS.StartDate,FM.OrderIndex ASC


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeRefundAllBatchGet]    
  
  @rOrgId smallint,    
  @rCode nvarchar(20)
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
	BEGIN  

	SELECT
		SM.FirstName+' '+SM.LastName AS Name,
		R.ReceiptNumber,
		R.ReceiptDate,
		RR.RefundDate,
		ISNULL(RR.RefundAmount,0)AS RefundAmount,
		ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,
		PTM.Title AS PayType,
		RR.ChequeNo,
		RR.BankName,
		RBM.Title AS ReceiptBook,
		RR.IsObsolete,
		A.OrgId,
		OM.DisplayTitle AS Organization,
		RR.BatchId,
		BM.Title AS Batch,
		RR.Remark,
		ISNULL(R.ChequeDate,'') AS ChequeDate,
		A.ClassName+' - '+A.DivisionName AS ClassName,
		STUFF((SELECT ','+Title FROM sFee.tFeeMaster FM 
		INNER JOIN sFee.tFeeSetup FS ON FS.FeeId = FM.Id 
		INNER JOIN sFee.tReceiptRefundDetail RRD ON RRD.FeeSetupId = FS.Id AND RRD.ReceiptRefundId=RR.Id
		WHERE RRD.ReceiptRefundId = RR.Id FOR XML PATH ('')), 1, 1, '') AS FeeDetail
   FROM 
		sFee.tReceiptRefund RR
		INNER JOIN sFee.tReceipt R ON RR.ReceiptId = R.Id
		INNER JOIN sStudent.vStudentAcademic A
			ON A.AcademicId=R.SourceId	
		INNER JOIN sSetup.tClassMaster Cm ON Cm.Id =A.ClassId
		INNER JOIN sStudent.tStudentMaster SM
			ON SM.Id=A.StudentId
		INNER JOIN sCommon.tSourceTypeMaster STM
			ON STM.Id=RR.SourceTypeId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=RR.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM
			ON OM.Id=SM.OrgId
		INNER JOIN sSetup.tBatchMaster BM
			ON BM.Id=RR.BatchId 
   WHERE 
		((SM.Code like @rCode) OR (ISNULL(@rCode,'')=''))
		AND 
		(RR.SourceTypeId=2001)
		AND ((SM.OrgId=@rOrgId) OR (@rOrgId=0))
  ORDER BY R.ReceiptNumber DESC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pFeeRefundDelete]
	 
		@rId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		
	BEGIN
		
		DELETE  RRD
		FROM sFee.tReceiptRefundDetail RRD
		INNER JOIN sFee.tReceiptRefund RR ON RR.Id = RRD.ReceiptRefundId
		WHERE RRD.ReceiptRefundId=@rId
	
		DELETE  RR
		FROM sFee.tReceiptRefund RR
		WHERE RR.Id=@rId
		
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeRefundDetail]
	 
		@rReceiptRefundId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT 
			0 AS Id,
			0 AS ReceiptBookId,
			FM.Id AS FeeId,
			FM.OrderIndex,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			FS.Id AS FeeSetupId,
			ISNULL(RRD.Amount,0) AS FeeRefundAmount
    FROM 
		sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS
			ON FS.FeeId=FM.Id
		INNER JOIN sFee.tReceiptDetail FRD
			ON FRD.FeeSetupId=FS.Id
		INNER JOIN sFee.tReceipt FR
			ON FR.Id=FRD.ReceiptId
		INNER JOIN sFee.tReceiptRefund RR 
			ON RR.ReceiptId=FR.Id AND RR.SourceId=FR.SourceId
		INNER JOIN sFee.tReceiptRefundDetail RRD 
			ON RRD.ReceiptRefundId=RR.Id AND RRD.FeeSetupId = FRD.FeeSetupId
		WHERE 
		RRD.ReceiptRefundId=@rReceiptRefundId
		ORDER BY FS.StartDate,FM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeRefundDetailGet]
		
		   @rAdmissionCategoryId int=0,
		   @rBatchId int,
		   @rOrgGroupBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
           @rReceiptDateTo date,
		   @rRefundId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 		
	
	SELECT
		RAM.FeeSetupId,
		AMast.Id AS AccountId,
		AMast.Title AS AccountName,
		RAM.AccountingYearId,
		AYM.Title AS AccountingYearName,
		RAM.RefundCreditLedgerId AS CreditLedgerId,
		CLM.Title AS CreditLedgerName,
		RAM.RefundDebitLedgerId AS DebitLedgerId,
		DLM.Title AS DebitLedgerName,
		RAM.PayTypeId,
		PTM.Title AS PayTypeName,
		FM.Id AS FeeId,
		FM.Title AS FeeTitle,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FS.ReceiptBookId AS ReceiptBookId,
		RBM.Title AS ReceiptBookTitle,
		SUM(RR.RefundAmount) AS ReceiptAmount,
		R.ReceiptNumber
  FROM 
		sFee.tRefundAccountMapping RAM 
		INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = RAM.FeeSetupId  
		INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId AND R.PayTypeId = RAM.PayTypeId					
		INNER JOIN sFee.tReceiptRefund RR ON RR.ReceiptId = R.Id 
					AND RR.RefundDate >= @rReceiptDate AND RR.RefundDate <= @rReceiptDateTo
		INNER JOIN sFee.tReceiptRefundDetail RRD ON RRD.ReceiptRefundId = RR.Id	
		INNER JOIN sFee.tFeeSetup FS ON FS.Id= RAM.FeeSetupId 
				AND (FS.AdmissionCategoryId=@rAdmissionCategoryId Or @rAdmissionCategoryId = 0) 
				AND (R.OrgGroupBatchId=@rOrgGroupBatchId)
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId 
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId	
        INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=RAM.AccountingYearId
        INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
        INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=RAM.RefundCreditLedgerId)  AND CLM.AccountingYearId = RAM.AccountingYearId
        INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=RAM.RefundDebitLedgerId) AND DLM.AccountingYearId = RAM.AccountingYearId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = RAM.PayTypeId
	WHERE  RR.Id = @rRefundId 
			AND ((RR.RefundDate>=@rReceiptDate)OR(ISNULL(@rReceiptDate,'')=''))
			AND ((RR.RefundDate<=@rReceiptDateTo)OR(ISNULL(@rReceiptDateTo,'')=''))
			AND ((RR.BatchId=@rBatchId) OR (@rBatchId=0))			
	GROUP BY 
			AMast.Id,AMast.Title,RAM.FeeSetupId,RAM.AccountingYearId,AYM.Title,RAM.RefundCreditLedgerId,CLM.Title,
			RAM.RefundDebitLedgerId,DLM.Title,RAM.PayTypeId,PTM.Title,FM.Id,FM.Title,FHM.Id,FHM.Title,FS.ReceiptBookId,
			RBM.Title,R.ReceiptNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeRefundGet]
    @rReceiptBookId int,
	@rBatchId int,
	@rOrgGroupId int,
	@rReceiptDate date,
	@rReceiptDateTo date,
	@rPayTypeId int = 0,
	@rChequePosting nvarchar(50)='',
    @rOrgGroupBatchId int      
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
		RR.Id AS RefundId,
		R.ReceiptDate,
		AMast.Title AS AccountName,
		AYM.Title AS AccountingYearName,
		AM.RefundCreditLedgerId AS CreditLedgerId,
		CLM.Title AS CreditLedgerName,
		AM.RefundDebitLedgerId AS DebitLedgerId,
		DLM.Title AS DebitLedgerName,
		SUM(RR.RefundAmount) AS ReceiptAmount,
		R.ChequeNo AS ChequeNo, R.ChequeDate AS ChequeDate, R.BankName AS BankName, R.ChequeClearDate AS ChequeClearDate,R.PayTypeId AS PayTypeId	, 
		ISNULL(AYM.ISLocked,0) AS ISLocked,
		R.ReceiptNumber,
		ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId 
	FROM 
		sFee.tReceiptRefund RR
		INNER JOIN sFee.tReceipt R ON RR.ReceiptId = R.Id	
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
		INNER JOIN sFee.tRefundAccountMapping AM ON RD.FeeSetupId = AM.FeeSetupId  AND R.PayTypeId = AM.PayTypeId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = AM.FeeSetupId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=RR.BatchId AND BM.OrgGroupBatchId=@rOrgGroupBatchId
		INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
		INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
		INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.RefundCreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
		INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.RefundDebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		WHERE 
			AMast.OrgGroupId=@rOrgGroupId
			AND 
			((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
			AND 
			((RR.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))
			AND ((RR.RefundDate>=@rReceiptDate)OR(ISNULL(@rReceiptDate,'')=''))
			AND ((RR.RefundDate<=@rReceiptDateTo)OR(ISNULL(@rReceiptDateTo,'')=''))
			AND ((RR.BatchId=@rBatchId) OR (@rBatchId=0))			
		GROUP BY R.ReceiptDate,AM.RefundCreditLedgerId,AM.RefundDebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptNumber	
		,R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,R.PayTypeId,R.ReceiptBookId,RR.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeRefundListGet]
		
		@rOrgGroupBatchId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rIdNo nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rFromReceiptNumber int=0,
		@rToReceiptNumber int=0,
		@rReceiptBookId int=0,
		@rSourceTypeId int=0,
		@rPayTypeId tinyint=0,
		@rChequeNo nvarchar(20)='',
		@rFromDate date='',
		@rToDate date='',
		@rOrgId smallint,
		@rBatchId int,
		@rOrgGroupId smallint,
		@rCreatedUserName nvarchar(100),
		@rCreatedUserId bigint,
		@rDepartmentId int=0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
			 BEGIN
				SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
				SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)
			 END
BEGIN 		
	
	SELECT
		--RR.Id AS FeeRefundId,
		R.Id AS MReceiptId,
		RR.Id AS ReceiptId,
		RR.SourceTypeId AS SourceTypeId,
		CASE WHEN RR.SourceTypeId=2001 THEN 'Student'
		ELSE  'Employee' END AS SourceType,
		--STM.Title 
		A.AcademicId,
		A.RollNo,
		SM.Code AS Code,
		SM.FirstName+' '+SM.LastName AS Name,
		R.ReceiptNumber,
		R.ReceiptDate,
		RR.RefundDate,
		ISNULL(RR.RefundAmount,0)AS RefundAmount,
		ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,
		ISNULL(R.DiscountAmount,0)AS DiscountAmount,
		RR.PayTypeId,
		PTM.Title AS PayType,
		RR.ChequeNo,
		RR.BankName,
		R.ReceiptBookId,
		RBM.Title AS ReceiptBook,
		RR.IsObsolete,
		A.OrgId,
		OM.DisplayTitle AS Organization,
		RR.BatchId,
		BM.Title AS Batch,
		RR.Remark,
		ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,
		ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,
		ISNULL(R.ChequeDate,'') AS ChequeDate,
		A.ClassName+' - '+A.DivisionName AS ClassName
  FROM 
		sFee.tReceiptRefund RR
		INNER JOIN sFee.tReceipt R ON RR.ReceiptId = R.Id
		INNER JOIN sStudent.vStudentAcademic A
			ON A.AcademicId=R.SourceId	
			AND (A.ClassId=@rClassId OR @rClassId=0) AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		INNER JOIN sSetup.tClassMaster Cm ON Cm.Id =A.ClassId
		INNER JOIN sStudent.tStudentMaster SM
			ON SM.Id=A.StudentId
			AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		INNER JOIN sCommon.tSourceTypeMaster STM
			ON STM.Id=RR.SourceTypeId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=RR.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM
			ON OM.Id=SM.OrgId
			 AND OM.OrgGroupId=@rOrgGroupId
		INNER JOIN sSetup.tBatchMaster BM
			ON BM.Id=RR.BatchId 
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=RR.CreatedUserId
		INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId
WHERE 
	((SM.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
	AND 
	(RR.SourceTypeId=2001)
	AND ((SM.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
	AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))
	AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))
	AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
	AND ((RR.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))
	AND ((RR.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))
	AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))
	AND ((RR.RefundDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))
	AND ((RR.RefundDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))
	AND ((SM.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((RR.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
	ORDER BY R.ReceiptNumber DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeRefundReceiptListGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(20)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0,
  @rIsFeeWise bit = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN     

IF(@rIsFeeWise = 0)
BEGIN
	SELECT 
	  A.StatusId,    
	  R.Id AS ReceiptId,    
	  R.SourceId AS SourceId,    
	  R.SourceTypeId AS SourceTypeId,    
	  CASE WHEN R.SourceTypeId=2001 THEN 'Student'    
	  ELSE  'Employee' END AS SourceType,    
	  --STM.Title     
	  A.Code AS Code,    
	  A.Name,    
	  R.ReceiptNumber,    
	  R.ReceiptDate,    
	  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
	  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
	  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
	  R.PayTypeId,    
	  PTM.Title AS PayType,    
	  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	  --R.ChequeNo,    
	  R.BankName,    
	  R.ReceiptBookId,    
	  RBM.Title AS ReceiptBook,    
	  R.IsObsolete,    
	  A.OrgId,    
	  OM.DisplayTitle AS Organization,    
	  R.BatchId,    
	  BM.Title AS Batch,    
	  R.Remark,    
	  ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,    
	  ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,    
	  ISNULL(R.ChequeDate,'') AS ChequeDate,    
	  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,    
	  Cm.title,    
	  CM.Id,    
	  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	  CM.Title +' - '+ DM.Title AS Class,    
	  A.SUId,    
	  ISNULL(R.AmountAfterDiscount,0)AS AmountAfterDiscount,    
	  ISNULL(R.CGSTPercentage,0)AS CGSTPercentage,    
	  ISNULL(R.SGSTPercentage,0)AS SGSTPercentage,    
	  ISNULL(R.CGSTAmount,0)AS CGSTAmount,    
	  ISNULL(R.SGSTAmount,0)AS SGSTAmount,    
	  ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId,    
	  R.CreatedDateTime AS ReceiptCreatedDateTime,
	  ISNULL(R.ReceiptPrintGroupId,'') AS ReceiptPrintGroupId,
	  0 AS FeeId,
	  '' AS FeeName,
	  0 AS FeeAmount,
	  0 AS FeeSetupId,
	  ISNULL(RF.Id,0) As RefundId
	FROM     
		sFee.tReceipt R    
		INNER JOIN sStudent.vStudentAcademic A    
		ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		Left Join sFee.tReceiptRefund RF ON RF.ReceiptId = R.Id   
		INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
		INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
		INNER JOIN sCommon.tSourceTypeMaster STM    
		ON STM.Id=R.SourceTypeId    
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
		ON PTM.Id=R.PayTypeId    
		INNER JOIN sFee.tReceiptBookMaster RBM    
		ON RBM.Id=R.ReceiptBookId    
		INNER JOIN sSetup.tOrganizationMaster OM    
		ON OM.Id=A.OrgId    
		AND OM.OrgGroupId=@rOrgGroupId    
		INNER JOIN sSetup.tBatchMaster BM    
		ON BM.Id=R.BatchId     
		AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
		INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
		LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
	WHERE     
		 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
		 AND (R.SourceTypeId=2001)    
		 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
		 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
		 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
		 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
		 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
		 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
		 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
		 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
		 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
		 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
		 AND (R.IsObsolete=@rIsObsolete)    
		 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
		 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
		 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
		 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
		 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
		 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
		 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
		 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
		 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
		 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
		 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
	 ORDER BY R.ReceiptNumber DESC   
END
ELSE IF(@rIsFeeWise = 1)
BEGIN
	SELECT 
	  A.StatusId,    
	  R.Id AS ReceiptId,    
	  R.SourceId AS SourceId,    
	  R.SourceTypeId AS SourceTypeId,    
	  CASE WHEN R.SourceTypeId=2001 THEN 'Student'    
	  ELSE  'Employee' END AS SourceType,    
	  --STM.Title     
	  A.Code AS Code,    
	  A.Name,    
	  R.ReceiptNumber,    
	  R.ReceiptDate,    
	  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
	  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
	  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
	  R.PayTypeId,    
	  PTM.Title AS PayType,    
	  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	  --R.ChequeNo,    
	  R.BankName,    
	  R.ReceiptBookId,    
	  RBM.Title AS ReceiptBook,    
	  R.IsObsolete,    
	  A.OrgId,    
	  OM.DisplayTitle AS Organization,    
	  R.BatchId,    
	  BM.Title AS Batch,    
	  R.Remark,    
	  ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,    
	  ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,    
	  ISNULL(R.ChequeDate,'') AS ChequeDate,    
	  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,    
	  Cm.title,    
	  CM.Id,    
	  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	  CM.Title +' - '+ DM.Title AS Class,    
	  A.SUId,    
	  ISNULL(R.AmountAfterDiscount,0)AS AmountAfterDiscount,    
	  ISNULL(R.CGSTPercentage,0)AS CGSTPercentage,    
	  ISNULL(R.SGSTPercentage,0)AS SGSTPercentage,    
	  ISNULL(R.CGSTAmount,0)AS CGSTAmount,    
	  ISNULL(R.SGSTAmount,0)AS SGSTAmount,    
	  ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId,    
	  R.CreatedDateTime AS ReceiptCreatedDateTime,
	  ISNULL(R.ReceiptPrintGroupId,'') AS ReceiptPrintGroupId,
	  FM.Id AS FeeId,
	  FM.Title AS FeeName,
	  RD.Amount AS FeeAmount,
	  FS.Id AS FeeSetupId,
	  ISNULL(RF.Id,0) As RefundId
	FROM     
		sFee.tReceipt R    
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sStudent.vStudentAcademic A    
		ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
		Left Join sFee.tReceiptRefund RF ON RF.ReceiptId = R.Id
		INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
		INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
		INNER JOIN sCommon.tSourceTypeMaster STM    
		ON STM.Id=R.SourceTypeId    
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
		ON PTM.Id=R.PayTypeId    
		INNER JOIN sFee.tReceiptBookMaster RBM    
		ON RBM.Id=R.ReceiptBookId    
		INNER JOIN sSetup.tOrganizationMaster OM    
		ON OM.Id=A.OrgId    
		AND OM.OrgGroupId=@rOrgGroupId    
		INNER JOIN sSetup.tBatchMaster BM    
		ON BM.Id=R.BatchId     
		AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
		INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
		LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
	WHERE     
		 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
		 AND (R.SourceTypeId=2001)    
		 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
		 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
		 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
		 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
		 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
		 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
		 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
		 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
		 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
		 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
		 AND (R.IsObsolete=@rIsObsolete)    
		 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
		 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
		 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
		 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
		 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
		 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
		 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
		 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
		 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
		 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
		 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
	 ORDER BY R.ReceiptNumber DESC   
END  
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeSetupAdd]
	 
		@rId int,
        @rClassId int,
        @rAdmissionCategoryId int,
        @rBatchId int,
        @rFeeId int,
        @rIsOptional bit,
        @rIsVariable bit,
        @rAmount decimal(12,2),
        @rStartDate date,
        @rEndDate date,
        @rReceiptBookId int,
        @rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rOrgId int,
		@rCheck bit,
		@rIsServiceTax bit,
		@rCollectionGroupId int = 0,
		@rOrgGroupId int=0,
		@rFeeDuration nvarchar(100) ='',
		@rLevelAmount decimal(12,2)=0,
		@rLateFeeRuleId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lFeeSetupId int=0
	
	--changes for Mantis Id:0040786
	SET @lFeeSetupId = (SELECT Id from sFee.tFeeSetup where ClassId = @rClassId AND BatchId = @rBatchId AND AdmissionCategoryId = @rAdmissionCategoryId AND FeeId = @rFeeId)
	IF(@lFeeSetupId > 0)
	BEGIN
		SET @rId = @lFeeSetupId
	END
	--End Mantis: 0040786

	 IF(@rCheck=1 AND @rId>0)
	 BEGIN
	 
	 IF(@rIsOptional = 1 AND @rIsVariable = 1)
	 BEGIN
		  SELECT 0 as Result
		  RETURN
	 END
	 ELSE
	 BEGIN
			IF EXists( SELECT * FROM (
			SELECT AcademicId,	   
					(SELECT ISNULL(SUM(RD.Amount),0)  
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD
					ON	RD.ReceiptId = R.Id
					AND RD.FeeSetupId = @rId
					WHERE R.SourceId = VA.AcademicId AND R.IsObsolete = 0) PaidAmount,		      
					(SELECT ISNULL(VariableAmount,0)-ISNULL(DiscountAmount,0) +
					IsNULL(AdditionalAmount,0) - ISNULL(NotApplicableAmount,0)  
					FROM  sFee.tFeeAllocation A		  
					WHERE A.SourceId = VA.AcademicId AND A.FeeSetupId = @rId  ) AllocationAmount
					--,
					--(SELECT Amount FROM sFee.tFeeSetup S WHERE S.Id = @rId 
					----S.ClassId = VA.AcademicId
					----AND S.AdmissionCategoryId = VA.AdmissionCategoryId
					--) AS FeeSetupAmount	   
			FROM sStudent.vStudentAcademic VA	   
			WHERE ClassId = @rClassId AND AdmissionCategoryId = @rAdmissionCategoryId AND VA.BatchId = @rBatchId
			   ) ST WHERE (@rAmount + ISNULL(ST.AllocationAmount,0) - ISNULL(ST.PaidAmount,0) < 0))
			   
			   select @rId as Result
			   ELSE
			   SELECT 0  as Result
			   RETURN
	 END
	
	--WHERE ST.Amount + AllocationAmount - PaidAmount > 0
	 -- SELECT @lFeeSetupId=R.FeeSetupId FROM
	 -- sFee.tFeeSetup FS
		--LEFT JOIN
		--(
		--    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		--    RD.FeeSetupId,FA.VariableAmount,FA.AdditionalAmount,FA.DiscountAmount,FA.NotApplicableAmount 
		--    FROM
		--    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id
		--     LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=RD.FeeSetupId AND FA.SourceId=R.SourceId 
		--     AND FA.SourceTypeId=R.SourceTypeId	
		--	WHERE						
		--	 R.IsObsolete = 0 
		--	 GROUP BY RD.FeeSetupId,R.SourceId,R.SourceTypeId,FA.VariableAmount,FA.AdditionalAmount,
		--	 FA.DiscountAmount,FA.NotApplicableAmount
		
		--) R ON R.FeeSetupId = FS.Id 
		--where ISNULL(R.FeeSetupId,0)=@rId 
		--AND (@rAmount +  ISNULL(R.VariableAmount,0) + ISNULL(R.AdditionalAmount,0.00) -  ISNULL(R.DiscountAmount,0)-ISNULL(R.NotApplicableAmount,0) -ISNULL(R.PaidAmount,0))<0
		--BEGIN
		



--	select @lFeeSetupId as Result
		--	RETURN
		--END
		
	END
	 
 IF(@rId = 0)	
BEGIN
	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeSetup', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tFeeSetup
		(
		   Id,
           ClassId,
           AdmissionCategoryId,
           BatchId,
           FeeId,
           IsOptional,
           IsVariable,
           Amount,
           StartDate,
           EndDate,
           ReceiptBookId,
           CreatedUserId,
           CreatedDateTime,
           IsServiceTax,
           CollectionGroupId,
           FeeDuration,
           LevelAmount,
		   LateFeeRuleId
        )
	VALUES
		(
			@lNextNumber,
			@rClassId,
			@rAdmissionCategoryId,
            @rBatchId,
            @rFeeId,
            @rIsOptional,
            @rIsVariable,
            @rAmount,
            @rStartDate,
            @rEndDate,
            @rReceiptBookId,
            @rCreatedUserId,
			sCommon.fGetDate(),
			@rIsServiceTax,
			@rCollectionGroupId,
			@rFeeDuration,
			@rLevelAmount,
			@rLateFeeRuleId
		)

		SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tFeeSetup
	    SET
			 --ClassId=@rClassId,
			 --AdmissionCategoryId=@rAdmissionCategoryId,
    --         BatchId=@rBatchId,
             IsOptional=@rIsOptional,
             IsVariable=@rIsVariable,
             Amount=@rAmount,
             StartDate=@rStartDate,
             EndDate=@rEndDate,
             ReceiptBookId=@rReceiptBookId,
             UpdatedUserId=@rUpdatedUserId,
			 UpdatedDateTime=sCommon.fGetDate(),
			 IsServiceTax=@rIsServiceTax,
			 CollectionGroupId=@rCollectionGroupId,
			 FeeDuration=@rFeeDuration,
			 LevelAmount=@rLevelAmount,
			 LateFeeRuleId=@rLateFeeRuleId
	      WHERE (Id = @rId)
	       --AND (FeeId=@rFeeId) 

	      SELECT 11 AS Result   
	 END  
	
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGRoupId)
	BEGIN
		Insert INto sSystem.tPortalSync 
		(
			OrgGRoupId,
			FeeChange
		)
		Values
		(
			@rOrgGRoupId,
			1
		)
	END
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
		
	END

	EXEC [sFee].[pFeeProcessGenerate] @rOrgId,@rBatchId,@rClassId,NULL,NULL,@rCreatedUserId,@lNextNumber

	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE OR ALTER PROCEDURE [sFee].[pFeeSetupApply]
	 
		   @rOrgId int,
           @rFromClassId int,
           @rFromAdmissionCategoryId int,
           @rFromBatchId int,
           @rToClassId int,
           @rToAdmissionCategoryId int,
           @rToBatchId int,       
           @rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION
	
	DECLARE @lNextNumber INT  
	DECLARE @lCountSetup INT
	DECLARE @lNextSetupNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFee.tFeeSetup
				SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY Id) AS Id,
				@rToClassId,
				@rToAdmissionCategoryId,
				@rToBatchId,
				FeeId,
				IsVariable,
				IsOptional,
				Amount,
				StartDate,
				EndDate,
				ReceiptBookId,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL,
				IsServiceTax,
				CollectionGroupId,
				FeeDuration,
				0,
				LevelAmount,
				LateFeeRuleId
				
				FROM sFee.tFeeSetup
				WHERE ClassId = @rFromClassId AND AdmissionCategoryId = @rFromAdmissionCategoryId
				AND BatchId = @rFromBatchId
				
				SELECT @lCountSetup = COUNT(Id)	FROM sFee.tFeeSetup
					WHERE ClassId = @rFromClassId 
					AND AdmissionCategoryId = @rFromAdmissionCategoryId
					AND BatchId = @rFromBatchId
					
				SET @lNextSetupNumber  = ISNULL(@lNextNumber,0) + ISNULL( @lCountSetup ,0)		
					
				EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sFee.tFeeSetup', @rCurrentNumber = @lNextSetupNumber 		
				
				SELECT 1 AS Result
				
			COMMIT TRANSACTION			
		END TRY
		
		BEGIN CATCH 
			ROLLBACK TRANSACTION
				SELECT -1 AS Result
		END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeSetupFeeWiseGet]
    @rAdmissionCategoryId int,
	@rBatchId int,
	@rOrgGroupId int,
	@rFeeId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
		ISNULL(FS.Id,0)AS Id,
		ISNULL(CM.Id,0)AS ClassId,
		ISNULL(CM.Title,'') AS ClassName,
		ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
		ISNULL(FS.BatchId,0)AS BatchId,
		ISNULL(FS.IsOptional,0)AS IsOptional,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
		ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
		ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
		CASE WHEN (SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0 THEN 'True' ELSE 'False' END AS IsReceiptBookChange,
		ISNULL(FS.IsServiceTax,0)AS IsServiceTax,
		ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,
		ISNULL(FS.FeeDuration,'')  AS FeeDuration,
		ISNULL(FS.LevelAmount,0) AS LevelAmount,
		ISNULL(FS.LateFeeRuleId, 0) AS LateFeeRuleId
  FROM 
		sSetup.tClassMaster CM
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id AND BC.BatchId = @rBatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		LEFT JOIN sFee.tFeeSetup FS ON CM.Id=FS.ClassId 
		AND (FS.FeeId=@rFeeId OR @rFeeId= 0) 
		AND (FS.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId= 0) 
		AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
WHERE 
		OM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,CM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeSetupFeeWiseRemove] 
	@rId INT
	,@rFeeId INT
	,@rAdmissionCategoryId INT
	,@rBatchId INT
	,@rCheck BIT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF (@rCheck = 1)
	BEGIN
		IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tFeeAllocation
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 50 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tReceiptDetail
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 51 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tFeeOptional
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 52 AS Result

			RETURN
		END

		-- Removed for mantis : 0028005 By Foram
		--If Exists(select FeeSetupId from sFee.tFeeAllocationStudent where FeeSetupId=@rId)
		--BEGIN
		--	select -50 as Result
		--	RETURN
		--END 
		SELECT 0 AS Result
	END
	ELSE
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION

			ALTER TABLE sfee.tReceiptDetail
				WITH CHECK CHECK CONSTRAINT FK_sFee_tReceiptDetail_FeeSetupId

			ALTER TABLE sFee.tFeeOptional
				WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeOptional_tFeeSetupId

			ALTER TABLE sFee.tFeeAllocation
				WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeAllocation_FeeSetupId

			-- For Fee Process Added By Foram on 2025-01-31 Start
			SELECT Id
			INTO #TempFeeSetupId
			FROM sFee.tFeeSetup
			WHERE FeeId = @rFeeId
				AND AdmissionCategoryId = @rAdmissionCategoryId
				AND BatchId = @rBatchId
				AND (
					(Id = @rId)
					OR (@rId = 0)
					)
			-- For Fee Process Added By Foram on 2025-01-31 End

			DELETE
			FROM sFee.tFeeSetup
			WHERE FeeId = @rFeeId
				AND AdmissionCategoryId = @rAdmissionCategoryId
				AND BatchId = @rBatchId
				AND (
					(Id = @rId)
					OR (@rId = 0)
					)

			-- For Fee Process Added By Foram on 2025-01-31 Start
			DELETE FAS
			FROM sFee.tFeeAllocationStudent FAS
			INNER JOIN #TempFeeSetupId FS ON FAS.FeeSetupId = FS.Id
			-- For Fee Process Added By Foram on 2025-01-31 End
			COMMIT TRANSACTION
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION

			SELECT - 1 AS Result
		END CATCH

		SELECT 11 AS Result
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeSetupGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS Id,
			ISNULL(CM.Id,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			FM.Title AS FeeTitle,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
			ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			--CASE WHEN ((SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0) AND ((SELECT COUNT(1) FROM sFee.tPostDatePayment WHERE ReceiptBookId=FS.ReceiptBookId) <=0) THEN 'True' 
			CASE WHEN ((SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0) AND ((SELECT COUNT(1) FROM sFee.tPostDatePayment PDP INNER JOIN sStudent.tAcademic A ON A.Id = PDP.SourceId AND PDP.SourceTypeId = 2001 WHERE A.ClassId = FS.ClassId AND ReceiptBookId=FS.ReceiptBookId) <=0) THEN 'True'  -- Changed PDC condition for mantis : 0032937
			ELSE 'False' END AS IsReceiptBookChange,
			ISNULL(FS.IsServiceTax,0)AS IsServiceTax,
			ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,
			ISNULL(FS.FeeDuration,'')  AS FeeDuration,
			ISNULL(FS.LevelAmount,0) AS LevelAmount,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(CGM.Title,'') AS CollectionGroupTitle,
			ISNULL(FS.LateFeeRuleId, 0) AS LateFeeRuleId
  FROM 
			sFee.tFeeMaster FM
		LEFT JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId OR @rClassId= 0) 
		AND (FS.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId= 0) 
		AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeSetupRemove] 
	@rId INT
	,@rClassId INT
	,@rAdmissionCategoryId INT
	,@rBatchId INT
	,@rCheck BIT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF (@rCheck = 1)
	BEGIN
		IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tFeeAllocation
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 50 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tReceiptDetail
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 51 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tFeeOptional
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 52 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tOnlineFeeDetail
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 53 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				--SELECT 1
				--FROM [sFee].[tPostDatePayment]
				--WHERE ReceiptBookId = (SELECT ReceiptBookId FROM sFee.tFeeSetup WHERE Id = @rId)
				SELECT 1 FROM sFee.tPostDatePayment PDP 
				INNER JOIN sStudent.tAcademic A ON A.Id = PDP.SourceId AND PDP.SourceTypeId = 2001 
				WHERE A.ClassId = (SELECT ClassId FROM sFee.tFeeSetup WHERE Id = @rId) AND ReceiptBookId=(SELECT ReceiptBookId FROM sFee.tFeeSetup WHERE Id = @rId)
				AND PDP.BatchId = (SELECT BatchId FROM sFee.tFeeSetup where Id = @rId) -- Add Batch Id Filter for Mantis Id: 0036102
			)
		BEGIN
			SELECT - 54 AS Result

			RETURN
		END

		--else If Exists(select FeeSetupId from sFee.tFeeAllocationStudent where FeeSetupId=@rId)
		--	    BEGIN
		--			select -50 as Result
		--			RETURN
		--		END 
		SELECT 0 AS Result
	END
	ELSE
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION

			ALTER TABLE sfee.tReceiptDetail
				WITH CHECK CHECK CONSTRAINT FK_sFee_tReceiptDetail_FeeSetupId

			ALTER TABLE sFee.tFeeOptional
				WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeOptional_tFeeSetupId

			ALTER TABLE sFee.tFeeAllocation
				WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeAllocation_FeeSetupId

			-- For Fee Process Added By Foram on 2025-01-31 Start
			SELECT Id INTO #TempFeeSetupId
			FROM sFee.tFeeSetup
			WHERE ClassId = @rClassId
				AND AdmissionCategoryId = @rAdmissionCategoryId
				AND BatchId = @rBatchId
				AND ((Id = @rId) OR (@rId = 0))
			-- For Fee Process Added By Foram on 2025-01-31 End

			DELETE
			FROM sFee.tFeeSetup
			WHERE ClassId = @rClassId
				AND AdmissionCategoryId = @rAdmissionCategoryId
				AND BatchId = @rBatchId
				AND ((Id = @rId) OR (@rId = 0))

			-- For Fee Process Added By Foram on 2025-01-31 Start
			DELETE FAS
			FROM sFee.tFeeAllocationStudent FAS
			INNER JOIN #TempFeeSetupId FS ON FAS.FeeSetupId = FS.Id
			-- For Fee Process Added By Foram on 2025-01-31 End

			COMMIT TRANSACTION
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION

			SELECT - 1 AS Result
		END CATCH

		SELECT 11 AS Result
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pFeeStatusCollectionGroupDashboardGet]
		@rType nvarchar(100)='',
		@rCount int =0 ,
		@rDivisionId int  =0,
		@rUptoDate date = '',
		@rClassId int  =0,
		@rBatchId int =0,
		@rUserId bigint  =0,
		@rBuilder1 nvarchar(max) ='',
		@rBuilder2 nvarchar(max) ='',
		@rIsDetail bit  =0,
		@rOrgId int  =0,
		@rOrgGroupId int=0,
		@rOrgGroupBatchId int  =0,
		@rCollectionGroupId int =0,
		@rReceiptBookId int =0
		
		

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

IF(@rType ='Paid&UnpaidDetils')
	BEGIN 
declare @ltempPaidDetails table(
OrgGroupId int,
ClassName nvarchar(50),
DivisionName nvarchar(50),
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2)
)
insert into @ltempPaidDetails
SELECT 
		 ISNULL(O.Id,0) AS OrgGroupId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 ISNULL(SA.DivisionName,'') AS DivisionName,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN 
		(
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND(SA1.IsActiveBatch =1) 
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND(SA1.IsActiveBatch =1) 
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				AND(SA1.IsActiveBatch =1) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Code,SA.Name,SC.ParentContactNo
	
	IF(@rCount = 1)
		BEGIN
			SELECT T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,
				T.ParentContactNo AS ParentContactNo,T.PaidAmount AS PaidAmount
			FROM @ltempPaidDetails T
			--WHERE PendingAmount  = 0
			GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.ClassName,T.Name,T.ParentContactNo,T.PaidAmount,T.Code
		END
	IF(@rCount = 2)
		BEGIN
			SELECT T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,
				T.ParentContactNo AS ParentContactNo,T.PendingAmount AS UnPaidAmount
			FROM @ltempPaidDetails T
			--WHERE PendingAmount  != 0
			GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.ClassName,T.Name,T.ParentContactNo,T.PendingAmount,T.Code
		END
	
END

IF(@rType ='TotalPaidDetils')
	BEGIN 
DECLARE @ltempTotalPaidDetails TABLE(
FeeHeadId bigint,
FeeHeadName nvarchar(200),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
ReceiptBookId bigint,
RecepitTitle nvarchar(100),
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2)
)
INSERT INTO @ltempTotalPaidDetails
SELECT 
		ISNULL(FHM.Id,0) AS FeeHeadId,
		ISNULL(FHM.code,'') AS FeeHeadName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(RBM.Id,'')  AS ReceiptBookId,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
		INNER JOIN 
		(
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
	GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Title,RBM.Title,RBM.Id
	
	SELECT T.FeeHeadId,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,T.CollectionGroupId,
	ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.FeeHeadName,'') AS FeeHeadName,
	T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
	ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
	ISNULL(T.PaidAmount,0) AS PaidCount,ISNULL(T.PendingAmount,0) AS  PendingCount from @ltempTotalPaidDetails T
	GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId
		
		--New Temp Table Create-------------
	DECLARE @ltempTotalStudentCount TABLE(
	AcademicId bigint,
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	EndDate date,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2)
	)
	INSERT INTO @ltempTotalStudentCount
	SELECT 
			ISNULL(SA.AcademicId,0) AS AcademicId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroup,
			ISNULL(RBM.Title,'')  AS ReceiptTitle,
			ISNULL(RBM.Id,0) As ReceiptBookId,
			ISNULL(CGM.EndDate,'') AS EndDate,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			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
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
		INNER JOIN 
		(
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
	GROUP BY SA.AcademicId,CGM.Id,CGM.Title,RBM.Title,RBM.Id,CGM.EndDate
	
SELECT E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,E.CollectionGroup AS CollectionGroup,E.EndDate AS EndDate,
SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount FROM (
SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
	ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,
	ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from @ltempTotalStudentCount T
		LEFT JOIN 
		(
			SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM @ltempTotalStudentCount --CollectionGroupId,CollectionGroup,
			WHERE PendingAmount  = 0
			GROUP BY CollectionGroupId,ReceiptBookId
		) A ON A.CollectionGroupId = T.CollectionGroupId
		LEFT JOIN 
		(
			SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM @ltempTotalStudentCount
			WHERE PendingAmount !=0
			GROUP BY CollectionGroupId,ReceiptBookId
		)B ON B.CollectionGroupId = T.CollectionGroupId 
		GROUP BY T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
		)E
		GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate
		
		-------------Create a New Temp Table For Pending date-----------------
		DECLARE @ltempPendingCount TABLE(
	AcademicId bigint,
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	EndDate date,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2)
	)
	INSERT INTO @ltempPendingCount
	SELECT 
			ISNULL(SA.AcademicId,0) AS AcademicId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroup,
			ISNULL(RBM.Title,'')  AS ReceiptTitle,
			ISNULL(RBM.Id,0) As ReceiptBookId,
			ISNULL(CGM.EndDate,'') AS EndDate,
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			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
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
		INNER JOIN 
		(
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
	GROUP BY SA.AcademicId,CGM.Id,CGM.Title,RBM.Title,RBM.Id,CGM.EndDate
		
	SELECT T.ReceiptBookId AS ReceiptId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,
	T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount
	FROM   @ltempPendingCount T
	WHERE PendingAmount !=0
	 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()-180) AND CONVERT(DATE,GETDATE())
	 GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup
		
	
END
IF(@rType ='PaidSubPart')
	BEGIN 
DECLARE @ltempPaidSubPart table(
AcademicId bigint,
OrgGroupId int,
ClassName nvarchar(50),
ClassId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2)
)

IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO @ltempPaidSubPart
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 SA.ClassName AS ClassName,
		 SA.ClassId AS ClassId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
					FS1.FeeId,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Title,RBM.Title,RBM.Id
	
	select T.OrgGroupId,T.ClassId,T.ClassName+' - '+ T.DivisionName  AS ClassDivision,ISNULL(SUM(T.PaidAmount),0) AS PaidCount, 
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from @ltempPaidSubPart T
		group by T.OrgGroupId,T.PaidAmount,T.ClassName,T.DivisionName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
	END 
	ELSE 
	BEGIN
	INSERT INTO @ltempPaidSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 SA.ClassName AS ClassName,
		 SA.ClassId AS ClassId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN 
		(
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Title,RBM.Title,RBM.Id
	
	select T.OrgGroupId,T.ClassId,T.ClassName+' - '+ T.DivisionName  AS ClassDivision,ISNULL(SUM(T.PaidAmount),0) AS PaidCount, 
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from @ltempPaidSubPart T
		group by T.OrgGroupId,T.PaidAmount,T.ClassName,T.DivisionName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
	END
END
IF(@rType ='PendingSubPart')
	BEGIN 
declare @ltempPendingSubPart table(
AcademicId bigint,
OrgGroupId int,
ClassName nvarchar(50),
ClassId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2)
)

IF(@rCollectionGroupId = 0)
	BEGIN
	insert into @ltempPendingSubPart
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 SA.ClassName AS ClassName,
		 SA.ClassId AS ClassId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
					FS1.FeeId,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Title,RBM.Title,RBM.Id
	
	select T.OrgGroupId,T.ClassId,T.ClassName+' - '+ T.DivisionName  AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingCount, 
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from @ltempPendingSubPart T
		
		group by T.OrgGroupId,T.PaidAmount,T.ClassName,T.DivisionName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId
		HAVING ISNULL(SUM(T.PendingAmount),0) > 0
	END 
	ELSE 
	BEGIN
	insert into @ltempPendingSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 SA.ClassName AS ClassName,
		 SA.ClassId AS ClassId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN 
		(
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Title,RBM.Title,RBM.Id
	
	select T.OrgGroupId,T.ClassId,T.ClassName+' - '+ T.DivisionName  AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingCount, 
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from @ltempPendingSubPart T
		group by T.OrgGroupId,T.PaidAmount,T.ClassName,T.DivisionName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId
		HAVING ISNULL(SUM(T.PendingAmount),0) > 0
	END
	END
IF(@rType ='TotalSubPart')
	BEGIN 
declare @ltempTotalSubPart table(
AcademicId bigint,
OrgGroupId int,
ClassName nvarchar(50),
ClassId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2)
)

IF(@rCollectionGroupId = 0)
	BEGIN
	insert into @ltempTotalSubPart
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 SA.ClassName AS ClassName,
		 SA.ClassId AS ClassId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
					FS1.FeeId,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Title,RBM.Title,RBM.Id
	
	select T.OrgGroupId,T.ClassId,T.ClassName+' - '+ T.DivisionName  AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS PaidCount, 
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from @ltempTotalSubPart T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount+PendingAmount) AS PaidCount  from @ltempTotalSubPart 
		--	--WHERE PendingAmount  != 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.OrgGroupId,T.ClassName,T.DivisionName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	END 
	ELSE 
	BEGIN
	insert into @ltempTotalSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 SA.ClassName AS ClassName,
		 SA.ClassId AS ClassId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN 
		(
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM 	ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Title,RBM.Title,RBM.Id

		 
	select T.OrgGroupId,T.ClassId,T.ClassName+' - '+ T.DivisionName  AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS PaidCount, 
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from @ltempTotalSubPart T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount+PendingAmount) AS PaidCount  from @ltempTotalSubPart T
		--	--WHERE PendingAmount  != 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.OrgGroupId,T.ClassName,T.DivisionName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	END
  END
  IF(@rType ='PaidSubPartDetails')
	BEGIN 
declare @ltempPaidSubPartDetails table(
AcademicId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
ClassId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2)
)

IF(@rCollectionGroupId = 0)
	BEGIN
	insert into @ltempPaidSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.ClassId AS ClassId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN 
		(
			SELECT 
					FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
					FS1.FeeId,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId 
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND (SA.ClassId = @rClassId) OR (@rClassId = 0)
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Title,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code
	
	select T.Name AS Name,T.ClassId,SUM(ISNULL(T.PaidAmount,0)) AS PaidCount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from @ltempPaidSubPartDetails T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
	END 
	ELSE 
	BEGIN
	insert into @ltempPaidSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.ClassId AS ClassId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN 
		(
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(FS1.IsOptional=0)
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		WHERE
				
			(FS1.IsOptional=1)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND (SA.ClassId = @rClassId) OR (@rClassId = 0)
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND(SA.IsActiveBatch =1)  
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Title,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code
	

	select T.Name AS Name,T.ClassId,SUM(ISNULL(T.PaidAmount,0)) AS PaidCount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from @ltempPaidSubPartDetails T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
	END
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeStatusDashboardGet]
	@rType nvarchar(100)='',
		@rClassId int =0 ,
		@rDivisionId int  =0,
		@rUptoDate date = '',
		@rBatchId int  =0,
		@rUserId bigint  =0,
		@rBuilder1 nvarchar(max) ='',
		@rBuilder2 nvarchar(max) ='',
		@rIsDetail bit  =0,
		@rOrgId int  =0,
		@rOrgGroupId int=0,
		@rOrgGroupBatchId int  =0,
		@rReceiptBookId int =0
		
		

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

IF(@rType ='Organization')
	BEGIN 
	declare @ltempOrganization table(
--AcademicId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
OrgGroupName nvarchar(200),
OrgGroupId int
)
insert into @ltempOrganization
SELECT 
		SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
		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,
		OGM.Title AS OrgGroupName,
		OGM.Id AS OrgGroupId
	FROM 
		sStudent.vStudentAcademic SA
	INNER JOIN 
	(
	SELECT 
		FS1.FeeId,
		FS1.Id,
		ISNULL(FS1.IsOptional,0)AS IsOptional,
		ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount,0)AS Amount,
		ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.AcademicId,
		FM.Title AS FeeName,
		FM.FeeHeadId
	FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		((FS1.IsOptional=0))
		UNION ALL
	SELECT 
		FS1.FeeId,
		FS1.Id,
		ISNULL(FS1.IsOptional,0)AS IsOptional,
		ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount,0)AS Amount,
		ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.AcademicId,
		FM.Title AS FeeName,
		FM.FeeHeadId
	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 FS1.BatchId = SA1.BatchId
		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	WHERE
		((FS1.IsOptional=1))
		) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
		SELECT 
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		FROM
			sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		WHERE		
			(R.SourceTypeId = 2001)
			AND (R.IsObsolete = 0) 
		GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
		WHERE	
		(SA.IsActiveBatch =1) 
		GROUP BY  OGM.Id,OGM.Title
	
	SELECT T.OrgGroupId,T.OrgGroupName,ISNULL(T.PaidAmount,0) AS PaidCount,ISNULL(T.PendingAmount,0) AS  PendingCount,ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalCount from @ltempOrganization T
	--select T.OrgGroupId,T.OrgGroupName,ISNULL(A.PaidCount,0) AS PaidCount,ISNULL(B.PendingCount,0) AS  PendingCount,ISNULL(ISNULL(A.PaidCount,0) + ISNULL(B.PendingCount,0),0) AS TotalCount from @ltempOrganization T
	--	INNER JOIN 
	--	(
	--		select OrgGroupId,OrgGroupName,ISNULL(SUM(PaidAmount),0) AS PaidCount  from @ltempOrganization
	--		WHERE PendingAmount  = 0
	--		group by OrgGroupName,OrgGroupId 
	--	) A ON A.OrgGroupId = T.OrgGroupId
	--	LEFT JOIN 
	--	(
	--		select OrgGroupId,OrgGroupName,ISNULL(SUM(PendingAmount),0) AS PendingCount  from @ltempOrganization
	--		WHERE PendingAmount !=0
	--		group by OrgGroupName,OrgGroupId 
	--	)B ON B.OrgGroupId = t.OrgGroupId 
	--	group by T.OrgGroupName,T.OrgGroupId,A.PaidCount,B.PendingCount
	
END
  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeStructureMasterAdd]
	@rId int,
	@rCode nvarchar(20),
	@rNumber smallint,
	@rTitle nvarchar(100), 
	 @rOrgId smallint,	
	 @rOrderIndex smallint, 	  	 	
	 @rCreatedUserId bigint, 
	 @rUpdatedUserId bigint,
	 @rIsActive bit,
	 @rFeeStructuredetailXml [nvarchar](max)
	       	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rFeeStructuredetailXml
BEGIN
	--BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
	If Exists(select Id from sFee.tFeeStructureMaster where Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
		If Exists(select Id from sFee.tFeeStructureMaster where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sFee.tFeeStructureMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sFee.tFeeStructureMaster where Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
		If Exists(select Id from sFee.tFeeStructureMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sFee.tFeeStructureMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	  --DECLARE @lNextNumberDetail BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeStructureMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tFeeStructureMaster
		(
			
			    Id,
				Code,
				Number,
				Title,
				OrgId,				
				OrderIndex,
				CreatedUserId	,			
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				IsActive
				
		)
	VALUES
		(
		
				@lNextNumber,
				@rCode,
				@rNumber,
				@rTitle,
				@rOrgId,				
				@rOrderIndex,
				@rCreatedUserId	,			
				sCommon.fGetDate(),
				@rUpdatedUserId,
				sCommon.fGetDate(),
				@rIsActive
			
		)						
		    --SELECT @lNextNumber AS Result
		      DELETE FROM sFee.tFeeStructureDetail WHERE FeeStructureId = @rId
		    INSERT INTO sFee.tFeeStructureDetail
			(
				  FeeStructureId,
			    FeeId,
			    FeeAmount
			)
		
			SELECT		
			
				@lNextNumber,
				FeeId,
				FeeAmount
						
				FROM OPENXML (@loDoc, '/Table/FeeStructureDetail', 1)
				WITH 
					 ( 
					    FeeId int,
					    FeeAmount decimal(8,2)
					  ) 
		
        SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sFee.tFeeStructureMaster
	    SET
	    
				Code=@rCode,
				Number=@rNumber,
				OrderIndex=@rOrderIndex,
				Title=@rTitle,				
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate(),
	    		IsActive=@rIsActive			      
	      WHERE Id = @rId
	      
	      DELETE FROM sFee.tFeeStructureDetail WHERE FeeStructureId = @rId
			 INSERT INTO sFee.tFeeStructureDetail
			(
				  FeeStructureId,
				  FeeId,
			      FeeAmount
			)
		
			SELECT		
			
				@lNextNumber,
				FeeId,
				FeeAmount
						
				FROM OPENXML (@loDoc, '/Table/FeeStructureDetail', 1)
				WITH 
					  ( 
					    FeeId int,
					    FeeAmount decimal(8,2)
					  ) 
		
        --SELECT 1 AS Result
	      
	      SELECT 11 AS Result
	 END  	
	--COMMIT TRANSACTION		
	--END TRY	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeeStructureMasterDelete]
@rFeeStructureId int
AS
BEGIN
 	 
		DELETE	FROM  sFee.tFeeStructureDetail WHERE FeeStructureId=@rFeeStructureId
		
		DELETE FROM sFee.tFeeStructureMaster WHERE Id=@rFeeStructureId
		SELECT 1 AS RESULT
	   
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeStructureMasterGet]

	 @rId int,
	  @rOrgId smallint,
	  @rNumber smallint=0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100),
	 @rIsWildCardSearch bit
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF @rIsWildCardSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			FSM.Id AS FeeStructureId,
		    FSM.Code,
		    FSM.Number,
		    FSM.Title,
		    FSM.OrgId,
		    FSM.OrderIndex,
		    FSM.IsActive
		
		    
		    
	FROM 
			sFee.tFeeStructureMaster FSM
	WHERE 
		(FSM.OrgId = @rOrgId)
		AND	((FSM.Id = @rId) OR (@rId = 0))
		AND ((FSM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
		AND ((FSM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND	((FSM.Number = @rNumber) OR (@rNumber = 0))	
	
		
		ORDER BY FSM.OrderIndex DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pFeeSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rBatchId int=0,
	@rDepartmentId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 

	--DECLARE @lAdmissionCategoryId int =  0
	--SET @lAdmissionCategoryId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
	
		if object_id('tempdb..#tTable') is not null
		BEGIN
			DROP TABLE #tTable
		END

		Create table #tTable(
			AcademicId bigint not null
		)

		Insert into #tTable
			select SA.AcademicId 
			FROM sFee.tFeeSetup FS
			INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
			where ((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			-- AND SA.AdmissionCategoryId=@lAdmissionCategoryId
			group by FS.ClassId,SA.AcademicId 

		--Create Table #ttemptable1
		--	(
		--		AcademicId bigint,
		--		PaidAmount int,
		--		PendingAmount int
		--	)
		--	Insert into #ttemptable1
		--	(
		--		AcademicId,
		--		PaidAmount,
		--		PendingAmount
		--	)
		--	Select SA.AcademicId , SUM(SF.PaidAmount) AS PaidAmount , SUM(SF.PendingAmount) AS PendingAmount
		--	From sStudent.vStudentAcademic SA 
		--	Inner Join sFee.tStudentFee SF ON SA.AcademicId=SF.AcademicId
		--	where SA.OrgId=9911 AND SA.BatchId=991100104
		--	Group by SA.AcademicId

		

	IF(@rType = 'FeeList')
	BEGIN

		if object_id('tempdb..#tempAcademicDetail') is not null
		BEGIN
			DROP TABLE #tempAcademicDetail
		END
		
		Create table #tempAcademicDetail(
			AcademicId bigint not null
		)

		SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
		INTO #tempReceiptDetail
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					Group By R.SourceId,FS.Id

		SELECT Distinct SourceId INTO #tempReceipt FROM sFee.tReceipt


		INSERT INTO #tempAcademicDetail
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 0
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
			
		UNION 	
		--Add Union because data wrong due to insert in #tempAcademicDetail -- mantisId - 0030182		
		--INSERT INTO #tempAcademicDetail
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 1
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
		
		--SELECT * FROM #tempAcademicDetail

		CREATE TABLE #tmp
		(
			AcademicId bigint,
			Amount decimal(12,2),
			VariableAmount decimal(12,2),
			AdditionalAmount decimal(12,2),
			DiscountAmount decimal(12,2),
			NotApplicableAmount decimal(12,2)
		)
		INSERT INTO #tmp
			Select SA.AcademicId  AS AcademicId 
			, SUM(FS1.Amount) AS Amount , Sum(FA1.VariableAmount) AS VariableAmount, SUM(FA1.AdditionalAmount)AS AdditionalAmount,SUM(FA1.DiscountAmount)AS DiscountAmount,
			SUM(FA1.NotApplicableAmount)AS NotApplicableAmount
			From sStudent.vStudentAcademic SA

			--Changes for pending fee minus count for mantis Id :0027388
			--LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId
			--LEFT JOIN sFee.tFeeSetup FS1 ON FA1.FeeSetupId = FS1.Id AND FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId  AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId AND FS1.Id = FA1.FeeSetupId
			INNER JOIN #tTable tmp1 ON tmp1.AcademicId = SA.AcademicId
		
			Where
			((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			group by FS1.ClassId,SA.AcademicId 

			
			SELECT COUNT(SA.AcademicId)AS TotalCount,COUNT(T.PaidCount) AS PaidCount,(COUNT(tmp.AcademicId)-COUNT(T.PaidCount))AS UnPaidCount
			, COUNT(PS.AcademicId) AS PartialCount
			FROM sStudent.vStudentAcademic SA 
			LEFT JOIN #tmp tmp ON SA.AcademicId = tmp.AcademicId 
			AND ISNULL(((ISNULL(Amount,0) + ISNULL(VariableAmount,0)+ ISNULL(0,AdditionalAmount)) - (DiscountAmount + NotApplicableAmount)),1) <> 0 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId
			)T ON T.AcademicId = SA.AcademicId 

			LEFT JOIN #tempAcademicDetail PS ON PS.AcademicId=SA.AcademicId
			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			--AND ACM.Code Like '%General%' 
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0	
			DROP TABLE  #tmp
		END
	ELSE IF(@rType = 'FeeGraph')
		BEGIN
		
		CREATE TABLE #tmpData
		(
			AcademicId bigint,
			Amount decimal(12,2),
			VariableAmount decimal(12,2),
			AdditionalAmount decimal(12,2),
			DiscountAmount decimal(12,2),
			NotApplicableAmount decimal(12,2)
		)
		INSERT INTO #tmpData
			Select SA.AcademicId  AS AcademicId 
			, SUM(FS1.Amount) AS Amount , Sum(FA1.VariableAmount) AS VariableAmount, SUM(FA1.AdditionalAmount)AS AdditionalAmount,SUM(FA1.DiscountAmount)AS DiscountAmount,
			SUM(FA1.NotApplicableAmount)AS NotApplicableAmount
			From sStudent.vStudentAcademic SA

			--Changes for pending fee minus count for mantis Id :0027388
			--LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId
			--LEFT JOIN sFee.tFeeSetup FS1 ON FA1.FeeSetupId = FS1.Id AND FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId  AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId AND FS1.Id = FA1.FeeSetupId
			INNER JOIN #tTable tmp1 ON tmp1.AcademicId = SA.AcademicId
		
			Where
			((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			group by FS1.ClassId,SA.AcademicId 


		SELECT CM.Id,CM.Title,ISNULL(T.TotalCount,0)AS TotalCount,COUNT(T1.PaidCount) AS PaidCount,(COUNT(tmpData.AcademicId)-COUNT(T1.PaidCount))AS UnPaidCount,CM.OrderIndex
			FROM sStudent.vStudentAcademic SA
			LEFT JOIN #tmpData tmpData ON SA.AcademicId = tmpData.AcademicId 
			AND ISNULL(((ISNULL(Amount,0) + ISNULL(VariableAmount,0)+ ISNULL(0,AdditionalAmount)) - (DiscountAmount + NotApplicableAmount)),1) <> 0 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			LEFT JOIN 
			(SELECT COUNT(SA1.AcademicId) AS TotalCount,SA1.ClassId AS ClassId FROM sStudent.vStudentAcademic SA1
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM1 ON SA1.AdmissionCategoryId = ACM1.Id
			Inner Join #tTable temp on SA1.AcademicId=temp.AcademicId
			WHERE ((SA1.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))AND SA1.StatusId =1
			--AND ACM1.Code Like '%General%' AND ACM1.IsObsolete = 0	
			--AND ACM1.ID = @lAdmissionCategoryId 
			AND ACM1.IsObsolete = 0
			GROUP BY ClassId
			)T ON T.ClassId = CM.Id	
			LEFT JOIN(
			SELECT COUNT(SA.AcademicId)as PaidCount,SA.AcademicId AS AcademicId,SA.ClassId AS ClassId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))AND SA.StatusId =1
			--AND ACM.Code Like '%General%' AND ACM.IsObsolete = 0
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0		
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId,SA.ClassId
			)T1 ON T1.AcademicId = SA.AcademicId  AND CM.Id = SA.ClassId
			WHERE ((CM.OrgId =@rOrgId)OR(@rOrgId=0))
			AND SA.StatusId =1
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0
			--AND ACM.Code Like '%General%' AND ACM.IsObsolete = 0	
			GROUP BY CM.Title, CM.Id,T.TotalCount,CM.OrderIndex
			ORDER BY CM.OrderIndex

			DROP TABLE #tmpData
		
		END
	ELSE IF (@rType = 'FeeListDetails')
		BEGIN

		if object_id('tempdb..#tempAcademicDetail') is not null
		BEGIN
			DROP TABLE #tempAcademicDetail1
		END
		
		Create table #tempAcademicDetail1(
			AcademicId bigint not null
		)

		SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
		INTO #tempReceiptDetail1
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					Group By R.SourceId,FS.Id

		SELECT Distinct SourceId INTO #tempReceipt1 FROM sFee.tReceipt

		INSERT INTO #tempAcademicDetail1
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail1 R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt1 RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 0
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					
		UNION
		--Add Union because data wrong due to insert in #tempAcademicDetail -- mantisId - 0030182
		--INSERT INTO #tempAcademicDetail1
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail1 R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt1 RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 1
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
		
		--SELECT * FROM #tempAcademicDetail1
		
		SELECT F.RollNo,F.Name,F.Code,F.Pending,F.[Partial],F.[Status],F.ClassDivision
		FROM
		(

		SELECT SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial],'' AS [Status]
			,SA.ClassName+'/'+SA.DivisionName AS ClassDivision,
			(
				Select (SUM(FS1.Amount)+Sum(FA1.VariableAmount)+ SUM(FA1.AdditionalAmount)) - (SUM(FA1.DiscountAmount)+ SUM(FA1.NotApplicableAmount)) 
				From sFee.tFeeAllocation FA1
				INNER JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId AND FA1.FeeSetupId = FS1.Id
				Where FA1.SourceId = SA.AcademicId 
			) AS IsFeePayAmount
			--,ISNULL(FS1.PaidAmount,0) AS PaidAmount ,ISNULL(FS1.PendingAmount,0)AS PendingAmount
			FROM sStudent.vStudentAcademic SA 
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			--LEFT Join #ttemptable1 FS1 ON FS1.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId, SA.Code,SA.Name FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
			LEFT JOIN #tempAcademicDetail1 PS ON PS.AcademicId=SA.AcademicId

			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	 			
			) AS F 
			WHERE ISNULL(F.IsFeePayAmount,1) >= 0
		END

	ELSE IF(@rType='FeeCollection')
		BEGIN
			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as TodayCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate=CAST(GETDATE() as DATE))

			SELECT ISNULL(Sum(R.ReceiptAmount),0.00) as MonthlyCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate>=CAST(DATEADD(DD,-(DAY(GETDATE() -1)), GETDATE()) as DATE) AND R.ReceiptDate<=CAST(DATEADD(DD,-(DAY(GETDATE())), DATEADD(MM, 1, GETDATE())) as DATE))

			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as UptodateCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate<=CAST(GETDATE() as DATE))
		END
		--Drop Table #ttemptable1
		Drop Table #tTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pFeeVariableAdd]
	@rOrgId int,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,
	@rDepartmentId int,	
	@rExemptionTypeId int,
	@rAdmissionCategoryId int,
	@rFeeId int,
	@rVariableAmount decimal(12,2),
	@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


IF NOT EXISTS(SELECT 1 FROM sFee.tFeeSetup WHERE BatchId = @rBatchId AND AdmissionCategoryId =  @rAdmissionCategoryId AND FeeId = @rFeeId AND IsVariable = 1 AND (ClassId =@rClassId OR @rClassId = 0)  )
BEGIN
SELECT -101 AS  Result -- Fee must be marked as variable in fee setup
RETURN
END

	INSERT INTO sFee.tFeeAllocation
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark,
			CreatedUserId,
			CreatedDateTime
		)
				
		SELECT
		2001,
		A.Id,
		(SELECT Id FROM sFee.tFeeSetup FS WHERE FS.ClassId = A.ClassId AND FS.BatchId = @rBatchId AND FS.FeeId = @rFeeId AND FS.AdmissionCategoryId = @rAdmissionCategoryId AND IsVariable = 1) AS FeeSetupId,
		@rVariableAmount,
		0,
		0,
		0,
		'',
		@rCreatedUserId,
		sCommon.fGetDate()
		FROM sStudent.tAcademic A
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
		INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
		LEFT JOIN (SELECT SourceId FROM  sFee.tFeeAllocation FA 
		INNER JOIN sStudent.tAcademic AC ON FA.SourceId = AC.Id
		INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id
		AND FS.BatchId = @rBatchId AND FS.FeeId = @rFeeId 
		AND FS.AdmissionCategoryId = @rAdmissionCategoryId
		AND FS.IsVariable = 1
		AND ((AC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((AC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((AC.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))
		 WHERE AC.BatchId = @rBatchId  
		 )AL ON AL.SourceId = A.Id 
		
		
        WHERE  
			 AL.SourceId IS NULL
  			AND ((A.BatchId=@rBatchId) OR (@rBatchId=0))			 
			--AND (SA.StatusId = @rStatusId OR @rStatusId=0)			 
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((A.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))
			AND ((A.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))

	-- Added For Update in Fee Proceess Table
	DECLARE @lFeeSetupId int
	SET @lFeeSetupId = (SELECT Id FROM sFee.tFeeSetup WHERE BatchId = @rBatchId AND AdmissionCategoryId = @rAdmissionCategoryId AND FeeId = @rFeeId AND IsVariable = 1 AND (ClassId = @rClassId OR @rClassId = 0))

	EXEC sFee.pFeeProcessGenerateVariableFeeAdd @rOrgId, @rBatchId, @rClassId, @rDivisionId, @rDepartmentId, @rExemptionTypeId, @rAdmissionCategoryId, @rFeeId, @rVariableAmount, @rCreatedUserId
	-- Added For Update in Fee Proceess Table

    SELECT 1 AS Result 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec sFee.pGetBatchAndDepartmentDropDowns
-- drop proc sFee.pGetBatchAndDepartmentDropDowns
CREATE OR ALTER PROCEDURE [sFee].[pGetBatchAndDepartmentDropDowns]
@rOrgGroupBatchId int,
@rOrgId int,
@rUserId bigint,
@rDepartmentId int
as
begin
	declare @lBatchRes varchar(max)='',@lDepartmentRes varchar(max)=''
	
	select @lBatchRes = @lBatchRes + '<option value="0"> -- ALL -- </option>'
	select @lBatchRes = @lBatchRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.tBatchMaster where IsObsolete=0 AND IsHistory=0 AND OrgGroupBatchId = @rOrgGroupBatchId and OrgId = @rOrgId
	order by OrderIndex
	
	select @lDepartmentRes = @lDepartmentRes + '<option value="0"> -- ALL -- </option>'
	select @lDepartmentRes = @lDepartmentRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.vDepartment where IsObsolete = 0 AND OrgId= @rOrgId and UserId = @rUserId
	and (Id = @rDepartmentId or @rDepartmentId = 0)
	order by OrderIndex
	
	select @lBatchRes as BatchRes,@lDepartmentRes as DepratmentRes
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec sFee.pGetCheckBoxLists
-- drop proc sFee.pGetCheckBoxLists
CREATE OR ALTER PROCEDURE [sFee].[pGetCheckBoxLists]
@rFlag int,
@rBatchId int,
@rOrgGroupId int,
@rUserId bigint
as
begin
	declare @lResult varchar(max)=''
	if @rFlag = 1
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,DivisionId) + '" />&nbsp;' + ClassDivisionName + '<br />'
		from sSetup.vBatchClassDivision where IsObsolete = 0 AND BatchId = @rBatchId
		Order BY OrderIndex
	end
	else
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sFee.vUserReceiptBook where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId and UserId = @rUserId
		Order BY OrderIndex
	end
	select @lResult as Result
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exce sFee.pGetClassDropDown
-- drop proc sFee.pGetClassDropDown
CREATE OR ALTER PROCEDURE [sFee].[pGetClassDropDown]
@rBatchId int
as
begin
	declare @lClassRes varchar(max)=''
	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	select @lClassRes = @lClassRes + '<option value="' + convert(varchar,ClassId) + '">' + ClassName + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 AND BatchId = @rBatchId
	
	select @lClassRes as ClassRes
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pGetDropDownLists]
@rOrgGroupId int,
@rOrgGroupBatchId int,
@rUserId bigint
AS
BEGIN
	declare @lOrgGroupRes varchar(max)='',@lOrganizationRes varchar(max)=''
	declare @lStatusRes varchar(max)='',@lReceiptBookRes varchar(max)=''
	declare @lDivisionRes varchar(max)='',@lClassRes varchar(max)=''
	declare @lFeeColumns varchar(max)='',@lReportList varchar(max)=''
	declare @lDepartmentRes varchar(max)='',@lBatchRes varchar(max)='',@lSavedReport nvarchar(max)=''
	
	declare @lAdmissionCategoryRes varchar(max)=''
	
	select @lOrgGroupRes = @lOrgGroupRes + '<option value="0"> -- Select -- </option>'
	select @lOrgGroupRes = @lOrgGroupRes + '<option ' + case when Id = @rOrgGroupBatchId then 'selected="selected"' else '' end + ' value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.tOrgGroupBatchMaster where IsObsolete = 0 AND IsHistory = 0 AND OrgGroupId = @rOrgGroupId
	order by OrderIndex
	
	select @lOrganizationRes = @lOrganizationRes + '<option value="0"> -- ALL -- </option>'
	select @lOrganizationRes = @lOrganizationRes + '<option value="' + convert(varchar,Id) + '">' + DisplayTitle + '</option>'
	from sSetup.tOrganizationMaster where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId
	order by OrderIndex
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option ' + case when Id = 1 then 'selected="selected"' else '' end + ' value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sStudent.tStatusMaster where IsObsolete = 0 order by Title
	
	select @lReceiptBookRes = @lReceiptBookRes + '<option value="0"> -- ALL -- </option>'
	select @lReceiptBookRes = @lReceiptBookRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sFee.vUserReceiptBook where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId AND UserId = @rUserId order by OrderIndex
	
	select @lDivisionRes = @lDivisionRes + '<option value="0"> -- ALL -- </option>'
	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	select @lDepartmentRes = @lDepartmentRes + '<option value="0"> -- ALL -- </option>'
	select @lBatchRes = @lBatchRes + '<option value="0"> -- ALL -- </option>'
	
	select @lFeeColumns = @lFeeColumns + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sFee' AND TABLE_NAME='vFeeColumnName'
	
	select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + FCS.Title + '</td>
	<td style="width:670px; word-wrap:break-word;">' + FCS.ColumnName + '</td>
	<td style="width:80px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),FCS.Id) + ',''' + convert(varchar(20),FCS.Title) + ''',''' + convert(varchar(max),FCS.ColumnName) +''');">View</a></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,FCS.Id) + ');"><img src="../../Images/Del.png"></a></td></tr>'
	from sFee.tFeeCustomSearch FCS
	Left JOIN sSetup.tOrganizationMaster OM ON OM.Id = FCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	LEFT JOIN sSecurity.tUser U ON U.Id=FCS.CreatedUserId
	WHERE (FCS.CreatedUserId = @rUserId OR FCS.IsCommon = 1  OR FCS.IsCommonForOrg = 1)
	
	select @lAdmissionCategoryRes = @lAdmissionCategoryRes + '<option value="0"> -- ALL -- </option>'
	select @lAdmissionCategoryRes = @lAdmissionCategoryRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sStudent.tAdmissionCategoryMaster where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId order by Id
	
	select @lSavedReport = @lSavedReport + '<option value="0"> -- Select -- </option>'
	select @lSavedReport =  @lSavedReport + '<option value="' + convert(varchar,FCS.Id)+ '">' + FCS.Title + '</option>'
	from sFee.tFeeCustomSearch FCS
	Left JOIN sSetup.tOrganizationMaster OM ON OM.Id = FCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	LEFT JOIN sSecurity.tUser U ON U.Id=FCS.CreatedUserId
	WHERE (FCS.CreatedUserId = @rUserId OR FCS.IsCommon = 1  OR FCS.IsCommonForOrg = 1)
	
	--select  @lClassRes
	
	select @lOrgGroupRes as OrgGroupRes,@lOrganizationRes as OrganizationRes,
	@lStatusRes as StatusRes,@lReceiptBookRes as ReceiptBookRes,
	@lDivisionRes as DivisionRes,@lClassRes as ClassRes,@lFeeColumns as AvailableRes,
	@lReportList as ReportList,@lDepartmentRes as DepartmentRes,@lBatchRes as BatchRes,@lAdmissionCategoryRes AS AdmissionCategoryRes,
	@lSavedReport AS SavedReportList
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pGetPaidFeeReceiptList]
	@rOrgGroupBatchId int,
	@rOrgId int,
	@rBatchId int, 
	@rCode nvarchar(20),
	@rReportId int=0,  
	@rIsCancel bit=0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON
      
BEGIN   

	SELECT   
		(CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		R.Id AS ReceiptId,  
		R.ReceiptNumber,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		SA.RollNo,  
		SA.Code,  
		SA.Name,  
		ISNULL(PTM.Title,'') AS PayType,
		CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		ISNULL(R.BankName,'') AS BankName,  
		R.ReceiptAmount,		  
		CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		R.CreatedUserId,  
		ISNULL(U.LoginTitle,'') AS UserName,  
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		R.Remark,
		R.DiscountAmount,  
		ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		SA.OrgId,  
		SA.OrganizationName,  
		ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		SA.OrgGroupBatchId AS BatchId,  
		SA.BatchName,  
		R.ChequeDate,  
		R.ChequeClearDate,
		SA.ClassName,
		R.ReceiptAmount AS ReceiptAmountWithDiscount
	FROM   
		sFee.tReceipt R  
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId  
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId  
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId  
	WHERE   
		R.SourceTypeId = 2001
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804)) OR ((@rReportId = 20456 OR @rReportId = 30804)))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		ORDER BY R.ReceiptNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec sFee.pGetUserLists
-- drop proc sFee.pGetUserLists
CREATE OR ALTER PROCEDURE [sFee].[pGetUserLists]
@rPageIndex int,
@rDisplayTitle varchar(300),
@rLoginTitle varchar(300),
@rOrgId int
as
begin
	declare @lTotalRecords int,@lPageSize int = 10,@lResult varchar(max)='',@lPaging varchar(max)=''
	declare @tbltmp table
	(
		tid int identity(1,1),t_UserId bigint
	)
	insert into @tbltmp
	select Id from sSecurity.tUser
	where IsObsolete = 0 and OrgId = @rOrgId
	and (SourceTypeId = 95 or SourceTypeId = 0)
	and (DisplayTitle like @rDisplayTitle + '%' or @rDisplayTitle = '')
	and (LoginTitle like @rLoginTitle + '%' or @rLoginTitle = '')
	
	select @lTotalRecords = count(*) from @tbltmp
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lTotalRecords,@lPageSize)
	select @lPaging = replace(@lPaging,'ChangePage','ChangeUserPage')
	
	select @lResult = @lResult + '<tr attrId="' + convert(varchar,Id) + '" attrDisplayTitle="' + isnull(DisplayTitle,'') + '">
	<td><a style="cursor:pointer;" onclick="SelectUsers(this);">Select</a></td><td>' + isnull(DisplayTitle,'') + '</td>
	<td>' + isnull(LoginTitle,'') + '</td></tr>'
	from sSecurity.tUser U,@tbltmp where t_UserId = Id
	and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lPaging as UserPaging,@lResult as UserResult,@lTotalRecords as UserTotal
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pGSTReceiptAdd]
	
	@rId bigint,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rReceiptNumber int,
	@rReceiptDate date,
	@rReceiptAmount decimal(12,2),
	@rTotalReceiptAmount decimal(12,2),
	@rDiscountAmount decimal(12,2),
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(40),
	@rBankName nvarchar(200),
	@rReceiptBookId int,
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rRemark nvarchar(200),
	@rReceiptDetailXml [nvarchar](max),
	@rChequeDate date,
	@rCharge decimal(12,2)=0,
	@rFeeInvoiceId bigint = NULL,
	@rCollectionGroupId int = 0,
	@rPaymentTransactionId bigint = 0,
	@rIsDiscountCoupon bit = 0,
	@rReceiptPrintGroupId nvarchar(100) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lItemValue nvarchar(20) = ''
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 1016 AND SourceId = @rOrgId WHERE CM.Id = 239

	-- GST
	DECLARE @lAmountAfterDiscount decimal(12,2) = NULL
	DECLARE @lCGSTPercentage decimal(12,2)  = NULL
	DECLARE @lSGSTPercentage decimal(12,2)  = NULL
	DECLARE @lCGSTAmount decimal(12,2)  = NULL
	DECLARE @lSGSTAmount decimal(12,2)  = NULL

	IF(@lItemValue='True' AND @rPayTypeId = 1)
	BEGIN 
		SET @lAmountAfterDiscount = 0
		SET @lCGSTAmount = 0
		SET @lSGSTAmount = 0
		SET @lCGSTPercentage = 0
		SET @lSGSTPercentage = 0
	END
	ELSE
	BEGIN 		
		SET @lAmountAfterDiscount = @rTotalReceiptAmount - @rDiscountAmount
		SELECT @lCGSTPercentage = CGSTPercentage,@lSGSTPercentage = SGSTPercentage FROM sFee.tReceiptBookMaster WHERE Id = @rReceiptBookId
		SET @lCGSTAmount = @rReceiptAmount*@lCGSTPercentage / 100
		SET @lSGSTAmount = @rReceiptAmount*@lSGSTPercentage / 100
		SET @rReceiptAmount = @lAmountAfterDiscount + @lCGSTAmount + @lSGSTAmount
	END
-- GST
	
	DECLARE @loDoc INT
	DECLARE @lIsCreated INT
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

	BEGIN
	BEGIN TRY

	 SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 339 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	 IF @lConfigValue IS NULL 
		SET @lConfigValue = 'ReceiptBookWise'
	 
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		-- #Start Mantis Id : 0036287
			ELSE IF(@lConfigValue='Continuous Batch')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			-- #End Mantis Id : 0036287

		-- For Mantis 0038951, By Foram
		IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WHERE BatchId = @rBatchId AND OrgGroupBatchId = @rOrgGroupBatchId 
												AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND ReceiptBookId = @rReceiptBookId 
												AND PayTypeId = @rPayTypeId AND ChequeNo = @rChequeNo AND BankName = @rBankName AND Amount = @rTotalReceiptAmount AND ReceiptId > 0)
		BEGIN
			SELECT -104 AS Result
			RETURN	
		END
		-- For Mantis 0038951, By Foram
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
		Print @rReceiptNumber
	END	

	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rPayTypeId,@rPaymentTransactionId,@rReceiptBookId,@rChequeNo,@rIsCreated = @lIsCreated OUTPUT 
	-- Added @rChequeNo for mantis 0035484 By Foram
 	
	IF(@lIsCreated = 1)
 	BEGIN
		SELECT -501 AS Result
		RETURN
	END
	
	IF(@lIsCreated = -1)	-- For Mantis 0032370 by Foram
 	BEGIN
		SELECT -502 AS Result
		RETURN
	END
	IF(@lIsCreated = -2)	-- For Mantis 0035484 by Foram
 	BEGIN
		SELECT -503 AS Result
		RETURN
	END
 
	 BEGIN TRANSACTION	
	 IF(@rId = 0)	
	 BEGIN

	 DECLARE @lNextNumber BIGINT     
	 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output


	 INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		  PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   AmountAfterDiscount,
		   CGSTPercentage,
		   SGSTPercentage,
		   CGSTAmount,
		   SGSTAmount,
		   PaymentTransactionId,
		   ReceiptPrintGroupId,
		   IsDiscountCoupon  ---Added By Dhruv for Issue . 0011150
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @rCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @lAmountAfterDiscount,
		    @lCGSTPercentage,
		    @lSGSTPercentage,
		    @lCGSTAmount,
		    @lSGSTAmount,
		    @rPaymentTransactionId,
			@rReceiptPrintGroupId,
			@rIsDiscountCoupon
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	    FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
			EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
		END
	
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END

		SET @rId = @lNextNumber
	END 
	ELSE
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
		SELECT @rId AS RESULT
	END 
		
	-- For Mantis 0023321 By Foram on 14/03/2024 START
	DECLARE @lSourceId bigint, @lSourceTypeId1 smallint, @lBatchId int, @lOrgGroupBatchId int, @lReceiptBookId int, 
		    @lPayTypeId smallint, @lChequeNo nvarchar(40), @lBankName nvarchar(200), @lTotalReceiptAmount decimal(12,2)

	SELECT 
		@lSourceId = SourceId, 
		@lSourceTypeId1 = SourceTypeId, 
		@lBatchId = BatchId, 
		@lOrgGroupBatchId = OrgGroupBatchId, 
		@lReceiptBookId = ReceiptBookId, 
		@lPayTypeId = PayTypeId, 
		@lChequeNo = ChequeNo, 
		@lBankName = BankName, 
		@lTotalReceiptAmount = TotalReceiptAmount
	FROM sFee.tReceipt WHERE Id = @rId


	IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
													AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
													AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount)
	BEGIN
		UPDATE sFee.tPostDatePayment 
		SET ReceiptId = @rId, ReceiptDate = @rReceiptDate, StatusId = 752 
		WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
			AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
			AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount
	END
	ELSE
	BEGIN
		UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END WHERE ReceiptId = @rId
	END
	-- For Mantis 0023321 By Foram on 14/03/2024 END
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pHTMLFeeReceiptDetailsGet]
			
			
			
			@rReceiptId bigint = 0
			  

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	SELECT 
			FR.Id AS ReceiptId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,			
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.BatchName AS BatchTitle,
			
			
			--FRD.Amount AS PaidAmount,
			FR.ReceiptAmount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,
			--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) END AS ChequeNo,	
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) END AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,	
			sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,0) AS ReceiptAmountInWord,
			FR.Remark,
			RBM.ReportId,
			--OM.Title AS OrganizationName,
			--DM.Title AS DepartmentName,			
			FR.IsObsolete AS IsCancelReceipt,			
			ISNULL(CONVERT(NVARCHAR(20), FR.ChequeDate),'') AS ChequeDate,
			ISNULL(OM.DisplayTitle,'') AS OrganizationTitle
			
	       
	FROM 
	
			sFee.tReceipt FR				
			
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId			
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
			
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))			
   
   -- ORDER BY             FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pImportDepositAdd]
       
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rDepositHeadId int 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lStudentId bigint,
			@lAmount decimal(10,2),
			@lDepositDate date,
			@lPayTypeId nvarchar(100),	
			@lChequeNo nvarchar(100),
			@lBankName nvarchar(100),
			@lRemark nvarchar(200),
			@lAcademicId bigint
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 
	(
		Id bigint identity,
		StudentId bigint,
		Amount decimal(10,2),
		DepositDate date,
		PayTypeId nvarchar(100),
		ChequeNo nvarchar(100),
		BankName nvarchar(100),
		Remark nvarchar(200),
		AcademicId bigint
	)
	
	INSERT INTO #tTable1
	(
		StudentId,
		Amount,
		DepositDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		AcademicId
	)
	
	SELECT
		 T.c.value('@StudentId','bigint') AS Code,
		 T.c.value('@Amount','decimal(10,2)') AS Amount,
		 T.c.value('@DepositDate','date') AS DepositDate,
		 T.c.value('@PayTypeId','nvarchar(100)') AS PayTypeId,
		 T.c.value('@ChequeNo','nvarchar(100)') AS ChequeNo,
		 T.c.value('@BankName','nvarchar(100)') AS BankName,
		 T.c.value('@Remark','nvarchar(200)') AS Remark,
		 T.c.value('@AcademicId','bigint') AS AcademicId
		 
	FROM @loXML.nodes('/Table/ImportDepositAdd')T(c)
	
	
SELECT @lCount =  COUNT(Id) FROM #tTable1
	
WHILE @lCount > 0 

BEGIN				
	
	SELECT	
		@lStudentId = StudentId,
		@lAmount = Amount,
		@lDepositDate = DepositDate,
		@lPayTypeId = PayTypeId,
		@lChequeNo= ChequeNo,
		@lBankName = BankName,
		@lRemark = Remark,
		@lAcademicId = AcademicId
											 	 
	FROM #tTable1 WHERE Id = @lCount 

	IF EXISTS(SELECT Id FROM sFee.tDepositAdd WHERE StudentId=@lStudentId AND OrgGroupBatchId = @rOrgGroupBatchId AND DepositHeadId = @rDepositHeadId)
		BEGIN
			UPDATE sFee.tDepositAdd
			SET	
				DepositHeadId = @rDepositHeadId,				
				Amount = @lAmount,			
				DepositDate = @lDepositDate,
				PayTypeId = @lPayTypeId,
				ChequeNo = sSetup.fPortalXMLTagsReplaceReverse(@lChequeNo),
				BankName =sSetup.fPortalXMLTagsReplaceReverse( @lBankName),
				Remark =sSetup.fPortalXMLTagsReplaceReverse(@lRemark)
				
			WHERE 
				StudentId=@lStudentId
				AND OrgGroupBatchId = @rOrgGroupBatchId			
		END
		ELSE
		BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sFee.tDepositAdd', 0, 101, 1,@outNextNumber = @lNextNumber output
			DECLARE @lDepositNumber INT
			SELECT @lDepositNumber = ISNULL(MAX(DepositNumber),0)+1 FROM sFee.tDepositAdd WHERE OrgGroupBatchId = @rOrgGroupBatchId
			
			INSERT INTO sFee.tDepositAdd
				(
					Id,	
					DepositHeadId,	
					StudentId,
					Amount,
					DepositDate,
					PayTypeId,
					ChequeNo,
					BankName,
					Remark,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime,
					OrgGroupBatchId,
					AcademicId,
					DepositNumber
				)
			VALUES
				(
					@lNextNumber,
					@rDepositHeadId,
					@lStudentId,
					@lAmount,
					@lDepositDate,
					@lPayTypeId,
					sSetup.fPortalXMLTagsReplaceReverse(@lChequeNo),
					sSetup.fPortalXMLTagsReplaceReverse(@lBankName),				
					sSetup.fPortalXMLTagsReplaceReverse(@lRemark),
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgGroupBatchId,
					@lAcademicId,
					@lDepositNumber
				)
			   
		END
		SET @lCount = @lCount - 1
	SELECT 1 AS Result, '' AS ResultDetail				

 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pImportDepositAdjustment]
       
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rDepositHeadId int 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lStudentId bigint,
			@lAmount decimal(10,2),
			@lAdjustmentDate date,
			@lExpenseTypeId nvarchar(100),
			@lRemark nvarchar(200),
			@lAcademicId bigint
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 
	(
		Id bigint identity,
		StudentId bigint,
		Amount decimal(10,2),
		AdjustmentDate date,
		ExpenseTypeId nvarchar(100),
		Remark nvarchar(200),
		AcademicId bigint
	)
	
	INSERT INTO #tTable1
	(
		StudentId,
		Amount,
		AdjustmentDate,
		ExpenseTypeId, 
		Remark,
		AcademicId
	)
	
	SELECT
		 T.c.value('@StudentId','bigint') AS Code,
		 T.c.value('@Amount','decimal(10,2)') AS Amount,
		 T.c.value('@AdjustmentDate','date') AS AdjustmentDate,
		 T.c.value('@ExpenseTypeId','nvarchar(100)') AS ExpenseType,
		 T.c.value('@Remark','nvarchar(200)') AS Remark,
		 T.c.value('@AcademicId','bigint') AS AcademicId
		 
	FROM @loXML.nodes('/Table/ImportDepositAdjustment')T(c)
	
	
SELECT @lCount =  COUNT(Id) FROM #tTable1
	
WHILE @lCount > 0 

BEGIN				
	
	SELECT	
		@lStudentId = StudentId,
		@lAmount = Amount,
		@lAdjustmentDate = AdjustmentDate,
		@lExpenseTypeId = ExpenseTypeId,
		@lRemark = Remark,
		@lAcademicId = AcademicId
											 	 
	FROM #tTable1 WHERE Id = @lCount 

	IF EXISTS(SELECT Id FROM sFee.tDepositAdjustment WHERE StudentId=@lStudentId AND OrgGroupBatchId = @rOrgGroupBatchId AND DepositHeadId = @rDepositHeadId)
		BEGIN
			UPDATE sFee.tDepositAdjustment
			SET	
				DepositHeadId = @rDepositHeadId,				
				Amount = @lAmount,			
				AdjustmentDate = @lAdjustmentDate,
				Remark = @lRemark,
				FeeDepositExpenseTypeId = @lExpenseTypeId
			WHERE 
				StudentId=@lStudentId
				AND OrgGroupBatchId = @rOrgGroupBatchId			
		END
		ELSE
		BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sFee.tDepositAdjustment', 0, 101, 1,@outNextNumber = @lNextNumber output
			DECLARE @lAdjustmentNumber INT
			SELECT @lAdjustmentNumber = ISNULL(MAX(AdjustmentNumber),0)+1 FROM sFee.tDepositAdjustment WHERE OrgGroupBatchId = @rOrgGroupBatchId
			
			INSERT INTO sFee.tDepositAdjustment
				(
					Id,	
					DepositHeadId,	
					StudentId,
					Amount,
					AdjustmentDate,
					Remark,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime,
					OrgGroupBatchId,
					FeeDepositExpenseTypeId,
					AcademicId,
					AdjustmentNumber
				)
			VALUES
				(
					@lNextNumber,
					@rDepositHeadId,
					@lStudentId,
					@lAmount,
					@lAdjustmentDate,				
					@lRemark,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgGroupBatchId,
					@lExpenseTypeId,
					@lAcademicId,
					@lAdjustmentNumber
				)
			   
		END
		SET @lCount = @lCount - 1
	SELECT 1 AS Result, '' AS ResultDetail				

 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pImportFee]
    @rOrgGroupId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,@lCode nvarchar(20),@lFeeHead nvarchar(100),
		@lTitle nvarchar(100),@lNumber int,@lFeeHeadId int,@lOrderIndex int
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	
		Code nvarchar(20), 
		Number int, 
		Name nvarchar(100),
		FeeHead nvarchar(100), 
		OrderIndex int
	)
	INSERT INTO #tTable
	(   
		Code, 
		Number, 
		Name, 
		FeeHead, 
		OrderIndex 
	)
	SELECT
		Code, 
		Number, 
		Name, 
		FeeHead, 
		OrderIndex
	FROM OPENXML (@intDoc, '/Table/ImportFee', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',			
		Name nvarchar(100) '@Name',			
		Number int '@Number',			
		FeeHead nvarchar(100) '@FeeHead',			
		OrderIndex int '@OrderIndex'
	)
EXEC sp_xml_removedocument @intDoc
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 
BEGIN	
		SET @lCode = ''
		SET @lTitle = ''
		SET @lNumber = 0
		SET @lFeeHeadId = 0
		SET @lOrderIndex = 0
		SET @lFeeHead=''
  SELECT		
		@lCode = Code,
		@lTitle = Name,
		@lNumber = Number,
		@lOrderIndex = OrderIndex,
	    @lFeeHead = FeeHead
FROM #tTable WHERE Id = @lCount  
		--BEGIN TRANSACTION
	select @lFeeHeadId=Id  from sFee.tFeeHeadMaster where OrgGroupId=@rOrgGroupId AND Title =@lFeeHead
	 IF NOT EXISTS(select 1 from sFee.tFeeMaster where Code=@lCode AND OrgGroupId=@rOrgGroupId)
  BEGIN	
		EXEC sFee.pFeeMasterAdd 0,@lNumber,@lCode,@lTitle,@lFeeHeadId,@lOrderIndex,0,@rUserId,@rOrgGroupId
	END
	 --ELSE	 
	 --BEGIN	
		--  UPDATE sFee.tFeeMaster	
		--  SET Title=@lTitle,Number=@lNumber,FeeHeadId=@lFeeHeadId,OrderIndex=@lOrderIndex,
		--  UpdatedUserId = @rUserId,UpdatedDateTime= sCommon.fGetDate() 
	 --     WHERE Code=@lCode AND OrgGroupId = @rOrgGroupId
		-- END
		 SET @lCount = @lCount - 1
		--COMMIT TRANSACTION			
END
	SELECT 1
	END TRY
	BEGIN CATCH
	
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pImportFeeExpenseBulk]
       
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	--@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rFeeId int=0 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lAcademicId bigint,
			@lExpenseAmount decimal(10,2),
			@lExpenseDate date,
			@lExpenseRemark nvarchar(200),	
			@lFeeExpenseTypeId int,
			@lFeeSetupId int
			
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 
	(
		Id bigint identity,
		AcademicId bigint,
		ExpenseAmount decimal(10,2),
		ExpenseDate date,
		ExpenseRemark nvarchar(200),
		FeeExpenseTypeId int,
		FeeSetupId int
	)
	
	INSERT INTO #tTable1
	(
		AcademicId,
		ExpenseAmount,
		ExpenseDate,
		ExpenseRemark,
		FeeExpenseTypeId,
		FeeSetupId
	)
	
	
	SELECT
		 T.c.value('@AcademicId','bigint') AS AcademicId,
		 T.c.value('@Amount','decimal(10,2)') AS Amount,
		 T.c.value('@ExpenseDate','date') AS ExpenseDate,
		 T.c.value('@Remark','nvarchar(200)') AS Remark,
		 T.c.value('@ExpenseTypeId','int') AS FeeExpenseTypeId,
		 T.c.value('@FeeSetupId','int') AS FeeSetupId
		 
	FROM @loXML.nodes('/Table/Import')T(c)
	
	
	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 

BEGIN	
		SELECT	
				@lAcademicId =AcademicId,
				@lExpenseAmount =ExpenseAmount,
				@lExpenseDate =ExpenseDate,
				@lExpenseRemark=ExpenseRemark,
				@lFeeExpenseTypeId=FeeExpenseTypeId,
				@lFeeSetupId=FeeSetupId
		FROM #tTable1 WHERE Id = @lCount
		 
		INSERT INTO sFee.tFeeExpense
			(
				AcademicId,	
				ExpenseAmount,
				ExpenseDate,
				ExpenseRemark,
				CreatedUserId,
				CreatedDateTime,
				FeeExpenseTypeId,
				FeeSetupId
			)
		VALUES
			(
				@lAcademicId,
				@lExpenseAmount,
				@lExpenseDate,
				sSetup.fPortalXMLTagsReplaceReverse(@lExpenseRemark),		
				@rCreatedUserId,
				sCommon.fGetDate(),
				@lFeeExpenseTypeId,
				@lFeeSetupId
			)
	SET @lCount = @lCount - 1
	SELECT 1 AS Result, '' AS ResultDetail				
END
SELECT 1 AS Result, '' AS ResultDetail	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pImportFeeOpening]
       
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	--@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rFeeId int=0 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lAcademicId bigint,
			@lFeeSetupId int,
			@lOpeningAmount decimal(10,2)
			
			
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 
	(
		Id bigint identity,
		AcademicId bigint,
		FeeSetupId int,
		OpeningAmount decimal(10,2)
	)
	
	INSERT INTO #tTable1
	(
		AcademicId,
		FeeSetupId,
		OpeningAmount
	)
	
	
	SELECT
		 T.c.value('@AcademicId','bigint') AS AcademicId,
		 T.c.value('@FeeSetupId','int') AS FeeSetupId,
		 T.c.value('@OpeningAmount','decimal(10,2)') AS OpeningAmount
		 
	FROM @loXML.nodes('/Table/Import')T(c)
	
	
	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 

BEGIN	
		SELECT	
				@lAcademicId =AcademicId,
				@lFeeSetupId =FeeSetupId,
				@lOpeningAmount =OpeningAmount
				
		FROM #tTable1 WHERE Id = @lCount
		 
		 IF NOT Exists(SELECT 1 FROM  sFee.tFeeOpening WHERE AcademicId = @lAcademicId AND FeeSetupId=@lFeeSetupId)
		 BEGIN
			INSERT INTO sFee.tFeeOpening
			(
				AcademicId,	
				FeeSetupId,
				OpeningAmount,
				CreatedUserId,
				CreatedDateTime
			)
		VALUES
			(
				@lAcademicId,
				@lFeeSetupId,		
				@lOpeningAmount,
				@rCreatedUserId,
				sCommon.fGetDate()
			)
			SET @lCount = @lCount - 1
			SELECT 11 AS Result, '' AS ResultDetail		
		 END
		 ELSE
		 BEGIN
			UPDATE sFee.tFeeOpening
			SET
			AcademicId=@lAcademicId,
			FeeSetupId=@lFeeSetupId,
			OpeningAmount=@lOpeningAmount,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			WHERE AcademicId = @lAcademicId AND FeeSetupId=@lFeeSetupId
		 END
		
	SET @lCount = @lCount - 1
	SELECT 11 AS Result, '' AS ResultDetail				
END
--SELECT 1 AS Result, '' AS ResultDetail	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pLateFeeRuleMasterAdd]
	    @rOrgId int,
        @rId int,
       -- @rCode nvarchar(20),
        @rTitle nvarchar(100),
		@rFeeRule nvarchar(max),
        @rIsObsolete bit
       
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId)
		--	BEGIN
		--	SELECT -101 as Result
		--	RETURN
		--END 
	
		IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			SELECT -102 as Result
			RETURN
		END 

			IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE FeeRule=@rFeeRule AND OrgId=@rOrgId)
			BEGIN
			SELECT -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--IF EXISTS (SELECT Id FROM sFee.LateFeeRuleMaster WHERE  Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND ReceiptBookId=@rReceiptBookId AND Id<>@rId)
		--BEGIN
		--	SELECT -101 as Result
		--	RETURN
		--END	
		IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE  Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -102 as Result
			RETURN
		END 

		IF EXISTS (SELECT Id FROM sFee.tLateFeeRuleMaster WHERE FeeRule=@rFeeRule AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			SELECT -103 as Result
			RETURN
       END
	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tLateFeeRuleMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO sFee.tLateFeeRuleMaster
		(
			OrgId,
			Id,
			--Code,
			Title,
			FeeRule,
			IsObsolete	
		)
	VALUES
		(
		    @rOrgId,
			@lNextNumber,
			--@rCode,
			@rTitle,
			@rFeeRule,
			@rIsObsolete
			
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tLateFeeRuleMaster
			--Code=@rCode,
			SET Title=@rTitle,
		    	FeeRule=@rFeeRule,
			IsObsolete=@rIsObsolete
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
	--if not exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGroupId)
	--BEGIN
	--	INsert Into sSystem.tPortalSync
	--	(
	--		OrgGroupId,
	--		FeeChange
	--	)
	--	Values
	--	(
	--		@rOrgGroupId,1
	--	)
	--END
	--ELse
	--BEGIN
	--	Update sSystem.tPortalSync
	--	Set
	--		FeeChange=1
	--	Where OrgGroupId=@rOrgGroupId
	
	--END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result 
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pLateFeeRuleMasterGet]
	 
	 @rOrgId int,
	 @rId int,
	 --@rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rFeeRule nvarchar(200)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			Id,
			--CGM.Code,
			Title,
			IsObsolete,
			OrgId,
			ISNULL(FeeRule,'') AS FeeRule
			
	FROM 
			sFee.tLateFeeRuleMaster 		
	WHERE 
			(OrgId = @rOrgId)
			AND	((Id = @rId) OR (@rId = 0))
			--AND ((CGM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pMenuMasterAdd]
     @rId int,
     @rParentMenuId int,
     @rTitle nvarchar(100), 
     @rTitleResourceKeyid int, 
     @rScreenId int,
     @rIsObsolete bit,
     @rOrderNumber smallint,
     @rShortcutKey nvarchar(50),
     @Status char
      	       	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

IF(@Status = 'A')	
	BEGIN
		
	Declare @MaxId Int 
	SET @MaxId=(SELECT MAX(id) as Id FROM sSecurity.tMenu)
	SET @MaxId=@MaxId + 1
	
	INSERT INTO sSecurity.tMenu
		(			
			 Id,
			 ParentMenuId,
			 Title,
			 TitleResourceKeyId,
			 ScreenId,
			 IsObsolete,
			 OrderNumber,
			 ShortcutKey

		)
	VALUES
		(			 
			 @MaxId, 
			 @rParentMenuId , 
			 @rTitle , 
			 @rTitleResourceKeyid , 
			 @rScreenId , 
			 @rIsObsolete,
			 @rOrderNumber ,			  
			 @rShortcutKey
		)
    SELECT 1 AS Result
	
	END	 

ELSE IF (@Status = 'U')
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sSecurity.tMenu
	    SET
	        ParentMenuId=@rParentMenuId,	        
			Title=@rTitle,
			TitleResourceKeyid=@rTitleResourceKeyid,
			ScreenId=@rScreenId,
			IsObsolete=@rIsObsolete,			
			OrderNumber=@rOrderNumber,
			ShortcutKey=@rShortcutKey
	      WHERE Id = @rId
	 SELECT 2 AS Result
	 END 

ELSE IF (@Status = 'D')
	 BEGIN
	  DELETE 
	    FROM 
	       sSecurity.tMenu 
	  WHERE Id=@rId
	  
	  SELECT 3 AS Result
	  	  
	 END

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 
CREATE OR ALTER PROCEDURE [sFee].[pMobileFeeReceiptDetailsGet]
		
		@rAcademicId bigint=0,
		@rReceiptId bigint =0,
		@rType nvarchar(20)=''
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	IF(@rType = 'FeeReceiptList')
		BEGIN
			SELECT 
				R.Id AS ReceiptId,
				ISNULL(RBM.Title,'') AS ReceiptBookTitle,
				R.ReceiptNumber,
				R.ReceiptDate,
				R.ReceiptAmount
			FROM sFee.tReceipt R
				INNER JOIN sStudent.tAcademic A ON A.Id = R.SourceId
				INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=R.ReceiptBookId
			WHERE 
				R.SourceTypeId = 2001
				AND	A.Id = @rAcademicId
				AND R.IsObsolete = 0 --Added for mantis : 38898
		END
	ELSE IF(@rType = 'FeeReceiptDetails')
		BEGIN
			SELECT
				R.Id AS ReceiptId,
				R.ReceiptNumber,
				SA.ClassId,
				SA.DivisionId,
				SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
				SA.RollNo,
				SA.Code,
				SA.Name,
				ISNULL(PTM.Title,'') AS PayType,
				CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
				ISNULL(ChequeDate,'01/01/0001') As ChequeDate,
				ISNULL(R.BankName,'') AS BankName,
				R.ReceiptAmount,
				R.ReceiptDate,
				R.CreatedUserId,
				ISNULL(U.DisplayTitle,'') AS UserName,
				ISNULL(RBM.Title,'') AS ReceiptBookTitle,
				ISNULL(RBM.BankName,'') AS ReceiptBookBank,
				ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
				ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
				R.Remark,
				R.DiscountAmount,
				ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,
				SA.OrgId,
				SA.OrganizationName,
				ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,
				ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,
				ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,
				ISNULL(R.CGSTAmount,0) AS CGSTAmount,
				ISNULL(R.SGSTAmount,0) AS SGSTAmount,
				SA.OrgGroupBatchId AS BatchId,
				SA.BatchName
			FROM 
				sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA
					ON SA.AcademicId=R.SourceId 
				INNER JOIN sFinanceCommon.tPayTypeMaster PTM
					ON PTM.Id=R.PayTypeId
				INNER JOIN sFee.tReceiptBookMaster RBM 
					ON RBM.Id=R.ReceiptBookId
				LEFT JOIN sSecurity.tUser U
					ON U.Id=R.CreatedUserId
			WHERE 
				R.SourceTypeId = 2001
				AND R.Id = @rReceiptId 
				AND R.IsObsolete = 0 --Added for mantis : 38898
		END

	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pMobileFeeReceiptRefundDetailsGet]
		
		@rAcademicId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT
		--RR.Id AS FeeRefundId,
		R.Id AS ReceiptId,
		A.AcademicId,
		A.RollNo,
		SM.Code AS Code,
		SM.FirstName+' '+SM.LastName AS Name,
		R.ReceiptNumber,
		R.ReceiptDate,
		RR.RefundDate,
		ISNULL(RR.RefundAmount,0)AS RefundAmount,
		ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,
		ISNULL(R.DiscountAmount,0)AS DiscountAmount,
		RR.PayTypeId,
		PTM.Title AS PayType,
		RR.ChequeNo,
		RR.BankName,
		R.ReceiptBookId,
		RBM.Title AS ReceiptBook,
		A.OrgId,
		OM.DisplayTitle AS Organization,
		RR.BatchId,
		BM.Title AS Batch,
		RR.Remark
  FROM 
		sFee.tReceiptRefund RR
		INNER JOIN sFee.tReceipt R ON RR.ReceiptId = R.Id
		INNER JOIN sStudent.vStudentAcademic A
			ON A.AcademicId=R.SourceId
		INNER JOIN sStudent.tStudentMaster SM
			ON SM.Id=A.StudentId
		INNER JOIN sCommon.tSourceTypeMaster STM
			ON STM.Id=RR.SourceTypeId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=RR.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM
			ON OM.Id=SM.OrgId
		INNER JOIN sSetup.tBatchMaster BM
			ON BM.Id=RR.BatchId  
WHERE 
		 A.AcademicId = @rAcademicId
		 AND 
		 (RR.SourceTypeId=2001)
		 AND 
		 RR.IsObsolete = 0
	ORDER BY R.ReceiptNumber DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pMorePendingfee]
	 @OrgGroupId int=0,
	 @configration int = 0,
	 @CollectionGroup int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

  BEGIN
	SELECT 
	 Top 1 1010 as 'OrgId',1001 as 'Class',1500 as 'StudentId',10 as 'StudentName'
	FROM 
		sStudent.vStudentAllDetail S
			
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
-- exec [sFee].[pMyFeeGet] 1201000000102,2001,120100001,0,'CollectionGroup'  
CREATE OR ALTER PROCEDURE [sFee].[pMyFeeGet]    
      
  @rSourceId bigint ,  --1201000000102  
  @rSourceTypeId int,  --2001  
  @rBatchId int,  --120100001  
  @rStudentId bigint =0,  
  @rDisplay varchar(20)=''  
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    BEGIN      
 if (@rStudentId <> 0)    
 SELECT @rSourceId = Id, @rSourceTypeId = 2001 FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId    
  DECLARE @lClassId int    
  DECLARE @lAdmissionCategoryId int    
  SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId    
    
  -----------------------------------------------------------------------------------------------------------------------------------------  
  
  create table #TempTable  
  (id int identity(1,1),Feeid bigint,FeeName nvarchar(100),FeeSetupId bigint,isOptional tinyint,IsVariable tinyint,Amount decimal(12,2),  
  StartDate Date,EndDate Date,FAAmount decimal(12,2),DiscountAmount decimal(12,2),AdditionalAmount decimal(12,2),PaidAmount decimal(12,2),PendingAmount decimal(12,2),  
  NotApplicableAmount decimal(12,2),Remark Varchar(Max),OrderIndex int,ReceiptNumber int,ReceiptDate Date,ReceiptBookId bigint,CollectionGroupId Bigint,  
  Col_StartDate Date,Col_EndDate Date,CollectionGroup varchar(100),FeeHeadid Bigint,FeeHead nvarchar(100),FeeDuration Varchar(100))  
  
  
  Insert into #TempTable  
  
SELECT     
   FM.Id AS FeeId,    
   FM.Title AS FeeName,    
   FS.Id AS FeeSetupId,    
   ISNULL(FS.IsOptional,0)AS IsOptional,    
   ISNULL(FS.IsVariable,0)AS IsVariable,    
   ISNULL(FS.Amount,0)AS Amount,    
   ISNULL(FS.StartDate,'1900-01-01')AS StartDate,    
   ISNULL(FS.EndDate,'1900-01-01')AS EndDate,    
   ISNULL(FA.VariableAmount,0.00)AS FAAmount,    
   ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,    
   ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,    
   ISNULL(R.PaidAmount,0) AS PaidAmount,    
   ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,    
   ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount,    
   ISNULL(FA.Remark,'') AS Remark,    
   FM.OrderIndex,    
   0 AS ReceiptNumber,    
   '1900-01-01'AS ReceiptDate,    
   ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,    
   ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,  
   ISNULL(CGM.StartDate,'') as Col_StartDate,  
 ISNULL(CGM.EndDate,'') as Col_EndDate,  
   ISNULL(CGM.Title,'') AS CollectionGroup,    
   FM.FeeHeadId,    
   FHM.Title AS FeeHead,    
   FS.FeeDuration    
  FROM     
   sFee.tFeeMaster FM    
  INNER JOIN     
  (    
   SELECT     
    FS1.FeeId,    
    FS1.Id,    
    ISNULL(FS1.IsOptional,0)AS IsOptional,    
    ISNULL(FS1.IsVariable,0)AS IsVariable,    
    ISNULL(FS1.Amount,0)AS Amount,    
    ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,    
    ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,    
    FS1.BatchId,    
    ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,    
    ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,  
    ISNULL(FS1.FeeDuration,'')  AS FeeDuration    
   FROM sFee.tFeeSetup FS1    
          
    WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0    
    AND FS1.BatchId = @rBatchId    
    UNION ALL    
        
   SELECT     
    FS1.FeeId,    
    FS1.Id,    
    ISNULL(FS1.IsOptional,0)AS IsOptional,    
    ISNULL(FS1.IsVariable,0)AS IsVariable,    
    ISNULL(FS1.Amount,0)AS Amount,    
    ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,    
    ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,    
    FS1.BatchId,    
    ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,    
    ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,   
    ISNULL(FS1.FeeDuration,'') AS FeeDuration    
         
   FROM sFee.tFeeSetup FS1    
        
  INNER JOIN sFee.tFeeOptional FO    
   ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)    
   WHERE    
    FS1.BatchId = @rBatchId    
   AND FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1    
  ) FS ON FS.FeeId=FM.Id    
  INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId    
  LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId    
  LEFT JOIN sFee.tFeeAllocation FA    
   ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)    
  LEFT JOIN    
  (    
      SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId    
      FROM    
      sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id       
   WHERE          
    R.SourceId= @rSourceId    
   AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))    
   AND R.IsObsolete = 0     
   AND R.BatchId = @rBatchId    
    GROUP BY FeeSetupId    
  ) R ON R.FeeSetupId = FS.Id     
WHERE     
 FS.BatchId=@rBatchId    
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC   
   
 --------------------------------------------------------------------------------------------  
 -- Get Group Wise Data ---  
  
 IF(@rDisplay = 'Fee Head')  
 BEGIN  
 Print @rDisplay + '1'  
   
 Create Table #temp_head  
 (id int identity(1,1),FeeHeadid Bigint,FeeHead nvarchar(200),Amount decimal(12,2),StartDate Date,EndDate Date,FAAmount decimal(12,2),  
 DiscountAmount decimal(12,2),AdditionalAmount decimal(12,2),PaidAmount decimal(12,2),PendingAmount decimal(12,2),  
 NotApplicableAmount decimal(12,2))  
  
 Insert into #temp_head  
 select FeeHeadid,FeeHead,sum(Amount) as Amount,min(StartDate) as StartDate,Max(EndDate) as EndDate,sum(FAAmount) as FAAmount,  
 sum(DiscountAmount) as DiscountAmount,sum(AdditionalAmount) as AdditionalAmount,sum(PaidAmount) as PaidAmount,  
 sum(PendingAmount) as PendingAmount,sum(NotApplicableAmount) as NotApplicableAmount--,Remark,ReceiptDate,ReceiptBookId,CollectionGroupID,CollectionGroup  
 from #TempTable  
 group by Feeheadid,FeeHead  
  
 Declare @i int  
  
 while(@i<= (Select Count(*) from #temp_head))  
 BEGIN  
 Update #temp_head set StartDate = (Select min(StartDate) from #tempTable A Where A.FeeHeadid = #temp_head.FeeHeadid) where id=@i  
 Update #temp_head set EndDate = (Select Max(EndDate) from #tempTable A Where A.FeeHeadid = #temp_head.FeeHeadid) where id=@i  
 PRINT 1  
 END  
  
 select FeeHeadid as Feeid,FeeHead as FeeName,PendingAmount,'' as IsVariable,  
 '' as FeeSetupId,'' as Remark,'' as ReceiptNumber,'' as ReceiptDate,'' as CollectionGroupId,FeeHeadid,0 as IsOptional,  
 (case when FAAmount>0 then FAAmount else Amount + AdditionalAmount - DiscountAmount - NotApplicableAmount End) as Amount ,  
 StartDate,EndDate,FAAmount,DiscountAmount,AdditionalAmount,PaidAmount,PendingAmount,NotApplicableAmount,'' as FeeDuration from #temp_head  
   
 END  
  
 ELSE IF(@rDisplay = 'Collection Group')  
 BEGIN  
  
 select CollectionGroupID as Feeid,CollectionGroup as FeeName, sum(PendingAmount) as PendingAmount,CollectionGroupID as FeeHeadid,  
 '' as IsVariable,'' as FeeSetupId,'' as Remark,'' as ReceiptNumber,'' as ReceiptDate,'' as CollectionGroupId,0 as IsOptional,  
 (case when sum(FAAmount)>0 then sum(FAAmount) else sum(Amount) + sum(AdditionalAmount) - sum(DiscountAmount) - sum(NotApplicableAmount) End) as Amount ,  
 Col_startDate as StartDate,Col_EndDate as EndDate,sum(FAAmount) as FAAmount,sum(DiscountAmount) as DiscountAmount,  
 sum(AdditionalAmount) as AdditionalAmount,sum(PaidAmount) as PaidAmount,sum(PendingAmount) as PendingAmount,  
 sum(NotApplicableAmount) as NotApplicableAmount,'' as FeeDuration from #TempTable  
 group by CollectionGroupID,CollectionGroup,Col_startDate,Col_EndDate  
  
 END  
  
 ELSE  
 BEGIN  
  
 select CollectionGroupID as Feeid,FeeName,PendingAmount,   
 '' as IsVariable,'' as FeeSetupId,'' as Remark,'' as ReceiptNumber,'' as ReceiptDate,'' as CollectionGroupId,0 as IsOptional,  
 CollectionGroupID as FeeHeadid,  
 (FAAmount + Amount + AdditionalAmount) - (DiscountAmount + NotApplicableAmount) as Amount ,  
 StartDate,EndDate,FAAmount,DiscountAmount, AdditionalAmount,PaidAmount,PendingAmount,NotApplicableAmount,'' as FeeDuration from #TempTable  
  
 END  
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pNotApplicableFeeDashBoardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rFeeHeadId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @rStudentCountStatus TABLE (  
			AcademicId bigint,  
			ReceiptBookId int,
			OrgName nvarchar(30), 
			OrgId int, 
			DepartmentId int, 
			ClassId int, 
			DivisionId int, 
			Amount decimal(12,0),  
			FAAmount decimal(12,0),  
			DiscountAmount decimal(12,0),  
			AdditionalAmount decimal(12,0),  
			NotApplicableAmount decimal(12,0),  
			PaidAmount decimal(12,0),  
			PendingAmount decimal(12,0),
			AdmissionDate Date,
			LeftDate date
		)  
   
		INSERT INTO @rStudentCountStatus  
			SELECT   
			SA.AcademicId,  
			FS.ReceiptBookId,
			SA.OrganizationName,
			SA.OrgId,
			SA.DepartmentId,
			SA.ClassId,
			SA.DivisionId,  
			ISNULL(FS.Amount,0)AS Amount,  
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,  
			ISNULL(R.PaidAmount,0) AS PaidAmount,  
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount  ,
			A.AdmissionDate,
			A.LeftDate
		FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN sStudent.tStudentAdmission A ON A.StudentId = SA.StudentId
		INNER JOIN   
		(  
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
		FROM sFee.tFeeSetup FS1  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=0) OR (0=0))  
			AND ((SA1.AdmissionCategoryId=0) OR (0=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
		WHERE   
			((FS1.ClassId=0) OR (0=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=0) OR (0=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.IsOptional=0)  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			
		UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
			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 FS1.BatchId = SA1.BatchId  
			AND ((SA1.ClassId=0) OR (0=0))   
			AND ((SA1.AdmissionCategoryId=0) OR (0=0))  
		WHERE  
			((FS1.ClassId=0) OR (0=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=0) OR (0=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (0=0))  
			AND (FS1.IsOptional=1)  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			) FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN  
		(  
		SELECT   
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
		FROM  
			sFee.tReceipt R   
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.ClassId=0 OR 0=0)   
			AND (SA1.DivisionId=0 OR 0=0)  
		WHERE    
			(R.SourceTypeId = 2001)  
			AND (R.IsObsolete = 0)   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)  
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND (R.ReceiptDate <= getdate())  
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
		GROUP BY FeeSetupId,R.SourceId  
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id  
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId   
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId  
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = 110100101) OR (110100101 = 0))   
		LEFT JOIN 
		(  
		SELECT   
			AT.SourceId   
		FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		) RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		WHERE   
			((0 = 0 AND  1 = 1) OR (0 = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))  
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))     
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))     
			AND (SA.StatusId=0 OR 0=0)  
			AND ((SA.RollNo >= 0) OR (0=0))  
			AND ((SA.RollNo <= 0) OR (0=0))  
			AND ((SA.Code='') OR (''=''))  
			AND ((SA.DepartmentId=0) OR (0=0))    
			AND ((SA.ExemptionTypeId=0) OR (0=0))    
			AND ((SA.ClassId=0) OR (0=0))  
			AND ((SA.DivisionId=0) OR (0=0))     
		--GROUP BY SA.AcademicId,  
		--	FS.ReceiptBookId,
		--	SA.OrganizationName,
		--	SA.OrgId,
		--	SA.DepartmentId,
		--	SA.ClassId,
		--	SA.DivisionId,  
		--	SA.ClassName,
		--	SA.DivisionName, FS.Amount,FA.VariableAmount,FA.AdditionalAmount,FA.DiscountAmount,FA.NotApplicableAmount,R.PaidAmount,A.AdmissionDate,
		--	A.LeftDate
		ORDER BY SA.AcademicId   
  IF(@rType='Organization')
  BEGIN
    SELECT ISNULL(SUM(SCS.NotApplicableAmount),0) AS  NotApplicableAmount FROM  @rStudentCountStatus SCS
  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
  where
	 LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	--AND ((SA.CreatedUserId=@rUserId) OR (@rUserId=0))
	--AND (SA.IsObsolete = 0) 
	--SELECT ISNULL(SUM(FA.NotApplicableAmount),0) AS  NotApplicableAmount FROM sFee.tReceipt R
	--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	--INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	--LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	--LEFT JOIN sFee.tFeeAllocation FA ON  FA.SourceId = SA.AcademicId 
	--WHERE R.SourceTypeId = 2001
 --   AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	--AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	--AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--AND (R.IsObsolete = 0) 
	
  END
  
  IF(@rType='ReceiptBook')
  BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(SCS.NotApplicableAmount),0) AS  NotApplicableAmount 
		FROM  @rStudentCountStatus SCS
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=SCS.ReceiptBookId
		WHERE 
		LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--AND (R.IsObsolete = 0) 
		GROUP BY RBM.Id,RBM.Title
		--SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,ISNULL(SUM(FA.NotApplicableAmount),0) AS  NotApplicableAmount FROM sFee.tReceipt R
		--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		--LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		--LEFT JOIN sFee.tFeeAllocation FA ON  FA.SourceId = SA.AcademicId 
		--WHERE R.SourceTypeId = 2001
		--AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		--AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		--AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--AND (R.IsObsolete = 0) 
		--GROUP BY RBM.Id,RBM.Title
  END
  
  IF(@rType='FeeHead')
  BEGIN

		SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,ISNULL(SUM(SCS.NotApplicableAmount),0) AS  NotApplicableAmount FROM  @rStudentCountStatus SCS
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=SCS.ReceiptBookId
		INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		WHERE  LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--AND (R.IsObsolete = 0) 
		AND (SCS.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
  END
  
  IF(@rType='FeeMaster')
  BEGIN

		SELECT  FM.Id AS FeeHeadId,FM.Title AS FeeMaster,ISNULL(SUM(SCS.NotApplicableAmount),0) AS  NotApplicableAmount FROM  @rStudentCountStatus SCS
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SCS.AcademicId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=SCS.ReceiptBookId
		INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		WHERE  LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SCS.ReceiptBookId = @rReceiptBookId)  
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
		END
 
  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOldExemptionFeeToExceptionAdd]
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId nvarchar(max),
	@rNewFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rXml  nvarchar(MAX)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 
	IF OBJECT_ID('tempdb..#TempOldExemptionFeeImport') IS NOT NULL DROP TABLE #TempOldExemptionFeeImport

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lCount int
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	CREATE TABLE #TempOldExemptionFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[ExemptionAmount] decimal(12,2) NULL
	)
	
	INSERT INTO #TempOldExemptionFeeImport 
	(
		StudentId,
		AcademicId,
		ExemptionAmount
	)	
	SELECT	
			A.StudentId,
			A.AcademicId,
			A.ExemptionAmount
	FROM OPENXML (@intDoc, '/Table/OldExemptionFeeImport', 1)
	WITH
	(
			StudentId bigint '@StudentId',
			AcademicId bigint '@AcademicId',
			ExemptionAmount decimal(12,2) '@ExemptionAmount'
	)A 
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldExemptionFeeImport
	
	--SELECT * FROM #TempOldExemptionFeeImport
	BEGIN TRANSACTION
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lExemptionAmount decimal(12,2)
		DECLARE @lAdmissionCategoryId int

		SELECT @lStudentId = StudentId,@lExemptionAmount=ExemptionAmount FROM #TempOldExemptionFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND AdmissionCategoryId = @lAdmissionCategoryId
		
		IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
		BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					ISNULL(FA.VariableAmount,0.00)AS FAAmount,
					ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
					ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
					ISNULL(R.PaidAmount,0) AS PaidAmount,
					ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS PendingAmount,
					ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount
				INTO #TempFeeSetup 
				FROM sFee.tFeeMaster FM
				INNER JOIN 
				(SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
					ISNULL(FS1.FeeDuration,'')  AS FeeDuration
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
					ISNULL(FS1.FeeDuration,'') AS FeeDuration
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				) FS ON FS.FeeId=FM.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 		
					WHERE						
					 R.SourceId= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0

				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					IF(@lPendingAmount >= @lExemptionAmount)
					BEGIN
						IF EXISTS(SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
						BEGIN
							-- Update Fee Allocation
							UPDATE sFee.tFeeAllocation SET DiscountAmount = @lExemptionAmount, UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
							WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId
						END
						ELSE
						BEGIN
							-- Insert Fee Allocation
							INSERT INTO sFee.tFeeAllocation
							(
								SourceTypeId,
								SourceId,
								FeeSetupId,
								VariableAmount,
								DiscountAmount,
								AdditionalAmount,
								NotApplicableAmount,
								Remark,
								ReferenceTypeId,
								ReferenceSourceId,
								CreatedUserId,
								CreatedDateTime,
								UpdatedUserId,
								UpdatedDateTime
							)
							VALUES
							(
								2001,
								@lAcademicId,
								@lFeeSetupId,
								0,
								@lExemptionAmount,
								NULL,
								NULL,
								'Old Year Exemption Fee',
								NULL,
								NULL,
								@rCreatedUserId,
								sCommon.fGetDate(),
								NULL,
								NULL
							)
						END

						-- For Fee Process Added By Foram on 2025-01-31
						IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
						BEGIN
							UPDATE FAS
							SET FAS.DiscountAmount = ISNULL(FA.DiscountAmount,0), 
							FAS.ToPayAmount = (ISNULL(FAS.FeeAmount,0) + ISNULL(FAS.VariableAmount,0) + ISNULL(FAS.AdditionalAmount ,0)
												- ISNULL(FA.DiscountAmount,0) - ISNULL(FAS.NotApplicableAmount,0) - ISNULL(FAS.PaidAmount,0)),
							FAS.UpdatedUserId = @rCreatedUserId, 
							FAS.UpdatedDateTime = sCommon.fGetDate()
							FROM sFee.tFeeAllocationStudent FAS
							INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId AND FA.SourceTypeId = 2001
							WHERE FAS.AcademicId = @lAcademicId AND FAS.FeeSetupId = @lFeeSetupId
						END
						ELSE
						BEGIN
							DECLARE @lFeeAmount decimal(12,2) = 0
							SELECT @lFeeAmount = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

							INSERT INTO sFee.tFeeAllocationStudent
							(
								AcademicId
								,FeeSetupId
								,FeeAmount
								,VariableAmount
								,DiscountAmount
								,AdditionalAmount
								,NotApplicableAmount
								,ToPayAmount
								,PaidAmount
								,Remark
								,CreatedUserId
								,CreatedDateTime
								,UpdatedUserId
								,UpdatedDateTime
							)
							SELECT 
								FA.SourceId
								,FA.FeeSetupId
								,@lFeeAmount
								,ISNULL(VariableAmount,0)
								,ISNULL(DiscountAmount,0)
								,ISNULL(AdditionalAmount,0)
								,ISNULL(NotApplicableAmount,0)
								,(@lFeeAmount + ISNULL(VariableAmount,0) + ISNULL(AdditionalAmount,0)  - ISNULL(DiscountAmount,0)  - ISNULL(NotApplicableAmount,0) )
								,0
								,Remark
								,CreatedUserId
								,CreatedDateTime
								,UpdatedUserId
								,UpdatedDateTime
							FROM sFee.tFeeAllocation FA
							WHERE FA.SourceTypeId = 2001 AND FA.SourceId = @lAcademicId AND FA.FeeSetupId = @lFeeSetupId
						END
						-- For Fee Process Added By Foram on 2025-01-31

					END
				END
		END
		 
		SET @lCount = @lCount - 1
	END
	 
	DROP TABLE #TempOldExemptionFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
		DROP TABLE #TempOldExemptionFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOldExemptionFeeToExemptionGet]
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId nvarchar(max),
	@rNewFeeId int,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF OBJECT_ID('tempdb..#TempOldExemptionFeeImport') IS NOT NULL DROP TABLE #TempOldExemptionFeeImport

	BEGIN TRY 

	DECLARE @lCount int
	
	-- Old Exemption Fee Import Temp Table
	CREATE TABLE #TempOldExemptionFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL,
		[AcademicId] bigint NULL,
		[Code] nvarchar(20),
		[Name] nvarchar(300),
		[RollNo] int,
		[ClassDivision] nvarchar(300),
		[ExemptionAmount] decimal(12,2) NULL,
		[NewExemptionAmount] decimal(12,2) NULL,
		[Status] nvarchar(max) NULL
	)
	-- End Exemption Fee Import Temp Table
	
	INSERT INTO #TempOldExemptionFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision,
		SUM(ISNULL(FA.DiscountAmount,0.00)) AS ExemptionAmount,
		0,
		''
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE 
				(FS1.IsOptional=0)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FM.Id=@rOldFeeId) OR (@rOldFeeId=0))
				AND (FM.Id IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rOldFeeId,',')) OR @rOldFeeId='') 
			
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
			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
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE
				(FS1.IsOptional=1)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))	
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FM.Id=@rOldFeeId) OR (@rOldFeeId=0))
				AND (FM.Id IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rOldFeeId,',')) OR @rOldFeeId='') 
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
	WHERE	
		SA.OrgId = @rOrgId 
		AND SA.BatchId=@rOldBatchId
		AND ISNULL(FA.DiscountAmount,0.00) > 0
	GROUP BY SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.RollNo,ISNULL(SA.ClassName, ''),ISNULL(SA.DivisionName, '')

	SELECT @lCount = COUNT(AutoId) FROM #TempOldExemptionFeeImport
	
	BEGIN TRANSACTION
	
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lAcademicId bigint = NULL
			DECLARE @lStudentId bigint = NULL
			DECLARE @lClassId int = NULL
			DECLARE @lFeeSetupId int = NULL
			DECLARE @lExemptionAmount decimal(12,2)
			DECLARE @lAdmissionCategoryId int

			SELECT @lStudentId = StudentId,@lExemptionAmount=ExemptionAmount FROM #TempOldExemptionFeeImport WHERE AutoId = @lCount
			SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
			SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND AdmissionCategoryId = @lAdmissionCategoryId
		
			IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
			BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					ISNULL(FA.VariableAmount,0.00)AS FAAmount,
					ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
					ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
					ISNULL(R.PaidAmount,0) AS PaidAmount,
					ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS PendingAmount,
					ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount
				INTO #TempFeeSetup 
				FROM sFee.tFeeMaster FM
				INNER JOIN 
				(SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
					ISNULL(FS1.FeeDuration,'')  AS FeeDuration
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
					ISNULL(FS1.FeeDuration,'') AS FeeDuration
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				) FS ON FS.FeeId=FM.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 		
					WHERE						
					 R.SourceId= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0
				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					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.FeeId = @rNewFeeId 
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					WHERE (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(RD.Amount,0.00) = 0)
					AND R.SourceId = @lAcademicId
					)

					IF(@lPendingAmount < @lExemptionAmount)
					BEGIN
						UPDATE #TempOldExemptionFeeImport SET Status = 'Amount assigned in New Fee is less than Old Paid Fee', NewExemptionAmount = @lPendingAmount WHERE AutoId = @lCount 
					END
					else if(@lIsReceiptGenerated = 1)
					begin
						UPDATE #TempOldExemptionFeeImport SET Status = 'Receipt Generated or Fee Already Paid in New Batch', NewExemptionAmount = @lPendingAmount WHERE AutoId = @lCount
					end
					else
					begin
						UPDATE #TempOldExemptionFeeImport SET Status = '', NewExemptionAmount = @lPendingAmount WHERE AutoId = @lCount
					end
				END
			END
			ELSE
			BEGIN
				UPDATE #TempOldExemptionFeeImport SET Status = 'Fee Setup not assigned in New Batch', NewExemptionAmount = 0 WHERE AutoId = @lCount
			END
			SET @lCount = @lCount - 1
		END
	 
		SELECT * FROM #TempOldExemptionFeeImport
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		DROP TABLE #TempOldExemptionFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, ERROR_LINE(), ERROR_MESSAGE()
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOldFeeDetailsImportAdd] 
	@rOldOrgGroupBatchId INT
	,@rNewOrgGroupBatchId INT
	,@rOldBatchId INT
	,@rNewBatchId INT
	,@rOrgId INT
	,@rCreatedUserId BIGINT
	,@rOldClassId BIGINT
	,@rNewClassId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		CREATE TABLE #TempOldFeeImport (
			[AutoId] INT identity
			,[StudentId] BIGINT NULL
			,[AcademicId] BIGINT NULL
			,[Amount] DECIMAL(12, 2) NULL
			,[DiscountAmount] DECIMAL(12, 2) NULL
			,[AdditionalAmount] DECIMAL(12, 2) NULL
			,[NotApplicableAmount] DECIMAL(12, 2) NULL
			,[AdmissionCategoryId] BIGINT
			,[FeeSetupId] BIGINT
			)

		INSERT INTO #TempOldFeeImport
		SELECT SA.StudentId
			,SA.AcademicId
			,
			--SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
			ISNULL(FA.VariableAmount, 0.00) AS Amount
			,ISNULL(FA.DiscountAmount, 0.00) AS DiscountAmount
			,ISNULL(FA.AdditionalAmount, 0.00) AS AdditionalAmount
			,ISNULL(FA.NotApplicableAmount, 0.00) AS NotApplicableAmount
			,SA.AdmissionCategoryId
			,FA.FeeSetupId
		FROM sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		WHERE SA.OrgGroupBatchId = @rOldOrgGroupBatchId
			AND (
				(SA.BatchId = @rOldBatchId)
				OR (@rOldBatchId = 0)
				)
			AND (
				(SA.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			AND (
				(SA.ClassId = @rOldClassId)
				OR (@rOldClassId = 0)
				)
			AND SA.StatusId = 1

		--Select * from #TempOldFeeImport
		BEGIN TRANSACTION

		DECLARE @lCount INT

		SELECT @lCount = COUNT(AutoId)
		FROM #TempOldFeeImport

		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lAcademicId BIGINT = NULL
			DECLARE @lOldAcademicId BIGINT = NULL
			DECLARE @lStudentId BIGINT = NULL
			DECLARE @lClassId INT = NULL
			DECLARE @lFeeSetupId INT = NULL
			--DECLARE @lPendingAmount decimal(12,2)
			DECLARE @lDiscountAmount DECIMAL(12, 2)
			DECLARE @lAdditionalAmount DECIMAL(12, 2)
			DECLARE @lNotApplicableAmount DECIMAL(12, 2)
			DECLARE @rNewAdmissionCategoryId BIGINT
			DECLARE @rOldAdmissionCategoryId BIGINT
			DECLARE @OldFeeName NVARCHAR(200)
			DECLARE @newFeeName NVARCHAR(200)
			DECLARE @lOldAmount DECIMAL(12, 2)
			DECLARE @lNewAmount DECIMAL(12, 2)
			DECLARE @FeeName NVARCHAR(500)
			DECLARE @lOldFeeSetupId BIGINT

			SELECT @lStudentId = StudentId
				,@lOldAcademicId = AcademicId
				,@lOldAmount = Amount
				,@lDiscountAmount = DiscountAmount
				,@lAdditionalAmount = AdditionalAmount
				,@lNotApplicableAmount = NotApplicableAmount
				,@rOldAdmissionCategoryId = AdmissionCategoryId
				,@lOldFeeSetupId = FeeSetupId
			FROM #TempOldFeeImport
			WHERE AutoId = @lCount

			SELECT @lAcademicId = AcademicId
				,@lClassId = ClassId
				,@rNewAdmissionCategoryId = AdmissionCategoryId
			FROM sStudent.vStudentAcademic SA
			WHERE StudentId = @lStudentId
				AND BatchId = @rNewBatchId

			SELECT @OldFeeName = FM.Code
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId = FS1.ClassId
				AND FS1.BatchId = SA1.BatchId
			WHERE FS1.ClassId = @rOldClassId
				AND FS1.BatchId = @rOldBatchId
				AND FS1.AdmissionCategoryId = @rOldAdmissionCategoryId
				AND FS1.Id = @lOldFeeSetupId

			SELECT @lFeeSetupId = FS1.Id
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId = FS1.ClassId
				AND FS1.BatchId = SA1.BatchId
			WHERE FS1.ClassId = @lClassId
				AND FS1.BatchId = @rNewBatchId
				AND FS1.AdmissionCategoryId = @rNewAdmissionCategoryId
				AND FM.Code = @OldFeeName

			SELECT @lNewAmount = FS1.Amount
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId = FS1.ClassId
				AND FS1.BatchId = SA1.BatchId
			WHERE FS1.ClassId = @lClassId
				AND FS1.BatchId = @rNewBatchId
				AND FS1.AdmissionCategoryId = @rNewAdmissionCategoryId
				AND FS1.Id = @lFeeSetupId

			--Select @OldFeeName=FM.Code FROM sFee.tFeeSetup FS1 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			--WHERE  ClassId = @rOldClassId  AND BatchId=@rOldBatchId AND AdmissionCategoryId = @rOldAdmissionCategoryId AND FS1.Id=@lOldFeeSetupId
			SELECT @NewFeeName = FM.Code
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId = FS1.ClassId
				AND FS1.BatchId = SA1.BatchId
			WHERE FS1.ClassId = @lClassId
				AND FS1.BatchId = @rNewBatchId
				AND FS1.AdmissionCategoryId = @rNewAdmissionCategoryId
				AND FS1.Id = @lFeeSetupId

			--Select @lOldAcademicId,@lAcademicId,@lFeeSetupId,@OldFeeName,@NewFeeName,@lNewAmount,@lDiscountAmount,@FeeName,@OldFeeName
			--Select @OldFeeName,@NewFeeName
			--SELECT @lFeeSetupId,@lAcademicId,@lStudentId
			IF NOT EXISTS (SELECT 1 FROM sFee.tFeeAllocation WHERE SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
			BEGIN
				IF @lAcademicId IS NOT NULL
					AND @lFeeSetupId IS NOT NULL
					AND @lClassId IS NOT NULL
					AND @OldFeeName IS NOT NULL
					AND @NewFeeName IS NOT NULL
					AND (@OldFeeName = @NewFeeName)
					AND (ISNULL(@lNewAmount, 0) >= ISNULL(@lDiscountAmount, 0))
				BEGIN
					INSERT INTO sFee.tFeeAllocation (
						SourceTypeId
						,SourceId
						,FeeSetupId
						,VariableAmount
						,DiscountAmount
						,AdditionalAmount
						,NotApplicableAmount
						,Remark
						,ReferenceTypeId
						,ReferenceSourceId
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
						)
					VALUES (
						2001
						,@lAcademicId
						,@lFeeSetupId
						,0
						,@lDiscountAmount
						,@lAdditionalAmount
						,@lNotApplicableAmount
						,'Old Year Discount,Additional,NotApplicable Fee'
						,NULL
						,NULL
						,@rCreatedUserId
						,sCommon.fGetDate()
						,NULL
						,NULL
						)

					-- For Fee Process Added By Foram on 2025-01-31
					IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
					BEGIN
						UPDATE FAS
						SET FAS.DiscountAmount = FA.DiscountAmount,
							FAS.AdditionalAmount = FA.AdditionalAmount,
							FAS.NotApplicableAmount = FA.NotApplicableAmount, 
							FAS.ToPayAmount = (FAS.FeeAmount + FAS.VariableAmount + FA.AdditionalAmount - FA.DiscountAmount - FA.NotApplicableAmount - FAS.PaidAmount),
							FAS.UpdatedUserId = @rCreatedUserId,
							FAS.UpdatedDateTime = sCommon.fGetDate()
						FROM sFee.tFeeAllocationStudent FAS
						INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId AND FA.SourceTypeId = 2001
						WHERE FAS.AcademicId = @lAcademicId AND FAS.FeeSetupId = @lFeeSetupId
					END
					ELSE
					BEGIN
						DECLARE @lFeeAmount1 decimal(12,2) = 0
						SELECT @lFeeAmount1 = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

						INSERT INTO sFee.tFeeAllocationStudent
						(
							AcademicId
							,FeeSetupId
							,FeeAmount
							,VariableAmount
							,DiscountAmount
							,AdditionalAmount
							,NotApplicableAmount
							,ToPayAmount
							,PaidAmount
							,Remark
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
						)
						SELECT 
							FA.SourceId
							,FA.FeeSetupId
							,@lFeeAmount1
							,VariableAmount
							,DiscountAmount
							,AdditionalAmount
							,NotApplicableAmount
							,(@lFeeAmount1 + VariableAmount + AdditionalAmount - DiscountAmount - NotApplicableAmount)
							,0
							,Remark
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
						FROM sFee.tFeeAllocation FA
						WHERE FA.SourceTypeId = 2001 AND FA.SourceId = @lAcademicId AND FA.FeeSetupId = @lFeeSetupId
					END
					-- For Fee Process Added By Foram on 2025-01-31
				END
				ELSE
				BEGIN
					SELECT - 102 AS Result
				END
			END
			ELSE
			BEGIN
				IF @lAcademicId IS NOT NULL
					AND @lFeeSetupId IS NOT NULL
					AND @lClassId IS NOT NULL
					AND @OldFeeName IS NOT NULL
					AND @NewFeeName IS NOT NULL
					AND (@OldFeeName = @NewFeeName)
					AND (ISNULL(@lNewAmount, 0) >= ISNULL(@lDiscountAmount, 0))
				BEGIN
					-- Update Fee Allocation
					UPDATE sFee.tFeeAllocation
					SET SourceTypeId = 2001
						,SourceId = @lAcademicId
						,FeeSetupId = @lFeeSetupId
						,
						--VariableAmount = 0,
						DiscountAmount = @lDiscountAmount
						,AdditionalAmount = @lAdditionalAmount
						,NotApplicableAmount = @lNotApplicableAmount
						,Remark = 'Old Year Discount,Additional,NotApplicable Fee'
						,ReferenceTypeId = NULL
						,ReferenceSourceId = NULL
						,CreatedUserId = @rCreatedUserId
						,CreatedDateTime = sCommon.fGetDate()
						,UpdatedUserId = NULL
						,UpdatedDateTime = NULL
					WHERE SourceId = @lAcademicId
						AND SourceTypeId = 2001
						AND FeeSetupId = @lFeeSetupId


					-- For Fee Process Added By Foram on 2025-01-31
					IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
					BEGIN
						UPDATE FAS
						SET FAS.DiscountAmount = ISNULL(FA.DiscountAmount,0),
							FAS.AdditionalAmount = ISNULL(FA.AdditionalAmount,0),
							FAS.NotApplicableAmount = ISNULL(FA.NotApplicableAmount,0), 
							FAS.ToPayAmount = (ISNULL(FAS.FeeAmount,0) + ISNULL(FAS.VariableAmount,0) + ISNULL(FA.AdditionalAmount,0)
											- ISNULL(FA.DiscountAmount,0) - ISNULL(FA.NotApplicableAmount,0) - ISNULL(FAS.PaidAmount,0)),
							FAS.UpdatedUserId = @rCreatedUserId,
							FAS.UpdatedDateTime = sCommon.fGetDate()
						FROM sFee.tFeeAllocationStudent FAS
						INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId AND FA.SourceTypeId = 2001
						WHERE FAS.AcademicId = @lAcademicId AND FAS.FeeSetupId = @lFeeSetupId
					END
					ELSE
					BEGIN
						DECLARE @lFeeAmount2 decimal(12,2) = 0
						SELECT @lFeeAmount2 = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

						INSERT INTO sFee.tFeeAllocationStudent
						(
							AcademicId
							,FeeSetupId
							,FeeAmount
							,VariableAmount
							,DiscountAmount
							,AdditionalAmount
							,NotApplicableAmount
							,ToPayAmount
							,PaidAmount
							,Remark
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
						)
						SELECT 
							FA.SourceId
							,FA.FeeSetupId
							,ISNULL(@lFeeAmount2,0)
							,ISNULL(VariableAmount,0)
							,ISNULL(DiscountAmount,0)
							,ISNULL(AdditionalAmount,0)
							,ISNULL(NotApplicableAmount,0)
							,(ISNULL(@lFeeAmount2,0) + ISNULL(VariableAmount,0)  + ISNULL(AdditionalAmount,0) - ISNULL(DiscountAmount,0) - ISNULL(NotApplicableAmount,0))
							,0
							,Remark
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
						FROM sFee.tFeeAllocation FA
						WHERE FA.SourceTypeId = 2001 AND FA.SourceId = @lAcademicId AND FA.FeeSetupId = @lFeeSetupId
					END
					-- For Fee Process Added By Foram on 2025-01-31

				END
				ELSE
				BEGIN
					SELECT - 102 AS Result
				END
			END

			SET @lCount = @lCount - 1
		END

		DROP TABLE #TempOldFeeImport

		SELECT 1 AS Result

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pOldFeeImportAdd]
	
	@rOldOrgGroupBatchId int,
	@rNewOrgGroupBatchId int,
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldAdmissionCategoryId int,
	@rNewAdmissionCategoryId int,
	@rOldReceiptBookId int,
	@rNewReceiptBookId int,
	@rFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rIdNos nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

	DECLARE @lCount int
	-- Old Fee Import Temp Table
	CREATE TABLE #TempOldFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PendingAmount] decimal(12,2) NULL
	)
	-- End Old Fee Import Temp Table
	
	INSERT INTO #TempOldFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		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,
				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=@rOrgId) OR (@rOrgId=0))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			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=@rOrgId) OR (@rOrgId=0))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				
		) 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=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOldOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOldOrgGroupBatchId)
				AND ((R.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				 
	WHERE	
			SA.OrgGroupBatchId = @rOldOrgGroupBatchId
			AND SA.OrgId = @rOrgId 
			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)
			AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			GROUP BY SA.StudentId,SA.AcademicId
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldFeeImport
	
	IF EXISTS 
	(
		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 (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	)
	BEGIN
		SELECT -101 AS Result
		RETURN
	END
	
	BEGIN TRANSACTION
	
	---- Delete Fee Optional
	DELETE FO FROM sFee.tFeeOptional FO
	INNER JOIN sStudent.tAcademic SA ON FO.SourceId = SA.Id AND SA.BatchId = @rNewBatchId	
	INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId
	AND FS.BatchId = @rNewBatchId 
	AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId 
	AND FS.FeeId = @rFeeId  
	AND FS.ReceiptBookId = @rNewReceiptBookId
	AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')

	-- Delete Fee Allocation
	DELETE FA FROM sFee.tFeeAllocation FA 
	INNER JOIN sStudent.tAcademic SA ON FA.SourceId = SA.Id AND SA.BatchId = @rNewBatchId
	INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId
	AND FS.BatchId = @rNewBatchId 
	AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId 
	AND FS.FeeId = @rFeeId AND FA.FeeSetupId = FS.Id
	AND FS.ReceiptBookId = @rNewReceiptBookId
	AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId 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 @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 NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL
		BEGIN
			-- Insert Fee Optional
				INSERT INTO sFee.tFeeOptional
			   (
			    FeeSetupId,
			    SourceTypeId,
			    SourceId,
			    BatchId
			   )
				VALUES
			   (
				@lFeeSetupId,
				2001,
				@lAcademicId,
				@rNewBatchId
			   )
			 
				-- Insert Fee Allocation
				INSERT INTO sFee.tFeeAllocation
			   (
			    SourceTypeId,
			    SourceId,
			    FeeSetupId,
			    VariableAmount,
			    DiscountAmount,
			    AdditionalAmount,
			    NotApplicableAmount,
			    Remark,
			    ReferenceTypeId,
			    ReferenceSourceId,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime
			   )
				VALUES
			   (
				2001,
				@lAcademicId,
				@lFeeSetupId,
				@lPendingAmount,
				0,
				NULL,
				NULL,
				'Old Year Pending Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			   )

			   -- For Fee Process Added By Foram on 2025-01-31
				IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
				BEGIN
					UPDATE FAS
					SET FAS.VariableAmount = ISNULL(FA.VariableAmount, 0), 
					FAS.ToPayAmount = (ISNULL(FAS.FeeAmount, 0) + ISNULL(FA.VariableAmount, 0) + ISNULL(FAS.AdditionalAmount, 0) 
									 - ISNULL(FAS.DiscountAmount, 0) - ISNULL(FAS.NotApplicableAmount, 0) - ISNULL(FAS.PaidAmount, 0)),  --Added ISNULL for mantis 0042456 by Foram
					FAS.UpdatedUserId = @rCreatedUserId,
					FAS.UpdatedDateTime = sCommon.fGetDate()
					FROM sFee.tFeeAllocationStudent FAS
					INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId AND FA.SourceTypeId = 2001
					WHERE FAS.AcademicId = @lAcademicId AND FAS.FeeSetupId = @lFeeSetupId
				END
				ELSE
				BEGIN
					DECLARE @lFeeAmount1 decimal(12,2) = 0
					SELECT @lFeeAmount1 = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

					INSERT INTO sFee.tFeeAllocationStudent
					(
						AcademicId
						,FeeSetupId
						,FeeAmount
						,VariableAmount
						,DiscountAmount
						,AdditionalAmount
						,NotApplicableAmount
						,ToPayAmount
						,PaidAmount
						,Remark
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
					)
					SELECT 
						FA.SourceId
						,FA.FeeSetupId
						,@lFeeAmount1
						,ISNULL(VariableAmount, 0)			--Added ISNULL for mantis 0042456 by Foram
						,ISNULL(DiscountAmount, 0)			--Added ISNULL for mantis 0042456 by Foram
						,ISNULL(AdditionalAmount, 0)		--Added ISNULL for mantis 0042456 by Foram
						,ISNULL(NotApplicableAmount, 0)		--Added ISNULL for mantis 0042456 by Foram
						,(@lFeeAmount1 + ISNULL(VariableAmount, 0) + ISNULL(AdditionalAmount, 0) - ISNULL(DiscountAmount, 0) - ISNULL(NotApplicableAmount, 0))
						,0
						,Remark
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
					FROM sFee.tFeeAllocation FA
					WHERE FA.SourceTypeId = 2001 AND FA.SourceId = @lAcademicId AND FA.FeeSetupId = @lFeeSetupId
				END
				-- For Fee Process Added By Foram on 2025-01-31
		END
		 
		SET @lCount = @lCount -1
	END
	 
	DROP TABLE #TempOldFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
DROP TABLE #TempOldFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOldFeeImportWithNAAdd]
	@rOldOrgGroupBatchId int,
	@rNewOrgGroupBatchId int,
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldAdmissionCategoryId int,
	@rNewAdmissionCategoryId int,
	@rOldReceiptBookId int,
	@rNewReceiptBookId int,
	@rFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rIdNos nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		IF OBJECT_ID('tempdb..#TempOldFeeImportWithNA') IS NOT NULL
			DROP TABLE #TempOldFeeImportWithNA

		IF OBJECT_ID('tempdb..#TempTotalOldFeeImportWithNA') IS NOT NULL
			DROP TABLE #TempTotalOldFeeImportWithNA

		IF OBJECT_ID('tempdb..#TempOldFeeSetup') IS NOT NULL
			DROP TABLE #TempOldFeeSetup

		DECLARE @lCount INT

		-- Old Fee Import Temp Table
		CREATE TABLE #TempOldFeeImportWithNA (
			[AutoId] INT identity
			,[StudentId] BIGINT NULL
			,[AcademicId] BIGINT NULL
			,[PendingAmount] DECIMAL(12, 2) NULL
			,[FeeSetupId] INT
			)

		CREATE TABLE #TempTotalOldFeeImportWithNA (
			[AutoId] INT identity
			,[StudentId] BIGINT NULL
			,[AcademicId] BIGINT NULL
			,[TotalPendingAmount] DECIMAL(12, 2) NULL
			)

		-- End Old Fee Import Temp Table
		INSERT INTO #TempOldFeeImportWithNA
		SELECT SA.StudentId
			,SA.AcademicId
			,ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) AS PendingAmount
			,FS.Id AS FeeSetupId
		--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
				,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 = @rOrgId)
					OR (@rOrgId = 0)
					)
				AND (
					SA1.Code IN (
						SELECT item
						FROM sCommon.fnSplit(@rIdNos, ',')
						)
					OR ISNULL(@rIdNos, '') = ''
					)
			
			UNION ALL
			
			SELECT FS1.FeeId
				,FS1.Id
				,ISNULL(FS1.IsOptional, 0) AS IsOptional
				,ISNULL(FS1.IsVariable, 0) AS IsVariable
				,ISNULL(FS1.Amount, 0) AS Amount
				,ISNULL(FS1.StartDate, '1900-01-01') AS StartDate
				,ISNULL(FS1.EndDate, '1900-01-01') AS EndDate
				,FS1.BatchId
				,ISNULL(FS1.ReceiptBookId, 0) AS ReceiptBookId
				,SA1.AcademicId
				,FM.Title AS FeeName
			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 = @rOrgId)
					OR (@rOrgId = 0)
					)
				AND (
					SA1.Code IN (
						SELECT item
						FROM sCommon.fnSplit(@rIdNos, ',')
						)
					OR ISNULL(@rIdNos, '') = ''
					)
			) 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 = @rOrgId)
					OR (@rOrgId = 0)
					)
				AND (R.IsObsolete = 0)
				AND ((SA1.OrgGroupBatchId = @rOldOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOldOrgGroupBatchId)
				AND (
					(R.BatchId = @rOldBatchId)
					OR (@rOldBatchId = 0)
					)
				AND (
					SA1.Code IN (
						SELECT item
						FROM sCommon.fnSplit(@rIdNos, ',')
						)
					OR ISNULL(@rIdNos, '') = ''
					)
			GROUP BY FeeSetupId
				,R.SourceId
			) R ON R.FeeSetupId = FS.Id
			AND SA.AcademicId = R.SourceId
		WHERE SA.OrgGroupBatchId = @rOldOrgGroupBatchId
			AND SA.OrgId = @rOrgId
			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)
			AND (
				SA.Code IN (
					SELECT item
					FROM sCommon.fnSplit(@rIdNos, ',')
					)
				OR ISNULL(@rIdNos, '') = ''
				)

		--GROUP BY SA.StudentId,SA.AcademicId
		INSERT INTO #TempTotalOldFeeImportWithNA
		SELECT StudentId
			,AcademicId
			,SUM(PendingAmount) AS TotalPendingAmount
		FROM #TempOldFeeImportWithNA
		GROUP BY StudentId
			,AcademicId

		SELECT @lCount = COUNT(AutoId)
		FROM #TempTotalOldFeeImportWithNA

		IF EXISTS (
				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 (
						SA.Code IN (
							SELECT item
							FROM sCommon.fnSplit(@rIdNos, ',')
							)
						OR ISNULL(@rIdNos, '') = ''
						)
				)
		BEGIN
			SELECT - 101 AS Result

			RETURN
		END

		--Mantis: 41939, Comment this code
		--IF OBJECT_ID('tempdb..#TempOldFeeImportWithNA') IS NOT NULL
		--	DROP TABLE #TempOldFeeImportWithNA

		--IF OBJECT_ID('tempdb..#TempTotalOldFeeImportWithNA') IS NOT NULL
		--	DROP TABLE #TempTotalOldFeeImportWithNA

		--IF OBJECT_ID('tempdb..#TempOldFeeSetup') IS NOT NULL
		--	DROP TABLE #TempOldFeeSetup
		--Mantis: 41939

		BEGIN TRANSACTION

		---- Delete Fee Optional
		DELETE FO
		FROM sFee.tFeeOptional FO
		INNER JOIN sStudent.tAcademic SA ON FO.SourceId = SA.Id
			AND SA.BatchId = @rNewBatchId
		INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id
			AND SA.ClassId = FS.ClassId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId
			AND SA1.BatchId = @rNewBatchId
			AND FS.BatchId = @rNewBatchId
			AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId
			AND FS.FeeId = @rFeeId
			AND FS.ReceiptBookId = @rNewReceiptBookId
			AND (
				SA1.Code IN (
					SELECT item
					FROM sCommon.fnSplit(@rIdNos, ',')
					)
				OR ISNULL(@rIdNos, '') = ''
				)

		-- Delete Fee Allocation
		DELETE FA
		FROM sFee.tFeeAllocation FA
		INNER JOIN sStudent.tAcademic SA ON FA.SourceId = SA.Id
			AND SA.BatchId = @rNewBatchId
		INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id
			AND SA.ClassId = FS.ClassId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId
			AND SA1.BatchId = @rNewBatchId
			AND FS.BatchId = @rNewBatchId
			AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId
			AND FS.FeeId = @rFeeId
			AND FA.FeeSetupId = FS.Id
			AND FS.ReceiptBookId = @rNewReceiptBookId
			AND (
				SA1.Code IN (
					SELECT item
					FROM sCommon.fnSplit(@rIdNos, ',')
					)
				OR ISNULL(@rIdNos, '') = ''
				)

		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lAcademicId BIGINT = NULL
				,@lOldAcademicId BIGINT = NULL
			DECLARE @lStudentId BIGINT = NULL
			DECLARE @lClassId INT = NULL
			DECLARE @lFeeSetupId INT = NULL
			DECLARE @lTotalPendingAmount DECIMAL(12, 2)

			SELECT @lStudentId = StudentId
				,@lTotalPendingAmount = TotalPendingAmount
				,@lOldAcademicId = AcademicId
			FROM #TempTotalOldFeeImportWithNA
			WHERE AutoId = @lCount

			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 NOT NULL
				AND @lFeeSetupId IS NOT NULL
				AND @lClassId IS NOT NULL
			BEGIN
				-- Insert Fee Optional
				INSERT INTO sFee.tFeeOptional (
					FeeSetupId
					,SourceTypeId
					,SourceId
					,BatchId
					)
				VALUES (
					@lFeeSetupId
					,2001
					,@lAcademicId
					,@rNewBatchId
					)

				-- Insert Fee Allocation
				INSERT INTO sFee.tFeeAllocation (
					SourceTypeId
					,SourceId
					,FeeSetupId
					,VariableAmount
					,DiscountAmount
					,AdditionalAmount
					,NotApplicableAmount
					,Remark
					,ReferenceTypeId
					,ReferenceSourceId
					,CreatedUserId
					,CreatedDateTime
					,UpdatedUserId
					,UpdatedDateTime
					)
				VALUES (
					2001
					,@lAcademicId
					,@lFeeSetupId
					,@lTotalPendingAmount
					,0
					,NULL
					,NULL
					,'Old Year Pending Fee'
					,NULL
					,NULL
					,@rCreatedUserId
					,sCommon.fGetDate()
					,NULL
					,NULL
					)

				-- For Fee Process Added By Foram on 2025-01-31
				IF EXISTS (
						SELECT 1
						FROM sFee.tFeeAllocationStudent
						WHERE AcademicId = @lAcademicId
							AND FeeSetupId = @lFeeSetupId
						)
				BEGIN
					UPDATE sFee.tFeeAllocationStudent
					SET VariableAmount = @lTotalPendingAmount
						,ToPayAmount = (FeeAmount + @lTotalPendingAmount + AdditionalAmount - DiscountAmount - NotApplicableAmount - PaidAmount)
						,UpdatedUserId = @rCreatedUserId
						,UpdatedDateTime = sCommon.fGetDate()
					WHERE AcademicId = @lAcademicId
						AND FeeSetupId = @lFeeSetupId
				END
				ELSE
				BEGIN
					DECLARE @lFeeAmount DECIMAL(12, 2) = 0

					SELECT @lFeeAmount = ISNULL(Amount, 0)
					FROM sFee.tFeeSetup
					WHERE Id = @lFeeSetupId

					INSERT INTO sFee.tFeeAllocationStudent (
						AcademicId
						,FeeSetupId
						,FeeAmount
						,VariableAmount
						,DiscountAmount
						,AdditionalAmount
						,NotApplicableAmount
						,ToPayAmount
						,PaidAmount
						,Remark
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
						)
					VALUES (
						@lAcademicId
						,@lFeeSetupId
						,@lFeeAmount
						,@lTotalPendingAmount
						,0
						,0
						,0
						,(@lFeeAmount - @lTotalPendingAmount)
						,0
						,'Old Year Pending Fee'
						,@rCreatedUserId
						,sCommon.fGetDate()
						,@rCreatedUserId
						,sCommon.fGetDate()
						);
				END

				-- For Fee Process Added By Foram on 2025-01-31
				--DECLARE @lCount1 int = 0
				--SELECT @lCount1 = COUNT(1) FROM #TempOldFeeImportWithNA WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId
				IF OBJECT_ID('tempdb..#TempOldFeeSetup') IS NOT NULL
					DROP TABLE #TempOldFeeSetup

				CREATE TABLE #TempOldFeeSetup (
					[AutoId] INT identity
					,[StudentId] BIGINT NULL
					,[AcademicId] BIGINT NULL
					,[PendingAmount] DECIMAL(12, 2) NULL
					,[FeeSetupId] INT
					)

				INSERT INTO #TempOldFeeSetup
				SELECT StudentId
					,AcademicId
					,PendingAmount
					,FeeSetupId
				FROM #TempOldFeeImportWithNA
				WHERE StudentId = @lStudentId
					AND AcademicId = @lOldAcademicId

				DECLARE @lCount1 INT = 0

				SELECT @lCount1 = COUNT(1)
				FROM #TempOldFeeSetup
				WHERE StudentId = @lStudentId
					AND AcademicId = @lOldAcademicId

				WHILE (@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount DECIMAL(12, 2)
						,@lOldFeeSetupId INT

					SELECT @lPendingAmount = PendingAmount
						,@lOldFeeSetupId = FeeSetupId
					FROM #TempOldFeeSetup
					WHERE StudentId = @lStudentId
						AND AcademicId = @lOldAcademicId
						AND AutoId = @lCount1

					IF EXISTS (
							SELECT 1
							FROM sFee.tFeeAllocation
							WHERE SourceTypeId = 2001
								AND SourceId = @lOldAcademicId
								AND FeeSetupId = @lOldFeeSetupId
							)
					BEGIN
						-- Update Fee Allocation
						UPDATE sFee.tFeeAllocation
						SET NotApplicableAmount = (ISNULL(NotApplicableAmount, 0) + ISNULL(@lPendingAmount, 0))
							,Remark = 'Transferred to New Batch'
							,UpdatedUserId = @rCreatedUserId
							,UpdatedDateTime = sCommon.fGetDate()
						WHERE SourceTypeId = 2001
							AND SourceId = @lOldAcademicId
							AND FeeSetupId = @lOldFeeSetupId
					END
					ELSE
					BEGIN
						-- Insert Fee Allocation
						INSERT INTO sFee.tFeeAllocation (
							SourceTypeId
							,SourceId
							,FeeSetupId
							,VariableAmount
							,DiscountAmount
							,AdditionalAmount
							,NotApplicableAmount
							,Remark
							,ReferenceTypeId
							,ReferenceSourceId
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
							)
						VALUES (
							2001
							,@lOldAcademicId
							,@lOldFeeSetupId
							,0
							,0
							,0
							,@lPendingAmount
							,'Transferred to New Batch'
							,NULL
							,NULL
							,@rCreatedUserId
							,sCommon.fGetDate()
							,@rCreatedUserId
							,sCommon.fGetDate()
							)
					END
					
					-- For Fee Process Added By Foram on 2025-01-31
					IF EXISTS (
							SELECT 1
							FROM sFee.tFeeAllocationStudent
							WHERE AcademicId = @lOldAcademicId
								AND FeeSetupId = @lOldFeeSetupId
							)
					BEGIN
						UPDATE FAS
						SET FAS.NotApplicableAmount = FA.NotApplicableAmount
							,FAS.ToPayAmount = (ISNULL(FAS.FeeAmount, 0) + ISNULL(FAS.VariableAmount, 0) + ISNULL(FAS.AdditionalAmount, 0)
											- ISNULL(FAS.DiscountAmount, 0) - ISNULL(FA.NotApplicableAmount, 0) - ISNULL(FAS.PaidAmount, 0)) --Added ISNULL for mantis 0042158 by Foram
							,FAS.UpdatedUserId = @rCreatedUserId
							,FAS.UpdatedDateTime = sCommon.fGetDate()
						FROM sFee.tFeeAllocationStudent FAS
						INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId
							AND FA.SourceTypeId = 2001
						WHERE FAS.AcademicId = @lOldAcademicId
							AND FAS.FeeSetupId = @lOldFeeSetupId
					END
					ELSE
					BEGIN
					
						DECLARE @lFeeAmount1 DECIMAL(12, 2) = 0

						SELECT @lFeeAmount1 = ISNULL(Amount, 0)
						FROM sFee.tFeeSetup
						WHERE Id = @lOldFeeSetupId
						Print @lFeeAmount1
						INSERT INTO sFee.tFeeAllocationStudent (
							AcademicId
							,FeeSetupId
							,FeeAmount
							,VariableAmount
							,DiscountAmount
							,AdditionalAmount
							,NotApplicableAmount
							,ToPayAmount
							,PaidAmount
							,Remark
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
							)
						SELECT FA.SourceId
							,FA.FeeSetupId
							,@lFeeAmount1
							,ISNULL(VariableAmount, 0)				--Added ISNULL for mantis 0042158 by Foram
							,ISNULL(DiscountAmount, 0)				--Added ISNULL for mantis 0042158 by Foram
							,ISNULL(AdditionalAmount, 0)			--Added ISNULL for mantis 0042158 by Foram
							,ISNULL(NotApplicableAmount, 0)			--Added ISNULL for mantis 0042158 by Foram
							,(@lFeeAmount1 + ISNULL(VariableAmount, 0) + ISNULL(AdditionalAmount, 0) - ISNULL(DiscountAmount, 0) - ISNULL(NotApplicableAmount, 0))
							,0
							,Remark
							,CreatedUserId
							,CreatedDateTime
							,UpdatedUserId
							,UpdatedDateTime
						FROM sFee.tFeeAllocation FA
						WHERE FA.SourceTypeId = 2001
							AND FA.SourceId = @lOldAcademicId
							AND FA.FeeSetupId = @lOldFeeSetupId
					END
					 
					-- For Fee Process Added By Foram on 2025-01-31
					SET @lCount1 = @lCount1 - 1
				END
			END
			
			SET @lCount = @lCount - 1
		END

		--Mantis: 41939
		--DROP TABLE #TempTotalOldFeeImportWithNA
		--DROP TABLE #TempOldFeeImportWithNA
		--DROP TABLE #TempOldFeeSetup

		IF OBJECT_ID('tempdb..#TempOldFeeImportWithNA') IS NOT NULL
			DROP TABLE #TempOldFeeImportWithNA

		IF OBJECT_ID('tempdb..#TempTotalOldFeeImportWithNA') IS NOT NULL
			DROP TABLE #TempTotalOldFeeImportWithNA

		IF OBJECT_ID('tempdb..#TempOldFeeSetup') IS NOT NULL
			DROP TABLE #TempOldFeeSetup
        --Mantis:41939

		SELECT 1 AS Result

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH

	    --Mantis: 41939
		--DROP TABLE #TempTotalOldFeeImportWithNA
		--DROP TABLE #TempOldFeeImportWithNA
		--DROP TABLE #TempOldFeeSetup

		IF OBJECT_ID('tempdb..#TempOldFeeImportWithNA') IS NOT NULL
			DROP TABLE #TempOldFeeImportWithNA

		IF OBJECT_ID('tempdb..#TempTotalOldFeeImportWithNA') IS NOT NULL
			DROP TABLE #TempTotalOldFeeImportWithNA

		IF OBJECT_ID('tempdb..#TempOldFeeSetup') IS NOT NULL
			DROP TABLE #TempOldFeeSetup
        --Mantis: 41939

		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOldFeewiseImportAdd]
	
	@rOldOrgGroupBatchId int,
	@rNewOrgGroupBatchId int,
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldAdmissionCategoryId int,
	@rNewAdmissionCategoryId int,
	@rOldReceiptBookId int,
	@rNewReceiptBookId int,
	@rOldFeeIds nvarchar(max),
	@rNewFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rIdNos nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY 

	DECLARE @lCount int
	-- Old Fee Import Temp Table
	CREATE TABLE #TempOldFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PendingAmount] decimal(12,2) NULL
	)
	-- End Old Fee Import Temp Table
	
	
	INSERT INTO #TempOldFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		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,
				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=@rOrgId) OR (@rOrgId=0))
				AND FM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			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=@rOrgId) OR (@rOrgId=0))
				AND FM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				
		) 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=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOldOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOldOrgGroupBatchId)
				AND ((R.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND FM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				 
	WHERE	
			SA.OrgGroupBatchId = @rOldOrgGroupBatchId
			AND SA.OrgId = @rOrgId 
			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)
			AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			GROUP BY SA.StudentId,SA.AcademicId
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldFeeImport
	
	IF EXISTS 
	(
		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 = @rNewFeeId 
		AND FS.ReceiptBookId = @rNewReceiptBookId
		AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	)
	BEGIN
		SELECT -101 AS Result
		RETURN
	END
	
	BEGIN TRANSACTION
	
	---- Delete Fee Optional
	DELETE FO FROM sFee.tFeeOptional FO 
	INNER JOIN sStudent.tAcademic SA ON FO.SourceId = SA.Id AND SA.BatchId = @rNewBatchId
	INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId
	AND FS.BatchId = @rNewBatchId 
	AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId 
	AND FS.FeeId = @rNewFeeId  
	AND FS.ReceiptBookId = @rNewReceiptBookId
	AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	INNER JOIN #TempOldFeeImport TOFI ON TOFI.StudentId = SA.StudentId 

	-- Delete Fee Allocation
	DELETE FA FROM sFee.tFeeAllocation FA 
	INNER JOIN sStudent.tAcademic SA ON FA.SourceId = SA.Id AND SA.BatchId = @rNewBatchId
	INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId
	AND FS.BatchId = @rNewBatchId 
	AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId 
	AND FS.FeeId = @rNewFeeId AND FA.FeeSetupId = FS.Id
	AND FS.ReceiptBookId = @rNewReceiptBookId
	AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	INNER JOIN #TempOldFeeImport TOFI ON TOFI.StudentId = SA.StudentId 

	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId 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 @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 = @rNewFeeId AND ReceiptBookId = @rNewReceiptBookId
		
		IF @lAcademicId IS NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL
		BEGIN
			-- Insert Fee Optional
			INSERT INTO sFee.tFeeOptional
			   (
			    FeeSetupId,
			    SourceTypeId,
			    SourceId,
			    BatchId
			   )
				VALUES
			   (
				@lFeeSetupId,
				2001,
				@lAcademicId,
				@rNewBatchId
			   )
			 
				-- Insert Fee Allocation
			INSERT INTO sFee.tFeeAllocation
			   (
			    SourceTypeId,
			    SourceId,
			    FeeSetupId,
			    VariableAmount,
			    DiscountAmount,
			    AdditionalAmount,
			    NotApplicableAmount,
			    Remark,
			    ReferenceTypeId,
			    ReferenceSourceId,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime
			   )
				VALUES
			   (
				2001,
				@lAcademicId,
				@lFeeSetupId,
				@lPendingAmount,
				0,
				NULL,
				NULL,
				'Old Year Pending Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			   )

			   -- For Fee Process Added By Foram on 2025-01-31
				IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
				BEGIN
					UPDATE FAS
					SET FAS.VariableAmount = ISNULL(FA.VariableAmount,0), 
					FAS.ToPayAmount = (ISNULL(FAS.FeeAmount,0) + ISNULL(FA.VariableAmount,0) + ISNULL(FAS.AdditionalAmount,0) - ISNULL(FAS.DiscountAmount,0) - ISNULL(FAS.NotApplicableAmount,0) - ISNULL(FAS.PaidAmount,0)),
					FAS.UpdatedUserId = @rCreatedUserId,
					FAS.UpdatedDateTime = sCommon.fGetDate()
					FROM sFee.tFeeAllocationStudent FAS
					INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId AND FA.SourceTypeId = 2001
					WHERE FAS.AcademicId = @lAcademicId AND FAS.FeeSetupId = @lFeeSetupId
				END
				ELSE
				BEGIN
					DECLARE @lFeeAmount1 decimal(12,2) = 0
					SELECT @lFeeAmount1 = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

					INSERT INTO sFee.tFeeAllocationStudent
					(
						AcademicId
						,FeeSetupId
						,FeeAmount
						,VariableAmount
						,DiscountAmount
						,AdditionalAmount
						,NotApplicableAmount
						,ToPayAmount
						,PaidAmount
						,Remark
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
					)
					SELECT 
						FA.SourceId
						,FA.FeeSetupId
						,ISNULL(@lFeeAmount1,0)
						,ISNULL(VariableAmount,0)
						,ISNULL(DiscountAmount,0)
						,ISNULL(AdditionalAmount,0)
						,ISNULL(NotApplicableAmount,0)
						,(ISNULL(@lFeeAmount1,0) + ISNULL(VariableAmount,0) + ISNULL(AdditionalAmount,0) - ISNULL(DiscountAmount,0) - ISNULL(NotApplicableAmount,0))
						,0
						,Remark
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
					FROM sFee.tFeeAllocation FA
					WHERE FA.SourceTypeId = 2001 AND FA.SourceId = @lAcademicId AND FA.FeeSetupId = @lFeeSetupId
				END
				-- For Fee Process Added By Foram on 2025-01-31
		END
		 
		SET @lCount = @lCount -1
	END
	 
	DROP TABLE #TempOldFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
DROP TABLE #TempOldFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOldFeewiseImportWithNAAdd]
	
	@rOldOrgGroupBatchId int,
	@rNewOrgGroupBatchId int,
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldAdmissionCategoryId int,
	@rNewAdmissionCategoryId int,
	@rOldReceiptBookId int,
	@rNewReceiptBookId int,
	@rOldFeeIds nvarchar(max),
	@rNewFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rIdNos nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY

	IF OBJECT_ID('tempdb..#TempOldFeeImportWithNA') IS NOT NULL 
		DROP TABLE #TempOldFeeImportWithNA

	IF OBJECT_ID('tempdb..#TempTotalOldFeeImportWithNA') IS NOT NULL 
		DROP TABLE #TempTotalOldFeeImportWithNA

	IF OBJECT_ID('tempdb..#TempOldFeeSetup') IS NOT NULL 
		DROP TABLE #TempOldFeeSetup

	DECLARE @lCount int

	-- Old Fee Import Temp Table
	CREATE TABLE #TempOldFeeImportWithNA
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PendingAmount] decimal(12,2) NULL,
		[FeeSetupId] int
	)
	CREATE TABLE #TempTotalOldFeeImportWithNA
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[TotalPendingAmount] decimal(12,2) NULL
	)
	-- End Old Fee Import Temp Table
	
	
	INSERT INTO #TempOldFeeImportWithNA 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS PendingAmount,
		FS.Id AS FeeSetupId
		--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,
				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=@rOrgId) OR (@rOrgId=0))
				AND FM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			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=@rOrgId) OR (@rOrgId=0))
			AND FM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
			AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
		) 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=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOldOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOldOrgGroupBatchId)
				AND ((R.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND FM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOldFeeIds,','))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	WHERE
		SA.OrgGroupBatchId = @rOldOrgGroupBatchId
		AND SA.OrgId = @rOrgId 
		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)
		AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	--GROUP BY SA.StudentId,SA.AcademicId

	INSERT INTO #TempTotalOldFeeImportWithNA
	SELECT StudentId, AcademicId, SUM(PendingAmount) AS TotalPendingAmount
	FROM #TempOldFeeImportWithNA
	GROUP BY StudentId, AcademicId
	
	SELECT @lCount = COUNT(AutoId) FROM #TempTotalOldFeeImportWithNA
	
	IF EXISTS 
	(
		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 = @rNewFeeId 
		AND FS.ReceiptBookId = @rNewReceiptBookId
		AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	)
	BEGIN
		SELECT -101 AS Result
		RETURN
	END
	
	BEGIN TRANSACTION
	
	---- Delete Fee Optional
	DELETE FO 
	FROM sFee.tFeeOptional FO 
	INNER JOIN sStudent.tAcademic SA ON FO.SourceId = SA.Id AND SA.BatchId = @rNewBatchId
	INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId
		AND FS.BatchId = @rNewBatchId AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId 
		AND FS.FeeId = @rNewFeeId AND FS.ReceiptBookId = @rNewReceiptBookId
		AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	INNER JOIN #TempTotalOldFeeImportWithNA TOFI ON TOFI.StudentId = SA.StudentId 

	-- Delete Fee Allocation
	DELETE FA 
	FROM sFee.tFeeAllocation FA 
	INNER JOIN sStudent.tAcademic SA ON FA.SourceId = SA.Id AND SA.BatchId = @rNewBatchId
	INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId
		AND FS.BatchId = @rNewBatchId AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId 
		AND FS.FeeId = @rNewFeeId AND FA.FeeSetupId = FS.Id AND FS.ReceiptBookId = @rNewReceiptBookId
		AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	INNER JOIN #TempTotalOldFeeImportWithNA TOFI ON TOFI.StudentId = SA.StudentId 

	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL, @lOldAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lTotalPendingAmount decimal(12,2)
		
		SELECT @lStudentId = StudentId,@lTotalPendingAmount=TotalPendingAmount,@lOldAcademicId=AcademicId FROM #TempTotalOldFeeImportWithNA WHERE AutoId = @lCount
		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 = @rNewFeeId AND ReceiptBookId = @rNewReceiptBookId

		IF @lAcademicId IS NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL
		BEGIN
			-- Insert Fee Optional
			INSERT INTO sFee.tFeeOptional
			(
			    FeeSetupId,
			    SourceTypeId,
			    SourceId,
			    BatchId
			)
			VALUES
			(
				@lFeeSetupId,
				2001,
				@lAcademicId,
				@rNewBatchId
			)
			 
			-- Insert Fee Allocation
			INSERT INTO sFee.tFeeAllocation
			(
			    SourceTypeId,
			    SourceId,
			    FeeSetupId,
			    VariableAmount,
			    DiscountAmount,
			    AdditionalAmount,
			    NotApplicableAmount,
			    Remark,
			    ReferenceTypeId,
			    ReferenceSourceId,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime
			)
			VALUES
			(
				2001,
				@lAcademicId,
				@lFeeSetupId,
				@lTotalPendingAmount,
				0,
				NULL,
				NULL,
				'Old Year Pending Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			)

			-- For Fee Process Added By Foram on 2025-01-30
			IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
			BEGIN
				UPDATE sFee.tFeeAllocationStudent
				SET VariableAmount = @lTotalPendingAmount, 
				ToPayAmount = (FeeAmount + @lTotalPendingAmount + AdditionalAmount - DiscountAmount - NotApplicableAmount - PaidAmount),
				UpdatedUserId = @rCreatedUserId, 
				UpdatedDateTime = sCommon.fGetDate()
				WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId
			END
			ELSE
			BEGIN
				DECLARE @lFeeAmount decimal(12,2) = 0
				SELECT @lFeeAmount = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

				INSERT INTO sFee.tFeeAllocationStudent
				(
					AcademicId
					,FeeSetupId
					,FeeAmount
					,VariableAmount
					,DiscountAmount
					,AdditionalAmount
					,NotApplicableAmount
					,ToPayAmount
					,PaidAmount
					,Remark
					,CreatedUserId
					,CreatedDateTime
					,UpdatedUserId
					,UpdatedDateTime
				)
				VALUES (
					@lAcademicId
					,@lFeeSetupId
					,@lFeeAmount
					,@lTotalPendingAmount
					,0
					,0
					,0
					,(@lFeeAmount - @lTotalPendingAmount) 
					,0
					,'Old Year Pending Fee'
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rCreatedUserId
					,sCommon.fGetDate()
				);
			END
			-- For Fee Process Added By Foram on 2025-01-30

			--DECLARE @lCount1 int = 0
			--SELECT @lCount1 = COUNT(1) FROM #TempOldFeeImportWithNA WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId

			CREATE TABLE #TempOldFeeSetup
			(
				[AutoId] int identity,
				[StudentId] bigint NULL ,
				[AcademicId] bigint NULL,
				[PendingAmount] decimal(12,2) NULL,
				[FeeSetupId] int
			)

			INSERT INTO #TempOldFeeSetup
			SELECT StudentId,AcademicId,PendingAmount,FeeSetupId FROM #TempOldFeeImportWithNA WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId

			DECLARE @lCount1 int = 0
			SELECT @lCount1 = COUNT(1) FROM #TempOldFeeSetup WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId

			WHILE(@lCount1 > 0)
			BEGIN
		
				DECLARE @lPendingAmount decimal(12,2), @lOldFeeSetupId int
				SELECT @lPendingAmount = PendingAmount, @lOldFeeSetupId = FeeSetupId FROM #TempOldFeeSetup WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId AND AutoId = @lCount1

				IF EXISTS(SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @lOldAcademicId AND FeeSetupId = @lOldFeeSetupId)
				BEGIN
					-- Update Fee Allocation
					UPDATE sFee.tFeeAllocation
					SET NotApplicableAmount = NotApplicableAmount + @lPendingAmount, Remark = 'Transferred to New Batch', UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
					WHERE SourceTypeId = 2001 AND SourceId = @lOldAcademicId AND FeeSetupId = @lOldFeeSetupId
				END
				ELSE
				BEGIN
					-- Insert Fee Allocation
					INSERT INTO sFee.tFeeAllocation
					(
						SourceTypeId,
						SourceId,
						FeeSetupId,
						VariableAmount,
						DiscountAmount,
						AdditionalAmount,
						NotApplicableAmount,
						Remark,
						ReferenceTypeId,
						ReferenceSourceId,
						CreatedUserId,
						CreatedDateTime,
						UpdatedUserId,
						UpdatedDateTime
					)
					VALUES
					(
						2001,
						@lOldAcademicId,
						@lOldFeeSetupId,
						0,
						0,
						0,
						@lPendingAmount,
						'Transferred to New Batch',
						NULL,
						NULL,
						@rCreatedUserId,
						sCommon.fGetDate(),
						@rCreatedUserId,
						sCommon.fGetDate()
					)
				END


				-- For Fee Process Added By Foram on 2025-01-30
				IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lOldAcademicId AND FeeSetupId = @lOldFeeSetupId)
				BEGIN
					UPDATE FAS
					SET FAS.NotApplicableAmount = FA.NotApplicableAmount, 
					FAS.ToPayAmount = (FAS.FeeAmount + FAS.VariableAmount + FAS.AdditionalAmount - FAS.DiscountAmount - FA.NotApplicableAmount - FAS.PaidAmount),
					FAS.UpdatedUserId = @rCreatedUserId, 
					FAS.UpdatedDateTime = sCommon.fGetDate()
					FROM sFee.tFeeAllocationStudent FAS
					INNER JOIN sFee.tFeeAllocation FA ON FAS.AcademicId = FA.SourceId AND FA.SourceTypeId = 2001
					WHERE FAS.AcademicId = @lOldAcademicId AND FAS.FeeSetupId = @lOldFeeSetupId
				END
				ELSE
				BEGIN
					DECLARE @lFeeAmount1 decimal(12,2) = 0
					SELECT @lFeeAmount1 = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lOldFeeSetupId

					INSERT INTO sFee.tFeeAllocationStudent
					(
						AcademicId
						,FeeSetupId
						,FeeAmount
						,VariableAmount
						,DiscountAmount
						,AdditionalAmount
						,NotApplicableAmount
						,ToPayAmount
						,PaidAmount
						,Remark
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
					)
					SELECT 
						FA.SourceId
						,FA.FeeSetupId
						,@lFeeAmount1
						,VariableAmount
						,DiscountAmount
						,AdditionalAmount
						,NotApplicableAmount
						,(@lFeeAmount1 + VariableAmount + AdditionalAmount - DiscountAmount - NotApplicableAmount)
						,0
						,Remark
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
					FROM sFee.tFeeAllocation FA
					WHERE FA.SourceTypeId = 2001 AND FA.SourceId = @lOldAcademicId AND FA.FeeSetupId = @lOldFeeSetupId
				END
				-- For Fee Process Added By Foram on 2025-01-30

				SET @lCount1 = @lCount1 -1
			END
		END
		 
		SET @lCount = @lCount -1
	END
	 
	DROP TABLE #TempTotalOldFeeImportWithNA
	DROP TABLE #TempOldFeeImportWithNA
	--DROP TABLE #TempOldFeeSetup
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
	DROP TABLE #TempTotalOldFeeImportWithNA
	DROP TABLE #TempOldFeeImportWithNA
	--DROP TABLE #TempOldFeeSetup
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOldPaidFeeToExceptionAdd]
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId int,
	@rNewFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rXml  nvarchar(MAX)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 
	IF OBJECT_ID('tempdb..#TempOldPaidFeeImport') IS NOT NULL DROP TABLE #TempOldPaidFeeImport

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lCount int
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	CREATE TABLE #TempOldPaidFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PaidAmount] decimal(12,2) NULL
	)
	
	INSERT INTO #TempOldPaidFeeImport 
	(
		StudentId,
		AcademicId,
		PaidAmount
	)	
	SELECT	
			A.StudentId,
			A.AcademicId,
			A.PaidAmount
	FROM OPENXML (@intDoc, '/Table/OldPaidFeeImport', 1)
	WITH
	(
			StudentId bigint '@StudentId',
			AcademicId bigint '@AcademicId',
			PaidAmount decimal(12,2) '@PaidAmount'
	)A 
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldPaidFeeImport
	
	SELECT * FROM #TempOldPaidFeeImport
	BEGIN TRANSACTION
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lPaidAmount decimal(12,2)
		DECLARE @lAdmissionCategoryId int

		SELECT @lStudentId = StudentId,@lPaidAmount=PaidAmount FROM #TempOldPaidFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId
		
		IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
		BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					ISNULL(FA.VariableAmount,0.00)AS FAAmount,
					ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
					ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
					ISNULL(R.PaidAmount,0) AS PaidAmount,
					ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS PendingAmount,
					ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount
				INTO #TempFeeSetup 
				FROM sFee.tFeeMaster FM
				INNER JOIN 
				(SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
					ISNULL(FS1.FeeDuration,'')  AS FeeDuration
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
					ISNULL(FS1.FeeDuration,'') AS FeeDuration
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				) FS ON FS.FeeId=FM.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 		
					WHERE						
					 R.SourceId= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0

				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					IF(@lPendingAmount > @lPaidAmount)
					BEGIN
						IF EXISTS(SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
						BEGIN
							-- Update Fee Allocation
							UPDATE sFee.tFeeAllocation SET DiscountAmount = DiscountAmount + @lPaidAmount, UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
							WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId
						END
						ELSE
						BEGIN
							-- Insert Fee Allocation
							INSERT INTO sFee.tFeeAllocation
							(
								SourceTypeId,
								SourceId,
								FeeSetupId,
								VariableAmount,
								DiscountAmount,
								AdditionalAmount,
								NotApplicableAmount,
								Remark,
								ReferenceTypeId,
								ReferenceSourceId,
								CreatedUserId,
								CreatedDateTime,
								UpdatedUserId,
								UpdatedDateTime
							)
							VALUES
							(
								2001,
								@lAcademicId,
								@lFeeSetupId,
								0,
								@lPaidAmount,
								NULL,
								NULL,
								'Old Year Paid Fee',
								NULL,
								NULL,
								@rCreatedUserId,
								sCommon.fGetDate(),
								NULL,
								NULL
							)
						END
					END
				END
		END
		 
		SET @lCount = @lCount - 1
	END
	 
	DROP TABLE #TempOldPaidFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
		DROP TABLE #TempOldPaidFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOldPaidFeeToExceptionGet]
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId int,
	@rNewFeeId int,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF OBJECT_ID('tempdb..#TempOldPaidFeeImport') IS NOT NULL DROP TABLE #TempOldPaidFeeImport

	BEGIN TRY 

	DECLARE @lCount int
	
	-- Old Paid Fee Import Temp Table
	CREATE TABLE #TempOldPaidFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL,
		[AcademicId] bigint NULL,
		[Code] nvarchar(20),
		[Name] nvarchar(300),
		[RollNo] int,
		[ClassDivision] nvarchar(300),
		[PaidAmount] decimal(12,2) NULL,
		[NewFeeAmount] decimal(12,2) NULL,
		[Status] nvarchar(max) NULL
	)
	-- End Paid Fee Import Temp Table
	
	INSERT INTO #TempOldPaidFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision,
		SUM(ISNULL(FA.DiscountAmount,0.00) + ISNULL(FA.NotApplicableAmount,0.00) + ISNULL(R.PaidAmount,0.00)) AS PaidAmount,
		0,
		''
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE 
				(FS1.IsOptional=0)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FM.Id=@rOldFeeId) OR (@rOldFeeId=0))
			
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
			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
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE
				(FS1.IsOptional=1)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))	
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FM.Id=@rOldFeeId) OR (@rOldFeeId=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 
				R.Id AS ReceiptId, ISNULL((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=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((FM.Id=@rOldFeeId) OR (@rOldFeeId=0))
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId	 
	WHERE	
		SA.OrgId = @rOrgId 
		AND SA.BatchId=@rOldBatchId
		AND (ISNULL(FA.DiscountAmount,0.00) + ISNULL(FA.NotApplicableAmount,0.00) + ISNULL(R.PaidAmount,0.00)) > 0
	GROUP BY SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.RollNo,ISNULL(SA.ClassName, ''),ISNULL(SA.DivisionName, '')

	SELECT @lCount = COUNT(AutoId) FROM #TempOldPaidFeeImport
	
	BEGIN TRANSACTION
	
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lAcademicId bigint = NULL
			DECLARE @lStudentId bigint = NULL
			DECLARE @lClassId int = NULL
			DECLARE @lFeeSetupId int = NULL
			DECLARE @lPaidAmount decimal(12,2)
			DECLARE @lAdmissionCategoryId int

			SELECT @lStudentId = StudentId,@lPaidAmount=PaidAmount FROM #TempOldPaidFeeImport WHERE AutoId = @lCount
			SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
			SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId
		
			IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
			BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					ISNULL(FA.VariableAmount,0.00)AS FAAmount,
					ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
					ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
					ISNULL(R.PaidAmount,0) AS PaidAmount,
					ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS PendingAmount,
					ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount
				INTO #TempFeeSetup 
				FROM sFee.tFeeMaster FM
				INNER JOIN 
				(SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
					ISNULL(FS1.FeeDuration,'')  AS FeeDuration
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
					ISNULL(FS1.FeeDuration,'') AS FeeDuration
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				) FS ON FS.FeeId=FM.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 		
					WHERE						
					 R.SourceId= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0
				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					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.FeeId = @rNewFeeId 
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					WHERE (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(RD.Amount,0.00) = 0)
					AND R.SourceId = @lAcademicId
					)

					IF(@lPendingAmount < @lPaidAmount)
					BEGIN
						UPDATE #TempOldPaidFeeImport SET Status = 'Amount assigned in New Fee is less than Old Paid Fee', NewFeeAmount = @lPendingAmount WHERE AutoId = @lCount 
					END
					else if(@lIsReceiptGenerated = 1)
					begin
						UPDATE #TempOldPaidFeeImport SET Status = 'Receipt Generated or Fee Already Paid in New Batch', NewFeeAmount = @lPendingAmount WHERE AutoId = @lCount
					end
					else
					begin
						UPDATE #TempOldPaidFeeImport SET Status = '', NewFeeAmount = @lPendingAmount WHERE AutoId = @lCount
					end
				END
			END
			ELSE
			BEGIN
				UPDATE #TempOldPaidFeeImport SET Status = 'Fee Setup not assigned in New Batch', NewFeeAmount = 0 WHERE AutoId = @lCount
			END
			SET @lCount = @lCount - 1
		END
	 
	 SELECT * FROM #TempOldPaidFeeImport
	--DROP TABLE #TempOldPaidFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH 
		DROP TABLE #TempOldPaidFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, ERROR_LINE(), ERROR_MESSAGE()
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOldPaidFeeToNotApplicableAdd]
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId nvarchar(max),
	@rNewFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rXml  nvarchar(MAX)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 
	IF OBJECT_ID('tempdb..#TempOldPaidFeeImport') IS NOT NULL DROP TABLE #TempOldPaidFeeImport

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lCount int
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	CREATE TABLE #TempOldPaidFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PaidAmount] decimal(12,2) NULL
	)
	
	INSERT INTO #TempOldPaidFeeImport 
	(
		StudentId,
		AcademicId,
		PaidAmount
	)	
	SELECT	
			A.StudentId,
			A.AcademicId,
			A.PaidAmount
	FROM OPENXML (@intDoc, '/Table/OldPaidFeeImport', 1)
	WITH
	(
			StudentId bigint '@StudentId',
			AcademicId bigint '@AcademicId',
			PaidAmount decimal(12,2) '@PaidAmount'
	)A 
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldPaidFeeImport
	
	BEGIN TRANSACTION
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lPaidAmount decimal(12,2)
		DECLARE @lAdmissionCategoryId int

		SELECT @lStudentId = StudentId,@lPaidAmount=PaidAmount FROM #TempOldPaidFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = Id,@lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND AdmissionCategoryId = @lAdmissionCategoryId

		IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
		BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					ISNULL(FA.VariableAmount,0.00)AS FAAmount,
					ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
					ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
					ISNULL(R.PaidAmount,0) AS PaidAmount,
					ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)-ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS PendingAmount,
					ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount
				INTO #TempFeeSetup 
				FROM sFee.tFeeMaster FM
				INNER JOIN 
				(SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
					ISNULL(FS1.FeeDuration,'')  AS FeeDuration
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
					ISNULL(FS1.FeeDuration,'') AS FeeDuration
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				) FS ON FS.FeeId=FM.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 		
					WHERE						
					 R.SourceId= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0

				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					IF(@lPendingAmount >= @lPaidAmount)
					BEGIN
						IF EXISTS(SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
						BEGIN
							-- Update Fee Allocation
							UPDATE sFee.tFeeAllocation SET NotApplicableAmount = @lPaidAmount, UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
							WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId	
						END
						ELSE
						BEGIN
							-- Insert Fee Allocation
							INSERT INTO sFee.tFeeAllocation
							(
								SourceTypeId,
								SourceId,
								FeeSetupId,
								VariableAmount,
								DiscountAmount,
								AdditionalAmount,
								NotApplicableAmount,
								Remark,
								ReferenceTypeId,
								ReferenceSourceId,
								CreatedUserId,
								CreatedDateTime,
								UpdatedUserId,
								UpdatedDateTime
							)
							VALUES
							(
								2001,
								@lAcademicId,
								@lFeeSetupId,
								0,
								0,
								0,
								@lPaidAmount,
								'Old Year Paid Fee',
								NULL,
								NULL,
								@rCreatedUserId,
								sCommon.fGetDate(),
								NULL,
								NULL
							)
						END

						-- For Fee Process Added By Foram on 2025-01-30
						IF EXISTS(SELECT 1 FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
						BEGIN
							UPDATE sFee.tFeeAllocationStudent
							SET NotApplicableAmount = @lPaidAmount, 
							ToPayAmount = (FeeAmount + VariableAmount + AdditionalAmount - DiscountAmount - @lPaidAmount - PaidAmount),
							UpdatedUserId = @rCreatedUserId, 
							UpdatedDateTime = sCommon.fGetDate()
							WHERE AcademicId = @lAcademicId AND FeeSetupId = @lFeeSetupId
						END
						ELSE
						BEGIN
							DECLARE @lFeeAmount decimal(12,2) = 0
							SELECT @lFeeAmount = ISNULL(Amount, 0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

							INSERT INTO sFee.tFeeAllocationStudent
							(
								AcademicId
								,FeeSetupId
								,FeeAmount
								,VariableAmount
								,DiscountAmount
								,AdditionalAmount
								,NotApplicableAmount
								,ToPayAmount
								,PaidAmount
								,Remark
								,CreatedUserId
								,CreatedDateTime
								,UpdatedUserId
								,UpdatedDateTime
							)
							VALUES (
								@lAcademicId
								,@lFeeSetupId
								,@lFeeAmount
								,0
								,0
								,0
								,@lPaidAmount
								,(@lFeeAmount - @lPaidAmount) 
								,0
								,'Old Year Paid Fee'
								,0
								,sCommon.fGetDate()
								,0
								,sCommon.fGetDate()
							);
						END
						-- For Fee Process Added By Foram on 2025-01-30
					END
				END
		END
		 
		SET @lCount = @lCount - 1
	END
	 
	DROP TABLE #TempOldPaidFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
		DROP TABLE #TempOldPaidFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOldPaidFeeToNotApplicableGet]
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId nvarchar(max),
	@rNewFeeId int,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF OBJECT_ID('tempdb..#TempOldPaidFeeImport') IS NOT NULL DROP TABLE #TempOldPaidFeeImport

	BEGIN TRY 

	DECLARE @lCount int
	
	-- Old Exemption Fee Import Temp Table
	CREATE TABLE #TempOldPaidFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL,
		[AcademicId] bigint NULL,
		[Code] nvarchar(20),
		[Name] nvarchar(300),
		[RollNo] int,
		[ClassDivision] nvarchar(300),
		[PaidAmount] decimal(12,2) NULL,
		[NewPaidAmount] decimal(12,2) NULL,
		[Status] nvarchar(max) NULL
	)
	-- End Exemption Fee Import Temp Table
	
	INSERT INTO #TempOldPaidFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision,
		SUM(ISNULL(R.PaidAmount,0.00)) AS PaidAmount,
		0,
		''
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01') AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01') AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE 
				(FS1.IsOptional=0)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FM.Id IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rOldFeeId,',')) OR @rOldFeeId='') 
			
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01') AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01') AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
			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
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE
				(FS1.IsOptional=1)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))	
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FM.Id IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rOldFeeId,',')) OR @rOldFeeId='') 
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		INNER 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 		
			WHERE R.SourceTypeId = 2001
			AND R.IsObsolete = 0 
			AND R.BatchId = @rOldBatchId
			GROUP BY RD.FeeSetupId, R.SourceId
		) R ON R.FeeSetupId = FS.Id AND R.SourceId = SA.AcademicId
	WHERE	
		SA.OrgId = @rOrgId 
		AND SA.BatchId=@rOldBatchId
		AND ISNULL(R.PaidAmount,0.00) > 0
	GROUP BY SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.RollNo,ISNULL(SA.ClassName, ''),ISNULL(SA.DivisionName, '')

	SELECT @lCount = COUNT(AutoId) FROM #TempOldPaidFeeImport
	
	BEGIN TRANSACTION
	
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lAcademicId bigint = NULL
			DECLARE @lStudentId bigint = NULL
			DECLARE @lClassId int = NULL
			DECLARE @lFeeSetupId int = NULL
			DECLARE @lPaidAmount decimal(12,2)
			DECLARE @lAdmissionCategoryId int

			SELECT @lStudentId = StudentId,@lPaidAmount=PaidAmount FROM #TempOldPaidFeeImport WHERE AutoId = @lCount
			SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.tAcademic SA 
			WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
			SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId AND AdmissionCategoryId = @lAdmissionCategoryId
		
			IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
			BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					ISNULL(FA.VariableAmount,0.00)AS FAAmount,
					ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
					ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
					ISNULL(R.PaidAmount,0) AS PaidAmount,
					ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS PendingAmount,
					ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount
				INTO #TempFeeSetup 
				FROM sFee.tFeeMaster FM
				INNER JOIN 
				(SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
					ISNULL(FS1.FeeDuration,'')  AS FeeDuration
				FROM sFee.tFeeSetup FS1
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				UNION ALL
				
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
					ISNULL(FS1.FeeDuration,'') AS FeeDuration
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
				) FS ON FS.FeeId=FM.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
				LEFT JOIN
				(
					SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 		
					WHERE						
					 R.SourceId= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0
				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					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.FeeId = @rNewFeeId 
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					WHERE (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(RD.Amount,0.00) = 0)
					AND R.SourceId = @lAcademicId
					)

					IF(@lPendingAmount < @lPaidAmount)
					BEGIN
						UPDATE #TempOldPaidFeeImport SET Status = 'Amount assigned in New Fee is less than Old Paid Fee', NewPaidAmount = @lPendingAmount WHERE AutoId = @lCount 
					END
					ELSE IF(@lIsReceiptGenerated = 1)
					BEGIN
						UPDATE #TempOldPaidFeeImport SET Status = 'Receipt Generated or Fee Already Paid in New Batch', NewPaidAmount = @lPendingAmount WHERE AutoId = @lCount
					END
					ELSE
					BEGIN
						UPDATE #TempOldPaidFeeImport SET Status = '', NewPaidAmount = @lPendingAmount WHERE AutoId = @lCount
					END
				END
			END
			ELSE
			BEGIN
				UPDATE #TempOldPaidFeeImport SET Status = 'Fee Setup not assigned in New Batch', NewPaidAmount = 0 WHERE AutoId = @lCount
			END
			SET @lCount = @lCount - 1
		END
	 
		SELECT * FROM #TempOldPaidFeeImport
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		DROP TABLE #TempOldPaidFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, ERROR_LINE(), ERROR_MESSAGE()
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOnlineFeeAdd]
	
			@rId bigint=0,
			@rSourceTypeId smallint,
			@rSourceId bigint,
			@rFeeAmount decimal(12, 2),
			@rPenaltyAmount decimal(12, 2),
			@rNetAmount decimal(12, 2),
			@rOnlineFeeDetailXml [nvarchar](max),
			@rOrgId int,
			@rReceiptBookId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rOnlineFeeDetailXml

BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	
			
			DECLARE @lWrongFeeSetupOrReceiptBook int = 0
			IF EXISTS (
					SELECT 1
					FROM sFee.tFeeSetup FS
					INNER JOIN (
						SELECT FeeSetupId
							,@rReceiptBookId AS ReceiptBookId
						FROM OPENXML(@loDoc, '/Table/OnlineFeeDetail', 1) WITH (FeeSetupId INT)
						) AS RD ON RD.FeeSetupId = FS.Id AND RD.ReceiptBookId <> FS.ReceiptBookId
					)
			BEGIN
				SELECT @lWrongFeeSetupOrReceiptBook = 1
			END

			IF(@lWrongFeeSetupOrReceiptBook = 0)
			BEGIN
				DECLARE @lNextNumber BIGINT     
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tOnlineFee', 0, 1, 1,@outNextNumber = @lNextNumber output

				INSERT INTO sFee.tOnlineFee
				(
					Id,
					SourceTypeId,
					SourceId,
					PayDateTime,
					FeeAmount,
					PenaltyAmount,
					NetAmount,
					ReceiptBookId
				)
				VALUES
				(
					@lNextNumber,
					@rSourceTypeId,
					@rSourceId,
					sCommon.fGetDate(),
					@rFeeAmount,
					@rPenaltyAmount,
					@rNetAmount,
					@rReceiptBookId
				)	
		
				INSERT INTO sFee.tOnlineFeeDetail
				(
					OnlineFeeId,
					FeeSetupId,
					Amount
				)
				SELECT  	
					@lNextNumber,
					FeeSetupId,
					Amount
				FROM OPENXML (@loDoc, '/Table/OnlineFeeDetail', 1)
				WITH ( 
						FeeSetupId int,
						Amount decimal(12,2)
					  ) 

				SELECT @lNextNumber AS Result
			END
			ELSE 
			BEGIN
				SELECT -1 AS Result
			END

			EXEC sp_xml_removedocument @loDoc
	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pOptionalFeeGet]

		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rSourceTypeId int,
		   @rSourceId bigint
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
			ISNULL(FS.Id,0)AS Id,
			FM.Title AS FeeTitle,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
			ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			CASE WHEN ISNULL(FO.SourceId,0) = 0 THEN 'False' ELSE 'True' END AS IsCheck
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId AND FS.IsOptional=1
			AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS.Id AND FO.SourceTypeId=@rSourceTypeId AND FO.SourceId=@rSourceId
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,FM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pOptionalFeeRemoveHistory] 
	 @rSourceId BIGINT
	,@rSourceTypeId INT
	,@rBatchId INT
	,@rFeeSetupId INT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lClassId INT
	DECLARE @lAdmissionCategoryId INT

	DECLARE @lExemptionTypeId INT = 0
	DECLARE @lExemptionType NVARCHAR(100) = ''

	SELECT @lClassId = ClassId, @lAdmissionCategoryId = AdmissionCategoryId, @lExemptionTypeId = ExemptionTypeId
	FROM sStudent.vStudentAcademic WHERE AcademicId = @rSourceId

	SELECT @lExemptionType = Title FROM [sFee].[tExemptionTypeMaster] WHERE Id = @lExemptionTypeId

	SELECT FM.Id AS FeeId
		,FM.Title AS FeeName
		,FS.Id AS FeeSetupId
		,ISNULL(FS.IsOptional, 0) AS IsOptional
		,ISNULL(FS.IsVariable, 0) AS IsVariable
		,ISNULL(FS.Amount, 0) AS Amount
		,ISNULL(FS.StartDate, '1900-01-01') AS StartDate
		,ISNULL(FS.EndDate, '1900-01-01') AS EndDate
		,ISNULL(FA.VariableAmount, 0.00) AS FAAmount
		,ISNULL(FA.DiscountAmount, 0.00) AS DiscountAmount
		,ISNULL(FA.AdditionalAmount, 0.00) AS AdditionalAmount
		,ISNULL(R.PaidAmount, 0) AS PaidAmount
		,ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) AS PendingAmount
		,ISNULL(FA.NotApplicableAmount, 0.00) AS NotApplicableAmount
		,ISNULL(FA.Remark, '') AS Remark
		,ISNULL(FA.NotApplicableRemark, '') AS NotApplicableRemark
		,ISNULL(FA.AdditionalRemark, '') AS AdditionalRemark
		,ISNULL(FA.DiscountRemark, '') AS ExemptionRemark
		,FM.OrderIndex
		,ISNULL(FS.ReceiptBookId, 0) AS ReceiptBookId
		,FS.CollectionGroupId
		,FM.FeeHeadId
		,FS.FeeDuration
		,ISNULL(FM.Code, '') AS FeeCode
		,CASE 
			WHEN (ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) > 0)
				AND (ISNULL(FS.StartDate, '1900-01-01') > GETDATE())
				AND (ISNULL(FS.Amount, 0) > 0 OR ISNULL(FA.VariableAmount, 0.00) > 0)
				THEN 'To Pay'
			WHEN (ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) > 0)
				AND (GETDATE() > ISNULL(FS.StartDate, '1900-01-01'))
				AND (ISNULL(FS.Amount, 0) > 0 OR ISNULL(FA.VariableAmount, 0.00) > 0
					)
				THEN 'Unpaid'
			WHEN (ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) <= 0)
				AND (ISNULL(FS.Amount, 0) > 0 OR ISNULL(FA.VariableAmount, 0.00) > 0
					)
				THEN 'Paid'
			ELSE ''
			END AS STATUS
		,@lExemptionType AS ExemptionType
		,@lExemptionTypeId AS ExemptionTypeId
	FROM sFee.tFeeMaster FM
	INNER JOIN (
		SELECT FS1.FeeId
			,FS1.Id
			,ISNULL(FS1.IsOptional, 0) AS IsOptional
			,ISNULL(FS1.IsVariable, 0) AS IsVariable
			,ISNULL(FS1.Amount, 0) AS Amount
			,ISNULL(FS1.StartDate, '1900-01-01') AS StartDate
			,ISNULL(FS1.EndDate, '1900-01-01') AS EndDate
			,FS1.BatchId
			,ISNULL(FS1.ReceiptBookId, 0) AS ReceiptBookId
			,ISNULL(FS1.CollectionGroupId, 0) AS CollectionGroupId
			,ISNULL(FS1.FeeDuration, '') AS FeeDuration
		FROM sFee.tFeeSetup FS1
		WHERE FS1.ClassId = @lClassId
			AND FS1.AdmissionCategoryId = @lAdmissionCategoryId
			AND IsOptional = 0
			AND FS1.BatchId = @rBatchId
		
		UNION ALL
		
		SELECT FS1.FeeId
			,FS1.Id
			,ISNULL(FS1.IsOptional, 0) AS IsOptional
			,ISNULL(FS1.IsVariable, 0) AS IsVariable
			,ISNULL(FS1.Amount, 0) AS Amount
			,ISNULL(FS1.StartDate, '1900-01-01') AS StartDate
			,ISNULL(FS1.EndDate, '1900-01-01') AS EndDate
			,FS1.BatchId
			,ISNULL(FS1.ReceiptBookId, 0) AS ReceiptBookId
			,ISNULL(FS1.CollectionGroupId, 0) AS CollectionGroupId
			,ISNULL(FS1.FeeDuration, '') AS FeeDuration
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId = FS1.Id
			AND (FO.SourceId = @rSourceId)
			AND (FO.SourceTypeId = @rSourceTypeId)
		WHERE FS1.BatchId = @rBatchId
			AND FS1.ClassId = @lClassId
			AND FS1.AdmissionCategoryId = @lAdmissionCategoryId
			AND IsOptional = 1
		) FS ON FS.FeeId = FM.Id
	LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId = FS.Id AND (FA.SourceId = @rSourceId) AND (FA.SourceTypeId = @rSourceTypeId)
	LEFT JOIN (
		SELECT ISNULL(SUM(RD.Amount), 0) AS PaidAmount
			,RD.FeeSetupId
		FROM sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
		WHERE R.SourceId = @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId = 0))
			AND R.IsObsolete = 0
			AND R.BatchId = @rBatchId
		GROUP BY RD.FeeSetupId
		) R ON R.FeeSetupId = FS.Id
	WHERE FS.BatchId = @rBatchId
		AND FS.Id = @rFeeSetupId
	ORDER BY FS.StartDate ASC
		,FM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pPaymentTransactionDelete]

			@rPaymentTransactionId bigint,
			@rDeletededUser nvarchar(100)			


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 --Insert Into sFee.tOnlineFeeDetailHistory
	
		INSERT INTO sFee.tOnlineFeeDetailHistory
           (
				OnlineFeeId
			   ,FeeSetupId
			   ,Amount
		   )
		SELECT  OnlineFeeId
			   ,FeeSetupId
               ,Amount
               FROM sFee.tOnlineFeeDetail OFD 
			   INNER JOIN sFee.tOnlineFee OnF ON OFD.OnlineFeeId=OnF.Id
			   INNER JOIN sOp.tPaymentTransaction PT ON 
			   OnF.Id=PT.TransactionSourceId AND PT.TransactionSourceTypeId=2024
			   WHERE PT.Id=@rPaymentTransactionId

	--Insert Into sFee.tOnlineFeeHistory

		INSERT INTO sFee.tOnlineFeeHistory
			   (
				Id 
			   ,SourceTypeId
			   ,SourceId
			   ,PayDateTime
			   ,FeeAmount
			   ,PenaltyAmount
			   ,NetAmount
			   ,ReceiptBookId
			   )
		SELECT OnF.Id
			  ,OnF.SourceTypeId
			  ,OnF.SourceId
			  ,OnF.PayDateTime
			  ,OnF.FeeAmount
			  ,OnF.PenaltyAmount
			  ,OnF.NetAmount
			  ,OnF.ReceiptBookId
		  FROM sFee.tOnlineFee OnF 
		  INNER JOIN sOp.tPaymentTransaction PT ON 
		  OnF.Id=PT.TransactionSourceId AND PT.TransactionSourceTypeId=2024
		  WHERE PT.Id=@rPaymentTransactionId

	--Insert Into sOp.tPaymentTransactionHistory
	
		INSERT INTO sOp.tPaymentTransactionHistory
			(
				Id,
				TransactionSourceTypeId,
				TransactionSourceId,
				PayerSourceTypeId,
				PayerSourceId,
				PayDateTime,
				PayAmount,
				TransactionStatusId,
				FunctionalityId,
				MerchantTransactionId,
				BankTransactionId,
				BankName,
				PaymentType,
				CardNumber,
				TransactionResponse,
				TransactionRequest,
				OSTypeId,
				DeletededUser,
				DeletedDateTime,
				PaymentGatewayId
			)
		SELECT	Id,
				TransactionSourceTypeId,
				TransactionSourceId,
				PayerSourceTypeId,
				PayerSourceId,
				PayDateTime,
				PayAmount,
				TransactionStatusId,
				FunctionalityId,
				MerchantTransactionId,
				BankTransactionId,
				BankName,
				PaymentType,
				CardNumber,
				TransactionResponse,
				TransactionRequest,
				OSTypeId,
				@rDeletededUser+'-'+(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id=@rDeletededUser),
				sCommon.fGetDate(),
				PaymentGatewayId
				FROM sOp.tPaymentTransaction WHERE Id=@rPaymentTransactionId
				AND TransactionSourceTypeId=2024

	DELETE OFD FROM sFee.tOnlineFeeDetail OFD
				    INNER JOIN sFee.tOnlineFee OnF ON OFD.OnlineFeeId=OnF.Id
			        INNER JOIN sOp.tPaymentTransaction PT ON 
			        OnF.Id=PT.TransactionSourceId AND PT.TransactionSourceTypeId=2024
			        WHERE PT.Id=@rPaymentTransactionId

	DELETE OnF FROM sFee.tOnlineFee OnF
	                INNER JOIN sOp.tPaymentTransaction PT ON 
		            OnF.Id=PT.TransactionSourceId AND PT.TransactionSourceTypeId=2024
		            WHERE PT.Id=@rPaymentTransactionId

	DELETE FROM sOp.tPaymentTransaction WHERE Id=@rPaymentTransactionId AND TransactionSourceTypeId=2024
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pPaytypeReceiptCollectionDashBoardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rFeeHeadId int=0,
	 @rPayTypeId int =0
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
   SELECT
   (
	SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
	) AS YesterdayAmount,
	(
	SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS DailyAmount,
	
	(
		SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS MonthlyAmount,
	
	(
		SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	) AS YearlyAmount
  END
  
  IF(@rType='ReceiptBook')
  BEGIN
  DECLARE @cols NVARCHAR(MAX),@query  NVARCHAR(MAX);
  IF(@rDay=-1)
	BEGIN
		SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
            INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	            WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.IsObsolete = 0) 
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query = 'SELECT ReceiptBookId,ReceiptBook, ' + @cols + ' from 
            (
            SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,PTM.Title AS PayTypeName, COALESCE(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
			WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0) 
			GROUP BY RBM.Id,RBM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount) 
                for PayTypeName in (' + @cols + ')
            ) p '
execute(@query)
	END
	IF(@rDay=1)
	BEGIN
		SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
            INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	            WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.IsObsolete = 0) 
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query = 'SELECT ReceiptBookId,ReceiptBook, ' + @cols + ' from 
            (
            SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,PTM.Title AS PayTypeName, COALESCE(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
			WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0) 
			GROUP BY RBM.Id,RBM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount) 
                for PayTypeName in (' + @cols + ')
            ) p '
execute(@query)
	END
	IF(@rDay=30)
	BEGIN
		SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
            INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
            WHERE R.SourceTypeId = 2001
            AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.IsObsolete = 0) 
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query = 'SELECT ReceiptBookId,ReceiptBook, ' + @cols + ' from 
            (
            SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,PTM.Title AS PayTypeName, COALESCE(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
			WHERE R.SourceTypeId = 2001
			AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0) 
			GROUP BY RBM.Id,RBM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount)
                for PayTypeName in (' + @cols + ')
            ) p '
            
execute(@query)
	END
	IF(@rDay=365)
	BEGIN
		SET @cols = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
            INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
            WHERE R.SourceTypeId = 2001
            AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.IsObsolete = 0) 
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query = 'SELECT ReceiptBookId,ReceiptBook, ' + @cols + ' from 
            (
            SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,PTM.Title AS PayTypeName, COALESCE(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
			WHERE R.SourceTypeId = 2001
			AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0) 
			GROUP BY RBM.Id,RBM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount)
                for PayTypeName in (' + @cols + ')
            ) p '
            
execute(@query)
	END
  END
  
  IF(@rType='FeeHead')
  BEGIN
  DECLARE @cols1 NVARCHAR(MAX),@query1  NVARCHAR(MAX);
  IF(@rDay=-1)
	BEGIN
	SET @cols1 = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
            INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
            WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.ReceiptBookId = @rReceiptBookId)
			AND (R.IsObsolete = 0) 
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query1 = 'SELECT FeeHeadId,FeeHead, ' + @cols1 + ' from 
            (
            SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0)
			AND (R.ReceiptBookId ='+CONVERT(nvarchar(20),@rReceiptBookId)+')  
			GROUP BY FHM.Id,FHM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount)
                for PayTypeName in (' + @cols1 + ')
            ) p '
execute(@query1)
	END
	IF(@rDay=1)
	BEGIN
	SET @cols1 = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
            INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
            WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.ReceiptBookId = @rReceiptBookId)
			AND (R.IsObsolete = 0) 
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query1 = 'SELECT FeeHeadId,FeeHead, ' + @cols1 + ' from 
            (
            SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0)
			AND (R.ReceiptBookId ='+CONVERT(nvarchar(20),@rReceiptBookId)+')  
			GROUP BY FHM.Id,FHM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount)
                for PayTypeName in (' + @cols1 + ')
            ) p '
execute(@query1)
	END
	IF(@rDay=30)
	BEGIN
		SET @cols1 = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
             INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
            WHERE R.SourceTypeId = 2001
            AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.IsObsolete = 0) 
			AND (R.ReceiptBookId = @rReceiptBookId)
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
set @query1 = 'SELECT FeeHeadId,FeeHead, ' + @cols1 + ' from 
            (
            SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			WHERE R.SourceTypeId = 2001
			AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0) 
			AND (R.ReceiptBookId ='+CONVERT(nvarchar(20),@rReceiptBookId)+') 
			GROUP BY FHM.Id,FHM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount)
                for PayTypeName in (' + @cols1 + ')
            ) p '
            
execute(@query1)
	END
	IF(@rDay=365)
	BEGIN
		SET @cols1 = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
             INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
            WHERE R.SourceTypeId = 2001
            AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.IsObsolete = 0) 
			AND (R.ReceiptBookId = @rReceiptBookId)
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query1 = 'SELECT FeeHeadId,FeeHead, ' + @cols1 + ' from 
            (
           SELECT  FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
			 INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			WHERE R.SourceTypeId = 2001
			AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0) 
			AND (R.ReceiptBookId ='+CONVERT(nvarchar(20),@rReceiptBookId)+') 
			GROUP BY FHM.Id,FHM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount)
                for PayTypeName in (' + @cols1 + ')
            ) p '
            
execute(@query1)
	END
  END
  
  IF(@rType='FeeMaster')
  BEGIN
   DECLARE @cols2 NVARCHAR(MAX),@query2  NVARCHAR(MAX);
   IF(@rDay=-1)
	BEGIN
	SET @cols2 = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
            INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
            WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.ReceiptBookId = @rReceiptBookId)
			AND (FHM.Id =@rFeeHeadId)
			AND (R.IsObsolete = 0) 
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query2 = 'SELECT FeeHeadId,FeeMaster, ' + @cols2 + ' from 
            (
            SELECT  FM.Id AS FeeHeadId,FM.Title AS FeeMaster,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
			WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = DATEADD(day, -1, convert(date, GETDATE()))
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0)
			AND (R.ReceiptBookId ='+CONVERT(nvarchar(20),@rReceiptBookId)+')  
			AND (FHM.Id ='+CONVERT(nvarchar(20),@rFeeHeadId)+') 
			GROUP BY FM.Id,FM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount)
                for PayTypeName in (' + @cols2 + ')
            ) p '
execute(@query2)
	END
	IF(@rDay=1)
	BEGIN
	SET @cols2 = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
            INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
            WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.ReceiptBookId = @rReceiptBookId)
			AND (FHM.Id =@rFeeHeadId)
			AND (R.IsObsolete = 0) 
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query2 = 'SELECT FeeHeadId,FeeMaster, ' + @cols2 + ' from 
            (
            SELECT  FM.Id AS FeeHeadId,FM.Title AS FeeMaster,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
			WHERE R.SourceTypeId = 2001
			AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0)
			AND (R.ReceiptBookId ='+CONVERT(nvarchar(20),@rReceiptBookId)+')  
			AND (FHM.Id ='+CONVERT(nvarchar(20),@rFeeHeadId)+') 
			GROUP BY FM.Id,FM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount)
                for PayTypeName in (' + @cols2 + ')
            ) p '
execute(@query2)
	END
	IF(@rDay=30)
	BEGIN
		SET @cols1 = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
             INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
            WHERE R.SourceTypeId = 2001
            AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.IsObsolete = 0) 
			AND (R.ReceiptBookId = @rReceiptBookId)
			AND (FHM.Id =@rFeeHeadId)
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
set @query1 = 'SELECT FeeHeadId,FeeMaster, ' + @cols1 + ' from 
            (
            SELECT  FM.Id AS FeeHeadId,FM.Title AS FeeMaster,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
			WHERE R.SourceTypeId = 2001
			AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0) 
			AND (R.ReceiptBookId ='+CONVERT(nvarchar(20),@rReceiptBookId)+') 
			AND (FHM.Id ='+CONVERT(nvarchar(20),@rFeeHeadId)+') 
			GROUP BY FM.Id,FM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount)
                for PayTypeName in (' + @cols1 + ')
            ) p '
            
execute(@query1)
	END
	IF(@rDay=365)
	BEGIN
		SET @cols1 = STUFF((SELECT ',' +  QUOTENAME(PTM.Title )
            FROM sFinanceCommon.tPayTypeMaster PTM  
             INNER JOIN sFee.tReceipt R ON PTM.Id=R.PayTypeId
            INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
            INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
            WHERE R.SourceTypeId = 2001
            AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.IsObsolete = 0) 
			AND (R.ReceiptBookId = @rReceiptBookId)
			AND (FHM.Id =@rFeeHeadId)
			Group by PTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query1 = 'SELECT FeeHeadId,FeeMaster, ' + @cols1 + ' from 
            (
           SELECT  FM.Id AS FeeHeadId,FM.Title AS FeeMaster,PTM.Title AS PayTypeName,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount FROM sFee.tReceipt R
			 INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
			WHERE R.SourceTypeId = 2001
			AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
			AND LEFT(SA.OrgGroupBatchId,4) ='+CONVERT(nvarchar(20),@rOrgGroupId)+'
			AND (SA.OrgGroupBatchId ='+CONVERT(nvarchar(20),@rOrgGroupBatchId)+')
			AND	((SA.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND ((SA.BatchId='+CONVERT(nvarchar(20),@rBatchId)+') OR ('+CONVERT(nvarchar(20),@rBatchId)+'=0))
			AND ((R.CreatedUserId='+CONVERT(nvarchar(20),@rUserId)+') OR ('+CONVERT(nvarchar(20),@rUserId)+'=0))
			AND (R.IsObsolete = 0) 
			AND (R.ReceiptBookId ='+CONVERT(nvarchar(20),@rReceiptBookId)+') 
			AND (FHM.Id ='+CONVERT(nvarchar(20),@rFeeHeadId)+') 
			GROUP BY FM.Id,FM.Title,PTM.Id,PTM.Title
           ) x
            pivot 
            (
                 Sum(ReceiptAmount)
                for PayTypeName in (' + @cols1 + ')
            ) p '
            
execute(@query1)
	END
END
 
  END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pPendingFeeCollectionGroupDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rOrgGroupId int=0,
	 @rCollectionGroupId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='CollectionGroup')
  BEGIN
	SELECT 
		CGM.Id AS CollectionGroupId,RBM.Title +' - '+ CGM.Title AS CollectionGroupName,
		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,
		COUNT(SA.AcademicId) AS PendingCount
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.IsActive = 1
			WHERE 
			    LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId
				AND (FS1.IsOptional=0)
			
			UNION ALL
			
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId		
			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
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.IsActive = 1
		WHERE
		        LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId
				AND (FS1.IsOptional=1)
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId
			    AND LEFT(R.OrgGroupBatchId,4) = @rOrgGroupId
				AND (R.ReceiptDate <= CONVERT(DATE,Getdate()))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id		
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO 
			ON SO.StudentId = SA.StudentId
		 INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	WHERE	
			LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND ((FS.StartDate <= CONVERT(DATE,Getdate())))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
			AND SA.StatusId = 1
	GROUP BY RBM.Title,CGM.Id,CGM.Title
  END
  
  IF(@rType='Student')
  BEGIN
	SELECT
	    SA.ClassName + ' - ' + SA.DivisionName AS ClassDivision,  
		SA.Code,
		SA.Name,
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
    FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.IsActive = 1
			WHERE 
			    LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId
				AND (FS1.IsOptional=0)
			
			UNION ALL
			
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId			 
			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
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.IsActive = 1
		WHERE
		        LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId
				AND (FS1.IsOptional=1)
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId
				AND LEFT(R.OrgGroupBatchId,4) = @rOrgGroupId
				AND (R.ReceiptDate <= CONVERT(DATE,Getdate()))
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id	
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO 
			ON SO.StudentId = SA.StudentId
		 INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	WHERE	
			LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
			AND ((FS.StartDate <= CONVERT(DATE,Getdate())))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
			AND SA.StatusId = 1
			AND CGM.Id = @rCollectionGroupId
	GROUP BY SA.ClassName,SA.DivisionName ,SA.Code,SA.Name
  END
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pPendingFeeDashboardGet]

	@rOrgGroupBatchId int = 0,
	@rCommonOrgGroupBatchId int = 0,
	@rType int,
	@rFilterType nvarchar(Max),
	@rFeeType nvarchar(Max),
	@rStudentStatus int = 0,
	@rUptoDate date = '',
	@rDepartmentId int=0,
	@rOrgId int,
	@rReceiptBookId int,
	@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN

	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('Type: ' + CAST(@rType AS nvarchar(100)), 
	'@rOrgGroupBatchId = ' +  CAST(@rOrgGroupBatchId AS nvarchar(100))
	+ ', @rCommonOrgGroupBatchId = ' +  CAST(@rCommonOrgGroupBatchId AS nvarchar(100))
	+ ', @rFilterType = ' +  CAST(@rFilterType AS nvarchar(100))
	+ ', @rFeeType = ' +  CAST(@rFeeType AS nvarchar(100))
	+ ', @rStudentStatus = ' +  CAST(@rStudentStatus AS nvarchar(100))
	+ ', @rUptoDate = ' +  CAST(@rUptoDate AS nvarchar(100))  
	+ ', @rDepartmentId = ' +  CAST(@rDepartmentId AS nvarchar(100))  
	+ ', @rOrgId = ' +  CAST(@rOrgId AS nvarchar(100))
	+ ', @rReceiptBookId = ' +  CAST(@rReceiptBookId AS nvarchar(100))
	+ ', @rOrgGroupId = ' +  CAST(@rOrgGroupId AS nvarchar(100)), 
	'',
	'', 
	GETDATE(), 
	'[sFee].[pPendingFeeDashboardGet]')
END

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

SELECT @rOrgGroupBatchId = Id FROM sSetup.tOrgGroupBatchMaster WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId

IF (@rType = 1)
 BEGIN
IF(@rFilterType = 'Organizationwise')		
BEGIN 
	IF OBJECT_ID('tempdb..#FeeReceiptTemp') IS NOT NULL DROP TABLE #FeeReceiptTemp
	CREATE TABLE #FeeReceiptTemp
		(
			PaidAmount decimal (12,2),
			FeesetupId int,
			SourceId bigint
		)

	INSERT INTO #FeeReceiptTemp
		SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		FROM
			sFee.tReceipt R WITH (NOLOCK)
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
			INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id=SA1.BatchId			
		WHERE		
			(R.SourceTypeId = 2001) 
			AND (R.IsObsolete = 0) 
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
			AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (R.ReceiptDate <= @rUptoDate) 
			AND BM.IsInContext = 1 
			GROUP BY FeeSetupId,R.SourceId

	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		
		CREATE TABLE #FeeHeadwisetmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		)

		INSERT INTO #FeeHeadwisetmp
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
			INNER JOIN #FeeHeadwisetmp FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN #FeeReceiptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FHM.OrderIndex

		DROP TABLE #FeeHeadwisetmp
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		CREATE TABLE #FeeMasterwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			OrderIndex int
		)
	 
	 INSERT INTO #FeeMasterwisetmp
		 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
 		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
				INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				INNER JOIN #FeeMasterwisetmp FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN #FeeReceiptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			WHERE
				SA.OrgGroupBatchId = @rOrgGroupBatchId
				AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
				AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				-- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FS.FeeId
	 DROP TABLE #FeeMasterwisetmp
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		CREATE TABLE #CollectionGroupwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			CollectionGroupId int
		)
		
		INSERT INTO #CollectionGroupwisetmp
	 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
 		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
			INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
			INNER JOIN #CollectionGroupwisetmp FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN #FeeReceiptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
		WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title,CGM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,CGM.Id

	 DROP TABLE #CollectionGroupwisetmp
	 END
	
	DROP TABLE #FeeReceiptTemp

END

ELSE IF(@rFilterType = 'Departmentwise')
BEGIN
	
	IF OBJECT_ID('tempdb..#FeeReceiptdeptTemp') IS NOT NULL DROP TABLE #FeeReceiptdeptTemp
	CREATE TABLE #FeeReceiptdeptTemp
		(
			PaidAmount decimal (12,2),
			FeesetupId int,
			SourceId bigint
		)

	INSERT INTO #FeeReceiptdeptTemp
	SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		FROM
			sFee.tReceipt R WITH (NOLOCK) 
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
			INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id=SA1.BatchId			
		WHERE		
			(R.SourceTypeId = 2001) 
			AND (R.IsObsolete = 0) 
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
			AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (R.ReceiptDate <= @rUptoDate) 
			AND BM.IsInContext = 1 
			GROUP BY FeeSetupId,R.SourceId

	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartFeeHeadWise') IS NOT NULL DROP TABLE #tmpDepartFeeHeadWise
		CREATE TABLE #tmpDepartFeeHeadWise
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		)

		Insert Into #tmpDepartFeeHeadWise
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
		INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
		INNER JOIN sSetup.tDepartmentMaster DM WITH (NOLOCK) ON DM.Id = SA.DepartmentId
		INNER JOIN #tmpDepartFeeHeadWise FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #FeeReceiptdeptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
		WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1 
		GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title,FHM.OrderIndex,DM.OrderIndex
		ORDER BY DM.OrderIndex,DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN

		IF OBJECT_ID('tempdb..#tmpDepartFeeMasterwise') IS NOT NULL DROP TABLE #tmpDepartFeeMasterwise
		CREATE TABLE #tmpDepartFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		OrderIndex int
		)

		Insert Into #tmpDepartFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
				INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM WITH (NOLOCK) ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartFeeMasterwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN #FeeReceiptdeptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName,FS.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartCollectionGroupwise') IS NOT NULL DROP TABLE #tmpDepartCollectionGroupwise
		CREATE TABLE #tmpDepartCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int
		)

		INSERT INTO #tmpDepartCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
				INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM WITH (NOLOCK) ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartCollectionGroupwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN #FeeReceiptdeptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title,CGM.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,CGM.Id
	 END

	 DROP TABLE #FeeReceiptdeptTemp
END
ELSE IF(@rFilterType = 'ReceiptBookwise')
BEGIN

	IF OBJECT_ID('tempdb..#FeeReceiptbookTemp') IS NOT NULL DROP TABLE #FeeReceiptbookTemp

	CREATE TABLE #FeeReceiptbookTemp
		(
			PaidAmount decimal (12,2),
			FeesetupId int,
			SourceId bigint
		)

	INSERT INTO #FeeReceiptbookTemp
		SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		FROM
			sFee.tReceipt R WITH (NOLOCK) 
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
			INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id=SA1.BatchId			
		WHERE		
			(R.SourceTypeId = 2001) 
			AND (R.IsObsolete = 0) 
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
			AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (R.ReceiptDate <= @rUptoDate) 
			AND BM.IsInContext = 1 
			GROUP BY FeeSetupId,R.SourceId
		
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
		-- For Timeout issue
		CREATE TABLE #tmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int 
		)

		INSERT INTO #tmp
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
 		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
		FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.tAcademic SA WITH (NOLOCK)
			INNER JOIN [sStudent].[tStudentMaster] SM WITH (NOLOCK) ON SA.StudentId = SM.Id 
			INNER JOIN [sSetup].[tBatchMaster] BM WITH (NOLOCK) ON SA.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
			INNER JOIN #tmp FS ON FS.AcademicId=SA.Id
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
			LEFT JOIN #FeeReceiptbookTemp R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
			INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
			INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
			WHERE
			  BM.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SM.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title,FHM.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FHM.Id

		DROP TABLE #tmp
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptFeeMasterwise') IS NOT NULL DROP TABLE #tmpReceiptFeeMasterwise
		CREATE TABLE #tmpReceiptFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int,
		OrderIndex int
		)

		INSERT INTO  #tmpReceiptFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
				INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptFeeMasterwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN #FeeReceiptbookTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FS.FeeId
	END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptCollectionGroupwise') IS NOT NULL DROP TABLE #tmpReceiptCollectionGroupwise
		CREATE TABLE #tmpReceiptCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int,
		ReceiptBookId int
		)

		INSERT INTO #tmpReceiptCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
 				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
				FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
				INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA WITH (NOLOCK)
				INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptCollectionGroupwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN #FeeReceiptbookTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title,CGM.OrderIndex,RBM.OrderIndex
			--ORDER BY ReceiptBookId,CGM.Id
			ORDER BY RBM.OrderIndex,CGM.OrderIndex
	END

	DROP TABLE #FeeReceiptbookTemp
END
	
END
ELSE IF(@rType = 2)
BEGIN
	IF OBJECT_ID('tempdb..#ReceiptTemp') IS NOT NULL DROP TABLE #ReceiptTemp

	CREATE TABLE #ReceiptTemp
		(
			PaidAmount decimal (12,2),
			FeesetupId int,
			SourceId bigint
		)

	INSERT INTO #ReceiptTemp
	SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
	FROM
		sFee.tReceipt R WITH (NOLOCK) 
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id=SA1.BatchId			
	WHERE		
		(R.SourceTypeId = 2001) 
		AND (R.IsObsolete = 0) 
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
		AND (R.ReceiptDate <= @rUptoDate) 
		AND BM.IsInContext = 1 
		GROUP BY FeeSetupId,R.SourceId

		IF OBJECT_ID('tempdb..#tmptbl') IS NOT NULL DROP TABLE #tmptbl
		CREATE TABLE #tmptbl
			(
				FeeId int,
				Id int,
				IsOptional bit,
				IsVariable bit,
				Amount decimal (12,2),
				StartDate date,
				EndDate date,
				BatchId int,
				ReceiptBookId int,
				AcademicId bigint,
				FeeName nvarchar(100),
				FeeHeadId int,
				CollectionGroupId int,
				FeeOrderIndex int
			)
		INSERT INTO #tmptbl 
			SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.Id AS AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 
						FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
						INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
						INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id			 
						AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE 
							BM.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=0)
							-- IsInContext
							AND BM.IsInContext = 1
						UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 			 
						FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
						INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id
						INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
						INNER JOIN sStudent.vStudentAcademic SA1 WITH (NOLOCK) ON SA1.AcademicId=FO.SourceId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE
							SA1.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=1)
							-- IsInContext
							AND BM.IsInContext = 1
	
		SELECT 
					SA.OrgId,
					SA.OrganizationName as OrgName,
					SA.ClassId,
					SA.ClassName,
					SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount
				FROM 
					sStudent.vStudentAcademic SA WITH (NOLOCK)
					INNER JOIN #tmptbl  FS ON FS.AcademicId=SA.AcademicId
					LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					LEFT JOIN #ReceiptTemp R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
					 INNER JOIN sSetup.tOrganizationMaster O WITH (NOLOCK) ON	
					 SA.OrgId = O.Id
					 INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) 
						ON FS.ReceiptBookId=RBM.Id
					 LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK)
						ON FS.CollectionGroupId=CGM.Id	
					 LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) 
						ON SC.StudentId = SA.StudentId
					 LEFT JOIN sStudent.tStudentOther SO WITH (NOLOCK)
						ON SO.StudentId = SA.StudentId
					 INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK)
						ON FHM.Id = FS.FeeHeadId
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON SA.BatchId = BM.Id	
				  LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 
				  LEFT JOIN
					(SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK) 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
					ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
				WHERE	
				 SA.OrgGroupBatchId = @rOrgGroupBatchId
                 AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0) AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				 AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
				 -- IsInContext
				 AND BM.IsInContext = 1
				GROUP BY SA.ClassId,SA.ClassName,SA.OrgId,SA.OrganizationName,SA.ClassOrderIndex,SA.DivisionOrder
				--Order By SA.ClassId
				Order By SA.ClassOrderIndex,SA.DivisionOrder --add for mantis : 0042058
	DROP TABLE #ReceiptTemp
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pPendingFeeDashboardGet_Old]

		@rOrgGroupBatchId int = 0,
		@rCommonOrgGroupBatchId int = 0,
		@rType int,
		@rFilterType nvarchar(Max),
		@rFeeType nvarchar(Max),
		@rStudentStatus int = 0,
		@rUptoDate date = '',
		@rDepartmentId int=0,
	    @rOrgId int,
		@rReceiptBookId int,
		@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT @rOrgGroupBatchId = Id FROM sSetup.tOrgGroupBatchMaster WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId

IF (@rType = 1)
 BEGIN
IF(@rFilterType = 'Organizationwise')		
	BEGIN 
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		--SELECT
		--	SA.OrgId,
		--	O.Title AS OrgName,
		--	SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
		--	FHM.Id AS FeeHeadId,
		--	FHM.Title AS FeeHeadName,
		--	FHM.OrderIndex
		--FROM
		--	sStudent.vStudentAcademic SA
		--	INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		--	INNER JOIN 
		--	(
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.Id As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
 	--			FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		--		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		--		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE 
		--			BM.OrgGroupBatchId = @rOrgGroupBatchId
		--			AND (FS1.IsOptional=0)
		--			-- IsInContext
		--			AND BM.IsInContext = 1
		--		UNION ALL
		--		SELECT 
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			FM.Title AS FeeName,
		--			FM.FeeHeadId,
		--			SA1.AcademicId As AcademicId,
		--			FS1.Id,
		--			FS1.StartDate
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		--		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		--		WHERE
		--				SA1.OrgGroupBatchId = @rOrgGroupBatchId
		--				AND (FS1.IsOptional=1)
		--				-- IsInContext
		--				AND BM.IsInContext = 1
		--		) FS ON FS.AcademicId=SA.AcademicId
		--		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		--		LEFT JOIN
		--		(
		--			SELECT 
		--			    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--			FROM
		--				sFee.tReceipt R 
		--				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
		--				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
		--			WHERE		
		--				(R.SourceTypeId = 2001)
		--				AND (R.IsObsolete = 0) 
		--				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
		--				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
		--				AND (R.ReceiptDate <= @rUptoDate) 
		--				-- IsInContext
		--				AND BM.IsInContext = 1 
		--				GROUP BY FeeSetupId,R.SourceId
		--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		--		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--	WHERE
		--	  SA.OrgGroupBatchId = @rOrgGroupBatchId
		--	  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
		--	  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		--	  -- IsInContext
		--	  AND BM.IsInContext = 1
		--	GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex
		--	ORDER BY OrgId,FHM.OrderIndex

		CREATE TABLE #FeeHeadwisetmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		--ReceiptBookId int 
		)

		INSERT INTO #FeeHeadwisetmp
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #FeeHeadwisetmp FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
					AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
					AND (R.ReceiptDate <= @rUptoDate) 
					-- IsInContext
					AND BM.IsInContext = 1 
					GROUP BY FeeSetupId,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FHM.OrderIndex

		DROP TABLE #FeeHeadwisetmp
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		CREATE TABLE #FeeMasterwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			OrderIndex int
		)
	 
	 INSERT INTO #FeeMasterwisetmp
		 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
 		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #FeeMasterwisetmp FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
				SA.OrgGroupBatchId = @rOrgGroupBatchId
				AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
				AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				-- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,FS.FeeId
	 DROP TABLE #FeeMasterwisetmp
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		CREATE TABLE #CollectionGroupwisetmp
		(
			FeeId int,
			Amount decimal (12,2),
			FeeName nvarchar(100),
			FeeHeadId int,
			AcademicId bigint,
			Id int,
			StartDate date,
			CollectionGroupId int
		)
	 INSERT INTO #CollectionGroupwisetmp
	 SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
 		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			FS1.FeeId,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.CollectionGroupId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1

	 SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(O.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN #CollectionGroupwisetmp FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title,CGM.OrderIndex,O.OrderIndex
			ORDER BY O.OrderIndex,OrgId,CGM.Id

	 DROP TABLE #CollectionGroupwisetmp
	 END
	END
ELSE IF(@rFilterType = 'Departmentwise')
	BEGIN
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartFeeHeadWise') IS NOT NULL DROP TABLE #tmpDepartFeeHeadWise
		CREATE TABLE #tmpDepartFeeHeadWise
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date
		)

		Insert Into #tmpDepartFeeHeadWise
		SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
		INNER JOIN #tmpDepartFeeHeadWise FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
			SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
			FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate)
				-- IsInContext
				AND BM.IsInContext = 1  
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1 
		GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title,FHM.OrderIndex,DM.OrderIndex
		ORDER BY DM.OrderIndex,DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN

		IF OBJECT_ID('tempdb..#tmpDepartFeeMasterwise') IS NOT NULL DROP TABLE #tmpDepartFeeMasterwise
		CREATE TABLE #tmpDepartFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		OrderIndex int
		)

		Insert Into #tmpDepartFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartFeeMasterwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName,FS.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		IF OBJECT_ID('tempdb..#tmpDepartCollectionGroupwise') IS NOT NULL DROP TABLE #tmpDepartCollectionGroupwise
		CREATE TABLE #tmpDepartCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int
		)

		INSERT INTO #tmpDepartCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1


		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(DM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
				INNER JOIN #tmpDepartCollectionGroupwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title,CGM.OrderIndex,DM.OrderIndex
			ORDER BY DM.OrderIndex,DepartmentId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'ReceiptBookwise')
	BEGIN
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
		-- For Timeout issue
		CREATE TABLE #tmp
		(
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int 
		)

		INSERT INTO #tmp
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.Id As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
 		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND (FS1.IsOptional=0)
			-- IsInContext
			AND BM.IsInContext = 1
		UNION ALL
		SELECT 
			ISNULL(FS1.Amount,0)AS Amount,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			SA1.AcademicId As AcademicId,
			FS1.Id,
			FS1.StartDate,
			FS1.ReceiptBookId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
				SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND (FS1.IsOptional=1)
				-- IsInContext
				AND BM.IsInContext = 1



	 SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.tAcademic SA
			INNER JOIN [sStudent].[tStudentMaster] SM ON SA.StudentId = SM.Id 
			INNER JOIN [sSetup].[tBatchMaster] BM ON SA.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			--INNER JOIN 
			--(
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.Id As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
 			--	FROM sFee.tFeeSetup FS1
				--INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				--INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				--AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE 
				--	BM.OrgGroupBatchId = @rOrgGroupBatchId
				--	AND (FS1.IsOptional=0)
				--	-- IsInContext
				--	AND BM.IsInContext = 1
				--UNION ALL
				--SELECT 
				--	ISNULL(FS1.Amount,0)AS Amount,
				--	FM.Title AS FeeName,
				--	FM.FeeHeadId,
				--	SA1.AcademicId As AcademicId,
				--	FS1.Id,
				--	FS1.StartDate,
				--	FS1.ReceiptBookId
				--FROM sFee.tFeeSetup FS1
				--INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				--AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				--INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				--WHERE
				--		SA1.OrgGroupBatchId = @rOrgGroupBatchId
				--		AND (FS1.IsOptional=1)
				--		-- IsInContext
				--		AND BM.IsInContext = 1
				--) 
				INNER JOIN #tmp FS ON FS.AcademicId=SA.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  BM.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SM.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title,FHM.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FHM.Id

		DROP TABLE #tmp
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptFeeMasterwise') IS NOT NULL DROP TABLE #tmpReceiptFeeMasterwise
		CREATE TABLE #tmpReceiptFeeMasterwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		ReceiptBookId int,
		OrderIndex int
		)

		INSERT INTO  #tmpReceiptFeeMasterwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptFeeMasterwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate) 
						-- IsInContext
						AND BM.IsInContext = 1 
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName,FS.OrderIndex,RBM.OrderIndex
			ORDER BY RBM.OrderIndex,ReceiptBookId,FS.FeeId
	END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	BEGIN

		IF OBJECT_ID('tempdb..#tmpReceiptCollectionGroupwise') IS NOT NULL DROP TABLE #tmpReceiptCollectionGroupwise
		CREATE TABLE #tmpReceiptCollectionGroupwise
		(
		FeeId int,
		Amount decimal (12,2),
		FeeName nvarchar(100),
		FeeHeadId int,
		AcademicId bigint,
		Id int,
		StartDate date,
		CollectionGroupId int,
		ReceiptBookId int
		)

		INSERT INTO #tmpReceiptCollectionGroupwise
		SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
					-- IsInContext
					AND BM.IsInContext = 1
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
						-- IsInContext
						AND BM.IsInContext = 1

		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex,
			ISNULL(RBM.OrderIndex,0) AS TypeOrderIndex
		FROM
			sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
				INNER JOIN #tmpReceiptCollectionGroupwise FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						-- IsInContext
						AND BM.IsInContext = 1
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			  -- IsInContext
			  AND BM.IsInContext = 1
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title,CGM.OrderIndex,RBM.OrderIndex
			--ORDER BY ReceiptBookId,CGM.Id
			ORDER BY RBM.OrderIndex,CGM.OrderIndex
	END
	END 
  END
ELSE IF(@rType = 2)
		BEGIN

			IF OBJECT_ID('tempdb..#tmptbl') IS NOT NULL DROP TABLE #tmptbl
			CREATE TABLE #tmptbl
			(
				FeeId int,
				Id int,
				IsOptional bit,
				IsVariable bit,
				Amount decimal (12,2),
				StartDate date,
				EndDate date,
				BatchId int,
				ReceiptBookId int,
				AcademicId bigint,
				FeeName nvarchar(100),
				FeeHeadId int,
				CollectionGroupId int,
				FeeOrderIndex int
			)
			INSERT INTO #tmptbl 
			SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.Id AS AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
						INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
						AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE 
							BM.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=0)
							-- IsInContext
							AND BM.IsInContext = 1
						UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE
							SA1.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=1)
							-- IsInContext
							AND BM.IsInContext = 1
	
				SELECT 
					SA.OrgId,
					SA.OrganizationName as OrgName,
					SA.ClassId,
					SA.ClassName,
					SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount
				FROM 
					sStudent.vStudentAcademic SA
					INNER JOIN #tmptbl  FS ON FS.AcademicId=SA.AcademicId
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					LEFT JOIN
					(
						SELECT 
								ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
						FROM
							sFee.tReceipt R 
							INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
							INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
							INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
							INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
							 
						WHERE		
							(R.SourceTypeId = 2001)
							AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND (R.IsObsolete = 0) 
							AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
							AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
							AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016
							-- IsInContext
							AND BM.IsInContext = 1
							GROUP BY FeeSetupId,R.SourceId
					) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
					 INNER JOIN sSetup.tOrganizationMaster O ON	
					 SA.OrgId = O.Id
					 INNER JOIN sFee.tReceiptBookMaster RBM 
						ON FS.ReceiptBookId=RBM.Id
					 LEFT JOIN sFee.tCollectionGroupMaster CGM
						ON FS.CollectionGroupId=CGM.Id	
					 LEFT JOIN sStudent.tStudentCommunication SC 
						ON SC.StudentId = SA.StudentId
					 LEFT JOIN sStudent.tStudentOther SO 
						ON SO.StudentId = SA.StudentId
					 INNER JOIN sFee.tFeeHeadMaster FHM
						ON FHM.Id = FS.FeeHeadId
					INNER JOIN sSetup.tBatchMaster BM ON SA.BatchId = BM.Id	
				  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
				  LEFT JOIN
					(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
					ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
				WHERE	
				 SA.OrgGroupBatchId = @rOrgGroupBatchId
                 AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
                 AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				 AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
				 -- IsInContext
				 AND BM.IsInContext = 1
				GROUP BY 
						SA.ClassId,SA.ClassName,SA.OrgId,SA.OrganizationName
				Order By
						SA.ClassId
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pPendingFeeStopApplicationAccessAdd]
	 @rXml nvarchar(MAX)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
	
	BEGIN TRANSACTION
	
	DECLARE @StrXML XML  
    SET @StrXML = CAST(@rXml AS XML)  
   
	DECLARE @tStudentCommunication TABLE  
	(  
	Id INT IDENTITY(1, 1),  
	AcademicId BIGINT,
	Remark nvarchar(1000),  
	IsStopApplicationAccess  SMALLINT		
	)   
	print 1
    INSERT INTO @tStudentCommunication  
    SELECT           
            T.c.value('@AcademicId','bigint') AS AcademicId,  
            T.c.value('@Remark','nvarchar(1000)') AS Remark,  
            T.c.value('@IsStopApplicationAccess','smallint') AS IsStopApplicationAccess             
    FROM   
            @StrXML.nodes('/Table/FeePendingList')T(c)  

			Select * FROM @tStudentCommunication
	Declare @lCount int=1
	WHILE(@lCount <= (SELECT count(*) FROM @tStudentCommunication))                
	BEGIN
		DECLARE @lIsStopApplicationAccess SmallInt,@lRemark nvarchar(1000)
		DECLARE @lAcademicId BigInt

		SELECT @lAcademicId = AcademicId , @lRemark = Remark,@lIsStopApplicationAccess = IsStopApplicationAccess FROM @tStudentCommunication WHERE Id = @lCount

		IF(@lIsStopApplicationAccess = 1)
		BEGIN
			UPDATE sStudent.tStudentCommunication SET IsStopApplicationAccess = @lIsStopApplicationAccess ,StudentCustomAlert = @lRemark 
			WHERE StudentId = (SELECT StudentId FROM sStudent.tAcademic WHERE Id = @lAcademicId)
		END
		ELSE
		BEGIN
			UPDATE sStudent.tStudentCommunication SET IsStopApplicationAccess = @lIsStopApplicationAccess ,StudentCustomAlert = @lRemark 
			WHERE StudentId = (SELECT StudentId FROM sStudent.tAcademic WHERE Id = @lAcademicId)
		END
		SET @lCount = @lCount + 1
	END
	SELECT 1 AS RESULT
 COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pPostDatedPaymentAdd]
	@rPostDatedPaymentXML  nvarchar(MAX),
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rSourceId bigint,
	@rSourceTypeId int

AS
SET NOCOUNT ON
BEGIN
	SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT
	DECLARE @lPDCIds nvarchar(max) = ''			-- Mantis Id : 	0039559	
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rPostDatedPaymentXML
	
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		AutoId bigint identity
		,Id	bigint
		,ReceiptBookId	int
		,PayTypeId	tinyint
		,PaymentClearanceDate	date
		,ChequeNo	nvarchar(40)
		,BankName	nvarchar(200)
		,Amount	decimal
		,Remark	nvarchar(200)
	)

	INSERT INTO #tempTable
	(
		Id
		,ReceiptBookId
		,PayTypeId
		,PaymentClearanceDate
		,ChequeNo
		,BankName
		,Amount
		,Remark
	)
	SELECT	
		A.Id
		,A.ReceiptBookId
		,A.PayTypeId
		,A.PaymentClearanceDate
		,A.ChequeNo
		,A.BankName
		,A.Amount
		,A.Remark
	FROM OPENXML (@intDoc, '/Table/PostDatedPayment', 1)
	WITH
	(
		Id	bigint					 '@Id'
		,ReceiptBookId	int			 '@ReceiptBookId'
		,PayTypeId	tinyint			 '@PayTypeId'
		,PaymentClearanceDate date   '@PaymentClearanceDate'
		,ChequeNo	nvarchar(40)	 '@ChequeNo'
		,BankName	nvarchar(200)	 '@BankName'
		,Amount	decimal				 '@Amount'
		,Remark	nvarchar(200)		 '@Remark'
	)A 

	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=AutoId FROM #tempTable
	
	WHILE @lId <= @lCount 
	BEGIN
		
		DECLARE @lId1 bigint = 0
		SELECT @lId1 = Id FROM #tempTable WHERE AutoId = @lId
		
		IF(@lId1 = 0)
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tPostDatePayment', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO sFee.tPostDatePayment
			(	
				Id
				,OrgId
				,BatchId
				,OrgGroupBatchId
				,SourceTypeId
				,SourceId
				,ReceiptBookId
				,PayTypeId
				,PaymentClearanceDate
				,ChequeNo
				,BankName
				,Amount
				,Remark
				,CreatedUserId
				,CreatedDateTime
				,StatusId
			)
			SELECT 
				@lNextNumber
				,@rOrgId
				,@rBatchId
				,@rOrgGroupBatchId
				,@rSourceTypeId
				,@rSourceId
				,TT.ReceiptBookId
				,TT.PayTypeId
				,TT.PaymentClearanceDate
				,TT.ChequeNo
				,TT.BankName
				,TT.Amount
				,TT.Remark
				,@rCreatedUserId
				,sCommon.fGetDate()
				,751
			FROM 
				#tempTable TT
			WHERE TT.AutoId = @lId

			SELECT @lNextNumber = MAX(Id) FROM sFee.tPostDatePayment Where OrgId=@rOrgId
			EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sFee.tPostDatePayment', @rCurrentNumber = @lNextNumber
			SET @lPDCIds = @lPDCIds + ',' + CAST(@lNextNumber as nvarchar(20))		-- Mantis Id : 	0039559	
		END
		ELSE
		BEGIN
			DECLARE @lReceiptBookId	int = 0
			DECLARE @lPayTypeId	tinyint = 0
			DECLARE @lPaymentClearanceDate date = NULL
			DECLARE @lChequeNo nvarchar(40) = NULL
			DECLARE @lBankName nvarchar(200) = NULL
			DECLARE @lAmount	decimal = 0
			DECLARE @lRemark	nvarchar(200) = NULL
			
			SELECT @lReceiptBookId = ReceiptBookId
				,@lPayTypeId = PayTypeId
				,@lPaymentClearanceDate = PaymentClearanceDate
				,@lChequeNo = ChequeNo
				,@lBankName = BankName
				,@lAmount = Amount
				,@lRemark = Remark
			 FROM #tempTable WHERE Id = @lId1

			UPDATE sFee.tPostDatePayment
			SET 
				OrgId = @rOrgId
				,BatchId = @rBatchId
				,OrgGroupBatchId = @rOrgGroupBatchId
				,SourceTypeId = @rSourceTypeId
				,SourceId = @rSourceId
				,ReceiptBookId = @lReceiptBookId
				,PayTypeId = @lPayTypeId
				,PaymentClearanceDate = @lPaymentClearanceDate
				,ChequeNo = @lChequeNo
				,BankName = @lBankName
				,Amount = @lAmount
				,Remark = @lRemark
				,UpdatedUserId = @rCreatedUserId
				,UpdatedDateTime = sCommon.fGetDate()
			WHERE Id = @lId1
		END
		
		SET @lId=@lId+1
		
	END
	EXEC sp_xml_removedocument @intDoc
	SELECT 1 as Result, @lPDCIds AS PDCIds		-- Mantis Id : 	0039559	
	DROP Table #tempTable
	END TRY	

	BEGIN CATCH 
	SELECT -1 AS Result,error_message() AS MSG, ERROR_LINE()
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pPostDatedPaymentDelete]
	@rId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			IF EXISTS (SELECT 1 FROM sFee.tPostDatePayment PDP INNER JOIN sFee.tReceipt R ON R.Id = PDP.ReceiptId WHERE PDP.Id = @rId)
			BEGIN
				SELECT -101 AS RESULT
			END
	
			ELSE
			BEGIN
				DELETE FROM sFee.tPostDatePayment
				WHERE Id=@rId

				SELECT 1 AS Result
			END		
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sFee].[pPostDatedPaymentGet]
	@rId bigint = 0,
	@rOrgGroupBatchId int=0,
	@rOrgId int = 0,
	@rBatchId int = 0,
	@rAdmissionCategoryId int = 0,
	@rIdNo nvarchar(20) = NULL,
	@rDepartmentId int = 0,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rReceiptBookId int = 0,
	@rCollectionGroupId int = 0,
	@rPayTypeId int = 0,
	@rStatusId int = 0,
	@rFirstName nvarchar(50) = NULL,
	@rFromReceiptNumber nvarchar(50) = NULL,
	@rToReceiptNumber nvarchar(50) = NULL,
	@rChequeNo nvarchar(50) = NULL,
	@rFromPaymentClearanceDate date = NULL,
	@rToPaymentClearanceDate date = NULL,
	@rOrgGroupId int = 0,
	@rSourceId bigint =0,
	@rSourceTypeId smallint = 0,
	@rUserId bigint = 0,
	@rStatusIds nvarchar(100) = '',
	@rFromCreatedDate date = NULL, --Added for mantis : 35660 by Nilesh
	@rToCreatedDate date = NULL --Added for mantis : 35660 by Nilesh

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 		
	BEGIN
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rChequeNo = sCommon.fSearchStringGet(@rChequeNo)  
	END
	--Select @rFromCreatedDate , @rToCreatedDate
	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(R.ReceiptDate, '') AS ReceiptDate
		,ISNULL(PTM.Title, '') AS PayType
        ,ISNULL(SM.Title, '') AS StatusTitle
		,ISNULL(PDP.DepositedDate, '') AS DepositedDate
		,ISNULL(PDP.ReceiptDate, '') AS PDPReceiptDate	-- Added for mantis 0034852 by Foram
		,ISNULL(PDP.CancelDate, '') AS CancelDate		-- Mantis Id : 0036351
		,U.DisplayTitle AS PDCEntryUserName
	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.vUserReceiptBook RBM ON RBM.Id=PDP.ReceiptBookId AND RBM.UserId=@rUserId    
		--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = PDP.ReceiptBookId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = PDP.StatusId
		INNER JOIN sSecurity.tUser U ON U.Id = PDP.CreatedUserId --Added by dhananjay for mantis : 40169
		LEFT JOIN sFee.tReceipt R ON R.Id = PDP.ReceiptId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = RBM.Id
	WHERE
		(PDP.Id = @rId OR @rId = 0)
		AND (PDP.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND (PDP.OrgId = @rOrgId OR @rOrgId = 0)
		AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		AND (SA.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
		AND ((SA.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (SA.ClassId = @rClassId OR @rClassId = 0)
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
		AND (PDP.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (CGM.Id = @rCollectionGroupId OR @rCollectionGroupId = 0)
		AND (PDP.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
		AND (PDP.StatusId = @rStatusId OR @rStatusId = 0)
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND (PDP.ChequeNo like @rChequeNo OR ISNULL(@rChequeNo, '') = '')
		AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(ISNULL(@rFromReceiptNumber, 0) =0))    
		AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(ISNULL(@rToReceiptNumber,0)=0))   
		AND (PDP.PaymentClearanceDate >= @rFromPaymentClearanceDate OR ISNULL(@rFromPaymentClearanceDate, '') = '')
		AND (PDP.PaymentClearanceDate <= @rToPaymentClearanceDate OR ISNULL(@rToPaymentClearanceDate, '') = '')
		AND (PDP.SourceId = @rSourceId OR @rSourceId = 0)
		AND (PDP.SourceTypeId = @rSourceTypeId OR @rSourceTypeId = 0)
		AND (PDP.StatusId IN (SELECT item FROM sCommon.fnSplit(@rStatusIds,',')) OR ISNULL(@rStatusIds, '') = '')
		AND ((CONVERT(date,PDP.CreatedDateTime) >= @rFromCreatedDate) OR ISNULL(@rFromCreatedDate, '') = '') --Added for mantis : 35660 by Nilesh
		AND ((CONVERT(date,PDP.CreatedDateTime) <= @rToCreatedDate) OR ISNULL(@rToCreatedDate, '') = '') --Added for mantis : 35660 by Nilesh
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pPostDatedPaymentUpdate] 
	@rId BIGINT
	,@rDepositedDate DATETIME
	,@rStatusId SMALLINT
	,@rIsDepositeDate BIT	-- Added for mantis 0034852 by Foram
	,@rIsReceiptDate bit	-- Added for mantis 0034852	by Foram
	,@rReceiptDate datetime -- Added for mantis 0034852	by Foram

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION
			IF(@rIsDepositeDate = 1)
			BEGIN
				IF(@rStatusId > 0)
				BEGIN
					UPDATE sFee.tPostDatePayment
					SET DepositedDate = @rDepositedDate
					,StatusId = @rStatusId
					WHERE Id = @rId
				END
				ELSE
				BEGIN
					UPDATE sFee.tPostDatePayment
					SET DepositedDate = @rDepositedDate
					WHERE Id = @rId
				END
			END
			IF(@rIsReceiptDate = 1) -- Added for mantis 0034852 by Foram
			BEGIN
				UPDATE sFee.tPostDatePayment
				SET ReceiptDate = @rReceiptDate
				WHERE Id = @rId
			END

			SELECT 1 AS RESULT

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pProcessedFeePendingAllOldBatchGet] 
	@rOrgGroupBatchId INT = 0
	,@rBatchId INT = ''
	,@rOrgId INT = 0
	,@rCode NVARCHAR(20) = ''
	,@rUserId BIGINT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT SA.AcademicId
		,SA.RollNo
		,SA.Name
		,SA.Code
		,SA.ClassId
		,SA.DivisionId
		,SA.ClassName
		,SA.DivisionName
		,SA.ClassName + ' - ' + SA.DivisionName AS ClassDivision
		,FS.Id AS FeeSetupId
		,ISNULL(FS.IsVariable, 0) AS IsVariable
		,ISNULL(FS.Amount, 0) AS Amount
		,ISNULL(FS.StartDate, '1900-01-01') AS StartDate
		,ISNULL(FS.EndDate, '1900-01-01') AS EndDate
		,ISNULL(FA.VariableAmount, 0.00) AS FAAmount
		,ISNULL(FA.DiscountAmount, 0.00) AS DiscountAmount
		,ISNULL(FA.AdditionalAmount, 0.00) AS AdditionalAmount
		,ISNULL(FA.PaidAmount, 0) AS PaidAmount
		,ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(FA.PaidAmount, 0.00) AS PendingAmount
		,ISNULL(FA.Remark, '') AS Remark
		,FS.ReceiptBookId
		,FS.FeeName
		,FS.FeeCode
		,SA.OrgId
		,O.Title AS OrgName
		,O.OrderIndex AS OrgOrderIndex
		,ISNULL(RBM.Title, '') AS ReceiptBookTitle
		,ISNULL(RBM.OrderIndex, 0) AS ReceiptOrderIndex
		,SA.BatchId
		,BM.Title AS BatchName
		,RT.Pickup AS Pickup
		,RT.DRoppoint AS DRoppoint
		,SC.PresentContactNo
		,ISNULL(SA.SUID, '') AS SUID
		,SA.ClassOrderIndex
		,SA.DivisionOrder AS DivisionOrderIndex
		,FS.OrderIndex AS FeeOrderIndex
	INTO #TempAllPendingFeeBatch
	FROM sStudent.vStudentAcademic SA
	INNER JOIN (
		SELECT FS1.FeeId
			,FS1.Id
			,ISNULL(FS1.IsOptional, 0) AS IsOptional
			,ISNULL(FS1.IsVariable, 0) AS IsVariable
			,ISNULL(FS1.Amount, 0) AS Amount
			,ISNULL(FS1.StartDate, '1900-01-01') AS StartDate
			,ISNULL(FS1.EndDate, '1900-01-01') AS EndDate
			,FS1.BatchId
			,ISNULL(FS1.ReceiptBookId, 0) AS ReceiptBookId
			,SA1.AcademicId
			,FM.Title AS FeeName
			,FM.Code AS FeeCode
			,FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId = FS1.ClassId
			AND FS1.BatchId = SA1.BatchId
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
		WHERE ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((SA1.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND (FS1.IsOptional = 0)	
			--AND ((FS1.BatchId = @rBatchId) OR (@rBatchId = 0))
			--AND ((SA1.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((SA1.Code = @rCode) OR (@rCode = ''))
		
		UNION ALL
		
		SELECT FS1.FeeId
			,FS1.Id
			,ISNULL(FS1.IsOptional, 0) AS IsOptional
			,ISNULL(FS1.IsVariable, 0) AS IsVariable
			,ISNULL(FS1.Amount, 0) AS Amount
			,ISNULL(FS1.StartDate, '1900-01-01') AS StartDate
			,ISNULL(FS1.EndDate, '1900-01-01') AS EndDate
			,FS1.BatchId
			,ISNULL(FS1.ReceiptBookId, 0) AS ReceiptBookId
			,SA1.AcademicId
			,FM.Title AS FeeName
			,FM.Code AS FeeCode
			,FM.OrderIndex
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId = FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FO.SourceId
			AND SA1.BatchId = FS1.BatchId
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND SA1.ClassId = FS1.ClassId
		WHERE 
			((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((SA1.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND (FS1.IsOptional = 1)
			--AND ((FS1.BatchId = @rBatchId) OR (@rBatchId = 0))
			--AND ((SA1.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((SA1.Code = @rCode) OR (@rCode = ''))
			
		) FS ON FS.AcademicId = SA.AcademicId
	INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId = RBM.Id
	INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	LEFT JOIN [sStudent].[tStudentCommunication] SC ON SC.studentId = SA.studentId
	LEFT JOIN sFee.tFeeAllocationStudent FA ON FA.FeeSetupId = FS.Id AND FA.AcademicId = 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 = @rOrgId) OR (@rOrgId = 0))
	--		AND (R.IsObsolete = 0)
	--		AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	--		--AND ((R.BatchId = @rBatchId) OR (@rBatchId = 0))
	--		AND ((R.CreatedUserId = @rUserId) OR (@rUserId = 0))
	--		AND ((SA1.Code = @rCode) OR (@rCode = ''))
	--	GROUP BY FeeSetupId,R.SourceId
	--	) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	--LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SA.StudentId
	--	AND AR.SourceTypeId = 2003
	--	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	--	AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))
	LEFT JOIN (
		SELECT AT.SourceId
			,B.OrgGroupBatchId
			,B.Title AS Pickup
			,B1.Title AS DRoppoint
		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))
		LEFT JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id = AT.DropDestinationId
		LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id = BM1.BusRouteId
			AND AT.SourceTypeId = 2003
			AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		) RT ON RT.SourceId = SA.StudentId
		AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	WHERE (
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			OR (@rOrgGroupBatchId = 0)
			)
		--AND (
		--	(SA.BatchId = @rBatchId)
		--	OR (@rBatchId = 0)
		--	)
		AND (
			(SA.Code = @rCode)
			OR (@rCode = '')
			)
		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(FA.PaidAmount, 0.00) != 0)
	ORDER BY SA.RollNo

	DECLARE @lBatchOrderIdex smallint = 0
	SET @lBatchOrderIdex = (SELECT OrderIndex FROM sSetup.tBatchMaster WHERE Id = @rBatchId) 

	SELECT T.OrgId
		,T.ReceiptBookId
		,T.AcademicId
		,T.DivisionId
		,T.ClassDivision
		,T.RollNo
		,T.Name
		,T.Code
		,T.ReceiptBookTitle
		,T.OrgName
		,SUM(T.PendingAmount) AS PendingAmount
		,(SELECT STUFF((
				SELECT ', ' + FeeCode
				FROM 
				(SELECT FeeCode, FeeOrderIndex FROM 
				#TempAllPendingFeeBatch
				WHERE T.AcademicId = AcademicId 
				AND T.ReceiptBookId = ReceiptBookId
				AND T.BatchId = BatchId
				GROUP BY FeeCode, FeeOrderIndex)
				AS A
				ORDER BY FeeOrderIndex
				FOR XML PATH('')
				), 1, 1, '')) AS PendingFeeName 
		--'[sFee].[fPendingFeeNamesGet]'(AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
		,T.ReceiptOrderIndex
		,T.BatchId
		,T.BatchName
		,T.Pickup
		,T.DRoppoint
		,T.PresentContactNo
		,T.SUID
		,T.ClassOrderIndex
		,T.DivisionOrderIndex
		,BM.OrderIndex AS BatchOrderIndex
	FROM #TempAllPendingFeeBatch T
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = T.BatchId 
	WHERE BM.OrderIndex < @lBatchOrderIdex
	GROUP BY T.OrgId
			,T.AcademicId
			,T.ReceiptBookId
			,T.DivisionId
			,T.BatchId
			,T.ClassDivision
			,T.RollNo
			,T.Name
			,T.Code
			,T.ReceiptBookTitle
			,T.OrgName
			,T.ReceiptOrderIndex
			,T.BatchName
			,T.Pickup
			,T.DRoppoint
			,T.PresentContactNo
			,T.SUID
			,T.ClassOrderIndex
			,T.DivisionOrderIndex
			,BM.OrderIndex
	
	ORDER BY AcademicId DESC 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pReceiptAdd]	
	@rId bigint,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rReceiptNumber int,
	@rReceiptDate date,
	@rReceiptAmount decimal(12,2),
	@rTotalReceiptAmount decimal(12,2),
	@rDiscountAmount decimal(12,2),
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(40),
	@rBankName nvarchar(200),
	@rReceiptBookId int,
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rRemark nvarchar(200),
	@rReceiptDetailXml [nvarchar](max),
	@rChequeDate date,
	@rCharge decimal(12,2)=0,
	@rFeeInvoiceId bigint = NULL,
	@rCollectionGroupId int = 0,
	@rDepositedLedgerId int = 0,
	@rPaymentTransactionId bigint = 0,
	@rReceiptPrintGroupId nvarchar(100),
	@rIsDiscountCoupon bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
DECLARE @lIsCreated INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

DECLARE @lIsEnableLog bit = 0 -- Set to 1 If want to add log for receipt add process

BEGIN
	BEGIN TRY
		
		IF(@lIsEnableLog = 1)
		BEGIN
		 INSERT INTO [sFee].[tFeeReceiptLog]
		 VALUES (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			    ,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			    ,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			    ,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt SP Main Process Start')
		END

		SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId

		DECLARE @lConfigValue nvarchar(50)=''
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 339 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

		IF @lConfigValue = '' 
		    SET @lConfigValue = 'ReceiptBookWise'

		IF @rChequeDate = '1900-01-01'
			SET @rChequeDate = NULL

		-- Mantis - 0030695
		 DECLARE @lConfigValue1 nvarchar(50)=''
		 SELECT @lConfigValue1 = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 543 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)
		-- Mantis - 0030695	 

		IF(@rReceiptNumber <> 0)
		BEGIN
			IF(@rId = 0)--ID Condition Added by dhruv for issue no.0013266	
			BEGIN
				IF(@lConfigValue='ReceiptBookWise')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				ELSE IF(@lConfigValue='PayTypeWise')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #Start Mantis Id : 0036287
				ELSE IF(@lConfigValue='Continuous Batch')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #End Mantis Id : 0036287

				-- Mantis - 0030695
				IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ChequeNo=@rChequeNo)
					BEGIN
						SELECT -103 AS Result
						RETURN	
					END
				END
				-- Mantis - 0030695

				-- For Mantis 0038951, By Foram
				IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @rBatchId AND OrgGroupBatchId = @rOrgGroupBatchId 
														AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND ReceiptBookId = @rReceiptBookId 
														AND PayTypeId = @rPayTypeId AND ChequeNo = @rChequeNo AND BankName = @rBankName AND Amount = @rTotalReceiptAmount AND ReceiptId > 0)
				BEGIN
					SELECT -104 AS Result
					RETURN	
				END
				-- For Mantis 0038951, By Foram
			END
			ELSE
			BEGIN
				IF(@lConfigValue='ReceiptBookWise')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				ELSE IF(@lConfigValue='PayTypeWise')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #Start Mantis Id : 0036287
				ELSE IF(@lConfigValue='Continuous Batch')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND Id != @rId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #End Mantis Id : 0036287

				-- Mantis - 0030695
				IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ChequeNo=@rChequeNo AND Id != @rId)
					BEGIN
						SELECT -103 AS Result
						RETURN	
					END
				END
				-- Mantis - 0030695
			END 
		END
		ELSE
		BEGIN
			SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
		END	

		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			 VALUES
			 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt No Generated and pReceiptAddValidate SP Start')
		END

		EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rPayTypeId,@rPaymentTransactionId,@rReceiptBookId,@rChequeNo,@rIsCreated = @lIsCreated OUTPUT 
		-- Added ,@rPayTypeId,@rPaymentTransactionId for mantis 0031290 By Foram	-- Added @rChequeNo for mantis 0035484 By Foram

		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			 VALUES
			 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pReceiptAddValidate SP End : ' + CAST(@lIsCreated AS NVARCHAR(10)))
		END

		IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
		IF(@lIsCreated = -1)	-- For Mantis 0032370 by Foram
 		BEGIN
			SELECT -502 AS Result
			RETURN
		END
		IF(@lIsCreated = -2)	-- For Mantis 0035484 by Foram
 		BEGIN
			SELECT -503 AS Result
			RETURN
		END
	END TRY
	BEGIN CATCH 
		SELECT -1 AS Result, ERROR_Message()
	END CATCH	

	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		
		--Added By Dhruv
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		--Added By Dhruv

		-- #Start Mantis Id : 0036287
			ELSE IF(@lConfigValue='Continuous Batch')
			BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
			-- #End Mantis Id : 0036287

		-- Mantis - 0030695
		IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ChequeNo=@rChequeNo)
			BEGIN
				SELECT -103 AS Result
				RETURN	
			END
		END
		-- Mantis - 0030695

		-- For Mantis 0038951, By Foram
		IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @rBatchId AND OrgGroupBatchId = @rOrgGroupBatchId 
												AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND ReceiptBookId = @rReceiptBookId 
												AND PayTypeId = @rPayTypeId AND ChequeNo = @rChequeNo AND BankName = @rBankName AND Amount = @rTotalReceiptAmount AND ReceiptId > 0)
		BEGIN
			SELECT -104 AS Result
			RETURN	
		END
		-- For Mantis 0038951, By Foram

		Declare @lSourceTypeId int 
		SET @lSourceTypeId =(select ISNULL(SourceTypeId,0) from sSecurity.tUser WITH (NOLOCK) where Id = @rCreatedUserId)

		DECLARE @lCreatedUserId bigint
		IF(@lSourceTypeId = 2001 OR @lSourceTypeId = 2003 OR @rCreatedUserId = 3)
			SET @lCreatedUserId=(Select [sCommon].[fGetBigIntIdForOrg](4,LEFT(@rOrgGroupBatchId,4)))
		ELSE
			SET @lCreatedUserId = @rCreatedUserId 

		

		BEGIN TRANSACTION

		DECLARE @lNextNumber BIGINT  , @lMaxReceiptId bigint = 0  
		--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
		SELECT @lMaxReceiptId = ISNULL(MAX(R.Id), 0) FROM sFee.tReceipt R WITH (NOLOCK) INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK)  ON BM.id = R.BatchId WHERE Bm.OrgId = @rOrgId

		IF EXISTS(SELECT 1 FROM sAudit.tReceiptDelete RD WITH (NOLOCK) INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK)  ON BM.Id = RD.BatchId WHERE BM.OrgId = @rOrgId AND RD.Id > @lMaxReceiptId)
		BEGIN
			SELECT @lMaxReceiptId = ISNULL(MAX(RD.Id), 0) FROM sAudit.tReceiptDelete RD WITH (NOLOCK) INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK)  ON BM.Id = RD.BatchId WHERE Bm.OrgId = @rOrgId
		END

		IF(@lMaxReceiptId = 0)
		BEGIN
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
					,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
					,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
					,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pTableRowIdGet SP Start')
			END

			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output

			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				 VALUES
				 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
					,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
					,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
					,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),CAST(@lNextNumber AS NVARCHAR(100))+'-pTableRowIdGet SP End & Receipt Add Start')
			END
		END
		ELSE
		BEGIN
			SET @lNextNumber =  @lMaxReceiptId + 1 
		END
		
	
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			 VALUES
			 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),CAST(@lNextNumber AS NVARCHAR(100))+'- ReceiptId - Receipt Add Start')
		END

		INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   DepositedLedgerId,
		   PaymentTransactionId,
		   ReceiptPrintGroupId,
		   IsDiscountCoupon  ---Added By Dhruv for Issue . 0011150
		   --Added for default value
		    ,IsChequeCleared
			,ChequeClearDate
			,AmountAfterDiscount
			,CGSTPercentage
			,SGSTPercentage
			,CGSTAmount
			,SGSTAmount
			,CancelStatusId
			,CancelStatusRemark
			,FirmReceiptBookId
			,TaxPercentage
			,CancelDateTime
        )
		VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @lCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @rDepositedLedgerId,
		    @rPaymentTransactionId,
			@rReceiptPrintGroupId,
			@rIsDiscountCoupon
			,0,NULL,0,0,0,0,0,0,NULL,0,0,NULL
		)
		
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt Add End and Receipt Detail Start') 
		END

		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		 IF(@lIsEnableLog = 1)
		         BEGIN
		         	INSERT INTO [sFee].[tFeeReceiptLog]
		         	VALUES
		         	(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		         	,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		         	,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		         	,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt Detail End') 
		         END

		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
	    IF (@rCharge > 0)
		BEGIN
		    IF(@lIsEnableLog = 1)
		    BEGIN
		    	INSERT INTO [sFee].[tFeeReceiptLog]
		    	VALUES
		    	(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		    	,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		    	,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		    	,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Charge Add Start') 
		    END
			
			EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@lCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
			
			IF(@lIsEnableLog = 1)
		    BEGIN
		    	INSERT INTO [sFee].[tFeeReceiptLog]
		    	VALUES
		    	(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		    	,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		    	,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		    	,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Charge Add End') 
		    END
		END
			
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) 
		FROM sFee.tReceiptBookMaster WITH (NOLOCK) where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pReceiptServiceTaxAdd SP Add Start')
			END

			EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@lCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
			
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pReceiptServiceTaxAdd SP Add End')
			END
		END

	    IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pFeeProcessGeneratePaidFeeAdd SP Start')
		END
		
		EXEC [sFee].[pFeeProcessGeneratePaidFeeAdd] @rOrgId,@rBatchId,@rSourceId,@lNextNumber,@lCreatedUserId
		
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pFeeProcessGeneratePaidFeeAdd SP End')
		END
			
		SET @rId = @lNextNumber

		-- For Mantis 0023321 By Foram on 14/03/2024 START
		DECLARE @lSourceId bigint, @lSourceTypeId1 smallint, @lBatchId int, @lOrgGroupBatchId int, @lReceiptBookId int, 
				@lPayTypeId smallint, @lChequeNo nvarchar(40), @lBankName nvarchar(200), @lTotalReceiptAmount decimal(12,2)

		SELECT
			@lSourceId = SourceId, 
			@lSourceTypeId1 = SourceTypeId, 
			@lBatchId = BatchId, 
			@lOrgGroupBatchId = OrgGroupBatchId, 
			@lReceiptBookId = ReceiptBookId, 
			@lPayTypeId = PayTypeId, 
			@lChequeNo = ChequeNo, 
			@lBankName = BankName, 
			@lTotalReceiptAmount = TotalReceiptAmount
		FROM sFee.tReceipt WHERE Id = @rId

		IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
														AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
														AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount)
		BEGIN
			UPDATE sFee.tPostDatePayment 
			SET ReceiptId = @rId, ReceiptDate = @rReceiptDate, StatusId = 752 
			WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
				AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
				AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount
		END
		ELSE
		BEGIN
			UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END WHERE ReceiptId = @rId
		END
		-- For Mantis 0023321 By Foram on 14/03/2024 END

		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'PDC Entry Done')
		END

		COMMIT TRANSACTION
	END 
	ELSE
	BEGIN
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Fee Receipt Update Start')
		END

		IF EXISTS(SELECT 1 FROM sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND Id = @rId)
		BEGIN
			BEGIN TRANSACTION
				UPDATE sFee.tReceipt SET
					ReceiptDate=@rReceiptDate,
					PayTypeId=@rPayTypeId,
					ChequeDate=@rChequeDate,
					ChequeNo=@rChequeNo,
					BankName=@rBankName,
					Remark=@rRemark
				WHERE Id=@rId

				-- For Mantis 0023321 By Foram on 14/03/2024 START
				DECLARE @lSourceId_1 bigint, @lSourceTypeId1_1 smallint, @lBatchId_1 int, @lOrgGroupBatchId_1 int, @lReceiptBookId_1 int, 
						@lPayTypeId_1 smallint, @lChequeNo_1 nvarchar(40), @lBankName_1 nvarchar(200), @lTotalReceiptAmount_1 decimal(12,2)

				SELECT
					@lSourceId_1 = SourceId, 
					@lSourceTypeId1_1 = SourceTypeId, 
					@lBatchId_1 = BatchId, 
					@lOrgGroupBatchId_1 = OrgGroupBatchId, 
					@lReceiptBookId_1 = ReceiptBookId, 
					@lPayTypeId_1 = PayTypeId, 
					@lChequeNo_1 = ChequeNo, 
					@lBankName_1 = BankName, 
					@lTotalReceiptAmount_1 = TotalReceiptAmount
				FROM sFee.tReceipt WHERE Id = @rId

				IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @lBatchId_1 AND OrgGroupBatchId = @lOrgGroupBatchId_1
																AND SourceTypeId = @lSourceTypeId1_1 AND SourceId = @lSourceId_1 AND ReceiptBookId = @lReceiptBookId_1 
																AND PayTypeId = @lPayTypeId_1 AND ChequeNo = @lChequeNo_1 AND BankName = @lBankName_1 AND Amount = @lTotalReceiptAmount_1)
				BEGIN
					UPDATE sFee.tPostDatePayment 
					SET ReceiptId = @rId, ReceiptDate = @rReceiptDate, StatusId = 752 
					WHERE BatchId = @lBatchId_1 AND OrgGroupBatchId = @lOrgGroupBatchId_1 
						AND SourceTypeId = @lSourceTypeId1_1 AND SourceId = @lSourceId_1 AND ReceiptBookId = @lReceiptBookId_1 
						AND PayTypeId = @lPayTypeId_1 AND ChequeNo = @lChequeNo_1 AND BankName = @lBankName_1 AND Amount = @lTotalReceiptAmount_1
				END
				ELSE
				BEGIN
					UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END WHERE ReceiptId = @rId
				END
				-- For Mantis 0023321 By Foram on 14/03/2024 END
								
			COMMIT TRANSACTION
		
			SELECT @rId AS RESULT
		END
		ELSE
		IF(@rReceiptNumber <> 0)
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END

		-- #Start Mantis Id : 0036287
			ELSE IF(@lConfigValue='Continuous Batch')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			-- #End Mantis Id : 0036287

		-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ChequeNo=@rChequeNo AND Id != @rId)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695

			BEGIN TRANSACTION

				UPDATE sFee.tReceipt SET
					ReceiptNumber = @rReceiptNumber,
					ReceiptDate=@rReceiptDate,
					PayTypeId=@rPayTypeId,
					ChequeDate=@rChequeDate,
					ChequeNo=@rChequeNo,
					BankName=@rBankName,
					Remark=@rRemark
				WHERE Id=@rId
		
				-- For Mantis 0023321 By Foram on 14/03/2024 START
				DECLARE @lSourceId_2 bigint, @lSourceTypeId1_2 smallint, @lBatchId_2 int, @lOrgGroupBatchId_2 int, @lReceiptBookId_2 int, 
						@lPayTypeId_2 smallint, @lChequeNo_2 nvarchar(40), @lBankName_2 nvarchar(200), @lTotalReceiptAmount_2 decimal(12,2)

				SELECT
					@lSourceId_2 = SourceId, 
					@lSourceTypeId1_2 = SourceTypeId, 
					@lBatchId_2 = BatchId, 
					@lOrgGroupBatchId_2 = OrgGroupBatchId, 
					@lReceiptBookId_2 = ReceiptBookId, 
					@lPayTypeId_2 = PayTypeId, 
					@lChequeNo_2 = ChequeNo, 
					@lBankName_2 = BankName, 
					@lTotalReceiptAmount_2 = TotalReceiptAmount
				FROM sFee.tReceipt WHERE Id = @rId

				IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @lBatchId_2 AND OrgGroupBatchId = @lOrgGroupBatchId_2
																AND SourceTypeId = @lSourceTypeId1_2 AND SourceId = @lSourceId_2 AND ReceiptBookId = @lReceiptBookId_2 
																AND PayTypeId = @lPayTypeId_2 AND ChequeNo = @lChequeNo_2 AND BankName = @lBankName_2 AND Amount = @lTotalReceiptAmount_2)
				BEGIN
					UPDATE sFee.tPostDatePayment 
					SET ReceiptId = @rId, ReceiptDate = @rReceiptDate, StatusId = 752 
					WHERE BatchId = @lBatchId_2 AND OrgGroupBatchId = @lOrgGroupBatchId_2
						AND SourceTypeId = @lSourceTypeId1_2 AND SourceId = @lSourceId_2 AND ReceiptBookId = @lReceiptBookId_2 
						AND PayTypeId = @lPayTypeId_2 AND ChequeNo = @lChequeNo_2 AND BankName = @lBankName_2 AND Amount = @lTotalReceiptAmount_2
				END
				ELSE
				BEGIN
					UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END WHERE ReceiptId = @rId
				END
				-- For Mantis 0023321 By Foram on 14/03/2024 END
								
				SELECT @rId AS RESULT
			COMMIT TRANSACTION 
		END
	
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Fee Receipt Update End')
			END
		END
	
	IF(@lIsEnableLog = 1)
	BEGIN
		INSERT INTO [sFee].[tFeeReceiptLog]
		VALUES
		(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt SP Main Process End')
	END
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),Error_Message())
			SELECT -1 AS Result, ERROR_Message()
		END
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pReceiptAddValidate] 
	@rAcademicId BIGINT
	,@rFeeSetupIds NVARCHAR(max) = ''
	,@rReceiptDetailXml [nvarchar] (max)
	,@rPayTypeId TINYINT = 0
	,@rPaymentTransactionId BIGINT = 0
	,@rReceiptBookId INT = 0
	,@rChequeNo nvarchar(40) = '' -- Added for mantis 0035484 by Foram
	,@rIsCreated INT OUTPUT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loDoc INT

	DECLARE @lWrongFeeSetupOrReceiptBook int = 0, @lAlreadyPaid int = 0, @lDuplicateReceipt int = 0

	EXEC sp_xml_preparedocument @loDoc OUTPUT,@rReceiptDetailXml

	CREATE TABLE #temptable (
		FeeId INT
		,Id INT
		,Amount DECIMAL(12, 2)
		,ReceiptBookId INT
		,AcademicId BIGINT
		)

	INSERT INTO #temptable (
		FeeId
		,Id
		,Amount
		,ReceiptBookId
		,AcademicId
		)
	SELECT FS1.FeeId
		,FS1.Id
		,
		--ISNULL(FS1.IsOptional,0)AS IsOptional,
		--ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount, 0) AS Amount
		,
		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	--FM.Title AS FeeName			 
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
	INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId = FS1.ClassId
		AND FS1.BatchId = SA1.BatchId
	INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS1.FeeId
	INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FM.FeeHeadId = FHM.Id
	WHERE (FS1.IsOptional = 0)
		AND SA1.Id = @rAcademicId
		AND (ISNULL(FS1.Id, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rFeeSetupIds, ',')) OR @rFeeSetupIds = '')
	
	UNION ALL
	
	SELECT FS1.FeeId
		,FS1.Id
		,
		--ISNULL(FS1.IsOptional,0)AS IsOptional,
		--ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount, 0) AS Amount
		,
		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	--FM.Title AS FeeName				
	FROM sFee.tFeeSetup FS1 WITH (NOLOCK)
	INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId = FS1.Id
	INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS1.FeeId
	INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FM.FeeHeadId = FHM.Id
	INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id = FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	WHERE (FS1.IsOptional = 1)
		AND SA1.Id = @rAcademicId
		AND (ISNULL(FS1.Id, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rFeeSetupIds, ',')) OR @rFeeSetupIds = '')

	CREATE TABLE #temptable1 (
		PaidAmount DECIMAL(12, 2)
		,FeeSetupId INT
		,SourceId BIGINT
		)

	INSERT INTO #temptable1 (
		PaidAmount
		,FeeSetupId
		,SourceId
		)
	SELECT ISNULL(SUM(RD.Amount), 0) AS PaidAmount
		,RD.FeeSetupId
		,R.SourceId
	FROM sFee.tReceipt R WITH (NOLOCK)
	INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id AND R.SourceTypeId = 2001
	INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
	INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id = R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId
	WHERE (R.SourceTypeId = 2001)
		AND R.SourceId = @rAcademicId
		AND (R.IsObsolete = 0)
		AND (ISNULL(FS.Id, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rFeeSetupIds, ',')) OR @rFeeSetupIds = '')
	GROUP BY FeeSetupId,R.SourceId

	-- For Mantis 0032370,0038190 by Foram Start
	IF (@rAcademicId > 0)
	BEGIN
		--changes for Mantis ID:0041386 by Hemali
		IF NOT EXISTS (
				SELECT 1
				FROM #temptable FS
				INNER JOIN (
					SELECT FeeSetupId
						,Amount
						,@rReceiptBookId AS ReceiptBookId
					FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
							FeeSetupId INT
							,Amount DECIMAL(12, 2)
							)
					) AS RD ON RD.FeeSetupId = FS.Id 
				)
		BEGIN
			SELECT @lWrongFeeSetupOrReceiptBook = 1
		END
		--changes for Mantis ID:0041386 by Hemali
		ELSE
		BEGIN
			IF EXISTS (
					SELECT 1
					FROM #temptable FS
					INNER JOIN (
						SELECT FeeSetupId
							,Amount
							,@rReceiptBookId AS ReceiptBookId
						FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
								FeeSetupId INT
								,Amount DECIMAL(12, 2)
								)
						) AS RD ON RD.FeeSetupId = FS.Id AND RD.ReceiptBookId <> FS.ReceiptBookId
					)
			BEGIN
				SELECT @lWrongFeeSetupOrReceiptBook = 1
			END
		END
	END -- For Mantis 0032370,0038190 by Foram End
	
	
	IF EXISTS (
			SELECT 1
			FROM sStudent.tAcademic SA WITH (NOLOCK)
			INNER JOIN #temptable
				--(
				--SELECT 
				--		FS1.FeeId,
				--		FS1.Id,
				--		--ISNULL(FS1.IsOptional,0)AS IsOptional,
				--		--ISNULL(FS1.IsVariable,0)AS IsVariable,
				--		ISNULL(FS1.Amount,0) AS Amount,
				--		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				--		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				--		--FS1.BatchId,
				--		--ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				--		SA1.Id AS AcademicId
				--		--FM.Title AS FeeName			 
				--	FROM sFee.tFeeSetup FS1
				--	INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				--	--INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
				--	AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
				--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--	--INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
				--	WHERE 
				--	    (FS1.IsOptional=0)
				--	    AND SA1.Id = @rAcademicId				
				--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				--		UNION ALL
				--	SELECT 
				--		FS1.FeeId,
				--		FS1.Id,
				--		--ISNULL(FS1.IsOptional,0)AS IsOptional,
				--		--ISNULL(FS1.IsVariable,0)AS IsVariable,
				--		ISNULL(FS1.Amount,0)AS Amount,
				--		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				--		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				--		--FS1.BatchId,
				--		--ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				--		SA1.Id AS AcademicId
				--		--FM.Title AS FeeName				
				--	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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
				--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId 
				--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				--WHERE
				--		  (FS1.IsOptional=1)
				--		   AND SA1.Id = @rAcademicId	
				--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='') 
				--)
				FS ON FS.AcademicId = SA.Id
			LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) ON FA.FeeSetupId = FS.Id AND FA.SourceId = SA.Id
			LEFT JOIN #temptable1
				--(
				--	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 AND R.SourceTypeId = 2001
				--		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
				--	WHERE	
				--	(R.SourceTypeId = 2001)
				--		 AND R.SourceId = @rAcademicId				
				--		AND (R.IsObsolete = 0) 
				--		AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				--		GROUP BY FeeSetupId,R.SourceId	
				--)
				R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
			LEFT JOIN (
				SELECT FeeSetupId
					,Amount
				FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
						FeeSetupId INT
						,Amount DECIMAL(12, 2)
						)
				) AS RD ON RD.FeeSetupId = FS.Id
			WHERE SA.Id = @rAcademicId
				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) - RD.Amount < 0)
			)
	BEGIN
		SELECT @lAlreadyPaid = 1
	END
	
	--Start for mantis 0031290 By Foram
	IF (@rPayTypeId = 8 AND (@rPaymentTransactionId > 0 OR LEN(@rChequeNo) > 0)) -- Added @rChequeNo for mantis 0035484 by Foram
	BEGIN
		IF EXISTS (
				SELECT 1
				FROM sFee.tReceipt R WITH (NOLOCK)
				INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id
					AND R.SourceTypeId = 2001
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
				INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id = R.SourceId
					AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId
				WHERE (R.SourceTypeId = 2001)
					AND R.SourceId = @rAcademicId
					AND (R.IsObsolete = 0)
					AND (
						ISNULL(FS.Id, 0) IN (
							SELECT cast(item AS INT)
							FROM sCommon.fnsplit(@rFeeSetupIds, ',')
							)
						OR @rFeeSetupIds = ''
						)
					--AND (R.PaymentTransactionId = @rPaymentTransactionId OR R.ChequeNo = @rChequeNo) -- Added @rChequeNo for mantis 0035484 by Foram
					AND ((
						ISNULL(R.PaymentTransactionId, 0) > 0 AND 
						(ISNULL(R.PaymentTransactionId, 0) = @rPaymentTransactionId OR 
							R.PaymentTransactionId = CASE WHEN ISNUMERIC(@rChequeNo) = 1 THEN CAST(@rChequeNo AS BIGINT) ELSE 0 END)
						) 
						OR 
						(
						ISNULL(R.ChequeNo, '') <> '' AND 
						(ISNULL(R.ChequeNo, '') = @rChequeNo OR R.ChequeNo = CAST(@rPaymentTransactionId AS NVARCHAR(20)))
						) 
					) -- Changes For Mantis Id: 0037034 by Hemali
					AND R.PayTypeId = 8
				)
		BEGIN
			SELECT @lDuplicateReceipt = 1
		END
	END
	--end for mantis 0031290 By Foram
	
	--@lWrongFeeSetupOrReceiptBook			-1
	--@lAlreadyPaid,@lDuplicateReceipt		1

	IF(@lWrongFeeSetupOrReceiptBook = 1)
	BEGIN
		SELECT @rIsCreated = -1
	END
	ELSE IF(@lAlreadyPaid = 1)
	BEGIN
		SELECT @rIsCreated = 1
	END
	ELSE IF(@lDuplicateReceipt = 1)
	BEGIN
		SELECT @rIsCreated = -2
	END
	ELSE
	BEGIN
		SELECT @rIsCreated = 0	
	END

	EXEC sp_xml_removedocument @loDoc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/* 
Mantis Id : 0031923	
TaxTypeId :
	Inclusive = 1
	Exclusive = 2
*/
 
 
CREATE OR ALTER PROCEDURE [sFee].[pReceiptBookMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFullTitle nvarchar(200)
           ,@rAddress1 nvarchar(200)
           ,@rAddress2 nvarchar(200)
           ,@rBankAccountNumber nvarchar(50)
           ,@rIsObsolete bit
           ,@rRemark1 nvarchar(500)
           ,@rRemark2 nvarchar(500)
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rIsOnPrePrinted bit
           ,@rReportId int
           ,@rIsSupressLogo bit
           ,@rOrderIndex int
           ,@rIsDisplaySchoolName bit
           ,@rIsMonthDetailOnly bit
           ,@rIsServiceTaxApplicable bit
           ,@rServiceTaxPercentage decimal(6,2)
           ,@rBankName nvarchar(150)=''
           ,@rIsFeeInvoiceHeadwise bit = 0
           ,@rGroupTitle nvarchar(200)=''
           ,@rIsSuppressFeeDetail bit=0
		   ,@rReceiptLogo varbinary(max)=NULL
		   ,@rHeaderDisplayId tinyint
		   ,@rReceiptBookHeader varbinary(max)=NULL
		   ,@rFeeInvoiceHeaderDisplayId tinyint
		   ,@rFeeInvoiceHeader varbinary(max)=NULL
		   ,@rCGSTPercentage decimal(5,2) = 0 
		   ,@rSGSTPercentage decimal(5,2) = 0
		   ,@rIsDisplayPendingFeeAmount bit = 0
		   ,@rDigitalSignature varbinary(max)=NULL
		   ,@rTaxLabel	nvarchar(50) = ''		-- Mantis Id : 0031923	
		   ,@rTaxTypeId tinyint = 0				-- Mantis Id : 0031923	
		   
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
If Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId) 
BEGIN
	If NOT Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id=@rId)
	BEGIN
		select -101 as Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete      
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo   
             ,OrderIndex=@rOrderIndex
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
			 ,ReceiptBookHeader=@rReceiptBookHeader
			 ,HeaderDisplayId=@rHeaderDisplayId
			 ,FeeInvoiceHeader=@rFeeInvoiceHeader
			 ,FeeInvoiceHeaderDisplayId=@rFeeInvoiceHeaderDisplayId
			 ,CGSTPercentage=@rCGSTPercentage
			 ,SGSTPercentage=@rSGSTPercentage
			 ,IsDisplayPendingFeeAmount=@rIsDisplayPendingFeeAmount
			 ,DigitalSignature=@rDigitalSignature
			 ,TaxLabel = @rTaxLabel
			 ,TaxTypeId = @rTaxTypeId
             
	      WHERE Id = @rId 	 
	      SELECT @lNextNumber AS Result
	 END  
END
ELSE
BEGIN
IF(@rId = 0)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tReceiptBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tReceiptBookMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[FullTitle]
			   ,[Address1] 
			   ,[Address2] 
			   ,[BankAccountNumber] 
			   ,[IsObsolete]
			   ,[Remark1] 
			   ,[Remark2] 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,IsOnPrePrinted
			   ,ReportId
			   ,IsSupressLogo
			   ,OrderIndex
			   ,IsDisplaySchoolName
			   ,IsMonthDetailOnly
			   ,IsServiceTaxApplicable
			   ,ServiceTaxPercentage
			   ,BankName
			   ,IsFeeInvoiceHeadwise
			   ,GroupTitle
			   ,IsSuppressFeeDetail
			   ,ReceiptLogo
			   ,HeaderDisplayId
			   ,ReceiptBookHeader
			   ,FeeInvoiceHeader
			   ,FeeInvoiceHeaderDisplayId
			   ,CGSTPercentage
			   ,SGSTPercentage
			   ,IsDisplayPendingFeeAmount
			   ,DigitalSignature
			   ,TaxLabel
			   ,TaxTypeId
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   ,@rIsMonthDetailOnly
			   ,@rIsServiceTaxApplicable
			   ,@rServiceTaxPercentage
			   ,@rBankName
			   ,@rIsFeeInvoiceHeadwise
			   ,@rGroupTitle
			   ,@rIsSuppressFeeDetail
			   ,@rReceiptLogo
			   ,@rHeaderDisplayId
			   ,@rReceiptBookHeader
			   ,@rFeeInvoiceHeader
			   ,@rFeeInvoiceHeaderDisplayId
			   ,@rCGSTPercentage
			   ,@rSGSTPercentage
			   ,@rIsDisplayPendingFeeAmount
			   ,@rDigitalSignature
			   ,@rTaxLabel
			   ,@rTaxTypeId
			   )
			   
 
INSERT INTO sSecurity.tUserAccess
           (
            SourceTypeId
            ,SourceId
           ,[UserId]
           
           )
SELECT 
		   2013
		   ,@lNextNumber
		  ,@rCreatedUserId
			   
			   
		    SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete          
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2                     
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()   
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo
             ,OrderIndex=@rOrderIndex              
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
			 ,HeaderDisplayId=@rHeaderDisplayId
			 ,ReceiptBookHeader=@rReceiptBookHeader
              ,FeeInvoiceHeaderDisplayId=@rFeeInvoiceHeaderDisplayId
			 ,FeeInvoiceHeader=@rFeeInvoiceHeader
			 ,CGSTPercentage=@rCGSTPercentage
			 ,SGSTPercentage=@rSGSTPercentage
			 ,IsDisplayPendingFeeAmount=@rIsDisplayPendingFeeAmount
			 ,DigitalSignature=@rDigitalSignature
			 ,TaxLabel=@rTaxLabel
			 ,TaxTypeId=@rTaxTypeId
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  
		
	
	END
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGRoupId=@rOrgGroupId)
	BEGIN
	Insert into sSystem.tPortalSync
	(
		OrgGroupId,
		FeeChange
	)
	Values
	(
		@rOrgGroupId,
		1
	)
	 
	END
	
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	END
	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pReceiptBookMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int,
           @rIsWildCardSearch bit
 
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT RBM.Id 
	  ,RBM.Code
      ,RBM.Title
      ,RBM.FullTitle
      ,RBM.Address1
      ,RBM.Address2
      ,RBM.BankAccountNumber
      ,RBM.IsObsolete
      ,RBM.Remark1
      ,RBM.Remark2
      ,ISNULL(RBM.IsOnPrePrinted ,0) AS IsOnPrePrinted
      ,ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo
      ,RBM.ReportId  
       --,RBM.OrderIndex  
      ,ISNULL(RBM.OrderIndex,0) AS OrderIndex
      ,ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName
      ,ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly
      ,ISNULL(RBM.IsServiceTaxApplicable,0) AS IsServiceTaxApplicable
	  ,ISNULL(RBM.ServiceTaxPercentage,0) AS ServiceTaxPercentage
	  ,ISNULL(RBM.BankName,'') AS BankName
	  ,ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise
	  ,ISNULL(RBM.GroupTitle,'') AS GroupTitle
	  ,ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail
	  ,RBM.ReceiptLogo
	  ,ISNULL(RBM.HeaderDisplayId,1) AS HeaderDisplayId
	  ,RBM.ReceiptBookHeader
	  ,ISNULL(RBM.FeeInvoiceHeaderDisplayId,1) AS FeeInvoiceHeaderDisplayId
	  ,RBM.FeeInvoiceHeader
	  ,ISNULL(RBM.CGSTPercentage,0) AS CGSTPercentage
	  ,ISNULL(RBM.SGSTPercentage,0) AS SGSTPercentage
	  ,ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount
      ,ISNULL(R.Title,'') AS ReportName
	  ,ISNULL(HDM.Title,'') AS ReceiptHeader
	  ,RBM.DigitalSignature
	  ,ISNULL(RBM.TaxLabel,'') AS TaxLabel		-- Mantis Id : 0031923	
	  ,ISNULL(RBM.TaxTypeId,0) AS TaxTypeId		-- Mantis Id : 0031923	
     
  FROM [sFee].[tReceiptBookMaster] RBM 
	INNER JOIN [sCommon].[tReport] R ON RBM.ReportId = R.Id
	LEFT JOIN [sCommon].[tHeaderDisplayMaster] HDM ON RBM.HeaderDisplayid = HDM.Id       
  
  WHERE 
		 RBM.Id = @rId OR @rId = 0
	AND ((RBM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((RBM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND  RBM.OrgGroupId = @rOrgGroupId 
	--AND  QM.IsObsolete = 0
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pReceiptBookOnlinePaymentGet]
          
           @rOrgGroupId int,
           @rStudentId bigint,
           @rBatchId int
AS
SET NOCOUNT ON
BEGIN

	

	DECLARE @lClassId int
	DECLARE @lAdmissionCategoryId int
	DECLARE @lBatchId int
	
	SELECT 
		@lClassId=A.ClassId,
		@lAdmissionCategoryId=A.AdmissionCategoryId,
		@lBatchId=A.BatchId  
	FROM 
		sStudent.tStudentMaster S
		INNER JOIN sStudent.tAcademic A ON S.Id = A.StudentId
	WHERE 
		S.Id = @rStudentId AND A.BatchId = @rBatchId
	
	
	SELECT DISTINCT 
		RBM.Id,
		RBM.Code,
		RBM.Title, 
		ISNULL(RBM.OrderIndex,0) AS OrderIndex
	FROM 
		[sFee].[tReceiptBookMaster] RBM
		INNER JOIN sFee.tFeeSetup FS ON FS.ReceiptBookId = RBM.Id
	WHERE 
		RBM.IsObsolete = 0
		AND RBM.OrgGroupId = @rOrgGroupId 
		AND FS.ClassId = @lClassId
		AND FS.AdmissionCategoryId = @lAdmissionCategoryId
		AND FS.BatchId = @lBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pReceiptChargeAdd] 
	@rSourceTypeId SMALLINT
	,@rSourceId BIGINT
	,@rReceiptId BIGINT
	,@rCreatedUserId BIGINT
	,@rOrgId INT
	,@rBatchId INT
	,@rCharge DECIMAL(12, 2) = 0
	,@rReceiptBookId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lClassId INT
		,@lFeeSetupId INT
		,@lAdmissionCategoryId BIGINT

	SELECT @lClassId = A.ClassId
		,@lAdmissionCategoryId = A.AdmissionCategoryId
	FROM sStudent.tAcademic A WITH (NOLOCK)
	INNER JOIN sStudent.tStudentMaster S WITH (NOLOCK) ON A.StudentId = S.Id
	WHERE A.Id = @rSourceId

	SELECT @lFeeSetupId = FS.ID
	FROM sFee.tFeeSetup FS WITH (NOLOCK)
	INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
	INNER JOIN sFee.tFeeHeadMaster FH WITH (NOLOCK) ON FM.FeeHeadId = FH.Id
	WHERE FS.BatchId = @rBatchId
		AND FS.ClassId = @lClassId
		AND FS.AdmissionCategoryId = @lAdmissionCategoryId
		AND FH.Number = '100'
		AND FS.IsVariable = 1
		AND FS.ReceiptBookId = @rReceiptBookId

	IF @lFeeSetupId IS NULL
		RETURN

	IF EXISTS (
			SELECT 1
			FROM sFee.tFeeAllocation WITH (NOLOCK)
			WHERE SourceTypeId = 2001
				AND SourceId = @rSourceId
				AND FeeSetupId = @lFeeSetupId
			)
	BEGIN
		UPDATE sFee.tFeeAllocation
		SET VariableAmount = (VariableAmount + @rCharge)
		WHERE SourceTypeId = 2001
			AND SourceId = @rSourceId
			AND FeeSetupId = @lFeeSetupId
	END
	ELSE
	BEGIN
		INSERT INTO sFee.tFeeAllocation (
			SourceTypeId
			,SourceId
			,FeeSetupId
			,VariableAmount
			,DiscountAmount
			,NotApplicableAmount
			,AdditionalAmount
			,Remark
			,CreatedUserId
			,CreatedDateTime
			)
		SELECT 2001
			,@rSourceId
			,@lFeeSetupId
			,@rCharge
			,0
			,0
			,0
			,''
			,@rCreatedUserId
			,sCommon.fGetDate()
	END

	--IF NOT EXISTS (SELECT 1 FROM sFee.tFeeOptional WHERE SourceTypeId = 2001 AND SourceId = @rSourceId 
	--	 AND FeeSetupId = @lFeeSetupId )
	--	 BEGIN
	--			 INSERT INTO sFee.tFeeOptional
	--			(
	--			   FeeSetupId,
	--				SourceTypeId,
	--				SourceId,
	--				BatchId
	--			)
	--			SELECT 
	--			 @lFeeSetupId,
	--			 2001,
	--			 @rSourceId,
	--			 @rBatchId
	--END
	INSERT INTO sFee.tReceiptDetail (
		ReceiptId
		,FeeSetupId
		,Amount
		)
	SELECT @rReceiptId
		,@lFeeSetupId
		,@rCharge

	UPDATE sFee.tReceipt
	SET ReceiptAmount = (ReceiptAmount + @rCharge)
		,TotalReceiptAmount = (TotalReceiptAmount + @rCharge)
	WHERE Id = @rReceiptId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/


CREATE OR ALTER PROCEDURE [sFee].[pReceiptDetailAdd]
	 
		   
		   @rReceiptId bigint,
		   @rReceiptDetailXml [nvarchar](max)
		
		 


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml


BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION
	 	
	--DECLARE @lNextNumber BIGINT     
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
   

	INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @rReceiptId,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
        SELECT 1 AS Result
		--SELECT @lNextNumber = MAX(Id)-1 FROM sFee.tReceipt		
  --      EXECUTE sCommon.pTableRowIdModify @rOrgId,'sFee.tReceipt',@lNextNumber,1,1
         
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
EXEC sp_xml_removedocument @loDoc





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 CREATE OR ALTER PROCEDURE [sFee].[pReceiptDetailDashBoardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rFeeHeadId int=0,
	 @rPayTypeId int =0,
	 @rCollectionGroupId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
  
  declare @ltempOrganization table(
OrgGroupId int,
OrgGroupName nvarchar(500),
ReceiptId bigint,
TotalReceiptAmount DECIMAL(12,2),
IsObsolete bit
)

INSERT INTO @ltempOrganization
SELECT OGM.Id AS OrgGroupId ,OGM.Title AS OrgGroupName,R.Id AS ReceiptCount,R.TotalReceiptAmount,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND(SA.IsActiveBatch =1)
			
			SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
			ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount FROM @ltempOrganization T  
			LEFT JOIN (
			SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM @ltempOrganization WHERE IsObsolete = 1
			GROUP BY OrgGroupId,OrgGroupName
			) A ON A.OrgGroupId=t.OrgGroupId
			WHERE IsObsolete = 0
			GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
		
  END
  
  IF(@rType='ReceiptBookCollectionGroup')
  BEGIN
declare @ltempReceiptBookCollection table(
RecepitTitle nvarchar(200),
CollectionTitle nvarchar(200),
ReceiptCount int,
ReceiptAmount DECIMAL(12,2),
ReceiptId bigint,
CollectionGroupId bigint,
IsObsolete bit
)

insert into @ltempReceiptBookCollection
 SELECT ISNULL(RBM.Title,'')  AS RecepitTitle ,ISNULL(CGM.Title,'') AS CollectionTitle,
			ISNULL(COUNT(DISTINCT R.Id),0) AS ReceiptCount,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,
			ISNULL(RBM.Id,0) AS ReceiptId,ISNULL(CGM.Id,0) AS CollectionGroupId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = SA.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (R.IsObsolete = 1) 
			AND(SA.IsActiveBatch =1)
			GROUP BY RBM.Title,CGM.Title,RBM.Id,CGM.Id, R.ReceiptBookId,R.IsObsolete
			
			 
			SELECT  TRC.RecepitTitle +'-'+ TRC.CollectionTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,TRC.CollectionGroupId AS CollectionGroupId,TRC.ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM @ltempReceiptBookCollection TRC 
			LEFT JOIN (
			SELECT ReceiptId,CollectionGroupId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM @ltempReceiptBookCollection WHERE IsObsolete = 1
			GROUP BY ReceiptId,CollectionGroupId
			) A ON A.ReceiptId=TRC.ReceiptId AND A.CollectionGroupId=TRC.CollectionGroupId
			
			WHERE IsObsolete = 0
			GROUP BY TRC.RecepitTitle,TRC.CollectionTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.CollectionGroupId,TRC.ReceiptCount 
		

  END
  
   IF(@rType='ReceiptBookCollectionGroupDetail')
  BEGIN
  declare @ltempReceiptBookCollectionDetail table(
Code nvarchar(200),
Name nvarchar(200),
ReceiptNumber bigint,
ReceiptAmount DECIMAL(12,2),
ReceiptId bigint,
IsObsolete bit
)
IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO @ltempReceiptBookCollectionDetail
 SELECT SA.Code AS Code,SA.Name AS Name,R.ReceiptNumber AS ReceiptNumber,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = SA.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND  ISNULL(CGM.Id,0)=0
			--AND (R.IsObsolete = 0) 
			AND(SA.IsActiveBatch =1)
			GROUP BY SA.Code,R.ReceiptNumber,SA.Name, R.ReceiptBookId,CGM.Id,R.Id,R.IsObsolete 
	END
ELSE
	BEGIN
	INSERT INTO @ltempReceiptBookCollectionDetail
 SELECT SA.Code AS Code,SA.Name AS Name,R.ReceiptNumber AS ReceiptNumber,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = SA.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND (R.IsObsolete = 0) 
			AND(SA.IsActiveBatch =1)
			GROUP BY SA.Code,R.ReceiptNumber,SA.Name, R.ReceiptBookId,CGM.Id,R.Id,R.IsObsolete 
			--ORDER BY 
	END
  SELECT *  FROM @ltempReceiptBookCollectionDetail ORDER BY ReceiptId
  END
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pReceiptEntryDashBoardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rFeeHeadId int=0,
	 @rPayTypeId int =0,
	 @rDivisionId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN

	SELECT ISNULL(SUM(R.TotalReceiptAmount),0) AS ReceiptAmount FROM sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
	WHERE R.SourceTypeId = 2001
    AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = 0) 
	
  END
  
  IF(@rType='ReceiptBook')
  BEGIN
		SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		GROUP BY RBM.Id,RBM.Title

  END
  
   IF(@rType='OrganizationList')
  BEGIN
		SELECT SA.OrgId AS OrgId,SA.OrganizationName AS OrganizationName,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY SA.OrgId,SA.OrganizationName

  END
  
   IF(@rType='ClassDivisionName')
  BEGIN
		SELECT SA.DivisionId, SA.ClassName +' - '+ SA.DivisionName AS DivisionName,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY SA.DivisionId,SA.ClassName,SA.DivisionName
  END
  
   IF(@rType='StudentList')
  BEGIN
		SELECT SA.Code,SA.Name,R.ReceiptNumber,SUM(R.TotalReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId=0)
		GROUP BY SA.Code,SA.Name,R.ReceiptNumber
  END
  
  
  IF(@rType='FeeHead')
  BEGIN
	IF(@rDay=1)
	BEGIN
	SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount  
	FROM sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
	IF(@rDay=30)
	BEGIN
		SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
	IF(@rDay=365)
	BEGIN
		SELECT FHM.Id AS FeeHeadId,FHM.Title AS FeeHead,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
	INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		GROUP BY FHM.Id,FHM.Title
	END
  END
  
  IF(@rType='FeeMaster')
  BEGIN
	IF(@rDay=1)
	BEGIN
	
		SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
	INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND	CONVERT(DATE,R.ReceiptDate) = CONVERT(DATE,GETDATE())
				AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
	IF(@rDay=30)
	BEGIN
		
		SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
	IF(@rDay=365)
	BEGIN
		
		SELECT FM.Id AS FeeHeadId,FM.Title AS FeeMaster,SUM(RD.Amount) AS ReceiptAmount 
		FROM sFee.tReceipt R
INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		WHERE R.SourceTypeId = 2001
		AND CONVERT(DATE,ReceiptDate) BETWEEN CONVERT(DATE,GETDATE()-365) AND CONVERT(DATE,GETDATE())
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 	 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (FHM.Id = @rFeeHeadId) 
		GROUP BY FM.Id,FM.Title
	END
END
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pReceiptRefundAdd]
	
		   @rId bigint,
		   @rSourceTypeId smallint,
		   @rSourceId bigint,
		   @rReceiptId bigint,
		   @rRefundDate date,
		   @rRefundAmount decimal(12,2),
		   @rPayTypeId tinyint,
		   @rChequeNo nvarchar(20),
		   @rBankName nvarchar(200),
		   @rRemark nvarchar(200),
		   @rIsObsolete bit,
		   @rBatchId int,
		   @rOrgGroupBatchId int,
		   @rCreatedUserId bigint,
		   @rOrgId int,
		   @rReceiptRefundDetailXml [nvarchar](max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptRefundDetailXml

BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceiptRefund', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sFee.tReceiptRefund
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptId,
		   RefundDate,
		   RefundAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   Remark,
		   IsObsolete,
		   BatchId,
		   OrgGroupBatchId,
		   CreatedUserId,
		   CreatedDateTime
        )
	VALUES
		(
		   @lNextNumber,
		   @rSourceTypeId,
		   @rSourceId,
		   @rReceiptId,
		   @rRefundDate,
		   @rRefundAmount,
		   @rPayTypeId,
		   @rChequeNo,
		   @rBankName,
		   @rRemark,
		   @rIsObsolete,
		   @rBatchId,
		   @rOrgGroupBatchId,
		   @rCreatedUserId,
		   sCommon.fGetDate()
		)
		
		INSERT INTO sFee.tReceiptRefundDetail
		(
		   ReceiptRefundId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptRefundDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT 1,@lNextNumber AS Result
		
		EXEC sp_xml_removedocument @loDoc
 END
 
 ELSE
	BEGIN
		UPDATE sFee.tReceiptRefund 
		SET
			RefundAmount=@rRefundAmount,
			RefundDate=@rRefundDate,
			PayTypeId=@rPayTypeId,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
		DELETE FROM sFee.tReceiptRefundDetail WHERE ReceiptRefundId=@rId
		
		INSERT INTO sFee.tReceiptRefundDetail
		(
		   ReceiptRefundId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @rId,
		  FeeSetupId,
		  Amount
		
		FROM OPENXML (@loDoc, '/Table/ReceiptRefundDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		SELECT 11 AS Result
	END 
 
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pReceiptServiceTaxAdd]
    
		   @rSourceTypeId smallint,
		   @rSourceId bigint,
		   @rReceiptId bigint,	 
		   @rCreatedUserId bigint,
		   @rOrgId int,
		   @rBatchId int,
		   @rTaxRate decimal(12,2)=0	 
		  
		   

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN	

DECLARE @lTotalAmount decimal(12,2)
DECLARE @lTaxAmount decimal(12,2)
DECLARE @lTaxTypeId tinyint

SELECT @lTotalAmount = ISNULL(SUM(D.Amount),0) 
	FROM sFee.tReceiptDetail D WITH (NOLOCK) INNER JOIN sFee.tFeeSetup S WITH (NOLOCK) ON D.FeeSetupId = S.Id
	WHERE D.ReceiptId = @rReceiptId AND S.IsServiceTax = 1

SELECT @lTaxTypeId = TaxTypeId FROM sFee.tReceiptBookMaster WITH (NOLOCK) WHERE Id = (SELECT ReceiptBookId FROM sFee.tReceipt WHERE Id = @rReceiptId)
 
--SET @lTaxAmount = round((@lTotalAmount) * (@rTaxRate/100),0)

-- #Start MantisId : 0031923
IF @lTaxTypeId = 2		-- Exclusive 
	BEGIN
		SET @lTaxAmount = round((@lTotalAmount) * (@rTaxRate/100),0)

		IF NOT EXISTS(SELECT 1 FROM sFee.tReceiptTaxDetail WITH (NOLOCK) WHERE ReceiptId = @rReceiptId)
		BEGIN
		INSERT INTO sFee.tReceiptTaxDetail
		SELECT 
			@rReceiptId,
			D.FeeSetupId,
			CASE WHEN S.IsServiceTax = 1 THEN round((D.Amount) * (@rTaxRate/100),0)
				ELSE 0 END,
			@lTaxTypeId,
			S.IsServiceTax

		FROM sFee.tReceiptDetail D INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = S.Id
		WHERE 
		D.ReceiptId = @rReceiptId
		END
	END
ELSE					-- Inclusive
	BEGIN
		SET @lTaxAmount = 0

		IF NOT EXISTS(SELECT 1 FROM sFee.tReceiptTaxDetail WITH (NOLOCK) WHERE ReceiptId = @rReceiptId)
		BEGIN
		INSERT INTO sFee.tReceiptTaxDetail
		SELECT 
			@rReceiptId,
			D.FeeSetupId,
			0,
			@lTaxTypeId,
			S.IsServiceTax

		FROM sFee.tReceiptDetail D INNER JOIN sFee.tFeeSetup S ON D.FeeSetupId = S.Id
		WHERE 
		D.ReceiptId = @rReceiptId
		END
	END					
-- #End MantisId : 0031923
 select @lTaxAmount
UPDATE sFee.tReceipt SET ReceiptAmount = (TotalReceiptAmount + @lTaxAmount) , -- DiscountAmount =  @lTaxAmount, Remove for Mantis : 0031923
		TaxPercentage = @rTaxRate WHERE Id =@rReceiptId
 
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pReceiptUpdate]
	
		   @rId bigint,
		   @rIsChequeCleared bit,
		   @rChequeClearDate date

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
BEGIN TRANSACTION	
	BEGIN
		
		IF(@rIsChequeCleared = 1)
		BEGIN
			-- Mantis - 0032950 By Foram
			DECLARE @lConfigValue nvarchar(50)='',@lOrgGroupBatchId int = 0
			SELECT @lOrgGroupBatchId = OrgGroupBatchId FROM sFee.tReceipt WHERE Id = @rId
			SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 552 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)
			
			IF(@lConfigValue = 'True')
			BEGIN
				UPDATE sFee.tReceipt SET
				IsChequeCleared=@rIsChequeCleared,
				ChequeClearDate=@rChequeClearDate,
				ReceiptDate=@rChequeClearDate
				WHERE Id=@rId
			END
			-- Mantis - 0032950	By Foram 
			ELSE
			BEGIN
				UPDATE sFee.tReceipt SET
				IsChequeCleared=@rIsChequeCleared,
				ChequeClearDate=@rChequeClearDate
				WHERE Id=@rId
			END
		END
		ELSE
		BEGIN
			UPDATE sFee.tReceipt SET
			IsChequeCleared=@rIsChequeCleared,
		    ChequeClearDate=NULL
			WHERE Id=@rId
		END
		
		SELECT 1 AS RESULT
	END 
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sFee].[pRecieptChequeClearListGet]  
    
  @rOrgGroupBatchId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rIdNo nvarchar(20)='',  
  @rFirstName nvarchar(100)='',  
  @rFromReceiptNumber int=0,  
  @rToReceiptNumber int=0,  
  @rReceiptBookId int=0,  
  @rSourceTypeId int=0,  
  @rPayTypeId tinyint=0,  
  @rChequeNo nvarchar(20)='',  
  @rFromDate date,  
  @rToDate date,  
  @rIsObsolete bit,  
  @rOrgId smallint,  
  @rBatchId int,  
  @rOrgGroupId smallint,  
  @rCreatedUserName nvarchar(100),  
  @rCreatedUserId bigint,  
  @rDepartmentId int=0,  
  @rFromChequeDate date='',  
  @rToChequeDate date='',
  @rPayTypeIds nvarchar(max) = '',
  @rChequeStatus nvarchar,
  @rFromChequeClearDate date = '',
  @rToChequeClearDate date = ''
   
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
    BEGIN  
    SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)  
    SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)  
    END  
BEGIN     
Print @rChequeStatus
 SELECT   
  R.Id AS ReceiptId,  
  R.SourceTypeId AS SourceTypeId,  
  CASE WHEN R.SourceTypeId=2001 THEN 'Student'  
  ELSE  'Employee' END AS SourceType,  
  --STM.Title   
  SM.Code AS Code,  
  SM.FirstName+' '+SM.LastName AS Name,  
  R.ReceiptNumber,  
  CONVERT(nvarchar(12),R.ReceiptDate,103) AS ReceiptDate,  
  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,  
  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,  
  ISNULL(R.DiscountAmount,0)AS DiscountAmount,  
  R.PayTypeId,  
  PTM.Title AS PayType,  
  R.ChequeNo,  
  R.BankName,  
  R.ReceiptBookId,  
  RBM.Title AS ReceiptBook,  
  R.IsObsolete,  
  A.OrgId,  
  OM.DisplayTitle AS Organization,  
  R.BatchId,  
  BM.Title AS Batch,  
  R.Remark,  
  CASE WHEN ISNULL(R.IsChequeCleared,0)=0 THEN 'N'  
  ELSE 'Y' END AS IsChequeCleared,  
  CONVERT(nvarchar(12),R.ChequeClearDate,103) AS ChequeClearDate,  
  CONVERT(nvarchar(12),R.ChequeDate,103) AS ChequeDate,  
  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,  
  Cm.title,  
  CM.Id,  
  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,  
  SM.SUId AS SUId,  
  CM.Title +' - '+DM.Title AS Class,
  R.IsChequeCleared
    
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.tAcademic A  
   ON A.Id=R.SourceId   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId   
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId   
  INNER JOIN sStudent.tStudentMaster SM  
   ON SM.Id=A.StudentId  
    --AND SM.StatusId=1  
   AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)  
  INNER JOIN sCommon.tSourceTypeMaster STM  
   ON STM.Id=R.SourceTypeId  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptBookMaster RBM  
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tOrganizationMaster OM  
   ON OM.Id=A.OrgId  
    AND OM.OrgGroupId=@rOrgGroupId  
  INNER JOIN sSetup.tBatchMaster BM  
   ON BM.Id=R.BatchId   
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId  
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId  
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId  
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId  
WHERE   
 ((SM.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))  
 AND (R.SourceTypeId=2001)  
 AND ((SM.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))  
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))  
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))  
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))  
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))  
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))  
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))  
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))  
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))  
 AND (R.IsObsolete=@rIsObsolete)  
 AND ((SM.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))  
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))   
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))  
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))  
 AND ((ISNULL(R.IsChequeCleared,0)=@rChequeStatus) OR (ISNULL(@rChequeStatus,'')=''))
 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))    
 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
 ORDER BY R.ReceiptNumber DESC  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRefundAccountMappingAdd]
	 
		   @rFeeSetupId int,
		   @rAccountingYearId int,
           @rRefundCreditLedgerId int,
           @rRefundDebitLedgerId int,
           @rPayTypeId int


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DELETE FROM sFee.tRefundAccountMapping WHERE FeeSetupId=@rFeeSetupId AND PayTypeId=@rPayTypeId
		
	BEGIN
	INSERT INTO sFee.tRefundAccountMapping
		(
		   FeeSetupId,
		   AccountingYearId,
		   RefundCreditLedgerId,
		   RefundDebitLedgerId,
		   PayTypeId
		   
		)
	VALUES
		(
			@rFeeSetupId,
			@rAccountingYearId,
			@rRefundCreditLedgerId,
			@rRefundDebitLedgerId,
			@rPayTypeId
		)
	
	SELECT 1 AS Result
		             
	END	 
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRefundAccountMappingGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptBookId int,
		   @rPayTypeId int = 0,
		   @rFeeId int = 0,
		   @rFeeHeadId int = 0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS FeeSetupId,
			ISNULL(AM.FeeSetupId,0)AS AMFeeSetupId,
			ISNULL(FS.ClassId,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FM.Title,'') AS FeeTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(AYM.AccountId,0) AS AccountId,
			ISNULL(AM.RefundCreditLedgerId,0) AS RefundCreditLedgerId,
			ISNULL(AM.RefundDebitLedgerId,0) AS RefundDebitLedgerId,
			ISNULL(AM.AccountingYearId,0) AS AccountingYearId,
			ISNULL(AM.PayTypeId,0) AS AMPayTypeId,
			ISNULL(PTM.Id,0) AS PayTypeId,
			ISNULL(PTM.Title,'') AS PayTypeName
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId AND (RBM.Id = @rReceiptBookId OR @rReceiptBookId=0)
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId		
		CROSS JOIN (SELECT PTM.Id,PTM.Title FROM sFinanceCommon.tPayTypeMaster PTM WHERE (PTM.Id = @rPayTypeId OR @rPayTypeId = 0)) PTM
		INNER JOIN sFee.tApplicablePayType APT ON APT.PayTypeId=PTM.Id -- Mentis Id : 0033089 by Vishruti
		LEFT JOIN sFee.tRefundAccountMapping AM ON AM.FeeSetupId=FS.Id AND AM.PayTypeId=PTM.Id
		LEFT JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.RefundCreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.RefundDebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=CLM.AccountingYearId AND AYM.Id=DLM.AccountingYearId
WHERE 
		FM.OrgGroupId=@rOrgGroupId	
		AND (FM.Id = @rFeeId OR @rFeeId=0)	
		AND (FHM.Id = @rFeeHeadId OR @rFeeHeadId = 0)
ORDER BY FM.OrderIndex,PTM.Id

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pRefundAccountMappingRemove]

	 @rFeeSetupId int,
	 @rPayTypeId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	 BEGIN TRANSACTION	
BEGIN
	 
	DELETE 
	FROM sFee.tRefundAccountMapping 
	WHERE FeeSetupId=@rFeeSetupId AND PayTypeId = @rPayTypeId
	
	SELECT 1 AS Result
END	
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptAllBatchFeeStatusGet]
		
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0    
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.StudentId,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		BM.Id AS BatchId,
		BM.Title AS BatchName,
		BM.OrderIndex AS BatchOrderIndex,
		[sFee].[fReceiptNumber_ReceiptDateGet](SA.AcademicId,SA.OrgId,SA.ClassId,SA.DivisionId,SA.OrgGroupBatchId,SA.BatchId,@rUserId,@rCommonBatch,@rUptoDate) AS ReceiptDetail
  FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			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 FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O 
			ON SA.OrgId = O.Id
		 INNER JOIN sSetup.tBatchMaster BM 
			ON BM.Id = SA.BatchId
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		
	WHERE	
   ((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))	
    --AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			     	
	ORDER BY BM.OrderIndex DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pRptChargeReceiptDetailsGet]
	 
		@rReceiptId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
DECLARE @lOrgGroupId int = 0
DECLARE @lCurrencyCode nvarchar(20) = ''
Declare @lIDConfigValue nvarchar(50)=''

 SELECT @lOrgGroupId = OrgGroupId   FROM sFee.tChargeReceipt R 
 INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
 WHERE R.Id = @rReceiptId
SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId)   
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId	 
/*******Changed for mantis : 32211 By Nilesh********/
--Declare @DecimalCount INT
--SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
--						  FROM sConfig.tConfigurationMaster CM
--						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
--						  AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 548

	SELECT 
			CRD.ChargeReceiptId,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			SA.AcademicId,
			--For Name
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Name 
			WHEN CR.SourceTypeId = 3 THEN CR.GuestName
			WHEN CR.SourceTypeId = 95 THEN EM.FirstName + ' ' + EM.LastName
			END ) AS NAME, 
			--For Code
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Code 
			WHEN CR.SourceTypeId = 95 THEN EM.Code
			END ) AS Code,
			--SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			CM.Id AS ChargeId,
			CM.Title AS ChargeName,
			CRD.Amount AS PaidAmount,
			--[sAccounting].[fDecimalValueGet] (ISNULL(CRD.Amount,0), @DecimalCount) AS PaidAmount, -- Added for mantis : 32211 by Nilesh
			PTM.Title AS PayType,
			ISNULL(CR.ChequeNo,'') AS ChequeNo,
			ISNULL(CR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			CR.Remark,
			U.DisplayTitle AS UserName,
			OM.OrgLogo,
			CR.SourceTypeId,
			ISNULL(RBM.Title,'') AS ChargeReceiptBookName,
			ISNULL(CCM.Title,'') AS ChargeCategoryName,
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			sFinanceCommon.fNumberToWordsWithDecimal (ISNULL(CR.ReceiptAmount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
			OM.Title AS OrganizationName,
			CR.ReceiptAmount,
			CM.OrderIndex,
			BM.Title AS Batch,
			@lCurrencyCode AS CurrencyCode,
		    ISNULL(GroupTitle,'') AS GroupTitle,
		    RBM.Remark1,
		    RBM.Remark2,
		    CR.ChequeDate,
		   @lIDConfigValue AS  ItemValue,
		    CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader
		    
			
	FROM 
			sFee.tChargeMaster CM
			INNER JOIN sFee.tChargeReceiptDetail CRD
				ON CRD.ChargeId=CM.Id
			INNER JOIN sFee.tChargeReceipt CR
				ON CR.Id=CRD.ChargeReceiptId 	 
			INNER JOIN sFee.tChargeCategoryMaster CCM
				ON CCM.ChargeReceiptBookId=	CR.ChargeReceiptBookId AND CCM.Id=CM.ChargeCategoryId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=CR.PayTypeId
			INNER JOIN sFee.tChargeReceiptBookMaster RBM 
				ON RBM.Id=CR.ChargeReceiptBookId
			INNER JOIN sSecurity.tUser U
				ON U.Id=CR.CreatedUserId
			LEFT JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId = 2001	
			LEFT JOIN sHrm.tEmployeeMaster EM
				ON EM.Id=CR.SourceId AND CR.SourceTypeId = 95	
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=SA.OrgId
	       INNER JOIN sSetup.tBatchMaster BM ON BM.Id = CR.BatchId				
	WHERE 
			CRD.ChargeReceiptId=@rReceiptId AND  ISNULL(EM.IsOtherUser,0) = 0

ORDER BY CM.OrderIndex ASC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptChargeReceiptListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSourceTypeId smallint,
	 @rSourceCode nvarchar(20),
	 @rGuestName nvarchar(200)='',
	 @rFromDate date,
	 @rToDate date,
	 @rFromNo int,
	 @rToNo int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrgGroupBatchId int,
	 @rDepartmentId int = 0,
	 @rStudentCode nvarchar(20) = '',
	 @rIsDetail bit=0,
	 @rCreatedUserName nvarchar(100)='',
	 @rPayTypeId int=0,
	 @rOrgGroupId int=0,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 		

Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0
Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			CR.ReceiptNumber,
			CR.ReceiptDate,
		    -- For Type 
			(CASE WHEN CR.SourceTypeId = 95 THEN	'Employee'
			 WHEN CR.SourceTypeId = 2001 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,
			-- For Name
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Name 
			WHEN CR.SourceTypeId = 3 THEN CR.GuestName
			WHEN CR.SourceTypeId = 95 THEN EM.EmployeeName
			END ) AS Name, 
			-- For Code
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Code 
			WHEN CR.SourceTypeId = 95 THEN EM.Code
			END ) AS Code,
			-- For Class Department
			(CASE WHEN CR.SourceTypeId = 95 THEN EM.DepartmentName
			WHEN CR.SourceTypeId = 2001 THEN (SA.ClassName + ' - '+ SA.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
			SA.RollNo,
			PTM.Title AS PayType,
			ISNULL(CR.ChequeNo,'') AS ChequeNo,
			ISNULL(CR.BankName,'') AS BankName,
			CR.Remark,
			CR.CreatedUserId,
			U.DisplayTitle AS UserName,
			CR.SourceTypeId,
			ISNULL(RBM.Id,0) AS ChargeReceiptBookId,
			ISNULL(RBM.Title,'') AS ChargeReceiptBookName,
			ISNULL(OM.Title,'') AS OrganizationName,
			CR.ReceiptAmount,
			@lIDConfigValue AS ItemValue 
			
	FROM 
			sFee.tChargeReceipt CR
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=CR.PayTypeId
			INNER JOIN sFee.tChargeReceiptBookMaster RBM 
				ON RBM.Id=CR.ChargeReceiptBookId
			INNER JOIN sSecurity.tUser U
				ON U.Id=CR.CreatedUserId
			LEFT JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId = 2001	
			LEFT JOIN sHrm.vExtEmployeeMaster EM
				ON EM.Id=CR.SourceId AND CR.SourceTypeId = 95	
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=SA.OrgId				
	WHERE 
			((CR.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			--AND (((@rSourceTypeId =2001 OR(@rSourceTypeId=0)) AND SA.Name like @rGuestName) 
			--	OR (ISNULL(@rGuestName,'')='') OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND EM.EmployeeName LIKE @rGuestName) OR (ISNULL(@rGuestName,'')='') 
			--	OR ((@rSourceTypeId =3 OR (@rSourceTypeId=0)) AND CR.GuestName LIKE @rGuestName) OR (ISNULL(@rGuestName,'')=''))
            AND (((@rSourceTypeId =2001 OR(@rSourceTypeId=0)) AND SA.Code LIKE @rStudentCode) OR (ISNULL(@rStudentCode,'')='') 
				OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND EM.Code LIKE @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And (CR.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
			AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
			ORDER BY CR.ReceiptNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptClasswiseFeeGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
	    @rCollectionGroupId int,
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = ''    
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	SELECT DISTINCT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		CM.Id AS ClassId,
		CM.Title AS ClassName,
		CM.OrderIndex AS ClassOrderIndex,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.StartDate,
		CGM.EndDate,
		FS.Amount
  FROM 
		sFee.tFeeSetup FS 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = FS.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id= FS.BatchId
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.OrgId = BM.OrgId
		
WHERE 
		(CGM.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((BM.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((DM.Id=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(DM.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptClasswiseSetup]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS Id,
			ISNULL(CM.Id,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			FM.Title AS FeeTitle,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
			ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			CASE WHEN (SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0 THEN 'True' ELSE 'False' END AS IsReceiptBookChange,
			ISNULL(FS.IsServiceTax,0)AS IsServiceTax,
			ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,
			ISNULL(FS.FeeDuration,'')  AS FeeDuration,
			ISNULL(FS.LevelAmount,0) AS LevelAmount,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ACM.Title As AdmissionCategory
  FROM 
			sFee.tFeeMaster FM
		LEFT JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId OR @rClassId= 0) 
		AND (FS.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId= 0) 
		AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId
		INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON FS.AdmissionCategoryId=ACM.Id
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		--ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex
		ORDER BY FM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptCustomFeePendingDetailListGet]  

	@rReportId int=0,  
	@rReceiptBookId int=0,  
	@rAdmissionCategoryId int=0,  
	@rClassId int=0,  
	@rDivisionId int=0,  
	@rUptoDate date='',  
	@rBatchId int=0,  
	@rUserId bigint=0,  
	@rBuilder1 nvarchar(max) = '',  
	@rBuilder2 nvarchar(max) = '',  
	@rIsDetail bit=0,  
	@rOrgId int=0,  
	@rOrgGroupBatchId int=0,  
	@rStatusId int=0,  
	@rCommonBatch nvarchar(100) = '',  
	@rDepartmentId int=0,  
	@rFromRollNo int=0,  
	@rToRollNo int=0,  
	@rCode nvarchar(20)='',  
	@rIsFilter bit=0,  
	@rIsHeader bit=0,    
	@rCreatedUserName nvarchar(20) = '',  
	@rIsReceiptBookGroup bit=0,  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,  
	@rOrgIds  nvarchar(max) = '',  
	@rPayDate date='',  
	@rCollectionGroupId int =0,  
	@rCastCategoryId int = 0,
	@rReportType int=0,
	@rClassStatusId int=0 ,
	@rCollectionGrupId nvarchar(max) ='',
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''
	 
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 
	
	CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max)
	)
	
	INSERT INTO #TempIsOptional
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup      
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId    
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id      
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))      
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  

	UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup       
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sFee.tFeeOptional FO  
			ON FO.FeeSetupId=FS1.Id  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId   
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId 
		WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
	 
	--select * from #TempIsOptional
	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint
	)
	
	INSERT INTO #TempReceipt
	SELECT   
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
	FROM  
		sFee.tReceipt R   
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId  
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId     
		AND (SA1.ClassId=@rClassId OR @rClassId=0)
		AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')   
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
	WHERE    
		(R.SourceTypeId = 2001)  
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND (R.IsObsolete = 0)   
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
		AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
	GROUP BY FeeSetupId,R.SourceId
	
	--select * from #TempReceipt
	
	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint  
	)
	

	INSERT INTO #TempAssignRoute
	SELECT 
		AT.SourceId 
	FROM 
		sTransport.tAssignRoute AT   
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	
	IF(@rReportType=1)
	BEGIN	   
		SELECT   		  
		SA.AcademicId,  
		SA.RollNo,  
		SA.Name,  
		SA.Code,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName,  
		SA.DivisionName,  		
		SA.ClassName+' - '+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,  		
		SA.OrgId,  
		O.Title AS OrgName,  				
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  		  
		ISNULL(CCM.Title,'') AS CastCategoryName,  		
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		SA.DepartmentName,
		(Select SUM(PaidAmount)
				FROM #TempReceipt R1
				Where R1.SourceId = SA.AcademicId) AS PaidAmount,
		--(SELECT  STUFF((SELECT ',' + Convert(varchar,ReceiptDate)
		--		FROM sFee.tReceipt
		--		where SourceId = SA.AcademicId
		--       FOR XML PATH('')
		--       ), 1, 1, '')) AS ReceiptDate
		sCommon.fGetDate() AS PrintDate
	
	FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA  
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster O ON   
		SA.OrgId = O.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM   
		ON FS.ReceiptBookId=RBM.Id  
		LEFT JOIN sStudent.tStudentCommunication SC   
		ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO   
		ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM   
		ON CCM.Id = SO.CastCategoryId    
		INNER JOIN sFee.tFeeHeadMaster FHM  
		ON FHM.Id = FS.FeeHeadId
		
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
	WHERE   
		SA.OrgGroupBatchId = @rOrgGroupBatchId  
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		AND ((SA.Code=@rCode) OR (@rCode=''))  
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) >= 0)     
		AND (  
				(@rFilterId = 0) -- All  
				OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
				OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
				OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')      
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0)) 
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
	GROUP BY
	SA.AcademicId,  
	SA.RollNo,  
	SA.Name,  
	SA.Code,  
	SA.ClassId,  
	SA.DivisionId,  
	SA.ClassName,  
	SA.DivisionName,
	SA.OrgId,  
	O.Title,  				
	SC.ParentContactNo,
	CCM.Title,
	SA.DepartmentName
	--R.PaidAmount,
	--R.SourceId
	Order by SA.RollNo  
	END	
	
	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #TempAssignRoute
	
	--SELECT   
	--	'' AS Builder1,  
	--	'' AS Builder2,  
	--	0 AS IsDetail,  
	--	0 As IsFilter,  
	--	0 As IsHeader,  
	--	0 AS IsDisplayOrgGroup,  
	--	1104000002505 AS AcademicId,  
	--	0 AS RollNo,  
	--	'' AS Name,  
	--	'' AS Code,  
	--	0 AS ClassId,  
	--	0 AS DivisionId,  
	--	'' AS ClassName,  
	--	'' AS DivisionName,  
	--	0 AS DivisionOrder,  
	--	'' AS ClassDivision,  
	--	0 AS FeeSetupId,  
	--	0 AS IsVariable,  
	--	0.00 AS Amount,  
	--	'2001-01-30' AS StartDate,  
	--	'2001-01-30' AS EndDate,  
	--	0.00 AS FAAmount,  
	--	0.00 AS DiscountAmount,  
	--	0.00 AS AdditionalAmount,  
	--	0.00 AS PaidAmount,
	--	0.00 PendingAmount,
	--	'' AS Remark,  
	--	'' AS FeeName,  
	--	0 AS FeeHeadId,  
	--	'' AS FeeHeadName,  
	--	0 AS FeeHeadOrderIndex,  
	--	0 AS OrgId,  
	--	'' AS OrgName,  
	--	0 AS OrgOrderIndex,  
	--	0 AS ReceiptBookId,   
	--	'' AS ReceiptBookTitle,  
	--	0 AS ReceiptOrderIndex,    
	--	0 As ReceiptBookId,  
	--	'' AS ReceiptBookFullTitle,
	--	'' AS RecieptBookAddress1,
	--	'' As RecieptBookAddress2,
	--	'' As Remark1,
	--	0 AS ReceiptOrderIndex,  
	--	0 AS OrgGoupBatchId,  
	--	0 AS DepartmentId,  
	--	'' AS DepartmentName,  
	--	'' AS ParentContactNo,  
	--	'' AS ReferenceRemark,  
	--	'2001-01-30' AS PayDate ,  
	--	0 AS CastCategoryId,  
	--	'' AS CastCategoryName,  
	--	0 AS CastCategoryOrderIndex,
	--	'' AS ReportTemplate,
	--0 As CollectionGroupId,
	--'' AS CollectionGroup,
	--'' AS BatchName,
	--'' AS FatherName,
	--'' AS FatherContactNo,
	--'' AS MotherName,
	--'' AS MotherContactNo

	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptDepositAddGet]
          
		   @rOrgId int,          
           @rDepositHeadId int = 0,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromDepositDate date,
           @rToDepositDate date,
           @rBatchId int = 0,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int=0

           
AS
SET NOCOUNT ON 

BEGIN
	Declare @lOrgId int = 0
	DECLARE @lOrgGroupId int = 0
Declare @lIDConfigValue nvarchar(50)=''
-- commented by dhananjay for mantis : 42361
--if(@rOrgGroupBatchId > 0)
--		begin 
--			SELECT @lOrgId = OrgId FROM sSetup.tBatchMaster where ID = 110100110
--			seT @rOrgId = @lOrgId
			
--			--select @rOrgId 
--			--RETURN;
--		end
 --commented by dhananjay for mantis : 42361
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 308 AND SourceId = @lOrgGroupId

SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
		--DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,	
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
		OI.CertificateHeaderA4  AS DepositHeaderA4,
		@lIDConfigValue AS DepositConfigValue,
		DA.DepositNumber AS DepositNumber --Mantis 0031422
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdd DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
  WHERE  
		(vSA.BatchId = @rBatchId OR @rBatchId  = 0)--uncommented & And Condition for zero condition by dhananjay for mantis : 42361
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND DA.OrgGRoupBatchId=@rOrgGroupBatchId
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		Order By DA.DepositDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptDepositAddReceiptGet] 
	 @rId BIGINT
	,@rOrgId INT
	,@rDepositHeadId INT
	,@rBatchId INT
	,@rOrgGroupId INT
	,@rOrgGroupBatchId INT = 0
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lOrgGroupId INT = 0
	DECLARE @lCurrencyCode NVARCHAR(20) = ''
	DECLARE @lIDConfigValue NVARCHAR(50) = ''

	SELECT @lIDConfigValue = ItemValue
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId = 308
		AND SourceId = @rOrgGroupId

	IF (@rOrgGroupId = 0)
	BEGIN
		SELECT @lOrgGroupId = R.OrgGroupId
		FROM sFee.tDepositHeadMaster R
		INNER JOIN sSetup.tOrgGroupMaster OB ON R.OrgGroupId = OB.Id
		WHERE R.Id = @rDepositHeadId

		SELECT @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId)
	END
	ELSE
	BEGIN
		SELECT @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId)
	END

	SELECT DHM.Title AS DepositHeadName
		,DA.Id
		,DA.DepositHeadId
		,
		--DA.StudentId AS StudentId,  
		vSA.AcademicId AS AcademicId
		,DA.Amount
		,DA.DepositDate
		,DA.PayTypeId
		,PTM.Title AS PayType
		,DA.ChequeNo
		,DA.BankName
		,DA.Remark
		,DA.CreatedDateTime
		,vSA.RollNo
		,vSA.Code
		,vSA.Name AS StudentName
		,vSA.ClassName + ' - ' + vSA.DivisionName AS ClassDivisionName
		,OM.Id AS OrgId
		,OM.DisplayTitle AS OrganizationName
		,sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount, 0.00), 1, 2, OM.OrgGroupId) AS ReceiptAmountInWords
		,vSA.BatchName
		,@lCurrencyCode AS CurrencyCode
		,DA.DepositNumber AS DepositNumber
		,OI.CertificateHeaderA4 AS DepositHeaderA4
		,@lIDConfigValue AS DepositConfigValue
		,U.DisplayTitle As CreatedUserName
	FROM sStudent.vStudentAcademic vSA
	INNER JOIN sFee.tDepositAdd DA ON DA.AcademicId = vSA.AcademicId
	INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = DA.PayTypeId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	LEFT JOIN sSecurity.tUser U ON U.Id = DA.CreatedUserId
	WHERE
		--vSA.BatchId = @rBatchId   
		(
			vSA.OrgId = @rOrgId
			OR @rOrgId = 0
			)
		AND (
			DA.DepositHeadId = @rDepositHeadId
			OR @rDepositHeadId = 0
			)
		--AND ((DHM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))  
		AND (DA.Id = @rId)
		--AND DA.OrgGRoupBatchId=@rOrgGroupBatchId  
		AND vSA.OrgGRoupBatchId = @rOrgGroupBatchId
	ORDER BY DA.DepositDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptDepositAddSummaryPayTypeWise]
	     
	 @rDepositHeadId int,
	 @rOrgGroupBatchId int = 0,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rBatchId int,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
     @rFromDate date='',
     @rToDate date='',
     @rPayTypeId int=0,
     @rIsWithDetails int=0
   
      
AS
BEGIN
	SELECT 			
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    'Deposite Add' As GroupType,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    DA.CreatedDateTime,
		    VA.StudentId,
		    @rBuilder1 As builder1,
		    DA.DepositNumber AS Number,		    
		    PTM.Title AS PayType,
		    DA.PayTypeId AS PayTypeId,
		    VA.ClassId AS ClassId,
		    VA.DivisionId AS DivisionId,
		    VA.OrganizationName AS OrgName,
		    DA.ChequeNo AS ChequeNo,
		    DA.BankName	AS BankName,
		    VA.OrgId,
		    @rIsWithDetails AS IsWithDetails,
		    VA.RollNo AS RollNo	    
		    
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DA.PayTypeId
			
			
			Where 
		   ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.DepositHeadId = @rDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
		    AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND  (VA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND  (DA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		    AND ((convert(date,DA.DepositDate)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    AND ((convert(date,DA.DepositDate)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
		    AND ((DA.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))
	
	Order by VA.ClassId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptDepositAdjustmentDetailGet] 
		
	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
	 @rORgGroupBatchId int = 0,
     @rIsBasedOnSUId bit = 0,
     @rBatchId int,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
     @rFromDate date='',
     @rToDate date=''
   
      
AS
BEGIN


			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			-ISnull (DAJ.Amount,0) As Amount,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    'DepositeAdjustment' As GroupType,
		    
		    VA.Name As StudentName, 
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     DAJ.CreatedDateTime,
		     VA.StudentId,
		     @rBuilder1 As builder1,
		     DAJ.AdjustmentNumber AS Number,
			 ISNULL(ETM.Title,'')AS ExpenseType
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		    AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((convert(date,DAJ.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((convert(date,DAJ.CreatedDateTime)<=@rToDate) OR (ISNULL(@rToDate,'')=''))
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pRptDepositAdjustmentGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromAdjustmentDate date,
           @rToAdjustmentDate date,
           @rBatchId int,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int=0,
           @rFeeDepositExpenseTypeId int
           
AS
SET NOCOUNT ON

BEGIN
DECLARE @lOrgGroupId int = 0
Declare @lIDConfigValue nvarchar(50)=''
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 308 AND SourceId = @lOrgGroupId
	/**Added for mantis : 32211 by Nilesh**/
	
	 --SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
		--				  FROM sConfig.tConfigurationMaster CM
		--				  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		--				  AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 548
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
	--	DA.StudentId AS StudentId,
		VSA.AcademicId AS AcademicId,
		DA.Amount,
		--([sAccounting].[fDecimalValueGet] (DA.Amount, @DecimalCount)) ,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
		@lIDConfigValue AS ItemValue
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
  WHERE  
		 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		AND (DA.FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId OR @rFeeDepositExpenseTypeId=0)
		AND (vSA.BatchId = @rBatchId OR @rBatchId='')
		Order By DA.CreatedDateTime
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptDepositAdjustmentReceiptGet]
          
   @rId bigint,          
   @rOrgId int,          
   @rDepositHeadId int,
   @rBatchId int,
   @rOrgGroupBatchId int=0,
   @rFeeDepositExpenseTypeId int,
   @rStrId nvarchar(max)= ''
           
AS
SET NOCOUNT ON

If @rId > 0 SET @rStrId = ''

BEGIN
DECLARE @lOrgGroupId int = 0
Declare @lIDConfigValue nvarchar(50)=''
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 308 AND SourceId = @lOrgGroupId


  SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
		--DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.RollNo,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
		Isnull(ET.Title,'') As ExpenseType,
		DA.AdjustmentNumber,
		@lIDConfigValue AS ItemValue
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
	    INNER  JOIN  [sFee].[tFeeDepositExpenseTypeMaster] ET ON ET.Id=FeeDepositExpenseTypeId
  WHERE  
	    --vSA.BatchId = @rBatchId 
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Id=@rId) OR (@rId = 0))
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		AND (DA.FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId OR @rFeeDepositExpenseTypeId=0)
		AND (DA.Id IN (SELECT item from sCommon.fnSplit(@rStrId,',')) OR  @rStrId='')
		Order By DA.CreatedDateTime
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptDepositBalanceGet]
          
           @rOrgId smallint,
           @rDepositHeadId int,
           @rBatchId int
AS
SET NOCOUNT ON
BEGIN
DECLARE @lOrgGroupId int = 0
Declare @lIDConfigValue nvarchar(50)=''
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 308 AND SourceId = @lOrgGroupId
SELECT   
		ISNULL(vBC.ClassId,0) AS ClassId,
        ISNULL(vBC.ClassName,'') AS ClassName,
        ISNULL(DB.DepositHeadId,0) AS DepositHeadId,
        ISNULL(DHM.Title,'') AS DepositHeadName,
        ISNULL(DB.BalanceAmount,0.00)AS BalanceAmount,
        ISNULL(OM.Id,0) AS OrgId,
        ISNULL(OM.DisplayTitle,'') AS OrganizationName,
		@lIDConfigValue AS ItemValue,
		ISNULL(DB.NegativeBalance,0.00)AS NegativeBalance
  FROM 		
	  	sSetup.vBatchClass vBC
		LEFT JOIN sFee.tDepositBalance DB ON DB.ClassId =vBC.ClassId AND (DB.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id=DB.DepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=@rOrgId
  WHERE 
		vBC.BatchId=@rBatchId
		AND (DB.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND (Om.Id=@rOrgId OR @rOrgId=0)

		order by vBC.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptDepositMinusGet]
          
           @rOrgId int,
           @rBatchId int,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int = 0
AS
SET NOCOUNT ON
BEGIN
SELECT 
		'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as SourceCode,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.RollNo,
--		DA.HostelDepositHeadId,
--		DHM.Title AS DepositHeadName,
		SA.OrgId,
		SA.OrganizationName,
		(D.TotalDeposit - A.TotalAdjustment) AS MinusAmount,
		sA.BatchId
  FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN
		(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.AcademicId FROM sFee.tDepositAdd DA GROUP BY DA.AcademicId  )D 
		ON D.AcademicId=SA.AcademicId
		LEFT JOIN 
		(select SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.AcademicId   FROM sFee.tDepositAdjustment AD  GROUP BY AD.AcademicId) A 
		ON A.AcademicId=SA.AcademicId
		--INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = D.HostelDepositHeadId
  WHERE  
       
  	 -- SA.BatchId = @rBatchId 
		 (SA.OrgId=@rOrgId OR @rOrgId=0)
		--AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		--AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		--AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		--AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		--AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((SA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND  (SA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		AND  D.TotalDeposit - A.TotalAdjustment < 0 
		  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptDepositPendingList] 
		
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
	 @rOrgId int =0,  
	 @rBatchId int =0,        
	 @rDepositHeadId int =0,
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int =0,
	 @rCode nvarchar(20) = ''
      
AS
BEGIN
	SELECT DISTINCT A.StudentId,A.AcademicId,A.Code,A.Name,A.OrganizationName,A.OrgId,A.ClassDivisionName,A.SetupAmount,A.Amount,A.MobileNo,
	(CASE WHEN ISNULL(A.SetupAmount,0)=0 THEN 0 ELSE (ISNULL(A.SetupAmount,0) - ISNULL(A.Amount,0))END)AS PendingAmount
	FROM (
	Select 
			VA.StudentId,
			VA.AcademicId,
			VA.Code,
			VA.Name,
			VA.OrganizationName,
			VA.OrgId,
			VA.ClassName+' - '+VA.DivisionName AS ClassDivisionName,
			DS.Amount AS SetupAmount,
			(Select SUM(DA1.Amount)from sStudent.vStudentAcademic  VA1
			LEFT JOIN sFee.tDepositAdd DA1  ON VA1.AcademicId = DA1.AcademicId
			LEFT JOIN sFee.tDepositSetup DS1 ON DS1.StudentId=VA1.StudentId AND DS1.DepositHeadId=DA1.DepositHeadId
			WHERE VA1.StudentId=VA.StudentId AND (DA1.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0))AS Amount,
			SC.ParentContactNo AS MobileNo,
			VA.BatchId
			
			from sStudent.vStudentAcademic  VA
			LEFT JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId
			LEFT JOIN sFee.tDepositSetup DS ON DS.StudentId=VA.StudentId 
			AND (DS.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
			INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = VA.StudentId
			
			WHERE 
				
			(VA.OrgId=@rOrgId OR @rOrgId=0)
			--AND (VA.BatchId=@rBatchId OR @rBatchId=0)
			AND VA.StatusId =1
			AND (VA.DepartmentId=@rDepartmentId OR @rDepartmentId=0)
			AND((VA.ClassId = @rClassId)OR(@rClassId=0))
			AND((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((VA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			--AND (DS.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
			--AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
			)A
			WHERE (A.BatchId=@rBatchId OR @rBatchId=0) AND (A.SetupAmount IS NOT NULL OR  A.Amount IS NOT NULL)

			--GROUP BY VA.AcademicId,VA.StudentId,VA.Code,VA.Name,VA.OrganizationName,VA.OrgId,VA.ClassName,VA.DivisionName,SC.ParentContactNo,DS.Amount
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptDepositRefundGet]
          
		   @rOrgId int,          
           @rDepositHeadId int = 0,
           @rFromRefundAmount decimal(12,2),
           @rToRefundAmount decimal(12,2),
           @rFromRefundDate date,
           @rToRefundDate date,
           @rBatchId int = 0,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int
           
AS
SET NOCOUNT ON

BEGIN
DECLARE @lOrgGroupId int = 0
DECLARE @lOrgId int = 0
Declare @lIDConfigValue nvarchar(50)=''
--comment by dhannajay for mantis : 42361
--if(@rOrgGroupBatchId > 0)
--		begin 
--			SELECT @lOrgId = OrgId FROM sSetup.tBatchMaster where ID = @rBatchId
--			seT @rOrgId = @lOrgId
			
--			--select @rOrgId 
--			--RETURN;
--		end
--comment by dhannajay for mantis : 42361
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE ((Id = @rOrgId )OR(@rOrgId=0))--Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 309 AND SourceId = @lOrgGroupId

SELECT 
		DHM.Title AS DepositHeadName,
		DR.DepositHeadId,
		--DR.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DR.RefundDate,
		DR.PayTypeId,
		DR.ChequeNo,
		DR.BankName,
		DR.Remark,
		DR.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
		CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
		(SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
		INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.AcademicId=D.AcademicId AND D.AcademicId = DR.AcademicId
		WHERE D.DepositHeadId = DR1.DepositHeadId AND D.AcademicId=DR1.AcademicId)         
		- (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.AcademicId=DA.AcademicId AND DA.AcademicId= DR.AcademicId
		WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.AcademicId=DR2.AcademicId  ) END AS RefundAmount,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
		OI.CertificateHeaderA4  AS DepositHeaderA4,
		@lIDConfigValue AS DepositConfigValue
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DR.DepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
		
  WHERE  
		--uncomment this filter by dhannajay for mantis : 42361
		(vSA.BatchId = @rBatchId  OR @rBatchId =0) --Add Condition zero by dhananjay for mantis : 42361
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		--uncomment this filter by dhannajay for mantis : 42361
		AND ((DR.DepositHeadId=@rDepositHeadId) OR (@rDepositHeadId=0))
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND VSA.OrgGroupbatchid=@rOrgGroupBatchId
		GROUP BY
		DHM.Title,DR.DepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName,OM.Id,OM.DisplayTitle, DR.AcademicId,OI.CertificateHeaderA4
		Order By DR.RefundDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptDepositRefundReceiptGet]
          
		   @rId bigint,
		   @rOrgId int,          
           @rDepositHeadId int,
           @rBatchId int,
           @rOrgGroupId int,
            @rOrgGroupBatchId int=0
           
AS
SET NOCOUNT ON 
BEGIN 	

	DECLARE @lOrgGroupId int = 0
	DECLARE @lOrgId int = 0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	Declare @lIDConfigValue nvarchar(50)=''
	if(@rOrgGroupBatchId > 0)
		begin 
			SELECT @lOrgId = OrgId FROM sSetup.tBatchMaster where ID = @rBatchId
			seT @rOrgId = @lOrgId	
		end
	
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 309 AND SourceId = @lOrgGroupId

	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = R.OrgGroupId  FROM sFee.tDepositHeadMaster R 
		INNER JOIN sSetup.tOrgGroupMaster OB ON R.OrgGroupId = OB.Id 
		WHERE R.Id = @rDepositHeadId
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END
SELECT  
DHM.Title AS DepositHeadName,
		DR.DepositHeadId,
		DR.Id,
		--DR.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DR.RefundDate,
		DR.PayTypeId,
		PTM.Title AS PayType,
		DR.ChequeNo,
		DR.BankName,
		DR.Remark,
		DR.CreatedDateTime,
		vSA.RollNo,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
		CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
		(SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
		INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.AcademicId=D.AcademicId AND D.AcademicId = DR.AcademicId
		WHERE D.DepositHeadId = DR1.DepositHeadId AND D.AcademicId=DR1.AcademicId)         
		- (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.AcademicId=DA.AcademicId AND DA.AcademicId= DR.AcademicId
		WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.AcademicId=DR2.AcademicId  ) END AS RefundAmount,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationNam,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DR.RefundAmount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
        vSA.BatchName,
        @lCurrencyCode AS CurrencyCode,
		DR.RefundNumber As RefundNumber,
		OI.CertificateHeaderA4  AS DepositHeaderA4,
		@lIDConfigValue AS DepositConfigValue
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DR.DepositHeadId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId  
		INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DR.PayTypeId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
  WHERE  
		--((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND 
		((DR.DepositHeadId=@rDepositHeadId) OR (@rDepositHeadId=0))
		AND ((DHM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
		AND (DR.Id=@rId)
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		AND vSA.BatchId = @rBatchId 
		Order By DR.RefundDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptDepositRefundSummaryPayTypeWise]
	     
	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
	 @rOrgGroupBatchId int = 0,
     @rIsBasedOnSUId bit = 0,
     @rBatchId int,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
     @rFromDate date='',
     @rToDate date='',
     @rPayTypeId int=0,
     @rIsWithDetails int=0
   
      
AS
BEGIN
	SELECT 
			DR.RefundDate As DepositDate,
			-ISnull (DR.RefundAmount,0) AS Amount,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    'Deposite Refund' As GroupType,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId,
		    DR.CreatedDateTime,
		    VA.StudentId,
		    @rBuilder1 As builder1,
		    DR.RefundNumber AS Number,		    
		    PTM.Title AS PayType,
		    DR.PayTypeId AS PayTypeId,
		    VA.ClassId AS ClassId,
		    VA.DivisionId AS DivisionId,
		    VA.OrganizationName AS OrgName,
		    DR.ChequeNo AS ChequeNo,
		    DR.BankName	AS BankName,
		    VA.OrgId,
		    @rIsWithDetails AS IsWithDetails,
		    VA.RollNo AS RollNo,
			SF.FatherName	    	 	    
		     
			FROM 
			sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DR.PayTypeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = VA.StudentId
			
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND  (VA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND  (DR.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND ((convert(date,DR.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((convert(date,DR.CreatedDateTime)<=@rTodate) OR (ISNULL(@rToDate,'')=''))
			AND ((DR.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))
	
	Order by VA.ClassId
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptDepositStatusStudentWise]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int =0,
	@rBatchId int =0,
	@rDepositHeadId int =0,
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int =0,
	@rCode nvarchar(20) = '',
	--Mantis ID Start : 36629
	@rFromDate date='',
    @rToDate date='',
	--Mantis ID End : 36629
	@rStatusId int =0, --add for mantis : 0040863
	@rClassStatusId int =0 --add for mantis : 0040863
AS
BEGIN
	SELECT DISTINCT 
		A.StudentId,
		A.AcademicId,
		A.Code,
		A.Name,
		A.OrganizationName,
		A.OrgId,
		A.ClassDivisionName,
		ISNULL(A.TotalAmount,0) AS TotalAmount,
		A.MobileNo,
		ISNULL(A.UsedAmount,0) AS UsedAmount,
		ISNULL(A.RefundAmount,0) AS RefundAmount,
		(ISNULL(A.TotalAmount,0) - ISNULL(A.UsedAmount,0) - ISNULL(A.RefundAmount,0)) AS BalanceAmount

	
	FROM
		(SELECT
			VA.StudentId,
			VA.AcademicId,
			VA.Code,
			VA.Name,
			VA.OrganizationName,
			VA.OrgId,
			VA.ClassName+' - '+VA.DivisionName AS ClassDivisionName,
			SC.ParentContactNo AS MobileNo,
			VA.BatchId,

			(SELECT SUM(DA1.Amount)
			 FROM sStudent.vStudentAcademic VA1
				LEFT JOIN sFee.tDepositAdd DA1 ON VA1.AcademicId = DA1.AcademicId
			 WHERE VA1.StudentId=VA.StudentId AND (DA1.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
			 AND ((DA1.DepositDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))--Added Both Date by dhananjay MAntis : 36629
				AND ((DA1.DepositDate <= @rToDate) OR (ISNUll(@rToDate,'')=''))
			 ) AS TotalAmount,

			(SELECT SUM(DAJ1.Amount)
			 FROM sStudent.vStudentAcademic VA2
				LEFT JOIN sFee.tDepositAdjustment DAJ1 ON VA2.AcademicId = DAJ1.AcademicId
			 WHERE VA2.StudentId=VA.StudentId AND (DAJ1.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
			 	 AND ((DAJ1.AdjustmentDate  >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))--Added Both Date by dhananjay MAntis : 36629
				AND ((DAJ1.AdjustmentDate  <= @rToDate) OR (ISNUll(@rToDate,'')=''))
			 ) AS UsedAmount,
			
			(SELECT SUM(DR1.RefundAmount)
			 FROM sStudent.vStudentAcademic VA3
				LEFT JOIN sFee.tDepositRefund DR1 ON VA3.AcademicId = DR1.AcademicId
			 WHERE VA3.StudentId=VA.StudentId AND (DR1.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
			 	 AND ((DR1.RefundDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))--Added Both Date by dhananjay MAntis : 36629
				AND ((DR1.RefundDate <= @rToDate) OR (ISNUll(@rToDate,'')=''))
			 
			 ) AS RefundAmount,
			 DA.DepositDate,
			 DAJ.AdjustmentDate,
			 DR.RefundDate
		

		FROM sStudent.vStudentAcademic VA
			LEFT JOIN sFee.tDepositAdd DA ON VA.AcademicId = DA.AcademicId
			INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = VA.StudentId
			LEFT JOIN sFee.tDepositAdjustment DAJ ON VA.AcademicId = DAJ.AcademicId
			LEFT JOIN sFee.tDepositRefund DR ON VA.AcademicId = DR.AcademicId
			
		WHERE (VA.OrgId=@rOrgId OR @rOrgId=0)
				AND (VA.StatusId =@rStatusId OR @rStatusId=0) --add for mantis : 0040863
				AND (VA.DepartmentId=@rDepartmentId OR @rDepartmentId=0)
				AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
				AND ((VA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
				AND (VA.ClassStatusId =@rClassStatusId OR @rClassStatusId=0)--add for mantis : 0040863
		)A
	WHERE (A.BatchId=@rBatchId OR @rBatchId=0) 
	AND (A.TotalAmount IS NOT NULL OR A.UsedAmount IS NOT NULL OR A.RefundAmount IS NOT NULL)
	--Added by dhananjay Start Mantis : 36629
	AND ((A.DepositDate >= @rFromDate) OR (A.AdjustmentDate >= @rFromDate) OR (A.RefundDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.DepositDate <= @rToDate) OR (A.AdjustmentDate <= @rToDate) OR (A.RefundDate <= @rToDate)  OR (ISNUll(@rToDate,'')=''))

	
	--Added by dhananjay Start Mantis : 36629
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptDepositStudentLedgerGet]

	 @rOrgId int,
	 @rCode  nvarchar(max)='',
	 @rDepositHeadId int,
	 @rFromDate date='',
     @rToDate date='',
	 @rClassId int=0
     
AS
BEGIN
WITH Tb0 as
( 
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
			VA.SUId,
		    --CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		     DA.CreatedDateTime,
		     '' AS ExpenseType,
			VA.ClassId,
			ISNULL([sProcurement].[fnGetStockDepositeDetail](DA.DepositHeadId , DA.AcademicId, @rFromDate ,@rToDate ),'')AS StockItemName,--Added by dhananjay for mantis - 0034487
			(CASE WHEN DA.ReferenceSourceTypeId=1021 THEN 'Stock Return' ELSE 'Deposit Add' END) AS DepositType,		--add for mantis: 35522
			CASE WHEN DA.ReferenceSourceTypeId = 1021 THEN [sFee].[fnGetStockDepositeAdd] (DA.ReferenceSourceId) --Added for mantis : 39166
			ELSE '' END AS StockItemNameQuantity
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			Where 
			((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			--AND VA.BatchId = @rBatchId
			--AND ((VA.ClassId=@rClassId) OR (@rClassId=0))
			--AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(VA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='')
		    --AND ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND (DA.DepositHeadId = @rDepositHeadId)
		    
			
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    --CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
			VA.SUId,
		    DAJ. CreatedDateTime,
		   ISNULL(ETM.Title,'')AS ExpenseType,
		   VA.ClassId,
		   ISNULL([sProcurement].[fnGetStockDepositeDetail](DAJ.DepositHeadId , VA.AcademicId, @rFromDate ,@rToDate),'')AS StockItemName,--Added by dhananjay for mantis - 0034487
		   '' AS DepositType,		--add for mantis: 35522
		   CASE WHEN DAJ.ReferenceSourceTypeId = 2039 THEN [sFee].[fnGetStockDepositeAdjustment] (DAJ.ReferenceSourceId) --Added for mantis : 39166
			ELSE '' END AS StockItemNameQuantity
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId
			Where 
			((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			--AND VA.BatchId = @rBatchId
			--AND ((VA.ClassId=@rClassId) OR (@rClassId=0))
			--AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		    AND (ISNULL(VA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='')
			AND (DAJ.DepositHeadId = @rDepositHeadId)
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     --CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
			 VA.SUId,
		    DR.CreatedDateTime,
		     '' AS ExpenseType,
			 VA.ClassId,
			 ISNULL([sProcurement].[fnGetStockDepositeDetail](DR.DepositHeadId , VA.AcademicId, @rFromDate ,@rToDate),'')AS StockItemName,--Added by dhananjay for mantis - 0034487
			 '' AS DepositType,		--add for mantis: 35522
			 '' AS StockItemNameQuantity --Added for mantis : 39166
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where 
			((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			--AND VA.BatchId = @rBatchId
			--AND ((VA.ClassId=@rClassId) OR (@rClassId=0))
			--AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		    AND (ISNULL(VA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='')
			AND (DR.DepositHeadId = @rDepositHeadId)
)
,Tb1 as
( 
	SELECT DepositDate,Credit,Debit,SUId,Row_Number() over (order by CreatedDateTime asc) as OrderId,AcademicId,Code,StudentName,Class ,CreatedDateTime,ExpenseType,ClassId,StockItemName,DepositType,StockItemNameQuantity FROM Tb0--Added StockItemName by dhananjay for mantis - 0034487 
	--add DepositType for mantis: 35522
)
  SELECT T1.DepositDate,
         T1.[Credit],
         T1.[Debit],(Sum(T2.Credit) - Sum(T2.Debit)) as Balance,
         T1.SUId,
         --CASE WHEN @rIsBasedOnSUId=0 THEN  T1.Code Else ISNULL(T1.SUId,'') END AS Code,
		 T1.Code AS Code,
         T1.StudentName,
         T1.Class,
        T1.CreatedDateTime,
        T1.ExpenseType,
		T1.StockItemName,
		T1.DepositType,		--add for mantis: 35522
		T1.StockItemNameQuantity --Added for mantis : 39166
		 FROM Tb1 as T1
		 INNER JOIN Tb1 as T2 ON T1.OrderId >= T2.OrderId
		 Where 
		 ((T1.DepositDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((T1.DepositDate <= @rToDate) OR (ISNUll(@rToDate,'')=''))
		 AND ((T1.ClassId=@rClassId) OR (@rClassId=0))
		 Group By T1.DepositDate,T1.Credit,T1.Debit,T1.AcademicId,T1.SUId,T1.Code,T1.StudentName,T1.Class,T1.CreatedDateTime,T1.ExpenseType,T1.StockItemName,T1.DepositType,T1.StockItemNameQuantity--Added StockItemName by dhananjay for mantis - 0034487
		 --add T1.DepositType for mantis: 35522
		 Order by T1.CreatedDateTime
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptDepositSummaryFeeHeadWise]
	     
	  @rOrgId int, 
	  @rOrgGroupBatchId int = 0,         
      @rDepositHeadId int=0,         
      @rFromDate date='',
      @rToDate date='',           
      @rStudentName nvarchar(100)='',
	  @rStudentCode nvarchar(100)='',
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rIsBasedOnSUId bit = 0,
	  @rDepartmentId int=0,
	  @rSUId nvarchar(50)='',
	  @rBatchId int=0,
	  @rBuilder1 nvarchar(max)='',
      @rBuilder2 nvarchar(max)=''
   
AS
BEGIN
		SELECT 
			 DAJ.AdjustmentDate As DepositDate,
			 ISnull (DAJ.Amount,0)  AS Amount,
		     VA.Code As Code,
		     VA.Name As StudentName, 
		     VA.StudentId AS StudentId,
		     VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     'Adjustment' AS GroupType,
		     ES.Title As ExpenseType,
		     DAJ.Id As GroupID,
		     @rBuilder1 As builder1,
		     ES.Id AS ExpenseTypeId,
		     VA.DepartmentId,
	         VA.ClassId,
	         VA.DepartmentName,
	         VA.ClassOrderIndex,
	         @rFromDate AS FromDate,
	         @rToDate AS ToDate
		    
		FROM  sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ES ON ES.Id=DAJ.FeeDepositExpenseTypeId
		Where 
			  ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			  AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			  AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			  AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		      AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		      AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		      AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		      AND (VA.OrgId=@rOrgId OR @rOrgId=0)
			  AND  (VA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		      AND (DAJ.DepositHeadId = @rDepositHeadId)
		      AND ((DAJ.AdjustmentDate >= ISNULL(@rFromDate,'')) OR (ISNULL(@rFromDate,'')=''))
		      AND ((DAJ.AdjustmentDate <= ISNULL(@rToDate,'')) OR (ISNULL(@rToDate,'')=''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptDepositWisetransactionList] 
		
	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
	 @rOrgGroupBatchId int = 0,
     @rBatchId int,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
     @rFromDate date='',
     @rToDate date=''
   
      
AS
BEGIN

--select '' DepositDate,
--		0 as Amount,
--		0 AS Credit,
--		0 AS Debit,
--		0 As Balance,
--		'' as Code,
--		'' as StudentName,
--		0 as StudentId,
--convert(bigint,0) as StudentId,
--		'' as Class,
--		'' as SUId,
--		'' as GroupType,
--		0 as GroupID
	
	SELECT * 
	FROM	
	(
	SELECT 
			
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    'DepositeAdd' As GroupType,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    DA.CreatedDateTime,
		    VA.StudentId,
		    @rBuilder1 As builder1,
		    DA.DepositNumber AS Number,
			VA.OrganizationName AS Oraganization

			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			Where 
		   ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.DepositHeadId = @rDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		    AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((DA.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		    AND ((convert(date,DA.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    AND ((convert(date,DA.CreatedDateTime)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			-ISnull (DAJ.Amount,0) As Amount,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    'DepositeAdjustment' As GroupType,
		    
		    VA.Name As StudentName, 
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     DAJ.CreatedDateTime,
		     VA.StudentId,
		     @rBuilder1 As builder1,
		     DAJ.AdjustmentNumber AS Number,
			 VA.OrganizationName AS Oraganization

			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
		    AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
			AND ((DAJ.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
			AND ((convert(date,DAJ.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((convert(date,DAJ.CreatedDateTime)<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			-ISnull (DR.RefundAmount,0) AS Amount,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    'DepositeRefund' As GroupType,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId,
		    DR.CreatedDateTime,
		    VA.StudentId,
		    @rBuilder1 As builder1,
		    DR.RefundNumber AS Number,
			VA.OrganizationName AS Oraganization
		     
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
			AND ((DR.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
			AND ((convert(date,DR.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((convert(date,DR.CreatedDateTime)<=@rTodate) OR (ISNULL(@rToDate,'')=''))
    ) A
	Order by A.DepositDate Asc
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptExpenseTypeWiseDepositList]

	     
		   @rOrgId int,
		   @rOrgGroupBatchId int = 0,          
           @rDepositHeadId int=0,         
           @rFromDate date='',
           @rToDate date='',           
           @rStudentName nvarchar(100)='',
		  @rStudentCode nvarchar(100)='',
		  @rClassId int=0,
		  @rDivisionId int=0,
		  @rIsBasedOnSUId bit = 0,
		  @rDepartmentId int=0,
		  @rSUId nvarchar(50)='',
		  @rBatchId int=0,
		  @rBuilder1 nvarchar(max)='',
	      @rBuilder2 nvarchar(max)='',
		  @rOrderBy int = 0
	    
   
AS
BEGIN
		SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
			VA.RollNo AS RollNo,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.Studentid   AS AcademicId ,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    'Add' AS GroupType,
	        '' As ExpenseType,
	         DA.Id As GroupID,
	          @rBuilder1 As builder1,
			  @rOrderBy AS OrderBy
		    
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId  
		
			Where 
		  ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		    AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		    AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		    AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		    AND (VA.OrgId=@rOrgId OR @rOrgId=0)
		    AND (DA.DepositHeadId = @rDepositHeadId)
			AND (VA.BatchId=@rBatchId OR @rBatchId=0)
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((DA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))

	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			-ISnull (DAJ.Amount,0)  AS Amount,
			VA.RollNo AS RollNo,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     'Adjustment' AS GroupType,
		     ES.Title As ExpenseType,
		     DAJ.Id As GroupID,
		     @rBuilder1 As builder1,
			 @rOrderBy AS OrderBy
		    
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ES ON ES.Id=DAJ.FeeDepositExpenseTypeId
			Where 
				((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		    AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		    AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		    AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		    AND (VA.OrgId=@rOrgId OR @rOrgId=0)
		    AND (DAJ.DepositHeadId = @rDepositHeadId)
			AND (VA.BatchId=@rBatchId OR @rBatchId=0)
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			-ISnull (DR.RefundAmount,0)  AS Amount,
			VA.RollNo AS RollNo,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId, 
		    'Refund' AS GroupType,
		    '' As ExpenseType,
		    DR.Id As GroupID,
		    @rBuilder1 As builder1,
			@rOrderBy AS OrderBy
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		    AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		    AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		    AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		    AND (VA.OrgId=@rOrgId OR @rOrgId=0)
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((DR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		    AND (DR.DepositHeadId = @rDepositHeadId)
			AND (VA.BatchId=@rBatchId OR @rBatchId=0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeCertificateBasedOnStudentFeeGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
	    @rIsFeeInvoiceHeadwise bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rStatusId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0    
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		--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) AS FeeAmount,
		--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 FeeAmount,
		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)  AS FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader	   
  FROM 
		sFee.tFeeMaster FM 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId				
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId				
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId				
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId			
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
    
 --   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 
	--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
	--		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--		AND (SA1.ClassId=@rClassId OR @rClassId=0) 
	--		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			
	--		--AND (R.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
	--		--AND (R.CollectionGroupId=@rCollectionGroupId OR @rCollectionGroupId=0)
	--	WHERE		
	--		(R.SourceTypeId = 2001)
	--		AND (R.IsObsolete = 0) 
	--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
	--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--		AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	--			GROUP BY FeeSetupId,R.SourceId--,R.ReceiptNumber,R.ReceiptDate,PTM.Title,R.ChequeNo,R.BankName,R.ChequeDate
	--) R ON R.FeeSetupId = FS.Id AND FS.AcademicId = R.SourceId
    
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
         AND (
			 (@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			 ) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pRptFeeCertificateWithAllFeeDetailsGet]  
  
	@rAdmissionCategoryId int,  
	@rClassId int,  
	@rDivisionId int,   
	@rBatchId int,    
	@rBuilder1 nvarchar(max),  
	@rBuilder2 nvarchar(max),   
	@rOrgId int,  
	@rOrgGroupBatchId int,  
	@rStatusId int,  
	@rCommonBatch nvarchar(100),  
	@rDepartmentId int,  
	@rFromRollNo int,  
    @rToRollNo int,  
    @rCode nvarchar(20),  
    @rIsDetail bit=0,  
	@rIsFilter bit,  
	@rIsHeader bit,  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,
	@rOrgIds nvarchar(max) = '',
	@rClassStatusId int=0	  
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN       
BEGIN
	CREATE TABLE #FeeSetup (
		FeeId INT,
		Id INT,
		Amount DECIMAL(12, 2),
		ClassId INT,
		AdmissionCategoryId INT,
		AcademicId BIGINT,
		BatchId INT
	);
	
	INSERT INTO #FeeSetup (FeeId, Id, Amount, ClassId, AdmissionCategoryId, AcademicId, BatchId)
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount, 0) AS Amount,
			FS1.ClassId,
			FS1.AdmissionCategoryId,
			0 AS AcademicId,
			FS1.BatchId
		FROM sFee.tFeeSetup FS1
		WHERE FS1.BatchId = @rBatchId AND IsOptional = 0 AND (FS1.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		UNION ALL
		SELECT 
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.Amount, 0) AS Amount,
			FS1.ClassId,
			FS1.AdmissionCategoryId,
			FO.SourceId AS AcademicId,
			FS1.BatchId
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId = FS1.Id AND FO.SourceTypeId = 2001
		WHERE FS1.BatchId = @rBatchId AND IsOptional = 1 AND (FS1.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0);

	CREATE TABLE #ReceiptAmount (
    PaidAmount DECIMAL(12, 2),
    FeeSetupId INT,
    SourceId BIGINT
	);

	INSERT INTO #ReceiptAmount (PaidAmount, FeeSetupId, SourceId)
		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 		
		WHERE R.SourceTypeId = 2001 AND R.IsObsolete = 0 AND R.BatchId = @rBatchId
		GROUP BY R.SourceId, FeeSetupId;

END	  
BEGIN
	SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,   
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,   
		SA.ClassId,  
		SA.ClassName,
		SA.ClassOrderIndex,  
		SA.DivisionId,  
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		SA.RollNo,  
		SA.AcademicId,  
		SA.FirstName,  
		SA.MiddleName,  
		SA.LastName,  
		SA.Code,  
		SA.Name,
		SA.OrgId, 
		ISNULL(SA.SUID,'') AS SUID,
		ISNULL(SA.BatchName,'') BatchName,
		ISNULL(SA.GenderId,0) AS GenderId,
		DM.Id AS DepartmentId,  
		DM.Title AS DepartmentName,  
		ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,   
		ISNULL(FM.Id,0) AS FeeId,  
		ISNULL(FM.Title,'') AS Fee,
		FM.Code AS FeeCode,  
		FM.OrderIndex AS FeeOrderIndex,
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
		ISNULL(FHM.Title,'') AS FeeHead,  
		ISNULL(FHM.Code,'') AS FeeHeadCode,  
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  	   
		ISNULL(R.PaidAmount,0.00) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) AS TotalAmount,
		--Added by dhananjay for mantis : 39885
		TBM.FromDate AS FromDate,
		TBM.ToDate AS ToDate,
		ISNULL(SF.FatherName,'' ) AS FatherName,  
		ISNULL(SF.MotherName,'' ) AS MotherName,
		sFinanceCommon.fDefaultCurrencyTitleGet(O.OrgGroupId) AS CurrencyTitle
		--Added by dhananjay for mantis : 39885

	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #FeeSetup FS ON SA.ClassId = FS.ClassId AND SA.BatchId = FS.BatchId AND (SA.AcademicId = FS.AcademicId OR FS.AcademicId = 0)
		LEFT JOIN #ReceiptAmount R ON SA.AcademicId = R.SourceId AND R.FeeSetupId = FS.Id	 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId  
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId   
		INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId=DM.Id  
		INNER JOIN sSetup.tOrganizationMaster O ON O.Id=sa.OrgId   
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		LEFT JOIN  
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		--Added by dhananjay for mantis : 39885
		INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=SA.BatchId --AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId  
		--Added by dhananjay for mantis : 39885
	WHERE    
		((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))    
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))        
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		AND ((SA.Code=@rCode) OR (@rCode=''))  
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))    
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')   
		AND (  
		(@rFilterId = 0) -- All  
			OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
		)  
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
	ORDER By SA.ClassId,SA.AcademicId
END

DROP TABLE #ReceiptAmount
DROP TABLE #FeeSetup

--BEGIN -- For DataSet Drag & Drop
--	SELECT
--	'' AS Builder1,
--	'' AS Builder2,
--	CONVERT(bit,0) AS IsDetail,
--	CONVERT(bit,0) AS IsFilter,
--	CONVERT(bit,0) AS IsHeader,
--	CONVERT(bit,0) AS IsDisplayOrgGroup,
--	0 AS ClassId,
--	'' AS ClassName,
--	0 AS ClassOrderIndex,
--	0 AS DivisionId,
--	'' AS DivisionName,
--  0 AS DivisionOrderIndex,
--	'' AS ClassDivision,
--	0 AS RollNo,
--	CONVERT(BigInt,0) AS AcademicId,
--	'' AS FirstName,
--	'' AS MiddleName,
--	'' AS LastName,
--	'' AS Code,
--	'' AS Name,
--	0 AS OrgId,
--	'' AS SUID,
--	'' AS BatchName,
--	0 AS GenderId,
--	0 AS DepartmentId,
--	'' AS DepartmentName,
--	0 AS DepartmentOrderIndex,
--	0 AS FeeId,
--	'' AS Fee,
--	'' AS FeeCode,
--	0 AS FeeOrderIndex,
--	0 AS FeeHeadId,
--	'' AS FeeHead,
--	'' AS FeeHeadCode,
--	0 AS FeeHeadOrderIndex,
--	CONVERT(DECIMAL,0) AS PaidAmount,
--	CONVERT(DECIMAL,0) AS PendingAmount,
--	CONVERT(DECIMAL,0) AS TotalAmount,
--	Convert(Date,'') AS FromDate,
--	Convert(Date,'') AS ToDate,
--	'' AS FatherName,  
--	'' AS MotherName,
--	'' AS CurrencyTitle	
--END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeCircularDetailsGet]
		
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rFeeGroupId int=0,
		@rCollectionGroupId int = 0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0  
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	--Fee Setup
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,		
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0) AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			0 AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-0 AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeId,
			FS.FeeName,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroup,
			ISNULL(CGM.OrderIndex,0) AS CollectionGroupOrderIndex,
			0 AS ReceiptNumber,
			'' AS ReceiptDate,
			'' AS PayTypeTitle,
			'' AS ChequeNo,
			'' AS BankName,
			'' AS ChequeDate,
			SA.BatchName,
			0 AS ReceiptAmount,
			@rUptoDate AS UptoDate		--Mantis: 36496
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
					AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
					AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				
			UNION ALL

			SELECT
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
					AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
					AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,',')) OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,',')) OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,',')) OR @rOrgIds='')  
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
			AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
		(
			SELECT AT.SourceId 
			FROM sTransport.tAssignRoute AT 
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		 ) RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
		((@rIsExemption = 0 AND 1 = 1) OR (@rIsExemption = 1 AND ISNULL(FA.DiscountAmount,0) > 0))
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND	((CGM.Id=@rCollectionGroupId) OR (@rCollectionGroupId=0))   
		AND ((@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			)	
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  	     
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))

	UNION ALL
	
	-- Fee Receipt
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,		
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,		
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			0 AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			0 AS FAAmount,
			0 AS DiscountAmount,
			0 AS AdditionalAmount,
			0 AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeId,
			FS.FeeName,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroup,
			ISNULL(CGM.OrderIndex,0) AS CollectionGroupOrderIndex,
			ISNULL(R.ReceiptNumber,0) AS ReceiptNumber,
			R.ReceiptDate,
			R.PayTypeTitle,
			R.ChequeNo,
			R.BankName,
			R.ChequeDate,
			SA.BatchName,
			R.ReceiptAmount,
			@rUptoDate AS UptoDate		--Mantis: 36496
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
					AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
					AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.CreatedUserId=@rUserId) OR (@rUserId=0)) 
				    
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
					AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
					AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  	
				AND ((FS1.CreatedUserId=@rUserId) OR (@rUserId=0))      
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		INNER  JOIN
		(
			SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId,
				R.ReceiptNumber,
				R.ReceiptDate,
				PTM.Title AS PayTypeTitle,
				R.ChequeNo,
				R.BankName,
				R.ChequeDate,
				R.ReceiptAmount
		    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 
				INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  	     
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0)) 
			GROUP BY FeeSetupId,R.SourceId,R.ReceiptNumber,R.ReceiptDate,PTM.Title,R.ChequeNo,R.BankName,R.ChequeDate,R.ReceiptAmount
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
		(
			SELECT AT.SourceId 
			FROM sTransport.tAssignRoute AT 
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		) RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND	((CGM.Id=@rCollectionGroupId) OR (@rCollectionGroupId=0))   
		AND ((@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			)	
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeCircularGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
	    @rIsFeeInvoiceHeadwise bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rStatusId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
		@rClassStatusId int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		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 FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader,
       ISNULL(RT.BusRouteName,'') AS BusRouteName,
       ISNULL(RT.KM,0) AS KM
  FROM 
		sFee.tFeeMaster FM 
		
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=FS.AcademicId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		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 
				INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					GROUP BY FeeSetupId,R.SourceId 
		) R ON R.FeeSetupId = FS.Id AND FS.AcademicId = R.SourceId
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId,ISNULL(B.Title,'') AS BusRouteName,ISNULL(BM.Distance,0) AS KM 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 = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 


WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
         AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 
				 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeCollectionStudentwithFeewiseGet]  
  @rReportId int,  
  @rReceiptBookId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rFromDate date,  
  @rToDate date,  
  @rFromReceiptNo int,  
  @rToReceiptNo int,  
  @rBatchId int,  
  @rUserId bigint,  
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max),  
  @rIsCancel bit,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int,  
  @rCommonBatch nvarchar(100),  
  @rDepartmentId int,  
  @rFromRollNo int,  
     @rToRollNo int,  
     @rCode nvarchar(20),  
     @rIsDetail bit=0,  
  @rIsFilter bit,  
  @rIsHeader bit,  
  @rCreatedUserName nvarchar(100)='',  
  @rFeeHeadId nvarchar(max) = '',  
  @rIsDisplayOrgGroup bit=0,  
  @rPayTypeId int=0,  
  @rFeeId nvarchar(max) = '',  
  @rFilterId int=0,
  @rOrgIds nvarchar(max) = '',
  @rClassStatusId int=0,
  @rPayTypeIds nvarchar(max) = '' ,
  @rBankName nvarchar(200)='' ,
  @rUserAcessUserId bigint = 0  ,
  @rCustomGroupId smallint = 0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN  
SET @rBankName = sCommon.fSearchStringGet(@rBankName)  
--IF(@rReportId=10145)
--	BEGIN
--	SELECT   
--  @rBuilder1 AS Builder1,  
--  @rBuilder2 AS Builder2,  
--  @rIsCancel AS IsCancel,  
--  @rIsDetail AS IsDetail,  
--  @rIsFilter As IsFilter,  
--  @rIsHeader As IsHeader,  
--  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
--  R.Id AS ReceiptId,  
--  R.ReceiptNumber,  
--  SA.ClassId,  
--  SA.ClassName,  
--  SA.DivisionId,  
--  SA.DivisionName,  
--  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
--  SA.RollNo,  
--  SA.AcademicId,  
--  SA.FirstName,  
--  SA.MiddleName,  
--  SA.LastName,  
--  SA.Code,  
--  SA.Name,  
--  PTM.Title AS PayType,  
--  --R.ChequeNo,  
--  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
--  R.BankName,  
--  --R.ReceiptAmount,  ,
--  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
--  R.ReceiptDate,  
--  FM.Title AS FeeDetail,  
--  FM.Code AS FeeCode,  
--  FM.OrderIndex AS FeeOrderIndex,  
--  RD.Amount AS DetailAmount,  
--  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
--  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
--  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
--  ISNULL(FHM.Title,'') AS FeeHead,  
--  ISNULL(FHM.Code,'') AS FeeHeadCode,  
--  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
--  SA.OrgId,  
--  O.DisplayTitle AS OrgName,  
--  O.OrderIndex AS OrgOrderIndex,  
--  ISNULL(R.Remark,'') AS Remark,  
--  DM.Id AS DepartmentId,  
--  DM.Title AS DepartmentName,  
--  SA.ClassOrderIndex,  
--  ISNULL(SO.GenderId,0) AS GenderId,  
--  ISNULL(SA.BatchName,'') BatchName,  
--  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
--  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
--  R.ChequeDate,  
--  ISNULL(FM.Id,0) AS FeeId,  
--  ISNULL(FM.Title,'') AS Fee,  
--  ISNULL(SF.FatherName,'' ) AS FatherName,  
--  ISNULL(SF.MotherName,'' ) AS MotherName,
--  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
--  RD.Amount AS PaidAmount,
--  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,
--  PTM.Id AS PayTypeId,
--  ISNULL(SA.SUID,'') AS SUID ,
--  @rCustomGroupId AS CustomGroupId

--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sStudent.vStudentAcademic SA  
--   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
--  INNER JOIN sFee.tReceiptDetail RD  
--   ON RD.ReceiptId=R.Id  
--  INNER JOIN sFee.tFeeSetup FS  
--   ON FS.Id=RD.FeeSetupId  
--  INNER JOIN sFee.tFeeMaster FM  
--   ON FM.Id=FS.FeeId  
--  INNER JOIN sFee.tFeeHeadMaster FHM  
--   ON FHM.Id=FM.FeeHeadId  
--  INNER JOIN sFee.tReceiptBookMaster RBM   
--   ON RBM.Id=R.ReceiptBookId  
--  INNER JOIN sSetup.tDepartmentMaster DM  
--   ON SA.DepartmentId=DM.Id  
--  INNER JOIN sSetup.tOrganizationMaster O  
--   ON O.Id=sa.OrgId 
--    --for UserAccess Wise (in ReceiptListFeeHeadHeadwise report)
--  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND O.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  
 
--  LEFT JOIN sStudent.tStudentOther SO  
--   ON SO.StudentId = SA.StudentId  
--  LEFT JOIN sStudent.tStudentFamily SF  
--   ON SF.StudentId = SA.StudentId  
--    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
--     LEFT JOIN  
-- (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
--    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
--    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
--    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
--WHERE   
-- R.SourceTypeId = 2001  
-- AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
-- AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
-- AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
-- AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
-- AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
-- AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
-- AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
-- AND (R.IsObsolete = @rIsCancel)   
-- AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
-- AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
-- AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
-- AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
-- AND ((SA.Code=@rCode) OR (@rCode=''))  
-- AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
-- --AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
-- AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
-- AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
-- AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
-- AND (  
--  (@rFilterId = 0) -- All  
--     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
--     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
--     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
--   )  
--  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
--  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
--	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
--	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
-- ORDER BY R.ReceiptNumber  
--	END

--ELSE
--	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,
  PTM.Id AS PayTypeId,
  ISNULL(SA.SUID,'') AS SUID
  ,ISNULL(U.DisplayTitle,'') AS CreatedUser ,
   @rCustomGroupId AS CustomGroupId
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
  LEFT JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId		-- Changed JOIN INNER to LEFT for Mantis Id : 	0037148


  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
 AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
 AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  
	--END
 --ORDER BY R.Id 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[PRptFeeExcemptionReportFeewiseGet]
		
	@rReportId int, 
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	--@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0,
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN


		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		--	@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			--SA.RollNo,
			SA.Name,
			--SA.Code,
			SA.ClassId,
			SA.DivisionId,
		--	SA.ClassName,
		--	SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			--FS.Id AS FeeSetupId,
			--ISNULL(FS.IsVariable,0)AS IsVariable,
			--ISNULL(FS.Amount,0)AS Amount,
			--ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			--ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			--ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			--ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			--ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			--ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			--ISNULL(R.PaidAmount,0) AS PaidAmount,
			--ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--FS.ReceiptBookId,
			FS.FeeName,
			
		--	FS.FeeCode,
		--	FS.FeeOrderIndex,
		--	SA.OrgId,
		--	O.DisplayTitle AS OrgName,
		--	O.OrderIndex AS OrgOrderIndex,
		--	ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			--SA.DepartmentId,
			--SA.DepartmentName,
			--SA.ExemptionTypeId,
			--ISNULL(ETM.Title,'') AS ExemptionType,
			--FHM.Id AS FeeHeadId,
			--FHM.Title AS FeeHeadName,
			--FHM.OrderIndex AS FeeHeadOrderIndex,
			--@rFeeGroupId As FeeGroup,
			--SA.OrgGroupBatchId AS BatchId,
			--SA.BatchName AS BatchName,
		--	0.00 AS CancelAmount,
		--	0.00 AS Discount,
			--SM.Title AS Status,
			--SA.SUId AS SUId,
			--CONVERT(Date,NULL) AS LeftDate, -- For DataSet Refresh
			--'' AS ExemptedRemarkFeeWise,		-- For DataSet Refresh
			--'' AS RemarkWithComma,
			--'' AS AdditionalRemark,
			--'' AS NotApplicableRemark,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(FA.DiscountAmount,0.00)AS ExemptionAmount,
			ISNULL(FA.DiscountRemark,'') AS ExemptionRemark,
			--(STUFF((SELECT  ','+ tFA.DiscountRemark	FROM sFee.tFeeAllocation tFA INNER JOIN sFee.tFeeSetup tFS On tFS.Id = tFA.FeeSetupId
			--WHERE tFA.SourceId = FA.SourceId AND (tFS.FeeId IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,',')) OR @rFeeId='')
			--ORDER BY tFA.DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) AS ExemptionRemark,	
			ISNULL(FA.Remark,'') AS Remark,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ACM.Title AS FeeCategory,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FS.FeeId
			
			
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId --Added by dhananjay for Mantis Id : 35270
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo


	
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pRptFeeFolioGet]
		
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rReportId int=0,
		@rIsFilter bit=0,
	    @rIsDisplayOrgGroup bit=0,
	    @rIsFeeInvoiceHeadwise bit=0,
		@rOrgGroupBatchId int=0,
		@rCommonBatch nvarchar(100)='',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rStatusId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFirstName nvarchar(100)='',
	    @rFromInvoiceNumber int=0,
		@rToInvoiceNumber int=0,
		@rCreatedUserName nvarchar(100)='',
		@rFeeInvoiceIds nvarchar(max)='',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '' , 
		@rParentContactNo nvarchar(20) = '',
		@rClassStatusId int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
	BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)
	END		
			 
BEGIN

SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		SA.AcademicId,
		SA.Name,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.RollNo,
		SA.Code,
		SA.DepartmentId,
		SA.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		FID.Amount AS FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		SA.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		--(CASE WHEN ROW_NUMBER() OVER (PARTITION BY OM.Id ORDER BY OM.Id) = 1 THEN OM.OrgLogo ELSE NULL END) AS OrgLogo,
		OM.OrgLogo,
		SC.ParentContactNo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		OGM.Title AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		FI.InvoiceNumber,
 
		CASE WHEN FAL.DiscountAmount=0 THEN  null
		 ELSE FAL.DiscountAmount END AS ExemptionAmount,
		 RBM.GroupTitle,
		 SA.Suid,
		ISnull(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
       ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
		
       
       CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader,
       isnull(rt.pickuppoint,'') as Pickuppoint,
        isnull(rt.Droppoint,'') as Droppoint,
        SA.MiddleName AS FatherName,
		ISNULL(SF.FatherName,'') AS FatherNameFamily,
		ISNULL(SF.MotherName,'') AS MotherName,
		FI.InvoiceDate  ,
		ISNULL(SA.LastName,'') As LastName    
  FROM 
		sFee.tFeeInvoiceDetail FID 
		INNER JOIN sFee.tFeeInvoice FI ON FI.Id = FID.FeeInvoiceId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FID.FeeSetupId		
		INNER JOIN sStudent.vStudentAcademic SA ON FI.SourceTypeId = 2001 AND FI.SourceId = SA.AcademicId AND FI.BatchId=SA.BatchId AND FI.OrgGroupBatchId = SA.OrgGroupBatchId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId AND SA.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
		LEFT JOIN sSecurity.tUser U ON U.Id=FI.CreatedUserId
		LEFT JOIN sFee.tFeeAllocation FAL  ON FAL.FeeSetupId  = FS.Id AND FAL.SourceId = FI.SourceId 
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
       LEFT JOIN
	(SELECT AT.SourceId,BM.Title as pickuppoint,BM1.Title as droppoint 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))
    Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
    LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
    ) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	Left JOIN sStudent.tStudentCommunication SC  ON SC.StudentId = SA.StudentId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND ((FI.InvoiceNumber>=@rFromInvoiceNumber)OR(@rFromInvoiceNumber=0))
		AND ((FI.InvoiceNumber<=@rToInvoiceNumber)OR(@rToInvoiceNumber=0))
		AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
		AND (ISNULL(FI.Id,0) IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rFeeInvoiceIds,','))OR @rFeeInvoiceIds='')
		AND (
		 (@rFilterId = 0) -- All
		 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
		 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
		 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
		)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		AND ((SC.ParentContactNo= @rParentContactNo) OR (ISNULL(@rParentContactNo,'')=''))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pRptFeeInvoiceGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
	    @rIsFeeInvoiceHeadwise bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rStatusId int,
		@rFromRollNo Int,
	    @rToRollNo Int,
	    @rCode nvarchar(20),
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0,
		@rIsDetail bit --added by dhananjay for mantis : 040860    
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
   if(@rReportId =20886)
   begin
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		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) AS FeeAmount,
		ISNULL(R.PaidAmount,0.00) AS PaidAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader
	  ,SC.PermanentStreetOne as PermanentStreetOne         -- #Start Mentis 29588
	  ,SC.PermanentStreetTwo as PermanentStreetTwo
	  ,SC.PermanentStreetThree as PermanentStreetThree 
	  ,SC.PermanentCountry as PermanentCountry
	  ,SC.PermanentState as PermanentState
	  ,SC.PermanentCity as PermanentCity
	  ,SC.PermanentZipCode as PermanentZipCode
	  ,SC.PermanentContactNo as PermanentContactNo 
	  ,SF.FatherName as FatherName
	  ,SF.MotherName as MotherName     
	  ,ISNULL(SAD.AdmissionNumber,'') AS AdmissionNumber 
	  ,SO.DateOfBirth as DateOfBirth                     
	  ,sFee.fFeeAmountSumGet (FS.AcademicId)  as TotalAmount	 -- #End Mantis 29588  
	  ,SI.StudentPhoto as StudentPhoto            -- Mentis 29588
	  ,SC.PresentStreetOne    --#Start Mantis - 0030332
	  ,SC.PresentStreetTwo
	  ,SC.PresentCity        
	  ,OI.CertificateHeaderA4Portrait AS CertificateHeaderA4  
	  ,TBM.FromDate AS BatchStartDate
	  ,TBM.ToDate AS BatchEndDate,		--#End Mantis - 0030332
	  @rIsDetail AS IsDetail  --Added by dhananjay for mantis : 40860
	    
  FROM 
		sFee.tFeeMaster FM 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId				
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId				
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId				
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId			
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = FS.OrgId		--	Mantis - 0030332 changed OGM.Id to FS.OrgId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
    
    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 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			
			--AND (R.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
			--AND (R.CollectionGroupId=@rCollectionGroupId OR @rCollectionGroupId=0)
		WHERE		
			(R.SourceTypeId = 2001)
			AND (R.IsObsolete = 0) 
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				GROUP BY FeeSetupId,R.SourceId--,R.ReceiptNumber,R.ReceiptDate,PTM.Title,R.ChequeNo,R.BankName,R.ChequeDate
	) R ON R.FeeSetupId = FS.Id AND FS.AcademicId = R.SourceId

	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentID = FS.StudentID    -- Mentis 29588
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentID = FS.StudentID           -- Mentis 29588
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId = FS.StudentID 
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentID = FS.StudentID      -- Mentis 29588
    INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id = FS.BatchId				-- Mantis 0030332
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
        --AND ISNULL(FS.Amount,0.00) > 0
		 AND (
			 (@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			 ) 
       end

	   else
	     begin

		             SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		--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) AS FeeAmount,
		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 FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader
	  ,'' as PermanentStreetOne         -- #Start Mentis 29588
	  ,'' as PermanentStreetTwo
	  ,'' as PermanentStreetThree 
	  ,'' as PermanentCountry
	  ,'' as PermanentState
	  ,'' as PermanentCity
	  ,'' as PermanentZipCode
	  ,'' as PermanentContactNo 
	  ,'' as FatherName
	  ,'' as MotherName     
	  ,0 as AdmissionNumber 
	  ,SO.DateOfBirth  
	  , Convert(Decimal,0) as TotalAmount      
	  ,convert(varbinary(max),'') as StudentPhoto -- #End Mentis 29588
	  ,'' as PresentStreetOne    --#Start mentis - 0030332
	  ,'' as PresentStreetTwo
	  ,'' as PresentCity        
	  ,Convert(varbinary(max),'') as CertificateHeaderA4  --#End mentis - 0030332
	  ,Convert(date,'') AS BatchStartDate
	  ,Convert(date,'') AS BatchEndDate,
	  0 AS IsDetail --Added by dhananjay for mantis : 40860
  FROM 
		sFee.tFeeMaster FM 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
    
    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 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			
			--AND (R.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
			--AND (R.CollectionGroupId=@rCollectionGroupId OR @rCollectionGroupId=0)
		WHERE		
			(R.SourceTypeId = 2001)
			AND (R.IsObsolete = 0) 
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				GROUP BY FeeSetupId,R.SourceId--,R.ReceiptNumber,R.ReceiptDate,PTM.Title,R.ChequeNo,R.BankName,R.ChequeDate
	) R ON R.FeeSetupId = FS.Id AND FS.AcademicId = R.SourceId
    
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
         AND (
			 (@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			 ) 

		 end


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeInvoicePendingStudentListGet]
		
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rIsFilter bit=0,
	    @rIsDisplayOrgGroup bit=0,
		@rOrgGroupBatchId int=0,
		@rCommonBatch nvarchar(100)='',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rStatusId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rCollectionGroupId int=0,
	    @rReportId int = 0,
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.Name,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.RollNo,
		SA.Code,
		SA.DepartmentId,
		SA.DepartmentName,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		SA.BatchName,
		FS.Amount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeSetup FS ON FS.ClassId = SA.ClassId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId AND SA.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sFee.tFeeInvoice FI ON FI.SourceId =SA.AcademicId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
       LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND FI.SourceId IS NULL
		AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 	
        AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')	
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')	
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))		     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeInvoiceRegisterGet]
		
		@rOrgGroupBatchId int,
		@rOrgId int=0,
		@rBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rIdNo nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rReceiptBookId int=0,
		@rFromInvoiceNumber int=0,
		@rToInvoiceNumber int=0,
		@rFromDate date='',
		@rToDate date='',
		@rOrgGroupId int,
		@rCollectionGroupId int = 0,
		@rDepartmentId int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		END			 
			 
BEGIN
		CREATE Table #InvoiceDetail
		(
		FeeInvoiceId bigint,
		FeeCode nvarchar(100),
		FeeAmount decimal(12,2),
		FeeOrder int,
		OrganizationName nvarchar(200),
		SUId nvarchar(50),
		Code nvarchar(20),
		ClassDiv nvarchar(200),
		RollNo int,
		Name nvarchar(300),
		InvoiceNumber int,
		InvoiceDate Date,
		InvoiceAmount decimal(12,2),
		ReceiptBookName nvarchar(100),
		CollectionGroupName nvarchar(100),
		VariableAmount decimal(12,2),
		DiscountAmount decimal(12,2),
		AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2)
		)
		
		INSERT INTO #InvoiceDetail
		SELECT
			FeeInvoiceId,
			FM.Code,
			ID.Amount,
			FM.OrderIndex,
			SA.OrganizationName,
			SA.SUId,
			SA.Code,
			SA.ClassName+' - '+ SA.DivisionName AS Class,
			RollNo,
			Name,
			FI.InvoiceNumber,
			FI.InvoiceDate,
			FI.InvoiceAmount,
			RBM.Title,
			CGM.Title,
			FA.VariableAmount,
			FA.DiscountAmount,
			FA.AdditionalAmount,
			FA.NotApplicableAmount
		FROM
		sFee.tFeeInvoiceDetail ID 
		INNER JOIN sFee.tFeeSetup FS ON ID.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sFee.tFeeInvoice FI ON FI.Id = ID.FeeInvoiceId AND FI.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=FI.SourceId	
			AND (SA.ClassId=@rClassId OR @rClassId=0) 
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND (SA.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		INNER JOIN sSetup.tClassMaster CM ON Cm.Id = SA.ClassId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FI.ReceiptBookId
		INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FI.CollectionGroupId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FI.SourceTypeId= FA.SourceTypeId AND FI.SourceId= FA.SourceId
		WHERE 
		((SA.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))	
		AND (FI.SourceTypeId=2001)
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND ((FI.InvoiceNumber>=@rFromInvoiceNumber)OR(@rFromInvoiceNumber=0))
		AND ((FI.InvoiceNumber<=@rToInvoiceNumber)OR(@rToInvoiceNumber=0))
		AND ((FI.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
		AND ((FI.CollectionGroupId=@rCollectionGroupId)OR(@rCollectionGroupId=0))
		AND ((FI.InvoiceDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))
		AND ((FI.InvoiceDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((FI.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		ORDER BY FI.InvoiceNumber DESC
			
	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT  DISTINCT ',' + QUOTENAME(ID.FeeCode)
                       FROM #InvoiceDetail ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')   
 
    SELECT @query = 
    'SELECT  
			P.*,
            ID.VariableAmount,
            ID.DiscountAmount,
            ID.AdditionalAmount,
            ID.NotApplicableAmount 
     FROM
    (SELECT  
        FeeInvoiceId,   
        OrganizationName,
        SUId,
        Code,
        ClassDiv,
        RollNo,
        Name,
        InvoiceNumber,
        CONVERT(varchar(11),InvoiceDate,103) AS InvoiceDate,
        FeeCode, 
        FeeAmount,
        ReceiptBookName,
        CollectionGroupName,
        InvoiceAmount
    FROM #InvoiceDetail)X
    PIVOT 
    (
         SUM(FeeAmount) 
         FOR [FeeCode] IN (' +  @cols + ')
    ) P
    LEFT JOIN
	(
		SELECT
		    FeeInvoiceId,
			SUM(VariableAmount) AS VariableAmount,
			SUM(DiscountAmount) AS DiscountAmount,
			SUM(AdditionalAmount) AS AdditionalAmount,
			SUM(NotApplicableAmount) AS NotApplicableAmount
		FROM  
			#InvoiceDetail
			GROUP BY FeeInvoiceId
    ) ID ON ID.FeeInvoiceId = P.FeeInvoiceId
    '
	EXECUTE(@query)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeMonthlyRegisterGet]
		
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rFromDate date='',
		@rToDate date='',
		@rFromReceiptNo int=0,
		@rToReceiptNo int=0,
		@rBatchId int,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)=0,
		@rBuilder2 nvarchar(max)=0,
		@rIsDetail bit=0,
		@rIsCancel bit=0,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int=0,
		@rPaytypeId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20),
	    @rIsFilter bit=0,
	    @rIsHeader bit=0,
	    @rCreatedUserName nvarchar(100)='',
	    @rFeeHeadId nvarchar(max) = '',
	    @rIsDisplayOrgGroup bit=0,
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
		@rClassStatusId int=0--,
	    --@rOrgIds nvarchar(max) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN

DECLARE @lStartMonth AS INT

SELECT @lStartMonth = MONTH(BM.FromDate) FROM sSetup.tBatchMaster BM WHERE BM.Id=@rBatchId

DECLARE @lMonth1 AS INT
DECLARE @lMonth2 AS INT
DECLARE @lMonth3 AS INT
DECLARE @lMonth4 AS INT
DECLARE @lMonth5 AS INT
DECLARE @lMonth6 AS INT
DECLARE @lMonth7 AS INT
DECLARE @lMonth8 AS INT
DECLARE @lMonth9 AS INT
DECLARE @lMonth10 AS INT
DECLARE @lMonth11 AS INT
DECLARE @lMonth12 AS INT

IF (@lStartMonth = 1)
BEGIN
	SET @lMonth1 = 1
	SET @lMonth2 = 2
	SET @lMonth3 = 3
	SET @lMonth4 = 4
	SET @lMonth5 = 5
	SET @lMonth6 = 6
	SET @lMonth7 = 7
	SET @lMonth8 = 8
	SET @lMonth9 = 9
	SET @lMonth10 = 10
	SET @lMonth11 = 11
	SET @lMonth12 = 12
END

ELSE IF (@lStartMonth = 2)
BEGIN
	SET @lMonth1 = 2
	SET @lMonth2 = 3
	SET @lMonth3 = 4
	SET @lMonth4 = 5
	SET @lMonth5 = 6
	SET @lMonth6 = 7
	SET @lMonth7 = 8
	SET @lMonth8 = 9
	SET @lMonth9 = 10
	SET @lMonth10 = 11
	SET @lMonth11 = 12
	SET @lMonth12 = 1
END

ELSE IF (@lStartMonth = 3)
BEGIN
	SET @lMonth1 = 3
	SET @lMonth2 = 4
	SET @lMonth3 = 5
	SET @lMonth4 = 6
	SET @lMonth5 = 7
	SET @lMonth6 = 8
	SET @lMonth7 = 9
	SET @lMonth8 = 10
	SET @lMonth9 = 11
	SET @lMonth10 = 12
	SET @lMonth11 = 1
	SET @lMonth12 = 2
END

ELSE IF (@lStartMonth = 4)
BEGIN
	SET @lMonth1 = 4
	SET @lMonth2 = 5
	SET @lMonth3 = 6
	SET @lMonth4 = 7
	SET @lMonth5 = 8
	SET @lMonth6 = 9
	SET @lMonth7 = 10
	SET @lMonth8 = 11
	SET @lMonth9 = 12
	SET @lMonth10 = 1
	SET @lMonth11 = 2
	SET @lMonth12 = 3
END

ELSE IF (@lStartMonth = 5)
BEGIN
	SET @lMonth1 = 5
	SET @lMonth2 = 6
	SET @lMonth3 = 7
	SET @lMonth4 = 8
	SET @lMonth5 = 9
	SET @lMonth6 = 10
	SET @lMonth7 = 11
	SET @lMonth8 = 12
	SET @lMonth9 = 1
	SET @lMonth10 = 2
	SET @lMonth11 = 3
	SET @lMonth12 = 4
END

ELSE IF (@lStartMonth = 6)
BEGIN
	SET @lMonth1 = 6
	SET @lMonth2 = 7
	SET @lMonth3 = 8
	SET @lMonth4 = 9
	SET @lMonth5 = 10
	SET @lMonth6 = 11
	SET @lMonth7 = 12
	SET @lMonth8 = 1
	SET @lMonth9 = 2
	SET @lMonth10 = 3
	SET @lMonth11 = 4
	SET @lMonth12 = 5
END

ELSE IF (@lStartMonth = 7)
BEGIN
	SET @lMonth1 = 7
	SET @lMonth2 = 8
	SET @lMonth3 = 9
	SET @lMonth4 = 10
	SET @lMonth5 = 11
	SET @lMonth6 = 12
	SET @lMonth7 = 1
	SET @lMonth8 = 2
	SET @lMonth9 = 3
	SET @lMonth10 = 4
	SET @lMonth11 = 5
	SET @lMonth12 = 6
END

ELSE IF (@lStartMonth = 8)
BEGIN
	SET @lMonth1 = 8
	SET @lMonth2 = 9
	SET @lMonth3 = 10
	SET @lMonth4 = 11
	SET @lMonth5 = 12
	SET @lMonth6 = 1
	SET @lMonth7 = 2
	SET @lMonth8 = 3
	SET @lMonth9 = 4
	SET @lMonth10 = 5
	SET @lMonth11 = 6
	SET @lMonth12 = 7
END

ELSE IF (@lStartMonth = 9)
BEGIN
	SET @lMonth1 = 9
	SET @lMonth2 = 10
	SET @lMonth3 = 11
	SET @lMonth4 = 12
	SET @lMonth5 = 1
	SET @lMonth6 = 2
	SET @lMonth7 = 3
	SET @lMonth8 = 4
	SET @lMonth9 = 5
	SET @lMonth10 = 6
	SET @lMonth11 = 7
	SET @lMonth12 = 8
END

ELSE IF (@lStartMonth = 10)
BEGIN
	SET @lMonth1 = 10
	SET @lMonth2 = 11
	SET @lMonth3 = 12
	SET @lMonth4 = 1
	SET @lMonth5 = 2
	SET @lMonth6 = 3
	SET @lMonth7 = 4
	SET @lMonth8 = 5
	SET @lMonth9 = 6
	SET @lMonth10 = 7
	SET @lMonth11 = 8
	SET @lMonth12 = 9
END

ELSE IF (@lStartMonth = 11)
BEGIN
	SET @lMonth1 = 11
	SET @lMonth2 = 12
	SET @lMonth3 = 1
	SET @lMonth4 = 2
	SET @lMonth5 = 3
	SET @lMonth6 = 4
	SET @lMonth7 = 5
	SET @lMonth8 = 6
	SET @lMonth9 = 7
	SET @lMonth10 = 8
	SET @lMonth11 = 9
	SET @lMonth12 = 10
END

ELSE IF (@lStartMonth = 12)
BEGIN
	SET @lMonth1 = 12
	SET @lMonth2 = 1
	SET @lMonth3 = 2
	SET @lMonth4 = 3
	SET @lMonth5 = 4
	SET @lMonth6 = 5
	SET @lMonth7 = 6
	SET @lMonth8 = 7
	SET @lMonth9 = 8
	SET @lMonth10 = 9
	SET @lMonth11 = 10
	SET @lMonth12 = 11
END

BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsCancel AS IsCancel,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,

		[sCommon].[fGetMonthName](@lMonth1) AS Month1,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth1,@rReceiptBookId) AS Detail1,

		[sCommon].[fGetMonthName](@lMonth2) AS Month2,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth2,@rReceiptBookId) AS Detail2,

		[sCommon].[fGetMonthName](@lMonth3) AS Month3,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth3,@rReceiptBookId) AS Detail3,

		[sCommon].[fGetMonthName](@lMonth4) AS Month4,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth4,@rReceiptBookId) AS Detail4,

		[sCommon].[fGetMonthName](@lMonth5) AS Month5,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth5,@rReceiptBookId) AS Detail5,

		[sCommon].[fGetMonthName](@lMonth6) AS Month6,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth6,@rReceiptBookId) AS Detail6,

		[sCommon].[fGetMonthName](@lMonth7) AS Month7,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth7,@rReceiptBookId) AS Detail7,

		[sCommon].[fGetMonthName](@lMonth8) AS Month8,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth8,@rReceiptBookId) AS Detail8,

		[sCommon].[fGetMonthName](@lMonth9) AS Month9,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth9,@rReceiptBookId) AS Detail9,

		[sCommon].[fGetMonthName](@lMonth10) AS Month10,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth10,@rReceiptBookId) AS Detail10,

		[sCommon].[fGetMonthName](@lMonth11) AS Month11,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth11,@rReceiptBookId) AS Detail11,

		[sCommon].[fGetMonthName](@lMonth12) AS Month12,
		[sFee].[fReceiptNumberDateGet](SA.AcademicId ,@lMonth12,@rReceiptBookId) AS Detail12
		
  FROM 
		  sStudent.vStudentAcademic SA
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		  
WHERE 
	(SA.OrgGroupBatchId = @rOrgGroupBatchId)
    AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
	AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
	AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	 AND (
			(@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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeePendingAllBatchGet]
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int='',
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',	
		@rBuilder2 nvarchar(max)='',
		@rIsDetail bit=0,
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId  int=0,
		@rOrgGroupId int = 0,
		@rOrgIds nvarchar(max) = '',
		@rReportType int=1,    
	    @rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	
	DECLARE @p as TempPendingFee

	IF(@rReportType=1)
	BEGIN
	
		INSERT INTO  @p 
	 
	SELECT 
	
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		--change by megha for 0027384
	    '' AS FatherContactNo,
		'' AS MotherContactNo,
		'' AS WhatsAppContactNo --added by dhananjay for : 37272
  FROM 
  
			 sStudent.vStudentAcademic SA
			 Left join [sStudent].[tStudentCommunication] SC ON SC.studentId=SA.studentId
			
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			    AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		AND SA1.ClassId = FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
		        AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			WHERE	
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
		
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sSetup.tBatchMaster BM 
			ON BM.Id=SA.BatchId	
      LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
        LEFT JOIN
	(SELECT AT.SourceId ,B.OrgGroupBatchId,B.Title As Pickup,B1.Title As DRoppoint 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))
	Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
    LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 ) RT
    ON RT.SourceId = SA.StudentId 
    AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			(CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
		   AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			    )
		   AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))	   
			Order by SA.RollNo
 
		SELECT
			@rBuilder1 AS Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName,
		    Pickup,
			DRoppoint,
			PresentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo,
			'' AS WhatsAppContactNo --added by dhananjay for : 37272
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo,SUID,ClassOrderIndex,DivisionOrderIndex,FatherContactNo,MotherContactNo,WhatsAppContactNo--added(WhatsAppContactNo) by dhananjay for : 37272
			ORDER BY AcademicId Desc
	END
	ELSE
	BEGIN
	
	INSERT INTO  @p 
	SELECT 
	
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FAS.FeeAmount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		FM.Title AS FeeName, 
		FM.Code AS FeeCode,
		--FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FM.OrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo,
		'' AS WhatsAppContactNo --added by dhananjay for : 37272

  FROM	 sStudent.vStudentAcademic SA
        INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
        LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
        LEFT JOIN
		(SELECT AT.SourceId ,B.OrgGroupBatchId,B.Title As Pickup,B1.Title As DRoppoint 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))
	    Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
        LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
        ) RT
        ON RT.SourceId = SA.StudentId 
        AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
        AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	   
	    WHERE	
			(CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND ISNULL(FAS.ToPayAmount,0) !=0
		   AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			    )
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		   AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
			Order by SA.RollNo

			
				SELECT
			@rBuilder1 AS Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName,
		    Pickup,
			DRoppoint,
			PresentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo,
			'' AS WhatsAppContactNo --added by dhananjay for : 37272
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo,SUID,ClassOrderIndex,
			DivisionOrderIndex
			
			ORDER BY AcademicId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeePendingDetailListAsOnDateGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0,
		@rFeeHeadId nvarchar(max) = '',
	    @rIsDisplayOrgGroup bit=0,
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''   
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeName,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))				
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)			
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)			
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))   
			Order by SA.RollNo
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeePendingDetailListAsOnDateOtherGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0,
		@rFeeHeadId nvarchar(max) = '',
	    @rIsDisplayOrgGroup bit=0,
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = '',
		@rReportType int=1,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''    
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
IF(@rReportType=1)
BEGIN
print '1'
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeName,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId=FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))				
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)	
			AND (SA.classstatusid = @rClassStatusId OR @rClassStatusId=0)		
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)			
			 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 	
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			Order by SA.RollNo
END
ELSE
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0)AS PendingAmount,
		--ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		
		ISNULL(FA.Remark,'') AS Remark,
		FM.Title AS FeeName, 
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  FROM sStudent.vStudentAcademic SA  
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FAS.FeeSetupId AND FA.SourceId=SA.AcademicId 		
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)			
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND (SA.classstatusid = @rClassStatusId OR @rClassStatusId=0)	
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)			
			AND ISNULL(FAS.ToPayAmount,0) !=0
			 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 	
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			Order by SA.RollNo
END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet]

	@rReportId int=0,
	@rReceiptBookId int=0,
	@rReceiptBookIds nvarchar(max) = '',
	@rAdmissionCategoryId int=0,
	@rAdmissionCategoryIds nvarchar(max) = '',
	@rClassId int=0,
	@rDivisionId int=0,
	@rUptoDate date='',
	@rBatchId int=0,
	@rUserId bigint=0,
	@rBuilder1 nvarchar(max) = '',
	@rBuilder2 nvarchar(max) = '',
	@rIsDetail bit=0,
	@rOrgId int=0,
	@rOrgGroupBatchId int=0,
	@rStatusId int=0,
	@rCommonBatch nvarchar(100) = '',
	@rDepartmentId int=0,
	@rFromRollNo int=0,
	@rToRollNo int=0,
	@rCode nvarchar(20)='',
	@rIsFilter bit=0,
	@rIsHeader bit=0,
	@rCreatedUserName nvarchar(20) = '',
	@rIsReceiptBookGroup bit=0,
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rOrgIds  nvarchar(max) = '',
	@rPayDate date='',
	@rCollectionGroupId int =0,
	@rCastCategoryId int = 0,
	@rReportType int=0,
	@rClassStatusId int=0 ,
	@rCollectionGrupId nvarchar(max) ='',
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	CREATE TABLE #TempIsOptional
	(
		FeeId int,
		Id int,
		IsOptional bit,
		IsVariable bit,
		Amount decimal(12,2),
		StartDate date,
		EndDate date,
		BatchId int,
		ReceiptBookId int,
		AcademicId bigint,
		FeeName nvarchar(100),
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max),
		FeeOrderIndex int,
		CollectionGroupOrderIndex int,
		CollectionGroupMasterRemark nvarchar(500),
		FeeDuration nvarchar(100)						--add
	)

	INSERT INTO #TempIsOptional
		SELECT
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.IsOptional,0)AS IsOptional,
			ISNULL(FS1.IsVariable,0)AS IsVariable,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
			FS1.BatchId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS AcademicId,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			FM.OrderIndex,
			CGM.OrderIndex  AS CollectionGroupOrderIndex,
			CGM.Remark AS CollectionGroupMasterRemark,
			FS1.FeeDuration AS FeeDuration							--add
		FROM
			sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id
			--AND RBM.Id = CGM.ReceiptBookId
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (FS1.AdmissionCategoryId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryIds,',')) OR @rAdmissionCategoryIds='')
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND (FS1.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND (FS1.IsOptional=0)
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')

	UNION ALL

		SELECT
			FS1.FeeId,
			FS1.Id,
			ISNULL(FS1.IsOptional,0)AS IsOptional,
			ISNULL(FS1.IsVariable,0)AS IsVariable,
			ISNULL(FS1.Amount,0)AS Amount,
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
			FS1.BatchId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS AcademicId,
			FM.Title AS FeeName,
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			FM.OrderIndex,
			CGM.OrderIndex  AS CollectionGroupOrderIndex,
			CGM.Remark AS CollectionGroupMasterRemark,
			FS1.FeeDuration AS FeeDuration					--add
		FROM
			sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId

			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id
			--AND RBM.Id = CGM.ReceiptBookId
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (FS1.AdmissionCategoryId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryIds,',')) OR @rAdmissionCategoryIds='')
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND (FS1.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND (FS1.IsOptional=1)
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')

	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint
	)

	INSERT INTO #TempReceipt
	SELECT
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
	FROM
		sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId
		AND (SA1.ClassId=@rClassId OR @rClassId=0)
		AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
	WHERE
		(R.SourceTypeId = 2001)
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (R.IsObsolete = 0)
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
	GROUP BY FeeSetupId,R.SourceId

	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint
	)

	INSERT INTO #TempAssignRoute
	SELECT
		AT.SourceId
	FROM
		sTransport.tAssignRoute AT
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))

	IF(@rReportType=1)
	BEGIN
		SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeName,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId
		END) AS ReceiptBookId,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')
		END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)
		END) AS ReceiptOrderIndex,
		--FS.ReceiptBookId,
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,
		@rPayDate AS PayDate,
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,
		ISNULL(CCM.Title,'') AS CastCategoryName,
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		FS.CollectionGroupId,
		FS.CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FS.FeeOrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	 SA.GenderId,
	 SA.FirstName as StudentName,
	 FS.CollectionGroupOrderIndex,
	 SA.SUId AS SUId,
	 FS.CollectionGroupMasterRemark,
	 SA.LastName as LastName,
	 FS.FeeDuration as FeeDuration,	--add
	 --Mantis: 31868, start
	 case when @rReportId=10147
		then O.OrgLogo
		else null end AS OrgLogo,
	 O.SmallAddress1 AS OrgAddress,
	 --Mantis: 31868, end
	 ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,       --Mantis - 0032963
	 ISNULL(ACM.Title,'') AS FeeCategory, -- Added by Dhananjay for Mantis Id - 35029
	 ISNULL(SSF.FatherMail,'') AS FatherMail, --add for mantis : 0036510
	 ISNULL(SSF.MotherMail,'') AS MotherMail, --add for mantis : 0036510
	 ISNULL(SC.ParentEmail,'') AS ParentEmail, -- add for mantis : 0039011
	 ISNULL(DM.OrderIndex,9999) AS DepartmentOrderIndex-- Added by Dhananjay for Mantis Id - 42557
	FROM
		sStudent.vStudentAcademic SA
		INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrganizationMaster O ON
		SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM
		ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sStudent.tStudentCommunication SC
		ON SC.StudentId = SA.StudentId
		LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId = SA.StudentId
		LEFT JOIN sCommon.tCastCategoryMaster CCM
		ON CCM.Id = SO.CastCategoryId
		INNER JOIN sFee.tFeeHeadMaster FHM
		ON FHM.Id = FS.FeeHeadId

		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
		INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id = SA.AdmissionCategoryId -- Added by Dhananjay for Mantis Id - 35029
		INNER JOIN sSetup.tDepartmentMaster DM On DM.Id = SA.DepartmentId-- Added by Dhananjay for Mantis Id - 42557
	WHERE
		SA.OrgGroupBatchId = @rOrgGroupBatchId
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
		AND (
				(@rFilterId = 0) -- All
				OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	Order by SA.RollNo
	END
	ELSE
	BEGIN
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00) PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		--FS.FeeName,
		FM.Title AS FeeName,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId
		END) AS ReceiptBookId,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')
		END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)
		END) AS ReceiptOrderIndex,
		ISNULL(FS.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,
		@rPayDate AS PayDate,
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,
		ISNULL(CCM.Title,'') AS CastCategoryName,
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FM.OrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		CGM.OrderIndex  AS CollectionGroupOrderIndex,
		SA.SUId AS SUId,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo, --Mantis - 0032963
		ISNULL(ACM.Title,'') AS FeeCategory, -- Added by Dhananjay for Mantis Id - 35029
		ISNULL(SSF.FatherMail,'') AS FatherMail, --add for mantis : 0036510
		ISNULL(SSF.MotherMail,'') AS MotherMail, --add for mantis : 0036510
		ISNULL(SC.ParentEmail,'') AS ParentEmail, --add for mantis : 0039011
		ISNULL(DM.OrderIndex,9999) AS DepartmentOrderIndex-- Added by Dhananjay for Mantis Id - 42557

	FROM
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FAS.FeeSetupId AND FA.SourceId=SA.AcademicId
		LEFT JOIN sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
        LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
		AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
		INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id = SA.AdmissionCategoryId -- Added by Dhananjay for Mantis Id - 35029
		INNER JOIN sSetup.tDepartmentMaster DM On DM.Id = SA.DepartmentId-- Added by Dhananjay for Mantis Id - 42557
	WHERE
		SA.OrgGroupBatchId = @rOrgGroupBatchId
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
		AND ISNULL(FAS.ToPayAmount,0.00) !=0
		AND (
				(@rFilterId = 0) -- All
				OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
	Order by SA.RollNo
	END

	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #TempAssignRoute



	--SELECT
	--    '' as Builder1,
	--	'' as Builder2,
	--	Convert(bit,0) as IsDetail,
	--	Convert(bit,0) as IsFilter,
	--	Convert(bit,0) as IsHeader,
	--	Convert(bit,0) as IsDisplayOrgGroup,
	--	Convert(bigint,0) as AcademicId,
	--	0 As RollNo,
	--	'' as Name,
	--	'' As Code,
	--	0 as ClassId,
	--	0 as DivisionId,
	--	'' as ClassName,
	--	'' as DivisionName,
	--	0 as DivisionOrder,
	--	 '' as ClassDivision,
	--	0 as FeeSetupId,
	--	Convert(bit,0) as IsVariable,
	--	 0.00 As Amount,
	--	'2001-01-30' AS StartDate,
	--	'2001-01-30' As EndDate,
	--	0.00 As FAAmount,
	--	0.00 As DiscountAmount,
	--	0.00 As AdditionalAmount,
	--	0.00 As PaidAmount,
	--	0.00 As  PendingAmount,
	--	'' AS Remark,
	--	--FS.FeeName,
	--	'' AS FeeName,
	--	0 AS FeeHeadId,
	--	'' AS FeeHeadName,
	--	0 As FeeHeadOrderIndex,
	--	0 As OrgId,
	--	'' AS OrgName,
	--	0 AS OrgOrderIndex,
	--	0 AS ReceiptBookId,
	--	'' AS ReceiptBookTitle,
	--	0 AS ReceiptOrderIndex,
	--	'' AS ReceiptBookFullTitle,
	--	'' AS RecieptBookAddress1,
	--	'' AS RecieptBookAddress2,
	--	'' As Remark1,
	--	0 As OrgGroupBatchId,
	--	0 As DepartmentId,
	--	'' AS DepartmentName,
	--	'' AS ParentContactNo,
	--	'' AS ReferenceRemark,
	--	'2001-01-30' AS PayDate ,
	--	0 AS CastCategoryId,
	--	'' AS CastCategoryName,
	--	0 AS CastCategoryOrderIndex,
	--	'' AS ReportTemplate,
	--	0 AS CollectionGroupId,
	--	'' AS CollectionGroup,
	--	'' AS BatchName,
	--	'' AS FatherName,
	--	 '' AS FatherContactNo,
	--	 '' AS MotherName,
	--	 '' AS MotherContactNo,
	--	0 AS FeeOrderIndex,
	--	'' AS Address,
	--	'' AS StudentContactNo,
	--    '' as StudentName,
	--	0 As GenderId,
	-- 0 AS CollectionGroupOrderIndex,
	-- '' AS SUId,
	-- '' AS CollectionGroupMasterRemark,
	-- '' AS LastName,
	-- '' AS FeeDuration,
	----Mantis: 31868, start
	-- Convert(varbinary(max),'') AS OrgLogo,
	-- '' AS OrgAddress,
	----Mantis: 31868, end
	--'' As WhatsAppContactNo,
	--'' As FeeCategory,
	--'' AS FatherMail,
	--'' AS MotherMail,
	--'' AS ParentEmail
	--0 AS DepartmentOrderIndex

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet_CTE]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = ''
		
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

CREATE TABLE #TempAcademic
(
    AcademicId bigint,
    StudentId bigint,
    RollNo int,
    Name nvarchar(150),
    Code nvarchar(20),
    ClassId int,
    DivisionId int,
    ClassName nvarchar(100),
     DivisionName nvarchar(100),
 DivisionOrder int,
 ClassDivision nvarchar(100),
 OrgId int,
 OrgGroupBatchId int,
 BatchId int,
 DepartmentId int,
 DepartmentName nvarchar(100),
 AdmissionCategoryId int,
 BatchName nvarchar(100)
)

INSERT INTO #TempAcademic
SELECT
SA.AcademicId,
SA.StudentId,
SA.RollNo,
SA.Name,
SA.Code,
SA.ClassId,
SA.DivisionId,
SA.ClassName,
SA.DivisionName,
SA.DivisionOrder,
SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
SA.OrgId,
SA.OrgGroupBatchId,
SA.BatchId,
SA.DepartmentId,
SA.DepartmentName,
SA.AdmissionCategoryId,
SA.BatchName
FROM sStudent.vStudentAcademic SA  
  WHERE     SA.OrgGroupBatchId = @rOrgGroupBatchId
  			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))		
		 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = '')) 

 

--DROP TABLE #TEMPTABLE

--With Academic_CTE
--(AcademicId,StudentId,RollNo,Name,Code,ClassId,
-- DivisionId,ClassName,DivisionName,DivisionOrder,ClassDivision,
-- 	OrgId,BatchId,OrgGroupBatchId,DepartmentId,DepartmentName,AdmissionCategoryId,
-- 	BatchName
--)  
--AS
--(
--SELECT
--SA.AcademicId,
--SA.StudentId,
--SA.RollNo,
--SA.Name,
--SA.Code,
--SA.ClassId,
--SA.DivisionId,
--SA.ClassName,
--SA.DivisionName,
--SA.DivisionOrder,
--SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
--SA.OrgId,
--SA.OrgGroupBatchId,
--SA.BatchId,
--SA.DepartmentId,
--SA.DepartmentName,
--SA.AdmissionCategoryId,
--SA.BatchName
--FROM sStudent.vStudentAcademic SA  
--  WHERE     SA.OrgGroupBatchId = @rOrgGroupBatchId
--  			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))		
--			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
--			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
--			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
--			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
--			AND ((SA.Code=@rCode) OR (@rCode=''))
--			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
--			AND ((SA.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
--			AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
--)
--select * from Academic_CTE


	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeName,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
		--ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  FROM 
  
			#TempAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId ,
				FM.Title AS FeeName,
				FM.FeeHeadId			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN #TempAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId			 		 
			--AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				--AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				-- AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))				
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    BM.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				--AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.FeeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
				
			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 #TempAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			--AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			--AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		  --      SA1.OrgGroupBatchId = @rOrgGroupBatchId
				--AND 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				--AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				--AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.FeeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
		) 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 #TempAcademic SA1 ON SA1.AcademicId=R.SourceId
				--INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				--AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				--AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				--AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				--AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.FeeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	WHERE	
	
			  ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		
			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)			
			Order by SA.RollNo
 DROP TABLE #TempAcademic
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet_Temp]  

	@rReportId int=0,  
	@rReceiptBookId int=0,  
	@rAdmissionCategoryId int=0,  
	@rClassId int=0,  
	@rDivisionId int=0,  
	@rUptoDate date='',  
	@rBatchId int=0,  
	@rUserId bigint=0,  
	@rBuilder1 nvarchar(max) = '',  
	@rBuilder2 nvarchar(max) = '',  
	@rIsDetail bit=0,  
	@rOrgId int=0,  
	@rOrgGroupBatchId int=0,  
	@rStatusId int=0,  
	@rCommonBatch nvarchar(100),  
	@rDepartmentId int=0,  
	@rFromRollNo int=0,  
	@rToRollNo int=0,  
	@rCode nvarchar(20)='',  
	@rIsFilter bit=0,  
	@rIsHeader bit=0,    
	@rCreatedUserName nvarchar(20) = '',  
	@rIsReceiptBookGroup bit=0,  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,  
	@rOrgIds  nvarchar(max) = '',  
	@rPayDate date='',  
	@rCollectionGroupId int =0,  
	@rCastCategoryId int = 0  

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN

	CREATE TABLE #TempAssignRoute (SourceId bigint )
	INSERT INTO #TempAssignRoute
	SELECT 
		AT.SourceId 
    FROM 
	sTransport.tAssignRoute AT   
	INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
	INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 
	AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))	
	 
	SELECT 
		
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		@rPayDate AS PayDate,
		
		T.AcademicId,
		T.RollNo,  
		T.Name,  
		T.Code,  
		T.ClassId,  
		T.DivisionId,
		T.ClassName,  
		T.DivisionName,  
		T.DivisionOrder,  
		T.ClassName+' - '+T.DivisionName AS ClassDivision,
		T.FeeSetupId,
		T.IsVariable,  
		T.FeeAmount AS Amount,  
		T.StartDate,  
		T.EndDate,  
		T.VariableAmount AS FAAmount,
		T.DiscountAmount,  
		T.AdditionalAmount,  
		T.FeePaid PaidAmount,  
		(T.FeeAmount - T.DiscountAmount - T.FeePaid + T.AdditionalAmount) AS PendingAmount,  
		T.Remark,  
		T.FeeName,  
		T.FeeHeadId,  
		T.FeeHeadName,  
		T.FeeHeadOrderIndex,
		T.OrgId,  
		T.OrgName,  
		T.OrgOrderIndex,  
		T.ReceiptBookId,   
		T.ReceiptBookTitle,
		T.ReceiptOrderIndex,    
		T.ReceiptBookFullTitle,
		T.RecieptBookAddress1,
		T.RecieptBookAddress2,
		T.Remark1,
		T.OrgGroupBatchId,  
		T.DepartmentId,  
		T.DepartmentName,  
		T.ParentContactNo, 
		T.ReferenceRemark,  
		
		T.CastCategoryId,  
		T.CastCategoryName,  
		T.CastCategoryOrderIndex
		
		-- AcademicId,
		-- FeeSetupId,
		-- FeeAmount,
		-- DiscountAmount,
		-- AdditionalAmount,
		-- NotApplicableAmount,
		-- FeePaid,
		--(T.FeeAmount - T.DiscountAmount - T.FeePaid + T.AdditionalAmount) AS PendingAmount
	FROM
		(
			SELECT 
			
			A.Id AS AcademicId,
			FS.Id AS FeeSetupId, 
			(CASE
				WHEN FS.IsVariable = 1 AND ISNULL(FA.VariableAmount,0) > 0 THEN FA.VariableAmount
				WHEN FS.IsOptional = 0 THEN FS.Amount
				WHEN FS.IsOptional = 1 AND FS.IsVariable = 0 AND FO.FeeSetupId IS NOT NULL THEN FS.Amount
				WHEN FS.IsOptional = 1 AND FO.FeeSetupId IS NULL THEN 0
			 END) AS FeeAmount,	
			
			ISNULL(FA.DiscountAmount,0) AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0) AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0) AS NotApplicableAmount, 
			ISNULL(FA.VariableAmount,0) AS VariableAmount, 
			FS.IsVariable,
			FS.StartDate,  
		    FS.EndDate,  
			
			(SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id WHERE R.SourceId = A.Id AND RD.FeeSetupId = FS.Id ) AS FeePaid,
			A.RollNo,
			SM.FirstName +' '+ SM.LastName AS Name,
			SM.Code,
			A.ClassId,
			A.DivisionId,
			CM.Title AS ClassName,  
			DM.Title AS DivisionName,  
			DM.OrderIndex AS DivisionOrder,  
			CM.Title+' - '+DM.Title AS ClassDivision,
			FA.Remark,
			FM.Title AS FeeName,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,  
			FHM.OrderIndex AS FeeHeadOrderIndex,
			A.OrgId,
			OM.Title AS OrgName,  
			OM.OrderIndex AS OrgOrderIndex,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0 WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId END) AS ReceiptBookId,   
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL' WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'') END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0 WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0) END) AS ReceiptOrderIndex,
			ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
			ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
			ISNULL(RBM.Address2,'') As RecieptBookAddress2,
			ISNULL(RBM.Remark1,'') As Remark1,
			BM.OrgGroupBatchId,
			CM.DepartmentId,
			tDM.Title AS DepartmentName,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,  
			ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,  
			ISNULL(CCM.Title,'') AS CastCategoryName,  
			ISNULL(CCM.OrderIndex,0) AS CastCategoryOrderIndex
			  
	 FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
			INNER JOIN sFee.tFeeSetup FS ON A.ClassId=FS.ClassId AND FS.BatchId = A.BatchId AND A.AdmissionCategoryId = FS.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
			LEFT JOIN sFee.tFeeOptional FO ON FS.Id = FO.FeeSetupId AND FO.BatchId = FS.BatchId AND A.Id = FO.SourceId AND FO.SourceTypeId = 2001
			LEFT JOIN sFee.tFeeAllocation FA ON   FS.Id = FA.FeeSetupId AND A.Id = FA.SourceId AND FO.SourceTypeId = 2001
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId
			INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tDepartmentMaster tDM ON tDM.Id = CM.DepartmentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId  
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
			LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=A.StudentId AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
			LEFT JOIN #TempAssignRoute RT ON RT.SourceId = A.StudentId AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
	WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((A.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND (SM.StatusId = @rStatusId OR @rStatusId=0)  
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
			AND ((SM.Code=@rCode) OR (@rCode=''))  
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-(SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id WHERE R.SourceId = A.Id AND RD.FeeSetupId = FS.Id ) != 0)     
			AND (  
					(@rFilterId = 0) -- All  
					OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
					OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
					OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
				)  
			AND (ISNULL(A.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')       
			AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0))   		
		
		)T Order by RollNo 	
	
	DROP TABLE #TempAssignRoute
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeePendingDetailListOtherGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rReportType int=1,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
IF(@rReportType=1)
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeId,
		FS.FeeName,
		FS.FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		SAD.LeftDate AS LeftDate,
		SO.ReferenceRemark
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    BM.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')		
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				AND (SA1.ClassId=@rClassId OR @rClassId=0)
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			Order by SA.RollNo
END
ELSE
BEGIN
SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0)AS PendingAmount,
		--ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FAS.Remark,'') AS Remark,
		FS.FeeId,
		--FS.FeeName,
		FM.Title AS FeeName, 
		--FS.FeeOrderIndex,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		SAD.LeftDate AS LeftDate,
		SO.ReferenceRemark
  FROM  sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId		
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND ISNULL(FAS.ToPayAmount,0) !=0
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
			Order by SA.RollNo
END 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeePendingDetailWithScholarshipListGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId  int=0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''  
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		0 AS FeeSetupId,		
		0 AS IsVariable,
		0 AS Amount,
		'1900-01-01' AS StartDate,
		'1900-01-01' AS EndDate,
	    0.00 AS FAAmount,
		0.00 AS DiscountAmount,
		0.00 AS AdditionalAmount,
		0 AS PaidAmount,
		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,
		'' AS Remark,
		0 ReceiptBookId,
		'' AS FeeName,
		'' AS FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		'' AS ReceiptBookTitle,
		0 AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.FeeOrderIndex,
		'' AS FatherContactNo, --Added for mantis : 34972 by Nilesh
		'' AS MotherContactNo, --Added for mantis : 34972 by Nilesh
		'' AS WhatsAppContactNo --added by dhananjay for : 37272
  FROM 
  
			 sStudent.vStudentAcademic SA			 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))  AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId 
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))   AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
	    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
       LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)	
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
            AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))		     
			GROUP BY 
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName,
			SA.DivisionName,
			OrgId,
			O.Title,
			O.OrderIndex,
			BatchName,
			SA.SUID,
			SA.ClassOrderIndex,
			SA.DivisionOrder,
			FeeOrderIndex
		
			Order by SA.RollNo

			SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsFilter AS IsFilter, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			p.AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			OrgName,
			ISNULL(SUM(PendingAmount),0) AS PendingAmount, 
			ISNULL(SUM(SS.ScholarshipPaid),0) AS ScholarshipPaid,
			ISNULL(SUM(SSE.EligibleAmount),0) AS EligibleAmount,
			ISNULL(SS.ReferenceRemark,'')   AS ReferenceRemark,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex
			--,
			--CASE ISNULL(SS.AcademicId,0) WHEN 0 THEN 0 ELSE 1 END AS IsScholarshipEligible		
			FROM @p p 
			
		LEFT JOIN				
		(SELECT  SE.AcademicId,Sum(PaidAmount) AS ScholarshipPaid,SO.ReferenceRemark FROM 
		sScholarship.tScholarshipEligibleStudent SE
		INNER JOIN sStudent.vStudentAcademic SA1  ON SE.AcademicId = SA1.AcademicId 
		INNER JOIN sScholarship.tScholarshipReceive RE ON SE.ScholarshipId = RE.ScholarshipId 
		INNER JOIN sScholarship.tScholarshipStudentPaid SP on SE.AcademicId = SP.AcademicId	AND SP.ScholarshipReceiveId = RE.Id	
		INNER JOIN sStudent.tStudentOther SO ON SA1.StudentId = SO.StudentId
		WHERE
		    (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		 	AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		 	AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		 	AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		 	AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
		 	AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		 	 AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 	 AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			 AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			 AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			 AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		 	GROUP BY SE.AcademicId,ReferenceRemark
		 ) SS ON p.AcademicId=SS.AcademicId
		LEFT JOIN				
		(SELECT  SE.AcademicId,SUM(SE.EligibleAmount) AS EligibleAmount FROM 
		sScholarship.tScholarshipEligibleStudent SE
		INNER JOIN sStudent.vStudentAcademic SA1  ON SE.AcademicId = SA1.AcademicId		 
		WHERE
		    (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		 	AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		 	AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		 	AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		 	AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
		 	AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		 	 AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 	 AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			 AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			 AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			 AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	  
		 	GROUP BY SE.AcademicId 
		 ) SSE ON p.AcademicId=SSE.AcademicId		 
		 
			GROUP By 
			OrgId,			
			p.AcademicId,
			--SS.AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			OrgName,
			ReferenceRemark,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex
			ORDER BY AcademicId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeePendingWithFeeNameGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0	,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '' ,
		@rReportType int=1,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = '',
		@rFromAmount decimal = 0.00,
		@rToAmount decimal = 0.00
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	IF(@rReportType=1)

		BEGIN

--CREATE TABLE #TempStudent
--	(
--	AcademicId bigint,
--	ClassId int,
--	BatchId int,
--	a
--	)
--	SELECT AcademicId

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int	
	--)
	
	DECLARE @p as TempPendingFee
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		0 AS FeeOrderIndex,	-- Pass static 0 for MantisId : 0032054
		--change by megha for 0027384
	    ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'')AS MotherContactNo,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo --Added (WhatsAppContactNo)by dhananjay for mantis - 37272
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId 
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId) R ON R.FeeSetupId = FS.Id 
				AND SA.AcademicId = R.SourceId
		       INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		       INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
			LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
			
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		    --change by megha for 0027384
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
			Order by SA.RollNo

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			FeeOrderIndex,
			ReceiptOrderIndex,
			FatherContactNo,
		    MotherContactNo,
			WhatsAppContactNo --Added (WhatsAppContactNo)by dhananjay for mantis - 37272
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint,SUID,ClassOrderIndex,
			DivisionOrderIndex,
			FeeOrderIndex,
			FatherContactNo,MotherContactNo,
			WhatsAppContactNo --Added (WhatsAppContactNo)by dhananjay for mantis - 37272
			HAVING
			((SUM(PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
			ORDER BY DivisionOrderIndex,AcademicId

END

	ELSE
		BEGIN

	INSERT INTO  @p
SELECT 

		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		--FS.FeeCode,
		FM.Title AS FeeName, 
		FM.Code AS FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		0 AS FeeOrderIndex, -- Pass static 0 for MantisId : 0032054
	    ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo --Added (WhatsAppContactNo)by dhananjay for mantis - 37272

  FROM  sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		--LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=SF.FeeSetupId AND FA.SourceId=SA.AcademicId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND ISNULL(FAS.ToPayAmount,0) !=0
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			Order by   SA.RollNo
			--FM.OrderIndex 
			

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			--ReceiptOrderIndex,
			FeeOrderIndex,
			FatherContactNo,
		    MotherContactNo,
			WhatsAppContactNo --Added (WhatsAppContactNo)by dhananjay for mantis - 37272
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint,SUID,ClassOrderIndex,
			DivisionOrderIndex,FeeOrderIndex,FatherContactNo,MotherContactNo,
			WhatsAppContactNo --Added (WhatsAppContactNo)by dhananjay for mantis - 37272
			HAVING
			((SUM(PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
			ORDER BY AcademicId

END 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sFee].[pRptFeeProcessGenerateGet] @rIsDisplayOrgGroup=1,@rClassStatusId=0,@rIsFilter=1,@rDepartmentId=0,@rOrgGroupBatchId=196100103,@rCommonBatch=N''
--,@rReportId=20624,@rReceiptBookId=0,@rOrgId=0,@rBatchId=0,@rUserId=0,@rIsHeader=0,@rFeeHeadId=N'',@rFeeId=N'',@rCreatedUserName=N'',@rAdmissionCategoryId=0
--,@rClassId=0,@rDivisionId=0,@rStatusId=0,@rFromRollNo=0,@rToRollNo=0,@rCode=N'',@rIsDetail=0,@rIsExemption=0
--,@rBuilder1=N'',@rBuilder2=N'',@rFilterId=0,@rOrgIds=N''

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeProcessGenerateGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	
	IF(@rReportId=30832 OR @rReportId=30838 OR @rReportId=30835 OR @rReportId=30840 OR @rReportId=30834)
	BEGIN
		
		SELECT 

			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			
			FAS.AcademicId,
			
			--A.RollNo,
			CTE1.RollNo,
			
			--SM.FirstName+' '+SM.LastName AS Name,
			----sStudent.fStudentNameGet(SM.FirstName,SM.MiddleName,SM.LastName,OM.StudentNameFormatId) AS Name,
			CTE1.Name,
			
			--SM.Code,
			CTE1.Code,

			--A.ClassId,
			--A.DivisionId,
			--CM.DisplayTitle AS ClassName,
			--DM.DisplayTitle AS DivisionName,
			--DM.OrderIndex AS DivisionOrderIndex,
			--CM.OrderIndex AS ClassOrderIndex,

			CTE1.ClassId,
			CTE1.DivisionId,
			CTE1.ClassName,
			CTE1.DivisionName,
			CTE1.DivisionOrderIndex,
			CTE1.ClassOrderIndex,
			
			
			----CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			--CTE1.ClassDivision,

			FAS.FeeSetupId,

			CTE2.IsVariable,
			CTE2.Amount,
			CTE2.StartDate,
			CTE2.EndDate,

			--FS.IsVariable,
			--FS.Amount,
			--FS.StartDate,
			--FS.EndDate,			
			
			FAS.VariableAmount AS FAAmount,
			FAS.DiscountAmount,
			FAS.AdditionalAmount,
			FAS.NotApplicableAmount,
			FAS.PaidAmount,
			FAS.ToPayAmount AS PendingAmount,			
			FAS.Remark,

			CTE2.ReceiptBookId,
			CTE2.FeeName,
			CTE2.FeeCode,

			--FS.ReceiptBookId,
			--FM.Title AS FeeName,
			--FM.Code As FeeCode,
			
			--A.OrgId,
			--OM.DisplayTitle AS OrgName,
			CTE1.OrgId,
			CTE1.OrgName,
			--OM.OrderIndex AS OrgOrderIndex,

			CTE2.ReceiptBookTitle,
			CTE2.ReceiptOrderIndex,

			--RBM.Title AS ReceiptBookTitle,
			--RBM.OrderIndex AS ReceiptOrderIndex,
			
			--CM.DepartmentId,
			--DeptM.DisplayTitle AS DepartmentName,
			CTE1.DepartmentId,
			CTE1.DepartmentName,

			--A.ExemptionTypeId,
			ETM.Id AS ExemptionTypeId,
			ETM.Title AS ExemptionType,
			
			--CTE1.ExemptionTypeId,
			--CTE1.ExemptionType,
			
			CTE2.FeeHeadId,
			CTE2.FeeHeadName,
			CTE2.FeeHeadOrderIndex,

			--FHM.Id AS FeeHeadId,
			--FHM.Title AS FeeHeadName,
			--FHM.OrderIndex AS FeeHeadOrderIndex,

			@rFeeGroupId As FeeGroup,
			@rOrgGroupBatchId AS BatchId,

			--BM.Title AS BatchName
			CTE1.BatchName

			--,0.00 AS CancelAmount,
			--0.00 AS Discount
		
		FROM sFee.tFeeAllocationStudent AS FAS
		JOIN (SELECT A.Id AS AcademicId,A.OrgId,CM.DepartmentId,A.DivisionId,A.ClassId,DM.OrderIndex AS DivisionOrderIndex,CM.OrderIndex AS ClassOrderIndex,A.ExemptionTypeId
				,A.RollNo,SM.FirstName+' '+SM.LastName AS Name,CM.DisplayTitle AS ClassName,DM.DisplayTitle AS DivisionName,SM.Code
				,OM.DisplayTitle AS OrgName,DeptM.DisplayTitle AS DepartmentName,BM.Title AS BatchName 
	--SELECT A.Id AS AcademicId,A.ExemptionTypeId,SM.Code,BM.Title AS BatchName ,ETM.Title AS ExemptionType
			FROM sStudent.tAcademic A						
				JOIN sStudent.tStudentAdmission AS SA ON SA.StudentId = A.StudentId  
				JOIN sSetup.tBatchMaster AS BM ON BM.Id = A.BatchId
				JOIN sSetup.tOrganizationMaster AS OM ON OM.Id=A.OrgId AND OM.IsObsolete=0
				JOIN sSetup.tClassMaster AS CM ON CM.Id = A.ClassId 				
				JOIN sSetup.tDepartmentMaster AS DeptM ON DeptM.Id = CM.DepartmentId
				JOIN sSetup.tDivisionMaster AS DM ON DM.Id = A.DivisionId
				JOIN sStudent.tStudentMaster AS SM ON SM.OrgId=A.OrgId AND SM.Id = A.StudentId

				WHERE
			--((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0)) AND	
			((A.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SM.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SM.Code=@rCode) OR (@rCode=''))
			AND ((DeptM.Id=@rDepartmentId) OR (@rDepartmentId=0))		
			--AND ((ETM.Id=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=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 (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (ISNULL(A.OrgId,0) IN( SELECT CAST(item AS INT) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
			AND (SA.AdmissionDate <= ISNULL(@rUptoDate,GETDATE()))
			AND ((A.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))

	) AS CTE1 ON CTE1.AcademicId=FAS.AcademicId
	
	JOIN ( SELECT FS.Id AS FeeSetupId,FS.ReceiptBookId,RBM.OrderIndex AS ReceiptOrderIndex,FHM.Id AS FeeHeadId,FHM.OrderIndex AS FeeHeadOrderIndex
				,FS.IsVariable,FS.Amount,FS.StartDate,FS.EndDate,FM.Title AS FeeName,FM.Code As FeeCode
				,RBM.Title AS ReceiptBookTitle,FHM.Title AS FeeHeadName
	--SELECT FS.Id AS FeeSetupId,FS.IsVariable,FS.Amount,FS.StartDate,FS.EndDate
	----,FM.Title AS FeeName,FM.Code As FeeCode,FHM.Title AS FeeHeadName
			FROM sFee.tFeeSetup AS FS				
				JOIN sFee.tReceiptBookMaster AS RBM ON RBM.Id=FS.ReceiptBookId
				JOIN sFee.tFeeMaster AS FM ON FM.Id=FS.FeeId
				JOIN sFee.tFeeHeadMaster AS FHM ON FHM.Id=FM.FeeHeadId
	) AS CTE2 ON CTE2.FeeSetUpId=FAS.FeeSetupId

	LEFT JOIN sFee.tExemptionTypeMaster AS ETM ON ETM.Id = CTE1.ExemptionTypeId	
	

	----FROM sFee.tFeeAllocationStudent AS FAS
	----JOIN ( SELECT A.Id AS AcademicId,A.OrgId,CM.DepartmentId,A.DivisionId,A.ClassId,DM.OrderIndex AS DivisionOrderIndex,CM.OrderIndex AS ClassOrderIndex,A.ExemptionTypeId
	----			,A.RollNo,SM.FirstName+' '+SM.LastName AS Name,CM.DisplayTitle AS ClassName,DM.DisplayTitle AS DivisionName,SM.Code
	----			,OM.DisplayTitle AS OrgName,DeptM.DisplayTitle AS DepartmentName,ETM.Title AS ExemptionType,BM.Title AS BatchName
	----		FROM sStudent.tAcademic A				
	----			JOIN sStudent.tStudentAdmission AS SA ON SA.StudentId = A.StudentId  
	----			JOIN sSetup.tBatchMaster AS BM ON BM.Id = A.BatchId
	----			JOIN sSetup.tOrganizationMaster AS OM ON OM.Id=A.OrgId AND OM.IsObsolete=0
	----			JOIN sSetup.tClassMaster AS CM ON CM.Id = A.ClassId 				
	----			JOIN sSetup.tDepartmentMaster AS DeptM ON DeptM.Id = CM.DepartmentId
	----			JOIN sSetup.tDivisionMaster AS DM ON DM.Id = A.DivisionId
	----			JOIN sStudent.tStudentMaster AS SM ON SM.OrgId=A.OrgId AND SM.Id = A.StudentId
	----			LEFT JOIN sFee.tExemptionTypeMaster AS ETM ON ETM.Id = A.ExemptionTypeId
	----			LEFT JOIN (SELECT AT.SourceId FROM sTransport.tAssignRoute AS AT 
	----						INNER JOIN sTransport.tBusRouteDestinationMaster AS BM ON BM.Id=AT.PickupDestinationId
	----						INNER JOIN sTransport.tBusRouteMaster AS B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
	----						) AS RT ON RT.SourceId = A.StudentId
	----	WHERE
	----		((A.BatchId=@rBatchId) OR (@rBatchId=0))   
	----		AND	((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
	----		AND (SM.StatusId=@rStatusId OR @rStatusId=0)
	----		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	----		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	----		AND ((SM.Code=@rCode) OR (@rCode=''))
	----		AND ((DeptM.Id=@rDepartmentId) OR (@rDepartmentId=0))		
	----		AND ((ETM.Id=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	----		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
	----		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	----		AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	----		AND (ISNULL(A.OrgId,0) IN( SELECT CAST(item AS INT) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	----		AND ((SA.LeftDate > @rUptoDate) OR (SA.LeftDate IS NULL))
	----		AND (SA.AdmissionDate <= ISNULL(@rUptoDate,GETDATE()))
	----		AND ((A.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	----) AS CTE1 ON CTE1.AcademicId=FAS.AcademicId
	
	----JOIN ( SELECT FS.Id AS FeeSetupId,FS.ReceiptBookId,RBM.OrderIndex AS ReceiptOrderIndex,FHM.Id AS FeeHeadId,FHM.OrderIndex AS FeeHeadOrderIndex
	----			,FS.IsVariable,FS.Amount,FS.StartDate,FS.EndDate,FM.Title AS FeeName,FM.Code As FeeCode
	----			,RBM.Title AS ReceiptBookTitle,FHM.Title AS FeeHeadName
	----		FROM sFee.tFeeSetup AS FS				
	----			JOIN sFee.tReceiptBookMaster AS RBM ON RBM.Id=FS.ReceiptBookId
	----			JOIN sFee.tFeeMaster AS FM ON FM.Id=FS.FeeId
	----			JOIN sFee.tFeeHeadMaster AS FHM ON FHM.Id=FM.FeeHeadId
	----		WHERE
	----			((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	----) AS CTE2 ON CTE2.FeeSetUpId=FAS.FeeSetupId


				
	--FROM sFee.tFeeAllocationStudent AS FAS
	--JOIN sStudent.tAcademic A ON FAS.AcademicId = A.Id
	--JOIN sStudent.tStudentMaster AS SM ON SM.Id = A.StudentId AND SM.OrgId=A.OrgId
	--JOIN sStudent.tStudentAdmission AS SA ON SA.StudentId = A.StudentId  
	--JOIN sSetup.tBatchMaster AS BM ON BM.Id = A.BatchId
	--JOIN sSetup.tOrganizationMaster AS OM ON OM.Id=A.OrgId AND OM.IsObsolete=0
	--JOIN sSetup.tClassMaster AS CM ON CM.Id = A.ClassId 
	--JOIN sSetup.tDivisionMaster AS DM ON DM.Id = A.DivisionId 			
	--JOIN sSetup.tDepartmentMaster AS DeptM ON DeptM.Id = CM.DepartmentId 	
	--JOIN sFee.tFeeSetup AS FS ON FS.Id=FAS.FeeSetupId
	--JOIN sFee.tFeeMaster AS FM ON FM.Id=FS.FeeId
	--JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
	--JOIN sFee.tReceiptBookMaster AS RBM ON RBM.Id=FS.ReceiptBookId
	--LEFT JOIN sFee.tExemptionTypeMaster AS ETM ON ETM.Id = A.ExemptionTypeId

	--WHERE
	----((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0)) AND	
	--		((A.BatchId=@rBatchId) OR (@rBatchId=0))   
	--		AND	((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
	--		AND (SM.StatusId=@rStatusId OR @rStatusId=0)
	--		--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	--		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--		AND ((SM.Code=@rCode) OR (@rCode=''))
	--		AND ((DeptM.Id=@rDepartmentId) OR (@rDepartmentId=0))		
	--		AND ((ETM.Id=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	--		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
	--		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=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 (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	--		AND (ISNULL(A.OrgId,0) IN( SELECT CAST(item AS INT) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--		AND (SA.AdmissionDate <= ISNULL(@rUptoDate,GETDATE()))
	--		AND ((A.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			
		--ORDER BY A.RollNo	
	
	END
	ELSE IF(@rReportId=30833)
	BEGIN

		SELECT 

			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			
			FAS.AcademicId,
			
			--A.RollNo,
			CTE1.RollNo,
			
			--SM.FirstName+' '+SM.LastName AS Name,
			----sStudent.fStudentNameGet(SM.FirstName,SM.MiddleName,SM.LastName,OM.StudentNameFormatId) AS Name,
			CTE1.Name,
			
			--SM.Code,
			CTE1.Code,

			--A.ClassId,
			--A.DivisionId,
			--CM.DisplayTitle AS ClassName,
			--DM.DisplayTitle AS DivisionName,
			--DM.OrderIndex AS DivisionOrderIndex,
			--CM.OrderIndex AS ClassOrderIndex,

			CTE1.ClassId,
			CTE1.DivisionId,
			CTE1.ClassName,
			CTE1.DivisionName,
			CTE1.DivisionOrderIndex,
			CTE1.ClassOrderIndex,
			
			
			----CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			--CTE1.ClassDivision,

			FAS.FeeSetupId,

			CTE2.IsVariable,
			CTE2.Amount,
			CTE2.StartDate,
			CTE2.EndDate,

			--FS.IsVariable,
			--FS.Amount,
			--FS.StartDate,
			--FS.EndDate,			
			
			FAS.VariableAmount AS FAAmount,
			FAS.DiscountAmount,
			FAS.AdditionalAmount,
			FAS.NotApplicableAmount,
			FAS.PaidAmount,
			FAS.ToPayAmount AS PendingAmount,			
			FAS.Remark,

			CTE2.ReceiptBookId,
			CTE2.FeeName,
			CTE2.FeeCode,

			--FS.ReceiptBookId,
			--FM.Title AS FeeName,
			--FM.Code As FeeCode,
			
			--A.OrgId,
			--OM.DisplayTitle AS OrgName,
			CTE1.OrgId,
			CTE1.OrgName,
			--OM.OrderIndex AS OrgOrderIndex,

			CTE2.ReceiptBookTitle,
			CTE2.ReceiptOrderIndex,

			--RBM.Title AS ReceiptBookTitle,
			--RBM.OrderIndex AS ReceiptOrderIndex,
			
			--CM.DepartmentId,
			--DeptM.DisplayTitle AS DepartmentName,
			CTE1.DepartmentId,
			CTE1.DepartmentName,

			--A.ExemptionTypeId,
			ETM.Id AS ExemptionTypeId,
			ETM.Title AS ExemptionType,
			
			--CTE1.ExemptionTypeId,
			--CTE1.ExemptionType,
			
			CTE2.FeeHeadId,
			CTE2.FeeHeadName,
			CTE2.FeeHeadOrderIndex,

			--FHM.Id AS FeeHeadId,
			--FHM.Title AS FeeHeadName,
			--FHM.OrderIndex AS FeeHeadOrderIndex,

			@rFeeGroupId As FeeGroup,
			@rOrgGroupBatchId AS BatchId,

			--BM.Title AS BatchName
			CTE1.BatchName

			--,0.00 AS CancelAmount,
			--0.00 AS Discount
			
	FROM sFee.tFeeAllocationStudent AS FAS
	JOIN ( SELECT A.Id AS AcademicId,A.OrgId,CM.DepartmentId,A.DivisionId,A.ClassId,DM.OrderIndex AS DivisionOrderIndex,CM.OrderIndex AS ClassOrderIndex,A.ExemptionTypeId
				,A.RollNo,SM.FirstName+' '+SM.LastName AS Name,CM.DisplayTitle AS ClassName,DM.DisplayTitle AS DivisionName,SM.Code
				,OM.DisplayTitle AS OrgName,DeptM.DisplayTitle AS DepartmentName,BM.Title AS BatchName
			FROM sStudent.tAcademic A						
				JOIN sStudent.tStudentAdmission AS SA ON SA.StudentId = A.StudentId  
				JOIN sSetup.tBatchMaster AS BM ON BM.Id = A.BatchId
				JOIN sSetup.tOrganizationMaster AS OM ON OM.Id=A.OrgId AND OM.IsObsolete=0
				JOIN sSetup.tClassMaster AS CM ON CM.Id = A.ClassId 				
				JOIN sSetup.tDepartmentMaster AS DeptM ON DeptM.Id = CM.DepartmentId
				JOIN sSetup.tDivisionMaster AS DM ON DM.Id = A.DivisionId
				JOIN sStudent.tStudentMaster AS SM ON SM.OrgId=A.OrgId AND SM.Id = A.StudentId
				LEFT JOIN (SELECT AT.SourceId FROM sTransport.tAssignRoute AS AT 
							INNER JOIN sTransport.tBusRouteDestinationMaster AS BM ON BM.Id=AT.PickupDestinationId
							INNER JOIN sTransport.tBusRouteMaster AS B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
							) AS RT ON RT.SourceId = A.StudentId
		WHERE
			((A.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			--AND (SM.StatusId=@rStatusId OR @rStatusId=0)
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SM.Code=@rCode) OR (@rCode=''))
			AND ((DeptM.Id=@rDepartmentId) OR (@rDepartmentId=0))		
			
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (ISNULL(A.OrgId,0) IN( SELECT CAST(item AS INT) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND ((SA.LeftDate > @rUptoDate) OR (SA.LeftDate IS NULL AND SM.StatusId = 1))
			AND (SA.AdmissionDate <= ISNULL(@rUptoDate,GETDATE()))
			--AND ((A.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))

	) AS CTE1 ON CTE1.AcademicId=FAS.AcademicId
	
	JOIN ( SELECT FS.Id AS FeeSetupId,FS.ReceiptBookId,RBM.OrderIndex AS ReceiptOrderIndex,FHM.Id AS FeeHeadId,FHM.OrderIndex AS FeeHeadOrderIndex
				,FS.IsVariable,FS.Amount,FS.StartDate,FS.EndDate,FM.Title AS FeeName,FM.Code As FeeCode
				,RBM.Title AS ReceiptBookTitle,FHM.Title AS FeeHeadName
			FROM sFee.tFeeSetup AS FS				
				JOIN sFee.tReceiptBookMaster AS RBM ON RBM.Id=FS.ReceiptBookId
				JOIN sFee.tFeeMaster AS FM ON FM.Id=FS.FeeId
				JOIN sFee.tFeeHeadMaster AS FHM ON FHM.Id=FM.FeeHeadId
			--WHERE
			--	((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	) AS CTE2 ON CTE2.FeeSetUpId=FAS.FeeSetupId

	LEFT JOIN sFee.tExemptionTypeMaster AS ETM ON ETM.Id = CTE1.ExemptionTypeId
	WHERE
	((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FAS.DiscountAmount,0) > 0))
	AND ((ETM.Id=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
		
		--SELECT 
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	@rIsDetail AS IsDetail,
		--	@rIsFilter As IsFilter,
		--	@rIsHeader As IsHeader, 
		--	@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		--	SA.AcademicId,
		--	SA.RollNo,
		--	SA.Name,
		--	SA.Code,
		--	SA.ClassId,
		--	SA.DivisionId,
		--	SA.ClassName,
		--	SA.DivisionName,
		--	SA.DivisionOrder AS DivisionOrderIndex,
		--	SA.ClassOrderIndex AS ClassOrderIndex,
		--	SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		--	FS.Id AS FeeSetupId,
		--	ISNULL(FS.IsVariable,0)AS IsVariable,
		--	ISNULL(FS.Amount,0)AS Amount,
		--	ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		--	ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		--	ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		--	ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		--	ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		--	ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		--	ISNULL(R.PaidAmount,0) AS PaidAmount,
		--	ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		--	ISNULL(FA.Remark,'') AS Remark,
		--	FS.ReceiptBookId,
		--	FS.FeeName,
		--	FS.FeeCode,
		--	SA.OrgId,
		--	O.DisplayTitle AS OrgName,
		--	O.OrderIndex AS OrgOrderIndex,
		--	ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--	ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		--	SA.DepartmentId,
		--	SA.DepartmentName,
		--	SA.ExemptionTypeId,
		--	ISNULL(ETM.Title,'') AS ExemptionType,
		--	FHM.Id AS FeeHeadId,
		--	FHM.Title AS FeeHeadName,
		--	FHM.OrderIndex AS FeeHeadOrderIndex,
		--	@rFeeGroupId As FeeGroup,
		--	SA.OrgGroupBatchId AS BatchId,
		--	SA.BatchName AS BatchName,
		--	0.00 AS CancelAmount,
		--	0.00 AS Discount
	 -- FROM 
		--	sStudent.vStudentAcademic SA
		--	INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
		--	INNER JOIN 
		--	(
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,
		--			FM.Title AS FeeName,
		--			FM.Code AS FeeCode,
		--			FM.FeeHeadId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		--			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--			UNION ALL
					
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,
		--			FM.Title AS FeeName,
		--			FM.Code As FeeCode,
		--			FM.FeeHeadId
		--		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 FS1.BatchId = SA1.BatchId
		--	AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--	WHERE
		--		((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		--		AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
		--			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--			AND (R.IsObsolete = 0) 
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		--			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		--			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
		--			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--			--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		--			--AND (tSA.AdmissionDate <= @rUptoDate)
		--			AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA1.StatusId = 1))
		--				GROUP BY FeeSetupId,R.SourceId
			
		--	) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		--	 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		--	 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		--	 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
		--	 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
		--	 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		--	 LEFT JOIN
		--	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		--	INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		--	INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		--	ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		--	WHERE	
		--	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
		--	AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		--	AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
		--	--AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		--	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		--	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--	AND ((SA.Code=@rCode) OR (@rCode=''))
		--	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
		--	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
		--	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		--	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		--AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		----AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		----AND (tSA.AdmissionDate <= @rUptoDate)
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA.StatusId = 1))
		-- --AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		--Order by SA.RollNo 

	END
	ELSE
	BEGIN

		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			
			FAS.AcademicId,
			
			--A.RollNo,
			CTE1.RollNo,
			
			--SM.FirstName+' '+SM.LastName AS Name,
			----sStudent.fStudentNameGet(SM.FirstName,SM.MiddleName,SM.LastName,OM.StudentNameFormatId) AS Name,
			CTE1.Name,
			
			--SM.Code,
			CTE1.Code,

			--A.ClassId,
			--A.DivisionId,
			--CM.DisplayTitle AS ClassName,
			--DM.DisplayTitle AS DivisionName,
			--DM.OrderIndex AS DivisionOrderIndex,
			--CM.OrderIndex AS ClassOrderIndex,

			CTE1.ClassId,
			CTE1.DivisionId,
			CTE1.ClassName,
			CTE1.DivisionName,
			CTE1.DivisionOrderIndex,
			CTE1.ClassOrderIndex,
			
			
			----CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			CTE1.ClassName+' - '+CTE1.DivisionName AS ClassDivision,

			FAS.FeeSetupId,

			CTE2.IsVariable,
			CTE2.Amount,
			CTE2.StartDate,
			CTE2.EndDate,

			--FS.IsVariable,
			--FS.Amount,
			--FS.StartDate,
			--FS.EndDate,			
			
			FAS.VariableAmount AS FAAmount,
			FAS.DiscountAmount,
			FAS.AdditionalAmount,
			FAS.NotApplicableAmount,
			FAS.PaidAmount,
			FAS.ToPayAmount AS PendingAmount,			
			FAS.Remark,

			CTE2.ReceiptBookId,
			CTE2.FeeName,
			CTE2.FeeCode,

			--FS.ReceiptBookId,
			--FM.Title AS FeeName,
			--FM.Code As FeeCode,
			
			--A.OrgId,
			--OM.DisplayTitle AS OrgName,
			CTE1.OrgId,
			CTE1.OrgName,
			CTE1.OrgOrderIndex,

			CTE2.ReceiptBookTitle,
			CTE2.ReceiptOrderIndex,

			--RBM.Title AS ReceiptBookTitle,
			--RBM.OrderIndex AS ReceiptOrderIndex,
			
			--CM.DepartmentId,
			--DeptM.DisplayTitle AS DepartmentName,
			CTE1.DepartmentId,
			CTE1.DepartmentName,

			--A.ExemptionTypeId,
			ETM.Id AS ExemptionTypeId,
			ETM.Title AS ExemptionType,
			
			--CTE1.ExemptionTypeId,
			--CTE1.ExemptionType,
			
			CTE2.FeeHeadId,
			CTE2.FeeHeadName,
			CTE2.FeeHeadOrderIndex,

			--FHM.Id AS FeeHeadId,
			--FHM.Title AS FeeHeadName,
			--FHM.OrderIndex AS FeeHeadOrderIndex,

			@rFeeGroupId As FeeGroup,
			@rOrgGroupBatchId AS BatchId,

			--BM.Title AS BatchName
			CTE1.BatchName

			,0.00 AS CancelAmount,
			0.00 AS Discount

	  FROM sFee.tFeeAllocationStudent AS FAS
	JOIN ( SELECT A.Id AS AcademicId,A.OrgId,CM.DepartmentId,A.DivisionId,A.ClassId,DM.OrderIndex AS DivisionOrderIndex,CM.OrderIndex AS ClassOrderIndex,A.ExemptionTypeId
				,A.RollNo,SM.FirstName+' '+SM.LastName AS Name,CM.DisplayTitle AS ClassName,DM.DisplayTitle AS DivisionName,SM.Code,OM.OrderIndex AS OrgOrderIndex
				,OM.DisplayTitle AS OrgName,DeptM.DisplayTitle AS DepartmentName,BM.Title AS BatchName 
	--SELECT A.Id AS AcademicId,A.ExemptionTypeId,SM.Code,BM.Title AS BatchName ,ETM.Title AS ExemptionType
			FROM sStudent.tAcademic A						
				JOIN sStudent.tStudentAdmission AS SA ON SA.StudentId = A.StudentId  
				JOIN sSetup.tBatchMaster AS BM ON BM.Id = A.BatchId
				JOIN sSetup.tOrganizationMaster AS OM ON OM.Id=A.OrgId AND OM.IsObsolete=0
				JOIN sSetup.tClassMaster AS CM ON CM.Id = A.ClassId 				
				JOIN sSetup.tDepartmentMaster AS DeptM ON DeptM.Id = CM.DepartmentId
				JOIN sSetup.tDivisionMaster AS DM ON DM.Id = A.DivisionId
				JOIN sStudent.tStudentMaster AS SM ON SM.OrgId=A.OrgId AND SM.Id = A.StudentId
				LEFT JOIN (SELECT AT.SourceId FROM sTransport.tAssignRoute AS AT 
							INNER JOIN sTransport.tBusRouteDestinationMaster AS BM ON BM.Id=AT.PickupDestinationId
							INNER JOIN sTransport.tBusRouteMaster AS B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003
							) AS RT ON RT.SourceId = A.StudentId
		WHERE
			((A.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SM.StatusId=@rStatusId OR @rStatusId=0)
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SM.Code=@rCode) OR (@rCode=''))
			AND ((DeptM.Id=@rDepartmentId) OR (@rDepartmentId=0))					
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (ISNULL(A.OrgId,0) IN( SELECT CAST(item AS INT) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND ((SA.LeftDate > @rUptoDate) OR (SA.LeftDate IS NULL AND SM.StatusId = 1))
			AND (SA.AdmissionDate <= ISNULL(@rUptoDate,GETDATE()))
			--AND ((A.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))

	) AS CTE1 ON CTE1.AcademicId=FAS.AcademicId
	
	JOIN ( SELECT FS.Id AS FeeSetupId,FS.ReceiptBookId,RBM.OrderIndex AS ReceiptOrderIndex,FHM.Id AS FeeHeadId,FHM.OrderIndex AS FeeHeadOrderIndex
				,FS.IsVariable,FS.Amount,FS.StartDate,FS.EndDate,FM.Title AS FeeName,FM.Code As FeeCode
				,RBM.Title AS ReceiptBookTitle,FHM.Title AS FeeHeadName
			FROM sFee.tFeeSetup AS FS				
				JOIN sFee.tReceiptBookMaster AS RBM ON RBM.Id=FS.ReceiptBookId
				JOIN sFee.tFeeMaster AS FM ON FM.Id=FS.FeeId
				JOIN sFee.tFeeHeadMaster AS FHM ON FHM.Id=FM.FeeHeadId
			--WHERE
			--	((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	) AS CTE2 ON CTE2.FeeSetUpId=FAS.FeeSetupId 					
	
	LEFT JOIN sFee.tExemptionTypeMaster AS ETM ON ETM.Id = CTE1.ExemptionTypeId		
	WHERE	
	((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FAS.DiscountAmount,0) > 0))
	AND ((ETM.Id=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			 
	END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeProcessSummaryGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	
	IF(@rReportId=20624 OR @rReportId=20842 OR @rReportId=10150 OR @rReportId=30714 OR @rReportId=30831)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo 
	END
	ELSE IF(@rReportId=30655)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  ISNULL(FA.NotApplicableAmount,0) > 0) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo
	END
	ELSE IF(@rReportId=30799)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R1.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R1.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			ISNULL(R2.TotalReceiptAmount,0.00) AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R1 ON R1.FeeSetupId = FS.Id AND SA.AcademicId = R1.SourceId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 1) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R2 ON R2.FeeSetupId = FS.Id AND SA.AcademicId = R2.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo 
	END
	ELSE IF(@rReportId=30825)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					--AND (tSA.AdmissionDate <= @rUptoDate)
					AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA1.StatusId = 1))
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			--AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		--AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA.StatusId = 1))
		 --AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo 
	END
	--ELSE IF(@rReportId=30821)
	--BEGIN
	--	SELECT 
	--		@rBuilder1 AS Builder1,
	--		@rBuilder2 AS Builder2,
	--		@rIsDetail AS IsDetail,
	--		@rIsFilter As IsFilter,
	--		@rIsHeader As IsHeader, 
	--		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
	--		SA.AcademicId,
	--		SA.RollNo,
	--		SA.Name,
	--		SA.Code,
	--		SA.ClassId,
	--		SA.DivisionId,
	--		SA.ClassName,
	--		SA.DivisionName,
	--		SA.DivisionOrder AS DivisionOrderIndex,
	--		SA.ClassOrderIndex AS ClassOrderIndex,
	--		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
	--		FS.Id AS FeeSetupId,
	--		ISNULL(FS.IsVariable,0)AS IsVariable,
	--		ISNULL(FS.Amount,0)AS Amount,
	--		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
	--		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
	--		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
	--		ISNULL(R.DiscountAmount,0.00)AS DiscountAmount,
	--		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
	--		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
	--		ISNULL(R.PaidAmount,0) AS PaidAmount,
	--		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
	--		ISNULL(FA.Remark,'') AS Remark,
	--		FS.ReceiptBookId,
	--		FS.FeeName,
	--		FS.FeeCode,
	--		SA.OrgId,
	--		O.DisplayTitle AS OrgName,
	--		O.OrderIndex AS OrgOrderIndex,
	--		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
	--		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
	--		SA.DepartmentId,
	--		SA.DepartmentName,
	--		SA.ExemptionTypeId,
	--		ISNULL(ETM.Title,'') AS ExemptionType,
	--		FHM.Id AS FeeHeadId,
	--		FHM.Title AS FeeHeadName,
	--		FHM.OrderIndex AS FeeHeadOrderIndex,
	--		@rFeeGroupId As FeeGroup,
	--		SA.OrgGroupBatchId AS BatchId,
	--		SA.BatchName AS BatchName,
	--		0.00 AS CancelAmount,
	--		(Select ISNULL(SUM(R.DiscountAmount),0) FROM  sFee.tReceipt R Where R.SourceId=SA.AcademicId)AS Discount
	--  FROM 
	--		sStudent.vStudentAcademic SA
	--		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
	--		INNER JOIN 
	--		(
	--			SELECT 
	--				FS1.FeeId,
	--				FS1.Id,
	--				ISNULL(FS1.IsOptional,0)AS IsOptional,
	--				ISNULL(FS1.IsVariable,0)AS IsVariable,
	--				ISNULL(FS1.Amount,0)AS Amount,
	--				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
	--				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
	--				FS1.BatchId,
	--				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code AS FeeCode,
	--				FM.FeeHeadId
	--			FROM sFee.tFeeSetup FS1
	--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	--			WHERE 
	--				((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--				AND (FS1.IsOptional=0)
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				UNION ALL
					
	--			SELECT 
	--				FS1.FeeId,
	--				FS1.Id,
	--				ISNULL(FS1.IsOptional,0)AS IsOptional,
	--				ISNULL(FS1.IsVariable,0)AS IsVariable,
	--				ISNULL(FS1.Amount,0)AS Amount,
	--				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
	--				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
	--				FS1.BatchId,
	--				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code As FeeCode,
	--				FM.FeeHeadId
	--			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 FS1.BatchId = SA1.BatchId
	--		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--		WHERE
	--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--			AND (FS1.IsOptional=1)
	--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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,R.DiscountAmount
	--			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 
	--				INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
	--				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
	--				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
	--			WHERE		
	--				(R.SourceTypeId = 2001)
	--				AND (R.IsObsolete = 0) 
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	--				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND (R.ReceiptDate <= @rUptoDate)
	--				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--				AND (tSA.AdmissionDate <= @rUptoDate)
	--					GROUP BY FeeSetupId,R.SourceId,R.DiscountAmount
			
	--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	--		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
	--		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
	--		 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
	--		 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
	--		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	--		 LEFT JOIN
	--		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
	--		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
	--		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
	--		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	--		WHERE	
	--		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
	--		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
	--		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
	--		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--		--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	--		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--		AND ((SA.Code=@rCode) OR (@rCode=''))
	--		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	--		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	--		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	--		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	--	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--	--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--	AND (tSA.AdmissionDate <= @rUptoDate)
	--	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
	--	Order by SA.RollNo 
	--END
	ELSE
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) END as ExampltedRemark,

			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId) END  as ExampltedRemark,

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo
	END
	
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptAllBatchGet]		
    @rOrgId INT,
	@rStudentId BIGINT
AS		 
BEGIN  
	SELECT
		BM.Title AS BatchName,
		--SUM(ISNULL(FST.Amount, 0) + ISNULL(FA.VariableAmount, 0.00)) AS TotalAmount,
		SUM(
			ISNULL(FST.Amount, 0.00) +
			ISNULL(FA.VariableAmount, 0.00) +
			ISNULL(FA.AdditionalAmount, 0.00) -
			ISNULL(FA.DiscountAmount, 0.00) -
			ISNULL(FA.NotApplicableAmount, 0.00)
		) AS TotalAmount,
		--SUM(
		--	ISNULL(FST.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 TotalPendingAmount,
		0 AS TotalPendingAmount,
		SUM(ISNULL(R.PaidAmount, 0.00)) AS TotalPaidAmount
    FROM 
	sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	INNER JOIN 
		(
			SELECT
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				SA1.AcademicId,
				FS1.Id
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON FS1.BatchId = SA1.BatchId
			AND SA1.ClassId = FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			WHERE FS1.IsOptional = 0

			UNION ALL
				
			SELECT
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				SA1.AcademicId,
				FS1.Id
			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 FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId =
		FS1.AdmissionCategoryId
		WHERE SA1.StudentId = @rStudentId
		)FST ON FST.AcademicId=SA.AcademicId
	LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId AND FA.FeeSetupId = FST.Id
    LEFT JOIN 
	(
		SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		FROM	sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		GROUP BY FeeSetupId,R.SourceId
		
		)R ON R.FeeSetupId = FST.Id 
		AND SA.AcademicId = R.SourceId
	WHERE SA.StudentId = @rStudentId
		  AND SA.OrgId = @rOrgId
		  AND SA.BatchId IN 
		  (
			SELECT TOP 2 Id 
			FROM sSetup.tBatchMaster 
			WHERE OrgId = @rOrgId 
			ORDER BY Title DESC
		  )
	GROUP BY --FST.Id,
             BM.Id, BM.Title;
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListBatchWiseGet]  
  @rReportId int,  
  @rReceiptBookId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rFromDate date,  
  @rToDate date,  
  @rFromReceiptNo int,  
  @rToReceiptNo int,  
  @rBatchId int,  
  @rUserId bigint,  
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max),  
  @rIsCancel bit,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int,  
  @rCommonBatch nvarchar(100),  
  @rDepartmentId int,  
  @rFromRollNo int,  
     @rToRollNo int,  
     @rCode nvarchar(20),  
     @rIsDetail bit=0,  
  @rIsFilter bit,  
  @rIsHeader bit,  
  @rCreatedUserName nvarchar(100)='',  
  @rFeeHeadId nvarchar(max) = '',  
  @rIsDisplayOrgGroup bit=0,  
  @rPayTypeId int=0,  
  @rFeeId nvarchar(max) = '',  
  @rFilterId int=0,
  @rOrgIds nvarchar(max) = '',
  @rClassStatusId int=0,
  @rPayTypeIds nvarchar(max) = '' ,
  @rBankName nvarchar(200)='' ,
  @rUserAcessUserId bigint = 0  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN  
SET @rBankName = sCommon.fSearchStringGet(@rBankName)  

  BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,   
  R.ReceiptNumber, 
  SA.DivisionId,   
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo, 
  SA.Code, 
  SA.Name, 
  FM.Code AS FeeCode,   
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount, 
  ISNULL(SA.BatchName,'') BatchName,
   R.ReceiptDate,
   SA.BatchId  
	  
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
  LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = O.Id
  LEFT JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId -- Change innerjoin to left join for mantis id :0029242
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
 INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=R.BatchId AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))

 
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
 AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
 AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  
	END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListGet]  
  @rReportId int,  
  @rReceiptBookId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rFromDate date,  
  @rToDate date,  
  @rFromReceiptNo int,  
  @rToReceiptNo int,  
  @rBatchId int,  
  @rUserId bigint,  
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max),  
  @rIsCancel bit,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int,  
  @rCommonBatch nvarchar(100),  
  @rDepartmentId int,  
  @rFromRollNo int,  
     @rToRollNo int,  
     @rCode nvarchar(20),  
     @rIsDetail bit=0,  
  @rIsFilter bit,  
  @rIsHeader bit,  
  @rCreatedUserName nvarchar(100)='',  
  @rFeeHeadId nvarchar(max) = '',  
  @rIsDisplayOrgGroup bit=0,  
  @rPayTypeId int=0,  
  @rFeeId nvarchar(max) = '',  
  @rFilterId int=0,
  @rOrgIds nvarchar(max) = '',
  @rClassStatusId int=0,
  @rPayTypeIds nvarchar(max) = '' ,
  @rBankName nvarchar(200)='' ,
  @rUserAcessUserId bigint = 0  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN  
SET @rBankName = sCommon.fSearchStringGet(@rBankName)  
IF(@rReportId=10145)
	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,
  PTM.Id AS PayTypeId,
  ISNULL(SA.SUID,'') AS SUID,
  ISNULL(U.DisplayTitle,'') AS CreatedUser
  ,TBM.FromDate AS FromDate
  ,TBM.ToDate AS ToDate
	 ,'' as PermanentStreetOne         -- Start Mentis 29588
	  ,'' as PermanentStreetTwo
	  ,'' as PermanentStreetThree 
	  ,'' as PermanentCountry
	  ,'' as PermanentState
	  ,'' as PermanentCity
	  ,'' as PermanentZipCode
	  ,'' as PermanentContactNo    
	  ,'' as AdmissionNumber 
	  ,SO.DateOfBirth  
	  ,Convert(Decimal,0) as TotalAmount    
	  ,convert(varbinary(max),'') as StudentPhoto                -- #End Mentis 29588
	  ,'' as PresentStreetOne  --Mentis 0030332
	  ,'' as PresentStreetTwo
	  ,'' as PresentCity		--Mentis 0030332
	  ,convert(varbinary(max),'') as CertificateHeaderA4  --mantis - 0030332
	  ,'' AS CurrencyTitle	
	  ,R.ChequeClearDate --Mantis id : 0037794 
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
    --for UserAccess Wise (in ReceiptListFeeHeadHeadwise report)
  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND O.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  
 
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
 INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=R.BatchId AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))
 LEFT JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId  -- Change innerjoin to left join for mantis id :0029242
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 --AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
 AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
 AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  

	END


ELSE
	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,
  PTM.Id AS PayTypeId,
  ISNULL(SA.SUID,'') AS SUID
  ,ISNULL(U.DisplayTitle,'NA') AS CreatedUser
  ,TBM.FromDate AS FromDate
  ,TBM.ToDate AS ToDate
   ,SC.PermanentStreetOne as PermanentStreetOne          -- Mentis 29588
	  ,SC.PermanentStreetTwo as PermanentStreetTwo
	  ,SC.PermanentStreetThree as PermanentStreetThree
	  ,SC.PermanentCountry as PermanentCountry
	  ,SC.PermanentState as PermanentState
	  ,SC.PermanentCity as PermanentCity
	  ,SC.PermanentZipCode as PermanentZipCode
	  ,SC.PermanentContactNo as PermanentContactNo    
	  ,SAD.AdmissionNumber as AdmissionNumber 
	  ,SO.DateOfBirth as DateOfBirth   
	  ,sFee.fFeeAmountSumGet (SA.AcademicId) AS TotalAmount 
	  --,SI.StudentPhoto as StudentPhoto              -- Mentis 29588 
	  ,CASE WHEN @rReportId=30217 THEN 0x ELSE SI.StudentPhoto END AS StudentPhoto -- mantisid - 0032096
	  ,SC.PresentStreetOne  --Mentis 0030332
	  ,SC.PresentStreetTwo
	  ,SC.PresentCity		--Mentis 0030332
	  ,OI.CertificateHeaderA4Portrait AS CertificateHeaderA4  --mantis - 0030332
	  ,sFinanceCommon.fDefaultCurrencyTitleGet(O.OrgGroupId) AS CurrencyTitle		--Mantis - 37460
	  ,R.ChequeClearDate AS ChequeClearDate  --Mantis id : 0037794
	  
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
  LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = O.Id
  LEFT JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId -- Change innerjoin to left join for mantis id :0029242
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
 INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=R.BatchId AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))

  LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentID = SA.StudentID   -- Mentis 29588
  LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentID = SA.StudentID      
  LEFT JOIN sStudent.tStudentImages SI ON SI.StudentID = SA.StudentID      -- Mentis 29588
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
 AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
 AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  
	END
 --ORDER BY R.Id 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListGetDemo]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rFromDate date,
		@rToDate date,
		@rFromReceiptNo int,
		@rToReceiptNo int,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsCancel bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsDetail bit=0,
		@rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rPayTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsCancel AS IsCancel,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.AcademicId,
		SA.FirstName,
		SA.MiddleName,
		SA.LastName,
		SA.Code,
		SA.Name,
		PTM.Title AS PayType,
		R.ChequeNo,
		R.BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		FM.Title AS FeeDetail,
		FM.Code AS FeeCode,
		FM.OrderIndex AS FeeOrderIndex,
		RD.Amount AS DetailAmount,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		ISNULL(FHM.Title,'') AS FeeHead,
		ISNULL(FHM.Code,'') AS FeeHeadCode,
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(R.Remark,'') AS Remark,
		DM.Id AS DepartmentId,
		DM.Title AS DepartmentName,
		SA.ClassOrderIndex,
		ISNULL(SO.GenderId,0) AS GenderId,
		ISNULL(SA.BatchName,'') BatchName,
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,
		sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,
		R.ChequeDate,
		ISNULL(FM.Id,0) AS FeeId,
		ISNULL(FM.Title,'') AS Fee,
		ISNULL(SF.FatherName,'' ) AS FatherName,
		ISNULL(SF.MotherName,'' ) AS MotherName
  FROM 
			sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptDetail RD
			ON RD.ReceiptId=R.Id
		INNER JOIN sFee.tFeeSetup FS
			ON FS.Id=RD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM
			ON FM.Id=FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tDepartmentMaster DM
			ON SA.DepartmentId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster O
			ON O.Id=sa.OrgId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		LEFT JOIN sStudent.tStudentOther SO
			ON SO.StudentId = SA.StudentId
		LEFT JOIN sStudent.tStudentFamily SF
			ON SF.StudentId = SA.StudentId
	   LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
     LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
WHERE 
	R.SourceTypeId = 2001
	AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId = @rStatusId OR @rStatusId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))
	AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
   )
	ORDER BY R.ReceiptNumber
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailPendingFeeAsOnDateWiseGet]
						
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)='',
			@rDivisionId int = 0,
			@rAdmissionCategoryId int = 0
			

	WITH EXECUTE AS CALLER
AS 
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

		SELECT  @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount,0.00),1,2,@lOrgGroupId)
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
		SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END

	IF(@rOrgGroupId=0) SET @rOrgGroupId=@lOrgGroupId

	SELECT 
	
			FR.ReceiptNumber,
			FR.ReceiptDate,		
			SA.Name AS Name, 
			SA.Code,
			SA.RollNo,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,		
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,					
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,		 
			OM.Title AS OrganizationName,			  
			(CASE 	
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,			
			FR.IsObsolete AS IsCancelReceipt, 
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			--BM.Title AS Batch,				  
			SA.BatchName AS Batch,
			FR.ChequeDate AS ChequeDate,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
			ISNULL(RBM.DigitalSignature,0x) AS DigitalSignature,
			--[sFee].[fPendingFeeAmountGet] (@rAcademicId bigint, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int, @rMonthId int, @rUptoDate Date,@rReceiptBookId int,@rFeeId nvarchar(max)=''),
			[sFee].[fPendingFeeAmountAsOnDatewiseGet] (SA.AcademicId , SA.BatchId , SA.OrgId , SA.OrgGroupBatchId , Convert(Date ,GetDate())) AS PendingFeeAsOnDatewise,
			ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
			ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted
			
 	FROM 
	
			sFee.tReceipt FR		
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001			
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id		
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			--INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((OM.Id = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
			AND ((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0) )
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END

--BEGIN
--SELECT

-- 0	AS ReceiptNumber,     
-- CAST('' AS date) AS ReceiptDate,    
-- ''	AS Name, 
--''	AS Code, 
-- 0	AS RollNo, 
--''	AS ClassDivision, 
--0	AS FeeHeadId, 
--''	AS FeeHead, 
--0	AS FeeId, 
--''	AS FeeName, 
--CAST(0.0 AS decimal(12,2)) AS PaidAmount,
--CAST(0 AS tinyint) AS PayTypeId,
--''	AS PayType,
--''	AS ChequeNo,	
--''	AS BankName, 
--''	AS Address1, 
--''	AS Address2, 
--''	AS FullTitle, 
--CAST(0.0 AS decimal(12,2)) AS TotalReceiptAmount,   
--CAST(0.0 AS decimal(12,2)) AS ReceiptAmount,					
--''	AS ReceiptAmountInWords,		
--CAST(0.0 AS decimal(12,2)) AS DiscountAmount, 
--''	AS Remark, 	
--0x  AS OrgLogo, 
--''	AS Remark1,
--''	AS Remark2,			 
--''	AS OrganizationName,  
--''	AS MonthDetail,    			
--''	AS FeeDuration,		
--CAST(0 AS smallint)	AS FeeHeadOrderIndex,
--CAST(0 AS bit) AS IsCancelReceipt,
--''	AS CurrencyCode,
--''	AS CurrencyTitle,
--''	AS Batch,
--CAST('' AS date) AS ChequeDate,
--''  AS GroupTitle,
--CAST(0 AS tinyint) AS HeaderDisplayId,
--0x  AS ReceiptBookHeader, 
--0x AS DigitalSignature,			
--'' AS PendingFeeAsOnDatewise,      
--CAST(0 AS bit) AS IsSuppressFeeDetail,
--CAST(0 AS bit) AS IsFeeInvoiceHeadwise,
--CAST(0 AS bit) AS IsMonthDetailOnly,
--CAST(0 AS bit) AS IsDisplaySchoolName,
--CAST(0 AS bit) AS IsOnPrePrinted

--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet] 
	@rReportId INT = 0
	,@rReceiptId BIGINT = 0
	,@rOrgGroupId INT = 0
	,@rReceiptBookId INT = 0
	,@rFromReceiptNo INT = 0
	,@rToReceiptNo INT = 0
	,@rOrgId INT = 0
	,@rBatchId INT = 0
	,@rReceiptDate DATE = ''
	,@rClassId INT = 0
	,@rOrgIds NVARCHAR(max) = ''
	,@rReceiptPrintGroupId NVARCHAR(100) = ''
	,@rDivisionId INT = 0
	,@rAdmissionCategoryId INT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lOrgGroupId INT = 0
	DECLARE @lAmountInWord NVARCHAR(500) = ''
	DECLARE @lReceiptAmount DECIMAL(12, 2) = 0.0
	DECLARE @lCurrencyCode NVARCHAR(20) = ''
	DECLARE @lCurrencyTitle NVARCHAR(100) = ''
	DECLARE @lIDConfigValue NVARCHAR(50) = '',@lOrgGroup_Id INT = 0

	SELECT @lOrgGroup_Id = OrgGroupId
	FROM sSetup.tOrganizationMaster
	WHERE Id = @rOrgId

	SELECT @lIDConfigValue = ItemValue
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236
		AND SourceId = @rOrgGroupId

	IF (@rOrgGroupId = 0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId
			,@lReceiptAmount = R.ReceiptAmount
		FROM sFee.tReceipt R
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id
		WHERE R.Id = @rReceiptId

		SELECT @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount, 0.00), 1, 2, @lOrgGroupId)
		--SELECT @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) -- Created common function for both code and title by Foram
		--SELECT @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) -- Created common function for both code and title by Foram
	END
	--ELSE
	--BEGIN
	--	--SELECT @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) -- Created common function for both code and title by Foram
	--END

	IF (@rOrgGroupId = 0)
		SET @rOrgGroupId = @lOrgGroupId

	SELECT @lCurrencyCode = CurrencyCode, @lCurrencyTitle = CurrencyTitle FROM [sFinanceCommon].[fDefaultCurrencyValueGet](@rOrgGroupId) -- For Optimization by Foram

	SELECT FRD.ReceiptId
		,FR.ReceiptNumber
		,FR.ReceiptDate
		,SA.AcademicId
		,SA.Name AS Name --SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
		,SA.Code
		,SA.RollNo
		,SA.ClassId
		,SA.DivisionId
		,SA.ClassName
		,SA.DivisionName
		,SA.ClassName + ' - ' + SA.DivisionName AS ClassDivision
		,FM.FeeHeadId
		,FHM.Title AS FeeHead
		,FM.Id AS FeeId
		,FM.Title AS FeeName
		,FRD.Amount AS PaidAmount
		,PTM.Id AS PayTypeId
		,PTM.Title AS PayType
		,
		--changes by Jash on 06/11/2020--%
		CASE 
			WHEN ISNULL(FR.ChequeNo, '') != ''
				THEN FR.ChequeNo
			ELSE CONVERT(NVARCHAR(20), ISNULL(FR.PaymentTransactionId, ''))
			END AS ChequeNo
		,
		--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo
		--	WHEN ISNULL(PT.BankTransactionId,'') = '' THEN  CONVERT(nvarchar(20),FR.PaymentTransactionId)
		--	ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
		--%ISNULL(FR.ChequeNo,'') AS ChequeNo,
		ISNULL(FR.BankName, '') AS BankName
		,ISNULL(RBM.Address1, '') AS Address1
		,ISNULL(RBM.Address2, '') AS Address2
		,ISNULL(RBM.FullTitle, '') AS FullTitle
		,ISNULL(FR.TotalReceiptAmount, 0.00) AS TotalReceiptAmount
		,ISNULL(FR.ReceiptAmount, 0.00) AS ReceiptAmount
		,sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount, 0.00), 1, 2, @rOrgGroupId) AS ReceiptAmountInWords
		--,(
		--	CASE 
		--		WHEN @rOrgGroupId = 0 -- For Single Receipt
		--			THEN ''
		--		WHEN @rOrgGroupId != 0 -- For Bulk Receipt
		--			THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount, 0.00), 1, 2, @rOrgGroupId)
		--		END
		--	) AS ReceiptAmountInWords
		,ISNULL(FR.DiscountAmount, 0.00) AS DiscountAmount
		,FR.Remark
		,(
			CASE 
				WHEN ISNULL(FR.PaymentTransactionId, 0) > 0
					THEN -- Navrachana
						'Online Generated'
				ELSE ISNULL(U.DisplayTitle, '')
				END
			) AS UserName
		,OM.OrgLogo
		--ISNULL(U.DisplayTitle,'') AS UserName,
		,RBM.Remark1
		,RBM.Remark2
		,ISNULL(RBM.IsOnPrePrinted, 0) AS IsOnPrePrinted
		,ISNULL(RBM.IsSupressLogo, 0) AS IsSupressLogo
		,ISNULL(RBM.IsDisplaySchoolName, 0) AS IsDisplaySchoolName
		,RBM.ReportId
		,OM.Title AS OrganizationName
		,
		--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0 THEN 
		--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	 			  
		(
			CASE 
				WHEN RBM.ReportId = 20576
					THEN [sFee].[fReceiptMonthDetailGet](FR.ID, 0) -- HM patel report
				WHEN RBM.ReportId = 30457
					THEN [sFee].[fReceiptMonthDetailGet](FR.ID, 1)
				WHEN ISNULL(RBM.IsMonthDetailOnly, 0) = 1 AND ISNULL(RBM.IsFeeInvoiceHeadwise, 0) = 1
					THEN [sFee].[fFeeHeadMonthNameGet](FR.ID, FHM.Id) -- Head wise Month name in detail
				WHEN ISNULL(RBM.IsMonthDetailOnly, 0) = 1 AND ISNULL(RBM.IsFeeInvoiceHeadwise, 0) = 0
					THEN [sFee].[fFeeMonthNameGet](FR.ID, FM.Id) -- Fee wise Month name in detail
				ELSE ''
				END
			) AS MonthDetail
		,(
			CASE 
				WHEN ISNULL(RBM.IsFeeInvoiceHeadwise, 0) = 1 AND @rReceiptId > 0 -- Added @rReceiptId condition for optimization by Foram
					THEN Stuff((
								SELECT N', ' + FS1.FeeDuration
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
									AND FR1.SourceTypeId = 2001
								INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
								INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId = FM1.Id
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
								WHERE FM1.FeeHeadId = FM.FeeHeadId
									AND FS.ClassId = FS1.ClassId
									AND FR1.Id = @rReceiptId
									--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
									AND (ISNULL(SA1.OrgId, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rOrgIds, ',')) OR @rOrgIds = '')
								ORDER BY FS1.StartDate
								FOR XML PATH('')
									,TYPE
								).value('text()[1]', 'nvarchar(max)'), 1, 2, N'') -- Fee Head wise Fee Duration
				WHEN ISNULL(RBM.IsFeeInvoiceHeadwise, 0) = 0
					THEN FS.FeeDuration -- Fee wise Fee Duration
				ELSE ''
				END
			) AS FeeDuration
		,
		--Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
		--sFee.tReceipt FR1				
		--INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
		--INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
		--INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
		--INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
		--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
		----Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
		--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
		--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		-- Order By FS.StartDate
		--FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,			
		DM.Title AS DepartmentName
		,FM.OrderIndex AS FeeOrderIndex
		,FHM.OrderIndex AS FeeHeadOrderIndex
		,FR.IsObsolete AS IsCancelReceipt
		,@lCurrencyCode AS CurrencyCode
		,@lCurrencyTitle AS CurrencyTitle
		,BM.Title AS Batch
		,FR.ChequeDate AS ChequeDate
		,ISNULL(RBM.IsMonthDetailOnly, 0) AS IsMonthDetailOnly
		,ISNULL(RBM.IsFeeInvoiceHeadwise, 0) AS IsFeeInvoiceHeadwise
		,ISNULL(RBM.GroupTitle, '') AS GroupTitle
		,ISNULL(RBM.IsSuppressFeeDetail, 0) AS IsSuppressFeeDetail
		,ISNULL(CGM.Title, '') AS CollectionGroupName
		,ISNULL(FI.InvoiceNumber, 0) AS InvoiceNumber
		,SA.SUID
		,CASE WHEN RBM.IsOnPrePrinted = 1 THEN 2 ELSE ISNULL(RBM.HeaderDisplayId, 1) END AS HeaderDisplayId
		,RBM.ReceiptBookHeader
		,RBM.ServiceTaxPercentage
		,ISNULL(FR.AmountAfterDiscount, 0) AS AmountAfterDiscount
		--,(
		--	CASE 
		--		WHEN FR.CGSTPercentage IS NULL
		--			THEN RBM.CGSTPercentage
		--		ELSE FR.CGSTPercentage
		--		END
		--	) AS CGSTPercentage
		,ISNULL(FR.CGSTPercentage,RBM.CGSTPercentage) AS CGSTPercentage -- removed above case and added dircetly ISNULL for optmization By Foram
		--,(
		--	CASE 
		--		WHEN FR.SGSTPercentage IS NULL
		--			THEN RBM.SGSTPercentage
		--		ELSE FR.SGSTPercentage
		--		END
		--	) AS SGSTPercentage
		,ISNULL(FR.SGSTPercentage,RBM.SGSTPercentage) AS SGSTPercentage -- removed above case and added dircetly ISNULL for optmization By Foram
		,ISNULL(FR.CGSTAmount, 0) AS CGSTAmount
		,ISNULL(FR.SGSTAmount, 0) AS SGSTAmount
		,ISNULL(OOM.GSTINNo, '') AS GSTINNo
		,ISNULL(OOM.HSNSACCode, '') AS HSNSACCode
		,@lIDConfigValue AS ItemValue
		,SF.FatherName
		,SF.MotherName
		,ISNULL(FA.DiscountAmount, 0) AS ExemptionAmount
		,ISNULL(FA.Remark, '') AS ExemptionRemark
		,EI.EmployeeSign
		,ISNULL(SC.PresentCity, '') AS PresentCity
		--,(
		--			ISNULL((
		--			CASE 
		--				WHEN SC.PresentStreetOne IS NOT NULL
		--					AND SC.PresentStreetOne != ''
		--					THEN '' + SC.PresentStreetOne
		--				END
		--			), '') 
		--			+ ISNULL((
		--			CASE 
		--				WHEN SC.PresentStreetTwo IS NOT NULL
		--					AND SC.PresentStreetTwo != ''
		--					THEN ', ' + SC.PresentStreetTwo
		--				END
		--			), '') 
		--			+ ISNULL((
		--			CASE 
		--				WHEN SC.PresentStreetThree IS NOT NULL
		--					AND SC.PresentStreetThree != ''
		--					THEN ', ' + SC.PresentStreetThree
		--				END
		--			), '') 
		--			+ ISNULL((
		--			CASE 
		--				WHEN SC.PresentCity IS NOT NULL
		--					AND SC.PresentCity != ''
		--					THEN ', ' + SC.PresentCity
		--				END
		--			), '') 
		--			+ ISNULL((
		--			CASE 
		--				WHEN SC.PresentState IS NOT NULL
		--					AND SC.PresentState != ''
		--					THEN ', ' + SC.PresentState
		--				END
		--			), '') 
		--			+ ISNULL((
		--			CASE 
		--				WHEN SC.PresentZipCode IS NOT NULL
		--					AND SC.PresentZipCode != ''
		--					THEN ', ' + SC.PresentZipCode
		--				END
		--			), '')
		--	) AS PresentAdress
		,LTRIM(
			ISNULL(NULLIF(SC.PresentStreetOne, ''), '') +
			ISNULL(', ' + NULLIF(SC.PresentStreetTwo, ''), '') +
			ISNULL(', ' + NULLIF(SC.PresentStreetThree, ''), '') +
			ISNULL(', ' + NULLIF(SC.PresentCity, ''), '') +
			ISNULL(', ' + NULLIF(SC.PresentState, ''), '') +
			ISNULL(', ' + NULLIF(SC.PresentZipCode, ''), '')
		) AS PresentAddress -- removed above case and added dircetly ISNULL for optmization By Foram
		--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
		,SC.ParentContactNo
		,ISNULL(RBM.IsDisplayPendingFeeAmount, 0) AS IsDisplayPendingFeeAmount
		,CASE 
			WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742
				THEN (
						CASE 
							WHEN ISNULL(RBM.IsDisplayPendingFeeAmount, 0) = 0
								THEN 0
							ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId, RBM.Id), 0)
							END
						)
			ELSE (
					CASE 
						WHEN ISNULL(RBM.IsDisplayPendingFeeAmount, 0) = 0
							THEN 0
						ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId, 0), 0)
						END
					)
			END AS PendingFeeAmount
		,SA.FirstName
		,SA.LastName
		,ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId), 0) AS FeeAmount
		,ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId), 0) AS ExemptionAmountSum
		,[sFee].[fTransportBusRouteGet](SA.StudentId, FR.OrgGroupBatchId) AS TransportBusRoute
		,ISNULL(RBM.BankAccountNumber, '') AS BankAccountNumber
		,ISNULL(FHM.Number, 0) AS FeeHeadNumber
		,ISNULL(FM.Number, 0) AS FeeNumber
		,ISNULL(RBM.DigitalSignature, 0x) AS DigitalSignature
		,ISNULL(FR.CancelStatusRemark, '') AS CancelStatusRemark
		,FS.Amount AS FeeSetupAmount
		,FR.CreatedDateTime
		,ISNULL(FR.PaymentTransactionId, 0) AS PaymentTransactionId
		,SA.MiddleName
		,CONVERT(CHAR(5), FR.CreatedDateTime, 108) AS CreatedTime
		,
		--by megha - 0026430
		(
			CASE 
				WHEN ISNULL(FA.VariableAmount, 0) > 0
					THEN FA.VariableAmount
				WHEN ISNULL(FS.Amount, 0) > 0
					THEN FS.Amount
				END
			) + ISNULL(FA.AdditionalAmount, 0) - ISNULL(FA.DiscountAmount, 0) - ISNULL(FA.NotApplicableAmount, 0) AS TotalPayableAmount
		,OGM.Title AS OrgGroupTitle
		,NID.CollectionGroupName AS NextInstallmentName
		,--Mantis End- 0031305
		ISNULL(HM.Title, '') AS House
		,--add for mantis: 32658
		NID.StartDate AS NextInstallmentStartDate
		,--Mantis -  Start 32760
		NID.EndDate AS NextInstallmentEndDate
		,NID.PendingAmount AS NextInstallmentAmount
		,--Mantis -  End 32760			
		ISNULL([sFee].[fFeeActualAmountSumGet](FR.SourceId), 0) AS FeeActualAmount
		,-- MantisId : 0032658
		ISNULL(SC.StudentContactNo, '') AS StudentContactNo
		,-- MantisId : 0032895
		--mantis Start - 0033973
		ISNULL(SC.PermanentStreetOne, '') AS PermanentStreetOne
		,ISNULL(SC.PermanentStreetTwo, '') AS PermanentStreetTwo
		,ISNULL(SC.PermanentStreetThree, '') AS PermanentStreetThree
		,
		--mantis End - 0033973
		--mantis Start - 0034206
		ISNull(SC.PermanentCountry, '') AS PermanentCountry
		,ISNull(SC.PermanentState, '') AS PermanentState
		,ISNull(SC.PermanentCity, '') AS PermanentCity
		,ISNull(SC.PermanentZipCode, '') AS PermanentZipCode
		,
		--mantis End - 0034206
		FS.StartDate
		,--mantis : 0034274
		FS.EndDate
		,--mantis : 0034274
		ISNull(CSM.Title, '') AS CasteCategory
		,--mantis : 0034588
		LM.Title AS Medium
		,--mantis : 0034588
		CASE 
			WHEN @rOrgGroupId = 1134
				OR @rOrgGroupId = 1742
				THEN ISNULL([sFee].[fPaidFeeAmountReceiptBookwiseGet](FR.SourceId, RBM.Id), 0)
			ELSE ISNULL([sFee].[fPaidFeeAmountReceiptBookwiseGet](FR.SourceId, 0), 0)
			END AS TotalPaidAmount
		,--mantis : 0034862
		ISNULL(SO.UIDNumber, '') AS UID
		,--Mantis - 35268
		ISNULL((
				SELECT TOP 1 BusRoute
				FROM [sFee].[fStudentWiseBusRoute](SA.StudentId, FR.OrgGroupBatchId)
				), '') AS BusRoute		,--Mantis - 35545
		ISNULL((
				SELECT TOP 1 PickupPoint
				FROM [sFee].[fStudentWiseBusRoute](SA.StudentId, FR.OrgGroupBatchId)
				), '') AS PickupPoint		,--Mantis - 35545
		--RR.RefundAmount AS RefundAmount		--mantis : 35909
		ISNULL((
				SELECT SUM(RefundAmount)
				FROM sFee.tReceiptRefund
				WHERE ReceiptId = FR.Id
				), 0) AS RefundAmount		,--mantis : 35909
		ISNULL(SF.FatherMail, '') AS FatherMail
		,--add for mantis : 0036283
		ISNULL(SF.MotherMail, '') AS MotherMail
		,--add for mantis : 0036283
		ISNULL(SF.FatherContactNo, '') AS FatherContactNo
		,--add for mantis : 0036283
		ISNULL(SF.MotherContactNo, '') AS MotherContactNo
		,--add for mantis : 0036283
		--ISNULL(FSCGM.Title,'') AS FeeSetupWiseCollectionGroupName --add for mantis : 37204
		STUFF((
				SELECT DISTINCT ', ' + ISNULL(CGM.Title, '')
				FROM sFee.tReceipt FR1
				INNER JOIN sfee.tReceiptDetail RD ON FR1.Id = RD.ReceiptId
					AND FR1.SourceTypeId = 2001
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
					AND FS.ReceiptBookId = FR1.ReceiptBookId
				INNER JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId = CGM.Id
					AND FR1.ReceiptBookId = CGM.ReceiptBookId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR1.SourceId
					AND SA.BatchId = FS.BatchId
					AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
				WHERE FR1.Id = FR.Id
				FOR XML PATH('')
					,TYPE
				).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS FeeSetupWiseCollectionGroupName		,--Add for mantis : 0037204
		--,PT.ID AS PaymentGatewayID
		SO.GenderId
		,-- Add for mantis : 0038284
		ISNULL(OI.SchoolStamp, 0x) AS SchoolStamp
		,--Added by dhananjay for mantis : 39933
		(
			CASE 
				WHEN ISNULL(FR.PaymentTransactionId, 0) > 0
					THEN -- Navrachana
						'Online Generated'
				ELSE ISNULL([sHrm].[fEmployeeNameGet](EM.FirstName, EM.MiddleName, EM.LastName, OM.EmployeeNameFormatId), '')
				END
			) AS UserNameFormat
		,--Mantis - 404385
		ISNULL(OM.HomePage, '') AS Board --Mantis - 42048
		,ISNULL(SC.PresentStreetOne,'') AS LocalPresentStreetOne--mantis : 0043901
		,ISNULL(SC.PresentStreetTwo,'') AS LocalPresentStreetTwo--mantis : 0043901
		,ISNULL(SC.PresentStreetThree,'') AS LocalPresentStreetThree--mantis : 0043901,
		,CONVERT(Nvarchar(10),SA.OrgId) AS OrgIdText  --Mantis - 44201
		,CONVERT(Nvarchar(20),SA.StudentId) AS StudentIdText	--Mantis - 44201
		,ISNULL([sFee].[fStudentFeeSetupReceiptAmountGet](SA.AcademicId,FS.id),0) AS TotalAmountFeeSetWise --mantis : 0043901
	FROM sFee.tReceipt FR
	INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId AND FR.SourceTypeId = 2001
	INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id
	INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = FR.PayTypeId
	INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId = DM.Id
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FR.ReceiptBookId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId -- Changed Left to Inner join for optimization by Foram
	INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId -- Mantis : 0029314
	INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId --mantis : 0034588	
	LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId = FS.Id AND FA.SourceId = SA.AcademicId
	LEFT JOIN sSecurity.tUser U ON U.Id = FR.CreatedUserId
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id --Added by dhananjay for mantis : 39933
	LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id = OOM.OrgId
	LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FR.CollectionGroupId
	LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = FR.FeeInvoiceId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId = 95
	--LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
	LEFT JOIN (SELECT CollectionGroupName,StartDate,EndDate,PendingAmount,SourceId,SourceTypeId 
	FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @rReceiptId)) NID -- Mantis Start - 0031305
			ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId -- Mantis End - 0031305
	LEFT JOIN sStudent.tStudentOther AS SO ON SO.StudentId = SA.StudentId
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId --add for mantis: 32658
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id = SO.CastCategoryId --mantis : 0034588
	--LEFT JOIN sFee.tReceiptRefund RR ON RR.ReceiptId = FR.Id		--mantis : 35909
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95 --Mantis - 40438
	WHERE (
			(FR.Id = @rReceiptId)
			OR (@rReceiptId = 0)
			)
		AND (
			(RBM.OrgGroupId = @rOrgGroupId)
			OR (@rOrgGroupId = 0)
			)
		AND (
			(FR.ReceiptBookId = @rReceiptBookId)
			OR (@rReceiptBookId = 0)
			)
		AND (
			(FR.ReceiptNumber >= @rFromReceiptNo)
			OR (@rFromReceiptNo = 0)
			)
		AND (
			(FR.ReceiptNumber <= @rToReceiptNo)
			OR (@rToReceiptNo = 0)
			)
		AND (
			(FR.BatchId = @rBatchId)
			OR (@rBatchId = 0)
			)
		AND (
			(BM.OrgId = @rOrgId)
			OR (@rOrgId = 0)
			)
		AND (
			(FR.ReceiptDate = @rReceiptDate)
			OR (ISNULL(@rReceiptDate, '') = '')
			)
		AND (
			(SA.ClassId = @rClassId)
			OR (@rClassId = 0)
			)
		AND (
			(SA.DivisionId = @rDivisionId)
			OR (@rDivisionId = 0)
			)
		AND (
			ISNULL(SA.OrgId, 0) IN (
				SELECT cast(item AS INT)
				FROM sCommon.fnsplit(@rOrgIds, ',')
				)
			OR @rOrgIds = ''
			)
		AND (
			(ISNULL(FR.ReceiptPrintGroupId, '') = @rReceiptPrintGroupId)
			OR (ISNULL(@rReceiptPrintGroupId, '') = '')
			)
		AND (
			(FS.AdmissionCategoryId = @rAdmissionCategoryId)
			OR (@rAdmissionCategoryId = 0)
			)
	ORDER BY FS.StartDate
		,FHM.OrderIndex
		,FM.OrderIndex ASC
END
	--BEGIN
	--SELECT
	-- CAST(0 AS bigint) AS ReceiptId,
	-- 0	AS ReceiptNumber,
	-- CAST('' AS date) AS ReceiptDate,
	-- CAST(0 AS bigint) AS AcademicId,
	-- ''	AS Name,
	--''	AS Code,
	-- 0	AS RollNo,
	--0	AS ClassId,
	--0	AS DivisionId,
	--''	AS ClassName,
	--''	AS DivisionName,
	--''	AS ClassDivision,
	--0	AS FeeHeadId,
	--''	AS FeeHead,
	--0	AS FeeId,
	--''	AS FeeName,
	--CAST(0.0 AS decimal(12,2)) AS PaidAmount,
	--CAST(0 AS tinyint) AS PayTypeId,
	--''	AS PayType,
	--''	AS ChequeNo,	
	--''	AS BankName,
	--''	AS Address1,
	--''	AS Address2,
	--''	AS FullTitle,
	--CAST(0.0 AS decimal(12,2)) AS TotalReceiptAmount,
	--CAST(0.0 AS decimal(12,2)) AS ReceiptAmount,					
	--''	AS ReceiptAmountInWords,		
	--CAST(0.0 AS decimal(12,2)) AS DiscountAmount,
	--''	AS Remark,
	--''	AS UserName,		
	--0x  AS OrgLogo,
	--''	AS Remark1,
	--''	AS Remark2,			 
	--CAST(0 AS bit) AS IsOnPrePrinted,
	--CAST(0 AS bit) AS IsSupressLogo,
	--CAST(0 AS bit) AS IsDisplaySchoolName,
	--0	AS ReportId,
	--''	AS OrganizationName,		  
	--''	AS MonthDetail,    			
	--''	AS FeeDuration,		
	--''	AS DepartmentName,
	-- 0	AS FeeOrderIndex,
	--CAST(0 AS smallint)	AS FeeHeadOrderIndex,
	--CAST(0 AS bit) AS IsCancelReceipt,
	--''	AS CurrencyCode,
	--''	AS CurrencyTitle,
	--''	AS Batch,
	--CAST('' AS date) AS ChequeDate,
	--CAST(0 AS bit) AS IsMonthDetailOnly,
	--CAST(0 AS bit) AS IsFeeInvoiceHeadwise,
	--''	AS GroupTitle,
	--CAST(0 AS bit) AS IsSuppressFeeDetail,
	--''	AS CollectionGroupName,
	--0	AS InvoiceNumber,
	--''	AS SUID,
	--CAST(0 AS tinyint) AS HeaderDisplayId,
	--0x  AS ReceiptBookHeader,
	--CAST(0.0 AS decimal(6,2)) AS ServiceTaxPercentage,
	--CAST(0.0 AS decimal(12,2)) AS AmountAfterDiscount,
	--CAST(0.0 AS decimal(5,2)) AS CGSTPercentage,
	--CAST(0.0 AS decimal(5,2)) AS SGSTPercentage,
	--CAST(0.0 AS decimal(12,2)) AS CGSTAmount,
	--CAST(0.0 AS decimal(12,2))	AS SGSTAmount,
	--''	AS GSTINNo,
	--''	AS HSNSACCode,
	--''	AS ItemValue ,
	--''	AS FatherName,
	--''	AS MotherName,
	--CAST(0.0 AS decimal(12,2)) AS ExemptionAmount,
	--''	AS ExemptionRemark,
	--0x AS EmployeeSign,
	--''	AS PresentCity,
	--''	AS PresentAdress,
	--''	AS ParentContactNo,	
	--CAST(0 AS bit) AS IsDisplayPendingFeeAmount,
	--CAST(0.0 AS decimal(12,0)) AS PendingFeeAmount,
	--''	AS FirstName,
	--''	AS LastName,
	--CAST(0.0 AS decimal(12,0))	AS FeeAmount,
	--CAST(0.0 AS decimal(12,0)) AS ExemptionAmountSum,
	--''	AS TransportBusRoute,
	--''	AS BankAccountNumber,
	--0	AS FeeHeadNumber,
	--0	AS FeeNumber,
	--0x AS DigitalSignature,
	--''	AS CancelStatusRemark,
	--CAST(0.0 AS decimal(12,2))	AS FeeSetupAmount,
	--CAST('' AS date)	AS CreatedDateTime ,
	--CAST(0 AS bigint)	AS PaymentTransactionId,
	--''	AS MiddleName,
	--'' AS CreatedTime,
	-- 0 AS TotalPayableAmount,
	-- '' AS OrgGroupTitle,
	-- '' AS NextInstallmentName,
	-- '' AS House,
	-- CAST('' AS date) AS NextInstallmentStartDate,
	-- CAST('' AS date) NextInstallmentEndDate,
	-- CAST(0.0 AS decimal(12,2)) AS NextInstallmentAmount,
	-- CAST(0.0 AS decimal(12,2)) AS FeeActualAmount,
	-- '' AS StudentContactNo,
	-- '' AS PermanentStreetOne,
	-- '' AS PermanentStreetTwo,
	-- '' AS PermanentStreetThree,
	--'' AS PermanentCountry,
	-- '' AS PermanentState,
	-- '' AS PermanentCity,
	-- '' AS PermanentZipCode,
	-- CAST('' AS date) AS StartDate,
	-- CAST('' AS date) AS EndDate,  
	--   '' AS CasteCategory,  
	--	   '' AS Medium,
	--CAST(0.0 AS decimal(12,0)) AS TotalPaidAmount,
	--''	AS UID,
	--'' AS BusRoute,
	--'' AS PickupPoint,
	-- CAST(0.0 AS decimal(12,2)) AS RefundAmount,
	--'' AS FatherMail,
	--'' AS MotherMail,
	--'' AS FatherContactNo,
	--'' AS MotherContactNo,
	--'' AS FeeSetupWiseCollectionGroupName,
	--'' AS GenderId,
	--'' AS UserNameFormat,
	--'' AS Board		--Mantis - 42048
	--,'' AS LocalPresentStreetOne
	--,'' AS LocalPresentStreetTwo
	--,'' AS LocalPresentStreetThree
	--Mantis Start - 44201
	--,'' AS OrgIdText	
	--,'' AS StudentIdText
	--Mantis End - 44201
	--,CAST(0.0 AS decimal(12,0)) AS TotalAmountFeeSetWise 
	--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptDoubleA5WithNextPendingFeeGet]			
	@rReportId int=0,
	@rReceiptId bigint = 0,
	@rOrgGroupId int = 0,
	@rReceiptBookId int = 0,
	@rFromReceiptNo int=0,
	@rToReceiptNo int=0,
	@rOrgId int = 0,
	@rBatchId int = 0,
	@rReceiptDate Date='',
	@rClassId int = 0,
	@rOrgIds nvarchar(max) = '',
	@rReceiptPrintGroupId nvarchar(100)='',
	@rDivisionId int = 0,
	@rAdmissionCategoryId int = 0  -- MantisId : 0029114

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

		SELECT  @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount,0.00),1,2,@lOrgGroupId)
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
		SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END

	IF(@rOrgGroupId=0) SET @rOrgGroupId=@lOrgGroupId

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  ISNULL(FR.PaymentTransactionId,0) > 0 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchorolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			(CASE WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE WHEN RBM.IsOnPrePrinted=1 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
	        ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			SC.ParentContactNo,
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0) END)
			ELSE 
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) END AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(FM.Number,0) AS FeeNumber,
			ISNULL(RBM.DigitalSignature,0x) AS DigitalSignature,
			ISNULL(FR.CancelStatusRemark,'') AS CancelStatusRemark,
			FS.Amount AS FeeSetupAmount,
			FR.CreatedDateTime ,
			ISNULL(FR.PaymentTransactionId,0) As PaymentTransactionId,
			ISNULL(SA.MiddleName, '') AS FatherName,
			CONVERT(char(5),FR.CreatedDateTime,108) AS CreatedTime,
			ISNULL(GM.Title, '') AS Gender,
			NID.PendingAmount AS NextInstallmentAmount,
			NID.CollectionGroupId AS NextInstallmentId,
			NID.StartDate AS NextInstallmentStartDate,
			NID.EndDate AS NextInstallmentEndDate,
			NID.CollectionGroupName AS NextInstallmentName		
	FROM 
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SA.GenderId
			LEFT JOIN (SELECT * FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @rReceiptId)) NID ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
			AND ((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0)) -- MantisId : 0029114
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END

--BEGIN
--SELECT
-- CAST(0 AS bigint) AS ReceiptId,
-- 0	AS ReceiptNumber,
-- CAST('' AS date) AS ReceiptDate,
-- CAST(0 AS bigint) AS AcademicId,
-- ''	AS Name,
--''	AS Code,
-- 0	AS RollNo,
--0	AS ClassId,
--0	AS DivisionId,
--''	AS ClassName,
--''	AS DivisionName,
--''	AS ClassDivision,
--0	AS FeeHeadId,
--''	AS FeeHead,
--0	AS FeeId,
--''	AS FeeName,
--CAST(0.0 AS decimal(12,2)) AS PaidAmount,
--CAST(0 AS tinyint) AS PayTypeId,
--''	AS PayType,
--''	AS ChequeNo,	
--''	AS BankName,
--''	AS Address1,
--''	AS Address2,
--''	AS FullTitle,
--CAST(0.0 AS decimal(12,2)) AS TotalReceiptAmount,
--CAST(0.0 AS decimal(12,2)) AS ReceiptAmount,					
--''	AS ReceiptAmountInWords,		
--CAST(0.0 AS decimal(12,2)) AS DiscountAmount,
--''	AS Remark,
--''	AS UserName,		
--0x  AS OrgLogo,
--''	AS Remark1,
--''	AS Remark2,			 
--CAST(0 AS bit) AS IsOnPrePrinted,
--CAST(0 AS bit) AS IsSupressLogo,
--CAST(0 AS bit) AS IsDisplaySchoolName,
--0	AS ReportId,
--''	AS OrganizationName,		  
--''	AS MonthDetail,    			
--''	AS FeeDuration,		
--''	AS DepartmentName,
-- 0	AS FeeOrderIndex,
--CAST(0 AS smallint)	AS FeeHeadOrderIndex,
--CAST(0 AS bit) AS IsCancelReceipt,
--''	AS CurrencyCode,
--''	AS CurrencyTitle,
--''	AS Batch,
--CAST('' AS date) AS ChequeDate,
--CAST(0 AS bit) AS IsMonthDetailOnly,
--CAST(0 AS bit) AS IsFeeInvoiceHeadwise,
--''	AS GroupTitle,
--CAST(0 AS bit) AS IsSuppressFeeDetail,
--''	AS CollectionGroupName,
--0	AS InvoiceNumber,
--''	AS SUID,
--CAST(0 AS tinyint) AS HeaderDisplayId,
--0x  AS ReceiptBookHeader,
--CAST(0.0 AS decimal(6,2)) AS ServiceTaxPercentage,
--CAST(0.0 AS decimal(12,2)) AS AmountAfterDiscount,
--CAST(0.0 AS decimal(5,2)) AS CGSTPercentage,
--CAST(0.0 AS decimal(5,2)) AS SGSTPercentage,
--CAST(0.0 AS decimal(12,2)) AS CGSTAmount,
--CAST(0.0 AS decimal(12,2))	AS SGSTAmount,
--''	AS GSTINNo,
--''	AS HSNSACCode,
--''	AS ItemValue ,
--''	AS FatherName,
--''	AS MotherName,
--CAST(0.0 AS decimal(12,2)) AS ExemptionAmount,
--''	AS ExemptionRemark,
--0x AS EmployeeSign,
--''	AS PresentCity,
--''	AS PresentAdress,
--''	AS ParentContactNo,	
--CAST(0 AS bit) AS IsDisplayPendingFeeAmount,
--CAST(0.0 AS decimal(12,0)) AS PendingFeeAmount,
--''	AS FirstName,
--''	AS LastName,
--CAST(0.0 AS decimal(12,0))	AS FeeAmount,
--CAST(0.0 AS decimal(12,0)) AS ExemptionAmountSum,
--''	AS TransportBusRoute,
--''	AS BankAccountNumber,
--0	AS FeeHeadNumber,
--0	AS FeeNumber,
--0x AS DigitalSignature,
--''	AS CancelStatusRemark,
--CAST(0.0 AS decimal(12,2))	AS FeeSetupAmount,
--CAST('' AS datetime) AS CreatedDateTime ,
--CAST(0 AS bigint)	AS PaymentTransactionId,
--''	AS MiddleName,
--'' AS CreatedTime,
--'' AS Gender,
--CAST(0.0 AS decimal(12,2)) AS NextInstallmentAmount,
--0 AS NextInstallmentId,
--CAST('' AS date) AS NextInstallmentStartDate,
--CAST('' AS date) AS NextInstallmentEndDate,
--'' AS NextInstallmentName		
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptFeeHeadDetailGet]
						
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

		SELECT  @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount,0.00),1,2,@lOrgGroupId)
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
		SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END

	IF(@rOrgGroupId=0) SET @rOrgGroupId=@lOrgGroupId

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,
			
			--changes by Jash on 06/11/2020--%
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo
			--	WHEN ISNULL(PT.BankTransactionId,'') = '' THEN  CONVERT(nvarchar(20),FR.PaymentTransactionId)
			--	ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
			--%


			--ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,
			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  U.SourceTypeId = 2003 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				  
			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    

			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,
			
			--Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
			--sFee.tReceipt FR1				
			--INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
			--INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
			--INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
			--INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
			--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
			----Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			-- Order By FS.StartDate
			--FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,
			
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
	        ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,

			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,
			
			
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0) END)
			ELSE 
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) END AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(FM.Number,0) AS FeeNumber,
			ISNULL(RBM.DigitalSignature,0x) AS DigitalSignature,
			ISNULL(FR.CancelStatusRemark,'') AS CancelStatusRemark,
			FS.Amount AS FeeSetupAmount

	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]  
  @rReportId int=0,  
  @rReceiptBookId int=0,  
  @rAdmissionCategoryId int=0,  
  @rClassId int=0,  
  @rDivisionId int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rFromReceiptNo int=0,  
  @rToReceiptNo int=0,  
  @rBatchId int,  
  @rUserId bigint=0,  
  @rBuilder1 nvarchar(max)='',  
  @rBuilder2 nvarchar(max)='',  
  @rIsDetail bit=0,  
  @rIsCancel bit=0,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int=0,  
  @rPaytypeId int=0,  
  @rCommonBatch nvarchar(100)='',  
  @rDepartmentId int=0,  
  @rFromRollNo int=0,  
     @rToRollNo int=0,  
     @rCode nvarchar(20),  
     @rIsFilter bit=0,  
     @rIsHeader bit=0,  
     @rCreatedUserName nvarchar(100)='',  
     @rFeeHeadId nvarchar(max) = '',  
     @rIsDisplayOrgGroup bit=0,  
     @rIsDiscount bit = 0,  
     @rFeeId nvarchar(max) = '',  
     @rFilterId int=0,  
     @rCustomGroupId smallint = 0,  
     @rOrgGroupId int=0,  
     @rFeeStatusId int=0,  
     @rFromChequeDate date='',      
	 @rToChequeDate date='',      
     @rBankName nvarchar(100)='',  
     @rOrgIds nvarchar(max) = '',  
     @rBankNames nvarchar(max) = '',  
  
  @rFromChequeClearDate Date = '',  
  @rToChequeClearDate Date = '' ,
  @rClassStatusId int=0 ,
  @rPayTypeIds nvarchar(max) = '',
  @rUserAcessUserId bigint = 0,
  @rReceiptBookIds nvarchar(max) = '',
  @rCastCategoryId int = 0
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
  BEGIN      
  SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
    END   
	--OR @rReportId=20547
  IF(@rReportId=10138)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId,
		  0 AS FeeId,
		  '' AS FeeCode,
		  '' AS FeeTitle,
		   0 AS FeeOrderIndex,
		   R.CancelStatusRemark AS CancelRemark,
		   0 AS FeeHeadId,
		   '' AS FeeHeadName,
		   0 AS CastCategoryId,
		   '' AS CastCategoryName,
		   SA.ClassName,--Added  by dhananjay for mantis id :  37114
		   R.ReceiptAmount AS ReceiptAmountWithDiscount,	-- MantisId : 0037716
		   0 AS FeeHeadOrderIndex --Added by dhannajay for mantis : 40222

		  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 SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  

		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 
												--OR @rReportId != 30804
				))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
																									  
		 ORDER BY R.ReceiptNumber
	END

	ELSE IF(@rReportId=20456)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		   @rIsCancel AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId,
		  0 AS FeeId,
		  '' AS FeeCode,
		  '' AS FeeTitle,
		   0 AS FeeOrderIndex,
		   R.CancelStatusRemark AS CancelRemark,
		   0 AS FeeHeadId,
		   '' AS FeeHeadName,
		   0 AS CastCategoryId,
		   '' AS CastCategoryName,
		   SA.ClassName,--Added  by dhananjay for mantis id :  37114
		   R.ReceiptAmount AS ReceiptAmountWithDiscount,	-- Mantis Id : 0037716
		   0 AS FeeHeadOrderIndex --Added by dhannajay for mantis : 40222

		  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 SA  ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM    ON RBM.Id=R.ReceiptBookId  		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 
												--OR @rReportId != 30804
				))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
	--		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')																							  
		 ORDER BY R.ReceiptNumber
	END

	ELSE IF(@rReportId=30866)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,
		  --R.ReceiptAmount,  
		  RD.Amount AS ReceiptAmount,
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate,
		   FM.Id AS FeeId,
		  FM.Code AS FeeCode,
		  FM.Title AS FeeTitle,
		   FM.OrderIndex AS FeeOrderIndex,
		   SA.ClassName,--Added  by dhananjay for mantis id :  37114
		   R.ReceiptAmount AS ReceiptAmountWithDiscount,	 -- Mantis Id : 0037716
		   0 AS FeeHeadOrderIndex --Added by dhannajay for mantis : 40222
		      
		  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 SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		 
  
		 ORDER BY R.ReceiptNumber  
	END

	ELSE IF(@rReportId=20547)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  RD.Amount AS ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId,
		   SA.ClassName,--Added  by dhananjay for mantis id :  37114
		   (Select R.ReceiptAmount/Count(1) From sFee.tReceiptDetail tRD Where tRD.ReceiptId = R.Id) AS ReceiptAmountWithDiscount,		-- Mantis Id : 0037716
		   0 AS FeeHeadOrderIndex --Added by dhannajay for mantis : 40222

		  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 SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  

		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		 AND (ISNULL(FM.Id, 0) IN (SELECT CAST(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId = '')
		 
		  AND (  
		  (@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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
  
		--GROUP BY R.Id,R.IsObsolete,R.ReceiptNumber,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.RollNo, SA.Code,SA.Name,PTM.Title,R.ChequeNo,R.PaymentTransactionId
		--  ,R.BankName,R.ReceiptAmount,R.ChequeClearDate,R.ReceiptDate,R.CreatedUserId,U.LoginTitle,RBM.Title,RBM.BankName,RBM.BankAccountNumber,
		--  R.ReceiptBookId,R.Remark,R.DiscountAmount,RBM.OrderIndex,SA.OrgId,SA.OrganizationName,  
		--  R.AmountAfterDiscount,R.CGSTPercentage,R.SGSTPercentage,R.CGSTAmount,R.SGSTAmount,SA.OrgGroupBatchId,
		--  SA.BatchName,R.ChequeDate,R.ChequeClearDate,SA.GenderId

		 ORDER BY R.ReceiptNumber
	END

	ELSE IF(@rReportId=30630)
	BEGIN
	 
	 SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,
		  --R.ReceiptAmount,  
		  A.ReceiptAmount as ReceiptAmount,
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,	
		   R.ChequeClearDate,
		   ISNULL(A.FeeHeadId,0) AS FeeHeadId,   --Mantis - 33979
		   ISNULL(A.FeeHeadName,'') AS FeeHeadName, --Mantis - 33979
		   SA.ClassName,--Added  by dhananjay for mantis id :  37114
		   R.ReceiptAmount AS ReceiptAmountWithDiscount,		-- Mantis Id : 0037716
		   0 AS FeeHeadOrderIndex --Added by dhannajay for mantis : 40222
		  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 (Select SUM(RD.Amount) AS ReceiptAmount,RD.ReceiptId,
						FM.FeeHeadId AS FeeHeadId, --Mantis - 33979
						FHM.title AS FeeHeadName   --Mantis - 33979
					    FROM
						sFee.tReceiptDetail RD
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId		 --Mantis - 33979				  
						WHERE (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
						AND (ISNULL(FM.Id, 0) IN (SELECT CAST(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId = '')
						Group By  RD.ReceiptId,
								  FM.FeeHeadId,
								  FHM.title) A ON A.ReceiptId = R.Id    --Mantis - 33979
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		
		 ORDER BY R.ReceiptNumber  

	END

	ELSE IF(@rReportId=31411)
	BEGIN
	 
	 SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,
		  --R.ReceiptAmount,  
		  A.ReceiptAmount as ReceiptAmount,
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,	
		   R.ChequeClearDate,
		   ISNULL(A.FeeHeadId,0) AS FeeHeadId,   --Mantis - 33979
		   ISNULL(A.FeeHeadName,'') AS FeeHeadName, --Mantis - 33979
		   SA.ClassName,--Added  by dhananjay for mantis id :  37114
		   R.ReceiptAmount AS ReceiptAmountWithDiscount	,	-- Mantis Id : 0037716
		   A.FeeHeadOrderIndex AS FeeHeadOrderIndex --Added by dhannajay for mantis : 40222
		  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 (Select SUM(RD.Amount) AS ReceiptAmount,RD.ReceiptId,
						FM.FeeHeadId AS FeeHeadId, --Mantis - 33979
						FHM.title AS FeeHeadName,   --Mantis - 33979
						FHM.OrderIndex AS FeeHeadOrderIndex --Added by dhannajay for mantis : 40222
					    FROM
						sFee.tReceiptDetail RD
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId		 --Mantis - 33979				  
						WHERE (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
						AND (ISNULL(FM.Id, 0) IN (SELECT CAST(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId = '')
						Group By  RD.ReceiptId,
								  FM.FeeHeadId,
								  FHM.title,
								  FHM.OrderIndex) A ON A.ReceiptId = R.Id    --Mantis - 33979
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		
		 ORDER BY R.ReceiptNumber  

	END
	
	-- Added for Loading issue by Foram on 04/04/2025
	ELSE IF(@rReportId=20461 AND ISNULL(@rCode, '') <> '' AND ISNULL(@rBuilder1, '') = '')
	BEGIN
		SELECT 
			ISNULL(RBM.Title, '') AS ReceiptBookTitle
			,R.ReceiptNumber
			,CASE WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate
				ELSE R.ReceiptDate END AS ReceiptDate
			,R.ReceiptAmount
			,ISNULL(PTM.Title, '') AS PayType
			,CASE WHEN ISNULL(R.ChequeNo, '') != '' THEN R.ChequeNo
				ELSE CONVERT(NVARCHAR(20), R.PaymentTransactionId) END AS ChequeNo
			,ISNULL(R.BankName, '') AS BankName
			,ISNULL((CASE @rReportId
						WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)
						WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id)
						WHEN 30804 THEN [sFee].[fReceiptFeeDetailGet](R.Id)
						ELSE ''END), '') AS FeeDetail --added by dhananjay for mantis : 40314
			,R.Id AS ReceiptId
			,ISNULL(R.ReceiptBookId, '0') AS ReceiptBookId
			,SA.OrgId
			,R.DiscountAmount
			,(CASE WHEN @rReportId IN (20456,30804)THEN R.IsObsolete ELSE @rIsCancel END) AS IsCancel
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.SourceId 
			AND ((SA.OrgId = @rOrgId)OR (@rOrgId = 0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id = R.CreatedUserId
		WHERE R.SourceTypeId = 2001
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((R.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND (R.IsObsolete = @rIsCancel)
			AND ((SA.Code = @rCode) OR (@rCode = ''))
		ORDER BY R.ReceiptDate
			,R.ReceiptNumber
	END
	-- Added for Loading issue by Foram on 04/04/2025
	
	ELSE
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		 -- SA.ClassName, 
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id)
		   WHEN 30804 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,    --added by dhananjay for mantis : 40314
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate,
		   ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId, -- add for mantis : 0035911
		   ISNULL(CCM.Title,'') AS CastCategoryName,   -- add for mantis : 0035911
		   SA.ClassName,--Added  by dhananjay for mantis id :  37114
		   R.ReceiptAmount AS ReceiptAmountWithDiscount,			-- Mantis Id : 0037716
		   0 AS FeeHeadOrderIndex --Added by dhannajay for mantis : 40222

		  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 SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId -- add for mantis : 0035911
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId -- add for mantis : 0035911
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		 
		 AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0)) -- add for mantis : 0035911
		 ORDER BY R.ReceiptDate, R.ReceiptNumber 
	END

-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptListWithTaxGet]  
	@rReportId int=0,  
	@rReceiptBookId int=0,  
	@rAdmissionCategoryId int=0,  
	@rClassId int=0,  
	@rDivisionId int=0,  
	@rFromDate date='',  
	@rToDate date='',  
	@rFromReceiptNo int=0,  
	@rToReceiptNo int=0,  
	@rBatchId int,  
	@rUserId bigint=0,  
	@rBuilder1 nvarchar(max)=0,  
	@rBuilder2 nvarchar(max)=0,  
	@rIsDetail bit=0,  
	@rIsCancel bit=0,  
	@rOrgId int,  
	@rOrgGroupBatchId int,  
	@rStatusId int=0,  
	@rPaytypeId int=0,  
	@rCommonBatch nvarchar(100)='',  
	@rDepartmentId int=0,  
	@rFromRollNo int=0,  
	@rToRollNo int=0,  
	@rCode nvarchar(20),  
	@rIsFilter bit=0,  
	@rIsHeader bit=0,  
	@rCreatedUserName nvarchar(100)='',  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rIsDiscount bit = 0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,  
	--@rCustomGroupId smallint = 0,  
	@rOrgGroupId int=0,  
	@rFeeStatusId int=0,  
	--@rFromChequeDate date='',      
	--@rToChequeDate date='',      
	--@rBankName nvarchar(100)='',  
	@rOrgIds nvarchar(max) = '',  
	--@rBankNames nvarchar(max) = '',   
	--@rFromChequeClearDate Date = '',  
	--@rToChequeClearDate Date = '' ,
	@rClassStatusId int=0 ,
	@rPayTypeIds nvarchar(max) = '',
	@rUserAcessUserId bigint = 0
	--@rReceiptBookIds nvarchar(max) = ''
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
	--BEGIN      
	--	SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
	--END   

	BEGIN
		SELECT   
			@rBuilder1 AS Builder1,  
			@rBuilder2 AS Builder2,  
			@rIsDetail AS IsDetail,  
			@rIsCancel AS IsCancel,  
			@rIsFilter As IsFilter,  
			@rIsHeader As IsHeader,  
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
			R.Id AS ReceiptId,  
			R.ReceiptNumber,  
			SA.ClassId,  
			SA.DivisionId,  
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
			SA.RollNo,  
			SA.Code,  
			SA.Name,  
			ISNULL(PTM.Title,'') AS PayType,    
			CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
			ISNULL(R.BankName,'') AS BankName,  
			R.ReceiptAmount,  
			R.ReceiptDate,  
			R.CreatedUserId,  
			ISNULL(U.LoginTitle,'') AS UserName,  
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
			ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
			ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
			'' AS FeeDetail,  
			R.Remark,  
			R.DiscountAmount,  
			ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
			SA.OrgId,  
			SA.OrganizationName,  
			ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
			ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
			ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
			ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
			ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
			SA.OrgGroupBatchId AS BatchId,  
			SA.BatchName,  
			R.ChequeDate,  
			R.ChequeClearDate,
			CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 1 AND ISNULL(RTD.IsTaxInclude,0) = 1
				THEN (RD.Amount - (RD.Amount * 100) / (ISNULL(R.TaxPercentage,0) + 100))
				ELSE ISNULL(RTD.TaxAmount,0) END AS DECIMAL(12, 2)) AS TaxAmount,	
			CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 1 AND ISNULL(RTD.IsTaxInclude,0) = 1
				THEN (RD.Amount * 100) / (ISNULL(R.TaxPercentage,0) + 100) 
				ELSE RD.Amount END AS DECIMAL(12, 2)) AS TotalWithoutTax,
			CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 2
				THEN (RD.Amount + (RD.Amount * ISNULL(R.TaxPercentage,0) / 100))
				ELSE RD.Amount END AS DECIMAL(12, 2)) AS TotalWithTax

		  FROM   
			sFee.tReceipt R   
    
			INNER JOIN sStudent.vStudentAcademic SA  
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
			INNER JOIN sFee.tReceiptTaxDetail RTD ON RD.ReceiptId = RTD.ReceiptId AND RD.FeeSetupId = RTD.FeeSetupId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
			ON PTM.Id=R.PayTypeId  
			INNER JOIN sFee.tReceiptBookMaster RBM   
			ON RBM.Id=R.ReceiptBookId  
			LEFT JOIN sSecurity.tUser U  
			ON U.Id=R.CreatedUserId  
			LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')  		 
	END 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptTotalGet]
		
		 
		
		@rFromDate date,
		@rToDate date,		
		@rOrgGroupBatchId int
		 
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
	 
		 
		 
		 
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.Id,'0') As ReceiptBookId,		 
		SUM(ReceiptAmount) AS TotalAmount,
		RBM.OrderIndex
		 
			
  FROM 
			sFee.tReceipt R 
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
			
WHERE 
	R.SourceTypeId = 2001	 
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND R.OrgGroupBatchId = @rOrgGroupBatchId	
	GROUP BY RBM.ID,RBM.Title,RBM.OrderIndex
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReceiptWithTaxDetailsGet]
						
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)='',
			@rDivisionId int = 0,
			@rAdmissionCategoryId int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

		SELECT  @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount,0.00),1,2,@lOrgGroupId)
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
		SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END

	IF(@rOrgGroupId=0) SET @rOrgGroupId=@lOrgGroupId

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,			
			SA.AcademicId,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,			
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,					
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  ISNULL(FR.PaymentTransactionId,0) > 0 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,					
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
			ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			SC.ParentContactNo,			
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0) END)
			ELSE 
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) END AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(FM.Number,0) AS FeeNumber,
			ISNULL(RBM.DigitalSignature,0x) AS DigitalSignature,
			ISNULL(FR.CancelStatusRemark,'') AS CancelStatusRemark,
			FS.Amount AS FeeSetupAmount,
			FR.CreatedDateTime ,
			ISNULL(FR.PaymentTransactionId,0) As PaymentTransactionId,
			SA.MiddleName,
			CONVERT(char(5),FR.CreatedDateTime,108) AS CreatedTime,
			(CASE WHEN ISNULL(FA.VariableAmount,0) > 0 Then FA.VariableAmount 
			      When ISNULL(FS.Amount,0) > 0 Then FS.Amount END) + ISNULL(FA.AdditionalAmount,0) - ISNULL(FA.DiscountAmount,0) - ISNULL(FA.NotApplicableAmount,0) As TotalPayableAmount,
			OGM.Title AS OrgGroupTitle,
			NID.CollectionGroupName AS NextInstallmentName,
			ISNULL(FRTD.TaxAmount,0) AS TaxAmount,
			ISNULL(FR.TaxPercentage,0) AS TaxPercentage,
			RBM.TaxLabel,
			RBM.TaxTypeId		-- 1 : Inclusive and 2 : Exclusive
	
		FROM
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001
			LEFT JOIN sFee.tReceiptTaxDetail FRTD ON FRD.ReceiptId=FRTD.ReceiptId	AND FRD.FeeSetupId = FRTD.FeeSetupId
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			LEFT JOIN (SELECT * FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @rReceiptId)) NID
			ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
			AND ((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0) )
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END

--BEGIN
--SELECT
-- CAST(0 AS bigint) AS ReceiptId,
-- 0	AS ReceiptNumber,
-- CAST('' AS date) AS ReceiptDate,
-- CAST(0 AS bigint) AS AcademicId,
-- ''	AS Name,
--''	AS Code,
-- 0	AS RollNo,
--0	AS ClassId,
--0	AS DivisionId,
--''	AS ClassName,
--''	AS DivisionName,
--''	AS ClassDivision,
--0	AS FeeHeadId,
--''	AS FeeHead,
--0	AS FeeId,
--''	AS FeeName,
--CAST(0.0 AS decimal(12,2)) AS PaidAmount,
--CAST(0 AS tinyint) AS PayTypeId,
--''	AS PayType,
--''	AS ChequeNo,	
--''	AS BankName,
--''	AS Address1,
--''	AS Address2,
--''	AS FullTitle,
--CAST(0.0 AS decimal(12,2)) AS TotalReceiptAmount,
--CAST(0.0 AS decimal(12,2)) AS ReceiptAmount,					
--''	AS ReceiptAmountInWords,		
--CAST(0.0 AS decimal(12,2)) AS DiscountAmount,
--''	AS Remark,
--''	AS UserName,		
--0x  AS OrgLogo,
--''	AS Remark1,
--''	AS Remark2,			 
--CAST(0 AS bit) AS IsOnPrePrinted,
--CAST(0 AS bit) AS IsSupressLogo,
--CAST(0 AS bit) AS IsDisplaySchoolName,
--0	AS ReportId,
--''	AS OrganizationName,		  
--''	AS MonthDetail,    			
--''	AS FeeDuration,		
--''	AS DepartmentName,
-- 0	AS FeeOrderIndex,
--CAST(0 AS smallint)	AS FeeHeadOrderIndex,
--CAST(0 AS bit) AS IsCancelReceipt,
--''	AS CurrencyCode,
--''	AS CurrencyTitle,
--''	AS Batch,
--CAST('' AS date) AS ChequeDate,
--CAST(0 AS bit) AS IsMonthDetailOnly,
--CAST(0 AS bit) AS IsFeeInvoiceHeadwise,
--''	AS GroupTitle,
--CAST(0 AS bit) AS IsSuppressFeeDetail,
--''	AS CollectionGroupName,
--0	AS InvoiceNumber,
--''	AS SUID,
--CAST(0 AS tinyint) AS HeaderDisplayId,
--0x  AS ReceiptBookHeader,
--CAST(0.0 AS decimal(6,2)) AS ServiceTaxPercentage,
--CAST(0.0 AS decimal(12,2)) AS AmountAfterDiscount,
--CAST(0.0 AS decimal(5,2)) AS CGSTPercentage,
--CAST(0.0 AS decimal(5,2)) AS SGSTPercentage,
--CAST(0.0 AS decimal(12,2)) AS CGSTAmount,
--CAST(0.0 AS decimal(12,2))	AS SGSTAmount,
--''	AS GSTINNo,
--''	AS HSNSACCode,
--''	AS ItemValue ,
--''	AS FatherName,
--''	AS MotherName,
--CAST(0.0 AS decimal(12,2)) AS ExemptionAmount,
--''	AS ExemptionRemark,
--0x AS EmployeeSign,
--''	AS PresentCity,
--''	AS PresentAdress,
--''	AS ParentContactNo,	
--CAST(0 AS bit) AS IsDisplayPendingFeeAmount,
--CAST(0.0 AS decimal(12,0)) AS PendingFeeAmount,
--''	AS FirstName,
--''	AS LastName,
--CAST(0.0 AS decimal(12,0))	AS FeeAmount,
--CAST(0.0 AS decimal(12,0)) AS ExemptionAmountSum,
--''	AS TransportBusRoute,
--''	AS BankAccountNumber,
--0	AS FeeHeadNumber,
--0	AS FeeNumber,
--0x AS DigitalSignature,
--''	AS CancelStatusRemark,
--CAST(0.0 AS decimal(12,2))	AS FeeSetupAmount,
--''	AS CreatedDateTime ,
--CAST(0 AS bigint)	AS PaymentTransactionId,
--''	AS MiddleName,
--'' AS CreatedTime,
-- 0 AS TotalPayableAmount,
-- '' AS OrgGroupTitle,
-- '' AS NextInstallmentName,
--Convert(Decimal,0) AS TaxAmount,
--Convert(Decimal,0) AS TaxPercentage,
--'' AS TaxLabel,
--0 AS TaxTypeId
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeRefundDetail]

		@rBuilder1 nvarchar(max)=0,
		@rBuilder2 nvarchar(max)=0,
		@rOrgGroupBatchId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rIdNo nvarchar(20)='',
		@rFromReceiptNumber int=0,
		@rToReceiptNumber int=0,
		@rReceiptBookId int=0,
		@rPayTypeId tinyint=0,
		@rFromDate date='',
		@rToDate date='',
		@rOrgId smallint,
		@rBatchId int,
		@rOrgGroupId int,
		@rCreatedUserName nvarchar(100),
		@rCreatedUserId bigint,
		@rDepartmentId int=0,
		@rPayTypeIds nvarchar(max),
		@rOrgIds nvarchar(max),
		@rReceiptBookIds nvarchar(max),
		@rIsDetail bit = 0,
		@rCollectionGroupId int=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)
END

BEGIN

	SELECT
		@rBuilder1 AS Builder1,
		R.Id AS MReceiptId,
		RR.Id AS ReceiptId,
		RR.SourceTypeId AS SourceTypeId,
		CASE WHEN RR.SourceTypeId=2001 THEN 'Student' ELSE 'Employee' END AS SourceType,
		A.AcademicId,
		A.RollNo,
		SM.Code AS Code,
		A.Name AS Name,
		R.ReceiptNumber,
		R.ReceiptDate,
		RR.RefundDate,
		ISNULL(RR.RefundAmount,0)AS RefundAmount,
		--Round(ISNULL(RR.RefundAmount,0),0) AS RefundAmount,
		ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,
		ISNULL(R.DiscountAmount,0)AS DiscountAmount,
		RR.PayTypeId,
		PTM.Title AS PayType,
		RR.ChequeNo,
		RR.BankName,
		R.ReceiptBookId,
		RBM.Title AS ReceiptBook,
		RR.IsObsolete,
		A.OrgId,
		OM.DisplayTitle AS Organization,
		RR.BatchId,
		BM.Title AS Batch,
		RR.Remark,
		ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,
		ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,
		ISNULL(R.ChequeDate,'') AS ChequeDate,
		A.ClassName+' / '+A.DivisionName AS ClassName,
		@rIsDetail AS IsDetail,
		A.ClassId,
		A.DivisionId,
		A.DepartmentId,
		A.DepartmentName

	FROM
		sFee.tReceiptRefund RR
		INNER JOIN sFee.tReceipt R ON RR.ReceiptId = R.Id
		INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.SourceId
			AND (A.ClassId=@rClassId OR @rClassId=0) AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		INNER JOIN sSetup.tClassMaster Cm ON Cm.Id =A.ClassId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		INNER JOIN sCommon.tSourceTypeMaster STM ON STM.Id=RR.SourceTypeId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=RR.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SM.OrgId
			 AND OM.OrgGroupId=@rOrgGroupId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=RR.BatchId
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=RR.CreatedUserId
		INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId

	WHERE
		((SM.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
		AND (RR.SourceTypeId=2001)
		AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))
		AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))
		AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
		AND ((RR.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))
		AND ((RR.RefundDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))
		AND ((RR.RefundDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))
		AND ((SM.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((RR.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND ((R.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
		AND (ISNULL(SM.OrgId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,',')) OR @rOrgIds='')
		AND (ISNULL(RR.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
	
	ORDER BY R.ReceiptNumber DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeRefundDetailsGet]

			@rReceiptRefundId bigint = 0,
			@rOrgGroupId int = 0
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	SELECT 
			RR.Id AS ReceiptRefundId,
			RR.ReceiptId,
			FR.ReceiptNumber,
			RR.RefundDate,
			SA.AcademicId,
			SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			RRD.Amount AS PaidAmount,
			PTM.Title AS PayType,
			ISNULL(RR.ChequeNo,'') AS ChequeNo,
			ISNULL(RR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(RR.RefundAmount,0.00) AS TotalRefundAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,
			sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(RR.RefundAmount,0.00),1,2,OM.OrgGroupId) AS RefundAmountInWords,
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			RR.Remark,
			ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			 ISNULL(GroupTitle,'') AS GroupTitle,
			 [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) AS CurrencyCode,
			 RBM.ReceiptBookHeader,
			  CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId
	FROM 
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD
				ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tReceiptRefund RR 
				ON RR.ReceiptId=FR.Id AND RR.SourceId=FR.SourceId
			INNER JOIN sFee.tReceiptRefundDetail RRD 
				ON RRD.ReceiptRefundId=RR.Id AND RRD.FeeSetupId = FRD.FeeSetupId	
			INNER JOIN sFee.tFeeSetup FS
				ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM
				ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM
				ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId = RR.SourceId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=RR.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM 
				ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U
				ON U.Id=RR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM
				ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=DM.OrgId
	WHERE 
	 RR.Id=@rReceiptRefundId 
ORDER BY FS.StartDate,FM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeRefundGet]
		
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rFeeGroupId int=0,
		@rOrgIds nvarchar(max) = '',
		@rIsReceiptBookGroup bit=0,
		  @rClassStatusId int=0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.ClassName,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		FS.ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(R.RefundAmount,0) AS RefundAmount,
		@rFeeGroupId As FeeGroup
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			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 FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		) FS ON FS.AcademicId=SA.AcademicId
		--LEFT JOIN sFee.tFeeAllocation FA
		--	ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		INNER JOIN
		(
		    SELECT 
					ISNULL(SUM(RRD.Amount),0) AS RefundAmount,RRD.FeeSetupId ,RR.SourceId
		    FROM
				sFee.tReceiptRefund RR
				INNER JOIN sFee.tReceiptRefundDetail RRD ON RRD.ReceiptRefundId = RR.Id
				INNER JOIN sFee.tFeeSetup FS ON RRD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=RR.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(RR.SourceTypeId = 2001)
				AND (RR.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((RR.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((RR.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (RR.RefundDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					GROUP BY RRD.FeeSetupId,RR.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId	
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	--((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
 --   AND	
    ((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND (
		(
		 @rFilterId = 0) -- All
		 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
		 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
		 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0))
		 )
		 )	
    AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  		 
			Order by SA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeRegisterAllStudentListGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rFromDate date,
		@rToDate date,
		@rFromReceiptNo int,
		@rToReceiptNo int,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsCancel bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsDetail bit=0,
		@rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rPayTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0  

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		SET @rToDate = NULL
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsCancel AS IsCancel,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		(SELECT STUFF    
            (    
                (    
                    SELECT ',' + CONVERT(varchar,R1.ReceiptNumber) FROM sFee.tReceipt R1 
                    LEFT JOIN sFee.tReceiptDetail RD1
						ON RD1.ReceiptId=R1.Id
					LEFT JOIN sFee.tFeeSetup FS1
						ON FS1.Id=RD1.FeeSetupId
					LEFT JOIN sFee.tFeeMaster FM1
						ON FM1.Id=FS1.FeeId     
                    WHERE SA.AcademicId=R1.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) AND   FM1.Code = FM.Code
                    FOR XML PATH('')    
                )    
                    
            ,1,1,'')) as ReceiptNumber,
		--R.ReceiptNumber,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.AcademicId,
		SA.FirstName,
		SA.MiddleName,
		SA.LastName,
		SA.Code,
		SA.Name,
		PTM.Title AS PayType,
		R.ChequeNo,
		R.BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		FM.Title AS FeeDetail,
		ISNULL(FM.Code,'') AS FeeCode,
		FM.OrderIndex AS FeeOrderIndex,
		(Select SUM(RD1.Amount)AS DetailAmount
			FROM 
				sStudent.vStudentAcademic SA1
				LEFT JOIN sFee.tReceipt R1 
					ON SA1.AcademicId=R1.SourceId AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				LEFT JOIN sFee.tReceiptDetail RD1
					ON RD1.ReceiptId=R1.Id
				LEFT JOIN sFee.tFeeSetup FS1
					ON FS1.Id=RD1.FeeSetupId
				LEFT JOIN sFee.tFeeMaster FM1
					ON FM1.Id=FS1.FeeId
					WHERE SA.AcademicId = R1.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) AND FM1.Code =FM.Code) AS DetailAmount,
		--RD.Amount AS DetailAmount,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		ISNULL(FHM.Title,'') AS FeeHead,
		ISNULL(FHM.Code,'') AS FeeHeadCode,
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(R.Remark,'') AS Remark,
		DM.Id AS DepartmentId,
		DM.Title AS DepartmentName,
		SA.ClassOrderIndex,
		ISNULL(SO.GenderId,0) AS GenderId,
		ISNULL(SA.BatchName,'') BatchName,
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,
		sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,
		R.ChequeDate
  FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sFee.tReceipt R 
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		LEFT JOIN sFee.tReceiptDetail RD
			ON RD.ReceiptId=R.Id
		LEFT JOIN sFee.tFeeSetup FS
			ON FS.Id=RD.FeeSetupId
		LEFT JOIN sFee.tFeeMaster FM
			ON FM.Id=FS.FeeId
		LEFT JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
		INNER JOIN sSetup.tDepartmentMaster DM
			ON SA.DepartmentId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster O
			ON O.Id=SA.OrgId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		LEFT JOIN sStudent.tStudentOther SO
			ON SO.StudentId = SA.StudentId
	   LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
      LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
				
WHERE 
	--R.SourceTypeId = 2001
	--AND	
	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId = @rStatusId OR @rStatusId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))
	AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
     AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	ORDER BY R.ReceiptNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeReportAllFeeWiseDetailsGet]    
	
	@rBuilder1 nvarchar(max) = '',  
	@rBuilder2 nvarchar(max) = '', 
	@rOrgGroupBatchId int,
	@rIsDisplayOrgGroup bit = 0,   
	@rAdmissionCategoryId int,    
	@rClassId int,    
	@rDivisionId int,    
	@rCode nvarchar(50)='',        
	@rFromReceiptNo int=0,    
	@rToReceiptNo int=0,    
	@rReceiptBookId int=0,        
	@rPayTypeId int,        
	@rFromDate date,    
	@rToDate date,    
	@rIsCancel bit,    
	@rOrgId smallint,    
	@rBatchId int,            
	@rDepartmentId int=0,           
	@rIsFilter bit = 0,
	@rCommonBatch nvarchar(100) = '',
	@rReportId int = 0,
	@rFromRollNo int = null,  
	@rToRollNo int = null,
    @rFilterId int = 0,
	@rOrgIds nvarchar(max) = ''
	,@rIsDetail bit=0

 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    

BEGIN       
	
	DECLARE @rOrgGroupId INT
	SELECT @rOrgGroupId = OrgGroupId FROM ssetup.tOrgGroupBatchMaster WHERE Id = @rOrgGroupBatchId
	DECLARE @OrgIds TABLE (Id INT);
	INSERT INTO @OrgIds
	SELECT CAST(item AS INT) FROM sCommon.fnsplit(@rOrgIds, ',');

	DECLARE @AssignRouteStudentIds TABLE (SourceId BIGINT);
	INSERT INTO @AssignRouteStudentIds
	SELECT AT.SourceId
	FROM sTransport.tAssignRoute AT WITH (NOLOCK)
	INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id = AT.PickupDestinationId
	INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id = BM.BusRouteId
		AND AT.SourceTypeId = 2003
		AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))

	IF OBJECT_ID('tempdb..#ReceiptAmount') IS NOT NULL DROP TABLE #ReceiptAmount;

	BEGIN
		CREATE TABLE #ReceiptAmount
		(
			ReceiptId BigInt,
			FeeId Int,
			Amount Decimal(12, 2),
			VariableAmount Decimal(12, 2),
			ExemptionAmount Decimal(12, 2),
			AdditionalAmount Decimal(12, 2),
			NotApplicableAmount Decimal(12, 2)
		)
	END
	INSERT INTO #ReceiptAmount (ReceiptId, FeeId, Amount, VariableAmount, ExemptionAmount, AdditionalAmount, NotApplicableAmount)
		SELECT 	 
		R.Id AS ReceiptId, 
		FS.FeeId,
		RD.Amount,
		FA.VariableAmount,
		FA.DiscountAmount AS ExemptionAmount,
		FA.AdditionalAmount,
		FA.NotApplicableAmount
	FROM 
		sFee.tReceiptDetail RD
		INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=R.SourceId AND FA.SourceTypeId = R.SourceTypeId
	WHERE 
		(R.SourceTypeId=2001)     
		AND ((R.ReceiptNumber>=@rFromReceiptNo)OR(@rFromReceiptNo=0))    
		AND ((R.ReceiptNumber<=@rToReceiptNo)OR(@rToReceiptNo=0))    
		AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
		AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))         
		AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
		AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
		AND (R.IsObsolete=@rIsCancel) 
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((FS.ClassId=@rClassId) OR (@rClassId=0)) 

 SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
    A.StatusId,    
	R.Id AS ReceiptId,
	ISNULL(RA.Amount,0) AS Amount,
	OM.DisplayTitle AS Organization,  
	BM.Title AS Batch,
	BM.Id AS BatchId,
	A.Code, 
	CM.Title +' - '+ DM.Title AS ClassDiv,
	A.Name,    
	R.ReceiptNumber,     
	CONVERT(VARCHAR(10), R.ReceiptDate, 103) AS ReceiptDate, 
	ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
	PTM.Title AS PayType,    
	ISNULL(NULLIF(R.ChequeNo, ''), CONVERT(NVARCHAR(20), R.PaymentTransactionId)) AS ChequeNo,    
	R.Remark,
	CONVERT(VARCHAR(10), R.ChequeDate, 103)AS ChequeDate,  
	ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	R.CreatedDateTime AS ReceiptCreatedDateTime,
	R.BankName,    
	RBM.Title AS ReceiptBook,    
    ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
    ISNULL(R.DiscountAmount,0)AS DiscountAmount,
	RA.VariableAmount,
	RA.ExemptionAmount,
	RA.AdditionalAmount,
	RA.NotApplicableAmount,
	ISNULL(A.SUId,'') As SUId,
	ISNULL(R.CancelDateTime,'')AS CancelDateTime,
	ISNULL(R.CancelStatusRemark,'')AS CancelRemark,
	FM.Id AS FeeId,
	FM.Code AS FeeCode,
	FM.Title AS FeeName,
	FM.OrderIndex AS FeeOrderIndex
	--start mantis : 0044420
	,FHM.Id AS FeeHeadId
	,FHM.Code AS FeeHeadCode
	,FHM.Title AS FeeHeadTitle
	,FHM.OrderIndex AS FeeHeadOrderIndex
	,@rIsDetail AS IsDetail
	--end : mantis : 0044420
FROM  
	sFee.tReceipt R
	INNER JOIN sStudent.vStudentAcademic A    
	ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)  
	INNER JOIN sFee.tFeeMaster FM ON FM.IsObsolete = 0 AND FM.OrgGroupId = @rOrgGroupId
	INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId-- mantis : 0044420
	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 OM.Id=A.OrgId   
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId    
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=R.BatchId   
	LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId     
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=A.StudentId AND AR.SourceTypeId=2003
    LEFT JOIN  @AssignRouteStudentIds RT ON RT.SourceId = A.StudentId
	LEFT JOIN #ReceiptAmount RA ON RA.ReceiptId = R.Id AND RA.FeeId = FM.Id 	
WHERE     
	((A.Code like @rCode) OR (ISNULL(@rCode,'')=''))    
	AND (R.SourceTypeId=2001)     
	AND ((R.ReceiptNumber>=@rFromReceiptNo)OR(@rFromReceiptNo=0))    
	AND ((R.ReceiptNumber<=@rToReceiptNo)OR(@rToReceiptNo=0))    
	AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
	AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))         
	AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
	AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
	AND (R.IsObsolete=@rIsCancel)    
	AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))       
	AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
	AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
	AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((A.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 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 (@rOrgIds = '' OR ISNULL(A.OrgId,0) IN (SELECT Id FROM @OrgIds))
	AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
	AND FM.IsObsolete = 0
	AND FHM.IsObsolete = 0 -- mantis : 0044420
	             
 ORDER BY R.ReceiptNumber DESC   
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeSetupStudentWiseGet]
	 
  @rBatchId int, 
  @rOrgId int,  
  @rOrgGroupBatchId int, 
  @rReceiptBookId int,
  @rDepartmentId int,
  @rAdmissionCategoryId int,
  @rClassId int,  
  @rDivisionId int,  
  @rFromRollNo int,  
  @rToRollNo int,  
  @rCode nvarchar(20), 
  @rClassStatusId int=0,
  @rCustomGroupId int=0,
  @rCommonBatch nvarchar(100),
  @rCollectionGroupId int = 0,
  @rCollectionGroupIds nvarchar(max) = '',
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max)
  

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rCustomGroupId AS CustomGroupId,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.FeeName,
			FS.Id AS FeeSetupId,
			--ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FA.VariableAmount,0)AS VariableAmount,
			(CASE WHEN ISNULL(FS.Amount,0.00) <> 0.00 AND ISNULL(FA.VariableAmount,0.00) = 0.00 THEN ISNULL(FS.Amount,0.00)
				 WHEN ISNULL(FS.Amount,0.00) = 0.00 AND ISNULL(FA.VariableAmount,0.00) <> 0.00 THEN ISNULL(FA.VariableAmount,0.00) 
				 WHEN ISNULL(FS.Amount,0.00) = 0.00 AND ISNULL(FA.VariableAmount,0.00) = 0.00 THEN 0.00
				 ELSE 0.00 
				 END) AS Amount,
			--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)-0AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		
			FS.FeeOrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId,
			FS.FeeHeadId,
			FHM.Title AS FeeHead,
			FS.FeeId
			--FS.FeeDuration,
			--ISNULL(FM.Code,'') AS FeeCode
		
			
  FROM 
			
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex
			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.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			
		WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
WHERE	
    	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
	AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
	AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND (ISNULL(FS.CollectionGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupIds,','))OR @rCollectionGroupIds='')  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeStatusCollectionGroupWiseGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rFeeGroupId int=0,
		@rCollectionGroupId int = 0,
		@rClassStatusId int=0 --,
		--@rOrgIds nvarchar(max) = '' 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max)
	)
	
	INSERT INTO #TempIsOptional
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup      
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId   
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id      
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))      
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup       
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sFee.tFeeOptional FO  
			ON FO.FeeSetupId=FS1.Id  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId   
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId 
		WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint  
	)
	
	INSERT INTO #TempReceipt
	SELECT   
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
	FROM  
		sFee.tReceipt R   
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId  
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId     
		AND (SA1.ClassId=@rClassId OR @rClassId=0)   
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
	WHERE    
		(R.SourceTypeId = 2001)  
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND (R.IsObsolete = 0)   
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
	GROUP BY FeeSetupId,R.SourceId  

	CREATE TABLE #PaidPendingCount
	(
		CollectionGroupMasterId int,
		ReceiptBookMasterId int,
		ClassId int,
		AcademicId bigint,
		ToPayAmount decimal(12,2)
	)
	INSERT INTO #PaidPendingCount

			SELECT 
			CGM1.Id,RBM1.Id,S1.ClassId,S1.Id,FAS.ToPayAmount FROM sStudent.tAcademic S1
			INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		    INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
			INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
			LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
	
	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint  
	)
	
	INSERT INTO #TempAssignRoute
	SELECT 
		AT.SourceId 
	FROM 
		sTransport.tAssignRoute AT   
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(CGM.OrderIndex,0) AS CollectionGroupOrderIndex,		
		CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.ClassId  ORDER BY SA.ClassId ) =1 THEN (SELECT COUNT(1) FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE A.ClassId= SA.ClassId AND A.BatchId = SA.BatchId  AND A.OrgId = SA.OrgId AND BM.OrgGroupBatchId = SA.OrgGroupBatchId GROUP BY ClassId) ELSE 0 END AS StudentCount,
		--CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.AcademicId  ORDER BY SA.AcademicId) =1 THEN (CASE WHEN (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)) > 0) THEN 1 ELSE 0 END) ELSE 0 END AS PendingAmount

		--( SELECT SUM(T.PaidCount) FROM 
		--(SELECT 
		--	COUNT(DISTINCT(S1.Id)) AS PaidCount FROM sStudent.tAcademic S1
		--	INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		-- INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
		--INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
		--LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--GROUP BY S1.Id
		--HAVING SUM(ISNULL(FAS.ToPayAmount,0.00)) = 0 
		--) T )			
		--	AS PaidCount,
		--( SELECT SUM(T.PendingCount) FROM 
		--(SELECT 
		--	COUNT(DISTINCT(S1.Id)) AS PendingCount FROM sStudent.tAcademic S1
		--	INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		-- INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
		--INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
		--LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--GROUP BY S1.Id
		--HAVING SUM(ISNULL(FAS.ToPayAmount,0.00)) > 0 
		--) T )			
		--	AS PendingCount,
	    --Comment PaidCount and PendingCount due to performance issue and create 2 temp table #PaidPendingCount and #TempAssignRoute--26/05/2023
		(SELECT COUNT(distinct(AcademicId)) FROM #PaidPendingCount WHERE ClassId = SA.ClassId AND ReceiptBookMasterId = RBM.Id AND CollectionGroupMasterId = CGM.Id AND ISNULL(ToPayAmount,0.00) = 0) AS PaidCount,
		(SELECT COUNT(distinct(AcademicId)) FROM #PaidPendingCount WHERE ClassId = SA.ClassId AND ReceiptBookMasterId = RBM.Id AND CollectionGroupMasterId = CGM.Id AND ISNULL(ToPayAmount,0.00) > 0) AS PendingCount,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'')AS MotherContactNo
		--CGM.Id,
		--RBM.Id,
		--SA.ClassId

		--( SELECT SUM(T.PaidCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PaidCount FROM sStudent.vStudentAcademic S1
		--	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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.AcademicId
		--	LEFT JOIN
		--	(
		--		SELECT 
		--				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--		FROM
		--				sFee.tReceipt R 
		--			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING 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)) = 0 
		--) T )			
		--	AS PaidCount,

		--	( SELECT SUM(T.PendingCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PendingCount FROM sStudent.vStudentAcademic S1
		--	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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.AcademicId
		--	LEFT JOIN
		--	(
		--		SELECT 
		--				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--		FROM
		--				sFee.tReceipt R 
		--			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING 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)) > 0 
		--) T )			
		--	AS PendingCount



  FROM 
  
	    sStudent.vStudentAcademic SA
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
		INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 --       LEFT JOIN
	--(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
 --   INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
 --   INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    --ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND	((CGM.Id=@rCollectionGroupId) OR (@rCollectionGroupId=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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
    --AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			     
			Order by SA.RollNo
			

	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #PaidPendingCount
	DROP TABLE #TempAssignRoute
	--SELECT 
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	'' AS IsDetail,
	--	'' As IsFilter,
	--	'' As IsHeader, 
	--	'' AS IsDisplayOrgGroup,
	--	0 AS AcademicId,
	--	0 AS RollNo,
	--	'' AS Name,
	--	'' AS Code,
	--	0 AS ClassId,
	--	0 AS DivisionId,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	0  AS DivisionOrderIndex,
	--	0 AS ClassOrderIndex,
	--	'' AS ClassDivision,
	--	0 AS FeeSetupId,
		
	--	0 AS IsVariable,
	--	0 AS Amount,
	--	'' AS StartDate,
	--	'' AS EndDate,
	--	0 AS FAAmount,
	--	0 AS DiscountAmount,
	--	0 AS AdditionalAmount,
	--	0 AS NotApplicableAmount,
	--	0 AS PaidAmount,
	--	0 AS PendingAmount,
	--	'' AS Remark,
	--	0 AS ReceiptBookId,
	--	'' AS FeeName,
	--	0 AS OrgId,
	--	'' AS OrgName,
	--	0 AS OrgOrderIndex,
	--	'' AS ReceiptBookTitle,
	--	0 AS ReceiptOrderIndex,
	--	0 AS DepartmentId,
	--	'' AS DepartmentName,
	--	0 AS ExemptionTypeId,
	--	'' AS ExemptionType,
	--	0 AS FeeHeadId,
	--	'' AS FeeHeadName,
	--	0 AS FeeHeadOrderIndex,
	--	0 As FeeGroup,
	--	0 AS CollectionGroupId,
	--	'' AS CollectionGroup,
	--	0 AS CollectionGroupOrderIndex,		
	--	0 AS StudentCount,
	--	0 AS PaidCount,
	--	0 AS PendingCount,
	--	'' AS Address,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo
				

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeStatusCollectionGroupWiseGet_Old]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rFeeGroupId int=0,
		@rCollectionGroupId int = 0,
		@rClassStatusId int=0 --,
		--@rOrgIds nvarchar(max) = '' 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max)
	)
	
	INSERT INTO #TempIsOptional
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup      
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId   
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id      
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))      
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup       
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sFee.tFeeOptional FO  
			ON FO.FeeSetupId=FS1.Id  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId   
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId 
		WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint  
	)
	
	INSERT INTO #TempReceipt
	SELECT   
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
	FROM  
		sFee.tReceipt R   
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId  
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId     
		AND (SA1.ClassId=@rClassId OR @rClassId=0)   
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
	WHERE    
		(R.SourceTypeId = 2001)  
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND (R.IsObsolete = 0)   
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
	GROUP BY FeeSetupId,R.SourceId  

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(CGM.OrderIndex,0) AS CollectionGroupOrderIndex,		
		CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.ClassId  ORDER BY SA.ClassId ) =1 THEN (SELECT COUNT(1) FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE A.ClassId= SA.ClassId AND A.BatchId = SA.BatchId  AND A.OrgId = SA.OrgId AND BM.OrgGroupBatchId = SA.OrgGroupBatchId GROUP BY ClassId) ELSE 0 END AS StudentCount,
		--CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.AcademicId  ORDER BY SA.AcademicId) =1 THEN (CASE WHEN (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)) > 0) THEN 1 ELSE 0 END) ELSE 0 END AS PendingAmount

		( SELECT SUM(T.PaidCount) FROM 
		(SELECT 
			COUNT(DISTINCT(S1.AcademicId)) AS PaidCount FROM sStudent.vStudentAcademic S1
			INNER JOIN #TempIsOptional FS1 ON FS1.AcademicId=S1.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA1  ON FA1.FeeSetupId=FS1.Id AND FA1.SourceId=S1.AcademicId  
		LEFT JOIN #TempReceipt R1 ON R1.FeeSetupId = FS1.Id AND S1.AcademicId = R1.SourceId
		INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS1.ReceiptBookId=RBM1.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS1.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		GROUP BY S1.AcademicId
		HAVING SUM(ISNULL(FS1.Amount,0.00)+ISNULL(FA1.VariableAmount,0.00)+ISNULL(FA1.AdditionalAmount,0.00) -ISNULL(FA1.DiscountAmount,0.00)-ISNULL(FA1.NotApplicableAmount,0.00)-ISNULL(R1.PaidAmount,0.00)) = 0 
		) T )			
			AS PaidCount,
		( SELECT SUM(T.PendingCount) FROM 
		(SELECT 
			COUNT(DISTINCT(S1.AcademicId)) AS PendingCount FROM sStudent.vStudentAcademic S1
			INNER JOIN #TempIsOptional FS1 ON FS1.AcademicId=S1.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA1  ON FA1.FeeSetupId=FS1.Id AND FA1.SourceId=S1.AcademicId  
		LEFT JOIN #TempReceipt R1 ON R1.FeeSetupId = FS1.Id AND S1.AcademicId = R1.SourceId
		INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS1.ReceiptBookId=RBM1.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS1.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		GROUP BY S1.AcademicId
		HAVING SUM(ISNULL(FS1.Amount,0.00)+ISNULL(FA1.VariableAmount,0.00)+ISNULL(FA1.AdditionalAmount,0.00) -ISNULL(FA1.DiscountAmount,0.00)-ISNULL(FA1.NotApplicableAmount,0.00)-ISNULL(R1.PaidAmount,0.00)) > 0 
		) T )			
			AS PendingCount

		--( SELECT SUM(T.PaidCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PaidCount FROM sStudent.vStudentAcademic S1
		--	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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.AcademicId
		--	LEFT JOIN
		--	(
		--		SELECT 
		--				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--		FROM
		--				sFee.tReceipt R 
		--			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING 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)) = 0 
		--) T )			
		--	AS PaidCount,

		--	( SELECT SUM(T.PendingCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PendingCount FROM sStudent.vStudentAcademic S1
		--	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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.AcademicId
		--	LEFT JOIN
		--	(
		--		SELECT 
		--				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--		FROM
		--				sFee.tReceipt R 
		--			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING 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)) > 0 
		--) T )			
		--	AS PendingCount



  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId
			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 FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND	((CGM.Id=@rCollectionGroupId) OR (@rCollectionGroupId=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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
    --AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			     
			Order by SA.RollNo
			

	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
				

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeStatusFeeHeadandBusRouteWiseGet]  

	@rOrgGroupBatchId int=0,
	@rCommonBatch nvarchar(100) = '',
	@rReceiptBookId int=0,
	--@rCollectionGroupId int =0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rDepartmentId int=0,
	@rAdmissionCategoryId int=0,
	@rClassId int=0,  
	@rDivisionId int=0,
	@rUptoDate date='',
	@rStatusId int=0,
	@rBuilder1 nvarchar(max) = '',  
	@rBuilder2 nvarchar(max) = '', 
	@rClassStatusId int=0 ,
	@rBusRouteId int = 0 ,
	@rFeeGroupId int=0
	
	 
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		
			SA.AcademicId,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			RT.RouteNumber,
			ISNULL(RT.BusRoute,'') AS BusRoute,
			FHM.Number,
			FS.FeeName,
			@rFeeGroupId As FeeGroup,
			FS.OrderIndex AS FeeWiseOrderIndex
		
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				--AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				--AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId,B.RouteNumber,B.Title AS BusRoute 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))
			AND ((B.Id = @rBusRouteId) OR (@rBusRouteId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			WHERE	
			((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 --(@rFilterId = 0) -- All
					 --OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 (isnull(RT.SourceId,0)!=0) -- Transport
					 --OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	

		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		 AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		 AND (FHM.Number=1001)
		Order by SA.RollNo

		--SELECT
		--'' AS Builder1,  
		--'' AS Builder2,  
		--0 AS AcademicId,  
		--0 PaidAmount,  
		--0 AS PendingAmount,  
		--0 AS FeeHeadId,  
		--'' AS FeeHeadName, 
		--0 AS RouteNumber,
		--'' AS BusRoute
	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeStatusNegativeGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0    
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00) AS PendingAmount,
		ISNULL(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FM.Title AS FeeName,
		SA.OrgId,
		SA.BatchId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex
		--,
		
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		 INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		 INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
		 INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FAS.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND ((FS.EndDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ISNULL(FAS.ToPayAmount,0.00) < 0
	 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 	
   AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))			     	
			Order by SA.Code,SA.RollNo
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeStatusStudentAndFeeWiseGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	
	
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			FA.Remark AS Remark
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeStatusStudentAndReceiptWiseGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0
			
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
--Added by dhananjay For Mantis : 42599
CREATE TABle  #LastFeePaymentDetails
(
AcademicId BIGINT, 
FeeHeadId INT,
FeeId INT,
LastPaymentDate DATETIME,
LastPaidAmount DECIMAL(12,2),
RowNumber INT  
)

Insert into #LastFeePaymentDetails
(
AcademicId,
FeeHeadId,
FeeId,
LastPaymentDate,
LastPaidAmount,
RowNumber 
)
Select
  R.SourceId, 
  FHM.Id,
  FM.Id,
  MAX(R.CreatedDateTime) AS LastPaymentDate,
  ISNULL(SUM(RD.Amount), 0) AS LastPaidAmount,
  ROW_NUMBER() OVER (PARTITION BY R.SourceId, FHM.Id, FM.Id ORDER BY MAX(R.CreatedDateTime) DESC) AS RowNumber 


				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 sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
					
					WHERE 	
					--R.SourceId = SA.AcademicId AND  FHM.Id = FS.FeeHeadId
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					
					GROUP BY R.SourceId,R.CreatedDateTime, FHM.Id ,FM.Id
					ORDER BY R.CreatedDateTime DESC
--Select * from #LastFeePaymentDetails
	--Added by dhananjay For Mantis : 42599
	
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			FA.Remark AS Remark,
			LFPD.LastPaymentDate,
			LFPD.LastPaidAmount
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 
			 LEFT JOIN #LastFeePaymentDetails LFPD ON LFPD.AcademicId = R.SourceId AND LFPD.FeeHeadId = FS.FeeHeadId AND LFPD.RowNumber = 1 AND LFPD.FeeId = FS.FeeId
			 
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeStatusStudentWiseDetails]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SC.ParentContactNo
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN sStudent.tStudentCommunication SC ON  SC.StudentId=SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeStatusStudentWisewithDiscountGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	

		CREATE TABLE #tmp
		(
		AcademicId bigint,
		RollNo int,
		Name nvarchar(200),
		Code nvarchar(100),
		ClassId bigint,
		DivisionId bigint,
		ClassName nvarchar(100),
		DivisionName nvarchar(100),
		DivisionOrderIndex int,
		ClassOrderIndex int,
		ClassDivision  nvarchar(200),
		--IsVariable int ,
		Amount decimal(12,2),
		--StartDate date,
	 --   EndDate date,
		FAAmount decimal(12,2),
		DiscountAmount decimal(12,2),
	    AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2),
		PaidAmount decimal(12,2),
		PendingAmount decimal(12,2),
		--Remark nvarchar(max),
		--ReceiptBookId bigint,
		--FeeName nvarchar(200),
		--FeeCode nvarchar(200),
		OrgId bigint,
		OrgName nvarchar(500),
		OrgOrderIndex int,
		--ReceiptBookTitle nvarchar(500),
		--ReceiptOrderIndex int,
		DepartmentId bigint,
		DepartmentName nvarchar(200),
		--ExemptionTypeId bigint, 
		--ExemptionType nvarchar(200),
		--FeeHeadId bigint,
		--FeeHeadName nvarchar(500),
	    --FeeHeadOrderIndex int,
		--FeeGroup int,
		BatchId bigint,
		BatchName nvarchar(200),
		CancelAmount decimal(12,2),
		Discount decimal(12,2),
		ParentContactNo nvarchar(100),  --Mantis - 37172
		ReceiptAmount decimal(12,2)
		
		)
		INSERT INTO #tmp
		SELECT 
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			--FS.Id AS FeeSetupId,
			--ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			--ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			--ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			--ISNULL(FA.Remark,'') AS Remark,
			--FS.ReceiptBookId,
			--FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			--SA.ExemptionTypeId,
			--ISNULL(ETM.Title,'') AS ExemptionType,
			--FHM.Id AS FeeHeadId,
			--FHM.Title AS FeeHeadName,
			--FHM.OrderIndex AS FeeHeadOrderIndex,
			--@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			(Select ISNULL(SUM(R.DiscountAmount),0) FROM  sFee.tReceipt R Where R.SourceId=SA.AcademicId AND ((R.ReceiptBookId=@rReceiptBookId)OR (@rReceiptBookId=0)) AND (R.ReceiptDate <= @rUptoDate)) AS Discount,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,   --Mantis - 37172
			ISNULL(R.ReceiptAmount,0)  AS ReceiptAmount

	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					--ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					--ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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,Sum(R.ReceiptAmount) as ReceiptAmount
				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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId  --Mantis - 37172

			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		 
		Order by SA.RollNo 
		--Select * from #tmp
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter AS IsFilter,
		@rIsHeader AS IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		AcademicId ,
		RollNo ,
		Name ,
		Code ,
		ClassId ,
		DivisionId ,
		ClassName ,
		DivisionName ,
		DivisionOrderIndex ,
		ClassOrderIndex ,
		ClassDivision  ,
		--IsVariable  ,
		--((select (SUM(Amount)) from #tmp t Where AcademicId=t1.AcademicId AND Amount > 0 )- (select (SUM(Amount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND Amount < 0 ))AS Amount,
		SUM(Amount)AS Amount ,
		--StartDate ,
	    --   EndDate ,
		--((select SUM(FAAmount) from #tmp t Where AcademicId=t1.AcademicId AND FAAmount < 0 )- (select( SUM(FAAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND FAAmount > 0 ))AS FAAmount,
		SUM(FAAmount )AS FAAmount,
		--((select SUM(DiscountAmount) from #tmp t Where AcademicId=t1.AcademicId AND DiscountAmount < 0 )- (select( SUM(DiscountAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND DiscountAmount > 0 ))AS DiscountAmount,
		SUM(DiscountAmount )AS DiscountAmount,
		--((select SUM(AdditionalAmount) from #tmp t Where AcademicId=t1.AcademicId AND AdditionalAmount < 0 )- (select( SUM(AdditionalAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND AdditionalAmount > 0 ))AS AdditionalAmount,
	    SUM(AdditionalAmount)AS AdditionalAmount,
		--((select SUM(NotApplicableAmount) from #tmp t Where AcademicId=t1.AcademicId AND NotApplicableAmount < 0 )- (select( SUM(NotApplicableAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND NotApplicableAmount > 0 ))AS NotApplicableAmount,
		SUM(NotApplicableAmount)AS NotApplicableAmount,
		--((select SUM(PaidAmount) from #tmp t Where AcademicId=t1.AcademicId AND PaidAmount < 0 )- (select( SUM(PaidAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND PaidAmount > 0 ))AS PaidAmount,
		SUM(PaidAmount)AS PaidAmount,
		--((select SUM(PendingAmount) from #tmp t Where AcademicId=t1.AcademicId AND PendingAmount < 0 )- (select( SUM(PendingAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND PendingAmount > 0 ))AS PendingAmount,
		SUM(PendingAmount)AS PendingAmount,
		OrgId ,
		OrgName ,
		OrgOrderIndex ,
		DepartmentId ,
		DepartmentName ,
		BatchId ,
		BatchName ,
		Discount,
		ParentContactNo  --Mantis - 37172
		--ReceiptBookId ,
		--ReceiptBookTitle
		,ReceiptAmount
		
	    FROM #tmp 
		--INNER JOIN #tmp t1 ON AcademicId=t1.AcademicId
		Group By AcademicId ,RollNo ,Name ,Code ,ClassId ,DivisionId ,ClassName ,DivisionName ,DivisionOrderIndex ,ClassOrderIndex ,ClassDivision  ,
		OrgId ,OrgName ,OrgOrderIndex ,DepartmentId ,DepartmentName ,BatchId ,BatchName ,Discount,ParentContactNo,ReceiptAmount
		--,ReceiptBookId ,ReceiptBookTitle
		
		
		DROP TABLE #tmp
	
	
	--SELECT 
	--	'' Builder1,
	--	'' AS Builder2,
	--	0 AS IsDetail,
	--	0 AS IsFilter,
	--	0 AS IsHeader,
	--	0 AS IsDisplayOrgGroup,
	--	convert(bigint,0) AS AcademicId ,
	--	0 AS RollNo ,
	--	''AS Name ,
	--	'' AS Code ,
	--	0 AS ClassId ,
	--	0 AS DivisionId ,
	--	'' AS ClassName ,
	--	'' AS DivisionName ,
	--	0 AS DivisionOrderIndex ,
	--	0 AS ClassOrderIndex ,
	--	'' AS ClassDivision  ,
	--	0 AS IsVariable  ,
	--	0 AS  Amount ,
	--	'' AS StartDate ,
	--    '' AS EndDate ,
	--	0.00 AS FAAmount,
	--	0.00 AS DiscountAmount,
	--  0.00 AS AdditionalAmount,
	--	0.00 AS NotApplicableAmount,
	--	0.00 AS PaidAmount,
	--	0.00 AS PendingAmount,
	--	0 AS OrgId ,
	--    '' AS OrgName ,
	--	0 AS OrgOrderIndex ,
	--	0 AS DepartmentId ,
	--    '' AS DepartmentName ,
	--	0 AS BatchId ,
	--	'' AS BatchName ,
	--	0 AS Discount ,
	--	0 AS ReceiptBookId,
	--	'' AS ReceiptBookTitle,
	-- '' AS ParentContactNo    --Mantis - 37172
	  
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeStatusStudentwisewithPaidDateGet]
	    
	    @rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rClassStatusId int=0--,
		--@rOrgIds nvarchar(max) = ''
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeId,
		FS.FeeName,
		FS.OrderIndex AS FeeOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.BatchId,
		SA.BatchName,
		BM.OrderIndex AS BatchOrderIndex,
		R.InvoiceNumber,
		R.ReceiptDate,
		SO.GenderId 
  FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		) 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, ISNULL(MAX(FI.InvoiceNumber),0) AS InvoiceNumber,MAX(R.ReceiptDate) as ReceiptDate
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
		 INNER JOIN sSetup.tBatchMaster BM
			ON BM.Id = SA.BatchId
	  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId=SO.StudentId		
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND (ISNULL(FA.VariableAmount,0.00) + ISNULL(FS.Amount,0)) != 0	
	AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			Order by SA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeSummaryGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0,
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	
	IF(@rReportId=20624)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SA.SUId AS SUId,
			CONVERT(Date,NULL) AS LeftDate, -- For DataSet Refresh
			'' AS ExemptedRemarkFeeWise,		-- For DataSet Refresh
			'' AS RemarkWithComma,
			'' AS AdditionalRemark,
			'' AS NotApplicableRemark,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270
			'' AS StudentContactNo,  --Mantis - 35489
			'' AS FatherName,		 --Mantis - 35489
			0.00 AS RefundAmount
			
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId --Added by dhananjay for Mantis Id : 35270
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	END
	ELSE IF (@rReportId=20842 OR @rReportId=10150 OR @rReportId=30714 OR @rReportId=30831)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SA.SUId AS SUId,
			SAD.LeftDate,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270
			'' AS StudentContactNo, --Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	END
	ELSE IF(@rReportId=30655)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270	
			'' AS StudentContactNo,	--Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  ISNULL(FA.NotApplicableAmount,0) > 0) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')	
		Order by SA.RollNo
	END
	ELSE IF(@rReportId=30799)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R1.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R1.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			ISNULL(R2.TotalReceiptAmount,0.00) AS CancelAmount,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270	
			'' AS StudentContactNo, --Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R1 ON R1.FeeSetupId = FS.Id AND SA.AcademicId = R1.SourceId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 1) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R2 ON R2.FeeSetupId = FS.Id AND SA.AcademicId = R2.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo 
	END
	ELSE IF(@rReportId=30825)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270	
			'' AS StudentContactNo,	--Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					--AND (tSA.AdmissionDate <= @rUptoDate)
					AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA1.StatusId = 1))
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			--AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		--AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA.StatusId = 1))
		 --AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo 
	END
	--ELSE IF(@rReportId=30821)
	--BEGIN
	--	SELECT 
	--		@rBuilder1 AS Builder1,
	--		@rBuilder2 AS Builder2,
	--		@rIsDetail AS IsDetail,
	--		@rIsFilter As IsFilter,
	--		@rIsHeader As IsHeader, 
	--		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
	--		SA.AcademicId,
	--		SA.RollNo,
	--		SA.Name,
	--		SA.Code,
	--		SA.ClassId,
	--		SA.DivisionId,
	--		SA.ClassName,
	--		SA.DivisionName,
	--		SA.DivisionOrder AS DivisionOrderIndex,
	--		SA.ClassOrderIndex AS ClassOrderIndex,
	--		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
	--		FS.Id AS FeeSetupId,
	--		ISNULL(FS.IsVariable,0)AS IsVariable,
	--		ISNULL(FS.Amount,0)AS Amount,
	--		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
	--		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
	--		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
	--		ISNULL(R.DiscountAmount,0.00)AS DiscountAmount,
	--		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
	--		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
	--		ISNULL(R.PaidAmount,0) AS PaidAmount,
	--		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
	--		ISNULL(FA.Remark,'') AS Remark,
	--		FS.ReceiptBookId,
	--		FS.FeeName,
	--		FS.FeeCode,
	--		SA.OrgId,
	--		O.DisplayTitle AS OrgName,
	--		O.OrderIndex AS OrgOrderIndex,
	--		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
	--		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
	--		SA.DepartmentId,
	--		SA.DepartmentName,
	--		SA.ExemptionTypeId,
	--		ISNULL(ETM.Title,'') AS ExemptionType,
	--		FHM.Id AS FeeHeadId,
	--		FHM.Title AS FeeHeadName,
	--		FHM.OrderIndex AS FeeHeadOrderIndex,
	--		@rFeeGroupId As FeeGroup,
	--		SA.OrgGroupBatchId AS BatchId,
	--		SA.BatchName AS BatchName,
	--		0.00 AS CancelAmount,
	--		(Select ISNULL(SUM(R.DiscountAmount),0) FROM  sFee.tReceipt R Where R.SourceId=SA.AcademicId)AS Discount
	--  FROM 
	--		sStudent.vStudentAcademic SA
	--		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
	--		INNER JOIN 
	--		(
	--			SELECT 
	--				FS1.FeeId,
	--				FS1.Id,
	--				ISNULL(FS1.IsOptional,0)AS IsOptional,
	--				ISNULL(FS1.IsVariable,0)AS IsVariable,
	--				ISNULL(FS1.Amount,0)AS Amount,
	--				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
	--				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
	--				FS1.BatchId,
	--				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code AS FeeCode,
	--				FM.FeeHeadId
	--			FROM sFee.tFeeSetup FS1
	--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	--			WHERE 
	--				((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--				AND (FS1.IsOptional=0)
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				UNION ALL
					
	--			SELECT 
	--				FS1.FeeId,
	--				FS1.Id,
	--				ISNULL(FS1.IsOptional,0)AS IsOptional,
	--				ISNULL(FS1.IsVariable,0)AS IsVariable,
	--				ISNULL(FS1.Amount,0)AS Amount,
	--				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
	--				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
	--				FS1.BatchId,
	--				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code As FeeCode,
	--				FM.FeeHeadId
	--			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 FS1.BatchId = SA1.BatchId
	--		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--		WHERE
	--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--			AND (FS1.IsOptional=1)
	--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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,R.DiscountAmount
	--			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 
	--				INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
	--				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
	--				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
	--			WHERE		
	--				(R.SourceTypeId = 2001)
	--				AND (R.IsObsolete = 0) 
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	--				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND (R.ReceiptDate <= @rUptoDate)
	--				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--				AND (tSA.AdmissionDate <= @rUptoDate)
	--					GROUP BY FeeSetupId,R.SourceId,R.DiscountAmount
			
	--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	--		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
	--		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
	--		 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
	--		 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
	--		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	--		 LEFT JOIN
	--		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
	--		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
	--		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
	--		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	--		WHERE	
	--		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
	--		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
	--		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
	--		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--		--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	--		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--		AND ((SA.Code=@rCode) OR (@rCode=''))
	--		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	--		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	--		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	--		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	--	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--	--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--	AND (tSA.AdmissionDate <= @rUptoDate)
	--	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
	--	Order by SA.RollNo 
	--END
	ELSE IF(@rReportId=30920)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			--CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			--ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) as ExampltedRemark,

			''  AdditionalRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270	
			'' AS StudentContactNo,	--Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
			AND (tSA.AdmissionDate <= @rUptoDate)
			AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		Order by SA.RollNo
	END

	ELSE IF(@rReportId=30232) -- Mantis : 0028532  #Start 
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) END as ExampltedRemark,

			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId) END  as ExampltedRemark,

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			SAD.LeftDate,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270
			'' AS StudentContactNo,	--Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')  
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo
	END -- #End

	ELSE IF (@rReportId=31399)--add for mantis: 36670
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			FS.IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeId,
			FS.FeeName,
			ISNULL(RE.RefundAmount,0.00) AS RefundAmount,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SA.SUId AS SUId,
			SAD.LeftDate,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,
			'' AS StudentContactNo,
			'' AS FatherName
			--,ISNULL(R.RefundAmount,0.00) AS RefundAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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--, ISNULL(SUM(RRD.Amount),0) AS RefundAmount
				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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					--LEFT JOIN sFee.tReceiptRefund RR ON RR.ReceiptId = R.Id
					--INNER JOIN sFee.tReceiptRefundDetail RRD ON RRD.ReceiptRefundId=RR.Id AND RRD.FeeSetupId=FS.Id
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
					--AND ((R.ReceiptNumber>=@rFromReceiptNo)OR(@rFromReceiptNo=0))
					--AND ((R.ReceiptNumber<=@rToReceiptNo)OR(@rToReceiptNo=0))
						GROUP BY RD.FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			LEFT JOIN
			(
				SELECT ISNULL(RRD.Amount,0) AS RefundAmount, R.Id, R.SourceId, FS.Id AS FeeSetupId
				FROM sFee.tReceiptRefund RR
					INNER JOIN sFee.tReceipt R ON R.Id=RR.ReceiptId AND R.SourceId=RR.SourceId
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id 
					INNER JOIN sFee.tReceiptRefundDetail RRD ON RRD.ReceiptRefundId=RR.Id AND FS.Id=RRD.FeeSetupId
				WHERE		
					(R.SourceTypeId = 2001)
					--AND (R.IsObsolete = 0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND (R.ReceiptDate <= @rUptoDate)
			)RE ON RE.SourceId=R.SourceId AND R.FeeSetupId=RE.FeeSetupId
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	END

	ELSE
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) END as ExampltedRemark,

			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId) END  as ExampltedRemark,

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			SAD.LeftDate,
			(STUFF((SELECT  ','+ tFA.DiscountRemark	FROM sFee.tFeeAllocation tFA INNER JOIN sFee.tFeeSetup tFS On tFS.Id = tFA.FeeSetupId
			WHERE tFA.SourceId = FA.SourceId AND (tFS.FeeId IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,',')) OR @rFeeId='')
			ORDER BY tFA.DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) AS ExemptedRemarkFeeWise	,	-- Mantis Id : 0030870
			--'' AS ParentContactNo, --Added by dhananjay for Mantis Id : 35270
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,	--Mantis - 35489
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,	--Mantis - 35489
			ISNULL(SA.MiddleName,'') AS FatherName	--Mantis - 35489
	  FROM	
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')  
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				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 FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId		--Mantis - 35489


			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo
	END
	
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptFeeSummaryOtherGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rIsReceiptBookGroup bit=0,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			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.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
		  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
       LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 	
    AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
	AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(SA.ClassId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')	
	AND (ISNULL(SA.DivisionId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  		     
			Order by SA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptFeeSummaryPaytypewiseReportGet]  
	@rReportId int=0,  
	@rIsFilter bit=0,  
	@rIsDisplayOrgGroup bit=0,
	@rOrgGroupBatchId int,  
	@rCommonBatch nvarchar(100)='',
	@rReceiptBookId int=0,  
	@rOrgId int,  
	@rBatchId int,
	@rDepartmentId int=0,  
	@rAdmissionCategoryId int=0,  
	@rClassId int=0,  
	@rDivisionId int=0, 
	@rFromDate date='',  
	@rToDate date='',  
	@rPaytypeId int=0, 
	@rCode nvarchar(20),
	@rFilterId int=0,  
	@rClassStatusId int=0 ,
	@rPayTypeIds nvarchar(max) = '',
	@rBuilder1 nvarchar(max)=0,  
    @rBuilder2 nvarchar(max)=0
	

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
 SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsFilter As IsFilter,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,
  RBM.Id AS ReceiptBookId,
  RBM.Title AS ReceiptBookTitle,
  RBM.FullTitle AS ReceiptBookFullTitle,
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.Code,  
  SA.Name,  
  ISNULL(PTM.Title,'') AS PayType,  
  RD.Amount AS ReceiptDetailAmount,  
  R.ReceiptAmount  
  FROM   
   sFee.tReceipt R  
   INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId
 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId 
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
  AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
    )  
 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
 AND R.IsObsolete = 0
  
 ORDER BY R.ReceiptNumber  

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptMultiFeeReceiptDetailsGet]
						
			@rReportId int=0,
			@rReceiptIds nvarchar(max) = '',
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)='',
			@rDivisionId int = 0,
			@rAdmissionCategoryId int = 0
			

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

DECLARE @lReceiptId bigint
CREATE TABLE #tmp
(
	Id int IDENTITY,
	ReceiptId bigint
)

INSERT INTO #tmp
SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@rReceiptIds,',')
	
DECLARE @lCountReceiptId int,@lId int

SELECT @lCountReceiptId=COUNT(Id) FROM #tmp
SELECT Top 1 @lId=Id FROM #tmp
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId


	CREATE TABLE #ReceiptDetail
	(
	  	ReceiptId bigint,
		ReceiptNumber int,
		ReceiptDate date,			
		AcademicId bigint,
		Name nvarchar(500),
		Code nvarchar(500),
		RollNo int,
		ClassId int,
		DivisionId int,
		ClassName nvarchar(500),
		DivisionName nvarchar(500),
		ClassDivision nvarchar(500),
		FeeHeadId int,
		FeeHead nvarchar(400),
		FeeId int,
		FeeName nvarchar(300),
		PaidAmount decimal(12,2),
		PayTypeId int,
		PayType nvarchar(500),			
		ChequeNo nvarchar(500),
		BankName nvarchar(500),
		Address1 nvarchar(max),
		Address2 nvarchar(max),
		FullTitle nvarchar(500),
		TotalReceiptAmount decimal(12,2),
		ReceiptAmount decimal(12,2),					
		ReceiptAmountInWords nvarchar(1000),			
		DiscountAmount decimal(12,2),
		Remark nvarchar(max),
		UserName nvarchar(500),
		OrgLogo varbinary(max),
		Remark1 nvarchar(max),
		Remark2 nvarchar(max),			 
		IsOnPrePrinted bit,
		IsSupressLogo bit,
		IsDisplaySchoolName bit,
		ReportId int,
		OrganizationName nvarchar(500),
		MonthDetail nvarchar(200),    		 	
		FeeDuration nvarchar(500),			
		DepartmentName nvarchar(500),
		FeeOrderIndex int,
		FeeHeadOrderIndex int,
		IsCancelReceipt bit,
		CurrencyCode nvarchar(200),
		CurrencyTitle nvarchar(200),
		Batch nvarchar(200),
		ChequeDate Date,
		IsMonthDetailOnly bit,
	    IsFeeInvoiceHeadwise bit,
	    GroupTitle nvarchar(200),
	    IsSuppressFeeDetail bit,
	    CollectionGroupName nvarchar(500),
	    InvoiceNumber int,
	    SUID nvarchar(400),
	    HeaderDisplayId int,
	    ReceiptBookHeader varbinary(max),
	    ServiceTaxPercentage decimal(6,2),
	    AmountAfterDiscount decimal(12,2),
	    CGSTPercentage decimal(5,2),
	    SGSTPercentage decimal(5,2),
	    CGSTAmount decimal(12,2),
	    SGSTAmount decimal(12,2),
		GSTINNo nvarchar(50),
	    HSNSACCode nvarchar(15),
	    ItemValue nvarchar(200),
	    FatherName nvarchar(200),
	    MotherName nvarchar(200),
	    ExemptionAmount decimal(12,2),
		ExemptionRemark nvarchar(max),
		EmployeeSign varbinary(max),
		PresentCity nvarchar(50),
		PresentAdress nvarchar(2000),
		ParentContactNo nvarchar(50),			
		IsDisplayPendingFeeAmount bit,
		PendingFeeAmount decimal(12,2),
		FirstName nvarchar(200),
		LastName nvarchar(200),
		FeeAmount decimal(12,2),
		ExemptionAmountSum decimal(12,0),
		TransportBusRoute nvarchar(max),
		BankAccountNumber nvarchar(50),
		FeeHeadNumber int,
		FeeNumber int,
		DigitalSignature varbinary(max),
		CancelStatusRemark nvarchar(max),
		FeeSetupAmount decimal(12,2),
		CreatedDateTime datetime,
		PaymentTransactionId bigint,
		MiddleName nvarchar(200),
		CreatedTime datetime,
		TotalPayableAmount decimal(12,2),
		OrgGroupTitle nvarchar(400),
		NextInstallmentName nvarchar(200), 
		House nvarchar(200),	
		NextInstallmentStartDate date, 
		NextInstallmentEndDate date,
		NextInstallmentAmount decimal(12,2),  
		FeeActualAmount decimal(12,2),	
		StudentContactNo nvarchar(100),
		ReceiptBookId bigint
	)

WHILE @lId <= @lCountReceiptId
	BEGIN

	SELECT @lReceiptId = ReceiptId FROM #tmp WHERE Id = @lId
	
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @lReceiptId

		SELECT  @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount,0.00),1,2,@lOrgGroupId)
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
		SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END

	IF(@rOrgGroupId=0) SET @rOrgGroupId=@lOrgGroupId

	INSERT INTO #ReceiptDetail
	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,			
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,			
			--changes by Jash on 06/11/2020--%
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,					
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  ISNULL(FR.PaymentTransactionId,0) > 0 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0 THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	 			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @lReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
			ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,			
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0) END)
			ELSE 
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) END AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(FM.Number,0) AS FeeNumber,
			ISNULL(RBM.DigitalSignature,0x) AS DigitalSignature,
			ISNULL(FR.CancelStatusRemark,'') AS CancelStatusRemark,
			FS.Amount AS FeeSetupAmount,
			FR.CreatedDateTime ,
			ISNULL(FR.PaymentTransactionId,0) As PaymentTransactionId,
			SA.MiddleName,
			CONVERT(char(5),FR.CreatedDateTime,108) AS CreatedTime,
			--by megha - 0026430

			(CASE WHEN ISNULL(FA.VariableAmount,0) > 0 Then FA.VariableAmount 
			      When ISNULL(FS.Amount,0) > 0 Then FS.Amount END) + ISNULL(FA.AdditionalAmount,0) - ISNULL(FA.DiscountAmount,0) - ISNULL(FA.NotApplicableAmount,0) As TotalPayableAmount,
			OGM.Title AS OrgGroupTitle,
			 NID.CollectionGroupName AS NextInstallmentName, --Mantis End- 0031305
			ISNULL(HM.Title,'') AS House,	--add for mantis: 32658
			NID.StartDate AS NextInstallmentStartDate, --Mantis -  Start 32760
			NID.EndDate AS NextInstallmentEndDate,
			NID.PendingAmount AS NextInstallmentAmount,   --Mantis -  End 32760			
			ISNULL([sFee].[fFeeActualAmountSumGet](FR.SourceId),0) AS FeeActualAmount,	-- MantisId : 0032658
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo -- MantisId : 0032895
			,RBM.Id
 	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId  -- Mantis : 0029314
			LEFT JOIN (SELECT * FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @lReceiptId)) NID -- Mantis Start - 0031305
			ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId -- Mantis End - 0031305
			LEFT JOIN sStudent.tStudentOther AS SO ON SO.StudentId = SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId		--add for mantis: 32658
	WHERE 
			((FR.Id=@lReceiptId) OR (@lReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
			AND ((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0) )
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
	

	SET @lId=@lId+1
	END


	Select * from #ReceiptDetail
	DROP TABLE #tmp
	DROP TABLE #ReceiptDetail
END

--BEGIN
--SELECT
-- CAST(0 AS bigint) AS ReceiptId,
-- 0	AS ReceiptNumber,
-- CAST('' AS date) AS ReceiptDate,
-- CAST(0 AS bigint) AS AcademicId,
-- ''	AS Name,
--''	AS Code,
-- 0	AS RollNo,
--0	AS ClassId,
--0	AS DivisionId,
--''	AS ClassName,
--''	AS DivisionName,
--''	AS ClassDivision,
--0	AS FeeHeadId,
--''	AS FeeHead,
--0	AS FeeId,
--''	AS FeeName,
--CAST(0.0 AS decimal(12,2)) AS PaidAmount,
--CAST(0 AS tinyint) AS PayTypeId,
--''	AS PayType,
--''	AS ChequeNo,	
--''	AS BankName,
--''	AS Address1,
--''	AS Address2,
--''	AS FullTitle,
--CAST(0.0 AS decimal(12,2)) AS TotalReceiptAmount,
--CAST(0.0 AS decimal(12,2)) AS ReceiptAmount,					
--''	AS ReceiptAmountInWords,		
--CAST(0.0 AS decimal(12,2)) AS DiscountAmount,
--''	AS Remark,
--''	AS UserName,		
--0x  AS OrgLogo,
--''	AS Remark1,
--''	AS Remark2,			 
--CAST(0 AS bit) AS IsOnPrePrinted,
--CAST(0 AS bit) AS IsSupressLogo,
--CAST(0 AS bit) AS IsDisplaySchoolName,
--0	AS ReportId,
--''	AS OrganizationName,		  
--''	AS MonthDetail,    			
--''	AS FeeDuration,		
--''	AS DepartmentName,
-- 0	AS FeeOrderIndex,
--CAST(0 AS smallint)	AS FeeHeadOrderIndex,
--CAST(0 AS bit) AS IsCancelReceipt,
--''	AS CurrencyCode,
--''	AS CurrencyTitle,
--''	AS Batch,
--CAST('' AS date) AS ChequeDate,
--CAST(0 AS bit) AS IsMonthDetailOnly,
--CAST(0 AS bit) AS IsFeeInvoiceHeadwise,
--''	AS GroupTitle,
--CAST(0 AS bit) AS IsSuppressFeeDetail,
--''	AS CollectionGroupName,
--0	AS InvoiceNumber,
--''	AS SUID,
--CAST(0 AS tinyint) AS HeaderDisplayId,
--0x  AS ReceiptBookHeader,
--CAST(0.0 AS decimal(6,2)) AS ServiceTaxPercentage,
--CAST(0.0 AS decimal(12,2)) AS AmountAfterDiscount,
--CAST(0.0 AS decimal(5,2)) AS CGSTPercentage,
--CAST(0.0 AS decimal(5,2)) AS SGSTPercentage,
--CAST(0.0 AS decimal(12,2)) AS CGSTAmount,
--CAST(0.0 AS decimal(12,2))	AS SGSTAmount,
--''	AS GSTINNo,
--''	AS HSNSACCode,
--''	AS ItemValue ,
--''	AS FatherName,
--''	AS MotherName,
--CAST(0.0 AS decimal(12,2)) AS ExemptionAmount,
--''	AS ExemptionRemark,
--0x AS EmployeeSign,
--''	AS PresentCity,
--''	AS PresentAdress,
--''	AS ParentContactNo,	
--CAST(0 AS bit) AS IsDisplayPendingFeeAmount,
--CAST(0.0 AS decimal(12,0)) AS PendingFeeAmount,
--''	AS FirstName,
--''	AS LastName,
--CAST(0.0 AS decimal(12,0))	AS FeeAmount,
--CAST(0.0 AS decimal(12,0)) AS ExemptionAmountSum,
--''	AS TransportBusRoute,
--''	AS BankAccountNumber,
--0	AS FeeHeadNumber,
--0	AS FeeNumber,
--0x AS DigitalSignature,
--''	AS CancelStatusRemark,
--CAST(0.0 AS decimal(12,2))	AS FeeSetupAmount,
--''	AS CreatedDateTime ,
--CAST(0 AS bigint)	AS PaymentTransactionId,
--''	AS MiddleName,
--'' AS CreatedTime,
-- 0 AS TotalPayableAmount,
-- '' AS OrgGroupTitle,
-- '' AS NextInstallmentName,
-- '' AS House,
-- CAST('' AS date) AS NextInstallmentStartDate,
-- CAST('' AS date) NextInstallmentEndDate,
-- CAST(0.0 AS decimal(12,2)) AS NextInstallmentAmount,
-- CAST(0.0 AS decimal(12,2)) AS FeeActualAmount,
-- '' AS StudentContactNo

--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptPDCFeeStatusWise]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	WITH CTE AS (
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SC.ParentContactNo,
			--ISNULL(PDP.Amount,0) As PDCEntryAmount,
			ISNULL(sFee.fnGetSumByReceiptBookWise(SA.AcademicId,SA.BatchId,FS.ReceiptBookId),0) AS PDCEntryAmount,
			ROW_NUMBER() OVER (PARTITION BY SA.AcademicId, FS.ReceiptBookId ORDER BY (SELECT NULL)) AS rn,
			SO.ReferenceRemark,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			[sFee].[fFeeAmountReceiptBookWiseSumGet](SA.AcademicId, FS.ReceiptBookId, 'TotalAmount')AS TotalFeeReceiptBookWise,--added by dhananjay for mantis - 39394
			[sFee].[fFeeAmountReceiptBookWiseSumGet](SA.AcademicId, FS.ReceiptBookId, 'PaidAmount')AS PaidAmountReceiptBookWise--added by dhananjay for mantis - 39394

	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN sStudent.tStudentCommunication SC ON  SC.StudentId=SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId						-- MantisId : 0036935
			--LEFT JOIN  sFee.tPostDatePayment PDP ON PDP.SourceId = SA.AcademicId AND PDP.SourceTypeId = 2001 AND FS.ReceiptBookId = PDP.ReceiptBookId AND SA.BatchId = PDP.BatchId--MAntis - 0034487

			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0	--added by dhananjay for mantis - 39394
		
		)

		SELECT
			Builder1,
			Builder2,
			IsDetail,
			IsFilter,
			IsHeader, 
			IsDisplayOrgGroup,
			AcademicId,
			RollNo,
			Name,
			Code,
			ClassId,
			DivisionId,
			ClassName,
			DivisionName,
			DivisionOrderIndex,
			ClassOrderIndex,
			ClassDivision,
			FeeSetupId,
			IsVariable,
			Amount,
			StartDate,
			EndDate,
			FAAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			PaidAmount,
			PendingAmount,
			Remark,
			ReceiptBookId,
			FeeName,
			FeeCode,
			FeeOrderIndex,
			OrgId,
			OrgName,
			OrgOrderIndex,
			ReceiptBookTitle,
			ReceiptOrderIndex,
			DepartmentId,
			DepartmentName,
			ExemptionTypeId,
			ExemptionType,
			FeeHeadId,
			FeeHeadName,
			FeeHeadOrderIndex,
			FeeGroup,
			BatchId,
			BatchName,
			CancelAmount,
			Discount,
			Status,
			ParentContactNo,
			CASE
				WHEN rn = 1 THEN PDCEntryAmount
				ELSE 0
			END AS PDCEntryAmount,
			ReferenceRemark,
			StudentContactNo,
			--added by dhananjay for mantis - 39394
			CASE
				WHEN rn = 1 THEN TotalFeeReceiptBookWise
				ELSE 0
			END AS TotalFeeReceiptBookWise,
			CASE
				WHEN rn = 1 THEN PaidAmountReceiptBookWise
				ELSE 0
			END AS PaidAmountReceiptBookWise
			--added by dhananjay for mantis - 39394
		FROM
			CTE
			--WHERE PendingAmount > 0
			Order by  FeeHeadOrderIndex,FeeOrderIndex,RollNo
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sFee].[pRptPDCStatusWiseDetails]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	WITH CTE AS (
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SC.ParentContactNo,
			--ISNULL(PDP.Amount,0) As PDCEntryAmount,
			ISNULL(sFee.fnGetSumByReceiptBookWise(SA.AcademicId,SA.BatchId,FS.ReceiptBookId),0) AS PDCEntryAmount,
			ROW_NUMBER() OVER (PARTITION BY SA.AcademicId, FS.ReceiptBookId ORDER BY (SELECT NULL)) AS rn,
			SO.ReferenceRemark

	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN sStudent.tStudentCommunication SC ON  SC.StudentId=SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId						-- MantisId : 0036935
			--LEFT JOIN  sFee.tPostDatePayment PDP ON PDP.SourceId = SA.AcademicId AND PDP.SourceTypeId = 2001 AND FS.ReceiptBookId = PDP.ReceiptBookId AND SA.BatchId = PDP.BatchId--MAntis - 0034487

			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		
		)

		SELECT
			Builder1,
			Builder2,
			IsDetail,
			IsFilter,
			IsHeader, 
			IsDisplayOrgGroup,
			AcademicId,
			RollNo,
			Name,
			Code,
			ClassId,
			DivisionId,
			ClassName,
			DivisionName,
			DivisionOrderIndex,
			ClassOrderIndex,
			ClassDivision,
			FeeSetupId,
			IsVariable,
			Amount,
			StartDate,
			EndDate,
			FAAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			PaidAmount,
			PendingAmount,
			Remark,
			ReceiptBookId,
			FeeName,
			FeeCode,
			FeeOrderIndex,
			OrgId,
			OrgName,
			OrgOrderIndex,
			ReceiptBookTitle,
			ReceiptOrderIndex,
			DepartmentId,
			DepartmentName,
			ExemptionTypeId,
			ExemptionType,
			FeeHeadId,
			FeeHeadName,
			FeeHeadOrderIndex,
			FeeGroup,
			BatchId,
			BatchName,
			CancelAmount,
			Discount,
			Status,
			ParentContactNo,
			CASE
				WHEN rn = 1 THEN PDCEntryAmount
				ELSE 0
			END AS PDCEntryAmount,
			ReferenceRemark
		FROM
			CTE
			Order by  FeeHeadOrderIndex,FeeOrderIndex,RollNo
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptPendingFee100PercentGet]

 @rOrgId int = 0,
 @rBatchId int = 0,
 @rOrgGroupBatchId int = 0,
 @rClassId int = 0,
 @rDivisionId int = 0,
 @rReceiptBookId int = 0,
 @rDepartmentId int = 0,
 @rCommonBatch nvarchar(100) = '',
 @rAdmissionCategoryId int = 0,
 @rClassStatusId int = 0,
 @rIsDisplayOrgGroup bit=0,
 @rIsFilter bit=0,
 @rBuilder1 nvarchar(max) = '',
 @rBuilder2 nvarchar(max) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF object_id('tempdb..#tTable') IS NOT NULL
	BEGIN
		DROP TABLE #tTable
	END
CREATE TABLE #tTable(
	AcademicId BIGINT NOT NULL,
	AdmissionCategoryId int,
	ReceiptBookId int
)
INSERT INTO #tTable
	SELECT SA.AcademicId, FS.AdmissionCategoryId, FS.ReceiptBookId
	FROM sFee.tFeeSetup FS
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
	--INNER JOIN sSetup.tBatchMaster BM ON FS.BatchId = BM.Id 
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
	WHERE 
	((SA.OrgId = @rOrgId)OR(@rOrgId = 0)) 
	AND ((SA.BatchId = @rBatchId) OR (@rBatchId = 0))
	AND (SA.BatchName = @rCommonBatch OR @rCommonBatch = '') 
	AND (SA.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (SA.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)
	AND (SA.ClassId = @rClassId OR @rClassId = 0)
	AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
	AND (FS.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
	AND (FS.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
	GROUP BY FS.ClassId,SA.AcademicId,FS.AdmissionCategoryId, FS.ReceiptBookId


SELECT F.AcademicId, F.RollNo, F.Name, F.Code, F.ClassName , F.DivisionName , @rIsFilter AS IsFilter ,
	 @rIsDisplayOrgGroup AS IsDisplayOrgGroup, F.ClassOrderIndex, F.DivisionOrder AS DivisionOrderIndex,
	 @rBuilder1 AS Builder1, @rBuilder2 AS Builder2, 
	 --Mantis Start-0031251
	   F.ParentContactNo,
	 --Mantis End 
	  --add by dhananjay for mantis - 35664 
	  F.ClassId,
	  F.DivisionId, 
	  --add by dhananjay for mantis - 35664 
	  --startAdd for mantis : 0035819
	  [sFee].[fPendingFeeAmountAcademicIdwiseGet](F.AcademicId) AS PendingAmount,
	  F.DepartmentId,
	  F.OrgId,
	  F.DepartmentName,
	  F.OrganizationName 
	  --End Add for mantis : 0035819
	FROM
		(

		SELECT 
			Distinct --Add for mantis : 0035819
			SA.AcademicId, SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial]
			,SA.ClassName , SA.DivisionName , SA.ClassOrderIndex , SA.DivisionOrder
			,(
				SELECT (SUM(FS1.Amount)+Sum(FA1.VariableAmount)+ SUM(FA1.AdditionalAmount)) - (SUM(FA1.DiscountAmount)+ SUM(FA1.NotApplicableAmount)) 
				FROM sFee.tFeeAllocation FA1
				INNER JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId AND FA1.FeeSetupId = FS1.Id
				WHERE FA1.SourceId = SA.AcademicId 
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
			) AS IsFeePayAmount, 
			--Mantis Start-0031251
			ISNULL(SC.ParentContactNo, '') AS ParentContactNo,
			--Mantis End
			 --add by dhananjay for mantis - 35664 
			SA.ClassId, 
			SA.DivisionId ,
			 --add by dhananjay for mantis - 35664 
			 --Start Add for mantis : 0035819
			 SA.DepartmentId, 
			 SA.OrgId,
			 SA.DepartmentName,
			 SA.OrganizationName
			 --End Add for mantis : 0035819
		FROM sStudent.vStudentAcademic SA 
		INNER JOIN #tTable FS  on  FS.AcademicId = SA.AcademicId
		LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,R.SourceId AS AcademicId--, SA.Code,SA.Name 
			FROM sFee.tReceipt R
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 --AND((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((R.BatchId = @rBatchId) OR (@rBatchId = 0)) AND (R.IsObsolete = 0)
			AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0) 
			GROUP BY R.SourceId--, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
		LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
					(
					SELECT 
						SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
					Group By R.SourceId,FS.Id
					) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
					(
					SELECT Distinct SourceId 
					FROM sFee.tReceipt 
					) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
							
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
					SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
					Group By R.SourceId,FS.Id
					) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
					SELECT Distinct SourceId 
					FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)

			) PS ON PS.AcademicId=SA.AcademicId
			--Mantis Start-0031251
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =SA.StudentId 
			--Mantis End

		WHERE 
			
		((SA.OrgId = @rOrgId)OR(@rOrgId = 0)) 
		AND SA.StatusId =1
		AND ((SA.BatchId = @rBatchId) OR (@rBatchId = 0))
		AND (SA.BatchName = @rCommonBatch OR @rCommonBatch = '') 
		AND (SA.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND (SA.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)
		AND (SA.ClassId = @rClassId OR @rClassId = 0)
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
		AND (FS.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (FS.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)	
		) 
		AS F 
		
	WHERE ISNULL(F.IsFeePayAmount,1) <> 0 AND F.Pending = 0 AND F.Partial = 0


	----For Dataset Drag and Drop
	--SELECT
	--CONVERT(BigInt,0) AS AcademicId,
	--0 AS RollNo,
	--'' AS Name,
	--'' AS Code,
	--'' AS ClassName,
	--'' AS DivisionName,
	--CONVERT(bit,0) AS IsFilter,
	--CONVERT(bit,0) AS IsDisplayOrgGroup,
	--0 AS ClassOrderIndex,
	--0 AS DivisionOrderIndex,
	--'' AS Builder1,
	--'' AS Builder2,
	--'' AS ParentContactNo, --Mantis 0031251
	-- --add by dhananjay for mantis35664 
	--0 AS ClassId,
	--0 As DivisionId,
	-- --add by dhananjay for mantis35664 
	-- 0 AS PendingAmount,
	-- 0 AS DepartmentId,
	-- 0 AS OrgId,
	-- '' AS DepartmentName,
	-- '' AS OrganizationName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptPendingFeeMonthwiseGet]
	 
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rFromReceiptNo int=0,
		@rToReceiptNo int=0,
		@rBatchId int,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)=0,
		@rBuilder2 nvarchar(max)=0,
		@rIsDetail bit=0,
		@rIsCancel bit=0,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int=0,
		@rPaytypeId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20),
	    @rIsFilter bit=0,
	    @rIsHeader bit=0,
	    @rCreatedUserName nvarchar(100)='',
	    @rFeeHeadId nvarchar(max) = '',
	    @rIsDisplayOrgGroup bit=0,
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rPayDate date='',--,
	    --@rOrgIds nvarchar(max) = ''
	    @rReportType int=1,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	
DECLARE @lStartMonth AS INT

SELECT @lStartMonth = MONTH(BM.FromDate) FROM sSetup.tBatchMaster BM WHERE BM.Id=@rBatchId

DECLARE @lMonth1 AS INT
DECLARE @lMonth2 AS INT
DECLARE @lMonth3 AS INT
DECLARE @lMonth4 AS INT
DECLARE @lMonth5 AS INT
DECLARE @lMonth6 AS INT
DECLARE @lMonth7 AS INT
DECLARE @lMonth8 AS INT
DECLARE @lMonth9 AS INT
DECLARE @lMonth10 AS INT
DECLARE @lMonth11 AS INT
DECLARE @lMonth12 AS INT

IF (@lStartMonth = 1)
BEGIN
	SET @lMonth1 = 1
	SET @lMonth2 = 2
	SET @lMonth3 = 3
	SET @lMonth4 = 4
	SET @lMonth5 = 5
	SET @lMonth6 = 6
	SET @lMonth7 = 7
	SET @lMonth8 = 8
	SET @lMonth9 = 9
	SET @lMonth10 = 10
	SET @lMonth11 = 11
	SET @lMonth12 = 12
END

ELSE IF (@lStartMonth = 2)
BEGIN
	SET @lMonth1 = 2
	SET @lMonth2 = 3
	SET @lMonth3 = 4
	SET @lMonth4 = 5
	SET @lMonth5 = 6
	SET @lMonth6 = 7
	SET @lMonth7 = 8
	SET @lMonth8 = 9
	SET @lMonth9 = 10
	SET @lMonth10 = 11
	SET @lMonth11 = 12
	SET @lMonth12 = 1
END

ELSE IF (@lStartMonth = 3)
BEGIN
	SET @lMonth1 = 3
	SET @lMonth2 = 4
	SET @lMonth3 = 5
	SET @lMonth4 = 6
	SET @lMonth5 = 7
	SET @lMonth6 = 8
	SET @lMonth7 = 9
	SET @lMonth8 = 10
	SET @lMonth9 = 11
	SET @lMonth10 = 12
	SET @lMonth11 = 1
	SET @lMonth12 = 2
END

ELSE IF (@lStartMonth = 4)
BEGIN
	SET @lMonth1 = 4
	SET @lMonth2 = 5
	SET @lMonth3 = 6
	SET @lMonth4 = 7
	SET @lMonth5 = 8
	SET @lMonth6 = 9
	SET @lMonth7 = 10
	SET @lMonth8 = 11
	SET @lMonth9 = 12
	SET @lMonth10 = 1
	SET @lMonth11 = 2
	SET @lMonth12 = 3
END

ELSE IF (@lStartMonth = 5)
BEGIN
	SET @lMonth1 = 5
	SET @lMonth2 = 6
	SET @lMonth3 = 7
	SET @lMonth4 = 8
	SET @lMonth5 = 9
	SET @lMonth6 = 10
	SET @lMonth7 = 11
	SET @lMonth8 = 12
	SET @lMonth9 = 1
	SET @lMonth10 = 2
	SET @lMonth11 = 3
	SET @lMonth12 = 4
END

ELSE IF (@lStartMonth = 6)
BEGIN
	SET @lMonth1 = 6
	SET @lMonth2 = 7
	SET @lMonth3 = 8
	SET @lMonth4 = 9
	SET @lMonth5 = 10
	SET @lMonth6 = 11
	SET @lMonth7 = 12
	SET @lMonth8 = 1
	SET @lMonth9 = 2
	SET @lMonth10 = 3
	SET @lMonth11 = 4
	SET @lMonth12 = 5
END

ELSE IF (@lStartMonth = 7)
BEGIN
	SET @lMonth1 = 7
	SET @lMonth2 = 8
	SET @lMonth3 = 9
	SET @lMonth4 = 10
	SET @lMonth5 = 11
	SET @lMonth6 = 12
	SET @lMonth7 = 1
	SET @lMonth8 = 2
	SET @lMonth9 = 3
	SET @lMonth10 = 4
	SET @lMonth11 = 5
	SET @lMonth12 = 6
END

ELSE IF (@lStartMonth = 8)
BEGIN
	SET @lMonth1 = 8
	SET @lMonth2 = 9
	SET @lMonth3 = 10
	SET @lMonth4 = 11
	SET @lMonth5 = 12
	SET @lMonth6 = 1
	SET @lMonth7 = 2
	SET @lMonth8 = 3
	SET @lMonth9 = 4
	SET @lMonth10 = 5
	SET @lMonth11 = 6
	SET @lMonth12 = 7
END

ELSE IF (@lStartMonth = 9)
BEGIN
	SET @lMonth1 = 9
	SET @lMonth2 = 10
	SET @lMonth3 = 11
	SET @lMonth4 = 12
	SET @lMonth5 = 1
	SET @lMonth6 = 2
	SET @lMonth7 = 3
	SET @lMonth8 = 4
	SET @lMonth9 = 5
	SET @lMonth10 = 6
	SET @lMonth11 = 7
	SET @lMonth12 = 8
END

ELSE IF (@lStartMonth = 10)
BEGIN
	SET @lMonth1 = 10
	SET @lMonth2 = 11
	SET @lMonth3 = 12
	SET @lMonth4 = 1
	SET @lMonth5 = 2
	SET @lMonth6 = 3
	SET @lMonth7 = 4
	SET @lMonth8 = 5
	SET @lMonth9 = 6
	SET @lMonth10 = 7
	SET @lMonth11 = 8
	SET @lMonth12 = 9
END

ELSE IF (@lStartMonth = 11)
BEGIN
	SET @lMonth1 = 11
	SET @lMonth2 = 12
	SET @lMonth3 = 1
	SET @lMonth4 = 2
	SET @lMonth5 = 3
	SET @lMonth6 = 4
	SET @lMonth7 = 5
	SET @lMonth8 = 6
	SET @lMonth9 = 7
	SET @lMonth10 = 8
	SET @lMonth11 = 9
	SET @lMonth12 = 10
END

ELSE IF (@lStartMonth = 12)
BEGIN
	SET @lMonth1 = 12
	SET @lMonth2 = 1
	SET @lMonth3 = 2
	SET @lMonth4 = 3
	SET @lMonth5 = 4
	SET @lMonth6 = 5
	SET @lMonth7 = 6
	SET @lMonth8 = 7
	SET @lMonth9 = 8
	SET @lMonth10 = 9
	SET @lMonth11 = 10
	SET @lMonth12 = 11
END

BEGIN


	CREATE TABLE #TempStudentPendingFee
	(
		[AcademicId] bigint NULL
	)

	IF(@rReportType=1)
		BEGIN    
	
			INSERT INTO #TempStudentPendingFee 
	SELECT 
	 	DISTINCT SA.AcademicId
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(FS.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
	    AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))   
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		SA.AdmissionCategoryId,

		[sCommon].[fGetMonthName](@lMonth1) AS Month1,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth1,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail1,

		[sCommon].[fGetMonthName](@lMonth2) AS Month2,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth2,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail2,

		[sCommon].[fGetMonthName](@lMonth3) AS Month3,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth3,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail3,

		[sCommon].[fGetMonthName](@lMonth4) AS Month4,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth4,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail4,

		[sCommon].[fGetMonthName](@lMonth5) AS Month5,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth5,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail5,

		[sCommon].[fGetMonthName](@lMonth6) AS Month6,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth6,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail6,

		[sCommon].[fGetMonthName](@lMonth7) AS Month7,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth7,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail7,

		[sCommon].[fGetMonthName](@lMonth8) AS Month8,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth8,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail8,

		[sCommon].[fGetMonthName](@lMonth9) AS Month9,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth9,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail9,

		[sCommon].[fGetMonthName](@lMonth10) AS Month10,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth10,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail10,

		[sCommon].[fGetMonthName](@lMonth11) AS Month11,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth11,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail11,

		[sCommon].[fGetMonthName](@lMonth12) AS Month12,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth12,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail12,
		
		@rPayDate AS PayDate
	
		
  FROM 
		  sStudent.vStudentAcademic SA
		  INNER JOIN #TempStudentPendingFee T ON T.AcademicId = SA.AcademicId
		   LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		  WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (
				 (@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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')   
				 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		END
	ELSE
		BEGIN
		INSERT INTO #TempStudentPendingFee 
		SELECT 	DISTINCT SA.AcademicId  FROM  sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId AND FS.BatchId =SA.BatchId  AND FS.AdmissionCategoryId=SA.AdmissionCategoryId AND SA.ClassId=FS.ClassId
		WHERE (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)
		AND ISNULL(FAS.ToPayAmount,0) !=0
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		SA.AdmissionCategoryId,

		[sCommon].[fGetMonthName](@lMonth1) AS Month1,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth1,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail1,

		[sCommon].[fGetMonthName](@lMonth2) AS Month2,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth2,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail2,

		[sCommon].[fGetMonthName](@lMonth3) AS Month3,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth3,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail3,

		[sCommon].[fGetMonthName](@lMonth4) AS Month4,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth4,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail4,

		[sCommon].[fGetMonthName](@lMonth5) AS Month5,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth5,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail5,

		[sCommon].[fGetMonthName](@lMonth6) AS Month6,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth6,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail6,

		[sCommon].[fGetMonthName](@lMonth7) AS Month7,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth7,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail7,

		[sCommon].[fGetMonthName](@lMonth8) AS Month8,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth8,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail8,

		[sCommon].[fGetMonthName](@lMonth9) AS Month9,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth9,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail9,

		[sCommon].[fGetMonthName](@lMonth10) AS Month10,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth10,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail10,

		[sCommon].[fGetMonthName](@lMonth11) AS Month11,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth11,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail11,

		[sCommon].[fGetMonthName](@lMonth12) AS Month12,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth12,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail12,
		
		@rPayDate AS PayDate
	
		
  FROM 
		  sStudent.vStudentAcademic SA
		  INNER JOIN #TempStudentPendingFee T ON T.AcademicId = SA.AcademicId
		   LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		  WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (
				 (@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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')   
				 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		END

END
		DROP TABLE #TempStudentPendingFee
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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(R.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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptReceiptListCollectionGroupwiseListGet]  
	@rReportId int,  
	@rReceiptBookId int,  
	@rAdmissionCategoryId int,  
	@rClassId int,  
	@rDivisionId int,  
	@rFromDate date,  
	@rToDate date,  
	@rFromReceiptNo int,  
	@rToReceiptNo int,  
	@rBatchId int,  
	@rUserId bigint,  
	@rBuilder1 nvarchar(max),  
	@rBuilder2 nvarchar(max),  
	@rIsCancel bit,  
	@rOrgId int,  
	@rOrgGroupBatchId int,  
	@rStatusId int,  
	@rCommonBatch nvarchar(100),  
	@rDepartmentId int,  
	@rFromRollNo int,  
	@rToRollNo int,  
	@rCode nvarchar(20),  
	@rIsDetail bit=0,  
	@rIsFilter bit,  
	@rIsHeader bit,  
	@rCreatedUserName nvarchar(100)='',  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rPayTypeId int=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,
	@rOrgIds nvarchar(max) = '',
	@rClassStatusId int=0,
	@rPayTypeIds nvarchar(max) = '',
	@rCollectionGroupId int =0  
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN    
	-- Added for optimization by Foram, Mantis : 0042814
	-- Pre-split inputs
	DECLARE @FeeHeadIds TABLE (Id INT);
	DECLARE @FeeIds TABLE (Id INT);
	DECLARE @OrgIds TABLE (Id INT);
	DECLARE @PayTypeIds TABLE (Id TINYINT);
	DECLARE @AssignRouteStudentIds TABLE (SourceId BIGINT);

	INSERT INTO @FeeHeadIds
	SELECT CAST(item AS INT) FROM sCommon.fnsplit(@rFeeHeadId, ',');

	INSERT INTO @FeeIds
	SELECT CAST(item AS INT) FROM sCommon.fnsplit(@rFeeId, ',');

	INSERT INTO @OrgIds
	SELECT CAST(item AS INT) FROM sCommon.fnsplit(@rOrgIds, ',');

	INSERT INTO @PayTypeIds
	SELECT CAST(item AS TINYINT) FROM sCommon.fnsplit(@rPayTypeIds, ',');

	INSERT INTO @AssignRouteStudentIds
	SELECT AT.SourceId
	FROM sTransport.tAssignRoute AT WITH (NOLOCK)
	INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id = AT.PickupDestinationId
	INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id = BM.BusRouteId
		AND AT.SourceTypeId = 2003
		AND (
			(B.OrgGroupBatchId = @rOrgGroupBatchId)
			OR (@rOrgGroupBatchId = 0)
			)

	DECLARE @lDefaultCurrencyTitle NVARCHAR(100)

	SELECT @lDefaultCurrencyTitle = ISNULL(COALESCE(CS.ItemValue, CM.ItemValue), 'Rupees')
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId = 2010 AND CS.SourceId = LEFT(@rOrgGroupBatchId, 4)
	WHERE CM.Id = 153;
	-- Added for optimization by Foram, Mantis : 0042814

	SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsCancel AS IsCancel,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		R.Id AS ReceiptId,  
		R.ReceiptNumber,  
		SA.ClassId,  
		SA.ClassName,  
		SA.DivisionId,  
		SA.DivisionName,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		SA.RollNo,  
		SA.AcademicId,  
		SA.FirstName,  
		SA.MiddleName,  
		SA.LastName,  
		SA.Code,  
		SA.Name,  
		PTM.Title AS PayType,  
		--R.ChequeNo,  
		--CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo, -- Commented for optimization by Foram, Mantis : 0042814
		ISNULL(NULLIF(R.ChequeNo, ''), CONVERT(NVARCHAR(20), R.PaymentTransactionId)) AS ChequeNo,    -- Added for optimization by Foram, Mantis : 0042814
		R.BankName,
		--R.ReceiptAmount,  ,
		CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
		R.ReceiptDate,  
		FM.Title AS FeeDetail,  
		FM.Code AS FeeCode,  
		FM.OrderIndex AS FeeOrderIndex,  
		RD.Amount AS DetailAmount,  
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		ISNULL(FHM.Title,'') AS FeeHead,  
		ISNULL(FHM.Code,'') AS FeeHeadCode,  
		ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
		SA.OrgId,  
		O.DisplayTitle AS OrgName,  
		O.OrderIndex AS OrgOrderIndex,  
		ISNULL(R.Remark,'') AS Remark,  
		DM.Id AS DepartmentId,  
		DM.Title AS DepartmentName,  
		SA.ClassOrderIndex,  
		--ISNULL(SO.GenderId,0) AS GenderId,  -- Commented for optimization by Foram, Mantis : 0042814
		ISNULL(SA.GenderId,0) AS GenderId, -- Added for optimization by Foram, Mantis : 0042814
		ISNULL(SA.BatchName,'') BatchName,  
		ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
		--sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  -- Commented for optimization by Foram, Mantis : 0042814
		sFinanceCommon.fNumberToWordsWithDecimalGet(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId,@lDefaultCurrencyTitle) AS ReceiptAmountInWords, -- Added for optimization by Foram, Mantis : 0042814
		R.ChequeDate,  
		ISNULL(FM.Id,0) AS FeeId,  
		ISNULL(FM.Title,'') AS Fee,  
		ISNULL(SF.FatherName,'' ) AS FatherName,  
		ISNULL(SF.MotherName,'' ) AS MotherNameDiscount,
		CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
		RD.Amount AS PaidAmount,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup  ,
		ISNULL(U.LoginTitle,'') AS UserName,
		SA.SUId AS SUId
	FROM   
		sFee.tReceipt R WITH (NOLOCK) 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM WITH (NOLOCK) ON PTM.Id=R.PayTypeId  
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId=R.Id  
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id=RD.FeeSetupId  
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS.FeeId  
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId  
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON RBM.Id=R.ReceiptBookId  
		INNER JOIN sSetup.tDepartmentMaster DM WITH (NOLOCK) ON SA.DepartmentId=DM.Id  
		INNER JOIN sSetup.tOrganizationMaster O  WITH (NOLOCK) ON O.Id=sa.OrgId  
		LEFT JOIN sSecurity.tUser U  WITH (NOLOCK) ON U.Id=R.CreatedUserId 
		--LEFT JOIN sStudent.tStudentOther SO  WITH (NOLOCK) ON SO.StudentId = SA.StudentId  -- Commented for optimization by Foram, Mantis : 0042814
		LEFT JOIN sStudent.tStudentFamily SF  WITH (NOLOCK) ON SF.StudentId = SA.StudentId  
		LEFT JOIN sHostel.tAssignRoom AR WITH (NOLOCK) ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		-- Commented for optimization by Foram, Mantis : 0042814
		--LEFT JOIN (SELECT AT.SourceId FROM sTransport.tAssignRoute AT WITH (NOLOCK)  
		--INNER JOIN sTransport.tBusRouteDestinationMaster BM WITH (NOLOCK) ON BM.Id=AT.PickupDestinationId  
		--INNER JOIN sTransport.tBusRouteMaster B WITH (NOLOCK) ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 
		--AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
		--ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		-- Commented for optimization by Foram, Mantis : 0042814
		LEFT JOIN @AssignRouteStudentIds RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) -- Added for optimization by Foram, Mantis : 0042814
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id  
	WHERE
		R.SourceTypeId = 2001  
		AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND (R.IsObsolete = @rIsCancel)   
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		AND ((SA.Code=@rCode) OR (@rCode=''))  
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		--AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
		AND (  
			(@rFilterId = 0) -- All  
			OR (@rFilterId = 2 AND isnull(AR.SourceId,0) <> 0) -- Hostel  
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0) <> 0) -- Transport  
			OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
		)  
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0)) 
		
		-- Commented for optimization by Foram, Mantis : 0042814 
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
		--AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='') 
		--AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
		-- Commented for optimization by Foram, Mantis : 0042814

		-- Added for optimization by Foram, Mantis : 0042814
		AND (@rFeeHeadId='' OR ISNULL(FM.FeeHeadId,0) IN (SELECT Id FROM @FeeHeadIds))
		AND (@rFeeId='' OR ISNULL(FM.Id,0) IN (SELECT Id FROM @FeeIds)) 
		AND (@rPayTypeIds='' OR ISNULL(R.PayTypeId,0) IN (SELECT Id FROM @PayTypeIds))
		AND (@rOrgIds='' OR ISNULL(SA.OrgId,0) IN (SELECT Id FROM @OrgIds))
		-- Added for optimization by Foram, Mantis : 0042814

	ORDER BY R.ReceiptNumber  

 --ORDER BY R.Id 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptReceiptRefundBatchwiseGet]

		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rFromDate date='',
		@rToDate date='',
		@rFromReceiptNo int=0,
		@rToReceiptNo int=0,
		@rBatchId int,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)=0,
		@rBuilder2 nvarchar(max)=0,
		@rIsDetail bit=0,
		@rIsCancel bit=0,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int=0,
		@rPaytypeId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rCode nvarchar(20),
		@rIsFilter bit=0,
		@rIsHeader bit=0,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rIsDiscount bit = 0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rCustomGroupId smallint = 0,
		@rOrgGroupId int=0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0,
		@rPayTypeIds nvarchar(max) = '' 
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsCancel AS IsCancel,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			RR.Id AS ReceiptRefundId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.RollNo,
			SA.Code,
			SA.Name,
			ISNULL(PTM.Title,'') AS PayType,
			ISNULL(RR.ChequeNo,'') AS ChequeNo,
			ISNULL(RR.BankName,'') AS BankName,
			RR.RefundAmount,
			RR.RefundDate,
			RR.CreatedUserId,
			ISNULL(U.LoginTitle,'') AS UserName,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.BankName,'') AS ReceiptBookBank,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
			RR.Remark,
			ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,
			SA.OrgId,
			SA.OrganizationName,
			@rCustomGroupId AS CustomGroupId,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName
		FROM 
			sFee.tReceipt R
			INNER JOIN 	sFee.tReceiptRefund RR ON R.Id = RR.ReceiptId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=RR.PayTypeId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
			LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)
		WHERE 
			R.SourceTypeId = 2001
			AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
			AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
			AND (R.IsObsolete = @rIsCancel) 
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
			AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
			AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=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))) -- School
			)
			AND	((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')     
		ORDER BY 
			R.ReceiptNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptReceiptSummaryDateWiseGet]
	@rReportId int=0,
	@rReceiptBookId int=0,
	@rAdmissionCategoryId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rFromDate date='',
	@rToDate date='',
	@rFromReceiptNo int=0,
	@rToReceiptNo int=0,
	@rBatchId int,
	@rUserId bigint=0,
	@rBuilder1 nvarchar(max)=0,
	@rBuilder2 nvarchar(max)=0,
	@rIsDetail bit=0,
	@rIsCancel bit=0,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rStatusId int=0,
	@rPaytypeId int=0,
	@rCommonBatch nvarchar(100)='',
	@rDepartmentId int=0,
	@rFromRollNo int=0,
	@rToRollNo int=0,
	@rCode nvarchar(20),
	@rIsFilter bit=0,
	@rIsHeader bit=0,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rIsDiscount bit = 0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rCustomGroupId smallint = 0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rClassStatusId int=0,
	@rPayTypeIds nvarchar(max) = '' 
	    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsCancel AS IsCancel,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		ISNULL(PTM.Id,0) AS PayTypeId,
		ISNULL(PTM.Title,'') AS PayType,
		--ISNULL(R.ChequeNo,'') AS ChequeNo,
		 CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		ISNULL(R.BankName,'') AS BankName,
		RD.Amount AS ReceiptAmount,
		R.ReceiptDate,
		R.CreatedUserId,
		ISNULL(U.LoginTitle,'') AS UserName,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		ISNULL(RBM.OrderIndex,0) As ReceiptBookOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.BankName,'') AS ReceiptBookBank,
		ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
		R.Remark,
		SA.OrgId,
		SA.OrganizationName,
		@rCustomGroupId AS CustomGroupId,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		FHM.Title AS FeeHeadName,
		[sFee].[fDatewiseFromToReceiptNumberGet](R.ReceiptBookId,R.BatchId,R.ReceiptDate) AS FromToReceiptNumber
	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 sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)
	WHERE
		R.SourceTypeId = 2001
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
		AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = @rIsCancel) 
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
		AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=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	((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')     
	ORDER BY 
		R.ReceiptNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptReceiptSummaryOrganizationFeeHeadAndPayTypeWiseGet]  
  @rReportId int=0,  
  @rReceiptBookId int=0,  
  @rAdmissionCategoryId int=0,  
  @rClassId int=0,  
  @rDivisionId int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rFromReceiptNo int=0,  
  @rToReceiptNo int=0,  
  @rBatchId int,  
  @rUserId bigint=0,  
  @rBuilder1 nvarchar(max)=0,  
  @rBuilder2 nvarchar(max)=0,  
  @rIsDetail bit=0,  
  @rIsCancel bit=0,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int=0,  
  @rPaytypeId int=0,  
  @rCommonBatch nvarchar(100)='',  
  @rDepartmentId int=0,  
  @rFromRollNo int=0,  
     @rToRollNo int=0,  
     @rCode nvarchar(20),  
     @rIsFilter bit=0,  
     @rIsHeader bit=0,  
     @rCreatedUserName nvarchar(100)='',  
     @rFeeHeadId nvarchar(max) = '',  
     @rIsDisplayOrgGroup bit=0,  
     @rIsDiscount bit = 0,  
     @rFeeId nvarchar(max) = '',  
     @rFilterId int=0,  
     @rCustomGroupId smallint = 0,  
     @rOrgGroupId int=0,  
     @rFeeStatusId int=0,  
     @rFromChequeDate date='',      
  @rToChequeDate date='',      
     @rBankName nvarchar(100)='',  
     @rOrgIds nvarchar(max) = '',  
     @rBankNames nvarchar(max) = '',  
  
  @rFromChequeClearDate Date = '',  
  @rToChequeClearDate Date = '' ,
  @rClassStatusId int=0 ,
  @rPayTypeIds nvarchar(max) = '',
  @rFeeGroupId int=0

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
  BEGIN      
  SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
    END   
  
 SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsDetail AS IsDetail,  
  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
  --@rIsCancel AS IsCancel,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  --SA.ClassName,  
  SA.DivisionId,  
  --SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.Code,  
  SA.Name,  
  ISNULL(PTM.Title,'') AS PayType,  
  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  ISNULL(R.BankName,'') AS BankName,  
  RD.Amount AS ReceiptAmount,  
  --R.ReceiptAmount,  
  --R.ReceiptDate,  
  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
  R.CreatedUserId,  
  ISNULL(U.LoginTitle,'') AS UserName,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
   ELSE '' END),'') AS FeeDetail,  
   R.Remark,  
   R.DiscountAmount,  
   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
   SA.OrgId,  
   SA.OrganizationName,  
   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
   @rCustomGroupId AS CustomGroupId,  
   SA.OrgGroupBatchId AS BatchId,  
   SA.BatchName,  
   R.ChequeDate,  
   R.ChequeClearDate,
   @rFeeGroupId As FeeGroup ,
   FM.Title AS FeeName,
   FHM.Title AS FeeHeadName
  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 sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
    
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  LEFT JOIN sSecurity.tUser U  
   ON U.Id=R.CreatedUserId  
 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId   
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
    AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId) 
   INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
  )))  
 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
  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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')     
  
 ORDER BY R.ReceiptNumber  
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptReceiptSummaryUserPayTypeWiseDetailsGet]  
	@rReportId int=0,
	@rReceiptBookId int=0,
	@rAdmissionCategoryId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rFromDate date='',
	@rToDate date='',
	@rFromReceiptNo int=0,
	@rToReceiptNo int=0,  
	@rBatchId int = 0,
	@rUserId bigint=0,
	@rBuilder1 nvarchar(max)=0,
	@rBuilder2 nvarchar(max)=0,
	@rIsDetail bit=0,
	@rIsCancel bit=0,
	@rOrgId int = 0,
	@rOrgGroupBatchId int = 0,
	@rStatusId int=0,
	@rPaytypeId int=0,
	@rCommonBatch nvarchar(100)='',
	@rDepartmentId int=0,
	@rFromRollNo int=0,
	@rToRollNo int=0,
	@rCode nvarchar(20)='',
	@rIsFilter bit=1,
	@rIsHeader bit=0,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rIsDiscount bit = 0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=1,
	@rCustomGroupId smallint = 0,
	@rOrgGroupId int=0,
	@rFeeStatusId int=0,
    @rBankName nvarchar(100)='',
    @rOrgIds nvarchar(max) = '',
    @rBankNames nvarchar(max) = '',
	@rFromChequeClearDate Date = '',
	@rToChequeClearDate Date = '' ,
	@rClassStatusId int=0 ,
	@rPayTypeIds nvarchar(max) = '',
	@rUserAcessUserId bigint = 0,
	@rReceiptBookIds nvarchar(max) = ''

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		R.IsObsolete AS IsCancel,   
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		R.Id AS ReceiptId,  
		R.ReceiptNumber,  
		SA.ClassId,  
		--SA.ClassName,  
		SA.DivisionId,  
		--SA.DivisionName,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		SA.RollNo,  
		SA.Code,  
		SA.Name,  
		ISNULL(PTM.Title,'') AS PayType,    
		CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		ISNULL(R.BankName,'') AS BankName,  
		R.ReceiptAmount,  
		R.ReceiptDate,  
		--CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		R.CreatedUserId,  
		ISNULL(U.LoginTitle,'') AS UserName,  
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  --Need to check
		ELSE '' END),'') AS FeeDetail,  
		R.Remark,  
		R.DiscountAmount,  
		ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		SA.OrgId,  
		SA.OrganizationName,  
		ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		@rCustomGroupId AS CustomGroupId,  
		SA.OrgGroupBatchId AS BatchId,  
		SA.BatchName,  
		R.ChequeDate,  
		R.ChequeClearDate ,
		SA.GenderId,
		ISNULL(FM.Id,0) AS FeeId,
		FM.Code AS FeeCode,  
		ISNULL(FM.Title,'') AS FeeTitle,
		FM.OrderIndex AS FeeOrderIndex,
		R.CancelStatusRemark AS CancelRemark,
		FM.FeeHeadId,
		FHM.Title AS FeeHeadName,
		RD.Amount AS DetailAmount
	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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id  

		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  

		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
	WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND (   
				(@rFeeStatusId = 0) -- All  
				OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
				OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
			)
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		 AND (ISNULL(FM.Id, 0) IN (SELECT CAST(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId = '')
		  AND (  
		  (@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 ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate >= @rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate <= @rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
  
		 ORDER BY R.ReceiptNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sFee].[pRptReceiptSummaryWithTaxGet]
	@rReportId int=0,
	@rReceiptBookId int=0,
	@rAdmissionCategoryId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rFromDate date='',
	@rToDate date='',
	@rFromReceiptNo int=0,
	@rToReceiptNo int=0,
	@rBatchId int,
	@rUserId bigint=0,
	@rBuilder1 nvarchar(max)=0,
	@rBuilder2 nvarchar(max)=0,
	@rIsDetail bit=0,
	@rIsCancel bit=0,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rStatusId int=0,
	@rPaytypeId int=0,
	@rCommonBatch nvarchar(100)='',
	@rDepartmentId int=0,
	@rFromRollNo int=0,
	@rToRollNo int=0,
	@rCode nvarchar(20),
	@rIsFilter bit=0,
	@rIsHeader bit=0,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rIsDiscount bit = 0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rCustomGroupId smallint = 0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rClassStatusId int=0,
	@rPayTypeIds nvarchar(max) = '' 
	    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsCancel AS IsCancel,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		ISNULL(PTM.Id,0) AS PayTypeId,
		ISNULL(PTM.Title,'') AS PayType,
		--ISNULL(R.ChequeNo,'') AS ChequeNo,
		 CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		ISNULL(R.BankName,'') AS BankName,
		RD.Amount AS ReceiptAmount,
		R.ReceiptDate,
		R.CreatedUserId,
		ISNULL(U.LoginTitle,'') AS UserName,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		ISNULL(RBM.OrderIndex,0) As ReceiptBookOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.BankName,'') AS ReceiptBookBank,
		ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
		R.Remark,
		SA.OrgId,
		SA.OrganizationName,
		@rCustomGroupId AS CustomGroupId,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		FHM.Title AS FeeHeadName,
		[sFee].[fDatewiseFromToReceiptNumberGet](R.ReceiptBookId,R.BatchId,R.ReceiptDate) AS FromToReceiptNumber,
		CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 1 AND ISNULL(RTD.IsTaxInclude,0) = 1
				THEN (RD.Amount - (RD.Amount * 100) / (ISNULL(R.TaxPercentage,0) + 100))
				ELSE ISNULL(RTD.TaxAmount,0) END AS DECIMAL(12, 2)) AS TaxAmount,		
		ISNULL(RTD.TaxTypeId,0) AS TaxTypeId,
		CASE WHEN ISNULL(RTD.TaxTypeId,0) = 1 THEN 'Inclusive'
			 WHEN ISNULL(RTD.TaxTypeId,0) = 2 THEN 'Exclusive'
			 ELSE '' END AS TaxType,
		ISNULL(RTD.IsTaxInclude,0) AS IsTaxInclude,
		ISNULL(R.TaxPercentage,0) AS TaxPercentage,
		CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 1 AND ISNULL(RTD.IsTaxInclude,0) = 1
				THEN (RD.Amount * 100) / (ISNULL(R.TaxPercentage,0) + 100) 
				ELSE RD.Amount END AS DECIMAL(12, 2)) AS TotalWithoutTax,
		CAST(CASE WHEN ISNULL(RTD.TaxTypeId,0) = 2
				THEN (RD.Amount + (RD.Amount * ISNULL(R.TaxPercentage,0) / 100))
				ELSE RD.Amount END AS DECIMAL(12, 2)) AS TotalWithTax

	FROM 
		sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
		INNER JOIN sFee.tReceiptTaxDetail RTD ON RD.ReceiptId = RTD.ReceiptId AND RD.FeeSetupId = RTD.FeeSetupId
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)
	WHERE
		R.SourceTypeId = 2001
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
		AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = @rIsCancel) 
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
		AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=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	((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		--AND ISNULL(RTD.TaxAmount,0) <> 0     
	ORDER BY 
		R.ReceiptNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


 
CREATE OR ALTER PROCEDURE [sFee].[pRptRoutewiseTransportFeeWithDetailGet] 
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int=0,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rRouteId int=0,
		@rDestinationId int = 0,
		@rTransportId int =0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	


--CREATE TABLE #TempStudent
--	(
--	AcademicId bigint,
--	ClassId int,
--	BatchId int,
--	a
--	)
--	SELECT AcademicId

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int 
	--)
	 
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId
		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo,
		'' AS WhatsAppContactNo --added by dhananjay for : 37272
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
			--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
		--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
		) 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 FS.Id = RD.FeeSetupId 
				INNER JOIN sfEe.tFeeMaster FM ON FM.Id = FS.FeeId 
				INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id AND FH.Number = 1001
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		INNER JOIN sTransport.tAssignRoute AR 
			ON  SA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003	
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM 
			ON BRDM.Id = AR.PickupDestinationId
	 INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
			Order by SA.RollNo

			SELECT
			P.OrgId,			 
			P.ReceiptBookId,
			P.AcademicId,
			P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,ReceiptBookTitle,OrgName,
			SUM(P.PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](P.AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			P.ReceiptOrderIndex,
			BR.Id AS BusRouteId,
			BR.Title AS BusRoute,
			BD.Title AS BusDestination,
			isnull(SC.ParentContactNo,'') AS ParentContactNo,
			P.SUID,
			P.ClassOrderIndex,
			P.DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo,
			--Added by dhananjay for mantis id Start - 35419
			ISNULL(P.PaidAmount,0) AS PaidAmount,
			--ISNULL(P.Amount,0) AS Amount	 ,
			--Added by dhananjay for mantis id End - 35419
			'' AS WhatsAppContactNo --added by dhananjay for : 37272
			--Start : add for mantis : 0040717
			,ISNULL(SC.PresentStreetOne,'') AS PresentStreetOne	
			,ISNULL(SC.PresentStreetTwo,'') AS	PresentStreetTwo
			,ISNULL(SC.PresentStreetThree,'') AS PresentStreetThree 	
			,ISNULL(SC.PresentCountry,'') AS PresentCountry	
			,ISNULL(SC.PresentState,'') AS	PresentState
			,ISNULL(SC.PresentCity,'')	AS PresentCity
			,ISNULL(SC.PresentZipCode,'') AS PresentZipCode
			--End : add for mantis : 0040717			
			FROM @p P INNER JOIN sStudent.vStudentAcademic VA ON p.AcademicId=VA.AcademicId
			INNER JOIN sTransport.tAssignRoute AR oN VA.StudentId = AR.SourceId AND SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BD ON BD.Id = AR.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id = BD.BusRouteId 
			AND BR.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =  VA.StudentId
			GROUP By P.ReceiptBookId,P.OrgId,P.AcademicId,P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,
			P.ReceiptBookTitle,P.OrgName,P.ReceiptOrderIndex,BR.Title,BD.Title,BR.Id,SC.ParentContactNo	,P.SUID,P.ClassOrderIndex,P.DivisionOrderIndex ,P.PaidAmount, --Added by dhananjay(P.PaidAmount,P.Amount) for mantis id - 35419
			p.WhatsAppContactNo, --added by dhananjay for : 37272
			SC.PresentStreetOne,SC.PresentStreetTwo,SC.PresentStreetThree,SC.PresentCountry,SC.PresentState,SC.PresentCity,SC.PresentZipCode
						
			ORDER BY P.AcademicId
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sFee].[pRptSchoolwiseChargeSummaryGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rChargeCategoryId int,
	 @rDepartmentId int,
	 @rOrgGroupId int=0,
	 @rStatusId int=0
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

 	SELECT Distinct
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.OrgGroupId,
			CM.Title AS ChargeName,
			CM.Id AS ChargeId,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			CCM.Id AS ChargeCategoryId,
			CCM.Title AS ChargeCategory,
			CM.ChargeAmount
      
	FROM 
			sFee.tChargeMaster CM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=CM.OrgGroupId
			INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.OrgId = OM.Id 
	WHERE 
			
			CM.IsObsolete=0
			AND (OM.Id=@rOrgId OR @rOrgId=0)
			AND (CM.ChargeCategoryId=@rChargeCategoryId OR @rChargeCategoryId=0)
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (CM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId=0)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptStudentCountStatusGet]  
    
		@rReportId int,  
		@rReceiptBookId int,  
		@rAdmissionCategoryId int,  
		@rClassId int,  
		@rDivisionId int,  
		@rUptoDate date,  
		@rBatchId int,  
		@rUserId bigint,  
		@rBuilder1 nvarchar(max),  
		@rBuilder2 nvarchar(max),  
		@rIsDetail bit,  
		@rOrgId int,  
		@rOrgGroupBatchId int,  
		@rIsExemption bit =0,  
		@rStatusId int,  
		@rCommonBatch nvarchar(100),  
		@rDepartmentId int,  
		@rFromRollNo int,  
		@rToRollNo int,  
		@rCode nvarchar(20),  
		@rIsFilter bit,  
		@rIsHeader bit,  
		@rCreatedUserName nvarchar(100)='',  
		@rFeeHeadId nvarchar(max) = '',  
		@rIsDisplayOrgGroup bit=0,  
		@rExemptionTypeId int=0,  
		@rFeeId nvarchar(max) = '',  
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0    
    
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN  
  
		DECLARE @rStudentCountStatus TABLE (  
			AcademicId bigint,  
			ReceiptBookId int, 
			OrgId int, 
			DepartmentId int, 
			ClassId int, 
			DivisionId int, 
			Amount decimal(12,0),  
			FAAmount decimal(12,0),  
			DiscountAmount decimal(12,0),  
			AdditionalAmount decimal(12,0),  
			NotApplicableAmount decimal(12,0),  
			PaidAmount decimal(12,0),  
			PendingAmount decimal(12,0),
			AdmissionDate Date,
			LeftDate date
		)  
   
		INSERT INTO @rStudentCountStatus  
			SELECT   
			SA.AcademicId,  
			FS.ReceiptBookId,
			SA.OrgId,
			SA.DepartmentId,
			SA.ClassId,
			SA.DivisionId,  
			ISNULL(FS.Amount,0)AS Amount,  
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,  
			ISNULL(R.PaidAmount,0) AS PaidAmount,  
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount  ,
			A.AdmissionDate,
			A.LeftDate
		FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN sStudent.tStudentAdmission A ON A.StudentId = SA.StudentId
		INNER JOIN   
		(  
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
		FROM sFee.tFeeSetup FS1  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
		WHERE   
			((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.IsOptional=0)  
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='') 
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')   
			
		UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
			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 FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))   
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
		WHERE  
			((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.IsOptional=1)  
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='') 
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')   
			) FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN  
		(  
		SELECT   
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
		FROM  
			sFee.tReceipt R   
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.ClassId=@rClassId OR @rClassId=0)   
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
		WHERE    
			(R.SourceTypeId = 2001)  
			AND (R.IsObsolete = 0)   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)  
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND (R.ReceiptDate <= @rUptoDate)  
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='') 
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
			
			AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0)) 
			  
		GROUP BY FeeSetupId,R.SourceId  
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id  
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId   
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId  
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		LEFT JOIN 
		(  
		SELECT   
			AT.SourceId   
		FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		) RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		WHERE   
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))  
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))     
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))     
			--AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
			AND ((SA.Code=@rCode) OR (@rCode=''))  
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))    
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))    
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND (  
			(@rFilterId = 0) -- All  
			OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')   			
			AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0)) 
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
			
		ORDER BY SA.RollNo  
     
     
		DECLARE @rFinalResult TABLE (     
		DivisionId int,  
		ReceiptBookId int, 
		OrgId int, 
		DepartmentId int, 
		ClassId int, 
		FullyPaid decimal(12,2),  
		FullyUnPaid decimal(12,2),  
		PartiallyPaid decimal(12,2),  
		Additional decimal(12,2),  
		Exemption decimal(12,2),  
		NA decimal(12,2)  
		)  
  
 

		INSERT INTO @rFinalResult  

		SELECT DivisionId,ReceiptBookId,OrgId,DepartmentId,ClassId,
		ISNULL((SELECT COUNT(Academicid) FROM  
		(SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)=SUM(PaidAmount)) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS FullyPaid, 

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING SUM(PaidAmount)=0  ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)  AS FullyUnPaid,  

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)<> SUM(PaidAmount)  AND SUM(PaidAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS PartiallyPaid,  

		ISNULL((SELECT COUNT(Academicid)  FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(AdditionalAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)AS Additional,  

		ISNULL((SELECT COUNT(Academicid)  FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(DiscountAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS Exemption,  

		ISNULL((SELECT COUNT(Academicid)  FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < @rUptoDate AND (LeftDate > @rUptoDate OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(NotApplicableAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS NA  
		FROM @rStudentCountStatus SCS Group By DivisionId,ReceiptBookId, OrgId,  DepartmentId, ClassId
  
		SELECT  
			@rBuilder1 AS Builder1,  
			@rBuilder2 AS Builder2,  
			@rIsDetail AS IsDetail,  
			@rIsFilter As IsFilter,  
			@rIsHeader As IsHeader,   
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
			RBM.Id AS ReceiptBookId,  
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
			OM.Id AS OrgId,  
			OM.DisplayTitle AS OrgName,  
			OM.OrderIndex AS OrgOrderIndex,  
			DM.Id AS DepartmentId,  
			DM.Title AS DepartmentName,  
			CM.Id AS ClassId,  
			CM.Title AS ClassName,  
			CM.OrderIndex AS ClassOrderIndex,  
			DivM.Id AS DivisionId,  
			DivM.Title AS DivisionName,  
			DivM.OrderIndex AS DivisionOrderIndex,  
			CM.Title+' - '+DivM.Title AS ClassDivision,  
			FR.FullyPaid,  
			FR.FullyUnPaid,  
			FR.PartiallyPaid,  
			FR.Additional,  
			FR.Exemption,  
			FR.NA  
		FROM 
			@rFinalResult FR  
			INNER JOIN sSetup.tDivisionMaster DivM ON  FR.DivisionId = DivM.Id  
			INNER JOIN sSetup.tClassMaster CM ON  CM.Id = FR.ClassId  
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = FR.DepartmentId  
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = FR.OrgId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON  RBM.Id = FR.ReceiptBookId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptStudentDepositListGet]
          
          @rOrgGroupId smallint,
		   @rOrgId int,
		   @rOrgGroupBatchId int = 0,        
           @rDepositHeadId int=0,         
           @rFromDate date='',
           @rToDate date='',        
           --@rCode nvarchar(20)='',          
           @rStudentName nvarchar(100)='',
		  @rStudentCode nvarchar(100)='',
		  @rClassId int=0,
		  @rDivisionId int=0,
		  @rIsBasedOnSUId bit = 0,
		  @rDepartmentId int=0,
		  @rSUId nvarchar(50)='',
		  @rBatchId int=0,
		  @rBuilder1 nvarchar(max)='',
	      @rBuilder2 nvarchar(max)=''
	   
           
AS
SET NOCOUNT ON
 
BEGIN
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rDepositHeadId AS DepositHeadId,
		--DHM.Title AS DepositHeadName,
		(SELECT [sFee].[fDepositHeadNameGet](@rDepositHeadId)) AS DepositHeadName,
		ISNULL(SA.StudentId,0) as StudentId,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		ISNULL(D.TotalDeposit,0) AS Deposit,
		ISNULL(A.TotalAdjustment,0) AS Adjustment,
		ISNULL(R.TotalRefund,0) Refund,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        SA.DivisionId,
		SA.DivisionOrder,
		SA.DivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,

		CASE WHEN @rIsBasedOnSUId=0 THEN SA.Code Else ISNULL(SA.suid,'') END AS SUId,
		SA.Code,
		D.DepositDate
		
  FROM 		
		sStudent.vStudentAcademic SA
		--INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
		--INNER JOIN sHostel.tRoomMaster RM ON  RM.Id=AR.RoomId 
	    --INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
		LEFT JOIN
		(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.AcademicId,ISNull(DA.DepositHeadId,0) AS DepositHeadId,DA.DepositDate As DepositDate FROM  sFee.tDepositAdd DA INNER JOIN sStudent.tAcademic A ON DA.AcademicId = A.Id  WHERE DA.DepositHeadId=@rDepositHeadId  GROUP  BY DA.AcademicId,DA.DepositHeadId,DA.DepositDate)D 
		ON D.AcademicId=SA.AcademicId
		LEFT JOIN 
		(SELECT SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.AcademicId,ISNULL(AD.DepositHeadId,0) AS DepositHeadId,AD.AdjustmentDate As AdjustmentDate FROM sFee.tDepositAdjustment AD INNER JOIN sStudent.tAcademic A ON AD.AcademicId = A.Id  WHERE AD.DepositHeadId=@rDepositHeadId GROUP BY AD.AcademicId,DepositHeadId,AD.AdjustmentDate)A 
		ON A.AcademicId=SA.AcademicId
		LEFT JOIN 
		(SELECT SUM(ISNULL(DR.RefundAmount,0)) AS TotalRefund,DR.AcademicId,ISNULL(DR.DepositHeadId,0) AS DepositHeadId,DR.RefundDate As RefundDate FROM sFee.tDepositRefund DR INNER JOIN sStudent.tAcademic A ON DR.AcademicId = A.Id  WHERE   DR.DepositHeadId=@rDepositHeadId GROUP BY DR.AcademicId,DepositHeadId,DR.RefundDate)R
		ON R.AcademicId=SA.AcademicId
		
    	--INNER JOIN  sFee.tDepositHeadMaster DHM ON DHM.Id = @rDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
  WHERE  
		(SA.OrgId=@rOrgId OR @rOrgId=0)
		
	AND(OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId=0)
	    --AND (DHM.Id=@rDepositHeadId)
	
		--AND (SA.BatchId=@rBatchId OR @rBatchId=0)
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		--AND (AR.OrgGroupBatchId=@rOrgGroupBatchId)
		AND  (SA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		 
		
		AND (
		((D.DepositDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((D.DepositDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		OR
		((A.AdjustmentDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((A.AdjustmentDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		OR
		((R.RefundDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((R.RefundDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))

		) 


		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptStudentFeeDetailsGet]
@rSourceId bigint = 0,
@rBatchId int = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN 
	SELECT 
		SA.AcademicId AS SourceId,
		SA.[Name] AS StudentName,
		SA.BatchId,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.AcademicId AS SourceIdText,
		2001 AS SourceTypeId,
		SA.ClassName,
		SA.DivisionName,
		SA.BatchName,
		SA.RollNo,
		ACM.Title AS FeeCategory,
		ISNULL(SA1.AdmissionNumber,'') AS AdmissionNumber,
		ISNULL(SA1.AdmissionDate,'') AS AdmissionDate ,
		ISNULL(SA1.AdmissionFormNumber,'') AS AdmissionFormNumber,
		--Added by dhananjay for mantis : 39497
		ISNULL(RBM.Title, '') AS ReceiptBookTitle,
		ISNULL(PTM.Title, '') AS PayType,
		PDP.PaymentClearanceDate AS ChequeDate,
		PDP.ChequeNo,
		PDP.BankName,
		PDP.Amount AS ReceiptAmount,
		ISNULL(PDP.Remark, '') AS Remark,
        ISNULL(SM.Title, '') AS StatusTitle,
		PDP.ReceiptBookId,
		PDP.PayTypeId,
		CASE WHEN PDP.SourceId IS NULL THEN 0 ELSE 1 END AS IsPDC
		--Added by dhananjay for mantis : 39497

	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN [sStudent].[tAdmissionCategoryMaster] ACM ON ACM.Id = SA.AdmissionCategoryId
		LEFT JOIN sStudent.tStudentAdmission SA1 ON SA1.StudentId = SA.StudentId
		--Added by dhananjay for mantis : 39497
		LEFT Join sFee.tPostDatePayment PDP ON PDP.SourceId = SA.AcademicId AND PDP.SourceTypeId = 2001
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PDP.PayTypeId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = PDP.StatusId
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=PDP.ReceiptBookId 
		--Added by dhananjay for mantis : 39497
	WHERE 
		SA.AcademicId = @rSourceId 		
		AND SA.BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sFee].[pRptStudentFeeHistoryGet]

	@rBuilder1 nvarchar(max),  
	@rBuilder2 nvarchar(max),
	@rOrgId int = 0,
	@rBatchId bigint = 0,
	@rFromDate date=NULL,
	@rToDate date=NULL,
	@rHistoryTypeId tinyint=null,
	@rOrgGroupBatchId int = 0,
	@rCommonBatch nvarchar(50) = '',
	@rDepartmentId int = 0,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rAdmissionCategoryId int = 0,
	@rFromRollNo int = 0,
	@rToRollNo int = 0,
	@rCode nvarchar(50) = '',
	@rFeeId nvarchar(Max) = '',
	@rReportId int = 0,
	@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		@rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,SA.AcademicId
		,(SA.FirstName + ' '+ SA.MiddleName + ' '+ SA.LastName) AS StudentName
		,ISNULL(SA.Code, '') AS StudentCode
		,FM.Code AS FeeName
		,FS.Amount AS FeeAmount
		,FAH.VariableAmount
		,FAH.DiscountAmount
		,FAH.AdditionalAmount
		,FAH.NotApplicableAmount
		,(FS.Amount + FAH.VariableAmount + FAH.AdditionalAmount - FAH.DiscountAmount - FAH.NotApplicableAmount) AS AmountAfterApply
		,FAH.Remark
		,FAH.ReferenceTypeId
		,FAH.ReferenceSourceId
		,FAH.UserId
		,U.DisplayTitle AS UserName
		,FAH.LogDateTime
		,FAH.DiscountRemark
		,FAH.AdditionalRemark
		,FAH.NotApplicableRemark
		,SA.DivisionOrder
		,SA.RollNo
	FROM sFee.tFeeAllocationHistory FAH
		INNER JOIN sStudent.vStudentAcademic SA ON FAH.SourceId=SA.AcademicId
		LEFT JOIN sFee.tFeeSetup FS ON FS.Id=FAH.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSecurity.tUser U ON U.Id=FAH.UserId
	WHERE 
		(SA.OrgId = @rOrgId OR @rOrgId = 0)
		AND (SA.BatchId = @rBatchId OR @rBatchId = 0)
		AND ((CAST(FAH.LogDateTime AS DATE) >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((CAST(FAH.LogDateTime AS DATE) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		AND ((ISNULL(FAH.HistoryTypeId,1) = @rHistoryTypeId) OR (ISNULL(@rHistoryTypeId, 0) = 0))
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = '')) 
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	ORDER BY FAH.LogDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sFee].[pRptStudentFeeRefundDetailsGet]
@rSourceIdText nvarchar(50) = '',
@rBatchId int = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN 
	SELECT 
		R.ReceiptNumber,
		RR.RefundDate,
		RR.RefundAmount,
		ISNULL(RR.ChequeNo,'') AS ChequeNumber,
		ISNULL(RR.BankName,'') AS BankName, 
		RBM.Title AS ReceiptBook,
		PTM.Title AS PayType,
		RR.SourceId,
		RR.BatchId,
		@rSourceIdText AS SourceIdText
	FROM 
		sFee.tReceiptRefund RR  
		INNER JOIN sFee.tReceipt R ON RR.ReceiptId = R.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = R.ReceiptBookId  
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = RR.PayTypeId  
	WHERE 
		RR.SourceId = @rSourceIdText 
		AND RR.SourceTypeId = 2001 
		AND RR.BatchId = @rBatchId 
		AND RR.IsObsolete = 0

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pRptStudentLedgerGet]

	 @rAcademicId bigint,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rDepositHeadId int,
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rBatchId int
AS
BEGIN
WITH Tb0 as
( 
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
			0 AS Debit,
			VA.Code As Code,
			VA.Name As StudentName,
			VA.AcademicId AS AcademicId,
			VA.ClassName + ' ' + VA.DivisionName AS Class,
			CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
			DA.CreatedDateTime,
			'' AS ExpenseType,
			VA.RollNo,
			SA.AdmissionNumber,	
			CASE WHEN DA.ReferenceSourceTypeId = 1021 THEN [sFee].[fnGetStockDepositeAdd] (DA.ReferenceSourceId)
			ELSE '' END AS StockItemNameQuantity, --add for mantis : 0035191
			(CASE WHEN DA.ReferenceSourceTypeId=1021 THEN 'Stock Return' ELSE 'Deposit Add' END) AS DepositType,		--add for mantis: 35522
			ISNULL(PT.Title, '') AS PayType, --Added for mantis : 0036944
			ISNULL(DA.Remark,'') AS Remark -- Mantis Id : 0036944
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			INNER JOIN sFinanceCommon.tPayTypeMaster AS PT ON DA.PayTypeId = PT.Id

			Where 
		   ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.DepositHeadId = @rDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
		    --AND VA.BatchId = @rBatchId
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		    DAJ. CreatedDateTime,
			ISNULL(ETM.Title,'')AS ExpenseType,
			VA.RollNo,
			SA.AdmissionNumber,
			CASE WHEN DAJ.ReferenceSourceTypeId = 2039 THEN [sFee].[fnGetStockDepositeAdjustment] (DAJ.ReferenceSourceId)
			ELSE '' END AS StockItemNameQuantity, --add for mantis : 0035191
			'' AS DepositType,	--add for mantis: 35522
			'' AS PayType, --Added for mantis : 36944
			ISNULL(DAJ.Remark,'') AS Remark -- Mantis Id : 0036944
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId
			  INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
		  -- AND VA.BatchId = @rBatchId
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		    DR.CreatedDateTime,
		     '' AS ExpenseType,
			 VA.RollNo,
			 SA.AdmissionNumber,
			 '' AS StockItemNameQuantity,
			 '' AS DepositType,		--add for mantis: 35522
			 '' AS PayType, --Added for mantis : 36944
			 ISNULL(DR.Remark,'') AS Remark -- Mantis Id : 0036944
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			  INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			--AND VA.BatchId = @rBatchId
)
,Tb1 as
( 
	SELECT DepositDate,Credit,Debit,Row_Number() over (order by CreatedDateTime asc) as OrderId,AcademicId,Code,SUId,StudentName,Class ,CreatedDateTime,ExpenseType,RollNo,AdmissionNumber,StockItemNameQuantity,DepositType,PayType,Remark FROM Tb0	--add DepositType for mantis: 35522, Added PayType & Remark for mantis : 36944
)

--SELECT * FROM Tb1

  SELECT T1.DepositDate,
         T1.[Credit],
         T1.[Debit],(Sum(T2.Credit) - Sum(T2.Debit)) as Balance,
         T1.SUId,
         T1.Code,
         T1.StudentName,
         T1.Class,
        T1.CreatedDateTime,
        T1.ExpenseType,
		T1.RollNo,
		T1.AdmissionNumber,
		@rIsBasedOnSUId AS BasedOnSUID,
		T1.StockItemNameQuantity,
		T1.DepositType,		--add for mantis: 35522
		T1.PayType, --Added for mantis : 36944
		T1.Remark

		 FROM Tb1 as T1
		 INNER JOIN Tb1 as T2 ON T1.OrderId >= T2.OrderId
		 Group By T1.DepositDate,T1.Credit,T1.Debit,T1.AcademicId,T1.SUId,T1.Code,T1.StudentName,T1.Class,T1.CreatedDateTime,T1.ExpenseType,T1.RollNo,T1.AdmissionNumber,T1.StockItemNameQuantity,T1.DepositType,T1.PayType,T1.Remark		--add T1.DepositType for mantis: 35522, Added PayType for mantis : 36944
		 Order by T1.CreatedDateTime 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptStudentOptionalFeeListGet]	 
		@rClassId int = 0,
		@rDivisionId int = 0,
		@rAdmissionCategoryId int = 0,		
		@rBatchId int = 0,
		@rOrgId int = 0,
		@rReceiptBookId int = 0,
		@rDepartmentId int = 0,
		@rOrgGroupBatchId int = 0,
		@rCommonBatch nvarchar(100)='', --nvarchar for mantis : 0044148
		@rFeeId nvarchar(max) = '',
		@rFromRollNo int = 0,
		@rToRollNo int = 0,
		@rFilterId int = 0,
		@rOrgGroupId int = 0,
		@rCode nvarchar(20) = '',
		@rReportId int = 0,
		@rIsDisplayOrgGroup bit = 0,
		@rIsFilter bit = 0,  
		@rBuilder1 nvarchar(max) = '',  
		@rBuilder2 nvarchar(max) = '',
		@rFeeHeadId int = 0

		WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			@rIsFilter AS IsFilter,
			@rBuilder1 AS Builder1,  
			@rBuilder2 AS Builder2,  
			SA.AcademicId,
			SA.Code,
			SA.Name,
			SA.RollNo,
			SA.ClassName,
			SA.DivisionName,
			ISNULL(FO.FeeSetupId,0) AS FeeSetupId,			
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			--Added by dhananjay mantis : 42689	
			SA.ClassOrderIndex,
			SA.DivisionOrder
			--Added by dhananjay mantis : 42689
	FROM 
		sFee.tFeeOptional FO
		INNER JOIN sStudent.vStudentAcademic SA ON FO.SourceId=SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FO.FeeSetupId AND FO.SourceTypeId=2001
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FO.BatchId AND SA.BatchId = BM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId	
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) 
		AND (SA.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 = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)
	WHERE 
		(RBM.OrgGroupId = @rOrgGroupId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId = 0))		
		AND ((BM.Id=@rBatchId) OR (@rBatchId = 0))
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))		
		AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))	
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))	
		AND ((OGBM.Id = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		--AND ((OGBM.CommonOrgGroupBatchId = @rCommonBatch) OR (@rCommonBatch = 0)) --comment for mantis : 0044148
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))--add for mantis : 0044148
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo = 0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo = 0))		
		AND (ISNULL(FS.FeeId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId='')
		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 ((SA.Code = @rCode) OR (@rCode = ''))
		ORDER BY SA.AcademicId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pRptStudentWiseAllFeeDetailGet]
	 
		@rReceiptId bigint
		--@lSourceId bigint ,
		--@lSourceTypeId int,
		--@lBatchId int
		--@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	--if (@rStudentId <> 0)
	--SELECT @lSourceId = Id, @lSourceTypeId = 2001 FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @lBatchId
		DECLARE @lSourceId bigint,@lSourceTypeId int,@lBatchId int

		SELECT @lSourceId = SourceId, @lSourceTypeId = SourceTypeId, @lBatchId = BatchId FROM sFee.tReceipt WHERE Id = @rReceiptId

		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		-- Added
		DECLARE @lExemptionTypeId int = 0
		DECLARE @lExemptionType nvarchar(100) = ''
		
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId, @lExemptionTypeId = ExemptionTypeId FROM sStudent.vStudentAcademic WHERE AcademicId=@lSourceId
		
		-- Added
		SELECT @lExemptionType = Title FROM [sFee].[tExemptionTypeMaster] WHERE Id = @lExemptionTypeId
SELECT 
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount
			
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				ISNULL(FS1.FeeDuration,'')  AS FeeDuration
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @lBatchId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
				ISNULL(FS1.FeeDuration,'') AS FeeDuration
				 
			FROM sFee.tFeeSetup FS1
			 
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lSourceId) AND(FO.SourceTypeId=@lSourceTypeId)
			WHERE
			 FS1.BatchId = @lBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lSourceId) AND(FA.SourceTypeId=@lSourceTypeId)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @lSourceId
			AND ((R.SourceTypeId = @lSourceTypeId) OR (@lSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @lBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@lBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sFee].[pRptStudentWiseFeeDetailGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN

WITH FeeData AS --added by dhananjay for mantis id - 36359
(
	SELECT 
			SA.Id AS AcademicId,
			SA.RollNo,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			SM.Code,
			CM.DisplayTitle AS ClassName,
			DM.DisplayTitle AS DivisionName,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			SUM(ISNULL(FS.Amount,0)+ISNULL(FA.VariableAmount,0)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00))AS Amount,
			ISNULL(SUM(R.PaidAmount),0) AS PaidAmount,
			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,
			O.DisplayTitle AS OrgName,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			BM.Title AS BatchName,
			TR.ReceiptNumber,
			TR.ReceiptId AS ReceiptId,  
			TR.PayType,  
			TR.ChequeNo,
			TR.BankName,  
			TR.ReceiptAmount,
			TR.ReceiptDate,  
			TR.FeeDetail,
			TR.ReceiptBookTitle,
			TR.ChequeDate,  --added by dhananjay for mantis id - 0035384
			ROW_NUMBER() OVER (PARTITION BY SA.Id, FHM.Id ORDER BY SA.Id) AS RowNum --added by dhananjay for mantis id - 36359
	  FROM 
			sStudent.tAcademic SA
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.Id AS AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
					UNION ALL
					
				SELECT 
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.Id AS AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
					INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA1.BatchId = BM.Id
					AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
						AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
						AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=1)
					AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.Id
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					INNER JOIN sSetup.tBatchMaster BM ON SA1.BatchId = BM.Id
				WHERE	
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')   
					GROUP BY RD.FeeSetupId ,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
			  LEFT JOIN
				(
					SELECT 
						 R.SourceId
						,R.Id AS ReceiptId,  
						R.ReceiptNumber,  
						PTM.Title AS PayType,  
						CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
						R.BankName,  
						ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,
						R.ReceiptDate,  
						(STUFF((SELECT  ','+FM.Title FROM sFee.tReceiptDetail RD INNER JOIN sFee.tFeeSetup FS ON FS.Id=RD.FeeSetupId INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId WHERE RD.ReceiptId = R.Id FOR XML PATH('')), 1, 1,NULL)) as FeeDetail,
						ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
						ISNULL(RBM.Title,'') AS ReceiptBookTitle,
						R.ChequeDate --added by dhananjay for mantis id - 0035384
					FROM
							sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
						ON PTM.Id=R.PayTypeId  
						INNER JOIN sFee.tReceiptBookMaster RBM   
						ON RBM.Id=R.ReceiptBookId  
						AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
						AND (SA1.ClassId=@rClassId OR @rClassId=0) 
						AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					WHERE		
						(R.SourceTypeId = 2001)
					    AND (R.IsObsolete = 0) 
					    AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					    AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					    AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					    AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					    AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
					    AND (R.ReceiptDate <= @rUptoDate)
					    AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					    AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					    AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					    AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
					GROUP BY  R.SourceId,R.Id,R.ReceiptNumber,PTM.Title,R.ChequeNo,R.PaymentTransactionId,R.BankName,R.ReceiptDate,R.ReceiptBookId,RBM.Title,R.ChequeDate--added (R.ChequeDate) by dhananjay for mantis id - 0035384
				) TR ON SA.Id = TR.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
				(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
				ON RT.SourceId = SA.StudentId AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
				((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
				AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
				AND	((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
				AND (SM.StatusId=@rStatusId OR @rStatusId=0)
				--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
				AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
				AND ((SM.Code=@rCode) OR (@rCode=''))
				AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
				AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
				AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	 	
		Group BY SA.Id,SA.RollNo,SM.FirstName+' '+SM.MiddleName+' '+SM.LastName,SM.Code,CM.DisplayTitle,DM.DisplayTitle,O.DisplayTitle,FHM.Id,FHM.Title,BM.Title,TR.ReceiptNumber,
				 TR.ReceiptId,TR.PayType,TR.ChequeNo,TR.BankName,TR.ReceiptAmount,TR.ReceiptDate,TR.FeeDetail,TR.ReceiptBookTitle,TR.ChequeDate--added (R.ChequeDate)by dhananjay for mantis id - 0035384
		--Order by SA.RollNo (--Commented by dhananjay for mantis id - 36359)

)
--added by dhananjay for mantis id - 36359
SELECT
	AcademicId,
			RollNo,
			Name,
			Code,
			ClassName,
			DivisionName,
			ClassDivision,
			CASE WHEN RowNum = 1 THEN Amount ELSE 0 END AS Amount,
			CASE WHEN RowNum = 1 THEN PaidAmount ELSE 0 END AS PaidAmount,
			CASE WHEN RowNum = 1 THEN PendingAmount ELSE 0 END AS PendingAmount,
			OrgName,
			FeeHeadId,
			FeeHeadName,
			BatchName,
			ReceiptNumber,
			ReceiptId AS ReceiptId,  
			PayType,  
			ChequeNo,
			BankName,  
			ReceiptAmount,
			ReceiptDate,  
			FeeDetail,
			ReceiptBookTitle,
			ChequeDate

			FROM

			FeeData

			Order by RollNo
			--added by dhananjay for mantis id - 36359
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptSummaryFeeStatusGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	--@rFromRollNo int,
 --   @rToRollNo int,
   -- @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	
	  @rCollectionGroupId int =0 ,    
	  @rIsReceiptBook bit=0,
	  @rIsOrganization bit=0,
	  @rIsDepartment bit=0,
	  @rIsClass bit=0,
	  @rIsDivision bit=0,
	    @rReportType int=0,
		  @rClassStatusId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

IF(@rReportType=1)
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		--SA.AcademicId,
		--SA.RollNo,
		--SA.Name,
		--SA.Code,
		
		
		SA.DivisionOrder AS DivisionOrderIndex,
		
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,		
		
		FS.FeeName,
		
	
	
	
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		SA.OrgGroupBatchId AS BatchId,
		SA.BatchName AS BatchName,
		
		
          @rIsReceiptBook AS IsReceiptBook,
		  @rIsOrganization AS IsOrganization,
		  @rIsDepartment AS IsDepartment,
		  @rIsClass AS IsClass,
		  @rIsDivision AS IsDivision,
		 
		
		 -- Receipt Book
		 ISNULL(FS.ReceiptBookId,'0') As ReceiptBookId,  
		 ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		 ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex ,
		  -- Receipt Book
         
          -- Org
		  SA.OrgId,  
		  O.Title AS OrgName,  
		  O.OrderIndex AS OrgOrderIndex, 
		  -- Org
		  
		   -- Department
		 SA.DepartmentId,
		 SA.DepartmentName,
		  -- Department
		  
		  -- Class
		  SA.ClassId,  
		  SA.ClassName,  
		  SA.ClassOrderIndex ,  
		  -- Class
		  
		   --Division 
		  SA.DivisionId,  
		  SA.DivisionName, 
		  --Division
		  
		  --Amount
		  
		  ISNULL(R.PaidAmount,0) AS PaidAmount
		  --Amount
  
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			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 FS1.BatchId = SA1.BatchId
		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		WHERE
			((FS1.ClassId=@rClassId) OR (@rClassId=0))
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND (FS1.IsOptional=1)
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=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 
				INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				--AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 --INNER JOIN sSetup.tDepartmentMaster DM  ON SA.DepartmentId=DM.Id  
		 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		WHERE	
		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		--AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
	AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	AND (tSA.AdmissionDate <= @rUptoDate)
	AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	Order by SA.RollNo 
	--GROUP BY 
	--FS.Id,ISNULL(FS.IsVariable,0),ISNULL(FS.Amount,0),ISNULL(FS.StartDate,'1900-01-01'),ISNULL(FS.EndDate,'1900-01-01'),ISNULL(FA.VariableAmount,0.00),ISNULL(FA.DiscountAmount,0.00),ISNULL(FA.AdditionalAmount,0.00),ISNULL(FA.NotApplicableAmount,0.00),ISNULL(FA.Remark,''),FS.FeeName,ExemptionTypeId,	SA.ExemptionTypeId,
	--	ISNULL(ETM.Title,''),
	--	FHM.Id,
	--	FHM.Title,
	--	FHM.OrderIndex,
		
	--	SA.OrgGroupBatchId,
	--	SA.BatchName,
	--FS.ReceiptBookId,RBM.Title,RBM.OrderIndex,RBM.OrderIndex,SA.OrgId,O.Title,O.OrderIndex,SA.DepartmentId,SA.DepartmentName,
 --   SA.ClassId,SA.ClassName,SA.ClassOrderIndex,SA.DivisionId,SA.DivisionName,SA.DivisionOrder,ISNULL(R.PaidAmount,0)
    
	
	
	 
	--Order by SA.RollNo
	
				
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
ELSE
BEGIN
SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,		
		SA.DivisionOrder AS DivisionOrderIndex,		
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FM.Title AS FeeName,	
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00)AS PendingAmount,		
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		SA.OrgGroupBatchId AS BatchId,
		SA.BatchName AS BatchName,		
		
          @rIsReceiptBook AS IsReceiptBook,
		  @rIsOrganization AS IsOrganization,
		  @rIsDepartment AS IsDepartment,
		  @rIsClass AS IsClass,
		  @rIsDivision AS IsDivision,	 
		
		 -- Receipt Book
		 ISNULL(FS.ReceiptBookId,'0') As ReceiptBookId,  
		 ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		 ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex ,
		  -- Receipt Book
         
          -- Org
		  SA.OrgId,  
		  O.Title AS OrgName,  
		  O.OrderIndex AS OrgOrderIndex, 	
		  
		   -- Department
		 SA.DepartmentId,
		 SA.DepartmentName,	
		  -- Class
		  SA.ClassId,  
		  SA.ClassName,  
		  SA.ClassOrderIndex , 
		  		 
		   --Division 
		  SA.DivisionId,  
		  SA.DivisionName 
		
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = 0) OR (0 = 0))  AND ((AR.OrgGroupBatchId = 0) OR (0 = 0)) 
        LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = 0) OR (0 = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = 0) OR (0 = 0)) 
		WHERE	
		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FAS.DiscountAmount,0) > 0))
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)		
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
	AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	AND (tSA.AdmissionDate <= @rUptoDate)
	AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	Order by SA.RollNo 
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptSummaryPaidFeeGet]  
  @rReportId int,  
  @rReceiptBookId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rUptoDate date,  
  --@rToDate date,  
  --@rFromReceiptNo int,  
  --@rToReceiptNo int,  
  @rBatchId int,  
  @rUserId bigint,  
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max),  
  @rIsCancel bit,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int,  
  @rCommonBatch nvarchar(100),  
  @rDepartmentId int,  
  --@rFromRollNo int,  
  --@rToRollNo int,  
  --@rCode nvarchar(20),  
  @rIsDetail bit=0,  
  @rIsFilter bit,  
  @rIsHeader bit,  
  @rCreatedUserName nvarchar(100)='',  
  @rFeeHeadId nvarchar(max) = '',  
  @rIsDisplayOrgGroup bit=0,  
  @rPayTypeId int=0,  
  @rFeeId nvarchar(max) = '',  
  @rFilterId int=0,
  @rOrgIds nvarchar(max) = ''  ,
  
  @rCollectionGroupId int =0 ,    
  @rIsReceiptBook bit=0,
  @rIsOrganization bit=0,
  @rIsDepartment bit=0,
  @rIsClass bit=0,
  @rIsDivision bit=0,
  
  @rIsCollectionGroup bit=0,
  @rIsFeeHead bit=0,
  @rIsFeeMaster bit=0,
  @rIsPayType bit=0,
  @rIsUser bit=0,
  @rReportType int=0,
  @rClassStatusId int=0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN    
 SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  

  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  

  R.ChequeNo,  
  R.BankName,  
 
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  
  
  @rIsReceiptBook AS IsReceiptBook,
  @rIsOrganization AS IsOrganization,
  @rIsDepartment AS IsDepartment,
  @rIsClass AS IsClass,
  @rIsDivision AS IsDivision,
  @rIsCollectionGroup AS IsCollectionGroup,
  @rIsFeeHead AS IsFeeHead,
  @rIsFeeMaster AS IsFeeMaster,
  @rIsPayType AS IsPayType,
  @rIsUser AS IsUser,

  ISNULL(R.Remark,'') AS Remark,  


  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  
  -- Receipt Book
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex, 
  -- Receipt Book
  
  -- Org
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  -- Org
  
  -- Department
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  -- Department
  
  -- Class
  SA.ClassId,  
  SA.ClassName,  
  SA.ClassOrderIndex,    
  -- Class
   
  --Division 
  SA.DivisionId,  
  SA.DivisionName,  
  SA.DivisionOrder,
  --Division
  
   --Paytype
   PTM.Id AS PayTypeId,
   PTM.Title AS PayType,
   --Paytype
   
    --User
   U.Id AS UserId,
   U.DisplayTitle AS UserTitle,
   --User   
  
  
  	-- Collection Group
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroupName,
		ISNULL(CGM.OrderIndex,'') AS CollectionGroupOrderIndex,
  
  
  -- Fee Head	
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,   
   -- Fee Head
   
   -- Fee
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
   -- Fee 
   
  
   RD.Amount AS ReceiptAmount    
    
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId 
  LEFT JOIN sFee.tCollectionGroupMaster CGM
			ON FS.CollectionGroupId=CGM.Id	
      
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId  
  LEFT JOIN sSecurity.tUser U  
   ON U.Id=R.CreatedUserId  
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 --AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 --AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 --AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 --AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = '')) 
 AND ((R.ReceiptDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = '')) 
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
-- AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 --AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 --AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
 AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
 AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
 ORDER BY R.ReceiptNumber  
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptSummaryPendingFeeGet]
		
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
	    @rOrgIds  nvarchar(max) = '',
	    @rPayDate date='',
	    @rCollectionGroupId int =0 ,
	    
	    @rIsReceiptBook bit=0,
	    @rIsOrganization bit=0,
	    @rIsDepartment bit=0,
	    @rIsClass bit=0,
	    @rIsDivision bit=0,
	    @rIsCollectionGroup bit=0,
	    @rIsFeeHead bit=0,
	    @rIsFeeMaster bit=0,
	    @rReportType int=0,
		@rClassStatusId int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

IF(@rReportType=1)
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		
		@rIsReceiptBook AS IsReceiptBook,
	    @rIsOrganization AS IsOrganization,
	    @rIsDepartment AS IsDepartment,
	    @rIsClass AS IsClass,
	    @rIsDivision AS IsDivision,
	    @rIsCollectionGroup AS IsCollectionGroup,
	    @rIsFeeHead AS IsFeeHead,
	    @rIsFeeMaster AS IsFeeMaster,
	    
		
		
		
		-- Receipt Book
		FS.ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		
		-- Org
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		
		-- Department
		SA.DepartmentId,
		SA.DepartmentName,
		
		-- Class
		SA.ClassId,
		SA.ClassName,
		SA.ClassOrderIndex,
		
		-- Division
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		
		-- Collection Group
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroupName,
		ISNULL(CGM.OrderIndex,'') AS CollectionGroupOrderIndex,
		
		-- Fee Head
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		
		-- Fee
		FS.FeeId,
		FS.FeeName,
		FS.FeeOrderIndex,
		
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount
  FROM 
  
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			
			WHERE 
			    BM.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				AND (FS1.IsOptional=0)
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex			 			 
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016
				-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON	
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sFee.tCollectionGroupMaster CGM
			ON FS.CollectionGroupId=CGM.Id	
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO 
			ON SO.StudentId = SA.StudentId
		 INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
      LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))	    
			GROUP BY 
			FS.ReceiptBookId,RBM.Title,RBM.OrderIndex,RBM.OrderIndex,SA.OrgId,O.Title,O.OrderIndex,SA.DepartmentId,SA.DepartmentName,
		    SA.ClassId,SA.ClassName,SA.ClassOrderIndex,SA.DivisionId,SA.DivisionName,SA.DivisionOrder,CGM.Id,CGM.Title,CGM.OrderIndex,
		    FHM.Id,FHM.Title,FHM.OrderIndex,FeeId,FeeName,FeeOrderIndex
END
ELSE
BEGIN
SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		
		@rIsReceiptBook AS IsReceiptBook,
	    @rIsOrganization AS IsOrganization,
	    @rIsDepartment AS IsDepartment,
	    @rIsClass AS IsClass,
	    @rIsDivision AS IsDivision,
	    @rIsCollectionGroup AS IsCollectionGroup,
	    @rIsFeeHead AS IsFeeHead,
	    @rIsFeeMaster AS IsFeeMaster,
	    
		
		
		
		-- Receipt Book
		FS.ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		
		-- Org
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		
		-- Department
		SA.DepartmentId,
		SA.DepartmentName,
		
		-- Class
		SA.ClassId,
		SA.ClassName,
		SA.ClassOrderIndex,
		
		-- Division
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		
		-- Collection Group
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroupName,
		ISNULL(CGM.OrderIndex,'') AS CollectionGroupOrderIndex,
		
		-- Fee Head
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		
		-- Fee
		FS.FeeId,
		--FS.FeeName,
		FM.Title AS FeeName,
		--FS.FeeOrderIndex,
		FM.OrderIndex AS FeeOrderIndex,
		SUM(ISNULL(SF.PendingAmount,0.00)) PendingAmount
		
		--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 sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
		INNER JOIN [sFee].[tStudentFee] SF ON SF.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=SF.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId		
		 LEFT JOIN sFee.tCollectionGroupMaster CGM	ON FS.CollectionGroupId=CGM.Id	
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId		 	
	  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
      LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND ISNULL(SF.PendingAmount,0.00) <> 0
			 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))	     
			GROUP BY 
			FS.ReceiptBookId,RBM.Title,RBM.OrderIndex,RBM.OrderIndex,SA.OrgId,O.Title,O.OrderIndex,SA.DepartmentId,SA.DepartmentName,
		    SA.ClassId,SA.ClassName,SA.ClassOrderIndex,SA.DivisionId,SA.DivisionName,SA.DivisionOrder,CGM.Id,CGM.Title,CGM.OrderIndex,
		    FHM.Id,FHM.Title,FHM.OrderIndex,FeeId,FM.Title,FM.OrderIndex
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pRptTotalDepositTransaction] 

	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
	 @rOrgGroupBatchId int = 0,
     @rBatchId int,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
     @rFromDate date='',
     @rToDate date='',
	 @rIsBasedOnSUId bit = 0
	 
AS
BEGIN	
	
	SELECT 
	   A.Code,
	   A.StudentId,
	   A.StudentName,
	   A.Class,
	   SUM(ISNULL(A.DepositeAmount,0)) AS TotalDeposite,
	   SUM(ISNULL(A.AdjustmentAmount,0)) AS AdjustmentAmount,
	   A.FeeDepositExpenseTypeId,
	   A.ExpenseType,
	   SUM(ISNULL(A.DepositeAmount,0)) - SUM(ISNULL(A.AdjustmentAmount,0))-SUM(ISNULL(A.RefundAmount,0)) RemainingAmount,
	   SUM(ISNULL(A.RefundAmount,0)) AS RefundAmount
	FROM
	   (
		SELECT 
		    VA.Code As Code,
			VA.StudentId AS StudentId,
		    VA.Name As StudentName,
		    VA.ClassName + ' - ' + VA.DivisionName AS Class,
			ISNULL(DA.Amount,0) AS DepositeAmount,
			0 AS AdjustmentAmount,
			0 AS FeeDepositExpenseTypeId,
			'Deposit' AS ExpenseType,
			0 As RefundAmount
		FROM sStudent.vStudentAcademic  VA
			LEFT JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
		Where 
		    ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DA.DepositHeadId = @rDepositHeadId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((VA.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((DA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			--AND ((convert(date,DA.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    --AND ((convert(date,DA.CreatedDateTime)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
			AND ((convert(date,DA.DepositDate)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    AND ((convert(date,DA.DepositDate)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
		
		UNION ALL

		SELECT 
		    VA.Code As Code,
			VA.StudentId AS StudentId,
		    VA.Name As StudentName,
		    VA.ClassName + ' - ' + VA.DivisionName AS Class,
			0 AS DepositeAmount,
			ISNULL(DAJ.Amount,0) AS AdjustmentAmount,
			DAJ.FeeDepositExpenseTypeId,
			DETM.Title as ExpenseType,
			0 As RefundAmount
		FROM sStudent.vStudentAcademic  VA
			LEFT JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			LEFT JOIN sFee.tFeeDepositExpenseTypeMaster DETM ON DETM.Id = DAJ.FeeDepositExpenseTypeId
		Where 
		    ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DAJ.DepositHeadId = @rDepositHeadId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((VA.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((DAJ.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			--AND ((convert(date,DAJ.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    --AND ((convert(date,DAJ.CreatedDateTime)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
			AND ((convert(date,DAJ.AdjustmentDate)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    AND ((convert(date,DAJ.AdjustmentDate)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
		

		UNION ALL

		SELECT 
		    VA.Code As Code,
			VA.StudentId AS StudentId,
		    VA.Name As StudentName,
		    VA.ClassName + ' - ' + VA.DivisionName AS Class,
			0 AS DepositeAmount,
			0 AS AdjustmentAmount,
			'' AS FeeDepositExpenseTypeId,
			'Refund' as ExpenseType,
			ISNULL(DR.RefundAmount,0) As RefundAmount
		FROM sStudent.vStudentAcademic  VA
			LEFT JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId 
		Where 
		    ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DR.DepositHeadId = @rDepositHeadId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((VA.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((DR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			--AND ((convert(date,DR.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    --AND ((convert(date,DR.CreatedDateTime)<=@rToDate) OR (ISNUll(@rToDate,'')='')
			AND ((convert(date,DR.RefundDate)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    AND ((convert(date,DR.RefundDate)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
		
	) A
	Group By A.Code,A.StudentId,A.StudentName,A.Class,A.FeeDepositExpenseTypeId,A.ExpenseType

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pRptTransportFeePendingWithFeeNameGet]
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int=0,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rRouteId int=0,
		@rDestinationId int = 0,
		@rTransportId int =0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	


--CREATE TABLE #TempStudent
--	(
--	AcademicId bigint,
--	ClassId int,
--	BatchId int,
--	a
--	)
--	SELECT AcademicId

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int 
	--)
	 
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId
		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo,
		'' AS WhatsAppContactNo --added by dhananjay for : 37272
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
			--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
		--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
		) 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 FS.Id = RD.FeeSetupId 
				INNER JOIN sfEe.tFeeMaster FM ON FM.Id = FS.FeeId 
				INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id AND FH.Number = 1001
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		INNER JOIN sTransport.tAssignRoute AR 
			ON  SA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003	
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM 
			ON BRDM.Id = AR.PickupDestinationId
	 INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
			Order by SA.RollNo

			SELECT
			P.OrgId,			 
			P.ReceiptBookId,
			P.AcademicId,
			P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,ReceiptBookTitle,OrgName,
			SUM(P.PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](P.AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			P.ReceiptOrderIndex,
			BR.Id AS BusRouteId,
			BR.Title AS BusRoute,
			BD.Title AS BusDestination,
			isnull(SC.ParentContactNo,'') AS ParentContactNo,
			P.SUID,
			P.ClassOrderIndex,
			P.DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo,
			'' AS WhatsAppContactNo --added by dhananjay for : 37272
			
			FROM @p P INNER JOIN sStudent.vStudentAcademic VA ON p.AcademicId=VA.AcademicId
			INNER JOIN sTransport.tAssignRoute AR oN VA.StudentId = AR.SourceId AND SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BD ON BD.Id = AR.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id = BD.BusRouteId 
			AND BR.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =  VA.StudentId
			GROUP By P.ReceiptBookId,P.OrgId,P.AcademicId,P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,
			P.ReceiptBookTitle,P.OrgName,P.ReceiptOrderIndex,BR.Title,BD.Title,BR.Id,SC.ParentContactNo	,P.SUID,P.ClassOrderIndex,P.DivisionOrderIndex
			ORDER BY P.AcademicId
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pSetOptionalFeeAdd]
	@rOrgId int,
    @rFeeMainGroupId int,
	@rDetail nvarchar(max) 
	
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rDetail=REPLACE(@rDetail,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	 BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rDetail
	Delete from sFee.tFeeMainGroupOptionalFee where FeeMainGroupid=@rFeeMainGroupId and	OrgId=@rOrgId	
	
	 INSERT INTO sFee.tFeeMainGroupOptionalFee
		(
			OrgId,FeeMainGroupId,FeeId
		)
		Select 
			@rOrgId,
			@rFeeMainGroupId,
			A.FeeId
		from OPENXML (@intDoc, '/Table/ResultMaster', 1)
		WITH
		(
			FeeId int '@FeeId'
		)A
		
		EXEC sp_xml_removedocument @intDoc
		SELECT 1 AS Result
		COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pStudentCountStatusDashBoardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rReceiptBookId int=0,
	 @rFeeHeadId int=0,
	 @rPayTypeId int =0,
	 @rDivisionId int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @rStudentCountStatus TABLE (  
			AcademicId bigint,  
			ReceiptBookId int,
			OrgName nvarchar(30), 
			OrgId int, 
			DepartmentId int, 
			ClassId int, 
			DivisionId int, 
			Amount decimal(12,0),  
			FAAmount decimal(12,0),  
			DiscountAmount decimal(12,0),  
			AdditionalAmount decimal(12,0),  
			NotApplicableAmount decimal(12,0),  
			PaidAmount decimal(12,0),  
			PendingAmount decimal(12,0),
			AdmissionDate Date,
			LeftDate date
		)  
   
		INSERT INTO @rStudentCountStatus  
			SELECT   
			SA.AcademicId,  
			FS.ReceiptBookId,
			SA.OrganizationName,
			SA.OrgId,
			SA.DepartmentId,
			SA.ClassId,
			SA.DivisionId,  
			ISNULL(FS.Amount,0)AS Amount,  
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,  
			ISNULL(R.PaidAmount,0) AS PaidAmount,  
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount  ,
			A.AdmissionDate,
			A.LeftDate
		FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN sStudent.tStudentAdmission A ON A.StudentId = SA.StudentId
		INNER JOIN   
		(  
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
		FROM sFee.tFeeSetup FS1  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=0) OR (0=0))  
			AND ((SA1.AdmissionCategoryId=0) OR (0=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
		WHERE   
			((FS1.ClassId=0) OR (0=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=0) OR (0=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.IsOptional=0)  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			
		UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
			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 FS1.BatchId = SA1.BatchId  
			AND ((SA1.ClassId=0) OR (0=0))   
			AND ((SA1.AdmissionCategoryId=0) OR (0=0))  
		WHERE  
			((FS1.ClassId=0) OR (0=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=0) OR (0=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (0=0))  
			AND (FS1.IsOptional=1)  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			) FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN  
		(  
		SELECT   
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
		FROM  
			sFee.tReceipt R   
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.ClassId=0 OR 0=0)   
			AND (SA1.DivisionId=0 OR 0=0)  
		WHERE    
			(R.SourceTypeId = 2001)  
			AND (R.IsObsolete = 0)   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)  
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
			AND ((SA1.BatchName = '') OR ('' = ''))  
			AND (R.ReceiptDate <= getdate())  
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
		GROUP BY FeeSetupId,R.SourceId  
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id  
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId   
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId  
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = 110100101) OR (110100101 = 0))   
		LEFT JOIN 
		(  
		SELECT   
			AT.SourceId   
		FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		) RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		WHERE   
			((0 = 0 AND  1 = 1) OR (0 = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))  
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))     
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))     
			AND (SA.StatusId=0 OR 0=0)  
			AND ((SA.RollNo >= 0) OR (0=0))  
			AND ((SA.RollNo <= 0) OR (0=0))  
			AND ((SA.Code='') OR (''=''))  
			AND ((SA.DepartmentId=0) OR (0=0))    
			AND ((SA.ExemptionTypeId=0) OR (0=0))    
			AND ((SA.ClassId=0) OR (0=0))  
			AND ((SA.DivisionId=0) OR (0=0))     
		ORDER BY SA.RollNo  

  IF(@rType='Organization')
  BEGIN
		 
		SELECT SCS.DivisionId,SCS.ReceiptBookId,SCS.OrgId,SCS.DepartmentId,SCS.ClassId,CM.Title+' - '+DivM.Title AS ClassDivision,   
		ISNULL((SELECT COUNT(Academicid) FROM  
		(SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate <  getdate() AND (LeftDate >  getdate() OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)=SUM(PaidAmount)) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS FullyPaid, 

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate <  getdate() AND (LeftDate >  getdate() OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING SUM(PaidAmount)=0  ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)  AS FullyUnPaid,  

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate <  getdate() AND (LeftDate >  getdate() OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)<> SUM(PaidAmount)  AND SUM(PaidAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS PartiallyPaid    
		FROM @rStudentCountStatus SCS
		INNER JOIN sFee.tReceipt R ON R.ReceiptBookId = SCS.ReceiptBookId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId 
		INNER JOIN sSetup.tDivisionMaster DivM ON  SCS.DivisionId = DivM.Id  
		INNER JOIN sSetup.tClassMaster CM ON  CM.Id = SCS.ClassId  
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SCS.DepartmentId  
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId 
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		where R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		Group By SCS.DivisionId,SCS.ReceiptBookId, SCS.OrgId,  SCS.DepartmentId, SCS.ClassId,CM.Title,DivM.Title
	
  END
  
  IF(@rType='ReceiptBook')
  BEGIN
		
		select a.ReceiptBookId,a.ReceiptBook,sum(isnull(a.FullyPaid,0))  as FullyPaid, sum(isnull(a.FullyUnPaid,0))  as FullyUnPaid, sum(isnull(a.PartiallyPaid,0))  as PartiallyPaid
 from (	 
				SELECT RBM.Id AS ReceiptBookId,RBM.Title AS ReceiptBook,  
		ISNULL((SELECT COUNT(Academicid) FROM  
		(SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate <  getdate() AND (LeftDate >  getdate() OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)=SUM(PaidAmount)) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS FullyPaid, 

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate <  getdate() AND (LeftDate >  getdate() OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING SUM(PaidAmount)=0  ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)  AS FullyUnPaid,  

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate <  getdate() AND (LeftDate >  getdate() OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)<> SUM(PaidAmount)  AND SUM(PaidAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS PartiallyPaid    
		FROM @rStudentCountStatus SCS
		INNER JOIN sFee.tReceipt R ON R.ReceiptBookId = SCS.ReceiptBookId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId 
		INNER JOIN sSetup.tDivisionMaster DivM ON  SCS.DivisionId = DivM.Id  
		INNER JOIN sSetup.tClassMaster CM ON  CM.Id = SCS.ClassId  
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SCS.DepartmentId  
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId 
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		where R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		Group By RBM.Id,RBM.Title,SCS.DivisionId
		) as a 
		Group by a.ReceiptBookId,a.ReceiptBook
  END
  
   IF(@rType='OrganizationList')
  BEGIN
			select a.OrgId,a.OrganizationName,sum(isnull(a.FullyPaid,0))  as FullyPaid, sum(isnull(a.FullyUnPaid,0))  as FullyUnPaid, sum(isnull(a.PartiallyPaid,0))  as PartiallyPaid
 from (	 
		 
	    SELECT SCS.OrgId AS OrgId,SCS.OrgName AS OrganizationName,     
	    
		ISNULL((SELECT COUNT(Academicid) FROM  
		(SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < getdate() AND (LeftDate > getdate() OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)=SUM(PaidAmount)) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS FullyPaid, 

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < getdate() AND (LeftDate > getdate() OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING SUM(PaidAmount)=0  ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)  AS FullyUnPaid,  

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < getdate() AND (LeftDate > getdate() OR ISNULL(LeftDate,'')= '')
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)<> SUM(PaidAmount)  AND SUM(PaidAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS PartiallyPaid    
		FROM @rStudentCountStatus SCS
		INNER JOIN sFee.tReceipt R ON R.ReceiptBookId = SCS.ReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId 
		INNER JOIN sSetup.tDivisionMaster DivM ON  SCS.DivisionId = DivM.Id  
		INNER JOIN sSetup.tClassMaster CM ON  CM.Id = SCS.ClassId  
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SCS.DepartmentId  
		 
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId

		where R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
			AND (R.ReceiptBookId = @rReceiptBookId) 
		Group By SCS.OrgId,SCS.OrgName,SCS.DivisionId
		) as a 
		Group by a.OrgId,a.OrganizationName

  END
  
   IF(@rType='ClassDivisionName')
  BEGIN
  	select a.DivisionId,a.DivisionName,sum(isnull(a.FullyPaid,0))  as FullyPaid, sum(isnull(a.FullyUnPaid,0))  as FullyUnPaid, sum(isnull(a.PartiallyPaid,0))  as PartiallyPaid
 from (	 
		 
	    SELECT SA.DivisionId, SA.ClassName +' - '+ SA.DivisionName AS DivisionName,    
	    
		ISNULL((SELECT COUNT(Academicid) FROM  
		(SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < getdate() AND (LeftDate > getdate() OR ISNULL(LeftDate,'')= '')AND (ReceiptBookId = @rReceiptBookId) 
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)=SUM(PaidAmount)) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS FullyPaid, 

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < getdate() AND (LeftDate > getdate() OR ISNULL(LeftDate,'')= '')AND (ReceiptBookId = @rReceiptBookId) 
		GROUP BY DivisionId,AcademicId   
		HAVING SUM(PaidAmount)=0  ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)  AS FullyUnPaid,  

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < getdate() AND (LeftDate > getdate() OR ISNULL(LeftDate,'')= '')AND (ReceiptBookId = @rReceiptBookId) 
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)<> SUM(PaidAmount)  AND SUM(PaidAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS PartiallyPaid    
		FROM @rStudentCountStatus SCS
		INNER JOIN sFee.tReceipt R ON R.ReceiptBookId = SCS.ReceiptBookId
			INNER JOIN sSetup.tDivisionMaster DivM ON  SCS.DivisionId = DivM.Id  
		INNER JOIN sSetup.tClassMaster CM ON  CM.Id = SCS.ClassId  
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SCS.DepartmentId  
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId AND SA.OrgId=OM.Id AND SA.ClassId = CM.Id  AND SA.DivisionId = DivM.Id
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId 
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId

		where R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		Group By SA.DivisionId,SA.ClassName,SA.DivisionName,SCS.DivisionId
		) as a 
		Group by a.DivisionId,a.DivisionName
  
  
		--SELECT SA.DivisionId, SA.ClassName +' - '+ SA.DivisionName AS DivisionName,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		--LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		--WHERE R.SourceTypeId = 2001
		--AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		--AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		--AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--AND (R.IsObsolete = 0) 
		--AND (R.ReceiptBookId = @rReceiptBookId) 
		--GROUP BY SA.DivisionId,SA.ClassName,SA.DivisionName
  END
  
   IF(@rType='StudentList')
  BEGIN
  	 	select a.Code,a.Name,a.ReceiptNumber,sum(isnull(a.FullyPaid,0))  as FullyPaid, sum(isnull(a.FullyUnPaid,0))  as FullyUnPaid, sum(isnull(a.PartiallyPaid,0))  as PartiallyPaid
 from (	 
		 
	    SELECT SA.Code,SA.Name,R.ReceiptNumber,     
	    
		ISNULL((SELECT COUNT(Academicid) FROM  
		(SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < getdate() AND (LeftDate > getdate() OR ISNULL(LeftDate,'')= '') AND (DivisionId = @rDivisionId OR @rDivisionId=0) AND (ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)=SUM(PaidAmount)) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS FullyPaid, 

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < getdate() AND (LeftDate > getdate() OR ISNULL(LeftDate,'')= '') AND (DivisionId = @rDivisionId OR @rDivisionId=0) AND (ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
		GROUP BY DivisionId,AcademicId   
		HAVING SUM(PaidAmount)=0  ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)  AS FullyUnPaid,  

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		WHERE AdmissionDate < getdate() AND (LeftDate > getdate() OR ISNULL(LeftDate,'')= '') AND (DivisionId = @rDivisionId OR @rDivisionId=0) AND (ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)<> SUM(PaidAmount)  AND SUM(PaidAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS PartiallyPaid    
		FROM @rStudentCountStatus SCS
		INNER JOIN sFee.tReceipt R ON R.ReceiptBookId = SCS.ReceiptBookId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId 
		INNER JOIN sSetup.tDivisionMaster DivM ON  SCS.DivisionId = DivM.Id  
		INNER JOIN sSetup.tClassMaster CM ON  CM.Id = SCS.ClassId  
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId AND SA.OrgId=OM.Id AND SA.ClassId = CM.Id  AND SA.DivisionId = DivM.Id
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId 
		--INNER JOIN sSetup.tDivisionMaster DivM ON  SCS.DivisionId = DivM.Id  
		--INNER JOIN sSetup.tClassMaster CM ON  CM.Id = SCS.ClassId  
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SCS.DepartmentId  
	
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId

		where R.SourceTypeId = 2001
		AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		AND (R.IsObsolete = 0) 
		AND (R.ReceiptBookId = @rReceiptBookId) 
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId=0)
		Group By SA.Code,SA.Name,R.ReceiptNumber,SCS.DivisionId
		) as a 
		Group by a.Code,a.Name,a.ReceiptNumber
  
		--SELECT SA.Code,SA.Name,R.ReceiptNumber,SUM(R.ReceiptAmount) AS ReceiptAmount FROM sFee.tReceipt R
		--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
		--INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId
		--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
		--LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
		--WHERE R.SourceTypeId = 2001
		--AND LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId
		--AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		--AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--AND (R.IsObsolete = 0) 
		--AND (R.ReceiptBookId = @rReceiptBookId) 
		--AND (SA.DivisionId = @rDivisionId OR @rDivisionId=0)
		--GROUP BY SA.Code,SA.Name,R.ReceiptNumber
  END
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pStudentDepositListGet]
          
	@rOrgGroupId smallint,
	@rOrgId int,          
	@rDepositHeadId int=0,         
	@rFromDate date='',
	@rToDate date='',        
	--@rCode nvarchar(20)='',          
	@rStudentName nvarchar(300)='',
	@rStudentCode nvarchar(100)='',
	@rClassId int=0,
	@rDivisionId int=0,
	@rIsBasedOnSUId bit = 0,
	@rDepartmentId int=0,
	@rSUId nvarchar(50)='',
	@rBatchId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)=''

           
AS
SET NOCOUNT ON
 
BEGIN
		SET @rStudentName = sCommon.fSearchStringGet(@rStudentName)

SELECT * FROM (


SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rDepositHeadId AS DepositHeadId,
		(SELECT [sFee].[fDepositHeadNameGet](@rDepositHeadId)) AS DepositHeadName,
		ISNULL(SA.StudentId,0) as StudentId,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		ISNULL(DA.Amount,0) AS TransactionAmount,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        SA.DivisionId,
		SA.DivisionOrder,
		SA.DivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,
		CASE WHEN @rIsBasedOnSUId=0 THEN SA.Code Else ISNULL(SA.suid,'') END AS SUId,
		SA.Code,
		DA.DepositDate AS TransactionDate,
		SA.DepartmentName As DepartmentName,
		SA.ClassName + '-'+ SA.DivisionName As ClassDivision,
		(ISNULL(DA.Amount,0))As Pending,
		'Deposit' As TransactionType,
		ISnull (DA.Amount,0) AS Credit,
		0 AS Debit,
		1 AS OrderIndex,
		DA.DepositNumber AS Number,
		DA.CreatedDateTime
  FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		INNER JOIN sFee.tDepositAdd DA ON DA.AcademicId=SA.AcademicId
		--(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.AcademicId,ISNull(DA.DepositHeadId,0) AS DepositHeadId,DA.DepositDate As DepositDate,DA.DepositNumber  As DepositNumber,DA.CreatedDateTime FROM  sFee.tDepositAdd DA INNER JOIN sStudent.tAcademic A ON DA.AcademicId = A.Id  WHERE DA.DepositHeadId=@rDepositHeadId  GROUP  BY DA.AcademicId,DA.DepositHeadId,DA.DepositDate,DA.DepositNumber,DA.CreatedDateTime)D 
		--ON D.AcademicId=SA.AcademicId
		
  WHERE  
		(SA.OrgId=@rOrgId OR @rOrgId=0)
		AND(OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId=0)
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND (((SA.FirstName +' '+SA.MiddleName+' '+ SA.LastName) like @rStudentName) OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND (DA.DepositHeadId = @rDepositHeadId) 
		AND (
		((DA.DepositDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((DA.DepositDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		) 

		
UNION ALL

SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rDepositHeadId AS DepositHeadId,
		(SELECT [sFee].[fDepositHeadNameGet](@rDepositHeadId)) AS DepositHeadName,
		ISNULL(SA.StudentId,0) as StudentId,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		ISNULL(A.Amount,0) AS TransactionAmount,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        SA.DivisionId,
		SA.DivisionOrder,
		SA.DivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,
		CASE WHEN @rIsBasedOnSUId=0 THEN SA.Code Else ISNULL(SA.suid,'') END AS SUId,
		SA.Code,
		A.AdjustmentDate AS TransactionDate,
		SA.DepartmentName As DepartmentName,
		SA.ClassName + '-'+ SA.DivisionName As ClassDivision,
		(ISNULL(A.Amount,0))As Pending,
		'Adjusment' AS TransactionType,
		0  AS Credit,
		ISnull (A.Amount,0)  AS Debit,
		2 AS OrderIndex,
		A.AdjustmentNumber AS Number,
		A.CreatedDateTime
  FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tDepositAdjustment A ON A.AcademicId=SA.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
  WHERE  
		(SA.OrgId=@rOrgId OR @rOrgId=0)
		AND(OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId=0)
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND (((SA.FirstName +' '+SA.MiddleName+' '+ SA.LastName) like @rStudentName) OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND (A.DepositHeadId = @rDepositHeadId)
		AND (
		((A.AdjustmentDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((A.AdjustmentDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		) 
			
		UNION ALL

SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rDepositHeadId AS DepositHeadId,
		(SELECT [sFee].[fDepositHeadNameGet](@rDepositHeadId)) AS DepositHeadName,
		ISNULL(SA.StudentId,0) as StudentId,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		ISNULL(R.RefundAmount,0) TransactionAmount,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        SA.DivisionId,
		SA.DivisionOrder,
		SA.DivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,
		CASE WHEN @rIsBasedOnSUId=0 THEN SA.Code Else ISNULL(SA.suid,'') END AS SUId,
		SA.Code,
		R.RefundDate AS TransactionDate,
		SA.DepartmentName As DepartmentName,
		SA.ClassName + '-'+ SA.DivisionName As ClassDivision,
		(ISNULL(R.RefundAmount,0))As Pending,
		'Refund' AS TransactionType,
		0  AS Credit,
		ISnull (R.RefundAmount,0)  AS Debit,
		3 AS OrderIndex,
		R.RefundNumber AS Number,
		R.CreatedDateTime
  FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		INNER JOIN sFee.tDepositRefund R ON R.AcademicId=SA.AcademicId
		--LEFT JOIN 
		--(SELECT SUM(ISNULL(DR.RefundAmount,0)) AS TotalRefund,DR.AcademicId,ISNULL(DR.DepositHeadId,0) AS DepositHeadId,DR.RefundDate As RefundDate,DR.RefundNumber AS RefundNumber,DR.CreatedDateTime FROM sFee.tDepositRefund DR INNER JOIN sStudent.tAcademic A ON DR.AcademicId = A.Id  WHERE   DR.DepositHeadId=@rDepositHeadId GROUP BY DR.AcademicId,DepositHeadId,DR.RefundDate,DR.RefundNumber,DR.CreatedDateTime)R
		--ON R.AcademicId=SA.AcademicId
  WHERE  
		(SA.OrgId=@rOrgId OR @rOrgId=0)
		AND(OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId=0)
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND (((SA.FirstName +' '+SA.MiddleName+' '+ SA.LastName) like @rStudentName) OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND (R.DepositHeadId = @rDepositHeadId)
		AND (
		((R.RefundDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((R.RefundDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		) 	

	) A
	Order by A.OrgId,A.Code,A.TransactionDate

		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pStudentFeeDetailGet]
	 
	   @rBusRouteId int,
	   @rOrgGroupId smallint, 
	   @rOrgGroupBatchId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.FeeOrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo,
		'' AS WhatsAppContactNo --added by dhananjay for : 37272	
  FROM 
        sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (FS1.IsOptional=1)
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
		) 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 FS.Id = RD.FeeSetupId 
				INNER JOIN sfEe.tFeeMaster FM ON FM.Id = FS.FeeId 
				INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id AND FH.Number = 1001
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
			GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sTransport.tAssignRoute AR ON  SA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003	
		 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
	     INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (SA.StatusId = 1)
			AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
    Order by SA.DivisionOrder

			SELECT 
				 CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassDivision,
			 	 SA.StudentId AS StudentId, 
			 	 SA.Code AS StudentCode,
				 0x AS StudentPhoto, 
				 SA.FirstName + ' ' + SA.LastName AS StudentName, 
				 BRDM.Title AS Destination,
				 ISNULL(P.PendingAmount,0.00) AS PendingAmount ,
				 ISNULL(P.FeeName,'')AS FeeName,
				 '' AS FatherContactNo,
		         '' AS MotherContactNo,
				 '' AS WhatsAppContactNo --added by dhananjay for : 37272
			FROM 
				 sTransport.tAssignRoute AR 
				 INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = AR.SourceId
		         INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId 
		         INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BRDM.BusRouteId 
		         INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId 
		         INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId 
                 LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId 
				 LEFT JOIN @p P ON P.AcademicId = SA.AcademicId
            WHERE 
                 BRM.Id = @rBusRouteId 
                 AND BRM.OrgGroupId = @rOrgGroupId 
                 AND BRM.OrgGroupBatchId = @rOrgGroupBatchId
                 AND SA.IsActiveBatch = 1
                 AND SA.StatusId = 1
            ORDER BY 
				 BRDM.OrderIndex,DM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pStudentFeeProcess]
	
	@rOrgGroupBatchId int,	
	@rOrgId int,
	@rBatchId int,
	@rAdmissionCategoryId int,
	@rIdNo nvarchar(500)='',
	@rDepartmentId int,
	@rClassId int,
	@rDivisionId int,	
	@rReceiptBookId int	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF OBJECT_ID('tempdb..#TempStudentFeeDetail') IS NOT NULL
		DROP TABLE #TempStudentFeeDetail

DECLARE @SrNo INT;
SET @SrNo=1
DECLARE @TempStudentDetailCount INT;

		SELECT ROW_NUMBER() over (order by SA.AcademicId, FS.Id ) as SrNo ,	SA.AcademicId,		
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptionalApplicable,
			ISNULL(FS.IsVariable,0)AS IsVariableApplicable,			
			ISNULL(FS.Amount,0)AS FeeAmount,	
			ISNULL(FA.VariableAmount,0.00)AS VariableAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount INTO #TempStudentFeeDetail			
		
	  FROM 
			sStudent.vStudentAcademic SA
			--INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId AND tSA.BATCHID=@rBatchId AND SA.BATCHID=@rBatchId AND  SA.ORGID=@rOrgId
			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,SA1.AcademicId					
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId			
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE ((FS1.ClassId=@rClassId) OR (@rClassId=0))
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND ((FS1.ReceiptBookId=0) OR (0=0))
			AND (FS1.IsOptional=0)					
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))	
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=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,SA1.AcademicId					
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId							
			WHERE ((FS1.ClassId=@rClassId) OR (@rClassId=0))
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND ((FS1.ReceiptBookId=0) OR (0=0))
			AND (FS1.IsOptional=1)				
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0)) AND (SA1.ClassId=@rClassId OR @rClassId=0) AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE (R.SourceTypeId = 2001)
			AND (R.IsObsolete = 0) 
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			GROUP BY FeeSetupId,R.SourceId) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId

			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
      LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			
			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))   
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
			AND ((SA.Code=@rIdNo) OR (@rIdNo=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))		

BEGIN TRANSACTION

	BEGIN TRY 

	SET @TempStudentDetailCount = (SELECT ISNULL(COUNT(*),0) FROM #TempStudentFeeDetail)


	WHILE @SrNo <= @TempStudentDetailCount
	BEGIN 

	DECLARE @Count INT;	

	SET @Count = (SELECT ISNULL(COUNT(*),0) FROM sFee.tStudentFee SF INNER JOIN #TempStudentFeeDetail TS ON TS.AcademicId=SF.AcademicId AND TS.FeeSetupId=SF.FeeSetupId WHERE TS.SrNo=@SrNo)

		IF(@Count=0)

		BEGIN
			
			INSERT INTO sFee.tStudentFee(AcademicId,FeeSetupId,IsOptionalApplicable,IsVariableApplicable,FeeAmount,VariableAmount,DiscountAmount,AdditionalAmount,NotApplicableAmount,PaidAmount,PendingAmount) 		
			(SELECT AcademicId,FeeSetupId,IsOptionalApplicable,IsVariableApplicable,FeeAmount,VariableAmount,DiscountAmount,AdditionalAmount,NotApplicableAmount,PaidAmount,PendingAmount 
			FROM #TempStudentFeeDetail where SrNo=@SrNo)
	  
		END
		ELSE
		BEGIN	

			UPDATE SF SET 
			FeeSetupId =TSF.FeeSetupId,
			AcademicId=TSF.AcademicId,
			IsOptionalApplicable=TSF.IsOptionalApplicable,
			IsVariableApplicable=TSF.IsVariableApplicable,		
			FeeAmount=TSF.FeeAmount,
			VariableAmount = TSF.VariableAmount,
			DiscountAmount=TSF.DiscountAmount,
			AdditionalAmount=TSF.AdditionalAmount,
			NotApplicableAmount=TSF.NotApplicableAmount,
			PaidAmount=TSF.PaidAmount,
			PendingAmount=TSF.PendingAmount
			from sFee.tStudentFee SF 
			INNER JOIN #TempStudentFeeDetail TSF ON TSF.AcademicId = SF.AcademicId AND TSF.FeeSetupId=SF.FeeSetupId 
			WHERE TSF.SrNo=@SrNo

		END

	SET @SrNo = @SrNo + 1;
END	
	COMMIT TRANSACTION

	SELECT 1 AS Result
	--SELECT * from #TempStudentFeeDetail
END TRY

BEGIN CATCH 

		ROLLBACK TRANSACTION
		SELECT -1 AS Result		
END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pStudentFeeReceiptListGet] 
	@rOrgGroupBatchId INT
	,@rOrgId INT
	,@rBatchId INT
	,@rCode NVARCHAR(20)
	,@rReportId INT = 0
	,@rIsCancel BIT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		SELECT ISNULL(RBM.Title, '') AS ReceiptBookTitle
			,R.ReceiptNumber
			,R.ReceiptDate
			,R.ReceiptAmount
			,ISNULL(PTM.Title, '') AS PayType
			,CASE 
				WHEN ISNULL(R.ChequeNo, '') != ''
					THEN R.ChequeNo
				ELSE CONVERT(NVARCHAR(20), R.PaymentTransactionId)
				END AS ChequeNo
			,ISNULL(R.BankName, '') AS BankName
			,ISNULL([sFee].[fReceiptFeeDetailGet](R.Id), '') AS FeeDetail
			,R.Id AS ReceiptId
			,ISNULL(R.ReceiptBookId, '0') AS ReceiptBookId
			,SA.OrgId
			,R.DiscountAmount
			,@rIsCancel AS IsCancel
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.SourceId
			AND (
				(SA.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = R.ReceiptBookId
		LEFT JOIN sSecurity.tUser U ON U.Id = R.CreatedUserId
		WHERE R.SourceTypeId = 2001
			AND (
				(SA.OrgGroupBatchId = @rOrgGroupBatchId)
				OR (@rOrgGroupBatchId = 0)
				)
			AND (
				(SA.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			AND (
				(R.BatchId = @rBatchId)
				OR (@rBatchId = 0)
				)
			AND (R.IsObsolete = @rIsCancel)
			AND (
				(SA.Code = @rCode)
				OR (@rCode = '')
				)
		ORDER BY R.ReceiptDate
			,R.ReceiptNumber

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT -1 AS Result
	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pStudentLedgerGet]  
   
  @rCode  nvarchar(20)='',  
  @rSUId nvarchar(50)='',  
  @rDepositHeadId int,  
  @rOrgId int,  
  @rBatchId int=0,  
  @rAcademicId bigint=0  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON   
BEGIN   
 SELECT A.DepositDate ,  
        A.Credit,  
        A.Debit,  
  A.ExpenseType,  
  A.TransactionType, 
  A.BatchName, 
  (CASE WHEN A.Debit = 0 THEN 'Credited' ELSE 'Debited' END)AS PayType,
  A.DepositType,		--add for mantis: 35522
  A.StockItemList		-- MantisId : 	0036181
         FROM(  
   SELECT   
   DA.DepositDate AS DepositDate,  
   ISnull (DA.Amount,0) AS Credit,  
      0 AS Debit,  
   '' AS ExpenseType,  
   'Deposit Add' AS TransactionType  ,
   DA.CreatedDateTime,
   VA.BatchName,
   (CASE WHEN DA.ReferenceSourceTypeId=1021 THEN 'Stock Return' ELSE 'Deposit Add' END) AS DepositType,		--add for mantis: 35522
   (CASE WHEN DA.ReferenceSourceTypeId = 1021 THEN sFee.fnGetStockDepositeAddItemName(DA.ReferenceSourceId) ELSE '' END) AS StockItemList		-- MantisId : 	0036181
   FROM sStudent.vStudentAcademic  VA  
   INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId   
   Where   
   ((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))  
   AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))  
   AND (DA.DepositHeadId = @rDepositHeadId)   
   AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))   
   AND VA.StudentId= @rAcademicId  
   ---AND VA.BatchId = @rBatchId  
   UNION ALL   
   SELECT   
   DAJ.AdjustmentDate As DepositDate,  
   0  AS Credit,  
   ISnull (DAJ.Amount,0)  AS Debit,  
   ISNULL(ETM.Title,'')AS ExpenseType,  
   ('Expense'+' '+ISNULL(ETM.Title,'')) AS TransactionType  ,
   DAJ.CreatedDateTime,
   VA.BatchName,
   '' AS DepositType,		--add for mantis: 35522
   (CASE WHEN DAJ.ReferenceSourceTypeId = 2039 THEN sFee.fnGetStockDepositeAdjustmentItemName(DAJ.ReferenceSourceId) ELSE '' END) AS StockItemList		-- MantisId : 	0036181
   FROM sStudent.vStudentAcademic  VA  
     INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId  
     INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId  
   Where   
   ((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))  
   AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))  
   AND (DAJ.DepositHeadId = @rDepositHeadId)   
   AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))   
   --AND VA.BatchId = @rBatchId  
   AND VA.StudentId = @rAcademicId  
   UNION ALL   
   SELECT   
   DR.RefundDate As DepositDate,  
   0  AS Credit,  
   ISnull (DR.RefundAmount,0)  AS Debit,  
   '' AS ExpenseType,  
   'Deposit Refund' AS TransactionType ,
    DR.CreatedDateTime,
	VA.BatchName,
	'' AS DepositType,		--add for mantis: 35522
	'' AS StockItemList			-- MantisId : 	0036181
   FROM sStudent.vStudentAcademic  VA  
     INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId  
   Where   
   ((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))  
   AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))  
   AND (DR.DepositHeadId = @rDepositHeadId)   
   AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))   
     -- AND VA.BatchId = @rBatchId  
      AND VA.StudentId = @rAcademicId  
   )A   
   Order BY A.DepositDate,A.CreatedDateTime
     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sFee].[pStudentwiseOptionalFeeGet]

		   @rClassId int = 0,
           @rAdmissionCategoryId int = 0,
		   @rBatchId int = 0,
		   @rOrgGroupId int = 0,
		   @rSourceTypeId int = 0,
		   @rSourceId bigint = 0,
		   @rType tinyint = 0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
IF(@rType = 1)
BEGIN
	SELECT 
			ISNULL(FS.Id,0)AS Id,
			FM.Title AS Title,		
			ISNULL(FS.Amount,0)AS Amount,
			CASE WHEN ISNULL(FO.SourceId,0) = 0 THEN 'False' ELSE 'True' END AS IsCheck
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId AND FS.IsOptional=1
			AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS.Id AND FO.SourceTypeId=@rSourceTypeId AND FO.SourceId=@rSourceId
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,FM.OrderIndex

END
ELSE
BEGIN
	SELECT 			
			FHM.Id AS Id,
			ISNULL(SUM(FS.Amount),0)AS Amount,			
			ISNULL(FHM.Title,'') AS Title,
			CASE WHEN ISNULL(COUNT(FO.SourceId),0) = COUNT(FS.Id) THEN 'True' ELSE 'False' END AS IsCheck
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId AND FS.IsOptional=1
			AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS.Id AND FO.SourceTypeId=@rSourceTypeId AND FO.SourceId=@rSourceId
WHERE 
		FM.OrgGroupId=@rOrgGroupId		
	GROUP BY FHM.Id,FHM.Title--,FO.SourceId
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pUpdateNegativeCharge]
	 
		@rReceiptBookId int=0,	 
		@rClassId int=0,
		@rDivisionId int=0,	 
		@rBatchId int=0,	 
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0, 
	    @rCode nvarchar(20)='',
	    @rSourceId bigint
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	



	create TABLE #TempFeeUpdate
	(	Id int IDENTITY,
	    AcademicId bigint,
		FeeSetupId int,
		PendingAmount Decimal(12,2)
    )

INSERT INTO #TempFeeUpdate


	SELECT 
	 
		SA.AcademicId, 
		FS.Id AS FeeSetupId,	 
		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,
				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.ClassId=@rClassId) OR (@rClassId=0))
				--AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			 
			WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.AcademicId=@rSourceId) OR (@rSourceId=0))
				 
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			--AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.AcademicId=@rSourceId) OR (@rSourceId=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 sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) 
				AND ((SA1.AcademicId=@rSourceId) OR (@rSourceId=0))
				GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
	
	WHERE	
	
			((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			--AND ((FS.EndDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			--AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			--AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			--AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.AcademicId=@rSourceId) OR (@rSourceId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			Order by SA.RollNo
				
	
--MERGE sFee.tFeeAllocation FA
--USING #TempFeeUpdate TU
--ON FA.FeeSetupId = TU.FeeSetupId AND FA.SourceTypeId = 2001 AND FA.SourceId = TU.AcademicId
 
--WHEN MATCHED THEN
--  UPDATE
--  SET FA.VariableAmount = ISNULL(FA.VariableAmount,0) - TU.PendingAmount
--WHEN NOT MATCHED BY TARGET THEN
--  INSERT (SourceTypeId, SourceId, FeeSetupId,VariableAmount,DiscountAmount,AdditionalAmount,NotApplicableAmount,Remark,ReferenceTypeId,ReferenceSourceId,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime)
--  VALUES (2001, TU.AcademicId,TU.FeeSetupId,-TU.PendingAmount,0,0,0,'',0,0,0,getdate(),0,getdate());
  
SELECT * FROM #TempFeeUpdate

DROP TABLE	#TempFeeUpdate

SELECT 1 AS Result
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sFee].[pUpdatePendingAsNAGet]
	 
		@rOrgGroupBatchId int=0,
		@rOrgId int=0,
		@rBatchId int=0,	 
		@rFromLeftDate Date=NULL,
		@rToLeftDate Date=NULL,
	    @rStatusId int=3

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	
	DECLARE @p AS TempPendingFee
	
	INSERT INTO @p 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo,
		'' AS WhatsAppContactNo --added by dhananjay for : 37272
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				
		) 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=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.StatusId = @rStatusId
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.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 = SA.StudentId 
		AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND SA.	StatusId = @rStatusId
			
			ORDER BY SA.RollNo
	 
			SELECT
				Temp.OrgId,			 
				Temp.ReceiptBookId,
				Temp.AcademicId,
				Temp.DivisionId,
				ClassDivision,
				Temp.RollNo, 
				Name,
				Temp.Code,
				ReceiptBookTitle,
				OrgName,
				SUM(PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](Temp.AcademicId,Temp.ReceiptBookId,	@p) AS PendingFeeName,
				ReceiptOrderIndex,
				Temp.BatchId,
				BatchName,
				'' AS SUId,
				SA.LeftDate,
				Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex,
				'' AS FatherContactNo,
		        '' AS  MotherContactNo,
				'' AS WhatsAppContactNo --added by dhananjay for : 37272
			FROM @p Temp
				INNER JOIN sStudent.tAcademic A ON A.Id =  Temp.AcademicId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId AND SM.StatusId = @rStatusId
				INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = A.StudentId
			WHERE 
			    ( (@rStatusId = 3 AND ((SA.LeftDate >= @rFromLeftDate) OR (ISNULL(@rFromLeftDate,'') = ''))
				  AND ((SA.LeftDate <= @rToLeftDate) OR (ISNULL(@rToLeftDate,'') = '')) )
				OR (@rStatusId = 2 AND ((SA.InActiveDate >= @rFromLeftDate) OR (ISNULL(@rFromLeftDate,'') = ''))
				  AND ((SA.InActiveDate <= @rToLeftDate) OR (ISNULL(@rToLeftDate,'') = '')) )
				)
				AND SM.StatusId = @rStatusId
				GROUP BY 
				Temp.OrgId,Temp.AcademicId,Temp.ReceiptBookId,Temp.DivisionId,Temp.BatchId,
				ClassDivision,Temp.RollNo, Name,Temp.Code,ReceiptBookTitle,
				OrgName,ReceiptOrderIndex,BatchName,SA.LeftDate,Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex
				ORDER BY Temp.AcademicId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pUpdatePendingAsNAUpdate] 
	@rReceiptBookId INT = 0
	,@rClassId INT = 0
	,@rDivisionId INT = 0
	,@rBatchId INT = 0
	,@rOrgId INT = 0
	,@rOrgGroupBatchId INT = 0
	,@rStatusId INT = 0
	,@rCode NVARCHAR(20) = ''
	,@rSourceId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	CREATE TABLE #TempFeeUpdate (
		Id INT IDENTITY
		,AcademicId BIGINT
		,FeeSetupId INT
		,PendingAmount DECIMAL(12, 2)
		)

	INSERT INTO #TempFeeUpdate
	SELECT SA.AcademicId
		,FS.Id AS FeeSetupId
		,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
			,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.ClassId = @rClassId)
				OR (@rClassId = 0)
				)
		--AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
		WHERE (
				(FS1.ClassId = @rClassId)
				OR (@rClassId = 0)
				)
			AND (
				(SA1.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			--AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (
				(FS1.ReceiptBookId = @rReceiptBookId)
				OR (@rReceiptBookId = 0)
				)
			AND (FS1.IsOptional = 0)
			--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND (
				(FS1.BatchId = @rBatchId)
				OR (@rBatchId = 0)
				)
			AND (
				(SA1.BatchId = @rBatchId)
				OR (@rBatchId = 0)
				)
			AND (
				(SA1.AcademicId = @rSourceId)
				OR (@rSourceId = 0)
				)
		
		UNION ALL
		
		SELECT FS1.FeeId
			,FS1.Id
			,ISNULL(FS1.IsOptional, 0) AS IsOptional
			,ISNULL(FS1.IsVariable, 0) AS IsVariable
			,ISNULL(FS1.Amount, 0) AS Amount
			,ISNULL(FS1.StartDate, '1900-01-01') AS StartDate
			,ISNULL(FS1.EndDate, '1900-01-01') AS EndDate
			,FS1.BatchId
			,ISNULL(FS1.ReceiptBookId, 0) AS ReceiptBookId
			,SA1.AcademicId
			,FM.Title AS FeeName
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId = FS1.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FO.SourceId
			AND SA1.BatchId = FS1.BatchId
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND (
				(SA1.ClassId = @rClassId)
				OR (@rClassId = 0)
				)
		--AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE (
				(FS1.ClassId = @rClassId)
				OR (@rClassId = 0)
				)
			AND (
				(SA1.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			--AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (
				(FS1.ReceiptBookId = @rReceiptBookId)
				OR (@rReceiptBookId = 0)
				)
			AND (FS1.IsOptional = 1)
			--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND (
				(FS1.BatchId = @rBatchId)
				OR (@rBatchId = 0)
				)
			AND (
				(SA1.BatchId = @rBatchId)
				OR (@rBatchId = 0)
				)
			AND (
				(SA1.AcademicId = @rSourceId)
				OR (@rSourceId = 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 sStudent.vStudentAcademic SA1 ON SA1.AcademicId = R.SourceId
			AND (
				SA1.ClassId = @rClassId
				OR @rClassId = 0
				)
			AND (
				SA1.DivisionId = @rDivisionId
				OR @rDivisionId = 0
				)
		WHERE (R.SourceTypeId = 2001)
			AND (
				(SA1.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			AND (R.IsObsolete = 0)
			AND (
				(SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				OR (@rBatchId = 0)
				)
			AND (
				(R.BatchId = @rBatchId)
				OR (@rBatchId = 0)
				)
			AND (
				(SA1.AcademicId = @rSourceId)
				OR (@rSourceId = 0)
				)
		GROUP BY FeeSetupId
			,R.SourceId
		) R ON R.FeeSetupId = FS.Id
		AND SA.AcademicId = R.SourceId
	INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
	INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId = RBM.Id
	WHERE (
			(SA.BatchId = @rBatchId)
			OR (@rBatchId = 0)
			)
		AND (
			SA.StatusId = @rStatusId
			OR @rStatusId = 0
			)
		--AND ((FS.EndDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		--AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND (
			(SA.Code = @rCode)
			OR (@rCode = '')
			)
		--AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (
			(SA.AcademicId = @rSourceId)
			OR (@rSourceId = 0)
			)
		AND (ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) != 0)
	ORDER BY SA.RollNo

	MERGE sFee.tFeeAllocation FA
	USING #TempFeeUpdate TU
		ON FA.FeeSetupId = TU.FeeSetupId
			AND FA.SourceTypeId = 2001
			AND FA.SourceId = TU.AcademicId
			--WHEN MATCHED AND
			--  bi.Quantity + bo.Quantity = 0 THEN
			--  DELETE
	WHEN MATCHED
		THEN
			UPDATE
			SET FA.NotApplicableAmount = ISNULL(FA.NotApplicableAmount, 0) + TU.PendingAmount
	WHEN NOT MATCHED BY TARGET
		THEN
			INSERT (
				SourceTypeId
				,SourceId
				,FeeSetupId
				,VariableAmount
				,DiscountAmount
				,AdditionalAmount
				,NotApplicableAmount
				,Remark
				,ReferenceTypeId
				,ReferenceSourceId
				,CreatedUserId
				,CreatedDateTime
				,UpdatedUserId
				,UpdatedDateTime
				)
			VALUES (
				2001
				,TU.AcademicId
				,TU.FeeSetupId
				,0
				,0
				,0
				,TU.PendingAmount
				,''
				,0
				,0
				,0
				,sCommon.fGetDate()
				,0
				,sCommon.fGetDate()
				);


	-- For Fee Process Added By Foram on 2025-01-30
	MERGE sFee.tFeeAllocationStudent FAS
	USING #TempFeeUpdate TU ON FAS.FeeSetupId = TU.FeeSetupId AND FAS.AcademicId = TU.AcademicId
	WHEN MATCHED
		THEN
			UPDATE 
			SET FAS.NotApplicableAmount = ISNULL(FAS.NotApplicableAmount, 0) + TU.PendingAmount,
				FAS.ToPayAmount = (ISNULL(FAS.FeeAmount, 0) + ISNULL(FAS.VariableAmount, 0) + ISNULL(FAS.AdditionalAmount, 0) - ISNULL(FAS.DiscountAmount, 0) - (ISNULL(FAS.NotApplicableAmount, 0) + TU.PendingAmount) - ISNULL(FAS.PaidAmount, 0))
	WHEN NOT MATCHED BY TARGET
		THEN
			INSERT (
				AcademicId
				,FeeSetupId
				,FeeAmount
				,VariableAmount
				,DiscountAmount
				,AdditionalAmount
				,NotApplicableAmount
				,ToPayAmount
				,PaidAmount
				,Remark
				,CreatedUserId
				,CreatedDateTime
				,UpdatedUserId
				,UpdatedDateTime
			)
			VALUES (
				TU.AcademicId
				,TU.FeeSetupId
				,(SELECT Amount FROM sFee.tFeeSetup WHERE Id = TU.FeeSetupId)
				,0
				,0
				,0
				,TU.PendingAmount
				,((SELECT Amount FROM sFee.tFeeSetup WHERE Id = TU.FeeSetupId) - TU.PendingAmount) 
				,0
				,''
				,0
				,sCommon.fGetDate()
				,0
				,sCommon.fGetDate()
			);
	-- For Fee Process Added By Foram on 2025-01-30

	--select * from #TempFeeUpdate
	--WHEN NOT MATCHED BY SOURCE
	--  AND bi.Quantity = 0 THEN
	--  DELETE;	
	DROP TABLE #TempFeeUpdate

	SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pUpdatePendingAsNotApplicable]
	 
		@rReceiptBookId int=0,	 
		@rClassId int=0,
		@rDivisionId int=0,	 
		@rBatchId int=0,	 
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0, 
	    @rCode nvarchar(20)='',
	    @rSourceId bigint
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

CREATE TABLE #TempFeeUpdate
	(	Id int IDENTITY,
	    AcademicId bigint,
		FeeSetupId int,
		PendingAmount Decimal(12,2)
    )

INSERT INTO #TempFeeUpdate
	SELECT 
		SA.AcademicId, 
		FS.Id AS FeeSetupId,	 
		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,
				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.ClassId=@rClassId) OR (@rClassId=0))
				--AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.AcademicId=@rSourceId) OR (@rSourceId=0))
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			--AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.AcademicId=@rSourceId) OR (@rSourceId=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 sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) 
				AND ((SA1.AcademicId=@rSourceId) OR (@rSourceId=0))
				GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
	WHERE   ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			--AND ((FS.EndDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			--AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			--AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			--AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.AcademicId=@rSourceId) OR (@rSourceId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			Order by SA.RollNo
				
--SELECT * FROM #TempFeeUpdate
IF EXISTS(Select 1 from sSetup.tBatchMaster WHERE Id = @rBatchId and OrgId = @rOrgId and OrgGroupBatchId = @rOrgGroupBatchId)
BEGIN
MERGE sFee.tFeeAllocation FA
USING #TempFeeUpdate TU
ON FA.FeeSetupId = TU.FeeSetupId AND FA.SourceTypeId = 2001 AND FA.SourceId = TU.AcademicId
--WHEN MATCHED AND
--  bi.Quantity + bo.Quantity = 0 THEN
--  DELETE
WHEN MATCHED THEN
  UPDATE
  SET FA.NotApplicableAmount = ISNULL(FA.NotApplicableAmount,0) + TU.PendingAmount,NotApplicableRemark = 'Update NA Amount'
WHEN NOT MATCHED BY TARGET THEN
  INSERT (SourceTypeId, SourceId, FeeSetupId,VariableAmount,DiscountAmount,AdditionalAmount,NotApplicableAmount,Remark,ReferenceTypeId,ReferenceSourceId,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,NotApplicableRemark)
  VALUES (2001, TU.AcademicId,TU.FeeSetupId,0,0,0,TU.PendingAmount,'',0,0,0,sCommon.fGetDate(),0,sCommon.fGetDate(),'Updated NA Amount');
 

MERGE sFee.tFeeAllocationStudent FAS
	USING #TempFeeUpdate TU ON FAS.FeeSetupId = TU.FeeSetupId AND FAS.AcademicId = TU.AcademicId
	WHEN MATCHED
		THEN
			UPDATE 
			SET FAS.NotApplicableAmount = ISNULL(FAS.NotApplicableAmount, 0) + TU.PendingAmount,
				FAS.ToPayAmount = (ISNULL(FAS.FeeAmount, 0) + ISNULL(FAS.VariableAmount, 0) + ISNULL(FAS.AdditionalAmount, 0) - ISNULL(FAS.DiscountAmount, 0) - (ISNULL(FAS.NotApplicableAmount, 0) + TU.PendingAmount) - ISNULL(FAS.PaidAmount, 0))
	WHEN NOT MATCHED BY TARGET
		THEN
			INSERT (
				AcademicId
				,FeeSetupId
				,FeeAmount
				,VariableAmount
				,DiscountAmount
				,AdditionalAmount
				,NotApplicableAmount
				,ToPayAmount
				,PaidAmount
				,Remark
				,CreatedUserId
				,CreatedDateTime
				,UpdatedUserId
				,UpdatedDateTime
			)
			VALUES (
				TU.AcademicId
				,TU.FeeSetupId
				,(SELECT Amount FROM sFee.tFeeSetup WHERE Id = TU.FeeSetupId)
				,0
				,0
				,0
				,TU.PendingAmount
				,((SELECT Amount FROM sFee.tFeeSetup WHERE Id = TU.FeeSetupId) - TU.PendingAmount) 
				,0
				,''
				,0
				,sCommon.fGetDate()
				,0
				,sCommon.fGetDate()
			);

SELECT 1 AS Result
END
ELSE
BEGIN
SELECT -1 AS Result
END
  --select * from #TempFeeUpdate
--WHEN NOT MATCHED BY SOURCE
--  AND bi.Quantity = 0 THEN
--  DELETE;	
DROP TABLE	#TempFeeUpdate


 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pValidateBulkFee]

	@rOrgGroupId smallint,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lFeeId int,
        @lCode nvarchar(20),       
        @lNumber int,
        @lTitle nvarchar(100),
        @lFeeHeadId int,
        @1ExistCode nvarchar(max) = '',
        @1ExistNumber nvarchar(max) = '',
        @1ExistTitle nvarchar(max) = '',
        @1DuplicateCode nvarchar(max) = '',
        @1DuplicateNumber nvarchar(max) = '',
        @1DuplicateTitle nvarchar(max) = ''
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
		FeeId int,
        Code nvarchar(20),
        Number int,
        Title nvarchar(100),
        FeeHeadId int
  )
  INSERT INTO #tTable1
	(
		FeeId,
	    Code,
	    Number, 
	    Title,
	    FeeHeadId
    ) 
   SELECT
		FeeId,
        Code,
	    Number, 
	    Title,
	    FeeHeadId
   
   FROM OPENXML (@intDoc, '/Table/FeeMaster', 1)
   With
   (
		FeeId int '@FeeId',
        Code nvarchar(50) '@Code',
        Number int '@Number',
        Title nvarchar(100) '@Title',
        FeeHeadId int '@FeeHeadId'
   )   
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
  
       SELECT         
         @lFeeId = FeeId,
         @lCode = Code, 
         @lNumber = Number,
         @lTitle = Title,
         @lFeeHeadId = FeeHeadId
         
     FROM #tTable1 WHERE Id = @lCount 
     
    IF Exists ((select 1 from sFee.tFeeMaster where Code = @lCode AND OrgGroupId = @rOrgGroupId AND @lFeeId=0))         
      BEGIN
		    SET @1ExistCode = @1ExistCode + @lCode + ','
       END	  
	IF Exists ((select 1 from sFee.tFeeMaster where Number = @lNumber AND OrgGroupId = @rOrgGroupId  AND @lFeeId=0))         
      BEGIN
			SET @1ExistNumber = @1ExistNumber + CAST(@lNumber as varchar(max)) + ','
       END
	IF Exists ((select 1 from sFee.tFeeMaster where Title = @lTitle AND OrgGroupId = @rOrgGroupId AND @lFeeId=0))         
      BEGIN
			SET @1ExistTitle = @1ExistTitle + @lTitle  + ','
       END
     SET @lCount = @lCount - 1	
   END	
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code='')
		BEGIN
			SELECT 'Enter Code' AS Code
			RETURN
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number='')
		BEGIN
			SELECT 'Enter Number' AS Code
			RETURN
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Title IS NULL OR Title='')
		BEGIN
			SELECT 'Enter Title' AS Code
			RETURN
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE FeeHeadId IS NULL OR FeeHeadId=0)
		BEGIN
			SELECT 'Select Fee Head' AS Code
			RETURN
		END
		
		SELECT @1DuplicateCode=COALESCE(@1DuplicateCode ,'') 
		+ Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		IF(@1DuplicateCode IS NOT NULL AND @1DuplicateCode != '')
		BEGIN
			SET @1DuplicateCode = 'Duplicate Code ' + @1DuplicateCode
			SELECT @1DuplicateCode AS Code
			RETURN
		END
			
		SELECT @1DuplicateNumber=COALESCE(@1DuplicateNumber ,'') 
			+ CONVERT(VARCHAR(20),Number) + ',' FROM #tTable1 GROUP BY Number HAVING ( COUNT(Number) > 1 AND ISNULL(Number,'')!='')	
		IF(@1DuplicateNumber IS NOT NULL AND @1DuplicateNumber != '')
		BEGIN
			SET @1DuplicateNumber = 'Duplicate Number ' + @1DuplicateNumber
			SELECT @1DuplicateNumber AS Code
			RETURN
		END
		
		SELECT @1DuplicateTitle=COALESCE(@1DuplicateTitle ,'') 
		+ Title + ',' FROM #tTable1 GROUP BY Title HAVING ( COUNT(Title) > 1 )	
		IF(@1DuplicateTitle IS NOT NULL AND @1DuplicateTitle != '')
		BEGIN
			SET @1DuplicateTitle = 'Duplicate Title ' + @1DuplicateTitle
			SELECT @1DuplicateTitle AS Code
			RETURN
		END
		
		IF((@1ExistCode IS NULL OR @1ExistCode = '') AND (@1ExistNumber IS NULL OR @1ExistNumber = '') AND (@1ExistTitle IS NULL OR @1ExistTitle = ''))
		BEGIN
			SELECT '' AS Code
			RETURN
		END
		
		IF (@1ExistCode IS NOT NULL AND @1ExistCode != '')
		BEGIN
			SET @1ExistCode = 'Exist Code ' + @1ExistCode
			Select @1ExistCode AS Code
			RETURN
		END
		
		IF (@1ExistNumber IS NOT NULL AND @1ExistNumber != '')
		BEGIN
			SET @1ExistNumber = 'Exist Number ' + @1ExistNumber
			Select @1ExistNumber AS Code
			RETURN
		END
		
		IF (@1ExistTitle IS NOT NULL AND @1ExistTitle != '')
		BEGIN
			SET @1ExistTitle = 'Exist Title ' + @1ExistTitle
			Select @1ExistTitle AS Code
			RETURN
		END
		Select '' AS Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFee].[pValidateImportFee]
     @rOrgGroupId smallint,
	 @rXmldoc [nvarchar](max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,  @lCode nvarchar(50),  @lTitle nvarchar(100), @lNumber int=0,@lFeeHead nvarchar(100),       
        @1ReturnCode int = 1,@1ExistFeeCode nvarchar(max) = '', @1DuplicateFeeCode nvarchar(max) = '',
        @1ExistFeeNumber nvarchar(max) = '',@1ExistFeeTitle nvarchar(max) = '',@1DuplicateFeeTitle nvarchar(max) = '',
        @1DuplicateFeeNumber nvarchar(max) = '',@1DuplicateOrderIndex nvarchar(max) = '',@1ExistFeeOrderIndex nvarchar(max)='',@lOrderIndex int=0
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(20),
        Name nvarchar(100),
        Number int,FeeHead nvarchar(100),
        OrderIndex int,
  )
  INSERT INTO #tTable1
	(
	    Code, Name, Number,FeeHead ,OrderIndex 
    ) 
   SELECT
        Code,Name,Number,FeeHead,OrderIndex
   FROM OPENXML (@intDoc, '/Table/ImportFee', 1)
   With
   (
        Code nvarchar(20) '@Code',   
        Name nvarchar(100) '@Name' ,
        Number    int '@Number',
        FeeHead Nvarchar(100) '@FeeHead',
        OrderIndex    int '@OrderIndex'
   ) 
EXEC sp_xml_removedocument @intDoc
    IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Code Should not be empty' AS StudentCode
END
     ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Name IS NULL OR Name COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	 SELECT 'Name Should not be empty' AS StudentCode
END
ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number='' OR Number Is NUll )
BEGIN
	SELECT 'Number Should not be empty' AS StudentCode
END
ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE OrderIndex = '' OR OrderIndex Is NUll )
BEGIN
	SELECT 'OrderIndex Should not be empty' AS StudentCode
END
ELSE 
     IF EXISTS(SELECT 1 fROM #tTable1 WHERE FeeHead IS NULL OR FeeHead COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'FeeHead Should not be empty' AS StudentCode
END
ELSE
BEGIN	
SELECT @lCount =  COUNT(Id) FROM #tTable1
WHILE @lCount > 0 
BEGIN
	SELECT @lCode = Code , @lTitle=Name,@lNumber=Number,@lFeeHead=FeeHead,@lOrderIndex=OrderIndex
	FROM #tTable1 WHERE Id = @lCount 
	IF NOT Exists (select 1 from sFee.tFeeHeadMaster where OrgGroupId=@rOrgGroupId AND Title COLLATE DATABASE_DEFAULT = @lFeeHead COLLATE DATABASE_DEFAULT)         
    BEGIN
		 SELECT 'Enter proper value for Gradeset : ' + @lFeeHead  AS StudentCode
    END	  
	IF Exists ((select 1 from sFee.tFeeMaster where OrgGroupId=@rOrgGroupId AND Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistFeeCode = @1ExistFeeCode + @lCode + ',' 
    END	  
    IF Exists ((select 1 from sFee.tFeeMaster where OrgGroupId=@rOrgGroupId AND Title COLLATE DATABASE_DEFAULT = @lTitle COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistFeeTitle = @1ExistFeeTitle + @lTitle + ','
    END	  
    IF Exists ((select 1 from sFee.tFeeMaster where OrgGroupId=@rOrgGroupId AND convert(varchar,Number) COLLATE DATABASE_DEFAULT = convert(varchar,@lNumber) COLLATE DATABASE_DEFAULT ))         
    BEGIN
		SET @1ExistFeeNumber = @1ExistFeeNumber + convert(varchar,@lNumber )+ ','
    END	 
      IF Exists ((select 1 from sFee.tFeeMaster where OrgGroupId=@rOrgGroupId AND convert(varchar,OrderIndex)  COLLATE DATABASE_DEFAULT = convert(varchar,@lOrderIndex) COLLATE DATABASE_DEFAULT ))               
    BEGIN
		SET @1ExistFeeOrderIndex = @1ExistFeeOrderIndex + convert(varchar,@lOrderIndex )+ ','
    END	 
	SET @lCount = @lCount - 1	
	END
SELECT @1DuplicateFeeCode=COALESCE(@1DuplicateFeeCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
SELECT @1DuplicateFeeTitle=COALESCE(@1DuplicateFeeTitle ,'') + Name + ',' FROM #tTable1 GROUP BY Name HAVING ( COUNT(Name) > 1 )	
SELECT @1DuplicateFeeNumber=COALESCE(@1DuplicateFeeNumber ,'') + CONVERT(varchar,Number) + ',' FROM #tTable1 GROUP BY Number HAVING ( COUNT(Number) > 1 )	
SELECT @1DuplicateOrderIndex=COALESCE(@1DuplicateOrderIndex ,'') +CONVERT(varchar, OrderIndex) + ',' FROM #tTable1 GROUP BY OrderIndex HAVING ( COUNT(OrderIndex) > 1 )	

	IF(@1DuplicateFeeCode IS NOT NULL AND @1DuplicateFeeCode != '')
	BEGIN
		SET @1DuplicateFeeCode = 'Duplicate Code : ' + @1DuplicateFeeCode
	END
	IF(@1DuplicateFeeTitle IS NOT NULL AND @1DuplicateFeeTitle != '')
	BEGIN
		SET @1DuplicateFeeTitle = 'Duplicate Name : ' + @1DuplicateFeeTitle
	END
	IF(@1DuplicateFeeNumber IS NOT NULL AND @1DuplicateFeeNumber != '')
	BEGIN
		SET @1DuplicateFeeNumber = 'Duplicate Number : ' + @1DuplicateFeeNumber
	END
	IF(@1DuplicateOrderIndex IS NOT NULL AND @1DuplicateOrderIndex != '')
	BEGIN
		SET @1DuplicateOrderIndex = 'Duplicate OrderIndex : ' + @1DuplicateOrderIndex
	END
	 IF (@1ExistFeeCode IS NOT NULL AND @1ExistFeeCode != '' )
	BEGIN
		SET @1ExistFeeCode = 'Exist Code : ' + @1ExistFeeCode
	END
	 IF (@1ExistFeeTitle IS NOT NULL AND @1ExistFeeTitle != '' )
	BEGIN
		SET @1ExistFeeTitle = 'Exist Name : ' + @1ExistFeeTitle
	END
	 IF (@1ExistFeenumber IS NOT NULL AND @1ExistFeenumber != '' )
	BEGIN
		SET @1ExistFeenumber = 'Exist Number : ' + @1ExistFeenumber
	END
	 IF (@1ExistFeeOrderIndex IS NOT NULL AND @1ExistFeeOrderIndex != '' )
	BEGIN
		SET @1ExistFeeOrderIndex = 'Exist OrderIndex : ' + @1ExistFeeOrderIndex
	END
	SELECT isnull(@1DuplicateFeeCode,'')+isnull(@1DuplicateFeeTitle,'')+isnull(@1DuplicateFeeNumber,'')+isnull(@1DuplicateOrderIndex,'')+isnull(@1ExistFeeCode,'')+
isnull(@1ExistFeeTitle,'') +isnull(@1ExistFeenumber,'')+ isnull(@1ExistFeeOrderIndex ,'')  AS StudentCode 
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFee].[pValidatePayType]
	@rPayTypeIds nvarchar(max) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN		

	CREATE TABLE #PayTypeTemp (Id bigint identity, TableName nvarchar(200))

	INSERT INTO #PayTypeTemp
	SELECT TABLE_SCHEMA + '.' + TABLE_NAME from INFORMATION_SCHEMA.COLUMNS 
	WHERE COLUMN_NAME like '%PayTypeId%' AND TABLE_NAME <> 'tApplicablePayType' AND TABLE_NAME <> 'tReceiptDeleted' AND TABLE_NAME <> 'vFeeCustomSearch'

	--SELECT * FROM #PayTypeTemp

	DECLARE @lTables nvarchar(max) = ''
	DECLARE @lCount int = 1
	DECLARE @lTotal int = (SELECT COUNT(Id) FROM #PayTypeTemp)	
	WHILE @lCount <= @lTotal 
	BEGIN			
		DECLARE @lTableName nvarchar(200) = (SELECT TableName FROM #PayTypeTemp WHERE Id = @lCount)	
		DECLARE @lQuery nvarchar(max) = ''
		SET @lQuery = 'IF EXISTS (SELECT 1 FROM '+CAST(@lTableName AS NVARCHAR(200))+' WHERE PayTypeId IN ('+CAST(@rPayTypeIds AS VARCHAR)+')) BEGIN SELECT 1 AS '''+CAST(@lTableName AS NVARCHAR(200))+''' END'		
		--PRINT(@lQuery)
		exec (@lQuery)
		SET @lCount = @lCount + 1	
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFee].[pWinFeeDetailDelete]
	 
		@rBatchId int,
		@rClassId int,
		@rDivisionId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
		BEGIN
			DELETE WFD FROM sFee.tWinfeeDetail WFD
			INNER JOIN sStudent.tAcademic A ON A.Id = WFD.AcademicId AND A.BatchId = WFD.BatchId 
			WHERE 
			(WFD.BatchId = @rBatchId)
			AND ((A.ClassId = @rClassId) OR (@rClassId=0))
			AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId=0))
			SELECT 1 AS Result
		END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pWinFeeDetailGet]
	 
		@rBatchId int,
		@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	
	DECLARE @lAcademicId bigint = 0
	DECLARE @lOrgId int
	DECLARE @lItemValue nvarchar(100)
		
	SELECT @lAcademicId = Id,@lOrgId = OrgId FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		
	SELECT @lItemValue=Itemvalue from sConfig.tConfigurationSetup WHERE SourceTypeId = 1016   AND SourceId = @lOrgId AND ConfigurationId = 145
	IF @lItemValue = 'False'
	BEGIN
		SET @lAcademicId=0
	END	
	
	SELECT 
	
	--WFD.feeChoiceId,
	ISNULL(WFD.feeName,0)AS feeName,
	--ISNULL(WFD.choice,0)AS choice,
	ISNULL(WFD.Amount,0)AS Amount,
	--ISNULL(WFD.exemption,0)AS exemption,
	ISNULL(WFD.paid,0)AS paid,
	ISNULL(WFD.scheduleDate,'1900-01-01')AS scheduleDate,
	--ISNULL(WFD.ReceiptBookName,'') AS ReceiptBookName,
	ISNULL(WFD.Amount,0.00)-ISNULL(WFD.exemption,0.00)-ISNULL(WFD.paid,0.00)AS PendingAmount,
	ISNULL(WFD.exemption,0.00) AS exemption
	FROM sFee.tWinfeeDetail WFD
	WHERE AcademicId = @lAcademicId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFee].[pXMLWinFeeDetailAdd]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	
	-----------------------
	
	
	--UPDATE sFee.tWinfeeDetail 
	--SET	AcademicId=A1.AcademicId,
	--	feeName=A1.feeName,
	--	choice=A1.choice,
	--	Amount=A1.Amount,
	--	exemption=A1.exemption,
	--	paid=A1.paid,
	--	scheduleDate=A1.scheduleDate,
	--	ReceiptBookName=A1.ReceiptBookName,
	--	UpdatedDateTime=A1.UpdatedDateTime,
	--	BatchId=A1.BatchId	
	--FROM
	--(
	--	SELECT	
	--	feeChoiceId,	
	--	AcademicId,
	--	feeName,
	--	choice,
	--	Amount,
	--	exemption,
	--	paid,
	--	--scheduleDate,
	--		CASE WHEN scheduleDate = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(scheduleDate, 8)) END AS scheduleDate,
	--	ReceiptBookName,
	--	UpdatedDateTime,
	--	--CASE WHEN UpdatedDateTime = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(UpdatedDateTime, 8)) END AS UpdatedDateTime,
	--	BatchId	
	--	FROM OPENXML (@intDoc, '/Table/UploadFee', 1)
	--	WITH
	--	(
	--		feeChoiceId int '@feeChoiceId',
	--		AcademicId bigint '@AcademicId',
	--		feeName nvarchar(100) '@feeName',
	--		choice int '@choice',
	--		Amount decimal(12,2) '@Amount',
	--		exemption decimal(12,2) '@exemption',
	--		paid decimal(12,2) '@paid',
	--		scheduleDate bigint '@scheduleDate',
	--		ReceiptBookName nvarchar(100) '@ReceiptBookName',
	--		UpdatedDateTime Datetime '@UpdatedDateTime',
	--		BatchId int '@BatchId'
	--	))A1 WHERE sFee.tWinfeeDetail.feeChoiceId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A1.feeChoiceId,5)),@rOrgId)
													
	delete from sFee.tWinfeeDetail where AcademicId in (select Id From sStudent.tAcademic Where OrgId = @rOrgId)
	
	INSERT INTO sFee.tWinfeeDetail
	(
		feeChoiceId,
		AcademicId,
		feeName,
		choice,
		Amount,
		exemption,
		paid,
		scheduleDate,
		ReceiptBookName,
		UpdatedDateTime,
		BatchId	
	)
	SELECT
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(feeChoiceId,5)),@rOrgId),
		AcademicId,
		feeName,
		choice,
		Amount,
		exemption,
		paid,
		--scheduleDate,
		CASE WHEN scheduleDate = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(scheduleDate, 8)) END AS scheduleDate,
		ReceiptBookName,
	--	UpdatedDateTime,
		CASE WHEN UpdatedDateTime = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(UpdatedDateTime, 8)) END AS UpdatedDateTime,
		BatchId	
 
   		
		
	FROM OPENXML (@intDoc, '/Table/UploadFee', 1)
	WITH
	(
		feeChoiceId int '@feeChoiceId',
		AcademicId bigint '@AcademicId',
		feeName nvarchar(100) '@feeName',
		choice int '@choice',
		Amount decimal(12,2) '@Amount',
		exemption decimal(12,2) '@exemption',
		paid decimal(12,2) '@paid',
		scheduleDate bigint '@scheduleDate',
		ReceiptBookName nvarchar(100) '@ReceiptBookName',
		UpdatedDateTime bigint '@UpdatedDateTime',
		BatchId int '@BatchId'
	) 
	WHERE AcademicId Not IN (Select AcademicId FRom sFee.tWinfeeDetail Where BatchId=BatchId) AND
	sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(feeChoiceId,5)),@rOrgId) NOT IN (Select FeeChoiceId FRom sFee.tWinfeeDetail Where BatchId=BatchId) 

	

	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFrontOffice].[pAppLostFoundRegisterGet]

	 @rOrgGroupId smallint=0,
	 @rFromDate date,
	 @rToDate date,
	 @rUserSourceId bigint = 0, -- If student to pass AcademicId, If Employee to pass EmployeeId
	 @rUserSourceTypeId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS

BEGIN 
 
	 
	IF @rUserSourceTypeId=2003
	BEGIN 
		
		DECLARE @lDivisionId int = 0
		SELECT @lDivisionId=DivisionId FROM  sStudent.tAcademic WHERE Id = @rUserSourceId

		SELECT 
			LF.Id As LostFoundRegisterId,
			LF.OrgGroupId,
			LF.OrgId,
			--LF.Id,
			LF.FoundNumber,
			LF.FoundDate,
			LF.ItemType,
			LF.ItemDescription,
			LF.LostFoundStatusId,
			LF.OwnerSourceTypeId,
			LF.OwnwerSourceId,
			LF.OwnerDetail,
			LF.CreatedUserId,
			LF.CreatedDateTime,
			LF.UpdatedUserId,
			LF.UpdatedDateTime,
			SM.Title,
			SM.Id,
			(CASE WHEN LF.OwnerSourceTypeId=2003 THEN  SMast.Code
			WHEN  LF.OwnerSourceTypeId=95  THEN EM.Code  ElSE ''
			 END) AS Code
			
			  FROM 
						sFrontOffice.tLostFoundRegister LF 
						INNER JOIN sFrontOffice.tLostFoundRegisterScope LFR ON LF.Id=LFR.LostFoundRegisterId AND LFR.SourceTypeId = 2005 AND LFR.SourceId= @lDivisionId
						INNER JOIN sCommon.tStatusMaster SM ON SM.Id=LF.LostFoundStatusId 
						LEFT JOIN sStudent.vStudentLastAcademic SMast ON SMast.StudentId = LF.OwnwerSourceId  AND LF.OwnerSourceTypeId=2003
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = LF.OwnwerSourceId  AND LF.OwnerSourceTypeId=95
			  WHERE 
  
				((LF.FoundDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((LF.FoundDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND  LF.OrgGroupId=@rOrgGroupId
				AND ISNULL(EM.IsOtherUser,0) = 0 

				Order by CreatedDateTime desc
	END
	

	IF @rUserSourceTypeId=95
	BEGIN
		
		DECLARE @lDepartmentId int = 0
		SELECT @lDepartmentId=[OrganizationDepartmentId] FROM  [sHrm].[tEmployeeJobDetail] WHERE EmployeeId = @rUserSourceId

		 

		SELECT 
			LF.Id As LostFoundRegisterId,
			LF.OrgGroupId,
			LF.OrgId,
			--LF.Id,
			LF.FoundNumber,
			LF.FoundDate,
			LF.ItemType,
			LF.ItemDescription,
			LF.LostFoundStatusId,
			LF.OwnerSourceTypeId,
			LF.OwnwerSourceId,
			LF.OwnerDetail,
			LF.CreatedUserId,
			LF.CreatedDateTime,
			LF.UpdatedUserId,
			LF.UpdatedDateTime,
			SM.Title,
			SM.Id,
			(CASE WHEN LF.OwnerSourceTypeId=2003 THEN  SMast.Code
			WHEN  LF.OwnerSourceTypeId=95  THEN EM.Code  ElSE ''
			 END) AS Code
			
			  FROM 
						sFrontOffice.tLostFoundRegister LF 
						INNER JOIN sFrontOffice.tLostFoundRegisterScope LFR ON LF.Id=LFR.LostFoundRegisterId  AND LFR.SourceTypeId = 2017 AND LFR.SourceId= @lDepartmentId
						INNER JOIN sCommon.tStatusMaster SM ON SM.Id=LF.LostFoundStatusId 
						LEFT JOIN sStudent.vStudentLastAcademic SMast ON SMast.StudentId = LF.OwnwerSourceId  AND LF.OwnerSourceTypeId=2003
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = LF.OwnwerSourceId  AND LF.OwnerSourceTypeId=95
			  WHERE 
				((LF.FoundDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((LF.FoundDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND  LF.OrgGroupId=@rOrgGroupId
				AND ISNULL(EM.IsOtherUser,0) = 0 
				Order by CreatedDateTime desc
	END

	IF @rUserSourceTypeId=0
	BEGIN 
		
		--DECLARE @lDivisionId int = 0
		--SELECT @lDivisionId=DivisionId FROM  sStudent.tAcademic WHERE Id = @rUserSourceId

		SELECT 
			LF.Id As LostFoundRegisterId,
			LF.OrgGroupId,
			LF.OrgId,
			--LF.Id,
			LF.FoundNumber,
			LF.FoundDate,
			LF.ItemType,
			LF.ItemDescription,
			LF.LostFoundStatusId,
			LF.OwnerSourceTypeId,
			LF.OwnwerSourceId,
			LF.OwnerDetail,
			LF.CreatedUserId,
			LF.CreatedDateTime,
			LF.UpdatedUserId,
			LF.UpdatedDateTime,
			SM.Title,
			SM.Id,
			(CASE WHEN LF.OwnerSourceTypeId=2003 THEN  SMast.Code
			WHEN  LF.OwnerSourceTypeId=95  THEN EM.Code  ElSE ''
			 END) AS Code
			
			  FROM 
						sFrontOffice.tLostFoundRegister LF 
						INNER JOIN sFrontOffice.tLostFoundRegisterScope LFR ON LF.Id=LFR.LostFoundRegisterId 
						--AND LFR.SourceTypeId = 2005 AND LFR.SourceId= @lDivisionId
						INNER JOIN sCommon.tStatusMaster SM ON SM.Id=LF.LostFoundStatusId 
						LEFT JOIN sStudent.vStudentLastAcademic SMast ON SMast.StudentId = LF.OwnwerSourceId  
						--AND LF.OwnerSourceTypeId=2003
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = LF.OwnwerSourceId  
						--AND LF.OwnerSourceTypeId=95
			  WHERE 
  
				((LF.FoundDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((LF.FoundDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND  LF.OrgGroupId=@rOrgGroupId
				AND ISNULL(EM.IsOtherUser,0) = 0 
				Order by CreatedDateTime desc
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFrontOffice].[pAssignmentScopeAdd]
			@rLostFoundRegisterId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
If(@rIsDeleted=1)
BEGIN
	Delete from sFrontOffice.tLostFoundRegisterScope where LostFoundRegisterId=@rLostFoundRegisterId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 

		BEGIN TRY
	
	 BEGIN TRANSACTION	    
	If Exists(select LostFoundRegisterId from sFrontOffice.tLostFoundRegisterScope where LostFoundRegisterId=@rLostFoundRegisterId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sFrontOffice.tLostFoundRegisterScope
			(
				LostFoundRegisterId
			   ,SourceTypeId
			   ,SourceId
			)
			VALUES
			(	
				@rLostFoundRegisterId
			   ,@rSourceTypeId
			   ,@rSourceId
			)		
			SELECT @rLostFoundRegisterId AS Result
	END
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	
END 	             
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFrontOffice].[pCourierDispatchAdd]
	 
		@rOrgGroupId smallint,
        @rId int,
        @rDispatchedTo nvarchar(200),
        @rDispatchedCity nvarchar(100),
        @rDispatchAddress nvarchar(300),
		@rDispatchDate date,
		@rRemark nvarchar(200),
		@rOrgId smallint,
		@rCreatedUserId bigint,
		@rCreatedDateTime date,
		@rDispatchTime nvarchar(50),
		@rDispatchedBy  nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sFrontOffice.tCourierDispatch where Id=@rId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sActivity.tEventSchedule where Title=@rTitle AND BatchId=@rBatchId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFrontOffice.tCourierDispatch', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tCourierDispatch
		(
			OrgGroupId,
			Id,
			DispatchedTo,
			DispatchedCity,
			DispatchAddress,
			DispatchDate,
			Remark,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			DispatchTime,
			DispatchedBy
			
		)
	VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
			@rDispatchedTo,
			@rDispatchedCity,
			@rDispatchAddress,
			@rDispatchDate,
			@rRemark,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rDispatchTime,
			@rDispatchedBy
			
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tCourierDispatch
	    SET
			
			OrgGroupId=@rOrgGroupId,
			Id=@rId,
			DispatchedTo=@rDispatchedTo,
			DispatchedCity=@rDispatchedCity,
			DispatchAddress=@rDispatchAddress,
			DispatchDate=@rDispatchDate,
			Remark=@rRemark,
			OrgId=@rOrgId,
			CreatedUserId=@rCreatedUserId,
			CreatedDateTime=sCommon.fGetDate(),
			DispatchTime=@rDispatchTime,
			DispatchedBy=@rDispatchedBy
			
	      
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pCourierDispatchDelete]
	 @rId int,
	 @rOrgGroupId smallint,
	 @rOrgId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sFrontOffice.tCourierDispatch where 
			(OrgGroupId = @rOrgGroupId) AND
			(Id = @rId) AND
			(OrgId = @rOrgId)
			--Delete from sActivity.tEventSchedule where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pCourierDispatchGet]

	 @rOrgGroupId smallint=0,
	 @rId int = 0,
	 @rDispatchedTo nvarchar(200),
	 --@rDispatchDate date,
	 @rOrgId smallint=0,
	 @rFromDate date,
	 @rToDate date
	 
	 --@rSyncedEventScheduleId int = 0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 SET @rDispatchedTo = sCommon.fSearchStringGet(@rDispatchedTo) 

BEGIN 
	 
	
	SELECT 
	
			OrgGroupId,
			Id,
			DispatchedTo,
			DispatchedCity,
			DispatchAddress,
			DispatchDate,
			Remark,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			Isnull(DispatchTime,'') AS DispatchTime,
			Isnull(DispatchedBy,'')  AS DispatchedBy
      
  FROM 
            sFrontOffice.tCourierDispatch
            
  WHERE 
  
      ((Id = @rId) OR (@rId = 0))
	AND ((DispatchedTo LIKE @rDispatchedTo) OR (ISNULL(@rDispatchedTo,'') = ''))
	AND ((DispatchDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((DispatchDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--AND ((DispatchDate = @rDispatchDate) OR (ISNULL(@rDispatchDate,'') = ''))
	AND OrgGroupId=@rOrgGroupId
	AND (OrgId = @rOrgId OR @rOrgId = 0)
	
	
	Order by CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFrontOffice].[pCourierReceiveAdd]
	 
		@rOrgGroupId smallint,
        @rId int,
        @rReceiveFrom nvarchar(100),
        @rReceiveDate date,
        @rReceiveFor nvarchar(100),
		@rRemark nvarchar(300),
		@rOrgId smallint,
		@rCreatedUserId bigint,
		@rCreatedDateTime date,
		@rReceivedTime nvarchar(50),
	    @rReceivedBy nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFrontOffice.tCourierDispatch', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tCourierReceive
		(
			OrgGroupId,
			Id,
			ReceiveFrom,
			ReceiveDate,
			ReceiveFor,
			Remark,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			ReceivedTime,
			ReceivedBy
		)
	VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
			@rReceiveFrom,
			@rReceiveDate,
			@rReceiveFor,
			@rRemark,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rReceivedTime,
			@rReceivedBy
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tCourierReceive
	    SET
			
			OrgGroupId=@rOrgGroupId,
			Id=@rId,
			ReceiveFrom=@rReceiveFrom,
			ReceiveDate=@rReceiveDate,
			ReceiveFor=@rReceiveFor,
			Remark=@rRemark,
			OrgId=@rOrgId,
			CreatedUserId=@rCreatedUserId,
			CreatedDateTime=sCommon.fGetDate(),
			ReceivedTime=@rReceivedTime,
			ReceivedBy=@rReceivedBy
	      
	      
	      WHERE Id = @rId
	      AND 
	      OrgId=@rOrgId
	      AND
	      OrgGroupId=@rOrgGroupId
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pCourierreceiveDelete]
	 @rId int,
	 @rOrgGroupId smallint,
	 @rOrgId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sFrontOffice.tCourierReceive where 
			(OrgGroupId = @rOrgGroupId) AND
			(Id = @rId) AND
			(OrgId = @rOrgId)
			--Delete from sActivity.tEventSchedule where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pCourierReceiveGet]

	 @rOrgGroupId smallint=0,
	 @rId int = 0,
	 @rReceiveFrom nvarchar(200),
	 --@rReceiveDate date,
	 @rReceiveFor nvarchar(100),
	 @rOrgId smallint=0,
	 @rFromDate date,
	 @rToDate date
	 
	 --@rSyncedEventScheduleId int = 0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rReceiveFor = sCommon.fSearchStringGet(@rReceiveFor) 
			SET @rReceiveFrom = sCommon.fSearchStringGet(@rReceiveFrom) 
			
BEGIN 
	 
	
	SELECT 
	
			OrgGroupId,
			Id,
			ReceiveFrom,
			ReceiveDate,
			ReceiveFor,
			Remark,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			ReceivedTime,
			ReceivedBy
      
  FROM 
           sFrontOffice.tCourierReceive
            
  WHERE 
  
      ((Id = @rId) OR (@rId = 0))
	AND ((ReceiveFrom LIKE @rReceiveFrom) OR (ISNULL(@rReceiveFrom,'') = ''))
	AND (( ReceiveDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND (( ReceiveDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--AND ((ReceiveDate = @rReceiveDate) OR (ISNULL(@rReceiveDate,'') = ''))
	AND ((ReceiveFor LIKE @rReceiveFor) OR (ISNULL(@rReceiveFor,'') = ''))
	AND OrgGroupId=@rOrgGroupId
	AND (OrgId = @rOrgId OR @rOrgId = 0)
	
	
	Order by CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pCreateStudentGatePassNo]
		@rOrgId [int],
		@rNumber [nvarchar](20) OUTPUT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lPrefixSetupId bigint
	DECLARE @lPrefix Nvarchar(10)
	DECLARE @lNumberLength TinyInt
	DECLARE @loNextId bigint
	DECLARE @rNextNumber [nvarchar](100)

	SELECT @lPrefixSetupId = PS.Id, @lPrefix = Prefix, @lNumberLength = ISNULL(NumberLength, 7)
	FROM sCommon.tPrefixSetup PS
	WHERE PrefixFunctionalityId = 2012
		AND PS.IsObsolete = 0
		AND PS.OrgId = @rOrgId
		AND PS.StoreLocationId = 0
		AND EffectiveDate = (SELECT MAX(EffectiveDate)
								FROM sCommon.tPrefixSetup
								WHERE PrefixFunctionalityId = 2012 AND OrgId = @rOrgId AND IsObsolete = 0 AND StoreLocationId=0 AND EffectiveDate <= sCommon.fGetDate())

	EXECUTE sCommon.pPrefixSetupCurrentNumberModify @rId = @lPrefixSetupId, @rNextNumber = @loNextId OUTPUT

	SET @rNextNumber = sCommon.fNumberStringGet(@lPrefix, @lNumberLength, @loNextId)
	SET @rNumber = ISNULL(@rNextNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id
		RETURN
	END
	ELSE
	BEGIN
		SET @rNumber=@rNumber
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFrontOffice].[pEmployeeGatePassAdd]
	
	@rOrgId int, 
	@rId int,
	@rEmployeeId bigint,
	@rReasonOfGatePass nvarchar(200),
	@rGatePassDate date,
	@rReturnGatePassDate date,
	@rGatePassTime datetime,
	@rReturnGatePassTime datetime,
	@rEntryModeStatusId smallint,
	@rCreatedUserId bigint,
	@rRemark nvarchar(200)='',
	@rStatusId int=0,
	@rAssignEmployeeId bigint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tEmployeeGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	IF(@rStatusId = 0 AND @rAssignEmployeeId = 0)
	BEGIN
		INSERT INTO sFrontOffice.tEmployeeGatePass
		(
			OrgId,
			Id,
			EmployeeId,
			ReasonOfGatePass,
			GatePassDate,
			ReturnGatePassDate,
			GatePassTime,
			EntryModeStatusId,
			CreatedUserId,
			CreatedDateTime,
			Remark,
			ReturnGatePassTime
		)
		VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rEmployeeId,
			@rReasonOfGatePass,
			@rGatePassDate,
			@rReturnGatePassDate,
			@rGatePassTime,
			@rEntryModeStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rRemark,
			@rReturnGatePassTime 
		)
	END
	ELSE
	BEGIN
		INSERT INTO sFrontOffice.tEmployeeGatePass
		(
			OrgId,
			Id,
			EmployeeId,
			ReasonOfGatePass,
			GatePassDate,
			ReturnGatePassDate,
			GatePassTime,
			EntryModeStatusId,
			CreatedUserId,
			CreatedDateTime,
			Remark,
			ReturnGatePassTime,
			AssignEmployeeId,
			StatusId
		)
		VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rEmployeeId,
			@rReasonOfGatePass,
			@rGatePassDate,
			@rReturnGatePassDate,
			@rGatePassTime,
			@rEntryModeStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rRemark,
			@rReturnGatePassTime,
			@rAssignEmployeeId,
			@rStatusId
		)
	END
		             
END	 
	 ELSE
BEGIN
	SET @lNextNumber = @rId
	UPDATE  sFrontOffice.tEmployeeGatePass
	SET
		ReasonOfGatePass=@rReasonOfGatePass,
		EmployeeId=@rEmployeeId,
		GatePassDate=@rGatePassDate,
		ReturnGatePassDate=@rReturnGatePassDate,
		GatePassTime=@rGatePassTime,
		ReturnGatePassTime=@rReturnGatePassTime,
		EntryModeStatusId=@rEntryModeStatusId,
		Remark=@rRemark,
		AssignEmployeeId = @rAssignEmployeeId
		
	WHERE Id = @rId 	   
END  
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFrontOffice].[pEmployeeGatePassGet]
      
   @rId int,
   @rOrgId int=0,
   @rFromGatePassDate datetime='',
   @rToGatePassDate datetime='',
   @rEntryModeStatusId smallint=0,
   @rCode nvarchar(20)='',
   @rOrgGroupId int=0,
   @rReportId int=0,
   @rStatusId int=0,
   @rUserSourceId bigint = 0
       
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		SELECT  
			EG.Id,
			EM.Code,
			EM.FirstName+' '+EM.MiddleName+' '+EM.LastName AS Name,
			EG.EmployeeId,
			EG.ReasonOfGatePass,
			EG.GatePassDate,
			ISNULL(EG.ReturnGatePassDate,'') AS ReturnGatePassDate,
			EG.GatePassTime,
			ISNULL(EG.ReturnGatePassTime,'') AS ReturnGatePassTime,
			EG.EntryModeStatusId,
			SM.Title AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			ISNULL(U.DisplayTitle,'') AS UserName,
			EI.EmployeePhoto,
			Remark,
			@GatePassConfig AS ConfigValue,
			ISNULL(EG.StatusId,0) as StatusId,
			SM1.Title as Status,
			ISNULL(EG.AssignEmployeeId,0) as AssignEmployeeId,
			CASE WHEN ISNULL(EG.AssignEmployeeId,0) = 0 THEN '' ELSE (SELECT FirstName+' '+MiddleName+' '+LastName FROM sHrm.tEmployeeMaster WHERE Id = EG.AssignEmployeeId) END AS AssignEmployeeName,
			ISNULL(EDM.Title,'') AS Designation,
			CASE WHEN EG.EntryModeStatusId = 582 THEN EG.GatePassTime
				 WHEN EG.EntryModeStatusId = 581 THEN EG.ReturnGatePassTime
				 ELSE '' END AS InTime,
			CASE WHEN EG.EntryModeStatusId = 582 THEN EG.ReturnGatePassTime
				 WHEN EG.EntryModeStatusId = 581 THEN EG.GatePassTime
				 ELSE '' END AS OutTime

		FROM 
		    sFrontOffice.tEmployeeGatePass EG 
		    INNER JOIN  sHrm.tEmployeeMaster EM ON EG.EmployeeId = EM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EG.OrgId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=EG.EntryModeStatusId
			LEFT JOIN sSecurity.tUser U	ON U.Id=EG.CreatedUserId
			--INNER JOIN sSecurity.tUserOrganization UO ON U.Id = @rUserId
		    LEFT JOIN  sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id
			LEFT JOIN sCommon.tStatusMaster SM1 ON SM1.Id = EG.StatusId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId -- #Start Mantis : 0028596
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM	ON EDM.Id  = EJD.EmployeeDesignationId -- #Start Mantis : 0028596
		WHERE 
			OM.OrgGroupId=@rOrgGroupId
		    AND ((EG.Id=@rId) OR (@rId=0))
			AND ((EG.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((EG.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((EG.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((EG.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((EM.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((ISNULL(EG.StatusId,0) = @rStatusId) OR (ISNULL(@rStatusId,-1) = -1 AND ISNULL(EG.StatusId,0) != 0))
			AND ((EG.EmployeeId = @rUserSourceId) OR (ISNULL(@rUserSourceId,0) = 0))
		ORDER BY EG.GatePassDate,EG.GatePassTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFrontOffice].[pEmployeeGatePassListingGet]
      
   @rId int,
   @rOrgId int=0,
   @rFromGatePassDate datetime='',
   @rToGatePassDate datetime='',
   @rEntryModeStatusId smallint=0,
   @rCode nvarchar(20)='',
   @rOrgGroupId int=0,
   @rStatusId int=0,
   @rUserSourceId bigint = 0
       
AS
SET NOCOUNT ON
BEGIN
		SELECT  
			EG.Id,
			EM.Code,
			EM.FirstName+' '+EM.MiddleName+' '+EM.LastName AS Name,
			EG.EmployeeId,
			EG.ReasonOfGatePass,
			EG.GatePassDate,
			ISNULL(EG.ReturnGatePassDate,'') AS ReturnGatePassDate,
			Convert(varchar,EG.GatePassTime,108) as GatePassTime,
			ISNULL(Convert(varchar,EG.ReturnGatePassTime,108),'') AS ReturnGatePassTime,
			EG.EntryModeStatusId,
			SM.Title AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			ISNULL(U.DisplayTitle,'') AS UserName,
			Remark,
			ISNULL(EG.StatusId,0) as StatusId,
			SM1.Title as Status,
			ISNULL(EG.AssignEmployeeId,0) as AssignEmployeeId
		FROM 
		    sFrontOffice.tEmployeeGatePass EG 
		    INNER JOIN  sHrm.tEmployeeMaster EM ON EG.EmployeeId = EM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EG.OrgId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=EG.EntryModeStatusId
			LEFT JOIN sSecurity.tUser U	ON U.Id=EG.CreatedUserId
			LEFT JOIN sCommon.tStatusMaster SM1 ON SM1.Id = EG.StatusId
		WHERE 
			OM.OrgGroupId=@rOrgGroupId
		    AND ((EG.Id=@rId) OR (@rId=0))
			AND ((EG.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((EG.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((EG.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((EG.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((EM.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((ISNULL(EG.StatusId,0) = @rStatusId) OR (ISNULL(@rStatusId,-1) = -1 AND ISNULL(EG.StatusId,0) != 0))
			AND ((EG.AssignEmployeeId = @rUserSourceId) OR (ISNULL(@rUserSourceId,0) = 0))
		ORDER BY EG.GatePassDate,EG.GatePassTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pGetVisitorRelativePhoto]
	@rAcademicId BigInt,
	@rRelativePhoto varbinary(max)=NULL

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select Relation,VisitorName,VisitorMobile,VisitorPhoto from
	(SELECT Distinct  Top 2
			ISNULL(Relation,'') AS Relation
		   ,ISNULL(VisitorName, '' ) AS VisitorName
		   ,ISNULL(VisitorMobile, '') AS VisitorMobile
		   ,VisitorPhoto 
		   ,CreatedDateTime
	FROM sFrontOffice.tStudentGatePass
	WHERE RelationshipId=7 AND AcademicId=@rAcademicId 
	AND VisitorPhoto is not null 
	AND ((CONVERT(VARBINARY(MAX), VisitorPhoto)) <> (CONVERT(VARBINARY(MAX), @rRelativePhoto))) 
	) A
	ORDER BY CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sFrontOffice].[pImportInwardRegister]
       
    @rOrgId int,
	@rOrgGroupId int,
	@rXmldoc [nvarchar](max),
	@rBatchId int,
	@rCreatedUserId bigint 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lLetterNumber nvarchar(100),
			@lLetterDate date,
			@lReceivedDate date,
			@lLetterFrom nvarchar(300),
			@lLetterSubject nvarchar(300),
			@lIsReplyRequired bit,
			@lIsReplied bit,
			@lReplyDetail nvarchar(100),
			@lRemark nvarchar(300),
			@lLetterRemark nvarchar(max)

	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 (
	Id bigint identity,
	LetterNumber nvarchar(100),
	LetterDate date,
	ReceivedDate date,
	LetterFrom nvarchar(300),
	LetterSubject nvarchar(300),
	IsReplyRequired bit,
	IsReplied bit,
	ReplyDetail nvarchar(100),
	Remark nvarchar(300),
	LetterRemark nvarchar(max))
	
	INSERT INTO #tTable1(
            LetterNumber
           ,LetterDate
           ,ReceivedDate
           ,LetterFrom
           ,LetterSubject
           ,IsReplyRequired
           ,IsReplied
           ,ReplyDetail
           ,Remark
           ,LetterRemark)
	SELECT
	       T.c.value('@LetterNumber','nvarchar(100)') AS LetterNumber,
		   T.c.value('@LetterDate','date') AS LetterDate,
		   T.c.value('@ReceivedDate','date') AS ReceivedDate,
		   T.c.value('@LetterFrom','nvarchar(300)') AS LetterFrom,
		   T.c.value('@LetterSubject','nvarchar(300)') AS LetterSubject,
		   T.c.value('@IsReplyRequired','bit') AS IsReplyRequired,
		   T.c.value('@IsReplied','bit') AS IsReplied,
		   T.c.value('@ReplyRemark','nvarchar(100)') AS ReplyDetail,
		   T.c.value('@Remark','nvarchar(300)') AS Remark,
		   T.c.value('@LetterRemark','nvarchar(max)') AS LetterRemark
	FROM @loXML.nodes('/Table/InwardRegister')T(c)
	
	
	
SELECT @lCount =  COUNT(Id) FROM #tTable1
	
	
WHILE @lCount > 0 

BEGIN				
	
SELECT	
		 @lLetterNumber = LetterNumber,
		 @lLetterDate = LetterDate,
		 @lReceivedDate = ReceivedDate,
		 @lLetterFrom = LetterFrom,
		 @lLetterSubject = LetterSubject,
		 @lIsReplyRequired = IsReplyRequired,
		 @lIsReplied = IsReplied,
		 @lReplyDetail = ReplyDetail,
		 @lRemark = Remark,
		 @lLetterRemark = LetterRemark
FROM #tTable1 WHERE Id = @lCount 

			DECLARE @lNextNumber BIGINT	
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tInwardRegister', 0, 1, 1,@outNextNumber = @lNextNumber output

			DECLARE @lInwardNumber INT 

			DECLARE @lConfigValue nvarchar(50)=''
			SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 298 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

			IF @lConfigValue = ''
			  SET @lConfigValue = 'False'
			
			IF @lConfigValue = 'True'
			BEGIN
				SELECT @lInwardNumber = ISNULL(MAX(InwardNumber),0)+1  FROM sFrontOffice.tInwardRegister where OrgId= @rOrgId AND BatchId = @rBatchId
			END
			ELSE
			BEGIN
				SELECT @lInwardNumber = ISNULL(MAX(InwardNumber),0)+1  FROM sFrontOffice.tInwardRegister where OrgId= @rOrgId 
			END

			INSERT INTO sFrontOffice.tInwardRegister
			(
				OrgId,
				Id,
				InwardNumber,
				LetterNumber,
				LetterDate,
				ReceivedDate,
				LetterFrom,
				LetterSubject,
				IsReplyRequired,
				IsReplied,
				ReplyDetail,
				OutwardRegisterId,
				Remark,
				CreatedUserId,
				CreatedDateTime,
				BatchId,
				LetterRemark
			)
			VALUES
			(
				@rOrgId,	
				@lNextNumber,
				@lInwardNumber,					
				@lLetterNumber,
				@lLetterDate,
				@lReceivedDate,
				@lLetterFrom,
				@lLetterSubject,
				@lIsReplyRequired,
				@lIsReplied,
				@lReplyDetail,
				0,
				@lRemark,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rBatchId,
				@lLetterRemark 
			)
				
		SET @lCount = @lCount - 1
	SELECT 1 AS Result, '' AS ResultDetail				

 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sFrontOffice].[pImportOutwardRegister]
       
    @rOrgId int,
	@rOrgGroupId int,
	@rXmldoc [nvarchar](max),
	@rBatchId int,
	@rCreatedUserId bigint 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lOutwardDate date,
			@lLetterNumber nvarchar(100),
			@lLetterDate date,
			@lLetterTo nvarchar(300),
			@lLetterSubject nvarchar(300),
			@lIsReplyRequired bit,
			@lIsReplied bit,
			@lReplyDetail nvarchar(100),
			@lRemark nvarchar(300),
			@lLetterRemark nvarchar(max)

	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 (
	Id bigint identity,
	OutwardDate Date,
	LetterNumber nvarchar(100),
	LetterDate date,
	LetterTo nvarchar(300),
	LetterSubject nvarchar(300),
	IsReplyRequired bit,
	IsReplied bit,
	ReplyDetail nvarchar(100),
	Remark nvarchar(300),
	LetterRemark nvarchar(max))
	
	INSERT INTO #tTable1(
			OutwardDate
           ,LetterNumber
           ,LetterDate
		   ,LetterTo
           ,LetterSubject
           ,IsReplyRequired
           ,IsReplied
           ,ReplyDetail
           ,Remark
           ,LetterRemark)
	SELECT
	       T.c.value('@OutwardDate','date') AS OutwardDate,
		   T.c.value('@LetterNumber','nvarchar(100)') AS LetterNumber,
		   T.c.value('@LetterDate','date') AS LetterDate,
		   T.c.value('@LetterTo','nvarchar(300)') AS LetterTo,
		   T.c.value('@LetterSubject','nvarchar(300)') AS LetterSubject,
		   T.c.value('@IsReplyRequired','bit') AS IsReplyRequired,
		   T.c.value('@IsReplied','bit') AS IsReplied,
		   T.c.value('@ReplyDetail','nvarchar(100)') AS ReplyDetail,
		   T.c.value('@Remark','nvarchar(300)') AS Remark,
		   T.c.value('@LetterRemark','nvarchar(max)') AS LetterRemark
	FROM @loXML.nodes('/Table/OutwardRegister')T(c)
	
	
	
SELECT @lCount =  COUNT(Id) FROM #tTable1
	
	
WHILE @lCount > 0 

BEGIN				
	
SELECT	
		 @lOutwardDate = OutwardDate,
		 @lLetterNumber = LetterNumber,
		 @lLetterDate = LetterDate,
		 @lLetterTo = LetterTo,
		 @lLetterSubject = LetterSubject,
		 @lIsReplyRequired = IsReplyRequired,
		 @lIsReplied = IsReplied,
		 @lReplyDetail = ReplyDetail,
		 @lRemark = Remark,
		 @lLetterRemark = LetterRemark
FROM #tTable1 WHERE Id = @lCount 

			DECLARE @lNextNumber BIGINT	
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tOutwardRegister', 0, 1, 1,@outNextNumber = @lNextNumber output

			DECLARE @lOutwardNumber INT 

			DECLARE @lConfigValue nvarchar(50)=''
			SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 299 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

			IF @lConfigValue = ''
			  SET @lConfigValue = 'False'
			
			IF @lConfigValue = 'True'
			BEGIN
				SELECT @lOutwardNumber = ISNULL(MAX(OutwardNumber),0)+1  FROM sFrontOffice.tOutwardRegister where OrgId= @rOrgId AND BatchId = @rBatchId
			END
			ELSE
			BEGIN
				SELECT @lOutwardNumber = ISNULL(MAX(OutwardNumber),0)+1  FROM sFrontOffice.tOutwardRegister where OrgId= @rOrgId 
			END

			INSERT INTO sFrontOffice.tOutwardRegister
			(
				OrgId,
				Id,
				OutwardNumber,
				OutwardDate,
				LetterNumber,
				LetterDate,
				LetterTo,
				LetterSubject,
				IsReplyRequired,
				IsReplied,
				ReplyDetail,
				InwardRegisterId,
				Remark,
				CreatedUserId,
				CreatedDateTime,
				BatchId,
				LetterRemark
			)
			VALUES
			(
				@rOrgId,	
				@lNextNumber,
				@lOutwardNumber,
				@lOutwardDate,					
				@lLetterNumber,
				@lLetterDate,
				@lLetterTo,
				@lLetterSubject,
				@lIsReplyRequired,
				@lIsReplied,
				@lReplyDetail,
				0,
				@lRemark,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rBatchId,
				@lLetterRemark 
			)
				
		SET @lCount = @lCount - 1
	SELECT 1 AS Result, '' AS ResultDetail				

 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFrontOffice].[pInwardRegisterAdd]
	 
		@rOrgId smallint,
        @rId int,
        @rInwardNumber	int	,
        @rLetterNumber	nvarchar(100),
        @rLetterDate	date,
        @rReceivedDate	date,
        @rLetterFrom	nvarchar(300),	
        @rLetterSubject	nvarchar(300),
        @rIsReplyRequired	bit	,
        @rIsReplied	bit	,
        @rReplyDetail	nvarchar(100),
        @rOutwardRegisterId	int	,
        @rRemark nvarchar(300),
        @rCreatedUserId bigint,
		--@rCreatedDateTime date,
		@rBatchId	int,
		@rLetterRemark  nvarchar(max)
		
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tInwardRegister', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tInwardRegister
		(
			OrgId,
			Id,
			InwardNumber,
			LetterNumber,
			LetterDate,
			ReceivedDate,
			LetterFrom,
			LetterSubject,
			IsReplyRequired,
			IsReplied,
			ReplyDetail,
			OutwardRegisterId,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			BatchId,
			LetterRemark
			
			
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rInwardNumber,
			@rLetterNumber,
			@rLetterDate,
			@rReceivedDate,
			@rLetterFrom,
			@rLetterSubject,
			@rIsReplyRequired,
			@rIsReplied,
			@rReplyDetail,
			@rOutwardRegisterId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rBatchId,
			@rLetterRemark
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tInwardRegister
	    SET
			
			OrgId=@rOrgId,
			Id=@rId,
			InwardNumber=@rInwardNumber,
			LetterNumber=@rLetterNumber,
			LetterDate=@rLetterDate,
			ReceivedDate=@rReceivedDate,
			
			LetterFrom=@rLetterFrom,
			LetterSubject=@rLetterSubject,
			IsReplyRequired=@rIsReplyRequired,
			IsReplied=@rIsReplied,
			ReplyDetail=@rReplyDetail,
			OutwardRegisterId=@rOutwardRegisterId,
			Remark=@rRemark,
			CreatedUserId=@rCreatedUserId,
			--CreatedDateTime=sCommon.fGetDate(),
			BatchId=@rBatchId,
			LetterRemark =@rLetterRemark
	      
	      
	      WHERE Id = @rId
	      AND 
	      OrgId=@rOrgId
	     
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pInwardRegisterGet]

	
	 @rId int = 0,
	 @rOrgId smallint=0,
	 @rFromDate date,
	 @rToDate date,
	 @rLetterFrom nvarchar(300),
	 @rLetterSubject nvarchar(300),
	 @rIsReplyRequired bit,
	 @rReplied int
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			--SET @rLetterFrom = sCommon.fSearchStringGet(@rLetterFrom) 
			
BEGIN 
	 
	SELECT 
	
			OrgId,
			Id,
			InwardNumber,
			LetterNumber,
			ISNULL(LetterDate,'0001/01/01') AS LetterDate,
			ReceivedDate,
			LetterFrom,
			LetterSubject,
			IsReplyRequired,
			IsReplied,
			ReplyDetail,
			ISNULL(OutwardRegisterId,0) AS OutwardRegisterId,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			BatchId,
			LetterRemark
      
  FROM 
           sFrontOffice.tInwardRegister
            
  WHERE 
  
      ((Id = @rId) OR (@rId = 0))
    AND ((LetterFrom LIKE @rLetterFrom) OR (ISNULL(@rLetterFrom,'') = ''))
	AND (( ReceivedDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND (( ReceivedDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((LetterSubject LIKE @rLetterSubject) OR (ISNULL(@rLetterSubject,'') = ''))
	AND  ((IsReplyRequired=@rIsReplyRequired) OR(ISNULL(@rIsReplyRequired,0)=0))
	AND((IsReplied=@rReplied)  OR (ISNULL(@rReplied,2)=2))
	
	
	AND OrgId=@rOrgId
	
	Order by CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFrontOffice].[pLostFoundRegisterAdd]
	  
		@rOrgGroupId smallint,
		@rOrgId smallint=0,
        @rId int,
        @rFoundNumber int,
        @rFoundDate date,
        @rItemType nvarchar(150),
		@rItemDescription nvarchar(300),
		@rLostFoundStatusId smallint,
		@rOwnerSourceTypeId smallint,
		@rOwnwerSourceId bigint,
		@rOwnerDetail nvarchar(200),
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
		IF EXISTS (SELECT Id FROM sFrontOffice.tLostFoundRegister WHERE OrgGroupId = @rOrgGroupId AND FoundNumber= @rFoundNumber)
		BEGIN
		SELECT  -101 AS  Result
		COMMIT TRANSACTION
		RETURN
		END
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFrontOffice.tLostFoundRegister', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tLostFoundRegister
		(
			OrgGroupId,
			OrgId,
			Id,
			FoundNumber,
			FoundDate,
			ItemType,
			ItemDescription,
			LostFoundStatusId,
			OwnerSourceTypeId,
			OwnwerSourceId,
			OwnerDetail,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgId,
			@lNextNumber,
			@rFoundNumber,
			@rFoundDate,
			@rItemType,
			@rItemDescription,
			@rLostFoundStatusId,
			@rOwnerSourceTypeId,
			@rOwnwerSourceId,
			@rOwnerDetail,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rUpdatedUserId	,	
			sCommon.fGetDate()
		)
		   
		    SELECT @lNextNumber AS Result
	
	--COMMIT TRANSACTION  
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tLostFoundRegister
	    SET
			
			OrgGroupId=@rOrgGroupId,
			OrgId=@rOrgId,
			Id=@rId,
			FoundNumber=@rFoundNumber,
			FoundDate=@rFoundDate,
			ItemType=@rItemType,
			ItemDescription=@rItemDescription,
			LostFoundStatusId=@rLostFoundStatusId,
			OwnerSourceTypeId=@rOwnerSourceTypeId,
			OwnwerSourceId=@rOwnwerSourceId,
			OwnerDetail=@rOwnerDetail,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      
	      WHERE Id = @rId
	       AND  OrgGroupId=@rOrgGroupId
	     
	      --AND 
	    --  OrgId=@rOrgId

	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pLostFoundRegisterGet]

	 @rOrgGroupId smallint=0,
	 @rId int = 0,
	 @rFoundNumber int,
	 @rOrgId smallint=0,
	 @rFromDate date,
	 @rToDate date,
	 @rLostFoundStatusId  bigint=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
--SET NOCOUNT ON
--			 SET @rDispatchedTo = sCommon.fSearchStringGet(@rDispatchedTo) 

BEGIN 
	 
	
	SELECT 
			LF.Id As LostFoundRegisterId,
			LF.OrgGroupId,
			LF.OrgId,
			--LF.Id,
			LF.FoundNumber,
			LF.FoundDate,
			LF.ItemType,
			LF.ItemDescription,
			LF.LostFoundStatusId,
			LF.OwnerSourceTypeId,
			LF.OwnwerSourceId,
			LF.OwnerDetail,
			LF.CreatedUserId,
			LF.CreatedDateTime,
			LF.UpdatedUserId,
			LF.UpdatedDateTime,
			SM.Title,
			SM.Id,
			(CASE WHEN LF.OwnerSourceTypeId=2003 THEN  SMast.Code
			WHEN  LF.OwnerSourceTypeId=95  THEN EM.Code  ElSE ''
			 END) AS Code
			
			
      
  FROM 
            sFrontOffice.tLostFoundRegister LF INNER JOIN 
            sCommon.tStatusMaster SM ON SM.Id=LF.LostFoundStatusId 
            LEFT JOIN sStudent.vStudentLastAcademic SMast ON SMast.StudentId = LF.OwnwerSourceId  AND LF.OwnerSourceTypeId=2003
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = LF.OwnwerSourceId  AND LF.OwnerSourceTypeId=95
            
            
            
            
  WHERE 
  
      ((LF.Id = @rId) OR (@rId = 0))
     AND ((LF.FoundNumber = @rFoundNumber) OR (@rFoundNumber = 0))
	--AND ((FoundDate LIKE @rFoundDate) OR (ISNULL(@rFoundDate,'') = ''))
	AND ((LF.FoundDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((LF.FoundDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND  LF.OrgGroupId=@rOrgGroupId
	AND  ((LF.LostFoundStatusId=@rLostFoundStatusId) OR (@rLostFoundStatusId = 0))
	AND ((LF.OrgId = @rOrgId) OR (@rOrgId = 0))
	AND ((LF.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	AND ISNULL(EM.IsOtherUser,0) = 0
	
	Order by CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pLostFoundRegisterScopeGet]
	 @rLostFoundRegisterId bigint,
	 @rOrgId smallint,
	 @rUserId bigint=0,
	 @rBatchId bigint=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lOrgGroupId int = 0
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	
	DECLARE @LostAndFoundEntryBasedOn nvarchar(100)
	SELECT @LostAndFoundEntryBasedOn = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 342 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
	
	IF (@LostAndFoundEntryBasedOn IS NULL)
	BEGIN
		
		SELECT 
			DISTINCT DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as ClassDept,
			2005 as SourceTypeId,
			CASE WHEN LFR.SourceId IS NULL OR LFR.LostFoundRegisterId!=@rLostFoundRegisterId THEN 0 ELSE 1 END AS IsObsolete,
			CM.OrderIndex+DM.OrderIndex AS OrderIndex,
			@rBatchId As BatchId
		--FROM 
		--	sSetup.tDivisionMaster DM
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
		--	LEFT JOIN sFrontOffice.tLostFoundRegisterScope LFR ON LFR.SourceId=DM.Id AND LFR.SourceTypeId=2005 AND LFR.LostFoundRegisterId=@rLostFoundRegisterId
		--	INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
		--	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
		--	INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId 
		--	--AND BC.BatchId=@rBatchId
		--WHERE DM.OrgId=@rOrgId
		--AND (U.UserId = @rUserId OR @rUserId =0)
			FROM 
				sSetup.tDivisionMaster DM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
				LEFT JOIN sFrontOffice.tLostFoundRegisterScope LFR ON LFR.SourceId=DM.Id AND LFR.SourceTypeId=2005 AND LFR.LostFoundRegisterId=@rLostFoundRegisterId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
				INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId AND BC.BatchId=@rBatchId
				WHERE DM.OrgId=@rOrgId 
			AND (U.UserId = @rUserId OR @rUserId =0)
		
		UNION ALL
		
		SELECT 
			DISTINCT ODM.Id  as SourceId,
			ODM.Title as ClassDept,
			2017 as SourceTypeId,
			CASE WHEN LFR.SourceId IS NULL OR LFR.LostFoundRegisterId!=@rLostFoundRegisterId THEN 0 ELSE 1 END AS IsObsolete,
			0 AS OrderIndex,
			0 AS BatchId 
		FROM 
			sSetup.tDepartmentMaster ODM  
			LEFT JOIN sFrontOffice.tLostFoundRegisterScope LFR ON LFR.SourceId=ODM.Id AND LFR.SourceTypeId=2017 AND LFR.LostFoundRegisterId=@rLostFoundRegisterId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = ODM.Id AND U.SourceTypeId=2017
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ODM.OrgId
		WHERE ODM.OrgId=@rOrgId
		AND (U.UserId = @rUserId OR @rUserId =0)
	END
	ELSE 
	BEGIN
		IF(@LostAndFoundEntryBasedOn='Common')
		BEGIN
			
			SELECT 
				DISTINCT DM.Id  as SourceId,
				CM.Title+'-'+DM.Title as ClassDept,
				2005 as SourceTypeId,
				CASE WHEN LFR.SourceId IS NULL OR LFR.LostFoundRegisterId!=@rLostFoundRegisterId THEN 0 ELSE 1 END AS IsObsolete,
				CM.OrderIndex+DM.OrderIndex AS OrderIndex,
				@rBatchId As BatchId
			FROM 
				sSetup.tDivisionMaster DM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
				LEFT JOIN sFrontOffice.tLostFoundRegisterScope LFR ON LFR.SourceId=DM.Id AND LFR.SourceTypeId=2005 AND LFR.LostFoundRegisterId=@rLostFoundRegisterId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId=2005
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
				INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId AND BC.BatchId=@rBatchId
			WHERE DM.OrgId=@rOrgId 
			AND (U.UserId = @rUserId OR @rUserId =0)
			
			UNION ALL
			
			SELECT 
				DISTINCT ODM.Id  as SourceId,
				ODM.Title as ClassDept,
				2017 as SourceTypeId,
				CASE WHEN LFR.SourceId IS NULL OR LFR.LostFoundRegisterId!=@rLostFoundRegisterId THEN 0 ELSE 1 END AS IsObsolete,
				0 AS OrderIndex,
				0 AS BatchId 
			FROM 
				sSetup.tDepartmentMaster ODM  
				LEFT JOIN sFrontOffice.tLostFoundRegisterScope LFR ON LFR.SourceId=ODM.Id AND LFR.SourceTypeId=2017 AND LFR.LostFoundRegisterId=@rLostFoundRegisterId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = ODM.Id AND U.SourceTypeId=2017
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ODM.OrgId
			WHERE ODM.OrgId=@rOrgId
			AND (U.UserId = @rUserId OR @rUserId =0)
		END
		ELSE
		BEGIN
			DECLARE @lEmployeeId bigint  = 0
			SELECT @lEmployeeId=SourceId FROM sSecurity.tUser WHERE Id=@rUserId
			
			SELECT 
				DISTINCT DM.Id  as SourceId,
				CM.Title+'-'+DM.Title as ClassDept,
				2005 as SourceTypeId,
				CASE WHEN LFR.SourceId IS NULL OR LFR.LostFoundRegisterId!=@rLostFoundRegisterId THEN 0 ELSE 1 END AS IsObsolete,
				CM.OrderIndex+DM.OrderIndex AS OrderIndex,
				@rBatchId As BatchId
			FROM 
				sSetup.tDivisionMaster DM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
				LEFT JOIN sFrontOffice.tLostFoundRegisterScope LFR ON LFR.SourceId=DM.Id AND LFR.SourceTypeId=2005 AND LFR.LostFoundRegisterId=@rLostFoundRegisterId
				INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id 
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
				INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId  
				--AND BC.BatchId=@rBatchId
			WHERE DM.OrgId=@rOrgId  AND (TSD.EmployeeId = @lEmployeeId or ISNULL(@lEmployeeId,0)=0)
			
			UNION ALL
			
			SELECT 
				DISTINCT ODM.Id  as SourceId,
				ODM.Title as ClassDept,
				2017 as SourceTypeId,
				CASE WHEN LFR.SourceId IS NULL OR LFR.LostFoundRegisterId!=@rLostFoundRegisterId THEN 0 ELSE 1 END AS IsObsolete,
				0 AS OrderIndex,
				0 AS BatchId 
			FROM 
				sSetup.tDepartmentMaster ODM  
				LEFT JOIN sFrontOffice.tLostFoundRegisterScope LFR ON LFR.SourceId=ODM.Id AND LFR.SourceTypeId=2017 AND LFR.LostFoundRegisterId=@rLostFoundRegisterId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = ODM.Id AND U.SourceTypeId=2017
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ODM.OrgId
			WHERE ODM.OrgId=@rOrgId
			AND (U.UserId = @rUserId OR @rUserId =0)
		END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFrontOffice].[pOutwardRegisterAdd]
	 
		@rOrgId smallint,
        @rId int,
        @rOutwardNumber	int	,
        @rOutwardDate date,
        @rLetterNumber	nvarchar(100),
        @rLetterDate	date,
        @rLetterTo nvarchar(300),
        @rLetterSubject	nvarchar(300),
        @rIsReplyRequired	bit	,
        @rIsReplied	bit	,
        @rReplyDetail	nvarchar(100),
        @rInwardRegisterId	int	,
        @rRemark nvarchar(300),
        @rCreatedUserId bigint,
		@rBatchId	int,
		@rLetterRemark nvarchar(max)
		
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY

	
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tOutwardRegister', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tOutwardRegister
		(
			OrgId,
			Id,
			OutwardNumber,
			OutwardDate,
			LetterNumber,
			LetterDate,
			LetterTo,
			LetterSubject,
			IsReplyRequired,
			IsReplied,
			ReplyDetail,
			InwardRegisterId,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			BatchId,
			LetterRemark
			
			
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rOutwardNumber,
			@rOutwardDate,
			@rLetterNumber,
			@rLetterDate,
			@rLetterTo,
			@rLetterSubject,
			@rIsReplyRequired,
			@rIsReplied,
			@rReplyDetail,
			@rInwardRegisterId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rBatchId,
			@rLetterRemark
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tOutwardRegister
	    SET
			
			OrgId=@rOrgId,
			Id=@rId,
			OutwardNumber=@rOutwardNumber,
			OutwardDate=@rOutwardDate,
			LetterNumber=@rLetterNumber,
			LetterDate=@rLetterDate,
			LetterTo=@rLetterTo,
			LetterSubject=@rLetterSubject,
			IsReplyRequired=@rIsReplyRequired,
			IsReplied=@rIsReplied,
			ReplyDetail=@rReplyDetail,
			InwardRegisterId=@rInwardRegisterId,
			Remark=@rRemark,
			--CreatedUserId=@rCreatedUserId,
			--CreatedDateTime=sCommon.fGetDate(),
			BatchId=@rBatchId,
			LetterRemark =@rLetterRemark
	      
	      
	      WHERE Id = @rId
	      AND 
	      OrgId=@rOrgId
	     
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pOutwardRegisterGet]

	
	 @rId int = 0,
	 @rOrgId smallint=0,
	 @rFromDate date,
	 @rToDate date,
	 @rLetterTo nvarchar(300),
	 @rLetterSubject nvarchar(300),
	 @rIsReplyRequired bit,
	 @rReplied int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			--SET @rLetterFrom = sCommon.fSearchStringGet(@rLetterFrom) 
			
BEGIN 
	 
	SELECT 
	
			OrgId,
			Id,
			OutwardNumber,
			LetterNumber,
			OutwardDate,
			ISNULL(LetterDate,'0001/01/01') AS LetterDate,
			LetterTo,
			LetterSubject,
			IsReplyRequired,
			IsReplied,
			ReplyDetail,
			ISNULL(InwardRegisterId,0) AS InwardRegisterId,
			Remark,
			BatchId,
			LetterRemark
      
  FROM 
           sFrontOffice.tOutwardRegister
            
  WHERE 
  
      ((Id = @rId) OR (@rId = 0))
    AND ((LetterTo LIKE @rLetterTo) OR (ISNULL(@rLetterTo,'') = ''))
	AND (( OutwardDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND (( OutwardDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((LetterSubject LIKE @rLetterSubject) OR (ISNULL(@rLetterSubject,'') = ''))
	AND  ((IsReplyRequired=@rIsReplyRequired) OR(ISNULL(@rIsReplyRequired,0)=0))
	AND((IsReplied=@rReplied)  OR (ISNULL(@rReplied,2)=2))
	AND OrgId=@rOrgId
	
	Order by CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sFrontOffice].[pRptInwardRegisterGet]

	
	--@rId int = 0,
	 @rOrgId smallint=0,
	 @rFromDate date,
	 @rToDate date,
	 @rLetterFrom nvarchar(300),
	 @rLetterSubject nvarchar(300),
	 @rIsReplyRequired bit,
	 @rReplied int,
	 @rBuilder1 nvarchar(max)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			--SET @rLetterFrom = sCommon.fSearchStringGet(@rLetterFrom) 
			
BEGIN 
	 
	SELECT 
			@rBuilder1 AS Builder1,
			IR.InwardNumber,
			IR.LetterNumber AS InwardLetterNumber ,
			IR.LetterDate AS InwardLetterDate,
			IR.ReceivedDate,
			IR.LetterFrom,
			IR.LetterSubject,
			IR.ReplyDetail,
			IR.Remark,
			OWR.LetterNumber As OutwardLetterNumber,
			OWR.LetterDate As OutwardLetterDate,
			OWRO.LetterDate ,
			OWRO.LetterNumber 
			
		
      
  FROM 
           sFrontOffice.tInwardRegister IR
           LEFT JOIN  sFrontOffice.tOutwardRegister OWR ON IR.Id=OWR.InwardRegisterId
           LEFT JOIN  sFrontOffice.tOutwardRegister OWRO ON OWRO.Id = ir.OutwardRegisterId
                
            
  WHERE 
  
     -- ((Id = @rId) OR (@rId = 0))
     ((IR.LetterFrom LIKE @rLetterFrom) OR (ISNULL(@rLetterFrom,'') = ''))
	AND (( IR.ReceivedDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((IR. ReceivedDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((IR.LetterSubject LIKE @rLetterSubject) OR (ISNULL(@rLetterSubject,'') = ''))
	AND  ((IR.IsReplyRequired=@rIsReplyRequired) OR(ISNULL(@rIsReplyRequired,0)=0))
	AND((IR.IsReplied=@rReplied)  OR (ISNULL(@rReplied,2)=2))
	AND IR.OrgId=@rOrgId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFrontOffice].[pRptOutwardRegisterGet]

	
	--@rId int = 0,
	 @rOrgId smallint=0,
	 @rFromDate date='',
	 @rToDate date='',
	 @rLetterTo nvarchar(300)='',
	 @rLetterSubject nvarchar(300)='',
	 @rIsReplyRequired bit=0,
	 @rReplied int=0,
	 @rOutwardNumber int=0,
	 @rBuilder1 nvarchar(max)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			--SET @rLetterFrom = sCommon.fSearchStringGet(@rLetterFrom) 
			
BEGIN 
	 
	SELECT 
			@rBuilder1 AS Builder1,
			OWR.OutwardNumber,
			OWR.LetterNumber AS OutwardLetterNumber,
			OWR.LetterDate AS OutwardLetterDate ,
			OWR.OutwardDate,
			OWR.LetterTo,
			OWR.LetterSubject,
			OWR.ReplyDetail,
			OWR.Remark,
			IR.LetterDate As InwardLetterDate,
			IR.LetterNumber As InwardLetterNumber,
			IRO.LetterDate ,
			IRO.LetterNumber,
			OWR.LetterRemark,
			OM.Title AS OrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			OM.OrgLogo
			
		
      
  FROM 
           sFrontOffice.tOutwardRegister OWR
           LEFT JOIN  sFrontOffice.tInwardRegister IR ON OWR.Id=IR.OutwardRegisterId
           LEFT JOIN  sFrontOffice.tInwardRegister IRO ON IRO.Id = OWR.InwardRegisterId
           INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=OWR.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
            
            
  WHERE 
  
     -- ((Id = @rId) OR (@rId = 0))
     ((OWR.LetterTo LIKE @rLetterTo) OR (ISNULL(@rLetterTo,'') = ''))
	AND ((OWR. OutwardDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND (( OWR.OutwardDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((OWR.LetterSubject LIKE @rLetterSubject) OR (ISNULL(@rLetterSubject,'') = ''))
	AND  ((OWR.IsReplyRequired=@rIsReplyRequired) OR(ISNULL(@rIsReplyRequired,0)=0))
	AND((OWR.IsReplied=@rReplied)  OR (ISNULL(@rReplied,2)=2))
	AND OWR.OrgId=@rOrgId
	AND ((OWR.OutwardNumber=@rOutwardNumber) OR (@rOutwardNumber=0))
	
	ORDER BY OWR.OutwardNumber ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pStudentGatePassAdd]
	
	@rOrgId int, 
	@rId int,
	@rAcademicId bigint,
	@rRelationshipId tinyint,
	@rRelation nvarchar(50),
	@rVisitorName nvarchar(100),
	@rVisitorMobile nvarchar(50),
	@rReasonOfGatePass nvarchar(200),
	@rVisitorPhoto varbinary(max),
	@rGatePassDate date,
	@rReturnGatePassDate date,
	@rGatePassTime datetime,
	@rReturnGatePassTime datetime,
	@rEntryModeStatusId smallint,
	@rCreatedUserId bigint,
	@rRemark nvarchar(200)='',
	@rGatePassNo nvarchar(20) = ''	--Mantis: 39477, change bigint to nvarchar(20)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tStudentGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sFrontOffice.tStudentGatePass
		(
			OrgId,
			Id,
			AcademicId,
			RelationshipId,
			Relation,
			VisitorName,
			VisitorMobile,
			ReasonOfGatePass,
			VisitorPhoto,
			GatePassDate,
			ReturnGatePassDate,
			GatePassTime,
			ReturnGatePassTime,
			EntryModeStatusId,
			CreatedUserId,
			CreatedDateTime,
			Remark,
			GatePassNo
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rAcademicId,
			@rRelationshipId,
			@rRelation,
			@rVisitorName,
			@rVisitorMobile,
			@rReasonOfGatePass,
			@rVisitorPhoto,
			@rGatePassDate,
			Null,
			@rGatePassTime,
			Null,
			@rEntryModeStatusId,
			@rCreatedUserId,
			sCommon.fGetDate()	,
			@rRemark,
			@rGatePassNo
		)
		             
END	 
	 ELSE
BEGIN
	SET @lNextNumber = @rId
	UPDATE  sFrontOffice.tStudentGatePass
	SET
		RelationshipId=@rRelationshipId,
		Relation=@rRelation,
		VisitorName=@rVisitorName,
		VisitorMobile=@rVisitorMobile,
		ReasonOfGatePass=@rReasonOfGatePass,
		VisitorPhoto=@rVisitorPhoto,
		GatePassDate=@rGatePassDate,
		ReturnGatePassDate=@rReturnGatePassDate,
		GatePassTime=@rGatePassTime,
		ReturnGatePassTime=@rReturnGatePassTime,
		EntryModeStatusId=@rEntryModeStatusId,
		Remark=@rRemark

	WHERE Id = @rId 	   
END  
	
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sFrontOffice].[pStudentGatePassGet]

			@rId int,
			@rOrgId int=0,
			@rFromGatePassDate datetime='',
			@rToGatePassDate datetime='',
			@rEntryModeStatusId smallint=0,
			@rCode nvarchar(20)='',
			@rIsPrintView bit=0,
			@rOrgGroupId int=0,
			@rUserId bigint= 0,
			@rDepartmentId int=0,
			@rClassId int=0,
			@rDivisionId int=0,
			@rUserSourceTypeId int = 0,
			@rBatchId int = 0
AS
SET NOCOUNT ON
BEGIN
	Declare @GatePassConfig nvarchar(20)=''
	SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
	IF (@rUserSourceTypeId = 0 OR @rUserSourceTypeId = 1)
	BEGIN
		SELECT
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.MiddleName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			--(CASE WHEN @rIsPrintView=1 THEN SGP.VisitorPhoto
			--	ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			CASE 
				WHEN @rIsPrintView = 1 THEN 
					CASE 
						WHEN ISNULL(DATALENGTH(SGP.VisitorPhoto), 0) > 4 THEN SGP.VisitorPhoto
						ELSE NULL  -- -- Add DATALENGTH Condition Report not open if VisitorPhoto = 0x00000000	MantisId : 0042932
					END
				ELSE 
					ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0))
			END AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.ReturnGatePassDate,'') As ReturnGatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.ReturnGatePassTime,'') As ReturnGatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			(CASE WHEN @rIsPrintView=1 THEN SI.StudentPhoto
				ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,

			(CASE WHEN @rIsPrintView=1 THEN SI.FatherPhoto
				ELSE ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS FatherPhoto,

			(CASE WHEN @rIsPrintView=1 THEN SI.MotherPhoto
				ELSE ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS MotherPhoto,

			(CASE WHEN @rIsPrintView=1 THEN SI.RelativePhoto
				ELSE ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) END) AS RelativePhoto,

			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue,
			SF.FatherContactNo,
			SF.MotherContactNo,
			SF.RelativeContactNo,
			SF.FatherName,
			SF.MotherName,
			SF.RelativeName,
			ISNULL(SGP.GatePassNo,'') AS GatePassNo,	--mantis: 39477, change ISNULL(SGP.GatePassNo,0) => ISNULL(SGP.GatePassNo,'')
		    --added by megha for 0027081
			CONVERT(VARCHAR, ISNULL(SGP.GatePassTime,''), 100) AS GatePassTime_12hours,
			(CASE WHEN @GatePassConfig='Image' THEN					--Add For 27089 mantis
				OI.CertificateHeaderA4
				ELSE NULL END) AS CertificateHeaderA4,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo
		FROM
			sStudent.vStudentAcademic vSA
				INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
				INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId
				INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
				LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SI.StudentId
				LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
				LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = vSA.OrgId			--Add For 27089 mantis
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SI.StudentId

		WHERE
			((SGP.Id=@rId) OR (@rId=0))
				AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
				AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
				AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
				AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
				AND (OM.OrgGroupId=@rOrgGroupId)
				AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				--AND vSA.IsActiveBatch=1
		ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
	END

	ELSE				-- Mantis id : 0038701 ( Add Else condition for User wise Data get)
	BEGIN
		IF OBJECT_ID('tempdb..#DivisionTemp') IS NOT NULL
			DROP TABLE #DivisionTemp;

		CREATE TABLE #DivisionTemp
		(
			DivisionId int
		);

		DECLARE @lStudentGatePassEntryBasedOn nvarchar(50)=''
		SELECT @lStudentGatePassEntryBasedOn = ItemValue From sConfig.tConfigurationSetup
		WHERE ConfigurationId = 591 AND SourceId = @rOrgGroupId
		DECLARE @lTeacherId bigint=0;
		SELECT @lTeacherId=SourceId From sSecurity.tUser Where Id=@rUserId AND SourceTypeId=95

		IF(@lStudentGatePassEntryBasedOn = 'Class Teacher')
		BEGIN
			INSERT INTO #DivisionTemp
			SELECT DISTINCT DM.Id AS DivisionId
			FROM sSetup.tClassMaster CM
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
			WHERE DM.InchargeemployeeID=@lTeacherId AND OM.OrgGroupId=@rOrgGroupId
		END
		ELSE IF(@lStudentGatePassEntryBasedOn = 'Class Teacher Batch')
		BEGIN
			INSERT INTO #DivisionTemp
			SELECT DISTINCT  DM.Id AS DivisionId
			FROM sSetup.tClassMaster CM
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
				INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
			WHERE DIE.EmployeeID=@lTeacherId   AND OM.OrgGroupId=@rOrgGroupId	AND (DIE.BatchId = @rBatchId OR @rBatchId = 0)
		END
		ELSE IF(@lStudentGatePassEntryBasedOn = 'Academic Setup')
		BEGIN
			INSERT INTO #DivisionTemp
			SELECT DISTINCT DivisionId
			FROM sAcademic.vTeacherSubjectDivision TSD INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=TSD.OrgId
			WHERE  TSD.EmployeeId= @lTeacherId
		END
		ELSE IF(@lStudentGatePassEntryBasedOn = 'User Access')
		BEGIN
			INSERT INTO #DivisionTemp
			SELECT DISTINCT DM.Id AS DivisionId
			FROM sSetup.tDivisionMaster DM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
				INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId= 2005
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
			WHERE  UserId = @rUserId
		END

		SELECT
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.MiddleName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			--(CASE  WHEN @rIsPrintView=1 THEN SGP.VisitorPhoto
			--	ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			CASE 
				WHEN @rIsPrintView = 1 THEN 
					CASE 
						WHEN ISNULL(DATALENGTH(SGP.VisitorPhoto), 0) > 4 THEN SGP.VisitorPhoto
						ELSE NULL  -- -- Add DATALENGTH Condition Report not open if VisitorPhoto = 0x00000000		MantisId : 0042932
					END
				ELSE 
					ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0))
			END AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.ReturnGatePassDate,'') As ReturnGatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.ReturnGatePassTime,'') As ReturnGatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN SI.StudentPhoto
				ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,

			(CASE  WHEN @rIsPrintView=1 THEN SI.FatherPhoto
				ELSE ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS FatherPhoto,

			(CASE  WHEN @rIsPrintView=1 THEN SI.MotherPhoto
				ELSE ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS MotherPhoto,

			(CASE  WHEN @rIsPrintView=1 THEN SI.RelativePhoto
				ELSE ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) END) AS RelativePhoto,

			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue,
			SF.FatherContactNo,
			SF.MotherContactNo,
			SF.RelativeContactNo,
			SF.FatherName,
			SF.MotherName,
			SF.RelativeName,
			ISNULL(SGP.GatePassNo,'') AS GatePassNo,	--mantis: 39477, change ISNULL(SGP.GatePassNo,0) => ISNULL(SGP.GatePassNo,'')
		    --added by megha for 0027081
			CONVERT(VARCHAR, ISNULL(SGP.GatePassTime,''), 100) AS GatePassTime_12hours,
			(CASE WHEN @GatePassConfig='Image' THEN					--Add For 27089 mantis
				OI.CertificateHeaderA4
				ELSE NULL END) AS CertificateHeaderA4,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo
		FROM
		    sStudent.vStudentAcademic vSA
			INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SI.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = vSA.OrgId			--Add For 27089 mantis
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SI.StudentId
			INNER JOIN #DivisionTemp TempDiv On TempDiv.DivisionId= vSA.DivisionId

		WHERE
			((SGP.Id=@rId) OR (@rId=0))
			AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND (OM.OrgGroupId=@rOrgGroupId)
			AND ((vSA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			--AND vSA.IsActiveBatch=1
			ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
	END

	--mantis: 39477, add below select for the rdlc report of the studentgatepass because when we replace the dataset then it will give an error of temp table
	--SELECT
	--	0 AS Id,
	--	'' AS Code,
	--	'' AS Name,
	--	'' AS Class,
	--	CONVERT(bigint,0) AS AcademicId,
	--	CONVERT(tinyint,0) AS RelationshipId,
	--	'' AS Relationship,
	--	'' AS Relation,
	--	'' AS VisitorName,
	--	'' AS VisitorMobile,
	--	'' AS ReasonOfGatePass,
	--	CONVERT(VARBINARY(MAX), '0x') AS VisitorPhoto,
	--	CONVERT(date,'') AS GatePassDate,
	--	CONVERT(date,'') AS ReturnGatePassDate,
	--	CONVERT(TIME,'') AS GatePassTime,
	--	CONVERT(TIME,'') As ReturnGatePassTime,
	--	CONVERT(smallint,0) AS EntryModeStatusId,
	--	''  AS EntryModeStatus,
	--	CONVERT(smallint,0) AS OrgId,
	--	CONVERT(VARBINARY(MAX), '0x') AS OrgLogo,
	--	'' AS Organization,
	--	CONVERT(VARBINARY(MAX), '0x') AS StudentPhoto,
	--	CONVERT(VARBINARY(MAX), '0x') AS FatherPhoto,
	--	CONVERT(VARBINARY(MAX), '0x') AS MotherPhoto,
	--	CONVERT(VARBINARY(MAX), '0x') AS RelativePhoto,
	--	'' AS UserName,
	--	'' AS SUId,
	--	'' AS Remark,
	--	'' AS ConfigValue,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo,
	--	'' AS RelativeContactNo,
	--	'' AS FatherName,
	--	'' AS MotherName,
	--	'' AS RelativeName,
	--	'' AS GatePassNo,
	--	'' AS GatePassTime_12hours,
	--	CONVERT(VARBINARY(MAX), '0x') AS CertificateHeaderA4,
	--	'' AS StudentContactNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pStudentGatePassUserControlStudentSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(50)='',
	@rUserId Bigint = 0

	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
BEGIN
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
END
	
	DECLARE @lOrgGroupId int=0
	DECLARE @lConfigValue nvarchar(50), @lIsStudentCommonSearchBatchWise nvarchar(50)
	DECLARE @lIsInContext bit=0

	--Get Configuration value OrgGroup wise -- 0037540
	SELECT @lOrgGroupId = OGBM.OrgGroupId FROM sSetup.tBatchMaster BM INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId WHERE BM.Id=@rBatchId
	SELECT @lIsStudentCommonSearchBatchWise = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 508 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 480 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId

	IF OBJECT_ID('tempdb..#DivisionTemp') IS NOT NULL
			DROP TABLE #DivisionTemp;

		CREATE TABLE #DivisionTemp
		(
			DivisionId int
		);

		DECLARE @lStudentGatePassEntryBasedOn nvarchar(50)=''
		SELECT @lStudentGatePassEntryBasedOn = ItemValue From sConfig.tConfigurationSetup
		WHERE ConfigurationId = 591 AND SourceId = @lOrgGroupId
		DECLARE @lTeacherId bigint=0;
		SELECT @lTeacherId=SourceId From sSecurity.tUser Where Id=@rUserId AND SourceTypeId=95 

			IF(@lStudentGatePassEntryBasedOn = 'Class Teacher') 
				BEGIN
					INSERT INTO #DivisionTemp
					SELECT DISTINCT DM.Id AS DivisionId
					FROM sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
					WHERE DM.InchargeemployeeID=@lTeacherId   AND OM.OrgGroupId=@lOrgGroupId    
				END
			ELSE IF(@lStudentGatePassEntryBasedOn = 'Class Teacher Batch')
				BEGIN
					INSERT INTO #DivisionTemp
					SELECT DISTINCT  DM.Id AS DivisionId
					FROM sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 
					INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
					WHERE DIE.EmployeeId=@lTeacherId   AND OM.OrgGroupId=@lOrgGroupId   AND DIE.BatchId = @rBatchId
				END
			ELSE IF(@lStudentGatePassEntryBasedOn = 'Academic Setup')
				BEGIN
					INSERT INTO #DivisionTemp
					SELECT DISTINCT DivisionId
					 FROM sAcademic.vTeacherSubjectDivision  TSD INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=TSD.OrgId   
					 WHERE  TSD.EmployeeId= @lTeacherId
				END
			ELSE IF(@lStudentGatePassEntryBasedOn = 'User Access')
				BEGIN
					INSERT INTO #DivisionTemp
					SELECT DISTINCT DM.Id AS DivisionId
					FROM sSetup.tDivisionMaster DM INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId= 2005
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId   WHERE  UserId = @rUserId
				END
	
	IF (@lIsStudentCommonSearchBatchWise = 'True')
	BEGIN
		IF(@rRollNo IS NULL)  
		BEGIN  
			SELECT   
			  SA.AcademicId,  
			  SA.StudentId,  
			  SA.FirstName,  
			  SA.LastName,  
			  SA.MiddleName,  
			  SA.Name, 
			  [sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName,  -- Add for Mantis Id:0036025
			  SA.Code,  
			  SA.ClassId,  
			  SA.ClassName,  
			  SA.DivisionId,  
			  SA.DivisionName,  
			  SA.Number,  
			  SA.RollNo,  
			  SA.StatusId,  
			  SA.StatusName,  
			  SA.OrgId,  
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,  
			  SA.BatchId,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId,
			  ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			  SA.FeesRemark 
			   
			 FROM   sStudent.vStudentAcademic SA 
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId 
			    LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId  
				LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
				INNER JOIN #DivisionTemp TempDiv On TempDiv.DivisionId= SA.DivisionId
			 WHERE   
			  
			 ((SA.ClassId=@rClassId)OR(@rClassId=0))  
			 AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))  
			 AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = ''))   
			 AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))   
			 AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))   
			 AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))   
			 AND(SA.OrgId=@rOrgId OR @rOrgId = 0)  
			 AND ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 0)  
			 AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))  
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
		ELSE  
		BEGIN  
			SELECT   
			  SA.AcademicId,  
			  SA.StudentId,  
			  SA.FirstName,  
			  SA.LastName,  
			  SA.MiddleName,  
			  SA.Name,  
			  [sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName, 
			  SA.Code,  
			  SA.ClassId,  
			  SA.ClassName,  
			  SA.DivisionId,  
			  SA.DivisionName,  
			  SA.Number,  
			  SA.RollNo,  
			  SA.StatusId,  
			  SA.StatusName,  
			  SA.OrgId,
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId,
			  ISNULL(SC.ParentContactNo,'') AS ParentContactNo, 
			  SA.FeesRemark

			 FROM  sStudent.vStudentAcademic SA      
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId 
			    LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId           
				LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
				INNER JOIN #DivisionTemp TempDiv On TempDiv.DivisionId= SA.DivisionId
			 WHERE   
			  
			 ((SA.ClassId=@rClassId)OR(@rClassId=0))  
			 AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))  
			 AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = ''))   
			 AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))   
			 AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))   
			 AND(SA.RollNo=@rRollNo)  
			 AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))   
			 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
			 AND ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 0) 
			 AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))    
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
	END

	ELSE
	BEGIN
		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
		SET @lIsInContext = 1
		ELSE
		SET @lIsInContext = 0

		IF(@rRollNo IS NULL)
		BEGIN
			SELECT 
				SA.AcademicId,
				SA.StudentId,
				SA.FirstName,
				SA.LastName,
				SA.MiddleName,
				SA.Name,
				[sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName, 
				SA.Code,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.Number,
				SA.RollNo,
				SA.StatusId,
				SA.StatusName,
				SA.OrgId,
				ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
				SA.BatchId,
				SA.SUId,
				ISNULL(So.GenderId,0) AS GenderId,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SA.FeesRemark
		
			FROM sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND SA.OrgGroupBatchId = BM.OrgGroupBatchId 
	            LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId	            
				LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
				INNER JOIN #DivisionTemp TempDiv On TempDiv.DivisionId= SA.DivisionId
			WHERE 
				((SA.ClassId=@rClassId)OR(@rClassId=0))
				AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
				AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
				AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
				AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
				AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
				AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
				AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
				AND(SA.BatchId=@rBatchId or @rBatchId = 0)
				AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
				AND BM.IsInContext = @lIsInContext
	
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
		END

		ELSE
		BEGIN
			SELECT 
					SA.AcademicId,
					SA.StudentId,
					SA.FirstName,
					SA.LastName,
					SA.MiddleName,
					SA.Name,
					[sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName, 
					SA.Code,
					SA.ClassId,
					SA.ClassName,
					SA.DivisionId,
					SA.DivisionName,
					SA.Number,
					SA.RollNo,
					SA.StatusId,
					SA.StatusName,
					SA.OrgId,
					--SA.Age,
					ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,
					SA.SUId,
					ISNULL(So.GenderId,0) AS GenderId,
					SA.FeesRemark 
					
			FROM  sStudent.vStudentAcademic SA
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId   
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND SA.OrgGroupBatchId = BM.OrgGroupBatchId  
		        LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
				INNER JOIN #DivisionTemp TempDiv On TempDiv.DivisionId= SA.DivisionId
			WHERE 
					((SA.ClassId=@rClassId)OR(@rClassId=0))
					AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
					AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
					AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
					AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
					AND(SA.RollNo=@rRollNo)
					AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
					AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
					AND(SA.BatchId=@rBatchId or @rBatchId = 0)
					AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 
					AND BM.IsInContext = @lIsInContext
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
		END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pSummaryDashboardCountGet]
	 
	 @rTypeId smallint,
	 @rOrgId smallint,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	If @rTypeId = 0 -- Todays Count
	BEGIN
	
		DECLARE @lTodayVisitorCount int, @lTodayCourierDispatch int,@lTodayCourierReceive int,@lTodayStudentGatePass int,@lTodayEmployeeGatePassCount int
		
		SELECT @lTodayVisitorCount = COUNT(Id) from sFrontOffice.tVisitorLog Where OrgId = @rOrgId AND VisitDate = CONVERT(date,sCommon.fGetDate())
		
		SELECT @lTodayCourierDispatch = COUNT(Id) from sFrontOffice.tCourierDispatch Where OrgGroupId = @rOrgId AND DispatchDate = CONVERT(date,sCommon.fGetDate())
		
		SELECT @lTodayCourierReceive = COUNT(Id) from sFrontOffice.tCourierReceive Where OrgGroupId = @rOrgId AND ReceiveDate = CONVERT(date,sCommon.fGetDate())
		
		SELECT @lTodayStudentGatePass = COUNT(Id) from sFrontOffice.tStudentGatePass Where OrgId = @rOrgId AND GatePassDate = CONVERT(date,sCommon.fGetDate())
		
		SELECT @lTodayEmployeeGatePassCount = COUNT(Id) from sFrontOffice.tEmployeeGatePass Where OrgId = @rOrgId AND GatePassDate = CONVERT(date,sCommon.fGetDate())
		
		SELECT @lTodayVisitorCount AS TodayVisitorCount, @lTodayCourierDispatch + @lTodayCourierReceive AS TodayCourierCount,
		@lTodayStudentGatePass AS TodayStudentGatePass, @lTodayEmployeeGatePassCount AS TodayEmployeeGatePassCount
		
	END
	
	If @rTypeId = 1  -- Month Count
	BEGIN
	
		DECLARE @lMonthVisitorCount int, @lMonthCourierDispatch int,@lMonthCourierReceive int,@lMonthStudentGatePass int,@lMonthEmployeeGatePassCount int
		
		SELECT @lMonthVisitorCount = COUNT(Id) from sFrontOffice.tVisitorLog Where OrgId = @rOrgId AND MONTH(VisitDate) = MONTH(sCommon.fGetDate()) AND YEAR(VisitDate) = YEAR(sCommon.fGetDate())
		
		SELECT @lMonthCourierDispatch = COUNT(Id) from sFrontOffice.tCourierDispatch Where OrgGroupId = @rOrgId AND MONTH(DispatchDate) = MONTH(sCommon.fGetDate()) AND YEAR(DispatchDate) = YEAR(sCommon.fGetDate())
		
		SELECT @lMonthCourierReceive = COUNT(Id) from sFrontOffice.tCourierReceive Where OrgGroupId = @rOrgId AND MONTH(ReceiveDate) =  MONTH(sCommon.fGetDate()) AND YEAR(ReceiveDate) = YEAR(sCommon.fGetDate())
		
		SELECT @lMonthStudentGatePass = COUNT(Id) from sFrontOffice.tStudentGatePass Where OrgId = @rOrgId AND MONTH(GatePassDate) =  MONTH(sCommon.fGetDate()) AND YEAR(GatePassDate) = YEAR(sCommon.fGetDate())
		
		SELECT @lMonthEmployeeGatePassCount = COUNT(Id) from sFrontOffice.tEmployeeGatePass Where OrgId = @rOrgId AND MONTH(GatePassDate) =  MONTH(sCommon.fGetDate()) AND YEAR(GatePassDate) = YEAR(sCommon.fGetDate())
		
		SELECT @lMonthVisitorCount AS MonthVisitorCount, @lMonthCourierDispatch + @lMonthCourierReceive AS MonthCourierCount,
		@lMonthStudentGatePass AS MonthStudentGatePass, @lMonthEmployeeGatePassCount AS MonthEmployeeGatePassCount
	END
	
	If @rTypeId = 2 -- Month Wise Visitor Count
	BEGIN
		--Select M.Id,LEFT(M.Title,3) AS MonthName, COUNT(V.Id) AS VisitorCount from sCommon.tMonthMaster M
		--LEFT JOIN sFrontOffice.tVisitorLog V ON MONTH(V.VisitDate) = M.Id AND OrgId = @rOrgId
		--AND YEAR(V.VisitDate) = YEAR(sCommon.fGetDate())
		--GROUP BY M.Id,M.Title
		--ORDER BY M.Id
		
		Select MY.MonthNumber, CONVERT(varchar,LEFT(M.Title,3)) + '-' + CONVERT(varchar,RIGHT(MY.YearNumber,2)) AS MonthName,COUNT(V.Id) AS Count
		FROM sSetup.fMonthYearForBatchGET(@rBatchId) MY
		LEFT JOIN sCommon.tMonthMaster M ON M.Id = MY.MonthNumber
		LEFT JOIN sFrontOffice.tVisitorLog V ON MONTH(V.VisitDate) = M.Id  AND YEAR(V.VisitDate) = MY.YearNumber AND V.OrgId = @rOrgId
		GROUP BY MY.YearNumber,MY.MonthNumber, M.Title
		ORDER BY  MY.YearNumber,MY.MonthNumber
	END
	
	If @rTypeId = 3 -- Month Wise Student GatePass Count
	BEGIN
		--Select M.Id,LEFT(M.Title,3) AS MonthName, COUNT(S.Id) AS StudentGatePassCount from sCommon.tMonthMaster M
		--LEFT JOIN sFrontOffice.tStudentGatePass S ON MONTH(S.GatePassDate) =  M.Id AND OrgId = @rOrgId
		--AND YEAR(S.GatePassDate) = YEAR(sCommon.fGetDate()) 
		--GROUP BY M.Id,M.Title
		--ORDER BY M.Id
		
		Select MY.MonthNumber, CONVERT(varchar,LEFT(M.Title,3)) + '-' + CONVERT(varchar,RIGHT(MY.YearNumber,2)) AS MonthName,COUNT(S.Id) AS StudentGatePassCount
		FROM sSetup.fMonthYearForBatchGET(@rBatchId) MY
		LEFT JOIN sCommon.tMonthMaster M ON M.Id = MY.MonthNumber
		LEFT JOIN sFrontOffice.tStudentGatePass S ON MONTH(S.GatePassDate) =  M.Id  AND YEAR(S.GatePassDate) = MY.YearNumber AND S.OrgId = @rOrgId
		GROUP BY MY.YearNumber,MY.MonthNumber, M.Title
		ORDER BY  MY.YearNumber,MY.MonthNumber
	END
	
	If @rTypeId = 4 -- Month Wise Employee GatePass Count
	BEGIN
		--Select M.Id,LEFT(M.Title,3) AS MonthName, COUNT(E.Id) AS EmployeeGatePassCount from sCommon.tMonthMaster M
		--LEFT JOIN sFrontOffice.tEmployeeGatePass E ON MONTH(E.GatePassDate) = M.Id AND OrgId = @rOrgId
		--AND YEAR(E.GatePassDate) = YEAR(sCommon.fGetDate())
		--GROUP BY M.Id,M.Title
		--ORDER BY M.Id
		
		Select MY.MonthNumber, CONVERT(varchar,LEFT(M.Title,3)) + '-' + CONVERT(varchar,RIGHT(MY.YearNumber,2)) AS MonthName,COUNT(E.Id) AS EmployeeGatePassCount
		FROM sSetup.fMonthYearForBatchGET(@rBatchId) MY
		LEFT JOIN sCommon.tMonthMaster M ON M.Id = MY.MonthNumber
		LEFT JOIN sFrontOffice.tEmployeeGatePass E ON MONTH(E.GatePassDate) = M.Id AND YEAR(E.GatePassDate) = MY.YearNumber AND E.OrgId = @rOrgId
		GROUP BY MY.YearNumber,MY.MonthNumber, M.Title
		ORDER BY  MY.YearNumber,MY.MonthNumber
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sFrontOffice].[pUpdateEmployeeGatePassOutDate]
	 
	@rId int,
	@rOutTime nvarchar(100),
	@rOrgId int,
	@rReturnGatePassDate datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
 BEGIN TRANSACTION	
	BEGIN
	 
	    UPDATE sFrontOffice.tEmployeeGatePass
	    SET ReturnGatePassTime=@rOutTime, ReturnGatePassDate=@rReturnGatePassDate --ReturnGatePassDate update for mantis : 0039459
	    WHERE Id = @rId  AND (OrgId=@rOrgId OR @rOrgId=0)	
	       
	 END
	   
		SELECT 
			Id,
			ReasonOfGatePass,
			GatePassDate,
			ISNULL(ReturnGatePassDate,'') AS ReturnGatePassDate,
			ISNULL(GatePassTime,'') AS GatePassTime,
			ISNULL(ReturnGatePassTime,'') AS ReturnGatePassTime,
			CreatedDateTime
		FROM 
			sFrontOffice.tEmployeeGatePass
	
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pUpdateStudentGatePassOutDate]
	 
	@rId int,
	@rOutTime nvarchar(100),
	@rOrgId int,
	@rReturnGatePassDate datetime
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
 BEGIN TRANSACTION	
	BEGIN
	 
	    UPDATE  sFrontOffice.tStudentGatePass
	    SET ReturnGatePassTime=@rOutTime, ReturnGatePassDate=@rReturnGatePassDate
	    WHERE Id = @rId  AND (OrgId=@rOrgId OR @rOrgId=0)	
	       
	 END
	   
		SELECT 
			Id,
			AcademicId,
			VisitorName,
			ReasonOfGatePass,
			ISNULL(GatePassDate,'') AS GatePassDate,
			ISNULL(ReturnGatePassDate,'') AS ReturnGatePassDate,
			ISNULL(GatePassTime,'') AS GatePassTime,
			ISNULL(ReturnGatePassTime,'') AS ReturnGatePassTime,
			ISNULL(VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			CreatedDateTime
		
		FROM 
			sFrontOffice.tStudentGatePass
	
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pUpdateVisitorLogOutDate]
	 
	@rId int,
	
	@rOutTime nvarchar(100),
	
	@rOrgId int
	
	
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
 BEGIN TRANSACTION	
	BEGIN
	 
	    UPDATE  sFrontOffice.tVisitorLog
	    SET
	   
	       
			OutTime=@rOutTime
			
			
			
	     
	      
	      
	      WHERE Id = @rId  AND (OrgId=@rOrgId OR @rOrgId=0)	   
	 END  
		SELECT 
		Id As VisitorId,
		VisitorName,
		NoOfVisitor,
		PurposeOfVisit,
		WhomToMeet As WhomToMeetId,
		WhomToMeetName,
		ISNULL(OutTime,'') AS OutTime,
		ISNULL(InTime,'') AS InTime,
		ISNULL(VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
		CreatedDateTime,
		ISNULL(StudentId,'') AS StudentId
		
		 From sFrontOffice.tVisitorLog
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pVisitorLogAdd]
	 
	@rId int,
	@rVisitorName nvarchar(100),	
	@rNoOfVisitor int,
	@rPurposeOfVisit nvarchar(200),
	@rWhomToMeet bigint=0,	
	@rWhomToMeetName nvarchar(100)='',
	@rInTime datetime,
	@rOutTime datetime,
	@rVisitorPhoto varbinary(max),
	@rOrgId int,
	@rCreatedUserId bigint,
	@rVisitDate date,
	@rRemark nvarchar(300)='',
	@rVisitorContactNumber nvarchar(100),
	@rStudentId nvarchar(100)='',
	@rStatusId int=0,
	@rTypeId int=0
	
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	
	--	IF(@rId = 0)	
	--BEGIN
	--	If Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
 
	--END
	--ELSE
	--BEGIN
 
	--	If  Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgId =@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	if(@rTypeId=0)
	begin
	 set @rTypeId=null
	end
	
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tVisitorLog', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sFrontOffice.tVisitorLog
		(
			Id,
			VisitorName,
			NoOfVisitor,
			PurposeOfVisit,
			WhomToMeet,
			WhomToMeetName,
			InTime,
			OutTime,
			VisitorPhoto,
			VisitDate,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			Remark,
			VisitorContactNumber,
			StudentId,
			StatusId,
			TypeId
		)
	VALUES
		(
			@lNextNumber,
			@rVisitorName,	
			@rNoOfVisitor,
			@rPurposeOfVisit,
			@rWhomToMeet,	
			@rWhomToMeetName,
			@rInTime,
			@rOutTime,
			@rVisitorPhoto,
			@rVisitDate,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rRemark,
			@rVisitorContactNumber,
			@rStudentId,
			@rStatusId,
			@rTypeId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tVisitorLog
	    SET
	   
	       VisitorName=@rVisitorName,
			NoOfVisitor=@rNoOfVisitor,
			PurposeOfVisit=@rPurposeOfVisit,
			WhomToMeet=@rWhomToMeet,
			WhomToMeetName=@rWhomToMeetName,
			InTime=@rInTime,
			OutTime=@rOutTime,
			VisitorPhoto=CASE WHEN @rVisitorPhoto IS NULL THEN VisitorPhoto ELSE @rVisitorPhoto END, -- Added by dhananjay mantis : 40440
			OrgId=@rOrgId,
			CreatedUserId=@rCreatedUserId,
			VisitDate=@rVisitDate,
			Remark	=@rRemark,
			VisitorContactNumber=@rVisitorContactNumber,
			StudentId=@rStudentId,
			TypeId=@rTypeId
		
	      
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sFrontOffice].[pVisitorLogGet]
          
           @rVisitorId int=0,
           --@rOutTimeFrom datetime,
           --@rOutTimeTo datetime,
           @rFromVisitDate datetime,
           @rToVisitDate datetime,
           @rOrgId int=0,
           @rWhomToMeetName nvarchar(100)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rTypeId int=0 ,
		   @rStatusId int=0, 
           --@rIsWildCardSearch bit
		   @rVisitorName nvarchar(100)='' --Added for mantis : 36642
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rWhomToMeetName = sCommon.fSearchStringGet(@rWhomToMeetName)
		--END
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
	   (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )
	   --+ (case when isnull(VL.StudentId,0)!=0 AND isnull(VL.WhomToMeet,0)!=0 then ',' else '' end)
	   --+isnull(case when  isnull(VL.StudentId,0)!=0 Then sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) end,'')
	   ) AS WhomToMeetName,
	   ISNULL(VL.InTime,'00:00') AS InTime,
       ISNULL(VL.OutTime,'00:00') AS OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(STM.Id,0) AS StudentId,
	   ISNULL(VTM.Title, '') AS VisitorType,
	   --(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 'Visitor' else 'Parents' end
			 --when ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 --ELSE 'Parents' END) AS VisitorType,
	   (CASE WHEN ISNULL(VL.OutTime,'00:00:00')='00:00:00' THEN 0
			 ELSE 1 END) AS InOutStatus,
		OM.OrgGroupId AS OrgGroupId,
		SM.Title as Status,
		ISNULL(VL.StatusId,0) as StatusId,
		ISNULL(VL.TypeId, 0) AS VisitorTypeId,
		--(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 1 else 2 end
		--	 when ISNULL(VL.StudentId,0)=0 THEN 1
		--	 ELSE 2 END) AS VisitorTypeId,
		ISNULL(STM.Code,'') AS StudentCode,
		ISNULL(STM.FirstName,'') +' '+ ISNULL(STM.LastName,'') AS  StudentName,
		 (select ISNULL(CM.Title,'') from sSetup.tClassMaster CM Inner join sStudent.tAcademic A ON A.ClassId=CM.Id AND A.StudentId=STM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive=1 GROUP BY CM.Title) AS StudentClass
		,(select ISNULL(DM.Title,'') from sSetup.tDivisionMaster DM Inner join sStudent.tAcademic A ON A.DivisionId=DM.Id AND A.StudentId=STM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive=1 GROUP BY DM.Title) AS StudentDivision
		--ISNULL(CM.Title,'') AS StudentClass,
		--ISNULL(DM.Title,'') AS StudentDivision
		,ISNULL(VL.VisitorName,'') AS VisitorName --Added for mantis : 36642
		,OI.CertificateHeaderA4		--Mantis - 43061
		 		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VL.StatusId
  LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=VL.WhomToMeet
  LEFT JOIN sStudent.tStudentMaster STM On STM.Id=VL.StudentId  
  --LEFT JOIN sStudent.tAcademic A ON A.StudentId = STM.Id
  --LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive=1
  --LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
  --LEFT JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
  LEFT JOIN sSetup.tOrganizationMaster AS OM1 ON STM.OrgId = OM1.Id 
  LEFT JOIN [sFrontOffice].[tVisitorTypeMaster] AS VTM ON VTM.Id = VL.TypeId 
  LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
 
  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND (((VL.WhomToMeetName LIKE @rWhomToMeetName) OR  (isnull(EM.EmployeeId,0)>0 AND EM.EmployeeName Like  @rWhomToMeetName) OR (isnull(STM.Id,0)>0 AND sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) like  @rWhomToMeetName)) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	--AND ((ISNULL(VL.TypeId,0)=0 AND (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0)))  OR (ISNULL(VL.TypeId,0)!=0 AND ((VL.TypeId=@rTypeId) or (@rTypeId=0)))) -- Visitor 
	AND ((VL.TypeId = @rTypeId) OR (@rTypeId = 0))
	AND ((VL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0)) 
	--AND BM.IsActive=1
	 -- Parents
	 AND ((VL.VisitorName LIKE '%' + @rVisitorName + '%') OR (ISNULL(@rVisitorName,'')='')) --Added for mantis : 36642
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sFrontOffice].[pVisitorLogListingGet]
       
    @rVisitorId int=0,
    @rFromVisitDate datetime='',
    @rToVisitDate datetime='',
    @rOrgId int=0,
    @rWhomToMeetName nvarchar(100)='',
    @rIsPrintView bit=0,
    @rOrgGroupId int =0,
    @rTypeId int=0 ,
	@rStatusId int=0 ,
	@rUserSourceId bigint = 0
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rWhomToMeetName = sCommon.fSearchStringGet(@rWhomToMeetName)
		--END
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
       isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') end,'' )+ (case when isnull(VL.StudentId,0)!=0 AND isnull(VL.WhomToMeet,0)!=0 then ',' else '' end)+
	   isnull(case when  isnull(VL.StudentId,0)!=0 Then sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) end,'') AS  WhomToMeetName,
       CONVERT(Varchar,VL.InTime,108)AS InTime,
       CONVERT(Varchar,VL.OutTime,108)AS OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(StudentId,0) AS StudentId,
	   ISNULL(VTM.Title, '') AS VisitorType,
	   --(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 'Visitor' else 'Parents' end
			 --when ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 --ELSE 'Parents' END) AS VisitorType,
	   (CASE WHEN ISNULL(VL.OutTime,'00:00:00')='00:00:00' THEN 0
			 ELSE 1 END) AS InOutStatus,
		OM.OrgGroupId AS OrgGroupId,
		ISNULL(VL.StatusId,0) as StatusId,
		SM.Title as Status,
		ISNULL(VL.TypeId, 0) AS VisitorTypeId
		--(CASE WHEN ISNULL(VL.TypeId,'')!='' then case when VL.TypeId=1 then 1 else 2 end
		--	 when ISNULL(VL.StudentId,0)=0 THEN 1
		--	 ELSE 2 END) AS VisitorTypeId
		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VL.StatusId
  Left Join  sHrm.vExtEmployeeMaster EM on EM.EmployeeId=VL.WhomToMeet
  left Join sStudent.tStudentMaster STM On STM.Id=VL.StudentId  
  left JOIN sSetup.tOrganizationMaster AS OM1 ON STM.OrgId = OM1.Id 
  LEFT JOIN [sFrontOffice].[tVisitorTypeMaster] AS VTM ON VTM.Id = VL.TypeId 

  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) 
	AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND (((VL.WhomToMeetName LIKE @rWhomToMeetName) OR  (isnull(EM.EmployeeId,0)>0 AND EM.EmployeeName Like  @rWhomToMeetName) OR (isnull(STM.Id,0)>0 AND sStudent.fStudentNameGet(STM.FirstName, STM.MiddleName,STM.LastName, OM1.StudentNameFormatId) like  @rWhomToMeetName)) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	--AND ((ISNULL(VL.TypeId,0)=0 AND (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0)))  OR (ISNULL(VL.TypeId,0)!=0 AND ((VL.TypeId=@rTypeId) or (@rTypeId=0)))) -- Visitor 
	AND ((VL.TypeId = @rTypeId) OR (@rTypeId = 0))
	AND ((VL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0)) 
	--AND (ISNULL(VL.StatusId,0) != 0)
	AND ((VL.WhomToMeet = @rUserSourceId) OR (ISNULL(@rUserSourceId,0) = 0))
	
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pActivityClassAdd]
	 
            @rActivityId int
           ,@rClassId int
		   ,@rOrgId bigint
		   ,@rIsDeleted bit
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF NOT EXISTS(SELECT ActivityId FROM [sGSEB].[tClassActivity] WHERE  ActivityId = @rActivityId AND ClassId = @rClassId )	
BEGIN
	INSERT INTO [sGSEB].[tClassActivity]
			   (
			    [ActivityId]
			   ,[ClassId]
			   )
		 VALUES
			   (
			    @rActivityId
			   ,@rClassId
			   )
		    SELECT @rActivityId AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
 BEGIN
   IF @rIsDeleted = 1
	 BEGIN
	    UPDATE  [sGSEB].[tClassActivity]
	    SET
	          [ActivityId]=@rActivityId
	         ,ClassId=@rClassId
	     WHERE ActivityId = @rActivityId AND ClassId = @rClassId   
	     
	     SELECT @rActivityId  AS Result
	  END    
   ELSE
	BEGIN
		DELETE FROM sGSEB.tClassActivity WHERE ActivityId = @rActivityId AND ClassId = @rClassId
		SELECT 1 AS RESULT
	END	
		--COMMIT TRANSACTION
  END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pActivityClassGet]
	   @rClassId int
	  ,@rOrgGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
SELECT 
			ISNULL(AM.ID,0) AS ActivityId,
			ISNULL(CA.ClassId,0) AS ClassId,			
			AM.Title AS ActivityName,
			CASE WHEN ISNULL(CA.ClassId,0)=0 THEN 'false' ELSE 'true' END AS Selected
FROM 
			
			sGSEB.tActivityMaster AM 
			LEFT JOIN sGSEB.tClassActivity CA ON AM.Id=CA.ActivityId
			AND (CA.ClassId=@rClassId OR @rClassId=0) 	
WHERE (AM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId =0)	
				
			  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sGSEB].[pActivityGroupMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
	       ,@rNumber int
           ,@rTitle nvarchar(100)       
           ,@rIsObsolete bit
           ,@rOrderIndex int
           ,@rUpdatedUserId bigint           
           ,@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sGSEB.tActivityGroupMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sGSEB.tActivityGroupMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
		If Exists(select Id from sGSEB.tActivityGroupMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sGSEB.tActivityGroupMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sGSEB.tActivityGroupMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sGSEB.tActivityGroupMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN
		
	--EXECUTE sCommon.pGetIntMaxIdForOrgGroup @rOrgGroupId, 'sGSEB.tActivityGroupMaster',@lNextNumber OUtput
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sGSEB.tActivityGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--output

	INSERT INTO [sGSEB].[tActivityGroupMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Number]
			   ,[Title]
			   ,[IsObsolete]
			   ,[OrderIndex]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rNumber
			   ,@rTitle
			   ,@rIsObsolete
			   ,@rOrderIndex
			   ,@rUpdatedUserId
			   ,sCommon.fGetDate()			
			   ,@rOrgGroupId
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sGSEB].[tActivityGroupMaster]
	    SET
			  Code=@rCode
			 ,Number=@rNumber
	         ,Title=@rTitle
	         ,OrderIndex=@rOrderIndex
	         ,[IsObsolete] = @rIsObsolete                          
             ,[UpdatedUserId] = @rUpdatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pActivityGroupMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF EXISTS (SELECT ActivityId FROM sGSEB.tActivityIndicatorMaster FI
			INNER JOIN sGSEB.tActivityMaster FM ON FI.ActivityId=FM.Id AND FM.ActivityGroupId = @rId)	
	  BEGIN	
		SELECT -101 AS RESULT
	   END
	ELSE IF EXISTS (SELECT A.ActivityId FROM sGSEB.tClassActivity A
					INNER JOIN sGSEB.tActivityMaster FM ON A.ActivityId=FM.Id AND FM.ActivityGroupId = @rId)  
	  BEGIN
		SELECT -101 AS RESULT
	  END	 
	ELSE
		BEGIN
			DELETE	FROM sGSEB.tActivityMaster WHERE ActivityGroupId=@rId		
			DELETE FROM sGSEB.tActivityGroupMaster WHERE Id = @rId	
			SELECT 1 AS RESULT			
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sGSEB].[pActivityGroupMasterGet] 
          
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			Set @rCode = sCommon.fSearchStringGet(@rCode)
		--END

BEGIN
SELECT FGM.Id AS Id
	  ,FGM.Title AS Title
	  ,FGM.Code AS Code
	  ,FGM.Number AS Number
	  ,FGM.OrderIndex AS OrderIndex
      ,FGM.IsObsolete AS IsObsolete
     
  FROM [sGSEB].[tActivityGroupMaster] FGM     
  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
	((FGM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((FGM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND FGM .OrgGroupId = @rOrgGroupId
	Order By FGM.OrderIndex ASC
         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sGSEB].[pActivityIndicatorDetailAdd]
	 
	        @rId int
           ,@rActivityId int
           ,@rTitle nvarchar(100)
           ,@rNumber smallint
		   ,@rOrderIndex int	
		   ,@rUpdatedUserId bigint
		   ,@rIsObsolete bit
		   ,@rOrgGroupId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sGSEB.tActivityIndicatorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	  EXECUTE sCommon.pGetIntMaxIdForOrgGroup @rOrgGroupId, 'sGSEB.tActivityIndicatorMaster',@lNextNumber OUtput
	  --EXECUTE sCommon.pTableRowIdGet rOrgGroupId, 'sGSEB.tActivityIndicatorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sGSEB].[tActivityIndicatorMaster]
			   (
			    [Id]
			   ,[ActivityId]
			   ,[Title]
			   ,[Number] 
			   ,[OrgGroupId]
			   ,[IsObsolete]
			   ,[OrderIndex]	
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rActivityId
			   ,@rTitle
			   ,@rNumber
			   ,@rOrgGroupId
			   ,@rIsObsolete
			   ,@rOrderIndex			   
			   ,@rUpdatedUserId			   
			   ,sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sGSEB].[tActivityIndicatorMaster]
	    SET
			 
	          ActivityId=@rActivityId
	         ,Title=@rTitle
	         ,Number=@rNumber
	         ,OrgGroupId=@rOrgGroupId
	         ,IsObsolete=@rIsObsolete
			 ,OrderIndex=@rOrderIndex
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pActivityIndicatorDetailGet]
	 @rActivityId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT			
			AIM.Id,
			AIM.ActivityId,
			ISNULL(AIM.Number,0) AS Number,
			ISNULL(AIM.TITLE,'') AS TITLE,
			AIM.OrderIndex
  FROM 
			sGSEB.[tActivityIndicatorMaster] AIM
WHERE 
			(AIM.ActivityId=@rActivityId OR @rActivityId=0)  order by AIM.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pActivityIndicatorGroupDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT ActivityId FROM sGSEB.tActivityIndicatorScore WHERE ActivityId = @rId)	
	  BEGIN
		DELETE	FROM sGSEB.tActivityIndicatorMaster WHERE ActivityId=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pActivityIndicatorMasterDelete]
@rId	 bigint
AS
BEGIN
BEGIN TRY
	--IF NOT EXISTS (SELECT Id FROM sGSEB.tClassActivity WHERE ActivityId = @rActivityId)	
	  BEGIN
		DELETE	FROM sGSEB.tActivityIndicatorMaster WHERE Id=@rId	
		SELECT 1 AS RESULT
	   END
	--ELSE
	--	BEGIN
	--		SELECT -101 AS RESULT
	--	END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pActivityIndicatorScoreAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	,
	@rExamId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT

		IF @rExamId = 1
		BEGIN
			UPDATE AI SET AI.Term1Indicator = 0,AI.Term1IndicatorText='' FROM sGSEB.tActivityIndicatorScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/ActivityIndicatorScore', 1)
				WITH ( 				
						AcademicId Bigint,ActivityTitle NVARCHAR(100)			
					  ) A 	ON AI.AcademicId = A.AcademicId
			INNER JOIN sGSEB.tActivityMaster AM ON AM.Id = AI.ActivityId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = AM.OrgGroupId AND OM.Id = @rORGId	
			AND AM.Title=A.ActivityTitle			  			
		END
		IF @rExamId = 2
		BEGIN
			UPDATE AI SET AI.Term2Indicator = 0,AI.Term2IndicatorText='' FROM sGSEB.tActivityIndicatorScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/ActivityIndicatorScore', 1)
				WITH ( 				
						AcademicId Bigint,
						ActivityTitle NVARCHAR(100)			
					  ) A 	ON AI.AcademicId = A.AcademicId
			INNER JOIN sGSEB.tActivityMaster AM ON AM.Id = AI.ActivityId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = AM.OrgGroupId AND OM.Id = @rORGId	
			AND AM.Title=A.ActivityTitle			  
	    END
	    
	    	DELETE AI FROM sGSEB.tActivityIndicatorScore AI
			INNER JOIN OPENXML (@loDoc, '/Table/ActivityIndicatorScore', 1)
				WITH ( 				
						AcademicId Bigint,
						ActivityTitle NVARCHAR(100),
						Term1Indicator nvarchar(20),
						Term2Indicator nvarchar(20)
					  ) A 	ON AI.AcademicId = A.AcademicId
			INNER JOIN sGSEB.tActivityMaster AM ON AM.Id = AI.ActivityId 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = AM.OrgGroupId AND OM.Id = @rORGId	
			AND AM.Title=A.ActivityTitle	AND (A.Term1Indicator='0' OR A.Term1Indicator='')
			AND (A.Term2Indicator='0' OR A.Term2Indicator='') 
		
		INSERT INTO sGSEB.tActivityIndicatorScore
			(AcademicId,ActivityId,Term1Indicator,Term2Indicator)
			
			SELECT		AcademicId,AM.Id,
						Replace(Term1Indicator,',','.'),
						Replace(Term2Indicator,',','.')
			
			FROM OPENXML (@loDoc, '/Table/ActivityIndicatorScore', 1)
			WITH ( 				
					AcademicId Bigint,ActivityTitle NVARCHAR(100),Term1Indicator nvarchar(20),Term2Indicator nvarchar(20)			
				  ) A 	
			INNER JOIN sGSEB.tActivityMaster AM ON AM.TITLE = A.ACTIVITYTITLE 			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = AM.OrgGroupId AND OM.Id = @rORGId
			INNER JOIN sGSEB.tActivityIndicatorMaster AIM ON AIM.ActivityId = AM.Id 
			AND (',' + A.Term1Indicator + ',' like '%,'+ cast(AIM.Number as varchar(255)) + ',%'
			 OR ',' + A.Term2Indicator + ',' like '%,'+ cast(AIM.Number as varchar(255)) + ',%')
	      SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pActivityIndicatorScoreGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rGSEBExamId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
	DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(AM.Title) 
					  From sGSEB.tClassActivity CA 
					  INNER JOIN sGSEB.tActivityMaster AM ON AM.Id= CA.ActivityId
					  AND CA.ClassId = @rClassId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

IF @rGSEBExamId =1         
	BEGIN
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Number,SA.Name,AM.Title,	 ISNULL(AIS.Term1Indicator,'''') AS Term1Indicator		
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sGSEB.tClassActivity CA ON CA.ClassId = SA.ClassId
	INNER JOIN sGSEB.tActivityMaster AM ON AM.Id = CA.ActivityId
	LEFT JOIN sGSEB.tActivityIndicatorScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.ActivityId=AM.Id
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '
	) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	END
ELSE
	BEGIN
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Number,SA.Name,AM.Title
		,ISNULL(AIS.Term2Indicator,'''') AS Term2Indicator
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sGSEB.tClassActivity CA ON CA.ClassId = SA.ClassId
	INNER JOIN sGSEB.tActivityMaster AM ON AM.Id = CA.ActivityId
	LEFT JOIN sGSEB.tActivityIndicatorScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.ActivityId=AM.Id
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '
	) MAIN
	PIVOT
	(
		max(Term2Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

	END
--print (@query)

execute(@query)
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sGSEB].[pActivityMasterAdd]
	 
	        @rId int
           ,@rActivityGroupId int
           ,@rNumber int
           ,@rTitle nvarchar(100)
		   ,@rOrderIndex int		  
		   ,@rUpdatedUserId bigint
		   ,@rOrgGroupId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int 
IF(@rId = 0)	
BEGIN
	--EXECUTE sCommon.pGetIntMaxIdForOrgGroup @rOrgGroupId, 'sGSEB.tActivityMaster',@lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sGSEB.tActivityMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	select @lNextNumber,@rNumber,@rTitle,@rOrgGroupId,@rActivityGroupId,0,@rOrderIndex,@rUpdatedUserId,sCommon.fGetDate()
	INSERT INTO [sGSEB].[tActivityMaster]
			   (
			    [Id]
			   ,[Number]
			   ,[Title] 
			   ,[OrgGroupId]			 
			   ,[ActivityGroupId]
			   ,[IsObsolete]
			   ,[OrderIndex]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rTitle
			   ,@rOrgGroupId
			   ,@rActivityGroupId
			   ,0
			   ,@rOrderIndex
			   ,@rUpdatedUserId
			   ,sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sGSEB].[tActivityMaster]
	    SET
			 
	          ActivityGroupId=@rActivityGroupId
	         ,Title=@rTitle
	         ,Number=@rNumber
			 ,OrderIndex=@rOrderIndex
			 ,OrgGroupId=@rOrgGroupId
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pActivityMasterDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT Id FROM sGSEB.tActivityIndicatorMaster WHERE ActivityId = @rId)	
	  BEGIN
		DELETE	FROM sGSEB.tActivityMaster WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pActivityMasterGet]
	 @rActivityGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT
			AGM.Id,
			AGM.Code As Code,
			AGM.Title AS Title,
			AGM.Number AS Number,
			AGM.OrderIndex AS OrderIndex,
			AGM.IsObsolete AS IsObsolete,
			AM.Id AS ActivityID,
			AM.ActivityGroupId AS ActivityGroupId,
			AM.TITLE AS ActivityTitle,
			AM.Number AS ActivityNumber,
			AM.OrderIndex AS ActivityOrderIndex
			
FROM 
			[sGSEB].[tActivityGroupMaster] AGM
			INNER JOIN sGSEB.tActivityMaster AM ON AGM.Id=AM.ActivityGroupId
WHERE 
			(AGM.Id=@rActivityGroupId OR @rActivityGroupId=0)  

ORDER BY	AGM.OrderIndex ASC,AM.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pAnusuchiBMarkValidateGet]	
	 @rClassId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	IF EXISTS (SELECT ID FROM sSetup.tClassMaster Where Id=@rClassId AND ClassGroupId >= 1 AND ClassGroupID <=5)		
		BEGIN	
			SELECT 5 AS MarkValidate
		END
	ELSE IF EXISTS (SELECT ID FROM sSetup.tClassMaster Where Id=@rClassId AND ClassGroupId >= 5 AND ClassGroupID <=8)		
		BEGIN
			SELECT 10 AS MarkValidate
		END 	
	ELSE
		BEGIN
			SELECT 0 AS MarkValidate
		END		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sGSEB].[pAnusuchiBScoreAdd]
	 
	        @rAcademicId bigint
           ,@rGSEBExamId int
           ,@rClassSubjectId int
           ,@rPd1 smallint
           ,@rPd2 smallint
           ,@rPd3 smallint
           ,@rPd4 smallint
           ,@rPd5 smallint
           ,@rPd6 smallint
           ,@rPd7 smallint
           ,@rPd8 smallint
           ,@rPd9 smallint
           ,@rPd10 smallint
           ,@rPd11 smallint
           ,@rPd12 smallint
           ,@rPd13 smallint
           ,@rPd14 smallint
           ,@rPd15 smallint
           ,@rPd16 smallint
           ,@rPd17 smallint
           ,@rPd18 smallint
           ,@rPd19 smallint
           ,@rPd20 smallint
           ,@rPd21 smallint
           ,@rPd22 smallint
           ,@rPd23 smallint
           ,@rPd24 smallint
           ,@rPd25 smallint
           ,@rPd26 smallint
           ,@rPd27 smallint
           ,@rPd28 smallint
           ,@rPd29 smallint
           ,@rPd30 smallint
           ,@rPd31 smallint
           ,@rPd32 smallint
           ,@rPd33 smallint
           ,@rPd34 smallint
           ,@rPd35 smallint
           ,@rPd36 smallint
           ,@rPd37 smallint
           ,@rPd38 smallint
           ,@rPd39 smallint
           ,@rPd40 smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF NOT EXISTS (SELECT ACADEMICID FROM sGSEB.tAnusuchiB WHERE ACADEMICID=@rAcademicId AND GSEBExamId = @rGSEBExamId AND CLASSSUBJECTID = @rClassSubjectId)	
BEGIN
	INSERT INTO [sGSEB].[tAnusuchiB]
			   (
			    [AcademicId]			 
			   ,[GSEBExamId]
			   ,[ClassSubjectId]
			   ,[Pd1]
			   ,[Pd2]
			   ,[Pd3]
			   ,[Pd4]
			   ,[Pd5]
			   ,[Pd6]
			   ,[Pd7]
			   ,[Pd8]
			   ,[Pd9]
			   ,[Pd10]
			   ,[Pd11]
			   ,[Pd12]
			   ,[Pd13]
			   ,[Pd14]
			   ,[Pd15]
			   ,[Pd16]
			   ,[Pd17]
			   ,[Pd18]
			   ,[Pd19]
			   ,[Pd20]
			   ,[Pd21]
			   ,[Pd22]
			   ,[Pd23]
			   ,[Pd24]
			   ,[Pd25]
			   ,[Pd26]
			   ,[Pd27]
			   ,[Pd28]
			   ,[Pd29]
			   ,[Pd30]
			   ,[Pd31]
			   ,[Pd32]
			   ,[Pd33]
			   ,[Pd34]
			   ,[Pd35]
			   ,[Pd36]
			   ,[Pd37]
			   ,[Pd38]
			   ,[Pd39]
			   ,[Pd40]
			   )
		 VALUES
			   (
				@rAcademicId
			   ,@rGSEBExamId
			   ,@rClassSubjectId
			   ,@rPd1
			   ,@rPd2
			   ,@rPd3
			   ,@rPd4
			   ,@rPd5
			   ,@rPd6
			   ,@rPd7
			   ,@rPd8
			   ,@rPd9
			   ,@rPd10
			   ,@rPd11
			   ,@rPd12
			   ,@rPd13
			   ,@rPd14
			   ,@rPd15
			   ,@rPd16
			   ,@rPd17
			   ,@rPd18
			   ,@rPd19
			   ,@rPd20
			   ,@rPd21
			   ,@rPd22
			   ,@rPd23
			   ,@rPd24
			   ,@rPd25
			   ,@rPd26
			   ,@rPd27
			   ,@rPd28
			   ,@rPd29
			   ,@rPd30
			   ,@rPd31
			   ,@rPd32
			   ,@rPd33
			   ,@rPd34
			   ,@rPd35
			   ,@rPd36
			   ,@rPd37
			   ,@rPd38
			   ,@rPd39
			   ,@rPd40			   
			   )
		    SELECT 1 AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	    UPDATE  [sGSEB].[tAnusuchiB]
	    SET  
	         Pd1=@rPd1
	         ,Pd2=@rPd2
	         ,Pd3=@rPd3
	         ,Pd4=@rPd4
	         ,Pd5=@rPd5
	         ,Pd6=@rPd6
	         ,Pd7=@rPd7
	         ,Pd8=@rPd8
	         ,Pd9=@rPd9
	         ,Pd10=@rPd10
	         ,Pd11=@rPd11
	         ,Pd12=@rPd12
	         ,Pd13=@rPd13
	         ,Pd14=@rPd14
	         ,Pd15=@rPd15
	         ,Pd16=@rPd16
	         ,Pd17=@rPd17
	         ,Pd18=@rPd18
	         ,Pd19=@rPd19
	         ,Pd20=@rPd20
	         ,Pd21=@rPd21
	         ,Pd22=@rPd22
	         ,Pd23=@rPd23
	         ,Pd24=@rPd24
	         ,Pd25=@rPd25
	         ,Pd26=@rPd26
	         ,Pd27=@rPd27
	         ,Pd28=@rPd28
	         ,Pd29=@rPd29
	         ,Pd30=@rPd30
	         ,Pd31=@rPd31
	         ,Pd32=@rPd32
	         ,Pd33=@rPd33
	         ,Pd34=@rPd34
	         ,Pd35=@rPd35
	         ,Pd36=@rPd36
	         ,Pd37=@rPd37
	         ,Pd38=@rPd38
	         ,Pd39=@rPd39
	         ,Pd40=@rPd40
	      WHERE AcademicId = @rAcademicId AND GSEBExamId = @rGSEBExamId  AND CLASSSubjectId =  @rClassSubjectId 
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pAnusuchiBScoreDivisionDelete]
@rGSEBExamId int,
@rDivisionId int
AS
BEGIN
BEGIN TRY
	  BEGIN
		DELETE	FROM sGSEB.tAnusuchiB WHERE GSEBExamId = @rGSEBExamId AND
		AcademicId IN (SELECT AcademicId From sStudent.vStudentFull SF WHERE DivisionId = @rDivisionId)		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pAnusuchiBScoreGet]	
	 @rGSEBExamId int,
	 @rDivisionId int,
	 @rClassSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT					
		@rGSEBExamId AS GSEBExamId,
		SF.AcademicId AS AcademicId,
		SF.NUMBER,
		SF.ROLLNO,
		SF.NAME AS STUDENTNAME,
		ISNULL(Pd1,0) AS Pd1,
		ISNULL(Pd2,0) AS Pd2,
		ISNULL(Pd3,0) AS Pd3,
		ISNULL(Pd4,0) AS Pd4,
		ISNULL(Pd5,0) AS Pd5,
		ISNULL(Pd6,0) AS Pd6,
		ISNULL(Pd7,0) AS Pd7,
		ISNULL(Pd8,0) AS Pd8,
		ISNULL(Pd9,0) AS Pd9,
		ISNULL(Pd10,0) AS Pd10,
		ISNULL(Pd11,0) AS Pd11,
		ISNULL(Pd12,0) AS Pd12,
		ISNULL(Pd13,0) AS Pd13,
		ISNULL(Pd14,0) AS Pd14,
		ISNULL(Pd15,0) AS Pd15,
		ISNULL(Pd16,0) AS Pd16,
		ISNULL(Pd17,0) AS Pd17,
		ISNULL(Pd18,0) AS Pd18,
		ISNULL(Pd19,0) AS Pd19,
		ISNULL(Pd20,0) AS Pd20,
		ISNULL(Pd20,0) AS Pd20,
		ISNULL(Pd21,0) AS Pd21,
		ISNULL(Pd22,0) AS Pd22,
		ISNULL(Pd23,0) AS Pd23,
		ISNULL(Pd24,0) AS Pd24,
		ISNULL(Pd25,0) AS Pd25,
		ISNULL(Pd26,0) AS Pd26,
		ISNULL(Pd27,0) AS Pd27,
		ISNULL(Pd28,0) AS Pd28,
		ISNULL(Pd29,0) AS Pd29,
		ISNULL(Pd30,0) AS Pd30,
		ISNULL(Pd31,0) AS Pd31,
		ISNULL(Pd32,0) AS Pd32,
		ISNULL(Pd33,0) AS Pd33,
		ISNULL(Pd34,0) AS Pd34,
		ISNULL(Pd35,0) AS Pd35,
		ISNULL(Pd36,0) AS Pd36,
		ISNULL(Pd37,0) AS Pd37,
		ISNULL(Pd38,0) AS Pd38,
		ISNULL(Pd39,0) AS Pd39,
		ISNULL(Pd40,0) AS Pd40,
		(Select count(*) From sGSEB.tAnusuchiB Where GSEBExamId= @rGSEBExamId) AS TotalPd
		
  FROM 
			sGSEB.tAnusuchiB HS 
			RIGHT JOIN sStudent.vStudentFull SF ON SF.AcademicId = HS.AcademicId			
   		    AND (HS.GSEBExamId = @rGSEBExamId OR @rGSEBExamId = 0)
   		    AND HS.ClassSubjectId = @rClassSubjectId
 
 WHERE  SF.DIVISIONID = @rDivisionId 
 
 ORDER BY SF.DIVISIONID,SF.ROLLNO
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sGSEB].[pGSEBExamMappingAdd]
	 
            @rClassId int
           ,@rGSEBExamId int
           ,@rExamId int
           ,@rBatchId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
BEGIN
    
    IF EXISTS (SELECT CLASSID FROM [sGSEB].[tGSEBExamMapping] WHERE GSEBExamId = @rGSEBExamId AND CLASSID = @rClassId AND ExamId <> @rExamId ) 
    BEGIN
		DELETE  RD FROM sGSEB.tResultDetail  RD
			INNER JOIN sGSEB.tResult R ON R.AcademicId=RD.AcademicId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId
			WHERE (SA.ClassId=@rClassId OR @rClassId = 0)
	END
	
    IF NOT EXISTS (SELECT CLASSID FROM [sGSEB].[tGSEBExamMapping] WHERE GSEBExamId = @rGSEBExamId AND CLASSID = @rClassId ) 
	BEGIN
	INSERT INTO [sGSEB].[tGSEBExamMapping]
			   (
			    [GSEBExamId]
			   ,[ClassId]
			   ,[BatchId]
			   ,[ExamId]
			   )
		 VALUES
			   (
			    @rGSEBExamId
			   ,@rClassId
			   ,@rBatchId
			   ,@rExamId
			   )
	 END

   
	

		    SELECT @rGSEBExamId AS Result
	
		--COMMIT TRANSACTION         
END	 
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pGSEBExamMappingGet]
	  @rClassId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
SELECT
	ISNULL(EM.ID,0) AS GSEBEXAMID,
	ISNULL(CE.CLASSId,0) AS CLASSID,
	ISNULL(CE.ExamId,0) AS ExamId,
	EM.Title AS ExamName,
	0 AS MaxMark

	
FROM
sGSEB.tGSEBExamMapping CE 
RIGHT JOIN sGSEB.tGSEBEXAMMASTER EM ON EM.Id = CE.GSEBExamId AND CE.CLASSId = @rClassId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pGSEBMarkEntryGet]
	 @rClassId int,
	 @rExamId int,
	 @rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

	SELECT  	
	ISNULL(RD.ID,0) AS ResultDetailId,
	ED.ClassSubjectId AS ClassSubjectId,
	ISNULL(RD.Obtain,0) AS Obtain
	--/isnull(ED.Maximum,1)*100
FROM sAssessment.tResultDetail RD 
	INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId
	INNER JOIN 	sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId
	INNER JOIN sAssessment.tExamMaster EM ON SA.ClassId = EM.ClassId  AND EM.Id=R.ExamId 
	AND (EM.Id = @rExamId) AND EM.ClassId=@rClassId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id AND RD.ExamDetailId = ED.Id		

		
Where   SA.ACADEMICID = @rAcademicId AND  SA.StatusId=1 Order By SA.RollNo
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pGSEBResultAdd] 
	        @rAcademicId bigint
		   ,@rUpdatedUserId bigint
		   ,@rOrgId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lGSEBResultId  BIGINT

SELECT @lGSEBResultId = ISNULL(AcademicId,0) FROM sGSEB.tResult WHERE AcademicId=@rAcademicId	 

IF(ISNULL(@lGSEBResultId,0) = 0)	
BEGIN
	INSERT INTO [sGSEB].[tResult]
			   (
			    [AcademicId]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
			    @rAcademicId
			   ,@rUpdatedUserId		   
			   ,sCommon.fGetDate()
			   )
		    SELECT @rAcademicId AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN	
	    UPDATE  [sGSEB].[tResult]
	    SET		 
			 UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE AcademicId = @rAcademicId 	   
	          SELECT @rAcademicId AS Result
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pGSEBResultDetailAdd]
            @rAcademicId bigint
		   ,@rClassSubjectId int
		   ,@rObtain decimal(6,2)		
		   ,@rExamOrder int
		   ,@rGSEBExamId INT
		   ,@rOrgId int
		   ,@IsPrimary smallint
		 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
 DECLARE @lGSEBResultDetailId BIGINT
SELECT @lGSEBResultDetailId= ISNULL(AcademicId,0) From sGSEB.tResultDetail Where AcademicId =@rAcademicId AND ClassSubjectId=@rClassSubjectId
IF ISNULL(@lGSEBResultDetailId,0) = 0
	 BEGIN
	 
	INSERT INTO [sGSEB].[tResultDetail]
			   (
			    [AcademicId] 
			   ,[ClassSubjectId]
			   ,[FA1]
			   ,[FA2]
			   ,[SA1]
			   ,[FA3]
			   ,[FA4]
			   ,[SA2]			 
			   )
		 VALUES
			   (
			    @rAcademicId
			   ,@rClassSubjectId
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   )
			   
			IF(@rExamOrder=1) UPDATE [sGSEB].[tResultDetail] SET [FA1]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=2) UPDATE [sGSEB].[tResultDetail] SET [FA2]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=3) UPDATE [sGSEB].[tResultDetail] SET [SA1]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=4) UPDATE [sGSEB].[tResultDetail] SET [FA3]=@rObtain  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=5) UPDATE [sGSEB].[tResultDetail] SET [FA4]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE UPDATE [sGSEB].[tResultDetail] SET [SA2]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
		--    SELECT 1 AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	       IF(@rExamOrder=1) UPDATE [sGSEB].[tResultDetail] SET [FA1]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=2) UPDATE [sGSEB].[tResultDetail] SET [FA2]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=3) UPDATE [sGSEB].[tResultDetail] SET [SA1]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=4) UPDATE [sGSEB].[tResultDetail] SET [FA3]=@rObtain  Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE IF(@rExamOrder=5)UPDATE [sGSEB].[tResultDetail] SET [FA4]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			ELSE UPDATE [sGSEB].[tResultDetail] SET [SA2]=@rObtain Where AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
			
		--	SELECT 1 AS Result
	
	 END  

-- Evaluation For Primary Result
	DECLARE @lCntHetu1 INT
	DECLARE @lCntHetu2 int
	
	SELECT @lCntHetu1=COUNT(*) from sGSEB.tHetuMaster where ClassSubjectId=@rClassSubjectId and GSEBExamId=1
	SELECT @lCntHetu2=COUNT(*) from sGSEB.tHetuMaster where ClassSubjectId=@rClassSubjectId and GSEBExamId=2
	
	IF @IsPrimary = 1  AND @lCntHetu1 > 0
	BEGIN

		-- Term1 Hetu Mark - Anusuchi A
			UPDATE RD SET FA1 = 40 / @lCntHetu1  *
			(SELECT (CASE WHEN HETU1 >= 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU2 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU3 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU4 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU5 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU6 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU7 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU8 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU9 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU10 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU11 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU12 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU13 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU14 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU15 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU16 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU17 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU18 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU19 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU20 = 1 THEN 1 ELSE 0 END )  FROM sGSEB.tHetuScore WHERE ClassSubjectId =@rClassSubjectId AND GSEBExamId=1 AND ACADEMICID=@rAcademicId)
			FROM sGSEB.tResultDetail RD WHERE AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
	END
	IF @IsPrimary = 1  AND @lCntHetu2 > 0
	BEGIN
		-- Term2 Hetu Mark - Anusuchi A
			UPDATE RD SET FA3 = 40 / @lCntHetu2  *
			(SELECT (CASE WHEN HETU1 >= 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU2 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU3 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU4 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU5 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU6 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU7 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU8 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU9 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU10 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU11 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU12 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU13 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU14 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU15 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU16 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU17 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU18 = 1 THEN 1 ELSE 0 END  + CASE WHEN HETU19 = 1 THEN 1 ELSE 0 END  +
			CASE WHEN HETU20 = 1 THEN 1 ELSE 0 END )  FROM sGSEB.tHetuScore WHERE ClassSubjectId =@rClassSubjectId AND GSEBExamId=2 AND ACADEMICID=@rAcademicId)
			FROM sGSEB.tResultDetail RD WHERE AcademicId = @rAcademicId AND ClassSubjectId=@rClassSubjectId
		
	END
	
	--- Anusuchi B Mark Update
	IF @IsPrimary =1 AND @rExamOrder =2
	BEGIN
			IF EXISTS (SELECT AcademicId FROM sGSEB.tAnusuchiB WHERE AcademicId=@rAcademicId
				AND ClassSubjectId=@rClassSubjectId AND GSEBExamId =1)
					BEGIN
					UPDATE RD SET FA2 = 
					 ISNULL(Pd1,0)+ ISNULL(Pd2,0) + ISNULL(Pd3,0) + ISNULL(Pd4,0) + ISNULL(Pd5,0)
					+ ISNULL(Pd6,0) + ISNULL(Pd7,0)	+ ISNULL(Pd8,0) + ISNULL(Pd9,0) + ISNULL(Pd10,0)
					+ ISNULL(Pd11,0) + ISNULL(Pd12,0) + ISNULL(Pd13,0) + ISNULL(Pd14,0) + ISNULL(Pd15,0)
					+ ISNULL(Pd16,0) + ISNULL(Pd17,0) + ISNULL(Pd18,0) + ISNULL(Pd19,0) + ISNULL(Pd20,0)
					+ ISNULL(Pd21,0) + ISNULL(Pd22,0) + ISNULL(Pd23,0) + ISNULL(Pd24,0) + ISNULL(Pd25,0)
					+ ISNULL(Pd26,0) + ISNULL(Pd27,0) + ISNULL(Pd28,0) + ISNULL(Pd29,0) + ISNULL(Pd30,0)
					+ ISNULL(Pd31,0) + ISNULL(Pd32,0) + ISNULL(Pd33,0) + ISNULL(Pd34,0) + ISNULL(Pd35,0)
					+ ISNULL(Pd36,0) + ISNULL(Pd37,0) + ISNULL(Pd38,0) + ISNULL(Pd39,0) + ISNULL(Pd40,0) 	
					FROM sGSEB.tResultDetail RD INNER JOIN sGSEB.tAnusuchiB  AB ON RD.AcademicId = AB.AcademicId
					AND RD.ClassSubjectId = AB.ClassSubjectId
					WHERE AB.GSEBExamId = 1 AND AB.ClassSubjectId = @rClassSubjectId AND AB.AcademicId = @rAcademicId
					END
	END
	IF @IsPrimary =1 AND @rExamOrder =4
	BEGIN
			IF EXISTS (SELECT AcademicId FROM sGSEB.tAnusuchiB WHERE AcademicId=@rAcademicId
				AND ClassSubjectId=@rClassSubjectId AND GSEBExamId =2)
					BEGIN
					UPDATE RD SET FA2 = 
					 ISNULL(Pd1,0)+ ISNULL(Pd2,0) + ISNULL(Pd3,0) + ISNULL(Pd4,0) + ISNULL(Pd5,0)
					+ ISNULL(Pd6,0) + ISNULL(Pd7,0)	+ ISNULL(Pd8,0) + ISNULL(Pd9,0) + ISNULL(Pd10,0)
					+ ISNULL(Pd11,0) + ISNULL(Pd12,0) + ISNULL(Pd13,0) + ISNULL(Pd14,0) + ISNULL(Pd15,0)
					+ ISNULL(Pd16,0) + ISNULL(Pd17,0) + ISNULL(Pd18,0) + ISNULL(Pd19,0) + ISNULL(Pd20,0)
					+ ISNULL(Pd21,0) + ISNULL(Pd22,0) + ISNULL(Pd23,0) + ISNULL(Pd24,0) + ISNULL(Pd25,0)
					+ ISNULL(Pd26,0) + ISNULL(Pd27,0) + ISNULL(Pd28,0) + ISNULL(Pd29,0) + ISNULL(Pd30,0)
					+ ISNULL(Pd31,0) + ISNULL(Pd32,0) + ISNULL(Pd33,0) + ISNULL(Pd34,0) + ISNULL(Pd35,0)
					+ ISNULL(Pd36,0) + ISNULL(Pd37,0) + ISNULL(Pd38,0) + ISNULL(Pd39,0) + ISNULL(Pd40,0) 	
					FROM sGSEB.tResultDetail RD INNER JOIN sGSEB.tAnusuchiB  AB ON RD.AcademicId = AB.AcademicId
					AND RD.ClassSubjectId = AB.ClassSubjectId
					WHERE AB.GSEBExamId = 2 AND AB.ClassSubjectId = @rClassSubjectId AND AB.AcademicId = @rAcademicId
					END
	END

-- Primary Result Evaluation End
		
--Grade Evaluation
DECLARE @MinimumScore decimal(5,2)
DECLARE @GradeTitle nvarchar(10)
DECLARE @GradePoint decimal(6,2)
DECLARE @lCount int
DECLARE @lDataSetID INT

SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamDetail WHERE ExamId = @rGSEBExamId AND ClassSubjectId = @rClassSubjectId

CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		GradeTitle nvarchar(10),
		GradePoint decimal(6,2) 					 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,GradeCode,GradePoint		
	FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
	order by Id Asc

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
DECLARE @lloopCount int
--set @lloopCount=1
while ( @lCount > 0 )
BEGIN
 
		SELECT @MinimumScore =MinimumScore,@GradeTitle=GradeTitle,@GradePoint=GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		
		IF @rExamOrder = 1 
		BEGIN				
			Update sGSEB.tResultDetail  Set FA1Grade = @GradeTitle WHERE FA1 >= @MinimumScore 
		END
		IF @rExamOrder = 2 
		BEGIN				
			Update sGSEB.tResultDetail  Set FA2Grade = @GradeTitle WHERE FA2 >= @MinimumScore 
		END
		IF @rExamOrder = 3 
		BEGIN				
			Update sGSEB.tResultDetail  Set SA1Grade = @GradeTitle WHERE SA1 >= @MinimumScore 
		END
		IF @rExamOrder = 4 
		BEGIN				
			Update sGSEB.tResultDetail  Set FA3Grade = @GradeTitle WHERE FA3 >= @MinimumScore 
		END
		IF @rExamOrder = 5 
		BEGIN				
			Update sGSEB.tResultDetail  Set FA4Grade = @GradeTitle WHERE FA4 >= @MinimumScore 
		END
		IF @rExamOrder = 6 
		BEGIN		
			Update sGSEB.tResultDetail  Set SA2Grade = @GradeTitle WHERE SA2 >= @MinimumScore 
		END
	
		Update sGSEB.tResultDetail  Set Grade = @GradeTitle WHERE (FA1+FA2+SA1+FA3+FA4+SA2)/6 >= @MinimumScore 
		
		--- Result Detail Optional Grade Calculation
		
		IF EXISTS (SELECT ACADEMICID FROM sGSEB.tResultDetailOptional WHERE AcademicId=@rAcademicId AND ClassSubjectId=@rClassSubjectId)
		BEGIN
		
				Update RDO  Set GradeTerm1 = @GradeTitle FROM sGSEB.tResultDetailOptional RDO
				INNER JOIN sGSEB.tResultDetail RD ON RD.AcademicId=RDO.AcademicId AND RD.ClassSubjectId=RDO.ClassSubjectId
				AND (RD.FA1+RD.FA2+RD.SA1)/3 >= @MinimumScore 

				Update RDO  Set GradeTerm2 = @GradeTitle FROM sGSEB.tResultDetailOptional RDO
				INNER JOIN sGSEB.tResultDetail RD ON RD.AcademicId=RDO.AcademicId AND RD.ClassSubjectId=RDO.ClassSubjectId
				AND (RD.FA3+RD.FA4+RD.SA2)/3 >= @MinimumScore 
		END
		ELSE
		BEGIN
		
			INSERT INTO sGSEB.tResultDetailOptional
			(	AcademicId,
				ClassSubjectId) 
			VALUES
			(	@rAcademicId,
				@rClassSubjectId)
	
			Update RDO  Set GradeTerm1 = @GradeTitle FROM sGSEB.tResultDetailOptional RDO
			INNER JOIN sGSEB.tResultDetail RD ON RD.AcademicId=RDO.AcademicId AND RD.ClassSubjectId=RDO.ClassSubjectId
			AND (RD.FA1+RD.FA2+RD.SA1)/3 >= @MinimumScore 

			Update RDO  Set GradeTerm2 = @GradeTitle FROM sGSEB.tResultDetailOptional RDO
			INNER JOIN sGSEB.tResultDetail RD ON RD.AcademicId=RDO.AcademicId AND RD.ClassSubjectId=RDO.ClassSubjectId
			AND (RD.FA3+RD.FA4+RD.SA2)/3 >= @MinimumScore 

			
		END
			
		SET @lCount = @lCount - 1
 END

	--End Grade Evaluation	
	
	-------- indicator Concatanate with Number Separation
	-- term1
	UPDATE sGSEB.tActivityIndicatorScore set Term1Indicator = 0 where Term1Indicator= '' or Term1Indicator is null
	AND AcademicId =@rAcademicId
	
	UPDATE AIS1 SET TERM1INDICATORTEXT = L1.Indicator1 FROM sGSEB.tActivityIndicatorScore AIS1
	INNER JOIN (
	SELECT [AcademicId] ,[ActivityId] ,
	STUFF(
	(SELECT DISTINCT ', ' +  AI.title FROM sGSEB.tActivityIndicatorMaster  AI
	INNER JOIN sGSEB.tActivityIndicatorScore AIS ON AI.ActivityId = AIS.ActivityId
	AND ',' +  REPLACE(Term1Indicator,'.',',') + ',' like '%,' + cast(AI.Number as varchar(10)) + ',%'
	where AIS.AcademicId=A1.AcademicId AND AIS.ActivityId=A1.ActivityId
	FOR XML PATH('')) ,1,1,'') as Indicator1
	FROM sGSEB.tActivityIndicatorScore A1 
	GROUP BY AcademicId,ActivityId) L1 
	ON L1.AcademicId=AIS1.AcademicId AND L1.ActivityId=AIS1.ActivityId
	WHERE L1.AcademicId =@rAcademicId
 
	--- term2
	UPDATE sGSEB.tActivityIndicatorScore set Term2Indicator = 0 where Term1Indicator= '' or Term2Indicator is null
	AND AcademicId =@rAcademicId
	
	UPDATE AIS1 SET Term2IndicatorText = L1.Indicator2 FROM sGSEB.tActivityIndicatorScore AIS1
	INNER JOIN (
	SELECT [AcademicId] ,[ActivityId] ,
	STUFF(
	(SELECT DISTINCT ', ' +  AI.title FROM sGSEB.tActivityIndicatorMaster  AI
	INNER JOIN sGSEB.tActivityIndicatorScore AIS ON AI.ActivityId = AIS.ActivityId
	AND ',' +  REPLACE(Term2Indicator,'.',',') + ',' like '%,' + cast(AI.Number as varchar(10)) + ',%'
	where AIS.AcademicId=A1.AcademicId AND AIS.ActivityId=A1.ActivityId
	FOR XML PATH('')) ,1,1,'') as Indicator2
	FROM sGSEB.tActivityIndicatorScore A1 
	GROUP BY AcademicId,ActivityId) L1 
	ON L1.AcademicId=AIS1.AcademicId AND L1.ActivityId=AIS1.ActivityId
	WHERE L1.AcademicId =@rAcademicId

		--- Optional Subject
			-- term1
		UPDATE sGSEB.tResultDetailOptional set Indicator1 = 0 where Indicator1= '' or Indicator1 is null
		AND AcademicId =@rAcademicId
		UPDATE AIS1 SET Indicator1Text = L1.Indicator1 FROM sGSEB.tResultDetailOptional AIS1
		INNER JOIN (
		SELECT [AcademicId] ,[ClassSubjectId],
		STUFF(
		(SELECT DISTINCT ', ' +  AI.title FROM sSetup.vClassSubject CS 
		INNER JOIN sGSEB.tResultDetailOptional AIS ON CS.ClassSubjectId = AIS.ClassSubjectId
		INNER JOIN sGSEB.tSubjectIndicatorMaster  AI ON CS.SubjectId=AI.SubjectId
		AND ',' +  REPLACE(Indicator1,'.',',') + ',' like '%,' + cast(AI.Number as varchar(10)) + ',%'
		where AIS.AcademicId=A1.AcademicId AND AIS.ClassSubjectId=A1.ClassSubjectId
		FOR XML PATH('')) ,1,1,'') as Indicator1
		FROM sGSEB.tResultDetailOptional A1 
		GROUP BY AcademicId,ClassSubjectId) L1 
		ON L1.AcademicId=AIS1.AcademicId AND L1.ClassSubjectId=AIS1.ClassSubjectId
		AND L1.AcademicId=@rAcademicId

			-- term2
		UPDATE sGSEB.tResultDetailOptional set Indicator2 = 0 where Indicator2= '' or Indicator2 is null
		AND AcademicId =@rAcademicId
		UPDATE AIS1 SET Indicator2Text = L1.Indicator2 FROM sGSEB.tResultDetailOptional AIS1
		INNER JOIN (
		SELECT [AcademicId] ,[ClassSubjectId],
		STUFF(
		(SELECT DISTINCT ', ' +  AI.title FROM sSetup.vClassSubject CS 
		INNER JOIN sGSEB.tResultDetailOptional AIS ON CS.ClassSubjectId = AIS.ClassSubjectId
		INNER JOIN sGSEB.tSubjectIndicatorMaster  AI ON CS.SubjectId=AI.SubjectId
		AND ',' +  REPLACE(Indicator2,'.',',') + ',' like '%,' + cast(AI.Number as varchar(10)) + ',%'
		where AIS.AcademicId=A1.AcademicId AND AIS.ClassSubjectId=A1.ClassSubjectId
		FOR XML PATH('')) ,1,1,'') as Indicator2
		FROM sGSEB.tResultDetailOptional A1 
		GROUP BY AcademicId,ClassSubjectId) L1 
		ON L1.AcademicId=AIS1.AcademicId AND L1.ClassSubjectId=AIS1.ClassSubjectId
		AND L1.AcademicId=@rAcademicId
	-------- end indicator combine
	 SELECT 1 AS Result
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pGSEBResultUpdate]
	  
	  @rMappExamId INT
	 ,@rGSEBExamId INT	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION		
		BEGIN
		  IF @rMappExamId= 1 
			BEGIN
				UPDATE GR SET GR.Total1 = AR.TotalMarks, GR.Obtain1 = AR.totalObtain,GR.Percentage1 = AR.Percentage,GR.Percentile1=AR.Percentile,
				GR.Grade1=AR.ResultGrade,GR.Result1 = AR.ResultStatus
				FROM sGSEB.tResult GR 
				INNER JOIN sAssessment.tResult AR ON AR.AcademicId = GR.AcademicId 
				AND AR.ExamId=@rGSEBExamId 
			END  
		 ELSE
			BEGIN
				UPDATE GR SET GR.Total2 = AR.TotalMarks, GR.Obtain2 = AR.totalObtain,GR.Percentage2 = AR.Percentage,GR.Percentile2=AR.Percentile,
				GR.Grade2=AR.ResultGrade,GR.Result2 = AR.ResultStatus
				FROM sGSEB.tResult GR 
				INNER JOIN sAssessment.tResult AR ON AR.AcademicId = GR.AcademicId 
				AND AR.ExamId=@rGSEBExamId 
			END  
		 
		 	UPDATE GR SET GR.Total = (GR.Total1+GR.Total2), 
		 		GR.Obtain = (GR.Obtain1+GR.Obtain2),
		 		GR.Percentage = (GR.Obtain /GR.Total)*100,
		 		GR.Percentile=0		
				FROM sGSEB.tResult GR 
			
		-------- Grade Evaluate
		DECLARE @MinimumScore decimal(5,2)
		DECLARE @GradeTitle nvarchar(10)
		DECLARE @GradePoint decimal(6,2)
		DECLARE @lCount int
		DECLARE @lDataSetID INT

		SELECT @lDataSetID=GradeSetId FROM sAssessment.tExamMaster WHERE Id = @rGSEBExamId 

		CREATE TABLE #tempGradeSetDetail
			(
				Id INT IDENTITY (1, 1),
				MinimumScore decimal(5,2),
				GradeTitle nvarchar(10),
				GradePoint decimal(6,2) 					 
			) 
			INSERT INTO #tempGradeSetDetail
			SELECT MinimumScore,GradeCode,GradePoint		
			FROM sAssessment.tGradeSetDetail where GradesetId=@lDataSetID
			order by Id Asc

		SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
		WHILE ( @lCount > 0 )
			BEGIN
				SELECT @MinimumScore =MinimumScore,@GradeTitle=GradeTitle,@GradePoint=GradePoint
				FROM #tempGradeSetDetail WHERE Id = @lCount
				Update sGSEB.tResult  Set Grade = @GradeTitle WHERE Percentage >= @MinimumScore  
				SET @lCount = @lCount - 1
			END
			------------------------
			
			----- Evaluate Percentile
			DECLARE @lDivisionId int
			CREATE TABLE #tempDivision
			(
				Id INT IDENTITY (1, 1),
				DivisionId int
			) 
			INSERT INTO #tempDivision
			SELECT Distinct DivisionId FROM sAssessment.tResult R Inner Join sStudent.tAcademic A ON A.Id  = R.AcademicId
			AND R.ExamId=@rGSEBExamId ORDER BY A.DivisionId Asc			
			SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail			
			WHILE ( @lCount > 0 )
				BEGIN
					SELECT @lDivisionId = DivisionId FROM #tempDivision WHERE ID=@lCount
					EXEC [sGSEB].[pResultPercentileUpdate]	@lDivisionId
					SET @lCount = @lCount - 1
				END
			-----------------------
			SELECT 1 AS Result
		END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sGSEB].[pHetuDetailAdd]
	 
	        @rId int
           ,@rClassSubjectId int
           ,@rGSEBExamId int
           ,@rTitle nvarchar(100)
           ,@rNumber smallint
		   ,@rOrderIndex int	
		   ,@rUpdatedUserId bigint
		   ,@rIsObsolete bit
		   ,@rOrgId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @TOTALCOUNT AS INT
	 

SELECT @TOTALCOUNT = COUNT(Id) FROM sGSEB.thetuMaster WHERE ClassSubjectId =@rClassSubjectId AND GSEBExamId=@rGSEBExamId

IF 	 @TOTALCOUNT > 20 
	 BEGIN
		SELECT -103
	 END
ELSE IF EXISTS(SELECT ID FROM sGSEB.thetuMaster WHERE ClassSubjectId =@rClassSubjectId AND GSEBExamId=@rGSEBExamId AND TITLE=@rTitle)
BEGIN	
	SELECT -102
END 	 
ELSE IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sGSEB.tHetuMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sGSEB].[tHetuMaster]
			   (
			    [Id]
			   ,[ClassSubjectId]
			   ,[GSEBExamId]
			   ,[Title]
			   ,[Number] 
			   ,[OrgId]
			   ,[IsObsolete]
			   ,[OrderIndex]	
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rClassSubjectId
			   ,@rGSEBExamId
			   ,@rTitle
			   ,@rNumber
			   ,@rOrgId
			   ,@rIsObsolete
			   ,@rOrderIndex			   
			   ,@rUpdatedUserId			   
			   ,sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sGSEB].[tHetuMaster]
	    SET
			 
	          ClassSubjectId=@rClassSubjectId
	         ,GSEBExamId = @rGSEBExamId 
	         ,Title=@rTitle
	         ,Number=@rNumber
	         ,OrgId=@rOrgId
	         ,IsObsolete=@rIsObsolete
			 ,OrderIndex=@rOrderIndex
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pHetuDetailGet]
	 @rClassSubjectId int,
	 @rGSEBExamId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT			
			HM.Id,
			HM.ClassSubjectId,
			HM.GSEBExamId,
			ISNULL(HM.Number,0) AS Number,
			ISNULL(HM.TITLE,'') AS TITLE,
			HM.OrderIndex
  FROM 
			sGSEB.[tHetuMaster] HM
WHERE 
			(HM.ClassSubjectId=@rClassSubjectId OR @rClassSubjectId = 0) 
			AND (HM.GSEBExamId = @rGSEBExamId OR @rGSEBExamId = 0)
			 order by HM.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pHetuGroupDelete]
@rClassSubjectId bigint,
@rGSEBExamId int
AS
BEGIN
BEGIN TRY
	IF NOT EXISTS (SELECT ClassSubjectId FROM sGSEB.tHetuScore WHERE ClassSubjectId = @rClassSubjectId AND GSEBExamId=@rGSEBExamId)	
	  BEGIN
		DELETE	FROM sGSEB.tHetuMaster WHERE ClassSubjectId=@rClassSubjectId AND GSEBExamId = @rGSEBExamId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pHetuMasterDelete]
@rId	 bigint,
@rGSEBExamId smallint,
@rClassSubjectId int

AS
BEGIN
BEGIN TRY

DECLARE @TOTALSCORECOUNT INT
DECLARE @TOTALCOUNT AS INT

SELECT @TOTALSCORECOUNT= MAX(CASE WHEN HETU1 >= 1 THEN 1 ELSE 0 END  +
CASE WHEN HETU2 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU3 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU4 >= 1 THEN 1 ELSE 0 END  +
CASE WHEN HETU5 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU6 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU7 >= 1 THEN 1 ELSE 0 END  +
CASE WHEN HETU8 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU9 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU10 >= 1 THEN 1 ELSE 0 END  +
CASE WHEN HETU11 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU12 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU13 >= 1 THEN 1 ELSE 0 END  +
CASE WHEN HETU14 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU15 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU16 >= 1 THEN 1 ELSE 0 END  +
CASE WHEN HETU17 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU18 >= 1 THEN 1 ELSE 0 END  + CASE WHEN HETU19 >= 1 THEN 1 ELSE 0 END  +
CASE WHEN HETU20 >= 1 THEN 1 ELSE 0 END )  FROM sGSEB.THETUSCORE 
WHERE ClassSubjectId =@rClassSubjectId AND GSEBExamId=@rGSEBExamId GROUP BY CLASSSUBJECTID,GSEBEXAMID

SELECT @TOTALCOUNT = COUNT(Id) FROM sGSEB.thetuMaster WHERE ClassSubjectId =@rClassSubjectId AND GSEBExamId=@rGSEBExamId

	IF @TOTALSCORECOUNT < @TOTALCOUNT 
	  BEGIN
		DELETE	FROM sGSEB.tHetuMaster WHERE Id=@rId	
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sGSEB].[pHetuScoreAdd]
	 
	        @rAcademicId bigint
           ,@rClassSubjectId int
           ,@rGSEBExamId int
           ,@rHetu1 smallint
           ,@rHetu2 smallint
           ,@rHetu3 smallint
           ,@rHetu4 smallint
           ,@rHetu5 smallint
           ,@rHetu6 smallint
           ,@rHetu7 smallint
           ,@rHetu8 smallint
           ,@rHetu9 smallint
           ,@rHetu10 smallint
           ,@rHetu11 smallint
           ,@rHetu12 smallint
           ,@rHetu13 smallint
           ,@rHetu14 smallint
           ,@rHetu15 smallint
           ,@rHetu16 smallint
           ,@rHetu17 smallint
           ,@rHetu18 smallint
           ,@rHetu19 smallint
           ,@rHetu20 smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF NOT EXISTS (SELECT ACADEMICID FROM sGSEB.tHetuScore WHERE ACADEMICID=@rAcademicId AND CLASSSUBJECTID =@rClassSubjectId
				AND GSEBExamId = @rGSEBExamId )	
BEGIN
	INSERT INTO [sGSEB].[tHetuScore]
			   (
			    [AcademicId]
			   ,[ClassSubjectId]
			   ,[GSEBExamId]
			   ,[Hetu1]
			   ,[Hetu2]
			   ,[Hetu3]
			   ,[Hetu4]
			   ,[Hetu5]
			   ,[Hetu6]
			   ,[Hetu7]
			   ,[Hetu8]
			   ,[Hetu9]
			   ,[Hetu10]
			   ,[Hetu11]
			   ,[Hetu12]
			   ,[Hetu13]
			   ,[Hetu14]
			   ,[Hetu15]
			   ,[Hetu16]
			   ,[Hetu17]
			   ,[Hetu18]
			   ,[Hetu19]
			   ,[Hetu20]
			   )
		 VALUES
			   (
				@rAcademicId
			   ,@rClassSubjectId
			   ,@rGSEBExamId
			   ,@rHetu1
			   ,@rHetu2
			   ,@rHetu3
			   ,@rHetu4
			   ,@rHetu5
			   ,@rHetu6
			   ,@rHetu7
			   ,@rHetu8
			   ,@rHetu9
			   ,@rHetu10
			   ,@rHetu11
			   ,@rHetu12
			   ,@rHetu13
			   ,@rHetu14
			   ,@rHetu15
			   ,@rHetu16
			   ,@rHetu17
			   ,@rHetu18
			   ,@rHetu19
			   ,@rHetu20
			   )
		    SELECT 1 AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	    UPDATE  [sGSEB].[tHetuScore]
	    SET  
	         Hetu1=@rHetu1
	         ,Hetu2=@rHetu2
	         ,Hetu3=@rHetu3
	         ,Hetu4=@rHetu4
	         ,Hetu5=@rHetu5
	         ,Hetu6=@rHetu6
	         ,Hetu7=@rHetu7
	         ,Hetu8=@rHetu8
	         ,Hetu9=@rHetu9
	         ,Hetu10=@rHetu10
	         ,Hetu11=@rHetu11
	         ,Hetu12=@rHetu12
	         ,Hetu13=@rHetu13
	         ,Hetu14=@rHetu14
	         ,Hetu15=@rHetu15
	         ,Hetu16=@rHetu16
	         ,Hetu17=@rHetu17
	         ,Hetu18=@rHetu18
	         ,Hetu19=@rHetu19
	         ,Hetu20=@rHetu20
	      WHERE AcademicId = @rAcademicId AND  ClassSubjectId=@rClassSubjectId 
	      AND GSEBExamId = @rGSEBExamId 
	      SELECT 1 AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pHetuScoreDivisionDelete]
@rClassSubjectId bigint,
@rGSEBExamId int,
@rDivisionId int
AS
BEGIN
BEGIN TRY
	  BEGIN
		DELETE	FROM sGSEB.tHetuScore WHERE ClassSubjectId=@rClassSubjectId AND GSEBExamId = @rGSEBExamId AND
		AcademicId IN (SELECT AcademicId From sStudent.vStudentFull SF WHERE DivisionId = @rDivisionId)		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pHetuScoreGet]
	 @rClassSubjectId int,
	 @rGSEBExamId int,
	 @rDivisionId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT				
		@rClassSubjectId AS ClassSubjectId,
		@rGSEBExamId AS GSEBExamId,
		SF.AcademicId AS AcademicId,
		SF.NUMBER,
		SF.ROLLNO,
		SF.NAME AS STUDENTNAME,
		ISNULL(HETU1,0) AS HETU1,
		ISNULL(HETU2,0) AS HETU2,
		ISNULL(HETU3,0) AS HETU3,
		ISNULL(HETU4,0) AS HETU4,
		ISNULL(HETU5,0) AS HETU5,
		ISNULL(HETU6,0) AS HETU6,
		ISNULL(HETU7,0) AS HETU7,
		ISNULL(HETU8,0) AS HETU8,
		ISNULL(HETU9,0) AS HETU9,
		ISNULL(HETU10,0) AS HETU10,
		ISNULL(HETU11,0) AS HETU11,
		ISNULL(HETU12,0) AS HETU12,
		ISNULL(HETU13,0) AS HETU13,
		ISNULL(HETU14,0) AS HETU14,
		ISNULL(HETU15,0) AS HETU15,
		ISNULL(HETU16,0) AS HETU16,
		ISNULL(HETU17,0) AS HETU17,
		ISNULL(HETU18,0) AS HETU18,
		ISNULL(HETU19,0) AS HETU19,
		ISNULL(HETU20,0) AS HETU20,
		(Select count(*) From sGSEB.tHetuMaster Where ClassSubjectId= @rClassSubjectId AND GSEBExamId= @rGSEBExamId) AS TotalHetu
		
  FROM 
			sGSEB.[tHetuScore] HS 
			RIGHT JOIN sStudent.vStudentFull SF ON SF.AcademicId = HS.AcademicId
			AND (HS.ClassSubjectId=@rClassSubjectId OR @rClassSubjectId = 0) 
   		    AND (HS.GSEBExamId = @rGSEBExamId OR @rGSEBExamId = 0)
 
 WHERE  SF.DIVISIONID = @rDivisionId
 
 ORDER BY SF.DIVISIONID,SF.ROLLNO
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pResultDelete]
	 @rGSEBExamId int
	,@rClassId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
			IF @rGSEBExamId=1 
				BEGIN	
					UPDATE RD SET RD.Total1=0,RD.Obtain1=0,RD.Result1='',RD.Percentage1=0,RD.Percentile1=0,
						   RD.Remark1='',RD.AttendanceTerm1=0,RD.WorkingDaysTerm1=0,
						   RD.Total=0,RD.Obtain=0,RD.Result='',RD.Percentage=0,RD.Percentile=0,
						   RD.Remark='',RD.AttendanceTotal=0,RD.WorkingDayTotal=0						   
						   FROM sGSEB.tResult RD  
						   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RD.AcademicId AND SA.ClassId=@rClassId 
							
					UPDATE RD SET RD.FA1=0,RD.FA1GRADE='',RD.FA2=0,RD.FA2GRADE='',RD.SA1=0,RD.SA1GRADE='',RD.GRADE='' 
							FROM sGSEB.tResultDetail RD
							INNER JOIN sGSEB.tResult R ON RD.AcademicId = R.AcademicId 
							INNER JOIN sStudent.vStudentAcademic  SA ON SA.AcademicId=R.AcademicId AND SA.ClassId=@rClassId
					
					UPDATE RO SET RO.Indicator1='',RO.GradeTerm1='',RO.Indicator1Text='' FROM sGSEB.tResultDetailOptional RO
							INNER JOIN sStudent.vStudentAcademic  SA ON SA.AcademicId=RO.AcademicId AND SA.ClassId=@rClassId
					
					SELECT 1 AS RESULT
				END
				
			IF @rGSEBExamId=2 
				BEGIN	
					UPDATE RD SET RD.Total2=0,RD.Obtain2=0,RD.Result2='',RD.Percentage2=0,RD.Percentile2=0,
						   RD.Remark2='',RD.AttendanceTerm2=0,RD.WorkingDaysTerm2=0,
						   RD.Total=0,RD.Obtain=0,RD.Result='',RD.Percentage=0,RD.Percentile=0,
						   RD.Remark='',RD.AttendanceTotal=0,RD.WorkingDayTotal=0						   
						   FROM sGSEB.tResult RD  
						   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RD.AcademicId AND SA.ClassId=@rClassId 
							
					UPDATE RD SET RD.FA3=0,RD.FA3GRADE='',RD.FA4=0,RD.FA4GRADE='',RD.SA2=0,RD.SA2GRADE='',RD.GRADE='' 
							FROM sGSEB.tResultDetail RD
							INNER JOIN sGSEB.tResult R ON RD.AcademicId = R.AcademicId 
							INNER JOIN sStudent.vStudentAcademic  SA ON SA.AcademicId=RD.AcademicId AND SA.ClassId=@rClassId
					
					UPDATE RO SET RO.Indicator2='',RO.GradeTerm2='',RO.Indicator2Text='' FROM sGSEB.tResultDetailOptional RO
							INNER JOIN sStudent.vStudentAcademic  SA ON SA.AcademicId=RO.AcademicId AND SA.ClassId=@rClassId
					
					SELECT 1 AS RESULT
			END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pResultPercentileUpdate]	
	 @rDivisionId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION		
DECLARE @AcademicId int
DECLARE @TotalObtain Decimal(5,2)
DECLARE @lCount int
DECLARE @TotalStudent int
DECLARE @CountStuent int
DECLARE @Percentile Decimal(5,2)

begin
	CREATE TABLE #tempPercentile
 		(
 			Id INT IDENTITY (1, 1),
			AcademicId bigint, 			
 			TotalObtain decimal(6,2)
 		) 
 		INSERT INTO #tempPercentile
 		SELECT R.AcademicId,ISNULL(R.Obtain,0) AS TotalObtain				
		FROM sGSEB.tResult R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.DivisionId=@rDivisionId AND StatusId=1
		order by R.Obtain ASC,R.AcademicId


SELECT @lCount =  COUNT(Id) FROM #tempPercentile
SET @TotalStudent=@lCount

while (@lCount > 0 )
BEGIN
	    SELECT @CountStuent=count(R.AcademicId)	
		FROM sGSEB.tResult R
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.DivisionId=@rDivisionId	AND StatusId=1	
		where R.Obtain < (Select TotalObtain From #tempPercentile Where Id = @lCount)

		SET @Percentile = @CountStuent*100/@TotalStudent
		
		Update R Set R.Percentile = @Percentile From sGSEB.tResult R
		INNER JOIN 		#tempPercentile tP	ON R.AcademicId=tP.AcademicId
		Where tp.Id=@lCount
		
		SET @lCount = @lCount - 1
 END	
END
Drop Table #tempPercentile
--SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptActivityIndicatorListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,	
	 @rDivisionId int,
	 @rActivityId int,
	 @rFromRollNo int,
	 @rToRollNo int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BVC.ClassName,
			BVC.DivisionName,
			SF.AcademicId,
			SF.Name,SF.Number, 
			AM.ID AS ActivityId,
			AM.Title AS ActivityName,							
			ISNULL(Term1IndicatorText,'') AS Term1IndicatorText,						
			ISNULL(Term2IndicatorText,'') AS Term2IndicatorText  						
	
	FROM sGSEB.tActivityIndicatorScore AIS							
		INNER JOIN sGSEB.tActivityMaster AM ON AIS.ActivityId = AM.Id							
		INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId=AIS.AcademicId AND SF.StatusId = 1							
		INNER JOIN sSetup.vBatchClassDivision BVC ON BVC.DivisionId = SF.DivisionId							
	
	WHERE (SF.DivisionId = @rDivisionId)
		AND AM.Id = @rActivityId
		AND SF.BatchId=@rBatchId 	
		AND (SF.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
		AND (SF.RollNo <= @rToRollNo OR @rToRollNo = 0)
		
	ORDER BY SF.AcademicId,AM.OrderIndex							
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptAnusuchi14Get]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,	
	 @rDivisionId int,
	 @rClassSubjectId int,
	 @rGSEBExamId smallint,
	 @rFromRollNo int,
	 @rToRollNo int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

		--SELECT	'' AS ClassName,
		--		'' AS DivisionName,
		--		'' AS ClassSubjectId,
		--		'' AS SubjectName,
		--		'' AS SA1,
		--		'' AS FA1,
		--		'' AS FA2,
		--		'' AS FA3,
		--		'' AS FA4,
		--		'' AS FA5
	
	----declare @rDivisionId int
	----declare  @rClassSubjectId int
	----Declare @rGSEBExamId smallint
	---- set @rDivisionId = 999900010
	---- set @rClassSubjectId = 999900002
	---- set @rGSEBExamId = 1
	 
	CREATE TABLE #tempAnusuchi14		
(	ClassSubjectId int,	
	SA1 NVARCHAR(50),	
	FA1 NVARCHAR(50),	
	FA2 NVARCHAR(50),	
	FA3 NVARCHAR(50),	
	FA4 NVARCHAR(50),	
	FA5 NVARCHAR(50),	
)		
INSERT INTO #tempAnusuchi14 (SA1,ClassSubjectId,FA1,FA2,FA3,FA4,FA5) VALUES ('SA 0 TO 6',@rClassSubjectId,'','','','','')		
INSERT INTO #tempAnusuchi14 (SA1,ClassSubjectId,FA1,FA2,FA3,FA4,FA5) VALUES ('SA 7 TO 12',@rClassSubjectId,'','','','','')		
INSERT INTO #tempAnusuchi14 (SA1,ClassSubjectId,FA1,FA2,FA3,FA4,FA5) VALUES ('SA 13 TO 18',@rClassSubjectId,'','','','','')		
INSERT INTO #tempAnusuchi14 (SA1,ClassSubjectId,FA1,FA2,FA3,FA4,FA5) VALUES ('SA 19 TO 24',@rClassSubjectId,'','','','','')		
INSERT INTO #tempAnusuchi14 (SA1,ClassSubjectId,FA1,FA2,FA3,FA4,FA5) VALUES ('SA 25 TO 30',@rClassSubjectId,'','','','','')		
		
CREATE TABLE #tempfasa		
(		
	Id int identity,	
	Expr1 decimal(6,2),	
	SA1 decimal(6,2),	
	Expr2 decimal(6,2),	
	SA2 decimal(6,2),	
	AcademicId Bigint,	
	RollNo int,	
	ClassSubjectId int	
) 		

IF @rGSEBExamId = 1 
BEGIN
	INSERT INTO #tempfasa		
	SELECT FA1+FA2 AS EXPR1,SA1,0 AS EXPR2, 0 AS SA2,RD.AcademicId,SA.RollNo,ClassSubjectId 
	FROM sGSEB.tResultDetail RD		
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=RD.AcademicId 
	AND SA.DivisionId = @rDivisionId AND SA.StatusId = 1 AND 		
	RD.ClassSubjectId=@rClassSubjectId		
	AND (SA.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
	AND (SA.RollNo <= @rToRollNo OR @rToRollNo = 0)
	ORDER BY RollNo,ClassSubjectId		
END
ELSE
BEGIN
	INSERT INTO #tempfasa		
	SELECT 0 AS EXPR1,0 AS SA1,FA3+FA4 AS EXPR2,SA2,RD.AcademicId,SA.RollNo,ClassSubjectId 
	FROM sGSEB.tResultDetail RD		
	INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=RD.AcademicId 
	AND SA.DivisionId = @rDivisionId AND SA.StatusId = 1 AND 		
	RD.ClassSubjectId=@rClassSubjectId	
	AND (SA.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
	AND (SA.RollNo <= @rToRollNo OR @rToRollNo = 0)	
	ORDER BY RollNo,ClassSubjectId		
END

		
declare @lCount int		
Declare @lExpr1 decimal(6,2)		
Declare @lExpr2 decimal(6,2)		
Declare @lSA1 decimal(6,2)		
Declare @lSA2  decimal(6,2)		
DECLARE @lFACode smallint		
DECLARE @lSACode NVARCHAR(20)		
DECLARE @lRollno int		
DECLARE @lFirsrRec int		
set @lFirsrRec =  1		
Select @lCount=Max(Id) From #tempfasa		
While @lFirsrRec <= @lCount		
Begin		
	Select @lExpr1=Expr1,@lExpr2=Expr2,@lSA1=SA1,@lSA2=SA2,@lRollno=RollNo From #tempfasa Where Id=@lFirsrRec	
		
	IF (@lExpr1 >= 0 AND @lExpr1 < = 4) OR (@lExpr2 >= 0 AND @lExpr2 < = 4)  BEGIN SET @lFACode=1 END	
	IF (@lExpr1 >= 5 AND @lExpr1 < = 8) OR (@lExpr2 >= 5 AND @lExpr2 < = 8)  BEGIN SET @lFACode=2 END	
	IF (@lExpr1 >= 9 AND @lExpr1 < = 12) OR (@lExpr2 >= 9 AND @lExpr2 < = 12)  BEGIN SET @lFACode=3 END	
	IF (@lExpr1 >= 13 AND @lExpr1 < = 16) OR (@lExpr2 >= 13 AND @lExpr2 < = 16)  BEGIN SET @lFACode=4 END	
	IF (@lExpr1 >= 17 AND @lExpr1 < = 20) OR (@lExpr2 >= 17 AND @lExpr2 < = 20)  BEGIN SET @lFACode=5 END	
		
	IF (@lSA1 >= 0 AND @lSA1 < = 6) OR (@lSA2 >= 0 AND @lSA2 < = 6)  BEGIN SET @lSACode='SA 0 TO 6' END	
	IF (@lSA1 >= 7 AND @lSA1 < = 12) OR (@lSA2 >= 7 AND @lSA2 < = 12)  BEGIN SET @lSACode='SA 7 TO 12' END	
	IF (@lSA1 >= 13 AND @lSA1 < = 18) OR (@lSA2 >= 13 AND @lSA2 < = 18)  BEGIN SET @lSACode='SA 13 TO 18' END	
	IF (@lSA1 >= 19 AND @lSA1 < = 24) OR (@lSA2 >= 19 AND @lSA2 < = 24)  BEGIN SET @lSACode='SA 19 TO 24' END	
	IF (@lSA1 >= 25 AND @lSA1 < = 30) OR (@lSA2 >= 25 AND @lSA2 < = 30)  BEGIN SET @lSACode='SA 25 TO 30' END	
		
	IF @lFACode = 1  BEGIN UPDATE #tempAnusuchi14 SET FA1 = CONVERT(nvarchar,FA1) + ',' + CONVERT(nvarchar,@lRollno) WHERE SA1 = @lSACode END	
	IF @lFACode = 2  BEGIN UPDATE #tempAnusuchi14 SET FA2 = CONVERT(nvarchar,FA2) + ',' + CONVERT(nvarchar,@lRollno) WHERE SA1 = @lSACode END	
	IF @lFACode = 3  BEGIN UPDATE #tempAnusuchi14 SET FA3 = CONVERT(nvarchar,FA3) + ',' + CONVERT(nvarchar,@lRollno) WHERE SA1 = @lSACode END	
	IF @lFACode = 4  BEGIN UPDATE #tempAnusuchi14 SET FA4 = CONVERT(nvarchar,FA4) + ',' + CONVERT(nvarchar,@lRollno) WHERE SA1 = @lSACode END	
	IF @lFACode = 5  BEGIN UPDATE #tempAnusuchi14 SET FA5 = CONVERT(nvarchar,FA5) + ',' + CONVERT(nvarchar,@lRollno) WHERE SA1 = @lSACode END	
		
		
	Set @lFirsrRec = @lFirsrRec + 1	
End		
		SELECT	BVC.ClassName,
				BVC.DivisionName,
				CS.ClassSubjectId,
				CS.SubjectName,
				AIS.SA1,
				AIS.FA1,
				AIS.FA2,
				AIS.FA3,
				AIS.FA4,
				AIS.FA5
		
		FROM sGSEB.#tempAnusuchi14 AIS		
			INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = AIS.ClassSubjectId 		
			INNER JOIN sSetup.vBatchClassDivision BVC ON CS.ClassId=BVC.ClassId 		
		
		WHERE BVC.DivisionId=@rDivisionId 		
		
		
drop table #tempAnusuchi14		
drop table #tempfasa		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptAnusuchi1A2AGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,	
	 @rClassId INT,
	 @rGSEBEXAMID INT,	 			
	 @rClassSubjectId INT,			
	 @rDivisionId int,
	 @rFromRollNo int,
	 @rToRollNo int	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
		--SELECT	@rBuilder1,
		--		@rBuilder2,		
		--		'' AS ClassName,
		--		'' AS DivisionName,
		--		'' AS RollNo,
		--		'' AS Name,
		--		'' AS Number,
		--		'' AS SubjectName,			
		--		'' AS AcademicId ,		
		--		'' AS FA11,		
		--		'' AS FA12,		
		--		'' AS FA13,		
		--		'' AS FA14,		
		--		'' AS FA15,		
		--		'' AS FA16,		
		--		'' AS FA1TOTAL,		
		--		'' AS FA15PERCENT,		
		--		'' AS FA21,		
		--		'' AS FA22,		
		--		'' AS FA23,		
		--		'' AS FA24,		
		--		'' AS FA25,		
		--		'' AS FA26,		
		--		'' AS FA2TOTAL,		
		--		'' AS FA25PERCENT,		
		--		'' AS SA11,		
		--		'' AS SA12,		
		--		'' AS SATOTAL,		
		--		'' AS SA5PERCENT
	
		
		
		
			
CREATE TABLE #tempAnusuchi1A			
(			
	AcademicId bigint,		
	FA11 DECIMAL(5,2),		
	FA12 DECIMAL(5,2),		
	FA13 DECIMAL(5,2),		
	FA14 DECIMAL(5,2),		
	FA15 DECIMAL(5,2),		
	FA16 DECIMAL(5,2),		
	FA1TOTAL DECIMAL(5,2),		
	FA15PERCENT DECIMAL(5,2),		
	FA21 DECIMAL(5,2),		
	FA22 DECIMAL(5,2),		
	FA23 DECIMAL(5,2),		
	FA24 DECIMAL(5,2),		
	FA25 DECIMAL(5,2),		
	FA26 DECIMAL(5,2),		
	FA2TOTAL DECIMAL(5,2),		
	FA25PERCENT DECIMAL(5,2),		
	SA11 DECIMAL(5,2),		
	SA12 DECIMAL(5,2),		
	SATOTAL DECIMAL(5,2),		
	SA5PERCENT DECIMAL(5,2)		
)			
INSERT INTO #tempAnusuchi1A (AcademicId) SELECT AcademicId FROM sStudent.vStudentAcademic WHERE DivisionId = @rDivisionId AND StatusId = 1			
			
CREATE TABLE #tempMainExamCombine			
(			
	ID INT IDENTITY,		
	SubExamId int,		
	ExamOrder Smallint		
)			
CREATE TABLE #tempSubExamCombine			
(			
	ID INT IDENTITY,		
	SubExamId int,		
	ExamOrder Smallint		
)			
			
INSERT INTO #tempMainExamCombine			
SELECT SubExamId,ExamOrder FROM sAssessment.tExamCombine EC
INNER JOIN sGSEB.tGSEBExamMapping EM ON EC.ExamId = EM.ExamId AND EM.ClassId = @rClassId 
WHERE EM.GSEBExamId = @rGSEBEXAMID

DECLARE @lCount int			
DECLARE @lSubCount int			
DECLARE @lMainExamId int			
Declare @lMainExamOrder smallint			
DECLARE @lSubExamId int			
Declare @lSubExamOrder smallint			
			
Select @lCount = MAX(Id) FROM #tempMainExamCombine			
WHILE @lCount > 0			
BEGIN			
	SELECT @lMainExamId= SUBEXAMID,@lMainExamOrder=ExamOrder FROM #tempMainExamCombine WHERE ID=@lCount		
	INSERT INTO #tempSubExamCombine SELECT SubExamId,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId = @lMainExamId		
	SELECT @lSubCount = MAX(ID) FROM #tempSubExamCombine		
	WHILE @lSubCount  > 0		
	BEGIN		
		SELECT @lSubExamId= SUBEXAMID,@lSubExamOrder=ExamOrder FROM #tempSubExamCombine WHERE ID=@lSubCount	
		IF @lMainExamOrder = 1 AND @lSubExamOrder = 1 	
		BEGIN	
			UPDATE TA SET FA11 = OBTAIN,FA15PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 1 AND @lSubExamOrder = 2 	
		BEGIN	
			UPDATE TA SET FA12 = OBTAIN,FA15PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 1 AND @lSubExamOrder = 3 	
		BEGIN	
			UPDATE TA SET FA13 = OBTAIN,FA15PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 1 AND @lSubExamOrder = 4 	
		BEGIN	
			UPDATE TA SET FA14 = OBTAIN,FA15PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 1 AND @lSubExamOrder = 5 	
		BEGIN	
			UPDATE TA SET FA15 = OBTAIN,FA15PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 1 AND @lSubExamOrder = 6 	
		BEGIN	
			UPDATE TA SET FA16 = OBTAIN,FA15PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 2 AND @lSubExamOrder = 1 	
		BEGIN	
			UPDATE TA SET FA21 = OBTAIN,FA25PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 2 AND @lSubExamOrder = 2 	
		BEGIN	
			UPDATE TA SET FA22 = OBTAIN,FA25PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 2 AND @lSubExamOrder = 3 	
		BEGIN	
			UPDATE TA SET FA23 = OBTAIN,FA25PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 2 AND @lSubExamOrder = 4 	
		BEGIN	
			UPDATE TA SET FA24 = OBTAIN,FA25PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 2 AND @lSubExamOrder = 5 	
		BEGIN	
			UPDATE TA SET FA25 = OBTAIN,FA25PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 2 AND @lSubExamOrder = 6 	
		BEGIN	
			UPDATE TA SET FA26 = OBTAIN,FA25PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 3 AND @lSubExamOrder = 1 	
		BEGIN	
			UPDATE TA SET SA11 = OBTAIN,SA5PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 3 AND @lSubExamOrder = 2 	
		BEGIN	
			UPDATE TA SET SA12 = OBTAIN,SA5PERCENT = Maximum FROM   #tempAnusuchi1A TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lSubExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
			
		SET @lSubCount  = @lSubCount  - 1	
	END		
	SET @lCount = @lCount - 1		
			
		UPDATE #tempAnusuchi1A SET FA1TOTAL = FA11 + FA12 + FA13+ FA14 + FA15 + FA16	
		UPDATE #tempAnusuchi1A SET FA2TOTAL = FA21 + FA22 + FA23+ FA24 + FA25 + FA26	
		UPDATE #tempAnusuchi1A SET SATOTAL = SA11 + SA12 	
			
		UPDATE #tempAnusuchi1A SET FA15PERCENT = (FA1TOTAL/FA15PERCENT) * 5  WHERE FA15PERCENT <> 0	
		UPDATE #tempAnusuchi1A SET FA25PERCENT = (FA2TOTAL/FA15PERCENT) * 5 WHERE FA25PERCENT <> 0	
		UPDATE #tempAnusuchi1A SET SA5PERCENT = (SATOTAL/FA15PERCENT) * 5  WHERE SA5PERCENT <> 0	
			
END			
			
--SELECT * FROM #tempAnusuchi1A			
			
	SELECT 	
		@rBuilder1,
		@rBuilder2,		
		BVC.ClassName,
		BVC.DivisionName,
		SF.RollNo,
		SF.Name,
		SF.Number,
		CS.SubjectName,			
		AIS.*		
	
	FROM #tempAnusuchi1A AIS			
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = @rClassSubjectId			
		INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId=AIS.AcademicId	 AND SF.StatusId = 1		
		INNER JOIN sSetup.vBatchClassDivision BVC ON BVC.DivisionId = SF.DivisionId AND CS.ClassId=BVC.ClassId			
	WHERE (SF.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
		   AND (SF.RollNo <= @rToRollNo OR @rToRollNo = 0)
	ORDER BY SF.RollNo			
			
			
DROP TABLE #tempAnusuchi1A			
DROP TABLE #tempMainExamCombine			
DROP TABLE #tempSubExamCombine			

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptAnusuchi5Get]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,	
	 @rClassId INT,
	 @rDivisionId int,
	 @rFromRollNo int,
	 @rToRollNo int	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

--SELECT	'' AS ClassName,
--		'' AS DivisionName,
--		'' AS Name,
--		'' AS Number,
--		'' AS Activity1,
--		'' AS Activity2,
--		'' AS Activity3,
--		'' AS Activity4,
--		'' AS Activity5,
--		'' AS Activity6,
--		'' AS Activity7,
--		'' AS Activity8

	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)					
						
	select @cols = STUFF((SELECT  ',' + QUOTENAME(Ed.Title) 					
						  From sGSEB.tActivityMaster Ed 
						  INNER JOIN sGSEB.tClassActivity CA ON CA.ActivityId = Ed.Id 
						  AND ClassId = @rClassId
	            FOR XML PATH(''), TYPE					
	            ).value('.', 'NVARCHAR(MAX)') 					
	        ,1,1,'')					
	       					
						
	set @query = ' SELECT ClassName,DivisionName,Name,Number, ' + @cols + ' FROM					
	( SELECT AM.Title AS Title, 					
			BVC.ClassName AS ClassName,			
			ISNULL( Term1IndicatorText,'''') AS Term1IndicatorText,			
			BVC.DivisionName AS DivisionName,			
			SF.Name AS Name,			
			SF.Number,			
			ISNULL(Term2IndicatorText,'''') AS Term2IndicatorText  			
		FROM sGSEB.tActivityIndicatorScore AIS				
		INNER JOIN sGSEB.tActivityMaster AM ON AIS.ActivityId = AM.Id				
		INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId=AIS.AcademicId AND SF.StatusId = 1				
		INNER JOIN sSetup.vBatchClassDivision BVC ON BVC.DivisionId = SF.DivisionId
		AND (SF.RollNo >= ' + @rFromRollNo + ' OR ' + @rFromRollNo + ' = 0)
		AND (SF.RollNo <= ' + @rToRollNo + ' OR ' + @rToRollNo + ' = 0) 
		AND SF.DivisionId = ' + @rDivisionId + ') MAIN				
	PIVOT					
	(					
		MAX(Term1IndicatorText)				
	FOR Title IN (' + @cols + ')					
	)pvt'					
	EXEC(@query)							
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptAnusuchi7Get]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,	
	 @rEXAMID INT,			
	 @rClassSubjectId INT,			
	 @rDivisionId int,
	 @rFromRollNo int,
	 @rToRollNo int	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
		--SELECT	'' AS AcademicId,
		--		'' AS Practical,		
		--		'' AS Theory,		
		--		'' AS Total,		
		--		'' AS Total70Percent,		
		--		'' AS Internal30Percent,		
		--		'' AS GrandTotal,		
		--		'' AS Grade,
		--		@rBuilder1,
		--		@rBuilder2,		
		--		'' AS ClassName,
		--		'' AS DivisionName,
		--		'' AS RollNo,
		--		'' AS Name,
		--		'' AS Number,
		--		'' AS SubjectName
		
		
		
			
CREATE TABLE #tempAnusuchi7			
(			
	AcademicId bigint,		
	Practical DECIMAL(5,2),		
	Theory DECIMAL(5,2),		
	Total DECIMAL(5,2),		
	Total70Percent DECIMAL(5,2),		
	Internal30Percent DECIMAL(5,2),		
	GrandTotal DECIMAL(5,2),		
	Grade Nvarchar(10)		
)			
INSERT INTO #tempAnusuchi7 (AcademicId) SELECT AcademicId FROM sStudent.vStudentAcademic WHERE DivisionId = @rDivisionId AND StatusId = 1			
			
CREATE TABLE #tempMainExamCombine			
(			
	ID INT IDENTITY,		
	SubExamId int,		
	ExamOrder Smallint		
)			
INSERT INTO #tempMainExamCombine			
SELECT SubExamId,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId = @rExamId			
DECLARE @lCount int			
DECLARE @lMainExamId int			
Declare @lMainExamOrder smallint			
			
			
Select @lCount = MAX(Id) FROM #tempMainExamCombine			
WHILE @lCount > 0			
BEGIN			
	SELECT @lMainExamId= SUBEXAMID,@lMainExamOrder=ExamOrder FROM #tempMainExamCombine WHERE ID=@lCount		
		IF @lMainExamOrder = 1 	
		BEGIN	
			UPDATE TA SET Practical = ISNULL(OBTAIN,0),Total70Percent = ISNULL(Total70Percent,0) + ISNULL(Maximum,0) FROM   #tempAnusuchi7 TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lMainExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 2	
		BEGIN	
			UPDATE TA SET Theory = ISNULL(OBTAIN,0),Total70Percent = ISNULL(Total70Percent,0) + ISNULL(Maximum,0) FROM   #tempAnusuchi7 TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lMainExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		IF @lMainExamOrder = 3	
		BEGIN	
			UPDATE TA SET Internal30Percent = ISNULL((OBTAIN/Maximum) * 30,0)  FROM   #tempAnusuchi7 TA 
			INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId
			INNER JOIN sAssessment.tResultDetail RD ON R.Id =RD.ResultId AND R.ExamId = @lMainExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND ED.ClassSubjectId = @rClassSubjectId
		END	
		SET @lCount = @lCount - 1	
END			
		UPDATE #tempAnusuchi7 SET Total = ISNULL(Theory,0) + ISNULL(Practical ,0)	
		UPDATE #tempAnusuchi7 SET Total70Percent = ISNULL(( Total / Total70Percent ) * 70,0) WHERE Total70Percent <> 0	
		UPDATE #tempAnusuchi7 SET GrandTotal = ISNULL(Total + Total70Percent ,0)	
		UPDATE #tempAnusuchi7 SET Practical=ISNULL(Practical,0),Theory=ISNULL(Theory,0),Total70Percent=ISNULL(Total70Percent,0),Internal30Percent=ISNULL(Internal30Percent,0)	
		UPDATE TA SET Grade= ResultGrade FROM #tempAnusuchi7 TA INNER JOIN sAssessment.tResult R ON R.AcademicId = TA.AcademicId AND R.ExamId =@rEXAMID	
			
			
--SELECT * FROM #tempAnusuchi7

SELECT 	
		@rBuilder1,
		@rBuilder2,		
		BVC.ClassName,
		BVC.DivisionName,
		SF.RollNo,
		SF.Name,
		SF.Number,
		CS.SubjectName,			
		AIS.*		
	
	FROM #tempAnusuchi7 AIS			
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = @rClassSubjectId			
		INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId=AIS.AcademicId	 AND SF.StatusId = 1		
		INNER JOIN sSetup.vBatchClassDivision BVC ON BVC.DivisionId = SF.DivisionId AND CS.ClassId=BVC.ClassId	
	WHERE (SF.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
		   AND (SF.RollNo <= @rToRollNo OR @rToRollNo = 0)				
	ORDER BY SF.RollNo		
			
DROP TABLE #tempAnusuchi7			
DROP TABLE #tempMainExamCombine			
		

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptAnusuchiAPrimaryGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,	
	 @rDivisionId int,
	 @rClassSubjectId int,
	 @rGSEBExamId smallint,
	 @rFromRollNo int,
	 @rToRollNo int	 	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BVC.ClassName,
		BVC.DivisionName,
		SF.AcademicId,
		SF.Name,SF.Number, 
		SM.Title AS SubjectName,
		GSEBExamId,
		Hetu1,
		Hetu2,
		Hetu3,
		Hetu4,
		Hetu5,
		Hetu6,
		Hetu7,
		Hetu8,
		Hetu9,
		Hetu10,
		Hetu11,
		Hetu12,
		Hetu13,
		Hetu14,
		Hetu15,
		Hetu16,
		Hetu17,
		Hetu18,
		Hetu19,
		Hetu20
	FROM sGSEB.tHetuScore HS
		INNER JOIN sSetup.tClassSubject CS ON CS.Id = HS.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id= CS.SubjectId
		INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId=HS.AcademicId AND SF.StatusId = 1							
		INNER JOIN sSetup.vBatchClassDivision BVC ON BVC.DivisionId = SF.DivisionId							
	
	WHERE (SF.DivisionId = @rDivisionId)
		AND HS.ClassSubjectId = @rClassSubjectId
		AND SF.BatchId=@rBatchId 	
		AND HS.GSEBExamId = @rGSEBExamId
		AND (SF.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
		AND (SF.RollNo <= @rToRollNo OR @rToRollNo = 0)		
	ORDER BY SF.AcademicId		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptAnusuchiBPrimaryGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,	
	 @rDivisionId int,
	 @rClassSubjectId int,
	 @rGSEBExamId smallint,
	 @rFromRollNo int,
	 @rToRollNo int	 	 

	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BVC.ClassName,
		BVC.DivisionName,
		SF.AcademicId,
		SF.Name,SF.Number, 
		SM.Title AS SubjectName,
		GSEBExamId,
		Pd1,
		Pd2,
		Pd3,
		Pd4,
		Pd5,
		Pd6,
		Pd7,
		Pd8,
		Pd9,
		Pd10,
		Pd11,
		Pd12,
		Pd13,
		Pd14,
		Pd15,
		Pd16,
		Pd17,
		Pd18,
		Pd19,
		Pd20,
		Pd21,
		Pd22,
		Pd23,
		Pd24,
		Pd25,
		Pd26,
		Pd27,
		Pd28,
		Pd29,
		Pd30,
		Pd31,
		Pd32,
		Pd33,
		Pd34,
		Pd35,
		Pd36,
		Pd37,
		Pd38,
		Pd39,
		Pd40

	FROM sGSEB.tAnusuchiB HS
		INNER JOIN sSetup.tClassSubject CS ON CS.Id = HS.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id= CS.SubjectId
		INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId=HS.AcademicId AND SF.StatusId = 1							
		INNER JOIN sSetup.vBatchClassDivision BVC ON BVC.DivisionId = SF.DivisionId							
	
	WHERE (SF.DivisionId = @rDivisionId)
		AND HS.ClassSubjectId = @rClassSubjectId
		AND SF.BatchId=@rBatchId 	
		AND HS.GSEBExamId = @rGSEBExamId
		AND (SF.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
		AND (SF.RollNo <= @rToRollNo OR @rToRollNo = 0)	
	ORDER BY SF.AcademicId		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptAnusuchiCPrimaryGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,	
	 @rClassId INT,
	 @rDivisionId int,
     @rFromRollNo int,
	 @rToRollNo int	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION			 	
	
		--SELECT	@rBuilder1,
		--		@rBuilder2,		
		--		'' AS ClassName,
		--		'' AS DivisionName,
		--		'' AS RollNo,
		--		'' AS Name,
		--		'' AS Number,
		--		'' AS SubjectName,			
		--		'' AS SUB1,
		--		'' AS SUB2,
		--		'' AS SUB3,
		--		'' AS SUB4,
		--		'' AS SUB5,
		--		'' AS SUB6,
		--		'' AS SUB7,			
		--		'' AS SUB8,
		--		'' AS SUB9,
		--		'' AS SUB10,
		--		'' AS SUB11,
		--		'' AS SUB12,
		--		'' AS Id,
		--		'' AS AcademicId,
		--		'' AS PD,
		--		'' AS PDGrade,
		--		'' AS Total,
		--		'' AS Percentage,
		--		'' AS Grade,
		--		'' AS FA11, '' AS  FA21 , '' AS SA11 , '' AS  FA31, '' AS FA41, '' AS SA21,'' AS GRADE1,
		--		'' AS FA12, '' AS  FA22 , '' AS SA12 , '' AS  FA32, '' AS FA42, '' AS SA22,'' AS GRADE2,
		--		'' AS FA13, '' AS  FA23 , '' AS SA13 , '' AS  FA33, '' AS FA43, '' AS SA23,'' AS GRADE3,
		--		'' AS FA14, '' AS  FA24 , '' AS SA14 , '' AS  FA34, '' AS FA44, '' AS SA24,'' AS GRADE4,
		--		'' AS FA15, '' AS  FA25 , '' AS SA15 , '' AS  FA35, '' AS FA45, '' AS SA25,'' AS GRADE5,
		--		'' AS FA16, '' AS  FA26 , '' AS SA16 , '' AS  FA36, '' AS FA46, '' AS SA26,'' AS GRADE6,
		--		'' AS FA17, '' AS  FA27 , '' AS SA17 , '' AS  FA37, '' AS FA47, '' AS SA27,'' AS GRADE7,
		--		'' AS FA18, '' AS  FA28 , '' AS SA18 , '' AS  FA38, '' AS FA48, '' AS SA28,'' AS GRADE8,
		--		'' AS FA19, '' AS  FA29 , '' AS SA19 , '' AS  FA39, '' AS FA49, '' AS SA29,'' AS GRADE9,
		--		'' AS FA110, '' AS  FA210 , '' AS SA110 , '' AS  FA310, '' AS FA410, '' AS SA210,'' AS GRADE10,
		--		'' AS FA111, '' AS  FA211 , '' AS SA111 , '' AS  FA311, '' AS FA411, '' AS SA211,'' AS GRADE11,
		--		'' AS FA112, '' AS  FA212 , '' AS SA112 , '' AS  FA312, '' AS FA412, '' AS SA212,'' AS GRADE12

		
		
DECLARE @query  AS NVARCHAR(MAX)		
BEGIN
			
CREATE TABLE #tempAnusuchiCMaster
(	ID INT IDENTITY,
	ACADEMICID BIGINT,	
	ClassSubjectId1 INT,
	ClassSubjectId2 INT,
	ClassSubjectId3 INT,
	ClassSubjectId4 INT,
	ClassSubjectId5 INT,
	ClassSubjectId6 INT,
	ClassSubjectId7 INT,	
	ClassSubjectId8 INT,	
	ClassSubjectId9 INT,	
	ClassSubjectId10 INT,	
	ClassSubjectId11 INT,	
	ClassSubjectId12 INT,
	PD DECIMAL(5,2),
	PDGrade nvarchar(5),	
	Total DECIMAL(6,2),
	Percentage DECIMAL(6,2),
	Grade	NVARCHAR(5),
	FA11 DECIMAL(5,2),FA21 DECIMAL(5,2),SA11 DECIMAL(5,2),FA31 DECIMAL(5,2),FA41 DECIMAL(5,2),SA21 DECIMAL(5,2),Grade1 Nvarchar(10),
	FA12 DECIMAL(5,2),FA22 DECIMAL(5,2),SA12 DECIMAL(5,2),FA32 DECIMAL(5,2),FA42 DECIMAL(5,2),SA22 DECIMAL(5,2),Grade2 Nvarchar(10),
	FA13 DECIMAL(5,2),FA23 DECIMAL(5,2),SA13 DECIMAL(5,2),FA33 DECIMAL(5,2),FA43 DECIMAL(5,2),SA23 DECIMAL(5,2),Grade3 Nvarchar(10),
	FA14 DECIMAL(5,2),FA24 DECIMAL(5,2),SA14 DECIMAL(5,2),FA34 DECIMAL(5,2),FA44 DECIMAL(5,2),SA24 DECIMAL(5,2),Grade4 Nvarchar(10),
	FA15 DECIMAL(5,2),FA25 DECIMAL(5,2),SA15 DECIMAL(5,2),FA35 DECIMAL(5,2),FA45 DECIMAL(5,2),SA25 DECIMAL(5,2),Grade5 Nvarchar(10),
	FA16 DECIMAL(5,2),FA26 DECIMAL(5,2),SA16 DECIMAL(5,2),FA36 DECIMAL(5,2),FA46 DECIMAL(5,2),SA26 DECIMAL(5,2),Grade6 Nvarchar(10),
	FA17 DECIMAL(5,2),FA27 DECIMAL(5,2),SA17 DECIMAL(5,2),FA37 DECIMAL(5,2),FA47 DECIMAL(5,2),SA27 DECIMAL(5,2),Grade7 Nvarchar(10),
	FA18 DECIMAL(5,2),FA28 DECIMAL(5,2),SA18 DECIMAL(5,2),FA38 DECIMAL(5,2),FA48 DECIMAL(5,2),SA28 DECIMAL(5,2),Grade8 Nvarchar(10),
	FA19 DECIMAL(5,2),FA29 DECIMAL(5,2),SA19 DECIMAL(5,2),FA39 DECIMAL(5,2),FA49 DECIMAL(5,2),SA29 DECIMAL(5,2),Grade9 Nvarchar(10),
	FA110 DECIMAL(5,2),FA210 DECIMAL(5,2),SA110 DECIMAL(5,2),FA310 DECIMAL(5,2),FA410 DECIMAL(5,2),SA210 DECIMAL(5,2),Grade10 Nvarchar(10),
	FA111 DECIMAL(5,2),FA211 DECIMAL(5,2),SA111 DECIMAL(5,2),FA311 DECIMAL(5,2),FA411 DECIMAL(5,2),SA211 DECIMAL(5,2),Grade11 Nvarchar(10),
	FA112 DECIMAL(5,2),FA212 DECIMAL(5,2),SA112 DECIMAL(5,2),FA312 DECIMAL(5,2),FA412 DECIMAL(5,2),SA212 DECIMAL(5,2),Grade12 Nvarchar(10)
)
CREATE TABLE #tempSubject
(Id int Identity,
 ClassSubjectId int)
 INSERT INTO #tempSubject SELECT distinct Id FROM sSetup.tClassSubject CS
 INNER JOIN sGSEB.tAnusuchiB AB ON AB.ClassSubjectId <> CS.Id
 AND CS.ClassId = @rClassId 
 
 INSERT INTO #tempAnusuchiCMaster (ACADEMICID)
 SELECT A.Id FROM sStudent.tAcademic A WHERE A.DivisionId = @rDivisionId 
 AND BatchId =@rBatchId  ORDER BY A.Id

DECLARE @lCount int
DECLARE @lSubCount int
DECLARE @lAcademicId BIGINT
DECLARE @lClassSubjectId INT
DECLARE @lColName NVARCHAR(20)
SELECT @lCount = MAX(Id) FROM #tempAnusuchiCMaster

WHILE @lCount > 0
BEGIN
	SELECT @lAcademicId=AcademicId FROM #tempAnusuchiCMaster WHERE ID = @lCount
	SELECT @lSubCount = MAX(Id) FROM #tempSubject
	WHILE @lSubCount > 0
	BEGIN
		SELECT @lClassSubjectId = ClassSubjectId FROM #tempSubject WHERE Id = @lSubCount
		SET @lColName = 'ClassSubjectId' + CONVERT(NVARCHAR,@lSubCount)
		SET @query =N'UPDATE  #tempAnusuchiCMaster  SET  ' + convert(varchar, @lColName) + ' = ' + 
					 CONVERT(NVARCHAR,@lClassSubjectId) + ' WHERE ACADEMICID = ' + CONVERT(NVARCHAR,@lAcademicId)
		EXEC sp_executesql  @query	
		
		SET @query =N'UPDATE  T  SET T.FA1' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.FA1,
					 T.FA2' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.FA2,
					 T.SA1' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.SA1,
					 T.FA3' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.FA3,
					 T.FA4' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.FA4,
					 T.SA2' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.SA2,
					 T.Grade' + CONVERT(NVARCHAR,@lSubCount) + ' = RD.Grade
					 FROM #tempAnusuchiCMaster T 	
					 INNER JOIN SGSEB.TRESULTDETAIL RD ON T.ACADEMICID = ' + CONVERT(NVARCHAR,@lAcademicId)  + ' AND ' +
					 convert(varchar, @lColName) + ' = ' + CONVERT(NVARCHAR,@lClassSubjectId)  + ' AND RD.ClassSubjectId= '+ convert(varchar, @lColName) +''
		execute (@query)	
		SET @lSubCount = @lSubCount - 1

	END
		-- Personality Development
		SET @query =N'UPDATE  T  SET PD = (RD.FA2 + RD.FA4)/2
					 FROM #tempAnusuchiCMaster T 
					 INNER JOIN SGSEB.TRESULTDETAIL RD ON T.ACADEMICID = ' + CONVERT(NVARCHAR,@lAcademicId) + '
					 INNER JOIN sGSEB.tAnusuchiB AB ON AB.ACADEMICID = T.ACADEMICID AND AB.CLASSSUBJECTID = RD.CLASSSUBJECTID'
		EXEC sp_executesql  @query			 

	SET @lCount = @lCount - 1 
END
------ Personality Development Grade Evaluation
DECLARE @MinimumScore decimal(5,2)
DECLARE @Grade nvarchar(10)
DECLARE @GradePoint Decimal(6,2)

	CREATE TABLE #tempGradeSetDetail
 		(
 			Id INT IDENTITY (1, 1),
 			MinimumScore decimal(5,2),
 			Grade nvarchar(10),
 			GradePoint Decimal(6,2)					 
 		) 
 		INSERT INTO #tempGradeSetDetail
 		SELECT MinimumScore,GradeTitle,GradePoint		
		FROM sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sGSEB.tGSEBExamMapping GEM ON EM.Id = GEM.ExamId AND  GSEBExamId = 1 and GEM.ClassId = @rClassId
		INNER JOIN sAssessment.tGradeSetMaster GM ON GM.ID = EM.GradeSetId
		INNER JOIN sAssessment.tGradeSetDetail GD ON GD.GradeSetId=GM.Id
		INNER JOIN sGSEB.tAnusuchiB AB ON AB.ClassSubjectId = ED.ClassSubjectId
		WHERE EM.BatchId = @rBatchId
		 ORDER BY GD.MinimumScore DESC
		

SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
while (@lCount > 0)
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@Grade= Grade,
		@GradePoint = GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		
	Update #tempAnusuchiCMaster  Set PDGrade = @Grade WHERE PD >= @MinimumScore 
		AND AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND BatchId = @rBatchId AND StatusId=1)

	SET @lCount = @lCount - 1
 END	
---------- Total And Grade
	UPDATE T SET T.TOTAL=R.Obtain,T.Percentage=R.Percentage,T.Grade=R.Grade  FROM #tempAnusuchiCMaster T
	INNER JOIN sGSEB.tResult R ON R.AcademicId = T.ACADEMICID
 --------------------------------
 

SELECT 	@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 			
			BVC.ClassName,
			BVC.DivisionName,		
			SF.Name,
			SF.Number,
			SF.RollNo, 		
			CS1.SubjectName AS SUB1,
			CS2.SubjectName AS SUB2,
			CS3.SubjectName AS SUB3,
			CS4.SubjectName AS SUB4,
			CS5.SubjectName AS SUB5,
			CS6.SubjectName AS SUB6,
			CS7.SubjectName AS SUB7,			
			CS8.SubjectName AS SUB8,
			CS9.SubjectName AS SUB9,
			CS10.SubjectName AS SUB10,
			CS11.SubjectName AS SUB11,
			CS12.SubjectName AS SUB12,
			AIS.*		 
FROM #tempAnusuchiCMaster AIS		
		LEFT JOIN sGSEB.tResultDetail RD ON RD.AcademicId=AIS.AcademicId AND RD.ClassSubjectId = AIS.ClassSubjectId1		
		LEFT JOIN sSetup.vClassSubject CS1 ON CS1.ClassSubjectId = AIS.ClassSubjectId1		
		LEFT JOIN sSetup.vClassSubject CS2 ON CS2.ClassSubjectId = AIS.ClassSubjectId2		
		LEFT JOIN sSetup.vClassSubject CS3 ON CS3.ClassSubjectId = AIS.ClassSubjectId3		
		LEFT JOIN sSetup.vClassSubject CS4 ON CS4.ClassSubjectId = AIS.ClassSubjectId4		
		LEFT JOIN sSetup.vClassSubject CS5 ON CS5.ClassSubjectId = AIS.ClassSubjectId5		
		LEFT JOIN sSetup.vClassSubject CS6 ON CS6.ClassSubjectId = AIS.ClassSubjectId6		
		LEFT JOIN sSetup.vClassSubject CS7 ON CS7.ClassSubjectId = AIS.ClassSubjectId7		
		LEFT JOIN sSetup.vClassSubject CS8 ON CS8.ClassSubjectId = AIS.ClassSubjectId8		
		LEFT JOIN sSetup.vClassSubject CS9 ON CS9.ClassSubjectId = AIS.ClassSubjectId9		
		LEFT JOIN sSetup.vClassSubject CS10 ON CS10.ClassSubjectId = AIS.ClassSubjectId10		
		LEFT JOIN sSetup.vClassSubject CS11 ON CS11.ClassSubjectId = AIS.ClassSubjectId11		
		LEFT JOIN sSetup.vClassSubject CS12 ON CS12.ClassSubjectId = AIS.ClassSubjectId12		
		INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId=AIS.AcademicId AND SF.StatusId = 1		
		INNER JOIN sSetup.vBatchClassDivision BVC ON BVC.DivisionId = SF.DivisionId
		AND (SF.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
		AND (SF.RollNo <= @rToRollNo OR @rToRollNo = 0)	
		AND SF.BatchId = @rBatchId
		ORDER BY SF.RollNo


DROP TABLE #tempAnusuchiCMaster
DROP TABLE #tempSubject


END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sGSEB].[pRptCoScholasticEvaluationGet]	 	 
	 --@rClassId int,
	 --@rBatchId int,
	 --@rOrgId int,
	 --@rDivisionId int
		@rAcademicId bigint 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 			
			AIS.AcademicId,
			convert(nvarchar,AIS.AcademicId) AS AcademicIdText,
			ISNULL(AIS.Term1IndicatorText,'') AS Term1IndicatorText,
			ISNULL(AIS.Term2IndicatorText,'') AS Term2IndicatorText,			
			AM.Title AS LifeSkills,
			AGM.Code AS GrpLifeSkillsCode,
			AGM.Title AS GrpLifeSkills,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division
	FROM 
			sGSEB.tActivityIndicatorScore AIS
			LEFT JOIN sGSEB.tActivityMaster AM ON AM.Id=AIS.ActivityId
			INNER JOIN sGSEB.tActivityGroupMaster AGM ON AGM.Id=AM.ActivityGroupId
			INNER JOIN sStudent.tAcademic A ON AIS.AcademicId=A.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	WHERE 
	(A.Id = @rAcademicId or @rAcademicId =0 )
	--		(A.BatchId=@rBatchId)
	--		AND (A.OrgId=@rOrgId)
	--	    AND (A.ClassId=@rClassId)
	---	    AND (A.DivisionId=@rDivisionId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptFirstTermResultGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rClassSubjectId int,
	 @rFromRollNo int,
	 @rToRollNo int	 
	 
	 
	 
	 
	 
	 --@rBuilder1 nvarchar(max)='',
	 --@rBuilder2 nvarchar(max)='', 
	 --@rSubjectId int,
	 --@rBatchId int,
	 --@rClassId int,
	 --@rDivisionId int,
	 --@rExamId int,
	 --@rCode nvarchar(20),
	 --@rFromRollNo int,
	 --@rToRollNo int,
	 --@rFromRank int,
	 --@rToRank int,
	 --@rGrade nvarchar(20)
	 
	 
	 
	 
	 
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 



	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SM.Code,
			ISNULL(SM.FirstName,'')+' '+ISNULL(SM.LastName,'') AS Name,
			A.RollNo,
			R.AcademicId,
			Convert(Nvarchar,R.AcademicId) AS AcademicIdText,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			SO.DateOfBirth,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(HM.Title,'') AS House,
			
			ISNULL(RD.FA1Grade,'') AS FA1Grade,
			ISNULL(RD.FA2Grade,'') AS FA2Grade,
			ISNULL(RD.FA3Grade,'')AS FA3Grade,
			ISNULL(RD.FA4Grade,'') AS FA4Grade,
			ISNULL(RD.SA1Grade,'') AS SA1Grade,
			ISNULL(RD.SA2Grade,'') AS SA2Grade,
			ISNULL(RD.FA1,0) AS FA1,
			ISNULL(RD.FA2,0) AS FA2,
			ISNULL(RD.FA3,0) AS FA3,
			ISNULL(RD.FA4,0) AS FA4,
			ISNULL(RD.SA1,0) AS SA1,
			ISNULL(RD.SA2,0) AS SA2,			
			ISNULL(RD.Grade,'') AS Grade,
			
			ISNULL(R.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(R.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(R.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			ISNULL(R.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
	
			SubM.Title As ClassSubject,
			ISNULL(BGM.Title,'') AS BloodGroup,
	
			ISNULL(R.TOTAL1,0) AS TOTAL1,
			ISNULL(R.Obtain1,0) AS Obtain1,
			ISNULL(R.Result1,0) AS Result1,
			ISNULL(R.Percentage1,0) AS Percentage1,
			ISNULL(R.Percentile1,0) AS Percentile1,
			ISNULL(R.Remark1,0) AS Remark1,
			ISNULL(R.AttendanceTerm1,0) AS AttendanceTerm1,
			ISNULL(R.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
			
			ISNULL(R.TOTAL2,0) AS TOTAL2,
			ISNULL(R.Obtain2,0) AS Obtain2,
			ISNULL(R.Result2,0) AS Result2,
			ISNULL(R.Percentage2,0) AS Percentage2,
			ISNULL(R.Percentile2,0) AS Percentile2,
			ISNULL(R.Remark2,0) AS Remark2,
			ISNULL(R.AttendanceTerm2,0) AS AttendanceTerm2,
			ISNULL(R.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
			
			ISNULL(R.TOTAL,0) AS TOTAL,
			ISNULL(R.Obtain,0) AS Obtain,
			ISNULL(R.Result,0) AS Result,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.Percentile,0) AS Percentile,
			ISNULL(R.Remark,0) AS Remark,
			ISNULL(R.Grade,'') AS ResultGrade
      
	FROM 
	
			sGSEB.tResultDetail RD			
			INNER JOIN sGSEB.tResult R  ON RD.AcademicId=R.AcademicId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId And SM.StatusId = 1
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId AND DM.ClassId=CM.Id
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sSetup.tClassSubject CS ON CS.Id=RD.ClassSubjectId AND CS.IsOptional=0
			INNER JOIN sSetup.tSubjectMaster SubM ON SubM.Id=CS.SubjectId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
	WHERE 
			
    A.BatchId = @rBatchId 
		
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND (A.ClassId=@rClassId OR @rClassId=0) 
	AND (RD.ClassSubjectId=@rClassSubjectId OR @rClassSubjectId=0)
	AND (A.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
	AND (A.RollNo <= @rToRollNo OR @rToRollNo = 0)	
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptOptionalSubjectIndicatorListGet]
	 
	 
	 @rBatchId int,	
	 @rDivisionId int,
	 @rClassSubjectId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromRollNo int,
	 @rToRollNo int	  
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 			
			BVC.ClassName,
			BVC.DivisionName,
			SF.AcademicId,
			SF.Name,
			SF.Number, 
			CS.ClassSubjectId,
			CS.SubjectName,			
			ISNULL(Indicator1Text,'') AS Indicator1Text,		
			ISNULL(Indicator2Text,'') AS Indicator2Text  		

	FROM sGSEB.tResultDetailOptional AIS			
			INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = AIS.ClassSubjectId			
			INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId=AIS.AcademicId AND SF.StatusId = 1			
			INNER JOIN sSetup.vBatchClassDivision BVC ON BVC.DivisionId = SF.DivisionId AND CS.ClassId=BVC.ClassId			
					
	
	WHERE 
	(SF.DivisionId = @rDivisionId) AND
		AIS.ClassSubjectId = @rClassSubjectId
		AND SF.BatchId=@rBatchId 	
		AND (SF.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
		AND (SF.RollNo <= @rToRollNo OR @rToRollNo = 0)	
	ORDER BY SF.AcademicId					
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pRptSubjectWiseResultGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,	
	 @rDivisionId int,
	 @rClassSubjectId int,
	 @rFromRollNo int,
	 @rToRollNo int	  
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 			
			BVC.ClassName,
			BVC.DivisionName,
			SF.AcademicId,
			SF.Name,
			SF.Number, 
			CS.ClassSubjectId,
			CS.SubjectName,		
			ISNULL(FA1,0) AS FA1,
			ISNULL(FA2,0) AS FA2,
			ISNULL(FA3,0) AS FA3,
			ISNULL(FA4,0) AS FA4,	
			ISNULL(SA1,0) AS SA1,
			ISNULL(SA2,0) AS SA2,
			ISNULL(GradeTerm1,'') AS GradeTerm1,
			ISNULL(GradeTerm2,'') AS GradeTerm2	

	FROM sGSEB.tResultDetailOptional AIS		
		INNER JOIN sGSEB.tResultDetail RD ON RD.AcademicId=AIS.AcademicId AND RD.ClassSubjectId = AIS.ClassSubjectId		
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = AIS.ClassSubjectId		
		INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId=AIS.AcademicId AND SF.StatusId = 1		
		INNER JOIN sSetup.vBatchClassDivision BVC ON BVC.DivisionId = SF.DivisionId AND CS.ClassId=BVC.ClassId		
	
	WHERE (SF.DivisionId = @rDivisionId)
		AND CS.ClassSubjectId = @rClassSubjectId
		AND SF.BatchId=@rBatchId 	
		AND (SF.RollNo >= @rFromRollNo OR @rFromRollNo = 0)
	AND (SF.RollNo <= @rToRollNo OR @rToRollNo = 0)	
	ORDER BY SF.AcademicId					
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sGSEB].[pSubjectIndicatorDetailAdd]
	 
	        @rId int
           ,@rSubjectId int
           ,@rTitle nvarchar(100)
           ,@rNumber smallint
		   ,@rOrderIndex int	
		   ,@rUpdatedUserId bigint
		   ,@rIsObsolete bit
		   ,@rOrgId int	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sGSEB.tSubjectIndicatorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sGSEB].[tSubjectIndicatorMaster]
			   (
			    [Id]
			   ,[SubjectId]
			   ,[Title]
			   ,[Number] 
			   ,[OrgId]
			   ,[IsObsolete]
			   ,[OrderIndex]	
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rSubjectId
			   ,@rTitle
			   ,@rNumber
			   ,@rOrgId
			   ,@rIsObsolete
			   ,@rOrderIndex			   
			   ,@rUpdatedUserId			   
			   ,sCommon.fGetDate()
			   )
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sGSEB].[tSubjectIndicatorMaster]
	    SET
			 
	          SubjectId=@rSubjectId
	         ,Title=@rTitle
	         ,Number=@rNumber
	         ,OrgId=@rOrgId
	         ,IsObsolete=@rIsObsolete
			 ,OrderIndex=@rOrderIndex
			 ,UpdatedUserId =@rUpdatedUserId
			 ,UpdatedDateTime=sCommon.fGetDate()
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pSubjectIndicatorDetailGet]
	 @rSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT			
			SIM.Id,
			SIM.SubjectId,
			SIM.Number,
			SIM.TITLE,
			SIM.OrderIndex
  FROM 
			sGSEB.[tSubjectIndicatorMaster] SIM
WHERE 
			(SIM.SubjectId=@rSubjectId OR @rSubjectId=0)  order by SIM.OrderIndex ASC		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pSubjectIndicatorGroupDelete]
@rId bigint
AS
BEGIN
BEGIN TRY
 IF NOT EXISTS (SELECT RD.ClassSubjectId FROM sGSEB.tResultDetailOptional RD 
                INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=RD.ClassSubjectId AND CS.SubjectId = @rId)	
	  BEGIN
		DELETE	FROM sGSEB.tSubjectIndicatorMaster WHERE SubjectId=@rId		
		SELECT 1 AS RESULT
	   END
	ELSE
		BEGIN
			SELECT -101 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pSubjectIndicatorMasterDelete]
@rId	 bigint
AS
BEGIN
BEGIN TRY
	--IF NOT EXISTS (SELECT Id FROM sGSEB.tClassActivity WHERE ActivityId = @rActivityId)	
	  BEGIN
		DELETE	FROM sGSEB.tSubjectIndicatorMaster WHERE Id=@rId	
		SELECT 1 AS RESULT
	   END
	--ELSE
	--	BEGIN
	--		SELECT -101 AS RESULT
	--	END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sGSEB].[pSubjectIndicatorScoreAdd]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lCount INT
	 
		--DELETE RDO FROM sGSEB.tResultDetailOptional RDO
		--INNER JOIN OPENXML (@loDoc, '/Table/SubjectIndicatorScore', 1)
		--	WITH ( 				
		--			AcademicId Bigint,SubjectName NVARCHAR(100)			
		--		  ) A 	ON RDO.AcademicId = A.AcademicId
		--INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = RDO.ClassSubjectId
		--AND CS.ORGID = @rORGId	AND CS.SubjectName=A.SubjectName
	
	IF NOT EXISTS (SELECT RDO.AcademicId FROM sGSEB.tResultDetailOptional RDO
			   INNER JOIN OPENXML (@loDoc, '/Table/SubjectIndicatorScore', 1)
			   WITH (AcademicId Bigint,SubjectName NVARCHAR(100)) B 
			   ON RDO.AcademicId = B.AcademicId
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = RDO.ClassSubjectId
		AND CS.ORGID = @rORGId	AND CS.SubjectName=B.SubjectName)
	 BEGIN
		INSERT INTO sGSEB.tResultDetailOptional
			(AcademicId,ClassSubjectId,Indicator1,Indicator2)			
			SELECT AcademicId,CS.ClassSubjectId,Term1Indicator,Term2Indicator										
			FROM OPENXML (@loDoc, '/Table/SubjectIndicatorScore', 1)
			WITH ( 				
					AcademicId Bigint,
					SubjectTitle NVARCHAR(100),
					Term1Indicator nvarchar(20),
					Term2Indicator nvarchar(20)			
				  ) A 	
			INNER JOIN sSetup.vClassSubject CS ON CS.SubjectName = A.SubjectTitle AND CS.ORGID = @rORGId	
			INNER JOIN sStudent.tAcademic AC ON AC.Id = A.AcademicId AND AC.ClassId = CS.ClassId
	 END  
	
	 ELSE
	
	 BEGIN
	
	 	UPDATE RDO
	 	SET
			RDO.AcademicId=B.AcademicId,
			RDO.ClassSubjectId=B.ClassSubjectId,
			RDO.Indicator1=B.Term1Indicator,
			RDO.Indicator2=B.Term2Indicator
		FROM	
		sGSEB.tResultDetailOptional RDO 					
		INNER JOIN (
			SELECT AcademicId,CS.ClassSubjectId,Term1Indicator,Term2Indicator										
			FROM OPENXML (@loDoc, '/Table/SubjectIndicatorScore', 1)
			WITH ( 				
					AcademicId Bigint,
					SubjectTitle NVARCHAR(100),
					Term1Indicator nvarchar(20),
					Term2Indicator nvarchar(20)			
				  ) A 	
			INNER JOIN sSetup.vClassSubject CS ON CS.SubjectName = A.SubjectTitle AND CS.ORGID = @rORGId	
			INNER JOIN sStudent.tAcademic AC ON AC.Id = A.AcademicId AND AC.ClassId = CS.ClassId ) AS B
			ON RDO.ACADEMICID = B.ACADEMICID AND RDO.ClassSubjectId=B.ClassSubjectId
		 
	 END  
	     SELECT 1 AS Result
	END
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sGSEB].[pSubjectIndicatorScoreGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rGSEBExamId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
	DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(CS.SubjectName) 
					  From sSetup.vClassSubject CS 
					  WHERE CS.ClassId = @rClassId AND IsOptional=1 Order By OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

IF @rGSEBExamId =1         
	BEGIN
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Number,SA.Name,CS.SubjectName,	 ISNULL(RDO.Indicator1,'''') AS Term1Indicator		
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sSetup.vClassSubject CS ON CS.ClassId = SA.ClassId
	LEFT JOIN sGSEB.tResultDetailOptional RDO ON RDO.AcademicId =SA.AcademicId AND RDO.ClassSubjectId=CS.ClassSubjectId
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '
	) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR SubjectName IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	

	END
ELSE
	BEGIN
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Number,SA.Name,CS.SubjectName,	 ISNULL(RDO.Indicator2,'''') AS Term2Indicator		
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sSetup.vClassSubject CS ON CS.ClassId = SA.ClassId
	LEFT JOIN sGSEB.tResultDetailOptional RDO ON RDO.AcademicId =SA.AcademicId AND RDO.ClassSubjectId=CS.ClassSubjectId
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '
	) MAIN
	PIVOT
	(
		max(Term2Indicator)
	FOR SubjectName IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	END
--print (@query)

execute(@query)
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pAssetTypeMasterAdd]
	 
        @rHostelId int,
        @rId int,
        @rCode nvarchar(20),
        @rTitle nvarchar(100),
        @rIsObsolete bit,
        @rCreatedUserId bigint,
        @rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM sHostel.tAssetTypeMaster WHERE Code=@rCode AND HostelId=@rHostelId AND OrgGroupId=@rOrgGroupId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM sHostel.tAssetTypeMaster WHERE Title=@rTitle AND HostelId=@rHostelId AND OrgGroupId=@rOrgGroupId)
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM sHostel.tAssetTypeMaster WHERE Code=@rCode AND HostelId=@rHostelId AND OrgGroupId=@rOrgGroupId  AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM sHostel.tAssetTypeMaster WHERE Title=@rTitle AND HostelId=@rHostelId AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tAssetTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT
	
	INSERT INTO sHostel.tAssetTypeMaster
		(
			HostelId,
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@rHostelId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tAssetTypeMaster
	    SET
			
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      AND HostelId=@rHostelId
	      AND OrgGroupId=@rOrgGroupId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pAssetTypeMasterGet]
	 
	 @rHostelId int,
	 @rId int,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgGroupId int	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			
			AM.Id,
			AM.Code,
			AM.Title,
			AM.IsObsolete,
			AM.HostelId
	FROM 
			sHostel.tAssetTypeMaster AM
	WHERE 
	    AM.HostelId = @rHostelId
		AND	((AM.Id = @rId) OR (@rId = 0))
		AND ((AM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((AM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND AM.OrgGroupId=@rOrgGroupId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pAssignRoomAdd]
	 
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rRoomId int,
	--@rCreatedUserId bigint,
	@rIsDeleted bit,
	@rBedNumber nvarchar(20),
	@rOrgGroupBatchId int = 0
	--@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	 --DECLARE @lNextNumber BIGINT 
 If(@rIsDeleted=1)
BEGIN
	Delete from sHostel.tAssignRoom where SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND OrgGroupBatchId=@rOrgGroupBatchId
	Select @rSourceId as Result
END	
ELSE

	If Exists(select SourceId from sHostel.tAssignRoom AR
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = AR.SourceId
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND BM.IsInContext = 1
	where SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND AR.OrgGroupBatchId=@rOrgGroupBatchId)
		BEGIN
			select -103 as Result
			RETURN
		END 
	   
	--SET @lNextNumber = @rSourceId 
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTransport.tAssignRoute', 0, 1, 1,@outNextNumber = @lNextNumber output
BEGIN TRY
BEGIN TRANSACTION	
BEGIN
	INSERT INTO sHostel.tAssignRoom
		(
			SourceTypeId,
			SourceId,
			RoomId,
			BedNumber,
			OrgGroupBatchId
			--CreatedUserId,
			--CreatedDateTime,
			--IsObsolete,
			--OrgId 
		)
	VALUES
		(
			@rSourceTypeId,
			@rSourceId,
			@rRoomId,
			@rBedNumber,
			@rOrgGroupBatchId
			--@rCreatedUserId,
			--sCommon.fGetDate(), 
			--@rIsObsolete,
			--@rOrgId
		)
		             
END	 
	 --ELSE
	 --BEGIN
	 --SET @lNextNumber = @rSourceId
	 --   UPDATE  sHostel.tAssignRoom
	 --   SET
		--	--SourceTypeId=@rSourceTypeId,
		--	--SourceId=@rSourceId,
		--	RoomId=@rRoomId
		--	--UpdatedUserId=@rCreatedUserId,
		--	--UpdatedDateTime=sCommon.fGetDate(), 
		--	--IsObsolete=@rIsObsolete
	      
	      
	 --     WHERE SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId 	   
	 --END  
		SELECT @rSourceID AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pAssignRoomAssetAdd]
	 
        @rRoomAssetId int,
        @rSourceTypeId smallint,
        @rSourceId bigint,
        @rHostelId int,
        @rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
	BEGIN
	IF NOT EXISTS (SELECT * FROM sHostel.tAssignRoomAsset WHERE RoomAssetId = @rRoomAssetId and SourceTypeId =@rSourceTypeId and SourceId =@rSourceId and HostelId = @rHostelId AND OrgGroupBatchId=@rOrgGroupBatchId )
	BEGIN
	INSERT INTO sHostel.tAssignRoomAsset
		(
		   RoomAssetId,
		   SourceTypeId,
		   SourceId,
		   HostelId,
		   OrgGroupBatchId
		)
	VALUES
		(
			@rRoomAssetId,
		    @rSourceTypeId,
		    @rSourceId,
		    @rHostelId,
		    @rOrgGroupBatchId
		)
		    SELECT 1 AS Result
	END	 
	END
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pAssignRoomAssetBulkAdd]
	 
        @rRoomAssetId int,
        @rSourceId bigint,
        @rHostelId int,
        @rAssetTypeId int,
        @rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
  --BEGIN TRY
   IF EXISTS (SELECT 1 FROM sHostel.tAssignRoomAsset WHERE  SourceTypeId =2003 and SourceId !=@rSourceId AND HostelId = @rHostelId AND RoomAssetId=@rRoomAssetId )
   --AND OrgGroupBatchId=@rOrgGroupBatchId)
	BEGIN
	SELECT -102 AS  Result
	Return
	END
 --BEGIN TRANSACTION
 	IF NOT EXISTS (SELECT 1 FROM sHostel.tAssignRoomAsset AR INNER JOIN  sHostel.tRoomAssetMaster  RM ON RM.id=AR.RoomAssetId  WHERE  AR.SourceTypeId =2003 AND AR.SourceId =@rSourceId AND AR.HostelId = @rHostelId  AND RM.AssetTypeId=@rAssetTypeId AND AR.OrgGroupBatchId=@rOrgGroupBatchId)
	BEGIN
	INSERT INTO sHostel.tAssignRoomAsset
		(
		   RoomAssetId,
		   SourceTypeId,
		   SourceId,
		   HostelId,
		   OrgGroupBatchId
		)
	VALUES
		(
			@rRoomAssetId,
		    2003,
		    @rSourceId,
		    @rHostelId,
		    @rOrgGroupBatchId
		)
		SELECT 1 As Result
	END	
	ELSE
	BEGIN
	UPDATE AR SET AR.RoomAssetId=@rRoomAssetId from sHostel.tAssignRoomAsset AR  
	INNER JOIN  sHostel.tRoomAssetMaster  RM ON RM.id=AR.RoomAssetId  
	WHERE  AR.SourceTypeId =2003 AND AR.SourceId =@rSourceId AND AR.HostelId = @rHostelId  AND RM.AssetTypeId=@rAssetTypeId AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	SELECT 11 As Result
	END
--COMMIT TRANSACTION		
--	END TRY
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pAssignRoomAssetBulkGet]
    @rHostelId int=0,
    @rRoomCategoryId int=0,
    @rBuildingId int=0,
    @rRoomId int,
    @rAssetTypeId int,
    @rOrgGroupBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
    select @cols = STUFF((SELECT ',' + QUOTENAME(Id) 
                    from sHostel.tAssetTypeMaster WHERE  ((Id=@rAssetTypeId) OR (@rAssetTypeId=0)) AND HostelId=@rHostelId  
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        if(isnull(@cols,'')='')
 BEGIN
 SELECT  -102  AS Result
 RETURN
 ENd
set @query = 'SELECT SourceId,Roomid,Building,Room,RoomCategory,Code,Name,ClassDivisionName,SUID,BedNumber,' + @cols + ' from 
             (
               Select
                 ISnull(RM.Title,'''') AS Room ,ISNULL(RCM.Title,'''') AS RoomCategory,ISNULL(BM.Title,'''') AS Building  ,isnull(RM.Id,0) AS Roomid,ISNULL(SA.StudentId,0) AS SourceId,
		SA.Code,SA.Name ,SA.ClassName + '' - '' + Sa.DivisionName AS ClassDivisionName,SA.SUID,AT.Id As AssetTypeId,ARR.RoomAssetId AS RoomAssetId,AR.BedNumber
         from  sStudent.vStudentAcademic SA
        INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = SA.StudentId  AND AR.SourceTypeId=2003  
        INNER JOIN sHostel.tRoomMaster RM  ON RM.Id=AR.RoomId 
        INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
         LEFT JOIN  sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId   
          AND ((RCM.Id='+Convert(varchar,@rRoomCategoryId)+') OR ('+convert(varchar,(@rRoomCategoryId))+'=0)) 
         LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId 
         LEFT JOIN sHostel.tAssignRoomAsset ARR ON ARR.SourceId=AR.SourceId  AND  ARR.OrgGroupBatchId=' + Convert(varchar,@rOrgGroupBatchId )+' AND ARR.SourceTypeId=2003  
         LEFT JOIN  sHostel.tRoomAssetMaster RAM ON RAM.ID=ARR.RoomAssetId
         LEFT JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RAM.AssetTypeId  
		      WHERE 
	         RM.HostelId=' + Convert(varchar,@rHostelId )+'
	         AND  SA.OrgGroupBatchId=' + Convert(varchar,@rOrgGroupBatchId )+'
	         AND  AR.OrgGroupBatchId=' + Convert(varchar,@rOrgGroupBatchId )+'
	         AND   ((RM.ID=' + Convert(varchar,@rRoomId )+') OR ('+Convert(varchar,@rRoomId )+'=0))
	          AND ((RCM.Id='+Convert(varchar,@rRoomCategoryId)+') OR ('+convert(varchar,(@rRoomCategoryId))+'=0))
	          AND   ((BM.ID=' + Convert(varchar,@rBuildingId )+') OR ('+Convert(varchar,@rBuildingId )+'=0))
	         
              ) x
            pivot 
            (
               SUM(RoomAssetId)  
                for AssetTypeId in (' + @cols + ')
            ) p '
            
 EXEC( @query)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pAssignRoomAssetGET]
	 
        @rHostelId int,
        @rRoomId int
        
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT
	
    DISTINCT AT.Title ,
	 RM.HostelId,
	 RM.RoomId,
	 RM.AssetTypeId
	 
	From 
	sHostel.tRoomAssetMaster RM 
	INNER JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RM.AssetTypeId AND AT.IsObsolete=0
	--LEFT JOIN sHostel.tAssignRoomAsset AR ON RM.Id=AR.RoomAssetId AND AR.SourceTypeId=2003
	--LEFT JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=AR.SourceId
WHERE 
RM.RoomId=@rRoomId
AND RM.HostelId=@rHostelId
--AND ((AR.SourceTypeId=@rSourceTypeId)OR (@rSourceTypeId=0))
--AND ((AR.SourceId=@rSourceId)OR (@rSourceId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pAssignRoomGet]
          
           @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
           @rHostelId int,
           @rRoomCategoryId int=0,
           @rRoomId int=0,
           @rOrgGroupBatchId int
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END


BEGIN

SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Employee' AS SourceType,
		95 AS SourceTypeId,
		ISNULL(EM.Id,0) as SourceId,
		EM.Code as SourceCode,
		EM.FirstName+' '+EM.LastName as SourceName,
		ODM.Title as ClassDivisionName,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		OM.DisplayTitle AS OrgDisplayTitle,
		AR.BedNumber AS BedNumber,
		RM.RoomCategoryId,
	    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
	    OM.Id AS OrgId,
	    '' AS SUId,
	    ISNULL(EC.PresentCity,'') AS City, --Added '' AS City--> ISNULL(EC.PresentCity,'') for mantis - 0034976
	    [sHostel].[fAssignRoomEmployeeAssetGet](@rHostelId ,@rRoomId,AR.SourceId ) AS AssetNumber,
	    RM.Id AS RoomId
	   
		
  FROM sHostel.tRoomMaster RM 
	INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.Id=RM.RoomCategoryId AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
	LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=95 AND AR.OrgGroupBatchId=@rOrgGroupBatchId
    LEFT JOIN sHrm.tEmployeeMaster EM ON AR.SourceId=EM.Id
    LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
    LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
    LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
    LEFT JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
    LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgID
	LEFT JOIN sHrm.tEmployeeCommunications EC ON  EC.EmployeeId = EM.Id --Added by dhananjay for mantis - 0034976

  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
		(RM.HostelId=@rHostelId OR @rHostelId=0)
	AND (RM.Id=@rRoomId OR @rRoomId=0)
	AND ISNULL(EM.Id,0) > 0
	--AND  CCM.IsObsolete = 0
	AND ISNULL(EM.IsOtherUser,0) = 0 
	UNION ALL
	
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Student' AS SourceType,
		2003 AS SourceTypeId,
	    ISNULL(SA.StudentId,0) as SourceId,
		SA.Code as SourceCode,
		SA.Name AS SourceName,
		sStudent.fStudentCurrentDivisionGet( SA.StudentId) AS ClassDivisionName,
		--'' AS  ClassDivisionName,
		--SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		OM.DisplayTitle AS OrgDisplayTitle,
		AR.BedNumber AS BedNumber,
		RM.RoomCategoryId,
	    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
	    OM.Id AS OrgId,
	    ISNULL(SA.SUId,'') AS SUId,
	    ISNULL(SC.PresentCity,'') AS City,
	    [sHostel].[fAssignRoomAssetGet](@rHostelId ,@rRoomId,SA.StudentId ) AS AssetNumber,
	    RM.Id AS RoomId
	    
  FROM sHostel.tRoomMaster RM 
	INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.Id=RM.RoomCategoryId AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
	LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003 AND AR.OrgGroupBatchId=@rOrgGroupBatchId
    LEFT JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId AND SA.OrgGroupBatchId=@rOrgGroupBatchId 
    INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
    INNER JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
    LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgID
    LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=AR.SourceId
  WHERE 
	--	CCM.Id = @rId OR @rId = 0
	--	AND 
		(RM.HostelId=@rHostelId OR @rHostelId=0)
		AND (RM.Id=@rRoomId OR @rRoomId=0)
		AND ISNULL(SA.StudentId,0) > 0
	--  AND  CCM.IsObsolete = 0
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pAttendanceListGet]
	 	 
	 	@rRoomId int,
		@rHostelId int,
		@rStudentCode nvarchar(20),
		@rFromAttendanceDate date,
		@rToAttendanceDate date,
	 	@rSuid nvarchar(50),
	 	@rPresent int,
	 	@rHostelAttendanceTypeId int,
	 	@rOrgGroupBatchId int,
	 	@rBuildingId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			SA.StudentId,
			SA.Code AS StudentCode,
			SA.Name,
			SA.SUId,
			ATR.AttendanceDate,
			ISNULL(ATR.IsPresent,'true') as IsPresent,
			ISNULL(ATR.AbsentReasonId,0) as AbsentReasonId,
			ARM.Title AS AbsentReasonName,
			RM.Title As RoomName,
			ATM.Title As AttendanceType
	 FROM  
			sStudent.vStudentAcademic SA 
			INNER JOIN sHostel.tAssignRoom AR ON SA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
		    INNER JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId = AR.SourceId 
			LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id=ATR.AbsentReasonId
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId 
	        INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	        INNER JOIN sHostel.tHostelAttendanceTypeMaster ATM ON ATM.Id=ATR.HostelAttendanceTypeId
	        LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
	    
			
  WHERE 
	 ((AR.RoomId=@rRoomId) OR (@rRoomId=0))
	 AND ATR.HostelId = @rHostelId
	  AND ((SA.Code = @rStudentCode) OR (@rStudentCode=''))
	  AND ((ATR.IsPresent=@rPresent) OR (@rPresent=2))
	  AND ((ATR.AttendanceDate >= @rFromAttendanceDate) OR (ISNULL(@rFromAttendanceDate,'') = ''))
	  AND ((ATR.AttendanceDate <= @rToAttendanceDate) OR (ISNULL(@rToAttendanceDate,'') = ''))
	   AND ((SA.SUId=@rSuid) OR (@rSuid=''))
	  AND  ((ATR.HostelAttendanceTypeId=@rHostelAttendanceTypeId) OR (@rHostelAttendanceTypeId=0))
	  AND SA.OrgGroupBatchId= @rOrgGroupBatchId
	  AND ATR.OrgGroupBatchId= @rOrgGroupBatchId
	    AND AR.OrgGroupBatchId= @rOrgGroupBatchId
	  AND (BM.Id=@rBuildingId OR @rBuildingId=0)
      ORDER BY ATR.AttendanceDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pAttendanceRegisterAdd]
	
	@rStrXml nvarchar(MAX),
    @rAttendanceDate date='',
    @rCreatedUserId bigint,
    @rRoomId int=0 ,
    @rHostelId int,
    @rHostelAttendanceTypeId int,
    @rOrgGroupBatchId int,
	@rBuildingId int = 0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE AR FROM sHostel.tAttendanceRegister AR 
	 INNER JOIN sHostel.tAssignRoom ASR ON ASR.SourceId = AR.StudentId AND ASR.SourceTypeId=2003   
	 INNER JOIN sHostel.tRoomMaster RM ON RM.Id = ASR.RoomId
	    WHERE 
	    AR.AttendanceDate = @rAttendanceDate
	    AND  (ASR.RoomId=@rRoomId OR @rRoomId=0)
	    AND AR.HostelId = @rHostelId
	    AND AR.HostelAttendanceTypeId=@rHostelAttendanceTypeId
	    AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		AND (RM.BuildingId = @rBuildingId OR @rBuildingId=0)
	 INSERT INTO sHostel.tAttendanceRegister
		(
			HostelId,
			StudentId,
			AttendanceDate,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			HostelAttendanceTypeId,
			OrgGroupBatchId
			)
		SELECT	
			@rHostelId,
			StudentId,
			@rAttendanceDate,
			IsPresent,
			ISNULL(AbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rHostelAttendanceTypeId,
			@rOrgGroupBatchId
						
		FROM OPENXML (@loDoc, '/Table/AttendanceRegister', 1)
		WITH ( 
				StudentId bigint,
				IsPresent bit,
				AbsentReasonId int,
				HostelAttendanceTypeId int
			  )  
        SELECT 1 AS Result
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pAttendanceRegisterDelete]
	 
	@rAttendanceDate date,
	@rRoomId int=0 ,
    @rHostelId int,
    @rHostelAttendanceTypeId int,
    @rOrgGroupBatchId int,
	@rBuildingId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	 BEGIN TRANSACTION	
DELETE AR
FROM sHostel.tAttendanceRegister AR
 INNER JOIN sHostel.tAssignRoom ASR ON ASR.SourceId = AR.StudentId AND ASR.SourceTypeId=2003  
  INNER JOIN sHostel.tRoomMaster RM ON RM.Id = ASR.RoomId
 WHERE 
	    AR.AttendanceDate = @rAttendanceDate
	    AND  (ASR.RoomId=@rRoomId OR @rRoomId=0)
	    AND AR.HostelId = @rHostelId
	    AND AR.HostelAttendanceTypeId=@rHostelAttendanceTypeId
	    AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	    AND (RM.BuildingId = @rBuildingId OR @rBuildingId = 0)
 SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pAttendanceRegisterDetailsGet]
          
           @rHostelId int,
           @rOrgId int,
           @rSourceTypeId smallint,
           @rCode nvarchar(20),
           @rFromAllocateDate date,
           @rToAllocateDate date,
           @rToVacantDate date='',
           @rFromVacantDate date='',
           @rSUID nvarchar(50),
           @rOrgGroupBatchId int
           
          
AS
SET NOCOUNT ON

BEGIN
SELECT  
		OM.DisplayTitle AS OrganizationName,
        (CASE WHEN HA.SourceTypeId = 95 THEN	'Employee'
			 WHEN HA.SourceTypeId = 2003 THEN	'Student' END) AS SourceType,

		(CASE WHEN HA.SourceTypeId = 95 THEN	Emp.Code
			 WHEN HA.SourceTypeId = 2003 THEN	SM.Code END) AS SourceCode, 	
		
		(CASE WHEN HA.SourceTypeId = 95 THEN	''
			 WHEN HA.SourceTypeId = 2003 THEN	SM.SUId END) AS SUId, 	

		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN HA.SourceTypeId = 2003 THEN SM.LastName + ' ' + SM.FirstName  END) AS SourceName,
			
		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN HA.SourceTypeId = 2003 THEN (sStudent.fStudentCurrentDivisionGet(SM.StudentId)) END) AS ClassDepartmentName,		
		 
		 HA.SourceTypeId,
		 HA.SourceId,
		 HA.AllocateDate,
		(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
		 ISNULL(HA.VacantReason,'') AS VacantReason

  FROM 
		sHostel.tHostelAdmission HA
        LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = HA.SourceId AND HA.SourceTypeId = 95 
		LEFT JOIN sStudent.vStudentAcademic SM
			ON SM.StudentId = HA.SourceId AND HA.SourceTypeId = 2003 AND SM.OrgGroupBatchId=@rOrgGroupBatchId 	
		LEFT JOIN sSetup.tOrganizationMaster OM ON (OM.Id = SM.OrgId) OR (OM.Id = Emp.OrgId)  	
  WHERE 
	
	(HA.Hosteld=@rHostelId)
	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
	AND ((HA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
        OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
	AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
	AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
	AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
	AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
	AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
	AND HA.OrgGroupBatchId=@rOrgGroupBatchId
	order by  HA.AllocateDate desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pAttendanceRegisterGet]
	 	 
	 	 @rRoomId int,
		 @rAttendanceDate date,
		 @rHostelId int,
		 @rHostelAttendanceTypeId int,
		 @rOrgGroupBatchId int,
		 @rBuildingId int = 0

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	IF EXISTS(SELECT 1 FROM sHostel.tAttendanceRegister ATR INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = ATR.StudentId AND AR.SourceTypeId=2003
	            INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
				WHERE ATR.AttendanceDate=@rAttendanceDate AND ATR.OrgGroupBatchId=@rOrgGroupBatchId AND ATR.HostelAttendanceTypeId=@rHostelAttendanceTypeId
				 AND AR.RoomId = @rRoomId AND RM.BuildingId = @rBuildingId )
	BEGIN
		SELECT 
			AR.SourceId AS StudentId,
			VA.Code,
			VA.Name,
			VA.SUId,
			ISNULL(ATR.IsPresent,'true') as IsPresent,
			ISNULL(ATR.AbsentReasonId,0) as AbsentReasonId,
			CASE WHEN ATR.CreatedUserId IS NULL THEN 'false' ELSE 'true' END AS IsDeleted,
			(SI.StudentPhoto) AS StudentPhoto,
			ISNULL(ATR.HostelAttendanceTypeId,0) AS HostelAttendanceTypeId
			
  FROM 
           sStudent.vStudentAcademic VA 
            INNER JOIN sHostel.tAssignRoom AR ON VA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
            LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=VA.StudentId
            INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
            INNER JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId=VA.StudentId 			
			AND (ATR.AttendanceDate=@rAttendanceDate) AND (ATR.OrgGroupBatchId=@rOrgGroupBatchId)
			AND isnull(ATR.HostelAttendanceTypeId,0)=@rHostelAttendanceTypeId
			INNER JOIN sHostel.tHostelAdmission HA ON HA.SourceId =  AR.SourceId  AND HA.SourceTypeId=2003 AND HA.OrgGroupBatchId = AR.OrgGroupBatchId
								  
  WHERE 
      RM.HostelId = @rHostelId
	  AND ((AR.RoomId=@rRoomId) OR (@rRoomId=0))
	   AND VA.OrgGroupBatchId=@rOrgGroupBatchId
	   AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	   AND ((RM.BuildingId = @rBuildingId) OR (@rBuildingId=0))
	   AND (HA.AllocateDate <= @rAttendanceDate)
  ORDER BY VA.Code
	END
	ELSE
		BEGIN
		SELECT 
				AR.SourceId AS StudentId,
				VA.Code,
				VA.Name,
				VA.SUId,
				ISNULL(ATR.IsPresent,'true') as IsPresent,
				ISNULL(ATR.AbsentReasonId,0) as AbsentReasonId,
				CASE WHEN ATR.CreatedUserId IS NULL THEN 'false' ELSE 'true' END AS IsDeleted,
				(SI.StudentPhoto) AS StudentPhoto,
				ISNULL(ATR.HostelAttendanceTypeId,0) AS HostelAttendanceTypeId
			
	  FROM 
			   sStudent.vStudentAcademic VA 
				INNER JOIN sHostel.tAssignRoom AR ON VA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=VA.StudentId
				INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
				LEFT JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId=VA.StudentId 			
				AND (ATR.AttendanceDate=@rAttendanceDate) AND (ATR.OrgGroupBatchId=@rOrgGroupBatchId)
				AND isnull(ATR.HostelAttendanceTypeId,0)=@rHostelAttendanceTypeId			
				INNER JOIN sHostel.tHostelAdmission HA ON HA.SourceId =  AR.SourceId  AND HA.SourceTypeId=2003 AND HA.OrgGroupBatchId = AR.OrgGroupBatchId
		  
	  WHERE 
		  RM.HostelId = @rHostelId
		  AND ((AR.RoomId=@rRoomId) OR (@rRoomId=0))
		   AND VA.OrgGroupBatchId=@rOrgGroupBatchId
		   AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		   AND ((RM.BuildingId = @rBuildingId) OR (@rBuildingId=0))
		   AND (HA.AllocateDate <= @rAttendanceDate)
	  ORDER BY VA.Code
	  END

	 --Select * from sHostel.tAttendanceRegister where Hostelattendancetypeid = 991100003 AND Attendancedate = '2022-12-28 00:00:00'

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pBuildingMasterAdd]
	 
        @rHostelId int,
        @rId int,
        @rCode nvarchar(20),
        @rTitle nvarchar(100),
        @rIsObsolete bit,
        @rCreatedUserId bigint,
        @rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM sHostel.tBuildingMaster WHERE Code=@rCode AND HostelId=@rHostelId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END 
	
		IF EXISTS(SELECT Id FROM sHostel.tBuildingMaster WHERE Title=@rTitle AND HostelId=@rHostelId)
			BEGIN
			SELECT -103 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT Id FROM sHostel.tBuildingMaster WHERE Code=@rCode AND HostelId=@rHostelId AND Id<>@rId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT Id FROM sHostel.tBuildingMaster WHERE Title=@rTitle AND HostelId=@rHostelId AND Id<>@rId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tBuildingMaster', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT
	
	INSERT INTO sHostel.tBuildingMaster
		(
			HostelId,
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rHostelId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tBuildingMaster
	    SET
			
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pBuildingMasterGet]
	 
	 @rHostelId int,
	 @rId int,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			BM.Id AS BuildingId,
			BM.HostelId,
			BM.Code,
			BM.Title,
			BM.IsObsolete
	FROM 
			sHostel.tBuildingMaster BM
	WHERE 
		BM.HostelId = @rHostelId
		AND	((BM.Id = @rId) OR (@rId = 0))
		AND ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pChangeRoomAdd]
	 
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rRoomId int,
	@rBedNumber nvarchar(20),
	@rLogDate date,
	@rChangeReason nvarchar(200),
	@rRoomCondition nvarchar(200),
	@rOrgGroupBatchId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	 BEGIN TRANSACTION	
	 
BEGIN	 
	 UPDATE  sHostel.tAssignRoom
	    SET
			RoomId=@rRoomId,
			BedNumber=@rBedNumber
	    WHERE SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId  AND OrgGroupBatchId=@rOrgGroupBatchId
END 
BEGIN
	INSERT INTO sHostel.tChangeRoom
		(
			RoomId,
			SourceTypeId,
			SourceId,
			LogDate,
			ChangeReason,
			RoomCondition,
			OrgGroupBatchId
		)
	VALUES
		(
			@rRoomId,
			@rSourceTypeId,
			@rSourceId,
			@rLogDate,
			@rChangeReason,
			@rRoomCondition,
			@rOrgGroupBatchId
		)
		             
END	 
	
		COMMIT TRANSACTION
		END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pChangeRoomGet]
          
           @rHostelId int,
           @rOrgId int,
           @rSourceTypeId smallint,
           @rCode nvarchar(20),
           @rFromLogDate date,
           @rToLogDate date,
           @rSUID nvarchar(50),
           @rOrgGroupBatchId int
          
AS
SET NOCOUNT ON

BEGIN
SELECT  
		OM.DisplayTitle AS OrganizationName,
        (CASE WHEN CR.SourceTypeId = 95 THEN	'Employee'
			 WHEN CR.SourceTypeId = 2003 THEN	'Student' END) AS SourceType,

		(CASE WHEN CR.SourceTypeId = 95 THEN	Emp.Code
			 WHEN CR.SourceTypeId = 2003 THEN	SM.Code END) AS SourceCode, 	
			 
		(CASE WHEN CR.SourceTypeId = 95 THEN	''
			 WHEN CR.SourceTypeId = 2003 THEN	SM.SUId END) AS SUId, 		 

		(CASE WHEN CR.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN CR.SourceTypeId = 2003 THEN SM.Name  END) AS SourceName,
			
		(CASE WHEN CR.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN CR.SourceTypeId = 2003 THEN (sStudent.fStudentCurrentDivisionGet(SM.StudentId)) END) AS ClassDepartmentName,	
		 RM.Title AS RoomName,
		 CR.SourceTypeId,
		 CR.SourceId,
		(CASE WHEN CR.LogDate = '1900-01-01' THEN ''
			ELSE CR.LogDate END) AS LogDate,	
		 ISNULL(CR.ChangeReason,'') AS ChangeReason

  FROM 
		sHostel.tChangeRoom CR
		INNER JOIN sHostel.tRoomMaster RM ON RM.Id = CR.RoomId
        LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = CR.SourceId AND CR.SourceTypeId = 95 
		LEFT JOIN sStudent.vStudentAcademic SM
			ON SM.StudentId = CR.SourceId AND CR.SourceTypeId = 2003 AND SM.OrgGroupBatchId=@rOrgGroupBatchId			
		LEFT JOIN sSetup.tOrganizationMaster OM ON (OM.Id = SM.OrgId) OR (OM.Id = Emp.OrgId)  	
  WHERE 
	
	(RM.HostelId=@rHostelId)
	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
	AND ((CR.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
        OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
	AND ((CR.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	AND ((CR.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
	AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
	AND CR.OrgGroupBatchId=@rOrgGroupBatchId
	order by  CR.LogDate desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pClasswiseHostelFeeUpdate]
	 
	@rBatchId int,
	@rOrgGroupId int,
	@rOrgGroupBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	-- Delete FeeOptional
	DELETE D FROM sFee.tFeeOptional D 
	INNER JOIN sFee.tFeeSetup FS ON D.FeeSetupId = FS.Id AND FS.BatchId = D.BatchId
	INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 	 
	INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
	WHERE 
	FHM.Number = 1002
	AND FHM.OrgGroupId = @rOrgGroupId
	AND D.BatchId = @rBatchId
	AND D.SourceId NOT IN 
	(SELECT R.SourceId FROM sFee.tReceipt R 
	INNER JOIN sFee.tReceiptDetail RD ON R.Id=RD.ReceiptId
	INNER JOIN sFee.tFeeOptional D ON D.SourceId = R.SourceId AND D.SourceTypeId = R.SourceTypeId 
	AND D.BatchId = R.BatchId AND D.FeeSetupId = Rd.FeeSetupId
	INNER JOIN sFee.tFeeSetup FS ON D.FeeSetupId = FS.Id AND FS.BatchId = D.BatchId
	INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 	 
	INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
	WHERE 
	FHM.Number = 1002
	AND FHM.OrgGroupId = @rOrgGroupId
	AND D.BatchId = @rBatchId)
	
	-- Insert FeeOptional
	INSERT INTO sFee.tFeeOptional
	SELECT	  
	FS.Id,
	2001,
	A.AcademicId,
	@rBatchId
	FROM sHostel.tAssignRoom AR
	INNER JOIN sStudent.vStudentAcademic A ON AR.SourceId = A.StudentId AND AR.SourceTypeId = 2003
	INNER JOIN sFee.tFeeSetup FS ON A.ClassId = FS.ClassId AND A.AdmissionCategoryId = FS.AdmissionCategoryId AND FS.BatchId = A.BatchId
	INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 	 
	INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
	WHERE  
	FHM.Number = 1002
	AND FHM.OrgGroupId = @rOrgGroupId
	AND A.BatchId = @rBatchId
	AND FS.IsOptional = 1
	AND AR.OrgGroupBatchId = @rOrgGroupBatchId
	AND A.AcademicId NOT IN 
	(SELECT R.SourceId FROM sFee.tReceipt R 
	INNER JOIN sFee.tReceiptDetail RD ON R.Id=RD.ReceiptId
	INNER JOIN sFee.tFeeOptional D ON D.SourceId = R.SourceId AND D.SourceTypeId = R.SourceTypeId 
	AND D.BatchId = R.BatchId AND D.FeeSetupId = Rd.FeeSetupId
	INNER JOIN sFee.tFeeSetup FS ON D.FeeSetupId = FS.Id AND FS.BatchId = D.BatchId
	INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 	 
	INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
	WHERE 
	FHM.Number = 1002
	AND FHM.OrgGroupId = @rOrgGroupId
	AND D.BatchId = @rBatchId)

	SELECT 1 AS Result
     
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHostel].[pDepositAddBulkGet]
       
       @rOrgId int=0,          
       @rHostelId int=0,
       @rCode nvarchar(20)='',
       @rRoomCategoryId int=0,
       @rBuildingId int=0,
       @rRoomId int=0,
       @rOrgGroupBatchId int=0,
	   @rStrSuid nvarchar(max)=''--Added for mantis : 35982 by Nilesh
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
		vSA.OrgId,
		vSA.StudentId,
		vSA.AcademicId,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
       ISNULL(VSA.SUID,'') AS SUID
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = vSA.StudentId AND AR.SourceTypeId=2003
		AND AR.OrgGroupBatchId = vSA.OrgGroupBatchId
		INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (RM.HostelId=@rHostelId OR @rHostelId=0)
		AND (RM.RoomCategoryId=@rRoomCategoryId OR @rRoomCategoryId=0)
		AND (RM.BuildingId=@rBuildingId OR @rBuildingId=0)
		AND (RM.Id=@rRoomId OR @rRoomId=0)
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		AND (ISNULL(vSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='')--Added for mantis : 35982 by Nilesh
   ORDER BY vSA.OrgId,vSA.ClassOrderIndex,vSA.DivisionOrder,vSA.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pDepositAdjustmentBulkGet]
           @rOrgId int,    
           @rCode nvarchar(max),
           @rHostelId int,
           @rOrgGroupBatchId int,
           @rStrSuid nvarchar(max)='',
           @rRoomCategoryId int,
           @rBuildingId int,
           @rRoomId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
		vSA.OrgId,
		vSA.StudentId AS StudentId,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(vSA.SUId,'') AS SUId,
        VSA.AcademicId,
        RCM.Title AS RoomCategory,
        RM.Title As Room
  FROM 		
			sStudent.vStudentAcademic vSA
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=VSA.StudentId AND AR.SourceTypeId=2003
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
			INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
			AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
		    LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (RM.HostelId=@rHostelId)
		AND ((VSA.OrgGroupBatchId=@rOrgGroupBatchId))
		AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId))
		AND RM.IsObsolete=0
	    AND (BM.Id=@rBuildingId OR @rBuildingId=0)
	    AND (RM.Id=@rRoomId OR @rRoomId=0)
	    AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
	    AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
		Order By VSA.SUId,VSA.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelAdmissionAdd]
	 
	@rHostelId int,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rAllocateDate date,
	@rOrgGroupBatchId int,
	@rIsSelfPermissionToGoOut bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	IF NOT EXISTS (SELECT 1 FROM sHostel.tHostelAdmission WHERE  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND OrgGroupBatchId=@rOrgGroupBatchId)
	BEGIN
	INSERT INTO sHostel.tHostelAdmission
		(
			Hosteld,
			SourceTypeId,
			SourceId,
			AllocateDate,
			OrgGroupBatchId,
			IsSelfPermissionToGoOut
		)
	VALUES
		(
			@rHostelId,
			@rSourceTypeId,
			@rSourceId,
			@rAllocateDate,
			@rOrgGroupBatchId,
			@rIsSelfPermissionToGoOut
		)
		
	SELECT 1 AS Result	   
	END
	ELSE
	BEGIN
	UPDATE  sHostel.tHostelAdmission SET
	AllocateDate=@rAllocateDate,
	IsSelfPermissionToGoOut=@rIsSelfPermissionToGoOut
	WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND OrgGroupBatchId=@rOrgGroupBatchId
	END     
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelAdmissionGet]
          
           @rHostelId int,
           @rOrgId int,
           @rSourceTypeId smallint,
           @rCode nvarchar(20),
           @rFromAllocateDate date,
           @rToAllocateDate date,
           @rToVacantDate date='',
           @rFromVacantDate date='',
           @rSUID nvarchar(50),
           @rOrgGroupBatchId int       
AS
SET NOCOUNT ON

BEGIN
IF (@rSourceTypeId = 95)
	BEGIN 
		SELECT
			OM.DisplayTitle AS OrganizationName,
			'Employee' AS SourceType,
			Emp.Code AS SourceCode, 
			'' AS SUId,
			Emp.EmployeeName AS SourceName,
			Emp.DepartmentName AS ClassDepartmentName,
			HA.SourceTypeId,
			HA.SourceId,
			HA.AllocateDate,
			(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
			ISNULL(HA.VacantReason,'') AS VacantReason,
			ISNULL(RM.Title, '') AS RoomName

		FROM 
			sHostel.tHostelAdmission HA 
			INNER JOIN sHrm.vExtEmployeeMaster Emp ON Emp.Id = HA.SourceId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgId
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = Emp.EmployeeId AND AR.SourceTypeId = 95 AND AR.OrgGroupBatchId = HA.OrgGroupBatchId 
			LEFT JOIN sHostel.tRoomMaster RM ON RM.HostelId = HA.Hosteld AND RM.Id = AR.RoomId	 

		WHERE 
			(HA.Hosteld=@rHostelId)
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
			AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
			AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
			AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
			AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
			AND HA.OrgGroupBatchId=@rOrgGroupBatchId
		--ORDER BY  HA.AllocateDate DESC
	END

ELSE IF (@rSourceTypeId = 2003)
	BEGIN
		SELECT
			OM.DisplayTitle AS OrganizationName,
			'Student' AS SourceType,
			SM.Code AS SourceCode, 
			SM.SUId,
			SM.LastName + ' ' + SM.FirstName  AS SourceName,
			sStudent.fStudentCurrentDivisionGet(SM.StudentId) AS ClassDepartmentName,
			HA.SourceTypeId,
			HA.SourceId,
			HA.AllocateDate,
			(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
			ISNULL(HA.VacantReason,'') AS VacantReason,
			ISNULL(RM.Title, '') AS RoomName

		FROM 
			sHostel.tHostelAdmission HA
			INNER JOIN sStudent.vStudentAcademic SM ON SM.StudentId = HA.SourceId AND SM.OrgGroupBatchId=@rOrgGroupBatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = SM.OrgGroupBatchId AND BM.Id = SM.BatchId 
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.StudentId AND AR.SourceTypeId = 2003 AND AR.OrgGroupBatchId = HA.OrgGroupBatchId
			LEFT JOIN sHostel.tRoomMaster RM ON RM.HostelId = HA.Hosteld AND RM.Id = AR.RoomId
			
		WHERE 
	
			(HA.Hosteld=@rHostelId)
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='')) 
			AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
			AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
			AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
			AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
			AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
			AND HA.OrgGroupBatchId=@rOrgGroupBatchId
			AND BM.IsInContext = 1
			--order by  HA.AllocateDate desc	
	END

ELSE
	BEGIN
		SELECT
			OM.DisplayTitle AS OrganizationName,
			'Employee' AS SourceType,
			Emp.Code AS SourceCode, 
			'' AS SUId,
			Emp.EmployeeName AS SourceName,
			Emp.DepartmentName AS ClassDepartmentName,
			HA.SourceTypeId,
			HA.SourceId,
			HA.AllocateDate,
			(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
			ISNULL(HA.VacantReason,'') AS VacantReason,
			ISNULL(RM.Title, '') AS RoomName

		FROM 
			sHostel.tHostelAdmission HA 
			INNER JOIN sHrm.vExtEmployeeMaster Emp ON Emp.Id = HA.SourceId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgId
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = Emp.EmployeeId AND AR.SourceTypeId = 95 AND AR.OrgGroupBatchId = HA.OrgGroupBatchId 
			LEFT JOIN sHostel.tRoomMaster RM ON RM.HostelId = HA.Hosteld AND RM.Id = AR.RoomId	 

		WHERE 
			(HA.Hosteld=@rHostelId)
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
			AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
			AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
			AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
			AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
			AND HA.OrgGroupBatchId=@rOrgGroupBatchId

			UNION ALL


			SELECT
			OM.DisplayTitle AS OrganizationName,
			'Student' AS SourceType,
			SM.Code AS SourceCode, 
			SM.SUId,
			SM.LastName + ' ' + SM.FirstName  AS SourceName,
			sStudent.fStudentCurrentDivisionGet(SM.StudentId) AS ClassDepartmentName,
			HA.SourceTypeId,
			HA.SourceId,
			HA.AllocateDate,
			(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
			ISNULL(HA.VacantReason,'') AS VacantReason,
			ISNULL(RM.Title, '') AS RoomName

		FROM 
			sHostel.tHostelAdmission HA
			INNER JOIN sStudent.vStudentAcademic SM ON SM.StudentId = HA.SourceId AND SM.OrgGroupBatchId=@rOrgGroupBatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = SM.OrgGroupBatchId AND BM.Id = SM.BatchId 
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId = SM.StudentId AND AR.SourceTypeId = 2003 AND AR.OrgGroupBatchId = HA.OrgGroupBatchId
			LEFT JOIN sHostel.tRoomMaster RM ON RM.HostelId = HA.Hosteld AND RM.Id = AR.RoomId
			
		WHERE 
	
			(HA.Hosteld=@rHostelId)
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='')) 
			AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
			AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
			AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
			AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
			AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
			AND HA.OrgGroupBatchId=@rOrgGroupBatchId
			AND BM.IsInContext = 1
			--order by  HA.AllocateDate desc
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelAdmissionUpdate]
	 
	@rHostelId int,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rVacantDate date,
	@rVacantReason nvarchar(200),
	@rRoomCondition nvarchar(200),
	@rOrgGroupBatchId int,
	@rRoomId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	UPDATE  sHostel.tHostelAdmission
	    SET
	    
			VacantDate=@rVacantDate,
			VacantReason=@rVacantReason,
			RoomCondition=@rRoomCondition,
			RoomId = @rRoomId
			
	    WHERE Hosteld=@rHostelId 
			AND SourceTypeId = @rSourceTypeId 
			AND SourceId = @rSourceId 	  
			AND OrgGroupBatchId= @rOrgGroupBatchId  
	SELECT 1 AS Result	
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelAttendanceTypeMasterAdd]
	 
	    @rId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rOrgGroupId int,
		@rCreatedUserId bigint,
		@rHostelId Int
		
		
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select 1 from sHostel.tHostelAttendanceTypeMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId )
		Begin
			select -102 as Result
			RETURN
		End
		If Exists(select 1 from sHostel.tHostelAttendanceTypeMaster  where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
	If Exists(select 1 from sHostel.tHostelAttendanceTypeMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId  AND HostelId=@rHostelId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sHostel.tHostelAttendanceTypeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId AND HostelId=@rHostelId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelAttendanceTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tHostelAttendanceTypeMaster
		(
			HostelId, 
			Id, 
			Code, 
			Title, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			OrgGroupId
		)
	VALUES
		(   @rHostelId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId
		)
		 SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tHostelAttendanceTypeMaster
	    SET
			Title=@rTitle,
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelAttendanceTypeMasterGet]
	 	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId int,
	 @rHostelId Int=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			Id,
			Title,
		    Code,
			IsObsolete
      
  FROM 
          sHostel.tHostelAttendanceTypeMaster 
            
  WHERE   
           ((Id = @rId) OR (@rId = 0))
	       AND ((Title like @rTitle +'%') OR (ISNULL(@rTitle,'') = ''))
	       AND ((Code like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
	       AND OrgGroupId=@rOrgGroupId
	       AND HostelId=@rHostelId
	     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelDataDelete]
	 
	@rHostelId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	DELETE  AR FROM sHostel.tAssignRoom AR INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId  WHERE RM.HostelId=@rHostelId
	DELETE FROM sHostel.tAttendanceRegister WHERE  HostelId=@rHostelId
	DELETE FROM sHostel.tBuildingMaster WHERE  HostelId=@rHostelId
	DELETE CR FROM sHostel.tChangeRoom CR INNER JOIN sHostel.tRoomMaster RM ON RM.Id=CR.RoomId  WHERE RM.HostelId=@rHostelId
	DELETE FROM sHostel.tHostelAdmission  WHERE Hosteld=@rHostelId
	DELETE FROM sHostel.tHostelAttendanceTypeMaster WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tAssetTypeMaster WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tAssignRoomAsset WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tHostelDepositAdd WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tHostelDepositAdjustment WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tHostelDepositHeadMaster  WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tHostelDepositRefund WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tHostelExpenseTypeMaster  WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tHostelExpenseSubTypeMaster  WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tHostelGatePassReasonMaster WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tHostelStudentGatePass WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tHostelWarden WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tRoomAssetMaster WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tRoomCategoryMaster WHERE HostelId=@rHostelId
	DELETE FROM sHostel.tRoomMaster WHERE HostelId=@rHostelId
    DELETE FROM sHostel.tStudentGatePass WHERE HostelId=@rHostelId
    DELETE FROM sHostel.tVisitorGatePass WHERE HostelId=@rHostelId
    DELETE FROM sHostel.tHostelMaster WHERE Id=@rHostelId
    
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositAddAdd]
	 
	@rId bigint,
	@rHostelDepositHeadId int,
	@rStudentId bigint,
	@rAmount decimal(12,2),
	@rDepositDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rHostelId int,
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lStudentId bigint,@lPriviousAmount decimal(12,2)=0
	DECLARE @lDepositAdd decimal(12,2)
	DECLARE @lAdjustmentAdd decimal(12,2)
	DECLARE @lRefundAdd decimal(12,2)
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

  SELECT @lStudentId= StudentId FROM sStudent.vStudentAcademic Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId
  SELECT @lDepositAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
	    WHERE D.StudentId = @lStudentId
	    AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId AND D.OrgGroupBatchId=@rOrgGroupBatchId)
   SELECT @lAdjustmentAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdjustment D 
	    WHERE D.StudentId = @lStudentId
	     AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId AND D.OrgGroupBatchId=@rOrgGroupBatchId)
  SELECT @lRefundAdd = (SELECT ISNULL(SUM(R.RefundAmount),0) FROM sHostel.tHostelDepositRefund R 
	    WHERE R.StudentId = @lStudentId
	     AND R.HostelDepositHeadId = @rHostelDepositHeadId  AND R.HostelId=@rHostelId AND R.OrgGroupBatchId=@rOrgGroupBatchId)
	     
	    SET @lPriviousAmount=@lDepositAdd - @lAdjustmentAdd - @lRefundAdd
	-- AMOUNT VALIDATION
	--If EXISTS
	--(SELECT DB.BalanceAmount FROM sFee.tDepositBalance DB WHERE DB.DepositHeadId = @rDepositHeadId AND DB.ClassId=@lClassId AND BalanceAmount 
	-- < (SELECT  ISNULL(SUM(DA.Amount),0) + @rAmount AS TotalAmount FROM sFee.tDepositAdd DA 
	--	WHERE DepositHeadId = @rDepositHeadId AND StudentId=@lStudentId AND Id <> @rId)) 				
	--BEGIN
	--	SELECT -102 as Result
	--	RETURN
	--END 

 DECLARE @lNextNumber bigint 
 IF(@rId = 0)	    
 BEGIN  
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelDepositAdd', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sHostel.tHostelDepositAdd
		(
		Id,
		HostelDepositHeadId,
		StudentId,
		Amount,
		DepositDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		HostelId,
		OrgGroupBatchId,
		PreviousBalance
		)
	VALUES
		(
		@lNextNumber,
		@rHostelDepositHeadId,
		@lStudentId,
		@rAmount,
		@rDepositDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rHostelId,
		@rOrgGroupBatchId,
		@lPriviousAmount
		) 
		SELECT @lNextNumber AS Result   
	END	
ELSE

    BEGIN 
    SET @lNextNumber = @rId
	    UPDATE sHostel.tHostelDepositAdd
	    SET
	    HostelDepositHeadId=@rHostelDepositHeadId,
	    StudentId=@lStudentId,
		Amount=@rAmount,
		DepositDate=@rDepositDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    HostelId=@rHostelId	 ,
	    OrgGroupBatchId=@rOrgGroupBatchId
	   
	    WHERE Id = @rId  AND HostelId=@rHostelId
	    SELECT @lNextNumber AS Result
	 END 
	  
	COMMIT TRANSACTION
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[PHostelDepositAddAllDelete]
	 
	      @rHostelId int,
          @rOrgGroupBatchId int,
          @rHostelDepositHeadId int,
          @rDepositId bigint,
          @rStudentId bigint
     
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	BEGIN TRY
			
			
	IF EXISTS (SELECT 1 FROM  sHostel.tHostelDepositAdjustment WHERE StudentId=@rStudentId AND HostelDepositHeadId=@rHostelDepositHeadId AND OrgGroupBatchId=@rOrgGroupBatchId AND HostelId=@rHostelId)
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	ELSE 
	IF EXISTS (SELECT 1 FROM  sHostel.tHostelDepositRefund WHERE StudentId=@rStudentId AND HostelDepositHeadId=@rHostelDepositHeadId  AND OrgGroupBatchId=@rOrgGroupBatchId AND HostelId=@rHostelId)
	BEGIN
		SELECT -102 AS RESULT
		RETURN
	END
	ELSE 
	BEGIN TRANSACTION
	BEGIN
		DELETE  sHostel.tHostelDepositAdd
		FROM sHostel.tHostelDepositAdd DA
		WHERE DA.Id=@rDepositId AND  DA.OrgGroupBatchId=@rOrgGroupBatchId
		AND DA.HostelId=@rHostelId  AND HostelDepositHeadId=@rHostelDepositHeadId 
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositAddDelete]
	 
		@rId bigint,
	  @rOrgGroupBatchId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lStudentId bigint
BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION	
			
	IF EXISTS (SELECT 1 FROM  sHostel.tHostelDepositAdjustment DA1 INNER JOIN sHostel.tHostelDepositAdd DA2 
							  ON DA1.StudentId=DA2.StudentId AND DA1.HostelDepositHeadId=DA2.HostelDepositHeadId AND DA1.HostelId=DA2.HostelId  AND DA1.OrgGroupBatchId=@rOrgGroupBatchId AND DA2.OrgGroupBatchId=@rOrgGroupBatchId)
	BEGIN
		SELECT -101 AS RESULT
	END
	ELSE 
	BEGIN
		DELETE  sHostel.tHostelDepositAdd
		FROM sHostel.tHostelDepositAdd DA
		WHERE DA.Id=@rId AND  DA.OrgGroupBatchId=@rOrgGroupBatchId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositAddGET]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromDepositDate date,
           @rToDepositDate date,
           @rHostelId int,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int
AS
SET NOCOUNT ON
BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
       ISNULL(VSA.SUID,'') AS SUID
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId 
  WHERE  
		
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DA.HostelId=@rHostelId)
		AND DA.OrgGroupBatchId=@rOrgGroupBatchId
		AND vSA.OrgGroupBatchId=@rOrgGroupBatchId
		Order By DA.DepositDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositAdjustmentAdd]
	
	@rId bigint, 
	@rHostelDepositHeadId int,
	@rStudentId bigint,
	@rAmount decimal(12,2),
	@rAdjustmentDate date,
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rBatchId int=0,
	@rOrgGroupId smallint ,
	@rHostelId int,
	@rHostelExpenseTypeId int,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

 SELECT @lStudentId= StudentId From sStudent.vStudentAcademic Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId
 	
	-- DATE VALIDATION
	--BEGIN
	--	IF EXISTS	(SELECT 1 FROM  sHostel.tHostelDepositAdd D  INNER JOIN sHostel.tHostelDepositAdjustment DA ON D.HostelDepositHeadId = DA.HostelDepositHeadId 
	--								AND D.StudentId=@lStudentId AND D.HostelId=@rHostelId  AND D.DepositDate > @rAdjustmentDate)
	--	BEGIN
	--		SELECT -101 as Result
	--		RETURN
	--	END 
	--END 
 
	-- AMOUNT VALIDATIEON
	--BEGIN
	--	 If EXISTS
	--		(SELECT ISNULL(SUM(D.Amount),0),DepositHeadId,StudentId FROM sFee.tDepositAdd D 
	--		WHERE D.DepositHeadId = @rDepositHeadId AND D.StudentId=@lStudentId Group by StudentId,DepositHeadId Having Sum(D.Amount) 
	--	 < (SELECT ISNULL(SUM(Amount),0)+ @rAmount AS TotalAmount FROM sFee.tDepositAdjustment DA 
	--		WHERE DA.DepositHeadId = @rDepositHeadId AND DA.StudentId=@lStudentId AND Id <> @rId )) 	
	--	BEGIN
	--		SELECT -102 as Result
	--		RETURN
	--	END 
	--END				
 
DECLARE @lNextNumber bigint 
IF(@rId = 0)
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelDepositAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output 
	INSERT INTO sHostel.tHostelDepositAdjustment
		(
		Id,
		HostelDepositHeadId,
		StudentId,
		Amount,
		AdjustmentDate,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		HostelId,
		HostelExpenseSubTypeId ,
	    OrgGroupBatchId 
		
		)
	VALUES
		(
		@lNextNumber,
		@rHostelDepositHeadId,
		@lStudentId,
		@rAmount,
		@rAdjustmentDate,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate()
		,@rHostelId
		,@rHostelExpenseTypeId 
	    ,@rOrgGroupBatchId 
		) 
		SELECT @lNextNumber AS Result   
	END	
ELSE
    BEGIN
    SET @lNextNumber = @rId
	    UPDATE sHostel.tHostelDepositAdjustment
	    SET
	    HostelDepositHeadId=@rHostelDepositHeadId,
	    StudentId=@lStudentId,
		Amount=@rAmount,
		AdjustmentDate=@rAdjustmentDate,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    HostelId=@rHostelId	    ,
	    HostelExpenseSubTypeId  =@rHostelExpenseTypeId
	    WHERE Id = @rId  AND HostelId=@rHostelId AND OrgGroupBatchId  =@rOrgGroupBatchId 
	    SELECT @lNextNumber AS Result
	 END  
	COMMIT TRANSACTION
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositAdjustmentDelete]
	 
		@rId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		

	--IF EXISTS (SELECT 1 FROM  sHostel.tHostelDepositRefund DR INNER JOIN sHostel.tHostelDepositAdjustment DA1 
	--						  ON DA1.StudentId=DR.StudentId AND DA1.HostelDepositHeadId=DR.HostelDepositHeadId AND DA1.HostelId=DR.HostelId)
	--BEGIN
	--	SELECT -101 AS RESULT
	--END
	
	--ELSE 
	BEGIN
		DELETE  sHostel.tHostelDepositAdjustment
		FROM sHostel.tHostelDepositAdjustment DA
		WHERE DA.Id=@rId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositAdjustmentGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromAdjustmentDate date,
           @rToAdjustmentDate date,
        --   @rBatchId int,
           @rCode nvarchar(20),
           @rHostelId int,
           @rHostelExpenseTypeId int,
           @rOrgGroupBatchId int,
           @rHostelExpenseSubTypeId int
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(vSA.SUId,'') AS SUId,
        Isnull(DA.HostelExpenseSubTypeId,0) AS HostelExpenseSubTypeId,
        ISNULL(EP.Title,'') AS HostelExpenseType,
        ISNULL(ES.Title,'') AS HostelSubExpenseType,
        Isnull(EP.Id,0) AS HostelExpenseTypeId
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdjustment DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId
	    LEFT JOIN sHostel.tHostelExpenseSubTypeMaster ES ON ES.Id = DA.HostelExpenseSubTypeId
	    LEFT JOIN sHostel.tHostelExpenseTypeMaster EP ON EP.Id = ES.ExpenseTypeId
  WHERE  
		--vSA.BatchId = @rBatchId 
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DA.HostelId=@rHostelId)
		AND ((VSA.OrgGroupBatchId=@rOrgGroupBatchId))
		AND ((DA.OrgGroupBatchId=@rOrgGroupBatchId))
		AND ((DA.HostelExpenseSubTypeId=@rHostelExpenseSubTypeId ) or (@rHostelExpenseSubTypeId=0))
	   AND ((EP.Id=@rHostelExpenseTypeId ) or (@rHostelExpenseTypeId=0))
		Order By DA.AdjustmentDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositBulkAdd]
	 
	@rId bigint=0,
	@rHostelDepositHeadId int=0,
	@rStudentId bigint=0,
	@rAmount decimal(12,2)=0,
	@rDepositDate date='',
	@rPayTypeId tinyint=0,
	@rChequeNo nvarchar(20)='',
	@rBankName nvarchar(200)='',
	@rRemark nvarchar(200)='',
	@rCreatedUserId bigint=0,
	@rHostelId int=0,
	@rOrgGroupId smallint=0,
	@rOrgGroupBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lStudentId bigint,@lPriviousAmount decimal(12,2)=0
	DECLARE @lDepositAdd decimal(12,2)
	DECLARE @lAdjustmentAdd decimal(12,2)
	DECLARE @lRefundAdd decimal(12,2)
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

  SELECT @lStudentId= StudentId FROM sStudent.vStudentAcademic Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId
  SELECT @lDepositAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
	    WHERE D.StudentId = @lStudentId
	    AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId AND D.OrgGroupBatchId=@rOrgGroupBatchId)
   SELECT @lAdjustmentAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdjustment D 
	    WHERE D.StudentId = @lStudentId
	     AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId AND D.OrgGroupBatchId=@rOrgGroupBatchId)
  SELECT @lRefundAdd = (SELECT ISNULL(SUM(R.RefundAmount),0) FROM sHostel.tHostelDepositRefund R 
	    WHERE R.StudentId = @lStudentId
	     AND R.HostelDepositHeadId = @rHostelDepositHeadId  AND R.HostelId=@rHostelId AND R.OrgGroupBatchId=@rOrgGroupBatchId)
	     
	    SET @lPriviousAmount=@lDepositAdd - @lAdjustmentAdd - @lRefundAdd
	-- AMOUNT VALIDATION
	--If EXISTS
	--(SELECT DB.BalanceAmount FROM sFee.tDepositBalance DB WHERE DB.DepositHeadId = @rDepositHeadId AND DB.ClassId=@lClassId AND BalanceAmount 
	-- < (SELECT  ISNULL(SUM(DA.Amount),0) + @rAmount AS TotalAmount FROM sFee.tDepositAdd DA 
	--	WHERE DepositHeadId = @rDepositHeadId AND StudentId=@lStudentId AND Id <> @rId)) 				
	--BEGIN
	--	SELECT -102 as Result
	--	RETURN
	--END 

 DECLARE @lNextNumber bigint     
 BEGIN  
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelDepositAdd', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sHostel.tHostelDepositAdd
		(
		Id,
		HostelDepositHeadId,
		StudentId,
		Amount,
		DepositDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		HostelId,
		OrgGroupBatchId,
		PreviousBalance
		)
	VALUES
		(
		@lNextNumber,
		@rHostelDepositHeadId,
		@lStudentId,
		@rAmount,
		@rDepositDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rHostelId,
		@rOrgGroupBatchId,
		@lPriviousAmount
		) 
		SELECT @lNextNumber AS Result   
	END	
	COMMIT TRANSACTION
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositHeadMasterAdd]
	 
	        @rId int
	       ,@rNumber int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rOrderIndex smallint
           ,@rIsObsolete bit
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId smallint
           ,@rHostelId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId  AND HostelId=@rHostelId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId  AND HostelId=@rHostelId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where Code=@rCode AND HostelId=@rHostelId AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If Exists(select Id from sHostel.tHostelDepositHeadMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If  Exists(select Id from sHostel.tHostelDepositHeadMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from sHostel.tHostelDepositHeadMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId  AND HostelId=@rHostelId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
	END
	
 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelDepositHeadMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sHostel].[tHostelDepositHeadMaster]
			   (
			    [Id]
			   ,[Number]  
			   ,[Code]
			   ,[Title]
			   ,[OrderIndex]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,[HostelId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rNumber
			   ,@rCode
			   ,@rTitle
			   ,@rOrderIndex
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rHostelId
			   )
			   SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sHostel].[tHostelDepositHeadMaster]
	    SET
			  Number=@rNumber
	         ,Code=@rCode
	         ,Title=@rTitle
	         ,OrderIndex=@rOrderIndex
             ,IsObsolete = @rIsObsolete                          
             ,UpdatedUserId = @rCreatedUserId
             ,UpdatedDateTime = sCommon.fGetDate() 
             ,HostelId=@rHostelId         
             
	      WHERE Id = @rId AND HostelId=@rHostelId  
	 END  
	      SELECT @lNextNumber AS Result
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositHeadMasterGet]
          
           @rId int,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId smallint,
           @rIsWildCardSearch bit,
           @rHostelId int
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT DHM.Id 
	  ,DHM.Number
      ,DHM.Code
      ,DHM.Title
      ,DHM.OrderIndex
      ,DHM.IsObsolete
     
  FROM sHostel.tHostelDepositHeadMaster DHM 
        
  WHERE 
		((DHM.Id = @rId) OR (@rId = 0))
	AND ((DHM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((DHM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND (DHM.OrgGroupId = @rOrgGroupId)
	AND (DHM.HostelId=@rHostelId)
		order by DHM.OrderIndex 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[PHostelDepositListGet]
	 
	      @rHostelId int,
	      @rRoomId int,
          @rOrgGroupBatchId int,
          @rStudentCode   nvarchar(max)='',
          @rSUId nvarchar(max)='',
          @rHostelDepositHeadId int
     
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT
	    DHM.Title AS DepositHeadName,
		DA.Id AS DepositId,
	    DA.Studentid AS Studentid,
		DA.Amount,
		DA.DepositDate,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
       ISNULL(VSA.SUID,'') AS SUID,
       RM.Title AS Room,
       	DA.HostelDepositHeadId
  FROM 		
		sHostel.tAssignRoom AR 
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId 
		INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id
	
		WHERE	
			 (DA.HostelId=@rHostelId)
			AND DA.OrgGroupBatchId=@rOrgGroupBatchId
		    AND AR.OrgGroupBatchId=@rOrgGroupBatchId
			AND vSA.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((DA.HostelDepositHeadId = @rHostelDepositHeadId) OR (ISNULL(@rHostelDepositHeadId,0) = 0))
			AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
			AND (ISNULL(vSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
	        AND (ISNULL(vSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
	    
			Order By VSA.SUID,VSA.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositRefundAdd]
	@rId bigint,
	@rHostelDepositHeadId int,
	@rStudentId bigint,
	@rRefundAmount decimal(12,2),
	@rRefundDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rHostelId int,
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lStudentId bigint
Declare @lRefundAmount decimal(12,2)
BEGIN	
BEGIN TRY
 SELECT @lStudentId= StudentId From  sStudent.vStudentAcademic Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId
  IF(@rId = 0)
  BEGIN
  
 DECLARE @lDepositAdd decimal(12,2)
 DECLARE @lAdjustmentAdd decimal(12,2)
 DECLARE @lRefundAdd decimal(12,2)
  
 SELECT @lDepositAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
	    WHERE D.StudentId = @lStudentId
	    AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId AND D.OrgGroupBatchId=@rOrgGroupBatchId)
  SELECT @lAdjustmentAdd = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdjustment D 
	    WHERE D.StudentId = @lStudentId
	     AND D.HostelDepositHeadId = @rHostelDepositHeadId   AND D.HostelId=@rHostelId AND D.OrgGroupBatchId=@rOrgGroupBatchId)
SELECT @lRefundAdd = (SELECT ISNULL(SUM(R.RefundAmount),0) FROM sHostel.tHostelDepositRefund R 
	    WHERE R.StudentId = @lStudentId
	     AND R.HostelDepositHeadId = @rHostelDepositHeadId  AND R.HostelId=@rHostelId AND R.OrgGroupBatchId=@rOrgGroupBatchId)
 
IF ( @lDepositAdd - @lAdjustmentAdd - @lRefundAdd < @rRefundAmount )
BEGIN
SELECT -101 AS RESULT -- Less then 0 amount re
RETURN
END
END
 
 ---- AMOUNT VALIDATIEON
 --IF EXISTS (SELECT 1 FROM sHostel.tHostelDepositRefund DR WHERE StudentId= @lStudentId AND HostelDepositHeadId = @rHostelDepositHeadId AND HostelId=@rHostelId)
 --BEGIN
	--SELECT @lRefundAmount = (SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
	--INNER JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = @lStudentId
	--WHERE D.HostelDepositHeadId = DR1.HostelDepositHeadId AND D.StudentId=DR1.StudentId AND D.HostelId=DR1.HostelId)

	-- - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sHostel.tHostelDepositAdjustment DA 
	-- INNER JOIN sHostel.tHostelDepositRefund DR2 ON DR2.HostelDepositHeadId=DA.HostelDepositHeadId AND DR2.StudentId=DA.StudentId AND DA.StudentId = @lStudentId
	-- WHERE DA.HostelDepositHeadId = DR2.HostelDepositHeadId AND DA.StudentId=DR2.StudentId AND DA.HostelId=DR2.HostelId) 
	 
	--IF @lRefundAmount < @rRefundAmount
	--	BEGIN
	--		SELECT -101 AS RESULT
	--		RETURN
	--	END		 
	--END	 
	
 -- DATE VALIDATION
 
	--BEGIN
	--	IF EXISTS	(SELECT 1 FROM  sHostel.tHostelDepositAdd D  INNER JOIN sHostel.tHostelDepositRefund DR ON D.HostelDepositHeadId = DR.HostelDepositHeadId 
	--								AND D.StudentId=@lStudentId  AND D.HostelId=@rHostelId AND D.DepositDate > @rRefundDate)
	--	BEGIN
	--		SELECT -102 as Result
	--		RETURN
	--	END 
	--END 
 
 --IF NOT EXISTS (SELECT 1 FROM sHostel.tHostelDepositRefund DR INNER JOIN sStudent.tAcademic A ON A.StudentId = DR.StudentId 
	--		    AND A.StudentId=@lStudentId AND DR.HostelDepositHeadId=@rHostelDepositHeadId AND DR.HostelId=@rHostelId)
	BEGIN TRANSACTION
  DECLARE @lNextNumber bigint 
 IF(@rId = 0)
 BEGIN   
 	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelDepositRefund', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sHostel.tHostelDepositRefund
		(
		Id,
		HostelDepositHeadId,
		StudentId,
		RefundAmount,
		RefundDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		HostelId,
		OrgGroupBatchId
		
		)
	VALUES
		(
		@lNextNumber,
		@rHostelDepositHeadId,
		@lStudentId,
		@rRefundAmount,
		@rRefundDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rHostelId,
		@rOrgGroupBatchId
		) 
		SELECT 1 AS Result   
	END	
	
ELSE
    BEGIN
	    UPDATE sHostel.tHostelDepositRefund
	    SET
		RefundAmount=@rRefundAmount,
		RefundDate=@rRefundDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate()	    
	    WHERE HostelDepositHeadId=@rHostelDepositHeadId 
	    AND HostelId=@rHostelId
	    AND Id = @rId  AND  OrgGroupBatchId=@rOrgGroupBatchId
	    SELECT @rStudentId AS Result
	 END  
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositRefundAmountGet]
	 
	@rHostelDepositHeadId int,
	@rStudentId bigint,
	@rHostelId int  ,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lStudentId bigint
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	

 SELECT @lStudentId= StudentId From  sStudent.vStudentAcademic Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId
 
 -- AMOUNT VALIDATIEON
 IF EXISTS (SELECT 1 FROM sHostel.tHostelDepositRefund DR WHERE StudentId= @lStudentId AND HostelDepositHeadId = @rHostelDepositHeadId AND DR.HostelId=@rHostelId AND DR.OrgGroupBatchId = @rOrgGroupBatchId )
  BEGIN
		SELECT ISNULL((SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
		--LEFT JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId
		WHERE D.HostelDepositHeadId = @rHostelDepositHeadId AND D.StudentId=@lStudentId AND D.HostelId=@rHostelId AND D.OrgGroupBatchId = @rOrgGroupBatchId)

		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sHostel.tHostelDepositAdjustment DA 
		 --LEFT JOIN sHostel.tHostelDepositRefund DR2 ON DR2.HostelDepositHeadId=DA.HostelDepositHeadId AND DR2.StudentId=DA.StudentId
		 WHERE DA.HostelDepositHeadId = @rHostelDepositHeadId AND  DA.OrgGroupBatchId = @rOrgGroupBatchId AND DA.StudentId=@lStudentId AND DA.HostelId=@rHostelId)
		 - (SELECT ISNULL(SUM(DR.RefundAmount),0) FROM sHostel.tHostelDepositRefund DR WHERE StudentId= @lStudentId   AND DR.OrgGroupBatchId = @rOrgGroupBatchId AND HostelDepositHeadId = @rHostelDepositHeadId AND HostelId=@rHostelId ),0) As RefundAmount
   END	
ELSE
BEGIN
		SELECT ISNULL((SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
		--LEFT JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId
		WHERE D.HostelDepositHeadId = @rHostelDepositHeadId AND D.StudentId=@lStudentId AND D.HostelId=@rHostelId  AND D.OrgGroupBatchId = @rOrgGroupBatchId)

		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sHostel.tHostelDepositAdjustment DA 
		 --LEFT JOIN sHostel.tHostelDepositRefund DR2 ON DR2.HostelDepositHeadId=DA.HostelDepositHeadId AND DR2.StudentId=DA.StudentId
		  WHERE DA.HostelDepositHeadId = @rHostelDepositHeadId AND DA.StudentId=@lStudentId  AND DA.OrgGroupBatchId = @rOrgGroupBatchId AND  DA.HostelId=@rHostelId),0) As RefundAmount
     END
	COMMIT TRANSACTION
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositRefundDelete]
	 
		@rStudentId bigint,
		@rHostelDepositHeadId int,
		@rHostelId int ,
	    @rOrgGroupBatchId int 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		

	
	BEGIN
		DELETE  sHostel.tHostelDepositRefund
		FROM sHostel.tHostelDepositRefund DR
		WHERE DR.StudentId=@rStudentId AND DR.HostelDepositHeadId=@rHostelDepositHeadId AND DR.OrgGroupBatchId=@rOrgGroupBatchId
		AND DR.HostelId=@rHostelId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelDepositRefundGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           @rFromRefundAmount decimal(12,2),
           @rToRefundAmount decimal(12,2),
           @rFromRefundDate date,
           @rToRefundDate date,
           @rHostelId int,
           @rCode nvarchar(20),
           @rId bigint,
           @rOrgGroupBatchId int
           
AS
SET NOCOUNT ON

BEGIN
SELECT 
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DR.HostelDepositHeadId,
		DR.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DR.RefundDate,
		DR.PayTypeId,
		DR.ChequeNo,
		DR.BankName,
		DR.Remark,
		DR.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
		ISNULL(DR.RefundAmount,0) AS RefundAmount,
		ISNULL(vSA.SUId,'')AS SUId,
		DR.Id
        
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DR.HostelDepositHeadId
		
  WHERE  
		--vSA.BatchId = @rBatchId 
		((DR.Id=@rId OR @rId=0))
		AND ((vSA.OrgId=@rOrgId OR @rOrgId=0))
		AND (DR.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DR.HostelId=@rHostelId)
		AND DR.OrgGroupBatchId=@rOrgGroupBatchId
		AND vSA.OrgGroupBatchId=@rOrgGroupBatchId
		GROUP BY
		DHM.Title,vSA.OrgId,DR.HostelDepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName ,vSA.SUId,DR.Id
		Order By DR.RefundDate     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventAssignAdd]
			@rId int
	       ,@rHostelEventScheduleId int
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsObsolete bit
           ,@rOrgId int
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
If(@rIsObsolete=1)
BEGIN

	Delete from sHostel.tHostelEventAssign where HostelEventScheduleId=@rHostelEventScheduleId AND SourceTypeId=@rSourceTypeId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN      
	If Exists(select Id from sHostel.tHostelEventAssign where HostelEventScheduleId=@rHostelEventScheduleId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			DECLARE @lNextNumber BIGINT
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHostel.tHostelEventAssign', 0, 1, 1,@outNextNumber = @lNextNumber output
			
			INSERT INTO sHostel.tHostelEventAssign
			(
				Id
			   ,HostelEventScheduleId
			   ,SourceTypeId
			   ,SourceId
			)
			VALUES
			(	@lNextNumber
			   ,@rHostelEventScheduleId
			   ,@rSourceTypeId
			   ,@rSourceId
			)		
			SELECT @lNextNumber AS Result
	END
END 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventAssignGet]

	 @rHostelEventScheduleId int,
	 @rOrgGroupBatchId int,
	 @rHostelId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
    SELECT 
			RM.Id  as SourceId,
			RM.Title as RoomTitle,
			2031 as SourceTypeId,
			CASE WHEN EA.SourceId IS NULL OR EA.HostelEventScheduleId!=@rHostelEventScheduleId THEN 0 ELSE 1 END AS IsObsolete
    FROM 
			sHostel.tRoomMaster RM
			LEFT JOIN sHostel.tHostelEventAssign EA ON EA.SourceId=RM.Id AND EA.SourceTypeId=2031
			AND EA.HostelEventScheduleId=@rHostelEventScheduleId
	WHERE
		    RM.HostelId=@rHostelId
		
UNION

	SELECT 
			RM.Id  as SourceId,
			RM.Title as RoomTitle,
			2031 as SourceTypeId,
			CASE WHEN EA.SourceId IS NULL OR EA.HostelEventScheduleId!=@rHostelEventScheduleId THEN 0 ELSE 1 END AS IsObsolete
    FROM 
			sHostel.tRoomMaster RM
			LEFT JOIN sHostel.tHostelEventAssign EA ON EA.SourceId=RM.Id AND EA.SourceTypeId=2031
			AND EA.HostelEventScheduleId=@rHostelEventScheduleId
	WHERE
		    RM.HostelId=@rHostelId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventAssignImport]
			 
    @rHostelEventScheduleId int
   ,@rSourceTypeId smallint
   ,@rSourceId bigint,
    @rOrgId smallint
   
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	  DECLARE @lNextNumber BIGINT
	  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHostel.tHostelEventAssign', 0, 1, 1,@outNextNumber = @lNextNumber output
	  Insert into sHostel.tHostelEventAssign 
	  (
		Id,
		HostelEventScheduleId,
		SourceTypeId,
		SourceId
	  )
	  Values
	  (
		@lNextNumber,
		@rHostelEventScheduleId,
		@rSourceTypeId,
		@rSourceId
	  )
	  Select 1 as result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventAttendanceAdd]

	@rHostelEventAttendanceXml [nvarchar](max),
	@rHostelEventScheduleId int,
	@rSourceTypeId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rHostelEventAttendanceXml
BEGIN
	
	 BEGIN TRY
	 BEGIN TRANSACTION
	
	 DELETE EA FROM sHostel.tHostelEventAttendance EA 
	 INNER JOIN 
	 (SELECT SourceId FROM OPENXML(@loDoc, '/Table/HostelEventAttendance', 1)
	 WITH(SourceId bigint))A 
	 ON EA.SourceId = A.SourceId 
	 AND EA.SourceTypeId=@rSourceTypeId 
	 AND HostelEventScheduleId=@rHostelEventScheduleId
	
	 --DELETE FROM sActivity.tEventAttendance WHERE EventScheduleId=@rEventScheduleId AND SourceTypeId = @rSourceTypeId
	
	 INSERT INTO sHostel.tHostelEventAttendance
		(
			HostelEventScheduleId,
			SourceTypeId,
			SourceId,
			IsSelfPresent,
			IsFatherPresent,
			IsMotherPresent,
			IsGuardianPresent
			)
		SELECT
			@rHostelEventScheduleId,
			@rSourceTypeId,
			SourceId,
			IsSelfPresent,
			IsFatherPresent,
			IsMotherPresent,
			IsGuardianPresent
		FROM OPENXML (@loDoc, '/Table/HostelEventAttendance', 1)
		WITH ( 
				SourceId bigint,
				IsSelfPresent bit,
				IsFatherPresent bit,
				IsMotherPresent bit,
				IsGuardianPresent bit
			  )
			  
	   SELECT 1 AS Result
	   EXEC sp_xml_removedocument @loDoc
	   
	   COMMIT TRANSACTION
		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventAttendanceGet]
	 
	 
	 @rHostelEventScheduleId int,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rOrgId smallint,
	 @rBatchId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		-- For Student Deatils
		IF(@rDivisionId != 0)
		BEGIN 
			SELECT
				vSA.AcademicId AS SourceId,
				vSA.Code,
				vSA.RollNo,
				vSA.Name,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				CONVERT (bit ,CASE WHEN EAT.SourceId IS NULL OR EAT.HostelEventScheduleId!=@rHostelEventScheduleId THEN 0 ELSE 1 END) AS IsObsolete,
				vSA.BatchId
			FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sHostel.tHostelEventAssign EA 
					ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 AND EA.HostelEventScheduleId=@rHostelEventScheduleId
				LEFT JOIN sHostel.tHostelEventAttendance EAT 
					ON EAT.HostelEventScheduleId = EA.HostelEventScheduleId AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
			WHERE
				vSA.OrgId=@rOrgId AND vSA.DivisionId = @rDivisionId
				AND vSA.BatchId = @rBatchId
			ORDER BY vSA.RollNo	
		END
		
		-- For Employee Deatils
		IF(@rDepartmentId != 0)
		BEGIN 
			SELECT
				vECD.EmployeeId AS SourceId,
				vECD.Code,
				vECD.EmployeeName AS Name,
				ISNULL(EAT.IsSelfPresent,0) AS IsSelfPresent,
				ISNULL(EAT.IsFatherPresent,0) AS IsFatherPresent,
				ISNULL(EAT.IsMotherPresent,0) AS IsMotherPresent,
				ISNULL(EAT.IsGuardianPresent,0) AS IsGuardianPresent,
				CONVERT (bit ,CASE WHEN EAT.SourceId IS NULL OR EAT.HostelEventScheduleId!=@rHostelEventScheduleId THEN 0 ELSE 1 END) AS IsObsolete
			FROM 
				sHrm.vEmployeeCommonDetail vECD
				INNER JOIN sHostel.tHostelEventAssign EA 
					ON EA.SourceId=vECD.OrganizationDepartmentId AND EA.SourceTypeId=2004 AND EA.HostelEventScheduleId=@rHostelEventScheduleId
				LEFT JOIN sHostel.tHostelEventAttendance EAT 
					ON EAT.HostelEventScheduleId = EA.HostelEventScheduleId AND EAT.SourceId = vECD.EmployeeId AND EAT.SourceTypeId = 95
			WHERE
				vECD.OrgId=@rOrgId AND vECD.OrganizationDepartmentId = @rDepartmentId
			ORDER BY vECD.Code	
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventFeedbackUpdate]
	 
	    @rHostelEventScheduleId int=0,
	    @rSourceTypeId int=0,
	    @rSourceId bigint,
		@rIsSelfPresent bit,
		@rIsFatherPresent bit,
		@rIsMotherPresent bit,
		@rIsGuardianPresent bit,
		@rSchoolFeedback nvarchar(500),
		@rParentFeedback nvarchar(500),
		@rSchoolAction nvarchar(500),
		@rParentAction nvarchar(500),
		@rIsTrackForReview bit
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	

 BEGIN 
	IF EXISTS(SELECT SourceId FROM sHostel.tHostelEventAttendance WHERE HostelEventScheduleId = @rHostelEventScheduleId AND SourceId=@rSourceId)
	BEGIN
	UPDATE  sHostel.tHostelEventAttendance
	    SET	
	        IsSelfPresent= @rIsSelfPresent,
		    IsFatherPresent=@rIsFatherPresent,
		    IsMotherPresent=@rIsMotherPresent,
		    IsGuardianPresent=@rIsGuardianPresent,		
			SchoolFeedback=@rSchoolFeedback,
			ParentFeedback=@rParentFeedback,
			SchoolAction=@rSchoolAction,
			ParentAction=@rParentAction,
			IsTrackForReview=@rIsTrackForReview
			
			
	      
	     -- SELECT @lNextNumber AS Result
	      WHERE HostelEventScheduleId = @rHostelEventScheduleId AND SourceId=@rSourceId
	     -- SELECT @lNextNumber AS Result
	     SELECT 2 AS Result
	END
	
	ELSE
	BEGIN
	INSERT INTO sHostel.tHostelEventAttendance
		(
		HostelEventScheduleId,
		SourceTypeId,
		SourceId,
		IsSelfPresent,
		IsFatherPresent,
		IsMotherPresent,
		IsGuardianPresent,
		SchoolFeedback,
		ParentFeedback,
		SchoolAction,
		ParentAction,
		IsTrackForReview		
		)
	VALUES
		(
		 @rHostelEventScheduleId,
		 @rSourceTypeId,		 
		 @rSourceId,
		 @rIsSelfPresent,
		 @rIsFatherPresent,
		 @rIsMotherPresent,
		 @rIsGuardianPresent,
		 @rSchoolFeedback,
		 @rParentFeedback,
		 @rSchoolAction,
		 @rParentAction,
		 @rIsTrackForReview
		)
		    SELECT 1 AS Result
	
	END
	    
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventImportAdd]
	 
	  @rOrgGroupBatchId int,
	  @rOrgId smallint,
	  @rInsertBatchid int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lNextNumber bigint,@lCount int
	DECLARE @Title nvarchar(100)
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHostel.tHostelEventSchedule', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	Set @lCount =(select  count(Id) from sHostel.tHostelEventSchedule where OrgGroupBatchId=@rOrgGroupBatchId  ANd Title not  in (Select  Title from sHostel.tHostelEventSchedule where OrgGroupBatchId=@rInsertBatchid))
 
	if exists(select  Title from sHostel.tHostelEventSchedule where OrgGroupBatchId=@rOrgGroupBatchId  ANd Title   in (Select  Title from sHostel.tHostelEventSchedule where OrgGroupBatchId=@rInsertBatchid))
	BEGIN
		return
		 
	END
	if NOT exists(select  Title from sHostel.tHostelEventSchedule where OrgGroupBatchId=@rOrgGroupBatchid )
	BEGIn
		Select 101 As result
		return 
	END
	Insert into sHostel.tHostelEventSchedule
	(
		    Id,
			Title,
			FromDate,
			ToDate,
			Remark,
			IsCommonForAll,
			IsHoliday,
			IsEnrollment,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupBatchId,
			HostelEventTypeId
	)
	
	Select
	 @lNextNumber + ROW_NUMBER() OVER(ORDER BY CASE WHEN Id < 0  THEN Id END DESC,CASE WHEN Id > 0 THEN Id END ASC) AS Id, 
	Title,FromDate,ToDate,Remark,IsCommonForAll,IsHoliday,IsEnrollment,CreatedUserId,CreatedDateTime,@rInsertBatchid,HostelEventTypeId from sHostel.tHostelEventSchedule
	Where OrgGroupBatchId=@rOrgGroupBatchId  
	
	
	SET @lNextNumber  = @lCount + @lNextNumber 
	 EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHostel.tHostelEventSchedule', @rCurrentNumber = @lNextNumber 
	 
	 
	 	Select 1 AS Result
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventScheduleAdd]
	 
        @rId int,
		@rTitle nvarchar(100),
		@rFromDate date,
		@rToDate date,
		@rRemark nvarchar(200),
		@rIsCommonForAll bit,
		@rIsHoliday bit,
		@rIsEnrollment bit,
		@rCreatedUserId bigint,
		@rOrgGroupBatchId int,
		@rOrgId int,
		@rHostelEventTypeId int,
		@rHostelId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sHostel.tHostelEventSchedule where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND HostelId = @rHostelId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sHostel.tHostelEventSchedule where Title=@rTitle AND OrgGroupBatchId=@rOrgGroupBatchId AND HostelId = @rHostelId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHostel.tHostelEventSchedule', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tHostelEventSchedule
		(
			Id,
			Title,
			FromDate,
			ToDate,
			Remark,
			IsCommonForAll,
			IsHoliday,
			IsEnrollment,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupBatchId,
			HostelEventTypeId,
			HostelId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rFromDate,
			@rToDate,
			@rRemark,
			@rIsCommonForAll,
			@rIsHoliday,
			@rIsEnrollment,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupBatchId,
			@rHostelEventTypeId,
			@rHostelId
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tHostelEventSchedule
	    SET
			Title=@rTitle,
			FromDate=@rFromDate,
			ToDate=@rToDate,
			Remark=@rRemark,
			IsCommonForAll=@rIsCommonForAll,
			IsHoliday=@rIsHoliday,
			IsEnrollment=@rIsEnrollment,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			HostelEventTypeId=@rHostelEventTypeId,
			HostelId = @rHostelId
	      
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventScheduleDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
		    Delete from sHostel.tHostelEventAttendance where HostelEventScheduleId=@rId
			Delete from sHostel.tHostelEventAssign where HostelEventScheduleId=@rId
			Delete from sHostel.tHostelEventSchedule where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventScheduleGet]

	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId int,
	 @rIsSearch bit = 1,
	 @rHostelEventTypeId int = 0,
	 @rSourceId bigint = 0,
	 @rSourceTypeId smallint = 0,
	 @rHostelId int =0
	 --@rSyncedEventScheduleId int = 0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	IF @rIsSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT 

			ES.Id as HostelEventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ES.OrgGroupBatchId,
			ISNULL(ES.HostelEventTypeId,0) AS HostelEventTypeId,
			ISNULL(EM.Title,'') AS HostelEventType,
			EM.HighlightColor,
			EM.Title AS HostelEventTypeName,
			ES.OrgGroupBatchId
		FROM 
			sHostel.tHostelEventSchedule ES
			INNER JOIN sHostel.tHostelEventTypeMaster EM ON EM.Id = ES.HostelEventTypeId 
			INNER JOIN sSetup.tOrgGroupBatchMaster BM ON BM.Id = ES.OrgGroupBatchId 
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = BM.OrgGroupId
		WHERE 

		((ES.Id = @rId) OR (@rId = 0))
		 AND ((ES.Id IN(SELECT HostelEventScheduleId FROM sHostel.tHostelEventAssign WHERE SourceTypeId=2005 AND 
				SourceId=(SELECT DivisionId FROM sStudent.vStudentName V 
				          INNER JOIN sSetup.tBatchMaster B ON V.BatchId = B.Id  WHERE StudentId=@rSourceId 
					      AND OrgGroupId = @rOrgGroupId  AND B.OrgGroupBatchId=@rOrgGroupBatchId))))
		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ES.OrgGroupBatchId=@rOrgGroupBatchId
		AND (( ES.HostelEventTypeId = @rHostelEventTypeId) OR (@rHostelEventTypeId = 0))
		AND ES.HostelId = @rHostelId
		ORDER BY ES.FromDate DESC
	END
	ELSE IF(@rSourceTypeId=95)
	BEGIN
		SELECT 

			ES.Id as HostelEventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ES.OrgGroupBatchId,
			ISNULL(ES.HostelEventTypeId,0) AS HostelEventTypeId,
			ISNULL(EM.Title,'') AS HostelEventType,
			EM.HighlightColor,
			EM.Title AS HostelEventTypeName,
			ES.OrgGroupBatchId
		FROM 
			sHostel.tHostelEventSchedule ES
			INNER JOIN sHostel.tHostelEventTypeMaster EM ON EM.Id = ES.HostelEventTypeId 
			INNER JOIN sSetup.tOrgGroupBatchMaster BM ON BM.Id = ES.OrgGroupBatchId 
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = BM.OrgGroupId
		WHERE 

		((ES.Id = @rId) OR (@rId = 0))
		AND (ES.Id IN(SELECT HostelEventScheduleId FROM sHostel.tHostelEventAssign WHERE SourceTypeId=2004 AND 
				SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId))) 
		AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ES.OrgGroupBatchId=@rOrgGroupBatchId
		AND (( ES.HostelEventTypeId = @rHostelEventTypeId) OR (@rHostelEventTypeId = 0))
		AND ES.HostelId = @rHostelId
		ORDER BY ES.FromDate DESC
	END
	ELSE
	BEGIN
		SELECT 

			ES.Id as HostelEventScheduleId,
			ES.Title,
			ES.FromDate,
			ES.ToDate,
			ES.Remark,
			ES.IsCommonForAll,
			ES.IsHoliday,
			ES.IsEnrollment,
			ES.OrgGroupBatchId,
			ISNULL(ES.HostelEventTypeId,0) AS HostelEventTypeId,
			ISNULL(EM.Title,'') AS HostelEventType,
			EM.HighlightColor,
			EM.Title AS HostelEventTypeName,
			ES.OrgGroupBatchId
		FROM 
			sHostel.tHostelEventSchedule ES
			INNER JOIN sHostel.tHostelEventTypeMaster EM ON EM.Id = ES.HostelEventTypeId 
			INNER JOIN sSetup.tOrgGroupBatchMaster BM ON BM.Id = ES.OrgGroupBatchId 
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = BM.OrgGroupId
		WHERE 
			((ES.Id = @rId) OR (@rId = 0))
			AND ((ES.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((ES.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((ES.FromDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ES.OrgGroupBatchId=@rOrgGroupBatchId
			AND (( ES.HostelEventTypeId = @rHostelEventTypeId) OR (@rHostelEventTypeId = 0))
			AND ES.HostelId = @rHostelId
			ORDER BY ES.FromDate DESC
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventTypeMasterAdd]
	 
		@rOrgGroupId int,
		@rHostelId int,
		@rId  int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rCreatedUserId bigint,
		@rCreatedDateTime date,
		@rIsObsolete bit,
		@rUpdateduserId bigint=0,
		@rUpdatedDateTime date='',
		@rHighlightColor nvarchar(100),
		@rOrderIndex int=0,
		@rHostelEventMainTypeId smallint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	--BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sHostel.tHostelEventTypeMaster where Title=@rTitle AND HostelId=@rHostelId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sActivity.tEventSchedule where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sHostel.tHostelEventTypeMaster where Title=@rTitle AND HostelId=@rHostelId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelEventTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tHostelEventTypeMaster
		(
		HostelId,
		Id,
		Code,
		Title,
		CreatedUserId,
		CreatedDateTime,
		IsObsolete,
		HighlightColor,
		UpdatedUserId,
		UpdatedDateTime,
		OrderIndex,
		HostelEventMainTypeId
		)
	VALUES
		(
		@rHostelId,
		@lNextNumber,
		@rCode,
		@rTitle,
		@rCreatedUserId,
		@rCreatedDateTime,
		@rIsObsolete,
		@rHighlightColor,
		@rCreatedUserId,
		@rCreatedDateTime,
		@rOrderIndex,
		@rHostelEventMainTypeId
		)
		SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tHostelEventTypeMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			HighlightColor=@rHighlightColor,
			OrderIndex=@rOrderIndex,
			HostelEventMainTypeId=@rHostelEventMainTypeId
        WHERE Id = @rId AND HostelId = @rHostelId
        SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventTypeMasterDelete]
	 
	 @rId int,
	 @rHostelId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		

		IF EXISTS (SELECT 1 FROM  sHostel.tHostelEventSchedule WHERE HostelEventTypeId=@rId)
		BEGIN
			SELECT -101 AS RESULT
		END
		ELSE 
		BEGIN
			DELETE FROM sHostel.tHostelEventTypeMaster WHERE Id=@rId AND HostelId=@rHostelId
			SELECT 1 AS Result
		END		
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelEventTypeMasterGet]

	 @rHostelId int,
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rHostelEventMainTypeId tinyint=0
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
SET @rTitle = sCommon.fSearchStringGet(@rTitle)
BEGIN 
	
	
	SELECT 
	
	EM.HostelId,
	EM.Id AS HostelEventTypeId,
	EM.Code AS Code,
	EM.Title AS Title,
	EM.IsObsolete,
	EM.HighlightColor,
	EM.OrderIndex,
	ISNULL(EM.HostelEventMainTypeId,'') AS HostelEventMainTypeId,
	ISNULL(EMTM.Title,'') AS HostelEventMainType
  FROM 
            sHostel.tHostelEventTypeMaster EM
            LEFT JOIN sHostel.tHostelEventMainTypeMaster EMTM ON EM.HostelEventMainTypeId = EMTM.Id
  WHERE 
   (EM.Id = @rId) OR (@rId=0)
   AND (EM.HostelId = @rHostelId) 
   AND ((EM.Title Like @rTitle )OR( ISNULL(@rTitle,'') = ''))
   AND ((EM.HostelEventMainTypeId = @rHostelEventMainTypeId) OR (@rHostelEventMainTypeId=0))
   ORDER BY
   EM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelExpenseSubTypeMasterAdd]
	 
	    @rId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rOrgGroupId int,
		@rCreatedUserId bigint,
		@rHostelId Int,
		@rExpenseTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select 1 from sHostel.tHostelExpenseSubTypeMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId AND ExpenseTypeId=@rExpenseTypeId )
		Begin
			select -102 as Result
			RETURN
		End
		If Exists(select 1 from sHostel.tHostelExpenseSubTypeMaster  where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId AND ExpenseTypeId=@rExpenseTypeId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
	If Exists(select 1 from sHostel.tHostelExpenseSubTypeMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId  AND HostelId=@rHostelId AND ExpenseTypeId=@rExpenseTypeId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sHostel.tHostelExpenseSubTypeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId AND HostelId=@rHostelId AND ExpenseTypeId=@rExpenseTypeId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelExpenseSubTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO sHostel.tHostelExpenseSubTypeMaster
		(
			HostelId, 
			Id, 
			Code, 
			Title, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			OrgGroupId,
			ExpenseTypeId
		)
	VALUES
		(   @rHostelId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId,
			@rExpenseTypeId
		)
		 SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tHostelExpenseSubTypeMaster
	    SET
			Title=@rTitle,
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
		ExpenseTypeId=@rExpenseTypeId
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelExpenseSubTypeMasterGet]
	 	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode varchar(20),
	 @rOrgGroupId int,
	 @rHostelId Int,
	 @rExpenseTypeId int
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			ETS.Id,
			ETS.Title,
		    ETS.Code,
			ETS.IsObsolete,
			ETS.ExpenseTypeId,
			ET.Title AS ExpenseType
      
  FROM 
          sHostel.tHostelExpenseSubTypeMaster  ETS INNER JOIN 
          sHostel.tHostelExpenseTypeMaster  ET ON  ET.Id=ETS.ExpenseTypeId
            
  WHERE   
           ((ETS.Id = @rId) OR (@rId = 0))
	       AND ((ETS.Title like @rTitle + '%') OR (ISNULL(@rTitle,'') = ''))
	       AND ((ETS.Code like @rCode +'%') OR (ISNULL(@rCode,'') = ''))
	       AND ETS.OrgGroupId=@rOrgGroupId
	       AND  ((ETS.ExpenseTypeId = @rExpenseTypeId) OR (@rExpenseTypeId = 0))
	       AND ETS.HostelId=@rHostelId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelExpenseTypeMasterAdd]
	 
	    @rId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rOrgGroupId int,
		@rCreatedUserId bigint,
		@rHostelId Int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select 1 from sHostel.tHostelExpenseTypeMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId )
		Begin
			select -102 as Result
			RETURN
		End
		If Exists(select 1 from sHostel.tHostelExpenseTypeMaster  where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND HostelId=@rHostelId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
	If Exists(select 1 from sHostel.tHostelExpenseTypeMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId  AND HostelId=@rHostelId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sHostel.tHostelExpenseTypeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId AND HostelId=@rHostelId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelExpenseTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tHostelExpenseTypeMaster
		(
			HostelId, 
			Id, 
			Code, 
			Title, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			OrgGroupId
		)
	VALUES
		(   @rHostelId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId
		)
		 SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tHostelExpenseTypeMaster
	    SET
			Title=@rTitle,
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelExpenseTypeMasterGet]
	 	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode varchar(20),
	 @rOrgGroupId int,
	 @rHostelId Int
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			Id,
			Title,
		    Code,
			IsObsolete
      
  FROM 
          sHostel.tHostelExpenseTypeMaster
            
  WHERE   
           ((Id = @rId) OR (@rId = 0))
	       AND ((Title like @rTitle+ '%') OR (ISNULL(@rTitle,'') = ''))
	       AND ((Code like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
	       AND OrgGroupId=@rOrgGroupId
	       AND HostelId=@rHostelId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelFeeUpdate] 
	@rClassId INT
	,@rFeeHeadId INT
	,@rCreatedUserId BIGINT
	,@rOrgId INT
	,@rOrgGroupId INT
	,@rBatchId INT
	,@rIsUpdate BIT = 0
	,@rOrgGroupBatchId INT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		CREATE TABLE #TempHostelFee (
			Id INT IDENTITY
			,AcademicId BIGINT
			,RoomId INT
			,FeeSetupId INT
			,Amount DECIMAL(12, 2)
			,ReceiptAmount DECIMAL(12, 2)
			)

		INSERT INTO #TempHostelFee
		SELECT A.AcademicId
			,AR.RoomId
			,FS.Id
			,RCM.RoomCharge
			,sFee.fStudentFeeSetupReceiptAmountGet(AcademicId, Fs.Id)
		FROM sHostel.tAssignRoom AR
		INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id
		INNER JOIN sHostel.tRoomCategoryMaster RCM ON RM.RoomCategoryId = RCM.Id
		INNER JOIN sStudent.vStudentAcademic A ON AR.SourceId = A.StudentId
			AND Ar.SourceTypeId = 2003
		INNER JOIN sFee.tFeeSetup FS ON A.ClassId = FS.ClassId
			AND A.AdmissionCategoryId = FS.AdmissionCategoryId
			AND FS.BatchId = A.BatchId
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
		WHERE FHM.Number = 1002
			AND FHM.OrgGroupId = @rOrgGroupId
			AND A.BatchId = @rBatchId
			AND FS.IsVariable = 1
			AND FS.IsOptional = 1
			AND AR.OrgGroupBatchId = @rOrgGroupBatchId

		--IF EXISTS(SELECT SOURCEID From sFee.tFeeAllocation FA INNER JOIN sStudent.tAcademic A ON A.Id = FA.SourceId 
		--WHERE A.BatchId = @rBatchId AND FA.SourceId NOT IN (SELECT AcademicId FROM #TempHostelFee RD WHERE ReceiptAmount > 0))
		--BEGIN
		--	DROP TABLE	#TempHostelFee
		--	SELECT -101 AS Result    
		--	RETURN
		--END
		DELETE FO
		FROM sFee.tFeeOptional FO
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FO.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
		WHERE FHM.Number = 1002
			AND FHM.OrgGroupId = @rOrgGroupId
			AND FS.BatchId = @rBatchId
			AND FS.IsVariable = 1
			AND FS.IsOptional = 1

		MERGE sFee.tFeeOptional FO
		USING #TempHostelFee RD
			ON FO.FeeSetupId = RD.FeeSetupId
				AND FO.SourceTypeId = 2001
				AND FO.SourceId = RD.AcademicId
				--WHEN MATCHED AND
				--  bi.Quantity + bo.Quantity = 0 THEN
				--  DELETE
				--WHEN MATCHED THEN
				--  UPDATE
				--  SET FA.VariableAmount = RD.Amount
		WHEN NOT MATCHED BY TARGET
			THEN
				INSERT (
					FeeSetupId
					,SourceTypeId
					,SourceId
					,BatchId
					)
				VALUES (
					RD.FeeSetupId
					,2001
					,RD.AcademicId
					,@rBatchId
					)
					-- WHEN NOT MATCHED  BY SOURCE   THEN
					--DELETE 
					;

		IF (@rIsUpdate = 1)
		BEGIN
			MERGE sFee.tFeeAllocation FA
			USING #TempHostelFee RD
				ON FA.FeeSetupId = RD.FeeSetupId
					AND FA.SourceTypeId = 2001
					AND FA.SourceId = RD.AcademicId
					--WHEN MATCHED AND
					--  bi.Quantity + bo.Quantity = 0 THEN
					--  DELETE
			WHEN MATCHED
				AND RD.ReceiptAmount <= RD.Amount
				THEN
					UPDATE
					SET FA.VariableAmount = RD.Amount
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
						SourceTypeId
						,SourceId
						,FeeSetupId
						,VariableAmount
						,DiscountAmount
						,AdditionalAmount
						,NotApplicableAmount
						,Remark
						,ReferenceTypeId
						,ReferenceSourceId
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
						)
					VALUES (
						2001
						,RD.AcademicId
						,RD.FeeSetupId
						,RD.Amount
						,0
						,0
						,0
						,''
						,0
						,0
						,@rCreatedUserId
						,sCommon.fGetDate()
						,@rCreatedUserId
						,sCommon.fGetDate()
						)
						--WHEN NOT MATCHED BY SOURCE THEN
						--DELETE
						;
		END
		ELSE
		BEGIN
			MERGE sFee.tFeeAllocation FA
			USING #TempHostelFee RD
				ON FA.FeeSetupId = RD.FeeSetupId
					AND FA.SourceTypeId = 2001
					AND FA.SourceId = RD.AcademicId
					--WHEN MATCHED AND
					--  bi.Quantity + bo.Quantity = 0 THEN
					--  DELETE
			WHEN NOT MATCHED BY TARGET
				THEN
					INSERT (
						SourceTypeId
						,SourceId
						,FeeSetupId
						,VariableAmount
						,DiscountAmount
						,AdditionalAmount
						,NotApplicableAmount
						,Remark
						,ReferenceTypeId
						,ReferenceSourceId
						,CreatedUserId
						,CreatedDateTime
						,UpdatedUserId
						,UpdatedDateTime
						)
					VALUES (
						2001
						,RD.AcademicId
						,RD.FeeSetupId
						,RD.Amount
						,0
						,0
						,0
						,''
						,0
						,0
						,@rCreatedUserId
						,sCommon.fGetDate()
						,@rCreatedUserId
						,sCommon.fGetDate()
						)
						--WHEN NOT MATCHED BY SOURCE THEN
						--DELETE
						;
		END

		DELETE FA
		FROM sFee.tFeeAllocation FA
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
		WHERE FHM.Number = 1002
			AND FHM.OrgGroupId = @rOrgGroupId
			AND FS.BatchId = @rBatchId
			AND FS.IsVariable = 1
			AND FS.IsOptional = 1
			AND FA.SourceId NOT IN (
				SELECT AcademicId
				FROM #TempHostelFee
				)

		-- For Fee Process Added By Foram on 2025-01-29
		UPDATE FAS
		SET FAS.VariableAmount = FA.VariableAmount, FAS.ToPayAmount = (FAS.FeeAmount + FA.VariableAmount + FAS.AdditionalAmount - FAS.DiscountAmount - FAS.NotApplicableAmount - FAS.PaidAmount)
		FROM sFee.tFeeAllocationStudent FAS
		INNER JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId = FAS.FeeSetupId AND FA.SourceTypeId = 2001 AND FA.SourceId = FAS.AcademicId
		INNER JOIN #TempHostelFee RD ON FA.FeeSetupId = RD.FeeSetupId AND FA.SourceTypeId = 2001 AND FA.SourceId = RD.AcademicId

		UPDATE FAS
		SET FAS.VariableAmount = 0, 
		FAS.AdditionalAmount = 0,
		FAS.DiscountAmount = 0,
		FAS.NotApplicableAmount = 0,
		FAS.ToPayAmount = (FAS.FeeAmount - FAS.PaidAmount)
		FROM 
		sFee.tFeeAllocationStudent FAS
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
		WHERE FHM.Number = 1002
			AND FHM.OrgGroupId = @rOrgGroupId
			AND FS.BatchId = @rBatchId
			AND FS.IsVariable = 1
			AND FS.IsOptional = 1
			AND FAS.AcademicId NOT IN (
				SELECT AcademicId
				FROM #TempHostelFee
				)
		-- For Fee Process Added By Foram on 2025-01-29

		DROP TABLE #TempHostelFee

		SELECT 1 AS Result

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelGetPassReasonMasterAdd]
	 @rHostelId int,	
	 @rId int, 
	 @rCode nvarchar(20), 
	 @rTitle nvarchar(100), 
	 @rIsObsolete bit, 
	 @rCreatedUserId bigint, 
	 @rUpdatedUserId bigint ,
	  @rOrgGroupId int      	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sHostel.tHostelGatePassReasonMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND HostelId = @rHostelId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sHostel.tHostelGatePassReasonMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND HostelId = @rHostelId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sHostel.tHostelGatePassReasonMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND HostelId = @rHostelId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sHostel.tHostelGatePassReasonMaster where Title=@rTitle  AND OrgGroupId=@rOrgGroupId AND HostelId = @rHostelId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelGatePassReasonMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tHostelGatePassReasonMaster
		(
			HostelId,
			 OrgGroupId,
			 Id,
			 Code,
			 Title,
			 IsObsolete,
			 CreatedUserId,
			 CreatedDateTime,
			 UpdatedUserId, 
			 UpdatedDateTime

		)
	VALUES
		(
			@rHostelId,
			 @rOrgGroupId ,
			 @lNextNumber, 
			 @rCode , 
			 @rTitle , 
			 @rIsObsolete , 
			 @rCreatedUserId , 
			 sCommon.fGetDate(),
			 @rUpdatedUserId  ,			  
			 sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tHostelGatePassReasonMaster
	    SET
			Title=@rTitle,
			Code=@rCode,
			IsObsolete=@rIsObsolete,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelGetPassReasonMasterGet]

	@rHostelId int,
	 @rId int,
	 @rOrgGroupId int ,     	
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rIsWildCardSearch bit
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF @rIsWildCardSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			HGRM.Id AS GetPassReasonId,
			HGRM.HostelId,			
			HGRM.Code	,	
			HGRM.Title,			
		    HGRM.OrgGroupId,
		    HGRM.CreatedUserId,
		    HGRM.CreatedDateTime,
		    HGRM.IsObsolete
		    
	FROM 
			sHostel.tHostelGatePassReasonMaster HGRM
	WHERE 
		HGRM.HostelId = @rHostelId
		AND(HGRM.OrgGroupId = @rOrgGroupId)
		AND	((HGRM.Id = @rId) OR (@rId = 0))
		AND ((HGRM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((HGRM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
			
	
		
		ORDER BY HGRM.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelMasterAdd]
	 
        @rId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(100),
		@rHostelTypeId int,
		@rNoOfRooms smallint,
		@rCreatedUserId bigint,
		@rIsObsolete bit,
		@rOrgGroupId smallint,
		@rReportOrgTitle  nvarchar(200) ,
		@rSmallAddress1 nvarchar(200),
		@rSmallAddress2 nvarchar(200)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		If Exists(select Id from sHostel.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sHostel.tHostelMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sHostel.tHostelMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tHostelMaster
		(
			Id,
			Title,
			Remark,
			HostelTypeId,
			NoOfRooms,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId ,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2
			
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rHostelTypeId,
			@rNoOfRooms,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rReportOrgTitle,
			@rSmallAddress1,
			@rSmallAddress2
		)
		
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2014
		   ,@lNextNumber
		   ,@rCreatedUserId
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tHostelMaster
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			HostelTypeId=@rHostelTypeId,
			NoOfRooms=@rNoOfRooms,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			ReportOrgTitle=@rReportOrgTitle ,
		    SmallAddress1=@rSmallAddress1 ,
		    SmallAddress2=@rSmallAddress2 
	      
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelMasterDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sHostel.tHostelWarden where HostelId=@rId
			Delete from sHostel.tHostelMaster where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rHostelTypeId int,
	 @rOrgGroupId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			HM.Id,
			HM.Title,
		    HM.Remark,
		    HM.HostelTypeId,
		    HTM.Title AS HostelType,
		    HM.NoOfRooms,	
			HM.IsObsolete,
			HM.ReportOrgTitle,
			HM.SmallAddress1,
			HM.SmallAddress2
			
      
  FROM 
            sHostel.tHostelMaster HM
            INNER JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
  WHERE   
           ((HM.Id = @rId) OR (@rId = 0))
	       AND ((HM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((HM.HostelTypeId=@rHostelTypeId) OR (@rHostelTypeId=0)) 
	       AND HM.OrgGroupId=@rOrgGroupId
	       Order by id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelModelGet]
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 HM.Id As HostelId,
		 Hm.Title AS HostelName,
		 HM.Title  As HostelType 
  FROM 
		   sHostel.tHostelMaster HM
		   INNER JOIN  sHostel.tHostelTypeMaster HTM ON HTM.Id = HM.HostelTypeId
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHostel].[pHostelSelfPermissionAdd]

	@rSourceId [nvarchar](max),
	@rHostelId int,
	@rSelfPermission int,
	@rOrgGroupBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 IF(@rSelfPermission=1)
	 BEGIN
	 UPDATE  sHostel.tHostelAdmission SET  IsSelfPermissionToGoOut=1 WHERE OrgGroupBatchId=@rOrgGroupBatchId AND Hosteld=@rHostelId  AND SourceTypeId=2003
	 AND SourceId  IN ( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rSourceId,',')) 
	 SELECT 11 AS RESULT 
	 END
	 ELSE
	 BEGIN 
	 UPDATE sHostel.tHostelAdmission  SET  IsSelfPermissionToGoOut=0 WHERE OrgGroupBatchId=@rOrgGroupBatchId AND Hosteld=@rHostelId  AND SourceTypeId=2003
	 AND SourceId  IN ( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rSourceId,',')) 
	 SELECT 1 AS RESULT
	 END
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelStudentGatePassAdd]
	 
		@rHostelId int,
        @rId int,
        @rStudentId bigint,
        @rWhithWhom nvarchar(100),
        @rApprovedBy nvarchar(100),
        @rReason nvarchar(100),
        @rOutDate date,
        @rOutTime time(7),
        @rInDate date,
        @rInTime time(7),
        @rCreatedUserId bigint,
        @rOrgId smallint
       
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


DECLARE @lStudentId bigint --change

BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 SELECT @lStudentId= StudentId From sStudent.tAcademic Where Id=@rStudentId--change

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHostel.tStudentGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tStudentGatePass
		(
			HostelId,
			Id,
			StudentId,
			WhithWhom,
			ApprovedBy,
			Reason,
			OutDate,
			OutTime,
			InDate,
			InTime,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
		@rHostelId,  
		@lNextNumber,	
        @rStudentId,
        @rWhithWhom, 
        @rApprovedBy, 
        @rReason, 
        @rOutDate,
        @rOutTime,
        @rInDate,
        @rInTime,
        @rCreatedUserId,
        sCommon.fGetDate()
		)
		    SELECT 1  AS Result,@lNextNumber
	END	 

ELSE
	 BEGIN
	-- SET @lNextNumber = @rId
	--SELECT @lStudentId= StudentId From sStudent.tAcademic Where Id=@rStudentId--change

	    UPDATE  sHostel.tStudentGatePass
	    SET
			HostelId=@rHostelId,
			StudentId=@rStudentId,
			WhithWhom=@rWhithWhom,
			ApprovedBy=@rApprovedBy,
			Reason=@rReason,
			OutDate=@rOutDate,
			OutTime=@rOutTime,
			InDate=@rInDate,
			InTime=@rInTime,
			CreatedUserId=@rCreatedUserId
			--CreatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelStudentGatePassBulkGet]
           @rOrgId int,    
           @rCode nvarchar(max),
           @rHostelId int,
           @rOrgGroupBatchId int,
           @rStrSuid nvarchar(max)='',
           @rRoomCategoryId int,
           @rBuildingId int,
           @rRoomId int,
           @rEntryModeStatusId smallint=0,
          @rBulkNumber nvarchar(20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 


	IF (@rBulkNumber = '-1')
	BEGIN
	  SELECT  
		vSA.OrgId,
		vSA.StudentId AS StudentId,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(vSA.SUId,'') AS SUId,
        VSA.AcademicId,
        RCM.Title AS RoomCategory,
        RM.Title As Room,
        --   '' as VisitorName ,--HSGP.VisitorName,
        ----CASE when HSGP.BulkNumber=0 THEN '' ELSE HSGP.BulkNumber END 
        --'' as BulkNumber , --  HSGP.BulkNumber,
        0 AS OrgGroupBatchId,
        0 as HostelStudentGatePassId
  FROM 		
			sStudent.vStudentAcademic vSA
			
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=VSA.StudentId AND AR.SourceTypeId=2003
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId			
			INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
			AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
		    LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
		    --LEFT JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId 
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		--AND (HSGP.BulkNumber=@rBulkNumber OR @rBulkNumber=-1)
		AND (RM.HostelId=@rHostelId)
		AND ((VSA.OrgGroupBatchId=@rOrgGroupBatchId))
		AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId))
		AND RM.IsObsolete=0
	    AND (BM.Id=@rBuildingId OR @rBuildingId=0)
	    AND (RM.Id=@rRoomId OR @rRoomId=0)
	    AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
	    AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
	    
		Order By VSA.RollNo
	END
	
	
	ELSE 
	BEGIN
	
	
    SELECT  
		vSA.OrgId,
		vSA.StudentId AS StudentId,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(vSA.SUId,'') AS SUId,
        VSA.AcademicId,
        RCM.Title AS RoomCategory,
        RMM.Title As Room,
        HSGP.VisitorName,
        HSGP.BulkNumber,
        IsNull(HSGP.Id,0) AS HostelStudentGatePassId,
        	HSGP.RelationshipId,		
			RM.Title AS Relationship,
			HSGP.Relation,
			HSGP.VisitorName,
			HSGP.VisitorMobile,
			HSGP.HostelGatePassReasonId,
			HGRM.Title AS HostelGetPassReason,
			HSGP.Remark,
			HSGP.OrgGroupBatchId,
			HSGP.GatePassDate,
			HSGP.EntryModeStatusId,
			HSGP.GatePassInDate,
			 CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
			  CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100) As GatePassInTime,
			  SM.Title AS EntryModeStatus
  FROM 		
			sStudent.vStudentAcademic vSA
			
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=VSA.StudentId AND AR.SourceTypeId=2003
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId			
			INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
			AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
		    LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
		   LEFT JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId  AND  ((HSGP.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		   LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId
		   LEFT JOIN sCommon.tRelationshipMaster RMM ON RMM.Id=HSGP.RelationshipId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (HSGP.BulkNumber=@rBulkNumber OR @rBulkNumber='-1')
		AND (RM.HostelId=@rHostelId)
		AND ((VSA.OrgGroupBatchId=@rOrgGroupBatchId))
		AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId))
		AND RM.IsObsolete=0
	    AND (BM.Id=@rBuildingId OR @rBuildingId=0)
	    AND (RM.Id=@rRoomId OR @rRoomId=0)
	    AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
	    AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
	    AND HSGP.BulkNumber IS not null
	    AND HSGP.EntryModeStatusId=581
	   -- AND vSA.StudentId in (select* from sHostel.tHostelStudentGatePass WHERe BulkNumber=@rBulkNumber )
		Order By VSA.RollNo
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelStudentGatePassGet]

	 @rId int,
	 @rStudentCode nvarchar(20),
	 @rHostelId int,
	 @rOutDate datetime,
	 @rInDate datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			SM.Code,
			--SM.FirstName+' '+SM.LastName AS StudentName,
			SM.Name AS StudentName,
			SG.WhithWhom,
			SG.ApprovedBy,
			SG.Reason,
			ISNULL(SG.OutDate,'') AS OutDate,
			ISNULL(SG.InDate,'') AS InDate,
			SG.Id,
			HM.Title AS HostelName,
			SM.Code,
			SG.StudentId,
			OutTime,
			InTime,
			ISNULL(SM.SUID,'') AS SUID
	FROM 
			sHostel.tStudentGatePass SG
			INNER JOIN sStudent.vStudentLastAcademic SM ON SM.StudentId=SG.StudentId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=SG.HostelId
	WHERE 
			((SG.Id = @rId) OR (@rId = 0))
		AND (SM.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
		AND ((SG.HostelId = @rHostelId) OR (@rHostelId = 0))
		--AND ((SG.OutDate=@rOutDate) OR (ISNULL(@rOutDate,'')=''))
		--AND ((SG.InDate=@rInDate) OR (ISNULL(@rInDate,'')=''))
		AND (SG.OutDate>=@rOutDate OR ISNULL(@rOutDate,'')='')
		AND (SG.OutDate<=@rInDate OR ISNULL(@rInDate,'')='')
		Order by SG.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelStudentGatePassNewAdd]
	
	@rOrgGroupId int,
	@rId int,
	@rStudentId bigint,
	@rRelationshipId tinyint,
	@rRelation nvarchar(50),
	@rVisitorName nvarchar(100),
	@rVisitorMobile nvarchar(50),
	@rHostelGatePassReasonId int,
	@rRemark nvarchar(200),
	@rVisitorPhoto varbinary(max)=0,
	@rGatePassDate date,
	@rGatePassTime datetime,
	@rEntryModeStatusId smallint,
	@rHostelId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint	,
	@rGatePassInDate date,
	@rGatePassInTime datetime,
	@rBulkNumber nvarchar=''			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN	
		DECLARE @lMaxId varchar(max)=''
		
		SELECT @lMaxId = Max(Id) from sHostel.tHostelStudentGatePass Where StudentId = @rStudentId 
		
		declare @lEntryModeStatusId varchar(max)=''
		Select @lEntryModeStatusId=EntryModeStatusId from sHostel.tHostelStudentGatePass Where Id = @lMaxId
			
		
		IF(@lEntryModeStatusId = 581 AND @rId = 0)
		BEGIN
			SELECT -101
			Return
		END		
	END
BEGIN TRY
BEGIN TRANSACTION	

	
IF(@rId = 0)
	BEGIN	
	DECLARE @lNextNumber INT,@lEntryMode int     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelStudentGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sHostel.tHostelStudentGatePass
		(
			Id,
			StudentId,
			RelationshipId,
			Relation,
			VisitorName,
			VisitorMobile,
			HostelGatePassReasonId,
			Remark,
			VisitorPhoto,
			GatePassDate,
			GatePassTime,
			EntryModeStatusId,
			HostelId,
			OrgGroupBatchId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			GatePassInDate,
			GatePassInTime,
			BulkNumber
		)
	VALUES
		(
			@lNextNumber,
			@rStudentId,
			@rRelationshipId,
			@rRelation,
			@rVisitorName,
			@rVisitorMobile,
			@rHostelGatePassReasonId,
			@rRemark,
			@rVisitorPhoto,
			@rGatePassDate,
			@rGatePassTime,
			@rEntryModeStatusId,
			@rHostelId,
			@rOrgGroupBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),	
			@rCreatedUserId,
			sCommon.fGetDate()	,
			@rGatePassInDate,
			NULL	,
			@rBulkNumber	
		)
		             
END	 
ELSE	 
BEGIN
	SET @lNextNumber = @rId
	UPDATE  sHostel.tHostelStudentGatePass
	SET
	
		RelationshipId=@rRelationshipId,
			Relation= @rRelation,
			VisitorName=@rVisitorName,
			VisitorMobile=@rVisitorMobile,
			HostelGatePassReasonId=@rHostelGatePassReasonId,
			Remark= @rRemark,
			VisitorPhoto=@rVisitorPhoto ,
			GatePassDate=@rGatePassDate ,
			GatePassTime=@rGatePassTime,
			EntryModeStatusId=@rEntryModeStatusId,
			GatePassInDate=@rGatePassInDate ,
			GatePassInTime=@rGatePassInTime
	
	WHERE Id = @rId 	   
END  
	
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelStudentGatePassNewBulkAdd]
	
	@rOrgGroupId int,
	@rId int,
	@rStudentId bigint,
	@rRelationshipId int,
	@rRelation nvarchar(50),
	@rVisitorName nvarchar(100),
	@rVisitorMobile nvarchar(50),
	@rHostelGatePassReasonId int,
	@rRemark nvarchar(200),
	@rVisitorPhoto varbinary(max)=null,
	@rGatePassDate date,
	@rGatePassTime datetime,
	@rEntryModeStatusId smallint,
	@rHostelId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint	,
	@rGatePassInDate date,
	@rGatePassInTime datetime,
	@rBulkNumber nvarchar(20)			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	--BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber INT,@lEntryMode smallint     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelStudentGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 
	INSERT INTO sHostel.tHostelStudentGatePass
		(
			Id,
			StudentId,
			RelationshipId,
			Relation,
			VisitorName,
			VisitorMobile,
			HostelGatePassReasonId,
			Remark,
			VisitorPhoto,
			GatePassDate,
			GatePassTime,
			EntryModeStatusId,
			HostelId,
			OrgGroupBatchId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			GatePassInDate,
			GatePassInTime,
			BulkNumber
		)
	VALUES
		(
			@lNextNumber,
			@rStudentId,
			@rRelationshipId,
			@rRelation,
			@rVisitorName,
			@rVisitorMobile,
			@rHostelGatePassReasonId,
			@rRemark,
			@rVisitorPhoto,
			@rGatePassDate,
			@rGatePassTime,
			@rEntryModeStatusId,
			@rHostelId,
			@rOrgGroupBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),	
			@rCreatedUserId,
			sCommon.fGetDate()	,
			@rGatePassInDate,
			@rGatePassInTime	,
			@rBulkNumber	
		)
		   SELECT @lNextNumber AS Result          
END	 
	 ELSE
BEGIN
	if exists (select 1 from sHostel.tHostelStudentGatePass where Id=@rId)
	BEGIN
		 Select @lEntryMode=EntryModeStatusId from sHostel.tHostelStudentGatePass Where Id=@rId
		 if(@lEntryMode=581)
		 BEGIN
		 
			UPDATE sHostel.tHostelStudentGatePass set EntryModeStatusId = @rEntryModeStatusId,
			GatePassInDate=@rGatePassInDate ,
			GatePassInTime=@rGatePassInTime
			where Id=@rId
			 
		 END
		 
		  if(@lEntryMode=582)
		 BEGIN
		 
			UPDATE sHostel.tHostelStudentGatePass set EntryModeStatusId = @rEntryModeStatusId,
			GatePassInDate=@rGatePassInDate ,
			GatePassInTime=@rGatePassInTime
			where Id=@rId
			
		 END
		SELECT -1 AS Result 
	END   
END  
	
	SELECT @lNextNumber AS Result
	
	--COMMIT TRANSACTION
	
	--END TRY
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelStudentGatePassNewGet]
          
           @rId int,
           @rOrgId int=0,
           @rHostelGatePassReasonId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rOrgGroupBatchId int=0,
           @rRoomId int =0,
           @rHostelId int =0
AS
SET NOCOUNT ON
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lConfigValue nvarchar(50)
DECLARE @lIsDisplayImageHeader bit = 0
BEGIN

--Select @rHostelId
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 232 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
			BEGIN
			SET @lIsOnPrePrinted = 0
			SET @lIsDisplayImageHeader = 0
			END
		ELSE IF (@lConfigValue = 'Image')
			BEGIN
			SET @lIsOnPrePrinted = 0
			SET @lIsDisplayImageHeader = 1
			END
		ELSE IF (@lConfigValue = 'Blank')
			BEGIN
			SET @lIsOnPrePrinted = 1
			END
	

			SELECT
				HSGP.Id, 
				HSGP.Id AS HostelStudentGatePassId,
				vSA.Code,
				--vSA.FirstName+' '+vSA.LastName AS Name,
				VSA.Name,
				VSA.ClassName+' - '+VSA.DivisionName AS Class,
				HSGP.StudentId,
				HSGP.RelationshipId,		
				RM.Title AS Relationship,
				HSGP.Relation,
				HSGP.VisitorName,
				HSGP.VisitorMobile,
				HSGP.HostelGatePassReasonId,
				HGRM.Title AS HostelGetPassReason,
				HSGP.Remark,
				--HSGP.VisitorPhoto	,


				--CASE  WHEN @rIsPrintView=1 THEN HSGP.VisitorPhoto		
				--ELSE ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END AS VisitorPhoto,
				--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
				HSGP.GatePassDate,
				HSGP.GatePassInDate,
				(CASE  WHEN @rIsPrintView=1 THEN 
				ISNULL(HSGP.VisitorPhoto,0x)
				ELSE ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0x)) END) AS VisitorPhoto,
				CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
				ISNULL(CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100), '12:00AM') As GatePassInTime,

				--ISNULL(HSGP.GatePassTime,'') As GatePassTime,
				HSGP.EntryModeStatusId,
				HSGP.HostelId,
				SM.Title AS EntryModeStatus,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				(CASE  WHEN @rIsPrintView=1 THEN 
				ISNULL(SI.StudentPhoto,0x)		
				ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0x)) END) AS StudentPhoto,
				--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				ISNULL(U.DisplayTitle,'') AS UserName,
				HSGP.OrgGroupBatchId,
				vSA.SUId,
				HM.Title As HostelName,
				HM.ReportOrgTitle AS ReportOrgTitle,
				HM.SmallAddress1 AS SmallAddress1,
				HM.SmallAddress2 AS SmallAddress2,
				@lIsOnPrePrinted AS IsOnPrePrinted,			
				ISNULL(HRM.Id,0) AS RoomId,
				ISNULL(HRM.Title,'') AS RoomTitle,
				@lIsDisplayImageHeader AS IsDisplayImageHeader,
				(CASE @lIsDisplayImageHeader WHEN 1 THEN
				OI.CertificateHeaderA4
				ELSE NULL END ) AS CertificateHeaderA4

		FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
				LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId
				LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=HSGP.RelationshipId
				LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
				LEFT JOIN sSecurity.tUser U	ON U.Id=HSGP.CreatedUserId
				LEFT JOIN  sHostel.tAssignRoom AR ON AR.SourceId=HSGP.StudentId AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  AND (AR.SourceTypeId=2003)--Added  (AR.SourceTypeId=2003) for mantis - 0033745 
				LEFT JOIN sHostel.tRoomMaster HRM ON HRM.Id = AR.RoomId
				INNER JOIN sHostel.tHostelMaster HM ON HM.Id = HSGP.HostelId
				LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = vSA.OrgId		--  MantisId : 0033298
			
		WHERE 
				OM.OrgGroupId=@rOrgGroupId
				AND HSGP.HostelId = @rHostelId
				AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId) 
				--if student remove from Assign room then it is not display in HostelStudentGatePass
				--AND (AR.SourceId=HSGP.StudentId) 
				AND (HSGP.OrgGroupBatchId=@rOrgGroupBatchId) 
				AND ((HSGP.Id=@rId) OR (@rId=0))
				AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((HSGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
				AND ((HSGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
				AND ((HSGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
				AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
				AND ((HSGP.HostelGatePassReasonId=@rHostelGatePassReasonId) OR (@rHostelGatePassReasonId=0))
				AND ((HRM.Id = @rRoomId) OR (@rRoomId = 0))
				
				ORDER BY HSGP.GatePassDate,HSGP.GatePassTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE  [sHostel].[pHostelStudentGatePassNewIntimeUpdate]

		@rEntryModeStatusId smallint,
		@rId int,
		@rGatePassInDate date,
		@rGatePassInTime datetime,
		@rOrgGroupBatchId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION
			BEGIN
				UPDATE sHostel.tHostelStudentGatePass
				SET EntryModeStatusId=@rEntryModeStatusId,
					GatePassInDate=@rGatePassInDate,
					GatePassInTime=@rGatePassInTime
				WHERE Id = @rId  AND (OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
				select 1 AS Result
			END
			--SELECT
			--Id As VisitorId,
			--VisitorName,
			--NoOfVisitor,
			--PurposeOfVisit,
			--WhomToMeet As WhomToMeetId,
			--WhomToMeetName,
			--ISNULL(OutTime,'') AS OutTime,
			--ISNULL(InTime,'') AS InTime,
			--ISNULL(VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			--CreatedDateTime

			-- From sFrontOffice.tVisitorLog

		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelStudentSearchGet]
	 
	 @rOrgId int,
	 @rHostelId int,
	 @rRoomId int,
	 @rStudentId bigint,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int,
	 @rSUId nvarchar(max)='',
	 @rDepartmentId  int,
	 @rOrgGroupId smallint=0,
	 @rBuildingId int=0,
	 @rSurName nvarchar(100)='',
	 @rIsSelfPermissionToGoOut int=0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 		
			SELECT 		
			O.DisplayTitle AS Organization,
			HM.Title AS Hostel,
			RM.Title AS Room,
			SD.Code AS StudentCode,
			SD.Name AS StudentName,
			SD.ClassName + ' - ' + SD.DivisionName AS Class,
			SD.DivisionName AS Division,
			SD.StudentId,			
			SD.ClassId,
			SD.DivisionId,
			HM.Id AS HostelId,
			RM.Id AS RoomId,
			O.Id AS OrgId,
			ISNULL(AR.BedNumber,'') AS BedNumber ,
			ISnull(SD.SUID,'') AS SUID,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISnull(SD.DepartmentName,'') As DepartmentName,
			[sHostel].[fAssignRoomAssetGet](HM.Id,RM.Id,SD.StudentId) AS AssetNumber,
			ISNULL(SC.PresentCity,'') AS City,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.ParentEmail,'') AS EMail,
			ISNULL(HA.IsSelfPermissionToGoOut,0) AS IsSelfPermissionToGoOut,
			SD.BatchId
			
			FROM sHostel.tAssignRoom AR 
			INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
			INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SD.BatchId AND BM.IsActive = 1
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
			LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
			LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
			INNER JOIN  sHostel.tHostelAdmission HA On HA.SourceId=AR.SourceId AND AR.SourceTypeId = 2003 AND HA.OrgGroupBatchId=@rOrgGroupBatchId
			Where 
			AR.SourceTypeId = 2003
			AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
			AND (AR.OrgGroupBatchId=@rOrgGroupBatchId)
			AND ((SD.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((HM.Id = @rHostelId) OR (ISNULL(@rHostelId,0) = 0))
			AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
			AND ((SD.StudentId = @rStudentId) OR (ISNULL(@rStudentId,0) = 0))
			AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
			AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
			--AND ((SD.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
			AND ((SD.firstname like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
			AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
			--AND ((SD.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND HM.OrgGroupId=@rOrgGroupId
			AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
	        AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
	        AND ((SD.Lastname like @rSurName + '%') OR (ISNULL(@rSurName,'') = ''))
	        AND ((BM.Id=@rBuildingId )OR (@rBuildingId=0))
	        AND ((IsSelfPermissionToGoOut=@rIsSelfPermissionToGoOut) OR(ISnull(@rIsSelfPermissionToGoOut,0)=0))
            
			order by SD.ClassId,RM.Id 


--			 declare @quer varchar(max)=''
--SELECT @quer='SELECT 	O.DisplayTitle AS Organization,RM.Title AS Room,
--			SD.Code AS StudentCode,
--			SD.Name AS StudentName ,
--			HM.Title AS Hostel,
--			SD.ClassName  + SD.DivisionName AS Class,
--			SD.DivisionName AS Division,
--			SD.StudentId,
--			SD.ClassId,
--			SD.DivisionId,
--			HM.Id AS HostelId,
--			RM.Id AS RoomId,
--			O.Id AS OrgId,
--			ISNULL(AR.BedNumber,'''') AS BedNumber ,
--			ISnull(SD.SUID,'''') AS SUID,
--			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
--			ISnull(SD.DepartmentName,'''') As DepartmentName,
--			[sHostel].[fAssignRoomAssetGet](HM.Id,RM.Id,SD.StudentId) AS AssetNumber,
--			ISNULL(SC.PresentCity,'''') AS City,
--			ISNULL(SC.ParentContactNo,'''') AS ContactNo,
--			ISNULL(SC.ParentEmail,'''') AS EMail,
--			ISNULL(HA.IsSelfPermissionToGoOut,0) AS IsSelfPermissionToGoOut
--			FROM sHostel.tAssignRoom AR 
--			INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
--			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
--			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
--			INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
--      		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
--			LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
--			LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
--			INNER JOIN  sHostel.tHostelAdmission HA On HA.SourceId=AR.SourceId AND AR.SourceTypeId = 2003 AND HA.OrgGroupBatchId='+COnvert(varchar,@rOrgGroupBatchId)+'
--			Where 
--			AR.SourceTypeId =2003
--			AND HM.OrgGroupId='+convert(varchar,@rOrgGroupId)+'
--			AND SD.OrgGroupBatchId='+convert(varchar,@rOrgGroupBatchId)+'
--			AND AR.OrgGroupBatchId='+convert(varchar,@rOrgGroupBatchId)+'
--			AND ((O.Id = '+convert(varchar,@rOrgId) + ') OR ('+Convert(varchar,@rOrgId) +'=0)) 
--			AND ((HM.Id= '+convert(varchar,@rStudentId) + ') OR (' + Convert(varchar,ISNULL(@rStudentId,0)) + ' = 0))
--			AND ((RM.Id= '+convert(varchar,@rRoomId) + ') OR (' + Convert(varchar,ISNULL(@rRoomId,0)) + ' = 0))
--			AND ((SD.StudentId= '+convert(varchar,@rHostelId) + ') OR (' + Convert(varchar,ISNULL(@rHostelId,0)) + ' = 0))
--			AND ((SD.ClassId= '+convert(varchar,@rClassId) + ') OR (' + Convert(varchar,ISNULL(@rClassId,0))+ ' = 0))
--			AND ((SD.DivisionId= '+convert(varchar,@rDivisionId) + ' OR ' +Convert(varchar,ISNULL(@rDivisionId,0))+ ' = 0))
--			AND ((SD.DepartmentId= '+convert(varchar,@rDepartmentId) + ' OR ' + Convert(varchar,ISNULL(@rDepartmentId,0))+ ' = 0))
--			AND HM.OrgGroupId= '+convert(varchar,@rOrgGroupId) + '
--			AND ((BM.Id= '+convert(varchar,@rBuildingId) + ' OR ' + Convert(varchar,ISNULL(@rBuildingId,0)) + ' = 0))
--			AND ((IsSelfPermissionToGoOut= '+convert(varchar,@rIsSelfPermissionToGoOut) + ' OR ' + Convert(varchar,ISNULL(@rIsSelfPermissionToGoOut,0))+ ' = 0))
--			AND ((SD.Name like ''' + @rStudentName + ''') OR (''' + @rStudentName + ''' = ''''))
--			AND ((SD.Lastname like '''+@rSurName + ''')OR (''' + @rSurName + ''' = ''''))
--			AND ((ISNULL(SD.SUID,'''') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit('''+@rSUId+''','','')))    OR (''' +  @rSUId + ''' = '''')) 
--			AND ((ISNULL(SD.Code,'''') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit('''+@rStudentCode+''','','')))    OR (''' +  @rStudentCode + ''' = '''')) 
			 
			 
--			order by SD.ClassId,RM.Id '
--		   			Exec   (@quer)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelSummaryDashBoardGet]
           @rHostelId int = 0,                      
           @rOrgGroupBatchId int = 0,
		   @rType int = 0,
		   @rDate date = '',
		   @rHostelAttendanceTypeId int = 0
AS
SET NOCOUNT ON
BEGIN
	IF(@rType = 1)
	BEGIN
		SELECT 		
		RM.Id,
		RM.Title,
		ISNULL(RM.StudentsPerRoom,0) AS StudentsPerRoom,
		ISNULL(COUNT(AR.SourceID),0) AS StudentsAllocated
	    
		FROM [sHostel].[tRoomMaster] RM			  			  
			  LEFT JOIN [sHostel].[tAssignRoom] AR ON AR.RoomId = RM.Id AND AR.OrgGroupBatchId=@rOrgGroupBatchId AND AR.SourceTypeId = 2003		  
	  
		WHERE 
			((RM.HostelId=@rHostelId) OR (@rHostelId=0))
			AND RM.IsObsolete=0			
			Group by RM.Id,RM.StudentsPerRoom,RM.Title
		END	
	ELSE IF(@rType = 2)
	BEGIN
		SELECT 
			(SELECT COUNT(AR.SourceId) FROM sHostel.tAssignRoom AR INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId WHERE AR.OrgGroupBatchId = @rOrgGroupBatchId AND RM.HostelId = @rHostelId AND AR.SourceTypeId = 2003) AS TotalStudents,
			SUM(CASE WHEN EntryModeStatusId = 581 AND OrgGroupBatchId = @rOrgGroupBatchId AND HostelId = @rHostelId then 1 ELSE 0 END) as OutCount,
			(SELECT COUNT(AR.SourceId) FROM sHostel.tAssignRoom AR INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId WHERE AR.OrgGroupBatchId = @rOrgGroupBatchId AND RM.HostelId = @rHostelId AND AR.SourceTypeId = 2003) - SUM(CASE WHEN EntryModeStatusId = 581 AND OrgGroupBatchId = @rOrgGroupBatchId AND HostelId = @rHostelId then 1 ELSE 0 END) as InCount
		FROM
			sHostel.tHostelStudentGatePass
		WHERE
			GatePassDate <=  @rDate AND HostelId = @rHostelId
	END
	ELSE IF(@rType = 3)
	BEGIN
		SELECT 
			(SELECT COUNT(AR.SourceId) FROM sHostel.tAssignRoom AR INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId WHERE AR.OrgGroupBatchId = @rOrgGroupBatchId AND RM.HostelId = @rHostelId AND AR.SourceTypeId = 2003) AS TotalStudents,
			COUNT(CASE WHEN IsPresent = 1 then 1 ELSE NULL END) as PresentCount,
			COUNT(CASE WHEN IsPresent = 0 then 1 ELSE NULL END) as AbsentCount,
			(SELECT COUNT(AR.SourceId) FROM sHostel.tAssignRoom AR INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId WHERE AR.OrgGroupBatchId = @rOrgGroupBatchId AND RM.HostelId = @rHostelId AND AR.SourceTypeId = 2003) - COUNT(StudentId) AS PendingCount
		FROM 
			sHostel.tAttendanceRegister
		WHERE 
			CAST(CreatedDateTime AS Date) = @rDate AND HostelId = @rHostelId AND OrgGroupBatchId = @rOrgGroupBatchId
			AND HostelAttendanceTypeId = @rHostelAttendanceTypeId 
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelWardenAdd]
	 
	        @rHostelId int
           ,@rEmployeeId bigint
           ,@rIsDeleted bit
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 --DECLARE @lNextNumber BIGINT
	 
If(@rIsDeleted=1)
BEGIN
	Delete from sHostel.tHostelWarden where HostelId=@rHostelId AND EmployeeId=@rEmployeeId
	Select @rEmployeeId as Result
END	
ELSE
BEGIN     
	
If NOT Exists(select top(1)* from sHostel.tHostelWarden where HostelId=@rHostelId AND EmployeeId=@rEmployeeId) AND @rIsDeleted = 0
BEGIN
--	If NOT Exists(select top(1)* from sFee.tChargeMaster where Title=@rTitle AND OrgId=@rOrgId AND Id=@rId)
--	BEGIN
--		select -101 as Result
--	END
--	ELSE
--	BEGIN
--	 SET @lNextNumber = @rId
--	    UPDATE  [sFee].[tChargeMaster]
--	    SET
--			  --Number=@rNumber
--	         --,Code=@rCode
--	         Title=@rTitle
--	         ,ChargeCategoryId=@rChargeCategoryId
--	         ,ChargeAmount=@rChargeAmount
--	         ,OrderIndex=@rOrderIndex
--             ,[IsObsolete] = @rIsObsolete                          
--             ,[UpdatedUserId] = @rCreatedUserId
--             ,[UpdatedDateTime] = sCommon.fGetDate()          
             
--	      WHERE Id = @rId 	 
--	      SELECT @lNextNumber AS Result
	
--		--COMMIT TRANSACTION  
--	 END  
--END
--ELSE
--BEGIN
--IF(@rId = 0)	
--BEGIN
--	EXECUTE sCommon.pTableRowIdGet 1, 'sAssessment.tGradeSetDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sHostel].[tHostelWarden] 
			   (
			    HostelId
			   ,EmployeeId
			    )
		 VALUES
			   (
				@rHostelId
			   ,@rEmployeeId	
				)
		    Select @rEmployeeId as Result
	
		--COMMIT TRANSACTION         
	END	 
	 ELSE
	 BEGIN
	    UPDATE  [sHostel].[tHostelWarden] 
	    SET
			 EmployeeId=@rEmployeeId
			 	             
	      WHERE HostelId=@rHostelId AND EmployeeId=@rEmployeeId 
	      SELECT @rEmployeeId AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelWardenGet]
	 @rHostelId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			HM.Id,
			HM.Title,
		    HM.Remark,
		    HM.HostelTypeId,
		    HM.NoOfRooms,	
			HM.IsObsolete,
			HW.EmployeeId,
			EM.FirstName+' '+EM.LastName as EmployeeName,
			HM.ReportOrgTitle,
			HM.SmallAddress1,
			HM.SmallAddress2
  FROM 
			sHostel.tHostelMaster HM
			LEFT JOIN [sHostel].[tHostelWarden] HW ON HW.HostelId=HM.Id
			LEFT JOIN sHRM.tEmployeeMaster EM ON EM.Id=HW.EmployeeId AND ISNULL(EM.IsOtherUser,0) = 0
WHERE 
			(HM.Id=@rHostelId OR @rHostelId=0) 

			 order by EmployeeName
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pHostelYearProcessAdd]
	@rSourceId bigint, --For New sourceid
	@rRoomId int,
	@rBedNumber nvarchar(20),
	@rFromOrgGroupBatchId int,
	@rToOrgGroupBatchId int,
    @rHostelId int,
    @rStudentId bigint, --For Old sourceid
    @rCreatedUserId bigint,
    @rOrgGroupId int,
    @rAcademicId bigint --For deposit add
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount int=0,@lHostelDepositHeadId int=0,@lAmount decimal(12,2)
	--If Exists(select SourceId from sHostel.tAssignRoom where SourceTypeId=2003 AND SourceId=@rStudentId AND OrgGroupBatchId=@rToOrgGroupBatchId)
	--	BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--DECLARE @lCountRoom int=0 ,@lCountsourceid int=0
	--select @lCountRoom=Isnull(StudentsPerRoom,0) from sHostel.tRoomMaster  where   HostelId=@rHostelId AND Id=@rRoomId
	--select @lCountsourceid =COUNT(SourceId)  from sHostel.tAssignRoom  where   OrgGroupBatchId=@rToOrgGroupBatchId AND RoomId=@rRoomId
 --   IF (@lCountsourceid =@lCountRoom)
	--	BEGIN
	--		select -103 as Result
	--		RETURN
 --         END 
          
  BEGIN TRY
  BEGIN TRANSACTION	
BEGIN
 DECLARE @lAllocateDate date = sCommon.fGetDate()
 DECLARE @lAdmissionAllocateDate date
	INSERT INTO sHostel.tAssignRoom
		(
			SourceTypeId,
			SourceId,
			RoomId,
			BedNumber,
			OrgGroupBatchId
		)
	  VALUES
		(
			2003,
			@rSourceId,
			@rRoomId,
			@rBedNumber,
			@rToOrgGroupBatchId
		) 
		  SELECT  @lAdmissionAllocateDate=AllocateDate FROM sHostel.tHostelAdmission WHERE  SourceId=@rStudentId AND OrgGroupBatchId=@rFromOrgGroupBatchId
		  AND Hosteld =@rHostelId AND SourceTypeId=2003
		EXEC sHostel.pHostelAdmissionAdd  @rHostelId,2003,@rSourceId,@lAdmissionAllocateDate,@rToOrgGroupBatchId,false  
	    
	    UPDATE sHostel.tAssignRoomAsset  SET OrgGroupBatchId=@rToOrgGroupBatchId,SourceId=@rSourceId
				WHERE SourceTypeId= 2003 AND SourceId=@rStudentId AND HostelId=@rHostelId
		
		CREATE TABLE #TempTable
		(
			Id Int identity,
			HostelDepositHeadId int,
			Amount decimal(12,2)
		)
		INSERT INTO #TempTable
			SELECT HostelDepositHeadId,(SUM(A.DepositAmount)-SUM(A.RefundAmount)-SUM(A.AdjustAmount))
			FROM
				(SELECT ISNULL(DA.AMount,0) AS DepositAmount,0 As AdjustAmount,0 AS RefundAmount ,HostelDepositHeadId FROM    
				sHostel.tHostelDepositAdd DA   WHERE  DA.StudentId=@rStudentId  AND DA.OrgGroupBatchId = @rFromOrgGroupBatchId AND  DA.HostelId = @rHostelId 
		  
		  UNION All  
		  SELECT  0 AS DepositAmount,AD.Amount AS AdjustAmount,0 AS RefundAmount ,HostelDepositHeadId  FROM   sHostel.tHostelDepositAdjustment AD  WHERE AD.StudentId=@rStudentId AND   AD.OrgGroupBatchId = @rFromOrgGroupBatchId AND AD.HostelId = @rHostelId
		  
		  UNION all
		  SELECT 0 AS DepositAmount,0 AS AdONjustAmount,RefundAmount,HostelDepositHeadId FROM  sHostel.tHostelDepositRefund DR  WHERE DR.StudentId=@rStudentId  AND  DR.OrgGroupBatchId =@rFromOrgGroupBatchId AND DR.HostelId = @rHostelId )A
		  Group By HostelDepositHeadId
		  
		  SELECT @lCount=Count(Id) FROM #TempTable
		  WHILE @lCount>0
		  BEGIN
			SELECT @lHostelDepositHeadId= HostelDepositHeadId,@lAmount=Amount FROM #TempTable WHERE ID=@lCount
			EXEC sHostel.pHostelDepositAddAdd 0,@lHostelDepositHeadId,@rAcademicId,@lAmount,@lAllocateDate,1,'','','',@rCreatedUserId,@rHostelId,@rOrgGroupId,@rToOrgGroupBatchId
			SET @lCount=@lCount-1
		   END
		   SELECT 1
END	 
		COMMIT TRANSACTION
		END TRY
	
	 BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	 END CATCH	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pHostelYearProcessGet]
           @rHostelId int,
           @rOrgGroupBatchId int,
           @rFromOrgGroupBatchId int,
           @rRoomId int,
           @rBuildingId int
AS
SET NOCOUNT ON
--SELECT 
--		RM.Id AS RoomId,
--		RM.Title AS Room,
--	    RCM.Title AS RoomCategory,
--	     CASE WHEN SM.ReferenceSourceId is null THEN VA.Code ElSE SM.Code  END AS Code,
--	     CASE WHEN SM.ReferenceSourceId is null THEN VA.Name ElSE SMA.Name   END AS Name,
--	    CASE WHEN SM.ReferenceSourceId is null THEN AR.SourceId ElSE SM.Id  END AS SourceId,
--	    Isnull(AR.BedNumber,'') AS BedNumber ,
--	    CASE WHEN SM.ReferenceSourceId is null THEN (VA.ClassName +'-' +va.DivisionName) ElSE (SMA.ClassName +'-' +SMA.DivisionName) END AS ClassName,
--	    AR.SourceId As StudentId,
--	    AR.RoomId,
--	    CASE WHEN SM.ReferenceSourceId is null THEN VA.AcademicId ElSE SMA.AcademicId   END AS AcademicId,
--	    CASE WHEN SM.ReferenceSourceId is null THEN VA.suId ElSE SM.suId  END AS suId ,
--	    [sHostel].[fAssignRoomStudentGet] (@rOrgGroupBatchId,CASE WHEN SM.ReferenceSourceId is null THEN AR.SourceId ElSE SM.Id END) AS Status
--	   -- CASE WHEN @rOrgGroupBatchId  in (select OrgGroupBatchId from sHostel.tAssignRoom where SourceTypeId=2003  AND  AR.SourceId=  CASE WHEN SM.ReferenceSourceId is null THEN AR.SourceId ElSE SM.Id END)THEN 'Transfer' ElSE 'Available'  END AS Status
	   
--	   FROM  sHostel.tAssignRoom AR 
--		  INNER JOIN sHostel.tRoomMaster  RM ON RM.Id=AR.RoomId 
--		  INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
--		  INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
--		  INNER JOIN sStudent.vStudentAcademic VA On VA.StudentId= AR.SourceId  AND VA.OrgGroupBatchId=@rOrgGroupBatchId
--		  LEFT JOIN sStudent.tStudentMaster SM ON AR.SourceId=SM.ReferenceSourceId
--		  LEFT JOIN sStudent.vStudentAcademic SMA ON SM.Id = SMA.StudentId AND SMA.OrgGroupBatchId=@rOrgGroupBatchId 
--WHERE 
--      AR.SourceTypeId=2003 
--     AND AR.OrgGroupBatchId=@rFromOrgGroupBatchId
--    -- AND VA.OrgGroupBatchId=@rOrgGroupBatchId
--     AND RM.HostelId=@rHostelId
--     AND RM.IsObsolete=0
	 
	SELECT RM.Id AS RoomId,
		   RM.Title AS Room,
	       RCM.Title AS RoomCategory,
	       V.Code,
	       V.Name,
	       AR.SourceId AS SourceId ,
	       AR.BedNumber,
	       (V.ClassName + '-' +V.DivisionName) AS ClassName,
	       AR.SourceId As StudentId,
	       AR.RoomId,
	       V.AcademicId AS  AcademicId,
	       V.SUID ,
	       [sHostel].[fAssignRoomStudentGet] (@rOrgGroupBatchId, AR.SourceId) AS Status
	        from sHostel.tAssignRoom AR
	        INNER JOIN sHostel.tRoomMaster  RM ON RM.Id=AR.RoomId
	        INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	        INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
				INNER JOIN
			(SELECT StudentId,Code,Name,AcademicId,SUId,ClassName,DivisionName FROM sStudent.vstudentAcademic V
			WHERE OrgGroupBatchId=@rOrgGroupBatchId AND StatusId=1
			) V ON AR.SourceId = V.StudentId
			LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
			WHERE 
			AR.SourceTypeId=2003 
			AND AR.OrgGroupBatchId=@rFromOrgGroupBatchId
			AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
            AND ((BM.Id=@rBuildingId )OR (@rBuildingId=0))
			AND ((HM.Id = @rHostelId) OR (@rHostelId = 0))
    UNION ALL
	SELECT RM.Id AS RoomId,
		   RM.Title AS Room,
	       RCM.Title AS RoomCategory,
	       V.Code,
	       V.Name,
	       V.StudentId AS SourceId ,
	       AR.BedNumber,
	      (V.ClassName + '-' +V.DivisionName) AS ClassName,
	       V.ReferenceSourceId As StudentId ,
	       AR.RoomId,
	       V.AcademicId AS  AcademicId,
	       V.SUID ,
	       [sHostel].[fAssignRoomStudentGet] (@rOrgGroupBatchId,  V.StudentId) AS Status
	        from sHostel.tAssignRoom AR
	        INNER JOIN sHostel.tRoomMaster  RM ON RM.Id=AR.RoomId
	        INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	        INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
	       INNER JOIN
           (SELECT ReferenceSourceId,StudentId,Code,Name,AcademicId,SUId,ClassName,DivisionName FROM sStudent.vstudentAcademic V
           WHERE OrgGroupBatchId=@rOrgGroupBatchId AND StatusId=1
            ) V ON AR.SourceId = V.ReferenceSourceId
            LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
	       WHERE 
	       AR.SourceTypeId=2003 
           AND AR.OrgGroupBatchId=@rFromOrgGroupBatchId
           AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
           AND ((BM.Id=@rBuildingId )OR (@rBuildingId=0))
		   AND ((HM.Id = @rHostelId) OR (@rHostelId = 0))
           
	--FROM  sHostel.tAssignRoom AR 
	--INNER JOIN sHostel.tRoomMaster  RM ON RM.Id=AR.RoomId 
	--INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	--INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
	--INNER JOIN sStudent.vStudentAcademic VA On VA.StudentId= AR.SourceId  AND VA.OrgGroupBatchId=@rOrgGroupBatchId

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pImportHostelRoomAdd]
	(	
		@rStrXml nvarchar(MAX) ,
	    @rOrgGroupBatchId int,
	    @rHosteld int
	    
		 
	)
AS

SET NOCOUNT ON

BEGIN
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT
			
 
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml
	 
	  
	UPDATE sHostel.tAssignRoom
	SET
		 RoomId = A1.RoomId 
	FROM
	(
		SELECT	
			 RoomId,
			 SourceId
			 			
			FROM OPENXML (@intDoc, '/Table/Import', 1)
			WITH
			(
				RoomId int '@RoomId',
				SourceId bigint '@SourceId' 
				
			))A1
	Where  A1.SourceId=sHostel.tAssignRoom.SourceId AND sHostel.tAssignRoom.OrgGroupBatchId=@rOrgGroupBatchId
	
	  	 
	INSERT INTO sHostel.tAssignRoom
	(
		 RoomId,
		 SourceTypeId,
		 SourceId,
		 OrgGroupBatchId
	)
	SELECT
		 RoomId,
		 2003,
		 SourceId,
		 @rOrgGroupBatchId
		
	FROM OPENXML (@intDoc, '/Table/Import', 1)
	WITH
	(
		RoomId int '@RoomId', --DepartmentId int '@DepartmentId',
		SourceId bigint '@SourceId' 
	)A1
	Where   A1.SourceId not in (Select SourceId from sHostel.tAssignRoom WHERE OrgGroupBatchId=@rOrgGroupBatchId)
	 
	 
	 	UPDATE sHostel.tHostelAdmission
	 	
	SET
		AllocateDate=sCommon.fGetDate()
	FROM
	(
		SELECT	
			 
			 SourceId
			 			
			FROM OPENXML (@intDoc, '/Table/Import', 1)
			WITH
			(
				RoomId int '@RoomId',
				SourceId bigint '@SourceId' 
				
			))A1
	Where  A1.SourceId=sHostel.tHostelAdmission.SourceId AND sHostel.tHostelAdmission.OrgGroupBatchId=@rOrgGroupBatchId AND SourceTypeId=2003
	
	 INSERT INTO sHostel.tHostelAdmission
	(
		    Hosteld,
			SourceTypeId,
			SourceId,
			AllocateDate,
			OrgGroupBatchId,
			IsSelfPermissionToGoOut
	)
	SELECT
			 @rHosteld,
			 2003,
			 SourceId,
			 sCommon.fGetDate(),
			 @rOrgGroupBatchId,
			 0
		
	FROM OPENXML (@intDoc, '/Table/Import', 1)
	WITH
	(
	    
		RoomId int '@RoomId', --DepartmentId int '@DepartmentId',
		SourceId bigint '@SourceId' 
	)A1
	Where   A1.SourceId not in (Select SourceId from sHostel.tHostelAdmission WHERE OrgGroupBatchId=@rOrgGroupBatchId AND SourceTypeId=2003)
	 
	 
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	
	 Select 1 As Result

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pImportLeadMasterAdd]
	(	
		@rStrXml nvarchar(MAX) 
		 
	)
AS

SET NOCOUNT ON

BEGIN
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT
			
 
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml
	 
	  
	UPDATE sHostel.tAssignRoom
	SET
		 RoomId = A1.RoomId 
	FROM
	(
		SELECT	
			 RoomId,
			 SourceId
			 			
			FROM OPENXML (@intDoc, '/Table/Import', 1)
			WITH
			(
				RoomId int '@RoomId',
				SourceId bigint '@SourceId' 
				
			))A1
	Where  A1.SourceId=sHostel.tAssignRoom.SourceId
	
	  	 
	INSERT INTO sHostel.tAssignRoom
	(
		 RoomId,
		 SourceTypeId,
		 SourceId
	)
	SELECT
		 RoomId,
		 2003,
		 SourceId
		
	FROM OPENXML (@intDoc, '/Table/Import', 1)
	WITH
	(
		RoomId int '@RoomId', --DepartmentId int '@DepartmentId',
		SourceId bigint '@SourceId' 
	)A1
	Where   A1.SourceId not in (Select SourceId from sHostel.tAssignRoom)
	 
	 
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	
	 Select 1 As Result

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pQuickAssignRoomAdd]
         @rStringXml [nvarchar](max),
         @rHostelId int=0,
         @rAssetAssign int,
         @rOrgGroupBatchId int
AS
SET NOCOUNT ON
BEGIN
 DECLARE @lInterrorCode INT,@intDoc INT,@lAllocateDate date
 DECLARE @lCount int,@lSourceId bigint,@lRoomId int
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStringXml
BEGIN
BEGIN TRY
	 BEGIN	
	-- DELETE  AR FROM sHostel.tRoomMaster RM INNER JOIN sHostel.tAssignRoom AR  ON AR.RoomId=RM.Id WHERE RM.HostelId=@rHostelId AND AR.SourceTypeId=2003
		CREATE TABLE #TemTable
		(   Id bigint identity,	 
			RoomId INT,
			SourceId BIGINT
		 )
	    INSERT INTO  #TemTable
         (RoomId,SourceId)
     	SELECT RoomId,SourceId
	   FROM OPENXML (@intDoc, '/Table/AssignRoomDetail',1)  
		  WITH (
				RoomId INT,
				SourceId BIGINT
				)
	EXEC sp_xml_removedocument @intDoc

			SELECT @lCount= Count(Id) FROM #TemTable
			
WHILE @lCount>0 
BEGIN
				SET @lSourceId=0
				SET @lRoomId=0
				
	SELECT @lSourceId= SourceId,@lRoomId=RoomId FROM #TemTable WHERE ID=@lCount
	BEGIN TRANSACTION 
	 IF  NOT EXISTS(SELECT 1 FROM sHostel.tAssignRoom  WHERE SourceId=@lSourceId AND SourceTypeId=2003 AND OrgGroupBatchId=@rOrgGroupBatchId )
     BEGIN
     INSERT INTO sHostel.tAssignRoom
     (RoomId, SourceTypeId, SourceId,OrgGroupBatchId)
     VALUES(@lRoomId,2003,@lSourceId,@rOrgGroupBatchId)
      Set @lAllocateDate=sCommon.fGetDate()
     EXEC [sHostel].[pHostelAdmissionAdd] @rHostelId,2003,@lSourceId,@lAllocateDate,@rOrgGroupBatchId,false
     END
     IF(@rAssetAssign=1)
     BEGIN
     IF  NOT EXISTS(SELECT 1 FROM sHostel.tAssignRoomAsset  WHERE SourceId=@lSourceId AND SourceTypeId=2003 AND OrgGroupBatchId=@rOrgGroupBatchId)
     BEGIN
     INSERT  INTO sHostel.tAssignRoomAsset(RoomAssetId, SourceTypeId, SourceId, HostelId,OrgGroupBatchId)
     SELECT RS.Id ,2003,@lSourceId,@rHostelId,@rOrgGroupBatchId FROM  (
     SELECT AM.Id,Rank()
          over (Partition BY AM.AssetTypeId
                ORDER BY AM.Id ASC ) AS Rank from sHostel.tRoomAssetMaster AM LEFT JOIN sHostel.tAssignRoomAsset RA
     ON AM.Id = RA.RoomAssetId   
    -- AND OrgGroupBatchId =@rOrgGroupBatchId
       WHERE RoomAssetId is null AND RoomId = @lRoomId)  RS WHERE Rank = 1
     END
     END
      SET @lCount = @lCount - 1
     COMMIT TRANSACTION
      
   END
    SELECT  1 AS Result
   DROP TABLE  #TemTable
END 
	END TRY
	BEGIN CATCH		
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHostel].[pQuickAssignRoomConfigVAlidationAdd]
	
	@rAssignRoomDetailXml [nvarchar](max),
	@rOrgId smallint,
	@rOrgGroupBatchId int
	 
	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignRoomDetailXml
BEGIN
	BEGIN TRY
	DECLARE @Assignstudent nvarchar(max)=''
	  BEGIN
	  
	  SELECT @Assignstudent = @Assignstudent+convert(varchar,VA.Code)+',' FROM sTransport.tAssignRoute AR
	  INNER JOIN sStudent.tStudentMaster VA ON VA.Id=AR.sourceId 
	   Where  SourceId in (SELECT
			         SourceId
		            FROM OPENXML (@loDoc, '/Table/AssignRoomDetail', 1)
		            WITH ( 
					SourceId bigint
				  ) )		 
				  
	SELECT @Assignstudent AS Result
	 END	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pQuickAssignRoomGet]
          
	   @rHostelId int,
	   @rRoomCategoryId int,
	   @rBuildingId int,
	   @rOrgGroupBatchId int,
	   @rOrgId smallint
AS
SET NOCOUNT ON

SELECT 
		RM.Id AS RoomId,
		RM.HostelId,
		RM.Title,
		ISNULL(RM.StudentsPerRoom,0) AS StudentsPerRoom,
		ISNULL(COUNT(AR.SourceID),0) AS StudentsAllocated,
		RM.RoomCategoryId,
	    RCM.Title AS RoomCategory,
	    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
	    ISNULL(BM.Title,'') AS BuildingName
FROM [sHostel].[tRoomMaster] RM
      INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = HM.OrgGroupId AND OM.Id = @rOrgId
      INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
		AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
	  LEFT JOIN [sHostel].[tAssignRoom] AR ON AR.RoomId = RM.Id AND AR.SourceTypeId=2003 AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	  LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
WHERE 
    ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
	AND RM.IsObsolete=0
	AND (BM.Id=@rBuildingId OR @rBuildingId=0)
	AND ((OM.Id = @rOrgId) OR (@rOrgId = 0))
	Group by RM.Id,RM.HostelId,RM.Title,RM.StudentsPerRoom,RM.RoomCategoryId,RCM.Title,RCM.RoomCharge,BM.Title,AR.OrgGroupBatchId

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRoomAssetManagementGET]
	 
        @rHostelId int,
        @rRoomId int,
        @rAssetTypeId int,
        @rBuildingId int,
        @rOrgGroupBatchId int
        
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT
	
     AT.Title  AS AssetType,
	 AT.Id AS AssetTypeId,
	 RM.Title AS Room,
	 RM.Id AS RoomId,
	 ARM.AssetNumber ,
	 ISNULL(AR.RoomAssetId,0) AS RoomAssetId,
	 CASE WHEN  AR.RoomAssetId is null THEN 'Available' ELSE 'Assign' END AS AssignStatus,
	 ISNULL(ARM.Id,0) AS Id ,
	 Case When AR.SourceTypeId=2003 THEN  VA.Name ELSE EM.FirstName  END As Name,
	 Case When AR.SourceTypeId=2003 THEN  VA.SUID ELSE ''  END As SUID,
	 Case When AR.SourceTypeId=2003 THEN VA.Code ELSE EM.Code  END As Code
	From 
	sHostel.tAssetTypeMaster AT
	INNER JOIN sHostel.tRoomAssetMaster ARM  ON AT.Id=ARM.AssetTypeId AND AT.IsObsolete=0
	LEFT JOIN sHostel.tAssignRoomAsset AR ON ARM.Id=AR.RoomAssetId  AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	INNER JOIN sHostel.tRoomMaster RM ON RM.Id=ARM.RoomId 
	LEFT JOIN  sStudent.vStudentAcademic VA on vA.StudentId = AR.SourceId and VA.OrgGroupBatchId=@rOrgGroupBatchId AND AR.SourceTypeId=2003
    LEFT JOIN sHrm.tEmployeeMaster EM ON AR.SourceId=EM.Id AND  AR.SourceTypeId=95
	
WHERE 
 RM.HostelId=@rHostelId
AND ((ARM.RoomId=@rRoomId)OR (@rRoomId=0))
AND ((AT.Id=@rAssetTypeId)OR (@rAssetTypeId=0))
AND ((RM.BuildingId=@rBuildingId)OR (@rBuildingId=0))
AND  ISNULL(EM.IsOtherUser,0) = 0
ORDER BY RM.Id,AT.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRoomAssetMasterAdd]
	 
        @rHostelId int,
        @rId int,
        @rRoomId int,
        @rAssetTypeId int,
        @rAssetNumber nvarchar(100),
        @rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
IF(@rId = 0)	
BEGIN
	If Exists(select Id from sHostel.tRoomAssetMaster where AssetNumber=@rAssetNumber AND HostelId=@rHostelId AND RoomId=@rRoomId )
	BEGIN
		select -103 as Result
		RETURN
	END 
END
--ELSE
--BEGIN
--	If  Exists(select Id from sHostel.tRoomAssetMaster where AssetNumber=@rAssetNumber AND HostelId=@rHostelId AND RoomId=@rRoomId AND Id<>@rId)
--	BEGIN
--		select -103 as Result
--		RETURN
--	END
--END
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT 

	--IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tRoomAssetMaster', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT
	
	INSERT INTO sHostel.tRoomAssetMaster
		(
			HostelId,
			Id,
			RoomId,
			AssetTypeId,
			AssetNumber
		)
	VALUES
		(
			@rHostelId,
			@lNextNumber,
			@rRoomId,
			@rAssetTypeId,
			@rAssetNumber
		)
		    SELECT 1 AS Result
	END	 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRoomAssetMasterGet]
	 
	 @rHostelId int,
	 @rId int=0,
	 @rRoomId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			
			RM.Id,
			RM.RoomId,
			RM.AssetTypeId,
			RM.AssetNumber,
			AM.Title AS AssetType
			
	FROM 
			sHostel.tRoomAssetMaster  RM
			INNER JOIN sHostel.tAssetTypeMaster  AM ON RM.AssetTypeId=AM.Id
	WHERE 
	    RM.HostelId = @rHostelId
	    AND	((RM.RoomId = @rRoomId) OR (@rRoomId = 0))
	    order by RM.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRoomAssetMasterUpdate]
	 
	@rHostelId int,
	@rRoomId int,
	@rRoomAssetId int,
	@rAssetNumber nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	If  Exists(select Id from sHostel.tRoomAssetMaster where AssetNumber=@rAssetNumber AND HostelId=@rHostelId AND RoomId=@rRoomId)
	BEGIN
		select -103 as Result
		RETURN
		END
	BEGIN TRANSACTION	
	UPDATE sHostel.tRoomAssetMaster
	    SET
			RoomId=@rRoomId
	    WHERE HostelId=@rHostelId 
			AND Id = @rRoomAssetId
			   
	SELECT 11 AS Result	             
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pRoomCategoryMasterAdd]
	 
        @rHostelId int,
        @rId int,
        @rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rRoomCharge decimal(12,2),
		@rCreatedUserId bigint,
		@rIsObsolete bit,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		If Exists(select Id from sHostel.tRoomCategoryMaster where Code=@rCode AND HostelId=@rHostelId)
			BEGIN
			select -102 as Result
			RETURN
		END
		If Exists(select Id from sHostel.tRoomCategoryMaster where Title=@rTitle AND HostelId=@rHostelId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sHostel.tRoomCategoryMaster where Code=@rCode AND HostelId=@rHostelId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sHostel.tRoomCategoryMaster where Title=@rTitle AND HostelId=@rHostelId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tRoomCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHostel.tRoomCategoryMaster
		(
			HostelId,
			Id,
			Code,
			Title,
			RoomCharge,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete 
		)
	VALUES
		(
			@rHostelId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rRoomCharge,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tRoomCategoryMaster
	    SET
			HostelId=@rHostelId,
			Code=@rCode,
			Title=@rTitle,
			RoomCharge=@rRoomCharge,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete
	      
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRoomCategoryMasterGet]
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rHostelId int,
	 @rOrgGroupId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			RCM.Id,
			RCM.Code,
			RCM.Title,
			ISNULL(RCM.RoomCharge,0) AS RoomCharge,
		    RCM.HostelId,
		    HM.Title AS Hostel,
			RCM.IsObsolete
      
  FROM 
            sHostel.tRoomCategoryMaster RCM
            INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RCM.HostelId AND (HM.OrgGroupId=@rOrgGroupId)
  WHERE   
			   ((RCM.Id = @rId) OR (@rId = 0))
		   AND ((RCM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	       AND ((RCM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((RCM.HostelId=@rHostelId) OR (@rHostelId=0)) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRoomListGet]
           @rHostelId int,
           @rRoomCategoryId int,
           @rBuildingId int,
           @rOrgGroupBatchId int
AS
SET NOCOUNT ON
BEGIN
SELECT 
		RM.Id,
		RM.HostelId,
		RM.Title,
		ISNULL(RM.StudentsPerRoom,0) AS StudentsPerRoom,
		ISNULL(COUNT(AR.SourceID),0) AS StudentsAllocated,
		RM.RoomCategoryId,
	    RCM.Title AS RoomCategory,
	    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
	    ISNULL(BM.Title,'') AS BuildingName
	    
FROM [sHostel].[tRoomMaster] RM
      INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
      INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
	  AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
	  LEFT JOIN [sHostel].[tAssignRoom] AR ON AR.RoomId = RM.Id AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	  LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
	  
WHERE 
    ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
	AND RM.IsObsolete=0
	AND (BM.Id=@rBuildingId OR @rBuildingId=0)
	Group by RM.Id,RM.HostelId,RM.Title,RM.StudentsPerRoom,RM.RoomCategoryId,RCM.Title,RCM.RoomCharge,BM.Title, AR.OrgGroupBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRoomMasterAdd]
	 
	@rId int,
	@rTitle nvarchar(100),
	@rRemark nvarchar(100),
	@rHostelId int,
	@rRoomCategoryId int,
	@rStudentsPerRoom smallint,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rAssignedEmployeeId bigint,
	@rOrgGroupId int,
	@rBuildingId int,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	
IF(@rId = 0)	
BEGIN
	If Exists(select Id from sHostel.tRoomMaster where Title=@rTitle AND HostelId=@rHostelId)
	BEGIN
		select -103 as Result
		RETURN
	END 
END
ELSE
BEGIN
	If  Exists(select Id from sHostel.tRoomMaster where Title=@rTitle AND HostelId=@rHostelId AND Id<>@rId)
	BEGIN
		select -103 as Result
		RETURN
	END
	
	If  Exists(select Count(SourceId) from sHostel.tAssignRoom where OrgGroupBatchId=@rOrgGroupBatchId AND RoomId=@rId having COUNT(sourceID) > @rStudentsPerRoom)
	BEGIN
		select -104 as Result
		RETURN
	END
END
	
 BEGIN TRANSACTION	
 DECLARE @lNextNumber INT 
 
 IF(@rId = 0)	
	BEGIN
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHostel.tRoomMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tRoomMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sHostel.tRoomMaster
		(
			Id,
			Title,
			Remark,
			HostelId,
			RoomCategoryId,
			StudentsPerRoom,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			AssignedEmployeeId,
			BuildingId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rHostelId,
			@rRoomCategoryId,
			@rStudentsPerRoom,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rAssignedEmployeeId,
			@rBuildingId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sHostel.tRoomMaster
	    SET
			Title=@rTitle,
			Remark=@rRemark,
			HostelId=@rHostelId,
			RoomCategoryId=@rRoomCategoryId,
			StudentsPerRoom=@rStudentsPerRoom,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			AssignedEmployeeId=@rAssignedEmployeeId,
			BuildingId=@rBuildingId
	      
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRoomMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rHostelId int,
	 @rRoomCategoryId int,
	 @rIsSearch bit = 1,
	 @rBuildingId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			RM.Id,
			RM.Title,
		    RM.Remark,
		    RM.HostelId,
		    HM.Title AS Hostel,
		    RM.RoomCategoryId,
		    RCM.Title AS RoomCategory,
		    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
		    RM.StudentsPerRoom,	
			RM.IsObsolete,
			ISNULL(RM.AssignedEmployeeId,0) AS AssignedEmployeeId,
			EM.Code AS AssignedEmployeeCode,
			EM.EmployeeName AS AssignedEmployeeName,
			EM.DepartmentName AS AssignedEmployeeDepartment,
			ISNULL(RM.BuildingId,0) AS BuildingId,
			ISNULL(BM.Title,'') AS BuildingName,
			ISNULL(OM.Id ,0)AS OrgId
      
  FROM 
            sHostel.tRoomMaster RM
            INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
            INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RM.RoomCategoryId = RCM.Id
            AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
            LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.Id=RM.AssignedEmployeeId
            LEFT JOIN sHostel.tBuildingMaster BM ON BM.Id=RM.BuildingId
            LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgID
  WHERE 
  
		((RM.Id = @rId) OR (@rId = 0))
	AND ((RM.BuildingId = @rBuildingId) OR (@rBuildingId = 0))	
	AND ((RM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
	ORDER BY RM.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptAddressLabelGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rIsBasedOnSUId bit = 0,
	 @rDepartmentId int=0,
	 @rSUId nvarchar(50)='',
	 @rRoomId int=0, 
	 @rFromAllocateDate date,
	 @rToAllocateDate Date
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
	HM.Title,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.OrgId,
		SA.DivisionId,
		SA.DivisionOrder,
		@rIsBasedOnSUId AS IsBasedOnSUId ,
		CD.PresentStreetOne AS Address1,
		CD.PresentStreetTwo AS Address2,
		CD.PresentStreetThree AS Address3,
		CD.PresentCountry AS AddressCountry,
		CD.PresentState AS AddressState,
		CD.PresentCity AS AddressCity,
		CD.PresentZipCode AS AddressZipCode,
		CD.PresentContactNo AS ContactNo,
		CD.ParentContactNo ,
		CD.StudentContactNo,
		CD.ParentEmail,
		CD.StudentEmail,
		SA.Name,
		SA.Code,
		SA.SUId,
		RM.Title As Room,
		[sHostel].[fAssignRoomAssetNumberGet](HM.Id,RM.Id,ISNULL(SA.StudentId,0)) As AssetNumber,
		SA.ClassName ,
		SA.DivisionName
			
			
	FROM 
		sStudent.vStudentAcademic SA 
		LEFT JOIN sStudent.tStudentCommunication CD ON  SA.StudentId=CD.StudentId
		INNER JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 
		INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId 
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
		INNER JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
	 
	WHERE 
 --(SA.OrgGroupBatchId = @rOrgGroupBatchId)

		((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
	    AND ((SA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND (SA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND (AR.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	    AND BM.IsInContext = 1
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptDepositWisetransactionList]

	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rOrgGroupBatchId int = 0,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
     @rRoomId int
      
AS
BEGIN
		SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    'DepositAdd' AS GroupType,
	        --'' As ExpenseSubType,
	        DA.Id As GroupID
		    
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			Where 
		  ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DA.DepositHeadId = @rDepositHeadId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0))
			AND ((DA.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0)) 			
			
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			ISnull (DAJ.Amount,0)  AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     'DepositAdjustment' AS GroupType,
		     --ES.Title As ExpenseSubType,
		     DAJ.Id As GroupID
		    
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  --INNER JOIN sHostel.tHostelExpenseSubTypeMaster ES ON ES.Id=DAJ.HostelExpenseSubTypeId
		     
			Where 
				((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DAJ.DepositHeadId = @rDepositHeadId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0))
			AND ((DAJ.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0)) 			
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			ISnull (DR.RefundAmount,0)  AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId, 
		    'DepositRefund' AS GroupType,
		    --'' As ExpenseSubType,
		    DR.Id As GroupID
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DR.DepositHeadId = @rDepositHeadId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0))
			AND ((DR.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0)) 		    


 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptExpenseTypeWiseDepositList]

	 @rHostelId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rOrgGroupBatchId int,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
    -- @rRoomId int,
     @rFromAllocateDate date,
	 @rToAllocateDate Date
      
AS
BEGIN
		SELECT 
			@rBuilder2 AS Builder2,
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    'Add' AS GroupType,
	        '' As ExpenseSubType,
	        '' AS ExpenseType,
	        DA.Id As GroupID,
			HM.ReportOrgTitle AS ReportOrgTitle,
			HM.SmallAddress1 AS SmallAddress1,
			HM.SmallAddress2 AS SmallAddress2
		    
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId  
			INNER JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=DA.StudentId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DA.HostelId
			Where 
		  ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DA.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	        AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
			
	UNION
			SELECT 
			@rBuilder2 AS Builder2,
			DAJ.AdjustmentDate As DepositDate,
			-ISnull (DAJ.Amount,0)  AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     'Adjustment' AS GroupType,
		     ES.Title As ExpenseSubType,
		     HT.Title AS ExpenseType,
		     DAJ.Id As GroupID,
			 '' AS ReportOrgTitle,
			 '' AS SmallAddress1,
			 '' AS SmallAddress2
		    
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId
			  INNER JOIN sHostel.tHostelExpenseSubTypeMaster ES ON ES.Id=DAJ.HostelExpenseSubTypeId
		      INNER JOIN sHostel.tHostelExpenseTypeMaster HT ON HT.Id= ES.ExpenseTypeId
			INNER JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=DAJ.StudentId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
			Where 
				((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DAJ.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DAJ.OrgGroupBatchId = @rOrgGroupBatchId
		    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	        AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	 UNION
			SELECT 
			@rBuilder2 AS Builder2,
			DR.RefundDate As DepositDate,
			-ISnull (DR.RefundAmount,0)  AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId, 
		    'Refund' AS GroupType,
		    '' As ExpenseSubType,
		    '' AS ExpenseType,
		    DR.Id As GroupID,
			'' AS ReportOrgTitle,
			'' AS SmallAddress1,
			'' AS SmallAddress2
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
			   INNER JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=DR.StudentId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DR.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DR.OrgGroupBatchId = @rOrgGroupBatchId
		    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	      AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))


 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptHostelAdmissionListGet]
          
           @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
	       @rHostelId int,
			@rOrgGroupBatchId int,
			@rOrgId int,
			@rRoomId int=0,
			@rStudentName nvarchar(100)='',
			@rStudentCode nvarchar(100)='',
			@rClassId int=0,
			@rDivisionId int=0,
			--@rIsBasedOnSUId bit = 0,
			@rDepartmentId int=0,
			@rSUId nvarchar(50)='' , 
			@rCode nvarchar(20)='',          		         
           --@rHostelDepositHeadId int=0,
           @rFromDate date,
           @rToDate date
                                                  				  		            
AS
SET NOCOUNT ON

BEGIN
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		vSA.SUId,
		vSA.AcademicId AS AcademicId,
		vSA.StudentId AS StudentId,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		RM.Id AS RoomId,
		RM.Title AS RoomName,
		--CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId,
	 HA.AllocateDate AS AdmissionDate
		
	
		
  FROM 		sHostel.tHostelAdmission HA
			LEFT JOIN sStudent.vStudentAcademic vSA ON vSA.StudentId = HA.SourceId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=HA.Hosteld
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=HA.SourceId
			LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId   
            INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = vSA.BatchId
		--sStudent.vStudentAcademic vSA		
		--INNER JOIN sHostel.tHostelAdmission HA ON HA.SourceId = vSA.AcademicId
		--INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = vSA.StudentId
		--INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DR.HostelDepositHeadId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		--INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DR.HostelId
		--LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=DR.StudentId  AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	 --   LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId   
		
  WHERE  
		
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)		
		AND ((HA.AllocateDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((HA.AllocateDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))		
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (HA.Hosteld=@rHostelId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((vSA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((vSA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((vSA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((vSA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (vSA.SUId like @rSUId OR ISNULL(@rSUId,'')='') 
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (HA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND BM.IsInContext = 1
		--GROUP BY
		
		--DHM.Title,DR.HostelDepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		--DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName,OM.Id,OM.DisplayTitle ,HM.ReportOrgTitle,HM.SmallAddress1,HM.SmallAddress2,RM.Id ,RM.Title,vSA.SUId 
		Order By HA.AllocateDate desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pRptHostelAttendanceSheetGet]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rHostelId int,
	 @rRoomId int = 0,
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @rStudentCode nvarchar(20)='',
	 @rStudentName nvarchar(100)='',
	  @rBatchId int = 0,
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int=0,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rHostelAttendanceTypeId int

	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	
--SET FMTONLY OFF 
DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	Declare @Days int 
 	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	HostelTitle Nvarchar(500),
	Code nvarchar(500),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(500),
	HostelAttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(500),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(500),
	DivisionName nvarchar(500),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	StatusId int,
	AttendanceDate date,
	HostelId Int,
	HostelAttendanceType varchar(100)-- add for mantis : 0039676

)
Insert INTO #AttendanceRegistertempTable
(	
	HostelTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	HostelAttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	StatusId,
	AttendanceDate,
	HostelId,
	HostelAttendanceType--add for mantis : 0039676
)
Select	      
	Hm.Title as HostelTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	ATR.HostelAttendanceTypeId ,
	YEAR(ATR.AttendanceDate) AS ForYear,
	MONTH(ATR.AttendanceDate) AS ForMonth,
	DATENAME(month, ATR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,
	Sa.DivisionName,	
	ATR.IsPresent,
	 day(ATR.AttendanceDate) AS DayPart,
	  A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	SA.StatusId,
	 ATR.AttendanceDate As AttendanceDate,
	 HM.Id,
	 ISNULL(ATM.Title,'') AS HostelAttendanceType--add for mantis : 0039676
	 
    from
            sStudent.vStudentAcademic SA 
			INNER JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId = SA.StudentId 
			INNER JOIN sHostel.tAssignRoom AR ON  ATR.StudentId= AR.SourceId AND AR.SourceTypeId=2003
			LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id=ATR.AbsentReasonId
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId 
	        INNER JOIN sHostel.tHostelMaster HM ON HM.Id=ATR.HostelId
	        INNER JOIN sHostel.tHostelAttendanceTypeMaster ATM ON ATM.Id=ATR.HostelAttendanceTypeId
	        LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            
             WHERE  
	        ((ATR.HostelAttendanceTypeId=@rHostelAttendanceTypeId) OR (@rHostelAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(ATR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(ATR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			   AND (ATR.HostelId=@rHostelId)
			   AND SA.OrgGroupBatchId= @rOrgGroupBatchId
				AND ATR.OrgGroupBatchId= @rOrgGroupBatchId
				 AND AR.OrgGroupBatchId= @rOrgGroupBatchId
			   AND ((AR.RoomId=@rRoomId) OR (@rRoomId=0))	--add for mantis : 0039676	

--select * from #AttendanceRegistertempTable
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)
SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](@rForYear,@rForMonth,@li,@rBatchId,@rClassId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

	SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			HostelTitle,
			HostelId,
			isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(HostelAttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			ISNULL(ABU.AUCount,0) AS AbsentUpto,
			ISNULL(TC.TCount,0) AS AttendanceCount,
		    ISNULL(AC.ACount,0) As  AbsentCount,
		    ISNULL(PC.PCount,0) As  PresentUpto,	    
		    
		    ClassOrderIndex,
		    DivisionOrderIndex,
			(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,0)) AS TotalPresent,
			 
			  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,1 ,@rBatchId ,@rClassId,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rClassId,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rClassId,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rClassId,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rClassId,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rClassId,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rClassId,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rClassId,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rClassId,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rClassId,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rClassId,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rClassId,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rClassId,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rClassId,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rClassId,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rClassId,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rClassId,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rClassId,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rClassId,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rClassId,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rClassId,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rClassId,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rClassId,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rClassId,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rClassId,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rClassId,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rClassId,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rClassId,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			CASE WHEN @Days>=29 THEN  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,29 ,@rBatchId,@rClassId ,@rDivisionId , isnull([29],''),@rOrgId ) end AS P29,
			CASE WHEN @Days>=30 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rClassId,@rDivisionId , isnull([30],''),@rOrgId ) end AS P30,
			CASE WHEN @Days>=31 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rClassId,@rDivisionId , isnull([31],''),@rOrgId )  end AS P31,
 
             sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,
			 HostelAttendanceType-- add for mantis : 0039676


 
FROM
(
	Select --TID, 
		HostelTitle,
		HostelId,
		Code,
		RollNo,
		AcademicId,
		Name,
		HostelAttendanceTypeId,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		HostelAttendanceType--add for mantis : 0039676
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sHostel.tAttendanceRegister ATR 
			INNER JOIN sStudent.tAcademic A ON ATR.StudentId = A.StudentId
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
		    INNER JOIN sSetup.tBatchMaster AS BM ON BM.Id = A.BatchId
			WHERE  
			 ATR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND ATR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((ATR.HostelAttendanceTypeId=@rHostelAttendanceTypeId) OR (@rHostelAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			AND (ATR.HostelId=@rHostelId)
			AND ATR.OrgGroupBatchId= @rOrgGroupBatchId
			AND BM.OrgGroupBatchId= @rOrgGroupBatchId
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
		LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS AUCount  FROM sHostel.tAttendanceRegister ATR 
			INNER JOIN sStudent.tAcademic A ON ATR.StudentId = A.StudentId 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
		    INNER JOIN sSetup.tBatchMaster AS BM ON BM.Id = A.BatchId
			WHERE  
			 ATR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND ATR.IsPresent = 0	    		
            --AND (SA.StatusId = 1)
	        AND ((ATR.HostelAttendanceTypeId=@rHostelAttendanceTypeId) OR (@rHostelAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			AND (ATR.HostelId=@rHostelId)
			AND ATR.OrgGroupBatchId= @rOrgGroupBatchId
			AND BM.OrgGroupBatchId= @rOrgGroupBatchId
			GROUP BY A.Id
    ) ABU ON ABU.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS TotalPresent  FROM sHostel.tAttendanceRegister ATR 
			INNER JOIN sStudent.tAcademic A ON ATR.StudentId= A.StudentId 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
		    INNER JOIN sSetup.tBatchMaster AS BM ON BM.Id = A.BatchId
			WHERE  
			ATR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
	        AND
	        ((ATR.HostelAttendanceTypeId=@rHostelAttendanceTypeId) OR (@rHostelAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			AND (ATR.HostelId=@rHostelId)
			AND ATR.OrgGroupBatchId= @rOrgGroupBatchId
			AND BM.OrgGroupBatchId= @rOrgGroupBatchId
			GROUP BY A.Id
    ) AA ON AA.AcademicId = PivotTable.AcademicId
 
    ORDER BY RollNo;
 
 		
select * from #TempDaysTempTable
			
drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
--SET FMTONLY on	
END

--SELECT 
--	CONVERT(date,'') AS LastDate
--	,CONVERT(date,'') AS LeftDate
--	,'' AS Builder1
--	,'' AS Builder2
--	, CONVERT(bigint,0) AS AcademicId
--	,'' AS HostelTitle
--	, 0 AS HostelId
--	,'' AS Code
--	,0 AS RollNo
--	,'' AS Name
--	,0 AS AttendanceTypeId
--	,0 AS ForYear
--	,0 AS ForMonth
--	,0 AS ClassId
--	,'' AS ClassName
--	,0 AS DivisionId
--	,'' AS DivisionName
--	,'' AS ForMonthInWord
--	,0 AS PresentCount
--	,0 AS AbsentUpto
--	,0 AS AttendanceCount
--	,0 AS AbsentCount
--	,0 AS PresentUpto
--	,0 AS ClassOrderIndex
--	,0 AS DivisionOrderIndex
--	,0 AS TotalPresent
--	,'' AS P1
--	,'' AS P2
--	,'' AS P3
--	,'' AS P4
--	,'' AS P5
--	,'' AS P6
--	,'' AS P7
--	,'' AS P8
--	,'' AS P9
--	,'' AS P10
--	,'' AS P11
--	,'' AS P12
--	,'' AS P13
--	,'' AS P14
--	,'' AS P15
--	,'' AS P16
--	,'' AS P17
--	,'' AS P18
--	,'' AS P19
--	,'' AS P20
--	,'' AS P21
--	,'' AS P22
--	,'' AS P23
--	,'' AS P24
--	,'' AS P25
--	,'' AS P26
--	,'' AS P27
--	,'' AS P28
--	,'' AS P29
--	,'' AS P30
--	,'' AS P31
--	,0 AS DaysInMonth
--	,'' AS HostelAttendanceType
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptHostelDepositAddGet]
          
		     @rOrgId int,          
             @rHostelDepositHeadId int=0,
             @rFromAmount decimal(12,2)=0,
             @rToAmount decimal(12,2)=0,
             @rFromDepositDate date='',
             @rToDepositDate date='',
          -- @rBatchId int,
             @rCode nvarchar(20)='',
             @rHostelId int,
             @rRoomId int=0,
             @rStudentName nvarchar(100)='',
			 @rStudentCode nvarchar(100)='',
			 @rClassId int=0,
		     @rDivisionId int=0,
			 @rIsBasedOnSUId bit = 0,
			 @rDepartmentId int=0,
			 @rSUId nvarchar(50)='',
			 @rOrgGroupBatchId int,
			 @rBuilder1 nvarchar(max)='',
			 @rBuilder2 nvarchar(max)='',
			 @rFromAllocateDate date=null,
	         @rToAllocateDate Date=null
           
AS
SET NOCOUNT ON 

BEGIN
SELECT  
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,	
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		RM.Id AS RoomId,
		RM.Title AS RoomName,
		CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId,
		PTM.Title AS PayType,
		U.DisplayTitle AS Username,
		U.Id As UserId
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DA.HostelId  
	    LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=DA.StudentId  AND  AR.OrgGroupBatchId=@rOrgGroupBatchId
	    LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId  
	    INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DA.PayTypeId
	    LEFT JOIN sSecurity.tUser U ON U.Id=DA.CreatedUserId
	    LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = vSA.BatchId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DA.HostelId=@rHostelId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((vSA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((vSA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((vSA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((vSA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (vSA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (DA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	    AND BM.IsInContext = 1
		Order By DA.DepositDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pRptHostelDepositAddReceiptGet]
          
		   @rId bigint,
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           --@rBatchId int,
           @rOrgGroupId int,
           @rHostelId int,
           @rOrgGroupBatchId int,
           @rStudentId bigint=0,
           @rdate datetime=''
          -- @rIsBasedOnSUId bit = 0
AS
SET NOCOUNT ON 
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lCurrencyCode nvarchar(20) = ''
 
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = R.OrgGroupId  FROM sHostel.tHostelDepositHeadMaster R 
		INNER JOIN sSetup.tOrgGroupMaster OB ON R.OrgGroupId = OB.Id 
		WHERE R.Id = @rHostelDepositHeadId
		
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END
	--SELECT  @lPriviousAmount =(SELECT (SELECT isnull(sum(DA.Amount),0) FROM  sHostel.tHostelDepositAdd DA WHERE DA.HostelDepositHeadId=@rHostelDepositHeadId AND DA.StudentId=@rStudentId AND DA.CreatedDateTime<@rdate  AND  DA.OrgGroupBatchId=@rOrgGroupBatchId ) -
 --      (SELECT isnull(sum(DA.Amount),0) FROM  sHostel.tHostelDepositAdjustment DA WHERE DA.HostelDepositHeadId=@rHostelDepositHeadId AND DA.StudentId=@rStudentId  AND DA.CreatedDateTime<@rdate   AND DA.OrgGroupBatchId=@rOrgGroupBatchId) -
 --      (SELECT isnull(sum(DA.RefundAmount),0) FROM  sHostel.tHostelDepositRefund DA WHERE DA.HostelDepositHeadId=@rHostelDepositHeadId AND DA.StudentId=@rStudentId AND DA.CreatedDateTime<@rdate  AND  DA.OrgGroupBatchId=@rOrgGroupBatchId ))

SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		PTM.Title AS PayType,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.RollNo,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
        vSA.BatchName,
        @lCurrencyCode AS CurrencyCode,
        HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		--CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId
		ISNULL(vSA.suid,'')  AS SUId,
		DA.PreviousBalance As PriviousBalance
		
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DA.PayTypeId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DA.HostelId 
  WHERE  
		--vSA.BatchId = @rBatchId 
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND (DA.Id=@rId)
	    AND (DA.HostelId=@rHostelId)
	    AND (DA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
	    
		Order By DA.DepositDate
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptHostelDepositAdjustmentGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int=0,
           @rFromAmount decimal(12,2)=0,
           @rToAmount decimal(12,2)=0,
           @rFromAdjustmentDate date='',
           @rToAdjustmentDate date='',
           --@rBatchId int,
           @rCode nvarchar(20)='',
           @rHostelId int,@rRoomId int=0,
           @rStudentName nvarchar(100)='',
		   @rStudentCode nvarchar(100)='',
		   @rClassId int=0,
		   @rDivisionId int=0,
		   @rIsBasedOnSUId bit = 0,
		   @rDepartmentId int=0,
		   @rSUId nvarchar(50)='',
		   @rOrgGroupBatchId int,
		   @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
	       @rFromAllocateDate date=null,
	       @rToAllocateDate Date=null
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
         HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		RM.Id AS RoomId,
		RM.Title AS RoomName,
		CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN  sHostel.tHostelDepositAdjustment DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DA.HostelId 
		LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=DA.StudentId AND  AR.OrgGroupBatchId=@rOrgGroupBatchId
	    LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId  
	     LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DA.HostelId=@rHostelId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((vSA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((vSA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((vSA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((vSA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (vSA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
	    AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND (DA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
		Order By DA.CreatedDateTime
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pRptHostelDepositAdjustmentReceiptGet]
          
		   @rId bigint,          
		   @rOrgId int,          
           @rHostelDepositHeadId int,
           --@rBatchId int,
           @rHostelId int,
           --@rIsBasedOnSUId bit = 0
            @rOrgGroupBatchId int
AS
SET NOCOUNT ON

BEGIN
   
SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.RollNo,
		vSA.BatchName,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(DA.Amount,0.00),1,2,OM.OrgGroupId) AS ReceiptAmountInWords,
         HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		--CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId
		ISNULL(vSA.suid,'') AS SUId
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdjustment DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DA.HostelId 
  WHERE  
		--vSA.BatchId = @rBatchId 
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND (DA.Id=@rId)
		AND (DA.HostelId=@rHostelId)
		AND (DA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		Order By DA.CreatedDateTime
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptHostelDepositMinusGet]
          
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rRoomId int=0,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rIsBasedOnSUId bit = 0,
	 @rDepartmentId int=0,
	 @rSUId nvarchar(50)='',
	 @rFromAllocateDate date,
	 @rToAllocateDate Date
           
AS
SET NOCOUNT ON

BEGIN
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as SourceCode,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.RollNo,
--		DA.HostelDepositHeadId,
--		DHM.Title AS DepositHeadName,
		SA.OrgId,
		SA.OrganizationName,
		(D.TotalDeposit - A.TotalAdjustment) AS MinusAmount,
		RM.Title AS Room,
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2
		
  FROM 		
		sStudent.vStudentAcademic SA
		LEFT  JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		LEFT JOIN sHostel.tRoomMaster RM ON  RM.Id=AR.RoomId 
	    LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
		LEFT JOIN
		(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.StudentId,DA.HostelId FROM sHostel.tHostelDepositAdd DA WHERE DA.HostelId = @rHostelId  AND DA.OrgGroupBatchId=@rOrgGroupBatchId GROUP BY DA.StudentId,DA.HostelId  )D 
		ON D.StudentId=SA.StudentId
		LEFT JOIN 
		(select SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.StudentId   FROM sHostel.tHostelDepositAdjustment AD WHERE AD.HostelId = @rHostelId   AND AD.OrgGroupBatchId=@rOrgGroupBatchId GROUP BY AD.StudentId) A 
		ON A.StudentId=SA.StudentId
		--INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = D.HostelDepositHeadId
		LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
		
  WHERE  
       
       D.TotalDeposit - A.TotalAdjustment < 0 
		AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((D.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='') 
		AND (SA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptHostelDepositRefundGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int=0,
           @rFromRefundAmount decimal(12,2)=0,
           @rToRefundAmount decimal(12,2)=0,
           @rFromRefundDate date='',
           @rToRefundDate date='',
           @rHostelId int,
           @rCode nvarchar(20)='',
           @rRoomId int=0,
           @rStudentName nvarchar(100)='',
		   @rStudentCode nvarchar(100)='',
		   @rClassId int=0,
		   @rDivisionId int=0,
		   @rIsBasedOnSUId bit = 0,
		   @rDepartmentId int=0,
		   @rSUId nvarchar(50)='',
		   @rOrgGroupBatchId int,
		   @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
	       @rFromAllocateDate date=null,
	       @rToAllocateDate Date=null
          
AS
SET NOCOUNT ON

BEGIN
SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			DHM.Title AS DepositHeadName,
			DR.HostelDepositHeadId,
			DR.StudentId AS StudentId,
			vSA.AcademicId AS AcademicId,
			DR.RefundDate,
			DR.PayTypeId,
			DR.ChequeNo,
			DR.BankName,
			DR.Remark,
			DR.CreatedDateTime,
			vSA.Code,
			vSA.Name AS StudentName,        
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,

			CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
			(SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
			INNER JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = DR.StudentId AND DR1.OrgGroupBatchId=@rOrgGroupBatchId
			WHERE D.HostelDepositHeadId = DR1.HostelDepositHeadId AND D.StudentId=DR1.StudentId AND D.OrgGroupBatchId=@rOrgGroupBatchId)         
			- (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sHostel.tHostelDepositAdjustment DA 
			INNER JOIN sHostel.tHostelDepositRefund DR2 ON DR2.HostelDepositHeadId=DA.HostelDepositHeadId AND DR2.StudentId=DA.StudentId AND DA.StudentId= DR.StudentId AND DA.OrgGroupBatchId=@rOrgGroupBatchId
			WHERE DA.HostelDepositHeadId = DR2.HostelDepositHeadId AND DA.StudentId=DR2.StudentId  AND  DR2.OrgGroupBatchId=@rOrgGroupBatchId) END AS RefundAmount,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrganizationName,
			HM.ReportOrgTitle,
			HM.SmallAddress1,
			HM.SmallAddress2,
			RM.Id AS RoomId,
			RM.Title AS RoomName,
			CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId,
			U.Id As UserId,
			U.DisplayTitle AS Username
		
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DR.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DR.HostelId
		LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=DR.StudentId  AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	    LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId   
	    LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=DR.CreatedUserId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DR.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DR.HostelId=@rHostelId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((vSA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((vSA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((vSA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((vSA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (vSA.SUId like @rSUId OR ISNULL(@rSUId,'')='') 
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (DR.OrgGroupBatchId=@rOrgGroupBatchId)
		   AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
		GROUP BY
		DHM.Title,DR.HostelDepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName,OM.Id,OM.DisplayTitle ,HM.ReportOrgTitle,HM.SmallAddress1,HM.SmallAddress2,RM.Id ,RM.Title,vSA.SUId,U.Id,U.DisplayTitle
		Order By DR.RefundDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sHostel].[pRptHostelDepositSummaryGet] 
          
		     @rOrgId int=0,          
            
             @rFromDepositDate date='',
             @rToDepositDate date='',
         
             @rHostelId int,
            
			 @rOrgGroupBatchId int,
			 @rBuilder1 nvarchar(max)='',
			 @rBuilder2 nvarchar(max)=''
			 
           
AS
SET NOCOUNT ON 

BEGIN
 Select @rBuilder2 AS Builder2,@rBuilder1 AS Builder1,Sum(DipositeAmount) AS DepositeAmount,Sum(DipositeAdjustmentAmount) AS DepositeAdjustmentAmount,Date,DepositeMonth,ReportOrgTitle,SmallAddress1,SmallAddress2 from (
 SELECT  
 
		Sum(DA.Amount) AS DipositeAmount,
		0 As DipositeAdjustmentAmount,
		DA.DepositDate AS Date,
		MONTH(DA.DepositDate) DepositeMonth,
        HM.ReportOrgTitle AS ReportOrgTitle,
		HM.SmallAddress1 AS SmallAddress1,
		HM.SmallAddress2 AS SmallAddress2
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DA.HostelId
		 
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = '')) AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		
		AND (DA.HostelId=@rHostelId)
	 
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (DA.OrgGroupBatchId=@rOrgGroupBatchId)
		Group BY  DA.DepositDate,HM.ReportOrgTitle,HM.SmallAddress1,HM.SmallAddress2
	
		 
Union  
	
		SELECT  
   
		0 AS DipositeAmount,
		SUM(HDA.Amount) As DipositeAdjustmentAmount,
		HDA.AdjustmentDate AS Date,
		MONTH(HDA.AdjustmentDate) DepositeMonth,
		'' AS ReportOrgTitle,
		'' AS SmallAddress1,
		'' AS SmallAddress2
  FROM 		
		sStudent.vStudentAcademic vSA
	     INNER JOIN  sHostel.tHostelDepositAdjustment HDA ON HDA.StudentId = vSA.StudentId 
					 
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
	 
		AND ((HDA.AdjustmentDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = '')) AND ((HDA.AdjustmentDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
						AND (HDA.HostelId=@rHostelId)
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (HDA.OrgGroupBatchId=@rOrgGroupBatchId)
		Group By HDA.AdjustmentDate
		 )A
		 Group By Date ,DepositeMonth,ReportOrgTitle,SmallAddress1,SmallAddress2
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHostel].[prptHostelStudentGatePassbulkGet]
          
           @rbulkNo nvarchar(20),
           @rOrgGroupBatchId int,
           @rstudentid nvarchar(max)='',
           @rOrgGroupId  int=0
AS
SET NOCOUNT ON
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lConfigValue nvarchar(50)
BEGIN
SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 232 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
		BEGIN
		SET @lIsOnPrePrinted = 0
		END
		ELSE IF (@lConfigValue = 'Blank')
		BEGIN
		SET @lIsOnPrePrinted = 1
	END
		SELECT
			HSGP.Id, 
			HSGP.Id AS HostelStudentGatePassId,
			vSA.Code,
			vSA.Name AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			HSGP.StudentId,
			HSGP.RelationshipId,		
			RM.Title AS Relationship,
			HSGP.Relation,
			 CASE WHEN HSGP.RelationshipId=2 Then SF.FatherName
			  WHEN HSGP.RelationshipId=3 Then SF.MotherName ELSE  HSGP.VisitorName   END AS VisitorName,
			 CASE WHEN HSGP.RelationshipId=2 Then SC.ParentContactNo
			     WHEN HSGP.RelationshipId=3 Then SC.ParentContactNo  ELSe  HSGP.VisitorMobile END AS VisitorMobile ,
			HSGP.HostelGatePassReasonId,
			HGRM.Title AS HostelGetPassReason,
			HSGP.Remark,
			--HSGP.VisitorPhoto	,
			
				
			--CASE  WHEN @rIsPrintView=1 THEN HSGP.VisitorPhoto		
			--ELSE ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			HSGP.GatePassDate,
			HSGP.GatePassInDate,
			 ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX),''))  AS VisitorPhoto,
			 CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
			  CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100) As GatePassInTime,
	
				--ISNULL(HSGP.GatePassTime,'') As GatePassTime,
			HSGP.EntryModeStatusId,
			HSGP.HostelId,
			SM.Title AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			  ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), ''))   AS StudentPhoto,
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			HSGP.OrgGroupBatchId,
			vSA.SUId,
			HM.Title As HostelName,
			HM.ReportOrgTitle AS ReportOrgTitle,
			HM.SmallAddress1 AS SmallAddress1,
			HM.SmallAddress2 AS SmallAddress2,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			RMM.Title AS RoomName,
			AR.BedNumber
			
			
		FROM 
		    sStudent.vStudentAcademic vSA
			INNER JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId AND VSA.OrgGroupBatchId=@rOrgGroupBatchId AND HSGP.OrgGroupBatchId=@rOrgGroupBatchId
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId
			LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=HSGP.RelationshipId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceTypeId = 2003 AND AR.SourceId= vSA.StudentId AND AR.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sSecurity.tUser U	ON U.Id=HSGP.CreatedUserId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=HSGP.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=HSGP.StudentId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = HSGP.HostelId
			LEFT JOIN sHostel.tRoomMaster RMM ON AR.RoomId = RMM.Id 
		WHERE 
		--SELECT * FROM sHostel.tAssignRoom
			 
			 HSGP.BulkNumber=@rbulkNo
			 AND (ISNULL(vSA.StudentId,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rstudentid,',')) OR @rstudentid='') 
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptHostelStudentGatePassGet]

	 @rId int,
	 @rStudentCode nvarchar(20),
	 @rHostelId int,
	 @rOutDate datetime,
	 @rInDate datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			VA.Code,
			VA.Name AS StudentName,
			SG.WhithWhom,
			SG.ApprovedBy,
			SG.Reason,
		    SG.OutDate,
			SG.InDate,
			SG.Id,
			HM.Title AS HostelName,
			VA.Code,
			SG.StudentId,
			SG.OutTime,
			SG.InTime,
			VA.OrganizationName,
			VA.ClassName+' - '+VA.DivisionName AS Class,
			SI.StudentPhoto	,
			ISNULL(U.DisplayTitle,'') AS UserName	
	FROM 
			sHostel.tStudentGatePass SG
			INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=SG.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=VA.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SG.CreatedUserId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=SG.HostelId
		  
	WHERE 
			((SG.Id = @rId) OR (@rId = 0))
		 AND (VA.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
		 AND ((SG.HostelId = @rHostelId) OR (@rHostelId = 0))
		 AND (SG.OutDate>=@rOutDate OR ISNULL(@rOutDate,'')='')
		 AND (SG.OutDate<=@rInDate OR ISNULL(@rInDate,'')='')
		END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHostel].[pRptRoomAssetListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rRoomId int=0,
	 @rOrgGroupBatchId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT
	   --AT.Id As AssetTypeId,
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
 		AT.Title AS AssetType,
        RAM.AssetTypeId AS AssetTypeId,
		RAM.AssetNumber AS AssetNumber,
        AR.RoomAssetId AS RoomAssetId,
		HM.Title AS HostelName,
		RAM.HostelId As HostelId,
		RAM.RoomId As RoomId,
		RM.Title As RoomName,
		[sHostel].[fRemainAssignRoomAssetGet](RAM.HostelId,RAM.RoomId, RAM.AssetTypeId) AS RemainAssetType,
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2
	FROM sHostel.tRoomAssetMaster RAM 
    INNER JOIN sHostel.tAssetTypeMaster AT ON AT.Id=RAM.AssetTypeId
    LEFT JOIN sHostel.tAssignRoomAsset AR ON RAM.Id=AR.RoomAssetId 
    --AND AR.OrgGroupBatchId=@rOrgGroupBatchId
    INNER JOIN sHostel.tRoomMaster RM ON Rm.Id=RAM.RoomId
    INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RAM.HostelId
    
	WHERE 
	   RAM.HostelId=@rHostelId
		AND ((RAM.RoomId=@rRoomId) OR (@rRoomId=0))
		
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pRptRoomwiseEmployeeListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rRoomId int=0,
	 --@rEmployeeName nvarchar(100)='',
	 @rEmployeeCode nvarchar(100)='',
	 @rDepartmentId int=0,
	 @rFromAllocateDate date='',
	 @rToAllocateDate Date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	SELECT
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Employee' AS SourceType,
		95 AS SourceTypeId,
		ISNULL(EM.Id,0) as SourceId,
		EM.Code as SourceCode,
		EM.FirstName+' '+EM.LastName as SourceName,
		OM.DisplayTitle AS OrganizatinName,
		ODM.Title as DepartmentName,
		EC.MobileNumber,
	    OM.Id AS OrgId,
	    '' AS SUId,
	    '' AS City,	   
	    [sHostel].[fAssignRoomEmployeeAssetGet](@rHostelId ,@rRoomId,AR.SourceId ) AS AssetNumber,
	    RM.Id AS RoomId,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,		
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
	   (SELECT sum(Total) FROM(SELECT Max(StudentsPerRoom) AS Total FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=95   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON AR.SourceId=EM.Id 
		WHERE ((RM.HostelId=@rHostelId) OR (@rHostelId=0)) AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		Group By RM.Id)A) AS TotalStudentPerRoom
		
	FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=95  AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON AR.SourceId=EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
		LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
		LEFT JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=95 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
	WHERE 
		(HAM.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((EM.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((EM.Code Like @rEmployeeCode) OR (ISNULL(@rEmployeeCode,'')=''))
		AND ((ODM.Id = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHostel].[pRptRoomwiseHostelFeeStudentListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rRoomId int=0,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rDepartmentId int=0,
	 @rStatusId int=0
	 
	 

	 	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as StudentCode,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,
		SA.DivisionName,
		SA.RollNo,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		SC.ParentContactNo,
		SA.OrgId,
		OM.DisplayTitle AS OrganizatinName,
		SA.DivisionId,
		SA.DivisionOrder,
		--@rIsBasedOnSUId AS IsBasedOnSUId,
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
	   (SELECT sum(Total) FROM(SELECT Max(StudentsPerRoom) AS Total FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId 
		WHERE ((RM.HostelId=@rHostelId) OR (@rHostelId=0)) AND  SA.OrgGroupBatchId = @rOrgGroupBatchId AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		GRoup By RM.Id)A) AS TotalStudentPerRoom
		, FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(RCM.RoomCharge,0)AS RoomCharge,
		ISNULL(FA.VariableAmount,0.00) AS VariableAmount,
		ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.TotalReceiptAmount,0.00)AS PendingAmount,
	
		ISNULL(R.TotalReceiptAmount,0)AS PaidAmount,
		R.Id AS ReceiptId,
		SA.AcademicId,
		RM.HostelId,
		RM.Id AS RoomId	
		
	FROM sHostel.tRoomMaster RM 
		INNER JOIN sHostel.tRoomCategoryMaster RCM ON RM.RoomCategoryId = RCM.Id
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId=SC.StudentId
		LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
		LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
	    LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
		INNER JOIN sFee.tFeeSetup FS  ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId 
				AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId AND FHM.Number = 1002
			LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = FS.Id
			LEFT JOIN sFee.tReceipt R ON RD.ReceiptId=R.Id AND R.SourceTypeId=2001 AND R.SourceId = SA.AcademicId

		
	WHERE 
       (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		 AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((SA.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
	    AND BM.IsInContext = 1
		AND (FS.IsOptional=1)
		AND (FS.IsVariable=1)
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)
	
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptRoomwiseStudentListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rRoomId int=0,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rIsBasedOnSUId bit = 0,
	 @rDepartmentId int=0,
	 @rSUId nvarchar(50)='',
	 @rFromAllocateDate date='',
	 @rToAllocateDate Date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 


	SELECT
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as SourceCode,
		SA.Name as SourceName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,
		SA.RollNo,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		SC.ParentContactNo,
		SA.OrgId,
		OM.DisplayTitle AS OrganizatinName,
		SA.DivisionId,
		SA.DivisionOrder,
		@rIsBasedOnSUId AS IsBasedOnSUId,
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
	   (SELECT sum(Total) FROM(SELECT Max(StudentsPerRoom) AS Total FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId 
		WHERE ((RM.HostelId=@rHostelId) OR (@rHostelId=0)) AND  SA.OrgGroupBatchId = @rOrgGroupBatchId AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		GRoup By RM.Id)A) AS TotalStudentPerRoom
		
	FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId AND BM.IsActive = 1
		LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId=SC.StudentId
		LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
		LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
	    LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
	    
	WHERE 
       (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		 AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		--AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	    AND BM.IsInContext = 1
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptStudentDepositListGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int=0,
           @rFromAmount decimal(12,2)=0,
           @rToAmount decimal(12,2)=0,
           @rFromDepositDate date='',
           @rToDepositDate date='',
          -- @rBatchId int,
           @rCode nvarchar(20)='',
           @rHostelId int,
           @rRoomId int=0,
           @rStudentName nvarchar(100)='',
		  @rStudentCode nvarchar(100)='',
		  @rClassId int=0,
		  @rDivisionId int=0,
		  @rIsBasedOnSUId bit = 0,
		  @rDepartmentId int=0,
		  @rSUId nvarchar(50)='',
		  @rOrgGroupBatchId int=0,
		  @rBuilder1 nvarchar(max)='',
	      @rBuilder2 nvarchar(max)='',
	      --@rFromDate date='',
	     -- @rTodate date='',
	      @rFromAllocateDate date,
	       @rToAllocateDate Date
           
AS
SET NOCOUNT ON
 
BEGIN
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rHostelDepositHeadId AS HostelDepositHeadId,
		--DHM.Title AS DepositHeadName,
		(SELECT [sHostel].[fDepositHeadNameGet](@rHostelId,@rHostelDepositHeadId)) AS DepositHeadName,
		ISNULL(SA.StudentId,0) as StudentId,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		ISNULL(D.TotalDeposit,0) AS Deposit,
		ISNULL(A.TotalAdjustment,0) AS Adjustment,
		ISNULL(R.TotalRefund,0) Refund,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		RM.Id AS RoomId,
		RM.Title AS RoomName,
		CASE WHEN @rIsBasedOnSUId=0 THEN SA.Code Else ISNULL(SA.suid,'') END AS SUId
		
  FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
		INNER JOIN sHostel.tRoomMaster RM ON  RM.Id=AR.RoomId 
	    INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
		LEFT JOIN
		(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.StudentId,ISNull(DA.HostelDepositHeadId,0) AS HostelDepositHeadId FROM sHostel.tHostelDepositAdd DA WHERE DA.HostelId = @rHostelId AND  (DA.OrgGroupBatchId=@rOrgGroupBatchId)  AND DA.HostelDepositHeadId=@rHostelDepositHeadId GROUP  BY DA.StudentId,DA.HostelId,HostelDepositHeadId)D 
		ON D.StudentId=SA.StudentId
		LEFT JOIN 
		(SELECT SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.StudentId,ISNULL(AD.HostelDepositHeadId,0) AS HostelDepositHeadId FROM sHostel.tHostelDepositAdjustment AD WHERE AD.HostelId = @rHostelId AND (AD.OrgGroupBatchId=@rOrgGroupBatchId) AND AD.HostelDepositHeadId=@rHostelDepositHeadId GROUP BY AD.StudentId,HostelDepositHeadId)A 
		ON A.StudentId=SA.StudentId
		LEFT JOIN 
		(SELECT SUM(ISNULL(DR.RefundAmount,0)) AS TotalRefund,DR.StudentId,ISNULL(DR.HostelDepositHeadId,0) AS HostelDepositHeadId FROM sHostel.tHostelDepositRefund DR WHERE DR.HostelId = @rHostelId AND (DR.OrgGroupBatchId=@rOrgGroupBatchId) AND  DR.HostelDepositHeadId=@rHostelDepositHeadId GROUP BY DR.StudentId,HostelDepositHeadId)R
		ON R.StudentId=SA.StudentId
    	INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = @rHostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		INNER JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
  WHERE  
		(SA.OrgId=@rOrgId OR @rOrgId=0)
		AND ((SA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
	    AND (HM.Id=@rHostelId)
	    AND (DHM.Id=@rHostelDepositHeadId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND (AR.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (SA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
		AND BM.IsInContext = 1
		--AND ((D.DepositDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		--AND ((D.DepositDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptStudentLedgerGet]
	 
	
	 @rHostelId int,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rHostelDepositHeadId int,
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rOrgGroupBatchId int=0
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 
Declare @lbal decimal
SET @lbal=0;
 select
        A.DepositDate,
        A.Credit,
        A.Debit,
CASE WHEN @rIsBasedOnSUId=0 THEN  A.Code Else ISNULL(A.suid,'') END AS Code,
        A.StudentName,
        RM.Title AS Room,
        A.Class ,
        A.Credit - A.Debit AS Bal
  FROM
 (
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		   VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		   -- @lbal+ISnull (DA.Amount,0)-0 As balance 
		   ISnull(DA.Amount,0)-0 As balance 
		    
			FROM sStudent.vStudentLastAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId 
			Where 
		  ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DA.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.HostelDepositHeadId = @rHostelDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			UNION ALL 
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		    -- @lbal+0-ISnull (DAJ.Amount,0) As balance 
		     0-ISnull(DAJ.Amount,0) As balance 
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId 
		     
			Where 
				((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DAJ.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND DAJ.OrgGroupBatchId=@rOrgGroupBatchId
			AND VA.OrgGroupBatchId=@rOrgGroupBatchId
			UNION ALL 
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    -- @lbal+0-ISnull (DR.RefundAmount,0) As balance 
		    0-ISnull(DR.RefundAmount,0) As balance
			FROM sStudent.vStudentLastAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
		     
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DR.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND DR.OrgGroupBatchId=@rOrgGroupBatchId
			AND VA.OrgGroupBatchId=@rOrgGroupBatchId
			) A
			LEFT JOIN sHostel.tAssignRoom  AR ON AR.SourceId=A.StudentId AND  AR.SourceTypeId = 2003 AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		
			LEFT JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			--Group By A.DepositDate,A.Credit,A.Debit,A.Code,A.SUId,A.StudentName,Rm.title,A.Class,  A.Balance
			order by  A.DepositDate 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptVacantStudentList]
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rHostelId int =0,
		@rOrgId int = 0,
		@rSourceTypeId smallint=0,
		@rCode nvarchar(20)=NULL,
		--@rFromAllocateDate date = '',
		--@rToAllocateDate date ='',
		@rToVacantDate date='',
		@rFromVacantDate date='',
		@rSUID nvarchar(50) = null,
		@rOrgGroupBatchId int = 0,
		@rRoomId int=0,
		@rStudentName nvarchar(100)='',
		@rStudentCode nvarchar(100)='',
		@rClassId int=0,
		@rDivisionId int=0,
		@rIsBasedOnSUId bit = 0,
		@rDepartmentId int=0

 WITH EXECUTE AS CALLER                  
AS
SET NOCOUNT ON
declare @lsumtotal As int=0

BEGIN

	SELECT   
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		OM.DisplayTitle AS OrganizationName,
        (CASE WHEN HA.SourceTypeId = 95 THEN	'Employee'
			 WHEN HA.SourceTypeId = 2003 THEN	'Student' END) AS SourceType,

		(CASE WHEN HA.SourceTypeId = 95 THEN	Emp.Code
			 WHEN HA.SourceTypeId = 2003 THEN	SM.Code END) AS SourceCode, 	
		
		(CASE WHEN HA.SourceTypeId = 95 THEN	''
			 WHEN HA.SourceTypeId = 2003 THEN	SM.SUId END) AS SUId, 	

		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN HA.SourceTypeId = 2003 THEN SM.LastName + ' ' + SM.FirstName  END) AS SourceName,
			
		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN HA.SourceTypeId = 2003 THEN (sStudent.fStudentCurrentDivisionGet(SM.StudentId)) END) AS ClassDepartmentName,		
		 
		 HA.SourceTypeId,
		 HA.SourceId,
		 HA.AllocateDate,
		(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
		 ISNULL(HA.VacantReason,'') AS VacantReason,
		SM.ClassName+'-'+SM.DivisionName as ClassDivisionName,
		SM.ClassId,
		SM.ClassName AS ClassName,
		SM.RollNo,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		ISNULL(RM.Title,'') AS Room,
		SC.ParentContactNo,
		SM.OrgId,
		OM.DisplayTitle AS OrganizatinName,
		SM.DivisionId,
		SM.DivisionOrder,
		@rIsBasedOnSUId AS IsBasedOnSUId,
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2


	FROM 
		sHostel.tHostelAdmission HA
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
		ON Emp.Id = HA.SourceId AND HA.SourceTypeId = 95 
		LEFT JOIN sStudent.vStudentAcademic SM
		ON SM.StudentId = HA.SourceId AND HA.SourceTypeId = 2003 AND SM.OrgGroupBatchId=@rOrgGroupBatchId 	
		LEFT JOIN sSetup.tOrganizationMaster OM ON (OM.Id = SM.OrgId) OR (OM.Id = Emp.OrgId)  
		LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = HA.RoomId 
		--LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		--INNER JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId AND BM.IsActive = 1
		LEFT JOIN sStudent.tStudentCommunication SC ON SM.StudentId=SC.StudentId
		LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
		LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
	WHERE 
		(HA.Hosteld=@rHostelId)
		AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		--AND ((HA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		--AND ((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
		--OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')='')
		AND ((SM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SM.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SM.Code Like @rStudentCode + '%') OR (ISNULL(@rStudentCode,'')=''))
		AND ((SM.FirstName like  @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		--AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
		--AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
		AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
		AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
		AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
		AND HA.OrgGroupBatchId=@rOrgGroupBatchId
		AND HA.VacantDate IS NOT NULL
		--ORDER BY HA.AllocateDate desc
		--GROUP BY HA.RoomId,OM.DisplayTitle,HM.SmallAddress1,HM.SmallAddress2,HM.ReportOrgTitle,SC.ParentContactNo,SM.OrgId,SM.DivisionOrder,SM.DivisionId,HA.SourceTypeId,HM.Title,RM.title,Emp.Code,HTM.Title,SM.Code,SM.SUId,Emp.EmployeeName,SM.FirstName,SM.LastName,Emp.DepartmentName,SM.StudentId,HA.SourceId,HA.AllocateDate,HA.VacantDate,HA.VacantReason,SM.ClassName,SM.DivisionName,SM.ClassId,SM.RollNo,RM.StudentsPerRoom
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pRptVisitorGatePassGet]


		   @rId int,
           --@rFromVisitDate datetime,
           --@rToVisitDate datetime,
           @rHostelId int,
            @rOrgGroupBatchId int
		   --@rVisitorName nvarchar(100),
		   --@rWhomToMeetSourceTypeId smallint,
		   --@rWhomToMeetSourceId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	
	SELECT 
			
			VG.Id,
			VG.VisitorName,
			VG.NoOfVisitor,
			VG.PurposeOfVisit,
			--ISNULL(VG.WhomToMeetName,'') AS WhomToMeetName,
			VG.InTime,
			VG.OutTime,
		    VG.VisitDate,
		    VG.VisitorPhoto, 
			HM.Title AS HostelName,
			CASE WHEN VG.WhomToMeetSourceTypeId=2003 THEN  ISNULL(SM.FirstName,'') 
			     WHEN VG.WhomToMeetSourceTypeId=95 THEN ISNULL(EM.FirstName,'')  ELSE VG.WhomToMeetName END
			       AS Name
	FROM 
			sHostel.tVisitorGatePass VG
			--Left JOIN sCommon.tSourceTypeMaster ST ON ST.Id=VG.WhomToMeetSourceTypeId
			Left JOIN sStudent.vStudentAcademic SM ON SM.StudentId=VG.WhomToMeetSourceId AND VG.WhomToMeetSourceTypeId=2003 AND SM.OrgGroupBatchId = @rOrgGroupBatchId 
			Left JOIN sHrm.tEmployeeMaster EM ON EM.Id=VG.WhomToMeetSourceId AND VG.WhomToMeetSourceTypeId=95
			Left JOIN sHostel.tHostelMaster HM ON HM.Id=VG.HostelId
	WHERE 
			((VG.Id = @rId) OR (@rId = 0))
			AND ((VG.HostelId = @rHostelId) OR (@rHostelId = 0))
			 AND VG.OrgGroupBatchId = @rOrgGroupBatchId  AND  ISNULL(EM.IsOtherUser,0) = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pStudentDetailListGet]
	 
	 @rHostelId int,
	 @rSUId nvarchar(50),
	 @rCode nvarchar(20),
	 @rOrgId int,
	 @rOrgGroupBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			--O.DisplayTitle AS Organization,
			--O.Id AS OrgId,
			RM.Title AS Room,
			SD.Code AS StudentCode,
			SD.Name AS StudentName,
			ISNULL(RAM.AssetNumber,'') AS AssetNumber,
			ISNULL(AM.Title,'') AS AssetType,
			ISNULL(RC.Title,'') As RoomCategory,
			ARA.RoomAssetId ,
			SD.StudentId  AS SourceId,
			AR.SourceTypeId AS SourceTypeId,
			AR.RoomId,
			ISNULL(SC.PresentStreetone,'') + ' ' + ISNULL(SC.PresentStreetTwo,'') + ' ' + ISNULL(SC.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SC.ParentContactNo,'') AS StudentContactNo,
			SD.ClassName + ' ' + SD.DivisionName AS Class,
			Isnull(SD.SUID,'') AS SUID,
			Ar.OrgGroupBatchId
			
			
			
	FROM sStudent.vStudentAcademic SD   
			INNER JOIN sHostel.tAssignRoom AR ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003   AND AR.OrgGroupBatchId=@rOrgGroupBatchId
			LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			INNER JOIN sHostel.tRoomCategoryMaster RC ON RC.ID=RM.RoomCategoryId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
			--INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
	        LEFT JOIN sHostel.tAssignRoomAsset  ARA ON ARA.SourceId=AR.SourceId AND  ARA.SourceTypeId=2003 AND ARA.OrgGroupBatchId=@rOrgGroupBatchId
	        LEFT JOIN sHostel.tRoomAssetMaster RAM ON RAM.Id=ARA.RoomAssetId AND ARA.SourceId=SD.StudentId  
            LEFT JOIN sHostel.tAssetTypeMaster  AM ON RAM.AssetTypeId=AM.Id
	WHERE 
	    HM.Id = @rHostelId
	    AND ((SD.SUID=@rSUId)OR (ISNULL(@rSUId,'')=''))
	    AND ((SD.Code=@rCode)OR (ISNULL(@rCode,'')=''))
	    AND ((SD.OrgId=@rOrgId)OR (ISNULL(@rOrgId,'')=''))
	    AND SD.OrgGroupBatchId=@rOrgGroupBatchId
	    AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	    --AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pStudentLedgerGet]
	 
	
	 @rHostelId int,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rHostelDepositHeadId int,
	 @rOrgId int,
	 @rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 
 SELECT A.Date,
        A.Credit,
        A.Debit
          FROM(
			SELECT 
			DA.DepositDate AS Date,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId 
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DA.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DA.OrgGroupBatchId = @rOrgGroupBatchId
			UNION ALL 
			SELECT 
			DAJ.AdjustmentDate As Date,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId
		     
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DAJ.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DAJ.OrgGroupBatchId = @rOrgGroupBatchId
			UNION ALL 
			SELECT 
			DR.RefundDate As Date,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
		     
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DR.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
		   AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		   AND DR.OrgGroupBatchId = @rOrgGroupBatchId
			)A 
			Order BY A.Date
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pStudentLedgerGet_NEW]

	 @rHostelId int,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rHostelDepositHeadId int,
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
      @rOrgGroupBatchId int
AS
BEGIN

--WITH Tb0 as
--( 
			SELECT A.*, RM.Title AS Room,
         HM.Title As HostelName,
         HM.SmallAddress1 AS SmallAddress1,
         HM.SmallAddress2 AS SmallAddress2,
       HM.ReportOrgTitle AS ReportOrgTitle from (SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		     DA.CreatedDateTime
		    
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId 
			Where 
		  ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DA.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.HostelDepositHeadId = @rHostelDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DA.OrgGroupBatchId = @rOrgGroupBatchId
			
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     DAJ.CreatedDateTime
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId
		     
			Where 
				((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DAJ.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DAJ.OrgGroupBatchId = @rOrgGroupBatchId
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId,
		     DR.CreatedDateTime
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DR.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DR.OrgGroupBatchId = @rOrgGroupBatchId
		    )  A
		   INNER JOIN sHostel.tAssignRoom  AR ON AR.SourceId=A.StudentId AND  AR.SourceTypeId = 2003 AND AR.OrgGroupBatchId = @rOrgGroupBatchId
           INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id
           INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
           ORDER BY CreatedDateTime
--)
--,Tb1 as
--( 
--	SELECT DepositDate,Credit,Debit,Row_Number() over (order by  CreatedDateTime asc) as [OrderId],StudentId,Code,SUId,StudentName,Class FROM Tb0
--)
 
--  SELECT T1.[DepositDate],
--         T1.[Credit],
--         T1.[Debit],(Sum(T2.Credit) - Sum(T2.Debit)) as Balance,
--         CASE WHEN @rIsBasedOnSUId=0 THEN  T1.Code Else ISNULL(T1.SUId,'') END AS Code,
--         T1.StudentName,
--         RM.Title AS Room,
--         T1.Class,
--         HM.Title As HostelName,
--         HM.SmallAddress1 AS SmallAddress1,
--         HM.SmallAddress2 AS SmallAddress2,
--         HM.ReportOrgTitle AS ReportOrgTitle
-- FROM Tb1 as T1
--INNER JOIN Tb1 as T2 ON T1.[OrderId] >= T2.[OrderId] 
--LEFT JOIN sHostel.tAssignRoom  AR ON AR.SourceId=T1.StudentId AND  AR.SourceTypeId = 2003
--LEFT JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id
--LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
--Group By T1.[DepositDate],T1.[Credit],T1.[Debit],T1.StudentId,T1.SUId,T1.Code,T1.StudentName,T1.Class,RM.Title,HM.Title,HM.SmallAddress1,HM.SmallAddress2,
--HM.ReportOrgTitle
-- Order by T1.[DepositDate]
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pUserControlFeePaidStudentSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(50)=''
	--@rHostelId int=0
	--@rIsStudentHostelFeePaid int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
 IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			DISTINCT
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			[sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName, -- Add for Mantis id:0036025
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId,
			SA.FeesRemark -- Changed for Mantis - 32729 by Nilesh
  FROM 
          sStudent.vStudentAcademic SA 
          INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		  INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		  INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId 
		  INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId AND FHM.Number = 1002
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId 
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
		AND ( SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			DISTINCT
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			[sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName, 
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.FeesRemark -- Changed for Mantis - 32729 by Nilesh 
  FROM 
          sStudent.vStudentAcademic SA 
          INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		  INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		  INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId 
		  INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId AND FHM.Number = 1002
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId               
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pUserControlStudentSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(50)='',
	@rHostelId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 

DECLARE @lInContextBatch int
SELECT @lInContextBatch = Id From sSetup.tBatchMaster BM Where BM.OrgGroupBatchId = @rOrgGroupBatchId AND IsInContext = 1


		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END

		IF(@rRollNo=0) 
		SET @rRollNo=NULL

 IF(@rRollNo IS NULL)
	BEGIN

	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			[sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName, -- Add for Mantis id:0036025
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			SA.FeesRemark
  FROM 
          sStudent.vStudentAcademic SA 
          INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND  AR.SourceTypeId=2003
          INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId 
          INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
		  INNER JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId 
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
		AND ( SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
		AND  RM.HostelId=@rHostelId
	  AND ( AR.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)
	  AND BM.IsInContext = 1

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			[sStudent].[fStudentNameGet](SA.FirstName , SA.MiddleName, SA.LastName,OM.StudentNameFormatId ) AS FullName, 
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.FeesRemark
  FROM 
          sStudent.vStudentAcademic SA   
           INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND  AR.SourceTypeId=2003
           INNER JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId   
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId         
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND(SA.BatchId=@rBatchId)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 	
		AND  RM.HostelId=@rHostelId
		  AND ( AR.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pVisitorGatePassAdd]
	@rId int,
	@rHostelId int,
	@rVisitorName [nvarchar](100),
	@rNoOfVisitor [tinyint],
	@rPurposeOfVisit [nvarchar](200),
	@rWhomToMeetSourceTypeId [smallint],
	--@rEmployeeId [int],
	@rWhomToMeetSourceId bigint,
	@rWhomToMeetName nvarchar(100),
	@rInTime time,
	@rOutTime time,
	@rVisitorPhoto varbinary(max)=null,
	@rVisitDate date,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	--IF(@rWhomToMeetSourceTypeId=0)
	--BEGIN
	--	SET @rWhomToMeetSourceId=NULL
	--	SET @rWhomToMeetSourceTypeId=NULL
	--END
	
	--else IF(@rWhomToMeetSourceTypeId=0)
	--BEGIN
	--SET @rWhomToMeetSourceId=NULL
	--END
	
	DECLARE @lNextNumber BIGINT	
	
	IF(@rId = 0)	
	BEGIN
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sHostel.tVisitorGatePass', 0, 101, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO sHostel.tVisitorGatePass
			(
				
				Id,
				HostelId,
				VisitorName,
				NoOfVisitor,
				PurposeOfVisit,
				WhomToMeetSourceTypeId,
				WhomToMeetSourceId,
				WhomToMeetName,
				InTime,
				OutTime,
				VisitorPhoto,
				VisitDate,
				CreatedUserId,
				CreatedDateTime,
			   OrgGroupBatchId
			)
		VALUES
			(
				@lNextNumber,
				@rHostelId,					
				@rVisitorName,
				@rNoOfVisitor,
				@rPurposeOfVisit,
				@rWhomToMeetSourceTypeId,
				@rWhomToMeetSourceId,
				@rWhomToMeetName,
				@rInTime,
				@rOutTime,
				@rVisitorPhoto,
				@rVisitDate,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgGroupBatchId
				 
			)
			SELECT 1 AS Result,@lNextNumber
		END	
	--		IF(@rWhomToMeetSourceTypeId=1  OR  @rWhomToMeetSourceTypeId=95)
	--			BEGIN
	--				IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserOrganization WHERE UserId = @lNextNumber AND OrgId = @rOrgId)
	--					BEGIN
	--						INSERT INTO sSecurity.tUserOrganization
	--						SELECT @rOrgId,@lNextNumber
	--					END
	--			END
	--	END	
			
	--SELECT @lNextNumber AS UserId
	
	ELSE
		BEGIN
			Update sHostel.tVisitorGatePass
				set
					HostelId=@rHostelId,
					VisitorName=@rVisitorName,
					NoOfVisitor=@rNoOfVisitor,
					PurposeOfVisit=@rPurposeOfVisit,
					WhomToMeetSourceTypeId=@rWhomToMeetSourceTypeId,
					WhomToMeetSourceId=@rWhomToMeetSourceId,
					WhomToMeetName=@rWhomToMeetName,
					InTime=@rInTime,
					OutTime=@rOutTime,	
					VisitorPhoto=@rVisitorPhoto,
					VisitDate=@rVisitDate,
					CreatedUserId=@rCreatedUserId
					
			where Id=@rId
			AND HostelId=@rHostelId
			AND OrgGroupBatchId=@rOrgGroupBatchId
		SELECT 11 AS Result
	END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHostel].[pVisitorGatePassGet]


		   @rId int,
           @rFromVisitDate datetime,
           @rToVisitDate datetime,
           @rHostelId int,
		   --@rVisitDate date,
		   @rVisitorName nvarchar(100),
		   @rWhomToMeetSourceTypeId smallint,
		   @rWhomToMeetSourceId bigint,
		   @rOrgGroupBatchId int
	 
	 --@rInDate datetime
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	
	
	SELECT 
			
			VG.Id,
			VG.HostelId,
			VG.VisitorName,
			VG.NoOfVisitor,
			VG.PurposeOfVisit,
			ISNULl(VG.WhomToMeetSourceTypeId,0) AS WhomToMeetSourceTypeId,
			ISNULL (VG.WhomToMeetSourceId,0) AS WhomToMeetSourceId,
			ISNULL(VG.WhomToMeetName,'') AS WhomToMeetName,
			VG.InTime,
			VG.OutTime,
			ISNULL(VG.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
			ISNULL(VG.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			HM.Title AS HostelName,
		    ISNULL(SM.FirstName,'') AS StudentName,
			ISNULL(EM.FirstName,'') AS EmployeeName,
			CASE WhomToMeetSourceTypeId
				WHEN 95 THEN 'Employee'
				WHEN 2003 THEN 'Student'
				ELSE 'Other' END AS SourceType,
		CASE WHEN VG.WhomToMeetSourceTypeId=95 THEN ISNULL(EM.FirstName,'')
				WHEN VG.WhomToMeetSourceTypeId=2003 THEN SM.Name
				ELSE VG.WhomToMeetName END AS Name,
		ISNULL(VG.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto	
	FROM 
		sHostel.tVisitorGatePass VG
			Left JOIN sCommon.tSourceTypeMaster ST ON ST.Id=VG.WhomToMeetSourceTypeId
			Left JOIN sStudent.vStudentAcademic SM ON SM.StudentId=VG.WhomToMeetSourceId AND VG.WhomToMeetSourceTypeId=2003  AND SM.OrgGroupBatchId = @rOrgGroupBatchId 
			Left JOIN sHrm.tEmployeeMaster EM ON EM.Id=VG.WhomToMeetSourceId AND VG.WhomToMeetSourceTypeId=95 AND  ISNULL(EM.IsOtherUser,0) = 0
			Left JOIN sHostel.tHostelMaster HM ON HM.Id=VG.HostelId
	WHERE 
			((VG.Id = @rId) OR (@rId = 0))
		--AND ((VG.VisitorName like @rVisitorName) OR (@rVisitorName=''))
		AND (((@rWhomToMeetSourceTypeId =2003 OR(@rWhomToMeetSourceTypeId=0)) AND SM.FirstName like @rVisitorName) 
		OR (ISNULL(@rVisitorName,'')='') OR ((@rWhomToMeetSourceTypeId =95 OR(@rWhomToMeetSourceTypeId=0)) AND EM.FirstName LIKE @rVisitorName) OR (ISNULL(@rVisitorName,'')='') 
		OR ((@rWhomToMeetSourceTypeId =1 OR (@rWhomToMeetSourceTypeId=0)) AND VG.VisitorName LIKE @rVisitorName) OR (ISNULL(@rVisitorName,'')=''))
		AND ((VG.WhomToMeetSourceTypeId=@rWhomToMeetSourceTypeId) OR (@rWhomToMeetSourceTypeId = 0))
		AND (VG.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
		AND (VG.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
		AND ((VG.HostelId = @rHostelId) OR (@rHostelId = 0))
		 AND VG.OrgGroupBatchId = @rOrgGroupBatchId 
	 
		
		order by  VG.CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pAbsentEmployeeDashboardGet]
	 
	 @rOrgGroupId int=0,
	 @rConfigurationValue int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	DECLARE @rStartDate date
	DECLARE @rEndDate date
	SET @rStartDate = getdate()
	SET @rEndDate = getdate() - @rConfigurationValue
	SELECT
		OM.Id AS OrgId,
		vEM.Code AS Code,
		vEM.EmployeeName,
		COUNT(EAR.EmployeeId) AS AbsentCount
	FROM
		sHrm.tEmployeeAttendanceRegister EAR 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
		INNER JOIN sHrm.vExtEmployeeMaster vEM ON vEM.EmployeeId = EAR.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	WHERE 
		OM.OrgGroupId = @rOrgGroupId
		AND BM.IsActive = 1
		AND EAR.IsPresent = 0
		--AND (EAR.AttendanceDate >= @rEndDate)	
		AND (EAR.AttendanceDate <= @rStartDate)
	GROUP BY OM.Id,vEM.Code,vEM.EmployeeName
	HAVING COUNT(EAR.EmployeeId) >= @rConfigurationValue
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[PAttendanceNotAdd]
	 @rOrgGroupId int=0,
	 @rConfi int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

  BEGIN
	SELECT 
	 top 5 COUNT(*) AS AttendanceNotAddCount
	FROM 
		sStudent.vStudentAllDetail S
			
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pAvailableLeaveEmployeeWise]
(
	@rOrgId int,    
    @rEmployeeId  bigint,  
    @rLeaveTypeId int,     
    @rBatchId int 
 )
AS
SET NOCOUNT ON

BEGIN
    
	   SELECT    
			SUM(NoOfLeave) AS AvailableLeave
       FROM 
			[sHrm].[tLeave] L  
	   WHERE 
			(L.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)      
		AND BatchId = @rBatchId AND L.OrgId = @rOrgId 
		AND L.StatusId = 550 -- apporved
      GROUP BY EmployeeId,LeaveTypeId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pCertificateJoiningAdd]    

	@rId bigint = 0,        
	@rOrgId smallint =0,    
	@rEmployeeId bigint=0,
	@rDepartmentId int=0,  
	@rEmployeeDesignationId int= 0,    
	@rNumber int = 0,    
	@rCertificateDate DATE= NULL,    
	@rDateOfJoining DATE=NULL,    
	@rPayScale nvarchar(150)='',
	@rAgreementPeriod nvarchar(150)='',    
	@rCertificateRemark nvarchar(500)='', 
	@rRemark nvarchar(500)='',   
	@rUserId bigint =0

WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN    
	BEGIN TRY     
	BEGIN TRANSACTION     

	IF(@rNumber = 0) 
	BEGIN
		SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sHrm.tCertificateJoining WHERE OrgId=@rOrgId
	END     
       
	IF(@rId = 0)     
	BEGIN 
		IF EXISTS(SELECT 1 FROM sHrm.tCertificateJoining WHERE Number=@rNumber AND OrgId=@rOrgId)    
		BEGIN    
			SELECT -103 AS Result    
			RETURN    
		END   
	END
	     
	DECLARE @lNextNumber BIGINT   
   
	IF(@rId = 0)     
	BEGIN 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCertificateJoining', 0, 1, 1,@outNextNumber = @lNextNumber output     
 
		INSERT INTO sHrm.tCertificateJoining     
		(      
			Id
			,OrgId    
			,EmployeeId 
			,DepartmentId
			,EmployeeDesignationId   
			,Number    
			,CertificateDate
			,DateOfJoining
			,Payscale   
			,AgreementPeriod
			,CertificateRemark       
			,Remark    
			,CreatedUserId    
			,CreatedDateTime
		)    
		VALUES     
		( 
			 @lNextNumber 
			,@rOrgId   
			,@rEmployeeId 
			,@rDepartmentId
			,@rEmployeeDesignationId
			,@rNumber    
			,@rCertificateDate     
			,@rDateofJoining    
			,@rPayScale     
			,@rAgreementPeriod    
			,@rCertificateRemark    
			,@rRemark        
			,@rUserId    
			,sCommon.fGetDate()
		)    
		SELECT 1 AS Result 
	END    
	ELSE    
	BEGIN    
		SET @lNextNumber = @rId 

		UPDATE sHrm.tCertificateJoining    
		SET    
		EmployeeId=@rEmployeeId,
		DepartmentId= @rDepartmentId, 
		EmployeeDesignationId=@rEmployeeDesignationId,
		Number=@rNumber,       
		CertificateDate=@rCertificateDate,
		DateOfJoining=@rDateOfJoining,
		PayScale=@rPayScale,
		AgreementPeriod=@rAgreementPeriod,
		CertificateRemark=@rCertificateRemark,
		Remark=@rRemark,
		UpdatedUserId=@rUserId,
		UpdatedDateTime=sCommon.fGetDate()
		WHERE Id = @rId    
	END
	SELECT 11 AS Result 
      
	SELECT @lNextNumber AS Result    
     
	COMMIT TRANSACTION    
	END TRY    
	BEGIN CATCH     
	ROLLBACK TRANSACTION    
	SELECT -1 AS Result    
	END CATCH     
     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pClubHouseCommiteeBulkAdd]    
  --@rId bigint = 0,    
  @rTypeId int = 0,
  @rEmployeeId bigint=0,
  @rTypeDetailId int = 0

WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN    
  DECLARE @lNextNumber BIGINT
  
  --IF(@rId = 0)     
  --BEGIN 

	  IF(@rTypeId = 1)
	  IF NOT EXISTS(SELECT 1 FROM [sHrm].[tAssignClub] WHERE EmployeeId=@rEmployeeId )
	  BEGIN   
	  	 INSERT INTO sHrm.tAssignClub     
			(      
			 ClubId   
			,EmployeeId        
			)    
			VALUES     
			( 
			 @rTypeDetailId    
			,@rEmployeeId    
			)    
		 SELECT 1 AS Result 
	  END
	  ELSE
	   BEGIN
	     SET @lNextNumber = @rTypeDetailId 
         UPDATE  sHrm.tAssignClub   
         SET    
         ClubId=@rTypeDetailId
     WHERE EmployeeId = @rEmployeeId    
       SELECT 1 AS Result
   END  

      IF(@rTypeId = 2)
	  IF NOT EXISTS(SELECT 1 FROM [sHrm].[tAssignHouse] WHERE EmployeeId=@rEmployeeId )
	  BEGIN   
	  	 INSERT INTO sHrm.tAssignHouse     
			(      
			 HouseId  
			,EmployeeId        
			)    
			VALUES     
			( 
			 @rTypeDetailId    
			,@rEmployeeId    
			)    
		 SELECT 1 AS Result 
	  END
	  ELSE
	   BEGIN
	    SET @lNextNumber = @rTypeDetailId 
        UPDATE  sHrm.tAssignHouse   
        SET    
        HouseId=@rTypeDetailId
    WHERE EmployeeId = @rEmployeeId    
       SELECT 1 AS Result
   END  

      IF(@rTypeId = 3)
	  IF NOT EXISTS(SELECT 1 FROM [sHrm].[tAssignCommittee] WHERE EmployeeId=@rEmployeeId )
	  BEGIN   
	  	 INSERT INTO sHrm.tAssignCommittee     
			(      
			 CommitteeId  
			,EmployeeId        
			)    
			VALUES     
			( 
			 @rTypeDetailId    
			,@rEmployeeId    
			)    
		 SELECT 1 AS Result 
	  END
	  ELSE
	   BEGIN
	    SET @lNextNumber = @rTypeDetailId 
        UPDATE  sHrm.tAssignCommittee   
        SET    
        CommitteeId=@rTypeDetailId
    WHERE EmployeeId = @rEmployeeId    
       SELECT 1 AS Result
   END  
 --END 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pCustomTagMasterAdd]
	 
	@rOrgGroupId int,	
	@rId int,
	@rNumber int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rCreatedUserId bigint,
	@rOrderIndex smallint,
	@rIsObsolete bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	-- For New Entry
	IF(@rId = 0)
		BEGIN
			If Exists(select Id from sHrm.tCustomTagMaster where Code=@rCode AND OrgGroupId= @rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
			END 
	 
		END
	-- For Update Entry	
	ELSE
		BEGIN
			If  Exists(select Id from sHrm.tCustomTagMaster where Code=@rCode AND Id<>@rId AND OrgGroupId= @rOrgGroupId)
			Begin
				select -103 as Result
				RETURN
			End
		END
BEGIN TRY
BEGIN TRANSACTION	
 IF(@rId = 0)	
 BEGIN
	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHrm.tCustomTagMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO  sHrm.tCustomTagMaster
		(
			 OrgGroupId,
			 Id,
			 Number,
			 Code,
			 Title,
			 CreatedUserId,
			 CreatedDateTime,
			 OrderIndex,
			 IsObsolete
		)
	VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
			@rNumber,
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrderIndex,
			@rIsObsolete
		)
		    SELECT 1 AS Result          
	END	 
ELSE
    BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sHrm.tCustomTagMaster
	    SET
	         Number=@rNumber,
			 Code=@rCode,
			 Title=@rTitle,
			 OrderIndex=@rOrderIndex,
			 IsObsolete=@rIsObsolete,
			 UpdatedUserId=@rCreatedUserId,
			 UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT 11 AS Result
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pCustomTagMasterGet]
	
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
END	 

BEGIN 

	SELECT 
	
	CTM.Id, 
	CTM.Code,
	CTM.Number,
	CTM.Title,
	CTM.IsObsolete,
	CTM.OrderIndex 
     
  FROM sHrm.tCustomTagMaster CTM         
             
  WHERE 
	  CTM.OrgGroupId = @rOrgGroupId		
      AND ((CTM.Id = @rId) OR (@rId = 0))
      AND ((CTM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))    
      AND ((CTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	  Order By CTM.OrderIndex DESC   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pDetailEmployeeModelGet]
	 
  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 Em.Id,
		 Em.FirstName + ' ' + EM.LastName AS FullName,
		 Gm.Title As Gender,
		 EC.CompanyEmail As Email, 
		 EC.MobileNumber ,
		 EPD.DateOfBirth
  FROM 
		  sHrm.tEmployeeMaster EM 
		  INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tGenderMaster Gm ON GM.Id = EPD.Genderid
		  INNER JOIn sHrm.tEmployeeCommunications Ec ON Ec.EmployeeID = EM.Id
		  WHERE  ISNULL(EM.IsOtherUser,0) = 0 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormChangeListGet]

	  @rId int=0,
	  @rOrgId smallint=0,
	  @rEmployeeCode nvarchar(100),
	  @rDepartmentId bigint=0,
	  @rFormStatusId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 
		SELECT 
			(SELECT MAX(AutoId) FROM sHrm.tDigitalFormEmployee WHERE DigitalFormId = DF.Id AND EmployeeId = DFS.EmployeeId) as Id,
			DF.Id as DigitalFormId,
			DF.Code,
			DF.Title,
			ECD.EmployeeId,
			ECD.Code as EmployeeCode,
			ECD.EmployeeName AS Name,
			ECD.DepartmentName AS DepartmentName,
			ISNULL(DFES.StatusId, 0) AS DigitalFormStatusId,
			ISNULL(SM.Title, '') AS DigitalFormStatus,
			ISNULL(DFES.ActionDateTime, '') AS FormActionDateTime
		FROM 
			sHrm.tDigitalForm DF
			INNER JOIN (SELECT DigitalFormId,EmployeeId FROM sHrm.tDigitalFormEmployee GROUP By EmployeeId,DigitalFormId) DFS ON DFS.DigitalFormId = DF.Id
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = DFS.EmployeeId
			LEFT JOIN [sHrm].[tDigitalFormEmployeeStatus] DFES ON DFES.DigitalFormId = DF.Id AND DFES.EmployeeId = ECD.EmployeeId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = DFES.StatusId
		WHERE 
			((DF.OrgId = @rOrgId)OR (@rOrgId=0))
			AND ((DF.Id = @rId) OR (@rId = 0))		
			AND ((ECD.Code = @rEmployeeCode) OR (@rEmployeeCode=''))
			AND ((ECD.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((ECD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND (DFES.StatusId = @rFormStatusId OR @rFormStatusId = 0)
	   ORDER BY Id Asc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormChangeRequestAdd]
			@rEmployeeId Bigint = 0,
			@rDigitalFormId int,
			@rUpdateFieldId int=0,
			@rFieldTypeId int,
			@rOldValue NVarchar(500)='',
			@rNewValue NVarchar(500)='',
			@rRemark nvarchar(500) = '',
			@rCreatedUserId BigInt,
			@rStatusId int,
			@rOldValueImage varbinary(Max) = 0x00000000,
			@rNewValueImage Varbinary(Max) = 0x00000000
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

		BEGIN

		IF(@rUpdateFieldId IN (7055,7056,7057,7058,7064))
		BEGIN
			IF NOT EXISTS (SELECT 1 FROM sHrm.tDigitalFormEmployee WHERE DigitalFormId = @rDigitalFormId AND EmployeeId = @rEmployeeId AND FieldTypeId = @rFieldTypeId AND UpdateFieldId = @rUpdateFieldId)
				BEGIN
				INSERT INTO sHrm.tDigitalFormEmployee
					(
					DigitalFormId,
					EmployeeId,
					FieldTypeId,
					UpdateFieldId,
					NewValue,
					OldValueImage,
					NewValueImage,
					StatusId,
					Remark,
					CreatedUserId,
					CreatedDateTime
					)
				Values
					(
					@rDigitalFormId,
					@rEmployeeId,
					@rFieldTypeId,
					@rUpdateFieldId,
					@rNewValue,
					@rOldValueImage,
					@rNewValueImage,
					@rStatusId,
					@rRemark,
					@rCreatedUserId,
					sCommon.fGetDate()
					)

				
				END
			ELSE
			BEGIN
				UPDATE 
					sHrm.tDigitalFormEmployee
				SET
					NewValueImage = @rNewValueImage
					,Remark = @rRemark
					,CreatedUserId = @rCreatedUserId
					,CreatedDateTime = sCommon.fGetDate()
					,StatusId = @rStatusId
				WHERE
					DigitalFormId = @rDigitalFormId 
					AND EmployeeId = @rEmployeeId
					AND FieldTypeId = @rFieldTypeId 
					AND UpdateFieldId = @rUpdateFieldId
			END
		END
		ELSE
		BEGIN
			IF NOT EXISTS (SELECT 1 FROM sHrm.tDigitalFormEmployee WHERE DigitalFormId = @rDigitalFormId AND EmployeeId = @rEmployeeId AND FieldTypeId = @rFieldTypeId AND UpdateFieldId = @rUpdateFieldId)
			BEGIN
			INSERT INTO sHrm.tDigitalFormEmployee
				(
				DigitalFormId,
				EmployeeId,
				FieldTypeId,
				UpdateFieldId,
				OldValue,
				NewValue,
				StatusId,
				Remark,
				CreatedUserId,
				CreatedDateTime
				)
			Values
				(
				@rDigitalFormId,
				@rEmployeeId,
				@rFieldTypeId,
				@rUpdateFieldId,
				@rOldValue,
				@rNewValue,
				@rStatusId,
				@rRemark,
				@rCreatedUserId,
				sCommon.fGetDate()
				)

			
			END
			ELSE
			BEGIN
			UPDATE 
				sHrm.tDigitalFormEmployee
			SET
				NewValue = @rNewValue
				,Remark = @rRemark
				,CreatedUserId = @rCreatedUserId
				,CreatedDateTime = sCommon.fGetDate()
				,StatusId = @rStatusId
			WHERE
				DigitalFormId = @rDigitalFormId 
				AND EmployeeId = @rEmployeeId 
				AND FieldTypeId = @rFieldTypeId 
				AND UpdateFieldId = @rUpdateFieldId
			END
		END
		
		SELECT 1 AS Result
		END
		
		COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormCustomFieldApprove]	 
	@rId Bigint = 0,
	@rOldValue NVarchar(500)='',
	@rNewValue NVarchar(500)='',
	@rActionRemark nvarchar(500) = '',
	@rActionUserId BigInt,
	@rActionDateTime DateTime,
	@rStatusId int,
	@rRequestId int =0,
	@rOrgId int = 0,
	@rCustomFieldId nvarchar(100)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN
	IF EXISTS(SELECT 1 FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)
	BEGIN
		 DECLARE @lEmployeeId BigInt
		 SET @lEmployeeId = (SELECT EmployeeId FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)

		 Declare @Sql nvarchar(max)
		 DECLARE @lResult int
		 IF OBJECT_ID('ListofEmpData') IS NOT NULL	
				BEGIN 
					DROP TABLE ListofEmpData
				END	

		IF(@rStatusId = 550)
			BEGIN
			CREATE TABLE ListofEmpData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
			insert into ListofEmpData VALUES (@rId,@lEmployeeId,@rNewValue,@rCustomFieldId,@rActionUserId,0)
	 --SELECT * FROM ListofEmpData
		UPDATE LD SET IsExist=1 
		   FROM sHrm.tEmployeeCustomFieldData SC
		      LEFT JOIN ListofEmpData LD ON SC.EmployeeId=LD.EmployeeId 
		      AND  EXISTS (SELECT EmployeeCustomFieldId FROM sHrm.tEmployeeCustomFieldData WHERE EmployeeId=LD.EmployeeId AND EmployeeCustomFieldId = LD.CustomFieldId) 
		
		
		set @sql='INSERT INTO sHrm.tEmployeeCustomFieldData
					(EmployeeId,EmployeeCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofEmpData LD WHERE LD.IsExist=0'
			
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCustomFieldData SC 
					INNER JOIN ListofEmpData LD ON SC.EmployeeId=LD.EmployeeId AND SC.EmployeeCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofEmpData
			 SET @lResult = 1;
	      IF(@lResult = 1)
			BEGIN
				UPDATE sHrm.tDigitalFormEmployee
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 1 AS Result
		END 
		ELSE IF(@rStatusId = 551)
		BEGIN
			CREATE TABLE ListofEmpData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
			insert into ListofEmpData VALUES (@rId,@lEmployeeId,@rOldValue,@rCustomFieldId,@rActionUserId,0)
	 
		UPDATE LD SET IsExist=1 
		   FROM sHrm.tSEmployeeCustomFieldData SC
		      LEFT JOIN ListofEmpData LD ON SC.EmployeeId=LD.EmployeeId 
		      AND  EXISTS (SELECT EmployeeCustomFieldId FROM sHrm.tEmployeeCustomFieldData WHERE EmployeeId=LD.EmployeeId AND EmployeeCustomFieldId = LD.CustomFieldId) 
		
		
		set @sql='INSERT INTO sHrm.tEmployeeCustomFieldData
					(EmployeeId,EmployeeCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofEmpData LD WHERE LD.IsExist=0'
			
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCustomFieldData SC 
					INNER JOIN ListofEmpData LD ON SC.EmployeeId=LD.EmployeeId AND SC.EmployeeCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofEmpData
			 SET @lResult = 1;
	      IF(@lResult = 1)
			BEGIN
				UPDATE sHrm.tDigitalFormEmployee
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 2 AS Result
		END
	END
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormEmployeeCustomFieldsDataGet]
	 		
	 @rEmployeeId bigint,	 
	 @rSubCategoryId int
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=FieldTypeId FROM sHrm.tEmployeeCustomFieldMaster WHERE Id=@rSubCategoryId
		
		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		 --0038705 : By Krunal K Patel -- Added FieldTypeId=5 
		 --IF(@lDataTypeId=3)   --For Free Text and Numeric
		 --BEGIN
		 
		     SET @Sql = 'select *from (Select Row_Number() OVER (PARTITION BY ECD.EmployeeId ORDER BY CASE WHEN ECF.FieldTypeId IS NOT NULL THEN ECF.FieldTypeId END Desc) as RowNumber, ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
		            CASE WHEN ECF.FieldTypeId=3 OR ECF.FieldTypeId=4 THEN
					ISNULL(EC.FieldData,'''') 
					WHEN ECF.FieldTypeId=2 THEN
					ISNULL(EC.FieldData,''0'')
					WHEN ECF.FieldTypeId=1 THEN
					ISNULL(EC.FieldData,''False'')
				    WHEN ECF.FieldTypeId=5 THEN
					ISNULL(EC.FieldData,'''') 				
					END AS SubCategory
			FROM 
		       
				 sHrm.vEmployeeCommonDetail ECD
		         LEFT JOIN sHrm.tEmployeeCustomFieldData EC ON EC.EmployeeId=ECD.EmployeeId
		         LEFT JOIN sHrm.tEmployeeCustomFieldMaster ECF ON ECF.Id=EC.EmployeeCustomFieldId AND ECF.FieldTypeId='''+@lDataTypeId+'''  AND ECF.Id= '''+CAST(@rSubCategoryId AS nvarchar(15))+''' AND ECF.IsObsolete=0 
		         
		    Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+') AS a where RowNumber =1'     
		 		
		  print @Sql		
		   		
			EXECUTE  sp_executesql @Sql		
	   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormEmployeeListGet]
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int 
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	IF(@rSourceTypeId = 95)
	BEGIN
	 DECLARE @lOrgId int,@lDepartmentId int,@lEmployeeId bigint
	

	 SELECT @lEmployeeId = ECD.EmployeeId,@lOrgId = ECD.OrgId,@lDepartmentId = ECD.DepartmentId
     FROM sHrm.vEmployeeCommonDetail ECD
     WHERE ECD.EmployeeId = @rSourceId AND ECD.OrgId = @rOrgId

     SELECT 
			 DF.Id,
			 DF.Code,
			 DF.Title,
			 DF.IsObsolete,
			 CONVERT(nvarchar,DF.CreatedDateTime,103) as CreatedDateTime, 
			 CASE WHEN U.SourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = U.SourceId )
			 WHEN U.SourceTypeId = 2003 THEN (SELECT FirstName+''+LastName as Name FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id WHERE A.Id = U.SourceId ) ELSE 'Admin' END As CreatedBy,
			 0 as Submitted,
			 0 as NotSubmitted,
			ISNULL(DFES.StatusId, 0) AS DigitalFormStatusId,
			ISNULL(SM.Title, '') AS DigitalFormStatus,
			ISNULL(DFES.VerifyDateTime, '') AS FormActionDateTime
     FROM 
		    [sHrm].[tDigitalForm] DF
			INNER JOIN sSecurity.tUser U ON DF.CreatedUserId = U.Id
			INNER JOIN (SELECT DFS.DigitalFormId FROM sHrm.tDigitalFormScope DFS
			WHERE (
			( 
			(DFS.SourceTypeId = 2021 AND DFS.SourceId =@lOrgId) 
			OR
			(DFS.SourceTypeId = 2017 AND DFS.SourceId =@lDepartmentId) OR
			--(DFS.SourceTypeId = 2016 AND DFS.SourceId =@lClassId) OR
			--(DFS.SourceTypeId = 2005 AND DFS.SourceId =@lDivisionId) OR
			(DFS.SourceTypeId = 95 AND DFS.SourceId =@lEmployeeId)
			--(DFS.SourceTypeId = 2001 AND DFS.SourceId =@lAcademicId)
				))
			) D
			ON D.DigitalFormId= DF.Id
			LEFT JOIN [sHrm].[tDigitalFormEmployeeStatus] DFES ON DFES.DigitalFormId = DF.Id AND DFES.EmployeeId = @lEmployeeId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = DFES.StatusId
	 WHERE
			DF.IsObsolete = 0
	 
	END 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormEmployeeStatusAdd]
	@rDigitalFormId int, 
	@rSourceId bigint,
	@rSourceTypeId smallint,
	@rStatusId smallint,
	@rCreatedUserId bigint,
	@rActionDateTime datetime = null,
	@rVerifyDateTime datetime = null,
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		IF @rSourceTypeId > 0
		BEGIN
			INSERT INTO [sHrm].[tDigitalFormEmployeeStatus]
			(
				DigitalFormId
				,EmployeeId
				,StatusId
				,CreatedUserId
				,ActionDateTime
				,VerifyDateTime
			)
			SELECT 
				@rDigitalFormId,
				EmployeeId,
				@rStatusId,
				@rCreatedUserId,
				@rActionDateTime,
				@rVerifyDateTime
			 FROM 
				sHrm.vEmployeeCommonDetail ECD
			 WHERE 
				
				@rSourceId = CASE WHEN @rSourceTypeId = 2017 THEN DepartmentId
									WHEN @rSourceTypeId = 95 THEN EmployeeId
									END
				AND OrgId=@rOrgId
		END	

		SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormFieldAdd]
			@rDigitalFormId bigint
           ,@rFieldTypeId smallint
           ,@rUpdateFieldId int
             
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN  
		IF EXISTS (SELECT 1 FROM sHrm.tDigitalFormField WHERE DigitalFormId = @rDigitalFormId AND FieldTypeId = @rFieldTypeId AND UpdateFieldId = @rUpdateFieldId)
		BEGIN
			SELECT -103 as Result
		END
		ELSE
		BEGIN
			INSERT INTO sHrm.tDigitalFormField
			(
				DigitalFormId
			   ,FieldTypeId
			   ,UpdateFieldId
			    
			)
			VALUES
			(	
				@rDigitalFormId
			   ,@rFieldTypeId
			   ,@rUpdateFieldId
			    
			)		
			SELECT 1 AS Result
		END 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormFieldApprove]
			@rId BIGINT = 0,
			@rUpdateFieldId INT=0,
			@rOldValue NVARCHAR(500)='',
			@rNewValue NVARCHAR(500)='',
			@rActionRemark NVARCHAR(500) = '',
			@rActionUserId BIGINT,
			@rActionDateTime DATETIME,
			@rStatusId INT,
			@rRequestId INT =0,
			@rOldValueImage VARBINARY(MAX) = 0x00000000,
			@rNewValueImage VARBINARY(MAX) = 0x00000000
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

		IF EXISTS(SELECT 1 FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)
		BEGIN
		    
			DECLARE @lResult INT
			DECLARE @lDataTypeId NVARCHAR(1)
			SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Id=@rUpdateFieldId

			IF(@lDataTypeId = 4)
			BEGIN
				SET @rNewValue = CONVERT(DATETIME,@rNewValue,104)
				SET @rOldValue = CONVERT(DATETIME,@rOldValue,104)
			END

			DECLARE @lUpdateField NVARCHAR(100)
			DECLARE @lUpdateFieldImage VARBINARY(MAX)
			DECLARE @lSubFunctionality NVARCHAR(100)
			DECLARE @lEmployeeId BIGINT

			SET @lUpdateField = (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)

			SET @lSubFunctionality = (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)
			SET @lEmployeeId = (SELECT EmployeeId FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)

			IF(@lUpdateField = 'Gender' OR @lUpdateField = 'Religion' OR @lUpdateField = 'MaritalStatus' OR @lUpdateField = 'BloodGroup' 
			 OR @lUpdateField = 'EmployeeDesignation' OR @lUpdateField = 'OrganizationDepartment' OR @lUpdateField = 'EmployeeType' 
			 OR @lUpdateField = 'EmployeeGroup' OR @lUpdateField = 'EmployeeGrade' OR @lUpdateField = 'OrgGroupDepartment' 
			 OR @lUpdateField = 'EmployeeManager'  OR @lUpdateField = 'Payroll' OR  @lUpdateField = 'PayrollGroup' OR @lUpdateField = 'Tribe')
			
			BEGIN
			SET @lUpdateField =@lUpdateField + 'Id'
			END
			IF(@lUpdateField = 'OrganizationHeadManager' )
			BEGIN
				SET @lUpdateField = 'EmployeeBusinessHeadId'
			END
			IF(@lUpdateField = 'CasteCategory' )
			BEGIN
			SET @lUpdateField = REPLACE(@lUpdateField,'Caste','Cast') + 'Id'
			END
			
			IF(@lUpdateField = 'FamilyCast' )
			BEGIN
				SET @lUpdateField = REPLACE(@lUpdateField,'Caste','Cast') 
			END
	
			Declare @Sql nvarchar(MAX)

			IF OBJECT_ID('ListofEmpData') IS NOT NULL	
			BEGIN 
				DROP TABLE ListofEmpData
			END	
			
			--Select @lSubFunctionality	
			IF(@rStatusId = 550)
			BEGIN
				
				IF(@lSubFunctionality = 'EmployeeImage')
				-----------------EmployeeImage--------------
					BEGIN
						IF(@lUpdateField = 'EmployeeImage')
						BEGIN
							SET @lUpdateField = 'EmployeePhoto'
						END

						CREATE TABLE ListofData(Id BIGINT,EmployeeId BIGINT,SubCategory VARBINARY(MAX),UpdatedUserId BIGINT,IsExist BIT);
						INSERT INTO ListofData VALUES (@rId,@lEmployeeId,@rNewValueImage,@rActionUserId,0)

						UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeImages)

						SET @sql='INSERT INTO sHrm.tEmployeeImages 
								(EmployeeId,'+@lUpdateField+',EmployeeSign,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,Ld.SubCategory,sCommon.fGetDate()
								FROM
									ListofData LD WHERE LD.IsExist=1'
					
						PRINT @sql		
						EXEC sp_executesql @sql
						SET  @sql='UPDATE sHrm.tEmployeeImages  set '+@lUpdateField+' = LD.SubCategory,
									EmployeeSign = LD.SubCategory,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeImages  EI 
									INNER JOIN ListofData LD ON EI.EmployeeId=LD.EmployeeId AND IsExist=0'
		
						EXEC sp_executesql @sql

						DROP TABLE ListofData
						SET @lResult = 1;
					END

				ELSE

				BEGIN

					CREATE TABLE ListofEmpData(Id BIGINT,EmployeeId BIGINT,SubCategory NVARCHAR(150),UpdatedUserId BIGINT,IsExist BIT);
					INSERT INTO ListofEmpData VALUES (@rId,@lEmployeeId,@rNewValue,@rActionUserId,0)
		
					IF(@lSubFunctionality = 'EmployeeCommunication')  ----EmployeeCommunication
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
								SET @sql='INSERT INTO sHrm.tEmployeeCommunications 
											(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
											SELECT
												LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
											FROM
												ListofEmpData LD WHERE LD.IsExist=1'
									
								PRINT @sql		
								EXEC sp_executesql @sql
								SET @sql='UPDATE sHrm.tEmployeeCommunications set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeeCommunications EC 
											INNER JOIN ListofEmpData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
								EXEC sp_executesql @sql
	
		
								DROP TABLE ListofEmpData
									 SET @lResult = 1;
						END
						
					ELSE IF(@lSubFunctionality = 'EmployeeOther')         -------EmployeeOther
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
			
								IF(@lUpdateField = 'DateOfBirth')
								BEGIN			
									SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail 
											(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
											SELECT
												LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
											FROM
												ListofEmpData LD WHERE LD.IsExist=1'
									EXEC sp_executesql @sql				
			 							
									SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
												UpdatedUserId=LD.UpdatedUserId,
												UpdatedDateTime=sCommon.fGetDate()  
												from sHrm.tEmployeePersonalDetail EPD 
												INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'			
									EXEC sp_executesql @sql
									SET @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
									EXEC sp_executesql @sql
								END
								ELSE
								BEGIN
									SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail
												(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
												SELECT
													LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
												FROM
													ListofEmpData LD WHERE LD.IsExist=1'
									EXEC sp_executesql @sql				
			 							
									SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
												UpdatedUserId=LD.UpdatedUserId,
												UpdatedDateTime=sCommon.fGetDate()  
												from sHrm.tEmployeePersonalDetail EPD 
												INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'
									
									EXEC sp_executesql @sql
									
								END
								DROP TABLE ListofEmpData
									 SET @lResult = 1;
						END	
							
					ELSE IF(@lSubFunctionality = 'JobDetail')		--------JobDetail
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeJobDetail) 
							IF(@lUpdateField = 'DateOfJoining')
							BEGIN			
								SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
								EXEC sp_executesql @sql				
			 						
								SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeeJobDetail  EJD 
											INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
								EXEC sp_executesql @sql
								SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfJoining=''1900-01-01'''
								EXEC sp_executesql @sql
							END
					ELSE IF(@lUpdateField = 'DateOfleaving')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfleaving=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'ProbationUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE ProbationUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'AhdocUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
							 		UpdatedUserId=LD.UpdatedUserId,
							 		UpdatedDateTime=sCommon.fGetDate()  
							 		from sHrm.tEmployeeJobDetail  EJD 
							 		INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE AhdocUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'PermanentDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE PermanentDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE
					BEGIN
						SET  @sql='INSERT INTO sHrm.tEmployeeJobDetail
							 		(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'
			
						EXEC sp_executesql @sql
					END
					DROP TABLE ListofEmpData
						 SET @lResult = 1;
					END	

					ELSE IF(@lSubFunctionality = 'EmployeeGeneral')			---------EmployeeGeneral
						BEGIN
						
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT Id FROM sHrm.tEmployeeMaster) 
							-- MantisId : 	0029269 Add EUID
							SET  @sql='INSERT INTO sHrm.tEmployeeMaster
										(Id,'+@lUpdateField+',CreatedUserId,CreatedDateTime,EUId)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate(),LD.EmployeeId
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'				 
							EXEC sp_executesql @sql
							SET  @sql='UPDATE sHrm.tEmployeeMaster set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeMaster EM 
										INNER JOIN ListofEmpData LD ON EM.Id=LD.EmployeeId AND IsExist=0'
		
							EXEC sp_executesql @sql
					
							DROP TABLE ListofEmpData
								 SET @lResult = 1;
						END
						--Add IsVPFDeduction because table not allow to insert null value in IsVPFDeduction column  mantisid -- 0032446
					ELSE IF(@lSubFunctionality = 'Statutory')	   ----------Statutory
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
							SET @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
										(EmployeeId,IsVPFDeduction,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,0,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'				
							EXEC sp_executesql @sql
							
							SET @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeeStatutoryAndOther ES 
											INNER JOIN ListofEmpData LD ON ES.EmployeeId=LD.EmployeeId AND IsExist=0'

							EXEC sp_executesql @sql
							 
							DROP TABLE ListofEmpData
							 SET @lResult = 1;
						END
				END	

				IF(@lResult = 1)
				BEGIN
					UPDATE sHrm.tDigitalFormEmployee
					SET
						StatusId = @rStatusId
						,ActionRemark = @rActionRemark
						,ActionUserId = @rActionUserId
						,ActionDateTime = @rActionDateTime
					WHERE 
						AutoId = @rRequestId
				END
			
				SELECT 1 AS Result
			END

			ELSE IF(@rStatusId = 551)
			IF(@lSubFunctionality = 'EmployeeImage')
				BEGIN
					IF(@lUpdateField = 'EmployeeImage')
						BEGIN
							SET @lUpdateField = 'EmployeePhoto'
						END

					CREATE TABLE ListofData(Id BIGINT,EmployeeId BIGINT,SubCategory VARBINARY(MAX),UpdatedUserId BIGINT,IsExist BIT);
					INSERT INTO ListofData VALUES (@rId,@lEmployeeId,@rOldValueImage,@rActionUserId,0)

					UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeImages)

					SET @sql='INSERT INTO sHrm.tEmployeeImages 
						(EmployeeId,'+@lUpdateField+',EmployeeSign,UpdatedDateTime)
						SELECT
							LD.EmployeeId,Ld.SubCategory,Ld.SubCategory,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'

					EXEC sp_executesql @sql

					DROP TABLE ListofData
					SET @lResult = 1;
				END

			ELSE
			BEGIN

				CREATE TABLE ListofEmpData(Id BIGINT,EmployeeId BIGINT,SubCategory NVARCHAR(150),UpdatedUserId BIGINT,IsExist BIT);
				INSERT INTO ListofEmpData VALUES (@rId,@lEmployeeId,@rNewValue,@rActionUserId,0)

			--UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
			
				IF(@lSubFunctionality = 'EmployeeCommunication')  ----EmployeeCommunication
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
							SET  @sql='INSERT INTO sHrm.tEmployeeCommunications 
										(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
								
							PRINT @sql		
							EXEC sp_executesql @sql
							SET  @sql='UPDATE sHrm.tEmployeeCommunications set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeCommunications EC 
										INNER JOIN ListofEmpData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
							EXEC sp_executesql @sql
	
		
							DROP TABLE ListofEmpData
								 SET @lResult = 1;
						END
					
				ELSE IF(@lSubFunctionality = 'EmployeeOther')         -------EmployeeOther
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
							IF(@lUpdateField = 'DateOfBirth')
							BEGIN			
								SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail 
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
								EXEC sp_executesql @sql				
			 						
								SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeePersonalDetail EPD 
											INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'			
								EXEC sp_executesql @sql
								SET @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
								EXEC sp_executesql @sql
						END
					ELSE
						BEGIN
							SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeePersonalDetail EPD 
										INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'
			
							EXEC sp_executesql @sql
						END
						DROP TABLE ListofEmpData
							 SET @lResult = 1;
						END	

				Else IF(@lSubFunctionality = 'JobDetail')		--------JobDetail
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeJobDetail) 
						IF(@lUpdateField = 'DateOfJoining')
						BEGIN			
							SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
									(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeJobDetail  EJD 
										INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
							EXEC sp_executesql @sql
							SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfJoining=''1900-01-01'''
							EXEC sp_executesql @sql
					END

					ELSE IF(@lUpdateField = 'DateOfleaving')
						BEGIN			
							SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
									(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeJobDetail  EJD 
										INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
							EXEC sp_executesql @sql
							SET  @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfleaving=''1900-01-01'''
							EXEC sp_executesql @sql
						END

					ELSE IF(@lUpdateField = 'ProbationUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE ProbationUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'AhdocUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE AhdocUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'PermanentDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE PermanentDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE
						BEGIN
							SET @sql='INSERT INTO sHrm.tEmployeeJobDetail
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeeJobDetail set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeJobDetail EJD 
										INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'
			
							EXEC sp_executesql @sql
						END
					DROP TABLE ListofEmpData
						 SET @lResult = 1;
					END	

				ELSE IF(@lSubFunctionality = 'EmployeeGeneral')			---------EmployeeGeneral
					BEGIN
					
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT Id FROM sHrm.tEmployeeMaster) 
						-- MantisId : 	0029269 Add EUID									
						SET @sql='INSERT INTO sHrm.tEmployeeMaster
									(Id,'+@lUpdateField+',CreatedUserId,CreatedDateTime,EUId)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate(),LD.EmployeeId
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'				
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeMaster set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeMaster EM 
									INNER JOIN ListofEmpData LD ON EM.Id=LD.EmployeeId AND IsExist=0'
		
						EXEC sp_executesql @sql
						
						DROP TABLE ListofEmpData
							 SET @lResult = 1;
					END
					--Add IsVPFDeduction because table not allow to insert null value in IsVPFDeduction column  mantisid -- 0032446
				 Else IF(@lSubFunctionality = 'Statutory')	   ----------Statutory
					BEGIN
						 UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
						 SET @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
									(EmployeeId,IsVPFDeduction,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,0,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'				
						 EXEC sp_executesql @sql
						 
						 SET @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeStatutoryAndOther ES 
										INNER JOIN ListofEmpData LD ON ES.EmployeeId=LD.EmployeeId AND IsExist=0'

						EXEC sp_executesql @sql
						  
						DROP TABLE ListofEmpData
							SET @lResult = 1;
					END
				
			END

			IF(@lResult = 1)
			BEGIN
				UPDATE sHrm.tDigitalFormEmployee
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 2 AS Result
		END

		ELSE
		BEGIN
		   SELECT -101 As Result
		END
		
		COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
		SELECT ERROR_MESSAGE() AS Error
	END CATCH
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormFieldDetailGet]
	 @rCategoryId int,
	 @rSubCategory nvarchar(500),
	 @rEmployeeId bigint,
	 @rIsBlank bit = 0

AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		IF(@rSubCategory = 'Gender' OR @rSubCategory = 'Religion'  OR @rSubCategory = 'MaritalStatus' OR @rSubCategory = 'BloodGroup' 
		OR @rSubCategory = 'EmployeeDesignation' OR @rSubCategory = 'OrganizationDepartment' OR @rSubCategory = 'EmployeeType'
		OR @rSubCategory = 'EmployeeGroup' OR @rSubCategory = 'EmployeeGrade' OR @rSubCategory = 'OrgGroupDepartment'
		OR @rSubCategory = 'EmployeeManager' 
		OR @rSubCategory = 'Payroll' OR @rSubCategory = 'PayrollGroup' OR @rSubCategory = 'Tribe'
		)
		BEGIN
			 
			SET @rSubCategory =@rSubCategory + 'Id'
			 -- print @rSubCategory
		END
		IF(@rSubCategory = 'OrganizationHeadManager' )
		BEGIN
			SET @rSubCategory = 'EmployeeBusinessHeadId'
		END
		IF(@rSubCategory = 'CasteCategory' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') + 'Id'
		END
		
		IF(@rSubCategory = 'FamilyCast' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') 
		END
		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		 
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- Communication
						'Select ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EC.'+@rSubCategory+','''') 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EC.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EC.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EC.'+@rSubCategory+',''0'') 
						END AS SubCategory
							FROM 
							sHrm.vEmployeeCommonDetail ECD
							LEFT JOIN sHrm.tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
							Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							 '
							
					 WHEN 2 THEN -- Other
						'Select ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EPD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EPD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EPD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						EPD.'+@rSubCategory+'
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EPD.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vEmployeeCommonDetail ECD
							LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON ECD.EmployeeId=EPD.EmployeeId
							Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EPD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EPD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EPD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EPD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
							
					WHEN 3 THEN -- Job Detail
						'Select ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EJD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EJD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EJD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EJD.'+@rSubCategory+',''0'')
						END AS SubCategory 
							FROM 
							sHrm.vEmployeeCommonDetail ECD
							LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=ECD.EmployeeId
							Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EJD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EJD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EJD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 
					WHEN 4 THEN --General
					   'Select ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EM.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vEmployeeCommonDetail ECD
							LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=ECD.EmployeeId
							Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
				   
					WHEN 5 THEN --Statutory 
					   'Select ECD.EmployeeId,ECD.Code,ECD.EmployeeName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(ES.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(ES.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(ES.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(ES.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(ES.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vEmployeeCommonDetail ECD
							LEFT JOIN sHrm.tEmployeeStatutoryAndOther ES ON ECD.EmployeeId=ES.EmployeeId
							Where ECD.EmployeeId='+CAST(@rEmployeeId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ES.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ES.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ES.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ES.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					
				
				
					END				
			
	   if(@Sql1 IS NOT NULL)		
			EXECUTE  sp_executesql @Sql1
	   else
			EXECUTE  sp_executesql @Sql
	   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormFieldGet]

	  @rDigitalFormId int
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
		 
		DFF.UpdateFieldId as Id,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT 'EmployeeCustomFields' as SubFunctionalityName FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 3 THEN 'EmployeeDocument' END AS SubFunctionalityName,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT FieldTitle FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId)
		WHEN DFF.FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 2 AND Id = DFF.UpdateFieldId ) END AS Field
	FROM 
		sHrm.tDigitalForm DF
		INNER JOIN sHrm.tDigitalFormField DFF ON DF.Id = DFF.DigitalFormId
	WHERE 
		((DF.Id = @rDigitalFormId) OR (@rDigitalFormId = 0))
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormMasterAdd]
	 
        @rId bigint = 0,
		@rCode nvarchar(100), 
		@rTitle nvarchar(100),
		@rIsObsolete bit =0,
		@rCreatedUserId bigint,
		@rOrgId int 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tDigitalForm', 0, 1, 1,@outNextNumber = @lNextNumber output
	Print @lNextNumber
	INSERT INTO sHrm.tDigitalForm
		(
			Id
		   ,Code
		   ,Title
		   ,OrgId
		   ,IsObsolete
		   ,CreatedUserId
           ,CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rOrgId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate()
		)

	 
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sHrm.tDigitalForm
	    SET
			 
        	 Id = @lNextNumber
		   ,Code = @rCode
		   ,Title = @rTitle
		   ,OrgId = @rOrgId
		   ,IsObsolete = @rIsObsolete
		   ,CreatedUserId = @rCreatedUserId
           ,CreatedDateTime = sCommon.fGetDate()

	      WHERE Id = @rId
	      
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormMasterDelete]

	  @rDigitalFormId int,
	  @rOrgId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DELETE FROM sHrm.tDigitalForm WHERE Id = @rDigitalFormId AND OrgId = @rOrgId
	DELETE FROM sHrm.tDigitalFormField WHERE DigitalFormId = @rDigitalFormId
	DELETE FROM sHrm.tDigitalFormScope WHERE DigitalFormId = @rDigitalFormId
	SELECT 1 as Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormMasterGet]

	  @rId int,
	  @rOrgId smallint=0,
	  @rTitle nvarchar(100),
	  @rCode nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
		DF.Id,
		DF.Code,
		DF.Title,
		CONVERT(nvarchar,DF.CreatedDateTime,103) as CreatedDateTime, 
		CASE WHEN U.SourceTypeId = 95 THEN (SELECT ShortName FROM sHrm.tEmployeeMaster WHERE Id = U.SourceId )
			 WHEN U.SourceTypeId = 2003 THEN (SELECT FirstName+''+LastName as Name FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id WHERE A.Id = U.SourceId ) ELSE 'Admin' END As CreatedBy,
		DF.IsObsolete
	FROM 
		sHrm.tDigitalForm DF
		INNER JOIN sSecurity.tUser U ON DF.CreatedUserId = U.Id
	WHERE 
	    ((DF.OrgId = @rOrgId)OR (@rOrgId=0))
		AND	((DF.Id = @rId) OR (@rId = 0))
		AND ((DF.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))		
		AND ((DF.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormMasterScopeDetailGet]
	@rSourceId bigint = 0,
	@rSourceTypeId int = 0,
	@rDigitalFormId bigint = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
	  IF(@rDigitalFormId != 0)
	  BEGIN
		SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId as SourceTypeId,
			 DS.SourceId as SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS DepartmentName,
             OM.DisplayTitle AS OrgName
			 
			FROM sHrm.tDigitalFormScope DS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DS.SourceId=OM.Id
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=2021

			UNION ALL

			SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId  as SourceTypeId,
			 DS.SourceId as SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS DepartmentName,
             OM.DisplayTitle AS OrgName 
			 
			FROM sHrm.tDigitalFormScope DS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON DS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id  
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=2017


			UNION ALL
			
			SELECT
			 DS.DigitalFormId,
			 DS.SourceTypeId as SourceTypeId,
			 DS.SourceId as SourceId,
			 [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,OM.EmployeeNameFormatId ) AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             EM.Code,
             ECD.DepartmentName AS DepartmentName,
             OM.DisplayTitle AS OrgName 
			 
			FROM sHrm.tDigitalFormScope DS
		    INNER JOIN [sHrm].[tEmployeeMaster] EM ON DS.SourceId=EM.Id AND EM.StatusId = 7
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id 
			WHERE DS.DigitalFormId=@rDigitalFormId AND DS.SourceTypeId=95
						
			 
	  END
	  ELSE IF(@rSourceId != 0 AND @rSourceTypeId != 0)
	  BEGIN
		SELECT
			  
			 [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,OM.EmployeeNameFormatId ) AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             EM.Code,
             ECD.DepartmentName AS DepartmentName,
             OM.DisplayTitle AS OrgName,
			 EM.Id AS SourceId,		--add by dhruvik for migration
			 @rSourceTypeId AS SourceTypeId		--add by dhruvik for migration
			 
			FROM 
			[sHrm].[tEmployeeMaster] EM
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId=EM.Id AND EM.StatusId = 7
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id
			WHERE EM.Id=@rSourceId AND @rSourceTypeId=95

		UNION ALL
		SELECT
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS DepartmentName,
             OM.DisplayTitle AS OrgName,
			 DM.Id AS SourceId,		--add by dhruvik for migration
			 @rSourceTypeId AS SourceTypeId		--add by dhruvik for migration
			FROM  
			 sSetup.tDepartmentMaster DM
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			WHERE DM.Id=@rSourceId AND @rSourceTypeId=2017
		
		UNION ALL
		SELECT  OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS DepartmentName,
             OM.DisplayTitle AS OrgName,
			 OM.Id AS SourceId,		--add by dhruvik for migration
			 @rSourceTypeId AS SourceTypeId		--add by dhruvik for migration
			 FROM sSetup.tOrganizationMaster OM  
			 WHERE   OM.Id = @rSourceId AND @rSourceTypeId = 2021
		
	  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormScopeAdd]
			@rDigitalFormId bigint
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
             
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN  
			IF EXISTS (SELECT 1 FROM sHrm.tDigitalFormScope WHERE DigitalFormId = @rDigitalFormId AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId)
			BEGIN
				SELECT -103 as Result
			END
			ELSE
			BEGIN
				INSERT INTO sHrm.tDigitalFormScope
				(
					DigitalFormId
				   ,SourceTypeId
				   ,SourceId
			    
				)
				VALUES
				(	
					@rDigitalFormId
				   ,@rSourceTypeId
				   ,@rSourceId
			    
				)		
				SELECT 1 AS Result
			END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pDigitalFormScopeValidate]
	 
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rFinalSourceTypeId smallint,
		@rFinalSourceId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2017 - Department
					   95 - Employee */

	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
		
			If EXISTS(Select 1 FROM 
				[sHrm].[tEmployeeMaster] EM
				INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId=EM.Id 
				Where ECD.DepartmentId = @rSourceId AND EM.Id = @rFinalSourceId AND @rFinalSourceTypeId = 95 )
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 	
			
		
	    END

    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
		If EXISTS(Select 1 FROM 
					[sHrm].[tEmployeeMaster] EM
					INNER JOIN sHrm.vEmployeeCommonDetail  ECD ON EM.Id = ECD.EmployeeId
					INNER JOIN sSetup.tDepartmentMaster DM ON ECD.DepartmentId =  DM.Id
					Where EM.Id = @rSourceId AND DM.Id = @rFinalSourceId AND @rFinalSourceTypeId = 2017)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
	
    END
			select 1 as Result,'' AS Msg
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pDivisionWiseStudentGet]

	 --@rOrgId int,
	 @rBatchId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int
	 --@rEmployeeId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
 
SELECT
A.Code,
A.OrganizationName,
A.RollNo,
A.ClassName+'-'+A.DivisionName AS ClassDivisionName,
A.Name

 FROM
                   sStudent.vStudentAcademic  
                   A INNER JOIN sSetup.tBatchMaster B ON A.BatchId = B.Id 
                   WHERE
                   B.OrgGroupBatchId = @rOrgGroupBatchId
                   AND A.DivisionId=@rDivisionId
                   --AND A.IsActiveBatch=1                 
                   AND A.StatusId=1
                   ORDER BY A.RollNo
               

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployee360ProfileFullGet]
	 
	@rEmployeeId bigint,
	
	--newly added parameter for report 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint = 0,
	@rOrgId smallint = 0,
	@rStrEmployeeId nvarchar(max)='',
	@rEmployeeTypeId [int] =0,
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rGenderId [int]= 0,	
	@rDesignationId [int]= 0,	
	@rAgeFrom nvarchar(10)='',
	@rAgeTo nvarchar(10)='',
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint= 0,
	@rEmployeeStatusId smallint=0
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	
SELECT 
		 --Personal Details
		 EM.Id,
		 EM.Code,
		 ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
		 ISNULL(EP.UIDNumber,'') AS UIDNumber,
		 ISNULL(EP.DateOfBirth,'') AS DateOfBirth,
		 CONVERT(varchar(20) ,ISNULL(EP.DateOfBirth,''),105) AS DateOfBirthJSON,
		 ISNULL(GM.Title,'') AS Gender,
		 ISNULL(MM.Title,'') AS MeritalStatus,
		 ISNULL(BGM.Title,'') AS BloodGroup,
		 ISNULL(EP.Qualification,'') AS Qualification,
		 ISNULL(EP.FamilyCast,'') AS FamilyCast,
		 
		 --Communication
		 ISNULL(EC.PresentStreetOne,'')+' '+ISNULL(EC.PresentStreetTwo,'')+' '+ISNULL(EC.PresentStreetThree,'') AS PresentAddress,
		 ISNULL(EC.PresentCity,'') AS PresentCity,
		 ISNULL(EC.PresentState,'') AS PresentState,
		 ISNULL(EC.PresentCountry,'') AS PresentCountry,
		 ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
		 ISNULL(EC.PresentContactNo,'') AS PresentContactNo,
		
		 ISNULL(EC.PermanentStreetOne,'')+' '+ISNULL(EC.PermanentStreetTwo,'')+' '+ISNULL(EC.PermanentStreetThree,'') AS PermanentAddress,
		 ISNULL(EC.PermanentCity,'') AS PermanentCity,
		 ISNULL(EC.PermanentState,'') AS PermanentState,
		 ISNULL(EC.PermanentCountry,'') AS PermanentCountry,
		 ISNULL(EC.PermanentZipCode,'') AS PermanentZipCode,
		 ISNULL(EC.PermanentContactNo,'') AS PermanentContactNo,
		 
		 ISNULL(EC.EmergencyStreetOne,'')+' '+ISNULL(EC.EmergencyStreetTwo,'')+' '+ISNULL(EC.EmergencyStreetThree,'') AS EmergencyAddress,
		 ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
		 ISNULL(EC.EmergencyState,'') AS EmergencyState,
		 ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
		 ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
		 ISNULL(EC.EmergencyContactNo,'') AS EmergencyContactNo,
		
		 --Job Details
		 ISNULL(EJ.DateOfJoining,'') AS DateOfJoining,	
		 CONVERT(varchar(20),ISNULL(EJ.DateOfJoining,''),105) AS DateOfJoiningJSON,		
		 (COALESCE(CAST(EJ.DateOfleaving AS NVARCHAR(23)),'')) AS DateOfleaving,
		 (CONvert(varchar(20),EJ.DateOfleaving, 105)) AS DateOfleavingJSON,
		 ISNULL(EJ.JobRemark,'') AS JobRemark,
		 ISNULL(EJ.ReferenceRemark,'') AS ReferenceRemark,
		 ISNULL(EDM.Title,'') AS EmployeeDesignation,
		 ISNULL(DM.Title,'') AS OrganizationDepartment,
		 ISNULL(EGM.Title,'') AS EmployeeGrade,
		 ISNULL(GrpM.Title,'') AS EmployeeGroup,
		 ISNULL(ETM.Title,'') AS EmployeeType,
		
		 ----Previous Employment
		 --ISNULL(EPE.CompanyName,'') AS PrevCompanyName,
		 --ISNULL(EPE.Designation,'') AS PrevDesignation,
		 --ISNULL(EPE.Duration,'') AS Duration,
		 --ISNULL(EPE.LastSalary,0) AS LastSalary,
		 --ISNULL(EPE.ReasonForLeaving,'') AS ReasonForLeaving,
		 --ISNULL(EPE.JobDescription,'') AS JobDescription,
		
		 --Notification Details
		 ISNULL(EC.PersonalEmail,'') As PersonalEmail,
		 ISNULL(EC.MobileNumber,'') AS MobileNumber,
		 ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,
		 ISNULL(EC.ExtensionNo,'') AS ExtensionNo,
		 ISNULL(EC.CompanyEmail,'') AS CompanyEmail,
		
		 --EI.EmployeePhoto,
		 ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		 ISNULL(ESO.BankName,'') AS BankName,
		 ISNULL(ESO.Branch,'') AS BankBranch,
		 ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		 ISNULL(ESO.PanNumber,'') AS PanNumber,
		 ISNULL(ESO.EPFNumber,'') AS EPFNumber,
		 ISNULL(ESO.IncrementDate,'') AS IncrementDate,
		 Convert( varchar(20),ISNULL(ESO.IncrementDate,''),105) AS IncrementDateJSON,
		 ISNULL(ESO.BasicPay,0) AS BasicPay,
	     --ISNULL(EFD.Occupation,'') AS Occupation,
		 convert(nvarchar(20),EM.Id) AS EmployeeIdText,
		 convert(nvarchar(20),@rOrgId) AS OrgIdText,
		 ISNULL(EJ.OrganizationDepartmentId,0) AS DepartmentId,
		 OM.DisplayTitle AS OrgTitle,
		 ISNULL(EP.AdhaarNumber,'') AS AdhaarNumber,
		 ISNULL(ESO.Payscale,'') AS Payscale,
		 --[sHrm].[fTeachingSubjectGet] (EM.Id) AS TeachingSubject
		 EJ.Subjects AS TeachingSubject,
		 RM.Title AS Religion,
		 CCM.Title AS CasteCategory,
		 EP.FamilyCast AS FamilyCast,
		 EP.UIDNumber,
		 EP.IdentificationMark1,
		 EP.AdhaarNumber,
		 EP.Qualification,
		 EmployeePhoto = (SELECT CAST(EI.EmployeePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64)	-- MantisId : 0035912	
  FROM 
		sHrm.tEmployeeMaster EM 
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.ID = EC.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id
		INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID	
		--INNER JOIN sHrm.tEmployeePreviousEmployment EPE ON EPE.EmployeeId=EM.ID
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EP.BloodGroupId    
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId
		LEFT JOIN sCommon.tMaritalStatusMaster MM ON MM.Id =  EP.MaritalstatusId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EP.ReligionId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId
		LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id=EJ.EmployeeGradeId
		LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJ.EmployeeGroupId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EP.CastCategoryId
		--LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON EFD.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId  
  WHERE 
		(EM.Id=@rEmployeeId OR @rEmployeeId = 0)
		AND (ISNULL(EM.Id,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
		AND ((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
		AND (ETM.Id = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
		AND (DM.Id = @rDepartmentId OR @rDepartmentId = 0)
		AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
		AND (GrpM.Id=@rEmployeeGroupId OR @rEmployeeGroupId=0) 
		AND (EGM.Id = @rGradeId OR @rGradeId = 0)
		AND (EDM.Id = @rDesignationId OR @rDesignationId = 0)
		AND (GM.Id = @rGenderId OR @rGenderId = 0)
		AND ((DATEDIFF(yy,EP.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
		AND ((DATEDIFF(yy,EP.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
		AND  ( EM.OrgId = @rOrgId OR @rOrgId = 0)
		AND ISNULL(EM.IsOtherUser,0) = 0 	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAllBAtchDocumentSubmitGet]
	 
        @rEmployeeId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN   UD.DocumentId is null THEN 'False' ELSE 'True'END AS IsCheck
			, ISNULL(UD.DocumentName,'')  As FileName,
			isnull(Ud.OrgGroupBatchId,0) AS OrgGroupBatchId,ISNULL(S.IsMigrate,0) as IsMigrate
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join [sHrm].[tEmployeeDocument]  S ON S.SubmitDocumentMasterId=D.id AND S.EmployeeId=@rEmployeeId
			Left Join [sCommon].[tUploadDocument] UD On UD.DocumentId=D.id AND UserSourceTypeId=95 AND UserSourceId=@rEmployeeId AND ( UD.UploadFunctionalityId=13)
			WHERE OrgId=@rOrgId AND SubmitDocumentFunctionalityId='2'
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAllDetailGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
			ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
			ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			ISNULL(SI.QRCode, CONVERT(VARBINARY(MAX),0)) AS QRCode
			
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
			ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
			ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			ISNULL(SI.QRCode, CONVERT(VARBINARY(MAX),0)) AS QRCode
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)	
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttenanceView_NewGet]

		@rOrgId int
		,@rForMonth smallint
		,@rForYear smallint
		,@rBatchId int 
		,@rDepartmentId int 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lFirstDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		
BEGIN 
  
	SELECT  
			 @lFirstDate AS LastDate
			,PT.EmployeeId
			,Code
			,Name
			,ForYear
			,ForMonth
			,ForMonthInWord
			,(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount
			,ISNULL(TC.TCount,0) AS AttendanceCount
			,ISNULL(AC.ACount,0) As  AbsentCount
			,ISNULL(PC.PCount,0) As  PresentUpto
			,0 AS TotalPresent
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,1,@rBatchId,PT.EmployeeId,[1],@rOrgId) AS P1
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,2,@rBatchId,PT.EmployeeId,[2],@rOrgId) AS P2
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,3,@rBatchId,PT.EmployeeId,[3],@rOrgId) AS P3 
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,4,@rBatchId,PT.EmployeeId,[4],@rOrgId) AS P4
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,5,@rBatchId,PT.EmployeeId,[5],@rOrgId) AS P5
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,6,@rBatchId,PT.EmployeeId,[6],@rOrgId) AS P6
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,7,@rBatchId,PT.EmployeeId,[7],@rOrgId) AS P7
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,8,@rBatchId,PT.EmployeeId,[8],@rOrgId) AS P8
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,9,@rBatchId,PT.EmployeeId,[9],@rOrgId) AS P9
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,10,@rBatchId,PT.EmployeeId,[10],@rOrgId) AS P10
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,11,@rBatchId,PT.EmployeeId,[11],@rOrgId) AS P11
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,12,@rBatchId,PT.EmployeeId,[12],@rOrgId) AS P12
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,13,@rBatchId,PT.EmployeeId,[13],@rOrgId) AS P13
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,14,@rBatchId,PT.EmployeeId,[14],@rOrgId) AS P14
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,15,@rBatchId,PT.EmployeeId,[15],@rOrgId) AS P15
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,16,@rBatchId,PT.EmployeeId,[16],@rOrgId) AS P16
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,17,@rBatchId,PT.EmployeeId,[17],@rOrgId) AS P17
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,18,@rBatchId,PT.EmployeeId,[18],@rOrgId) AS P18
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,19,@rBatchId,PT.EmployeeId,[19],@rOrgId) AS P19
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,20,@rBatchId,PT.EmployeeId,[20],@rOrgId) AS P20
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,21,@rBatchId,PT.EmployeeId,[21],@rOrgId) AS P21
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,22,@rBatchId,PT.EmployeeId,[22],@rOrgId) AS P22
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,23,@rBatchId,PT.EmployeeId,[23],@rOrgId) AS P23
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,24,@rBatchId,PT.EmployeeId,[24],@rOrgId) AS P24
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,25,@rBatchId,PT.EmployeeId,[25],@rOrgId) AS P25
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,26,@rBatchId,PT.EmployeeId,[26],@rOrgId) AS P26
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,27,@rBatchId,PT.EmployeeId,[27],@rOrgId) AS P27
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,28,@rBatchId,PT.EmployeeId,[28],@rOrgId) AS P28
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,29,@rBatchId,PT.EmployeeId,[29],@rOrgId) AS P29
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,30,@rBatchId,PT.EmployeeId,[30],@rOrgId) AS P30
			,[sHrm].[fWeekHOffHolidayLeaveGet](@rForYear,@rForMonth,31,@rBatchId,PT.EmployeeId,[31],@rOrgId) AS P31
	FROM
		(
			SELECT   
				 Em.Code
				,Em.FirstName + ' ' + Em.LastName AS Name
				,Em.Id AS EmployeeId 
				,YEAR(ER.AttendanceDate) AS ForYear
				,MONTH(ER.AttendanceDate) AS ForMonth
				,DATENAME(MONTH, ER.AttendanceDate) AS ForMonthInWord
				,(CASE ER.IsPresent WHEN 1 THEN 'P' WHEN 0 THEN 'A' ELSE  ' ' END )AS  IsPresent		
				,DAY(ER.AttendanceDate) AS DayPart 
			FROM
				sHrm.tEmployeeMaster Em 
				INNER JOIN sHrm.tEmployeeAttendanceRegister ER ON ER.EmployeeId= EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
		    WHERE  
				((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((DM.Id=@rDepartmentId) OR (@rDepartmentId=0))
				AND ISNULL(EM.IsOtherUser,0) = 0 
				) AS SourceTable
			
			PIVOT
			(	
				MIN(IsPresent)
				FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
			) AS PT
			LEFT JOIN
			(
				SELECT EM.Id AS EmployeeId, COUNT(1) AS TCount 
				FROM sHrm.tEmployeeAttendanceRegister ER
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.OrganizationDepartmentId
				WHERE 		
				((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))
				AND ISNULL(EM.IsOtherUser,0) = 0 
				GROUP BY Em.Id
			) TC ON TC.EmployeeId = PT.employeeid

			LEFT JOIN
			(
				SELECT EM.Id AS EmployeeId, COUNT(1) AS ACount 
				FROM sHrm.tEmployeeAttendanceRegister ER
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.OrganizationDepartmentId
				WHERE
				ER.IsPresent = 0	 		
				AND (EM.StatusId = 7)
				AND ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))
				AND ISNULL(EM.IsOtherUser,0) = 0 				
				GROUP BY EM.Id
			) AC ON AC.EmployeeId = PT.EmployeeId
			LEFT JOIN
			(
				SELECT EM.Id AS Employeeid, COUNT(1) AS PCount  
				FROM sHrm.tEmployeeAttendanceRegister ER 
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.Organizationdepartmentid
				WHERE  
				ER.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
				AND ER.IsPresent = 1	    		
				AND ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))	          
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))
				AND ISNULL(EM.IsOtherUser,0) = 0 				
				GROUP BY EM.Id
			) PC ON PC.Employeeid = PT.EmployeeId

			ORDER BY Code
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttenanceviewGet]

		 @rBuilder1 nvarchar(max)=''
		,@rBuilder2 nvarchar(max)='' 
		,@rOrgId int
		,@rForMonth smallint
		,@rForYear smallint
		,@rBatchId int = 0
		,@rDepartmentId int = 0
		,@rDivisionId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lFirstDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	Declare @Days int 
	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	
BEGIN 
  
	SELECT  
			 @lFirstDate AS LastDate
			,PT.EmployeeId
			,Number
			,Code
			,Name
			,ForYear
			,ForMonth
			,ForMonthInWord
			,(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount
			,ISNULL(TC.TCount,0) AS AttendanceCount
			,ISNULL(AC.ACount,0) As  AbsentCount
			,ISNULL(PC.PCount,0) As  PresentUpto
			,0 AS TotalPresent
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),PT.DateOfJoining,PT.DateOfLeaving,[1]) AS P1
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),DateOfJoining,DateOfLeaving,[2]) AS P2
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),DateOfJoining,DateOfLeaving,[3]) AS P3
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),DateOfJoining,DateOfLeaving,[4]) AS P4
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),DateOfJoining,DateOfLeaving,[5]) AS P5
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),DateOfJoining,DateOfLeaving,[6]) AS P6
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),DateOfJoining,DateOfLeaving,[7]) AS P7
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),DateOfJoining,DateOfLeaving,[8]) AS P8
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),DateOfJoining,DateOfLeaving,[9]) AS P9
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),DateOfJoining,DateOfLeaving,[10]) AS P10
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),DateOfJoining,DateOfLeaving,[11]) AS P11
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),DateOfJoining,DateOfLeaving,[12]) AS P12
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),DateOfJoining,DateOfLeaving,[13]) AS P13
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),DateOfJoining,DateOfLeaving,[14]) AS P14
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),DateOfJoining,DateOfLeaving,[15]) AS P15
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),DateOfJoining,DateOfLeaving,[16]) AS P16
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),DateOfJoining,DateOfLeaving,[17]) AS P17
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),DateOfJoining,DateOfLeaving,[18]) AS P18
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),DateOfJoining,DateOfLeaving,[19]) AS P19
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),DateOfJoining,DateOfLeaving,[20]) AS P20
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),DateOfJoining,DateOfLeaving,[21]) AS P21
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),DateOfJoining,DateOfLeaving,[22]) AS P22
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),DateOfJoining,DateOfLeaving,[23]) AS P23
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),DateOfJoining,DateOfLeaving,[24]) AS P24
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),DateOfJoining,DateOfLeaving,[25]) AS P25
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),DateOfJoining,DateOfLeaving,[26]) AS P26
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),DateOfJoining,DateOfLeaving,[27]) AS P27
			,[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),DateOfJoining,DateOfLeaving,[28]) AS P28
			,CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),PT.DateOfJoining,PT.DateOfLeaving,[29]) end AS P29
			,CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),PT.DateOfJoining,PT.DateOfLeaving,[30])end AS P30
			,CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceJoiningDateGet](PT.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),PT.DateOfJoining,PT.DateOfLeaving,[31])end AS P431	 
			
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,1,@rBatchId,@rDepartmentId,@rOrgId) AS P1
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,2,@rBatchId,@rDepartmentId,@rOrgId) AS P2
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,3,@rBatchId,@rDepartmentId,@rOrgId) AS P3 
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,4,@rBatchId,@rDepartmentId,@rOrgId) AS P4
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,5,@rBatchId,@rDepartmentId,@rOrgId) AS P5
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,6,@rBatchId,@rDepartmentId,@rOrgId) AS P6
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,7,@rBatchId,@rDepartmentId,@rOrgId) AS P7
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,8,@rBatchId,@rDepartmentId,@rOrgId) AS P8
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,9,@rBatchId,@rDepartmentId,@rOrgId) AS P9
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,10,@rBatchId,@rDepartmentId,@rOrgId) AS P10
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,11,@rBatchId,@rDepartmentId,@rOrgId) AS P11
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,12,@rBatchId,@rDepartmentId,@rOrgId) AS P12
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,13,@rBatchId,@rDepartmentId,@rOrgId) AS P13
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,14,@rBatchId,@rDepartmentId,@rOrgId) AS P14
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,15,@rBatchId,@rDepartmentId,@rOrgId) AS P15
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,16,@rBatchId,@rDepartmentId,@rOrgId) AS P16
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,17,@rBatchId,@rDepartmentId,@rOrgId) AS P17
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,18,@rBatchId,@rDepartmentId,@rOrgId) AS P18
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,19,@rBatchId,@rDepartmentId,@rOrgId) AS P19
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,20,@rBatchId,@rDepartmentId,@rOrgId) AS P20
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,21,@rBatchId,@rDepartmentId,@rOrgId) AS P21
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,22,@rBatchId,@rDepartmentId,@rOrgId) AS P22
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,23,@rBatchId,@rDepartmentId,@rOrgId) AS P23
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,24,@rBatchId,@rDepartmentId,@rOrgId) AS P24
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,25,@rBatchId,@rDepartmentId,@rOrgId) AS P25
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,26,@rBatchId,@rDepartmentId,@rOrgId) AS P26
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,27,@rBatchId,@rDepartmentId,@rOrgId) AS P27
			--,[sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,28,@rBatchId,@rDepartmentId,@rOrgId) AS P28
			--,CASE WHEN @Days>=29 THEN  [sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,29,@rBatchId,@rDepartmentId,@rOrgId)end AS P29
			--,CASE WHEN @Days>=30 THEN [sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,30,@rBatchId,@rDepartmentId,@rOrgId) end AS P30
		 --   ,CASE WHEN @Days>=31 THEN [sHrm].[fWeekHOffGet](PT.EmployeeId,@rForYear,@rForMonth,31,@rBatchId,@rDepartmentId,@rOrgId) end AS P431 
		  
	FROM
		(
			SELECT   
				 Em.Code
				,Em.FirstName + ' ' + Em.LastName AS Name
				,Em.Id AS EmployeeId 
				,YEAR(ER.AttendanceDate) AS ForYear
				,MONTH(ER.AttendanceDate) AS ForMonth
				,DATENAME(MONTH, ER.AttendanceDate) AS ForMonthInWord
				,(CASE ER.IsPresent WHEN 1 THEN 'P' WHEN 0 THEN 'A' ELSE  ' ' END )AS  IsPresent		
				,DAY(ER.AttendanceDate) AS DayPart
				,Em.Number 
				,EJD.DateOfJoining,
				EJD.DateOfleaving
			FROM
				sHrm.tEmployeeMaster Em 
				INNER JOIN sHrm.tEmployeeAttendanceRegister ER ON ER.EmployeeId= EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
		    WHERE  
				((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((DM.Id=@rDepartmentId) OR (@rDepartmentId=0))
				AND (EJD.DateOfleaving >= (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
				OR ISNULL(EJD.DateOfleaving,'')='')				
				AND Em.IsOtherUser = 0 AND ISNULL(EM.IsOtherUser,0) = 0 ) AS SourceTable

			
			PIVOT
			(	
				MIN(IsPresent)
				FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
			) AS PT
			LEFT JOIN
			(
				SELECT EM.Id AS EmployeeId, COUNT(1) AS TCount 
				FROM sHrm.tEmployeeAttendanceRegister ER
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.OrganizationDepartmentId
				WHERE 		
				((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))
				AND ISNULL(EM.IsOtherUser,0) = 0 
				GROUP BY Em.Id
			) TC ON TC.EmployeeId = PT.employeeid

			LEFT JOIN
			(
				SELECT EM.Id AS EmployeeId, COUNT(1) AS ACount 
				FROM sHrm.tEmployeeAttendanceRegister ER
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.OrganizationDepartmentId
				WHERE
				ER.IsPresent = 0	 		
				AND (EM.StatusId = 7)
				AND ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))
				AND ((YEAR(ER.AttendanceDate)=@rForYear) OR (@rForYear= 0))
				AND ((MONTH(ER.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))
				AND ISNULL(EM.IsOtherUser,0) = 0 		
				GROUP BY EM.Id
			) AC ON AC.EmployeeId = PT.EmployeeId
			LEFT JOIN
			(
				SELECT EM.Id AS Employeeid, COUNT(1) AS PCount  
				FROM sHrm.tEmployeeAttendanceRegister ER 
				INNER JOIN sHrm.tEmployeeMaster EM ON ER.EmployeeId = EM.Id 
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.Employeeid = EM.Id
				INNER JOIN sSetup.tDepartmentMaster Deprt ON Deprt.Id= EJD.Organizationdepartmentid
				WHERE  
				ER.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
				AND ER.IsPresent = 1	    		
				AND ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
				AND ((ER.BatchId=@rBatchId) OR (@rBatchId= 0))	          
				AND ((Deprt.Id=@rDepartmentId) OR (@rDepartmentId=0))	
				AND ISNULL(EM.IsOtherUser,0) = 0 	
				GROUP BY EM.Id
			) PC ON PC.Employeeid = PT.EmployeeId

			ORDER BY Number
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceAdd]

	       @rEmployeeId bigint,
           @rForMonth tinyint,
           @rForYear smallint,
           @rTotalWorkingDays tinyint,
           @rLWP decimal(12,2),
           @rPaidLeave decimal(12,2)=0,
           @rBatchId int
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION

IF EXISTS (Select 1 FROM sHrm.tEmployeeAttendance Where EmployeeId = @rEmployeeId AND ForYear = @rForYear AND ForMonth = @rForMonth AND BatchId = @rBatchId)  
  BEGIN
     DELETE FROM sHrm.tEmployeeAttendance Where EmployeeId = @rEmployeeId AND ForYear = @rForYear AND ForMonth = @rForMonth AND BatchId = @rBatchId
  END
   
	INSERT INTO [sHrm].[tEmployeeAttendance]
           (
           [EmployeeId]
           ,[ForMonth]
           ,[ForYear]
           ,[TotalWorkingDays]
           ,[LWP]
           ,[PaidLeave]
           ,[BatchId]
           )
     VALUES
           (
           @rEmployeeId,
           @rForMonth,
           @rForYear,
           @rTotalWorkingDays,
           @rLWP,
           @rPaidLeave,
           @rBatchId
           )
		 
	SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH						
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceAPIGet]
	 	 
	 	  @rForMonth smallint = 0,
	      @rForYear smallint = 0,
	      @rEmployeeId bigint = 0,	      
	      @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
	 
	        CAST(DAY(ER.AttendanceDate) AS NVARCHAR) AS DayNo,
			
			CASE  
			      WHEN ER.IsPresent = 1  THEN 'P' 
				  WHEN ER.IsPresent = 0 THEN 'A'
				  ELSE  '' END AS  Presence,			
			OM.WeekOffs,
			ISNULL(CAST([sHrm].[fEmployeeHolidayDatesList](EM.Id, ISNULL(EJD.OrganizationDepartmentId,0), @rForYear,@rForMonth,@rBatchId, EM.OrgID) AS NVARCHAR),'')  As Holidays,--Changed by Nilesh for mantis : 34328
			CAST((SELECT COUNT(IsPresent) FROM sHrm.tEmployeeAttendanceRegister ER WHERE EmployeeId = @rEmployeeId AND IsPresent = 1 AND AttendanceDate <= GETDATE()) AS NVARCHAR) AS UptoPresentCount,
			CAST((SELECT COUNT(IsPresent) FROM sHrm.tEmployeeAttendanceRegister ER WHERE EmployeeId = @rEmployeeId AND AttendanceDate <= GETDATE()) AS NVARCHAR) AS TotalCount
	From  
			sHrm.tEmployeeMaster EM
            INNER JOIN sHrm.tEmployeeAttendanceRegister ER ON ER.EmployeeId=EM.Id
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			LEFT JOIN  sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	
	WHERE			
		EM.Id=@rEmployeeId
		AND YEAR(ER.AttendanceDate)=@rForYear
		AND MONTH(ER.AttendanceDate)=@rForMonth
		AND ER.BatchId=@rBatchId
		
		ORDER BY DayNo ASC
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceBatchWiseGet]
	 
	@rEmployeeId bigint,
	@rBatchId int,
	@rOrgId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT  
		EM.EmployeeName,
		ISNULL(EM.EmployeeGrade,'') AS EmployeeGrade,
		ISNULL(WD.TotalDays,0) AS TotalDays,
		ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
		(ISNULL(AT.TotalWorkingDays,0) - ((ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)))) AS PresentDays,
		(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS PayrollDays,
		(ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) AS LWP,  
		ISNULL(AT.PaidLeave,0) AS PaidLeave,
		ISNULL(AT.LWP,0) AS UnPaidLeave,
		MM.Title AS Month,
		WD.ForYear
	FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId		
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.BatchId = @rBatchId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId AND WD.ForMonth = AT.ForMonth AND WD.Foryear = AT.ForYear AND WD.BatchId = @rBatchId
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id = WD.ForMonth
	WHERE 
		EM.OrgID = @rOrgId AND EM.EmployeeId = @rEmployeeId 
	ORDER BY 
		WD.ForMonth
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceDelete]

	       @rEmployeeId bigint,
           @rForMonth tinyint,
           @rForYear smallint,
           @rBatchId int
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
	
	DELETE EA FROM [sHrm].[tEmployeeAttendance] EA
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EA.EmployeeId
    WHERE ForMonth=@rForMonth AND ForYear=@rForYear AND EM.StatusId IN(8,9,10) AND ISNULL(EM.IsOtherUser,0) = 0 

	DELETE FROM [sHrm].[tEmployeeAttendance] WHERE EmployeeId=@rEmployeeId AND ForMonth=@rForMonth AND ForYear=@rForYear AND BatchId=@rBatchId
				 
	SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH						
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceGet]
	 
	@rForYear  bigint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int,
	@rDepartmentId int=0,
	@rEmployeeId bigint = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	
BEGIN 
	SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeName,
		EM.EmployeeId,
		ISNULL(EM.EmployeeGrade,'') AS EmployeeGrade,
		ISNULL(WD.TotalDays,0) AS TotalDays,
		
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) + 1 
		--	ELSE ISNULL(WD.TotalDays,0) 
		--END AS TotalDays,
		--ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
		
		CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
			ELSE ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) 
		END AS WorkingDays,
		
		(ISNULL(AT.TotalWorkingDays,0) - ((ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)))) AS PresentDays,
		
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) + (1) 
		--	ELSE (ISNULL(AT.TotalWorkingDays,0) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0))) 
		--END AS PresentDays,
		
		(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS PayrollDays,
		
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) - ISNULL(AT.LWP,0) + (1)
		--	ELSE (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) 
		--END AS PayrollDays,
		
		(ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) AS LWP,   -- Absent Days
		ISNULL(AT.PaidLeave,0) AS PaidLeave,
		ISNULL(AT.LWP,0) AS UnPaidLeave,
		ISNULL(AT.LateCount,0) AS LateCount,
		ISNULL(AT.LateDeductionDays,0) AS LateDeductionDays,
		ISNULL(AT.SandwichDeductionDays,0) AS SandwichDeductionDays,
		ISNULL(CONVERT(VARCHAR(50),EM.DateOfJoining,103),'') AS DateOfJoining,
		ISNULL(CONVERT(VARCHAR(50),EM.DateOfLeaving,103),'') AS DateOfLeaving
		
	FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId		 
		AND AT.ForMonth=@rForMonth AND AT.ForYear=@rForYear AND AT.BatchId = @rBatchId
	WHERE 
		EM.OrgID = @rOrgId 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
		AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		--AND  Code='E158'
		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (EM.IsOtherUser = 0)
		AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	ORDER BY 
		EM.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterAdd]
	 
	@rEmployeeId bigint,
	@rAttendanceDate date,
	@rIsPresent bit=0,
	@rAttendanceTagId int=0,
	@rAbsentReasonId int=0,
	@rUpdatedUserId bigint=0,
	@rBatchId int,
	@rIsDeleted bit,
	@rLeaveTypeId int=0,
	@rLeavePeriodId tinyint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN



If(@rIsDeleted=1)
BEGIN
	DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId=@rEmployeeId 
	AND AttendanceDate=@rAttendanceDate AND BatchId=@rBatchId
	SELECT @rEmployeeId as Result
	RETURN
END
	DECLARE @lDateOfJoining date
	SELECT @lDateOfJoining = DateOfJoining FROM sHrm.tEmployeeJobDetail  WHERE Employeeid = @rEmployeeId
	
	IF @lDateOfJoining IS NOT NULL
	BEGIN
		IF @rAttendanceDate < @lDateOfJoining
		BEGIN
			 SELECT -101 AS Result
			 RETURN
		END
	END
	
	BEGIN TRY
	BEGIN TRANSACTION	
	 
	--IF NOT EXISTS(SELECT EmployeeId FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId=@rEmployeeId 
	--AND AttendanceDate=@rAttendanceDate AND BatchId=@rBatchId)
	
	BEGIN
	
	DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId=@rEmployeeId 
	AND AttendanceDate=@rAttendanceDate AND BatchId=@rBatchId
	
		INSERT INTO sHrm.tEmployeeAttendanceRegister
		(
			EmployeeId,
			AttendanceDate,
			IsPresent,
			AttendanceTagId,
			AbsentReasonId,
			UpdatedUserId,
			UpdatedDateTime,
			BatchId,
			LeaveTypeId,
			LeavePeriodId
		)
		VALUES
		(
			@rEmployeeId,
			@rAttendanceDate,
			@rIsPresent,
			@rAttendanceTagId,
			@rAbsentReasonId,
			@rUpdatedUserId,
			sCommon.fGetDate(),
			@rBatchId,
			@rLeaveTypeId,
			@rLeavePeriodId
		)		
	 	
	 	SELECT 1 AS Result
	 	
	END	
--ELSE
--	 BEGIN
--	   UPDATE  sHrm.tEmployeeAttendanceRegister
--	    SET
--			IsPresent=@rIsPresent,
--			AbsentReasonId=@rAbsentReasonId,
--			UpdatedUserId=@rUpdatedUserId,
--			UpdatedDateTime=sCommon.fGetDate()
	    
--	    WHERE EmployeeId=@rEmployeeId 
--			AND AttendanceDate=@rAttendanceDate
--			AND BatchId=@rBatchId 
			  
--	    SELECT 11 AS Result
	    
--	 END  	

		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		
		SELECT -1 AS Result
		
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterAPIAdd]
	 
	@rEmployeeId bigint,
	@rAttendanceDate date,
	@rIsPresent bit=0,
	@rAttendanceTagId int=0,
	@rAbsentReasonId int=0,
	@rUpdatedUserId bigint=0,
	@rBatchId int,
	@rIsDeleted bit,
	@rLeaveTypeId int=0,
	@rLeavePeriodId tinyint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lDateOfJoining date
	SELECT @lDateOfJoining = DateOfJoining FROM sHrm.tEmployeeJobDetail  WHERE Employeeid = @rEmployeeId
	
	IF @lDateOfJoining IS NOT NULL
	BEGIN
		IF @rAttendanceDate < @lDateOfJoining
		BEGIN
			 SELECT -101 AS Result
			 RETURN
		END
	END

	--DECLARE @rIsAllowFutureAttendaneDate bit = 0
	--SELECT @rIsAllowFutureAttendaneDate = ItemValue FROM sConfig.tConfigurationSetup  WHERE ConfigurationId = 571
	--IF(@rAttendanceDate > GetDate() AND @rIsAllowFutureAttendaneDate = 'false')
	--BEGIN
	--	SELECT -102 AS Result
	--	RETURN
	--END

	BEGIN TRY
	BEGIN TRANSACTION	
	
	BEGIN
	
	DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId=@rEmployeeId 
	AND AttendanceDate=@rAttendanceDate AND BatchId=@rBatchId
	
		INSERT INTO sHrm.tEmployeeAttendanceRegister
		(
			EmployeeId,
			AttendanceDate,
			IsPresent,
			AttendanceTagId,
			AbsentReasonId,
			UpdatedUserId,
			UpdatedDateTime,
			BatchId,
			LeaveTypeId,
			LeavePeriodId
		)
		VALUES
		(
			@rEmployeeId,
			@rAttendanceDate,
			@rIsPresent,
			@rAttendanceTagId,
			@rAbsentReasonId,
			@rUpdatedUserId,
			sCommon.fGetDate(),
			@rBatchId,
			@rLeaveTypeId,
			@rLeavePeriodId
		)		
	 	
	 	SELECT 1 AS Result
	 	
	END 	

		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		
		SELECT -1 AS Result
		
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterGet]
	 	 
	 	 @rDepartmentId int=0,
	 	 @rAttendanceDate date='',
	 	 @rCode nvarchar(20)='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  BEGIN
	SELECT 
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			EM.DepartmentName,
			--ISNULL(EAR.IsPresent,'true') as IsPresent,	--Mantis: 33478, commit
			--CASE WHEN L.NoOfLeave IS NULL THEN CASE WHEN EAR.IsPresent IS NULL THEN 'true' ELSE EAR.IsPresent END ELSE 'false' END AS IsPresent,	--Mantis: 33478, add
			CASE WHEN L.NoOfLeave IS NULL THEN ISNULL(EAR.IsPresent,'true') ELSE 'false' END AS IsPresent,	--Mantis: 33478, add
			ISNULL(EAR.AbsentReasonId,0) as AbsentReasonId,
			CASE WHEN EAR.UpdatedUserId IS NULL THEN cast(0 as bit) ELSE cast(1 as bit) END AS IsDeleted,
			ISNULL(EAR.AttendanceTagId,0) AS AttendanceTagId
			--,ISNULL(EAR.LeaveTypeId,0) AS LeaveTypeId		--Mantis: 33478, commit
			,ISNULL(L.LeaveTypeId,ISNULL(EAR.LeaveTypeId,0)) AS LeaveTypeId,	--Mantis: 33478, add
			--,ISNULL(EAR.LeavePeriodId,0) AS LeavePeriodId		--Mantis: 33478, commit
			ISNULL(L.LeavePeriodId,ISNULL(EAR.LeavePeriodId,0)) AS LeavePeriodId	--Mantis: 33478, add
  FROM 
			sHrm.vExtEmployeeMaster EM
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=EM.EmployeeId
			 --AND (( convert(DATE,EAR.AttendanceDate,102) = @rAttendanceDate) OR (@rAttendanceDate='')) 	
			AND EAR.AttendanceDate =@rAttendanceDate
			AND (EAR.BatchId = @rBatchId)
			LEFT JOIN sHrm.tLeave L ON L.EmployeeId=EM.EmployeeId AND L.StatusId=550 AND L.BatchId = @rBatchId AND L.FromDate <= @rAttendanceDate AND L.ToDate >= @rAttendanceDate	--Mantis: 33478, add Left join
    WHERE 
		  ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		  AND ((EM.Code like @rCode) OR (ISNULL(@rCode,'')=''))
		  AND (EM.OrgId = @rOrgId)
		   --AND ((convert(DATE,EM.DateOfleaving,102) >= @rAttendanceDate) OR (@rAttendanceDate=''))
		   -- AND ((convert(DATE,EM.DateOfleaving,102) <= @rAttendanceDate) OR (@rAttendanceDate='')) 
		  AND ((EM.DateOfleaving >= @rAttendanceDate) OR ISNULL(EM.DateOfleaving,'') = '')
          AND ((EM.DateOfJoining <= @rAttendanceDate) OR ISNULL(EM.DateOfJoining,'') = '') 
		  AND (EM.StatusId = 7)
		  AND (EM.IsOtherUser = 0)
          ORDER BY EM.Number
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 --pRptEmployeeAttendanceRegisterGet 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterReportProcess]
	 
		@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,
		@rStatusId smallint=0,
		@rEmployeeStatusId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		
		Set @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		
		set @Firstdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		set @Lastdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @Days)
		
		
		DELETE FROM [sHrm].[tTempEmployeeAttendanceRegister]
			INSERT INTO [sHrm].[tTempEmployeeAttendanceRegister]
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			EM.Code AS EmployeeCode,
			EM.EmployeeId,
			EM.EmployeeName,   
			EM.DepartmentName,
			EM.EmployeeGrade,      
		   	sCommon.fGetDaysInMonth (@rForMonth,@rForYear) AS TotalDays,
		    [sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P1,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P2,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P3,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P4,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P5,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P6,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P7,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P8,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P9,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P10,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P11,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P12,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P13,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P14,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P15,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P16,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P17,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P18,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P19,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P20,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P21,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P22,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P23,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P24,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P25,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P26,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P27,
			[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P28,
			CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),EM.DateOfJoining,EM.DateOfLeaving,'') end AS P29,
			CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),EM.DateOfJoining,EM.DateOfLeaving,'')end AS P30,
			CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceWithLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),EM.DateOfJoining,EM.DateOfLeaving,'')end AS P31
			,LTM.Code
			,EM.Number
			,(SELECT ISNULL(SUM(CONVERT(decimal(12,2), '.'+PARSENAME(NoOfLeave,1))),0) FROM sHrm.tLeave WHERE LeaveTypeId = LTM.Id AND FromDate BETWEEN @FirstDate AND @LastDate AND StatusId!=551 AND OrgId = @rOrgId AND BatchId = @rBatchId AND EmployeeId = EM.EmployeeId) AS LeaveCount
			
			FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId				
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId						
			
    		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=@rStatusId) OR (@rStatusId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
    		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
    		--AND ((ISNULL(EM.DateOfJoining,''))<=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),IN(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)))))			
			AND EM.IsOtherUser = 0

			SELECT 1 AS Result
			--SELECT * FROM [sHrm].[tTempEmployeeAttendanceRegister]
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rOrgId int,
    @rAttendanceDate date='',
    @rCreatedUserId bigint,
    @rBatchId int=0,
	@rDepartmentId int=0
		
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
BEGIN TRANSACTION 
BEGIN
	DELETE EAR FROM sHrm.tEmployeeAttendanceRegister EAR
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EAR.EmployeeId
	INNER JOIN sHrm.vEmployeeCommonDetail  EJD ON EJD.EmployeeId = EM.Id
	WHERE EAR.AttendanceDate=@rAttendanceDate AND EAR.BatchId=@rBatchId AND ISNULL(EM.IsOtherUser,0) = 0 
	AND ((EJD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
	 
	 INSERT INTO sHrm.tEmployeeAttendanceRegister 
		(
			EmployeeId,	
			AttendanceDate,
			IsPresent,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId,
			BatchId
			)
		SELECT	
		DISTINCT	
			EJD.EmployeeId,
			@rAttendanceDate,
			IsPresent,
			@rCreatedUserId,
			sCommon.fGetDate(),
			ISNULL(AttendanceTagId,0),
			@rBatchId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				EmployeeId bigint,
				IsPresent bit,
				AdmissionDate datetime,
				AttendanceTagId smallint,
				BatchId int
		   ) AS At
		   LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = At.EmployeeId
		   WHere (EJD.DateOfJoining <= @rAttendanceDate OR  ISNULL(EJD.DateOfJoining,'') = '')
		 AND ((EJD.DateOfLeaving > @rAttendanceDate) OR  ISNULL(EJD.DateOfLeaving,'') = '') 
        SELECT 1 AS Result
	 END	
		
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceSummaryDashboard]
	@rType nvarchar(50)='',
	@rBatchId int=0,
	@rOrgGroupBatchId int=0,
	@rOrgId smallint=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 

	IF(@rType = 'EmployeePresentDetails')
		BEGIN
		    
		    SELECT 
		    (SELECT ISNULL(COUNT(EM.EmployeeId),0) AS AbsentCount FROM sHrm.vExtEmployeeMaster EM 
		           LEFT JOIN sHrm.tEmployeeAttendanceRegister EAT ON EAT.EmployeeId=EM.EmployeeId AND EAT.AttendanceDate =CONVERT(char(10), GetDate(),126) 
		               AND (EAT.BatchId = @rBatchId) 
		     WHERE ((EM.DateOfleaving >= CONVERT(char(10), GetDate(),126)) OR ISNULL(EM.DateOfleaving,'') = '')  AND (EM.OrgId = @rOrgId) AND (EM.StatusId = 7)) AS TotalCount,
		     
		     
		      (SELECT ISNULL(COUNT(EM.EmployeeId),0) AS AbsentCount FROM sHrm.vExtEmployeeMaster EM 
		           LEFT JOIN sHrm.tEmployeeAttendanceRegister EAT ON EAT.EmployeeId=EM.EmployeeId AND EAT.AttendanceDate =CONVERT(char(10), GetDate(),126) 
		               AND (EAT.BatchId = @rBatchId) 
		     WHERE ((EM.DateOfleaving >= CONVERT(char(10), GetDate(),126)) OR ISNULL(EM.DateOfleaving,'') = '')  AND (EM.OrgId = @rOrgId) AND EAT.IsPresent=1) AS PresentCount,
		     
		     
		       
		      (SELECT ISNULL(COUNT(EM.EmployeeId),0) AS AbsentCount FROM sHrm.vExtEmployeeMaster EM 
		           LEFT JOIN sHrm.tEmployeeAttendanceRegister EAT ON EAT.EmployeeId=EM.EmployeeId AND EAT.AttendanceDate =CONVERT(char(10), GetDate(),126) 
		               AND (EAT.BatchId = @rBatchId) 
		     WHERE ((EM.DateOfleaving >= CONVERT(char(10), GetDate(),126)) OR ISNULL(EM.DateOfleaving,'') = '')  AND (EM.OrgId = @rOrgId) AND EAT.IsPresent=0) AS AbsentCount,
		     
		      (SELECT ISNULL(COUNT(EM.EmployeeId),0) AS AbsentCount FROM sHrm.vExtEmployeeMaster EM 
		           LEFT JOIN sHrm.tEmployeeAttendanceRegister EAT ON EAT.EmployeeId=EM.EmployeeId AND EAT.AttendanceDate =CONVERT(char(10), GetDate(),126) 
		               AND (EAT.BatchId = @rBatchId) 
		     WHERE ((EM.DateOfleaving >= CONVERT(char(10), GetDate(),126)) OR ISNULL(EM.DateOfleaving,'') = '')  AND (EM.OrgId = @rOrgId) AND EAT.EmployeeId IS NULL AND (EM.StatusId = 7)) AS PendingAttendance
		         
		     
		    --(SELECT ISNULL(COUNT(EAT.EmployeeId),0) AS AbsentCount FROM sHrm.tEmployeeAttendanceRegister EAT  WHERE EAT.IsPresent=1 AND  EAT.AttendanceDate=CONVERT(char(10), GetDate(),126) AND EAT.BatchId= @rBatchId ) AS PresentCount,
		    --(SELECT ISNULL(COUNT(EAT.EmployeeId),0) AS AbsentCount FROM sHrm.tEmployeeAttendanceRegister EAT  WHERE EAT.IsPresent=0 AND EAT.AttendanceDate=CONVERT(char(10), GetDate(),126) AND EAT.BatchId= @rBatchId) AS AbsentCount,		    
         --(SELECT COUNT(Id) From sHrm.tEmployeeMaster EM WHERE ORGId=@rOrgId AND ID NOT IN (SELECT EmployeeId FROM sHrm.tEmployeeAttendanceRegister EAT WHERE EAT.AttendanceDate=CONVERT(char(10), GetDate(),126) AND EAT.BatchId= @rBatchId)) AS PendingAttendance
         
         
		    
		END
		
	 ELSE IF(@rType = 'EmployeeLeaveDetails')
	 
	  BEGIN
	  
	   SELECT 		
		--(SELECT ISNULL(SUM(NoOfLeave),0) AS ApprovedLeaves FROM sHrm.tLeave HL1 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL1.BatchId where HL1.StatusId=550 AND HL1.ToDate  >= DATEADD(day,-30, getdate()) AND HL1.FromDate  <= getdate() AND HL1.BatchId= @rBatchId AND BM.OrgGroupBatchId = 110100111) AS ApprovedLeaves,
		(SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves FROM sHrm.tLeave HL2 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL2.BatchId where HL2.StatusId=549 AND HL2.ToDate  >= DATEADD(day,-30, getdate()) AND HL2.FromDate  <= getdate() AND  BM.OrgGroupBatchId = @rOrgGroupBatchId ) AS PendingLeaves,
		(SELECT ISNULL(SUM(NoOfLeave),0) AS ApprovedLeaves FROM sHrm.tLeave HL1 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL1.BatchId where HL1.StatusId=550 AND HL1.ToDate  >= DATEADD(day,-30, getdate()) AND HL1.FromDate  <= getdate() AND BM.OrgGroupBatchId = @rOrgGroupBatchId) AS ApprovedLeaves,						
		(SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves FROM sHrm.tLeave HL3 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL3.BatchId where HL3.StatusId=551 AND HL3.ToDate  >= DATEADD(day,-30, getdate()) AND HL3.FromDate  <= getdate() AND BM.OrgGroupBatchId = @rOrgGroupBatchId) AS RejectedLeaves
		
	  END
	  
	 ELSE IF(@rType = 'EmployeeCurrentYearLeaveDetails')
	 
	  BEGIN
	  
	   SELECT 	
	   (SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves 
	            FROM sHrm.tLeave HL2 
	               INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL2.BatchId 	               
				   INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = HL2.EmployeeId
				   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = HL2.EmployeeId 
	               where HL2.StatusId=549 AND HL2.FromDate  >= convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AND HL2.ToDate  <= convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 ) AND  BM.OrgGroupBatchId = @rOrgGroupBatchId) AS PendingLeaves,	
		(SELECT ISNULL(SUM(NoOfLeave),0) AS ApprovedLeaves 
		      FROM sHrm.tLeave HL1 
		         INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL1.BatchId 
		         INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = HL1.EmployeeId
			     INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = HL1.EmployeeId 
		      where HL1.StatusId=550 AND HL1.FromDate  >= convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AND HL1.ToDate  <= convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 ) AND   BM.OrgGroupBatchId = @rOrgGroupBatchId) AS ApprovedLeaves,		
		(SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves 
		      FROM sHrm.tLeave HL3 		         
		          INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL3.BatchId 
		          INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = HL3.EmployeeId
			      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = HL3.EmployeeId 
		          where HL3.StatusId=551 AND HL3.FromDate  >= convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AND HL3.ToDate  <= convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 ) AND   BM.OrgGroupBatchId = @rOrgGroupBatchId) AS RejectedLeaves
	  
	  END   
	  
	  
	   ELSE IF(@rType = 'EmployeeMonthWiseAbsentPIChartDetails')
	   
	    BEGIN
	        Select M.Id,M.Title, ISNULL(COUNT(AttendanceDate),0) AS AbsentCount  From sCommon.tMonthMaster M
			 LEFT JOIN  sHrm.tEmployeeAttendanceRegister ER ON MONTH(ER.AttendanceDate) =M.Id AND BatchId=@rBatchId AND IsPresent=0
			 GROUP BY M.Id,M.Title
			 ORDER BY M.Id
 
	    END
	  	
	  ELSE IF(@rType = 'EmployeeMonthWiseLeavePIChartDetails')	
	  	
	  	BEGIN
	       
          Select M.Id,M.Title, ISNULL(SUM(NoOfLeave),0) AS LeaveCount  From sCommon.tMonthMaster M
			 LEFT JOIN  sHrm.tLeave HL ON MONTH(HL.FromDate) =M.Id AND BatchId=@rBatchId 
			 GROUP BY M.Id,M.Title
			 ORDER BY M.Id
 
	    END		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceViewGet]
	 
	@rForYear  bigint,
	@rBatchId int,
	@rOrgId int,
	@rEmployeeId bigint
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT  
         DateName( month , DateAdd( month , WD.ForMonth , -1 )) As NameofMonth,
         ISNULL(WD.TotalDays,0) AS TotalDays,
         ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
         --ISNULL(AT.LWP,0) AS LWP,         
         ISNULL(AT.PaidLeave,0) AS PaidLeave,
         CONVERT(DECIMAL(12,2),(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
		  ISNULL(AT.TotalWorkingDays,0) -(CONVERT(DECIMAL(12,2),(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)))) AS AbsentDays
     

        FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND  WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId		 
		AND AT.ForMonth=WD.ForMonth AND AT.ForYear=@rForYear AND AT.BatchId = @rBatchId
    	WHERE EM.OrgID = @rOrgId 
		 AND EM.EmployeeId=@rEmployeeId AND AT.EmployeeId=@rEmployeeId
	    -- AND EM.EmployeeId=1101000000039 AND AT.EmployeeId=1101000000039
    	ORDER BY EM.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceXML]
    
    @rBatchId int,
    @rForMonth tinyint,
    @rForYear smallint,
	@rXmlDoc nvarchar(MAX)
	
AS
SET NOCOUNT ON

BEGIN
DECLARE @lInterrorCode INT,@intDoc INT

BEGIN TRY

	BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	
	DELETE EA FROM sHrm.tEmployeeAttendance EA 
	INNER JOIN (SELECT EmployeeId FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH(EmployeeId bigint '@EmployeeId'))A ON  EA.EmployeeId = A.EmployeeId AND EA.ForYear=@rForYear AND EA.ForMonth=@rForMonth AND EA.BatchId=@rBatchId
	
	INSERT INTO shrm.tEmployeeAttendance
	(
		EmployeeId,
		ForMonth,
		ForYear,		
		TotalWorkingDays,
		LWP,
		PaidLeave,
		BatchId,
		LateCount,
		LateDeductionDays,
		SandwichDeductionDays
	)
	SELECT
		EmployeeId,
		@rForMonth,
		@rForYear,		
		TotalWorkingDays,
		LWP,
		PaidLeave,
		@rBatchId,
		LateCount,
		LateDeductionDays,
		SandwichDeductionDays
	FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH
	(		
		EmployeeId bigint '@EmployeeId',
		TotalWorkingDays tinyint '@TotalWorkingDays',
		LWP decimal(12,2) '@LWP',
		PaidLeave decimal(12,2) '@PaidLeave',
		LateCount tinyint '@LateCount',
		LateDeductionDays decimal(12,2) '@LateDeductionDays',
		SandwichDeductionDays decimal(12,2) '@SandwichDeductionDays'
	)A
	
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	
	SELECT 1
END TRY
BEGIN CATCH
	SELECT -1
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeAttendanceXMLAdd]
	(
		@rXmlDoc nvarchar(MAX)
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	-----------------------
	DELETE EA FROM sHrm.tEmployeeAttendance EA INNER JOIN 
	(SELECT EmployeeId,ForMonth,ForYear,BatchId FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH
	(		
		EmployeeId BigINT '@Id',
		ForMonth Tinyint '@Month',
		ForYear Smallint '@Year',
		BatchId int '@BatchId'
	))A ON  EA.EmployeeId = A.EmployeeId AND EA.ForYear=A.ForYear AND EA.ForMonth=A.ForMonth AND EA.BatchId=A.BatchId 
		
	
	INSERT INTO shrm.tEmployeeAttendance
	(
		EmployeeId,
		ForMonth,
		ForYear,		
		TotalWorkingDays,
		LWP,
		BatchId
	)
	SELECT
		EmployeeId,
		ForMonth,
		ForYear,		
		TotalWorkingDays,
		LWP,
		BatchId
		
	FROM OPENXML (@intDoc, '/Table/EmployeeAttendace', 1)
	WITH
	(		
		EmployeeId BigINT '@Id',
		ForMonth Tinyint '@Month',
		ForYear Smallint '@Year',
		TotalWorkingDays Tinyint '@TotdalWorkingDays',
		LWP decimal(5,2) '@LWP',
		BatchId int '@BatchId'
	)A
	
	
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeBulkDataUpdateGet]
	 
	 @rEmployeeDataTypeId int,
	 @rLocationId nvarchar(50)  
	 
AS
SET NOCOUNT ON

BEGIN
		 Declare @Sql nvarchar(max)
		 
		 SET @Sql =  CASE @rEmployeeDataTypeId					  
					 WHEN 1 THEN -- ProcessType
					  'SELECT EJD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EJD.ProcessTypeId,''0'') AS SelectedValue
					   FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'
				 	
				 	 WHEN 2 THEN -- Company
					  'SELECT EJD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EJD.EmployeeCompanyId,0) AS SelectedValue
					   FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'
				 				  
					 WHEN 3 THEN -- Contractor
					  'SELECT EJD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EJD.ContractorId,'''') AS SelectedValue
					   FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'				  
					 				  
					 WHEN 4 THEN --Designation
					 'SELECT EJD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EJD.EmployeeDesignationId,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'			 
		 				  
					 WHEN 5 THEN --EsiNumber
					 'SELECT EJD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EJD.ESINumber,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'				   
				 				  
					 WHEN 6 THEN --BloodGroup
					 'SELECT EPD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EPD.BloodGroupId,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'					   
				 				  
					 WHEN 7 THEN --MaritalStatus
					 'SELECT EPD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EPD.MaritalStatusId,'''') AS SelectedValue
					  FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC' 
				 				  
					 WHEN 8 THEN --Religion
					 'SELECT EPD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EPD.ReligionId,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'					   
				 				  
					 WHEN 9 THEN --Idmark1
					 'SELECT EPD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EPD.IdentificationMark1,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC'	   
			 				  
					 WHEN 10 THEN --IdMark2
					 'SELECT EPD.EmployeeId,ISNULL(EM.FirstName,'''')+'' ''+ISNULL(EM.MiddleName,'''')+'' ''+ISNULL(EM.LastName,'''') AS Name,EM.Code,ISNULL(EPD.IdentificationMark2,'''') AS SelectedValue
					FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId WHERE EmployeeLocationId = '+@rLocationId+' Order By EM.Code ASC' 	
				END 
				
		
	   EXECUTE  sp_executesql @Sql
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeBulkImagesAdd]
	 
	@rCode nvarchar(20),
	@rEmployeePhoto varbinary(max),
	@rOrgId smallint,
	@rPhotoType nvarchar(50),
	@rEmployeeSign varbinary(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	
	DECLARE @lEmployeeId bigint
	
	SELECT @lEmployeeId=Id FROM sHrm.tEmployeeMaster WHERE Code=@rCode AND OrgId=@rOrgId AND ISNULL(IsOtherUser,0) = 0
	IF(ISNULL(@lEmployeeId,'') = '')
	BEGIN
		SELECT 1 AS Result
		RETURN
	END
	
	BEGIN TRANSACTION
	
	IF NOT EXISTS(SELECT EmployeeId FROM sHrm.tEmployeeImages WHERE EmployeeId=@lEmployeeId)
	BEGIN 
	INSERT INTO sHrm.tEmployeeImages
		(
			EmployeeId,
			EmployeePhoto,
			UpdatedDateTime
		)
	VALUES
		(
			@lEmployeeId,
			@rEmployeePhoto,
			sCommon.fGetDate()
		)
		             
	END	 
	
	 IF @rPhotoType = 'TempEmployeePhotos'
	 BEGIN
	  UPDATE sHrm.tEmployeeImages SET EmployeePhoto=@rEmployeePhoto,UpdatedDateTime = sCommon.fGetDate() WHERE EmployeeId=@lEmployeeId
	 END 
	 ELSE IF @rPhotoType = 'TempEmployeeSign'
	 BEGIN
	  UPDATE sHrm.tEmployeeImages  SET EmployeeSign=@rEmployeeSign,UpdatedDateTime = sCommon.fGetDate() WHERE EmployeeId=@lEmployeeId	 	 
	 END 
	 
	 ELSE
	 BEGIN
	    UPDATE sHrm.tEmployeeImages
	    SET
			EmployeePhoto=@rEmployeePhoto,
			UpdatedDateTime=Getdate()
			
	      WHERE 
			EmployeeId=@lEmployeeId
	      
	 END
		SELECT 1 AS Result
	  
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeChangeHistoryAdd]
		   @rId bigint,
	       @rEmployeeId bigint,
		   @rChangeTypeId int,	       
	       @rDateOfChange date,
		   @rOldValue nvarchar(500)='',
		   @rNewValue nvarchar(500)='',
		   @rRemark nvarchar(1000)='',
	       @rCreatedUserId bigint
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION		 
		
	  IF(@rId = 0)	
		BEGIN			
				INSERT INTO sHrm.tEmployeeChangeHistory
				(EmployeeId,ChangeTypeId,DateOfChange,OldValue,NewValue,Remark,CreatedUserId,CreatedDateTime)
				VALUES
				(@rEmployeeId,@rChangeTypeId,@rDateOfChange,@rOldValue,@rNewValue,@rRemark,@rCreatedUserId,sCommon.fGetDate())
		END
		
		ELSE
		
		BEGIN			
				UPDATE  sHrm.tEmployeeChangeHistory
				SET
					EmployeeId=@rEmployeeId,
					ChangeTypeId=@rChangeTypeId,
					DateOfChange=@rDateOfChange,
					OldValue=@rOldValue,
					NewValue=@rNewValue,
					Remark=@rRemark,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate()
				
				WHERE AutoId = @rId
		 END  	
		
		SELECT 1 AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeChangeHistoryGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20)='',	 	
	 @rFromDate date=NULL,
	 @rToDate date=NULL,
	 @rChangeTypeId smallint=0,
	 @rOrgId int = 0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF @rIsSearch = 1
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rName = sCommon.fSearchStringGet(@rName)
		--END
	
	SELECT 
	
			EC.AutoId AS Id,
			EC.EmployeeId,
			EM.FirstName+' '+EM.LastName as Name,
			EM.Designation As Designation,
			EM.Code,
			EC.DateOfChange,
			CT.Title,
			EC.ChangeTypeId,
			EC.OldValue,
			EC.NewValue,
			EC.Remark
			
  FROM 
            sHrm.tEmployeeChangeHistory EC
       INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=EC.EmployeeId 
	   INNER JOIN sHrm.tChangeTypeMaster CT ON CT.ID=EC.ChangeTypeId
  WHERE 
  
	((EC.AutoId = @rId) OR (@rId = 0))
	AND ((EM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))	
	AND ((EC.ChangeTypeId = @rChangeTypeId) OR (@rChangeTypeId = 0))
	AND ((EC.DateOfChange >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((EC.DateOfChange <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
	AND ISNULL(EM.IsOtherUser,0)=0
	ORDER BY EM.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeChangeHistoryRemove]
		   @rId bigint
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	 
		 DELETE FROM sHrm.tEmployeeChangeHistory WHERE AutoId = @rId 
		
		SELECT 1 AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeClubAdd]
	
	@rEmployeeClubImpXml [nvarchar](max),
	@rEmployeeId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEmployeeClubImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sHrm.tAssignClub WHERE EmployeeId=@rEmployeeId
	
		 INSERT INTO sHrm.tAssignClub
		(
			ClubId,
			EmployeeId
			)
		SELECT
			ClubId,
			EmployeeId
		FROM OPENXML (@loDoc, '/Table/EmployeeClub', 1)
		WITH ( 
				ClubId int,
				EmployeeId bigint
			  ) 

		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeColumnNameGet]

AS
SET NOCOUNT ON

BEGIN
		Select COLUMN_NAME AS ColumnName from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sHrm' AND TABLE_NAME='vEmployeeColumnName'
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCommitteeAdd]
	
	@rEmployeeCommitteeImpXml [nvarchar](max),
	@rEmployeeId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEmployeeCommitteeImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sHrm.tAssignCommittee WHERE EmployeeId=@rEmployeeId
	
		 INSERT INTO sHrm.tAssignCommittee
		(
			CommitteeId,
			EmployeeId
			)
		SELECT
			CommitteeId,
			EmployeeId
		FROM OPENXML (@loDoc, '/Table/EmployeeCommittee', 1)
		WITH ( 
				CommitteeId int,
				EmployeeId bigint
			  ) 

		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCommunicationsAdd]
	 
	     @rEmployeeId bigint,
         @rPresentStreetOne nvarchar(150)='',
         @rPresentStreetTwo nvarchar(150)='',
         @rPresentStreetThree nvarchar(150)='',
         @rPresentCountry nvarchar(50)='',
         @rPresentState nvarchar(50)='',
         @rPresentCity nvarchar(50)='',
         @rPresentZipCode nvarchar(20)='',
         @rPresentContactNo nvarchar(20)='',
         @rPermanentStreetOne nvarchar(150)='',
         @rPermanentStreetTwo nvarchar(150)='',
         @rPermanentStreetThree nvarchar(150)='',
         @rPermanentCountry nvarchar(50)='',
         @rPermanentState nvarchar(50)='',
         @rPermanentCity nvarchar(50)='',
         @rPermanentZipCode nvarchar(20)='',
         @rPermanentContactNo nvarchar(20)='',
         @rEmergencyStreetOne nvarchar(150)='',
         @rEmergencyStreetTwo nvarchar(150)='',
         @rEmergencyStreetThree nvarchar(150)='',
         @rEmergencyCountry nvarchar(50)='',
         @rEmergencyState nvarchar(50)='',
         @rEmergencyCity nvarchar(50)='',
         @rEmergencyZipCode nvarchar(20)='',
         @rEmergencyContactNo nvarchar(20)='',
         @rPhoneNoCompany nvarchar(50)='',
         @rExtensionNo nvarchar(10)='',
         @rCompanyEmail nvarchar(100)='',
         @rPersonalEmail nvarchar(100)='',
         @rMobileNumber nvarchar(20)='',
         @rCreatedUserId bigint=0,
		 @rWhatsAppContactNo nvarchar(20)=''
    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT * FROM [sHrm].[tEmployeeCommunications] WHERE EmployeeId = @rEmployeeId)
BEGIN 
	--DECLARE @lNextNumber BIGINT     
	--EXECUTE sCommon.pTableRowIdGet 0, 'sStudent.tStudentCommunication', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sHrm].[tEmployeeCommunications]
           (
				[EmployeeId]
			   ,[PresentStreetOne]
			   ,[PresentStreetTwo]
			   ,[PresentStreetThree]
			   ,[PresentCountry]
			   ,[PresentState]
			   ,[PresentCity]
			   ,[PresentZipCode]
			   ,[PresentContactNo]
			   ,[PermanentStreetOne]
			   ,[PermanentStreetTwo]
			   ,[PermanentStreetThree]
			   ,[PermanentCountry]
			   ,[PermanentState]
			   ,[PermanentCity]
			   ,[PermanentZipCode]
			   ,[PermanentContactNo]
			   ,[EmergencyStreetOne]
			   ,[EmergencyStreetTwo]
			   ,[EmergencyStreetThree]
			   ,[EmergencyCountry]
			   ,[EmergencyState]
			   ,[EmergencyCity]
			   ,[EmergencyZipCode]
			   ,[EmergencyContactNo]
			   ,[PhoneNoCompany]
			   ,[ExtensionNo]
			   ,[CompanyEmail]
			   ,[PersonalEmail]
			   ,[MobileNumber]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[WhatsAppContactNo]
           )
     VALUES
           (
			 @rEmployeeId,
			 @rPresentStreetOne,
			 @rPresentStreetTwo,
			 @rPresentStreetThree,
			 @rPresentCountry,
			 @rPresentState,
			 @rPresentCity,
			 @rPresentZipCode,
			 @rPresentContactNo,
			 @rPermanentStreetOne,
			 @rPermanentStreetTwo,
			 @rPermanentStreetThree,
			 @rPermanentCountry,
			 @rPermanentState,
			 @rPermanentCity,
			 @rPermanentZipCode,
			 @rPermanentContactNo,
			 @rEmergencyStreetOne,
			 @rEmergencyStreetTwo,
			 @rEmergencyStreetThree,
			 @rEmergencyCountry,
			 @rEmergencyState,
			 @rEmergencyCity,
			 @rEmergencyZipCode,
			 @rEmergencyContactNo,
			 @rPhoneNoCompany,
			 @rExtensionNo,
			 @rCompanyEmail,
			 @rPersonalEmail,
			 @rMobileNumber,
			 @rCreatedUserId,
			 sCommon.fGetDate(),
			 @rCreatedUserId,
			 sCommon.fGetDate(),
			 @rWhatsAppContactNo
        )
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rStudentId
	  UPDATE [sHrm].[tEmployeeCommunications]
   SET 
      
       [PresentStreetOne] = @rPresentStreetOne
      ,[PresentStreetTwo] = @rPresentStreetTwo
      ,[PresentStreetThree] = @rPresentStreetThree
      ,[PresentCountry] = @rPresentCountry
      ,[PresentState] = @rPresentState
      ,[PresentCity] = @rPresentCity
      ,[PresentZipCode] = @rPresentZipCode
      ,[PresentContactNo] = @rPresentContactNo
      ,[PermanentStreetOne] = @rPermanentStreetOne
      ,[PermanentStreetTwo] = @rPermanentStreetTwo
      ,[PermanentStreetThree] = @rPermanentStreetThree
      ,[PermanentCountry] = @rPermanentCountry
      ,[PermanentState] = @rPermanentState
      ,[PermanentCity] = @rPermanentCity
      ,[PermanentZipCode] = @rPermanentZipCode
      ,[PermanentContactNo] = @rPermanentContactNo
      ,[EmergencyStreetOne] = @rEmergencyStreetOne
      ,[EmergencyStreetTwo] = @rEmergencyStreetTwo
      ,[EmergencyStreetThree] = @rEmergencyStreetThree
      ,[EmergencyCountry] = @rEmergencyCountry
      ,[EmergencyState] = @rEmergencyState
      ,[EmergencyCity] = @rEmergencyCity
      ,[EmergencyZipCode] = @rEmergencyZipCode
      ,[EmergencyContactNo] = @rEmergencyContactNo
      ,[PhoneNoCompany] = @rPhoneNoCompany
      ,[ExtensionNo] = @rExtensionNo 
      ,[CompanyEmail] = @rCompanyEmail 
      ,[PersonalEmail] = @rPersonalEmail 
      ,[MobileNumber] = @rMobileNumber     
      ,[UpdatedUserId] = @rCreatedUserId
      ,[UpdatedDateTime] =  sCommon.fGetDate() 
	  ,[WhatsAppContactNo] = @rWhatsAppContactNo
	   
	   WHERE EmployeeId = @rEmployeeId	   
	 END  
		SELECT 11 AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCommunicationsBatchWiseGet]
	 
	 @rEmployeeId bigint,
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
	
SELECT [EmployeeId]
      ,ISNULL([PresentStreetOne],'') AS [PresentStreetOne]
      ,ISNULL([PresentStreetTwo],'') AS [PresentStreetTwo]
      ,ISNULL([PresentStreetThree],'') AS [PresentStreetThree]
      ,ISNULL([PresentCountry],'') AS [PresentCountry]
      ,ISNULL([PresentState],'') AS [PresentState]
      ,ISNULL([PresentCity],'') AS [PresentCity]
      ,ISNULL([PresentZipCode],'') AS [PresentZipCode]
      ,ISNULL([PresentContactNo],'') AS [PresentContactNo]
      ,ISNULL([PermanentStreetOne],'') AS [PermanentStreetOne]
      ,ISNULL([PermanentStreetTwo],'') AS [PermanentStreetTwo]
      ,ISNULL([PermanentStreetThree],'') AS [PermanentStreetThree]
      ,ISNULL([PermanentCountry],'') AS [PermanentCountry]
      ,ISNULL([PermanentState],'') AS [PermanentState]
      ,ISNULL([PermanentCity],'') AS [PermanentCity]
      ,ISNULL([PermanentZipCode],'') AS [PermanentZipCode]
      ,ISNULL([PermanentContactNo],'') AS [PermanentContactNo]
      ,ISNULL([EmergencyStreetOne],'') AS [EmergencyStreetOne]
      ,ISNULL([EmergencyStreetTwo],'') AS [EmergencyStreetTwo]
      ,ISNULL([EmergencyStreetThree],'') AS [EmergencyStreetThree]
      ,ISNULL([EmergencyCountry],'') AS [EmergencyCountry]
      ,ISNULL([EmergencyState],'') AS [EmergencyState]
      ,ISNULL([EmergencyCity],'') AS [EmergencyCity]
      ,ISNULL([EmergencyZipCode],'') AS [EmergencyZipCode]
      ,ISNULL([EmergencyContactNo],'') AS [EmergencyContactNo]
      ,ISNULL([PhoneNoCompany],'') AS [PhoneNoCompany]
      ,ISNULL([ExtensionNo],'') AS [ExtensionNo]
      ,ISNULL([CompanyEmail],'') AS [CompanyEmail]
      ,ISNULL([PersonalEmail],'') AS [PersonalEmail]
      ,ISNULL([MobileNumber],'') AS [MobileNumber]
    
  FROM  [sHrm].[tBatchEmployeeCommunications]
             
  WHERE 
		EmployeeId = @rEmployeeId 
		AND BatchId = @rBatchId
		--	((SM.Code=@rCode) OR (ISNULL(@rCode,'') = ''))
		--AND(SM.OrgId=@rOrgId)

 --     ((BM.Id = @rId) OR (@rId = 0))
	--AND  ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	--AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	--AND(BM.OrgId=@rOrgId)

--ORDER BY BM.OrderIndex ASC
  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCommunicationsGet]
	 
	 @rEmployeeId bigint,
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
	
SELECT [EmployeeId]
      ,ISNULL([PresentStreetOne],'') AS [PresentStreetOne]
      ,ISNULL([PresentStreetTwo],'') AS [PresentStreetTwo]
      ,ISNULL([PresentStreetThree],'') AS [PresentStreetThree]
      ,ISNULL([PresentCountry],'') AS [PresentCountry]
      ,ISNULL([PresentState],'') AS [PresentState]
      ,ISNULL([PresentCity],'') AS [PresentCity]
      ,ISNULL([PresentZipCode],'') AS [PresentZipCode]
      ,ISNULL([PresentContactNo],'') AS [PresentContactNo]
      ,ISNULL([PermanentStreetOne],'') AS [PermanentStreetOne]
      ,ISNULL([PermanentStreetTwo],'') AS [PermanentStreetTwo]
      ,ISNULL([PermanentStreetThree],'') AS [PermanentStreetThree]
      ,ISNULL([PermanentCountry],'') AS [PermanentCountry]
      ,ISNULL([PermanentState],'') AS [PermanentState]
      ,ISNULL([PermanentCity],'') AS [PermanentCity]
      ,ISNULL([PermanentZipCode],'') AS [PermanentZipCode]
      ,ISNULL([PermanentContactNo],'') AS [PermanentContactNo]
      ,ISNULL([EmergencyStreetOne],'') AS [EmergencyStreetOne]
      ,ISNULL([EmergencyStreetTwo],'') AS [EmergencyStreetTwo]
      ,ISNULL([EmergencyStreetThree],'') AS [EmergencyStreetThree]
      ,ISNULL([EmergencyCountry],'') AS [EmergencyCountry]
      ,ISNULL([EmergencyState],'') AS [EmergencyState]
      ,ISNULL([EmergencyCity],'') AS [EmergencyCity]
      ,ISNULL([EmergencyZipCode],'') AS [EmergencyZipCode]
      ,ISNULL([EmergencyContactNo],'') AS [EmergencyContactNo]
      ,ISNULL([PhoneNoCompany],'') AS [PhoneNoCompany]
      ,ISNULL([ExtensionNo],'') AS [ExtensionNo]
      ,ISNULL([CompanyEmail],'') AS [CompanyEmail]
      ,ISNULL([PersonalEmail],'') AS [PersonalEmail]
      ,ISNULL([MobileNumber],'') AS [MobileNumber]
	  ,ISNULL([WhatsAppContactNo],'') AS [WhatsAppContactNo]
    
  FROM  [sHrm].[tEmployeeCommunications]
             
  WHERE 
		EmployeeId = @rEmployeeId 
		--	((SM.Code=@rCode) OR (ISNULL(@rCode,'') = ''))
		--AND(SM.OrgId=@rOrgId)

 --     ((BM.Id = @rId) OR (@rId = 0))
	--AND  ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	--AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	--AND(BM.OrgId=@rOrgId)

--ORDER BY BM.OrderIndex ASC
  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCustomFieldAdd]
		 
	@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsObsolete int =0,
	@rDataTypeId int = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	

DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMAster WHERE Id = @rOrgId
 
IF(@rId = 0)	
BEGIN
    IF NOT EXISTS(SELECT 2 FROM sHrm.tEmployeeCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId AND OrgGroupId=@lOrgGroupId)
    --IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle)
	BEGIN
	      DECLARE @lNextNumber int
	      EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
Print @lNextNumber
	      INSERT INTO sHrm.tEmployeeCustomFieldMaster
	      (
		    Id
		   ,FieldTitle
		   ,FieldTypeId
		   ,FieldList
		   ,IsFieldMandatory
		   ,FieldGroup
		   ,FieldOrder
		   ,CreatedUserId
		   ,CreatedDateTime
		   ,OrgGroupId
		   ,IsObsolete
		   ,DataId
	      )
	     VALUES
	     (
		   @lNextNumber
		  ,@rFieldTitle
		  ,@rFieldTypeId
		  ,@rFieldList
		  ,@rIsFieldMandatory
		  ,@rFieldGroup
		  ,@rFieldOrder
		  ,@rCreatedUserId
		  ,@rCreatedDateTime
		  ,@lOrgGroupId
		  ,@rIsObsolete
		  ,@rDataTypeId
	     )
     END
	 ELSE
	 SELECT -101 As RESULT
END
	 	 
ELSE
BEGIN
	SET @lNextNumber = @rId

	
	
		UPDATE sHrm.tEmployeeCustomFieldMaster
		SET 
		FieldTitle = @rFieldTitle
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,IsObsolete=@rIsObsolete
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
		,UpdatedUserId=@rUpdatedUserId
		,UpdatedDateTime=@rUpdatedDateTime
		,DataId = @rDataTypeId
		WHERE Id = @rId 
	
	
END  
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCustomFieldDelete]

@rId int,
@rOrgId smallint=0,
@rOrgGroupId int=0
AS
BEGIN
 	 
	 IF NOT EXISTS(Select 1 from sHrm.tEmployeeCustomFieldData ECF 
	          INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=ECF.EmployeeId
	          INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId 
	        WHERE ECF.EmployeeCustomFieldId=@rId AND StatusId=7 AND OM.OrgGroupId=@rOrgGroupId
	           AND (ECF.FieldData <> '0' AND ECF.FieldData<>'' AND ECF.FieldData IS NOT NULL))
	 BEGIN
        
        DELETE ECF FROM sHrm.tEmployeeCustomFieldData ECF 
           INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=ECF.EmployeeId
	       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId 
        WHERE ECF.EmployeeCustomFieldId=@rId AND StatusId=1 AND OM.OrgGroupId=@rOrgGroupId
         
		DELETE	FROM sHrm.tEmployeeCustomFieldMaster WHERE Id=@rId 
		SELECT 1 AS RESULT
	  END 

	  ELSE

	    SELECT -101 As RESULT

 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCustomFieldDetailsGet]	 
	@rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		Id,
	    FieldTitle,	
		FieldGroup,	
		FieldTypeId,
		FieldList,
		IsFieldMandatory,
		IsObsolete,
		FieldOrder,
		ISNULL(DataId,0) DataId
	FROM 
		 sHrm.tEmployeeCustomFieldMaster

	WHERE 
		OrgGroupId = @rOrgGroupId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCustomFieldFieldAdd]
	  
	@rEmployeeId bigint=0,
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
print @rStrXml
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
	UPDATE sHrm.tEmployeeCustomFieldData 
			SET 
				EmployeeCustomFieldId=A.EmployeeCustomFieldId,
				FieldData= [sSetup].[fPortalXMLTagsReplaceReverse](A.FieldData),				
				UpdatedUserId=A.UpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
			FROM (
			SELECT
				EmployeeCustomFieldId,FieldData,UpdatedUserId,EmployeeId,AutoId	
				FROM OPENXML (@loDoc, '/Table/EmployeeCustomField', 1)
			WITH
			(
				AutoId int '@AutoId',		
				EmployeeId Bigint '@EmployeeId',
				EmployeeCustomFieldId INT '@EmployeeCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			))A 
			INNER JOIN sHrm.tEmployeeCustomFieldData ECM ON  ECM.EmployeeId=A.EmployeeId AND ECM.AutoID=A.AutoId 
	
	
	  INSERT INTO sHrm.tEmployeeCustomFieldData
		(
		    
			EmployeeId,
			EmployeeCustomFieldId,
			FieldData,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
		SELECT
				A.EmployeeId,A.EmployeeCustomFieldId,[sSetup].[fPortalXMLTagsReplaceReverse](A.FieldData),A.CreatedUserId,sCommon.fGetDate(),A.UpdatedUserId,sCommon.fGetDate()	
				FROM OPENXML (@loDoc, '/Table/EmployeeCustomField', 1)
			WITH
			(		
			    AutoId int '@AutoId',		
				EmployeeId Bigint '@EmployeeId',
				EmployeeCustomFieldId INT '@EmployeeCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			)A 
			LEFT JOIN sHrm.tEmployeeCustomFieldData ECM ON ECM.EmployeeId=A.EmployeeId AND ECM.AutoID=A.AutoId 
			WHERE ECM.EmployeeId IS NULL 
			
	
		
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCustomFieldUpdate]
		 
	@rId int,
	@rOrgId int,
	--@rFieldTitle nvarchar(500),
	--@rFieldTypeId tinyint,
	--@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	--@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	--@rCreatedUserId bigint,	
	--@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsObsolete int =0
	--@rDataTypeId int = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		BEGIN TRANSACTION	

			DECLARE @lOrgGroupId int=0
			SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMAster WHERE Id = @rOrgId
 
			--IF(@rId = 0)	
			--BEGIN
				--IF NOT EXISTS(SELECT 2 FROM sHrm.tEmployeeCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId AND OrgGroupId=@lOrgGroupId)
				----IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle)
				--BEGIN
	      --DECLARE @lNextNumber int
--	      EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
--Print @lNextNumber
--	      INSERT INTO sHrm.tEmployeeCustomFieldMaster
--	      (
--		    Id
--		   ,FieldTitle
--		   ,FieldTypeId
--		   ,FieldList
--		   ,IsFieldMandatory
--		   ,FieldGroup
--		   ,FieldOrder
--		   ,CreatedUserId
--		   ,CreatedDateTime
--		   ,OrgGroupId
--		   ,IsObsolete
--		   ,DataId
--	      )
--	     VALUES
--	     (
--		   @lNextNumber
--		  ,@rFieldTitle
--		  ,@rFieldTypeId
--		  ,@rFieldList
--		  ,@rIsFieldMandatory
--		  ,@rFieldGroup
--		  ,@rFieldOrder
--		  ,@rCreatedUserId
--		  ,@rCreatedDateTime
--		  ,@lOrgGroupId
--		  ,@rIsObsolete
--		  ,@rDataTypeId
--	     )
--     END
--	 ELSE
--	 SELECT -101 As RESULT
--END
	 	 
--ELSE
--BEGIN
	--SET @lNextNumber = @rId

	
	
			UPDATE sHrm.tEmployeeCustomFieldMaster
			SET 
				--FieldTitle = @rFieldTitle
				--,FieldTypeId = @rFieldTypeId
				--,FieldList=@rFieldList
				IsFieldMandatory=@rIsFieldMandatory
				,IsObsolete=@rIsObsolete
				--,FieldGroup=@rFieldGroup
				,FieldOrder=@rFieldOrder
				,UpdatedUserId=@rUpdatedUserId
				,UpdatedDateTime=@rUpdatedDateTime
				--,DataId = @rDataTypeId
			WHERE Id = @rId 
	
	
--END  
			SELECT @rId AS Result
	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCustomReportListGet]
	@rCreatedUserId bigint,
	@rOrgId smallint
AS
SET NOCOUNT ON

BEGIN
		SELECT 
			ECS.Id,
			ECS.Title,
			ECS.ColumnName,
			U.DisplayTitle AS CreatedUserName,
			CASE WHEN ECS.CreatedUserId = @rCreatedUserId THEN 'true' ELSE 'false' END AS IsDelete
		FROM sHrm.tEmployeeCustomSearch ECS
		INNER JOIN sSecurity.tUser U ON U.Id=ECS.CreatedUserId
		WHERE 
			    ((ECS.CreatedUserId = @rCreatedUserId) OR (ECS.IsCommon = 1))
			AND ECS.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCustomSearchGet]
(
	@rPageIndex int = null,
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'Number',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName[nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',
	@rEmployeeGroupId[nvarchar](50)='',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rLeftFromDate Date = '0001-01-01',
	@rLeftToDate Date = '9999-12-31',
	@rProbationUptoDate Date ,
	@rAhdocUptoDate Date ,
	@rPermanentDate Date ,
	@rDropDownStatusId int,
	
	@rNumber int = null,
	@rCustomTagId nvarchar(max) = '',
	@rDateOfResignation Date = '',
	@rIsOtherUser int=0,
	@rOrgGroupId int
 )
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	
	if @rDOBToDate = '9999-12-31'
	begin
		select @rDOBToDate = null
	end
	
	if @rLeftToDate = '9999-12-31'
	begin
		select @rLeftToDate = null
	end
	
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEMP')
	 BEGIN		
		DROP Table sHrm.tTempEMP
	 END

	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	

	IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT EM.Id AS EmployeeId1	
		INTO sHrm.tTempEMP
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.Id AND ISNULL(EM.IsOtherUser,0) = @rIsOtherUser 
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id
		WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND OM.OrgGroupId = @rOrgGroupId AND ISNULL(EM.IsOtherUser,0) = 0 AND (ISNULL(ECT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS EmployeeId1
		INTO sHrm.tTempEMP
	END



	SELECT * into sHrm.tTempEmployee1
	FROM sHrm.vEmployeeCustomSearch ECS 
	INNER JOIN sHrm.tTempEMP T2 ON ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = ''
	WHERE ((ECS.OrgId = @rOrgId) OR (@rOrgId = 0))
	AND ECS.OrgGroupId = @rOrgGroupId
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
	AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
	AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
	AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
	AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
	AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))
	AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
	AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='')
	AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='')
	AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='')
	AND (ISNULL(ECS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
	AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='')
	AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.Number = @rNumber) OR (ISNULL(@rNumber,0) = 0))
	AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
	AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
	AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
	AND ((ECS.DateofResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
	--AND ISNULL(ECS.IsOtherUser,0) = 0
	AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser
	ORDER BY ECS.Number
	
	SET @rOrderBy=Replace(@rOrderBy,'Number','Number')
	Print @rOrderBy
	SET @sql='SELECT TE.EmployeeId,TE.Code AS Code
	,[sHrm].[fEmployeeNameGet](TE.FirstName , TE.MiddleName, TE.LastName, ISNULL(OM.EmployeeNameFormatId,1)) AS Name
	,TE.EmployeeType,TE.OrganizationDepartment AS OrganizationDepartment,
	StatusName FROM sHrm.tTempEmployee1 TE
	INNER JOIN sSetup.tOrganizationMaster OM ON TE.OrgId = OM.Id
	ORDER BY '+@rOrderBy
	exec(@Sql)
	
	create table #EMPLOYEETEMP
	(
		tid int identity(1,1)
		,t_EmployeeId bigint
		,EmployeeName nvarchar(300)
	)
	select @Sql = 'insert into #EMPLOYEETEMP
	SELECT TE.EmployeeId, [sHrm].[fEmployeeNameGet](TE.FirstName , TE.MiddleName, TE.LastName, ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName
	FROM sHrm.tTempEmployee1 TE
	INNER JOIN sSetup.tOrganizationMaster OM ON TE.OrgId = OM.Id
	ORDER BY ' + @rOrderBy
	
	exec (@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lTotalRecords int,@lPageSize int = 10,@lResult nvarchar(max) = '',@lPaging varchar(max) = ''
	
	select @lTotalRecords = COUNT(*) FROM #EMPLOYEETEMP
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
	select @lResult = @lResult + '<tr><td><a style="cursor:pointer;" onclick="SelectEmp(' + convert(varchar,EmployeeId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
	<td>' + isnull(Organization,'') + '</td><td>' + isnull(OrganizationDepartment,'') + '</td><td>' + isnull(Code,'') + '</td><td>' + isnull(EmployeeName,'') + '</td><td>' + isnull(EmployeeType,'') + '</td>
	<td>' + isnull(StatusName,'') + '</td></tr>'	
	from sHrm.tTempEmployee1,#EMPLOYEETEMP
	where t_EmployeeId = EmployeeId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	order by tid
	
	select @lResult as EmpList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP TABLE #EMPLOYEETEMP
	DROP Table sHrm.tTempEmployee1
	DROP Table sHrm.tTempEMP
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeCustomTagAdd]
	
	@rEmployeeCustomTagImpXml [nvarchar](max),
	@rEmployeeId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEmployeeCustomTagImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sHrm.tEmployeeCustomTag WHERE EmployeeId=@rEmployeeId
	
		 INSERT INTO sHrm.tEmployeeCustomTag
		(
			EmployeeId,
			CustomTagId
			)
		SELECT
			EmployeeId,
			CustomTagId
		FROM OPENXML (@loDoc, '/Table/EmployeeCustomTag', 1)
		WITH ( 
				EmployeeId bigint,
				CustomTagId int
			  ) 

		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rDepartmentId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
	SELECT 
		COUNT(*) AS EmployeeCount
	FROM 
		sHrm.vExtEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	WHERE 
		(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (EM.OrgId = @rOrgId OR @rOrgId=0)
		AND EM.StatusId = 7
  END
  
  IF(@rType='Department')
  BEGIN
	SELECT 
		EM.DepartmentId, EM.DepartmentName,COUNT(*) AS EmployeeCount
	FROM 
		sHrm.vExtEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	WHERE 
		(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (EM.OrgId = @rOrgId OR @rOrgId=0)
		AND EM.StatusId = 7
	GROUP BY EM.DepartmentId, EM.DepartmentName
  END
  
  IF(@rType='Employee')
  BEGIN
	SELECT 
		EM.Code, EM.EmployeeName,COUNT(*) AS EmployeeCount
	FROM 
		sHrm.vExtEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	WHERE 
		(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (EM.OrgId = @rOrgId OR @rOrgId=0)
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId=0)
		AND EM.StatusId = 7
	GROUP BY EM.Code, EM.EmployeeName
  END
  
  IF(@rType='OrgGroup')
  BEGIN
	SELECT 
		OM.Id AS OrgId, OM.DisplayTitle AS Organization,COUNT(*) AS EmployeeCount
	FROM 
		sHrm.vExtEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	WHERE 
		(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (EM.OrgId = @rOrgId OR @rOrgId=0)
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId=0)
		AND EM.StatusId = 7
	GROUP BY OM.Id, OM.DisplayTitle
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDataModify]	 
	@rCategoryId int,
	@rXML nvarchar(max),
	@rSubCategoryField nvarchar(100),
	@rOrgGroupId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT

--BEGIN TRY
--BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup'
	OR @rSubCategoryField = 'MaritalStatus' OR @rSubCategoryField = 'OrganizationDepartment' OR @rSubCategoryField = 'EmployeeType' OR @rSubCategoryField = 'EmployeeBusinessHead'
			OR @rSubCategoryField = 'EmployeeGroup' OR @rSubCategoryField = 'EmployeeGrade' OR @rSubCategoryField = 'Relationship' OR  @rSubCategoryField = 'EmployeeDesignation'
			OR  @rSubCategoryField = 'Payroll' OR  @rSubCategoryField = 'PayrollGroup'  OR  @rSubCategoryField = 'OrgGroupDepartment' OR  @rSubCategoryField = 'EmployeeManager' 
			OR @rSubCategoryField = 'Tribe'
			)
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	ELSE IF (@rSubCategoryField = 'CasteCategory' )
		BEGIN
			SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')+'Id'
		END
	ELSE IF(@rSubCategoryField = 'NotEmployee')
		 BEGIN
		 SET @rSubCategoryField = Replace(@rSubCategoryField,'NotEmployee','IsOtherUser')
		 END
	ELSE IF(@rSubCategoryField = 'PaymentMode')
		 BEGIN
		 SET @rSubCategoryField = Replace(@rSubCategoryField,'PaymentMode','PayTypeId')
		 END

	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications) 
		
		set @sql='INSERT INTO sHrm.tEmployeeCommunications 
					(EmployeeId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCommunications set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCommunications EC 
					INNER JOIN ListofData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END
	    
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
					
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	Else IF(@rCategoryId= 3)
	
		BEGIN
	 
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		IF(@rSubCategoryField = 'EmployeeManagerId' )
			BEGIN

		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = (SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=LD.SubCategory AND ISNULL(IsOtherUser,0) = 0 ),
				  UpdatedUserId=LD.UpdatedUserId,
				  UpdatedDateTime=sCommon.fGetDate()  
				  from sHrm.tEmployeeJobDetail EJ	
				  INNER JOIN ListofData LD ON LD.EmployeeId=EJ.EmployeeId'
				  Exec sp_executesql @sql
		END

		ELSE
		BEGIN
	
		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeJobDetail EJ 
					INNER JOIN ListofData LD ON EJ.EmployeeId=LD.EmployeeId'
		
		Exec sp_executesql @sql
		END
		IF(@rSubCategoryField = 'DateOfJoining' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfJoining=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'DateOfleaving' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfleaving=''1900-01-01'''
			Exec sp_executesql @sql
		END		
		IF(@rSubCategoryField = 'PermanentDate' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE PermanentDate=''1900-01-01'''
			Exec sp_executesql @sql
		END	
		IF(@rSubCategoryField = 'ProbationUptoDate' )
		BEGIN

		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE ProbationUptoDate=''1900-01-01'''
			Exec sp_executesql @sql
		END	
		IF(@rSubCategoryField = 'AhdocUptoDate' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE AhdocUptoDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		IF(@rSubCategoryField = 'DateOfResignation' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfResignation=''1900-01-01'''
			Exec sp_executesql @sql
		END		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		
		
		IF(@rSubCategoryField = 'CustomTag')
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId, SubCategory, UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster WHERE  ISNULL(IsOtherUser,0) = 0 ) 

			 
			DELETE FROM sHrm.tEmployeeCustomTag WHERE EmployeeId In (SELECT EmployeeId FROM ListofData WHERE IsExist=0)
			set @sql = '
				        INSERT INTO sHrm.tEmployeeCustomTag (EmployeeId,CustomTagId)
						SELECT
							LD.EmployeeId,
							CTM.Id
						FROM sHrm.tCustomTagMaster CTM INNER JOIN ListofData LD ON CTM.Title = LD.SubCategory 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = LD.EmployeeId 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID 
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId  
						WHERE IsExist = 0 AND CTM.OrgGroupId = OGM.Id'
			 
		END
		ELSE
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster WHERE  ISNULL(IsOtherUser,0) = 0 ) 
		set @sql='UPDATE sHrm.tEmployeeMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeMaster HEM 
					INNER JOIN ListofData LD ON HEM.Id=LD.EmployeeId AND IsExist=0 AND ISNULL(HEM.IsOtherUser,0) = 0 ' 
		END
		Print @sql
		Exec sp_executesql @sql
		Drop Table ListofData
			SELECT 1 AS StatusId
	    END
	    
	    Else IF(@rCategoryId= 5)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 
						
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
		
		set @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
					(EmployeeId,'+@rSubCategoryField+',IsVPFDeduction,UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,0,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql			
		
		
		IF(@rSubCategoryField = 'EPFJoinDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE EPFJoinDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE IF(@rSubCategoryField = 'IncrementDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE IncrementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
			ELSE IF(@rSubCategoryField = 'RetirementDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE RetirementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'

			Exec sp_executesql @sql
		END
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	    
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	Drop Table ListofData
	--	SELECT -1 AS Result
	--END CATCH

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDataUpdateGet]
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rIsBlank bit,
	 @rStatusId int,
	 @rDepartmentId int,
	 @rGroupId int,
	 @rTypeId int,
	 @rGradeId int 
	  
	 --@rOrderBy int
	 
AS
SET NOCOUNT ON

BEGIN

		 DECLARE @lDataTypeId nvarchar(1)
		 IF(@rSubCategory = 'EmployeeBusinessHead')
		 BEGIN
			SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field='OrganizationHeadManager'
		 END
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		IF(@rSubCategory = 'MaritalStatus' OR @rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup'
		   OR @rSubCategory = 'OrganizationDepartment' OR @rSubCategory = 'EmployeeType' OR @rSubCategory = 'EmployeeBusinessHead'
			OR @rSubCategory = 'EmployeeGroup' OR @rSubCategory = 'EmployeeGrade' OR @rSubCategory = 'EmployeeDesignation'
			 OR @rSubCategory='Payroll' OR @rSubCategory='PayrollGroup'
			  OR @rSubCategory='OrgGroupDepartment'  OR @rSubCategory='EmployeeManager' OR @rSubCategory='CustomTag'
			  OR @rSubCategory='Tribe'
			 )
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id'
		END
		
		 ELSE IF ( @rSubCategory = 'CasteCategory')
			BEGIN 
		 		SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') + 'Id'
		 END
		 ELSE IF(@rSubCategory = 'NotEmployee')
		 BEGIN
		 SET @rSubCategory = Replace(@rSubCategory,'NotEmployee','IsOtherUser')
		 END
		 ELSE IF(@rSubCategory = 'PaymentMode')
		 BEGIN
		 SET @rSubCategory = Replace(@rSubCategory,'PaymentMode','PayTypeId')
		 END
		
		 Declare @Sql nvarchar(max)
		 print @lDataTypeId
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- EmployeeCommunication
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EC.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EC.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EC.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EC.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId 
							Where  ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15)) 
							
							+ 'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
					 WHEN 2 THEN -- Other
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EP.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EP.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EP.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EP.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EP.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EP.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EP.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EP.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EP.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
							
					WHEN 3 THEN -- JobDetail
					
					CASE WHEN  @rSubCategory ='EmployeeManagerId' then 
						
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),'''')
						WHEN '+@lDataTypeId+'=2 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0'')
						WHEN '+@lDataTypeId+'=3 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''False'')
						WHEN '+@lDataTypeId+'=4 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0'')
						END AS SubCategory 
							FROM 
							sHrm.vExtEmployeeMaster EM
							INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0),'''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'

							else

								'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
								CASE WHEN '+@lDataTypeId+'=1 THEN ISNULL(EJD.'+@rSubCategory+','''')
								WHEN '+@lDataTypeId+'=2 THEN ISNULL(EJD.'+@rSubCategory+',''0'')
								WHEN '+@lDataTypeId+'=3 THEN ISNULL(EJD.'+@rSubCategory+',''False'')
								WHEN '+@lDataTypeId+'=4 THEN ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')
								WHEN '+@lDataTypeId+'=5 THEN ISNULL(EJD.'+@rSubCategory+',''0'')
								END AS SubCategory 
								FROM 
								sHrm.vExtEmployeeMaster EM
								INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.EmployeeId  
								Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
								+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
								AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
								AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
								AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
								AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
								AND 
									('+CAST(@rIsBlank AS nvarchar(1))+'=0 
									OR ('+@lDataTypeId+'=1 AND ISNULL(EJD.'+@rSubCategory+','''')='''')
									OR ('+@lDataTypeId+'=2 AND ISNULL(EJD.'+@rSubCategory+',''0'')=''0'')
									OR ('+@lDataTypeId+'=3 AND ISNULL(EJD.'+@rSubCategory+',''False'')=''False'')
									OR ('+@lDataTypeId+'=4 AND ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
								) ORDER BY EM.Number'
							end
					 
					WHEN 4 THEN --General
						
						CASE WHEN  @rSubCategory ='CustomTagId' then 

							'Select  EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,STUFF( (SELECT DISTINCT '','' + CTM.Title FROM sHrm.tEmployeeCustomTag ECT INNER JOIN sHrm.tCustomTagMaster CTM ON ECT.CustomTagId=CTM.Id 
							WHERE ECT.EmployeeId = EM.EmployeeId FOR XML PATH ('''')), 1, 1, '''')  AS SubCategory
							
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.EmployeeId  
							LEFT JOIN sHrm.tCustomTagMaster CTM ON ECT.CustomTagId=CTM.Id

							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ECT.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ECT.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ECT.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ECT.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							GROUP BY EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,EM.Number ORDER BY EM.Number'
						else

						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
					    CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(HEM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(HEM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(HEM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(HEM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(HEM.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							INNER JOIN sHrm.tEmployeeMaster HEM ON HEM.Id=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(HEM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(HEM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(HEM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(HEM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
				   
					     end
					
					WHEN 5 THEN --Statutory
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
					    CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(ESO.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(ESO.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(ESO.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(ESO.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(ESO.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ESO.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ESO.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ESO.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ESO.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
				   
					END
		print @Sql    
	    
	   EXECUTE  sp_executesql @Sql
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDelete]
	 
           @rId bigint,
           @rOrgId smallint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
		delete D from  sHrm.tEmployeeJobDetail D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 
		 delete D from   sHrm.tEmployeeImages D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rId AND ISNULL(E.IsOtherUser,0) = 0
		 
		 
		  delete D from   sHrm.tEmployeeFamilyDetails D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId = @rId AND ISNULL(E.IsOtherUser,0) = 0
		 
		 
		   delete D from   sHrm.tEmployeeCommunications D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rId AND ISNULL(E.IsOtherUser,0) = 0
		 
		 
		 
			delete D from   sHrm.tEmployeePersonalDetail D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId=@rId AND ISNULL(E.IsOtherUser,0) = 0
		 
		 
		   delete D from   sHrm.tEmployeePreviousEmployment D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId =@rId AND ISNULL(E.IsOtherUser,0) = 0
		 
		 
			delete D from   sHrm.tEmployeeQualification D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId=@rId AND ISNULL(E.IsOtherUser,0) = 0
		 
		   delete D from    sHrm.tEmployeeStatutoryAndOther D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rId AND ISNULL(E.IsOtherUser,0) = 0
 
DELETE E FROM sHrm.temployeeMaster E WHERE E.OrgID = @rOrgId AND E.Id =@rId AND ISNULL(E.IsOtherUser,0) = 0

Select 1 As Result
 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDesignationMasterAdd]
	
	@rOrgId smallint,
	@rCode [nvarchar](20),
	@rTitle [nvarchar](100),	 
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],	 
	@OutDesignationId int = null output  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
	DECLARE @lNextNumber INT
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeDesignationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sHrm.tEmployeeDesignationMaster
		(
			Id,
			Code,
			Title,			 
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,		 
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
		SET @OutDesignationId = @lNextNumber -- addd for import functionality
	SELECT @lNextNumber AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH						
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDesignationMasterGet]
	@rOrgId smallint,
	@rId [int] = 0,
	@rCode [nvarchar](20) = '',
	@rTitle [nvarchar](100) = ''
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	 SET @rCode = sCommon.fSearchStringGet(@rCode)
	 SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		 
		 SELECT 
				EDM.Id AS Id,
				EDM.Code AS Code,
				EDM.Title AS Title,	 
				EDM.IsObsolete AS IsObsolete,
				EDM.CreatedUserId AS CreatedUserId,
				EDM.CreatedDateTime AS CreatedDateTime,
				EDM.UpdatedUserId AS UpdatedUserId,
				EDM.UpdatedDateTime AS UpdatedDateTime	
				
				
		 FROM sHrm.tEmployeeDesignationMaster EDM
		   
	 WHERE ((EDM.Id = @rId) OR (@rId = 0))
		   AND ((EDM.Code Like @rCode) OR (@rCode = ''))
		   AND ((EDM.Title Like @rTitle) OR (@rTitle = ''))		 
		   AND ((EDM.OrgId = @rOrgId) OR (@rOrgId = 0))
		  
		    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDesignationMasterModify]
	@rId [int],
	@rCode [nvarchar](20),
	@rTitle [nvarchar](100), 
	@rIsObsolete [bit], 
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sHrm.tEmployeeDesignationMaster
		SET 
			Code = @rCode,
			Title = @rTitle,		 
			IsObsolete = @rIsObsolete,		 
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDetailFormGet]	
	@rEmployeeId bigint = 0,	
	@rOrgId int = 0,
	@Tab nvarchar(20) = '',
	@rOrgGroupId int = 0,
	@rBatchId int = 0

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lTimesheetCol nvarchar(20) = DAY(sCommon.fGetDate())
	DECLARE @lFromDate Date = CAST(sCommon.fGetDate()-1 AS DATE)
	DECLARE @lToDate Date = CAST(sCommon.fGetDate() AS DATE)
	IF(LEN(@lTimesheetCol) = 1)
	BEGIN
		SET @lTimesheetCol = '0' + @lTimesheetCol
	END
	--Start
	IF(LOWER(@Tab) = 'overview')
	BEGIN
		-- Employee Header Details
		SELECT 
			EM.Id,
			EM.Code,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
			ISNULL(EP.DateOfBirth,'') AS DateOfBirth,
			ISNULL(GM.Title,'') AS Gender,
			ISNULL(EI.EmployeePhoto,0x) AS EmployeePhoto,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(EDM.Title,'') AS EmployeeDesignation,
			ISNULL(DM.Title,'') AS OrganizationDepartment,
			ISNULL(ETM.Title,'') AS EmployeeType
		FROM 
			sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID	
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId 
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId
	  WHERE 
			(EM.Id=@rEmployeeId)


		-- Attendance Card
		SELECT 
		(SELECT ISNULL(IsPresent,0) FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = @rEmployeeId AND AttendanceDate = CAST(sCommon.fGetDate() AS DATE)) AS TodayAttendance,
		(SELECT ISNULL(IsPresent,0) FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = @rEmployeeId AND AttendanceDate = CAST(sCommon.fGetDate() - 1 AS DATE)) AS YesterdayAttendance,	
		(SELECT ISNULL(COUNT(IsPresent),0) FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = @rEmployeeId AND MONTH(AttendanceDate) = MONTH(sCommon.fGetDate()) AND YEAR(AttendanceDate) = YEAR(sCommon.fGetDate()) AND IsPresent = 1) AS MonthlyPresence,
		(SELECT ISNULL(COUNT(IsPresent),0) FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = @rEmployeeId AND MONTH(AttendanceDate) = MONTH(sCommon.fGetDate()) AND YEAR(AttendanceDate) = YEAR(sCommon.fGetDate()) AND IsPresent = 0) AS MonthlyAbsence,
		ISNULL(WD.TotalDays,0) AS TotalDays,ISNULL(WD.TotalDays,0) AS WorkingDays FROM
		sHrm.vEmployeeCommonDetail EM INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId AND WD.BatchId = @rBatchId
		WHERE EmployeeId = @rEmployeeId AND WD.ForMonth =MONTH(sCommon.fGetDate())  AND WD.Foryear = YEAR(sCommon.fGetDate())

		--TimeSheet Card
		DECLARE @fDay nvarchar(10) = DAY(sCommon.fGetDate()-1)
		set @fDay= (SELECT CASE WHEN @fDay BETWEEN 0 AND 9 THEN RIGHT('0' + CAST(@fDay AS VARCHAR(2)), 2) ELSE CAST(@fDay AS NVARCHAR(10)) END)
		DECLARE @lDay nvarchar(10) = DAY(sCommon.fGetDate())
		set @lDay= (SELECT CASE WHEN @lDay BETWEEN 0 AND 9 THEN RIGHT('0' + CAST(@lDay AS VARCHAR(2)), 2) ELSE CAST(@lDay AS NVARCHAR(10)) END)
		Declare  @lQuery nvarchar(max) = '(Select 
					 D'+CAST(@lDay AS VARCHAR)+'_IN AS FirstIn,
					D'+CAST(@lDay AS VARCHAR)+'_OUT AS LastOut,
					D'+CAST(@lDay AS VARCHAR)+'_E AS Early,
					D'+CAST(@lDay AS VARCHAR)+'_L AS LateBy,
					D'+CAST(@lDay AS VARCHAR)+'_T AS Duration
					 from sBiometric.tMonthTrans
					WHERE EmployeeId = '+CAST(@rEmployeeId AS VARCHAR) + 'AND MONTH(Attn_Dt) = ''' +    CAST(MONTH(sCommon.fGetDate()) AS VARCHAR) + '''   AND SourceTypeId = '+CAST(95 AS VARCHAR)
					+') Union (Select 
					D'+CAST(@fDay AS VARCHAR)+'_IN AS FirstIn,
					D'+CAST(@fDay AS VARCHAR)+'_OUT AS LastOut,
					D'+CAST(@fDay AS VARCHAR)+'_E AS Early,
					D'+CAST(@fDay AS VARCHAR)+'_L AS LateBy,
					D'+CAST(@fDay AS VARCHAR)+'_T AS Duration
					from sBiometric.tMonthTrans
					WHERE EmployeeId = '+CAST(@rEmployeeId AS VARCHAR) + 'AND MONTH(Attn_Dt) = ''' +   CAST(MONTH(sCommon.fGetDate()) AS VARCHAR) + '''   AND SourceTypeId = '+CAST(95 AS VARCHAR)+')'
			EXEC (@lQuery)	
			print(@lQuery)


		-- Leave Card
		SELECT 
		ReportDate,FromDate,ToDate,NoOfLeave,LTM.Title AS LeaveType,LeaveReason,ISNULL(SM.Title,'Pending') AS StatusName 
		FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId INNER JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId AND SM.StatusTypeId = 113 
		WHERE EmployeeId = @rEmployeeId AND MONTH(ReportDate) = MONTH(sCommon.fGetDate()) AND YEAR(ReportDate) = YEAR(sCommon.fGetDate())
		
		--Payroll Card
		SELECT 
		ISNULL((SELECT ISNULL( IsApproved,0) FROM [sPayroll].[tPayProcess] PP inner join [sPayroll].[tPayProcessEmployee] PPE on PP.ID=PPe.PayProcessId WHERE EmployeeId = @rEmployeeId  AND  MONTH(SalaryMonth) = MONTH(sCommon.fGetDate()) AND YEAR(SalaryYear) = YEAR(sCommon.fGetDate())),0) AS CurrentMonthPayrollStatus,
		ISNULL((SELECT ISNULL( IsApproved, 0) FROM [sPayroll].[tPayProcess] PP inner join [sPayroll].[tPayProcessEmployee] PPE on PP.ID=PPe.PayProcessId WHERE EmployeeId = @rEmployeeId  AND  MONTH(SalaryMonth) = MONTH(sCommon.fGetDate()) AND YEAR(SalaryYear) = YEAR(sCommon.fGetDate())),0) AS LastMonthPayrollStatus

		--Timetable Card
		SELECT 
			ISNULL(SubjectId,0) AS SubjectId,
			ISNULL(SM.Title,'') AS Subject,
			ISNULL(TT.LectureNumber,'') AS LactureNumber,
			ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
			ISNULL(CL.Id,0) AS ClassId,
			ISNULL(DV.Code,'') AS ClassDivisionName,
			ISNULL(TTT.FromTime,'') AS Time
		FROM 
			sTimetable.tTimeTable TT  
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
			INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
			INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
			INNER JOIN sSetup.tClassMaster CL ON CL.Id = DV.ClassId
			INNER JOIN sTimetable.tTimeTableTime TTT ON TTT.DayId=TT.DayId AND TTT.TimeTableSchemaId=TT.TimeTableSchemaId AND TTT.LectureNumber=TT.LectureNumber AND TTT.DivisionId=TT.DivisionId
	
		WHERE
			((EmployeeId = @rEmployeeId))
			AND ((TT.DayId = DATEPART(WEEKDAY, sCommon.fGetDate())))
			AND ((DV.OrgId=@rOrgId) OR (@rOrgId=0))
			AND  ISNULL(EM.IsOtherUser,0) = 0
			order by TT.LectureNumber
		-- Lecture Online learning Card
		select 
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(SM.Title,'') AS SubjectName ,
			ISNULL(OL.Title,'') AS Title,
			CONVERT(NVARCHAR(5),OL.StartTime,108) AS  StartTime,
			CONVERT(NVARCHAR(5),OL.EndTime,108) AS EndTime,
			OL.IsCompleted as Status,
			  (SELECT
						  (
						  STUFF((SELECT ',' + a.Code
						  FROM
						  (
						  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
						  UNION ALL
						  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
						  ) a
						  FOR XML PATH ('')), 1, 1, '') ) ) as Source 
		from
			sAcademic.tOnlineLearning OL
						INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
						LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
						LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId


		Where OL.TeacherEmployeeId=@rEmployeeId AND OL.StartDate = CAST(sCommon.fGetDate() AS DATE)

		--Subject Card
		select distinct SM.Title AS SubjectName from
			[sAcademic].[tTeacherSubject] TS 
		  inner join [sSetup].[tSubjectMaster] SM on SM.Id=TS.SubjectId
		  where TS.EmployeeId=@rEmployeeId
		    -- Exam Schedule
		  SELECT
				ESGM.Title AS ExamName,
				SM.Title AS 'Subject',
				ED.ExamDate AS ExamDate,
				ED.ExamTime AS ExamTime,
				CM.Title AS ClassName,
				ISNULL(ED.ExamTopic,'') AS ExamTopic
			FROM 
				sAssessment.tExamMaster E 
				INNER JOIN sAssessment.tExamDetail ED ON E.Id = ED.ExamId
				INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
				INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
				LEFT JOIN sSetup.tClassMaster CM ON CM.Id = CS.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
				Where E.Id in (SELECT
								E.Id AS ExamId
								FROM 
								sAssessment.tExamMaster E
								INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
								Inner join sSetup.tDivisionMaster DM ON E.ClassId=DM.ClassId
								WHERE 
								E.BatchId = @rBatchId  AND ISNULL(E.IsPublishExamSchedule,0) = 1 AND DM.InchargeEmployeeId=@rEmployeeId)
	END
	IF(LOWER(@Tab) = 'employeealldetails')
	BEGIN
		SELECT 
		 --Personal Details
		 EM.Id,
		 EM.Code,
		 ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
		 IsNull(EM.ShortName,'') AS ShortName,
		 ISNULL(EP.UIDNumber,'') AS UIDNumber,
		 ISNULL(EP.DateOfBirth,'') AS DateOfBirth,
		 CONVERT(varchar(20) ,ISNULL(EP.DateOfBirth,''),105) AS DateOfBirthJSON,
		 ISNULL(GM.Title,'') AS Gender,
		 ISNULL(MM.Title,'') AS MeritalStatus,
		 ISNULL(BGM.Title,'') AS BloodGroup,
		 ISNULL(EP.Qualification,'') AS Qualification,
		 ISNULL(EP.FamilyCast,'') AS FamilyCast,
		 ISNULL(EM.StatusId,'') AS StatusId,
		 ISNULL(EM.Number,'') AS Number,
		 
		 --Communication
		 ISNULL(EC.PresentStreetOne,'')+' '+ISNULL(EC.PresentStreetTwo,'')+' '+ISNULL(EC.PresentStreetThree,'') AS PresentAddress,
		 ISNULL(EC.PresentCity,'') AS PresentCity,
		 ISNULL(EC.PresentState,'') AS PresentState,
		 ISNULL(EC.PresentCountry,'') AS PresentCountry,
		 ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
		 ISNULL(EC.PresentContactNo,'') AS PresentContactNo,
		
		 ISNULL(EC.PermanentStreetOne,'')+' '+ISNULL(EC.PermanentStreetTwo,'')+' '+ISNULL(EC.PermanentStreetThree,'') AS PermanentAddress,
		 ISNULL(EC.PermanentCity,'') AS PermanentCity,
		 ISNULL(EC.PermanentState,'') AS PermanentState,
		 ISNULL(EC.PermanentCountry,'') AS PermanentCountry,
		 ISNULL(EC.PermanentZipCode,'') AS PermanentZipCode,
		 ISNULL(EC.PermanentContactNo,'') AS PermanentContactNo,
		 
		 ISNULL(EC.EmergencyStreetOne,'')+' '+ISNULL(EC.EmergencyStreetTwo,'')+' '+ISNULL(EC.EmergencyStreetThree,'') AS EmergencyAddress,
		 ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
		 ISNULL(EC.EmergencyState,'') AS EmergencyState,
		 ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
		 ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
		 ISNULL(EC.EmergencyContactNo,'') AS EmergencyContactNo,
		
		 --Job Details
		 ISNULL(EJ.DateOfJoining,'') AS DateOfJoining,	
		 CONVERT(varchar(20),ISNULL(EJ.DateOfJoining,''),105) AS DateOfJoiningJSON,		
		 ISNULL(EJ.DateOfleaving ,'') AS DateOfLeaving,
		 (CONvert(varchar(20),EJ.DateOfleaving, 105)) AS DateOfLeavingJSON,
		 ISNULL(EJ.JobRemark,'') AS JobRemark,
		 ISNULL(EJ.ReferenceRemark,'') AS ReferenceRemark,
		 ISNULL(EDM.Title,'') AS EmployeeDesignation,
		 ISNULL(DM.Title,'') AS OrganizationDepartment,
		 ISNULL(EGM.Title,'') AS EmployeeGrade,
		 ISNULL(GrpM.Title,'') AS EmployeeGroup,
		 ISNULL(ETM.Title,'') AS EmployeeType,
		 ISNULL(EJ.ReasonOfleaving,'') AS ReasonOfleaving,
		 ISNULL(EJ.ProbationDays,'') AS ProbationDays,
		 ISNULL(EJ.ProbationUptoDate,'') AS ProbationUptoDate,
		 ISNULL(EJ.AhdocUptoDate,'') AS AhdocUptoDate,
		 ISNULL(EJ.PermanentDate,'') AS PermanentDate,
		 ISNULL(EJ.DateOfResignation,'') AS DateOfResignation,
		 ISNULL(EMM.FirstName,'') + ' ' + ISNULL(EMM.MiddleName,'') + ' ' + ISNULL(EMM.LastName,'') AS EmployeeManager,
		 ISNULL(OHM.FirstName,'') + ' ' + ISNULL(OHM.MiddleName,'') + ' ' + ISNULL(OHM.LastName,'') AS OrganizationHeadManager,
		 ISNULL(OH.DisplayTitle,'') AS OrganizationHead,
		 ISNULL(OGDM.Title,'') AS OrgGroupDepartment, 
		 ----Previous Employment
		 --ISNULL(EPE.CompanyName,'') AS PrevCompanyName,
		 --ISNULL(EPE.Designation,'') AS PrevDesignation,
		 --ISNULL(EPE.Duration,'') AS Duration,
		 --ISNULL(EPE.LastSalary,0) AS LastSalary,
		 --ISNULL(EPE.ReasonForLeaving,'') AS ReasonForLeaving,
		 --ISNULL(EPE.JobDescription,'') AS JobDescription,
		
		 --Notification Details
		 ISNULL(EC.PersonalEmail,'') As PersonalEmail,
		 ISNULL(EC.MobileNumber,'') AS MobileNumber,
		 ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,
		 ISNULL(EC.ExtensionNo,'') AS ExtensionNo,
		 ISNULL(EC.CompanyEmail,'') AS CompanyEmail,
		 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		
		 --EI.EmployeePhoto,
		 ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		 ISNULL(ESO.BankName,'') AS BankName,
		 ISNULL(ESO.Branch,'') AS BankBranch,
		 ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		 ISNULL(ESO.PanNumber,'') AS PanNumber,
		 ISNULL(ESO.EPFNumber,'') AS EPFNumber,
		 ISNULL(ESO.IncrementDate,'') AS IncrementDate,
		 Convert( varchar(20),ISNULL(ESO.IncrementDate,''),105) AS IncrementDateJSON,
		 ISNULL(ESO.BasicPay,0) AS BasicPay,
		 ISNULL(ESO.ESINumber,'') AS ESINumber,
		 ISNULL(ESO.EPFJoinDate,'') AS EPFJoinDate,
		 ISNULL(ESO.UAN,'') AS UAN,
		 ISNULL(ESO.AccountHolderName,'') AS AccountHolderName,
		 ISNULL(ESO.RetirementDate,'') AS RetirementDate,
		 ISNULL(PM.Title,'') AS PayRollTitle,
		 ISNULL(PGM.Title,'') AS PayRollGroupTitle,

	     --ISNULL(EFD.Occupation,'') AS Occupation,
		 convert(nvarchar(20),EM.Id) AS EmployeeIdText,
		 convert(nvarchar(20),@rOrgId) AS OrgIdText,
		 ISNULL(EJ.OrganizationDepartmentId,0) AS DepartmentId,
		 OM.DisplayTitle AS OrgTitle,
		 ISNULL(EP.AdhaarNumber,'') AS AdhaarNumber,
		 ISNULL(ESO.Payscale,'') AS Payscale,
		 --[sHrm].[fTeachingSubjectGet] (EM.Id) AS TeachingSubject
		 EJ.Subjects AS TeachingSubject,
		 RM.Title AS Religion,
		 CCM.Title AS CasteCategory,
		 EP.FamilyCast AS FamilyCast,
		 EP.UIDNumber,
		 EP.IdentificationMark1,
		 EP.AdhaarNumber,
		 EP.Qualification,
		 ISNULL(EI.EmployeePhoto,0x) AS EmployeePhoto,
		 ISNULL(EI.EmployeeSign,0x) AS EmployeeSign 
  FROM 
		sHrm.tEmployeeMaster EM 
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.ID = EC.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id
		INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID	
		--INNER JOIN sHrm.tEmployeePreviousEmployment EPE ON EPE.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeMaster EMM ON EMM.Id=EJ.EmployeeManagerId
		LEFT JOIN sHrm.tEmployeeMaster OHM ON OHM.Id=EJ.EmployeeBusinessHeadId
		LEFT JOIN sSetup.tOrganizationMaster OH ON OH.Id=LEFT(EJ.EmployeeBusinessHeadId,4)
		LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id=EJ.OrgGroupDepartmentId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EP.BloodGroupId    
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId
		LEFT JOIN sCommon.tMaritalStatusMaster MM ON MM.Id =  EP.MaritalstatusId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EP.ReligionId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId
		LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id=EJ.EmployeeGradeId
		LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJ.EmployeeGroupId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id
		LEFT JOIN sPayroll.tPayrollMaster PM ON ESO.PayrollId=PM.Id
		LEFT JOIN sPayroll.tPayrollGroupMaster PGM ON ESO.PayrollGroupId=PGM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EP.CastCategoryId
		--LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON EFD.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId  
  WHERE 
		(EM.Id=@rEmployeeId)
	END
	IF(LOWER(@Tab) = 'employeeattendance')
	BEGIN
		

		SELECT  
			EM.EmployeeName,
			ISNULL(EM.EmployeeGrade,'') AS EmployeeGrade,
			ISNULL(WD.TotalDays,0) AS TotalDays,
			ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
			(ISNULL(AT.TotalWorkingDays,0) - ((ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)))) AS PresentDays,
			(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS PayrollDays,
			(ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) AS LWP,  
			ISNULL(AT.PaidLeave,0) AS PaidLeave,
			ISNULL(AT.LWP,0) AS UnPaidLeave,
			MM.Title AS Month,
			WD.ForYear
		FROM 
			sHrm.vEmployeeCommonDetail EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId		
			INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.BatchId = @rBatchId
			INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId AND WD.ForMonth = AT.ForMonth AND WD.Foryear = AT.ForYear AND WD.BatchId = @rBatchId
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id = WD.ForMonth
		WHERE 
			EM.OrgID = @rOrgId AND EM.EmployeeId = @rEmployeeId 
		ORDER BY 
			WD.ForMonth
	END
	IF(LOWER(@Tab)='employeeleave')
	BEGIN
	SELECT 
			L.Id AS LeaveId
			,L.EmployeeId
			,L.ReportDate
			,L.FromDate
			,L.ToDate
			,LeavePeriodId
			,L.LeaveTypeId
			,CASE WHEN LeaveReason = '- Select -' THEN 'NA' ELSE LeaveReason END AS LeaveReason
			,LPM.Title AS LeavePeriod
			,LTM.Title AS LeaveType
			,EM.EmployeeName
			,EM.Code AS EmployeeCode
			,ISNULL(L.StatusId,0) AS StatusId
			,ISNULL(SM.Title,'Pending') AS StatusName
			,L.NoOfLeave      
			,ISNULL(L.FromTime,'') AS FromTime
			,ISNULL(L.ToTime,'') AS ToTime
			,ISNULL(L.LeaveRemark,'') AS LeaveRemark		       
		FROM 
			sHrm.tLeave L 
			INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId 
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId			
		WHERE 				
			L.EmployeeId = @rEmployeeId AND BatchId = @rBatchId AND L.OrgId = @rOrgId
		Order By L.FromDate DESC

	SELECT 
		ISNULL(LB.BalanceLeave,0) AS TotalBalance, 
		ISNULL(SUM(L.NoOfLeave),0) AS UsedBalance, 
		ISNULL(LB.BalanceLeave,0) - ISNULL(SUM(L.NoOfLeave),0) AS AvailableBalance, 
		ISNULL(LTM.Title,'') AS LeaveType ,
		ISNULL(SUM(L1.NoOfLeave),0) AS PendingBalance
	FROM 
		sHrm.tLeaveBalance LB 
		LEFT JOIN sHrm.tLeave L ON LB.EmployeeId=L.EmployeeId AND LB.BatchId = L.BatchId AND LB.LeaveTypeId = L.LeaveTypeId AND L.StatusId = 550 
		LEFT JOIN sHrm.tLeave L1 ON LB.EmployeeId=L1.EmployeeId AND LB.BatchId = L1.BatchId AND LB.LeaveTypeId = L1.LeaveTypeId  AND L1.StatusId = 549 
		LEFT JOIN sHrm.tLeaveTypeMaster LTM ON LB.LeaveTypeId = LTM.Id 
		WHERE LB.BatchId =@rBatchId AND LB.EmployeeId = @rEmployeeId
		GROUP BY LTM.Title,LB.BalanceLeave

	END

	IF(LOWER(@Tab)='certificate')
	BEGIN
	SELECT 'Employment' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sHrm].[tCertificateEmployment] WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId
		UNION ALL
		SELECT 'Experience' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sHrm].[tCertificateExperience] WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId 
		UNION ALL
		SELECT 'Increment' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sHrm].[tCertificateIncrement] WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND BatchId = @rBatchId
		UNION ALL
		SELECT 'Relieving' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sHrm].[tCertificateRelieving] WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId		
		
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDetailGet]
(
	@rOrgId int,
	@rId int = 0,
	@rCode [nvarchar](20) = ''
 )
AS
SET NOCOUNT ON

BEGIN
 
 SET @rCode = ISNULL(@rCode,'')
		
		SELECT 
				EM.Id AS Id,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS NameFull, 
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS NameSurname, 
				EJD.OrganizationDepartmentId AS DepartmentId,
				ODM.Title AS Department,
				ISNULL(EJD.EmployeeDesignationId,0) AS DesignationId ,
				ISNULL(EDM.Title,'') AS Designation,
				EJD.EmployeeGradeId			
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id			
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId						 			
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId		
		WHERE 
				((EM.Code Like   @rCode ) OR (@rCode = ''))
			AND ((EM.Id = @rId) OR (@rId = 0))
			AND EM.OrgId = @rOrgId
			AND ISNULL(EM.IsOtherUser,0) = 0 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDetailListGet]
(
	@rOrgId int,
	@rCode [nvarchar](20) = '',
	@rFirstname [nvarchar](50) = '',		
	@rLastName [nvarchar](50) = '',		
	@rDepartmentId [int] = 0,
	@rDesignationId [int] = 0
 )
AS
SET NOCOUNT ON

BEGIN
 
 		SET @rCode = ISNULL( sCommon.fSearchStringGet(@rCode),'')
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		SELECT 
				EM.Id AS Id,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS NameFull, 
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS NameSurname, 
				EJD.OrganizationDepartmentId AS DepartmentId,
				ODM.Title AS Department,
				ISNULL(EJD.EmployeeDesignationId,0) AS DesignationId ,
				ISNULL(EDM.Title,'') AS Designation,
				EJD.EmployeeGradeId			
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id			
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId						 			
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId		
		WHERE 
				((EM.Code Like '%' +  @rCode + '%' ) OR (@rCode = ''))
			AND ((EM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((EM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EJD.EmployeeDesignationId = @rDesignationId) OR (@rDesignationId = 0))	
			AND EM.OrgId = @rOrgId
			AND ISNULL(EM.IsOtherUser,0) = 0 
			ORDER BY EM.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDetailRemove]
 
	@rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
				-- SET @1Result = 1
				 
				-- IF EXISTS(Select 1 FROM sPayroll.tPayProcessEmployee Where EmployeeId = @rEmployeeId)
				-- BEGIN
				--   SET @1Result = -101				   
				-- END
				 
				-- IF EXISTS(Select 1 FROM sActivity.tActivityParticipant Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN
				--   SET @1Result = -101				   
				-- END
				 
				-- ELSE IF EXISTS(Select 1 FROM sHostel.tAssignRoom where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN
				--    SET @1Result = -101
				-- END			 
				 
				-- ELSE IF EXISTS(SELECT 1 FROM sCommunication.tPollMember WHERE SourceId = @rEmployeeId AND SourceTypeId = 95)
				--  BEGIN
				--     SET @1Result = -101
				--  END
				-- ELSE IF EXISTS(SELECT 1 FROM sHrm.tEmployeeAttendance Where EmployeeId = @rEmployeeId)
				-- BEGIN
				--    SET @1Result = -101
				-- END
				 
				-- ELSE IF EXISTS(Select 1 FROM sHostel.tHostelWarden Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END		
				-- ELSE IF EXISTS(Select 1 FROM sCommunication.tDiscussionGroupMember Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	
				-- ELSE IF EXISTS(Select 1 FROM sHrm.tLeave Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END				
				--ELSE IF EXISTS(Select 1 FROM sBi.tAction Where AssignedToEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END		 
				-- ELSE IF EXISTS(Select 1 FROM sBi.tAudit Where BackupAuditorEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	 
				-- ELSE IF EXISTS(Select 1 FROM sLibrary.tBookLog  Where ReaderSourceId = @rEmployeeId and ReaderSourceTypeId = 95)
				-- BEGIN 
				--    SET @1Result = -101
				-- END			 
				-- ELSE IF EXISTS(Select 1 FROM sFee.tChargeReceipt Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	 
				-- ELSE IF EXISTS(Select 1 FROM sSetup.tDivisionMaster Where InchargeEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sProcurement.tFirstAidEmoloyee Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sProcurement.tFirstAidInspection Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sOrderEntry.tIssueReturn Where ParticipantSourceId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sTimetable.tProxySetting Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sCommunication.tQueryCategoryMaster Where InchargeEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sAccounting.tReimbursement Where ParticipantSourceId = @rEmployeeId AND ParticipantSourceTypeId = 95 )
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sTimetable.tTimeTable Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sBi.tAudit Where LeadAuditorEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	 
				-- ELSE 
				--  BEGIN 
				--     SET @1Result = 1 
				     DELETE From sHrm.tEmployeeCustomTag Where EmployeeId=@rId
				     DELETE From sHrm.tEmployeeJobDetail Where EmployeeId = @rId 			
					 DELETE From sHrm.tEmployeePersonalDetail Where EmployeeId = @rId
					 DELETE From sHrm.tEmployeeCommunications Where EmployeeId = @rId
					 DELETE From sHrm.tEmployeeFamilyDetails Where EmployeeId = @rId
					 DELETE From sHrm.tEmployeePreviousEmployment Where EmployeeId = @rId
					 Delete From sHrm.tEmployeeImages where EmployeeId=@rId
					--Delete from sSecurity.tDivisionPermission Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					--Delete from sSecurity.tUserPreference Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					--Delete from sSecurity.tUserProfile Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					--Delete from sSecurity.tUserRole Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					--Delete from sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95
					
					UPDATE sSecurity.tUser SET SourceTypeId = 1,SourceId = 0 WHERE SourceTypeId = 95 AND SourceId = @rId
					
					DELETE FROM sHrm.tEmployeeMaster Where Id = @rId AND ISNULL(IsOtherUser,0) = 0 
				  COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDigitalFormDetailGet]

	  @rDigitalFormId int = 0,
	  @rEmployeeId bigint = 0,
	  @rId int=0,
	  @rEmployeeCode nvarchar(100)='',
	  --@rClassId bigint=0,
	  @rDepartmentId bigint=0,
	  @rStatusId smallint=0,
	  @rOrgId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
		ISNULL(DFS.AutoId,0) as Id,
		DFF.UpdateFieldId as UpdateFieldId,
		DF.Id as DigitalFormId,
		ECD.EmployeeId,
		ECD.Code as EmployeeCode,
		ECD.EmployeeName AS Name,
		ECD.DepartmentName AS DepartmentName,
		ISNULL(DF.Code,'') as Code,
		ISNULL(DF.Title,'') as Title,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT 'EmployeeCustomFields' as SubFunctionalityName FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId)
		WHEN DFF.FieldTypeId = 3 THEN 'EmployeeDocument' END AS SubFunctionalityName,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT FieldTitle FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId)
		WHEN DFF.FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 2 AND Id = DFF.UpdateFieldId ) END AS Field,

		DFF.UpdateFieldId,
		DFF.FieldTypeId,
		ISNULL(DFS.Remark,'') as Remark,
		ISNULL(DFS.ActionRemark,'') as ActionRemark,
		ISNULL(SM.Title,'') as Status,
		DFS.OldValue,
		DFS.NewValue,
		DFS.OldValueImage,
		DFS.NewValueImage
	FROM 
		sHrm.tDigitalForm DF
		INNER JOIN sHrm.tDigitalFormField DFF ON DF.Id = DFF.DigitalFormId
		INNER JOIN sHrm.tDigitalFormEmployee DFS ON DFS.DigitalFormId = DF.Id AND DFF.UpdateFieldId = DFS.UpdateFieldId
		INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = DFS.EmployeeId
		LEFT JOIN sCommon.tStatusMaster SM ON DFS.StatusId = SM.Id
	WHERE 
		((DF.Id = @rDigitalFormId) OR (@rDigitalFormId = 0)) 
		AND ((DF.Id = @rId) OR (@rId = 0))		
		AND ((ECD.Code = @rEmployeeCode) OR (@rEmployeeCode=0))
		--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((ECD.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		AND ((ECD.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND ((DFS.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((ECD.OrgId = @rOrgId) OR (@rOrgId = 0))
		ORDER By DFS.AutoId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDigitalFormGet]

	  @rDigitalFormId int,
	  @rEmployeeId bigint
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
		ISNULL(DFE.AutoId,0) as Id,
		DF.Id as DigitalFormId,
		DFF.UpdateFieldId as UpdateFieldId,
		ISNULL(DF.Code,'') as Code,
		ISNULL(DF.Title,'') as Title,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT 'EmployeeCustomFields' as SubFunctionalityName FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId)
		WHEN DFF.FieldTypeId = 3 THEN 'EmployeeDocument' END AS SubFunctionalityName,

		CASE WHEN DFF.FieldTypeId = 1 THEN (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = DFF.UpdateFieldId) 
		WHEN DFF.FieldTypeId = 2 THEN (SELECT FieldTitle FROM sHrm.tEmployeeCustomFieldMaster WHERE Id = DFF.UpdateFieldId)
		WHEN DFF.FieldTypeId = 3 THEN (SELECT DocumentName FROM sCommon.tSubmitDocumentMaster WHERE SubmitDocumentFunctionalityId = 2 AND Id = DFF.UpdateFieldId ) END AS Field,

		DFF.UpdateFieldId,
		DFF.FieldTypeId,
		ISNULL(DFE.Remark,'') as Remark,
		ISNULL(DFE.ActionRemark,'') as ActionRemark,
		ISNULL(SM.Title,'') as Status,
		(SELECT ECD.Code FROM sHrm.vEmployeeCommonDetail ECD WHERE EmployeeId = @rEmployeeId)  as EmployeeCode
	FROM 
		sHrm.tDigitalForm DF
		INNER JOIN sHrm.tDigitalFormField DFF ON DF.Id = DFF.DigitalFormId
		LEFT JOIN sHrm.tDigitalFormEmployee DFE ON DFE.DigitalFormId = DF.Id AND DFF.UpdateFieldId = DFE.UpdateFieldId AND DFE.EmployeeId = @rEmployeeId
		LEFT JOIN sCommon.tStatusMaster SM ON DFE.StatusId = SM.Id
	WHERE 
		((DF.Id = @rDigitalFormId) OR (@rDigitalFormId = 0)) 
		ORDER By DFE.AutoId
	 
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDocumentAdd]
	 
        @rEmployeeId bigint,
		@rDocumenetXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDocumenetXml
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		DELETE FROM [sHrm].[tEmployeeDocument] WHERE EmployeeId=@rEmployeeId
	
		INSERT INTO sHrm.tEmployeeDocument
		(
			EmployeeId, 
			SubmitDocumentMasterId,
			DocumentName,
			IsMigrate
		)
		SELECT
		   @rEmployeeId,
		   SubmitDocumentMasterId,
		   DocumentName,
		   isnull(IsMigrate,0)
		FROM OPENXML (@loDoc, '/Table/SubmitDocument', 1)
		WITH ( 
				SubmitDocumentMasterId int,
				DocumentName nvarchar(150),
				IsMigrate bit
			  ) 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDocumentAllBatchDepartmentWiseGet]

	@rOrgId smallint,
	@rCode nvarchar(20) = '',
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rDocumentId int=0

AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END

		SELECT 
				EC.EmployeeId AS Id,
				EC.Code AS Code,
				ISNULL(EC.EmployeeName, '') AS Name,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EC.DepartmentId,
				EC.DepartmentName,
				OM.DisplayTitle,
				OM.Id As OrgId,
				ISNULL([sHrm].[fEmployeeDocumentAllBatchDepartmentwiseget](@rDocumentId,EC.Id),'') AS DocumentName


		FROM 
				sHrm.vEmployeeCommunication EC
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EC.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EC.DepartmentId AND U.SourceTypeId=2017
		WHERE 
				((EC.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((EC.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
			AND ((EC.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((EC.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((EC.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EC.StatusId = @rStatusId) OR (@rStatusId = 0))	
			AND U.UserId = @rUserId
			AND (ISNULL(EC.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR ISNULL(@rMultiCode,'')='')
			
			ORDER BY EC.Number
	END TRY
	BEGIN CATCH
		SELECT -1 As Result,ERROR_LINE(),ERROR_MESSAGE()
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDocumentBulkAdd]
	 
        @rEmployeeId bigint,
		@rSubmitDocumentMasterId int ,
		@rDocumentName nvarchar(150)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	If NOT EXISTS(SELECT 1 FROM sHrm.tEmployeeDocument where EmployeeId=@rEmployeeId AND SubmitDocumentMasterId=@rSubmitDocumentMasterId)
	BEGIN
		INSERT INTO sHrm.tEmployeeDocument
		(
			EmployeeId, 
			SubmitDocumentMasterId,
			DocumentName
		)
		VALUES(@rEmployeeId,@rSubmitDocumentMasterId,@rDocumentName)
	
	SELECT 1 AS Result
	END
	ELSE
		BEGIN
			UPDATE  sHrm.tEmployeeDocument
			SET DocumentName = @rDocumentName
			WHERE EmployeeId =@rEmployeeId AND SubmitDocumentMasterId=@rSubmitDocumentMasterId
			SELECT 1 AS Result
		END
		
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDocumentDepartmentWiseGet]

	@rOrgId smallint,
	@rCode nvarchar(20) = '',
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rDocumentId int=0

AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END

		SELECT 
				EC.EmployeeId AS Id,
				EC.Code AS Code,
				ISNULL(EC.EmployeeName, '') AS Name,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EC.DepartmentId,
				EC.DepartmentName,
				OM.DisplayTitle,
				OM.Id As OrgId,
				ISNULL(sHrm.fEmployeeDocumentDepartmentwiseget(@rDocumentId,EC.Id),'') AS DocumentName
		FROM 
				sHrm.vEmployeeCommunication EC
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EC.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EC.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EC.DepartmentId AND U.SourceTypeId=2017
		WHERE 
				((EC.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((EC.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
			AND ((EC.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((EC.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((EC.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EC.StatusId = @rStatusId) OR (@rStatusId = 0))	
			AND U.UserId = @rUserId
			AND (ISNULL(EC.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR ISNULL(@rMultiCode,'')='')
			
			ORDER BY EC.Number
	END TRY
	BEGIN CATCH
		SELECT -1 As Result,ERROR_LINE(),ERROR_MESSAGE()
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDocumentget]
	 
	 @rOrgId int,
     @rCode nvarchar(20),
	 @rStatusId smallint,
	 @rDepartmentId int,
	 @rName [nvarchar](50) = '',	
	 @rSurName [nvarchar](50) = '',
	 @rEmployeeTypeId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rName= sCommon.fSearchStringGet(@rName)
		SET @rSurName= sCommon.fSearchStringGet(@rSurName)

    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
    select @cols = STUFF((SELECT ',' + QUOTENAME(DocumentName) 
                    from  sCommon.tSubmitDocumentMaster WHERE  OrgId=@rOrgId  AND SubmitDocumentFunctionalityId=2
                    Order by Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
      If(ISNULL(@Cols,'')='')
		 BEGIN
		    SELECT -101 AS Result
		 RETURN
		 END
  set @query = 'SELECT Name,Code,EmployeeType,Department,' + @cols + ' from 
             (
               SELECT
               ISNULL(EM.FirstName, '''') + ''  '' + ISNULL(EM.MiddleName, '''') + ''  '' + ISNULL(EM.LastName, '''') AS Name,S.DocumentName,EM.Code,ISNULL(ETM.Title,'''') As EmployeeType,
			  ODM.Title AS Department,CASE WHEN D.SubmitDocumentMasterId IS NULL  THEN ''No'' ELSE ''Yes'' END AS DocumentId
               FROM sHrm.tEmployeeMaster EM  
			   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			   INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			   INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
               LEFT JOIN [sHrm].[tEmployeeDocument] D ON D.EmployeeId=EM.Id
               LEFT JOIN sCommon.tSubmitDocumentMaster  S ON S.Id=D.SubmitDocumentMasterId AND SubmitDocumentFunctionalityId=2
		        WHERE ISNULL(EM.IsOtherUser,0) =0 
	          AND ((EM.OrgId=' + CAST(@rOrgId AS NVARCHAR(50))+'))
	          AND ((EJD.EmployeeTypeId=' + CAST(@rEmployeeTypeId AS NVARCHAR(30))+') OR ('+CAST(@rEmployeeTypeId AS NVARCHAR(50))+'= 0))
	          AND ((EJD.OrganizationDepartmentId =' + CAST(@rDepartmentId AS NVARCHAR(30))+') OR ('+CAST(@rDepartmentId AS NVARCHAR(50))+'= 0))
	          AND ((EM.Code  like  '''+ convert(varchar,@rCode )+''') OR ('''+convert(varchar,@rCode )+'''= ''''))
			  AND ((EM.FirstName  like  '''+ convert(varchar,@rName )+''') OR ('''+convert(varchar,@rName )+'''= ''''))
			  AND ((EM.LastName  like  '''+ convert(varchar,@rSurName )+''') OR ('''+convert(varchar,@rSurName )+'''= ''''))
	       	  AND ((EM.StatusId=' + CAST(@rStatusId AS NVARCHAR(30))+') OR ('+CAST(@rStatusId AS NVARCHAR(50))+'= 0))
              ) x
            pivot 
            (
                MIN(DocumentId)
                for DocumentName in (' + isnull(@cols,0) + ')  
            ) p order by Code'
            
  print @query
 execute(@query)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeDocumentSubmitGet]
	 
        @rEmployeeId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck
			,ISNULL(S.DocumentName,'') As FileName
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join [sHrm].[tEmployeeDocument]  S ON S.SubmitDocumentMasterId=D.id AND S.EmployeeId=@rEmployeeId
			WHERE OrgId=@rOrgId AND SubmitDocumentFunctionalityId='2'
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeFamilyDelete]
			
			@rParticipantId bigint,
		    @rOrgId int
AS
SET NOCOUNT ON
 
BEGIN 
      
   IF EXISTS (SELECT 1 FROM sOrderEntry.tIssueReturn where ParticipantSourceTypeId = 1001 AND ParticipantSourceId = @rParticipantId)
	 SELECT -1 AS RESULT
   ELSE IF EXISTS (SELECT 1 FROM sAccounting.tReimbursement where ParticipantSourceTypeId = 1001 AND ParticipantSourceId = @rParticipantId)
     SELECT -1 AS RESULT
   ELSE 
    BEGIN
     DELETE FROM sHrm.tEmployeeFamilyDetails WHERE Id = @rParticipantId AND OrgId = @rOrgId
      SELECT 1 AS RESULT
    END
         
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeFamilyDetailsAdd]
    
    @rId bigint,
	@rOrgId smallint,
	@rEmployeeId [bigint],
	@rRelationshipId [smallint],
	@rName [nvarchar](100),	
	@rDateOfBirth [date],
	@rBloodGroupId [tinyint],
	@rIsActive [bit], 
	@rCreatedUserId [bigint],
	@rOccupation [nvarchar](100),
	@rMobileNo nvarchar(20) = '',
	@rEmailId nvarchar(100) = ''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION
	
 IF NOT EXISTS(SELECT 1 FROM sHrm.tEmployeeFamilyDetails Where Id = @rId AND EmployeeId = @rEmployeeId AND OrgId = @rOrgId)
  
  BEGIN
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeFamilyDetails', 0, 1, 1,@outNextNumber = @lNextNumber output

		IF (@rBloodGroupId <= 0)
			SET @rBloodGroupId = NULL
 
		INSERT INTO sHrm.tEmployeeFamilyDetails
			(
				Id,
				EmployeeId,
				RelationshipId,
				Name,		
				DateOfBirth,
				BloodGroupId,
				IsActive,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				OrgId,
				Occupation,
				MobileNo,
				EmailId
			)
		VALUES
			(
				@lNextNumber,
				@rEmployeeId,
				@rRelationshipId,
				@rName,			
				@rDateOfBirth,
				@rBloodGroupId,
				@rIsActive,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgId,
				@rOccupation,
				@rMobileNo,
				@rEmailId
			)
	END
	ELSE
	  SET @lNextNumber = @rId
	  
	  UPDATE sHrm.tEmployeeFamilyDetails
	  SET  
	        Name = @rName,
			RelationshipId = @rRelationshipId,			
			DateOfBirth = @rDateOfBirth,
			BloodGroupId = @rBloodGroupId,
			IsActive = @rIsActive,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			Occupation = @rOccupation,
			MobileNo = @rMobileNo,
			EmailId = @rEmailId
	  WHERE 
			Id = @rId 
		AND EmployeeId = @rEmployeeId
	  
		SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeFamilyDetailsGet]
	
	@rOrgId smallint,
	@rEmployeeId [bigint] = 0

AS
SET NOCOUNT ON

BEGIN
		SELECT 
				FD.Id,
				EmployeeId,
				RelationshipId,
				RM.Title AS Relationship,
				Name,		 
				ISNULL(DateOfBirth,'0001/01/01') AS DateOfBirth,
				CONVERT(VARCHAR, DATEDIFF(YEAR, DateOfBirth, sCommon.fGetDate())) AS Age,
				ISNULL(BloodGroupId,0) AS BloodGroupId,		 
				ISNULL(BGM.Title,'')  AS BloodGroup,
				ISNULL(FD.Occupation,'') AS Occupation,
				IsActive,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				2 AS OperationState,
				ISNULL(MobileNo,'') AS MobileNo,
				ISNULL(EmailId,'') AS Email
		FROM 
				sHrm.tEmployeeFamilyDetails FD
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id = FD.RelationshipId		
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = FD.BloodGroupId		 
	  WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND FD.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeFamilyDetailsModify]
	@rId [int],
	@rEmployeeId [int],
	@rRelationshipId [smallint],
	@rName [nvarchar](100),	
	@rDateOfBirth [date],
	@rBloodGroupId [tinyint],
	@rIsActive [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
		--IF (@rDateOfBirth <= 0)
		--	SET @rDateOfBirth = NULL
			
		IF (@rBloodGroupId <= 0)
			SET @rBloodGroupId = NULL
			
 
			
	 UPDATE sHrm.tEmployeeFamilyDetails
		SET 
			Name = @rName,
			RelationshipId = @rRelationshipId,			
			DateOfBirth = @rDateOfBirth,
			BloodGroupId = @rBloodGroupId,
			IsActive = @rIsActive,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId AND EmployeeId = @rEmployeeId
	
	
	SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeForceDelete]
	 
           @rEmployeeId bigint,
           @rOrgId smallint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	 
		 --	* FrontOffice * --
		 -- LostFoundRegister
		 DELETE D FROM sFrontOffice.tLostFoundRegister D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.OwnwerSourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.OwnwerSourceId = @rEmployeeId AND D.OwnerSourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
	 
		 --	* Communication * --
		 -- DiscussionGroupMember
		 DELETE D FROM sCommunication.tDiscussionGroupMember D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.SourceId = @rEmployeeId AND D.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
		
		 --	* Academic * --
		 -- TeacherSubjectDivision
		 DELETE D FROM sAcademic.tTeacherSubjectDivision D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- LessonPlanResource
		 DELETE D FROM sAcademic.tLessonPlanResource D
		 INNER JOIN sAcademic.tLessonPlan DD ON DD.Id = D.LessonPlanId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- LessonPlan
		 DELETE D FROM sAcademic.tLessonPlan D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- Classwork
		 DELETE D FROM sAcademic.tClasswork D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
	 
		 --	* Canteen * --
		 -- CanteenIssueDetail
		 DELETE D FROM sCanteen.tCanteenIssueDetail D
		 INNER JOIN sCanteen.tCanteenIssue DD ON DD.Id = D.CanteenIssueId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- CanteenIssue
		 DELETE D FROM sCanteen.tCanteenIssue D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.SourceId = @rEmployeeId AND D.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
	 
		 --	* Library * --
		 -- BookLogPenalty
		 DELETE D FROM sLibrary.tBookLogPenalty D
		 INNER JOIN sLibrary.tBookLog DD ON DD.Id = D.BookLogId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.ReaderSourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.ReaderSourceId = @rEmployeeId AND DD.ReaderSourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- BookLog
		 DELETE D FROM sLibrary.tBookLog D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.ReaderSourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.ReaderSourceId = @rEmployeeId AND D.ReaderSourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
	 
	
		
		 --	* TimeTable * --
		 -- AssignTeacher
		 DELETE D FROM sTimetable.tAssignTeacher D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 --	* Hostel * --
		 -- AssignRoom
		 DELETE D FROM sHostel.tAssignRoom D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.SourceId = @rEmployeeId AND D.SourceTypeId = 95 AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- HostelWarden
		 DELETE D FROM sHostel.tHostelWarden D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- VisitorGatePass
		 DELETE D FROM sHostel.tVisitorGatePass D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.WhomToMeetSourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.WhomToMeetSourceId = @rEmployeeId AND WhomToMeetSourceTypeId = 95 AND ISNULL(E.IsOtherUser,0) = 0 
		
		 --	* Activity * --
		 -- ActivityParticipant
		 DELETE D FROM sActivity.tActivityParticipant D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.SourceId = @rEmployeeId AND D.SourceTypeId = 95 AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 --	* Payroll * --
		 
		 -- PayProcessEmployee
		 DELETE D FROM sPayroll.tPayProcessEmployee D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
	 
		 --	* Leave * --
		 
		 -- Leave
		 DELETE D FROM sHrm.tLeave D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- LeaveBalance
		 DELETE D FROM sHrm.tLeaveBalance D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- LeaveBalanceAdd
		 DELETE D FROM sHrm.tLeaveBalanceAdd D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		
		 --	* Certificate * --
		
		 -- CertificateEmployment
		 DELETE D FROM sHrm.tCertificateEmployment D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- CertificateExperience
		 DELETE D FROM sHrm.tCertificateExperience D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- CertificateRelieving
		 DELETE D FROM sHrm.tCertificateRelieving D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 
		 --	* Attendance * --
		 
		 -- EmployeeAttendance
		 DELETE D FROM sHrm.tEmployeeAttendance D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		
		 -- EmployeeAttendanceRegister
		 DELETE D FROM sHrm.tEmployeeAttendanceRegister D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
			
			


		 --	* Security * --
		
		 -- UserLog
		 DELETE D FROM sSecurity.tUserLog D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- UserDashboardNotification
		 DELETE D FROM sSecurity.tUserDashboardNotification D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- UserDashlet
		 DELETE D FROM sSecurity.tUserDashlet D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 

		 -- UserPreference
		 DELETE D FROM sSecurity.tUserPreference D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- UserProfile
		 DELETE D FROM sSecurity.tUserProfile D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- UserOrganization
		 DELETE D FROM sSecurity.tUserOrganization D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 
		
		 -- UserAccess
		 DELETE D FROM sSecurity.tUserAccess D
		 INNER JOIN sSecurity.tUser DD ON DD.Id = D.UserId
		 INNER JOIN sHrm.tEmployeeMaster E  ON DD.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND DD.SourceId = @rEmployeeId AND DD.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 

		 -- User
		 DELETE D FROM sSecurity.tUser D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.SourceId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.SourceId = @rEmployeeId AND D.SourceTypeId=95 AND ISNULL(E.IsOtherUser,0) = 0 

      
		 
		 
		 	 --	* Setup * --
		 -- Update DivisionMaster
		 UPDATE sSetup.tDivisionMaster SET InchargeEmployeeId = 0 WHERE InchargeEmployeeId = @rEmployeeId
		 
		
				 --	* Employee * --		
		
		 -- EmployeeJobDetail
		 DELETE D FROM  sHrm.tEmployeeJobDetail D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 		 
		 -- EmployeeImages
		 DELETE D FROM sHrm.tEmployeeImages D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- EmployeeFamilyDetails
		 DELETE D FROM sHrm.tEmployeeFamilyDetails D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- EmployeeCommunications
		 DELETE D FROM sHrm.tEmployeeCommunications D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- EmployeePersonalDetail
		 DELETE D FROM sHrm.tEmployeePersonalDetail D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId=@rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- EmployeePreviousEmployment
		 DELETE D FROM sHrm.tEmployeePreviousEmployment D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId  AND D.EmployeeId =@rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- EmployeeQualification
	     DELETE D FROM sHrm.tEmployeeQualification D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId=@rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
		 
		 -- EmployeeStatutoryAndOther
		 DELETE D FROM sHrm.tEmployeeStatutoryAndOther D
		 INNER JOIN sHrm.tEmployeeMaster E  ON D.EmployeeId = E.Id
		 WHERE E.OrgId = @rOrgId AND D.EmployeeId =@rEmployeeId  AND ISNULL(E.IsOtherUser,0) = 0 
		 
		    -- EmployeeMaster
		 DELETE E FROM sHrm.tEmployeeMaster E WHERE E.OrgID = @rOrgId AND E.Id =@rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 

		 --Start Charge
		DELETE CRD FROM sFee.tChargeReceiptDetail CRD
		INNER JOIN sFee.tChargeReceipt CR ON CRD.ChargeReceiptId=CR.Id
		WHERE CR.SourceId = @rEmployeeId AND CR.SourceTypeId = 95 AND CR.OrgId = @rOrgId
		DELETE FROM sFee.tChargeReceipt WHERE SourceId = @rEmployeeId AND SourceTypeId = 95 AND OrgId = @rOrgId
		--End Charge
		 
		 -- Start Online Learning --

		 Delete OLA from sAcademic.tOnlineLearningAssignment OLA 
		 INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLA.OnlineLearningId where OL.TeacherEmployeeId = @rEmployeeId

		 Delete OLAS from sAcademic.tOnlineLearningAssignmentSubmit OLAS 
		 INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLAS.OnlineLearningId where OL.TeacherEmployeeId = @rEmployeeId

		 Delete OLR from sAcademic.tOnlineLearningResource OLR 
		 INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLR.OnlineLearningId where OL.TeacherEmployeeId = @rEmployeeId

		 Delete OLR from sAcademic.tOnlineLearningReference OLR 
		 INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLR.OnlineLearningId where OL.TeacherEmployeeId = @rEmployeeId

		 Delete OLA from sAcademic.tOnlineLearningAttendance OLA
		 INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLA.OnlineLearningId where OL.TeacherEmployeeId = @rEmployeeId

		 Delete OLAL from sAcademic.tOnlineLearningAttendanceLog OLAL
		 INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLAL.OnlineLearningId where OL.TeacherEmployeeId = @rEmployeeId

		 Delete OLS from sAcademic.tOnlineLearningScope OLS
		 INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLS.OnlineLearningId where OL.TeacherEmployeeId = @rEmployeeId

		 Delete OMS from sAcademic.tOnlineMeetingSettings OMS
		 INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OMS.OnlineLearningId where OL.TeacherEmployeeId = @rEmployeeId

		 Delete OL from sAcademic.tOnlineLearning OL where OL.TeacherEmployeeId = @rEmployeeId

		 -- End Online Learning --
		 SELECT 1 AS Result
 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeGenerateReport]	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'Code',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',	 
	@rDOBFromDate Date = '',
	@rDOBToDate Date = '',
	@rDOJFromDate Date = '',
	@rDOJToDate Date = '',
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rIsCommonForOrg bit,
	@rLeftFromDate Date = '',
	@rLeftToDate Date = '',
	@rNumber int,
	@rProbationUptoDate Date = '',
	@rAhdocUptoDate Date = '',
	@rPermanentDate Date = '',
	@rCustomTagId nvarchar(max) = '',
	@rDateOfResignation Date = '',
	@rIsOtherUser int=0,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	
	--if @rColumnName <> ''
	--begin
	--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
	--end
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate=''
	IF(@rDOJFromDate IS NULL)
		SET @rDOJFromDate=''
	IF(@rLeftFromDate IS NULL)
		SET @rLeftFromDate=''
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate=''
	IF(@rDOJToDate IS NULL)
		SET @rDOJToDate=''
	IF(@rLeftToDate ='9999-12-31 00:00:00')
		SET @rLeftToDate=''

	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	
		DECLARE @lNextNumber BIGINT 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sHrm.tEmployeeCustomSearch
			(
				Id,Title,ColumnName,OrgId,Code,FirstName,LastName,EmployeeTypeId,StatusId,OrganizationDepartmentId,ReligionId,
				MaritalStatusId,Qualification,GenderId,EmployeeDesignationId,BloodGroupId,DOBFromDate,DOBToDate,DOJFromDate,
				DOJToDate,IsCommon,CreatedUserId,CreatedDateTime,IsCommonForOrg,CustomTag,DropDownStatusId,OrderBy)
		VALUES
			(
				@lNextNumber,@rTitle,@rColumnName,@rOrgId,@rCode,@rFirstName,@rLastName,@rEmployeeTypeId,@rStatusId,@rOrganizationDepartmentId,@rReligionId,
				@rMaritalStatusId,@rQualification,@rGenderId,@rEmployeeDesignationId,@rBloodGroupId,@rDOBFromDate,@rDOBToDate,@rDOJFromDate,
				@rDOJToDate,@rIsCommon,@rCreatedUserId,sCommon.fGetDate(),@rIsCommonForOrg,@rCustomTagId,@rDropDownStatusId,@rOrderBy)
			--SELECT @lNextNumber AS Result
	END
	
	IF(@rId > 0)
	BEGIN

		Select
				@rColumnName=ColumnName,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rEmployeeTypeId=EmployeeTypeId,
				@rStatusId=StatusId,
				@rOrganizationDepartmentId=OrganizationDepartmentId,
				@rReligionId=ReligionId,
				@rMaritalStatusId=MaritalStatusId,
				@rQualification=Qualification,
				@rGenderId=GenderId,
				@rEmployeeDesignationId=EmployeeDesignationId,
				@rBloodGroupId=BloodGroupId,					 
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOJFromDate=DOJFromDate,
				@rDOJToDate=DOJToDate,
				@rCustomTagId=CustomTag,
				@rDropDownStatusId=ISNULL(DropDownStatusId,0),
				@rOrderBy=ISNULL(OrderBy,'Code')
				
		FROM
			sHrm.tEmployeeCustomSearch
		WHERE
			Id=@rId
	END
	
	DECLARE @Sql nvarchar(MAX)
	SET @rColumnName=Replace(@rColumnName,',ID No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')

	SET @rColumnName=Replace(@rColumnName,',GR No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
 
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEmployee')
	 BEGIN		
		DROP Table sHrm.tTempEmployee
	 END
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEmployee13')
		 BEGIN
			DROP Table sHrm.tTempEmployee13
		 END
	 IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT EM.Id AS EmployeeId1	
		INTO sHrm.tTempEmployee
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.Id  AND ISNULL(EM.IsOtherUser,0) = @rIsOtherUser 
		WHERE EM.OrgId = @rOrgId AND (ISNULL(ECT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS EmployeeId1
		INTO sHrm.tTempEmployee
	END

	--select * from sHrm.tTempEmployee
	
	 DECLARE @lAvailableEmployeeColumns nvarchar(max)=''
			DECLARE @lAvailableEmployeeCustomRes nvarchar(max)=''
			Declare @Title as nvarchar(max)
			DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
		
			SET @lAvailableEmployeeColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sHrm.tEmployeeCustomFieldMaster PP  WHERE PP.OrgGroupId = @rOrgGroupId  
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					--print @lAvailableEmployeeColumns
	        IF(@lAvailableEmployeeColumns IS NOT NULL)
	        BEGIN	
			--Added alias CustomFieldTitle to FieldTitle column for mantis : 36567												
				set @query = 'SELECT  EmployeeId AS EmployeeId13 ,' + @lAvailableEmployeeColumns + ' into sHrm.tTempEmployee13 from 
					 (
						select PPE.FieldTitle AS CustomFieldTitle,PP.EmployeeId,FieldData
						FROM
						sHrm.tEmployeeCustomFieldData PP 
							INNER JOIN sHrm.tEmployeeCustomFieldMaster PPE ON PPE.Id = PP.EmployeeCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = PP.EmployeeId										
							WHERE EM.OrgId='''+convert(varchar(20),@rOrgId)+''' 
					) x 
					pivot 
					(
						Max(FieldData)
						for CustomFieldTitle in (' +@lAvailableEmployeeColumns  + ')
					) p'
                execute(@query)

				SELECT  T13.*, ECS.OrgID, Organization, ECS.EmployeeId, ECS.Code, ECS.FirstName, ECS.MiddleName, ECS.LastName, 
				[sHrm].[fEmployeeNameGet](ECS.FirstName, ECS.MiddleName, ECS.LastName, ISNULL(OM.EmployeeNameFormatId,1)) AS Name,
				ECS.StatusId, ECS.StatusName, ECS.IsObsolete, ECS.EmployeeJobDetail, ECS.EmployeeDesignationId, ECS.EmployeeDesignation, 
				ECS.OrganizationDepartmentId, ECS.OrganizationDepartment, ECS.DateOfJoining, ECS.EmployeeTypeId, ECS.EmployeeType, ECS.EmployeeGroup, 
				ECS.DateOfLeaving, ECS.ReasonOfLeaving, ECS.Subjects, ECS.EmployeePersonalDetailId, ECS.UIDNumber, ECS.DateOfBirth, ECS.GenderId, 
				ECS.Gender, ECS.ReligionID, ECS.Religion, ECS.MaritalStatusID, ECS.MaritalStatus, ECS.IdentificationMark1, ECS.BloodGroupId, 
				ECS.BloodGroup, ECS.Qualification, ECS.FamilyCast, ECS.CastCategory, ECS.EmployeeGroupId, ECS.MobileNumber, ECS.PersonalEmail, 
				ECS.CompanyEmail, ECS.PhoneNoCompany, ECS.ExtensionNo, ECS.PresentStreetOne, ECS.PresentStreetTwo, ECS.PresentStreetThree, ECS.PresentCountry
				,ECS.PresentState, ECS.PresentCity, ECS.PresentZipCode, ECS.PresentContactNo, ECS.PermanentStreetOne, ECS.PermanentStreetTwo, 
				ECS.PermanentStreetThree, ECS.PermanentCountry, ECS.PermanentState, ECS.PermanentCity, ECS.PermanentZipCode, ECS.PermanentContactNo
				,ECS.EmergencyStreetOne, ECS.EmergencyStreetTwo, ECS.EmergencyStreetThree, ECS.EmergencyCountry, ECS.EmergencyState, ECS.EmergencyCity, 
				ECS.EmergencyZipCode, ECS.EmergencyContactNo, ECS.EPFNumber, ECS.ESINumber, ECS.AccountNumber, ECS.BankName, ECS.Branch, ECS.IFSCNumber
				,ECS.PanNumber, ECS.BasicPay, ECS.IncrementDate, ECS.EPFJoinDate, ECS.Payscale, ECS.AdhaarNumber, ECS.RetirementDate, ECS.Number,
				ECS.ProbationUptoDate, ECS.AhdocUptoDate, ECS.DateOfResignation, ECS.IsOtherUser, ECS.CustomTag, ECS.OrgGroupId, ECS.AccountHolderName, 
				ECS.WhatsAppContactNo, ECS.PunchId, ECS.ShiftName, ECS.PresentAddress,ECS.PermanentDate,ECS.Age		--add age for mantis: 37124
				into sHrm.tTempEmployee2
				FROM sHrm.vEmployeeCustomSearch ECS
				INNER JOIN sHrm.tTempEmployee T2 ON (ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = '')
				INNER JOIN sSetup.tOrganizationMaster OM ON ECS.OrgId = OM.Id			
				LEFT JOIN  sHrm.tTempEmployee13 T13 ON ECS.EmployeeId= T13.EmployeeId13
		
				WHERE
				 ((ECS.OrgId = @rOrgId) OR (@rOrgId = 0))
				 AND ECS.OrgGroupId = @rOrgGroupId
				AND ((ECS.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
				AND ((ECS.FirstName Like @rFirstName  + '%') OR (ISNULL(@rFirstName,'') = ''))	 			 
				AND ((ECS.LastName Like @rLastName + '%')OR(ISNULL(@rLastName,'') = ''))
				AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
				AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
				AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
				AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
				AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
				AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 			
				AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
				AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
				AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
				AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
				AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))			
				AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
				AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
				AND ((ECS.Number = @rNumber) OR (@rNumber=0))
				AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
				AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
				AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
				AND ((ECS.DateOfResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
				AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser 
 
				SET @sql=
				'SELECT '+
				@rColumnName+' 
				FROM sHrm.tTempEmployee2 ORDER BY '+@rOrderBy
				--SELECT @sql

				exec(@Sql)
		
				DROP Table sHrm.tTempEmployee2
				DROP Table sHrm.tTempEmployee
				DROP Table sHrm.tTempEmployee13
		END
		ELSE
		BEGIN
				SELECT  ECS.OrgID, Organization, ECS.EmployeeId, ECS.Code, ECS.FirstName, ECS.MiddleName, ECS.LastName, 
				[sHrm].[fEmployeeNameGet](ECS.FirstName, ECS.MiddleName, ECS.LastName, ISNULL(OM.EmployeeNameFormatId,1)) AS Name,
				ECS.StatusId, ECS.StatusName, ECS.IsObsolete, ECS.EmployeeJobDetail, ECS.EmployeeDesignationId, ECS.EmployeeDesignation, 
				ECS.OrganizationDepartmentId, ECS.OrganizationDepartment, ECS.DateOfJoining, ECS.EmployeeTypeId, ECS.EmployeeType, ECS.EmployeeGroup, 
				ECS.DateOfLeaving, ECS.ReasonOfLeaving, ECS.Subjects, ECS.EmployeePersonalDetailId, ECS.UIDNumber, ECS.DateOfBirth, ECS.GenderId, 
				ECS.Gender, ECS.ReligionID, ECS.Religion, ECS.MaritalStatusID, ECS.MaritalStatus, ECS.IdentificationMark1, ECS.BloodGroupId, 
				ECS.BloodGroup, ECS.Qualification, ECS.FamilyCast, ECS.CastCategory, ECS.EmployeeGroupId, ECS.MobileNumber, ECS.PersonalEmail, 
				ECS.CompanyEmail, ECS.PhoneNoCompany, ECS.ExtensionNo, ECS.PresentStreetOne, ECS.PresentStreetTwo, ECS.PresentStreetThree, ECS.PresentCountry
				,ECS.PresentState, ECS.PresentCity, ECS.PresentZipCode, ECS.PresentContactNo, ECS.PermanentStreetOne, ECS.PermanentStreetTwo, 
				ECS.PermanentStreetThree, ECS.PermanentCountry, ECS.PermanentState, ECS.PermanentCity, ECS.PermanentZipCode, ECS.PermanentContactNo
				,ECS.EmergencyStreetOne, ECS.EmergencyStreetTwo, ECS.EmergencyStreetThree, ECS.EmergencyCountry, ECS.EmergencyState, ECS.EmergencyCity, 
				ECS.EmergencyZipCode, ECS.EmergencyContactNo, ECS.EPFNumber, ECS.ESINumber, ECS.AccountNumber, ECS.BankName, ECS.Branch, ECS.IFSCNumber
				,ECS.PanNumber, ECS.BasicPay, ECS.IncrementDate, ECS.EPFJoinDate, ECS.Payscale, ECS.AdhaarNumber, ECS.RetirementDate, ECS.Number,
				ECS.ProbationUptoDate, ECS.AhdocUptoDate, ECS.DateOfResignation, ECS.IsOtherUser, ECS.CustomTag, ECS.OrgGroupId, ECS.AccountHolderName, 
				ECS.WhatsAppContactNo, ECS.PunchId, ECS.ShiftName, ECS.PresentAddress,ECS.PermanentDate,ECS.Age		--add age for mantis: 37124
				into sHrm.tTempEmployee2
				FROM sHrm.vEmployeeCustomSearch ECS
				INNER JOIN sHrm.tTempEmployee T2 ON (ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = '')
				INNER JOIN sSetup.tOrganizationMaster OM ON ECS.OrgId = OM.Id	
				WHERE
				 ((ECS.OrgId = @rOrgId) OR (@rOrgId = 0))
				 AND ECS.OrgGroupId = @rOrgGroupId
				AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
				AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
				AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
				AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND ((ISNULL(ECS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
				AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
				AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
				AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
				AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
				AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 			
				AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
				AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
				AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
				AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
				AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))			
				AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
				AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
				AND ((ECS.Number = @rNumber) OR (@rNumber=0))
				AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
				AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
				AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
				AND ((ECS.DateOfResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
				AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser 
 
				SET @sql=
				'SELECT '+
				@rColumnName+' 
				FROM sHrm.tTempEmployee2 ORDER BY '+@rOrderBy
				
				exec(@Sql)
		
				DROP Table sHrm.tTempEmployee2
				DROP Table sHrm.tTempEmployee
		END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, Error_Message()
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeGet] 
	 @rFirstName NVARCHAR(50) = ''
	,@rLastName NVARCHAR(50) = ''
	,@rID NVARCHAR(50) = ''
	,@rOrgGroupId INT = 0
	,@rMiddleName NVARCHAR(50) = ''
	,@rContactNo NVARCHAR(50) = ''
	,@rCommonSearch NVARCHAR(500) = ''
	,@rUserId BIGINT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF OBJECT_ID('tempdb..#EmpAutoSearchTemp') IS NOT NULL
		DROP TABLE #EmpAutoSearchTemp

	CREATE TABLE #EmpAutoSearchTemp (
		EmployeeId BIGINT
		,EmployeeData NVARCHAR(max)
		,)

	INSERT INTO #EmpAutoSearchTemp
	SELECT EM.Id AS EmployeeId
		,EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName + ' ' + DM.DisplayTitle + ' ' + EM.Code AS EmployeeData
	FROM sHrm.tEmployeeMaster EM
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId

	SELECT [sHrm].[fEmployeeNameGet](VEM.FirstName, VEM.MiddleName, VEM.LastName, OM.StudentNameFormatId) AS Name
		,SM.Title AS StatusName
		,VEM.EmployeeId AS EmployeeId
		,VEM.Code
		,OM.DisplayTitle AS Organization
		,VEM.DepartmentName
		,VEM.DepartmentId
		,CASE 
			WHEN RIGHT(REPLACE(([sHrm].[fEmployeeContactsGet](VEM.EmployeeId)), ' ', ''), 1) = ','
				THEN reverse(stuff(reverse(([sHrm].[fEmployeeContactsGet](VEM.EmployeeId))), 1, 1, ''))
			WHEN LEFT(REPLACE(([sHrm].[fEmployeeContactsGet](VEM.EmployeeId)), ' ', ''), 1) = ','
				THEN STUFF(([sHrm].[fEmployeeContactsGet](VEM.EmployeeId)), 1, 1, '')
			ELSE ([sHrm].[fEmployeeContactsGet](VEM.EmployeeId))
			END AS ContactNo
		,EAS.EmployeeData
		,VEM.OrgId
		,ISNULL(EC.MobileNumber, '') AS MobileNumber
		,ISNULL(EC.CompanyEmail, '') AS Email
		,ISNULL(EI.EmployeePhoto, 0x) AS EmployeePhoto
		,ISNULL(U.Id, 0) AS UserId
		,EC.WhatsAppContactNo
	FROM [sHrm].[vEmployeeCommonDetail] VEM
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = VEM.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = VEM.OrgId
	INNER JOIN #EmpAutoSearchTemp EAS ON EAS.EmployeeId = VEM.EmployeeId
	LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = VEM.EmployeeId
	LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VEM.EmployeeStatusId
	LEFT JOIN [sHrm].[tEmployeeImages] EI ON EI.EmployeeId = VEM.EmployeeId
	LEFT JOIN sSecurity.tUser U ON U.OrgId = OM.Id AND U.SourceId = VEM.EmployeeId AND U.SourceTypeId = 95
	WHERE ((VEM.FirstName LIKE @rFirstName + '%') OR (@rFirstName = ''))
		AND ((VEM.LastName LIKE @rLastName + '%') OR (@rLastName = ''))
		AND ((VEM.MiddleName LIKE @rMiddleName + '%') OR (@rMiddleName = ''))
		AND ((VEM.Code = @rID) OR (@rID = ''))
		AND ((EC.MobileNumber = @rContactNo) OR (EC.PermanentContactNo = @rContactNo) OR (EC.EmergencyContactNo = @rContactNo)
			OR (EC.PhoneNoCompany = @rContactNo) OR (EC.PresentContactNo = @rContactNo) OR (EC.WhatsAppContactNo = @rContactNo)
			OR (@rContactNo = ''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((EAS.EmployeeData LIKE '%' + @rCommonSearch + '%') OR (@rCommonSearch = ''))

	DROP TABLE #EmpAutoSearchTemp
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeGradeMasterAdd]
           
           @rId int,
           @rCode nvarchar(50),
           @rTitle nvarchar(100),      
           @rIsFixPay bit,
           @rIsPayrollApplicable bit,          
           @rOrgId smallint,
           @rIsObsolete bit,
           @rCreatedUserId bigint,
           @rOrderIndex int 
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint
	 
    IF (@rId = 0)
	
	BEGIN	
	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeGradeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output	
		INSERT INTO [sHrm].[tEmployeeGradeMaster]
           (
            [Id]
           ,[Code]
           ,[Title]          
           ,[IsFixPay]
           ,[IsPayrollApplicable]         
           ,[OrgId]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime] 
           ,OrderIndex         
           )
     VALUES
           (
           @lNextNumber,
           @rCode,
           @rTitle, 
           @rIsFixPay, 
           @rIsPayrollApplicable,             
           @rOrgId, 
           @rIsObsolete, 
           @rCreatedUserId,
           sCommon.fGetDate(),
           @rOrderIndex     
           )	
	END
	ELSE
    BEGIN
	SET  @lNextNumber = @rId
		 UPDATE [sHrm].[tEmployeeGradeMaster]
		 SET 		   
		   [Code] = @rCode 
		  ,[Title] = @rTitle 
		  ,[IsFixPay] = @rIsFixPay
		  ,[IsPayrollApplicable] = @rIsPayrollApplicable		    
		  ,[IsObsolete] = @rIsObsolete       
		  ,[UpdatedUserId] = @rCreatedUserId   
		  ,UpdatedDateTime = sCommon.fGetDate()
		  ,OrderIndex = @rOrderIndex		                    
		 WHERE Id = @rId
	     END 
	   
	     SELECT @lNextNumber AS Result	   
	     COMMIT TRANSACTION
	     	    
	END TRY	
	  BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	  END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeGradeMasterListGet]
(
    @rId int = 0,
    @rName nvarchar(20),
  	@rOrgId [smallint], 
	@rCode [nvarchar](20),	 
	@rIsWildCardSearch bit
 )
AS
SET NOCOUNT ON

BEGIN
    
    IF(@rIsWildCardSearch = 0)
    BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rName = sCommon.fSearchStringGet(@rName) 
    END
	   SELECT  EGM.[Id]
			  ,EGM.[Code]
			  ,EGM.[Title]
			  ,[IsFixPay]
			  ,[IsPayrollApplicable]		  
			  ,EGM.[IsObsolete]
			  ,OrderIndex		 
 
    FROM  [sHrm].[tEmployeeGradeMaster] EGM  
	WHERE 
			EGM.OrgId = @rOrgId			 
			AND ((EGM.Id  = @rId) OR (@rId = 0))
			AND ((EGM.Code Like  @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((EGM.Title Like @rName) OR (ISNULL(@rName,'')='')) 
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeGradeMasterRemove]
 (
	@rGradeId int
 )
AS
SET NOCOUNT ON	
	DECLARE @1Result Int	
	BEGIN TRY	
    BEGIN TRANSACTION
			BEGIN	 
				 --SET @1Result = 1
				 
				 IF EXISTS(Select 1 FROM sHrm.tLeaveTypeGradeSettings Where EmployeeGradeId = @rGradeId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				 ELSE IF EXISTS(Select 1  FROM sHrm.tEmployeeJobDetail Where EmployeeGradeId = @rGradeId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				 ELSE IF EXISTS(Select 1  FROM sHrm.tWorkingDays Where EmployeeGradeId = @rGradeId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				 ELSE IF EXISTS(Select 1 From sPayroll.tPaySetup Where SourceId = @rGradeId AND SourceTypeId = 483)
				 BEGIN
				   SET @1Result = -101
				 END
				 ELSE
				   BEGIN
				      DELETE FROM sHrm.tEmployeeGradeMaster Where Id = @rGradeId 
				      SET @1Result = 1
				   END
				 
				 --ELSE IF EXISTS(Select 1 FROM sHostel.tAssignRoom where SourceId = @rEmployeeId AND SourceTypeId = 95)
				 --BEGIN
				 --   SET @1Result = -101
				 --END			 
				 
				 --ELSE IF EXISTS(SELECT 1 FROM sCommunication.tPollMember WHERE SourceId = @rEmployeeId AND SourceTypeId = 95)
				 -- BEGIN
				 --    SET @1Result = -101
				 -- END
				 --ELSE IF EXISTS(SELECT 1 FROM sHrm.tEmployeeAttendance Where EmployeeId = @rEmployeeId)
				 --BEGIN
				 --   SET @1Result = -101
				 --END
				 
				 --ELSE IF EXISTS(Select 1 FROM sHostel.tHostelWarden Where EmployeeId = @rEmployeeId)
				 --BEGIN 
				 --   SET @1Result = -101
				 --END		
				 --ELSE IF EXISTS(Select 1 FROM sCommunication.tDiscussionGroupMember Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				 --BEGIN 
				 --   SET @1Result = -101
				 --END	
				 	  
			SELECT @1Result AS Result
				 	  
			END
	  COMMIT TRANSACTION
      END TRY
         
      BEGIN CATCH
	  ROLLBACK TRANSACTION
	  SELECT -1 AS RESULT
	  END CATCH

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeHistoryBatchWiseAdd]
	 
	 @rEmployeeId bigint,
	 @rBatchId int,
	 @rOrgId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 BEGIN TRY
	 BEGIN TRANSACTION	
	 Print 1
	 -- Employee Master
	 IF EXISTS(SELECT 1 FROM sHrm.tBatchEmployeeMaster WHERE Id = @rEmployeeId AND BatchId = @rBatchId)
	 BEGIN
		UPDATE BE
		SET BE.OrgID = E.OrgId,
			BE.Code = E.Code,
			BE.FirstName = E.FirstName,
			BE.MiddleName = E.MiddleName,
			BE.LastName = E.LastName,
			BE.ShortName = E.ShortName,
			BE.StatusId = E.StatusId,
			BE.IsObsolete = E.IsObsolete,
			BE.CreatedUserId = E.CreatedUserId,
			BE.CreatedDateTime = E.CreatedDateTime,
			BE.UpdatedUserId = E.UpdatedUserId,
			BE.UpdatedDateTime = E.UpdatedDateTime,
			BE.ShiftId = E.ShiftId,
			BE.PunchId = E.PunchId
		FROM sHrm.tBatchEmployeeMaster BE
		INNER JOIN sHrm.tEmployeeMaster E ON E.Id = BE.Id
		WHERE E.Id = @rEmployeeId AND ISNULL(E.IsOtherUser,0) = 0 
	 END
	 ELSE
	 BEGIN
		INSERT INTO sHrm.tBatchEmployeeMaster
		(
			   OrgID, Id,BatchId,Code,FirstName,MiddleName,LastName,ShortName,StatusId,IsObsolete,
			   CreatedUserId,CreatedDateTime,UpdatedUserId, UpdatedDateTime,ShiftId,PunchId
		)
		SELECT OrgID, @rEmployeeId,@rBatchId,Code,FirstName,MiddleName,LastName,ShortName,StatusId,IsObsolete,
			   CreatedUserId,CreatedDateTime,UpdatedUserId, UpdatedDateTime,ShiftId,PunchId
		FROM   sHrm.tEmployeeMaster WHERE Id = @rEmployeeId AND ISNULL(IsOtherUser,0) = 0 
	 END
	 -- Ends
	 Print 2
	 -- Employee Communication
	 IF EXISTS(SELECT 1 FROM sHrm.tBatchEmployeeCommunications WHERE EmployeeId = @rEmployeeId AND BatchId = @rBatchId)
	 BEGIN
		UPDATE BEC
		SET BEC.PresentStreetOne = E.PresentStreetOne,
		    BEC.PresentStreetTwo = E.PresentStreetTwo,
		    BEC.PresentStreetThree = E.PresentStreetThree,
		    BEC.PresentCountry = E.PresentCountry,
		    BEC.PresentState = E.PresentState,
		    BEC.PresentCity = E.PresentCity,
		    BEC.PresentZipCode = E.PresentZipCode,
		    BEC.PresentContactNo = E.PresentContactNo,
		    BEC.PermanentStreetOne = E.PermanentStreetOne,
		    BEC.PermanentStreetTwo = E.PermanentStreetTwo,
		    BEC.PermanentStreetThree = E.PermanentStreetThree,
		    BEC.PermanentCountry = E.PermanentCountry,
		    BEC.PermanentState = E.PermanentState,
		    BEC.PermanentCity = E.PermanentCity,
		    BEC.PermanentZipCode = E.PermanentZipCode,
		    BEC.PermanentContactNo = E.PermanentContactNo,
		    BEC.EmergencyStreetOne = E.EmergencyStreetOne,
		    BEC.EmergencyStreetTwo = E.EmergencyStreetTwo,
		    BEC.EmergencyStreetThree = E.EmergencyStreetThree,
		    BEC.EmergencyCountry = E.EmergencyCountry,
		    BEC.EmergencyState = E.EmergencyState,
		    BEC.EmergencyCity = E.EmergencyCity,
		    BEC.EmergencyZipCode = E.EmergencyZipCode,
		    BEC.EmergencyContactNo = E.EmergencyContactNo,
		    BEC.PhoneNoCompany = E.PhoneNoCompany,
		    BEC.ExtensionNo = E.ExtensionNo,
		    BEC.CompanyEmail = E.CompanyEmail,
		    BEC.PersonalEmail = E.PersonalEmail,
		    BEC.MobileNumber = E.MobileNumber,
		    BEC.CreatedUserId = E.CreatedUserId,
		    BEC.CreatedDateTime = E.CreatedDateTime,
		    BEC.UpdatedUserId = E.UpdatedUserId,
		    BEC.UpdatedDateTime = E.UpdatedDateTime
		FROM sHrm.tBatchEmployeeCommunications BEC
		INNER JOIN sHrm.tEmployeeCommunications E ON E.EmployeeId = BEC.EmployeeId
		WHERE E.EmployeeId = @rEmployeeId
	 END
	 ELSE
	 BEGIN
		INSERT INTO sHrm.tBatchEmployeeCommunications
		(
			   EmployeeId, BatchId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,PresentState,
			   PresentCity,PresentZipCode,PresentContactNo,PermanentStreetOne,PermanentStreetTwo,PermanentStreetThree,
			   PermanentCountry,PermanentState,PermanentCity,PermanentZipCode,PermanentContactNo,
			   EmergencyStreetOne,EmergencyStreetTwo,EmergencyStreetThree,EmergencyCountry,EmergencyState,
			   EmergencyCity,EmergencyZipCode,EmergencyContactNo,PhoneNoCompany,ExtensionNo,CompanyEmail,
			   PersonalEmail,MobileNumber,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
		)
		SELECT EmployeeId, @rBatchId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,PresentState,
			   PresentCity,PresentZipCode,PresentContactNo,PermanentStreetOne,PermanentStreetTwo,PermanentStreetThree,
			   PermanentCountry,PermanentState,PermanentCity,PermanentZipCode,PermanentContactNo,
			   EmergencyStreetOne,EmergencyStreetTwo,EmergencyStreetThree,EmergencyCountry,EmergencyState,
			   EmergencyCity,EmergencyZipCode,EmergencyContactNo,PhoneNoCompany,ExtensionNo,CompanyEmail,
			   PersonalEmail,MobileNumber,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
		FROM   sHrm.tEmployeeCommunications WHERE EmployeeId = @rEmployeeId
	 END
	 --Ends
	 Print 3
	 -- Employee Family Details
	 IF EXISTS(SELECT 1 FROM sHrm.tBatchEmployeeFamilyDetails WHERE EmployeeId = @rEmployeeId AND BatchId = @rBatchId)
	 BEGIN
		UPDATE EFD
		SET EFD.OrgId = E.OrgId,
			EFD.RelationshipId = E.RelationshipId,
			EFD.Name = E.Name,		
			EFD.DateOfBirth = E.DateOfBirth,
			EFD.BloodGroupId = E.BloodGroupId,
			EFD.IsActive = E.IsActive,
			EFD.CreatedUserId = E.CreatedUserId,
			EFD.CreatedDateTime = E.CreatedDateTime,
			EFD.UpdatedUserId = E.UpdatedUserId,
			EFD.UpdatedDateTime = E.UpdatedDateTime,
			EFD.Occupation = E.Occupation
		FROM sHrm.tBatchEmployeeFamilyDetails EFD
		INNER JOIN sHrm.tEmployeeFamilyDetails E ON E.EmployeeId = EFD.EmployeeId
		WHERE E.EmployeeId = @rEmployeeId
	 END
	 ELSE
	 BEGIN
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tBatchEmployeeFamilyDetails', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sHrm.tBatchEmployeeFamilyDetails
		(
			 OrgId,Id,EmployeeId,BatchId,RelationshipId,Name,DateOfBirth,BloodGroupId,IsActive,CreatedUserId,
			 CreatedDateTime,UpdatedUserId,UpdatedDateTime,Occupation
		)
		SELECT OrgId,@lNextNumber,EmployeeId,@rBatchId,RelationshipId,Name,DateOfBirth,BloodGroupId,IsActive,CreatedUserId,
			   CreatedDateTime,UpdatedUserId,UpdatedDateTime,Occupation
		FROM   sHrm.tEmployeeFamilyDetails WHERE EmployeeId = @rEmployeeId
	 END
	 --Ends
	 Print 4
	 -- Employee Job Detail
	 IF EXISTS(SELECT 1 FROM sHrm.tBatchEmployeeJobDetail WHERE EmployeeId = @rEmployeeId AND BatchId = @rBatchId)
	 BEGIN
		UPDATE EJD
		SET EJD.OrgId = E.OrgId,
			EJD.EmployeeDesignationId = E.EmployeeDesignationId,
			EJD.OrganizationDepartmentId = E.OrganizationDepartmentId,
			EJD.DateOfJoining = E.DateOfJoining,
			EJD.UpdatedUserId = E.UpdatedUserId,
			EJD.UpdatedDateTime = E.UpdatedDateTime,
			EJD.EmployeeTypeId = E.EmployeeTypeId,
			EJD.DateOfleaving = E.DateOfleaving,
			EJD.ReasonOfleaving = E.ReasonOfleaving,
			EJD.EmployeeGroupId = E.EmployeeGroupId,
			EJD.EmployeeGradeId = E.EmployeeGradeId,
			EJD.JobRemark = E.JobRemark,
			EJD.EmployeeManagerId = E.EmployeeManagerId,
			EJD.ProbationDays = E.ProbationDays,
			EJD.ReferenceRemark = E.ReferenceRemark,
			EJD.EmployeeBusinessHeadId = E.EmployeeBusinessHeadId,
			EJD.Subjects = E.Subjects,
			EJD.OrgGroupDepartmentId  = E.OrgGroupDepartmentId
		FROM sHrm.tBatchEmployeeJobDetail EJD
		INNER JOIN sHrm.tEmployeeJobDetail E ON E.EmployeeId = EJD.EmployeeId
		WHERE E.EmployeeId = @rEmployeeId
	 END
	 ELSE
	 BEGIN
		INSERT INTO sHrm.tBatchEmployeeJobDetail
		(
			OrgId,EmployeeId,BatchId,EmployeeDesignationId,OrganizationDepartmentId,DateOfJoining,UpdatedUserId,
			UpdatedDateTime,EmployeeTypeId,DateOfleaving,ReasonOfleaving,EmployeeGroupId,EmployeeGradeId,JobRemark,
			EmployeeManagerId,ProbationDays,ReferenceRemark,EmployeeBusinessHeadId,Subjects,OrgGroupDepartmentId
		)
		SELECT OrgId,EmployeeId,@rBatchId,EmployeeDesignationId,OrganizationDepartmentId,DateOfJoining,UpdatedUserId,
			   UpdatedDateTime,EmployeeTypeId,DateOfleaving,ReasonOfleaving,EmployeeGroupId,EmployeeGradeId,JobRemark,
			   EmployeeManagerId,ProbationDays,ReferenceRemark,EmployeeBusinessHeadId,Subjects,OrgGroupDepartmentId
		FROM   sHrm.tEmployeeJobDetail WHERE EmployeeId = @rEmployeeId
	 END
	 --Ends
	 Print 5
	 -- Employee Personal Detail
	 IF EXISTS(SELECT 1 FROM sHrm.tBatchEmployeePersonalDetail WHERE EmployeeId = @rEmployeeId AND BatchId = @rBatchId)
	 BEGIN
		UPDATE EPD
		SET EPD.OrgId = E.OrgId,
			EPD.UIDNumber  = E.UIDNumber,
			EPD.DateOfBirth = E.DateOfBirth,
			EPD.GenderId = E.GenderId,
			EPD.ReligionId = E.ReligionId,
			EPD.MaritalStatusId = E.MaritalStatusId,
			EPD.IdentificationMark1 = E.IdentificationMark1,
			EPD.BloodGroupId = E.BloodGroupId,
			EPD.Qualification = E.Qualification,
			EPD.UpdatedUserId = E.UpdatedUserId,
			EPD.UpdatedDateTime = E.UpdatedDateTime,
			EPD.FamilyCast = E.FamilyCast,
			EPD.CastCategoryId = E.CastCategoryId,
			EPD.AdhaarNumber = E.AdhaarNumber
		FROM sHrm.tBatchEmployeePersonalDetail EPD
		INNER JOIN sHrm.tEmployeePersonalDetail E ON E.EmployeeId = EPD.EmployeeId
		WHERE E.EmployeeId = @rEmployeeId
	 END
	 ELSE
	 BEGIN
		INSERT INTO sHrm.tBatchEmployeePersonalDetail
		(
			OrgId,EmployeeId,BatchId,UIDNumber,DateOfBirth,GenderId,ReligionId,MaritalStatusId,IdentificationMark1,
			BloodGroupId,Qualification,UpdatedUserId,UpdatedDateTime,FamilyCast,CastCategoryId,AdhaarNumber
		)
		SELECT OrgId,EmployeeId,@rBatchId,UIDNumber,DateOfBirth,GenderId,ReligionId,MaritalStatusId,IdentificationMark1,
			   BloodGroupId,Qualification,UpdatedUserId,UpdatedDateTime,FamilyCast,CastCategoryId,AdhaarNumber
		FROM   sHrm.tEmployeePersonalDetail WHERE EmployeeId = @rEmployeeId
	 END
	 --Ends
	 Print 6
	  -- Employee Statutory And Other
	 IF EXISTS(SELECT 1 FROM sHrm.tBatchEmployeeStatutoryAndOther WHERE EmployeeId = @rEmployeeId AND BatchId = @rBatchId)
	 BEGIN
		UPDATE ESD
		SET ESD.EPFNumber = E.EPFNumber,
            ESD.IsVPFDeduction = E.IsVPFDeduction,
            ESD.VPFContributionId = E.VPFContributionId,
            ESD.VPFContributionEffectiveFrom = E.VPFContributionEffectiveFrom,
            ESD.VPFPercentage = E.VPFPercentage,
            ESD.VPFAmount = E.VPFAmount,
            ESD.ESINumber = E.ESINumber,
            ESD.BankName = E.BankName,
            ESD.Branch = E.Branch,
            ESD.AccountNumber = E.AccountNumber,
            ESD.IFSCNumber = E.IFSCNumber,
            ESD.PanNumber = E.PanNumber,
            ESD.IncomeTaxStatusId = E.IncomeTaxStatusId,
            ESD.UpdatedUserId = E.UpdatedUserId,
            ESD.UpdatedDateTime = E.UpdatedDateTime,
            ESD.IncrementDate = E.IncrementDate,
            ESD.BasicPay = E.BasicPay,
            ESD.PayrollId = E.PayrollId,
            ESD.PayrollGroupId = E.PayrollGroupId,
            ESD.Payscale = E.Payscale,
            ESD.EPFJoinDate = E.EPFJoinDate,
            ESD.UAN = E.UAN,
            ESD.RetirementDate = E.RetirementDate
		FROM sHrm.tBatchEmployeeStatutoryAndOther ESD
		INNER JOIN sHrm.tEmployeeStatutoryAndOther E ON E.EmployeeId = ESD.EmployeeId
		WHERE E.EmployeeId = @rEmployeeId
	 END
	 ELSE
	 BEGIN
		INSERT INTO sHrm.tBatchEmployeeStatutoryAndOther
		(
			EmployeeId,BatchId,EPFNumber,IsVPFDeduction,VPFContributionId,VPFContributionEffectiveFrom,VPFPercentage,
            VPFAmount,ESINumber,BankName,Branch,AccountNumber,IFSCNumber,PanNumber,IncomeTaxStatusId,
            UpdatedUserId,UpdatedDateTime,IncrementDate,BasicPay,PayrollId,PayrollGroupId,Payscale,
            EPFJoinDate,UAN,RetirementDate
		)
		SELECT EmployeeId,@rBatchId,EPFNumber,IsVPFDeduction,VPFContributionId,VPFContributionEffectiveFrom,VPFPercentage,
               VPFAmount,ESINumber,BankName,Branch,AccountNumber,IFSCNumber,PanNumber,IncomeTaxStatusId,
               UpdatedUserId,UpdatedDateTime,IncrementDate,BasicPay,PayrollId,PayrollGroupId,Payscale,
               EPFJoinDate,UAN,RetirementDate
		FROM   sHrm.tEmployeeStatutoryAndOther WHERE EmployeeId = @rEmployeeId
	 END
	 --Ends
	 Print 7
	 SELECT 1 AS Result
	 COMMIT TRANSACTION
		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeHolidaysCountGet]
	 
	@rForYear int,
	@rForMonth int,
	@rEmployeeId  bigint,	 
	@rEmployeeGradeId  int=0,	
	--@rDepartmentId int=0, 
	@rBatchId int,
	@rOrgId nvarchar(max) = ''  
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)

	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	
	
	
	SELECT
			EM.Id AS EmployeeId,
		EM.Code,
		EM.FirstName +' '+ EM.LastName AS Name,
		EGM.Title AS EmployeeGradeTitle,


		CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
			ELSE ISNULL(EWD.TotalDays,@lMonthDay)

		END AS TotalDays,

		--ISNULL(EWD.TotalDays,@lMonthDay) AS TotalDays,

--		ISNULL(EWD.WorkingDays,@lMonthDay) AS WorkingDay,
		(CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
			--ELSE ISNULL(EWD.WorkingDays,@lMonthDay)
			ELSE @lMonthDay
		END )- ([sHrm].[fEmployeeHolidayGet](EM.Id,0, @rForYear,@rForMonth,@rBatchId,@rOrgId))  AS WorkingDay,


		ISNULL(EWD.VacationDays,0) AS VacationDays,
		
		--[sHrm].[fEmployeeHolidayGet](EM.Id,0, @rForYear,@rForMonth,@rBatchId,@rOrgId)AS HoliDays,		-- Mantis Id : 0038655 Commented
		0 AS HoliDays,		-- Mantis Id : 0038655 Add static 0
		--AS HoliDays
		ISNULL(EWD.WeekOffs,0) AS WeekOffs
		
	FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId= EM.Id
		INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id =  EJD.EmployeeGradeId
		LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON EWD.EmployeeId=EM.Id 
		AND EWD.BatchId=@rBatchId 
		AND EWD.ForYear=@rForYear
		AND EWD.ForMonth =@rForMonth 
	WHERE
		EM.StatusId=7  AND ISNULL(EM.IsOtherUser,0) = 0 
		AND (EM.Id = @rEmployeeId OR @rEmployeeId=0)
		AND (EJD.EmployeeGradeId = @rEmployeeGradeId OR @rEmployeeGradeId=0)
		AND ((EJD.DateOfleaving >= @lFirstDate) OR ISNULL(EJD.DateOfleaving,'') = '')
		AND ((EJD.DateOfJoining <= @lLasteDate) OR ISNULL(EJD.DateOfJoining,'') = '')
		AND EM.OrgId=@rOrgId
		AND EM.IsOtherUser = 0
	Order By EM.Number	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeHouseAdd]
	
	@rEmployeeHouseImpXml [nvarchar](max),
	@rEmployeeId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEmployeeHouseImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sHrm.tAssignHouse WHERE EmployeeId=@rEmployeeId
	
		 INSERT INTO sHrm.tAssignHouse
		(
			HouseId,
			EmployeeId
			)
		SELECT
			HouseId,
			EmployeeId
		FROM OPENXML (@loDoc, '/Table/EmployeeHouse', 1)
		WITH ( 
				HouseId int,
				EmployeeId bigint
			  ) 

		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeIcardOrgAdd]
	 
	@rIcardTemplateId int,
	@rOrgId int,
	@rICardBackground varbinary(max)=null,
	@rICardBackBackGround varbinary(max)=null,
	@rICardOrgTitle nvarchar(200)='',
	@rICardAddress1 nvarchar(200)='',
	@rICardAddress2 nvarchar(200)='',
	@rICardAddress3 nvarchar(200)='',
	@rLabelColor nvarchar(20)='',
	@rDetailColor nvarchar(20)='',
	@rHeaderColor nvarchar(20)='',
	@rIsShowBarcode bit=0,
	@rIsShowBirthdate bit=0,
	@rIsShowBloodGroup bit=0,
	@rIsPrincipalSignature bit=0
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

			IF (@rIcardTemplateId=0)
			BEGIN
					DELETE FROM sHrm.tEmployeeICardOrg WHERE OrgId=@rOrgId
					SELECT -103 AS Result
					RETURN
			END 
			
	BEGIN TRY
		BEGIN TRANSACTION
		
		
	IF NOT EXISTS (SELECT 1 FROM sHrm.tEmployeeICardOrg WHERE OrgId=@rOrgId)	
	
	
	   BEGIN
			INSERT INTO sHrm.tEmployeeICardOrg
			(
				EmployeeIcardTemplateId,
				OrgId,
				ICardBackground,
				ICardBackBackGround
			)
			VALUES
			(
				@rIcardTemplateId,
				@rOrgId,
				@rICardBackground,
				NULL
			)
			SELECT 1 AS Result	 
		END	 
	ELSE
		BEGIN
			UPDATE sHrm.tEmployeeICardOrg
			SET
				EmployeeIcardTemplateId=@rIcardTemplateId,
				ICardBackground=@rICardBackground,
				ICardBackBackGround=@rICardBackBackGround,
				IcardOrgTitle=@rICardOrgTitle,
				IcardAddress1=@rICardAddress1,
				IcardAddress2=@rICardAddress2,
				IcardAddress3=@rICardAddress3,
				LabelColor=@rLabelColor,
				DetailColor=@rDetailColor,
				HeaderColor=@rHeaderColor,
				IsShowBarcode = @rIsShowBarCode,
				IsShowBirthdate=@rIsShowBirthdate,
	            IsShowBloodGroup=@rIsShowBloodGroup ,
	            IsPrincipalSignature =@rIsPrincipalSignature 

				
			WHERE OrgId=@rOrgId
			SELECT 11 AS Result
		END  
		COMMIT TRANSACTION
			END TRY
		BEGIN CATCH 
			ROLLBACK TRANSACTION
			SELECT -1 AS Result
		END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeImagesAdd]
	 
	@rEmployeeId bigint,
	@rEmployeePhoto varbinary(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
	
	IF NOT EXISTS(SELECT EmployeeId FROM sHrm.tEmployeeImages WHERE EmployeeId=@rEmployeeId)
	BEGIN 
	INSERT INTO sHrm.tEmployeeImages
		(
			EmployeeId,
			EmployeePhoto
		)
	VALUES
		(
			@rEmployeeId,
			@rEmployeePhoto
		)         
	END	 
	 ELSE
	 BEGIN
	    UPDATE sHrm.tEmployeeImages
	    SET
			EmployeePhoto=@rEmployeePhoto
	      WHERE 
			EmployeeId=@rEmployeeId
	 END  
		SELECT 1 AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeImagesGet]
	 
	 @rEmployeeId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
  SELECT 
		ISNULL(EmployeePhoto,0) AS EmployeePhoto,
		ISNULL(EmployeeSign,0) AS EmployeeSign
  FROM 
        sHrm.tEmployeeImages
  WHERE 
		(EmployeeId=@rEmployeeId)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeJobDetailAdd]
    
    @rOrgId smallint,
	@rEmployeeId [bigint], 
	@rEmployeeDesignationId [int],
	@rOrganizationDepartmentId [int],
	@rDateOfJoining Date,
	@rCreatedUserId [bigint],
	@rEmployeeTypeId int,
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rJobRemark nvarchar(200) = '',
	@rEmployeeManagerId bigint=0,
	@rProbationDays smallint = NULL,
	@rSubjects nvarchar(200) = NULL,
	@rOrgGroupDepartmentId int=0,
	@rProbationUptoDate datetime,
	@rAhdocUptoDate datetime,
	@rPermanentDate datetime,
	@rDateOfResignation datetime,
	@rDateOfLeaving datetime =null
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION
	
			IF (@rEmployeeDesignationId <= 0)
			SET @rEmployeeDesignationId = NULL		
			
			IF(@rEmployeeTypeId <= 0)
			SET @rEmployeeTypeId = NULL			
			
			IF(@rEmployeeGradeId <= 0) 
			SET @rEmployeeGradeId = NULL
			
			IF(@rEmployeeGroupId <= 0)
			SET @rEmployeeGroupId = NULL
			
			IF(@rEmployeeManagerId <= 0)
			SET @rEmployeeManagerId = NULL
			
	INSERT INTO sHrm.tEmployeeJobDetail
		(
			EmployeeId,	
			EmployeeDesignationId,
			OrganizationDepartmentId,
			DateOfJoining,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			EmployeeTypeId,
			EmployeeGradeId,
			EmployeeGroupId,
			JobRemark,
			EmployeeManagerId,
			ProbationDays,
			Subjects,
			OrgGroupDepartmentId,
			ProbationUptoDate,
			AhdocUptoDate,
			PermanentDate,
			DateOfResignation,
			DateOfLeaving
		)
	VALUES
		(
			@rEmployeeId, 			 
			@rEmployeeDesignationId,
			@rOrganizationDepartmentId,
			@rDateOfJoining,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rEmployeeTypeId,
			@rEmployeeGradeId,
			@rEmployeeGroupId,
			@rJobRemark,
			@rEmployeeManagerId,
			@rProbationDays,
			@rSubjects,
			@rOrgGroupDepartmentId,
			@rProbationUptoDate,
			@rAhdocUptoDate,
			@rPermanentDate,
			@rDateOfResignation ,
			@rDateOfLeaving
		)
	
	SELECT @rEmployeeId AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error Creating Job Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeJobDetailBatchWiseGet]
	
	@rOrgId smallint,
	@rEmployeeId bigint = 0,
	@rBatchId int= 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			JD.EmployeeId,			 
			ISNULL(JD.EmployeeDesignationId,0) AS EmployeeDesignationId,
			ISNULL(DM.Title,'') AS EmployeeDesignation,
			JD.OrganizationDepartmentId,
			ODM.Title AS OrganizationDepartment, 
			JD.DateOfJoining,
			JD.UpdatedUserId,
			JD.UpdatedDateTime,
			ISNULL(JD.EmployeeTypeId,0) AS EmployeeTypeId,
			ISNULL(JD.DateOfleaving,'01-01-0001') AS DateOfLeaving,
			ISNULL(JD.ReasonOfleaving,'') AS ReasonOfLeaving,
			ISNULL(JD.JobRemark,'') AS JobRemark,
			ISNULL(JD.EmployeeGradeId,0) AS EmployeeGradeId,
			ISNULL(JD.EmployeeGroupId,0) AS EmployeeGroupId,
			ISNULL(JD.EmployeeManagerId,0) AS EmployeeManagerId,
			ISNULL(JD.ReferenceRemark,'') AS ReferenceRemark,
			ISNULL(JD.ProbationDays,'') AS ProbationDays,
			JD.OrgId,
			ISNULL(JD.Subjects,'') AS Subjects,
			ISNULL(JD.OrgGroupDepartmentId,0) AS OrgGroupDepartmentId,
			ISNULL(JD.EmployeeBusinessHeadId,0) AS BusinessHeadManagerId
	   FROM 
			sHrm.tBatchEmployeeJobDetail JD
	   INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = JD.OrganizationDepartmentId	
	   LEFT JOIN sHrm.tEmployeeDesignationMaster DM ON DM.Id  = JD.EmployeeDesignationId
	   WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		     AND JD.OrgId = @rOrgId
		     AND JD.BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeJobDetailGet]
	
	@rOrgId smallint,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			JD.EmployeeId,			 
			ISNULL(JD.EmployeeDesignationId,0) AS EmployeeDesignationId,
			ISNULL(DM.Title,'') AS EmployeeDesignation,
			JD.OrganizationDepartmentId,
			ODM.Title AS OrganizationDepartment, 
			JD.DateOfJoining,
			JD.UpdatedUserId,
			JD.UpdatedDateTime,
			ISNULL(JD.EmployeeTypeId,0) AS EmployeeTypeId,
			ISNULL(JD.DateOfleaving,'01-01-0001') AS DateOfLeaving,
			ISNULL(JD.ReasonOfleaving,'') AS ReasonOfLeaving,
			ISNULL(JD.JobRemark,'') AS JobRemark,
			ISNULL(JD.EmployeeGradeId,0) AS EmployeeGradeId,
			ISNULL(JD.EmployeeGroupId,0) AS EmployeeGroupId,
			ISNULL(JD.EmployeeManagerId,0) AS EmployeeManagerId,
			ISNULL(JD.ReferenceRemark,'') AS ReferenceRemark,
			ISNULL(JD.ProbationDays,'') AS ProbationDays,
			JD.OrgId,
			ISNULL(JD.Subjects,'') AS Subjects,
			ISNULL(JD.OrgGroupDepartmentId,0) AS OrgGroupDepartmentId,
			ISNULL(JD.EmployeeBusinessHeadId,0) AS BusinessHeadManagerId,
			JD.ProbationUptoDate,
			JD.AhdocUptoDate,
			JD.PermanentDate,
			JD.DateOfResignation
	   FROM 
			sHrm.tEmployeeJobDetail JD
	   INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = JD.OrganizationDepartmentId	
	   LEFT JOIN sHrm.tEmployeeDesignationMaster DM ON DM.Id  = JD.EmployeeDesignationId
	   WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND JD.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeJobDetailModify]
 
	@rEmployeeId [bigint], 
	@rEmployeeDesignationId [int],
	@rOrganizationDepartmentId [int],
	@rDateOfJoining Date,
	@rUpdatedUserId [bigint],
	@rEmployeeTypeId int,
	@rDateOfLeaving Date = null,
	@rReasonOfLeaving nvarchar(200) = null,
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rJobRemark nvarchar(200),
	@rEmployeeManagerId bigint,
	@rReferenceRemark nvarchar(200)='',
	@rProbationDays smallint=NULL,
	@rSubjects nvarchar(200) = NULL,
	@rOrgGroupDepartmentId int=0,
	@rBusinessHeadManagerId bigint,
	@rProbationUptoDate Date,
	@rAhdocUptoDate Date,
	@rPermanentDate Date,
	@rDateOfResignation Date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
			IF (@rEmployeeDesignationId <= 0)
			SET @rEmployeeDesignationId = NULL
			
	 UPDATE sHrm.tEmployeeJobDetail
		SET  
			EmployeeDesignationId = @rEmployeeDesignationId,			 
			OrganizationDepartmentId = @rOrganizationDepartmentId,
			DateOfJoining =	@rDateOfJoining,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			EmployeeTypeId = @rEmployeeTypeId,
			DateOfleaving = @rDateOfLeaving,
			ReasonOfleaving = @rReasonOfLeaving,
			EmployeeGradeId = @rEmployeeGradeId,
			EmployeeGroupId = @rEmployeeGroupId,
			JobRemark=@rJobRemark,
			EmployeeManagerId=@rEmployeeManagerId,
			ReferenceRemark = @rReferenceRemark,
			ProbationDays = @rProbationDays,
			Subjects = @rSubjects,
			OrgGroupDepartmentId =@rOrgGroupDepartmentId,
			EmployeeBusinessHeadId=@rBusinessHeadManagerId,
			ProbationUptoDate = @rProbationUptoDate,
			AhdocUptoDate = @rAhdocUptoDate,
			PermanentDate = @rPermanentDate,
			DateOfResignation = @rDateOfResignation
	  WHERE 
			EmployeeId = @rEmployeeId
	
	  SELECT 1 AS JobDetailId From sHrm.tEmployeeJobDetail where EmployeeId = @rEmployeeId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeJobTitleMasterAdd]
	@rOrgId smallint,
	@rCode [nvarchar](100),
	@rTitle [nvarchar](20),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeJobTitleMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sHrm.tEmployeeJobTitleMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
		
		SELECT @lNextNumber AS Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeJobTitleMasterGet]
	
	@rOrgId smallint,
	@rId [int] = 0,
	@rCode [nvarchar](100) = '',
	@rTitle [nvarchar](20) = '',
	@rEmployeeGradeId [int] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	
	 SELECT 
			JTM.Id,
			JTM.Code,
			JTM.Title,
			JTM.IsObsolete,
			JTM.CreatedUserId,
			JTM.CreatedDateTime,
			JTM.UpdatedUserId,
			JTM.UpdatedDateTime
	   FROM 
			sHrm.tEmployeeJobTitleMaster JTM
	   WHERE 
			((JTM.Id = @rId) OR (@rId = 0))
	   AND ((JTM.Title LIKE @rTitle) OR (@rTitle = ''))
	   AND ((JTM.Code LIKE  @rCode) OR (@rCode = ''))
	   AND JTM.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeJobTitleMasterModify]
	@rId [int],
	@rCode [nvarchar](100),
	@rTitle [nvarchar](20),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sHrm.tEmployeeJobTitleMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  
	  SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeLateStatusAdd]
           
        @rEmployeeId bigint,
        @rLateDate date,  
        @rLateStatus nvarchar(10)='',
        @rStatusId smallint=0,
        @rEarlyLeaveRemark nvarchar(200)='',
        @rCreatedUserId bigint,
        @rIsUpdate bit = 0,
        @rEarlyHrs decimal(10,2)=0,
        @FieldHrs decimal(10,2)=0
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	BEGIN TRANSACTION
	IF(@rIsUpdate = 0)	
	BEGIN
		  INSERT INTO sBiometric.tEmployeeLateStatus
          (
		   EmployeeId,
		   LateDate,
		   LateStatus,
		   StatusId,
		   EarlyLeaveRemark,
		   CreatedUserId,
		   CreatedDateTime,
		   UpdatedUserId,
		   UpdatedDateTime,
		   FieldHrs
          )
          VALUES
           (
            @rEmployeeId,
            @rLateDate,
            @rLateStatus,
            @rStatusId,
            @rEarlyLeaveRemark,
            @rCreatedUserId,
            sCommon.fGetDate(),
            @rCreatedUserId,
            sCommon.fGetDate(),
            @FieldHrs
           )
	
	SELECT 1 AS Result	   
	
	END
	ELSE
	BEGIN
		UPDATE  sBiometric.tEmployeeLateStatus
	    SET
			StatusId = @rStatusId,
			EarlyHrs = @rEarlyHrs,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			FieldHrs= CASE WHEN @rStatusId=549 THEN @FieldHrs ELSE FieldHrs END--@FieldHrs
	     WHERE EmployeeId = @rEmployeeId AND LateDate = @rLateDate
		 
		 SELECT 1 AS Result	   
	END   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeLeaveBulkXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rId bigint =0,
        @rEmployeeId bigint=0,
        @rReportDate date='',
		--@rLeaveDate Date,
        --@rLeavePeriodId tinyint=0,
        --@rLeaveTypeId int=0,
        --@rLeaveReson nvarchar(200)='',
        @rNoOfLeave decimal=1,
        @rBatchId int,
        @rOrgId int,
        @rCreatedUserId bigint,
        @rStatusId int =549,
        @rFromTime datetime ='',
		@rToTime datetime ='',
		@rDepartmentId int
    
    
		
AS
SET NOCOUNT ON

BEGIN
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
DECLARE @lCount INT

    CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		EmployeeId bigint,
		FromDate date,
		ToDate date,
		LeavePeriodId int,
		LeaveTypeId int,
		LeaveReason nvarchar(100),
		LeaveDate Date,
		NoOfLeave decimal(5,2)
	)
	INSERT INTO #tTable
	(
            [EmployeeId]
           ,[FromDate]
           ,[ToDate]
           ,[LeavePeriodId]
           ,[LeaveTypeId]
           ,[LeaveReason]
		   ,NoOfLeave
           )          
           SELECT	
            At.EmployeeId 
           ,At.FromDate 
           ,At.ToDate 
           ,At.LeavePeriodId 
           ,At.LeaveTypeId 
           ,At.LeaveReason 
		   ,At.NoOfLeave
			FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				EmployeeId bigint,
				FromDate date,
				ToDate date,
				LeavePeriodId int,
				LeaveTypeId int,
				LeaveReason nvarchar(100),
				LeaveDate Date,
				NoOfLeave decimal(5,2)
		   ) AS At	


	DECLARE @lItemValue nvarchar(20) = '', @lOrgGroupId int
	
	SELECT @lOrgGroupId = OrgGroupId from [sSetup].[tOrganizationMaster] WHERE Id = @rOrgId

	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 545


	DECLARE @lNextNumber bigint

	SELECT @lCount =  COUNT(Id) FROM #tTable
	WHILE @lCount > 0 
	BEGIN

	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeave', 0, 1, 1,@outNextNumber = @lNextNumber output	
	    
		  INSERT INTO [sHrm].[tLeave]
           (
            [Id]
           ,[EmployeeId]
           ,[ReportDate]
           ,[FromDate]
           ,[ToDate]
           ,[LeavePeriodId]
           ,[LeaveTypeId]
           ,[LeaveReason]
           ,NoOfLeave
           ,BatchId
           ,[OrgId]           
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[StatusId]
           ,[FromTime]
           ,[ToTime]
           )          
           SELECT		
			 @lNextNumber
           ,temp.EmployeeId 
           ,sCommon.fGetDate()
           ,temp.FromDate 
           ,temp.ToDate 
           ,temp.LeavePeriodId 
           ,temp.LeaveTypeId 
           ,temp.LeaveReason 
           ,NoOfLeave
           ,@rBatchId
           ,@rOrgId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rStatusId      
           ,@rFromTime
           ,@rToTime 
			FROM #tTable temp Where temp.Id= @lCount 
			
			--mantisid - 0031565

			DECLARE @lLeaveTypeId int, @lIsLWP bit
			SELECT @lLeaveTypeId = LeaveTypeId FROM #tTable Where Id= @lCount 

			SELECT @lIsLWP = IsLWP from sHrm.tLeaveTypeMaster Where Id = @lLeaveTypeId AND OrgId = @rOrgId

			IF(@lItemValue = 'True' AND @lIsLWP = 'true')
			BEGIN
				UPDATE sHrm.tLeave SET StatusId = 550 WHERE Id = @lNextNumber
			END

		SET @lCount = @lCount - 1
		END	   		
		
        SELECT 1 AS Result
	 --END	
    
           
            --ELSE
            --SELECT -1 AS Result
            --END	
	
		
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeManagerListGet]
	@rOrgId smallint=0,
	@rEmployeeId bigint =0
AS
SET NOCOUNT ON
BEGIN 


CREATE TABLE #TempEmployeeId
	(
	EmployeeId bigint,
    EmployeeManagerId bigint
	)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeId,
			 EJD.EmployeeManagerId			 
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId  
			 WHERE  ((EmployeeID = @rEmployeeId) OR (@rEmployeeId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
			-- AND EM.FirstName like '%'+@rEmpName+'%'
			 	
			 UNION ALL

			 SELECT
			 E.EmployeeId,
			 E.EmployeeManagerId
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeManagerId = E.EmployeeId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId  
			 AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
			)
		INSERT INTO #TempEmployeeId(EmployeeId,EmployeeManagerId) SELECT E.* FROM EmployeeCTE E
		
   END
 
		SELECT 
		EM.Id AS EmployeeId ,EM.FirstName +' ' +EM.LastName  AS EmployeeName,
		ISNULL(EM1.Id,'') AS EmployeeManagerId ,ISNULL(EM1.FirstName +' ' +EM1.LastName,'')  AS EmployeeManagerName
	FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		INNER JOIN #TempEmployeeId TE ON TE.EmployeeId = EM.Id AND ISNULL(EM.IsOtherUser,0) = 0 
		LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = TE.EmployeeManagerId AND ISNULL(EM1.IsOtherUser,0) = 0 

		DROP Table #TempEmployeeId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterAdd]
    
    @rOrgId smallint,
	@rCode [nvarchar](100),
	@rFirstName [nvarchar](100),
	@rMiddleName [nvarchar](100),
	@rLastName [nvarchar](100),
    @rEmployeeTypeId int,
	@rDepartmentId int,
	@rDateOfBirth Date,
	@rDateOfJoining Date,
	@rGenderId int,
	@rReligionId int=null,--
	@rStatusId [int],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@OutEmployeeId bigint = null output,--
	@rEmployeeDesignationId INT,
	@rBloodGroupId TINYINT = 0,--
	@rQualification nvarchar(150) = '',
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rShortName nvarchar(50),
	@rEmployeeManagerId bigint=0,
	@rFamilyCast nvarchar(150) = '',
	@rCastCategoryId int  =null,
	@rNumber bigint=0,
	@rProbationUptoDate date = null,
	@rAhdocUptoDate date = null,
	@rPermanentDate date= null,
	@rIsOtherUser smallint = 0,
	@rDateOfResignation date = null,
	@rDateOfLeaving Date = null,
	@rTribeId int = null,
	@rAdhaarNumber nvarchar(40)='',
	@rMaritalStatusId TINYINT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	
	DECLARE @loEmpNumber Nvarchar(100)
	DECLARE @lEmpPrefixResult Int
    

	IF EXISTS(SELECT Id FROM sHrm.tEmployeeMaster WHERE Code=@rCode AND OrgId=@rOrgId AND ISNULL(IsOtherUser,0) = 0 )
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
 

		
    
 --   IF((@rCode = Null) OR (@rCode = ''))
 --   BEGIN
	--	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 94,@rStoreLocationId = 0, @rNextNumber = @loEmpNumber OUTPUT	
	--	SET @loEmpNumber = ISNULL(@loEmpNumber, '-300')
	--	SET @lEmpPrefixResult = '-300'	
	--END
	--ELSE
	--  BEGIN
 --       SET	@loEmpNumber = @rCode
 --     END
            		
	--IF (@loEmpNumber <> '-300')
	--BEGIN
	
	--BEGIN TRY
 --	BEGIN TRANSACTION
	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				
		INSERT INTO sHrm.tEmployeeMaster
			(
				Id,
				Code,
				FirstName,
				MiddleName,
				LastName,
				ShortName,
				StatusId,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				OrgId,
				Number,
				IsOtherUser,
				EUId			-- MantisId : 	0029269
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rFirstName,
				@rMiddleName,
				@rLastName,
				@rShortName,
				@rStatusId,
				@rIsObsolete,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgId,
				@rNumber,
				@rIsOtherUser,
				@lNextNumber		-- MantisId : 	0029269
			)
	    
		 
				
		SELECT Id AS RESULT, @loEmpNumber AS EmpCode FROM sHrm.tEmployeeMaster WHERE  Id = @lNextNumber
		SET @OutEmployeeId = @lNextNumber -- added for import employee
		
		BEGIN 
        Execute sHrm.pEmployeeJobDetailAdd  
	       @rOrgId,@lNextNumber,@rEmployeeDesignationId,@rDepartmentId,@rDateOfJoining,@rCreatedUserId,
	       @rEmployeeTypeId,@rEmployeeGradeId,@rEmployeeGroupId,'',@rEmployeeManagerId,NULL,NULL,0,@rProbationUptoDate,@rAhdocUptoDate,@rPermanentDate,@rDateOfResignation,@rDateOfLeaving
	          
	     Execute sHrm.pEmployeePersonalDetailAdd @rOrgId,@lNextNumber,'',@rDateOfBirth,@rGenderId,@rReligionId,
	     @rMaritalStatusId,'',@rBloodGroupId,@rQualification,@rCreatedUserId,@rFamilyCast,@rCastCategoryId,@rTribeId,@rAdhaarNumber

	      
		END	

		--COMMIT TRANSACTION
	 
		--END TRY
		
		--BEGIN CATCH
		--ROLLBACK TRANSACTION 
 
		--	RAISERROR ('Error saving employee Master', -- Message text.
  --             16, -- Severity.
  --             1 -- State.
  --             );           
		 
 
		--END CATCH			
 
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterBatchWiseGet]
	 
	 @rEmployeeId bigint = 0,
	 @rBatchId int = 0,
	 @rOrgId smallint = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	 SELECT 
				EM.Id,
				EM.Id AS EmployeeId,
				EM.Code,
				EM.FirstName,
				EM.MiddleName,
				EM.LastName,
				EM.ShortName AS EmpShortName,
				EM.StatusId,
				EM.IsObsolete,
				EM.FirstName+' '+EM.LastName As EmployeeFullName,
				EJD.OrganizationDepartmentId AS DepartmentId,
				EJD.DateOfJoining,
				EJD.EmployeeTypeId,
				EPD.DateOfBirth,
				EPD.GenderId,
				EJD.EmployeeDesignationId,
				ISNULL(DM.Title,'') AS EmployeeDesignation,
				EJD.EmployeeGradeId,
				EJD.EmployeeGroupId,
				DEP.title AS EmployeeDepartment
	
   FROM 
				sHrm.tBatchEmployeeMaster EM 
			    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId 
			    LEFT JOIN sHrm.tEmployeeDesignationMaster DM	ON DM.Id  = EJD.EmployeeDesignationId
			    LEFT JOIN sSetup.tDepartmentMaster AS DEP ON DEP.id=EJD.OrganizationDepartmentId
	WHERE 
			    EM.OrgId = @rOrgId
			    AND ((EM.Id = @rEmployeeId) OR (@rEmployeeId = 0))
			    AND EM.BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterGet]
	 
	 @rOrgId smallint,
	 @rId [bigint] = 0,
	 @rCode nvarchar(50) = ''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 --  IF @rCode <> ''
		--BEGIN			
		--SET @rCode = sCommon.fSearchStringGet(@rCode)
		--END
	 SELECT 
				EM.Id,
				EM.Id AS EmployeeId,
				EM.Code,
				EM.FirstName,
				EM.MiddleName,
				EM.LastName,
				EM.ShortName AS EmpShortName,
				EM.StatusId,
				EM.IsObsolete,
				EM.FirstName+' '+EM.LastName As EmployeeFullName,
				EJD.OrganizationDepartmentId AS DepartmentId,
				EJD.DateOfJoining,
				EJD.EmployeeTypeId,
				EPD.DateOfBirth,
				EPD.GenderId,
				EJD.EmployeeDesignationId,
				ISNULL(DM.Title,'') AS EmployeeDesignation,
				EJD.EmployeeGradeId,
				EJD.EmployeeGroupId,
				DEP.title AS EmployeeDepartment,
				EM.Number As Number,
				EJD.ProbationUptoDate,
				EJD.AhdocUptoDate,
				EJD.PermanentDate,
				EJD.DateOfResignation,
				CAST(ISNULL(EJD.DateOfleaving,'01-01-0001') as nvarchar(50)) As DateOfleaving,
				CAST(EM.IsOtherUser as int) As IsOtherUser,
				EM.EUId
	
   FROM 
				sHrm.tEmployeeMaster EM 
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
		   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId 
		   LEFT JOIN sHrm.tEmployeeDesignationMaster DM	ON DM.Id  = EJD.EmployeeDesignationId
		   LEFT JOIN [sSetup].[tDepartmentMaster] DEP ON DEP.id=EJD.OrganizationDepartmentId
	WHERE 
			    EM.OrgId = @rOrgId
		   AND ((EM.Id = @rId) OR (@rId = 0))
		   AND ((EM.Code= @rCode) OR (@rCode = ''))
		   --AND ISNULL(EM.IsOtherUser,0) = 0 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterListingBatchWiseGet]
(
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rName [nvarchar](50) = '',	
	@rSurName[nvarchar](50) = '',
	@rEmployeeTypeId int = 0,
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rOrgGroupId int = 0,
	@rUserId bigint=0,
	@rFilterId smallint = 0,
	@rIsOtherUser smallint = 0,
	@rBatchId int = 0
 )
AS
SET NOCOUNT ON

BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rSurName = sCommon.fSearchStringGet(@rSurName)
 	
		IF @rFilterId = 0
		BEGIN
		SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				OM.DisplayTitle,
				OM.Id AS OrgId
		FROM 
				sHrm.tEmployeeMaster EM			
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
			INNER JOIN [sHrm].[tEmployeeBatch] EB ON EB.EmployeeId=EM.Id
			--AND U.UserId = EM.Id
		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND	((EB.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((EM.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))
			AND ((ISNULL(EM.IsOtherUser,0) = @rIsOtherUser))
			--AND ISNULL(EM.IsOtherUser,0) = 0 
			 
		Order By EM.Number
		
		END
		ELSE
		BEGIN
		SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				OM.DisplayTitle,
				OM.Id AS OrgId
		FROM 
				sHrm.tEmployeeMaster EM				
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
			INNER JOIN [sHrm].[tEmployeeBatch] EB ON EB.EmployeeId=EM.Id
			--AND U.UserId = EM.Id
		WHERE 
			((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND	((EB.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((EM.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))
			AND (EM.ID NOT IN (SELECT ID FROM sHrm.tBatchEmployeeMaster))
			AND ((ISNULL(EM.IsOtherUser,0) = @rIsOtherUser))
			--AND ISNULL(EM.IsOtherUser,0) = 0 
		Order By EM.Number
		END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterListingGet]
(
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rName [nvarchar](50) = '',	
	@rSurName[nvarchar](50) = '',
	@rEmployeeTypeId int = 0,
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rOrgGroupId int = 0,
	@rUserId bigint=0,
	@rFilterId smallint = 0,
	@rIsOtherUser smallint = 0
 )
AS
SET NOCOUNT ON

BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rSurName = sCommon.fSearchStringGet(@rSurName)
 	
		IF @rFilterId = 0
		BEGIN
		SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Name,
				--ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				OM.DisplayTitle,
				OM.Id AS OrgId
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
			--AND U.UserId = EM.Id
		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND ((EM.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))
			AND ((ISNULL(EM.IsOtherUser,0) = @rIsOtherUser))
			--AND ISNULL(EM.IsOtherUser,0) = 0 
			 
		Order By EM.Number
		
		END
		ELSE
		BEGIN
		SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				OM.DisplayTitle,
				OM.Id AS OrgId
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
			--AND U.UserId = EM.Id
		WHERE 
			((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND ((EM.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))
			AND (EM.ID NOT IN (SELECT ID FROM sHrm.tBatchEmployeeMaster))
			AND ((ISNULL(EM.IsOtherUser,0) = @rIsOtherUser))
			--AND ISNULL(EM.IsOtherUser,0) = 0 
		Order By EM.Number
		END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterListingImportAdd] --1101,0
(
	@rOrgId int=0,	
	@rEmployeeId bigint,	
	@rBatchId int,	
	@rDepartmentId int = 0,
	@rOrgGroupId int = 0,
	@rUserId bigint=0,
	@rStatusId int = 0,
	@rCode nvarchar(20) = '',
	@rIsObsolete bit = 0

 )
AS
SET NOCOUNT ON

BEGIN
		
	IF(@rEmployeeId=0)
	BEGIN
		DELETE FROM sHrm.tEmployeeBatch WHERE EmployeeId IN (
		SELECT EM.Id FROM 
				sHrm.tEmployeeMaster EM
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
				INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
				--AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
				--AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))	
				)
		INSERT INTO sHrm.tEmployeeBatch(EmployeeId,BatchId) 
			SELECT EM.Id,@rBatchId FROM 
				sHrm.tEmployeeMaster EM
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
				INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
				--AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
				--AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))	
	END
	ELSE IF EXISTS(SELECT 1 FROM sHrm.tEmployeeBatch WHERE EmployeeId=@rEmployeeId)
	BEGIN
		DELETE FROM sHrm.tEmployeeBatch WHERE EmployeeId = @rEmployeeId
		INSERT INTO sHrm.tEmployeeBatch(EmployeeId,BatchId) VALUES (@rEmployeeId,@rBatchId)
	END
	ELSE
	BEGIN
		INSERT INTO sHrm.tEmployeeBatch(EmployeeId,BatchId) VALUES (@rEmployeeId,@rBatchId)
	END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterListingImportGet] --1101,0
(
	@rOrgId smallint,	
	@rCode [nvarchar](20) = '',
	@rName [nvarchar](50) = '',	
	@rSurName[nvarchar](50) = '',
	@rEmployeeTypeId int = 0,
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rOrgGroupId int = 0,
	@rUserId bigint=0,
	@rFilterId smallint = 0,
	@rIsOtherUser smallint = 0

 )
AS
SET NOCOUNT ON

BEGIN
		
	SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				--EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				--EJD.EmployeeGroupId,
				--OM.DisplayTitle,
				OM.Id AS OrgId
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			--AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			--AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))
			 
		--ORDER BY EM.Number
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterListWithPhotoBatchWiseGet]

	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rName [nvarchar](50) = '',	
	@rSurName[nvarchar](50) = '',
	@rEmployeeTypeId int = 0,
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rUserId bigint=0,
	@rIsOtherUser smallint = 0,
	@rMultiCode nvarchar(max)='',
	@rIsEmployeePhoto bit=1,
	@rBatchId int = 0

AS
SET NOCOUNT ON

BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rSurName = sCommon.fSearchStringGet(@rSurName)
		--SELECT @rCode
		IF(@rIsEmployeePhoto =1)
			BEGIN
				SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
				OM.DisplayTitle,
				OM.Id As OrgId
		FROM 
				sHrm.tEmployeeMaster EM				
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
			INNER JOIN [sHrm].[tEmployeeBatch] EB ON EB.EmployeeId=EM.Id
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId= EM.Id

		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND	((EB.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((EM.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND U.UserId = @rUserId
			AND ((EM.IsOtherUser = @rIsOtherUser) OR (@rIsOtherUser = -1))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND (ISNULL(EM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,'.')) OR ISNULL(@rMultiCode,'')='')
			--Order By EM.Code	
			Order By EM.Number
			END
			ELSE
			BEGIN
				SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				ISNULL(EI.EmployeeSign, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
				OM.DisplayTitle,
				OM.Id As OrgId
		FROM 
				sHrm.tEmployeeMaster EM			
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
			INNER JOIN [sHrm].[tEmployeeBatch] EB ON EB.EmployeeId=EM.Id
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId= EM.Id
		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND	((EB.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((EM.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND U.UserId = @rUserId
			AND ((EM.IsOtherUser = @rIsOtherUser) OR (@rIsOtherUser = -1))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND (ISNULL(EM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,'.')) OR ISNULL(@rMultiCode,'')='')
			--Order By EM.Code	
			Order By EM.Number
			END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterListWithPhotoGet]

	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rName [nvarchar](50) = '',	
	@rSurName[nvarchar](50) = '',
	@rEmployeeTypeId int = 0,
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rUserId bigint=0,
	@rIsOtherUser smallint = 0,
	@rMultiCode nvarchar(max)='',
	@rIsEmployeePhoto bit=1

AS
SET NOCOUNT ON

BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rSurName = sCommon.fSearchStringGet(@rSurName)
		--SELECT @rCode
		IF(@rIsEmployeePhoto =1)
			BEGIN
				SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
				OM.DisplayTitle,
				OM.Id As OrgId
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId= EM.Id
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((EM.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND U.UserId = @rUserId
			AND ((EM.IsOtherUser = @rIsOtherUser) OR (@rIsOtherUser = -1))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND (ISNULL(EM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,'.')) OR ISNULL(@rMultiCode,'')='')
			--Order By EM.Code	
			Order By EM.Number
			END
			ELSE
			BEGIN
				SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				ISNULL(EI.EmployeeSign, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
				OM.DisplayTitle,
				OM.Id As OrgId
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId= EM.Id
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((EM.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND U.UserId = @rUserId
			AND ((EM.IsOtherUser = @rIsOtherUser) OR (@rIsOtherUser = -1))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND (ISNULL(EM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,'.')) OR ISNULL(@rMultiCode,'')='')
			--Order By EM.Code	
			Order By EM.Number
			END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterModify]
	
	@rId [bigint],
	@rCode [nvarchar](20),
	@rFirstName [nvarchar](100),
	@rMiddleName [nvarchar](100),
	@rLastName [nvarchar](100),
	@rEmployeeTypeId int,
	@rDepartmentId int,
	@rDateOfBirth Date,
	@rDateOfJoining Date,
	@rGenderId int,
	@rStatusId [smallint],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rEmployeePhoto varbinary(max),
	@rEmployeeDesignationId [int],
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rShortName nvarchar(50),
	@rNumber bigint = 0,
	@rIsOtherUser smallint = 0,
	@rDateOfLeaving Date =NULL 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lOrgId int
	
	SELECT @lOrgId = OrgId FROM sHrm.tEmployeeMaster WHERE Id=@rId AND ISNULL(IsOtherUser,0) = 0 

	IF EXISTS(SELECT Id FROM sHrm.tEmployeeMaster WHERE Code=@rCode AND OrgId=@lOrgId AND Id<>@rId  )
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
			
	 UPDATE sHrm.tEmployeeMaster
		SET
		    Code = @rCode, 
			FirstName = @rFirstName,
			MiddleName = @rMiddleName,
			LastName = @rLastName,
			StatusId = @rStatusId,
			ShortName=@rShortName,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			Number = @rNumber,
			IsOtherUser = @rIsOtherUser
	  WHERE 
			Id = @rId 
	  
	SELECT @rId AS RESULT
	
	BEGIN 
	UPDATE sHrm.tEmployeeJobDetail
		SET 
			EmployeeDesignationId = @rEmployeeDesignationId,	
			OrganizationDepartmentId = @rDepartmentId,
			DateOfJoining =	@rDateOfJoining,
			UpdatedUserId = @rUpdatedUserId,
			EmployeeTypeId = @rEmployeeTypeId,
			EmployeeGradeId = @rEmployeeGradeId,
			EmployeeGroupId = @rEmployeeGroupId,
			DateOfLeaving = @rDateOfLeaving
		WHERE 
			EmployeeId = @rId
			
		--IF(@rStatusId = 9)
		--BEGIN
		--	UPDATE sHrm.tEmployeeJobDetail
		--	SET
		--	DateOfLeaving = @rDateOfLeaving
		--	WHERE 
		--	EmployeeId = @rId
		--END
	
	UPDATE sHrm.tEmployeePersonalDetail
		SET 
			DateOfBirth	=	@rDateOfBirth,
			GenderId	=	@rGenderId,
			UpdatedUserId = @rUpdatedUserId
		WHERE 
			EmployeeId = @rId	
	
	IF @rStatusId = 9
	BEGIN
		UPDATE sSecurity.tUser
			SET 
				IsObsolete = 1,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			WHERE 
				SourceId = @rId AND SourceTypeId = 95
				
		
	END
	ELSE IF @rStatusId = 7
	BEGIN
		UPDATE sSecurity.tUser
			SET 
				IsObsolete = 0,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			WHERE 
				SourceId = @rId AND SourceTypeId = 95
	END
	
	--IF @rStatusId != 9
	--BEGIN
	--	UPDATE sHrm.tEmployeeJobDetail
	--	SET 
	--		DateOfleaving = NULL,	
	--		ReasonOfleaving = NULL
	--	WHERE 
	--		EmployeeId = @rId		
	--END
	
	
	  
	  --BEGIN
	  --   Execute sHrm.pEmployeeJobDetailModify 
	  --     0,@rId,0,@rEmployeeDesignationId,@rLocationId,@rDepartmentId,@rDateOfJoining,'','',0,0,@rUpdatedUserId,
	  --     0,0,@rEmployeeTypeId,@rProcessTypeId,NULL,NULL,NULL,0,0
	     --Execute sHrm.pEmployeePersonalDetailModify
	     --  0,@rId,'',@rDateOfBirth,@rGenderId,0,0,'','',0,0,'','','','','',0,'',0,'',0,0,@rUpdatedUserId,@rIsBirthDateUnknown
	     
	  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMonthWiseLeaveGet]
	 
	@rEmployeeId bigint,	 
	@rForMonth int,
	@rForYear int,
	@rBatchId int,
	@rIsConsiderBiometricRule bit=0,
	@rIsSandwichRuleApplicable bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
  
 SELECT 
			
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, @lFirstDate , EJD.DateOfJoining) 
		--	ELSE ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](1,L.FromDate,L.ToDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0)
		--END AS NoOfLeave,	
   
        ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](1,L.FromDate,L.ToDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0) AS NoOfLeave,
        ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](0,L.FromDate,L.ToDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0) AS PaidLeave,

		 --ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](1,@lFirstDate,@lLasteDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0) AS NoOfLeave,
   --     ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](0,@lFirstDate,@lLasteDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0) AS PaidLeave,
        
        CASE WHEN @rIsConsiderBiometricRule = 1 THEN ISNULL([sBiometric].[fEmployeeLateCountGet](@rEmployeeId, @rForMonth,@rForYear),0) ELSE 0 END AS LateCount
        FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		LEFT JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId	 AND L.BatchId = @rBatchId 	AND L.StatusId = 550 -- apporved 
    	WHERE EM.EmployeeId = @rEmployeeId  
    	GROUP BY EJD.DateOfJoining
    	
    	IF(@rIsSandwichRuleApplicable=1)
    		EXEC [sHrm].[pEmployeeMonthWiseSandwichDaysCountGet] @rEmployeeId,@rForMonth,@rForYear,@rBatchId
    	ELSE
    		SELECT 0 AS SandwichDayCount
    		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMonthWiseSandwichDaysCountGet]
	 
	@rEmployeeId bigint,	 
	@rForMonth int,
	@rForYear int,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		DECLARE @lLeave table(
		AutoId int identity,
		FromDate date,
		ToDate date
		)
		
		INSERT INTO @lLeave
		SELECT   
			L.FromDate,
			L.ToDate
        FROM 
			sHrm.tLeave L 
		WHERE 
			L.EmployeeId = @rEmployeeId 
			AND L.BatchId = @rBatchId 
			--AND L.StatusId = 550
			AND (
				(MONTH (L.FromDate) = @rForMonth AND YEAR (L.FromDate) = @rForYear)
				OR 
				(MONTH (L.ToDate) = @rForMonth AND YEAR (L.ToDate) = @rForYear)
				)
		
		DECLARE @lFirstDate date
		DECLARE @lLasteDate date
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
		DECLARE @lDayCount int
		SET @lDayCount = DAY(@lLasteDate)
		
		DECLARE @lWeekOff table(
		AutoId int identity,
		WeekOffDate date
		)
		
		WHILE @lDayCount > 0 
		BEGIN
			DECLARE @lWeekHOffStatus nvarchar(10)=''
			SELECT @lWeekHOffStatus = [sHrm].[fWeekHOffGet] (@rEmployeeId,@rForYear,@rForMonth,@lDayCount,@rBatchId,0,LEFT(@rBatchId,4))
			IF(@lWeekHOffStatus='H' OR @lWeekHOffStatus='W')
			BEGIN
				INSERT INTO @lWeekOff 
				SELECT CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/'+CONVERT(NVARCHAR(2),@lDayCount)))
			END
			SET @lDayCount = @lDayCount - 1
		END
		
		DECLARE @lLeaveCount int=0
		SELECT @lLeaveCount=COUNT(1) FROM @lLeave
		
		DECLARE @lWeekOffCount int=0
		SELECT @lWeekOffCount=COUNT(1) FROM @lWeekOff
		
		
		DECLARE @lSandwichDayCount int=0
		
		WHILE @lLeaveCount > 0 
		BEGIN
			DECLARE @lLeaveFromDate date
			DECLARE @lLeaveToDate date
			SELECT @lLeaveFromDate=FromDate,@lLeaveToDate=ToDate FROM @lLeave WHERE AutoId = @lLeaveCount
				
			WHILE @lWeekOffCount > 0 
			BEGIN
				DECLARE @lWeekOffDate date
				DECLARE @lMinLeaveFromDate date
				DECLARE @lPlusLeaveFromDate date
				SET @lMinLeaveFromDate = DATEADD(day,-1,@lLeaveFromDate)
				SET @lPlusLeaveFromDate = DATEADD(day,1,@lLeaveFromDate)
				SELECT @lWeekOffDate=WeekOffDate FROM @lWeekOff WHERE AutoId = @lWeekOffCount
				
				IF(@lMinLeaveFromDate=@lWeekOffDate OR @lPlusLeaveFromDate=@lWeekOffDate)
					SET @lSandwichDayCount = @lSandwichDayCount+1	
				
				SET @lWeekOffCount = @lWeekOffCount - 1
			END
			SET @lLeaveCount = @lLeaveCount - 1
		END
		
		SELECT @lSandwichDayCount AS SandwichDayCount
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pEmployeePendingLeaveDashboardGet]
	 
	 @rType nvarchar(100)='',
	 
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
  SELECT
	(
		SELECT 
			COUNT(L.Id) 
		FROM 
			sHrm.tLeave L 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = L.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId
		WHERE 
			L.StatusId = 549 
			AND ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId=0)
			AND (L.OrgId = @rOrgId OR @rOrgId=0) 
			AND (L.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,L.ReportDate)=CONVERT(DATE,GETDATE())
	) AS DailyCount,
	
		(
		SELECT 
			COUNT(L.Id) 
		FROM 
			sHrm.tLeave L 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = L.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId
		WHERE 
			L.StatusId = 549 
			AND ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId=0)
			AND (L.OrgId = @rOrgId OR @rOrgId=0) 
			AND (L.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,L.ReportDate)=DATEADD(day, -1, convert(date, GETDATE())) 
	) AS YesterdayCount,
	
	(
		SELECT 
			COUNT(L.Id) 
		FROM 
			sHrm.tLeave L 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = L.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId
		WHERE 
			L.StatusId = 549 
			AND ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId=0)
			AND (L.OrgId = @rOrgId OR @rOrgId=0) 
			AND (L.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,L.ReportDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE())
	) AS WeeklyCount,
	
	(
		SELECT 
			COUNT(L.Id) 
		FROM 
			sHrm.tLeave L 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = L.OrgId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId
		WHERE 
			L.StatusId = 549 
			AND ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId=0)
			AND (L.OrgId = @rOrgId OR @rOrgId=0) 
			AND (L.BatchId = @rBatchId OR @rBatchId=0) 
			AND CONVERT(DATE,L.ReportDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
	)  AS MonthlyCount
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeePersonalDetailAdd]
	
	@rOrgId smallint,
	@rEmployeeId [bigint],
	@rUIDNumber [nvarchar](50),
	@rDateOfBirth	date,
	@rGenderId	tinyint,
	@rReligionId	int,
	@rMaritalStatusId	tinyint,
	@rIdentificationMark1	nvarchar(100),
	@rBloodGroupId	tinyint,
	@rQualification	nvarchar(150),
	@rCreatedUserId [bigint],
	@rFamilyCast nvarchar(150)='',
	@rCastCategoryId int=NULL,
	@rTribeId int = null,
	@rAdhaarNumber nvarchar(40)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeePersonalDetail', 0, 1, 1,@outNextNumber = @lNextNumber output

 		IF (@rReligionId <= 0)
			SET @rReligionId = NULL
		
		IF (@rCastCategoryId <= 0)
			SET @rCastCategoryId = NULL	
			
  		IF (@rMaritalStatusId <= 0)
			SET @rMaritalStatusId = NULL
			
	  	IF (@rBloodGroupId <= 0 OR @rBloodGroupId Is null)
			SET @rBloodGroupId = 9

		IF (@rTribeId <= 0)
			SET @rTribeId = NULL
		
	INSERT INTO sHrm.tEmployeePersonalDetail
		(
			EmployeeId,
			UIDNumber,
			DateOfBirth,
			GenderId,
			ReligionId,
			MaritalStatusId,
			IdentificationMark1,
			BloodGroupId,
			Qualification,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			FamilyCast,
			CastCategoryId,
			TribeId,
			AdhaarNumber
		)
	VALUES
		(
			@rEmployeeId,
			@rUIDNumber,
			@rDateOfBirth,
			@rGenderId,
			@rReligionId,
			@rMaritalStatusId,
			@rIdentificationMark1,
			@rBloodGroupId,
			@rQualification,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rFamilyCast,
			@rCastCategoryId,
			@rTribeId,
			@rAdhaarNumber
		)
	SELECT @lNextNumber AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeePersonalDetailBatchWiseGet]
	
	@rOrgId smallint,
	@rEmployeeId bigint = 0,
	@rBatchId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			EPD.UIDNumber,
			EPD.EmployeeId,			 
			EPD.DateOfBirth,
			EPD.GenderId,			
			ISNULL(EPD.ReligionId,0) AS ReligionId, 
			ISNULL(EPD.MaritalStatusId,0) AS MaritalStatusId, 
			EPD.IdentificationMark1,
			EPD.BloodGroupId, 
			ISNULL(EPD.Qualification,'') AS Qualification,
			EPD.UpdatedUserId,
			EPD.UpdatedDateTime,
			ISNULL(EPD.FamilyCast,'') AS FamilyCast,
			ISNULL(EPD.CastCategoryId,0) AS CastCategoryId,
			AdhaarNumber
	FROM 
			sHrm.tBatchEmployeePersonalDetail EPD 
	WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		    AND EPD.OrgId = @rOrgId
		    AND EPD.BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeePersonalDetailGet]
	
	@rOrgId smallint,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			EPD.UIDNumber,
			EPD.EmployeeId,			 
			EPD.DateOfBirth,
			EPD.GenderId,			
			ISNULL(EPD.ReligionId,0) AS ReligionId, 
			ISNULL(EPD.MaritalStatusId,0) AS MaritalStatusId, 
			EPD.IdentificationMark1,
			EPD.BloodGroupId, 
			ISNULL(EPD.Qualification,'') AS Qualification,
			EPD.UpdatedUserId,
			EPD.UpdatedDateTime,
			ISNULL(EPD.FamilyCast,'') AS FamilyCast,
			ISNULL(EPD.CastCategoryId,0) AS CastCategoryId,
			AdhaarNumber,
			ISNULL(EPD.TribeId, 0) AS TribeId
	FROM 
			sHrm.tEmployeePersonalDetail EPD 
	WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND EPD.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeePersonalDetailModify]
	 
	@rEmployeeId [bigint],
	@rUIDNumber [nvarchar](50),
	@rDateOfBirth	date,
	@rGenderId	tinyint,
	@rReligionId	int,
	@rMaritalStatusId	tinyint,
	@rIdentificationMark1	nvarchar(100),
	@rBloodGroupId	tinyint,
	@rQualification	nvarchar(150),
	@rUpdatedUserId [bigint],
	@rFamilyCast nvarchar(150)='',
	@rCastCategoryId int=NULL,
	@rAdhaarNumber nvarchar(20)='',
	@rTribeId int = NULL
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		IF (@rReligionId <= 0)
			SET @rReligionId = NULL			
		IF (@rCastCategoryId <= 0)
			SET @rCastCategoryId = NULL		
  		IF (@rMaritalStatusId <= 0)
			SET @rMaritalStatusId = NULL	
	  	IF (@rBloodGroupId <= 0 OR @rBloodGroupId Is null)
			SET @rBloodGroupId = 9			
		IF (@rTribeId <= 0)
			SET @rTribeId = NULL	
				
	UPDATE sHrm.tEmployeePersonalDetail
		SET 
				UIDNumber = @rUIDNumber,
				DateOfBirth	=	@rDateOfBirth,
				GenderId	=	@rGenderId,
				ReligionId	=	@rReligionId,
				MaritalStatusId	=	@rMaritalStatusId,
				IdentificationMark1	=	@rIdentificationMark1,		 
				BloodGroupId	=	@rBloodGroupId,
				Qualification	=	@rQualification,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				FamilyCast = @rFamilyCast,
				CastCategoryId = @rCastCategoryId,
				AdhaarNumber =@rAdhaarNumber,
				TribeId = @rTribeId
	    WHERE 
				EmployeeId = @rEmployeeId
	       
	  SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeePresenceDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
  SELECT
	  ISNULL((
	 SELECT 
	   ISNULL((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM 
	   ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE())
	    AND  (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId 
	    OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR 
	   INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE())
	    AND  (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0)
	     AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0),0) as B
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0))) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY OM.OrgGroupId
	  ),0)
       AS DailyAverage,
       ISNULL((
	 SELECT 
	   ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM 
	   ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE())
	    AND  (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId 
	    OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0))+'/'+
	   CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR 
	   INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE())
	    AND  (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0)
	     AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0)),0) AS B
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0))) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY OM.OrgGroupId
	  ),'0/0') 
       AS DailyCount,
        ISNULL((
	   SELECT 
	   ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM 
	   ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster 
	   BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE())) AND 
	    (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND 
	    (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0))+'/'+
	   CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON 
	   EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster 
	   BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE())) AND  (OM.OrgGroupId = @rOrgGroupId) 
	   AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  
	   HAVING COUNT(EAR.EmployeeId) > 0)),0)AS B
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE()))
	    AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0))) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY OM.OrgGroupId
	  ),'0/0' )
       AS YesterdayCount,
       ISNULL((
	   SELECT 
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM 
	   ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster 
	   BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE())) AND 
	    (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND 
	    (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON 
	   EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster 
	   BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE())) AND  (OM.OrgGroupId = @rOrgGroupId) 
	   AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  
	   HAVING COUNT(EAR.EmployeeId) > 0)),0) AS B
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) = DATEADD(day, -1, convert(date, GETDATE()))
	    AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0))) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY OM.OrgGroupId
	  ),0)
       AS YesterdayAverage,
       ISNULL((
       SELECT 
	   ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0)) +'/'+
	   CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND   ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0)),0)AS B
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY OM.OrgGroupId
       ),'0/0') 
       AS WeeklyCount,
       ISNULL((
       SELECT 
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND   ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0)),0)
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0))) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY OM.OrgGroupId
       ),0) 
       AS WeeklyAverage,
       ISNULL((
       SELECT 
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND   ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND   ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0)),0)
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY OM.OrgGroupId
       ),0) 
       AS MonthlyAverage,
         ISNULL((
       SELECT 
	   ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0))+'/'+
	   CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND   ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  HAVING COUNT(EAR.EmployeeId) > 0)),0)AS B
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0)  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY OM.OrgGroupId
       ),'0/0')
       AS MonthlyCount
  END
  
  IF(@rType='Department')
  BEGIN
  	IF(@rDay=-1)
	BEGIN
	   SELECT 
	   EM.DepartmentId,EM.DepartmentName,
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM 
	   ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM 
	   ON BM.Id = EAR.BatchId WHERE IsPresent=1 
	   AND CONVERT(DATE,AttendanceDate) BETWEEN DATEADD(day, -1, convert(date, GETDATE())) AND DATEADD(day, -1, convert(date, GETDATE())) AND  
	   (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId 
	   OR @rBatchId=0)  AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR 
	   INNER JOIN sHrm.vEmployeeCommonDetail vEM 
	   ON EAR.EmployeeId = vEM.EmployeeId 
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate)
	    BETWEEN DATEADD(day, -1, convert(date, GETDATE())) AND DATEADD(day, -1, convert(date, GETDATE())) AND  ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0)))
	     AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)
	     AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0)),0) AS YesterdayAverage,
	   ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM 
	   ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM 
	   ON BM.Id = EAR.BatchId WHERE IsPresent=1 
	   AND CONVERT(DATE,AttendanceDate) BETWEEN DATEADD(day, -1, convert(date, GETDATE())) AND DATEADD(day, -1, convert(date, GETDATE())) AND  
	   (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId 
	   OR @rBatchId=0)  AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0))+'/'+ 
	   CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR 
	   INNER JOIN sHrm.vEmployeeCommonDetail vEM 
	   ON EAR.EmployeeId = vEM.EmployeeId 
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate)
	    BETWEEN DATEADD(day, -1, convert(date, GETDATE())) AND DATEADD(day, -1, convert(date, GETDATE())) AND 
	    ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0)))
	     AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)
	     AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0)),0) AS YesterdayCount
	     
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail EM ON EAR.EmployeeId = EM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) BETWEEN DATEADD(day, -1, convert(date, GETDATE())) AND DATEADD(day, -1, convert(date, GETDATE()))
	    AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0))) AND (EM.OrgId = @rOrgId OR @rOrgId=0)
	     AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY EM.DepartmentId,EM.DepartmentName
	END
	IF(@rDay=1)
	BEGIN
	   SELECT 
	   EM.DepartmentId,EM.DepartmentName,
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)  AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0) AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0)),0) AS DailyAverage,
	   ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)  AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0))+'/'+
	   CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0) AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0)),0) AS DailyCount
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail EM ON EAR.EmployeeId = EM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()) AND CONVERT(DATE,GETDATE()) AND (OM.OrgGroupId = @rOrgGroupId) AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) AND (EM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY EM.DepartmentId,EM.DepartmentName
	END
	IF(@rDay=7)
	BEGIN
	   SELECT 
	   EM.DepartmentId,EM.DepartmentName,
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0) AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0) AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0)),0) AS WeeklyAverage,
	    ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0) AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0))+'/'+
	   CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0) AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0)),0) AS WeeklyCount
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail EM ON EAR.EmployeeId = EM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0))) AND (EM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY EM.DepartmentId,EM.DepartmentName
	END
	IF(@rDay=30)
	BEGIN
	   SELECT 
	   EM.DepartmentId,EM.DepartmentName,
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0) AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0) AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0)),0) AS MonthlyAverage,
	   ISNULL(CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0) AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0))+'/'+
	   CONVERT(nvarchar(30),(SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) AND (vEM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0) AND EM.DepartmentId =  vEM.DepartmentId   HAVING COUNT(EAR.EmployeeId) > 0)),0) AS MonthlyCount
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail EM ON EAR.EmployeeId = EM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0))) AND (EM.OrgId = @rOrgId OR @rOrgId=0) AND (EAR.BatchId = @rBatchId OR @rBatchId=0)	
	   GROUP BY EM.DepartmentId,EM.DepartmentName
	END
  END	
  
  IF(@rType='OrgGroup')
  BEGIN
  	IF(@rDay=-1)
	BEGIN
	   SELECT 
	   OM.Id AS OrgId, OM.DisplayTitle AS Organization,
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM 
	   ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM 
	   ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) =  DATEADD(day, -1, convert(date, GETDATE())) 
	   AND  (OM.OrgGroupId = @rOrgGroupId) 
	   AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM 
	   ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster
	    BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) =  DATEADD(day, -1, convert(date, GETDATE())) AND  (OM.OrgGroupId = @rOrgGroupId) 
	    AND (BM.OrgGroupBatchId = @rOrgGroupBatchId) HAVING COUNT(EAR.EmployeeId) > 0)),0) AS YesterdayCount
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) =  DATEADD(day, -1, convert(date, GETDATE())) AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0))) 
	   GROUP BY OM.Id, OM.DisplayTitle
	END
	IF(@rDay=1)
	BEGIN
	   SELECT 
	   OM.Id AS OrgId, OM.DisplayTitle AS Organization,
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON 
	   EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON 
	   BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON 
	   EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster 
	   BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId =0) AND
	   ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId=0) HAVING COUNT(EAR.EmployeeId) > 0)),0) AS DailyAverage
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) = CONVERT(DATE,GETDATE()) AND((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0))) 
	   GROUP BY OM.Id, OM.DisplayTitle
	END
	IF(@rDay=7)
	BEGIN
	   SELECT 
	   OM.Id AS OrgId, OM.DisplayTitle AS Organization,
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)   HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) HAVING COUNT(EAR.EmployeeId) > 0)),0) AS WeeklyAverage
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-7) AND CONVERT(DATE,GETDATE()) AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0)))
	   GROUP BY OM.Id, OM.DisplayTitle
	END
	IF(@rDay=30)
	BEGIN
	   SELECT 
	   OM.Id AS OrgId, OM.DisplayTitle AS Organization,
	   ISNULL(((SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE IsPresent=1 AND CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0) HAVING COUNT(EAR.EmployeeId) > 0) * 100 / 
	   (SELECT COUNT(EAR.EmployeeId)  FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND  ((OM.OrgGroupId = @rOrgGroupId) OR @rOrgGroupId=0) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR @rOrgGroupBatchId =0)   HAVING COUNT(EAR.EmployeeId) > 0)),0) AS MonthlyAverage
	   FROM sHrm.tEmployeeAttendanceRegister EAR INNER JOIN sHrm.vEmployeeCommonDetail vEM ON EAR.EmployeeId = vEM.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vEM.OrgId
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId
	   WHERE CONVERT(DATE,AttendanceDate) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE()) AND ((OM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId = 0) ) AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId OR (@rOrgGroupBatchId =0)))
	   GROUP BY OM.Id, OM.DisplayTitle
	END
  END	
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeePreviousEmploymentAdd]
	@rId bigint,
	@rOrgId smallint,
	@rEmployeeId [bigint],
	@rCompanyName [nvarchar](300),	
	@rDesignation nvarchar(100), 
	@rDuration [nvarchar](300),
	@rRemark nvarchar(200),
	@rLastSalary int,
	@rReasonForLeaving nvarchar(100),
	@rJobDescription nvarchar(100),
	@rIsInternal bit,
	@rCreatedUserId [bigint]
 
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
 IF NOT EXISTS(SELECT 1 FROM sHrm.tEmployeePreviousEmployment WHERE Id = @rId AND EmployeeId = @rEmployeeId AND OrgId = @rOrgId)
		
		BEGIN		
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeePreviousEmployment', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sHrm.tEmployeePreviousEmployment
			(
				Id,
				EmployeeId,
				CompanyName,						 
				Designation,
				Remark,
				Duration,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				OrgId,
			    LastSalary,
			    ReasonForLeaving,
			    JobDescription,
			    IsInternal
			    
			)
		VALUES
			(
				@lNextNumber,
				@rEmployeeId,
				@rCompanyName, 			
				@rDesignation,
				@rRemark,
				@rDuration,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgId,
				@rLastSalary,
			    @rReasonForLeaving,
			    @rJobDescription,
			    @rIsInternal
			)
		END
 
  ELSE
    BEGIN
       SET @lNextNumber = @rId
      UPDATE sHrm.tEmployeePreviousEmployment
		SET 			
			CompanyName = @rCompanyName,				
			Designation = @rDesignation,
			Remark = @rRemark,		 
			Duration = @rDuration,		 
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			LastSalary = @rLastSalary,
			ReasonForLeaving = @rReasonForLeaving,
			JobDescription = @rJobDescription,
			IsInternal = @rIsInternal
			
	  WHERE Id = @rId AND EmployeeId = @rEmployeeId       
      
    END		
				
		SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeePreviousEmploymentDelete]
	@rId [bigint],
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 DELETE FROM  sHrm.tEmployeePreviousEmployment
	 
	  WHERE Id = @rId AND OrgId = @rOrgId
	  
	  SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeePreviousEmploymentGet]  
   
 @rOrgId int,  
 @rEmployeeId [bigint] = 0  
   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
SELECT     Id,
    EmployeeId,
    CompanyName,
      ISNULL(Designation,'') AS Designation, 
       ISNULL(Remark,'') AS Remark,
       ISNULL(Duration,'') AS Duration ,
                  CreatedUserId,
                      CreatedDateTime AS CreatedDateTime,
                      CONVERT(varchar(20), CreatedDateTime, 105) AS CreatedDateTimeJSON,
                         UpdatedUserId,
                            UpdatedDateTime  AS UpdatedDateTime,  
                               CONVERT(varchar(20),UpdatedDateTime, 105)  AS UpdatedDateTimeJSON,  
   2 AS OperationState,  
       ISNULL(LastSalary,0) AS Lastsalary,
            ISNULL(ReasonForLeaving,'') AS ReasonForLeaving,
                   ISNULL(JobDescription,'') AS JobDescription,
                          ISNULL(IsInternal,0) AS IsInternal   
                          FROM     sHrm.tEmployeePreviousEmployment  
 WHERE      (EmployeeId = @rEmployeeId)    AND OrgId = @rOrgId END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeProfileFullGet]  
 @rEmployeeId bigint,  
 --newly added parameter for report   
 @rBuilder1 nvarchar(max)='',  
 @rBuilder2 nvarchar(max)='',  
 @rReportId smallint = 0,  
 @rOrgId smallint = 0,  
 @rStrEmployeeId nvarchar(max)='',  
 @rEmployeeTypeId [int] =0,  
 @rDepartmentId [int]= 0,  
 @rGradeId [int]= 0,  
 @rGenderId [int]= 0,   
 @rDesignationId [int]= 0,   
 @rAgeFrom nvarchar(10)='',  
 @rAgeTo nvarchar(10)='',  
 @rEmployeeCode nvarchar(50)='',  
 @rEmployeeGroupId smallint= 0,  
 @rEmployeeStatusId smallint=0  
   
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
   
BEGIN   
  
SELECT   
   --Personal Details  
   EM.Id,  
   EM.Code,  
   ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,  
   ISNULL(EP.UIDNumber,'') AS UIDNumber,  
   ISNULL(EP.DateOfBirth,'') AS DateOfBirth,  
   ISNULL(GM.Title,'') AS Gender,  
   ISNULL(MM.Title,'') AS MeritalStatus,  
   ISNULL(BGM.Title,'') AS BloodGroup,  
   ISNULL(EP.Qualification,'') AS Qualification,  
   ISNULL(EP.FamilyCast,'') AS FamilyCast,  
   --Communication  
   ISNULL(EC.PresentStreetOne,'')+' '+ISNULL(EC.PresentStreetTwo,'')+' '+ISNULL(EC.PresentStreetThree,'') AS PresentAddress,  
   ISNULL(EC.PresentCity,'') AS PresentCity,  
  ISNULL(EC.PresentState,'') AS PresentState,  
  ISNULL(EC.PresentCountry,'') AS PresentCountry,  
  ISNULL(EC.PresentZipCode,'') AS PresentZipCode,  
  ISNULL(EC.PresentContactNo,'') AS PresentContactNo,  
  ISNULL(EC.PermanentStreetOne,'')+' '+ISNULL(EC.PermanentStreetTwo,'')+' '+ISNULL(EC.PermanentStreetThree,'') AS PermanentAddress,  
  ISNULL(EC.PermanentCity,'') AS PermanentCity,  
  ISNULL(EC.PermanentState,'') AS PermanentState,  
  ISNULL(EC.PermanentCountry,'') AS PermanentCountry,  
  ISNULL(EC.PermanentZipCode,'') AS PermanentZipCode,  
  ISNULL(EC.PermanentContactNo,'') AS PermanentContactNo,  
   ISNULL(EC.EmergencyStreetOne,'')+' '+ISNULL(EC.EmergencyStreetTwo,'')+' '+ISNULL(EC.EmergencyStreetThree,'') AS EmergencyAddress,  
  ISNULL(EC.EmergencyCity,'') AS EmergencyCity,  
  ISNULL(EC.EmergencyState,'') AS EmergencyState,  
  ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,  
  ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,  
  ISNULL(EC.EmergencyContactNo,'') AS EmergencyContactNo,  
  --Job Details  
  ISNULL(EJ.DateOfJoining,'') AS DateOfJoining,    
  (COALESCE(CAST(EJ.DateOfleaving AS NVARCHAR(23)),'')) AS DateOfleaving,  
  ISNULL(EJ.JobRemark,'') AS JobRemark,  
  ISNULL(EJ.ReferenceRemark,'') AS ReferenceRemark,  
  ISNULL(EDM.Title,'') AS EmployeeDesignation,  
  ISNULL(DM.Title,'') AS OrganizationDepartment,  
  ISNULL(EGM.Title,'') AS EmployeeGrade,  
  ISNULL(GrpM.Title,'') AS EmployeeGroup,  
  ISNULL(ETM.Title,'') AS EmployeeType,  
  ISNULL(EJ.ProbationUptoDate,'') AS ProbationUptoDate,  
  ISNULL(EJ.AhdocUptoDate,'') AS AhdocUptoDate,  
  ISNULL(EJ.PermanentDate,'') AS PermanentDate,  
  ISNULL(EJ.DateOfResignation,'') AS DateOfResignation,  
  ----Previous Employment  
  --ISNULL(EPE.CompanyName,'') AS PrevCompanyName,  
  --ISNULL(EPE.Designation,'') AS PrevDesignation,  
  --ISNULL(EPE.Duration,'') AS Duration,  
  --ISNULL(EPE.LastSalary,0) AS LastSalary,  
  --ISNULL(EPE.ReasonForLeaving,'') AS ReasonForLeaving,  
  --ISNULL(EPE.JobDescription,'') AS JobDescription,  
  --Notification Details  
  ISNULL(EC.PersonalEmail,'') As PersonalEmail,  
  ISNULL(EC.MobileNumber,'') AS MobileNumber,  
  ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,  
  ISNULL(EC.ExtensionNo,'') AS ExtensionNo,  
  ISNULL(EC.CompanyEmail,'') AS CompanyEmail,  
  --EI.EmployeePhoto,  
  CASE @rReportId WHEN 0 THEN ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) ELSE EI.EmployeePhoto END AS EmployeePhoto ,  
  ISNULL(ESO.AccountNumber,'') AS AccountNumber,  
  ISNULL(ESO.BankName,'') AS BankName,  
  ISNULL(ESO.Branch,'') AS BankBranch,  
  ISNULL(ESO.PanNumber,'') AS PanNumber,  
  ISNULL(ESO.UAN,'') AS UANNumber,  
  ISNULL(ESO.EPFNumber,'') AS EPFNumber,  
  ISNULL(ESO.IncrementDate,'') AS IncrementDate,  
  ISNULL(ESO.BasicPay,0) AS BasicPay,  
     --ISNULL(EFD.Occupation,'') AS Occupation,  
  convert(nvarchar(20),EM.Id) AS EmployeeIdText,  
  convert(nvarchar(20),@rOrgId) AS OrgIdText,  
  ISNULL(EJ.OrganizationDepartmentId,0) AS DepartmentId,  
  OM.DisplayTitle AS OrgTitle,  
  ISNULL(EP.AdhaarNumber,'') AS AdhaarNumber,  
  ISNULL(ESO.Payscale,'') AS Payscale,  
  --[sHrm].[fTeachingSubjectGet] (EM.Id) AS TeachingSubject  
  EJ.Subjects AS TeachingSubject  
  FROM   
  sHrm.tEmployeeMaster EM   
  LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.ID = EC.EmployeeId  
  INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id  
  INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID    
  --INNER JOIN sHrm.tEmployeePreviousEmployment EPE ON EPE.EmployeeId=EM.ID  
  LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EP.BloodGroupId      
  LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId  
  LEFT JOIN sCommon.tMaritalStatusMaster MM ON MM.Id =  EP.MaritalstatusId  
  --LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EJ.ReligionId  
  LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id  
  LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId  
  LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId  
  LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId  
  LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id=EJ.EmployeeGradeId  
  LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJ.EmployeeGroupId  
  LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id  
  --LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON EFD.EmployeeId = EM.Id  
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId    
  WHERE   
  (EM.Id=@rEmployeeId OR @rEmployeeId = 0)  
  AND (ISNULL(EM.Id,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='')   
  AND ((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )  
  AND (ETM.Id = @rEmployeeTypeId OR @rEmployeeTypeId = 0)  
  AND (DM.Id = @rDepartmentId OR @rDepartmentId = 0)  
  AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)  
  AND (GrpM.Id=@rEmployeeGroupId OR @rEmployeeGroupId=0)   
  AND (EGM.Id = @rGradeId OR @rGradeId = 0)  
  AND (EDM.Id = @rDesignationId OR @rDesignationId = 0)  
  AND (GM.Id = @rGenderId OR @rGenderId = 0)  
  AND ((DATEDIFF(yy,EP.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))  
  AND ((DATEDIFF(yy,EP.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))  
  AND  ( EM.OrgId = @rOrgId OR @rOrgId = 0)  
  --AND ISNULL(EM.IsOtherUser,0) = 0     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeProfileGet]
 
	@rOrgId int,
	@rDepartmentId int = 0,
	@rEmployeeId bigint,
	@rGroupId int
 
AS
SET NOCOUNT ON

BEGIN
		SELECT 
				EM.Id AS EmployeeId,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(EC.CompanyEmail,'') AS EmailId,
				DM.Id AS DepartmentId,
				DM.Title AS DepartmentName,
				CONVERT(date,EJD.DateOfJoining) AS DateOfJoining,
				EM.Code AS Code,
				ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
				GrpM.Id AS EmployeeGroupId,
				GrpM.Title AS GroupName,
				[sHrm].[fEmployeeSubjectGet](EM.Id) AS Subjects,
				ISNULL(EC.MobileNumber,'') AS MobileNumber,
				CONVERT(nvarchar(10), ROW_NUMBER() OVER ( ORDER BY EM.Id )) AS SrNo,
				ISNULL(EPD.GenderId,0) AS GenderId,
				ISNULL(GM.Title,'') AS Gender
		FROM 
				sHrm.tEmployeeMaster EM
				INNER JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
				LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id
				LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJD.EmployeeGroupId
		WHERE 
				EM.OrgId = @rOrgId 
				AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
				AND ((EM.Id=@rEmployeeId) OR (@rEmployeeId=0))
				AND ((EJD.EmployeeGroupId = @rGroupId) OR (@rGroupId = 0))	
				AND EM.StatusId = 7
				AND ISNULL(EM.IsOtherUser,0) = 0 
		ORder BY case When ISnumeric(Em.Code)=1 Then convert(nvarchar,Em.Code)  When ISnumeric(Em.Code)=0 then Em.Code End ASC	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeQualificationDelete]
			
			@rId bigint,
		    @rOrgId int
AS
SET NOCOUNT ON
 
BEGIN 
      
    BEGIN
     DELETE FROM sHrm.tEmployeeQualification WHERE Id = @rId AND OrgId = @rOrgId
      SELECT 1 AS RESULT
    END
         
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeQualificationDetailsAdd]
    
    @rId bigint,
	@rOrgId smallint,
	@rEmployeeId [bigint],
	@rExamPassed [nvarchar](100),
	@rPassYear [nvarchar](20),
	@rPercentage [decimal](8,2),
	@rGrade [nvarchar](50),
	@rInstituteDetail [nvarchar](200),
	@rBoardDetail [nvarchar](200),
	@rSubjects [nvarchar](200),
	@rRemark [nvarchar](100),
	@rCreatedUserId [bigint]

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION
	
 IF NOT EXISTS(SELECT 1 FROM sHrm.tEmployeeQualification Where Id = @rId AND EmployeeId = @rEmployeeId AND OrgId = @rOrgId)
  
  BEGIN
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeQualification', 0, 1, 1,@outNextNumber = @lNextNumber output

		
		INSERT INTO sHrm.tEmployeeQualification
			(
				OrgId,
				Id,
				EmployeeId,
				ExamPassed,
				PassYear,
				Percentage,
				Grade,
				InstituteDetail,
				BoardDetail,
				Subjects,
				Remark,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime
			)
		VALUES
			(
				@rOrgId,
				@lNextNumber,
				@rEmployeeId,
				@rExamPassed,
				@rPassYear,
				@rPercentage,
				@rGrade,
				@rInstituteDetail,
				@rBoardDetail,
				@rSubjects,
				@rRemark,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate()
			)
	END
	ELSE
	  SET @lNextNumber = @rId
	  
	  UPDATE sHrm.tEmployeeQualification
	  SET  
	        ExamPassed = @rExamPassed,
			PassYear = @rPassYear,			
			Percentage = @rPercentage,
			Grade = @rGrade,
			InstituteDetail = @rInstituteDetail,
			BoardDetail = @rBoardDetail,
			Subjects = @rSubjects,
			Remark = @rRemark,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
			
	  WHERE 
			Id = @rId 
		AND EmployeeId = @rEmployeeId
	  
		SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeQualificationDetailsGet]
	
	@rOrgId int,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			--convert(nvarchar(20),EmployeeId) AS EmployeeIdText,
			--convert(nvarchar(20),@rOrgId) AS OrgIdText,
			OrgId,
			Id,
			EmployeeId,
			ISNULL(ExamPassed,'') AS ExamPassed,
			
			ISNULL(PassYear,'') AS PassYear,
			ISNULL(Percentage,0) AS Percentage,
			ISNULL(Grade,'') AS Grade,
			ISNULL(InstituteDetail,'') AS InstituteDetail,
			ISNULL(BoardDetail,'') AS BoardDetail,
			ISNULL(Subjects,'') AS Subjects,
			ISNULL(Remark,'') AS Remark,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		
		
	 FROM 
			sHrm.tEmployeeQualification
	 WHERE 
			 (EmployeeId = @rEmployeeId) OR @rEmployeeId=0
		AND OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeRegisterAttendanceGet]
	@rForYear  smallint,
	@rForMonth smallint,
	@rBatchId int,
	@rOrgId int,
	@rDepartmentId int=0
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date,@lLastDate date
	
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	--SET @lLastDate = sCommon.fGetLastDateofMonth(@lFirstDate)
	SET @lLastDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	Declare @Days int 
	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	--DECLARE @lAdmissionDate date 
	-- select @lAdmissionDate=Stud.DateOfJoining from    sStudent.tStudentAdmission Stud  inner join sStudent.vStudentAcademic A ON A.StudentId = Stud.StudentId
	--						Where AdmissionStandardId=@rClassId AND Stud.BatchId =@rBatchId  
	 
BEGIN 
 
CREATE Table #EmployeeAttendanceRegistertempTable
(
	 
	EmployeeCode nvarchar(50),
	EmployeeId bigint,
	EmployeeName nvarchar(100),
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	DepartmentId int,
	DepartmentName nvarchar(50),
	IsPresent bit,
	DayPart int,
	AttendanceDate date,
	DateOfJoining date,
	DateOfLeaving  date,
	AttendanceTagId int ,
	Number bigint ,
	IsOtherUser smallint
 
)
Insert INTO #EmployeeAttendanceRegistertempTable
(	
	EmployeeCode ,
	EmployeeId ,
	EmployeeName,
	ForYear ,
	ForMonth,
	ForMonthInWord,
	DepartmentId ,
	DepartmentName ,
	IsPresent ,
	DayPart ,
	AttendanceDate ,
	DateOfJoining ,
	DateOfLeaving ,
	AttendanceTagId,
	Number,
	IsOtherUser
)
SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeId AS EmployeeId,
		EM.EmployeeName,
		YEAR(EAR.AttendanceDate) AS ForYear,
		MONTH(EAR.AttendanceDate) AS ForMonth,
		DATENAME(month, EAR.AttendanceDate) AS ForMonthInWord,
		EM.DepartmentId,
		EM.DepartmentName,
		EAR.IsPresent,
		day(EAR.AttendanceDate) AS DayPart,
		EAR.AttendanceDate,
		--ISNULL(CONVERT(VARCHAR(50),EM.DateOfJoining,103),'') AS DateOfJoining,
		EJD.DateOfJoining,
		EJD.DateOfLeaving,
		--ISNULL(CONVERT(VARCHAR(50),EM.DateOfLeaving,103),'') AS DateOfLeaving,
			EAR.AttendancetagId,
		EM.Number,
		EM.IsOtherUser

	FROM 
		
		--sHrm.vEmployeeCommonDetail EM 
		--INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		--LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		--AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
		
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
	WHERE 
		EM.OrgId = @rOrgId 
		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((EJD.DateOfleaving >= @lFirstDate) OR ISNULL(EJD.DateOfleaving,'') = '')
		AND ((EJD.DateOfJoining <= @lLastDate) OR ISNULL(EJD.DateOfJoining,'') = '')
		AND EM.IsOtherUser = 0
	ORDER BY EM.Number	
	--SELECT * FROM 	#EmployeeAttendanceRegistertempTable
CREATE TABLE #TempDaysTempTable
(
 DayPart int
 )
WHILE @li<=@Days

BEGIN

INSERT INTO #TempDaysTempTable
(
	DayPart 
)

SELECT 
@li AS DayPart
SET @li = @li + 1

END
 
SELECT  
			@lFirstDate AS LastDate,
			DateOfleaving,
			PivotTable.EmployeeId,
			DepartmentName,
			isnull(EmployeeCode,'') as EmployeeCode,
			isnull(EmployeeName,'') as EmployeeName,
			isnull(ForYear,'') AS ForYear,
			isnull(ForMonth,'') AS ForMonth,
			DepartmentId,
			DepartmentName,
			ForMonthInWord,	 
			--old function DepartmentWise
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),DateOfJoining,DateOfLeaving,[1]) AS P1,
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),DateOfJoining,DateOfLeaving,[2]) AS P2,
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),DateOfJoining,DateOfLeaving,[3]) AS P3,
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),DateOfJoining,DateOfLeaving,[4]) AS P4,
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),DateOfJoining,DateOfLeaving,[5]) AS P5,
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),DateOfJoining,DateOfLeaving,[6]) AS P6,
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),DateOfJoining,DateOfLeaving,[7]) AS P7,
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),DateOfJoining,DateOfLeaving,[8]) AS P8,
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),DateOfJoining,DateOfLeaving,[9]) AS P9,
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),DateOfJoining,DateOfLeaving,[10]) AS P10,
			--[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),DateOfJoining,DateOfLeaving,[11]) AS P11,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),DateOfJoining,DateOfLeaving,[12]) AS P12,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),DateOfJoining,DateOfLeaving,[13]) AS P13,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),DateOfJoining,DateOfLeaving,[14]) AS P14,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),DateOfJoining,DateOfLeaving,[15]) AS P15,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),DateOfJoining,DateOfLeaving,[16]) AS P16,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),DateOfJoining,DateOfLeaving,[17]) AS P17,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),DateOfJoining,DateOfLeaving,[18]) AS P18,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),DateOfJoining,DateOfLeaving,[19]) AS P19,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),DateOfJoining,DateOfLeaving,[20]) AS P20,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),DateOfJoining,DateOfLeaving,[21]) AS P21,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),DateOfJoining,DateOfLeaving,[22]) AS P22,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),DateOfJoining,DateOfLeaving,[23]) AS P23,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),DateOfJoining,DateOfLeaving,[24]) AS P24,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),DateOfJoining,DateOfLeaving,[25]) AS P25,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),DateOfJoining,DateOfLeaving,[26]) AS P26,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),DateOfJoining,DateOfLeaving,[27]) AS P27,
			-- [sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),DateOfJoining,DateOfLeaving,[28]) AS P28,
			-- CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),DateOfJoining,DateOfLeaving,[29]) end AS P29,
			-- CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),DateOfJoining,DateOfLeaving,[30])end AS P30,
			-- CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),DateOfJoining,DateOfLeaving,[31])end AS P31,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),DateOfJoining,DateOfLeaving,[1]) AS P1,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),DateOfJoining,DateOfLeaving,[2]) AS P2,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),DateOfJoining,DateOfLeaving,[3]) AS P3,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),DateOfJoining,DateOfLeaving,[4]) AS P4,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),DateOfJoining,DateOfLeaving,[5]) AS P5,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),DateOfJoining,DateOfLeaving,[6]) AS P6,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),DateOfJoining,DateOfLeaving,[7]) AS P7,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),DateOfJoining,DateOfLeaving,[8]) AS P8,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),DateOfJoining,DateOfLeaving,[9]) AS P9,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),DateOfJoining,DateOfLeaving,[10]) AS P10,
			[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),DateOfJoining,DateOfLeaving,[11]) AS P11,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),DateOfJoining,DateOfLeaving,[12]) AS P12,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),DateOfJoining,DateOfLeaving,[13]) AS P13,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),DateOfJoining,DateOfLeaving,[14]) AS P14,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),DateOfJoining,DateOfLeaving,[15]) AS P15,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),DateOfJoining,DateOfLeaving,[16]) AS P16,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),DateOfJoining,DateOfLeaving,[17]) AS P17,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),DateOfJoining,DateOfLeaving,[18]) AS P18,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),DateOfJoining,DateOfLeaving,[19]) AS P19,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),DateOfJoining,DateOfLeaving,[20]) AS P20,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),DateOfJoining,DateOfLeaving,[21]) AS P21,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),DateOfJoining,DateOfLeaving,[22]) AS P22,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),DateOfJoining,DateOfLeaving,[23]) AS P23,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),DateOfJoining,DateOfLeaving,[24]) AS P24,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),DateOfJoining,DateOfLeaving,[25]) AS P25,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),DateOfJoining,DateOfLeaving,[26]) AS P26,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),DateOfJoining,DateOfLeaving,[27]) AS P27,
			 [sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),DateOfJoining,DateOfLeaving,[28]) AS P28,
			 CASE WHEN @Days>=29 THEN[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),DateOfJoining,DateOfLeaving,[29]) end AS P29,
			 CASE WHEN @Days>=30 THEN[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),DateOfJoining,DateOfLeaving,[30])end AS P30,
			 CASE WHEN @Days>=31 THEN[sHrm].[fEmployeeWiseAttendanceJoiningDateGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),DateOfJoining,DateOfLeaving,[31])end AS P31,		 		 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,
0 Ispresent,
0 AS AttendanceTagId,
DateOfJoining   
FROM
(
	Select  
		EmployeeCode,
		EmployeeId,
		EmployeeName,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		DepartmentId,
		DepartmentName,
		(
			CASE 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		DateOfLeaving,		 
		DateOfJoining,
		Number	
	 FROM 
		#EmployeeAttendanceRegistertempTable ST 
		LEFT JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE 
		  ((DateOfLeaving >= @lFirstDate) OR ISNULL(DateOfLeaving,'') = '')
		  AND IsOtherUser = 0
	   -- WHERE 
	   -- ForYear=@rForYear AND ForMonth=@rForMonth
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  EmployeeId AS EmployeeId, COUNT(1) AS TCount 
		   FROM  
				#EmployeeAttendanceRegistertempTable
				WHERE AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		     GROUP BY  EmployeeId 
    ) TC ON TC.EmployeeId = PivotTable.EmployeeId 
	LEFT JOIN
	(
		Select EmployeeId AS EmployeeId, COUNT(1) AS ACount 
		   FROM  #EmployeeAttendanceRegistertempTable
		    WHERE   IsPresent = 0	 	 
		      AND AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			GROUP BY  EmployeeId
    ) AC ON AC.EmployeeId = PivotTable.EmployeeId
	LEFT JOIN
	(
		SELECT EJD.EmployeeId, COUNT(1) AS PCount  FROM 
		
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
		--sHrm.tEmployeeMaster EM 
		--INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		--LEFT JOIN  sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EJD.EmployeeId 	   
			WHERE   
	 --        ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
	 --       AND ((DM.Id = @rDepartmentId)OR (@rDepartmentId=0))
	 --       AND ((EAR.BatchId=@rBatchId) OR (@rBatchId= 0))
	 --       AND EAR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
	 --GROUP BY EJD.EmployeeId
	    ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
	       AND ((EM.DepartmentId = @rDepartmentId)OR (@rDepartmentId=0))
	       AND ((EAR.BatchId=@rBatchId) OR (@rBatchId= 0))
	       AND EAR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		   AND EM.IsOtherUser = 0
	 GROUP BY EJD.EmployeeId 
    ) PC ON PC.EmployeeId = PivotTable.EmployeeId
	Order By PivotTable.Number
 
   
    
select * from #TempDaysTempTable 
SELECT * FROM #EmployeeAttendanceRegistertempTable
drop table #EmployeeAttendanceRegistertempTable	  
drop table #TempDaysTempTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeReplacementDelete]
	 
        @rExistingEmployeeId BIGINT,
		@rTitle NVARCHAR(500)
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rTitle = 'Assign Teacher')
	BEGIN
		delete from sTimetable.tAssignTeacher where EmployeeId = @rExistingEmployeeId
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		
		delete from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId
		
		delete from sAcademic.tTeacherSubjectDivision where EmployeeId = @rExistingEmployeeId		
	END

	IF (@rTitle ='Time Table')
	BEGIN
		Delete sTimetable.tTimeTable where EmployeeId  = @rExistingEmployeeId
		
		DELETE sTimetable.tTeacherWorkLoad  WHERE EmployeeId = @rExistingEmployeeId 
	END
	
	IF (@rTitle ='User Access')
	BEGIN

		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		
		IF (@lExistingUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
		
			delete from sSecurity.tUserOrganization  WHERE UserId=@lExistingUserId

			delete from sSecurity.tUserAccess  WHERE UserId=@lExistingUserId
		END
	END

	IF (@rTitle ='Class Teacher')
	BEGIN
		Update sSetup.tDivisionMaster SET InchargeEmployeeId = 0 where  InchargeEmployeeId =  @rExistingEmployeeId
	END

	-- #Start Remove for MantisId : 0035518
	--IF (@rTitle ='Lesson Plan')
	--BEGIN
	--	Delete sAcademic.tLessonPlan where EmployeeId =  @rExistingEmployeeId
	--END
	-- #End Remove for MantisId : 0035518
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeReplacementDeleteAndTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rTitle NVARCHAR(500)
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	--CREATE Table #tmpSplitTable
	--(
	--	Id NVARCHAR(150)
	--)

	--INSERT INTO #tmpSplitTable
	--SELECT CAST(item AS NVARCHAR(150)) AS Id FROM  sCommon.fnsplit(@rId,',')
	
	IF (@rTitle = 'Assign Teacher')
	BEGIN
		IF NOT EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rNewEmployeeId)
		begin
			INSERT INTO sTimetable.tAssignTeacher
			Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId
			delete from sTimetable.tAssignTeacher where EmployeeId = @rExistingEmployeeId
		end		
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId 
		and SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		
		delete from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId
		
		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId 
		from sAcademic.tTeacherSubjectDivision 
		where SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		AND EmployeeId = @rExistingEmployeeId
		
		delete from sAcademic.tTeacherSubjectDivision where EmployeeId = @rExistingEmployeeId		
	END

	IF (@rTitle ='Time Table')
	BEGIN
		Update sTimetable.tTimeTable
		Set EmployeeId = @rNewEmployeeId from sTimetable.tTimeTable where EmployeeId  = @rExistingEmployeeId
		
		UPDATE sTimetable.tTeacherWorkLoad SET EmployeeId = @rNewEmployeeId WHERE EmployeeId = @rExistingEmployeeId 
	END
	
	IF (@rTitle ='User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)

		IF (@lNewUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
		Insert into sSecurity.tUserOrganization 
		select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId
		AND OrgId NOT in (select OrgId from sSecurity.tUserOrganization WHERE UserId=@lNewUserId)

		delete from sSecurity.tUserOrganization  WHERE UserId=@lExistingUserId

		INSERT INTO sSecurity.tUserAccess
		SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId
		AND SourceId not in (select SourceId from  sSecurity.tUserAccess WHERE UserId=@lNewUserId)

		delete from sSecurity.tUserAccess  WHERE UserId=@lExistingUserId
		END
	END

	IF (@rTitle ='Class Teacher')
	BEGIN
		Update sSetup.tDivisionMaster SET InchargeEmployeeId = @rNewEmployeeId where  InchargeEmployeeId = @rExistingEmployeeId
	END

	-- #Start Remove for MantisId : 0035518
	--IF (@rTitle ='Lesson Plan')
	--BEGIN
	--	Update sAcademic.tLessonPlan SET EmployeeId = @rNewEmployeeId where EmployeeId = @rExistingEmployeeId
	--END
	-- #End Remove for MantisId : 0035518

	--Drop Table #tmpSplitTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeReplacementGet]
	 
        @rEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lTeacherSubjectId bigint = 0 , @lTeacherDivisionId bigint = 0
	IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL DROP TABLE #tmpTable
	CREATE Table #tmpTable 
	(
		Id bigint IDENTITY,
		Title nvarchar(50)
	)

	IF EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Assign Teacher'
		)
	END


	set @lTeacherSubjectId = (select top 1 1 from sAcademic.tTeacherSubject where EmployeeId = @rEmployeeId)
	SET @lTeacherDivisionId = (select top 1 1 from sAcademic.tTeacherSubjectDivision where EmployeeId = @rEmployeeId)
	IF ((@lTeacherSubjectId = 1) OR (@lTeacherDivisionId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Teacher Subject Division'
		)
	END

	IF EXISTS (select top 1 1 from sTimetable.tTimeTable where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Time Table'
		)
	END
		
	declare @lUserId bigint= (select top 1 Id from sSecurity.tUser where SourceId = @rEmployeeId AND SourceTypeId = 95)
	declare @lUserOrganizationId int ,@lUserAccessId int
	SET @lUserOrganizationId = (SELECT Top 1 1 FROM sSecurity.tUserOrganization WHERE UserId=@lUserId)
	SET @lUserAccessId= (SELECT top 1 1 FROM sSecurity.tUserAccess WHERE UserId=@lUserId)
	IF ((@lUserOrganizationId = 1) OR (@lUserAccessId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'User Access'
		)
	END

	IF EXISTS (select top 1 1 from sSetup.tDivisionMaster where InchargeEmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Class Teacher'
		)
	END	

	-- #Start Remove for MantisId : 0035518
	--IF EXISTS (select top 1 1 from sAcademic.tLessonPlan where EmployeeId = @rEmployeeId)
	--BEGIN
	--	Insert INTO #tmpTable Values
	--	(
	--		'Lesson Plan'
	--	)
	--END
	-- #End Remove for MantisId : 0035518

	select * from #tmpTable order by Title

	Drop Table #tmpTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeReplacementTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rTitle NVARCHAR(max),
		@rOrgId int
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	--CREATE Table #tmpSplitTable
	--(
	--	Id NVARCHAR(max)
	--)

	--INSERT INTO #tmpSplitTable
	--SELECT CAST(item AS NVARCHAR(max)) AS Id FROM  sCommon.fnsplit(@rId,',')

	IF (@rTitle = 'Assign Teacher')
	BEGIN
		IF NOT EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rNewEmployeeId)
		begin
			INSERT INTO sTimetable.tAssignTeacher
			Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId
		end
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId 
		and SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		
		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId 
		from sAcademic.tTeacherSubjectDivision 
		where SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		AND EmployeeId = @rExistingEmployeeId
		
	END
	
	IF (@rTitle = 'User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)
		IF (@lNewUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
			Insert into sSecurity.tUserOrganization 
			select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId
			AND OrgId NOT in (select OrgId from sSecurity.tUserOrganization WHERE UserId=@lNewUserId)

			INSERT INTO sSecurity.tUserAccess
			SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId
			AND SourceId not in (select SourceId from  sSecurity.tUserAccess WHERE UserId=@lNewUserId)
		END
	END
	
	--IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Time Table')
	--BEGIN

	--	UPDATE sTimetable.tTimeTable 
	--	SET EmployeeId = @rNewEmployeeId 
	--	WHERE EmployeeId = @rExistingEmployeeId 

	--	UPDATE sTimetable.tTeacherWorkLoad 
	--	SET EmployeeId = @rNewEmployeeId WHERE EmployeeId = @rExistingEmployeeId 
	--END

	--IF EXISTS (SELECT 1 from #tmpSplitTable WHERE Id ='Class Teacher')
	--BEGIN
	--	Update sSetup.tDivisionMaster SET InchargeEmployeeId = @rNewEmployeeId where  InchargeEmployeeId = @rExistingEmployeeId
	--END

	--Drop Table #tmpSplitTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeRuleApply]
    @rEmployeeId bigint,
    @rForMonth int,
    @rForYear int,
    @rBatchId int,
	@rOrgId int,
	@rOrgGroupId int,
	@rUserId Bigint
    
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		DECLARE @lIsAbsentAsLWP bit=0,@lIsSandwichRuleApplicable bit=0
		DECLARE @lAbsentAsLWP nvarchar(50),@lSandwichRuleApplicable nvarchar(50)
		Declare @Days int 
		DECLARE @lCount int = 0
		select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		DECLARE @lLeaveTypeId int = 0

		--Configuration
		--Is Absent AS LWP
		SELECT @lAbsentAsLWP = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 258 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
		IF (@lAbsentAsLWP IS NULL) OR (@lAbsentAsLWP = 'False')
		SET @lIsAbsentAsLWP = 0
		ELSE
		SET @lIsAbsentAsLWP = 1

		--Is Sandwich Rule Applicable
		SELECT @lSandwichRuleApplicable = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 304 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
		IF (@lSandwichRuleApplicable IS NULL) OR (@lSandwichRuleApplicable = 'False')
		SET @lIsSandwichRuleApplicable = 0
		ELSE
		SET @lIsSandwichRuleApplicable = 1
		IF(@rEmployeeId!=0 )
		BEGIN	
		

			-- Biometric Employee Configuration
			--Is Absent AS LWP
			DECLARE @lIsAbsentAsLWPEmployeeWise nvarchar(100)
			SELECT @lIsAbsentAsLWPEmployeeWise = Value FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @rEmployeeId AND EmployeeConfigurationMasterId = 1
			IF (@lIsAbsentAsLWPEmployeeWise IS NULL)
			BEGIN					
				SET @lIsAbsentAsLWPEmployeeWise = @lAbsentAsLWP 
			END

			----Is Sandwich Rule Applicable
			DECLARE @lIsSandwichRuleApplicableEmployeeWise nvarchar(100)
			SELECT @lIsSandwichRuleApplicableEmployeeWise = Value FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @rEmployeeId AND EmployeeConfigurationMasterId = 3
			IF (@lIsSandwichRuleApplicableEmployeeWise IS NULL)
			BEGIN					
				SET @lIsSandwichRuleApplicableEmployeeWise = @lSandwichRuleApplicable
			END

			--Is Absent As LWP 
			IF(@lIsAbsentAsLWPEmployeeWise = 'True')
			BEGIN
			DECLARE @lAttendance table(
					AutoId int identity,
					AttendanceDate date
					)
		
					INSERT INTO @lAttendance
					SELECT   
						EAR.AttendanceDate
					FROM 
						[sHrm].[tEmployeeAttendanceRegister] EAR
					WHERE 
						EAR.EmployeeId = @rEmployeeId 
						AND EAR.BatchId = @rBatchId
						AND EAR.IsPresent=0
						AND (MONTH (EAR.AttendanceDate) = @rForMonth AND YEAR (EAR.AttendanceDate) = @rForYear)

				DECLARE @lAttendanceDayCount int
				DECLARE @lAttendanceDate date
			
			
				SELECT @lAttendanceDayCount=COUNT(1) FROM @lAttendance
				WHILE (@lAttendanceDayCount > 0)
				BEGIN
					DECLARE @WeekofDay nvarchar(10)=''
					SELECT @lAttendanceDate=AttendanceDate FROM @lAttendance WHERE AutoId = @lAttendanceDayCount
					SELECT @WeekofDay = [sHrm].[fWeekHOffGet] (@rEmployeeId,year(@lAttendanceDate),MONTH(@lAttendanceDate),day(@lAttendanceDate),@rBatchId,0,@rOrgId)
					SELECT @lLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND IsLWP=1
					IF(@lLeaveTypeId!=0 AND NOT (@WeekofDay= 'W' OR @WeekofDay= 'H')) 
					BEGIN										
					
							EXEC [sHrm].[pLeaveAdd] 0,@rEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,1,@lLeaveTypeId,'LWP Leave',1,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
					
					END
				set @lAttendanceDayCount=@lAttendanceDayCount-1
				END
			END

			--Is Sandwich Rule Applicable
			IF(@lIsSandwichRuleApplicableEmployeeWise = 'True')
			BEGIN
				DECLARE @lLeave table(
					AutoId int identity,
					FromDate date,
					ToDate date
					)
		
					INSERT INTO @lLeave
					SELECT   
						L.FromDate,
						L.ToDate
					FROM 
						sHrm.tLeave L 
					WHERE 
						L.EmployeeId = @rEmployeeId 
						AND L.BatchId = @rBatchId 
						AND L.StatusId != 551
						AND (
							(MONTH (L.FromDate) = @rForMonth AND YEAR (L.FromDate) = @rForYear)
							OR 
							(MONTH (L.ToDate) = @rForMonth AND YEAR (L.ToDate) = @rForYear)
							)
						AND L.LeavePeriodId!=2
						
					DECLARE @lFirstDate date
					DECLARE @lLasteDate date
					SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
					SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
					DECLARE @lDayCount int
					SET @lDayCount = DAY(@lLasteDate)
		
					DECLARE @lWeekOff table(
					AutoId int identity,
					WeekOffDate date
					)

					WHILE (@lDayCount > 0)
					BEGIN
						DECLARE @lWeekHOffStatus nvarchar(10)=''
						SELECT @lWeekHOffStatus = [sHrm].[fWeekHOffGet] (@rEmployeeId,@rForYear,@rForMonth,@lDayCount,@rBatchId,0,@rOrgId)
						IF( @lWeekHOffStatus='W' OR @lWeekHOffStatus= 'H')
						BEGIN
							INSERT INTO @lWeekOff 
							SELECT CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/'+CONVERT(NVARCHAR(2),@lDayCount)))
						END
						SET @lDayCount = @lDayCount - 1
					END
		
				DECLARE @lLeaveCount int=0
				SELECT @lLeaveCount=COUNT(1) FROM @lLeave
				DECLARE @lWeekOffCount int=0
		
				DECLARE @lSandwichDayCount int=0
				SELECT @lLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND IsLWP=1

				WHILE @lLeaveCount > 0 
				BEGIN
					SELECT @lWeekOffCount=COUNT(1) FROM @lWeekOff
					DECLARE @lLeaveFromDate date
					DECLARE @lLeaveToDate date
					SELECT @lLeaveFromDate=FromDate,@lLeaveToDate=ToDate FROM @lLeave WHERE AutoId = @lLeaveCount
					DECLARE @lFromWeekOffDate date
					DECLARE @lToWeekOffDate date
					DECLARE @lMinLeaveFromDate date
					DECLARE @lPlusLeaveToDate date
					DECLARE @lIsSendwichRule bit=0
					declare @lWekofDateMovment int=0 --1 for next, 2 for previous

					SET @lMinLeaveFromDate = DATEADD(day,-1,@lLeaveFromDate)
					SET @lPlusLeaveToDate = DATEADD(day,1,@lLeaveToDate)
					set @lFromWeekOffDate=@lPlusLeaveToDate
					set @lToWeekOffDate= @lMinLeaveFromDate
					

					WHILE @lWeekOffCount > 0 
					BEGIN
						if EXISTS(select 1  FROM @lWeekOff WHERE WeekOffDate = @lPlusLeaveToDate AND (@lWekofDateMovment=0 OR @lWekofDateMovment=1))
						BEGIN
							SELECT @lToWeekOffDate=WeekOffDate FROM @lWeekOff WHERE WeekOffDate = @lPlusLeaveToDate
							set @lPlusLeaveToDate=DATEADD(day,1,@lPlusLeaveToDate)
							set @lWekofDateMovment=1
						END
						if EXISTS(select 1  FROM @lWeekOff WHERE WeekOffDate = @lMinLeaveFromDate AND (@lWekofDateMovment=0 OR @lWekofDateMovment=2))
						BEGIN
							SELECT @lFromWeekOffDate=WeekOffDate FROM @lWeekOff WHERE WeekOffDate = @lMinLeaveFromDate
							set @lMinLeaveFromDate = DATEADD(day,-1,@lMinLeaveFromDate)
							set @lWekofDateMovment=2
						END
						else
						BEGIN
						SET @lWeekOffCount =0
						End
				
						SET @lWeekOffCount = @lWeekOffCount - 1
					END
					if EXISTS(select 1 from @lLeave WHERE FromDate = @lPlusLeaveToDate AND @lWekofDateMovment=1 )
					BEGIN

						set @lIsSendwichRule=1
					END
					if EXISTS(select 1 from @lLeave WHERE ToDate = @lMinLeaveFromDate AND @lWekofDateMovment=2)
					BEGIN
						set @lIsSendwichRule=1
					END
					IF(@lIsSendwichRule=1)
					BEGIN
						declare @lNoOfPeriod decimal(5,2)=0.00
						select @lNoOfPeriod = DATEDIFF(day, @lFromWeekOffDate, @lToWeekOffDate)+1.00
						EXEC [sHrm].[pLeaveAdd] 0,@rEmployeeId,@lToWeekOffDate,@lFromWeekOffDate,@lToWeekOffDate ,1,@lLeaveTypeId,'Sandwich Leave',@lNoOfPeriod,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
					END
					SET @lLeaveCount = @lLeaveCount - 1
				END
			End
		End
	SELECT 1 AS RESULT	
	   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
End

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeStatutoryDetailAdd]

	       @rEmployeeId bigint,
	       @rAccountNumber nvarchar(20),
	       @rBankName nvarchar(200),
           @rBranch nvarchar(50),          
           @rEPFNumber nvarchar(50),
           @rPanNumber nvarchar(20),
           @rIsVPFDeduction bit,
           @rVPFContributionId tinyint,
           @rVPFContributionEffectiveFrom date,
           @rVPFPercentage decimal(5,2),
           @rVPFAmount decimal(22,6),
           @rESINumber nvarchar(20),        
           @rIFSCNumber nvarchar(50),           
           @rIncomeTaxStatusId int,
           @rUpdatedUserId bigint,            
           @rIncrementDate date,
           @rBasicPay decimal(12,2),
           @rPayrollId int,
           @rPayrollGroupId int,
           @rPayscale nvarchar(150)='',
           @rEPFJoinDate date = NULL,
           @rUAN nvarchar(20)='',
           @rRetirementDate date,
		   @rAccountHolderName nvarchar(300)='',
		   @rPayTypeId int = 0
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
	DECLARE @lNextNumber BIGINT 
 	  
IF NOT EXISTS(Select 1 From sHrm.tEmployeeStatutoryAndOther Where EmployeeId = @rEmployeeId)
   BEGIN
	INSERT INTO sHrm.tEmployeeStatutoryAndOther
           (
            [EmployeeId]
           ,[EPFNumber]
           ,[IsVPFDeduction]
           ,[VPFContributionId]
           ,[VPFContributionEffectiveFrom]
           ,[VPFPercentage]
           ,[VPFAmount]
           ,[ESINumber]
           ,[BankName]
           ,[Branch]
           ,[AccountNumber]
           ,[IFSCNumber]
           ,[PanNumber]
           ,[IncomeTaxStatusId]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[IncrementDate]
           ,[BasicPay]
           ,[PayrollId]
           ,[PayrollGroupId]
           ,[Payscale]
           ,[EPFJoinDate]
           ,[UAN]
           ,[RetirementDate]
		   ,[AccountHolderName]
		   ,[PayTypeId]
           )
     VALUES
           (
           @rEmployeeId,
           @rEPFNumber,
           @rIsVPFDeduction,
           @rVPFContributionId,
           @rVPFContributionEffectiveFrom,
           @rVPFPercentage,
           @rVPFAmount,
           @rESINumber,
           @rBankName,
           @rBranch,
           @rAccountNumber,
           @rIFSCNumber,
           @rPanNumber,
           @rIncomeTaxStatusId,
           @rUpdatedUserId,
           sCommon.fGetDate(),
           @rIncrementDate,
           @rBasicPay,
           @rPayrollId,
           @rPayrollGroupId,
           @rPayscale,
           @rEPFJoinDate,
           @rUAN,
           @rRetirementDate,
		   @rAccountHolderName,
		   @rPayTypeId
           )
     END
     ELSE
     BEGIN
      UPDATE sHrm.tEmployeeStatutoryAndOther
      SET 
		  [EPFNumber] = @rEPFNumber,
		  [IsVPFDeduction] = @rIsVPFDeduction, 
		  [VPFContributionId] = @rVPFContributionId, 
		  [VPFContributionEffectiveFrom] = @rVPFContributionEffectiveFrom, 
		  [VPFPercentage] = @rVPFPercentage, 
		  [VPFAmount] = @rVPFAmount, 
		  [ESINumber] = @rESINumber, 
		  [BankName] = @rBankName, 
		  [Branch] = @rBranch, 
		  [AccountNumber] = @rAccountNumber, 
		  [IFSCNumber] = @rIFSCNumber, 
		  [PanNumber] = @rPanNumber, 
		  [IncomeTaxStatusId] = @rIncomeTaxStatusId, 
		  [UpdatedUserId] = @rUpdatedUserId, 
		  [UpdatedDateTime] = sCommon.fGetDate(), 
		  [IncrementDate] = @rIncrementDate, 
		  [BasicPay] = @rBasicPay,
		  [PayrollId]=@rPayrollId,
          [PayrollGroupId]=@rPayrollGroupId,
          [Payscale]=@rPayscale,
          [EPFJoinDate]=@rEPFJoinDate,
          [UAN]=@rUAN,
          [RetirementDate]=@rRetirementDate,
		  [AccountHolderName]=@rAccountHolderName,
		  [PayTypeId]=@rPayTypeId
	  WHERE 
			EmployeeId = @rEmployeeId
     END    
     
	SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeStatutoryDetailBatchWiseGet]
	
	@rOrgId smallint,
	@rEmployeeId bigint = 0,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
		    [EmployeeId]
		  , [EPFNumber]
		  , [IsVPFDeduction]
		  ,ISNULL([VPFContributionId],0) AS VPFContributionId
		  ,ISNULL([VPFContributionEffectiveFrom],'1/1/0001')  AS VPFContributionEffectiveFrom
		  ,ISNULL([VPFPercentage],0) AS VPFPercentage
		  ,ISNULL([VPFAmount],0) AS VPFAmount
		  ,[ESINumber]
		  ,[BankName]
		  ,[Branch]
		  ,[AccountNumber]
		  ,[IFSCNumber]
		  ,[PanNumber]
		  ,ISNULL([IncomeTaxStatusId],0) AS IncomeTaxStatusId       
		  ,ISNULL([IncrementDate],'1/1/0001') AS IncrementDate
		  ,ISNULL([BasicPay],0) AS BasicPay
		  ,ISNULL([PayrollId],0) AS PayrollId
		  ,ISNULL([PayrollGroupId],0) AS PayrollGroupId 
		  ,ISNULL([Payscale],'') AS Payscale
		  ,ISNULL([EPFJoinDate],'1/1/0001') AS EPFJoinDate
		  ,ISNULL(UAN,'') AS UAN
		  ,ISNULL(RetirementDate,'1/1/0001') AS RetirementDate
		  
	FROM 
			[sHrm].[tBatchEmployeeStatutoryAndOther] 
			 
	Where 
			 EmployeeId = @rEmployeeId	  
			 AND BatchId = @rBatchId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeStatutoryDetailGet]
	
	@rOrgId smallint,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
		    [EmployeeId]
		  , [EPFNumber]
		  , [IsVPFDeduction]
		  ,ISNULL([VPFContributionId],0) AS VPFContributionId
		  ,ISNULL([VPFContributionEffectiveFrom],'1/1/0001')  AS VPFContributionEffectiveFrom
		  ,ISNULL([VPFPercentage],0) AS VPFPercentage
		  ,ISNULL([VPFAmount],0) AS VPFAmount
		  ,[ESINumber]
		  ,[BankName]
		  ,[Branch]
		  ,[AccountNumber]
		  ,[IFSCNumber]
		  ,[PanNumber]
		  ,ISNULL([IncomeTaxStatusId],0) AS IncomeTaxStatusId       
		  ,ISNULL([IncrementDate],'1/1/0001') AS IncrementDate
		  ,ISNULL([BasicPay],0) AS BasicPay
		  ,ISNULL([PayrollId],0) AS PayrollId
		  ,ISNULL([PayrollGroupId],0) AS PayrollGroupId 
		  ,ISNULL([Payscale],'') AS Payscale
		  ,ISNULL([EPFJoinDate],'1/1/0001') AS EPFJoinDate
		  ,ISNULL(UAN,'') AS UAN
		  ,ISNULL(RetirementDate,'1/1/0001') AS RetirementDate
		  ,ISNULL([AccountHolderName],'')As AccountHolderName
		  ,ISNULL([PayTypeId],0) AS PayTypeId
		  
	FROM 
			[sHrm].[tEmployeeStatutoryAndOther] 
			 
	Where 
			 EmployeeId = @rEmployeeId	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeStudentDocumentMigrationAdd]
        @rUserSourceId bigint,
		@rUserSourceTypeId smallint,
		@DocumentId int,
		@DocumentName nvarchar(150)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		if(@rUserSourceTypeId=95)
		Begin
		INSERT INTO sHrm.tEmployeeDocument
		(
			EmployeeId, 
			SubmitDocumentMasterId,
			DocumentName,
			IsMigrate
		)
		VALUES   (@rUserSourceId,@DocumentId,@DocumentName,1)  
		END
		if(@rUserSourceTypeId=2003)
		BEGIN
		INSERT INTO sStudent.tStudentDocument
			(
				StudentId, 
				SubmitDocumentMasterId,
				DocumentName,
				IsMigrate
			)
			VALUES   (@rUserSourceId,@DocumentId,@DocumentName,1)   
		END 
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeSummaryDashboardGet]

	@rTypeId int=0,
	@rFilterType nvarchar(50)='',
	@rOrgGroupId smallint=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 

 DECLARE @cols NVARCHAR(MAX),@query  NVARCHAR(MAX),@cols1 NVARCHAR(MAX);
  
------------1
	IF(@rTypeId = 1)
	BEGIN
			SELECT 
				 OGM.Id As OrgGroupId		
				,OGM.Title As OrgGroupName
				--,COUNT(EM.Code) As Total
				,ISNULL((SELECT COUNT(EM.Id) FROM sHrm.tEmployeeMaster EM
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
					INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
					WHERE OGM.Id=OGMM.Id AND ISNULL(EM.IsOtherUser,0) = 0  --AND COGBM.Id=@rCommonOrgGroupBatchId  
					),0) AS Total
				,ISNULL((SELECT COUNT(EM.Id) FROM sHrm.tEmployeeMaster EM
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
					INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
					WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
					and EM.statusid=7 AND ISNULL(EM.IsOtherUser,0) = 0 ),0) AS Active
				
			FROM
				sSetup.tOrgGroupMaster OGM
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			    LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  Group By EM1.Code) AEM ON  EM.Code = AEM.Code
			WHERE OGM.Id != 1 AND OGM.IsObsolete = 0
			Group By OGM.Title,OGM.Id
			Order By OrgGroupName
	END
-------------11 
	ELSE IF(@rTypeId = 11)
	BEGIN
		IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
		 SELECT 
			 OM.Title As Organization
			,COUNT(EM.Code) As Total
			,COUNT(AEM.Code) as Active
		
		FROM 
			sSetup.tOrgGroupMaster OGM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id
       		LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
			 WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  Group By EM1.Code) AEM ON  EM.Code = AEM.Code

		WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0)) AND OGM.IsObsolete = 0
		Group By OM.Title
		Order By Organization
		END

		ELSE IF(@rFilterType = 'Genderwise')--Genderwise
		BEGIN
			 SELECT 
				 OM.Title As Organization
				,COUNT(Male.Code) as Male
				,COUNT(Female.Code) as Female
				,COUNT(EM.Code) as Total
			FROM
				sSetup.tOrgGroupMaster OGM
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 1 Group By EM1.Code) Male ON  EM.Code = Male.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 2 Group By EM1.Code) Female ON  EM.Code = Female.Code
			WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0)) AND OGM.IsObsolete = 0
			Group By OM.Title
			Order By Organization
		END

		ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
		BEGIN
			 SELECT 
				OM.Title As Organization
				,COUNT(T1.Code) as Teaching
				,COUNT(T2.Code) as NonTeaching

			FROM 
				sSetup.tOrgGroupMaster OGM
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 

				LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=1 Group By EM1.Code) T1 ON  EM.Code = T1.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=2 Group By EM1.Code) T2 ON  EM.Code = T2.Code
				 
			WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))AND OGM.IsObsolete = 0
			Group By OM.Title
			Order By Organization
		END

		ELSE IF(@rFilterType = 'EmployeeTypewise')--EmployeeTypewise
		BEGIN
			 SELECT 
					 OM.Title As Organization,
					 ETM.Title As EmployeeType,
					 COUNT(EJD.EmployeeId) AS Total
				FROM 
					sSetup.tOrgGroupMaster OGM
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
					LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.OrgId = OM.Id
					 LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeTypeId = ETM.Id
					
				WHERE 
					((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))AND OGM.IsObsolete = 0
				Group By ETM.Title,OM.Title
		END
	END
------------------21
	ELSE IF(@rTypeId = 21)
		BEGIN
			IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
			BEGIN
  				SELECT 
					 OGD.Title As OrganizationDepartment
					,COUNT(EJD.EmployeeId) As Total
					,COUNT(AEM.Code) as Active
		
				FROM 
					sCommon.tOrgGroupDepartmentMaster OGD
					LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.OrgGroupDepartmentId = OGD.Id
					LEFT JOIN (SELECT EM1.Code As Code,EM1.Id FROM sHrm.tEmployeeMaster EM1 
					 WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  Group By EM1.Code,EM1.Id) AEM ON  EJD.EmployeeId = AEM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EJD.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))AND OGM.IsObsolete = 0
				Group By OGD.Title
				Order By OrganizationDepartment
			END

			ELSE IF(@rFilterType = 'Genderwise')---Genderwise
			BEGIN
				SELECT
					 OGD.Title As OrganizationDepartment
					,COUNT(Male.Code) as Male
					,COUNT(Female.Code) as Female
					,COUNT(EM.Code) as Total
				FROM sCommon.tOrgGroupDepartmentMaster OGD
					LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.OrgGroupDepartmentId = OGD.Id
					LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId AND ISNULL(EM.IsOtherUser,0) = 0 
					LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
						INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
						WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 1 Group By EM1.Code) Male ON  EM.Code = Male.Code
					LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
						INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
						WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 2 Group By EM1.Code) Female ON  EM.Code = Female.Code
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0)) AND EM.StatusId = 7 AND OGM.IsObsolete = 0
				Group By OGD.Title
				Order By OrganizationDepartment
			END

			ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
			BEGIN
				SELECT
		    			OGD.Title As OrganizationDepartment
						,COUNT(T1.Code) as Teaching
						,COUNT(T2.Code) as NonTeaching

					FROM sCommon.tOrgGroupDepartmentMaster OGD
					LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.OrgGroupDepartmentId = OGD.Id
					LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId AND ISNULL(EM.IsOtherUser,0) = 0 
						LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
							INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
							INNER JOIN sCommon.tOrgGroupDepartmentMaster OGD ON OGD.Id = EJD.OrgGroupDepartmentId
							WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=1 Group By EM1.Code) T1 ON  EM.Code = T1.Code
						LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
							INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
							INNER JOIN sCommon.tOrgGroupDepartmentMaster OGD ON OGD.Id = EJD.OrgGroupDepartmentId
							WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=2 Group By EM1.Code) T2 ON  EM.Code = T2.Code
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						INNER JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EJD.EmployeeGroupId
					WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0)) AND EM.StatusId = 7
						 AND OGM.IsObsolete = 0  AND OGD.IsObsolete = 0
					Group By OGD.Title
					Order By OrganizationDepartment
			END

			ELSE IF(@rFilterType = 'EmployeeTypewise')--EmployeeTypewise
			BEGIN
				 	SELECT 
					 OGD.Title As OrganizationDepartment,
					 ETM.Title As EmployeeType,
					 COUNT(EJD.EmployeeId) AS Total
				FROM 
					sCommon.tOrgGroupDepartmentMaster OGD
					LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.OrgGroupDepartmentId = OGD.Id
					LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId AND ISNULL(EM.IsOtherUser,0) = 0 
					LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON EJD.EmployeeTypeId = ETM.Id
					 LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = ETM.OrgId
					 LEFT JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId 
				WHERE 
					((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0)) AND OGD.IsObsolete = 0
				Group By ETM.Title,OGD.Title
			END
		END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeTravelAdd]
        @rOrgId int,
        @rId bigint,
        @rEmployeeId bigint,
        @rReportDate date,
        @rTravelFromDate date,
        @rTravelToDate date,
        @rTravelPeriodId tinyint,       
        @rTravelReason nvarchar(200),
        @rTravelRemark nvarchar(200),
        @rNoOfDays decimal(5,2),
        @rFromTime datetime=null,
		@rToTime datetime=null,
        @rBatchId int,
       
        @rCreatedUserId bigint,
        @rStatusId int,
		@rStatusReason nvarchar(100) = ''
       
AS
SET NOCOUNT ON

BEGIN


      DECLARE @1Days int
	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint
	 
    IF (@rId = 0)
     BEGIN
       
       IF(@rTravelPeriodId = 2) --For Half Leave	  	
       SELECT @1Days = SUM(NoOfDays) from sHrm.tEmployeeTravel where EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND TravelFromDate = @rTravelFromDate
       ELSE
         SET @1Days = 1
     		
	   IF NOT EXISTS(SELECT 1 FROM sHrm.tEmployeeTravel WHERE EmployeeId = @rEmployeeId 
	   AND(( TravelFromDate  BETWEEN @rTravelFromDate AND @rTravelToDate) OR (TravelToDate BETWEEN @rTravelFromDate AND @rTravelToDate)
	   OR (@rTravelFromDate  BETWEEN TravelFromDate AND TravelToDate) OR (@rTravelToDate BETWEEN TravelFromDate AND TravelToDate)) AND OrgId = @rOrgId AND BatchId = @rBatchId AND StatusId!=643)OR @1Days != 1 
	   BEGIN
	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeTravel', 0, 1, 1,@outNextNumber = @lNextNumber output	
	    
		  INSERT INTO sHrm.tEmployeeTravel
           (
            [Id]
           ,[EmployeeId]
           ,[ReportDate]
           ,TravelFromDate
           ,TravelToDate
           ,TravelPeriodId       
           ,TravelReason
           ,TravelRemark
           ,NoOfDays
            ,[FromTime]
           ,[ToTime]
           ,[OrgId] 
            ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime] 
           ,BatchId                              
           ,[StatusId]
		   ,StatusReason
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId 
           ,@rReportDate 
           ,@rTravelFromDate
           ,@rTravelToDate 
           ,@rTravelPeriodId          
           ,@rTravelReason 
           ,@rTravelRemark
           ,@rNoOfDays
           ,@rFromTime
           ,@rToTime  
           ,@rOrgId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rBatchId                      
           ,@rStatusId       
           ,@rStatusReason
           )
            SELECT 1 AS Result
            END
          ELSE
            SET @lNextNumber = -101            
          END
	ELSE
	BEGIN
	SET @lNextNumber = @rId
		UPDATE sHrm.tEmployeeTravel
		SET 	 
		   [EmployeeId]= @rEmployeeId 
		  ,[ReportDate]= @rReportDate 
		  ,[TravelFromDate]= @rTravelFromDate
		  ,TravelToDate= @rTravelToDate
		  ,[TravelPeriodId]= @rTravelPeriodId
		 
		  ,TravelReason= @rTravelReason
		  ,TravelRemark=@rTravelRemark
		  ,NoOfDays = @rNoOfDays
		  ,[OrgId]= @rOrgId        
		  ,[UpdatedUserId]= @rCreatedUserId
		  ,[UpdatedDateTime]= sCommon.fGetDate()
		  ,[FromTime] = @rFromTime
          ,[ToTime] = @rToTime
		  ,StatusReason = @rStatusReason    
		WHERE Id = @rId
		 SELECT 11 AS Result
	 END 
	   SELECT @lNextNumber AS Result	   
	   COMMIT TRANSACTION
	   		
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeTravelGet]
(
	@rOrgId int,
    @rId bigint = 0,
    @rEmployeeId  bigint,   
    @rFromDate date,
    
    @rTodate date,
    @rBatchId int,
    @rEmployeeCode nvarchar(100),
    @rEmployeeName nvarchar(100) ,
    @rStatusId int=0
 )
AS
SET NOCOUNT ON

BEGIN
    
	SELECT 
		   E.[Id] AS TravelId
		  ,E.[EmployeeId]
		  ,[ReportDate]
		  ,TravelFromDate
		  ,TravelToDate
		  ,TravelPeriodId		  
		  ,TravelReason
		  ,TravelRemark
		  ,TPM.Title AS TravelPeriod
		 ,StatusReason
		  ,EM.EmployeeName
		  ,EM.Code AS EmployeeCode
		  ,ISNULL(E.StatusId,0) AS StatusId
		  ,ISNULL(SM.Title,'Pending') AS StatusName
		  ,E.NoOfDays    
		  ,ISNULL(E.FromTime,'') AS FromTime
          ,ISNULL(E.ToTime,'') AS ToTime
		  --,(ISNULL((Select NoOfLeave FROM sHrm.tLeaveTypeGradeSettings LGS WHERE LGS.EmployeeGradeId = EM.EmployeeGradeId AND LGS.LeaveTypeId = L.LeaveTypeId),0) - L.NoOfLeave) AS AvailableLeave
      
  FROM 
			sHrm.tEmployeeTravel E
	  INNER JOIN sHrm.tTravelPeriodMaster TPM ON TPM.Id = E.TravelPeriodId
	  
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = E.EmployeeId 
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = E.StatusId
	  --INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.EmployeeGradeId = EM.EmployeeGradeId AND LTGS.LeaveTypeId = L.LeaveTypeId 
  WHERE 
		  (E.Id = @rId OR @rId = 0)
      AND (E.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((E.TravelFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((E.TravelFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
       
      AND BatchId = @rBatchId AND E.OrgId = @rOrgId 
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (E.StatusId = @rStatusId OR @rStatusId = 0)
      Order By [ReportDate] DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeTravelListingGet]
(
	@rOrgId int,
    @rId bigint = 0,
    @rEmployeeId  bigint,   
    @rTravelFromDate date,
  
    @rTravelToDate date,
    @rOrgGroupBatchId int,
    @rEmployeeCode nvarchar(100)='',
    @rEmployeeName nvarchar(100)='',
    @rStatusId int = 0 
 )
AS
SET NOCOUNT ON

BEGIN
    
	SELECT 
		   T.[Id] AS TravelId
		  ,T.[EmployeeId]
		  ,T.[ReportDate]
		  ,T.TravelFromDate
		  ,T.TravelToDate
		  ,T.TravelPeriodId
		 ,T.TravelRemark
		  ,T.TravelReason
		  ,T.StatusReason
		  ,TPM.Title AS TravelPeriod
		 
		  ,EM.EmployeeName
		  ,EM.Code AS EmployeeCode
		  ,T.NoOfDays
		  ,ISNULL(T.StatusId,0) AS StatusId
		  ,ISNULL(SM.Title,'Pending') AS StatusName
		  --,ISNULL(T.LeaveRemark,'') AS  TravelRemark
		  ,OM.DisplayTitle AS OrganizationName
      
  FROM 
		 sHrm.tEmployeeTravel T
	  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = T.BatchId		
	  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
	  INNER JOIN sHrm.tTravelPeriodMaster TPM ON TPM.Id = T.TravelPeriodId
	
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = T.EmployeeId
	  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = T.EmployeeId
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = T.StatusId
  WHERE 
		  (T.Id = @rId OR @rId = 0)
      AND (EJD.EmployeeManagerId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((T.TravelFromDate >= @rTravelFromDate) OR (ISNULL(@rTravelFromDate,'') = ''))
      AND ((T.TravelFromDate <= @rTravelToDate) OR (ISNULL(@rTravelToDate,'') = ''))
        
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId
      AND ((T.OrgId = @rOrgId) OR (@rOrgId = 0))
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (T.StatusId = @rStatusId OR @rStatusId = 0)  
      Order By [ReportDate] DESC    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeTravelModify]
           
        @rId bigint,
        @rEmployeeId bigint,
      
        @rOrgId smallint,
        @rStatusId int,
        @rStatusReason nvarchar(100)
        --@rLeaveRemark nvarchar(200) 
        
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

	BEGIN
		UPDATE sHrm.tEmployeeTravel
		SET 	 
		  [StatusId]=@rStatusId,
		  StatusReason=@rStatusReason
                            
		WHERE EmployeeId = @rEmployeeId AND Id=@rId
	 END 
	   SELECT @rEmployeeId AS Result	   
	   COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeUploadedDocumentListGet]
	 
	 @rSourceId bigint,
	 @rOrgId int = 0,
	 --@rDivisionId int = 0,
	 --@rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	--IF (@rSourceId!=0)
	--BEGIN
	--	SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
	--	 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	--END


	SELECT @rSourceId AS SourceId,
			EDU.Id,
			EDU.Title,
			EDTM.Title AS DocumentType,
			EM.Code,
			EDU.DocumentUploadDate,
			EM.OrgId	  
	  FROM [sCommunication].[tEmployeeDocumentUpload] EDU
	  JOIN sCommunication.tEmployeeDocumentTypeMaster EDTM ON EDTM.Id=EDU.EmployeeDocumentTypeId
	  JOIN sHrm.tEmployeeMaster EM ON EM.OrgId=EDU.OrgId
  
	  WHERE EDU.IsObsolete=0 AND EM.Id = @rSourceId
			AND EM.OrgId=@rOrgId 
			AND ( EDU.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
			AND EDU.DocumentUploadDate <= REPLACE(CONVERT(VARCHAR, sCommon.fGetDate(), 111), '/','-') 
	ORDER BY EDU.DocumentUploadDate,EM.Code DESC

--		SELECT 
--			@rSourceId AS SourceId,
--			SDU.Id,
--			SDU.Title,
--			SDTM.Title AS DocumentType,
--			S.Code,
--			SDU.DocumentUploadDate,
--			 BM.OrgId
--		FROM 
--			sCommunication.tStudentDocumentUpload SDU  
--			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = SDU.DivisionId AND SDU.BatchId = S.BatchId 
--			AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
--			INNER JOIN sCommunication.tStudentDocumentTypeMaster SDTM ON SDTM.Id = SDU.StudentDocumentTypeId
--			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
--		WHERE 
--			SDU.DivisionId=@rDivisionId
--			AND SDU.BatchId=@rBatchId
--			AND SDU.IsObsolete=0
--			AND ( SDU.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
--			and SDU.DocumentUploadDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
--				order by SDU.DocumentUploadDate,S.RollNo,S.Code DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeWiseAttendanceGet]
	 
	@rForYear  bigint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int,
	@rDepartmentId int=0,
	@rEmployeeId bigint = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))

	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	
BEGIN 
	SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeName,
		EM.EmployeeId,
		ISNULL(EM.EmployeeGrade,'') AS EmployeeGrade,
		--ISNULL(WD.TotalDays,0) AS TotalDays,
		CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
			ELSE ISNULL(EWD.TotalDays,@lMonthDay)

		END AS TotalDays,

		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) + 1 
		--	ELSE ISNULL(WD.TotalDays,0) 
		--END AS TotalDays,
		--ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
		
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
		--	WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
		--	THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
		--	ELSE ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) 
		--END AS WorkingDays,
		(CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
			ELSE ISNULL(AT.TotalWorkingDays,ISNULL(EWD.WorkingDays,@lMonthDay))		--add AT.TotalWorkingDays for 29619 Mantis Id

		END ) AS WorkingDays,
		
		(ISNULL(AT.TotalWorkingDays,0) - ((ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)))) AS PresentDays,
		
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) + (1) 
		--	ELSE (ISNULL(AT.TotalWorkingDays,0) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0))) 
		--END AS PresentDays,
		
		(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS PayrollDays,
		
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) - ISNULL(AT.LWP,0) + (1)
		--	ELSE (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) 
		--END AS PayrollDays,
		
		(ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) AS LWP,   -- Absent Days
		ISNULL(AT.PaidLeave,0) AS PaidLeave,
		ISNULL(AT.LWP,0) AS UnPaidLeave,
		ISNULL(AT.LateCount,0) AS LateCount,
		ISNULL(AT.LateDeductionDays,0) AS LateDeductionDays,
		ISNULL(AT.SandwichDeductionDays,0) AS SandwichDeductionDays,
		ISNULL(CONVERT(VARCHAR(50),EM.DateOfJoining,103),'') AS DateOfJoining,
		ISNULL(CONVERT(VARCHAR(50),EM.DateOfLeaving,103),'') AS DateOfLeaving
		
	FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		--INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		--AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id =  EJD.EmployeeGradeId
		INNER JOIN sHrm.tEmployeeWorkingDays EWD ON EWD.EmployeeId=EM.EmployeeId	--make a inner join insted of left join for 29619 Mantis Id
		AND EWD.BatchId=@rBatchId 
		AND EWD.ForYear=@rForYear
		AND EWD.ForMonth =@rForMonth 
		LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId		 
		AND AT.ForMonth=@rForMonth AND AT.ForYear=@rForYear AND AT.BatchId = @rBatchId
	WHERE 
		EM.OrgID = @rOrgId 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
		AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (EM.IsOtherUser = 0)
		AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	ORDER BY 
		EM.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeWorkingDaysAdd]
	      
	       @rForMonth tinyint,
           @rForYear smallint,  
           @rTotalDays tinyint,
           @rWorkingDay tinyint,
           @rVacationDays tinyint,
           @rSundays tinyint,
           @rHoliDays tinyint,
           @rBatchId int, 
           @rEmployeeId bigint
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
		
   DELETE FROM sHrm.tEmployeeWorkingDays Where ForMonth = @rForMonth AND ForYear = @rForYear AND BatchId = @rBatchId AND EmployeeId = @rEmployeeId
 
   INSERT INTO sHrm.tEmployeeWorkingDays
		(  
			[ForMonth]
           ,[ForYear]
           ,[TotalDays]
           ,[WorkingDays]
           ,[VacationDays]
           ,[WeekOffs]
           ,[HoliDays]
           ,[BatchId]
           ,[EmployeeId]
        )
     VALUES
        (
           @rForMonth,
           @rForYear,  
           @rTotalDays,
           @rWorkingDay,
           @rVacationDays,
           @rSundays,
           @rHoliDays,
           @rBatchId, 
           @rEmployeeId
        )
	SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH						
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeWorkingDaysListGet]
	 
	@rForYear smallint,
	@rForMonth smallint,
	@rEmployeeId  bigint,	 
	@rEmployeeGradeId  int,	 
	@rBatchId int,
	@rOrgId nvarchar(max) = ''  
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)

	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	
	
	
	SELECT
		EM.Id AS EmployeeId,
		EM.Code,
		EM.FirstName +' '+ EM.LastName AS Name,
		EGM.Title AS EmployeeGradeTitle,


		CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
			ELSE ISNULL(EWD.TotalDays,@lMonthDay)

		END AS TotalDays,

		--ISNULL(EWD.TotalDays,@lMonthDay) AS TotalDays,

--		ISNULL(EWD.WorkingDays,@lMonthDay) AS WorkingDay,
		(CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
			ELSE ISNULL(EWD.WorkingDays,@lMonthDay)

		END )AS WorkingDay,


		ISNULL(EWD.VacationDays,0) AS VacationDays,
		ISNULL(EWD.WeekOffs,0) AS WeekOffs,
		ISNULL(EWD.Holidays,0)AS HoliDays,
		EJD.OrganizationDepartmentId AS DepartmentId
		--AS HoliDays
		
	FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId= EM.Id
		INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id =  EJD.EmployeeGradeId
		LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON EWD.EmployeeId=EM.Id 
		AND EWD.BatchId=@rBatchId 
		AND EWD.ForYear=@rForYear
		AND EWD.ForMonth =@rForMonth 
	WHERE
		EM.StatusId=7  AND ISNULL(EM.IsOtherUser,0) = 0 
		AND (EM.Id = @rEmployeeId OR @rEmployeeId=0)
		AND (EJD.EmployeeGradeId = @rEmployeeGradeId OR @rEmployeeGradeId=0)
		AND ((EJD.DateOfleaving >= @lFirstDate) OR ISNULL(EJD.DateOfleaving,'') = '')
		AND ((EJD.DateOfJoining <= @lLasteDate) OR ISNULL(EJD.DateOfJoining,'') = '')
		AND EM.OrgId=@rOrgId
		AND EM.IsOtherUser = 0
	Order By EM.Number	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmploymentCertificateAdd]
			@rId bigint
	       ,@rEmployeeId bigint
	       ,@rNumber int
	       ,@rCertificateDate date
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
	       ,@rRemark nvarchar(200)
	       ,@rDesignationId int
	       ,@rCertificateReason nvarchar(200)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	 
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sHrm.tCertificateEmployment WHERE OrgId=@rOrgId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sHrm.tCertificateEmployment WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END

	  DECLARE @lNextNumber BIGINT
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCertificateEmployment', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sHrm.tCertificateEmployment
				(
					Id
				   ,EmployeeId
				   ,Number
				   ,CertificateDate
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime,
				   Remark,
				   EmployeeDesignationId,
				   CertificateReason
				)
				VALUES
				(	@lNextNumber
				   ,@rEmployeeId
				   ,@rNumber
				   ,@rCertificateDate
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate()
				   ,@rRemark
				   ,@rDesignationId
				   ,@rCertificateReason
				)
		END
		
		ELSE
		
		BEGIN
			SET @lNextNumber = @rId
				UPDATE  sHrm.tCertificateEmployment
				SET
					EmployeeId=@rEmployeeId,
					CertificateDate=@rCertificateDate,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					Remark=@rRemark,
					EmployeeDesignationId=@rDesignationId,
					CertificateReason=@rCertificateReason
					
				WHERE Id = @rId
		 END  	
		
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pEmploymentCertificateGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	-- @rBatchId int,
	 @rIsSearch bit = 1,
	 @rEmployeeId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			EC.Id,
			EC.EmployeeId,
			SA.FirstName+' '+SA.LastName as Name,
			EC.Number,
			EC.CertificateDate ,
			EC.Remark,
			isnull(EC.EmployeeDesignationId,0) AS EmployeeDesignationId ,
			EC.CertificateReason,
			--SA.EmployeeDesignationId As DesignationId,
			SA.Designation As Designation,
			SA.Code
		
			
  FROM 
            sHrm.tCertificateEmployment EC
       INNER JOIN sHrm.vExtEmployeeMaster SA ON SA.EmployeeId=EC.EmployeeId AND SA.OrgId=@rOrgId 
  WHERE 
  
	((EC.Id = @rId) OR (@rId = 0))
	AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((SA.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))
	AND ((EC.Number >= @rFromNo) OR (@rFromNo=0))
	AND ((EC.Number <= @rToNo) OR (@rToNo=0))
	AND ((EC.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((EC.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--AND (SA.ClassId = @rClassId OR @rClassId = 0)
	--AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
	ORDER BY EC.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pExperienceCertificateAdd]
			@rId bigint
	       ,@rEmployeeId bigint
	       ,@rNumber int
	       ,@rCertificateDate date
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
	       ,@rRemark nvarchar(50)
	       ,@rDesignationId int
	       ,@rCertificateReason nvarchar(200)
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	 
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sHrm.tCertificateExperience WHERE OrgId=@rOrgId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sHrm.tCertificateExperience WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END

	  DECLARE @lNextNumber BIGINT
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCertificateExperience', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sHrm.tCertificateExperience
				(
					Id
				   ,EmployeeId
				   ,Number
				   ,CertificateDate
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime,
				   Remark,
				   EmployeeDesignationId,
				   CertificateReason
				)
				VALUES
				(	@lNextNumber
				   ,@rEmployeeId
				   ,@rNumber
				   ,@rCertificateDate
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate()
				   ,@rRemark
				   ,@rDesignationId
				   ,@rCertificateReason
				)
		END
		
		ELSE
		
		BEGIN
			SET @lNextNumber = @rId
				UPDATE  sHrm.tCertificateExperience
				SET
					EmployeeId=@rEmployeeId,
					CertificateDate=@rCertificateDate,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					Remark=@rRemark,
					EmployeeDesignationId=@rDesignationId,
					CertificateReason=@rCertificateReason
					
				WHERE Id = @rId
		 END  	
		
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pExperienceCertificateGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	-- @rBatchId int,
	 @rIsSearch bit = 1,
	@rEmployeeId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			EC.Id,
			EC.EmployeeId,
			SA.FirstName+' '+SA.LastName as Name,
			EC.Number,
			EC.CertificateDate ,
			EC.Remark,
			isnull(EC.EmployeeDesignationId,0) AS EmployeeDesignationId ,
			EC.CertificateReason,
			SA.Designation As Designation,
			SA.Code
		
			
  FROM 
            sHrm.tCertificateExperience EC
       INNER JOIN sHrm.vExtEmployeeMaster SA ON SA.EmployeeId=EC.EmployeeId AND SA.OrgId=@rOrgId 
  WHERE 
  
	((EC.Id = @rId) OR (@rId = 0))
	AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((SA.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))
	AND ((EC.Number >= @rFromNo) OR (@rFromNo=0))
	AND ((EC.Number <= @rToNo) OR (@rToNo=0))
	AND ((EC.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((EC.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	ORDER BY EC.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pExportLeave] 
	@rFromBatchId INT
	,@rToBatchId INT
	,@rOrgId INT
	,@rIsDelete BIT
	,@rUserId BIGINT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		IF (@rIsDelete = 1)
		BEGIN
			DELETE
			FROM sHrm.tLeaveBalance
			WHERE BatchId = @rToBatchId

			SELECT 101 AS RESULT

			RETURN
		END

		IF EXISTS (
				SELECT 1
				FROM sHrm.tLeaveBalance
				WHERE BatchId = @rToBatchId
				)
		BEGIN
			SELECT - 101 AS RESULT

			RETURN
		END

		BEGIN TRANSACTION

		DECLARE @lCount INT

		-- Leave Balance Temp Table
		CREATE TABLE #TempLeaveBalance (
			[AutoId] INT IDENTITY
			,[EmployeeId] BIGINT NOT NULL
			,[LeaveTypeId] INT NOT NULL
			,[BatchId] INT NOT NULL
			,[PendingNoOfLeave] DECIMAL(5, 2) NOT NULL
			,[MaximumCarryForward] INT NOT NULL
			,[OldSettingNoOfLeave] INT NOT NULL
			,[NewSettingNoOfLeave] INT NOT NULL
			,[EmployeeNoOfLeave] DECIMAL(5, 2) NOT NULL
			,[MaxInMonth] DECIMAL(5, 2) NULL
			)

		-- End Create Table
		INSERT INTO #TempLeaveBalance
		SELECT EM.Id
			,
			--EM.Code,
			--EM.FirstName +' '+EM.LastName,
			ISNULL(B.LeaveTypeId, 0)
			,@rToBatchId
			,(
				CASE 
					WHEN (ISNULL(LB.BalanceLeave, 0) - ISNULL(A.NoOfLeave, 0)) > 0
						THEN ISNULL(LB.BalanceLeave, 0) - ISNULL(A.NoOfLeave, 0)
					ELSE 0
					END
				) AS NoOfLeave
			,ISNULL(B.MaximumCarryForward, 0)
			,ISNULL(LB.BalanceLeave, 0)
			,ISNULL(B.NoOfLeave, 0)
			,ISNULL(A.NoOfLeave, 0)
			,ISNULL(LB.MaxInMonth, 0)
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId AND StatusId = 7 AND ISNULL(EM.IsOtherUser, 0) = 0
		-- Changes join sequence for mantis 0035174,0038454 by Foram
		LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = EM.Id 
		LEFT JOIN (
			SELECT LeaveTypeId
				,EmployeeGradeId
				,NoOfLeave
				,LTM.MaximumCarryForward
			FROM sHrm.tLeaveTypeGradeSettings LTGS
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LTGS.LeaveTypeId
			WHERE LTGS.OrgId = @rOrgId
				AND LTM.IsCarryForward = 1
		) B ON B.EmployeeGradeId = EJD.EmployeeGradeId AND B.LeaveTypeId = LB.LeaveTypeId
		LEFT JOIN (
			SELECT L.EmployeeId
				,L.LeaveTypeId
				,SUM(L.NoOfLeave) AS NoOfLeave
				,LTM.MaximumCarryForward
			FROM sHrm.tLeave L
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON L.LeaveTypeId = LTM.Id
				AND IsCarryForward = 1
				AND IsLWP = 0
				AND StatusId = 550
			WHERE L.BatchId = @rFromBatchId
				AND L.OrgId = @rOrgId
				AND LTM.IsCarryForward = 1
			GROUP BY L.EmployeeId
				,L.LeaveTypeId
				,LTM.MaximumCarryForward
		) A ON A.EmployeeId = EM.Id AND B.LeaveTypeId = A.LeaveTypeId AND B.LeaveTypeId = LB.LeaveTypeId
		WHERE EM.OrgID = @rOrgId
			AND LB.BatchId = @rFromBatchId
			AND ISNULL(B.LeaveTypeId,0) > 0
		--SELECT * FROM #TempLeaveBalance

		SELECT @lCount = COUNT(EmployeeId)
		FROM #TempLeaveBalance

		DECLARE @lBatchName NVARCHAR(100)

		SELECT @lBatchName = Title
		FROM sSetup.tBatchMaster
		WHERE Id = @rFromBatchId

		WHILE (@lCount > 0)
		BEGIN
			-- Leave Balance Entry
			INSERT INTO sHrm.tLeaveBalance (
				EmployeeId
				,LeaveTypeId
				,BalanceLeave
				,BatchId
				,LastYearBalanceLeave
				,CurrentBalanceLeave
				)
			SELECT EmployeeId
				,LeaveTypeId
				,(
					CASE 
						WHEN (PendingNoOfLeave >= MaximumCarryForward)
							THEN NewSettingNoOfLeave + MaximumCarryForward
						WHEN (PendingNoOfLeave <= MaximumCarryForward)
							THEN NewSettingNoOfLeave + PendingNoOfLeave
						ELSE NewSettingNoOfLeave
						END
					) AS NoOfLeave
				,BatchId
				,
				--MaxInMonth,
				(
					CASE 
						WHEN (PendingNoOfLeave >= MaximumCarryForward)
							THEN MaximumCarryForward
						ELSE PendingNoOfLeave
						END
					) AS LastYearLeave
				,NewSettingNoOfLeave AS CurrentYearLeave
			FROM #TempLeaveBalance
			WHERE AutoId = @lCount

			-- Add Leave Balance Log
			INSERT INTO sHrm.tLeaveBalanceLog
			SELECT EmployeeId
				,LeaveTypeId
				,NewSettingNoOfLeave
				,1
				,CASE 
					WHEN (PendingNoOfLeave >= MaximumCarryForward)
						THEN MaximumCarryForward
					WHEN (PendingNoOfLeave <= MaximumCarryForward)
						THEN PendingNoOfLeave
					ELSE 0
					END AS TransactionLeave
				,'Carry Forward leave from (' + @lBatchName + ')'
				,BatchId
				,@rUserId
				,sCommon.fGetDate()
			FROM #TempLeaveBalance
			WHERE AutoId = @lCount

			-- END Leave Balance Entry
			SET @lCount = @lCount - 1
		END

		DROP TABLE #TempLeaveBalance

		SELECT 1 AS Result

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		DROP TABLE #TempLeaveBalance

		ROLLBACK TRANSACTION

		SELECT - 1 AS Result, ERROR_MESSAGE() as error
	END CATCH
END
	-- Change History 
	/* 

Change Date : 19/03/2020
Changes by : Jash Gandhi

Change Discription :
	Added 2 fields in INSERT INTO sHrm.tLeaveBalance Query :- 
	Pending Leave from temporary table(#TempLeaveBalance) will go to LastYearBalanceLeave column and NewSettingNoOfLeave will go into CurrentYearBalanceLeave column
*/

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[PFee]
	 @rOrgGroupId int=0,
	 @configration int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

  BEGIN
	SELECT 
	 Top 1 1001 as 'CollectionGroup',1500 as 'PendingAmount',10 as 'PendingCount'
	FROM 
		sStudent.vStudentAllDetail S
			
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pGeneralEmployeeModelGet]
	  @rEmployeeId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		 Em.Id,
		 Em.FirstName + ' ' + EM.LastName AS FullName,
		 Gm.Title As Gender,
		 EC.CompanyEmail AS Email, 
		 EC.MobileNumber
  FROM 
		  sHrm.tEmployeeMaster EM 
		  INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id AND ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sCommon.tGenderMaster Gm ON GM.Id = EPD.Genderid
		  INNER JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId= EM.Id
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pGetCheckBoxLists]
@rFlag int,
@rOrgId int,
@rOrgGroupId int
as
begin
	declare @lResult varchar(max)=''

	if @rFlag = 0
	begin
		declare @ddlStatusMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlReligionMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlMaritalStatusMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlGenderMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlEmployeeDesignationMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlEmployeeTypeMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlEmployeeGroupMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlBloodGroupMaster varchar(max)='<option value="0">-- ALL --</option>'
		declare @ddlDepartmentMaster varchar(max)='<option value="0">-- ALL --</option>'	
		declare @ddlEmployeeGradeMaster varchar(max)='<option value="0">-- ALL --</option>'

		select @ddlStatusMaster = @ddlStatusMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sCommon.tStatusMaster where StatusTypeId = 4
		select @ddlReligionMaster = @ddlReligionMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sCommon.tReligionMaster where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId									  
		select @ddlMaritalStatusMaster = @ddlMaritalStatusMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sCommon.tMaritalStatusMaster where IsObsolete = 0															   
		select @ddlGenderMaster = @ddlGenderMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sCommon.tGenderMaster where IsObsolete = 0																	  
		select @ddlEmployeeDesignationMaster = @ddlEmployeeDesignationMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sHrm.tEmployeeDesignationMaster where IsObsolete = 0 AND OrgId = @rOrgId									   
		select @ddlEmployeeTypeMaster = @ddlEmployeeTypeMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sHrm.tEmployeeTypeMaster where IsObsolete = 0 AND OrgId = @rOrgId											  
		select @ddlEmployeeGroupMaster = @ddlEmployeeGroupMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sHrm.tEmployeeGroupMaster WHERE IsObsolete = 0																   
		select @ddlBloodGroupMaster = @ddlBloodGroupMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sCommon.tBloodGroupMaster where IsObsolete = 0															   
		select @ddlDepartmentMaster = @ddlDepartmentMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sSetup.tDepartmentMaster where IsObsolete = 0 AND OrgId = @rOrgId											   
		select @ddlEmployeeGradeMaster = @ddlEmployeeGradeMaster + '<option value="' + convert(varchar,Id) +'">' + Title + '</option>'
		from sHrm.tEmployeeGradeMaster where IsObsolete = 0 AND OrgId = @rOrgId
		select @ddlStatusMaster as StatusMaster,@ddlReligionMaster as ReligionMaster,@ddlMaritalStatusMaster as MaritalStatusMaster,@ddlGenderMaster as GenderMaster,
		@ddlEmployeeDesignationMaster as EmployeeDesignationMaster,@ddlEmployeeTypeMaster as EmployeeTypeMaster,@ddlEmployeeGroupMaster as EmployeeGroupMaster,
		@ddlBloodGroupMaster as BloodGroupMaster,@ddlDepartmentMaster as DepartmentMaster,@ddlEmployeeGradeMaster as EmployeeGradeMaster
	end
	else if @rFlag = 1
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tStatusMaster where StatusTypeId = 4
	end
	else if @rFlag = 2
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tReligionMaster where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId
	end
	else if @rFlag = 3
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tMaritalStatusMaster where IsObsolete = 0
	end
	else if @rFlag = 4
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tGenderMaster where IsObsolete = 0
	end
	else if @rFlag = 5
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeDesignationMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	else if @rFlag = 6
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeTypeMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	else if @rFlag = 7
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeGroupMaster WHERE IsObsolete = 0
	end
	else if @rFlag = 8
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tBloodGroupMaster where IsObsolete = 0
	end
	else if @rFlag = 9
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sSetup.tDepartmentMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	
	else if @rFlag = 10
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeGradeMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	
	select @lResult as Result
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 

CREATE OR ALTER PROCEDURE [sHrm].[pGetDropDowns]
@rOrgId int,
@rUserId bigint,
@rOrgGroupId int = 1101,
@rPayrollYearId int = null
as
begin
	declare @lStatusRes varchar(max)='',@lColumnRes varchar(max)='',@lReportList varchar(max)=''
	declare @lOrganizationRes nvarchar(max) = '',@lPayRollYear varchar(max) = '',@lPayrollColumn varchar(max) = ''
	declare @lPayrollReportList varchar(max) = '', @lSavedReport nvarchar(max)='', @lSavedReport1 nvarchar(max)=''
	declare @lCustomtagdrop nvarchar(max)=''
	
	select @lOrganizationRes = @lOrganizationRes + '<option value="0"> -- ALL -- </option>'
	select @lOrganizationRes = @lOrganizationRes + '<option ' + case when Id = @rOrgId then 'selected="selected"' else '' end + ' value="' + convert(varchar,Id) + '">' + DisplayTitle + '</option>'
	from sSetup.vUserOrganization where IsObsolete = 0 AND OrgGroupId = isnull(@rOrgGroupId,0) and UserId = @rUserId
	order by OrderIndex
	
	select @lPayRollYear = @lPayRollYear + '<option value="0"> -- Select -- </option>'
	select top 1 @lPayRollYear = @lPayRollYear + '<option value="' + convert(varchar,YearNumber) + '">' + convert(varchar,YearNumber) + '</option>'
	from sPayroll.fMonthYearForPayrollGet(@rPayrollYearId)
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option value="7">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="9">Left</option>'
	select @lStatusRes = @lStatusRes + '<option value="8">Suspended</option>'
	select @lStatusRes = @lStatusRes + '<option value="10">Unknown</option>'
	select @lStatusRes = @lStatusRes + '<option value="738">Retired</option>'
	
	select @lColumnRes = @lColumnRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sHrm' AND TABLE_NAME='vEmployeeColumnName'
	
	select @lPayrollColumn = @lPayrollColumn + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sPayroll' AND TABLE_NAME='vPayrollColumnName'
	
	select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),SCS.Id) + ',''' + convert(varchar(20),SCS.Title) + ''',''' + convert(varchar(max),SCS.ColumnName) +''');">View</a></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="/Images/Del.png"></i></a></td></tr>'
	from sHrm.tEmployeeCustomSearch SCS
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	LEFT JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1  OR SCS.IsCommonForOrg = 1)
	
	select @lPayrollReportList = @lPayrollReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="/Images/Del.png"></i></a></td></tr>'
	from sPayroll.tPayrollCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lSavedReport = @lSavedReport + '<option value="0"> -- Select -- </option>'
	select @lSavedReport =  @lSavedReport + '<option value="' + convert(varchar,ECS.Id)+ '">' + ECS.Title + '</option>'
	from sHrm.tEmployeeCustomSearch  ECS
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = ECS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	WHERE (ECS.CreatedUserId = @rUserId OR ECS.IsCommon = 1 OR ECS.IsCommonForOrg = 1)

	select @lSavedReport1 = @lSavedReport1 + '<option value="0"> -- Select -- </option>'
	select @lSavedReport1 =  @lSavedReport1 + '<option value="' + convert(varchar,PCS.Id)+ '">' + PCS.Title + '</option>'
	from sPayroll.tPayrollCustomSearch  PCS
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = PCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	WHERE (PCS.CreatedUserId = @rUserId OR PCS.IsCommon = 1 OR PCS.IsCommonForOrg = 1)
	

	select @lCustomtagdrop  = @lCustomtagdrop  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
	from sHrm.tCustomTagMaster where IsObsolete =0  and OrgGroupId = @rOrgGroupId

	DECLARE @lAvailableEmployeeColumns nvarchar(max)=''
	 DECLARE @lAvailableEmployeeCustomRes nvarchar(max)=''
	 Declare @Title as nvarchar(max)


	   SET @lAvailableEmployeeColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
						from sHrm.tEmployeeCustomFieldMaster PP WHERE PP.IsObsolete=0 AND PP.OrgGroupId =@rOrgGroupId
				FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
	        
		DECLARE @lEmployeeCustomFields TABLE
		(
		  Title nvarchar(max)
		)
		 INSERT INTO  @lEmployeeCustomFields      
		select Item AS Title from sCommon.fnSplit(@lAvailableEmployeeColumns , ',')

	        
		select @lAvailableEmployeeCustomRes = @lAvailableEmployeeCustomRes +'<option class=EmployeeCustom value="|' + Title + '||">|' + Title + '||</option>'
		from @lEmployeeCustomFields

		
	
	select @lStatusRes as StatusRes,@lColumnRes as AvailableRes,@lReportList as ReportList,
	@lOrganizationRes as OrganizationRes,@lPayRollYear as PayRollYear,@lPayrollColumn as PayrollColumn,
	@lPayrollReportList as PayrollReportList, @lSavedReport AS SavedReportList,@lCustomtagdrop AS customtaghklist,@lAvailableEmployeeCustomRes as AvailableEmployeeCustomRes
	
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pGetEmployeeMananger]

	  --@rLeadId int 
	  @rLeadFollowupId bigint
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			 
BEGIN
				 
		 CREATE TABLE #TempEmployeeId
			(
		EmployeeId bigint
			)
		 
BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeManagerId
			 FROM sHrm.tEmployeeJobDetail EJD
			 --INNER JOIN sErp.tLeadMaster LM ON LM.LeadOwnerEmployeeId = EJD.EmployeeId
			 INNER JOIN sErp.tLeadFollowup LF ON LF.FollowUpEmployeeId = EJD.EmployeeId
			 WHERE LF.Id = @rLeadFollowupId

			 UNION ALL

			 SELECT
			  E.EmployeeManagerId 
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeManagerId = E.EmployeeId
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeManagerId FROM EmployeeCTE E
END
    SELECT 
    EM.Id As EmployeeManagerId
     FROM
		sHrm.tEmployeeMaster EM 
		  INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.Id AND ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND ISNULL(EM.IsOtherUser,0) = 0
			 		  
DROP TABLE #TempEmployeeId
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pHoliDayCountGet]
	
	@rForMonth int=0,
	@rForYear int=0,
	@rBatchId int=0,
	@rOrgId int=0,
	--@rClassId int=0,
	@rEmployeeId bigint=0,
	@rDepartmentId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	CREATE table #Table1 (Id bigint identity,FromDate Date,ToDate Date,SourceId bigint,IsExists bit)
	
	CREATE table #Table2 (Id bigint identity,FromDate Date,ToDate Date,SourceId bigint)
	
	INSERT INTO #Table2 
						SELECT ES.FromDate,ES.ToDate,EA.SourceId FROM sActivity.tEventSchedule ES 
						INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id 
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						INNER JOIN sHrm.vEmployeeCommunication EC ON EC.DepartmentId=DM.Id 				   
						WHERE ((ES.BatchId=@rBatchId)) 
						AND ((MONTH(ES.FromDate)<=@rForMonth) 
						AND (YEAR(ES.FromDate)=@rForYear))
						AND ((MONTH(ES.ToDate)>=@rForMonth) 
						AND (YEAR(ES.ToDate)=@rForYear)) 
						AND ES.IsHoliday=1 
						AND EA.SourceTypeId  = 2004
						AND ((EC.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
						GROUP BY ES.FromDate,ES.ToDate,EA.SourceId
					   
						UNION ALL
					   
						SELECT ES.FromDate,ES.ToDate,EA.SourceId FROM sActivity.tEventSchedule ES 
						INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id 			    
						INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId=EA.SourceId 
						WHERE ((ES.BatchId=@rBatchId)) 
						AND ((MONTH(ES.FromDate)<=@rForMonth) 
						AND (YEAR(ES.FromDate)=@rForYear))
						AND ((MONTH(ES.ToDate)>=@rForMonth) 
						AND (YEAR(ES.ToDate)=@rForYear)) 
						AND ES.IsHoliday=1 
						AND EA.SourceTypeId =95
						AND (EC.EmployeeId=@rEmployeeId OR (@rEmployeeId=0))
						GROUP BY ES.FromDate,ES.ToDate,EA.SourceId 
	  
	INSERT INTO #Table1 
	select FromDate,ToDate,Max(SourceId),0
	from
	( 
	SELECT case when MONTH(FromDate)=@rForMonth then FromDate
				when MONTH(FromDate)<>@rForMonth and MONTH(ToDate)=@rForMonth then DATEADD(DD,-Day(ToDate)+1,ToDate)
				when MONTH(FromDate)<@rForMonth and MONTH(ToDate)>@rForMonth then cast(rtrim(@rForYear *10000+ @rForMonth *100+ 01) as date) --mantis:28433
				else FromDate end as FromDate,
				ToDate,
				SourceId	
	From #Table2
	GROUP BY  FromDate,ToDate,SourceId
	)As Tmp
	GROUP BY  Tmp.FromDate,Tmp.ToDate,Tmp.SourceId
	--select * from #Table2 
	--select * from #Table1
	DECLARE @lTempCount int=0
	SELECT @lTempCount = count(Id) from #Table1
	WHILE @lTempCount > 0 
	BEGIN
		DECLARE @lFromDate Date,@lToDate Date

		SELECT @lFromDate = FromDate, @lToDate = ToDate FROM #Table1 WHERE Id=@lTempCount
		IF EXISTS(SELECT 1 FROM #Table1 WHERE Id <> @lTempCount AND ((@lFromDate between FromDate and ToDate) AND (@lToDate between FromDate and ToDate)))
		BEGIN
			UPDATE #Table1 SET IsExists = 1 WHERE Id = @lTempCount	
		END
		SET @lTempCount = @lTempCount - 1
	END
	 
	DECLARE @lCount int
	SELECT @lCount = count(Id) from #Table1
	DECLARE @lStatus nvarchar(5),@lFromYear int,@lFromMonth int,@lFromDay int,@lSourceId bigint,@lToYear int,@lToMonth int,@lToDay int
	DECLARE @lHoliDayCount int,@lBeginCount int ,@lEndCount int , @lTotalMonth int 
	SET @lHoliDayCount =0
	
		WHILE @lCount > 0 
					BEGIN
						SELECT
							@lFromYear = YEAR(FromDate),
							@lFromMonth = MONTH(FromDate),
							@lFromDay = DAY(FromDate),
							@lToYear = YEAR(ToDate),
							@lToMonth = MONTH(ToDate),
							@lToDay = DAY(ToDate),
							@lSourceId = SourceId,
							@lBeginCount = DAY(FromDate),
							@lEndCount = DAY(ToDate)
						FROM #Table1 T WHERE Id = @lCount AND IsExists = 0
					
						IF(@lFromDay = @lToDay  AND @lFromMonth = @lToMonth)
						BEGIN
							
							--SELECT @lStatus = [sAttendance].[fWeekHOffGet]
							--(@lFromYear,@lFromMonth,@lFromDay,@rBatchId,0,@lSourceId,'',@rOrgId)
							--SELECT @lStatus = [sHrm].[fAttendanceWithLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lFromDay,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
							--this function is created for mantisid -- 29177 
							-- if Holiday is weekoff then display Holiday instead of weekoff for that comment above function and create new function
							SELECT @lStatus = [sHrm].[fAttendanceWithEMPLeaveGet](@rEmployeeId,@lFromYear,@lFromMonth,@lFromDay,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)		-- Mantis Id : 0038655 (Replaced @lSourceId with @rEmployeeId)
							IF(@lStatus = 'H')SET @lHoliDayCount=@lHoliDayCount+1
							
							
						END
						ELSE IF(@lFromDay != @lToDay)
						BEGIN
							IF(@lFromMonth = @lToMonth)
							BEGIN
								WHILE (@lBeginCount <= @lEndCount)
								BEGIN
								  
									--SELECT @lStatus = [sAttendance].[fWeekHOffGet] 	(@lFromYear,@lFromMonth,@lFromDay,@rBatchId,0,@lSourceId,'',@rOrgId)
									--SELECT @lStatus = [sHrm].[fAttendanceWithLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
									--this function is created for mantisid -- 29177 
									-- if Holiday is weekoff then display Holiday instead of weekoff for that comment above function and create new function
									SELECT @lStatus = [sHrm].[fAttendanceWithEMPLeaveGet](@rEmployeeId,@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)	-- Mantis Id : 0038655 (Replaced @lSourceId with @rEmployeeId)
									IF(@lStatus = 'H')
										SET @lHoliDayCount=@lHoliDayCount+1
									
									SET @lBeginCount = @lBeginCount +1	
							   END
							END
							ELSE
							BEGIN
								SET @lTotalMonth = @lToMonth - @lFromMonth
								 WHILE (@lTotalMonth > 0 AND @rForMonth=@lFromMonth)
								 BEGIN
									 DECLARE @lDays int = 0
									 SELECT @lDays = sCommon.fGetDaysInMonth(@lFromMonth,@lFromYear)
									 WHILE (@lBeginCount  <= @lDays)
									 BEGIN
										
										--SELECT @lStatus = [sHrm].[fAttendanceWithLeaveGet](@lSourceId,@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)
										--this function is created for mantisid -- 29177 
										-- if Holiday is weekoff then display Holiday instead of weekoff for that comment above function and create new function
										SELECT @lStatus = [sHrm].[fAttendanceWithEMPLeaveGet](@rEmployeeId,@lFromYear,@lFromMonth,@lBeginCount,@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),@lFromDay))),'','',0)	-- Mantis Id : 0038655 (Replaced @lSourceId with @rEmployeeId)
										IF(@lStatus = 'H')
											SET @lHoliDayCount=@lHoliDayCount+1
											
										SET @lBeginCount = @lBeginCount +1
									END
									SET @lTotalMonth = @lTotalMonth-1
								 END
							END
						END
						SET @lCount = @lCount - 1
					END
	SELECT @lHoliDayCount
	DROP TABLE #Table1
	DROP TABLE #Table2
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[PHomework]
	 @rOrgGroupId int=0,
	 @rConfi int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

  BEGIN
	SELECT 
	 top 5 COUNT(*) AS HomeworkCount
	FROM 
		sStudent.vStudentAllDetail S
			
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pIDNoGenerationGet]
	 
	  
	 
	 @rOrgId smallint 
	  

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			EM.Id AS EmployeeId,
			EM.Code, 
			EM.FirstName,
			EM.LastName,
			EM.FirstName+' '+ EM.MiddleName+' ' +EM.LastName AS Name
  FROM 
			sHrm.tEmployeeMaster  EM 
		
  WHERE 
			--(SO.ClassId=@rClassId OR @rClassId=0)
			--AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
			--AND (SO.RecordStatusId=@rRecordStatusId OR @rRecordStatusId=0)
			--AND SO.BatchId=@rBatchId
			  EM.OrgId=@rOrgId 
			  AND ISNULL(EM.IsOtherUser,0) = 0
 Order By EM.Number		   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pIDNoGenerationUpdate]
	 
	@rEmployeeId bigint,
	@rIDNo nvarchar(20),
	@rCreatedUserId bigint,
	@rOrgId smallint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		   DECLARE @lCode nvarchar(20)
		   SELECT @lCode=Code FROM sHrm.tEmployeeMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rEmployeeId --AND ISNULL(IsOtherUser,0) = 0
		   IF @lCode IS NOT NULL
		   BEGIN
					SELECT -103 AS Result,@lCode AS Code
					RETURN
		   END 
		   
		 --  IF EXISTS(SELECT @lCode=Code FROM sStudent.tStudentMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rStudentId)
			--	BEGIN
			--	SELECT -103 AS RESULT
			--	RETURN
			--END 
	BEGIN TRY
	 BEGIN TRANSACTION	
	 BEGIN
	    UPDATE  sHrm.tEmployeeMaster
	    SET
		    Code=@rIDNo, 	  
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      WHERE Id = @rEmployeeId AND ISNULL(IsOtherUser,0) = 0	   
	 END  
		SELECT 1 AS RESULT
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pImportEmployee]
	
	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--BEGIN TRY

DECLARE @lCount INT, @lECount BigInt
DECLARE @lInterrorCode INT,
    
			@intDoc INT,
			@lCode nvarchar(20),
			@lShortName nvarchar(50),
			@lFirstName Nvarchar(100),
			@lMiddleName Nvarchar(100),
			@lLastName Nvarchar(100),
			@lGenderId int = 0,
			@lGender nvarchar(10),
			@lEmployeeTypeId int = 0,
			@lEmployeeType nvarchar(100),
			@lEmployeeGroupId int,
			@lEmployeeGroup nvarchar(100),
			@lEmployeeGradeId int,
			@lEmployeeGrade nvarchar(100),
			@lDepartmentId int,
			@lDepartment nvarchar(100),
			@lDesignationId int,
			@lDesignation nvarchar(100),
			@lQualification nvarchar(150),
			@lDOB DATETIME,
			@lDOJ DATETIME,
			@lReligionId int,
			@lReligion nvarchar(100),
			
			@lCastCategoryId int,
			@lCastCategory nvarchar(50),
				
			@lCompanyPhoneNo Nvarchar(50),
			@lExtentionNo Nvarchar(10),
			@lCompanyEmailId Nvarchar(100),
			@lPersonalEmailId Nvarchar(100),
			@lMobileNo Nvarchar(20),
			@lPresentStreetOne nvarchar(50),
			@lPresentStreetTwo nvarchar(50),
			@lPresentStreetThree nvarchar(50),
			@lPresentCity nvarchar(50),
			@lPresentZipCode nvarchar(20),
			@lPresentState nvarchar(50),
			@lPresentCountry nvarchar(50),
			@lPresentContactNo nvarchar(20),
			@lFamilyCast nvarchar(150),
			@lAccountNumber nvarchar(150),
			@lBankName nvarchar(150),
			@lBranch nvarchar(150),
			@lEPFNumber nvarchar(150),
			@lPanNumber nvarchar(150),
			@OutDesignationId int,
			@lAdhaarNumber nvarchar(20),
			@lNumber bigint = '',
			@lProbationUptoDate DATE,
			@lAhdocUptoDate DATE,
			@lPermanentDate DATE,
			@lDateOfResignation DATE,
			@lWhatsAppContactNo nvarchar(20),
			@lTribeId int = 0,
			@lTribe nvarchar(100),
			@lBloodGroupId TINYINT,
			@lBloodGroup nvarchar(100),
			@lMaritalStatusId TINYINT,
			@lMaritalStatus nvarchar(100)

DECLARE @OutEmployeeId bigint		
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

 
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(20),
		ShortName nvarchar(50),
		FirstName Nvarchar(100),
		MiddleName Nvarchar(100) null,
		LastName Nvarchar(100),
		GenderId int null,
		Gender nvarchar(10),
		EmployeeTypeId int null,
		EmployeeType nvarchar(100),
		EmployeeGroupId int null,
		EmployeeGroup nvarchar(100),
		EmployeeGradeId int null,
		EmployeeGrade nvarchar(100),
		DepartmentId int null,
		Department nvarchar(100),
		DesignationId int null,
		Designation nvarchar(100),
		Qualification nvarchar(150),	 
		DOB date,
		DOJ date,
		ReligionId int,
		Religion nvarchar(100),
		CastCategoryId int,
		CastCategory nvarchar(50),
		CompanyPhoneNo nvarchar(50) null,
		ExtentionNo nvarchar(10) null,
		CompanyEmailId nvarchar(100) null,
		PersonalEmailId nvarchar(100) null,
		MobileNo nvarchar(20) null,
		PresentStreetOne nvarchar(50),
		PresentStreetTwo nvarchar(50),
		PresentStreetThree nvarchar(50),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		PresentState nvarchar(50),
		PresentCountry nvarchar(50),
		PresentContactNo nvarchar(20),
		FamilyCast nvarchar(150),
		AccountNumber nvarchar(150),
		BankName nvarchar(150),
		Branch nvarchar(150),
		EPFNumber nvarchar(150),
		PanNumber nvarchar(150),
		CreatedUserId bigint null,
		AdhaarNumber nvarchar(20),
		Number bigint null,
		ProbationUptoDate date,
		AhdocUptoDate date,
		PermanentDate date,
		DateOfResignation date,
		WhatsAppContactNo nvarchar(20),
		TribeId int null,
		Tribe nvarchar(100),
		BloodGroupId TINYINT,
		BloodGroup nvarchar(100),
		MaritalStatusId TINYINT,
		MaritalStatus nvarchar(100)
	)
		
	INSERT INTO #tTable
	(
		Code,
		ShortName,
		FirstName,
		MiddleName,
		LastName,
		GenderId,
		Gender,
		EmployeeTypeId,
		EmployeeType,
		EmployeeGroupId,
		EmployeeGroup,
		EmployeeGradeId,
		EmployeeGrade,
		DepartmentId,
		Department,
		DesignationId,
		Designation,
		Qualification,	 
		DOB,
		DOJ,
		ReligionId,
		Religion,
		CastCategoryId,
		CastCategory,
		CompanyPhoneNo,
		ExtentionNo,
		CompanyEmailId,
		PersonalEmailId,
		MobileNo,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		FamilyCast,
		AccountNumber,
		BankName,
		Branch,
		EPFNumber,
		PanNumber,		
		CreatedUserId,
		AdhaarNumber,
		Number,
		ProbationUptoDate,
		AhdocUptoDate,
		PermanentDate,
		DateOfResignation,
		WhatsAppContactNo,
		TribeId,
		Tribe,
		BloodGroupId,
		BloodGroup,
		MaritalStatusId,
		MaritalStatus
	)
	SELECT
		Code,
		ShortName,
		FirstName,
		MiddleName,
		LastName,
		0,
		Gender,
		0,
		EmployeeType,
		0,
		EmployeeGroup,
		0,
		EmployeeGrade,
		0,
		Department,
		0,
		Designation,
		Qualification,	 
		DOB,
		DOJ,
		0,
		Religion,
		0,
		CastCategory,
		CompanyPhoneNo,
		ExtentionNo,
		CompanyEmailId,
		PersonalEmailId,
		MobileNo,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		FamilyCast,
		AccountNumber,
		BankName,
		Branch,
		EPFNumber,
		PanNumber,	
		CreatedUserId,
		AdhaarNumber,
		Number,
		ProbationUptoDate,
		AhdocUptoDate,
		PermanentDate,
		DateOfResignation,
		WhatsAppContactNo,
		0,
		Tribe,
		0,
		BloodGroup,
		0,
		MaritalStatus

	FROM OPENXML (@intDoc, '/Table/ImportEmployee', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',
		ShortName nvarchar(50) '@ShortName',
		FirstName Nvarchar(100) '@FirstName',
		MiddleName Nvarchar(100) '@MiddleName',
		LastName Nvarchar(100) '@LastName',  			
		Gender nvarchar(10) '@Gender', 			
		EmployeeType nvarchar(100) '@EmployeeType',		
		EmployeeGroup nvarchar(100) '@EmployeeGroup',
		EmployeeGrade nvarchar(100) '@EmployeeGrade',	
		Department nvarchar(100) '@Department', 			
		Designation nvarchar(100) '@Designation',	 		
		Qualification nvarchar(150) '@Qualification',	 			
		DOB nvarchar(15) '@DOB', 			
		DOJ nvarchar(15) '@DOJ',	 			
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(50) '@CastCategory',
		CompanyPhoneNo nvarchar(50) '@CompanyPhoneNo',
		ExtentionNo nvarchar(10) '@ExtentionNo', 	
		CompanyEmailId nvarchar(100) '@CompanyEmailId',
		PersonalEmailId nvarchar(100) '@PersonalEmailId',
		MobileNo nvarchar(20) '@MobileNo',
		PresentStreetOne nvarchar(50) '@PresentStreetOne',
		PresentStreetTwo nvarchar(50) '@PresentStreetTwo',
		PresentStreetThree nvarchar(50) '@PresentStreetThree',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		PresentState nvarchar(50) '@PresentState',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentContactNo nvarchar(20) '@PresentContactNo',		
		CreatedUserId bigint '@CreatedUserId',
		FamilyCast nvarchar(150) '@FamilyCast',
		AccountNumber nvarchar(150) '@AccountNumber',
		BankName nvarchar(150) '@BankName',
		Branch nvarchar(150) '@Branch',
		EPFNumber nvarchar(150) '@EPFNumber',
		PanNumber nvarchar(150) '@PanNumber',
		AdhaarNumber nvarchar(20) '@AdhaarNumber',
		Number bigint '@Number',
		ProbationUptoDate nvarchar(15) '@ProbationUptoDate',
		AhdocUptoDate nvarchar(15) '@AhdocUptoDate',
		PermanentDate nvarchar(15) '@PermanentDate',
		DateOfResignation nvarchar(15) '@DateOfResignation',
		WhatsAppContactNo nvarchar(20) '@WhatsAppContactNo',
		Tribe nvarchar(100) '@Tribe',
		BloodGroup nvarchar(100) '@BloodGroup',
		MaritalStatus nvarchar(100) '@MaritalStatus'
	)
	

EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable
SELECT Top 1 @lECount = Id FROM #tTable order by Id -- MantisId : 0029269
WHILE @lCount >= @lECount

BEGIN
		SET	@lCode = ''	
		SET @lShortName = ''
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''	
		SET	@lGenderId = 0
		SET	@lGender = ''
		SET	@lEmployeeTypeId = 0
		SET	@lEmployeeType = ''
		SET	@lEmployeeGroupId = null
		SET	@lEmployeeGroup = ''
		SET	@lEmployeeGradeId = null
		SET	@lEmployeeGrade = ''
		SET	@lDepartmentId = null
		SET	@lDesignationId = null
		SET	@lDepartment = ''
		SET	@lDesignation = ''
		SET @lQualification = ''	
		SET	@lDOB = null
		SET	@lDOJ = null
		SET @lReligionId = null
		SET @lReligion = ''
		SET @lCastCategoryId = NULL
		SET @lCastCategory =''
		SET	@lCompanyPhoneNo = null
		SET	@lExtentionNo = null
		SET	@lCompanyEmailId = null
		SET	@lPersonalEmailId = null
		SET	@lMobileNo = null
		SET @OutEmployeeId = null
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lPresentState = ''
		SET @lPresentCountry = ''
		SET @lPresentContactNo = ''
		SET	@lFamilyCast = ''
		SET	@lAccountNumber = ''
		SET	@lBankName = ''
		SET	@lBranch = ''
		SET	@lEPFNumber = ''
		SET	@lPanNumber = ''
		SET @lAdhaarNumber=''
		SET @lNumber = null
		SET @lProbationUptoDate = null
		SET @lAhdocUptoDate = null
		SET @lPermanentDate = null
		SET @lDateOfResignation = null
		SET @lWhatsAppContactNo = ''
		SET	@lTribeId = 0
		SET	@lTribe = ''
		SET @lBloodGroupId = 0
		SET	@lBloodGroup = ''
		SET	@lMaritalStatusId = 0
		SET	@lMaritalStatus = ''
SELECT		
		@lCode = Code,
		@lShortName = ShortName,
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,	
		@lGender = Gender,
		@lEmployeeType = EmployeeType,	
	    @lEmployeeGroup = EmployeeGroup,
	    @lEmployeeGrade = EmployeeGrade,
		@lDepartment = Department,
		@lDesignation= Designation,	
		@lQualification = Qualification,	
		@lDOB = CASE			
		WHEN DOB = '' THEN  '01/01/1900'
		ELSE DOB  
		--CONVERT(datetime, DOB, 103)
		END,		
		@lDOJ = CASE	
		WHEN DOJ = '' THEN  sCommon.fGetDate()
		ELSE DOJ 
		END,			
		--@lDOB = convert(datetime, DOB, 103),
		--@lDOJ = convert(datetime, DOJ, 103),
		@lReligion = Religion,
		@lCastCategory = CastCategory,
	    @lCompanyPhoneNo = CompanyPhoneNo,
	    @lExtentionNo = ExtentionNo,
	    @lCompanyEmailId = CompanyEmailId,
		@lPersonalEmailId = PersonalEmailId,
		@lMobileNo = MobileNo,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lPresentContactNo = PresentContactNo,
		@lFamilyCast = FamilyCast,
		@lAccountNumber = AccountNumber,
		@lBankName = BankName,
		@lBranch = Branch,
		@lEPFNumber = EPFNumber,
		@lPanNumber = PanNumber,
		@lAdhaarNumber =AdhaarNumber,
		--@lNumber = CASE WHEN Number = 0 THEN  null ELSE Number  END
		@lNumber = Number,
		@lProbationUptoDate = CASE 
		WHEN ProbationUptoDate = '01-01-1900' THEN null
		ELSE ProbationUptoDate END,
		@lAhdocUptoDate = CASE
		WHEN AhdocUptoDate = '01-01-1900' THEN null
		ELSE AhdocUptoDate END,
		@lPermanentDate = CASE
		WHEN PermanentDate = '01-01-1900' THEN null
		ELSE PermanentDate END,
		@lDateOfResignation = CASE
		WHEN DateOfResignation = '01-01-1900' THEN null
		ELSE DateOfResignation END,
		@lWhatsAppContactNo = WhatsAppContactNo,
		@lTribe = Tribe,
		@lBloodGroup = BloodGroup,
		@lMaritalStatus = MaritalStatus
											 	 
FROM #tTable WHERE Id = @lECount  


select * from #tTable

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lEmployeeTypeId = ID FROM sHrm.tEmployeeTypeMaster WHERE Title = @lEmployeeType AND OrgId = @rOrgId
	SELECT	@lEmployeeGroupId  = ID FROM sHrm.tEmployeeGroupMaster WHERE Title = @lEmployeeGroup
	SELECT	@lEmployeeGradeId  = ID FROM sHrm.tEmployeeGradeMaster WHERE Title = @lEmployeeGrade AND OrgId = @rOrgId
	SELECT	@lDepartmentId  = ID FROM sSetup.tDepartmentMaster WHERE Title = @lDepartment AND OrgId = @rOrgId
	SELECT	@lDesignationId  = ID FROM sHrm.tEmployeeDesignationMaster WHERE Title = @lDesignation AND OrgId = @rOrgId
	SELECT	@lReligionId  = ID FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId = @rOrgGroupId
	SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId
	SELECT	@lTribeId = ID FROM sCommon.tTribeMaster WHERE Title = @lTribe
	SELECT	@lBloodGroupId = ID FROM sCommon.tBloodGroupMaster WHERE Title = @lBloodGroup
	SELECT	@lMaritalStatusId = ID FROM sCommon.tMaritalStatusMaster WHERE Title = @lMaritalStatus

	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
	IF(@lEmployeeGroupId IS NULL)
		SET @lEmployeeGroupId = 0
	IF(@lEmployeeGradeId IS NULL)
		SET @lEmployeeGradeId = 0
	IF(@lTribeId IS NULL)
		SET @lTribeId = 0
	IF(@lBloodGroupId IS NULL)
		SET @lBloodGroupId = 0
	IF(@lMaritalStatusId IS NULL)
		SET @lMaritalStatusId = 0
 --BEGIN TRANSACTION
    --Default Group Id = 1
--IF 	@lDepartmentId IS NULL  AND @lDepartment != ''
--BEGIN
--DECLARE @1DepartmentGroupId  int 
-- SET @1DepartmentGroupId = sCommon.fGetIntIdForOrg(1,@rOrgId) 
-- EXEC [sCommon].[pOrganizationDepartmentMasterAdd] @rOrgId,@lDepartment,@lDepartment,0,@rUserId,@OutDepartmentId OUTPUT
--END
--ELSE
--SET @OutDepartmentId = @lDepartmentId

--IF 	@lEmployeeGradeId IS NULL  AND @lEmployeeGrade != ''
--BEGIN
--DECLARE @1EmployeeGradeGroupId  int 
-- EXEC [sHrm].[pEmployeeGradeMasterAdd] @rOrgId,@lEmployeeGrade,@lEmployeeGrade,0,@rUserId,@OutEmployeeGradeId OUTPUT
--END
--ELSE
--SET @OutEmployeeGradeId = @lEmployeeGradeId

IF 	@lDesignationId IS NULL  AND @lDesignation != ''
BEGIN
 EXEC [sHrm].[pEmployeeDesignationMasterAdd] @rOrgId,@lDesignation,@lDesignation,0,@rUserId,@OutDesignationId = @OutDesignationId OUTPUT
END
ELSE
SET @OutDesignationId = @lDesignationId

--UPDATE #tTable SET
--		GenderId = @lGenderId ,
--		EmpTypeId = @lEmpTypeId,
--		DepartmentId = @OutDepartmentId,
--		DesignationId = @lDesignationId,
--		ContractorId = @OutContractorId,
--		BloodGroupId = @lBloodGroupId WHERE Id = @lCount
  
EXEC [sHrm].[pEmployeeMasterAdd] @rOrgId,@lCode,@lFirstName,@lMiddleName,@lLastName,@lEmployeeTypeId,
@lDepartmentId,@lDOB,@lDOJ,@lGenderId,@lReligionId,7,0,@rUserId,@OutEmployeeId OUTPUT,
@lDesignationId,@lBloodGroupId,@lQualification,@lEmployeeGradeId,@lEmployeeGroupId,@lShortName,0,@lFamilyCast,@lCastCategoryId,@lNumber
,@lProbationUptoDate,@lAhdocUptoDate,@lPermanentDate,0,@lDateOfResignation,NULL,@lTribeId,@lAdhaarNumber,@lMaritalStatusId
 
EXEC [sHrm].[pEmployeeCommunicationsAdd] @OutEmployeeId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,Null,Null,NULL,NULL,NULL,NULL,Null,
Null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lCompanyPhoneNo,@lExtentionNo,@lCompanyEmailId,@lPersonalEmailId,@lMobileNo,@rUserId,@lWhatsAppContactNo
		
EXEC [sHrm].[pEmployeeStatutoryDetailAdd] @OutEmployeeId,@lAccountNumber,@lBankName,@lBranch,@lEPFNumber,@lPanNumber,
 0,NULL,NULL,0,0,NULL,NULL,NULL,@rUserId,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL					

		SET @lECount = @lECount + 1	
		--COMMIT TRANSACTION	
END
		SELECT 1 Result		
	--END TRY
	--BEGIN CATCH
	
	--SELECT ERROR_MESSAGE(), ERROR_LINE()
	--END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pImportEmployees_Update_Dynamicly] 
@rOrgId int,
@rCreatedUserId bigint,
@rCode varchar(200) = '',
@rShortName varchar(200) = '',
@rFirstName varchar(200) = '',
@rMiddleName varchar(200) = '',
@rLastName varchar(200) = '',
@rGender varchar(50) = '',
@rEmpType varchar(100) = '',
@rEmpGroup varchar(100) = '',
@rEmpGrade varchar(100) = '',
@rDepartment varchar(150) = '',
@rDesignation varchar(150) = '',
@rQualification varchar(150) = '',
@rDOB datetime = '',
@rDateOfJoining datetime = '',
@rReligion varchar(150) = '',
@rCompayPhoneNo varchar(15) = '',
@rExtensionNo varchar(15)='',
@rCompayMailId varchar(100)='',
@rPersonalEmailid varchar(100)='',
@rMobileNo varchar(50)='',
@rPresentStreetOne varchar(200)='',
@rPresentStreetTwo varchar(200)='',
@rPresentStreetThree varchar(200)='',
@rPresentCity varchar(100)='',
@rPresentZipCode varchar(15)='',
@rPresentState varchar(100)='',
@rPresentCountry varchar(100)='',
@rPresentContactNo varchar(50)='',
@rCastCategory varchar(50)='',
@rFamilyCast varchar(100)='',
@rAccountNumber varchar(100)='',
@rBankName varchar(100)='',
@rBranch varchar(100)=0,
@rEPFNumber varchar(100)=0,
@rPanNumber  varchar(100)='',
@rAdhaarNumber varchar(100)='',
@rValidate varchar(250)='' ,
@rOrgGroupId int,
@rIdentificationMark1  varchar(200)='',
@rUIDNumber varchar(50)='',
@rDateOfLeaving datetime = '',
@rReason varchar(200)='',
@rBloodGroup varchar(50)='',
@rNumber Bigint,
@rProbationUptoDate date = '',
@rAhdocUptoDate date = '',
@rPermanentDate date = '',
@rDateOfResignation date = '',
@rWhatsAppContactNo nvarchar(20) = ''

as
begin	

	IF(@rDateOfLeaving='') 
	SET @rDateOfLeaving = NULL
	IF(@rDOB='') 
	SET @rDOB = NULL
	IF(@rDateOfJoining='') 
	SET @rDateOfJoining = NULL
	IF(@rProbationUptoDate='')
	SET @rProbationUptoDate = NULL
	IF(@rAhdocUptoDate='')
	SET @rAhdocUptoDate = NULL
	IF(@rPermanentDate='')
	SET @rPermanentDate = NULL
	IF(@rDateOfResignation='')
	SET @rDateOfResignation = NULL
	
	declare @EmpId bigint = 0
	select @EmpId = Id from sHrm.tEmployeeMaster where Code = @rCode and OrgID = @rOrgId AND ISNULL(IsOtherUser,0) = 0
	select @EmpId = isnull(@EmpId,0)
	
	declare @genderid int,@emptypeid int,@cmpanyid int,@departmenttid int,@designationid int, 
	 @employeegradeid int,@empgroupid int,@religionId int,@castcatagoryId int,@bloodgroupid int
	 
	
	select @rGender = case when upper(@rGender) = 'M' then 'Male'
	when  upper(@rGender) = 'MALE' then 'Male'
	when upper(@rGender) ='FEMALE' then 'Female'
	when upper(@rGender) = 'F' then 'Female' when upper(@rGender) = 'N' then 'Not Known' else 'Not Known' end
	 
	select @genderid = isnull(Id,0) from sCommon.tGenderMaster where Title = @rGender
	
	select @emptypeid = isnull(Id,0) from sHrm.tEmployeeTypeMaster where Title = @rEmpType and OrgId = @rOrgId
 
	select @empgroupid = isnull(Id,0) from sHrm.tEmployeeGroupMaster where Title = @rEmpGroup
	
	select @employeegradeid = isnull(Id,0) from sHrm.tEmployeeGradeMaster where Title = @rEmpGrade and OrgId = @rOrgId
	 
	 select @departmenttid = isnull(Id,0) from sSetup.tDepartmentMaster where Title = @rDepartment and OrgId = @rOrgId
	 
	  select @bloodgroupid = isnull(Id,0) from sCommon.tBloodGroupMaster where Title = @rBloodGroup 
	
	if (isnull(@rDesignation,'') <> '')
	select @designationid =  isnull(Id,0) from sHrm.tEmployeeDesignationMaster where Title = @rDesignation and OrgId = @rOrgId
	else
	select @designationid = 0
	
	 if (isnull(@rReligion,'') <> '')
			select @religionId =  isnull(Id,0) from sCommon.tReligionMaster where Title = @rReligion and OrgGroupId = @rOrgGroupId
	else
			select @religionId = 0
	
	 if (isnull(@rCastCategory,'') <> '')
	 select @castcatagoryId =  isnull(Id,0) from sCommon.tCastCategoryMaster where Title = @rCastCategory and OrgGroupId = @rOrgGroupId
	 else
	select @castcatagoryId = 0
			
	select @genderid = isnull(@genderid,0),@emptypeid = isnull(@emptypeid,0),@empgroupid = isnull(@empgroupid,0),
	@employeegradeid = isnull(@employeegradeid,0),@departmenttid = isnull(@departmenttid,0),@designationid = isnull(@designationid,0),
	@religionId = isnull(@religionId,0),@castcatagoryId = isnull(@castcatagoryId,0) 
	
	declare @lNextNumber bigint,@Title varchar(100)=''
	
	if @rEmpGroup = ''
	begin
		
		if exists (select 1 from sHrm.tEmployeeGroupMaster where  Title = @Title)
		begin
			select @empgroupid = Id from sHrm.tEmployeeGroupMaster where Title = @Title
		end
		
	end
	
	 
	
	if @rEmpType = ''
	begin		
		
		if exists (select 1 from sHrm.tEmployeeTypeMaster where OrgId = @rOrgId and Title = @Title)
		begin
			select @emptypeid = Id from sHrm.tEmployeeTypeMaster where OrgId = @rOrgId and Title = @Title
		end
	end
	
	 
	if @rEmpGrade = ''
	begin
		 
		if exists(select 1 from sHrm.tEmployeeGradeMaster where OrgId = @rOrgId and Title = @Title)
		begin
			select @employeegradeid = Id from sHrm.tEmployeeGradeMaster where OrgId = @rOrgId and Title = @Title
		end
	end
	
	
	if @rDepartment = ''
	begin		
		 
		if exists (select * from sSetup.tDepartmentMaster  where Title = @Title and OrgId = @rOrgId)
		begin
			select @departmenttid = Id from sSetup.tDepartmentMaster  where Title = @Title and OrgId = @rOrgId
		end
	end
		

	if @rDesignation = ''
	begin
		select @Title = Title from sHrm.tEmployeeDesignationMaster where Id = 1
		if exists (select * from sHrm.tEmployeeDesignationMaster where Title = @Title and OrgId = @rOrgId)
		begin
			select @designationid = Id from sHrm.tEmployeeDesignationMaster where Title = @Title and OrgId = @rOrgId			
		end
	end
	 
	 if @rCastCategory = ''
	begin
		
		if exists (select 1 from sCommon.tCastCategoryMaster where  Title = @Title and OrgGroupId=@rOrgGroupId)
		begin
			select @castcatagoryId = Id from sCommon.tCastCategoryMaster where Title = @Title and OrgGroupId=@rOrgGroupId
		end
		
	end
	
	 
	 if @rReligion = ''
	begin
		
		if exists (select 1 from sCommon.tReligionMaster where  Title = @Title and OrgGroupId=@rOrgGroupId)
		begin
			select @religionId = Id from sCommon.tReligionMaster where Title = @Title and OrgGroupId=@rOrgGroupId
		end
		
	end
	
	if @rShortName <> ''
	select @rShortName = [sSetup].[fPortalXMLTagsReplaceReverse](@rShortName)
	if @rFirstName <> ''
	select @rFirstName = [sSetup].[fPortalXMLTagsReplaceReverse](@rFirstName)
	if @rMiddleName <> ''
	select @rMiddleName = [sSetup].[fPortalXMLTagsReplaceReverse](@rMiddleName)
	if @rLastName <> ''
	select @rLastName = [sSetup].[fPortalXMLTagsReplaceReverse](@rLastName)
	if @rCompayPhoneNo <> ''
	select @rCompayPhoneNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rCompayPhoneNo)
	if @rExtensionNo <> ''
	select @rExtensionNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rExtensionNo)
	if @rCompayMailId <> ''
	select @rCompayMailId = [sSetup].[fPortalXMLTagsReplaceReverse](@rCompayMailId)
	if @rPersonalEmailid <> ''
	select @rPersonalEmailid = [sSetup].[fPortalXMLTagsReplaceReverse](@rPersonalEmailid)
	if @rMobileNo <> ''
	select @rMobileNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rMobileNo)
	if @rPresentStreetOne <> ''
	select @rPresentStreetOne = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetOne)
	if @rPresentStreetTwo <> ''
	select @rPresentStreetTwo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetTwo)
	if @rPresentStreetThree <> ''
	select @rPresentStreetThree = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetThree)
	if @rPresentCity <> ''
	select @rPresentCity = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCity)
	if @rPresentZipCode <> ''
	select @rPresentZipCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentZipCode)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rPresentCountry <> ''
	select @rPresentCountry = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCountry)
	if @rPresentContactNo <> ''
	select @rPresentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentContactNo)
	if @rFamilyCast <> ''
	select @rFamilyCast = [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilyCast)
	if @rAccountNumber <> ''
	select @rAccountNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAccountNumber)
	if @rBankName <> ''
	select @rBankName = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankName)
	if @rBranch <> ''
	select @rBranch = [sSetup].[fPortalXMLTagsReplaceReverse](@rBranch)
	if @rEPFNumber<> ''
	select @rEPFNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rEPFNumber)
	if @rPanNumber <> ''
	select @rPanNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rPanNumber)
	if @rAdhaarNumber <> ''
	select @rAdhaarNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdhaarNumber)
	if @rWhatsAppContactNo <> ''
	select @rWhatsAppContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rWhatsAppContactNo)
	  
	 
	begin

		UPDATE sHrm.tEmployeeMaster 
		SET 
		ShortName = case when isnull(@rShortName,'') <> '' then @rShortName else ShortName end
		,FirstName = case when isnull(@rFirstName,'') <> '' then @rFirstName else FirstName end
		,MiddleName   = case when isnull(@rMiddleName,'') <> '' then @rMiddleName else MiddleName end
		,LastName     = case when isnull(@rLastName,'') <> '' then @rLastName else LastName end
		--,StatusId     = case when isnull(@statusid,0) <> 0 then @statusid else StatusId end
		,IsObsolete   = case when isnull(IsObsolete,'') <> '' then IsObsolete else IsObsolete end
		,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		,Number = @rNumber
		WHERE Id = @EmpId and OrgId = @rOrgId AND ISNULL(IsOtherUser,0) = 0

		  
		UPDATE sHrm.tEmployeeJobDetail
		SET 
			EmployeeDesignationId = case when isnull(@designationid,0) <> 0 then @designationid else EmployeeDesignationId end,	 
			OrganizationDepartmentId = case when isnull(@departmenttid,0) <> 0 then @departmenttid else OrganizationDepartmentId end,
			DateOfJoining =	case when isnull(@rDateOfJoining,'') <> '' then @rDateOfJoining else DateOfJoining end,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			EmployeeTypeId = case when isnull(@emptypeid,0) <> 0 then @emptypeid else EmployeeTypeId end,
			EmployeeGroupId = case when isnull(@empgroupid,0) <> 0 then @empgroupid else EmployeeGroupid end,
			EmployeeGradeId = case when isnull(@employeegradeid,0) <> 0 then @employeegradeid else EmployeeGradeId  end ,
			DateOfleaving =  case when isnull(@rDateOfLeaving,'') <> '' then @rDateOfLeaving else DateOfleaving end,
			ReasonOfleaving = case when isnull(@rReason,'') <> '' then @rReason else ReasonOfleaving end,
			ProbationUptoDate = @rProbationUptoDate,
			AhdocUptoDate = @rAhdocUptoDate,
			PermanentDate = @rPermanentDate,
			DateOfResignation = @rDateOfResignation
			  
	  WHERE EmployeeId = @EmpId and OrgId = @rOrgId
	  
		Update sHrm.tEmployeePersonalDetail 
		set  
		GenderId = case when isnull(@genderid,0) <> 0 then @genderid else GenderId  end,
		ReligionId =  case when isnull(@religionId,0) <> 0 then @religionId else ReligionId  end,
		Qualification =  case when isnull(@rQualification,'') <> '' then @rQualification else Qualification  end,
		BloodGroupId =  case when isnull(@bloodgroupid,0) <> 0 then @bloodgroupid else BloodGroupId  end,
		DateOfBirth =  case when isnull(@rDOB,0) <> 0 then @rDOB else DateOfBirth  end,
		IdentificationMark1 =  case when isnull(@rIdentificationMark1,'') <> '' then @rIdentificationMark1 else IdentificationMark1  end,
		UIDNumber =  case when isnull(@rUIDNumber,0) <> 0 then @rUIDNumber else UIDNumber  end,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate(),
		FamilyCast =case when isnull(@rFamilyCast,'') <> '' then @rFamilyCast else FamilyCast  end,
		AdhaarNumber =case when isnull(@rAdhaarNumber,'') <> '' then @rAdhaarNumber else AdhaarNumber  end,
		CastCategoryId =case when isnull(@castcatagoryId,0) <> 0 then @castcatagoryId else FamilyCast  end
		where EmployeeId = @EmpId and OrgId = @rOrgId
		
  		UPDATE [sHrm].[tEmployeeCommunications]
		SET 
	      
		   [PresentStreetOne] = case when isnull(@rPresentStreetOne,'') <> '' then @rPresentStreetOne else [PresentStreetOne] end 
		  ,[PresentStreetTwo] =  case when isnull(@rPresentStreetTwo,'') <> '' then @rPresentStreetTwo else [PresentStreetTwo] end 
		  ,[PresentStreetThree] = case when isnull(@rPresentStreetThree,'') <> '' then @rPresentStreetThree else [PresentStreetThree] end 
		  ,[PresentCountry] = case when isnull(@rPresentCountry,'') <> '' then @rPresentCountry else [PresentCountry] end 
		  ,[PresentState] =  case when isnull(@rPresentState,'') <> '' then @rPresentState else [PresentState] end 
		  ,[PresentCity] =  case when isnull(@rPresentCity,'') <> '' then @rPresentCity else [PresentCity] end 
		  ,[EmergencyContactNo] = case when isnull(@rMobileNo,'') <> '' then @rMobileNo else [EmergencyContactNo] end 
		  ,[PhoneNoCompany] = case when isnull(@rCompayPhoneNo,'') <> '' then @rCompayPhoneNo else [PhoneNoCompany] end 
		  ,[ExtensionNo] = case when isnull(@rExtensionNo,'') <> '' then @rExtensionNo else [ExtensionNo] end  
		  ,[CompanyEmail] =  case when isnull(@rCompayMailId,'') <> '' then @rCompayMailId else [CompanyEmail]  end   
		  ,[PersonalEmail] =  case when isnull(@rPersonalEmailid,'') <> '' then @rPersonalEmailid else [PersonalEmail]  end   
		  ,[MobileNumber] =  case when isnull(@rMobileNo,'') <> '' then @rMobileNo else [MobileNumber]  end      
		  ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		  ,[WhatsAppContactNo] =  case when isnull(@rWhatsAppContactNo,'') <> '' then @rWhatsAppContactNo else [WhatsAppContactNo]  end    
		  ,PresentZipCode = case when isnull(@rPresentZipCode,'') <> '' then @rPresentZipCode else PresentZipCode  end    
		  ,PresentContactNo = case when isnull(@rPresentContactNo,'') <> '' then @rPresentContactNo else PresentContactNo  end    
		WHERE EmployeeId = @EmpId

		Update [sHrm].[tEmployeeStatutoryAndOther]
		SET
		AccountNumber = case when isnull(@rAccountNumber,'') <> '' then @rAccountNumber else AccountNumber  end, 
		BankName = case when isnull(@rBankName,'') <> '' then @rBankName else BankName  end,
		Branch = case when isnull(@rBranch,'') <> '' then @rBranch else Branch  end , 
		EPFNumber = case when isnull(@rEPFNumber,'') <> '' then @rEPFNumber else EPFNumber  end,
		PanNumber = case when isnull(@rPanNumber,'') <> '' then @rPanNumber else PanNumber  end
		where EmployeeId = @EmpId 
	end	
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pImportEmployeesValidateFordynamic]
@rXml varchar(max)
as
begin

DECLARE @loXML XML
SET @loXML = CAST(@rXml AS XML)
	declare @tblemp table(tid int identity(1,1),ecode varchar(200))
	insert into @tblemp(ecode)
	select 
	T.c.value('@Code','varchar(200)') AS EmpCode
	FROM 
	@loXML.nodes('/Table/ImportEmployee')T(c)
	
	declare @validate varchar(max)='',@orgid int,@cnt int,@i int
    select @cnt = count(*),@i = 1 from @tblemp
	while @i <= @cnt
	begin
		declare @Code varchar(200)
		select @Code = ecode from @tblemp where tid = @i
		if not exists (select 1 from sHrm.tEmployeeMaster where Code = @Code AND ISNULL(IsOtherUser,0) = 0)
		begin
			select @validate = @validate + 'employee code Like : '+@Code+' Not Found ,<br/>' 
		end
		select @i = @i + 1;
	end
	
	select isnull(@validate,'') as valid
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pImportStockItem_Update_Dynamicly]
@rOrgId int,
@rCreatedUserId bigint,
@rCode varchar(200) = '',
@rTitle varchar(200) = '',
@rItemSubGroupId bigint = 0,
@rStockItemCategoryId bigint = 0,
@rIssueStockUomId bigint = 0,
@rStandardPrice decimal(18,5) ,
@rIsBatch varchar(10),
@rBinId bigint =0,
@rlocationId bigint  
as
begin	


	declare @StockItemid bigint = 0
	select @StockItemid = Id from sIp.tStockItemMaster where Code = sSetup.fPortalXMLTagsReplaceReverse(@rCode) and Title = sSetup.fPortalXMLTagsReplaceReverse(@rTitle) and LocationId = @rlocationId and OrgGroupId = @rOrgId
	select @StockItemid = isnull(@StockItemid,0)

	begin

		UPDATE sIp.tStockItemMaster
		SET ItemSubGroupId = case when isnull(@rItemSubGroupId,0) <> 0 then @rItemSubGroupId else ItemSubGroupId end
		,StockItemCategoryId   = case when isnull(@rStockItemCategoryId,0) <> 0 then @rStockItemCategoryId else StockItemCategoryId end
		,IssueStockUomId     = case when isnull(@rIssueStockUomId,0) <> 0 then @rIssueStockUomId else IssueStockUomId end
		,BinId  = case when isnull(@rBinId,0) <> 0 then @rBinId else @rBinId end
		
		,IsBatchWiseTracking  = case when isnull(@rIsBatch,'') <> '' then 
		case when @rIsBatch='True' then 1 when @rIsBatch='Yes' 
		then 1 when @rIsBatch='1' then 1 else 0 end 
		else IsBatchWiseTracking end
		
		,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		WHERE Id = @StockItemid and OrgGroupId = @rOrgId
		
		
		Update Sip.tStockItemPlanning  set StandardPrice  = case when isnull(@rStandardPrice,0) <> 0 then @rStandardPrice else StandardPrice end
		where StockItemId=@StockItemid
			
	end	
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pImportStockItemValidateFordynamic]
@rXml varchar(max),
@locationId bigint =0
as
begin



DECLARE @loXML XML
SET @loXML = CAST(@rXml AS XML)
	declare @tblemp table(tid int identity(1,1),ecode varchar(200),eName varchar(max),eStockLocationId bigint)
	insert into @tblemp(ecode,eName,eStockLocationId)
	select 
	T.c.value('@Code','varchar(200)') AS EmpCode,
	T.c.value('@Title','varchar(max)') AS Title	,
	@locationId
	FROM 
	@loXML.nodes('/Table/ImportStockItemCheck')T(c)
	
	declare @validate varchar(max)='',@orgid int,@cnt int,@i int
    select @cnt = count(*),@i = 1 from @tblemp
	while @i <= @cnt
	begin
		declare @Code varchar(200),@name varchar(max),@location_id bigint 
		select @Code = ecode,@name =eName,@location_id = @locationId from @tblemp where tid = @i
		if not exists (select 1 from sIp.tStockItemMaster where Code = @Code and Title = @name and LocationId = @location_id)
		begin
			select @validate = @validate + 'Stock Item Code Like : '+@Code+' Not Found ,<br/>' 
		end
		select @i = @i + 1;
	end
	
	select isnull(@validate,'') as valid
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pImportUser]
    
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rCreatedUserId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @loXML XML,@lCount int,
			@lUserType nvarchar(100),
			@lEmployeeCode nvarchar(100),
			@lUserName nvarchar(100),
			@lDisplayName nvarchar(100),
			@lPassword nvarchar(500),
			@lRole nvarchar(100),
			@lRoleId bigint
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	CREATE TABLE #tTable1 (
	Id bigint identity,
	UserType nvarchar(50) collate SQL_Latin1_General_CP1_CI_AS ,
	EmployeeCode nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	UserName nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	DisplayName nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	[Password] nvarchar(500) collate SQL_Latin1_General_CP1_CI_AS ,
	[Role] nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	RoleId bigint)
	
	INSERT INTO #tTable1(
		UserType,
		EmployeeCode,
		UserName,
		DisplayName, 
		[Password],
		[Role],
		RoleId)      
	SELECT
		 T.c.value('@UserType','nvarchar(50)') AS UserType,
		 T.c.value('@EmployeeCode','nvarchar(100)') AS EmployeeCode,
		 T.c.value('@UserName','nvarchar(100)') AS UserName,
		 T.c.value('@DisplayName','nvarchar(100)') AS DisplayName,
		 T.c.value('@Password','nvarchar(500)') AS [Password],
		 T.c.value('@Role','nvarchar(100)') AS [Role],
		 T.c.value('@RolId','nvarchar(100)') AS RoleId
	FROM @loXML.nodes('/Table/ImportUser')T(c)
  			
BEGIN

	DECLARE @rUserSourceId bigint = NULL, @rUserSourceTypeId bigInt = NULL, @EmployeeId bigint = NULL, @tmp varchar(500),@tmp1 varchar(500)

	SET @tmp = ''
	SET @tmp1 =''
	
	SELECT @tmp = @tmp + T.EmployeeCode  + ', '  from #tTable1 T 
	LEFT JOIN  sHrm.tEmployeeMaster EM ON T.EmployeeCode  = EM.Code 
	AND EM.OrgId = @rOrgId 
	WHERE EM.ID IS NULL AND T.EmployeeCode <> '' AND ISNULL(EM.IsOtherUser,0) = 0 AND upper(T.UserType) = 'EMPLOYEE' 
 
	SELECT @tmp1 = @tmp1 + T.EmployeeCode  + ', '  from #tTable1 T 
	LEFT JOIN  sStudent.tStudentMaster SM ON T.EmployeeCode  = SM.Code 
	AND SM.OrgId = @rOrgId  
	WHERE SM.ID IS NULL AND T.EmployeeCode <> '' AND upper(T.UserType) = 'STUDENT'

	IF @tmp <> ''
	BEGIN
		SELECT -101 AS Result, SUBSTRING(@tmp, 0, LEN(@tmp)) AS ResultDetail
		RETURN
	END

	IF @tmp1 <> ''
	BEGIN
		SELECT -102 AS Result, SUBSTRING(@tmp1, 0, LEN(@tmp1)) AS ResultDetail
		RETURN
	END

	SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
	BEGIN		
		SELECT         
			@lUserType = UserType ,
			@lEmployeeCode = EmployeeCode,
			@lUserName = UserName,
			@lDisplayName = DisplayName,
			@lPassword = [Password],
			@lRole = [Role],
			@lRoleId = RoleId
		FROM #tTable1 WHERE Id = @lCount    
	     
		IF UPPER(@lUserType) = 'EMPLOYEE'
		BEGIN
		 SELECT @rUserSourceId = Id FROM sHrm.tEmployeeMaster WHERE Code = @lEmployeeCode AND OrgID=@rOrgId AND ISNULL(IsOtherUser,0) = 0
		 SELECT @rUserSourceTypeId = 95
		END

		ELSE IF(UPPER(@lUserType) = 'STUDENT')
		BEGIN
			SELECT @rUserSourceId = Id FROM sStudent.tStudentMaster WHERE Code = @lEmployeeCode AND OrgID=@rOrgId 
			SELECT @rUserSourceTypeId =2003
		END

		ELSE
		BEGIN
			 SELECT @rUserSourceId = 0
			 SELECT @rUserSourceTypeId = 1
		END

		-- Added 'AND SourceTypeId=@rUserSourceTypeId AND SourceId <> @rUserSourceId' for mantis 0027721 by foram 
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE OrgId = @rOrgId AND LoginTitle=@lUserName AND SourceTypeId=@rUserSourceTypeId AND SourceId <> @rUserSourceId)							
		BEGIN
			Select -103 As Result, 'User Name Already Exist for Code ' + @lEmployeeCode  As ResultDetail
			return
		END
		-- Commented for mantis 0027721 by foram
		--IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE OrgId = @rOrgId AND SourceTypeId=@rUserSourceTypeId AND SourceId = @rUserSourceId)							
		--BEGIN
		--	Select -104 As Result, 'User Already Exist for Code ' + @lEmployeeCode As ResultDetail
		--	return
		--END

		-- Uncommented for mantis 0027721 by foram
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceId = @rUserSourceId AND OrgId=@rOrgId AND SourceTypeId=@rUserSourceTypeId)--AND LoginTitle = @lUserName )
		BEGIN
			UPDATE sSecurity.tUser
			SET	
				LoginPassword = @lPassword,				
				IsObsolete = 0,			
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LoginTitle = @lUserName,
				DisplayTitle = @lDisplayName
			WHERE 
				SourceId = @rUserSourceId AND OrgId=@rOrgId	AND SourceTypeId=@rUserSourceTypeId  --AND LoginTitle = @lUserName		
		END
		ELSE
		BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sSecurity.tUser
				(
					Id,		
					DisplayTitle,
					LoginTitle,
					LoginPassword,
					LastLockOutDate,
					NumberOfLogonAttempt,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime,
					OrgId,
					SourceId,
					SourceTypeId	
				)
			VALUES
				(
					@lNextNumber,
					@lDisplayName,					
					@lUserName,
					@lPassword,
					sCommon.fGetDate(),
					0,
					0,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgId,
					@rUserSourceId,
					@rUserSourceTypeId
				)
				
			IF NOT EXISTS(Select 1 From [sSecurity].[tUserRole]  WHERE RoleId = @lRoleId AND UserId=@lNextNumber)
			BEGIN
				INSERT INTO 
				[sSecurity].[tUserRole] (RoleId, UserId, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsPrimary)
				VALUES
				(@lRoleId,@lNextNumber,0,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),1)
			END
		END
		SET @lCount = @lCount-1
	  END 
	SELECT 1 AS Result, '' AS ResultDetail
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
    
CREATE OR ALTER PROCEDURE [sHrm].[pIncrementCertificateAdd]    
    
@rId bigint = 0,    
  @rCode nvarchar(20)='',    
  @rName nvarchar(200)='',    
  @rFromNo int = 0,    
  @rToNo int =0,    
  @rFromDate date='',    
  @rToDate date='',    
  @rOrgId smallint =0,    
  @rIsSearch bit = 1,    
  @rEmployeeId bigint=0,    
  @rBatchId int = 0,    
  @rNumber int = 0,    
  @rEmployeeDesignationId int= 0,    
  @rQualification nvarchar(150)='',    
  @rPayScale nvarchar(200)='',    
  @rExistingBasicPay decimal(12,2)= 0,    
  @rRevisedBasicPay decimal(12,2)= 0,    
  @rRevisedBasicPayDate DATE='',    
  @rGradePayInRevisedPayStructure decimal(12,2)= 0,    
  @rBasicPayInRevisedPayStructureBasicPayAndGradePay decimal(12,2)= 0.00,    
  @rGrossSalaryAsPerExistingPayScale decimal(12,2)= 0.00,    
  @rRevisedGrossSalaryAsOn decimal(12,2)= 0.00,    
  @rIncrementDate DATE = '',    
  @rRemark nvarchar(200)='',    
  @rCertificateDate DATE= '',    
  @rCreatedUserId bigint =0,    
  @rCreatedDateTime DATE=''    
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN    
 --BEGIN TRY     
 -- BEGIN TRANSACTION     
      
  IF(@rNumber = 0)    BEGIN    SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sHrm.tCertificateIncrement WHERE OrgId=@rOrgId   END     
       
  IF(@rId = 0)     
  BEGIN    IF EXISTS(SELECT 1 FROM sHrm.tCertificateIncrement WHERE Number=@rNumber AND OrgId=@rOrgId)    
   BEGIN    
    SELECT -103 AS Result    
    RETURN    
   END   
   END     
   DECLARE @lNextNumber BIGINT   
   DECLARE @lQualification nvarchar(150)
   
    IF(@rId = 0)     
  BEGIN    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCertificateIncrement', 0, 1, 1,@outNextNumber = @lNextNumber output     
  SELECT @lQualification= Qualification FROM  sHrm.vExtEmployeeMaster WHERE EmployeeId = @rEmployeeId
 
  INSERT INTO sHrm.tCertificateIncrement     
  (      Id    
       ,EmployeeId    
       ,Number    
       ,CertificateDate        ,OrgId        ,Remark        ,BatchId     
       ,EmployeeDesignationId     
       ,Qualification     
     ,PayScale    
     ,ExistingBasicPay    
     ,RevisedBasicPay     
     ,RevisedBasicPayDate    
     ,GradePayInRevisedPayStructure    
     ,BasicPayInRevisedPayStructureBasicPayAndGradePay    
     ,GrossSalaryAsPerExistingPayScale    
     ,RevisedGrossSalaryAsOn     
     ,IncrementDate    
     ,CreatedUserId    
     ,CreatedDateTime     )    
      VALUES     
      ( @lNextNumber    
       ,@rEmployeeId    
       ,@rNumber    
       ,@rCertificateDate        ,@rOrgId        ,@rRemark        ,@rBatchId     
       ,@rEmployeeDesignationId    
       ,@lQualification     
     ,@rPayScale    
     ,@rExistingBasicPay    
     ,@rRevisedBasicPay     
     ,@rRevisedBasicPayDate    
     ,@rGradePayInRevisedPayStructure    
     ,@rBasicPayInRevisedPayStructureBasicPayAndGradePay    
     ,@rGrossSalaryAsPerExistingPayScale    
     ,@rRevisedGrossSalaryAsOn     
     ,@rIncrementDate    
     ,@rCreatedUserId    
     ,@rCreatedDateTime     )    
     SELECT 1 AS Result 
  END    
      
  ELSE    
      
  BEGIN    
  
   SET @lNextNumber = @rId 
    UPDATE  sHrm.tCertificateIncrement    
    SET    
     EmployeeId=@rEmployeeId,    
     CertificateDate=@rCertificateDate,      
     UpdatedUserId=@rCreatedUserId,      
     UpdatedDateTime=sCommon.fGetDate(),    
     Remark=@rRemark,         
     BatchId=@rBatchId,    
      EmployeeDesignationId=@rEmployeeDesignationId,    
      Qualification= @rQualification ,    
      PayScale=@rPayScale,     
      ExistingBasicPay=@rExistingBasicPay,    
      RevisedBasicPay=@rRevisedBasicPay,    
      RevisedBasicPayDate=@rRevisedBasicPayDate,    
      GradePayInRevisedPayStructure=@rGradePayInRevisedPayStructure,    
      BasicPayInRevisedPayStructureBasicPayAndGradePay=@rBasicPayInRevisedPayStructureBasicPayAndGradePay,    
      GrossSalaryAsPerExistingPayScale=@rGrossSalaryAsPerExistingPayScale,    
      RevisedGrossSalaryAsOn=@rRevisedGrossSalaryAsOn,    
      IncrementDate=@rIncrementDate    
    WHERE Id = @rId    
   END
     SELECT 11 AS Result 
      
  SELECT @lNextNumber AS Result    
     
 --COMMIT TRANSACTION    
 --END TRY    
     
 --BEGIN CATCH     
 -- ROLLBACK TRANSACTION    
 -- SELECT -1 AS Result    
 --END CATCH     
     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pIncrementCertificateGet]  
    
  @rId bigint = 0,  
  @rCode nvarchar(20),  
  @rName nvarchar(200),  
  @rFromNo int,  
  @rToNo int,  
  @rFromDate date,  
  @rToDate date,  
  @rOrgId smallint,  
  @rBatchId int =0,
  @rIsSearch bit = 1,  
  @rEmployeeId bigint=0
      
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
  
BEGIN   
  IF @rIsSearch = 1  
  BEGIN  
   SET @rCode = sCommon.fSearchStringGet(@rCode)  
   SET @rName = sCommon.fSearchStringGet(@rName)  
  END  
   
 SELECT   
   
   CI.Id,  
   CI.EmployeeId,  
   EEM.FirstName+' '+EEM.LastName as Name,  
   CI.Number,  
   CI.CertificateDate ,  
   CI.Remark,  
   isnull(EEM.Designation,0) AS Designation,    
   CI.Qualification As Qualification, 
   EEM.Code , 
   CI.BatchId ,
	CI.PayScale,
	CI.ExistingBasicPay,
	CI.RevisedBasicPay, 
	CI.RevisedBasicPayDate,
	CI.GradePayInRevisedPayStructure,
	CI.BasicPayInRevisedPayStructureBasicPayAndGradePay,
	CI.GrossSalaryAsPerExistingPayScale,
	CI.RevisedGrossSalaryAsOn, 
	CI.IncrementDate,
	BM.Title As Batch
     
  FROM   
            sHrm.tCertificateIncrement CI  
       INNER JOIN sHrm.vExtEmployeeMaster EEM ON EEM.EmployeeId=CI.EmployeeId AND EEM.OrgId=@rOrgId   
       LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = CI.BatchId
  WHERE   
    
 ((CI.Id = @rId) OR (@rId = 0))  
 AND ((BM.Id = @rBatchId) OR (@rBatchId = 0)) 
 AND ((EEM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))  
 AND ((EEM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))  
 AND ((CI.Number >= @rFromNo) OR (@rFromNo=0))  
 AND ((CI.Number <= @rToNo) OR (@rToNo=0))  
 AND ((CI.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
 AND ((CI.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
 ORDER BY CI.Number  DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pJoiningCertificateAdd]    

	@rId bigint = 0,        
	@rOrgId smallint =0,    
	@rEmployeeId bigint=0,
	@rDepartmentId int=0,  
	@rEmployeeDesignationId int= 0,    
	@rNumber int = 0,    
	@rCertificateDate DATE= NULL,    
	@rDateOfJoining DATE=NULL,    
	@rPayScale nvarchar(150)='',
	@rAgreementPeriod nvarchar(150)='',    
	@rCertificateRemark nvarchar(500)='', 
	@rRemark nvarchar(500)='',   
	@rUserId bigint =0

WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN    
	BEGIN TRY     
	BEGIN TRANSACTION     

	IF(@rNumber = 0) 
	BEGIN
		SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sHrm.tCertificateJoining WHERE OrgId=@rOrgId
	END     
       
	IF(@rId = 0)     
	BEGIN 
		IF EXISTS(SELECT 1 FROM sHrm.tCertificateJoining WHERE Number=@rNumber AND OrgId=@rOrgId)    
		BEGIN    
			SELECT -103 AS Result    
			RETURN    
		END   
	END
	     
	DECLARE @lNextNumber BIGINT   
   
	IF(@rId = 0)     
	BEGIN 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCertificateJoining', 0, 1, 1,@outNextNumber = @lNextNumber output     
 
		INSERT INTO sHrm.tCertificateJoining     
		(      
			Id
			,OrgId    
			,EmployeeId 
			,DepartmentId
			,EmployeeDesignationId   
			,Number    
			,CertificateDate
			,DateOfJoining
			,Payscale   
			,AgreementPeriod
			,CertificateRemark       
			,Remark    
			,CreatedUserId    
			,CreatedDateTime
		)    
		VALUES     
		( 
			 @lNextNumber 
			,@rOrgId   
			,@rEmployeeId 
			,@rDepartmentId
			,@rEmployeeDesignationId
			,@rNumber    
			,@rCertificateDate     
			,@rDateofJoining    
			,@rPayScale     
			,@rAgreementPeriod    
			,@rCertificateRemark    
			,@rRemark        
			,@rUserId    
			,sCommon.fGetDate()
		)    
		SELECT 1 AS Result 
	END    
	ELSE    
	BEGIN    
		SET @lNextNumber = @rId 

		UPDATE sHrm.tCertificateJoining    
		SET    
		EmployeeId=@rEmployeeId,
		DepartmentId= @rDepartmentId, 
		EmployeeDesignationId=@rEmployeeDesignationId,
		Number=@rNumber,       
		CertificateDate=@rCertificateDate,
		DateOfJoining=@rDateOfJoining,
		PayScale=@rPayScale,
		AgreementPeriod=@rAgreementPeriod,
		CertificateRemark=@rCertificateRemark,
		Remark=@rRemark,
		UpdatedUserId=@rUserId,
		UpdatedDateTime=sCommon.fGetDate()
		WHERE Id = @rId    
	END
	SELECT 11 AS Result 
      
	SELECT @lNextNumber AS Result    
     
	COMMIT TRANSACTION    
	END TRY    
	BEGIN CATCH     
	ROLLBACK TRANSACTION    
	SELECT -1 AS Result    
	END CATCH     
     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pJoiningCertificateGet]  
    
  @rId bigint = 0,  
  @rCode nvarchar(20),  
  @rName nvarchar(200),  
  @rFromNo int,  
  @rToNo int,  
  @rFromDate date,  
  @rToDate date,  
  @rOrgId smallint,  
  --@rBatchId int =0,
  @rIsSearch bit = 1,
  @rDepartmentId int = 0,  
  @rEmployeeId bigint=0
      
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
  
BEGIN   
  IF @rIsSearch = 1  
  BEGIN  
   SET @rCode = sCommon.fSearchStringGet(@rCode)  
   SET @rName = sCommon.fSearchStringGet(@rName)  
  END  
   
 SELECT   
   
   CJ.Id,  
   CJ.EmployeeId,  
   EEM.FirstName+' '+EEM.LastName as Name,  
   CJ.Number,  
   CJ.CertificateDate ,  
   CJ.Remark,  
   isnull(EEM.Designation,0) AS Designation,    
   EEM.Code , 
	CJ.PayScale,
	CJ.DateOfJoining,
	CJ.AgreementPeriod, 
	CJ.CertificateRemark,
	CJ.DepartmentId,
	EEM.DateofJoining AS EmployeeDateofJoining  --added
	--EEM.DepartmentName As Department
	--BM.Title As Batch
     
  FROM   
            sHrm.tCertificateJoining CJ  
       INNER JOIN sHrm.vExtEmployeeMaster EEM ON EEM.EmployeeId=CJ.EmployeeId AND EEM.OrgId=@rOrgId   
       --LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = CI.BatchId
  WHERE   
    
 ((CJ.Id = @rId) OR (@rId = 0))  
 --AND ((BM.Id = @rBatchId) OR (@rBatchId = 0)) 
 AND ((EEM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))  
 AND ((EEM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))  
 AND ((CJ.Number >= @rFromNo) OR (@rFromNo=0))  
 AND ((CJ.Number <= @rToNo) OR (@rToNo=0))  
 AND ((CJ.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
 AND ((CJ.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
 AND ((EEM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0) )	
 ORDER BY CJ.Number  DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveAdd]
           
        @rId bigint,
        @rEmployeeId bigint,
        @rReportDate date,
        @rFromDate date,
        @rToDate date,
        @rLeavePeriodId tinyint,
        @rLeaveTypeId int,
        @rLeaveReson nvarchar(200),
        @rNoOfLeave decimal(5,2),
        @rBatchId int,
        @rOrgId int,
        @rCreatedUserId bigint,
        @rStatusId int,
        @rFromTime datetime,
		@rToTime datetime
AS
SET NOCOUNT ON

BEGIN

IF EXISTS (SELECT 1 FROM  sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId AND isLwp = 0)
BEGIN
   DECLARE @lMainLeaveTypeId tinyint
   SET @lMainLeaveTypeId =0
   SELECT @lMainLeaveTypeId = ISNULL(MainLeaveTypeId,0) FROM sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId
   
   DECLARE @lMaxInMonth decimal(5,2)
   DECLARE @lNumberOfLeave decimal(5,2)
   SET @lMaxInMonth =0
   SET @lNumberOfLeave =0
   
   DECLARE @lFirstDate date
   DECLARE @lLastDate date
   
   SET @lFirstDate = DATEADD(mm, DATEDIFF(mm, 0, @rFromDate), 0)
   SET @lLastDate = DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, @rFromDate) + 1, 0))

   
   
   SELECT @lMaxInMonth = ISNULL(LB.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
   INNER JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EJD.EmployeeId AND LB.BatchId = @rBatchId
   WHERE EJD.OrgId = @rOrgId AND LB.LeaveTypeId=@rLeaveTypeId AND EJD.EmployeeId=@rEmployeeId
   
   -- For Employee Specific 08/11/2017 - by Ramesh Gurjar
   IF(@lMaxInMonth=0)
   BEGIN
		SELECT @lMaxInMonth = ISNULL(LTGS.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
		INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON EJD.EmployeeGradeId=LTGS.EmployeeGradeId 
		WHERE LTGS.OrgId = @rOrgId 
		AND LTGS.LeaveTypeId=@rLeaveTypeId 
		AND  EJD.EmployeeId=@rEmployeeId
   END
   -- End
   
   SELECT  @lNumberOfLeave= ISNULL(SUM(L.NoOfLeave),0) 
   FROM     
   sHrm.tLeave L  
   WHERE  
   L.EmployeeId=@rEmployeeId 
   AND (L.FromDate>=@lFirstDate) AND (L.FromDate<=@lLastDate)
   AND L.LeaveTypeId=@rLeaveTypeId AND L.StatusId = 550
   GROUP BY L.EmployeeId

 
			 --IF (@lMaxInMonth < (@lNumberOfLeave+@rNoOfLeave) AND @lMainLeaveTypeId!=3)  -- comment due to validate at page side
				--BEGIN
				--	SELECT -105  AS RESULT
				--	RETURN
				--END
		
  END
     
   DECLARE @1Leave int
    
	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint
	 
    IF (@rId = 0)
     BEGIN
       
       IF(@rLeavePeriodId = 2) --For Half Leave	  	
       SELECT @1Leave = SUM(NoOfLeave) from sHrm.tLeave where EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND FromDate = @rFromDate 
       ELSE
         SET @1Leave = 1
     		
	   IF NOT EXISTS(SELECT 1 FROM sHrm.tLeave WHERE EmployeeId = @rEmployeeId 
	   AND(( FromDate  BETWEEN @rFromDate AND @rToDate) OR (ToDate BETWEEN @rFromDate AND @rToDate)
	   OR (@rFromDate  BETWEEN FromDate AND ToDate) OR (@rToDate BETWEEN FromDate AND ToDate)) AND OrgId = @rOrgId AND BatchId = @rBatchId AND StatusId!=551)-- OR @1Leave != 1
	   BEGIN
	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeave', 0, 1, 1,@outNextNumber = @lNextNumber output	
	    
		  INSERT INTO [sHrm].[tLeave]
           (
            [Id]
           ,[EmployeeId]
           ,[ReportDate]
           ,[FromDate]
           ,[ToDate]
           ,[LeavePeriodId]
           ,[LeaveTypeId]
           ,[LeaveReason]
           ,NoOfLeave
           ,BatchId
           ,[OrgId]           
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[StatusId]
           ,[FromTime]
           ,[ToTime]
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId 
           ,@rReportDate 
           ,@rFromDate 
           ,@rToDate 
           ,@rLeavePeriodId 
           ,@rLeaveTypeId 
           ,@rLeaveReson 
           ,@rNoOfLeave
           ,@rBatchId
           ,@rOrgId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rStatusId       
           ,@rFromTime
           ,@rToTime      
           )
            END
          ELSE
            SET @lNextNumber = -101            
          END
	ELSE
	BEGIN
	SET @lNextNumber = @rId
		UPDATE sHrm.tLeave
		SET 	 
		   [EmployeeId]= @rEmployeeId 
		  ,[ReportDate]= @rReportDate 
		  ,[FromDate]= @rFromDate 
		  ,[ToDate]= @rToDate 
		  ,[LeavePeriodId]= @rLeavePeriodId 
		  ,[LeaveTypeId]= @rLeaveTypeId 
		  ,[LeaveReason]= @rLeaveReson 
		  ,NoOfLeave = @rNoOfLeave
		  ,[OrgId]= @rOrgId        
		  ,[UpdatedUserId]= @rCreatedUserId
		  ,[UpdatedDateTime]= sCommon.fGetDate()
		  ,[FromTime] = @rFromTime
          ,[ToTime] = @rToTime    
		WHERE Id = @rId
	 END 
	   SELECT @lNextNumber AS Result	   
	   COMMIT TRANSACTION
	   		
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveApproveValidate]

        @rId bigint,
        @rEmployeeId bigint,
        @rFromDate date,
        @rLeaveTypeId int,
        @rNoOfLeave decimal(5,2),
        @rBatchId int,
        @rOrgId int
        
AS
SET NOCOUNT ON

BEGIN
	IF EXISTS (SELECT 1 FROM  sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId AND isLwp = 0)
	BEGIN
	   DECLARE @lMainLeaveTypeId tinyint
	   SET @lMainLeaveTypeId =0
	   SELECT @lMainLeaveTypeId = ISNULL(MainLeaveTypeId,0) FROM sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId
	   
	   DECLARE @lMaxInMonth decimal(5,2)
	   DECLARE @lNumberOfLeave decimal(5,2)
	   SET @lMaxInMonth =0
	   SET @lNumberOfLeave =0
	   
	   DECLARE @lFirstDate date
	   DECLARE @lLastDate date
	   
	   SET @lFirstDate = DATEADD(mm, DATEDIFF(mm, 0, @rFromDate), 0)
	   SET @lLastDate = DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, @rFromDate) + 1, 0))
	   
	   SELECT @lMaxInMonth = ISNULL(LB.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
	   INNER JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EJD.EmployeeId AND LB.BatchId = @rBatchId
	   WHERE EJD.OrgId = @rOrgId AND LB.LeaveTypeId=@rLeaveTypeId AND EJD.EmployeeId=@rEmployeeId
	   
	   -- For Employee Specific 08/11/2017 - by Ramesh Gurjar
	   IF(@lMaxInMonth=0)
	   BEGIN
			SELECT @lMaxInMonth = ISNULL(LTGS.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
			INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON EJD.EmployeeGradeId=LTGS.EmployeeGradeId 
			WHERE LTGS.OrgId = @rOrgId 
			AND LTGS.LeaveTypeId=@rLeaveTypeId 
			AND  EJD.EmployeeId=@rEmployeeId
	   END
	   
	   --BEGIN LEAVE CARY FORWARD VALIDATION
		DECLARE @lLeaveCarryForwordRuleId int=1
		DECLARE @lMonthDiffrence int
		Declare @lDateofJoining date = (SELECT DateOfJoining FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rEmployeeId)
		 SELECT @lLeaveCarryForwordRuleId=ISNULL(LTGS.LeaveCarryForwordRuleId,1) FROM sHrm.tEmployeeJobDetail EJD
		 INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON EJD.EmployeeGradeId=LTGS.EmployeeGradeId 
		 WHERE LTGS.OrgId =@rOrgId
		 AND LTGS.LeaveTypeId=@rLeaveTypeId
		 AND  EJD.EmployeeId=@rEmployeeId

		 
		 if(@lLeaveCarryForwordRuleId=1)
		 Begin
		  set @lMaxInMonth=@lMaxInMonth
		 END
		 else if(@lLeaveCarryForwordRuleId=2)
		 Begin
			 select @lMaxInMonth= Case When @lDateofJoining<LeaveYearFromDate Then @lMaxInMonth*(DATEDIFF(month,LeaveYearFromDate,@rFromDate)+1) else @lMaxInMonth*(DATEDIFF(month,LeaveYearFromDate,@lDateofJoining)+1) end 
			 ,@lFirstDate=Case When @lDateofJoining<LeaveYearFromDate Then LeaveYearFromDate else @lDateofJoining END from [sSetup].[tBatchMaster] WHere Id=@rBatchId
		 END
		
	   --END LEAVE CARY FORWARD VALIDATION
	   


	   SELECT  @lNumberOfLeave= ISNULL(SUM(L.NoOfLeave),0) 
	   FROM     
	   sHrm.tLeave L  
	   WHERE  
	   L.EmployeeId=@rEmployeeId 
	   AND (L.FromDate>=@lFirstDate) AND (L.FromDate<=@lLastDate)
	   AND L.LeaveTypeId=@rLeaveTypeId AND L.StatusId = 550
	   GROUP BY L.EmployeeId
	   
	   IF (@lMaxInMonth < (@lNumberOfLeave+@rNoOfLeave) AND @lMainLeaveTypeId!=3)
	   BEGIN
			SELECT -105  AS RESULT
			RETURN
	   END
	   ELSE
	   BEGIN
			SELECT 1
	   END	
   END
   ELSE 
   SELECT 1
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceAdd]
	 
        @rId bigint,
        @rEmployeeId bigint,
        @rReportDate date,
        @rLeaveTypeId int,
        @rAddBalance decimal(5,2),
        @rBatchId int,
        @rAddBalanceRemark nvarchar(200),
        @rCreatedUserId bigint,
        @rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 IF(@rId = 0)
	 BEGIN
		   IF EXISTS(SELECT 1 FROM sHrm.tLeaveBalanceAdd WHERE EmployeeId = @rEmployeeId AND ReportDate = @rReportDate AND BatchId = @rBatchId AND LeaveTypeId = @rLeaveTypeId)
		   BEGIN
				SELECT -101  AS Result
				RETURN
		   END
	 END

	 BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lBalanceLeave decimal(5,2) 
	 SET @lBalanceLeave = 0.00
	 DECLARE @lUpdateBalanceLeave decimal(5,2) 
	 SET @lUpdateBalanceLeave = 0.00	
	
	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeaveBalanceAdd', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHrm.tLeaveBalanceAdd
		(
			Id,
			EmployeeId,
			ReportDate,
			LeaveTypeId,
			AddBalance,
			BatchId,
			AddBalanceRemark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rEmployeeId,
			@rReportDate,
			@rLeaveTypeId,
			@rAddBalance,
			@rBatchId,
			@rAddBalanceRemark,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
	
	
	SELECT @lBalanceLeave=BalanceLeave FROM sHrm.tLeaveBalance  WHERE EmployeeId = @rEmployeeId AND LeaveTypeId = @rLeaveTypeId AND BatchId = @rBatchId
	
	-- Add Leave Balance Log
	INSERT INTO sHrm.tLeaveBalanceLog 
	SELECT @rEmployeeId,@rLeaveTypeId,@lBalanceLeave,3,@rAddBalance,
	'Add Leave Balance',@rBatchId,@rCreatedUserId,sCommon.fGetDate()
	
	DELETE FROM sHrm.tLeaveBalance  
	WHERE EmployeeId = @rEmployeeId 
	AND LeaveTypeId = @rLeaveTypeId 
	AND BatchId = @rBatchId
	 	
	INSERT INTO sHrm.tLeaveBalance
		(
			EmployeeId,
			LeaveTypeId,
			BalanceLeave,
			BatchId
		)
	VALUES
		(
			@rEmployeeId,
			@rLeaveTypeId,
			@rAddBalance+@lBalanceLeave,
			@rBatchId
		)
		    SELECT 1,@lNextNumber AS Result
	END	 
ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    
	    SELECT @lBalanceLeave=AddBalance FROM sHrm.tLeaveBalanceAdd WHERE Id=@rId
	    
	    UPDATE  sHrm.tLeaveBalanceAdd
	    SET
			EmployeeId=@rEmployeeId,
			ReportDate=@rReportDate,
			LeaveTypeId=@rLeaveTypeId,
			AddBalance=@rAddBalance,
			AddBalanceRemark=@rAddBalanceRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	    WHERE Id = @rId
	  
	    SELECT @lUpdateBalanceLeave=BalanceLeave FROM sHrm.tLeaveBalance  WHERE EmployeeId = @rEmployeeId AND LeaveTypeId = @rLeaveTypeId AND BatchId = @rBatchId
	  
		UPDATE sHrm.tLeaveBalance
		SET
			BalanceLeave= @lUpdateBalanceLeave + (@rAddBalance-@lBalanceLeave)
		WHERE EmployeeId = @rEmployeeId 
		AND LeaveTypeId = @rLeaveTypeId 
		AND BatchId = @rBatchId	 	
			SELECT 11 AS Result
	 END  

	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceAddDelete]
	 
	@rId bigint,
    @rEmployeeId bigint,
    @rLeaveTypeId int,
    @rAddBalance decimal(5,2),
    @rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DECLARE @lBalanceLeave decimal(5,2) 
		SET @lBalanceLeave = 0.00
		
		DELETE FROM sHrm.tLeaveBalanceAdd WHERE Id = @rId
		
		SELECT @lBalanceLeave=BalanceLeave FROM sHrm.tLeaveBalance  WHERE EmployeeId = @rEmployeeId AND LeaveTypeId = @rLeaveTypeId AND BatchId = @rBatchId
		
		UPDATE sHrm.tLeaveBalance
		SET
			BalanceLeave= @lBalanceLeave - @rAddBalance
		WHERE EmployeeId = @rEmployeeId 
		AND LeaveTypeId = @rLeaveTypeId 
		AND BatchId = @rBatchId	 	
		
		SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceAddGet]

	 @rId int,
	 @rCode nvarchar(20),
	 @rName nvarchar(100),
	 @rFromReportDate date,
	 @rToReportDate date,
	 @rLeaveTypeId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	SELECT 
			LBA.Id,
			LBA.EmployeeId,
			ECD.Code,
			ECD.EmployeeName,
			ECD.DepartmentName,
			LBA.ReportDate,
			LBA.AddBalance,
			LBA.BatchId,
			LBA.AddBalanceRemark,
			LBA.LeaveTypeId,
			LTM.Title AS LeaveTypeName
			
	FROM 
			sHrm.tLeaveBalanceAdd LBA
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LBA.LeaveTypeId AND LTM.IsLWP=0
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON LBA.EmployeeId = ECD.EmployeeId
	WHERE 
		(LBA.BatchId = @rBatchId)
		AND	((LBA.Id = @rId) OR (@rId = 0))
		AND ((LBA.ReportDate>=@rFromReportDate) OR (ISNULL(@rFromReportDate,'')=''))
		AND ((LBA.ReportDate<=@rToReportDate) OR (ISNULL(@rToReportDate,'')=''))
		AND ((LBA.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
		AND ((ECD.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND ((ECD.EmployeeName like @rName) OR (ISNULL(@rName,'')=''))
		AND  ISNULL(ECD.IsOtherUser,0)=0
		ORDER BY ECD.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceAddRequestAdd]
	 
        @rId bigint,
        @rEmployeeId bigint,
        @rReportDate date,
        @rLeaveTypeId int,
        @rAddRequestBalance decimal(5,2),
        @rBatchId int,
        @rAddRequestBalanceRemark nvarchar(200),
        @rCreatedUserId bigint,
        @rOrgId int,
        @rWorkedHours decimal(5,2)=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	   IF(@rId = 0)
	   BEGIN
		   IF EXISTS(SELECT 1 FROM sHrm.tLeaveBalanceAddRequest WHERE LeaveTypeId = @rLeaveTypeId AND EmployeeId = @rEmployeeId AND ReportDate = @rReportDate AND BatchId = @rBatchId AND StatusId!=551)
		   BEGIN
				SELECT -101  AS Result
				RETURN
		   END
	   END
	    
	 BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 DECLARE @lNextNumber BIGINT 
	
	IF(@rId = 0)	
	BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeaveBalanceAddRequest', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sHrm.tLeaveBalanceAddRequest
			(
				Id,
				EmployeeId,
				ReportDate,
				LeaveTypeId,
				AddRequestBalance,
				BatchId,
				AddRequestBalanceRemark,
				StatusId,
				CreatedUserId,
				CreatedDateTime,
				WorkedHours
			)
		VALUES
			(
				@lNextNumber,
				@rEmployeeId,
				@rReportDate,
				@rLeaveTypeId,
				@rAddRequestBalance,
				@rBatchId,
				@rAddRequestBalanceRemark,
				549,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rWorkedHours
			)
		SELECT 1,@lNextNumber AS Result
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    
	    UPDATE sHrm.tLeaveBalanceAddRequest
	    SET
			EmployeeId=@rEmployeeId,
			ReportDate=@rReportDate,
			LeaveTypeId=@rLeaveTypeId,
			AddRequestBalance=@rAddRequestBalance,
			AddRequestBalanceRemark=@rAddRequestBalanceRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			WorkedHours = @rWorkedHours
	    WHERE Id = @rId
		SELECT 11 AS Result
	 END  

	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceAddRequestDelete]
	 
	@rId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DELETE FROM sHrm.tLeaveBalanceAddRequest WHERE Id = @rId
		SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceAddRequestGet]

	 @rId int,
	 @rCode nvarchar(20),
	 @rName nvarchar(100),
	 @rFromReportDate date,
	 @rToReportDate date,
	 @rLeaveTypeId int,
	 @rBatchId int,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	SELECT 
			LBAR.Id,
			LBAR.EmployeeId,
			ECD.Code,
			ECD.EmployeeName,
			ECD.DepartmentName,
			LBAR.ReportDate,
			LBAR.AddRequestBalance,
			LBAR.BatchId,
			LBAR.AddRequestBalanceRemark,
			LBAR.LeaveTypeId,
			LTM.Title AS LeaveTypeName,
			LBAR.StatusId,
		    SM.Title AS StatusName,
		    ISNULL(LBAR.WorkedHours,0) AS WorkedHours
	FROM 
			sHrm.tLeaveBalanceAddRequest LBAR
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LBAR.LeaveTypeId AND LTM.IsLWP=0
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON LBAR.EmployeeId = ECD.EmployeeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = LBAR.StatusId
	WHERE 
		(LBAR.BatchId = @rBatchId)
		AND	((LBAR.Id = @rId) OR (@rId = 0))
		AND ((LBAR.ReportDate>=@rFromReportDate) OR (ISNULL(@rFromReportDate,'')=''))
		AND ((LBAR.ReportDate<=@rToReportDate) OR (ISNULL(@rToReportDate,'')=''))
		AND ((LBAR.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
		AND ((ECD.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND ((ECD.EmployeeName like @rName) OR (ISNULL(@rName,'')=''))
		AND (LBAR.StatusId = @rStatusId OR @rStatusId = 0)
		ORDER BY ECD.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceAdjustGet]

	 @rId int,
	 @rCode nvarchar(20),
	 @rName nvarchar(100),
	 @rFromReportDate date,
	 @rToReportDate date,
	 @rLeaveTypeId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	SELECT 
			LBL.Id,
			LBL.EmployeeId,
			ECD.Code,
			ECD.EmployeeName,
			ECD.DepartmentName,
			LBL.CreatedDateTime AS ReportDate,
			LBL.TransactionLeave AS AdjustBalance,
			ISNULL(LBL.BalanceLeave,0) AS BalanceLeave,
			LBL.BatchId,
			LBL.Remark,
			LBL.LeaveTypeId,
			LTM.Title AS LeaveTypeName
	FROM 
			sHrm.tLeaveBalanceLog LBL
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LBL.LeaveTypeId AND LTM.IsLWP=0
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON LBL.EmployeeId = ECD.EmployeeId
	WHERE 
		(LBL.BatchId = @rBatchId)
		AND	((LBL.Id = @rId) OR (@rId = 0))
		AND ((CONVERT(DATE, LBL.CreatedDateTime)>=@rFromReportDate) OR (ISNULL(@rFromReportDate,'')=''))
		AND ((CONVERT(DATE, LBL.CreatedDateTime)<=@rToReportDate) OR (ISNULL(@rToReportDate,'')=''))
		AND ((LBL.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
		AND ((ECD.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND ((ECD.EmployeeName like @rName) OR (ISNULL(@rName,'')=''))
		AND LBL.LeaveTransactionId = 5
		AND ECD.IsOtherUser = 0
		ORDER BY ECD.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceAdjustModify]
	 
        @rEmployeeId bigint,
        @rLeaveTypeId int,
        @rAdjustBalance decimal(5,2),
        @rBatchId int,
        @rRemark nvarchar(200),
        @rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	 
	DECLARE @lBalanceLeave decimal(8,2) = 0
	SELECT @lBalanceLeave=BalanceLeave FROM sHrm.tLeaveBalance  WHERE EmployeeId = @rEmployeeId AND LeaveTypeId = @rLeaveTypeId AND BatchId = @rBatchId
		
	DELETE FROM sHrm.tLeaveBalance  
	WHERE EmployeeId = @rEmployeeId 
	AND LeaveTypeId = @rLeaveTypeId 
	AND BatchId = @rBatchId
	
	INSERT INTO sHrm.tLeaveBalance
		(
			EmployeeId,
			LeaveTypeId,
			BalanceLeave,
			BatchId
		)
	VALUES
		(
			@rEmployeeId,
			@rLeaveTypeId,
			@rAdjustBalance+@lBalanceLeave,
			@rBatchId
		)
		
	-- Add Leave Balance Log
	INSERT INTO sHrm.tLeaveBalanceLog 
	SELECT @rEmployeeId,@rLeaveTypeId,@lBalanceLeave,5,@rAdjustBalance,
	@rRemark,@rBatchId,@rCreatedUserId,sCommon.fGetDate()
		
	SELECT 1 AS Result

	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceApproved_RejectedAdd]
	 
        @rId bigint,
        @rEmployeeId bigint,
        @rReportDate date,
        @rLeaveTypeId int,
        @rAddBalance decimal(5,2),
        @rBatchId int,
        @rAddBalanceRemark nvarchar(200),
        @rCreatedUserId bigint,
        @rOrgId int,
        @rStatusId int=0,
        @rStatusRemark nvarchar(200)='',
        @rLeaveBalanceAddRequestId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lBalanceLeave decimal(5,2) 
	 SET @lBalanceLeave = 0.00
	 DECLARE @lUpdateBalanceLeave decimal(5,2) 
	 SET @lUpdateBalanceLeave = 0.00	
	
	IF(@rStatusId=550)
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeaveBalanceAdd', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sHrm.tLeaveBalanceAdd
		(
			Id,
			EmployeeId,
			ReportDate,
			LeaveTypeId,
			AddBalance,
			BatchId,
			AddBalanceRemark,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rEmployeeId,
			@rReportDate,
			@rLeaveTypeId,
			@rAddBalance,
			@rBatchId,
			@rAddBalanceRemark,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
	
	SELECT @lBalanceLeave=BalanceLeave FROM sHrm.tLeaveBalance  WHERE EmployeeId = @rEmployeeId AND LeaveTypeId = @rLeaveTypeId AND BatchId = @rBatchId
	
	-- Add Leave Balance Log
	INSERT INTO sHrm.tLeaveBalanceLog 
	SELECT @rEmployeeId,@rLeaveTypeId,@lBalanceLeave,3,@rAddBalance,
	'Add Leave Balance - Approved',@rBatchId,@rCreatedUserId,sCommon.fGetDate()
	
	DELETE FROM sHrm.tLeaveBalance  
	WHERE EmployeeId = @rEmployeeId 
	AND LeaveTypeId = @rLeaveTypeId 
	AND BatchId = @rBatchId
	 	
	INSERT INTO sHrm.tLeaveBalance
		(
			EmployeeId,
			LeaveTypeId,
			BalanceLeave,
			BatchId
		)
	VALUES
		(
			@rEmployeeId,
			@rLeaveTypeId,
			@rAddBalance+@lBalanceLeave,
			@rBatchId
		)
	
	IF(@rStatusId=550) -- Approved
	BEGIN
			UPDATE sHrm.tLeaveBalanceAddRequest 
			SET StatusId= @rStatusId,
			StatusRemark=@rStatusRemark, 
			LeaveBalanceAddId=@lNextNumber
			WHERE EmployeeId = @rEmployeeId AND Id=@rLeaveBalanceAddRequestId
	END
	
		    SELECT 1 AS Result
	END
	
	IF(@rStatusId=551) -- Rejected
	BEGIN
		
		DECLARE @lStatusId int=0
		
		SELECT @lStatusId=StatusId FROM sHrm.tLeaveBalanceAddRequest  WHERE Id = @rLeaveBalanceAddRequestId
		
		SET @lBalanceLeave = 0.00
		
		DELETE FROM sHrm.tLeaveBalanceAdd WHERE Id = @rId
		
		SELECT @lBalanceLeave=BalanceLeave FROM sHrm.tLeaveBalance  WHERE EmployeeId = @rEmployeeId AND LeaveTypeId = @rLeaveTypeId AND BatchId = @rBatchId
		
		IF(@lStatusId=550)
		BEGIN
			UPDATE sHrm.tLeaveBalance
			SET
				BalanceLeave= @lBalanceLeave - @rAddBalance
			WHERE EmployeeId = @rEmployeeId 
			AND LeaveTypeId = @rLeaveTypeId 
			AND BatchId = @rBatchId	 	
			
			-- Add Leave Balance Log
			INSERT INTO sHrm.tLeaveBalanceLog 
			SELECT @rEmployeeId,@rLeaveTypeId,@lBalanceLeave-@rAddBalance,3,@rAddBalance,
			'Add Leave Balance - Rejected',@rBatchId,@rCreatedUserId,sCommon.fGetDate()
		END
		
		UPDATE sHrm.tLeaveBalanceAddRequest 
		SET StatusId= @rStatusId,
		StatusRemark=@rStatusRemark, 
		LeaveBalanceAddId=0
		WHERE EmployeeId = @rEmployeeId AND Id=@rLeaveBalanceAddRequestId
			
		SELECT 1 AS Result
	END
			 
	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceBulkAdd]
	 	
	@rStrXml [nvarchar](max),
	@rBatchId int
	 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN 
	 BEGIN	
		UPDATE LB 
		SET
		LB.BalanceLeave = A.BalanceLeave   
		FROM sHrm.tLeaveBalance LB
		INNER JOIN OPENXML (@loDoc, '/Table/BalanceLeave', 1)
			WITH ( 				
						EmployeeId bigint,
						LeaveTypeId int,
						BalanceLeave decimal(5,2)
				  ) A 
		ON LB.EmployeeId = A.EmployeeId
		AND LB.LeaveTypeId=A.LeaveTypeId
		AND LB.BatchId = @rBatchId
		
		INSERT INTO  sHrm.tLeaveBalance
			(EmployeeId,LeaveTypeId,BalanceLeave,BatchId)
			SELECT	
			A.EmployeeId,A.LeaveTypeId,A.BalanceLeave,@rBatchId
			FROM OPENXML (@loDoc, '/Table/BalanceLeave', 1)
			WITH ( 				
					EmployeeId bigint,
					LeaveTypeId int,
					BalanceLeave decimal(5,2)
				  ) A  
				  LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = A.EmployeeId 
				  AND LB.LeaveTypeId=A.LeaveTypeId  AND @rBatchId = LB.BatchId 
			      WHERE 
			      (LB.EmployeeId IS NULL AND LB.LeaveTypeId IS NULL AND LB.BatchId IS NULL)
			      
		-- Add Leave Balance Log
		INSERT INTO sHrm.tLeaveBalanceLog 
			SELECT	
			A.EmployeeId,A.LeaveTypeId,A.BalanceLeave,2,A.BalanceLeave,'Balance Add', @rBatchId,0,sCommon.fGetDate()
			FROM OPENXML (@loDoc, '/Table/BalanceLeave', 1)
			WITH ( 				
					EmployeeId bigint,
					LeaveTypeId int,
					BalanceLeave decimal(5,2)
				  ) A  
				  LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = A.EmployeeId 
				  AND LB.LeaveTypeId=A.LeaveTypeId  AND @rBatchId = LB.BatchId 
			      WHERE 
			      (LB.EmployeeId IS NULL AND LB.LeaveTypeId IS NULL AND LB.BatchId IS NULL)      
			      
		--DELETE FROM sHrm.tLeaveBalance WHERE BalanceLeave=0.00 AND BatchId = @rBatchId	      
		
 		SELECT 1 AS Result
 		
	END		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceBulkGet]

	  @rEmployeeTypeId int=0,
	  @rEmployeeGroupId int=0,
	  @rEmployeeGradeId int=0,
	  @rDepartmentId int=0,
	  @rLeaveTypeId int=0,
	  @rOrgId int,
	  @rBatchId int 
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
	SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(LTM.Title) FROM sHrm.tLeaveTypeMaster LTM
				 WHERE ((LTM.Id=@rLeaveTypeId)OR (@rLeaveTypeId=0)) AND ((LTM.OrgId=@rOrgId)OR (@rOrgId=0)) AND IsLWP=0
				 ORDER BY LTM.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'),1,1,'')
       
	SET @query = 'SELECT EmployeeId,Code,EmployeeName,DepartmentName,EmployeeDesignation,DateOfJoining,EmployeeGrade,Number, ' + @cols + '
	FROM
	(
		SELECT 
		ECD.EmployeeId,
		ECD.Code,
		ECD.EmployeeName,
		ECD.DepartmentName,
		EDM.Title AS EmployeeDesignation, 
		LTM.Title,
		ECD.DateOfJoining,
		ECD.EmployeeGrade,
		ECD.Number,
		CASE WHEN LB.BalanceLeave IS NULL THEN ISNULL(LTGS.NoOfLeave,0) ELSE ISNULL(LB.BalanceLeave,0) END AS BalanceLeave
		
	FROM  
	sHrm.vEmployeeCommonDetail ECD 
	INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.OrgId = ECD.OrgID AND LTGS.EmployeeGradeId =  ECD.EmployeeGradeId
	LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = ECD.EmployeeDesignationId
	LEFT JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id= LTGS.LeaveTypeId
	LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = ECD.EmployeeId  AND LB.LeaveTypeId = LTGS.LeaveTypeId AND LB.BatchId = '+ CONVERT(nvarchar,@rBatchId) + '
	WHERE 
	ECD.EmployeeStatusId = 7 AND ISNULL(ECD.IsOtherUser,0)=0
	AND ((ECD.EmployeeTypeId= '+ CONVERT(nvarchar,@rEmployeeTypeId) + ') OR ('+ CONVERT(nvarchar,@rEmployeeTypeId) + '= '+ CONVERT(nvarchar,0) + '))
	AND ((ECD.EmployeeGroupId= ' + CONVERT(nvarchar,@rEmployeeGroupId) + ') OR (' + CONVERT(nvarchar,@rEmployeeGroupId) + '= ' + CONVERT(nvarchar,0) + '))
	AND ((ECD.EmployeeGradeId= ' + CONVERT(nvarchar,@rEmployeeGradeId) + ') OR (' + CONVERT(nvarchar,@rEmployeeGradeId) + '= ' + CONVERT(nvarchar,0) + '))
	AND ((ECD.OrgId= ' + CONVERT(nvarchar,@rOrgId) + ') OR (' + CONVERT(nvarchar,@rOrgId) + '= ' + CONVERT(nvarchar,0) + '))
	AND ((ECD.DepartmentId= ' + CONVERT(nvarchar,@rDepartmentId) + ' ) OR (' + CONVERT(nvarchar,@rDepartmentId) + '= ' + CONVERT(nvarchar,0) + ' ))
	 ) MAIN
	PIVOT
	(max(BalanceLeave)
	FOR Title IN (' + @cols + ')
	)pvt Order by Number'
	
	
EXECUTE(@query)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceListingGet]

    @rId bigint = 0,
    @rEmployeeId  bigint,   
    @rLeaveTypeId int,
	@rFromDate date,
    @rTodate date,
    @rOrgGroupBatchId int,
    @rEmployeeCode nvarchar(100),
    @rEmployeeName nvarchar(100),
    @rStatusId int = 0,
    @rOrgId int = 0

AS
SET NOCOUNT ON

BEGIN
    
	SELECT 
		   LBAR.Id AS LeaveBalanceAddRequestId
		  ,LBAR.EmployeeId
		  ,LBAR.ReportDate
		  ,LBAR.LeaveTypeId
		  ,LBAR.AddRequestBalanceRemark
		  ,LTM.Title AS LeaveType
		  ,EM.EmployeeName
		  ,EM.Code AS EmployeeCode
		  ,LBAR.AddRequestBalance
		  ,ISNULL(LBAR.StatusId,0) AS StatusId
		  ,ISNULL(SM.Title,'Pending') AS StatusName
		  ,ISNULL(LBAR.StatusRemark,'') AS StatusRemark
		  ,ISNULL(LBAR.WorkedHours,0) AS WorkedHours
  FROM 
	  sHrm.tLeaveBalanceAddRequest LBAR
	  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = LBAR.BatchId		
	  INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LBAR.LeaveTypeId
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = LBAR.EmployeeId
	  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = LBAR.EmployeeId
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = LBAR.StatusId
  WHERE 
	  (LBAR.Id = @rId OR @rId = 0)
      AND (EJD.EmployeeManagerId = @rEmployeeId OR @rEmployeeId = 0)
      AND (LBAR.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)      
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (LBAR.StatusId = @rStatusId OR @rStatusId = 0)      
      AND ((LBAR.ReportDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((LBAR.ReportDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	  AND EM.IsOtherUser = 0
      AND BM.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceLogGet]
	 @rCode nvarchar(20),
	 @rName nvarchar(100),
	 @rLeaveTypeId int,
	 @rLeaveTransactionId tinyint,
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	SELECT 
			ECD.Code,
			ECD.EmployeeName,
			ECD.DepartmentName,
			LBL.CreatedDateTime AS LogDate,
			--LBL.TransactionLeave AS TransactionLeave,			
			case when LeaveTransactionId=2 then ISNULL(LBL.TransactionLeave,0) else CONVERT(decimal(16,2), ISNULL(LBL.BalanceLeave,0)) + CONVERT(decimal(16,2), ISNULL(LBL.TransactionLeave,0)) end as TransactionLeave,		
			ISNULL(LBL.BalanceLeave,0) AS BalanceLeave,			
			case when LeaveTransactionId=2 then ISNULL(LBL.TransactionLeave,0)-ISNULL(LBL.BalanceLeave,0) 
			else (CONVERT(decimal(16,2), ISNULL(LBL.BalanceLeave,0)) + CONVERT(decimal(16,2), ISNULL(LBL.TransactionLeave,0)))-ISNULL(LBL.BalanceLeave,0) end as TransactionCount,
			LBL.BatchId,
			LBL.Remark,
			LBL.LeaveTypeId,
			LTM.Title AS LeaveTypeName,		
			LT.Title  +' ('+ CONVERT(Nvarchar(max), ISNULL(LBL.BalanceLeave,0)) +' To '+CONVERT(Nvarchar(max), ISNULL(LBL.TransactionLeave,0))+')' As LeaveTransactionType,
			ISNULL(LB.BalanceLeave,0) AS UpdatedBalance
	FROM
			sHrm.tLeaveBalanceLog LBL
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LBL.LeaveTypeId AND LTM.IsLWP=0
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON LBL.EmployeeId = ECD.EmployeeId
			INNER JOIN sHrm.tLeaveTransactionMaster LT ON LT.Id=LBL.LeaveTransactionId 
			LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = LBL.EmployeeId AND LB.LeaveTypeId = LBL.LeaveTypeId AND  LB.BatchId =  LBL.BatchId 
	WHERE 
		(LBL.BatchId = @rBatchId)
		AND ((CONVERT(DATE, LBL.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(DATE, LBL.CreatedDateTime)<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((LBL.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
		AND ((ECD.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND ((ECD.EmployeeName like @rName) OR (ISNULL(@rName,'')=''))
		AND ((LBL.LeaveTransactionId = @rLeaveTransactionId) OR (@rLeaveTransactionId = 0))
		AND LT.IsObsolete=0
		AND ISNULL(ECD.IsOtherUser,0)=0		
	ORDER BY LBL.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceTypewiseAdd]
	 
	@rEmployeeId bigint,
	@rLeaveTypeId int,
	@rBalanceLeave decimal(8,2),
	@rBatchId int,
	@rUserId bigint,
	@rMaxInMonth decimal(5,2) = 0,
	@rLastYearBalanceLeave decimal(8,2) = 0,
	@rCurrentBalanceLeave decimal(8,2) = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
	BEGIN TRANSACTION	
		
		DECLARE @lBalanceLeave decimal(8,2) = 0
		SELECT @lBalanceLeave =  BalanceLeave FROM sHrm.tLeaveBalance WHERE EmployeeId=@rEmployeeId AND LeaveTypeId=@rLeaveTypeId AND BatchId=@rBatchId

		DELETE FROM sHrm.tLeaveBalance WHERE EmployeeId=@rEmployeeId AND LeaveTypeId=@rLeaveTypeId AND BatchId=@rBatchId
		
		INSERT INTO sHrm.tLeaveBalance
			(
				EmployeeId,
				LeaveTypeId,
				BalanceLeave,
				BatchId,
				MaxInMonth,
				LastYearBalanceLeave,
				CurrentBalanceLeave
			)
		VALUES
			(
				@rEmployeeId,
				@rLeaveTypeId,
				@rBalanceLeave,
				@rBatchId,
				@rMaxInMonth,
				@rLastYearBalanceLeave,
				@rCurrentBalanceLeave
			)
			
		INSERT INTO sHrm.tLeaveBalanceLog 
		SELECT @rEmployeeId,@rLeaveTypeId,@lBalanceLeave,2,@rBalanceLeave,
		'Leave Balance',@rBatchId,@rUserId,sCommon.fGetDate()
		
 		SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBalanceTypewiseGet]

	  @rEmployeeTypeId int=0,
	  @rEmployeeGroupId int=0,
	  @rEmployeeGradeId int=0,
	  @rDepartmentId int=0,
	  @rLeaveTypeId int=0,
	  @rOrgId int,
	  @rBatchId int 
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	    
	SELECT 
		ECD.EmployeeId,
		ECD.Code,
		ECD.EmployeeName,
		ECD.DepartmentName,
		ISNULL(EDM.Title,'') AS EmployeeDesignation, 
		CASE WHEN LB.EmployeeId IS NULL THEN CONVERT(bit,0) ELSE CONVERT(bit,1) END AS IsCheck,
		CASE WHEN LB.BalanceLeave IS NULL THEN ISNULL(LTGS.NoOfLeave,0) ELSE ISNULL(LB.BalanceLeave,0) END AS BalanceLeave,
		CASE WHEN LB.MaxInMonth IS NULL THEN ISNULL(LTGS.MaxInMonth,0) ELSE ISNULL(LB.MaxInMonth,0) END AS MaxInMonth,
		ISNULL(LB.LastYearBalanceLeave,0) AS LastYearBalanceLeave,
		ISNULL(LB.CurrentBalanceLeave,0) AS CurrentBalanceLeave,
	    ISNULL((SELECT TOP 1 BalanceLeave  FROM sHrm.tLeaveBalanceLog WHERE EmployeeId = ECD.EmployeeId AND LeaveTypeId=LTGS.LeaveTypeId AND BatchId = @rBatchId AND BalanceLeave!=0 AND LeaveTransactionId=2 ORDER BY CreatedDateTime ASC),0) AS FirstBalanceLeave
	FROM  
		sHrm.vEmployeeCommonDetail ECD 
		INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.OrgId = ECD.OrgID AND LTGS.EmployeeGradeId =  ECD.EmployeeGradeId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = ECD.EmployeeDesignationId
		LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = ECD.EmployeeId  AND LB.LeaveTypeId = @rLeaveTypeId AND LB.BatchId = @rBatchId
	WHERE 
		ECD.EmployeeStatusId = 7
		AND ((ECD.EmployeeTypeId= @rEmployeeTypeId) OR (@rEmployeeTypeId= 0))
		AND ((ECD.EmployeeGroupId= @rEmployeeGroupId) OR (@rEmployeeGroupId= 0))
		AND ((ECD.EmployeeGradeId= @rEmployeeGradeId) OR (@rEmployeeGradeId= 0))
		AND ((ECD.OrgId= @rOrgId) OR (@rOrgId= 0))
		AND ((ECD.DepartmentId= @rDepartmentId ) OR (@rDepartmentId= 0 ))
		AND LTGS.LeaveTypeId = @rLeaveTypeId
		AND ISNULL(ECD.IsOtherUser,0)=0 
	ORDER BY ECD.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sHrm].[pLeaveBulkGet]  
(  
	@rOrgId int,  
    @rEmployeeId  bigint,     
    @rFromDate date,   
    @rTodate date,  
    @rOrgGroupBatchId int,   
    @rOrgGroupId int,  
    @rDepartmentId int,
	@rStatusId int = 0
	 
 )  
AS  
SET NOCOUNT ON  

BEGIN
		SELECT 
		EM.EmployeeId,
		EMP.FirstName +' '+EMP.MiddleName+' '+EMP.LastName As EmployeeName,
		EMP.Code As EmployeeCode,
		EAR.AttendanceDate As LeaveDate,
		EAR.IsPresent
		
		FROM 
		sHrm.tEmployeeAttendanceRegister EAR
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EAR.BatchId    
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
		LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = EAR.EmployeeId 
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = EAR.EmployeeId   
		WHERE EAR.EmployeeId 
		NOT IN (SELECT EmployeeId FROM sHrm.tLeave WHERE Fromdate >=AttendanceDate AND TODATE <=AttendanceDate)
		--AND  AttendanceDate >=@rFromDate AND AttendanceDate <=@rToDate
		AND  ((AttendanceDate >=@rFromDate)  OR (ISNULL(@rFromDate,'')=''))
		AND ((AttendanceDate <=@rToDate)  OR (ISNULL(@rToDate,'')=''))
		and IsPresent=0
		AND ((EM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		AND ((EMP.OrgId = @rOrgId) OR (@rOrgId = 0)) 
		AND ((EMP.StatusId = @rStatusId) OR (@rStatusId = 0))
		--ORDER BY EMP.Code

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pLeaveHierarchyLevelAdd]
        --@rId bigint,   
        @rLeaveId bigint,
        @rStatusId int,
        --@rRemark nvarchar(500),
        @rEmployeeId bigint,
		@rOrgId int
       
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

	BEGIN
	DECLARE @lActionByEmployeeId bigint
	SELECT @lActionByEmployeeId = EmployeeManagerId from [sHrm].[tEmployeeJobDetail] WHere EmployeeId = @rEmployeeId AND OrgId = @rOrgId
	IF(@lActionByEmployeeId > 0)
     BEGIN
		INSERT INTO [sHrm].[tLeaveHierarchyLevel]
			   (LeaveId
			   ,StatusId
			   ,Remark
			   ,ActionByEmployeeId
			   ,ActionDatetime)
		 VALUES
			   (@rLeaveId
			   ,@rStatusId
			   ,''
			   ,@lActionByEmployeeId
			   ,sCommon.fGetDate())
	 END
	END

	 SELECT 1 AS Result	   
	   COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pLeaveHierarchyLevelUpdate]
        @rLeaveHierarchyLevelId bigint,   
		@rStatusId int,
		@rHierarchyLevelCount int,
        @rLeaveId bigint,
        @rRemark nvarchar(500),
        @rEmployeeId bigint,
		@rOrgId int
       
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

	BEGIN
	DECLARE @lActionByEmployeeId bigint
	SELECT @lActionByEmployeeId = EmployeeManagerId from [sHrm].[tEmployeeJobDetail] WHere EmployeeId = @rEmployeeId 
	--AND OrgId = @rOrgId

	UPDATE [sHrm].[tLeaveHierarchyLevel] SET StatusId = @rStatusId , Remark = @rRemark WHERE AutoId = @rLeaveHierarchyLevelId

	DECLARE @lLeaveCount int
	SELECT @lLeaveCount = COUNT(AutoId) FROM [sHrm].[tLeaveHierarchyLevel] WHERE LeaveId = @rLeaveId

	IF(@rStatusId = 550)
	BEGIN
		IF(@rHierarchyLevelCount <> @lLeaveCount)
		BEGIN
			 --IF (@rStatusId = 550)
			 --BEGIN
				INSERT INTO [sHrm].[tLeaveHierarchyLevel]
					   (LeaveId
					   ,StatusId
					   ,Remark
					   ,ActionByEmployeeId
					   ,ActionDatetime)
				 VALUES
					   (@rLeaveId
					   ,549
					   ,''
					   ,@lActionByEmployeeId
					   ,sCommon.fGetDate())

						SELECT 0 AS Result 
			 --END
		END
		ELSE
		BEGIN
			 UPDATE [sHrm].[tLeave] SET StatusId = @rStatusId Where Id = @rLeaveId
			 
			 SELECT @rStatusId AS Result 
			
		END
	END
	ELSE
	BEGIN
		UPDATE [sHrm].[tLeave] SET StatusId = @rStatusId Where Id = @rLeaveId
			--IF(@rHierarchyLevelCount = @lLeaveCount)
			--BEGIN
				DELETE FROM [sHrm].[tLeaveHierarchyLevel] Where LeaveId = @rLeaveId AND ActionByEmployeeId = @lActionByEmployeeId
			--END
		SELECT @rStatusId AS Result 
	END
	
	END 	   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sHrm].[pLeaveHierarchyListingAllGet]  
(  
	@rOrgId int,  
	@rLeaveHierarchyLevelId bigint = 0,
    @rEmployeeId  bigint,     
    @rFromDate date,  
    @rLeaveTypeId int,  
    @rTodate date,  
    @rOrgGroupBatchId int,  
    @rEmployeeCode nvarchar(100)='',  
    @rEmployeeName nvarchar(100)='',  
    @rStatusId int = 0,  
    @rDepartmentId int,
	@rIsAdmin bit = 0
 )  
AS  
SET NOCOUNT ON  
  
IF(@rIsAdmin = 0)

BEGIN  
 
IF OBJECT_ID('tempdb..#EmployeeListTemp') IS NOT NULL
	BEGIN
		DROP TABLE #EmployeeListTemp;
	END     
	CREATE Table #EmployeeListTemp(EmployeeId Bigint, EmployeeName nvarchar(50))

	DECLARE @lHierarchyLevel int
	DECLARE @lOrgId int
	IF (@rOrgId = 0) BEGIN SET @lOrgId = LEFT(@rEmployeeId,4) END ELSE BEGIN SET @lOrgId = @rOrgId END
	SELECT @lHierarchyLevel = ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 485 AND SourceTypeId = 1016 AND SourceId = @lOrgId

	DECLARE @lTempEmployeeIdList NVARCHAR(MAX);
	DECLARE @lTempEmployeeId NVARCHAR(MAX);
	DECLARE @lCount1 int = 1

	SET @lTempEmployeeIdList = CONVERT(nvarchar(Max),@rEmployeeId)

While @lHierarchyLevel > @lCount1
	BEGIN
		INSERT INTO #EmployeeListTemp
			SELECT EJD.EmployeeId,EM.ShortName FROM sHrm.tEmployeeJobDetail EJD INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId Where EmployeeManagerId IN (SELECT cast(item as BigInt) FROM sCommon.fnsplit(@lTempEmployeeIdList,','))

		SET @lTempEmployeeId = STUFF((
		SELECT ',' + CAST(EJD.EmployeeId AS NVARCHAR(MAX))
		FROM sHrm.tEmployeeJobDetail EJD INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId Where EmployeeManagerId IN (SELECT cast(item as BigInt) FROM sCommon.fnsplit(@lTempEmployeeIdList,','))
		FOR XML PATH(''), TYPE
	).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

	SET @lTempEmployeeIdList = @lTempEmployeeId
	SET @lCount1 = @lCount1 + 1

	END


IF OBJECT_ID('tempdb..#EmployeeListLeaveTemp') IS NOT NULL
	BEGIN
		DROP TABLE #EmployeeListLeaveTemp;
	END     
CREATE Table #EmployeeListLeaveTemp(EmployeeId Bigint)

DECLARE @lTempEmployeeIdListLeave NVARCHAR(MAX);
DECLARE @lTempEmployeeIdLeave NVARCHAR(MAX);
DECLARE @lCount2 int = 1

SELECT @lTempEmployeeIdListLeave = STUFF((
    SELECT ',' + CAST(EJD.EmployeeId AS NVARCHAR(MAX))
    FROM sHrm.tEmployeeJobDetail EJD INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId Where EmployeeManagerId = @rEmployeeId
    FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '');


While @lHierarchyLevel > @lCount2

	BEGIN

		INSERT INTO #EmployeeListLeaveTemp
			SELECT EJD.EmployeeId FROM sHrm.tEmployeeJobDetail EJD INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId Where EmployeeManagerId IN (SELECT cast(item as BigInt) FROM sCommon.fnsplit(@lTempEmployeeIdListLeave,','))

	SET @lTempEmployeeIdLeave = STUFF((
		SELECT ',' + CAST(EJD.EmployeeId AS NVARCHAR(MAX))
		FROM sHrm.tEmployeeJobDetail EJD INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId Where EmployeeManagerId IN (SELECT cast(item as BigInt) FROM sCommon.fnsplit(@lTempEmployeeIdListLeave,','))
		FOR XML PATH(''), TYPE
	).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

	SET @lTempEmployeeIdListLeave = @lTempEmployeeIdLeave
	SET @lCount2 = @lCount2 + 1

	END


   SELECT   
      L.[Id] AS LeaveId,  
	  LHL.AutoId AS LeaveHierarchyLevelId,
      L.[EmployeeId],  
      L.[ReportDate],  
      L.[FromDate],  
      L.[ToDate],  
      L.[LeavePeriodId],  
      L.[LeaveTypeId],  
      L.[LeaveReason],  
      LPM.Title AS LeavePeriod,  
      LTM.Title AS LeaveType,   
	  [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
      EM.Code AS EmployeeCode,  
      L.NoOfLeave,  
      ISNULL(LHL.StatusId,0) AS StatusId,  
      ISNULL(SM.Title,'Pending') AS StatusName,  
      ISNULL(L.LeaveRemark,'') AS  LeaveRemark,  
      OM.DisplayTitle AS OrganizationName,    
      OM.Id AS OrgId,  
      L.BatchId AS BatchId,  
      EM.DepartmentId AS DepartmentId,  
      EM.DepartmentName As DepartmentName,
	  ELT.EmployeeName AS ActionByEmployee
  FROM   
	  sHrm.tLeaveHierarchyLevel LHL
	  INNER JOIN sHrm.tLeave L  ON L.Id = LHL.LeaveId
      INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId    
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
      INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId  
      INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId  
      INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId  
      INNER JOIN sCommon.tStatusMaster SM ON SM.Id = LHL.StatusId  
	  INNER JOIN #EmployeeListTemp ELT ON ELT.EmployeeId = LHL.ActionByEmployeeId
  WHERE   
      (LHL.AutoId = @rLeaveHierarchyLevelId OR @rLeaveHierarchyLevelId = 0)     
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)        
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
      AND ((L.OrgId = @rOrgId) OR (@rOrgId = 0))  
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')  
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')  
      AND (LHL.StatusId = @rStatusId OR @rStatusId = 0) 
      AND ((EM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
	  AND ISNULL(EM.IsOtherUser,0)=0 
	  AND L.EmployeeId IN (Select EmployeeId From #EmployeeListLeaveTemp)
END

ELSE

BEGIN

   SELECT   
      L.[Id] AS LeaveId,  
	  LHL.AutoId AS LeaveHierarchyLevelId,
      L.[EmployeeId],  
      L.[ReportDate],  
      L.[FromDate],  
      L.[ToDate],  
      L.[LeavePeriodId],  
      L.[LeaveTypeId],  
      L.[LeaveReason],  
      LPM.Title AS LeavePeriod,  
      LTM.Title AS LeaveType,   
	  [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
      EM.Code AS EmployeeCode,  
      L.NoOfLeave,  
      ISNULL(LHL.StatusId,0) AS StatusId,  
      ISNULL(SM.Title,'Pending') AS StatusName,  
      ISNULL(L.LeaveRemark,'') AS  LeaveRemark,  
      OM.DisplayTitle AS OrganizationName,    
      OM.Id AS OrgId,  
      L.BatchId AS BatchId,  
      EM.DepartmentId AS DepartmentId,  
      EM.DepartmentName As DepartmentName,
	  EmpM.ShortName AS ActionByEmployee
  FROM   
	  sHrm.tLeaveHierarchyLevel LHL
	  INNER JOIN sHrm.tLeave L  ON L.Id = LHL.LeaveId
      INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId    
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
      INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId  
      INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId  
      INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId  
      INNER JOIN sCommon.tStatusMaster SM ON SM.Id = LHL.StatusId  
	  INNER JOIN sHrm.tEmployeeMaster EmpM ON EmpM.Id = LHL.ActionByEmployeeId
  WHERE   
      (LHL.AutoId = @rLeaveHierarchyLevelId OR @rLeaveHierarchyLevelId = 0)     
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)        
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
      AND ((L.OrgId = @rOrgId) OR (@rOrgId = 0))  
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')  
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')  
      AND (LHL.StatusId = @rStatusId OR @rStatusId = 0) 
      AND ((EM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
	  AND ISNULL(EM.IsOtherUser,0)=0 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pLeaveHierarchyListingGet]  
(  
	@rOrgId int,  
	@rLeaveHierarchyLevelId bigint = 0,
    --@rId bigint = 0,  
    @rEmployeeId  bigint,     
    @rFromDate date,  
    @rLeaveTypeId int,  
    @rTodate date,  
    @rOrgGroupBatchId int,  
    @rEmployeeCode nvarchar(100)='',  
    @rEmployeeName nvarchar(100)='',  
    @rStatusId int = 0,  
    --@rOrgGroupId int,  
    --@rIsSearchLeaveHierarchyWise int = 0,  
    @rDepartmentId int
	
	--@rUserId bigint = 0
 )  
AS  
SET NOCOUNT ON  
  
BEGIN  
      
   SELECT   
      L.[Id] AS LeaveId,  
	  LHL.AutoId AS LeaveHierarchyLevelId,
      L.[EmployeeId],  
      L.[ReportDate],  
      L.[FromDate],  
      L.[ToDate],  
      L.[LeavePeriodId],  
      L.[LeaveTypeId],  
      L.[LeaveReason],  
      LPM.Title AS LeavePeriod,  
      LTM.Title AS LeaveType,  
      --EM.EmployeeName,  
	  [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
      EM.Code AS EmployeeCode,  
      L.NoOfLeave,  
      ISNULL(LHL.StatusId,0) AS StatusId,  
      ISNULL(SM.Title,'Pending') AS StatusName,  
      ISNULL(L.LeaveRemark,'') AS  LeaveRemark,  
      OM.DisplayTitle AS OrganizationName,  
      --L.ActionByEmployeeId,  
      --CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND L.StatusId = 549 THEN NULL  
      --WHEN L.ActionByEmployeeId = 0 AND L.StatusId != 549 THEN US.DisplayTitle  
      --ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
      OM.Id AS OrgId,  
      L.BatchId AS BatchId,  
      EM.DepartmentId AS DepartmentId,  
      EM.DepartmentName As DepartmentName,
	  ISNULL(L.FromTime, '') AS FromTime, --Added for mantis : 36564
	  ISNULL(L.ToTime, '') As ToTime --Added for mantis : 36564
  FROM   
	  sHrm.tLeaveHierarchyLevel LHL
	  INNER JOIN sHrm.tLeave L  ON L.Id = LHL.LeaveId
      INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId    
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
	  --INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = OM.Id AND UO.UserId = @rUserId
      INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId  
      INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId  
      INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId  
      --INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId  
      INNER JOIN sCommon.tStatusMaster SM ON SM.Id = LHL.StatusId  
      --LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
      --LEFT JOIN sSecurity.tUser US ON US.Id = L.UpdatedUserId 
	  --INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     
  WHERE   
      (LHL.AutoId = @rLeaveHierarchyLevelId OR @rLeaveHierarchyLevelId = 0)     
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)        
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
      AND ((L.OrgId = @rOrgId) OR (@rOrgId = 0))  
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')  
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')  
      AND (LHL.StatusId = @rStatusId OR @rStatusId = 0) 
      AND ((EM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
	  AND ISNULL(EM.IsOtherUser,0)=0 
	  AND (LHL.ActionByEmployeeId = @rEmployeeId) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sHrm].[pLeaveListGet]
(
	@rOrgId int ,
    @rId bigint = 0,
    @rEmployeeId  bigint ,   
    @rFromDate date = '',
    @rLeaveTypeId int = 0,
    @rTodate date = '',
    @rBatchId int ,
    @rEmployeeCode nvarchar(100) = '',
    @rEmployeeName nvarchar(100) = '',
    @rStatusId int=0
 )
AS
SET NOCOUNT ON

BEGIN
    
	SELECT 
		   L.Id AS LeaveId
		  ,L.EmployeeId
		  ,L.ReportDate
		  ,L.FromDate
		  ,L.ToDate
		  ,LeavePeriodId
		  ,L.LeaveTypeId
		  ,CASE WHEN LeaveReason = '- Select -' THEN 'NA' ELSE LeaveReason END AS LeaveReason
		  ,LPM.Title AS LeavePeriod
		  ,LTM.Title AS LeaveType
		  ,EM.EmployeeName
		  ,EM.Code AS EmployeeCode
		  ,ISNULL(L.StatusId,0) AS StatusId
		  ,ISNULL(SM.Title,'Pending') AS StatusName
		  ,L.NoOfLeave      
		  ,ISNULL(L.FromTime,'') AS FromTime
          ,ISNULL(L.ToTime,'') AS ToTime
          ,ISNULL(L.LeaveRemark,'') AS LeaveRemark
		  --,(ISNULL((Select NoOfLeave FROM sHrm.tLeaveTypeGradeSettings LGS WHERE LGS.EmployeeGradeId = EM.EmployeeGradeId AND LGS.LeaveTypeId = L.LeaveTypeId),0) - L.NoOfLeave) AS AvailableLeave
      
  FROM 
		  sHrm.tLeave L 
		  INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId
		  INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
		  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId 
		  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId
	  --INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.EmployeeGradeId = EM.EmployeeGradeId AND LTGS.LeaveTypeId = L.LeaveTypeId 
  WHERE 
		  (L.Id = @rId OR @rId = 0)
      AND (L.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)      
      AND BatchId = @rBatchId AND L.OrgId = @rOrgId 
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (L.StatusId = @rStatusId OR @rStatusId = 0)
  Order By L.FromDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pLeaveListingGet]  
(  
	@rOrgId int,  
    @rId bigint = 0,  
    @rEmployeeId  bigint,     
    @rFromDate date,  
    @rLeaveTypeId int,  
    @rTodate date,  
    @rOrgGroupBatchId int,  
    @rEmployeeCode nvarchar(100)='',  
    @rEmployeeName nvarchar(100)='',  
    @rStatusId int = 0,  
    @rOrgGroupId int,  
    @rIsSearchLeaveHierarchyWise int = 0,  
    @rDepartmentId int,
	@rUserId bigint = 0
 )  
AS  
SET NOCOUNT ON  
  
BEGIN  
      
    CREATE TABLE #TempEmployeeId  
    (  
  EmployeeId bigint  
    )  
      
    IF(@rIsSearchLeaveHierarchyWise = 1)  
 BEGIN  
  WITH EmployeeCTE AS  
   (  
    SELECT  
     EmployeeID  
    FROM sHrm.tEmployeeJobDetail  
    WHERE ((EmployeeManagerId = @rEmployeeId) OR (@rEmployeeId = 0))  
     --AND ((OrgId = @rOrgId) OR (@rOrgId = 0))  
  
    UNION ALL  
  
    SELECT  
     E.EmployeeID  
    FROM sHrm.tEmployeeJobDetail E  
    JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId  
   )  
  INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E  
    END  
      
      
    ELSE  
    BEGIN  
  INSERT INTO #TempEmployeeId(EmployeeId)  
  SELECT EmployeeId FROM sHrm.tEmployeeJobDetail EJD   
  WHERE ((EJD.EmployeeManagerId = @rEmployeeId) OR (@rEmployeeId = 0))  
      AND ((OrgId = @rOrgId) OR (@rOrgId = 0))  
    END  
      
  SELECT   
      L.[Id] AS LeaveId,  
      L.[EmployeeId],  
      L.[ReportDate],  
      L.[FromDate],  
      L.[ToDate],  
      L.[LeavePeriodId],  
      L.[LeaveTypeId],  
      L.[LeaveReason],  
      LPM.Title AS LeavePeriod,  
      LTM.Title AS LeaveType,  
      --EM.EmployeeName,  
	  [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
      EM.Code AS EmployeeCode,  
      L.NoOfLeave,  
      ISNULL(L.StatusId,0) AS StatusId,  
      ISNULL(SM.Title,'Pending') AS StatusName,  
      ISNULL(L.LeaveRemark,'') AS  LeaveRemark,  
      OM.DisplayTitle AS OrganizationName,  
      L.ActionByEmployeeId,  
      CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND L.StatusId = 549 THEN NULL  
      WHEN L.ActionByEmployeeId = 0 AND L.StatusId != 549 THEN US.DisplayTitle  
      ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
      OM.Id AS OrgId,  
      L.BatchId AS BatchId,  
      EM.DepartmentId AS DepartmentId,  
      EM.DepartmentName As DepartmentName,
	  US.Id As UserId,
	  ISNULL(L.FromTime,'') AS FromTime, --Added for mantis : 36564
      ISNULL(L.ToTime,'') AS ToTime --Added for mantis : 36564
  FROM   
      sHrm.tLeave L  
      INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId    
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
	  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = OM.Id AND UO.UserId = @rUserId
      INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId  
      INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId  
      INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId  
      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId  
      INNER JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
      INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = L.EmployeeId  
      LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
      LEFT JOIN sSecurity.tUser US ON US.Id = L.UpdatedUserId 
	  INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     

  WHERE   
      (L.Id = @rId OR @rId = 0)     
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)        
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
      AND ((L.OrgId = @rOrgId) OR (@rOrgId = 0))  
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')  
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')  
      AND (L.StatusId = @rStatusId OR @rStatusId = 0) 
      AND ((EM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
	  AND ISNULL(EM.IsOtherUser,0)=0 
	  AND U.UserId = @rUserId     
  ORDER BY   
      L.FromDate DESC  
       
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pLeaveListingModify]
           
        @rId bigint,
        @rEmployeeId bigint,
        @rBatchId int,
        @rOrgId int,
        @rStatusId int,
        @rLeaveRemark nvarchar(200), 
        @rActionByEmployeeId bigint,
        @rUpdatedUserId bigint = 0
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

	BEGIN
		UPDATE sHrm.tLeave
		SET 	 
		  [StatusId]=@rStatusId,
          [LeaveRemark]=@rLeaveRemark,
          [ActionByEmployeeId]=@rActionByEmployeeId,
          [UpdatedUserId]=@rUpdatedUserId                  
		WHERE EmployeeId = @rEmployeeId AND Id=@rId
		
		--DECLARE @lLeaveTypeId int = 0
		--DECLARE @lBalanceLeave decimal(8,2) = 0
		--DECLARE @lAddBalance decimal(5,2) = 0
		--DECLARE @lStatusId int = 0
		
		--SELECT @lLeaveTypeId=LeaveTypeId , @lAddBalance=NoOfLeave, @lStatusId = StatusId FROM sHrm.tLeave WHERE EmployeeId = @rEmployeeId AND Id=@rId
		
		--SELECT @lBalanceLeave=BalanceLeave FROM sHrm.tLeaveBalance WHERE EmployeeId = @rEmployeeId AND LeaveTypeId=@lLeaveTypeId AND BatchId = @rBatchId
		
		--IF(@rStatusId=550) -- Approved
		--BEGIN
		--	-- Add Leave Balance Log
		--	INSERT INTO sHrm.tLeaveBalanceLog 
		--	SELECT @rEmployeeId,@lLeaveTypeId,@lBalanceLeave+@lAddBalance,4,@lAddBalance,
		--	'Add Leave - Approved',@rBatchId,0,sCommon.fGetDate()	 
		--END
		--ELSE
		--BEGIN
		--		IF(@lStatusId=551)
		--		BEGIN
		--			 -- Add Leave Balance Log
		--			INSERT INTO sHrm.tLeaveBalanceLog 
		--			SELECT @rEmployeeId,@lLeaveTypeId,@lBalanceLeave-@lAddBalance,4,@lAddBalance,
		--			'Add Leave - Rejected',@rBatchId,0,sCommon.fGetDate()
		--		END
		--END
		-- Update Leave in EmployeeRegister when leave is Approved from LeaveListing Screen (only in Approved) - mantisid - 0027169
		IF(@rStatusId = 550)
		BEGIN
			CREATE TABLE #tmp
			(
				Id int IDENTITY,
				LeaveDate DATE
			)

			DECLARE	@StartDate DATE, @EndDate DATE , @lEmployeeId bigint
			SELECT @StartDate = FromDate FROM sHrm.tLeave WHERE Id = @rId 
			SELECT @EndDate = ToDate FROM sHrm.tLeave WHERE Id = @rId
			SELECT @lEmployeeId = EmployeeId FROM sHrm.tLeave WHERE Id = @rId;
			
			WITH ListDates(AllDates) AS 
			(    
				SELECT @StartDate AS DATE
				UNION ALL
				SELECT DATEADD(DAY,1,AllDates)
				FROM ListDates 
				WHERE AllDates < @EndDate)

			INSERT INTO #tmp
			SELECT AllDates
			FROM ListDates

			--Select * from #tmp
			DECLARE @lCount int,@lId int,@lLeaveDate Date , @lLeaveTypeId int, @lLeavePeriodId int
			SELECT @lCount=COUNT(Id) FROM #tmp
			SELECT Top 1 @lId=Id FROM #tmp
			
			WHILE @lId <= @lCount
			BEGIN
				SELECT @lLeaveDate=LeaveDate FROM #tmp WHERE Id=@lId
				SELECT @lLeaveTypeId = LeaveTypeId , @lLeavePeriodId = LeavePeriodId FROM sHrm.tLeave WHERE Id = @rId


				IF EXISTS(SELECT 1 FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = @lEmployeeId AND AttendanceDate = @lLeaveDate AND BatchId = @rBatchId)
				BEGIN
				--Print 111
				--	SELECT 0 ,@lLeaveTypeId, @lLeavePeriodId FROM sHrm.tEmployeeAttendanceRegister 
				--		WHERE AttendanceDate = @lLeaveDate AND EmployeeId = @lEmployeeId AND BatchId = @rBatchId

					UPDATE sHrm.tEmployeeAttendanceRegister SET IsPresent = 0 ,LeaveTypeId = @lLeaveTypeId, LeavePeriodId = @lLeavePeriodId
					WHERE AttendanceDate = @lLeaveDate AND EmployeeId = @lEmployeeId AND BatchId = @rBatchId
				END
				--ELSE
				--BEGIN
			
				--INSERT INTO sHrm.tEmployeeAttendanceRegister
				--   (EmployeeId
				--   ,[AttendanceDate]
				--   ,[IsPresent]
				--   ,[AbsentReasonId]
				--   ,[UpdatedUserId]
				--   ,[UpdatedDateTime]
				--   ,[BatchId]
				--   ,[AttendanceTagId]
				--   ,[LeaveTypeId]
				--   ,[LeavePeriodId])
				-- VALUES
				--	   (@lEmployeeId
				--	   ,@lLeaveDate
				--	   ,0
				--	   ,0
				--	   ,1
				--	   ,GetDate()
				--	   ,@rBatchId
				--	   ,NULL
				--	   ,@lLeaveTypeId
				--	   ,@lLeavePeriodId
				--	   )
				
				--END

				SET @lId=@lId+1
			END
			DROP TABLE #tmp
			
		END
		
	 END 
	   SELECT @rId AS Result	   
	   COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pLeavePeriodAdd]
	 
	@rOrgId int,
	@rLeavePeriodId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION		 
	 INSERT INTO sHrm.tLeavePeriod
		(
			OrgId,
			LeavePeriodId 
		)
		VALUES
		(
			@rOrgId,
			@rLeavePeriodId
		)		
	 	            
		SELECT @rOrgId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pLeaveTypeGradeSeetingListGet]
    @rEmployeeGradeId int = 0,
    @rOrgId int
AS
SET NOCOUNT ON

BEGIN
       
       SELECT 
				 LTM.Id AS LeaveTypeId,
				 LTM.Title AS LeaveType,
				 ISNULL(LTGS.EmployeeGradeId,0) AS EmployeeGradeId,
				 ISNULL(LTGS.NoOfLeave,0) AS NoOFLeave,
				 ISNULL(LTGS.MaxInMonth,0) AS MaxInMonth,
				 LTGS.LeaveTypeId ,
				 Isnull(LTGS.LeaveCarryForwordRuleId,1) AS LeaveCarryForwordRuleId
       FROM 
			   sHrm.tLeaveTypeMaster LTM 
		   LEFT JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.LeaveTypeId = LTM.Id AND EmployeeGradeId = @rEmployeeGradeId
       WHERE 
			   LTM.IsObsolete = 0
			AND LTM.OrgId = @rOrgId   AND IsLWP = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveTypeGradeSettingAdd]
           
           @rLeaveTypeId int,
           @rEmployeeGradeId int,
           @rNoOfLeave decimal(5,2),--decimal for mantis : 40618
           @rMaxInMonth decimal(5,2),          
           @rOrgId smallint,
		   @rLeaveCarryForwordRuleId int=1
        
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint	  
	
	IF EXISTS(SELECT 1 FROM sHrm.tLeaveTypeGradeSettings WHere LeaveTypeId = @rLeaveTypeId AND OrgId = @rOrgId AND EmployeeGradeId = @rEmployeeGradeId)
	DELETE FROM sHrm.tLeaveTypeGradeSettings WHere LeaveTypeId = @rLeaveTypeId AND OrgId = @rOrgId AND EmployeeGradeId = @rEmployeeGradeId
	
	BEGIN		     
		   INSERT INTO [sHrm].[tLeaveTypeGradeSettings]
           (
            [OrgId]
           ,[LeaveTypeId]
           ,[EmployeeGradeId]
           ,[NoOfLeave]
           ,[MaxInMonth]
		   ,[LeaveCarryForwordRuleId]
           )
     VALUES
           (
            @rOrgId
           ,@rLeaveTypeId
           ,@rEmployeeGradeId
           ,@rNoOfLeave
           ,@rMaxInMonth
		   ,@rLeaveCarryForwordRuleId
           )		 
          END
	   SELECT 1 AS Result	   
	   COMMIT TRANSACTION
	   		
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveTypeMasterAdd]
           
           @rId int,
           @rCode nvarchar(100),
           @rTitle nvarchar(100),
           @rIsCarryForward bit,
           @rIsLWP bit,
           @rOrgId smallint,
           @rIsObsolete bit,
           @rCreatedUserId bigint,
           @rMaximumCarryForward smallint=0,
           @rMainLeaveTypeId tinyint = 0 
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint
	 
    IF (@rId = 0)
	
	BEGIN	
	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeaveTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output	
		INSERT INTO  [sHrm].[tLeaveTypeMaster]
          (
           [OrgId]
           ,[Id]
           ,[Code]
           ,[Title]
           ,[IsCarryForward]
           ,IsLWP
           ,[IsObsolete]
           ,[MaximumCarryForward]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,UpdatedUserId
           ,UpdatedDateTime
           ,MainLeaveTypeId
          )
     VALUES
           (
           @rOrgId,
           @lNextNumber, 
           @rCode, 
           @rTitle, 
           @rIsCarryForward, 
           @rIsLWP,
           @rIsObsolete, 
           @rMaximumCarryForward,
           @rCreatedUserId, 
           sCommon.fGetDate(),
           0,
           sCommon.fGetDate(),
           @rMainLeaveTypeId 
           )
          END
	ELSE
	BEGIN
	SET @lNextNumber = @rId
		UPDATE [sHrm].[tLeaveTypeMaster]
		SET 		   
		   [Code] = @rCode 
		  ,[Title] = @rTitle 
		  ,IsCarryForward = @rIsCarryForward  
		  ,IsLWP = @rIsLWP
		  ,MaximumCarryForward = @rMaximumCarryForward
		  ,[IsObsolete] = @rIsObsolete       
		  ,[UpdatedUserId] = @rCreatedUserId   
		  ,UpdatedDateTime = sCommon.fGetDate()		                    
		  ,MainLeaveTypeId = @rMainLeaveTypeId
		WHERE Id = @rId
	 END 
	   SELECT @lNextNumber AS Result	   
	   COMMIT TRANSACTION
	   		
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveTypeMasterListGet]
(
    @rId int = 0,
    @rName nvarchar(20),
  	@rOrgId [smallint], 
	@rCode [nvarchar](20),
	@rIsWildCardSearch bit
 )
AS
SET NOCOUNT ON

BEGIN
    
    IF(@rIsWildCardSearch = 0)
    BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rName = sCommon.fSearchStringGet(@rName) 
    END
	SELECT 
		   L.OrgId
		  ,L.Id
		  ,L.Code
		  ,L.Title
		  ,L.IsCarryForward
		  ,L.IsLWP
		  ,L.IsObsolete
		  ,ISNULL(L.MaximumCarryForward,0) AS MaximumCarryForward
		  ,ISNULL(L.MainLeaveTypeId,0) AS MainLeaveTypeId,
		  MLTM.Title AS MainLeaveType
		  ,ISNULL(L.IsMonthCarryForward,0) AS IsMonthCarryForward
		  ,ISNULL(L.MonthCarryForward,0) AS MonthCarryForward
		  
  FROM     
		[sHrm].[tLeaveTypeMaster] L
		LEFT JOIN sHrm.tMainLeaveTypeMaster MLTM ON MLTM.Id = L.MainLeaveTypeId
  WHERE 
		((L.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((L.Id  = @rId) OR (@rId = 0))
		AND ((L.Code Like  @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((L.Title Like @rName) OR (ISNULL(@rName,'')='')) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pLeaveTypeMasterRemove]
 (
	@rLeaveTypeId int
 )
AS
SET NOCOUNT ON
	
	DECLARE @1Result Int
	
	BEGIN TRY	
    BEGIN TRANSACTION
			BEGIN	 
				 --SET @1Result = 1
				 
				 IF EXISTS(Select 1 FROM sHrm.tLeaveTypeGradeSettings Where LeaveTypeId = @rLeaveTypeId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				 ELSE IF EXISTS(Select 1 FROM sHrm.tLeave Where LeaveTypeId = @rLeaveTypeId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				 ELSE
				   BEGIN
				      DELETE FROM sHrm.tLeaveTypeMaster Where Id = @rLeaveTypeId
				      SET @1Result = 1
				   END
				 
				 --ELSE IF EXISTS(Select 1 FROM sHostel.tAssignRoom where SourceId = @rEmployeeId AND SourceTypeId = 95)
				 --BEGIN
				 --   SET @1Result = -101
				 --END			 
				 
				 --ELSE IF EXISTS(SELECT 1 FROM sCommunication.tPollMember WHERE SourceId = @rEmployeeId AND SourceTypeId = 95)
				 -- BEGIN
				 --    SET @1Result = -101
				 -- END
				 --ELSE IF EXISTS(SELECT 1 FROM sHrm.tEmployeeAttendance Where EmployeeId = @rEmployeeId)
				 --BEGIN
				 --   SET @1Result = -101
				 --END
				 
				 --ELSE IF EXISTS(Select 1 FROM sHostel.tHostelWarden Where EmployeeId = @rEmployeeId)
				 --BEGIN 
				 --   SET @1Result = -101
				 --END		
				 --ELSE IF EXISTS(Select 1 FROM sCommunication.tDiscussionGroupMember Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				 --BEGIN 
				 --   SET @1Result = -101
				 --END	
				 	  
			SELECT @1Result AS Result
				 	  
			END
	  COMMIT TRANSACTION
      END TRY
         
      BEGIN CATCH
	  ROLLBACK TRANSACTION
	  SELECT -1 AS RESULT
	  END CATCH

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pLessonPlanEmployeeReplacementDeleteAndTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT = 0,
		@rAction NVARCHAR(100),
		@rSubjectId Int,
		@rFromDate datetime='',
		@rToDate datetime='' 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF (@rAction ='DeleteAndTransfer')
	BEGIN
		--Update sAcademic.tLessonPlan SET EmployeeId = @rNewEmployeeId where EmployeeId = @rExistingEmployeeId
			UPDATE LP
			SET LP.EmployeeId = @rNewEmployeeId
			FROM sAcademic.tLessonPlan LP
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
			WHERE LP.EmployeeId = @rExistingEmployeeId 
			AND SM.Id = @rSubjectId
			AND (LP.StartDate >= @rFromDate OR LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (LP.StartDate <= @rToDate OR LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')


	END
	ELSE IF(@rAction ='Delete')
	BEGIN
		--Delete sAcademic.tLessonPlan where EmployeeId =  @rExistingEmployeeId AND 
			DELETE LP
			FROM sAcademic.tLessonPlan LP
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
			WHERE LP.EmployeeId = @rExistingEmployeeId 
			AND SM.Id = @rSubjectId
			AND (LP.StartDate >= @rFromDate OR LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (LP.StartDate <= @rToDate OR LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
	END

	--Drop Table #tmpSplitTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pLessonPlanEmployeeReplacementGet]
	 
        @rEmployeeId bigint,
		@rFromDate datetime='',
		@rToDate datetime='' 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT DISTINCT SM.Id AS SubjectId, ISNULL(SM.Title,'') AS SubjectName FROM 
		sAcademic.tLessonPlan LP 
		INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
	WHERE EmployeeId = @rEmployeeId
		AND (LP.StartDate >= @rFromDate OR LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
		AND (LP.StartDate <= @rToDate OR LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pMISEmployeeSummaryDashboardGet]

	@rTypeId int=0,
	@rFilterType nvarchar(50)='',
	@rOrgGroupId smallint=0,
	@rOrgSubGroupId int=0,
	@rOrgId int=0,
	@rStatusId int=0,
	@rGenderId int=0,
	@rEmployeeGroupId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
  
------------1
	IF(@rTypeId = 1)
	BEGIN
		IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
			SELECT 
				 OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName
				,COUNT(EM.Code) As Total
				,COUNT(AEM.Code) as Active
			FROM
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
			    LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
				WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  Group By EM1.Code) AEM ON  EM.Code = AEM.Code
			WHERE OGM.Id != 1 AND ISNULL(OGM.IsObsolete,0) = 0 AND OGM.Id = @rOrgGroupId
			Group By OSGM.Id,OSGM.Title
			Order By OrgSubGroupName
		END
		ELSE IF(@rFilterType = 'Genderwise')--Genderwise
		BEGIN
		 SELECT 
				 OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName
				,COUNT(Male.Code) as Male
				,COUNT(Female.Code) as Female
				,COUNT(EM.Code) as Total
			FROM
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 1 Group By EM1.Code) Male ON  EM.Code = Male.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 2 Group By EM1.Code) Female ON  EM.Code = Female.Code
			WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0)) AND ISNULL(OGM.IsObsolete,0) = 0
			Group By OSGM.Id,OSGM.Title
			Order By OrgSubGroupName
		END
		ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
		BEGIN
			 SELECT 
				OSGM.Id As OrgSubGroupId		
				,OSGM.Title As OrgSubGroupName
				,COUNT(T1.Code) as Teaching
				,COUNT(T2.Code) as NonTeaching

			FROM 
				sSetup.tOrgSubGroupMaster OSGM
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 

				LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=1 Group By EM1.Code) T1 ON  EM.Code = T1.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=2 Group By EM1.Code) T2 ON  EM.Code = T2.Code
				 
			WHERE ((OGM.Id = @rOrgGroupId) OR (@rOrgGroupId = 0))AND ISNULL(OGM.IsObsolete,0) = 0
			Group By OSGM.Id,OSGM.Title
			Order By OrgSubGroupName
		END
	END
-------------11 
	ELSE IF(@rTypeId = 2)
	BEGIN
		IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
		 SELECT 
			 OM.Title As Organization
			,OM.Id As OrgId
			,COUNT(EM.Code) As Total
			,COUNT(AEM.Code) as Active
		FROM 
			sSetup.tOrgGroupMaster OGM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id
       		LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
			 WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  Group By EM1.Code) AEM ON  EM.Code = AEM.Code
		WHERE ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0)) AND EM.IsOtherUser = 0
		Group By OM.Title,OM.Id
		Order By Organization
		END

		ELSE IF(@rFilterType = 'Genderwise')--Genderwise
		BEGIN
			 SELECT 
				 OM.Title As Organization
				,OM.Id As OrgId
				,COUNT(Male.Code) as Male
				,COUNT(Female.Code) as Female
				,COUNT(EM.Code) as Total
			FROM
				sSetup.tOrgGroupMaster OGM
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 1 Group By EM1.Code) Male ON  EM.Code = Male.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EPD.GenderId = 2 Group By EM1.Code) Female ON  EM.Code = Female.Code
			WHERE ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0)) AND ISNULL(OGM.IsObsolete,0) = 0
			Group By OM.Title,OM.Id
			Order By Organization
		END

		ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
		BEGIN
			 SELECT 
				OM.Title As Organization
				,OM.Id As OrgId
				,COUNT(T1.Code) as Teaching
				,COUNT(T2.Code) as NonTeaching

			FROM 
				sSetup.tOrgGroupMaster OGM
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.OrgId = OM.Id AND EM.StatusId = 7 AND ISNULL(EM.IsOtherUser,0) = 0 

				LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=1 Group By EM1.Code) T1 ON  EM.Code = T1.Code
				LEFT JOIN (SELECT EM1.Code As Code FROM sHrm.tEmployeeMaster EM1 
					INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM1.Id
					WHERE EM1.StatusId = 7 AND ISNULL(EM1.IsOtherUser,0) = 0  AND EJD.EmployeeGroupId=2 Group By EM1.Code) T2 ON  EM.Code = T2.Code
				 
			WHERE ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))AND ISNULL(OGM.IsObsolete,0) = 0
			Group By OM.Title,OM.Id
			Order By Organization
		END
		 
	END
------------------21
	ELSE IF(@rTypeId = 3)
		BEGIN
		IF(@rFilterType = 'Statuswise')--Statuswise (Total/Active)
		BEGIN
			SELECT 
				(EM.Id)EmployeeID,
				(EM.Code)EmployeeCode,
				(EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.MobileNumber) AS ContactNo
			 from  sHrm.tEmployeeMaster EM 
				   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
				   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
				   LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
				And ISNULL(OGME.IsObsolete,0) = 0
				and ((EM.StatusId=@rStatusId) OR (@rStatusId = 0)) AND  ISNULL(EM.IsOtherUser,0) = 0	
		END
		ELSE IF(@rFilterType = 'Genderwise')--Genderwise
		BEGIN
			SELECT 
					(EM.Id)EmployeeID,
					(EM.Code)EmployeeCode,
					(EM.FirstName+' '+EM.LastName) AS EmployeeName,
					(EC.MobileNumber) AS ContactNo
				 from  sHrm.tEmployeeMaster EM 
					   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
					   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
					   LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
					   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
				WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
					And ISNULL(OGME.IsObsolete,0) = 0
					and (EM.StatusId=7) AND  ISNULL(EM.IsOtherUser,0) = 0	
					and EPD.GenderId = @rGenderId
		END
		ELSE IF(@rFilterType = 'EmployeeGroupwise')--EmployeeGroupwise
		BEGIN
			SELECT 
					(EM.Id)EmployeeID,
					(EM.Code)EmployeeCode,
					(EM.FirstName+' '+EM.LastName) AS EmployeeName,
					(EC.MobileNumber) AS ContactNo
				 from  sHrm.tEmployeeMaster EM 
					   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
					   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
					   LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
					   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				WHERE ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
					And ISNULL(OGME.IsObsolete,0) = 0
					and (EM.StatusId=7) AND  ISNULL(EM.IsOtherUser,0) = 0	
					and EJD.EmployeeGroupId = @rEmployeeGroupId
		END
		END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pNewEmployeeCustomFieldAdd]
		 
	--@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	--@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	--@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	--@rIsObsolete int =0,
	@rDataTypeId int = 1,
	@rCustomFieldMasterId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		BEGIN TRANSACTION	

			DECLARE @lOrgGroupId int=0, @lIsEmployee bit = 0
			SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMAster WHERE Id = @rOrgId
			select @lIsEmployee = IsEmployee From sSetup.tCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId AND OrgGroupId=@lOrgGroupId
 
			IF(@lIsEmployee=1)	
			BEGIN
				IF NOT EXISTS(SELECT 2 FROM sHrm.tEmployeeCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId)
				BEGIN
					DECLARE @lNextNumber int
					EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sHrm.tEmployeeCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output --mantis: 39728, change @rOrgId => @lOrgGroupId
					Print @lNextNumber
					INSERT INTO sHrm.tEmployeeCustomFieldMaster
					(
						Id
					   ,FieldTitle
					   ,FieldTypeId
					   ,FieldList
					   ,IsFieldMandatory
					   ,FieldGroup
					   ,FieldOrder
					   ,CreatedUserId
					   ,CreatedDateTime
					   ,OrgGroupId
					   ,IsObsolete
					   ,DataId
					   ,CustomFieldMasterId		--add for mantis: 32799
					)
					VALUES
					(
					   @lNextNumber
					  ,@rFieldTitle
					  ,@rFieldTypeId
					  ,@rFieldList
					  ,0
					  ,@rFieldGroup
					  ,0
					  ,@rCreatedUserId
					  ,@rCreatedDateTime
					  ,@lOrgGroupId
					  ,0
					  ,@rDataTypeId
					  ,@rCustomFieldMasterId	--add for mantis: 32799
					)
				END
			--ELSE
	--	 SELECT -101 As RESULT
	--END
	 	 
				ELSE
				BEGIN
				--SET @lNextNumber = @rId

					UPDATE sHrm.tEmployeeCustomFieldMaster
					SET 
						FieldTitle = @rFieldTitle
						,FieldTypeId = @rFieldTypeId
						,FieldList=@rFieldList
						--,IsFieldMandatory=@rIsFieldMandatory
						--,IsObsolete=@rIsObsolete
						,FieldGroup=@rFieldGroup
						--,FieldOrder=@rFieldOrder
						,UpdatedUserId=@rUpdatedUserId
						,UpdatedDateTime=@rUpdatedDateTime
						,DataId = @rDataTypeId
					WHERE CustomFieldMasterId=@rCustomFieldMasterId
	
	
				END  
			END
			ELSE
			BEGIN
				IF EXISTS(SELECT 2 FROM sHrm.tEmployeeCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId)
				BEGIN
					DECLARE @lEmployeeCustomFieldMasterId int=0
					SELECT @lEmployeeCustomFieldMasterId = Id FROM sHrm.tEmployeeCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId

					EXEC sHrm.pEmployeeCustomFieldDelete @lEmployeeCustomFieldMasterId, @rOrgId, @lOrgGroupId
				END
			END	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[PNoAbsentEmployee]
	 @rOrgGroupId int=0,
	 @rConfi int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

  BEGIN
	SELECT 
	 top 5 COUNT(*) AS AbsentEmployeeCount
	FROM 
		sStudent.vStudentAllDetail S
			
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pQualificationMasterAdd]
	
	@rOrgGroupId smallint,
	@rCode [nvarchar](20),
	@rTitle [nvarchar](100),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE  sCommon.pTableRowIdGet @rOrgGroupId, 'sHrm.tQualificationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sHrm.tQualificationMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pQualificationMasterGet]
	
	@rOrgGroupId smallint,
	@rId [int] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM 
			sHrm.tQualificationMaster
	  WHERE 
			((Id = @rId) OR (@rId = 0))
		AND OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pQualificationMasterModify]
	@rId [smallint],
	@rCode [nvarchar](20),
	@rTitle [nvarchar](100),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sHrm.tQualificationMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pRelievingCertificateAdd]
			@rId bigint
	       ,@rEmployeeId bigint
	       ,@rNumber int
	       ,@rCertificateDate date
	       ,@rCreatedUserId bigint
	       ,@rOrgId int
	       ,@rJobRemark nvarchar(200)
	      
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	 
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sHrm.tCertificateRelieving WHERE OrgId=@rOrgId
		END	
			
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sHrm.tCertificateRelieving WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END

	  DECLARE @lNextNumber BIGINT
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCertificateRelieving', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sHrm.tCertificateRelieving
				(
					Id
				   ,EmployeeId
				   ,Number
				   ,CertificateDate
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,JobRemark
				)
				VALUES
				(	@lNextNumber
				   ,@rEmployeeId
				   ,@rNumber
				   ,@rCertificateDate
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate()
				   ,@rJobRemark
				)
		END
		
		ELSE
		
		BEGIN
			SET @lNextNumber = @rId
				UPDATE  sHrm.tCertificateRelieving
				SET
					EmployeeId=@rEmployeeId,
					CertificateDate=@rCertificateDate,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					JobRemark=@rJobRemark
					
				WHERE Id = @rId
		 END  	
		
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRelievingCertificateGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	-- @rBatchId int,
	 @rIsSearch bit = 1,
	 @rEmployeeId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
		END
	
	SELECT 
	
			CR.Id,
			CR.EmployeeId,
			EM.FirstName+' '+EM.LastName as Name,
			CR.Number,
			CR.CertificateDate ,
			CR.JobRemark,
			--isnull(SA.Designation,0) AS EmployeeDesignationId ,
			
			EM.Designation As Designation,
			EM.Code
		
			
  FROM 
            sHrm.tCertificateRelieving CR
       INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=CR.EmployeeId AND EM.OrgId=@rOrgId 
  WHERE 
  
	((CR.Id = @rId) OR (@rId = 0))
	AND ((EM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND ((EM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))
	AND ((CR.Number >= @rFromNo) OR (@rFromNo=0))
	AND ((CR.Number <= @rToNo) OR (@rToNo=0))
	AND ((CR.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((CR.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	ORDER BY CR.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sHrm].[pRpt EmpLeavePresenceOLD]
	 
		@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
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			
			
				
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			@rIsDetail AS IsDetail,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,   
			EM.EmployeeId,
			EM.DepartmentName,
			EM.EmployeeGrade,      
			ISNULL(LB.BalanceLeave,0) AS BalanceLeave,
			ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
			LTM.Id AS LeaveTypeId,	
			LTM.Title AS LeaveType,
			(
				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
        FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0
			LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EM.EmployeeId AND LTM.Id = LB.LeaveTypeId AND LB.BatchId=@rBatchId
			LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.OrgId=EM.OrgID 
			LEFT JOIN sHrm.tWorkingDays WD ON WD.EmployeeGradeId = EGM.Id
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			
			
    	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))
    		ORDER BY EM.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pRptAttendanceSheet]
	 	 
	 	 @rBuilder1 nvarchar(max)='',
		 @rBuilder2 nvarchar(max)='',
	 	 @rDepartmentId int=0,
	 	 --@rAttendanceDate date='',
	 	 @rCode nvarchar(20)='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0,
	 	 @rStatusId int=0,
	 	 @rEmployeeGradeId int=0,
		 @rFromDate date='',
		 @rToDate date=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  BEGIN
  Set @rFromDate= Cast(@rFromDate AS DATE)
  Set @rToDate=Cast(@rToDate AS DATE)

    IF OBJECT_ID('#Temp') IS NOT NULL
    DROP TABLE #Temp

	IF OBJECT_ID('#TEMPTABLE') IS NOT NULL
    DROP TABLE #TEMPTABLE

create table #Temp
(
	id INT NOT NULL    IDENTITY    PRIMARY KEY,
    AllDate date,
)

;WITH   AllDays
          AS ( SELECT   @rFromDate AS MyDate, 1 AS [level]
               UNION ALL
               SELECT   DATEADD(DAY, 1,MyDate), [level] + 1
               FROM     AllDays
               WHERE    MyDate < @rToDate )

	  INSERT INTO #Temp(AllDate)
	  SELECT MyDate
	  FROM AllDays 
	  option (maxrecursion 0)

  --Select * from #Temp
 
SELECT 
			ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS ItemNo,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			EM.DepartmentName,
			ISNULL(EAR.IsPresent,0) as IsPresent,
			ISNULL(EAR.AttendanceDate,'') AS AttendanceDate	,
			DATENAME(month, EAR.AttendanceDate) + '-'+ Convert(varchar,Year(EAR.AttendanceDate)) As MonthofDate,
			DATENAME(day, EAR.AttendanceDate)As dayofDate,
			EM.DepartmentId,
			ISNULL(EM.DateOfJoining,'')AS DateOfJoining,
			ISNULL(EM.DateOfleaving,'')AS DateOfleaving	
			INTO #TEMPTABLE		
  FROM 
			sHrm.vExtEmployeeMaster EM
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=EM.EmployeeId			 
			AND (EAR.BatchId = @rBatchId)AND EAR.AttendanceDate between @rFromDate AND @rToDate
    WHERE 
		  ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		  AND ((EM.Code like @rCode) OR (ISNULL(@rCode,'')=''))
		  AND (EM.OrgId = @rOrgId)		  
		  AND ((EM.StatusId = @rStatusId) OR ISNULL(@rStatusId,0)=0)
		  AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR ISNULL(@rEmployeeGradeId,0)=0)
		  AND (EM.DateOfJoining<= @rToDate OR ISNULL(EM.DateOfJoining,'')='')
		  AND (EM.DateOfleaving>= @rFromDate OR ISNULL(EM.DateOfleaving,'')='')
		  AND EM.IsOtherUser = 0
          ORDER BY EAR.AttendanceDate,EM.Code

		  --Select * from #TEMPTABLE


			select Distinct
			tmp1.Builder1,
			tmp1.Builder2,
			tmp1.EmployeeId,
			tmp1.EmployeeCode,
			tmp1.EmployeeName,
			tmp1.DepartmentName,
			ISNULL((SELECT IsPresent FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = tmp1.EmployeeId AND AttendanceDate=Alldate AND BatchId=@rBatchId),0) AS IsPresent,
			tmp.AllDate,
			DATENAME(month, tmp.AllDate) + '-'+ Convert(varchar,Year(tmp.AllDate)) As MonthofDate,
			DATENAME(day, tmp.AllDate)As dayofDate,
            --[sHrm].[fWeekHOffGet](tmp1.EmployeeId, Year(tmp.AllDate),month(tmp.AllDate),day(tmp.AllDate),@rBatchId,tmp1.DepartmentId,@rOrgId) AS [Status]			
			[sHrm].[fAttendanceWithLeaveGet](tmp1.EmployeeId, Year(tmp.AllDate),month(tmp.AllDate),day(tmp.AllDate),@rBatchId,tmp1.DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),Year(tmp.AllDate))+'-'+CONVERT(NVARCHAR(2),month(tmp.AllDate))+'-'+CONVERT(NVARCHAR(2),day(tmp.AllDate)))),tmp1.DateOfJoining,tmp1.DateOfleaving,'') AS [Status]

			FROM #Temp tmp
			CROSS JOIN #TEMPTABLE tmp1
			--Where tmp1.Ispresent = 0
			ORDER BY tmp.AllDate

		  Drop table #Temp
		  Drop Table #TEMPTABLE
				
  END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptCountCategorywiseEmployeeGet]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rCategoryId smallint,
	@rOrgId smallint,
	@rDepartmentId [int]= 0,
	@rDesignationId [int]= 0,
	@rEmployeeId [bigint]= 0,
	@rEmployeeCode nvarchar(50)='',
	@rGenderIds nvarchar(max)='',
	@rEmployeeGroupIds nvarchar(max)='',
	@rCasteCategoryIds nvarchar(max) = '',
	@rReligionIds nvarchar(max) = '',
	@rEmployeeTypeIds nvarchar(max) = '',
	@rBloodGroupIds nvarchar(max) = '',
	@rUserId bigint = 0,
	@rEmployeeStatusId smallint,
	@rGradeId [int]= 0,
	@rTribeIds nvarchar(max) = ''
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
	SELECT

		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		ECD.EmployeeId,
	    ECD.Code,	
		[sHrm].[fEmployeeNameGet](ECD.FirstName , ECD.MiddleName, ECD.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,	
		--ECD.EmployeeName, 	 								 
		ECD.DepartmentId,  			
		ECD.DepartmentName,
		ECD.MobileNumber,
		ECD.PhoneNoCompany,
		ECD.EmployeeDesignation,
		ECD.ExtensionNo,
		ECD.DateOfBirth,
		ISNULL(GM.Title,'') As Gender,
		CCM.OrderIndex AS CasteNumber,
		CASE WHEN  @rCategoryId=1 -- Gender
		THEN ISNULL(GM.Title,'')
		WHEN  @rCategoryId=2 -- Employee Group
		THEN ISNULL(EGM.Title,'')
		WHEN @rCategoryId=3 --Employee Type
		THEN Isnull(ETM.Title,'')
		WHEN  @rCategoryId=4 -- Religion
		THEN ISNULL(RM.Title,'') 
		WHEN  @rCategoryId=5 -- Caste Category
		THEN ISNULL(CCM.Title,'')
		WHEN  @rCategoryId=6 -- BloodGroupwise Summary
		THEN ISNULL(BGM.Title,'') 
		WHEN  @rCategoryId=7 -- Tribewise Summary
		THEN ISNULL(TM.Title,'') 	
		END AS Head,
		ECD.OrgId,
		ISNULL(OM.Title,'') AS Organization

	FROM 
			[sHrm].[vEmployeeCommonDetail] ECD 
			inner JOIN [sHrm].[tEmployeePersonalDetail] EPD on ECD.EmployeeId=EPD.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgId
			INNER JOIN sSetup.vDepartment D ON D.Id = ECD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=ECD.EmployeeTypeId
			left JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id=ECD.EmployeeGroupId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=ECD.GenderId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=EPD.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=ECD.BloodGroupId
			LEFT JOIN sCommon.tTribeMaster TM ON TM.Id=EPD.TribeId
	WHERE
			((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	   AND (ISNULL(ECD.EmployeeGroupId,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupIds,','))OR @rEmployeeGroupIds='')
	   AND (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	   AND (ISNULL(RM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionIds,','))OR @rReligionIds='')
	   AND (ISNULL(GM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderIds,','))OR @rGenderIds='')  
	   AND (ISNULL(ECD.EmployeeTypeId,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeIds,','))OR @rEmployeeTypeIds='')  	    
	   AND (ISNULL(BGM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupIds,','))OR @rBloodGroupIds='')
	   AND (ISNULL(TM.Id,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rTribeIds,',')) OR @rTribeIds='')
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	   AND  ECD.OrgId = @rOrgId
	   AND ISNULL(ECD.IsOtherUser,0)=0
	   AND (D.UserId = @rUserId OR @rUserId = 0)	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptDailyStaffAttendanceGet]
	 	 
	 	 @rBuilder1 nvarchar(max)='',
		 @rBuilder2 nvarchar(max)='',
	 	 @rDepartmentId int=0,
	 	 @rAttendanceDate date='',
	 	 @rCode nvarchar(20)='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0,
	 	 @rStatusId int=0,
	 	 @rEmployeeGradeId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			EM.DepartmentName,
			EAR.IsPresent as IsPresent,
			ISNULL(EAR.AttendanceDate,'') AS AttendanceDate,
			[sHrm].[fEmployeeLeaveTypeCodeGet] (@rBatchId,EM.EmployeeId,@rAttendanceDate) AS LeaveType,
			ISNULL(EAR.EmployeeId,0) AS EmployeeIdForPresent
		
  FROM 
			sHrm.vExtEmployeeMaster EM
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=EM.EmployeeId 
			AND EAR.AttendanceDate =@rAttendanceDate
			AND (EAR.BatchId = @rBatchId)
    WHERE 
		  ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		  AND ((EM.Code like @rCode) OR (ISNULL(@rCode,'')=''))
		  AND (EM.OrgId = @rOrgId)		  
		  AND ((EM.StatusId = @rStatusId) OR ISNULL(@rStatusId,0)=0)
		  AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR ISNULL(@rEmployeeGradeId,0)=0)
		  --AND (@rAttendanceDate>=EM.DateOfJoining)
		  AND ((EM.DateOfleaving >= @rAttendanceDate) OR ISNULL(EM.DateOfleaving,'') = '')
          AND ((EM.DateOfJoining <= @rAttendanceDate) OR ISNULL(EM.DateOfJoining,'') = '') 
		  AND (EM.StatusId = 7)
		  AND (EM.IsOtherUser = 0)	
          ORDER BY EM.Code
  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmpLeavePresence]
	 
		@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 = null,
	    @rToDate date=null
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			@rIsDetail AS IsDetail,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,   
			EM.EmployeeId,
			EM.DepartmentName,
			EM.EmployeeGrade,      
			ISNULL(LB.BalanceLeave,0) AS BalanceLeave,
			ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
			 ISNULL(AT.LWP,0) AS LWP,
			 CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			LTM.Id AS LeaveTypeId,	
			LTM.Title AS LeaveType,
			(
				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,
			EM.Number,
			EWD.WorkingDays AS EmployeeWorkingDay	--add for 27636 mantis

        FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0
			LEFT 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 
			LEFT JOIN sHrm.tWorkingDays WD ON WD.EmployeeGradeId = EGM.Id AND WD.ForYear = @rForYear AND WD.forMonth = @rForMonth
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForYear = @rForYear AND AT.forMonth = @rForMonth
			LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON EWD.EmployeeId=EM.EmployeeId AND EWD.BatchId=@rBatchId AND EWD.ForYear=@rForYear AND EWD.ForMonth =@rForMonth	--add for 27636 mantis
			
    	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.IsOtherUser = 0
    		ORDER BY EM.Code
    		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeAllDetailList]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)
DECLARE @lIsDisplayImageHeader bit=0

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 129 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsOnPrePrinted = 0
	ELSE
	SET @lIsOnPrePrinted = 1
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayImageHeader = 0
	ELSE
	SET @lIsDisplayImageHeader = 1	
	
	
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		    EM.Id,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        EM.EmployeeName,
	       	EM.FirstName,
			EM.MiddleName,
			EM.LastName,	
			EM.ShortName,
			EM.OrgID,
			EM.GenderId,
			EM.DateOfBirth,
			EM.DateOfJoining,
			EM.DateOfleaving,
			EM.ReasonOfleaving,
			EM.JobRemark,
			EM.StatusId,
			EM.CreatedUserId,
			EM.CreatedDateTime,
			EM.UpdatedUserId,
			EM.UpdatedDateTime,
			EM.IsObsolete,
			EM.PhoneNoCompany,
			EM.CompanyEmail,
			EM.ExtensionNo,
			EM.UserId,
			EM.DepartmentId,
			EM.DepartmentCode,  
			EM.DepartmentName,
		    EM.MobileNumber,
			EM.EmployeeTypeId,
			EM.DesignationId,
			EM.Designation,
			EM.ParticipantSourceTypeId,
			EM.EmployeeGroup,
			EM.EmployeeGroupId,
			EM.EmployeePhoto,
			EC.PresentStreetOne,
			EC.PresentStreetTwo,
			EC.PresentStreetThree,
			EC.PresentCity,
			EC.PresentState,
			EC.PresentCountry,
			EC.PresentZipCode,
			EC.PresentContactNo,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			GM.Title AS Gender,
			EM.EmployeeType,
			EM.Qualification,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4 ,
			--[sHrm].[fTeachingSubjectGet] (EM.Id) AS TeachingSubject,
			EJD.Subjects AS TeachingSubject,
			ISNULL(ESO.EPFNumber,'') AS EPFNumber,
			ISNULL(EP.AdhaarNumber,'') AS AdhaarNumber
	FROM 
			[sHrm].[vExtEmployeeMaster] EM
			INNER JOIN sHrm.tEmployeeCommunications EC ON EM.Id=EC.EmployeeId
			INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.Id		
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EM.GenderId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
	WHERE
			((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(EM.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (EM.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (EM.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (EM.DesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (EM.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  EM.OrgId = @rOrgId
	   AND ISNULL(EM.IsOtherUser,0)=0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceGet]
	 
	@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,
	@rEmployeeStatusId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 EM.Code AS EmployeeCode,
			 EM.EmployeeName,   
			 EM.EmployeeId,
			 EM.DepartmentName,
			 EM.EmployeeGrade,     
			 ISNULL(WD.TotalDays,ISNULL(AT.TotalWorkingDays,0)) As TotalDays,
			 ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
			 ISNULL(AT.LWP,0) AS LWP,
			-- CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			 (ISNULL(AT.TotalWorkingDays,0) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0))) AS PresentDays,
			 MM.Title AS MonthName,
			 AT.ForYear As YearName,			
			 --L.LeaveReason,
			 --L.NoOfLeave,
			 --L.ReportDate,
			 --L.FromDate,
			 --L.ToDate,
			 --LPM.Title As LeavePeriod,
			 --LTM.Title As LeaveType,
			 --LTM.IsCarryForward,
			 --LTM.IsLWP
			  EM.EmployeeDesignation As Designation, -- Mantis 0030721
			  [sHrm].[fEmployeeNameGet](EM.FirstName, EM.MiddleName, Em.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise, --Mantis 0031250
			  EM.Number -- Added for Mantis : 32040 by Nilesh
        FROM 
			sHrm.vEmployeeCommonDetail EM 
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
			LEFT JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
			AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			--INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
			--INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
    	WHERE 
    			EM.OrgID = @rOrgId 
    		AND (AT.BatchId=@rBatchId)
    		AND ((AT.ForMonth=@rForMonth) OR (@rForMonth=0))
    		AND ((AT.ForYear=@rForYear) OR (@rForYear=0))
    		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 ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    		--AND ((L.ToDate>=@rToDate) OR (ISNULL(@rToDate,'')=''))
    		AND EM.IsOtherUser = 0
    		ORDER BY EM.Number
    		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceRegisterGet]
	 
		@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,
		@rStatusId smallint=0,
		@rEmployeeStatusId int = 0,
		@rFromNumber int = NULL,
		@rToNumber int = NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

DECLARE @li int 
SET @li=1
Declare @ldate datetime,@lDays int
declare @Days int
Declare @Firstdate datetime
Declare @Lastdate datetime

		
Set @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		
set @Firstdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
set @Lastdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @Days)
		
CREATE Table #EmployeeAttendanceRegistertempTable
(
	 
	EmployeeCode nvarchar(50),
	EmployeeId bigint,
	EmployeeName nvarchar(100),
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	DepartmentId int,
	DepartmentName nvarchar(50),
	IsPresent bit,
	DayPart int,
	AttendanceDate date,
	DateOfJoining date,
	DateOfLeaving  date,
	AttendanceTagId int ,
	Number int ,
	IsOtherUser smallint,
	EmployeeGrade nvarchar(500),
	Code nvarchar(200),
	LeaveCount decimal(12,2),
	LeaveType nvarchar(100), 
	WorkingDays tinyint,
	HoliDays tinyint 
 
)
Insert INTO #EmployeeAttendanceRegistertempTable
(	
	EmployeeCode ,
	EmployeeId ,
	EmployeeName,
	ForYear ,
	ForMonth,
	ForMonthInWord,
	DepartmentId ,
	DepartmentName ,
	IsPresent ,
	DayPart ,
	AttendanceDate ,
	DateOfJoining ,
	DateOfLeaving ,
	AttendanceTagId,
	Number,
	IsOtherUser,
	EmployeeGrade,
	Code,
	LeaveCount,
	LeaveType , 
	WorkingDays ,
	HoliDays  
)
SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeId AS EmployeeId,
		EM.EmployeeName,
		YEAR(EAR.AttendanceDate) AS ForYear,
		MONTH(EAR.AttendanceDate) AS ForMonth,
		DATENAME(month, EAR.AttendanceDate) AS ForMonthInWord,
		EM.DepartmentId,
		EM.DepartmentName,
		EAR.IsPresent,
		day(EAR.AttendanceDate) AS DayPart,
		EAR.AttendanceDate,
		EJD.DateOfJoining,
		EJD.DateOfLeaving,
			EAR.AttendancetagId,
		EM.Number,
		EM.IsOtherUser,
		EM.EmployeeGrade,
		LTM.Code,
		(SELECT ISNULL(SUM(CONVERT(decimal(12,2),  '.'+PARSENAME(NoOfLeave,1))),0) FROM sHrm.tLeave WHERE LeaveTypeId = LTM.Id AND FromDate BETWEEN @FirstDate AND @LastDate AND StatusId!=551 AND OrgId = @rOrgId AND BatchId = @rBatchId AND EmployeeId = EM.EmployeeId) AS LeaveCount,
		LTM.Title AS LeaveType , 
		WD.WorkingDays ,
		WD.HoliDays  

	FROM 

		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
		INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId AND LTM.IsObsolete=0	
	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=@rStatusId) OR (@rStatusId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
    		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
			AND EM.IsOtherUser = 0
			AND (EM.Number >= @rFromNumber OR @rFromNumber IS NULL) AND (EM.Number <= @rToNumber OR @rToNumber IS NULL)
			ORDER BY EM.Number

CREATE TABLE #TempDaysTempTable
(
 DayPart int
 )
WHILE @li<=@Days

BEGIN

INSERT INTO #TempDaysTempTable
(
	DayPart 
)

SELECT 
@li AS DayPart
SET @li = @li + 1

END

		
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			Number,
			isnull(EmployeeCode,'') as EmployeeCode,
			PivotTable.EmployeeId,
			isnull(EmployeeName,'') as EmployeeName,   
			DepartmentName,
			EmployeeGrade,      
		   	sCommon.fGetDaysInMonth (@rForMonth,@rForYear) AS TotalDays,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),DateOfJoining,DateOfLeaving,[1]) AS P1,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),DateOfJoining,DateOfLeaving,[2]) AS P2,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),DateOfJoining,DateOfLeaving,[3]) AS P3,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),DateOfJoining,DateOfLeaving,[4])  AS P4,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),DateOfJoining,DateOfLeaving,[5]) AS P5,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),DateOfJoining,DateOfLeaving,[6]) AS P6,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),DateOfJoining,DateOfLeaving,[7])  AS P7,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),DateOfJoining,DateOfLeaving,[8]) As P8,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),DateOfJoining,DateOfLeaving,[9]) AS P9,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),DateOfJoining,DateOfLeaving,[10]) AS P10,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),DateOfJoining,DateOfLeaving,[11]) AS P11,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),DateOfJoining,DateOfLeaving,[12]) AS P12,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),DateOfJoining,DateOfLeaving,[13]) AS P13,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),DateOfJoining,DateOfLeaving,[14]) AS P14,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),DateOfJoining,DateOfLeaving,[15]) AS P15,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),DateOfJoining,DateOfLeaving,[16])  AS P16,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),DateOfJoining,DateOfLeaving,[17]) AS P17,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),DateOfJoining,DateOfLeaving,[18])  AS P18,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),DateOfJoining,DateOfLeaving,[19])  AS P19,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),DateOfJoining,DateOfLeaving,[20])  AS P20,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),DateOfJoining,DateOfLeaving,[21]) AS P21,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),DateOfJoining,DateOfLeaving,[22]) AS P22,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),DateOfJoining,DateOfLeaving,[23]) AS P23,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),DateOfJoining,DateOfLeaving,[24]) AS P24,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),DateOfJoining,DateOfLeaving,[25]) AS P25,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),DateOfJoining,DateOfLeaving,[26]) AS P26,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),DateOfJoining,DateOfLeaving,[27]) AS P27,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),DateOfJoining,DateOfLeaving,[28]) AS P28,
			CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),DateOfJoining,DateOfLeaving,[29]) end AS P29,
			CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),DateOfJoining,DateOfLeaving,[30])end AS P30,
			CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),DateOfJoining,DateOfLeaving,[31])end AS P31,
			Code,
			LeaveCount,
			LeaveType , 
			WorkingDays ,
			HoliDays  
			FROM
(
	Select  
		EmployeeCode,
		EmployeeId,
		EmployeeName,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		DepartmentId,
		DepartmentName,
		(
			CASE 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		DateOfLeaving,		 
		DateOfJoining,
		Number,
		EmployeeGrade,
		Code,
		LeaveCount	,
		LeaveType , 
		WorkingDays ,
		HoliDays 
	 FROM 
		#EmployeeAttendanceRegistertempTable ST 
		LEFT JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE 
		  ((DateOfLeaving >= @FirstDate) OR ISNULL(DateOfLeaving,'') = '')
		  AND IsOtherUser = 0
	   -- WHERE 
	   -- ForYear=@rForYear AND ForMonth=@rForMonth
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  EmployeeId AS EmployeeId, COUNT(1) AS TCount 
		   FROM  
				#EmployeeAttendanceRegistertempTable
				WHERE AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		     GROUP BY  EmployeeId 
    ) TC ON TC.EmployeeId = PivotTable.EmployeeId 
	LEFT JOIN
	(
		Select EmployeeId AS EmployeeId, COUNT(1) AS ACount 
		   FROM  #EmployeeAttendanceRegistertempTable
		    WHERE   IsPresent = 0	 	 
		      AND AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			GROUP BY  EmployeeId
    ) AC ON AC.EmployeeId = PivotTable.EmployeeId
	LEFT JOIN
	(
		SELECT EJD.EmployeeId, COUNT(1) AS PCount  FROM 
		
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
	   
			WHERE   
	
	    ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
	       AND ((EM.DepartmentId = @rDepartmentId)OR (@rDepartmentId=0))
	       AND ((EAR.BatchId=@rBatchId) OR (@rBatchId= 0))
	       AND EAR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		   AND EM.IsOtherUser = 0
	 GROUP BY EJD.EmployeeId 
    ) PC ON PC.EmployeeId = PivotTable.EmployeeId
		
	Order By PivotTable.Number	
			--FROM
			--sHrm.vEmployeeCommonDetail EM
			--INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId				
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId						
			
   -- 		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=@rStatusId) OR (@rStatusId=0))
   -- 		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
   -- 		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
   -- 		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
   -- 		--AND ((ISNULL(EM.DateOfJoining,''))<=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),IN(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)))))			
			--AND EM.IsOtherUser = 0
			--AND E.Number>=@rFromNumber AND E.Number<=@rToNumber

			--SELECT 
			--	'' as [Builder1]
			--	,'' as [Builder2]
			--	,convert(bigint,0) as [Number]
   --   ,'' as [EmployeeCode]
   --   ,convert(bigint,0)  as [EmployeeId]
   --   ,'' as [EmployeeName]
   --   ,'' as [DepartmentName]
   --   ,'' as [EmployeeGrade]
   --   ,0 as [TotalDays]
   --   ,'' as [P1]
   --   ,'' as [P2]
   --   ,'' as [P3]
   --   ,'' as [P4]
   --   ,'' as [P5]
   --   ,'' as [P6]
   --   ,'' as [P7]
   --   ,'' as [P8]
   --   ,'' as [P9]
   --   ,'' as [P10]
   --   ,'' as [P11]
   --   ,'' as [P12]
   --   ,'' as [P13]
   --   ,'' as [P14]
   --   ,'' as [P15]
   --   ,'' as [P16]
   --   ,'' as [P17]
   --   ,'' as [P18]
   --   ,'' as [P19]
   --   ,'' as [P20]
   --   ,'' as [P21]
   --   ,'' as [P22]
   --   ,'' as [P23]
   --   ,'' as [P24]
   --   ,'' as [P25]
   --   ,'' as [P26]
   --   ,'' as [P27]
   --   ,'' as [P28]
   --   ,'' as [P29]
   --   ,'' as [P30]
   --   ,'' as [P31]
   --   ,'' as [Code]
   --   ,0 as [LeaveCount]
   --   ,'' as [LeaveType] 
	  --,convert(tinyint,0) as [WorkingDays] 
	  --,convert(tinyint,0) as [HoliDays]  
 
drop table #EmployeeAttendanceRegistertempTable	  
drop table #TempDaysTempTable
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 
 --pRptEmployeeAttendanceRegisterGet 
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceRegisterGet_old]
	 
		@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,
		@rStatusId smallint=0,
		@rEmployeeStatusId int = 0,
		@rFromNumber int,
		@rToNumber int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		
		Set @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		
		set @Firstdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		set @Lastdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @Days)
		
		
		--DELETE FROM [sHrm].[tTempEmployeeAttendanceRegister]
			--INSERT INTO [sHrm].[tTempEmployeeAttendanceRegister]
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			EM.Code AS EmployeeCode,
			EM.EmployeeId,
			EM.EmployeeName,   
			EM.DepartmentName,
			EM.EmployeeGrade,      
		   	sCommon.fGetDaysInMonth (@rForMonth,@rForYear) AS TotalDays,
		    [sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P1,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P2,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P3,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P4,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P5,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P6,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P7,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P8,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P9,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P10,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P11,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P12,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P13,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P14,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P15,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P16,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P17,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P18,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P19,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P20,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P21,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P22,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P23,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P24,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P25,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P26,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P27,
			[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),EM.DateOfJoining,EM.DateOfLeaving,'') AS P28,
			CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),EM.DateOfJoining,EM.DateOfLeaving,'') end AS P29,
			CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),EM.DateOfJoining,EM.DateOfLeaving,'')end AS P30,
			CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceWithApproveLeaveGet](EM.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,@rDepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),EM.DateOfJoining,EM.DateOfLeaving,'')end AS P31
			,LTM.Code,
			--,(Select Code FROM sHrm.tLeaveTypeMaster)
			--,STUFF
			--(
			--	(
			--		SELECT ',' + LTM1.Code
			--		FROM sHrm.tLeaveTypeMaster LTM1
			--	   Where E.OrgID=LTM1.OrgId					
			--		--ORDER BY owner
			--		FOR XML PATH('')
			--	), 1, 1, ''
			--) AS Code
			(SELECT ISNULL(SUM(NoOfLeave),0) FROM sHrm.tLeave WHERE LeaveTypeId = LTM.Id AND FromDate BETWEEN @FirstDate AND @LastDate AND StatusId!=551 AND OrgId = @rOrgId AND BatchId = @rBatchId AND EmployeeId = EM.EmployeeId) AS LeaveCount
							
			FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId				
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId						
			
    		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=@rStatusId) OR (@rStatusId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
    		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
    		--AND ((ISNULL(EM.DateOfJoining,''))<=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),IN(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)))))			
			AND EM.IsOtherUser = 0
			AND E.Number>=@rFromNumber AND E.Number<=@rToNumber

		--	SELECT [Builder1]
  --    ,[Builder2]
  --    ,[EmployeeCode]
  --    ,[EmployeeId]
  --    ,[EmployeeName]
  --    ,[DepartmentName]
  --    ,[EmployeeGrade]
  --    ,[TotalDays]
  --    ,[P1]
  --    ,[P2]
  --    ,[P3]
  --    ,[P4]
  --    ,[P5]
  --    ,[P6]
  --    ,[P7]
  --    ,[P8]
  --    ,[P9]
  --    ,[P10]
  --    ,[P11]
  --    ,[P12]
  --    ,[P13]
  --    ,[P14]
  --    ,[P15]
  --    ,[P16]
  --    ,[P17]
  --    ,[P18]
  --    ,[P19]
  --    ,[P20]
  --    ,[P21]
  --    ,[P22]
  --    ,[P23]
  --    ,[P24]
  --    ,[P25]
  --    ,[P26]
  --    ,[P27]
  --    ,[P28]
  --    ,[P29]
  --    ,[P30]
  --    ,[P31]
  --    ,[Code]
  --FROM [sHrm].[tTempEmployeeAttendanceRegister]
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeAvailableLeaveWithPay]

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rDepartmentId int,
		@rEmployeeGradeId int,
		@rEmployeeStatusId int=0,
		@rEmployeeCode nvarchar (200),
		@rEmployeeName nvarchar(200),
		@rBatchId int,
		@rOrgId int,
		@rLeaveTypeIds nvarchar(50) = '',
		@rEmployeeId bigint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.Code AS EmployeeCode,
		EM.EmployeeName,
		EM.EmployeeId,
		EM.DepartmentName,
		EM.EmployeeGrade,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		LTM.Id AS LeaveTypeId,
		LTM.Title AS LeaveType,
		(SELECT	(ISNULL(LB.BalanceLeave,0) - ISNULL(SUM(NoOfLeave),0)) AS AvailableBalance
		 FROM sHrm.tLeaveBalance LB
			  LEFT JOIN sHrm.tLeave L ON LB.EmployeeId=L.EmployeeId AND LB.BatchId = L.BatchId AND LB.LeaveTypeId = L.LeaveTypeId AND L.StatusId = 550
		 WHERE LB.BatchId = @rBatchId AND LB.EmployeeId=EM.EmployeeId AND LB.LeaveTypeId=LTM.Id
		 GROUP BY LB.BalanceLeave) AS AvailableBalance
	FROM
		sHrm.vEmployeeCommonDetail EM
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		LEFT JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 AND IsLWP=0
	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.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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeBarcodeListGet]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

	
	SELECT
			--@rBuilder1 AS Builder1,
			--@rBuilder2 AS Builder2,
	        EM.Id AS EmployeeId,
	        EM.Code
			
			
	FROM 
			[sHrm].[vExtEmployeeMaster] EM
			
	WHERE
			((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(EM.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (EM.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (EM.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (EM.DesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (EM.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  EM.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeBirthday]
	
	@rOrgId smallint,
	@rTypeId [int] = 0,
	@rGradeId [int] = 0,
	@rDepartmentId [int] = 0,
	@rDesignationId [int] = 0,
	@rEmployeeId [int] = 0,
	@rIsActive [bit] = 0,
	@rBirthMonth [smallint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

	 SELECT 
			   EM.Code AS EmployeeId,
			   ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
			   EPD.DateOfBirth AS DateOfBirth,
			   DATEDIFF(YEAR, EPD.DateOfBirth, sCommon.fGetDate()) AS Age,
			   MONTH(EPD.DateOfBirth) AS MonthId,
			   Day(EPD.DateOfBirth) AS DayId,
			   RTRIM(DATENAME(MONTH, EPD.DateOfBirth)) + ' ' + LTRIM(STR(DAY(EPD.DateOfBirth))) AS BirthDayMonth
	   
	   FROM 
				sHrm.tEmployeeJobDetail EJD
		   INNER JOIN sHrm.tEmployeeMaster EM ON EJD.EmployeeId = EM.Id
		   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EJD.EmployeeId = EPD.EmployeeId
		   INNER JOIN sHrm.tEmployeeTypeMaster ETM ON EJD.EmployeeTypeId = ETM.Id
		   INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EJD.EmployeeGradeId = EGM.Id
		   INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EJD.EmployeeDesignationId = EDM.Id
		   INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id
	   WHERE 
		   (EJD.EmployeeTypeId = @rTypeId OR @rTypeId  = 0) 
	   AND (EJD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (EJD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId  = 0) 
	   AND (EJD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	   AND (EM.Id = @rEmployeeId OR @rEmployeeId = 0) AND EM.IsObsolete = @rIsActive
	   AND (DATEPART(MONTH, EPD.DateOfBirth) = @rBirthMonth OR @rBirthMonth = 0)
	   AND EM.OrgID = @rOrgId AND  ISNULL(EM.IsOtherUser,0) = 0
	   ORDER BY MonthId, DayId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeBirthdayDetailsListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rStrCode nvarchar(max),
	 @rDepartmentId int,
	 @rEmployeeId bigint,
	 @rStatusId int,
	 @rDateOfBirth int
	  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.Id AS EmployeeId,
		EM.Code ,
		ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
		ISNULL(EC.MobileNumber,'') AS MobileNumber,
		ISNULL(EP.DateOfBirth,'') AS DateOfBirth,  
		ISNULL(GM.Title,'') AS Gender,  
		EI.EmployeePhoto
		FROM sHrm.tEmployeeMaster EM  
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id 
		INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId 
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.ID = EC.EmployeeId 
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id  
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId
		WHERE 
		EM.OrgId=@rOrgId
		AND (ISNULL(EM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((EM.Id=@rEmployeeId) OR (@rEmployeeId=0))
		AND (EM.StatusId = @rStatusId OR @rStatusId = 0)
		AND ((MONTH(EP.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
		AND (DM.Id = @rDepartmentId OR @rDepartmentId = 0)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeCommonDetail]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rEmployeeTypeId [int],
	@rEmployeeGroupId [int] = 0,
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rStatusId [int]= 0,
	@rAgeFrom [int] = 0,
	@rAgeTo [int] = 100,
	@rIsDetail bit = 0,
	@rBloodGroupId [int] = 0,
	@rMaritalStatusId [int] = 0,
	@rEmployeeCode nvarchar(50)=''
						
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

SET @rBloodGroupId = ISNULL(@rBloodGroupId,0)
SET @rMaritalStatusId = ISNULL(@rMaritalStatusId,0)

	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		    ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 						
			ECD.PhoneNoCompany,
			ECD.CompanyEmail,
			ECD.ExtensionNo,		 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    --ECD.OrgID,
		    ISNULL(ECD.BloodGroup,'Unknown') AS BloodGroup,
		    ISNULL((SELECT Title FROM sCommon.tAgeGroupMaster WHERE ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= AgeFrom) AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE())) <=AgeTo))),'NoRange') AS AgeGroupName,		     
		    ISNULL(CASE @rReportId
			WHEN 10081 THEN ECD.BloodGroup -- Blood Group List
			WHEN 10082 THEN ECD.BloodGroup -- Blood Group Summary 
			WHEN 10084 THEN ECD.BloodGroup  -- Blood Group Age Group Wise
			WHEN 10085 THEN ECD.GenderTitle   -- Gender Wise List
			WHEN 10086 THEN ECD.GenderTitle   -- Gender Wise Summary
			WHEN 10087 THEN ECD.GenderTitle   -- Gender Wise Age Group Wise
			--WHEN 10091 THEN ECD.MaritialStatusTitle  -- Marital Wise List
			WHEN 10092 THEN ECD.MaritialStatusTitle  -- Marital Wise Summary
			WHEN 10093 THEN ECD.MaritialStatusTitle  -- Marital Wise Age Group Wise
			WHEN 10095 THEN 'First Aid Training'
			--WHEN 10096 THEN 'Fire Training' 
			--WHEN 10098 THEN 'Disability'  
			WHEN 10097 THEN 'Employee List'
			WHEN 3 THEN 'Third'
			ELSE 'Other'
			END,'Unknown') AS Filter,
			@rIsDetail AS IsDetail,
			@rReportId AS ReportId
	FROM 
			[sHrm].[vEmployeeCommonDetail] ECD 
		
	WHERE
			((ECD.Code = @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND(ECD.EmployeeStatusId=@rStatusId OR @rStatusId=0)	  
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0) 	   
	  -- AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	      --AND (DATEDIFF(YYYY, ECD.DateOfBirth, sCommon.fGetDate()) = @rAge OR @rAge = 0)
	   AND  ECD.OrgId = @rOrgId
	   AND (ECD.BloodGroupId = @rBloodGroupId OR @rBloodGroupId = 0)
	   AND (ECD.EmployeeGroupId = @rEmployeeGroupId OR @rEmployeeGroupId = 0)
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)
	   AND (ECD.MaritalStatusId = @rMaritalStatusId OR @rMaritalStatusId = 0)   
	   --AND (ECD.IsFireTraining = (CASE @rReportId WHEN 10096 THEN 1 ELSE ECD.IsFireTraining END))  
	   --AND (ECD.IsFirstAidTraining = (CASE @rReportId WHEN 10095 THEN 1 ELSE ECD.IsFirstAidTraining END)) 
	   --AND (ECD.IsDisability = (CASE @rReportId WHEN 10098 THEN 1 ELSE ECD.IsDisability END)) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeCommunicationsSubGet]
	 
	 @rEmployeeId bigint,
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
	
SELECT [EmployeeId],
		convert(nvarchar(20),EmployeeId) AS EmployeeIdText,
		convert(nvarchar(20),@rOrgId) AS OrgIdText,
	   ISNULL([PresentStreetOne],'') + ' ' + ISNULL([PresentStreetTwo],'') + ' ' + ISNULL([PresentStreetThree],'') AS PresentAddress
      ,ISNULL([PresentStreetOne],'') AS [PresentStreetOne]
      ,ISNULL([PresentStreetTwo],'') AS [PresentStreetTwo]
      ,ISNULL([PresentStreetThree],'') AS [PresentStreetThree]
      ,ISNULL([PresentCountry],'') AS [PresentCountry]
      ,ISNULL([PresentState],'') AS [PresentState]
      ,ISNULL([PresentCity],'') AS [PresentCity]
      ,ISNULL([PresentZipCode],'') AS [PresentZipCode]
      ,ISNULL([PresentContactNo],'') AS [PresentContactNo]
      ,ISNULL([PermanentStreetOne],'') + ' ' + ISNULL([PermanentStreetTwo],'') + ' ' + ISNULL([PermanentStreetThree],'') AS PermanentAddress
      ,ISNULL([PermanentStreetOne],'') AS [PermanentStreetOne]
      ,ISNULL([PermanentStreetTwo],'') AS [PermanentStreetTwo]
      ,ISNULL([PermanentStreetThree],'') AS [PermanentStreetThree]
      ,ISNULL([PermanentCountry],'') AS [PermanentCountry]
      ,ISNULL([PermanentState],'') AS [PermanentState]
      ,ISNULL([PermanentCity],'') AS [PermanentCity]
      ,ISNULL([PermanentZipCode],'') AS [PermanentZipCode]
      ,ISNULL([PermanentContactNo],'') AS [PermanentContactNo]
      ,ISNULL([EmergencyStreetOne],'') + ' ' + ISNULL([EmergencyStreetTwo],'') + ' ' + ISNULL([EmergencyStreetThree],'') AS EmergencyAddress
      ,ISNULL([EmergencyStreetOne],'') AS [EmergencyStreetOne]
      ,ISNULL([EmergencyStreetTwo],'') AS [EmergencyStreetTwo]
      ,ISNULL([EmergencyStreetThree],'') AS [EmergencyStreetThree]
      ,ISNULL([EmergencyCountry],'') AS [EmergencyCountry]
      ,ISNULL([EmergencyState],'') AS [EmergencyState]
      ,ISNULL([EmergencyCity],'') AS [EmergencyCity]
      ,ISNULL([EmergencyZipCode],'') AS [EmergencyZipCode]
      ,ISNULL([EmergencyContactNo],'') AS [EmergencyContactNo]
      ,ISNULL([PhoneNoCompany],'') AS [PhoneNoCompany]
      ,ISNULL([ExtensionNo],'') AS [ExtensionNo]
      ,ISNULL([CompanyEmail],'') AS [CompanyEmail]
      ,ISNULL([PersonalEmail],'') AS [PersonalEmail]
      ,ISNULL([MobileNumber],'') AS [MobileNumber]
    
  FROM  [sHrm].[tEmployeeCommunications]
             
  WHERE 
		EmployeeId = @rEmployeeId 
		--	((SM.Code=@rCode) OR (ISNULL(@rCode,'') = ''))
		--AND(SM.OrgId=@rOrgId)

 --     ((BM.Id = @rId) OR (@rId = 0))
	--AND  ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	--AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	--AND(BM.OrgId=@rOrgId)

--ORDER BY BM.OrderIndex ASC
  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeDetailWithExpenseGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeCode nvarchar (200),
	@rDepartmentId int,
	@rEmployeeGradeId int,
	@rForYear  smallint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int,
	@rEmployeeStatusId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 EM.Code AS EmployeeCode,
			 EM.EmployeeName,   
			 EM.EmployeeId,
			 EM.DepartmentName,
			 EM.EmployeeGrade,      
			 ISNULL(WD.TotalDays,ISNULL(AT.TotalWorkingDays,0)) As TotalDays,
			 ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
			 ISNULL(AT.LWP,0) AS LWP,
			 CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			 MM.Title AS MonthName,
			 AT.ForYear As YearName,
			 ISNULL(E.Amount,0) AS Amount
        FROM 
			sHrm.vEmployeeCommonDetail EM 
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
			LEFT JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
			AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
			LEFT JOIN sAccounting.tExpense E ON EM.EmployeeId = E.EmployeeId AND DATEPART(MONTH,E.ExpenseDate)=AT.ForMonth
    	WHERE 
    		EM.OrgID = @rOrgId AND AT.BatchId=@rBatchId 
    		AND ((AT.ForMonth=@rForMonth) OR (@rForMonth=0))
    		AND ((AT.ForYear=@rForYear) OR (@rForYear=0))
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code LIKE @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		ORDER BY  EM.EmployeeId,AT.ForYear,AT.ForMonth
    		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeEmploymentDetail]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	--@rIsDetail bit = 0,
	--@rBloodGroupId [int] = 0,
	--@rMaritalStatusId [int] = 0,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
	        ECD.Code,	      	
			ECD.EmployeeName,
			EPE.CompanyName,
			EPE.Duration,
			EPE.Designation,
			EPE.LastSalary,
			EPE.ReasonForLeaving,
			EPE.JobDescription,
			EPE.Remark 	 								 
		
		    
	FROM 
			[sHrm].[vEmployeeCommonDetail] ECD 
			inner join [sHrm].[tEmployeePreviousEmployment] EPE on ECD.EmployeeId=EPE.EmployeeId
	WHERE
			((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeFamilyDetail]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	--@rIsDetail bit = 0,
	--@rBloodGroupId [int] = 0,
	--@rMaritalStatusId [int] = 0,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.Code,
			ECD.EmployeeName As ShortName,
			RM.Title As Relation,
			EFD.Name,
			BGM.Title As BloodGroup,
			EFD.DateOfBirth,
			EFD.Occupation

	    								 
		
		    
	FROM 
			[sHrm].[tEmployeeFamilyDetails] EFD inner join [sHrm].[vEmployeeCommonDetail] ECD  on EFD.EmployeeId=ECD.EmployeeId
			inner join sCommon.tBloodGroupMaster BGM on EFD.BloodGroupId=BGM.Id
			inner join sCommon.tRelationshipMaster RM on EFD.RelationshipId=RM.Id
	WHERE
			((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeFamilyDetailsSubGet]
	
	@rOrgId smallint,
	@rEmployeeId [bigint] = 0

AS
SET NOCOUNT ON

BEGIN
		SELECT 
		convert(nvarchar(20),EmployeeId) AS EmployeeIdText,
			convert(nvarchar(20),@rOrgId) AS OrgIdText,
				FD.Id,
				EmployeeId,
				RelationshipId,
				RM.Title AS Relationship,
				Name,		 
				ISNULL(DateOfBirth,'0001/01/01') AS DateOfBirth,
				CONVERT(VARCHAR, DATEDIFF(YEAR, DateOfBirth, sCommon.fGetDate())) AS Age,
				ISNULL(BloodGroupId,0) AS BloodGroupId,		 
				ISNULL(BGM.Title,'')  AS BloodGroup,
				ISNULL(FD.Occupation,'') AS Occupation,
				IsActive,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				2 AS OperationState
		FROM 
				sHrm.tEmployeeFamilyDetails FD
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id = FD.RelationshipId		
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = FD.BloodGroupId		 
	  WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND FD.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeIcardGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rIsShowBarcode bit=0,
	@rStrCode nvarchar(max)='',
	@rBatchName nvarchar(100) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.EmployeeDesignation,
		    ECD.PhoneNoCompany,
		    ECD.BloodGroup,
		    ECD.DateOfBirth,
			EI.EmployeePhoto,
		    OM.Title AS OrgName,
		    OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,	
		    OM.OrgLogo AS ICardLogo,
			ICO.ICardBackground,	
			ICO.ICardBackBackground,						
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(EC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(EC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(EC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(EC.PresentCity,'') AS PresentCity,
			ISNULL(EC.PresentState,'') AS PresentState,
			ISNULL(EC.PresentCountry,'') AS PresentCountry,
			ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
			ECD.DateofJoining,
			EI.EmployeeSign,
			@rIsShowBarcode As IsShowBarcode,
			ISNULL(EC.EmergencyStreetOne,'') AS EmergencyStreetOne,
			ISNULL(EC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
			ISNULL(EC.EmergencyStreetThree,'') AS EmergencyStreetThree,
			ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
			ISNULL(EC.EmergencyState,'') AS EmergencyState,
			ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(PanNumber,'') AS PanNumber,
			EC.EmergencyContactNo AS EmergencyContactNo,
			EPD.Qualification AS Qualification,
			--ISNULL(EM.MiddleName,'')AS FatherName,
			ISNULL(ECD.MiddleName,'')AS FatherName,
			ECD.GenderTitle,
			ISNULL(ECD.FirstName,'')AS FirstName,
			ISNULL(ECD.LastName,'')AS SurName,
			(CASE WHEN RelationshipId = 2 THEN EFD.MobileNo ELSE '' END )AS FatherContactNo,
			ISNULL(@rBatchName,'') AS BatchName,
			ISNULL(EC.PresentContactNo,'') AS PresentContactNo,
			--added by megha for 0027070
			ISNULL(ECD.CompanyEmail,'')AS CompanyEmail,
			ISNULL(EC.PersonalEmail,'')AS PersonalEmail,
			ISNULL(ECD.EmployeeGrade,'')AS EmployeeGrade,
			ISNULL(ECD.Number,0) AS Number, --add fro mantis : 0035451
			ISNULL(ECD.JobRemark,'') AS JobRemark --Add for mantis : 0038429


		FROM 
			sHrm.vEmployeeCommonDetail ECD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgID
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeeICardOrg ICO ON ECD.OrgId = ICO.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther EO ON EO.EmployeeId = ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EO.EmployeeId
			LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ECD.EmployeeId=EFD.EmployeeId AND EFD.RelationshipId = 2
			--LEFT JOIN sCommon.tRelationshipMaster RM on EFD.RelationshipId=RM.Id AND RM.Id=2
			--LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = ECD.EmployeeId

			
		WHERE
		((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ISNULL(ECD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')   
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
	   AND ISNULL(ECD.IsOtherUser,0)=0
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeJobDetails]
	
	@rOrgId smallint,
	@rTypeId [int],
	@rGradeId [int],
	@rDesignationId [int],
	@rDepartmentId [int],
	@rEmployeeId [int],
	@rReportingTo [int],
	@rIsActive [bit]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

    SELECT 
			  EJD.EmployeeId AS EmployeeId,
			  vEM.Code AS EmployeeNumber,
			  vEM.EmployeeName AS EmployeeName,
			  EJD.EmployeeTypeId AS EmployeeTypeId,
			  ETM.Title AS [Type],
			  EJD.EmployeeGradeId AS GradeId,
			  EGM.Title AS Grade,
			  EJD.EmployeeDesignationId AS DesignationId,
			  EDM.Title AS Designation,
			  EJD.OrganizationDepartmentId AS DepartmentId,
			  ODM.Title AS Department,
			  vEEM.EmployeeName AS ReportingTo 
	  FROM 
			sHrm.tEmployeeJobDetail EJD
	    INNER JOIN sHrm.vExtEmployeeMaster vEM ON EJD.EmployeeId = vEM.Id  	  
		INNER JOIN sHrm.tEmployeeTypeMaster ETM	ON EJD.EmployeeTypeId = ETM.Id
		INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EJD.EmployeeGradeId = EGM.Id
		INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EJD.EmployeeDesignationId = EDM.Id
		INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id
		LEFT OUTER JOIN sHrm.vExtEmployeeMaster vEEM ON EJD.EmployeeId = vEEM.Id
	   WHERE 
			(EJD.EmployeeTypeId = @rTypeId OR @rTypeId = 0) 
	   AND (EJD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (EJD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	   AND (EJD.EmployeeId = @rReportingTo OR @rReportingTo = 0)
	   AND (EJD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (EJD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	   AND vEM.IsObsolete = @rIsActive
	   AND EJD.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeLeaveDetailsGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeName nvarchar(200)='',
	@rEmployeeCode nvarchar (200),
	@rEmployeeId bigint=0,
	@rDepartmentId int=0,
	@rEmployeeGradeId int=0,
	@rForYear  smallint='',
	@rForMonth tinyint='',
	@rBatchId int,
	@rOrgId int,
	@rFromDate date,
	@rToDate date,
	@rLeaveReson nvarchar(100)='',
	@rStatusId int=0,
	@rEmployeeStatusId int = 0 ,
	@rLeaveTypeId int =0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 



       SELECT 
				 @rBuilder1 AS Builder1,
				 @rBuilder2 AS Builder2, 
				 EM.Code AS EmployeeCode,
				 EM.EmployeeName,   
				 EM.EmployeeId,
				 EM.DepartmentName,
				 EM.EmployeeGrade,      
				 --ISNULL(AT.LWP,0) AS LWP,
				 --CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
				 --MM.Title AS MonthName,
		   --      (SELECT  t1.MonthTitle FROM (SELECT MonthTitle,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (100100001))  AS T1
				 --WHERE MonthNumber = 4) AS MonthName,
				 --(SELECT  t2.YearNumber FROM (SELECT YearNumber,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (100100001))  AS T2
				 --WHERE YearNumber = 2014 AND MonthNumber = 4 ) AS YearName,
				 --AT.ForYear As YearName,
				 L.LeaveReason,
				 L.NoOfLeave,
				 L.ReportDate,
				 L.FromDate,
				 L.ToDate,
				 LPM.Title As LeavePeriod,
				 LTM.Title As LeaveType,
				 LTM.IsCarryForward,
				 LTM.IsLWP,
				 ISNULL(SM.Title,'') AS StatusName,
				 OM.Title AS OrganizationTitle,
				 ISNULL(OM.StreetOne,'') AS StreetOne,
				 ISNULL(OM.StreetTwo,'')AS StreetTwo,
				 ISNULL(OM.StreetThree,'')AS StreetThree,
				 ISNULL(OM.CityName,'')AS CityName,
				 ISNULL(OM.StateName,'')AS StateName,
				 ISNULL(OM.CountryName,'')AS CountryName,
				 ISNULL(OM.ZipCode,'')AS ZipCode,
				 ISNULL(EM.EmployeeDesignation,'')AS EmployeeDesignation ,
				 ISNULL(LM.BalanceLeave,0) AS TotalLeave ,
				 ISNULL(EC.MobileNumber,'')AS MobileNumber,
				 ISNULL((SELECT    
						SUM(NoOfLeave) AS UsedLeave
					FROM 
						sHrm.tLeave L1  
					WHERE 
						(L1.EmployeeId = EM.EmployeeId) 
						AND (L1.LeaveTypeId = L.LeaveTypeId)      
						AND BatchId = @rBatchId AND L.OrgId = @rOrgId 
						AND L1.StatusId = 550 -- apporved
						GROUP BY L1.EmployeeId,L1.LeaveTypeId),0) AS UsedLeave, -- Mantis : 0027600
				L.Id AS LeaveId		-- MantisId : 0035002
				,ISNULL(EI.EmployeeSign,0x) AS EmployeeSign-- add for mantis : 0042373	

        FROM 
				sHrm.vEmployeeCommonDetail EM 
		--LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
		--LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
		INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
		INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		--INNER JOIN sHrm.tLeaveBalance LM ON LM.EmployeeId = EM.EmployeeId 
		LEFT JOIN sHrm.tLeaveBalance LM ON LM.EmployeeId = EM.EmployeeId AND LM.BatchId = L.BatchId AND LM.LeaveTypeId = L.LeaveTypeId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.EmployeeId -- add for mantis : 0042373	
    	WHERE 
    	EM.OrgID = @rOrgId 
    	AND L.BatchId=@rBatchId
    	AND (YEAR(L.FromDate) = @rForYear OR @rForYear='') 
    	AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth='') 
    	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 ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
    	AND ((L.LeaveReason Like '%'+@rLeaveReson+'%' ) OR (ISNULL(@rLeaveReson,'')=''))
    	AND ((L.StatusId=@rStatusId) OR (@rStatusId=0))
    	AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
		AND ((LM.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
	ORDER BY L.FromDate DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeList]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	--@rIsDetail bit = 0,
	--@rBloodGroupId [int] = 0,
	--@rMaritalStatusId [int] = 0,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rUserId bigint = 0
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		    ECD.EmployeeId,
	        ECD.Code,	
			[sHrm].[fEmployeeNameGet](ECD.FirstName , ECD.MiddleName, ECD.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,	
			--ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.PhoneNoCompany,
		    ECD.EmployeeDesignation,
		    ECD.ExtensionNo,
		    ECD.DateOfBirth
		    
	FROM 
			[sHrm].[vEmployeeCommonDetail] ECD 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgId
			INNER JOIN sSetup.vDepartment D ON D.Id = ECD.OrganizationDepartmentId
	WHERE
			((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
	   AND ISNULL(ECD.IsOtherUser,0)=0
	   AND (D.UserId = @rUserId OR @rUserId = 0)	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeListAsOnDate]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max)='',
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAsOnDate Date,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rUserId bigint = 0
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		    ECD.EmployeeId,
	        ECD.Code,	
			[sHrm].[fEmployeeNameGet](ECD.FirstName , ECD.MiddleName, ECD.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.PhoneNoCompany,
		    ECD.EmployeeDesignation,
		    ECD.ExtensionNo,
		    ECD.DateOfBirth,
			ECD.DateOfJoining
		    
	FROM 
			[sHrm].[vEmployeeCommonDetail] ECD 
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgId
			INNER JOIN sSetup.vDepartment D ON D.Id = ECD.OrganizationDepartmentId
	WHERE
			((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	   AND  ECD.OrgId = @rOrgId
	   AND ISNULL(ECD.IsOtherUser,0)=0
	   AND (D.UserId = @rUserId OR @rUserId = 0)
	   AND ((ECD.DateOfleaving > @rAsOnDate) OR (ECD.DateOfleaving Is null))
	   AND ((ECD.DateOfJoining <= @rAsOnDate) OR (ECD.DateOfJoining Is null))		
		
		   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeePersonalDetails]
	
	@rOrgId smallint,
	@rTypeId [int],
	@rGradeId [int],
	@rDesignationId [int],
	@rDepartmentId [int],
	@rEmployeeId [int],
	@rAge [smallint],
	@rIsActive [bit]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

	SELECT 
			   EPD.UIDNumber AS UIDNumber,
			   EPD.DateOfBirth AS DateOfBirth,
			   DATEDIFF(YYYY, EPD.DateOfBirth, sCommon.fGetDate()) AS Age,
			   EPD.GenderId AS GenderId,
			   GM.Title AS Gender,
			   EPD.MaritalStatusId AS MaritalStatusId,
			   MSM.Title AS MaritalStatus,
			   EPD.IdentificationMark1 AS IdentificationMark1,
			   vEM.EmployeeName AS EmployeeName
	   FROM 
				sHrm.tEmployeePersonalDetail EPD
	   INNER JOIN sCommon.tGenderMaster GM ON EPD.GenderId = GM.Id
	   INNER JOIN sCommon.tMaritalStatusMaster MSM ON EPD.MaritalStatusId = MSM.Id
	   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EPD.EmployeeId = EJD.EmployeeId
	   INNER JOIN sHrm.vExtEmployeeMaster vEM ON EJD.EmployeeId = vEM.Id  	  
	   INNER JOIN sHrm.tEmployeeTypeMaster ETM ON EJD.EmployeeTypeId = ETM.Id
	   INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EJD.EmployeeGradeId = EGM.Id
	   INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EJD.EmployeeDesignationId = EDM.Id
	   INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id
	   
	   WHERE 
				(EJD.EmployeeTypeId = @rTypeId OR @rTypeId = 0) 
		   AND (EJD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
		   AND (EJD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
		   AND (DATEDIFF(YYYY, EPD.DateOfBirth, sCommon.fGetDate()) = @rAge OR @rAge = 0)
		   AND (EJD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		   AND (EJD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND vEM.IsObsolete = @rIsActive
		   AND EPD.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeePreviousEmploymentSubGet]
	
	@rOrgId int,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			convert(nvarchar(20),EM.Id) AS EmployeeIdText,
			convert(nvarchar(20),@rOrgId) AS OrgIdText,
			EPE.Id,
			EPE.EmployeeId,
			EPE.CompanyName, 		
			ISNULL(EPE.Designation,'') AS Designation,
			ISNULL(EPE.Remark,'') AS Remark,
			ISNULL(EPE.Duration,'') AS Duration ,
			EPE.CreatedUserId,
			EPE.CreatedDateTime,
			EPE.UpdatedUserId,
			EPE.UpdatedDateTime,
			2 AS OperationState,
			ISNULL(EPE.LastSalary,0) AS Lastsalary,
		    ISNULL(EPE.ReasonForLeaving,'') AS ReasonForLeaving,
		    ISNULL(EPE.JobDescription,'') AS JobDescription,
		    ISNULL(EPE.IsInternal,0) AS IsInternal
	 FROM 
			sHrm.tEmployeeMaster EM 
			LEFT JOIN sHrm.tEmployeePreviousEmployment EPE
			ON   EPE.EmployeeId = EM.Id 
	 WHERE 
			 ((EM.Id = @rEmployeeId) OR (@rEmployeeId=0))
		AND EM.OrgId = @rOrgId AND  ISNULL(EM.IsOtherUser,0) = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeProfileGet]
(

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rPayrollId int,
		@rPayrollGroupId int,
		@rPayrollYearId int,
    	@rEmployeeId bigint,
		@rEmployeeCode nvarchar(200),
		@rEmployeeName nvarchar(200),
	    @rOrderByField nvarchar(20)='',
		@rOrgId int = 0,
		@rDepartmentId int = 0,
		@rStatusId int = 0,
	 @rEmployeeGroupId int = 0
)
AS
SET NOCOUNT ON

BEGIN

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

		SELECT 
				@rOrderByField AS OrderByField,
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				EM.EmployeeId AS EmployeeId,
				tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS Name,
				DM.Id AS DepartmentId,
				DM.Title AS DepartmentName,
				CONVERT(date,EJD.DateOfJoining) AS DateOfJoining,
				EM.Code AS Code,
				CONVERT(date,EJD.DateOfleaving) AS DateOfleaving,
				EDM.Title AS Designation,
				EPD.Qualification,
				EM.GenderTitle,
				CONVERT(date,EPD.DateOfBirth) AS DateOfBirth,
				EPD.UIDNumber,
				EC.PersonalEmail AS Email,
				ESO.BankName,
				ESO.AccountNumber,
				ESO.EPFNumber,
				ESO.PanNumber,
				EC.MobileNumber,
				ISNULL(DATEDIFF(YY,EJD.DateOfJoining,EJD.DateOfleaving),'')AS EXPYEAR,
				ISNULL(DATEDIFF(MM,EJD.DateOfJoining,EJD.DateOfleaving),'') AS EXPMONTH,
				EM.FirstName,
				EM.LastName,
				tEM.Number,
				--@lIsOnPrePrinted AS IsOnPrePrinted,
				--@lIsDisplayImageHeader AS IsDisplayImageHeader,
				--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
				(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
				--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
				ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId ,
				ISNULL(ESO.BasicPay,0)AS BasicPay,
				EM.EmployeeGroupId,
				EGM.Title AS EmployeeGroupTitle
				--,PP.SalaryMonth
		FROM 
			sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
			INNER JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
			INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
			INNER JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EM.EmployeeGroupId
		WHERE 
				(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			 AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			 AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			 AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			 AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			 AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			 AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			 AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
			 AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeQualificationGet]
	
		@rEmployeeId bigint,
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rReportId smallint = 0,
		@rOrgId smallint = 0,
		@rStrEmployeeId nvarchar(max)='',
		@rEmployeeTypeId [int] =0,
		@rDepartmentId [int]= 0,
		@rGradeId [int]= 0,
		@rGenderId [int]= 0,	
		@rDesignationId [int]= 0,	
		@rAgeFrom nvarchar(10)='',
		@rAgeTo nvarchar(10)='',
		@rEmployeeCode nvarchar(50)='',
		@rEmployeeGroupId smallint= 0,
		@rEmployeeStatusId smallint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			convert(nvarchar(20),EQ.EmployeeId) AS EmployeeIdText,
			convert(nvarchar(20),@rOrgId) AS OrgIdText,
			EQ.Id,
			EQ.EmployeeId,
			ISNULL(EQ.ExamPassed,'') AS ExamPassed,
			ISNULL(EQ.PassYear,'') AS PassYear,
			ISNULL(EQ.Percentage,0) AS Percentage,
			ISNULL(EQ.Grade,'') AS Grade,
			ISNULL(EQ.InstituteDetail,'') AS InstituteDetail,
			ISNULL(EQ.BoardDetail,'') AS BoardDetail,
			ISNULL(EQ.Subjects,'') AS Subjects,
			ISNULL(EQ.Remark,'') AS Remark,
			EQ.CreatedUserId,
			EQ.CreatedDateTime,
			EQ.UpdatedUserId,
			EQ.UpdatedDateTime,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,
			EM.Code AS EmpCode,
			DM.DisplayTitle AS EmployeeOrgDept,
			ETM.Title AS EmployeeType,
			SM.Title AS EmployeeStatus
	 FROM 
			sHrm.tEmployeeQualification EQ
			LEFT JOIN sHrm.tEmployeeMaster EM ON EQ.EmployeeId = EM.Id
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.ID = EC.EmployeeId
			LEFT JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id
			LEFT JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID		
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EP.BloodGroupId    
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId
			LEFT JOIN sCommon.tMaritalStatusMaster MM ON MM.Id =  EP.MaritalstatusId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId
			LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id=EJ.EmployeeGradeId
			LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJ.EmployeeGroupId
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id
			LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON EFD.EmployeeId = EM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId 
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
	 WHERE 
			(EM.Id=@rEmployeeId OR @rEmployeeId = 0)
			AND (ISNULL(EM.Id,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
			AND ((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
			AND (ETM.Id = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
			AND (DM.Id = @rDepartmentId OR @rDepartmentId = 0)
			AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
			AND (GrpM.Id=@rEmployeeGroupId OR @rEmployeeGroupId=0) 
			AND (EGM.Id = @rGradeId OR @rGradeId = 0)
			AND (EDM.Id = @rDesignationId OR @rDesignationId = 0)
			AND (GM.Id = @rGenderId OR @rGenderId = 0)
			AND ((DATEDIFF(yy,EP.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
			AND ((DATEDIFF(yy,EP.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
			AND  ( (EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND  ISNULL(EM.IsOtherUser,0) = 0
	 ORDER BY
			EQ.PassYear DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeQualificationSubGet]
	
	@rOrgId int,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			convert(nvarchar(20),EmployeeId) AS EmployeeIdText,
			convert(nvarchar(20),@rOrgId) AS OrgIdText,
			Id,
			EmployeeId,
			ISNULL(ExamPassed,'') AS ExamPassed,
			
			ISNULL(PassYear,'') AS PassYear,
			ISNULL(Percentage,0) AS Percentage,
			ISNULL(Grade,'') AS Grade,
			ISNULL(InstituteDetail,'') AS InstituteDetail,
			ISNULL(BoardDetail,'') AS BoardDetail,
			ISNULL(Subjects,'') AS Subjects,
			ISNULL(Remark,'') AS Remark,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		
		
	 FROM 
			sHrm.tEmployeeQualification
	 WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		    AND OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptEmployeeStatutoryDetailSubGet]
	
	@rOrgId smallint,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
		  convert(nvarchar(20),EmployeeId) AS EmployeeIdText,
		  convert(nvarchar(20),@rOrgId) AS OrgIdText,
		    [EmployeeId]
		  , [EPFNumber]
		  , [IsVPFDeduction]
		  ,ISNULL([VPFContributionId],0) AS VPFContributionId
		  ,ISNULL([VPFContributionEffectiveFrom],'1/1/0001')  AS VPFContributionEffectiveFrom
		  ,ISNULL([VPFPercentage],0) AS VPFPercentage
		  ,ISNULL([VPFAmount],0) AS VPFAmount
		  ,[ESINumber]
		  ,[BankName]
		  ,[Branch]
		  ,[AccountNumber]
		  ,[IFSCNumber]
		  ,[PanNumber]
		  ,ISNULL([IncomeTaxStatusId],0) AS IncomeTaxStatusId       
		  ,ISNULL([IncrementDate],'1/1/0001') AS IncrementDate
		  ,ISNULL([BasicPay],0) AS BasicPay
		  ,ISNULL([PayrollId],0) AS PayrollId
		  ,ISNULL([PayrollGroupId],0) AS PayrollGroupId 
		  ,ISNULL([Payscale],'') AS Payscale
		  ,ISNULL([EPFJoinDate],'1/1/0001') AS EPFJoinDate
		  ,ISNULL(UAN,'') AS UAN
	FROM 
			[sHrm].[tEmployeeStatutoryAndOther] 
			 
	Where 
			 EmployeeId = @rEmployeeId	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pRptEmploymentCertificateGet]
	
	 
	 --@rReportId int=0,
	-- @rStrEmployeeId nvarchar(max),
	 --@rEmployeeTypeId [int]= 0,
	@rEmployeeId [bigint]= 0,
	 --@rEmployeeGroupId smallint=0,
	-- @rEmployeeStatusId smallint=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rCode nvarchar(20)='',
	 --@rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rFromDate date='',
     @rToDate date='',
     @rName nvarchar(20)=''
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)
DECLARE @lIsDisplayImageHeader bit=0

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        EM.EmployeeName,
	       	EM.FirstName,
			EM.MiddleName,
			EM.LastName,	
			EM.ShortName,
			EM.OrgID,
			EM.GenderId,
			EM.DateOfJoining,
			EM.StatusId,
			EM.UserId,
			EM.DepartmentId,
			--EM.DepartmentCode,
			EM.EmployeeTypeId,
			EM.DesignationId,
			EM.Designation,
			--EM.EmployeeGroup,
			--EM.EmployeeGroupId,
			EM.EmployeePhoto,
			EC.PresentStreetOne,
			EC.PresentStreetTwo,
			EC.PresentStreetThree,
			EC.PresentCity,
			EC.PresentState,
			EC.PresentCountry,
			EC.PresentZipCode,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4 ,
			CE.Remark,
			CE.CertificateReason,
			CE.CertificateDate,
			CE.Number,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,	
			ISNULL(EM.MaritalStatusId,0)AS MaritalStatusId,
			RRG.SchoolRequiredSignature,
			ISNULL(ES.RetirementDate,'') AS RetirementDate
			
	FROM 
	        sHrm.tCertificateEmployment CE
            INNER JOIN [sHrm].[vExtEmployeeMaster] EM  ON EM.EmployeeId=CE.EmployeeId  
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.EmployeeId=EC.EmployeeId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EM.GenderId
		    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=7
			INNER JOIN [sHrm].[tEmployeeStatutoryAndOther] AS ES ON ES.EmployeeId = CE.EmployeeId
	WHERE
			((EM.Code LIKE @rCode)OR (@rCode = '' ))
	   --AND (ISNULL(EM.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	   AND ((EM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))
	   AND ((CE.Number=@rNumber) OR (@rNumber=''))
	   AND ((CE.Number >= @rFromNo) OR (@rFromNo=0))
	   AND ((CE.Number <= @rToNo) OR (@rToNo=0))
	   AND ((CE.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	   AND ((CE.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))	   
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  EM.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sHrm].[pRptExperienceCertificateGet]
	
	 
	 --@rReportId int=0,
	-- @rStrEmployeeId nvarchar(max),
	 --@rEmployeeTypeId [int]= 0,
	@rEmployeeId [bigint]= 0,
	 --@rEmployeeGroupId smallint=0,
	-- @rEmployeeStatusId smallint=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rCode nvarchar(20)='',
	 --@rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rFromDate date='',
     @rToDate date='',
     @rName nvarchar(20)=''
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)
DECLARE @lIsDisplayImageHeader bit=0

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        EM.EmployeeName,
	       	EM.FirstName,
			EM.MiddleName,
			EM.LastName,	
			EM.ShortName,
			EM.OrgID,
			EM.GenderId,
			EM.DateOfJoining,
			EM.StatusId,
			EM.UserId,
			EM.DepartmentId,
			EM.DateOfleaving,
			EM.EmployeeTypeId,
			EM.DesignationId,
			EM.Designation,
			--EM.EmployeeGroup,
			--EM.EmployeeGroupId,
			EM.EmployeePhoto,
			EC.PresentStreetOne,
			EC.PresentStreetTwo,
			EC.PresentStreetThree,
			EC.PresentCity,
			EC.PresentState,
			EC.PresentCountry,
			EC.PresentZipCode,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4 ,
			CE.Remark,
			CE.CertificateReason,
			CE.CertificateDate,
			CE.Number,
			convert(varchar(4),DATEDIFF(MONTH, EM.DateOfJoining, EM.DateOfleaving)/12) +' years '+
			convert(varchar(2),DATEDIFF(MONTH, EM.DateOfJoining, EM.DateOfleaving) % 12)+ ' months' As ExpMonth,
			EM.MaritalStatusId,
			RRG.SchoolRemark1,
			RRG.SchoolRemark2,
			RRG.SchoolRemark3,
			RRG.SchoolRequiredSignature,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			convert(varchar(4),DATEDIFF(MONTH, EM.DateOfJoining, EM.DateOfleaving)/12) AS years,  --Mantis - 35275
			convert(varchar(2),DATEDIFF(MONTH, EM.DateOfJoining, EM.DateOfleaving) % 12) AS months,  --Mantis - 35275
			EM.Qualification,	 --Mantis - 35275
			ISNULL(U.DisplayTitle,'') AS UserName,	--Mantis : 0038104		 
			ISNULL(OM.CityName,'') AS CityName,    --added by dhannajay for mantis : 39862
			ISNULL(EM.DepartmentName,'') AS DepartmentName    --added by dhananjay for manntis :  40755
			
	FROM 
	        sHrm.tCertificateExperience CE
            INNER JOIN [sHrm].[vExtEmployeeMaster] EM  ON EM.EmployeeId=CE.EmployeeId  
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.EmployeeId=EC.EmployeeId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EM.GenderId
		    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=7
			LEFT JOIN sSecurity.tUser U ON U.Id=CE.CreatedUserId --Mantis : 0038104	
	WHERE
			((EM.Code LIKE @rCode)OR (@rCode = '' ))
	   --AND (ISNULL(EM.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	   AND ((EM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))
	   AND ((CE.Number=@rNumber) OR (@rNumber=''))
	   AND ((CE.Number >= @rFromNo) OR (@rFromNo=0))
	   AND ((CE.Number <= @rToNo) OR (@rToNo=0))
	   AND ((CE.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	   AND ((CE.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))	   
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  EM.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pRptIncrementCertificateGet]  
  
  @rEmployeeId [bigint]= 0,  
  @rBuilder1 nvarchar(max)='',  
  @rBuilder2 nvarchar(max)='',   
  @rOrgId smallint,  
  @rCode nvarchar(20)='',  
  @rFromNo int=0,  
  @rToNo int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rName nvarchar(20)='' ,
  @rBatchId int =0
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  
  
BEGIN  
DECLARE @lIsOnPrePrinted bit = 0  
  
DECLARE @lConfigValue nvarchar(50)  
DECLARE @lIsDisplayImageHeader bit=0  
  
SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 AND SourceTypeId = 1016 AND SourceId = @rOrgId  
   
 IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')  
 BEGIN  
 SET @lIsOnPrePrinted = 0  
 SET @lIsDisplayImageHeader = 0  
 END  
 ELSE IF (@lConfigValue = 'Blank')  
 BEGIN  
 SET @lIsOnPrePrinted = 1  
 SET @lIsDisplayImageHeader = 0  
 END  
 ELSE IF (@lConfigValue = 'Image')  
 BEGIN  
 SET @lIsOnPrePrinted = 0  
 SET @lIsDisplayImageHeader = 1  
 END  
   
   
   
 SELECT  
   @rBuilder1 AS Builder1,  
   @rBuilder2 AS Builder2,  
         EM.Id AS EmployeeId,  
         EM.Code,  
         EM.EmployeeName,  
         EM.FirstName,  
   EM.MiddleName,  
   EM.LastName,   
   EM.ShortName,  
   EM.OrgID,  
   EM.DepartmentId,  
   EM.DepartmentName,  
   EM.DesignationId,  
   EM.Designation,  
   EM.EmployeePhoto, 
   EM.DateOfJoining, 
      CI.Qualification,  
   @lIsOnPrePrinted AS IsOnPrePrinted,  
   @lIsDisplayImageHeader AS IsDisplayImageHeader,  
   OI.CertificateHeaderA4 ,  
   CI.Remark,  
   CI.CertificateDate,  
   EM.MaritalStatusId,  
   BM.Title as Batch,  
   CI.PayScale,  
 CI.ExistingBasicPay,  
 CI.RevisedBasicPay,   
 CI.RevisedBasicPayDate,  
 CI.GradePayInRevisedPayStructure,  
 CI.BasicPayInRevisedPayStructureBasicPayAndGradePay,  
 CI.GrossSalaryAsPerExistingPayScale,  
 CI.RevisedGrossSalaryAsOn,   
 CI.IncrementDate,  
 CI.Number
 --(CASE WHEN OI.CertificateHeaderA4Portrait IS NULL THEN
 --OI.CertificateHeaderA4
 --ELSE OI.CertificateHeaderA4Portrait END ) AS CertificateHeader  
 FROM   
         sHrm.tCertificateIncrement CI   
            INNER JOIN [sHrm].[vExtEmployeeMaster] EM  ON EM.EmployeeId=CI.EmployeeId    
   LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = CI.BatchId  
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId  
   LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id 
   
   
 WHERE    ((EM.Code LIKE @rCode)OR (@rCode = '' ))     AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))     AND ((EM.FirstName like @rName) OR (ISNULL(@rName,'') = ''))  
			AND ((BM.Id = @rBatchId) OR (@rBatchId = 0)) 
    AND ((CI.Number >= @rFromNo) OR (ISNULL(@rFromNo,0)=0))  
    AND ((CI.Number <= @rToNo) OR (ISNULL(@rToNo,0)=0))  
    AND ((CI.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
    AND ((CI.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))        AND  EM.OrgId = @rOrgId  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pRptJoiningCertificateGet]  
 
  @rEmployeeId [bigint]= 0, 
  @rBuilder1 nvarchar(max)='',  
  @rBuilder2 nvarchar(max)='',    
  @rOrgId smallint,  
  @rCode nvarchar(20)='',  
  @rFromNo int=0,  
  @rToNo int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rName nvarchar(20)='',
  @rBatchName nvarchar(100)='' --added for mantis - 37085
  ,@rPrintTemplateId int = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  
  
BEGIN  
DECLARE @lIsOnPrePrinted bit = 0  
  
DECLARE @lConfigValue nvarchar(50)  
DECLARE @lIsDisplayImageHeader bit=0  

DECLARE @lTemplate nvarchar(max) = '' 
SELECT @lTemplate = Template FROM sCertificate.tPrintTemplate WHERE PrintTemplateFunctionalityId = 7 AND Id = @rPrintTemplateId

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 AND SourceTypeId = 1016 AND SourceId = @rOrgId  
   
 IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')  
 BEGIN  
 SET @lIsOnPrePrinted = 0  
 SET @lIsDisplayImageHeader = 0  
 END  
 ELSE IF (@lConfigValue = 'Blank')  
 BEGIN  
 SET @lIsOnPrePrinted = 1  
 SET @lIsDisplayImageHeader = 0  
 END  
 ELSE IF (@lConfigValue = 'Image')  
 BEGIN  
 SET @lIsOnPrePrinted = 0  
 SET @lIsDisplayImageHeader = 1  
 END  
   
 SELECT  
   @rBuilder1 AS Builder1,  
   @rBuilder2 AS Builder2,  
   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, 
   @lIsOnPrePrinted AS IsOnPrePrinted,  
   @lIsDisplayImageHeader AS IsDisplayImageHeader,  
   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 AS LocalAddress,
    EC.PresentStreetOne  + CASE WHEN EC.PresentStreetOne = '' OR (EC.PresentStreetTwo = '' AND EC.PresentStreetThree = '') Then '' ELSE '-' END 
   		    + EC.PresentStreetTwo + CASE WHEN EC.PresentStreetTwo = '' OR EC.PresentStreetThree = '' Then '' ELSE '-' END	
			+ EC.PresentStreetThree AS LocalAddress,
   --EC.PresentCity+ '-'+EC.PresentState+'-'+EC.PresentZipCode+'-'+EC.PresentContactNo As LocalAddress1,
	EC.PresentCity  + CASE WHEN EC.PresentCity = '' OR (EC.PresentState = '' AND EC.PresentZipCode = '' AND EC.PresentContactNo = '') Then '' ELSE '-' END 
		+ EC.PresentState + CASE WHEN EC.PresentState = '' OR (EC.PresentZipCode = '' AND EC.PresentContactNo = '') Then '' ELSE '-' END	
		+ EC.PresentZipCode + CASE WHEN EC.PresentZipCode = '' OR EC.PresentContactNo = '' Then '' ELSE '-' END
		+ EC.PresentContactNo AS LocalAddress1,
   ISNULL(EDM1.Title,'Admin') AS UserDesignation,
   --Replace(Replace(RTrim(Ltrim(EC.PresentCity +' '+ EC.PresentState +' '+ EC.PresentZipCode)),'  ',' '),' ','-') AS LocalAddress2
   EC.PresentCity  + CASE WHEN EC.PresentCity = '' OR (EC.PresentState = '' AND EC.PresentZipCode = '') Then '' ELSE '-' END 
   		    + EC.PresentState + CASE WHEN EC.PresentState = '' OR EC.PresentZipCode = '' Then '' ELSE '-' END	
			+ EC.PresentZipCode AS LocalAddress2,
	ISNULL(CJ.DateOfJoining,'') As CertificateDateOfJoining,
	EM.GenderId,
	@rBatchName AS BatchName --added for mantis - 37085
	,[sHrm].[fEmployeeJoiningCertificateTemplate](EM.EmployeeId,@lTemplate) AS Template --add for mantis : 42473

 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
	  LEFT JOIN  sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId  --added
	  INNER JOIN  sSetup.tDepartmentMaster DM ON DM.Id=CJ.DepartmentId
	  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
 WHERE    
 
    ((EM.Code LIKE @rCode)OR (@rCode = '' ))     
    AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))    
    AND ((EM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))
    AND ((CJ.Number >= @rFromNo) OR (ISNULL(@rFromNo,0)=0))  
    AND ((CJ.Number <= @rToNo) OR (ISNULL(@rToNo,0)=0))  
    AND ((CJ.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
    AND ((CJ.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
    AND  EM.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR 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
        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 (
				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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pRptRelievingCertificateGet]
	
	 
	 --@rReportId int=0,
	-- @rStrEmployeeId nvarchar(max),
	 --@rEmployeeTypeId [int]= 0,
	@rEmployeeId [bigint]= 0,
	 --@rEmployeeGroupId smallint=0,
	-- @rEmployeeStatusId smallint=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rCode nvarchar(20)='',
	 --@rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rFromDate date='',
     @rToDate date='',
     @rName nvarchar(20)=''
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)
DECLARE @lIsDisplayImageHeader bit=0

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        EM.EmployeeName,
	       	EM.FirstName,
			EM.MiddleName,
			EM.LastName,	
			EM.ShortName,
			EM.OrgID,
			EM.GenderId,
			EM.DateOfJoining,
			EM.StatusId,
			EM.UserId,
			EM.DepartmentId,
			EM.DateOfleaving,
			EM.EmployeeTypeId,
			EM.DesignationId,
			EM.Designation,
			EM.EmployeePhoto,
			EC.PresentStreetOne,
			EC.PresentStreetTwo,
			EC.PresentStreetThree,
			EC.PresentCity,
			EC.PresentState,
			EC.PresentCountry,
			EC.PresentZipCode,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4 ,
			CE.JobRemark,
			CE.CertificateDate,
			CE.Number,
			ISNULL(EM.MaritalStatusId,0)AS MaritalStatusId,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			RRG.SchoolRequiredSignature	
			 
			
	FROM 
	        sHrm.tCertificateRelieving CE
            INNER JOIN [sHrm].[vExtEmployeeMaster] EM  ON EM.EmployeeId=CE.EmployeeId  
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.EmployeeId=EC.EmployeeId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EM.GenderId
		    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=7
	WHERE
			((EM.Code LIKE @rCode)OR (@rCode = '' ))
	   --AND (ISNULL(EM.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	   AND ((EM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))
	   AND ((CE.Number=@rNumber) OR (@rNumber=''))
	   AND ((CE.Number >= @rFromNo) OR (@rFromNo=0))
	   AND ((CE.Number <= @rToNo) OR (@rToNo=0))
	   AND ((CE.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	   AND ((CE.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))	   
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  EM.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sHrm].[pSettlementDays]        
@rEmployeeId  bigint,             
@rLastSalaryDate date,          
@rLastWorkingDate date,          
@rBatchId int,
@rPerMonthLeave decimal(4,2) = 1.50,
@rLatePunchTime time = '10:30'

AS          
SET NOCOUNT ON          
BEGIN          


        
CREATE TABLE #TEMPTBL(ID INT IDENTITY(1,1),[Total Leave CL] VARCHAR(100),[Eligible CL  Balance] VARCHAR(100),[Total Comp off] VARCHAR(100),        
[Total Other] VARCHAR(100),[Used CL(Approved CL)] VARCHAR(100),[Pending CL] VARCHAR(100),[Pending Comp off] VARCHAR(100),[Pending Other] VARCHAR(100),        
[Pending LWP] VARCHAR(100),[Balance] VARCHAR(100),[Allowance Days] VARCHAR(100),[LATE PUNCH] VARCHAR(100),[LATE PUNCH AFTER 10:30 (During Notice Period)] VARCHAR(100),[Approved LWP] VARCHAR(100),[Approved VA] VARCHAR(100),
[Not Approved CL] VARCHAR(100),[Not Approved LWP] VARCHAR(100),[Not Approved VA] VARCHAR(100))        
        
Declare @TotalLeave float = (Select SUM(BalanceLeave) from  sHrm.tLeaveBalance LB inner join sHrm.tLeaveTypeMaster LTM on LTM.Id = LB.LeaveTypeid         
       Where LB.BatchId = @rBatchId And LB.EmployeeId = @rEmployeeId And LTM.MainLeaveTypeId = 1)        
        
Declare @DateofJoining date = (SELECT DateOfJoining FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rEmployeeId)
Declare @BatchStartDate date = (select fromdate from [sSetup].[tBatchMaster] where id=@rBatchId)
Declare @BatchToDate date = (select todate from [sSetup].[tBatchMaster] where id=@rBatchId)
Declare @StartDate date 


IF(@DateofJoining > @BatchStartDate )
BEGIN
SET @StartDate = @DateofJoining
END
ELSE
BEGIN
SET @StartDate = @BatchStartDate
END

Declare @BatchMonthDiff int  = (SELECT DATEDIFF(month, @StartDate, @BatchToDate) + 1 AS DateDiff); 

--Declare @PerMonthLeave float = round((@TotalLeave * 1.0) / @BatchMonthDiff,2,2)        

Declare @MonthDiff int  = (SELECT DATEDIFF(month, @StartDate, @rLastWorkingDate) - 1 AS DateDiff);   
     
Declare @LeaveForRemainingDays float,@LeaveForFirstMonth float;        
      
Declare @lLastDayOfMonth int = DAY(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@rLastWorkingDate)+1,0)))       

 IF(@rPerMonthLeave=1.50)
 BEGIN
        
 if(day(@rLastWorkingDate) >= 10 AND day(@rLastWorkingDate) < 20 )        
 begin        
  set @LeaveForRemainingDays= 0.5        
 end        
 else if(day(@rLastWorkingDate) >= 20 AND day(@rLastWorkingDate) < @lLastDayOfMonth )       
 begin        
  set @LeaveForRemainingDays= 1.0        
 end        
 else if(day(@rLastWorkingDate) = @lLastDayOfMonth)        
 begin        
  set @LeaveForRemainingDays= 1.5        
 end        
 else        
 begin        
  set @LeaveForRemainingDays= 0        
 end  
 
 if(day(@StartDate) = 1)
 begin
	set @LeaveForFirstMonth = 1.5
 end     
 else if(day(@StartDate) > 1 AND day(@StartDate) <=10)
 begin
	set @LeaveForFirstMonth = 1.0
 end
 else if(day(@StartDate) > 10 AND day(@StartDate) <= 20)
 begin
	set @LeaveForFirstMonth = 0.5
 end
 else
 begin
	set @LeaveForFirstMonth = 0
 end

 END
 ELSE IF(@rPerMonthLeave=1.25)
 BEGIN

 if(day(@rLastWorkingDate) >= 10 AND day(@rLastWorkingDate) < 20 )        
 begin        
   set @LeaveForRemainingDays= 0.41        
 end        
 else if(day(@rLastWorkingDate) >= 20 AND day(@rLastWorkingDate) < @lLastDayOfMonth )       
 begin        
   set @LeaveForRemainingDays= 0.83        
 end        
 else if(day(@rLastWorkingDate) = @lLastDayOfMonth)        
 begin        
   set @LeaveForRemainingDays= 1.25        
 end    
 else        
 begin			
   set @LeaveForRemainingDays= 0        
 end

 if(day(@StartDate) = 1)
 begin
	set @LeaveForFirstMonth = 1.25
 end     
 else if(day(@StartDate) > 1 AND day(@StartDate) <=10)
 begin
	set @LeaveForFirstMonth = 0.83
 end
 else if(day(@StartDate) > 10 AND day(@StartDate) <= 20)
 begin
	set @LeaveForFirstMonth = 0.41
 end
 else
 begin
	set @LeaveForFirstMonth = 0
 end
      
 END
 
Declare @EligibleCLBalance decimal(4,2) = (@MonthDiff * @rPerMonthLeave) + @LeaveForRemainingDays + @LeaveForFirstMonth       
        
Declare @TotalCompOff Float =(Select SUM(BalanceLeave) from  sHrm.tLeaveBalance LB inner join sHrm.tLeaveTypeMaster LTM on LTM.Id = LB.LeaveTypeid         
       Where LB.BatchId = @rBatchId And LB.EmployeeId = @rEmployeeId And LTM.MainLeaveTypeId = 3)         
        
Declare @TotalOtherOff Float = (Select SUM(BalanceLeave) from  sHrm.tLeaveBalance LB inner join sHrm.tLeaveTypeMaster LTM on LTM.Id = LB.LeaveTypeid         
       Where LB.BatchId = @rBatchId And LB.EmployeeId = @rEmployeeId And LTM.MainLeaveTypeId = 5)        
        
Declare @UsedCL Float = (SELECT isnull(sum(NoOfLeave),0) FROM  sHrm.tLeave L inner join sHrm.tLeaveTypeMaster LTM on L.LeaveTypeId = LTM.Id         
      where L.EmployeeId = @rEmployeeId and L.BatchId = @rBatchId        
      and MainLeaveTypeId = 1 and Datediff(day,ToDate,@rLastSalaryDate) >0 and L.statusId = 550)        
        
Declare @PendingCL Float = (SELECT isnull(sum(NoOfLeave),0) FROM  sHrm.tLeave L inner join sHrm.tLeaveTypeMaster LTM on L.LeaveTypeId = LTM.Id         
      where L.EmployeeId = @rEmployeeId and L.BatchId = @rBatchId        
      and LTM.MainLeaveTypeId = 1 and Datediff(day,ToDate,@rLastSalaryDate) <= 0)        
        
Declare @PendingCompOff Float = (SELECT isnull(SUM(NoOfLeave),0) FROM  sHrm.tLeave L inner join sHrm.tLeaveTypeMaster LTM on L.LeaveTypeId = LTM.Id         
        WHERE BatchId = @rBatchId And EmployeeId = @rEmployeeId and LTM.MainLeaveTypeid = 3 )
		--and Datediff(day,ToDate,@rLastSalaryDate) < 0)        
        
Declare @PendingOther Float =  (SELECT isnull(SUM(NoOfLeave),0) FROM  sHrm.tLeave L inner join sHrm.tLeaveTypeMaster LTM on L.LeaveTypeId = LTM.Id         
       WHERE BatchId = @rBatchId And EmployeeId = @rEmployeeId and LTM.MainLeaveTypeid = 5  and Datediff(day,ToDate,@rLastSalaryDate) < 0)        
        
Declare @PendingLWP Float = (SELECT isnull(SUM(NoOfLeave),0) FROM  sHrm.tLeave L inner join sHrm.tLeaveTypeMaster LTM on L.LeaveTypeId = LTM.Id         
       WHERE BatchId = @rBatchId And EmployeeId = @rEmployeeId and LTM.MainLeaveTypeid = 4  and Datediff(day,ToDate,@rLastSalaryDate) < 0)        
   
   --SET @EligibleCLBalance = ROUND(isnull(@EligibleCLBalance,0),0)
   
        
Declare @Balance Float = (ISNULL(@EligibleCLBalance,0) +ISNULL(@TotalCompOff,0) +ISNULL( @TotalOtherOff,0)) - (ISNULL(@UsedCL,0) + ISNULL(@PendingCL,0) + ISNULL(@PendingCompOff,0) + ISNULL(@PendingOther,0) + ISNULL(@PendingLWP,0))        

-------Not Approved--------------
Declare @ApprovedLWP Float = (SELECT isnull(sum(NoOfLeave),0) FROM  sHrm.tLeave L inner join sHrm.tLeaveTypeMaster LTM on L.LeaveTypeId = LTM.Id         
      where L.EmployeeId = @rEmployeeId and L.BatchId = @rBatchId        
      and MainLeaveTypeId = 4 and Datediff(day,ToDate,@rLastSalaryDate) >0 and L.statusId = 550)   

Declare @ApprovedVA Float = (SELECT isnull(sum(NoOfLeave),0) FROM  sHrm.tLeave L inner join sHrm.tLeaveTypeMaster LTM on L.LeaveTypeId = LTM.Id         
      where L.EmployeeId = @rEmployeeId and L.BatchId = @rBatchId        
      and MainLeaveTypeId = 5 and Datediff(day,ToDate,@rLastSalaryDate) >0 and L.statusId = 550)

Declare @NotApprovedCL Float = (SELECT isnull(sum(NoOfLeave),0) FROM  sHrm.tLeave L inner join sHrm.tLeaveTypeMaster LTM on L.LeaveTypeId = LTM.Id         
      where L.EmployeeId = @rEmployeeId and L.BatchId = @rBatchId        
      and MainLeaveTypeId = 1 and Datediff(day,ToDate,@rLastSalaryDate) >0 and L.statusId = 549)  

Declare @NotApprovedLWP Float = (SELECT isnull(sum(NoOfLeave),0) FROM  sHrm.tLeave L inner join sHrm.tLeaveTypeMaster LTM on L.LeaveTypeId = LTM.Id         
      where L.EmployeeId = @rEmployeeId and L.BatchId = @rBatchId        
      and MainLeaveTypeId = 4 and Datediff(day,ToDate,@rLastSalaryDate) >0 and L.statusId = 549)

Declare @NotApprovedVA Float = (SELECT isnull(sum(NoOfLeave),0) FROM  sHrm.tLeave L inner join sHrm.tLeaveTypeMaster LTM on L.LeaveTypeId = LTM.Id         
      where L.EmployeeId = @rEmployeeId and L.BatchId = @rBatchId        
      and MainLeaveTypeId = 5 and Datediff(day,ToDate,@rLastSalaryDate) >0 and L.statusId = 549)
------------------------------------------------------------------------------------------------------------------------------------------
--SELECT @Balance AS Balance,  @EligibleCLBalance AS EligibleCLBalance , @TotalCompOff AS TotalCompOff , @TotalOtherOff AS TotalOtherOff , @UsedCL AS UsedCL, @PendingCL AS PendingCL, @PendingCompOff AS PendingCompOff, @PendingOther AS PendingOther , @PendingLWP AS PendingLWP 

create table #temp(id int identity(1,1),O_Time varchar(10),LP varchar(10))

declare @Allowance int
declare @Latepunch int
declare @LatepunchAfter1030 int

declare @datefrom datetime = @rLastSalaryDate
declare @dateto datetime = @rLastWorkingDate

while(@datefrom<=@dateto)
begin
declare @query varchar(500)
set @query	= 'select '+'D'+RIGHT(100+convert(int,convert(varchar(20),DATEPART(day,@datefrom))),2) + '_O'+','+
				'D'+RIGHT(100+convert(int,convert(varchar(20),DATEPART(day,@datefrom))),2) + '_IN'+
				' from [sBiometric].[tMonthTrans] where Attn_Dt ='+''''+ 
				convert(varchar(25),(SELECT DATEADD(month, DATEDIFF(month, 0,convert(varchar(25),@datefrom,121)), 0)),121)+''''+
				' and Employeeid = ' + convert(varchar(15),@rEmployeeId)
print @query
insert into #temp
exec (@query)
set @datefrom = DATEADD(day, 1, @datefrom)
end

set @Allowance = (select count(*) from #temp where convert(time,O_Time) >= '01:20')
set @Latepunch = (select count(*) from #temp where convert(time,LP) > @rLatePunchTime)
set @LatepunchAfter1030 = (select count(*) from #temp where convert(time,LP) > '10:30')
drop table #temp

------------------------------------------------------------------------------------------------------------------------------------------


INSERT INTO #TEMPTBL        
SELECT isnull(@TotalLeave,0),
--ROUND(isnull(@EligibleCLBalance,0),0),
 isnull(@EligibleCLBalance,0),
isnull(@TotalCompOff,0),isnull(@TotalOtherOff,0),        
isnull(@UsedCL,0),isnull(@PendingCL,0),(ISNULL(@TotalCompOff,0) - ISNULL(@PendingCompOff,0)),isnull(@PendingOther,0),isnull(@PendingLWP,0),
--ROUND(isnull(@Balance,0),0),
 isnull(@Balance,0) - (ISNULL(@TotalCompOff,0) - ISNULL(@PendingCompOff,0)) ,
isnull(@allowance,0),isnull(@latepunch,0),isnull(@LatepunchAfter1030,0),@ApprovedLWP,@ApprovedVA,@NotApprovedCL,@NotApprovedLWP,@NotApprovedVA
  
DECLARE @SQL NVARCHAR(MAX);

SET @SQL = 'SELECT NAME,EMPLOYEE        
			FROM         
			   (SELECT Id,[Total Leave CL],[Eligible CL  Balance] as [Eligible CL Balance ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastWorkingDate, 106)+')],[Total Comp off] as [Total Comp off ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastSalaryDate, 106)+')],
			   [Total Other],[Used CL(Approved CL)] as [Used CL(Approved CL) ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastSalaryDate, 106)+')],[Pending CL] as [Pending CL (During Notice Period)],[Pending Comp off] as [Pending Comp off (During Notice Period)],
			   [Pending Other] as [Pending Other (During Notice Period)],[Pending LWP] as [Pending LWP (During Notice Period)],[Balance],  
			   [Allowance Days], [LATE PUNCH] as [LATE PUNCH (During Notice Period)], [LATE PUNCH AFTER 10:30 (During Notice Period)],[Approved LWP] as [Approved LWP ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastSalaryDate, 106)+')],[Approved VA],[Not Approved CL] as [Not Approved CL ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastWorkingDate, 106)+')],[Not Approved LWP] as [Not Approved LWP ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastWorkingDate, 106)+')],[Not Approved VA]
			   FROM #TEMPTBL) p        
			UNPIVOT        
			   (EMPLOYEE FOR NAME IN         
				  ([Total Leave CL],[Eligible CL Balance ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastWorkingDate, 106)+')],[Total Comp off ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastSalaryDate, 106)+')],
				  [Total Other],[Used CL(Approved CL) ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastSalaryDate, 106)+')],[Pending CL (During Notice Period)],[Pending Comp off (During Notice Period)],
				  [Pending Other (During Notice Period)],[Pending LWP (During Notice Period)],[Balance],
				  [Allowance Days], [LATE PUNCH (During Notice Period)], [LATE PUNCH AFTER 10:30 (During Notice Period)],[Approved LWP ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastSalaryDate, 106)+')],[Approved VA],[Not Approved CL ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastWorkingDate, 106)+')],[Not Approved LWP ('+ convert(varchar, @BatchStartDate, 106) +' To '+convert(varchar, @rLastWorkingDate, 106)+')],[Not Approved VA])        
			)AS unpvt';

exec (@SQL);
DROP TABLE #TEMPTBL

--SELECT @Balance AS Balance,  @EligibleCLBalance AS EligibleCLBalance , @TotalCompOff AS TotalCompOff , @TotalOtherOff AS TotalOtherOff , @UsedCL AS UsedCL, @PendingCL AS PendingCL, @PendingCompOff AS PendingCompOff, @PendingOther AS PendingOther , @PendingLWP AS PendingLWP 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pShiftAllocationEmployeeListGet]
	 
	 @rOrgId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
	        EM.Id AS EmployeeId,
			EM.Code,
			EM.StatusId,
			EM.FirstName+' '+EM.MiddleName+' '+EM.LastName As EmployeeName
	 FROM 
			sHrm.tEmployeeMaster EM 
	   
	 WHERE  
			EM.OrgId = @rOrgId
	    AND (EM.StatusId = 7)
	    AND (EM.IsObsolete=0) AND  ISNULL(EM.IsOtherUser,0) = 0
	    order by EmployeeName asc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pStaffAttendaceDashboardGet]
	 
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId bigint =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--Changes for Mantis Id: 0039838
DECLARE @lConfigValueDashboard nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValueDashboard = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValueDashboard, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValueDashboard <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValueDashboard <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

if @rTypeId=1
BEGIN
	IF(@rSyncDate=1)
	BEGIN
		DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		INSERT INTO sHrm.tTempStaffAttendance
	SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,
	'' As OrgTitle,
 --TotalCount
			ISNULL((SELECT COUNT(EM.Id) FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			--INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
			--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM.IsOtherUser,0) = 0),0) 
			AS TotalCount,

 --PresentCount
    ISNULL((SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
      ),0) AS PresentCount,
--AbsentCount
      ISNULL((SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
      ),0) As AbsentCount,
--LeaveCount
    ISNULL( (SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId				
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		  INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId   and EM.statusid=7 
		  AND  ISNULL(EM.IsOtherUser,0) = 0
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	),0) As LeaveCount,
--AB10Count
	 ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',
--AB3DaysCount
    ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
--Leave3DayCount    
  ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
   
--HundredPerAttnCount		
    ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount',
--PendingCount	  
	    ISNULL((SELECT 
        COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE OGM.Id=OGMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM.IsOtherUser,0) = 0
	 
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ),0) AS PendingCount,
	   
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId   AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And ISNULL(OGM.IsObsolete,0) = 0
		SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
	END
	ELSE
	BEGIN
		IF  Exists(select 1 from sHrm.tTempStaffAttendance    where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND EmployeeAttendanceDate=  CONVERT(date,@rUptoDate,102)AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
		BEGIN	
			SELECT * FROM sHrm.tTempStaffAttendance   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			return
		END
		ELSE
		BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
--TotalCount	
				SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,'' As OrgTitle,
	    ISNULL((SELECT 
        COUNT(EM.Id) 
     FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
          --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		  --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		  --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0),0) AS TotalCount,
  --  (SELECT 
  --      COUNT(EM.Id) 
  --   FROM sHrm.tEmployeeMaster EM
		--  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		--  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
  --        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		--  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		--  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 --WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 --and EM.statusid=7) AS Total,

    ISNULL((SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
		   and EM.statusid=7
      ),0) AS PresentCount,

     ISNULL((SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			 and EM.statusid=7
      ),0) As AbsentCount,
      
    ISNULL((SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId				
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		  INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  and EM.statusid=7
	),0) As LeaveCount,

	ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',

   ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
    
 ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126) 
		  and EM.statusid=7
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
   
		
   ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
            OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount',

	   ISNULL((SELECT COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		 WHERE OGM.Id=OGMM.Id 
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
							WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ),0) AS PendingCount,
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId  AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And ISNULL(ISNULL(OGM.IsObsolete,0),0) = 0
			SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		END
	END
END
  
ELSE IF @rTypeId=2  

BEGIN
IF(@rUserId = 0)
  BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
          COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
           INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		   INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
  OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.MobileNumber) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
 WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
            OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.MobileNumber) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And ISNULL(OGMT.IsObsolete,0) = 0
	ORDER BY OM.OrderIndex
  END   
ELSE IF(@rUserId <> 0)
  BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
           INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		   INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.MobileNumber) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
             OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.MobileNumber) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
	INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And OGMT.IsObsolete = 0 AND U.UserId = @rUserId
  END 
  END
  
  
else if @rTypeId=3   
  BEGIN
--TotalCount
    (SELECT 
      (DME.Id) As DepartmentId,
        DME.Code As DepartmentCode,OGMM.Id AS OrgGroupId,
        OGMM.Title As OrgGroupTitle,0 As OrgId,'' As OrgTitle,
        COUNT(DME.Id) As TotalCount,
--PresentCount
	(SELECT 
            COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE DME.Id=DMER.Id 
			and ETRP.IsPresent=1 
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	   ) AS PresentCount,
--AbsentCount			
	  (SELECT COUNT(ETRP.EmployeeId) 
            FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	   WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
			and EM.statusid=7
		) AS AbsentCount,
--LeaveCount			
   (SELECT    
        COUNT(EM.Id)
    FROM sHrm.tLeave SHT
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
	WHERE DME.Id=DMER.Id AND				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))		
			 and EM.statusid=7		
	) AS LeaveCount,
				
--AB10%Count				
     (SELECT 
         COUNT(EmployeeId) 
      FROM (
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100)) as Percentage		
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
		WHERE DME.Id=DMER.Id AND 
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	    GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	    HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100))<=90
	     ) AS Tmp) AS 'AB10Count',
	           
--AB3DaysCount	           
      (SELECT 
          COUNT(EmployeeId) FROM(
	         SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
	   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	    WHERE
            DME.Id=DMER.Id  AND IsPresent IN(0) 
            AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) as AB3DaysCount,
  --Leave3DayCount
   (SELECT COUNT(EmployeeId) FROM(
	   SELECT
			d.EmployeeId,d.FromDate,d.ToDate
	   FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND 
			 d.ToDate=CONVERT(char(10), @rUptoDate,126)   
			 and EM.statusid=7     
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)        
      )  AS Leave3DayCount,
        
--HundredPerAttnCount     
        
  (SELECT 
      COUNT(EmployeeId) FROM(
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,
            (OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage		
	      FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND 		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	  ) AS Tmp) As 'HundredPerAttnCount',

--PendingCount


	  (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where    EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId = OGMM.Id and EM.statusid=7) 
	AS PendingCount

	FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE OGMM.ID=@rOrgGroupId AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId AND 
	And ISNULL(OGMM.IsObsolete,0) = 0
	GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title
	) 
					
  END
  
  
else if @rTypeId=4 
  BEGIN     
     SELECT (DME.Id) As DepartmentId,
         DME.Code As DepartmentCode,
         OGMM.Id AS OrgGroupId,OGMM.Title As OrgGroupTitle,
         OM.Id As OrgId,OM.DisplayTitle As OrgTitle,
         COUNT(DME.Id) As TotalCount, 
         (SELECT 
            COUNT(ETRP.EmployeeId) 
          FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7
           ) As PresentCount,
			
	  (SELECT 
	      COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
       WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId  
	   and EM.statusid=7
	   AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	  ) AS AbsentCount,
			
			
      (SELECT 
       COUNT(EM.Id)
      FROM sHrm.tLeave SHT
            INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	       
	        INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
            LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	  WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 and EM.statusid=7
	  ) As LeaveCount,
				
				
     (SELECT 
         COUNT(EmployeeId) FROM  (
            SELECT    
                OGMEL.Id as OrgGroupId,
                OGMEL.Title AS OrgGroupTitle,
                OMEL.Id AS OrgId,(OMEL.Title) As OrgTitle,
                DMER.Id,DMER.Code AS DepartmentCode,
                (EM.Id)EmployeeID,
                (EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.MobileNumber) AS ContactNo,
				COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
                CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage

			 FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
			 WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
				and EM.statusid=7
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	         HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100))<=90
	       ) AS Tmp) As 'AB10Count',
	           
	         
   (SELECT 
       COUNT(EmployeeId) FROM(
	      SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			    d.EmployeeId,
			    AttendanceDate,
			    d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId  AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
			IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, CONVERT(DATE, @rUptoDate, 126)) AND @rUptoDate    
			and EM.statusid=7           
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) AS AB3DaysCount,
        
  (SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT 
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d		
 			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId	
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		  
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND 
			 d.ToDate=CONVERT(CHAR(10), @rUptoDate,126)     
			 and EM.statusid=7   
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)       
    )  AS Leave3DayCount,
        
        
    (SELECT 
       COUNT(EmployeeId) FROM  (
          SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(Count(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	) AS Tmp) As 'HundredPerAttnCount',
	 (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where  OM.Id=OMM.Id and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId=OGMM.Id and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) 
	AS PendingCount
  
   FROM sHrm.tEmployeeMaster EM
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
     --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    INNER JOIN sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=EM.ID
    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD1.OrgGroupDepartmentId
	LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID              
  WHERE DME.OrgGroupId=@rOrgGroupId And EJD1.OrgId=@rOrgId and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId 
  And ISNULL(OGMM.IsObsolete,0) = 0
  GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title,OM.Id,OM.DisplayTitle
	 
END  
   
   
else if @rTypeId=5   

BEGIN
   (SELECT(DM.code) As Dept,
          (EM.Id) As EmployeeId,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
          (EC.MobileNumber) AS ContactNo
    FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DM.Id=@rDepartmentId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGMM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
     )
END
   
ELSE IF @rTypeId=31
 BEGIN
     SELECT 
        (OGMM.id) AS OrgGroupId,(OGMM.Title) As OrgGroupTitle,
        (OM.id) OrgId,(OM.Title) OrgTitle,
        (DME.Code) As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
     INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	    
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID                    
	 WHERE DME.OrgGroupId=@rOrgGroupId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGMM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND DME.Id=@rDepartmentId--) As Total
	 Order By EM.Code
       
 END   
 
ELSE IF @rTypeId=41 
 BEGIN
	SELECT 
	   (OGMM.id) As OrgGroupId,
	   (OGMM.Title) As OrgGroupTitle,
	   (OM.id) OrgId,(OM.Title) OrgTitle,
	   DME.Code As DepartmentCode,(EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
	   ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
	   (EC.MobileNumber) AS ContactNo,
	   NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	   
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE 
		EJD.OrgId=@rOrgId --AND COGBM.Id=@rCommonOrgGroupBatchId 
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0	
		 And ISNULL(OGMM.IsObsolete,0) = 0
		AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))   
	Order By EM.Code
 END   
 
ELSE IF @rTypeId=32   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
        ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
    FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	 WHERE DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=1
	  And ISNULL(OGME.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
	Order By EM.Code
END

else if @rTypeId=42  

BEGIN
    SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
        (EM.Id)EmployeeID,
		(EM.Code)EmployeeCode,
        (EM.FirstName+' '+EM.LastName) AS EmployeeName,
        ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE EJD.OrgId=@rOrgId
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=1
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		And ISNULL(OGME.IsObsolete,0) = 0
		and ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
	Order By EM.Code
END


else if @rTypeId=33  
  BEGIN
     SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId 
	And ISNULL(OGME.IsObsolete,0) = 0
	and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	    AND ETRP.AttendanceDate = CONVERT(CHAR(10),  @rUptoDate,126)
	Order By EM.Code
  END   
  
  ELSE IF @rTypeId=43   
  BEGIN
     SELECT 
       (OGME.id) As OrgGroupId,
       (OGME.Title) As OrgGroupTitle,
 (OME.id) OrgId,(OME.Title) OrgTitle,
       DMER.Code As DepartmentCode,
       (EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,
       (EM.FirstName+' '+EM.LastName) AS EmployeeName,
       ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
       (EC.MobileNumber) AS ContactNo,
	   NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	  WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=0 
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		And ISNULL(OGME.IsObsolete,0) = 0
		and ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	Order By EM.Code
  END 
   
 ELSE IF @rTypeId=34
   
   BEGIN
      
       select (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
              (EM.FirstName+' '+EM.LastName) AS EmployeeName,
              ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
              (EC.MobileNumber) AS ContactNo,
			  ISNULL(SM.Title,'') AS LeaveStatus--Added for mantis : 35520 by Nilesh
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id = SHT.StatusId--Added for mantis : 35520 by Nilesh
	   WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   AND			
				((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		Order By EM.Code
   END
   
   
 ELSE IF @rTypeId=44    
   BEGIN
       SELECT (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
			  (EM.Id)EmployeeID,
              (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
              (EC.MobileNumber) AS ContactNo,
			   ISNULL(SM.Title,'') AS LeaveStatus--Added for mantis : 35520 by Nilesh
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id = SHT.StatusId--Added for mantis : 35520 by Nilesh
	   WHERE EJD.OrgId=@rOrgId	AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And				
				 ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		Order By EM.Code
   END
   
 ELSE IF @rTypeId=35 
   
   BEGIN

    select * from (
          select    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,--DMER.Id,DMER.Code As DeptCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			  (EC.MobileNumber) AS ContactNo,DMER.Code As DepartmentCode,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
			  convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
		  WHERE DMER.OrgGroupId=@rOrgGroupId  AND DMER.Id=@rDepartmentId 
		  And OGMEL.IsObsolete = 0
		  
		  AND COGBM.Id=@rCommonOrgGroupBatchId AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,EJD.DateOfJoining,EDM.title,
				EM.Id,(EM.Code),(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),DMER.Code
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	   ) AS Tmp
      
   END
   
   
   else if @rTypeId=45 
   
   BEGIN
   
    SELECT * FROM (
          SELECT    
               OGMEL.Id as OrgGroupId,
               OGMEL.Title As OrgGroupTitle,
               OMEL.Id As OrgId,
               (OMEL.Title) As OrgTitle,
               (EM.Id)EmployeeID,
			   (EM.Code)EmployeeCode,
               (EM.FirstName+' '+EM.LastName) AS EmployeeName,
               ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
				(EC.MobileNumber) AS ContactNo,DMER.Code As DepartmentCode,
				count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
                convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId			
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE EJD.OrgId=@rOrgId  AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			    and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,EJD.DateOfJoining,EDM.title
				,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),DMER.Code 
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	    ) AS Tmp
      
   END
   
   
 ELSE IF @rTypeId=36
  
  BEGIN
    (SELECT Temp.OrgGroupId,
            Temp.OrgGroupTitle,
            Temp.OrgId,Temp.OrgTitle,
            (EMR.Id) As EmployeeId,
			EMR.Code As EmployeeCode,
            (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,
            ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
            (ECR.PresentContactNo) AS ContactNo,
			DepartmentCode
     FROM(select ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		    d.EmployeeId,(EM.Code)EmployeeCode,
		    AttendanceDate,d.IsPresent,
		    OGMEL.Id As OrgGroupId,
		    OGMEL.Title As OrgGroupTitle,
		    OMEL.Id As OrgId,OMEL.Title As OrgTitle,
		    DMER.Code As DepartmentCode
          FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
        WHERE
            DMER.OrgGroupId=@rOrgGroupId And DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			AND 
            IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate       
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
            INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId AND  ISNULL(EMR.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID        
        where rowno=3
      ) 
       
  END
  
  
  
 ELSE IF @rTypeId=46 
 
  BEGIN
  (SELECT Temp.OrgGroupId,
          Temp.OrgGroupTitle,
          Temp.OrgId,Temp.OrgTitle,
          (EMR.Id) As EmployeeId,
		  EMR.Code As EmployeeCode,
          (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,	
          ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,	
          (ECR.PresentContactNo) AS ContactNo,DepartmentCode
      FROM(
	      select 
	         ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			 d.EmployeeId,
			 EM.Code As EmployeeCode,
			 AttendanceDate,d.IsPresent,
			 OGMEL.Id As OrgGroupId,
			 OGMEL.Title As OrgGroupTitle,
			 OMEL.Id As OrgId,
			 OMEL.Title As OrgTitle,
			 DMER.Code As DepartmentCode
		   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
        EJD.OrgId=@rOrgId 
        AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And OGMEL.IsObsolete = 0
		and EM.statusid=7
		AND
        IsPresent IN(0) AND COGBM.Id=@rCommonOrgGroupBatchId 
        AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
		INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId AND  ISNULL(EMR.IsOtherUser,0) = 0
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID
      WHERE rowno=3
    ) 
    
  END

  ELSE IF @rTypeId=37
  
  BEGIN
     (SELECT * FROM(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,
			OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.ID As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
            (EC.MobileNumber) AS ContactNo,
            DME.Code As DepartmentCode
		FROM sHrm.tLeave d
	 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
		    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
			d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and DME.OrgGroupId=@rOrgGroupId AND DME.Id=@rDepartmentId And OGMEL.IsObsolete = 0
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
      ) 
  END

  ELSE IF @rTypeId=47   
  
  BEGIN
  
     (SELECT * from(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.Id As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			(EC.MobileNumber) AS ContactNo,DME.Code As DepartmentCode
		  FROM sHrm.tLeave d
		 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
          AND EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
          AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) 
        ) AS Temp where (DATEDIFF(d, FromDate, ToDate)=2)        
      ) 
  
  
  END 
  
  
  else if @rTypeId=38
  
  BEGIN
      SELECT    
          OGMEL.Id as OrgGroupId,
          OGMEL.Title As OrgGroupTitle,
          OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
          DMER.Id,DMER.Code As DepartmentCode,
          (EM.Id)EmployeeID,
		  (EM.Code)EmployeeCode,
          (EM.FirstName+' '+EM.LastName) AS EmployeeName,
           ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
		  (EC.MobileNumber) AS ContactNo,
		   count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
		   convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
	  FROM sHrm.tEmployeeAttendanceRegister EAR		
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	  WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0 
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	  AND		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
	  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),EJD.DateOfJoining,EDM.title
	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  
  END
  
  
  ELSE IF @rTypeId=48 
  
  BEGIN
      
      SELECT    
           OGMEL.Id as OrgGroupId,
           OGMEL.Title As OrgGroupTitle,
           OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
           DMER.Id,DMER.Code As DepartmentCode,
           (EM.Id)EmployeeID,
		   (EM.Code)EmployeeCode,
           (EM.FirstName+' '+EM.LastName) AS EmployeeName,
            ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage						
		FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId  And OGMEL.IsObsolete = 0
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),EJD.DateOfJoining,EDM.title
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  END

  ELSE IF @rTypeId=39   

BEGIN
    SELECT 
       (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId And ISNULL(OGME.IsObsolete,0) = 0
	and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	AND EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))		
	Order By EM.Code
END

  ELSE IF @rTypeId=49   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,
		(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		

		WHERE EJD.OrgId=@rOrgId
		AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		And ISNULL(OGME.IsObsolete,0) = 0
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		AND   EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10),@rUptoDate,126))		
		Order By EM.Code
END


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pStaffAttendaceDashboardGetNew]
	 
	 @rTypeId smallint,
	 @rFromDate date=NULL,
	 @rToDate date=NULL,
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

if (@rTypeId=1)
BEGIN
 

SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
 --AB10Count
	 ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             (EM.Id)EmployeeID 
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			((EAR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			((EAR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = '')) AND
			 EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			 -- IsInContext
			 AND BMEL.IsInContext = 1
		GROUP BY OGMEL.Id,OGMEL.Title,EM.Id
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',
--AB3DaysCount
    ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND ((d.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			      ((d.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = '')) 
			  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			  -- IsInContext
			  AND BMEL.IsInContext = 1
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
--Leave3DayCount    
  ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
		   (((d.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND ((d.FromDate >= @rToDate) OR (ISNULL(@rToDate,'') = ''))OR
		   ((d.ToDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND ((d.ToDate >= @rToDate) OR (ISNULL(@rToDate,'') = '')))
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  -- IsInContext
		  AND BMEL.IsInContext = 1
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
--HundredPerAttnCount		
    ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId 
		        AND ((EAR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		        AND ((EAR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = '')) 
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				-- IsInContext
				AND BMEL.IsInContext = 1
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount'

    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE (OGM.Id=@rOrgGroupId OR @rOrgGroupId=0) AND COGBM.Id=@rCommonOrgGroupBatchId
	And ISNULL(OGM.IsObsolete,0) = 0
END
ELSE IF(@rTypeId=2)
	BEGIN

	SELECT (DME.Id) As DepartmentId,
         DME.Code As DepartmentCode,
        
     (SELECT 
         COUNT(EmployeeId) FROM  (
            SELECT    
                OGMEL.Id as OrgGroupId,
                OGMEL.Title AS OrgGroupTitle,
                OMEL.Id AS OrgId,(OMEL.Title) As OrgTitle,
                DMER.Id,DMER.Code AS DepartmentCode,
                (EM.Id)EmployeeID,
                (EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.PresentContactNo) AS ContactNo,
				COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
                CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage

			 FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
			 WHERE DME.Id=DMER.Id  AND DMER.OrgGroupId=@rOrgGroupId AND  
				((EAR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		        AND ((EAR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = '')) AND COGBM.Id=@rCommonOrgGroupBatchId 
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				-- IsInContext
				AND BMEL.IsInContext = 1
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)

	         HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100))<=90
	       ) AS Tmp) As 'AB10Count',
	           
	           
   (SELECT 
       COUNT(EmployeeId) FROM(
	      SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			    d.EmployeeId,
			    AttendanceDate,
			    d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND DMER.OrgGroupId=@rOrgGroupId AND  
			IsPresent IN(0) AND ((d.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		        AND ((d.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))     
			and EM.statusid=7   AND  ISNULL(EM.IsOtherUser,0) = 0  
			-- IsInContext
			AND BMEL.IsInContext = 1       
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) AS AB3DaysCount,
        
  (SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT 
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d		
 			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId	
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		  
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND DMER.OrgGroupId=@rOrgGroupId AND 
			 (((d.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND ((d.FromDate >= @rToDate) OR (ISNULL(@rToDate,'') = ''))OR
		   ((d.ToDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND ((d.ToDate >= @rToDate) OR (ISNULL(@rToDate,'') = '')))     
			 and EM.statusid=7   AND  ISNULL(EM.IsOtherUser,0) = 0
			 -- IsInContext
			 AND BMEL.IsInContext = 1
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)       
    )  AS Leave3DayCount,
        
        
    (SELECT 
       COUNT(EmployeeId) FROM  (
          SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(Count(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE DME.Id=DMER.Id AND DMER.OrgGroupId=@rOrgGroupId AND
			((EAR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		    AND ((EAR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			-- IsInContext
			AND BMEL.IsInContext = 1
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	) AS Tmp) As 'HundredPerAttnCount' 

   FROM sHrm.tEmployeeMaster EM
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
     --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    INNER JOIN sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=EM.ID
    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD1.OrgGroupDepartmentId
	LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID              
  WHERE DME.OrgGroupId=@rOrgGroupId and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId 
  And ISNULL(OGMM.IsObsolete,0) = 0
  GROUP BY DME.Id,DME.Code
  END
ELSE IF(@rTypeId=3)
	BEGIN
	SELECT 
		(EM.Id)EmployeeID,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL((SELECT 
		COUNT(ETRP.EmployeeId) 
		FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		INNER JOIN sHrm.tEmployeeMaster EM1 ON ETRP.EmployeeId=EM1.Id AND  ISNULL(EM1.IsOtherUser,0) = 0
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM1.ID		
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE OGM.Id = OGME.Id AND EM.Id = EM1.Id AND COGBM.Id=@rCommonOrgGroupBatchId
	
			AND ((ETRP.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			      ((ETRP.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  and EM1.statusid=7
			-- IsInContext
			AND BME.IsInContext = 1
		),0) 
		AS TotalCount----------Total Count
		,ISNULL((SELECT 
		COUNT(ETRP.EmployeeId) 
		FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		INNER JOIN sHrm.tEmployeeMaster EM1 ON ETRP.EmployeeId=EM1.Id AND  ISNULL(EM1.IsOtherUser,0) = 0
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM1.ID		
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE OGM.Id = OGME.Id AND EM.Id = EM1.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
			AND ((ETRP.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			      ((ETRP.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  and EM1.statusid=7
				 -- IsInContext
				 AND BME.IsInContext = 1
		),0) AS PresentCount,--------------Present Count
		ISNULL((SELECT 
		COUNT(ETRP.EmployeeId) 
		FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		INNER JOIN sHrm.tEmployeeMaster EM1 ON ETRP.EmployeeId=EM1.Id AND  ISNULL(EM1.IsOtherUser,0) = 0
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM1.ID
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM1.ID=EC.EmployeeID
		WHERE OGM.Id = OGME.Id AND EM1.Id = EM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
		AND ((ETRP.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			      ((ETRP.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  and EM1.statusid=7
				  -- IsInContext
				  AND BME.IsInContext = 1
		),0) As AbsentCount -----------------Absent Count

     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	    
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID                    
	 WHERE DME.OrgGroupId=@rOrgGroupId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND DME.Id=@rDepartmentId--) As Total
	 Group BY EM.Id,(EM.FirstName+' '+EM.LastName),OGM.Id
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pStaffBiometricDashboardGet]
	@rTypeId smallint,
	@rDate date,
	@rOrgGroupId int,
	@rCommonOrgGroupBatchId int,
	@rOrgId int=0,
	@rDepartmentId int=0,
	@rStatusId smallint


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;


WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

	Declare @lQuery nvarchar(Max)
	DECLARE @lDay as nvarchar(3)
	DECLARE @lMonth as nvarchar(3)
	DECLARE @lYear as nvarchar(4)

	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rDate) AS varchar(2)), 2)
	Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@rDate) AS varchar(2)), 2)
	Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@rDate) AS varchar(4)), 4)
	
	if(@rTypeId=1)
	BEGIN
		set @lQuery ='SELECT     
						OGM.Id AS OrgGroupId,
						OGM.Title As OrgGroupTitle,
						0 As DepartmentId,
						'''' As DepartmentCode,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00'' then 1 else 0 end) as INCount,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'' then 1 else 0 end) as OUTCount,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'' AND Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00''  then 1 else 0 end) as BothCount,
						Count(EM.Id) as TotalCount	 
				FROM 
					sHrm.tEmployeeMaster EM
				Left JOIN sBiometric.tMonthTrans MT  On EM.Id = MT.EmployeeId  AND ATTN_DT = cast(rtrim(' + convert(nvarchar(15),@lYear) + ' *10000+ ' + convert(nvarchar(15),@lMonth) + ' *100+ 01) as datetime) 
				AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE OGM.Id<>1 AND OGBM.CommonOrgGroupBatchId ='+convert(nvarchar(20),@rCommonOrgGroupBatchId)+'   AND ((OGM.Id = '+convert(nvarchar(20),@rOrgGroupId)+'  )OR('+convert(nvarchar(20),@rOrgGroupId)+' =0))
				And ISNULL(OGM.IsObsolete,0) = 0
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 Group by OGM.Id,OGM.Title'


		--print @lQuery
		EXECUTE(@lQuery)
	END
	Else if(@rTypeId=2)
	BEGIN
		set @lQuery ='SELECT     
						OGM.Id AS OrgGroupId,
						OGM.Title As OrgGroupTitle,
						(DME.Id) As DepartmentId,
						DME.Code As DepartmentCode,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00'' then 1 else 0 end) as INCount,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'' then 1 else 0 end) as OUTCount,
						Sum(case when Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'' AND Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00''  then 1 else 0 end) as BothCount,
						Count(EM.Id) as TotalCount	 
				FROM 
					sHrm.tEmployeeMaster EM
				Left JOIN sBiometric.tMonthTrans MT  On EM.Id = MT.EmployeeId  AND ATTN_DT = cast(rtrim(' + convert(nvarchar(15),@lYear) + ' *10000+ ' + convert(nvarchar(15),@lMonth) + ' *100+ 01) as datetime) 
				AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE OGM.Id<>1 AND OGBM.CommonOrgGroupBatchId ='+convert(nvarchar(20),@rCommonOrgGroupBatchId)+'   AND ((OGM.Id = '+convert(nvarchar(20),@rOrgGroupId)+'  )OR('+convert(nvarchar(20),@rOrgGroupId)+' =0))
				And ISNULL(OGM.IsObsolete,0) = 0
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 Group by OGM.Id,OGM.Title,(DME.Id),DME.Code'
		--print @lQuery
		EXECUTE(@lQuery)
	End
	

	Else if(@rTypeId=3)
	BEGIN
		set @lQuery ='SELECT   
						(EM.Id)EmployeeID,
						EM.Code EmployeeCode,
						(EM.FirstName+'' ''+EM.LastName) AS EmployeeName,  
						Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') as  IN_Time,
						Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'') as OUT_Time
						 
				FROM 
					sHrm.tEmployeeMaster EM
				Left JOIN sBiometric.tMonthTrans MT  On EM.Id = MT.EmployeeId  AND ATTN_DT = cast(rtrim(' + convert(nvarchar(15),@lYear) + ' *10000+ ' + convert(nvarchar(15),@lMonth) + ' *100+ 01) as datetime) 
				AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE OGM.Id<>1 AND OGBM.CommonOrgGroupBatchId='+convert(nvarchar(20),@rCommonOrgGroupBatchId)+'   AND ((OGM.Id = '+convert(nvarchar(20),@rOrgGroupId)+'  )OR('+convert(nvarchar(20),@rOrgGroupId)+' =0))
				And ISNULL(OGM.IsObsolete,0) = 0 
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 
				AND  (DME.Id='+convert(nvarchar(20),@rDepartmentId)+'  OR 0='+convert(nvarchar(20),@rDepartmentId)+' )
				AND (( '+convert(nvarchar(20),@rStatusId)+'=1 AND Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00'') OR
					(  '+convert(nvarchar(20),@rStatusId)+'=2 AND Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'') OR
					( '+convert(nvarchar(20),@rStatusId)+'=3 AND Isnull(D'+convert(nvarchar(15),@lDay)+'_OUT,''00:00'')<>''00:00'' AND Isnull(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'')<>''00:00'' ) OR
					( '+convert(nvarchar(20),@rStatusId)+'=0 ))'
		--print @lQuery
		EXECUTE(@lQuery)
	End
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pStaffCountDashboardGet]
	 
	 @rTypeId smallint,
	 @rOrgGroupId int = 0,
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rCommonOrgGroupBatchId int = 0	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--Changes for Mantis Id: 0039838	
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

	IF (@rTypeId=1)
	BEGIN
		 
	SELECT     
		OGM.Id AS OrgGroupId,
		OGM.Title AS OrgGroupTitle,
		EDM.Title AS Designation,
		COUNT(ISNULL(EM.Id, 0)) AS StaffCount
	FROM sHrm.tEmployeeMaster EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		INNER JOIN sHrm.tEmployeeDesignationMaster EDM  ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
	
	WHERE 
					 
		(OGM.Id=@rOrgGroupId OR @rOrgGroupId=0) 
		AND COGBM.Id = @rCommonOrgGroupBatchId
		AND EDM.IsObsolete = 0
		AND EM.StatusId = 7
		And ISNULL(OGM.IsObsolete,0) = 0
	
	GROUP BY OGM.Id, OGM.Title, EDM.Title
			 
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pTeacherSubjectGet]

	 --@rOrgId int,
	@rBatchId int,
	 @rEmployeeId bigint,
	 @rOrgGroupBatchId int
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
 
SELECT
 --SM.Title AS SubjectName,
 DISTINCT
 OM.Id, 
 DM.OrderIndex,
 --DM.Code AS ClassDivisionName,
 DM.ClassDivisionName AS ClassDivisionName,
 OM.DisplayTitle AS OrgName,
 --Sm.Id,
 DM.DivisionId As DivisionId  ,
 (SELECT  Count (AcademicId) FROM sStudent.vStudentAcademic A INNER JOIN sSetup.tBatchMaster B ON A.BatchId = B.Id
  WHERE DivisionId=DM.DivisionId AND B.OrgGroupBatchId = @rOrgGroupBatchId
  AND A.StatusId=1) AS StudentCount
 FROM
 sAcademic.tTeacherSubjectDivision TSD 
 					--INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
					INNER JOIN sSetup.vBatchClassDivision DM ON DM.DivisionId=TSD.DivisionId
                    
                    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
                   WHERE TSD.EmployeeId=@rEmployeeId
                   --AND OM.Id=@rOrgId
                   ORDER BY OM.Id,DM.OrderIndex

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pTransferEmployee]
		   
		   @rFromOrgId int,
		   @rToOrgId int,
		   @rToDepartmentId int,
		   @rToEmployeeTypeId int,
		   @rToEmployeeGradeId int,
		   @rToEmployeeDesignationId int,
		   @rEmployeeId bigint,
		   @rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF EXISTS(SELECT 1 FROM sHrm.tEmployeeMaster WHERE OrgId = @rToOrgId AND ReferenceEmployeeId = @rEmployeeId AND  ISNULL(IsOtherUser,0) = 0) 
	BEGIN
		SELECT -101
		RETURN
	END
	
	BEGIN TRY
		BEGIN TRANSACTION
		
		
		
		
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sHrm.tEmployeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		-- Employee Master 
		INSERT INTO sHrm.tEmployeeMaster
		(OrgID,Id,Code,FirstName,MiddleName,LastName,ShortName,StatusId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,ShiftId,PunchId,ReferenceEmployeeId,EUId)		-- MantisId : 	0029269 Add EUID
		SELECT @rToOrgId,@lNextNumber,@lNextNumber,FirstName,MiddleName,LastName,ShortName,StatusId,IsObsolete,@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate(),ShiftId,PunchId,Id,@lNextNumber FROM sHrm.tEmployeeMaster WHERE OrgId = @rFromOrgId AND Id = @rEmployeeId AND  ISNULL(IsOtherUser,0) = 0
		
		-- Employee Job Detail
		INSERT INTO sHrm.tEmployeeJobDetail
		(OrgID,EmployeeId,EmployeeDesignationId,OrganizationDepartmentId,DateOfJoining,UpdatedUserId,UpdatedDateTime,EmployeeTypeId,DateOfleaving,ReasonOfleaving,EmployeeGroupId,EmployeeGradeId,JobRemark,EmployeeManagerId,ProbationDays,ReferenceRemark,EmployeeBusinessHeadId,Subjects,OrgGroupDepartmentId)
		SELECT @rToOrgId,@lNextNumber,@rToEmployeeDesignationId,@rToDepartmentId,DateOfJoining,@rUserId,sCommon.fGetDate(),@rToEmployeeTypeId,DateOfleaving,ReasonOfleaving,EmployeeGroupId,EmployeeGradeId,JobRemark,NULL,ProbationDays,ReferenceRemark,NULL,Subjects,OrgGroupDepartmentId FROM sHrm.tEmployeeJobDetail WHERE OrgId = @rFromOrgId AND EmployeeId = @rEmployeeId
		
		-- Employee Personal Detail
		INSERT INTO sHrm.tEmployeePersonalDetail
		(OrgID,EmployeeId,UIDNumber,DateOfBirth,GenderId,ReligionId,MaritalStatusId,IdentificationMark1,BloodGroupId,Qualification,UpdatedUserId,UpdatedDateTime,FamilyCast,CastCategoryId,AdhaarNumber)
		SELECT @rToOrgId,@lNextNumber,UIDNumber,DateOfBirth,GenderId,ReligionId,MaritalStatusId,IdentificationMark1,BloodGroupId,Qualification,@rUserId,sCommon.fGetDate(),FamilyCast,CastCategoryId,AdhaarNumber FROM sHrm.tEmployeePersonalDetail WHERE OrgId = @rFromOrgId AND EmployeeId = @rEmployeeId
		
		-- Employee Communications
		INSERT INTO sHrm.tEmployeeCommunications
		(EmployeeId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,PresentState,PresentCity,PresentZipCode,PresentContactNo,
		PermanentStreetOne,PermanentStreetTwo,PermanentStreetThree,PermanentCountry,PermanentState,PermanentCity,PermanentZipCode,PermanentContactNo,
		EmergencyStreetOne,EmergencyStreetTwo,EmergencyStreetThree,EmergencyCountry,EmergencyState,EmergencyCity,EmergencyZipCode,EmergencyContactNo,
		PhoneNoCompany,ExtensionNo,CompanyEmail ,PersonalEmail,MobileNumber,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime)
		SELECT @lNextNumber,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,PresentState,PresentCity,PresentZipCode,PresentContactNo,
		PermanentStreetOne,PermanentStreetTwo,PermanentStreetThree,PermanentCountry,PermanentState,PermanentCity,PermanentZipCode,PermanentContactNo,
		EmergencyStreetOne,EmergencyStreetTwo,EmergencyStreetThree,EmergencyCountry,EmergencyState,EmergencyCity,EmergencyZipCode,EmergencyContactNo,
		PhoneNoCompany,ExtensionNo,CompanyEmail ,PersonalEmail,MobileNumber,@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate() 
		FROM sHrm.tEmployeeCommunications EC INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id
		WHERE EM.OrgId = @rFromOrgId AND EC.EmployeeId = @rEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
		
		-- Employee Statutory And Other
		INSERT INTO sHrm.tEmployeeStatutoryAndOther
		([EmployeeId],[EPFNumber],[IsVPFDeduction],[VPFContributionId],[VPFContributionEffectiveFrom],[VPFPercentage]
        ,[VPFAmount],[ESINumber],[BankName],[Branch],[AccountNumber],[IFSCNumber],[PanNumber],[IncomeTaxStatusId]
        ,[UpdatedUserId],[UpdatedDateTime],[IncrementDate],[BasicPay],[PayrollId],[PayrollGroupId]
        ,[Payscale],[EPFJoinDate],[UAN],[RetirementDate])
		SELECT 
		@lNextNumber,[EPFNumber],[IsVPFDeduction],[VPFContributionId],[VPFContributionEffectiveFrom],[VPFPercentage]
        ,[VPFAmount],[ESINumber],[BankName],[Branch],[AccountNumber],[IFSCNumber],[PanNumber],[IncomeTaxStatusId]
        ,@lNextNumber,sCommon.fGetDate(),[IncrementDate],[BasicPay],NULL,NULL
        ,[Payscale],[EPFJoinDate],[UAN],[RetirementDate]
		FROM sHrm.tEmployeeStatutoryAndOther ESO INNER JOIN sHrm.tEmployeeMaster EM ON ESO.EmployeeId = EM.Id
		WHERE EM.OrgId = @rFromOrgId AND ESO.EmployeeId = @rEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
		
		SELECT 1
		COMMIT TRANSACTION			
	END TRY
		
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pValidateImportEmployee]
    
    @rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(20),     
        @lDOB nvarchar(15),        
        @lDOJ nvarchar(15),      
        @1ReturnCode int = 1,
        @1ExistEmployeeCode nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1ValidDOJ nvarchar(max) = '',
        @1DuplicateEmployeeCode nvarchar(max) = ''
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
DECLARE @lConfigValue nvarchar(50)
SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 512 AND SourceTypeId = 2010 AND SourceId = @rOrgId

CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(20),
        FirstName nvarchar(100),
        LastName nvarchar(100),
		EmployeeType nvarchar(100),
		EmployeeGroup nvarchar(100),
		EmployeeGrade nvarchar(100),
		Department nvarchar(100),
		Designation nvarchar(100),
        Gender nvarchar(10),
        DOB nvarchar(15),
		DOJ nvarchar(15),
		Religion nvarchar(100)
  )
  INSERT INTO #tTable1
	(
	    Code,
	    FirstName,
	    LastName,
	    EmployeeType,
	    EmployeeGroup,
	    EmployeeGrade,
	    Department,
	    Designation,
	    Gender,
	    DOB,
	    DOJ,
	    Religion
    ) 
   SELECT
        Code,
	    FirstName,
	    LastName,
	    EmployeeType,
	    EmployeeGroup,
	    EmployeeGrade,
	    Department,
	    Designation,
	    Gender,
	    DOB,
	    DOJ,
	    Religion   
   
   FROM OPENXML (@intDoc, '/Table/ImportEmployee', 1)
   With
   (
        Code nvarchar(50) '@Code',
        FirstName nvarchar(100) '@FirstName',
        LastName nvarchar(100) '@LastName',
        EmployeeType nvarchar(100) '@EmployeeType',
        EmployeeGroup nvarchar(100) '@EmployeeGroup',
        EmployeeGrade nvarchar(100) '@EmployeeGrade',
        Department nvarchar(100) '@Department',
        Designation nvarchar(100) '@Designation',
		Gender nvarchar(10) '@Gender',
		DOB nvarchar(15) '@DOB',
		DOJ nvarchar(15) '@DOJ',
		Religion nvarchar(100) '@Religion'
   )   
EXEC sp_xml_removedocument @intDoc

SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
BEGIN
  
    SELECT         
         
         @lCode = Code, 
         @lDOB=DOB,
         @lDOJ=DOJ
         
    FROM #tTable1 WHERE Id = @lCount 
     
    IF Exists ((select 1 from sHrm.tEmployeeMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND  ISNULL(IsOtherUser,0) = 0))         
    BEGIN
		SET @1ExistEmployeeCode = @1ExistEmployeeCode + @lCode + ','
    END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lDOB+','
	END
	IF(ISDATE(@lDOJ) = 0 AND @lDOJ!='')
	BEGIN
		SET @1ValidDOJ=@1ValidDOJ + @lDOJ+','
	END
		SET @lCount = @lCount - 1	
    END	

	IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Code Should not be empty' AS EmployeeCode
		
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Surname Should not be empty' AS EmployeeCode
	   
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'First Name Should not be empty' AS EmployeeCode
	     
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Gender Should not be empty' AS EmployeeCode
	      
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeType IS NULL OR EmployeeType COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Employee Type Should not be empty' AS EmployeeCode
	     
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGroup IS NULL OR EmployeeGroup COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Employee Group Should not be empty' AS EmployeeCode
	      
	END
	--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGrade IS NULL OR EmployeeGrade COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	--BEGIN
	--	SELECT 'Employee Grade Should not be empty' AS EmployeeCode
	--END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Department COLLATE DATABASE_DEFAULT  IS NULL OR Department COLLATE DATABASE_DEFAULT = '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SELECT 'Department Should not be empty' AS EmployeeCode
	   
	END
	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeType COLLATE DATABASE_DEFAULT  NOT IN(SELECT Title FROM sHrm.tEmployeeTypeMaster WHERE OrgId=@rOrgId))
	BEGIN
		SELECT 'Enter proper value for Employee Type' AS EmployeeCode
	   
	END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGroup  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sHrm.tEmployeeGroupMaster))
	BEGIN
		SELECT 'Enter proper value for Employee Group' AS EmployeeCode
	     
	END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE EmployeeGrade  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sHrm.tEmployeeGradeMaster WHERE OrgId=@rOrgId))
	BEGIN
		SELECT 'Enter proper value for Employee Grade' AS EmployeeCode
	      
	END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Department  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tDepartmentMaster WHERE OrgId=@rOrgId))
	BEGIN
		SELECT 'Enter proper value for Department' AS EmployeeCode
	     
	END	
	--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Designation  COLLATE DATABASE_DEFAULT !=''  COLLATE DATABASE_DEFAULT AND Designation  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sHrm.tEmployeeDesignationMaster WHERE OrgId=@rOrgId))
	--BEGIN
	--	SELECT 'Enter proper value for Designation' AS EmployeeCode
	--END	
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion!='' AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
	BEGIN
		SELECT 'Enter proper value for Religion' AS EmployeeCode
	      
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender!='' AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
	BEGIN
		SELECT 'Enter proper value for gender' AS EmployeeCode
	     
	END
	
	--ELSE IF((@1ExistEmployeeCode IS NULL OR @1ExistEmployeeCode = '') 
	--AND (@1ValidDOB IS NULL OR @1ValidDOB = '') AND (@1ValidDOJ IS NULL OR @1ValidDOJ = ''))
	--BEGIN
	--	SELECT '' AS EmployeeCode
	--      
	--END
	ELSE IF (@1ExistEmployeeCode IS NOT NULL AND @1ExistEmployeeCode != '')
	BEGIN
		SET @1ExistEmployeeCode = 'Exist Code ' + @1ExistEmployeeCode
		Select @1ExistEmployeeCode AS EmployeeCode
	      
	END
	ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
	BEGIN
		SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
		Select @1ValidDOB AS EmployeeCode
	      
	END

	ELSE IF ((@1ValidDOJ IS NOT NULL AND @1ValidDOJ != ''))
	BEGIN
		SET @1ValidDOJ = 'Wrong Date Of Joining ' + @1ValidDOJ
		Select @1ValidDOJ AS EmployeeCode
	      
	END
	ELSE IF ((@lDOJ IS NULL OR @lDOJ = '') AND @lConfigValue = 'True')
	BEGIN
		SET @1ValidDOJ = 'Enter Date Of Joining ' + @1ValidDOJ
		Select @1ValidDOJ AS EmployeeCode
	   
	END
	ELSE 
	BEGIN
		SELECT @1DuplicateEmployeeCode=COALESCE(@1DuplicateEmployeeCode ,'') 
		+ Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		IF(@1DuplicateEmployeeCode IS NOT NULL AND @1DuplicateEmployeeCode != '')
		BEGIN
			SET @1DuplicateEmployeeCode = 'Duplicate Code ' + @1DuplicateEmployeeCode
			SELECT @1DuplicateEmployeeCode AS EmployeeCode
		END
	ELSE
	BEGIN
		SELECT '' AS EmployeeCode
	END  
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pWorkingDaysAdd]
	      
	       @rForMonth tinyint,
           @rForYear smallint,  
           @rTotalDays tinyint,
           @rWorkingDay tinyint,
           @rVacationDays tinyint,
           @rSundays tinyint,
           @rHoliDays tinyint,
           @rBatchId int, 
           @rEmployeeGradeId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
		
   DELETE FROM sHrm.tWorkingDays Where ForMonth = @rForMonth AND ForYear = @rForYear AND BatchId = @rBatchId AND EmployeeGradeId = @rEmployeeGradeId
 
 --IF NOT EXISTS (SELECT 1 FROM sHrm.tWorkingDays Where ForMonth = @rForMonth AND ForYear = @rForYear AND BatchId = @rBatchId AND EmployeeGradeId = @rEmployeeGradeId)
 --  BEGIN
	INSERT INTO sHrm.tWorkingDays
		(  [ForMonth]
           ,[ForYear]
           ,[TotalDays]
           ,[WorkingDays]
           ,[VacationDays]
           ,[WeekOffs]
           ,[HoliDays]
           ,[BatchId]
           ,[EmployeeGradeId])
     VALUES
           (
           @rForMonth,
           @rForYear,  
           @rTotalDays,
           @rWorkingDay,
           @rVacationDays,
           @rSundays,
           @rHoliDays,
           @rBatchId, 
           @rEmployeeGradeId
           )
	--END 
	SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH						
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pWorkingDaysListGet]
	 
	@rEmployeeGradeId  bigint,	 
	@rBatchId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
    --SET @rCode = sCommon.fSearchStringGet(@rCode)
    --SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		 
	--SELECT [ForMonth]
	--		,[ForYear]
	--	    ,[TotalDays]
	--	    ,[WorkingDays]
	--	    ,[VacationDays]
	--	    ,[Sundays]
	--	    ,[HoliDays]
	--	    ,[BatchId]
	--	    ,[EmployeeGradeId]
    -- FROM [sHrm].[tWorkingDays]
		   
    	Select 
				MY.MonthTitle AS ForMonthInWord,
				MY.MonthNumber AS ForMonth, 
				MY.YearNumber AS ForYear,
				ISNULL((CASE [WorkingDays] WHEN 0 THEN [TotalDays]-[WorkingDays]
				 ELSE [WorkingDays] END),0) AS WorkingDay,
				ISNULL([TotalDays],MY.NoOfDays) AS TotalDays,
			    --ISNULL([WorkingDays],0) AS WorkingDay,
			    ISNULL([VacationDays],0) AS VacationDays,
			    ISNULL([WeekOffs],0) AS Sundays,
			    --ISNULL([HoliDays],0) AS HoliDays,
			    ISNULL(EmployeeGradeId,0) AS EmployeeGradeId,
			    ISNULL([Holidays],0) AS HoliDays
		From 
				sSetup.fMonthYearForBatchGET(@rBatchId) AS MY
			LEFT JOIN [sHrm].[tWorkingDays] WD ON WD.BatchId=MY.BatchId 
				AND (WD.EmployeeGradeId = @rEmployeeGradeId)
				AND WD.ForMonth = MY.MonthNumber AND WD.ForYear = MY.YearNumber
		WHERE
			(MY.BatchId=@rBatchId)  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sHrm].[pXMLEmployeeMasterAdd]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	select 1
	-----------------------
	INSERT INTO sSetup.tDepartmentMaster
	(
		OrgId,
		Id,
		Code,
		Title,
		DisplayTitle,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime
	)
	SELECT TOP(1)
		A.OrgId,
		sCommon.fGetIntIdForOrg(1,A.OrgId),
		'Default Department',
		'Default Department',
		'Default Department',
		0,
		9999000000003,
		sCommon.fGetDate(),
		9999000000003,
		sCommon.fGetDate()	
	
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		OrgId smallint '@OrgId'
	)A Left Join sSetup.tDepartmentMaster DM ON DM.Id = sCommon.fGetIntIdForOrg(1,A.OrgId)
	Where DM.Id is null 
	
	SELECT @lNextNumber = MAX(ID) FROM sSetup.tDepartmentMaster Where OrgId=@rOrgId
    EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sSetup.tDepartmentMaster', @rCurrentNumber = @lNextNumber 

	-- Update EmployeeMaster
	UPDATE sHrm.tEmployeeMaster
	SET
		FirstName=A.FirstName,
		MiddleName=A.MiddleName,
		LastName=A.LastName,
		StatusId=A.StatusId,
		UpdatedUserId=9999000000003,
		UpdatedDateTime=sCommon.fGetDate()
	FROM
	(
		SELECT
			Id,
			OrgId,
			FirstName,
			MiddleName,
			LastName,
			CASE WHEN StatusId = 1 THEN 7 ELSE 9 END AS StatusId
		
		FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
		WITH
		(
			Id int '@Id' ,
			Code nvarchar(10) '@Code',
			FirstName nvarchar(100) '@FirstName',
			LastName nvarchar(100) '@LastName',
			MiddleName nvarchar(100) '@MiddleName',	
			StatusId tinyint '@StatusId',
			OrgId smallint '@OrgId'
		))A INNER JOIN sHRM.tEmployeeMaster E ON E.ID= sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId) AND  ISNULL(E.IsOtherUser,0) = 0
	
	-- Insert Employee Master
	INSERT INTO sHrm.tEmployeeMaster
	(
		OrgID,
		Id,
		Code,
		FirstName,
		MiddleName,
		LastName,
		StatusId,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		EUId				-- MantisId : 	0029269
	)
	SELECT
		A.OrgId,
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId),
		A.Code,
		A.FirstName,
		A.MiddleName,
		A.LastName,
		CASE WHEN A.StatusId = 1 THEN 7 ELSE 9 END,
		0,
		9999000000003,
		sCommon.fGetDate(),
		9999000000003,
		sCommon.fGetDate(),
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId)
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,
		Code nvarchar(10) '@Code',
		FirstName nvarchar(100) '@FirstName',
		LastName nvarchar(100) '@LastName',
		MiddleName nvarchar(100) '@MiddleName',	
		StatusId tinyint '@StatusId',
		OrgId smallint '@OrgId'
	)A LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId) AND  ISNULL(EM.IsOtherUser,0) = 0
	WHERE EM.Id IS NULL
	
	SELECT @lNextNumber = MAX(ID) FROM sHrm.tEmployeeMaster Where OrgId=@rOrgId AND  ISNULL(IsOtherUser,0) = 0
    EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeMaster', @rCurrentNumber = @lNextNumber 

	-- Update PersonalDetail
	UPDATE sHrm.tEmployeePersonalDetail
	SET
		DateOfBirth=A.DateOfBirth,
		GenderId=A.GenderId,
		MaritalStatusId=A.MaritalStatusId,
		BloodGroupId=A.BloodGroupId,
		Qualification=A.Qualification,
		UpdatedUserId=9999000000003,
		UpdatedDateTime=sCommon.fGetDate()
	FROM
	(	
	SELECT
		OrgId,
		Id,
		CASE WHEN DateOfBirth = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(DateOfBirth, 8)) END AS DateOfBirth,
		CASE WHEN GenderId = 101 OR GenderId = 1 THEN 1 ELSE 2 END AS GenderId,
		CASE WHEN MaritalStatusId  =1 THEN 2 ELSE 1 END AS MaritalStatusId,
		CASE WHEN BloodGroupId =1 THEN 1
			 WHEN BloodGroupId =2 THEN 8
			 WHEN BloodGroupId =3 THEN 5
			 WHEN BloodGroupId =4 THEN 3
			 WHEN BloodGroupId =5 THEN 4
			 WHEN BloodGroupId =6 THEN 2
			 WHEN BloodGroupId =7 THEN 7
			 WHEN BloodGroupId =8 THEN 6 ELSE 9 END AS BloodGroupId,
		Qualification
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id bigint '@Id' ,	
		DateOfBirth int '@dateofbirth',
		GenderId int '@genderId',
		MaritalStatusId int '@MaritalStatusId',
		BloodGroupId int '@BloodGroupId',
		Qualification nvarchar(50) '@Qualification',	
		OrgId smallint '@OrgId'
	))A  INNER JOIN sHRM.tEmployeePersonalDetail EP ON EP.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId) 
	
	
	
	-- Insert PersonalDetail
	INSERT INTO sHrm.tEmployeePersonalDetail
	(
		OrgId,		
		EmployeeId,
		DateOfBirth,
		GenderId,
		MaritalStatusId,
		BloodGroupId,
		Qualification,
		UpdatedUserId,
		UpdatedDateTime
	)
	
	SELECT
		A.OrgId,
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId),
		CASE WHEN A.DateOfBirth = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(A.DateOfBirth, 8)) END,
		CASE WHEN A.GenderId = 101 OR A.GenderId = 1 THEN 1 ELSE 2 END,
		CASE WHEN A.MaritalStatusId  =1 THEN 2 ELSE 1 END,
		CASE WHEN A.BloodGroupId =1 THEN 1
			 WHEN A.BloodGroupId =2 THEN 8
			 WHEN A.BloodGroupId =3 THEN 5
			 WHEN A.BloodGroupId =4 THEN 3
			 WHEN A.BloodGroupId =5 THEN 4
			 WHEN A.BloodGroupId =6 THEN 2
			 WHEN A.BloodGroupId =7 THEN 7
			 WHEN A.BloodGroupId =8 THEN 6 ELSE 9 END,
		A.Qualification,
		9999000000003,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id bigint '@Id' ,	
		DateOfBirth int '@dateofbirth',
		GenderId int '@genderId',
		MaritalStatusId int '@MaritalStatusId',
		BloodGroupId int '@BloodGroupId',
		Qualification nvarchar(50) '@Qualification',	
		OrgId smallint '@OrgId'
	)A LEFT JOIN sHrm.tEmployeePersonalDetail EP ON EP.EMPLOYEEID = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId) 
	WHERE EP.EmployeeId is null
	
	-- Update Job Detail
	UPDATE sHrm.tEmployeeJobDetail
	SET
		DateOfJoining = A.DateOfJoining,		
		EmployeeDesignationId = A.EmployeeDesignationId,
		EmployeeGroupId = A.EmployeeGroupId,
		UpdatedUserId=9999000000003,
		UpdatedDateTime=sCommon.fGetDate()
	FROM
	(
	SELECT
		OrgId,
		Id,
		EmployeeGroupId,
		CASE WHEN DateOfJoining = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(DateOfJoining, 8)) END AS DateOfJoining,
		sCommon.fGetIntIdForOrg(EmployeeDesignationId,OrgId) AS EmployeeDesignationId
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,	
		DateOfJoining int '@DateOfJoining',
		OrgId smallint '@OrgId',
		EmployeeGroupId smallint '@EmployeeGroupId',
		EmployeeDesignationId int '@EmployeeDesignationId'
	))A  INNER JOIN sHRM.tEmployeeJobDetail EJ ON EJ.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId)  
	
	
	-- Insert Job Detail
	INSERT INTO sHrm.tEmployeeJobDetail
	(
		OrgId,
		--Id,
		EmployeeId,
		OrganizationDepartmentId,
		DateOfJoining,		
		EmployeeTypeId,
		EmployeeGroupId,
		EmployeeDesignationId,
		EmployeeGradeId,	
		UpdatedUserId,
		UpdatedDateTime
	)
	SELECT
		A.OrgId,
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId),
		sCommon.fGetIntIdForOrg(1,A.OrgId),
		CASE WHEN A.DateOfJoining = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(A.DateOfJoining, 8)) END,
		sCommon.fGetIntIdForOrg(1,A.OrgId),
		A.EmployeeGroupId,
		sCommon.fGetIntIdForOrg(A.EmployeeDesignationId,A.OrgId),
		0,	
		9999000000003,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,	
		DateOfJoining int '@DateOfJoining',
		OrgId smallint '@OrgId',
		EmployeeGroupId smallint '@EmployeeGroupId',
		EmployeeDesignationId int '@EmployeeDesignationId'
	)A Left Join sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId)
	where EJ.EmployeeId is null
	


	-- Update Communication Detail
	UPDATE sHrm.tEmployeeCommunications
	SET
		MobileNumber = A.MobileNumber,
		PersonalEmail = A.PersonalEmail,
		PresentStreetOne = A.PresentStreetOne,
		PresentStreetTwo = A.PresentStreetTwo,
		PresentCity = A.PresentCity,
		PresentZipCode = A.PresentZipCode,
		PresentContactNo = A.PresentContactNo,
		PermanentStreetOne =A.PermanentStreetOne,
		PermanentStreetTwo=A.PermanentStreetTwo,
		PermanentCity=A.PermanentCity,
		PermanentZipCode=A.PermanentZipCode
	FROM
	(
	SELECT
		Id,
		MobileNumber,
		PersonalEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentCity,
		PresentZipCode,
		PresentContactNo,
		PermanentStreetOne,
		PermanentStreetTwo,
		PermanentCity,
		PermanentZipCode
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,
		MobileNumber nvarchar(20) '@MobileNumber',
		PersonalEmail nvarchar(100) '@PersonalEmail',
		OrgId smallint '@OrgId',
		PresentStreetOne NVARCHAR(50) '@PresentStreetOne',
		PresentStreetTwo NVARCHAR(50) '@PresentStreetTwo',
		PresentCity NVARCHAR(50) '@PresentCity',
		PresentZipCode NVARCHAR(50) '@PresentZipCode',
		PresentContactNo NVARCHAR(20) '@PresentContactNo',
		PermanentStreetOne NVARCHAR(50) '@PermanentStreetOne',
		PermanentStreetTwo NVARCHAR(50) '@PermanentStreetTwo',
		PermanentCity NVARCHAR(50) '@PermanentCity',
		PermanentZipCode NVARCHAR(50) '@PermanentZipCode'
	))A INNER JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId =sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId) 
	
	-- Insert Communication Detail
	INSERT INTO sHrm.tEmployeeCommunications
	(
		EmployeeId,
		MobileNumber,
		PersonalEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentCity,
		PresentZipCode,
		PresentContactNo,
		PermanentStreetOne,
		PermanentStreetTwo,
		PermanentCity,
		PermanentZipCode,
		CreatedUserId,
		CreatedDateTime
	)
	SELECT
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId),
		A.MobileNumber,
		A.PersonalEmail,
		A.PresentStreetOne,
		A.PresentStreetTwo,
		A.PresentCity,
		A.PresentZipCode,
		A.PresentContactNo,
		A.PermanentStreetOne,
		A.PermanentStreetTwo,
		A.PermanentCity,
		A.PermanentZipCode,
		9999000000003,
		sCommon.fGetDate()
				
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,
		MobileNumber nvarchar(20) '@MobileNumber',
		PersonalEmail nvarchar(100) '@PersonalEmail',
		OrgId smallint '@OrgId',
		PresentStreetOne NVARCHAR(50) '@PresentStreetOne',
		PresentStreetTwo NVARCHAR(50) '@PresentStreetTwo',
		PresentCity NVARCHAR(50) '@PresentCity',
		PresentZipCode NVARCHAR(50) '@PresentZipCode',
		PresentContactNo NVARCHAR(20) '@PresentContactNo',
		PermanentStreetOne NVARCHAR(50) '@PermanentStreetOne',
		PermanentStreetTwo NVARCHAR(50) '@PermanentStreetTwo',
		PermanentCity NVARCHAR(50) '@PermanentCity',
		PermanentZipCode NVARCHAR(50) '@PermanentZipCode'

	)A LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId) 
	WHERE EC.EmployeeId IS null



	IF NOT EXISTS (SELECT ID FROM sHrm.tEmployeeGradeMaster WHERE ID = 1)
	BEGIN
		INSERT INTO sHrm.tEmployeeGradeMaster (Id,Code,Title,
		IsObsolete,CreatedUserId,CreatedDateTime) VALUES
		(1,'Default Grade','Default Grade',0,9999000000003,sCommon.fGetDate())
	END

	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sHrm].[pXMLEmployeeMasterUpdate]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	-----------------------
	

	UPDATE sHrm.tEmployeeMaster
	SET 
		FirstName=A.FirstName,
		MiddleName=A.MiddleName,
		LastName=A.LastName,
		StatusId=A.StatusId,
		UpdatedUserId=9999000000003,
		UpdatedDateTime=sCommon.fGetDate()
	FROM (
	SELECT
		OrgId,ID,Code,FirstName,MiddleName,LastName,
		CASE WHEN StatusId = 1 THEN 7 ELSE 9 END AS StatusId		
		FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,
		Code nvarchar(10) '@Code',
		FirstName nvarchar(100) '@FirstName',
		LastName nvarchar(100) '@LastName',
		MiddleName nvarchar(100) '@MiddleName',	
		StatusId tinyint '@StatusId',
		OrgId smallint '@OrgId'
	))A 
	Where sHrm.tEmployeeMaster.Id = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId)  AND  ISNULL(IsOtherUser,0) = 0
	
	
	UPDATE sHrm.tEmployeePersonalDetail
	SET	DateOfBirth=A.DateOfBirth,
		GenderId=A.GenderId,
		MaritalStatusId=A.MaritalStatusId,
		BloodGroupId=A.BloodGroupId,
		Qualification=A.Qualification,
		UpdatedUserId=9999000000003,
		UpdatedDateTime=sCommon.fGetDate()
	FROM
	(	
		SELECT
		OrgId,Id,		
		CASE WHEN DateOfBirth = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(DateOfBirth, 8)) END AS DateOfBirth,
		CASE WHEN GenderId = 101 OR GenderId = 1 THEN 1 ELSE 2 END AS GenderId,
		CASE WHEN MaritalStatusId  =1 THEN 2 ELSE 1 END AS MaritalStatusId,
		CASE WHEN BloodGroupId =1 THEN 1
			 WHEN BloodGroupId =2 THEN 8
			 WHEN BloodGroupId =3 THEN 5
			 WHEN BloodGroupId =4 THEN 3
			 WHEN BloodGroupId =5 THEN 4
			 WHEN BloodGroupId =6 THEN 2
			 WHEN BloodGroupId =7 THEN 7
			 WHEN BloodGroupId =8 THEN 6 ELSE 9 END AS BloodGroupId,
		Qualification
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id bigint '@Id' ,	
		DateOfBirth int '@dateofbirth',
		GenderId int '@genderId',
		MaritalStatusId int '@MaritalStatusId',
		BloodGroupId int '@BloodGroupId',
		Qualification nvarchar(50) '@Qualification',	
		OrgId smallint '@OrgId'
	)) A
	WHERE sHrm.tEmployeePersonalDetail.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId)


	UPDATE sHrm.tEmployeeJobDetail
	SET
		DateOfJoining = A.DateOfJoining,		
		UpdatedUserId = 9999000000003,
		UpdatedDateTime =sCommon.fGetDate()
	FROM (
	SELECT
		OrgId,
		Id,
		CASE WHEN DateOfJoining = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(DateOfJoining, 8)) END AS DateOfJoining
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,	
		DateOfJoining int '@DateOfJoining',
		OrgId smallint '@OrgId',
		EmployeeGroupId smallint '@EmployeeGroupId',
		EmployeeDesignationId int '@EmployeeDesignationId'
	))A
	WHERE sHrm.tEmployeeJobDetail.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId)

	UPDATE sHrm.tEmployeeCommunications
	SET
		
		MobileNumber=A.MobileNumber,
		PersonalEmail=A.PersonalEmail,
		CreatedUserId=9999000000003,
		CreatedDateTime=sCommon.fGetDate()
	FROM (
	SELECT
		Id,OrgId,
		MobileNumber,
		PersonalEmail
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,
		MobileNumber nvarchar(20) '@MobileNumber',
		PersonalEmail nvarchar(100) '@PersonalEmail',
		OrgId smallint '@OrgId'
	))A
	WHERE sHrm.tEmployeeCommunications.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId)
	


	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sInfrastructure].[pResourceMasterAdd] 
	 
        @rId int,
		@rTitle nvarchar(100),
		@rCode nvarchar(20),
		@rIsObsolete bit,
		@rCreatedUserId bigint ,
		@rOrgId int,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sInfrastructure.tResourceMaster where Code=@rCode AND OrgGroupId =@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sInfrastructure.tResourceMaster where Title=@rTitle AND OrgGroupId =@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sInfrastructure.tResourceMaster where Code=@rCode  AND Id<>@rId AND OrgGroupId =@rOrgGroupId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sInfrastructure.tResourceMaster where Title=@rTitle AND Id<>@rId AND OrgGroupId =@rOrgGroupId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sInfrastructure.tResourceMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sInfrastructure.tResourceMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime ,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate() ,
			@rOrgGroupId
		)
		    SELECT 1 AS Result
	
 COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sInfrastructure.tResourceMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete, 
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      
	      WHERE Id = @rId AND OrgGroupId=@rOrgGroupId
	      SELECT 11 AS Result
	
		 COMMIT TRANSACTION
	 END  	

	 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sInfrastructure].[pResourceMasterGet] 
	 
        @rId int,
		@rTitle nvarchar(100),
		@rCode nvarchar(100),
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRANSACTION
	BEGIN TRY
		Select Id,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime
		From sInfrastructure.tResourceMaster 
		Where
		((Id=@rId) OR (@rId=0))
		AND ((Code like '%'+@rCode+'%') OR (ISNULL(@rCode,'')=''))
		AND ((Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
		AND  OrgGroupId=@rOrgGroupId
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sInfrastructure].[pResourceRequestAdd] 
	 
        @rId bigint,
		@rRequestDate datetime,
		@rRequestFromTime datetime,
		@rRequestToTime datetime,
		@rResourceId int,
		@rRequestedBy nvarchar(100),
		@rRequestedRemark nvarchar(250),
		@rStatusId smallint=704,
		@rCreatedUserId bigint ,
		@rOrgId int,
		@rOrgGRoupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sInfrastructure.tResourceRequest', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sInfrastructure.tResourceRequest
		(
			Id,
			RequestDate,
			RequestFromTime,
			RequestToTime,
			ResourceId,
			RequestedBy,
			RequestedRemark,
			StatusId,
			CreatedUserId,
			CreatedDateTime ,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rRequestDate,
			@rRequestFromTime,
			@rRequestToTime,
			@rResourceId,
			@rRequestedBy,
			@rRequestedRemark,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate() ,
			@rOrgGRoupId
		)
		    SELECT 1 AS Result
	
 
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sInfrastructure.tResourceRequest
	    SET
			RequestDate=@rRequestDate,
			RequestFromTime=@rRequestFromTime,
			RequestToTime=@rRequestToTime, 
			ResourceId=@rResourceId,
			RequestedBy=@rRequestedBy,
			RequestedRemark=@rRequestedRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      
	      WHERE Id = @rId AND OrgGroupId=@rOrgGRoupId
	      SELECT 11 AS Result
	
		 
	 END  	

	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sInfrastructure].[pResourceRequestGet] 
	 
        @rId bigint,
		@rRequestFromTime date='',
		@rRequestToTime date='',
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRANSACTION
	BEGIN TRY
		Select 
			RR.Id,ISNULL(RR.RequestDate,'') AS RequestDate,ISNULL(RR.RequestFromTime,'') AS RequestFromTime,ISNULL(RR.RequestToTime,'') As RequestToTime,ISNULL(RR.ResourceId,0) AS ResourceId,RR.RequestedBy,
			RR.RequestedRemark,ISNULL(RR.StatusId,0) AS StatusId,SM.Title As Status
		From sInfrastructure.tResourceRequest RR
		INNER JOIN sInfrastructure.tResourceMaster R ON R.Id =RR.ResourceId  
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id =RR.StatusId
		
		Where
		((RR.Id=@rId) OR (@rId=0))
		AND ((RequestFromTime=@rRequestFromTime) OR (ISNULL(@rRequestFromTime,'')=''))
		AND ((RequestToTime=@rRequestToTime) OR (ISNULL(@rRequestToTime,'')=''))
		AND RR.OrgGroupId =@rOrgGroupId
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pAutoCompleteForStockItem]	 
	 
	 @rStockitemName Nvarchar(50) = ''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN    
    
      SELECT SIM.Id,
			 SIM.Code,			 
			 SIM.Title			 
	   FROM	sIp.tStockItemMaster SIM	       	
	   Where  
	         ((SIM.Title LIKE @rStockitemName + '%' ) OR (ISNULL(@rStockitemName, '') = '')) 
	         AND SIM.IsObsolete = 0 
	        -- AND SIM.IsDrug = 1
	     
	  	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pBinMaintenanceGet]
	@rStoreLocationId [int] = 0,
	@rId [int] = 0,
	@rIsWildCardSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
/*IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rItemCode = sCommon.fSearchStringGet(@rItemCode)	

		END
*/
	 
	 SELECT BM.Id,			
			BM.IsObsolete,
			SIB.Id AS ItemId,
			STM.Code AS ItemCode,
			STM.Title AS ItemName			
	   FROM sIp.tBinMaster BM INNER JOIN  sIp.tStockItemBin SIB
	   ON SIB.BinId = BM.Id   
	   INNER JOIN sIp.tStockItemMaster STM
	   ON STM.Id = SIB.StockItemId
	  WHERE ((BM.Id = @rId) OR (@rId = 0))	   
	  AND BM.StoreLocationId = @rStoreLocationId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pBinMaintenanceTransfer]
 
	@rId [int],
	@rUpdatedUserId [bigint],
	@rBinUpdateXML [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lIntErrorCode INT,   
				@lIntDoc INT
				
	  EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rBinUpdateXML
						
					  
			UPDATE sIp.tStockItemBin
				SET				
				sIp.tStockItemBin.BinId = @rId, 
				sIp.tStockItemBin.UpdatedUserId =  @rUpdatedUserId, 
				sIp.tStockItemBin.UpdatedDateTime = sCommon.fGetDate()
			FROM OPENXML (@lIntDoc, '/BinUpdate/BinMaintenance', 1)
				 WITH ( 
				 Id INT, 
				 BinId INT
				 --ObsoleteRemark NVARCHAR(300),
				 --UpdatedUserId BIGINT		
					  ) XmlTable
					WHERE sIp.tStockItemBin.Id = XmlTable.Id --IN ( SELECT Id	FROM OPENXML (@lIntDoc, '/OrderDetailUpdateFormat/OrderDetailUpdate', 1)  
		  
	
SELECT 1 AS RESULT

 
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pBinMasterAdd]
	@rOrgGroupId int,
	@rCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rStoreLocationId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sIp.tBinMaster WHERE UPPER(Title) = UPPER(@rTitle) AND StoreLocationId = @rStoreLocationId  )

BEGIN	

	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tBinMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sIp.tBinMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StoreLocationId
		 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rStoreLocationId
		 
		)
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pBinMasterGet]
 
	@rId [int] = 0,
	@rTitle [nvarchar](50) = '',
	@rIsWildCardSearch [bit] = 1,
	@rCode [nvarchar](20) = '',
	@rStoreLocationId [int] = 0
	--,@rLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	 
	 SELECT BM.Id,
			BM.Code,
			BM.Title,
			BM.IsObsolete,
			BM.StoreLocationId AS LocationId,
			SLM.Title AS LocationCode
			--,LM.Id AS LocationId 			
	  FROM sIp.tBinMaster BM INNER JOIN  sIp.tStoreLocationMaster SLM
	   ON BM.StoreLocationId  = SLM.Id 
	   --INNER JOIN sCommon.tLocationMaster LM
	   --ON LM.Id=SLM.LocationId
	  WHERE ((BM.Id = @rId) OR (@rId = 0))
	   AND ((BM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND ((BM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((BM.StoreLocationId = @rStoreLocationId) )
	  
	   --AND LM.Id=@rLocationId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pBinMasterModify]
	 
	@rId [int],
	@rCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rStoreLocationId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--DECLARE @lAccId dInt
IF NOT EXISTS (SELECT 1 FROM sIp.tBinMaster WHERE UPPER(Title) = UPPER(@rTitle)  AND Id  <> @rId AND StoreLocationId = @rStoreLocationId )
BEGIN
--IF(@rStoreLocationCode <> '') 
 --SET @lAccId = (select Id  FROM sIp.tStoreLocationMaster  WHERE code = @rStoreLocationCode)
	 UPDATE sIp.tBinMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			--StoreLocationId = @rStoreLocationId, 
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pCheckUomGet]
	@rUomId [int] = 0,
	@rStockItemId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	  
		SELECT	SIPOUM.ITEMsOURCEID,
			SIPOUM.sTOCKITEMPURCHASEUOMID		
	   FROM sprocurement.[vExtPurchaseOrderDetail]  SIPOUM  
 WHERE ((SIPOUM.ITEMsOURCEID = @rStockItemId) AND (SIPOUM.sTOCKITEMPURCHASEUOMID = @rUomId) )
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pImportStockIem]
	@rOrgId int,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rStoreLocationId int,
	@rOrgGroupId smallint,
	@rLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,@intDoc INT,@lCode nvarchar(20),
	@lName nvarchar(100),@lSubGroup nvarchar(100),
	@lStockItemCategory nvarchar(100),@lIssueUOM nvarchar(50),
	@lSubGroupId int,@lStockItemCategoryId int,@lIssuUOMId int,
	@lResult int,@lresultCode nvarchar(100),@lIsBatchWiseTracking bit,
	@lSafetyStock decimal(12,2),@lStandardDose nvarchar(500),@lReminder nvarchar(500),@lStandardPrice decimal(22,6)
	Declare @lbinCode nvarchar(20),@lVendorCode nvarchar(50),@lVendorCategory nvarchar(50),
	@lBinId int,@lVendorId int, @lVendorCategoryId int

	Declare @loXML XML
    SET @loXML = CAST(@rXmldoc AS XML)

	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	CREATE TABLE #tTable1 
	(
		Id int identity,Code nvarchar(50),Name nvarchar(100),SubGroup nvarchar(100),
		StockItemCategory nvarchar(100),IssueUOM nvarchar(50),SafetyStock decimal(12,2),
		BinCode nvarchar(50),VendorCode nvarchar(50), IsBatchWiseTracking bit ,StandardPrice decimal(22,6)
	)
	INSERT INTO #tTable1
	Select 
		 T.c.value('@Code','nvarchar(20)') AS Code,
            T.c.value('@Name','nvarchar(100)') AS Name,
            T.c.value('@SubGroup','nvarchar(100)') AS SubGroup,
            T.c.value('@StockItemCategory','Nvarchar(100)') AS StockItemCategory,
            T.c.value('@IssueUOM','nvarchar(50)')   AS IssueUOM,
            T.c.value('@SafetyStock','Decimal(12,2)') AS SafetyStock,
            T.c.value('@BinCode','nvarchar(50)') AS BinCode,
            T.c.value('@VendorCode','nvarchar(50)') AS VendorCode,
			T.c.value('@IsBatchWiseTracking','bit') AS IsBatchWiseTracking,
			T.c.value('@StandardPrice','decimal(22,6)') AS StandardPrice
	
	FROM 
            @loXML.nodes('/Table/ImportStockItem')T(c)
	--INSERT INTO #tTable1
	--(
	--	Code,Name,SubGroup,StockItemCategory,IssueUOM,SafetyStock,BinCode,
	--	VendorCode, IsBatchWiseTracking
	--)      
	--SELECT Code,Name,SubGroup,StockItemCategory,IssueUOM,SafetyStock,BinCode,
	--VendorCode, IsBatchWiseTracking
	--FROM OPENXML (@intDoc, '/Table/ImportStockItem', 1)
	--With
	--(   
	--	Code nvarchar(20) '@Code',Name nvarchar(100) '@Name',
	--	SubGroup nvarchar(100) '@SubGroup',
	--	StockItemCategory nvarchar(100) '@StockItemCategory',
	--	IssueUOM nvarchar(50) '@IssueUOM',
	--	SafetyStock decimal(12,2) '@SafetyStock',
	--	BinCode nvarchar(50) '@BinCode',
	--	VendorCode nvarchar(50) '@VendorCode',
	--	--VendorCategory nvarchar(50) '@VendorCategory',
	--	IsBatchWiseTracking  '@IsBatchWiseTracking'
	--)
	EXEC sp_xml_removedocument @intDoc
	SELECT @lCount = COUNT(Id) FROM #tTable1
	PRINT @lCount
	WHILE @lCount > 0 
	BEGIN
		SELECT @lCode = Code,@lName = [ssetup].[fPortalXMLTagsReplaceReverse](Name),@lSubGroup = SubGroup,
		@lStockItemCategory = StockItemCategory,@lIssueUOM = IssueUOM,
		@lSafetyStock=SafetyStock,@lbinCode=BinCode,
		@lVendorCode=VendorCode, @lIsBatchWiseTracking=IsBatchWiseTracking, @lStandardPrice = StandardPrice
		FROM #tTable1 WHERE Id = @lCount
		
		IF NOT EXISTS(SELECT 1 FROM sIp.tStockItemMaster where Code = @lCode AND StoreLocationId = @rStoreLocationId)           
		BEGIN
			SELECT @lSubGroupId = Id From sIp.tItemSubGroupMaster where Title = @lSubGroup
			SELECT @lStockItemCategoryId= Id From sIp.tStockItemCategoryMaster where Title = @lStockItemCategory AND Storelocationid=@rStoreLocationId
			
			Select @lBinId = Id from sIp.tBinMaster where StoreLocationId =@rStoreLocationId And Code = @lBinCode
			Select @lVendorId = Id from sProcurement.tVendorMaster where LocationId= @rStoreLocationId And Code=@lVendorCode
			--Select @lVendorCategoryId=Id from sProcurement.tVendorCategoryMaster Where OrgGroupId =@rOrgGroupId And Code=@lVendorCategory
			
			SELECT @lIssuUOMId= Id From sFinanceCommon.tStockUomMaster where Title = @lIssueUOM AND OrgGroupId=@rOrgGroupId
			
			if  @lBinId is null	
			BEGIN
				Select -1 As Result
				Return
			END

			if @lVendorId is null
			BEGIN
				Select -2 As Result
				Return
			END
			
			if @lIssuUOMId is null
			BEGIN
				Select -11 As Result
				Return
			END

			IF @lSubGroupId IS NULL
			BEGIN
				Select -3 As Result
				Return
			END

			--Select @lIssuUOMId AS IssuUOMId,@lStockItemCategoryId AS StockItemCategoryId,@lSubGroupId AS SubGroupId
			--SET @lResult = -101
			print @lIssuUOMId
			print @lSubGroupId

			IF(@lSubGroupId > 0  AND @lIssuUOMId>0)
			BEGIN
				DECLARE @lNextNumber INT
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tStockItemMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				  
				INSERT INTO	sIp.tStockItemMaster
				(
					Id,Code,Title,CreatedUserId,CreatedDateTime,UpdatedUserId,
					UpdatedDateTime,StockItemCategoryId,IsBatchWiseTracking,
					IssueStockUomId,ItemSubGroupId,SafetyStock,VendorId,
					IsObsolete,OrgGroupId,TaxGroupId,Remark,IsBlockedForIssue,
					StoreLocationId,LocationId,StandardDose,BinId,Reminder
				)
				VALUES
				(
					@lNextNumber,@lCode,@lName,@rUserId,sCommon.fGetDate(),
					@rUserId,sCommon.fGetDate(),@lStockItemCategoryId,
					@lIsBatchWiseTracking,@lIssuUOMId,@lSubGroupId,
					@lSafetyStock,@lVendorId,0,@rOrgGroupId,null,null,0,
					@rStoreLocationId,@rLocationId,null,@lBinId,@lReminder
				)
				
				
				EXECUTE [sIp].[pStockItemPlanningAdd] 0,@lNextNumber,0,0,0,@lStandardPrice,null,null,@rStoreLocationId,@rOrgGroupId
  				EXECUTE sProcurement.pStockBatchAdd  @rOrgGroupId,@rStoreLocationId,@lNextNumber,null,null,0,@rUserId ,0 
  	
				--EXECUTE	sIp.pStockItemPurchaseUomAdd @rOrgGroupId,@lNextNumber,@rIssueStockUomId,1,0,@rCreatedUserId	
				--EXEC [sIp].[pItemStandardPriceLogAdd] @lNextNumber, @rStandardPrice, @rCreatedUserId,@rOrgGroupId
 
				SET @lResult = 1
				
				Set @lresultCode= @lCode
				 
			END
		END
		  
		ELSE
		BEGIN
			Set @lResult=-101
			Set @lresultCode= @lCode
		END
		SET @lCount = @lCount - 1
	END
	Select @lResult AS Result,@lresultCode AS Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pImportStockItemCategory]
	  
	@rStrXml nvarchar(max),
	@rStoreLocationId int,
	@rScreenId int,
	@rOrgId int,
	@rCreatedUserId Bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lInterrorCode INT,@intDoc INT
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml

BEGIN
		
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		Code nvarchar(100),
		Name nvarchar(100)
	)

	INSERT INTO #tempTable
	(
		Code,
		Name
	)

	SELECT  A.Code,A.Name
			FROM OPENXML (@intDoc, '/Table/ImportStockMainMasterItem', 1)
	WITH
	(
		Code nvarchar(100) '@Code',
		Name nvarchar(100) '@Name'			
	) A
	
	EXEC sp_xml_removedocument @intDoc

	DECLARE @lCode nvarchar(100),@lTitle nvarchar(100)

	DECLARE @lCount int,@lId int

	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable

	WHILE @lId <= @lCount 
	BEGIN
		select @lCode = Code from #tempTable where Id = @lId
		select @lTitle = Name from #tempTable where Id = @lId
		
		IF Exists (SELECT Id FROM sIp.tStockItemCategoryMaster WHERE Code = @lCode AND StoreLocationId  = @rStoreLocationId)
		BEGIN
			Select -102 AS Result, 'Code Already Exists ' + @lCode AS Msg
			RETURN
		END

		IF EXISTS(SELECT Id FROM sIp.tStockItemCategoryMaster WHERE Title = @lTitle AND StoreLocationId  = @rStoreLocationId)
		BEGIN
		 Select -103 AS Result, 'Name Already Exists ' + @lTitle AS Msg
		 RETURN
		END

		SET @lId=@lId+1
	END
		

	Declare @lIsStatic1to100 bit, @lNextNumber BigInt, @lSeed int

	SET @lIsStatic1to100 = (SELECT IsStatic1to100 FROM sCommon.tCommonMaster AS tCM  LEFT JOIN sSecurity.tScreen SS ON ((tCM.ScreenId = SS.Id) AND (SS.IsObsolete = 0)) WHERE (ScreenId = @rScreenId))
	
	SET @lSeed = (CASE WHEN @lIsStatic1to100 = 1 THEN 101 ELSE 1 END)

	DECLARE @lCount1 int,@lId1 int
	SELECT @lCount1 = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId1=Id FROM #tempTable

	WHILE @lId1 <= @lCount1 
	BEGIN
		EXECUTE  sCommon.pTableRowIdGet  @rOrgId, 'sIp.tStockItemCategoryMaster', 0, @lSeed, 1,@outNextNumber = @lNextNumber output
		SET @lNextNumber = @lNextNumber

		select @lCode = Code from #tempTable where Id = @lId1
		select @lTitle = Name from #tempTable where Id = @lId1
		INSERT INTO sIp.tStockItemCategoryMaster
			(Id, Code, Title, IsObsolete, CreatedUserId,  CreatedDateTime, UpdatedUserId, UpdatedDateTime, StoreLocationId)
		VALUES
			(@lNextNumber, @lCode, @lTitle, 0, @rCreatedUserId, sCommon.fGetDate(), @rCreatedUserId, sCommon.fGetDate(), @rStoreLocationId)

		SET @lId1=@lId1+1
	END

	Select 1 AS Result, '' AS Msg

	DROP Table #tempTable
	END TRY

	BEGIN CATCH 
	SELECT -1 AS Result, error_message() AS Msg
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pImportStockItemSubGroup]
	  
	@rStrXml nvarchar(max),
	@rStoreLocationId int,
	@rOrgGroupId int,
	@rCreatedUserId Bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lInterrorCode INT,@intDoc INT
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml

BEGIN
		
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		Code nvarchar(100),
		Name nvarchar(100),
		ItemMainGroup nvarchar(100)
	)

	INSERT INTO #tempTable
	(
		Code,
		Name,
		ItemMainGroup
	)

	SELECT  A.Code,A.Name,A.ItemMainGroup
			FROM OPENXML (@intDoc, '/Table/ImportStockMainMasterItem', 1)
	WITH
	(
		Code nvarchar(100) '@Code',
		Name nvarchar(100) '@Name',
		ItemMainGroup nvarchar(100) '@ItemMainGroup'		
	) A
	
	EXEC sp_xml_removedocument @intDoc

	DECLARE @lCode nvarchar(100),@lTitle nvarchar(100),@lItemMainGroup nvarchar(100)

	DECLARE @lCount int,@lId int

	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable

	WHILE @lId <= @lCount 
	BEGIN
		select @lCode = Code from #tempTable where Id = @lId
		select @lTitle = Name from #tempTable where Id = @lId
		SELECT @lItemMainGroup= ItemMainGroup from #tempTable where Id = @lId

		IF Exists (SELECT Id FROM sIp.tItemSubGroupMaster WHERE Code = @lCode AND StoreLocationId  = @rStoreLocationId)
		BEGIN
			Select -102 AS Result, 'Code Already Exists ' + @lCode AS Msg
			RETURN
		END

		IF EXISTS(SELECT Id FROM sIp.tItemSubGroupMaster WHERE Title = @lTitle AND StoreLocationId  = @rStoreLocationId)
		BEGIN
		 Select -103 AS Result, 'Name Already Exists ' + @lTitle AS Msg
		 RETURN
		END

		IF NOT EXISTS(SELECT Id FROM sIp.tItemMainGroupMaster WHERE Title = @lItemMainGroup AND StoreLocationId  = @rStoreLocationId)
		BEGIN
		 Select -100 AS Result, 'Item Main Group Not Exists ' + @lItemMainGroup AS Msg
		 RETURN
		END

		SET @lId=@lId+1
	END
		

	DECLARE @lCount1 int,@lId1 int
	SELECT @lCount1 = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId1=Id FROM #tempTable

	WHILE @lId1 <= @lCount1 
	BEGIN
		DECLARE @lNextNumber INT,@lItemMainGroupId int
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tItemSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

		select @lCode = Code from #tempTable where Id = @lId1
		select @lTitle = Name from #tempTable where Id = @lId1
		SELECT @lItemMainGroup= ItemMainGroup from #tempTable where Id = @lId1

		SET @lItemMainGroupId =(Select Id from sIp.tItemMainGroupMaster WHERE Title = @lItemMainGroup AND StoreLocationId  = @rStoreLocationId)
		
		INSERT INTO sIp.tItemSubGroupMaster
		(
			Id,
			Code,
			Title,
			ItemMainGroupId,			
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId,
			StoreLocationId
		)
	VALUES
		(
			@lNextNumber,
			@lCode,
			@lTitle,
			@lItemMainGroupId,			
			0,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rStoreLocationId
		)

		SET @lId1=@lId1+1
	END

	Select 1 AS Result, '' AS Msg

	DROP Table #tempTable
	END TRY

	BEGIN CATCH 
	SELECT -1 AS Result, error_message() AS Msg
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pImportStockMainGroupMaster]
	  
	@rStrXml nvarchar(max),
	@rStoreLocationId int,
	@rScreenId int,
	@rOrgId int,
	@rCreatedUserId Bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lInterrorCode INT,@intDoc INT
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml

BEGIN
		
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		Code nvarchar(100),
		Name nvarchar(100)
	)

	INSERT INTO #tempTable
	(
		Code,
		Name
	)

	SELECT  A.Code,A.Name
			FROM OPENXML (@intDoc, '/Table/ImportStockMainMasterItem', 1)
	WITH
	(
		Code nvarchar(100) '@Code',
		Name nvarchar(100) '@Name'			
	) A
	
	EXEC sp_xml_removedocument @intDoc

	
	DECLARE @lCode nvarchar(100),@lTitle nvarchar(100)

	DECLARE @lCount int,@lId int

	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable

	WHILE @lId <= @lCount 
	BEGIN
		select @lCode = Code from #tempTable where Id = @lId
		select @lTitle = Name from #tempTable where Id = @lId
		
		IF Exists (SELECT Id FROM sIp.tItemMainGroupMaster WHERE Code = @lCode AND StoreLocationId  = @rStoreLocationId)
		BEGIN
			Select -102 AS Result, 'Code Already Exists ' + @lCode AS Msg
			RETURN
		END

		IF EXISTS(SELECT Id FROM sIp.tItemMainGroupMaster WHERE Title = @lTitle AND StoreLocationId  = @rStoreLocationId)
		BEGIN
		 Select -103 AS Result, 'Name Already Exists ' + @lTitle AS Msg
		 RETURN
		END

		SET @lId=@lId+1
	END
		

	Declare @lIsStatic1to100 bit, @lNextNumber BigInt, @lSeed int

	SET @lIsStatic1to100 = (SELECT IsStatic1to100 FROM sCommon.tCommonMaster AS tCM  LEFT JOIN sSecurity.tScreen SS ON ((tCM.ScreenId = SS.Id) AND (SS.IsObsolete = 0)) WHERE (ScreenId = @rScreenId))
	
	SET @lSeed = (CASE WHEN @lIsStatic1to100 = 1 THEN 101 ELSE 1 END)

	DECLARE @lCount1 int,@lId1 int
	SELECT @lCount1 = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId1=Id FROM #tempTable

	WHILE @lId1 <= @lCount1 
	BEGIN
		EXECUTE  sCommon.pTableRowIdGet  @rOrgId, 'sIp.tItemMainGroupMaster', 0, @lSeed, 1,@outNextNumber = @lNextNumber output
		SET @lNextNumber = @lNextNumber

		select @lCode = Code from #tempTable where Id = @lId1
		select @lTitle = Name from #tempTable where Id = @lId1
		INSERT INTO sIp.tItemMainGroupMaster
			(Id, Code, Title, CreatedUserId,  CreatedDateTime, IsObsolete, StoreLocationId)
		VALUES
			(@lNextNumber, @lCode, @lTitle, @rCreatedUserId, sCommon.fGetDate(), 0,@rStoreLocationId)

		SET @lId1=@lId1+1
	END

	Select 1 AS Result, '' AS Msg

	DROP Table #tempTable
	END TRY

	BEGIN CATCH 
	SELECT -1 AS Result, error_message() AS Msg
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pItemMainGroupMasterAdd]
	@rCode [nvarchar](10),
	@rTitle [nvarchar](50),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	--EXECUTE sCommon.pTableRowIdGet 'sIp.tItemMainGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tItemMainGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sIp.tItemMainGroupMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pItemMainGroupMasterGet]
	@rId [smallint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sIp.tItemMainGroupMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pItemMainGroupMasterModify]
	@rId [smallint],
	@rCode [nvarchar](10),
	@rTitle [nvarchar](50),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sIp.tItemMainGroupMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pItemMainGroupMasterRemove]
	@rId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sIp.tItemMainGroupMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pItemStandardPriceLogAdd]
	@rStockItemId [int],
	@rStandardPrice [decimal](22, 6),
	@rCreatedUserId [bigint],
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN	

	DECLARE @lNextNumber BIGINT

	 EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sIp.tItemStandardPriceLog',@lNextNumber = @lNextNumber output

	INSERT INTO sIp.tItemStandardPriceLog
		(
			Id,
			StockItemId,
			StandardPrice,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rStockItemId,
			@rStandardPrice,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
END



/****** Object:  StoredProcedure [sProcurement].[pPurchaseOrderDetailGet]    Script Date: 07/09/2013 16:25:29 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pItemSubGroupMasterAdd]
	@rOrgGroupId int,
	@rCode [nvarchar](20),
	@rTitle [nvarchar](100),
	@rItemMainGroupId [int],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rStoreLocationId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF NOT EXISTS (SELECT 1 FROM sIp.tItemSubGroupMaster WHERE UPPER(Title) = UPPER(@rTitle) AND OrgGroupId=@rOrgGroupId AND StoreLocationId=@rStoreLocationId )
BEGIN

	DECLARE @lNextNumber INT
	 
	 --EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sIp.tItemSubGroupMaster',@lNextNumber = @lNextNumber output
	 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tItemSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sIp.tItemSubGroupMaster
		(
			Id,
			Code,
			Title,
			ItemMainGroupId,			
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId,
			StoreLocationId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rItemMainGroupId,			
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rStoreLocationId
		)
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pItemSubGroupMasterForPrescriptionGet]
	@rOrgGroupId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 
	 SELECT C.Id,
			C.Code,			 
			C.ItemMainGroupId,			
			C.IsObsolete,			 
			M.Title AS ItemMainGroupName
			
	   FROM sIp.tItemSubGroupMaster C INNER JOIN sIp.tItemMainGroupMaster M
			ON C.ItemMainGroupID = M.ID
	  WHERE  
	         C.OrgGroupId = @rOrgGroupId
	       
	   

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sIp].[pItemSubGroupMasterGet]
	 
	@rId [int] = 0,
	@rCode [nvarchar](20) = '',
	@rTitle [nvarchar](100) = '',
	@rStoreLocationId int = 0,
	@rIsWildCardSearch [bit] = 1,
	@rMainGroupId int = 0,
	@rOrgGroupId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
		END
		
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)

	 SELECT C.Id,
			C.Code,
			C.Title,
			ISNULL(C.ItemMainGroupId,0) AS ItemMainGroupId,			
			C.IsObsolete,
			C.CreatedUserId,
			C.CreatedDateTime,
			C.UpdatedUserId,
			C.UpdatedDateTime, 
			ISNULL(M.Title,'') AS ItemMainGroupName
	   FROM sIp.tItemSubGroupMaster C INNER JOIN sIp.tItemMainGroupMaster M
			ON C.ItemMainGroupID = M.ID
	  WHERE ((C.Id = @rId) OR (@rId = 0))
	  	    AND ((C.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	       AND ((C.Code LIKE @rCode ) OR (ISNULL(@rCode, '') = ''))
	       AND ((c.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0) )
	       AND (( C.ItemMainGroupId = @rMainGroupId) OR (@rMainGroupId = 0))
			AND ((C.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))
	       
	   

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pItemSubGroupMasterModify]
	@rId [int],
	@rCode [nvarchar](20),
	@rTitle [nvarchar](100),
	@rItemMainGroupId [int],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET NOCOUNT ON
BEGIN
IF NOT EXISTS (SELECT 1 FROM sIp.tItemSubGroupMaster WHERE UPPER(Title) = UPPER(@rTitle) AND Id  <> @rId)

BEGIN
	 UPDATE sIp.tItemSubGroupMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			ItemMainGroupId = @rItemMainGroupId,			
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pItemSubGroupMasterRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sIp.tItemSubGroupMaster	 
	    SET IsObsolete = 1
	  WHERE Id = @rId
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockChargeMappingAdd] 
	@rXmlDoc NVARCHAR(max) = ''
AS
SET NOCOUNT ON

BEGIN
	SET @rXmlDoc = REPLACE(@rXmlDoc, '&', 'AND')

	DECLARE @lInterrorCode INT
		,@intDoc INT

	--BEGIN TRY
	BEGIN TRANSACTION

	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT
		,@rXmlDoc

	CREATE TABLE #tTable (
		ChargeId INT NOT NULL
		,StockItemId INT NOT NULL
		,CreatedUserId BIGINT NOT NULL
		)

	INSERT INTO #tTable (
		ChargeId
		,StockItemId
		,CreatedUserId
		)
	SELECT A.ChargeId
		,A.StockItemId
		,A.CreatedUserId
	FROM OPENXML(@intDoc, '/Table/StockChargeMapping', 1) WITH (
			ChargeId INT '@ChargeId'
			,StockItemId INT '@StockItemId'
			,CreatedUserId BIGINT '@CreatedUserId'
			) A

	--SELECT * FROM #tTable		
	DELETE SCM
	FROM [sIp].[tStockChargeMapping] AS SCM
	INNER JOIN #tTable T ON T.StockItemId = SCM.StockItemId

	INSERT INTO [sIp].[tStockChargeMapping] (
		ChargeId
		,StockItemId
		,CreatedUserId
		,CreatedDateTime
		)
	SELECT ChargeId
		,StockItemId
		,CreatedUserId
		,sCommon.fGetDate()
	FROM #tTable

	SELECT 1 AS RESULT

	DROP TABLE #tTable

	COMMIT TRANSACTION
		--END TRY
		--BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1
		--END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sIp].[pStockChargeMappingGet]

@rStockMainGroupId int = 0,
@rStockSubGroupId int = 0,
@rStockItemCategoryId int = 0,
@rStoreLocationId int = 0

AS
SET NOCOUNT ON

BEGIN
	SELECT 
		SIM.Id AS StockItemId,
		SIM.Title AS StockItem,
		ISNULL(SCM.ChargeId,0) AS ChargeId,
		ISNULL(CCM.Id,0) AS ChargeCategoryId,
		ISNULL(CRBM.Id,0) AS ChargeReceiptBookId
	FROM
		[sIp].[tStockItemMaster] SIM
		INNER JOIN sIp.tItemSubGroupMaster SGM ON SIM.ItemSubGroupId = SGM.Id
		LEFT JOIN [sIp].[tStockChargeMapping] SCM ON SCM.StockItemId = SIM.Id
		LEFT JOIN sFee.tChargeMaster CM ON CM.Id = SCM.ChargeId
		LEFT JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id = CM.ChargeCategoryId
		LEFT JOIN sFee.tChargeReceiptBookMaster CRBM ON CRBM.Id = CCM.ChargeReceiptBookId
	WHERE 
		(SIM.StockItemCategoryId = @rStockItemCategoryId OR @rStockItemCategoryId = 0)
		AND (SIM.ItemSubGroupId = @rStockSubGroupId OR @rStockSubGroupId = 0)
		AND (SGM.ItemMainGroupId = @rStockMainGroupId OR @rStockMainGroupId = 0)
		AND SIM.StoreLocationId = @rStoreLocationId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockDefectiveItemMasterAdd]
(	
		@rId int = 0,
		@rOrgGroupId int,
		@rNumber nvarchar(20) = '',
		@rStockItemId int,
		@rStockItemRemark nvarchar(500) = '',
		@rStockInwardId int = 0,
		@rStockInwardRemark nvarchar(500) = '',
		@rCreatedUserId	BigInt,
		@rOrgId int,
		@rStoreLocationId int
)			
AS
SET NOCOUNT ON
BEGIN
IF(@rId = 0)
BEGIN
	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2010,
	@rStoreLocationId = @rStoreLocationId, @rNextNumber  = @rNumber OUTPUT
	
	SET @rNumber = ISNULL(@rNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	END
	DECLARE @lNextNumberStockDefectiveId INT
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sIp.tStockDefectiveItemMaster',@lNextNumber = @lNextNumberStockDefectiveId output
  
	INSERT INTO sIp.tStockDefectiveItemMaster
	(
		Id,
		Number,
		StockItemId, 
		StockItemRemark,		 
		StockInwardId,			 
		StockInwardRemark,
		CreatedUserId,
		CreatedDateTime,
		OrgGroupId
	)
	VALUES
	(
		@lNextNumberStockDefectiveId,
		@rNumber,
		@rStockItemId,
		@rStockItemRemark,		 
		@rStockInwardId,			 
		@rStockInwardRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rOrgGroupId			
	)

	SELECT @lNextNumberStockDefectiveId AS Result
END
ELSE
BEGIN
	UPDATE sIp.tStockDefectiveItemMaster
	SET
		StockItemId = @rStockItemId,  
		StockItemRemark = @rStockItemRemark,		 
		StockInwardId = @rStockInwardId,			 
		StockInwardRemark = @rStockInwardRemark,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate(),
		OrgGroupId = @rOrgGroupId
	WHERE Id = @rId

	SELECT @rId AS Result
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockDefectiveItemMasterListGet]
	@rOrgGroupId int,
	@rId int = 0,
	@rStockDefectiveItemNumber nvarchar(20) = '',
	@rStockItemCode nvarchar(20) = '',
	@rStockItemTitle nvarchar(50) = '',
	@rStockInwardCode nvarchar(20) = '',
	@rStockInwardDate datetime = null

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SET @rStockDefectiveItemNumber = sCommon.fSearchStringGet(@rStockDefectiveItemNumber)	
	SET @rStockItemCode = sCommon.fSearchStringGet(@rStockItemCode)
	SET @rStockItemTitle = sCommon.fSearchStringGet(@rStockItemTitle)
	SET @rStockInwardCode = sCommon.fSearchStringGet(@rStockInwardCode)

	SELECT 
		SDIM.Id,
		SDIM.Number AS StockDefectiveItemNumber,
		SDIM.StockItemId,
		ISNULL(SDIM.StockItemRemark, '') AS StockItemRemark,
		SDIM.StockInwardId,
		ISNULL(SDIM.StockInwardRemark, '') AS StockInwardRemark,
		SDIM.OrgGroupId,
		SDIM.CreatedUserId,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemTitle,
		SI.Number AS StockInwardCode,
		0 AS StoreLocationId,
		0 AS OrgId,
		SI.TransactionDate AS StockInwardDate
	FROM sIp.tStockDefectiveItemMaster SDIM
		LEFT JOIN sIp.tStockItemMaster SIM ON SIM.Id = SDIM.StockItemId
		LEFT JOIN sProcurement.tStockInward SI ON SI.Id = SDIM.StockInwardId
	WHERE  
		(SDIM.Id = @rId OR @rId = 0)
		AND (SDIM.Number LIKE @rStockDefectiveItemNumber OR ISNULL(@rStockDefectiveItemNumber,'') = '')
		AND ((SIM.Title LIKE @rStockItemTitle) OR (ISNULL(@rStockItemTitle, '') = ''))
		AND ((SIM.Code LIKE @rStockItemCode) OR (ISNULL(@rStockItemCode, '') = ''))	
		AND ((SI.Number LIKE @rStockInwardCode) OR (ISNULL(@rStockInwardCode, '') = ''))
		AND (SI.TransactionDate = @rStockInwardDate OR ISNULL(@rStockInwardDate, '') = '')
		AND SDIM.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItembinAdd]
    @rOrgGroupId Int,
	@rStockItemId [int],
	@rBinId [int],
	@rStoreLocationId int,
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId,'sIp.tStockItembin', 0, 1, 1,@outNextNumber = @lNextNumber output

	
	INSERT INTO sIp.tStockItembin
		(
		    
			Id,
			StockItemId,
			BinId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StoreLocationId
		)
	VALUES
		(
			 
			@lNextNumber,
			@rStockItemId,
			@rBinId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rStoreLocationId
		)
		SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemBinGetlist]
	@rStoreLocationId int,
	@rIsWildCardSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
IF    @rIsWildCardSearch = 1
BEGIN
	  SELECT  Bin.ID, Bin.Title, Bin.StoreLocationId 
	  FROM sIp.tBinMaster Bin  WHERE Bin.IsObsolete = 0	
	  AND StoreLocationId = @rStoreLocationId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemBinModify]    
	@rId [int],
	@rStockItemId [int],
	@rBinId [int],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sIp.tStockItembin
		SET 
			StockItemId = @rStockItemId,
			BinId = @rBinId,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemForPrescriptionGet]
	 
	 @rOrgId int,
	 @rStockitemName Nvarchar(50) = '',
	 @rSubgroupCode Nvarchar(50) = '' ,
	 --@rselectedtext Nvarchar(50) = '',
	 @rLocationId int 
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN    
    
    --IF(@rselectedtext = 'All')
    BEGIN
      SELECT SIM.Id,
			 SIM.Code,			 
			 SIM.Title AS StockItemName,
			 ISNULL(DI.Title,'') AS DrugInstruction,
			 SIM.DrugInstructionId,
		     ISNULL(DI.Dosage,0) AS Dosage,
			 SIM.IsNotInstore,
			 SIM.IsAllowDirectIssue,
			 SIM.Remark,
			 SIM.ItemSubGroupId
			 
			 			 
	   FROM	sIp.tStockItemMaster SIM
	        INNER JOIN sIp.tItemSubGroupMaster SGM ON SGM.Id = SIM.ItemSubGroupId	
	        LEFT JOIN sExamination.tDrugInstructionMaster DI ON DI.Id = SIM.DrugInstructionId 
	        
	   Where SIM.OrgId = @rOrgId
	     AND SIM.IsObsolete = 0 
	     AND SIM.IsDrug = 1 AND SIM.IsBlockedForIssue = 0
	     AND  ((SIM.Title LIKE @rStockitemName + '%' ) OR (ISNULL(@rStockitemName, '') = '')) 
	     AND  ((SGM.Code LIKE @rSubgroupCode) OR (ISNULL(@rSubgroupCode, '') = ''))
	     AND  (SIM.LocationId = @rLocationId)
  END
 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sIp].[pStockItemMasterAdd]
    @rOrgGroupId int,
	@rCode [nvarchar](100),
	@rTitle [nvarchar](100),
	@rCreatedUserId [bigint],
	@rStockItemCategoryId int,	 
	@rIsBatchWiseTracking [bit],
	@rIssueStockUomId [int],
	@rItemSubGroupId [int],
	@rMaximumInventory [decimal](12, 2),	
	@rReOrderPoint [decimal](12, 2),
	@rSafetyStock [decimal](12, 2),	 
	@rStandardPrice [decimal](22, 6), 
	@rTaxGroupId Int,	 
	@rVendorId [int],	 
	@rIsObsolete [bit],
	@rStoreLocationId int,
	@rIsBlockedForIssue bit,	
	@rDrugRemark nvarchar(500),
	@rOrgId int=0,
	@rBinId int=0,
	@rReorderQuantity decimal(12,2)=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

--IF NOT EXISTS (SELECT 1 FROM sIp.tStockItemMaster WHERE UPPER(UniversalProductCode) = UPPER(@rUniversalProductCode) AND UPPER(UniversalProductCode) <> NULL  )
 
BEGIN

DECLARE @lCount INT 
DECLARE @StoreLocationId INT 
DECLARE @rStockBatchId INT

 --IF NOT EXISTS (SELECT 1 FROM sIp.tStockItemMaster WHERE UPPER(Code) = UPPER(@rCode) AND OrgGroupId = @rOrgGroupId AND LocationId=@rLocationId)
 --BEGIN	

	DECLARE @lNextNumber INT
	 
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sIp.tStockItemMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tStockItemMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sIp.tStockItemMaster
		(
			Id,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,		
			StockItemCategoryId,			 
			IsBatchWiseTracking,
			IssueStockUomId,
			ItemSubGroupId, 
			TaxGroupId,		 
			VendorId, 			 
			IsObsolete,
			OrgGroupId,
			IsBlockedForIssue,
			StoreLocationId,		
			Remark,
			LocationId,
			BinId
			
	
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),			
			@rStockItemCategoryId, 			 
			@rIsBatchWiseTracking,			 
			@rIssueStockUomId,
			@rItemSubGroupId,			
			(CASE WHEN @rTaxGroupId <= 0 THEN NULL ELSE @rTaxGroupId END),	 
		     @rVendorId  ,			 
			@rIsObsolete,
			@rOrgGroupId,
			@rIsBlockedForIssue,
			@rStoreLocationId,			
			@rDrugRemark,
			@rStoreLocationId,
			@rBinId	
		)
 
 
CREATE TABLE #tmpStoreLocation
(
	Id int identity,
	StoreLocationId int
)	 
		 
INSERT INTO #tmpStoreLocation
SELECT Id FROM sIP.tStoreLocationMaster WHERE Id = @rStoreLocationId

SELECT @lCount =  COUNT(Id) FROM #tmpStoreLocation

WHILE @lCount > 0 
 	BEGIN

 		SELECT  @StoreLocationId = StoreLocationId 
 	   FROM #tmpStoreLocation WHERE Id = @lCount	
 
	EXECUTE [sIp].[pStockItemPlanningAdd] 0,@lNextNumber,@rMaximumInventory,@rReorderPoint,@rSafetyStock,@rStandardPrice,null,null,@StoreLocationId,@rOrgGroupId,@rReorderQuantity
 	EXECUTE sProcurement.pStockBatchAdd  @rOrgGroupId,@StoreLocationId,@lNextNumber,null,null,0,@rCreatedUserId ,@rStandardPrice,  @rStockBatchId
 
		SET @lCount = @lCount - 1
	END	
 	
	EXECUTE	sIp.pStockItemPurchaseUomAdd @rOrgGroupId,@lNextNumber,@rIssueStockUomId,1,0,@rCreatedUserId	
 
	
	EXEC [sIp].[pItemStandardPriceLogAdd] @lNextNumber, @rStandardPrice, @rCreatedUserId,@rOrgGroupId

SELECT @lNextNumber AS RESULT 
    
 END
 
-- ELSE
--	BEGIN
--		SELECT -100 AS RESULT 
--	END
--END
   
 
--ELSE
--	BEGIN
--		SELECT -300 AS RESULT
--	END
--END




/****** Object:  StoredProcedure [sIp].[pStockItemMasterModify]    Script Date: 07/09/2013 16:20:05 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemMasterGet]
    @rOrgGroupId int,
	@rId [int] = 0,
	@rCode [nvarchar](100),  
	@rTitle [nvarchar](100),  
	@rIsAbsoluteTitle [bit] = 0,
	@rIsWildCardSearch [bit] = 1,
	@rStoreLocationId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF @rIsAbsoluteTitle = 0
	BEGIN
		IF @rIsWildCardSearch = 1
			BEGIN
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END
	END
 


	SELECT 	SIM.Id,
			SIM.Code,
			--CAST(SIM.StockItemTypeId AS INT) AS StockItemTypeId,
			SIM.Title,
			CAST(ISNULL(SIP.LastPurchasePrice, 0) AS DECIMAL(22, 2)) LastPurchasePrice, 
			SIM.CreatedUserId,
			SIM.CreatedDateTime,
			SIM.UpdatedUserId,
			SIM.UpdatedDateTime,
			--SIT.Title AS StockItemTypeTitle,
			--SIT.Code AS StockItemTypeCode,
			SIM.IssueStockUomId,
			SU.Code UomCode,
			Su.Title UomTitle,
			SIM.IsBatchWiseTracking
			
	   FROM	sIp.tStockItemMaster SIM
	   INNER JOIN sIp.tStockItemPlanning SIP 
	   ON SIP.StockItemId=SIM.Id	
	 --  INNER JOIN sIp.tStockItemTypeMaster SIT
		--ON SIM.StockItemTypeId = SIT.Id
	   LEFT OUTER JOIN sFinanceCommon.tStockUomMaster SU
		ON SU.Id = SIM.IssueStockUomId
	   WHERE((SIM.Id = @rId) OR (@rId = 0)) 
		AND	((SIM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
		AND	(((SIM.Title LIKE @rTitle) AND @rIsAbsoluteTitle = 0) OR (@rTitle = '' AND @rIsAbsoluteTitle = 0) OR ((SIM.Title = @rTitle ) AND @rIsAbsoluteTitle = 1))
		AND SIM.OrgGroupId = @rOrgGroupId
		AND ((SIP.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0)) 
		and SIM.IsObsolete= 0
		
END
 
/****** Object:  StoredProcedure [sProcurement].[pStockItemDetailsForPoDetailsGet]    Script Date: 07/09/2013 16:15:00 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemMasterGrnModify]
	@rId [bigint],
	@rUpdatedUserId [bigint],
	@rLastPurchasePrice [decimal](22, 6),
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--IF NOT EXISTS (SELECT 1 FROM sIp.tStockItemMaster WHERE UPPER(Title) = UPPER(@rTitle))
BEGIN
	--SELECT @rId
	 UPDATE sIp.tStockItemPlanning
		SET 
			StockItemId = @rId,			
			--UpdatedUserId = @rUpdatedUserId,
			--UpdatedDateTime = sCommon.fGetDate(),
			LastPurchasePrice = (CASE WHEN @rLastPurchasePrice <= 0 THEN NULL ELSE @rLastPurchasePrice END)			
	  WHERE StockItemId = @rId	AND StoreLocationId=@rStoreLocationId  
	SELECT 1 AS RESULT
END

--ELSE

 --BEGIN
 ----SELECT -100 AS RESULT
 --END



/****** Object:  StoredProcedure [sProcurement].[pStockFreezeAdjustmentDetailGet]    Script Date: 07/09/2013 16:31:30 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sIp].[pStockItemMasterListGet]
	  @rOrgGroupId [int],
	  @rId [int] = 0,
	  @rTitle [nvarchar](100) = '',
	  @rIsWildCardSearch [bit] = 1,
	  @rCode [nvarchar](20) = '',	 
	  @rStoreLocationId [int]=0,
	  @rItemMainGroupId int,
	  @rItemSubGroupId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lSreffered AS BIT
SET @lSreffered = 0
DECLARE @lCount INT
DECLARE @lUpperBound Int
 
 

	IF @rIsWildCardSearch = 1

		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
		 
	IF @rId = 0
		BEGIN	
			SELECT @lcount = COUNT(Id) FROM sIp.tStockItemMaster WHERE ((Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))AND ((Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = '') AND OrgGroupId = @rOrgGroupId AND StoreLocationId = @rStoreLocationId)
			 
			IF @lCount  = 1
				BEGIN
					SELECT @rId = Id FROM sIp.tStockItemMaster WHERE ((Code = @rCode)  OR (ISNULL(@rCode, '') = '')) AND ((Title = @rTitle) OR (ISNULL(@rTitle, '') = '') AND OrgGroupId = @rOrgGroupId AND StoreLocationId = @rStoreLocationId) 
					IF EXISTS(SELECT Id FROM sProcurement.tStockBatch  WHERE StockItemId = @rId  )
						BEGIN
							SET @lSreffered = 1
						END
					ELSE IF EXISTS(SELECT Id FROM sProcurement.tPurchaseOrderDetail WHERE ItemSourceTypeId = 34 AND ItemSourceId = @rId  )
						BEGIN
							SET @lSreffered = 1
							 
						END
				END
		END		
	ELSE IF @rId <> 0 
		BEGIN
			IF EXISTS(SELECT Id FROM sProcurement.tStockBatch  WHERE StockItemId = @rId  )
					BEGIN
						SET @lSreffered = 1
					END
					ELSE IF EXISTS(SELECT Id FROM sProcurement.tPurchaseOrderDetail WHERE ItemSourceTypeId = 34 AND ItemSourceId = @rId  )

					BEGIN
						  SET @lSreffered = 1
					END
		END
	 
 
	 
 
	 SELECT 
			Row_Number() OVER(ORDER BY SIM.Id) AS RowNumber,
	        @lSreffered AS lSreffered,
	        SIM.Id,
			SIM.Code,
			--IMGM.Title AS ItemMainGroup,
			SIM.Title,
			SIM.CreatedUserId,
			SIM.CreatedDateTime,
			SIM.UpdatedUserId,
			SIM.UpdatedDateTime,
			--SIM.StockItemTypeId,
			ISNULL(SIM.StockItemCategoryId,0) AS StockItemCategoryId,			 
			SIM.IsBatchWiseTracking,		 
			--SIM.IsCritical,
			--SIM.IsDangerousDrug,
			--SIM.IsPoison,
			--SIM.IsPsychotropic,
			SIM.IssueStockUomId,
			ISNULL(SIM.ItemSubGroupId,0) AS ItemSubGroupId,
			SIP.MaximumInventory,
			--SIM.PatentDrugName,
			SIP.ReOrderPoint,
			SIP.SafetyStock,
			--SIM.IsNotInStore,
			--SIM.IsAllowDirectIssue,
			--SIM.DrugInstructionId, 	 
			--SIM.StandardPrice,	
			ISNULL(SIM.TaxGroupId,0) AS TaxGroupId,  	 
			ISNULL(SIM.VendorId, '0') VendorId, 
			ISNULL(ven.Title,'') AS VENDORTITLE,			 		 
			SGM.ItemMainGroupId AS MAINID,
		    --SIM.IsDrug,		    
		    ISNULL(CAST(SIP.StandardPrice AS DECIMAL(18, 2)), '0') StandardPrice,
		    ISNULL(CAST(SIP.LastPurchasePrice AS DECIMAL(18, 2)), '0') LastPurchasePrice,
		    ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') WeightedAverageCost,		    
		    ISNULL(SIM.IsObsolete, '0') IsObsolete,
		    SOM.Title AS IssueStockUOMTitle,
		    SIM.StoreLocationId,
		    SIM.IsBlockedForIssue,
		    --SIM.IsFirstAdd,
		    SIM.Remark AS DrugRemark,
		    ISNULL(SIP.Id,0) AS StockItemPlanningId,
		    --SIM.Reminder,
		    SGM.Title AS SubGroupName,
		    IMGM.Title AS MainGroupName,
		    ISNULl(B.Id,0) as BinId,
		     B.Title As BinTitle,
		     isnull(SIP.ReorderQuantity,0) AS ReorderQuantity
		    --COUNT(*) over() AS TotalRecords		    
		   
						
FROM sIp.tStockItemMaster SIM 
LEFT JOIN sIp.tStockItemPlanning SIP 
ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
INNER JOIN  sIp.tItemSubGroupMaster  SGM 
ON SIM.ItemSubGroupId = SGM.Id 
INNER JOIN  sIp.tItemMainGroupMaster IMGM
ON IMGM.Id=SGM.ItemMainGroupId
LEFT JOIN sFinanceCommon.tStockUomMaster SOM
ON SIM.IssueStockUomId = SOM.Id 
LEFT JOIN sprocurement.vExtVendorMaster ven 
ON SIM.vendorid = ven.Id 
LEFT JOIn sIp.tBinMaster B ON B.ID= SIM.BinID
WHERE
((SIM.Id = @rId) OR (@rId = 0))
AND	((SIM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
AND ((SIM.Title LIKE @rTitle + '%' ) OR (ISNULL(@rTitle, '') = '')) --add '%' for mantis id - 0035279
AND SIM.OrgGroupId = @rOrgGroupId 
AND ((SIM.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
AND ((SIM.ItemSubGroupId = @rItemSubGroupId) OR (@rItemSubGroupId = 0))
AND ((SGM.ItemMainGroupId = @rItemMainGroupId) OR (@rItemMainGroupId = 0))

 
END 



/****** Object:  StoredProcedure [sIp].[pStockItemPlanningAdd]    Script Date: 07/09/2013 16:12:45 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sIp].[pStockItemMasterModify]
	 
	@rId [int],
	@rCode [nvarchar](100),
	@rTitle [nvarchar](100),
	@rUpdatedUserId [bigint],	 
	@rStockItemCategoryId [int],	 
	@rIsBatchWiseTracking [bit], 
	@rIssueStockUomId [int],
	@rItemSubGroupId [int],
	@rMaximumInventory [decimal](12, 2),	 
	@rReOrderPoint [decimal](12, 2),
	@rSafetyStock [decimal](12, 2),
	@rStandardPrice [decimal](22, 6), 
 	@rTaxGroupId [int],  
	@rVendorId [int],	
	@rIsObsolete [bit], 
	@rIsBlockedForIssue bit, 
	@rDrugRemark nvarchar(500),
	@rStoreLocationId int,	
	@rOrgGroupId int,
	@rOrgId INT,
	@rBinId int=0,
	@rReorderQuantity decimal(12,2)=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 DECLARE @lCount INT 
DECLARE @StoreLocationId INT 
	--SELECT @rId
	 UPDATE sIp.tStockItemMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),			 
			StockItemCategoryId = @rStockItemCategoryId,		 
			IsBatchWiseTracking = @rIsBatchWiseTracking,			 
			IssueStockUomId = @rIssueStockUomId,
			ItemSubGroupId = @rItemSubGroupId,
			TaxGroupId = (CASE WHEN @rTaxGroupId <= 0 THEN NULL ELSE @rTaxGroupId END),			 
			VendorId = (CASE WHEN @rVendorId <= 0 THEN NULL ELSE @rVendorId END),
			IsObsolete = @rIsObsolete,
			IsBlockedForIssue = @rIsBlockedForIssue,
			StoreLocationId = @rStoreLocationId,			 
			Remark = @rDrugRemark,
			BinId=@rBinId 
			 
		 
			
	  WHERE Id = @rId
	  
	EXEC [sIp].[pItemStandardPriceLogAdd] @rId, @rStandardPrice, @rUpdatedUserId,@rOrgGroupId
	
 	EXECUTE [sIp].[pStockItemPlanningModify]  @rId,@rMaximumInventory,@rReorderPoint,@rSafetyStock,@rStandardPrice,null,null,@rStoreLocationId,@rReorderQuantity
		
	--EXECUTE sProcurement.pStockBatchAdd  @rOrgId,@rStoreLocationId,@rId,null,null,0,@rUpdatedUserId 
		
SELECT @rId AS RESULT
END

/****** Object:  StoredProcedure [sCwb].[pDoctorActivityTypeMasterGet]    Script Date: 07/09/2013 16:20:51 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemMasterRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN TRY	
   BEGIN TRANSACTION
		BEGIN
		DELETE FROM sIp.tStockItemPlanning WHERE StockItemId=@rId
		DELETE FROM sProcurement.tStockBatch WHERE StockItemId=@rId
		DELETE FROM sIp.tStockItemPurchaseUom where StockItemId = @rId
		DELETE FROM sIp.tItemStandardPriceLog where StockItemId=@rId
		
		SELECT 1 AS Result
	END
	  COMMIT TRANSACTION
      END TRY
         
      BEGIN CATCH
	  ROLLBACK TRANSACTION
	 SELECT -1 AS RESULT
	  END CATCH

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemMasterSearchDataGet]
	
	@rLocationId int ,
	@rCurrentAlphabet nvarchar(10) 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		 
	SELECT
			Id,
			Code,
			Title from sIp.tStockItemMaster 
	   
	  WHERE  
		 ((Title Like @rCurrentAlphabet + '%') OR (ISNULL(@rCurrentAlphabet,'')=''))
	   AND ((LocationId = @rLocationId) OR (ISNULL(@rLocationId,0)=0)) 

	  
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemPlanningAdd]
	
	@rStockItemPlanningId int,
	@rStockItemId int,
	@rMaximumInventory decimal(12,2), 
	@rReorderPoint decimal(12,2),
	@rSafetyStock decimal(12,2),
	@rStandardPrice decimal(22,6),
	@rLastPurchasePrice decimal(22,6),
	@rWeightedAverageCost decimal(22,6),
	@rStoreLocationId int,
	@rOrgId int,
	@rReorderQuantity decimal(12,2)=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		--BEGIN TRY	
  -- BEGIN TRANSACTION

  --  IF(@rStockItemPlanningId = 0)
  --  BEGIN
	DECLARE @lNextNumber BIGINT     
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgId, 'sIp.tStockItemPlanning',@lNextNumber = @lNextNumber output

	INSERT INTO sIp.tStockItemPlanning
		(
			Id,
			StockItemId,
			MaximumInventory,
			ReorderPoint,
			SafetyStock,
			StandardPrice,
			LastPurchasePrice,
			WeightedAverageCost,
			StoreLocationId,
			OrgGroupId,
			ReOrderQuantity
		)
	VALUES
		(
			@lNextNumber,
			@rStockItemId,
			@rMaximumInventory,
			@rReorderPoint,
			@rSafetyStock,
			@rStandardPrice,
			@rLastPurchasePrice,
			@rWeightedAverageCost,
			@rStoreLocationId,
			@rOrgId,
			@rReorderQuantity
		)	
			SET @rStockItemId = @lNextNumber
	--END
	-- ELSE
	-- BEGIN
	--  SET @lNextNumber = @rStockItemPlanningId 
	--  UPDATE  sIp.tStockItemPlanning
	--   SET	     
	--      MaximumInventory=@rMaximumInventory,
	--      ReorderPoint=@rReorderPoint,
	--      SafetyStock=@rSafetyStock,
	--      StandardPrice=@rStandardPrice
	--      --LastPurchasePrice=@rLastPurchasePrice,
	--      --WeightedAverageCost=@rWeightedAverageCost
	           	    
	--    WHERE Id=@rStockItemPlanningId
	--  END 
	----SELECT @lNextNumber AS Result
  
	--  COMMIT TRANSACTION
 --        END TRY
         
 --       BEGIN CATCH
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS RESULT
	--    END CATCH	
END


/****** Object:  StoredProcedure [sIp].[pStockItemPlanningModify]    Script Date: 07/09/2013 16:24:14 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sIp].[pStockItemPlanningGet]
	
	@rOrgGroupId [smallint], 
	@rStockItemId [int] = 0,
	@rStockItemCode [nvarchar](20) = '',
	@rStockItemName [nvarchar](50) = '',
	@rLocationId int =0,
	@rStorelocation int=0, 
	@rMainGroup int=0,
	@rSubGroup int=0,
	@rItemCatagory int=0,
	@rUserId bigint=0 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
   SET @rStockItemName = sCommon.fSearchStringGet(@rStockItemName)
    SET @rStockItemCode = sCommon.fSearchStringGet(@rStockItemCode)
				SELECT 
					 SIP.Id,
					SIP.StockItemId,
					SIP.StoreLocationId,
					ISNULL(SLM.Title,'') AS StoreLocationName,	
					SIM.Code AS StockItemCode,
					SIM.Title AS StockItemName,
					ISNULL(SIP.LastPurchasePrice,0) AS LastPurchasePrice,
					ISNULL(SIP.WeightedAverageCost,0) AS WeightedAverageCost,
					ISNULL(SIP.StandardPrice,0) AS StandardPrice,
					ISNULL(SIP.MaximumInventory,0) AS MaximumInventory,
					ISNULL(SIP.ReOrderPoint,0) AS ReOrderPoint ,
					
					--SUOM.Title AS UOM,
			 
					ISNULL(SIP.SafetyStock,0) AS SafetyStock,
					ISNULL(SIP.ReOrderQuantity,0) As ReOrderQuantity
				From sIp.tStockItemPlanning SIP
				Left join 	sIp.tStockItemMaster SIM on SIM.Id=StockItemId
				Left join   sIp.tStoreLocationMaster SLM ON	SLM.Id = SIP.StoreLocationId
				INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId		
				--INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id		
				INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
				INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId														
					
				WHERE  ((SLM.LocationId = @rLocationId) OR (@rLocationId = 0))
				AND ((SLM.Id = @rStorelocation) OR (@rStorelocation = 0))
				--AND    ((SB.StockItemId = @rStockItemId) OR (@rStockItemId = 0))				 
				--AND    ((SIM.Code IN (SELECT item FROM  sCommon.fnsplit(@rStockItemCode,','))) OR (ISNULL(@rStockItemCode, '') = ''))
				AND     SIM.OrgGRoupId = @rOrgGroupId
				AND ((IMGM.Id=@rMainGroup)OR(@rMainGroup=0))
				AND ((ISGM.Id =@rSubGroup)OR (@rSubGroup=0))
				--AND UL.UserId = @rUserId
			    AND ((SIM.Title LIKE @rStockItemName) OR (ISNULL(@rStockItemName, '') = ''))		 
			    AND ((SIM.Code LIKE @rStockItemCode) OR (ISNULL(@rStockItemCode, '') = ''))		 
			   AND ((SIM.StockItemCategoryId=@rItemCatagory) OR (@ritemCatagory=0))
END


/****** Object:  StoredProcedure [sIp].[pStockItemPlanningModify]    Script Date: 07/09/2013 16:24:14 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemPlanningModify]
	
	@rStockItemId int,
	@rMaximumInventory decimal(12,2), 
	@rReorderPoint decimal(12,2),
	@rSafetyStock decimal(12,2),
	@rStandardPrice decimal(22,6),
	@rLastPurchasePrice decimal(22,6),
	@rWeightedAverageCost decimal(22,6),
	@rStoreLocationId int,
	@rReorderQuantity decimal(12,2)=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	  
	  UPDATE  sIp.tStockItemPlanning
	   SET	     
	      MaximumInventory=@rMaximumInventory,
	      ReorderPoint=@rReorderPoint,
	      SafetyStock=@rSafetyStock,
	      StandardPrice=@rStandardPrice,
	      ReOrderQuantity =@rReorderQuantity
	      --LastPurchasePrice=@rLastPurchasePrice,
	      --WeightedAverageCost=@rWeightedAverageCost
	           	    
	    WHERE StockItemId=@rStockItemId AND StoreLocationId=@rStoreLocationId
	  
	--SELECT @lNextNumber AS Result
  
	 -- COMMIT TRANSACTION
  --       END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END




/****** Object:  StoredProcedure [sIp].[pWeightedAverageCostLogAdd]    Script Date: 07/09/2013 16:14:04 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemPurchaseUomAdd]
   
    @rOrgGroupId int,
	@rStockItemId [int],
	@rStockUomId [int],
	@rConversionFactor [decimal](12, 2),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
 

	 EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sIp.tStockItemPurchaseUom',@lNextNumber = @lNextNumber output

	INSERT INTO sIp.tStockItemPurchaseUom
		(
			Id,
			StockItemId,
			StockUomId,
			ConversionFactor,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rStockItemId,
			@rStockUomId,
			@rConversionFactor,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
		--SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemPurchaseUomGet]
	@rIsWildCardSearch [bit] = 1,
	@rStockItemId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT SIPOUM.Id,
			SIPOUM.StockItemId,
			SIPOUM.StockUomId,
			SIPOUM.ConversionFactor,
			SIPOUM.IsObsolete,
			SIPOUM.CreatedUserId,
			SIPOUM.CreatedDateTime,
			SIPOUM.UpdatedUserId,
			SIPOUM.UpdatedDateTime
			,SUOM.TITLE  AS Title 
	   FROM sIp.tStockItemPurchaseUom  SIPOUM
  INNER JOIN  sIp.tStockItemMaster SIM
   ON  SIPOUM.StockItemId = SIM.Id AND SIPOUM.IsObsolete = 0 
	INNER JOIN   sFinanceCommon.tStockUomMaster SUOM 
    ON  SIPOUM.StockUomId = SUOM.Id  	   
	 WHERE ((SIPOUM.StockItemId = @rStockItemId)) AND SIPOUM.IsObsolete = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemPurchaseUomGetlist]
	@rOrgId Int,
	@rIsWildCardSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
IF    @rIsWildCardSearch = 1
BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	 -- SELECT	0 AS ID, 
		--		0 AS StockItemId, 
		--		Id  AS StockUomId,
		--		0 AS ConversionFactor, 
		--		IsObsolete,
		--		CreatedUserId, 
		--		CreatedDateTime,
		--		UpdatedUserId, 
		--		UpdatedDateTime,
		--		TITLE  AS Title, 
		--		Code 
		--FROM 
		--		sFinanceCommon.tStockUomMaster SUOM 		
		--WHERE 
		--		SUOM.IsObsolete = 0
		--		AND OrgId = @rOrgId

		SELECT	0 AS ID, 
				0 AS StockItemId, 
				0 AS StockUomId,
				0 AS ConversionFactor, 
				0 AS IsObsolete,
				0 AS CreatedUserId, 
				0 AS CreatedDateTime,
				0 AS UpdatedUserId, 
				0 AS UpdatedDateTime,
				0 AS Title, 
				0 AS Code 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemPurchaseUomModify]
	@rId [int],
	@rStockItemId [int],
	@rStockUomId [int],
	@rConversionFactor [decimal](12, 2),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 
	 UPDATE sIp.tStockItemPurchaseUom
		SET 
			StockItemId = @rStockItemId,
			StockUomId = @rStockUomId,
			ConversionFactor = @rConversionFactor,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemPurchaseUomRemove]
	@rId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sIp.tStockItemPurchaseUom
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemTotalBinGet]
	@rIsWildCardSearch [bit] = 1,
	@rStockItemId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
SELECT Bin.Title, Stbin.Id, Stbin.StockItemId, Stbin.binId, Store.ID   AS LocationId,   Stbin.CreatedUserId


FROM sIp.tStockItembin Stbin INNER JOIN sIp.tBinMaster Bin
ON Stbin.BINID = BIN.Id  INNER JOIN sIp.tStoreLocationMaster Store
ON Store.Id = Bin.StorelocationId   
	 WHERE ((Stbin.StockItemId = @rStockItemId)) AND Stbin.IsObsolete = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemTypeMasterGet]
	@rId [smallint] = 0,
	@rCode [nvarchar](10) = '',
	@rTitle [nvarchar](50) = '',
	@rIsWildCardSearch [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
BEGIN

	 SELECT SIT.Id,
			SIT.Code,
			SIT.Title,
			SIT.IsObsolete,		
			
			SIT.AccrualAccountId,
			AAM.Code AccrualAccountCode,	
			
				
				
			SIT.CogsAccountId,
			COGAM.Code CogsAccountCode,	
					
			SIT.ConsumptionAccountId,
			CAM.Code ConsumptionAccountCode,
			
			SIT.InventoryAccountId,
			IVAM.Code InventoryAccountCode,
			
			SIT.PriceAdjustmentAccountId,
			PAAM.Code PriceAdjustmentAccountCode,
			
			SIT.WriteOffAccountId,
			WOAM.Code WriteOffAccountCode
			
	   FROM sIp.tStockItemTypeMaster SIT
	   INNER JOIN sAccounting.tAccountMaster AAM
					ON SIT.AccrualAccountId = AAM.Id
	   INNER JOIN sAccounting.tAccountMaster COGAM
					ON SIT.CogsAccountId = COGAM.Id
	   INNER JOIN sAccounting.tAccountMaster CAM
					ON SIT.ConsumptionAccountId = CAM.Id
	   INNER JOIN sAccounting.tAccountMaster IVAM
					ON SIT.InventoryAccountId = IVAM.Id
	   INNER JOIN sAccounting.tAccountMaster PAAM
					ON SIT.PriceAdjustmentAccountId = PAAM.Id
	   INNER JOIN sAccounting.tAccountMaster WOAM
					ON SIT.WriteOffAccountId = WOAM.Id					
	  WHERE ((SIT.Id = @rId) OR (@rId = 0))
	   AND ((SIT.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND ((SIT.Title LIKE @rTitle ) OR (ISNULL(@rTitle, '') = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockItemTypeMasterRemove]
	@rId [smallint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sIP.tStockItemTypeMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
	  
	  SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStockStatusGet]
	  @rOrgGroupId [int],
	  @rCode [nvarchar](50) = '',	 
	  @rStoreLocationId [int]=0,
	  @rItemMainGroupId int,
	  @rItemSubGroupId int,
	  @rItemCatagory int,
	  @rItemName nvarchar(100)='',
	  @rVendorId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
   SET @rItemName = sCommon.fSearchStringGet(@rItemName)
      SET @rCode = sCommon.fSearchStringGet(@rCode)
	Select 
		SLM.Title AS StoreLocation,
		SM.Code AS StockItemCode,
		SM.Title AS StockItemTitle,
		SUOM.Title As UOM,
		SIP.MaximumInventory,
		SIP.ReOrderPoint,
		SIP.ReOrderQuantity,
		SIP.SafetyStock,
		SM.Id As StockItemId,
		(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
			WHERE SB.StockItemId = SM.Id 
			AND ((SB.StorelocationId = @rStorelocationId) OR (@rStorelocationId = 0))
		--AND UL1.UserId = @rUserId
		) AS Quantity,
		SM.VendorID,
		SM.IsBatchWiseTracking
			
	From
		 sIp.tStockItemMaster SM
		 INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SM.IssueStockUomId
		 LEFT JOIN sIp.tStockItemPlanning SIP ON SM.Id = SIP.StockItemId
		 INNER JOIN sIp.tStoreLocationMaster SLM ON	SLM.Id = SM.StoreLocationId
		 INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SM.ItemSubGroupId
		 INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
	Where
		SM.OrgGroupId =@rOrgGroupId
		AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
		--AND ((SM.Code IN (SELECT item FROM  sCommon.fnsplit(@rCode,','))) OR (ISNULL(@rCode, '') = ''))
		AND ((IMGM.Id=@rItemMainGroupId)OR(@rItemMainGroupId=0))
		AND ((ISGM.Id =@rItemSubGroupId)OR (@rItemSubGroupId=0))
		AND ((SM.StockItemCategoryId=@rItemCatagory) OR (@ritemCatagory=0))
		AND ((SM.Title LIKE @rItemName) OR (ISNULL(@rItemName, '') = ''))
		 AND ((SM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
		 AND ((SM.VendorID=@rVendorId) OR (@rVendorId=0))	
		 AND SM.IsObsolete = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sIp].[pStockStoreLocationDelete]

		@rStoreLocationId int,
		@rOrgId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
		BEGIN
			
			-- Update Charge Receipt Detail
			UPDATE  CRD
				SET CRD.StockIssueId=0
				FROM sFee.tChargeReceiptDetail CRD 
				INNER JOIN [sProcurement].[tStockIssue] SI ON SI.Id=CRD.StockIssueId
				where FromStoreLocationId=@rStoreLocationId

			-- Detete Stock Adjustment Batch]
			DELETE SAB FROM [sProcurement].[tStockAdjustmentBatch] AS SAB
			INNER JOIN [sProcurement].[tStockAdjustmentDetail] sad ON SAD.id=SAB.StockAdjustmentDetailId
			WHERE SAD.StoreLocationId=@rStoreLocationId

			-- Detete Stock Adjustment Detail
			DELETE FROM  [sProcurement].[tStockAdjustmentDetail] WHERE StoreLocationId=@rStoreLocationId
			
			-- Detete Stock Adjustment
			DELETE FROM  [sProcurement].[tStockAdjustment] WHERE FromStoreLocationId=@rStoreLocationId

			-- Detete Stock Inward Batch
			DELETE SIB FROM [sProcurement].[tStockInwardBatch] SIB
			INNER JOIN [sProcurement].[tStockInwardDetail] SI ON SI.Id=SIB.StockInwardDetailId
			INNER JOIN [sIp].[tStockItemMaster] SM ON SM.Id=SI.StockItemId
			where SM.StoreLocationId=@rStoreLocationId

			-- Detete Stock Inward Detail
			DELETE SI FROM [sProcurement].[tStockInwardDetail] SI
			INNER JOIN [sIp].[tStockItemMaster] SM ON SM.Id=SI.StockItemId
			WHERE SM.StoreLocationId=@rStoreLocationId

			-- Detete Stock Inward Request Detail
			DELETE SIRD FROM [sProcurement].[tStockInwardRequestDetail] SIRD
			INNER JOIN [sProcurement].[tStockInwardRequest] SIR ON SIR.Id=SIRD.StockInwardRequestId
			WHERE SIR.FromStoreLocationId=@rStoreLocationId
			
			-- Detete Stock Inward Return Batch
			DELETE SIRB FROM [sProcurement].[tStockInwardReturnBatch] SIRB
			INNER JOIN [sProcurement].[tStockInwardReturn] SIR ON SIRB.StockInwardReturnId=SIR.Id
			where SIR.FromStoreLocationId=@rStoreLocationId

			-- Detete Stock Inward Return
			DELETE  FROM [sProcurement].[tStockInwardReturn] WHERE FromStoreLocationId=@rStoreLocationId
			
			-- Detete Stock Inward Request]
			DELETE FROM [sProcurement].[tStockInwardRequest] WHERE FromStoreLocationId=@rStoreLocationId
			
			-- Detete Stock Inward
			DELETE FROM [sProcurement].[tStockInward] WHERE ToStoreLocationId=@rStoreLocationId

			-- Detete Stock Issue Request Detail
			DELETE SIRD FROM [sProcurement].[tStockIssueRequestDetail] SIRD 
			INNER JOIN [sProcurement].[tStockIssueRequest] SIR ON SIR.Id=SIRD.StockIssueRequestId
			WHERE SIR.FromStoreLocationId=@rStoreLocationId
			
			-- Detete Stock Issue Request
			DELETE FROM  [sProcurement].[tStockIssueRequest] WHERE FromStoreLocationId=@rStoreLocationId
			
			-- Detete Stock Issue Return Batch
			DELETE SIRB FROM [sProcurement].[tStockIssueReturnBatch] SIRB
			INNER JOIN [sProcurement].[tStockIssueBatch] SIB on SIB.id=SIRB.StockIssueBatchId
			INNER JOIN [sProcurement].[tStockIssueDetail] SID on SID.id=SIB.StockIssueDetailId
			INNER JOIN [sProcurement].[tStockIssue] SI ON SI.Id=SID.StockIssueId
			WHERE SI.FromStoreLocationId=@rStoreLocationId
			
			-- Detete Stock Issue Batch
			DELETE SIB FROM [sProcurement].[tStockIssueBatch] SIB
			INNER JOIN [sProcurement].[tStockIssueDetail] SID on SID.id=SIB.StockIssueDetailId
			INNER JOIN [sProcurement].[tStockIssue] SI ON SI.Id=SID.StockIssueId
			where SI.FromStoreLocationId=@rStoreLocationId

			-- Detete Stock Issue Detail
			DELETE SID FROM [sProcurement].[tStockIssueDetail] SID
			INNER JOIN [sProcurement].[tStockIssue] SI ON SI.Id=SID.StockIssueId
			WHERE SI.FromStoreLocationId=@rStoreLocationId

			-- Detete Other Stock Issue Batch
			DELETE OSIB FROM [sProcurement].[tOtherStockIssueBatch] OSIB 
			INNER JOIN [sProcurement].[tOtherStockIssue] OSI ON OSIB.OtherStockIssueId=OSI.Id
			WHERE OSI.StoreLocationId=@rStoreLocationId
			
			-- Detete Other Stock Issue
			DELETE FROM [sProcurement].[tOtherStockIssue] WHERE StoreLocationId=@rStoreLocationId
			
			-- Detete Stock Issue Return
			DELETE FROM [sProcurement].[tStockIssueReturn] WHERE ToStoreLocationId=@rStoreLocationId

			-- Detete Stock Issue
			DELETE  FROM [sProcurement].[tStockIssue] WHERE FromStoreLocationId=@rStoreLocationId

			-- Detete Stock Transfer Batch
			DELETE SIB FROM [sProcurement].[tStockTransferBatch] SIB
			INNER JOIN [sProcurement].[tStockTransferDetail] STD ON STD.id=SIB.StockTransferDetailId
			INNER JOIN [sProcurement].[tStockTransfer] ST ON ST.Id=STD.StockItemId
			WHERE ST.FromStoreLocationId=@rStoreLocationId OR ST.ToStoreLocationId=@rStoreLocationId
			
			-- Detete Stock Transfer Detail
			DELETE STD FROM [sProcurement].[tStockTransferDetail] STD
			INNER JOIN [sProcurement].[tStockTransfer] ST ON ST.Id=STD.StockItemId
			WHERE ST.FromStoreLocationId=@rStoreLocationId OR ST.ToStoreLocationId=@rStoreLocationId
			
			-- Detete Stock Transfer
			DELETE FROM [sProcurement].[tStockTransfer] 
			WHERE FromStoreLocationId=@rStoreLocationId OR ToStoreLocationId=@rStoreLocationId

			-- Detete Stock Transfer Request Detail
			DELETE STRD FROM [sProcurement].[tStockTransferRequestDetail] STRD
			INNER JOIN [sProcurement].[tStockTransferRequest] STR ON STR.Id=STRD.StockTransferRequestId
			WHERE STR.FromStoreLocationId=@rStoreLocationId OR STR.ToStoreLocationId=@rStoreLocationId

			-- Detete Stock Transfer Request
			DELETE FROM [sProcurement].[tStockTransferRequest]
			WHERE FromStoreLocationId=@rStoreLocationId OR ToStoreLocationId=@rStoreLocationId

			-- Detete Stock Stock Reset Batch
			DELETE SRB FROM [sProcurement].[tStockResetBatch] SRB
			INNER JOIN [sProcurement].[tStockReset] SR ON SR.Id=SRB.StockResetId
			WHERE SR.ToStoreLocationId=@rStoreLocationId
			
			-- Detete Stock Stock Reset
			DELETE FROM [sProcurement].[tStockReset] WHERE ToStoreLocationId=@rStoreLocationId

			-- Detete Stock Issue
			DELETE FROM [sIp].[tStockItemBin]  WHERE StoreLocationId=@rStoreLocationId

			-- Detete Stock Item Planning
			DELETE FROM [sIp].[tStockItemPlanning] WHERE StoreLocationId=@rStoreLocationId

			-- Detete Weighted Average Cost Log
			DELETE FROM [sIp].[tWeightedAverageCostLog] WHERE StoreLocationId=@rStoreLocationId

			-- Detete Other Stock Batch
			DELETE OSB FROM [sProcurement].[tOtherStockBatch] OSB
			INNER JOIN [sProcurement].[tStockBatch] SB on SB.id=OSB.StockBatchId
			INNER JOIN [sIp].[tStockItemMaster] SM ON SM.Id=SB.StockItemId
			WHERE SM.StoreLocationId=@rStoreLocationId
			
			-- Detete Other Stock Location Master
			DELETE FROM [sProcurement].[tOtherStockLocationMaster] WHERE StoreLocationId=@rStoreLocationId
			
			-- Detete Stock Batch
			DELETE FROM [sProcurement].[tStockBatch] where StoreLocationId=@rStoreLocationId

			-- Detete Stock Item Purchase Uom
			DELETE SIPU FROM [sIp].[tStockItemPurchaseUom] SIPU
			INNER JOIN [sIp].[tStockItemMaster] SM ON SM.Id=SIPU.StockItemId
			WHERE SM.StoreLocationId=@rStoreLocationId

			-- Detete Stock Item Master
			DELETE FROM sIp.tStockItemMaster WHERE StoreLocationId=@rStoreLocationId

			-- Detete Bin Master
			DELETE FROM [sIp].[tBinMaster] WHERE StoreLocationId=@rStoreLocationId
			
			-- Detete Item Main Group Master
			DELETE FROM [sIp].[tItemMainGroupMaster] WHERE StoreLocationId=@rStoreLocationId
			
			-- Detete Stock Item Category Master
			DELETE FROM [sIp].[tStockItemCategoryMaster] WHERE StoreLocationId=@rStoreLocationId

			-- Detete User Access
			DELETE UA FROM sSecurity.tUserAccess UA WHERE UA.SourceId =@rStoreLocationId AND UA.SourceTypeId = 1014
			
			-- Detete Store Location Master
			DELETE FROM [sIp].[tStoreLocationMaster] WHERE Id=@rStoreLocationId
		END		
		COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStoreLocationMasterAdd]
	@rTitle [nvarchar](100),
	@rCreatedUserId [bigint],
	@rIsObsolete [bit],
	@rCode [nvarchar](100),
	@rOrgGroupId int,
	@rIsBatchwiseTracking bit = 0,
	@rDepositHeadId int=0,
	@rDepositExpenseTypeId int=0,
	@rReportId smallint=0
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sIp.tStoreLocationMaster WHERE UPPER(Title) = UPPER(@rTitle)  AND OrgGroupId = @rOrgGroupId )


BEGIN

	DECLARE @StockItemId INT
	DECLARE @lCount INT 
	DECLARE @rStockBatchId INT
	DECLARE @lNextNumber INT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tStoreLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tStoreLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	

	INSERT INTO sIp.tStoreLocationMaster
		(
			Id,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			UpdatedUserId,
			UpdatedDateTime,
			Code,
			LocationId, 
			OrgGroupId,
		 	IsBatchwiseTracking,
			DepositHeadId,
			DepositExpenseTypeId,
			ReportId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCode,
			@lNextNumber,
			@rOrgGroupId,
			@rIsBatchwiseTracking,
			@rDepositHeadId,
			@rDepositExpenseTypeId,
			@rReportId
			 
		)
		
	  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   1014
		   ,@lNextNumber
		   ,@rCreatedUserId		
		
--CREATE TABLE #tmpStockItemMaster
--(
--	Id bigint identity,
--	StockItemId int
--)	 
		 
--INSERT INTO #tmpStockItemMaster
--SELECT Id FROM sIP.tStockItemMaster WHERE LocationId = @rLocationId

--SELECT @lCount =  COUNT(Id) FROM #tmpStockItemMaster

--WHILE @lCount > 0 
-- 	BEGIN

-- 		SELECT  @StockItemId = StockItemId 
-- 	   FROM #tmpStockItemMaster WHERE Id = @lCount	
	
-- 	EXECUTE sProcurement.pStockBatchAdd @rOrgGroupId,@lNextNumber,@StockItemId,null,null,0,@rCreatedUserId ,  @rStockBatchId
--		SET @lCount = @lCount - 1
--	END	
 	
	--EXECUTE	sIp.pStockItemPurchaseUomAdd @rOrgId,@lNextNumber,@rIssueStockUomId,1,0,@rCreatedUserId	
	----EXEC [sIp].[pItemStandardPriceLogAdd] @rOrgId,@lNextNumber, @rStandardPrice, @rCreatedUserId
 --   SELECT @lNextNumber AS RESULT
    
    
 --END
		
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStoreLocationMasterGet]
	@rId [int] = 0,
	@rTitle [nvarchar](20) = '',
	@rCode [nvarchar](100) = '',
	@rLocationId [int] = 0,
	@rOrgGroupId int,
	@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
		
	


	 SELECT SLM.Id,
			SLM.Title,
			SLM.CreatedUserId,
			SLM.CreatedDateTime,
			SLM.IsObsolete,
			SLM.UpdatedUserId,
			SLM.UpdatedDateTime,
			SLM.Code,		
			SLM.OrgGroupId,
			OM.Title AS OrgGroupName,
			SLM.Title AS StoreLocationName,
			ISNULL(SLM.IsBatchwiseTracking,0) AS IsBatchwiseTracking,
			Isnull(SLM.DepositHeadId,0) as DepositHeadId,
			Isnull(SLM.DepositExpenseTypeId,0) as DepositExpenseTypeId,
			Isnull(SLM.ReportId,0) as ReportId

	   FROM sIp.tStoreLocationMaster SLM 	   
	   INNER JOIN sSetup.tOrgGroupMaster OM ON OM.Id=SLM.OrgGroupId
	  WHERE ((SLM.Id = @rId) OR (@rId = 0))
	   AND ((SLM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((SLM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))	  
	   AND  (SLM.OrgGroupId = @rOrgGroupId)  
	   --AND SLM.IsObsolete = 0
END



/****** Object:  StoredProcedure [sExamination].[pIssueReturnDataGet]    Script Date: 06/15/2013 16:42:58 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStoreLocationMasterModify]
	@rId [int],
	@rTitle [nvarchar](100),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rCode [nvarchar](100),	
	@rOrgGroupId int,
	@rIsBatchwiseTracking bit = 0,
	@rDepositHeadId int=0,
	@rDepositExpenseTypeId int=0,
	@rReportId smallint=0


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
IF NOT EXISTS (SELECT 1 FROM sIP.tStoreLocationMaster WHERE UPPER(Title) = UPPER(@rTitle) AND Id  <> @rId AND OrgGroupId = @rOrgGroupId)
BEGIN

	 UPDATE sIP.tStoreLocationMaster
		SET 
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
		    Code = @rCode,
		    IsBatchwiseTracking = @rIsBatchwiseTracking,
			DepositHeadId=@rDepositHeadId,
			DepositExpenseTypeId=@rDepositExpenseTypeId,
			ReportId=@rReportId
			
	  WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	  
	  
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pStoreLocationMasterRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
  IF(@rId != 0)
    BEGIN 
	 UPDATE sIp.tStoreLocationMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
	 
	 SELECT 1 AS Result 
	  
	END
	 ELSE
	   SELECT 0 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pTransferRecieptWACModify]
	
	@rItemSourceId int,
	@rForStoreLocationId int,
	@rWeightedAverageCost decimal(22,6)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	  
	  UPDATE  sIp.tStockItemPlanning
	   SET	     
	      WeightedAverageCost = @rWeightedAverageCost
	           	    
	    WHERE StockItemId=@rItemSourceId AND StoreLocationId=@rForStoreLocationId
	  
	  SELECT 1 AS Result
	--SELECT @lNextNumber AS Result
  
	 -- COMMIT TRANSACTION
  --       END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END




/****** Object:  StoredProcedure [sProcurement].[pRptFirstAidIssueList]    Script Date: 07/09/2013 16:30:08 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sIp].[pUniformItemAdd]
	 
        @rId int,
		@rCode nvarchar(100),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rCreatedUserId bigint,
		@rOrgGroupId int,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
	
		If Exists(select Id from sIp.tUniformItem where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	 
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tUniformItem', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sIp.tUniformItem
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			 OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			 @rOrgGroupId
		)
		    SELECT 1 AS Result
	
		        
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sIp.tUniformItem
	    SET
			Code = @rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() ,
			 OrgGroupId = @rOrgGroupId
	      
	      
	      WHERE Id = @rId
	      SELECT 101 AS Result
	
		--COMMIT TRANSACTION
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pUniformMasterGet]
	
	@rId int=0,
	@rCode nvarchar(100) ,
	@rTitle nvarchar(100),
	@rOrgGroupId int 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		 
	SELECT
			Id,
			Code,
			Title,
			IsObsolete,
			OrgGroupId
			 
	from sIp.tUniformItem
	   
	  WHERE  
			((Id = @rId) OR (@rId =0))
		 AND ((Title Like @rTitle + '%') OR (ISNULL(@rTitle,'')=''))
		AND ((Code = @rCode) OR (ISNULL(@rCode,'')='')) 
		AND OrgGroupId = @rOrgGroupId
	  
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pValidateImportStockItem]
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rLocationId int
	 
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),             
        @1ReturnCode int = 1,
        @1ExistStockItemCode nvarchar(400) = '' 
       
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         
         
         @lCode = Code       
         
     FROM #tTable1 WHERE Id = @lCount    
 
    IF Exists ((select 1 from sIp.tStockItemMaster SM where SM.Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND LocationId = @rLocationId))         
          BEGIN
  			    SET @1ExistStockItemCode = @1ExistStockItemCode + @lCode + ','
	       END	       
	       
     SET @lCount = @lCount - 1	
   END		
		Select @1ExistStockItemCode AS StockItemCode
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pWeightedAverageCostLogAdd]
	@rOrgId [int],
	@rSourceTypeId [smallint],
	@rSourceId [bigint],
	@rItemSourceTypeId [smallint],
	@rItemSourceId [bigint],
	@rQuantity [decimal](12, 2),
	@rValue [decimal](22, 6),
	@rIsReceipt [bit],
	@rClosingQuantity [decimal](12, 2),
	@rClosingValue [decimal](22, 6),
	@rWeightedAverageCost [decimal](22, 6),
	@rCreatedUserId [bigint],
	@rStoreLocationId [int]  ,
	@rStoreLocationClosingQuantity [decimal](12, 2) = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 

BEGIN

 --BEGIN TRY	
	       --BEGIN TRANSACTION
	IF EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE ItemSourceId = @rItemSourceId AND StoreLocationId = @rStoreLocationId)
	       BEGIN
		IF (@rClosingQuantity < 0)
		BEGIN
			--RAISERROR('-101', 15, 106)
			Select -102 AS RESULT
			RETURN
		END
		END
	DECLARE @lNextNumber BIGINT
	DECLARE @lLocationId INT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tWeightedAverageCostLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	--Added for Issue HIMS - 6338
	 EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] 1001, 'sIp.tWeightedAverageCostLog',@lNextNumber = @lNextNumber output
	
	IF @rStoreLocationId = 0 
	BEGIN
		SET @rStoreLocationId = 1
	END
	
	--SELECT @lLocationId = LocationId FROM sIp.tStoreLocationMaster WHERE ID = @rStoreLocationId
	 SET @lLocationId = 0
 IF NOT EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId AND StoreLocationID = @rStoreLocationId)
  BEGIN	 
	-- END of addition
	INSERT INTO sIp.tWeightedAverageCostLog
		(
			 
			SourceTypeId, 
			SourceId, 
			ItemSourceTypeId, 
			ItemSourceId, 
			Quantity, 
			Value, 
			IsReceipt, 
			ClosingQuantity, 
			ClosingValue, 
			WeightedAverageCost, 
			CreatedUserId, 
			CreatedDateTime, 
			StoreLocationId, 
			StoreLocationClosingQuantity,
			OrgGroupId,
			LocationId
		)
	VALUES
		(
		 
			@rSourceTypeId, 
			@rSourceId, 
			@rItemSourceTypeId, 
			@rItemSourceId, 
			@rQuantity, 
			@rValue, 
			@rIsReceipt, 
			@rClosingQuantity, 
			@rClosingValue, 
			@rWeightedAverageCost, 
			@rCreatedUserId, 
			sCommon.fGetDate(),
			@rStoreLocationId, 
			@rStoreLocationClosingQuantity,
			@rOrgId,
			@lLocationId
			
		)
	END
		
		IF (@rSourceTypeId = 46 AND @rItemSourceTypeId = 34)
		BEGIN
			UPDATE sip.tStockItemPlanning  
			SET WeightedAverageCost = @rWeightedAverageCost 
			WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
		END
		
		IF (@rSourceTypeId = 1010 AND @rItemSourceTypeId = 34)
		BEGIN
			UPDATE sip.tStockItemPlanning  
			SET WeightedAverageCost = @rWeightedAverageCost 
			WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
		END
 
		SELECT 1 AS RESULT
		-- COMMIT TRANSACTION
  --      END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END




/****** Object:  StoredProcedure [sIp].[pStockItemMasterGet]    Script Date: 07/09/2013 16:14:40 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sIp].[pWeightedAverageCostLogAdd_New]
	@rOrgGroupId [int],
	@rSourceTypeId [smallint],
	@rSourceId [bigint],
	@rItemSourceTypeId [smallint],
	@rItemSourceId [bigint],
	@rQuantity [decimal](12, 2),
	@rValue [decimal](22, 6),
	@rIsReceipt [bit],
	--@rClosingQuantity [decimal](12, 2),
	--@rClosingValue [decimal](22, 6),
	@rWeightedAverageCost [decimal](22, 6)=0,
	@rCreatedUserId [bigint],
	@rStoreLocationId [int]  ,
	@rStoreLocationClosingQuantity [decimal](12, 2) = 0,
	@rPhysicalQuantity decimal(12,2)=0,
	@rItemBatchId int = 0,
	@rItemName nvarchar(200) = '',
	@rLocationId [int],
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 

BEGIN

 --BEGIN TRY	
	       --BEGIN TRANSACTION
	       
	DECLARE @lOldClosingQuantity [decimal](12, 2) = 0
	DECLARE @lOldClosingValue [decimal](12, 2) = 0
	DECLARE @lOldWeightedAverageCost [decimal](12, 2) = 0
	DECLARE @lNewClosingQuantity [decimal](12, 2) = 0
	DECLARE @lNewClosingValue [decimal](12, 2) = 0
	DECLARE @lNewWeightedAverageCost [decimal](12, 2)= 0	
	DECLARE @lStockBatchQuantity [decimal](12, 2) = 0
	       
	SELECT @lStockBatchQuantity = SB.AvailableQuantity FROM sProcurement.tStockBatch SB  
	WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId AND SB.StoreLocationId =@rStoreLocationId       
	       
	if @rSourceTypeId=50 -- Stock Adjustment
	BEGIN 
		SET @lNewClosingQuantity = ISNULL(@rPhysicalQuantity,0) 
		SET @lNewClosingValue =   ISNULL(@rPhysicalQuantity,0) * @rWeightedAverageCost
		SET @lNewWeightedAverageCost = @rWeightedAverageCost
	END
	else if @rSourceTypeId=2028 --  Stock reset
	BEGIN
	
		SET @lNewClosingQuantity = ISNULL(@rPhysicalQuantity,0) 
		SET @lNewClosingValue =   ISNULL(@rPhysicalQuantity,0) * @rValue
		SET @lNewWeightedAverageCost = @rValue
	    SET @lStockBatchQuantity = @rPhysicalQuantity

	END
	ELSE
	BEGIN
		SELECT TOP 1 @lOldClosingQuantity = ClosingQuantity,@lOldClosingValue = ClosingValue,
		@lOldWeightedAverageCost = WeightedAverageCost FROM sIp.tWeightedAverageCostLog
		WHERE ItemSourceId = @rItemSourceId AND StoreLocationId = @rStoreLocationId ORDER BY ID Desc	 
		IF (@rIsReceipt = 1)
		BEGIN
			SET @lNewClosingQuantity = ISNULL(@lOldClosingQuantity,0) + @rQuantity
			SET @lNewClosingValue =   ISNULL(@lOldClosingValue,0) + @rValue
			SET @lNewWeightedAverageCost = @lNewClosingValue / @lNewClosingQuantity
			SET @lStockBatchQuantity = @lStockBatchQuantity + @rQuantity
		END
		ELSE
		BEGIN
			SET @lNewClosingQuantity = ISNULL(@lOldClosingQuantity,0) - @rQuantity
			SET @lNewClosingValue =   ISNULL(@lOldClosingValue,0) - @rValue
			SET @lNewWeightedAverageCost = @lOldWeightedAverageCost		
			SET @lStockBatchQuantity = @lStockBatchQuantity - @rQuantity
		END
	END      
	DECLARE @lNextNumber BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tWeightedAverageCostLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	IF NOT EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId
	AND StoreLocationID = @rStoreLocationId)
	BEGIN
		INSERT INTO sIp.tWeightedAverageCostLog
		(
			 SourceTypeId,SourceId,ItemSourceTypeId,ItemSourceId,Quantity,Value,IsReceipt,
			ClosingQuantity,ClosingValue,WeightedAverageCost,CreatedUserId,CreatedDateTime,StoreLocationId,
			StoreLocationClosingQuantity,OrgGroupId,LocationId
		)
		VALUES
		(
			@rSourceTypeId,@rSourceId,@rItemSourceTypeId,@rItemSourceId,@rQuantity,@rValue,@rIsReceipt,
			@lNewClosingQuantity,@lNewClosingValue,@lNewWeightedAverageCost,@rCreatedUserId,sCommon.fGetDate(),
			@rStoreLocationId,@rStoreLocationClosingQuantity,@rOrgGroupId,@rLocationId
		)
	END
	IF (@rSourceTypeId = 46 AND @rItemSourceTypeId = 34) -- GoodReceiptNotBatch
	BEGIN
		UPDATE sip.tStockItemPlanning  
		SET WeightedAverageCost = @lNewWeightedAverageCost 
		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
	END
	IF (@rSourceTypeId = 1010 AND @rItemSourceTypeId = 34) -- Stock Inward
	BEGIN 
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity + @rQuantity,SB.ItemRate = @rValue
		from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		AND SB.StoreLocationId =@rStoreLocationId
		 
		UPDATE sip.tStockItemPlanning  
		SET WeightedAverageCost = @lNewWeightedAverageCost 
		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
		--select  SB.AvailableQuantity from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		--AND SB.StoreLocationId =@rStoreLocationId
	END
	IF (@rSourceTypeId = 51 OR @rSourceTypeId = 48 ) -- Stock Issue / dispense
	BEGIN
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity - @rQuantity
		from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		AND SB.StoreLocationId =@rStoreLocationId		
	END
	if(@rSourceTypeId = 1013) -- Stock Inward Return
	BEGIN
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity - @rQuantity from sProcurement.tStockBatch SB
		Where SB.Id=@rItemBatchId AND SB.StockItemId= @rItemSourceId And SB.StorelocationID=@rStoreLocationId
	END	 
		IF(@rSourceTypeId = 1012) -- Stock Issue Return
	BEGIN
		Update SB Set SB.AvailableQuantity = SB.AvailableQuantity + @rQuantity from sProcurement.tStockBatch SB
		Where SB.Id=@rItemBatchId AND SB.StockItemId= @rItemSourceId And SB.StorelocationID=@rStoreLocationId
	END	 
	
	  
	 
	IF NOT EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId
	AND StoreLocationID = @rStoreLocationId)
	BEGIN
	 
	--if(@rSourceTypeId != 2028)
	--BEGIN
	 
		INSERT INTO sIp.tWeightedAverageCostLog
		(
			SourceTypeId,SourceId,ItemSourceTypeId,ItemSourceId,Quantity,Value,IsReceipt,
			ClosingQuantity,ClosingValue,WeightedAverageCost,CreatedUserId,CreatedDateTime,StoreLocationId,
			StoreLocationClosingQuantity,OrgGroupId,LocationId
		)
		VALUES
		(
			@rSourceTypeId,@rSourceId,@rItemSourceTypeId,@rItemSourceId,@rQuantity,@rValue,@rIsReceipt,
			@lNewClosingQuantity,@lNewClosingValue,@lNewWeightedAverageCost,@rCreatedUserId,sCommon.fGetDate(),
			@rStoreLocationId,@rStoreLocationClosingQuantity,@rOrgGroupId,@rLocationId
		)
	END
	--else
	--	BEGIN
	 
	-- set @lNewWeightedAverageCost = isnull(@rValue,0)
	-- SET @lNewClosingValue =   (isnull(@rQuantity,0) * isnull(@rValue,0))
	-- INSERT INTO sIp.tWeightedAverageCostLog
	--	(
	--		SourceTypeId,SourceId,ItemSourceTypeId,ItemSourceId,Quantity,Value,IsReceipt,
	--		ClosingQuantity,ClosingValue,WeightedAverageCost,CreatedUserId,CreatedDateTime,StoreLocationId,
	--		StoreLocationClosingQuantity,OrgGroupId,LocationId
	--	)
	--	VALUES
	--	(
	--		@rSourceTypeId,@rSourceId,@rItemSourceTypeId,@rItemSourceId,@rQuantity,@rValue,@rIsReceipt,
	--		@rQuantity,@lNewClosingValue,@lNewWeightedAverageCost,@rCreatedUserId,sCommon.fGetDate(),
	--		@rStoreLocationId,@rStoreLocationClosingQuantity,@rOrgGroupId,@rLocationId
	--	)
	--	END
	--END       
	       
 IF (@rSourceTypeId = 2028 AND @rItemSourceTypeId = 34) -- Stock Reset
	BEGIN 
		
		Update SB Set SB.AvailableQuantity = @rPhysicalQuantity ,SB.ItemRate = @rValue
		from sProcurement.tStockBatch SB WHERE Id = @rItemBatchId AND StockItemId = @rItemSourceId
		AND SB.StoreLocationId =@rStoreLocationId
		
		UPDATE sip.tStockItemPlanning  
		SET WeightedAverageCost = @rValue 
		WHERE StockItemId = @rItemSourceId
		AND StoreLocationId = @rStoreLocationId		
	END
	
	
	       
	--IF EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE ItemSourceId = @rItemSourceId AND StoreLocationId = @rStoreLocationId)
	--       BEGIN
	--	IF (@rClosingQuantity < 0)
	--	BEGIN
	--		--RAISERROR('-101', 15, 106)
	--		Select -102 AS RESULT
	--		RETURN
	--	END
	--	END
	--DECLARE @lNextNumber BIGINT
	--DECLARE @lLocationId INT
	----EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sIp.tWeightedAverageCostLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	----Added for Issue HIMS - 6338
	-- EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] 1001, 'sIp.tWeightedAverageCostLog',@lNextNumber = @lNextNumber output
	
	--IF @rStoreLocationId = 0 
	--BEGIN
	--	SET @rStoreLocationId = 1
	--END
	
	----SELECT @lLocationId = LocationId FROM sIp.tStoreLocationMaster WHERE ID = @rStoreLocationId
	-- SET @lLocationId = 0
 --IF NOT EXISTS (SELECT 1 FROM sIp.tWeightedAverageCostLog WHERE SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId AND StoreLocationID = @rStoreLocationId)
 -- BEGIN	 
	---- END of addition
	--INSERT INTO sIp.tWeightedAverageCostLog
	--	(
	--		Id, 
	--		SourceTypeId, 
	--		SourceId, 
	--		ItemSourceTypeId, 
	--		ItemSourceId, 
	--		Quantity, 
	--		Value, 
	--		IsReceipt, 
	--		ClosingQuantity, 
	--		ClosingValue, 
	--		WeightedAverageCost, 
	--		CreatedUserId, 
	--		CreatedDateTime, 
	--		StoreLocationId, 
	--		StoreLocationClosingQuantity,
	--		OrgGroupId,
	--		LocationId
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		@rSourceTypeId, 
	--		@rSourceId, 
	--		@rItemSourceTypeId, 
	--		@rItemSourceId, 
	--		@rQuantity, 
	--		@rValue, 
	--		@rIsReceipt, 
	--		@rClosingQuantity, 
	--		@rClosingValue, 
	--		@rWeightedAverageCost, 
	--		@rCreatedUserId, 
	--		sCommon.fGetDate(),
	--		@rStoreLocationId, 
	--		@rStoreLocationClosingQuantity,
	--		@rOrgId,
	--		@lLocationId
			
	--	)
	--END
		
	--	IF (@rSourceTypeId = 46 AND @rItemSourceTypeId = 34)
	--	BEGIN
	--		UPDATE sip.tStockItemPlanning  
	--		SET WeightedAverageCost = @rWeightedAverageCost 
	--		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
	--	END
		
	--	IF (@rSourceTypeId = 1010 AND @rItemSourceTypeId = 34)
	--	BEGIN
	--		UPDATE sip.tStockItemPlanning  
	--		SET WeightedAverageCost = @rWeightedAverageCost 
	--		WHERE StockItemId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
	--	END
  
		-- COMMIT TRANSACTION
  --      END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END




/****** Object:  StoredProcedure [sIp].[pStockItemMasterGet]    Script Date: 07/09/2013 16:14:40 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sIp].[pWeightedAverageCostLogGet]
	@rOrgId [int],
	@rItemSourceTypeId [smallint],
	@rItemSourceId [bigint],
	@rStoreLocationId [int],
	@rIsTransferReceiptTransaction bit,
	@rTransferFromStoreLocationId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--DECLARE @lLocationId INT	
--SELECT @lLocationId = LocationId FROM sIp.tStoreLocationMaster WHERE ID = @rStoreLocationId


	DECLARE @lIdForClQty bigInt
	DECLARE @lIdForStoClQty Int
	DECLARE @lSourceTypeId smallInt
	DECLARE @lSourceId bigint
	DECLARE @lItemSourceTypeId smallInt
	DECLARE @lItemSourceId bigint
	DECLARE @lQuantity Decimal(12,2)
	DECLARE @lValue decimal(22,6)
	DECLARE @lIsReceipt bit
	DECLARE @lClosingQuantity Decimal(12,2)
	DECLARE @lClosingValue decimal(22,6)
	DECLARE @lWeightedAverageCost decimal(22,6)
	DECLARE @lCreatedUserId BigInt
	DECLARE @lStoreClosingQuantity Decimal(12,2)
	DECLARE @lStoreLocationId Int
	Declare @lTransferReceiptWAC decimal(22,6)
	Declare @lIsWACLogEntryExists bit=1
	
	SET  @lIdForClQty = 0
	SET  @lIdForStoClQty = 0
	SET  @lSourceTypeId = 0
	SET  @lSourceId = 0
	SET  @lQuantity = 0
	SET  @lValue = 0
	SET  @lIsReceipt = 0
	SET  @lClosingQuantity = 0
	SET  @lClosingValue = 0
	SET  @lWeightedAverageCost = 0
	SET  @lCreatedUserId = 0
	
	SET  @lItemSourceTypeId = @rItemSourceTypeId
	SET  @lItemSourceId = @rItemSourceId	
	SET  @lStoreLocationId = @rStoreLocationId
	
	
	SELECT TOP 1 
		@lIdForClQty = Id, 
		@lSourceTypeId = SourceTypeId, 
		@lSourceId = SourceId, 
		@lItemSourceTypeId = ItemSourceTypeId, 
		@lItemSourceId = ItemSourceId, 
		@lQuantity = Quantity, 
		@lValue = Value, 
		@lIsReceipt = IsReceipt, 
		@lClosingQuantity = ClosingQuantity, 
		@lClosingValue = ClosingValue, 
		@lWeightedAverageCost = WeightedAverageCost, 
		@lCreatedUserId = CreatedUserId
	FROM sIp.tWeightedAverageCostLog 
	WHERE ItemSourceTypeId = @rItemSourceTypeId   AND ItemSourceId = @rItemSourceId
	AND OrgGroupId = @rOrgId
	 --AND LocationId = @lLocationId
	AND StoreLocationId = @rStoreLocationId
	 ORDER BY ID DESC

	
	-- There is no entry in the WAC Log, Fetch the Last Purchase Price AS WAC   
	IF @lIdForClQty = 0
	BEGIN
		-- For Stcok Item
		IF @rItemSourceTypeId = 34
		BEGIN
			IF @rIsTransferReceiptTransaction=1 
			BEGIN
			 SELECT @lWeightedAverageCost =  SIP.WeightedAverageCost
			FROM  sIp.tStockItemPlanning SIP
			WHERE SIP.StockItemid = @rItemSourceId
			AND StoreLocationId = @rTransferFromStoreLocationId 
			END
			 ELSE
			 BEGIN
			SELECT @lWeightedAverageCost = SIP.LastPurchasePrice 
			FROM  sIp.tStockItemPlanning SIP
			WHERE SIP.StockItemid = @rItemSourceId
			AND StoreLocationId = @rStoreLocationId 
			END
			--AND LocationId = @lLocationId
			
			SELECT @lClosingQuantity = SUM(B.AvailableQuantity) 
			FROM sProcurement.vExtStockBatch B 
			--INNER JOIN sIp.tStoreLocationMaster SLM On B.StoreLocationId = SLM.Id
			WHERE B.StockItemId = @rItemSourceId
			AND B.OrgGroupId = @rOrgId
			AND B.StoreLocationId = @rStoreLocationId			
			--AND SLM.LocationId = @lLocationId
			
			SET @lClosingValue = @lClosingQuantity * @lWeightedAverageCost
		END
	END
	ELSE
	BEGIN
			IF @rIsTransferReceiptTransaction=1 
			BEGIN
			 SELECT @lTransferReceiptWAC =  SIP.WeightedAverageCost
			FROM  sIp.tStockItemPlanning SIP
			WHERE SIP.StockItemid = @rItemSourceId
			AND StoreLocationId = @rTransferFromStoreLocationId 
			END
	END
	-- Store Location Closing Quantity
	--SELECT TOP 1
	--	@lIdForStoClQty = Id, 
	--	@lStoreClosingQuantity = StoreLocationClosingQuantity
	--FROM sIp.tWeightedAverageCostLog 
	--WHERE ItemSourceTypeId = @rItemSourceTypeId   AND ItemSourceId = @rItemSourceId AND StoreLocationId = @rStoreLocationId
	--	AND OrgId = @rOrgId AND LocationId = @lLocationId ORDER BY ID DESC

	---- There is no entry in the WAC Log for the passed location Id
	--IF @lIdForStoClQty = 0
	--BEGIN
	--	-- For Stcok Item
	--	IF @rItemSourceTypeId = 34
	--	BEGIN
	--		SELECT @lStoreClosingQuantity = SUM(B.AvailableQuantity) 
	--		FROM sProcurement.vExtStockBatch B 
	--		WHERE B.StockItemId = @rItemSourceId AND B.StoreLocationId = @rStoreLocationId
	--			AND B.OrgId = @rOrgId   
	--	END
	--END

	SELECT 
		@lIdForClQty AS Id, 
		@lIdForStoClQty AS ForStoreLocationId,
		@rStoreLocationId AS StoreLocationId,
		@lSourceTypeId AS SourceTypeId, 
		@lSourceId AS SourceId, 
		@lItemSourceTypeId AS ItemSourceTypeId, 
		@lItemSourceId AS ItemSourceId, 
		@lQuantity AS Quantity, 
		@lValue AS Value, 
		@lIsReceipt AS IsReceipt, 
		@lClosingQuantity AS ClosingQuantity, 
		@lClosingValue AS ClosingValue, 
		@lWeightedAverageCost AS WeightedAverageCost, 
		@lCreatedUserId AS CreatedUserId, 
		@lStoreClosingQuantity AS StoreLocationClosingQuantity,
		@lIsWACLogEntryExists AS IsWACLogEntryExists,
		@lTransferReceiptWAC AS TransferRecieptWAC   
		
	
				
		     
END




/****** Object:  StoredProcedure [sIp].[pItemStandardPriceLogAdd]    Script Date: 07/09/2013 16:25:02 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pAssessmentYearAdd]   
** Desc:  Insert data in [[tAssessmentYear]] table 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/SelectAssessmentYear.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/
CREATE OR ALTER PROCEDURE [siTax].[pAssessmentYearAdd]   
   	    @rId bigint,
		@rOrgGroupId smallint,
        @rTitle nvarchar(100),
		@rCode nvarchar(100),
		@rIsObsolete bit =null,
        @rCreatedUserId bigint
        
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		

		If Exists(select Id from [siTax].[tAssessmentYear] where code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
	
		If Exists(select Id from [siTax].[tAssessmentYear] where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		

		If  Exists(select Id from [siTax].[tAssessmentYear] where code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End

		If  Exists(select Id from [siTax].[tAssessmentYear] where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'siTax.tAssessmentYear', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO siTax.tAssessmentYear
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			0,
		    @rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  siTax.tAssessmentYear
	    SET
			OrgGroupId=@rOrgGroupId,
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pAssessmentYearGet]  
** Desc:  Display record in Assessment Year Master
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/AssessmentYearMaster.aspx 
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/

--EXEC [siTax].[pAssessmentYearGet] 100100003,1001,'',''

CREATE OR ALTER PROCEDURE [siTax].[pAssessmentYearGet]

	 @rId int,
	 @rOrgGroupId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
	   [Id]
      ,[OrgGroupId]
      ,[Code]
      ,[Title]
      ,case IsObsolete when 0 then 'N' else 'Y' end as InActive
	  ,IsObsolete 
	   
  FROM [siTax].[tAssessmentYear] as PT
		    
	
		
	WHERE 
		(PT.OrgGroupId = @rOrgGroupId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((PT.Code like @rCode) OR (ISNULL(@rCode,'') = ''))

    ORDER BY PT.CreatedDateTime DESC


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pEmployeeDataImportListGet]   
** Desc:  Display Employee  details For  Payroll Data Import
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/PayrollDataImport.aspx 
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/
-- EXEC [siTax].[pEmployeeDataImportListGet]   100100001,0,100100016,1001

CREATE OR ALTER PROCEDURE [siTax].[pEmployeeDataImportListGet]   
	@rPayrollId int,
	@rPayrollGroupId int,
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rPayrollYearId int =null
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--SELECT 
--EM.Id,
--EM.Code AS Code,
--ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
--CASE WHEN f16.Id IS NOT NULL THEN 'Imported' ELSE 'Remaining' END  AS  Status,
--CASE WHEN f16.Id IS NOT NULL THEN  CONVERT(BIT,0) ELSE CONVERT(BIT,1) END  AS  Enable
--,org.Title as 'Organization'

--FROM 
--sHrm.tEmployeeMaster EM
--INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
--INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id  
--LEFT JOIN siTax.tForm16 as f16 on f16.EmployeeId=EM.Id and AssesmentYearId= @rAssesmentYearId AND OrgGroupId =@rOrgGroupId	
--LEFT JOIN sSetup.tOrganizationMaster  as org on org.id=EM.[OrgID]			
--WHERE ESO.PayrollId = @rPayrollId 
--AND ((ESO.PayrollGroupId=@rPayrollGroupId) OR (@rPayrollGroupId=0))
--ORDER BY EM.OrgId,EM.Code

	SELECT 
		EM.Id,
		EM.Code AS Code,
		ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
		CASE WHEN f16.Id IS NOT NULL THEN 'Imported' ELSE 'Remaining' END  AS  Status,
		CASE WHEN f16.Id IS NOT NULL THEN  CONVERT(BIT,0) ELSE CONVERT(BIT,1) END  AS  Enable
		,org.Title as 'Organization'

	FROM 
		sHrm.tEmployeeMaster EM

		INNER JOIN (SELECT PYM.ID AS PayrollId,PGM.ID AS PayrollGroupId,PY.Id AS PayrollYearId,PPE.EmployeeId
		FROM sPayroll.tPayProcessEmployee AS PPE 
		INNER JOIN sPayroll.tPayProcess AS PP ON PP.ID=PPE.PayProcessId
		INNER JOIN sPayroll.tPayrollGroupMaster  AS PGM ON PGM.ID=PPE.PayrollGroupId
		INNER JOIN sPayroll.tPayrollMaster AS PYM ON PYM.Id=PGM.PayrollId
		INNER JOIN sPayroll.tPayrollYearMaster AS PY ON PY.Id=PP.PayrollYearId
		GROUP BY PYM.ID,PGM.ID ,PY.Id,PPE.EmployeeId) AS Details on Details.EmployeeId= EM.Id
		LEFT JOIN siTax.tForm16 as f16 on f16.EmployeeId=EM.Id and AssesmentYearId= @rAssesmentYearId AND OrgGroupId =@rOrgGroupId	
		LEFT JOIN sSetup.tOrganizationMaster  as org on org.id=EM.[OrgID]			
	WHERE Details.PayrollId = @rPayrollId 
		AND Details.PayrollYearId=@rPayrollYearId
		AND ((Details.PayrollGroupId=@rPayrollGroupId) OR (@rPayrollGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0 
	ORDER BY EM.OrgId,EM.Code





END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [siTax].[pEmployeeListGet]   
	@rPayrollId int,
	@rPayrollGroupId int,
	@rAssesmentYearId bigint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SELECT 
EM.Id,
ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName
FROM 
sHrm.tEmployeeMaster EM
INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id  
WHERE ESO.PayrollId = @rPayrollId 
AND ((ESO.PayrollGroupId=@rPayrollGroupId) OR (@rPayrollGroupId=0))
AND ISNULL(EM.IsOtherUser,0) = 0 
ORDER BY EM.OrgId,EM.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pForm16IncomeTaxSlabDetailGet]   
** Desc:  Calcalation Of Tax TaxAmount
** Auth:  Savan Vaghela
** Date:  16-January-2017
** Page:  
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    06-Febuary-2017      Savan Vaghela  configure TaxExeption
************************************************************/
--EXEC [siTax].[pForm16Add]  3333000000041,100100016,1001,1001000000003,100100001,100100001
CREATE OR ALTER PROCEDURE [siTax].[pForm16Add]   
	@rEmployeeId bigint,
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rCreatedUserId bigint,
	@rPayrollId BIgINT = null,
	@rPayrollYearId BIGINT=null 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			DECLARE @lNextNumber BIGINT 
					BEGIN
	 					DECLARE @Count INT =0,@Counter INT=0,@NetAmount DECIMAL(18,2)=0
											
						DECLARE @TableIncomeTaxSlab TABLE (RowID int Identity(1,1), IncomeTaxSubgroupId INT,DefaultPayElementId INT,  NetAmount DECIMAL(18,2),Amount DECIMAL(18,2))
						DECLARE @TableIncome TABLE (PayElementDefaultId INT, NetAmount DECIMAL(18,2), Amount DECIMAL(18,2))

						INSERT INTO @TableIncome
						SELECT PE.PayElementDefaultId,SUM(PPE.TotalEarning) AS NetAmount,SUM(ISNULL(PEM.Amount,0))Amount
						FROM sPayroll.tPayProcessEmployee           AS PPE 
						INNER JOIN sPayroll.tPayProcess             AS PP   ON PP.ID=PPE.PayProcessId
						INNER JOIN sPayroll.tPayrollGroupMaster     AS PGM  ON PGM.ID=PPE.PayrollGroupId
						INNER JOIN sPayroll.tPayrollMaster          AS PYM  ON PYM.Id=PGM.PayrollId
						INNER JOIN sPayroll.tPayrollYearMaster      AS PY   ON PY.Id=PP.PayrollYearId
						INNER JOIN sPayroll.tPayProcessElement      AS PEM  ON PEM.PayProcessEmployeeId=PPE.ID
						INNER JOIN sPayroll.tPayElement             AS PE   ON PE.ID=PEM.PayElementId AND PE.PayrollId=PYM.ID
						INNER JOIN sPayroll.tPayElementDefault      AS PPDE ON PPDE.id=PE.PayElementDefaultId
						WHERE PE.PayElementDefaultId in 
						(
							SELECT DefaultPayElementId 
							FROM [siTax].[tStaticIncomeTaxSubGroup] 
							WHERE ISNULL(DefaultPayElementId,0)<>0 
							UNION ALL
							SELECT  56 as DefaultPayElementId UNION ALL
							SELECT  61 as DefaultPayElementId
						)
						AND PYM.ID=@rPayrollId AND PY.Id=@rPayrollYearId AND PPE.EmployeeId=@rEmployeeId
						GROUP BY PPE.EmployeeId,PE.PayElementDefaultId,PEM.PayElementId,PE.TITLE


						IF NOT EXISTS  (select 1 from @TableIncome Where PayElementDefaultId=52)
						BEGIN
							INSERT INTO @TableIncome(PayElementDefaultId,NetAmount,Amount)
							VALUES (52,0,0)
						END

						IF NOT EXISTS  (select 1 from @TableIncome Where PayElementDefaultId=61)
						BEGIN
							INSERT INTO @TableIncome(PayElementDefaultId,NetAmount,Amount)
							VALUES (61,0,0)
						END

						IF NOT EXISTS  (select 1 from @TableIncome Where PayElementDefaultId=56)
						BEGIN
							INSERT INTO @TableIncome(PayElementDefaultId,NetAmount,Amount)
							VALUES (56,0,0)
						END

						IF NOT EXISTS  (select 1 from @TableIncome Where PayElementDefaultId=54)
						BEGIN
							INSERT INTO @TableIncome(PayElementDefaultId,NetAmount,Amount)
							VALUES (54,0,0)
						END


						UPDATE @TableIncome SET Amount=Amount + (SELECT ISNULL(Amount,0) FROM @TableIncome WHERE  PayElementDefaultId=56) WHERE  PayElementDefaultId=54
						UPDATE @TableIncome SET Amount=Amount + (SELECT ISNULL(Amount,0) FROM @TableIncome WHERE  PayElementDefaultId=61) WHERE  PayElementDefaultId=52
						
						DELETE FROM @TableIncome WHERE  PayElementDefaultId in (56,61)
						
						 

						INSERT INTO @TableIncomeTaxSlab
						SELECT ITSG.Id AS IncomeTaxSubgroupId,ITSG.DefaultPayElementId,ISNULL(Details.NetAmount,0)NetAmount,ISNULL(Details.Amount,0)Amount
						FROM [siTax].[tStaticIncomeTaxSubGroup]  AS ITSG
						LEFT JOIN (
						SELECT * FROM (SELECT * FROM @TableIncome) AS Details
						) AS  Details ON Details.PayElementDefaultId=ITSG.DefaultPayElementId
						WHERE ISNULL(ITSG.DefaultPayElementId,0)<>0



						
						SELECT @Count=COUNT(1) FROM @TableIncomeTaxSlab
						SELECT TOP 1 @NetAmount=  MAX(NetAmount) FROM @TableIncomeTaxSlab WHERE NetAmount<>0 
						
						

							IF NOT EXISTS(SELECT 1 FROM [siTax].[tForm16] WHERE EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId)
								BEGIN
								    
									EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'siTax.tForm16', 0, 1, 1,@outNextNumber = @lNextNumber output
									
									INSERT INTO  [siTax].[tForm16]  (Id,EmployeeId,AssesmentYearId,IsObsolete,CreatedUserId,CreatedDateTime,OrgGroupId)
									
									VALUES (@lNextNumber,@rEmployeeId,@rAssesmentYearId,0,@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId)

									INSERT INTO  [siTax].[tForm16Detail] (Form16Id,IncomeTaxSubgroupId,GrossAmount,QualifyingAmount,DeductibleAmount,IsObsolete,CreatedUserId,CreatedDateTime)
									
									SELECT @lNextNumber,StaticIncomeTaxSubGroupId,0,0,0,0,@rCreatedUserId,sCommon.fGetDate() 
									FROM [siTax].[tIncomeTaxSubGroup] 
									WHERE 
										AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId
								END
							ELSE
								BEGIN
									SELECT @lNextNumber=Id 
									FROM [siTax].[tForm16] 
									WHERE 
										EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId
								END


							UPDATE [siTax].[tForm16Detail] SET GrossAmount=ISNULL(@NetAmount,0) WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=1
							WHILE (@Count>@Counter)
							BEGIN
								 SET @Counter=@Counter+1	
								 DECLARE 	@IncomeTaxSubgroupId int=0
								 DECLARE 	@Amount DECIMAL(18,2)=0
								 
								 SELECT @IncomeTaxSubgroupId=IncomeTaxSubgroupId,@Amount=Amount   
								 FROM @TableIncomeTaxSlab 
								 WHERE RowID=@Counter
								 UPDATE [siTax].[tForm16Detail] 
								 SET GrossAmount=@Amount
								 WHERE 
									 Form16Id=@lNextNumber 
									 AND IncomeTaxSubgroupId=@IncomeTaxSubgroupId
								 
							END
							
							SELECT 1 as Result

					END	 						
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pForm16DetailsAdd] 
** Desc:  Add and Update Record for the [siTax].[tForm16] table 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/Form16New.aspx  
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/

CREATE OR ALTER PROCEDURE [siTax].[pForm16DetailsAdd]   
	@rId bigint,
	@rEmployeeId bigint,
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rCreatedUserId bigint,
	@rGrossAmount VARCHAR(MAX),
	@rQualifyingAmount VARCHAR(MAX),
	@rDeductibleAmount VARCHAR(MAX)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			DECLARE @lNextNumber BIGINT 

			

			DECLARE @TableGrossAmount      TABLE  (RowID int Identity(1,1),GrossAmount DECIMAL(18,2))
			DECLARE @TableQualifyingAmount TABLE  (RowID int Identity(1,1),QualifyingAmount DECIMAL(18,2))
			DECLARE @TableDeductibleAmount TABLE  (RowID int Identity(1,1),DeductibleAmount DECIMAL(18,2))

			INSERT INTO @TableGrossAmount(GrossAmount)           SELECT CAST(item as DECIMAL(18,2)) FROM scommon.fnSplit(@rGrossAmount,',')
			INSERT INTO @TableQualifyingAmount(QualifyingAmount) SELECT CAST(item as DECIMAL(18,2)) FROM scommon.fnSplit(@rQualifyingAmount,',')
			INSERT INTO @TableDeductibleAmount(DeductibleAmount) SELECT CAST(item as DECIMAL(18,2)) FROM scommon.fnSplit(@rDeductibleAmount,',')

				IF(@rId = 0)	
					BEGIN
						  IF NOT EXISTS(SELECT 1 FROM [siTax].[tForm16] WHERE EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId)
							BEGIN
							    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'siTax.tForm16', 0, 1, 1,@outNextNumber = @lNextNumber output
								INSERT INTO  [siTax].[tForm16]  (Id,EmployeeId,AssesmentYearId,IsObsolete,CreatedUserId,CreatedDateTime,OrgGroupId)
								VALUES (@lNextNumber,@rEmployeeId,@rAssesmentYearId,0,@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId)

								INSERT INTO  [siTax].[tForm16Detail] (Form16Id,IncomeTaxSubgroupId,GrossAmount,QualifyingAmount,DeductibleAmount,IsObsolete,CreatedUserId,CreatedDateTime)
								SELECT @lNextNumber,StaticIncomeTaxSubGroupId,0,QualifyingLimit,0,0,@rCreatedUserId,sCommon.fGetDate() FROm [siTax].[tIncomeTaxSubGroup] Where AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId


								DECLARE @Count int =0
								SELECT @Count= COUNT(1) FROm [siTax].[tStaticIncomeTaxSubGroup]
								DECLARE @Countter int =0

								WHILE(@Count>@Countter)
									BEGIN
										SET @Countter=@Countter+1
											UPDATE [siTax].[tForm16Detail] SET 
											 GrossAmount=(SELECT GrossAmount FROM @TableGrossAmount WHERE RowID=@Countter)
											,QualifyingAmount=(SELECT QualifyingAmount FROM @TableQualifyingAmount WHERE RowID=@Countter)
											,DeductibleAmount=(SELECT DeductibleAmount FROM @TableDeductibleAmount WHERE RowID=@Countter) 
										WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=@Countter
										PRINt @Countter
									END
								SELECT 1 as Result,@lNextNumber AS Form16Id
								print '1'
							END
							
						ELSE
							BEGIN
								
								SELECT @lNextNumber=Id FROM [siTax].[tForm16] WHERE EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId

								UPDATE [siTax].[tForm16] SET UpdatedUserId=@rCreatedUserId,	UpdatedDateTime=sCommon.fGetDate() WHERE ID=@lNextNumber
								DECLARE @Count1 int =0
								SELECT @Count1= COUNT(1) FROm [siTax].[tStaticIncomeTaxSubGroup]
								DECLARE @Countter1 int =0

								WHILE(@Count1>@Countter1)
									BEGIN
										SET @Countter1=@Countter1+1
											UPDATE [siTax].[tForm16Detail] SET 
											 GrossAmount=(SELECT GrossAmount FROM @TableGrossAmount WHERE RowID=@Countter1)
											,QualifyingAmount=(SELECT QualifyingAmount FROM @TableQualifyingAmount WHERE RowID=@Countter1)
											,DeductibleAmount=(SELECT DeductibleAmount FROM @TableDeductibleAmount WHERE RowID=@Countter1) 
										WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=@Countter1
										PRINt @Countter1
									END
								SELECT 1 as Result,@lNextNumber AS Form16Id
							END
					END	 
				ELSE
					BEGIN
						SET @lNextNumber = @rId
							UPDATE [siTax].[tForm16] SET UpdatedUserId=@rCreatedUserId,	UpdatedDateTime=sCommon.fGetDate() WHERE ID=@lNextNumber
								DECLARE @Count2 int =0
								SELECT @Count2= COUNT(1) FROm [siTax].[tStaticIncomeTaxSubGroup]
								DECLARE @Countter2 int =0

								WHILE(@Count2>@Countter2)
									BEGIN
										SET @Countter2=@Countter2+1
											UPDATE [siTax].[tForm16Detail] SET 
											 GrossAmount=(SELECT GrossAmount FROM @TableGrossAmount WHERE RowID=@Countter2)
											,QualifyingAmount=(SELECT QualifyingAmount FROM @TableQualifyingAmount WHERE RowID=@Countter2)
											,DeductibleAmount=(SELECT DeductibleAmount FROM @TableDeductibleAmount WHERE RowID=@Countter2) 
										WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=@Countter2
										PRINt @Countter2
									END
						SELECT 11 AS Result,@lNextNumber AS Form16Id
					END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [siTax].[pForm16DetailsAddBulk]   
	@rXml nvarchar(MAX),
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rCreatedUserId bigint,
	@rSubGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			DECLARE @lNextNumber BIGINT 

			DECLARE @StrXML XML  
			SET @StrXML = CAST(@rXml AS XML)  
   
			DECLARE @tForm16Detail TABLE  
			(  
			Id INT IDENTITY(1, 1),  
			FormId BIGINT,
			EmployeeId BIGINT,
			GrossAmount VARCHAR(MAX),
			QualifyingAmount VARCHAR(MAX),  
			DeductibleAmount  VARCHAR(MAX)		
			)   
			INSERT INTO @tForm16Detail  
			SELECT           
					T.c.value('@FormId','bigint') AS FormId,  
					T.c.value('@EmployeeId','bigint') AS EmployeeId,  
					T.c.value('@GrossAmount','varchar(max)') AS GrossAmount,
					T.c.value('@QualifyingAmount','varchar(max)') AS QualifyingAmount,
					T.c.value('@DeductibleAmount','varchar(max)') AS DeductibleAmount    
			FROM   
					@StrXML.nodes('/Table/Form16')T(c)  
						
			
			Declare @lCount int=1
			WHILE(@lCount <= (SELECT count(*) FROM @tForm16Detail))                
			BEGIN
				DECLARE @lId bigint,@lEmployeeId bigint,@lGrossAmount varchar(max),@lQualifyingAmount varchar(max),@lDeductibleAmount varchar(max)

				SELECT @lId = FormId , @lEmployeeId = EmployeeId,@lGrossAmount = GrossAmount,@lQualifyingAmount = QualifyingAmount,@lDeductibleAmount = DeductibleAmount  FROM @tForm16Detail WHERE Id = @lCount

				IF(@lId = 0)	
				BEGIN
				     EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'siTax.tForm16', 0, 1, 1,@outNextNumber = @lNextNumber output
					 INSERT INTO  [siTax].[tForm16]  (Id,EmployeeId,AssesmentYearId,IsObsolete,CreatedUserId,CreatedDateTime,OrgGroupId)
					 VALUES (@lNextNumber,@lEmployeeId,@rAssesmentYearId,0,@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId)

					 INSERT INTO  [siTax].[tForm16Detail] (Form16Id,IncomeTaxSubgroupId,GrossAmount,QualifyingAmount,DeductibleAmount,IsObsolete,CreatedUserId,CreatedDateTime)
					 SELECT @lNextNumber,StaticIncomeTaxSubGroupId,0,QualifyingLimit,0,0,@rCreatedUserId,sCommon.fGetDate() FROm [siTax].[tIncomeTaxSubGroup] Where AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId

					 UPDATE [siTax].[tForm16Detail] SET 
					 GrossAmount=@lGrossAmount
				     ,QualifyingAmount=@lQualifyingAmount
				     ,DeductibleAmount=@lDeductibleAmount 
					 WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=@rSubGroupId

					 SELECT 1 as Result,@lNextNumber AS Form16Id
				END
				ELSE 
				BEGIN
					SELECT @lNextNumber=@lId 

					UPDATE [siTax].[tForm16] SET UpdatedUserId=@rCreatedUserId,	UpdatedDateTime=sCommon.fGetDate() WHERE ID=@lNextNumber
					
					 UPDATE [siTax].[tForm16Detail] SET 
					 GrossAmount=@lGrossAmount
				     ,QualifyingAmount=@lQualifyingAmount
				     ,DeductibleAmount=@lDeductibleAmount 
					 WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=@rSubGroupId

					SELECT 1 as Result,@lNextNumber AS Form16Id
				END
				SET @lCount = @lCount + 1
			END		
					 
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pForm16DetailsGet] 
** Desc:  Insert data in [tIncomeTaxSlab] table 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/Form16New.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/
--EXEC [siTax].[pIncomeTaxChallanGet] 0,1001,100100016,'','','',0,0
CREATE OR ALTER PROCEDURE [siTax].[pForm16DetailsGet]
	@rId int,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rAssessmentYearId bigint,
	@rTitle VARCHAR(50)='',
	@rCode  VARCHAR(50)='',
	@PageIndex INT = 1,
    @PageSize INT = 10
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
			
	END

	SELECT * FROM (
	SELECT
	
		PT.[Id]
		,ROW_NUMBER() OVER(ORDER BY PT.[Id] ASC) AS RowNumber
		,PT.[EmployeeId]
		,PT.[AssesmentYearId]
		,PT.[OrgGroupId]
		,PT.[IsObsolete]
		,CASE PT.[IsObsolete] WHEN 0 THEN 'N' ELSE 'Y' END AS InActive
		,G.[FirstName] +' '+ G.[LastName] as [EmployeeName]
		,G.[Code]
		,G.[OrgID]
		,PT.[CreatedDateTime]
		,org.Title as 'Organization'
		,AY.Title AS AssesmentYear
 	FROM [siTax].[tForm16] as PT
	LEFT JOIN [sHrm].[tEmployeeMaster] as G on g.Id=PT.[EmployeeId]
	LEFT JOIN [sSetup].[tOrganizationMaster]  as org on org.id=G.[OrgID]
	LEFT JOIN [siTax].[tAssessmentYear] AS AY on ay.Id=PT.AssesmentYearId
	WHERE (PT.[OrgGroupId] = @rOrgGroupId) 
		AND ((G.[OrgID]=@rOrgId) OR (@rOrgId=-1))
		AND ( PT.[AssesmentYearId]= @rAssessmentYearId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((G.[FirstName] +' '+ G.[LastName] LIKE @rTitle) OR (@rTitle=''))
		AND ((G.[Code] LIKE @rCode ) OR (@rCode=''))
		AND ISNULL(G.IsOtherUser,0) = 0 
		
		
	) as a
	WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
	ORDER by a.[Code],a.CreatedDateTime 


	SELECT COUNT(1) as Records 	FROM [siTax].[tForm16] as PT
	LEFT JOIN [sHrm].[tEmployeeMaster] as G on g.Id=PT.[EmployeeId] AND ISNULL(G.IsOtherUser,0) = 0 

	WHERE (PT.[OrgGroupId] = @rOrgGroupId) 
		AND ((G.[OrgID]=@rOrgId) OR (@rOrgId=-1))
		AND ( PT.[AssesmentYearId]= @rAssessmentYearId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((G.[FirstName] +' '+ G.[LastName] LIKE @rTitle) OR (@rTitle=''))
		AND ((G.[Code] LIKE @rCode ) OR (@rCode=''))
		AND ISNULL(G.IsOtherUser,0) = 0
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [siTax].[pForm16EmployeeDataUpdate]   
	@rEmployeeId bigint,
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rGrossAmount DECIMAL(18,2),
	@rQualifyingAmount DECIMAL(18,2),
	@rDeductibleAmount DECIMAL(18,2),
	@rIncomeTaxSubgroupId int 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			DECLARE @Form16Id BigINT=0
			SELECT @Form16Id =ID FROm [siTax].[tForm16] WHERE EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId AND OrgGroupId=@rOrgGroupId
			SET @Form16Id=ISNULL(@Form16Id,0)
						
			UPDATE [siTax].[tForm16Detail] SET GrossAmount=@rGrossAmount,QualifyingAmount=@rQualifyingAmount,DeductibleAmount=@rDeductibleAmount 
			WHERE Form16Id=@Form16Id AND IncomeTaxSubgroupId=@rIncomeTaxSubgroupId 
			
			SELECT 1 AS Result
								
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [siTax].[pForm16EmployeeDetailGet]   
	@rEmployeeId bigint,
	@rAssesmentYearId bigint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT ITG.Id as 'GroupID'
		  ,ITSG.Id as 'SubGroupID'
		  ,ISNULL(ITG.GroupCode,'') +'  '+ ISNULL(ITG.DisplayName,'') +'  '+ ISNULL(ITG.ActionName,'') as 'Group'
		  ,ITSG.SubGroupName 
		  ,ISNULL(d.GrossAmount,0)GrossAmount
		  ,ITSG.QualifyingLimit as  QualifyingAmount
		  ,ISNULL(d.DeductibleAmount,0)DeductibleAmount
		  ,ITSG.IsEditable
		  ,d.Form16Id
	FROm [siTax].[tStaticIncomeTaxGroup] AS ITG 
		 LEFT JOIN [siTax].[tStaticIncomeTaxSubGroup] AS ITSG on ITG.Id=ITSG.StaticIncomeTaxGroupId
		 LEFT JOIN (SELECT f.Id AS Form16Id,fd.IncomeTaxSubgroupId,	fd.GrossAmount,	fd.QualifyingAmount,	fd.DeductibleAmount
				    FROm [siTax].[tForm16] as f
					INNER JOIN [siTax].[tForm16Detail] as fd on f.id =fd.Form16Id
	                WHERE f.EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId 
	                AND OrgGroupId=@rOrgGroupId) AS d ON d.IncomeTaxSubgroupId=ITSG.id
	
	ORDER by ITG.OrderIndex,ITSG.OrderIndex


		DECLARE @PayrollId int = 0


		SELECT @PayrollId=ISNULL(ESO.PayrollId,0) FROM sHrm.tEmployeeMaster AS  EMP
		LEFT JOIN [sHrm].[tEmployeeStatutoryAndOther]  AS ESO ON ESO.EmployeeId=EMP.id
		LEFT JOIN sPayroll.tPayrollMaster PM ON PM.id = ESO.PayrollId
		WHERE EMP.id=@rEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
		SELECT ISNULL(ESO.PayrollId,0)PayrollId,ISNULL(PM.Title,'')PayrollName FROM sHrm.tEmployeeMaster AS  EMP
		LEFT JOIN [sHrm].[tEmployeeStatutoryAndOther]  AS ESO ON ESO.EmployeeId=EMP.id
		LEFT JOIN sPayroll.tPayrollMaster PM ON PM.id = ESO.PayrollId
		WHERE EMP.id=@rEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0

		SELECT -1 as ID,'- Select -' AS Code, 0 as OrderIndex union ALL
		SELECT Id,Code,Id as OrderIndex FROM sPayroll.tPayrollYearMaster WHERE IsActive=0 AND PayrollId=@PayrollId
		order by OrderIndex


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [siTax].[pForm16IncomeTaxSlabDetailGet]   
@rEmployeeId bigint,
@rAssesmentYearId bigint,
@rOrgGroupId int,
@rGrossAmount DECIMAL(18,2),
@rTaxDeducatedatsourceus192 DECIMAL(18,2)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	DECLARE @GenderId INT
	DECLARE @DateOfBirth DATE
	DECLARE @Age INT
	DECLARE @TaxPercentage DECIMAL(18,2) 
	DECLARE @TaxExeption DECIMAL(18,2)
	DECLARE @AmountFROM DECIMAL(18,2) 
	DECLARE @AmountTo DECIMAL(18,2)
	DECLARE @Count INT =0
	DECLARE @Counter INT =0
	DECLARE @TaxAmount DECIMAL(18,2)=0
	DECLARE @EducationCess DECIMAL(18,2)=0
	DECLARE @TaxPayable DECIMAL(18,2)=0
	DECLARE @ReliefUnderSection89 DECIMAL(18,2)=0
	DECLARE @TaxPayable2 DECIMAL(18,2)=0
	DECLARE @TaxSeductedAtSource192 DECIMAL(18,2)=0
	DECLARE @Balance DECIMAL(18,2)=0
	DECLARE @TaxCalculation DECIMAL(18,2)=0


	
	SELECT @GenderId=ISNULL(GenderId,0),@DateOfBirth=ISNULL(DateOfBirth, DATEADD(year,-30,sCommon.fGetDate())) 
	FROM [sHrm].[tEmployeePersonalDetail] 
	WHERE Employeeid=@rEmployeeId

	SET @Age= DATEDIFF(yy, @DateOfBirth, sCommon.fGetDate())
	SELECT @GenderId=ISNULL(GenderId,0),@DateOfBirth=ISNULL(DateOfBirth,sCommon.fGetDate()) 
	FROM [sHrm].[tEmployeePersonalDetail] 
	WHERE Employeeid=@rEmployeeId
	
	SET @Age= DATEDIFF(yy, @DateOfBirth, sCommon.fGetDate())
		
	
	
	DECLARE @TableIncomeTaxSlab    TABLE(RowID int Identity(1,1),AmountFROM DECIMAL(18,2),AmountTo DECIMAL(18,2),TaxPercentage DECIMAL(18,2),TaxExeption DECIMAL(18,2))
	
	INSERT INTO @TableIncomeTaxSlab
	
	SELECT AmountFROM,AmountTo,TaxPercentage,TaxExeption 
	FROM  [siTax].[tIncomeTaxSlab]  
	WHERE OrgGroupId=@rOrgGroupId AND (AssessmentYearId=@rAssesmentYearId) AND (GenderId=@GenderId) AND IsObsolete=0 AND TaxPercentage<>0.00
	ORDER BY AmountFROM

	SELECT @Count=COUNT(1) 
	FROM @TableIncomeTaxSlab 
	WHERE   @rGrossAmount>AmountFROM  

	

	SELECT @TaxCalculation=MIN(AmountFROM) 
	FROM @TableIncomeTaxSlab
	SET @TaxCalculation=ISNULL(@TaxCalculation,0)
	

	IF (@TaxCalculation<=@rGrossAmount)
		BEGIN
			SELECT @ReliefUnderSection89=SUM(TaxExeption)	FROM  [siTax].[tIncomeTaxSlab]  WHERE OrgGroupId=@rOrgGroupId AND (AssessmentYearId=@rAssesmentYearId) AND (GenderId=@GenderId) AND IsObsolete=0 AND TaxPercentage <>0.00
			DECLARE @MyTaxAmount DECIMAL(18,2)=0
			WHILE(@Count<>0)
				BEGIN
			
					SELECT @AmountFROM=AmountFROM,@AmountTo=AmountTo,@TaxPercentage=TaxPercentage,@TaxExeption =TaxExeption 
					FROM @TableIncomeTaxSlab 
					WHERE RowID=@Count
					
					IF @Counter=0
						BEGIN
							SET @MyTaxAmount=	((@rGrossAmount-@AmountFROM)*@TaxPercentage)/100
							SET @TaxAmount=@TaxAmount+@MyTaxAmount
						END
					ELSE
						BEGIN
							SET @MyTaxAmount=((@AmountTo-@AmountFROM)*@TaxPercentage)/100 
							SET @TaxAmount=@TaxAmount+@MyTaxAmount
						END
	
						SET @Count=@Count-1
						SET @Counter=@Counter+1
				END

			 SELECT 	@ReliefUnderSection89 =SUM(TaxExeption)					FROM @TableIncomeTaxSlab WHERE RowID between 1 and @Counter
			 


			--SELECT @TaxSeductedAtSource192=ISNULL(SUM(Amount),0) 
			--FROM [siTax].[tIncomeTaxChallan] 
			--WHERE 
			--IsObsolete=0 
			--AND AssesmentYearId=@rAssesmentYearId 
			--AND EmployeeId=@rEmployeeId 
			--AND OrgGroupId=@rOrgGroupId 
	

			
			SET @TaxSeductedAtSource192=@TaxSeductedAtSource192+@rTaxDeducatedatsourceus192
			
			IF(@rGrossAmount <= @AmountTo)
			BEGIN
				 IF(@TaxAmount > @ReliefUnderSection89)
				 BEGIN
					SET @Balance=@TaxAmount-@ReliefUnderSection89
				 END
				 ELSE
				 BEGIN
					 SET @ReliefUnderSection89 = @TaxAmount
					 SET @Balance=@TaxAmount-@ReliefUnderSection89
				 END
			END
			ELSE 
			BEGIN
				SET @Balance = @TaxAmount
				SET @ReliefUnderSection89 = 0
			END

 			IF @Balance < 0
			BEGIN			
			SET @Balance = 0
			END
			
			SET @EducationCess =(@Balance*4)/100
			SET @TaxPayable=@Balance
	
			--SET @TaxPayable2 =CASE WHEN @TaxPayable>@ReliefUnderSection89 AND @TaxAmount <= 350000  THEN  @TaxPayable-@ReliefUnderSection89 ELSE 0 END 
			SET @TaxPayable2 =@Balance+@EducationCess
			SET @Balance=@TaxPayable2-@TaxSeductedAtSource192

			print  @TaxPayable2
			print  @TaxSeductedAtSource192
			 
		END

	SELECT ISNULL(@TaxAmount,0) AS TaxAmount
	,ISNULL(@EducationCess,0) AS EducationCess3
	,ISNULL(@TaxPayable,0) AS TaxPayable
	,ISNULL(@ReliefUnderSection89,0) AS ReliefUnderSection89
	, ISNULL(@TaxPayable2,0) AS TaxPayable2
	,ISNULL(@TaxSeductedAtSource192,0) AS TaxSeductedAtSource192
	,ISNULL(@Balance,0) AS Balance
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pForm16IsEditable]   
** Desc:  IsEditable
** Auth:  Savan Vaghela
** Date:  08-Febuary-2017
** Page:  
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    06-Febuary-2017      Savan Vaghela  Create First Time
************************************************************/
--EXEC [siTax].[pForm16IsEditable]
CREATE OR ALTER PROCEDURE [siTax].[pForm16IsEditable]   
	@rCreatedUserId BigINT= null
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SELECT CONVERT(bit, IsEditable)IsEditable FROm [siTax].[tStaticIncomeTaxSubGroup] order by OrderIndex

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [siTax].[pForm16SubDetailAdd]   
	@rAutoId bigint,
	@rForm16Id bigint,
	@rEmployeeId bigint,
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rCreatedUserId bigint,
	@rGrossAmount decimal,
	@rQualifyingAmount decimal,
	@rDeductibleAmount decimal,
	@rStaticIncomeTaxSubSubId int =0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
		
		IF(@rAutoId=0)
		BEGIN
			INSERT INTO siTax.tForm16SubDetail
			(
			   Form16Id,
			   IncomeTaxSubSubgroupId,		   
			   GrossAmount,
			   QualifyingAmount,
			   DeductibleAmount,			   
			   IsObsolete,
			   CreatedUserId,
			   CreatedDateTime           
			 )
			VALUES
			(
				@rForm16Id,
				@rStaticIncomeTaxSubSubId,
				@rGrossAmount,
				@rQualifyingAmount,
				@rDeductibleAmount,		
				0,		
				@rCreatedUserId,
				getdate()
			)
			Select 1 AS Result
		END
		ELSE
		BEGIN
			Update siTax.tForm16SubDetail 
			SET			
			GrossAmount=@rGrossAmount,
			QualifyingAmount=@rQualifyingAmount,
			DeductibleAmount=@rDeductibleAmount,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=getdate()
			WHERE AutoId=@rAutoId
			
			Select 11 AS Result
		END	
		
 		  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [siTax].[pForm16SubGroupEmployeeWiseGet]   
	
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rSubGroupId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT  
	       EM.Id AS EmployeeId
		  ,EM.Code AS Code
		  ,EM.FirstName +' '+ EM.LastName AS EmployeeName
		  ,ISNULL(d.GrossAmount,0)GrossAmount
		  ,(SELECT QualifyingLimit FROM [siTax].[tStaticIncomeTaxSubGroup] WHERE Id = @rSubGroupId) as  QualifyingAmount
		  ,ISNULL(d.DeductibleAmount,0)DeductibleAmount
		  ,(SELECT IsEditable FROM [siTax].[tStaticIncomeTaxSubGroup] WHERE Id = @rSubGroupId) as IsEditable
		  ,ISNULL(d.Form16Id,0) AS Form16Id
	FROm  sHrm.tEmployeeMaster EM
		  LEFT JOIN (SELECT f.Id AS Form16Id,fd.IncomeTaxSubgroupId,fd.GrossAmount,fd.QualifyingAmount,fd.DeductibleAmount,f.EmployeeId
				    FROM  [siTax].[tForm16] as f 
					LEFT JOIN [siTax].[tForm16Detail] as fd on f.id =fd.Form16Id
					WHERE AssesmentYearId=@rAssesmentYearId  AND OrgGroupId=@rOrgGroupId AND fd.IncomeTaxSubGroupId = @rSubGroupId
					) AS d ON d.EmployeeId=EM.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pIncomeTaxChallanAdd]   
** Desc:  Insert data in tIncomeTaxChallan table 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/IncomeTaxChallan.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/
CREATE OR ALTER PROCEDURE [siTax].[pIncomeTaxChallanAdd]   
	@rId bigint,
	@rEmployeeId bigint,
	@rMonthFor smallint,
	@rYearFor smallint,
	@rChallanNo nvarchar(50),
	@rChallanDate datetime,
	@rBankCode nvarchar(50),
	@rAmount decimal(18,2),
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rIsObsolete bit =null,
	@rCreatedUserId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			DECLARE @lNextNumber BIGINT 
				IF(@rId = 0)	
					BEGIN
						EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'siTax.tIncomeTaxChallan', 0, 1, 1,@outNextNumber = @lNextNumber output
							INSERT INTO [siTax].[tIncomeTaxChallan]
							(
								Id,
								EmployeeId,
								MonthFor,
								YearFor,
								ChallanNo,
								ChallanDate,
								BankCode,
								Amount,
								AssesmentYearId,
								OrgGroupId,
								IsObsolete,
								CreatedUserId,
								CreatedDateTime
								)
							VALUES
								(
								@lNextNumber,
								@rEmployeeId,
								@rMonthFor,
								@rYearFor,
								@rChallanNo,
								@rChallanDate,
								@rBankCode,
								@rAmount,
								@rAssesmentYearId,
								@rOrgGroupId,
								0,
								@rCreatedUserId,
								sCommon.fGetDate()
								)
							SELECT 1 AS Result
					END	 
				ELSE
					BEGIN
						SET @lNextNumber = @rId
						UPDATE  [siTax].[tIncomeTaxChallan]
						SET
							EmployeeId=@rEmployeeId,
							MonthFor=@rMonthFor,
							YearFor=@rYearFor,
							ChallanNo=@rChallanNo,
							ChallanDate=@rChallanDate,
							BankCode=@rBankCode,
							Amount=@rAmount,
							AssesmentYearId=@rAssesmentYearId,
							OrgGroupId=@rOrgGroupId,
							IsObsolete=@rIsObsolete,
							UpdatedUserId=@rCreatedUserId,
							UpdatedDateTime=sCommon.fGetDate()
						WHERE Id = @lNextNumber
						SELECT 11 AS Result
					END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pIncomeTaxSlabAdd]  
** Desc:  get data for Income Tax Challan page 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/IncomeTaxChallan.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/
--EXEC [siTax].[pIncomeTaxChallanGet] 0,1001,100100016,'','','',0,0
CREATE OR ALTER PROCEDURE [siTax].[pIncomeTaxChallanGet]
	@rId int,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rAssessmentYearId bigint,
	@rTitle VARCHAR(50)='',
	@rCode  VARCHAR(50)='',
	@rChallanNo VARCHAR(50)='',
	@rYearFor int = null,
	@rMonthFor int = null,
	@rFromDate datetime = null,
	@rToDate datetime = null,
	@PageIndex INT = 1,
    @PageSize INT = 10
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rChallanNo = sCommon.fSearchStringGet(@rChallanNo)
		
	END

	SET @rOrgId = CASE WHEN @rOrgId=-1 THEN 0 ELSE @rOrgId END

	SELECT * FROM (
	SELECT
	
		PT.[Id]
		,ROW_NUMBER() OVER(ORDER BY G.[FirstName] +' '+ G.[LastName], PT.[YearFor],PT.[MonthFor],PT.[Id] ASC) AS RowNumber
		,PT.[EmployeeId]
		,PT.[MonthFor]
		,PT.[YearFor]
		,PT.[ChallanNo]
		,CONVERT(VARCHAR(20), PT.[ChallanDate],103) as  [ChallanDate]
		,PT.[BankCode]
		,PT.[Amount]
		,PT.[AssesmentYearId]
		,PT.[OrgGroupId]
		,PT.[IsObsolete]
		,CASE PT.[IsObsolete] WHEN 0 THEN 'N' ELSE 'Y' END AS InActive
		,DateName(month,DateAdd(month,PT.[MonthFor],-1))  +'-'+ CAST(PT.[YearFor] as VARCHAR)  AS [MonthName]
		,G.[FirstName] +' '+ G.[LastName] as [EmployeeName]
		,G.[Code]
		,G.[OrgID]
		,PT.[CreatedDateTime]
		,OMD.Title AS 'OrgName'
 	FROM [siTax].[tIncomeTaxChallan] as PT
	INNER JOIN [sHrm].[tEmployeeMaster] as G on g.Id=PT.[EmployeeId]
	LEFT JOIN  sSetup.tOrganizationMaster      AS OMD ON OMD.Id=g.OrgID
	WHERE (PT.[OrgGroupId] = @rOrgGroupId) 
		AND ((g.OrgID=@rOrgId)OR (@rOrgId=0))
		AND ( PT.[AssesmentYearId]= @rAssessmentYearId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((G.[FirstName] +' '+ G.[LastName] LIKE @rTitle) OR (@rTitle=''))
		AND ((G.[Code] LIKE @rCode ) OR (@rCode=''))
		AND ((PT.[ChallanNo] LIKE @rChallanNo) or (@rChallanNo=''))
		AND	((PT.[YearFor] = @rYearFor) OR (@rYearFor = 0))
		AND	((PT.[MonthFor] = @rMonthFor) OR (@rMonthFor = 0))
	    AND CONVERT(DATE,PT.[ChallanDate]) BETWEEN CONVERT(DATE,ISNULL(@rFromDate, CONVERT(DATE,PT.[ChallanDate]))) AND CONVERT(DATE,ISNULL(@rToDate, CONVERT(DATE,PT.[ChallanDate])))
	AND ISNULL(G.IsOtherUser,0) = 0
	) as a
	WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
	ORDER by  a.EmployeeName ,a.YearFor,a.MonthFor


	SELECT COUNT(1) as Records 	FROM [siTax].[tIncomeTaxChallan] as PT
	INNER JOIN [sHrm].[tEmployeeMaster] as G on g.Id=PT.[EmployeeId]

	WHERE (PT.[OrgGroupId] = @rOrgGroupId) 
		AND ((g.OrgID=@rOrgId)OR (@rOrgId=0))
		AND ( PT.[AssesmentYearId]= @rAssessmentYearId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((G.[FirstName] +' '+ G.[LastName] LIKE @rTitle) OR (@rTitle=''))
		AND ((G.[Code] LIKE @rCode ) OR (@rCode=''))
		AND ((PT.[ChallanNo] LIKE @rChallanNo) or (@rChallanNo=''))
		AND	((PT.[YearFor] = @rYearFor) OR (@rYearFor = 0))
		AND	((PT.[MonthFor] = @rMonthFor) OR (@rMonthFor = 0))
		AND ISNULL(G.IsOtherUser,0) = 0
	    AND CONVERT(DATE,PT.[ChallanDate]) BETWEEN CONVERT(DATE,ISNULL(@rFromDate, CONVERT(DATE,PT.[ChallanDate]))) AND CONVERT(DATE,ISNULL(@rToDate, CONVERT(DATE,PT.[ChallanDate])))


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pIncomeTaxGroupAdd] 
** Desc:  Insert data in Select Assessment Year page
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/SelectAssessmentYear.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/
--EXEC [siTax].[pIncomeTaxGroupAdd]   100100001,1001,1001000000003
CREATE OR ALTER PROCEDURE [siTax].[pIncomeTaxGroupAdd]   
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rCreatedUserId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(SELECT 1 FROM siTax.tIncomeTaxGroup WHERE AssesmentYearId=@rAssesmentYearId AND OrgGroupId=@rOrgGroupId)
		BEGIN
			 INSERT INTO [siTax].[tIncomeTaxGroup] (StaticIncomeTaxGroupId,GroupName,DisplayName,GroupCode,ActionName,OrderIndex,GroupRemark,AssesmentYearId,CreatedUserId,CreatedDateTime,OrgGroupId) 
			 SELECT Id,GroupName,DisplayName,GroupCode,ActionName,OrderIndex,GroupRemark,@rAssesmentYearId,@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId FROM [siTax].[tStaticIncomeTaxGroup]
			 INSERT INTO [siTax].[tIncomeTaxSubGroup] (StaticIncomeTaxSubGroupId,StaticIncomeTaxGroupId,SubGroupName,SubGroupCode,OrderIndex,SubGroupRemark,QualifyingLimit,DefaultPayElementId,AssesmentYearId,CreatedUserId,CreatedDateTime,OrgGroupId)
			 SELECT Id,StaticIncomeTaxGroupId,SubGroupName,SubGroupCode,OrderIndex,SubGroupRemark,QualifyingLimit,DefaultPayElementId,@rAssesmentYearId,@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId FROM [siTax].[tStaticIncomeTaxSubGroup]
			 SELECT 1 AS Result
		END
	ELSE
		BEGIN
			 SELECT 1 AS Result
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pIncomeTaxSlabAdd]  
** Desc:  Insert data in [tIncomeTaxSlab] table 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/IncomeTaxSlab.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/
CREATE OR ALTER PROCEDURE [siTax].[pIncomeTaxSlabAdd]   
	@rId int,
	@rGenderId int,
	@rAmountFrom DECIMAL(18,2),
	@rAmountTo DECIMAL(18,2),
	@rTaxPercentage DECIMAL(18,2),
	@rTaxExeption DECIMAL(8,2),
	@rAssessmentYearId bigint,
	@rAgeFrom smallint,
	@rAgeTo smallint,
	@rIsObsolete bit =null,
	@rCreatedUserId bigint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			DECLARE @lNextNumber BIGINT 
				IF(@rId = 0)	
						BEGIN
							EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'siTax.tIncomeTaxSlab', 0, 1, 1,@outNextNumber = @lNextNumber output
								INSERT INTO [siTax].[tIncomeTaxSlab]
									(
									Id,
									GenderId,
									AmountFrom,
									AmountTo,
									TaxPercentage,
									TaxExeption,
									AssessmentYearId,
									AgeFrom,
									AgeTo,
									IsObsolete,
									CreatedUserId,
									CreatedDateTime,
									OrgGroupId
									)
									VALUES
									(
									@lNextNumber,
									@rGenderId,
									@rAmountFrom,
									@rAmountTo,
									@rTaxPercentage,
									@rTaxExeption,
									@rAssessmentYearId,
									@rAgeFrom,
									@rAgeTo,
									0,
									@rCreatedUserId,
									sCommon.fGetDate(),
									@rOrgGroupId
									)
										SELECT 1 AS Result
									END	 
									ELSE
									BEGIN
										SET @lNextNumber = @rId
																								UPDATE  [siTax].[tIncomeTaxSlab]
									SET
									GenderId=@rGenderId,
									AmountFrom=@rAmountFrom,
									AmountTo=@rAmountTo,
									TaxPercentage=@rTaxPercentage,
									TaxExeption=@rTaxExeption,
									AssessmentYearId=@rAssessmentYearId,
									AgeFrom=@rAgeFrom,
									AgeTo=@rAgeTo,
									IsObsolete=@rIsObsolete,
									UpdatedUserId=@rCreatedUserId,
									UpdatedDateTime=sCommon.fGetDate(),
									OrgGroupId=@rOrgGroupId
									WHERE Id = @rId
							SELECT 11 AS Result
							END  	
						COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [siTax].[pIncomeTaxGroupAdd] 
** Desc:  Insert data in Select Assessment Year page
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/SelectAssessmentYear.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/
--EXEC [siTax].[pIncomeTaxSlabGet] 0,1001,100100001,0
CREATE OR ALTER PROCEDURE [siTax].[pIncomeTaxSlabGet]
	@rId int,
	@rOrgGroupId smallint,
	@rAssessmentYearId bigint,
	@rGenderId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN 
	--BEGIN
	--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	--SET @rCode = sCommon.fSearchStringGet(@rCode)
	--END
	SELECT
		PT.Id 
		,PT.[GenderId]
		,G.[Title]
		,PT.[AmountFrom]
		,  PT.[AmountTo]
		,PT.[TaxPercentage]
		,PT.[TaxExeption]
		,PT.[AssessmentYearId]
		,PT.[AgeFrom]
		,PT.[AgeTo]
		,PT.[CreatedUserId]
		,PT.[OrgGroupId]
		,case PT.[IsObsolete] when 0 then 'N' else 'Y' end as InActive
		,[PT].[IsObsolete]
		,CASE WHEN  PT.[AmountTo] <=1000000.00  THEN  CAST ( PT.[AmountTo] as VARCHAR(150))  ELSE 'More Than 10 Lakhs' END AS 'DsplayAmountTo'
	FROM [siTax].[tIncomeTaxSlab] as PT
	LEFT JOIN [sCommon].[tGenderMaster] as G on g.Id=PT.GenderId

	WHERE (PT.OrgGroupId = @rOrgGroupId) 
		AND ( PT.[AssessmentYearId]= @rAssessmentYearId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.GenderId=@rGenderId) OR (@rGenderId=0))
	ORDER BY PT.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [siTax].[pRptEmployeeChallanList]
	@rEmployeeID bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rAssessmentYearId bigint,
	@rBuilder1 VARCHAR(MAX)=null,
	@rBuilder2 VARCHAR(MAX)=null,
	@rStatusId smallint=0
WITH EXECUTE AS CALLER
AS

BEGIN 



--DECLARE @rOrgId INT =3333
--DECLARE @rEmployeeID BIGINT=3333000000046
--DECLARE @rOrgGroupId smallINT=1001
--DECLARE @rAssessmentYearId bigINT=1001000000009




	SELECT @rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,ROW_NUMBER() OVER (PARTITION BY EMP.id   ORDER BY EMP.Code ,PT.YearFor,PT.MonthFor) AS RowNumber
		,EMP.id AS EmployeeID
		,ISNULL(FirstName,'') +' '+ISNULL(MiddleName,'')+' '+ ISNULL(LastName,'') +' - '+ ISNULL(EMP.Code,'') as EmpName
		,PT.[ChallanNo]
		--,CONVERT(VARCHAR(20), PT.[ChallanDate],103) as  [ChallanDate]
		,REPLACE(CONVERT(VARCHAR(20), PT.[ChallanDate],106),' ','-') as  [ChallanDate]
		,PT.[BankCode]
		,DateName(month,DateAdd(month,PT.[MonthFor],-1))  +'-'+ CAST(PT.[YearFor] as VARCHAR)  AS [MonthName]
		,PT.[Amount]
	FROM sHrm.tEmployeeMaster                      AS EMP 
		INNER JOIN sHrm.tEmployeeStatutoryAndOther AS EMO ON EMO.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeCommunications    AS ECM ON ECM.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeJobDetail         AS EJD ON EMP.Id = EJD.EmployeeId 
	    INNER JOIN sHrm.tEmployeePersonalDetail    AS EPD ON EMP.Id = EPD.EmployeeId	
		LEFT JOIN  sSetup.tOrganizationMaster      AS OMD ON OMD.Id=EMP.OrgID
		LEFT JOIN  sSetup.tOrganizationOtherDetail AS OOD ON OOD.OrgId=OMD.id
		INNER JOIN [siTax].[tIncomeTaxChallan]     AS PT  ON PT.EmployeeId=EMP.Id
	WHERE EMP.OrgID=@rOrgId AND 
		  ((EMP.StatusId=@rStatusId) OR (@rStatusId=0)) AND 
	      ((EMP.id=@rEmployeeID) OR (@rEmployeeID=0)) AND 
		  PT.AssesmentYearId=@rAssessmentYearId
		  AND  ISNULL(EMP.IsOtherUser,0) = 0
	ORDER by  EMP.Code ,PT.YearFor,PT.MonthFor
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [siTax].[pRptForm16PartB]
	@rEmployeeID bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rAssessmentYearId bigint,
	@rBuilder1 VARCHAR(MAX)=null,
	@rBuilder2 VARCHAR(MAX)=null,
	@rStatusId smallint=0
WITH EXECUTE AS CALLER
AS

BEGIN 



--DECLARE @rOrgId INT =3333
--DECLARE @rEmployeeID BIGINT=3333000000046
--DECLARE @rOrgGroupId smallINT=1001
--DECLARE @rAssessmentYearId bigINT=1001000000009




	DECLARE @year INT,@AssessmentYear VARCHAR(1000),@FromDate Date,@ToDate Date,@Place VARCHAR(1000)
	DECLARE @Quarter1 DECIMAL(18,2),@Quarter2 DECIMAL(18,2),@Quarter3 DECIMAL(18,2),@Quarter4 DECIMAL(18,2),@Total DECIMAL(18,2),@AmountWord  VARCHAR(500)

	SELECT @year=SUBSTRING(Title,0,5),@AssessmentYear=Title 
	FROm [siTax].[tAssessmentYear] 
	WHERE id=@rAssessmentYearId 

	SET @year=ISNULL(@year,2000)
	SET @FromDate= CONVERT(DATE, CAST( CAST((@year-1) AS varchar(10)) +'-'+  '4' +'-'+ '1' AS VARCHAR(100)))
	SET @ToDate= CONVERT(DATE, CAST( CAST(@year AS varchar(10)) +'-'+  '3' +'-'+ '31' AS VARCHAR(100)))

	

	DECLARE @EmployeeMaster  TABLE 		(			RowID INT Identity(1,1),			EmployeeID bigINT		)


	

	DECLARE @QuarterDetails	 TABLE 
		(
			RowID INT Identity(1,1),
			EmployeeID bigINT,
			GroupID INT ,SubGroupID INT,
			GroupCount INT,
			GroupHeader VARCHAR(200),
			SubGroupName VARCHAR(200),
			GrossAmount DECIMAL(18,2),
			QualifyingAmount DECIMAL(18,2),
			DeductibleAmount DECIMAL(18,2),
			OrderIndex1 INT,
			OrderIndex2 INT
		)

	INSERT INTO @EmployeeMaster(EmployeeID)
	SELECT EMP.ID 
	FROM sHrm.vExtEmployeeMaster  AS EMP
	INNER JOIN [siTax].[tForm16] AS F16 ON f16.EmployeeId=EMP.ID
	WHERE EMP.OrgID=@rOrgId AND  ((EMP.StatusId=@rStatusId) OR (@rStatusId=0)) AND F16.AssesmentYearId=@rAssessmentYearId

	DECLARE @Count INT = (SELECT COUNT(0) FROM   @EmployeeMaster)
	DECLARE @EmpID BigINT=null


	While (@Count<>0) 
		BEGIN
		
			SELECT @EmpID=EmployeeID 
			FROM @EmployeeMaster 
			WHERE RowID=@Count
	
			INSERT INTO @QuarterDetails
			(
				EmployeeID,
				GroupID,
				SubGroupID,
				GroupCount,
				GroupHeader,
				SubGroupName,
				GrossAmount,
				QualifyingAmount,
				DeductibleAmount,
				OrderIndex1,
				OrderIndex2
			)
	
			SELECT  
				@EmpID,
				ITG.Id,
				ITSG.Id,
				cnt.GroupCount,
				ISNULL(ITG.GroupCode,'') +'  '+ ISNULL(ITG.DisplayName,'') +'  '+ ISNULL(ITG.ActionName,''),
				ITSG.SubGroupName,
				d.GrossAmount,
				d.QualifyingAmount,
				d.DeductibleAmount,
				ITG.OrderIndex,
				ITSG.OrderIndex
			FROm [siTax].[tStaticIncomeTaxGroup] AS ITG 
			LEFT JOIN [siTax].[tStaticIncomeTaxSubGroup] AS ITSG on ITG.Id=ITSG.StaticIncomeTaxGroupId
			LEFT JOIN (
							SELECT StaticIncomeTaxGroupId,count(1) as GroupCount 
							FROm [siTax].[tStaticIncomeTaxSubGroup] 
							GROUP by StaticIncomeTaxGroupId
					  ) AS cnt on cnt.StaticIncomeTaxGroupId=ITG.id
			LEFT JOIN  (
							SELECT FD.IncomeTaxSubgroupId,FD.GrossAmount,FD.QualifyingAmount,FD.DeductibleAmount 
							FROM  [siTax].[tForm16Detail]  AS fd 
							INNER JOIN [siTax].[tForm16] as f on f.id =fd.Form16Id AND  f.EmployeeId=@EmpID and AssesmentYearId=@rAssessmentYearId
					   ) AS d on d.IncomeTaxSubgroupId=ITSG.id
			ORDER by ITG.OrderIndex,ITSG.OrderIndex
			SET @Count=@Count-1
	END

	--SELECT q.GroupID,q.SubGroupID,q.GroupCount,q.GroupHeader,q.SubGroupName,q.GrossAmount,q.QualifyingAmount,q.DeductibleAmount  FROM ##QuarterDetails AS q
	
	SELECT 
		q.GroupID,q.SubGroupID,q.GroupCount,q.GroupHeader,q.SubGroupName
		, CASE WHEN  q.GrossAmount =0 THEN NULL ELSE q.GrossAmount END AS GrossAmount
		, CASE WHEN  q.QualifyingAmount =0 THEN NULL ELSE q.QualifyingAmount END AS QualifyingAmount
		, CASE WHEN  q.DeductibleAmount =0 THEN NULL ELSE q.DeductibleAmount END AS DeductibleAmount
		,ISNULL(FirstName,'') +' '+ISNULL(MiddleName,'')+' '+ ISNULL(LastName,'') as EmpName
		,ISNULL(EMO.PanNumber,'') AS PANNumberEmp
		,ISNULL(ECM.PresentStreetOne,'') +' '+ ISNULL(ECM.PresentStreetTwo,'')+' '+ ISNULL(ECM.PresentStreetThree,'') AS EmpAddLine1
		,ISNULL(ECM.PresentCity,'') +'-'+ISNULL(ECM.PresentZipCode,'') +' '+ISNULL(ECM.PresentState,'') +' '+ ISNULL(ECM.PresentCountry,'')   AS EmpAddLine2
		,ISNULL(oo.TaxCertifyAuthorityName,'') AS Name
		,ISNULL(oo.TaxCertifyAuthorityFatherName,'') AS FatherName
		,ISNULL(oo.TaxCertifyAuthorityDesignation,'') as Designation
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityName,'')+ '</U>' AS NameHTML
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityFatherName,'')+ '</U>' AS FatherNameHTML
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityDesignation,'')+ '</U>' AS DesignationHTML
		,ISNULL(oo.TaxCertifyAuthorityRelation,'') as Relation
		,ISNULL(StreetThree,'') +' - '+ISNULL(CityName,'') AS Place
		,ISNULL(@AssessmentYear,'') AS AssessmentYear
		,REPLACE(CONVERT(VARCHAR,@FromDate,106),' ','-')AS FromDate
		,REPLACE(CONVERT(VARCHAR,@ToDate,106),' ','-') as ToDate
		,REPLACE(CONVERT(VARCHAR,sCommon.fGetDate(),106),' ','-')AS Date
		,EMP.id  as EmployeeID	
		,@rOrgGroupId as OrgGroupId	
		,@rOrgId AS OrgId
		,@rAssessmentYearId AS AssessmentYearId
		,CAST(@rOrgGroupId AS VARCHAR(50)) as OrgGroupIdText
		,CAST(@rOrgId AS VARCHAR(50)) AS OrgIdText
		,CAST(EMP.id AS VARCHAR(50))  as EmployeeIDText
		,CAST(@rAssessmentYearId AS VARCHAR(50))   AS AssessmentYearIdText
	FROM sHrm.tEmployeeMaster  AS EMP 
		INNER JOIN sHrm.tEmployeeStatutoryAndOther AS EMO on EMO.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeCommunications AS ECM on ECM.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EMP.Id = EJD.EmployeeId 
	    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EMP.Id = EPD.EmployeeId	
		LEFT JOIN sSetup.tOrganizationMaster  AS OM ON OM.Id=EMP.OrgID
		LEFT JOIN sSetup.tOrganizationOtherDetail AS oo ON oo.OrgId=om.id
		INNER JOIN @QuarterDetails AS Q ON Q.EmployeeID=EMP.Id
	WHERE EMP.OrgID=@rOrgId 
	AND ((EMP.StatusId=@rStatusId) OR (@rStatusId=0))
	AND ((EMP.id=@rEmployeeID) OR (@rEmployeeID=0))
	ORDER by Q.EmployeeID,OrderIndex1,OrderIndex2
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [siTax].[pRptTDSReport]
	@rEmployeeID bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rAssessmentYearId bigint,
	@rBuilder1 VARCHAR(MAX)=null,
	@rBuilder2 VARCHAR(MAX)=null,
	@rStatusId smallint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	--DECLARE @rOrgId int =1001
	--DECLARE @rEmployeeID BIGINT=3333000000044,1001000000160
	--DECLARE @rOrgGroupId smallint=1001
	--DECLARE @rAssessmentYearId bigint=1001000000009




	DECLARE @year int,@AssessmentYear VARCHAR(1000),@FromDate Date,@ToDate Date,@Place VARCHAR(1000),@rItemValue NVARCHAR(50)
	DECLARE @Quarter1 Decimal(18,2),@Quarter2 Decimal(18,2),@Quarter3 Decimal(18,2),@Quarter4 Decimal(18,2),@Total Decimal(18,2),@AmountWord  VARCHAR(500)

	SELECT @year=SUBSTRING(Title,0,5),@AssessmentYear=Title 
	FROm [siTax].[tAssessmentYear] 
	WHERE id=@rAssessmentYearId 
	
	SET @year=ISNULL(@year,2000)
	SET @FromDate= CONVERT(DATE, CAST( CAST((@year-1) AS varchar(10)) +'-'+  '4' +'-'+ '1' AS VARCHAR(100)))
	SET @ToDate= CONVERT(DATE, CAST( CAST(@year AS varchar(10)) +'-'+  '3' +'-'+ '31' AS VARCHAR(100)))





	
	
	DECLARE   @EmployeeMaster TABLE(RowID int Identity(1,1),EmployeeID bigint)
	
	
	
	DECLARE	 @QuarterDetails TABLE 
		(
			RowID int Identity(1,1),
			EmployeeID bigint,
			Quarter1 Decimal(18,2),
			Quarter2 Decimal(18,2),
			Quarter3 Decimal(18,2),
			Quarter4 Decimal(18,2),
			Total Decimal(18,2),
			AmountWord NVARCHAR(500),
			TotalHTML NVARCHAR(500)
		)

	INSERT INTO @EmployeeMaster(EmployeeID)
	SELECT EMP.ID 
	FROM sHrm.vExtEmployeeMaster  AS EMP
	INNER JOIN [siTax].[tForm16] AS F16 ON f16.EmployeeId=EMP.ID
	WHERE EMP.OrgID=@rOrgId AND ((EMP.StatusId=@rStatusId) OR (@rStatusId=0)) AND F16.AssesmentYearId=@rAssessmentYearId

	
	select @rItemValue=ISNULL(CGS.ItemValue,CNF.ItemValue) from [sConfig].[tConfigurationMaster] AS CNF
	LEFT JOIN [sConfig].[tConfigurationSetup] AS CGS ON CGS.ConfigurationId=CNF.Id AND CGS.SourceTypeId = 2010 AND CGS.SourceId = @rOrgGroupId
	WHERE CNF.id=211 

	PRINT @rItemValue
		

	DECLARE @Count int = (SELECT COUNT(0) FROM   @EmployeeMaster)
	DECLARE @EmpID Bigint=null


	While (@Count<>0) 
	BEGIN

		SELECT @EmpID=EmployeeID FROM @EmployeeMaster WHERE RowID=@Count
	
		SELECT 
			@Quarter1=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			  EmployeeId =@EmpID AND 
			  OrgGroupId=@rOrgGroupId AND 
			  AssesmentYearId=@rAssessmentYearId AND 
			  YearFor=(@year-1) AND 
			  MonthFor IN (4,5,6)
		
		SELECT 
			@Quarter2=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			EmployeeId =@EmpID AND 
			OrgGroupId=@rOrgGroupId AND 
			AssesmentYearId=@rAssessmentYearId AND 
			YearFor=(@year-1) AND -- updated by Kundan : Assessment year is next year for current Finanacial Year
			MonthFor IN (7,8,9)
		
		SELECT 
			@Quarter3=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			  EmployeeId =@EmpID AND 
			  OrgGroupId=@rOrgGroupId AND 
			  AssesmentYearId=@rAssessmentYearId AND 
			  YearFor=(@year-1) AND 
			  MonthFor IN (10,11,12)
		
		SELECT 
			@Quarter4=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			  EmployeeId =@EmpID AND 
			  OrgGroupId=@rOrgGroupId AND 
			  AssesmentYearId=@rAssessmentYearId AND 
			  YearFor=(@year) AND 
			  MonthFor IN (1,2,3)
		
		SET @Total=@Quarter1+@Quarter2+@Quarter3+@Quarter4
		SET @AmountWord = [sFinanceCommon].[fNumberToWordsWithDecimal](@Total,0,2,0)+ ' Only'
		
		INSERT INTO 
		@QuarterDetails 
		(
			EmployeeID,
			Quarter1,
			Quarter2,
			Quarter3,
			Quarter4,
			Total,
			AmountWord,
			TotalHTML
		)
		SELECT 
			@EmpID, 
			@Quarter1,
			@Quarter2,
			@Quarter3,
			@Quarter4,
			@Total,
			@AmountWord,
			'<U>'+ CAST(@Total AS NVARCHAR(50)) + '</U>'
	
	
		PRINT @Count 
		PRINT @EmpID 
		SET @Count=@Count-1
	END

	SELECT 
		 CASE WHEN @rItemValue='False' THEN  ISNULL(OM.Title,'') ELSE OG.Title END AS OrgName
		,ISNULL(OM.StreetOne,'') +', '+ISNULL(OM.StreetTwo,'') AS OrgAddLine1
		,ISNULL(OM.CityName,'')+'-'+ISNULL(OM.ZipCode,'')   +' ,'+ISNULL(OM.StateName,'') +' ,'+ISNULL(OM.CountryName,'') AS OrgAddLine2
		,ISNULL(OM.PhoneNo,'') AS PhoneNo
		,ISNULL(OM.Email,'')  AS EmailID
		,ISNULL(oo.PANNumber,'') AS PANNumber
		,ISNULL(oo.TANNumber,'') AS TANNumber
		,ISNULL(oo.TaxOfficeDetail,'') AS TaxOfficeDetail
		,ISNULL(FirstName,'') +' '+ISNULL(MiddleName,'')+' '+ ISNULL(LastName,'') as EmpName
		,ISNULL(EMO.PanNumber,'') AS PANNumberEmp
		,ISNULL(ECM.PresentStreetOne,'') +' '+ ISNULL(ECM.PresentStreetTwo,'')+' '+ ISNULL(ECM.PresentStreetThree,'') AS EmpAddLine1
		,ISNULL(ECM.PresentCity,'') +'-'+ISNULL(ECM.PresentZipCode,'') +' '+ISNULL(ECM.PresentState,'') +' '+ ISNULL(ECM.PresentCountry,'')   AS EmpAddLine2
		,ISNULL(oo.TaxCertifyAuthorityName,'') AS Name
		,ISNULL(oo.TaxCertifyAuthorityFatherName,'') AS FatherName
		,ISNULL(oo.TaxCertifyAuthorityDesignation,'') as Designation
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityName,'')+ '</U>' AS NameHTML
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityDesignation,'')+ '</U>' AS DesignationHTML
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityFatherName,'')+ '</U>' AS FatherNameHTML
		,ISNULL(oo.TaxCertifyAuthorityRelation,'') as Relation
		,ISNULL(StreetThree,'') +' - '+ISNULL(CityName,'') AS Place
		,ISNULL(@AssessmentYear,'') AS AssessmentYear
		,REPLACE(CONVERT(VARCHAR,@FromDate,106),' ','-')AS FromDate
		,REPLACE(CONVERT(VARCHAR,@ToDate,106),' ','-') as ToDate
		,QD.Quarter1 as Quarter1
		,QD.Quarter2 as Quarter2	
		,QD.Quarter3 as Quarter3
		,QD.Quarter4 as Quarter4
		,EMP.id  as EmployeeID	
		,@rOrgGroupId as OrgGroupId	
		,@rAssessmentYearId AS AssessmentYearId
		,REPLACE(CONVERT(VARCHAR,sCommon.fGetDate(),106),' ','-')AS Date
		,QD.Total as Total
		,QD.TotalHTML as TotalHTML
		,'<U>'+  QD.AmountWord +'</U>' as AmountWord
		,ISNULL(ITC.Amount,0) as Amount
		,ITC.BankCode as BankCode
		,ISNULL(CONVERT(VARCHAR(20),ITC.ChallanDate ,103),'') AS ChallanDate
		,ITC.ChallanNo as ChallanNo
		,ROW_NUMBER() OVER (PARTITION BY EMP.id ORDER BY EMP.id, ITC.YearFor, ITC.MonthFor) AS RowNumber
		,CAST(EMP.id AS VARCHAR)  as EmployeeIDText	
		,CAST(@rOrgGroupId AS VARCHAR) as OrgGroupIdText	
		,CAST(@rOrgId	 AS VARCHAR) as OrgIdText		
		,CAST (@rAssessmentYearId AS VARCHAR) AS AssessmentYearIdText,
		ITC.Id AS ChallanId
	FROM sHrm.tEmployeeMaster  AS EMP 
		INNER JOIN sHrm.tEmployeeStatutoryAndOther                         AS EMO ON EMO.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeCommunications                            AS ECM ON ECM.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeJobDetail                                 AS EJD ON EMP.Id = EJD.EmployeeId 
	    INNER JOIN sHrm.tEmployeePersonalDetail							   AS EPD ON EMP.Id = EPD.EmployeeId	
		LEFT JOIN sSetup.tOrganizationMaster                               AS OM  ON OM.Id=EMP.OrgID
		LEFT JOIN sSetup.tOrganizationOtherDetail                          AS oo  ON oo.OrgId=om.id
		LEFT JOIN [siTax].[tIncomeTaxChallan]                              AS ITC ON ITC.EmployeeId=EMP.id  AND ITC.IsObsolete=0 AND  ITC.AssesmentYearId=@rAssessmentYearId 
		INNER JOIN @QuarterDetails                                         AS QD  ON QD.EmployeeID=EMP.Id
		LEFT JOIN [sSetup].[tOrgGroupMaster] OG ON  OG.id=OM.OrgGroupId
	WHERE EMP.OrgID=@rOrgId 
		AND ((EMP.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((EMP.id=@rEmployeeID) OR (@rEmployeeID=0))
	ORDER BY EMP.id,ITC.YearFor, ITC.MonthFor,ISNULL(FirstName,'') +' '+ISNULL(MiddleName,'')+' '+ ISNULL(LastName,'')

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pAccessionRegisterExportGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rPublisher nvarchar(200),
	 @rSupplier nvarchar(200),
	 @rAuthor nvarchar(200),
	 @rSubject nvarchar(200),
	 @rLanguage nvarchar(200),
	 @rLocation nvarchar(200),
	 @rEdition nvarchar(50),
	 @rPrice decimal=0,
	 @rCurrency nvarchar(100),
	 @rISBNNumber nvarchar(100),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rBookAgeGroupId int,
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rCreatedUserId bigint,
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150),
	 @rAccessionNo nvarchar(50),
	 @rClassificationNo nvarchar(50)
	 --@rPageIndex int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	        SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rPublisher = sCommon.fSearchStringGet(@rPublisher)
			SET @rSupplier = sCommon.fSearchStringGet(@rSupplier)
			SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
			SET @rSubject = sCommon.fSearchStringGet(@rSubject)
			SET @rLanguage = sCommon.fSearchStringGet(@rLanguage)
			SET @rLocation = sCommon.fSearchStringGet(@rLocation)
			SET @rEdition = sCommon.fSearchStringGet(@rEdition)
			SET @rCurrency = sCommon.fSearchStringGet(@rCurrency)
			SET @rISBNNumber = sCommon.fSearchStringGet(@rISBNNumber)
			SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
			SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
			SET @rClassificationNo = sCommon.fSearchStringGet(@rClassificationNo)
		    SET @rAccessionNo = sCommon.fSearchStringGet(@rAccessionNo)
		    	declare @quer varchar(max)=''
		     
	declare @lId bigint = 0,@lCode nvarchar(200),@lTitle nvarchar(100),@lOrgId int,
	@lPublisher nvarchar(200),@lSupplier nvarchar(200),@lAuthor nvarchar(200),
	@lSubject nvarchar(200),@lLanguage nvarchar(200),@lLocation nvarchar(200),
	@lEdition nvarchar(50),@lPrice decimal=0,@lCurrency nvarchar(100),
	@lISBNNumber nvarchar(100),@lBookTag nvarchar(200),@lBookCustomTag nvarchar(200),
	@lBookAgeGroupId int,@lResourceTypeId int,@lStatusId smallint,@lCreatedUserId bigint,
	@lLibraryId int,@lBookDepartment nvarchar(150),@lAccessionNo nvarchar(50),
	@lClassificationNo nvarchar(50)
	
	select @lId = isnull(@rId,0),@lCode = isnull(@rCode,''),@lTitle = isnull(@rTitle,''),
	@lOrgId = isnull(@rOrgId,0),@lPublisher = isnull(@rPublisher,''),@lSupplier = isnull(@rSupplier,''),
	@lAuthor = isnull(@rAuthor,''),@lSubject = isnull(@rSubject,''),
	@lLanguage = isnull(@rLanguage,''),@lLocation = isnull(@rLocation,''),
	@lEdition = isnull(@rEdition,''),@lPrice = isnull(@rPrice,0),@lCurrency = isnull(@rCurrency,''),
	@lISBNNumber = isnull(@rISBNNumber,''),@lBookTag = isnull(@rBookTag,''),
	@lBookCustomTag = isnull(@rBookCustomTag,''),@lBookAgeGroupId = isnull(@rBookAgeGroupId,0),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lCreatedUserId = isnull(@rCreatedUserId,0),
	@lLibraryId = isnull(@rLibraryId,0),@lBookDepartment = isnull(@rBookDepartment,''),@lAccessionNo = isnull(@rAccessionNo,''),
	@lClassificationNo = isnull(@rClassificationNo,'')
	SELECT @quer=' SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	ISNULL(SM.Title,'''') AS StatusName,
	ISNUll(BM.ClassificationNo,'''') AS ClassificationNo,
	ISNUll(BM.AccessionNo,'''') AS AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate 
	
	
	  FROM 
        sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
         ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM
         ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL
         ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM
         ON SM.Id=BL.StatusId
           
 
	WHERE ((BM.Id = ' + convert(varchar,@lId) + ') OR (' + convert(varchar,@lId) + ' = 0))
	AND ((BM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
	AND ((BM.Title like ''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.Publisher like ''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like ''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like ''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like ''' + @lLanguage + ''') OR (''' + @lLanguage + ''' = ''''))  
	AND ((BM.Location like ''' + @lLocation + ''') OR (''' + @lLocation + ''' = ''''))  
	AND ((BM.Edition like ''' + @lEdition + ''') OR (''' + @lEdition + ''' = ''''))  
	AND ((BM.ISBNNumber like ''' + @lISBNNumber + ''') OR (''' + @lISBNNumber + ''' = ''''))  
	AND ((BM.BookTag like ''' + @lBookTag + ''') OR ( ''' + @lBookTag + ''' = ''''))
	AND ((BM.BookCustomTag like ''' + @lBookCustomTag + ''') OR (''' + @lBookCustomTag + ''' = ''''))
	AND ((BM.BookAgeGroupId = ' + convert(varchar,@lBookAgeGroupId) + ') OR(' + convert(varchar,@lBookAgeGroupId) + ' = 0))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BM.Price = ' + convert(varchar,@lPrice) + ') OR (' + convert(varchar,@lPrice) + ' = 0))
	AND ((BM.Currency like ''' + @lCurrency + ''') OR (''' + @lCurrency  + ''' = ''''))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND ((BM.BookDepartment like ''' + @lBookDepartment + ''') OR (''' + @lBookDepartment + ''' = ''''))
	AND ((BM.ClassificationNo like ''' + @lClassificationNo + ''') OR (''' + @lClassificationNo + ''' = ''''))
	AND ((BM.AccessionNo like ''' + @lAccessionNo + ''') OR (''' + @lAccessionNo + ''' = ''''))
	AND BM.LibraryId = ' + convert(varchar,@lLibraryId)
	
 Exec (@quer)
END

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- drop proc [sLibrary].[pAccessionRegisterGet]
CREATE OR ALTER PROCEDURE [sLibrary].[pAccessionRegisterGet]
@rId bigint = 0,
@rCode nvarchar(200),
@rTitle nvarchar(100),
@rOrgId int,
@rPublisher nvarchar(200),
@rSupplier nvarchar(200),
@rAuthor nvarchar(200),
@rSubject nvarchar(200),
@rLanguage nvarchar(200),
@rLocation nvarchar(200),
@rEdition nvarchar(50),
@rPrice decimal=0,
@rCurrency nvarchar(100),
@rISBNNumber nvarchar(100),
@rBookTag nvarchar(200),
@rBookCustomTag nvarchar(200),
@rBookAgeGroupId int,
@rResourceTypeId int,
@rStatusId smallint,
@rCreatedUserId bigint,
@rLibraryId int,
@rBookDepartment nvarchar(150),
@rAccessionNo nvarchar(50),
@rClassificationNo nvarchar(50),
@rPageIndex int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS OFF
	--SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	SET @rPublisher = sCommon.fSearchStringGet(@rPublisher)
	SET @rSupplier = sCommon.fSearchStringGet(@rSupplier)
	SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
	SET @rSubject = sCommon.fSearchStringGet(@rSubject)
	SET @rLanguage = sCommon.fSearchStringGet(@rLanguage)
	SET @rLocation = sCommon.fSearchStringGet(@rLocation)
	SET @rEdition = sCommon.fSearchStringGet(@rEdition)
	SET @rCurrency = sCommon.fSearchStringGet(@rCurrency)
	SET @rISBNNumber = sCommon.fSearchStringGet(@rISBNNumber)
	SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
	SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
	SET @rClassificationNo = sCommon.fSearchStringGet(@rClassificationNo)
	SET @rAccessionNo = sCommon.fSearchStringGet(@rAccessionNo)

	DECLARE @TotalRecord int,@lpaging varchar(max)='',@PageSize int=50
	declare @lId bigint = 0,@lCode nvarchar(200),@lTitle nvarchar(100),@lOrgId int,
	@lPublisher nvarchar(200),@lSupplier nvarchar(200),@lAuthor nvarchar(200),
	@lSubject nvarchar(200),@lLanguage nvarchar(200),@lLocation nvarchar(200),
	@lEdition nvarchar(50),@lPrice decimal=0,@lCurrency nvarchar(100),
	@lISBNNumber nvarchar(100),@lBookTag nvarchar(200),@lBookCustomTag nvarchar(200),
	@lBookAgeGroupId int,@lResourceTypeId int,@lStatusId smallint,@lCreatedUserId bigint,
	@lLibraryId int,@lBookDepartment nvarchar(150),@lAccessionNo nvarchar(50),
	@lClassificationNo nvarchar(50),@lPageIndex int=0
	
	select @lId = isnull(@rId,0),@lCode = isnull(@rCode,''),@lTitle = isnull(@rTitle,''),
	@lOrgId = isnull(@rOrgId,0),@lPublisher = isnull(@rPublisher,''),@lSupplier = isnull(@rSupplier,''),
	@lAuthor = isnull(@rAuthor,''),@lSubject = isnull(@rSubject,''),
	@lLanguage = isnull(@rLanguage,''),@lLocation = isnull(@rLocation,''),
	@lEdition = isnull(@rEdition,''),@lPrice = isnull(@rPrice,0),@lCurrency = isnull(@rCurrency,''),
	@lISBNNumber = isnull(@rISBNNumber,''),@lBookTag = isnull(@rBookTag,''),
	@lBookCustomTag = isnull(@rBookCustomTag,''),@lBookAgeGroupId = isnull(@rBookAgeGroupId,0),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lCreatedUserId = isnull(@rCreatedUserId,0),
	@lLibraryId = isnull(@rLibraryId,0),@lBookDepartment = isnull(@rBookDepartment,''),@lAccessionNo = isnull(@rAccessionNo,''),
	@lClassificationNo = isnull(@rClassificationNo,''),@lPageIndex = isnull(@rPageIndex,1)
	
	create table #tbltmp (tid int identity(1,1),aid bigint)
	declare @quer varchar(max)=''
	select @quer = 'INSERT INTO #tbltmp
	SELECT BM.Id FROM 
	sLibrary.tBookMaster BM
	LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
	ON BM.BookAgeGroupId=AGM.Id
	INNER JOIN sLibrary.tResourceTypeMaster RTM
	ON BM.ResourceTypeId=RTM.Id
	INNER JOIN sLibrary.tBookLog BL
	ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
	INNER JOIN sCommon.tStatusMaster SM 
	ON SM.Id=BL.StatusId  AND SM.StatusTypeId=106

	WHERE ((BM.Id = ' + convert(varchar,@lId) + ') OR (' + convert(varchar,@lId) + ' = 0))
	AND ((BM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
	AND ((BM.Title like ''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.Publisher like ''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like ''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like ''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like ''' + @lLanguage + ''') OR (''' + @lLanguage + ''' = ''''))  
	AND ((BM.Location like ''' + @lLocation + ''') OR (''' + @lLocation + ''' = ''''))  
	AND ((BM.Edition like ''' + @lEdition + ''') OR (''' + @lEdition + ''' = ''''))  
	AND ((BM.ISBNNumber like ''' + @lISBNNumber + ''') OR (''' + @lISBNNumber + ''' = ''''))  
	AND ((BM.BookTag like ''' + @lBookTag + ''') OR ( ''' + @lBookTag + ''' = ''''))
	AND ((BM.BookCustomTag like ''' + @lBookCustomTag + ''') OR (''' + @lBookCustomTag + ''' = ''''))
	AND ((BM.BookAgeGroupId = ' + convert(varchar,@lBookAgeGroupId) + ') OR(' + convert(varchar,@lBookAgeGroupId) + ' = 0))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BM.Price = ' + convert(varchar,@lPrice) + ') OR (' + convert(varchar,@lPrice) + ' = 0))
	AND ((BM.Currency like ''' + @lCurrency + ''') OR (''' + @lCurrency  + ''' = ''''))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND ((BM.BookDepartment like ''' + @lBookDepartment + ''') OR (''' + @lBookDepartment + ''' = ''''))
	AND ((BM.ClassificationNo like ''' + @lClassificationNo + ''') OR (''' + @lClassificationNo + ''' = ''''))
	AND ((BM.AccessionNo like ''' + @lAccessionNo + ''') OR (''' + @lAccessionNo + ''' = ''''))
	AND BM.LibraryId = ' + convert(varchar,@lLibraryId)
	
	exec (@quer)
	SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'')AS Publisher,
	ISNULL(BM.Supplier,'')AS Supplier,
	ISNULL(BM.Author,'')AS Author,
	ISNULL(BM.BookSubject,'') AS BookSubject,
	ISNULL(BM.BookLanguage,'') AS BookLanguage,
	ISNULL(BM.Location,'') AS Location,
	ISNULL(BM.Edition,'')AS Edition,
	ISNULL(BM.ISBNNumber,'') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'') AS Currency,
	ISNULL(BM.BookTag,'')AS BookTag,
	ISNULL(BM.BookCustomTag,'') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'') AS BookDepartment,
	ISNULL(BM.ClassNumber,'') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	ISNULL(SM.Title,'') AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.LibraryId,
	SM.Id AS StatusId,
	ISNUll(BM.ClassificationNo,'') AS ClassificationNo,
	ISNUll(BM.AccessionNo,'') AS AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	ISNULL(BM.PurchaseDate,'0001/01/01') AS PurchaseDate 

	FROM 
	sLibrary.tBookMaster BM
	LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
	ON BM.BookAgeGroupId=AGM.Id
	INNER JOIN sLibrary.tResourceTypeMaster RTM
	ON BM.ResourceTypeId=RTM.Id
	INNER JOIN sLibrary.tBookLog BL
	ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
	INNER JOIN sCommon.tStatusMaster SM 
	ON SM.Id=BL.StatusId,#tbltmp t where t.aid = BM.Id and tid BETWEEN ((@PageSize *(@rPageIndex-1) )+ 1) and (@PageSize*@rPageIndex)
	SELECT @TotalRecord = count(*) from #tbltmp

	SELECT @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@TotalRecord,@PageSize)
	SELECT @lpaging as Paging
	drop table #tbltmp
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- drop proc [sLibrary].[pAccessionRegisterGetNew]
CREATE OR ALTER PROCEDURE [sLibrary].[pAccessionRegisterGetNew]
@rId bigint = 0,
@rCode nvarchar(200),
@rTitle nvarchar(100),
@rOrgId int,
@rPublisher nvarchar(200),
@rSupplier nvarchar(200),
@rAuthor nvarchar(200),
@rSubject nvarchar(200),
@rLanguage nvarchar(200),
@rLocation nvarchar(200),
@rEdition nvarchar(50),
@rPrice decimal=0,
@rCurrency nvarchar(100),
@rISBNNumber nvarchar(100),
@rBookTag nvarchar(200),
@rBookCustomTag nvarchar(200),
@rBookAgeGroupId int,
@rResourceTypeId int,
@rStatusId smallint,
@rCreatedUserId bigint,
@rLibraryId int,
@rBookDepartment nvarchar(150),
@rAccessionNo nvarchar(50),
@rClassificationNo nvarchar(50),
@rPageIndex int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS OFF

	DECLARE @TotalRecord int,@lpaging varchar(max)='',@PageSize int=50

	declare @lId bigint = 0,@lCode nvarchar(200),@lTitle nvarchar(100),@lOrgId int,
	@lPublisher nvarchar(200),@lSupplier nvarchar(200),@lAuthor nvarchar(200),
	@lSubject nvarchar(200),@lLanguage nvarchar(200),@lLocation nvarchar(200),
	@lEdition nvarchar(50),@lPrice decimal=0,@lCurrency nvarchar(100),
	@lISBNNumber nvarchar(100),@lBookTag nvarchar(200),@lBookCustomTag nvarchar(200),
	@lBookAgeGroupId int,@lResourceTypeId int,@lStatusId smallint,@lCreatedUserId bigint,
	@lLibraryId int,@lBookDepartment nvarchar(150),@lAccessionNo nvarchar(50),
	@lClassificationNo nvarchar(50),@lPageIndex int=0
	
	select @lId = isnull(@rId,0),@lCode = isnull(@rCode,''),@lTitle = isnull(@rTitle,''),
	@lOrgId = isnull(@rOrgId,0),@lPublisher = isnull(@rPublisher,''),@lSupplier = isnull(@rSupplier,''),
	@lAuthor = isnull(@rAuthor,''),@lSubject = isnull(@rSubject,''),
	@lLanguage = isnull(@rLanguage,''),@lLocation = isnull(@rLocation,''),
	@lEdition = isnull(@rEdition,''),@lPrice = isnull(@rPrice,0),@lCurrency = isnull(@rCurrency,''),
	@lISBNNumber = isnull(@rISBNNumber,''),@lBookTag = isnull(@rBookTag,''),
	@lBookCustomTag = isnull(@rBookCustomTag,''),@lBookAgeGroupId = isnull(@rBookAgeGroupId,0),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lCreatedUserId = isnull(@rCreatedUserId,0),
	@lLibraryId = isnull(@rLibraryId,0),@lBookDepartment = isnull(@rBookDepartment,''),@lAccessionNo = isnull(@rAccessionNo,''),
	@lClassificationNo = isnull(@rClassificationNo,''),@lPageIndex = isnull(@rPageIndex,1)
	
	create table #tbltmp (tid int identity(1,1),aid bigint)
	declare @quer varchar(max)=''
	select @quer = 'INSERT INTO #tbltmp
	SELECT BM.Id FROM 
	sLibrary.tBookMaster BM
	LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
	ON BM.BookAgeGroupId=AGM.Id
	INNER JOIN sLibrary.tResourceTypeMaster RTM
	ON BM.ResourceTypeId=RTM.Id
	INNER JOIN sLibrary.tBookLog BL
	ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
	INNER JOIN sCommon.tStatusMaster SM 
	ON SM.Id=BL.StatusId  AND SM.StatusTypeId=106

	WHERE ((BM.Id = ' + convert(varchar,@lId) + ') OR (' + convert(varchar,@lId) + ' = 0))
	AND ((BM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
	AND ((BM.Title like ''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.Publisher like ''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like ''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like ''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like ''' + @lLanguage + ''') OR (''' + @lLanguage + ''' = ''''))  
	AND ((BM.Location like ''' + @lLocation + ''') OR (''' + @lLocation + ''' = ''''))  
	AND ((BM.Edition like ''' + @lEdition + ''') OR (''' + @lEdition + ''' = ''''))  
	AND ((BM.ISBNNumber like ''' + @lISBNNumber + ''') OR (''' + @lISBNNumber + ''' = ''''))  
	AND ((BM.BookTag like ''' + @lBookTag + ''') OR ( ''' + @lBookTag + ''' = ''''))
	AND ((BM.BookCustomTag like ''' + @lBookCustomTag + ''') OR (''' + @lBookCustomTag + ''' = ''''))
	AND ((BM.BookAgeGroupId = ' + convert(varchar,@lBookAgeGroupId) + ') OR(' + convert(varchar,@lBookAgeGroupId) + ' = 0))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BM.Price = ' + convert(varchar,@lPrice) + ') OR (' + convert(varchar,@lPrice) + ' = 0))
	AND ((BM.Currency like ''' + @lCurrency + ''') OR (''' + @lCurrency  + ''' = ''''))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND ((BM.BookDepartment like ''' + @lBookDepartment + ''') OR (''' + @lBookDepartment + ''' = ''''))
	AND ((BM.ClassificationNo like ''' + @lClassificationNo + ''') OR (''' + @lClassificationNo + ''' = ''''))
	AND ((BM.AccessionNo like ''' + @lAccessionNo + ''') OR (''' + @lAccessionNo + ''' = ''''))
	AND BM.LibraryId = ' + convert(varchar,@lLibraryId)
	
	exec (@quer)
	SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'')AS Publisher,
	ISNULL(BM.Supplier,'')AS Supplier,
	ISNULL(BM.Author,'')AS Author,
	ISNULL(BM.BookSubject,'') AS BookSubject,
	ISNULL(BM.BookLanguage,'') AS BookLanguage,
	ISNULL(BM.Location,'') AS Location,
	ISNULL(BM.Edition,'')AS Edition,
	ISNULL(BM.ISBNNumber,'') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'') AS Currency,
	ISNULL(BM.BookTag,'')AS BookTag,
	ISNULL(BM.BookCustomTag,'') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'') AS BookDepartment,
	ISNULL(BM.ClassNumber,'') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	ISNULL(SM.Title,'') AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.LibraryId,
	SM.Id AS StatusId,
	ISNUll(BM.ClassificationNo,'') AS ClassificationNo,
	ISNUll(BM.AccessionNo,'') AS AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	ISNULL(BM.PurchaseDate,'0001/01/01') AS PurchaseDate 

	FROM 
	sLibrary.tBookMaster BM
	LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
	ON BM.BookAgeGroupId=AGM.Id
	INNER JOIN sLibrary.tResourceTypeMaster RTM
	ON BM.ResourceTypeId=RTM.Id
	INNER JOIN sLibrary.tBookLog BL
	ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
	INNER JOIN sCommon.tStatusMaster SM 
	ON SM.Id=BL.StatusId,#tbltmp t where t.aid = BM.Id and tid BETWEEN ((@PageSize *(@rPageIndex-1) )+ 1) and (@PageSize*@rPageIndex)
	SELECT @TotalRecord = count(*) from #tbltmp

	SELECT @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@TotalRecord,@PageSize)
	SELECT @lpaging as Paging
	drop table #tbltmp
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pAdavanceAutoAlertBookReturnDueListGet]

	 @rOrgId smallint,
	 @rBatchId int,	
	 @rLibraryId int,
	 @rOrgGroupId int=0,	
	 @rClassId int=0,
	 @rDepartmentId int=0,
	  @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		
	
	SELECT 
		
			BL.Id AS BookLogId,
			'Student' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS SourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS SourceId,
			SC.Code AS ReaderCode,
			SC.Name AS ReaderName,
			SC.ClassName+'-'+SC.DivisionName AS ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			--replace (
			--replace (
			--replace (
			--replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',SC.Name),
			--'[BookCode]',BM.Code),
			--'[BookName]',BM.Title),
			--'[DueDate]',BL.DueDate)
			-- AS EmailTemplate,
			--replace (
			--replace (
			--replace (
			--replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',SC.Name),
			--'[BookCode]',BM.Code),
			--'[BookName]',BM.Title),
			--'[DueDate]',BL.DueDate)
			-- AS SMSTemplate,

			 replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS MsgText,
			 	 
 @rTemplate AS Template,
			-- (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS Subject,
			@rMailSubject AS Subject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName,
			 LM.ReportOrgTitle,
	         LM.SmallAddress1,
	         LM.SmallAddress2,
	         VA.SUId,BL.OrgId,LM.OrgGroupId,
	         ISNULL(BL.ReaderSourceTypeId,0) AS ReceiverSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReceiverSourceId
	       			 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = SC.BatchId
			INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = SC.BatchId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
					
		 (BL.DueDate=CONVERT(DATE,GETDATE()+1,101)) AND (BL.IsCurrentStatus=1)
		AND (BL.StatusId = 523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId		
		AND ((VA.ClassId=@rClassId)OR(@rClassId=0))
		AND(VA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
	UNION ALL

	SELECT 
		
			BL.Id AS BookLogId,
			'Employee' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS SourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS SourceId,
			EC.Code AS ReaderCode,
			EC.FirstName+' '+EC.LastName AS ReaderName,
			EC.DepartmentName as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			EC.PhoneNoCompany AS MobileNo,
			EC.CompanyEmail AS EmailId,
			--replace (
			--replace (
			--replace (
			--replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',EC.EmployeeName),
			--'[BookCode]',BM.Code),
			--'[BookName]',BM.Title),
			--'[DueDate]',BL.DueDate)
			-- AS EmailTemplate,
			-- replace (
			--replace (
			--replace (
			--replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',EC.EmployeeName),
			--'[BookCode]',BM.Code),
			--'[BookName]',BM.Title),
			--'[DueDate]',BL.DueDate)
			-- AS SMSTemplate,
			--  replace (
			--replace (
			--replace (
			--replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=3),'[Name]',EC.EmployeeName),
			--'[BookCode]',BM.Code),
			--'[BookName]',BM.Title),
			--'[DueDate]',BL.DueDate)
			-- AS MsgText,

				 replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS MsgText,
			 	@rTemplate AS Template,
			-- (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS Subject,
			@rMailSubject AS Subject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName,
			 LM.ReportOrgTitle,
	         LM.SmallAddress1,
	         LM.SmallAddress2,
	         '' AS SUId,BL.OrgId,LM.OrgGroupId,
	         
	           ISNULL(BL.ReaderSourceTypeId,0) AS ReceiverSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReceiverSourceId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 AND BL.OrgId=EC.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			
	WHERE 
			 (BL.StatusId = 523) 
		AND (BL.DueDate=CONVERT(DATE,GETDATE()+1,101) ) AND  (BL.IsCurrentStatus=1)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
		AND(EC.DepartmentId=@rDepartmentId or @rDepartmentId = 0)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pAssignBooksBulkForClassGet]
	 
	 @rLibraryId int,
	 @rClassId int=null,
	 @rOrgId smallint,
	 @rBatchId int=null,
	 @rDivisionId int=null,
	 @rSourceType int,
	 @rDepartmentId int=null

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
if(@rSourceType=2003)
BEGIN
	SELECT 
	
	VA.Name,
	VA.Code,
	VA.RollNo,
	VA.StudentId AS Id
	 
  FROM 
  sStudent.vStudentAcademic  VA
 
	WHERE   
	VA.ClassId=@rClassId
	AND VA.BatchId=@rBatchId
	AND VA.OrgId=@rOrgId
	AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	order by VA.RollNo
    
END
ELSE 
BEGIN
SELECT
		EM.FirstName +' - '+	EM.LastName AS Name,
		EM.Code,
		 '' RollNo,
		EM.Id AS Id
	 
		FROM 
		sHrm.tEmployeeMaster EM 
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
		WHERE 
		EM.OrgId = @rOrgId
		AND ((EJD.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0 
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pAssignBooksBulkReturnGet]
	 
	 @rLibraryId int,
	 @rClassId int=null,
	 @rOrgId smallint,
	 @rBatchId int=null,
	 @rDivisionId int=null,
	 @rSourceType int,
	 @rDepartmentId int=null


	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
if(@rSourceType=2003)
BEGIN
	SELECT 
	Distinct VA.StudentId AS id,
	VA.Name,
	VA.Code,
	VA.RollNo,
	VA.StudentId
			 
  FROM 
  sStudent.vStudentLastAcademic  VA
  INNER JOIN sLibrary.tBookLog BL ON VA.StudentId=BL.ReaderSourceId AND  BL.IsCurrentStatus=1 AND  BL.ReaderSourceTypeId=2003
  	AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
 
  WHERE         
 VA.ClassId=@rClassId
 AND VA.BatchId=@rBatchId
 AND VA.OrgId=@rOrgId
 AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
 AND BL.LibraryId=@rLibraryId
 order by VA.RollNo
    
END
ELSE 
BEGIN
	SELECT
		Distinct EM.Id AS Id,
	 '' RollNo,
		EM.FirstName +' - '+	EM.LastName AS Name,
		EM.Code
		FROM 
		sHrm.tEmployeeMaster EM 
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
		  INNER JOIN sLibrary.tBookLog BL ON EM.Id=BL.ReaderSourceId AND  BL.IsCurrentStatus=1 AND  BL.ReaderSourceTypeId=95
  	    AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		WHERE 
		EM.OrgId = @rOrgId
		AND ((EJD.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0 
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pAssignOrganizationAdd]
	 
	@rLibraryId int,
	@rOrgId smallint,
	@rIsObsolete bit
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	IF(@rIsObsolete = 0)
	BEGIN
		DELETE FROM sLibrary.tAssignOrganization WHERE LibraryId=@rLibraryId AND OrgId=@rOrgId
	END
	ELSE IF NOT EXISTS(SELECT 1 FROM sLibrary.tAssignOrganization WHERE LibraryId=@rLibraryId AND OrgId=@rOrgId)
	BEGIN
		INSERT INTO sLibrary.tAssignOrganization
		(
			LibraryId,
			OrgId
		)
		VALUES
		(
			@rLibraryId,
			@rOrgId
		)
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pAssignOrganizationGet]
	 
	@rLibraryId int,
	@rOrgGroupId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				CASE WHEN AO.LibraryId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	FROM
			sSetup.tOrganizationMaster OM
		LEFT JOIN sLibrary.tAssignOrganization AO ON AO.OrgId=OM.Id AND AO.LibraryId=@rLibraryId
	WHERE
		OM.OrgGroupId=@rOrgGroupId
	Order by OM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [sLibrary].[pBookCountListGet] 1,100100013
CREATE OR ALTER PROCEDURE [sLibrary].[pBookCountListGet]
	 
	  @rResourceTypeId tinyint,
	  @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
    select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from  sCommon.tStatusMaster WHERE StatusTypeId=106 AND IsObsolete=0
                    group by Title,Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
set @query = 'SELECT CASE  WHEN P.BookLanguage='''' THEN ''Other'' ELSE P.BookLanguage END AS  "Book Language",BookSubject AS "Book Subject",' + @cols + ' from 
             (
               Select
                ISNULL(BM.BookLanguage,'''') AS BookLanguage,ISNULL(BM.BookSubject,'''')AS BookSubject,BL.StatusId,ISNULL(SM.Title,'''')AS StatusName
               from sLibrary.tBookLog BL
	           INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		       INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
		       INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
		        WHERE 
	       ((BL.LibraryId=' + CAST(@rLibraryId AS NVARCHAR(30))+'))
	        AND ((BM.ResourceTypeId=' + CAST(@rResourceTypeId AS NVARCHAR(30))+') OR ('+CAST(@rResourceTypeId AS NVARCHAR(30))+'= 0))
             AND BL.IsCurrentStatus=1
              ) x
            pivot 
            (
                Count(StatusId)
                for StatusName in (' + @cols + ')
            ) p order by BookLanguage'
            
print @query
 execute(@query)
	--SELECT *
	--FROM  
	--(SELECT 
	--Case WHEN BM.BookLanguage=''  Then 'Other' ELSE BM.BookLanguage END AS BookLanguage ,
	--Count(BL.StatusId) AS CNT ,
	--ISNULL(SM.Title,'')AS StatusName,
	--ISNULL(BL.StatusId,'') AS StatusId
	--from 
	--    sLibrary.tBookLog BL
	--    INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	--	INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	--	INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	--WHERE 
	--  (BM.ResourceTypeId=@rResourceTypeId OR @rResourceTypeId=0)
	--	AND (BL.LibraryId=@rLibraryId
	--   AND	BL.IsCurrentStatus=1)
	--	group By BM.BookLanguage,BL.StatusId,SM.Title)
	--		 A
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookGroup1MasterAdd]
	 
        @rId int,
        @rCode nvarchar(20),
		@rTitle nvarchar(100),		
		@rCreatedUserId bigint,
		@rIsObsolete bit,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		If Exists(select Id from sLibrary.tBookGroup1Master where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sLibrary.tBookGroup1Master where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 		
	END
	ELSE
	BEGIN
		If Exists(select Id from sLibrary.tBookGroup1Master where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sLibrary.tBookGroup1Master where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int
	
	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tBookGroup1Master', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sLibrary.tBookGroup1Master
		(
			Id,			
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsObsolete,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,			
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId			
		)
		
		  --INSERT INTO sSecurity.tUserAccess
    --       (
    --       SourceTypeId
    --       ,SourceId
    --       ,[UserId]
           
    --       )
		  -- SELECT 
		  -- 2011
		  -- ,@lNextNumber
		  -- ,@rCreatedUserId
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tBookGroup1Master
	    SET
			Title=@rTitle,
			Code=@rCode,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookGroup1MasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId int,
	 @rIsSearch bit = 1	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	SELECT 
			Id,
			Code,
			Title,
			IsObsolete
      
  FROM 
            sLibrary.tBookGroup1Master
  WHERE   
           ((Id = @rId) OR (@rId = 0))
	       AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((Code like @rCode) OR (ISNULL(@rCode,'') = ''))	       
	       AND OrgGroupId=@rOrgGroupId
	       Order by id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pBookGroup2MasterAdd]
	 
        @rId int,
        @rCode nvarchar(20),
		@rTitle nvarchar(100),		
		@rCreatedUserId bigint,
		@rIsObsolete bit,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		If Exists(select Id from sLibrary.tBookGroup2Master where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sLibrary.tBookGroup2Master where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 		
	END
	ELSE
	BEGIN
		If Exists(select Id from sLibrary.tBookGroup2Master where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sLibrary.tBookGroup2Master where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tBookGroup2Master', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sLibrary.tBookGroup2Master
		(
			Id,			
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsObsolete,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,			
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId
		)
		
		  --INSERT INTO sSecurity.tUserAccess
    --       (
    --       SourceTypeId
    --       ,SourceId
    --       ,[UserId]
           
    --       )
		  -- SELECT 
		  -- 2011
		  -- ,@lNextNumber
		  -- ,@rCreatedUserId
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tBookGroup2Master
	    SET
			Title=@rTitle,		
			Code=@rCode,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookGroup2MasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId int,
	 @rIsSearch bit = 1
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	SELECT 
			Id,			
			Code,
			Title,
			IsObsolete
      
  FROM 
            sLibrary.tBookGroup2Master
  WHERE   
           ((Id = @rId) OR (@rId = 0))
	       AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((Code like @rCode) OR (ISNULL(@rCode,'') = ''))	       
	       AND OrgGroupId=@rOrgGroupId
	       Order by id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookListGet]
	
	 @rName nvarchar(500),
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rLibraryId int
	 	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--DECLARE @lpaging
BEGIN 


	  --BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
					
	  --END
	 declare @quer varchar(max)=''
	declare @lOrgId int,@lName nvarchar(200),@lResourceTypeId int,@lStatusId smallint,@lLibraryId int

	
	select 
	@lName = isnull(@rName,''),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lLibraryId = isnull(@rLibraryId,0)

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(BM.UpdatedDateTime,'''') AS UpdatedDateTime,
	BM.LibraryId,
	SM.Id AS StatusId,
	BM.ClassificationNo,
	BM.AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	 ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate,
    ISNUll(BM.BookRemark,'''') AS BookRemark,
    ISNULL(BM.BillNumber,'''') AS BillNumber,
    BM.YearOfPublication,
    ISNULL(BM.BookEntryDate,''0001/01/01'') AS BookEntryDate,
    ISNULL(BM.BookGroup1Id,0) AS BookGroup1Id,
    ISNULL(BM.BookGroup2Id,0) AS BookGroup2Id,
	ISNULL(BL.ReaderSourceId,0)AS ReaderSourceId
 
	FROM 
         sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
         
         WHERE  
	 ((BM.Publisher like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Title like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Code like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Author like ''' + @lName + ''') OR (''' + @lName + ''' = '''') 
	 OR (BM.BookSubject like ''' + @lName + ''') OR (''' + @lName + ''' = ''''))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND BM.LibraryId = ' + convert(varchar,@lLibraryId)
	
	print(@quer);
	exec (@quer)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pBookLocationMasterAdd]
	
	@rLibraryId int,
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 
	 
	 IF(@rId = 0)	
	 BEGIN
			IF EXISTS(SELECT 1 FROM sLibrary.tBookLocationMaster WHERE Code=@rCode AND LibraryId=@rLibraryId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			IF EXISTS(SELECT 1 FROM sLibrary.tBookLocationMaster WHERE Title=@rTitle AND LibraryId=@rLibraryId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
	 END
	 ELSE
	 BEGIN
			IF EXISTS(SELECT 1 FROM sLibrary.tBookLocationMaster WHERE Code=@rCode AND LibraryId=@rLibraryId AND ID<>@rId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			IF EXISTS(SELECT 1 FROM sLibrary.tBookLocationMaster WHERE Title=@rTitle AND LibraryId=@rLibraryId AND ID<>@rId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
	 END
	BEGIN TRANSACTION	 
 IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber BIGINT   
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tBookLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sLibrary.tBookLocationMaster
		(
			LibraryId,
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rLibraryId,
			@lNextNumber,
			@rCode,
			@rTitle, 
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sLibrary.tBookLocationMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookLocationMasterGet]
	 
	 @rLibraryId int,
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			BLM.LibraryId,
			BLM.Id,
			BLM.Code,
			BLM.Title,	
			BLM.IsObsolete
  FROM 
            sLibrary.tBookLocationMaster BLM
  WHERE 
  BLM.LibraryId=@rLibraryId
	AND	((BLM.Id = @rId) OR (@rId = 0))
    AND ((BLM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((BLM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sLibrary].[pBookLogAdd]
		--@rId bigint,
        @rReaderSourceTypeId smallint,
		@rReaderSourceId bigint,
		@rResourceSourceTypeId smallint,
		@rResourceSourceId bigint,
		@rLogDate date,
		@rDueDate date,
		@rStatusId smallint,
		@rRemark nvarchar(150),
		@rIsCurrentStatus bit,
		@rOrgId smallint,
		@rBatchId int,
		@rCreatedUserId bigint,
		@rLibraryId int,
		@rBookActionStatusId int,
		@rBookLogId bigint = 0 OUT
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	--IF (@rId = 0)
	--BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tBookLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	UPDATE sLibrary.tBookLog
	    SET
			IsCurrentStatus=0,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE ResourceSourceTypeId = @rResourceSourceTypeId AND ResourceSourceId = @rResourceSourceId
		AND LibraryId = @rLibraryId
		      
		
	INSERT INTO sLibrary.tBookLog
		(
			Id,
			ReaderSourceTypeId,
			ReaderSourceId,
			ResourceSourceTypeId,
			ResourceSourceId,
			LogDate,
			DueDate,
			StatusId,
			Remark,
			IsCurrentStatus,
			OrgId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			BookActionStatusId
		)
	VALUES
		(
			@lNextNumber,
			@rReaderSourceTypeId,
			@rReaderSourceId,
			@rResourceSourceTypeId,
			@rResourceSourceId,
			ISNULL(@rLogDate,sCommon.fGetDate()),
			ISNULL(@rDueDate,sCommon.fGetDate()),
			@rStatusId,
			@rRemark,
			@rIsCurrentStatus,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rBookActionStatusId
		)
		    SELECT @lNextNumber AS Result
			SET @rBookLogId = @lNextNumber
	--END	
	--ELSE
	-- BEGIN
	-- SET @lNextNumber = @rId
	--    UPDATE sLibrary.tBookLog
	--    SET
	--		ReaderSourceTypeId=@rReaderSourceTypeId,
	--		ReaderSourceId=@rReaderSourceId,
	--		ResourceSourceTypeId=@rResourceSourceTypeId,
	--		ResourceSourceId=@rResourceSourceId,
	--		LogDate=@rLogDate,
	--		DueDate=@rDueDate,
	--		StatusId=@rStatusId,
	--		Remark=@rRemark,
	--		IsCurrentStatus=@rIsCurrentStatus,
	--		UpdatedUserId=@rCreatedUserId,
	--		UpdatedDateTime=sCommon.fGetDate()
	      
	--      WHERE Id = @rId
	--      SELECT @lNextNumber AS Result
	
	-- END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pBookLogGet]
	 @rBookLogId bigint,
	 @rResourceSourceId bigint,
	 @rStatusId smallint,
	 @rIscurrentStatus bit,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
DECLARE @lEmployeeString  VARCHAR(MAX);

	SELECT 
			BL.Id AS BookLogId,
			BL.ReaderSourceTypeId,
			BL.ReaderSourceId,
			SA.Code AS ReaderCode,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept,
			SA.ClassId As SourceId,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			BL.Remark,
			BL.IsCurrentStatus,
			IS1.PenaltyPerDay,
			BL.OrgId,
			BL.BatchId,
			ISNULL(BL.ReturnDate,'') AS ReturnDate,
			SA.SUId,
			BM.Author,
			BM.Publisher,
			( SELECT  stuff((
        SELECT ', ' + cast(CM.Title AS VARCHAR(MAX))
        FROM sSetup.tClassmaster CM
        INNER JOIN sLibrary.tBooksForClass BFC1 ON CM.Id= BFC1.ClassId  
        WHERE BFC.BookId = BFC1.BookId
        GROUP BY CM.Title,BFC1.BookId   
        for xml path('')
    ),1,1,'')  FROM sLibrary.tBooksForClass BFC
 WHERE BFC.BookId =   BM.Id 
GROUP BY  BFC.BookId) AS AssignClassDivision 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId = 2005 AND IS1.LibraryId = BL.LibraryId
	WHERE 
			((BL.ResourceSourceId=@rResourceSourceId) OR (@rResourceSourceId=0))
			AND ((BL.Id=@rBookLogId) OR (@rBookLogId=0))
			AND ((BL.IsCurrentStatus=@rIscurrentStatus) OR (@rIscurrentStatus=0))
			AND ((BL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
	
	UNION ALL
	
	SELECT 
			BL.Id AS BookLogId,
			BL.ReaderSourceTypeId,
			BL.ReaderSourceId,
			EM.Code AS ReaderCode,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			ODM.Title as ClassDept,
			ODM.Id AS SourceId,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			BL.Remark,
			BL.IsCurrentStatus,
			IS1.PenaltyPerDay,
			BL.OrgId,
			BL.BatchId,
			ISNULL(BL.ReturnDate,'') AS ReturnDate,
			'' AS SUId,
			BM.Author,
			BM.Publisher,
			'' AS AssignClassDivision 	
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId = 2004 AND IS1.LibraryId = BL.LibraryId
	WHERE 
			((BL.ResourceSourceId=@rResourceSourceId) OR (@rResourceSourceId=0))
			AND ((BL.Id=@rBookLogId) OR (@rBookLogId=0))
			AND ((BL.IsCurrentStatus=@rIscurrentStatus) OR (@rIscurrentStatus=0))
			AND ((BL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND ISNULL(EM.IsOtherUser,0) = 0 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookLogListViewGet]
	 @rReaderSourceTypeId smallint=2003,
	 @rAcademicId bigint,
	 @rOrgId smallint,
	 @rBatchId int
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lBookgrid VARCHAR(max)=''

SELECT  @lBookgrid = @lBookgrid + '<tr>
  <td align="left" scope="col">' +  Isnull(LM.Title,'') + '</td>
	<td align="left" scope="col">' + ISNULL(BM.Code,'')+ '</td>	
	<td align="left" scope="col">' + isnull(BM.Title,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(BL.LogDate,''),103) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(BL.DueDate,''),103) + '</td>
	<td align="left" scope="col">' + CASE WHEN SM.Title = 'Available' THEN  'Returned' ELSE ISNULL(SM.Title,'') END + '</td>
</tr>'	
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND BL.LibraryId = IS1.LibraryId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId AND SM.IsObsolete = 0 AND SM.StatusTypeId=106
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE ((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		 AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=521) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND SA.AcademicId=@rAcademicId
	select isnull(@lBookgrid,'') as Bookgrid
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pBookLogListViewGetEmployee]
	 @rReaderSourceTypeId smallint=95,
	 @rOrgId smallint,
	 @rEmployeeId Bigint	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lBookgrid VARCHAR(max)=''

SELECT  @lBookgrid = @lBookgrid + '<tr>
  <td align="left" scope="col">' +  Isnull(LM.Title,'') + '</td>
	<td align="left" scope="col">' + ISNULL(BM.Code,'')+ '</td>	
	<td align="left" scope="col">' + isnull(BM.Title,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(BL.LogDate,''),103) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(BL.DueDate,''),103) + '</td>
	<td align="left" scope="col">' + CASE WHEN SM.Title = 'Available' THEN  'Returned' ELSE ISNULL(SM.Title,'') END + '</td>
</tr>'	
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId AND SM.IsObsolete = 0 AND SM.StatusTypeId=106
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE ((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		 AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=521) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.ReaderSourceId = @rEmployeeId)
	select isnull(@lBookgrid,'') as Bookgrid
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pBookLogPenaltyAdd]
		@rId bigint,
        @rBookLogId bigint,
        @rPenaltyDays smallint,
        @rPenaltyRate decimal(12,2),
        @rPenaltyAmount decimal(12,2),
        @rPenaltyTypeId tinyint,
        @rOrgId smallint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	IF (@rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tBookLogPenalty', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sLibrary.tBookLogPenalty
		(
			Id,
			BookLogId,
			PenaltyDays,
			PenaltyRate,
			PenaltyAmount,
			PenaltyTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rBookLogId,
			@rPenaltyDays,
			@rPenaltyRate,
			@rPenaltyAmount,
			@rPenaltyTypeId
		)
		    SELECT @lNextNumber AS Result
	      
	END	
	ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sLibrary.tBookLogPenalty
	    SET
			BookLogId=@rBookLogId,
			PenaltyDays=@rPenaltyDays,
			PenaltyRate=@rPenaltyRate,
			PenaltyAmount=@rPenaltyAmount,
			PenaltyTypeId=@rPenaltyTypeId
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookLogPenaltyGet]
	 @rBookLogId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
	SELECT 
			ISNULL(BLP.Id,0) AS Id,
			ISNULL(BLP.PenaltyDays,0) AS PenaltyDays,
			ISNULL(BLP.PenaltyRate,0) AS PenaltyRate,
			ISNULL(BLP.PenaltyAmount,0) AS PenaltyAmount,
			ISNULL(BLP.PenaltyTypeId,0) AS PenaltyTypeId
	FROM 
			sLibrary.tBookLogPenalty BLP 
			INNER JOIN sLibrary.tBookLog BL ON BL.Id=BLP.BookLogId
	WHERE 
			((BLP.BookLogId=@rBookLogId) OR (@rBookLogId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookMaintainanceGet]
	 @rBookLogId bigint,
	 @rResourceSourceId bigint,
	 @rIsCurrentStatus bit,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN @rBookLogId != 0 THEN BL.LogDate END AS LogDate,
			CASE WHEN @rBookLogId != 0 THEN BL.DueDate END AS DueDate,
			CASE WHEN @rBookLogId != 0 THEN BL.Remark END AS Remark
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId 
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			((BL.Id=@rBookLogId) OR (@rBookLogId=0))
		AND ((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.IsCurrentStatus=@rIsCurrentStatus) OR (@rIsCurrentStatus=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookMasterAdd]
	 
	
	@rId bigint,
	@rCode nvarchar(25),
	@rTitle nvarchar(100),
	@rPublisher nvarchar(200),
	@rSupplier nvarchar(200),
	@rAuthor nvarchar(200),
	@rSubject nvarchar(200),
	@rLanguage nvarchar(200),
	@rLocation nvarchar(200),
	@rEdition nvarchar(50),
	@rISBNNumber nvarchar(100),
	@rPrice decimal(12,2),
	@rCurrency nvarchar(100),
	@rBookTag nvarchar(200),
	@rBookCustomTag nvarchar(200),
	@rBookAgeGroupId int,
	@rResourceTypeId int,
	@rOrgGroupId int,
	@rBatchId int,
	@rLibraryId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rBookDepartment nvarchar(150),
	@rClassNumber nvarchar(50),
	@rBookVolume smallint,
	@rNoOfCopies smallint,
	@rClassificationNo nvarchar(50),
	@rAccessionNo nvarchar(50),
	@rNoOfPages int,
	@rPurchaseDate date,
	@rBookRemark  nvarchar(300),
	@rBillNumber nvarchar(100),
	@rYearOfPublication nvarchar(50),
	@rBookEntryDate date,
	@rBookImage varbinary(max)=null,
	@rBookGroup1Id int=0,
	@rBookGroup2Id int=0,
	@rOrderIndex int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rId = 0)
    BEGIN
		IF Exists(Select @rCode from sLibrary.tBookMaster where Code=@rCode AND LibraryId = @rLibraryId AND Id!=@rId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
		
		IF Exists(Select 1 from sLibrary.tBookMaster where AccessionNo=@rAccessionNo AND LibraryId = @rLibraryId AND Id <> @rId)
		BEGIN
			Select -107 AS Result
			RETURN
		END
	END
	ELSE
		BEGIN
		IF Exists(Select 1 from sLibrary.tBookMaster where AccessionNo=@rAccessionNo AND LibraryId = @rLibraryId AND Id!=@rId)
		BEGIN
			Select -107 AS Result
			RETURN
		END
	 
 		IF Exists(Select @rCode from sLibrary.tBookMaster where Code=@rCode AND LibraryId = @rLibraryId  AND Id!=@rId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
	END

	BEGIN TRY
	BEGIN TRANSACTION	
		
    IF(@rId = 0)
    BEGIN
    
    DECLARE @lNextNumber BIGINT   
    
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sLibrary.tBookMaster
		(
			Id,
			Code,
			Title,
			Publisher,
			Supplier,
			Author,
			BookSubject,
			BookLanguage,
			Location,
			Edition,
			ISBNNumber,
			Price,
			Currency,
			BookTag,
			BookCustomTag,
			BookAgeGroupId,
			ResourceTypeId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			BookDepartment,
			ClassNumber,
			BookVolume,
			NoOfCopies,
			ClassificationNo ,
			AccessionNo,
			NoOfPages,
			PurchaseDate,
			BookRemark,
			BillNumber,
			YearOfPublication,
			BookEntryDate,
			BookImage,
			BookGroup1Id,
			BookGroup2Id,
			OrderIndex
			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
		    @rPublisher,
		    @rSupplier,
			@rAuthor,
			@rSubject,
			@rLanguage,
			@rLocation,
			@rEdition,
			@rISBNNumber,
			@rPrice,
			@rCurrency,
			@rBookTag,
			@rBookCustomTag,
			@rBookAgeGroupId,
			@rResourceTypeId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rBookDepartment,
			@rClassNumber,
			@rBookVolume,
			@rNoOfCopies,
			@rClassificationNo ,
			@rAccessionNo,
			@rNoOfPages,
			@rPurchaseDate,
			@rBookRemark,
			@rBillNumber,
			@rYearOfPublication,
			@rBookEntryDate,
			@rBookImage,
			@rBookGroup1Id,
			@rBookGroup2Id,
			@rOrderIndex
		)
		
	  EXECUTE sLibrary.pBookLogAdd NULL,NULL,2009,@lNextNumber,null,null,521,NULL,1,@rOrgGroupId,@rBatchId,@rCreatedUserId,@rLibraryId,NULL
	  
	  SELECT @lNextNumber AS Result
	END
	ELSE
	BEGIN
	    SET @lNextNumber = @rId
	    UPDATE  sLibrary.tBookMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			Publisher=@rPublisher,
			Supplier=@rSupplier,
			Author=@rAuthor,
			BookSubject=@rSubject,
			BookLanguage=@rLanguage,
			Location=@rLocation,
			Edition=@rEdition,
			ISBNNumber=@rISBNNumber,
			Price=@rPrice,
			Currency=@rCurrency,
			BookTag=@rBookTag,
			BookCustomTag=@rBookCustomTag,
			BookAgeGroupId=@rBookAgeGroupId,
			ResourceTypeId=@rResourceTypeId,						
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			BookDepartment=@rBookDepartment,
			ClassNumber=@rClassNumber,
			BookVolume=@rBookVolume,
			NoOfCopies=@rNoOfCopies,
			ClassificationNo=@rClassificationNo ,
			AccessionNo=@rAccessionNo,
			NoOfPages=@rNoOfPages,
			PurchaseDate=@rPurchaseDate,
			BookRemark=@rBookRemark,
			BillNumber=@rBillNumber,
			YearOfPublication=@rYearOfPublication,
			BookEntryDate=@rBookEntryDate,
			BookImage=@rBookImage,
			BookGroup1Id=@rBookGroup1Id,
			BookGroup2Id=@rBookGroup2Id,
			OrderIndex=@rOrderIndex
	      WHERE Id = @rId 
	      SELECT @lNextNumber AS Result
    END	
		
COMMIT TRANSACTION
END TRY
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookMasterBulkDelete]
	 
	 @rId bigint,
	 @rLibraryId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	BEGIN TRY
		
			BEGIN TRANSACTION
				Delete from sLibrary.tBookLog WHERE ResourceSourceId=@rId  AND LibraryId=@rLibraryId
				Delete from sLibrary.tBookMaster WHERE Id=@rId AND LibraryId=@rLibraryId
				Select 1 AS Result
			COMMIT TRANSACTION	
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookMasterDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	--BEGIN TRY
			DECLARE @lCount int
			Select @lCount=Count(*) FROM sLibrary.tBookLog WHERE ResourceSourceId=@rId
			IF(@lCount <= 1)
			BEGIN
			BEGIN TRANSACTION
				Delete from sLibrary.tBookLog WHERE ResourceSourceId=@rId
				Delete from sLibrary.tBookMaster WHERE Id=@rId
			COMMIT TRANSACTION	
			END
			ELSE
			BEGIN
				SELECT -101 Result,N'Record Reffered in Book Log Table can not deleted' AS ResultText
				--EXEC sp_addmessage 50006, 1, N'Record Reffered in Book Log Table can not deleted';
				--RAISERROR (50006,16,1,'')
			END
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookMasterGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rPublisher nvarchar(200),
	 @rSupplier nvarchar(200),
	 @rAuthor nvarchar(200),
	 @rSubject nvarchar(200),
	 @rLanguage nvarchar(200),
	 @rLocation nvarchar(200),
	 @rEdition nvarchar(50),
	 @rPrice decimal=0,
	 @rCurrency nvarchar(100),
	 @rISBNNumber nvarchar(100),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rBookAgeGroupId int,
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rCreatedUserId bigint,
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150),
	 @rShowWithPhotoId int=0,
	 @rBookGroup1Id int=0,
	 @rBookGroup2Id int=0,
	 @rAccession nvarchar(50),
	 @rOrderIndex int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--DECLARE @lpaging
BEGIN 


	  --BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rPublisher = sCommon.fSearchStringGet(@rPublisher)
			SET @rSupplier = sCommon.fSearchStringGet(@rSupplier)
			SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
			SET @rSubject = sCommon.fSearchStringGet(@rSubject)
			SET @rLanguage = sCommon.fSearchStringGet(@rLanguage)
			SET @rLocation = sCommon.fSearchStringGet(@rLocation)
			SET @rEdition = sCommon.fSearchStringGet(@rEdition)
			SET @rCurrency = sCommon.fSearchStringGet(@rCurrency)
			SET @rISBNNumber = sCommon.fSearchStringGet(@rISBNNumber)
			SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
			SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
			SET @rAccession = sCommon.fSearchStringGet(@rAccession)
		
	  --END
	 declare @quer nvarchar(max)=''
	declare @lId bigint = 0,@lCode nvarchar(200),@lTitle nvarchar(100),@lOrgId int,
	@lPublisher nvarchar(200),@lSupplier nvarchar(200),@lAuthor nvarchar(200),
	@lSubject nvarchar(200),@lLanguage nvarchar(200),@lLocation nvarchar(200),
	@lEdition nvarchar(50),@lPrice decimal=0,@lCurrency nvarchar(100),
	@lISBNNumber nvarchar(100),@lBookTag nvarchar(200),@lBookCustomTag nvarchar(200),
	@lBookAgeGroupId int,@lResourceTypeId int,@lStatusId smallint,@lCreatedUserId bigint,
	@lLibraryId int,@lBookDepartment nvarchar(150),@lBookGroup1Id int,@lBookGroup2Id int,@lAccession nvarchar(50),
	@lOrderIndex int
	select @lId = isnull(@rId,0),@lCode = isnull(@rCode,''),@lTitle = isnull(@rTitle,''),
	@lOrgId = isnull(@rOrgId,0),@lPublisher = isnull(@rPublisher,''),@lSupplier = isnull(@rSupplier,''),
	@lAuthor = isnull(@rAuthor,''),@lSubject = isnull(@rSubject,''),
	@lLanguage = isnull(@rLanguage,''),@lLocation = isnull(@rLocation,''),
	@lEdition = isnull(@rEdition,''),@lPrice = isnull(@rPrice,0),@lCurrency = isnull(@rCurrency,''),
	@lISBNNumber = isnull(@rISBNNumber,''),@lBookTag = isnull(@rBookTag,''),
	@lBookCustomTag = isnull(@rBookCustomTag,''),@lBookAgeGroupId = isnull(@rBookAgeGroupId,0),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lCreatedUserId = isnull(@rCreatedUserId,0),
	@lLibraryId = isnull(@rLibraryId,0),@lBookDepartment = isnull(@rBookDepartment,''),
	@lBookGroup1Id = isnull(@rBookGroup1Id,0),@lBookGroup2Id = isnull(@rBookGroup2Id,0),@lAccession = ISNULL(@rAccession,''),
	@lOrderIndex=ISNULL(@rOrderIndex,0)

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	ISNULL(U1.DisplayTitle,'''') AS CreatedUserName ,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(U2.DisplayTitle,'''') AS UpdatedUserName ,
	ISNULL(BM.UpdatedDateTime,'''') AS UpdatedDateTime,
	BM.LibraryId,
	ISNULL(LM.Title,'''') AS LibraryName,
	SM.Id AS StatusId,
	BM.ClassificationNo,
	BM.AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	 ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate,
    ISNUll(BM.BookRemark,'''') AS BookRemark,
    ISNULL(BM.BillNumber,'''') AS BillNumber,
    BM.YearOfPublication,
    ISNULL(BM.BookEntryDate,''0001/01/01'') AS BookEntryDate,
    CASE WHEN ' + convert(varchar,@rShowWithPhotoId) + '= 1 Then ISNULL(BM.BookImage, CONVERT(VARBINARY(MAX), 0)) ELSE BM.BookImage END AS BookPicture,
    ISNULL(BM.BookGroup1Id,0) AS BookGroup1Id,
    ISNULL(BM.BookGroup2Id,0) AS BookGroup2Id,
	ISNULL(BM.OrderIndex,0) AS OrderIndex 
	
	
	
    

	FROM 
         sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
		 INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BM.LibraryId
		 INNER JOIN sSecurity.tUser U1 ON U1.Id = BM.CreatedUserId
		 LEFT JOIN sSecurity.tUser U2 ON U2.Id = BM.UpdatedUserId
		  
         
         WHERE ((BM.Id = ' + convert(varchar,@lId) + ') OR (' + convert(varchar,@lId) + ' = 0))
	AND ((BM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
	AND ((BM.Title like N''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.AccessionNo like ''' + @lAccession + ''') OR (''' + @lAccession + ''' = '''')) 
	AND ((BM.Publisher like N''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like N''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like N''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like N''' + @lLanguage + ''') OR (''' + @lLanguage + ''' = ''''))  
	AND ((BM.Location like ''' + @lLocation + ''') OR (''' + @lLocation + ''' = ''''))  
	AND ((BM.Edition like ''' + @lEdition + ''') OR (''' + @lEdition + ''' = ''''))  
	AND ((BM.ISBNNumber like ''' + @lISBNNumber + ''') OR (''' + @lISBNNumber + ''' = ''''))  
	AND ((BM.BookTag like ''' + @lBookTag + ''') OR ( ''' + @lBookTag + ''' = ''''))
	AND ((BM.BookCustomTag like ''' + @lBookCustomTag + ''') OR (''' + @lBookCustomTag + ''' = ''''))
	AND ((BM.BookAgeGroupId = ' + convert(varchar,@lBookAgeGroupId) + ') OR(' + convert(varchar,@lBookAgeGroupId) + ' = 0))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BM.BookGroup1Id = ' + convert(varchar,@lBookGroup1Id) + ') OR (' + convert(varchar,@lBookGroup1Id) + ' = 0))
	AND ((BM.BookGroup2Id = ' + convert(varchar,@lBookGroup2Id) + ') OR (' + convert(varchar,@lBookGroup2Id) + ' = 0))
	AND ((BM.Price = ' + convert(varchar,@lPrice) + ') OR (' + convert(varchar,@lPrice) + ' = 0))
	AND ((BM.Currency like ''' + @lCurrency + ''') OR (''' + @lCurrency  + ''' = ''''))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND ((BM.BookDepartment like ''' + @lBookDepartment + ''') OR (''' + @lBookDepartment + ''' = ''''))
	AND (BM.LibraryId = ' + convert(varchar,@lLibraryId) +')
	Order By  CASE ISNUMERIC(BM.Code) WHEN 1 THEN REPLICATE(0 , 100 - LEN(BM.Code)) + BM.Code ELSE BM.Code  END '--add for mantis : 0040840
	print(@quer);
	exec (@quer)
	

  --FROM 
  --      sLibrary.tBookMaster BM
  --       LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
  --       ON BM.BookAgeGroupId=AGM.Id
  --       INNER JOIN sLibrary.tResourceTypeMaster RTM
  --       ON BM.ResourceTypeId=RTM.Id
  --       INNER JOIN sLibrary.tBookLog BL
  --       ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
  --       INNER JOIN sCommon.tStatusMaster SM
  --       ON SM.Id=BL.StatusId 
        -- WHERE 
  
      --((BM.Id = @rId) OR (@rId = 0))
      --ANd ((BM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
      -- AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      --  AND  ((BM.Publisher like @rPublisher) OR (ISNULL(@rPublisher,'') = '')) 
      --   AND  ((BM.Supplier like @rSupplier) OR (ISNULL(@rSupplier,'') = '')) 
      --    AND  ((BM.Author like @rAuthor) OR (ISNULL(@rAuthor,'') = '')) 
      --     AND  ((BM.BookSubject like @rSubject) OR (ISNULL(@rSubject,'') = ''))  
      --      AND  ((BM.BookLanguage like @rLanguage) OR (ISNULL(@rLanguage,'') = ''))  
      --       AND  ((BM.Location like @rLocation) OR (ISNULL(@rLocation,'') = ''))  
      --        AND  ((BM.Edition like @rEdition) OR (ISNULL(@rEdition,'') = ''))  
      --         AND  ((BM.ISBNNumber like @rISBNNumber) OR (ISNULL(@rISBNNumber,'') = ''))  
      --          AND  ((BM.BookTag like @rBookTag) OR (ISNULL(@rBookTag,'') = ''))
      --           AND  ((BM.BookCustomTag like @rBookCustomTag) OR (ISNULL(@rBookCustomTag,'') = ''))
      --            AND  ((BM.BookAgeGroupId = @rBookAgeGroupId) OR(@rBookAgeGroupId=0))
      --             AND  ((BM.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId=0))
      --              AND  ((BM.Price = @rPrice) OR (@rPrice=0))
      --               AND  ((BM.Currency like @rCurrency) OR (ISNULL(@rCurrency,'') = ''))
      --                AND  ((BL.StatusId = @rStatusId) OR (@rStatusId=0))
      --                ANd ((BM.BookDepartment like @rBookDepartment) OR (ISNULL(@rBookDepartment,'') = ''))
						--AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	  --AND BM.LibraryId = @rLibraryId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pBookRelease]
		
		@rResourceSourceTypeId smallint,
		@rResourceSourceId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	UPDATE sLibrary.tBookLog
	    SET
			StatusId=521,
			BookActionStatusId=2,
			UpdatedUserId=1,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE IsCurrentStatus=1 AND StatusId=522 AND ResourceSourceTypeId=@rResourceSourceTypeId AND ResourceSourceId=@rResourceSourceId
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE OR ALTER PROCEDURE [sLibrary].[pBooksForClassAdd]
	 
	
	@rAssignBooksToClassDetailXml [nvarchar](max),
	--@rAcademicId bigint,
	@rClassId int
	--@rBatchId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAssignBooksToClassDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	
	 DELETE FROM sLibrary.tBooksForClass 
				 WHERE ClassId=@rClassId 
	
 
	 INSERT INTO sLibrary.tBooksForClass
		(
			ClassId,
			BookId
			
			)
		SELECT
		ClassId,
		BookId
			
		FROM OPENXML (@loDoc, '/Table/AssignBooksToClassDetail', 1)
		WITH ( 
				ClassId int,
				BookId bigint
				
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END








GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sLibrary].[pBooksForClassGet]
	 
	 @rLibraryId int,
	 @rClassId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	SELECT 
	BM.Id,
	BM.Title,
	BM.Publisher,
	BM.Author,
	BM.BookSubject,
	BM.BookLanguage,
	BM.Edition,
	ISNULL(BFC.BookId,0) AS BFCBookId,
	ISNULL(BM.AccessionNo,'') AS AccessionNo
  FROM 
       sLibrary.tBookMaster BM
       LEFT JOIN sLibrary.tBooksForClass BFC ON BFC.BookId=BM.Id AND BFC.ClassId=@rClassId
      
  WHERE   
	(BM.LibraryId= @rLibraryId)
    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sLibrary].[pBulkBookLogListGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderCode nvarchar(20),
	 @rReaderName nvarchar(200),
	 @rResourceCode nvarchar(25),
	 @rResourceName nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rStatusId int,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rLibraryId int,
	 @rIsCurrentStatus bit,
	 @rOrgGroupBatchId int = 0,
	 @rSUId nvarchar(50)='',
	 @rDepartmentId int = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		SET @rReaderCode = sCommon.fSearchStringGet(@rReaderCode)
		SET @rReaderName = sCommon.fSearchStringGet(@rReaderName)
		SET @rResourceCode = sCommon.fSearchStringGet(@rResourceCode)
		SET @rResourceName = sCommon.fSearchStringGet(@rResourceName)
		
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Student' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			SA.Code AS ReaderCode,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)!=1 Then 'Return' WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)=1 Then 'Release' ELSE SM.Title END AS TransactionStatus,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2,
	        ISnull(SA.SUId,'') AS SUId,
	        BMM.Title AS BatchName,
	        OM.Title AS OrgName
	        
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND SA.BatchId = BL.BatchId 
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.Id = BL.BatchId AND BMM.IsInContext = 1 --AND BMM.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
			--INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003
			--AND SA.BatchId = BL.BatchId
			--AND SA.IsActiveBatch = 1
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
			AND ((SA.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
			AND ((SA.Name Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
			AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
			AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
			AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((BL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0))
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND ((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
			AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			--AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		    AND ((BL.IsCurrentStatus = @rIsCurrentStatus) OR (@rIsCurrentStatus = 0))
			AND (BL.ReaderSourceTypeId != 0)
			
	UNION

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Employee' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			EM.Code AS ReaderCode,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			ODM.Title as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)!=1 Then 'Return' WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)=1 Then 'Release' ELSE SM.Title END AS TransactionStatus,
			BL.IsCurrentStatus,
			BL.CreatedDateTime ,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2,
	        '' AS SUId,
	        '' AS BatchName,
	        '' AS OrgName
	         
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
			AND ((EM.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
			AND ((EM.FirstName+' '+EM.LastName Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
			AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
			AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
			AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((BL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0))
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND (BL.ReaderSourceTypeId != 0)
			AND ((BL.IsCurrentStatus = @rIsCurrentStatus) OR (@rIsCurrentStatus = 0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0)) -- Added for mantis : 38241
	UNION 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'' AS ReaderSourceType,
			0 AS ReaderSourceTypeId,
			0 AS ReaderSourceId,
			'' AS ReaderCode,
			'' AS ReaderName,
			'' as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			SM.Title AS TransactionStatus,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2,
	        '' AS SUId,
	        '' AS BatchName,
	        '' AS OrgName
			
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			(ISNULL(BL.ReaderSourceTypeId,0)=@rReaderSourceTypeId AND @rReaderSourceTypeId=0)
			AND (('' Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
			AND (('' Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
			AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
			AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
			AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((BL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0))
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND (BL.ReaderSourceTypeId != 0)
			AND ((BL.IsCurrentStatus = @rIsCurrentStatus) OR (@rIsCurrentStatus = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pBulkBookRelease]
		
		@rLibraryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	UPDATE sLibrary.tBookLog
	    SET
			StatusId=521,
			UpdatedUserId=1,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE IsCurrentStatus=1 AND StatusId=522 AND DueDate <= sCommon.fGetDate()  AND LibraryId=@rLibraryId 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pImportBook]
    @rOrgGroupId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int,
	@rLibraryId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lCode nvarchar(25),
		@lTitle nvarchar(100),
		@lPublisher nvarchar(200),
		@lSupplier nvarchar(200),
		@lAuthor nvarchar(200),
		@lBookSubject nvarchar(200),
		@lBookLanguage nvarchar(200),
		@lLocation nvarchar(200),
		@lEdition nvarchar(50),
		@lISBNNumber nvarchar(100),
		@lPrice decimal(12,2),
		@lCurrency nvarchar(100),
		@lBookTag nvarchar(200),
		@lBookCustomTag nvarchar(200),
		@lBookDepartment nvarchar(150),
		@lClassNumber nvarchar(50),
		@lBookVolume int,
		@lNoOfCopies int,
		@lClassificationNo nvarchar(50),
		@lAccessionNo nvarchar(50),
		@lNoOfPages int,
		@lPurchaseDate date,
		@lBookRemark nvarchar(300),
		@lBillNumber nvarchar(100),
		@lYearOfPublication nvarchar(50),
		@lBookEntryDate date,
		@lBookGroup1Id int,
		@lBookGroup2Id int
		
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(25),
		Title nvarchar(100),
		Publisher nvarchar(200),
		Supplier nvarchar(200),
		Author nvarchar(200),
		BookSubject nvarchar(200),
		BookLanguage nvarchar(200),
		Location nvarchar(200),
		Edition nvarchar(50),
		ISBNNumber nvarchar(100),
		Price decimal(12,2),
		Currency nvarchar(100),
		BookTag nvarchar(200),
		BookCustomTag nvarchar(200),
		BookDepartment nvarchar(150),
		ClassNumber nvarchar(50),
		BookVolume int,
		NoOfCopies int,
		ClassificationNo nvarchar(50),
		AccessionNo nvarchar(50), 
		NoOfPages int,
		PurchaseDate date,
		BookRemark nvarchar(300),
		BillNumber nvarchar(100),
		YearOfPublication nvarchar(50),
		BookEntryDate date,
		BookGroup1Id int,
		BookGroup2Id int
	)
		
	INSERT INTO #tTable
	(
		Code,
		Title,
		Publisher,
		Supplier,
		Author,
		BookSubject,
		BookLanguage,
		Location,
		Edition,
		ISBNNumber,
		Price,
		Currency,
		BookTag,
		BookCustomTag,
		BookDepartment,
		ClassNumber,
		BookVolume,
		NoOfCopies,
		ClassificationNo,
		AccessionNo, 
		NoOfPages,
		PurchaseDate,
		BookRemark ,
		BillNumber,
		YearOfPublication,
		BookEntryDate,
		BookGroup1Id, 
		BookGroup2Id
	)
	SELECT
		Code,
		Title,
		Publisher,
		Supplier,
		Author,
		BookSubject,
		BookLanguage,
		Location,
		Edition,
		ISBNNumber,
		Price,
		Currency,
		BookTag,
		BookCustomTag,
		BookDepartment,
		ClassNumber,
		BookVolume,
		NoOfCopies,
		ClassificationNo,
		AccessionNo, 
		NoOfPages,
		PurchaseDate,
		BookRemark ,
		BillNumber,
		YearOfPublication,
		BookEntryDate,
		BookGroup1Id,
		BookGroup2Id 
		
	FROM OPENXML (@intDoc, '/Table/ImportBook', 1)
	WITH
	( 
		Code nvarchar(25) '@Code',			
		Title nvarchar(100) '@Title',			
		Publisher nvarchar(200) '@Publisher',			
		Supplier nvarchar(200) '@Supplier',			
		Author nvarchar(200) '@Author',			
		BookSubject nvarchar(200) '@BookSubject',			
		BookLanguage nvarchar(200) '@BookLanguage',			
		Location nvarchar(200) '@Location',			
		Edition nvarchar(50) '@Edition',			
		ISBNNumber nvarchar(100) '@ISBNNumber',			
		Price decimal(12,2) '@Price',			
		Currency nvarchar(100) '@Currency',			
		BookTag nvarchar(200) '@BookTag',			
		BookCustomTag nvarchar(200) '@BookCustomTag',
		BookDepartment nvarchar(150) '@BookDepartment',
		ClassNumber nvarchar(50) '@ClassNumber',
		BookVolume int '@BookVolume',
		NoOfCopies int '@NoOfCopies',
		ClassificationNo nvarchar(50) '@ClassificationNo',
		AccessionNo nvarchar(50) '@AccessionNo',
		NoOfPages int '@NoOfPages',
		PurchaseDate date '@PurchaseDate',
		BookRemark nvarchar(300) '@BookRemark',
		BillNumber nvarchar(100) '@BillNumber',
		YearOfPublication nvarchar(100) '@YearOfPublication',
		BookEntryDate date '@BookEntryDate',
		BookGroup1Id int '@BookGroup1Id',
		BookGroup2Id int '@BookGroup2Id'
	)
	
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 

BEGIN
		SET @lCode = ''
		SET @lTitle = ''
		SET @lPublisher = ''
		SET @lSupplier = ''
		SET @lAuthor = ''
		SET @lBookSubject = ''
		SET @lBookLanguage = ''
		SET @lLocation = ''
		SET @lEdition = ''
		SET @lISBNNumber = ''
		SET @lPrice = 0
		SET @lCurrency = ''
		SET @lBookTag = ''
		SET @lBookCustomTag = ''
		SET @lBookDepartment = ''
		SET @lClassNumber = ''
		SET @lBookVolume = 0
		SET @lNoOfCopies = 0
		SET @lClassificationNo = ''
		SET @lAccessionNo = ''
		SET @lNoOfPages =0
		SET @lPurchaseDate = NULL
		SET @lBookRemark = ''
		SET @lBillNumber =''
		SET @lYearOfPublication ='' 
		SET @lBookEntryDate = NULL
		SET @lBookGroup1Id = 0
		SET @lBookGroup2Id = 0

SELECT		
		@lCode = Code,
		@lTitle = Title,
		@lPublisher = Publisher,
		@lSupplier = Supplier,
		@lAuthor = Author,
		@lBookSubject = BookSubject,
		@lBookLanguage = BookLanguage,
		@lLocation = Location,
		@lEdition = Edition,
		@lISBNNumber = ISBNNumber,
		@lPrice = Price,
		@lCurrency = Currency,
		@lBookTag = BookTag,
		@lBookCustomTag = BookCustomTag,
		@lBookDepartment = BookDepartment,
		@lClassNumber = ClassNumber,
		@lBookVolume = BookVolume,
		@lNoOfCopies = NoOfCopies,
		@lClassificationNo=ClassificationNo,
		@lAccessionNo=AccessionNo,
		@lNoOfPages=NoOfPages,
		@lPurchaseDate=PurchaseDate,
		@lBookRemark=BookRemark,
		@lBillNumber=BillNumber,
		@lYearOfPublication=YearOfPublication,
		@lBookEntryDate=BookEntryDate,
		@lBookGroup1Id=BookGroup1Id,
		@lBookGroup2Id=BookGroup2Id
			
											 	 
FROM #tTable WHERE Id = @lCount  

	BEGIN TRY
		BEGIN TRANSACTION
	 IF NOT EXISTS(select 1 from sLibrary.tBookMaster where Code=@lCode AND LibraryId = @rLibraryId)
  BEGIN	
		EXEC [sLibrary].[pBookMasterAdd] 0,@lCode,@lTitle,@lPublisher,@lSupplier,@lAuthor,@lBookSubject,
		@lBookLanguage,@lLocation,@lEdition,@lISBNNumber,@lPrice,@lCurrency,@lBookTag,@lBookCustomTag,		
		NULL,1,@rOrgGroupId,@rBatchId,@rLibraryId,@rUserId,@rUserId,
		@lBookDepartment,@lClassNumber,@lBookVolume,@lNoOfCopies,@lClassificationNo,@lAccessionNo,@lNoOfPages,@lPurchaseDate,
		@lBookRemark,@lBillNumber,@lYearOfPublication,@lBookEntryDate,NULL,@lBookGroup1Id,@lBookGroup2Id
	END
	 ELSE	 
	 BEGIN	
		  UPDATE  sLibrary.tBookMaster
		  SET Title=@lTitle,Publisher=@lPublisher,Supplier=@lSupplier,Author=@lAuthor,BookSubject=@lBookSubject,BookLanguage=@lBookLanguage,Location=@lLocation,
			Edition=@lEdition,ISBNNumber=@lISBNNumber,Price=@lPrice,Currency=@lCurrency,BookTag=@lBookTag,BookCustomTag=@lBookCustomTag,ResourceTypeId=1,						
		    UpdatedUserId=@rUserId,UpdatedDateTime=sCommon.fGetDate(),BookDepartment=@lBookDepartment,ClassNumber=@lClassNumber,BookVolume=@lBookVolume,
			NoOfCopies=@lNoOfCopies,ClassificationNo=@lClassificationNo ,AccessionNo=@lAccessionNo,NoOfPages=@lNoOfPages,PurchaseDate=@lPurchaseDate,
			BookRemark=@lBookRemark,BillNumber=@lBillNumber,YearOfPublication=@lYearOfPublication,BookEntryDate=@lBookEntryDate,BookGroup1Id=@lBookGroup1Id,BookGroup2Id=@lBookGroup2Id
	      WHERE  Code=@lCode AND LibraryId = @rLibraryId
		 END
		 SET @lCount = @lCount - 1
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	Rollback Transaction	
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	Return
	END CATCH				
END

	SELECT 1
	END TRY
	BEGIN CATCH
	
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sLibrary].[pImportBook_Update_Dynamicly]
@rOrgId int,
@rUserId bigint,
@rCode varchar(200) = null, 
@rTitle varchar(300) = null,
@rPublisher nvarchar(200)=null,
@rSupplier nvarchar(200)=null,
@rAuthor nvarchar(200)=null,
@rBookSubject nvarchar(200)=null,
@rBookLanguage nvarchar(200)=null,
@rLocation nvarchar(200)=null,
@rEdition nvarchar(50)=null,
@rISBNNumber nvarchar(100)=null,
@rPrice decimal(12,2)=null,
@rCurrency nvarchar(100)=null,
@rBookTag nvarchar(200)=null,
@rBookCustomTag nvarchar(200)=null,
@rBookDepartment nvarchar(150)=null,
@rClassNumber nvarchar(50)=null,
@rBookVolume int=null,
@rNoOfCopies int=null,
@rClassificationNo nvarchar(50)=null,
@rAccessionNo nvarchar(50)=null, 
@rNoOfPages int=null,
@rPurchaseDate date=null,
@rBookRemark nvarchar(300)=null,
@rBillNumber nvarchar(100)=null,
@rYearOfPublication nvarchar(50)=null,
@rBookEntryDate date=null,
@rLibraryId int,
@rStatusId int,
@rRemark nvarchar(150)=null,
@rBatchId int,
@rDueDate date=null,
@rBookGroup1Id int,
@rBookGroup2Id int

as
begin	
	
	
	declare @Id bigint = 0
	select @Id = Id from sLibrary.tBookMaster  where Code = @rCode and  LibraryId = @rLibraryId
	select @Id = isnull(@Id,0)
	declare @lNextNumber bigint
	
	 
	if @rTitle <> ''
	select @rTitle = [sSetup].[fPortalXMLTagsReplaceReverse](@rTitle)
	if @rPublisher <> ''
	select @rPublisher = [sSetup].[fPortalXMLTagsReplaceReverse](@rPublisher)
	
	if @rSupplier <> ''
	select @rSupplier = [sSetup].[fPortalXMLTagsReplaceReverse](@rSupplier)

	 if @rAuthor <> ''
	select @rAuthor = [sSetup].[fPortalXMLTagsReplaceReverse](@rAuthor)
	 if @rBookSubject <> ''
	select @rBookSubject = [sSetup].[fPortalXMLTagsReplaceReverse](@rBookSubject)
	 if @rBookLanguage <> ''
	select @rBookLanguage = [sSetup].[fPortalXMLTagsReplaceReverse](@rBookLanguage)
	if @rLocation <> ''
	select @rLocation= [sSetup].[fPortalXMLTagsReplaceReverse](@rLocation)
	if @rEdition <> ''
	select @rEdition= [sSetup].[fPortalXMLTagsReplaceReverse](@rEdition)
	if @rISBNNumber <> ''
	select @rISBNNumber= [sSetup].[fPortalXMLTagsReplaceReverse](@rISBNNumber)
	if @rCurrency <> ''
	select @rCurrency= [sSetup].[fPortalXMLTagsReplaceReverse](@rCurrency)
	if @rBookTag <> ''
	select @rBookTag= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookTag)
		if @rBookCustomTag<> ''
	select @rBookCustomTag= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookCustomTag)
	if @rBookDepartment <> ''
	select @rBookDepartment= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookDepartment)
	if @rClassNumber <> ''
	select @rClassNumber= [sSetup].[fPortalXMLTagsReplaceReverse](@rClassNumber)
	if @rBookVolume <> ''
	select @rBookVolume= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookVolume)
	if @rNoOfCopies <> ''
	select @rNoOfCopies= [sSetup].[fPortalXMLTagsReplaceReverse](@rNoOfCopies)
	if @rClassificationNo <> ''
	select @rClassificationNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rClassificationNo)
	if @rAccessionNo<> ''
	select @rAccessionNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rAccessionNo)
	if @rNoOfPages<> ''
	select @rNoOfPages= [sSetup].[fPortalXMLTagsReplaceReverse](@rNoOfPages)
	if @rPurchaseDate<> ''
	select @rPurchaseDate= [sSetup].[fPortalXMLTagsReplaceReverse](@rPurchaseDate)
	if @rBookRemark<> ''
	select @rBookRemark= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookRemark)
	if @rBillNumber<> ''
	select @rBillNumber= [sSetup].[fPortalXMLTagsReplaceReverse](@rBillNumber)
	if @rYearOfPublication<> ''
	select @rYearOfPublication= [sSetup].[fPortalXMLTagsReplaceReverse](@rYearOfPublication)
	if @rBookEntryDate<> ''
	select @rBookEntryDate= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookEntryDate)
	if @rPrice<> 0
	select @rPrice= [sSetup].[fPortalXMLTagsReplaceReverse](@rPrice)
	if @rRemark<> ''
	select @rRemark= [sSetup].[fPortalXMLTagsReplaceReverse](@rRemark)
	if @rBookGroup1Id<> ''
	select @rBookGroup1Id= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookGroup1Id)
	if @rBookGroup2Id<> ''
	select @rBookGroup2Id= [sSetup].[fPortalXMLTagsReplaceReverse](@rBookGroup2Id)
	
	begin

		UPDATE sLibrary.tBookMaster
		SET 
		Title = case when isnull(@rTitle,'') <> '' then @rTitle else Title end
		,Publisher   = case when isnull(@rpublisher,'') <> '' then @rpublisher else Publisher end
		,Supplier     = case when isnull(@rSupplier,'') <> '' then @rSupplier else Supplier end
		,Author     = case when isnull(@rAuthor,'') <> '' then @rAuthor else Author end
		,Location     = case when isnull(@rLocation,'') <> '' then @rLocation else Location end
		,Edition     = case when isnull(@rEdition,'') <> '' then @rEdition else Edition end
		,BookSubject = case when isnull(@rBookSubject,'') <> '' then @rBookSubject else BookSubject end
		,BookLanguage   = case when isnull(@rBookLanguage,'') <> '' then @rBookLanguage else BookLanguage end
		,Price     = case when isnull(@rPrice,0) <> 0 then @rPrice else Price end
		,Currency     = case when isnull(@rCurrency,'') <> '' then @rCurrency else Currency end
		,ISBNNumber=case when isnull(@rISBNNumber,'') <> '' then @rISBNNumber else ISBNNumber end
		,BookTag   = case when isnull(@rBookTag,'') <> '' then @rBookTag else BookTag end
		,BookCustomTag     = case when isnull(@rBookCustomTag,'') <> '' then @rBookCustomTag else BookCustomTag end
		,BookDepartment     = case when isnull(@rBookDepartment,'') <> '' then @rBookDepartment else BookDepartment end
		,ClassNumber = case when isnull(@rClassNumber,'') <> '' then @rClassNumber else ClassNumber end
		,BookVolume   = case when isnull(@rBookVolume,'') <> '' then @rBookVolume else BookVolume end
		,NoOfCopies     = case when isnull(@rNoOfCopies,'') <> '' then @rNoOfCopies else NoOfCopies end
		,ClassificationNo     = case when isnull(@rClassificationNo,'') <> '' then @rClassificationNo else ClassificationNo end
		,AccessionNo = case when isnull(@rAccessionNo,'') <> '' then @rAccessionNo else AccessionNo end
		,NoOfPages   = case when isnull(@rNoOfPages,'') <> '' then @rNoOfPages else NoOfPages end
		,PurchaseDate     = case when isnull(@rPurchaseDate,'') <> '' then @rPurchaseDate else PurchaseDate end
		,BookRemark     = case when isnull(@rBookRemark,'') <> '' then @rBookRemark else BookRemark end
		,BillNumber     = case when isnull(@rBillNumber,'') <> '' then @rBillNumber else BillNumber end
		,YearOfPublication     = case when isnull(@rYearOfPublication,'') <> '' then @rBookRemark else YearOfPublication end
		,BookEntryDate     = case when isnull(@rBookEntryDate,'') <> '' then @rBookEntryDate else BookEntryDate end
		,BookGroup1Id = case when isnull(@rBookGroup1Id,'') <> '' then @rBookGroup1Id else BookGroup1Id end
		,BookGroup2Id = case when isnull(@rBookGroup2Id,'') <> '' then @rBookGroup2Id else BookGroup2Id end
		,UpdatedUserId = @rUserId
		,UpdatedDateTime = sCommon.fGetDate()
		WHERE Id = @Id and LibraryId= @rLibraryId
		  
		IF @rStatusId<> 0
		BEGIN
		 UPDATE sLibrary.tBookLog
	    SET
			IsCurrentStatus=0,
			UpdatedUserId=@rUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE IsCurrentStatus = 1 AND ResourceSourceId = @Id

	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tBookLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO sLibrary.tBookLog
		(
			Id,	ReaderSourceTypeId,ReaderSourceId,ResourceSourceTypeId,ResourceSourceId,
			LogDate,DueDate,StatusId,Remark,IsCurrentStatus,OrgId,BatchId,CreatedUserId,CreatedDateTime,LibraryId
		)
	VALUES
	(@lNextNumber,NUll,NUll,1,@Id,sCommon.fGetDate(),@rDueDate,@rStatusId,@rRemark,2009,
	@rOrgId,@rBatchId,@rUserId,sCommon.fGetDate(),@rLibraryId)
		END
			END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sLibrary].[pImportBookIssueReturn]
@rXmlDoc nvarchar(MAX) = ''

			
AS
SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT


DECLARE @lReaderSourceTypeId smallint = 0,
		@lReaderSourceId bigint = 0,
		@lResourceSourceTypeId smallint = 0,
		@lResourceSourceId bigint = 0,
		@lLogDate date = '',
		@lDueDate date = '',
		@lReturnDate date = '',
		@lStatusId int = 0,
		@lRemark nvarchar(150) = '' ,
		@lIsCurrentStatus bit = 0,
		@lOrgId int = 0,
		@lBatchId int = 0,
		@lCreatedUserId bigint = 0,
		@lLibraryId int = 0,
		@lBookActionStatusId tinyint = 0,
		@lPenaltyDays smallint = 0,
		@lPenaltyRate decimal (12,2) = 0,
		@lPenaltyAmount decimal (12,2) = 0,
		@lPenaltyTypeId tinyint = 0,
		@lTypeId tinyint = 0


	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	
	CREATE TABLE #tTable  
	(
			Id bigint identity not null,
			ReaderSourceTypeId smallint not null,
			ReaderSourceId bigint not null,
			ResourceSourceTypeId smallint not null,
			ResourceSourceId bigint not null,
			LogDate date not null,
			DueDate date not null,
			ReturnDate date not null,
			StatusId int not null,
			Remark nvarchar(150) null,
			IsCurrentStatus bit not null,
			OrgId int not null,
			BatchId int not null,
			CreatedUserId bigint not null,			
			LibraryId int not null,
			BookActionStatusId tinyint null,
			PenaltyDays smallint not null,
			PenaltyRate decimal (12,2) not null,
			PenaltyAmount decimal (12,2) not null,
			PenaltyTypeId tinyint null,
			TypeId tinyint null
	)

	INSERT INTO #tTable 
	(			
			ReaderSourceTypeId,
			ReaderSourceId,
			ResourceSourceTypeId,
			ResourceSourceId,
			LogDate,
			DueDate,
			ReturnDate,
			StatusId,
			Remark,
			IsCurrentStatus,
			OrgId,
			BatchId,
			CreatedUserId,
			LibraryId,
			BookActionStatusId,
			PenaltyDays,
			PenaltyRate,
			PenaltyAmount,
			PenaltyTypeId,
			TypeId
	)
	SELECT		
		A.ReaderSourceTypeId,
		A.ReaderSourceId,			
		A.ResourceSourceTypeId,
		A.ResourceSourceId,
		A.LogDate,
		A.DueDate,		
		A.ReturnDate, 
		A.StatusId,				
		A.Remark,		
		A.IsCurrentStatus,
		A.OrgId,
		A.BatchId,
		A.CreatedUserId,
		A.LibraryId,
		A.BookActionStatusId,
		A.PenaltyDays,
		A.PenaltyRate,
		A.PenaltyAmount,
		A.PenaltyTypeId,
		A.TypeId			
		
	FROM OPENXML (@intDoc, '/Table/ImportBookIssueReturn', 1)
	WITH
	(						
		ReaderSourceTypeId smallint '@ReaderSourceTypeId',
		ReaderSourceId bigint '@ReaderSourceId',
		ResourceSourceTypeId smallint '@ResourceSourceTypeId',
		ResourceSourceId bigint '@ResourceSourceId',		
		LogDate date '@LogDate',
		DueDate date '@DueDate',
		ReturnDate date '@ReturnDate',		 		
		StatusId int '@StatusId',		
		Remark nvarchar(150) '@Remark',		
		IsCurrentStatus bit '@IsCurrentStatus',
		OrgId int '@OrgId',
		BatchId int '@BatchId',
		CreatedUserId bigint '@CreatedUserId',
		LibraryId int '@LibraryId',
		BookActionStatusId tinyint '@BookActionStatusId',			
		PenaltyDays smallint '@PenaltyDays',
		PenaltyRate decimal (12,2) '@PenaltyRate',
		PenaltyAmount decimal(12,2) '@PenaltyAmount',
		PenaltyTypeId tinyint '@PenaltyTypeId',
		TypeId tinyint '@TypeId'
	)A 

	EXEC sp_xml_removedocument @intDoc

	--SELECT * FROM #tTable

DECLARE @lCount int
DECLARE @lBookLogId bigint = 0
DECLARE @lPrevBookLogId bigint = 0
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 
BEGIN
	SELECT
	@lReaderSourceTypeId = ReaderSourceTypeId,
	@lReaderSourceId = ReaderSourceId,
	@lResourceSourceTypeId = ResourceSourceTypeId,
	@lResourceSourceId = ResourceSourceId,
	@lLogDate = LogDate,
	@lDueDate = DueDate,
	@lReturnDate = ReturnDate,
	@lStatusId = StatusId,
	@lRemark = Remark,
	@lIsCurrentStatus = IsCurrentStatus,
	@lOrgId = OrgId,
	@lBatchId = BatchId,
	@lCreatedUserId = CreatedUserId,
	@lLibraryId = LibraryId,
	@lBookActionStatusId = BookActionStatusId,
	@lPenaltyDays = PenaltyDays,
	@lPenaltyRate = PenaltyRate,
	@lPenaltyAmount = PenaltyAmount,
	@lPenaltyTypeId = PenaltyTypeId,
	@lTypeId = TypeId
	FROM #tTable WHERE Id = @lCount

	SELECT @lPrevBookLogId = Id FROM sLibrary.tBookLog WHERE ResourceSourceId = @lResourceSourceId AND StatusId = 523 AND IsCurrentStatus = 1

	IF(@lTypeId = 1)
	BEGIN
	EXEC [sLibrary].[pBookLogAdd] @lReaderSourceTypeId, @lReaderSourceId, @lResourceSourceTypeId, @lResourceSourceId, @lLogDate, @lDueDate, @lStatusId, @lRemark, @lIsCurrentStatus, 
	@lOrgId, @lBatchId, @lCreatedUserId, @lLibraryId, @lBookActionStatusId
	END
	ELSE
	BEGIN
		EXEC [sLibrary].[pBookLogAdd] @lReaderSourceTypeId, @lReaderSourceId, @lResourceSourceTypeId, @lResourceSourceId, @lLogDate, @lDueDate, @lStatusId, @lRemark, @lIsCurrentStatus, 
		@lOrgId, @lBatchId, @lCreatedUserId, @lLibraryId, @lBookActionStatusId, @lBookLogId OUTPUT

		--SELECT @lBookLogId = Id FROM sLibrary.tBookLog WHERE ReaderSourceId = @lReaderSourceId AND ResourceSourceId = @lResourceSourceId AND ReaderSourceTypeId = @lResourceSourceTypeId
		--AND ReaderSourceTypeId = @lReaderSourceTypeId ANd OrgId = @lOrgId AND BatchId = @lBatchId AND LibraryId = @lLibraryId AND StatusId = 523
		
		UPDATE sLibrary.tBookLog SET ReturnDate = @lReturnDate WHERE Id = @lPrevBookLogId AND StatusId = 523

		IF(@lPenaltyDays > 0)
		BEGIN
		EXEC [sLibrary].[pBookLogPenaltyAdd] 0,@lBookLogId, @lPenaltyDays, @lPenaltyRate, @lPenaltyAmount, @lPenaltyTypeId, @lOrgId
		END
	END

	SET @lCount = @lCount - 1	
END
SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pImportBookValidateFordynamic]
@rXml varchar(max),
@rLibraryId int
as
begin

DECLARE @loXML XML
SET @loXML = CAST(@rXml AS XML)
	declare @tbl table(tid int identity(1,1),ecode varchar(200))
	insert into @tbl(ecode)
	select 
	T.c.value('@Code','varchar(200)') AS BookCode
	FROM 
	@loXML.nodes('/Table/ImportBook')T(c)
	
	declare @validate varchar(max)='',@orgid int,@cnt int,@i int
    select @cnt = count(*),@i = 1 from @tbl
	while @i <= @cnt
	begin
		declare @Code varchar(200)
		select @Code = ecode from @tbl where tid = @i
		if not exists (select 1 from [sLibrary].[tBookMaster] where Code = @Code AND LibraryId = @rLibraryId )
		begin
			select @validate = @validate + 'Book code Like : '+@Code+' Not Found ,<br/>' 
		end
		select @i = @i + 1;
	end
	
	select isnull(@validate,'') as valid
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pIssueSettingAdd]
	 
        @rSourceTypeId smallint,
        @rSourceId bigint,
		@rNoOfBookIssuable smallint,
		@rIssueDays smallint,
		@rPenaltyPerDay decimal(12,2),
		@rReserveDays smallint,
		@rCreatedUserId bigint,
		@rLibraryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	IF NOT EXISTS(Select SourceId from sLibrary.tIssueSetting WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND LibraryId = @rLibraryId )
	BEGIN
	INSERT INTO sLibrary.tIssueSetting
		(
			SourceTypeId,
			SourceId,
			NoOfBookIssuable,
			IssueDays,
			PenaltyPerDay,
			ReserveDays,
			LibraryId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@rSourceTypeId,
			@rSourceId,
			@rNoOfBookIssuable,
			@rIssueDays,
			@rPenaltyPerDay,
			@rReserveDays,
			@rLibraryId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		    SELECT @rSourceId AS Result
	      
	END	
	ELSE
	 BEGIN
	    UPDATE  sLibrary.tIssueSetting
	    SET
			NoOfBookIssuable=@rNoOfBookIssuable,
			IssueDays=@rIssueDays,
			PenaltyPerDay=@rPenaltyPerDay,
			ReserveDays=@rReserveDays,
			LibraryId=@rLibraryId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE SourceTypeId = @rSourceTypeId
			AND SourceId=@rSourceId
			AND LibraryId = @rLibraryId
	      SELECT @rSourceId AS Result
	
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pIssueSettingDetailGet]
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rReaderSourceTypeId = 2003)
	BEGIN
	SELECT 	
			ISNULL(IS1.NoOfBookIssuable,0) AS NoOfBookIssuable,
		    ISNULL(IS1.IssueDays,0) AS IssueDays,
		    ISNULL(IS1.PenaltyPerDay,0) AS PenaltyPerDay,
		    ISNULL(IS1.ReserveDays,0) AS ReserveDays
  FROM 
				sStudent.vStudentLastAcademic SA
            INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
  WHERE
			((SA.StudentId=@rReaderSourceId) OR (@rReaderSourceId=0))
		AND SA.OrgId=@rOrgId
		AND((IS1.LibraryId = @rLibraryId)OR(@rLibraryId=0))
		--AND SA.BatchId=@rBatchId	
		
	END
	ELSE IF (@rReaderSourceTypeId = 95)
	BEGIN		
	SELECT 
			ISNULL(IS1.NoOfBookIssuable,0) AS NoOfBookIssuable,
		    ISNULL(IS1.IssueDays,0) AS IssueDays,
		    ISNULL(IS1.PenaltyPerDay,0) AS PenaltyPerDay,
		    ISNULL(IS1.ReserveDays,0) AS ReserveDays
  FROM 
				sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id=EJD.OrganizationDepartmentId
            INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004
  WHERE
			((EM.Id=@rReaderSourceId) OR (@rReaderSourceId=0)) AND ISNULL(EM.IsOtherUser,0) = 0
		AND ODM.OrgId=@rOrgId
		AND((IS1.LibraryId = @rLibraryId)OR(@rLibraryId=0))
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pIssueSettingGet]
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int,
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
if(@rSourceTypeId=2005)
Begin
	SELECT 	
			2005 AS SourceTypeId,
			BC.ClassId AS SourceId,
			BC.ClassName AS Source,
			BC.OrderIndex,
		    ISNULL(IS1.NoOfBookIssuable,0) AS NoOfBookIssuable,
		    ISNULL(IS1.IssueDays,0) AS IssueDays,
		    ISNULL(IS1.PenaltyPerDay,0) AS PenaltyPerDay,
		    ISNULL(IS1.ReserveDays,0) AS ReserveDays,
		   ISNULL(IS1.LibraryId,'') As LibraryId
  FROM 
				sSetup.vBatchClass BC 
            LEFT JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=BC.ClassId AND IS1.SourceTypeId=2005 AND ((IS1.LibraryId=@rLibraryId) OR (@rLibraryId=0))
  WHERE
			 ((IS1.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((BC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BC.DepartmentId=@rDepartmentId) OR(@rDepartmentId=0))
		--AND ((IS1.LibraryId=@rLibraryId) OR (@rLibraryId=0))
End		
		
If(@rSourceTypeId=2004)	
Begin		
	SELECT 
			2004 AS SourceTypeId,
			ODM.Id AS SourceId,
			ODM.Title AS Source,
			0 AS OrderIndex,
		    ISNULL(IS1.NoOfBookIssuable,0) AS NoOfBookIssuable,
		    ISNULL(IS1.IssueDays,0) AS IssueDays,
		    ISNULL(IS1.PenaltyPerDay,0) AS PenaltyPerDay,
		    ISNULL(IS1.ReserveDays,0) AS ReserveDays,
		    ISNULL(IS1.LibraryId,'') As LibraryId
  FROM 
				sSetup.tDepartmentMaster ODM
            LEFT JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004 AND ((IS1.LibraryId=@rLibraryId) OR (@rLibraryId=0))
  WHERE
			((IS1.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ODM.OrgId=@rOrgId
End
if(@rSourceTypeId=2003)
Begin		
	SELECT 
		2003 AS SourceTypeId,
		SA.StudentId AS SourceId,
		SA.Name AS Source,
		0 AS OrderIndex,
		ISNULL(IS1.NoOfBookIssuable,0) AS NoOfBookIssuable,
		ISNULL(IS1.IssueDays,0) AS IssueDays,
		ISNULL(IS1.PenaltyPerDay,0) AS PenaltyPerDay,
		ISNULL(IS1.ReserveDays,0) AS ReserveDays,
		ISNULL(IS1.LibraryId,'') As LibraryId 
	from 
		sStudent.vStudentAcademic  SA 
		Left Join sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.StudentId AND IS1.SourceTypeId=2003 AND ((IS1.LibraryId=@rLibraryId) OR (@rLibraryId=0))
    WHERE
		((IS1.SourceId=@rSourceId) OR (@rSourceId=0))
		AND SA.OrgId=@rOrgId 
		AND StatusId=1 
		AND DivisionId= @rDivisionId
		AND BatchId=@rBatchId
		AND IsActiveBatch=1 
		
	ORDER BY RollNo
end
if(@rSourceTypeId=95)
Begin	

	SELECT 
		95 AS SourceTypeId,
		EC.EmployeeId AS SourceId,
		EC.EmployeeName AS Source,
		0 AS OrderIndex,
		ISNULL(IS1.NoOfBookIssuable,0) AS NoOfBookIssuable,
		ISNULL(IS1.IssueDays,0) AS IssueDays,
		ISNULL(IS1.PenaltyPerDay,0) AS PenaltyPerDay,
		ISNULL(IS1.ReserveDays,0) AS ReserveDays,
		ISNULL(IS1.LibraryId,'') As LibraryId 
	from 
		sHrm.vEmployeeCommunication  EC 
		Left Join sLibrary.tIssueSetting IS1 ON IS1.SourceId=EC.EmployeeId AND IS1.SourceTypeId=95 AND ((IS1.LibraryId=@rLibraryId) OR (@rLibraryId=0))
    WHERE
		((IS1.SourceId=@rSourceId) OR (@rSourceId=0))
		AND EC.OrgId=@rOrgId 
		AND StatusId=7
		AND DepartmentId= @rDepartmentId
	ORDER BY Code
end
if(@rSourceTypeId=2016)
Begin	
	SELECT 
		2016 AS SourceTypeId,
		DM.Id AS SourceId,
		DM.DisplayTitle AS Source,
		0 AS OrderIndex,
		ISNULL(IS1.NoOfBookIssuable,0) AS NoOfBookIssuable,
		ISNULL(IS1.IssueDays,0) AS IssueDays,
		ISNULL(IS1.PenaltyPerDay,0) AS PenaltyPerDay,
		ISNULL(IS1.ReserveDays,0) AS ReserveDays,
		ISNULL(IS1.LibraryId,'') As LibraryId 
	from 
		sSetup.tDivisionMaster DM
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND CM.OrgId=@rOrgId
		Left Join sLibrary.tIssueSetting IS1 ON IS1.SourceId=DM.Id AND IS1.SourceTypeId=2016 AND ((IS1.LibraryId=@rLibraryId) OR (@rLibraryId=0))
    WHERE
		((IS1.SourceId=@rSourceId) OR (@rSourceId=0))
		AND DM.OrgId=@rOrgId 
		AND CM.Id=@rClassId
	 Order by DM.OrderIndex
end
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryAttendanceAdd]

	@rId bigint,
	@rLibraryId int,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rGuestName nvarchar(100),	
	@rAttendanceDate date,
	@rInTime time(7),
	@rOutTime time(7),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rOrgGroupBatchId int,
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber bigint     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tLibraryAttendance', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sLibrary.tLibraryAttendance
		(
			Id,
			LibraryId,
			SourceTypeId,
			SourceId,
			GuestName,
			AttendanceDate,
			InTime,
			OutTime,
			Remark,
			CreatedUserId,
			OrgGroupBatchId
		)
	VALUES
		(
			@lNextNumber,
			@rLibraryId,
			@rSourceTypeId,
			@rSourceId,
			@rGuestName,
			@rAttendanceDate,
			@rInTime,
			@rOutTime,
			@rRemark,
			@rCreatedUserId,
			@rOrgGroupBatchId
		)
		SELECT 1 AS Result
	END	 
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tLibraryAttendance
	    SET
	        Id=@rId,
			LibraryId=@rLibraryId,
			SourceTypeId=@rSourceTypeId,
			SourceId=@rSourceId,
			GuestName=@rGuestName,
			AttendanceDate=@rAttendanceDate,
			InTime=@rInTime,
			OutTime=@rOutTime,
			Remark=@rRemark,
			CreatedUserId=@rCreatedUserId
	     WHERE Id = @rId 	  
	     
	     SELECT 11 AS Result 
	END  
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryAttendanceDivisionWIseAdd]

	 
	@rLibraryId int,
	 
	@rDetail nvarchar(max),
	 
	@rAttendanceDate date,
	@rInTime time(7),
	@rOutTime time(7),
	 
	@rCreatedUserId bigint,
	@rOrgGroupBatchId int,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rDetail=REPLACE(@rDetail,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	 BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rDetail
	
	--Delete  LA   from   sLibrary.tLibraryAttendance  LA Inner Join sStudent.vStudentAcademic A ON LA.SourceId = A.StudentId 
	--			where LA.LibraryId = @rLibraryId and LA.SourceTypeId = 2003 and  LA.OrgGroupBatchId=@rOrgGroupBatchId 
	--			AND AttendanceDate = @rAttendanceDate AND A.DivisionId=@rDivisionId
				--)
	 
	
	 
	DECLARE @lNextNumber bigint     
	 
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tLibraryAttendance', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sLibrary.tLibraryAttendance
		(
			Id,
			LibraryId,
			SourceTypeId,
			SourceId,
			GuestName,
			AttendanceDate,
			InTime,
			OutTime,
			Remark,
			CreatedUserId,
			OrgGroupBatchId
		)
	Select 
			 @lNextNumber+ ROW_NUMBER() OVER(ORDER BY A.SourceId),
			@rLibraryId,
			2003,
			A.SourceId,
			'',
			@rAttendanceDate,
			@rInTime,
			@rOutTime,
			A.Remark,
			@rCreatedUserId,
			@rOrgGroupBatchId
	from OPENXML (@intDoc, '/Table/RowData', 1)
	WITH
	(
		 
		SourceId bigint '@SourceId',
		Remark nvarchar(200) '@Remark' 
	)A  
	Left join sLibrary.tLibraryAttendance LA ON A.SourceId = LA.SourceId AND LA.LibraryId=@rLibraryId AND LA.AttendanceDate = @rAttendanceDate AND LA.OrgGroupBatchId=@rOrgGroupBatchId
	WHERE ISNULL(LA.Id,0)=0

	 	EXEC sp_xml_removedocument @intDoc

	SELECT @lNextNumber = MAX(ID) FROM sLibrary.tLibraryAttendance Where OrgGroupBatchId=@rOrgGroupBatchId    
	EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sLibrary.tLibraryAttendance', @rCurrentNumber = @lNextNumber 

		SELECT 1 AS Result
	 
		
		COMMIT TRANSACTION
		
	----END TRY	
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryAttendanceDivisionWIseoutTimeAdd]

	 
	@rLibraryId int,
	 
	@rDetail nvarchar(max),
	 
	@rAttendanceDate date,
  
	@rOutTime time(7),
	@rRemark nvarchar(200),
	@rOrgGroupBatchId int
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 BEGIN TRANSACTION	
	SET @rDetail=REPLACE(@rDetail,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rDetail	
		Update 
			sLibrary.tLibraryAttendance 
		set OutTime =@rOutTime,
			Remark=A.Remark
		From 
		(
		Select  SourceId ,Remark
			FROM OPENXML (@intDoc, '/Table/RowData', 1)
			WITH
			( 
				SourceId bigint '@SourceId',
				Remark nvarchar(200) '@Remark'
			))A
			Where sLibrary.tLibraryAttendance.SourceId=A.SourceId 
			And sLibrary.tLibraryAttendance.LibraryId=@rLibraryId
			 And OrgGroupBatchId=@rOrgGroupBatchId AND SourceTypeId=2003
			 ANd AttendanceDate=@rAttendanceDate
	EXEC sp_xml_removedocument @intDoc
		COMMIT TRANSACTION
		
	 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryAttendanceGet]
          
           @rId bigint,
           @rLibraryId int,
           @rSourceTypeId smallint,
           @rName nvarchar(200),
           @rCode nvarchar(20),
           @rFromAttendanceDate date,
           @rToAttendanceDate date,
           @rOrgGroupBatchId int,
           @rOrgId int=0
           
AS
SET NOCOUNT ON
			SET @rName = sCommon.fSearchStringGet(@rName)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
BEGIN
SELECT   
	   LA.Id AS LibraryAttendanceId,
	   LA.LibraryId,
	   
		(CASE WHEN LA.SourceTypeId = 95 THEN	'Employee'
			 WHEN LA.SourceTypeId = 2003 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,

		(CASE WHEN LA.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN LA.SourceTypeId = 2003 THEN vSF.Name
			ELSE
			ISNULL(LA.GuestName,'') 
			END) AS Name,
			
		(CASE WHEN LA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN LA.SourceTypeId = 2003 THEN DM.Title
			ELSE '' END) AS DepartmentName,		 	
		 
		(CASE WHEN LA.SourceTypeId = 95 THEN	Emp.Code
			 WHEN LA.SourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
			
		(CASE WHEN LA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN LA.SourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
			 	 
	   LA.SourceId,
	   LA.SourceTypeId,
	   LA.GuestName,
	   LA.AttendanceDate,
	   LA.InTime,
	   LA.OutTime,
	   LA.Remark,
	   (CASE WHEN LA.OutTime = Convert(time,'00:00:00') THEN ''
		ELSE convert(varchar(5),DateDiff(SECOND, LA.InTime, LA.OutTime)/3600)+
		':'+convert(varchar(5),DateDiff(SECOND, LA.InTime, LA.OutTime)%3600/60)+
		':'+convert(varchar(5),(DateDiff(SECOND, LA.InTime, LA.OutTime)%60))
		END) AS TotalTime,
		ISNULL(OM.Id,0) AS OrgId,
		ISNULL(OM.DisplayTitle,'') AS OrgName
		--(CASE WHEN LA.SourceTypeId = 95 THEN ''
		--	WHEN LA.SourceTypeId = 2003 THEN vSF.SUId
		--	ELSE '' END) AS SUId		 
		
	   
  FROM  sLibrary.tLibraryAttendance LA
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = LA.SourceId AND LA.SourceTypeId = 95 
				--AND(((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = '')) AND @rSourceTypeId = 95  )
				--AND(((Emp.EmployeeName like @rName) OR (ISNULL(@rName,'') = '')) AND @rSourceTypeId = 95 )
				
		LEFT JOIN 
		sStudent.vStudentAcademic vSF ON vSF.StudentId = LA.SourceId AND LA.SourceTypeId = 2003
		and vsf.statusid = 1  -- Added for mantis : 33185 by Nilesh
		and vsf.isactivebatch = 1 -- Added for mantis : 33185 by Nilesh
		--sStudent.vStudentLastAcademic vSF ON vSF.StudentId = LA.SourceId AND LA.SourceTypeId = 2003 -- Commented
		
		--AND(((vSF.Code like @rCode) OR (ISNULL(@rCode,'') = '')) AND @rSourceTypeId = 2003)
		--AND(((vSF.Name like @rName) OR (ISNULL(@rName,'') = '')) AND @rSourceTypeId = 2003)
		--AND(vSF.BatchId= @rBatchId)
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = vSF.DepartmentId		
		LEFT JOIN sSetup.tOrganizationMaster OM ON ((OM.Id = Emp.OrgId) OR (OM.Id = vSF.OrgId))
  WHERE 
  
	LA.LibraryId=@rLibraryId
	AND LA.OrgGroupBatchId=@rOrgGroupBatchId
	AND ((LA.Id=@rId) OR (@rId=0))
	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
	AND ((LA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND vSF.Name like @rName) 
		OR (ISNULL(@rName,'')='') OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.EmployeeName LIKE @rName) OR (ISNULL(@rName,'')='') 
		OR ((@rSourceTypeId =1 OR (@rSourceTypeId=0)) AND LA.GuestName LIKE @rName) OR (ISNULL(@rName,'')=''))
    AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND vSF.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
        OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
	AND (LA.AttendanceDate>=@rFromAttendanceDate OR ISNULL(@rFromAttendanceDate,'')='')
	AND (LA.AttendanceDate<=@rToAttendanceDate OR ISNULL(@rToAttendanceDate,'')='')
	--AND vSF.StatusId = 1 -- Commented for mantis : 33185 by Nilesh
	--AND (vSF.IsActiveBatch = 1 OR Emp.StatusId = 7) -- Commented for mantis : 33185 by Nilesh
    ORDER BY LA.AttendanceDate,LA.InTime DESC
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryDashboardGet]            
  @rOrgGroupId int =0,      
  @BatchId int = 0,        
  @rType nvarchar(50) = '' ,
  @rCommonOrgGroupBatchId int=0       
        
WITH EXECUTE AS CALLER            
AS            
SET NOCOUNT ON            
BEGIN        
	IF(@rType = 'Book')        
		BEGIN 
			SELECT OGM.Id AS OrgGroupId ,OGM.Title AS OrgGroupName,COUNT(LB.id) AS BookCount FROM sLibrary.tLibraryMaster LB     
			INNER JOIN  sLibrary.tBookMaster BM on LB.id = BM.Libraryid      
			INNER JOIN sSetup.torggroupmaster OGM on OGM.id = LB.OrgGroupid    
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE LB.IsObsolete = 0      
			AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
			GROUP BY OGM.Title ,OGM.Id   
			ORDER BY OGM.Id
		END        
	IF(@rType = 'BookDetails')  
		BEGIN       
			SELECT SM.Title AS Title,COUNT(LB.Id) AS BookCount  
			FROM sLibrary.tLibraryMaster LB       
			INNER JOIN sLibrary.tBookMaster BM ON BM.Libraryid = LB.id     
			INNER JOIN sSetup.torggroupmaster OGM ON OGM.id = LB.OrgGroupid    
			INNER JOIN sLibrary.tBookLog BL ON BL.LibraryId = LB.id  and ResourceSourceId = BM.id and ResourceSourceTypeId = 2009   
			INNER JOIN sCommon.tstatusmaster SM ON SM.id = BL.Statusid      
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE LB.IsObsolete = 0 AND ((LB.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
			GROUP BY SM.Title   
			ORDER BY SM.Title   
		END        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryDataDelete]
	 
	@rLibraryId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DELETE FROM sLibrary.tAssignOrganization   WHERE  LibraryId=@rLibraryId
	DELETE FROM sLibrary.tBookLocationMaster  WHERE  LibraryId=@rLibraryId
	DELETE BP FROM sLibrary.tBookLogPenalty BP INNER JOIN  sLibrary.tBookLog BL ON BL.ID=BP.BookLogId  WHERE BL.LibraryId=@rLibraryId
	DELETE FROM sLibrary.tBookLog  WHERE  LibraryId=@rLibraryId
    DELETE B FROM sLibrary.tBooksForClass B INNER JOIN  sLibrary.tBookMaster BM ON B.BookId=BM.Id WHERE  LibraryId=@rLibraryId
    DELETE FROM sLibrary.tBookMaster  WHERE  LibraryId=@rLibraryId
    DELETE FROM sLibrary.tLibraryAttendance  WHERE  LibraryId=@rLibraryId
	DELETE MR FROM sLibrary.tMagazineReceive MR INNER JOIN  sLibrary.tMagazineMaster   MG ON  MG.Id=MR.MagazineId  WHERE  LibraryId=@rLibraryId
    DELETE FROM sLibrary.tMagazineMaster  WHERE LibraryId=@rLibraryId
    DELETE FROM sLibrary.tLibraryMaster  WHERE Id=@rLibraryId
    
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION SD			 
			Delete from sSecurity.tUserAccess where SourceId=@rId AND SourceTypeId = 2011
			Delete from sLibrary.tLibraryMaster where Id=@rId  
		 
		COMMIT TRANSACTION	SD
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION SD
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryDetailGet]
	 
	 @rOrgGroupId int,
	 @rOrgId int
	 
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		AO.LibraryId,
		LM.Title AS LibraryName
	FROM  
		sLibrary.tAssignOrganization AO
		INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=AO.LibraryId
  
	WHERE 
		AO.OrgId=@rOrgId  
		AND LM.OrgGroupId = @rOrgGroupId
		AND LM.IsObsolete=0
  
	ORDER BY LM.Title

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryMasterAdd]
	 
        @rId int,
        @rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rNumber int,
		@rCreatedUserId bigint,
		@rIsObsolete bit,
		@rOrgGroupId smallint,
		@rReportOrgTitle  nvarchar(200) ,
		@rSmallAddress1 nvarchar(200),
		@rSmallAddress2 nvarchar(200)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		If Exists(select Id from sLibrary.tLibraryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sLibrary.tLibraryMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sLibrary.tLibraryMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sLibrary.tLibraryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tLibraryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sLibrary.tLibraryMaster
		(
			Id,
			Number,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsObsolete,
			OrgGroupId ,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2
			
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rReportOrgTitle,
			@rSmallAddress1,
			@rSmallAddress2
		)
		
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2011
		   ,@lNextNumber
		   ,@rCreatedUserId
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tLibraryMaster
	    SET
			Title=@rTitle,
			Number=@rNumber,
			Code=@rCode,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			ReportOrgTitle=@rReportOrgTitle ,
		    SmallAddress1=@rSmallAddress1 ,
		    SmallAddress2=@rSmallAddress2 
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	SELECT 
			Id,
			ISNULL(Number,0) AS Number,
			Code,
			Title,
			IsObsolete,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2
      
  FROM 
            sLibrary.tLibraryMaster 
  WHERE   
           ((Id = @rId) OR (@rId = 0))
	       AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	       AND OrgGroupId=@rOrgGroupId
	       Order by id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryStudentGet]
          
           @rDivisionID int=0,
           @rOrgGroupBatchId int=0,
           @rOrgId int,
           @rAttendanceDate date='',
           @rLibraryId int
           
AS
SET NOCOUNT ON
			 
BEGIN
SELECT   
		StudentId AS Id,
	   code,
	   Name As Name,
	   SUId,
	   CASE WHEN LA.Id IS NUll THEN 'false' else 'true' END AS Checked,
	   LA.InTime,
	   CASE WHEN LA.OutTime=Convert(time,'00:00:00') THEN '' else LA.OutTime END AS OutTime,
	   LA.AttendanceDate,LA.Remark
	   from sStudent.vStudentAcademic A
	   LEFT JOIN sLibrary.tLibraryAttendance LA ON LA.SourceId = A.StudentId AND LibraryId=@rLibraryId AND ((convert(date,LA.AttendanceDate )= @rAttendanceDate) OR (ISNULL(@rAttendanceDate,'')='')) AND LA.OrgGroupBatchId=@rOrgGroupBatchId
	   
		Where DivisionId = @rDivisionID
		AND A.OrgGroupBatchId=@rOrgGroupBatchId
		AND A.StatusId = 1
		AND A.IsActiveBatch = 1
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pLibrarySummaryDashboard]
	@rType nvarchar(20)='',
	@rGroupBatchId bigint = 0,
	@rOrgGroupId int =0,
	@rLibraryId int =0,
	@rOrgId int =0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'BookCountGet')
		BEGIN 
		CREATE table #Table1 (TodayIssueCount int,TodayReturnCount int,TodayAddNewBook int,LostBook int,TotalBookInCirculation int,TodayDueCount int,
		DueCount int,TotalBook int,BookReturnInFuture int)
		INSERT INTO #Table1
			SELECT TodayIssueCount, TodayReturnCount,TodayAddNewBook,LostBook,TotalBookInCirculation,TodayDueCount,DueCount,TotalBook,BookReturnInFuture FROM(
				SELECT ISNULL((SELECT COUNT(BL.Id) FROM sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId 
				WHERE((LibraryId=@rLibraryId)OR(@rLibraryId=0))AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND ((BL.BatchId = @rGroupBatchId)OR(@rGroupBatchId=0))
				AND CONVERT(DATE,LogDate) = CONVERT(DATE,GETDATE())AND BL.StatusId = 523 AND BL.IsCurrentStatus =1),0)AS TodayIssueCount,
				ISNULL((SELECT COUNT(BL.Id) FROM sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId WHERE ((LibraryId=@rLibraryId)OR(@rLibraryId =0))AND ((BL.BatchId = @rGroupBatchId)OR(@rGroupBatchId=0)) AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))AND CONVERT(DATE,ReturnDate) = CONVERT(DATE,GETDATE())),0)AS TodayReturnCount,
				ISNULL(( SELECT COUNT(BM.Id) FROM sLibrary.tBookMaster BM INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BM.LibraryId  WHERE ((BM.LibraryId=@rLibraryId)OR(@rLibraryId =0))AND((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND CONVERT(DATE,BM.CreatedDateTime) = CONVERT(DATE,GETDATE())),0) AS TodayAddNewBook,
				
				ISNULL((SELECT COUNT(BL.Id) FROM  sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
				WHERE ((BL.LibraryId=@rLibraryId)OR(@rLibraryId =0))AND ((BL.BatchId = @rGroupBatchId)OR(@rGroupBatchId=0)) AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND BL.StatusId = 525),0)AS LostBook,
				
				
				ISNULL( (SELECT COUNT(BL.Id) FROM  sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId 
				WHERE ((BL.LibraryId=@rLibraryId)OR(@rLibraryId =0))AND ((BL.BatchId = @rGroupBatchId)OR(@rGroupBatchId=0)) AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND BL.StatusId = 523 AND IsCurrentStatus =1),0)AS TotalBookInCirculation,
				
				ISNULL((SELECT COUNT(BL.Id) FROM sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId 
				WHERE ((BL.LibraryId=@rLibraryId)OR(@rLibraryId =0))AND ((BL.BatchId = @rGroupBatchId)OR(@rGroupBatchId=0))
				AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  AND BL.StatusId = 523 AND BL.IsCurrentStatus =1
				 AND CONVERT(DATE,DueDate) = CONVERT(DATE,GETDATE())),0)AS TodayDueCount,
				 
				ISNULL((SELECT COUNT(BL.Id) From sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BL.BatchId INNER JOIN sSetup.tOrgGRoupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId 
				WHERE ((LibraryId=@rLibraryId)OR(@rLibraryId =0)) AND ((OrgGroupBatchId = @rGroupBatchId)OR(@rGroupBatchId =0))
				AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND BL.DueDate < getdate() 
				AND BL.DueDate > BM.FromDate AND BL.DueDate < BM.ToDate  AND BL.StatusId = 523 AND BL.IsCurrentStatus =1),0)AS DueCount,
				
				ISNULL((SELECT COUNT(BM.Id)FROM sLibrary.tBookMaster BM INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BM.LibraryId 
				 WHERE  ((BM.LibraryId=@rLibraryId)OR(@rLibraryId =0))AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))),0)AS TotalBook,
				--ISNULL(( SELECT COUNT(BL.Id) 
				-- FROM sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId WHERE 
				-- ((LibraryId=@rLibraryId)OR(@rLibraryId =0))AND ((BL.BatchId = @rGroupBatchId)OR(@rGroupBatchId=0)) AND
				--  ((LM.OrgGroupId = OrgGroupId)OR(OrgGroupId=0))AND CONVERT(DATE,BL.ReturnDate) = CONVERT(DATE,GETDATE()),0) AS BookReturnInFuture
				 ISNULL((SELECT COUNT(BL.Id) FROM sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId WHERE ((LibraryId=@rLibraryId)OR(@rLibraryId =0))  AND IsCurrentStatus=1 AND ((BL.BatchId = @rGroupBatchId)OR(@rGroupBatchId=0)) AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))AND CONVERT(DATE,DueDate) >= CONVERT(DATE,GETDATE())),0)AS BookReturnInFuture
				--ISNULL(((SELECT COUNT(BM.Id)FROM sLibrary.tBookMaster BM INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BM.LibraryId 
				--WHERE ((BM.LibraryId=@rLibraryId)OR(@rLibraryId =0))AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
				---((SELECT COUNT(BL.Id) FROM  sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId 
				--  WHERE ((LibraryId=@rLibraryId)OR(@rLibraryId =0))AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND StatusId = 526) 
				--  +(Select COUNT(BL.Id) From sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
				--   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BL.BatchId 
				--  INNER JOIN sSetup.tOrgGRoupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId WHERE ((LibraryId=@rLibraryId)OR(@rLibraryId =0)) 
				--  AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND((OrgGroupBatchId = @rGroupBatchId)OR(@rGroupBatchId =0)) 
				--  AND BL.DueDate < getdate() AND BL.DueDate > BM.FromDate AND BL.DueDate < BM.ToDate AND OGBM.IsActive =1 ))),0)AS AvailableBook
					)T
			GROUP BY  TodayIssueCount, TodayReturnCount,TodayAddNewBook,LostBook,TotalBookInCirculation,TodayDueCount,DueCount,TotalBook,BookReturnInFuture
			SELECT * FROM #Table1
		END
	ELSE IF(@rType = 'DateWiseBookCountGet')
		BEGIN
			;WITH CTE AS
				(
				SELECT convert(date,GETDATE()) sDate, DATENAME(DW, GETDATE()) sDayofWeek
				UNION ALL
				SELECT DATEADD(DAY,-1,sDate), DATENAME(DW, DATEADD(DAY,-1,sDate))
				FROM CTE
				WHERE sDate > GETDATE()-29
				)
			SELECT convert(varchar(20),C.sDate,3) AS Date,
				ISNULL((SELECT COUNT(BL.Id) FROM sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId   WHERE ((LibraryId=@rLibraryId)OR(@rLibraryId=0))AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND LogDate = C.sDate),0)AS IssueCount,
				ISNULL((SELECT COUNT(BL.Id) FROM sLibrary.tBookLog BL INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId  WHERE ((LibraryId=@rLibraryId)OR(@rLibraryId=0))AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND ReturnDate = C.sDate),0)AS ReturnCount
			FROM CTE C
				LEFT JOIN sLibrary.tBookLog BL ON BL.LogDate = C.sDate
				--WHERE ((BL.LibraryId=@rLibraryId)OR(@rLibraryId=@rLibraryId))
			GROUP BY BL.LogDate,C.sDate
			ORDER BY sDate 
		END
	ELSE IF (@rType = 'NewBookArrival')
		BEGIN
			SELECT BM.Title FROM sLibrary.tBookMaster BM
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BM.LibraryId
			 
			WHERE CONVERT(DATE,BM.CreatedDateTime) BETWEEN CONVERT(DATE,GETDATE()-30) AND CONVERT(DATE,GETDATE())
				AND ((BM.LibraryId=@rLibraryId)OR(@rLibraryId=0))
				 AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		END
	ELSE IF (@rType = 'TodayDueBook')
		BEGIN
			SELECT SM.FirstName+' '+SM.LastName AS Name,BM.Title AS BookName FROM sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id = BL.ReaderSourceId
				INNER JOIN sLibrary.tBookMaster BM ON BM.Id = BL.ResourceSourceId
			WHERE CONVERT(DATE,DueDate) = CONVERT(DATE,GETDATE())
				AND ((BL.LibraryId=@rLibraryId)OR(@rLibraryId=0))
				AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				AND ((BL.BatchId = @rGroupBatchId)OR(@rGroupBatchId=0))
				 AND BL.StatusId = 523 AND BL.IsCurrentStatus =1
				GROUP BY  SM.FirstName,SM.LastName,BM.Title
		END
	ELSE IF (@rType = 'BookTypeDetail')
		BEGIN
			SELECT RTM.Title,COUNT(BM.Id)AS BookCount FROM sLibrary.tBookMaster BM 
				INNER JOIN sLibrary.tResourceTypeMaster RTM ON RTM.Id = BM.ResourceTypeId
				INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BM.LibraryId
				
			WHERE ((BM.LibraryId=@rLibraryId)OR(@rLibraryId=0))
			AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			GROUP BY RTM.Title
		END
	ELSE IF (@rType = 'NoofIssueBook')
		BEGIN
			SELECT BM.Title,COUNT(BL.Id) AS BookCount FROM sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
				INNER JOIN sLibrary.tBookMaster BM ON BM.Id = BL.ResourceSourceId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id = BL.StatusId
			WHERE SM.Id =523 AND ((BL.LibraryId=@rLibraryId)OR(@rLibraryId=0))
			AND ((LM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND BL.IsCurrentStatus =1
			AND ((BL.BatchId = @rGroupBatchId)OR(@rGroupBatchId=0))
				GROUP BY BM.Title
		END
END


--SELECT * FROM sCommon.tStatusMaster WHERE StatusTypeId=106



--exec sLibrary.pBookMasterGet @rId=0,@rCode=N'',@rTitle=N'',@rPublisher=NULL,
--@rSupplier=NULL,@rAuthor=NULL,@rSubject=NULL,@rLanguage=NULL,@rLocation=NULL,
--@rPrice=0,@rCurrency=N'',@rEdition=NULL,@rISBNNumber=NULL,@rBookTag=NULL,
--@rBookCustomTag=NULL,@rBookAgeGroupId=0,@rResourceTypeId=0,@rStatusId=0,
--@rOrgId=1201,@rCreatedUserId=0,@rLibraryId=120100001,@rBookDepartment=N'',@rShowWithPhotoId=1,@rBookGroup1Id=0,@rBookGroup2Id=0
--go

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pLibraryWiseBookOrderIndexGet]           
@rLibraryId int
WITH EXECUTE AS CALLER          
AS
SET NOCOUNT ON
BEGIN
DECLARE @lNumberString as nvarchar(1000)

SET @lNumberString = (Select ISNULL(max(BM.OrderIndex)+1,1) AS Number FROM sLibrary.tBookMaster BM WHERE BM.LibraryId=@rLibraryId)

SELECT @lNumberString AS Number

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pMagazineMasterAdd]
	
	@rId bigint,
	@rCode nvarchar(25),
	@rTitle nvarchar(300),
	@rPublisher nvarchar(200),
	@rMagazineSubject nvarchar(200),
	@rMagazineLanguage nvarchar(200),
	@rLocation nvarchar(200),
	@rEdition nvarchar(50),
	@rPrice decimal(12,2),
	@rCurrency nvarchar(100),
	@rMagazineCustomTag nvarchar(200),
	@rMagazineAgeGroupId int,
	@rCreatedUserId bigint,
	@rLibraryId int,
	@rFrequencyId int,
	@rOrgGroupId int,
	@rMagazineTypeId int=0,
	@rNoOfCopies smallint=0,
	@rVolumeNo smallInt=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		

IF(@rId = 0)
	BEGIN
    	IF Exists(Select @rCode from sLibrary.tMagazineMaster where Code=@rCode AND LibraryId = @rLibraryId )
		BEGIN
			Select -103 AS Result
			RETURN
		END
		
		IF Exists(Select @rTitle from sLibrary.tMagazineMaster where Title=@rTitle AND LibraryId = @rLibraryId )
		BEGIN
			Select -104 AS Result
			RETURN
		END
	END		
ELSE
	BEGIN	
		IF Exists(Select @rCode from sLibrary.tMagazineMaster where Code=@rCode AND LibraryId = @rLibraryId  AND Id!=@rId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
		
		IF Exists(Select @rTitle from sLibrary.tMagazineMaster where Title=@rTitle AND LibraryId = @rLibraryId  AND Id!=@rId)
		BEGIN
			Select -104 AS Result
			RETURN
		END
	END	
	 	BEGIN TRANSACTION
		DECLARE @lNextNumber BIGINT   
IF(@rId = 0)
BEGIN	
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tMagazineMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sLibrary.tMagazineMaster
		(
			Id,
			Code,
			Title,
			Publisher,
			MagazineSubject,
			MagazineLanguage,
			Location,
			Edition,
			Price,
			Currency,
			MagazineCustomTag,
			MagazineAgeGroupId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			FrequencyId,
			MagazineTypeId,
			NoOfCopies,
			VolumeNo
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rPublisher,
			@rMagazineSubject,
			@rMagazineLanguage,
			@rLocation,
			@rEdition,
			@rPrice,
			@rCurrency,
			@rMagazineCustomTag,
			@rMagazineAgeGroupId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rFrequencyId,
			@rMagazineTypeId,
			@rNoOfCopies,
			@rVolumeNo
		)
		   Select 1 AS Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tMagazineMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			Publisher=@rPublisher,
			MagazineSubject=@rMagazineSubject,
			MagazineLanguage=@rMagazineLanguage,
			Location=@rLocation,
			Edition=@rEdition,
			Price=@rPrice,
			Currency=@rCurrency,
			MagazineCustomTag=@rMagazineCustomTag,
			MagazineAgeGroupId=@rMagazineAgeGroupId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LibraryId=@rLibraryId,
			FrequencyId=@rFrequencyId,
			MagazineTypeId=@rMagazineTypeId,
			NoOfCopies=@rNoOfCopies,
			VolumeNo=@rVolumeNo
	      
	      WHERE Id = @rId 
	      SELECT 11 AS Result
	
END	
	COMMIT TRANSACTION
END TRY
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pMagazineMasterGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(300),
	 @rOrgId int,
	 @rPublisher nvarchar(200),
	 @rMagazineSubject nvarchar(200),
	 @rMagazineLanguage nvarchar(200),
	 @rLocation nvarchar(200),
	 @rEdition nvarchar(50),
	 @rMagazineCustomTag nvarchar(200),
	 @rMagazineAgeGroupId int,
	 @rFrequencyId int,
	 @rLibraryId int,
	 @rMagazineTypeId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rPublisher = sCommon.fSearchStringGet(@rPublisher)
		SET @rMagazineSubject = sCommon.fSearchStringGet(@rMagazineSubject)
		SET @rMagazineLanguage = sCommon.fSearchStringGet(@rMagazineLanguage)
		SET @rLocation = sCommon.fSearchStringGet(@rLocation)
		SET @rEdition = sCommon.fSearchStringGet(@rEdition)
		SET @rLocation = sCommon.fSearchStringGet(@rLocation)
		SET @rEdition = sCommon.fSearchStringGet(@rEdition)
		SET @rMagazineCustomTag = sCommon.fSearchStringGet(@rMagazineCustomTag)
		
	SELECT 
		MM.Id AS MagazineId,
		MM.Code,
		MM.Title,
		ISNULL(MM.Publisher,'') AS Publisher,
		ISNULL(MM.MagazineSubject,'') AS MagazineSubject,
		ISNULL(MM.MagazineLanguage,'') AS MagazineLanguage,
		ISNULL(MM.Location,'') AS Location,
		ISNULL(MM.Edition,'') AS Edition,
		ISNULL(MM.Price,0) AS Price,
		ISNULL(MM.Currency,0) AS Currency,
		ISNULL(MM.MagazineCustomTag,'') AS MagazineCustomTag,
		ISNULL(MM.MagazineAgeGroupId,0) AS MagazineAgeGroupId,
		ISNULL(MM.FrequencyId,0) AS FrequencyId,
		MM.LibraryId,
		ISNULL(AGM.Title,'') AS MagazineAgeGroupName,
		ISNULL(FM.Title,'') AS FrequencyName,
		ISNULL(MM.MagazineTypeId,0) AS MagazineTypeId,
		ISNULL(MM.NoOfCopies,0) As NoOfCopies,
		ISNULL(MM.VolumeNo,0) AS VolumeNo
  FROM 
		sLibrary.tMagazineMaster MM
			LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
				ON MM.MagazineAgeGroupId=AGM.Id
			LEFT JOIN sCommon.tFrequencyMaster FM
				ON MM.FrequencyId=FM.Id
  WHERE 
		((MM.Id = @rId) OR (@rId = 0))
		AND MM.LibraryId = @rLibraryId	
		ANd ((MM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((MM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
		AND ((MM.Publisher like @rPublisher) OR (ISNULL(@rPublisher,'') = '')) 
		AND ((MM.MagazineSubject like @rMagazineSubject) OR (ISNULL(@rMagazineSubject,'') = '')) 
		AND ((MM.MagazineLanguage like @rMagazineLanguage) OR (ISNULL(@rMagazineLanguage,'') = '')) 
		AND ((MM.Location like @rLocation) OR (ISNULL(@rLocation,'') = ''))  
		AND ((MM.Edition like @rEdition) OR (ISNULL(@rEdition,'') = ''))  
		AND ((MM.MagazineCustomTag like @rMagazineCustomTag) OR (ISNULL(@rMagazineCustomTag,'') = ''))
		AND ((MM.MagazineAgeGroupId = @rMagazineAgeGroupId) OR(@rMagazineAgeGroupId=0))
		AND ((MM.FrequencyId = @rFrequencyId) OR (@rFrequencyId=0))
		AND ((MM.MagazineTypeId=@rMagazineTypeId) OR(@rMagazineTypeId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pMagazineReceiveAdd]
	
	@rId bigint,
	@rMagazineId bigint,
	@rReceiveDate date,
	@rVolumeNumber nvarchar(50),
	@rIssueNumber int,
	@rCreatedUserId bigint,
	@rOrgGroupId int,
	@rMagazineAmount decimal(8,2)=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
--IF(@rId = 0)
--	BEGIN
--    	IF Exists(Select @rCode from sLibrary.tMagazineMaster where Code=@rCode AND LibraryId = @rLibraryId )
--		BEGIN
--			Select -103 AS Result
--			RETURN
--		END
--	END		
--ELSE
--	BEGIN	
--		IF Exists(Select @rCode from sLibrary.tMagazineMaster where Code=@rCode AND LibraryId = @rLibraryId  AND Id!=@rId)
--		BEGIN
--			Select -103 AS Result
--			RETURN
--		END
--	END	
	 	BEGIN TRANSACTION
		DECLARE @lNextNumber BIGINT   
IF(@rId = 0)
BEGIN	
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tMagazineReceive', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sLibrary.tMagazineReceive
		(
			Id,
			MagazineId,
			ReceiveDate,
			VolumeNumber,
			IssueNumber,
			CreatedUserId,
			CreatedDateTime,
			MagazineAmount
		)
	VALUES
		(
			@lNextNumber,
			@rMagazineId,
			@rReceiveDate,
			@rVolumeNumber,
			@rIssueNumber,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rMagazineAmount
		)
		   Select 1 AS Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tMagazineReceive
	    SET
			MagazineId=@rMagazineId,
			ReceiveDate=@rReceiveDate,
			VolumeNumber=@rVolumeNumber,
			IssueNumber=@rIssueNumber,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			MagazineAmount=@rMagazineAmount
	      WHERE Id = @rId 
	      SELECT 11 AS Result
END	
	COMMIT TRANSACTION
END TRY
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pMagazineReceiveGet]
	 
	 @rId bigint = 0,
	 @rLibraryId int,
	 @rMagazineId bigint,
	 @rMagazineCode nvarchar(25),
	 @rFromReceiveDate date,
	 @rToReceiveDate date
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SET @rMagazineCode = sCommon.fSearchStringGet(@rMagazineCode)
	SELECT 
	     MR.Id AS MagazineReceiveId,
	     MR.MagazineId,
	     MM.Code AS MagazineCode,
	     MM.Title AS MagazineName,
	     MR.ReceiveDate,
	     ISNULL(MR.VolumeNumber,'') AS VolumeNumber,
	     ISNULL(IssueNumber,0) AS IssueNumber,
	     ISNULL(MM.Price,0) AS Price,
		 ISNULL(FM.Title,'') AS FrequencyName,
		  LM.ReportOrgTitle,
	      LM.SmallAddress1,
	      LM.SmallAddress2,
	      ISNULL(MagazineAmount,0)AS MagazineAmount
		
	    
  FROM 
		sLibrary.tMagazineReceive MR
			INNER JOIN sLibrary.tMagazineMaster MM ON MM.Id=MR.MagazineId
			LEFT JOIN sCommon.tFrequencyMaster FM ON MM.FrequencyId=FM.Id
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=MM.LibraryId
  WHERE 
		MM.LibraryId=@rLibraryId
		AND ((MR.Id = @rId) OR (@rId = 0))
		AND ((MR.MagazineId = @rMagazineId) OR (@rMagazineId = 0))
		ANd ((MM.Code like @rMagazineCode) OR (ISNULL(@rMagazineCode,'') = ''))
		AND (MR.ReceiveDate>=@rFromReceiveDate OR ISNULL(@rFromReceiveDate,'')='')
		AND (MR.ReceiveDate<=@rToReceiveDate OR ISNULL(@rToReceiveDate,'')='')
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pMagazineTypeMasterAdd]
	 
        @rId int,
        @rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rNumber int,
		@rCreatedUserId bigint,
		@rIsObsolete bit,
		@rOrgGroupId smallint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		If Exists(select Id from sLibrary.tMagazineTypeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sLibrary.tMagazineTypeMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sLibrary.tMagazineTypeMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sLibrary.tMagazineTypeMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tMagazineTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sLibrary.tMagazineTypeMaster
		(
			
			Id,
			OrgGroupId ,
			Number,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsObsolete 
			
		)
	VALUES
		(
			@lNextNumber,
			@rOrgGroupId,
			@rNumber,
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete 
		)
		
		  --INSERT INTO sSecurity.tUserAccess
    --       (
    --       SourceTypeId
    --       ,SourceId
    --       ,[UserId]
           
    --       )
		  -- SELECT 
		  -- 2011
		  -- ,@lNextNumber
		  -- ,@rCreatedUserId
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sLibrary.tMagazineTypeMaster
	    SET
			Title=@rTitle,
			Number=@rNumber,
			Code=@rCode,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete 
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pMagazineTypeMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	SELECT 
			Id,
			ISNULL(Number,0) AS Number,
			Code,
			Title,
			IsObsolete 
      
  FROM 
            sLibrary.tMagazineTypeMaster
  WHERE   
           ((Id = @rId) OR (@rId = 0))
	       AND ((Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       AND ((Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	       AND OrgGroupId=@rOrgGroupId
	       Order by id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sLibrary].[pMISLibraryDashboardGet]            
  @rOrgGroupId int =0,        
  @rType int = 0 ,
  @rCommonOrgGroupBatchId int=0,
  @rLibraryId bigint=0       
        
WITH EXECUTE AS CALLER            
AS            
SET NOCOUNT ON            
BEGIN        
	IF(@rType = 1)        
		BEGIN 
			SELECT LB.Title as Library,LB.Id as Id,COUNT(BM.Id) as BookCount FROM sLibrary.tLibraryMaster LB     
			INNER JOIN  sLibrary.tBookMaster BM on LB.id = BM.Libraryid 
			INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId      
			INNER JOIN sSetup.torggroupmaster OGM on OGM.id = LB.OrgGroupid    
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE LB.IsObsolete = 0   
			AND LB.OrgGroupId = @rOrgGroupId   
			AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
			GROUP BY LB.Title,LB.Id
			ORDER BY LB.Title
		END        
	IF(@rType = 2)  
		BEGIN       
			SELECT SM.Title AS Title,COUNT(BM.Id) AS BookCount  
			FROM sLibrary.tLibraryMaster LB       
			INNER JOIN sLibrary.tBookMaster BM ON BM.Libraryid = LB.id     
			INNER JOIN sLibrary.tBookLog BL ON  ResourceSourceId = BM.id  AND IsCurrentStatus = 1
			LEFT JOIN sCommon.tstatusmaster SM ON SM.id = BL.Statusid   
			INNER JOIN sSetup.torggroupmaster OGM on OGM.id = LB.OrgGroupid 	   
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE LB.IsObsolete = 0 
			AND  LB.Id = @rLibraryId AND LB.OrgGroupId = @rOrgGroupId   
			AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
			GROUP BY SM.Title   
			ORDER BY SM.Title   
		END        
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pMyBookLogAdd]
		--@rId bigint,
        @rReaderSourceTypeId smallint,
		@rReaderSourceId bigint,
		@rResourceSourceTypeId smallint,
		@rResourceSourceId bigint,
		@rLogDate date,
		@rDueDate date,
		@rStatusId smallint,
		@rRemark nvarchar(150),
		@rIsCurrentStatus bit,
		@rOrgId smallint,
		@rBatchId int,
		@rCreatedUserId bigint,
		@rLibraryId int,
		@rBookActionStatusId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	--IF (@rId = 0)
	--BEGIN
	--add for mantis: 43750, start
	DECLARE @lReserveDays int=0
	DECLARE @Temp TABLE (NoOfBookIssuable smallint, IssueDays smallint, PenaltyPerDay decimal(12,2), ReserveDays smallint)
	INSERT INTO @Temp exec sLibrary.pIssueSettingDetailGet @rReaderSourceTypeId,@rReaderSourceId,@rOrgId,@rBatchId,@rLibraryId
	SELECT @lReserveDays = ReserveDays FROM @Temp
	--add for mantis: 43750, end

	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tBookLog', 0, 1, 1,@outNextNumber = @lNextNumber output

	UPDATE sLibrary.tBookLog
	    SET
			IsCurrentStatus=0,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE ResourceSourceTypeId = @rResourceSourceTypeId AND ResourceSourceId = @rResourceSourceId
		--AND LibraryId = @rLibraryId


	INSERT INTO sLibrary.tBookLog
		(
			Id,
			ReaderSourceTypeId,
			ReaderSourceId,
			ResourceSourceTypeId,
			ResourceSourceId,
			LogDate,
			DueDate,
			StatusId,
			Remark,
			IsCurrentStatus,
			OrgId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			BookActionStatusId
		)
	VALUES
		(
			@lNextNumber,
			@rReaderSourceTypeId,
			@rReaderSourceId,
			@rResourceSourceTypeId,
			@rResourceSourceId,
			ISNULL(@rLogDate,sCommon.fGetDate()),
			--mantis: 43750, comment below line and add new line below it
			--ISNULL(@rDueDate,sCommon.fGetDate()),
			ISNULL(@rDueDate,DATEADD(DAY,@lReserveDays,sCommon.fGetDate())), --mantis: 43750
			@rStatusId,
			@rRemark,
			@rIsCurrentStatus,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rBookActionStatusId
		)
		    SELECT @lNextNumber AS Result

	--END
	--ELSE
	-- BEGIN
	-- SET @lNextNumber = @rId
	--    UPDATE sLibrary.tBookLog
	--    SET
	--		ReaderSourceTypeId=@rReaderSourceTypeId,
	--		ReaderSourceId=@rReaderSourceId,
	--		ResourceSourceTypeId=@rResourceSourceTypeId,
	--		ResourceSourceId=@rResourceSourceId,
	--		LogDate=@rLogDate,
	--		DueDate=@rDueDate,
	--		StatusId=@rStatusId,
	--		Remark=@rRemark,
	--		IsCurrentStatus=@rIsCurrentStatus,
	--		UpdatedUserId=@rCreatedUserId,
	--		UpdatedDateTime=sCommon.fGetDate()

	--      WHERE Id = @rId
	--      SELECT @lNextNumber AS Result

	-- END

	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pMyBookLogListGet]
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId   
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND (BL.LibraryId=@rLibraryId)
		AND ISNULL(EM.IsOtherUser,0) = 0
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pNewspaperLogAdd]
	
	@rId int,
	@rNewspaperId Int,
	@rNewsPaperDate DateTime,
	@rNoOfCopy Smallint,
	@rLibraryId int,
	@rCreatedUserId bigint,
	@rNewspaperAmount decimal(12,2)
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF(@rId = 0)
    BEGIN
    
	INSERT INTO [sLibrary].[tNewspaperLog]
           ([NewspaperId]
           ,[NewspaperDate]
           ,[NoOfCopy]
           ,[CreatedUserId]
           ,[CreatedDateTime]
		   ,[NewspaperAmount])
     VALUES
           (@rNewspaperId
           ,@rNewspaperDate
           ,@rNoOfCopy
           ,@rCreatedUserId
           ,sCommon.fGetDate(),
		   @rNewspaperAmount)
	SELECT 1 AS Result
	End
	ELSE 
	BEGIN
	 
	UPDATE [sLibrary].[tNewspaperLog]
		SET [NewspaperId] = @rNewspaperId
		  ,[NewspaperDate] = @rNewspaperDate
		  ,[NoOfCopy] = @rNoOfCopy
		  ,[NewspaperAmount] = @rNewspaperAmount
	WHERE  AutoId = @rId
		 SELECT 11 AS Result
	END
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pNewspaperLogGet]
	 @rId bigint = 0,
	 @rNewspaperId int,
	 @rFromNewspaperDate Date,
	 @rToNewspaperDate Date,
	 @rLibraryId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
		SELECT NL.AutoId AS Id
		  ,NM.Title AS NewsPaperName
		  ,NM.Id AS NewsPaperId
		  ,NM.Language AS NewsPaperLanguage
		  ,NM.LibraryId AS LibraryId
		  ,LM.Title AS LibraryName
		  ,isnull(NM.NewsTypeId,0) AS NewsTypeId
		  ,NM.CreatedUserId AS CreatedUserId
		  ,NM.CreatedDateTime AS CreatedDateTime
		  ,NL.NewsPaperDate AS NewsPaperDate
		  ,NL.NoOfCopy AS NoOfCopy,
		   isnull(NL.NewspaperAmount,0) AS NewspaperAmount
		 
		  
	  FROM [sLibrary].[tNewspaperLog] NL 
	  inner Join [sLibrary].[tNewspaperMaster] NM On NL.NewspaperId=NM.Id
	  inner join [sLibrary].[tLibraryMaster] LM ON LM.Id=NM.LibraryId
	  where 
	  (LM.Id=@rLibraryId)
		AND ((NL.AutoId=@rId) OR (@rId=0))
		AND ((NL.NewspaperId=@rNewspaperId) OR (@rNewspaperId=0))
		AND (NL.NewspaperDate>=@rFromNewspaperDate OR ISNULL(@rFromNewspaperDate,'')='')
		AND (NL.NewspaperDate<=@rToNewspaperDate OR ISNULL(@rToNewspaperDate,'')='')
		--AND ((NM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	--order By NL.NewsPaperDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pNewspaperMasterAdd]
	
	@rId int,
	@rCode nvarchar(25),
	@rTitle nvarchar(100),
	@rIsObsolete Bit,
	@rLanguage nvarchar(100),
	@rNewsTypeId smallint,
	@rOrgGroupId int,	
	@rLibraryId int,
	@rCreatedUserId bigint
	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF(@rId = 0)
    BEGIN
		IF Exists(Select 1 from sLibrary.tNewspaperMaster where Code=@rCode AND LibraryId = @rLibraryId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
		IF Exists(Select 1 from sLibrary.tNewspaperMaster where Title=@rTitle AND LibraryId = @rLibraryId)
		BEGIN
			Select -104 AS Result
			RETURN
		END
		
	END
ELSE
	BEGIN
 		IF Exists(Select @rCode from sLibrary.tNewspaperMaster where Code=@rCode AND LibraryId = @rLibraryId  AND Id<>@rId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
		IF Exists(Select 1 from sLibrary.tNewspaperMaster where Title=@rTitle AND LibraryId = @rLibraryId AND Id<>@rId)
		BEGIN
			Select -104 AS Result
			RETURN
		END
	END
IF(@rId = 0)
    BEGIN
    
    DECLARE @lNextNumber BIGINT   
    
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tNewspaperMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sLibrary].[tNewspaperMaster]
           ([Id]
           ,[Code]
           ,[Title]
		   ,[IsObsolete]
           ,[Language]
		   ,[NewsTypeId]
           ,[LibraryId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
		   
           )
     VALUES
           (@lNextNumber
           ,@rCode
           ,@rTitle
		   ,@rIsObsolete
           ,@rLanguage
           ,@rNewsTypeId
           ,@rLibraryId
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           )
	SELECT 1 AS Result
	End
	ELSE 
	BEGIN
	 SET @lNextNumber = @rId
	 UPDATE [sLibrary].[tNewspaperMaster]
		   SET [Code] = @rCode
			  ,[Title] = @rTitle
			  ,[IsObsolete]=@rIsObsolete
			  ,[Language] = @rLanguage
			  ,[NewsTypeId]=@rNewsTypeId
			  ,[LibraryId] = @rLibraryId
			  ,[UpdatedUserId] = @rCreatedUserId
			  ,[UpdatedDateTime] = sCommon.fGetDate()
			  
		 WHERE Id = @rId
		 SELECT 11 AS Result
	END
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pNewspaperMasterDelete]
	
	@rId int
	
	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		IF Exists(Select 1 from sLibrary.tNewspaperLog where NewspaperId=@rId)
		BEGIN
			Select -103 AS Result
			RETURN
		END

    BEGIN
   Delete From [sLibrary].[tNewspaperMaster] where Id=@rId
           
	SELECT 1 AS Result
	End
	
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pNewspaperMasterGet]
	 @rId int = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(100),
	 @rOrgGroupId int,
	 @rLanguage nvarchar(200),
	 @rCreatedUserId bigint,
	 @rLibraryId int,
	 @rNewsTypeId smallint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	SET @rLanguage = sCommon.fSearchStringGet(@rLanguage)
		SELECT NM.Id AS Id
		  ,NM.Code AS Code
		  ,NM.Title AS Title
		  ,NM.Language AS Language
		  ,NM.LibraryId AS LibraryId
		  ,LM.Title AS LibraryName
		  ,isnull(NM.IsObsolete,0) AS IsObsolete
		  ,isnull(NM.NewsTypeId,0) AS NewsTypeId
		  ,NM.CreatedUserId AS CreatedUserId
		  ,NM.CreatedDateTime AS CreatedDateTime
		 
		  
	  FROM [sLibrary].[tNewspaperMaster] NM
	  inner join [sLibrary].[tLibraryMaster] LM ON LM.Id=NM.LibraryId
	  where 
	  (LM.Id=@rLibraryId)
		AND ((NM.Id=@rId) OR (@rId=0))
		AND ((NM.Code like @rCode) OR (Isnull(@rCode,'')=''))
		AND ((NM.Title like @rTitle) OR (isnull(@rTitle,'')=''))
		AND ((LM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))
		AND ((NM.Language like @rLanguage) OR (isnull(@rLanguage,'')=''))
		AND ((NM.NewsTypeId=@rNewsTypeId) OR (@rNewsTypeId=0))

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pReaderBookLogListGet]
	 @rReaderSourceTypeId smallint=0,
	 @rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId,
			BM.Id As BookId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId 
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND IS1.LibraryId=@rLibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		--AND (BL.OrgId=@rOrgId)
		--AND (BL.BatchId=@rBatchId)
		-- because of pAssignBooksBulkReturnGet sp (due date and Book Code not display) - done by sarangi - mantisid - 0026852
		AND (SA.OrgId=@rOrgId)
		AND (SA.BatchId=@rBatchId)
		--AND  SA.IsActiveBatch = 1
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId,
			BM.Id As BookId   
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004 AND IS1.LibraryId=@rLibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		-- because of pAssignBooksBulkReturnGet sp (due date and Book Code not display) - done by sarangi - mantisid - 0026852
		--AND (BL.OrgId=@rOrgId)
		AND (EM.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND (BL.LibraryId=@rLibraryId)
		AND ISNULL(EM.IsOtherUser,0) = 0
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pReaderMyBookLogListGet]
	 @rReaderSourceTypeId smallint=0,
	 @rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId 
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND IS1.LibraryId=@rLibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		--AND  SA.IsActiveBatch = 1
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId   
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004 AND IS1.LibraryId=@rLibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND (BL.LibraryId=@rLibraryId)
		AND ISNULL(EM.IsOtherUser,0) = 0
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pReturnDueListGet]
	 @rReaderSourceTypeId smallint,
	 @rReaderCode nvarchar(20),
	 @rReaderName nvarchar(200),
	 @rResourceCode nvarchar(25),
	 @rResourceName nvarchar(100),
	 @rDueDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rLibraryId int,
	 @rOrgGroupId int=0,
	 @rSUId nvarchar(50)='',
	 @rClassId int=0,
	 @rDepartmentId int=0,
	 @rDivisionId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		
		SET @rReaderCode = sCommon.fSearchStringGet(@rReaderCode)
		SET @rReaderName = sCommon.fSearchStringGet(@rReaderName)
		SET @rResourceCode = sCommon.fSearchStringGet(@rResourceCode)
		SET @rResourceName = sCommon.fSearchStringGet(@rResourceName)
		
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Student' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			VA.Code AS ReaderCode,
			VA.Name AS ReaderName,
			VA.ClassName+'-'+VA.DivisionName AS ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',VA.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS EmailTemplate,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',VA.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS SMSTemplate,

			 replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=3),'[Name]',VA.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS MobileTemplate,

			 (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS MailSubject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName,
			 LM.ReportOrgTitle,
	         LM.SmallAddress1,
	         LM.SmallAddress2,
	         VA.SUId
			 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			--INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = SC.BatchId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 
			INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = VA.BatchId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
		AND ((VA.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND ((VA.Name Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.DueDate<=@rDueDate) AND (BL.IsCurrentStatus=1)
		AND (BL.StatusId = 523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
		AND ((VA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
		AND ((VA.ClassId=@rClassId)OR(@rClassId=0))
		AND ((VA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND(VA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
	UNION ALL

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Employee' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			EC.Code AS ReaderCode,
			EC.FirstName+' '+EC.LastName AS ReaderName,
			EC.DepartmentName as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			EC.PhoneNoCompany AS MobileNo,
			EC.CompanyEmail AS EmailId,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS EmailTemplate,
			 replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS SMSTemplate,
			  replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=3),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS MobileTemplate,
			 (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS MailSubject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName,
			 LM.ReportOrgTitle,
	         LM.SmallAddress1,
	         LM.SmallAddress2,
	         '' AS SUId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 AND BL.OrgId=EC.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
		AND ((EC.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND ((EC.FirstName+' '+EC.LastName Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.StatusId = 523) 
		AND (BL.DueDate<=@rDueDate) AND  (BL.IsCurrentStatus=1)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
		AND(EC.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
		
	UNION ALL

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'' AS ReaderSourceType,
			0 AS ReaderSourceTypeId,
			0 AS ReaderSourceId,
			'' AS ReaderCode,
			'' AS ReaderName,
			'' as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			'' AS MobileNo,
			'' AS EmailId,
			'' AS EmailTemplate,
			'' AS SMSTemplate,
			'' AS MailSubject,
			'' AS MobileTemplate,
			LM.Id AS LibraryId,
			LM.Title AS LibraryName,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2,
	        '' AS SUId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(ISNULL(BL.ReaderSourceTypeId,0)=@rReaderSourceTypeId AND @rReaderSourceTypeId=0)
		AND (('' Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND (('' Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.StatusId = 523) 
		AND (BL.DueDate<=@rDueDate) AND (BL.IsCurrentStatus=1) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pRptAccessionRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rAccessionNo nvarchar(50)='',
	 @rClassificationNo nvarchar(50)='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 @rBookSubjectDrop nvarchar(200)='',
	 @rBookSubjectText nvarchar(200)='',
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date='',
	 @rBookDepartment nvarchar(150)--mantis - 0033576
           
AS
SET NOCOUNT ON
BEGIN
	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rAccessionNo = sCommon.fSearchStringGet(@rAccessionNo)
		SET @rClassificationNo = sCommon.fSearchStringGet(@rClassificationNo)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
		SET @rBookDepartment = sCommon.fSearchStringGet(@rBookDepartment)
	END
	SELECT   
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Id AS BookId,
		BM.Code AS BookCode,
		BM.Title AS BookName,
		BM.Author,
		BM.Publisher,
		BM.ClassificationNo,
		BM.BookSubject,
		BM.AccessionNo,
		BM.Edition,
		BM.NoOfPages,
		BM.BookLanguage,
		BM.Supplier,
		BM.PurchaseDate,
		BM.Price,
		BM.ISBNNumber,
		BM.Location,
		BM.BookRemark,
		LM.ReportOrgTitle,
		LM.SmallAddress1,
		LM.SmallAddress2,
		BM.BookDepartment--mantis - 0033576
	FROM  
		sLibrary.tBookMaster BM 
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.AccessionNo like @rAccessionNo) OR (@rAccessionNo=''))
		AND ((BM.ClassificationNo like @rClassificationNo) OR (@rClassificationNo=''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') =''))
		AND ((BM.BookDepartment like @rBookDepartment) OR (ISNULL(@rBookDepartment,'') =''))--mantis - 0033576
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pRptBookListCirculationGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	--@rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	-- @rOrgId smallint,
	 --@rBatchId int,
	 --@rClassId int,
	 --@rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rTopFrequency  smallint,
	 @rBookPublisher nvarchar(200)='' ,     --Mantis - 32621
	 @rAuthor nvarchar(200)=''         --Mantis - 32621
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)

		SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	        
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND SA.BatchId = BL.BatchId
	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
	UNION

	SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95

	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			AND  ISNULL(EM.IsOtherUser,0) = 0
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))     --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))                  --Mantis - 32621
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
			
	UNION 

	SELECT 
	Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	WHERE (BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND (ISNULL(BL.ReaderSourceTypeId,0)=0 AND 0=0)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))           --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))           --Mantis - 32621
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			ORDER BY COUNT(BL.Id) desc


		
		--SELECT Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2 FROM sLibrary.tBookLog BL
		--	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		--	--INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
		--WHERE (BL.LibraryId=@rLibraryId) AND ReaderSourceTypeId = 2003 AND BL.StatusId = 523 AND IsCurrentStatus =0
		--	AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		--	AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		 
		--	GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
		--	ORDER BY COUNT(BL.Id) desc

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pRptBookListCirculationLowFrequencyGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	--@rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 --@rOrgId smallint,
	 --@rBatchId int,
	 --@rClassId int,
	 --@rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rTopFrequency  smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	        
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND SA.BatchId = BL.BatchId
	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
	UNION

	SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95

	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			AND  ISNULL(EM.IsOtherUser,0) = 0
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
			
	UNION 

	SELECT 
	Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	WHERE (BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND (ISNULL(BL.ReaderSourceTypeId,0)=0 AND 0=0)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			ORDER BY COUNT(BL.Id) 

		--SELECT Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2 FROM sLibrary.tBookLog BL
		--	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		--	INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
		--WHERE (BL.LibraryId=@rLibraryId) AND ReaderSourceTypeId = 2003 AND BL.StatusId = 523 AND IsCurrentStatus =0
		--	AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		--	AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		--	GROUP  by BM.Id,BM.Code,BM.Title
		--	ORDER BY COUNT(BL.Id) 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pRptBookListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),      
	 @rBookSubjectText nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150)='',
	 @rIsDetail bit=0,
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 --@rOrgGroupId int,
	 @rFromCode nvarchar(25) ='',
	 @rToCode nvarchar(25) ='',
	 @rSpecificCode nvarchar(max) ='',
	 @rBookSubjectDrop nvarchar(500)='',
	 @rFromDate date ='',
	 @rToDate date ='',
	 --Start For Mantis: 31829
	 @rFromBookCode nvarchar(50)='', --changes bigint to nvarchar for mantis id :0034855
	 @rToBookCode nvarchar(50)='', --changes bigint to nvarchar for mantis id :0034855
	 --End For Mantis: 31829
	 @rAuthor nvarchar(200)=''         --Mantis - 32621  --add ''(2 single quot) for Mantis: 33633
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	--DECLARE @rFromCodeInt INT, @rToCodeInt INT
	--DECLARE @BookConfig NVARCHAR, @rFromCodeString NVARCHAR, @rToCodeString NVARCHAR
	--SELECT @BookConfig = ItemValue From sConfig.tConfigurationSetup	WHERE ConfigurationId = 260 AND SourceId = @rOrgGroupId
	
	--SET @rFromCodeInt = Convert(Int,ISNULL(@rFromCode,0))
	--SET @rToCodeInt = Convert(Int,ISNULL(@rToCode,0))
	--SET @rFromCodeString = Convert(nvarchar,ISNULL(@rFromCode,''))
	--SET @rToCodeString = Convert(nvarchar,ISNULL(@rToCode,''))
	
	DECLARE @ListofBookCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
		INSERT INTO @ListofBookCodes
	
	select q2.value from
		(SELECT cast('<x>'+replace(@rSpecificCode,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
		(SELECT x.value('.','nvarchar(max)') as value FROM thexml.nodes('x') as f(x))q2
		

	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rBookDepartment = sCommon.fSearchStringGet(@rBookDepartment)
    END

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher,BM.Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
		BM.BookLanguage,
		BM.BookCustomTag,
		BM.BookCustomTag,
		BM.Location,
		BM.ISBNNumber,
		LM.ReportOrgTitle,
        LM.SmallAddress1,
        LM.SmallAddress2,
        CASE WHEN BM.BookDepartment is null THEN 'Blank'
            WHEN BM.BookDepartment='' THEN 'Blank'  ELSE BM.BookDepartment END AS  BookDepartment,
        BM.NoOfCopies,
        @rIsDetail AS IsDetail,
        LM.Code AS LibraryCode,	       
         LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo
		
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookDepartment like @rBookDepartment) OR (@rBookDepartment=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') =''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
		AND ((BM.Code IN(SELECT Code FROM @ListofBookCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code >= @rFromCodeString ELSE BM.Code > @rFromCodeInt END AS BM.Code
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code <= @rToCodeString ELSE BM.Code > @rToCodeInt END AS BM.Code
		AND ((BM.BookEntryDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((BM.BookEntryDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))		
		--AND ((BM.Code >= @rFromBookCode) OR (@rFromBookCode='')) AND ((BM.Code <= @rToBookCode) OR (@rToBookCode='')) -- Add New Condition For Mantis Id:0034855
		--Start : mantis : 41054 Changes by Vishruti
		AND ((
				@rFromBookCode = '' AND @rToBookCode = '') OR
			(ISNUMERIC(BM.Code) = 1 -- Numeric filtering
				AND (
					(@rFromBookCode = '' OR TRY_CAST(BM.Code AS INT) >= TRY_CAST(NULLIF(@rFromBookCode, '') AS INT))
					AND (@rToBookCode = '' OR TRY_CAST(BM.Code AS INT) <= TRY_CAST(NULLIF(@rToBookCode, '') AS INT))
				)
			)
			OR
			(
				ISNUMERIC(BM.Code) = 0 -- Alphabetic filtering
				AND (((BM.Code >= @rFromBookCode) OR (@rFromBookCode='')) AND ((BM.Code <= @rToBookCode) OR (@rToBookCode=''))) 


      
			)
		)
		--End : mantis : 41054 Changes by Vishruti
		AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621

		ORDER BY
		CASE WHEN BM.Code like '%[0-9]%' 
		 THEN Replicate('0', 100 - Len(BM.Code)) + BM.Code
		 ELSE BM.Code  END
		--ORDER BY CONVERT(INT, BM.Code)
		
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pRptBookListNotIssueGet]
@rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rReaderSourceTypeId smallint=0,
	 --@rReaderSourceId bigint,
	 --@rOrgId smallint,	
	@rOrgGroupId int =0,
	 @rFromLogDate date='',
	 @rToLogDate date='',
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

		 SELECT  @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BM.Code AS Code,
			BM.Title AS Title FROM sLibrary.tBookMaster BM
LEFT JOIN
(SELECT DISTINCT ISNULL(BL.ResourceSourceId,0) AS BookId FROM  sLibrary.tBookLog BL 
	INNER JOIN sSetup.tOrganizationMaster OM ON BL.OrgId = OM.Id
	WHERE BL.LibraryId=@rLibraryId 
	--AND ISNULL(BL.ReaderSourceTypeId,0) =0 AND ISNULL(ReaderSourceId,0) = 0
	AND OM.OrgGroupId = @rOrgGroupId AND BL.StatusId = 523 AND ResourceSourceTypeId = 2009 
	--AND ((BL.LogDate>= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	--		AND((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			) B ON BM.Id = B.BookId
WHERE BookId IS NULL AND BM.LibraryId=@rLibraryId 


	--SELECT 
	     
	--        @rBuilder1 AS Builder1,
	--		@rBuilder2 AS Builder2,
	--		BM.Code AS Code,
	--		BM.Title AS Title
			
			
	--FROM sLibrary.tBookLog BL
	--	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	--		INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
	----WHERE ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	----	AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))		
	----	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	----	AND BL.ReaderSourceTypeId IS NULL AND  BL.ReaderSourceId IS NULL
	----	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
	----	AND (BL.LibraryId=@rLibraryId)
	--	WHERE BL.ResourceSourceId  IN (
	--		SELECT BM.Id FROM sLibrary.tBookLog  BL
	--		INNER JOIN   sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	--		WHERE((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	--		AND((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))	
	--		AND BL.LibraryId=@rLibraryId 
	--		AND BL.ReaderSourceTypeId IS NULL AND  BL.ReaderSourceId IS NULL)
	--		AND BL.ReaderSourceTypeId IS NULL AND  BL.ReaderSourceId IS NULL
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pRptBookListNotReturnGet]
	 
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
           @rLibraryId int=0,
           @rSourceTypeId int=0,
           @rFromLogDate date='',
           @rToLogDate date='',
           @rOrgId smallint=0,
           @rBatchId int=0,
           @rFromDueDate date='',
		   @rToDueDate date='',
		   @rBookPublisher nvarchar(200)='' , --Mantis - 32621
		   @rAuthor nvarchar(200)=''          --Mantis - 32621
		    
           
AS
SET NOCOUNT ON
BEGIN
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
SELECT   
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   BL.Id AS BookLogId,
	   BL.LibraryId,
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	'Employee'
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,

		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.EmployeeName
			WHEN BL.ReaderSourceTypeId = 2003 THEN vSF.Name
			ELSE
			''
			END) AS Name,
			
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.DepartmentName
			WHEN BL.ReaderSourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
		 
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	Emp.Code
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
	   BL.ReaderSourceTypeId,
	   BL.ReaderSourceId,
	   BL.LogDate,
	   BL.DueDate,
	   BL.ReturnDate,
	   BM.Code AS BookCode,
	   BM.Title AS BookName,
	   OM.DisplayTitle AS OrganizationName,
	    LM.ReportOrgTitle,
	    LM.SmallAddress1,
	    LM.SmallAddress2
	   
  FROM  
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 95 
		LEFT JOIN sStudent.vStudentLastAcademic vSF
			ON vSF.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 2003 
			AND (SELECT IsActive FROM sSetup.tBatchMaster WHERE Id=vSF.BatchId AND IsActive = 1) = 1	
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId			
 
  WHERE 
    BL.StatusId = 523 
	AND BL.LibraryId=@rLibraryId
	--AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
	--AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
	AND ((BL.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,'') = ''))
	AND ((BL.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,'') = ''))
	AND ((BL.ReaderSourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
	AND (ISNULL(BL.ReturnDate,'')='')
	AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
	AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621



	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pRptBookLogPenaltyListGet]
	 
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
           @rLibraryId int,
           @rSourceTypeId int,
           @rFromLogDate date,
           @rToLogDate date,
           @rOrgId smallint=0,
           @rBatchId int=0
           
           
AS
SET NOCOUNT ON
BEGIN
SELECT   
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   BL.Id AS BookLogId,
	   BL.LibraryId,
	   
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	'Employee'
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,

		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.EmployeeName
			WHEN BL.ReaderSourceTypeId = 2003 THEN vSF.Name
			ELSE
			''
			END) AS Name,
			
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.DepartmentName
			WHEN BL.ReaderSourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
		 
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	Emp.Code
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
			 	 
	   BL.ReaderSourceTypeId,
	   BL.ReaderSourceId,
	   BL.LogDate,
	   BL.DueDate,
	   BM.Code AS BookCode,
	   BM.Title AS BookName,
	   BLP.PenaltyDays,
	   BLP.PenaltyRate,
	   BLP.PenaltyAmount,
	   LM.ReportOrgTitle,
	   LM.SmallAddress1,
	   LM.SmallAddress2
	   
  FROM  
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sLibrary.tBookLogPenalty BLP ON BLP.BookLogId = BL.Id
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 95 
		LEFT JOIN sStudent.vStudentFull vSF
			ON vSF.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 2003 
			AND (SELECT IsActive FROM sSetup.tBatchMaster WHERE Id=vSF.BatchId AND IsActive = 1) = 1				
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = vSF.DepartmentId		
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	
  WHERE 
  
	BL.LibraryId=@rLibraryId
	AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
	AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
	AND ((BL.ReaderSourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pRptBookLogRegisterGet]
	 
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
           @rLibraryId int=0,
           @rSourceTypeId int=0,
           @rFromLogDate date='',
           @rToLogDate date='',
           @rOrgId smallint=0,
           @rBatchId int=0,
           @rFromDueDate date='',
		   @rToDueDate date='',
		   @rBookPublisher nvarchar(200)='' ,      --Mantis - 32621
	 	   @rAuthor nvarchar(200)='',          --Mantis - 32621
		   @rClassId int = 0, --mantis - 34518
		   @rDivisionId int = 0, --mantis - 34518
		   @rBookDepartment nvarchar(150) = '' --mantis - 34518
		         
           
AS
SET NOCOUNT ON
BEGIN
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
		SET @rBookDepartment = sCommon.fSearchStringGet(@rBookDepartment) --mantis - 34518
SELECT   
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   BL.Id AS BookLogId,
	   BL.LibraryId,
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	'Employee'
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,

		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.EmployeeName
			WHEN BL.ReaderSourceTypeId = 2003 THEN vSF.Name
			ELSE
			''
			END) AS Name,
			
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.DepartmentName
			WHEN BL.ReaderSourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
		 
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	Emp.Code
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
	   BL.ReaderSourceTypeId,
	   BL.ReaderSourceId,
	   BL.LogDate,
	   BL.DueDate,
	   BL.ReturnDate,
	   BM.Code AS BookCode,
	   BM.Title AS BookName,
	   OM.DisplayTitle AS OrganizationName,
	    LM.ReportOrgTitle,
	    LM.SmallAddress1,
	    LM.SmallAddress2,
		vSF.ClassName,    --mantis - 34518
		vSF.DivisionName, --mantis - 34518
		ISNULL(BM.BookDepartment,'') AS BookDepartment  --mantis - 34518
	   
  FROM  
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 95 
		LEFT JOIN sStudent.vStudentLastAcademic vSF
			ON vSF.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 2003 
			--AND (SELECT IsActive FROM sSetup.tBatchMaster WHERE Id=vSF.BatchId AND IsActive = 1) = 1	 edited by Jash for Issue no :- 0018773
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId			
 
  WHERE 
    BL.StatusId = 523 
	AND BL.LibraryId=@rLibraryId
	AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
	AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
	AND ((BL.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,'') = ''))
	AND ((BL.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,'') = ''))
	AND ((BL.ReaderSourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0)) 
	AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))   --Mantis - 32621
	AND ((BM.Author like @rAuthor) OR (@rAuthor=''))         --Mantis - 32621
	AND ((vSF.ClassId=@rClassId) OR (@rClassId=0)) --mantis - 34518
	AND ((vSF.DivisionId=@rDivisionId) OR (@rDivisionId=0))  --mantis - 34518
	AND ((BM.BookDepartment like @rBookDepartment) OR (ISNULL(@rBookDepartment,'') =''))--mantis - 34518


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 CREATE OR ALTER PROCEDURE [sLibrary].[pRptBookPenaltyDetailGet] 
	
	 @rBookLogId BIGINT

	 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
   SELECT 
			BL.Id AS BookLogId,
			SA.Code AS ReaderCode,
			SA.Name AS ReaderName,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.ReturnDate,
			'' AS BatchName,
	        OM.Title AS OrgName,
	        BLP.PenaltyDays,
			BLP.PenaltyRate,
			BLP.PenaltyAmount,
			LM.Title AS Library
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sLibrary.tBookLogPenalty BLP ON BLP.BookLogId = BL.Id 
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND SA.BatchId = BL.BatchId 
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.Id = BL.BatchId AND BMM.IsInContext = 1 --AND BMM.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			BL.Id = @rBookLogId
	UNION

	SELECT 
			BL.Id AS BookLogId,
			EM.Code AS ReaderCode,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.ReturnDate,
			'' AS BatchName,
	        '' AS OrgName,
	        BLP.PenaltyDays,
			BLP.PenaltyRate,
			BLP.PenaltyAmount,
			LM.Title AS Library
	         
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sLibrary.tBookLogPenalty BLP ON BLP.BookLogId = BL.Id 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			BL.Id = @rBookLogId
			AND ISNULL(EM.IsOtherUser,0) = 0 
	UNION 

	SELECT 
			BL.Id AS BookLogId,
			'' AS ReaderCode,
			'' AS ReaderName,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.ReturnDate,
			'' AS BatchName,
	        '' AS OrgName,
	        BLP.PenaltyDays,
			BLP.PenaltyRate,
			BLP.PenaltyAmount,
			LM.Title AS Library
			
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sLibrary.tBookLogPenalty BLP ON BLP.BookLogId = BL.Id 
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			(BL.ReaderSourceTypeId != 95 AND BL.ReaderSourceTypeId != 2003)
			AND BL.Id = @rBookLogId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pRptBookPurchaseListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rAccessionNo nvarchar(50)='',
	 @rClassificationNo nvarchar(50)='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 @rBookSubjectDrop nvarchar(200)='',
	 @rBookSubjectText nvarchar(200)='',
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date=''
           
AS
SET NOCOUNT ON
BEGIN
	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rAccessionNo = sCommon.fSearchStringGet(@rAccessionNo)
		SET @rClassificationNo = sCommon.fSearchStringGet(@rClassificationNo)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
	END
	SELECT   
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Id AS BookId,
		BM.Code AS BookCode,
		BM.Title AS BookName,
		BM.Author,
		BM.Publisher,
		BM.ClassificationNo,
		BM.BookSubject,
		BM.AccessionNo,
		BM.Edition,
		BM.NoOfPages,
		BM.BookLanguage,
		BM.Supplier,
		BM.PurchaseDate,
		BM.Price,
		BM.ISBNNumber,
		BM.Location,
		BM.BookRemark,
		LM.ReportOrgTitle,
		LM.SmallAddress1,
		LM.SmallAddress2,
		BM.NoOfCopies,
		BM.BillNumber,
		BM.Currency,
		BM.BookEntryDate,
		SM.Title AS StatusName
	FROM  
		sLibrary.tBookMaster BM 
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
		INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.AccessionNo like @rAccessionNo) OR (@rAccessionNo=''))
		AND ((BM.ClassificationNo like @rClassificationNo) OR (@rClassificationNo=''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') =''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pRptFavouriteBooksCountGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rLibraryId int,
	 @rFromLogDate date,
	 @rToLogDate date
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BL.ReaderSourceTypeId,
			BL.ReaderSourceId,
			SA.Code AS ReaderCode,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
			SA.ClassId,
			SA.DivisionName,
			SA.DivisionId,
			SA.ClassName,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,			
			BL.LogDate,
			BL.DueDate,
			
			OM.DisplayTitle As OrgName,
			BL.OrgId,
			BL.BatchId,
			BM.Code AS BookCode,
			BM.Title AS BookName,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=BL.OrgId
		    LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
			
			
	WHERE 
			
		
		
		BL.StatusId=523
		AND (BL.LibraryId=@rLibraryId)
		AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
		AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
		
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pRptLibraryRegularUserGet]

		 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	--@rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 --@rOrgId smallint,
	 --@rBatchId int,
	 --@rClassId int,
	 --@rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rTopFrequency  smallint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT 
	    Top(@rTopFrequency) SA.StudentId,SA.Name,
		SA.RollNo,
		SA.Code,
		SA.ClassName,
		SA.DivisionName, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2 
			FROM sStudent.vStudentLastAcademic SA 
INNER JOIN sLibrary.tBookLog BL ON SA.StudentId=BL.ReaderSourceId
	WHERE ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.LibraryId=@rLibraryId) AND ReaderSourceTypeId = 2003  
		AND BL.StatusId = 523
		GROUP  by SA.StudentId,SA.Name,SA.RollNo,SA.Code,SA.ClassName,SA.DivisionName
ORDER BY COUNT(BL.Id) desc
		

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sLibrary].[pRptLostBookListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookSubjectText nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 @rBookSubjectDrop nvarchar(200)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	
	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
    END

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher AS Publisher,
		BM.Supplier AS Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
        LM.Code AS LibraryCode,	       
        LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo,
		BL.LogDate AS LogDate,
		ISNULL(BL.Remark,'') AS Remark,
		SA.Name AS ReaderName
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
		INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
		INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND SA.BatchId = BL.BatchId 
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND (BL.StatusId = 525)

	UNION

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher AS Publisher,
		BM.Supplier AS Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
        LM.Code AS LibraryCode,	       
        LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo,
		BL.LogDate AS LogDate,
		ISNULL(BL.Remark,'') AS Remark,
		EM.FirstName+' '+EM.LastName AS ReaderName
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
		INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND (BL.StatusId = 525)
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pRptMagazineMonthlyCount]

	 
	@rLibraryId int ,
	@rFromLogDate date='',
	@rToLogDate date='',
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rMagazineTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


	CREATE Table #table
	(
		NoOfCopies int,
		Id bigint 
	)
	Insert Into #table
		
	Select  M.NoOfCopies,M.Id
	From sLibrary.tMagazineMaster M
	WHere M.LibraryId =@rLibraryId
	AND (M.MagazineTypeId=@rMagazineTypeId)
  
	Select 
		MM.Code,
		MM.Title,
		MM.NoOfCopies,
		ISNULL(MM.Currency,'') AS Currency,
		MM.Price,
		MR.Id,
		MR.VolumeNumber,
		MR.MagazineAmount,
		MR.IssueNumber,
		CONVERT(date,ReceiveDate) ReceiveDate,
		@rBuilder1 As Builder1,
		@rBuilder2 As Builder2 ,
		(Select Sum(NoOfCopies) from #table) AS Total 
		 
	From sLibrary.tMagazineMaster MM
	INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId=MM.Id
	WHere MM.LibraryId =@rLibraryId
	AND  (MR.ReceiveDate>=@rFromLogDate) 
	AND (MR.ReceiveDate<=@rToLogDate)
	AND  (MM.MagazineTypeId=@rMagazineTypeId) 
	 
	ORder by ReceiveDate
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pRptMagazineMonthlyList]

	 
	@rLibraryId int=0 ,
 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rMagazineTypeId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		--Select 
		--	'' V1,'' V2,'' V3,'' V4,'' V5,'' V6,'' V7,'' V8,'' V9,'' V10,'' V11,'' V12,0 Id,
		--	'' Title,'' I1,'' I2,'' I3,'' I4,'' I5,'' I6,'' I7,'' I8,'' I9,'' I10,'' I11,'' I12 ,
		--	 0 P1,0 P2,0 P3,0 P4,0 P5,0 P6,0 P7,0 P8,0 P9,0 P10,0 P11,0 P12,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2,
		--    '' ReportOrgTitle,'' SmallAddress1,'' SmallAddress2
	Declare @lCount int
	Declare @MagazineId bigint
	Create Table #temp
	(
			Id int identity,MagazineId nvarchar(20),V1 nvarchar(max),V2 nvarchar(max),V3 nvarchar(max),V4 nvarchar(max),V5 nvarchar(max),V6 nvarchar(max),
			V7 nvarchar(max),V8 nvarchar(max),V9 nvarchar(max),V10 nvarchar(max),V11 nvarchar(max),V12 nvarchar(max),
			I1 nvarchar(max),I2 nvarchar(max),I3 nvarchar(max),I4 nvarchar(max),I5 nvarchar(max),I6 nvarchar(max),
			I7 nvarchar(max),I8 nvarchar(max),I9 nvarchar(max),I10 nvarchar(max),I11 nvarchar(max),I12 nvarchar(max),
			P1 decimal(8,2),P2 decimal(8,2),P3 decimal(8,2),P4 decimal(8,2),P5 decimal(8,2),P6 decimal(8,2),
			P7 decimal(8,2),P8 decimal(8,2),P9 decimal(8,2),P10 decimal(8,2),P11 decimal(8,2),P12 decimal(8,2),
	)
	Insert Into #temp
	(
			MagazineId--V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12
			
	)
    Select  Id from sLibrary.tMagazineMaster
    Where  LibraryId=@rLibraryId
    AND ((MagazineTypeId=@rMagazineTypeId) OR (@rMagazineTypeId=0))
    	
    select  @lCount=COUNT(*) from #temp
    while(@lCount>0)
    BEGIN
		select @MagazineId = MagazineId from #temp Where Id= @lCount
		 
		Update #temp Set V1 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
						AND Month(ReceiveDate)=1 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I1 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=1
					  AND tm.MagazineId=@MagazineId 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 P1 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=1)
					 Where MagazineId=@MagazineId 
					 
		  Update #temp Set V2 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=2 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					I2 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=2
					  AND tm.MagazineId=@MagazineId

					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					  P2 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=2)
					Where MagazineId=@MagazineId 
					 
		  Update #temp Set V3 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=3 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I3 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=3
					AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 P3 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=3)
					 Where MagazineId=@MagazineId 
					 
		  Update #temp Set V4 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=4 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I4 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=4
						AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 P4 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=4)
					 Where MagazineId=@MagazineId 
	                 
		     Update #temp Set V5 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=5 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I5 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=5
								AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					  P5 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=5)
					  Where MagazineId=@MagazineId
		
		  Update #temp Set V6 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=6 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I6 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=6
						AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ,
					  P6 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=6)
					 Where MagazineId=@MagazineId
					 
	  Update #temp Set V7 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=7
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I7 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=7
							AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					  P7= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=7)
					 Where MagazineId=@MagazineId
					 
		  Update #temp Set V8= STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=8
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I8 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=8
						AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ,
					  P8= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=8)
					 Where MagazineId=@MagazineId
					 
		  Update #temp Set V9 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=9
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I9 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=9
							AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 P9= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=9)
					 Where MagazineId=@MagazineId
					 
		  Update #temp Set V10 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=10
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I10 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=10
								AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ,
					  P10= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=10)
					 Where MagazineId=@MagazineId
					 
		  Update #temp Set V11 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'')
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=11
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ,
			 	    I11 = STUFF((SELECT     ',' +ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=11 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 P11= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=11)
					 Where MagazineId=@MagazineId
					 
		  Update #temp Set V12 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'')
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=12
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ,
					 I12 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=12
					AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					        P12= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=12)
					 Where MagazineId=@MagazineId
		 
	 
					  
					 
		Set @lCount=@lCount-1
    END

       
    
	Select Tm.V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12,M.Id,
			M.Title,I1,I2,I3,I4,I5,I6,I7,I8,I9,I10,I11,I12 
			,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2,
			LM.ReportOrgTitle,LM.SmallAddress1,LM.SmallAddress2
     from #temp Tm
     INNER JOIN sLibrary.tMagazineMaster M ON M.Id=Tm.MagazineId
     AND ((MagazineTypeId=@rMagazineTypeId) OR (@rMagazineTypeId=0))
     LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=M.LibraryId
    --  Where  LibraryId=110100001
    --AND ((MagazineTypeId=0) OR (0=0))
    
     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pRptMonthlyNotIssuingBookStudentListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rReaderSourceId bigint,
	 @rOrgGroupId int=0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromLogDate date='',
	 @rToLogDate date='',
	 @rLibraryId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT    
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.Name,
		SA.RollNo,
		SA.Code,
		SA.ClassName,
		SA.DivisionName

	FROM sStudent.vStudentLastAcademic SA
INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
 LEFT JOIN
(SELECT DISTINCT ISNULL(BL.ReaderSourceId,0) AS StudentId FROM  sLibrary.tBookLog BL 
	INNER JOIN sSetup.tOrganizationMaster OM ON BL.OrgId = OM.Id
	WHERE BL.LibraryId=@rLibraryId 
	AND OM.OrgGroupId = @rOrgGroupId AND BL.StatusId = 523 AND ReaderSourceTypeId = 2003 
	AND ((BL.LogDate>= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))) B ON SA.StudentId= B.StudentId
WHERE B.StudentId IS NULL AND OM.OrgGroupId = @rOrgGroupId
	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sLibrary].[pRptReaderBookListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rCode nvarchar(20) = '',  --added
	 @rBookPublisher nvarchar(200)='' ,      --Mantis - 32621
	 @rAuthor nvarchar(200)='' 	 --Mantis - 32621
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	If(@rReaderSourceTypeId=2003)
	BEGIN
		SELECT

				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				BL.Id AS BookLogId,
				BM.Code AS ResourceCode,
				BM.Title AS ResourceName,
				BL.LogDate,
				BL.DueDate,
				IS1.NoOfBookIssuable,
				BL.StatusId ,
				SM.Title AS Status,
				SA.Name,
				SA.RollNo,
				SA.Code,
				SA.ClassName,
				SA.DivisionName,
				LM.ReportOrgTitle,
				LM.SmallAddress1,
				LM.SmallAddress2,
				ISNULL(U.DisplayTitle,'') AS UserName-- added by dhananjay for mantis : 0035757

		FROM
				sLibrary.tBookLog BL
				INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
				INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
				INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND IS1.LibraryId = BL.LibraryId --Added LibraryId for mantis : 35942 by Nilesh
				INNER JOIN sSetup.tBatchMaster B ON SA.BatchId = B.Id --AND B.IsActive = 1
				LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
				LEFT JOIN sSecurity.tUser U ON U.Id=BL.CreatedUserId-- added by dhananjay for mantis : 0035757
		WHERE
				((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
			--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
			AND (SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.StatusId=523)
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND (SA.Code=@rCode OR @rCode='') --added
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
		AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621
	END
	ELSE If(@rReaderSourceTypeId=95)
	BEGIN
			SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
			SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
		SELECT

				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				BL.Id AS BookLogId,
				BM.Code AS ResourceCode,
				BM.Title AS ResourceName,
				BM.BookSubject,
				BL.LogDate,
				BL.DueDate,
				IS1.NoOfBookIssuable,
				BL.StatusId,
				SM.Title AS Status,
				BL.IsCurrentStatus,
				EM.FirstName+' '+EM.LastName AS Name,
				EM.Code,
				ODM.Title AS EmpDept,
				LM.ReportOrgTitle,
				LM.SmallAddress1,
				LM.SmallAddress2,
				'' AS UserName-- added by dhananjay for mantis : 0035757
		FROM
				sLibrary.tBookLog BL
				LEFT JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
				INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
				INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004 AND IS1.LibraryId = BL.LibraryId--Added LibraryId for mantis : 35942 by Nilesh
				LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId

		WHERE
				((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
			--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.StatusId=523)
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND  ISNULL(EM.IsOtherUser,0) = 0
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))		   --Mantis - 32621
			AND (EM.Code=@rCode OR @rCode='') --mantis id : 0035097
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pRptSpineLabelGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookSubjectText nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 @rBookSubjectDrop nvarchar(500)='',
	 --Add for Mantis Id: 0037797
	 @rFromBookCode nvarchar(50)='',
	 @rToBookCode nvarchar(50)='',
	 @rSpecificCode nvarchar(max) ='' --Add for Mantis Id: 0039954
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

--Start : Add for Mantis Id: 0039954
	DECLARE @ListofBookCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
			INSERT INTO @ListofBookCodes
	
	select q2.value from
		(SELECT cast('<x>'+replace(@rSpecificCode,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
		(SELECT x.value('.','nvarchar(max)') as value FROM thexml.nodes('x') as f(x))q2
--End : Add for Mantis Id: 0039954
		
	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
    END

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher,BM.Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
		BM.BookLanguage,
		BM.BookCustomTag,
		BM.BookTag,
		BM.Location,
		BM.ISBNNumber,
		LM.ReportOrgTitle,
        LM.SmallAddress1,
        LM.SmallAddress2,
        CASE WHEN BM.BookDepartment is null THEN 'Blank'
            WHEN BM.BookDepartment='' THEN 'Blank'  ELSE BM.BookDepartment END AS  BookDepartment,
        BM.NoOfCopies,
        LM.Code AS LibraryCode,	       
        LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo,
		BM.ClassificationNo
		
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((BM.Code >= @rFromBookCode) OR (@rFromBookCode=''))  --Add for Mantis Id: 0037797
		AND ((BM.Code <= @rToBookCode) OR (@rToBookCode='')) 
		AND ((BM.Code IN(SELECT Code FROM @ListofBookCodes)) OR (ISNULL(@rSpecificCode,'') = '')) --Add for Mantis Id: 0039954

		ORDER BY
		CASE WHEN BM.Code like '%[0-9]%' 
			THEN Replicate('0', 100 - Len(BM.Code)) + BM.Code
			ELSE BM.Code  END
		
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pValidateImportBook]
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rRecordId Int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),             
        @1ReturnCode int = 1,
        @1ExistBookCode nvarchar(max) = '',
        @1DuplicateBookCode nvarchar(max) = '',
		@lExistAccessionNo nvarchar(max) = '',
		@lDuplicateAccessionNo nvarchar(max) = '',
		@lAccessionNo nvarchar(50) 
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(25),
        Title nvarchar(100),
		AccessionNo nvarchar(50)
  )
  INSERT INTO #tTable1
	(
	    Code,
	    Title,
		AccessionNo   
    ) 
   SELECT
        Code,
        Title,
		AccessionNo	    
   
   FROM OPENXML (@intDoc, '/Table/ImportBook', 1)
   With
   (
   
        Code nvarchar(25) '@Code',   
        Title nvarchar(100) '@Title',
		AccessionNo nvarchar(50) '@AccessionNo'     
   )     
   
EXEC sp_xml_removedocument @intDoc
			
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Code Should not be empty' AS BookCode
END
ELSE
IF EXISTS(SELECT 1 fROM #tTable1 WHERE Title IS NULL OR Title COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Title Should not be empty' AS BookCode
END
ELSE
IF EXISTS(SELECT 1 fROM #tTable1 WHERE AccessionNo IS NULL OR AccessionNo COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'AccessionNo Should not be empty' AS BookCode
END
ELSE
BEGIN
			
SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 
BEGIN

	SELECT         
	@lCode = Code,
	@lAccessionNo = AccessionNo  	 
	FROM #tTable1 WHERE Id = @lCount    

	IF Exists ((select 1 from sLibrary.tBookMaster where LibraryId = @rOrgId AND Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT))         
    BEGIN
		SET @1ExistBookCode = @1ExistBookCode + @lCode + ','
    END	    
	IF Exists ((select 1 from sLibrary.tBookMaster where LibraryId = @rOrgId AND AccessionNo COLLATE DATABASE_DEFAULT = @lAccessionNo COLLATE DATABASE_DEFAULT))       
    BEGIN
		SET @lExistAccessionNo = @lExistAccessionNo + @lAccessionNo + ','
    END	    
	
	SET @lCount = @lCount - 1	
	END		

	SELECT @1DuplicateBookCode=COALESCE(@1DuplicateBookCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
	IF(@1DuplicateBookCode IS NOT NULL AND @1DuplicateBookCode != '')
	BEGIN
		SET @1DuplicateBookCode = 'Duplicate Code : ' + @1DuplicateBookCode
		SELECT @1DuplicateBookCode AS StudentCode
	END
	SELECT @lDuplicateAccessionNo=COALESCE(@lDuplicateAccessionNo ,'') + AccessionNo + ',' FROM #tTable1 GROUP BY AccessionNo HAVING ( COUNT(AccessionNo) > 1 )
	IF(@lDuplicateAccessionNo IS NOT NULL AND @lDuplicateAccessionNo != '')
	BEGIN
		SET @lDuplicateAccessionNo = 'Duplicate AccessionNo : ' + @lDuplicateAccessionNo
		SELECT @lDuplicateAccessionNo AS DuplicateAccessionNo
	END
	IF(@1ExistBookCode IS NULL OR @1ExistBookCode = '')
	BEGIN
		SELECT '' AS BookCode
	END
	ELSE IF (@1ExistBookCode IS NOT NULL AND @1ExistBookCode != '' AND @rRecordId=1)
	BEGIN
		SET @1ExistBookCode = 'Exist Code : ' + @1ExistBookCode
		Select @1ExistBookCode AS BookCode
	END
	ELSE IF (@1ExistBookCode IS NOT NULL AND @1ExistBookCode != '' AND @rRecordId=2)
	BEGIN
		--SET @1ExistBookCode = 'Exist Code : ' + @1ExistBookCode
		Select '' AS BookCode
	END

	IF(@lExistAccessionNo IS NULL OR @lExistAccessionNo = '')
	BEGIN
		SELECT '' AS ExistAccessionNo
	END
	ELSE IF (@lExistAccessionNo IS NOT NULL AND @lExistAccessionNo != '' AND @rRecordId=1)
	BEGIN
		SET @lExistAccessionNo = 'Exist AccessionNo : ' + @lExistAccessionNo
		Select @lExistAccessionNo AS ExistAccessionNo
	END
	ELSE IF (@lExistAccessionNo IS NOT NULL AND @lExistAccessionNo != '' AND @rRecordId=2)
	BEGIN
		--SET @1ExistBookCode = 'Exist Code : ' + @1ExistBookCode
		Select '' AS ExistAccessionNo
	END
END
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pViewBookDetailGet]
	 @rResourceSourceId bigint,
	 @rIsCurrentStatus bit,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @rReaderSourceTypeId smallint 
	Select @rReaderSourceTypeId=ReaderSourceTypeId from sLibrary.tBookLog WHERE ResourceSourceId=@rResourceSourceId AND IsCurrentStatus=@rIsCurrentStatus
	IF(@rReaderSourceTypeId IS NOT NULL)
	BEGIN
	SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus AND BL.ReaderSourceTypeId=2003
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId 
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		
		UNION ALL
		
		SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			ODM.Title as ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus AND BL.ReaderSourceTypeId=95
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		AND  ISNULL(EM.IsOtherUser,0) = 0
	END
	ELSE
	BEGIN
	
		SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			'' AS ReaderName,
			'' AS ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sLibrary].[pViewMyBookDetailGet]
	 @rResourceSourceId bigint,
	 @rIsCurrentStatus bit,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @rReaderSourceTypeId smallint 
	Select @rReaderSourceTypeId=ReaderSourceTypeId from sLibrary.tBookLog WHERE ResourceSourceId=@rResourceSourceId AND IsCurrentStatus=@rIsCurrentStatus
	IF(@rReaderSourceTypeId IS NOT NULL)
	BEGIN
	SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus AND BL.ReaderSourceTypeId=2003
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId 
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		
		UNION ALL
		
		SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			ODM.Title as ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus AND BL.ReaderSourceTypeId=95
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		AND  ISNULL(EM.IsOtherUser,0) = 0
	END
	ELSE
	BEGIN
	
		SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			'' AS ReaderName,
			'' AS ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sLibrary].[pXMLNewspaperLogAdd]
(
	@rXml  nvarchar(MAX),
	@rOrgId int,
	@rCreatedUserId bigint,
	@rLibraryId int = 0	--mantis: 44411
)
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	BEGIN TRY

		CREATE TABLE #tempTable  
		(
			Id bigint identity,
			NewspaperId smallint,
			NewspaperTitle nvarchar(300),
			NewspaperLanguage nvarchar(100),
			NewsType nvarchar(30),
			NewspaperDate datetime,
			NoOfCopy int,
			NewspaperAmount decimal(12,2)
		)

		INSERT INTO #tempTable
		(
			NewspaperTitle,
			NewspaperLanguage,
			NewsType,
			NewspaperDate,
			NoOfCopy,
			NewspaperAmount
		)
		SELECT	
			A.NewspaperTitle,
			A.NewspaperLanguage,
			A.NewsType,
			CONVERT(datetime, A.NewspaperDate, 103) AS NewspaperDate,
			A.NoOfCopy,
			A.NewspaperAmount
		FROM OPENXML (@intDoc, '/Table/NewspaperLog', 1)
		WITH
		( 
			NewspaperTitle NVARCHAR(300) '@NewspaperTitle',
			NewspaperLanguage NVARCHAR(100) '@NewspaperLanguage',
			NewsType NVARCHAR(30) '@NewsType',
			NewspaperDate datetime '@NewspaperDate',
			NoOfCopy int '@NoOfCopy',
			NewspaperAmount decimal(12,2) '@NewspaperAmount' 
		)A 

		--Select * from #tempTable return
		DECLARE @lCount int,@lId int
		SELECT @lCount = COUNT(Id) FROM #tempTable
		SELECT Top 1 @lId=Id FROM #tempTable
	
		WHILE @lId <= @lCount 
		BEGIN

			DECLARE @lNewspaperId BIGINT, @lNewspaperDate date, @lNoOfCopy Int, @lNewspaperAmount int
	
			SELECT @lNewspaperId = NM.Id 
			FROM sLibrary.tNewspaperMaster AS NM
				INNER JOIN #tempTable AS TT ON TT.NewspaperTitle = NM.Title 
			WHERE  TT.Id = @lId
				AND NM.LibraryId = @rLibraryId	--mantis: 44411

			SELECT @lNewspaperDate = NewspaperDate from #tempTable where  Id = @lId
			SELECT @lNoOfCopy = NoOfCopy from #tempTable where  Id = @lId
			SELECT @lNewspaperAmount = NewspaperAmount from #tempTable where  Id = @lId
		
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tNewspaperLog', 0, 1, 1,@outNextNumber = @lNextNumber output

			print @lNextNumber
										
			SET IDENTITY_INSERT sLibrary.tNewspaperLog ON

			INSERT INTO sLibrary.tNewspaperLog
			(
				AutoId,
				NewspaperId,
				NewspaperDate,
				NoOfCopy,
				NewspaperAmount,
				CreatedUserId,
				CreatedDateTime 	
			)
			Values
			(	
				@lNextNumber,
				@lNewspaperId,
				@lNewspaperDate,
				@lNoOfCopy,
				@lNewspaperAmount,
				@rCreatedUserId,
				sCommon.fGetDate()   
			)

			SET IDENTITY_INSERT sLibrary.tNewspaperLog OFF
	
			SELECT @lNextNumber = MAX(AutoId) FROM sLibrary.tNewspaperLog
			EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sLibrary.tNewspaperLog', @rCurrentNumber = @lNextNumber 

			SET @lId=@lId+1
		
		END
		EXEC sp_xml_removedocument @intDoc
		SELECT 1 as Result
		DROP Table #tempTable
	END TRY	

	BEGIN CATCH 
		SELECT -1 AS Result,error_message() AS MSG
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanPayrollMappingAdd]
** Desc:  Get Year For EMIDetail Page 
** Auth:  Savan Vaghela
** Date:  01-March-2017
** Page:  /Pages/Hrm/Loan/EMIDetail.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    04-March-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pInstalmentGet]
CREATE OR ALTER PROCEDURE [sLoan].[pInstalmentGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @MinYear INT=0
DECLARE @MaxYear INT=0
DECLARE @YearMaster TABLE (RowID int IDENTITY,YearName INT)
SELECT @MinYear=MIN(YEAR(EmiDate)) from [sLoan].[tLoanEMI] 
SELECT @MaxYear=MAX(YEAR(EmiDate)) from [sLoan].[tLoanEMI] 

While (@MaxYear >=@MinYear)
	BEGIN
		INSERT INTO @YearMaster
		SELECT @MinYear
		SET @MinYear=@MinYear+1
	END

SELECT * FROM @YearMaster
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanTypeMasterAdd]
** Desc:  Create and Update Data in Loan Type Master Table
** Auth:  Savan Vaghela
** Date:  20-Febuary-2017
** Page:  /Pages/Hrm/Loan/LoanTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    20-Febuary-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pLoanTypeMasterAdd] 0,1001,3333,1001000000009
CREATE OR ALTER PROCEDURE [sLoan].[pLoanDetailAdd]
	    @rId BIGINT,
		@rLoanTypeId INT,
		@rEmployeeId BIGINT,
		@rLoanAmount DECIMAL(18,2),
		@rInterestRate DECIMAL(18,2),
		@rApprovedDate DATETIME,
		@rRepaymentStartDate DATETIME,
		@rInterestTypeId SmallINT,
		@rNoofInstallament SmallINT,
		@rOrgId SmallINT,
		@rIsObsolete bit =null,
        @rCreatedUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
			DECLARE @Interest DECIMAL(18,2)
			DECLARE @EMIMonthAmount DECIMAL(18,2)
			DECLARE @EMIInterestAmount DECIMAL(18,2)
			DECLARE @SeduleAmount DECIMAL(18,2)=@rLoanAmount


		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLoan.tLoanDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sLoan.tLoanDetail
				(
					Id,
					LoanTypeId,
					EmployeeId,
					LoanAmount,
					InterestRate,
					ApprovedDate,
					RepaymentStartDate,
					InterestTypeId,
					NoofInstallament,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					OrgId,
					IsCompleted
				)
				VALUES
				(
					@lNextNumber,
					@rLoanTypeId,
					@rEmployeeId,
					@rLoanAmount,
					@rInterestRate,
					@rApprovedDate,
					@rRepaymentStartDate,
					@rInterestTypeId,
					@rNoofInstallament,
					0,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgId,
					0
				)
			

				SET @Interest =(@rLoanAmount*@rInterestRate*@rNoofInstallament)/(100*12)
				SET @EMIMonthAmount=@rLoanAmount/@rNoofInstallament

					
				IF	(@rInterestTypeId=1)
					BEGIN
						SET @EMIInterestAmount=0
					END
	
				ELSE IF (@rInterestTypeId=2)
					BEGIN
						SET @EMIInterestAmount=@Interest/@rNoofInstallament
					END


				WHILE (@rNoofInstallament <> 0)
					BEGIN
						IF(@rInterestTypeId=3)
							BEGIN
								SET @EMIInterestAmount = ((@SeduleAmount*@rInterestRate*@rNoofInstallament)/ (100*12))/@rNoofInstallament
								SET @SeduleAmount=@SeduleAmount-@EMIMonthAmount 
							END

						INSERT INTO sLoan.tLoanEMI (LoanDetailId,EmiDate,EmiAmount,InterestAmount,StatusId,CreatedUserId,CreatedDateTime,IsObsolete)
						SELECT @lNextNumber,@rRepaymentStartDate,ROUND(@EMIMonthAmount,0),ROUND(@EMIInterestAmount,0),0,@rCreatedUserId,sCommon.fGetDate(),0
						
						
						SET @rRepaymentStartDate= DATEADD(month, 1, @rRepaymentStartDate);
						SET @rNoofInstallament =@rNoofInstallament -1
					END

				
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  sLoan.tLoanDetail
				SET
				LoanTypeId=@rLoanTypeId,
				EmployeeId=@rEmployeeId,
				LoanAmount=@rLoanAmount,
				InterestRate=@rInterestRate,
				ApprovedDate=@rApprovedDate,
				RepaymentStartDate=@rRepaymentStartDate,
				InterestTypeId=@rInterestTypeId,
				NoofInstallament=@rNoofInstallament,
				IsObsolete=@rIsObsolete,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
				WHERE Id = @rId


				--UPDATE sLoan.tLoanEMI SET IsObsolete=1, UpdatedUserId=@rCreatedUserId,UpdatedDateTime=sCommon.fGetDate() WHERE LoanDetailId=@rId
				DELETE FROM sLoan.tLoanEMI  WHERE LoanDetailId=@rId
				

				SET @Interest =(@rLoanAmount*@rInterestRate*@rNoofInstallament)/(100*12)
				SET @EMIMonthAmount=@rLoanAmount/@rNoofInstallament

					
				IF	(@rInterestTypeId=1)
					BEGIN
						SET @EMIInterestAmount=0
					END
	
				ELSE IF (@rInterestTypeId=2)
					BEGIN
						SET @EMIInterestAmount=@Interest/@rNoofInstallament
					END


				WHILE (@rNoofInstallament <> 0)
					BEGIN
						IF(@rInterestTypeId=3)
							BEGIN
								SET @EMIInterestAmount = ((@SeduleAmount*@rInterestRate*@rNoofInstallament)/ (100*12))/@rNoofInstallament
								SET @SeduleAmount=@SeduleAmount-@EMIMonthAmount 
							END

						INSERT INTO sLoan.tLoanEMI (LoanDetailId,EmiDate,EmiAmount,InterestAmount,StatusId,CreatedUserId,CreatedDateTime,IsObsolete)
						SELECT @lNextNumber,@rRepaymentStartDate,ROUND(@EMIMonthAmount,0),ROUND(@EMIInterestAmount,0),0,@rCreatedUserId,sCommon.fGetDate(),0
						
						
						SET @rRepaymentStartDate= DATEADD(month, 1, @rRepaymentStartDate);
						SET @rNoofInstallament =@rNoofInstallament -1
					END





				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanEmiDetailGet]
** Desc:  Get EMI Schedule ANd Interest Details
** Auth:  Savan Vaghela
** Date:  21-Febuary-2017
** Page:  /Pages/Hrm/Loan/LoanDetail.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    21-Febuary-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pLoanEmiDetailGet] 60000,10,12,'2017-02-22',2
CREATE OR ALTER PROCEDURE [sLoan].[pLoanEmiDetailGet]
	@LoanAmount DECIMAL(18,2),
	@RateOfInterest DECIMAL(18,2),
	@NoOfInstallament SMALLINT,
	@ApprovedDate DATE,
	@InterestType SMALLINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @Interest DECIMAL(18,2)
	DECLARE @EMIMonthAmount DECIMAL(18,2)
	DECLARE @EMIInterestAmount DECIMAL(18,2)
	DECLARE @SeduleAmount DECIMAL(18,2)=@LoanAmount
	DECLARE @DiffAmount DECIMAL(18,0)

	SET @Interest =(@LoanAmount*@RateOfInterest*@NoOfInstallament)/(100*12)
	SET @EMIMonthAmount=@LoanAmount/@NoOfInstallament
	SET @DiffAmount = (@LoanAmount - (ROUND(@EMIMonthAmount,0) * @NoOfInstallament))
	 
	DECLARE   @EmployeeMaster TABLE	(RowID int Identity(1,1),EMIDate DateTIME,EMIMonthAmount DECIMAL(18,2),EMIInterestAmount DECIMAL(18,2))
	
	IF	(@InterestType=1)
		BEGIN
			SET @EMIInterestAmount=0
		END
	
	ELSE IF (@InterestType=2)
		BEGIN
			SET @EMIInterestAmount=@Interest/@NoOfInstallament
		END


	WHILE (@NoOfInstallament <> 0)
		BEGIN
			IF(@InterestType=3)
				BEGIN
					SET @EMIInterestAmount = ((@SeduleAmount*@RateOfInterest*@NoOfInstallament)/ (100*12))/@NoOfInstallament
					SET @SeduleAmount=@SeduleAmount-@EMIMonthAmount 
				END
		IF(@NoOfInstallament = 1)
			BEGIN
			INSERT INTO @EmployeeMaster (EMIDate,EMIMonthAmount,EMIInterestAmount)
			SELECT @ApprovedDate,ROUND(@EMIMonthAmount+ @DiffAmount,0),ROUND(@EMIInterestAmount ,0)
			SET @ApprovedDate= DATEADD(month, 1, @ApprovedDate);
			SET @NoOfInstallament =@NoOfInstallament -1
			END
		ELSE
			BEGIN
			INSERT INTO @EmployeeMaster (EMIDate,EMIMonthAmount,EMIInterestAmount)
			SELECT @ApprovedDate,ROUND(@EMIMonthAmount,0),ROUND(@EMIInterestAmount,0)
			SET @ApprovedDate= DATEADD(month, 1, @ApprovedDate);
			SET @NoOfInstallament =@NoOfInstallament -1
			END
			
		END

		
	SELECT Emp.RowID
	,UPPER(SUBSTRING( DateName(month,DateAdd(month,MONTH(Emp.EmiDate) ,-1)),1,3)  +'-'+ CAST(YEAR(Emp.EmiDate)  as VARCHAR))  AS [MonthName]
	,Emp.EMIMonthAmount AS MonthAmount
	,Emp.EMIInterestAmount AS Interest
	,Emp.EMIMonthAmount +Emp.EMIInterestAmount AS Total
	,'Pending' AS Status
	--,SUBSTRING(REPLACE(CONVERT(NVARCHAR(50),newid()),'-',''),0,10) AS Status
	--,ABS(CHECKSUM(NewId())) % 3 AS StatusLabel
	,0 AS StatusLabel
	FROM @EmployeeMaster AS Emp
	ORDER BY RowID 
	SELECT SUM(EMIInterestAmount)TotalInterest,SUM(EMIMonthAmount),SUM(EMIInterestAmount+EMIMonthAmount) FROM @EmployeeMaster

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanEMIGet]
** Desc:  Get EMI Schedule ANd Interest Details
** Auth:  Savan Vaghela
** Date:  21-Febuary-2017
** Page:  /Pages/Hrm/Loan/LoanDetail.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    21-Febuary-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pLoanEMIGet] 9998000000001
CREATE OR ALTER PROCEDURE [sLoan].[pLoanEMIGet]
	@rLoanDetailId BIGINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT  
		EMI.Id AS ID 
		,ROW_NUMBER() OVER(ORDER BY  EMI.EmiDate) AS  RowID
		,UPPER(SUBSTRING( DateName(month,DateAdd(month,MONTH(EMI.EmiDate) ,-1)),1,3)  +'-'+ CAST(YEAR(EMI.EmiDate)  as VARCHAR))  AS [MonthName]
		,EMI.EmiAmount AS MonthAmount
		,
EMI.InterestAmount AS Interest
		,EMI.EmiAmount +EMI.InterestAmount AS Total
		, CASE EMI.StatusId WHEN 0 THEN  'Pending' WHEN 1 THEN 'Paid' WHEN 2 THEN 'Skip' END  AS Status
		,EMI.StatusId AS StatusLabel
		,REPLACE(CONVERT(VARCHAR(20),EMI.EmiDate,106),'
','-') AS InstallamentDate 
	FROM sLoan.tLoanEMI AS EMI 
	WHERE EMI.LoanDetailId=@rLoanDetailId AND EMI.IsObsolete=0
	ORDER BY EMI.EmiDate



	SELECT SUM(InterestAmount),SUM(EmiAmount),SUM(InterestAmount+EmiAmount) FROM sLoan.tLoanEMI AS EMI WHERE EMI.LoanDetailId=@rLoanDetailId AND EMI.IsObsolete=0 AND EMI.StatusId in (0,1)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanEMIGetForPaid]
** Desc:  Get Data From LoanTypeMaster Table 
** Auth:  Savan Vaghela
** Date:  23-Febuary-2017
** Page:  /Pages/Hrm/Loan/EMIDetail.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    23-Febuary-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pLoanEMIGetForPaid] 1001,1001,100100002,2,2017
CREATE OR ALTER PROCEDURE [sLoan].[pLoanEMIGetForPaid]
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rLoanTypeId INT,
	@rMonth smallint,
	@rYear smallint,
	@rLoanStatus SMALLINT,
	@rInstalmentStatus SMALLINT,
	@rEmployeeOrgId SMALLINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT 
		
		EMI.Id 
		,LND.Id AS LoanID
	    ,LND.EmployeeId
		,ISNULL(EMP.[FirstName],'') +' '+ ISNULL(EMP.[LastName],'')  as [Employee]
		,EMP.[Code]
		,CONVERT(VARCHAR(20), LND.RepaymentStartDate,103) AS RepaymentStartDate
		,EMI.EmiAmount
		,EMI.InterestAmount
		,EMI.EmiAmount+ EMI.InterestAmount AS 'Total'
		,EMI.StatusId
		,UPPER(DateName(month,DateAdd(month,MONTH(EMIDate) ,-1))  +'-'+ CAST(YEAR(EMIDate)  as VARCHAR))  AS [MonthName] 
		,CASE EMI.StatusId WHEN 0 THEN  'Pending' WHEN 1 THEN 'Paid' WHEN 2 THEN 'Skip' END  AS Status
		,EMI.StatusId AS StatusLabel
		,CASE WHEN  EMI.StatusId in (1,2)  THEN  CAST (0 AS BIT)  ELSE    CAST (1 AS BIT)  END  AS Enabled
		,ITM.Title AS 'IntrestType'
		,LTM.Title AS 'LoanType'
		,EMI.EmiDate
 	FROM sLoan.tLoanDetail  AS LND
		INNER JOIN [sLoan].[tLoanEMI] AS EMI ON EMI.LoanDetailId=LND.Id
		LEFT  JOIN sLoan.tLoanTypeMaster      AS LTM ON LTM.Id=LND.LoanTypeId
		LEFT  JOIN sLoan.tInsterestTypeMaster AS ITM ON ITM.Id=LND.InterestTypeId
		INNER JOIN sHrm.tEmployeeMaster       AS EMP ON EMP.Id=LND.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster AS OMD ON OMD.Id=EMP.OrgID
	WHERE EMI.IsObsolete=0 
		AND (LND.[OrgId] = @rOrgId)
		AND ((EMP.OrgID=@rEmployeeOrgId ) OR (@rEmployeeOrgId=-1 ))
		AND MONTH(EMI.EmiDate)=@rMonth
		AND YEAR(EMI.EmiDate)=@rYear 
		AND ((LND.IsCompleted=CONVERT(bit,@rLoanStatus)) OR (@rLoanStatus=-1))
		AND ((LND.LoanTypeId=@rLoanTypeId) OR (@rLoanTypeId=-1))
		AND ((EMI.StatusId=@rInstalmentStatus) OR  (@rInstalmentStatus=-1))
		AND ISNULL(EMP.IsOtherUser,0) = 0
	ORDER BY EMP.[Code],LND.Id,EMI.EmiDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanEMIGetForPaid]
** Desc:  Get Loan EMI Status
** Auth:  Savan Vaghela
** Date:  27-Febuary-2017
** Page:  Pages/Hrm/Loan/EMIDetail.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    27-Febuary-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pLoanEMIStatusChange] 48,1001000000023

CREATE OR ALTER PROCEDURE [sLoan].[pLoanEMIStatusChange]
	@rLoanDetailId BIGINT,
	@rLoanEMIId BIGINT,
	@rStatusId SMALLINT,
	@rCreatedUserId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
--DECLARE @rLoanDetailId BIGINT =9999000000001 
--DECLARE @rLoanEMIId BIGINT =104
--DECLARE @rStatusId SMALLINT =1
--DECLARE @rCreatedUserId bigint =1

	IF (@rStatusId=1)
		BEGIN
			UPDATE sLoan.tLoanEMI SET StatusId=@rStatusId WHERE ID=@rLoanEMIId

			IF NOT EXISTS(	SELECT ID FROM [sLoan].[tLoanEMI] WHERE LoanDetailId=@rLoanDetailId	AND IsObsolete=0 AND  ID>@rLoanEMIId )
				BEGIN
					UPDATE [sLoan].[tLoanDetail] SET IsCompleted=1 WHERE Id=@rLoanDetailId
				END
		END
	
	ELSE IF (@rStatusId=2)
		BEGIN
			DECLARE  @EmiDate DATE=null
			DECLARE  @EmiAmount DECIMAL(18,2)=null
			DECLARE  @InterestAmount DECIMAL(18,2)=null

			SELECT 
				@EmiAmount=EmiAmount,@InterestAmount=InterestAmount   
			FROM sLoan.tLoanEMI 
			WHERE ID=@rLoanEMIId AND IsObsolete=0

			SELECT 
				@EmiDate =MAX(EmiDate) 
			FROM sLoan.tLoanEMI 
			WHERE LoanDetailId=@rLoanDetailId AND IsObsolete=0

			SET @EmiAmount=ISNULL(@EmiAmount,0)
			SET @InterestAmount=ISNULL(@InterestAmount,0)
			SET @EmiDate=DATEADD(MONTH,1,ISNULL(@EmiDate,sCommon.fGetDate()))
			
			UPDATE sLoan.tLoanEMI 
			SET StatusId=2 
			WHERE ID=@rLoanEMIId
			
			
			INSERT INTO sLoan.tLoanEMI(LoanDetailId,EmiAmount,EmiDate,StatusId,InterestAmount,CreatedUserId,CreatedDateTime,IsObsolete) 
			VALUES (@rLoanDetailId,@EmiAmount,@EmiDate,0,0,@rCreatedUserId,sCommon.fGetDate(),0)


			DECLARE @EMITable TABLE (RowID int IDENTITY,EMIID BIGINT,InterestAmount DECIMAL(18,2))

			INSERT INTO @EMITable 
			
			SELECT ID,InterestAmount 
			FROM sLoan.tLoanEMI 
			WHERE ID >=@rLoanEMIId AND  LoanDetailId=@rLoanDetailId AND IsObsolete=0 
			ORDER BY EmiDate


			DECLARE @Count int=(SELECT COUNT(1) FROM @EMITable)
			DECLARE @Counter int=1

			WHILE (@Count>@Counter)
				BEGIN
					DECLARE @IntAmount DECIMAL(18,2)
					DECLARE @EmiID BIGINT

					SELECT @IntAmount=InterestAmount 
					FROM @EMITable 
					WHERE RowID=@Counter
				
					SELECT @EmiID=EMIID 
					FROM @EMITable 
					WHERE RowID=(@Counter+1)
					
					UPDATE sLoan.tLoanEMI 
					SET InterestAmount =@IntAmount 
					WHERE Id=@EmiID
					
					PRINt     CAST (@EmiID AS VARCHAR(50)) +'-'+  CAST (@IntAmount AS VARCHAR(50)) 
					SET @Counter=@Counter+1
				END
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanEMIGetForPaid]
** Desc:  Get Loan EMI Status
** Auth:  Savan Vaghela
** Date:  27-Febuary-2017
** Page:  Pages/Hrm/Loan/EMIDetail.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    27-Febuary-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pLoanEMIStatusGet] 47,1001000000023
CREATE OR ALTER PROCEDURE [sLoan].[pLoanEMIStatusGet]
	@rEmiID BIGINT,
	@rLoanID BIGINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	IF EXISTS(	SELECT ID
		FROM [sLoan].[tLoanEMI] 
		WHERE 
		LoanDetailId=@rLoanID 
		AND IsObsolete=0 
		AND StatusId in (0) 
		AND  ID<@rEmiID )
		BEGIN	
			SELECT CAST(1 AS BIT) AS Status
		END
	ELSE
		BEGIN
			SELECT CAST(0 AS BIT) AS Status
		END	

		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanListGet]
** Desc:  Get Data From LoanTypeMaster Table 
** Auth:  Savan Vaghela
** Date:  01-March-2017
** Page:  /Pages/Hrm/Loan/LoanTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    01-March-2017      Savan Vaghela       
** 1    09-May-2017        Savan Vaghela        Add Checked logic for checkbox Checked
************************************************************/
--EXEC [sLoan].[pLoanListGet] 1001,1001
CREATE OR ALTER PROCEDURE [sLoan].[pLoanListGet]
	@rOrgId smallint,
	@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	
	SELECT 
	LTM.Id AS LoanTypeId
	,LTM.Code,LTM.Title
	,ISNULL(LPM.PayElementId,0)PayElementId
	,PED.Code AS PayElementCode
	,PED.Title as PayElementTitle
	,CASE WHEN  ISNULL(LPM.PayElementId,0)=0 THEN  'Pending' ELSE 'Mapped'   END  AS Status
	,CASE WHEN  ISNULL(LPM.PayElementId,0)=0 THEN  0 ELSE 1  END AS StatusLabel
	,CASE WHEN  ISNULL(LPM.PayElementId,0)=0 THEN  CONVERT(BIT,0) ELSE CONVERT(BIT,1)  END AS Checked
	FROM [sLoan].[tLoanTypeMaster] as LTM
	LEFT JOIN [sLoan].[tLoanPayrollMapping] AS LPM ON LPM.LoanTypeId=LTM.Id AND LTM.OrgId=LPM.OrgId
	LEFT JOIN [sPayroll].[tPayElementDefault] AS PED ON PED.ID=LPM.PayElementId AND LPM.OrgId=LTM.OrgId
	WHERe  LTM.OrgId=@rOrgId
	ORDER BY 3 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanPayrollMappingAdd]
** Desc:  Get Data From LoanTypeMaster Table 
** Auth:  Savan Vaghela
** Date:  01-March-2017
** Page:  /Pages/Hrm/Loan/LoanPayrollMapping.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    01-March-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pLoanPayrollMappingAdd] 1001,1001,1001
CREATE OR ALTER PROCEDURE [sLoan].[pLoanPayrollMappingAdd]
	@rOrgId SMALLINT,
	@rLoanTypeId INT,
	@rPayElementId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	 
			IF NOT EXISTS (SELECT LoanTypeId FROM [sLoan].[tLoanPayrollMapping] WHERE OrgId=@rOrgId AND LoanTypeId=@rLoanTypeId)
				BEGIN	
					INSERT INTO [sLoan].[tLoanPayrollMapping] VALUES (@rLoanTypeId,@rPayElementId,@rOrgId)
					SELECT 1 AS Result

				END
			ELSE
				BEGIN
					UPDATE [sLoan].[tLoanPayrollMapping] SET PayElementId=@rPayElementId WHERE OrgId=@rOrgId AND LoanTypeId=@rLoanTypeId 
					SELECT 11 AS Result
				END
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanTypeMasterAdd]
** Desc:  Create and Update Data in Loan Type Master Table
** Auth:  Savan Vaghela
** Date:  20-Febuary-2017
** Page:  /Pages/Hrm/Loan/LoanTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    20-Febuary-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pLoanTypeMasterAdd] 0,1001,3333,1001000000009
CREATE OR ALTER PROCEDURE [sLoan].[pLoanTypeMasterAdd]
	    @rId int,
		@rCode nvarchar(100),
		@rTitle nvarchar(100),
		@rOrgId SmallINT,
		@rIsObsolete bit =null,
        @rCreatedUserId bigint 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		IF(@rId = 0)	
			BEGIN
				IF Exists(SELECT Id FROM [sLoan].[tLoanTypeMaster] WHERE Code=@rCode AND OrgId=@rOrgId )
					BEGIN
						SELECT -101 as Result
						RETURN
					END 
				IF Exists(SELECT Id FROM [sLoan].[tLoanTypeMaster]  WHERE Title=@rTitle AND OrgId=@rOrgId )
					BEGIN
						SELECT -102 as Result
						RETURN
					END 
			END
		
		ELSE
			BEGIN
				IF  Exists(SELECT Id FROM [sLoan].[tLoanTypeMaster]  WHERE Code=@rCode AND OrgId=@rOrgId AND Id<>@rId )
					BEGIN
						SELECT -101 as Result
						RETURN
					END
				IF  Exists(SELECT Id FROM [sLoan].[tLoanTypeMaster]  WHERE Title=@rTitle AND OrgId=@rOrgId  AND Id<>@rId )
					BEGIN
						SELECT -102 as Result
						RETURN
					END
			END
	
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
	
		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLoan.tLoanTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sLoan].[tLoanTypeMaster]
				(
					Id,
					Code,
					Title,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					OrgId
				)
				VALUES
				(
					@lNextNumber,
					@rCode,
					@rTitle,
					0,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgId
				)
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sLoan].[tLoanTypeMaster]
				SET
				Code=@rCode,
				Title=@rTitle,
				IsObsolete=@rIsObsolete,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
				WHERE Id = @rId
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pLoanTypeMasterAdd]
** Desc:  Get Data From LoanTypeMaster Table 
** Auth:  Savan Vaghela
** Date:  20-Febuary-2017
** Page:  /Pages/Hrm/Loan/LoanTypeMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    20-Febuary-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pLoanTypeMasterGet] '','',1001
CREATE OR ALTER PROCEDURE [sLoan].[pLoanTypeMasterGet]
	@rTitle VARCHAR(250),
	@rCode VARCHAR(250),
	@rOrgId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	SET @rCode = sCommon.fSearchStringGet(@rCode)

	SELECT
		LT.Id,
		LT.Code,
		LT.Title,
		LT.IsObsolete,
		LT.CreatedUserId,
		LT.CreatedDateTime,
		LT.UpdatedUserId,
		LT.UpdatedDateTime,
		LT.OrgId,
		case LT.[IsObsolete] when 0 then 'N' else 'Y' end as InActive
	FROM [sLoan].[tLoanTypeMaster] as LT
	WHERE (LT.OrgId = @rOrgId)  AND 
		((LT.Code LIKE @rCode) OR (@rCode='')) AND 
		((LT.Title LIKE @rTitle) OR (@rTitle=''))  
	ORDER BY LT.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pRptEmployeeLoanDetails]
** Desc:  30108-> Employee Loan Details Report
** Auth:  Savan Vaghela
** Date:  27-Febuary-2017
** Page:  /Pages/Hrm/IncomeTax/ReportCriteria/LoanReportCriteria.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    27-Febuary-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pRptEmployeeLoanDetails] 1001,0,0,0,0,'','',0
CREATE OR ALTER PROCEDURE [sLoan].[pRptEmployeeLoanDetails]
	@rOrgGroupId SMALLINT,
	@rOrgId SMALLINT,
	@rLoanTypeId INT,
	@rInterestTypeId SMALLINT=NULL,
	@rEmployeeID BIGINT,
	@rBuilder1 VARCHAR(MAX)=null,
	@rBuilder2 VARCHAR(MAX)=null,
	@rLoanStatus SMALLINT,
	@rEmployeeOrgId smallint
WITH EXECUTE AS CALLER
AS
BEGIN 


	DECLARE   @EmployeeMaster TABLE	(
		RowID int Identity(1,1)
		,EmployeeID BIGINT
		,InstallmentWiseTotal DECIMAL(18,2)
		,InstallmentWiseInterestTotal DECIMAL(18,2)
		,TotalLoanAmount DECIMAL(18,2)
		,TotalPaidAmount DECIMAL(18,2)
		,TotalPendingAmount DECIMAL(18,2)
		)
		
		
		INSERT INTO 
			@EmployeeMaster
				(
					EmployeeID
					,InstallmentWiseTotal
					,InstallmentWiseInterestTotal
					,TotalLoanAmount
					,TotalPaidAmount
					,TotalPendingAmount
				)
		
			SELECT 
			a.EmployeeId
			,SUM(InstallmentWiseTotal)InstallmentWiseTotal
			,SUM(InstallmentWiseInterestTotal)InstallmentWiseInterestTotal
			,SUM(TotalLoanAmount)TotalLoanAmount
			,SUM(TotalPaidAmount)TotalPaidAmount
			,SUM(TotalPendingAmount)TotalPendingAmount 
			FROM 
				(
					SELECT 
					LND.EmployeeId
					,(SELECT ISNULL(SUM(EmiAmount+InterestAmount),0) FROM [sLoan].[tLoanEMI] WHERE LoanDetailId=LND.Id AND IsObsolete=0 AND StatusId in (0,1)) AS InstallmentWiseTotal
					,(SELECT ISNULL(SUM(InterestAmount),0) FROM [sLoan].[tLoanEMI] WHERE LoanDetailId=LND.Id AND IsObsolete=0 AND StatusId in (0,1)) AS InstallmentWiseInterestTotal
					,LND.LoanAmount AS TotalLoanAmount 
					,(SELECT ISNULL(SUM(EmiAmount+InterestAmount),0) FROM [sLoan].[tLoanEMI] WHERE LoanDetailId=LND.Id AND IsObsolete=0 AND StatusId=1) AS  TotalPaidAmount	
					,(SELECT ISNULL(SUM(EmiAmount+InterestAmount),0) FROM [sLoan].[tLoanEMI] WHERE LoanDetailId=LND.Id AND IsObsolete=0 AND StatusId=0) AS  TotalPendingAmount	
					FROM sLoan.tLoanDetail  AS LND
							INNER JOIN sLoan.tLoanTypeMaster      AS LTM ON LTM.Id=LND.LoanTypeId
							INNER JOIN sLoan.tInsterestTypeMaster AS ITM ON ITM.Id=LND.InterestTypeId
							INNER JOIN sHrm.tEmployeeMaster       AS EMP ON EMP.Id=LND.EmployeeId
							INNER JOIN sSetup.tOrganizationMaster AS OMD ON OMD.Id=EMP.OrgID
							INNER JOIN [sLoan].[tLoanEMI]         AS EMI ON EMI.LoanDetailId=LND.Id
					WHERE LND.IsObsolete=0
							AND ((LND.[OrgID] = @rOrgId))
							AND ((LND.IsCompleted=CONVERT(bit,@rLoanStatus)) OR (@rLoanStatus=-1))
							AND ((LND.LoanTypeId=@rLoanTypeId) OR (@rLoanTypeId=0))
							AND ((LND.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
							AND ((emp.OrgId = @rEmployeeOrgId) OR (@rEmployeeOrgId=-1))
							AND  ISNULL(EMP.IsOtherUser,0) = 0
					GROUP BY LND.EmployeeId,LND.LoanAmount,LND.Id	
				) AS a
			GROUP BY a.EmployeeId

	SELECT
	 @rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,LND.ID AS LoanDetailId
		,LND.EmployeeId
		,ISNULL(EMP.[FirstName],'') +' ' + ISNULL(EMP.MiddleName,'')+ ' ' + ISNULL(EMP.[LastName],'')   as [EmployeeName]
		,LND.LoanTypeId
		,LTM.Title AS [LoanType]
		,LND.InterestTypeId
		,ITM.Title AS [InsterestType]
		,LND.LoanAmount
		,LND.InterestRate
		,EMI.EmiAmount		
		,EMI.InterestAmount
		,EMI.EmiAmount+EMI.InterestAmount AS 'TotalAmount'
		,CONVERT(VARCHAR(15),EMI.EmiDate,103) AS EmiDate
		,CASE EMI.StatusId WHEN 0 THEN 'N' WHEN 1 THEN 'Y' WHEN 2 THEN 'S' END AS Status
		,(SELECT ISNULL(SUM(EmiAmount+InterestAmount),0) FROM [sLoan].[tLoanEMI] WHERE LoanDetailId=LND.Id AND IsObsolete=0 AND StatusId=1) AS PaidAmount
		,(SELECT ISNULL(SUM(EmiAmount+InterestAmount),0) FROM [sLoan].[tLoanEMI] WHERE LoanDetailId=LND.Id AND IsObsolete=0 AND StatusId=0) AS PendingAmount
		,ETD.InstallmentWiseTotal
		,ETD.InstallmentWiseInterestTotal
		,ETD.TotalLoanAmount
		,ETD.TotalPaidAmount
		,ETD.TotalPendingAmount
 	FROM sLoan.tLoanDetail  AS LND
		INNER JOIN sLoan.tLoanTypeMaster      AS LTM ON LTM.Id=LND.LoanTypeId
		INNER JOIN sLoan.tInsterestTypeMaster AS ITM ON ITM.Id=LND.InterestTypeId
		INNER JOIN sHrm.tEmployeeMaster       AS EMP ON EMP.Id=LND.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster AS OMD ON OMD.Id=EMP.OrgID
		INNER JOIN [sLoan].[tLoanEMI]         AS EMI ON EMI.LoanDetailId=LND.Id
		INNER JOIN @EmployeeMaster            AS ETD ON ETD.EmployeeID=LND.EmployeeId
	WHERE LND.IsObsolete=0
		AND ((LND.[OrgID] = @rOrgId))
		AND ((LND.IsCompleted=CONVERT(bit,@rLoanStatus)) OR (@rLoanStatus=-1))
		AND ((LND.LoanTypeId=@rLoanTypeId) OR (@rLoanTypeId=0))
		AND ((LND.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
		AND ((emp.OrgId = @rEmployeeOrgId) OR (@rEmployeeOrgId=-1))
		AND  ISNULL(EMP.IsOtherUser,0) = 0
	ORDER BY EMP.[Code],LND.ID,LND.LoanTypeId,EMI.EmiDate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sLoan].[pRptEmployeeLoanDetails]
** Desc:  30108-> Employee Loan Details Report
** Auth:  Savan Vaghela
** Date:  03-March-2017
** Page:  /Pages/Hrm/IncomeTax/ReportCriteria/LoanReportCriteria.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    03-March-2017      Savan Vaghela       
************************************************************/
--EXEC [sLoan].[pRptLoanSummary] 1001,0,0,null,0,null,null,-1
CREATE OR ALTER PROCEDURE [sLoan].[pRptLoanSummary]
	@rOrgGroupId SMALLINT,
	@rOrgId SMALLINT,
	@rLoanTypeId INT,
	@rInterestTypeId SMALLINT=NULL,
	@rEmployeeID BIGINT,
	@rBuilder1 VARCHAR(MAX)=null,
	@rBuilder2 VARCHAR(MAX)=null,
	@rLoanStatus SMALLINT,
	@rEmployeeOrgId smallint

WITH EXECUTE AS CALLER
AS
BEGIN 
	SELECT
		@rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,LND.Id
		,LND.EmployeeId
		,ISNULL(EMP.[FirstName],'') +' ' + ISNULL(EMP.[MiddleName],'') +' '+ ISNULL(EMP.[LastName],'')  AS [Employee]
		,LND.LoanTypeId
		,LTM.Title AS [LoanType]
		,LND.InterestTypeId
		,ITM.Title AS [InsterestType]
		,LND.LoanAmount
		,LND.InterestRate
		,LND.NoofInstallament
		,REPLACE(CONVERT(VARCHAR(20), LND.ApprovedDate,106),' ','-')																		   AS ApprovedDate
		,REPLACE(CONVERT(VARCHAR(20), LND.RepaymentStartDate,106),' ','-')																       AS RepaymentStartDate
		,(SELECT ISNULL(SUM(InterestAmount),0)           FROM sLoan.tLoanEMI WHERE LoanDetailId=LND.id AND StatusId IN (0,1) AND IsObsolete=0) AS InterestAmount
		,(SELECT ISNULL(SUM(EmiAmount+InterestAmount),0) FROM sLoan.tLoanEMI WHERE LoanDetailId=LND.id AND StatusId IN (1) AND IsObsolete=0)   AS PaidAmount
		,(SELECT ISNULL(SUM(EmiAmount+InterestAmount),0) FROM sLoan.tLoanEMI WHERE LoanDetailId=LND.id AND StatusId IN (0) AND IsObsolete=0)   AS PendingAmount
		,(SELECT COUNT(1) FROM sLoan.tLoanEMI WHERE LoanDetailId=LND.id AND StatusId=1 AND IsObsolete=0) AS PaidEmi
		,(SELECT COUNT(1) FROM sLoan.tLoanEMI WHERE LoanDetailId=LND.id AND StatusId=2 AND IsObsolete=0) AS SkipEMI
 	FROM sLoan.tLoanDetail                    AS LND
		INNER JOIN sLoan.tLoanTypeMaster      AS LTM ON LTM.Id=LND.LoanTypeId
		INNER JOIN sLoan.tInsterestTypeMaster AS ITM ON ITM.Id=LND.InterestTypeId
		INNER JOIN sHrm.tEmployeeMaster       AS EMP ON EMP.Id=LND.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster AS OMD ON OMD.Id=EMP.OrgID
	WHERE LND.IsObsolete=0
		AND ((LND.IsCompleted=CONVERT(bit,@rLoanStatus)) OR (@rLoanStatus=-1))
		AND ((LND.[OrgId] = @rOrgId)                     OR (@rOrgId=0))
		AND ((emp.OrgId = @rEmployeeOrgId) OR (@rEmployeeOrgId=-1))
		AND ((LND.LoanTypeId=@rLoanTypeId)               OR (@rLoanTypeId=0))
		AND ((LND.EmployeeId=@rEmployeeId)               OR (@rEmployeeId=0))
	    AND (LND.InterestTypeId = ISNULL(@rInterestTypeId,LND.InterestTypeId))
		AND  ISNULL(EMP.IsOtherUser,0) = 0
	ORDER BY EMP.[Code],LTM.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/******************************
** Name:  [sLoan].[ptLoanDetailGet]   
** Desc:  Employee Loan Detail 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/IncomeTaxChallan.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
** 1    09-May - 2017        Savan Vaghela       Add new column InterestAmount
************************************************************/
--EXEC [sLoan].[ptLoanDetailGet] 0,1001,1001,'','',-1
CREATE OR ALTER PROCEDURE [sLoan].[ptLoanDetailGet]
	@rId int,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rTitle VARCHAR(50)='',
	@rCode  VARCHAR(50)='',
	@rFromDate datetime = null,
	@rToDate datetime = null,
	@PageIndex INT = 1,
    @PageSize INT = 10,
	@rEmployeeId BIGINT = null,
	@rLoanTypeId INT=null,
	@rEmployeeOrgId smallint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END

	SELECT a.*
	,CASE WHEN a.NoofInstallament=a.PaidEmi THEN 'Completed' ELSE 'On Going' END AS 'LoanStatus'
	,a.NoofInstallament-a.PaidEmi AS PendingEMI  FROM (
	SELECT
	
		LND.Id
		,ROW_NUMBER() OVER(ORDER BY  LND.CreatedDateTime DESC) AS RowNumber
		,LND.LoanTypeId
		,LTM.Title AS [LoanType]
		,LND.InterestTypeId
		,ITM.Title AS [InsterestType]
		,LND.EmployeeId
		,EMP.[Code] +' - '+ ISNULL(EMP.[FirstName],'') +' '+ ISNULL(EMP.[LastName],'')  as [EmployeeName]
		,ISNULL(EMP.[FirstName],'') +' '+ ISNULL(EMP.[LastName],'')  as [Employee]
		,EMP.[Code]
		,LND.LoanAmount
		,LND.InterestRate
		,CONVERT(VARCHAR(20), LND.ApprovedDate,103) AS ApprovedDate
		,CONVERT(VARCHAR(20), LND.RepaymentStartDate,103) AS RepaymentStartDate
		,LND.NoofInstallament
		,EMP.[OrgID]
		,OMD.Title AS 'OrgName'
		,LND.CreatedDateTime
		,LND.IsObsolete
		,(SELECT COUNT(1) FROM sLoan.tLoanEMI WHERE LoanDetailId=LND.id AND StatusId=1 AND IsObsolete=0) AS PaidEmi
		,(SELECT COUNT(1) FROM sLoan.tLoanEMI WHERE LoanDetailId=LND.id AND StatusId=2 AND IsObsolete=0) AS SkipEMI
		,(SELECT SUM(InterestAmount) FROM sLoan.tLoanEMI WHERE LoanDetailId=LND.id AND StatusId IN (0,1) AND IsObsolete=0) AS InterestAmount
		
 	FROM sLoan.tLoanDetail  AS LND
		LEFT  JOIN sLoan.tLoanTypeMaster      AS LTM ON LTM.Id=LND.LoanTypeId
		LEFT  JOIN sLoan.tInsterestTypeMaster AS ITM ON ITM.Id=LND.InterestTypeId
		INNER JOIN sHrm.tEmployeeMaster       AS EMP ON EMP.Id=LND.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster AS OMD ON OMD.Id=EMP.OrgID
	WHERE 
	    (LND.[OrgId] = @rOrgId) 
		AND ((emp.OrgId = @rEmployeeOrgId) OR (@rEmployeeOrgId=-1))
		AND ((EMP.[FirstName] +' '+ EMP.[LastName] LIKE @rTitle) OR (@rTitle=''))
		AND ((EMP.[Code] LIKE @rCode)                           OR (@rCode=''))
		AND (LND.LoanTypeId= ISNULL(@rLoanTypeId,LND.LoanTypeId) )
		AND CONVERT(DATE,LND.ApprovedDate) BETWEEN CONVERT(DATE,ISNULL(@rFromDate, CONVERT(DATE,LND.ApprovedDate))) 
		AND CONVERT(DATE,ISNULL(@rToDate, CONVERT(DATE,LND.ApprovedDate)))
		AND LND.EmployeeId=ISNULL(@rEmployeeId,LND.EmployeeId)
		AND  ISNULL(EMP.IsOtherUser,0) = 0
		AND LTM.IsObsolete = 0 -- Added for mantis : 41439
	) as a
	WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
	ORDER by  a.CreatedDateTime DESC ,a.Code 





	SELECT COUNT(1) as Records  FROM sLoan.tLoanDetail  AS LND
		LEFT  JOIN sLoan.tLoanTypeMaster AS LTM ON LTM.Id=LND.LoanTypeId
		LEFT  JOIN sLoan.tInsterestTypeMaster AS ITM ON ITM.Id=LND.InterestTypeId
		INNER JOIN sHrm.tEmployeeMaster  AS EMP ON EMP.Id=LND.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster      AS OMD ON OMD.Id=EMP.OrgID
	WHERE 
		  (LND.[OrgId] = @rOrgId) 
		AND ((emp.OrgId = @rEmployeeOrgId) OR (@rEmployeeOrgId=-1))
		AND ((EMP.[FirstName] +' '+ EMP.[LastName] LIKE @rTitle) OR (@rTitle=''))
		AND ((EMP.[Code] LIKE @rCode ) OR (@rCode=''))
		AND (LND.LoanTypeId= ISNULL(@rLoanTypeId,LND.LoanTypeId) )
		AND CONVERT(DATE,LND.ApprovedDate)	BETWEEN CONVERT(DATE,ISNULL(@rFromDate, CONVERT(DATE,LND.ApprovedDate))) 
		AND CONVERT(DATE,ISNULL(@rToDate, CONVERT(DATE,LND.ApprovedDate)))
		AND LND.EmployeeId=ISNULL(@rEmployeeId,LND.EmployeeId)
		AND  ISNULL(EMP.IsOtherUser,0) = 0
		AND LTM.IsObsolete = 0 -- Added for mantis : 41439

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sMis].[pEmployeeGroupAndTypewiseSummaryGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rClassId int,
	--@rDivisionId int,
	@rDepartmentId int,
	@rOrgMainGroupId int,
	@rOrgSubGroupId int,
	@rOrgId smallint,
	@rOrgGroupBatchId int,
	@rStrOrgMainGroupId nvarchar(max),
	@rStrOrgSubGroupId nvarchar(max),
	@rStrOrgId nvarchar(max),
	@rStrDepartmentId nvarchar(max),
	@rStrClassId nvarchar(max),
	@rOrgGroupId int,
	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rReportId int =0,
	@rIsDisplayOrgGroup bit=0,
	@rIsDisplayGender bit=0,
	@rBatchGroupId int =0,
	@rStatusId int=0,
	@rStudentStatusId int=0,
	@rEmployeeStatusId int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsTestDivision AS IsTestDivision ,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			@rIsDisplayGender AS IsDisplayGender,			
			
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle ,
			EGM.Id as EmployeeJobdetailId,									
			EGM.Title as Staff,
			ETM.Id as EmployeTypeId,
			ETM.Title as EmployeeType,
			DM.Id as DepartmentId,
			DM.Title as DepartmentName
			--DV.OrderIndex AS DivisionOrder
			FROM 			
			--sStudent.tAcademic A
			sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail	 EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeGroupMaster EGM on EJD.EmployeeGroupId = EGM.Id			 
			INNER JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id = EJD.EmployeeTypeId		
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			
			--INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId = OG.Id
			--INNER JOIN sSetup.tBatchMaster BM ON  BM.OrgGroupBAtchId=OBM.Id
			--AND	BM.IsActive = 1 
			----AND   (BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END)
			----INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId 	AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
	WHERE 
		
		--((A.ClassId=@rClassId) OR (@rClassId=0))
		--AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		
			--AND
				((DM.Id = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			--AND ((BM.Id=@rBatchId) OR (@rBatchId=0))			 
			--AND  (BM.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((OM.OrgGroupId = @rOrgGroupId))
			AND ((EM.StatusId = @rEmployeeStatusId) OR (@rEmployeeStatusId = 0))
			 --AND ((SM.StatusId=@rStudentStatusId) OR (@rStudentStatusId=0))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND ISNULL(EM.IsOtherUser,0) = 0 
			--AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sMis].[pRptAppStudentUserSummaryGet]
(
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rOrgGroupId int = 0 ,
	@rOrgGroupBatchId int = 0,
	@rOrgMainGroupId int = 0,
	@rOrgSubGroupId int = 0,
	@rOrgId int = 0
 )
AS
SET NOCOUNT ON

BEGIN
		 SELECT 
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				OM2.ID AS OrgId,
				OM2.DisplayTitle AS OrgName,
				OM2.Code, 
				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND OM.Id = OM2.Id  AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) AS 'StudentCreatedUser',
 
				ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND OM1.Id = OM2.Id AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND SC.StatusId = 1),0) AS 'StudentRegister',

				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND OM.Id = OM2.Id AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003 AND A.UserId IS NULL),0) AS 'StudentNotRegister'
				 
				FROM
				 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM2 ON OM2.Id = U.OrgId
				INNER JOIN sSetup.tOrgSubGroupMaster OSGM2 ON OSGM2.Id = OM2.OrgSubGroupId
				INNER JOIN sSetup.tOrgMainGroupMaster OMGM2 ON OMGM2.Id = OSGM2.OrgMainGroupId
				LEFT JOIN (
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				INNER JOIN sSetup.tOrgSubGroupMaster OSGM1 ON OSGM1.Id = OM1.OrgSubGroupId
				INNER JOIN sSetup.tOrgMainGroupMaster OMGM1 ON OMGM1.Id = OSGM1.OrgMainGroupId
				AND(OM1.Id !=1)
				AND ((OM1.Id = @rOrgId) OR (@rOrgId = 0))
				AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
				AND ((OMGM1.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
				AND ((OSGM1.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				 
				WHERE U.IsObsolete = 0
				AND((OM2.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM2.Id !=1)
				AND ((OM2.Id = @rOrgId) OR (@rOrgId = 0))
				AND ((OMGM2.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
				AND ((OSGM2.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
				GROUP BY OM2.Id,OM2.DisplayTitle,OM2.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sMis].[pRptAttendanceSummaryOrgnizationwiseGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rOrgSubGroupId int=0,
		@rOrgId smallint=0,
		@rFromDate Date='',
		@rToDate Date='',
		@rStrOrgSubGroupId nvarchar(max)='',
		@rStrOrgId nvarchar(max)='',
		@rOrgGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0,
		@rIsTestOrg bit=0,
		@rIsTestSubGroup bit =0,
		@rStrClassId nvarchar(max)='',
		@rStrDivisionId nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
CREATE TABLE #PresentAbsentCount
(
OrgSubGroupId int,
OrgSubGroupTitle nvarchar(50),
OrgId smallint,
OrgDisplayTitle nvarchar(100),
AcademicId bigint,
PresentCount int,
AbsentCount int,
OrgOrderIndex int ,
ClassId int,
ClassTitle nvarchar(100),
DivisionId int ,
DivisionTitle nvarchar(100),
DepartmentId int ,
DepartmentTitle nvarchar(100)

)

INSERT INTO #PresentAbsentCount
SELECT		
			--OMGM.Id AS OrgMainGroupId,
			--OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			SR.AcademicId ,
			COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)As PresentCount,
			COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)As AbsentCount,
			OM.OrderIndex As OrgOrderIndex ,
			CM.Id As ClassId ,
			CM.Title As ClassTitle ,
			DIM.Id As DivisionId ,
			DIM.Title As DivisionTitle,
			DM.Id As DepartmentId,
			DM.Title As DepartmentTitle

			from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND (BM.IsActive = @rStatusId OR @rStatusId IS NULL)
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id=A.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			INNER JOIN sSetup.tDivisionMaster DIM ON DIM.ClassId = CM.Id And DIM.Id = A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			--INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			WHERE
			AttendanceTypeId = 1
			AND (SR.AttendanceDate >= @rFromDate OR @rFromDate IS NULL)
			AND SR.AttendanceDate <= @rToDate
			AND   ((BM.IsActive =@rStatusId) OR @rStatusId IS NULL)
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			--AND ((OM.OrgGroupId = @rOrgGroupId))
			AND ((SM.StatusID =@rStudentStatusId) OR (@rStudentStatusId=0))
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (A.ClassId IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='') 
			AND (A.DivisionId IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDivisionId,','))OR @rStrDivisionId='')
			GROUP BY AcademicId,OSGM.Id,OSGM.Title,OM.Id,OM.DisplayTitle,OM.OrderIndex,CM.Id,CM.Title,DIM.Id,DIM.Title ,  DM.Id,DM.Title

--SELECT * FROM #PresentAbsentCount
CREATE TABLE #PresentAbsentPercentage
(
OrgSubGroupId int,
OrgSubGroupTitle nvarchar(50),
OrgId smallint,
OrgDisplayTitle nvarchar(100),
AcademicId bigint,
Percentage Decimal,
OrgOrderIndex int,
ClassId int,
ClassTitle nvarchar(100),
DivisionId int ,
DivisionTitle nvarchar(100) ,
DepartmentId int ,
DepartmentTitle nvarchar(100)

)

	INSERT INTO #PresentAbsentPercentage
	SELECT OrgSubGroupId,OrgSubGroupTitle,OrgId,OrgDisplayTitle,AcademicId,
	(PresentCount*100)/(PresentCount+AbsentCount),OrgOrderIndex,ClassId,ClassTitle,DivisionId,DivisionTitle,DepartmentId,DepartmentTitle
		FROM #PresentAbsentCount

	--Select * FROM #PresentAbsentPercentage
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		OrgSubGroupId,
		OrgSubGroupTitle,
		OrgId,
		OrgDisplayTitle,
		COUNT(CASE WHEN Percentage > 80 THEN 1 END) AS Greaterthan80,
		COUNT(CASE WHEN Percentage > 70 AND Percentage <=80  THEN 1 END) AS Between7080,
		COUNT(CASE WHEN Percentage > 60 AND Percentage <=70  THEN 1 END) AS Between6070,
		COUNT(CASE WHEN Percentage > 50 AND Percentage <=60  THEN 1 END) AS Between5160,
		COUNT(CASE WHEN Percentage <= 50 THEN 1 END) AS Lessthan50,
		COUNT(CASE WHEN Percentage =100  THEN 1 END) AS Equal100,
		COUNT(CASE WHEN Percentage >= 91 AND Percentage <=99  THEN 1 END) AS Between9199,
		COUNT(CASE WHEN Percentage >= 81 AND Percentage <=90  THEN 1 END) AS Between8190,
		COUNT(CASE WHEN Percentage >= 21 AND Percentage <=50  THEN 1 END) AS Between2150,
		COUNT(CASE WHEN Percentage > 0 AND Percentage <=20  THEN 1 END) AS Between120,
		COUNT(CASE WHEN Percentage <=0  THEN 1 END) AS Equal0,
		OrgOrderIndex,		
		@rIsTestOrg AS IsTestOrg,
		@rIsTestSubGroup AS IsTestSubGroup,
		ClassId,
		ClassTitle,
		DivisionId,
		DivisionTitle ,
		DepartmentId ,
		DepartmentTitle
		FROM #PresentAbsentPercentage 
		GROUP By OrgSubGroupId,OrgSubGroupTitle,OrgId,OrgDisplayTitle,OrgOrderIndex,ClassId,ClassTitle,DivisionId,DivisionTitle ,DepartmentId ,DepartmentTitle
			
		DROP TABLE #PresentAbsentPercentage
		DROP TABLE #PresentAbsentCount



			 -- SELECT 
			 --'' AS Builder1,
			 --'' AS Builder2,
			 --0 AS OrgSubGroupId,
			 --'' AS OrgSubGroupTitle,
			 --0 AS OrgId,
			 --'' AS OrgDisplayTitle,
			 --0 AS Greaterthan80,
			 --0 AS Between7080,
			 --0 AS Between6070,
			 --0 AS Between5160,
			 --0 AS Lessthan50,
			 --0 AS Equal100,
			--0  AS Between9199,
			--0 AS Between8190,
			 --0 AS Between2150,
			 --0 AS Between120,
			 --0 AS Equal0,
			 --0 AS OrgOrderIndex,
			 --0 AS IsTestOrg,
			 --0 AS IsTestSubGroup ,
			 --0 As ClassId ,
			 --'' As ClassTitle ,
			 --0 As DivisionId ,
			 --'' As DivisionTitle ,
			 --0 As DepartmentId ,
			 --'' As DepartmentTitle
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 
CREATE OR ALTER PROCEDURE [sMis].[pRptAverageAttendanceClassWise]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0,
		@rIsDisplayGender bit = 0,
		@rIsTestDivision bit = 0,		-- Mantis Id : 0042610
		@rDivisionId int = 0,
		@rStrDivisionId nvarchar(max) = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			@rIsDisplayGender AS IsDisplayGender,
			
			(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
					INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
					--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1	
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId
					LEFT JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=Bm.batchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
					INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SM.Id 
					WHERE CM.Id = A.ClassId
					AND AttendanceTypeId = 1
					AND SR.IsPresent=1
					AND SR.AttendanceDate >= @rFromDate
					AND SR.AttendanceDate <= @rToDate
					AND BM.IsActive =@rStatusId
					AND ((SM.StatusID=@rStudentStatusId) OR (@rStudentStatusId=0))
					AND A.DivisionId = DivM.Id		-- Mantis Id : 0042610
			) PresentCount,
			(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
					INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId
					LEFT JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=Bm.batchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
					INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SM.Id 
					WHERE CM.Id = A.ClassId
					AND AttendanceTypeId = 1
					AND SR.IsPresent=0
					AND SR.AttendanceDate >= @rFromDate
					AND SR.AttendanceDate <= @rToDate
					AND BM.IsActive =@rStatusId
					AND ((SM.StatusID=@rStudentStatusId) OR (@rStudentStatusId=0))
					AND A.DivisionId = DivM.Id		-- Mantis Id : 0042610
			) AbsentCount,
			@rIsTestDivision AS IsTestDivision,
			DivM.Id AS DivisionId,
			DivM.OrderIndex AS DivisionOrderIndex,
			DivM.Title AS DivisionName



		FROM 
			sSetup.tClassMaster CM			
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.ClassId = CM.Id				-- Mantis Id : 0042610
			
	WHERE 
			
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='') 
			AND (DivM.Id = @rDivisionId OR @rDivisionId = 0)		-- Mantis Id : 0042610
			AND (@rStrDivisionId = '' OR DivM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDivisionId,',')))		-- Mantis Id : 0042610

			ORDER BY CM.OrderIndex ASC


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sMis].[pRptAverageAttendanceGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0,
		@rIsDisplayGender bit = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			DIM.Title AS DivisionName,
			DIM.Id AS DivisionId,
			--SO.GenderId AS GenderId,
			@rIsDisplayGender AS IsDisplayGender,
	(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id AND DIM.Id = A.DivisionId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId	
			LEFT JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=Bm.batchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SM.Id AND (SO.GenderId = 1)
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND SR.IsPresent=1
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate	
			 --AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 AND   BM.IsActive =@rStatusId
			 AND ((SM.StatusID =@rStudentStatusId) OR (@rStudentStatusId=0))
			 AND SO.GenderId = 1
	) MalePresentCount,

	(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id AND DIM.Id = A.DivisionId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId		
			INNER JOIN 	sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SM.Id AND (SO.GenderId = 1)
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			AND SR.IsPresent=0
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate
			 --AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 AND   BM.IsActive=@rStatusId
			 AND ((SM.StatusID=@rStudentStatusId) OR (@rStudentStatusId=0))
			 AND SO.GenderId = 1
	) MaleAbsentCount,

	(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id AND DIM.Id = A.DivisionId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId	
			LEFT JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=Bm.batchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SM.Id AND (SO.GenderId = 2)
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND SR.IsPresent=1
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate	
			 --AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 AND   BM.IsActive =@rStatusId
			 AND ((SM.StatusID =@rStudentStatusId) OR (@rStudentStatusId=0))
			 AND SO.GenderId = 2
	) FemalePresentCount,

	(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id AND DIM.Id = A.DivisionId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId		
			INNER JOIN 	sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SM.Id AND (SO.GenderId = 2)
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			AND SR.IsPresent=0
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate
			 --AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 AND   BM.IsActive=@rStatusId
			 AND ((SM.StatusID=@rStudentStatusId) OR (@rStudentStatusId=0))
			 AND SO.GenderId = 2
	) FemaleAbsentCount,
			
	(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id AND DIM.Id = A.DivisionId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId	
			LEFT JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=Bm.batchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND SR.IsPresent=1
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate	
			 --AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 AND   BM.IsActive =@rStatusId
			 AND ((SM.StatusID =@rStudentStatusId) OR (@rStudentStatusId=0))
	) PresentCount,

	(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id AND DIM.Id = A.DivisionId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId		
			INNER JOIN 	sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			AND SR.IsPresent=0
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate
			 --AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 AND   BM.IsActive=@rStatusId
			 AND ((SM.StatusID=@rStudentStatusId) OR (@rStudentStatusId=0))
	) AbsentCount

		FROM 
			sSetup.tClassMaster CM			
			--INNER JOIN sSetup.tBatchClass BC ON BC.ClassId= CM.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tDivisionMaster DIM ON DIM.ClassId = CM.Id
			--INNER JOIN sStudent.tAcademic A ON A.ClassId = CM.Id
			--INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId
	WHERE 
			--BC.BatchId = @rBatchId
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='') 

			ORDER BY CM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sMis].[pRptCastCategorywiseStudentGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rClassId int,
	@rDivisionId int,
	@rDepartmentId int,
	@rOrgMainGroupId int,
	@rOrgSubGroupId int,
	@rOrgId smallint,
	@rOrgGroupBatchId int,
	@rStrOrgMainGroupId nvarchar(max),
	@rStrOrgSubGroupId nvarchar(max),
	@rStrOrgId nvarchar(max),
	@rStrDepartmentId nvarchar(max),
	@rStrClassId nvarchar(max),
	@rOrgGroupId int,
	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rReportId int =0,
	@rIsDisplayOrgGroup bit=0,
	@rIsDisplayGender bit=0,
	@rBatchGroupId int =0,
	@rStatusId int=0,
	@rStudentStatusId int=0,
	@rClassStatusId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsTestDivision AS IsTestDivision ,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			@rIsDisplayGender AS IsDisplayGender,
			DV.Id AS DivisionId,
			CM.Id AS ClassId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Department,
			CM.DisplayTitle+' '+DV.DisplayTitle AS ClassDivision,
			
			ISNULL(GM.Title,'') As Gender,
			A.Id AS AcademicId,
			--OBM.Title,
			
			DV.DisplayTitle AS Division,
		
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			CASE WHEN  @rReportId=20621	 -- Caste Category wise Summary
			THEN ISNULL(CCM.Title,'') 
		    WHEN  @rReportId=20623 -- Religionwise Summary
			THEN ISNULL(RM.Title,'')
			END AS Head,
			DV.OrderIndex AS DivisionOrder
			FROM 
			
			
			sStudent.tAcademic A	
			INNER JOIN	sSetup.tClassMaster CM	ON CM.Id=A.ClassId	
			INNER JOIN sSetup.tDivisionMaster DV ON DV.Id=A.DivisionId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId	
				
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId		
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId = OG.Id
			INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId 
			--AND	BM.IsActive = 1 
			AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND BM.OrgGroupBatchId=OBM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId 	AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			
	WHERE 
		
		((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			--AND ((BM.Id=@rBatchId) OR (@rBatchId=0))			 
			AND  (BM.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((OM.OrgGroupId = @rOrgGroupId))
			 AND ((SM.StatusId=@rStudentStatusId) OR (@rStudentStatusId=0))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			AND ((A.ClassStatusId=@rClassStatusId) OR (@rClassStatusId = 0))		
			 	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sMis].[pRptClassCapacityGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rOrgGroupBatchId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0,
		@rUptoDate datetime = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			(SELECT COUNT(1) FROM sSetup.tDivisionMaster DM WHERE DM.ClassId=CM.Id) AS DivisionCount,
			ISNULL(CM.Capacity,0) AS Capacity,
			
			(SELECT ISNULL(count(1),0)  FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id = BM.BatchGroupId 
			INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id 
			WHERE A.ClassId = CM.Id 
			AND SA.AdmissionDate <= @rUptoDate
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((BGM.Id = @rBatchGroupId) OR (@rBatchGroupId = 0)) 
			AND ((SM.StatusId = @rStudentStatusId) OR (@rStudentStatusId=0))) 
			AS CurrentStrength,
			
			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id AND SA.leftDate <= @rUptoDate
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
			AND BM.OrgId=CM.OrgId AND BM.OrgGroupBatchId=@rOrgGroupBatchId
			WHERE  A.ClassId = CM.Id)
			AS AdmissionLeft,
			
			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id AND SA.AdmissionDate = @rUptoDate
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
			AND BM.OrgId=CM.OrgId AND BM.OrgGroupBatchId=@rOrgGroupBatchId AND SM.StatusId = 1
			WHERE  A.ClassId = CM.Id) 
			AS AdmissionGiven,

			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			AND BM.OrderIndex = (SELECT TOP 1 BM.OrderIndex -1 FROM sSetup.tBatchMaster BM	INNER JOIN  sSetup.tOrgGroupBatchMaster ORGM ON BM.OrgGroupBatchId=ORGM.Id
			WHERE BM.OrgId=CM.OrgId 
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId ORDER BY BM.OrderIndex DESC
			) WHERE A.ClassId = CM.Id AND SM.StatusId = 1) 
			AS PreviousStrength
	FROM 
			sSetup.tClassMaster CM
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
	WHERE 
			((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			ORDER BY CM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sMis].[pRptDivisionCapacityGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rDepartmentId int,
		@rClassId int,
		@rDivisionId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rOrgGroupBatchId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestDepartment bit=0,
		@rIsTestClass bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0
		
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

  SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			DM.Id AS DivisionId,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			DM.DisplayTitle AS DivisionName,
			CM.DisplayTitle+'-'+DM.DisplayTitle AS ClassDivisionName,
			DM.OrderIndex,
			ISNULL(DM.Capacity,0) AS Capacity,
			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.ID=BM.BatchgroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			WHERE A.DivisionId = DM.Id AND SM.StatusId = 1 			
			AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SM.StatusId = @rStudentStatusId) OR (@rStudentStatusId=0))
			) AS CurrentStrength,
			CM.DepartmentId,
			DeptM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle
  FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			--INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId
			INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
  WHERE 
			--BC.BatchId = @rBatchId
			((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			
			ORDER BY CM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sMis].[pRptInquiryAdmissionGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		--@rStrOrgMainGroupDisId nvarchar(max),
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0 ,
		@rStatusId int=0
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
--SET @rBatchId = ISNULL(@rBatchId,0)
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			--ISNULL(CM.Capacity,0) AS Capacity,
			--(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id WHERE A.ClassId = CM.Id AND SM.StatusId = 1 AND A.BatchId = @rBatchId) AS CurrentStrength,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			(select COUNT(AI.Id) FROM sAdmission.tAdmissionInquiry AI INNER JOIN sSetup.tBatchMaster BM
			 ON AI.ForBatchId = BM.Id
			 INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId  AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			 WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND   AI.InquiryDate >= @rFromDate AND AI.InquiryDate <= @rToDate 
			 AND AI.ForClassId = CM.Id AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			
			 )  NoOfInquiry,
		    (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND SA.AdmissionStandardId = A.ClassId
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id= BM.BatchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			
			WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND SA.AdmissionDate >= @rFromDate AND   
			SA.AdmissionDate <= @rToDate AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND A.ClassId =CM.Id  ) AS NoOfAdmission
 
	FROM 
			sSetup.tClassMaster CM						
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId = OG.Id
			--INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
	WHERE 
			--BC.BatchId = @rBatchId
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			--AND ((BM.Id=@rBatchId) OR (@rBatchId=0))			 
			AND  (OBM.Id = @rOrgGroupBatchId)
			AND ((OM.OrgGroupId = @rOrgGroupId))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			 
			--AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupDisId,','))OR @rStrOrgMainGroupDisId='')
			 
			ORDER BY CM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sMis].[pRptResultAnalysisExamWiseGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		
		@rOrgGroupBatchId int,
		@rExamId int,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--Select 
--		0 AS OrgMainGroupId,
--	    '' AS OrgMainGroupName,
--		0 AS OrgSubGroupId,
--		'' AS SubGroupName,
--		'' AS OrgName,
--		0 AS DepartmentId,
--		0 AS OrgId,
--		'' AS Code,
--		'' AS Name,
--		0 AS RollNo,
--		0 AS AcademicId,			
--		'' AS Class,
--		0 As ClassId,
--		'' AS Division,
--		0 AS DivisionId,
--		'' AS Exam,
--		0 AS SubjectId,	
--		'' AS SubjectCode,
--		'' AS SubjectName,
--		--RD.SubjectGrade,
--		--R.ResultGrade,
--		--BM.OrgGroupBatchId,
--		--RD.Obtain,
--		'' AS SubjectGrade,
--		--R.Percentage,
--		'' AS ResultGrade,
--		@rExamId AS ExamId


			
 
 
 
		Select 
		OMGM.Id AS OrgMainGroupId,
		OMGM.Code AS OrgMainGroupName,
		OSGM.Id AS OrgSubGroupId,
		OSGM.Code AS SubGroupName,
		OM.Title AS OrgName,
		DM.Id AS DepartmentId,
		--CM.Id,
		stum.OrgId,
		Stum.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		A.Id AS AcademicId,			
		CM.DisplayTitle AS Class,
		CM.Id As ClassId,
		DM.DisplayTitle AS Division,
		DM.Id AS DivisionId,
		ETM.Code AS Exam,
		CS.Id AS SubjectId,	
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		--RD.SubjectGrade,
		--R.ResultGrade,
		--BM.OrgGroupBatchId,
		--RD.Obtain,
		[sAssessment].[fGetConfigGrade](stum.OrgId,RD.Obtain) AS SubjectGrade,
		--R.Percentage,
		[sAssessment].[fGetResuultGradeCount](stum.OrgId,RD.Obtain,@rExamId,@rStrOrgMainGroupId,@rStrOrgSubGroupId,@rStrOrgId,@rStrDepartmentId,@rStrClassId,@rOrgGroupBatchId,CM.Id,DM.Id)AS ResultGrade,
		@rExamId AS ExamId,
		--R.ResultGrade,
		 --OMGM.Id
		 ISNULL(RD.IsPresent, 0) AS IsPresent      --Mantis 30006

		 from sStudent.tStudentMaster Stum 
		INNER JOIN  sStudent.tAcademic A ON Stum.Id=A.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON Stum.OrgId = OM.Id
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD 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 sAssessment.tExamTypeMaster ETM ON ETM.Id=ESGM.ExamTypeId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
		INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
		INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId	
		INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId

		WHERE		
			ETM.Id=@rExamId
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sMis].[pRptResultAnalysisExamWiseWithAttendanceGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		
		@rOrgGroupBatchId int,
		@rExamId int,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max)

	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--Select 
--		0 AS OrgMainGroupId,
--	    '' AS OrgMainGroupName,
--		0 AS OrgSubGroupId,
--		'' AS SubGroupName,
--		'' AS OrgName,
--		0 AS DepartmentId,
--		0 AS OrgId,
--		'' AS Code,
--		'' AS Name,
--		0 AS RollNo,
--		0 AS AcademicId,			
--		'' AS Class,
--		0 As ClassId,
--		'' AS Division,
--		0 AS DivisionId,
--		'' AS Exam,
--		0 AS SubjectId,	
--		'' AS SubjectCode,
--		'' AS SubjectName,
--		--RD.SubjectGrade,
--		--R.ResultGrade,
--		--BM.OrgGroupBatchId,
--		--RD.Obtain,
--		'' AS SubjectGrade,
--		--R.Percentage,
--		'' AS ResultGrade,
--		@rExamId AS ExamId,
--		0 AS Attendance


			
 
 
 
		Select Distinct
		OMGM.Id AS OrgMainGroupId,
		OMGM.Code AS OrgMainGroupName,
		OSGM.Id AS OrgSubGroupId,
		OSGM.Code AS SubGroupName,
		OM.Title AS OrgName,
		DM.Id AS DepartmentId,
		--CM.Id,
		stum.OrgId,
		Stum.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		A.Id AS AcademicId,			
		CM.DisplayTitle AS Class,
		CM.Id As ClassId,
		DM.DisplayTitle AS Division,
		DM.Id AS DivisionId,
		ETM.Code AS Exam,
		--CS.Id AS SubjectId,	
		--SM.Code AS SubjectCode,
		--SM.Title AS SubjectName,
		--RD.SubjectGrade,
		--R.ResultGrade,
		--BM.OrgGroupBatchId,
		--RD.Obtain,
		--[sAssessment].[fGetConfigGrade](stum.OrgId,RD.Obtain) AS SubjectGrade,
		--R.Percentage,
		[sAssessment].[fGetConfigGrade](stum.OrgId,R.Percentage)AS ResultGrade,
		@rExamId AS ExamId,
		(CASE WHEN (SR.PresentDays<>0 AND SR.TotalDays<>0) THEN ROUND(((CAST(SR.PresentDays AS FLOAT)/CAST(SR.TotalDays AS FLOAT))*100),2) ELSE 0 END)AS Attendance,
		--((CAST(SR.PresentDays AS FLOAT)/CAST(SR.TotalDays AS FLOAT))*100)AS Attendance
		ISNULL(SR.PresentDays,0)AS PresentDays,
		ISNULL(SR.TotalDays,0)AS TotalDays
		
		
		 from sStudent.tStudentMaster Stum 
		INNER JOIN  sStudent.tAcademic A ON Stum.Id=A.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON Stum.OrgId = OM.Id
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		--INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		INNER JOIN sAssessment.tExamTypeMaster ETM ON ETM.Id=ESGM.ExamTypeId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
		INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
		INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId	
		INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId

		WHERE		
			ETM.Id=@rExamId
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sMis].[pRptResultAnalysisSubjectWiseWithAttendanceGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 	
		@rOrgGroupBatchId int,
		@rExamId int,
		@rOrgId int = 0,
		@rClassId int = 0,
		@rDivisionId int = 0,
		@rClassSubjectId int = 0

	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
 
 
 
		Select Distinct
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		OMGM.Id AS OrgMainGroupId,
		OMGM.Code AS OrgMainGroupName,
		OSGM.Id AS OrgSubGroupId,
		OSGM.Code AS SubGroupName,
		OM.Title AS OrgName,
		DM.Id AS DepartmentId,
		stum.OrgId,
		Stum.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		A.Id AS AcademicId,			
		CM.DisplayTitle AS Class,
		CM.Id As ClassId,
		DM.DisplayTitle AS Division,
		DM.Id AS DivisionId,
		ESGM.Title AS Exam,
		CS.Id AS SubjectId,	
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		BM.OrgGroupBatchId,
		RD.Obtain,
		[sAssessment].[fGetConfigurationGrade](stum.OrgId,RD.Obtain) AS SubjectGrade,
		R.Percentage,
		[sAssessment].[fGetConfigurationGrade](stum.OrgId,R.Percentage)AS ResultGrade,
		@rExamId AS ExamId,
		(CASE WHEN (SR.PresentDays<>0 AND SR.TotalDays<>0) THEN ROUND(((CAST(SR.PresentDays AS FLOAT)/CAST(SR.TotalDays AS FLOAT))*100),2) ELSE 0 END)AS Attendance,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		ISNULL(SR.TotalDays,0)AS TotalDays
		
		
		 from sStudent.tStudentMaster Stum 
		INNER JOIN  sStudent.tAcademic A ON Stum.Id=A.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON Stum.OrgId = OM.Id
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		--INNER JOIN sAssessment.tExamTypeMaster ETM ON ETM.Id=ESGM.ExamTypeId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
		INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
		INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId	
		INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId

		WHERE		
			EM.Id=@rExamId
			AND (OM.Id = @rOrgId OR @rOrgId = 0)
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND CM.Id = @rClassId
			AND (DM.Id = @rDivisionId OR @rDivisionId = 0)
			AND (CS.Id = @rClassSubjectId OR @rClassSubjectId = 0)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sMis].[pRptStudentBirthdayList]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rOrgMainGroupId int,
	@rOrgSubGroupId int,
	@rOrgGroupId int,
	@rOrgId smallint,
	--@rOrgGroupBatchId int, 
	@rDepartmentId int,
	@rClassId int,
	@rDivisionId int,
    @rStudentStatusId int=0,
	@rMonth tinyint =0,

	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rStrOrgMainGroupId nvarchar(max) = '',
	@rStrOrgSubGroupId nvarchar(max) = '',
	@rStrOrgId nvarchar(max) = '',
	@rStrDepartmentId nvarchar(max) = '',
	@rStrClassId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

Declare @lIDConfigValue nvarchar(50)='' 


 SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId

	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsTestDivision AS IsTestDivision,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			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.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,
			SF.FatherOfficeContactNo,
			SF.MotherOfficeContactNo,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			SD.DepartmentId,
			DM.Title AS Department,
			@lIDConfigValue AS ItemValue 
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN	sSetup.tClassMaster CM	ON CM.Id=SD.ClassId	
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId		
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId	
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId = OG.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId			 --Mantis 43838(INNER to LEFT)
			--INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID AND BC.BatchId = SD.BatchId 
			--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   
	WHERE 
		((SD.OrgId=@rOrgId) OR (@rOrgId=0))
		And ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		And (Month(SD.DateOfBirth)=@rMonth OR @rMonth = 0)
		AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
		AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
		AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
		AND ((SD.StatusId  = @rStudentStatusId) OR (@rStudentStatusId = 0))
		AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
		AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
		AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit(@rStrOrgId,','))OR @rStrOrgId='')
		AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrDepartmentId,','))OR @rStrDepartmentId='')
		AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrClassId,','))OR @rStrClassId='')
		AND SD.IsActiveBatch = 1
	 Order by
	 SD.RollNo
	 --SD.AcademicId,SD.StudentId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sMis].[pRptStudentStrengthDivisionWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rDepartmentId int,
	 --@rStudentCode varchar(20)='',
	 @rReportId int=0,
	 @rOrggroupBatchID int=0,
	 --@rAsOnDate Date ='',
    @rStatusId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  DECLARE @lCount Int
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			A.ClassId,
			A.DivisionId,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			DM.OrderIndex AS DivisionOrder,
			Cm.OrderINdex AS ClassOrderIndex  ,
		    ISNUll(AR.SourceId,0) AS HostelStudent,
			ISNUll(RT.SourceId,0) AS TransportStudent,
			A.StudentId,
			SM.StatusId,
			@rStatusId AS [Status]
			FROM 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			--LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			--LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			--LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			--LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			--LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			--LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			--LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=A.AdmissionCategoryId
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=A.StudentId AND AR.SourceTypeId=2003 
			AND  ((AR.OrggroupBatchID=@rOrggroupBatchID) OR (@rOrggroupBatchID=0))
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = A.StudentId
			--INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
			INNER JOIN  sSetup.tOrganizationMaster OM ON OM.Id = A.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
    
	WHERE 
		(A.OrgId=@rOrgId  OR @rOrgId = 0)
		--AND	A.BatchId = @rBatchId 
		--AND AR.OrggroupBatchID = @rOrggroupBatchID
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--AND SM.StatusId = 1
		--AND ((SM.Code=@rStudentCode) OR (@rStudentCode='')) --vishruti
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--start by megha - mentis 0026391
		--AND ((SA.LeftDate > @rAsOnDate) OR (SA.LeftDate Is null AND SM.StatusId = 1))
		--AND ((SA.LeftDate > @rAsOnDate) OR (SA.LeftDate Is null))  --vishruti
	    AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0))
		And BM.OrgGroupBatchId = @rOrggroupBatchID 
		--and BM.IsInContext=1
		--end
	   END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sMis].[pRptStudentStrengthGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rOrgGroupId int,
		@rIsDisplayOrgGroup bit=0,
		@rBatchgroupId int =0,
		@rStatusID int =0,
		@rStudentStatusId int=0
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
		 
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
						
		    (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id = BM.batchGroupId ANd ((BGM.ID=@rBatchgroupId) OR (@rBatchGroupId=0))
			--WHERE BM.IsActive = 1 
			WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND SA.AdmissionDate < @rFromDate
			AND A.ClassId =CM.Id   
			AND ((SM.StatusID = @rStudentStatusId) OR (@rStudentStatusId=0))
			) AS OpeningStrength,
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.batchGroupId AND ((BGm.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			--WHERE BM.IsActive = 1 
			WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND SA.AdmissionDate >= @rFromDate AND SA.AdmissionDate <= @rToDate
			AND A.ClassId =CM.Id 
			 AND ((SM.StatusID = @rStudentStatusId) OR (@rStudentStatusId=0))
			 ) AS NewJoinedStudent,
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupid AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			--WHERE BM.IsActive = 1 
			WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND SA.LeftDate >= @rFromDate AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id
			AND ((SM.StatusID = @rStudentStatusId) OR (@rStudentStatusId=0))
			    ) AS LeftStudent,
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId 
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tBatchGroupMaster BGM on BGM.Id=BM.BatchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			--WHERE BM.IsActive = 1
			WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 --AND SM.StatusId = 1
			 AND ( SA.LeftDate > @rToDate OR SA.LeftDate IS NULL)
			AND A.ClassId =CM.Id  
			 AND ((SM.StatusId=@rStudentStatusId) OR (@rStudentStatusId=0))
			) AS ClosingStrength
 
 
	FROM 
			sSetup.tClassMaster CM			 
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId AND DM.IsObsolete = 0
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId AND DM.IsObsolete = 0
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
	WHERE 
		 
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			 
			ORDER BY CM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sOmr].[pAnalysisScanHistoryGet]
	 
	 @rClassId int,
	 @rSubjectId int,
	 @rExamId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lCount SMALLINT
	
	SELECT	@lCount=NumberOfQuestion	
	FROM sOmr.tExamSetup ES
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ES.ExamDetailId AND ClassSubjectId=@rSubjectId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = ED.ExamId AND EM.ClassId = @rClassId AND EM.Id = @rExamId
	
	
	SELECT	@lCount AS NumberOfQuestion,
			AnsKeyString,
			AttemptScanString,
			ED.Id as ExamDetailId
	FROM	sOmr.tScanHistory AS SH	
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id = SH.ExamDetailId AND ClassSubjectId=@rSubjectId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = ED.ExamId AND EM.ClassId = @rClassId AND EM.Id = @rExamId
	ORDER BY AcademicId
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sOmr].[pAnswerKeyAnalysisAdd]	 
			 @rExamDetailId int
			,@rQuestionNumber smallint
			,@rTrueAnswer smallint
			,@rFalseAnswer smallint
			,@rNonAttemptAnswer smallint
			,@rMultiAttemptAnswer smallint
			,@rOrgId int
			,@rUpdatedUserId bigint
		   
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 


		INSERT INTO [sOmr].[tTempAnsKeyAnalysis]
				   (
					ExamDetailId
				   ,Questionnumber	
				   ,TrueAnswer
				   ,FalseAnswer
				   ,NonAttemptAnswer
				   ,MultiAttemptAnswer
				   ,CreatedUserId
				   ,OrgId
				   )
			 VALUES
				   (
					@rExamDetailId 
				   ,@rQuestionNumber 
				   ,@rTrueAnswer
				   ,@rFalseAnswer 
				   ,@rNonAttemptAnswer 
				   ,@rMultiAttemptAnswer
				   ,@rUpdatedUserId
				   ,@rOrgId				   
				   )
				SELECT @rExamDetailId AS Result
	

--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sOmr].[pAnswerKeyAnalysisDelete]	 
			@rOrgId int
			,@rUpdatedUserId bigint
		   
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 


		DELETE FROM [sOmr].[tTempAnsKeyAnalysis]
		WHERE (CreatedUserId = @rUpdatedUserId  OR @rUpdatedUserId  = 0 )
		AND  ( OrgId = @rOrgId OR @rOrgId = 0)
				  
				SELECT 1 AS Result
	

--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sOmr].[pAnswerKeyAnalysisGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rExamId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT	SM.Title AS SubjectName,
			ESGM.Title AS ExamName,
			DM.Code AS ClassDiv, 
			QuestionNumber,
			TrueAnswer,
			FalseAnswer,
			NonAttemptAnswer,
			MultiAttemptAnswer
			
	FROM	sOmr.tTempAnsKeyAnalysis A
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = A.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = ED.ExamId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CS.ClassId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	WHERE 
			EM.BatchId = @rBatchId 
			AND (EM.ClassId=@rClassId OR @rClassId=0) 
			AND (DM.Id=@rDivisionId OR @rDivisionId=0)
			AND (EM.Id=@rExamId)
			AND (CS.Id = @rSubjectId)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sOmr].[pAnswerKeySetupAdd]
	 
	        @rExamDetailId int
           ,@rQuestionNumber smallint
		   ,@rMarks decimal(5,2)
		   ,@rAnswerKey NVARCHAR(5)
		   ,@rPaperSeriesId TINYINT
		   ,@rIsCancel bit
		   
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF NOT EXISTS 	 (SELECT ExamDetailId FROM sOmr.tAnswerKeySetup WHERE ExamDetailId=@rExamDetailId 
				  AND PaperSeriesId=@rPaperSeriesId AND QuestionNumber = @rQuestionNumber)  
	BEGIN
	INSERT INTO [sOmr].[tAnswerKeySetup]
			   (
			    ExamDetailId
			   ,QuestionNumber			  
			   ,Marks		
			   ,AnswerKey	   
			   ,PaperSeriesId
			   ,IsCancel
			   )
		 VALUES
			   (
			    @rExamDetailId 
			   ,@rQuestionNumber 
			   ,@rMarks
			   ,@rAnswerKey 
			   ,@rPaperSeriesId 
			   ,@rIsCancel
			   )
		    SELECT @rExamDetailId AS Result
	END	 
ELSE
    BEGIN
			 BEGIN
				UPDATE  [sOmr].[tAnswerKeySetup]
				SET
						Marks =@rMarks,IsCancel=@rIsCancel,AnswerKey=@rAnswerKey
				  WHERE ExamDetailId = @rExamDetailId	AND PaperSeriesId=@rPaperSeriesId AND
						QuestionNumber =    @rQuestionNumber
				  SELECT @rExamDetailId AS Result
			
			 END 
	END 

COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sOmr].[pCheckListOMRGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rExamId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT	ESGM.Title AS Name,
			A.RollNo,
			A.FirstName + ' ' + A.MiddleName + ' ' + A.LastName AS StudentName,
			SM.Title, 
			NoOfTrueQuestion,
			NoOfFalseQuestion,
			NoOfNonAttempts,
			NoOfMultiAttempts,
			MarkasperOMR,
			FalseQueString,
			NonAttemptString,
			MultiAttemptQueString,
			AnsKeyString,
			AttemptScanString ,
			CancelQueString
	
	FROM	sOmr.tScanHistory SH
			INNER JOIN sStudent.vStudentAcademic  A ON A.AcademicId = SH.AcademicId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = SH.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = ED.ExamId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id= EM.ExamSubGroupId
	WHERE 
			
		     EM.BatchId = @rBatchId 
		AND (EM.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND (EM.Id=@rExamId)
		AND (CS.Id = @rSubjectId)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sOmr].[pExamSetupAdd]
	 
	        @rExamDetailId int
           ,@rNumberOfQuestion smallint
		   ,@rWrongMarkDeduction decimal(5,2)
		   ,@rNonAttemptMarkDeduction decimal(5,2)
		   ,@rMultiAttemptMarkDeduction Decimal(5,2)
		   ,@rPaperSerise tinyint
		   ,@rIsObsolete bit
		   ,@rIsMultiTrueAns bit
		   
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

IF NOT EXISTS 	 (SELECT @rExamDetailId FROM sOmr.tExamSetup WHERE ExamDetailId=@rExamDetailId) AND @rIsObsolete = 1 
	BEGIN
	INSERT INTO [sOmr].[tExamSetup]
			   (
			    ExamDetailId
			   ,NumberOfQuestion	
			   ,WrongMarkDeduction
			   ,NonAttemptMarkDeduction
			   ,MultiAttemptMarkDeduction
			   ,PaperSeriese
			   ,IsMultiTrueAns
			   )
		 VALUES
			   (
			    @rExamDetailId 
			   ,@rNumberOfQuestion 
			   ,@rWrongMarkDeduction
			   ,@rNonAttemptMarkDeduction 
			   ,@rMultiAttemptMarkDeduction 
			   ,@rPaperSerise 
			   ,@rIsMultiTrueAns
			   )
		    SELECT @rExamDetailId AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
    BEGIN
	IF @rIsObsolete = 1 
			 BEGIN
				UPDATE  [sOmr].[tExamSetup]
				SET
						NumberOfQuestion =@rNumberOfQuestion
					   ,WrongMarkDeduction=@rWrongMarkDeduction 
					   ,NonAttemptMarkDeduction=@rNonAttemptMarkDeduction 
					   ,MultiAttemptMarkDeduction=@rMultiAttemptMarkDeduction 
					   ,PaperSeriese =@rPaperSerise 
					   ,IsMultiTrueAns=@rIsMultiTrueAns
				  WHERE ExamDetailId = @rExamDetailId	   
				  SELECT @rExamDetailId AS Result
			
				--COMMIT TRANSACTION
			 END 
	ELSE
		BEGIN
			DELETE FROM [sOmr].[tExamSetup] WHERE ExamDetailId = @rExamDetailId
			SELECT @rExamDetailId AS Result
		END		  
	END 

--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOmr].[pMarksUpdateSubjectListGet]
	 @rClassId int,
	 @rExamId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
		SELECT 
	    ED.Id AS ExamDetailId,
		SM.Title as SubjectName,
		CASE WHEN ISNULL(ES.IsUpdated,0) <> 0 THEN 'Result Updated' ELSE 'Not Updated' END AS Status
	FROM 
			[sSetup].[tClassMaster] CM INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId	
			INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id	AND ED.ExamId = @rExamId
			INNER JOIN sOmr.tExamSetup ES ON ES.ExamDetailId = ED.Id
	Where (CS.Classid=@rClassId) 	    
			order by CS.OrderIndex ASC
			
		
		
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sOmr].[pMarkUpdate]	 
	       @rExamDetailId int,
	       @rOrgId INT          
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 	
	 DECLARE @lDetailNextNumber BIGINT 	 
	 Declare @lCount int
	 DECLARE @lExamId int
	 DECLARE @lAcademicId bigint
	 DECLARE @lMarks Decimal(5,2)
	
	CREATE TABLE #tempScanHistory
	(	
		Id INT IDENTITY (1, 1),
		ExamId int,
		AcademicId bigint,
		MarkAsPerOMR decimal(5,2)
	)  	
	INSERT INTO #tempScanHistory (ExamId,AcademicId,MarkAsPerOMR) 
	SELECT ED.ExamId,SH.AcademicId,SH.MarkasperOMR FROM sOmr.tScanHistory SH
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id = SH.ExamDetailId AND ExamDetailId = @rExamDetailId	

	SELECT @lCount =  COUNT(Id) FROM #tempScanHistory
	WHILE (@lCount > 0)
	BEGIN
		
		SELECT @lExamId =ExamId,@lAcademicId= AcademicId,@lMarks=MarkAsPerOMR FROM #tempScanHistory WHERE Id = @lCount	
			
		IF NOT EXISTS (SELECT Id FROM sAssessment.tResult WHERE ExamId= @lExamId AND AcademicId=@lAcademicId)
		BEGIN
		
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
			
			INSERT INTO [sAssessment].[tResult]
				   (
					[Id],[AcademicId],[ExamId],[TotalMarks],[TotalObtain],[ResultStatus]
				   ,[ResultGrade],[ResultGradePoint],[RankNumber],[Percentage]
				   ,[Percentile],[ResultRemark],[OtherRemark1],[UpdatedUserId],[UpdatedDateTime]
				   )
			 VALUES
				   (
					@lNextNumber,@lAcademicId,@lExamId,0,0
				   ,'','',0,0,0.0,0.0,'',''
				   ,999900003
				   ,sCommon.fGetDate()
			   )
		END		
		ELSE
			BEGIN
				SELECT @lNextNumber = Id FROM sAssessment.tResult WHERE ExamId= @lExamId AND AcademicId=@lAcademicId
			END
		---------------		
		IF NOT EXISTS(SELECT Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult 
					  Where AcademicId=@lAcademicId AND ExamId=@lExamId) AND ExamDetailId=@rExamDetailId)	
			BEGIN
				
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lDetailNextNumber output					
				INSERT INTO [sAssessment].[tResultDetail]
				   (
					[Id]
				   ,[ResultId] 
				   ,[ExamDetailId]
				   ,[Obtain]
				   ,[IsPresent]
				   )
			 VALUES
				   (
					@lDetailNextNumber,
					@lNextNumber
				   ,@rExamDetailId
				   ,@lMarks
				   ,1
				   )
				  
				  
		END	 
	 ELSE
		 BEGIN
		 	
			Select @lDetailNextNumber = Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@lAcademicId AND ExamId=@lExamId) AND ExamDetailId=@rExamDetailId
	  
			UPDATE  [sAssessment].[tResultDetail]
			SET
	          ExamDetailId=@rExamDetailId
			 ,Obtain=@lMarks
			 ,IsPresent=1
			WHERE Id = @lDetailNextNumber 		    
		END  
		---------------
		SET @lCount = @lCount -1	
	END	
	
	UPDATE sOmr.tExamSetup SET IsUpdated= 1 WHERE ExamDetailId = @rExamDetailId
	
	SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOmr].[pOMRAnswerKeyListGet]
	 @rClassId int,
	 @rExamId int,
	 @rClassSubjectId int,
	 @rPaperSeries tinyint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		

DECLARE @vNumberOfQuestion int
DECLARE @vExamDetailId int

 		
IF EXISTS (SELECT * FROM sOmr.tAnswerKeySetup ES INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ES.ExamdetailId
AND ExamId = @rExamId AND ClassSubjectId = @rClassSubjectId AND PaperSeriesId  = @rPaperSeries)
BEGIN
	SELECT  ES.ExamdetailId,
			QuestionNumber,
		    Answerkey,
		    Marks,
		    ISNULL(IsCancel	 ,0) AS IsCancel
	FROM sOmr.tAnswerKeySetup ES
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ES.ExamdetailId
	AND ExamId = @rExamId 
	AND ClassSubjectId = @rClassSubjectId
	AND PaperSeriesId  = @rPaperSeries
	ORDER BY QuestionNumber
END
ELSE
	BEGIN
		CREATE TABLE #tempAnswerKeySetup
 		(	Id INT IDENTITY (1, 1),
 			ExamDetailId int,
 			QuestionNumber int,
 			AnswerKey nvarchar(5),
 			Marks decimal(12,2),
 			PaperSeries tinyint,
 			IsCancel bit
 		)  	

		SELECT @vNumberOfQuestion=NUMBEROFQUESTION,@vExamDetailId=ES.ExamDetailId FROM sOmr.TExamSetup ES
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ES.ExamdetailId
		AND ExamId = @rExamId 
		AND ClassSubjectId = @rClassSubjectId
		AND ES.PaperSeriese >= @rPaperSeries AND @rPaperSeries <> 0 
		
		
		WHILE (@vNumberOfQuestion > 0)
		BEGIN
			INSERT INTO #tempAnswerKeySetup (ExamDetailId,QuestionNumber,AnswerKey,Marks,PaperSeries,IsCancel)	
			VALUES (@vExamDetailId,@vNumberOfQuestion,'',1,@rPaperSeries,0)		
			SET @vNumberOfQuestion = @vNumberOfQuestion  -1
		END		
		SELECT * FROM #tempAnswerKeySetup ORDER BY QuestionNumber
	END		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOmr].[pOMRExamSubjectListGet]
	 @rClassId int,
	 @rExamId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
	    ED.Id AS ExamDetailId,
		SM.Title as SubjectName,
		CS.Id as ClassSubjectId,
		ISNULL(ED.Maximum,0) AS Marks,
		ISNULL(NumberOfQuestion,0) AS NumberOfQuestion,
		ISNULL(PaperSeriese,0) AS PaperSeriese,
		ISNULL(WrongMarkDeduction,0) AS WrongMarkDeduction,
		ISNULL(NonAttemptMarkDeduction,0) AS NonAttemptMarkDeduction,
		ISNULL(MultiAttemptMarkDeduction,0) AS MultiAttemptMarkDeduction,
		CASE WHEN ISNULL(NumberOfQuestion,0) <> 0 THEN 1 ELSE 0  END as Selected,
		CASE WHEN ISNULL(IsMultiTrueAns,0) <> 0 THEN 1 ELSE 0  END as IsMultiTrueAns
		
	FROM 
			[sSetup].[tClassMaster] CM INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.Id
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId	
			INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id	AND ED.ExamId = @rExamId
			LEFT JOIN sOmr.tExamSetup ES ON ES.ExamDetailId = ED.Id
			
	Where (CS.Classid=@rClassId or @rClassId=0) 	    
			order by CS.OrderIndex ASC
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sOp].[pGatewayConfigurationAdd]
	
	@rId int,
	@rOrgGroupId smallint,
	@rPaymentGatewayId smallint,
	@rGatewayURL nvarchar(1000),
	@rServerPort nvarchar(50),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(50),
	@rProductId nvarchar(100),
	@rTermsCondition nvarchar(max)='',
	@rPrivacyPolicy nvarchar(max)='',
	@rPaymentPolicy nvarchar(max)='',
	@rDisclaimer nvarchar(max)='',
	@rContactUs nvarchar(max)='',
	@rAboutUs nvarchar(max)='',
	@rIsObsolete bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION	
	
	DECLARE @lNextNumber INT  	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT 1 FROM sOp.tGatewayConfiguration WHERE OrgGroupId = @rOrgGroupId AND PaymentGatewayId = @rPaymentGatewayId)
		BEGIN
			SELECT -11 AS RESULT
			RETURN   
		END
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayConfiguration', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sOp.tGatewayConfiguration
			(
				Id,
				OrgGroupId,
				PaymentGatewayId,
				GatewayURL,
				ServerPort,
				LoginId,
				LoginPassword,
				ProductId,
				TermsCondition,
				PrivacyPolicy,
				PaymentPolicy,
				Disclaimer,
				ContactUs,
				AboutUs,
				IsObsolete
			)
		VALUES
			(
				@lNextNumber,
				@rOrgGroupId,
				@rPaymentGatewayId,
				@rGatewayURL,
				@rServerPort,
				@rLoginId,
				@rLoginPassword,
				@rProductId,
				@rTermsCondition,
				@rPrivacyPolicy,
				@rPaymentPolicy,
				@rDisclaimer,
				@rContactUs,
				@rAboutUs,
				@rIsObsolete
			)

	END 
	ELSE
	BEGIN

		SET @lNextNumber = @rId
	    UPDATE  sOp.tGatewayConfiguration
	    SET
			PaymentGatewayId=@rPaymentGatewayId,
			GatewayURL=@rGatewayURL,
			ServerPort=@rServerPort,
			LoginId=@rLoginId,
			LoginPassword=@rLoginPassword,
			ProductId=@rProductId,
			TermsCondition=@rTermsCondition,
			PrivacyPolicy=@rPrivacyPolicy,
			PaymentPolicy=@rPaymentPolicy,
			Disclaimer=@rDisclaimer,
			ContactUs=@rContactUs,
			AboutUs=@rAboutUs,
			IsObsolete=@rIsObsolete
	     WHERE Id = @rId   

	END  
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sOp].[pGatewayConfigurationGet]
	 
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT
			ISNULL(GC.Id,0) AS Id,
			GC.OrgGroupId,
			GC.PaymentGatewayId,
			GC.GatewayURL,
			GC.ServerPort,
			GC.LoginId,
			GC.LoginPassword,
			GC.ProductId,
			ISNULL(TermsCondition,'') AS TermsCondition,
			ISNULL(PrivacyPolicy,'') AS PrivacyPolicy,
			ISNULL(PaymentPolicy,'') AS PaymentPolicy,
			ISNULL(Disclaimer,'') AS Disclaimer,
			ISNULL(ContactUs,'') AS ContactUs,
			ISNULL(AboutUs,'') AS AboutUs,
			ISNULL(IsObsolete,'') AS IsObsolete,
			PGM.Title AS PaymentGateway
	FROM
			sOp.tGatewayConfiguration GC
			INNER JOIN sOp.tPaymentGatewayMaster PGM ON PGM.Id = GC.PaymentGatewayId
	WHERE 
			GC.OrgGroupId=@rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOp].[pGatewayProductAdd]
	 
    @rId int,
	@rGatewayConfigurationId int,
	@rTitle nvarchar(150),
	@rGatewayURL nvarchar(1000),
	@rServerPort nvarchar(50),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(50),
	@rProductId nvarchar(100),
	@rOrgGroupId int,
		
	@rCCAvenueMerchantID nvarchar(50)='',
	@rCCAvenueAccessCode nvarchar(100)='',
	@rCCAvenueWorkingKey nvarchar(100)='',
	@rCCAvenueWhitelistURL nvarchar(500)='',
	@rCCAvenueSubAccountId nvarchar(100)='',
		
	@rAtomReqHashKey nvarchar(100)='',
	@rAtomRespHashKey nvarchar(100)='',
		
	@rPaytmMID nvarchar(50)='',
	@rPaytmMerchantKey nvarchar(50)='',
	@rPaytmChannelId nvarchar(20)='',
	@rPaytmIndustryTypeId nvarchar(20)='',
	@rPaytmWebsite nvarchar(20)='',
	@rPaytmStatusCheckURL nvarchar(500)='',
		
	@rPayUMoneyMERCHANTID nvarchar(20)='',
	@rPayUMoneyMERCHANTKEY nvarchar(20)='',
	@rPayUMoneySALT nvarchar(20)='',
	@rPayUMoneyHASHSEQUENCE nvarchar(200)='',
	@rPayUMoneyAUTHHEADER nvarchar(50)='',
		
	@rBillDeskMerchantID nvarchar(50)='',
	@rBillDeskChecksumKey nvarchar(50)='',
	@rBillDeskSecurityID nvarchar(50)='',
	@rBillDeskUniqueIdentifier nvarchar(50)='',
		
	@rEazypayMerchantId nvarchar(50)='',
	@rEazypayAESKey nvarchar(50)='',
		
	@rAxisMerchantId nvarchar(50)='',
	@rAxisAPIKey nvarchar(50)='',
	@rAxisResponseKey nvarchar(50)='',
		
	@rRazorpayMID nvarchar(50)='',
	@rRazorpayKeyID nvarchar(50)='',
	@rRazorpaySecretKey nvarchar(50)='',
	@rRazorpaySubMerchantId nvarchar(50)='',
	
	@rBBPSCharge nvarchar(500) = '',
	@rBBPSGST decimal(12,2) = 0,
		
	@rGrayQuestClientId nvarchar(50)='',
	@rGrayQuestSecretKey nvarchar(50)='',
	@rGrayQuestApiKey nvarchar(50)='',

	@rEasebuzzKey nvarchar(50)='',
	@rEasebuzzSalt nvarchar(50)='',
	@rEasebuzzIsLiveEnvironment bit = null,
	@rEasebuzzIsEnableiFrame bit = null,
	@rEasebuzzSubMerchantId nvarchar(50)='',

	@rHesabeAccessCode nvarchar(50)='',
	@rHesabeMerchantCode nvarchar(50)='',
	@rHesabeMerchantKey nvarchar(50) = '',
	@rHesabeMerchantIV nvarchar(50)='',
	@rHesabeVersion nvarchar(10) = '2.0',
	@rHesabeIsLiveEnvironment bit = null,

	--For Mantis 0034589 by Foram
	@rRazorpayCollectNowMID	nvarchar(50) = '',
	@rRazorpayCollectNowKeyID nvarchar(50) = '',
	@rRazorpayCollectNowSecretKey nvarchar(50) = '',
	--For Mantis 0034589 by Foram

	--For Mantis 0040006 by Foram
	@rPaytmNewMID nvarchar(50)='',
	@rPaytmNewMerchantKey nvarchar(50)='',
	@rPaytmNewChannelId nvarchar(20)='',
	@rPaytmNewIndustryTypeId nvarchar(20)='',
	@rPaytmNewWebsite nvarchar(20)='',
	@rPaytmNewStatusCheckURL nvarchar(500)='',
	--For Mantis 0040006 by Foram
	--start Mantis : 0040383
	@rBillDeskV2MerchantID nvarchar(50)='',
	@rBillDeskV2SubMerchantID nvarchar(50)='',
	@rBillDeskV2ChecksumKey nvarchar(50)='',
	@rBillDeskV2SecurityID nvarchar(50)='',
	@rBillDeskV2UniqueIdentifier nvarchar(50)='',

	@rEazypayICICIV4MerchantID nvarchar(50)='',
	@rEazypayICICIV4SubMerchantID nvarchar(50)='',	
	@rEazypayICICIV4AESKey nvarchar(50)=''
	--end Mantis : 0040383
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId AND Id<>@rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
	END	

	BEGIN TRANSACTION	
	DECLARE @lNextNumber INT     
	IF(@rId = 0)	
	BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayProduct', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sOp].[tGatewayProduct]
		(
			[Id],
			[GatewayConfigurationId],
			[Title],
			[GatewayURL],
			[ServerPort],
			[LoginId],
			[LoginPassword],
			[ProductId],
			[CCAvenueMerchantID],
			[CCAvenueAccessCode],
			[CCAvenueWorkingKey],
			[CCAvenueWhitelistURL],
			[CCAvenueSubAccountId],
			[AtomReqHashKey],
			[AtomRespHashKey],
			[PaytmMID],
			[PaytmMerchantKey],
			[PaytmChannelId],
			[PaytmIndustryTypeId],
			[PaytmWebsite],
			[PaytmStatusCheckURL],
			[PayUMoneyMERCHANTID],
			[PayUMoneyMERCHANTKEY],
			[PayUMoneySALT],
			[PayUMoneyHASHSEQUENCE],
			[PayUMoneyAUTHHEADER],
			[BillDeskMerchantID],
			[BillDeskChecksumKey],
			[BillDeskSecurityID],
			[BillDeskUniqueIdentifier],
			[EazypayMerchantId],
			[EazypayAESKey],
			[AxisMerchantId],
			[AxisAPIKey],
			[AxisResponseKey],
			[RazorpayMID],
			[RazorpayKeyID],
			[RazorpaySecretKey],
			[BBPSCharges],
			[BBPSGST],
			[GrayQuestClientId],
			[GrayQuestSecretKey],
			[GrayQuestAPIKey],
			[EasebuzzKey],
			[EasebuzzSalt],
			[EasebuzzIsLiveEnvironment],
			[EasebuzzIsEnableiFrame],
			[EasebuzzSubMerchantId],
			HesabeAccessCode,
			HesabeMerchantKey,
			HesabeMerchantIV,
			HesabeMerchantCode,
			HesabeVersion,
			HesabeIsLiveEnvironment,
			RazorpaySubMerchantId,
			--For Mantis 0034589 by Foram Start
			RazorpayCollectNowMID,
			RazorpayCollectNowKeyID,
			RazorpayCollectNowSecretKey,
			--For Mantis 0034589 by Foram End
			--For Mantis 0040006 by Foram
			[PaytmNewMID],
			[PaytmNewMerchantKey],
			[PaytmNewChannelId],
			[PaytmNewIndustryTypeId],
			[PaytmNewWebsite],
			[PaytmNewStatusCheckURL],
			--For Mantis 0040006 by Foram
			--start Mantis : 0040383
			[BillDeskV2MerchantID],
			[BillDeskV2SubMerchantID],
			[BillDeskV2ChecksumKey],
			[BillDeskV2SecurityID],
			[BillDeskV2UniqueIdentifier],

			[EazypayICICIV4MerchantID],
			[EazypayICICIV4SubMerchantID],
			[EazypayICICIV4AESKey]			
			--end Mantis : 0040383

		)
		VALUES
		(
			@lNextNumber,
			@rGatewayConfigurationId,
			@rTitle,
			@rGatewayURL,
			@rServerPort,
			@rLoginId,
			@rLoginPassword,
			@rProductId,
			@rCCAvenueMerchantID,
			@rCCAvenueAccessCode,
			@rCCAvenueWorkingKey,
			@rCCAvenueWhitelistURL,
			@rCCAvenueSubAccountId,
			@rAtomReqHashKey,
			@rAtomRespHashKey,
			@rPaytmMID,
			@rPaytmMerchantKey,
			@rPaytmChannelId,
			@rPaytmIndustryTypeId,
			@rPaytmWebsite,
			@rPaytmStatusCheckURL,
			@rPayUMoneyMERCHANTID,
			@rPayUMoneyMERCHANTKEY,
			@rPayUMoneySALT,
			@rPayUMoneyHASHSEQUENCE,
			@rPayUMoneyAUTHHEADER,
			@rBillDeskMerchantID,
			@rBillDeskChecksumKey,
			@rBillDeskSecurityID,
			@rBillDeskUniqueIdentifier,
			@rEazypayMerchantId,
			@rEazypayAESKey,
			@rAxisMerchantId,
			@rAxisAPIKey,
			@rAxisResponseKey,
			@rRazorpayMID,
			@rRazorpayKeyID,
			@rRazorpaySecretKey,
			@rBBPSCharge,
			@rBBPSGST,
			@rGrayQuestClientId,
			@rGrayQuestSecretKey,
			@rGrayQuestApiKey,
			@rEasebuzzKey,
			@rEasebuzzSalt,
			@rEasebuzzIsLiveEnvironment,
			@rEasebuzzIsEnableiFrame,
			@rEasebuzzSubMerchantId,
			@rHesabeAccessCode,
			@rHesabeMerchantKey,
			@rHesabeMerchantIV,
			@rHesabeMerchantCode,
			@rHesabeVersion,
			@rHesabeIsLiveEnvironment,
			@rRazorpaySubMerchantId,
			--For Mantis 0034589 by Foram Start
			@rRazorpayCollectNowMID,
			@rRazorpayCollectNowKeyID,
			@rRazorpayCollectNowSecretKey,
			--For Mantis 0034589 by Foram End
			--For Mantis 0040006 by Foram
			@rPaytmNewMID,
			@rPaytmNewMerchantKey,
			@rPaytmNewChannelId,
			@rPaytmNewIndustryTypeId,
			@rPaytmNewWebsite,
			@rPaytmNewStatusCheckURL,
			--For Mantis 0040006 by Foram
			--start Mantis : 0040383
			@rBillDeskV2MerchantID,
			@rBillDeskV2SubMerchantID,
			@rBillDeskV2ChecksumKey,
			@rBillDeskV2SecurityID,
			@rBillDeskV2UniqueIdentifier,

			@rEazypayICICIV4MerchantID,
			@rEazypayICICIV4SubMerchantID,
			@rEazypayICICIV4AESKey
			--end Mantis : 0040383
		)
		    SELECT 1 AS Result
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    UPDATE  [sOp].[tGatewayProduct]
	    SET
			[GatewayConfigurationId]=@rGatewayConfigurationId,
			[Title]=@rTitle,
			[GatewayURL]=@rGatewayURL,
			[ServerPort]=@rServerPort,
			[LoginId]=@rLoginId,
			[LoginPassword]=@rLoginPassword,
			[ProductId]=@rProductId,
			[CCAvenueMerchantID]=@rCCAvenueMerchantID,
			[CCAvenueAccessCode]=@rCCAvenueAccessCode,
			[CCAvenueWorkingKey]=@rCCAvenueWorkingKey,
			[CCAvenueWhitelistURL]=@rCCAvenueWhitelistURL,
			[CCAvenueSubAccountId]=@rCCAvenueSubAccountId,
			[AtomReqHashKey]=@rAtomReqHashKey,
			[AtomRespHashKey]=@rAtomRespHashKey,
			[PaytmMID]=@rPaytmMID,
			[PaytmMerchantKey]=@rPaytmMerchantKey,
			[PaytmChannelId]=@rPaytmChannelId,
			[PaytmIndustryTypeId]=@rPaytmIndustryTypeId,
			[PaytmWebsite]=@rPaytmWebsite,
			[PaytmStatusCheckURL]=@rPaytmStatusCheckURL,
			[PayUMoneyMERCHANTID]=@rPayUMoneyMERCHANTID,
			[PayUMoneyMERCHANTKEY]=@rPayUMoneyMERCHANTKEY,
			[PayUMoneySALT]=@rPayUMoneySALT,
			[PayUMoneyHASHSEQUENCE]=@rPayUMoneyHASHSEQUENCE,
			[PayUMoneyAUTHHEADER]=@rPayUMoneyAUTHHEADER,
			[BillDeskMerchantID]=@rBillDeskMerchantID,
			[BillDeskChecksumKey]=@rBillDeskChecksumKey,
			[BillDeskSecurityID]=@rBillDeskSecurityID,
			[BillDeskUniqueIdentifier]=@rBillDeskUniqueIdentifier,
			[EazypayMerchantId]=@rEazypayMerchantId,
			[EazypayAESKey]=@rEazypayAESKey,
			[AxisMerchantId]=@rAxisMerchantId,
			[AxisAPIKey]=@rAxisAPIKey,
			[AxisResponseKey]=@rAxisResponseKey,
			[RazorpayMID]=@rRazorpayMID,
			[RazorpayKeyID]=@rRazorpayKeyID,
			[RazorpaySecretKey]=@rRazorpaySecretKey,
			[BBPSCharges] = @rBBPSCharge,
			[BBPSGST] = @rBBPSGST,
			GrayQuestClientId = @rGrayQuestClientId,
			GrayQuestSecretKey = @rGrayQuestSecretKey,
			GrayQuestAPIKey = @rGrayQuestApiKey,
			[EasebuzzKey] = @rEasebuzzKey,
			[EasebuzzSalt] = @rEasebuzzSalt,
			[EasebuzzIsLiveEnvironment] = @rEasebuzzIsLiveEnvironment,
			[EasebuzzIsEnableiFrame] = @rEasebuzzIsEnableiFrame,
			[EasebuzzSubMerchantId] = @rEasebuzzSubMerchantId,
			HesabeAccessCode = @rHesabeAccessCode,
			HesabeMerchantKey = @rHesabeMerchantKey,
			HesabeMerchantIV = @rHesabeMerchantIV,
			HesabeMerchantCode = @rHesabeMerchantCode,
			HesabeVersion = @rHesabeVersion,
			HesabeIsLiveEnvironment = @rHesabeIsLiveEnvironment,
			RazorpaySubMerchantId = @rRazorpaySubMerchantId,
			--For Mantis 0034589 by Foram Start
			RazorpayCollectNowMID = @rRazorpayCollectNowMID,
			RazorpayCollectNowKeyID = @rRazorpayCollectNowKeyID,
			RazorpayCollectNowSecretKey	= @rRazorpayCollectNowSecretKey,
			--For Mantis 0034589 by Foram End
			--For Mantis 0040006 by Foram
			[PaytmNewMID]=@rPaytmNewMID,
			[PaytmNewMerchantKey]=@rPaytmNewMerchantKey,
			[PaytmNewChannelId]=@rPaytmNewChannelId,
			[PaytmNewIndustryTypeId]=@rPaytmNewIndustryTypeId,
			[PaytmNewWebsite]=@rPaytmNewWebsite,
			[PaytmNewStatusCheckURL]=@rPaytmNewStatusCheckURL,
			--For Mantis 0040006 by Foram
			--start Mantis : 0040383
			[BillDeskV2MerchantID]=@rBillDeskV2MerchantID,
			[BillDeskV2SubMerchantID]=@rBillDeskV2SubMerchantID,
			[BillDeskV2ChecksumKey]=@rBillDeskV2ChecksumKey,
			[BillDeskV2SecurityID]=@rBillDeskV2SecurityID,
			[BillDeskV2UniqueIdentifier]=@rBillDeskV2UniqueIdentifier,

			[EazypayICICIV4MerchantID]=@rEazypayICICIV4MerchantID,
			[EazypayICICIV4SubMerchantID]=@rEazypayICICIV4SubMerchantID,
			[EazypayICICIV4AESKey]=@rEazypayICICIV4AESKey
			
			--end Mantis : 0040383
	    WHERE Id = @rId
	    SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOp].[pGatewayProductGet]

	 @rId int,
	 @rGatewayConfigurationId int,
	 @rTitle nvarchar(150),
	 @rOrgGroupId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			GP.Id,
			GP.GatewayConfigurationId,
			PGM.Title AS PaymentGatewayName,
			GP.Title AS GatewayProductName,
			ISNULL(GP.GatewayURL,'') AS GatewayURL,
			ISNULL(GP.ServerPort,'') AS ServerPort,
			ISNULL(GP.LoginId,'') AS LoginId,
			ISNULL(GP.LoginPassword,'') AS LoginPassword,
			ISNULL(GP.ProductId,'') AS ProductId,
			
			ISNULL(GP.CCAvenueMerchantID,'') AS CCAvenueMerchantID,
			ISNULL(GP.CCAvenueAccessCode,'') AS CCAvenueAccessCode,
			ISNULL(GP.CCAvenueWorkingKey,'') AS CCAvenueWorkingKey,
			ISNULL(GP.CCAvenueWhitelistURL,'') AS CCAvenueWhitelistURL,
			ISNULL(GP.CCAvenueSubAccountId,'') AS CCAvenueSubAccountId,
			
			ISNULL(GP.AtomReqHashKey,'') AS AtomReqHashKey,
			ISNULL(GP.AtomRespHashKey,'') AS AtomRespHashKey,
			ISNULL(GP.PaytmMID,'') AS PaytmMID,
			ISNULL(GP.PaytmMerchantKey,'') AS PaytmMerchantKey,
			ISNULL(GP.PaytmChannelId,'') AS PaytmChannelId,
			ISNULL(GP.PaytmIndustryTypeId,'') AS PaytmIndustryTypeId,
			ISNULL(GP.PaytmWebsite,'') AS PaytmWebsite,
			ISNULL(GP.PaytmStatusCheckURL,'') AS PaytmStatusCheckURL,
			ISNULL(GP.PayUMoneyMERCHANTID,'') AS PayUMoneyMERCHANTID,
			ISNULL(GP.PayUMoneyMERCHANTKEY,'') AS PayUMoneyMERCHANTKEY,
			ISNULL(GP.PayUMoneySALT,'') AS PayUMoneySALT,
			ISNULL(GP.PayUMoneyHASHSEQUENCE,'') AS PayUMoneyHASHSEQUENCE,
			ISNULL(GP.PayUMoneyAUTHHEADER,'') AS PayUMoneyAUTHHEADER,
			
			ISNULL(GP.BillDeskMerchantID,'') AS BillDeskMerchantID,
			ISNULL(GP.BillDeskChecksumKey,'') AS BillDeskChecksumKey,
			ISNULL(GP.BillDeskSecurityID,'') AS BillDeskSecurityID,
			ISNULL(GP.BillDeskUniqueIdentifier,'') AS BillDeskUniqueIdentifier,
			ISNULL(GP.EazypayMerchantId,'') AS EazypayMerchantId,
			ISNULL(GP.EazypayAESKey,'') AS EazypayAESKey,

			ISNULL(GP.AxisMerchantId,'') AS AxisMerchantId,
			ISNULL(GP.AxisAPIKey,'') AS AxisAPIKey,
			ISNULL(GP.AxisResponseKey,'') AS AxisResponseKey,

			ISNULL(GP.RazorpayMID,'') AS RazorpayMID,
			ISNULL(GP.RazorpayKeyID,'') AS RazorpayKeyID,
			ISNULL(GP.RazorpaySecretKey,'') AS RazorpaySecretKey,

			ISNULL(GP.BBPSCharges,'') AS BBPSCharges,
			ISNULL(GP.BBPSGST,0) AS BBPSGST,

			ISNULL(GP.GrayQuestClientId,'') AS GrayQuestClientId,
			ISNULL(GP.GrayQuestSecretKey,'') AS GrayQuestSecretKey,
			ISNULL(GP.GrayQuestApiKey,'') AS GrayQuestApiKey,

			ISNULL(GP.EasebuzzKey,'') AS EasebuzzKey,
			ISNULL(GP.EasebuzzSalt,'') AS EasebuzzSalt,
			ISNULL(GP.EasebuzzIsLiveEnvironment, 0) AS EasebuzzIsLiveEnvironment,
			ISNULL(GP.EasebuzzIsEnableiFrame, 0) AS EasebuzzIsEnableiFrame,
			ISNULL(GP.EasebuzzSubMerchantId,'') AS EasebuzzSubMerchantId,

			ISNULL(GP.HesabeAccessCode,'') AS HesabeAccessCode,
			ISNULL(GP.HesabeMerchantKey,'') AS HesabeMerchantKey,
			ISNULL(GP.HesabeMerchantIV, '') AS HesabeMerchantIV,
			ISNULL(GP.HesabeMerchantCode, '') AS HesabeMerchantCode,
			ISNULL(GP.HesabeVersion, '2.0') AS HesabeVersion,
			ISNULL(GP.HesabeIsLiveEnvironment,0) AS HesabeIsLiveEnvironment,

			ISNULL(GP.RazorpaySubMerchantId, '') AS RazorpaySubMerchantId,

			--For Mantis 0034589 by Foram
			ISNULL(RazorpayCollectNowMID, '') AS RazorpayCollectNowMID,
			ISNULL(RazorpayCollectNowKeyID, '') AS RazorpayCollectNowKeyID,
			ISNULL(RazorpayCollectNowSecretKey, '') AS RazorpayCollectNowSecretKey,
			--For Mantis 0034589 by Foram

			--For Mantis 0040006 by Foram
			ISNULL(GP.PaytmNewMID,'') AS PaytmNewMID,
			ISNULL(GP.PaytmNewMerchantKey,'') AS PaytmNewMerchantKey,
			ISNULL(GP.PaytmNewChannelId,'') AS PaytmNewChannelId,
			ISNULL(GP.PaytmNewIndustryTypeId,'') AS PaytmNewIndustryTypeId,
			ISNULL(GP.PaytmNewWebsite,'') AS PaytmNewWebsite,
			ISNULL(GP.PaytmNewStatusCheckURL,'') AS PaytmNewStatusCheckURL,
			--For Mantis 0040006 by Foram
			--start Mantis : 0040383
			ISNULL(GP.BillDeskV2MerchantID,'') AS BillDeskV2MerchantID,
			ISNULL(GP.BillDeskV2SubMerchantID,'') AS BillDeskV2SubMerchantID,
			ISNULL(GP.BillDeskV2ChecksumKey,'') AS BillDeskV2ChecksumKey,
			ISNULL(GP.BillDeskV2SecurityID,'') AS BillDeskV2SecurityID,
			ISNULL(GP.BillDeskV2UniqueIdentifier,'') AS BillDeskV2UniqueIdentifier,

			ISNULL(GP.EazypayICICIV4MerchantID,'') AS EazypayICICIV4MerchantID,
			ISNULL(GP.EazypayICICIV4SubMerchantID,'') AS EazypayICICIV4SubMerchantID,
			ISNULL(GP.EazypayICICIV4AESKey,'') AS EazypayICICIV4AESKey
			
			--end Mantis : 0040383
	FROM 
			[sOp].[tGatewayProduct] GP
			INNER JOIN [sOp].[tGatewayConfiguration] GC ON GC.Id = GP.GatewayConfigurationId
			INNER JOIN [sOp].[tPaymentGatewayMaster] PGM ON PGM.Id = GC.PaymentGatewayId
	WHERE 
			(GC.OrgGroupId = @rOrgGroupId)
			AND	((GP.Id = @rId) OR (@rId = 0))
			AND	((GP.GatewayConfigurationId = @rGatewayConfigurationId) OR (@rGatewayConfigurationId = 0))
			AND ((GP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ISNULL(GC.IsObsolete,0) = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sOp].[pGatewayProductReceiptBookMappingAdd]
    
    @rOrgGroupId int,
	@rXmldoc [nvarchar](max),
	@rGatewayConfigurationId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @loDoc INT
BEGIN TRY
BEGIN TRANSACTION
			
	DELETE GPRBM FROM [sOp].[tGatewayProductReceiptBookMapping] GPRBM
	INNER JOIN [sOp].[tGatewayProduct] GP ON GP.Id = GPRBM.GatewayProductId
	INNER JOIN [sFee].[tReceiptBookMaster] RBM ON RBM.Id = GPRBM.ReceiptBookId 
	WHERE RBM.OrgGroupId=@rOrgGroupId AND GP.GatewayConfigurationId=@rGatewayConfigurationId
			
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXmldoc
		
	INSERT INTO [sOp].[tGatewayProductReceiptBookMapping]
	(
		[GatewayProductId],
		[ReceiptBookId],
		IsObsolete
	)
	SELECT
		GatewayProductId,
		ReceiptBookId,
		IsObsolete
	FROM OPENXML (@loDoc, '/Table/GatewayProductReceiptBookMapping', 1)
	WITH
	( 
		GatewayProductId int,
		ReceiptBookId int,
		IsObsolete bit
	)
	SELECT 1 AS Result	
	EXEC sp_xml_removedocument @loDoc
		
COMMIT TRANSACTION			

END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT -1 Result
END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sOp].[pGatewayProductReceiptBookMappingGet]

	 @rOrgGroupId int,
	 @rGatewayConfigurationId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			RBM.Id AS ReceiptBookId,
			RBM.Title AS ReceiptBookName,
			ISNULL(A.GatewayProductId,0) AS GatewayProductId,
			[sFee].[fCheckEntryPaymentTransactionGet](RBM.Id,@rGatewayConfigurationId) AS IsEnabled,
			ISNULL(A.IsObsolete,0) AS IsObsolete
	FROM 
			[sFee].[tReceiptBookMaster] RBM
			LEFT JOIN
			(SELECT RBM.Id,GPRBM.GatewayProductId,GPRBM.IsObsolete FROM [sFee].[tReceiptBookMaster] RBM 
			INNER JOIN [sOp].[tGatewayProductReceiptBookMapping] GPRBM ON RBM.Id = GPRBM.ReceiptBookId 
		    INNER JOIN [sOp].[tGatewayProduct] GP ON GP.Id = GPRBM.GatewayProductId AND GP.GatewayConfigurationId = @rGatewayConfigurationId
		    ) A ON A.Id = RBM.Id
			WHERE 
			RBM.OrgGroupId=@rOrgGroupId AND RBM.IsObsolete = 0
			ORDER BY RBM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sOp].[pOnlineFeeGet]

		@rOnlineFeeId bigint,
		@rSourceTypeId smallint
		
AS
SET NOCOUNT ON

BEGIN
	
	SELECT  
		TOF.Id AS OnlineFeeId,
		TOF.SourceTypeId,
		TOF.SourceId,
		TOF.PayDateTime,
		TOF.FeeAmount,
		TOF.PenaltyAmount,
		TOF.NetAmount,
		TOF.ReceiptBookId,
		A.OrgId,
		A.BatchId
	FROM 
		 sFee.tOnlineFee TOF
		 INNER JOIN sOp.tPaymentTransaction PT ON PT.TransactionSourceId=TOF.Id
		 INNER JOIN sStudent.tAcademic A ON A.Id = TOF.SourceId
	WHERE 
		 TOF.Id = @rOnlineFeeId AND PT.TransactionSourceTypeId = @rSourceTypeId	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOp].[pPaymentTransactionAdd] 
	@rId BIGINT = 0
	,@rTransactionSourceTypeId SMALLINT
	,@rTransactionSourceId BIGINT
	,@rPayerSourceTypeId SMALLINT
	,@rPayerSourceId BIGINT
	,@rPayAmount DECIMAL(12, 2)
	,@rTransactionStatusId INT
	,@rFunctionalityId SMALLINT
	,@rOrgId INT
	,@rOSTypeId SMALLINT = 0
	,@rPaymentGatewayId SMALLINT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

			DECLARE @lWrongFeeSetupOrReceiptBook int = 0
			IF(@rTransactionSourceTypeId = 2024)
			BEGIN
				IF NOT EXISTS (
						SELECT 1
						FROM sFee.tFeeSetup FS
						INNER JOIN sFee.tOnlineFee tOF ON tOF.ReceiptBookId = FS.ReceiptBookId
						INNER JOIN sFee.tOnlineFeeDetail OFD ON OFD.OnlineFeeId = tOF.Id AND OFD.FeeSetupId = FS.Id
						WHERE tOF.Id = @rTransactionSourceId 
						)
				BEGIN
					SELECT @lWrongFeeSetupOrReceiptBook = 1
				END
			END

			IF(@lWrongFeeSetupOrReceiptBook = 0)
			BEGIN

				DECLARE @lNextNumber BIGINT

				EXECUTE sCommon.pTableRowIdGet @rOrgId,'sOp.tPaymentTransaction',0,1,1,@outNextNumber = @lNextNumber OUTPUT

				INSERT INTO sOp.tPaymentTransaction (
					Id
					,TransactionSourceTypeId
					,TransactionSourceId
					,PayerSourceTypeId
					,PayerSourceId
					,PayDateTime
					,PayAmount
					,TransactionStatusId
					,FunctionalityId
					,OSTypeId
					,PaymentGatewayId
					)
				VALUES (
					@lNextNumber
					,@rTransactionSourceTypeId
					,@rTransactionSourceId
					,@rPayerSourceTypeId
					,@rPayerSourceId
					,sCommon.fGetDate()
					,@rPayAmount
					,@rTransactionStatusId
					,@rFunctionalityId
					,@rOSTypeId
					,@rPaymentGatewayId
				)

				SELECT @lNextNumber AS Result
			END
			ELSE
			BEGIN
				SELECT 0 AS Result
			END
		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 

CREATE OR ALTER PROCEDURE [sOp].[pPaymentTransactionDetailGet]
	@rOrgGroupId smallint=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rReferenceNo bigint=0,
	@rFunctionalityId int,
	@rReceiptBookId bigint
AS
SET NOCOUNT ON

BEGIN
	IF(@rFunctionalityId = 1)
	BEGIN
		SELECT  
			TSM.Title As TransactionStatus,
			FM.Title AS Functionality,
			PT.PayAmount,
			PT.PayDateTime,
			CONVERT(nvarchar(20),SM.Code) AS Code,
			SM.FirstName + ' ' + SM.LastName AS Name,
			CM.DisplayTitle +' - '+ DM.DisplayTitle AS ClassName,
			PT.Id AS PaymentTransactionId,
			ISNULL(OS.Title,'') AS OSType,
			ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
			ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId,
			BM.Title AS Batch,
			A.RollNo,
			SC.ParentContactNo,
			SC.ParentEmail,
			ISNULL(PGM.Title+'/'+GP.Title,'') AS PaymentGateway,
			ISNULL(R.ReceiptNumber,0) AS ReceiptNumber
		FROM 
			sOp.tPaymentTransaction PT 
			LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
			INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
			INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
			INNER JOIN sStudent.tAcademic A ON A.Id = PT.PayerSourceId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN sOp.tpaymentGatewayMaster PGM ON PT.PaymentGatewayId = PGM.Id
			LEFT JOIN sFee.tReceipt R ON R.PaymentTransactionId = PT.Id
			INNER JOIN 
			(
				SELECT OP.Id,RB.Id as ReceiptBookId FROM sFee.tOnlineFee OP 
				INNER JOIN  sFee.tReceiptBookMaster RB ON RB.Id = OP.ReceiptBookId
				WHERE RB.Id = @rReceiptBookId
			) O ON O.Id = PT.TransactionSourceId AND TransactionSourceTypeId = 2024
			INNER JOIN sOp.tGatewayProductReceiptBookMapping GPRM ON GPRM.ReceiptBookId = O.ReceiptBookId --AND ISNULL(GPRM.IsObsolete,0) = 0
			INNER JOIN sOp.tGatewayConfiguration GC ON GC.PaymentGatewayId = PGM.Id AND GC.OrgGroupId = @rOrgGroupId
			INNER JOIN sOp.tGatewayProduct GP ON GP.GatewayConfigurationId = GC.Id AND GP.Id = GPRM.GatewayProductId
		WHERE 
			 (PT.FunctionalityId = 1)
			 AND OM.OrgGroupId = @rOrgGroupId
			 AND OM.Id = @rOrgId
			 AND BM.Id = @rBatchId
			 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
	END
	ELSE IF(@rFunctionalityId = 2)
	BEGIN
		SELECT  
			TSM.Title As TransactionStatus,
			FM.Title AS Functionality,
			PT.PayAmount,
			PT.PayDateTime,
			CONVERT(nvarchar(20),AF.FormNo) AS Code,
			AF.FirstName + ' ' + AF.LastName AS Name,
			CM.DisplayTitle AS ClassName,
			PT.Id AS PaymentTransactionId,
			ISNULL(OS.Title,'') AS OSType,
			ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
			ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId,
			BM.Title AS Batch,
			0 AS RollNo,
			AF.ContactNo AS ParentContactNo,
			AF.ContactEmail AS ParentEmail,
			ISNULL(PGM.Title+'/'+GP.Title,'') AS PaymentGateway,
			ISNULL(R.ReceiptNumber,0) AS ReceiptNumber
		FROM 
			sOp.tPaymentTransaction PT           
			LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
			INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
			INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
			INNER JOIN sAdmission.tAdmissionForm AF ON AF.Id = PT.PayerSourceId
			INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.BatchId=AF.BatchId AND AC.ClassId=AF.ForClassId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = AC.ReceiptBookId AND RBM.Id = @rReceiptBookId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sOp.tpaymentGatewayMaster PGM ON PT.PaymentGatewayId = PGM.Id
			LEFT JOIN sFee.tReceipt R ON R.PaymentTransactionId = PT.Id
			LEFT JOIN sOp.tGatewayProductReceiptBookMapping GPRM ON GPRM.ReceiptBookId = RBM.Id --AND ISNULL(GPRM.IsObsolete,0) = 0
			INNER JOIN sOp.tGatewayConfiguration GC ON GC.PaymentGatewayId = PGM.Id AND GC.OrgGroupId = @rOrgGroupId
			INNER JOIN sOp.tGatewayProduct GP ON GP.GatewayConfigurationId = GC.Id AND GP.Id = GPRM.GatewayProductId
		WHERE 
				(PT.FunctionalityId = 2)
			 AND OM.OrgGroupId = @rOrgGroupId
			 AND OM.Id = @rOrgId
			 AND BM.Id = @rBatchId
			 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sOp].[pPaymentTransactionGet]
	@rId bigint = 0,
	@rFromDate date,
	@rToDate date,
	@rTransactionStatusId int,
	@rFunctionalityId smallint,
	@rFirstName nvarchar(50)='',
	@rOrgGroupId smallint=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rReceiptBookId int=0,
	@rOSTypeId int=0,
	@rFormNo int=0,
	@rReferenceNo bigint=0,
	@rPaymentGatewayId smallint = 0
AS
SET NOCOUNT ON

BEGIN
	IF(@rFunctionalityId=0)
	BEGIN
	
	SELECT * FROM 
	(
	SELECT  
		TSM.Title As TransactionStatus,
		FM.Title AS Functionality,
		PT.PayAmount,
		PT.PayDateTime,
		CONVERT(nvarchar(20),SM.Code) AS Code,
		SM.FirstName + ' ' + SM.LastName AS Name,
		CM.DisplayTitle +' - '+ DM.DisplayTitle AS ClassName,
		TSM.ColorCode,
		PT.TransactionSourceTypeId,
		PT.TransactionSourceId,
		PT.BankName,
		PT.Id AS PaymentTransactionId,
		PT.TransactionStatusId,
		ISNULL(PT.MerchantTransactionId,0) AS MerchantTransactionId,
		ISNULL(PT.FunctionalityId,0) AS FunctionalityId,
		O.Title AS ReceiptBook,
		ISNULL(OS.Title,'') AS OSType,
		ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
		ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId,
		O.ReceiptBookId 
	FROM 
		sOp.tPaymentTransaction PT     
		LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
		INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
		INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
		INNER JOIN sStudent.tAcademic A ON A.Id = PT.PayerSourceId
		INNER JOIN sStudent.tStudentMaster SM ON SM.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 OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN 
		(
			SELECT OP.Id,RB.Title,RB.Id as ReceiptBookId FROM sFee.tOnlineFee OP 
			INNER JOIN  sFee.tReceiptBookMaster RB ON RB.Id = OP.ReceiptBookId
			WHERE (RB.Id = @rReceiptBookId OR @rReceiptBookId=0)
		) O ON O.Id = PT.TransactionSourceId AND TransactionSourceTypeId = 2024
		
	WHERE 
		 ((PT.TransactionStatusId = @rTransactionStatusId) OR (@rTransactionStatusId=0))
		 AND (PT.FunctionalityId = 1)
		 AND ((PT.PayDateTime >=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((PT.PayDateTime < DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		 AND ((PT.PayerSourceId=@rId) OR (@rId=0))
		 --AND ((SM.FirstName like '%'+ @rFirstName + '%') OR (@rFirstName=''))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (ISNULL(PT.OSTypeId,0) = @rOSTypeId OR @rOSTypeId=0)
		 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
		 AND (ISNULL(PT.PaymentGatewayId,0) = @rPaymentGatewayId OR @rPaymentGatewayId=0)
	UNION ALL
	
	SELECT  
		TSM.Title As TransactionStatus,
		FM.Title AS Functionality,
		PT.PayAmount,
		PT.PayDateTime,
		CONVERT(nvarchar(20),AF.FormNo) AS Code,
		AF.FirstName + ' ' + AF.LastName AS Name,
		CM.DisplayTitle AS ClassName,
		TSM.ColorCode,
		PT.TransactionSourceTypeId,
		PT.TransactionSourceId,
		PT.BankName,
		PT.Id AS PaymentTransactionId,
		PT.TransactionStatusId,
		ISNULL(PT.MerchantTransactionId,0) AS MerchantTransactionId,
		ISNULL(PT.FunctionalityId,0) AS FunctionalityId,
		RBM.Title AS ReceiptBook,
		ISNULL(OS.Title,'') AS OSType,
		ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
		ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId,
		RBM.Id AS ReceiptBookId
	FROM 
		sOp.tPaymentTransaction PT                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
		LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId
		INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
		INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
		INNER JOIN sAdmission.tAdmissionForm AF ON AF.Id = PT.PayerSourceId
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.BatchId=AF.BatchId AND AC.ClassId=AF.ForClassId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = AC.ReceiptBookId AND (RBM.Id = @rReceiptBookId OR @rReceiptBookId=0)
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		 
	WHERE 
		 ((PT.TransactionStatusId = @rTransactionStatusId) OR (@rTransactionStatusId=0))
		 AND (PT.FunctionalityId = 2)
		 AND ((PT.PayDateTime >=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((PT.PayDateTime < DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		 AND ((PT.PayerSourceId=@rId) OR (@rId=0))
		 AND ((AF.FormNo = @rFormNo) OR (ISNULL(@rFormNo,0)=0))
		 --AND ((AF.FirstName like '%'+ @rFirstName + '%') OR (@rFirstName=''))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (ISNULL(PT.OSTypeId,0) = @rOSTypeId OR @rOSTypeId=0)
		 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
		 AND (ISNULL(PT.PaymentGatewayId,0) = @rPaymentGatewayId OR @rPaymentGatewayId=0)
	) A
	ORDER BY PayDateTime DESC
	END	
	
	IF(@rFunctionalityId=1)
	BEGIN
	SELECT  
		TSM.Title As TransactionStatus,
		FM.Title AS Functionality,
		PT.PayAmount,
		PT.PayDateTime,
		CONVERT(nvarchar(20),SM.Code) AS Code,
		SM.FirstName + ' ' + SM.LastName AS Name,
		CM.DisplayTitle +' - '+ DM.DisplayTitle AS ClassName,
		TSM.ColorCode,
		PT.TransactionSourceTypeId,
		PT.TransactionSourceId,
		PT.BankName,
		PT.Id AS PaymentTransactionId,
		PT.TransactionStatusId,
		ISNULL(PT.MerchantTransactionId,0) AS MerchantTransactionId,
		ISNULL(PT.FunctionalityId,0) AS FunctionalityId,
		O.Title AS ReceiptBook,
		ISNULL(OS.Title,'') AS OSType,
		ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
		ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId,
		O.ReceiptBookId
	FROM 
		sOp.tPaymentTransaction PT 
		LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
		INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
		INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
		INNER JOIN sStudent.tAcademic A ON A.Id = PT.PayerSourceId
		INNER JOIN sStudent.tStudentMaster SM ON SM.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 OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN 
		(
			SELECT OP.Id,RB.Title,RB.Id as ReceiptBookId FROM sFee.tOnlineFee OP 
			INNER JOIN  sFee.tReceiptBookMaster RB ON RB.Id = OP.ReceiptBookId
			WHERE (RB.Id = @rReceiptBookId OR @rReceiptBookId=0)
		) O ON O.Id = PT.TransactionSourceId AND TransactionSourceTypeId = 2024
	WHERE 
		 ((PT.TransactionStatusId = @rTransactionStatusId) OR (@rTransactionStatusId=0))
		 AND (PT.FunctionalityId = 1)
		 AND ((PT.PayDateTime >=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((PT.PayDateTime < DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		 AND ((PT.PayerSourceId=@rId) OR (@rId=0))
		 --AND ((SM.FirstName like '%'+ @rFirstName + '%') OR (@rFirstName=''))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (ISNULL(PT.OSTypeId,0) = @rOSTypeId OR @rOSTypeId=0)
		 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
		 AND (ISNULL(PT.PaymentGatewayId,0) = @rPaymentGatewayId OR @rPaymentGatewayId=0)
		 ORDER BY PT.PayDateTime DESC
	END
	
	IF(@rFunctionalityId=2)
	BEGIN
		SELECT  
		TSM.Title As TransactionStatus,
		FM.Title AS Functionality,
		PT.PayAmount,
		PT.PayDateTime,
		CONVERT(nvarchar(20),AF.FormNo) AS Code,
		AF.FirstName + ' ' + AF.LastName AS Name,
		CM.DisplayTitle AS ClassName,
		TSM.ColorCode,
		PT.TransactionSourceTypeId,
		PT.TransactionSourceId,
		PT.BankName,
		PT.Id AS PaymentTransactionId,
		PT.TransactionStatusId,
		ISNULL(PT.MerchantTransactionId,0) AS MerchantTransactionId,
		ISNULL(PT.FunctionalityId,0) AS FunctionalityId,
		RBM.Title AS ReceiptBook,
		ISNULL(OS.Title,'') AS OSType,
		ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
		ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId,
		RBM.Id AS ReceiptBookId
	FROM 
		sOp.tPaymentTransaction PT           
		LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
		INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
		INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
		INNER JOIN sAdmission.tAdmissionForm AF ON AF.Id = PT.PayerSourceId
		INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.BatchId=AF.BatchId AND AC.ClassId=AF.ForClassId 
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = AC.ReceiptBookId AND (RBM.Id = @rReceiptBookId OR @rReceiptBookId=0)
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
	WHERE 
		 ((PT.TransactionStatusId = @rTransactionStatusId) OR (@rTransactionStatusId=0))
		 AND (PT.FunctionalityId = 2)
		 AND ((PT.PayDateTime >=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((PT.PayDateTime < DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		 AND ((PT.PayerSourceId=@rId) OR (@rId=0))
		 AND ((AF.FormNo = @rFormNo) OR (ISNULL(@rFormNo,0)=0))
		 --AND ((AF.FirstName like '%'+ @rFirstName + '%') OR (@rFirstName=''))
		 AND OM.OrgGroupId = @rOrgGroupId
		 AND OM.Id = @rOrgId
		 AND BM.Id = @rBatchId
		 AND (ISNULL(PT.OSTypeId,0) = @rOSTypeId OR @rOSTypeId=0)
		 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
		 AND (ISNULL(PT.PaymentGatewayId,0) = @rPaymentGatewayId OR @rPaymentGatewayId=0)
		 ORDER BY PT.PayDateTime DESC
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- exec [sOp].[pPaymentTransactionStatusDetailGet] 9911, 9911, 991100105, 9911000000570, 9911000002072
CREATE OR ALTER PROCEDURE [sOp].[pPaymentTransactionStatusDetailGet]
@rOrgGroupId smallint=0,
@rOrgId int=0,
@rBatchId int=0,
@rUserId bigint,
@rPaymentTransactionId bigint
AS
BEGIN
	SELECT 
		PT.TransactionStatusId AS StatusId
	FROM sOp.tPaymentTransaction PT 
		LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
		INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
		INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
		INNER JOIN sStudent.tAcademic A ON A.Id = PT.PayerSourceId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	WHERE OM.OrgGroupId = @rOrgGroupId
		AND OM.Id = @rOrgId
		AND BM.Id = @rBatchId
		AND SM.id = @rUserId
		AND PT.Id = @rPaymentTransactionId
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOp].[pPaymentTransactionUpdate]
	 
	@rPaymentTransactionId bigint,
	@rMerchantTransactionId nvarchar(50),
	@rBankTransactionId bigint,
	@rBankName nvarchar(100),
	@rPaymentType nvarchar(50),
	@rCardNumber nvarchar(100),
	@rTransactionResponse nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
BEGIN TRY
BEGIN TRANSACTION	
 
    BEGIN 
	    UPDATE sOp.tPaymentTransaction
	    SET
	    MerchantTransactionId=@rMerchantTransactionId,
	    BankTransactionId=@rBankTransactionId,
	    BankName=@rBankName,
	    PaymentType=@rPaymentType,
	    CardNumber=@rCardNumber,
	    TransactionResponse=@rTransactionResponse
	    WHERE Id = @rPaymentTransactionId 
	    SELECT @rPaymentTransactionId AS Result
	END  
	
	COMMIT TRANSACTION
	
END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pCheckEditTestMaster]
	@rId [int] = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  
      		 
	IF EXISTS(SELECT 1 FROM sExamination.tTestRequest where TestId = @rId)
	  BEGIN
	    SELECT 1 AS IsEdit
	    END
	  ELSE	    
	    SELECT 0 AS IsEdit	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pIssueReturnAdd]
	@rOrgId int,
	@rReturnedByName [nvarchar](100),
	@rParticipantSourceId bigint,
	@rParticipantSourceTypeId int,
	@rRemark [nvarchar](300),
	@rCreatedUserId [bigint],
	@rIssueReturnDetailDataXml [nvarchar](max),
	@rNumber [nvarchar](20) OUTPUT,
	@rStoreLocationId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	DECLARE @loNextNumber nVarchar(20)	
	 
	EXECUTE sCommon.pPrefixSetupNextNumberGet  @rOrgId = @rOrgId, @rPrefixFunctionalityId = 53,@rStoreLocationId = @rStoreLocationId, @rNextNumber  = @loNextNumber OUTPUT

	SET @rNumber = @loNextNumber
	SET @rNumber = ISNULL(@rNumber, '-300')

IF @rNumber = '-300'
BEGIN

--IF @rStockIssueRequestId = 0
--SET @rStockIssueRequestId = NULL
--SELECT -300 AS Result, 0 AS PrescriptionID, '' AS PrescriptionNumber
SELECT -300 AS Result, '' AS Number, 0 AS Id 
RETURN
END

DECLARE @lNextNumber BIGINT
EXECUTE sCommon.pTableRowIdGet @rOrgId,'sOrderEntry.tIssueReturn', 0, 1, 1,@outNextNumber = @lNextNumber output
		--IF (@rNumber IS NULL)
		--BEGIN
		--	RAISERROR('5000', 15, 106) --error, severity, state
		--	RETURN
		--END

	INSERT INTO sOrderEntry.tIssueReturn
		(
			Id,
			Number,
			ReturnedByName,
			ToStoreLocationId,
			ParticipantSourceTypeId,
			ParticipantSourceId,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rNumber,
			@rReturnedByName,
			@rStoreLocationId,
			@rParticipantSourceTypeId,
			@rParticipantSourceId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
	EXEC [sOrderEntry].[pIssueReturnDetailAdd] @lNextNumber,@rIssueReturnDetailDataXml,@rOrgId
	
	SELECT 1 AS Result, @rNumber AS Number, @lNextNumber AS Id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pIssueReturnDetailAdd]
	@rIssueReturnId [int],
	@rIssueReturnDetailDataXml [nvarchar](max),
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	--DECLARE @lNextNumber INT
	--EXECUTE @lNextNumber = sCommon.pTableRowIdGet 0,'sOrderEntry.tIssueReturnDetail',  0,  1,  1

	DECLARE @loIdoc INT
	DECLARE @lCurrentId BIGINT
	DECLARE @lCount INT
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT,  @rIssueReturnDetailDataXml

	EXEC sCommon.pTableRowIdGet @rOrgId,'sOrderEntry.tIssueReturnDetail',  1,  1,  1,@outNextNumber = @lCurrentId output

	INSERT INTO sOrderEntry.tIssueReturnDetail
		(
			Id, 
			IssueReturnId, 
			DispenseBatchId, 
			IssuedQuantity, 
			ReturnQuantity, 
			ReasonId,
			CreatedDateTime,
			OrgId
		)
	SELECT  
		(row_number() OVER ( ORDER BY @lCurrentId )+ @lCurrentId) AS Id,  
		@rIssueReturnId,   
		DispenseBatchId,   
		IssuedQuantity,  
		ReturnQuantity,
		ReasonId,
		sCommon.fGetDate(),
		@rOrgId
		
	FROM OPENXML (@loIdoc,  '/IssueReturn/IssueReturnDetail',  1)
		WITH ( 
				DispenseBatchId BIGINT,  
				IssuedQuantity DECIMAL(22, 2), 
				ReturnQuantity DECIMAL(22, 2), 
				ReasonId INT,
				StockItemId INT,
				StockBatchId INT				
			  ) 
			  
			  	DECLARE @lLastNumber BIGINT     
		SELECT @lLastNumber = MAX(Id) FROM sOrderEntry.tIssueReturnDetail WHERE OrgId = @rOrgId  
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sOrderEntry.tIssueReturnDetail', @rCurrentNumber = @lLastNumber   	
			  
	--SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/IssueReturn/IssueReturnDetail',  1)
	--			 WITH (DispenseBatchId INT)
	--SET @lCurrentId  = @lCount + @lCurrentId 
		
	--EXECUTE sCommon.pTableRowIdModify @rOrgId=1 , @rTableTitle = 'sOrderEntry.tIssueReturnDetail',  @rCurrentNumber = @lCurrentId 	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pIssueReturnGet]
	@rNumber [nvarchar](30) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SELECT DISTINCT
			IR.Id AS IssueReturnId,  
			IR.Number IssueReturnNumber,  
			IR.ReturnedByName,  
			IR.ToStoreLocationId,  
			IR.Remark AS Remarks,  
			IR.CreatedUserId,  
			IR.CreatedDateTime AS IssueReturnDate,
			CASE IR.ParticipantSourceTypeId
	   WHEN  95 THEN EM.Code
	   WHEN 1001 THEN EM2.Code
	   END AS Code,
	   CASE IR.ParticipantSourceTypeId
	   WHEN  95 THEN EM.Id
	   WHEN 1001 THEN EFD.Id 
	   END AS EmployeeId,
			--EM.Code,
			--EM.Id AS EmployeeId,
			IRD.ReturnQuantity,
			DB.ReturnQuantity AS ReturnedQuantity,
			SIM.Code AS ItemCode,
			SIM.Title AS ItemName,
			DB.Id AS DispenseBatchId,
			IRD.Id AS IssueReturnDetailId,
			SIM.Id AS ItemId,
			SB.Id AS BatchId,
			IR.ToStoreLocationId AS StoreLocationId
			--P.Id AS PrescriptionId		--OE.RegistrationId
				
	   FROM sOrderEntry.tIssueReturn IR	
		INNER JOIN sOrderEntry.tIssueReturnDetail IRD
			ON IR.Id = IRD.IssueReturnId
			--INNER JOIN sHrm.tEmployeeMaster EM 
			--ON EM.Id=IR.ParticipantSourceId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=IR.ParticipantSourceId  AND IR.ParticipantSourceTypeId = 95 AND ISNULL(EM.IsOtherUser,0) = 0
   LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON IR.ParticipantSourceId = EFD.Id AND IR.ParticipantSourceTypeId = 1001
   LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = EFD.EmployeeId   AND ISNULL(EM2.IsOtherUser,0) = 0
			INNER JOIN sPharmacy.tDispenseBatch DB ON DB.Id=IRD.DispenseBatchId
	INNER JOIN sProcurement.tStockBatch SB ON SB.Id=DB.StockbatchId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId
	 
		--INNER JOIN	sOrderEntry.tOrderEntryBatch OEB
		--	ON OEB.Id = IRD.OrderEntryBatchId
		--INNER JOIN sOrderEntry.tOrderEntry OE
		--	ON OEB.OrderEntryId = OE.Id AND OE.ItemSourceTypeId in (34,  90)
		WHERE ((IR.Number = @rNumber) OR (@rNumber = ''))	

SELECT DISTINCT		
				IRD.IssuedQuantity,  
				IRD.ReturnQuantity,
			DB.ReturnQuantity AS ReturnedQuantity,  
				IRD.Id AS IssueReturnDetailId,  
				--T1.TotalIssuedQuantity,  	
				----(T1.TotalIssuedQuantity + T2.TotalOrderEntryIssuedQuantity) AS TotalIssuedQuantity,  
				--T1.TotalReturnQuantity,  
				IRD.ReasonId,
				CASE IR.ParticipantSourceTypeId
	   WHEN  95 THEN EM.Code
	   WHEN 1001 THEN EM2.Code
	   END AS Code,
	   CASE IR.ParticipantSourceTypeId
	   WHEN  95 THEN EM.Id
	   WHEN 1001 THEN EFD.Id 
	   END AS EmployeeId,
				--EM.Code,
				--EM.Id AS EmployeeId,
			SIM.Code AS ItemCode,
			SIM.Title AS ItemName,
			DB.Id AS DispenseBatchId,
			SIM.Id AS ItemId,
			SB.Id AS BatchId,
			IR.ToStoreLocationId AS StoreLocationId,
			IR.CreatedUserId
			--P.Id AS PrescriptionId 
				
				--CAST(OE.CreatedDateTime AS DATE) AS OrderDate,  
				--OEB.Id AS OrderEntryBatchId,  
				--OEB.OrderEntryId,  
				--OEB.BatchSourceId AS BatchId,  
				--ISNULL((CASE WHEN OE.ItemSourceTypeId = 34 THEN SB.Number ELSE CB.Number END),  '') AS BatchNumber,  
				--ISNULL((CASE WHEN OE.ItemSourceTypeId = 34 THEN SB.ExpiryDate ELSE CB.ExpiryDate END),  '') ExpiryDate,  
							
				--(CASE WHEN OE.ItemSourceTypeId = 34 THEN SIM.Code ELSE CIM.Code END) AS ItemCode,  
				--(CASE WHEN OE.ItemSourceTypeId = 34 THEN SIM.Title ELSE CIM.Title END)  AS ItemName, 
				--IM.Code AS ItemCode,  
				--IM.Title  AS ItemName,   
				--RM.Title AS ReasonName, 
				----ISNULL(SIM.Id,  0) AS ItemId
				--ISNULL(IM.Id,  0) AS ItemId,
				--ISNULL(OE.ItemSourceTypeId, 0) AS ItemSourceTypeId
				--T2.TotalOrderEntryIssuedQuantity,  
				--T1.BatchSourceId,   
				--T2.BatchSourceId,   
				--SB.Id
							
	   FROM sOrderEntry.tIssueReturn IR
		INNER JOIN sOrderEntry.tIssueReturnDetail IRD
			ON IR.Id = IRD.IssueReturnId
			--INNER JOIN sHrm.tEmployeeMaster EM 
			--ON EM.Id=IR.ParticipantSourceId
   LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=IR.ParticipantSourceId  AND IR.ParticipantSourceTypeId = 95 AND ISNULL(EM.IsOtherUser,0) = 0
   LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON IR.ParticipantSourceId = EFD.Id AND IR.ParticipantSourceTypeId = 1001
   LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = EFD.EmployeeId   AND ISNULL(EM2.IsOtherUser,0) = 0
			lEFT JOIN sCommon.tReasonMaster RM
			ON IRD.ReasonId = RM.Id
			INNER JOIN sPharmacy.tDispenseBatch DB ON DB.Id= IRD.DispenseBatchId
   INNER JOIN sProcurement.tStockBatch SB ON SB.Id=DB.StockbatchId
   INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId
 
		--INNER JOIN	sOrderEntry.tOrderEntryBatch OEB
		--	ON OEB.Id = IRD.OrderEntryBatchId
		--INNER JOIN sOrderEntry.tOrderEntry OE
		--	ON OEB.OrderEntryId = OE.Id AND OE.ItemSourceTypeId IN (34,  90)
		--LEFT JOIN sProcurement.vExtStockBatch SB
		--	ON OEB.BatchSourceId = SB.Id AND OEB.BatchSourceTypeId = 88
		--LEFT JOIN sConsignment.vExtConsignmentBatch CB
		--	ON OEB.BatchSourceId = CB.Id AND OEB.BatchSourceTypeId = 89
		--LEFT OUTER JOIN sIp.vExtStockItemMaster SIM	
		--	ON OE.ItemSourceId = SIM.Id AND OE.ItemSourceTypeId = 34
		--LEFT OUTER JOIN sConsignment.vExtItemMaster CIM	
		--	ON OE.ItemSourceId = CIM.Id AND OE.ItemSourceTypeId = 90
		--LEFT OUTER JOIN sOrderEntry.vExtItemMaster IM
		--	On OE.ItemSourceId = IM.Id AND OE.ItemSourceTypeId = IM.ItemSourceId AND (IM.ItemSourceId IN(34,  90))
		
	--INNER JOIN(SELECT IR.Id,   OEB.BatchSourceId,    SUM(IRD.IssuedQuantity) AS TotalIssuedQuantity,   SUM(IRD.ReturnQuantity) AS TotalReturnQuantity  
	--				FROM sOrderEntry.tIssueReturn IR
	--				INNER JOIN sOrderEntry.tIssueReturnDetail IRD
	--				ON IR.Id = IRD.IssueReturnId 
	--				INNER JOIN	sOrderEntry.tOrderEntryBatch OEB
	--				ON OEB.Id = IRD.OrderEntryBatchId 
	--				WHERE ((IR.Number = @rNumber) OR (@rNumber = ''))
	--				AND ((OEB.BatchSourceTypeId = 88 OR OEB.BatchSourceTypeId = 89) OR (ISNULL(OEB.BatchSourceTypeId, 0) = 0)) --OR (IM.IsBatchWiseTracking = 0 AND OEB.BatchSourceTypeId = 0) --AND (CASE WHEN IM.IsBatchWiseTracking = 1 THEN (OEB.BatchSourceTypeId = 88 OR OEB.BatchSourceTypeId = 89) ELSE 0)
	--				GROUP BY  OEB.BatchSourceId,   IR.Id 					
	--			   )T1 
	--		ON T1.Id = IR.Id AND T1.BatchSourceId = ((CASE WHEN OEB.BatchSourceTypeId = 88 THEN SB.Id ELSE CB.Id END))--(CASE WHEN IM.IsBatchWiseTracking = 1 THEN(CASE WHEN OEB.BatchSourceTypeId = 88 THEN SB.Id ELSE CB.Id END) ELSE 0 END)
	
			WHERE ((IR.Number = @rNumber) OR (@rNumber = ''))
				ORDER BY IRD.Id ASC
END

--select * from sOrderEntry.tIssueReturn
--select * from sOrderEntry.tIssueReturnDetail




/****** Object:  StoredProcedure [sAccounting].[pReimbursementTypeMasterGet]    Script Date: 06/15/2013 16:43:57 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pItemDetailsGet]
	@rId [int] = 0,
	@rItemSourceTypeId [int] = 0,
	@rItemCode [nvarchar](30) = '',
	@rItemDescription [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT	IM.Id AS ItemId,
			IM.Code AS ItemCode,
			IM.Title AS ItemDescription,
			IM.ServiceItemTypeId AS ItemTypeId,
			IM.ServiceItemTypeCode AS ItemTypeCode,
			IM.ServiceItemTypeTitle AS ItemTypeDescription,
			IM.ServiceCategoryId AS ItemCategoryId,
			IM.ServiceCategoryCode AS ItemCategoryCode,
			IM.ServiceCategoryTitle AS ItemCategoryTitle,
			IM.StandardPrice AS StandardPrice,
			--IM.TaxGroupId AS TaxGroupId,
			--IM.RateTypeId AS RateTypeId,
			--IM.LuxuryTaxRate AS LuxuryTaxRate,
			--IM.OrganizationDepartmentId AS DepartmentId,
			--IM.OrganizationDepartmentCode AS DepartmentCode,
			--IM.OrganizationDepartmentTitle AS DepartmentDescription,
			IM.ItemSourceId AS ItemSourceTypeId,
			--IM.IpRate AS PriceInPatient,
			--IM.OpRate AS PriceOutPatient,
			CAST(IM.IsBatchWiseTracking AS BIT) AS IsBatchWiseTrackingAvailableForStockItem
	
	FROM	sOrderEntry.vExtItemMaster IM
	
	WHERE	((IM.Id = @rId) OR (@rId = 0))
			AND ((IM.ItemSourceId = @rItemSourceTypeId) OR (@rItemSourceTypeId = 0))
			AND ((IM.Code = @rItemCode) OR (@rItemCode = ''))
			AND ((IM.Title = @rItemDescription) OR (@rItemDescription = ''))

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pListValueMasterAdd]
	 
	@rListValueMasterId int,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rListValueTypeId int,
	@rIsDelete bit,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		BEGIN TRY	
   BEGIN TRANSACTION

    IF(@rListValueMasterId = 0)
    BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sOrderEntry.tListValueMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	INSERT INTO sOrderEntry.tListValueMaster
		(
			Id,
			Code,
			Title,
			ListValueTypeId
		     
			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rListValueTypeId
		 		
			
		)	
	END
	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rListValueMasterId
	 IF(@rIsDelete = 0)
		BEGIN
	    UPDATE  sOrderEntry.tListValueMaster
	    SET
	      Code=@rCode, 
	      Title=@rTitle,
	      ListValueTypeId=@rListValueTypeId	      
	      WHERE Id = @rListValueMasterId 	  
	 END
	 ELSE 
	 DELETE FROM sOrderEntry.tListValueMaster  WHERE Id = @rListValueMasterId 	
	 END
	SELECT @lNextNumber AS Result
  
	  COMMIT TRANSACTION
         END TRY
         
        BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	    END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pListValueMasterGet]
	
	@rId int
 
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
 

	 SELECT 
			 
			LVM.Id,
			LVM.Code,
			LVM.Title AS Name,
			LVM.ListValueTypeId
			 
					 
	   FROM    sOrderEntry.tListValueMaster LVM
		 
	    
	  WHERE  LVM.ListValueTypeId=@rId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pListValueTypeMasterAdd]
	 
	@rId int,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sOrderEntry.tListValueTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sOrderEntry.tListValueTypeMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId		 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sOrderEntry.tListValueTypeMaster
	    SET
	      Code=@rCode, 
	      Title=@rTitle,
	      IsObsolete=@rIsObsolete,
	      UpdatedUserId = @rCreatedUserId,
		  UpdatedDateTime = sCommon.fGetDate()      
	       
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pListValueTypeMasterGet]
	
	 
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rOrgId int 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			BEGIN
				 SET @rCode = sCommon.fSearchStringGet(@rCode)
				 SET @rTitle=sCommon.fSearchStringGet(@rTitle)
			END

BEGIN

	 SELECT 
			LVTM.Id AS ListValueTypeId,
			LVTM.Code AS ListValueTypeCode,
			LVTM.Title AS ListValueTypeName,
			LVTM.IsObsolete AS IsObsolete
											 
	  FROM  sOrderEntry.tListValueTypeMaster LVTM 
	    
	  WHERE ((LVTM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	  AND	((LVTM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	  AND    (OrgId = @rOrgId) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pOrderEntryAdd]
	@rOrgId [int],
	@rOrderSourceScreenId [tinyint],
	@rOrderSourceTypeId [smallint],
	@rOrderSourceId [bigint],
	@rItemSourceTypeId [smallint],
	@rItemSourceId [int],
	@rDoctorEmployeeId [int],
	@rServiceOrganizationDepartmentId [smallint],
	@rOrderOrganizationDepartmentId [smallint],
	@rRemark [nvarchar](300),
	@rUnitPrice [decimal](22, 6),		
	@rQuantity [smallint],	
	@rPatientAmount [decimal](22, 6),	
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rSourceTypeId [int],
	@rSourceId [bigint]
		 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sOrderEntry.tOrderEntry', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sOrderEntry.tOrderEntry
		(
			OrgId,
			Id,
			OrderSourceScreenId,
			OrderSourceTypeId,
			OrderSourceId,
			ItemSourceTypeId,
			ItemSourceId,
			DoctorEmployeeId,
			ServiceOrganizationDepartmentId,
			OrderOrganizationDepartmentId,
			Remark,
			UnitPrice, 
			Quantity, 
			PatientAmount,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			SourceTypeId,
			SourceId			 
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			
			@rOrderSourceScreenId,
			CASE
				WHEN @rOrderSourceTypeId > 0
				THEN @rOrderSourceTypeId
				ELSE NULL
			END,
			CASE
				WHEN @rOrderSourceTypeId IN (26)
				THEN @lNextNumber
				ELSE @rOrderSourceId
			END,
			@rItemSourceTypeId,
			@rItemSourceId,
			CASE 
				WHEN @rDoctorEmployeeId > 0
				THEN @rDoctorEmployeeId
				ELSE NULL
			END,
			@rServiceOrganizationDepartmentId,
			CASE 
				WHEN @rOrderOrganizationDepartmentId > 0
				THEN @rOrderOrganizationDepartmentId
				ELSE NULL
			END,
			@rRemark,
			@rUnitPrice, 
			@rQuantity, 
			@rPatientAmount,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSourceTypeId,
			@rSourceId			 
		)
		
		SELECT @lNextNumber AS Result
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pOrderEntryBatchAdd]
	@rOrgId [int],
	@rOrderEntryId [int],
	@rBatchSourceTypeId [int],
	@rBatchSourceId [int],
	@rQuantity [decimal](12, 2)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	
		DECLARE @lNextNumber INT
		EXECUTE  sCommon.pTableRowIdGet @rOrgId,  'sOrderEntry.tOrderEntryBatch', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sOrderEntry.tOrderEntryBatch
		(
			OrgId,
			Id,
			OrderEntryId,
			BatchSourceTypeId,
			BatchSourceId,
			Quantity
		)
		VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rOrderEntryId,
			@rBatchSourceTypeId,
			@rBatchSourceId,
			@rQuantity
		)
		
		SELECT @lNextNumber AS Result
		
	END TRY
	
	BEGIN CATCH
		SELECT -1 AS Result
	END CATCH
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pOrderEntryBatchGet]
	@rOrderEntryId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		SELECT	OEB.Id,
				OEB.OrderEntryId,
				OEB.OrderEntryId AS OrderEntryDetailId,
				OEB.BatchSourceId,
				OEB.BatchSourceId AS BatchId,
				
				CASE OE.ItemSourceTypeId
					WHEN 34
					THEN vESB.Number
					ELSE vECBDFOE.Number
				END AS BatchNumber,
				
				--vESB.Number AS BatchNumber,
				
				CASE OE.ItemSourceTypeId
					WHEN 34
					THEN vESB.ExpiryDate
					ELSE vECBDFOE.ExpiryDate
				END AS ExpiryDate,
				
				--vESB.ExpiryDate AS ExpiryDate,
				
				CASE OE.ItemSourceTypeId
					WHEN 34
					THEN vESB.AvailableQuantity
					ELSE vECBDFOE.AvailableQuantity
				END AS AvailableQuantity,
				--vESB.AvailableQuantity AS AvailableQuantity,
				
				
				OEB.Quantity AS Quantity,
				OEB.Quantity AS UsedQuantity,
				CAST(OEB.Quantity AS INT) AS QuantityTaken,
				
				CASE OE.ItemSourceTypeId
					WHEN 34
					THEN vESB.StoreLocationId
					ELSE vECBDFOE.RequestedFromLocationId
				END AS StoreLocationId,
				--vESB.StoreLocationId AS StoreLocationId,	
				
				CASE OE.ItemSourceTypeId
					WHEN 34
					THEN vESB.StoreLocationId
					ELSE vECBDFOE.RequestedFromLocationId
				END AS IssueLocationId,
				--vESB.StoreLocationId AS IssueLocationId,
				
				vECBDFOE.ReceiptNumber,
				vECBDFOE.VendorName,
				
				OE.ItemSourceId AS ItemId,
				OE.ItemSourceTypeId AS ItemSourceTypeId
		
		FROM	sOrderEntry.tOrderEntryBatch OEB
		
				INNER JOIN sOrderEntry.tOrderEntry OE
					ON OEB.OrderEntryId = OE.Id
					
				LEFT OUTER JOIN sProcurement.vExtStockBatch vESB
					ON OEB.BatchSourceId = vESB.Id
						AND OE.ItemSourceTypeId = 34
						
				LEFT OUTER JOIN sConsignment.vExtConsignmentBatchDetailsForOe vECBDFOE
					ON OEB.BatchSourceId = vECBDFOE.Id
						AND OE.ItemSourceTypeId = 90
						
		WHERE	OEB.OrderEntryId = @rOrderEntryId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pOrderEntryBatchModify]
	@rId [int],
	@rQuantity [decimal](12, 2),
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	UPDATE	sOrderEntry.tOrderEntryBatch
	 
	SET		Quantity = @rQuantity,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	
	WHERE	Id = @rId
	
	SELECT 1 AS Result
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pOrderEntryDelete]
	
	@rOrgId [int],
	@rOrderSourceScreenId [tinyint],
	@rOrderSourceTypeId [smallint],
	@rOrderSourceId [bigint],
	@rItemSourceTypeId [smallint],
	@rItemSourceId [int],	
	@rSourceTypeId [int],
	@rSourceId [bigint]	
	
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 DELETE FROM sOrderEntry.tOrderEntry	    
	  WHERE OrderSourceTypeId = @rOrderSourceTypeId
			AND OrderSourceId = @rOrderSourceId
			AND ItemSourceTypeId = @rItemSourceTypeId
			AND ItemSourceId = @rItemSourceId
			AND SourceTypeId = @rSourceTypeId
			AND SourceId = @rSourceId
			AND OrderSourceScreenId = @rOrderSourceScreenId
			AND OrgId = @rOrgId
			
			SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pOrderEntryGet]
	@rRegistrationId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	 SELECT	OE.Id AS Id,
			OE.OrderSourceScreenId AS OrderSourceScreenId,
			OE.OrderSourceTypeId AS OrderSourceTypeId,
			OE.OrderSourceId AS OrderSourceId,
			OE.ItemSourceTypeId AS ItemSourceTypeId,
			OE.ItemSourceId AS ItemId,
			
			--CASE 
			--	WHEN OE.ItemSourceTypeId = 25
			--	THEN vEIMServiceItem.Code 
			--	ELSE vEIMStockItem.Code 
			--END AS ItemCode,
			
			vEIM.Code AS ItemCode,
			
			--CASE 
			--	WHEN OE.ItemSourceTypeId = 25
			--	THEN vEIMServiceItem.Title
			--	ELSE vEIMStockItem.Title 
			--END AS ItemDescription,
			
			vEIM.Title AS ItemDescription,
					
			OE.DoctorEmployeeId AS DoctorEmployeeId,
			vEDM.DoctorName AS DoctorName,
			OE.ServiceOrganizationDepartmentId AS ServiceDepartmentId,
			OE.OrderOrganizationDepartmentId AS OrderDepartmentId,
			ODM.Title AS ServiceDepartmentName,
			OE.Remark AS Remarks,
			OE.UnitPrice AS UnitPrice,
			OE.DiscountPercentage AS DiscountPercentage,
			OE.DiscountAmount AS DiscountAmount,
			OE.Quantity AS Quantity,
			OE.TaxAmount AS TaxAmount,
			OE.CorporateAmount AS CorporateOrderEntryAmount,
			OE.PatientAmount AS PatientOrderEntryAmount,
			OE.IsObsolete AS IsObsolete,
			OE.CreatedDateTime AS CreatedDateTime,
			OE.RegistrationId AS RegistrationId,
			vERWPD.ServiceChargeTypeId AS ServiceChargeTypeId,
			vERWPD.CorporateId AS CorporateId,
			vERWPD.PrivilegeId AS PrivilegeId,
			vERWPD.IsDisplayDiscountOnBill AS DisplayDiscountAmountOnBill,
			
			--CASE 
			--	WHEN OE.ItemSourceTypeId = 25
			--	THEN vEIMServiceItem.TaxGroupId
			--	ELSE vEIMStockItem.TaxGroupId 
			--END AS TaxId,
			
			--vEIM.TaxGroupId AS TaxId,
			
			--CASE 
			--	WHEN OE.ItemSourceTypeId = 25
			--	THEN vEIMServiceItem.RateTypeId
			--	ELSE vEIMStockItem.RateTypeId 
			--END AS RateTypeId,
			
			--vEIM.RateTypeId AS RateTypeId,
			
			--CASE 
			--	WHEN OE.ItemSourceTypeId = 25
			--	THEN vEIMServiceItem.StandardPrice
			--	ELSE vEIMStockItem.StandardPrice 
			--END AS StandardPrice,
			
			vEIM.StandardPrice AS StandardPrice,
			
			--CASE 
			--	WHEN OE.ItemSourceTypeId = 25
			--	THEN vEIMServiceItem.LuxuryTaxRate
			--	ELSE vEIMStockItem.LuxuryTaxRate 
			--END AS LuxuryTaxRate,
			
			----vEIM.LuxuryTaxRate AS LuxuryTaxRate,
			
			--CASE 
			--	WHEN OEB.OrderEntryId IS NULL 
			--	THEN CAST(0 AS BIT)
			--	ELSE CAST(1 AS BIT)
			--END AS IsBatchDetailsAvialble,
			
			--CASE 
			--	WHEN OE.ItemSourceTypeId = 25
			--	THEN CAST(0 AS BIT)
			--	ELSE CAST(vEIMStockItem.IsBatchWiseTracking AS BIT)
			--END AS IsBatchDetailsAvialble,
			
			CAST(vEIM.IsBatchWiseTracking AS BIT) AS IsBatchDetailsAvialble,
			
			OE.CreatedUserId AS CreatedUserId
			
			
	FROM	sOrderEntry.tOrderEntry OE
				
			LEFT OUTER JOIN (SELECT DISTINCT OrderEntryId FROM sOrderEntry.tOrderEntryBatch) OEB
				ON OE.Id = OEB.OrderEntryId
		      
		    LEFT OUTER JOIN sCwb.vExtDoctorMaster vEDM
				ON vEDM.EmployeeId = OE.DoctorEmployeeId
				
			LEFT OUTER JOIN sSetup.tDepartmentMaster ODM
				ON ODM.Id = OE.ServiceOrganizationDepartmentId
				
			LEFT OUTER JOIN sOrderEntry.vExtItemMaster vEIM
				ON vEIM.Id = OE.ItemSourceId
					AND vEIM.ItemSourceId = OE.ItemSourceTypeId
				
			--LEFT OUTER JOIN sOrderEntry.vExtItemMaster vEIMServiceItem
			--	ON vEIMServiceItem.Id = OE.ItemSourceId
			--		AND vEIMServiceItem.ItemSourceId = 25
			--		AND (OrderSourceScreenId IN (1, 2, 3, 6))
					
			--LEFT OUTER JOIN sOrderEntry.vExtItemMaster vEIMStockItem
			--	ON vEIMStockItem.Id = OE.ItemSourceId
			--		AND vEIMStockItem.ItemSourceId = 34
			--		AND (OrderSourceScreenId IN (1, 5, 6))
					
			INNER JOIN sRegistration.vExtRegistrationWithPatientDetail vERWPD
				ON OE.RegistrationId = vERWPD.Id

	   
	WHERE	((RegistrationId = @rRegistrationId) OR (@rRegistrationId = 0))
			AND OE.IsObsolete = 0
			AND OE.IsBilled = 0
			
	ORDER BY OE.Id DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pOrderEntryItemBatchGet]
	@rRegistrationId [int] = 0,
	@rItemSourceTypeId [int] = 0,
	@rItemId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		SELECT	OE.ItemSourceId AS ItemId,
				OE.ItemSourceTypeId AS ItemSourceTypeId,
				vEIM.Code AS ItemCode,
				vEIM.Title AS ItemName,
				OE.CreatedDateTime AS OrderDate,
				
				CASE	
					WHEN OEB.BatchSourceTypeId = 88
					THEN OEB.BatchSourceId 
					ELSE OEB.BatchSourceId 
				END AS BatchId,
				
				CASE	
					WHEN OEB.BatchSourceTypeId = 88
					THEN vESB.Number 
					ELSE (CASE WHEN vEIM.IsBatchWiseTracking = 1 THEN vECIDFIR.Number + ' - ' + vECIDFIR.VendorName + ' - ' + vECIDFIR.ReceiptNumber
							ELSE vECIDFIR.Number + ' - ' + vECIDFIR.VendorName END)
				END AS BatchNumber,
				
				CASE	
					WHEN OEB.BatchSourceTypeId = 88
					THEN vESB.ExpiryDate 
					ELSE sCommon.fGetDate()
				END  AS ExpiryDate,
				
				CAST (vEIM.IsBatchWiseTracking AS BIT) AS IsBatchWiseTracking,
				
				OEB.Id AS OrderEntryBatchId, 
				OE.Id AS OrderEntryId,
				OEB.Quantity AS IssuedQuantity,
				ISNULL((CASE WHEN OEB.BatchSourceTypeId = 89
					THEN (SELECT REQLOC.RequestedFromLocationId FROM sConsignment.vExtRequestFromLocationForIssueReturn REQLOC
							WHERE REQLOC.BatchSourceId = OEB.BatchSourceId) 
					END), 0) AS ConsignmentLocationId
				
		
		FROM	sOrderEntry.tOrderEntryBatch OEB
		
				INNER JOIN sOrderEntry.tOrderEntry OE
					ON OEB.OrderEntryId = OE.Id
					
				LEFT OUTER JOIN sProcurement.vExtStockBatch vESB
					ON OEB.BatchSourceId = vESB.Id
						AND OEB.BatchSourceTypeId = 88
					
				LEFT OUTER JOIN sConsignment.vExtConsignmentItemDetailForIssueReturn vECIDFIR
					ON OEB.BatchSourceId = vECIDFIR.Id
						AND OEB.BatchSourceTypeId = 89
					
				INNER JOIN sOrderEntry.vExtItemMaster vEIM
					ON	vEIM.Id = OE.ItemSourceId
						AND vEIM.ItemSourceId = OE.ItemSourceTypeId
	   
		WHERE	((OE.RegistrationId = @rRegistrationId) OR (@rRegistrationId = 0))
				AND ((OE.ItemSourceTypeId = @rItemSourceTypeId) OR (@rItemSourceTypeId = 0))
				AND ((OE.ItemSourceId = @rItemId) OR (@rItemId = 0))
				AND (OE.IsBilled = 0)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pOrderEntryRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sOrderEntry.tOrderEntry
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pParameterMasterDelete]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS(SELECT ID FROM sOrderEntry.tServiceDetail WHERE ServiceParameterId = @rId)
BEGIN
SELECT -101 AS RESULT
END
ELSE
BEGIN
DELETE FROM sOrderEntry.tServiceParameterRange WHERE ServiceParameterId = @rId
DELETE FROM sOrderEntry.tServiceParameterMaster WHERE Id = @rId


SELECT 1 AS RESULT
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pPatientSearchGet]
	@rPId [nvarchar](20) = '',
	@rPatientName [nvarchar](30) = '',
	@rMobileNumber [nvarchar](20) = '',
	@rProofIdType [nvarchar](20) = '',
	@rProofIdNumber [nvarchar](20) = '',
	@rDOB [datetime] = '1/1/1900'
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lDatePresent Int 

SET @rPId = sCommon.fSearchStringGet(@rPId)
SET @rPatientName = sCommon.fSearchStringGet(@rPatientName)
SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber)
SET @rProofIdType = sCommon.fSearchStringGet(@rProofIdType)
SET @rProofIdNumber = sCommon.fSearchStringGet(@rProofIdNumber)

IF (CAST(@rDOB AS DATE) =  CAST('1/1/1900' AS DATE))
BEGIN
  SET  @lDatePresent = 0
END
ELSE
BEGIN
  SET  @lDatePresent = 1
END

SELECT DISTINCT Top 1000  PM.Id  AS Id,
		ISNULL(PM.PatientNumber, '') AS PId,
		ISNULL(PM.PatientName, '') AS PatientName,
		PM.FirstName AS FirstName,
		PM.MiddleName AS MiddleName,
		PM.LastName AS LastName,
		ISNULL(IdM.Title, '') AS IdProofType,
		ISNULL(IdProofNumber, '') AS IdProofNumber,
		ISNULL(DateOfBirth, '')  AS DateOfBirth,
		(CASE DateOfBirth 
		          WHEN '1900-01-01 00:00:00.000' THEN NULL
				  ELSE  ISNULL(DateOfBirth, NULL)
		END) DOB,
		ISNULL(PC.PhoneNumberMobile, '') AS MobileNumber,
		PC.PhoneNumberHome AS LandLine,
		PC.EmailPrimary AS EmailId,
		PA.StreetOne AS StreetOne,
		PA.StreetTwo AS StreetTwo,
		PA.StreetThree AS StreetThree,
		PA.StreetFour AS StreetFour,
		PA.ZipCode AS ZipCode,
		PA.AreaId AS AreaId,
		AM.Title AS Area,
		AM.CityId AS CityId,
		CM.Title AS CityTitle,
		CM.StateId AS StateId,
		SM.Title AS StateTitle,
		SM.CountryId AS CountryId,
		CountryMaster.Title AS CountryTitle,
		PM.GenderId AS GenderId,
		GM.Title AS Gender,
		PM.MaritalStatusId AS MaritalStatusId,
		MM.Title AS MaritalStatus,
		PM.SalutationId AS SalutationId,
		SalutationMaster.Title AS Salutation,
		REG.RegStatus AS VisitType,
		REG.ServiceChargeTypeId AS PatientType		
		

		 FROM 
		 --sRegistration.vExtPatientMaster PM
		 --LEFT JOIN sRegistration.vExtRegistration REG
		 --ON PM.Id = REG.PatientId
		  sOrderEntry.tOrderEntry OE
		 --ON OE.RegistrationId = REG.Id AND OE.IsBilled = 0
		 INNER JOIN sRegistration.vExtRegistration REG
		 ON OE.RegistrationId = REG.Id AND OE.IsBilled = 0
		 LEFT JOIN  sRegistration.vExtPatientMaster PM		 
		 ON PM.Id = REG.PatientId
		 LEFT  JOIN sCommon.tIdProofTypeMaster IdM
		 ON PM.IdProofTypeId = IdM.Id
		 LEFT JOIN sRegistration.vExtPatientContact PC
		 ON PM.CommunicationContactId = PC.Id
		 LEFT JOIN sRegistration.vExtPatientAddress PA
		 ON PM.CommunicationAddressId = PA.Id
		 LEFT JOIN sCommon.tAreaMaster AM
		 ON PA.AreaId = AM.Id
		 LEFT JOIN sCommon.tCityMaster CM
		 ON AM.CityId = CM.Id
		 LEFT JOIN sCommon.tStateMaster SM
		 ON CM.StateId = SM.Id
		 LEFT JOIN sCommon.tCountryMaster CountryMaster
		 ON SM.CountryId = CountryMaster.Id
		 LEFT JOIN sCommon.tGenderMaster GM
		 ON PM.GenderId = GM.Id
		 LEFT JOIN sCommon.tMaritalStatusMaster MM
		 ON PM.MaritalStatusId = MM.Id
		 LEFT JOIN sCommon.tSalutationMaster SalutationMaster
		 ON PM.SalutationId =  SalutationMaster.Id
		 
		 
		 WHERE 
		      ((PM.PatientNumber Like @rPId) OR(@rPId = ''))
			AND ((PM.PatientName Like  @rPatientName)  OR (@rPatientName = ''))
			AND ((PC.PhoneNumberMobile Like @rMobileNumber) OR(@rMobileNumber = ''))
			AND (
			        ((PM.IdProofTypeId Like @rProofIdType )  AND (PM.IdProofNumber Like @rProofIdNumber ) )
			          OR ((@rProofIdType = '') AND (@rProofIdNumber = '' ))
			       )
			AND PM.IsObsolete = 0
	        AND
	     
				(( REG.ServiceChargeTypeId IN (1, 2)) AND (REG.RegStatusId = 1)) 
			
			
      AND 
			      (
			     ( CAST(CONVERT(NVARCHAR(12), PM.DateOfBirth, 101) AS DATETIME) =  CAST(CONVERT(NVARCHAR(12),  @rDOB, 101) AS DATETIME) AND (@lDatePresent = 1))
			     OR
			     ( CAST(CONVERT(NVARCHAR(12), ISNULL(PM.DateOfBirth, '1900-01-01'), 101) AS DATETIME) > =  CAST(CONVERT(NVARCHAR(12), '1900-01-01', 101) AS DATETIME) AND (@lDatePresent = 0))
			      )
 	 
			       
		ORDER BY  PM.Id DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pRptDepartmentWiseListing]
	@rFromDate [datetime] = '1900/1/1',
	@rToDate [datetime] = '1900/1/1',
	@rFromDept [nvarchar](20) = '',
	@rToDept [nvarchar](20) = '',
	@rStatus [int] = 0,
	@rCreditNote [int] = 1,
	@rDebitNote [int] = 1,
	@rBillLevelDiscounts [int] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
IF (@rCreditNote = 1 AND @rDebitNote = 1 AND @rBillLevelDiscounts = 1)
	BEGIN
		SELECT DISTINCT
				B.BillNumber AS DocNo,
				 B.CreatedDateTime AS DocDateTime,
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType,
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 OE.Quantity AS Quantity,
				 BD.Amount AS Amount,
				 BD.DiscountAmount AS Discount,
				 0 AS BillLevelDiscount,
				 BD.TaxAmount AS Tax,
				 (BD.Amount + BD.TaxAmount - BD.DiscountAmount)AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  OE.ODMTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  OE.DeptId DepartmentId,
				  
				  ISNULL(UPPER(SM.SITMTitle), UPPER(ISNULL(StockMaster.SITMTitle, CON.SITMTitle))) AS ServiceDescription,
				  ISNULL(UPPER(SM.SITMCodeTitle), UPPER(ISNULL(StockMaster.SITMCodeTitle, CON.ConsCodeTitle))) AS ServiceItemcodeName,
				  ISNULL(UPPER(SM.SMTitle), UPPER(ISNULL(StockMaster.SMTitle, CON.ConsTitle))) AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts,
				  'Credit Note / Debit Note / Bill Level Discount'			 AS TransactionType,
			BD.Id AS LineItemId
				 
				 
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
								FROM sOrderEntry.tServiceMaster SM
									INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
										ON 	SITM.Id = SM.ServiceItemTypeId) SM	
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
								FROM sIp.vExtStockItemMaster StockMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
								FROM sConsignment.vExtItemMaster ConsMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
						ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
	UNION ALL
	
	SELECT	DISTINCT	
				 B.CNNumber AS DocNo,
				B.CNDate AS DocDateTime,
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType,
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 1 AS Quantity,
				 -B.DocumentAmount AS Amount,
				 0 AS BillLevelDiscount,
				 0 AS Discount,
				 0 AS Tax,
				 -B.DocumentAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  B.DeptTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  B.DeptId DepartmentId,
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'CREDIT NOTE' AS ServiceItemcodeName,
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
				 
				 
		FROM    sOrderEntry.tBillingDetail BD
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate,
									CN.Amount DocumentAmount, CN.DeptTitle DeptTitle, CN.DeptId DeptId
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT CN.BillingId, CND.OrganizationDepartmentId, CN.Number,
										CN.RoundOffAmount Amount, CN.CreatedDateTime, ODM.Title DeptTitle, ODM.Id DeptId 
											 FROM sNotes.tCreditNote CN
												INNER JOIN sNotes.tCreditNoteDetail CND
													ON CND.CreditNoteId = CN.Id
												INNER JOIN sSetup.tDepartmentMaster ODM
										ON CND.OrganizationDepartmentId = ODM.Id) CN
									ON CN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
				
				
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, 
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId
								FROM sOrderEntry.tOrderEntry OE
									--INNER JOIN sSetup.tDepartmentMaster ODM
									--	ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle, StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((B.DeptTitle >= @rFromDept AND B.DeptTitle <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
						
		UNION ALL
						
		SELECT	DISTINCT
			 B.DNNumber AS DocNo, 
			 B.DNDate AS DocDateTime,
			--(CASE 
	 	--			WHEN B.DebtorTypeID = 1 THEN 
			--			ISNULL(B.vRPDPatientNumber, '')
			--		ELSE 
			--			ISNULL(B.CMCode, '')
			--		END
			--) AS Pid,
			ISNULL(B.vRPDPatientNumber, '') AS Pid,
			B.PatientType AS PatientType,
			--(CASE 
	 	--			WHEN B.DebtorTypeID = 1 THEN 
			--			ISNULL(B.vRPDPatientName, '')
			--		ELSE 
			--			ISNULL(B.CMTitle, '')
			--		END
			--) AS PatientName,
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
			 --OE.Quantity AS Quantity,
			 1 AS Quantity,
			 B.DocumentAmount AS Amount,
			 0 AS Discount,
			 0 AS BillLevelDiscount,
			 0 AS Tax,
			 B.DocumentAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  B.DeptTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  B.DeptId DepartmentId,
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'DEBIT NOTE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
				 
		FROM    sOrderEntry.tBillingDetail BD
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate,
									DN.Amount DocumentAmount, DN.DeptTitle DeptTitle, DN.DeptId DeptId
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT DN.BillingId, DND.OrganizationDepartmentId, DN.Number,
										DN.RoundOffAmount Amount, DN.CreatedDateTime, ODM.Title DeptTitle, ODM.Id DeptId 
											 FROM sNotes.tDebitNote DN
												INNER JOIN sNotes.tDebitNoteDetail DND
													ON DND.DebitNoteId = DN.Id
												LEFT JOIN sSetup.tDepartmentMaster ODM
										ON DND.OrganizationDepartmentId = ODM.Id) DN
									ON DN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
				
			
				
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle, StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
				--WHERE	((B.DNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
				--WHERE	((B.DNDate >= @rFromDate AND B.DNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
				WHERE	((B.DNDate >= @rFromDate AND B.DNDate <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((B.DeptTitle >= @rFromDept AND B.DeptTitle <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
		UNION ALL

		SELECT		DISTINCT
				POS.Number AS DocNo, 
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 0 AS Quantity,
				 SUM(POS.Quantity * POS.UnitPrice) AS Amount,
				 SUM(POS.ItemLevelDiscount) AS Discount,
				 0 AS BillLevelDiscount,
				 SUM(POS.TaxAmount) AS Tax,
				 SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount) AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  ODM.Title AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  ODM.Id DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'POINT OF SALE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			--POS.Id AS LineItemId			
			0 AS LineItemId
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
			GROUP BY POS.Number,
			POS.CreatedDateTime,
			vRPD.PatientNumber,
			vRPD.ServiceChargeTypeTitle,
			vRPD.PatientName,
			ODM.Title,
			ODM.Id,
			POS.Id
					

		UNION ALL
		--BLD 
		SELECT	 DISTINCT
				 B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 0 AS Quantity,
				 0 AS Amount,
				 0 AS Discount,
				 B.DiscountAmount AS BillLevelDiscount,
				 0 AS Tax,
				 -B.DiscountAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  --OE.ODMTitle AS DepartmentTitle,
				  ''  AS DepartmentTitle,
				  'BILL LEVEL DISCOUNTS' AS DiscountForGrouping,
				  0 DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  '' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			--B.Id AS LineItemId			
			0 AS LineItemId
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				RIGHT JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id --AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id --AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id --AND OE.ItemSourceTypeId = 90
				
					
			--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			
			--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
				AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
				OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
	
		UNION ALL

		SELECT		DISTINCT
				 POS.Number AS DocNo, 
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				
				 0 AS Quantity,
				 0 AS Amount,
				 0 AS Discount,
				 POSHeader.DiscountAmount AS BillLevelDiscount,
				 0 AS Tax,
				 -POSHeader.DiscountAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  
				  ''  AS DepartmentTitle,
				  'BILL LEVEL DISCOUNTS' AS DiscountForGrouping,
				  0 DepartmentId, 
				  
				  '' AS ServiceDescription,
				  '' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			--POS.Id AS LineItemId
			0 AS LineItemId
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sPharmacy.vExtPointOfSale POSHeader
			ON POSHeader.Id = POS.PointOfSaleId
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id 
				
			
			WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
	END
	ELSE IF (@rCreditNote = 1 AND @rDebitNote = 0 AND @rBillLevelDiscounts = 0)
	BEGIN
		SELECT	
				B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 OE.Quantity AS Quantity,
				 BD.Amount AS Amount,
				 BD.DiscountAmount AS Discount,
				 0 AS BillLevelDiscount,
				 BD.TaxAmount AS Tax,
				 (BD.Amount + BD.TaxAmount - BD.DiscountAmount)AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  OE.ODMTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  OE.DeptId DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems,
				  ISNULL(UPPER(SM.SITMTitle), UPPER(ISNULL(StockMaster.SITMTitle, CON.SITMTitle))) AS ServiceDescription,
				  ISNULL(UPPER(SM.SITMCodeTitle), UPPER(ISNULL(StockMaster.SITMCodeTitle, CON.ConsCodeTitle))) AS ServiceItemcodeName,
				  ISNULL(UPPER(SM.SMTitle), UPPER(ISNULL(StockMaster.SMTitle, CON.ConsTitle))) AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note'											AS TransactionType,
			BD.Id AS LineItemId
				 
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
								FROM sOrderEntry.tServiceMaster SM
									INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
										ON 	SITM.Id = SM.ServiceItemTypeId) SM	
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
								FROM sIp.vExtStockItemMaster StockMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
								FROM sConsignment.vExtItemMaster ConsMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
						ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
	UNION ALL
	
	SELECT	DISTINCT	
				 B.CNNumber AS DocNo,
				B.CNDate AS DocDateTime,
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType,
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 1 AS Quantity,
				 -B.DocumentAmount AS Amount,
				 0 AS BillLevelDiscount,
				 0 AS Discount,
				 0 AS Tax,
				 -B.DocumentAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  B.DeptTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  B.DeptId DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'CREDIT NOTE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note'											AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
				 
				 
		FROM    sOrderEntry.tBillingDetail BD
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate,
									CN.Amount DocumentAmount, CN.DeptTitle DeptTitle, CN.DeptId DeptId
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT CN.BillingId, CND.OrganizationDepartmentId, CN.Number,
										CN.RoundOffAmount Amount, CN.CreatedDateTime, ODM.Title DeptTitle, ODM.Id DeptId 
											 FROM sNotes.tCreditNote CN
												INNER JOIN sNotes.tCreditNoteDetail CND
													ON CND.CreditNoteId = CN.Id
												INNER JOIN sSetup.tDepartmentMaster ODM
										ON CND.OrganizationDepartmentId = ODM.Id) CN
									ON CN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
				
				
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, 
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId
								FROM sOrderEntry.tOrderEntry OE
									--INNER JOIN sSetup.tDepartmentMaster ODM
									--	ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle, StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((B.DeptTitle >= @rFromDept AND B.DeptTitle <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
						
		UNION ALL


		SELECT		DISTINCT
				POS.Number AS DocNo, 
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 0 AS Quantity,
				 SUM(POS.Quantity * POS.UnitPrice) AS Amount,
				 SUM(POS.ItemLevelDiscount) AS Discount,
				 0 AS BillLevelDiscount,
				 SUM(POS.TaxAmount) AS Tax,
				 SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount) AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  ODM.Title AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  ODM.Id DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'POINT OF SALE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note'											AS TransactionType,
			--POS.Id AS LineItemId
			0 AS LineItemId				 
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
			GROUP BY POS.Number,
			POS.CreatedDateTime,
			vRPD.PatientNumber,
			vRPD.ServiceChargeTypeTitle,
			vRPD.PatientName,
			ODM.Title,
			ODM.Id,
			POS.Id
	END			
	ELSE IF (@rDebitNote = 1 AND @rCreditNote = 0 AND @rBillLevelDiscounts = 0)
	BEGIN
		SELECT DISTINCT
				B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 OE.Quantity AS Quantity,
				 BD.Amount AS Amount,
				 BD.DiscountAmount AS Discount,
				 0 AS BillLevelDiscount,
				 BD.TaxAmount AS Tax,
				 (BD.Amount + BD.TaxAmount - BD.DiscountAmount)AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  OE.ODMTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  OE.DeptId DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems,
				  ISNULL(UPPER(SM.SITMTitle), UPPER(ISNULL(StockMaster.SITMTitle, CON.SITMTitle))) AS ServiceDescription,
				  ISNULL(UPPER(SM.SITMCodeTitle), UPPER(ISNULL(StockMaster.SITMCodeTitle, CON.ConsCodeTitle))) AS ServiceItemcodeName,
				  ISNULL(UPPER(SM.SMTitle), UPPER(ISNULL(StockMaster.SMTitle, CON.ConsTitle))) AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note'											AS TransactionType,
			BD.Id AS LineItemId
		FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
								FROM sOrderEntry.tServiceMaster SM
									INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
										ON 	SITM.Id = SM.ServiceItemTypeId) SM	
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
								FROM sIp.vExtStockItemMaster StockMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
								FROM sConsignment.vExtItemMaster ConsMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
						ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
	UNION ALL
	
	SELECT	DISTINCT
			 B.DNNumber AS DocNo, 
			 B.DNDate AS DocDateTime,
			--(CASE 
	 	--			WHEN B.DebtorTypeID = 1 THEN 
			--			ISNULL(B.vRPDPatientNumber, '')
			--		ELSE 
			--			ISNULL(B.CMCode, '')
			--		END
			--) AS Pid,
			ISNULL(B.vRPDPatientNumber, '') AS Pid,
			B.PatientType AS PatientType,
			--(CASE 
	 	--			WHEN B.DebtorTypeID = 1 THEN 
			--			ISNULL(B.vRPDPatientName, '')
			--		ELSE 
			--			ISNULL(B.CMTitle, '')
			--		END
			--) AS PatientName,
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
			 --OE.Quantity AS Quantity,
			 1 AS Quantity,
			 B.DocumentAmount AS Amount,
			 0 AS Discount,
			 0 AS BillLevelDiscount,
			 0 AS Tax,
			 B.DocumentAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  B.DeptTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  B.DeptId DepartmentId,
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'DEBIT NOTE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note'											AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
				 
		FROM    sOrderEntry.tBillingDetail BD
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate,
									DN.Amount DocumentAmount, DN.DeptTitle DeptTitle, DN.DeptId DeptId
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT DN.BillingId, DND.OrganizationDepartmentId, DN.Number,
										DN.RoundOffAmount Amount, DN.CreatedDateTime, ODM.Title DeptTitle, ODM.Id DeptId 
											 FROM sNotes.tDebitNote DN
												INNER JOIN sNotes.tDebitNoteDetail DND
													ON DND.DebitNoteId = DN.Id
												LEFT JOIN sSetup.tDepartmentMaster ODM
										ON DND.OrganizationDepartmentId = ODM.Id) DN
									ON DN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
				
			
				
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle, StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
						
				--WHERE	((B.DNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
				--WHERE	((B.DNDate >= @rFromDate AND B.DNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
				WHERE	((B.DNDate >= @rFromDate AND B.DNDate <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((B.DeptTitle >= @rFromDept AND B.DeptTitle <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
	UNION ALL

	SELECT DISTINCT
				POS.Number AS DocNo, 
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 0 AS Quantity,
				 SUM(POS.Quantity * POS.UnitPrice) AS Amount,
				 SUM(POS.ItemLevelDiscount) AS Discount,
				 0 AS BillLevelDiscount,
				 SUM(POS.TaxAmount) AS Tax,
				 SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount) AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  ODM.Title AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  ODM.Id DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'POINT OF SALE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note'											AS TransactionType,
			--POS.Id AS LineItemId
			0 AS LineItemId				 
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
			GROUP BY POS.Number,
			POS.CreatedDateTime,
			vRPD.PatientNumber,
			vRPD.ServiceChargeTypeTitle,
			vRPD.PatientName,
			ODM.Title,
			ODM.Id,
			POS.Id
	END
	ELSE IF (@rDebitNote = 0 AND @rCreditNote = 0 AND @rBillLevelDiscounts = 1)
	BEGIN
	SELECT DISTINCT
				B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 OE.Quantity AS Quantity,
				 BD.Amount AS Amount,
				 BD.DiscountAmount AS Discount,
				 0 AS BillLevelDiscount,
				 BD.TaxAmount AS Tax,
				 (BD.Amount + BD.TaxAmount - BD.DiscountAmount)AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  OE.ODMTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  OE.DeptId DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems,
				  ISNULL(UPPER(SM.SITMTitle), UPPER(ISNULL(StockMaster.SITMTitle, CON.SITMTitle))) AS ServiceDescription,
				  ISNULL(UPPER(SM.SITMCodeTitle), UPPER(ISNULL(StockMaster.SITMCodeTitle, CON.ConsCodeTitle))) AS ServiceItemcodeName,
				  ISNULL(UPPER(SM.SMTitle), UPPER(ISNULL(StockMaster.SMTitle, CON.ConsTitle))) AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Bill Level Discount'									AS TransactionType,
			BD.Id AS LineItemId				 
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
								FROM sOrderEntry.tServiceMaster SM
									INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
										ON 	SITM.Id = SM.ServiceItemTypeId) SM	
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
								FROM sIp.vExtStockItemMaster StockMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
								FROM sConsignment.vExtItemMaster ConsMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
						ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
	UNION ALL	

	SELECT DISTINCT
				POS.Number AS DocNo, 
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 0 AS Quantity,
				 SUM(POS.Quantity * POS.UnitPrice) AS Amount,
				 SUM(POS.ItemLevelDiscount) AS Discount,
				 0 AS BillLevelDiscount,
				 SUM(POS.TaxAmount) AS Tax,
				 SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount) AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  ODM.Title AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  ODM.Id DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'POINT OF SALE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Bill Level Discount'									AS TransactionType,
			--POS.Id AS LineItemId
			0 AS LineItemId
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
			GROUP BY POS.Number,
			POS.CreatedDateTime,
			vRPD.PatientNumber,
			vRPD.ServiceChargeTypeTitle,
			vRPD.PatientName,
			ODM.Title,
			ODM.Id,
			POS.Id
						

	UNION ALL

	SELECT	 DISTINCT
				 B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 0 AS Quantity,
				 0 AS Amount,
				 0 AS Discount,
				 B.DiscountAmount AS BillLevelDiscount,
				 0 AS Tax,
				 -B.DiscountAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  --OE.ODMTitle AS DepartmentTitle,
				  ''  AS DepartmentTitle,
				  'BILL LEVEL DISCOUNTS' AS DiscountForGrouping,
				  0 DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  '' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Bill Level Discount'									AS TransactionType,
			--B.Id AS LineItemId			
			0 AS LineItemId
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				RIGHT JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
	
	UNION ALL

	SELECT		DISTINCT
				 POS.Number AS DocNo, 
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				
				 0 AS Quantity,
				 0 AS Amount,
				 0 AS Discount,
				 POSHeader.DiscountAmount AS BillLevelDiscount,
				 0 AS Tax,
				 -POSHeader.DiscountAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  
				  ''  AS DepartmentTitle,
				  'BILL LEVEL DISCOUNTS' AS DiscountForGrouping,
				  0 DepartmentId, 
				  
				  '' AS ServiceDescription,
				  '' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Bill Level Discount'									AS TransactionType,
			--POS.Id AS LineItemId			
			0 AS LineItemId
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sPharmacy.vExtPointOfSale POSHeader
			ON POSHeader.Id = POS.PointOfSaleId
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id 
				
	WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
		
	END
	ELSE IF (@rCreditNote = 1 AND @rDebitNote = 0 AND @rBillLevelDiscounts = 1)
	BEGIN
		SELECT DISTINCT
				B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 OE.Quantity AS Quantity,
				 BD.Amount AS Amount,
				 BD.DiscountAmount AS Discount,
				 0 AS BillLevelDiscount,
				 BD.TaxAmount AS Tax,
				 (BD.Amount + BD.TaxAmount - BD.DiscountAmount)AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  OE.ODMTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  OE.DeptId DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems,
				  ISNULL(UPPER(SM.SITMTitle), UPPER(ISNULL(StockMaster.SITMTitle, CON.SITMTitle))) AS ServiceDescription,
				  ISNULL(UPPER(SM.SITMCodeTitle), UPPER(ISNULL(StockMaster.SITMCodeTitle, CON.ConsCodeTitle))) AS ServiceItemcodeName,
				  ISNULL(UPPER(SM.SMTitle), UPPER(ISNULL(StockMaster.SMTitle, CON.ConsTitle))) AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			BD.Id AS LineItemId	
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
								FROM sOrderEntry.tServiceMaster SM
									INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
										ON 	SITM.Id = SM.ServiceItemTypeId) SM	
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
								FROM sIp.vExtStockItemMaster StockMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
								FROM sConsignment.vExtItemMaster ConsMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
						ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
	UNION ALL
	
	SELECT	DISTINCT	
				 B.CNNumber AS DocNo, 
				B.CNDate AS DocDateTime,
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType,
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 1 AS Quantity,
				 -B.DocumentAmount AS Amount,
				 0 AS BillLevelDiscount,
				 0 AS Discount,
				 0 AS Tax,
				 -B.DocumentAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  B.DeptTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  B.DeptId DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'CREDIT NOTE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts,
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			--BD.Id AS LineItemId			
			0 AS LineItemId 
				 
				 
		FROM    sOrderEntry.tBillingDetail BD
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate,
									CN.Amount DocumentAmount, CN.DeptTitle DeptTitle, CN.DeptId DeptId
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT CN.BillingId, CND.OrganizationDepartmentId, CN.Number,
										CN.RoundOffAmount Amount, CN.CreatedDateTime, ODM.Title DeptTitle, ODM.Id DeptId 
											 FROM sNotes.tCreditNote CN
												INNER JOIN sNotes.tCreditNoteDetail CND
													ON CND.CreditNoteId = CN.Id
												INNER JOIN sSetup.tDepartmentMaster ODM
										ON CND.OrganizationDepartmentId = ODM.Id) CN
									ON CN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
				
				
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, 
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId
								FROM sOrderEntry.tOrderEntry OE
									--INNER JOIN sSetup.tDepartmentMaster ODM
									--	ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle, StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((B.DeptTitle >= @rFromDept AND B.DeptTitle <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
						
	UNION ALL

	SELECT DISTINCT
				POS.Number AS DocNo, 
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 0 AS Quantity,
				 SUM(POS.Quantity * POS.UnitPrice) AS Amount,
				 SUM(POS.ItemLevelDiscount) AS Discount,
				 0 AS BillLevelDiscount,
				 SUM(POS.TaxAmount) AS Tax,
				 SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount) AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  ODM.Title AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  ODM.Id DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'POINT OF SALE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts,
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			--POS.Id AS LineItemId
			0 AS LineItemId
				 
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
			GROUP BY POS.Number,
			POS.CreatedDateTime,
			vRPD.PatientNumber,
			vRPD.ServiceChargeTypeTitle,
			vRPD.PatientName,
			ODM.Title,
			ODM.Id,
			POS.Id
						

	UNION ALL

	SELECT	 DISTINCT
				 B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 0 AS Quantity,
				 0 AS Amount,
				 0 AS Discount,
				 B.DiscountAmount AS BillLevelDiscount,
				 0 AS Tax,
				 -B.DiscountAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  --OE.ODMTitle AS DepartmentTitle,
				  ''  AS DepartmentTitle,
				  'BILL LEVEL DISCOUNTS' AS DiscountForGrouping,
				  0 DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  '' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts,
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			--B.Id AS LineItemId			
			0 AS LineItemId	 
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				RIGHT JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
	
	UNION ALL

	SELECT DISTINCT
				 POS.Number AS DocNo,
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				
				 0 AS Quantity,
				 0 AS Amount,
				 0 AS Discount,
				 POSHeader.DiscountAmount AS BillLevelDiscount,
				 0 AS Tax,
				 -POSHeader.DiscountAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  
				  ''  AS DepartmentTitle,
				  'BILL LEVEL DISCOUNTS' AS DiscountForGrouping,
				  0 DepartmentId, 
				  
				  '' AS ServiceDescription,
				  '' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts,
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			--POS.Id AS LineItemId
			0 AS LineItemId
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sPharmacy.vExtPointOfSale POSHeader
			ON POSHeader.Id = POS.PointOfSaleId
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id 						
			
		WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
	END
	ELSE IF (@rCreditNote = 0 AND @rDebitNote = 1 AND @rBillLevelDiscounts = 1)
	BEGIN
		SELECT DISTINCT
				B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 OE.Quantity AS Quantity,
				 BD.Amount AS Amount,
				 BD.DiscountAmount AS Discount,
				 0 AS BillLevelDiscount,
				 BD.TaxAmount AS Tax,
				 (BD.Amount + BD.TaxAmount - BD.DiscountAmount)AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  OE.ODMTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  OE.DeptId DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems,
				  ISNULL(UPPER(SM.SITMTitle), UPPER(ISNULL(StockMaster.SITMTitle, CON.SITMTitle))) AS ServiceDescription,
				  ISNULL(UPPER(SM.SITMCodeTitle), UPPER(ISNULL(StockMaster.SITMCodeTitle, CON.ConsCodeTitle))) AS ServiceItemcodeName,
				  ISNULL(UPPER(SM.SMTitle), UPPER(ISNULL(StockMaster.SMTitle, CON.ConsTitle))) AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note / Bill Level Discount'						AS TransactionType,
			BD.Id AS LineItemId				 
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
								FROM sOrderEntry.tServiceMaster SM
									INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
										ON 	SITM.Id = SM.ServiceItemTypeId) SM	
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
								FROM sIp.vExtStockItemMaster StockMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
								FROM sConsignment.vExtItemMaster ConsMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
						ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
	UNION ALL
						
	SELECT	DISTINCT
			 B.DNNumber AS DocNo, 
			 B.DNDate AS DocDateTime,
			--(CASE 
	 	--			WHEN B.DebtorTypeID = 1 THEN 
			--			ISNULL(B.vRPDPatientNumber, '')
			--		ELSE 
			--			ISNULL(B.CMCode, '')
			--		END
			--) AS Pid,
			ISNULL(B.vRPDPatientNumber, '') AS Pid,
			B.PatientType AS PatientType,
			--(CASE 
	 	--			WHEN B.DebtorTypeID = 1 THEN 
			--			ISNULL(B.vRPDPatientName, '')
			--		ELSE 
			--			ISNULL(B.CMTitle, '')
			--		END
			--) AS PatientName,
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
			 --OE.Quantity AS Quantity,
			 1 AS Quantity,
			 B.DocumentAmount AS Amount,
			 0 AS Discount,
			 0 AS BillLevelDiscount,
			 0 AS Tax,
			 B.DocumentAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  B.DeptTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  B.DeptId DepartmentId,
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'DEBIT NOTE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note / Bill Level Discount'						AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
				 
		FROM    sOrderEntry.tBillingDetail BD
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate,
									DN.Amount DocumentAmount, DN.DeptTitle DeptTitle, DN.DeptId DeptId
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT DN.BillingId, DND.OrganizationDepartmentId, DN.Number,
										DN.RoundOffAmount Amount, DN.CreatedDateTime, ODM.Title DeptTitle, ODM.Id DeptId 
											 FROM sNotes.tDebitNote DN
												INNER JOIN sNotes.tDebitNoteDetail DND
													ON DND.DebitNoteId = DN.Id
												LEFT JOIN sSetup.tDepartmentMaster ODM
										ON DND.OrganizationDepartmentId = ODM.Id) DN
									ON DN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
				
			
				
				--LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
				--					OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
				--				FROM sOrderEntry.tOrderEntry OE
				--					INNER JOIN sSetup.tDepartmentMaster ODM
				--						ON OE.ServiceOrganizationDepartmentId = ODM.Id
				--			)OE
				--		ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle, StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
						
				--WHERE	((B.DNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
				--WHERE	((B.DNDate >= @rFromDate AND B.DNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
				WHERE	((B.DNDate >= @rFromDate AND B.DNDate <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((B.DeptTitle >= @rFromDept AND B.DeptTitle <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
	UNION ALL

	SELECT DISTINCT
				POS.Number AS DocNo, 
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 0 AS Quantity,
				 SUM(POS.Quantity * POS.UnitPrice) AS Amount,
				 SUM(POS.ItemLevelDiscount) AS Discount,
				 0 AS BillLevelDiscount,
				 SUM(POS.TaxAmount) AS Tax,
				 SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount) AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  ODM.Title AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  ODM.Id DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'POINT OF SALE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note / Bill Level Discount'						AS TransactionType,
			--POS.Id AS LineItemId		
			0 AS LineItemId		 
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
			GROUP BY POS.Number,
			POS.CreatedDateTime,
			vRPD.PatientNumber,
			vRPD.ServiceChargeTypeTitle,
			vRPD.PatientName,
			ODM.Title,
			ODM.Id,
			POS.Id
			
	UNION ALL

	SELECT	 DISTINCT
				 B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 0 AS Quantity,
				 0 AS Amount,
				 0 AS Discount,
				 B.DiscountAmount AS BillLevelDiscount,
				 0 AS Tax,
				 -B.DiscountAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  --OE.ODMTitle AS DepartmentTitle,
				  ''  AS DepartmentTitle,
				  'BILL LEVEL DISCOUNTS' AS DiscountForGrouping,
				  0 DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  '' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note / Bill Level Discount'						AS TransactionType,
			B.Id AS LineItemId
				 
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				RIGHT JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
	
	UNION ALL

	SELECT		DISTINCT
				 POS.Number AS DocNo, 
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				
				 0 AS Quantity,
				 0 AS Amount,
				 0 AS Discount,
				 POSHeader.DiscountAmount AS BillLevelDiscount,
				 0 AS Tax,
				 -POSHeader.DiscountAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  
				  ''  AS DepartmentTitle,
				  'BILL LEVEL DISCOUNTS' AS DiscountForGrouping,
				  0 DepartmentId, 
				  
				  '' AS ServiceDescription,
				  '' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note / Bill Level Discount'						AS TransactionType,
			--POS.Id AS LineItemId
			0 AS LineItemId
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sPharmacy.vExtPointOfSale POSHeader
			ON POSHeader.Id = POS.PointOfSaleId
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id 
						
			
			WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
	END
	ELSE IF (@rCreditNote = 0 AND @rDebitNote = 0 AND @rBillLevelDiscounts = 0)
	BEGIN
		SELECT DISTINCT
				B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 OE.Quantity AS Quantity,
				 BD.Amount AS Amount,
				 BD.DiscountAmount AS Discount,
				 0 AS BillLevelDiscount,
				 BD.TaxAmount AS Tax,
				 (BD.Amount + BD.TaxAmount - BD.DiscountAmount)AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  OE.ODMTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  OE.DeptId DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems,
				  ISNULL(UPPER(SM.SITMTitle), UPPER(ISNULL(StockMaster.SITMTitle, CON.SITMTitle))) AS ServiceDescription,
				  ISNULL(UPPER(SM.SITMCodeTitle), UPPER(ISNULL(StockMaster.SITMCodeTitle, CON.ConsCodeTitle))) AS ServiceItemcodeName,
				  ISNULL(UPPER(SM.SMTitle), UPPER(ISNULL(StockMaster.SMTitle, CON.ConsTitle))) AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  ''													AS TransactionType,
			BD.Id AS LineItemId			 
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
								FROM sOrderEntry.tServiceMaster SM
									INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
										ON 	SITM.Id = SM.ServiceItemTypeId) SM	
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
								FROM sIp.vExtStockItemMaster StockMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
								FROM sConsignment.vExtItemMaster ConsMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
						ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
	UNION ALL
	
	SELECT DISTINCT
				POS.Number AS DocNo, 
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 0 AS Quantity,
				 SUM(POS.Quantity * POS.UnitPrice) AS Amount,
				 SUM(POS.ItemLevelDiscount) AS Discount,
				 0 AS BillLevelDiscount,
				 SUM(POS.TaxAmount) AS Tax,
				 SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount) AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  ODM.Title AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  ODM.Id DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'POINT OF SALE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  ''													AS TransactionType,
			--POS.Id AS LineItemId
			0 AS LineItemId
				 
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
			GROUP BY POS.Number,
			POS.CreatedDateTime,
			vRPD.PatientNumber,
			vRPD.ServiceChargeTypeTitle,
			vRPD.PatientName,
			ODM.Title,
			ODM.Id,
			POS.Id
	END
	ELSE IF (@rCreditNote = 1 AND @rDebitNote = 1 AND @rBillLevelDiscounts = 0)
	BEGIN
		SELECT DISTINCT
				B.BillNumber AS DocNo, 
				 B.CreatedDateTime AS DocDateTime, 
				-- (CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType, 
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				 ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 OE.Quantity AS Quantity,
				 BD.Amount AS Amount,
				 BD.DiscountAmount AS Discount,
				 0 AS BillLevelDiscount,
				 BD.TaxAmount AS Tax,
				 (BD.Amount + BD.TaxAmount - BD.DiscountAmount)AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
						  
				  OE.ODMTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  OE.DeptId DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems,
				  ISNULL(UPPER(SM.SITMTitle), UPPER(ISNULL(StockMaster.SITMTitle, CON.SITMTitle))) AS ServiceDescription,
				  ISNULL(UPPER(SM.SITMCodeTitle), UPPER(ISNULL(StockMaster.SITMCodeTitle, CON.ConsCodeTitle))) AS ServiceItemcodeName,
				  ISNULL(UPPER(SM.SMTitle), UPPER(ISNULL(StockMaster.SMTitle, CON.ConsTitle))) AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note'								AS TransactionType,
			BD.Id AS LineItemId			 
				 
		FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
								FROM sOrderEntry.tServiceMaster SM
									INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
										ON 	SITM.Id = SM.ServiceItemTypeId) SM	
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle,  StockMaster.Id
								FROM sIp.vExtStockItemMaster StockMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
								FROM sConsignment.vExtItemMaster ConsMaster
									INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
										ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
						ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
				
						
		--WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		
		--WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
		WHERE	((B.CreatedDateTime >= @rFromDate AND B.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ASCII(OE.ODMTitle) >= ASCII(@rFromDept) AND ASCII(OE.ODMTitle) <= ASCII(@rToDept)) 
			OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
	UNION ALL
	
	SELECT	DISTINCT	
				B.CNNumber AS DocNo, 
				B.CNDate AS DocDateTime,
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientNumber, '')
				--	ELSE 
				--		ISNULL(B.CMCode, '')
				--	END
				--) AS Pid,
				ISNULL(B.vRPDPatientNumber, '') AS Pid,
				B.PatientType AS PatientType,
				--(CASE 
	 		--		WHEN B.DebtorTypeID = 1 THEN 
				--		ISNULL(B.vRPDPatientName, '')
				--	ELSE 
				--		ISNULL(B.CMTitle, '')
				--	END
				--) AS PatientName,
				ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 1 AS Quantity,
				 -B.DocumentAmount AS Amount,
				 0 AS BillLevelDiscount,
				 0 AS Discount,
				 0 AS Tax,
				 -B.DocumentAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  B.DeptTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  B.DeptId DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'CREDIT NOTE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note'								AS TransactionType,
			--BD.Id AS LineItemId		
			0 AS LineItemId	 
				 
		FROM    sOrderEntry.tBillingDetail BD
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate,
									CN.Amount DocumentAmount, CN.DeptTitle DeptTitle, CN.DeptId DeptId
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT CN.BillingId, CND.OrganizationDepartmentId, CN.Number,
										CN.RoundOffAmount Amount, CN.CreatedDateTime, ODM.Title DeptTitle, ODM.Id DeptId 
											 FROM sNotes.tCreditNote CN
												INNER JOIN sNotes.tCreditNoteDetail CND
													ON CND.CreditNoteId = CN.Id
												INNER JOIN sSetup.tDepartmentMaster ODM
										ON CND.OrganizationDepartmentId = ODM.Id) CN
									ON CN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
				
				
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, 
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId
								FROM sOrderEntry.tOrderEntry OE
									--INNER JOIN sSetup.tDepartmentMaster ODM
									--	ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle, StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((B.DeptTitle >= @rFromDept AND B.DeptTitle <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
						
						UNION ALL
						
	SELECT DISTINCT
			 B.DNNumber AS DocNo, 
			 B.DNDate AS DocDateTime,
			--(CASE 
	 	--			WHEN B.DebtorTypeID = 1 THEN 
			--			ISNULL(B.vRPDPatientNumber, '')
			--		ELSE 
			--			ISNULL(B.CMCode, '')
			--		END
			--) AS Pid,
			ISNULL(B.vRPDPatientNumber, '') AS Pid,
			B.PatientType AS PatientType,
			--(CASE 
	 	--			WHEN B.DebtorTypeID = 1 THEN 
			--			ISNULL(B.vRPDPatientName, '')
			--		ELSE 
			--			ISNULL(B.CMTitle, '')
			--		END
			--) AS PatientName,
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
			 --OE.Quantity AS Quantity,
			 1 AS Quantity,
			 B.DocumentAmount AS Amount,
			 0 AS Discount,
			 0 AS BillLevelDiscount,
			 0 AS Tax,
			 B.DocumentAmount AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  B.DeptTitle AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  B.DeptId DepartmentId,
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'DEBIT NOTE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note'								AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
				 
		FROM    sOrderEntry.tBillingDetail BD
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate,
									DN.Amount DocumentAmount, DN.DeptTitle DeptTitle, DN.DeptId DeptId
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT DN.BillingId, DND.OrganizationDepartmentId, DN.Number,
										DN.RoundOffAmount Amount, DN.CreatedDateTime, ODM.Title DeptTitle, ODM.Id DeptId 
											 FROM sNotes.tDebitNote DN
												INNER JOIN sNotes.tDebitNoteDetail DND
													ON DND.DebitNoteId = DN.Id
												LEFT JOIN sSetup.tDepartmentMaster ODM
										ON DND.OrganizationDepartmentId = ODM.Id) DN
									ON DN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id										
							
							) B
							ON BD.BillingId  = B.Id
				
			
				
				LEFT JOIN	(SELECT OE.RegistrationId, OE.Id, OE.ServiceOrganizationDepartmentId, ODM.Title ODMTitle,
									OE.Quantity, OE.TaxAmount, OE.ItemSourceId, OE.ItemSourceTypeId, ODM.Id DeptId
								FROM sOrderEntry.tOrderEntry OE
									INNER JOIN sSetup.tDepartmentMaster ODM
										ON OE.ServiceOrganizationDepartmentId = ODM.Id
							)OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				--LEFT JOIN  (SELECT SM.Title SMTitle, SITM.Title SITMTitle, SM.Code + ', ' + SM.Title SITMCodeTitle, SM.Id
				--				FROM sOrderEntry.tServiceMaster SM
				--					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
				--						ON 	SITM.Id = SM.ServiceItemTypeId) SM	
				--		ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				--LEFT JOIN (SELECT StockMaster.Title SMTitle, SItemMaster.Title SITMTitle, StockMaster.Code + ', ' + StockMaster.Title SITMCodeTitle, StockMaster.Id
				--				FROM sIp.vExtStockItemMaster StockMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = StockMaster.StockItemTypeId) StockMaster
				--		ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				--LEFT JOIN (SELECT ConsMaster.Title ConsTitle, SItemMaster.Title SITMTitle, ConsMaster.Code + ', ' + ConsMaster.Title ConsCodeTitle,  ConsMaster.Id
				--				FROM sConsignment.vExtItemMaster ConsMaster
				--					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				--						ON 	SItemMaster.Id = ConsMaster.StockItemTypeId) CON
				--		ON OE.ItemSourceId = CON.Id AND OE.ItemSourceTypeId = 90
						
				--WHERE	((B.DNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
				--WHERE	((B.DNDate >= @rFromDate AND B.DNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
				WHERE	((B.DNDate >= @rFromDate AND B.DNDate <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((B.DeptTitle >= @rFromDept AND B.DeptTitle <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
	UNION ALL

	SELECT		DISTINCT
				POS.Number AS DocNo,
				POS.CreatedDateTime AS DocDateTime,
				
				ISNULL(vRPD.PatientNumber, '') AS Pid,
				vRPD.ServiceChargeTypeTitle AS PatientType,
				
				ISNULL(UPPER(vRPD.PatientName), '') AS PatientName,
				 --OE.Quantity AS Quantity,
				 0 AS Quantity,
				 SUM(POS.Quantity * POS.UnitPrice) AS Amount,
				 SUM(POS.ItemLevelDiscount) AS Discount,
				 0 AS BillLevelDiscount,
				 SUM(POS.TaxAmount) AS Tax,
				 SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount) AS Net,
				 
				 (CASE @rFromDate
					WHEN '1900/1/1' THEN
						'1900/1/1'
					ELSE
						@rFromDate	
					END
					) AS DateFrom,
				 (CASE @rToDate
					WHEN '1900/1/1' THEN
						sCommon.fGetDate()
					ELSE
						@rToDate	
					END
					) AS DateTo,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rFromDept
					END
				  )AS FromDepartment,
				 (CASE 
					WHEN @rFromDept = '' OR @rToDept = '' THEN
						'ALL'
					ELSE
						@rToDept
					END
				  ) AS ToDepartment,
				  
				  ODM.Title AS DepartmentTitle,
				  '' AS DiscountForGrouping,
				  ODM.Id DepartmentId, 
				  --ISNULL(UPPER(SM.SITMTitle), UPPER(StockMaster.SITMTitle)) AS ServiceDescription,
				  --ISNULL(UPPER(SM.SITMCodeTitle), UPPER(StockMaster.SITMCodeTitle)) AS ServiceItemcodeName, 
				  --ISNULL(UPPER(SM.SMTitle), UPPER(StockMaster.SMTitle)) AS ServiceItems
				  '' AS ServiceDescription,
				  'POINT OF SALE' AS ServiceItemcodeName, 
				  '' AS ServiceItems,
				  @rStatus												AS SummaryOrDetail,
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note'								AS TransactionType,
			--POS.Id AS LineItemId
			0 AS LineItemId				 
				 
		FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
						
			--WHERE	((B.CNDate BETWEEN @rFromDate AND @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			--WHERE	((B.CNDate >= @rFromDate AND B.CNDate <= @rToDate) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			WHERE	((POS.CreatedDateTime >= @rFromDate AND POS.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			AND	((ODM.Title >= @rFromDept AND ODM.Title <= @rToDept) OR ((ISNULL(@rFromDept, '') = '')) OR (ISNULL(@rToDept, '') = ''))
			
			GROUP BY POS.Number,
			POS.CreatedDateTime,
			vRPD.PatientNumber,
			vRPD.ServiceChargeTypeTitle,
			vRPD.PatientName,
			ODM.Title,
			ODM.Id,
			POS.Id

END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pRptServiceItemListing]
	@rFromDate [datetime],
	@rToDate [datetime],
	@rItemType [int] = 0,
	@rServiceMainGroup [int] = 0,
	@rFromItemName [int] = 0,
	@rToItemName [int] = 0,
	@rStatus [int] = 0,
	@rCreditNote [int] = 1,
	@rDebitNote [int] = 1,
	@rBillLevelDiscounts [int] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN

DECLARE @lItemTypeId		Int = 0,
		@lItemTitle			nVarchar(20) = ''
		
(SELECT @lItemTypeId = ISM.Id FROM sFinanceCommon.tItemSourceMaster ISM WHERE ISM.Id = @rItemType)
(SELECT @lItemTitle = ISM.Title FROM sFinanceCommon.tItemSourceMaster ISM WHERE ISM.Id = @rItemType)



DECLARE @lTtempTable Table(Id INT, vRPDId INT, BRegId INT, BillNumber NVARCHAR(20), CreatedDateTime DATETIME,
						vRPDPatientNumber NVARCHAR(20), DebtorTypeID TINYINT, vRPDPatientName NVARCHAR(302),
						PatientType NVARCHAR(10), CMCode NVARCHAR(10), CMTitle NVARCHAR(100),
						DiscountAmount Decimal(22,6))

INSERT INTO @lTtempTable
SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber,
			B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID,
			vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType,
			CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
			
	FROM sOrderEntry.tBilling B
	INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  B.RegistrationId = vRPD.Id
	LEFT JOIN sOrderEntry.tDebtorRegistration DR
			ON B.RegistrationId = DR.RegistrationId
	LEFT JOIN	sOrderEntry.tCorporateMaster CM
			ON	DR.CorporateId = CM.Id
	WHERE ((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
			
			
IF (@rCreditNote = 1 AND @rDebitNote = 1 AND @rBillLevelDiscounts = 1)
BEGIN
	SELECT	DISTINCT  B.BillNumber									AS DocNo,
			B.CreatedDateTime								AS DocDate,
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid,
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
			B.PatientType AS PatientType,
			OE.Quantity										AS Quantity,
			BD.Amount										AS Amount,
			BD.DiscountAmount								AS Discount,
			0								AS BillLevelDuiscount,
			BD.TaxAmount									AS Tax,
			BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net,
			'' AS DiscountForGrouping,
			ISNULL(UPPER(SITM.Title), '')	AS ServiceMainGroupTitle,
			ISNULL(UPPER(SM.Title), '') AS ServiceTitle,
			ISNULL(UPPER(SITM.Code), '') AS ServiceMainGroupCode,
			ISNULL(UPPER(SM.Code), '') 	AS ServiceCode,
		 	
	 		(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,
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName,
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName,
					  @rStatus												AS SummaryOrDetail,
					  @rCreditNote											AS DisplayCreditNote,
					  @rDebitNote											AS DisplayDebitNote,
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts,
					  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			BD.Id AS LineItemId
					  
		 		 	
	 		FROM    sOrderEntry.tBillingDetail BD
					
					INNER JOIN 	(
								SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle,  DiscountAmount			
								FROM						
								@lTtempTable B
										WHERE
										--(CAST(B.CreatedDateTime AS DATE) BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE)) 
										--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
										((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
							) B
					
								ON BD.BillingId  = B.Id	
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sOrderEntry.tServiceMaster SM
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
						ON 	SITM.Id = SM.ServiceItemTypeId					
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((SM.Id > =  (@rFromItemName)) AND ((SM.Id) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND ((SITM.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	UNION ALL
	
	--STOCKITEM
	SELECT DISTINCT B.BillNumber									AS DocNo, 
			B.CreatedDateTime								AS DocDate, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
			B.PatientType AS PatientType, 
			OE.Quantity										AS Quantity, 
			BD.Amount										AS Amount, 
			BD.DiscountAmount								AS Discount, 
			0								AS BillLevelDuiscount, 
			BD.TaxAmount									AS Tax, 
			BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
			'' AS DiscountForGrouping, 
			UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
			UPPER(StockMaster.Title) AS ServiceTitle, 
			UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
			UPPER(StockMaster.Code) 	AS ServiceCode, 
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			BD.Id AS LineItemId
					  
		 		 	
	 		FROM    sOrderEntry.tBillingDetail BD
					
					--INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
					--					B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
					--					vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
					--					CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
										
					--			FROM sOrderEntry.tBilling B
					--			INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
					--					ON  B.RegistrationId = vRPD.Id
					--			LEFT JOIN sOrderEntry.tDebtorRegistration DR
					--					ON B.RegistrationId = DR.RegistrationId
					--			LEFT JOIN	sOrderEntry.tCorporateMaster CM
					--					ON	DR.CorporateId = CM.Id
					--					WHERE		
					--					((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

					--		) B
					INNER JOIN (
						SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
								FROM						
								@lTtempTable B WHERE		
								((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
					) B ON BD.BillingId  = B.Id
								
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sIp.vExtStockItemMaster StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
						ON 	SItemMaster.Id = StockMaster.StockItemTypeId							
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND ((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	UNION ALL
	
	-- Consignment Item
	SELECT DISTINCT B.BillNumber									AS DocNo, 
			B.CreatedDateTime								AS DocDate, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
			B.PatientType AS PatientType, 
			OE.Quantity										AS Quantity, 
			BD.Amount										AS Amount, 
			BD.DiscountAmount								AS Discount, 
			0								AS BillLevelDuiscount, 
			BD.TaxAmount									AS Tax, 
			BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
			'' AS DiscountForGrouping, 
			ISNULL(UPPER(SITM.Title), '')	AS ServiceMainGroupTitle, 
			ISNULL(UPPER(SM.Title), '') AS ServiceTitle, 
			ISNULL(UPPER(SITM.Code), '') AS ServiceMainGroupCode, 
			ISNULL(UPPER(SM.Code), '') 	AS ServiceCode, 
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			BD.Id AS LineItemId
					  
		 		 	
	 		FROM    sOrderEntry.tBillingDetail BD
					
					INNER JOIN 	(
								SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle,  DiscountAmount			
								FROM						
								@lTtempTable B
										WHERE
										--(CAST(B.CreatedDateTime AS DATE) BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE)) 
										--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
										((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
							) B
					
								ON BD.BillingId  = B.Id	
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sConsignment.vExtItemMaster SM
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 90 
					INNER JOIN sIp.vExtStockItemTypeMaster SITM
						ON 	SITM.Id = SM.StockItemTypeId					
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((SM.Id > =  (@rFromItemName)) AND ((SM.Id) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND ((SITM.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	UNION ALL
	
	-- CN 
	SELECT	 DISTINCT B.CNNumber									AS DocNo, 
			B.CNDate									AS DocDate, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
			B.PatientType AS PatientType, 
			--OE.Quantity										AS Quantity, 
			1												AS Quantity, 
			-B.DocumentAmount								AS Amount, 
			0												AS Discount, 
			0												AS BillLevelDuiscount, 
			0												AS Tax, 
			-B.DocumentAmount								AS Net, 
			--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
			--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
			--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
			--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
			'' AS DiscountForGrouping, 
			'CREDIT NOTE'	AS ServiceMainGroupTitle, 
			'' AS ServiceTitle, 
			'CN' AS ServiceMainGroupCode, 
			'' 	AS ServiceCode, 
		 	
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
			
	 		FROM    sOrderEntry.tBillingDetail BD
					
					INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
										B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
										vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
										CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate, 
										CN.Amount DocumentAmount
										
								FROM sOrderEntry.tBilling B
								INNER JOIN (SELECT CN.Number, CN.CreatedDateTime, SUM(CN.RoundOffAmount) Amount, CN.BillingId
											FROM sNotes.tCreditNote CN
												INNER JOIN sNotes.tCreditNoteDetail CND
													ON CND.CreditNoteId = CN.Id
													WHERE ((CN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
													GROUP BY CN.Number, CN.CreatedDateTime, CN.BillingId) CN
										ON CN.BillingId = B.Id
								INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
										ON  B.RegistrationId = vRPD.Id
								LEFT JOIN sOrderEntry.tDebtorRegistration DR
										ON B.RegistrationId = DR.RegistrationId
								LEFT JOIN	sOrderEntry.tCorporateMaster CM
										ON	DR.CorporateId = CM.Id
										WHERE		((CN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
										--WHERE		(CAST(CN.CreatedDateTime AS DATE) BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE)) 
										--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
							) B
								ON BD.BillingId  = B.Id
								
								
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sOrderEntry.tServiceMaster SM
						ON 	OE.ItemSourceId = SM.Id
					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
						ON 	SITM.Id = SM.ServiceItemTypeId
					LEFT JOIN sIp.vExtStockItemMaster StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id
					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
						ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	WHERE		((B.CNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((SM.Id > =  (@rFromItemName)) AND ((SM.Id < =  (@rToItemName)))
				OR (@rFromItemName = 0) OR (@rToItemName = 0)))
	AND ((SITM.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	--UNION ALL

	-- CN STOCK ITEM
	--SELECT	 DISTINCT B.CNNumber									AS DocNo, 
	--		B.CNDate									AS DocDate, 
	--		--(CASE 
	--	 --				WHEN B.DebtorTypeID = 1 THEN 
	--		--				ISNULL(B.vRPDPatientNumber, '')
	--		--			ELSE 
	--		--				ISNULL(B.CMCode, '')
	--		--			END
	--		--)												AS Pid, 
	--		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--		--(CASE 
	--	 --				WHEN B.DebtorTypeID = 1 THEN 
	--		--				ISNULL(B.vRPDPatientName, '')
	--		--			ELSE 
	--		--				ISNULL(B.CMTitle, '')
	--		--			END
	--		--)												AS PatientName, 
	--		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--		B.PatientType AS PatientType, 
	--		--OE.Quantity										AS Quantity, 
	--		1												AS Quantity, 
	--		-B.DocumentAmount								AS Amount, 
	--		0												AS Discount, 
	--		0												AS BillLevelDuiscount, 
	--		0												AS Tax, 
	--		-B.DocumentAmount								AS Net, 
	--		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--		'' AS DiscountForGrouping, 
	--		'CREDIT NOTE'	AS ServiceMainGroupTitle, 
	--		'' AS ServiceTitle, 
	--		'CN' AS ServiceMainGroupCode, 
	--		'' 	AS ServiceCode, 
		 	
		 	
	-- 		(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, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 				'ALL'
	-- 			ELSE 
	-- 				@lItemTitle
	-- 			END
	-- 		 )												AS ItemType, 
		 	 
	-- 		(CASE 
	-- 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE 
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 				ELSE
	-- 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 				END
	-- 			END
	-- 		 )												AS MainGroup, 
		 	 
	-- 		(CASE 
	-- 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 				ELSE
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 				END
	-- 			END
	-- 		)												AS FromItemName, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 				ELSE
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 				END
	-- 			END
	-- 		)												AS ToItemName, 
	--				  @rStatus												AS SummaryOrDetail, 
	--				  @rCreditNote											AS DisplayCreditNote, 
	--				  @rDebitNote											AS DisplayDebitNote, 
	--				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--				  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType
	-- 		FROM    sOrderEntry.tBillingDetail BD
					
	--				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--									CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate, 
	--									CN.Amount DocumentAmount
										
	--							FROM sOrderEntry.tBilling B
	--							INNER JOIN (SELECT CN.Number, CN.CreatedDateTime, SUM(CN.RoundOffAmount) Amount, CN.BillingId
	--										FROM sNotes.tCreditNote CN
	--											INNER JOIN sNotes.tCreditNoteDetail CND
	--												ON CND.CreditNoteId = CN.Id
	--												WHERE ((CN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--												GROUP BY CN.Number, CN.CreatedDateTime, CN.BillingId) CN
	--									ON CN.BillingId = B.Id
	--							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--									ON  B.RegistrationId = vRPD.Id
	--							LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--									ON B.RegistrationId = DR.RegistrationId
	--							LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--									ON	DR.CorporateId = CM.Id
	--									WHERE		((CN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--									--WHERE		(CAST(CN.CreatedDateTime AS DATE) BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE)) 
	--									--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--						) B
	--							ON BD.BillingId  = B.Id
								
	--				LEFT JOIN sOrderEntry.tOrderEntry OE
	--					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--				INNER JOIN sSetup.tDepartmentMaster ODM
	--					ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--				LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	--WHERE		((B.CNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND ((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	-- DN SERVICE ITEM
	SELECT	 DISTINCT B.DNNumber									AS DocNo, 
			B.DNDate								AS DocDate, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
			B.PatientType AS PatientType, 
			--OE.Quantity										AS Quantity, 
			1												AS Quantity, 
			B.DocumentAmount								AS Amount, 
			0												AS Discount, 
			0												AS BillLevelDuiscount, 
			0												AS Tax, 
			B.DocumentAmount						AS Net, 
			--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
			--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
			--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
			--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
			'' AS DiscountForGrouping, 
			'DEBIT NOTE'	AS ServiceMainGroupTitle, 
			'' AS ServiceTitle, 
			'DN' AS ServiceMainGroupCode, 
			'' 	AS ServiceCode, 	 	
		 	
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName,  
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
		 	
	 		FROM    sOrderEntry.tBillingDetail BD
					
					INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
										B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
										vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
										CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate, 
										DN.Amount DocumentAmount
										
								FROM sOrderEntry.tBilling B
								INNER JOIN (SELECT DN.Number, DN.CreatedDateTime, SUM(DN.RoundOffAmount) Amount, DN.BillingId
											FROM sNotes.tDebitNote DN
												INNER JOIN sNotes.tDebitNoteDetail DND
													ON DND.DebitNoteId = DN.Id
													WHERE		((DN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
													GROUP BY DN.Number, DN.CreatedDateTime, DN.BillingId) DN
										ON DN.BillingId = B.Id
								INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
										ON  B.RegistrationId = vRPD.Id
								LEFT JOIN sOrderEntry.tDebtorRegistration DR
										ON B.RegistrationId = DR.RegistrationId
								LEFT JOIN	sOrderEntry.tCorporateMaster CM
										ON	DR.CorporateId = CM.Id
										WHERE		((DN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
										--WHERE		(CAST(DN.CreatedDateTime AS DATE) BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE)) 
										--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))


							) B
								ON BD.BillingId  = B.Id
								
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sOrderEntry.tServiceMaster SM
						ON 	OE.ItemSourceId = SM.Id
					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
						ON 	SITM.Id = SM.ServiceItemTypeId
					LEFT JOIN sIp.vExtStockItemMaster StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id
					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
						ON 	SItemMaster.Id = StockMaster.StockItemTypeId		
	WHERE		((B.DNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((SM.Id > =  @rFromItemName) AND (SM.Id < =  @rToItemName))
				OR (@rFromItemName = 0) OR (@rToItemName = 0))
	AND ((SITM.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	
	-- DN STOCK ITEM
	
	--SELECT	 DISTINCT B.DNNumber									AS DocNo, 
	--		B.DNDate								AS DocDate, 
	--		--(CASE 
	--	 --				WHEN B.DebtorTypeID = 1 THEN 
	--		--				ISNULL(B.vRPDPatientNumber, '')
	--		--			ELSE 
	--		--				ISNULL(B.CMCode, '')
	--		--			END
	--		--)												AS Pid, 
	--		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--		--(CASE 
	--	 --				WHEN B.DebtorTypeID = 1 THEN 
	--		--				ISNULL(B.vRPDPatientName, '')
	--		--			ELSE 
	--		--				ISNULL(B.CMTitle, '')
	--		--			END
	--		--)												AS PatientName, 
	--		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--		B.PatientType AS PatientType, 
	--		--OE.Quantity										AS Quantity, 
	--		1												AS Quantity, 
	--		B.DocumentAmount								AS Amount, 
	--		0												AS Discount, 
	--		0												AS BillLevelDuiscount, 
	--		0												AS Tax, 
	--		B.DocumentAmount						AS Net, 
	--		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--		'' AS DiscountForGrouping, 
	--		'DEBIT NOTE'	AS ServiceMainGroupTitle, 
	--		'' AS ServiceTitle, 
	--		'DN' AS ServiceMainGroupCode, 
	--		'' 	AS ServiceCode, 	 	
		 	
		 	
	-- 		(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, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 				'ALL'
	-- 			ELSE 
	-- 				@lItemTitle
	-- 			END
	-- 		 )												AS ItemType, 
		 	 
	-- 		(CASE 
	-- 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE 
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 				ELSE
	-- 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 				END
	-- 			END
	-- 		 )												AS MainGroup, 
		 	 
	-- 		(CASE 
	-- 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 				ELSE
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 				END
	-- 			END
	-- 		)												AS FromItemName, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 				ELSE
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 				END
	-- 			END
	-- 		)												AS ToItemName, 
	--				  @rStatus												AS SummaryOrDetail, 
	--				  @rCreditNote											AS DisplayCreditNote, 
	--				  @rDebitNote											AS DisplayDebitNote, 
	--				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--				  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType
		 	
	-- 		FROM    sOrderEntry.tBillingDetail BD
					
	--				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--									CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate, 
	--									DN.Amount DocumentAmount
										
	--							FROM sOrderEntry.tBilling B
	--							INNER JOIN (SELECT DN.Number, DN.CreatedDateTime, SUM(DN.RoundOffAmount) Amount, DN.BillingId
	--										FROM sNotes.tDebitNote DN
	--											INNER JOIN sNotes.tDebitNoteDetail DND
	--												ON DND.DebitNoteId = DN.Id
	--												WHERE		((DN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--												GROUP BY DN.Number, DN.CreatedDateTime, DN.BillingId) DN
	--									ON DN.BillingId = B.Id
	--							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--									ON  B.RegistrationId = vRPD.Id
	--							LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--									ON B.RegistrationId = DR.RegistrationId
	--							LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--									ON	DR.CorporateId = CM.Id
	--									WHERE		((DN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--									--WHERE		(CAST(DN.CreatedDateTime AS DATE) BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE)) 
	--									--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))


	--						) B
	--							ON BD.BillingId  = B.Id
								
	--				LEFT JOIN sOrderEntry.tOrderEntry OE
	--					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--				INNER JOIN sSetup.tDepartmentMaster ODM
	--					ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--				LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	--WHERE		((B.DNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND ((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	--UNION ALL


	SELECT	 DISTINCT POS.Number								AS DocNo, 
			POS.CreatedDateTime								AS DocDate, 
			
			ISNULL(vRPD.PatientNumber, '') AS Pid, 
			
			ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
			vRPD.ServiceChargeTypeTitle				 AS PatientType, 
			
			0												AS Quantity, 
			--B.POSQuantity									AS Quantity, 
			SUM(POS.Quantity * POS.UnitPrice)								AS Amount, 
			SUM(POS.ItemLevelDiscount)								AS Discount, 
			0							AS BillLevelDuiscount, 
			SUM(POS.TaxAmount)									AS Tax, 
			SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount)			AS Net, 
			
			'' AS DiscountForGrouping, 
			'POINT OF SALE'	AS ServiceMainGroupTitle, 
			'' AS ServiceTitle, 
			'POS' AS ServiceMainGroupCode, 
			'' 	AS ServiceCode, 
		 	
	 	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			--POS.Id AS LineItemId
			0 AS LineItemId
	FROM	sPharmacy.vExtPointOfSaleDetail POS
			INNER JOIN sIp.vExtStockItemMaster SIM
				ON POS.StockItemId = SIM.Id
			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				ON 	SItemMaster.Id = SIM.StockItemTypeId
			INNER JOIN sSetup.tDepartmentMaster ODM
				ON SIM.OrganizationDepartmentId = ODM.Id
			INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
				ON  POS.RegistrationId = vRPD.Id
			
			
	WHERE
	--		((POS.CreatedDateTime BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE))) 
	((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			(((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0)))

	GROUP BY
			POS.Number, 
			POS.CreatedDateTime, 
			vRPD.PatientNumber, 
			vRPD.PatientName, 
			vRPD.ServiceChargeTypeTitle,
			POS.Id
		
				
	UNION ALL
	-- BLD Service Item
	SELECT	 DISTINCT B.BillNumber									AS DocNo, 
			B.CreatedDateTime								AS DocDate, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
			B.PatientType AS PatientType, 
			0										AS Quantity, 
			0										AS Amount, 
			0								AS Discount, 
			B.DiscountAmount								AS BillLevelDuiscount, 
			0									AS Tax, 
			-B.DiscountAmount	AS Net, 
			--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
			--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
			--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
			--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
			'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
			''	AS ServiceMainGroupTitle, 
			'' AS ServiceTitle, 
			'' AS ServiceMainGroupCode, 
			'' 	AS ServiceCode, 
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			--B.Id AS LineItemId
		 	0 AS LineItemId
	 		FROM    sOrderEntry.tBillingDetail BD
					
					RIGHT JOIN 	(
					--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
					--					B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
					--					vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
					--					CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
										
					--			FROM sOrderEntry.tBilling B
					--			INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
					--					ON  B.RegistrationId = vRPD.Id
					--			LEFT JOIN sOrderEntry.tDebtorRegistration DR
					--					ON B.RegistrationId = DR.RegistrationId
					--			LEFT JOIN	sOrderEntry.tCorporateMaster CM
					--					ON	DR.CorporateId = CM.Id
					
					SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
								FROM						
								@lTtempTable B
										WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
										--WHERE		(CAST(B.CreatedDateTime AS DATE) BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE)) 
										--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))


							) B
								ON BD.BillingId  = B.Id
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sOrderEntry.tServiceMaster SM
						ON 	OE.ItemSourceId = SM.Id -- AND OE.ItemSourceTypeId = 25 
					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
						ON 	SITM.Id = SM.ServiceItemTypeId	
					LEFT JOIN sIp.vExtStockItemMaster StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id --AND OE.ItemSourceTypeId = 34
					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
						ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((SM.Id > =  (@rFromItemName)) AND ((SM.Id) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0)))

	UNION ALL
	
	-- BLD STOCK ITEM
	
	--SELECT	 DISTINCT B.BillNumber									AS DocNo, 
	--		B.CreatedDateTime								AS DocDate, 
	--		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--		B.PatientType AS PatientType, 
	--		0										AS Quantity, 
	--		0										AS Amount, 
	--		0								AS Discount, 
	--		B.DiscountAmount								AS BillLevelDuiscount, 
	--		0									AS Tax, 
	--		-B.DiscountAmount	AS Net, 
	--		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--		'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
	--		''	AS ServiceMainGroupTitle, 
	--		'' AS ServiceTitle, 
	--		'' AS ServiceMainGroupCode, 
	--		'' 	AS ServiceCode, 
		 	
	-- 		(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, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 				'ALL'
	-- 			ELSE 
	-- 				@lItemTitle
	-- 			END
	-- 		 )												AS ItemType, 
		 	 
	-- 		(CASE 
	-- 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE 
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 				ELSE
	-- 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 				END
	-- 			END
	-- 		 )												AS MainGroup, 
		 	 
	-- 		(CASE 
	-- 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	-- 				END
	-- 			END
	-- 		)												AS FromItemName, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	-- 				END
	-- 			END
	-- 		)												AS ToItemName, 
	--				  @rStatus												AS SummaryOrDetail, 
	--				  @rCreditNote											AS DisplayCreditNote, 
	--				  @rDebitNote											AS DisplayDebitNote, 
	--				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--				  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
	--		BD.Id AS LineItemId
		 		 	
	-- 		FROM    sOrderEntry.tBillingDetail BD
					
	--				INNER JOIN 	(
					
	--							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
										
	--							--FROM sOrderEntry.tBilling B
	--							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--							--		ON  B.RegistrationId = vRPD.Id
	--							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--							--		ON B.RegistrationId = DR.RegistrationId
	--							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--							--		ON	DR.CorporateId = CM.Id
	--							SELECT Id, vRPDId, BRegId, BillNumber, 
	--									CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
	--									vRPDPatientName, PatientType, 
	--									CMCode, CMTitle, DiscountAmount			
	--							FROM						
	--							@lTtempTable B
	--									WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--									--WHERE		(CAST(B.CreatedDateTime AS DATE) BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE)) 
	--									--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))


	--						) B
	--							ON BD.BillingId  = B.Id
								
	--				LEFT JOIN sOrderEntry.tOrderEntry OE
	--					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--				INNER JOIN sSetup.tDepartmentMaster ODM
	--					ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--				LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	--WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0)))
	
	--UNION ALL
	---- Consignment Item
	--SELECT	 DISTINCT B.BillNumber									AS DocNo, 
	--		B.CreatedDateTime								AS DocDate, 
	--		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--		B.PatientType AS PatientType, 
	--		0										AS Quantity, 
	--		0										AS Amount, 
	--		0								AS Discount, 
	--		B.DiscountAmount								AS BillLevelDuiscount, 
	--		0									AS Tax, 
	--		-B.DiscountAmount	AS Net, 
	--		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--		'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
	--		''	AS ServiceMainGroupTitle, 
	--		'' AS ServiceTitle, 
	--		'' AS ServiceMainGroupCode, 
	--		'' 	AS ServiceCode, 
		 	
	-- 		(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, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 				'ALL'
	-- 			ELSE 
	-- 				@lItemTitle
	-- 			END
	-- 		 )												AS ItemType, 
		 	 
	-- 		(CASE 
	-- 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE 
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 				ELSE
	-- 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 				END
	-- 			END
	-- 		 )												AS MainGroup, 
		 	 
	-- 		(CASE 
	-- 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	-- 				END
	-- 			END
	-- 		)												AS FromItemName, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	-- 				END
	-- 			END
	-- 		)												AS ToItemName, 
	--				  @rStatus												AS SummaryOrDetail, 
	--				  @rCreditNote											AS DisplayCreditNote, 
	--				  @rDebitNote											AS DisplayDebitNote, 
	--				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--				  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
	--		BD.Id AS LineItemId
		 		 	
	-- 		FROM    sOrderEntry.tBillingDetail BD
					
	--				INNER JOIN 	(
					
	--							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
										
	--							--FROM sOrderEntry.tBilling B
	--							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--							--		ON  B.RegistrationId = vRPD.Id
	--							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--							--		ON B.RegistrationId = DR.RegistrationId
	--							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--							--		ON	DR.CorporateId = CM.Id
	--							SELECT Id, vRPDId, BRegId, BillNumber, 
	--									CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
	--									vRPDPatientName, PatientType, 
	--									CMCode, CMTitle, DiscountAmount			
	--							FROM						
	--							@lTtempTable B
	--									WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--									--WHERE		(CAST(B.CreatedDateTime AS DATE) BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE)) 
	--									--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))


	--						) B
	--							ON BD.BillingId  = B.Id
								
	--				LEFT JOIN sOrderEntry.tOrderEntry OE
	--					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--				INNER JOIN sSetup.tDepartmentMaster ODM
	--					ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--				LEFT JOIN sConsignment.vExtItemMaster StockMaster
	--					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
	--				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	--WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0)))
	
	--UNION ALL
	
	SELECT	 DISTINCT POS.Number								AS DocNo, 
			POS.CreatedDateTime								AS DocDate, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(vRPD.PatientNumber, '') AS Pid, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
			vRPD.ServiceChargeTypeTitle AS PatientType, 
			--OE.Quantity										AS Quantity, 
			0									AS Quantity, 
			0								AS Amount, 
			0								AS Discount, 
			POSHeader.DiscountAmount								AS BillLevelDuiscount, 
			0									AS Tax, 
			-POSHeader.DiscountAmount			AS Net, 
			
			'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
			''	AS ServiceMainGroupTitle, 
			'' AS ServiceTitle, 
			'' AS ServiceMainGroupCode, 
			'' 	AS ServiceCode, 
		 	
		 	
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  'Credit Note / Debit Note / Bill Level Discount'			AS TransactionType,
			--POS.Id AS LineItemId
		 	0 AS LineItemId
	 		FROM	sPharmacy.vExtPointOfSaleDetail POS
	 		INNER JOIN sPharmacy.vExtPointOfSale POSHeader
				ON POSHeader.Id = POS.PointOfSaleId
			INNER JOIN sIp.vExtStockItemMaster SIM
				ON POS.StockItemId = SIM.Id
			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				ON 	SItemMaster.Id = SIM.StockItemTypeId
			INNER JOIN sSetup.tDepartmentMaster ODM
				ON SIM.OrganizationDepartmentId = ODM.Id
			INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
				ON  POS.RegistrationId = vRPD.Id
						
			
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--WHERE		((POS.CreatedDateTime BETWEEN CAST(@rFromDate AS DATE) AND CAST(@rToDate AS DATE))) 
	--OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			(((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0)))

		 		
		ORDER BY ServiceMainGroupTitle
END
ELSE IF (@rCreditNote = 0 AND @rDebitNote = 0 AND @rBillLevelDiscounts = 0)
BEGIN
	SELECT	DISTINCT  B.BillNumber									AS DocNo,
			B.CreatedDateTime								AS DocDate,
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName,
			B.PatientType AS PatientType,
			OE.Quantity										AS Quantity, 
			BD.Amount										AS Amount, 
			BD.DiscountAmount								AS Discount, 
			0								AS BillLevelDuiscount, 
			BD.TaxAmount									AS Tax, 
			BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
			'' AS DiscountForGrouping, 
			SITM.Title	AS ServiceMainGroupTitle, 
			SM.Title AS ServiceTitle, 
			SITM.Code AS ServiceMainGroupCode, 
			SM.Code	AS ServiceCode,
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  ''													AS TransactionType,
			BD.Id AS LineItemId
		 		 	
	 		FROM    sOrderEntry.tBillingDetail BD
					
					INNER JOIN 	(
						--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
						--				B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
						--				vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
						--				CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
										
						--		FROM sOrderEntry.tBilling B
						--		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
						--				ON  B.RegistrationId = vRPD.Id
						--		LEFT JOIN sOrderEntry.tDebtorRegistration DR
						--				ON B.RegistrationId = DR.RegistrationId
						--		LEFT JOIN	sOrderEntry.tCorporateMaster CM
						--				ON	DR.CorporateId = CM.Id
								SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
								FROM						
								@lTtempTable B
										WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

							) B
								ON BD.BillingId  = B.Id
								
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sOrderEntry.tServiceMaster SM
						ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
					INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
						ON 	SITM.Id = SM.ServiceItemTypeId
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((SM.Id > =  @rFromItemName) AND (SM.Id < =  @rToItemName))
				OR (@rFromItemName = 0) OR (@rToItemName = 0))
	AND ((SITM.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL
	--Stock Item
	SELECT DISTINCT B.BillNumber									AS DocNo, 
			B.CreatedDateTime								AS DocDate, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
			B.PatientType AS PatientType, 
			OE.Quantity										AS Quantity, 
			BD.Amount										AS Amount, 
			BD.DiscountAmount								AS Discount, 
			0								AS BillLevelDuiscount, 
			BD.TaxAmount									AS Tax, 
			BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
			'' AS DiscountForGrouping, 
			UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
			UPPER(StockMaster.Title) AS ServiceTitle, 
			UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
			UPPER(StockMaster.Code) 	AS ServiceCode, 
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  ''													AS TransactionType,
			BD.Id AS LineItemId
		 		 	
	 		FROM    sOrderEntry.tBillingDetail BD
					
					INNER JOIN 	(
								--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
								--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
								--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
								--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
										
								--FROM sOrderEntry.tBilling B
								--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
								--		ON  B.RegistrationId = vRPD.Id
								--LEFT JOIN sOrderEntry.tDebtorRegistration DR
								--		ON B.RegistrationId = DR.RegistrationId
								--LEFT JOIN	sOrderEntry.tCorporateMaster CM
								--		ON	DR.CorporateId = CM.Id
								SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
								FROM						
									@lTtempTable B
								WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
							) B
								ON BD.BillingId  = B.Id
								
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sIp.vExtStockItemMaster StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
						ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND ((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	--Consignment Item
	UNION ALL
	SELECT DISTINCT B.BillNumber									AS DocNo, 
			B.CreatedDateTime								AS DocDate, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
			B.PatientType AS PatientType, 
			OE.Quantity										AS Quantity, 
			BD.Amount										AS Amount, 
			BD.DiscountAmount								AS Discount, 
			0								AS BillLevelDuiscount, 
			BD.TaxAmount									AS Tax, 
			BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
			'' AS DiscountForGrouping, 
			UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
			UPPER(StockMaster.Title) AS ServiceTitle, 
			UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
			UPPER(StockMaster.Code) 	AS ServiceCode, 
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  ''													AS TransactionType,
			BD.Id AS LineItemId
		 		 	
	 		FROM    sOrderEntry.tBillingDetail BD
					
					INNER JOIN 	(
								--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
								--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
								--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
								--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
										
								--FROM sOrderEntry.tBilling B
								--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
								--		ON  B.RegistrationId = vRPD.Id
								--LEFT JOIN sOrderEntry.tDebtorRegistration DR
								--		ON B.RegistrationId = DR.RegistrationId
								--LEFT JOIN	sOrderEntry.tCorporateMaster CM
								--		ON	DR.CorporateId = CM.Id
								SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
								FROM						
									@lTtempTable B
								WHERE	((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
							) B
								ON BD.BillingId  = B.Id
								
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sConsignment.vExtItemMaster StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
						ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND ((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL

	SELECT	 DISTINCT POS.Number								AS DocNo, 
			POS.CreatedDateTime								AS DocDate, 
			
			ISNULL(vRPD.PatientNumber, '') AS Pid, 
			
			ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
			vRPD.ServiceChargeTypeTitle				 AS PatientType, 
			
			0												AS Quantity, 
			--B.POSQuantity									AS Quantity, 
			SUM(POS.Quantity * POS.UnitPrice)								AS Amount, 
			SUM(POS.ItemLevelDiscount)								AS Discount, 
			0							AS BillLevelDuiscount, 
			SUM(POS.TaxAmount)									AS Tax, 
			SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount)			AS Net, 
			
			'' AS DiscountForGrouping, 
			'POINT OF SALE'	AS ServiceMainGroupTitle, 
			'' AS ServiceTitle, 
			'POS' AS ServiceMainGroupCode, 
			'' 	AS ServiceCode, 
		 	
	 	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup,
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName,
					  @rStatus												AS SummaryOrDetail,
					  @rCreditNote											AS DisplayCreditNote,
					  @rDebitNote											AS DisplayDebitNote,
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts,
					  ''													AS TransactionType,
			--POS.Id AS LineItemId
		 	0 AS LineItemId				
	FROM	sPharmacy.vExtPointOfSaleDetail POS
			INNER JOIN sIp.vExtStockItemMaster SIM
				ON POS.StockItemId = SIM.Id
			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				ON 	SItemMaster.Id = SIM.StockItemTypeId
			INNER JOIN sSetup.tDepartmentMaster ODM
				ON SIM.OrganizationDepartmentId = ODM.Id
			INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
				ON  POS.RegistrationId = vRPD.Id
						
			
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

				
	GROUP BY
			POS.Number, 
			POS.CreatedDateTime, 
			vRPD.PatientNumber,
			vRPD.PatientName, 
			vRPD.ServiceChargeTypeTitle,
			POS.Id	

END
ELSE IF (@rCreditNote = 0 AND @rDebitNote = 0 AND @rBillLevelDiscounts = 1)
BEGIN
	SELECT	DISTINCT  B.BillNumber									AS DocNo,
		B.CreatedDateTime								AS DocDate,
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		SITM.Title AS ServiceMainGroupTitle, 
		SM.Title AS ServiceTitle, 
		SITM.Code AS ServiceMainGroupCode, 
		SM.Code AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Bill Level Discount'									AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
								SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
								FROM						
								@lTtempTable B
									WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((SM.Id > =  @rFromItemName) AND (SM.Id < =  @rToItemName))
				OR (@rFromItemName = 0) OR (@rToItemName = 0))
	AND ((SITM.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	-- Stock Item
	SELECT DISTINCT	  B.BillNumber									AS DocNo,
		B.CreatedDateTime								AS DocDate,
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
		UPPER(StockMaster.Title) AS ServiceTitle, 
		UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
		UPPER(StockMaster.Code) AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName,
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName,  
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note'											AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id
									WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	-- Consignment Item
	SELECT DISTINCT	  B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
		UPPER(StockMaster.Title) AS ServiceTitle, 
		UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
		UPPER(StockMaster.Code) AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName,  
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note'											AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id
									WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sConsignment.vExtItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	
	SELECT	 DISTINCT POS.Number								AS DocNo, 
		POS.CreatedDateTime								AS DocDate, 
		
		ISNULL(vRPD.PatientNumber, '') AS Pid, 
		
		ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
		vRPD.ServiceChargeTypeTitle				 AS PatientType, 
		
		0												AS Quantity, 
		--B.POSQuantity									AS Quantity, 
		SUM(POS.Quantity * POS.UnitPrice)								AS Amount, 
		SUM(POS.ItemLevelDiscount)								AS Discount, 
		0							AS BillLevelDuiscount, 
		SUM(POS.TaxAmount)									AS Tax, 
		SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount)			AS Net, 
		
		'' AS DiscountForGrouping, 
		'POINT OF SALE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'POS' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Bill Level Discount'									AS TransactionType,
			--POS.Id AS LineItemId
		 	0 AS LineItemId
	FROM	sPharmacy.vExtPointOfSaleDetail POS
			INNER JOIN sIp.vExtStockItemMaster SIM
				ON POS.StockItemId = SIM.Id
			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				ON 	SItemMaster.Id = SIM.StockItemTypeId
			INNER JOIN sSetup.tDepartmentMaster ODM
				ON SIM.OrganizationDepartmentId = ODM.Id
			INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
				ON  POS.RegistrationId = vRPD.Id
						
			
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

				
	GROUP BY
			POS.Number, 
			POS.CreatedDateTime, 
			vRPD.PatientNumber, 
			vRPD.PatientName, 
			vRPD.ServiceChargeTypeTitle,
			POS.Id
		
				
	UNION ALL

	SELECT	 DISTINCT B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		0										AS Quantity, 
		0										AS Amount,
		0								AS Discount,
		B.DiscountAmount								AS BillLevelDuiscount,
		0									AS Tax,
		-B.DiscountAmount	AS Net,
		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
		'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
		''	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Bill Level Discount'									AS TransactionType,
			--B.Id AS LineItemId
	 		0 AS LineItemId
	 	FROM    sOrderEntry.tBillingDetail BD
				
				RIGHT JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id --AND OE.ItemSourceTypeId = 25 
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id --AND OE.ItemSourceTypeId = 34
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
											
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((SM.Id > =  (@rFromItemName)) AND ((SM.Id) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND ((SITM.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	--UNION ALL
	----Stock item	
	--SELECT	 DISTINCT B.BillNumber									AS DocNo, 
	--	B.CreatedDateTime								AS DocDate, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	0										AS Quantity, 
	--	0										AS Amount, 
	--	0								AS Discount, 
	--	B.DiscountAmount								AS BillLevelDuiscount, 
	--	0									AS Tax, 
	--	-B.DiscountAmount	AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
	--	''	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	-- 				END
	-- 			END
	-- 		)												AS FromItemName, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	-- 				END
	-- 			END
	-- 		)												AS ToItemName,  
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Bill Level Discount'									AS TransactionType
	 		 	
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(
	--						--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--						--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--						--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--						--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
	--						--FROM sOrderEntry.tBilling B
	--						--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--						--		ON  B.RegistrationId = vRPD.Id
	--						--LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--						--		ON B.RegistrationId = DR.RegistrationId
	--						--LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--						--		ON	DR.CorporateId = CM.Id
							
	--						SELECT Id, vRPDId, BRegId, BillNumber, 
	--									CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
	--									vRPDPatientName, PatientType, 
	--									CMCode, CMTitle, DiscountAmount			
	--						FROM
	--							@lTtempTable B
	--						WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--					) B
	--						ON BD.BillingId  = B.Id
							
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	--WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND ((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	--UNION ALL
	----Consignment Item	
	--SELECT	 DISTINCT B.BillNumber									AS DocNo, 
	--	B.CreatedDateTime								AS DocDate, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	0										AS Quantity, 
	--	0										AS Amount, 
	--	0								AS Discount, 
	--	B.DiscountAmount								AS BillLevelDuiscount, 
	--	0									AS Tax, 
	--	-B.DiscountAmount	AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
	--	''	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	-- 				END
	-- 			END
	-- 		)												AS FromItemName, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	-- 				END
	-- 			END
	-- 		)												AS ToItemName,  
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Bill Level Discount'									AS TransactionType
	 		 	
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(
	--						--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--						--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--						--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--						--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
	--						--FROM sOrderEntry.tBilling B
	--						--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--						--		ON  B.RegistrationId = vRPD.Id
	--						--LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--						--		ON B.RegistrationId = DR.RegistrationId
	--						--LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--						--		ON	DR.CorporateId = CM.Id
							
	--						SELECT Id, vRPDId, BRegId, BillNumber, 
	--									CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
	--									vRPDPatientName, PatientType, 
	--									CMCode, CMTitle, DiscountAmount			
	--						FROM
	--							@lTtempTable B
	--						WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--					) B
	--						ON BD.BillingId  = B.Id
							
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sConsignment.vExtItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	--WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND ((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL

	SELECT	 DISTINCT POS.Number								AS DocNo, 
		POS.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(vRPD.PatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
		vRPD.ServiceChargeTypeTitle AS PatientType, 
		--OE.Quantity										AS Quantity, 
		0									AS Quantity, 
		0								AS Amount, 
		0								AS Discount, 
		POSHeader.DiscountAmount								AS BillLevelDuiscount, 
		0									AS Tax, 
		-POSHeader.DiscountAmount			AS Net, 
		
		'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
		''	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote,
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts,
				  'Bill Level Discount'									AS TransactionType,
			--POS.Id AS LineItemId
	 		0 AS LineItemId
	 	FROM	sPharmacy.vExtPointOfSaleDetail POS
	 	INNER JOIN sPharmacy.vExtPointOfSale POSHeader
			ON POSHeader.Id = POS.PointOfSaleId
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
					
		
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	 				
	
	ORDER BY ServiceMainGroupTitle
END
ELSE IF (@rCreditNote = 0 AND @rDebitNote = 1 AND @rBillLevelDiscounts = 0)
BEGIN
	SELECT	DISTINCT  B.BillNumber									AS DocNo,
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		SITM.Title	AS ServiceMainGroupTitle, 
		SM.Title AS ServiceTitle, 
		SITM.Code AS ServiceMainGroupCode, 
		SM.Code AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note'											AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((SM.Id > =  (@rFromItemName)) AND (SM.Id < =  @rToItemName))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND ((SITM.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	--Stock Item	
	SELECT DISTINCT	  B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
		UPPER(StockMaster.Title) AS ServiceTitle, 
		UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
		UPPER(StockMaster.Code) 	AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note'											AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND ((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL
	--Consignment Item
	SELECT DISTINCT	  B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
		UPPER(StockMaster.Title) AS ServiceTitle, 
		UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
		UPPER(StockMaster.Code) 	AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note'											AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sConsignment.vExtItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND ((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL

	SELECT	 DISTINCT B.DNNumber									AS DocNo, 
		B.DNDate								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		--OE.Quantity										AS Quantity, 
		1												AS Quantity, 
		B.DocumentAmount								AS Amount, 
		0												AS Discount, 
		0												AS BillLevelDuiscount, 
		0												AS Tax, 
		B.DocumentAmount						AS Net, 
		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
		'' AS DiscountForGrouping, 
		'DEBIT NOTE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'DN' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note'											AS TransactionType,
			--BD.Id AS LineItemId
	 		0 AS LineItemId
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate, 
									DN.Amount DocumentAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT DN.Number, DN.CreatedDateTime, SUM(DN.RoundOffAmount) Amount, DN.BillingId
										FROM sNotes.tDebitNote DN
											INNER JOIN sNotes.tDebitNoteDetail DND
												ON DND.DebitNoteId = DN.Id
												GROUP BY DN.Number, DN.CreatedDateTime, DN.BillingId) DN
									ON DN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id
									WHERE		((DN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId	
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
										
	WHERE		((B.DNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	
	--Stock Item
	--SELECT	 DISTINCT B.DNNumber									AS DocNo, 
	--	B.DNDate								AS DocDate, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientNumber, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMCode, '')
	--	--			END
	--	--)												AS Pid, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientName, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMTitle, '')
	--	--			END
	--	--)												AS PatientName, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	--OE.Quantity										AS Quantity, 
	--	1												AS Quantity, 
	--	B.DocumentAmount								AS Amount, 
	--	0												AS Discount, 
	--	0												AS BillLevelDuiscount, 
	--	0												AS Tax, 
	--	B.DocumentAmount						AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'' AS DiscountForGrouping, 
	--	'DEBIT NOTE'	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'DN' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 	
	 	
	 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 			END
	-- 		END
	-- 	)												AS FromItemName, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 			END
	-- 		END
	-- 	)												AS ToItemName, 
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Debit Note'											AS TransactionType
	 	
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--								B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--								vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--								CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate, 
	--								DN.Amount DocumentAmount
									
	--						FROM sOrderEntry.tBilling B
	--						INNER JOIN (SELECT DN.Number, DN.CreatedDateTime, SUM(DN.RoundOffAmount) Amount, DN.BillingId
	--									FROM sNotes.tDebitNote DN
	--										INNER JOIN sNotes.tDebitNoteDetail DND
	--											ON DND.DebitNoteId = DN.Id
	--											GROUP BY DN.Number, DN.CreatedDateTime, DN.BillingId) DN
	--								ON DN.BillingId = B.Id
	--						INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--								ON  B.RegistrationId = vRPD.Id
	--						LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--								ON B.RegistrationId = DR.RegistrationId
	--						LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--								ON	DR.CorporateId = CM.Id
	--								WHERE		((DN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

	--					) B
	--						ON BD.BillingId  = B.Id
							
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	--WHERE		((B.DNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			(((StockMaster.Id > =  (@rFromItemName)) AND ((StockMaster.Id) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND ((SItemMaster.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	--UNION ALL

		SELECT	 DISTINCT POS.Number								AS DocNo, 
			POS.CreatedDateTime								AS DocDate, 
			
			ISNULL(vRPD.PatientNumber, '') AS Pid, 
			
			ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
			vRPD.ServiceChargeTypeTitle				 AS PatientType, 
			
			0												AS Quantity, 
			--B.POSQuantity									AS Quantity, 
			SUM(POS.Quantity * POS.UnitPrice)								AS Amount, 
			SUM(POS.ItemLevelDiscount)								AS Discount, 
			0							AS BillLevelDuiscount, 
			SUM(POS.TaxAmount)									AS Tax, 
			SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount)			AS Net, 
			
			'' AS DiscountForGrouping, 
			'POINT OF SALE'	AS ServiceMainGroupTitle, 
			'' AS ServiceTitle, 
			'POS' AS ServiceMainGroupCode, 
			'' 	AS ServiceCode, 
		 	
	 	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  'Debit Note'											AS TransactionType,
			--POS.Id AS LineItemId
		 	0 AS LineItemId
	FROM	sPharmacy.vExtPointOfSaleDetail POS
			INNER JOIN sIp.vExtStockItemMaster SIM
				ON POS.StockItemId = SIM.Id
			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				ON 	SItemMaster.Id = SIM.StockItemTypeId
			INNER JOIN sSetup.tDepartmentMaster ODM
				ON SIM.OrganizationDepartmentId = ODM.Id
			INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
				ON  POS.RegistrationId = vRPD.Id
						
			
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

			
	GROUP BY
		POS.Number, 
		POS.CreatedDateTime, 
		vRPD.PatientNumber, 
		vRPD.PatientName, 
		vRPD.ServiceChargeTypeTitle,
		POS.Id
	
			

END
ELSE IF (@rCreditNote = 0 AND @rDebitNote = 1 AND @rBillLevelDiscounts = 1)
BEGIN
	SELECT	DISTINCT  B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		SITM.Title	AS ServiceMainGroupTitle, 
		SM.Title AS ServiceTitle, 
		SITM.Code AS ServiceMainGroupCode, 
		SM.Code AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note / Bill Level Discount'						AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId	
				
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND ((SITM.Id = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	--Stock Item
	SELECT DISTINCT	  B.BillNumber									AS DocNo, 
			B.CreatedDateTime								AS DocDate, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
			B.PatientType AS PatientType, 
			OE.Quantity										AS Quantity, 
			BD.Amount										AS Amount, 
			BD.DiscountAmount								AS Discount, 
			0								AS BillLevelDuiscount, 
			BD.TaxAmount									AS Tax, 
			BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
			'' AS DiscountForGrouping, 
			UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
			UPPER(StockMaster.Title) AS ServiceTitle, 
			UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
			UPPER(StockMaster.Code) 	AS ServiceCode, 
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  'Debit Note / Bill Level Discount'						AS TransactionType,
			BD.Id AS LineItemId
		 		 	
	 		FROM    sOrderEntry.tBillingDetail BD
					
					INNER JOIN 	(
								--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
								--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
								--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
								--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
										
								--FROM sOrderEntry.tBilling B
								--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
								--		ON  B.RegistrationId = vRPD.Id
								--LEFT JOIN sOrderEntry.tDebtorRegistration DR
								--		ON B.RegistrationId = DR.RegistrationId
								--LEFT JOIN	sOrderEntry.tCorporateMaster CM
								--		ON	DR.CorporateId = CM.Id
								SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
								FROM						
									@lTtempTable B
								WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

							) B
								ON BD.BillingId  = B.Id
								
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sIp.vExtStockItemMaster StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
						ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL
	-- Consignment Item
	SELECT DISTINCT	  B.BillNumber									AS DocNo, 
			B.CreatedDateTime								AS DocDate, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientNumber, '')
			--			ELSE 
			--				ISNULL(B.CMCode, '')
			--			END
			--)												AS Pid, 
			ISNULL(B.vRPDPatientNumber, '') AS Pid, 
			--(CASE 
		 --				WHEN B.DebtorTypeID = 1 THEN 
			--				ISNULL(B.vRPDPatientName, '')
			--			ELSE 
			--				ISNULL(B.CMTitle, '')
			--			END
			--)												AS PatientName, 
			ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
			B.PatientType AS PatientType, 
			OE.Quantity										AS Quantity, 
			BD.Amount										AS Amount, 
			BD.DiscountAmount								AS Discount, 
			0								AS BillLevelDuiscount, 
			BD.TaxAmount									AS Tax, 
			BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
			'' AS DiscountForGrouping, 
			UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
			UPPER(StockMaster.Title) AS ServiceTitle, 
			UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
			UPPER(StockMaster.Code) 	AS ServiceCode, 
		 	
	 		(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, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 				'ALL'
	 			ELSE 
	 				@lItemTitle
	 			END
	 		 )												AS ItemType, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 				'ALL'
	 			ELSE 
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 				ELSE
	 					(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 				END
	 			END
	 		 )												AS MainGroup, 
		 	 
	 		(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
					  @rStatus												AS SummaryOrDetail, 
					  @rCreditNote											AS DisplayCreditNote, 
					  @rDebitNote											AS DisplayDebitNote, 
					  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
					  'Debit Note / Bill Level Discount'						AS TransactionType,
			BD.Id AS LineItemId
		 		 	
	 		FROM    sOrderEntry.tBillingDetail BD
					
					INNER JOIN 	(
								--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
								--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
								--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
								--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
										
								--FROM sOrderEntry.tBilling B
								--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
								--		ON  B.RegistrationId = vRPD.Id
								--LEFT JOIN sOrderEntry.tDebtorRegistration DR
								--		ON B.RegistrationId = DR.RegistrationId
								--LEFT JOIN	sOrderEntry.tCorporateMaster CM
								--		ON	DR.CorporateId = CM.Id
								SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
								FROM						
									@lTtempTable B
								WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

							) B
								ON BD.BillingId  = B.Id
								
					LEFT JOIN sOrderEntry.tOrderEntry OE
						ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON OE.ServiceOrganizationDepartmentId = ODM.Id
					LEFT JOIN sConsignment.vExtItemMaster StockMaster
						ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
					INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
						ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL
	
	SELECT	 DISTINCT B.DNNumber									AS DocNo, 
		B.DNDate								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		--OE.Quantity										AS Quantity, 
		1												AS Quantity, 
		B.DocumentAmount								AS Amount, 
		0												AS Discount, 
		0												AS BillLevelDuiscount, 
		0												AS Tax, 
		B.DocumentAmount						AS Net, 
		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
		'' AS DiscountForGrouping, 
		'DEBIT NOTE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'DN' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note / Bill Level Discount'						AS TransactionType,
			--BD.Id AS LineItemId
	 		0 AS LineItemId
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate, 
									DN.Amount DocumentAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT DN.Number, DN.CreatedDateTime, SUM(DN.RoundOffAmount) Amount, DN.BillingId
										FROM sNotes.tDebitNote DN
											INNER JOIN sNotes.tDebitNoteDetail DND
												ON DND.DebitNoteId = DN.Id
												GROUP BY DN.Number, DN.CreatedDateTime, DN.BillingId) DN
									ON DN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id
									WHERE		((DN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.DNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))


	--UNION ALL 
	----Stock item
	--SELECT	 DISTINCT B.DNNumber									AS DocNo, 
	--	B.DNDate								AS DocDate, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientNumber, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMCode, '')
	--	--			END
	--	--)												AS Pid, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientName, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMTitle, '')
	--	--			END
	--	--)												AS PatientName, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	--OE.Quantity										AS Quantity, 
	--	1												AS Quantity, 
	--	B.DocumentAmount								AS Amount, 
	--	0												AS Discount, 
	--	0												AS BillLevelDuiscount, 
	--	0												AS Tax, 
	--	B.DocumentAmount						AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'' AS DiscountForGrouping, 
	--	'DEBIT NOTE'	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'DN' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 	
	 		 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 			END
	-- 		END
	-- 	)												AS FromItemName, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 			END
	-- 		END
	-- 	)												AS ToItemName, 
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Debit Note/Bill Level Discount'						AS TransactionType
	 	
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--								B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--								vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--								CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate, 
	--								DN.Amount DocumentAmount
									
	--						FROM sOrderEntry.tBilling B
	--						INNER JOIN (SELECT DN.Number, DN.CreatedDateTime, SUM(DN.RoundOffAmount) Amount, DN.BillingId
	--									FROM sNotes.tDebitNote DN
	--										INNER JOIN sNotes.tDebitNoteDetail DND
	--											ON DND.DebitNoteId = DN.Id
	--											GROUP BY DN.Number, DN.CreatedDateTime, DN.BillingId) DN
	--								ON DN.BillingId = B.Id
	--						INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--								ON  B.RegistrationId = vRPD.Id
	--						LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--								ON B.RegistrationId = DR.RegistrationId
	--						LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--								ON	DR.CorporateId = CM.Id
	--								WHERE		((DN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

	--					) B
	--						ON BD.BillingId  = B.Id
							
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	--WHERE		((B.DNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))


	UNION ALL


	SELECT	 DISTINCT POS.Number								AS DocNo, 
		POS.CreatedDateTime								AS DocDate, 
		
		ISNULL(vRPD.PatientNumber, '') AS Pid, 
		
		ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
		vRPD.ServiceChargeTypeTitle				 AS PatientType, 
		
		0												AS Quantity, 
		--B.POSQuantity									AS Quantity, 
		SUM(POS.Quantity * POS.UnitPrice)								AS Amount, 
		SUM(POS.ItemLevelDiscount)								AS Discount, 
		0							AS BillLevelDuiscount, 
		SUM(POS.TaxAmount)									AS Tax, 
		SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount)			AS Net, 
		
		'' AS DiscountForGrouping, 
		'POINT OF SALE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'POS' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note / Bill Level Discount'						AS TransactionType,
			--POS.Id AS LineItemId
	 		0 AS LineItemId		
	FROM	sPharmacy.vExtPointOfSaleDetail POS
			INNER JOIN sIp.vExtStockItemMaster SIM
				ON POS.StockItemId = SIM.Id
			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				ON 	SItemMaster.Id = SIM.StockItemTypeId
			INNER JOIN sSetup.tDepartmentMaster ODM
				ON SIM.OrganizationDepartmentId = ODM.Id
			INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
				ON  POS.RegistrationId = vRPD.Id
			
			
			
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

				
	GROUP BY
			POS.Number, 
			POS.CreatedDateTime, 
			vRPD.PatientNumber, 
			vRPD.PatientName, 
			vRPD.ServiceChargeTypeTitle,
			POS.Id
		
				
	UNION ALL
	--BLD
	SELECT	 DISTINCT B.BillNumber						AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		0										AS Quantity, 
		0										AS Amount, 
		0								AS Discount, 
		B.DiscountAmount								AS BillLevelDuiscount, 
		0									AS Tax, 
		-B.DiscountAmount	AS Net, 
		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
		'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
		''	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note / Bill Level Discount'						AS TransactionType,
			B.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				RIGHT JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id --AND OE.ItemSourceTypeId = 25
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id --AND OE.ItemSourceTypeId = 34
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	--UNION ALL
	----Stock Item
	
	--SELECT	 DISTINCT B.BillNumber						AS DocNo, 
	--	B.CreatedDateTime								AS DocDate, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	0										AS Quantity, 
	--	0										AS Amount, 
	--	0								AS Discount, 
	--	B.DiscountAmount								AS BillLevelDuiscount, 
	--	0									AS Tax, 
	--	-B.DiscountAmount	AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
	--	''	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	-- 				END
	-- 			END
	-- 		)												AS FromItemName, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	-- 				END
	-- 			END
	-- 		)												AS ToItemName, 
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Debit Note / Bill Level Discount'						AS TransactionType
	 		 	
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(
	--						--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--						--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--						--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--						--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
	--						--FROM sOrderEntry.tBilling B
	--						--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--						--		ON  B.RegistrationId = vRPD.Id
	--						--LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--						--		ON B.RegistrationId = DR.RegistrationId
	--						--LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--						--		ON	DR.CorporateId = CM.Id
	--						SELECT Id, vRPDId, BRegId, BillNumber, 
	--									CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
	--									vRPDPatientName, PatientType, 
	--									CMCode, CMTitle, DiscountAmount			
	--						FROM						
	--							@lTtempTable B							
	--						WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--					) B
	--						ON BD.BillingId  = B.Id
							
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId							
	--WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	--UNION ALL
	----Consignment Item	
	--SELECT	 DISTINCT B.BillNumber						AS DocNo, 
	--	B.CreatedDateTime								AS DocDate, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	0										AS Quantity, 
	--	0										AS Amount, 
	--	0								AS Discount, 
	--	B.DiscountAmount								AS BillLevelDuiscount, 
	--	0									AS Tax, 
	--	-B.DiscountAmount	AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
	--	''	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	-- 				END
	-- 			END
	-- 		)												AS FromItemName, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	-- 				END
	-- 			END
	-- 		)												AS ToItemName, 
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Debit Note / Bill Level Discount'						AS TransactionType
	 		 	
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(
	--						--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--						--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--						--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--						--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
	--						--FROM sOrderEntry.tBilling B
	--						--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--						--		ON  B.RegistrationId = vRPD.Id
	--						--LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--						--		ON B.RegistrationId = DR.RegistrationId
	--						--LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--						--		ON	DR.CorporateId = CM.Id
	--						SELECT Id, vRPDId, BRegId, BillNumber, 
	--									CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
	--									vRPDPatientName, PatientType, 
	--									CMCode, CMTitle, DiscountAmount			
	--						FROM						
	--							@lTtempTable B							
	--						WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--					) B
	--						ON BD.BillingId  = B.Id
							
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
	--			INNER JOIN sConsignment.vExtItemMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId							
	--WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL

	SELECT	 DISTINCT POS.Number								AS DocNo, 
		POS.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(vRPD.PatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
		vRPD.ServiceChargeTypeTitle AS PatientType, 
		--OE.Quantity										AS Quantity, 
		0									AS Quantity, 
		0								AS Amount, 
		0								AS Discount, 
		POSHeader.DiscountAmount								AS BillLevelDuiscount, 
		0									AS Tax, 
		-POSHeader.DiscountAmount			AS Net, 
		
		'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
		''	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName,
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote,
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Debit Note / Bill Level Discount'						AS TransactionType,
			--POS.Id AS LineItemId
	 		0 AS LineItemId
	 	FROM	sPharmacy.vExtPointOfSaleDetail POS
	 	INNER JOIN sPharmacy.vExtPointOfSale POSHeader
			ON POSHeader.Id = POS.PointOfSaleId
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
					
		
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))				
	
	ORDER BY ServiceMainGroupTitle
END
ELSE IF (@rCreditNote = 1 AND @rDebitNote = 0 AND @rBillLevelDiscounts = 0)
BEGIN
	SELECT	DISTINCT  B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		SITM.Title	AS ServiceMainGroupTitle, 
		SM.Title AS ServiceTitle, 
		SITM.Code AS ServiceMainGroupCode, 
		SM.Code AS ServiceCode,
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note'											AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId							
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND ((SM.Id) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	--Stock Item
	SELECT	DISTINCT  B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		UPPER(SItemMaster.Title) AS ServiceMainGroupTitle, 
		UPPER(StockMaster.Title) AS ServiceTitle, 
		UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
		UPPER(StockMaster.Code) 	AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note'											AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B	
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	--Consignment Item
	SELECT	DISTINCT  B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		UPPER(SItemMaster.Title) AS ServiceMainGroupTitle, 
		UPPER(StockMaster.Title) AS ServiceTitle, 
		UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
		UPPER(StockMaster.Code) 	AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note'											AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B	
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sConsignment.vExtItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL
	
	SELECT	 DISTINCT B.CNNumber									AS DocNo, 
		B.CNDate									AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		--OE.Quantity										AS Quantity, 
		1												AS Quantity, 
		-B.DocumentAmount								AS Amount, 
		0												AS Discount, 
		0												AS BillLevelDuiscount, 
		0												AS Tax, 
		-B.DocumentAmount								AS Net, 
		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
		'' AS DiscountForGrouping, 
		'CREDIT NOTE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'CN' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note'											AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate, 
									CN.Amount DocumentAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT CN.Number, CN.CreatedDateTime, SUM(CN.RoundOffAmount) Amount, CN.BillingId
										FROM sNotes.tCreditNote CN
											INNER JOIN sNotes.tCreditNoteDetail CND
												ON CND.CreditNoteId = CN.Id
												GROUP BY CN.Number, CN.CreatedDateTime, CN.BillingId) CN
									ON CN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id
									WHERE		((CN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	WHERE		((B.CNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	--UNION ALL
	----Stock Item
	--SELECT	 DISTINCT B.CNNumber					AS DocNo, 
	--	B.CNDate									AS DocDate, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientNumber, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMCode, '')
	--	--			END
	--	--)												AS Pid, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientName, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMTitle, '')
	--	--			END
	--	--)												AS PatientName, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	--OE.Quantity										AS Quantity, 
	--	1												AS Quantity, 
	--	-B.DocumentAmount								AS Amount, 
	--	0												AS Discount, 
	--	0												AS BillLevelDuiscount, 
	--	0												AS Tax, 
	--	-B.DocumentAmount								AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'' AS DiscountForGrouping, 
	--	'CREDIT NOTE'	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'CN' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 		 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 			END
	-- 		END
	-- 	)												AS FromItemName, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 			END
	-- 		END
	-- 	)												AS ToItemName, 
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Credit Note'											AS TransactionType
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--								B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--								vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--								CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate, 
	--								CN.Amount DocumentAmount
									
	--						FROM sOrderEntry.tBilling B
	--						INNER JOIN (SELECT CN.Number, CN.CreatedDateTime, SUM(CN.RoundOffAmount) Amount, CN.BillingId
	--									FROM sNotes.tCreditNote CN
	--										INNER JOIN sNotes.tCreditNoteDetail CND
	--											ON CND.CreditNoteId = CN.Id
	--											GROUP BY CN.Number, CN.CreatedDateTime, CN.BillingId) CN
	--								ON CN.BillingId = B.Id
	--						INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--								ON  B.RegistrationId = vRPD.Id
	--						LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--								ON B.RegistrationId = DR.RegistrationId
	--						LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--								ON	DR.CorporateId = CM.Id
	--								WHERE		((CN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

	--					) B
	--						ON BD.BillingId  = B.Id
							
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	--WHERE		((B.CNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
			
	UNION ALL

	SELECT	 DISTINCT POS.Number								AS DocNo, 
		POS.CreatedDateTime								AS DocDate, 
		
		ISNULL(vRPD.PatientNumber, '') AS Pid, 
		
		ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
		vRPD.ServiceChargeTypeTitle				 AS PatientType, 
		
		0												AS Quantity, 
		--B.POSQuantity									AS Quantity, 
		SUM(POS.Quantity * POS.UnitPrice)								AS Amount, 
		SUM(POS.ItemLevelDiscount)								AS Discount, 
		0							AS BillLevelDuiscount, 
		SUM(POS.TaxAmount)									AS Tax, 
		SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount)			AS Net, 
		
		'' AS DiscountForGrouping, 
		'POINT OF SALE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'POS' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note'											AS TransactionType,
			--POS.Id AS LineItemId
	 		0 AS LineItemId
	FROM	sPharmacy.vExtPointOfSaleDetail POS
			INNER JOIN sIp.vExtStockItemMaster SIM
				ON POS.StockItemId = SIM.Id
			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
				ON 	SItemMaster.Id = SIM.StockItemTypeId
			INNER JOIN sSetup.tDepartmentMaster ODM
				ON SIM.OrganizationDepartmentId = ODM.Id
			INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
				ON  POS.RegistrationId = vRPD.Id
			
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

			
	GROUP BY
		POS.Number, 
		POS.CreatedDateTime, 
		vRPD.PatientNumber, 
		vRPD.PatientName, 
		vRPD.ServiceChargeTypeTitle,
		POS.Id
END
ELSE IF (@rCreditNote = 1 AND @rDebitNote = 0 AND @rBillLevelDiscounts = 1)
BEGIN
	SELECT	DISTINCT  B.BillNumber								AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		SITM.Title	AS ServiceMainGroupTitle,
		SM.Title AS ServiceTitle,
		SITM.Code AS ServiceMainGroupCode,
		SM.Code 	AS ServiceCode,
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL
	--Stock Item
	SELECT	DISTINCT  B.BillNumber								AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
		UPPER(StockMaster.Title) AS ServiceTitle, 
		UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
		UPPER(StockMaster.Code)	AS ServiceCode,
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			BD.Id AS LineItemId
			 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL
	--Consignment Item
	SELECT	DISTINCT  B.BillNumber								AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		UPPER(SItemMaster.Title)	AS ServiceMainGroupTitle, 
		UPPER(StockMaster.Title) AS ServiceTitle, 
		UPPER(SItemMaster.Code) AS ServiceMainGroupCode, 
		UPPER(StockMaster.Code)	AS ServiceCode,
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			BD.Id AS LineItemId
			 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sConsignment.vExtItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL

	SELECT	 DISTINCT B.CNNumber									AS DocNo, 
		B.CNDate									AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		--OE.Quantity										AS Quantity, 
		1												AS Quantity, 
		-B.DocumentAmount								AS Amount, 
		0												AS Discount, 
		0												AS BillLevelDuiscount, 
		0												AS Tax, 
		-B.DocumentAmount								AS Net, 
		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
		'' AS DiscountForGrouping, 
		'CREDIT NOTE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'CN' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
				  
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate, 
									CN.Amount DocumentAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT CN.Number, CN.CreatedDateTime, SUM(CN.RoundOffAmount) Amount, CN.BillingId
										FROM sNotes.tCreditNote CN
											INNER JOIN sNotes.tCreditNoteDetail CND
												ON CND.CreditNoteId = CN.Id
												GROUP BY CN.Number, CN.CreatedDateTime, CN.BillingId) CN
									ON CN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id
									WHERE		((CN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
					
	WHERE		((B.CNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	--UNION ALL
	
	----STOCK Item
	--SELECT	 DISTINCT B.CNNumber									AS DocNo, 
	--	B.CNDate									AS DocDate, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientNumber, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMCode, '')
	--	--			END
	--	--)												AS Pid, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientName, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMTitle, '')
	--	--			END
	--	--)												AS PatientName, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	--OE.Quantity										AS Quantity, 
	--	1												AS Quantity, 
	--	-B.DocumentAmount								AS Amount, 
	--	0												AS Discount, 
	--	0												AS BillLevelDuiscount, 
	--	0												AS Tax, 
	--	-B.DocumentAmount								AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'' AS DiscountForGrouping, 
	--	'CREDIT NOTE'	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'CN' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 	
	 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 			END
	-- 		END
	-- 	)												AS FromItemName, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 			END
	-- 		END
	-- 	)												AS ToItemName, 
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Credit Note/Bill Level Discount'						AS TransactionType
				  
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--								B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--								vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--								CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate, 
	--								CN.Amount DocumentAmount
									
	--						FROM sOrderEntry.tBilling B
	--						INNER JOIN (SELECT CN.Number, CN.CreatedDateTime, SUM(CN.RoundOffAmount) Amount, CN.BillingId
	--									FROM sNotes.tCreditNote CN
	--										INNER JOIN sNotes.tCreditNoteDetail CND
	--											ON CND.CreditNoteId = CN.Id
	--											GROUP BY CN.Number, CN.CreatedDateTime, CN.BillingId) CN
	--								ON CN.BillingId = B.Id
	--						INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--								ON  B.RegistrationId = vRPD.Id
	--						LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--								ON B.RegistrationId = DR.RegistrationId
	--						LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--								ON	DR.CorporateId = CM.Id
	--								WHERE		((CN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

	--					) B
	--						ON BD.BillingId  = B.Id
							
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	--WHERE		((B.CNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL

	SELECT	 DISTINCT POS.Number								AS DocNo, 
		POS.CreatedDateTime								AS DocDate, 
		
		ISNULL(vRPD.PatientNumber, '') AS Pid, 
		
		ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
		vRPD.ServiceChargeTypeTitle				 AS PatientType, 
		
		0												AS Quantity, 
		--B.POSQuantity									AS Quantity, 
		SUM(POS.Quantity * POS.UnitPrice)								AS Amount, 
		SUM(POS.ItemLevelDiscount)								AS Discount, 
		0							AS BillLevelDuiscount, 
		SUM(POS.TaxAmount)									AS Tax, 
		SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount)			AS Net, 
		
		'' AS DiscountForGrouping, 
		'POINT OF SALE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'POS' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			--POS.Id AS LineItemId
	 		0 AS LineItemId
	FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
		
			
			
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

				
	GROUP BY
			POS.Number, 
			POS.CreatedDateTime, 
			vRPD.PatientNumber, 
			vRPD.PatientName, 
			vRPD.ServiceChargeTypeTitle,
			POS.Id
	
			
	UNION ALL
	--BLD 
	SELECT	 DISTINCT B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		0										AS Quantity, 
		0										AS Amount, 
		0								AS Discount, 
		B.DiscountAmount								AS BillLevelDuiscount, 
		0									AS Tax, 
		-B.DiscountAmount	AS Net, 
		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
		'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
		''	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			--B.Id AS LineItemId
	 		0 AS LineItemId
	 	FROM    sOrderEntry.tBillingDetail BD
				
				RIGHT JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id --AND OE.ItemSourceTypeId = 25 
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id --AND OE.ItemSourceTypeId = 34
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL
	
	----sTOCK ITEM
	--SELECT	 DISTINCT B.BillNumber									AS DocNo, 
	--	B.CreatedDateTime								AS DocDate, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	0										AS Quantity, 
	--	0										AS Amount, 
	--	0								AS Discount, 
	--	B.DiscountAmount								AS BillLevelDuiscount, 
	--	0									AS Tax, 
	--	-B.DiscountAmount	AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
	--	''	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	-- 				END
	-- 			END
	-- 		)												AS FromItemName, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	-- 				END
	-- 			END
	-- 		)												AS ToItemName, 
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Credit Note / Bill Level Discount'						AS TransactionType
	 		 	
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(
	--						--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--						--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--						--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--						--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
	--						--FROM sOrderEntry.tBilling B
	--						--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--						--		ON  B.RegistrationId = vRPD.Id
	--						--LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--						--		ON B.RegistrationId = DR.RegistrationId
	--						--LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--						--		ON	DR.CorporateId = CM.Id
	--						SELECT Id, vRPDId, BRegId, BillNumber,
	--									CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
	--									vRPDPatientName, PatientType, 
	--									CMCode, CMTitle, DiscountAmount			
	--						FROM
	--							@lTtempTable B
	--						WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--					) B
	--						ON BD.BillingId  = B.Id
				
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	--WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	--UNION ALL
	
	--Consignment ITEM
	--SELECT	 DISTINCT B.BillNumber									AS DocNo, 
	--	B.CreatedDateTime								AS DocDate, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	0										AS Quantity, 
	--	0										AS Amount, 
	--	0								AS Discount, 
	--	B.DiscountAmount								AS BillLevelDuiscount, 
	--	0									AS Tax, 
	--	-B.DiscountAmount	AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
	--	''	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	-- 				END
	-- 			END
	-- 		)												AS FromItemName, 
		 	
	-- 		(CASE 
	-- 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 				'ALL'
	-- 			ELSE
	-- 				CASE WHEN (@rItemType = 2) THEN
	-- 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 					WHEN (@rItemType = 1) THEN
	-- 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 					WHEN (@rItemType = 3) THEN
	-- 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	-- 				END
	-- 			END
	-- 		)												AS ToItemName, 
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Credit Note / Bill Level Discount'						AS TransactionType
	 		 	
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(
	--						--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--						--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--						--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--						--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
	--						--FROM sOrderEntry.tBilling B
	--						--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--						--		ON  B.RegistrationId = vRPD.Id
	--						--LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--						--		ON B.RegistrationId = DR.RegistrationId
	--						--LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--						--		ON	DR.CorporateId = CM.Id
	--						SELECT Id, vRPDId, BRegId, BillNumber,
	--									CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
	--									vRPDPatientName, PatientType, 
	--									CMCode, CMTitle, DiscountAmount			
	--						FROM
	--							@lTtempTable B
	--						WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--					) B
	--						ON BD.BillingId  = B.Id
				
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sConsignment.vExtItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	--WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	--UNION ALL

	SELECT	 DISTINCT POS.Number								AS DocNo, 
		POS.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(vRPD.PatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
		vRPD.ServiceChargeTypeTitle AS PatientType, 
		--OE.Quantity										AS Quantity, 
		0									AS Quantity, 
		0								AS Amount, 
		0								AS Discount, 
		POSHeader.DiscountAmount								AS BillLevelDuiscount, 
		0									AS Tax, 
		-POSHeader.DiscountAmount			AS Net, 
		
		'BILL LEVEL DISCOUNTS' AS DiscountForGrouping, 
		''	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 		 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Bill Level Discount'						AS TransactionType,
			--POS.Id AS LineItemId
	 		0 AS LineItemId
	 	FROM	sPharmacy.vExtPointOfSaleDetail POS
	 	INNER JOIN sPharmacy.vExtPointOfSale POSHeader
			ON POSHeader.Id = POS.PointOfSaleId
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id				
		
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
			
	ORDER BY ServiceMainGroupTitle
END
ELSE IF (@rCreditNote = 1 AND @rDebitNote = 1 AND @rBillLevelDiscounts = 0)
BEGIN
	SELECT DISTINCT B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		SITM.Title	AS ServiceMainGroupTitle, 
		SM.Title AS ServiceTitle, 
		SITM.Code AS ServiceMainGroupCode, 
		SM.Code AS ServiceCode,
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note'								AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount			
							FROM						
								@lTtempTable B
							WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id AND OE.ItemSourceTypeId = 25 
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL
	
	-- Stock Item
	SELECT DISTINCT	  B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		SItemMaster.Title	AS ServiceMainGroupTitle, 
		StockMaster.Title AS ServiceTitle, 
		SItemMaster.Code AS ServiceMainGroupCode, 
		StockMaster.Code 	AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note'								AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount	
							FROM	
								@lTtempTable B
							WHERE ((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL
	
	-- Consignment Item
	SELECT DISTINCT	  B.BillNumber									AS DocNo, 
		B.CreatedDateTime								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		OE.Quantity										AS Quantity, 
		BD.Amount										AS Amount, 
		BD.DiscountAmount								AS Discount, 
		0								AS BillLevelDuiscount, 
		BD.TaxAmount									AS Tax, 
		BD.Amount + BD.TaxAmount - BD.DiscountAmount	AS Net, 
		'' AS DiscountForGrouping, 
		SItemMaster.Title	AS ServiceMainGroupTitle, 
		StockMaster.Title AS ServiceTitle, 
		SItemMaster.Code AS ServiceMainGroupCode, 
		StockMaster.Code 	AS ServiceCode, 
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note'								AS TransactionType,
			BD.Id AS LineItemId
	 		 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(
							--SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
							--		B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
							--		vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
							--		CM.Code CMCode, CM.Title CMTitle, B.DiscountAmount
									
							--FROM sOrderEntry.tBilling B
							--INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
							--		ON  B.RegistrationId = vRPD.Id
							--LEFT JOIN sOrderEntry.tDebtorRegistration DR
							--		ON B.RegistrationId = DR.RegistrationId
							--LEFT JOIN	sOrderEntry.tCorporateMaster CM
							--		ON	DR.CorporateId = CM.Id
							SELECT Id, vRPDId, BRegId, BillNumber, 
										CreatedDateTime, vRPDPatientNumber, DebtorTypeID, 
										vRPDPatientName, PatientType, 
										CMCode, CMTitle, DiscountAmount	
							FROM	
								@lTtempTable B
							WHERE ((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sConsignment.vExtItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 90
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
	
	UNION ALL

	SELECT	 DISTINCT B.CNNumber									AS DocNo, 
		B.CNDate									AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		--OE.Quantity										AS Quantity, 
		1												AS Quantity, 
		-B.DocumentAmount								AS Amount, 
		0												AS Discount, 
		0												AS BillLevelDuiscount, 
		0												AS Tax, 
		-B.DocumentAmount								AS Net, 
		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
		'' AS DiscountForGrouping, 
		'CREDIT NOTE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'CN' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note'								AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
			
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate, 
									CN.Amount DocumentAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT CN.Number, CN.CreatedDateTime, SUM(CN.RoundOffAmount) Amount, CN.BillingId
										FROM sNotes.tCreditNote CN
											INNER JOIN sNotes.tCreditNoteDetail CND
												ON CND.CreditNoteId = CN.Id
												GROUP BY CN.Number, CN.CreatedDateTime, CN.BillingId) CN
									ON CN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id
									WHERE		((CN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId			
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId			
	WHERE		((B.CNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	--UNION ALL
	----Stock Item
	--SELECT	 DISTINCT B.CNNumber									AS DocNo, 
	--	B.CNDate									AS DocDate, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientNumber, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMCode, '')
	--	--			END
	--	--)												AS Pid, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientName, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMTitle, '')
	--	--			END
	--	--)												AS PatientName, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	--OE.Quantity										AS Quantity, 
	--	1												AS Quantity, 
	--	-B.DocumentAmount								AS Amount, 
	--	0												AS Discount, 
	--	0												AS BillLevelDuiscount, 
	--	0												AS Tax, 
	--	-B.DocumentAmount								AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'' AS DiscountForGrouping, 
	--	'CREDIT NOTE'	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'CN' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode, 
	 	
	 	
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 			END
	-- 		END
	-- 	)												AS FromItemName, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 			END
	-- 		END
	-- 	)												AS ToItemName, 
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Credit Note/Debit Note'								AS TransactionType
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--								B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--								vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--								CM.Code CMCode, CM.Title CMTitle, CN.Number CNNumber, CN.CreatedDateTime CNDate, 
	--								CN.Amount DocumentAmount
									
	--						FROM sOrderEntry.tBilling B
	--						INNER JOIN (SELECT CN.Number, CN.CreatedDateTime, SUM(CN.RoundOffAmount) Amount, CN.BillingId
	--									FROM sNotes.tCreditNote CN
	--										INNER JOIN sNotes.tCreditNoteDetail CND
	--											ON CND.CreditNoteId = CN.Id
	--											GROUP BY CN.Number, CN.CreatedDateTime, CN.BillingId) CN
	--								ON CN.BillingId = B.Id
	--						INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--								ON  B.RegistrationId = vRPD.Id
	--						LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--								ON B.RegistrationId = DR.RegistrationId
	--						LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--								ON	DR.CorporateId = CM.Id
	--								WHERE		((CN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

	--					) B
	--						ON BD.BillingId  = B.Id
							
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	--WHERE		((B.CNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL

	SELECT	 DISTINCT B.DNNumber									AS DocNo, 
		B.DNDate								AS DocDate, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientNumber, '')
		--			ELSE 
		--				ISNULL(B.CMCode, '')
		--			END
		--)												AS Pid, 
		ISNULL(B.vRPDPatientNumber, '') AS Pid, 
		--(CASE 
	 --				WHEN B.DebtorTypeID = 1 THEN 
		--				ISNULL(B.vRPDPatientName, '')
		--			ELSE 
		--				ISNULL(B.CMTitle, '')
		--			END
		--)												AS PatientName, 
		ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
		B.PatientType AS PatientType, 
		--OE.Quantity										AS Quantity, 
		1												AS Quantity, 
		B.DocumentAmount								AS Amount, 
		0												AS Discount, 
		0												AS BillLevelDuiscount, 
		0												AS Tax, 
		B.DocumentAmount						AS Net, 
		--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
		--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
		--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
		--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
		'' AS DiscountForGrouping, 
		'DEBIT NOTE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'DN' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	
	 	
	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note'								AS TransactionType,
			--BD.Id AS LineItemId
			0 AS LineItemId
	 	
	 	FROM    sOrderEntry.tBillingDetail BD
				
				INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
									B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
									vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
									CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate, 
									DN.Amount DocumentAmount
									
							FROM sOrderEntry.tBilling B
							INNER JOIN (SELECT DN.Number, DN.CreatedDateTime, SUM(DN.RoundOffAmount) Amount, DN.BillingId
										FROM sNotes.tDebitNote DN
											INNER JOIN sNotes.tDebitNoteDetail DND
												ON DND.DebitNoteId = DN.Id
												GROUP BY DN.Number, DN.CreatedDateTime, DN.BillingId) DN
									ON DN.BillingId = B.Id
							INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
									ON  B.RegistrationId = vRPD.Id
							LEFT JOIN sOrderEntry.tDebtorRegistration DR
									ON B.RegistrationId = DR.RegistrationId
							LEFT JOIN	sOrderEntry.tCorporateMaster CM
									ON	DR.CorporateId = CM.Id
									WHERE		((DN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

						) B
							ON BD.BillingId  = B.Id
							
				LEFT JOIN sOrderEntry.tOrderEntry OE
					ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
				INNER JOIN sSetup.tDepartmentMaster ODM
					ON OE.ServiceOrganizationDepartmentId = ODM.Id
				LEFT JOIN sOrderEntry.tServiceMaster SM
					ON 	OE.ItemSourceId = SM.Id
				INNER JOIN sOrderEntry.tServiceItemTypeMaster SITM
					ON 	SITM.Id = SM.ServiceItemTypeId
				LEFT JOIN sIp.vExtStockItemMaster StockMaster
					ON 	OE.ItemSourceId = StockMaster.Id
				INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
					ON 	SItemMaster.Id = StockMaster.StockItemTypeId
						
	WHERE		((B.DNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	AND			((((SM.Id) > =  (@rFromItemName)) AND (((SM.Id)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND (((SITM.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	--UNION ALL
	----Stock Item
	
	--SELECT	 DISTINCT B.DNNumber				AS DocNo,
	--	B.DNDate								AS DocDate,
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientNumber, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMCode, '')
	--	--			END
	--	--)												AS Pid, 
	--	ISNULL(B.vRPDPatientNumber, '') AS Pid, 
	--	--(CASE 
	-- --				WHEN B.DebtorTypeID = 1 THEN 
	--	--				ISNULL(B.vRPDPatientName, '')
	--	--			ELSE 
	--	--				ISNULL(B.CMTitle, '')
	--	--			END
	--	--)												AS PatientName, 
	--	ISNULL(UPPER(B.vRPDPatientName), '') AS PatientName, 
	--	B.PatientType AS PatientType, 
	--	--OE.Quantity										AS Quantity, 
	--	1												AS Quantity, 
	--	B.DocumentAmount								AS Amount, 
	--	0												AS Discount, 
	--	0												AS BillLevelDuiscount, 
	--	0												AS Tax, 
	--	B.DocumentAmount						AS Net, 
	--	--ISNULL(UPPER(SITM.Title), UPPER(SItemMaster.Title))	AS ServiceMainGroupTitle, 
	--	--ISNULL(UPPER(SM.Title), UPPER(StockMaster.Title)) AS ServiceTitle, 
	--	--ISNULL(UPPER(SITM.Code), UPPER(SItemMaster.Code)) AS ServiceMainGroupCode, 
	--	--ISNULL(UPPER(SM.Code), UPPER(StockMaster.Code)) 	AS ServiceCode, 
	--	'' AS DiscountForGrouping, 
	--	'DEBIT NOTE'	AS ServiceMainGroupTitle, 
	--	'' AS ServiceTitle, 
	--	'DN' AS ServiceMainGroupCode, 
	--	'' 	AS ServiceCode,
		
	-- 	(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, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			@lItemTitle
	-- 		END
	-- 	 )												AS ItemType, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE 
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	-- 			ELSE
	-- 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	-- 			END
	-- 		END
	-- 	 )												AS MainGroup, 
	 	 
	-- 	(CASE 
	-- 		WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	-- 			END
	-- 		END
	-- 	)												AS FromItemName, 
	 	
	-- 	(CASE 
	-- 		WHEN ISNULL(@rToItemName, 0) = 0 THEN
	-- 			'ALL'
	-- 		ELSE
	-- 			CASE WHEN (@rItemType = 2) THEN
	-- 				(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	-- 			ELSE
	-- 				(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	-- 			END
	-- 		END
	-- 	)												AS ToItemName, 
	--			  @rStatus												AS SummaryOrDetail, 
	--			  @rCreditNote											AS DisplayCreditNote, 
	--			  @rDebitNote											AS DisplayDebitNote, 
	--			  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
	--			  'Credit Note/Debit Note'								AS TransactionType
	 	
	-- 	FROM    sOrderEntry.tBillingDetail BD
				
	--			INNER JOIN 	(SELECT B.Id, vRPD.PatientId vRPDId, B.RegistrationId BRegId, B.BillNumber, 
	--								B.CreatedDateTime, vRPD.PatientNumber vRPDPatientNumber, B.DebtorTypeId DebtorTypeID, 
	--								vRPD.PatientName vRPDPatientName, vRPD.ServiceChargeTypeTitle PatientType, 
	--								CM.Code CMCode, CM.Title CMTitle, DN.Number DNNumber, DN.CreatedDateTime DNDate, 
	--								DN.Amount DocumentAmount
									
	--						FROM sOrderEntry.tBilling B
	--						INNER JOIN (SELECT DN.Number, DN.CreatedDateTime, SUM(DN.RoundOffAmount) Amount, DN.BillingId
	--									FROM sNotes.tDebitNote DN
	--										INNER JOIN sNotes.tDebitNoteDetail DND
	--											ON DND.DebitNoteId = DN.Id
	--											GROUP BY DN.Number, DN.CreatedDateTime, DN.BillingId) DN
	--								ON DN.BillingId = B.Id
	--						INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
	--								ON  B.RegistrationId = vRPD.Id
	--						LEFT JOIN sOrderEntry.tDebtorRegistration DR
	--								ON B.RegistrationId = DR.RegistrationId
	--						LEFT JOIN	sOrderEntry.tCorporateMaster CM
	--								ON	DR.CorporateId = CM.Id
	--								WHERE		((DN.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))

	--					) B
	--						ON BD.BillingId  = B.Id
							
	--			LEFT JOIN sOrderEntry.tOrderEntry OE
	--				ON	B.BRegId = OE.RegistrationId AND OE.Id = BD.OrderEntryId
	--			INNER JOIN sSetup.tDepartmentMaster ODM
	--				ON OE.ServiceOrganizationDepartmentId = ODM.Id
	--			LEFT JOIN sIp.vExtStockItemMaster StockMaster
	--				ON 	OE.ItemSourceId = StockMaster.Id AND OE.ItemSourceTypeId = 34
	--			INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
	--				ON 	SItemMaster.Id = StockMaster.StockItemTypeId
							
	--WHERE		((B.DNDate BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	--AND ((@lItemTypeId = @rItemType) OR (@rItemType = 0))
	--AND			((((StockMaster.Id) > =  (@rFromItemName)) AND (((StockMaster.Id)) < =  (@rToItemName)))
	--			OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	--AND (((SItemMaster.Id) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))

	UNION ALL

	SELECT	 DISTINCT POS.Number								AS DocNo, 
		POS.CreatedDateTime								AS DocDate, 
		
		ISNULL(vRPD.PatientNumber, '') AS Pid, 
		
		ISNULL(UPPER(vRPD.PatientName), '') AS PatientName, 
		vRPD.ServiceChargeTypeTitle				 AS PatientType, 
		
		0												AS Quantity, 
		--B.POSQuantity									AS Quantity, 
		SUM(POS.Quantity * POS.UnitPrice)								AS Amount, 
		SUM(POS.ItemLevelDiscount)								AS Discount, 
		0							AS BillLevelDuiscount, 
		SUM(POS.TaxAmount)									AS Tax, 
		SUM((POS.Quantity * POS.UnitPrice) + POS.TaxAmount - POS.ItemLevelDiscount)			AS Net, 
		
		'' AS DiscountForGrouping, 
		'POINT OF SALE'	AS ServiceMainGroupTitle, 
		'' AS ServiceTitle, 
		'POS' AS ServiceMainGroupCode, 
		'' 	AS ServiceCode, 
	 	
	 	 	(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, 
	 	
	 	(CASE 
	 		WHEN ISNULL(@rItemType, 0)  = 0 THEN
	 			'ALL'
	 		ELSE 
	 			@lItemTitle
	 		END
	 	 )												AS ItemType, 
	 	 
	 	(CASE 
	 		WHEN ISNULL(@rServiceMainGroup, 0) = 0 THEN
	 			'ALL'
	 		ELSE 
	 			CASE WHEN (@rItemType = 2) THEN
	 				(SELECT SITM.Title FROM sOrderEntry.tServiceItemTypeMaster SITM WHERE SITM.Id = @rServiceMainGroup)
	 			ELSE
	 				(SELECT SItemMaster.Title FROM sIp.vExtStockItemTypeMaster SItemMaster WHERE SItemMaster.Id = @rServiceMainGroup)
	 			END
	 		END
	 	 )												AS MainGroup, 
	 	 
	 	(CASE 
	 			WHEN ISNULL(@rFromItemName, 0) = 0  THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rFromItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rFromItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rFromItemName)
	 				END
	 			END
	 		)												AS FromItemName, 
		 	
	 		(CASE 
	 			WHEN ISNULL(@rToItemName, 0) = 0 THEN
	 				'ALL'
	 			ELSE
	 				CASE WHEN (@rItemType = 2) THEN
	 					(SELECT SM.Title FROM sOrderEntry.tServiceMaster SM WHERE SM.Id = @rToItemName)
	 					WHEN (@rItemType = 1) THEN
	 					(SELECT StockMaster.Title FROM sIp.vExtStockItemMaster StockMaster WHERE StockMaster.Id = @rToItemName)
	 					WHEN (@rItemType = 3) THEN
	 					(SELECT ConMaster.Title FROM sConsignment.vExtItemMaster ConMaster WHERE ConMaster.Id = @rToItemName)
	 				END
	 			END
	 		)												AS ToItemName, 
				  @rStatus												AS SummaryOrDetail, 
				  @rCreditNote											AS DisplayCreditNote, 
				  @rDebitNote											AS DisplayDebitNote, 
				  @rBillLevelDiscounts									AS DisplayBillLevelDiscounts, 
				  'Credit Note / Debit Note'								AS TransactionType,
			--POS.Id AS LineItemId
	 		0 AS LineItemId
FROM	sPharmacy.vExtPointOfSaleDetail POS
		INNER JOIN sIp.vExtStockItemMaster SIM
			ON POS.StockItemId = SIM.Id
		INNER JOIN sIp.vExtStockItemTypeMaster SItemMaster
			ON 	SItemMaster.Id = SIM.StockItemTypeId
		INNER JOIN sSetup.tDepartmentMaster ODM
			ON SIM.OrganizationDepartmentId = ODM.Id
		INNER JOIN	sRegistration.vExtRegistrationWithPatientDetail vRPD
			ON  POS.RegistrationId = vRPD.Id
			
			
	WHERE		((POS.CreatedDateTime BETWEEN @rFromDate AND (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '') OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
	AND			((ISNULL(SIM.Id, 0) > =  (@rFromItemName) AND ((ISNULL(SIM.Id, 0)) < =  (@rToItemName)))
				OR (ISNULL(@rFromItemName, '') = 0) OR (ISNULL(@rToItemName, '') = 0))
	AND			((ISNULL(SItemMaster.Id, 0) = @rServiceMainGroup) OR (@rServiceMainGroup = 0))
				
	GROUP BY
			POS.Number, 
			POS.CreatedDateTime, 
			vRPD.PatientNumber, 
			vRPD.PatientName, 
			vRPD.ServiceChargeTypeTitle,
			POS.Id

END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pRptStockIssueReturn]
 
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

   SELECT  
				SIM.Code AS ItemNumber,
				SIM.Title AS ItemName,		
				IR.ReturnedByName,	
				IR.Number, 	
				IR.CreatedDateTime AS IssuedReturnDate,
		
				IRD.IssuedQuantity,
				IRD.ReturnQuantity,
				LM.Title AS ToLocation,
				RM.Title AS Reason,
				P.Id AS PrescriptionId,
				P.CreatedDateTime AS PrescriptionDate,
				(SELECT (FirstName + ' ' + LastName) AS Name From sHrm.tEmployeeMaster Where Id=E.DoctorEmployeeId AND  ISNULL(IsOtherUser,0) = 0
					) AS DoctorName
    
		FROM  sOrderEntry.tIssueReturn IR		
		INNER JOIN sOrderEntry.tIssueReturnDetail IRD
		ON IR.Id = IRD.IssueReturnId
		INNER JOIN sIp.tStoreLocationMaster LM
		ON IR.ToStoreLocationId = LM.Id
		INNER JOIN sPharmacy.tDispenseBatch DB
		ON DB.Id=IRD.DispenseBatchId 
		INNER JOIN sProcurement.tStockBatch SB
		ON SB.Id=DB.StockBatchId  
		INNER JOIN sIp.tStockItemMaster SIM
		ON SB.StockItemId  = SIM.Id
		INNER JOIN sPharmacy.tDispense D
		ON D.Id=DB.DispenseId
		INNER JOIN sExamination.tPrescriptionDetail PD
		ON PD.Id=D.PrescriptionDetailId
		INNER JOIN sExamination.tPrescription P
		ON P.Id=PD.PrescriptionId
		 INNER JOIN sExamination.tExamination E
		ON P.SourceId=E.Id
		 --INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=E.ParticipantSourceId
		LEFT JOIN sCommon.tReasonMaster RM
		ON RM.Id = IRD.ReasonId
	 	
		 
		WHERE IR.Id = @rId 
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceCostAdd]
	@rId int,
	@rServiceId int,
	@rServiceCost decimal(6,2), 
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 
IF(@rId = 0) 
 BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 0, 'sOrderEntry.tServiceCost', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sOrderEntry.tServiceCost
		(
			Id,		
			ServiceId,			
			ServiceCost,
			StoreLocationId 
		)
	VALUES
		(
			 @lNextNumber,
			 @rServiceId,
			 @rServiceCost,
			 @rStoreLocationId
		)
			SELECT @lNextNumber AS RESULT
END
ELSE
BEGIN
 UPDATE sOrderEntry.tServiceCost
		SET	 ServiceCost=@rServiceCost
	  WHERE ServiceId = @rServiceId AND StoreLocationId=@rStoreLocationId
	  SELECT @rId AS RESULT
END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceCostGet]
	 
	@rStoreLocationId int,
	@rOrgId int  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
SELECT  ISNULL(SC.Id,0) AS ServiceCostId,
		SM.Id AS ServiceId,
 		SM.Code,
		SM.Title,
		ISNULL(SC.ServiceCost,0) AS  ServiceCost

from sOrderEntry.tServiceMaster SM
LEFT JOIN sOrderEntry.tServiceCost SC
 ON SM.Id=SC.ServiceId AND SC.StoreLocationId=@rStoreLocationId
 
 WHERE SM.IsObsolete=0
 AND SM.OrgId = @rOrgId
 
 --WHERE SC.StoreLocationId=@rStoreLocationId
	         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceDetailAdd_old]
	@rOrgId int,
	@rServiceParameterId [int],
	@rServiceId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sOrderEntry.tServiceDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sOrderEntry.tServiceDetail
		(
			[Id]
			,ServiceId
           ,[ServiceParameterId]
          
		)
	VALUES
		(
			@lNextNumber,
			@rServiceId,
			@rServiceParameterId			 
		)
		
	    BEGIN
			  SELECT 1 AS Result
		    END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceItemRemove]
	@rServiceId [int],
	@rStoreLocationId int,
	@rStockItemId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 DECLARE @lServiceCostId int = 0
	 SELECT @lServiceCostId=Id FROM sOrderEntry.tServiceCost WHERE ServiceId=@rServiceId AND StoreLocationId=@rStoreLocationId 
	 
	 DELETE FROM sOrderEntry.tServiceItemSetup WHERE ServiceCostId=@lServiceCostId AND StockItemId=@rStockItemId 
	 
	 SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceItemSetupAdd]
	@rId int,
	@rItemConsumptionQuantity decimal(6,2), 
	@rStockItemId int,
	@rServiceId int,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lServiceCostId int
	SELECT @lServiceCostId=Id FROM sOrderEntry.tServiceCost	WHERE ServiceId=@rServiceId AND StoreLocationId=@rStoreLocationId 
 
IF(@rId = 0) 
 BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 0, 'sOrderEntry.tServiceItemSetup', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sOrderEntry.tServiceItemSetup
		(
			Id,		
			ServiceCostId,			
			StockItemId,
			ItemConsumptionQuantity 
		)
	VALUES
		(
			 @lNextNumber,
			 @lServiceCostId,
			 @rStockItemId,
			 @rItemConsumptionQuantity
		)
			SELECT @lNextNumber AS RESULT
END
ELSE
BEGIN
 UPDATE sOrderEntry.tServiceItemSetup
		SET	 ItemConsumptionQuantity=@rItemConsumptionQuantity
	  WHERE ServiceCostId = @lServiceCostId AND StockItemId=@rStockItemId
	  SELECT @rId AS RESULT
END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceItemSetupGet]
	 
	@rStoreLocationId int,
	@rServiceId int  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lServiceCostId int = 0
	DECLARE @lLocationId int = 0
IF(@rServiceId > 0)
BEGIN

	SELECT @lServiceCostId=Id FROM sOrderEntry.tServiceCost WHERE ServiceId=@rServiceId AND StoreLocationId=@rStoreLocationId 
	SELECT @lLocationId =LocationId from sIp.tStoreLocationMaster WHERE Id=@rStoreLocationId 
	END
	
BEGIN
SELECT ISNULL(SIS.Id,0) AS Id,
	   ISNULL(SIS.ServiceCostId,0) AS ServiceCostId,
	   SIM.Id AS StockItemId,
	   ISNULL(SIS.ItemConsumptionQuantity,0) AS ItemConsumptionQuantity,
	   SIM.Code,
	   SIM.Title AS Name ,
	   SIM.Isobsolete
		FROM sIp.tStockItemMaster SIM
		INNER JOIN sOrderEntry.tServiceItemSetup SIS 
		ON SIS.StockItemId=SIM.Id AND (ServiceCostId=@lServiceCostId)
		
		WHERE 
	          SIM.IsObsolete=0 AND SIM.LocationId = @lLocationId
	          
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceItemSetupmasterGet]
	 
	@rStoreLocationId int  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
SELECT  ISNULL(SC.Id,0) AS ServiceCostId,
		SM.Id AS ServiceId,
 		SM.Code,
		SM.Title,
		ISNULL(SC.ServiceCost,0) AS  ServiceCost

from sOrderEntry.tServiceMaster SM
INNER JOIN sOrderEntry.tServiceCost SC
 ON SM.Id=SC.ServiceId AND SC.StoreLocationId=@rStoreLocationId
 
 WHERE SM.IsObsolete=0
 
 --WHERE SC.StoreLocationId=@rStoreLocationId
	         
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To add records to sOrderEntry.tServiceItemTypeMaster table
	Created date     : 29 Apr 2009
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Changed By and Date
	Test script      : EXECUTE sOrderEntry.pServiceItemTypeMasterAdd @rCode = 0, @rTitle = 0, @rIsObsolete = 0, @rCreatedUserId = 0
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceItemTypeMasterAdd]
	(
		@rCode Nvarchar(10),
		@rTitle Nvarchar(50),
		@rIsObsolete Bit,
		@rCreatedUserId BigInt
	)
AS

SET NOCOUNT ON

BEGIN
	INSERT INTO sOrderEntry.tServiceItemTypeMaster
		(
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate()
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To get records from sOrderEntry.tServiceItemTypeMaster table
	Created date     : 29 Apr 2009
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Update sp with order by
	Test script      : EXECUTE sOrderEntry.pServiceItemTypeMasterGet @rID = 0, @rCode = ''
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceItemTypeMasterGet]
	(
		@rId int = 0,
		@rCode Nvarchar(10) = ''
	)
AS

SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserID,
			UpdatedDateTime
	   FROM sOrderEntry.tServiceItemTypeMaster
	  WHERE ((Id = @rId) OR (@rId = 0))
	  AND ((Code = @rCode) OR (@rCode = ''))
	  ORDER BY Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To modify records in sOrderEntry.tServiceItemTypeMaster table
	Created date     : 29 Apr 2009
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Changed By and Date
	Test script      : EXECUTE sOrderEntry.pServiceItemTypeMasterModify @rId = 0, @rCode = 0, @rTitle = 0, @rIsObsolete = 0, @rUpdatedUserId = 0
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceItemTypeMasterModify]
	(
		@rId SmallInt,
		@rCode Nvarchar(10),
		@rTitle Nvarchar(50),
		@rIsObsolete Bit,
		@rUpdatedUserId BigInt
	)
AS

SET NOCOUNT ON

BEGIN
	 UPDATE sOrderEntry.tServiceItemTypeMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserID = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceMasterAdd]
	
	@rCode [nvarchar](30),
	@rTitle [nvarchar](100), 
	@rServiceSubGroupId [int],	
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rOrgId [int],
	@rId [int]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 
	IF NOT EXISTS(SELECT 1 FROM sOrderEntry.tServiceMaster Where Id = @rId)	
	BEGIN 
	 INSERT INTO [sOrderEntry].[tServiceMaster]
           (
            [Id]
           ,[Code]
           ,[Title]
           ,[ServiceSubGroupId]
           ,[IsObsolete]
           --,[ServiceAreaId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,OrgId
           )
     VALUES
           (
            @rId
           ,@rCode 
           ,@rTitle 
           ,@rServiceSubGroupId 
           ,@rIsObsolete 
           --,@lAreaNextNumber 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rOrgId
           
          )
          
	END
	
	ELSE
	
	BEGIN
	 
		UPDATE sOrderEntry.tServiceMaster 
		SET 
					
			--[Id]	=	@lNextNumber
            [Code]	=	@rCode
           ,[Title]	=	@rTitle          
           ,[ServiceSubGroupId]	=	@rServiceSubGroupId
           ,[IsObsolete]	=	@rIsObsolete			
		   ,UpdatedUserId=@rCreatedUserId
		   ,UpdatedDateTime=sCommon.fGetDate()			
			WHERE 
			  Id = @rId
				  --Title=@rTitle	  
	END	 
	  
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceModify_Old]
	--@rCode [nvarchar](30),
	@rTitle [nvarchar](100),
	@rRemark [nvarchar](200),
	@rServiceSubGroupId [int],	
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rId int,
	@rOrgId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sOrderEntry.tServiceParameterMaster
		SET 
		    --[Code] = @rCode
            [Title] = @rTitle         
           ,[ServiceSubGroupId] = ServiceSubGroupId
		   ,IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  BEGIN
		  DELETE FROM sOrderEntry.tServiceParameterDetail
		  WHERE  ServiceParameterId=@rId
		END
	  BEGIN
		  SELECT 1 AS Result
	  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To add records to sOrderEntry.tServiceCategoryMaster table
	Created date     : 22 Apr 2009
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Changed By and Date
	Test script      : EXECUTE sOrderEntry.pServiceCategoryMasterAdd @rServiceItemTypeId = 0, @rCode = 0, @rTitle = 0, @rIsObsolete = 0, @rCreatedUserId = 0
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceSubGroupMasterAdd]
	(   
	    @rOrgId int,
		@rServiceMainGroupId int,
		@rCode Nvarchar(100),
		@rTitle Nvarchar(100),
		@rIsObsolete Bit,
		@rCreatedUserId BigInt 
	)
AS

SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber bigint	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sOrderEntry.tServiceSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sOrderEntry.tServiceSubGroupMaster
		(
			Id,		 
			ServiceMainGroupId,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,			 
			@rServiceMainGroupId,
			@rCode,
			@rTitle,
			@rIsObsolete, 
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To get records from sOrderEntry.tServiceCategoryMaster table
	Created date     : 22 Apr 2009
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Added IsObsoleteYN filed
	Test script      : EXECUTE sOrderEntry.pServiceCategoryMasterGet @rId = 0, @rCode = '', @rTitle = ''
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceSubGroupMasterGet]
	(
		@rId SmallInt = 0,
		@rCode Nvarchar(10) = '',
		@rTitle Nvarchar(50) = '',
		@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN

SET @rCode = sCommon.fSearchStringGet(@rCode)
SET @rTitle = sCommon.fSearchStringGet(@rTitle)

	 SELECT SCM.Id,
			SCM.ServiceMainGroupId,
			SCM.Code,
			SCM.Title,			 
			SIM.Title AS ServiceSubGroupTitle, 
			SCM.IsObsolete, 
			(CASE SCM.IsObsolete WHEN '0' THEN 'N' ELSE 'Y' END) AS IsObsoleteYN
	   FROM sOrderEntry.tServiceMainGroupMaster SIM	
	   INNER JOIN sOrderEntry.tServiceSubGroupMaster SCM	
	   ON SCM.ServiceMainGroupId = SIM.Id
	  WHERE ((SCM.Id = @rId) OR (@rId = 0))
	        AND ((SCM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	        AND ((SCM.Title LIKE @rTitle ) OR (ISNULL(@rTitle, '') = ''))
	        AND (SIM.OrgId = @rOrgId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To modify records in sOrderEntry.tServiceCategoryMaster table
	Created date     : 22 Apr 2009
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Changed By and Date
	Test script      : EXECUTE sOrderEntry.pServiceCategoryMasterModify @rId = 0, @rServiceItemTypeId = 0, @rCode = 0, @rTitle = 0, @rIsObsolete = 0, @rUpdatedUserId = 0
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sOrderEntry].[pServiceSubGroupMasterModify]
	(
		@rId int,
		@rServiceMainGroupId int,
		@rCode Nvarchar(10),
		@rTitle Nvarchar(50),
		@rIsObsolete Bit,
		@rUpdatedUserId BigInt
	)
AS

SET NOCOUNT ON

BEGIN

	 UPDATE sOrderEntry.tServiceSubGroupMaster
		SET 
			ServiceMainGroupId = @rServiceMainGroupId,
			Code = @rCode,
			Title = @rTitle,
			UpdatedUserId = @rUpdatedUserId,
			IsObsolete = @rIsObsolete, 
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestDetailAdd]
	@rOrgId int,
	@TestParameterId [int],
	@rTestMasterId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sOrderEntry.tTestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sOrderEntry.tTestDetail
		(
			[Id]
			,TestId
           ,[TestParameterId]
           ,IsObsolete
       
          
		)
	VALUES
		(
			@lNextNumber,
			@rTestMasterId,
			@TestParameterId,
			0
	 
					 
		)
		
	    BEGIN
     SELECT 1 AS Result
   END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestDetailGet]
	--@rTestParameterId  int = 0
	   @rTestMasterId int = 0
	  
	--@rItemCode [nvarchar](10) = '',
	--@rItemDescription [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT SD.Id AS TestDetailId,
			SD.TestParameterId,
			SD.TestId AS TestMasterId,
			SPM.Title AS TestParameter,
			pvt.Title AS ParameterType 
			--sOrderEntry.tTestParameterDetail.IsObsolete,
			
	   FROM   sOrderEntry.tTestDetail SD INNER JOIN sOrderEntry.tTestParameterMaster SPM ON SPM.Id = SD.TestParameterId  			    
	          INNER JOIN sOrderEntry.tParameterValueTypeMaster pvt ON pvt.Id =  SPM.ParameterValueTypeId    	   
    			 							
	  WHERE		SD.IsObsolete = 0 AND
				((SD.TestId = @rTestMasterId) OR (@rTestMasterId = 0))
				--AND SD.OrgId = @rOrgId
				--AND ((sIp.vExtStockItemMaster.Code = @rItemCode) OR (ISNULL(@rItemCode, '') = ''))
				--AND ((sIp.vExtStockItemMaster.Title = @rItemDescription) OR (ISNULL(@rItemDescription, '') = ''))				
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestDetailModify]
	@rId [int],
	@rTestParameterId [int],
    @rTestId int,
	@rIsObsolete [bit]
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sOrderEntry.tTestDetail
		SET 
			TestParameterId = @rTestParameterId,
		  	TestId = @rTestId,		   
			IsObsolete = @rIsObsolete
			 
	  WHERE Id = @rId 
	  
	  BEGIN
		  SELECT 1 AS Result
	  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestMasterAdd]
	
	@rCode [nvarchar](30),
	@rTitle [nvarchar](100), 
	@rServiceSubGroupId [int],	
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rOrgId [int],
	@rId [int]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lNextNumber BIGINT
	DECLARE @Id BIGINT
	DECLARE @TestId BIGINT

--SET @rOrgId = 0
	IF @rId = 0		
	BEGIN
	
	 --DECLARE @lAreaNextNumber BIGINT     
	 --EXECUTE @lAreaNextNumber = sCommon.pTableRowIdGet 0,'sExamination.tAreaMaster', 0, 1, 1
	
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sOrderEntry.tServiceMaster',0,1, 1,@outNextNumber = @lNextNumber output
	
	 INSERT INTO [sOrderEntry].[tTestMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[ServiceSubGroupId]
           ,[IsObsolete]
           --,[ServiceAreaId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,OrgId
           )
     VALUES
           (
            @lNextNumber 
           ,@rCode 
           ,@rTitle 
           ,@rServiceSubGroupId 
           ,@rIsObsolete 
           --,@lAreaNextNumber 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rOrgId           
          )
          
          BEGIN
	        
	         	INSERT INTO sExamination.tAreaMaster
						(
							Id,
							Title,
							Remark,
							AreaTypeId,
							IsObsolete,
							PagePath,
							OrgId,
							AreaGroupId,
							ImagePath
						)
					VALUES
						(
							@lNextNumber,
							@rTitle,
							'p',
							'1',
							'false',
							'~/Pages/Examination/ServiceResult.aspx?ServiceAreaId=' +  ltrim(str(@lNextNumber)),
						    @rOrgId,
						    4,
						    '~/Images/Icon 16x16/icon_outpatient.gif'							
						)	           
	                 
	    END
       
	END
	
	ELSE
	
	BEGIN
	
	     BEGIN
			
			UPDATE sExamination.tAreaMaster 
			SET Title = @rTitle,
			    IsObsolete = @rIsObsolete
			WHERE Id =  @rId AND OrgId = @rOrgId
	     END   
	    
	    SET  @lNextNumber = @rId
		UPDATE sOrderEntry.tTestMaster 
		SET 					
			--[Id]	=	@lNextNumber
            [Code]	=	@rCode
           ,[Title]	=	@rTitle          
           ,[ServiceSubGroupId]	=	@rServiceSubGroupId
           ,[IsObsolete]	=	@rIsObsolete			
		   ,UpdatedUserId=@rCreatedUserId
		   ,UpdatedDateTime=sCommon.fGetDate()			
			WHERE 
			  Id = @rId
				  --Title=@rTitle	  
	END	 
	  BEGIN
	     EXECUTE sOrderEntry.pServiceMasterAdd
			    @rCode,
				@rTitle, 
				@rServiceSubGroupId,	
				@rIsObsolete,
				@rCreatedUserId,
				@rOrgId,
				@lNextNumber	     
	  END	
	
		 BEGIN
		  SET @Id=(SELECT ISNULL(Id,0) as Id
					FROM sOrderEntry.tTestMaster
					WHERE Title=@rTitle AND OrgId = @rOrgId)
		  IF @Id != 0 
			  BEGIN
				SET @TestId=@Id
			  END
		  ELSE
			  BEGIN
				SET @TestId=@lNextNumber
			  END
		  BEGIN
			  DELETE FROM sOrderEntry.tTestDetail
				  WHERE TestId=@TestId
		  END
		  IF @Id != 0 
			  BEGIN
				SELECT @Id AS Result
			  END
		  ELSE
			  BEGIN
				SELECT @lNextNumber AS Result
			  END
			  --SELECT @lNextNumber AS Result
			 
		 
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestMasterForRequestGet]
	
	@rOrgId int,
	@rId [bigint],
	@rCurrentAlphabet nvarchar(10),
	@rServiceMainGroupId int,
	@rSubGroupId int = 0
	 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		 
	 SELECT  SM.Id AS Id,
	         SM.Code,
			 SM.Title,
			 SSM.ServiceMainGroupId,
			 SSM.Id AS SubgroupId,
			 SSM.Title AS SubGroup,
			 MGM.Title AS MainGroup,
			 AM.AreaTypeId
		 	  
	    FROM sOrderEntry.tServiceMaster SM
			--INNER JOIN  sOrderEntry.tTestMaster TM ON SM.Id = TM.Id
	        INNER JOIN sOrderEntry.tServiceSubGroupMaster SSM ON SM.ServiceSubGroupId = SSM.Id
	        INNER JOIN sOrderEntry.tServiceMainGroupMaster MGM ON MGM.Id = SSM.ServiceMainGroupId 
	        INNER JOIN sExamination.tAreaOrganizationMaster AOM ON AOM.AreaId=SM.Id 
	        INNER JOIN sExamination.tAreaMaster AM ON AM.Id = SM.Id 
	      
	   
	  WHERE AM.AreaTypeId = 1 AND ((SM.Id = @rId) OR (@rId = 0))   
	   AND ((SM.Title Like @rCurrentAlphabet + '%') OR (ISNULL(@rCurrentAlphabet,'')=''))
	   AND ((SSM.ServiceMainGroupId = @rServiceMainGroupId) OR (ISNULL(@rServiceMainGroupId,0)=0)) 
	   AND ((SSM.Id = @rSubGroupId) OR (@rSubGroupId = 0)) AND AOM.OrgId = @rOrgId
	   AND SM.OrgId = @rOrgId
	   
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestMasterGet]
	
	@rId [int] = 0,
	@rCode nvarchar(30)='',
	@rTitle [nvarchar](30) = '',
	@rOrgId int 
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		 
        --SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle) 
    
      		 
	 SELECT SM.Id,	        	       		
			SM.Code,  		 
			SM.Title,  			 
			SM.IsObsolete, 
			CASE WHEN SM.IsObsolete = 1 THEN 'Y'
				    ELSE 'N'
			END AS IsObsoleteValue,			 
			 SSM.ServiceMainGroupId AS MainGroupId,
			 SSM.Id AS ServiceSubGroupId,
			 SSM.Title AS SubGroup,
			 MGM.Title AS MainGroup,
			 AM.AreaTypeId	    
		    
		  FROM sOrderEntry.tTestMaster SM INNER JOIN sOrderEntry.tServiceSubGroupMaster SSM 
		  ON SM.ServiceSubGroupId = SSM.Id INNER JOIN sOrderEntry.tServiceMainGroupMaster MGM 
		  ON MGM.Id = SSM.ServiceMainGroupId  INNER JOIN sExamination.tAreaMaster AM ON AM.Id = SM.Id 
		  --INNER JOIN sOrderEntry.tTestDetail SD ON SM.Id = SD.TestId 
		  --INNER JOIN sOrderEntry.tTestParameterMaster SPM ON SD.TestParameterId = SPM.Id 
		  WHERE ((SM.Id = @rId) OR (@rId = 0)) 		 
				AND ((SM.Code = @rCode) OR (@rCode = ''))
				AND ((SM.Title Like '%' + @rTitle + '%') OR (@rTitle = ''))
				AND SM.OrgId = @rOrgId
				
		
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestMasterListGet]
	@rId [int] = 0,
	@rCode nvarchar(30)='',
	@rTitle [nvarchar](30) = '',	 
	@rServiceMainGroupId int = 0,
	@rServiceSubGroupId int = 0,
	@rOrgId int
	  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

        SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle) 


	 SELECT SM.Id AS TestId,			
			SM.Code AS TestCode,  		 
			SM.Title AS TestName, 	 
			SM.IsObsolete,
			SM.ServiceSubGroupId,		 
			CASE WHEN SM.IsObsolete = 1 THEN 'Y'
				    ELSE 'N'
			END AS IsObsoleteValue,		 
			SMM.Title AS MainGroup,
			SSG.Title AS SubGroup
			--TR.TestId AS TestRequestTestId
 
	  FROM sOrderEntry.tTestMaster SM  
	  INNER JOIN sOrderEntry.tServiceSubGroupMaster SSG ON SSG.Id = SM.ServiceSubGroupId 
	  INNER JOIN sOrderEntry.tServiceMainGroupMaster SMM ON SMM.Id = SSG.ServiceMainGroupId
	  --INNER JOIN sExamination.tTestRequest TR ON TR.TestId = SM.Id
	  
	  WHERE ((SM.Id = @rId) OR (@rId = 0)) 		 
			AND ((SM.Code Like  @rCode + '%') OR (@rCode = ''))
			AND ((SM.Title Like @rTitle + '%') OR (@rTitle = ''))		 
			AND ((SSG.ServiceMainGroupId = @rServiceMainGroupId) OR (@rServiceMainGroupId = 0))
			AND ((SSG.Id = @rServiceSubGroupId) OR (@rServiceSubGroupId = 0))
			AND SM.OrgId = @rOrgId
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestMasterModify]
	--@rCode [nvarchar](30),
	@rTitle [nvarchar](100), 
	@rServiceSubGroupId [int],	
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rId int,
	@rOrgId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sOrderEntry.tTestMaster
		SET 
		    --[Code] = @rCode
            [Title] = @rTitle         
           ,[ServiceSubGroupId] = @rServiceSubGroupId
		   ,IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  BEGIN
		  DELETE FROM sOrderEntry.tTestDetail
		  WHERE  TestId=@rId
		END
		
IF(@rIsObsolete = 1)
BEGIN
UPDATE sOrderEntry.tServiceMaster Set IsObsolete=@rIsObsolete where Id=@rId
UPDATE sExamination.tAreaMaster Set IsObsolete=@rIsObsolete where Id=@rId
END		
	  BEGIN
		  SELECT 1 AS Result
	  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParameterAdd]
	
	@rCode [nvarchar](30),
	@rTitle [nvarchar](100),
	@rRemark [nvarchar](200),
	@rSampleId [int],
	@rClinicalUOM nvarchar(50),
	@rParameterValueTypeId [int],
	@rListValueTypeId [int],
	@rNumericFormat [nvarchar](30),
	@rServiceSubGroupId [int],	
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rOrgId [int],
	@rId [int]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lNextNumber BIGINT
	DECLARE @Id BIGINT
	DECLARE @TestParameterId BIGINT


	UPDATE sOrderEntry.tTestParameterMaster 
		SET 
					
			--[Id]	=	@lNextNumber
            [Code]	=	@rCode
           ,[Title]	=	@rTitle
           ,[Remark]	=	@rRemark
           ,[SampleId]	=	@rSampleId
           ,[ClinicalUOM]	=	@rClinicalUOM
           ,[ParameterValueTypeId]	=	@rParameterValueTypeId
           ,[ListValueTypeId]	=	@rListValueTypeId
           ,[NumericFormat]	=	@rNumericFormat
           ,[ServiceSubGroupId]	=	@rServiceSubGroupId
           ,[IsObsolete]	=	@rIsObsolete			
		   ,UpdatedUserId=@rCreatedUserId
		   ,UpdatedDateTime=sCommon.fGetDate()			
			WHERE 
			  Id = @rId

SELECT @Id AS Result
	--IF @rId = 0		
	--BEGIN
	
	--EXECUTE sCommon.pTableRowIdGet @rOrgId,'sOrderEntry.tTestParameterMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	--  INSERT INTO sOrderEntry.tTestParameterMaster
	--	(
	--		[Id]
 --          ,[Code]
 --          ,[Title]
 --          ,[Remark]
 --          ,[SampleId]
 --          ,[ClinicalUOM]
 --          ,[ParameterValueTypeId]
 --          ,[ListValueTypeId]
 --          ,[NumericFormat]
 --          ,[ServiceSubGroupId]
 --          ,[IsObsolete]
 --          ,[CreatedUserId]
 --          ,[CreatedDateTime]
 --          ,[UpdatedUserId]
 --          ,[UpdatedDateTime] 
 --          ,OrgId
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		@rCode,
	--		@rTitle,
	--		@rRemark,
	--		@rSampleId,
	--		@rClinicalUOM,
	--		@rParameterValueTypeId,
	--		@rListValueTypeId,
	--		@rNumericFormat,
	--		@rServiceSubGroupId,	
	--		@rIsObsolete,
	--		@rCreatedUserId,
	--		sCommon.fGetDate(),
	--		@rCreatedUserId,
	--		sCommon.fGetDate(),
	--		@rOrgId 
	--	)
	--END
	
	--ELSE
	
	--BEGIN
	
	--	UPDATE sOrderEntry.tTestParameterMaster 
	--	SET 
					
	--		--[Id]	=	@lNextNumber
 --           [Code]	=	@rCode
 --          ,[Title]	=	@rTitle
 --          ,[Remark]	=	@rRemark
 --          ,[SampleId]	=	@rSampleId
 --          ,[ClinicalUOM]	=	@rClinicalUOM
 --          ,[ParameterValueTypeId]	=	@rParameterValueTypeId
 --          ,[ListValueTypeId]	=	@rListValueTypeId
 --          ,[NumericFormat]	=	@rNumericFormat
 --          ,[ServiceSubGroupId]	=	@rServiceSubGroupId
 --          ,[IsObsolete]	=	@rIsObsolete			
	--	   ,UpdatedUserId=@rCreatedUserId
	--	   ,UpdatedDateTime=sCommon.fGetDate()			
	--		WHERE 
	--		  Id = @rId
	--			  --Title=@rTitle	  
	--END	 
	--	 BEGIN
	--	  SET @Id=(SELECT ISNULL(Id,0) as Id
	--				FROM sOrderEntry.tTestParameterMaster
	--				WHERE Title=@rTitle AND OrgId = @rOrgId)
	--	  IF @Id != 0 
	--		  BEGIN
	--			SET @TestParameterId=@Id
	--		  END
	--	  ELSE
	--		  BEGIN
	--			SET @TestParameterId=@lNextNumber
	--		  END
	--	  BEGIN
	--		  DELETE FROM sOrderEntry.tTestParameterDetail
	--			  WHERE TestParameterId=@TestParameterId
	--	  END
	--	  IF @Id != 0 
	--		  BEGIN
	--			SELECT @Id AS Result
	--		  END
	--	  ELSE
	--		  BEGIN
	--			SELECT @lNextNumber AS Result
	--		  END
	--		  SELECT @lNextNumber AS Result
			 
		 
--END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParameterDetailAdd]
	@rOrgId int,
	@rTestParameterId [int],
	@rGenderId [int],
	@rAgeFrom [int],
	@rAgeTo [int],
	@rMinimun Decimal(12,4),
	@rMaximum Decimal(12,4),
	@rRemark [nvarchar](100),
	@rDiagnosisRemark nvarchar(100) = NULL,
	@rRecommendationRemark nvarchar(100) = NULL,
	@rIsNormal bit = NULL
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sOrderEntry.tTestParameterDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sOrderEntry.tTestParameterDetail
		(
			[Id]
           ,[TestParameterId]
           ,[GenderId]
           ,[AgeFrom]
           ,[AgeTo]
           ,[Minimum]
           ,[Maximum]
           ,[Remark]            
           ,IsObsolete
           ,IsNormal
           ,Diagnosis
           ,Recommendation
      
		)
	VALUES
		(
			@lNextNumber,
			@rTestParameterId,
			@rGenderId,
			@rAgeFrom,
			@rAgeTo,
			@rMinimun,
			@rMaximum,
			@rRemark,		     
		    0,
		    @rIsNormal,
		    @rDiagnosisRemark,
		    @rRecommendationRemark
		 	    		    
		)
		
	    BEGIN
			  SELECT 1 AS Result
		    END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParameterDetailGet]
	@rTestParameterId  int = 0
	--,
	--@rItemCode [nvarchar](10) = '',
	--@rItemDescription [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT SPD.Id,
			SPD.TestParameterId,
			SPD.GenderId,
			SPD.AgeFrom,
			SPD.AgeTo,
			SPD.Minimum,
			SPD.Maximum,
			SPD.Remark,
			SPD.IsObsolete,			
			GM.Title As Gender,
			ISNULL(SPD.Diagnosis,'') AS DiagnosisRemark,
			ISNULL(SPD.Recommendation,'') AS RecommendationRemark,
			ISNULL(SPD.IsNormal,0) as IsNormal
			
			--sOrderEntry.tTestParameterDetail.IsObsolete,
			
	   FROM   sOrderEntry.tTestParameterDetail SPD	   			    
	    	    INNER JOIN sCommon.tGenderMaster GM
    			ON SPD.GenderId = GM.Id									
	  WHERE		 SPD.IsObsolete = 0 AND
				 ((SPD.TestParameterId = @rTestParameterId) OR (@rTestParameterId = 0))
				--AND ((sIp.vExtStockItemMaster.Code = @rItemCode) OR (ISNULL(@rItemCode, '') = ''))
				--AND ((sIp.vExtStockItemMaster.Title = @rItemDescription) OR (ISNULL(@rItemDescription, '') = ''))
				
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParameterDetailModify]
	@rId [int],
	@rTestParameterId [int] = 0,
	@rGenderId [int],
	@rAgeFrom [smallint],
	@rAgeTo [smallint],	
	@rRemark nvarchar(100),
	@rMinimum Decimal(12,4),
	@rMaximum Decimal(12,4),	 
	--@rLessDiagnosisRemark nvarchar(100),
	--@rMoreDiagnosisRemark nvarchar(100),
	--@rLessRecommendationRemark nvarchar(100),
	--@rMoreRecommendationRemark nvarchar(100),
	@rIsObsolete [bit],
	@rDiagnosisRemark nvarchar(300) = NULL,
	@rRecommendationRemark nvarchar(300) = NULL,
	@rIsNormal bit = NULL
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sOrderEntry.tTestParameterDetail
		SET 
			--TestParameterId = @rTestParameterId,
		 
			Minimum = @rMinimum,			
			Maximum = @rMaximum 	 
		   --,LessDiagnosisRemark = @rLessDiagnosisRemark
     --      ,MoreDiagnosisRemark = @rMoreDiagnosisRemark
     --      ,LessRecommendationRemark = @rLessRecommendationRemark
     --      ,MoreRecommendationRemark = @rMoreRecommendationRemark
           ,IsNormal = @rIsNormal
           ,Diagnosis = @rDiagnosisRemark
           ,Recommendation = @rRecommendationRemark
 	  WHERE Id = @rId 
	  
	  BEGIN
		  SELECT 1 AS Result
	  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParameterGet]
	@rId [int] = 0,
	@rCode nvarchar(100)='',
	@rTitle [nvarchar](100) = '',
     @rOrgId int
	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

        --SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle) 


	 SELECT SPM.Id,			
			SPM.Code,  		 
			SPM.Title,  
			Remark,
			SampleId,
			ClinicalUOM,
			SPM.IsObsolete,
			ParameterValueTypeId,
			ListValueTypeId,
			NumericFormat,
			CASE WHEN SPM.IsObsolete = 1 THEN 'Y'
				    ELSE 'N'
			END AS IsObsoleteValue,
			ServiceSubGroupId,
			SGM.ServiceMainGroupId AS ServiceMainGroupId,
			ISNULL(TD.TestParameterId,0) AS TestParameterId      
		    
		    
		  FROM sOrderEntry.tTestParameterMaster SPM INNER JOIN sOrderEntry.tServiceSubGroupMaster SGM ON SPM.ServiceSubGroupId = SGM.Id
		    LEFT JOIN sOrderEntry.tTestDetail TD ON TD.TestParameterId = SPM.Id
		  WHERE ((SPM.Id = @rId) OR (@rId = 0)) 		 
				AND ((SPM.Code = @rCode) OR (@rCode = ''))
				AND ((SPM.Title Like '%' + @rTitle + '%') OR (@rTitle = ''))
				AND SPM.OrgId = @rOrgId
			
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParameterListGet]
	@rId [int] = 0,
	@rCode nvarchar(30)='',
	@rTitle [nvarchar](30) = '',	 
	@rServiceMainGroupId int = 0,
	@rServiceSubGroupId int = 0,
	@rSampleId int = 0,
	@rTypeId int = 0,
	@rOrgId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

        SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rTitle = sCommon.fSearchStringGet(@rTitle) 
  
	 SELECT SPM.Id AS TestParameterId,			
			SPM.Code AS TestParameterCode,  		 
			SPM.Title AS ServiceName, 	 
			SPM.IsObsolete,
			SPM.ServiceSubGroupId,	
			SSG.Title AS SubGroup,	 
			CASE WHEN SPM.IsObsolete = 1 THEN 'Y'
				    ELSE 'N'
			END AS IsObsoleteValue,		 
			SMM.Title AS MainGroup,
			PVT.Title AS TypeName,
		    SM.Title AS SampleName,		
		    ISNULL(TD.TestParameterId,0) AS ParameterId 
		    --CASE WHEN (TD.TestParameterId = NULL) THEN 0
		    --ELSE 1 END AS IsEdit
		    
 
	  FROM sOrderEntry.tTestParameterMaster SPM INNER JOIN sExamination.tSampleMaster SM ON SM.Id = SPM.SampleId
	  INNER JOIN sOrderEntry.tParameterValueTypeMaster PVT ON PVT.Id = SPM.ParameterValueTypeId
	  INNER JOIN sOrderEntry.tServiceSubGroupMaster SSG ON SSG.Id = SPM.ServiceSubGroupId 	  
	  INNER JOIN sOrderEntry.tServiceMainGroupMaster SMM ON SMM.Id = SSG.ServiceMainGroupId 
	  LEFT JOIN sOrderEntry.tTestDetail TD ON TD.TestParameterId = SPM.Id AND TD.IsObsolete = 0
	  
	  WHERE ((SPM.Id = @rId) OR (@rId = 0)) 		 
			AND ((SPM.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((SPM.Title Like @rTitle + '%') OR (@rTitle = ''))	
			AND ((SPM.SampleId = @rSampleId)OR(@rSampleId = 0))
		    AND ((SPM.ParameterValueTypeId = @rTypeId)OR(@rTypeId = 0))	 
			AND ((SSG.ServiceMainGroupId = @rServiceMainGroupId) OR (@rServiceMainGroupId = 0))
			AND ((SSG.Id = @rServiceSubGroupId) OR (@rServiceSubGroupId = 0))
			AND SPM.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParameterModify]
	--@rCode [nvarchar](30),
	@rTitle [nvarchar](100),
	@rRemark [nvarchar](200),
	@rSampleId [int],
	@rClinicalUOM NVARCHAR(50),
	@rParameterValueTypeId [int],
	@rListValueTypeId [int],
	@rNumericFormat [nvarchar](30),
	@rServiceSubGroupId [int],	
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rId int,
	@rOrgId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sOrderEntry.tTestParameterMaster
		SET
		    --[Code] = @rCode
            [Title] = @rTitle
           ,[Remark] = @rRemark
           ,[SampleId] = @rSampleId
           ,[ClinicalUOM] = @rClinicalUOM
           ,[ParameterValueTypeId] = @rParameterValueTypeId
           ,[ListValueTypeId] = @rListValueTypeId
           ,[NumericFormat] = @rNumericFormat
           ,[ServiceSubGroupId] = @rServiceSubGroupId
		   ,IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	 -- BEGIN
		--  DELETE FROM sOrderEntry.tTestParameterDetail
		--  WHERE  TestParameterId=@rId
		--END
	  BEGIN
		  SELECT 1 AS Result
	  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParameterOrderIndexModify]
	 
	@rTestParameterId [int],
	@rTestMasterId int = 0,
	@rOrderIndex int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	UPDATE sOrderEntry.tTestDetail		
		SET  
		    OrderIndex = @rOrderIndex 
	    
	    WHERE TestParameterId = @rTestParameterId 
	    
     SELECT 1 AS Result 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sOrderEntry].[pTestParemeterOrderIndexGet]
	 
	 @rTestId int 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT  
			SD.TestParameterId,
			SD.TestId AS TestMasterId,
			SD.OrderIndex AS OrderIndex,
			TPM.Title
			--sOrderEntry.tTestParameterDetail.IsObsolete,
			
	  FROM   sOrderEntry.tTestDetail SD INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = SD.TestParameterId  
	  WHERE		 SD.IsObsolete = 0 AND
				 ((SD.TestId = @rTestId) OR (@rTestId = 0)) 
				--AND ((sIp.vExtStockItemMaster.Code = @rItemCode) OR (ISNULL(@rItemCode, '') = ''))
				--AND ((sIp.vExtStockItemMaster.Title = @rItemDescription) OR (ISNULL(@rItemDescription, '') = ''))				
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pAllElementPaySetupGet]
	  
	-- @rId int,
	 @rSourceId bigint=0,
	 @rPayrollId int=0,
	 @rPayrollYearId int=0
	 --@rSourceTypeId smallint,	
	 --@rEmployeeCode nvarchar(100),
	 --@rEmployeeName nvarchar(100),
	 --@rPayElementId int,
	
	 
	 
 WITH EXECUTE AS CALLER
AS
 SET NOCOUNT ON
 
BEGIN 



 SELECT 
		   ISNULL(PS.[ID],0) AS PaySetupId	  		  
		  ,PE.Id AS PayElementId
		  ,PS.SourceId
		  ,PE.Title  AS PayElementName
		  ,[Amount]
		  ,[Percentage]
		  ,ISNULL([ProcessOrder],0) AS ProcessOrder
		  ,ISNULL(PS.DefaultAmount,0) AS DefaultAmount
		  ,ISNULL(PS.[PayrollId],0) AS PayrollId	
		  ,PE.IsEmployeeSpecific      
	      ,PE.IsDepend
	      ,EM.Code
	      ,EM.EmployeeName
	     ,OM.Id AS OrgId
	      ,OM.DisplayTitle AS OrgName
		  ,PET.Title AS PayElementType
		  ,ISNULL(PS.Formula,'') As Formula
	     
	      
	FROM  sPayroll.tPayElement PE INNER JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId   AND PE.PayrollId=PS.PayrollId
		   INNER JOIN sHrm.vEmployeeCommonDetail Em ON Em.EmployeeId = PS.SourceId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
		   INNER JOIN sPayroll.tPayElementDefault PED ON PED.ID = PE.PayElementDefaultId
		   INNER JOIN sPayroll.tPayElementType PET ON PET.Id=PED.PayElementTypeId
		    WHERE (PS.PayrollId = @rPayrollId OR @rPayrollId = 0)   AND (PS.SourceId = @rSourceId OR @rSourceId = 0)    AND (PS.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0)

		   UNION 

		   SELECT 0 PaySetupId, PE.Id as PayElementId,0 SourceId,PE.Title AS PayElementName,
		   0 AS Amount,0 AS Percentage,0 AS ProcessOrder,0 AS DefaultAmount,
		   PayrollId,IsEmployeeSpecific,IsDepend
		   ,'' Code,'' EmployeeName,0 OrgId,'' OrgName ,PET.Title AS PayElementType
		   ,'' As Formula
		   FROM sPayroll.vPayElement PE
		   INNER JOIN sPayroll.tPayElementType PET ON PET.Id=PE.PayElementTypeId
		   WHERE IsObsolete = 0 AND PayrollId=@rPayrollId
		   AND PE.Id NOT IN(SELECT PayElementId FROM sPayroll.tPaySetup WHERE  (PayrollId = @rPayrollId OR @rPayrollId = 0)  AND (SourceId = @rSourceId OR @rSourceId = 0) AND (PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) )
		  
		    ORDER BY PayElementName


	

		
	--   SELECT 
	--	   ISNULL(PS.[ID],0) AS PaySetupId	  		  
	--	  ,PE.Id AS PayElementId
	--	  ,PS.SourceId
	--	  ,[Amount]
	--	  ,[Percentage]
	--	  ,ISNULL([ProcessOrder],0) AS ProcessOrder
	--	  ,ISNULL(PS.[PayrollId],0) AS PayrollId
	--      ,PE.Title  AS PayElementName
	--      ,PE.IsDepend
	--      ,EM.Code
	--      ,EM.EmployeeName
	--      ,OM.Id AS OrgId
	--      ,OM.DisplayTitle AS OrgName
	--     ,ISNULL(PS.DefaultAmount,0) AS DefaultAmount
	      
	--FROM  sPayroll.tPayElement PE INNER JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId  
	--	   INNER JOIN sHrm.vEmployeeCommonDetail Em ON Em.EmployeeId = PS.SourceId
	--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
		   
		  
 --  WHERE (PS.SourceId = @rSourceId OR @rSourceId = 0)
 --  AND (PS.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0)
 --  AND (PS.PayrollId = @rPayrollId OR @rPayrollId = 0)
 --        Order By EM.OrgId,EM.Code
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pCalculatePayrollAmount] 
	      	        
            @1PaypSetupId int,
            @1PayElementId int,
            @1Percentage DECIMAl(5,2),
            @1SourceId bigint,
            @1OrgGroupId int,
            @1EmployeeId bigint,
            @lNextNumber bigint,
            @rPayrollId int,
	        @rPayrollYearId int,
			@lFormula nvarchar(200),
            @1Result decimal(22,6) output          
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
      
      DECLARE @lTotalAmount Decimal(22,2)
      DECLARE @1DependPayElementId int   
      DECLARE @1COUNT INT
      DECLARE @1Amount Decimal(22,2)
      DECLARE @1IsDepend bit
      DECLARE @1DependPaySetupId int   
      DECLARE @1DependPercentage decimal(5,2)  
      DECLARE @1PayElementTypeId int
      DECLARE @1DependentTotal decimal(22,2)
      DECLARE @1IsDeduct bit
      
      BEGIN  
   
    DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	--mantis: 43241, start
	DECLARE @lIsRoundOffToWholeNumber nvarchar(50)
	DECLARE @lRoundOffToWholeNumber int
	SELECT @lIsRoundOffToWholeNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 248 AND SourceTypeId = 2010 AND SourceId = @1OrgGroupId
	
	IF (@lIsRoundOffToWholeNumber IS NULL) OR (@lIsRoundOffToWholeNumber = 'True')
		SET @lRoundOffToWholeNumber = 0
	ELSE
		SET @lRoundOffToWholeNumber = 2
	--mantis: 43241, end
      
		SET @lTotalAmount = 0   
      
        ----For Calculate EmployeeBasic
        --IF  EXISTS (Select 1 FROM sPayroll.tPaySetupDependent WHere PaySetupId = @1PaypSetupId AND DependentPayElementId = @lBasicPayElementId) AND   
        -- EXISTS(Select 1 FROM sPayroll.tPaySetup Where PayElementId = @lBasicPayElementId AND SourceId = @1EmployeeId   AND SourceTypeId = 95)
        --BEGIN   
        --    SELECT @lTotalAmount = ISNULL(Amount,0) from sPayroll.tPayProcessElement Where PayProcessEmployeeId = @lNextNumber AND PayElementId = @lBasicPayElementId
            
        --   SELECT @lTotalAmount,'Basic'
        --    --select Amount from sPayroll.tPayProcessElement Where PayProcessEmployeeId AND PayElementId
        --END
       
		CREATE TABLE #tmpDependPayElementDetail
		(
			Id INT IDENTITY (1, 1),
			DependPayElementId  int,
			ProgressOrder int,
			IsDeduct bit		 		
		)		
		INSERT INTO #tmpDependPayElementDetail		
		SELECT PayElementId,ProcessOrder,ISNULL(IsDeduct,0)  from sPayroll.tPaySetupDependent PSD INNER JOIN sPayroll.tPaySetup PS ON  
        DependentPayElementId = PayElementId WHERE PaySetupId = @1PaypSetupId AND PS.PayrollYearId = @rPayrollYearId
        AND SourceId = @1SourceId --AND SourceTypeId = 2020
        ORDER BY ProcessOrder DESC  
       
 
        
        SELECT @1COUNT = COUNT(*) FROM #tmpDependPayElementDetail
	    SET @1DependentTotal = 0
	      WHILE @1COUNT > 0
	        BEGIN	   
	          SET @1DependPayElementId = 0
	          SET @1Amount = 0.0
	          SET @1DependPercentage = 0
	          SET @1DependPaySetupId = 0 
	          SET @1PayElementTypeId = 0
	          
	           
	          
	           SELECT @1DependPayElementId = DependPayElementId,@1IsDeduct=IsDeduct FROM #tmpDependPayElementDetail WHERE Id = @1COUNT
	           SELECT @1DependPaySetupId = Id,@1DependPercentage = Percentage FROM sPayroll.tPaySetup PS WHERE PayElementId = @1DependPayElementId AND PS.PayrollYearId = @rPayrollYearId
	            AND SourceId = @1SourceId
	          SELECT @1Amount = AMOUNT from sPayroll.tPayProcessElement Where PayProcessEmployeeId = @lNextNumber AND PayElementId = @1DependPayElementId
	          
	           
	            
	           SELECT @1PayElementTypeId = PayElementTypeId FROM sPayroll.tPayElement Where Id = @1DependPayElementId  
	             
	           
	               IF EXISTS (SELECT 1 FROM sPayroll.tPaySetupDependent WHERE PaySetupId = @1DependPaySetupId)
	                BEGIN 	                   
	                   EXECUTE [sPayroll].[pCalculatePayrollAmount] @1DependPaySetupId,@1PayElementId,@1DependPercentage,@1SourceId,@1OrgGroupId,@1EmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@lFormula,@1Result OUTPUT
						
	                   IF(@1IsDeduct=0)
							SET @1DependentTotal = @1DependentTotal + ISNULL(@1Result,0)
					   ELSE
							SET @1DependentTotal = @1DependentTotal - ISNULL(@1Result,0)
							
	                END 
	               ELSE
	               BEGIN     
	                    IF(@1IsDeduct=0)    
							SET @1DependentTotal = ISNULL(@1DependentTotal,0) + ISNULL(@1Amount,0)	                  
						ELSE
							SET @1DependentTotal = ISNULL(@1DependentTotal,0) - ISNULL(@1Amount,0)	                  	
	               END  
	          
	            SET  @1COUNT = @1COUNT - 1               
	            
	        END	       
	        
			IF(@lFormula!='')
			BEGIN
			 
				SELECT   @lTotalAmount =   [sPayroll].[fCalculateDependentBasedOnFormula](@lFormula,@1DependentTotal)
				--SET @lTotalAmount = ROUND((@1DependentTotal * @1Percentage)/100,0)
            END
            ELSE
				SET @lTotalAmount = ROUND((@1DependentTotal * @1Percentage)/100,@lRoundOffToWholeNumber) --mantis: 43241

		    
		    SET @1Result = @lTotalAmount
	 
      END
      --SELECT * FROM #tmpDependPayElementDetail
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pCalculateStaticPayElement]

	        @rPayProcessEmployeeId bigint,
	        @rOrgGroupId int,
	        @rSalary DECIMAL(22,6),
	        @rSourceId bigint,
	        @rDeductionAmount DECIMAL(22,6),
	        @rPayrollId int,
	        @rPayrollYearId int,
			@lPayrollGroupId int =0,
			@rSalaryMonth tinyint = 0,
			@rSalaryYear smallint = 0,
			@rEmployeeId bigint = 0,
			@rIsAllow bit=0 --mantis: 40774

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lIsRoundOffToWholeNumber nvarchar(50)
	DECLARE @lRoundOffToWholeNumber int
	DECLARE @lProfessionalTaxAgeRestriction int

	SELECT @lProfessionalTaxAgeRestriction = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 406 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	SELECT @lIsRoundOffToWholeNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 248 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	IF (@lIsRoundOffToWholeNumber IS NULL) OR (@lIsRoundOffToWholeNumber = 'True')
		SET @lRoundOffToWholeNumber = 0
	ELSE
		SET @lRoundOffToWholeNumber = 2

	IF (@lProfessionalTaxAgeRestriction IS NULL) OR (LEN(@lProfessionalTaxAgeRestriction) = 0)
		SET @lProfessionalTaxAgeRestriction = 65

	BEGIN

	DECLARE @lNextNumber BIGINT
	DECLARE @1Basic DECIMAl(22,6)
	DECLARE @1PfSalaryLimit DECIMAL(22,6)
	DECLARE @1PayProcesdsElementId bigint
	DECLARE @1ESISalaryLimit DECIMAL(22,6)
    DECLARE @1Tax DECIMAL(22,6)
    --DECLARE @1EmployeePfAmount Decimal(22,6)
    DECLARE @1EmployeeESIAmount Decimal(22,6)
    DECLARE @1TotalDeductionAmount DECIMAL(22,6)

    DECLARE @1EmployeePfPercent DECIMAL(22,2)
    DECLARE @1EmployerPfPercent DECIMAL(22,2)
    DECLARE @1EmployerFpsPercent DECIMAL(22,2)
    DECLARE @1EmployeeESIPercent DECIMAL(22,2)
    DECLARE @1EmployerESIPercent DECIMAL(22,2)
    DECLARE @1EmployeePfAmount DECIMAL(22,2)
    DECLARE @1EmployerPfAmount DECIMAL(22,2)
    DECLARE @1AdminChargesPercent DECIMAL(22,2)
    DECLARE @1EdliPercent DECIMAL(22,3)
    DECLARE @1InspectionChargesPercent DECIMAL(22,3)


    DECLARE @lEmployerFpsPercent DECIMAL(22,2)
    DECLARE @lValuesforMax DECIMAL(22,2)
    DECLARE @1Max DECIMAL(22,2)
    DECLARE @lRestrictionEmployerFpsPercent DECIMAL(22,2)
    DECLARE @1Bal DECIMAL(22,2)
    DECLARE @lEmployerPfPercent DECIMAL(22,2)

	DECLARE @1Earning1EmployeePfAmount DECIMAL(22,2)  --add for mantis: 40774
	DECLARE @1Deduction1EmployeePfAmount DECIMAL(22,2)  --add for mantis: 40774

	SET @1Tax = 0.0
	SET @1EmployeePfAmount = 0.0
	SET @1EmployeeESIAmount = 0.0
	SET @1Basic = 0.0
	SET @1PfSalaryLimit = 0.0

	SET @1EmployeePfPercent = 0.0
    SET @1EmployerPfPercent = 0.0
    SET @1EmployerFpsPercent = 0.0
    SET @1AdminChargesPercent = 0.0
    SET @1EdliPercent = 0.0
    SET @1InspectionChargesPercent = 0.0


    SET @lEmployerFpsPercent = 0.0
    SET @lValuesforMax = 0.0
    SET @1Max = 0.0
    SET @lRestrictionEmployerFpsPercent = 0.0
    SET @1Bal = 0.0
    SET @lEmployerPfPercent = 0.0

    SET @1EmployeeESIPercent = 0.0
    SET @1EmployerESIPercent = 0.0

	SET @1Earning1EmployeePfAmount = 0.0  --add for mantis: 40774
	SET @1Deduction1EmployeePfAmount = 0.0  --add for mantis: 40774

    DECLARE @lPTPayElementId int
    DECLARE @lPFPayElementId int
    DECLARE @lBasicPayElementId int
    DECLARE @lESIPayElementId int
    DECLARE @1EmployeePfPercentEmpSetup DECIMAL(12,2)
	DECLARE @lEarning1PayElementId int	--Add for Mantis: 40774
	DECLARE @lDeduction1PayElementId int	--Add for Mantis: 40774

	SELECT @lPTPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	SELECT @lPFPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 56
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lESIPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 55
	SELECT @lEarning1PayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 41 --Add for Mantis: 40774
	SELECT @lDeduction1PayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 91 --Add for Mantis: 40774


	 --For Professional Tax
	IF EXISTS (SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId)
	BEGIN
	
		DECLARE @lDOB date 
		DECLARE @lMonthBeginDate date
		DECLARE @lMonthEndDate date
		DECLARE @lAge smallint
		DECLARE @lGenderId tinyint --mantis :27611

		SELECT @lDOB = DateOfBirth,@lGenderId=GenderId FROM sHrm.tEmployeePersonalDetail WHERE EmployeeId = @rEmployeeId	--mantis :27611	
		SET @lMonthBeginDate= CAST(CAST(@rSalaryYear AS varchar) + '-' + CAST(@rSalaryMonth AS varchar) + '-' + '1' AS date)		
		SET @lMonthEndDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lMonthBeginDate)+1,0))
		SET @lAge = [sCommon].[fAgeAtDate] (@lDOB,@lMonthEndDate)
		
		IF(@lAge <= @lProfessionalTaxAgeRestriction OR @lDOB is null)
		BEGIN
		DECLARE @lGrossBasic decimal(22,6)=0
		  --      Select * from sPayroll.tProfessionalTaxRange
		        
		  --      SELECT  TOP 1  Tax  FROM sPayroll.tProfessionalTaxRange 
				--where Salary < @rSalary Order By Salary Desc


      DECLARE @lConfigValueForPTCalculation nvarchar(50)=''
	  SELECT @lConfigValueForPTCalculation = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 378 AND SourceId = @rOrgGroupId

	  IF(@lConfigValueForPTCalculation  IS NOT NULL AND  @lConfigValueForPTCalculation!='')
	  BEGIN
		IF(@lConfigValueForPTCalculation ='TotalEarning')
		  BEGIN
				SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
				where Salary <= @rSalary AND PayrollYearId = @rPayrollYearId AND (isnull(GenderId,0)=@lGenderId OR isnull(GenderId,0)=0) Order By Salary Desc --mantis :27611
		        -- Professional Tax 
		        
		        IF @1Tax <> 0
		        BEGIN 
					SET @1Tax = ROUND(@1Tax,@lRoundOffToWholeNumber)
		        	UPDATE sPayroll.tPayProcessElement  
					SET AMOUNT = @1Tax
					WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId	 
		        END
		  END	
		  ELSE IF(@lConfigValueForPTCalculation ='GrossBasic')   
		  BEGIN  
		  
			  SELECT @lGrossBasic = ISNULL(SUM(GrossBasic),0) FROM sPayroll.tPayProcessEmployee WHERE ID =  @rPayProcessEmployeeId

			  SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
			  where Salary <= @lGrossBasic AND PayrollYearId = @rPayrollYearId AND (isnull(GenderId,0)=@lGenderId OR isnull(GenderId,0)=0) 
			  Order By Salary Desc --mantis :27611
		       
		        IF @1Tax <> 0
		        BEGIN 
					SET @1Tax = ROUND(@1Tax,@lRoundOffToWholeNumber)
		        	UPDATE sPayroll.tPayProcessElement  
					SET AMOUNT = @1Tax
					WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId	 
		        END
		  END
	  END
	  ELSE
	  BEGIN
	      
				SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
				where Salary <= @rSalary AND PayrollYearId = @rPayrollYearId AND (isnull(GenderId,0)=@lGenderId OR isnull(GenderId,0)=0) Order By Salary Desc --mantis :27611
		        -- Professional Tax 
		        
		        
		        IF @1Tax <> 0
		        BEGIN 
					SET @1Tax = ROUND(@1Tax,@lRoundOffToWholeNumber)
		        	UPDATE sPayroll.tPayProcessElement  
					SET AMOUNT = @1Tax
					WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId	 
		        END
	  END
	END
END

	 --For PfElement

	  IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId)
	  BEGIN
	  -- start for age calculation
	  DECLARE @lEmployeeId bigint = 0
	  DECLARE @lPayProcessId int = 0
	  DECLARE @lSalaryMonth tinyint = 0
	  DECLARE @lSalaryYear smallint = 0  
	  DECLARE @lEmployeeAge smallint = 0  
	  DECLARE @lDateOfBirth date	
	  DECLARE @lFirstDateOfMonth date
	  DECLARE @lLastDateOfMonth date
	  
	  SELECT @lEmployeeId = EmployeeId,@lPayProcessId = PayProcessId FROM sPayroll.tPayProcessEmployee WHERE ID = @rPayProcessEmployeeId
	  SELECT @lDateOfBirth = DateOfBirth FROM sHrm.tEmployeePersonalDetail WHERE EmployeeId = @lEmployeeId
	  SELECT @lSalaryMonth = SalaryMonth,@lSalaryYear = SalaryYear  FROM sPayroll.tPayProcess WHERE Id = @lPayProcessId
	 
      SET @lFirstDateOfMonth= CAST(CAST(@lSalaryYear AS varchar) + '-' + CAST(@lSalaryMonth AS varchar) + '-' + '1' AS date)
      SET @lLastDateOfMonth=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDateOfMonth)+1,0))
      SET @lEmployeeAge = [sCommon].[fAgeAtDate] (@lDateOfBirth,@lLastDateOfMonth)
      
      -- end for age calculation
      

	  
			  SET @1Basic = 0.0	          
	          SET @1PayProcesdsElementId = 0.0
	      
	   --   SELECT @1Basic = ISNULL(Amount,0) from sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lBasicPayElementId	      
		  --SELECT @1Basic =  Amount FROM sPayroll.tPaySetup Where SourceId = @rSourceId AND PayElementId = @lBasicPayElementId  --Basic Pay Element
		  
		  SELECT @1Basic = ISNULL(SUM(amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement PE 
		  ON PPE.PayElementId = PE.ID  WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId IN 
		  (SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS 
		  ON  PD.PaySetupId = PS.ID
		  INNER JOIN sPayroll.tPayElement PE 
		  ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId
		  AND PE.PayElementDefaultId = 56 AND SourceID = @lPayrollGroupId)	     
		  
	     
	      -- For PF Process(sPayroll.tPfProcess) 
	      
	      SELECT 
			  @1PfSalaryLimit = PfSalaryLimit,
			  @1EmployeePfPercent=EmployeePfPercent,
			  @1EmployerPfPercent=EmployerPfPercent, 
			  @1EmployerFpsPercent=EmployerFpsPercent,
			  @1AdminChargesPercent=AdminChargesPercent,
			  @1EdliPercent=EdliPercent,
			  @1InspectionChargesPercent=InspectionChargesPercent
	      FROM  
			  sPayroll.tPfSetup Where PayrollYearId = @rPayrollYearId 
	      
	      
	      SELECT @1EmployeePfPercentEmpSetup = Percentage  FROM sPayroll.tPaySetup WHERE SourceTypeId = 95 AND SourceId = (SELECT EmployeeId FROM sPayroll.tPayProcessEmployee WHERE ID = @rPayProcessEmployeeId)
				AND PayElementId = @lPFPayElementId AND PayrollYearId = @rPayrollYearId
	   
	   IF @1EmployeePfPercentEmpSetup IS NOT NULL
	   SET @1EmployeePfPercent = @1EmployeePfPercentEmpSetup
	  
	      
	   SELECT @1PayProcesdsElementId = Id  FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId
	       
	       --SET @1AdminChargesPercent =  ROUND(@1Basic*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
	       
	       
	        IF(@lEmployeeAge >= 58)
			BEGIN
				SET @lEmployerFpsPercent =  0
			END
			ELSE
			BEGIN
				SET @lEmployerFpsPercent =  ROUND(@1Basic*@1EmployerFpsPercent/100,@lRoundOffToWholeNumber)
			END
	      
	       SET @lValuesforMax = ROUND(@1PfSalaryLimit*@1EmployerFpsPercent/100,@lRoundOffToWholeNumber)
	       
	       IF(@lEmployerFpsPercent>@lValuesforMax)
			BEGIN
				SET @1Max = ROUND(@lEmployerFpsPercent-@lValuesforMax,@lRoundOffToWholeNumber)
			END
		   ELSE
			BEGIN
				SET @1Max = ROUND(@lEmployerFpsPercent,0)
			END
			
			IF(@lEmployerFpsPercent = @1Max)
			BEGIN
				SET @lRestrictionEmployerFpsPercent = ROUND(@lEmployerFpsPercent,@lRoundOffToWholeNumber)
			END
		   ELSE
			BEGIN
				SET @lRestrictionEmployerFpsPercent = ROUND(@lEmployerFpsPercent-@1Max,@lRoundOffToWholeNumber)
			END
			
			IF(@lEmployerFpsPercent > @lValuesforMax)
			BEGIN
				SET @1Bal = ROUND(@lEmployerFpsPercent-@lValuesforMax,0)
			END
		   ELSE
			BEGIN
				SET @1Bal = 0
			END
			
		   	SET @lEmployerPfPercent = ROUND(@1Basic*@1EmployerPfPercent/100,@lRoundOffToWholeNumber)
		   		        
	       IF(@1Basic < @1PfSalaryLimit)
			   BEGIN
			   
				 IF(@lEmployeeAge >= 58)
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1Basic*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1Basic*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1Basic*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  
					  SET @1AdminChargesPercent =  ROUND(@1Basic*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
				 ELSE 
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1Basic*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1Bal+ @lEmployerPfPercent,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1Basic*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  
					  SET @1AdminChargesPercent =  ROUND(@1Basic*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
			   END
	       ELSE
			   BEGIN
			   
			   IF(@lEmployeeAge >= 58)
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1AdminChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
				 ELSE 
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployerPfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1AdminChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
			   END
	       
	       --IF(@1Basic > @1PfSalaryLimit)
	       --   BEGIN
	           --SET @1EmployeePfAmount = @1Basic*@1EmployeePfPercent/100 
	             INSERT INTO  [sPayroll].[tPfProcess]
							   (
							    [PayProcessElementId]
							   ,[EmployeePfAmount]
							   ,[EmployerPfAmount]
							   ,[EmployerFpsAmount]
							   ,[EligibleFpsAmount]
							   ,[AdminChargesAmount]
							   ,[EdliChargesAmount]
							   ,[InspectionChargesAmount]
							   )
							   Values
							   (
							     @1PayProcesdsElementId,
							     @1EmployeePfAmount,
							     @1EmployerPfAmount,
							     @lRestrictionEmployerFpsPercent,
							     0.0,
							     @1AdminChargesPercent,
							     @1EdliPercent,
                                 @1InspectionChargesPercent	    
							    ) 
					
				 IF(@1PfSalaryLimit > 0)			    
				 BEGIN
					UPDATE sPayroll.tPayProcessElement 
					SET Amount = @1EmployeePfAmount WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId			    
				 END	
				--END
	  END

	  --FOR Esi Element
	 IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lESIPayElementId)
	  BEGIN 
			   SET @1PayProcesdsElementId = 0.0  
			   SET @1ESISalaryLimit = 0.0			
			   SELECT  @1ESISalaryLimit = EsiSalaryLimit,@1EmployeeESIPercent=EmployeeEsiPercent,@1EmployerESIPercent = EmployerEsiPercent FROM sPayroll.tEsiSetup Where PayrollYearId = @rPayrollYearId
			   SELECT @1PayProcesdsElementId = Id FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lESIPayElementId
			    
		   IF(@1ESISalaryLimit > @rSalary)					   
			  BEGIN
			  SET @1EmployeeESIAmount = @rSalary * @1EmployeeESIPercent/100	
			   INSERT INTO [sPayroll].[tEsiProcess]
						   (
							    [PayProcessElementId]
							   ,[EmployeeEsiAmount]
							   ,[EmployerEsiAmount]
						   )
						   Values
						   (
						       @1PayProcesdsElementId
						      ,@rSalary * @1EmployeeESIPercent/100
						      ,@rSalary * @1EmployerESIPercent/100
						   )
				SET @1EmployeeESIAmount = ROUND(@1EmployeeESIAmount,@lRoundOffToWholeNumber)						   
				UPDATE sPayroll.tPayProcessElement SET Amount = @1EmployeeESIAmount WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lESIPayElementId  
			   END	 
	  END

	--Add for Mantis: 40774, start
	IF(@rIsAllow=1)
	BEGIN
		--For Earning1
		IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lEarning1PayElementId)
		BEGIN
			SET @1Basic = 0.0
			SELECT @1Basic = ISNULL(SUM(amount),0)
			FROM sPayroll.tPayProcessElement PPE
				INNER JOIN sPayroll.tPayElement PE ON PPE.PayElementId = PE.ID
			WHERE PayProcessEmployeeId = @rPayProcessEmployeeId
				AND PayElementId IN (SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD
					INNER JOIN sPayroll.tPaySetup PS ON PD.PaySetupId = PS.ID
					INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID
					WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId AND PE.PayElementDefaultId = 41 AND SourceID = @lPayrollGroupId)

			IF(@1Basic>0)
			BEGIN
				SELECT @1EmployeePfPercent = Percentage FROM sPayroll.tPaySetup WHERE PayElementId=@lEarning1PayElementId AND PayrollId=@rPayrollId AND PayrollYearId=@rPayrollYearId
				SET @1Earning1EmployeePfAmount = ROUND(@1Basic * ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
				SET @rSalary = @rSalary + @1Earning1EmployeePfAmount
				UPDATE sPayroll.tPayProcessElement SET Amount = @1Earning1EmployeePfAmount WHERE PayProcessEmployeeId=@rPayProcessEmployeeId AND PayElementId=@lEarning1PayElementId
			END
		END

		--For Deduction1
		IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lDeduction1PayElementId)
		BEGIN
			SET @1Basic = 0.0
			SELECT @1Basic = ISNULL(SUM(amount),0)
			FROM sPayroll.tPayProcessElement PPE
				INNER JOIN sPayroll.tPayElement PE ON PPE.PayElementId = PE.ID
			WHERE PayProcessEmployeeId = @rPayProcessEmployeeId
				AND PayElementId IN (SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD
					INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
					INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID
					WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId AND PE.PayElementDefaultId = 41 AND SourceID = @lPayrollGroupId)

			IF(@1Basic>0)
			BEGIN
				SELECT @1EmployeePfPercent=Percentage FROM sPayroll.tPaySetup WHERE PayElementId=@lDeduction1PayElementId AND PayrollId=@rPayrollId AND PayrollYearId = @rPayrollYearId
				SET @1Deduction1EmployeePfAmount = ROUND(@1Basic * ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
				UPDATE sPayroll.tPayProcessElement SET Amount=@1Deduction1EmployeePfAmount WHERE PayProcessEmployeeId=@rPayProcessEmployeeId AND PayElementId=@lDeduction1PayElementId
			END
		END
	END
	--Add for Mantis: 40774, end

	  SET @1TotalDeductionAmount = @rDeductionAmount + @1Tax + @1EmployeePfAmount + @1EmployeeESIAmount + @1Deduction1EmployeePfAmount --add for mantis: 40774, @1Deduction1EmployeePfAmount

	  UPDATE sPayroll.tPayProcessEmployee
	  SET
	      TotalEarning = ROUND(@rSalary,@lRoundOffToWholeNumber),
	      TotalDeduction = ROUND(@1TotalDeductionAmount,@lRoundOffToWholeNumber),
		  NetAmount = ROUND(@rSalary,@lRoundOffToWholeNumber) - ROUND(@1TotalDeductionAmount,@lRoundOffToWholeNumber)
	  WHERE ID = @rPayProcessEmployeeId

    END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pCopyPaySetupAdd]
	  
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgGroupId int,
     @rCopyGradeId bigint,
     @rPayrollId int,
     @rPayrollYearId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       DELETE PSD FROM sPayroll.tPaySetup PS INNER JOIN  sPayroll.tPaySetupDependent PSD ON PSD.PaySetupId = PS.ID 
	   WHERE SourceId = @rCopyGradeId AND SourceTypeId = @rSourceTypeId AND PayrollId = @rPayrollId  AND PayrollYearId = @rPayrollYearId
		
	   DELETE FROM sPayroll.tPaySetup WHERE SourceId = @rCopyGradeId AND SourceTypeId = @rSourceTypeId AND PayrollId = @rPayrollId AND PayrollYearId = @rPayrollYearId
		
		DECLARE @1Count int
		DECLARE @1PaySetupId int
		DECLARE @lNextNumber BIGINT
		
		CREATE TABLE #TempTable
		(
		    ID INT IDENTITY(1,1),
		    PaySetupId INT,
		    PayElementId INT,
		    AMOUNT DECIMAL(22,2),
		    Percentage DECIMAL(22,2),
		    ProcessOrder int,
		    DefaultAmount decimal(22,2),
			Formula NVARCHAR(200) --Added by Nilesh for mantis : 34316
		 ) 
       		
       	INSERT INTO #TempTable 
        SELECT  ID, 
         PayElementId
		,[Amount]
		,[Percentage]
        ,[ProcessOrder]  
        ,[DefaultAmount]
	    ,Formula --Added by Nilesh for mantis : 34316
	   FROM [sPayroll].[tPaySetup] PS   
			  
	   WHERE PayrollId = @rPayrollId  AND PayrollYearId = @rPayrollYearId  AND  PS.SourceTypeId = @rSourceTypeId AND PS.SourceId = @rSourceId
	   
	   SELECT @1Count = COUNT(Id) FROM #TempTable
	   
	   WHILE @1Count > 0	     
	     BEGIN 
	        SET @1PaySetupId = 0
	        EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPaySetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	        
	        INSERT INTO sPayroll.tPaySetup   
	        SELECT @lNextNumber,
				   @rSourceTypeId,      
                   @rCopyGradeId,
	               PayElementId
				   ,[Amount]
				   ,[Percentage]
				   ,[ProcessOrder]     
	               ,@rPayrollId
	               ,NULL
	               ,@rPayrollYearId
	               ,[DefaultAmount]
				   ,Formula --Added by Nilesh for mantis : 34316
	                
	        FROM #TempTable Where Id = @1Count				    
	        
	        SELECT @1PaySetupId = PaySetupId From #TempTable Where Id = @1Count
	        
	        IF EXISTS(SELECT 1 FROM sPayroll.tPaySetupDependent Where PaySetupId = @1PaysetupId)
	          BEGIN  
	          
	                --Select @1PaysetupId
	                INSERT INTO sPayroll.tPaySetupDependent
	                SELECT DependentPayElementId,@lNextNumber,IsDeduct FROM sPayroll.tPaySetupDependent Where PaySetupId = @1PaysetupId	               
	          END       
	          
	        SET @1Count = @1Count - 1
	     END
	     
	     DROP TABLE #TempTable
	     
	     SELECT @lNextNumber AS Result
       
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 

CREATE OR ALTER PROCEDURE [sPayroll].[pEmployeePayElementDetailGet]
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rPayrollId int,
	 @rPayElementId int,
	 @rPayrollYearId int=0,
	 @rMonth int=0,
	 @rYear int=0
	 --@rPayrollGroupId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lWorkingDays int
--Declare @lFirstDate Date
--DECLARE @lEndDate Date

--select @lFirstDate=DATEADD(month,@rMonth-1,DATEADD(year,@rYear-1900,0)) /*First*/

--select @lEndDate=DATEADD(day,-1,DATEADD(month,@rMonth,DATEADD(year,@rYear-1900,0))) /*Last*/
SELECT @lWorkingDays=
       DATEDIFF(DAY,
                DATEADD(DAY, 0, DATEADD(m, ((@rYear - 1900) * 12) + @rMonth - 1, 0)),
                DATEADD(DAY, 0, DATEADD(m, ((@rYear - 1900) * 12) + @rMonth, 0))
               ) 


    SELECT  
		ISNULL(PS.Id,0) AS PaySetupId,
		EM.EmployeeId,
		EM.EmployeeName,
		EM.Code,
		EM.DepartmentName,
		PS.Amount,
		ISNULL(PE.SortOrder,0) AS ProcessOrder,
		ISNULL(PS.PayElementId,0) AS PayElementId,
		ISNULL(PS.DefaultAmount,0) AS DefaultAmount,
		PS.PayrollYearId,
		[sHrm].[fEmployeeLeaveStatusGet] (@rMonth,@rYear,EM.EmployeeId)AS IsEmployeeOnLeave,
		@lWorkingDays AS WorkingDays,
		ISNULL(PE.SortOrder,0) AS ProcessOrder
	FROM sHrm.vEmployeeCommonDetail EM
		INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON EM.EmployeeId = ESO.EmployeeId	 
		LEFT JOIN sPayroll.tPaySetup PS ON PS.SourceId = EM.EmployeeId  
		AND SourceTypeId = @rSourceTypeId 
		AND PS.PayElementId = @rPayElementId
		AND PS.PayRollId = ESO.PayrollId
		AND PS.PayRollYearId = @rPayrollYearId
		INNER JOIN sPayroll.tPaySetup PS1 ON PS1.SourceId = ESO.PayrollGroupId AND PS1.SourceTypeId = 2020
		LEFT JOIN sPayroll.tPayElement PE ON PS1.PayElementId = PE.ID 
	WHERE  ESO.PayrollId = @rPayrollId 
		--AND (ESO.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId=0)
		AND EM.EmployeeStatusId=7
		AND ISNULL(EM.IsOtherUser,0)=0 
		AND PE.ID=@rPayElementId
		AND PS1.PayrollYearId = @rPayrollYearId
	ORDER BY EM.OrgId,EM.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pEmployeePayElementMasterRemove]
 (
	@rId int
 )
AS
SET NOCOUNT ON	
	DECLARE @1Result Int
	DECLARE @rPayElementId int
		
	BEGIN TRY	
    BEGIN TRANSACTION
			BEGIN	 
			
			    SET @rPayElementId = @rId
				 --SET @1Result = 1
				 
				 IF EXISTS(Select 1 FROM sPayroll.tPayProcessElement Where PayElementId = @rPayElementId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				 ELSE IF EXISTS(Select 1  FROM sPayroll.tPaySetup  Where PayElementId = @rPayElementId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				 ELSE IF EXISTS(Select 1  FROM sPayroll.tPaySetupDependent Where DependentPayElementId = @rPayElementId)
				 BEGIN
				   SET @1Result = -101				   
				 END
				  
				 ELSE
				   BEGIN
				      DELETE FROM sPayroll.tPayElement Where Id = @rPayElementId
				      SET @1Result = 1
				   END
				  
				 	  
			SELECT @1Result AS Result
				 	  
			END
	  COMMIT TRANSACTION
      END TRY
         
      BEGIN CATCH
	  ROLLBACK TRANSACTION
	  SELECT -1 AS RESULT
	  END CATCH

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sPayroll].[pEmployeePayrollListGet]

	@rPayrollId int,
	@rPayrollGroupId int,
	@rForYear int,
	@rForMonth int
 
AS
SET NOCOUNT ON

BEGIN
		SELECT 
			EM.Code AS Code,
			ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
			ISNULL(ETM.Title,'') As EmployeeType,
			OM.DisplayTitle AS OrganizationName,
			ODM.Title AS OrganizationDepartmentName,
			PGM.Title AS PayrollGroupName,
			ISNULL(AT.TotalWorkingDays,0) AS WorkingDays, 
			ISNULL(AT.LWP,0) AS LWP,
			(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0) ) AS PresentDays
		FROM 
			sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id  
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON ESO.PayrollGroupId = PGM.ID
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId			
			INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.Id
			INNER JOIN sSetup.tBatchMaster BM ON AT.BatchId = BM.Id	AND BM.IsActive = 1
		WHERE 
			ESO.PayrollId = @rPayrollId 
			AND ((ESO.PayrollGroupId=@rPayrollGroupId) OR (@rPayrollGroupId=0))
			AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth
			AND ISNULL(EM.IsOtherUser,0) = 0 
		ORDER BY EM.OrgId,EM.Number
		--,EM.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pEsiSetupAdd] 
	      
		   @rId int,
	       @rPayrollYearId int,
           @rEmployeeEsiPercent decimal(5,2),
           @rEmployerEsiPercent decimal(5,2),
           @rEsiSalaryLimit decimal(22,6),
           @rRoundingTypeId tinyint,
           @rRoundingPrecision int,
           @rEffectiveDate date,
           @rCreatedUserId bigint,
           @rOrgGroupId int
           
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	--DECLARE @lNextNumber BIGINT
  
  IF NOT Exists (Select 1 From sPayroll.tEsiSetup Where PayrollYearId = @rPayrollYearId)
    
    BEGIN	
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sPayroll.tEsiSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO  [sPayroll].[tEsiSetup]
           (
            [ID]
           ,[PayrollYearId]
           ,[EmployeeEsiPercent]
           ,[EmployerEsiPercent]
           ,[EsiSalaryLimit]
           ,[RoundingTypeId]
           ,[RoundingPrecision]
           ,[EffectiveDate]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           )
     VALUES
           (
		   @rId,
           @rPayrollYearId,
           @rEmployeeEsiPercent,
           @rEmployerEsiPercent,
           @rEsiSalaryLimit,
           @rRoundingTypeId,
           @rRoundingPrecision,
           @rEffectiveDate,
           @rCreatedUserId,
           sCommon.fGetDate()
          )
         END
    ELSE
		BEGIN    
		     --SET @lNextNumber = @rId
		     UPDATE [sPayroll].[tEsiSetup]
			   SET        
				   EmployeeEsiPercent = @rEmployeeEsiPercent 
				  ,[EmployerEsiPercent] = @rEmployerEsiPercent 
				  ,[EsiSalaryLimit] = @rEsiSalaryLimit 
				  ,[RoundingTypeId] = @rRoundingTypeId 
				  ,[RoundingPrecision] = @rRoundingPrecision 
				  ,[EffectiveDate] = @rEffectiveDate 	
			  Where PayrollYearId = @rPayrollYearId
		END        
	SELECT @rId AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error Creating Esi Setup Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pEsiSetupGet]
	 @rId int,
	 @rPayrollYearId int 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	SELECT 
		   [ID] 
		  ,[EmployeeEsiPercent]
		  ,[EmployerEsiPercent]
		  ,[EsiSalaryLimit]
		  ,[RoundingTypeId]
		  ,[RoundingPrecision]
		  ,[EffectiveDate]
		  ,[PayrollYearId]
      
   FROM [sPayroll].[tEsiSetup]
  
  
Where  
     (Id = @rId OR @rId = 0) AND 
     PayrollYearId = @rPayrollYearId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pGetPayProcessEmployeeDetail]
	
	 @rId int,
	 --@rOrgId int,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rPayrollGroupId int,
	 @rForMonth int,
	 @rForYear int,
	-- @rBatchId int,
	 @rPayrollYearId int
	 
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  

	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT  
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		PPE.EmployeeId,
		EM.EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeGradeId,
		EM.DepartmentId,
		EM.DepartmentName,
		PPE.TotalEarning,
		PPE.TotalDeduction,
		PPE.NetAmount,
		ISNULL(PPE.WorkingDays,0) AS WorkingDays,
		(ISNULL(PPE.WorkingDays,0) - ISNULL(PPE.Lwp,0)) AS PresentDays,
		ISNULL(PPE.Lwp,0) AS AbsentDays,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
	    (SELECT  t1.MonthTitle FROM (SELECT MonthTitle,MonthNumber FROM [sPayroll].[fMonthYearForPayrollGet] (@rPayrollYearId))  AS T1
		WHERE MonthNumber = SalaryMonth) AS MonthTitle,
		EM.CompanyEmail

	FROM sPayroll.tPayProcess PP INNER JOIN  
	sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID INNER JOIN
	sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
	--INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId 
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id

where 
      --(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND 
      --OrgID = @rOrgId 
      --AND 
      ((EM.Code Like   @rEmployeeCode  ) OR (@rEmployeeCode = ''))
	  AND ((EM.FirstName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (SalaryYear = @rForYear OR @rForYear = 0)
	  AND  PP.PayrollYearId = @rPayrollYearId
	  AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
      AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ISNULL(EM.IsOtherUser,0)=0 
	 -- AND PP.BatchId = @rBatchId
	  
	  Order By EM.OrgID,EM.Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pGetPayProcessSetupDetail]
	
	 @rPayrollYearId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	SELECT
	
		PP.ID AS PayProcessId,
		PP.SalaryMonth,
		PP.SalaryYear,
		ISNULL(PP.IsApproved,0) AS IsApproved,
		ISNULL(PP.IsPublish,0) AS IsPublish,
	    (SELECT  t1.MonthTitle FROM (SELECT MonthTitle,MonthNumber FROM [sPayroll].[fMonthYearForPayrollGet] (@rPayrollYearId))  AS T1
		WHERE MonthNumber = SalaryMonth) AS MonthTitle

	FROM sPayroll.tPayProcess PP 

WHERE
	    PP.PayrollYearId = @rPayrollYearId
	    ORDER BY PP.SalaryYear DESC,PP.SalaryMonth DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sPayroll].[pGetPayrollDetailEmployeeMonthWise]
	 
	 @rEmployeeId bigint,
	 @rForMonth nvarchar(max),
	 @rForYear nvarchar(max),
	 @rPayrollYearId int,
	 @rIsMobileApp bit=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  
	   
	   DECLARE @rPayrollId int
	   SELECT @rPayrollId = PayrollId FROM sPayroll.tPayrollYearMaster WHERE Id  = @rPayrollYearId
	   
	   CREATE TABLE #TempEmpName(EmployeeId bigint, EmployeeName nvarchar(50) )
	   INSERT INTO #TempEmpName (EmployeeId, EmployeeName )
	   Select tEM.Id AS EmployeeId ,tEM.FirstName +' '+ tEM.MiddleName+' '+tEm.LastName AS EmployeeName
	   From sHrm.tEmployeeMaster tEM Where tEm.Id = @rEmployeeId
	   
	   if(@rIsMobileApp=1)
	   BEGIN
			SELECT
				P.PayElementTypeId as PayElementTypeId,
				P.Title,
				PE.Amount
		   FROM 
				sPayroll.tPayProcess PP 
				INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
				INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
				INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
				INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
				INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1 
				LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
				LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
				LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
				INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
				INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
				INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
				LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
				AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
				INNER JOIN #TempEmpName T ON T.EmployeeId = tEM.Id
		   WHERE 
			   (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			   AND (P.IsObsolete=0)
			   AND (PP.SalaryMonth IN (SELECT (item) from sCommon.fnSplit(@rForMonth,',')) OR @rForMonth = '')
			   AND (PP.SalaryYear IN (SELECT (item) from sCommon.fnSplit(@rForYear,','))  OR @rForYear = '')
			   AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			   AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			   AND (P.PayElementTypeId = 1 OR P.PayElementTypeId = 2)
	   END
	   ELSE
	   BEGIN
		   DECLARE @lEmpEarning VARCHAR(max)='', @lEmpDeduction VARCHAR(max)=''
		   SELECT @lEmpEarning = @lEmpEarning +'<tr>
				<td align="left" scope="col">' +   convert(varchar,P.Title) + '</td>
				<td align="left" scope="col">' +   convert(varchar,PE.Amount) + '</td>
				</tr>'
		   FROM 
				sPayroll.tPayProcess PP 
				INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
				INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
				INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
				INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
				INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1 
				LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
				LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
				LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
				INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
				INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
				INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
				LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
				AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
				INNER JOIN #TempEmpName T ON T.EmployeeId = tEM.Id
		   WHERE 
			   (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			   AND (P.IsObsolete=0)
			   AND (PP.SalaryMonth IN (SELECT (item) from sCommon.fnSplit(@rForMonth,',')) OR @rForMonth = '')
			   AND (PP.SalaryYear IN (SELECT (item) from sCommon.fnSplit(@rForYear,','))  OR @rForYear = '')
			   AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			   AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			   AND P.PayElementTypeId = 1
		   
		   SELECT @lEmpDeduction = @lEmpDeduction +'<tr>
				<td align="left" scope="col">' +   convert(varchar,P.Title) + '</td>
				<td align="left" scope="col">' +   convert(varchar,PE.Amount) + '</td>
				</tr>'
		   FROM 
				sPayroll.tPayProcess PP 
				INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
				INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
				INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
				INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
				INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1 
				LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
				LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
				LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
				INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
				INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
				INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
				LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
				AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
				INNER JOIN #TempEmpName T ON T.EmployeeId = tEM.Id
		   WHERE 
			   (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			   AND (P.IsObsolete=0)
			   AND (PP.SalaryMonth IN (SELECT (item) from sCommon.fnSplit(@rForMonth,',')) OR @rForMonth = '')
			   AND (PP.SalaryYear IN (SELECT (item) from sCommon.fnSplit(@rForYear,','))  OR @rForYear = '')
			   AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			   AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			   AND P.PayElementTypeId = 2
	 
		 SELECT ISNULL(@lEmpEarning,'') as EmpEarning,ISNULL(@lEmpDeduction,'') as EmpDeduction
	 
	 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sPayroll].[pGetPayrollDetailEmployeeWise]
	 
	 @rEmployeeId bigint,
	 @rForMonth nvarchar(max),
	 @rForYear nvarchar(max),
	 @rPayrollYearId int,
	 --@rIsDetail bit
	 @rIsMobileApp bit=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  

	DECLARE @rPayrollId int
	SELECT @rPayrollId = PayrollId FROM sPayroll.tPayrollYearMaster WHERE Id  =@rPayrollYearId
	--DECLARE @lFirstDate Date
	--DECLARE @lLasteDate Date
	--IF(@rForMonth!='' and @rForYear!='')
	--BEGIN
		--SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		--SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	--END
	
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1


--IF @rIsDetail = 0
--BEGIN
	
	--SELECT
	--	EM.EmployeeId, 
	--	PP.ID As PayProcessId,
	--	PPE.ID AS PayProcessEmployeeId,
	--	PP.SalaryMonth,
	--	PP.SalaryYear,
	--	tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
	--	EM.Code AS EmployeeCode,
	--	EM.EmployeeDesignation,
	--	EM.EmployeeGrade,
	--	ESO.EPFNumber,
	--	ESO.PanNumber,
	--	PPE.TotalEarning,		
	--	PPE.TotalDeduction,
	--	PPE.NetAmount,
	--	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	--	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
	--	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	--	PE.Amount As PPEAmount,
	--	P.Title AS PayElementTitle,
	--	P.ID AS PayElementId,
	--	P.PayElementTypeId,
	--	ISNULL(ESO.BankName,'') AS BankName,
	--	ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
	--	MM.Title AS MonthName,
	--	P.Title AS PayElementName,
	--	P.Code AS PayElementCode,
	--	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.WorkingDays else 0 END) AS WorkingDays,
	--	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
	--	ISNULL(WorkingDays,0) - ISNULL(Lwp,0) AS PresentDays,
	--	(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
	--	P.SortOrder,
	--	PY.Title AS PayrollYearName,
	--	PGM.Id AS PayrollGroupId,
	--	PGM.Title AS PayrollGroupName,
	--	PPE.GrossBasic,
	--	P.PayElementDefaultId,
	--	ISNULL(EPD.Qualification,'') AS Qualification,
	--	EJD.DateOfJoining AS DateOfAppointment,
	--	ISNULL(ESO.PayScale,'') AS PayScale,
	--	EPD.DateOfBirth,
	--	ISNULL(ESO.BasicPay,0) AS BasicPay,
	--	DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
	--	ESO.UAN,
	--	EPD.GenderId,
	--	ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark
		
		CREATE TABLE #TempDaysValue(PayProcessId int ,WorkingDays  decimal ,PresentDays decimal )
		INSERT INTO #TempDaysValue (PayProcessId, WorkingDays, PresentDays )
		SELECT PP.Id AS PayProcessId, (CASE WHEN PayElementId = @lBasicPayElementId then PPE.WorkingDays else 0 END) AS WorkingDays, ISNULL(WorkingDays,0) - ISNULL(Lwp,0) AS PresentDays
		FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1 AND PayElementDefaultId=1
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
			LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
			AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
	    WHERE 
		   (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		   AND (P.IsObsolete=0)
		   AND (PP.SalaryMonth IN (SELECT (item) from sCommon.fnSplit(@rForMonth,',')) OR @rForMonth = '')
		   AND (PP.SalaryYear IN (SELECT (item) from sCommon.fnSplit(@rForYear,','))  OR @rForYear = '')
		   AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		   AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	    ORDER BY 
		   PP.SalaryMonth
		if(@rIsMobileApp=1)
		BEGIN
			SELECT 
				MM.Title AS Month,
				PP.SalaryYear AS SalaryYear,
				T.WorkingDays,
				T.PresentDays,
				PPE.TotalEarning,
				PPE.TotalDeduction,
				PPE.NetAmount,
				isnull(PP.SalaryMonth,0) AS SalaryMonth
		
	   FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1 AND PayElementDefaultId=1
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
			LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
			AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
			INNER JOIN #TempDaysValue T ON T.PayProcessId = PP.Id 
	   WHERE 
		   (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		   AND (P.IsObsolete=0)
		   AND (PP.SalaryMonth IN (SELECT (item) from sCommon.fnSplit(@rForMonth,',')) OR @rForMonth = '')
		   AND (PP.SalaryYear IN (SELECT (item) from sCommon.fnSplit(@rForYear,','))  OR @rForYear = '')
		   AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		   AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	   ORDER BY 
		   PP.SalaryMonth
		END
		ELSE
		BEGIN
			DECLARE @lempgrid VARCHAR(max)=''
			SELECT  @lempgrid = @lempgrid + '<tr>
			<td align="left" scope="col">' +   convert(varchar,MM.Title) + '</td>
			<td align="left" scope="col">' +   convert(varchar,PP.SalaryYear) + '</td>
			<td align="left" scope="col">' +   convert(varchar,T.WorkingDays) + '</td>
			<td align="left" scope="col">' +   convert(varchar,T.PresentDays) + '</td>
			<td align="left" scope="col">' +   convert(varchar,PPE.TotalEarning) + '</td>
			<td align="left" scope="col">' +   convert(varchar,PPE.TotalDeduction) + '</td>
			<td align="left" scope="col">' +   convert(varchar,PPE.NetAmount) + '</td>
			<td scope="col" align="center"><a class="fa fa-plus-square"  
			onclick="SelectPayrollDetail(this,' + convert(varchar,isnull(PP.SalaryMonth,0)) + ',' + convert(varchar,isnull(PP.SalaryYear,0)) + ',' + convert(varchar,isnull(@rPayrollYearId,0)) + ');"></a></td></tr>'	
		
	   FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1 AND PayElementDefaultId=1
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
			LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
			AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
			INNER JOIN #TempDaysValue T ON T.PayProcessId = PP.Id 
	   WHERE 
		   (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		   AND (P.IsObsolete=0)
		   AND (PP.SalaryMonth IN (SELECT (item) from sCommon.fnSplit(@rForMonth,',')) OR @rForMonth = '')
		   AND (PP.SalaryYear IN (SELECT (item) from sCommon.fnSplit(@rForYear,','))  OR @rForYear = '')
		   AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		   AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	   ORDER BY 
		   PP.SalaryMonth
	 
	 
		SELECT ISNULL(@lempgrid,'') as EmpGrid
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [sPayroll].[pGetTaxDetails] 9911000000065,
CREATE OR ALTER PROCEDURE [sPayroll].[pGetTaxDetails]
	 @rEmployeeId bigint,
	 @rAssesmentYearId bigint = 0,
	 @rOrgGroupId int
AS
SET NOCOUNT ON

BEGIN

SELECT ITG.Id as 'GroupID'
		  ,ITSG.Id as 'SubGroupID'
		  ,ISNULL(ITG.GroupCode,'') +'  '+ ISNULL(ITG.DisplayName,'') +'  '+ ISNULL(ITG.ActionName,'') as 'GroupName'
		  ,ITSG.SubGroupName 
		  ,ISNULL(d.GrossAmount,0)GrossAmount
		  ,ITSG.QualifyingLimit as  QualifyingAmount
		  ,ISNULL(d.DeductibleAmount,0)DeductibleAmount
		  ,ITSG.IsEditable
		  ,d.Form16Id
	FROM [siTax].[tStaticIncomeTaxGroup] AS ITG 
		 LEFT JOIN [siTax].[tStaticIncomeTaxSubGroup] AS ITSG on ITG.Id=ITSG.StaticIncomeTaxGroupId
		 LEFT JOIN (SELECT f.Id AS Form16Id,fd.IncomeTaxSubgroupId,	fd.GrossAmount,	fd.QualifyingAmount,	fd.DeductibleAmount
				    FROM [siTax].[tForm16] as f
					INNER JOIN [siTax].[tForm16Detail] as fd on f.id =fd.Form16Id
	                WHERE f.EmployeeId=@rEmployeeId AND (AssesmentYearId=@rAssesmentYearId OR @rAssesmentYearId = 0)
	                AND OrgGroupId=@rOrgGroupId) AS d ON d.IncomeTaxSubgroupId=ITSG.id
	
	ORDER by ITG.OrderIndex,ITSG.OrderIndex

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pMobilePayrollPaySlipDetail]
	 @rEmployeeId bigint,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollYearId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
DECLARE @rPayrollId int
	SELECT @rPayrollId = PayrollId FROM sPayroll.tPayrollYearMaster WHERE Id  =@rPayrollYearId
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	SELECT
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeDesignation,
		EM.EmployeeGrade,
		ESO.EPFNumber,
		ESO.PanNumber,
		PPE.TotalEarning,		
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		PE.Amount As PPEAmount,
		P.Title AS PayElementTitle,
		P.ID AS PayElementId,
		P.PayElementTypeId,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
		MM.Title AS MonthName,
		P.Title AS PayElementName,
		P.Code AS PayElementCode,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.WorkingDays else 0 END) AS WorkingDays,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
		P.SortOrder,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		PPE.GrossBasic,
		P.PayElementDefaultId,
		ISNULL(EPD.Qualification,'') AS Qualification,
		EJD.DateOfJoining AS DateOfAppointment,
		ISNULL(ESO.PayScale,'') AS PayScale,
		EPD.DateOfBirth,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
		ESO.UAN,
		EPD.GenderId,
		ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark
	FROM 
	sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
	AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND (P.IsObsolete=0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pMonthYearBatchwiseGet]
	@rBatchId int,
	@rEmployeeId bigint,
	@rPayrollGroupId int
AS
BEGIN
 
 DECLARE @lFromDate date
 DECLARE @lToDate date
 DECLARE @lMonthYearTable TABLE(
						MonthName nvarchar(20) NOT NULL,
                        Month nvarchar(10) NOT NULL,
                        Year nvarchar(10) NOT NULL)

 SELECT @lFromDate=FromDate,@lToDate=Todate FROM sSetup.tBatchMaster WHERE Id = @rBatchId

 INSERT INTO @lMonthYearTable
 SELECT 
 DATENAME(MONTH, DATEADD(MONTH, x.number, @lFromDate)) AS 'MonthName',
 DATEPART(MONTH, DATEADD(MONTH, x.number, @lFromDate)) AS 'Month',
 Convert(varchar(4), Year(DATEADD(MONTH, x.number, @lFromDate))) AS 'Year'
 FROM master.dbo.spt_values x
 WHERE x.type = 'P'
 AND x.number <= DATEDIFF(MONTH, @lFromDate, @lToDate)
 
 SELECT DISTINCT MY.MonthName,MY.Month,MY.Year FROM @lMonthYearTable MY INNER JOIN 
 sPayroll.tPayProcess PP ON MY.Month = PP.SalaryMonth AND  MY.Year = PP.SalaryYear
 INNER JOIN sPayroll.tPayProcessEmployee PPE ON PP.ID =PPE.PayProcessId
 WHERE  CAST(LEFT(PP.PayrollYearId, 4) AS int) =  CAST(LEFT(@rBatchId, 4) AS int) 
 AND PPE.EmployeeId=@rEmployeeId AND PPE.PayrollGroupId=@rPayrollGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPayElementAdd] 
	      
			@rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rPayElementTypeId tinyint
           ,@rPaidCategoryId tinyint
           ,@rIsLwp bit
           ,@rIsEmployeeSpecific bit
           ,@rIsDepend bit
           ,@rIsAvailDuringProbation bit
           ,@rIsIncludeInPaySlip bit
           ,@rSortOrder tinyint
           ,@rIsObsolete bit
           ,@rOrgGroupId int
           ,@rCreatedUserId bigint
		   ,@rPayElementDefaultId int
		   ,@rPayrollId int
		   ,@rIsIncludeInTotal bit=0
      
        
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT

	--Add Validation of code because if in Earning and Deduction both there are same code then issue in Pay Process Employee screen in SP(pPayrollProcessEmployeeDetailGet) for pivot - mantisid - 0027028
	IF (@rId = 0)
    BEGIN
		IF EXISTS (Select 1 from sPayroll.tPayElement WHERE Code=@rCode AND PayrollId = @rPayrollId)
		BEGIN
			SELECT -101 AS Result
			COMMIT TRANSACTION
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS (Select 1 from sPayroll.tPayElement WHERE Code=@rCode AND PayrollId = @rPayrollId AND Id != @rId)
			BEGIN
				SELECT -101 AS Result
				COMMIT TRANSACTION
				RETURN
			END 
	END
  
  IF (@rId = 0)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayElement', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPayElement]
           (
            [ID]
           ,[Code]
           ,[Title]
           ,[PayElementTypeId]
           ,[PaidCategoryId]
           ,[IsLwp]
           ,[IsEmployeeSpecific]
           ,[IsDepend]
           ,[IsAvailDuringProbation]
           ,[IsIncludeInPaySlip]
           ,[SortOrder]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[PayElementDefaultId]
           ,[PayrollId]
           ,[IsIncludeInTotal]
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rPayElementTypeId 
           ,@rPaidCategoryId 
           ,@rIsLwp 
           ,@rIsEmployeeSpecific 
           ,@rIsDepend 
           ,@rIsAvailDuringProbation 
           ,@rIsIncludeInPaySlip 
           ,@rSortOrder 
           ,@rIsObsolete 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()  
           ,@rCreatedUserId 
           ,sCommon.fGetDate() 
           ,@rPayElementDefaultId
           ,@rPayrollId
           ,@rIsIncludeInTotal
           )
    	END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		    UPDATE  [sPayroll].[tPayElement]
			   SET   
			       [Code] = @rCode
				  ,[Title] = @rTitle 
				  ,[PayElementTypeId] = @rPayElementTypeId 
				  ,[PaidCategoryId] = @rPaidCategoryId 
				  ,[IsLwp] = @rIsLwp 
				  ,[IsEmployeeSpecific] = @rIsEmployeeSpecific 
				  ,[IsDepend] = @rIsDepend 
				  ,[IsAvailDuringProbation] = @rIsAvailDuringProbation 
				  ,[IsIncludeInPaySlip] = @rIsIncludeInPaySlip 
				  ,[SortOrder] = @rSortOrder 
				  ,[IsObsolete] = @rIsObsolete  
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate() 
				  --,[PayElementDefaultId] = @rPayElementDefaultId
				  ,[PayrollId]=@rPayrollId
				  ,[IsIncludeInTotal]=@rIsIncludeInTotal
			   WHERE Id = @rId   		     		    
			END        
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Element Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPayElementGet]
	 @rId int,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rPayElementTypeId int,
	 @rPaidCategoryId int,
	 @rPayrollId int,
	 @rIsWildCardSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

    IF(@rIsWildCardSearch = 0)
	 BEGIN  	  
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END
	

 SELECT PE.Id
      ,PE.[Code]
      ,PE.[Title]
      ,PE.[PayElementTypeId]
      ,PE.[PaidCategoryId]
      ,ISNULL(PE.[IsLwp],0) AS IsLwp 
      ,ISNULL(PE.[IsEmployeeSpecific],0) As IsEmployeeSpecific
      ,ISNULL(PE.[IsDepend],0) As IsDepend
      ,ISNULL(PE.[IsAvailDuringProbation],0) AS IsAvailDuringProbation
      ,ISNULL(PE.[IsIncludeInPaySlip],0) AS IsIncludeInPaySlip
      ,PE.[SortOrder]
      ,PE.[IsObsolete]
      ,PET.Title AS PayElementType
      ,PC.Title AS PaidCategory     
      ,ISNULL(PE.PayElementDefaultId,0) AS PayElementDefaultId
      ,PED.Code AS PayElementDefaultCode
      ,ISNULL(PE.IsIncludeInTotal,0) AS IsIncludeInTotal
     
  FROM  sPayroll.tPayElement PE 
  INNER JOIN sPayroll.tPayElementType PET 
	ON PET.Id = PE.PayElementTypeId   
  INNER JOIN sPayroll.tPaidCategory PC 
	ON PC.Id = PE.PaidCategoryId
  INNER JOIN sPayroll.tPayElementDefault PED	
	ON PED.Id = PE.PayElementDefaultId

Where 
	 PE.PayrollId = @rPayrollId  
     AND (PE.Id = @rId OR @rId = 0)
     AND (PE.Code Like @rCode OR ISNULL(@rCode,'') = '')
     AND (PE.Title Like @rTitle OR ISNULL(@rTitle,'') = '')
     AND (PE.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0)
     AND (PE.PaidCategoryId = @rPaidCategoryId OR @rPaidCategoryId = 0) 
     ORDER BY PE.SortOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPayElementListGet]

           @rPayrollId int
           
AS
SET NOCOUNT ON

BEGIN

	SELECT  
			ISNULL(PE.ID,0) AS ID,
			PED.Code,
			PED.Title,
			PED.PayElementTypeId,
			PED.PaidCategoryId,
			ISNULL(PE.IsLwp,0) AS IsLwp,
			ISNULL(PE.IsEmployeeSpecific,0) AS IsEmployeeSpecific,
			ISNULL(PE.IsDepend,0) AS IsDepend,
			ISNULL(PE.IsAvailDuringProbation,0) AS IsAvailDuringProbation,
			ISNULL(PE.IsIncludeInPaySlip,0) AS IsIncludeInPaySlip,
			CASE ISNULL(PE.SortOrder,0)
				WHEN 0 THEN PED.SortOrder
				ELSE PE.SortOrder
			END AS SortOrder,
			--ISNULL(PE.SortOrder,0) AS SortOrder,
			ISNULL(PE.IsObsolete,0) AS IsObsolete,
			PE.CreatedUserId,
			PE.CreatedDateTime,
			PE.UpdatedUserId,
			PE.UpdatedDateTime,
			PED.ID AS PayElementDefaultId,
			PE.PayrollId,
			PET.Title AS PayElementType,
			ISNULL(PE.IsIncludeInTotal,0) AS IsIncludeInTotal
	FROM
			sPayroll.tPayElementDefault PED 
				INNER JOIN sPayroll.tPayElementType PET 
			ON PET.Id=PED.PayElementTypeId
				INNER JOIN sPayroll.tPayElement PE 
			ON PED.ID = PE.PayElementDefaultId AND PE.PayrollId=@rPayrollId AND PE.IsObsolete = 0
			WHERE PED.IsObsolete = 0
			
			ORDER BY PE.SortOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPayProcessAdd] 
	      
	        @rID int
           ,@rSalaryMonth tinyint
           ,@rSalaryYear smallint
           ,@rIsApproved bit
           ,@rStartDateTime datetime           
           ,@rStatusId smallint
           ,@rCreatedUserId bigint        
           ,@rPayrollYearId int
           ,@rOrgGroupId int
           ,@rPayrollId int
           ,@rEmployeeId bigint=0
		   ,@rIsAllow bit=0 --mantis: 40774
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lNextNumber bigint
	DECLARE @lPayProcessId int=0
	
	IF(@rEmployeeId=0)
	BEGIN 
		IF EXISTS(Select 1 FROM sPayroll.tPayProcess Where SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId)
		BEGIN
				SELECT -101 as Result
				RETURN
		END		
	END
	ELSE 
	BEGIN
		IF EXISTS(SELECT 1 FROM sPayroll.tPayProcess PP INNER JOIN sPayroll.tPayProcessEmployee PPE ON PP.Id = PPE.PayProcessId Where PP.SalaryMonth = @rSalaryMonth AND PP.SalaryYear = @rSalaryYear AND PP.PayrollYearId = @rPayrollYearId AND PPE.EmployeeId = @rEmployeeId)
		BEGIN
				SELECT -101 as Result
				RETURN
		END		
		
		SELECT @lPayProcessId = ID  FROM sPayroll.tPayProcess Where  SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId
	END
	
		
	BEGIN TRY
	BEGIN TRANSACTION  
    IF(@rEmployeeId=0)
	BEGIN 
     IF EXISTS(Select 1 FROM sPayroll.tPayProcess Where SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId)
      BEGIN      
		
		SELECT @lPayProcessId = ID  FROM sPayroll.tPayProcess Where  SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId
		 
		DELETE PE from sPayroll.tPayProcessEmployee  PPE
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId = PPE.ID
		WHERE PayProcessId = @lPayProcessId 
		
		DELETE FROM sPayroll.tPayProcessEmployee where PayProcessId = @lPayProcessId
        
        DELETE FROM sPayroll.tPayProcess Where  SalaryMonth = @rSalaryMonth AND SalaryYear = @rSalaryYear AND PayrollYearId = @rPayrollYearId        
        
        DELETE FROM sPayroll.tPfProcess Where PayProcessElementId NOT IN (Select ID From sPayroll.tPayProcessElement)
		DELETE FROM sPayroll.tEsiProcess Where PayProcessElementId NOT IN (Select ID From sPayroll.tPayProcessElement)
      END
     END 
    
    
    IF(@lPayProcessId=0)
    BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcess', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO  [sPayroll].[tPayProcess]
           (
            [ID]
           ,[SalaryMonth]
           ,[SalaryYear]
           ,[IsApproved]
           ,[StartDateTime]   
           ,EndDateTime     
           ,[StatusId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[PayrollYearId]
           )
     VALUES
           (
            @lNextNumber
           ,@rSalaryMonth
           ,@rSalaryYear
           ,@rIsApproved
           ,sCommon.fGetDate()
           ,NULL
           ,@rStatusId
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,@rPayrollYearId
           )
		    Print @lNextNumber
     SELECT @lNextNumber AS Result   --Added by dhananjay for mantis : 
    EXECUTE [sPayroll].[pPayProcessEmployeeAdd] @lNextNumber,@rOrgGroupId,@rPayrollId,@rPayrollYearId,@rSalaryMonth,@rSalaryYear,@rEmployeeId,@rIsAllow --mantis: 40774, add @rIsAllow
	
	END
	ELSE
	BEGIN
		SELECT @lPayProcessId AS Result --Added by dhananjay for mantis : 
	  EXECUTE [sPayroll].[pPayProcessEmployeeAdd] @lPayProcessId,@rOrgGroupId,@rPayrollId,@rPayrollYearId,@rSalaryMonth,@rSalaryYear,@rEmployeeId,@rIsAllow --mantis: 40774, add @rIsAllow
	 
	END
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Process Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPayroll].[pPayProcessDelete]
	 
           @rSalaryMonth tinyint,
           @rSalaryYear smallint,
           @rPayrollYearId int,
           @rPayrollId int,
           @rOrgGroupId int,
           @rEmployeeId bigint=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	-- Delete For EsiProcess
	DELETE sPayroll.tEsiProcess
			FROM sPayroll.tEsiProcess EP
		INNER JOIN sPayroll.tPayProcessElement PPE  
			ON EP.PayProcessElementId=PPE.ID
		INNER JOIN sPayroll.tPayProcessEmployee PPEM 
			ON PPEM.ID=PPE.PayProcessEmployeeId
		INNER JOIN sPayroll.tPayProcess PP
			ON PP.ID=PPEM.PayProcessId
		INNER JOIN sPayroll.tPayrollYearMaster PYM
			ON PYM.Id=PP.PayrollYearId
	WHERE 
		PP.SalaryMonth=@rSalaryMonth
		AND ((PP.SalaryYear = @rSalaryYear))
		AND ((PP.PayrollYearId = @rPayrollYearId))
		AND ((PYM.PayrollId = @rPayrollId))
		AND ((PYM.OrgGroupId = @rOrgGroupId))
		AND (PPEM.EmployeeId = @rEmployeeId OR @rEmployeeId=0)

	-- Delete For PfProcess
	DELETE sPayroll.tPfProcess
			FROM sPayroll.tPfProcess PFP
		INNER JOIN sPayroll.tPayProcessElement PPE  
			ON PFP.PayProcessElementId=PPE.ID
		INNER JOIN sPayroll.tPayProcessEmployee PPEM 
			ON PPEM.ID=PPE.PayProcessEmployeeId
		INNER JOIN sPayroll.tPayProcess PP
			ON PP.ID=PPEM.PayProcessId
		INNER JOIN sPayroll.tPayrollYearMaster PYM
			ON PYM.Id=PP.PayrollYearId
	WHERE 
		PP.SalaryMonth=@rSalaryMonth
		AND ((PP.SalaryYear = @rSalaryYear))
		AND ((PP.PayrollYearId = @rPayrollYearId))
		AND ((PYM.PayrollId = @rPayrollId))
		AND ((PYM.OrgGroupId = @rOrgGroupId))
		AND (PPEM.EmployeeId = @rEmployeeId OR @rEmployeeId=0)
		
	
	-- Delete For PayProcessElement
	DELETE sPayroll.tPayProcessElement
			FROM sPayroll.tPayProcessElement PPE 
		INNER JOIN sPayroll.tPayProcessEmployee PPEM 
			ON PPEM.ID=PPE.PayProcessEmployeeId
		INNER JOIN sPayroll.tPayProcess PP
			ON PP.ID=PPEM.PayProcessId
		INNER JOIN sPayroll.tPayrollYearMaster PYM
			ON PYM.Id=PP.PayrollYearId
	WHERE 
		PP.SalaryMonth=@rSalaryMonth
		AND ((PP.SalaryYear = @rSalaryYear))
		AND ((PP.PayrollYearId = @rPayrollYearId))
		AND ((PYM.PayrollId = @rPayrollId))
		AND ((PYM.OrgGroupId = @rOrgGroupId))
		AND (PPEM.EmployeeId = @rEmployeeId OR @rEmployeeId=0)
		
	
	IF(@rEmployeeId=0)	
	BEGIN
		
		-- Delete For PayProcessEmployee
		DELETE sPayroll.tPayProcessEmployee
				FROM sPayroll.tPayProcessEmployee PPEM 
			INNER JOIN sPayroll.tPayProcess PP
				ON PP.ID=PPEM.PayProcessId
			INNER JOIN sPayroll.tPayrollYearMaster PYM
				ON PYM.Id=PP.PayrollYearId
		WHERE 
			PP.SalaryMonth=@rSalaryMonth
			AND ((PP.SalaryYear = @rSalaryYear))
			AND ((PP.PayrollYearId = @rPayrollYearId))
			AND ((PYM.PayrollId = @rPayrollId))
			AND ((PYM.OrgGroupId = @rOrgGroupId))
			AND (PPEM.EmployeeId = @rEmployeeId OR @rEmployeeId=0)
	    
	    -- Delete For PayProcess
		DELETE sPayroll.tPayProcess
				FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayrollYearMaster PYM
				ON PYM.Id=PP.PayrollYearId
		WHERE 
			PP.SalaryMonth=@rSalaryMonth
			AND ((PP.SalaryYear = @rSalaryYear))
			AND ((PP.PayrollYearId = @rPayrollYearId))
			AND ((PYM.PayrollId = @rPayrollId))
			AND ((PYM.OrgGroupId = @rOrgGroupId))				
	END
	ELSE
	BEGIN
			
		    DECLARE @lCount int=0
			SELECT @lCount=COUNT(EmployeeId) FROM sPayroll.tPayProcessEmployee PPEM 
			INNER JOIN sPayroll.tPayProcess PP
				ON PP.ID=PPEM.PayProcessId
			INNER JOIN sPayroll.tPayrollYearMaster PYM
				ON PYM.Id=PP.PayrollYearId
		    WHERE 
			PP.SalaryMonth=@rSalaryMonth
			AND ((PP.SalaryYear = @rSalaryYear))
			AND ((PP.PayrollYearId = @rPayrollYearId))
			AND ((PYM.PayrollId = @rPayrollId))
			AND ((PYM.OrgGroupId = @rOrgGroupId))
			
			-- Delete For PayProcessEmployee
			DELETE sPayroll.tPayProcessEmployee
					FROM sPayroll.tPayProcessEmployee PPEM 
				INNER JOIN sPayroll.tPayProcess PP
					ON PP.ID=PPEM.PayProcessId
				INNER JOIN sPayroll.tPayrollYearMaster PYM
					ON PYM.Id=PP.PayrollYearId
			WHERE 
				PP.SalaryMonth=@rSalaryMonth
				AND ((PP.SalaryYear = @rSalaryYear))
				AND ((PP.PayrollYearId = @rPayrollYearId))
				AND ((PYM.PayrollId = @rPayrollId))
				AND ((PYM.OrgGroupId = @rOrgGroupId))
				AND (PPEM.EmployeeId = @rEmployeeId OR @rEmployeeId=0)
			
		IF(@lCount=1)	
		BEGIN
		
			-- Delete For PayProcessEmployee
			DELETE sPayroll.tPayProcessEmployee
					FROM sPayroll.tPayProcessEmployee PPEM 
				INNER JOIN sPayroll.tPayProcess PP
					ON PP.ID=PPEM.PayProcessId
				INNER JOIN sPayroll.tPayrollYearMaster PYM
					ON PYM.Id=PP.PayrollYearId
			WHERE 
				PP.SalaryMonth=@rSalaryMonth
				AND ((PP.SalaryYear = @rSalaryYear))
				AND ((PP.PayrollYearId = @rPayrollYearId))
				AND ((PYM.PayrollId = @rPayrollId))
				AND ((PYM.OrgGroupId = @rOrgGroupId))
				AND (PPEM.EmployeeId = @rEmployeeId OR @rEmployeeId=0)
			
			-- Delete For PayProcess
			DELETE sPayroll.tPayProcess
					FROM sPayroll.tPayProcess PP
				INNER JOIN sPayroll.tPayrollYearMaster PYM
					ON PYM.Id=PP.PayrollYearId
			WHERE 
				PP.SalaryMonth=@rSalaryMonth
				AND ((PP.SalaryYear = @rSalaryYear))
				AND ((PP.PayrollYearId = @rPayrollYearId))
				AND ((PYM.PayrollId = @rPayrollId))
				AND ((PYM.OrgGroupId = @rOrgGroupId))
		END
			
	END
	
	SELECT 1 AS Result

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPayProcessElementGet]
	  
	  @rPayProcessEmployeeId bigint 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
		 PPE.PayElementId,
		 PE.Title AS PayElement,
		 PPE.Amount,
		 PET.Title AS PayElementType,
		 PayElementTypeId,
		 PPE.PayProcessEmployeeId,
		 ISNULL(PE.IsIncludeInTotal,0) AS IsIncludeInTotal
	 FROM 
		 sPayroll.tPayProcessElement PPE 
		 INNER JOIN sPayroll.tPayElement PE ON PPE.PayElementId = PE.ID
		 INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
		 
	 WHERE PayProcessEmployeeId = @rPayProcessEmployeeId  AND PE.IsIncludeInPaySlip = 1
	 ORDER BY SortOrder
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPayProcessEmployeeAdd] 
	      	        
            @rPayProcessId int            
           ,@rOrgGroupId int
		   ,@rPayrollId int
		   ,@rPayrollYearId int
		   ,@rSalaryMonth tinyint
           ,@rSalaryYear smallint
           ,@rEmployeeId bigint=0
		   ,@rIsAllow bit=0 --mantis: 40774
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lNextNumber BIGINT
	DECLARE @1PayProcessElementId bigint
	DECLARE @1Count int
	DECLARE @1EmployeeId bigint
	DECLARE @lPayrollGroupId int
	DECLARE @1PayElementCount int
	DECLARE @1TotalEarningAmount DECIMAL(22,6)
	DECLARE @1PaySetupId int
	DECLARE @1SourceId bigint
    DECLARE @1Percentage decimal(5,2)
	DECLARE @1Result decimal(22,6)
	DECLARE @1Amount decimal(22,6)
	DECLARE @1IsDepend bit
	DECLARE @1PayElementId int
	DECLARE @1LWPDeduction decimal(22,6) 
	DECLARE @1IsLwp Bit
	DECLARE @1PayElementTypeId int
	DECLARE @1TotalDeductionAmount DECIMAL(22,6)
	DECLARE @1EmployeeBasicPay DECIMAL(22,6)
	
	DECLARE @1WorkingDays int
	DECLARE @1Lwp Decimal(12,2)
	DECLARE @lPaidLeave Decimal(12,2)
	DECLARE @1GrossBasic Decimal(12,2)
	DECLARE @1PayElementDefaultId int
    DECLARE @lIsIncludeInTotal Bit
	DECLARE @lFormula nvarchar(200)=''
    
    
    DECLARE @lLastDayOfMonth int = DAY(sCommon.GetLastDateofMonth (CONVERT(nvarchar(4),@rSalaryYear)+'-'+CONVERT(nvarchar(2),@rSalaryMonth)+'-01'))
    -- Loan Configuration
    DECLARE @lConfigValue nvarchar(50)
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 206 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	DECLARE @lIsCalculateAllPayElementAsPerJoining nvarchar(50)
	SELECT @lIsCalculateAllPayElementAsPerJoining = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 307 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	DECLARE @lIsPayrollCountBasedOnWorkingDays nvarchar(50)
	SELECT @lIsPayrollCountBasedOnWorkingDays = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 310 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
    
    DECLARE @lIsPayrollEvaluationOnFixDay nvarchar(50)
	SELECT @lIsPayrollEvaluationOnFixDay = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 324 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
    
	DECLARE @lIsRoundOffToWholeNumber nvarchar(50)
	DECLARE @lRoundOffToWholeNumber int
	SELECT @lIsRoundOffToWholeNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 248 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	IF (@lIsRoundOffToWholeNumber IS NULL) OR (@lIsRoundOffToWholeNumber = 'True')
		SET @lRoundOffToWholeNumber = 0
	ELSE
		SET @lRoundOffToWholeNumber = 2	
	--IF (@rId = 0)
	IF(@rEmployeeId=0)
	BEGIN
		CREATE TABLE #tmpEmpDetail
		(
			Id INT IDENTITY (1, 1),
			EmployeeId  bigint,
			PayrollGroupId int
		)
		 
		INSERT INTO #tmpEmpDetail
		Select ES.EmployeeId,PayrollGroupId FROM sHrm.tEmployeeStatutoryAndOther ES
		INNER JOIN  sHrm.tEmployeeAttendance EA ON ES.EmployeeId = EA.EmployeeId
		INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
		Where PayrollId = @rPayrollId AND PayrollGroupId IS NOT NULL
		AND EA.ForMonth = @rSalaryMonth AND EA.ForYear = @rSalaryYear
   
		Select @1Count = COUNT(*) FROM #tmpEmpDetail 
      
		WHILE @1Count > 0 
		BEGIN	 
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessEmployee', 0, 1, 1,@outNextNumber = @lNextNumber output	
		    SELECT @1EmployeeId = EmployeeId,@lPayrollGroupId = PayrollGroupId FROM #tmpEmpDetail WHERE ID = @1Count
		   
		    SELECT @1WorkingDays = TotalWorkingDays,@1Lwp = LWP, @lPaidLeave=ISNULL(PaidLeave,0) FROM sHrm.tEmployeeAttendance EA
		    INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
		    Where EA.EmployeeId=@1EmployeeId AND EA.ForYear=@rSalaryYear AND EA.ForMonth=@rSalaryMonth
					
		    SELECT @1GrossBasic = PS.Amount FROM sPayroll.tPaySetup PS 
			INNER JOIN sPayroll.tPayElement PE ON PE.Id=PS.PayElementId
			Where PS.SourceTypeId = 95 
			AND PS.SourceId=@1EmployeeId 
			AND PS.PayrollId=@rPayrollId 
			AND PS.PayrollYearId = @rPayrollYearId 
			AND PE.PayElementDefaultId=1 
		   
		    IF EXISTS (SELECT 1 FROM sPayroll.tPaySetup WHERE SourceTypeId=2020 AND SourceId=@lPayrollGroupId AND PayrollId=@rPayrollId AND PayrollYearId=@rPayrollYearId)
		    BEGIN		    
		    INSERT INTO  [sPayroll].[tPayProcessEmployee]
				   (
				    [ID]
				   ,[PayProcessId]
				   ,[EmployeeId]
				   ,[PayrollGroupId]
				   ,TotalEarning
				   ,TotalDeduction
				   ,NetAmount
				   ,WorkingDays
				   ,Lwp
				   ,GrossBasic
				   ,PaidLeave
				   )
			VALUES
				   (
				    @lNextNumber
				   ,@rPayProcessId
				   ,@1EmployeeId 
				   ,@lPayrollGroupId
				   ,0.0
				   ,0.0
				   ,0.0
				   ,@1WorkingDays
				   ,@1Lwp
				   ,@1GrossBasic
				   ,@lPaidLeave
				   )
				   
		      
	     -- FOR Counting Total Earning
	 
		 CREATE TABLE #tmpPaysetupElement
		(
		   Id INT IDENTITY (1, 1),
		   PaySetupId int,
		   SourceId bigint,
		   SourceTypeId int,
		   PayElementId int,
		   Amount DECIMAl(22,6) NULL,
		   Percentage DECIMAl(5,2) NULL,
		   IsDepend bit,
		   PayElementTypeId int,
		   ProcessOrder int,
		   PayElementDefaultId int  ,
		   Formula nvarchar(200)
		)  
		   
		   BEGIN
		 --IF EXISTS (select 1 from sPayroll.tpaysetup where SourceId = @1EmployeeId AND SourceTypeId = 3016) --For Pay Setup Employee
		     INSERT INTO #tmpPaysetupElement
		     SELECT PE.ID,PE.SourceId,PE.SourceTypeId,PE.PayElementId,PE.Amount,PE.Percentage,PE.IsDepend,PE.PayElementTypeId,PE.ProcessOrder,PayElementDefaultId,PE.Formula FROM 
		     (		     
		     SELECT PS.ID,SourceId,95 AS SourceTypeId ,PayElementId,Amount,Percentage,ISNULL(IsDepend,0) AS IsDepend,PayElementTypeId,ProcessOrder,PE.PayElementDefaultId,ISNULL(PS.Formula,'') As Formula
		     FROM sPayroll.tPaySetup PS INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @1EmployeeId 
			 AND SourceTypeId = 95 
			 AND PS.PayrollId=@rPayrollId 
			 AND PS.PayrollYearId = @rPayrollYearId
		 
		 --ELSE 
		     UNION ALL
		      
		     --INSERT INTO #tmpPaysetupElement
		     SELECT PS.ID,SourceId,2020 AS SourceTypeId,PayElementId,Amount,Percentage,IsDepend,PayElementTypeId,ProcessOrder 
			 ,PE.PayElementDefaultId,ISNULL(PS.Formula,'') As Formula
		     FROM sPayroll.tPaySetup  PS  INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @lPayrollGroupId AND SourceTypeId = 2020 AND PS.PayrollId=@rPayrollId AND PS.PayrollYearId = @rPayrollYearId
			 AND PayElementId NOT IN (SELECT  PayElementId FROM sPayroll.tPaySetup  PS 
		     INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
		     WHERE SourceId = @1EmployeeId 
		     AND SourceTypeId = 95 
		     AND PS.PayrollId=@rPayrollId 
		     AND PS.PayrollYearId = @rPayrollYearId)  			 
			 
		     ) PE  ORDER BY ProcessOrder  DESC
		  	END	
		  	  
		    --Select * FROM #tmpPaysetupElement
		  
		  	SELECT @1PayElementCount = COUNT(*) FROM #tmpPaysetupElement
			
			SET @1TotalDeductionAmount = 0
			SET   @1TotalEarningAmount = 0
			WHILE @1PayElementCount > 0
				BEGIN				
					SET @1PaySetupId = 0
					SET @1SourceId = 0
					SET @1Percentage = 0.0
					SET @1Result = 0.0
					SET @1Amount = 0.0 			
					SET @1PayElementId = 0
					SET @1IsLwp = 0
					SET @1LWPDeduction = 0
					SET @1PayElementDefaultId = 0
					SET @lFormula = ''
			  
			    SELECT @1PaySetupId = PaySetupId,@1SourceId = SourceId,@1PayElementId = PayElementId,@1Result = Amount,
			    @1Percentage = Percentage,@1IsDepend = IsDepend,@1PayElementTypeId=PayElementTypeId,@1PayElementDefaultId =PayElementDefaultId,
				@lFormula=Formula
				FROM #tmpPaysetupElement WHERE Id = @1PayElementCount
			      
			    SELECT @1IsLwp = IsLwp, @lIsIncludeInTotal=IsIncludeInTotal FROM sPayroll.tPayElement Where Id = @1PayElementId AND PayrollId = @rPayrollId
			    
			    IF(@1PayElementDefaultId=1)
			    BEGIN
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END
			    
			    --IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND @lIsCalculateAllPayElementAsPerJoining IS NULL) OR (@lIsCalculateAllPayElementAsPerJoining = 'False')
			    IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND (@lIsCalculateAllPayElementAsPerJoining IS NULL OR @lIsCalculateAllPayElementAsPerJoining = 'False'))		-- Mantis Id : 0043289
			    BEGIN 
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END	    
			       
			    IF(@1IsLwp = 1) 			     
			        SELECT @1LWPDeduction = [sPayroll].[fCalculateLWP] (@1EmployeeId, @rPayProcessId,ISNULL(@1Result,0))			      
			               
			    IF(@1IsDepend = 1 AND @1PayElementDefaultId NOT IN(55,56,57)) -- ESI,PF,PT seperatly calculated
			        EXECUTE [sPayroll].[pCalculatePayrollAmount]  @1PaySetupId,@1PayElementId,@1Percentage,@1SourceId,@rOrgGroupId,@1EmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@lFormula,@1Result OUTPUT
			    
			    IF(@1WorkingDays = 0)      
					SET @1Result =  0    
			    ELSE
					SET @1Result =  ROUND(ISNULL(@1Result,0.0) -  ISNULL(@1LWPDeduction,0.00),@lRoundOffToWholeNumber)	         
			      
			    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessElement', 0, 1, 1,@outNextNumber = @1PayProcessElementId output	
		
	        	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')	
	        	BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   )  
	        	END
	        	ELSE
	        	BEGIN
	        		IF(@1PayElementDefaultId = 58)
	        		BEGIN
						SET @1Result= [sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,58)
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						  ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,58)
						   )  
					END
					
	        		ELSE IF(@1PayElementDefaultId = 63)
	        		BEGIN
					SET @1Result= [sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,63)
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,63)
						   )  
					END
					ELSE
					BEGIN
					INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						 @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   )  
					END
						   
				END
			       
			    
			    
			     IF( @1PayElementTypeId = 1)
			     BEGIN	      	 
			      IF(@lIsIncludeInTotal = 1)
					SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0) + ISNULL(@1Result,0)		      
				  ELSE
					SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0)	      
			     END
			     
			     ELSE 
			       BEGIN 
			        IF(@lIsIncludeInTotal = 1)
						SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0) + ISNULL(@1Result,0) 	      
					ELSE
						SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0)	  
			            --- ISNULL(@1LWPDeduction,0)      
			       END   
			     		    
			    SET @1PayElementCount = @1PayElementCount -1			     
			  END	 
		    --SELECT * from #tmpPaysetupElement
			DROP TABLE #tmpPaysetupElement
		       
			END	   
		   EXECUTE [sPayroll].[pCalculateStaticPayElement]  @lNextNumber,@rOrgGroupId,@1TotalEarningAmount,@1SourceId,@1TotalDeductionAmount,@rPayrollId,@rPayrollYearId,@lPayrollGroupId,@rSalaryMonth,@rSalaryYear,@1EmployeeId,@rIsAllow --mantis: 40774, add @rIsAllow
			--SELECT  TOP 1 @lTax = Tax  FROM sPayroll.tProfessionalTaxRange where Salary < @rSalary Order By Salary Desc
  		    
		 SET @1Count = @1Count - 1	
	END	    
	--DROP TABLE #tmpPaysetupElement
	DROP TABLE #tmpEmpDetail
	SELECT @lNextNumber AS Result	
	
	END
	ELSE
	BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessEmployee', 0, 1, 1,@outNextNumber = @lNextNumber output	
		    
			SELECT @lPayrollGroupId = PayrollGroupId FROM sHrm.tEmployeeStatutoryAndOther WHERE EmployeeId = @rEmployeeId
		    
		    SELECT @1WorkingDays = TotalWorkingDays,@1Lwp = LWP, @lPaidLeave=ISNULL(PaidLeave,0) FROM sHrm.tEmployeeAttendance EA
		    INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
		     Where EA.EmployeeId=@rEmployeeId AND EA.ForYear=@rSalaryYear AND EA.ForMonth=@rSalaryMonth


		    SELECT @1GrossBasic = PS.Amount FROM sPayroll.tPaySetup PS 
			INNER JOIN sPayroll.tPayElement PE ON PE.Id=PS.PayElementId
			Where PS.SourceTypeId = 95 
			AND PS.SourceId=@rEmployeeId 
			AND PS.PayrollId=@rPayrollId 
			AND PS.PayrollYearId = @rPayrollYearId 
			AND PE.PayElementDefaultId=1 
					  
		   INSERT INTO  [sPayroll].[tPayProcessEmployee]
				   (
				    [ID]
				   ,[PayProcessId]
				   ,[EmployeeId]
				   ,[PayrollGroupId]
				   ,TotalEarning
				   ,TotalDeduction
				   ,NetAmount
				   ,WorkingDays
				   ,Lwp
				   ,GrossBasic
				   ,PaidLeave
				   )
			 VALUES
				   (
				    @lNextNumber
				   ,@rPayProcessId
				   ,@rEmployeeId 
				   ,@lPayrollGroupId
				   ,0.0
				   ,0.0
				   ,0.0
				   ,@1WorkingDays
				   ,@1Lwp
				   ,@1GrossBasic
				   ,@lPaidLeave
				   )
		   
	     -- FOR Counting Total Earning
	 
			CREATE TABLE #TempPaysetupElement
		(
		   Id INT IDENTITY (1, 1),
		   PaySetupId int,
		   SourceId bigint,
		   SourceTypeId int,
		   PayElementId int,
		   Amount DECIMAl(22,6) NULL,
		   Percentage DECIMAl(5,2) NULL,
		   IsDepend bit,
		   PayElementTypeId int,
		   ProcessOrder int,
		   PayElementDefaultId int,
		   Formula nvarchar(200)
		)  
		   
			BEGIN
		     INSERT INTO #TempPaysetupElement
		     SELECT PE.ID,PE.SourceId,PE.SourceTypeId,PE.PayElementId,PE.Amount,PE.Percentage,PE.IsDepend,PE.PayElementTypeId,PE.ProcessOrder,PayElementDefaultId,PE.Formula FROM 
		     (		     
		     SELECT PS.ID,SourceId,95 AS SourceTypeId ,PayElementId,Amount,Percentage,ISNULL(IsDepend,0) AS IsDepend,PayElementTypeId,ProcessOrder,PE.PayElementDefaultId,ISNULL(PS.Formula,'') AS  Formula
		     FROM sPayroll.tPaySetup PS INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @rEmployeeId 
			 AND SourceTypeId = 95 
			 AND PS.PayrollId=@rPayrollId 
			 AND PS.PayrollYearId = @rPayrollYearId
		     UNION ALL
		     SELECT PS.ID,SourceId,2020 AS SourceTypeId,PayElementId,Amount,Percentage,IsDepend,PayElementTypeId,ProcessOrder ,PE.PayElementDefaultId,ISNULL(PS.Formula,'') AS  Formula
		     FROM sPayroll.tPaySetup  PS  INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @lPayrollGroupId AND SourceTypeId = 2020 AND PS.PayrollId=@rPayrollId AND PS.PayrollYearId = @rPayrollYearId
			 AND PayElementId NOT IN (SELECT  PayElementId FROM sPayroll.tPaySetup  PS 
		     INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
		     WHERE SourceId = @rEmployeeId 
		     AND SourceTypeId = 95 
		     AND PS.PayrollId=@rPayrollId 
		     AND PS.PayrollYearId = @rPayrollYearId)  			 
		     ) PE  ORDER BY ProcessOrder  DESC
		  	END	
		  	  
		  	SELECT @1PayElementCount = COUNT(*) FROM #TempPaysetupElement
			
			SET @1TotalDeductionAmount = 0
			SET   @1TotalEarningAmount = 0
			WHILE @1PayElementCount > 0
			BEGIN				
					SET @1PaySetupId = 0
					SET @1SourceId = 0
					SET @1Percentage = 0.0
					SET @1Result = 0.0
					SET @1Amount = 0.0 			
					SET @1PayElementId = 0
					SET @1IsLwp = 0
					SET @1LWPDeduction = 0
					SET @1PayElementDefaultId = 0
					SET @lFormula=''
			  
			    SELECT @1PaySetupId = PaySetupId,@1SourceId = SourceId,@1PayElementId = PayElementId,@1Result = Amount,
			    @1Percentage = Percentage,@1IsDepend = IsDepend,@1PayElementTypeId=PayElementTypeId,@1PayElementDefaultId =PayElementDefaultId, @lFormula=Formula FROM #TempPaysetupElement WHERE Id = @1PayElementCount
			      
			    SELECT @1IsLwp = IsLwp, @lIsIncludeInTotal=IsIncludeInTotal FROM sPayroll.tPayElement Where Id = @1PayElementId AND PayrollId = @rPayrollId
			    					      
			    IF(@1PayElementDefaultId=1)
			    BEGIN
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END
			    
			    IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND @lIsCalculateAllPayElementAsPerJoining IS NULL) OR (@lIsCalculateAllPayElementAsPerJoining = 'False')
			    BEGIN 
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END	    
			    
			  --  IF(@1PayElementDefaultId=1)
			  --  BEGIN 
					--IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
					--	SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
					--ELSE
					--	SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			  --  END	 
			    
			  --  IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND @lIsCalculateAllPayElementAsPerJoining IS NULL) OR (@lIsCalculateAllPayElementAsPerJoining = 'False')
			  --  BEGIN 
					--IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
					--	SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
					--ELSE
					--	SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays
			  --  END	    
			       
			    IF(@1IsLwp = 1) 			     
			        SELECT @1LWPDeduction = [sPayroll].[fCalculateLWP] (@rEmployeeId, @rPayProcessId,ISNULL(@1Result,0))			      
			           
			    IF(@1IsDepend = 1 AND @1PayElementDefaultId NOT IN(55,56,57)) -- ESI,PF,PT seperatly calculated
					BEGIN 
						
						EXECUTE [sPayroll].[pCalculatePayrollAmount]  @1PaySetupId,@1PayElementId,@1Percentage,@1SourceId,@rOrgGroupId,@rEmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@lFormula,@1Result OUTPUT
						-- PRINT CAST(@1Result As varchar) + 'FormulaAmount' + CAST(@1PayElementDefaultId As nvarchar) 
					END
			    
			           
			    IF(@1WorkingDays = 0)      
					SET @1Result =  0    
			    ELSE
					SET @1Result =  ROUND(ISNULL(@1Result,0.0) -  ISNULL(@1LWPDeduction,0.00),@lRoundOffToWholeNumber)	       
				
			    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessElement', 0, 1, 1,@outNextNumber = @1PayProcessElementId output	
			        
			    IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')	
	        	BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   ) 
						   -- PRINT CAST(@1Result As varchar) + ' Config, '  + CAST(@1PayProcessElementId  As varchar) 
	        	END
	        	ELSE
	        	BEGIN
	        		IF(@1PayElementDefaultId = 58)
	        		BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						  ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,58)
						  
						   )  
						   -- PRINT CAST(@1Result As varchar) + ' 58, '  + CAST(@1PayProcessElementId  As varchar)
					END
	        		ELSE IF(@1PayElementDefaultId = 63)
	        		BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,63)
						   
						   )  
						   -- PRINT CAST(@1Result As varchar) + ' 63, '  + CAST(@1PayProcessElementId  As varchar)
					END
					ELSE
					BEGIN
					INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   ) 
						   -- PRINT CAST(@1Result As varchar) + ' else, '  + CAST(@1PayProcessElementId  As varchar)
					END	
					
				END
			    
			      IF(@1WorkingDays = 0)
			      BEGIN
						IF( @1PayElementTypeId = 1)
						 BEGIN	      	 
						  IF(@lIsIncludeInTotal = 1)
							SET @1TotalEarningAmount = 0 
						  ELSE
							SET @1TotalEarningAmount = 0
						 END
						 ELSE 
						 BEGIN 
							IF(@lIsIncludeInTotal = 1)
								SET @1TotalDeductionAmount = 0
							ELSE
								SET @1TotalDeductionAmount = 0
						 END   
			      END
			      ELSE
			      BEGIN
			             IF( @1PayElementTypeId = 1)
						 BEGIN	      	 
						  IF(@lIsIncludeInTotal = 1)
							SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0) + ISNULL(@1Result,0)		      
						  ELSE
							SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0)	      
						 END
						 ELSE 
						 BEGIN 
							IF(@lIsIncludeInTotal = 1)
								SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0) + ISNULL(@1Result,0) 	      
							ELSE
								SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0)	  
						 END   
			      END
			       
			     SET @1PayElementCount = @1PayElementCount -1	
			   	
			   	 END
			   	 
			DROP TABLE #TempPaysetupElement
				   
		   EXECUTE [sPayroll].[pCalculateStaticPayElement]  @lNextNumber,@rOrgGroupId,@1TotalEarningAmount,@1SourceId,@1TotalDeductionAmount,@rPayrollId,@rPayrollYearId,@lPayrollGroupId,@rSalaryMonth,@rSalaryYear,@rEmployeeId,@rIsAllow --mantis: 40774, add @rIsAllow
	    
		
	SELECT @lNextNumber AS Result	
	
	END	
    
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


 CREATE OR ALTER PROCEDURE [sPayroll].[pPayProcessEmployeeDetailGet]
	 @rEmployeeId bigint,
	 @rPayrollGroupId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollYearId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))

	DECLARE @lPayrollGroupId int
	SELECT @lPayrollGroupId = PayrollGroupId FROM sHrm.tEmployeeStatutoryAndOther WHERE EmployeeId = @rEmployeeId

	IF EXISTS (SELECT 1 FROM sPayroll.tPayProcessEmployee PPE INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId = PP.Id WHERE EmployeeId = @rEmployeeId AND SalaryMonth = @rForMonth AND SalaryYear = @rForYear AND PayrollYearId = @rPayrollYearId)
	BEGIN
		SELECT 
		PP.Id As ProcessId,
		PPE.Id As PayProcessEmployeeId,
			PAE.Title AS PayElement,
			PE.Amount AS ProcessAmount,
			PET.Title AS PayElementType,
			PayElementTypeId,
			PS.Amount,
			PS.Percentage,
			ISNULL(PS.ProcessOrder,0) AS ProcessOrder,
			ISNULL(PS.DefaultAmount,0) AS DefaultAmount,
			PAE.IsDepend,
			PAE.IsEmployeeSpecific,
			PS.Id AS PaySetupId,
			PS.PayElementId,
			PS.SourceId,
			95 as SourceTypeId,
			PAE.payElementDefaultId,
			PAE.IsLwp,
			PS.Formula,
			PAE.PayrollId
		FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			LEFT JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId = PPE.Id
			INNER JOIN sPayroll.tPayElement PAE ON PAE.Id = PE.PayElementId
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
			INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PAE.PayElementTypeId
			INNER JOIN sPayroll.tPaySetup PS ON PS.PayElementId = PAE.Id 
			AND PS.SourceId = EM.EmployeeId AND PS.PayrollYearId = PP.PayrollYearId
			INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=AT.BatchId AND BM.IsActive=1
		WHERE 
			(EM.EmployeeId = @rEmployeeId) AND PS.SourceTypeId = 95
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (SalaryYear = @rForYear OR @rForYear = 0)
			AND  PP.PayrollYearId = @rPayrollYearId AND PET.Id = 1
			AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth

		UNION ALL

		SELECT  
		PP.Id As ProcessId,
			PPE.Id As PayProcessEmployeeId,
			PAE.Title AS PayElement,
			PE.Amount AS ProcessAmount,
			PET.Title AS PayElementType,
			PayElementTypeId,
			PS.Amount,
			PS.Percentage,
			ISNULL(PS.ProcessOrder,0) AS ProcessOrder,
			ISNULL(PS.DefaultAmount,0) AS DefaultAmount,
			PAE.IsDepend,
			PAE.IsEmployeeSpecific,
			PS.Id AS PaySetupId,
			PS.PayElementId,
			PS.SourceId,
			2020 as SourceTypeId,
			PAE.payElementDefaultId,
			PAE.IsLwp,
			PS.Formula,
			PAE.PayrollId
		FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			LEFT JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId = PPE.Id
			INNER JOIN sPayroll.tPayElement PAE ON PAE.Id = PE.PayElementId
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
			INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PAE.PayElementTypeId
			INNER JOIN sPayroll.tPaySetup PS ON PS.PayElementId = PAE.Id 
			AND PS.SourceTypeId = 2020 AND PPE.PayrollGroupId=PS.SourceId AND PS.PayrollYearId = PP.PayrollYearId
			INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=AT.BatchId AND BM.IsActive=1
		WHERE 
			(EM.EmployeeId = @rEmployeeId)
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (SalaryYear = @rForYear OR @rForYear = 0)
			AND  PP.PayrollYearId = @rPayrollYearId AND PET.Id = 1
			AND PS.PayElementId NOT IN (SELECT PayElementId FROM sPayroll.tPaySetup  PS 
				INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
				WHERE SourceId = @rEmployeeId AND SourceTypeId = 95 
				AND PS.PayrollYearId = @rPayrollYearId)
			AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth

		Order By ProcessOrder
		 

		 SELECT 
		 PP.Id As ProcessId,
		 	PPE.Id As PayProcessEmployeeId,
			PAE.Title AS PayElement,
			PE.Amount AS ProcessAmount,
			PET.Title AS PayElementType,
			PayElementTypeId,
			PS.Amount,
			PS.Percentage,
			ISNULL(PS.ProcessOrder,0) AS ProcessOrder,
			ISNULL(PS.DefaultAmount,0) AS DefaultAmount,
			PAE.IsDepend,
			PAE.IsEmployeeSpecific,
			PS.Id AS PaySetupId,
			PS.PayElementId,
			PS.SourceId,
			95 as SourceTypeId,
			PAE.payElementDefaultId,
			PAE.IsLwp
		FROM 
			sPayroll.tPayProcess PP 
			LEFT JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			LEFT JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId = PPE.Id
			INNER JOIN sPayroll.tPayElement PAE ON PAE.Id = PE.PayElementId
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
			INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PAE.PayElementTypeId
			INNER JOIN sPayroll.tPaySetup PS ON PS.PayElementId = PAE.Id 
			AND PS.SourceId = EM.EmployeeId AND PS.PayrollYearId = PP.PayrollYearId
			INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=AT.BatchId AND BM.IsActive=1
		WHERE 
			(EM.EmployeeId = @rEmployeeId) AND PS.SourceTypeId = 95
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (SalaryYear = @rForYear OR @rForYear = 0)
			AND  PP.PayrollYearId = @rPayrollYearId AND PET.Id = 2
			AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth

		UNION ALL

		SELECT  
		PP.Id As ProcessId,
			PPE.Id As PayProcessEmployeeId,
			PAE.Title AS PayElement,
			PE.Amount AS ProcessAmount,
			PET.Title AS PayElementType,
			PayElementTypeId,
			PS.Amount,
			PS.Percentage,
			ISNULL(PS.ProcessOrder,0) AS ProcessOrder,
			ISNULL(PS.DefaultAmount,0) AS DefaultAmount,
			PAE.IsDepend,
			PAE.IsEmployeeSpecific,
			PS.Id AS PaySetupId,
			PS.PayElementId,
			PS.SourceId,
			2020 as SourceTypeId,
			PAE.payElementDefaultId,
			PAE.IsLwp
		FROM 
			sPayroll.tPayProcess PP 
			LEFT JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			LEFT JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId = PPE.Id
			INNER JOIN sPayroll.tPayElement PAE ON PAE.Id = PE.PayElementId
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
			INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PAE.PayElementTypeId
			INNER JOIN sPayroll.tPaySetup PS ON PS.PayElementId = PAE.Id
			AND PS.SourceTypeId = 2020 AND PPE.PayrollGroupId=PS.SourceId AND PS.PayrollYearId = PP.PayrollYearId
			INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=AT.BatchId AND BM.IsActive=1
		WHERE 
			(EM.EmployeeId = @rEmployeeId)
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (SalaryYear = @rForYear OR @rForYear = 0)
			AND  PP.PayrollYearId = @rPayrollYearId AND PET.Id = 2
			AND PS.PayElementId NOT IN (SELECT PayElementId FROM sPayroll.tPaySetup  PS 
				INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
				WHERE SourceId = @rEmployeeId AND SourceTypeId = 95 
				AND PS.PayrollYearId = @rPayrollYearId)
			AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth

		Order By ProcessOrder
	END
	ELSE
	BEGIN
	     
		 SELECT 
		 
			 PE.Title As PayElement,
			 0 As ProcessAmount,
			 PET.Title AS PayElementType,
			 PE.PayElementTypeId AS PayElementTypeId,
			 PS.Amount,
			 PS.Percentage,
			 ISNULL(PS.ProcessOrder,0) AS ProcessOrder,
			 ISNULL(PS.DefaultAmount,0) AS DefaultAmount,
			 PE.IsDepend,
			 PE.IsEmployeeSpecific,
			 PS.Id AS PaySetupId,
			 PS.PayElementId,
			 PS.SourceId,
			95 as SourceTypeId,
			PE.payElementDefaultId,
			PE.IsLwp,
			ISNULL(PS.Formula,'') As Formula,
			PE.PayrollId
		 FROM 
			 sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON EM.EmployeeId = ESO.EmployeeId
			INNER JOIN sPayroll.tPayrollMaster PM ON PM.Id = ESO.PayrollId
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PY.PayrollId = PM.Id AND (PY.Id = @rPayrollYearId)
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID	
			INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			INNER JOIN sSetup.tBatchMaster BM ON AT.BatchId = BM.Id	AND BM.IsActive = 1
			INNER JOIN sPayroll.tPaySetup PS ON PS.PayrollId = PM.Id 
			INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
		 WHERE 
			 SourceId = @rEmployeeId
			 AND SourceTypeId = 95 
			 AND PS.PayrollYearId = @rPayrollYearId
			 AND PET.Id = 1 AND EM.EmployeeId = @rEmployeeId
			 AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth
			 AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			 AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			 AND EM.IsOtherUser = 0

		 UNION ALL

		 SELECT 

			 PE.Title As PayElement,
			 0 As ProcessAmount,
			 PET.Title AS PayElementType,
			 PE.PayElementTypeId AS PayElementTypeId,
			 PS.Amount,
			 PS.Percentage,
			 ISNULL(PS.ProcessOrder,0) AS ProcessOrder,
			 ISNULL(PS.DefaultAmount,0) AS DefaultAmount,
			 PE.IsDepend,
			 PE.IsEmployeeSpecific,
			 PS.Id AS PaySetupId,
			 PS.PayElementId,
			 PS.SourceId,
			 2020 as SourceTypeId,
			 PE.payElementDefaultId,
			PE.IsLwp,
			ISNULL(PS.Formula,'') As Formula,
			PE.PayrollId
		 FROM 
			 sHrm.vEmployeeCommonDetail EM
			 INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON EM.EmployeeId = ESO.EmployeeId
			 INNER JOIN sPayroll.tPayrollMaster PM ON PM.Id = ESO.PayrollId
			 INNER JOIN sPayroll.tPayrollYearMaster PY ON PY.PayrollId = PM.Id AND (PY.Id = @rPayrollYearId)
			 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID	
			 INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			 INNER JOIN sSetup.tBatchMaster BM ON AT.BatchId = BM.Id	AND BM.IsActive = 1
			 INNER JOIN sPayroll.tPaySetup PS ON PS.PayrollId = PM.Id
			 INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
		 WHERE 
			 SourceId = @lPayrollGroupId AND SourceTypeId = 2020 
			 AND PS.PayrollYearId = @rPayrollYearId  AND PET.Id = 1
			 AND PayElementId NOT IN (SELECT  PayElementId FROM sPayroll.tPaySetup  PS 
				 INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
				 WHERE SourceId = @rEmployeeId AND SourceTypeId = 95 
				 AND PS.PayrollYearId = @rPayrollYearId) 
			 AND EM.EmployeeId = @rEmployeeId
			 AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth
			 AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			 AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			 AND EM.IsOtherUser = 0

		Order By ProcessOrder

		SELECT 
			 PE.Title As PayElement,
			 0 As ProcessAmount,
			 PET.Title AS PayElementType,
			 PE.PayElementTypeId AS PayElementTypeId,
			 PS.Amount,
			 PS.Percentage,
			 ISNULL(PS.ProcessOrder,0) AS ProcessOrder,
			 ISNULL(PS.DefaultAmount,0) AS DefaultAmount,
			 PE.IsDepend,
			 PE.IsEmployeeSpecific,
			 PS.Id AS PaySetupId,
			 PS.PayElementId,
			 PS.SourceId,
			 95 as SourceTypeId,
			 PE.payElementDefaultId,
			PE.IsLwp,
			ISNULL(PS.Formula,'') As Formula,
			PE.PayrollId
		 FROM 
			 sHrm.vEmployeeCommonDetail EM
			 INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON EM.EmployeeId = ESO.EmployeeId
			 INNER JOIN sPayroll.tPayrollMaster PM ON PM.Id = ESO.PayrollId
			 INNER JOIN sPayroll.tPayrollYearMaster PY ON PY.PayrollId = PM.Id AND (PY.Id = @rPayrollYearId)
			 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID	
			 INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			 INNER JOIN sSetup.tBatchMaster BM ON AT.BatchId = BM.Id	AND BM.IsActive = 1
			 INNER JOIN sPayroll.tPaySetup PS ON PS.PayrollId = PM.Id
			 INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
		 WHERE 
			 SourceId = @rEmployeeId
			 AND SourceTypeId = 95 
			 AND PS.PayrollYearId = @rPayrollYearId
			 AND PET.Id = 2 AND EM.EmployeeId = @rEmployeeId
			 AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth
			 AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			 AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			 AND EM.IsOtherUser = 0
		 
		 UNION ALL

		 SELECT 

			 PE.Title As PayElement,
			 0 As ProcessAmount,
			 PET.Title AS PayElementType,
			 PE.PayElementTypeId AS PayElementTypeId,
			 PS.Amount,
			 PS.Percentage,
			 ISNULL(PS.ProcessOrder,0) AS ProcessOrder,
			 ISNULL(PS.DefaultAmount,0) AS DefaultAmount,
			 PE.IsDepend,
			 PE.IsEmployeeSpecific,
			 PS.Id AS PaySetupId,
			 PS.PayElementId,
			 PS.SourceId,
			 2020 as SourceTypeId,
			 PE.payElementDefaultId,
			PE.IsLwp,
			ISNULL(PS.Formula,'') As Formula,
			PE.PayrollId
		 FROM 
			 sHrm.vEmployeeCommonDetail EM
			 INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON EM.EmployeeId = ESO.EmployeeId
			 INNER JOIN sPayroll.tPayrollMaster PM ON PM.Id = ESO.PayrollId
			 INNER JOIN sPayroll.tPayrollYearMaster PY ON PY.PayrollId = PM.Id AND (PY.Id = @rPayrollYearId)
			 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID	
			 INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			 INNER JOIN sSetup.tBatchMaster BM ON AT.BatchId = BM.Id	AND BM.IsActive = 1
			 INNER JOIN sPayroll.tPaySetup PS ON PS.PayrollId = PM.Id
			 INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
		 WHERE 
			 SourceId = @lPayrollGroupId AND SourceTypeId = 2020 
			 AND PS.PayrollYearId = @rPayrollYearId  AND PET.Id = 2
			 AND PayElementId NOT IN (SELECT  PayElementId FROM sPayroll.tPaySetup  PS 
				 INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
				 WHERE SourceId = @rEmployeeId AND SourceTypeId = 95 
				 AND PS.PayrollYearId = @rPayrollYearId) 
			AND EM.EmployeeId = @rEmployeeId
			AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth
			AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			AND EM.IsOtherUser = 0
		Order By ProcessOrder
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sPayroll].[pPayProcessEmployeeList]
	
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rPayrollGroupId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollYearId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT  
		EM.EmployeeId,
		EM.EmployeeName,
		EM.Code AS EmployeeCode,
		OM.DisplayTitle AS OrgName,
		CASE  WHEN A.EmployeeId IS NOT NULL THEN 'Generated' ELSE 'Pending' END AS StatusName
	FROM 
		sHrm.vEmployeeCommonDetail EM
		INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO
			ON EM.EmployeeId = ESO.EmployeeId
		INNER JOIN sPayroll.tPayrollMaster PM
			ON PM.Id = ESO.PayrollId
		INNER JOIN sPayroll.tPayrollYearMaster PY 
			ON PY.PayrollId = PM.Id AND (PY.Id = @rPayrollYearId)
		INNER JOIN sSetup.tOrganizationMaster OM 
			ON OM.Id = EM.OrgID	
		INNER JOIN sHrm.tEmployeeAttendance AT 
			ON AT.EmployeeId=EM.EmployeeId
		INNER JOIN sSetup.tBatchMaster BM 
			ON AT.BatchId = BM.Id	AND BM.IsActive = 1
		LEFT JOIN 
		(
			SELECT PPE.EmployeeId FROM sHrm.vEmployeeCommonDetail EM
		INNER JOIN sPayroll.tPayProcessEmployee PPE 
			ON PPE.EmployeeId = EM.EmployeeId 
		INNER JOIN sPayroll.tPayProcess PP 	
			ON PPE.PayProcessId = PP.ID 
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0) 
			AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
			AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0)
		) A ON A.EmployeeId =  EM.EmployeeId	
	WHERE 
		((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.FirstName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
		AND ((ESO.PayrollGroupId = @rPayrollGroupId) OR (@rPayrollGroupId = 0))
		AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND EM.IsOtherUser = 0
		ORDER BY EM.OrgID,EM.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPayProcessEmployeeRemarkList]
	
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollYearId int
	 ,@rBankName nvarchar(100)='' --add for mantis : 0041906	
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)
END
BEGIN  
	SELECT  
		EM.EmployeeId,
		EM.EmployeeName,
		EM.Code AS EmployeeCode,
		OM.DisplayTitle AS OrgName,
		PER.Remark,
		PER.AutoId,
		ISNULL(PER.ChequeNo,'') ChequeNo,
		PER.PayDate,
		CASE WHEN ISNULL(PER.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
			ELSE ISNULL(PER.PayTypeId,0) END AS PayTypeId,
		ISNULL(ESO.BankName, '') AS BankName
	FROM 
		sHrm.vEmployeeCommonDetail EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID	
		INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON EM.EmployeeId = ESO.EmployeeId
		LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON
		PER.SalaryMonth=@rForMonth AND PER.SalaryYear=@rForYear	AND PER.PayrollYearId=@rPayrollYearId AND EM.EmployeeId = PER.EmployeeId
		INNER JOIN sPayroll.tPayrollMaster PM ON PM.Id = ESO.PayrollId
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PY.PayrollId = PM.Id
		--LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PER.PayTypeId
		--LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId
	WHERE 
		PY.Id = @rPayrollYearId AND ISNULL(EM.IsOtherUser,0) = 0
		AND ((UPPER(ESO.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))--add for mantis : 00419065  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPayProcessRemarkManage] 
 @rID int
,@rSalaryMonth tinyint
,@rSalaryYear smallint
,@rPayrollYearId int
,@rEmployeeId bigint=0
,@rRemark nvarchar(1000)=''
,@rPayTypeId tinyint = 0
,@rChequeNo nvarchar(40) = ''
,@rPayDate Date = Null
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

BEGIN TRY	
	
  IF EXISTS(Select 1 FROM sPayroll.tPayProcessEmployeeRemark Where AutoId=@rID)
	BEGIN
	  UPDATE [sPayroll].[tPayProcessEmployeeRemark] 
	  SET Remark=@rRemark
			,PayTypeId = @rPayTypeId
			,ChequeNo = @rChequeNo
			,PayDate = @rPayDate
	  where AutoId=@rID    
	  
	  select @rID
	END
  ELSE
	BEGIN
	   INSERT INTO [sPayroll].[tPayProcessEmployeeRemark]
           (
            [SalaryMonth]
           ,[SalaryYear]   
           ,[PayrollYearId]        
           ,[EmployeeId]
           ,[Remark]
		   ,[PayTypeId]
		   ,[ChequeNo]
		   ,[PayDate]
           )
     VALUES
           (
            @rSalaryMonth
           ,@rSalaryYear
           ,@rPayrollYearId
           ,@rEmployeeId           
           ,@rRemark
		   ,@rPayTypeId
		   ,@rChequeNo
		   ,@rPayDate
           )
       SELECT SCOPE_IDENTITY()
	END
END TRY	

BEGIN CATCH 
		SELECT -1 AS Result
END CATCH		
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPayProcessUpdate]
	
		   @rPayProcessId bigint,
		   @rIsApproved bit,
		   @rIsPublish bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
BEGIN TRANSACTION	
	BEGIN
		UPDATE sPayroll.tPayProcess SET
			IsApproved=@rIsApproved,
		    IsPublish=@rIsPublish
		WHERE Id=@rPayProcessId
	SELECT 1 AS RESULT
	END 
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollColumnNameGet]

AS
SET NOCOUNT ON

BEGIN
		Select COLUMN_NAME AS ColumnName from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sPayroll' AND TABLE_NAME='vPayrollColumnName'
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollCustomReportListGet]
	
	@rCreatedUserId bigint,
	@rOrgId smallint
	
AS
SET NOCOUNT ON

BEGIN
		SELECT 
				PCS.Id,
				PCS.Title,
				PCS.ColumnName,
				U.DisplayTitle AS CreatedUserName,
				CASE WHEN PCS.CreatedUserId = @rCreatedUserId THEN 'true' ELSE 'false' END AS IsDelete
		FROM 
				sPayroll.tPayrollCustomSearch PCS
			    LEFT JOIN sSecurity.tUser U ON U.Id=PCS.CreatedUserId
		WHERE 
			    ((PCS.CreatedUserId = @rCreatedUserId) OR (PCS.IsCommon = 1) OR (PCS.IsCommonForOrg = 1))  
			--AND PCS.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [sPayroll].[pPayrollCustomSearchGet]
-- drop proc [sPayroll].[pPayrollCustomSearchGet]
CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollCustomSearchGet] 
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'Code',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName[nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',
	@rEmployeeGroupId[nvarchar](50)='',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rDropDownStatusId int,
	@rPayrollId int,
	@rPageIndex int = null
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	
	SELECT PCS.*
	into sPayroll.tTempPayroll1
	FROM sPayroll.vPayrollCustomSearch PCS
	WHERE ((PCS.OrgId = @rOrgId) OR (@rOrgId = 0))
	AND PCS.PayrollId = @rPayrollId
	AND ((PCS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((PCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((PCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(PCS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
	AND ((PCS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
	AND ((PCS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
	AND ((PCS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
	AND ((PCS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
	AND (ISNULL(PCS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='')
	AND (ISNULL(PCS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (ISNULL(PCS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='')
	AND (ISNULL(PCS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='')
	AND (ISNULL(PCS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
	AND (ISNULL(PCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(PCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(PCS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='')
	AND (ISNULL(PCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND ((PCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ISNULL(PCS.IsOtherUser,0) = 0
	
	SET @rOrderBy=Replace(@rOrderBy,'Code','Code')
	SET @sql='SELECT EmployeeId,Code AS Code,Name,EmployeeType,
	OrganizationDepartment AS OrganizationDepartment,StatusName,
	OrgName,0 AS SalaryMonth
	FROM sPayroll.tTempPayroll1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	create table #TEMPPay
	(
		tid int identity(1,1),t_EmpId bigint
	)
	SET @sql='insert into #TEMPPay SELECT EmployeeId FROM sPayroll.tTempPayroll1 ORDER BY '+ @rOrderBy
	exec(@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lPageSize int = 10,@lTotalRecords int,@lPaging varchar(max)='',@lResult varchar(max)=''
	
	select @lTotalRecords = count(1) from #TEMPPay
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr><td>' + isnull(OrgName,'') + '</td><td>' + isnull(OrganizationDepartment,'') + '</td>
	<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td><td>' + isnull(EmployeeType,'') + '</td>
	<td>' + isnull(StatusName,'') + '</td></tr>'
	from sPayroll.tTempPayroll1,#TEMPPay where EmployeeId = t_EmpId
	and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lTotalRecords as TotalRecords,@lResult as EmpList,@lPaging as Paging
	
	DROP Table sPayroll.tTempPayroll1
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION SD			 
			Delete from sSecurity.tUserAccess where SourceId=@rId AND SourceTypeId = 2019
			Delete from sPayroll.tPayrollMaster where Id=@rId  
		 
		COMMIT TRANSACTION	SD
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION SD
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollForIncomeTaxGet]
	 @rEmployeeId BIGINT,
     @rPayrollYearId INT
AS
SET NOCOUNT ON

BEGIN
	
	  DECLARE @lPayrollId INT

	  SELECT @lPayrollId=ISNULL(ESO.PayrollId,0) FROM sHrm.tEmployeeMaster AS  EMP  
	  LEFT JOIN [sHrm].[tEmployeeStatutoryAndOther]  AS ESO ON ESO.EmployeeId=EMP.id  
	  LEFT JOIN sPayroll.tPayrollMaster PM ON PM.id = ESO.PayrollId  
	  WHERE EMP.id=@rEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0  

	  --SELECT ISNULL(ESO.PayrollId,0)PayrollId,ISNULL(PM.Title,'')PayrollName FROM sHrm.tEmployeeMaster AS  EMP  
	  --LEFT JOIN [sHrm].[tEmployeeStatutoryAndOther]  AS ESO ON ESO.EmployeeId=EMP.id  
	  --LEFT JOIN sPayroll.tPayrollMaster PM ON PM.id = ESO.PayrollId  
	  --WHERE EMP.id=@rEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 


	  DECLARE @TableIncome TABLE (PayElementDefaultId INT, NetAmount DECIMAL(18,2), Amount DECIMAL(18,2))  
      
	  INSERT INTO @TableIncome  
      SELECT PE.PayElementDefaultId,SUM(PPE.TotalEarning) AS NetAmount,SUM(ISNULL(PEM.Amount,0))Amount  
      FROM sPayroll.tPayProcessEmployee           AS PPE   
      INNER JOIN sPayroll.tPayProcess             AS PP   ON PP.ID=PPE.PayProcessId  
      INNER JOIN sPayroll.tPayrollGroupMaster     AS PGM  ON PGM.ID=PPE.PayrollGroupId  
      INNER JOIN sPayroll.tPayrollMaster          AS PYM  ON PYM.Id=PGM.PayrollId  
      INNER JOIN sPayroll.tPayrollYearMaster      AS PY   ON PY.Id=PP.PayrollYearId  
      INNER JOIN sPayroll.tPayProcessElement      AS PEM  ON PEM.PayProcessEmployeeId=PPE.ID  
      INNER JOIN sPayroll.tPayElement             AS PE   ON PE.ID=PEM.PayElementId AND PE.PayrollId=PYM.ID  
      INNER JOIN sPayroll.tPayElementDefault      AS PPDE ON PPDE.id=PE.PayElementDefaultId  
      WHERE PE.PayElementDefaultId in   
      (  
       SELECT DefaultPayElementId   
       FROM [siTax].[tStaticIncomeTaxSubGroup]   
       WHERE ISNULL(DefaultPayElementId,0) <> 0   
       UNION ALL  
       SELECT  56 as DefaultPayElementId UNION ALL  
       SELECT  61 as DefaultPayElementId  
      )  
	  AND PYM.ID=@lPayrollId AND PY.Id=@rPayrollYearId AND PPE.EmployeeId=@rEmployeeId  
      GROUP BY PPE.EmployeeId,PE.PayElementDefaultId,PEM.PayElementId,PE.TITLE  
	  
	  SELECT TOP 1 * FROM @TableIncome ORDER BY PayElementDefaultId DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollGenerateReport]
	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'Code',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',	 
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rPayrollId int,
	@rSalaryYear int,
	@rSalaryMonth int=0,
	@rIsCommonForOrg bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOJFromDate IS NULL)
		SET @rDOJFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9999-12-31'
	IF(@rDOJToDate IS NULL)
		SET @rDOJToDate='9999-12-31'
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sPayroll.tPayrollCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sPayroll.tPayrollCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrgId,
			Code,
			FirstName,	
			LastName,
			EmployeeTypeId,
			StatusId,
			OrganizationDepartmentId,
			ReligionId,
			MaritalStatusId,
			Qualification,
			GenderId,
			EmployeeDesignationId,
			BloodGroupId,	 
			DOBFromDate,
			DOBToDate,
			DOJFromDate,
			DOJToDate,
			IsCommon,
			CreatedUserId,
			CreatedDateTime,
			IsCommonForOrg
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrgId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rEmployeeTypeId,
			@rStatusId,
			@rOrganizationDepartmentId,
			@rReligionId,
			@rMaritalStatusId,
			@rQualification,
			@rGenderId,
			@rEmployeeDesignationId,
			@rBloodGroupId,	 
			@rDOBFromDate,
			@rDOBToDate,
			@rDOJFromDate,
			@rDOJToDate,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsCommonForOrg
		) 
	END
	
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rEmployeeTypeId=EmployeeTypeId,
				@rStatusId=StatusId,
				@rOrganizationDepartmentId=OrganizationDepartmentId,
				@rReligionId=ReligionId,
				@rMaritalStatusId=MaritalStatusId,
				@rQualification=Qualification,
				@rGenderId=GenderId,
				@rEmployeeDesignationId=EmployeeDesignationId,
				@rBloodGroupId=BloodGroupId,	 
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOJFromDate=DOJFromDate,
				@rDOJToDate=DOJToDate
		FROM
			sPayroll.tPayrollCustomSearch
		WHERE
			Id=@rId
	END
	
	DECLARE @Sql nvarchar(MAX)
	SET @rColumnName=Replace(@rColumnName,'Code','Code')
	SET @rOrderBy=Replace(@rOrderBy,'Code','Code')
	SET  @rColumnName = Replace(@rColumnName,'Caste','Cast')
 
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)

	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
	select @cols = STUFF((SELECT ',' + QUOTENAME(PED.Title,'[]'), '' AS EmployeeId, '' AS SalaryMonth
                    from sPayroll.tPayProcess PP 
                    INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.Id
                    INNER JOIN sPayroll.tPayProcessElement PPEl ON PPEl.PayProcessEmployeeId = PPE.ID
                    INNER JOIN sPayroll.tPayElement PE ON PE.ID = PPEl.PayElementId
					LEFT JOIN [sPayroll].[tPayElementDefault] PED ON PED.Id = PE.PayElementDefaultId
                    WHERE PE.PayrollId = @rPayrollId AND PP.SalaryYear = @rSalaryYear
                    group by PED.Title
                    order by PED.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

    IF(@cols IS NOT NULL)
    BEGIN    
		
		--mantis: 43241, add below if condition only
		IF OBJECT_ID('sPayroll.tTempPayrol3','U') is not null
		BEGIN
			DROP TABLE sPayroll.tTempPayrol3
		END

		set @query = 'SELECT SalaryMonth AS SalaryMonth, EmployeeId AS EmployeeId1 ,' + @cols + ',NetAmount into sPayroll.tTempPayrol3 from 
             (
                select PP.SalaryMonth, PPE.EmployeeId, PPEl.Amount,PPE.NetAmount,
                PE.Title
                FROM
                sPayroll.tPayProcess PP 
                    INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.Id
                INNER JOIN sPayroll.tPayProcessElement PPEl ON PPEl.PayProcessEmployeeId = PPE.ID
                INNER JOIN sPayroll.tPayElement PE ON PE.ID = PPEl.PayElementId
                 WHERE PE.PayrollId = '+CONVERT(nvarchar,@rPayrollId)+'
                    AND PP.SalaryYear = '+CONVERT(nvarchar,@rSalaryYear)+'
            ) x 
            pivot 
            (
                SUM(Amount)
                for  Title in (' +@cols  + ')
            ) p '
         
         print   @query 
	    execute(@query)
		
		SELECT 
			* into sPayroll.tTempPayroll
		FROM 
			sPayroll.vPayrollCustomSearch PCS 
			INNER JOIN sPayroll.tTempPayrol3 t3 ON PCS.EmployeeId = t3.EmployeeId1
		WHERE 
			((PCS.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND PCS.PayrollId = @rPayrollId 
			AND ((PCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((PCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((PCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(PCS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
			AND ((ISNULL(PCS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ISNULL(PCS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
			AND ((ISNULL(PCS.DateOfJoining,'') >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
			AND ((ISNULL(PCS.DateOfJoining,'') <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
			AND (ISNULL(PCS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			
			AND (ISNULL(PCS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		    AND (ISNULL(PCS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 
			
		    AND (ISNULL(PCS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
			
		    AND (ISNULL(PCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		    AND (ISNULL(PCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		    AND (ISNULL(PCS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		    AND (ISNULL(PCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
	
			AND ((PCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ISNULL(PCS.IsOtherUser,0) = 0
			
		SET @sql='SELECT '+ @rColumnName  +' FROM sPayroll.tTempPayroll ORDER BY '+@rOrderBy
		exec(@Sql)
		
		
		DROP Table sPayroll.tTempPayrol3
	END
	ELSE
	BEGIN
	
		--mantis: 43241, add below if condition only
		IF OBJECT_ID('sPayroll.tTempPayroll','U') is not null
		BEGIN
			DROP TABLE sPayroll.tTempPayroll
		END

		SELECT 
			0 AS NetAmount ,* into sPayroll.tTempPayroll
		FROM 
			sPayroll.vPayrollCustomSearch PCS 
		WHERE 
			((PCS.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND PCS.PayrollId = @rPayrollId 
			AND ((PCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((PCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((PCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(PCS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
			AND ((ISNULL(PCS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ISNULL(PCS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
			AND ((ISNULL(PCS.DateOfJoining,'') >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
			AND ((ISNULL(PCS.DateOfJoining,'') <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
			AND (ISNULL(PCS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			
			AND (ISNULL(PCS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		    AND (ISNULL(PCS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 
			
		    AND (ISNULL(PCS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
			
		    AND (ISNULL(PCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		    AND (ISNULL(PCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		    AND (ISNULL(PCS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		    AND (ISNULL(PCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
	
			AND ((PCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ISNULL(PCS.IsOtherUser,0) = 0
			
		SET @sql='SELECT '+ @rColumnName  +' FROM sPayroll.tTempPayroll ORDER BY '+@rOrderBy
		exec(@Sql)
	END	
	DROP Table sPayroll.tTempPayroll	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollGetForIncomeTax]
	 @rEmployeeId BIGINT,
     @rPayrollYearId INT
AS
SET NOCOUNT ON

BEGIN
	  SELECT PPE.PayElementId,
			 PE.Code AS PayElement,
			 PPE.Amount,
			 PET.Title AS PayElementType,
			 PayElementTypeId,
			 PPE.PayProcessEmployeeId,
			 ISNULL(PE.IsIncludeInTotal,0) AS IsIncludeInTotal
		 FROM 
			 sPayroll.tPayProcessElement PPE 
			 INNER JOIN sPayroll.tPayElement PE ON PPE.PayElementId = PE.ID
			 INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
		 WHERE 
		 PayProcessEmployeeId in 
		 (select PPE.Id from sPayroll.tPayProcessEmployee PPE
			INNER JOIN sPayroll.tPayProcess AS PP ON PP.ID=PPE.PayProcessId   
			where EmployeeId = @rEmployeeId AND PP.PayrollYearId = @rPayrollYearId)--(select TOP 1 PayRollId from sPayroll.tPayrollYearMaster Where Id = @rPayrollYearId))
		 AND PE.IsIncludeInPaySlip = 1
		 ORDER BY SortOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollGroupMasterAdd]
	 
	        @rId int,
			@rCode nvarchar(100),
			@rTitle nvarchar(100),
			@rCreatedUserId bigint,       
			@rIsObsolete bit,
			@rPayrollId int,
			@rOrgGroupId smallint    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
    
	DECLARE @lNextNumber INT     

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPayroll.tPayrollGroupMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sPayroll].[tPayrollGroupMaster]
           (
			[Id],
           [Code],
           [Title],
           [CreatedUserId],
           [CreatedDateTime],
            [IsObsolete],
           [PayrollId],
           [OrgGroupId]
           )
     VALUES
           (
           @lNextNumber,
           @rCode ,
           @rTitle ,
           @rCreatedUserId, 
           sCommon.fGetDate(),
           @rIsObsolete,
           ISNULL(@rPayrollId,''),
           @rOrgGroupId 
           ) 
           SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sPayroll].[tPayrollGroupMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime =sCommon.fGetDate(),
			IsObsolete = @rIsObsolete,
			PayrollId = @rPayrollId,	
			OrgGroupId = @rOrgGroupId
	      
	      WHERE Id = @rId 	 
	       SELECT 11 AS Result  
	 END  
		 
	
		  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollGroupMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100),
	 @rOrgGroupId smallint,
	 @rPayrollId int
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		BEGIN 
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
		END	 
	SELECT 
		PGM.Id,
		PGM.Code,
		PGM.Title,
		PGM.IsObsolete
  FROM 
		sPayroll.tPayrollGroupMaster PGM
		INNER JOIN sPayroll.tPayrollMaster PM
		ON PGM.PayrollId=PM.Id
  WHERE 
		PGM.PayrollId = @rPayrollId 
        AND ((PGM.Id = @rId) OR (@rId = 0))
        AND  ((PGM.Title LIKE @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((PGM.Code LIKE @rCode) OR (ISNULL(@rCode,'') = ''))
		AND PGM.OrgGroupId = @rOrgGroupId
		ORDER BY PGM.CreatedDateTime DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollMasterAdd]
	 
	        @rId int,
			@rCode nvarchar(100),
			@rTitle nvarchar(100),
			@rCreatedUserId bigint,       
			@rOrgGroupId smallint,
			@rIsActive bit,
			@rIsFormulawise bit =0,
			@rHeaderDisplayId tinyint=0
			--@rPayrollHeader varbinary(max)=NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sPayroll.tPayrollMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sPayroll.tPayrollMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sPayroll.tPayrollMaster where Code=@rCode AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If  Exists(select Id from sPayroll.tPayrollMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
	END
	 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
    
	DECLARE @lNextNumber INT     

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPayroll.tPayrollMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sPayroll].[tPayrollMaster]
           (
			[Id],
           [Code],
           [Title],
           [CreatedUserId],
           [CreatedDateTime],
           --[UpdatedUserId],
           --[UpdatedDateTime],
           [OrgGroupId],
           [IsActive],
           IsFormulawise,
		   HeaderDisplayId
           )
     VALUES
           (
            @lNextNumber,
           @rCode ,
           @rTitle ,
           @rCreatedUserId, 
           sCommon.fGetDate(),
           --@rCreatedUserId,
           --sCommon.fGetDate(), 
           @rOrgGroupId, 
           @rIsActive,
           @rIsFormulawise,
		   @rHeaderDisplayId
		  -- @rPayrollHeader
           ) 
           
           	INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           
           )
		   SELECT 
		   2019
		   ,@lNextNumber
		   ,@rCreatedUserId	
           
           SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sPayroll].[tPayrollMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime =sCommon.fGetDate(),	
			IsActive = @rIsActive,
			IsFormulawise = @rIsFormulawise,
			HeaderDisplayId = @rHeaderDisplayId
			--PayrollHeader = @rPayrollHeader
	      
	      WHERE Id = @rId 	 
	       SELECT @lNextNumber AS Result  
	 END  
		 
	
		  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100),
	 @rOrgGroupId smallint
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  BEGIN 
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END	 
	SELECT 
		PM.Id,
		PM.Code,
		PM.Title,
		PM.IsActive,
		ISNULL(PM.IsFormulawise,0 ) As IsFormulawise,
		PM.PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1) AS HeaderDisplayId   
  FROM 
      sPayroll.tPayrollMaster PM
  WHERE  
        ((PM.Id = @rId) OR (@rId = 0))
        AND  ((PM.Title LIKE @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((PM.Code LIKE @rCode) OR (ISNULL(@rCode,'') = ''))
		AND PM.OrgGroupId = @rOrgGroupId
		order by PM.CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollPaySetupImport]
	
	@rPayrollId int,
	@rFromPayrollYearId int,
	@rToPayrollYearId int,
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

	IF EXISTS (SELECT 1 FROM sPayroll.tPaySetup WHERE PayrollId = @rPayrollId AND PayrollYearId = @rToPayrollYearId)
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	
	BEGIN TRANSACTION
	DECLARE @lCount int
	DECLARE @lNextNumber int
	
	-- Pay Setup Temp Table
	CREATE TABLE #TempPaySetup(
	[AutoId] int identity,
	[ID] [int] NOT NULL,
	[SourceTypeId] [smallint] NOT NULL,
	[SourceId] [bigint] NOT NULL,
	[PayElementId] [int] NOT NULL,
	[Amount] [decimal](22, 2) NULL,
	[Percentage] [decimal](5, 2) NULL,
	[ProcessOrder] [tinyint] NOT NULL,
	[PayrollId] [int] NULL,
	[OrderIndex] [int] NULL,
	[PayrollYearId] [int] NULL,
	[DefaultAmount] [decimal](22,2) NULL,
	[Formula] [nvarchar](200) NULL
	)
	-- End Create Table
	
	INSERT INTO #TempPaySetup SELECT * FROM sPayroll.tPaySetup WHERE PayrollId = @rPayrollId AND PayrollYearId = @rFromPayrollYearId
	
	Select @lCount = COUNT(Id) From #TempPaySetup
	
	WHILE (@lCount > 0)
	BEGIN
		-- Pay Setup Entry
		
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPaySetup', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sPayroll.tPaySetup
		SELECT @lNextNumber,SourceTypeId,SourceId,PayElementId,Amount,Percentage,ProcessOrder,@rPayrollId,OrderIndex,@rToPayrollYearId,DefaultAmount,Formula
		FROM #TempPaySetup Where AutoId = @lCount
		
		-- END Pay Setup Entry
		SET @lCount = @lCount -1
	END

	DROP TABLE #TempPaySetup 
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
DROP TABLE #TempPaySetup 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollProcessEmployeeDetailGet]
	
	 @rEmployeeCode nvarchar(200),
	 @rPayrollId int,
	 @rPayrollYearId int,
	 @rOrgId int,
	 @rForMonth int,
	 @rForYear int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @colsEarning AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX)
DECLARE @colsDeduction AS NVARCHAR(MAX)

SELECT @colsEarning = STUFF((SELECT DISTINCT ',' + QUOTENAME(P.Code) FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	WHERE 
		(P.IsObsolete=0) AND P.PayElementTypeId = 1
		AND ((EM.Code = @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0)  
		AND (tEM.OrgId = @rOrgId)
	FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

	SELECT @colsDeduction = STUFF((SELECT DISTINCT ',' + QUOTENAME(P.Code) FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	WHERE 
		(P.IsObsolete=0) AND P.PayElementTypeId = 2
		AND ((EM.Code = @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0)  
		AND (tEM.OrgId = @rOrgId)
	FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

 
	SET @query = '
		SELECT ' + @colsEarning + ',TotalEarning,' + @colsDeduction + ',TotalDeduction,NetAmount FRom (
		SELECT 
			
			tEM.FirstName +'' ''+tEM.MiddleName+'' ''+tEm.LastName AS EmployeeName,
			PPE.TotalEarning,		
			PPE.TotalDeduction,
			ISNULL(PPE.NetAmount,0) AS NetAmount,
			ISNULL(PE.Amount,0) As PPEAmount,
			P.Code AS PayElementCode,
			PPE.Id as PayProcessEmpId
		FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		WHERE 
			(P.IsObsolete=0)
			AND ((EM.Code = '''+@rEmployeeCode+''' ) OR ('''+@rEmployeeCode+''' = ''''))
			AND ((PY.PayrollId='+ CONVERT(NVARCHAR(10),@rPayrollId) +') OR ('+ CONVERT(NVARCHAR(10),@rPayrollId) +'=0))
			AND (PP.PayrollYearId = '+ CONVERT(NVARCHAR(10),@rPayrollYearId) +' OR '+ CONVERT(NVARCHAR(10),@rPayrollYearId) +' = 0) 
			AND (tEM.OrgId = '+ CONVERT(NVARCHAR(10),@rOrgId) +')
			AND PP.SalaryMonth = '+ CONVERT(NVARCHAR(10),@rForMonth) +'
			AND PP.SalaryYear = '+ CONVERT(NVARCHAR(10),@rForYear) +'
		) X
		pivot 
		(   Sum(PPEAmount)
			for PayElementCode in (' + @colsEarning + ',' + @colsDeduction + ')
		) p '
	IF(@query IS NOT NULL)	
		EXECUTE(@query)

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollYearMasterAdd]
	 
	        @rId int,
			@rCode nvarchar(100),
			@rTitle nvarchar(100),
			@rFromDate date,
			@rToDate date,
			@rCreatedUserId bigint,
			@rPayrollId int,     
			@rOrgGroupId smallint,
			@rIsActive bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sPayroll.tPayrollYearMaster where Code=@rCode AND PayrollId=@rPayrollId AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sPayroll.tPayrollYearMaster where Title=@rTitle AND PayrollId=@rPayrollId AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sPayroll.tPayrollYearMaster where Code=@rCode AND PayrollId=@rPayrollId AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -101 as Result
			RETURN
		End 
		If  Exists(select Id from sPayroll.tPayrollYearMaster where Title=@rTitle AND PayrollId=@rPayrollId AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
	END
	 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
    
	DECLARE @lNextNumber INT     

EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPayroll.tPayrollYearMaster',@lNextNumber = @lNextNumber output
 
INSERT INTO [sPayroll].[tPayrollYearMaster]
           (
			[Id],
           [Code],
           [Title],
           [FromDate],
           [ToDate],
           [CreatedUserId],
           [CreatedDateTime],
           [PayrollId],
           --[UpdatedUserId],
           --[UpdatedDateTime],
           [IsActive],
           [OrgGroupId]
         
           )
     VALUES
           (
            @lNextNumber,
           @rCode ,
           @rTitle ,
           @rFromDate,
           @rToDate,
           @rCreatedUserId, 
           sCommon.fGetDate(),
           @rPayrollId,
           --@rCreatedUserId,
           --sCommon.fGetDate(), 
           @rIsActive,
           @rOrgGroupId 
           
           ) 
           SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sPayroll].[tPayrollYearMaster]
	    SET
			code = @rCode,
			Title = @rTitle,
			FromDate =@rFromDate,
			ToDate = @rToDate,
			UpdatedUserId= @rCreatedUserId,
			UpdatedDateTime =sCommon.fGetDate(),
			PayrollId = @rPayrollId,	
			IsActive = @rIsActive,
			OrgGroupId = @rOrgGroupId
	      
	      WHERE Id = @rId 	 
	       SELECT 11 AS Result  
	 END  
		 
	
		  COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPayrollYearMasterGet]
	 
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100),
	 @rOrgGroupId smallint,
	 @rPayrollId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  BEGIN 
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rCode = sCommon.fSearchStringGet(@rCode)
	  END	
	   
	SELECT 
		PYM.Id,
		PM.Title AS PayrollName,
		PYM.Code,
		PYM.Title,
		PYM.IsActive,
		PYM.PayrollId,
		PM.Title,
		PYM.FromDate,
		PYM.ToDate,
		CASE PYM.IsActive When 0 then 'Y' ELSE 'N' END AS Active
  FROM 
      sPayroll.tPayrollYearMaster PYM
      INNER JOIN sPayroll.tPayrollMaster PM ON PM.Id = PYM.PayrollId
  WHERE  
        ((PYM.Id = @rId) OR (@rId = 0))
        AND ((PYM.PayrollId = @rPayrollId) OR (@rPayrollId = 0))
        AND ((PYM.Title LIKE @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND ((PYM.Code LIKE @rCode) OR (ISNULL(@rCode,'') = ''))
		AND PYM.OrgGroupId = @rOrgGroupId
		Order By PYM.CreatedDateTime Desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPaySetupAdd] 
	      
	        @rID int
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rPayElementId int
           ,@rAmount decimal(22,6)
           ,@rPercentage decimal(5,2)
           ,@rProcessOrder tinyint
           ,@rOrgGroupId int
           ,@rIsObsolete bit
           ,@rPayrollId int
           ,@rOrderIndex int=0
           ,@rPayrollYearId int=0
           ,@rDefaultAmount decimal(22,2)=0
		   ,@rFormula nvarchar(200)=''
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Mantis Start - 43837
	IF EXISTS(select 1 from [sPayroll].[tPaySetup] where SourceTypeId=@rSourceTypeId and SourceId=@rSourceId and ProcessOrder=@rProcessOrder and PayrollId=@rPayrollId and PayrollYearId=@rPayrollYearId and Id <> @rID)
	BEGIN
		SELECT -101 AS Result
		return
	END
	--Mantis End - 43837
	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
	
  IF(@rIsObsolete = 0 AND @rId > 0)
  BEGIN
    SET @lNextNumber = 1
    DELETE FROM sPayroll.tPaySetup Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND PayElementId = @rPayElementId AND PayrollId = @rPayrollId
      
  END
 
  ELSE	
  
  BEGIN
  IF (@rId = 0 AND @rIsObsolete = 1)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPaySetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPaySetup]
           ([ID]
           ,[SourceTypeId]
           ,[SourceId]
           ,[PayElementId]
           ,[Amount]
           ,[Percentage]
           ,[ProcessOrder]
           ,[PayrollId]
           ,[OrderIndex]
           ,[PayrollYearId]
           ,[DefaultAmount]
		   ,[Formula]
           )
     VALUES
           (
			@lNextNumber 
		   ,@rSourceTypeId 
		   ,@rSourceId 
		   ,@rPayElementId 
		   ,@rAmount 
		   ,@rPercentage 
		   ,@rProcessOrder 
		   ,@rPayrollId
		   ,@rOrderIndex
		   ,@rPayrollYearId
		   ,@rDefaultAmount
		   ,@rFormula
           )
    	END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		     UPDATE  [sPayroll].[tPaySetup]
			   SET       
				  [PayElementId] = @rPayElementId
				  ,[Amount] = @rAmount
				  ,[Percentage] = @rPercentage
				  ,[ProcessOrder] = @rProcessOrder
				  ,[PayrollId] = @rPayrollId
				  ,[OrderIndex] = @rOrderIndex
				  ,[PayrollYearId] = @rPayrollYearId
				  ,DefaultAmount=@rDefaultAmount
				  ,[Formula]=@rFormula
			WHERE Id = @rId		
		END 
		
 
		IF EXISTS(SELECT 1 FROM sPayroll.tPayElement WHERE ID=@rPayElementId  AND PayrollId =@rPayrollId AND IsEmployeeSpecific = 1   )
	 	BEGIN
			UPDATE sPayroll.tPaySetup
			   SET       
				  ProcessOrder = @rProcessOrder
			WHERE 	SourceTypeId = 95 AND PayElementId=@rPayElementId AND PayrollId =@rPayrollId AND PayrollYearId=@rPayrollYearId 
		END
		
	END       
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Set Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPaySetupDependantAdd] 
	      
	        @rDependPayElementId int,
	        @rPaySetupId int,
	        @rIsDeduct bit=0
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT 
    
    BEGIN	

IF NOT EXISTS(SELECT 1 FROM sPayroll.tPaySetupDependent Where DependentPayElementId = @rDependPayElementId AND PaySetupId = @rPaySetupId)	 
  BEGIN	
	INSERT INTO sPayroll.tPaySetupDependent
           (
            DependentPayElementId,
            PaySetupId,
            IsDeduct
           )
     VALUES
           (
			@rDependPayElementId,
	        @rPaySetupId,
	        @rIsDeduct
           )
    	END
    END
  --  ELSE
		--BEGIN    
		--     SET @lNextNumber = @rId
		--     UPDATE  [sPayroll].[tPaySetup]
		--	   SET       
		--		  [PayElementId] = @rPayElementId
		--		  ,[Amount] = @rAmount
		--		  ,[Percentage] = @rPercentage
		--		  ,[ProcessOrder] = @rProcessOrder
		--		  ,[OrgId] = @rOrgId
 
		--	WHERE Id = @rId		     		     		    
		--END        
	SELECT 1 AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Depend Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sPayroll].[pPaySetupDependentGet]
	 
	 @rPaySetupId int,
	 @rPayrollId int
	  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
    
    Select           
         DependentPayElementId AS DependPayElementId,
         PE.Title AS DependPayElement,
         CASE WHEN ISNULL(PSD.IsDeduct,0) = 0 THEN 'Add(+)'  WHEN ISNULL(PSD.IsDeduct,0) = 1 THEN  'Deduct(-)' END AS PayElementStatus
        
    From sPayroll.tPaySetupDependent  PSD
    INNER JOIN sPayroll.tPayElement PE ON PE.ID = PSD.DependentPayElementId	 
    
    WHERE PaysetupId = @rPaySetupId 
	AND PE.PayrollId = @rPayrollId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPaySetupDependentRemove]
	 
	 @rPaySetupId int,
	 @rPayElementId int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	 
    DELETE         
    From sPayroll.tPaySetupDependent   
    WHERE PaysetupId = @rPaySetupId   AND DependentPayElementId = @rPayElementId
    SELECT 1 AS Result
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pPaySetupElementWiseEmployeeGet]
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rPayrollId int,
	 @rPayElementId int,
	 @rPayrollYearId int=0,
	 @rPayrollGroupId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
		ISNULL(PS.Id,0) AS PaySetupId,
		EM.EmployeeId,
		EM.EmployeeName,
		EM.Code,
		EM.DepartmentName,
		PS.Amount,
		ISNULL(PE.SortOrder,0) AS ProcessOrder,
		ISNULL(PS.PayElementId,0) AS PayElementId,
		ISNULL(PS.DefaultAmount,0) AS DefaultAmount ,
		ISNULL(PS.Formula,'') AS Formula
	FROM sHrm.vEmployeeCommonDetail EM
		INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON EM.EmployeeId = ESO.EmployeeId	 
		LEFT JOIN sPayroll.tPaySetup PS ON PS.SourceId = EM.EmployeeId  
		AND SourceTypeId = @rSourceTypeId 
		AND PS.PayElementId = @rPayElementId
		AND PS.PayRollId = ESO.PayrollId
		AND PS.PayRollYearId = @rPayrollYearId
		LEFT JOIN sPayroll.tPayElement PE ON  PE.ID=@rPayElementId			
	WHERE  ESO.PayrollId = @rPayrollId 
		AND (ESO.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId=0)
		AND EM.EmployeeStatusId=7
		AND ISNULL(EM.IsOtherUser,0)=0 
	ORDER BY EM.OrgId,EM.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sPayroll].[pPaySetupEmployeeGet]
	  
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rPayrollId int,
	 @rEmployeeCode nvarchar(100),
	 @rEmployeeName nvarchar(100),
	 @rPayElementId int,
	 @rId int,
	 @rPayrollYearId int=0
	 
 WITH EXECUTE AS CALLER
AS
 SET NOCOUNT ON
 
BEGIN 		
	   SELECT 
		   ISNULL(PS.[ID],0) AS PaySetupId	  		  
		  ,PE.Id AS PayElementId
		  ,PS.SourceId
		  ,[Amount]
		  ,[Percentage]
		  ,ISNULL([ProcessOrder],0) AS ProcessOrder
		  ,ISNULL(PS.[PayrollId],0) AS PayrollId
	      ,PE.Title  AS PayElement
	      ,PE.IsDepend
	      ,EM.Code
	      ,EM.EmployeeName
	      ,OM.Id AS OrgId
	      ,OM.DisplayTitle AS OrgName
	     ,ISNULL(PS.DefaultAmount,0) AS DefaultAmount
	     ,ISNULL(PS.Formula,'') As Formula
	      
	FROM  sPayroll.tPayElement PE INNER JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId  
		   INNER JOIN sHrm.vEmployeeCommonDetail Em ON Em.EmployeeId = PS.SourceId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
		   
		  
   WHERE 
         (Ps.ID = @rId OR ISNULL(@rId,0) = 0)
         AND PE.IsObsolete = 0  AND PE.PayrollId = @rPayrollId AND PS.PayRollYearId = @rPayrollYearId
         AND  PS.SourceTypeId = @rSourceTypeId
         AND (PS.SourceId = @rSourceId OR @rSourceId = 0)
         AND (EM.Code LIKE @rEmployeeCode + '%' OR ISNULL(@rEmployeeCode,'') = '')
         AND (EmployeeName LIKE @rEmployeeName + '%' OR ISNULL(@rEmployeeName,'') = '')
         AND (SourceId = @rSourceId OR ISNULL(@rSourceId,0) = 0)
         AND (PE.Id = @rPayElementId OR ISNULL(@rPayElementId,0) = 0)
		 AND (EM.IsOtherUser = 0)
         Order By EM.OrgId,EM.Number
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPaySetupEmployeeRemove]
	 
	 @rPaySetupId int
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    DELETE         
    From sPayroll.tPaySetupDependent   
    WHERE PaysetupId = @rPaySetupId   
    
    DELETE FROM sPayroll.tPaySetup
    Where Id = @rPaySetupId
    
    SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sPayroll].[pPaySetupGet]
	  
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rPayrollId int,
	 @rPayrollYearId int=0
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       		
		SELECT 
			   ISNULL(PS.[ID],0) AS PaySetupId	  		  
			  ,PE.Id AS PayElementId
			  ,[Amount]
			  ,[Percentage]
			  ,ISNULL([ProcessOrder],0) AS ProcessOrder
			  ,ISNULL(PS.[PayrollId],0) AS PayrollId
			  ,PE.Title  AS PayElement
			  ,[sPayroll].[fGetPaySetupDependentElement](ISNULL(PS.Id,0)) AS PaysetupDependentElement
			  ,ISNULL(PE.IsDepend,0) AS IsDepend
			  ,PE.PayElementDefaultId
			  ,ISNULL(PE.SortOrder,0) AS DisplayOrder
			  ,ISNULL(PS.[PayrollYearId],0) AS PayrollYearId
			  ,ISNULL(PS.DefaultAmount,0) AS DefaultAmount
			  ,ISNULL(PS.Formula,'') AS Formula
		      
		FROM  sPayroll.tPayElement PE LEFT JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId AND
			  PS.SourceTypeId = @rSourceTypeId AND PS.SourceId = @rSourceId AND PS.PayrollYearId = @rPayrollYearId 
			  
	   WHERE PE.IsObsolete = 0  AND PE.PayrollId = @rPayrollId 
	    
	   Order by ProcessOrder,PE.SortOrder
       
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPaySetupRemove]
	 
	 @rSourceTypeId smallint,
	 @rSourceId bigint
 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       DELETE PSD FROM sPayroll.tPaySetup PS INNER JOIN  sPayroll.tPaySetupDependent PSD ON PSD.PaySetupId = PS.ID
	   WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId		
	   DELETE FROM sPayroll.tPaySetup WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId   
    
       SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPfSetupAdd] 
	      
		    @rId int
           ,@rPayrollYearId int
           ,@rPfSalaryLimit decimal(22,6)
           ,@rFpsSalaryLimit decimal(22,6)
           ,@rEmployeePfPercent decimal(5,2)
           ,@rEmployerPfPercent decimal(5,2)
           ,@rEmployerFpsPercent decimal(5,2)
           ,@rAdminChargesPercent decimal(5,2)
           ,@rEdliPercent decimal(5,3)
           ,@rInspectionChargesPercent decimal(5,3)
           ,@rMaximumAgeForFps smallint
           ,@rRoundingTypeId tinyint
           ,@rRoundingPrecision int
           ,@rMaximumVpfPercent decimal(5,2)
           ,@rMaximumVpfAmount decimal(22,6)
           ,@rCreatedUserId bigint 
           ,@rOrgGroupId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
  
   IF Not Exists (Select 1 From [sPayroll].[tPfSetup] Where PayrollYearId = @rPayrollYearId)
    
    BEGIN	
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sPayroll.tPfSetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO  [sPayroll].[tPfSetup]
           (
            [Id]
           ,[PayrollYearId]
           ,[PfSalaryLimit]
           ,[FpsSalaryLimit]
           ,[EmployeePfPercent]
           ,[EmployerPfPercent]
           ,[EmployerFpsPercent]
           ,[AdminChargesPercent]
           ,[EdliPercent]
           ,[InspectionChargesPercent]
           ,[MaximumAgeForFps]
           ,[RoundingTypeId]
           ,[RoundingPrecision]
           ,[MaximumVpfPercent]
           ,[MaximumVpfAmount]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           )
     VALUES
           (
            @rId 
           ,@rPayrollYearId 
           ,@rPfSalaryLimit 
           ,@rFpsSalaryLimit 
           ,@rEmployeePfPercent 
           ,@rEmployerPfPercent 
           ,@rEmployerFpsPercent 
           ,@rAdminChargesPercent 
           ,@rEdliPercent 
           ,@rInspectionChargesPercent 
           ,@rMaximumAgeForFps 
           ,@rRoundingTypeId 
           ,@rRoundingPrecision 
           ,@rMaximumVpfPercent 
           ,@rMaximumVpfAmount 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           )
         END
    ELSE
		BEGIN    
		     --SET @lNextNumber = @rId
		     UPDATE  [sPayroll].[tPfSetup]
			   SET  
				   [PfSalaryLimit] = @rPfSalaryLimit
				  ,[FpsSalaryLimit] = @rFpsSalaryLimit
				  ,[EmployeePfPercent] = @rEmployeePfPercent 
				  ,[EmployerPfPercent] = @rEmployerPfPercent 
				  ,[EmployerFpsPercent] = @rEmployerFpsPercent 
				  ,[AdminChargesPercent] = @rAdminChargesPercent 
				  ,[EdliPercent] = @rEdliPercent 
				  ,[InspectionChargesPercent] = @rInspectionChargesPercent 
				  ,[MaximumAgeForFps] = @rMaximumAgeForFps 
				  ,[RoundingTypeId] = @rRoundingTypeId 
				  ,[RoundingPrecision] = @rRoundingPrecision 
				  ,[MaximumVpfPercent] = @rMaximumVpfPercent 
				  ,[MaximumVpfAmount] = @rMaximumVpfAmount 
      
			  Where PayrollYearId = @rPayrollYearId	     		    
		END        
	SELECT @rId AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error Creating Pf Setup Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pPfSetupGet]
	 @rId int,
	 @rPayrollYearId int 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	SELECT [Id]
		  ,[PayrollYearId]
		  ,[PfSalaryLimit]
		  ,[FpsSalaryLimit]
		  ,[EmployeePfPercent]
		  ,[EmployerPfPercent]
		  ,[EmployerFpsPercent]
		  ,[AdminChargesPercent]
		  ,[EdliPercent]
		  ,[InspectionChargesPercent]
		  ,[MaximumAgeForFps]
		  ,[RoundingTypeId]
		  ,[RoundingPrecision]
		  ,[MaximumVpfPercent]
		  ,[MaximumVpfAmount]
		 
	FROM  [sPayroll].[tPfSetup] 
  
	Where  
		 (Id = @rId OR @rId = 0) AND 
		 PayrollYearId = @rPayrollYearId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pProfessionalTaxRangeAdd] 
	      
		    @rId int
           ,@rSalary decimal(22,6)
           ,@rTax decimal(22,6)
           ,@rPayrollYearId int
           ,@rOrgGroupId smallint
           ,@rCreatedUserId bigint
		   ,@rGenderId tinyint=0
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
  
  IF (@rId = 0)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tProfessionalTaxRange', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tProfessionalTaxRange]
           (
            [Id]
           ,[Salary]
           ,[Tax]
           ,[PayrollYearId]
           ,[CreatedUserId]
           ,[CreatedDateTime]
		   ,[GenderId]
           )
     VALUES
           (
            @lNextNumber 
           ,@rSalary 
           ,@rTax 
           ,@rPayrollYearId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
		   ,@rGenderId
           )
         END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		     UPDATE  [sPayroll].[tProfessionalTaxRange]
			   SET  
				   [Salary] = @rSalary
				  ,[Tax] = @rTax 
				  ,[GenderId]=@rGenderId
			 
      
			  Where Id = @rId	     		    
		END        
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error Creating Professional Tax Range Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pProfessionalTaxRangeGet]
	 @rId int,
	 @rPayrollYearId int
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  

       SELECT   
           [Id]
		  ,[Salary]
		  ,[Tax]
		 ,isnull(GenderId,0) as GenderId
	   FROM  [sPayroll].[tProfessionalTaxRange]
  
  
Where  
     (Id = @rId OR @rId = 0) AND 
     PayrollYearId = @rPayrollYearId
     
     ORDER BY Salary DESC,GenderId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pRemoveProfessionalTaxRange]
	 
	 @rId int,
	 @rPayrollYearId int
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  

       DELETE 		 
	   FROM  [sPayroll].[tProfessionalTaxRange]  
  
Where  
     Id = @rId AND 
     PayrollYearId = @rPayrollYearId 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pRptBankStatement]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0,
	 @rPayTypeId tinyint =0,   -- Mantis #Start - 32058
	 @rDesignationId int= 0,
	 @rGradeId int= 0,
	 @rBankName nvarchar(200)=''  -- Mantis #End - 32058
	  
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	 
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)
	

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,
		EM.Code AS EmployeeCode,
		PPE.TotalEarning,
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		MM.Title AS MonthName,
		ISNULL(PPE.WorkingDays,0) AS WorkingDays,
		(ISNULL(PPE.WorkingDays,0) - ISNULL(PPE.Lwp,0)) AS PresentDays,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		tEM.FirstName,
		tEm.LastName,
		ISNULL(ESO.AccountHolderName,'')AS AccountHolderName,
		tEM.Number,
		EM.EmployeeDesignation,
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
		ISNULL(PER.ChequeNo,'') ChequeNo,
		PER.PayDate,
		ISNULL(PER.PayTypeId,0) AS PayTypeId,
		tEM.CreatedDateTime

		
	FROM sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth	
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON
		PER.SalaryMonth=@rForMonth AND PER.SalaryYear=@rForYear	AND PER.PayrollYearId=@rPayrollYearId AND EM.EmployeeId = PER.EmployeeId
where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0) 
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
	  AND ((UPPER(ESO.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    -- Mantis Start - 32058
	  AND (PER.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
	  AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	  AND (EM.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)           -- Mantis End - 32058
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pRptEmployeePaybillDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0,
	 -- mantis 29994
	 @rBankName nvarchar(200)=''
	  
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	 
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)
	-- mantis-29994
	SET @rBankName = sCommon.fSearchStringGet(@rBankName)


	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		PPE.TotalEarning,
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		MM.Title AS MonthName,
		ISNULL(PPE.WorkingDays,0) AS WorkingDays,
		(ISNULL(PPE.WorkingDays,0) - ISNULL(PPE.Lwp,0)) AS PresentDays,
		--ISNULL(PPE.Lwp,0) AS AbsentDays,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		tEM.FirstName,
		tEm.LastName,
		ISNULL(ESO.AccountHolderName,'')AS AccountHolderName,
		tEM.Number,
		EM.EmployeeDesignation,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
		ISNULL(PER.Remark,'') AS PayProcessEmployeeRemark -- add for mantis : 0041002

		
	FROM sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth	
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
	INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON PER.SalaryMonth=PP.SalaryMonth AND PER.SalaryYear=PP.SalaryYear	AND PER.PayrollYearId=PP.PayrollYearId AND PER.EmployeeId = PPE.EmployeeId  -- add for mantis : 0041002
where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0) 
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
	  --mantis- 29994
	  AND ((ESO.BankName Like '%' + @rBankName  + '%') OR (@rBankName = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
CREATE OR ALTER PROCEDURE [sPayroll].[pRptEmployeePFDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 


	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	   (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID 
		--WHERE PS.PayrollId = @rPayrollId 
		--AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId 
		--AND AT.ForMonth =PP.SalaryMonth AND AT.ForYear =PP.SalaryYear
		AND AT.ForMonth=PP.SalaryMonth AND AT.ForYear =PP.SalaryYear
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id		
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))		
		--AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)	
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))	
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))		
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pRptEmployeeSalaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rReportId smallint=0,
	 @rOrderByField nvarchar(20)='',
	 @rMonths nvarchar(50)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0,
	 @rDesignationId int= 0,		-- MantisId : 0032059
	 @rGradeId int= 0,				-- MantisId : 0032059	
	 @rBatchId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

		SELECT
			@rOrderByField AS OrderByField,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			EM.EmployeeId, 
			PP.ID As PayProcessId,
			PPE.ID AS PayProcessEmployeeId,
			PP.SalaryMonth,
			PP.SalaryYear,
			tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
			EM.Code AS EmployeeCode,
			EM.EmployeeDesignation,
			EM.EmployeeGrade,
			ESO.EPFNumber,
			ESO.PanNumber,
			PPE.TotalEarning,		
			PPE.TotalDeduction,
			PPE.NetAmount,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
			PE.Amount As PPEAmount,
			P.Title AS PayElementTitle,
			P.ID AS PayElementId,
			P.PayElementTypeId,
			ISNULL(ESO.BankName,'') AS BankName,
			ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
			MM.Title AS MonthName,
			P.Title AS PayElementName,
			P.Code AS PayElementCode,
			(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.WorkingDays,@lMonthDay) else 0 END) AS WorkingDays,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
			(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
			P.SortOrder,
			PY.Title AS PayrollYearName,
			PGM.Id AS PayrollGroupId,
			PGM.Title AS PayrollGroupName,
			PPE.GrossBasic,
			P.PayElementDefaultId,
			ISNULL(EPD.Qualification,'') AS Qualification,
			EJD.DateOfJoining AS DateOfAppointment,
			ISNULL(ESO.PayScale,'') AS PayScale,
			EPD.DateOfBirth,
			ISNULL(ROG.SelectableField,'') AS SelectableField,
			RGO.SchoolRequiredSignature ,
			RGO.SchoolRemark1,
			ISNULL(ESO.BasicPay,0) AS BasicPay,
			DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
			ESO.UAN,
			EPD.GenderId,
			ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark,
			tEM.FirstName,
			tEm.LastName,
			EM.DateOfJoining,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(REPLACE(REPLACE(
			(SELECT STUFF(
			(
			  SELECT  ' ' + Leave FROM -- create comma separated values
				(
						Select '<br>'+('<b>'+ LTM.Code +'</b>' +' - '+ CAST(SUM(CAST(L.NoOfLeave AS FLOAT)) AS varchar(50)) ) + '</br>'AS Leave 
						from 
						sHrm.tLeaveTypeMaster LTM  
						INNER JOIN sHrm.tLeave L ON  EM.EmployeeId = L.EmployeeId 
						INNER JOIN sCommon.tStatusMaster SM ON SM.Id=L.StatusId
						Where EM.EmployeeId=EM.EmployeeId AND LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 
						AND LTM.Id = L.LeaveTypeId AND SM.Id=550
						AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
						AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
						GROUP BY LTM.Code
						)AS T FOR XML PATH('')
			)
			,1,1,'')),'&lt;','<'),'&gt;','>')
			,'') AS LeaveCount,
			tEM.Number,
			(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
			ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
			ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
			ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber,
			EM.DepartmentName, --Mantis : 0029371
			ESO.ESINumber,
			CASE 
				WHEN ISNULL(P.IsEmployeeSpecific,0) = 1
				THEN
					(SELECT PS.Amount 
						FROM sPayroll.tPaySetup PS 
						WHERE PS.PayElementId = P.Id 
						AND (PS.SourceId = tEM.Id AND PS.SourceTypeId = 95) 
						AND PS.PayrollYearId = PP.PayrollYearId)
				ELSE
					(SELECT PS.Amount 
						FROM sPayroll.tPaySetup PS 
						WHERE PS.PayElementId = P.Id 
						AND (PS.SourceId = PPE.PayrollGroupId AND PS.SourceTypeId = 2020) 
						AND PS.PayrollYearId = PP.PayrollYearId) 
			END AS PaySetupAmount,					--MantisId = 0030726
			tEM.CreatedDateTime AS CreatedDateTime, --mantis - 0030732
			[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,	--MantisId = 0030726
			ISNULL(PPR.ChequeNo,'') ChequeNo,	--#Start Mantis Id : 0031036
			PPR.PayDate,
			CASE WHEN ISNULL(PPR.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
				ELSE ISNULL(PPR.PayTypeId,0) END AS PayTypeId,
			CASE WHEN ISNULL(PPR.PayTypeId,0) = 0 THEN ISNULL(PTM2.Title,'')
				ELSE ISNULL(PTM.Title,'') END AS PayTypeName,	--#End Mantis Id : 0031036
			ESO.RetirementDate AS RetirementDate, --Mantis - 0031406
			PM.Title AS PayrollTitle,				-- Mantis Id : 0032059
			ISNULL(EI.EmployeePhoto,0x) AS EmployeePhoto,               -- Add for mentis : 0034079
			ESO.IncrementDate , --Add for mantis : 0036465

			   --Mantis Start - 43067
			   (
				SELECT TOP 1 ISNULL(WD.TotalDays, 0)
					FROM sHrm.tWorkingDays WD
					WHERE 
						PP.SalaryYear = WD.ForYear
						AND PP.SalaryMonth = WD.ForMonth
						AND WD.EmployeeGradeId = EJD.EmployeeGradeId
						AND (WD.BatchId = @rBatchId OR @rBatchId = 0)
				) AS TotalDays,
			 (
				SELECT TOP 1 ISNULL(EA.TotalWorkingDays, 0) - (ISNULL(EA.LWP, 0) + ISNULL(EA.PaidLeave, 0))
				FROM sHrm.tEmployeeAttendance EA
				WHERE 
					EA.EmployeeId = EM.EmployeeId
					AND PP.SalaryYear = EA.ForYear
					AND PP.SalaryMonth = EA.ForMonth
					AND (EA.BatchId = @rBatchId OR @rBatchId = 0)
			) AS PresentDays,
			--Mantis End - 43067
			CASE WHEN P.IsDepend = 0 AND P.PayElementTypeId <> 1 THEN 0.0
			ELSE sPayroll.fGetPayElementNetAmount(P.Id, tEM.Id, PPE.PayrollGroupId, PP.PayrollYearId,P.IsEmployeeSpecific) END AS DependSetupAmount		-- Mantis Id : 0043659	
		FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
			LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
			LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
			AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PPR.PayTypeId		--#Start Mantis Id : 0031036
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId		--#End Mantis Id : 0031036
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = tEM.Id                -- Add for mentis : 0034079
		where 
			(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND (P.IsObsolete=0)
			AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
			AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
			AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
			AND ((EJD.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
			AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)						-- MantisId : 0032059
			AND (EM.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	-- MantisId : 0032059
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pRptIncomeTaxAdvancePlanning]
	
	 @rEmployeeCode nvarchar(200),
	 @rPayrollId int,
	 @rPayrollYearId int,
	 @rOrgId int,
	 
	 @rEmployeeId bigint=0,
	 @rAssessmentYearId bigint=0,
	 @rOrgGroupId int=0,
	 @rUserId bigint=0

	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	--SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	
	DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX)
	
		SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(P.Code) FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	WHERE 
		(P.IsObsolete=0)
		AND ((EM.Code = @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0)  
		AND (tEM.OrgId = @rOrgId)
	FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')
	
	SET @query = '
		SELECT MonthYearName,SalaryMonth,SalaryYear,EmployeeName,TotalEarning,TotalDeduction,NetAmount,' + @cols + ' FRom (
		SELECT 
			MM.Title +'' - ''+ convert(nvarchar(10),PP.SalaryYear) AS MonthYearName,
			PP.SalaryMonth,
			PP.SalaryYear,
			tEM.FirstName +'' ''+tEM.MiddleName+'' ''+tEm.LastName AS EmployeeName,
			PPE.TotalEarning,		
			PPE.TotalDeduction,
			PPE.NetAmount,
			PE.Amount As PPEAmount,
			P.Code AS PayElementCode
		FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		WHERE 
			(P.IsObsolete=0)
			AND ((EM.Code = ''' +  @rEmployeeCode + ''' ) OR (''' + @rEmployeeCode + ''' = ''''))
			AND ((PY.PayrollId=' + CONVERT(NVARCHAR(10),@rPayrollId) + ') OR (' + CONVERT(NVARCHAR(10),@rPayrollId) + '=0))
			AND (PP.PayrollYearId = ' + CONVERT(NVARCHAR(10),@rPayrollYearId) + ' OR ' + CONVERT(NVARCHAR(10),@rPayrollYearId) + ' = 0) 
			AND (tEM.OrgId = '+ CONVERT(NVARCHAR(10),@rOrgId) +')
		) X
		pivot 
		(   Sum(PPEAmount)
			for PayElementCode in (' + @cols + ')
		) p '
	IF(@query IS NOT NULL)	
		EXECUTE(@query + ' ORDER BY SalaryYear,SalaryMonth')

	  IF NOT EXISTS(SELECT 1 FROM siTax.tTaxPlanning WHERE EmployeeId = @rEmployeeId AND AssesmentYearId = @rAssessmentYearId)  
	  BEGIN
			INSERT INTO 
				siTax.tTaxPlanning (EmployeeId,AssesmentYearId,IncomeTaxSubgroupId,QualifyingAmount,IsObsolete,CreatedUserId,CreatedDateTime,OrgGroupId)
			SELECT 
				@rEmployeeId AS EmployeeId,
				@rAssessmentYearId AS AssessmentYearId,
				Id AS IncomeTaxSubgroupId,
				QualifyingLimit AS QualifyingAmount,
				0 AS IsObsolete,
				@rUserId AS CreatedUserId,
				sCommon.fGetDate() AS CreatedDateTime,
				@rOrgGroupId AS OrgGroupId
			FROM 
				siTax.tStaticIncomeTaxSubGroup
			WHERE 
				Id IN(2,3,17,20,21,22,23,24,27,28,29,30,31,32,33)
	  END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pRptMonthlyPayElementwiseListGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rPayElementId int,
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,	
	 @rPayElementTypeId int=0,
	 @rMonths nvarchar(50)='',
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rIsDetail bit = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0,
	 @rDesignationId int= 0,  -- Mantis - 0032060
	 @rGradeId int= 0          -- Mantis - 0032060
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	DECLARE @lProfessionalTaxPayElementId int
	
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lProfessionalTaxPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)


	SELECT 
	@rOrderByField AS OrderByField,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp,
	EM.FirstName,
	EM.LastName,
	tEM.Number,
	OM.Id AS OrganizationId,
	OM.Title AS OrganizationTitle,
	OM.Code AS OrganizationCode,
	OM.OrderIndex AS OrganizationOrderIndex,
	@rIsDetail AS IsDetail,
	EM.DateOfBirth,
	EM.DateOfJoining,
	(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
	ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
	tEM.CreatedDateTime as CreatedDateTime,
			CASE 
			WHEN ISNULL(P.IsEmployeeSpecific,0) = 1
			THEN
				(SELECT PS.Percentage 
					FROM sPayroll.tPaySetup PS 
					WHERE PS.PayElementId = P.Id 
					AND (PS.SourceId = tEM.Id AND PS.SourceTypeId = 95) 
					AND PS.PayrollYearId = PP.PayrollYearId)
			ELSE
				(SELECT PS.Percentage
					FROM sPayroll.tPaySetup PS 
					WHERE PS.PayElementId = P.Id 
					AND (PS.SourceId = PPE.PayrollGroupId AND PS.SourceTypeId = 2020) 
					AND PS.PayrollYearId = PP.PayrollYearId) 
			END AS PaySetupPercentage,
			ESO.AccountNumber,
		[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise
		
	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId AND P.IsObsolete = 0
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
	  AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)                       -- Mantis - 0032060
	  AND (EM.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	  -- Mantis - 0032060
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sPayroll].[pRptMonthlyPFStatement]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	 

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

	SELECT
		@rOrderByField AS OrderByField, 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		ISNULL(PPE.TotalEarning,0) AS TotalEarning,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	    (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND PGM.Id=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroup,
		EM.FirstName,
		EM.LastName,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		--LEFT JOIN 
		--(
		--SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		--FROM sPayroll.tPayProcess PP 
		--INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		--INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		--INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		--LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		--INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		--INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		--INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		--WHERE 
		--(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		--AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		--AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		--AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	 --   AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		--AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		--AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		--AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		--) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND PFPro.EmployeePfAmount!=0
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
		AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pRptMonthlyProfessoionTaxSummary]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rEmployeeId bigint,
		@rEmployeeCode nvarchar(200),
		@rEmployeeName nvarchar(200),
		@rDepartmentId int,
		@rForMonth int,
		@rForYear int,
		@rPayrollId int,
		@rPayrollGroupId int,
		@rPayrollYearId int,
		@rOrgId int = 0,
		@rStatusId int = 0,
		@rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN   
		
		DECLARE @lFirstDate Date
		DECLARE @lLasteDate Date
	
	
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
		
 
		SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
		SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

		SELECT
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2, 
			PTR.Id,
			PTR.Tax,
			ISNULL(A.NomberOfEmployee,0) AS NumberOfEmployee,
			--@lIsOnPrePrinted AS IsOnPrePrinted,
			--@lIsDisplayImageHeader AS IsDisplayImageHeader,
			PayrollHeader,
			HeaderDisplayId
		FROM 
			sPayroll.tProfessionalTaxRange PTR
		LEFT JOIN 
		(	
		SELECT 
			PTR.Id, COUNT(EM.EmployeeId) AS NomberOfEmployee ,PE.Amount,
			(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
		FROM 
			sPayroll.tProfessionalTaxRange PTR
			INNER JOIN sPayroll.tPayProcess PP ON PP.PayrollYearId = PTR.PayrollYearId
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID  AND PayElementDefaultId = 57 
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId	
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
			INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		WHERE 
			(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND (P.IsObsolete=0)
			AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
			AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
			AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		GROUP BY 
			PTR.Id,PE.Amount,PM.PayrollHeader,PM.HeaderDisplayId -- Removed EM.Employee from Groupby for mantis 0030813 by Foram
		) A ON A.Id = PTR.Id AND PTR.Tax = A.Amount
		WHERE PTR.PayrollYearId = @rPayrollYearId
		GROUP BY PTR.Id,PTR.Tax,A.NomberOfEmployee,PayrollHeader,HeaderDisplayId
		ORDER BY PTR.Tax
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pRptPayElementwiseSummaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rPayElementId int,
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,	
	 @rPayElementTypeId int=0,
	 @rMonths nvarchar(50)='',
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rIsDetail bit = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	DECLARE @lProfessionalTaxPayElementId int
	
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lProfessionalTaxPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

	SELECT 
	@rOrderByField AS OrderByField,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp,
	EM.FirstName,
	EM.LastName,
	tEM.Number,
	OM.Id AS OrganizationId,
	OM.Title AS OrganizationTitle,
	OM.Code AS OrganizationCode,
	OM.OrderIndex AS OrganizationOrderIndex,
	@rIsDetail AS IsDetail,
	EM.DateOfBirth,
	EM.DateOfJoining,
	--@lIsOnPrePrinted AS IsOnPrePrinted,
	--@lIsDisplayImageHeader AS IsDisplayImageHeader,
	--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
	(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
	--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
	ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
	tEM.CreatedDateTime as CreatedDateTime,
	[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise	 ---30737
		
	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId AND P.IsObsolete = 0
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sPayroll].[pRptPayrollReconcilationGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rPayElementId int,
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,	
	 @rPayElementTypeId int=0,
	 @rMonths nvarchar(50)='',
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rIsDetail bit = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0,
	 @rCompareWithMonth int = 0,
	 @rCompareWithYear int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	DECLARE @lProfessionalTaxPayElementId int
	
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lProfessionalTaxPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

	DECLARE @lFromMonth nvarchar(20) = (SELECT Title FROM sCommon.tMonthMaster WHERE Id = @rForMonth)
	DECLARE @lToMonth nvarchar(20) = (SELECT Title FROM sCommon.tMonthMaster WHERE Id = @rCompareWithMonth)

	SELECT 
	@rOrderByField AS OrderByField,
	@lFromMonth + ' ' + CAST(@rForYear AS nvarchar) + ' compare with ' + @lToMonth + ' ' + CAST(@rCompareWithYear AS nvarchar) AS Builder1,
	@rBuilder2 AS Builder2,	
	Fr.Amount,
	ISNULL(Comp.Amount,0) AS CompAmount,
	Fr.PayElementId, 
	Fr.PayElementName,
	Fr.PayElementCode,
	Fr.EmployeeId,
	Fr.EmployeeName,
	Fr.Code,
	Fr.EmployeeDesignation,
	Fr.SalaryMonth + '-' + Fr.SalaryYear AS SalaryMonthYear,
	ISNULL(Comp.SalaryMonth + '-' + Comp.SalaryYear,0) AS CompSalaryMonthYear,
	Fr.[MonthName],
	ISNULL(Comp.[MonthName],'') AS CompMonthName,
	Fr.PayrollYearName,
	Fr.SortOrder,
	Fr.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	Fr.TotalEarning,
	ISNULL(Comp.TotalEarning,0) AS CompTotalEarning,
	Fr.TotalDeduction,
	ISNULL(Comp.TotalDeduction,0) AS CompTotalDeduction,
	Fr.NetAmount,
	ISNULL(Comp.NetAmount,0) AS CompNetAmount,
	Fr.TotalEarningTotal,
	ISNULL(Comp.TotalEarningTotal,0) AS CompTotalEarningTotal,
	Fr.TotalDeductionTotal,
	ISNULL(Comp.TotalDeductionTotal,0) AS CompTotalDeductionTotal,
	Fr.NetAmountTotal,	
	ISNULL(Comp.NetAmountTotal,0) AS CompNetAmountTotal,
	Fr.PayrollGroupId,
	Fr.PayrollGroupName,
	Fr.GrossBasic,
	ISNULL(Comp.GrossBasic,0) AS CompGrossBasic,
	Fr.PayElementDefaultId,
	Fr.WorkingDays,
	ISNULL(Comp.WorkingDays,0) AS CompWorkingDays,
	Fr.Lwp,
	ISNULL(Comp.Lwp,0) AS CompLwp,
	Fr.FirstName,
	Fr.LastName,
	Fr.Number,
	Fr.OrganizationId,
	Fr.OrganizationTitle,
	Fr.OrganizationCode,
	Fr.OrganizationOrderIndex,
	@rIsDetail AS IsDetail,
	--@lIsOnPrePrinted AS IsOnPrePrinted,
	--@lIsDisplayImageHeader AS IsDisplayImageHeader,	
	PayrollHeader,
	HeaderDisplayId
	FROM 


	(SELECT 
	@rOrderByField AS OrderByField,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp,
	EM.FirstName,
	EM.LastName,
	tEM.Number,
	OM.Id AS OrganizationId,
	OM.Title AS OrganizationTitle,
	OM.Code AS OrganizationCode,
	OM.OrderIndex AS OrganizationOrderIndex,
	@rIsDetail AS IsDetail,
	--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
	(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
	--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
	ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId

	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId AND P.IsObsolete = 0
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))	
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
	  ) Fr 


	  LEFT JOIN 
	  
	  (SELECT 
	@rOrderByField AS OrderByField,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp,
	EM.FirstName,
	EM.LastName,
	tEM.Number,
	OM.Id AS OrganizationId,
	OM.Title AS OrganizationTitle,
	OM.Code AS OrganizationCode,
	OM.OrderIndex AS OrganizationOrderIndex,
	@rIsDetail AS IsDetail

	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId AND P.IsObsolete = 0
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rCompareWithMonth OR @rCompareWithMonth = 0)
	  AND (PP.SalaryYear = @rCompareWithYear OR @rCompareWithYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))	
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
	  ) Comp ON Comp.PayElementId = Fr.PayElementId AND Comp.EmployeeId = Fr.EmployeeId


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

CREATE OR ALTER PROCEDURE [sPayroll].[pRptPaysheetDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rReportId smallint=0,
	 @rOrgId int,
	 @rOrderByField nvarchar(20)='',
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
DECLARE @lOrgGroupId int = 0
DECLARE @lCurrencyCode nvarchar(20) = ''
    SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

	SELECT
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@lCurrencyCode AS CurrencyCode,
		@rForYear AS Foryear,
		(Select DateName( month , DateAdd( month ,@rForMonth, 0 ) - 1 )) AS ForMonth,
		(SELECT Title FROM sSetup.tOrganizationMaster  WHERE Id= EM.OrgId ) AS OrgName,
		(SELECT OG.Title FROM sSetup.tOrgGroupMaster OG INNER JOIN sSetup.tOrganizationMaster OM  ON OG.Id=OM.OrgGroupId WHERE OM.Id=EM.OrgId) AS TrustName,
		(SELECT SmallAddress1 FROM sSetup.tOrganizationMaster WHERE Id= EM.OrgId ) AS ReportAddress1,
		(SELECT SmallAddress2 FROM sSetup.tOrganizationMaster WHERE Id= EM.OrgId ) AS ReportAddress2,
	  --  (SELECT EM1.FirstName+' '+EM1.MiddleName+' ' +EM1.LastName From  sHrm.tEmployeeMaster EM1
			--INNER JOIN sHrm.tEmployeeJobDetail EJ ON EM1.Id=EJ.EmployeeId
			--INNER JOIN sHrm.tEmployeeDesignationMaster ED ON ED.Id=EJ.EmployeeDesignationId
			--Where EJ.OrgId=EM.OrgID AND ED.Code='PRINCIPAL' AND  ISNULL(EM.IsOtherUser,0) = 0)AS HeadMasterName,
		(Select STUFF((SELECT ','+ (EM1.FirstName+' '+EM1.MiddleName+' ' +EM1.LastName) From  sHrm.tEmployeeMaster EM1
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EM1.Id=EJ.EmployeeId
		INNER JOIN sHrm.tEmployeeDesignationMaster ED ON ED.Id=EJ.EmployeeDesignationId
		Where EJ.OrgId=EM.OrgID AND ED.Code='PRINCIPAL' AND  ISNULL(EM.IsOtherUser,0) = 0
		FOR XML Path('')),1,1,''))AS HeadMasterName,
		
		10000 AS SalaryGrant,
		10000 AS RecoveryAdj,
		10000 AS GrossAmount,
		10000 AS TutionFees	,						
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=1 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS BasicPay,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=8 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS GradePay,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=2 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS DA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=4 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS HRA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=3 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS CLA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=18 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS TA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=17 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS Differenc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=56 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS PF,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS PT,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS TrSoc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS NtrSoc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=54 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS LIC,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS RD,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=52 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS IncomeTax,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=52 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS Other,
			1 AS HM,
			1 AS AHM,
			1 AS Sup,
			1 AS TG,
			1 AS TUG,
			1 AS SplTr,
			1 AS OS,
			1 AS HC,
			1 AS SrCl,
			1 AS JrCl,
			1 AS Libr,
			1 AS LAs,
			1 AS LAt,
			1 AS Naik,
			1 AS Peon,
			1 AS SS,
			EM.FirstName,
		    EM.LastName,
			EM.OrgID,
			--@lIsOnPrePrinted AS IsOnPrePrinted,
			--@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
			(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
			--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
			ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
			
			
	FROM 
	sHrm.tEmployeeMaster EM
    INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.EmployeeId = EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId AND EM.IsObsolete = 0 
	INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id AND ODM.IsObsolete = 0
	--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = EM.OrgID
	INNER JOIN sPayroll.tPayrollMaster PM ON  PM.Id = @rPayrollId
	WHERE ((EM.OrgID = @rOrgId) OR (@rOrgId = 0))
	AND (ODM.Id = @rDepartmentId OR @rDepartmentId = 0)
	AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
	AND ((EJD.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pRptPayStatementGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0,
	 @rDesignationId int= 0,   -- Mantis Start - 32061
	 @rGradeId int= 0          -- Mantis End - 32061
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1

	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)


	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    ISNULL(ESO.UAN,'') AS UAN,
	    (CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarning,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeduction,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmount,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
		EM.DateOfLeaving,
		tEM.CreatedDateTime,
		ISNULL(PPE.WorkingDays,@lMonthDay) WorkingDays,
		PPE.Lwp,
		ISNULL(PPE.PaidLeave,0) PaidLeave,
		ISNULL(PER.ChequeNo,'') ChequeNo,
		PER.PayDate,
		CASE WHEN ISNULL(PER.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
			ELSE ISNULL(PER.PayTypeId,0) END AS PayTypeId,
		CASE WHEN ISNULL(PER.PayTypeId,0) = 0 THEN ISNULL(PTM2.Title,'')
			ELSE ISNULL(PTM.Title,'') END AS PayTypeName,
		ESO.AccountNumber -- Added for mantis : 32061 by Nilesh


	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
		LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON
			PER.SalaryMonth=@rForMonth AND PER.SalaryYear=@rForYear	AND PER.PayrollYearId=@rPayrollYearId AND EM.EmployeeId = PER.EmployeeId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PER.PayTypeId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '' OR ISNULL(@lFirstDate,'')='')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '' OR ISNULL(@lLasteDate,'')='')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)						-- Mantis Start - 32061
	  AND (EM.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)       -- Mantis End - 32061
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
CREATE OR ALTER PROCEDURE [sPayroll].[pRptPFChallanDetailGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		--ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		--tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		--EM.Code AS EmployeeCode,
		--ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
		(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
		(SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    --ISNULL(ESO.UAN,'') AS UAN,
	   -- PPE.TotalEarning,
	    OOD.PFEstablishmentCode,
	    OM.DisplayTitle AS OrganizationName,
	    OM.StreetOne + ' ' + OM.StreetTwo + ' ' + OM.StreetThree AS OrgAddress,
		OM.CityName AS OrgCity,
		OM.StateName AS OrgState,
		OM.CountryName AS OrgCountry,
		OM.ZipCode AS OrgZipCode,
		OM.HomePage AS OrgHomePage,
		OM.PhoneNo AS OrgPhoneNo,
		OM.RegistrationDetail AS OrgRegistrationDetail,
	    EM.FirstName,
		EM.LastName,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		--INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		INNER JOIN sSetup.tOrganizationOtherDetail OOD ON OOD.OrgId = EM.OrgID 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = OOD.OrgId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		--LEFT JOIN 
		--(
		--SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		--FROM sPayroll.tPayProcess PP 
		--INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		--INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		--INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		--LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		--INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		--INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		--INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		--WHERE 
		--(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		--AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		--AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		--AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	 --   AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		--AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		--AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		--AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		--AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
  --      AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		--) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pRptPFDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	   (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
		(SELECT SUM(PE1.Amount) FROM sPayroll.tPayProcessElement PE1
		INNER JOIN sPayroll.tPayElement P1 ON PE1.PayElementId=P1.Id
		INNER JOIN sPayroll.tPayProcessEmployee PPE1 ON PPE1.Id = PE1.PayProcessEmployeeID
		INNER JOIN sPayroll.tPayProcess PP1 ON PP1.Id = PPE1.PayProcessId AND PP1.SalaryMonth = PP.SalaryMonth AND PP1.SalaryYear = PP.SalaryYear
		WHERE P1.PayElementDefaultId IN (1,2,16) AND PPE1.EmployeeId = PPE.EmployeeId 
		AND P1.PayrollId = P.PayrollId
		GROUP BY PPE1.EmployeeId) AS BasicDaOaAmount,		-- #Start Mantis Id : 0030729
		EM.DateOfLeaving,
		tEM.CreatedDateTime,
		[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise	-- #End Mantis Id : 0030729


	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = 0) OR (0 = 0))  AND ((AT.ForYear = 0) OR (0 = 0)) 
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId		-- Mantis Id : 0030729
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '' OR ISNULL(@lFirstDate,'')='')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '' OR ISNULL(@lLasteDate,'')='')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sPayroll].[pRptPFECRFormat]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrgGroupId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lFirstDate Date
DECLARE @lLasteDate Date


SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))	

DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lIsECRIsLWP nvarchar(10)

SELECT @lIsECRIsLWP = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 259 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

IF (@lIsECRIsLWP = '') OR (@lIsECRIsLWP = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1

BEGIN  

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

-- For report
	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    ISNULL(A.WorkingDays,0) AS WorkingDays,
	    (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    CASE WHEN @lIsActivateUniqueId = 1 THEN ROUND(1+PPE.Lwp,0)-1 ELSE 0 END AS NCPDays,
	    ISNULL(A.TotalEarning,0) AS TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId,PPE.TotalEarning
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
--	For Notepad report
	
	SELECT 
		ISNULL(ESO.UAN,'') AS UAN,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		--ISNULL(cast(replace(A.TotalEarning, '.','') as integer),0) AS TotalEarning,
		ISNULL(CONVERT(DECIMAL(12,0),A.TotalEarning),0) AS TotalEarning,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		THEN 
		--(SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE 
		(SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE
		INNER JOIN sPayroll.tPayElement P ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId 
		IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit1,
		ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit1,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  THEN 
		--(SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
		(SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit2,
		ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit2,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--THEN (SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P
		THEN (SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		--)  ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit3,
		)  ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit3,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit1,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit2,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit3,
		--ISNULL(cast(replace(PFPro.EmployeePfAmount, '.','') as integer),0) AS EmployeePfAmount,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployeePfAmount),0) AS EmployeePfAmount,
		--ISNULL(cast(replace(PFPro.EmployerFpsAmount, '.','') as integer),0) AS EmployerFpsAmount,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployerFpsAmount),0) AS EmployerFpsAmount,
		--ISNULL(cast(replace(PFPro.EmployeePfAmount, '.','') as integer),0) - ISNULL(cast(replace(PFPro.EmployerFpsAmount, '.','') as integer),0) AS EPFEPS,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployeePfAmount),0) - ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployerFpsAmount),0) AS EPFEPS,
		--CASE WHEN @lIsActivateUniqueId = 1 THEN cast(replace(ROUND(1+PPE.Lwp,0)-1, '.','') as integer) ELSE 0 END AS NCPDays,
		CASE WHEN @lIsActivateUniqueId = 1 THEN Convert(DECIMAL(12,0),(1+PPE.Lwp)-1,0) ELSE 0 END AS NCPDays,
		0 AS RefundAdv
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId,PPE.TotalEarning
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 		
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pSelectPayElementAdd] 
	      
			@rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rPayElementTypeId tinyint
           ,@rPaidCategoryId tinyint
           ,@rIsLwp bit
           ,@rIsEmployeeSpecific bit
           ,@rIsDepend bit
           ,@rIsAvailDuringProbation bit
           ,@rIsIncludeInPaySlip bit
           ,@rSortOrder tinyint
           ,@rIsObsolete bit
           ,@rOrgGroupId int
           ,@rCreatedUserId bigint
           ,@rPayElementDefaultId int
		   ,@rPayrollId int
           ,@rIsIncludeInTotal bit=0
		   ,@rPayrollYearId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
  
	--IF (@rId = 0)
	IF NOT EXISTS(SELECT 1 FROM [sPayroll].[tPayElement] WHERE PayElementDefaultId = @rPayElementDefaultId AND
	PayrollId = @rPayrollId)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayElement', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPayElement]
           (
            [ID]
           ,[Code]
           ,[Title]
           ,[PayElementTypeId]
           ,[PaidCategoryId]
           ,[IsLwp]
           ,[IsEmployeeSpecific]
           ,[IsDepend]
           ,[IsAvailDuringProbation]
           ,[IsIncludeInPaySlip]
           ,[SortOrder]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[PayElementDefaultId]
           ,[PayrollId]
           ,[IsIncludeInTotal]
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rPayElementTypeId 
           ,@rPaidCategoryId 
           ,@rIsLwp 
           ,@rIsEmployeeSpecific 
           ,@rIsDepend 
           ,@rIsAvailDuringProbation 
           ,@rIsIncludeInPaySlip 
           ,@rSortOrder 
           ,@rIsObsolete 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()  
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rPayElementDefaultId
           ,@rPayrollId
           ,@rIsIncludeInTotal
           )
        SELECT 1 AS RESULT
    	END
    ELSE
		BEGIN    
		    SET @lNextNumber = @rId
		    UPDATE  [sPayroll].[tPayElement]
			   SET   
				   --[Title] = @rTitle 
				  --,
				  [PayElementTypeId] = @rPayElementTypeId 
				  ,[PaidCategoryId] = @rPaidCategoryId 
				  ,[IsLwp] = @rIsLwp 
				  ,[IsEmployeeSpecific] = @rIsEmployeeSpecific 
				  ,[IsDepend] = @rIsDepend 
				  ,[IsAvailDuringProbation] = @rIsAvailDuringProbation 
				  ,[IsIncludeInPaySlip] = @rIsIncludeInPaySlip 
				  ,[SortOrder] = @rSortOrder 
				  ,[IsObsolete] = @rIsObsolete  
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate()
				  ,[PayElementDefaultId] = @rPayElementDefaultId
				  ,[PayrollId]=@rPayrollId
				  ,[IsIncludeInTotal]=@rIsIncludeInTotal
			   WHERE PayrollId = @rPayrollId AND PayElementDefaultId = @rPayElementDefaultId    		     		    
			END        

	--Add Data Into tPayElementHistory 

	IF NOT EXISTS(SELECT 1 FROM [sPayroll].[tPayElementHistory] WHERE PayElementDefaultId = @rPayElementDefaultId AND
	PayrollId = @rPayrollId AND PayrollYearId=@rPayrollYearId)
    
    BEGIN	

	INSERT INTO [sPayroll].[tPayElementHistory]
           (
            [ID]
           ,[Code]
           ,[Title]
           ,[PayElementTypeId]
           ,[PaidCategoryId]
           ,[IsLwp]
           ,[IsEmployeeSpecific]
           ,[IsDepend]
           ,[IsAvailDuringProbation]
           ,[IsIncludeInPaySlip]
           ,[SortOrder]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[PayElementDefaultId]
           ,[PayrollId]
           ,[IsIncludeInTotal]
           ,[PayrollYearId]
           )
     VALUES
           (
            @lNextNumber
           ,@rCode 
           ,@rTitle 
           ,@rPayElementTypeId 
           ,@rPaidCategoryId 
           ,@rIsLwp 
           ,@rIsEmployeeSpecific 
           ,@rIsDepend 
           ,@rIsAvailDuringProbation 
           ,@rIsIncludeInPaySlip 
           ,@rSortOrder 
           ,@rIsObsolete 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()  
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rPayElementDefaultId
           ,@rPayrollId
           ,@rIsIncludeInTotal
		   ,@rPayrollYearId
           )
        SELECT 1 AS RESULT
    	END
    ELSE
		BEGIN    
		    SET @lNextNumber = @rId
		    UPDATE  [sPayroll].[tPayElementHistory]
			   SET   
				   --[Title] = @rTitle 
				  --,
				  [PayElementTypeId] = @rPayElementTypeId 
				  ,[PaidCategoryId] = @rPaidCategoryId 
				  ,[IsLwp] = @rIsLwp 
				  ,[IsEmployeeSpecific] = @rIsEmployeeSpecific 
				  ,[IsDepend] = @rIsDepend 
				  ,[IsAvailDuringProbation] = @rIsAvailDuringProbation 
				  ,[IsIncludeInPaySlip] = @rIsIncludeInPaySlip 
				  ,[SortOrder] = @rSortOrder 
				  ,[IsObsolete] = @rIsObsolete  
				  ,[UpdatedUserId] = @rCreatedUserId 
				  ,[UpdatedDateTime] = sCommon.fGetDate()
				  ,[PayElementDefaultId] = @rPayElementDefaultId
				  ,[PayrollId]=@rPayrollId
				  ,[IsIncludeInTotal]=@rIsIncludeInTotal
				  ,[PayrollYearId]=@rPayrollYearId
			   WHERE PayrollId = @rPayrollId AND PayElementDefaultId = @rPayElementDefaultId  AND PayrollYearId = @rPayrollYearId 		     		    
			END  



	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPayroll].[pSelectPayElementGet]

           @rPayrollId int
           
AS
SET NOCOUNT ON

BEGIN

	SELECT  
			ISNULL(PE.ID,0) AS ID,
			PED.Code,
			PED.Title,
			PED.PayElementTypeId,
			PED.PaidCategoryId,
			ISNULL(PED.IsLwp,0) AS IsLwp,
			ISNULL(PED.IsEmployeeSpecific,0) AS IsEmployeeSpecific,
			ISNULL(PED.IsDepend,0) AS IsDepend,
			ISNULL(PED.IsAvailDuringProbation,0) AS IsAvailDuringProbation,
			ISNULL(PED.IsIncludeInPaySlip,0) AS IsIncludeInPaySlip,
			PED.SortOrder,
			--CASE ISNULL(PED.SortOrder,0)
			--	WHEN 0 THEN PED.SortOrder
			--	ELSE PE.SortOrder
			--END AS SortOrder,
			--ISNULL(PE.SortOrder,0) AS SortOrder,
			ISNULL(PE.IsObsolete,0) AS IsObsolete,
			PE.CreatedUserId,
			PE.CreatedDateTime,
			PE.UpdatedUserId,
			PE.UpdatedDateTime,
			PED.ID AS PayElementDefaultId,
			PE.PayrollId,
			PET.Title AS PayElementType,
			ISNULL(PED.IsIncludeInTotal,0) AS IsIncludeInTotal
	FROM
			sPayroll.tPayElementDefault PED 
				INNER JOIN sPayroll.tPayElementType PET 
			ON PET.Id=PED.PayElementTypeId
				LEFT JOIN sPayroll.tPayElement PE 
			ON PED.ID = PE.PayElementDefaultId AND PE.PayrollId=@rPayrollId AND PE.IsObsolete = 0
			WHERE PED.IsObsolete = 0
			
			ORDER BY PED.SortOrder
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPayroll].[pSelectPayElementHistoryGet]

           @rPayrollId int,
		   @rPayrollYearId int=0
           
AS
SET NOCOUNT ON

BEGIN

	SELECT  
			ISNULL(PE.ID,0) AS ID,
			PED.Code,
			PED.Title,
			PED.PayElementTypeId,
			PED.PaidCategoryId,
			ISNULL(PED.IsLwp,0) AS IsLwp,
			ISNULL(PED.IsEmployeeSpecific,0) AS IsEmployeeSpecific,
			ISNULL(PED.IsDepend,0) AS IsDepend,
			ISNULL(PED.IsAvailDuringProbation,0) AS IsAvailDuringProbation,
			ISNULL(PED.IsIncludeInPaySlip,0) AS IsIncludeInPaySlip,
			PED.SortOrder,
			ISNULL(PE.IsObsolete,0) AS IsObsolete,
			PE.CreatedUserId,
			PE.CreatedDateTime,
			PE.UpdatedUserId,
			PE.UpdatedDateTime,
			PED.ID AS PayElementDefaultId,
			PE.PayrollId,
			PET.Title AS PayElementType,
			ISNULL(PED.IsIncludeInTotal,0) AS IsIncludeInTotal
	FROM
			sPayroll.tPayElementDefault PED 
				INNER JOIN sPayroll.tPayElementType PET 
			ON PET.Id=PED.PayElementTypeId
				INNER JOIN sPayroll.tPayElementHistory PE  
			ON PED.ID = PE.PayElementDefaultId 
			WHERE PED.IsObsolete = 0
			AND PE.PayrollId=@rPayrollId
			AND PE.PayrollYearId=@rPayrollYearId AND PE.IsObsolete = 0
			
			ORDER BY PED.SortOrder

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sPayroll].[pXMLModifyOpeningBalance]
	
	@rLedgerOpeningBalanceXml [nvarchar](max)
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
   BEGIN TRY
	BEGIN TRANSACTION

		DECLARE @loDoc INT
		EXEC sp_xml_preparedocument @loDoc OUTPUT, @rLedgerOpeningBalanceXml
		BEGIN
		
 
			UPDATE LM 			  
			SET 
			LM.OpeningBalance = E.OpeningBalance 			
			FROM			
			sAccounting.tLedgerMaster  LM
			INNER JOIN	 
			(
					SELECT Id AS Id ,OpeningBalance AS OpeningBalance,AccountingYearId AS AccountingYearId  FROM
					OPENXML (@loDoc, '/Table/LedgerMaster', 1)
					WITH (
							Id int, 
							OpeningBalance Decimal(22,2),
							AccountingYearId int)
							 
			)E
						
			ON E.Id = LM.Id	WHERE LM.Id = E.Id AND LM.AccountingYearId = E.AccountingYearId
			
			Select 1 As Result 
		END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sPoliciesForms].[pFolderFileGet]
** Desc:  get Record From FolderFile Table
** Auth:  Savan Vaghela
** Date:  10-April-2017
** Page:  /Pages/Hrm/PoliciesForms/FormsMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    10-April-2017      Savan Vaghela       
************************************************************/
--EXEC [sPoliciesForms].[pDeleteFolderFileByID] 100100241
CREATE OR ALTER PROCEDURE [sPoliciesForms].[pDeleteFolderFileByID]
	@rFileFolderId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			BEGIN
				IF OBJECT_ID('tempdb..#TempFolderDetails') IS NOT NULL
				DROP TABLE #TempFolderDetails	

				;WITH
				  cteReports (id)
				  AS
				  (
					SELECT id 
					FROM [sPoliciesForms].[tFolderFile]  
					WHERE Id =@rFileFolderId  
	 
					UNION ALL
   
					SELECT e.id 
					FROM [sPoliciesForms].[tFolderFile] e
					INNER JOIN cteReports r
					 ON e.PerentFolderId = r.id
				  )
				SELECT id INTO #TempFolderDetails	FROM cteReports 
				
				DELETE FROM [sPoliciesForms].[tFolderFile]				WHERE  id in (SELECT id FROM #TempFolderDetails )
				DELETE FROM [sPoliciesForms].[tFolderFilePermission]    WHERE  FolderFileId in (SELECT id FROM #TempFolderDetails )
							
				
				SELECT 1 AS Result
			END	 
		COMMIT TRANSACTION		
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -11 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sPoliciesForms].[pFolderFileAdd]
** Desc:  Insert Record on FolderFile Table
** Auth:  Savan Vaghela
** Date:  3-April-2017
** Page:  /Pages/Hrm/PoliciesForms/FormsMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    3-April-2017      Savan Vaghela       
************************************************************/
--EXEC [sPoliciesForms].[pFolderFileAdd]
CREATE OR ALTER PROCEDURE [sPoliciesForms].[pFileExitsCheck]
	 	@rTitle nvarchar(200),
	 	@rPerentFolderId INT
WITH EXECUTE AS CALLER
AS
BEGIN
	 
	 
			BEGIN
				IF Exists(SELECT Id FROM [sPoliciesForms].[tFolderFile] WHERE IsFolder=0 AND Title=@rTitle AND PerentFolderId=@rPerentFolderId )
					BEGIN
						SELECT 1 as Result
					END 
				ELSE
					BEGIN	
						SELECT 0 as Result
					END
			END
		
		 
			 
	
		 
	 
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sPoliciesForms].[pFolderFileAdd]
** Desc:  Insert Record on FolderFile Table
** Auth:  Savan Vaghela
** Date:  3-April-2017
** Page:  /Pages/Hrm/PoliciesForms/FormsMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    3-April-2017      Savan Vaghela       
************************************************************/
--EXEC [sPoliciesForms].[pFolderFileAdd]
CREATE OR ALTER PROCEDURE [sPoliciesForms].[pFolderFileAdd]
	    @rId int,
		@rIsForms Bit,
		@rIsFolder BIT,
		@rTitle nvarchar(200),
		@rRemark nvarchar(400),
		@rContentType nvarchar(400) = null,
		@rPerentFolderId INT,
		@rSize Float = null,
		@rAccessible  SMALLINT,
		@rViewAccess SMALLINT,
		@rUploadAccess SMALLINT,
		@rEditAccess SMALLINT,
		@rDeleteAccess  SMALLINT,
		@rOrgId SMALLINT,
		@rIsObsolete bit =null,
        @rCreatedUserId bigint ,
		@Access NVARCHAR(MAX),
		@View   NVARCHAR(MAX),  
		@Upload NVARCHAR(MAX),
		@Edit   NVARCHAR(MAX),
		@Delete NVARCHAR(MAX),
		@rOrgGroupId INT
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		IF(@rId = 0)	
			BEGIN
				IF Exists(SELECT Id FROM [sPoliciesForms].[tFolderFile] WHERE Title=@rTitle AND PerentFolderId=@rPerentFolderId AND IsForms= @rIsForms)
					BEGIN
						SELECT -101 as Result
						RETURN
					END 
				
			END
		
		ELSE
			BEGIN
				IF  Exists(SELECT Id FROM [sPoliciesForms].[tFolderFile] WHERE Title=@rTitle  AND PerentFolderId=@rPerentFolderId AND Id<>@rId AND IsForms= @rIsForms)
					BEGIN
						SELECT -101 as Result
						RETURN
					END
			END
	
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
	
		IF(@rId = 0)	
			BEGIN

				



				


				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sPoliciesForms.tFolderFile', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sPoliciesForms].[tFolderFile]
				(
					Id,
					IsForms,
					IsFolder,
					Title,
					Remark,
					ContentType,
					PerentFolderId,
					Size,
					Accessible,
					ViewAccess,
					UploadAccess,
					EditAccess,
					DeleteAccess,
					OrgId,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime
					 
				)
				VALUES
				(
					@lNextNumber,
					@rIsForms,
					@rIsFolder,
					@rTitle,
					@rRemark,
					@rContentType,
					@rPerentFolderId,
					@rSize,
					@rAccessible,
					@rViewAccess,
					@rUploadAccess,
					@rEditAccess,
					@rDeleteAccess,
					@rOrgId,
					0,
					@rCreatedUserId,
					sCommon.fGetDate()
					
				)

				DECLARE @AccessibleToFD      TABLE (RowID INT ,item int)INSERT INTO @AccessibleToFD SELECT * FROM [sCommon].[fnSplitRowID](@Access,',')
				DECLARE @ViewAccessFD        TABLE (RowID INT ,item int)INSERT INTO @ViewAccessFD   SELECT * FROM [sCommon].[fnSplitRowID](@View,',')
				DECLARE @UploadAccessFD      TABLE (RowID INT ,item int)INSERT INTO @UploadAccessFD SELECT * FROM [sCommon].[fnSplitRowID](@Upload,',')
				DECLARE @EditAccessFD        TABLE (RowID INT ,item int)INSERT INTO @EditAccessFD   SELECT * FROM [sCommon].[fnSplitRowID](@Edit,',')
				DECLARE @DeleteAccessFD      TABLE (RowID INT ,item int)INSERT INTO @DeleteAccessFD SELECT * FROM [sCommon].[fnSplitRowID](@Delete,',')
				

				INSERT INTO [sPoliciesForms].[tFolderFilePermission](FolderFileId,RoleId,IsAccess,IsView,IsUpload,IsEdit,IsDelete)


				SELECT
					@lNextNumber 
					,ROL.ID
					,CASE WHEN @rAccessible  =1 THEN  CONVERT(bit,0)  WHEN @rAccessible  =3 THEN  CONVERT(bit,1) WHEN  AccessibleToFD.RowID IS NOT NULL THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END  
					,CASE WHEN @rViewAccess  =1 THEN  CONVERT(bit,0)  WHEN @rViewAccess  =3 THEN  CONVERT(bit,1) WHEN  ViewAccessFD.RowID IS NOT NULL THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END  
					,CASE WHEN (@rUploadAccess=1 OR @rUploadAccess=-1) THEN  CONVERT(bit,0)  WHEN @rUploadAccess=3 THEN  CONVERT(bit,1) WHEN  UploadAccessFD.RowID IS NOT NULL THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END   
					,CASE WHEN @rEditAccess  =1 THEN  CONVERT(bit,0)  WHEN @rEditAccess  =3 THEN  CONVERT(bit,1) WHEN  EditAccessFD.RowID IS NOT NULL THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END  
					,CASE WHEN @rDeleteAccess=1 THEN  CONVERT(bit,0)  WHEN @rDeleteAccess=3 THEN  CONVERT(bit,1) WHEN  DeleteAccessFD.RowID IS NOT NULL THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END  
				FROM sSecurity.tRole       AS ROL
					LEFT JOIN  @AccessibleToFD AS AccessibleToFD ON AccessibleToFD.item=ROL.Id
					LEFT JOIN  @ViewAccessFD   AS ViewAccessFD   ON ViewAccessFD.item=ROL.Id
					LEFT JOIN  @UploadAccessFD AS UploadAccessFD ON UploadAccessFD.item=ROL.Id
					LEFT JOIN  @EditAccessFD   AS EditAccessFD   ON EditAccessFD.item=ROL.Id
					LEFT JOIN  @DeleteAccessFD AS DeleteAccessFD ON DeleteAccessFD.item=ROL.Id
				WHERE ROL.IsObsolete = 0 AND ROL.OrgGroupId = @rOrgGroupId

				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sPoliciesForms].[tFolderFile]
				SET
				Title=@rTitle,
				Remark=@rRemark,
				IsObsolete=@rIsObsolete,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
				WHERE Id = @rId
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sPoliciesForms].[pFolderFileGet]
** Desc:  get Record From FolderFile Table
** Auth:  Savan Vaghela
** Date:  3-April-2017
** Page:  /Pages/Hrm/PoliciesForms/FormsMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    3-April-2017      Savan Vaghela       
************************************************************/
--EXEC [sPoliciesForms].[pFolderFileGet] 1001,1001000000003,0,1
CREATE OR ALTER PROCEDURE [sPoliciesForms].[pFolderFileGet] @rOrgId smallint,
@rCreatedUserId bigint,
@rPerentFolderId int,
@rIsForms bit 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

    DECLARE @rRoleId int
    SELECT @rRoleId = RoleId FROM [sSecurity].[tUserRole] WHERE UserID = @rCreatedUserId AND IsObsolete = 0

    SELECT 
		UFF.Id, UFF.Title, CASE WHEN UFF.IsFolder = 1 THEN 'Folder' ELSE 'File' END AS Type, 
		CASE WHEN UFF.IsFolder = 1 THEN 1 ELSE 0 END AS TypeId,
		CASE WHEN UFF.IsFolder = 1 THEN [sPoliciesForms].[fFileFolderSizeGet]([sPoliciesForms].[fFolderSizeGet](UFF.Id)) ELSE [sPoliciesForms].[fFileFolderSizeGet](ISNULL(UFF.Size, 0)) END AS Size,
		USR.DisplayTitle AS CreatedUser,
		CONVERT(varchar(20), UFF.CreatedDateTime, 113) AS CreateDate,
		CONVERT(bit, 1) AS IsAccess,
		CONVERT(bit, 1) AS IsView,
		CONVERT(bit, 1) AS IsUpload,
		CONVERT(bit, 1) AS IsEdit,
		CONVERT(bit, 1) AS IsDelete,
		FolderPath = [sPoliciesForms].[fFolderPathGet](UFF.Id)
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId = @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsForms = @rIsForms

    UNION ALL

    SELECT
        UFF.Id, UFF.Title,
        CASE WHEN UFF.IsFolder = 1 THEN 'Folder' ELSE 'File' END AS Type,
        CASE WHEN UFF.IsFolder = 1 THEN 1 ELSE 0 END AS TypeId,
        CASE WHEN UFF.IsFolder = 1 THEN [sPoliciesForms].[fFileFolderSizeGet]([sPoliciesForms].[fFolderSizeGet](UFF.Id)) ELSE [sPoliciesForms].[fFileFolderSizeGet](ISNULL(UFF.Size, 0)) END AS Size,
        USR.DisplayTitle AS CreatedUser,
       CONVERT(varchar(20), UFF.CreatedDateTime, 113) AS CreateDate,
        FFP.IsAccess,
        FFP.IsView,
        FFP.IsUpload,
        FFP.IsEdit,
        FFP.IsDelete,
        FolderPath = [sPoliciesForms].[fFolderPathGet](UFF.Id)
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    LEFT JOIN [sPoliciesForms].[tFolderFilePermission] AS FFP ON FFP.FolderFileId = UFF.Id
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId <> @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsForms = @rIsForms
    AND UFF.Id IN (SELECT FolderFileId FROM [sPoliciesForms].[tFolderFilePermission] WHERE FolderFileId = UFF.Id
    AND RoleId = @rRoleId AND IsView = 1)
    AND FFP.RoleId = @rRoleId


    SELECT UFF.Id, UFF.Title,FolderPath = [sPoliciesForms].[fFolderPathGet](UFF.Id)
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId = @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsFolder = 1
    AND UFF.IsForms = @rIsForms

    UNION ALL

    SELECT UFF.Id, UFF.Title,FolderPath = [sPoliciesForms].[fFolderPathGet](UFF.Id) 
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    LEFT JOIN [sPoliciesForms].[tFolderFilePermission] AS FFP ON FFP.FolderFileId = UFF.Id
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId <> @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsForms = @rIsForms
    AND UFF.IsFolder = 1
    AND UFF.Id IN (SELECT FolderFileId FROM [sPoliciesForms].[tFolderFilePermission]
    WHERE FolderFileId = UFF.Id
    AND RoleId = @rRoleId AND IsView = 1)
    AND FFP.RoleId = @rRoleId


    SELECT UFF.Id, UFF.Title, ISNULL(Exe.ImageName, 'unknown.png') AS ImageName
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    LEFT JOIN ( SELECT * FROM [sPoliciesForms].[tFolderImageName]) AS Exe ON LOWER(Exe.Extension) = LOWER(REVERSE(LEFT(REVERSE(UFF.Title), CHARINDEX('.', REVERSE(UFF.Title)) - 1)))
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId = @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsFolder = 0
    AND UFF.IsForms = @rIsForms


    UNION ALL

    SELECT UFF.Id, UFF.Title, ISNULL(Exe.ImageName, 'unknown.png') AS ImageName
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    LEFT JOIN (SELECT * FROM [sPoliciesForms].[tFolderImageName]) AS Exe ON LOWER(Exe.Extension) = LOWER(REVERSE(LEFT(REVERSE(UFF.Title), CHARINDEX('.', REVERSE(UFF.Title)) - 1)))
    LEFT JOIN [sPoliciesForms].[tFolderFilePermission] AS FFP ON FFP.FolderFileId = UFF.Id
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId <> @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsForms = @rIsForms
    AND UFF.IsFolder = 0
    AND UFF.Id IN (SELECT FolderFileId
    FROM [sPoliciesForms].[tFolderFilePermission]
    WHERE FolderFileId = UFF.Id
    AND RoleId = @rRoleId
    AND IsView = 1)
    AND FFP.RoleId = @rRoleId


    IF (@rPerentFolderId = 0)
    BEGIN
        SELECT
            CONVERT(bit, 1) AS IsAccess,
            CONVERT(bit, 1) IsView,
            CONVERT(bit, 1) IsUpload,
            CONVERT(bit, 1) AS IsEdit,
            CONVERT(bit, 1) AS IsDelete
    END
    ELSE
    BEGIN
        SELECT
            CASE WHEN FOL.CreatedUserId = @rCreatedUserId THEN CONVERT(bit, 1) ELSE IsAccess END AS IsAccess,
            CASE WHEN FOL.CreatedUserId = @rCreatedUserId THEN CONVERT(bit, 1) ELSE IsView END AS IsView,
            CASE WHEN FOL.CreatedUserId = @rCreatedUserId THEN CONVERT(bit, 1) ELSE IsUpload END AS IsUpload,
            CASE WHEN FOL.CreatedUserId = @rCreatedUserId THEN CONVERT(bit, 1) ELSE IsEdit END AS IsEdit,
            CASE WHEN FOL.CreatedUserId = @rCreatedUserId THEN CONVERT(bit, 1) ELSE IsDelete END AS IsDelete
        FROM [sPoliciesForms].[tFolderFile] AS FOL
        INNER JOIN [sPoliciesForms].[tFolderFilePermission] AS PER ON PER.FolderFileId = FOL.Id
        WHERE FOL.OrgId = @rOrgId
        AND FOL.Id = @rPerentFolderId
        AND FOL.IsForms = @rIsForms
        AND PER.RoleId = @rRoleId
    END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************
** Name:  [sPoliciesForms].[pFolderFileGet]
** Desc:  get Record From FolderFile Table
** Auth:  Savan Vaghela
** Date:  10-April-2017
** Page:  /Pages/Hrm/PoliciesForms/FormsMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    10-April-2017      Savan Vaghela       
************************************************************/
--EXEC [sPoliciesForms].[pFolderFileGetByID] 100100334
CREATE OR ALTER PROCEDURE [sPoliciesForms].[pFolderFileGetByID]
	@rFileFolderId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT
		UFF.Id 
		,UFF.Title
		,ISNULL(UFF.Remark,'') Description
		,CASE When UFF.PerentFolderId=0 THEN 'Root' ELSE  UPF.Title END AS ParentFolder 
		,CASE WHEN UFF.IsFolder=1 THEN 'Folder' ELSE 'File' END AS Type
		,CASE WHEN UFF.IsFolder=1 THEN 1 ELSE 0  END AS TypeId
		,CASE WHEN UFF.IsFolder=1 THEN     [sPoliciesForms].[fFileFolderSizeGet]([sPoliciesForms].[fFolderSizeGet](UFF.Id)) ELSE [sPoliciesForms].[fFileFolderSizeGet](ISNULL(UFF.Size,0))  END AS Size
		,USR.DisplayTitle AS CreatedUser
		,CONVERT(VARCHAR(20), USR.CreatedDateTime, 113) AS CreateDate
		,ISNULL(UFF.ContentType,'')ContentType
		, CASE WHEN UFF.IsForms=1 THEN 'Forms' ELSE 'Policies' END  + [sPoliciesForms].[fFolderPathGet](@rFileFolderId)AS FilePath 
	FROM   
		[sPoliciesForms].[tFolderFile] AS UFF
		LEFT JOIN [sPoliciesForms].[tFolderFile]  AS UPF ON UPF.Id=UFF.PerentFolderId
		LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id=UFF.CreatedUserId
	WHERE UFF.Id=@rFileFolderId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPortal].[pBookDropdownListet]
	 
	 @rOrgGroupId int,
	 @rOrgId smallint
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
 SELECT Id,Title 
 FROM sLibrary.tResourceTypeMaster ORDER BY Title


 SELECT Id,Title 
 FROM sLibrary.tLibraryMaster LM 
 INNER JOIN sLibrary.tAssignOrganization AO ON AO.LibraryId=LM.Id 
  WHERE LM.IsObsolete = 0 AND OrgGroupId=@rOrgGroupId AND AO.OrgId = @rOrgId ORDER BY Title

 
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPortal].[pClassDropdownList]
	 @rBatchId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT ClassId , ClassName , OrderIndex FROM  
( SELECT CAST(sSetup.vBatchClass.ClassId AS NVARCHAR(25)) AS ClassId , 
CAST(sSetup.vBatchClass.ClassName AS NVARCHAR(300)) AS ClassName , 
CAST(sSetup.vBatchClass.OrderIndex AS NVARCHAR(300)) AS OrderIndex 
FROM sSetup.vBatchClass WHERE ClassId = 0  UNION SELECT DISTINCT 
CAST(sSetup.vBatchClass.ClassId AS NVARCHAR(25)) AS ClassId , 
CAST(sSetup.vBatchClass.ClassName AS NVARCHAR(300)) AS ClassName , 
CAST(sSetup.vBatchClass.OrderIndex AS NVARCHAR(300)) AS OrderIndex 
FROM sSetup.vBatchClass WHERE 1 = 1  AND  IsObsolete = 0  AND BatchId=@rBatchId )  AS NewTable  ORDER BY CAST(OrderIndex AS INT ) ASC 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPortal].[pDepositHeadMasterDropDownLists]
@rOrgGroupId smallint


AS
BEGIN
	SELECT Id, Title FROM sFee.tDepositHeadMaster WHERE IsObsolete = 0 AND OrgGroupId =@rOrgGroupId
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPortal].[pFeeBatchDropDownLists]
@rId int

AS
BEGIN
	select Id , Title 
	from sSetup.tBatchMaster where IsObsolete = 0 
	AND IsHistory= 0
   and OrgId =@rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPortal].[pGetLessonPlan]

	  @rStudentId BIGINT
	 ,@rBatchId INT
	 ,@rOrgId INT
	 ,@rFromDate DATETIME = ''
	 ,@rToDate DATETIME = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lTopicId NVARCHAR(MAX)
	
		SELECT  @lTopicId = STUFF((SELECT DISTINCT ',' + CONVERT(NVARCHAR(MAX), ISNULL( TL.TopicId,0))
	           FROM sAcademic.tLessonPlan TL
			   INNER JOIN sStudent.tAcademic TA ON TA.BatchId = TL.BatchId AND TA.DivisionId = TL.DivisionId 
		WHERE TL.BatchId = @rBatchId AND TA.StudentId = @rStudentId  
	           FOR XML PATH('')), 1, 1, '')
		FROM sAcademic.tLessonPlan TL1
		ORDER BY TL1.TopicId


	SELECT DISTINCT 
			 TM.SubjectId
			,SM.Title AS SubjectName
		FROM  sAcademic.tLessonPlan LP 
		INNER JOIN sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId  
		INNER JOIN  sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId  
		WHERE  LP.TopicId IN (SELECT item FROM sCommon.fnSplit(@lTopicId,','))
		AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
        OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')=''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPortal].[pQueryAdd]
	 
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int,
	@rQueryCategoryId int,
	@rId AS bigint,
	@rTitle nvarchar(100),
	@rRemark nvarchar(1000),
	@rIsUserView bit,
	@rIsAssigneeView bit,
	@rStatusId smallint,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rSubjectId int=0,
	@rAssignedToEmployeeId bigint=0,
	@rAssignedToRemark nvarchar(500)='',
	@rIsOfflineEntry bit=0,
	@rFromSourceTypeId smallInt=0,
	@rFromSourceId bigint=0,
	@rTargetResolutionDate datetime=null    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId = 0)
BEGIN
DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQuery', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	DECLARE @lNumber int=0
	SELECT @lNumber=ISNULL(MAX(Number),0)+1 FROM sCommunication.tQuery WHERE OrgGroupBatchId = @rOrgGroupBatchId
	
	
	INSERT INTO sCommunication.tQuery
		(
			OrgGroupId,
			OrgGroupBatchId,
			QueryCategoryId,
			Id,
			Title,
			Number,
			Remark,
			IsUserView,
			IsAssigneeView,
			StatusId,
			CreatedUserId,
			CreatedDateTime,
			SubjectId,
			AssignedToEmployeeId,
			AssignedToRemark,
			IsOfflineEntry,
			FromSourceTypeId,
			FromSourceId,
			TargetResolutionDate
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rQueryCategoryId,
			@lNextNumber,
			@rTitle,
			@lNumber,
			@rRemark,
			@rIsUserView,
			@rIsAssigneeView,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSubjectId,
			@rAssignedToEmployeeId,
			@rAssignedToRemark,
			@rIsOfflineEntry,
			@rFromSourceTypeId,
			@rFromSourceId,
			@rTargetResolutionDate
		)
		--select @lNextNumber,1 as result
		select @lNextNumber,@lNextNumber as result
END
ELSE
BEGIN
		UPDATE sCommunication.tQuery 
		SET IsUserView = @rIsUserView,
		IsAssigneeView=@rIsAssigneeView,
		AssignedToEmployeeId=@rAssignedToEmployeeId,
		AssignedToRemark=@rAssignedToRemark,
		IsOfflineEntry=@rIsOfflineEntry,
		FromSourceTypeId=@rFromSourceTypeId,
		FromSourceId=@rFromSourceId,
		TargetResolutionDate=@rTargetResolutionDate,
		Remark=@rRemark
		
		 WHERE Id = @rId
		select 0,11 as result
END
	
	COMMIT TRANSACTION
	
END TRY

	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPortal].[pStaffDropdownList]
	 
	 @rOrgId int
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
SELECT Id, Title FROM sSetup.tDepartmentMaster WHERE IsObsolete = 0 AND OrgId =  @rOrgId

SELECT Id, Title FROM sHrm.tEmployeeGroupMaster WHERE IsObsolete = 0  

 
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pAccountRemarksGet]
	@rAccountCode [nvarchar](100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		SELECT Remark FROM sAccounting.vExtAccountMaster
			WHERE Code = @rAccountCode
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [sProcurement].[pDeleteStockItem]
-- drop proc [sProcurement].[pDeleteStockItem]
CREATE OR ALTER PROCEDURE [sProcurement].[pDeleteStockItem]	
	@rStockItemId int	
AS

BEGIN

delete sab from [sProcurement].[tStockAdjustmentBatch] as sab
inner join [sProcurement].[tStockAdjustmentDetail] sad On Sad.id=sab.StockAdjustmentDetailId
where sad.StockItemId=@rStockItemId

delete From  [sProcurement].[tStockAdjustmentDetail] where StockItemId=@rStockItemId

delete sib from [sProcurement].[tStockInwardBatch] sib
inner join [sProcurement].[tStockInwardDetail] si on si.Id=sib.StockInwardDetailId
where si.StockItemId=@rStockItemId

delete From [sProcurement].[tStockInwardDetail] where StockItemId=@rStockItemId

delete sib from [sProcurement].[tStockIssueBatch] sib
inner join [sProcurement].[tStockIssueDetail] si on si.id=sib.StockIssueDetailId
where si.StockItemId=@rStockItemId

delete from [sProcurement].[tStockIssueDetail] where StockItemId=@rStockItemId

delete sib from [sProcurement].[tStockTransferBatch] sib
inner join [sProcurement].[tStockTransferDetail] si on si.id=sib.StockTransferDetailId
where si.StockItemId=@rStockItemId

delete from [sProcurement].[tStockTransferDetail] where StockItemId=@rStockItemId

delete from [sProcurement].[tStockInwardRequestDetail] where StockItemId=@rStockItemId
 
delete from [sProcurement].[tStockIssueRequestDetail] where StockItemId=@rStockItemId

delete sib from [sProcurement].[tStockIssueReturnBatch] sib
inner join [sProcurement].[tStockIssueBatch] si on si.id=sib.StockIssueBatchId
inner join [sProcurement].[tStockBatch] sb on sb.id=si.StockBatchId
where sb.StockItemId=@rStockItemId


delete sib from [sProcurement].[tStockResetBatch] sib
inner join [sProcurement].[tStockBatch] sb on sb.id=sib.StockBatchId
where sb.StockItemId=@rStockItemId

delete from [sProcurement].[tStockTransferRequestDetail] where StockItemId=@rStockItemId

delete from [sIp].[tStockItemBin] where StockItemId=@rStockItemId
 
delete from [sIp].[tStockItemPlanning] where StockItemId=@rStockItemId

delete from [sIp].[tWeightedAverageCostLog] where ItemSourceId =@rStockItemId

delete sib from [sProcurement].[tOtherStockBatch] sib
inner join [sProcurement].[tStockBatch] si on si.id=sib.StockBatchId
where si.StockItemId=@rStockItemId

delete from [sProcurement].[tStockBatch] where StockItemId=@rStockItemId


delete from [sIp].[tStockItemPurchaseUom] where StockItemId=@rStockItemId

delete From sIp.tStockItemMaster where id=@rStockItemId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pFirstAidEmoloyeeDetailRemove]
	 @rId bigint,
	 @rFAEId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 
	Delete From sProcurement.tFirstAidEmployeeDetail
	 where (Id=@rId OR @rId=0)
	 AND FirstAidEmployeeId=@rFAEId
	
	
	SELECT 1 AS Result
 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pFirstAidEmoloyeeGet]
	 
	 @rId bigint,
	 @rNumber nvarchar(50)
	 --@rClaimNumber[nvarchar](50),
	 --@rPolicyNumber[nvarchar](50),
	 --@rEmployeeCode[nvarchar](50)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	 --BEGIN
		--	SET @rClaimNumber = sCommon.fSearchStringGet(@rClaimNumber)
		--	SET @rEmployeeCode=sCommon.fSearchStringGet(@rEmployeeCode)
		--	SET @rPolicyNumber=sCommon.fSearchStringGet(@rPolicyNumber)
		--	--SET @rPolicyId=sCommon.fSearchStringGet(@rPolicyId)
		
	 --END
  SELECT 
		 FAE.Id AS FAEId,
		 FAE.Number,
		 FAE.FirstAidId,
		 FAE.Remark AS FAERemark,
		 FAE.IssueDate,
		 FAE.IssueBy,
		 FAE.EmployeeId,
		 EM.FirstName +  ' ' + EM.LastName AS EmployeeName,
		 EM.Code AS EmployeeCode,
		 FAM.Id AS FAMId,
		 FAM.OrganizationDepartmentId AS DepartmentId
	     
	      
	    
      
  FROM 
		sProcurement.tFirstAidEmoloyee FAE
		INNER JOIN sHrm.tEmployeeMaster EM
		ON EM.Id=FAE.EmployeeId
		INNER JOIN sCommon.tFirstAidMaster FAM
		ON FAM.Id=FAE.FirstAidId
		--INNER JOIN sCommon.tOrganizationDepartmentMaster ODM
		--ON ODM.Id=FAM.OrganizationDepartmentId
		
             
  WHERE 
		
      ((FAE.Id = @rId) OR (@rId = 0))
      AND  ((FAE.Number like @rNumber) OR (ISNULL(@rNumber,'') = '')) 
	  AND ISNULL(EM.IsOtherUser,0) = 0 
      --OR (@rId = 0))
      --AND  ((C.Number like @rClaimNumber) OR (ISNULL(@rClaimNumber,'') = '')) 
      -- AND  ((PM.PolicyNumber like @rPolicyNumber) OR (ISNULL(@rPolicyNumber,'') = '')) 
      --AND((EM.Code like @rEmployeeCode) OR (EM2.Code like @rEmployeeCode) OR (ISNULL(@rEmployeeCode,'')=''))
    
  
		
END


 --CONVERT(INT,PM.OriginalPremium) AS OriginalPremium,

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pFirstAidEmployeeDetailAdd]
	
	@rId bigint,
	@rFirstAidEmployeeId bigint,
	@rStockItemId int,
	@rIssuedQuantity decimal(12,2),
	@rDetailRemark nvarchar(300),
	@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		--BEGIN TRY	
  -- BEGIN TRANSACTION

    IF(@rId = 0)
    BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tFirstAidEmployeeDetail', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sProcurement.tFirstAidEmployeeDetail
		(
			Id,
			FirstAidEmployeeId,
			StockItemId,
			IssuedQuantity,
			Remark
		)
	VALUES
		(
			@lNextNumber,
			@rFirstAidEmployeeId,
			@rStockItemId,
			@rIssuedQuantity,
			@rDetailRemark
		)	
	END
	 ELSE
	 BEGIN
	  SET @lNextNumber = @rId 
	  UPDATE  sProcurement.tFirstAidEmployeeDetail
	   SET	
	        FirstAidEmployeeId=@rFirstAidEmployeeId,
	        StockItemId=@rStockItemId,
	        IssuedQuantity=@rIssuedQuantity,
	        Remark=@rDetailRemark
	     
	           	    
	    WHERE Id = @rId
	  END 
	SELECT @lNextNumber AS Result
  
	 -- COMMIT TRANSACTION
  --       END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pFirstAidInspectionDetailAdd]
	
	@rId bigint,
	@rFirstAidInspectionId bigint,
	@rFirstAidId int,
	@rIsWellMaintained bit,
	@rDetailRemark nvarchar(300),
	@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		--BEGIN TRY	
  -- BEGIN TRANSACTION

    IF(@rId = 0)
    BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tFirstAidInspectionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sProcurement.tFirstAidInspectionDetail
		(
			Id,
			FirstAidInspectionId,
			FirstAidId,
			IsWellMaintained,
			Remark
		)
	VALUES
		(
			@lNextNumber,
			@rFirstAidInspectionId,
			@rFirstAidId,
			@rIsWellMaintained,
			@rDetailRemark
		)	
	END
	 ELSE
	 BEGIN
	  SET @lNextNumber = @rId 
	  UPDATE  sProcurement.tFirstAidInspectionDetail
	   SET	
	        FirstAidInspectionId=@rFirstAidInspectionId,
	        FirstAidId=@rFirstAidId,
	        IsWellMaintained=@rIsWellMaintained,
	        Remark=@rDetailRemark
	     
	           	    
	    WHERE Id = @rId
	  END 
	SELECT @lNextNumber AS Result
  
	 -- COMMIT TRANSACTION
  --       END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pFirstAidInspectionDetailGet]
		
	
	@rFAIId bigint,
	@rStoreLocationId int,
	@rOrgId int
 			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

	  SELECT 
		FAM.Code AS FirstAidCode,
		FAM.Title AS FirstAidTitle,
		FAM.Id AS FirstAidId,
		ISNULL(FAID.Id,'')AS FAIDId,
		ISNULL(FAID.FirstAidInspectionId,'')AS FAIId,
		ISNULL(FAID.IsWellMaintained,0)AS IsWellMaintained,
		ISNULL(FAID.Remark,'')AS Remark
		
	  
	  
	  FROM 
			sCommon.tFirstAidMaster FAM
			LEFT JOIN sProcurement.tFirstAidInspectionDetail FAID ON FAM.Id=FAID.FirstAidId
				AND FAID.FirstAidInspectionId=@rFAIId
				
	  WHERE
			(FAM.IsObsolete=0)
			AND (FAM.StoreLocationId=@rStoreLocationId)
			AND (FAM.OrgId=@rOrgId)
	 ORDER BY FAM.Title ASC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pFirstAidInspectionDetailRemove]
	 @rId bigint,
	 @rFAIId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 
	Delete From sProcurement.tFirstAidInspectionDetail
	 where (Id=@rId OR @rId=0)
	 AND FirstAidInspectionId=@rFAIId
	
	
	SELECT 1 AS Result
 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pFirstAidInspectionGet]
	 
	 @rId bigint,
	 @rNumber nvarchar(50)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

  SELECT 
		 FAI.Id AS FAIId,
		 FAI.Number,
		 FAI.Remark AS FAIRemark,
		 FAI.InspectionDate,
		 FAI.EmployeeId,
		 EM.FirstName +  ' ' + EM.LastName AS EmployeeName,
		 EM.Code AS EmployeeCode

  FROM 
		sProcurement.tFirstAidInspection FAI
		INNER JOIN sHrm.tEmployeeMaster EM
		ON EM.Id=FAI.EmployeeId
     
  WHERE 
		
      ((FAI.Id = @rId)  OR (@rId = 0))
 	   AND  ((FAI.Number like @rNumber) OR (ISNULL(@rNumber,'') = '')) 
	   AND ISNULL(EM.IsOtherUser,0) = 0 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteAdd]
	@rOrgGroupId [int],
	@rPurchaseOrderId [bigint],
	@rReceivedByName [nvarchar](100),
	@rDeliveryOrderNumber [nvarchar](50),
	@rDeliveryOrderDate [date],
	@rAmount [decimal](22, 6),
	@rPackagingCharge [decimal](22, 6),
	@rRoundedNetAmount [decimal](22, 6),
	@rRemark [nvarchar](300),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rStoreLocationId [int],
	@rNumber Nvarchar(20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tGoodsReceiptNote', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	--DECLARE @loNextNumber nVarchar(20)
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 28,@rStoreLocationId = @rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
	----SELECT @loNextNumber
	

	--IF (@loNextNumber IS NULL)
	--BEGIN
	--	--RAISERROR('5000', 15, 106) --error, severity, state -300
	--   SELECT Result = -5000,GRNNumber = 0
		
	--	RETURN
	--END
	
	SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tGoodsReceiptNote WHERE StoreLocationId = @rStoreLocationId
	SET @rNumber = @rNumber + 1
	
	INSERT INTO sProcurement.tGoodsReceiptNote
		(
			Id,
			PurchaseOrderId,
			Number,
			ReceivedByName,
			DeliveryOrderNumber,
			DeliveryOrderDate,
			Amount,
			PackagingCharge,
			RoundedNetAmount,
			Remark,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StoreLocationId,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rPurchaseOrderId,
			@rNumber,
			@rReceivedByName,
			@rDeliveryOrderNumber,
			@rDeliveryOrderDate,
			@rAmount,
			@rPackagingCharge,
			@rRoundedNetAmount,
			@rRemark,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rStoreLocationId,
			@rOrgGroupId
		)
			SELECT Result = @lNextNumber, GRNNumber = @rNumber
			
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteBatchAdd]
	@rOrgGroupId [int],
	@rBatchDetailXml [nvarchar](max),
	@rGoodsReceiptNoteDetailId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--BEGIN TRY
--BEGIN TRANSACTION
	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tGoodsReceiptNoteBatch', 0, 1, 1,@outNextNumber = @lNextNumber output


	DECLARE @lIntErrorCode INT,   
	@lIntDoc INT
				
	EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rBatchDetailXml  
	
	
	CREATE TABLE #tBatchDetail 
	 (  
		Id INT,
		GoodsReceiptNoteDetailId INT,
		Number NVARCHAR(200),
		ExpiryDate DATE,
		ReceiptQuantity DECIMAL(12, 2),
		ReceiptBonusQuantity DECIMAL(12, 2),
		UpdatedUserId BIGINT,
		ReturnQuantity  DECIMAL(26, 2),
		IsObsolete BIT
	 )
	 
	 INSERT INTO #tBatchDetail  
	 (  
		Id,
		GoodsReceiptNoteDetailId,
		Number,
		ExpiryDate,
		ReceiptQuantity,
		ReceiptBonusQuantity,
		UpdatedUserId,
		ReturnQuantity,
		IsObsolete
	 )
	 SELECT 
		Id,
		GoodsReceiptNoteDetailId,
		Number,
		ExpiryDate,
		ReceiptQuantity,
		ReceiptBonusQuantity,
		UpdatedUserId,
		0,
		IsObsolete
		FROM OPENXML (@lIntDoc, '/GoodsReceiptNoteDetailsXmlFormat/GoodsReceiptNoteBatchXml', 1)  
			WITH  
			(  
			    Id INT,
				GoodsReceiptNoteDetailId INT,
				Number NVARCHAR(200),
				ExpiryDate DATE,
				ReceiptQuantity DECIMAL(12, 2),
				ReceiptBonusQuantity DECIMAL(12, 2),
				UpdatedUserId BIGINT,
				ReturnQuantity  DECIMAL(26, 2),
				IsObsolete BIT
			) 
		 
	
	DECLARE @lCurrentNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tGoodsReceiptNoteBatch',  1,  1,  1,@outNextNumber = @lCurrentNumber output
	SET @lCurrentNumber = @lCurrentNumber + 1
	
		INSERT INTO sProcurement.tGoodsReceiptNoteBatch
		(
			Id,
			GoodsReceiptNoteDetailId,
			Number,
			ExpiryDate,
			ReceiptQuantity,
			ReceiptBonusQuantity,
			UpdatedUserId,
			ReturnedQuantity,
			IsObsolete,
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT 	
			@lCurrentNumber + Id,
	        @rGoodsReceiptNoteDetailId,
	        CASE WHEN Number = '' THEN NULL ELSE Number END,
			CASE WHEN ExpiryDate = '1/1/0001' THEN NULL ELSE ExpiryDate END,
			ReceiptQuantity,
			ReceiptBonusQuantity,
			UpdatedUserId,
			0,
			IsObsolete,
			sCommon.fgetDate(),
			@rOrgGroupId
			FROM #tBatchDetail
	
	SELECT @lCurrentNumber = MAX(Id) + @lCurrentNumber FROM #tBatchDetail
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tGoodsReceiptNoteBatch', @rCurrentNumber = @lCurrentNumber	
	
	--COMMIT TRANSACTION
	
	
	SELECT Id FROM sProcurement.tGoodsReceiptNoteBatch WHERE GoodsReceiptNoteDetailId = @rGoodsReceiptNoteDetailId
	--END TRY
	--BEGIN CATCH
	--ROLLBACK TRANSACTION
	--SELECT ERROR_MESSAGE()
	--SELECT  -1 AS Id
	--END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteBatchGet]
	@rOrgGroupId [int] ,
	@rId [bigint] = 0,
	@rGoodsReceiptNoteDetailId [bigint] = 0,
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0,
	@rIsGReN [bit] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT GRNB.Id AS BatchId,
			GRNB.GoodsReceiptNoteDetailId,
			GRNB.Number AS BatchNumber, 
			GRNB.Expirydate AS ExpiryDate,
			GRN.StoreLocationId,
			POD.ItemSourceId AS StockItemId,
			SIM.IsBatchWiseTracking,
			CASE WHEN @rIsGReN = 0 THEN
				CASE WHEN SIM.IsBatchWiseTracking = 1 THEN GRNB.ReceiptQuantity
				ELSE
				GRND.ReceiptQuantity
				END
			ELSE 
				CASE WHEN SIM.IsBatchWiseTracking = 1 THEN ((GRNB.ReceiptQuantity + GRNB.ReceiptBonusQuantity) - GRNB.ReturnedQuantity)
					ELSE
					GRND.ReceiptQuantity
					END
			END AS ReceiptQuantity,
			CASE WHEN SIM.IsBatchWiseTracking = 1 THEN GRNB.ReceiptBonusQuantity
			ELSE
			GRND.ReceiptBonusQuantity
			END AS ReceiptBonusQuantity,
			-- START Modified BY Rajendra ON 28/Jan/2010 Issue Number: HIMS-1908 
			--'1' AS UOM,
			--'1' AS ConversionFactor,
			ESIPU.Title AS UOM,
			SIPUOM.ConversionFactor,
			ISNULL((SELECT SUM(AvailableQuantity) FROM sProcurement.tStockBatch SB 
				WHERE SB.StoreLocationId = @rStoreLocationId AND SB.StockItemId = @rStockItemId AND GRNB.Number = SB.Number AND GRNB.ExpiryDate = SB.ExpiryDate), 0) AvailableQuantity
				
			
		   -- END Modified BY Rajendra ON 28/Jan/2010 Issue Number: HIMS-1908 			
	   FROM sProcurement.tGoodsReceiptNoteBatch GRNB
		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND					
			ON GRNB.GoodsReceiptNoteDetailId = GRND.Id			
		INNER JOIN sProcurement.tGoodsReceiptNote GRN
			ON GRND.GoodsReceiptNoteId = GRN.Id
		-- START Modified BY Rajendra ON 28/Jan/2010 Issue Number: HIMS-1908
		INNER JOIN sProcurement.tPurchaseOrderDetail POD 
			ON POD.Id = GRND.PurchaseOrderDetailId 
		INNER JOIN sIp.tStockItemPurchaseUom SIPUOM 
			ON SIPUOM.Id = POD.StockItemPurchaseUomId
		INNER JOIN sIp.vExtStockItemPurchaseUom ESIPU 
			ON  ESIPU.Id = POD.StockItemPurchaseUomId
			INNER JOIN sIp.tStockItemMaster SIM ON
			SIM.Id = POD.ItemSourceId
		
		-- END Modified BY Rajendra ON 28/Jan/2010 Issue Number: HIMS-1908 			
	  WHERE ((GRNB.Id = @rId) OR (@rId = 0)) AND
			((GRNB.GoodsReceiptNoteDetailId = @rGoodsReceiptNoteDetailId) OR (@rGoodsReceiptNoteDetailId = 0))
			AND GRNB.OrgGroupId = @rOrgGroupId 
			
					 
			
			END
--BEGIN
--	 SELECT Id,
--			GoodsReceiptNoteDetailId,
--			Number,
--			ExpiryDate,
--			ReceiptQuantity,
--			ReceiptBonusQuantity,
--			AvailableQuantity,
--			IsObsolete,
--			CreatedUserId,
--			CreatedDateTime,
--			UpdatedUserId,
--			UpdatedDateTime
--	   FROM sProcurement.tGoodsReceiptNoteBatch
--	  WHERE ((Id = @rId) OR (@rId = 0))
--END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteBatchRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tGoodsReceiptNoteBatch
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteDetailAdd]
	@rOrgGroupId [int],
	@rGoodsReceiptNoteId [bigint],
	@rPurchaseOrderDetailId [bigint],
	@rReceiptQuantity [decimal](12, 2),
	@rReceiptBonusQuantity [decimal](12, 2),
	@rNetUnitPrice [decimal](22, 6),
	@rTaxGroupId [int],
	@rTaxRate [decimal](5, 2),
	@rTaxAmount [decimal](22, 6),
	@rOtherTaxAmount [decimal](22, 6),
	@rAddOnCharges [decimal](22, 6) = 0,
	@rDiscountAmount [decimal](22, 6),
	@rDiscountPercentage [decimal](5, 2),
	@rIsObsolete [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
IF @rTaxGroupId = 0
SET @rTaxGroupId = NULL
BEGIN
--BEGIN TRY
--BEGIN TRANSACTION
	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tGoodsReceiptNoteDetail', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sProcurement.tGoodsReceiptNoteDetail
		(
			Id,
			GoodsReceiptNoteId,
			PurchaseOrderDetailId,
			ReceiptQuantity,
			ReceiptBonusQuantity,
			NetUnitPrice,
			TaxGroupId,
			TaxRate,
			TaxAmount,
			OtherTaxAmount,
			DiscountAmount,
			DiscountPercentage,
			AddOnCharges,
			IsObsolete,
			InvoicedQuantity,
			DraftInvoicedQuantity,
			OrgGroupId
			
		)
	VALUES 
	(	
		@lNextNumber,
		@rGoodsReceiptNoteId,
		@rPurchaseOrderDetailId,
		@rReceiptQuantity,
		@rReceiptBonusQuantity,
		@rNetUnitPrice,
		@rTaxGroupId,
		@rTaxRate,
		@rTaxAmount,
		@rOtherTaxAmount,
		@rDiscountAmount,
		@rDiscountPercentage,
		@rAddOnCharges,
		@rIsObsolete,
		0.0,
		0.0,
		@rOrgGroupId
	
	)
	SELECT Result = @lNextNumber
--COMMIT TRANSACTION
--	END TRY
--	BEGIN CATCH
--	ROLLBACK TRANSACTION
--	SELECT Result = -1
--	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteDetailGet]
	@rOrgGroupId [int] ,
	@rId [bigint] = 0,
	@rGoodsReceiptDetailId [bigint] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
		GRND.Id,
		SIM.Id AS ItemId,
		SIM.Code,
		SIM.Title,
		-- START Modified by Rajendra on 28/Jan/2010 Issue Number: HIMS-1908 
		--'1' AS UOM,
		ESIPU.Code AS UOM,
		-- END Modified by Rajendra on 28/Jan/2010 Issue Number: HIMS-1908 
		SIPUOM.ConversionFactor,
		SIM.IsBatchWiseTracking, 
		POD.OrderQuantity,
		POD.BonusQuantity,
		POD.ReceivedOrderQuantity AS ReceiptQuantity,
		POD.ReceivedBonusQuantity AS ReceiptBonusQuantity,
		GRND.ReceiptQuantity AS CurrentReceiptQuantity,
		GRND.ReceiptBonusQuantity AS CurrentBonusReceiptQuantity,
		(SELECT ((SUM(ReceiptQuantity) + SUM(ReceiptBonusQuantity)) - SUM(ReturnedQuantity)) FROM sProcurement.tGoodsReceiptNoteBatch
		WHERE GoodsReceiptNoteDetailId = GRND.Id) AS BalanceQuantity,
		CASE WHEN GRND.ReceiptQuantity > 0 THEN (GRND.NetUnitPrice / GRND.ReceiptQuantity)
		ELSE GRND.NetUnitPrice END
		 AS UnitPrice,
		SIP.StandardPrice, 
		GRND.NetUnitPrice,
		GRND.DiscountPercentage,
		GRND.DiscountAmount,
		TGM.Code AS TaxCode,
		GRND.TaxAmount,
		GRND.TaxRate,
		GRND.OtherTaxAmount,
		GRND.AddonCharges,
		(GRND.NetUnitPrice - GRND.DiscountAmount + GRND.TaxAmount + GRND.OtherTaxAmount + GRND.AddonCharges) AS NetAmount
		FROM sProcurement.tGoodsReceiptNoteDetail GRND
		
			INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id = GRND.PurchaseOrderDetailId
			INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = POD.ItemSourceId
			INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
			LEFT JOIN sTax.vExtTaxGroupMaster TGM ON TGM.Id = GRND.TaxGroupId
			INNER JOIN sIp.tStockItemPurchaseUom SIPUOM ON SIPUOM.Id = POD.StockItemPurchaseUomId
			-- START Modified by Rajendra on 28/Jan/2010 Issue Number: HIMS-1908 
			INNER JOIN sIp.vExtStockItemPurchaseUom ESIPU ON  ESIPU.Id = POD.StockItemPurchaseUomId
			-- END Modified by Rajendra on 28/Jan/2010 Issue Number: HIMS-1908 
	 WHERE ((GRND.Id = @rGoodsReceiptDetailId OR @rGoodsReceiptDetailId = 0)) AND 
	 (GRND.GoodsReceiptNoteId = @rId OR @rId = 0)
	 AND GRND.OrgGroupId = @rOrgGroupId
	 
END




/****** Object:  StoredProcedure [sProcurement].[pStockItemFreezeVerification]    Script Date: 07/09/2013 16:26:38 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteDetailRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tGoodsReceiptNoteDetail
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteForReturnGet]
	@rOrgGroupId [int] ,
	@rId [bigint] = 0,
	@rGRNNumber [nvarchar](50) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
IF @rGRNNumber = NULL
SET @rGRNNumber = ''
BEGIN
	 SELECT
		 GRN.Id,
		 GRN.Number,
		 PO.Number AS PONumber,
		 GRN.CreatedDateTime,
		 PO.CreatedDateTime AS POCreatedDate,
		 GRN.DeliveryOrderNumber,
		 GRN.DeliveryOrderDate,
		 GRN.Amount AS NetTotal,
		 GRN.PackagingCharge,
		 GRN.RoundedNetAmount,
		 GRN.ReceivedByName,
		 VM.Title AS ContactPersonName,
		 VM.Id AS VendorId,
		 SLM.Id AS StoreLocationId,
		 SLM.Title,
		 SLM1.Title AS OrderingLocation
	
		 
		 FROM sProcurement.tGoodsReceiptNote GRN
	INNER JOIN sProcurement.tPurchaseOrder PO ON PO.Id = GRN.PurchaseOrderId
	INNER JOIN sProcurement.tVendorMaster VM ON VM.Id = PO.VendorId
	INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = GRN.StoreLocationId
	LEFT JOIN sIp.tStoreLocationMaster SLM1 ON SLM1.Id = PO.StoreLocationId	
	 WHERE ((GRN.Id = @rId) OR (@rId = 0))
	AND (GRN.Number LIKE @rGRNNumber OR @rGRNNumber = '')
	AND GRN.OrgGroupId = @rOrgGroupId
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteGet]
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			PurchaseOrderId,
			Number,
			ReceivedByName,
			DeliveryOrderNumber,
			DeliveryOrderDate,
			Amount,
			PackagingCharge,
			RoundedNetAmount,
			Remark,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StoreLocationId
	   FROM sProcurement.tGoodsReceiptNote
	  WHERE ((Id = @rId) OR (@rId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteInvoiceQuantityModify]
	@rOrgId [int],	
	@rGRNInvoiceModifyXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	BEGIN TRY
		DECLARE @loIdoc INT
		EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rGRNInvoiceModifyXml
		
		UPDATE sProcurement.tGoodsReceiptNoteDetail
		SET InvoicedQuantity = GRND.InvoicedQuantity + XmlTable.InvoicedQuantity,
		DraftInvoicedQuantity = (CASE WHEN XmlTable.IsSumDraftInvoiceQuantity = 1 THEN GRND.DraftInvoicedQuantity + ISNULL(XmlTable.DraftInvoicedQuantity, 0)
		ELSE GRND.DraftInvoicedQuantity - ISNULL(XmlTable.DraftInvoicedQuantity, 0) END)
		FROM OPENXML (@loIdoc, '/GRNInvoiceDetailsXmlFormat/GRNInvoiceXml', 1)
				 WITH ( 
						Id INT, 
						InvoicedQuantity DECIMAL(22, 6),
						DraftInvoicedQuantity DECIMAL(22, 6),
						IsSumDraftInvoiceQuantity BIT
					  ) XmlTable
			INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND
				ON	GRND.Id = XmlTable.Id 
				
				SELECT Result = 1
	END TRY
	BEGIN CATCH
		SELECT Result = -1
	END CATCH
			 
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteLatestGet]
	@rOrgGroupId [int],
	@rGoodsReceiptNoteDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

BEGIN TRY
	DECLARE @loIdoc INT
	
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rGoodsReceiptNoteDetailXml
	
	
	SELECT TOP 1
		GRN.Id,
		GRN.Number,
		GRN.CreatedDateTime,
		GRN.CreatedUserId
	FROM sProcurement.tGoodsReceiptNote GRN
	INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND ON
	GRND.GoodsReceiptNoteId = GRN.Id
	WHERE GRND.Id IN 
	
	(
			SELECT  
				GoodsReceiptNoteDetailId
			FROM OPENXML (@loIdoc, '/GoodsReceiptNote/GoodsReceiptNoteDetail', 1)
				WITH ( 
						GoodsReceiptNoteDetailId INT
					  ) 
	)
	AND GRN.OrgGroupId = @rOrgGroupId
		
	ORDER BY GRN.CreatedDateTime DESC
		
		
		END TRY
		BEGIN CATCH
		
		END CATCH
		
		END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tGoodsReceiptNote
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnAdd]
	@rOrgGroupId [int],
	@rGoodsReceiptNoteId [bigint],
	@rNumber [nvarchar](20) OUTPUT,
	@rDeliveryOrderNumber [nvarchar](50),
	@rDeliveryOrderDate [date],
	@rReturnDate [date],
	@rRemark [nvarchar](300),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rGoodsReturnNoteDetailsXml [nvarchar](max),
	@rBatchDetailsXml [nvarchar](max),
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	--DECLARE @loNextNumber nVarchar(20)
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tGoodsReceiptNoteReturn', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 24,@rStoreLocationId = @rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
	--SET @rNumber = @loNextNumber


	--IF (@rNumber IS NULL)
	--BEGIN
	--	RAISERROR('5000', 15, 106)--error, severity, state -300 
	--	RETURN
	--END
SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tGoodsReceiptNoteReturn WHERE StoreLocationId = @rStoreLocationId
SET @rNumber = @rNumber + 1

	INSERT INTO sProcurement.tGoodsReceiptNoteReturn
		(
			Id,
			GoodsReceiptNoteId,
			Number,
			DeliveryOrderNumber,
			DeliveryOrderDate,
			ReturnDate,
			Remark,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId,
			StoreLocationId
		)
	VALUES
		(
			@lNextNumber,
			@rGoodsReceiptNoteId,
			@rNumber,
			@rDeliveryOrderNumber,
			@rDeliveryOrderDate,
			@rReturnDate,
			@rRemark,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rStoreLocationId
		)	
	EXEC sProcurement.pGoodsReceiptNoteReturnDetailAdd @rOrgGroupId = @rOrgGroupId, @rGoodsReceiptNoteReturnId = @lNextNumber, @rGoodsReturnNoteDetailsXml = @rGoodsReturnNoteDetailsXml, @rCreatedUserId = @rCreatedUserId, @rBatchDetailXml = @rBatchDetailsXml
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnBatchAdd]
	@rBatchDetailXml [nvarchar](max),
	@rGoodsReturnNoteDetailId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet 'sProcurement.tGoodsReceiptNoteReturnBatch', 0, 1, 1,@outNextNumber = @lNextNumber output


		DECLARE @lIntErrorCode INT,   
				@lIntDoc INT
				
	EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rBatchDetailXml  
	
	
	CREATE TABLE #tBatchDetail 
	 (  
		Id SMALLINT IDENTITY(1, 1), -- Creation of Id column
		--GoodsReceiptNoteReturnDetailId SMALLINT,
		GoodsReceiptNoteBatchId SMALLINT,
		ReturnQuantity  DECIMAL(26, 2),
		IsObsolete BIT,
	 )
	 
	 INSERT INTO #tBatchDetail  
	 (  
		--GoodsReceiptNoteReturnDetailId,
		GoodsReceiptNoteBatchId,
		ReturnQuantity,
		IsObsolete
	 )
	 SELECT GoodsReceiptNoteBatchId, ReturnQuantity,  0
		FROM OPENXML (@lIntDoc, '/GoodsReturnNoteBatchXmlFormat/GoodsReturnNoteBatchXml', 1)  
			WITH  
			(  
			  --GoodsReceiptNoteReturnDetailId NVARCHAR(200), 
			  GoodsReceiptNoteBatchId NVARCHAR(200),
			  ReturnQuantity NVARCHAR(200),
			  IsObsolete NVARCHAR(200) 
			) 
		 
	
	DECLARE @lCurrentNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet 'sProcurement.tGoodsReceiptNoteReturnBatch',  1,  1,  1,@outNextNumber = @lNextNumber output

		INSERT INTO sProcurement.tGoodsReceiptNoteReturnBatch
		(
			Id,
			GoodsReceiptNoteReturnDetailId,
			GoodsReceiptNoteBatchId,
			ReturnQuantity,
			IsObsolete
		)
	SELECT 	@lCurrentNumber + Id, @rGoodsReturnNoteDetailId, GoodsReceiptNoteBatchId, ReturnQuantity, IsObsolete FROM #tBatchDetail
	
	SELECT @lCurrentNumber = MAX(Id) + @lCurrentNumber FROM #tBatchDetail
	EXECUTE sCommon.pTableRowIdModify @rTableTitle = 'sProcurement.tGoodsReceiptNoteReturnBatch', @rCurrentNumber = @lCurrentNumber	
	--INSERT INTO sProcurement.tGoodsReceiptNoteReturnBatch
	--	(
	--		Id,
	--		GoodsReceiptNoteReturnDetailId,
	--		GoodsReceiptNoteBatchId,
	--		ReturnQuantity,
	--		IsObsolete,
	--		CreatedUserId,
	--		CreatedDateTime,
	--		UpdatedUserId,
	--		UpdatedDateTime
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		@rGoodsReceiptNoteReturnDetailId,
	--		@rGoodsReceiptNoteBatchId,
	--		@rReturnQuantity,
	--		@rIsObsolete,
	--		@rCreatedUserId,
	--		sCommon.fGetDate(),
	--		@rCreatedUserId,
	--		sCommon.fGetDate()
	--	)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnBatchGet]
	@rId [int] = 0,
	@rGoodsReceiptNoteReturnDetailId [int] = 0,
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT GRNRB.Id,
			GRNRB.GoodsReceiptNoteReturnDetailId,
			--GRNB.GoodsReceiptNoteDetailId,
			GRNRB.GoodsReceiptNoteBatchId,
			GRNRB.ReturnQuantity AS Quantity,
			SB.Number AS BatchNumber, 
			SB.Expirydate AS ExpiryDate,	
			SB.AvailableQuantity AS AvailableQuantity,
			GRND.ReceiptQuantity AS CurrentReceiptQuantity,
			--GRND.ReceiptBonusQuantity AS CurrentReceiptBonusQuantity,
			--GRNB.ReturnedQuantity AS Quantity,
			'1' AS UOM,
			'1' AS ConversionFactor
	   FROM sProcurement.tGoodsReceiptNoteReturnBatch GRNRB
		INNER JOIN sProcurement.tGoodsReceiptNoteReturnDetail GRNRD
			ON GRNRD.Id = GRNRB.GoodsReceiptNoteReturnDetailId
		INNER JOIN sProcurement.tGoodsReceiptNoteReturn GRNR
			ON GRNR.Id = GRNRD.GoodsReceiptNoteReturnId
		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND					
			ON GRNRD.GoodsReceiptNoteDetailId = GRND.Id
			
		INNER JOIN sProcurement.tGoodsReceiptNote GRN
			ON GRND.GoodsReceiptNoteId = GRN.Id
		INNER JOIN sProcurement.tStockBatch SB
			ON GRN.StoreLocationId = SB.storelocationid
			
	  WHERE ((GRNRB.Id = @rId) OR (@rId = 0)) AND
			((GRNRB.GoodsReceiptNoteReturnDetailId = @rGoodsReceiptNoteReturnDetailId) OR (@rGoodsReceiptNoteReturnDetailId = 0))-- AND
					--((GRNR.Number = @rNumber) OR (@rNumber = ''))  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnBatchRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tGoodsReceiptNoteReturnBatch
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnDetailAdd]
	@rOrgGroupId [int],
	@rGoodsReceiptNoteReturnId [bigint],
	@rGoodsReturnNoteDetailsXml [nvarchar](max),
	@rCreatedUserId [bigint],
	@rBatchDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lIntErrorCode INT, @lIntDoc INT				
	EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rGoodsReturnNoteDetailsXml  
		
	DECLARE @tGoodsReturnDetail TABLE
	 (  
		Id SMALLINT IDENTITY(1, 1), -- Creation of Id column
		TempId Int,
		GoodsReceiptNoteReturnId Int,
		GoodsReceiptNoteReturnDetailId Int, 
		GoodsReceiptNoteDetailId INT,	
		ReasonId INT,	
		ReturnQuantity  DECIMAL(26, 2),
		IsObsolete BIT,
		IsBatch BIT,
		GoodsReceiptNoteBatchId Int
	 )
	 
	 INSERT INTO @tGoodsReturnDetail
	 (		
		TempId,
		GoodsReceiptNoteDetailId,	
		ReasonId,	
		ReturnQuantity,
		IsObsolete,
		IsBatch,
		GoodsReceiptNoteBatchId
	 )
	 SELECT TempId, GoodsReceiptNoteDetailId, ReasonId, ReturnQuantity,  0, IsBatch, GoodsReceiptNoteBatchId	
	 FROM OPENXML (@lIntDoc, '/Root/GoodsReturnNoteDetails', 1)   
			WITH  
			( 	
			  TempId NVARCHAR(200),	  
			  GoodsReceiptNoteDetailId NVARCHAR(200), 	
			  ReasonId 	NVARCHAR(200), 		  
			  ReturnQuantity NVARCHAR(200),
			  IsObsolete NVARCHAR(200),
			  IsBatch NVARCHAR(200),
			  GoodsReceiptNoteBatchId NVARCHAR(200)
			)XmlTable	
	
	DECLARE @lNextNumberReturnDetail BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tGoodsReceiptNoteReturnDetail',  1,  1,  1,@outNextNumber = @lNextNumberReturnDetail output

	INSERT INTO sProcurement.tGoodsReceiptNoteReturnDetail
		(
			Id,
			GoodsReceiptNoteReturnId,
			GoodsReceiptNoteDetailId,
			ReasonId,		
			ReturnQuantity,
			IsObsolete,
			IsDraftCreated,
			OrgGroupId
		)
	SELECT 	@lNextNumberReturnDetail + Id, @rGoodsReceiptNoteReturnId, GoodsReceiptNoteDetailId, ReasonId, ReturnQuantity, IsObsolete, 0,@rOrgGroupId FROM @tGoodsReturnDetail
	
	UPDATE @tGoodsReturnDetail SET GoodsReceiptNoteReturnDetailId = @lNextNumberReturnDetail + Id 

	SELECT @lNextNumberReturnDetail = MAX(Id) + @lNextNumberReturnDetail FROM @tGoodsReturnDetail
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tGoodsReceiptNoteReturnDetail', @rCurrentNumber = @lNextNumberReturnDetail 
	
	--To Insert in Batch Table
	DECLARE @tBatch TABLE
	(
		Id	smallInt IDENTITY(1, 1), --IDENTITY(0, 1), 
		GoodsReceiptNoteReturnId        Int,
		GoodsReceiptNoteReturnDetailId	Int,
		GoodsReceiptNoteBatchId			Int,
		ReturnQuantity					Decimal(12,2),
		IsObsolete						bit,
		TempId							Int--,
		--Number							Nvarchar(200)
	)
	
	INSERT INTO @tBatch  
			(			 
			GoodsReceiptNoteReturnDetailId,	
			GoodsReceiptNoteBatchId,
			ReturnQuantity,	
			TempId--,
			--Number
			)
	SELECT					
			1, 
			GoodsReceiptNoteBatchId,	
			ReturnQuantity,
			Id--,  --i.e. TempId
			--Number
	
	
	FROM OPENXML (@lIntDoc, '/Root/GoodsReturnNoteDetails/GoodsReturnNoteBatchDetails', 1)  
		WITH  
		(  
			GoodsReceiptNoteBatchId 	Nvarchar(200)	'@GoodsReceiptNoteBatchId',			
			ReturnQuantity 				Nvarchar(200)	'@ReturnQuantity',			
			Id							Nvarchar(200)	'@Id'--,
			--Number						Nvarchar(200)	'@Number'
		) XmlTable
	
	DECLARE @lNextNumberBatch BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tGoodsReceiptNoteReturnBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output	

	INSERT INTO sProcurement.tGoodsReceiptNoteReturnBatch
		(
			Id,
			GoodsReceiptNoteReturnDetailId,
			GoodsReceiptNoteBatchId,
			ReturnQuantity,
			IsObsolete,
			OrgGroupId
		)
	SELECT 		 
				@lNextNumberBatch + B.Id, 				
				GRD.GoodsReceiptNoteReturnDetailId, 
				B.GoodsReceiptNoteBatchId,
				B.ReturnQuantity,				
				0,
				@rOrgGroupId
				
	FROM		@tGoodsReturnDetail GRD 
				INNER JOIN @tBatch B 
				ON B.TempId = GRD.TempId --i.e. Id = TempId
			
	SELECT @lNextNumberBatch = MAX(Id) + @lNextNumberBatch FROM @tBatch
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tGoodsReceiptNoteReturnBatch', @rCurrentNumber = @lNextNumberBatch 

	--SELECT GRD.ReturnQuantity FROM @tGoodsReturnDetail GRD
	----To Upadte sProcurement.tGoodsReceiptNoteBatch Start	
	--UPDATE sProcurement.tGoodsReceiptNoteBatch 
	--			SET	sProcurement.tGoodsReceiptNoteBatch.ReturnedQuantity = GRD.ReturnQuantity + sProcurement.tGoodsReceiptNoteBatch.ReturnedQuantity, 
	--			sProcurement.tGoodsReceiptNoteBatch .UpdatedUserId =  @rCreatedUserId,
	--			sProcurement.tGoodsReceiptNoteBatch .UpdatedDateTime = sCommon.fGetDate()		
	--FROM @tGoodsReturnDetail GRD
	--	--INNER JOIN @tBatch B
	--	--ON GRD.TempId = B.TempId	 
	--	WHERE sProcurement.tGoodsReceiptNoteBatch.Id = GRD.GoodsReceiptNoteBatchId
	--		AND ISNULL(GRD.IsBatch, 0) = 0 
	
	 
	--SELECT B.ReturnQuantity FROM @tBatch B
		
	UPDATE sProcurement.tGoodsReceiptNoteBatch 
				SET	sProcurement.tGoodsReceiptNoteBatch.ReturnedQuantity =  B.ReturnQuantity + sProcurement.tGoodsReceiptNoteBatch.ReturnedQuantity, 
				sProcurement.tGoodsReceiptNoteBatch .UpdatedUserId =  @rCreatedUserId,
				sProcurement.tGoodsReceiptNoteBatch .UpdatedDateTime = sCommon.fGetDate()		
	FROM @tGoodsReturnDetail GRD
		INNER JOIN @tBatch B
		ON GRD.TempId = B.TempId	 
		WHERE sProcurement.tGoodsReceiptNoteBatch.Id = B.GoodsReceiptNoteBatchId

	--To Upadte sProcurement.tGoodsReceiptNoteBatch End
	
	--select * from 	sProcurement.tGoodsReceiptNoteBatch where isnull(number, '') = ''
	--select * from     sProcurement.tGoodsReceiptNote
	--select * from 	sProcurement.tGoodsReceiptNoteDetail where isnull(number, '') = ''
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnDetailGet]
	@rId [int] = 0,
	@rGoodsReceiptNoteReturnId [int] = 0,
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT GRNRD.Id,
			GRNRD.GoodsReceiptNoteReturnId,
			GRNRD.GoodsReceiptNoteDetailId,
			GRNRD.ReturnQuantity,
			GRNRD.ReasonId,
			SIM.Id AS ItemId,
			SIM.Code AS ItemCode,
			SIM.Title AS ItemName,
			1.0 AS UOM,
			SIPUOM.ConversionFactor,			
			GRND.ReceiptQuantity,
			IsDraftCreated,
			(POD.OrderQuantity - GRND.ReceiptQuantity) AS BalanceQuantity,
			--netUnitPrice = GoodsReceiptDetailsData.UnitPrice * GoodsReceiptDetailsData.ReturnedQuantity;
			--discountAmount = GoodsReceiptDetailsData.ReturnedQuantity * (GoodsReceiptDetailsData.DiscountPercentage / 100);
			--taxAmount = (netUnitPrice - discountAmount) * GoodsReceiptDetailsData.TaxRate;
			--otherTaxAmount = GoodsReceiptDetailsData.ReturnedQuantity * GoodsReceiptDetailsData.OtherTaxAmount;
			--netAmount = netUnitPrice + discountAmount + taxAmount + otherTaxAmount;
			--netTotal
			(GRND.NetUnitPrice / POD.OrderQuantity) AS UnitPrice,
			((GRND.NetUnitPrice / POD.OrderQuantity) * GRNRD.ReturnQuantity) AS NetUnitPrice,
			((GRND.NetUnitPrice / POD.OrderQuantity) * GRNRD.ReturnQuantity) AS NetAmount,
			TGM.Code AS TaxCode,
			(((GRND.NetUnitPrice / POD.OrderQuantity) * GRNRD.ReturnQuantity) - GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100)) * GRND.TaxRate AS TaxAmount,
			GRNRD.ReturnQuantity * GRND.OtherTaxAmount AS OtherTaxAmount,
			GRND.DiscountPercentage,
			GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100) AS  DiscountAmount,
			((GRND.NetUnitPrice / POD.OrderQuantity) * GRNRD.ReturnQuantity) + (GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100)) + (	(((GRND.NetUnitPrice / POD.OrderQuantity) * GRNRD.ReturnQuantity) - GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100)) * GRND.TaxRate ) + (GRNRD.ReturnQuantity * GRND.OtherTaxAmount)						AS NetAmount
			--SUM(((GRND.NetUnitPrice / POD.OrderQuantity) * GRNRD.ReturnQuantity)) AS NetTotal

	   FROM sProcurement.tGoodsReceiptNoteReturnDetail GRNRD
	    INNER JOIN sProcurement.tGoodsReceiptNoteReturn GRNR
			ON GRNRD.GoodsReceiptNoteReturnId = GRNR.Id
		INNER JOIN sProcurement.tGoodsReceiptNoteDetail  GRND
			ON GRNRD.GoodsReceiptNoteDetailId = GRND.Id
		INNER JOIN sProcurement.tPurchaseOrderDetail POD 
			ON POD.Id = GRND.PurchaseOrderDetailId
		INNER JOIN sIp.tStockItemMaster SIM 
			ON SIM.Id = POD.ItemSourceId
		INNER JOIN sTax.vExtTaxGroupMaster TGM 
			ON TGM.Id = GRND.TaxGroupId
		INNER JOIN sIp.tStockItemPurchaseUom SIPUOM 
			ON SIPUOM.Id = POD.StockItemPurchaseUomId
		
	  WHERE ((GRNRD.Id = @rId) OR (@rId = 0)) AND
				((GRNR.Id = @rGoodsReceiptNoteReturnId) OR (@rGoodsReceiptNoteReturnId = 0)) AND
					((GRNR.Number = @rNumber) OR (@rNumber = ''))  
					
	 --EXECUTE sProcurement.pGoodsReceiptNoteReturnBatchGet @rID = 0, @rGoodsReceiptNoteReturnDetailId = GRNRD.Id, @rNumber = ''
END

--SELECT 
--		GRND.Id,
--		SIM.Code,
--		SIM.Title,
--		1.0 AS UOM,
--		SIPUOM.ConversionFactor,
--		SIM.IsBatchWiseTracking, 
--		POD.OrderQuantity,
--		GRND.ReceiptQuantity,
--		(POD.OrderQuantity - GRND.ReceiptQuantity) AS BalanceQuantity,
--		(GRND.NetUnitPrice / POD.OrderQuantity) AS UnitPrice,
--		SIM.StandardPrice, 
--		GRND.NetUnitPrice,
--		GRND.DiscountPercentage,
--		GRND.DiscountAmount,
--		TGM.Code AS TaxCode,
--		GRND.TaxAmount,
--		GRND.OtherTaxAmount,
--		(GRND.NetUnitPrice - GRND.DiscountAmount + GRND.TaxAmount + GRND.OtherTaxAmount) AS NetAmount
--		FROM sProcurement.tGoodsReceiptNoteDetail GRND
--			INNER JOIN sProcurement.tPurchaseOrderDetail POD ON POD.Id = GRND.PurchaseOrderDetailId
--			INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = POD.ItemSourceId
--			INNER JOIN sTax.vExtTaxGroupMaster TGM ON TGM.Id = GRND.TaxGroupId
--			INNER JOIN sIp.tStockItemPurchaseUom SIPUOM ON SIPUOM.Id = POD.StockItemPurchaseUomId
--	 WHERE ((GRND.Id = @rGoodsReceiptDetailId OR @rGoodsReceiptDetailId = 0)) AND 
--	 (GRND.GoodsReceiptNoteId = @rId OR @rId = 0)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnDetailRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tGoodsReceiptNoteReturnDetail
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnForAccountsPayableModify]
    @rOrgGroupId int = 0,
	@rUpdatedUserId [smallint],
	@rGoodsReturnNoteDetailsUpdateXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 DECLARE @lIntErrorCode INT, @lIntDoc INT				
	 EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rGoodsReturnNoteDetailsUpdateXml

	  
	  UPDATE sProcurement.tGoodsReceiptNoteReturnDetail
			SET	sProcurement.tGoodsReceiptNoteReturnDetail.IsDraftCreated = XmlTable.IsDraftCreated
			FROM OPENXML (@lIntDoc, '/GoodsReturnNote/GoodsReturnNoteDetails', 1)
				 WITH ( 
						 Id INT, 
						 IsDraftCreated BIT		
					  ) XmlTable
	WHERE sProcurement.tGoodsReceiptNoteReturnDetail.Id = XmlTable.Id 		  
	SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnGet]
	@rOrgGroupId [int] ,
	@rId [bigint] = 0,
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	--To Get Header Details
	 SELECT GRNR.Id,
			GRNR.GoodsReceiptNoteId,
			GRNR.Number,
			GRNR.DeliveryOrderNumber,
			GRNR.DeliveryOrderDate,
			GRNR.ReturnDate,
			GRNR.Remark,
			GRNR.IsObsolete,
			GRNR.CreatedUserId,
			GRNR.CreatedDateTime,
			GRNR.UpdatedUserId,
			GRNR.UpdatedDateTime,
			GRN.Number AS GoodsReceiptNoteNumber,
			SLM.Id AS StoreLocationId,
			SLM.Title AS StoreLocation,
			VM.Id AS VendorId,
			VM.Title AS VendorName,
			GRN.CreatedDateTime AS ReceiptDate, 
			GRNR.CreatedUserId,			
			PO.CreatedDateTime AS POCreatedDate
 
						
	   FROM sProcurement.tGoodsReceiptNoteReturn GRNR
		INNER JOIN sProcurement.tGoodsReceiptNote GRN 
			ON GRNR.GoodsReceiptNoteId = GRN.Id
		INNER JOIN sProcurement.tPurchaseOrder PO 
			ON PO.Id = GRN.PurchaseOrderId
		INNER JOIN sProcurement.tVendorMaster VM 
			ON VM.Id = PO.VendorId
		INNER JOIN sIp.tStoreLocationMaster SLM 
			ON SLM.Id = GRN.StoreLocationId

			 WHERE ((GRNR.Id = @rId) OR (@rId = 0)) AND
				 ((GRNR.Number = @rNumber) OR (@rNumber = ''))
				 AND GRNR.OrgGroupId =@rOrgGroupId

	--To Get Details
	--DECLARE @lNetUnitPrice DECIMAL(22, 6)
	 SELECT 
			GRNRD.Id AS GoodsReturnNoteDetailId, --For Batch details
			SIM.IsBatchWiseTracking,
			GRNRD.GoodsReceiptNoteReturnId,
			GRNRD.GoodsReceiptNoteDetailId,
			GRNRD.ReturnQuantity,
			GRNRD.ReasonId,
			SIM.Id AS ItemId,
			SIM.Code AS ItemCode,
			SIM.Title AS ItemName,
			SU.Title AS UOM,
			SIPUOM.ConversionFactor,			
			GRND.ReceiptQuantity,
			(SELECT ((SUM(ReceiptQuantity) + SUM(ReceiptBonusQuantity)) - SUM(ReturnedQuantity)) FROM sProcurement.tGoodsReceiptNoteBatch
				WHERE GoodsReceiptNoteDetailId = GRND.Id) AS BalanceQuantity,			
		
			CASE WHEN GRND.ReceiptQuantity > 0 THEN (GRND.NetUnitPrice / GRND.ReceiptQuantity)
			ELSE GRND.NetUnitPrice END
			AS UnitPrice,
						
			--((GRND.NetUnitPrice / POD.OrderQuantity) * GRNRD.ReturnQuantity) AS NetUnitPrice,
			
			
		    CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRD.ReturnQuantity) END
			AS NetUnitPrice,
			
			GRND.DiscountPercentage,
			
			--Return Qnt. * UP * D%					
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			* (GRND.DiscountPercentage/100)
			AS  DiscountAmount,
			
			
			
			--((GRNRD.ReturnQuantity * 
			--(CASE WHEN GRND.ReceiptQuantity > 0   THEN (GRND.NetUnitPrice / GRND.ReceiptQuantity)
			--ELSE GRND.NetUnitPrice END) )* (GRND.DiscountPercentage/100)) AS  DiscountAmount,
						
			TGM.Code AS TaxCode,
			GRND.TaxRate,
			
			CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.AddOnCharges * GRNRD.ReturnQuantity) END 
			AS AddOnCharges,
			
			--(netUnitPrice - discountAmount) * (TaxRate / 100);
			--NetUnitPrice
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRD.ReturnQuantity) END
			- --Disc. Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			* (GRND.DiscountPercentage/100)
			)
			* --(TaxRate / 100)
			(GRND.TaxRate/ 100)
			AS TaxAmount,			
					
			
			CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.ReceiptQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			ELSE (GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount) END
			AS OtherTaxAmount,

			 --Amount - Disc. Amount + Tax Amount + Other tax Amount + Add ON
			 --Amount
			 CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRD.ReturnQuantity) END
			 -
			 --Discount Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			* (GRND.DiscountPercentage/100)
			
			 + --Tax Amount
					(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRD.ReturnQuantity) END
			- --Disc. Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			* (GRND.DiscountPercentage/100)
			)
			* --(TaxRate / 100)
			(GRND.TaxRate/ 100)			 
			 + --Other tax Amount
			CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.ReceiptQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			ELSE (GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount) END
			+ --Add ON
			CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.AddOnCharges * GRNRD.ReturnQuantity) END 
			AS NetAmount
			
		
	   FROM sProcurement.tGoodsReceiptNoteReturnDetail GRNRD
	    INNER JOIN sProcurement.tGoodsReceiptNoteReturn GRNR
			ON GRNRD.GoodsReceiptNoteReturnId = GRNR.Id
		INNER JOIN sProcurement.tGoodsReceiptNoteDetail  GRND
			ON GRNRD.GoodsReceiptNoteDetailId = GRND.Id
		--INNER JOIN sProcurement.tGoodsReceiptNoteBatch GRNB
		--	ON GRND.Id = GRNB.GoodsReceiptNoteDetailId
		INNER JOIN sProcurement.tPurchaseOrderDetail POD 
			ON POD.Id = GRND.PurchaseOrderDetailId
		INNER JOIN sIp.tStockItemMaster SIM 
			ON SIM.Id = POD.ItemSourceId
		LEFT JOIN sTax.vExtTaxGroupMaster TGM 
			ON TGM.Id = GRND.TaxGroupId
		INNER JOIN sIp.tStockItemPurchaseUom SIPUOM 
			ON SIPUOM.Id = POD.StockItemPurchaseUomId
		INNER JOIN sFinanceCommon.tStockUomMaster SU
			ON SU.Id = SIPUOM.StockUomId		
		
	  WHERE ((GRNR.Id = @rId) OR (@rId = 0)) AND
				--((GRNR.Id = @rGoodsReceiptNoteReturnId) OR (@rGoodsReceiptNoteReturnId = 0)) AND
					((GRNR.Number = @rNumber) OR (@rNumber = '')) 
					AND GRNR.OrgGroupId = @rOrgGroupId
						  ORDER BY POD.Id ASC

	--To Get Batch Details
	 SELECT GRNRB.Id AS WACStockBatchId, --i.e. Batch Id for GRNRB
			GRNRB.GoodsReceiptNoteReturnDetailId AS GoodsReturnNoteDetailId,
			GRND.Id AS GoodsReceiptNoteDetailId,
			GRNRB.GoodsReceiptNoteBatchId,
			GRNRB.ReturnQuantity AS POQuantity,
			(GRNRB.ReturnQuantity * SIPUOM.ConversionFactor) AS Quantity,
			SB.Number AS BatchNumber, 
			SB.Expirydate AS ExpiryDate,
			ISNULL((SELECT AvailableQuantity FROM sProcurement.tStockBatch SB 
				WHERE SB.StoreLocationId = GRN.StoreLocationId AND SB.StockItemId = POD.ItemSourceId AND GRNB.Number = SB.Number AND GRNB.ExpiryDate = SB.ExpiryDate), 0.00) AvailableQuantity,
			--ISNULL((SELECT SUM(AvailableQuantity) FROM sProcurement.tStockBatch SB 
			--	WHERE SB.StoreLocationId = GRN.StoreLocationId AND SB.StockItemId = POD.ItemSourceId AND GRNB.Number = SB.Number AND GRNB.ExpiryDate = SB.ExpiryDate), 0.00) AvailableQuantity,
			--SB.AvailableQuantity AS AvailableQuantity,
			(CASE WHEN SIM.IsBatchWiseTracking = 1 THEN ((GRNB.ReceiptQuantity + GRNB.ReceiptBonusQuantity) - GRNB.ReturnedQuantity)
			ELSE
			GRND.ReceiptQuantity
			END) AS CurrentReceiptQuantity,
			
			
			--(GRND.ReceiptQuantity + GRND.ReceiptBonusQuantity  - GRNB.ReturnedQuantity) AS CurrentReceiptQuantity,
			--GRND.ReceiptBonusQuantity AS CurrentReceiptBonusQuantity,
			--GRNB.ReturnedQuantity AS Quantity,
			--'1' AS UOM,
			ESIPU.Title AS UOM,
			SIM.Id AS StockItemId,
			--1.00 AS ConversionFactor
			SIPUOM.ConversionFactor
			--GRNRD.Id AS TempGoodsReturnNoteDetailId
			
	   FROM sProcurement.tGoodsReceiptNoteReturnBatch GRNRB
		INNER JOIN sProcurement.tGoodsReceiptNoteReturnDetail GRNRD
			ON GRNRD.Id = GRNRB.GoodsReceiptNoteReturnDetailId
		INNER JOIN sProcurement.tGoodsReceiptNoteReturn GRNR
			ON GRNR.Id = GRNRD.GoodsReceiptNoteReturnId
		INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND					
			ON GRNRD.GoodsReceiptNoteDetailId = GRND.Id			
		INNER JOIN sProcurement.tGoodsReceiptNote GRN
			ON GRND.GoodsReceiptNoteId = GRN.Id
		INNER JOIN sProcurement.tGoodsReceiptNoteBatch GRNB
			ON GRNRB.GoodsReceiptNoteBatchid = GRNB.Id
		INNER JOIN sProcurement.tPurchaseOrderDetail POD
			ON POD.Id = GRND.PurchaseOrderDetailId
		LEFT JOIN sProcurement.tStockBatch SB		
			ON GRN.StoreLocationId = SB.StorelocationId
			AND GRNB.Number = SB.Number
			AND SB.StockItemId = POD.ItemSourceId
		INNER JOIN sIp.tStockItemPurchaseUom SIPUOM 
			ON SIPUOM.Id = POD.StockItemPurchaseUomId
		INNER JOIN sIp.vExtStockItemPurchaseUom ESIPU 
			ON  ESIPU.Id = POD.StockItemPurchaseUomId
		INNER JOIN sIp.tStockItemMaster SIM 
			ON SIM.Id = POD.ItemSourceId	
				
			
	  WHERE ((GRNR.Id = @rId) OR (@rId = 0)) AND
				--SB.StoreLocationId = GRN.StoreLocationId AND 
				--	SB.StockItemId = POD.ItemSourceId AND 
				--		GRNB.Number = SB.Number AND GRNB.ExpiryDate = SB.ExpiryDate AND			
							((GRNR.Number = @rNumber) OR (@rNumber = ''))  
							
								AND GRNR.OrgGroupId = @rOrgGroupId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnModify]
	@rId [int],
	@rGoodsReceiptNoteId [int],
	@rNumber [nvarchar](20),
	@rDeliveryOrderNumber [nvarchar](50),
	@rDeliveryOrderDate [date],
	@rReturnDate [date],
	@rRemark [nvarchar](300),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tGoodsReceiptNoteReturn
		SET 
			GoodsReceiptNoteId = @rGoodsReceiptNoteId,
			Number = @rNumber,
			DeliveryOrderNumber = @rDeliveryOrderNumber,
			DeliveryOrderDate = @rDeliveryOrderDate,
			ReturnDate = @rReturnDate,
			Remark = @rRemark,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pGoodsReceiptNoteReturnRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tGoodsReceiptNoteReturn
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pItemMaintypeCheckForFreeze]
 
 @rItemMainGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	SELECT Count(*) AS Result from sIp.tStockItemMaster SIM 
	INNER JOIN sIp.tItemSubGroupMaster ISB ON ISB.Id=SIM.ItemSubGroupId 
	INNER JOIN sIp.tItemMainGroupMaster IGM ON IGM.Id=ISB.ItemMainGroupId

WHERE IGM.Id=@rItemMainGroupId
	AND SIM.IsObsolete=0
	AND IGM.IsObsolete=0
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pPurchaseOrderAdd]
    @rOrgGroupId int,
	@rParentPurchaseOrderId [bigint] = 0,
	@rRequestedByName [nvarchar](300),
	@rRequestedOrganizationDepartmentId [int],
	@rVendorId [int],
	@rStoreLocationId [int],
	@rPaymentDays [smallint],
	@rStatusId [smallint],
	@rAmount [decimal](22, 6),
	@rDiscountAmount [decimal](22, 6),
	@rDiscountPercentage [decimal](5, 2),
	@rRoundedNetAmount [decimal](22, 6),
	@rRemark [nvarchar](300),
	@rCreatedUserId [bigint],	
	@rShipToStoreLocationId [int],
	@rPurchaseOrderDetailXml [nvarchar](max),	
	@rId [bigint] OUTPUT,
	@rNumber Nvarchar(20) = ''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet  @rOrgGroupId, 'sProcurement.tPurchaseOrder', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	--IF @rStatusId = 42 
	--	BEGIN
	--		DECLARE @loNextNumber nVarchar(20)
	--		EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 32,@rStoreLocationId = @rStoreLocationId , @rNextNumber = @loNextNumber OUTPUT
			
			
	--		IF (@loNextNumber IS NULL)
	--			BEGIN
	--				RAISERROR('5000', 15, 106)
	--				RETURN
	--			END
	--	END
	--ELSE
	--	BEGIN
			
	--		EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId,  @rPrefixFunctionalityId = 1,@rStoreLocationId = @rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
			
			
	--		IF (@loNextNumber IS NULL)
	--			BEGIN
	--				RAISERROR('5000', 15, 106)
	--				RETURN
	--			END
	--	END
	
	SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tPurchaseOrder WHERE StoreLocationId = @rStoreLocationId
	SET @rNumber = @rNumber + 1
	
	INSERT INTO sProcurement.tPurchaseOrder
		(
			Id,
			ParentPurchaseOrderId,
			Number,
			RequestedByName,
			RequestedOrganizationDepartmentId,
			VendorId,
			StoreLocationId,
			PaymentDays,
			StatusId,
			Amount,
			DiscountAmount,
			DiscountPercentage,
			RoundedNetAmount,
			Remark,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ShipToStoreLocationId,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			(CASE WHEN @rParentPurchaseOrderId = 0 THEN NULL ELSE @rParentPurchaseOrderId END),
			@rNumber,
			@rRequestedByName,
			@rRequestedOrganizationDepartmentId,
			@rVendorId,
			@rStoreLocationId,
			@rPaymentDays,
			@rStatusId,
			@rAmount,
			@rDiscountAmount,
			@rDiscountPercentage,
			@rRoundedNetAmount,
			@rRemark,
			0,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			(CASE WHEN @rShipToStoreLocationId = 0 THEN NULL ELSE @rShipToStoreLocationId END),
			@rOrgGroupId
		)
	
	SELECT  @rId = ID FROM sProcurement.tPurchaseOrder WHERE Number = @rNumber
	EXEC [sProcurement].[pPurchaseOrderDetailAdd] @rOrgGroupId, @lNextNumber, @rPurchaseOrderDetailXml, @rCreatedUserId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pPurchaseOrderDetailAdd]
    @rOrgGroupId int,
	@rPurchaseOrderId [bigint],
	@rPurchaseOrderDetailXml [nvarchar](max),
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    DECLARE @loIdoc INT
	DECLARE @lPurchaseOrderDetailCurrentId bigint
	DECLARE @lCount INT
	
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rPurchaseOrderDetailXml
	EXEC sCommon.pTableRowIdGet  @rOrgGroupId, 'sProcurement.tPurchaseOrderDetail', 1, 1, 1,@outNextNumber = @lPurchaseOrderDetailCurrentId output
	
	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,
			OrgGroupId
		)
	SELECT  
		@lPurchaseOrderDetailCurrentId + ROW_NUMBER() OVER(ORDER BY CASE  
																		WHEN Id < 0  THEN Id           
																	END DESC,
																	CASE 
																		WHEN Id > 0 THEN Id
																	END ASC) AS Id, 
		@rPurchaseOrderId,
		ItemSourceTypeId,
		ItemSourceId,
		PurchaseUomId,
		OrderQuantity,
		ReceivedOrderQuantity,
		BonusQuantity,
		NetUnitPrice,
		(CASE WHEN TaxGroupId = 0 THEN NULL ELSE TaxGroupId END) AS TaxGroupId,
		TaxRate,
		TaxAmount,
		OtherTaxAmount,
		DiscountAmount,
		DiscountPercentage,
		RequestedDeliveryDate,
		IsObsolete,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rOrgGroupId
	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
			  ) 
						  

		
						  
		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/PurchaseOrder/PurchaseOrderDetail', 1)
				 WITH ( ItemSourceId INT)
		SET @lPurchaseOrderDetailCurrentId  = @lCount + @lPurchaseOrderDetailCurrentId 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sProcurement.tPurchaseOrderDetail', @rCurrentNumber = @lPurchaseOrderDetailCurrentId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pPurchaseOrderDetailFromGrnModify]
	@rPurchaseOrderDetailModifyXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		DECLARE @loIdoc INT
		EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rPurchaseOrderDetailModifyXml
		
		UPDATE sProcurement.tPurchaseOrderDetail
		SET ReceivedOrderQuantity = XmlTable.ReceivedOrderQuantity,
			ReceivedBonusQuantity = XmlTable.ReceivedBonusQuantity,
			UpdatedUserId = XmlTable.UpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM OPENXML (@loIdoc, '/PurchaseOrder/PurchaseOrderDetail', 1)
				 WITH ( 
						Id bigint, 
						ReceivedOrderQuantity DECIMAL(22, 6),
						ReceivedBonusQuantity DECIMAL(22, 6),
						UpdatedUserId BIGINT
						
					  ) XmlTable
			INNER JOIN sProcurement.tPurchaseOrderDetail POD
				ON	POD.Id = XmlTable.Id 
			 
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pPurchaseOrderDetailGet]
    @rOrgGroupId int,
	@rPurchaseOrderId [bigint] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT POD.Id,
			POD.PurchaseOrderId,
			POD.ItemSourceTypeId,
			POD.ItemSourceId,
			POD.StockItemPurchaseUomId,
			POD.OrderQuantity,
			POD.ReceivedOrderQuantity,
			ISNULL(POD.ReceivedBonusQuantity, 0) ReceivedBonusQuantity,
			POD.BonusQuantity,
			POD.NetUnitPrice,
			ISNULL(POD.TaxGroupId, 0) TaxGroupId,
			POD.TaxRate,
			POD.TaxAmount,
			POD.OtherTaxAmount,
			POD.DiscountAmount,
			POD.DiscountPercentage,
			POD.RequestedDeliveryDate,
			POD.IsObsolete,
			(CASE WHEN ItemSourceTypeId = 34 THEN SIM.Code END)  AS ItemCode,
			(CASE WHEN ItemSourceTypeId = 34 THEN SIM.Title END)  AS ItemTitle,
			SIPU.ConversionFactor,
			SIM.IsBatchWiseTracking,
			SU.Code UomCode,
			SU.Title UomTitle,
			ISNULL(TGM.Code, '')  TaxCode,
			ISNULL(TGM.Title, '') TaxTitle
			
			
		FROM 
			sProcurement.tPurchaseOrderDetail POD
		LEFT JOIN
			sIP.vExtStockItemMaster SIM
		ON
			SIM.Id = POD.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		INNER JOIN sIP.tStockItemPurchaseUom SIPU
		ON
			SIPU.Id = POD.StockItemPurchaseUomId
		INNER JOIN 
				sFinanceCommon.tStockUomMaster SU
		ON
			SU.Id = SIPU.StockUOmId
		LEFT JOIN 
				sTax.vExtTaxGroupMaster TGM
		ON
				TGM.Id = POD.TaxGroupId
	  WHERE ((PurchaseOrderId = @rPurchaseOrderId) OR (@rPurchaseOrderId = 0)) AND POD.IsObsolete = 0
	  AND POD.OrgGroupId = @rOrgGroupId
	  ORDER BY POD.Id ASC
END





/****** Object:  StoredProcedure [sProcurement].[pPurchaseOrderGet]    Script Date: 07/09/2013 16:25:47 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pPurchaseOrderDetailRemove]
	@rId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tPurchaseOrderDetail
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pPurchaseOrderGet]
	@rOrgGroupId smallint,
	@rId [bigint] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		
	 SELECT PO.Id,
			ISNULL(PO.ParentPurchaseOrderId, 0) ParentPurchaseOrderId,
			PO.Number,
			PO.RequestedByName,
			PO.RequestedOrganizationDepartmentId,
			PO.VendorId,
			PO.StoreLocationId,
			PO.PaymentDays,
			PO.StatusId,
			PO.Amount,
			PO.DiscountAmount,
			PO.DiscountPercentage,
			PO.RoundedNetAmount,
			PO.UpdatedDateTime,
			ISNULL(PO.Remark, '') Remark,
			PO.IsObsolete,
			Po.StatusId,
		 
		 
			ISNULL(PO.ShipToStoreLocationId, 0) ShipToStoreLocationId,
			PO1.Number AS DraftPONumber,
			PO.CreatedDateTime AS SubmittedDate,
			ODM.Title AS DepartmentName,
			SLM.Title AS StoreLocation,
			ISNULL(SLM1.Title, '') AS ShipToStoreLocation,
			VM.Title AS VendorName,
			ISNULL(VM.CreditDays, 0) AS VendorCreditDays,
			VM.Code AS VendorCode
 
			
		FROM sProcurement.tPurchaseOrder PO
		LEFT JOIN
			sProcurement.tPurchaseOrder PO1
		ON
			PO1.ID = PO.ParentPurchaseOrderId
		INNER JOIN
			sSetup.tDepartmentMaster ODM
		ON
			ODM.ID = PO.RequestedOrganizationDepartmentId
		INNER JOIN
			sIP.tStoreLocationMaster SLM 
		ON
			SLM.Id = PO.StoreLocationId
		LEFT JOIN
			sIP.tStoreLocationMaster SLM1 
		ON
			SLM1.Id = PO.ShipToStoreLocationId
		INNER JOIN 
			sProcurement.tVendorMaster VM
		ON
			VM.Id = PO.VendorId
 
	  WHERE ((PO.Id = @rId) OR (@rId = 0))
	  AND PO.OrgGroupId =  @rOrgGroupId 

	  
	  EXEC [sProcurement].[pPurchaseOrderDetailGet] @rOrgGroupId, @rId,@rStoreLocationId
END




/****** Object:  StoredProcedure [sProcurement].[pGoodsReceiptNoteDetailGet]    Script Date: 07/09/2013 16:26:19 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pPurchaseOrderIdGet]
	@rOrgGroupId int,
	@rPurchaseOrderNumber [nvarchar](20),
	@rVendorId [int] = 0,
	@rPurchaseOrderStatusId [int],
	@rStoreLocationId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		IF (@rPurchaseOrderStatusId = 42)
		BEGIN
			SELECT
					Id
			FROM
					sProcurement.vPurchaseOrderDraftPo
			WHERE
					Number = @rPurchaseOrderNumber
					AND OrgGroupId = @rOrgGroupId
					AND ((StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
		END
		IF (@rPurchaseOrderStatusId = 43)
		BEGIN
			SELECT
					Id
			FROM
					sProcurement.tPurchaseOrder
			WHERE
				    IsObsolete = 0 
					AND  StatusId = @rPurchaseOrderStatusId 
					AND Number = @rPurchaseOrderNumber 
					AND ((VendorId = @rVendorId) OR (@rVendorId = 0))
					AND OrgGroupId = @rOrgGroupId
					AND ((StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
				 
		END
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pPurchaseOrderListingGet]
	@rOrgGroupId int,
	@rId [bigint] = 0,
	@rFromDate [datetime] = '1/1/1900',
	@rToDate [datetime] = '',
	@rLocationId [nvarchar](20) = '',
	@rVendorId [int] = 0,
	@rPOStatusId [nvarchar](20) = '',
	@rIsDeleted [bit] = 0,
	@rStoreLocationId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	BEGIN
	
		IF (@rToDate = '')
		 SET @rToDate = sCommon.fGetDate()
		 
	SELECT DISTINCT Id,
			Number,
			ParentPurchaseOrderId,
			VendorId,
			StoreLocationId,
			--StatusId,
			(CASE WHEN IsObsolete = 1 THEN 90 ELSE StatusId END) AS StatusId,
			RoundedNetAmount,
			IsObsolete,
			DraftPONumber,
			SubmittedDate,
			--StatusName,
			(CASE WHEN IsObsolete = 1 THEN 'Deleted' ELSE StatusName END) AS StatusName, 
			StoreLocation,
			VendorName
 
	FROM
	(		
		SELECT PO.Id,
			PO.Number,
			PO.ParentPurchaseOrderId,
			PO.VendorId,
			PO.StoreLocationId,
			PO.StatusId,
			PO.RoundedNetAmount,
			PO.IsObsolete,
			PO1.Number AS DraftPONumber,
			PO.CreatedDateTime AS SubmittedDate,
			SM.Title AS StatusName,
			SLM.Title AS StoreLocation,
			VM.Title AS VendorName
 
			
		FROM sProcurement.tPurchaseOrder PO
		LEFT JOIN
			sProcurement.tPurchaseOrder PO1 
		ON
			PO1.ID = PO.ParentPurchaseOrderId 
		INNER JOIN
			sCommon.tStatusMaster SM 
		ON
			SM.Id = PO.StatusId
		INNER JOIN
			sIP.tStoreLocationMaster SLM 
		ON
			SLM.Id = PO.StoreLocationId
		INNER JOIN 
			sProcurement.tVendorMaster VM
		ON
			VM.Id = PO.VendorId
			
 
			
	  WHERE ((PO.Id = @rId) OR (@rId = 0))
		AND ((PO.Number LIKE @rId) OR  (ISNULL(@rId, '') = '')) 
	    --AND ((PO.StoreLocationId = @rLocationId) OR (@rLocationId = 0))
	    AND PO.StoreLocationId =  @rStoreLocationId
	    AND ((PO.VendorId = @rVendorId) OR (@rVendorId = 0))
	    AND ((PO.StatusId = @rPOStatusId) OR (@rPOStatusId = 0))
	    
	    --AND (PO.StatusId NOT IN (SELECT PO.StatusID 
					--				FROM sProcurement.tPurchaseOrder PO
					--				WHERE PO.IsObsolete = 0 AND PO.ParentPurchaseOrderId IS NOT NULL) OR (@rPOStatusId = 0))
	     
	    
	    AND ((CAST(PO.CreatedDateTime AS DATE) >= @rFromDate) OR (@rFromDate = ''))
	    AND ((CAST(PO.CreatedDateTime AS DATE) <= @rToDate) OR (@rToDate = ''))
	 --   AND ((PO.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		--AND ((PO.CreatedDateTime <= @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))
	    AND ISNULL(PO.ParentPurchaseOrderId, 0) <> 0
	    AND ((@rPOStatusId  = 0) OR ((((PO.IsObsolete = 1) AND (@rIsDeleted = 1)) OR ((@rIsDeleted = 0) AND (PO.IsObsolete = 0) AND (@rPOStatusId <> 0) ))))
		AND PO.OrgGroupId = @rOrgGroupId
	    --AND (PO.ParentPurchaseOrderId IS NOT NULL)
	    
	    UNION ALL
	    
	    SELECT PO.Id,
			PO.Number,
			PO.ParentPurchaseOrderId,
			PO.VendorId,
			PO.StoreLocationId,
			PO.StatusId,
			PO.RoundedNetAmount,
			PO.IsObsolete,
			PO1.Number AS DraftPONumber,
			PO.CreatedDateTime AS SubmittedDate,
			SM.Title AS StatusName,
			SLM.Title AS StoreLocation,
			VM.Title AS VendorName
 
		
		FROM sProcurement.tPurchaseOrder PO
		LEFT JOIN
			sProcurement.tPurchaseOrder PO1 
		ON
			PO1.ID = PO.ParentPurchaseOrderId 
		INNER JOIN
			sCommon.tStatusMaster SM 
		ON
			SM.Id = PO.StatusId
		INNER JOIN
			sIP.tStoreLocationMaster SLM 
		ON
			SLM.Id = PO.StoreLocationId
		INNER JOIN 
			sProcurement.tVendorMaster VM
		ON
			VM.Id = PO.VendorId
 
			
	  WHERE ((PO.Id = @rId) OR (@rId = 0))
		AND ((PO.Number LIKE @rId) OR  (ISNULL(@rId, '') = '')) 
	    --AND ((PO.StoreLocationId = @rLocationId) OR (@rLocationId = 0))
	    AND (PO.StoreLocationId = @rStoreLocationId) 
	   
	    AND ((PO.VendorId = @rVendorId) OR (@rVendorId = 0))
	    AND ((PO.StatusId = @rPOStatusId) OR (@rPOStatusId = 0))
	    	    
	    --AND (PO.StatusId NOT IN (SELECT PO.StatusID 
					--			FROM sProcurement.tPurchaseOrder PO
					--				WHERE PO.IsObsolete = 1 AND PO.ParentPurchaseOrderId IS NOT NULL) OR (@rPOStatusId = 0))
	    
	    AND ((CAST(PO.CreatedDateTime AS DATE) >= @rFromDate) OR (@rFromDate = ''))
	    AND ((CAST(PO.CreatedDateTime AS DATE) <= @rToDate) OR (@rToDate = ''))
	 --   AND ((PO.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		--AND ((PO.CreatedDateTime <= @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))
	    AND (PO.ParentPurchaseOrderId IS NULL)
	   AND ((@rPOStatusId  = 0) OR ((((PO.IsObsolete = 1) AND (@rIsDeleted = 1)) OR ((@rIsDeleted = 0) AND (PO.IsObsolete = 0) AND (@rPOStatusId <> 0) ))))
	   AND PO.OrgGroupId = @rOrgGroupId
	    AND PO.Id NOT IN( SELECT PO.ParentPurchaseOrderId 
													FROM 
															sProcurement.tPurchaseOrder PO 
													LEFT JOIN
															sProcurement.tPurchaseOrder PO1 
													ON
															PO1.ID = PO.ParentPurchaseOrderId
													WHERE   
															PO.ParentPurchaseOrderId IS NOT NULL AND PO.OrgGroupId = @rOrgGroupId  )

	) AS TABL
	ORDER BY Id DESC
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pPurchaseOrderModify]
	@rOrgGroupId smallint,
	@rId [bigint],
	@rParentPurchaseOrderId [bigint] = 0,
	@rRequestedByName [nvarchar](300),
	@rRequestedOrganizationDepartmentId [int],
	@rVendorId [int],
	@rStoreLocationId [int],
	@rPaymentDays [int],
	@rStatusId [smallint],
	@rAmount [decimal](22, 6),
	@rDiscountAmount [decimal](22, 6),
	@rDiscountPercentage [decimal](5, 2),
	@rRoundedNetAmount [decimal](22, 6),
	@rRemark [nvarchar](300),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rShipToStoreLocationId [int],
	@rPurchaseOrderDetailModifyXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tPurchaseOrder
		SET 
			ParentPurchaseOrderId = (CASE WHEN @rParentPurchaseOrderId = 0 THEN NULL ELSE @rParentPurchaseOrderId END),
			RequestedByName = @rRequestedByName,
			RequestedOrganizationDepartmentId = @rRequestedOrganizationDepartmentId,
			VendorId = @rVendorId,
			StoreLocationId = @rStoreLocationId,
			PaymentDays = @rPaymentDays,
			StatusId = @rStatusId,
			Amount = @rAmount,
			DiscountAmount = @rDiscountAmount,
			DiscountPercentage = @rDiscountPercentage,
			RoundedNetAmount = @rRoundedNetAmount,
			Remark = @rRemark,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),	 
			ShipToStoreLocationId = CASE WHEN @rShipToStoreLocationId = -1 OR @rShipToStoreLocationId = 0 THEN NULL ELSE @rShipToStoreLocationId END
	  WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	  
	  EXEC [sProcurement].[pPurchaseOrderDetailModify] @rOrgGroupId, @rId, @rPurchaseOrderDetailModifyXml, @rUpdatedUserId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pPurchaseOrderRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tPurchaseOrder
	    SET IsObsolete = 1
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptFirstAidEmployee]
 
	@rFAEId bigint = 0,
	@rOrgId smallint,
	@rStoreLocationId int,
	@rEmployeeCode nvarchar(20)='',
	@rDeptId int=0,
	@rFirstAidId int=0,
	@rFromDate date=NULL,
	@rToDate date=NULL,
	@rBuilder1 nvarchar(MAX)='',
	@rBuilder2 nvarchar(MAX)=''
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
	    FAE.Id AS FAEId,
	    FAE.Number AS IssueNumber,
	    EM.Code AS EmployeeCode,
	   (EM.FirstName+' '+EM.LastName)AS EmployeeName,
	    FAE.StoreLocationId,
	    LM.Title AS LocationName,
	    ISNULL(FAE.Remark,'')AS FAERemark,
		--FAE.OrgId,
		EM.OrgId,
		FAE.IssueDate AS IssueDate,	
		FAE.IssueBy,
		FAM.Id AS FirstAidId,
		FAM.Code AS FirstAidCode,
		FAM.Title AS FirstAidTitle,
		FAED.IssuedQuantity,
		SIM.Code ItemCode,
		SIM.Title AS ItemName,
		ISNULL(FAED.Remark,'') AS FAEDRemark,
		ODM.Id AS DepartmentId,
		ODM.Title AS DepartmentName
		
	
	FROM 
	 sProcurement.tFirstAidEmoloyee FAE
	 INNER JOIN sProcurement.tFirstAidEmployeeDetail FAED
		ON FAE.Id=FAED.FirstAidEmployeeId
	 INNER JOIN sCommon.tFirstAidMaster FAM
		ON FAE.FirstAidId=FAM.Id
	 INNER JOIN sIp.tStockItemMaster SIM
		ON SIM.Id=FAED.StockItemId
	 INNER JOIN sIp.tStoreLocationMaster LM
	    ON FAE.StoreLocationId = LM.Id  
	 INNER JOIN sHrm.tEmployeeMaster EM
	    ON EM.Id=FAE.EmployeeId
	 INNER JOIN sSetup.tDepartmentMaster ODM
		ON ODM.Id=FAM.OrganizationDepartmentId
	    
	 WHERE (FAE.Id=@rFAEId OR @rFAEId=0)
	 AND(EM.Code=@rEmployeeCode OR @rEmployeeCode= '') 
	 AND(ODM.Id=@rDeptId OR @rDeptId=0)
	 AND(FAM.Id=@rFirstAidId OR @rFirstAidId=0)
	 AND (FAE.StoreLocationId=@rStoreLocationId)
	 --AND (FAE.OrgId=@rOrgId)
	 AND (EM.OrgId=@rOrgId)
	 AND (FAE.IssueDate >= @rFromDate OR ISNULL(@rFromDate,'')='') 
     AND (FAE.IssueDate <= @rToDate OR ISNULL(@rToDate,'')='')
     AND  ISNULL(EM.IsOtherUser,0) = 0
     ORDER BY SIM.Title ASC

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptFirstAidInspection]
 
	@rFAIId bigint = 0,
	@rOrgId smallint,
	@rStoreLocationId int
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	SELECT
	    FAI.Id,
	    (EM.FirstName+' '+EM.LastName)AS EmployeeName,
		FAI.Number AS InspectionNumber,
		ISNULL(FAI.Remark,'')AS FAIRemark,
		FAI.InspectionDate,	
		FAM.Code,
		FAM.Title,
		FAID.IsWellMaintained,
		ISNULL(FAID.Remark,'')AS FAIDRemark,
		FAI.StoreLocationId,
		LM.Title AS LocationName,
		--FAI.OrgId
		EM.OrgId
			
	FROM 
	 sProcurement.tFirstAidInspection FAI
	 INNER JOIN sProcurement.tFirstAidInspectionDetail FAID
		ON FAI.Id=FAID.FirstAidInspectionId
	 INNER JOIN sCommon.tFirstAidMaster FAM
		ON FAID.FirstAidId=FAM.Id
	 INNER JOIN sIp.tStoreLocationMaster LM
	    ON FAI.StoreLocationId = LM.Id  
	 INNER JOIN sHrm.tEmployeeMaster EM
	    ON EM.Id=FAI.EmployeeId
	
	 WHERE (FAI.Id=@rFAIId   
	 AND FAI.StoreLocationId=@rStoreLocationId
	 --AND FAI.OrgId=@rOrgId 
	 AND EM.OrgId=@rOrgId 
	 AND  ISNULL(EM.IsOtherUser,0) = 0)
	 
	 ORDER BY FAM.Title ASC
	 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptFirstAidIssueList]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rFromDate datetime = '1900/1/1',
	@rToDate datetime = '1900/1/1',
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	@rReportId smallint,
	@rMainGroupId smallint,
	@rSubGroupId smallint,
	@rOrgId int,
	@rLocationId int,
	@rStoreLocationId int
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

 	SELECT
 		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
 		FAM.Id AS FirstAidId,
 		FAM.Title AS FirstAidName,
 		SI.CreatedDateTime AS Dates,
 		SI.Id AS IssueId,
 		SIM.Code AS ItemCode,
 		SIM.Title AS ItemName,
 		SIDL.IssuedQuantity AS Quantity,
 		SIP.WeightedAverageCost AS Cost,
 		(SIDL.IssuedQuantity * SIP.WeightedAverageCost) AS Value,
 		@rReportId AS ReportId
		
	FROM 
		sCommon.tFirstAidMaster FAM
		INNER JOIN sProcurement.tStockIssue SI ON SI.FirstAidId=FAM.Id AND FAM.StoreLocationId=@rStoreLocationId
		INNER JOIN sProcurement.tStockIssueDetail SIDL ON SIDL.StockIssueId=SI.Id
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIDL.StockItemId
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId = @rStoreLocationId
		INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
			
	   WHERE	
			 SIM.IsObsolete=0	     
	    AND (FAM.OrgId=@rOrgId)
		AND ((SI.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((SI.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (IMGM.Id = @rMainGroupId OR @rMainGroupId=0)
		AND (ISGM.Id = @rSubGroupId OR @rSubGroupId=0)
		--AND (ODM.Id=@rDepartmentId OR @rDepartmentId=0)
		--AND (SLM.Id=@rFromLocationId OR @rFromLocationId=0)
		--AND (SLM.Id=@rToLocationId OR @rToLocationId=0)
		AND (SIM.LocationId = @rLocationId OR @rLocationId=0)
		AND(SIM.Code=@rItemCode OR @rItemCode='')
		AND (SIM.Title = @rItemName OR @rItemName = '')
		
END




/****** Object:  StoredProcedure [sProcurement].[pRptStockItemListing]    Script Date: 07/09/2013 16:30:30 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptFirstAidStock]
 	
	@rStoreLocationId int,
	@rFromDate date=NULL,
	@rToDate date=NULL,
	@rBuilder1 nvarchar(MAX)='',
	@rBuilder2 nvarchar(MAX)=''
		
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SIMM.Id AS StockItemId,
		SIMM.Code,
		SIMM.Title,
		FAEE.StoreLocationId,
		LM.Title AS LocationName,
		@rFromDate AS FromDate,
		@rToDate AS ToDate,


(select ISNULL(SUM(SD.IssuedQuantity),0) from sProcurement.tStockIssueDetail SD INNER JOIN sProcurement.tStockIssue SI 
	ON SI.Id=SD.StockIssueId  WHERE (SD.StockItemId=SIMM.Id) AND (SI.FromStoreLocationId=FAEE.StoreLocationId)
	AND (CONVERT(DATE,SI.CreatedDateTime)>= @rFromDate OR ISNULL(@rFromDate,'')='') 
     AND (CONVERT(DATE,SI.CreatedDateTime) <= @rToDate OR ISNULL(@rToDate,'')=''))AS SIQuantity,

(select ISNULL(SUM(FAED.IssuedQuantity),0)from sProcurement.tFirstAidEmployeeDetail FAED INNER JOIN sProcurement.tFirstAidEmoloyee
 FAE ON FAE.Id=FAED.FirstAidEmployeeId 	WHERE (FAED.StockItemId=SIMM.Id) AND (FAE.StoreLocationId=FAEE.StoreLocationId) 
 AND (FAE.IssueDate >= @rFromDate OR ISNULL(@rFromDate,'')='') 
     AND (FAE.IssueDate <= @rToDate OR ISNULL(@rToDate,'')=''))
 AS FAEQuantity
		
	FROM
	
	sProcurement.tFirstAidEmoloyee FAEE
	INNER JOIN sProcurement.tFirstAidEmployeeDetail FAED
		ON FAEE.Id=FAED.FirstAidEmployeeId
	--INNER JOIN sProcurement.tStockIssue SII
	--	ON SII.FirstAidId=FAEE.FirstAidId
	INNER JOIN sIp.tStockItemMaster SIMM
		ON SIMM.Id=FAED.StockItemId
	INNER JOIN sIp.tStoreLocationMaster LM
	    ON FAEE.StoreLocationId = LM.Id  

WHERE
	 FAEE.StoreLocationId=@rStoreLocationId
	
     
	
	
GROUP BY SIMM.Id,SIMM.Code,FAEE.StoreLocationId,LM.Title,SIMM.Title
	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptFsnList]
	@rItemId [int] = 0,
	@rFsnId [int] = 0,
	@rStoreLocationId [int] = 0
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

   SELECT 	SIM.Code AS ItemNumber,
				SIM.Title AS ItemName,
				FSN.Title  AS FSNType,
				UOM.Title  AS UOM,
				SB.AvailableQuantity,
				LM.Title,
				
				(CASE	@rItemId
						WHEN 0 THEN 'All'
						ELSE SIM.Title
						END)							
														AS ParamItemNumber, 
				(CASE	@rFsnId
						WHEN 0 THEN 'All'
						ELSE FSN.Title
						END)				             AS ParamFsn,		
						
				(CASE	@rStoreLocationId
						WHEN 0 THEN 'All'
						ELSE LM.Title
						END)				             AS ParamLocationName	 
				
			
				/*
					tStockBatch	StockItemId
					tStockBatch	StoreLocationId
				*/
				FROM		sIP.tStockItemMaster  SIM	
				INNER JOIN  sIp.tFsnMaster FSN
				ON SIM.FsnId = FSN.Id 
				INNER JOIN sFinanceCommon.tStockUomMaster UOM
				ON SIM.IssueStockUomId = UOM.Id 
				INNER JOIN sProcurement.tStockBatch SB
				ON SIM.Id = SB.StockItemId		
				INNER JOIN 	sIp.tStoreLocationMaster LM
				ON 	SB.StoreLocationId = LM.Id 
				
				
				WHERE		((SIM.Id = @rItemId) OR (@rItemId = 0)) 	
	AND			((SIM.FsnId   = @rFsnId) OR (@rFsnId = 0))
	AND          (( SB.StoreLocationId  = @rStoreLocationId) OR (@rStoreLocationId = 0))
	AND SB.AvailableQuantity > 0
				
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
		Purpose          : Report for grn listing
		Created date     : 15 Apr 2010
		Author           : Rajendra Patel
		Copyright©       : Copyright © Sapphire software
		Last Change Desc : grn amount taken after taking all calculation
		Test script      : EXECUTE sProcurement.pRptGoodsReceiptNoteListing @rFromDate = '2010-06-09',
							@rToDate = '2010-06-09',
							@rDepartmentId = 0,
							@rVendorId = 0,
							@rGRNType = 0,
							@rInvoicedId = 0,
							@rReportType = 1
	*******************************************************************************/
CREATE OR ALTER PROCEDURE [sProcurement].[pRptGoodsReceiptNoteListing]
(
	@rOrgGroupId Int,
	@rFromDate Date = '1/1/1900',
	@rToDate Date = '1/1/1900',
	@rDepartmentId Int = 0,
	@rVendorId Int = 0,
	@rStoreLocationId int, 
	@rInvoicedId Int = 0,
	@rReportType Nvarchar(100) = ''
)	

AS
BEGIN
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

DECLARE @lCurrencyId Int
SET @lCurrencyId = 0

 
	

	SELECT	DISTINCT GRN.Id,
				 GRND.PurchaseOrderDetailId							AS PurchaseOrderDetailId,
				 GRN.Number											AS GrnNo,
				 GRN.CreatedDateTime								AS GrnDate,
				 PO.Number											AS PoNo,
				 PO.CreatedDateTime									AS PoDate,				 
				 VM.Title											AS VendorName,
				 SIM.Code											AS ItemNo,
				 SIM.Title											AS ItemName,
				 
				(CASE WHEN @rVendorId = 0 THEN 'All' ELSE VM.Title END) AS VendorHeaderName, 
				(CASE 
					WHEN SIM.IsBatchWiseTracking = 1 THEN
						(GRNB.ReceiptQuantity * SIPU.ConversionFactor)
					ELSE
						(GRNB.ReceiptQuantity * SIPU.ConversionFactor)
					END) AS ReceivedQty,
			 
			    (ISNULL(GRND.NetUnitPrice/GRND.ReceiptQuantity, 0))/(SIPU.ConversionFactor) AS UnitPrice,			    				 
        		 ((ISNULL(GRNB.ReceiptQuantity, 0) * ISNULL((GRND.NetUnitPrice - GRND.DiscountAmount + GRND.TaxAmount + GRND.OtherTaxAmount + GRND.AddOnCharges) / GRND.ReceiptQuantity, 0)))	AS POValue,
				 --(CASE
					--WHEN PO.CurrencyId = (SELECT ForeignCurrencyId FROM sCommon.tCompanyInformation) 
					--	THEN (ISNULL(GRND.ReceiptQuantity, 0) * ISNULL(GRND.NetUnitPrice / GRND.ReceiptQuantity, 0))/ CRM.Rate
					--ELSE 
					--	(ISNULL(GRND.ReceiptQuantity, 0) * ISNULL(GRND.NetUnitPrice / GRND.ReceiptQuantity, 0))
					--END
				 -- ) AS POValue,
				  (CASE @rFromDate
						WHEN sCommon.fGetDate() THEN 'ALL'
						ELSE @rFromDate
						END) AS ParamStartDate,
						
						(CASE @rToDate
						WHEN sCommon.fGetDate() THEN 'ALL'
						ELSE @rToDate
						END) AS ParamEndDate,
					(CASE @rDepartmentId
						WHEN 0 THEN 'All'
						ELSE (SELECT Title FROM sSetup.tDepartmentMaster WHERE Id = @rDepartmentId)
					END)	AS ParamDepartment,
					(CASE @rVendorId
						WHEN 0 THEN 'All'
						ELSE (SELECT Title FROM sProcurement.tVendorMaster WHERE Id = @rVendorId)
					END)	AS ParamVendor,
	--				@rGRNType dInt = 0,
	--@rInvoicedId dInt = 0
					(CASE @rInvoicedId
						WHEN 0 THEN 'All'
						WHEN 1 THEN 'Yes'
						WHEN 2 THEN 'No'
					END) AS ParamInvoiced,
 
					sCommon.fGetDate() AS ParamReportDate,
					(CASE @rReportType 
						WHEN 0 THEN 'Summary'
						WHEN 1 THEN 'Details'						
					END)AS ParamReportType			 
							  
		FROM		sProcurement.tGoodsReceiptNote GRN
					INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND
						ON GRND.GoodsReceiptNoteId = GRN.Id
					INNER JOIN sProcurement.tGoodsReceiptNoteBatch GRNB
						ON GRNB.GoodsReceiptNoteDetailId = GRND.Id									
					INNER JOIN sProcurement.tPurchaseOrder PO
						ON GRN.PurchaseOrderId = PO.Id
					INNER JOIN sProcurement.tVendorMaster VM
						ON VM.Id = PO.VendorId
					INNER JOIN sIp.tStoreLocationMaster SLM
						ON SLM.Id = PO.StoreLocationId					
					INNER JOIN sProcurement.tPurchaseOrderDetail POD
						ON POD.PurchaseOrderId = PO.Id
						AND POD.Id = GRND.PurchaseOrderDetailId
					INNER JOIN sIp.tStockItemMaster SIM
						ON SIM.Id = POD.ItemSourceId
					INNER JOIN sIp.tStockItemPurchaseUom SIPU
						ON SIPU.Id = POD.StockItemPurchaseUomId 
					INNER JOIN sFinanceCommon.tStockUomMaster SUOM
						ON SUOM.Id = SIPU.StockUomId
					INNER JOIN sSecurity.tUser U
						ON U.Id = GRN.CreatedUserId
 
					
			WHERE ((VM.Id = @rVendorId) Or (@rVendorId = 0))
			AND (GRN.CreatedDateTime BETWEEN CAST(@rFromDate AS DATE) AND CASE WHEN @rToDate = CAST('1900-01-01' AS DATE) THEN DATEADD(DD, 1, sCommon.fGetDate()) ELSE  DATEADD(DD, 1, @rToDate) END)
			AND ((PO.RequestedOrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))			
			AND (( @rInvoicedId = 2 AND GRND.ReceiptQuantity <> GRND.InvoicedQuantity) OR (@rInvoicedId = 0 OR @rInvoicedId = 1))
			AND (( @rInvoicedId = 1 AND GRND.ReceiptQuantity = GRND.InvoicedQuantity) OR (@rInvoicedId = 0 OR @rInvoicedId = 2))
			AND GRN.OrgGroupId = @rOrgGroupId
			AND GRN.StoreLocationId=@rStoreLocationId
			
			
			
			
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptGoodsReceivedNote]
	@rOrgGroupId Int,
	@rGRNNo [nvarchar](20) = '',
	@rGRNId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN 
		SELECT	DISTINCT GRN.Id,
				 VM.Title								AS VendorName,
				 
				 ISNULL(VM.StreetOne, '') AS StreetOne, 
				 ISNULL(VM.StreetTwo, '') AS StreetTwo,  
				 ISNULL(VM.StreetThree, '') AS StreetThree, 
				 ISNULL(VM.StreetFour, '') AS StreetFour,
				 ISNULL(VM.Area,'') AS AreaTitle,
				 ISNULL(VM.City,'') AS CityTitle,
				 ISNULL(VM.Country,'') AS StateTitle,
				 ISNULL(VM.State,'') AS CountryTitle,
				 GRND.PurchaseOrderDetailId							AS PurchaseOrderDetailId,
				 GRN.Number											AS GrnNo,
				 CONVERT(varchar, sCommon.fReportDateGet(GRN.CreatedDateTime))								AS GrnDate,
				 PO.Number											AS PoNo,
				 CONVERT(varchar, sCommon.fReportDateGet(PO.CreatedDateTime))								AS PoDate,
				 GRN.DeliveryOrderNumber							AS DoNo,
				 CONVERT(varchar, sCommon.fReportDateGet(GRN.DeliveryOrderDate))							AS DoDate,
				 SLM.Title											AS ReceivingLocation,
							 
				 SIM.Code											AS ItemNo,
				 SIM.Title											AS ItemName,
				 SUOM.Code											AS Uom,
				 SIPU.ConversionFactor								AS ConversionFactor,
				(CASE 
					WHEN SIM.IsBatchWiseTracking = 1 THEN
						GRNB.ReceiptQuantity
					ELSE
						GRND.ReceiptQuantity
					END)											AS ReceivedQty,
				 (CASE 
					WHEN SIM.IsBatchWiseTracking = 1 THEN
						GRNB.ReceiptBonusQuantity
					ELSE
						GRND.ReceiptBonusQuantity
					END)											AS ReceivedBonusQty,
				 (CASE 
					WHEN SIM.IsBatchWiseTracking = 1 THEN
						GRNB.Number
					ELSE
						''
					END)											AS BatchNo,
				 (CASE 
					WHEN SIM.IsBatchWiseTracking = 1 THEN
						CONVERT(varchar, sCommon.fReportDateGet(GRNB.ExpiryDate))
					ELSE
						''
					END)											AS ExpiryDate,
				 ISNULL(BM.Title, '')											AS BinNo,
				 (CASE 
					WHEN GRND.ReceiptQuantity <> 0 THEN
						ISNULL(GRND.NetUnitPrice/GRND.ReceiptQuantity, 0)
					END
				 )									AS UnitPrice,
				 (CASE 
					WHEN GRND.ReceiptQuantity <> 0 THEN
						ISNULL((GRND.NetUnitPrice/GRND.ReceiptQuantity) * GRNB.ReceiptQuantity, 0)
					END
				 )												AS Amount,
				 (CASE 
					WHEN GRND.ReceiptQuantity <> 0 THEN
						ISNULL((GRND.DiscountAmount/GRND.ReceiptQuantity) * GRNB.ReceiptQuantity, 0)
					END
				 )											AS DiscountAmount,
				 (CASE 
					WHEN GRND.ReceiptQuantity <> 0 THEN
						ISNULL((GRND.TaxAmount/GRND.ReceiptQuantity) * GRNB.ReceiptQuantity, 0)
					END
				 )												AS TaxAmount,
				 (CASE 
					WHEN GRND.ReceiptQuantity <> 0 THEN
						ISNULL((GRND.OtherTaxAmount/GRND.ReceiptQuantity) * GRNB.ReceiptQuantity, 0)
					END
				 )											AS OtherTaxes,
				 (CASE 
					WHEN GRND.ReceiptQuantity <> 0 THEN
						ISNULL((GRND.AddonCharges/GRND.ReceiptQuantity) * GRNB.ReceiptQuantity, 0)
					END
				 )												AS AddOnCharges,
							 
				--((ISNULL(GRND.NetUnitPrice, 0)) + ISNULL(GRND.TaxAmount, 0) + ISNULL(GRND.OtherTaxAmount, 0) + ISNULL(GRND.AddonCharges, 0) - ISNULL(GRND.DiscountAmount, 0))
				-- AS NetAmount,
				(CASE 
					WHEN GRND.ReceiptQuantity <> 0 THEN
				 (ISNULL((GRND.NetUnitPrice/GRND.ReceiptQuantity) * GRNB.ReceiptQuantity, 0) + 
				 ISNULL((GRND.TaxAmount/GRND.ReceiptQuantity) * GRNB.ReceiptQuantity, 0) + 
				 ISNULL((GRND.OtherTaxAmount/GRND.ReceiptQuantity) * GRNB.ReceiptQuantity, 0) + 
				 ISNULL((GRND.AddonCharges/GRND.ReceiptQuantity) * GRNB.ReceiptQuantity, 0) - 
				 ISNULL((GRND.DiscountAmount/GRND.ReceiptQuantity) * GRNB.ReceiptQuantity, 0))
					END
				 )														AS NetAmount,
				 ISNULL(GRN.Remark, '') AS Remarks,
				 GRN.PackagingCharge AS PackagingCharge,
				 U.DisplayTitle AS GeneratedBy
				 --'[' + CurrM.Code + ']' AS CurrencyName
				
							  
		FROM		sProcurement.tGoodsReceiptNote GRN
					INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND
						ON GRND.GoodsReceiptNoteId = GRN.Id
					INNER JOIN sProcurement.tGoodsReceiptNoteBatch GRNB
						ON GRNB.GoodsReceiptNoteDetailId = GRND.Id
									
					INNER JOIN sProcurement.tPurchaseOrder PO
						ON GRN.PurchaseOrderId = PO.Id
					INNER JOIN sProcurement.tVendorMaster VM
						ON VM.Id = PO.VendorId
					INNER JOIN sIp.tStoreLocationMaster SLM
						ON SLM.Id = GRN.StoreLocationId
					--INNER JOIN sFinanceCommon.tCurrencyMaster CurrM
					--	ON CurrM.Id = PO.CurrencyId
					
					INNER JOIN sProcurement.tPurchaseOrderDetail POD
						ON POD.PurchaseOrderId = PO.Id
						AND POD.Id = GRND.PurchaseOrderDetailId
					INNER JOIN sIp.tStockItemMaster SIM
						ON SIM.Id = POD.ItemSourceId
					LEFT JOIN sIp.tStockItemBin SIB
						ON SIB.StockItemId=SIM.Id
					LEFT JOIN sIp.tBinMaster BM
						ON BM.Id = SIB.BinId
					INNER JOIN sIp.tStockItemPurchaseUom SIPU
						--ON SIPU.StockItemId = SIM.Id
						ON SIPU.Id = POD.StockItemPurchaseUomId 
					INNER JOIN sFinanceCommon.tStockUomMaster SUOM
						ON SUOM.Id = SIPU.StockUomId
					INNER JOIN sSecurity.tUser U
						ON U.Id = GRN.CreatedUserId
					
					--LEFT JOIN	sCommon.tAreaMaster AM
					--			ON AM.Id = VM.AreaId
					--LEFT JOIN	sCommon.tCityMaster CiM
					--			ON CiM.Id = VM.CityId
					--LEFT JOIN	sCommon.tStateMaster SM
					--			ON SM.Id = VM.StateId
					--LEFT JOIN	sCommon.tCountryMaster CoM
					--			ON CoM.Id = VM.CountryId
					
			WHERE ((GRN.Id = @rGRNId) OR (ISNULL(@rGRNId, 0) = 0))
			AND ((GRN.Number = @rGRNNo) OR (ISNULL(@rGRNNo, '') = ''))
			AND GRN.OrgGroupId = @rOrgGroupId
			ORDER BY GRND.PurchaseOrderDetailId
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptGoodsReturnNote]
	@rOrgGroupId Int,
	@rGRNNo [nvarchar](20) = '',
	@rGRNId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN 
DECLARE @lSumOfTotalAmountReturned DECIMAL(22,  6)
SELECT	DISTINCT


				
			@lSumOfTotalAmountReturned = 
			(SELECT	
			SUM( 
			/**Sub Total Amount Returned Start**/
			--Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)
			
			--DiscountAmount
			-	 
			(CASE WHEN SIM.IsBatchWiseTracking =  1 THEN				  
				 CAST((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
				 WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
				 ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)	 * (GRND.DiscountPercentage/100)AS DECIMAL(22,  6))
			 ELSE 
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
			END)	
			
			--Tax Amount = (netUnitPrice - discountAmount) * (TaxRate / 100);
			+
			
			(--Amount
			((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)			
			--Disc. Amount
			- 
			(CASE WHEN SIM.IsBatchWiseTracking =  1 THEN
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
					ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))		
				  ELSE 
				  --CAST((GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))	
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
				  END)	
			)
			--TaxRate
			* (GRND.TaxRate/ 100)
			)
			
			--Other Tax Amount
			+ 
			((GRND.OtherTaxAmount/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END))
			
			--AddOnCharges
			+ 
			(			
			(GRND.AddOnCharges/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END)
			)	
			/**Sub Total Amount Returned End**/
			
			
			
			----Amount - Disc. Amount  +  Tax Amount  +  Other tax Amount  +  Add ON
			----Amount
			----CAST(
			--((			
			----CAST(
			--CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) 
			--END 
			----AS DECIMAL(22,  6))
			
			-- -
			-- --Discount Amount
			--(CASE 
			--	  WHEN SIM.IsBatchWiseTracking =  1 THEN
			--	  CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--		ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) * (GRND.DiscountPercentage/100))  
			--		AS DECIMAL(22, 6))		
			--	  ELSE 
			--	  CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			--		ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			--		* (GRND.DiscountPercentage/100)) 
			--		AS DECIMAL(22,  6)
			--		)	            
			--	  END)	
			--)
			
			--  +  --Tax Amount			
			--((
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)			
			-- --Disc. Amount
			--- (CASE 
			--	  WHEN SIM.IsBatchWiseTracking =  1 THEN
			--	  --CAST(
			--	  (GRNRB.ReturnQuantity * (GRND.DiscountPercentage/100))  
			--	  --AS DECIMAL(22,  6))		
			--	  ELSE 
			--	  --CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			--		ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			--		* (GRND.DiscountPercentage/100)) 
			--		--AS DECIMAL(22,  6))	            
			--	  END)	
			--)	
			--* (GRND.TaxRate/ 100))
			
					 
			--  +  --Other tax Amount
			----CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.ReceiptQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			----ELSE (GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount) END
			----CAST(
			--(			
			--(GRND.OtherTaxAmount/ GRND.ReceiptQuantity) *
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			--ELSE (GRNRB.ReturnQuantity) END)
			--)
			----AS DECIMAL(22,  6))
			-- +  --Add ON
			 
			----CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			----ELSE (GRND.AddOnCharges * GRNRD.ReturnQuantity) END 
			----CAST(
			--(			
			--(GRND.AddOnCharges/ GRND.ReceiptQuantity) *
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			--ELSE (GRNRB.ReturnQuantity) END)
			--)
			----AS DECIMAL(22,  6))
		
			--)
			----AS DECIMAL(22,  6))	
			) 
			
			
						FROM		sProcurement.tGoodsReceiptNoteReturn GRNR
					INNER JOIN sProcurement.tGoodsReceiptNoteReturnDetail GRNRD
						ON GRNRD.GoodsReceiptNoteReturnId =  GRNR.Id AND GRNRD.ReturnQuantity > 0
					INNER JOIN sProcurement.tGoodsReceiptNoteReturnBatch GRNRB
						ON GRNRB.GoodsReceiptNoteReturnDetailId =  GRNRD.Id	AND GRNRB.ReturnQuantity > 0	
					INNER JOIN sProcurement.tGoodsReceiptNote GRN
						ON GRN.Id =  GRNR.GoodsReceiptNoteId
					INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND
						ON GRND.GoodsReceiptNoteId =  GRN.Id
							AND GRNRD.GoodsReceiptNoteDetailId =  GRND.Id
					INNER JOIN sProcurement.tGoodsReceiptNoteBatch GRNB
						ON GRNB.GoodsReceiptNoteDetailId =  GRND.Id									
							AND GRNRB.GoodsReceiptNoteBatchId =  GRNB.Id
					INNER JOIN sProcurement.tPurchaseOrder PO
						ON GRN.PurchaseOrderId =  PO.Id
					INNER JOIN sProcurement.tVendorMaster VM
						ON VM.Id =  PO.VendorId
					INNER JOIN sIp.tStoreLocationMaster SLM
						ON SLM.Id =  PO.StoreLocationId
					
					INNER JOIN sProcurement.tPurchaseOrderDetail POD
						ON POD.PurchaseOrderId =  PO.Id
						AND POD.Id =  GRND.PurchaseOrderDetailId
					INNER JOIN sIp.tStockItemMaster SIM
						ON SIM.Id =  POD.ItemSourceId
					--INNER JOIN sIp.tBinMaster BM
						--ON BM.Id =  SIM.BinId
					INNER JOIN sIp.tStockItemPurchaseUom SIPU						
						ON SIPU.Id =  POD.StockItemPurchaseUomId 
					INNER JOIN sFinanceCommon.tStockUomMaster SUOM
						ON SUOM.Id =  SIPU.StockUomId
					INNER JOIN sSecurity.tUser U
						ON U.Id =  GRN.CreatedUserId
					--INNER JOIN sFinanceCommon.tCurrencyMaster CM
					--	ON PO.CurrencyId = CM.Id
					INNER JOIN sCommon.tReasonMaster RM
						ON RM.Id = GRNRD.ReasonId
						
					--LEFT JOIN	sCommon.tAreaMaster AM
					--			ON AM.Id =  VM.AreaId
					--LEFT JOIN	sCommon.tCityMaster CiM
					--			ON CiM.Id =  VM.CityId
					--LEFT JOIN	sCommon.tStateMaster SM
					--			ON SM.Id =  VM.StateId
					--LEFT JOIN	sCommon.tCountryMaster CoM
					--			ON CoM.Id =  VM.CountryId
					
			WHERE ((GRNR.Id =  @rGRNId) OR (ISNULL(@rGRNId,  0) =  0))
			AND ((GRNR.Number =  @rGRNNo) OR (ISNULL(@rGRNNo,  '') =  ''))
																	
			)--AS ParamSumOfTotalAmountReturned, 
			SELECT @lSumOfTotalAmountReturned								AS ParamSumOfTotalAmountReturned, 
			sFinanceCommon.fRoundOff(@lSumOfTotalAmountReturned,  1)			AS ParamRoundedSumOfTotalAmountReturned, 
			
				--For Operation
				 GRNR.Id, 
				 GRNRD.Id, 
				 GRNR.Number, 
				 SIM.IsBatchWiseTracking, 
				 GRND.TaxRate, 
				 --For Display 
				 VM.Title								AS VendorName, 
				 ISNULL(VM.StreetOne,  '')							AS StreetOne,  
				 ISNULL(VM.StreetTwo,  '')							AS StreetTwo,   
				 ISNULL(VM.StreetThree,  '')							AS StreetThree,  
				 ISNULL(VM.StreetFour,  '')							AS StreetFour, 
		
				 --ISNULL(AM.Title,  '')								AS AreaTitle, 
				 --ISNULL(CiM.Title,  ' ')								AS CityTitle, 				 			
				 --ISNULL(SM.Title,  '')								AS StateTitle, 
				 --ISNULL(CoM.Title,  '')								AS CountryTitle, 
				  ISNULL(VM.Area,'') AS AreaTitle,
				  ISNULL(VM.City,'') AS CityTitle,
				  ISNULL(VM.Country,'') AS StateTitle,
				  ISNULL(VM.State,'') AS CountryTitle,	      
				  ISNULL(VM.ZipCode,  '')								AS ZipCode, 
				 
				 GRNR.Number 										AS GoodsReturnNo,  				
				 sCommon.fReportDateGet(GRNR.ReturnDate)			AS GoodsReturnDate1,  
				 
				 
				 GRN.Number											AS GrnNo, 
				 sCommon.fReportDateGet(GRN.CreatedDateTime) 		AS GrnDate1, 
				 PO.Number											AS PoNo, 
				 sCommon.fReportDateGet(	PO.CreatedDateTime)   	AS PoDate1, 
				 GRN.DeliveryOrderNumber							AS DoNo, 
				 sCommon.fReportDateGet(GRNR.DeliveryOrderDate)		AS DoDate1, 
				 SLM.Title											AS ReceivingLocation, 							 
				 
				 SIM.Code											AS ItemNo, 
				 SIM.Title											AS ItemName, 
				 SUOM.Title											AS Uom, 
				 SIPU.ConversionFactor								AS ConversionFactor, 
				(CASE 
					WHEN SIM.IsBatchWiseTracking =  1 THEN
						GRNRB.ReturnQuantity
					ELSE 
						GRNRD.ReturnQuantity
					END)											AS ReturnedQuantity, 
				 (CASE 
					WHEN SIM.IsBatchWiseTracking =  1 THEN
						GRNB.ReceiptBonusQuantity
					ELSE
						GRND.ReceiptBonusQuantity
					END)											AS BonusQty, 
				 (CASE 
					WHEN SIM.IsBatchWiseTracking =  1 THEN
						GRNB.Number
					ELSE
						''
					END)											AS BatchNo, 
				 (CASE 
					WHEN SIM.IsBatchWiseTracking =  1 THEN
						sCommon.fReportDateGet(GRNB.ExpiryDate)	
					ELSE
						''
					END)											AS ExpiryDate1, 
				 ''											AS BinNo, --BM.Code 
				 --CM.Code											AS CurrencyCode,
				 --CM.Title											AS CurrencTitle,
				 RM.Title											AS ReasonTitle,
				 
				 (SELECT ((SUM(ReceiptQuantity)  +  SUM(ReceiptBonusQuantity)) - SUM(ReturnedQuantity)) FROM sProcurement.tGoodsReceiptNoteBatch
				WHERE GoodsReceiptNoteDetailId = GRND.Id) AS BalanceQuantity,			
		
			(SELECT ((SUM(ReceiptQuantity)  +  SUM(ReceiptBonusQuantity)) - SUM(ReturnedQuantity)) FROM sProcurement.tGoodsReceiptNoteBatch
				WHERE GoodsReceiptNoteDetailId = GRND.Id) AS BalanceQuantity,			
		
			CASE WHEN GRND.ReceiptQuantity > 0 THEN (GRND.NetUnitPrice / GRND.ReceiptQuantity)
			ELSE GRND.NetUnitPrice END
			AS UnitPrice,

			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) AS Amount,
				 
				 
				 
				 (CASE 
				  WHEN SIM.IsBatchWiseTracking =  1 THEN
				  --CAST((GRNRB.ReturnQuantity * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  2))	
				  CAST((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
					ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)	 * (GRND.DiscountPercentage/100)AS DECIMAL(22,  6))
				  ELSE 

				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
				  END)																								AS  DiscountAmount, 
			
			--Tax Amount = (netUnitPrice - discountAmount) * (TaxRate / 100);
			(
			--Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)			
			 --Disc. Amount
			- (CASE 
				  WHEN SIM.IsBatchWiseTracking =  1 THEN
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
					ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))		
				  ELSE 
				  --CAST((GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))	
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
				  END)	
			)	
			--TaxRate
			* (GRND.TaxRate/ 100)
			AS TaxAmount,
				 
			/*Old Tax Amount	 
				 
			--(netUnitPrice - discountAmount) * (TaxRate / 100);
			--NetUnitPrice
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRD.ReturnQuantity) END
			- --Disc. Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			* (GRND.DiscountPercentage/100)
			)
			* --(TaxRate / 100)
			(GRND.TaxRate/ 100)
			AS TaxAmount,
			Old Tax Amount*/
			
			--Other Tax Amount
			--CAST(
			(			
			(GRND.OtherTaxAmount/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END)
			)
			--AS DECIMAL(22,  6))				
			AS OtherTaxAmount,
			
				
			/*Old Other Tax Amount	 
			(
			CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.ReceiptQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			ELSE (GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) 
			* (GRND.OtherTaxAmount) 
			END)							
			AS OtherTaxAmount, 
			Old Other Tax Amount*/

			-- --Amount - Disc. Amount  +  Tax Amount  +  Other tax Amount  +  Add ON
			-- --Amount
			----CAST(
			--( 
					
			
			----(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			----ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END
			--(
			
			----CAST(
			--CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) 
			--END 
			----AS DECIMAL(22,  6))
			
			-- -
			-- --Discount Amount
			----(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			----ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			----* (GRND.DiscountPercentage/100)
			--(CASE 
			--	  WHEN SIM.IsBatchWiseTracking =  1 THEN
			--	  --CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--		ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) * (GRND.DiscountPercentage/100)) 
			--		-- AS DECIMAL(22,  6))		
			--	  ELSE 
			--	  --CAST((GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))	
			--	  --CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			--		ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			--		* (GRND.DiscountPercentage/100)) 
			--		--AS DECIMAL(22,  6))	            
			--	  END)	
			--)
			
			--  +  --Tax Amount			
			--((
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			--ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)			
			-- --Disc. Amount
			--- (CASE 
			--	  WHEN SIM.IsBatchWiseTracking =  1 THEN
			--	  --CAST(
			--	  (GRNRB.ReturnQuantity * (GRND.DiscountPercentage/100))  
			--	  --AS DECIMAL(22,  6))		
			--	  ELSE 
				  	
			--	  --CAST(
			--	  ((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			--		WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			--		ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			--		* (GRND.DiscountPercentage/100)) 
			--		--AS DECIMAL(22,  6))	            
			--	  END)	
			--)	
			--* (GRND.TaxRate/ 100))
			
					 
			--  +  --Other tax Amount
			----CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.ReceiptQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			----ELSE (GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount) END
			----CAST(
			--(			
			--(GRND.OtherTaxAmount/ GRND.ReceiptQuantity) *
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			--ELSE (GRNRB.ReturnQuantity) END)
			--)
			----AS DECIMAL(22,  6))
			-- +  --Add ON
			 
			----CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <= GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			----WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			----ELSE (GRND.AddOnCharges * GRNRD.ReturnQuantity) END 
			----CAST(
			--(			
			--(GRND.AddOnCharges/ GRND.ReceiptQuantity) *
			--(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			--WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			--ELSE (GRNRB.ReturnQuantity) END)
			--)
			----AS DECIMAL(22,  6))
			
			--)
			----AS DECIMAL(22,  6)) 
			--AS TotalAmountReturned1,
			
			/* Old AddOnCharges
			ISNULL((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.AddOnCharges * GRNRD.ReturnQuantity) END), 0)																AS AddOnCharges, 
			*/
				
			(			
			(GRND.AddOnCharges/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END)
			)	
			AS AddOnCharges, 
			
			/**Sub Total Amount Returned Start**/
			--Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)
			
			--DiscountAmount
			-	 
			(CASE WHEN SIM.IsBatchWiseTracking =  1 THEN				  
				 CAST((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
				 WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
				 ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)	 * (GRND.DiscountPercentage/100)AS DECIMAL(22,  6))
			 ELSE 
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
			END)	
			
			--Tax Amount = (netUnitPrice - discountAmount) * (TaxRate / 100);
			+
			
			(--Amount
			((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END)			
			--Disc. Amount
			- 
			(CASE WHEN SIM.IsBatchWiseTracking =  1 THEN
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
					ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END) * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))		
				  ELSE 
				  --CAST((GRNRD.ReturnQuantity * (GRND.DiscountPercentage/100))  AS DECIMAL(22,  6))	
				  CAST(((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity <=  GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
					WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
					ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
					* (GRND.DiscountPercentage/100)) AS DECIMAL(22,  6))	            
				  END)	
			)
			--TaxRate
			* (GRND.TaxRate/ 100)
			)
			
			--Other Tax Amount
			+ 
			((GRND.OtherTaxAmount/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END))
			
			--AddOnCharges
			+ 
			(			
			(GRND.AddOnCharges/ GRND.ReceiptQuantity) *
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =  GRND.ReceiptQuantity) THEN (GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN (GRND.ReceiptQuantity)
			ELSE (GRNRB.ReturnQuantity) END)
			)	
			
			AS TotalAmountReturned1,
			/**Sub Total Amount Returned End**/
				
		
				GRNR.Remark AS Remarks, 			 
				U.DisplayTitle AS GeneratedBy

							  
		FROM		sProcurement.tGoodsReceiptNoteReturn GRNR
					INNER JOIN sProcurement.tGoodsReceiptNoteReturnDetail GRNRD
						ON GRNRD.GoodsReceiptNoteReturnId =  GRNR.Id  AND GRNRD.ReturnQuantity > 0
					INNER JOIN sProcurement.tGoodsReceiptNoteReturnBatch GRNRB
						ON GRNRB.GoodsReceiptNoteReturnDetailId =  GRNRD.Id	AND GRNRB.ReturnQuantity > 0	
					INNER JOIN sProcurement.tGoodsReceiptNote GRN
						ON GRN.Id =  GRNR.GoodsReceiptNoteId
					INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND
						ON GRND.GoodsReceiptNoteId =  GRN.Id
							AND GRNRD.GoodsReceiptNoteDetailId =  GRND.Id
					INNER JOIN sProcurement.tGoodsReceiptNoteBatch GRNB
						ON GRNB.GoodsReceiptNoteDetailId =  GRND.Id									
							AND GRNRB.GoodsReceiptNoteBatchId =  GRNB.Id
					INNER JOIN sProcurement.tPurchaseOrder PO
						ON GRN.PurchaseOrderId =  PO.Id
					INNER JOIN sProcurement.tVendorMaster VM
						ON VM.Id =  PO.VendorId
					INNER JOIN sIp.tStoreLocationMaster SLM
						ON SLM.Id =  PO.StoreLocationId
					
					INNER JOIN sProcurement.tPurchaseOrderDetail POD
						ON POD.PurchaseOrderId =  PO.Id
						AND POD.Id =  GRND.PurchaseOrderDetailId
					INNER JOIN sIp.tStockItemMaster SIM
						ON SIM.Id =  POD.ItemSourceId
					--LEFT JOIN sIp.tBinMaster BM
						--ON BM.Id =  SIM.BinId
					INNER JOIN sIp.tStockItemPurchaseUom SIPU						
						ON SIPU.Id =  POD.StockItemPurchaseUomId 
					INNER JOIN sFinanceCommon.tStockUomMaster SUOM
						ON SUOM.Id =  SIPU.StockUomId
					INNER JOIN sSecurity.tUser U
						ON U.Id =  GRN.CreatedUserId
					--INNER JOIN sFinanceCommon.tCurrencyMaster CM
					--	ON PO.CurrencyId = CM.Id
					INNER JOIN sCommon.tReasonMaster RM
						ON RM.Id = GRNRD.ReasonId
					
					--LEFT JOIN	sCommon.tAreaMaster AM
					--			ON AM.Id =  VM.AreaId
					--LEFT JOIN	sCommon.tCityMaster CiM
					--			ON CiM.Id =  VM.CityId
					--LEFT JOIN	sCommon.tStateMaster SM
					--			ON SM.Id =  VM.StateId
					--LEFT JOIN	sCommon.tCountryMaster CoM
					--			ON CoM.Id =  VM.CountryId
					
			WHERE ((GRNR.Id =  @rGRNId) OR (ISNULL(@rGRNId,  0) =  0))
				AND ((GRNR.Number =  @rGRNNo) OR (ISNULL(@rGRNNo,  '') =  ''))
				AND GRNR.OrgGroupId = @rOrgGroupId
		
			ORDER BY GRNRD.Id ASC 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptGoodsReturnNoteListing]
	@rOrgGroupId Int,
	@rFromDate [datetime] = '',
	@rToDate [datetime] = '',
	@rDepartmentId [int] = 0,
	@rVendorId [int] = 0,
	--@rCreditReceived [smallint] = 0,	
	@rReportType [smallint] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN 
--DECLARE @lGrenValue AS DECIMAL(22, 6)
SELECT	DISTINCT   
--GRNRD.Id,
--PCNID.Id,	
--********************************************************************************************************************
 																							
	 
		(CASE 
			WHEN SIM.IsBatchWiseTracking  =   1 THEN
			--Amount
			CAST((CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity <  =   GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END		
			-
			 --Discount Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			ELSE ((GRND.NetUnitPrice) * (GRNRB.ReturnQuantity))  END)
			* (GRND.DiscountPercentage/100)
			
			
			 +  (
			 --Tax Amount  =   (netUnitPrice - discountAmount) * (TaxRate / 100);
			
					(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRB.ReturnQuantity) END
			- --Disc. Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRB.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			ELSE ((GRND.NetUnitPrice) * (GRNRB.ReturnQuantity))  END)
			* (GRND.DiscountPercentage/100)
			)
			* --(TaxRate / 100)
			(GRND.TaxRate/ 100)	
			
			)	
			  +  --Other tax Amount
			CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRNRB.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRB.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.ReceiptQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			ELSE (GRNRB.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount) END	 
			 +  --Add ON
			CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.AddOnCharges * GRNRD.ReturnQuantity) END)
			AS DECIMAL(22,  2))
			ELSE CAST((				 
			 --Amount - Disc. Amount  +  Tax Amount  +  Other tax Amount  +  Add ON
			 --Amount
			 CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRD.ReturnQuantity) END
			 -
			 --Discount Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			* (GRND.DiscountPercentage/100)
			
			  +  --Tax Amount
					(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice/ GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.NetUnitPrice* GRNRD.ReturnQuantity) END
			- --Disc. Amount
			(CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.NetUnitPrice / GRND.ReceiptQuantity) * GRND.ReceiptQuantity)
			ELSE ((GRND.NetUnitPrice) * (GRNRD.ReturnQuantity))  END)
			* (GRND.DiscountPercentage/100)
			)
			* --(TaxRate / 100)
			(GRND.TaxRate/ 100)			 
			  +  --Other tax Amount
			CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.ReceiptQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount))
			ELSE (GRNRD.ReturnQuantity/ GRND.ReceiptQuantity) * (GRND.OtherTaxAmount) END
			 +  --Add ON
			CASE WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity < =   GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRNRD.ReturnQuantity)
			WHEN (GRND.ReceiptQuantity > 0 AND GRNRD.ReturnQuantity > GRND.ReceiptQuantity) THEN ((GRND.AddOnCharges / GRND.ReceiptQuantity)* GRND.ReceiptQuantity)
			ELSE (GRND.AddOnCharges * GRNRD.ReturnQuantity) END 
				 )AS DECIMAL(22,  6))     	
            END																							   
	 
	) AS GRENValue,																		   
--*************************************************For Criteria*******************************************************			
				(CASE	@rFromDate
					WHEN '' THEN 'All'
					ELSE sCommon.fReportDateGet(@rFromDate)
					END)														AS ParamFromDate, 
				
				(CASE	@rToDate
					WHEN '' THEN 'All'
					ELSE sCommon.fReportDateGet(@rToDate)
					END)														AS ParamToDate,  --Convert(Nvarchar(50), @rToDate, 101)
				
				(CASE	@rVendorId
					WHEN 0 THEN 'All'
					ELSE VM.Title
					END)							
																				AS ParamVendor, 
				
				(CASE	@rDepartmentId
					WHEN 0 THEN 'All'
					ELSE ODM.Title
					END)														AS ParamDepartment,	
				
				--(CASE	@rCreditReceived
				--	WHEN 0 THEN 'All'
				--	WHEN 1 THEN 'YES'
				--	WHEN 2 THEN 'NO'
				--	END)														AS ParamCreditReceived,	
					
 
					
				(CASE	@rReportType
					WHEN 0 THEN 'Summary'
					WHEN 1 THEN 'Detail'
					END)														AS ParamReportType,	
--****************************************For Detail Display******************************************************
			--SELECT 
 
				 GRNR.Number 										AS GoodsReturnNo,  				
				 sCommon.fReportDateGet(GRNR.ReturnDate)			AS GoodsReturnDate,  
				 PO.Number											AS PoNo,
				 VM.Title											AS VendorName, 
				 SIM.Title											AS ItemName,
				 (GRNRD.ReturnQuantity * SIPUOM.ConversionFactor)   AS ReturnedQuantity,			
				 SIPUOM.ConversionFactor							AS ConversionFactor, 
	 
				(ISNULL(GRND.NetUnitPrice/GRND.ReceiptQuantity, 0)/ SIPUOM.ConversionFactor)AS UnitPrice, 
				 									
				 (POD.OrderQuantity	* SIPUOM.ConversionFactor)		AS POQuantity,
				 --(CASE
					--WHEN PO.CurrencyId  =  (SELECT ForeignCurrencyId FROM sCommon.tCompanyInformation) 
					--	THEN (ISNULL(GRNRD.ReturnQuantity, 0) * ISNULL(GRND.NetUnitPrice / GRND.ReceiptQuantity, 0))/ CRM.Rate
					--ELSE 
					--	(ISNULL(GRNRD.ReturnQuantity, 0) * ISNULL(GRND.NetUnitPrice / GRND.ReceiptQuantity, 0))
					--END
				 -- ) AS POValue,
				  

					 
								 (POD.OrderQuantity  * POD.NetUnitPrice - POD.DiscountAmount + POD.TaxAmount + POD.OtherTaxAmount) AS POValue
				--ELSE (POD.OrderQuantity  * POD.NetUnitPrice - POD.DiscountAmount + POD.TaxAmount + POD.OtherTaxAmount) END 
				  
				  
				 
 
  
		  
		FROM		sProcurement.tGoodsReceiptNoteReturn GRNR
					INNER JOIN sProcurement.tGoodsReceiptNoteReturnDetail GRNRD
						ON GRNRD.GoodsReceiptNoteReturnId  =   GRNR.Id  AND GRNRD.ReturnQuantity > 0
					INNER JOIN sProcurement.tGoodsReceiptNoteReturnBatch GRNRB
						ON GRNRB.GoodsReceiptNoteReturnDetailId  =   GRNRD.Id	AND GRNRB.ReturnQuantity > 0	
					INNER JOIN sProcurement.tGoodsReceiptNote GRN
						ON GRN.Id  =   GRNR.GoodsReceiptNoteId
					INNER JOIN sProcurement.tGoodsReceiptNoteDetail GRND
						ON GRND.GoodsReceiptNoteId  =   GRN.Id
							AND GRNRD.GoodsReceiptNoteDetailId  =   GRND.Id					
					INNER JOIN sProcurement.tPurchaseOrder PO
						ON GRN.PurchaseOrderId  =   PO.Id
					INNER JOIN sProcurement.tVendorMaster VM
						ON VM.Id  =   PO.VendorId					
					INNER JOIN sProcurement.tPurchaseOrderDetail POD
						ON POD.PurchaseOrderId  =   PO.Id
						AND POD.Id  =   GRND.PurchaseOrderDetailId
					INNER JOIN sIp.tStockItemMaster SIM
						ON SIM.Id  =   POD.ItemSourceId
					INNER JOIN sIp.tStockItemPurchaseUom SIPU						
						ON SIPU.Id  =   POD.StockItemPurchaseUomId 
					INNER JOIN sSecurity.tUser U
						ON U.Id  =   GRN.CreatedUserId					 
					INNER JOIN sSetup.tDepartmentMaster ODM
						ON PO.RequestedOrganizationDepartmentId  =  ODM.Id
					INNER JOIN sIp.tStockItemPurchaseUom SIPUOM 
						ON SIPUOM.Id = POD.StockItemPurchaseUomId			
					--LEFT JOIN(SELECT GoodsReceiptNoteReturnDetailId, EPCNI.Id, EPCNI.Number, EPCNI.Amount, EPCNI.StatusId FROM sAccountsPayable.vExtPurchaseCreditNoteItemDetail PCNID 
					--			INNER JOIN  sAccountsPayable.vExtPurchaseCreditNoteItem EPCNI
					--			ON  EPCNI.Id =  PCNID.PurchaseCreditNoteItemId
					--			WHERE  ParentPurchaseCreditNoteItemId IS NOT NULL) PCNI
					--	ON GRNRD.Id  =  PCNI.GoodsReceiptNoteReturnDetailId
					----LEFT JOIN (SELECT Id, Number, Amount, StatusId FROM sAccountsPayable.vExtPurchaseCreditNoteItem WHERE  ParentPurchaseCreditNoteItemId IS NOT NULL) PCNI
					----	ON PCNID.PurchaseCreditNoteItemId  =  PCNI.Id 			
					--LEFT JOIN sCash.vExtReceiptVoucherWithDetails RVD
					--	ON PCNI.Id  =  RVD.DocumentSourceId AND RVD.DocumentSourceTypeId  =  55
				
					
			WHERE 
			 (GRNR.CreatedDateTime BETWEEN CAST(@rFromDate AS DATE) AND CASE WHEN @rToDate = CAST('1900-01-01' AS DATE) THEN DATEADD(DD, 1, sCommon.fGetDate()) ELSE  DATEADD(DD, 1, @rToDate) END)
			AND 
			((PO.VendorId  =  @rVendorId) OR (@rVendorId  =  0))
			AND ((PO.RequestedOrganizationDepartmentId  =  @rDepartmentId) OR (@rDepartmentId  =  0))
			AND GRNR.OrgGroupId = @rOrgGroupId
			AND GRNR.StoreLocationId=@rStoreLocationId
		
			--AND  (ROUND(ISNULL(PCNI.Amount, 0), 2) = ISNULL((CASE WHEN @rCreditReceived = 1 THEN (SELECT ISNULL(SUM(ISNULL(RVD.Amount, 0)), 0) 
			--																	   FROM sCash.vExtReceiptVoucherWithDetails RVD 
			--																	   INNER JOIN sAccountsPayable.vExtPurchaseCreditNoteItem PCNI 
			--																	   ON RVD.DocumentSourceId  =  PCNI.Id 
			--																	   INNER JOIN sAccountsPayable.vExtPurchaseCreditNoteItemDetail PCNID
			--																	   ON PCNI.Id = PCNID.PurchaseCreditNoteItemId																				   
			--																	   WHERE RVD.DocumentSourceTypeId  =  55 AND PCNID.GoodsReceiptNoteReturnDetailId = GRNRD.ID
			--																	   GROUP BY RVD.DocumentSourceTypeId--, RVD.DocumentSourceId 
			--																	   )					   
			--												 ELSE ROUND(ISNULL(PCNI.Amount, 0), 2) END), 0) OR @rCreditReceived = 0) 
															
		 --   AND  (ROUND(ISNULL(PCNI.Amount, -1), 2) <> ISNULL((CASE WHEN @rCreditReceived = 2 THEN (SELECT ISNULL(SUM(ISNULL(RVD.Amount, 0)), 0) 
			--																	   FROM sCash.vExtReceiptVoucherWithDetails RVD 
			--																	   INNER JOIN sAccountsPayable.vExtPurchaseCreditNoteItem PCNI 
			--																	   ON RVD.DocumentSourceId  =  PCNI.Id 
			--																	   INNER JOIN sAccountsPayable.vExtPurchaseCreditNoteItemDetail PCNID
			--																	   ON PCNI.Id = PCNID.PurchaseCreditNoteItemId																				   
			--																	   WHERE RVD.DocumentSourceTypeId = 55 
			--																	   AND PCNID.GoodsReceiptNoteReturnDetailId = GRNRD.ID
			--																	   GROUP BY RVD.DocumentSourceTypeId--, RVD.DocumentSourceId 
			--																	   )					   
			--												 ELSE -1 END), 0) OR @rCreditReceived = 0)
															
										
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptPurchaseOrder]
	@rOrgGroupId int,
	@rPurchOrderNo [nvarchar](20) = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
  SELECT POD.ItemSourceTypeId,
		 PO.Number AS PONo, 
         PO.CreatedDateTime AS PODate,
         PO.Remark AS PORemarks, PO.RequestedByName AS RequestedBy,
         PO.PaymentDays AS PaymDays,
         VM.Code AS VendorNo, VM.Title AS VendorName, 
         --(CASE WHEN VM.CreditDays = 0 THEN '' ELSE CAST(VM.CreditDays AS NVARCHAR(20) ) END)AS Terms, 
         PO.PaymentDays AS Terms,          
         ISNULL(VM.StreetOne, '') AS StreetOne, ISNULL(VM.StreetTwo, '') AS StreetTwo,  
         ISNULL(VM.StreetThree, '') AS StreetThree, ISNULL(VM.StreetFour, '') AS StreetFour,         
          ISNULL(VM.Area,'') AS AreaTitle,
		  ISNULL(VM.City,'') AS CityTitle,
		  ISNULL(VM.Country,'') AS StateTitle,
		  ISNULL(VM.State,'') AS CountryTitle,	         
         POD.OrderQuantity AS OrderQty, 
         
          -- POD.ItemSourceTypeId, POD.ItemSourceId,
                 --
           (CASE  POD.ItemSourceTypeId 
             WHEN 25 THEN
               (SELECT SrvTM.Code FROM sOrderEntry.vExtServiceItemTypeMaster AS SrvTM WHERE SrvTM.id = POD.ItemSourceId AND OrgGroupId = @rOrgGroupId)
             WHEN 34 THEN
               (SELECT STIM.Code FROM sIp.tStockItemMaster AS STIM WHERE STIM.id = POD.ItemSourceId AND OrgGroupId = @rOrgGroupId)
           END) AS ItemNo,
           
			(CASE  POD.ItemSourceTypeId 
             WHEN 25 THEN
               (SELECT SrvTM.Title FROM sOrderEntry.vExtServiceItemTypeMaster AS SrvTM WHERE SrvTM.id = POD.ItemSourceId AND SrvTM.OrgGroupId = @rOrgGroupId)
             WHEN 34 THEN
               (SELECT STIM.Title FROM sIp.tStockItemMaster AS STIM WHERE STIM.id = POD.ItemSourceId AND STIM.OrgGroupId = @rOrgGroupId)
           END) AS ItemDesc,                    
           --
           POD.NetUnitPrice AS UnitPrice, (POD.OrderQuantity * POD.NetUnitPrice) AS Amnt,
           (POD.orderquantity + POD.bonusquantity) AS TotalQty,
               POD.BonusQuantity AS BonusQty,
               POD.DiscountAmount AS DiscAmnt,
               POD.DiscountPercentage AS DiscPerc, POD.TaxAmount AS TaxAmnt,
                 POD.TaxRate AS PTaxRate,
              (SELECT TGM1.code FROM sTax.vExtTaxGroupMaster AS TGM1 WHERE
                   TGM1.Id = POD.TaxGroupId) AS TaxGroupCode,
                  POD.OtherTaxAmount AS OtherTaxAmnt,
                  PO.DiscountAmount AS PODiscAmnt,
           (POD.orderquantity * POD.NetUnitPrice + POD.TaxAmount
                    + POD.OtherTaxAmount - POD.DiscountAmount) AS NetAmnt,    
                    PO.RoundedNetAmount AS RoundedNetAmnt,                
         --ACCM.Code AS AccountNo,  
         SUOM.Title AS UOM,
         OrgDeptM.Title AS ReqByDeptName,
         SLM.Title AS ShipTo,
         --CurrM.Title AS FCY,
         0 AS CurrExchRate,
          --CurrM.Title AS LCY,
         PO.StatusId
	FROM   sProcurement.tPurchaseOrder AS PO
  INNER JOIN  sProcurement.tPurchaseOrderDetail  AS POD
  ON POD.PurchaseOrderId = PO.Id        
  --LEFT JOIN sFinanceCommon.tCurrencyMaster AS CurrM
  --ON CurrM.Id = PO.CurrencyId 
  LEFT JOIN sProcurement.tVendorMaster AS VM
  ON VM.Id = PO.VendorId  
  INNER JOIN sIP.tStockItemPurchaseUom SIPU
  ON SIPU.Id = POD.StockItemPurchaseUomId
  INNER JOIN sFinanceCommon.tStockUomMaster SUOM
  ON SUOM.Id = SIPU.StockUOmId
  --LEFT JOIN sFinanceCommon.tStockUomMaster AS SUOM
  --ON SUOM.Id = POD.StockItemPurchaseUomId 
  LEFT JOIN sProcurement.tVendorCategoryMaster AS VCM
  ON VCM.Id = VM.VendorCategoryId  
  --LEFT JOIN sAccounting.tAccountMaster AS ACCM
  --ON ACCM.Id = VCM.AccountId
  LEFT JOIN sIp.tStoreLocationMaster AS SLM
  ON PO.ShipToStoreLocationId = SLM.Id
  LEFT JOIN sSetup.tDepartmentMaster AS OrgDeptM
  ON PO.RequestedOrganizationDepartmentId = OrgDeptM.Id  
    WHERE	((PO.Number = @rPurchOrderNo) OR (ISNULL(@rPurchOrderNo, '') = ''))
     AND POD.IsObsolete = 0 AND PO.OrgGroupId = @rOrgGroupId
			AND PO.StoreLocationId=@rStoreLocationId
    END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptPurchaseOrderListing]
	@rOrgGroupId int,
	@rStartDate [date] = '1/1/1900',
	@rEndDate [date] = '1/1/1900',
	@rDepartmentId [int] = 0,
	@rVendorId [int] = 0,
	@rPoStatusId [int] = 0,
	@rReportType [tinyint] = 0,
	@rStorelocationId int
WITH EXECUTE AS CALLER
AS
BEGIN
		SET NOCOUNT ON
		SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
		SELECT 
				PO.Number, 
				PO.UpdatedDateTime  AS PoDate,
				CASE WHEN @rVendorId = 0 THEN 'All' ELSE VM.Title END AS VendorHeaderName, 
				VM.Title VendorName,
				SIM.Title ItemDescription,
				POD.RequestedDeliveryDate,
				POD.OrderQuantity,
			    POD.NetUnitPrice AS NetUnitPrice,
			   (POD.OrderQuantity  * POD.NetUnitPrice - POD.DiscountAmount + POD.TaxAmount + POD.OtherTaxAmount)  AS ItemValue,
				CAST(@rStartDate AS DATE) AS StartDate,
				CAST(@rEndDate AS DATE) AS EndDate,
				CASE WHEN @rPoStatusId = 1 THEN 'Pending' ELSE (CASE WHEN @rPoStatusId = 2 THEN 'Completed' ELSE (CASE WHEN @rPoStatusId = 3 THEN 'Partial' ELSE 'All' END) END) END AS PoStatus12,				
				@rReportType AS IsDetail,
				CASE WHEN @rReportType = 0 THEN 'Summary' ELSE 'Detail' END AS ReportType,
				CASE WHEN @rDepartmentId = 0 THEN 'All' ELSE ODM.Title END AS Department,				 
				PRQ.OrderQuantity,
				PRQ.ReceivedOrderQuantity
												
		FROM 
				sProcurement.tPurchaseOrder PO
		LEFT JOIN
				sProcurement.tPurchaseOrder PO1 
		ON
				PO1.ID = PO.ParentPurchaseOrderId 
		INNER JOIN
				sProcurement.tPurchaseOrderDetail POD
		ON
				POD.PurchaseOrderId = PO.Id
		INNER JOIN
				sIp.tStockItemMaster SIM
		ON
				SIM.Id = POD.ItemSourceId
		INNER JOIN
				sProcurement.tVendorMaster VM
		ON
				PO.VendorId = VM.Id
		INNER JOIN
				sSetup.tDepartmentMaster ODM
		ON
				PO.RequestedOrganizationDepartmentId = ODM.Id
 
		LEFT JOIN (SELECT PurchaseOrderId, SUM(OrderQuantity) OrderQuantity,  SUM(ReceivedOrderQuantity) ReceivedOrderQuantity
							FROM sProcurement.tPurchaseOrderDetail POD WHERE OrgGroupId = @rOrgGroupId
				   GROUP BY POD.PurchaseOrderId ) PRQ
		ON
			PRQ.PurchaseOrderId = PO.Id
		WHERE 
			PO.UpdatedDateTime BETWEEN CAST(@rStartDate AS DATE) AND CASE WHEN @rEndDate = CAST('1900-01-01' AS DATE) THEN DATEADD(DD, 1, sCommon.fGetDate()) ELSE  DATEADD(DD, 1, @rEndDate) END
			AND ((PO.RequestedOrganizationDepartmentId  = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((PO.VendorId = @rVendorId) OR (@rVendorId = 0))
			--AND ((PO.StatusId = @rPoStatusId) OR (@rPoStatusId = 0)) 		 
			AND PO.ParentPurchaseOrderId IS NOT NULL
			AND ((@rPOStatusId  = 1 AND PRQ.ReceivedOrderQuantity = 0)
				OR (@rPOStatusId = 2 AND (PRQ.OrderQuantity - ISNULL(PRQ.ReceivedOrderQuantity, 0)) = 0)  
					OR (@rPOStatusId = 3 AND (PRQ.OrderQuantity - ISNULL(PRQ.ReceivedOrderQuantity, 0)) <> 0 AND ISNULL(PRQ.ReceivedOrderQuantity, 0) > 0) 
						OR (@rPOStatusId = 0))
			AND PO.OrgGroupId = @rOrgGroupId
			AND PO.StoreLocationId=@rStorelocationId
		
		
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockAdjustmentRegisterGet]
  @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,
	@rFromRegisterNo int = 0,		-- #Start Mantis Id : 0035096
	@rToRegisterNo int = 0,			
	@rFromRegisterNoYear int = 0,
	@rToRegisterNoYear int = 0		-- #End Mantis Id : 0035096
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
				SIM.Code AS ItemCode,
				SIM.Title AS ItemName,		
				SI.Number AS Billno, 	
				SI.CreatedDateTime AS IssuedDate,
				ID.SystemQuantity,
				ID.PhysicalQuantity,
				 
				SB.ExpiryDate,
				--SB.Price AS Amount,
				SB.Number As BatchNumber,
				SI.Id,
				@rDetail AS Detail,
				@rBuilder1 As Builder1,
				@rBuilder2 AS Builder2,
				SIM.IsObsolete
				
		FROM  sProcurement.tStockAdjustment SI		
		INNER JOIN sProcurement.tStockAdjustmentDetail ID ON SI.Id = ID.StockAdjustmentId 
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
	    LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = ID.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	
		 
		  WHERE	     
	     --SIM.IsObsolete=0
		  (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) >= CAST(@rFromDate AS DATE)) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((CAST(SI.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(@rToDate,'') = '') )
		AND (SB.OrgGroupId = @rOrgGroupId)
		-- #Start Mantis Id : 0035096
		AND ((SI.Number IS NOT NULL AND LEN(SI.Number) >= 6 AND ISNUMERIC(SUBSTRING(SI.Number, 3, 2)) = 1 AND ISNUMERIC(SUBSTRING(SI.Number, 6, LEN(SI.Number) - 5)) = 1 
			AND (CAST(SUBSTRING(SI.Number, 3, 2) AS INT) > @rFromRegisterNoYear OR (CAST(SUBSTRING(SI.Number, 3, 2) AS INT) = @rFromRegisterNoYear AND CAST(SUBSTRING(SI.Number, 6, LEN(SI.Number) - 5) AS INT) >= @rFromRegisterNo)))
			OR @rFromRegisterNoYear = 0 OR @rFromRegisterNo = 0)
		AND ((SI.Number IS NOT NULL AND LEN(SI.Number) >= 6 AND ISNUMERIC(SUBSTRING(SI.Number, 3, 2)) = 1 AND ISNUMERIC(SUBSTRING(SI.Number, 6, LEN(SI.Number) - 5)) = 1 
			AND (CAST(SUBSTRING(SI.Number, 3, 2) AS INT) < @rToRegisterNoYear OR (CAST(SUBSTRING(SI.Number, 3, 2) AS INT) = @rToRegisterNoYear AND CAST(SUBSTRING(SI.Number, 6, LEN(SI.Number) - 5) AS INT) <= @rToRegisterNo)))
			OR @rToRegisterNoYear = 0 OR @rToRegisterNo = 0)
		-- #End Mantis Id : 0035096
		 
    Order  by SIM.Title	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockAudit]
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN

DECLARE @lCount INT
DECLARE @lStockItemId INT
CREATE TABLE #tmpStockItemId
(
	Id INT IDENTITY (1, 1),  
	StockItemId INT
)


CREATE TABLE #tmpStockItemBin
(
	StockItemId INT,  
	BinNumber NVARCHAR(300) 
)

INSERT INTO #tmpStockItemId SELECT DISTINCT StockItemId FROM sIp.tStockItemBin

DECLARE @lBinNumber varchar(max)
SET @lBinNumber = '' 

SELECT @lCount =  COUNT(StockItemId) FROM #tmpStockItemId

WHILE @lCount > 0 
	BEGIN
	 SELECT  @lStockItemId = StockItemId FROM #tmpStockItemId WHERE Id = @lCount
	 SELECT @lBinNumber =  @lBinNumber + ', ' + CAST(BM.Title AS VARCHAR(50))  FROM sIp.tBinMaster BM
				INNER JOIN sIp.tStockItemBin SIB
					ON SIB.BinId = BM.Id 
						WHERE SIB.StockItemId = @lStockItemId
	 SET @lCount = @lCount - 1
		INSERT INTO #tmpStockItemBin VALUES(@lStockItemId, @lBinNumber)
	SET @lBinNumber = ''
END


SELECT  
		SIM.Code AS ItemNo,
		SIM.Title  AS ItemName,
		SIM.StandardPrice,
		SAD.PhysicalQuantity,
		SAD.SystemQuantity,
		LOC.Title AS Location,
		SUD.Number,
		SUBSTRING(BM.BinNumber, 2, LEN(BM.BinNumber)) AS BinRef, 
		SUD.CreatedDateTime,
		(SAD.PhysicalQuantity-SAD.SystemQuantity) AS InNos,
		(SIM.WeightedAverageCost*(SAD.PhysicalQuantity-SAD.SystemQuantity)) AS CostValue
				
		FROM sProcurement.tStockAudit SUD
		INNER JOIN sProcurement.tStockAuditDetail SAD 
		ON SAD.StockAuditId = SUD.Id 
		INNER JOIN sIp.tStoreLocationMaster  LOC
		ON LOC.Id = SUD.StoreLocationId 
		INNER JOIN sIp.tStockItemMaster SIM 
		ON SIM.Id = SAD.StockItemId
		LEFT JOIN #tmpStockItemBin BM
		ON SIM.Id = BM.StockItemId	
WHERE SUD.Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockAudjustment]
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
				SIM.Code AS ItemNo,
				SIM.Title AS ItemName,
				SB.Number AS BatchNo,
				LOC.Title AS Location,
				SAD.SystemQuantity,
				SAD.PhysicalQuantity,
				SA.Number,
				SA.CreatedDateTime,				
				SAD.StockBatchId,
				SAD.StoreLocationId,				
				SAD.StockAdjustmentId								
				 				
				FROM sProcurement.tStockAdjustmentDetail SAD
				INNER JOIN sProcurement.tStockAdjustment SA
				ON SAD.StockAdjustmentId = SA.Id
				INNER JOIN sIp.tStoreLocationMaster  LOC
				ON LOC.Id = SAD.StoreLocationId 
				LEFT JOIN sProcurement.tStockBatch SB
				ON SAD.StockBatchId = SB.Id
				INNER JOIN sIp.tStockItemMaster SIM 
				ON SIM.Id = SAD.StockItemId		
				
WHERE SAD.StockAdjustmentId = @rId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockInward]
 
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

   SELECT  
				SIM.Code AS ItemNumber,
				SIM.Title AS ItemName,		
				SI.InwardByName,	
				SI.Number, 	
				case when SI.TransactionDate is not null then  SI.TransactionDate else SI.CreatedDateTime end AS IssuedDate,
		
				ID.InwardQuantity,
				ID.RequestedQuantity,
				
				LM.Title AS FromLocation,
				UOM.Title AS UOM,
				Id.InwardValue		
				
    
    
		FROM  sProcurement.tStockInward SI		
		INNER JOIN sProcurement.tStockInwardDetail ID
		ON SI.Id = ID.StockInwardId
		 
		INNER JOIN sIp.tStoreLocationMaster LM
		ON SI.ToStoreLocationId = LM.Id  
		INNER JOIN sIp.tStockItemMaster SIM
		ON ID.StockItemId  = SIM.Id 
		INNER JOIN sFinanceCommon.tStockUomMaster UOM  
		ON SIM.IssueStockUomId = UOM.Id  	
		
		
		WHERE SI.Id = @rId 
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockInwardGet]
  @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100), 
	@rOrgId int,
	@rFromDate datetime = '',
	@rToDate datetime = ''
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
				SIM.Code AS ItemCode,
				SIM.Title AS ItemName,		
				SI.InwardByName,	
				SI.Number AS Billno, 	
				SI.CreatedDateTime AS IssuedDate,
				ID.InwardQuantity,
				ID.RequestedQuantity,
				 ID.InwardValue,
				--SI.POReference AS POReference,
				--SI.InvoiceReference AS InvoiceReference,
				--VM.Code As SupplierCode,
				--VM.Title As SupplierName,
				SB.ExpiryDate,
				SIP.WeightedAverageCost AS Amount,
				SB.Number As BatchNumber,
				SI.Id AS  StockInwardId
				
		FROM  sProcurement.tStockInward SI		
		INNER JOIN sProcurement.tStockInwardDetail ID ON SI.Id = ID.StockInwardId
		INNER JOIN sProcurement.tStockInwardBatch SIB ON ID.Id = SIB.StockInwardDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
	    LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId
	    --LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id = SI.VendorId
	    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	
		 
		  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 (SIM.IsAllowDirectIssue = ( CASE @rIsAllowDirectIssue WHEN 1 THEN 1 ELSE SIM.IsAllowDirectIssue END))
		--AND (SIM.IsNotInStore = ( CASE @rIsNotInStore WHEN 1 THEN 1 ELSE SIM.IsNotInStore END))
		--AND (SIM.IsBlockedForIssue = ( CASE @rIsBlockedForIssue WHEN 1 THEN 1 ELSE SIM.IsBlockedForIssue END))
		--AND (SIM.IsFirstAdd = ( CASE @rIsFirstAdd WHEN 1 THEN 1 ELSE SIM.IsFirstAdd END))
		--AND ((SI.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) 
		--AND ((SI.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'') = '') )
		 AND (SB.OrgGroupId = @rOrgId)
    Order  by SIM.Title	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockInwardRegisterGet]
   
    @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 datetime = '',
	@rToDate datetime = '',
	@rDetail bit =0,
	@rVendorID int=0,
	@rFromInwardNo int = 0,		-- #Start Mantis Id : 0035096
	@rToInwardNo int = 0,			
	@rFromInwardNoYear int = 0,
	@rToInwardNoYear int = 0		-- #End Mantis Id : 0035096
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
		SIM.Code AS ItemCode,
		SIM.Title AS ItemName,		
		SI.InwardByName,	
		SI.Number AS Billno, 	
		SI.TransactionDate AS IssuedDate,
		ID.InwardQuantity,
		ID.RequestedQuantity,
		SB.ExpiryDate,
		SIP.WeightedAverageCost AS Amount,
		SB.Number As BatchNumber,
		SI.Id AS  StockInwardId,
		@rDetail AS Detail,
		@rBuilder1 As Builder1,
		@rBuilder2 AS Builder2,
		VM.Code AS VendorCOde,
		VM.Title As VendorTitle,
		SB.StoreLocationId,
		SUOM.Title AS UOM,
		SI.CreatedDateTime AS TransactionDate,
		SIReq.CreatedDateTime AS RequestedDate,
		ID.InwardValue
				
  FROM  sProcurement.tStockInward SI		
		INNER JOIN sProcurement.tStockInwardDetail ID ON SI.Id = ID.StockInwardId
		INNER JOIN sProcurement.tStockInwardBatch SIB ON ID.Id = SIB.StockInwardDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
	    LEFT JOIN sProcurement.tStockBatch SB ON SB.StockItemId = SIM.Id
	    LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id = SI.VendorId
	    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	
		INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId 
		LEFT JOIN	sProcurement.tStockInwardRequest SIReq ON SIReq.Id = SI.StockInwardRequestId
		 
  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 ((CONVERT(DATE,SI.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((CONVERT(DATE,SI.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = '') )
		AND (SB.OrgGroupId = @rOrgGroupId)
		AND ((SI.VendorId=@rVendorID) OR (@rVendorId=0))
		-- #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) > @rFromInwardNoYear OR (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) = @rFromInwardNoYear AND CAST(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6) AS INT) >= @rFromInwardNo)))
			OR @rFromInwardNoYear = 0 OR @rFromInwardNo = 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) < @rToInwardNoYear OR (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) = @rToInwardNoYear AND CAST(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6) AS INT) <= @rToInwardNo)))
			OR @rToInwardNoYear = 0 OR @rToInwardNo = 0)
		-- #End Mantis Id : 0035096

    Order  by SIM.Title	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockInwardRequestDetail]
	@rOrgGroupId int,
	@rStockInwardRequestId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT SIRD.Id,
			SIRD.StockInwardRequestId,
			SIRD.StockItemId,
			SIRD.RequestedQuantity,
			SIRD.Remark,
			SIRD.UpdatedUserID,
			SIRD.UpdatedDateTime,
			SIM.Code ItemCode,
			SIM.Title ItemTitle,
			SU.Code UomCode,
			SU.Title UomTitle,
			SU.Id IssueStockUomId,
			SIM.IsBatchWiseTracking,
			SIM.Code StockItemCode,
			SIM.Title StockItemName,
			SU.Title Uom,
		    '' as Number,
			SIRD.InwardQuantity,
			'' ExpiryDate,
			'' As InwardValue,
			SB.AvailableQuantity AS AvailableQuantity,
			--Added by dhananajay for mantis Start : 38948
			SIR.CreatedDateTime AS RequestedDate,
			ISNULL(SIR.RequestedByName,'') AS RequestedBy,
			ISNULL(SIR.Number, '') AS RequestNo,
			SGM.Title AS ItemSubGroup,
			IMGM.Title AS ItemMainGroup
			--Added by dhananajay for mantis End : 38948
	   FROM 
			sProcurement.tStockInwardRequestDetail SIRD
		    INNER JOIN sIP.tStockItemMaster SIM ON SIM.Id = SIRD.StockItemId
		    INNER JOIN sFinanceCommon.tStockUomMaster  SU ON SU.Id = SIM.IssueStockUomId
		    LEFT JOIN sProcurement.tStockBatch SB ON SB.StockItemId=SIm.Id
			--Added by dhananajay for mantis Start : 38948
			INNER JOIN  sIp.tItemSubGroupMaster  SGM ON SIM.ItemSubGroupId = SGM.Id 
			INNER JOIN  sIp.tItemMainGroupMaster IMGM ON IMGM.Id=SGM.ItemMainGroupId
			INNER JOIN  sProcurement.tStockInwardRequest  SIR ON SIR.Id = SIRD.StockInwardRequestId
			--Added by dhananajay forsProcurement.tStockInwardRequest mantis End : 38948
	   WHERE 
		    ((SIRD.StockInwardRequestId = @rStockInwardRequestId) OR (@rStockInwardRequestId = 0))
		    AND SIRD.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockInwardReturn]

	@rId [int] = 0

WITH EXECUTE AS CALLER
AS
BEGIN
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

	SELECT SIR.Id,
			SIR.Number,
			ISNULL(SIR.ReturnByName,'') AS ReturnByName,
			SIR.FromStoreLocationId,
			SIR.Remark,
			SIR.StockInwardId,
			SIRB.StockInwardBatchId,
			SIRB.Quantity,
			SIM.Code AS StockItemCode,
			SIM.Title AS StockItemName,
			SIM.Id AS StockItemId,
			SIB.StockBatchId AS BatchId,
			SIR.CreatedUserId,
			SI.Number AS InwardNumber,
			SIND.InwardQuantity,
			SIND.InwardValue,
			RM.Title AS ReasonName,
			case when SIR.TransactionDate is not null then SIR.TransactionDate else SIR.CreatedDateTime end as CreatedDateTime

	FROM sProcurement.tStockInwardReturn SIR
		INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id
		INNER JOIN sProcurement.tStockInwardBatch SIB ON SIB.Id=SIRB.StockInwardBatchId
		INNER JOIN sProcurement.tStockInwardDetail SIND ON SIND.Id=SIB.StockInwardDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
		INNER JOIN sProcurement.tStockInward SI ON SI.Id=SIR.StockInwardId
		LEFT JOIN sCommon.tReasonMaster RM ON RM.Id=SIRB.ReasonId	--mantis: 35818, change INNER JOIN => LEFT JOIN

	WHERE SIR.Id = @rId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockInwardReturnRegisterGet]
  @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 datetime = '',
	@rToDate datetime = '',
	@rDetail bit =0
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
				SIM.Code AS ItemCode,
				SIM.Title AS ItemName,		
				SI.ReturnByName,	
				SI.Number AS Billno, 	
				SI.CreatedDateTime AS IssuedDate,
				SIRB. Quantity AS InwardQuantity,
				 
				VM.Code As SupplierCode,
				VM.Title As SupplierName,
				 SB.ExpiryDate,
				 SB.ItemRate AS Amount,
				--SB.Number As BatchNumber,
				SI.Id, 
				@rDetail AS Detail,
				@rBuilder1 As Builder1,
				@rBuilder2 AS Builder2
				
	  FROM  sProcurement.tStockInwardReturn SI
		INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SI.Id
		INNER JOIN sProcurement.tStockInwardBatch SIB ON SIB.Id=SIRB.StockInwardBatchId
		INNER JOIN sProcurement.tStockInwardDetail SIND ON SIND.Id=SIB.StockInwardDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON SIND.StockItemId  = SIM.Id 
		LEFT JOIN sProcurement.tStockBatch SB ON SB.StockItemId = SIM.Id
	    LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id = SIM.VendorId
	    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	
		 
		  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 ((SI.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((SI.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'') = '') )
		AND SI.OrgGroupId=@rOrgGroupId
		----AND (SB.OrgId = @rOrgId)
		 
    Order  by SIM.Title	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockIssue]
 
	@rId [int] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

   SELECT  
				SIM.Code AS ItemNumber,
				SIM.Title AS ItemName,		
				SI.IssuedByName,	
				SI.Number, 	
				SI.CreatedDateTime AS IssuedDate,
				ID.IssuedQuantity,
				ID.RequestedQuantity,
				ISNULL(DM.Title,'') AS ToDepartment,
				ISNULL(LM.Title,'') AS FromLocation,
				UOM.Title AS UOM,
				(SIP.WeightedAverageCost*ID.IssuedQuantity) AS IssueValue,
				ISNULL(SI.FirstAidId,0) AS FirstAidId,
				FAM.Title AS FirstAidName,
				SI.TransactionDate
    
		FROM  sProcurement.tStockIssue SI		
		INNER JOIN sProcurement.tStockIssueDetail ID
		ON SI.Id = ID.StockIssueId
		LEFT JOIN sSetup.tDepartmentMaster DM
		ON SI.ToOrganizationDepartmentId = DM.Id  
		INNER JOIN sIp.tStoreLocationMaster LM
		ON SI.FromStoreLocationId = LM.Id  
		INNER JOIN sIp.tStockItemMaster SIM
		ON ID.StockItemId  = SIM.Id 
		INNER JOIN sIp.tStockItemPlanning SIP
		ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
		INNER JOIN sFinanceCommon.tStockUomMaster UOM  
		ON SIM.IssueStockUomId = UOM.Id
		LEFT JOIN sCommon.tFirstAidMaster FAM 
		ON FAM.Id=SI.FirstAidId  	
		
		
		WHERE SI.Id = @rId 
			
END




/****** Object:  StoredProcedure [sProcurement].[pRptStockItemMaxInventory]    Script Date: 07/09/2013 16:27:32 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockIssueEmployee]
 
	@rId int = 0,
	@rStoreLocationId int = 0,
	@rMainGroupId int=0,
	@rSubGroupId int=0,
	@rItemCode nvarchar(50)='',
	@rItemName nvarchar(50)='',
	@rOrgGroupId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rStockItemCategoryId int=0,
	@rFromDate date='',
	@rTodate date='',
	@rToDepartmentId int =0,
	@rNumber nvarchar(10)='',
	@rEmployeeId bigint = 0,
	@rOrgId smallint = 0,
	@rBatchId int = 0,
	--Mantis : 39564  : Krunal K Patel
	@rFromIssueDate date='',
	@rToIssuedate date=''
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

       SELECT  
			@rBuilder1 AS Builder1,
			SIM.Code AS ItemNumber,
			SIM.Title AS ItemName,		
			SI.IssuedByName,	
			SI.Number, 	
			SI.CreatedDateTime AS IssuedDate,
			ID.IssuedQuantity,
			ID.RequestedQuantity,
			EM.FirstName +' '+EM.MiddleName As EmployeeName,
			EM.Code AS EmployeeCode,
			SG.Code AS ItemSubGroup,
			SG.Id AS ItemSubGroupId,
			OM.DisplayTitle,
			EM.DepartmentName AS Department,
			(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		    WHERE SB.StockItemId = SIM.Id 
		    AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
			) AS Quantity ,
			EM.OrgID,
			ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') AS WeightedAverageCost,
			SI.Remark--mantis - 0032620

		FROM  
			sProcurement.tStockIssue SI		
			INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
			INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
			LEFT JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
			INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId = SI.IssueToSourceId
			INNER JOIN sIp.tItemSubGroupMaster SG ON SG.Id=SIM.ItemSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgID
			 
		WHERE 
			 ((SI.Id = @rId) OR (@rId=0))
			 AND SI.FromStoreLocationId =@rStoreLocationId
			 AND ((SIM.ItemSubGroupId= @rSubGroupId) OR (@rSubGroupId=0))
			 AND ((SIM.Code = @rItemCode) OR (@rItemCode=''))	
			 AND ((SIM.Title = @rItemName) OR (@rItemName=''))
			 AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
			 AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
			 AND SI.OrgGroupId = @rOrgGroupId
			 AND ((SI.ToOrganizationDepartmentId=@rToDepartmentId) OR (@rToDepartmentId=0))
			 AND ((SI.Number like @rNumber) OR  (ISNULL(@rNumber,'')= ''))
			 AND ((SI.IssueToSourceId= @rEmployeeId) OR (ISNULL(@rEmployeeId,0)=0))
			 AND SI.IssueToSourceTypeId = 95
			 AND ((EM.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			 --Mantis : 39564 : Krunal K Patel
			 AND ((convert(Date,ISNULL(SI.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
			 AND ((convert(date,ISNULL(SI.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))	
			 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockIssueRegisterGet]
    @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,
	@rToDepartmentId int=0,
	@rIssuedToName nvarchar(100),
	--Mantis : 39564  : Krunal K Patel
	@rFromIssueDate date='',
	@rToIssuedate date=''
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
		SIM.Code AS ItemCode,
		SIM.Title AS ItemName,		
		SI.IssuedByName,	
		SI.Number AS Billno, 	
		SI.CreatedDateTime AS IssuedDate,
		ID.IssuedQuantity,
		ID.RequestedQuantity,
		 
		--SI.POReference AS POReference,
		--SI.InvoiceReference AS InvoiceReference,
		--VM.Code As SupplierCode,
		--VM.Title As SupplierName,
		SB.ExpiryDate,
		SIP.WeightedAverageCost AS Amount,
		SB.Number As BatchNumber,
		SI.Id AS  StockInwardId,
		@rDetail AS Detail,
		@rBuilder1 As Builder1,
		@rBuilder2 AS Builder2,
		SUOM.Title AS UOM,
		SI.IssueToName,
		SI.TransactionDate ,
		SI.Remark --Mantis - 0032620
				
   FROM  sProcurement.tStockIssue SI		
		INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
		INNER JOIN sProcurement.tStockIssueBatch SIB ON ID.Id = SIB.StockIssueDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
	    LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId
	    --LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id = SI.VendorId
	    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	
		INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId
		 
   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 ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
	    AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
		AND (SI.OrgGroupId = @rOrgGroupId)
		AND ((SI.ToOrganizationDepartmentId = @rToDepartmentId) OR (@rToDepartmentId=0))
		AND ((SI.IssueToName = @rIssuedToName) OR (@rIssuedToName = ''))
		 --Mantis : 39564 : Krunal K Patel
		AND ((convert(Date,ISNULL(SI.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
		AND ((convert(date,ISNULL(SI.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))		
    Order  by SIM.Title	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockIssueRegisterStudentWiseGet]
    @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,
	@rToDepartmentId int=0,
	@rIssuedToName nvarchar(100),
	--Mantis : 39564  : Krunal K Patel
	@rFromIssueDate date='',
	@rToIssuedate date=''
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
		SIM.Code AS ItemCode,
		SIM.Title AS ItemName,		
		SI.IssuedByName,	
		SI.Number AS Billno, 	
		SI.CreatedDateTime AS IssuedDate,
		ID.IssuedQuantity,
		ID.RequestedQuantity,
		SB.ExpiryDate,
		SIP.WeightedAverageCost AS Amount,
		SB.Number As BatchNumber,
		SI.Id AS  StockInwardId,
		@rDetail AS Detail,
		@rBuilder1 As Builder1,
		@rBuilder2 AS Builder2,
		SUOM.Title AS UOM,
		SI.IssueToName,
		SI.TransactionDate ,
		SI.Remark,
		SM.FirstName +' '+SM.MiddleName As StudentName,
		Sm.Code AS StudentCode,
		A.OrgId,
		A.BatchId
				
   FROM  sProcurement.tStockIssue SI		
		INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
		INNER JOIN sProcurement.tStockIssueBatch SIB ON ID.Id = SIB.StockIssueDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
	    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	
		INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId
		INNER JOIN sStudent.tAcademic A on A.Id=IssueToSourceId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentID 
   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 ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
	    AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
		AND (SI.OrgGroupId = @rOrgGroupId)
		AND ((SI.ToOrganizationDepartmentId = @rToDepartmentId) OR (@rToDepartmentId=0))
		AND ((SI.IssueToName = @rIssuedToName) OR (@rIssuedToName = ''))
		AND (SI.IssueToSourceTypeId=2001)	
		 --Mantis : 39564 : Krunal K Patel
		AND ((convert(Date,ISNULL(SI.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
		AND ((convert(date,ISNULL(SI.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))			
    Order  by SIM.Title	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockIssueRequestDetailGet]
	@rOrgGroupId int,
	@rStockIssueRequestId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			ISNULL(SIRD.Id,0) As ID,
			ISNULL(SIRD.StockIssueRequestId,0) AS StockIssueRequestId ,
			SIRD.StockItemId,
			ISNULL(SIRD.RequestedQuantity,0) As RequestedQuantity,
			SIRD.Remark,
			SIRD.UpdatedUserID,
			SIRD.UpdatedDateTime,
			SIM.Code ItemCode,
			SIM.Title ItemTitle,
			SU.Code UomCode,
			SU.Title UomTitle,
			ISNULL(SU.Id,0)AS  IssueStockUomId,
			SIM.IsBatchWiseTracking,
			SIM.Code StockItemCode,
			SIM.Title StockItemName,
			SU.Title Uom,
		    '' as Number,
			SIRD.IssuedQuantity,
			SIR.Number,
			SIR.CreatedDateTime as 'ReqDate',
			(
				Select sum( AvailableQuantity)
				FROM sProcurement.tStockBatch SB
				INNER JOIN sIP.tStockItemMaster SIM ON SIM.Id = SB.StockItemID
				INNER JOIN sProcurement.tStockIssueRequestDetail SIRD1 ON SIRD1.StockItemId = SIM.Id
				WHERE ((SIRD1.StockIssueRequestId = @rStockIssueRequestId) OR (@rStockIssueRequestId = 0))
				AND SIRD1.OrgGroupId = @rOrgGroupId  AND SB.StockItemId = SIRD.StockItemId
			) AS AvailableQuantity,
			EM.Code AS ReqEmployeeCode
 
	   FROM 
			sProcurement.tStockIssueRequestDetail SIRD
	   INNER JOIN  sIP.tStockItemMaster SIM
		ON SIM.Id = SIRD.StockItemId
		INNER JOIN sFinanceCommon.tStockUomMaster  SU
		ON SU.Id = SIM.IssueStockUomId
		INNER JOIN sProcurement.tStockIssueRequest SIR ON SIR.ID=SIRD.StockIssueRequestId
		Left Join sCommon.vEmployeeMaster EM ON SIR.CreatedUserId=EM.UserId
	  WHERE ((SIRD.StockIssueRequestId = @rStockIssueRequestId) OR (@rStockIssueRequestId = 0))
	  AND SIRD.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockIssueReturn]

	@rId [bigint] = 0

WITH EXECUTE AS CALLER
AS
BEGIN

	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	

	SELECT SIR.Id,
		SIR.Number,
		ISNULL(SIR.ReturnedByName,'') AS ReturnedByName,
		SIR.ToStoreLocationId,
		SIR.Remark,
		SIR.StockIssueId,
		SIRB.StockIssueBatchId,
		SIRB.ReturnQuantity,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIM.Id AS StockItemId,
		SIB.StockBatchId AS BatchId,
		SIR.CreatedUserId,
		SI.Number AS InwardNumber,
		SIND.IssuedQuantity, 
		RM.Title AS ReasonName,
		case when SIR.TransactionDate is not null then SIR.TransactionDate else SIR.CreatedDateTime end as CreatedDateTime

	FROM sProcurement.tStockIssueReturn SIR
		INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.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 SIM.Id=SIND.StockItemId
		INNER JOIN sProcurement.tStockIssue SI ON SI.Id=SIR.StockIssueId
		LEFT JOIN sCommon.tReasonMaster RM ON RM.Id=SIRB.ReasonId	--mantis: 35818, change INNER JOIN => LEFT JOIN

	WHERE SIR.Id = @rId 

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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 datetime = '',
	@rToDate datetime = '',
	@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
				
				
		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
		 
		  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 ((SI.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((SI.CreatedDateTime <= @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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockIssueStudent]
 
	@rId int = 0,
	@rStoreLocationId int = 0,
	@rMainGroupId int=0,
	@rSubGroupId int=0,
	@rItemCode nvarchar(50)='',
	@rItemName nvarchar(50)='',
	@rOrgGroupId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rStockItemCategoryId int=0,
	@rFromDate date='',
	@rTodate date='',
	@rToDepartmentId int =0,
	@rNumber nvarchar(10)='',
	@rAcademicId bigint = 0,
	@rOrgId smallint = 0,
	@rBatchId int = 0,
	@rClassId int=0,
	@rDivisionId int=0,
	--Mantis : 39564  : Krunal K Patel
	@rFromIssueDate date='',
	@rToIssuedate date=''
	--Mantis : 39564 : Krunal K Patel
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	Declare @lIDConfigValue nvarchar(50)=''
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId

       SELECT  
			@rBuilder1 AS Builder1,
			SIM.Code AS ItemNumber,
			SIM.Title AS ItemName,		
			SI.IssuedByName,	
			SI.Number, 	
			SI.CreatedDateTime AS IssuedDate,
			ID.IssuedQuantity,
			ID.RequestedQuantity,
			SM.FirstName +' '+SM.MiddleName As StudentName,
			Sm.Code AS StudentCode,
			SG.Code AS ItemSubGroup,
			SG.Id AS ItemSubGroupId,
			OM.DisplayTitle,
			BM.Title AS BatchTitle,
			CM.Title +'-'+ DM.TItle As Class,
			(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		    WHERE SB.StockItemId = SIM.Id 
		    AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
			) AS Quantity ,
			A.OrgId,
			A.BatchId,
			ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') AS WeightedAverageCost,
			@lIDConfigValue AS IdNoLabel,
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)) AS Amount,

			(sFinanceCommon.fNumberToWordsWithDecimal(
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)),1,2,SI.OrgGroupId)
			) AS AmountInWords,
			SI.Remark,--Mantis - 0032620
			SI.TransactionDate AS TransactionDate, --Mantis : 0034980
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name  --Mantis - 43970
		
		FROM  
			sProcurement.tStockIssue SI		
			INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
			INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
			LEFT JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
			INNER JOIN sStudent.tAcademic A on A.Id=IssueToSourceId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentID
			INNER JOIN sIp.tItemSubGroupMaster SG ON SG.Id=SIM.ItemSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM on CM.id =A.ClassId 
			INNER JOIN sSetup.tDivisionMaster DM on DM.Id=A.DivisionId
			INNER JOIn sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		WHERE 
			 ((SI.Id = @rId) OR (@rId=0))
			 AND SI.FromStoreLocationId =@rStoreLocationId
			 AND ((SIM.ItemSubGroupId= @rSubGroupId) OR (@rSubGroupId=0))
			 AND ((SIM.Code = @rItemCode) OR (@rItemCode=''))	
			 AND ((SIM.Title = @rItemName) OR (@rItemName=''))
			 AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
			 AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
			 AND SI.OrgGroupId = @rOrgGroupId
			 AND ((SI.ToOrganizationDepartmentId=@rToDepartmentId) OR (@rToDepartmentId=0))
			 AND ((SI.Number like @rNumber) OR  (ISNULL(@rNumber,'')= ''))
			 AND ((SI.IssueToSourceId= @rAcademicId) OR (ISNULL(@rAcademicId,0)=0))
			 AND SI.IssueToSourceTypeId = 2001
			 AND ((A.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			 AND ((A.ClassId =  @rClassId) OR (@rClassId=0)) --mantisid : 0034341
			 AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0)) --mantisid : 0034341
			 --AND ((A.BatchId = @rBatchId) OR (ISNULL(@rBatchId,0) = 0))
			 --Mantis : 39564 : Krunal K Patel
			 AND ((convert(Date,ISNULL(SI.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
			 AND ((convert(date,ISNULL(SI.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))
			--Mantis : 39564 : Krunal K Patel
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockIssueStudentReceipt]
 
	@rId int = 0,
	@rStoreLocationId int = 0,
	@rMainGroupId int=0,
	@rSubGroupId int=0,
	@rItemCode nvarchar(50)='',
	@rItemName nvarchar(50)='',
	@rOrgGroupId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rStockItemCategoryId int=0,
	@rFromDate date='',
	@rTodate date='',
	@rToDepartmentId int =0,
	@rNumber nvarchar(10)='',
	@rAcademicId bigint = 0,
	@rOrgId smallint = 0,
	@rBatchId int = 0
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	Declare @lIDConfigValue nvarchar(50)=''
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@rOrgGroupId) 
       SELECT  
			@rBuilder1 AS Builder1,
			SIM.Code AS ItemNumber,
			SIM.Title AS ItemName,		
			SI.IssuedByName,	
			SI.Number, 	
			SI.CreatedDateTime AS IssuedDate,
			ID.IssuedQuantity,
			ID.RequestedQuantity,
			SM.FirstName +' '+SM.MiddleName As StudentName,
			Sm.Code AS StudentCode,
			SG.Code AS ItemSubGroup,
			SG.Id AS ItemSubGroupId,
			OM.DisplayTitle,
			BM.Title AS BatchTitle,
			CM.Title +'-'+ DM.TItle As Class,
			(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		    WHERE SB.StockItemId = SIM.Id 
		    AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
			) AS Quantity ,
			A.OrgId,
			A.BatchId,
			ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') AS WeightedAverageCost,
			@lIDConfigValue AS IdNoLabel,
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)) AS Amount,
			replace(
			(sFinanceCommon.fNumberToWordsWithDecimal(
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)),1,2,SI.OrgGroupId)
			),'Rupees Rupees',[sFinanceCommon].[fDefaultCurrencyMinorTitleGet](OM.OrgGroupId)) AS AmountInWords,
			ISNULL(SI.PayTypeId,0) as PayTypeId,
			 ISNULL(PTM.Title,'Not Charged') AS PayType,
			ISNULL(SI.ReceiptNumber,0) as ReceiptNumber,
			ISNULL(SI.BankName,'') as BankName,
			ISNULL(SI.ChequeNo,'') as ChequeNo,
			ISNULL(SI.ChequeDate,'') as ChequeDate,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle

		FROM  
			sProcurement.tStockIssue SI		
			INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
			INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
			LEFT JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
			INNER JOIN sStudent.tAcademic A on A.Id=IssueToSourceId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentID
			INNER JOIN sIp.tItemSubGroupMaster SG ON SG.Id=SIM.ItemSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM on CM.id =A.ClassId 
			INNER JOIN sSetup.tDivisionMaster DM on DM.Id=A.DivisionId
			INNER JOIn sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			Left JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=SI.PayTypeId 
		WHERE 
			 ((SI.Id = @rId) OR (@rId=0))
			 AND SI.FromStoreLocationId =@rStoreLocationId
			 AND ((SIM.ItemSubGroupId= @rSubGroupId) OR (@rSubGroupId=0))
			 AND ((SIM.Code = @rItemCode) OR (@rItemCode=''))	
			 AND ((SIM.Title = @rItemName) OR (@rItemName=''))
			 AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
			 AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
			 AND SI.OrgGroupId = @rOrgGroupId
			 AND ((SI.ToOrganizationDepartmentId=@rToDepartmentId) OR (@rToDepartmentId=0))
			 AND ((SI.Number like @rNumber) OR  (ISNULL(@rNumber,'')= ''))
			 AND ((SI.IssueToSourceId= @rAcademicId) OR (ISNULL(@rAcademicId,0)=0))
			 AND SI.IssueToSourceTypeId = 2001
			 AND ((A.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			 --AND ((A.BatchId = @rBatchId) OR (ISNULL(@rBatchId,0) = 0))
END


SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockIssueStudentWithoutReturnGet]
    @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rStoreLocationId int,
	@rOrgGroupId int,
	@rFromDate date = '',
	@rToDate date = '',
	@rDetail bit =0,
	@rNumber nvarchar(10)='',
	@rAcademicId bigInt = 0,
	@rClassId int=0,
	@rDivisionId int=0,
	--Mantis : 39564  : Krunal K Patel
	@rFromIssueDate date='',
	@rToIssuedate date=''
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
		SIM.Code AS ItemCode,
		SIM.Title AS ItemName,		
		SI.IssuedByName,	
		SI.Number AS Billno, 	
		SI.CreatedDateTime AS IssuedDate,
		ID.IssuedQuantity,
		ID.RequestedQuantity,
		SB.ExpiryDate,
		SIP.WeightedAverageCost AS Amount,
		SB.Number As BatchNumber,
		SI.Id AS  StockIssueId,
		ID.Id AS StockIssueDetailId,
		@rDetail AS Detail,
		@rBuilder1 As Builder1,
		@rBuilder2 AS Builder2,
		SUOM.Title AS UOM,
		SI.IssueToName,
		SI.TransactionDate ,
		SI.Remark, 
		CASE 
			WHEN QuantityFn.Quantity IS NULL THEN ID.IssuedQuantity
			ELSE QuantityFn.Quantity
		END AS Quantity,
		SM.FirstName +' '+SM.MiddleName As StudentName,		--Mantis - 39292
		--added by dhananjay for mantis : 39767
		ISNULL(ISGM.Title,'') AS ItemSubGroup,
		ISNULL(CM.Title,'') AS Std
		--added by dhananjay for mantis : 39767
				 
   FROM  sProcurement.tStockIssue SI		
		INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
		INNER JOIN sProcurement.tStockIssueBatch SIB ON ID.Id = SIB.StockIssueDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
	    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	
		INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId
		INNER JOIN sStudent.tAcademic A on A.Id = SI.IssueToSourceId AND SI.IssueToSourceTypeId = 2001
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId --added by dhananjay for mantis : 39767
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentID		--Mantis - 39292
		OUTER APPLY (
				SELECT sProcurement.fGetStockIssueQuantityWithoutReturn(SI.Id, ID.Id) AS Quantity
				) AS QuantityFn
		
		 
   WHERE	     
	     SIM.IsObsolete=0
		AND(SB.StoreLocationId= @rStoreLocationId)
		AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
	    AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
		AND (SI.OrgGroupId = @rOrgGroupId)
		AND ( ISNULL(QuantityFn.Quantity, 0) > 0 OR QuantityFn.Quantity IS NULL)
		AND ((SI.Number like @rNumber) OR  (ISNULL(@rNumber,'')= ''))
		AND ((SI.IssueToSourceId= @rAcademicId) OR (ISNULL(@rAcademicId,0)=0))	
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		 --Mantis : 39564 : Krunal K Patel
		AND ((convert(Date,ISNULL(SI.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
		AND ((convert(date,ISNULL(SI.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))			
    Order  by SIM.Title	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockItemBatchListing]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	--@rIsAllowDirectIssue bit,
	--@rIsNotInStore bit=0,
	--@rIsBlockedForIssue bit=0,
	@rIsFirstAdd bit=0,
	@rOrgGroupId int,
	@rFromDate datetime = '',
	@rToDate datetime = ''
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
-- 
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		--@rReportId AS ReportId,
		SIM.Id AS StockItemId,
		SIM.Code AS Code,
		SIM.Title As Name,
	    SB.ExpiryDate,
		SIM.Remark,
		SB.Number AS BatchNo,
		SB.AvailableQuantity AS Stock
	
	FROM 
		sProcurement.tStockBatch SB
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId
		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	
		--INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
		
				
	   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 SIM.IsBatchWiseTracking=1
		AND ((SB.ExpiryDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((SB.ExpiryDate <= @rToDate) OR (ISNULL(@rToDate,'') = '') )
		AND (SB.OrgGroupId = @rOrgGroupId)
		AND SB.Number!=''
       Order  by SIM.Title	
END

 




/****** Object:  StoredProcedure [sIp].[pStockItemMasterGrnModify]    Script Date: 07/09/2013 16:31:01 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockItemBelowReorderLevel]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	--@rIsAllowDirectIssue bit,
	--@rIsNotInStore bit,
	--@rIsBlockedForIssue bit,
	--@rIsFirstAdd bit,
	@rOrgGroupId int
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

-- select * from [sExamination].[vExtAllExaminationDetail]
-- select * from [sExamination].[tExposure]
-- select * from [sExamination].[tExposureHazardMaster]
-- 
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rReportId AS ReportId,
		SIM.Id AS StockItemId,
		IMGM.Id AS MainGroupId,
		IMGM.Title AS MainGroupTitle,
		ISGM.Id AS SubGroupId,
		ISGM.Title AS SubGroupTitle,
		SIM.Code AS Code,
		SIM.Title AS Name,
		SUM(SB.AvailableQuantity) AS AvailableQuantity,
		SIP.ReOrderPoint,
		SUOM.Title AS OUM
		
	
	FROM 
		sProcurement.tStockBatch SB
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId
		INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId = @rStoreLocationId
		INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId
		--INNER JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId
			
	   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 (SIM.IsAllowDirectIssue = ( CASE @rIsAllowDirectIssue WHEN 1 THEN 1 ELSE SIM.IsAllowDirectIssue END))
		--AND (SIM.IsNotInStore = ( CASE @rIsNotInStore WHEN 1 THEN 1 ELSE SIM.IsNotInStore END))
		--AND (SIM.IsBlockedForIssue = ( CASE @rIsBlockedForIssue WHEN 1 THEN 1 ELSE SIM.IsBlockedForIssue END))
		--AND (SIM.IsFirstAdd = ( CASE IsFirstAdd WHEN 1 THEN 1 ELSE SIM.IsFirstAdd END))
		AND (SB.OrgGroupId = @rOrgGroupId)
	GROUP BY SIM.Id,IMGM.Id, IMGM.Title, ISGM.Id ,ISGM.Title, SIM.Code, SIM.Title,SIP.ReOrderPoint, SUOM.Title
	HAVING SUM(SB.AvailableQuantity) < SIP.ReOrderPoint
	
		

		   
END

 



/****** Object:  View [sIp].[vExtStockItemMainGroupList]    Script Date: 07/09/2013 16:28:38 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockItemListing]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100), 
	@rOrgGroupId int
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
-- 
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rReportId AS ReportId,
		SIM.Id AS StockItemId,
		IMGM.Id AS MainGroupId,
		IMGM.Title AS MainGroupTitle,
		ISGM.Id AS SubGroupId,
		ISGM.Title AS SubGroupTitle,
		SIM.Code AS Code,
		SIM.Title AS Name,
		SB.AvailableQuantity AS Stock,
		SIP.WeightedAverageCost AS Cost,
		(SIP.WeightedAverageCost * SB.AvailableQuantity) AS Value,
		CASE WHEN SICM.Code is null THEN 'Blank' ELSE SICM.Code END As StockItemCategory,
		SICM.Id StockItemCategoryId,
		SUOM.Title AS UOM
			
	FROM 
		sProcurement.tStockBatch SB
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId
		INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
		LEFT JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId
		INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId
	
		--sIp.vExtStockItemMainGroupList SIMGL
		--INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIMGL.StockItemId
		--INNER JOIN sProcurement.tStockBatch SB ON SB.StockItemId=SIM.Id
		--INNER JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId
				
	   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 (SIM.IsBlockedForIssue = ( CASE @rIsBlockedForIssue WHEN 1 THEN 1 ELSE SIM.IsBlockedForIssue END))
	 
		AND (SB.OrgGroupId = @rOrgGroupId)
    Order  by SIM.Title	
END

/****** Object:  StoredProcedure [sIp].[pStockItemMasterGrnModify]    Script Date: 07/09/2013 16:31:01 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockItemMaxInventory]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
 
	@rOrgGroupId int
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

-- select * from [sExamination].[vExtAllExaminationDetail]
-- select * from [sExamination].[tExposure]
-- select * from [sExamination].[tExposureHazardMaster]
-- 
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rReportId AS ReportId,
		SIM.Id AS StockItemId,
		IMGM.Id AS MainGroupId,
		IMGM.Title AS MainGroupTitle,
		ISGM.Id AS SubGroupId,
		ISGM.Title AS SubGroupTitle,
		SIM.Code AS Code,
		SIM.Title AS Name,
		SUM(SB.AvailableQuantity) AS AvailableQuantity,
		SIP.MaximumInventory,
		SUOM.Title AS UOM
	
	FROM 
		sProcurement.tStockBatch SB
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId
		INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId = @rStoreLocationId
		INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId
		--INNER JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId
			
	   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 (SB.OrgGroupId = @rOrgGroupId)
	GROUP BY SIM.Id,IMGM.Id, IMGM.Title, ISGM.Id ,ISGM.Title, SIM.Code, SIM.Title,SIP.MaximumInventory,SUOM.Title
	HAVING SUM(SB.AvailableQuantity) > SIP.MaximumInventory
	
		--EAED.MainTypeId = 8
		--AND (EAED.StoreLocationId = @rStoreLocationId)
		----AND (EAED.SetupId=@rRoundId)
		--AND (EAED.ParticipantCode Like  @rEmployeeCode ) OR (@rEmployeeCode = '')
		--AND(FM.Id = @rFunctionId OR @rFunctionId = 0)
		--AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
		--AND(ODM.Id = @rDepartmentId OR @rDepartmentId = 0)
		--AND(GM.Id=@rGradeId OR @rGradeId=0)
		--AND(EDM.Id = @rDesignationId OR @rDesignationId = 0)	 
		--AND(EJD.EmployeeJobTitleId = @rJobTitleId OR @rJobTitleId = 0)	
		--AND(EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)	
		--AND(EJD.ContractorId=@rContractorId OR @rContractorId=0)
		--AND(EJD.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
		--AND(EAED.GenderId=@rGenderId OR @rGenderId=0)
		--AND(EAED.StatusId=@rStatusId OR @rStatusId=0) 
		--AND ((DATEDIFF(yy,EAED.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
		--AND ((DATEDIFF(yy,EAED.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	 --   AND ((EAED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		--AND ((EAED.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		--AND (EAED.LocationId = @rLocationId) 
		--AND (EAED.OrgId =  @rOrgId)
		----AND(AL.Id=@rCaseCauseId or @rCaseCauseId=0)
		--AND(EAED.ParticipantSourceTypeId=@rParticipantTypeId or @rParticipantTypeId=0)

		   
END

 




/****** Object:  StoredProcedure [sProcurement].[pRptStockItemBelowReorderLevel]    Script Date: 07/09/2013 16:27:58 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---USE [NetVidyalaya]

CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockItemWiseTransaction]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rFilterId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(100)='',
	@rOrgId smallint,
	@rFromDate datetime = '1900/1/1',
	@rToDate datetime = '1900/1/1',
	--Mantis : 0040056  : Krunal K Patel
	@rFromIssueDate date='1900/1/1',
	@rToIssuedate date='1900/1/1'
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
  SET @rItemName = sCommon.fSearchStringGet(@rItemName)
	  
	SELECT
	     WAC.Id,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 SIM.Id AS StockItemId,
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Good Reciept Note' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 null as TransactionDate
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
				
	WHERE
	    SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 46)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 7) OR (ISNULL(@rFilterId,  0) = 0))
		
		
UNION ALL
			
	SELECT
		 WAC.Id,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 SIM.Id AS StockItemId,
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Good Return Note' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 null as TransactionDate
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	WHERE	     
	    SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 47)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 8) OR (ISNULL(@rFilterId,  0) = 0))
		
				
UNION ALL
			
	SELECT
		 WAC.Id,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 SIM.Id AS StockItemId,
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Inward' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 case when s.TransactionDate is not null then s.TransactionDate  else 	 WAC.CreatedDateTime end  as TransactionDate
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		left join sProcurement.tStockInwardBatch SB on SB.Id  = WAC.SourceId
		left join sProcurement.tStockInwardDetail ssd on ssd.Id = SB.StockInwardDetailId
		left join sProcurement.tStockInward s on s.Id = ssd.StockInwardId
				
    WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1010)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 11) OR (ISNULL(@rFilterId,  0) = 0))
		 --Mantis : 0040056 : Krunal K Patel
		AND ((convert(Date,ISNULL(s.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
		AND ((convert(date,ISNULL(s.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))
			
				
UNION ALL
			
	SELECT
		 WAC.Id,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 SIM.Id AS StockItemId,
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Issue' + 
		  CASE WHEN s.IssueToSourceTypeId = 2001 THEN + ' - Student'  
			  WHEN s.IssueToSourceTypeId = 95 THEN + ' - Employee' 
			  ELSE '' END
		 AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 case when s.TransactionDate is not null then s.TransactionDate  else 	 WAC.CreatedDateTime end  as TransactionDate
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
	    INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		left join sProcurement.tStockIssueBatch SB on SB.Id  = WAC.SourceId
		left join sProcurement.tStockIssueDetail ssd on ssd.Id = SB.StockIssueDetailId
		left join sProcurement.tStockIssue s on s.Id = ssd.StockIssueId
				
    WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 51)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 1) OR (ISNULL(@rFilterId,  0) = 0))
		 --Mantis : 0040056 : Krunal K Patel
		AND ((convert(Date,ISNULL(s.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
		AND ((convert(date,ISNULL(s.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))
			
		
					
UNION ALL
			
	SELECT
		 WAC.Id,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 SIM.Id AS StockItemId,
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Transfer' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 WAC.CreatedDateTime as TransactionDate
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		LEFT join sProcurement.tStockTransfer s on s.Id = WAC.SourceId 
			
				
    WHERE	     
	    SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 52)
	    AND WAC.StoreLocationId= @rStoreLocationId 
	    AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')
		AND ((@rFilterId = 2) OR (ISNULL(@rFilterId,  0) = 0))
		
		
						
UNION ALL
			
	SELECT
		 WAC.Id,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 SIM.Id AS StockItemId,
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Freeze Adjustmnet' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 WAC.CreatedDateTime   as TransactionDate
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
				
    WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 104)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 10) OR (ISNULL(@rFilterId,  0) = 0))
		
		
		
							
UNION ALL
			
	SELECT
		 WAC.Id,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 SIM.Id AS StockItemId,
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Dispense' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 WAC.CreatedDateTime as TransactionDate
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	WHERE	     
	     SIM.IsObsolete=0	     
	     AND (WAC.SourceTypeId = 48)
		 AND WAC.StoreLocationId= @rStoreLocationId 
		 AND (WAC.OrgGroupId = @rOrgId)
		 AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		 AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		 AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		 AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		 AND (SIM.Id=@rId OR @rId = 0)
		 --AND (SIM.Code like @rItemCode OR @rItemCode = '')
		 AND (SIM.Title like @rItemName OR @rItemName = '')		
		 AND ((@rFilterId = 3) OR (ISNULL(@rFilterId,  0) = 0))
		
		UNION ALL
			
	SELECT
		 WAC.Id,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 SIM.Id AS StockItemId,
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Inward Return' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 case when s.TransactionDate is not null then s.TransactionDate  else 	 WAC.CreatedDateTime end  as TransactionDate
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		left join sProcurement.tStockInwardReturnBatch ir on ir.StockInwardBatchId = WAC.SourceId  
		LEFT join  sProcurement.tStockInwardReturn s on s.Id = ir.StockInwardReturnId
		
	WHERE	     
	    SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1013)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 12) OR (ISNULL(@rFilterId,  0) = 0))
		--Mantis : 0040056 : Krunal K Patel
		AND ((convert(Date,ISNULL(s.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
		AND ((convert(date,ISNULL(s.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))
		
		
UNION ALL
			
	SELECT
		 WAC.Id,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 SIM.Id AS StockItemId,
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Issue Return' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		---(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 case when s.TransactionDate is not null then s.TransactionDate  else 	 WAC.CreatedDateTime end  as TransactionDate
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
        left join  sProcurement.tStockIssueReturnBatch da on da.Id =  WAC.SourceId  
		LEFT join  sProcurement.tStockIssueReturn s on s.Id = da.StockIssueReturnId
				
	   WHERE	
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1012)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 5) OR (ISNULL(@rFilterId,  0) = 0))
		--Mantis : 0040056 : Krunal K Patel
		AND ((convert(Date,ISNULL(s.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
		AND ((convert(date,ISNULL(s.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))
		
	
Union All 
		
		SELECT 
			 WAC.Id,
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2,
			 SIM.Id AS StockItemId,
			 SIM.Code AS ItemCode,
			 SIM.Title AS ItemName,
			 'Stock Adjustment' AS TransactionType,
			 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
			 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
			 WAC.WeightedAverageCost,
			---(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
			 WAC.ClosingValue AS Amount,
			 WAC.CreatedDateTime,
			 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
			 case when s.TransactionDate is not null then s.TransactionDate  else 	 WAC.CreatedDateTime end  as TransactionDate
		  
		FROM 
			 sIp.tWeightedAverageCostLog WAC
			 INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
			 left join sProcurement.tStockAdjustmentBatch sb on sb.Id =  WAC.SourceId 
			 left join sProcurement.tStockAdjustmentDetail sbd on sbd.Id =  Sb.StockAdjustmentDetailId 
			 LEFT join sProcurement.tStockAdjustment s on s.Id = sbd.StockAdjustmentId
		
		WHERE 
			 SIM.IsObsolete=0 AND (WAC.SourceTypeId = 50)
			 AND WAC.StoreLocationId= @rStoreLocationId AND (WAC.OrgGroupId = @rOrgId)
			 AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
			 AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
			 AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
			 AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
			 --AND (ISNULL(SIM.Code,'') IN (SELECT item FROM  sCommon.fnsplit(@rItemCode,',')) OR @rItemCode='')
			 AND ((@rFilterId = 9) OR (ISNULL(@rFilterId,  0) = 0))
			 AND ((SIM.Title LIKE @rItemName) OR (ISNULL(@rItemName, '') = ''))
			 --Mantis : 0040056 : Krunal K Patel
			 AND ((convert(Date,ISNULL(s.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
			 AND ((convert(date,ISNULL(s.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))
			
			
UNION ALL
		
		
	SELECT
		 WAC.Id,
		 @rBuilder1 AS Builder1,
		 @rBuilder2 AS Builder2,
		 SIM.Id AS StockItemId,
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Reset' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 case when s.TransactionDate is not null then s.TransactionDate  else 	 WAC.CreatedDateTime end  as TransactionDate
	FROM 
		 sIp.tWeightedAverageCostLog WAC
		 INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 left join  sProcurement.tStockResetBatch da on da.Id =  WAC.SourceId  
		 LEFT join sProcurement.tStockReset s on s.Id = da.StockResetId
		 
		
	WHERE	     
	     SIM.IsObsolete=0	     
	     AND (WAC.SourceTypeId = 2028)
		 AND WAC.StoreLocationId= @rStoreLocationId 
		 AND (WAC.OrgGroupId = @rOrgId)
		 AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		 AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		 AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		 AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		 AND (SIM.Id=@rId OR @rId = 0)
		 --AND (SIM.Code like @rItemCode OR @rItemCode = '')
		 AND (SIM.Title like @rItemName OR @rItemName = '')		
		 AND ((@rFilterId = 12) OR (ISNULL(@rFilterId,  0) = 0))
		 --Mantis : 0040056 : Krunal K Patel
		 AND ((convert(Date,ISNULL(s.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
		 AND ((convert(date,ISNULL(s.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))
			
		
      Order by WAC.Id	desc	
END


SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pRptStockUtilization]
	@rLocationId [int] = 0,
	@rId [int] = 0,
	@rItemMainGroupId [int] = 0,
	@rItemSubGroupId [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
 
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
	IF(@rItemMainGroupId <> 0)
		BEGIN
		SELECT @lMainGroupCode = SIM.MainGroupCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId
		SELECT @lMainGroupTitle = SIM.MainGroupTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId
		END
		--IF(@lSubGroupCode <> 0)
		--BEGIN
		--SELECT @lSubGroupCode = SIM.SubGroupCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId
		--SELECT @lSubGroupTitle = SIM.SubGroupTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId
		--END
		SELECT @lStockItemCode = SIM.StockItemCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId
		SELECT @lStockItemTitle = SIM.StockItemTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.StockItemId = @rId
	END

ELSE IF (@rItemMainGroupId <> 0)
	BEGIN
		SELECT @lMainGroupCode = SIM.MainGroupCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId	
		SELECT @lMainGroupTitle = SIM.MainGroupTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId	
		IF(@rItemSubGroupId <> 0)
		BEGIN
		SELECT @lSubGroupCode = SIM.SubGroupCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId	
		SELECT @lSubGroupTitle = SIM.SubGroupTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId	
		END
		
			
		
		--SELECT @lStockItemCode = SIM.StockItemCode FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId
		--SELECT @lStockItemTitle = SIM.StockItemTitle FROM sIp.vExtStockItemMainGroupList SIM WHERE SIM.MainGroupId = @rItemMainGroupId
		
			
	END  
	
	

SELECT @lLocation = SLM.Title FROM sIp.tStoreLocationMaster SLM WHERE SLM.Id = @rLocationId
BEGIN

DECLARE @tConsume TABLE 
	     (
	     StockItemTitle NVARCHAR(100),
	    ItemCode NVARCHAR(100),
	    ISSUEQNTY INT,
	    StockItemId INT,
	    LOCATIONID INT,
	    PhysicalQnty INT,
	    SaleQnty INT,
	    MONTHYEAR INT,
		BILLQNTY INT
		
	   )

INSERT @tConsume
		(
		StockItemTitle,
		 ItemCode,
	    ISSUEQNTY,
	    StockItemId,
	    LOCATIONID,
	    PhysicalQnty,
	    SaleQnty,
	    MONTHYEAR,
		BILLQNTY 	   
	    )

SELECT 
		STITEM.StockItemTitle, 
		STITEM.StockItemCode,
		StIssue.IssueQnty AS ISSUEQNTY,
		StIssue.StockItemId,
		StIssue.FromStoreLocationId  AS LOCATIONID,
		0 AS PhysicalQnty,
		0 AS SaleQnty,
		StIssue.[month]  MONTHYEAR,
		0 AS   BILLQNTY   
		
  FROM     sIp.vExtStockItemMainGroupList   STITEM  
   INNER JOIN
          ( SELECT SIS.FromStoreLocationId,
                   SISD.StockItemId,
                   SUM(SISD.IssuedQuantity) IssueQnty,
                   Month(SIS.CreatedDateTime) [month] 
         FROM sProcurement.vExtStockIssue SIS
  INNER JOIN sProcurement.vExtStockIssueDetail SISD
         ON SIS.Id = SISD.StockIssueId
             GROUP BY  SISD.StockItemId, Month(SIS.CreatedDateTime), SIS.FromStoreLocationId ) StIssue
         ON 
StIssue.StockItemId = STITEM.StockItemId 


UNION ALL 
SELECT 
		STITEM.StockItemTitle, 
		STITEM.StockItemCode,
		0 AS ISSUEQNTY,
		STITEM.StockItemId,
		StAdj.StoreLocationId AS LOCATIONID,
		StAdj.PhysicalQnty  PhysicalQnty,
		0 AS SaleQnty,
		StAdj.[month]  MONTHYEAR,
		0 AS   BILLQNTY    
	 
		
 FROM     sIp.vExtStockItemMainGroupList   STITEM  
   INNER JOIN
       
    (SELECT Stadjd.StoreLocationId,
                   Stadjd.StockItemId,                
                  SUM(Stadjd.SystemQuantity) - SUM(Stadjd.PhysicalQuantity)   PhysicalQnty,
                   Month(Stad.CreatedDateTime) [month] 
           FROM  sProcurement.vExtStockAdjustment Stad 
   INNER JOIN sProcurement.vExtStockAdjustmentDetail Stadjd
         ON Stad.Id = Stadjd.StockAdjustmentId 
             GROUP BY  Stadjd.StockItemId, Month(Stad.CreatedDateTime), Stadjd.StoreLocationId ) StAdj
         ON   StAdj.StockItemId = STITEM.StockItemId 
         
        UNION ALL
        SELECT 
		STITEM.StockItemTitle, 
		STITEM.StockItemCode,
		0 AS ISSUEQNTY,
		STITEM.StockItemId,
		1  AS LOCATIONID,
		0 AS PhysicalQnty,
		POS.SaleQnty  AS SaleQnty,
		POS.[month]  MONTHYEAR,
		0 AS   BILLQNTY        
	 
		
 FROM     sIp.vExtStockItemMainGroupList   STITEM   
         
         INNER JOIN     
    (SELECT        Ssaled.StockItemId,
                   SUM(Ssaled.Quantity ) SaleQnty,
                   Month(Ssale.CreatedDateTime) [month] 
           FROM  sPharmacy.vExtPointOfSale Ssale
   INNER JOIN sPharmacy.vExtPointOfSaleDetail Ssaled
         ON Ssale.Id = Ssaled.PointOfSaleId  
             GROUP BY  Ssaled.StockItemId, Month(Ssale.CreatedDateTime)   ) POS
         ON   POS.StockItemId = STITEM.StockItemId  
         
         UNION ALL
          SELECT 
		STITEM.StockItemTitle, 
		STITEM.StockItemCode,
		0 AS ISSUEQNTY,
		STITEM.StockItemId,
		1  AS LOCATIONID,
		0 AS PhysicalQnty,
		0 AS SaleQnty,
		OER.[month]  MONTHYEAR,
		OER.BILLQNTY  BILLQNTY     
	 
		
 FROM     sIp.vExtStockItemMainGroupList   STITEM   
         
         INNER JOIN     
    (SELECT        OEN.ItemSourceId,
                   SUM(OEN.Quantity ) BILLQNTY,
                   Month(TBD.CreatedDateTime) [month] 
           FROM  sOrderEntry.vExtOrderEntry OEN
   INNER JOIN sOrderEntry.vExtBillingDetail TBD
   ON OEN.Id = TBD.OrderEntryId AND OEN.IsBilled = 1 
       
             GROUP BY   OEN.ItemSourceId,  Month(TBD.CreatedDateTime)  ) OER
         ON   OER.ItemSourceId  = STITEM.StockItemId  
        

END

 DECLARE @tSales TABLE 
  ( RowID INT IDENTITY(1, 1), STOCKITEMID smallint, LOCATIONID INT, Monthyear INT, RunningTotal INT, RunningTot INT)

INSERT INTO @tSales (STOCKITEMID, LOCATIONID,  Monthyear,  RunningTotal,  RunningTot)
	 (SELECT CON.StockItemId, CON.LOCATIONID, CON.MONTHYEAR,  SUM(CON.ISSUEQNTY + CON.PhysicalQnty + CON.SaleQnty + CON.BILLQNTY) SaleQty, 0
		  
		   FROM  @tConsume CON  GROUP BY CON.StockItemId,  LOCATIONID, CON.MONTHYEAR   HAVING   CON.MONTHYEAR  < MONTH(@rFromDate ) )  
DECLARE @lLocationId INT
SET		@lLocationId = -999 

 DECLARE @lStockId INT
 SET     @lStockId = -999  
  DECLARE @lMonth INT
 SET     @lMonth = -999 
DECLARE @lRunningTotal INT
SET @lRunningTotal = 0
 
UPDATE @tSales
SET @lRunningTotal = RunningTot =
      CASE      
		  WHEN ( @lStockId = STOCKITEMID AND @lLocationId = LOCATIONID  ) 
				THEN @lRunningTotal + RunningTotal 
				ELSE RunningTotal					
		END,
		@lLocationId = LOCATIONID, 
		@lStockId = STOCKITEMID, 
		@lMonth = Monthyear 


   
 --SELECT STOCKITEMID AS STOCKITEMID, LOCATIONID AS LOCATION, Monthyear,  RunningTotal AS OB, RunningTot FROM  #tSales ORDER BY STOCKITEMID--, LOCATIONID, Monthyear
   
 
 	 --(SELECT CON.StockItemId, CON.LOCATIONID,  SUM(CON.ISSUEQNTY + CON.PhysicalQnty + CON.SaleQnty + CON.BILLQNTY) SaleQty
		 --  FROM  @tConsume CON  WHERE  CON.MONTHYEAR < MONTH(@rFromDate ) GROUP BY CON.StockItemId, CON.LOCATIONID     ) 
		 
		 

      

BEGIN
DECLARE @tPorder TABLE 
	(
	    ItemCode NVARCHAR(100),
		TotPoQnty INT,
		[Month] INT,
		LocationId INT
		
	)

INSERT @tPorder
		(
		ItemCode,
		TotPoQnty,
		[Month],
		LocationId
		
	
	    )
	    
	    
	    SELECT 
		STITEM.StockItemCode   AS CODE,
		T1.OrderQuantity,
		[Month],
		T1.Id 
 FROM    sIp.vExtStockItemMainGroupList   STITEM  
 INNER JOIN
		(SELECT SLM.Id,  POD.ItemSourceId, SUM(POD.OrderQuantity) OrderQuantity, MONTH(PO.CreatedDateTime) [Month]
				  FROM sProcurement.vExtPurchaseOrder PO
				INNER JOIN sProcurement.vExtPurchaseOrderDetail POD
					ON PO.Id = POD.PurchaseOrderId AND PO.StatusId = 43
					INNER JOIN sIp.tStoreLocationMaster SLM 
				    ON	SLM.ID = PO.StoreLocationId
							GROUP BY SLM.Id, POD.ItemSourceId, MONTH(PO.CreatedDateTime)) T1
ON
		T1.ItemSourceId = STITEM.StockItemId   
 GROUP BY STITEM.StockItemCode, T1.OrderQuantity, T1.[Month], T1.Id

END



BEGIN
DECLARE @tGrn TABLE 
	(
	    ItemCode NVARCHAR(100),		
		TotGrnQnty INT,
		[Month] INT,
		LocationId INT
				
	)

INSERT @tGrn
		(
		ItemCode,
	    TotGrnQnty,  
	    [Month],
		LocationId
	
	    )
	    
	  SELECT 
		STITEM.StockItemCode   AS CODE,
		T1.GRNQuantity,
		[Month],
		T1.Id
	
 FROM    sIp.vExtStockItemMainGroupList   STITEM  
 INNER JOIN
		(SELECT SLM.Id, POD.ItemSourceId, SUM(GRND.ReceiptQuantity + GRND.ReceiptBonusQuantity) GRNQuantity, MONTH(GRN.CreatedDateTime) [Month]--, Number
				  FROM sProcurement.vExtPurchaseOrder PO
				INNER JOIN sProcurement.vExtPurchaseOrderDetail POD
					ON PO.Id = POD.PurchaseOrderId AND PO.StatusId = 43
					INNER JOIN sProcurement.vExtGoodsReceiptNote GRN
					ON GRN.PurchaseOrderId = PO.Id
				INNER JOIN sProcurement.vExtGoodsReceiptNoteDetail GRND
					ON GRND.GoodsReceiptNoteId = GRN.Id AND GRND.PurchaseOrderDetailId = POD.Id
					INNER JOIN sIp.tStoreLocationMaster SLM 
				    ON	SLM.ID = PO.StoreLocationId
							GROUP BY SLM.Id, POD.ItemSourceId, MONTH(GRN.CreatedDateTime)) T1
ON
		T1.ItemSourceId = STITEM.StockItemId   
       
   
END


BEGIN

 DECLARE @tGren TABLE 
	     (
	    ItemCode NVARCHAR(100),
	    TotGrenQnty INT,
		[Month] INT,
		LocationId INT
		
		
		
		
	   )

INSERT @tGren
		(
		ItemCode,
	    TotGrenQnty,
	    [Month],
	    LocationId
	   
	    )
	     SELECT 
		STITEM.StockItemCode   AS CODE,
		T2.GRENQuantity,
		[Month],
		T2.Id
 FROM    sIp.vExtStockItemMainGroupList   STITEM  
 INNER JOIN
 
 ( SELECT	SLM.Title, 
			SLM.Id, 
			POD.ItemSourceId, 
			SUM(GREND.ReturnQuantity) GRENQuantity, 
			MONTH(GREN.CreatedDateTime) [Month]  
	FROM sProcurement.vExtGoodsReceiptNoteReturnDetail GREND
         INNER JOIN sProcurement.vExtGoodsReceiptNoteReturn GREN
					ON GREN.Id = GREND.GoodsReceiptNoteReturnId
		 INNER JOIN  sProcurement.vExtGoodsReceiptNote GRN
	    			ON  GREN.GoodsReceiptNoteId = GRN.ID 
	     INNER JOIN  sProcurement.vExtGoodsReceiptNoteDetail GRND
	     	        ON	GRN.Id = GRND.GoodsReceiptNoteId  
	     INNER JOIN  sProcurement.vExtPurchaseOrder PO
					ON   GRN.PurchaseOrderId = PO.Id 	
		 INNER JOIN sProcurement.vExtPurchaseOrderDetail POD
					 ON GRND.PurchaseOrderDetailId = POD.Id AND PO.StatusId = 43           
	     INNER JOIN sIp.tStoreLocationMaster SLM 
				    ON	SLM.ID = PO.StoreLocationId
						
				   
GROUP BY SLM.Title, POD.ItemSourceId, MONTH(GREN.CreatedDateTime), SLM.Id	) T2

ON
		T2.ItemSourceId = STITEM.StockItemId   
	    
	 

 
	    
	

END
BEGIN
SELECT 
        @lStockItemTitle  AS ITEMTITLE, 
        @lSubGroupTitle AS SubGroupTitle, 
        @rFromDate AS FROMMONTH,   
        @rToDate	AS TOMONTH, 
		STITEM.StockItemTitle    AS Title, 
		STITEM.StockItemCode   AS CODE,
		STITEM.Wac AS WAC,
		STITEM.Saleprice,
		T1.OrderQuantity * (T1.ConversionFactor) AS OrderQuantity,
		T1.CreatedDateTime,
		T1.Number  AS PONUMBER,
		ISNULL(T2.GRNNumber, 'NA') AS GRNNO,
		ISNULL(T2.GRNQuantity * (T1.ConversionFactor), '0') AS GRNQuantity,
		ISNULL(T3.GRNNumber, 'NA') AS GRNNumber,
		ISNULL(T3.GRENQuantity * (T1.ConversionFactor), '0') AS GRENQuantity,
		T1.location,
		0  AS  ClosingQnty,    
        @lMainGroupTitle AS MainGroupTitlefORDISPLY,
       -- STITEM.MainGroupTitle,
        STITEM.MainGroupTitle,
        (POD.TotPoQnty)* (T1.ConversionFactor) AS TotPoQnty,
      ISNULL(TGRN.TotGrnQnty * (T1.ConversionFactor), '0') AS TotGrnQnty,
      ISNULL(TGREN.TotGrenQnty * (T1.ConversionFactor), '0') AS TotGrenQnty,
       ISNULL(CONS.CONSUMEQNTY, '0')  AS CONSUMEQNTY,
      --  Closeing.StockItemId,
       ISNULL(Closeing.OPQTY * (T1.ConversionFactor), '0')  AS OPQTY
   
       
 
       
 FROM    sIp.vExtStockItemMainGroupList   STITEM  
 
 
 INNER JOIN
 
		(SELECT  UOM.ConversionFactor, SLM.Title  location, PO.StoreLocationId, PO.Id POID, POD.ItemSourceId, 0 AS CONSUMEQNTY,
	
		 SUM(POD.OrderQuantity) OrderQuantity, PO.CreatedDateTime, Number FROM sProcurement.vExtPurchaseOrder PO
				INNER JOIN sProcurement.vExtPurchaseOrderDetail POD
					ON PO.Id = POD.PurchaseOrderId AND PO.StatusId = 43
					INNER JOIN sIp.tStoreLocationMaster SLM 
				    ON	SLM.ID = PO.StoreLocationId
				    INNER JOIN SIP.tStockItemPurchaseUom  UOM   
				  ON  UOM.ID = POD.StockItemPurchaseUomId
				
							GROUP BY PO.StoreLocationId, POD.ItemSourceId, PO.CreatedDateTime, PO.Number, PO.Id, SLM.Title, UOM.ConversionFactor ) T1
ON
		T1.ItemSourceId = STITEM.StockItemId 
		
		 LEFT JOIN 
		 (SELECT CON.StockItemId, CON.LOCATIONID, CON.MONTHYEAR,  SUM(CON.ISSUEQNTY + CON.PhysicalQnty + CON.SaleQnty + CON.BILLQNTY) CONSUMEQNTY 
		   FROM  @tConsume CON  GROUP BY CON.StockItemId, CON.MONTHYEAR,  CON.LOCATIONID) CONS
		  
				  ON 
				   CONS.LOCATIONID = T1.StoreLocationId AND    CONS.StockItemId = T1.ItemSourceId AND CONS.MONTHYEAR = Month(T1.CreatedDateTime)  
				   
				 -------------
			--			    LEFT JOIN 
		 --(SELECT CON.StockItemId, CON.LOCATIONID,   SUM(CON.ISSUEQNTY + CON.PhysicalQnty + CON.SaleQnty + CON.BILLQNTY) OPQTY
		 --  FROM  @tConsume CON  WHERE CON.MONTHYEAR < Month(@rFromDate)   GROUP BY CON.StockItemId, CON.LOCATIONID ) Closeing
		  
			--	  ON 
			--	 Closeing.LOCATIONID = T1.StoreLocationId AND    Closeing.StockItemId = T1.ItemSourceId  
				 
				 
				 
				 LEFT JOIN 
		 (SELECT CON.StockItemId, CON.LOCATIONID,   SUM(RunningTotal) OPQTY
		   FROM  @tSales CON  WHERE CON.MONTHYEAR < Month(@rFromDate)   GROUP BY CON.StockItemId, CON.LOCATIONID ) Closeing
		  
				  ON 
				 Closeing.LOCATIONID = T1.StoreLocationId AND    Closeing.StockItemId = T1.ItemSourceId  
		
	
				 
				   
		
		LEFT JOIN     @tPorder POD  ON POD.ItemCode = STITEM.StockItemCode  AND Month(T1.CreatedDateTime) = POD.[Month] AND POD.LocationId = T1.StoreLocationId
LEFT JOIN
(SELECT POD.ItemSourceId, PO.StoreLocationId,  GRN.PurchaseOrderId  POID, GRN.Id  GRNNID,  SUM(GRND.ReceiptQuantity + GRND.ReceiptBonusQuantity ) GRNQuantity, GRN.CreatedDateTime, GRN.Number GRNNumber  FROM sProcurement.vExtGoodsReceiptNoteDetail GRND
INNER JOIN sProcurement.vExtGoodsReceiptNote GRN
					ON GRN.Id = GRND.GoodsReceiptNoteId 
INNER JOIN sProcurement.vExtPurchaseOrder PO
					ON GRN.PurchaseOrderId = PO.Id
INNER JOIN  sProcurement.vExtPurchaseOrderDetail POD
					ON GRND.PurchaseOrderDetailId = POD.Id
				
			GROUP BY POD.ItemSourceId, PO.StoreLocationId, GRN.PurchaseOrderId, GRN.Number, GRN.Id, GRN.CreatedDateTime ) T2
ON
		T2.POID = T1.POID  AND T2.ItemSourceId = T1.ItemSourceId AND T2.StoreLocationId = T1.StoreLocationId
LEFT JOIN    @tGrn TGRN  ON TGRN.ItemCode = STITEM.StockItemCode  AND Month(T2.CreatedDateTime) = TGRN.[Month] AND T2.StoreLocationId = TGRN.LocationId
		
		  
	LEFT JOIN
	
	
	(SELECT  POD.ItemSourceId, PO.StoreLocationId, GRN.PurchaseOrderId  POID, GREN.Id  GRENID,  SUM(GREND.ReturnQuantity ) GRENQuantity, GREN.CreatedDateTime, GREN.Number GRNNumber, GRN.Id  GRNId FROM sProcurement.vExtGoodsReceiptNoteReturnDetail GREND
          INNER JOIN sProcurement.vExtGoodsReceiptNoteReturn GREN
				   ON GREN.Id = GREND.GoodsReceiptNoteReturnId
		 INNER JOIN  sProcurement.vExtGoodsReceiptNote GRN
	    			ON  GREN.GoodsReceiptNoteId = GRN.ID 
	     INNER JOIN  sProcurement.vExtGoodsReceiptNoteDetail GRND  
	     	        ON GRN.Id = GRND.GoodsReceiptNoteId  
	     INNER JOIN   sProcurement.vExtPurchaseOrder PO
					ON PO.Id = GRN.PurchaseOrderId      
	     INNER JOIN  sProcurement.vExtPurchaseOrderDetail POD
					ON GRND.PurchaseOrderDetailId = POD.Id
					
				   
GROUP BY POD.ItemSourceId, GRN.PurchaseOrderId, GREN.Number, GREN.Id, GREN.CreatedDateTime, GRN.Id, PO.StoreLocationId )T3
	ON
 T2.ItemSourceId = T3.ItemSourceId --AND T3.GRNId = T2.GRNNID
 LEFT JOIN    @tGren TGREN  ON TGREN.ItemCode = STITEM.StockItemCode  AND Month(T3.CreatedDateTime) = TGREN.[Month] AND T3.StoreLocationId = TGREN.LocationId
			

		
	WHERE ((T1.CreatedDateTime >= @rFromDate AND T1.CreatedDateTime <= (@rToDate + 1)) OR (ISNULL(@rFromDate, '') = '')OR (ISNULL(@rToDate, sCommon.fGetDate()) = sCommon.fGetDate()))
AND    ((T1.StoreLocationId = @rLocationId) OR (ISNULL(@rLocationId, 0) = 0))
  AND 
  ((STITEM.StockItemId = @rId) OR (ISNULL(@rId, 0) = 0))
 AND ((STITEM.MainGroupId  = @rItemMainGroupId) OR (ISNULL(@rItemMainGroupId, 0) = 0))	
--AND ((STITEM.SubGroupId = @lSubGroupCode) OR (ISNULL(@lSubGroupCode, 0) = 0))	
		


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAdjustGet]
	@rOrgGroupId int,
	@rNumber [nvarchar](20)='',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
SELECT Id AdjustmentId,Number AdjustmentNumber,CreatedDateTime
FROM sProcurement.tStockAdjustment WHERE  
((Number like '%' +@rNumber+'%')OR(ISNULL(@rNumber,'') = '*' ))
AND OrgGroupId = @rOrgGroupId
AND ((CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
AND ((CreatedDateTime<= DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
AND FromStoreLocationId=@rStoreLocationId
order by CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAdjustment_New]
(
@rOrgGroupId [int],
@rNumber Nvarchar(20) = '',
@rStoreLocationId Int,
@rRemark Nvarchar(300),
@rCreatedUserId	BigInt,
@rDetail Nvarchar(Max),
@rLocationId int=0		,
@rOrgid int
)
AS
SET NOCOUNT ON
BEGIN
BEGIN
	 TRY
		DECLARE @loXML XML
		SET @loXML = CAST(@rDetail AS XML)
		DECLARE @lIntErrorCode INT
		EXEC sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId,
		@rPrefixFunctionalityId = 26,@rStoreLocationId = @rStoreLocationId,
		@rNextNumber  = @rNumber OUTPUT
		SET @rNumber = ISNULL(@rNumber, '-300')
		
		IF @rNumber = '-300'
		BEGIN
			SELECT -300 AS Result, '' AS Number, 0 AS Id 
			RETURN
		END

		DECLARE @tStockAdjustDetail TABLE
		(
			Id Int IDENTITY(1,1),StockItemId int,SystemQuantity decimal(12,2),AdjustedQuantity decimal(12,2),PhysicalQuantity decimal(12,2),
			ReasonId int,StockBatchID int,Batch nvarchar(100)
		)

		INSERT INTO @tStockAdjustDetail
		SELECT T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@SystemQuantity','decimal(12,2)') AS SystemQuantity,
		T.c.value('@AdjustedQuantity','decimal(12,2)') AS AdjustedQuantity,
		T.c.value('@PhysicalQuantity','decimal(12,2)') AS PhysicalQuantity,
		T.c.value('@ReasonId','int') AS ReasonId,T.c.value('@StockBatchID','int') AS StockBatchID,
		T.c.value('@Batch','nvarchar(100)') AS Batch FROM @loXML.nodes('/Table/StockAdjust')T(c)
		
		--select * from @tStockAdjustDetail
	BEGIN TRANSACTION
		
		DECLARE @lNextNumberStockAdjust INT
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockAdjustment', 0, 1, 1,@outNextNumber = @lNextNumberStockAdjust output

		INSERT INTO sProcurement.tStockAdjustment
		(
			Id,Number,CreatedUserId,CreatedDateTime,OrgGroupId,FromStoreLocationId
		)
		VALUES
		(
			@lNextNumberStockAdjust,@rNumber,@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId,@rStoreLocationId
		)
		DECLARE @lNextNumberStockAdjustDetail BigInt,@lCOunt int,@lItemId int,@lSystemQuantity decimal(12,2),
		@lPhysicalQuantity decimal(12,2),@lReasonId int,@lStockBatchId int,@lBatch nvarchar(300),@lAdjustedQuantity decimal(12,2),
		@lWeightedAverageCost decimal(12,2),@lInwardValue decimal(12,2)
		
		SET @lWeightedAverageCost = 0
		
		Select @lCOunt = count(*) from @tStockAdjustDetail
		
		while @lcount>0
		BEGIN
			Select @lItemId = StockItemId,@lSystemQuantity = SystemQuantity,@lAdjustedQuantity=AdjustedQuantity,@lPhysicalQuantity=PhysicalQuantity,
			@lCOunt=Id,@lBatch=Batch,@lStockBatchID=StockBatchID,@lReasonId=ReasonId from @tStockAdjustDetail where Id=@lCOunt
			
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning Where StockItemId = @lItemId AND StoreLocationId =  @rStoreLocationId

			if Exists(Select Id from sProcurement.tStockAdjustmentDetail where StockAdjustmentId=@lNextNumberStockAdjust and StockItemId = @lItemId AND StockBatchId = @lStockBatchId)
			BEGIN
				Select @lNextNumberStockAdjustDetail= Id from sProcurement.tStockAdjustmentDetail 
				Where StockAdjustmentId = @lNextNumberStockAdjust AND StockIteMid =@lItemId AND StockBatchId = @lStockBatchId
			END
			else
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockAdjustmentDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockAdjustDetail output
				
				INSERT INTO sProcurement.tStockAdjustmentDetail
				(
					Id,StockAdjustmentId,StockItemId,StoreLocationId,SystemQuantity,Remark,ReasonId,PhysicalQuantity,StockBatchId,OrgGroupId
				)
				SELECT @lNextNumberStockAdjustDetail,@lNextNumberStockAdjust,StockItemId,@rStoreLocationId,
				SystemQuantity,@rRemark, ReasonId,PhysicalQuantity,StockBatchId,@rOrgGroupId from @tStockAdjustDetail where Id=@lcount
			END
			
			Update SB Set SB.AvailableQuantity = @lPhysicalQuantity
			from sProcurement.tStockBatch SB WHERE Id = @lStockBatchId AND 
			StockItemId = @lItemId AND SB.StoreLocationId =@rStoreLocationId
						
			SET @lInwardValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lAdjustedQuantity,0)
			
			if @lAdjustedQuantity < 0
			BEGIN	 
				SET @lAdjustedQuantity = ABS(@lAdjustedQuantity)
				Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=50,
				@rSourceId=@lNextNumberStockAdjustDetail,@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity= @lAdjustedQuantity,
				@rValue=@lInwardValue ,@rIsReceipt=0,@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rStoreLocationId,
				@rLocationId=@rLocationId,@rPhysicalQuantity =@lPhysicalQuantity,@rWeightedAverageCost =@lWeightedAverageCost
			END
			ELSE
			BEGIN				 
				Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=50,@rSourceId=@lNextNumberStockAdjustDetail,
				@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lAdjustedQuantity ,@rValue=@lInwardValue ,@rIsReceipt=1,
				@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rStoreLocationId ,@rLocationId=@rLocationId,@rPhysicalQuantity=@lPhysicalQuantity,
				@rWeightedAverageCost =@lWeightedAverageCost
			END
			set @lcount =@lcount-1
		END
	SELECT 1 AS Result ,@lNextNumberStockAdjust as ResultDetails,@rNumber as Number
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT,'' as ResultDetails,'' as Number
	END CATCH	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockAdjustmentAdd]  
	@rOrgGroupId int,
	@rNumber [nvarchar](20),
	@rCreatedUserId [bigint],
	@rStoreLocationId int,
	@rResult [int] = 0 OUTPUT,
	@rAdjDate datetime = null	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	DECLARE @loNextNumber nVarchar(20)
	DECLARE @lAdjustmentNumber nVarchar(20)
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockAdjustment',@lNextNumber = @lNextNumber output

    EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId  =  27,@rStoreLocationId = @rStorelocationId, @rNextNumber  =  @loNextNumber OUTPUT
    
 --SET @loNextNumber = NULL

    
    SET @lAdjustmentNumber  =  ISNULL(@loNextNumber, '-200')

--SELECT @lAppNumber

SET @rResult  =  -200 
IF (@lAdjustmentNumber <> '-200')
 BEGIN	
 SET @rResult  =  0
--SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tStockAdjustment WHERE FromStoreLocationId = @rStoreLocationId
--SET @rNumber = @rNumber + 1
	INSERT INTO sProcurement.tStockAdjustment
		(
			Id,
			Number,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			FromStoreLocationId,
			TransactionDate
		)
	VALUES
		(
			@lNextNumber,
			@lAdjustmentNumber,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rStoreLocationId,
			@rAdjDate
		)
		SET @rResult  =  @lNextNumber 
	
	END

		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAdjustmentDetailAdd]
	@rOrgGroupId int,
	@rStockAdjustmentId [int],
	@rStockItemId [int],
	@rStoreLocationId [int],
	@rSystemQuantity [decimal](22, 6),
	@rPhysicalQuantity [decimal](22, 6),
	@rRemark [nvarchar](300),
	@rReasonId [int],
	@rGoodsReceiptNoteBatchId [int],
	@rNewId [int] OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN    
    
	DECLARE @lNextNumber INT
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockAdjustmentDetail',@lNextNumber = @lNextNumber output

	INSERT INTO sProcurement.tStockAdjustmentDetail
		(
			Id,
			StockAdjustmentId,
			StockItemId,
			StoreLocationId,
			SystemQuantity,
			PhysicalQuantity,
			Remark,
			ReasonId,
			StockBatchId,
			OrgGroupId		
		)
	VALUES
		(
			@lNextNumber,
			@rStockAdjustmentId,
			@rStockItemId,
			@rStoreLocationId,
			CAST(@rSystemQuantity AS DECIMAL(12, 2)),
			CAST(@rPhysicalQuantity AS DECIMAL(12, 2)),
			@rRemark,
			@rReasonId,
			CASE
				WHEN @rGoodsReceiptNoteBatchId > 0
				THEN @rGoodsReceiptNoteBatchId
				ELSE NULL
			END,
			@rOrgGroupId			
		)
		
	SET	@rNewId = @lNextNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAdjustmentDetailGet]
	@rOrgGroupId int,
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT AD.Id AdjustmentDetailId,
			AD.StockAdjustmentId StockAdjustmentId,
			AD.StoreLocationId StoreLocationId,
			AD.SystemQuantity SystemQuantity,
			AD.PhysicalQuantity PhysicalQuantity,
			AD.PhysicalQuantity - AD.SystemQuantity AdjustedQuantity,
			AD.Remark Remark,
			AD.ReasonId ReasonId,
			SIM.Id stockItemId,
			SIM.Code Code,
			SIM.Title Name,
			AD.StockBatchId GoodsReceiptNoteBatchId,
			SB.Number BatchNo,
			SB.ExpiryDate ExpiryDate,
			RM.Title Reason,
			UM.Code UOM,
			SLM.Title Location
			
			 
			
	   FROM sProcurement.tStockAdjustmentDetail AD
	   
	       LEFT JOIN sIp.tStockItemMaster SIM
	        ON AD.StockItemId = SIM.Id
	        
	     
	        LEFT JOIN sFinanceCommon.tStockUomMaster UM
	        ON SIM.IssueStockUomId = UM.Id
	       
	        
	        LEFT JOIN sProcurement.tStockBatch SB
	        ON AD.StockBatchId = SB.Id AND ISNULL(SB.number,'')!=''
	        
	        LEFT JOIN sCommon.tReasonMaster RM
	        ON AD.ReasonId = RM.Id
	        
	        LEFT JOIN sIp.tStoreLocationMaster SLM
	        ON AD.StoreLocationId = SLM.Id
	   
	  WHERE ((AD.StockAdjustmentId = @rId) OR (@rId = 0))
	  AND AD.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAdjustmentGet]
	@rOrgGroupId int,
	@rId [int] = 0,
	@rFromStoreLocationId [int] = 0,
	@rAdjustmentNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id AdjustmentId,
			Number AdjustmentNumber,
			CreatedUserId,
			CreatedDateTime,
			case when TransactionDate is not null then TransactionDate else CreatedDateTime end as 'TransactionDate'
	   FROM sProcurement.tStockAdjustment
	 
	  	WHERE ((Id = @rId) OR (@rId = 0))
				        AND ((Number = @rAdjustmentNumber)OR(ISNULL(@rAdjustmentNumber,'') = '' ))
				        AND OrgGroupId = @rOrgGroupId
				        AND ((FromStoreLocationId = @rFromStoreLocationId) OR (@rFromStoreLocationId = 0))
					    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAuditAdd]
	@rOrgId int,
	@rStoreLocationId [int],
	@rCreatedUserId [bigint],
	@rStockAuditDetailXml [nvarchar](max),
	@rNumber [nvarchar](20) OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--DECLARE @lNextNumber BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockAudit', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	--DECLARE @loNextNumber nVarchar(20)
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 29,@rStoreLocationId = @rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
	
	
	--IF (@loNextNumber IS NULL)
	--	BEGIN
	--		RAISERROR('5000', 15, 106)
	--		RETURN
	--	END
	--INSERT INTO sProcurement.tStockAudit
	--	(
	--		Id,
	--		Number,
	--		StoreLocationId,
	--		CreatedUserId,
	--		CreatedDateTime,
	--		OrgId
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		@loNextNumber,
	--		@rStoreLocationId,
	--		@rCreatedUserId,
	--		sCommon.fGetDate(),
	--		@rOrgId
	--	)
	--	SET @rNumber = @loNextNumber
	--	EXEC sProcurement.pStockAuditDetailAdd @rOrgId,  @lNextNumber, @rStockAuditDetailXml
	SELECT 0 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAuditDetailAdd]
	@rOrgId int,
	@rStockAuditId [int],
	@rStockAuditDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @loIdoc INT
	DECLARE @lStockAuditDetailCurrentId INT
	DECLARE @lCount INT 
		
	SET @lCount = 0

	

	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockAuditDetailXml
	EXEC sCommon.pTableRowIdGet  @rOrgId, 'sProcurement.tStockAuditDetail', 1, 1, 1,@outNextNumber = @lStockAuditDetailCurrentId output

	INSERT INTO sProcurement.tStockAuditDetail
		(
			Id,
			StockAuditId,
			StockItemId,
			SystemQuantity,
			PhysicalQuantity,
			OrgId
		)
	SELECT  
		@lStockAuditDetailCurrentId + ROW_NUMBER() OVER(ORDER BY StockItemId) AS Id, 
		@rStockAuditId,
		StockItemId,
		SystemQuantity,
		PhysicalQuantity,
		@rOrgId
	FROM OPENXML (@loIdoc, '/StockAudit/StockAuditDetail', 1)
		WITH ( 
				StockItemId INT, 
				SystemQuantity DECIMAL(22, 6), 
				PhysicalQuantity DECIMAL(22, 6)
			  ) 
		
		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockAudit/StockAuditDetail', 1)
				 WITH ( StockItemId INT)
		
		
		SET @lStockAuditDetailCurrentId  = @lCount + @lStockAuditDetailCurrentId 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sProcurement.tStockAuditDetail', @rCurrentNumber = @lStockAuditDetailCurrentId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAuditDetailGet]
	@rOrgId int,
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			StockAuditId,
			StockItemId,
			SystemQuantity,
			PhysicalQuantity
	   FROM sProcurement.tStockAuditDetail
	  WHERE ((Id = @rId) OR (@rId = 0))
	  AND OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAuditDetailListGet]
	@rOrgId int,
	@rId [int] = 0,
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--SELECT	SA.Id,
	--		SA.Number,
	--		SA.StoreLocationId,
	--		SA.CreatedUserId,
	--		SAD.StockAuditId,
	--		SAD.StockItemId,
	--		SAD.SystemQuantity,
	--		SAD.PhysicalQuantity,
	--		SLM.Title AS StoreLocation,
	--		SIM.Title AS ItemName
	--FROM sProcurement.tStockAudit SA
	--INNER JOIN 
	--	sProcurement.tStockAuditDetail SAD
	--ON
	--	SAD.StockAuditId = SA.Id
	--INNER JOIN
	--	sIP.tStoreLocationMaster SLM
	--ON
	--	SLM.Id = SA.StoreLocationId
	--INNER JOIN  sIp.tStockItemMaster SIM
	--ON SIM.ID = SAD.StockItemId
	
	--WHERE ((SA.Id = @rId) OR (@rId = 0))
	--AND ((SA.Number = @rNumber) OR (@rNumber = ''))
	--AND SA.OrgId = @rOrgId
	
	SELECT	0 AS Id,
			0 AS Number,
			0 AS StoreLocationId,
			0 AS CreatedUserId,
			0 AS StockAuditId,
			0 AS StockItemId,
			0 AS SystemQuantity,
			0 AS PhysicalQuantity,
			0 AS StoreLocation,
			0 AS ItemName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAuditSearchGet]
	@rOrgId [int],	
	@rLocationId [int] = 0,
	@rItemMainGroupId [int] = 0,
	@rItemSubGroupId [int] = 0,
	@rStockItemId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--SELECT 
	--	SB.StockItemId,
	--	SIM.Code AS ItemCode,
	--	SIM.Title AS ItemName,
	--	SUM(SB.AvailableQuantity) AS SQuantity								 
	--FROM sIp.tStockItemMaster SIM
	--	INNER JOIN sProcurement.tStockBatch SB
	--	ON SIM.Id = SB.StockItemId	   
	--	INNER JOIN sIp.tItemSubGroupMaster ISG
	--	ON ISG.Id = SIM.ItemSubGroupId
	--    -- WHERE SIM.OrgId = @rOrgId --Commented as No orgid is there in table
	--	GROUP BY SB.StockItemId, SB.StoreLocationId, SIM.ItemSubGroupId, ISG.ItemMainGroupId, SIM.Code, SIM.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 SQuantity	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockAvailableQuantityGet]
	 
	@rOrgGroupId [int],	
	@rId [bigint] = 0,
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0,
	@rStockItemCode [nvarchar](100) = '',
	@rStockItemTitle [nvarchar](300) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF ISNULL(@rStockItemId, 0) = 0
BEGIN
IF (ISNULL(@rStockItemCode, '' ) <> '')
SELECT @rStockItemId = Id FROM sIp.tStockItemMaster WHERE Code = @rStockItemCode AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0 And StoreLocationId = @rStoreLocationId

IF ISNULL(@rStockItemId, 0) = 0
BEGIN
IF (ISNULL(@rStockItemTitle, '' ) <> '')
SELECT @rStockItemId = Id FROM sIp.tStockItemMaster WHERE Title = @rStockItemTitle  AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0 And StoreLocationId = @rStoreLocationId
END
END
DECLARE @lStockBatchId Int 
SET @lStockBatchId = -1
IF ISNULL(@rStockItemId, 0) = 0 AND ISNULL(@rId, 0) <> -1
BEGIN
SELECT		-101			AS Id, 
			''				AS Code,
			''				AS Title, 
			CAST(0 AS BIT)	AS IsBatchWiseTracking,
			''				AS UOMCode,
			''				AS UOMTitle,
			0				AS AvailableQuantity,
			-101			AS StoreLocationId,
			-101			AS StockItemId,
			@lStockBatchId	AS StockBatchId
			
END
ELSE
BEGIN

--SELECT		@lStockBatchId = SB.Id 
--FROM		sProcurement.tStockBatch SB
--INNER JOIN	sIp.tStockItemMaster SIM
--			ON SIM.Id = SB.StockItemId 
--WHERE		StoreLocationId = @rStoreLocationId
--AND			StockItemId = @rStockItemId
--AND			SIM.IsBatchWiseTracking = 0

SELECT		SIM.Id, 
			SIM.Code,
			SIM.Title, 
			SIM.IsBatchWiseTracking,
 
			--SIM.IssueStockUomId,
			SUMa.Code				AS UOMCode,
			SUMa.Title				AS UOMTitle,
			TBL.AvailableQuantity,
			TBL.StoreLocationId,
			TBL.StockItemId,
			TBL.StockBatchId			AS StockBatchId 
FROM		sIp.tStockItemMaster SIM
INNER JOIN (
			SELECT	MAX(Id)					AS StockBatchId,
					StoreLocationId, 
					StockItemId, 
					SUM(AvailableQuantity)  AS AvailableQuantity
			FROM 
			sProcurement.tStockBatch 
			WHERE OrgGroupId = @rOrgGroupId
			GROUP BY StoreLocationId, StockItemId
			) TBL
			ON TBL.StockItemId = SIM.Id 
INNER JOIN  sFinanceCommon.tStockUomMaster SUMa
			ON SUMa.Id = SIM.IssueStockUomId
WHERE		((TBL.StoreLocationId = @rStoreLocationId ) OR (@rStoreLocationId = 0))
AND			((TBL.StockItemId = @rStockItemId ) OR (@rStockItemId = 0))
AND         SIM.OrgGroupId = @rOrgGroupId
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchAdd]
	@rOrgId [int],
	@rStoreLocationId [int],
	@rStockItemId [int],
	@rNumber [nvarchar](20),
	@rExpiryDate [date],
	@rAvailableQuantity [decimal](12, 2),
	@rCreatedUserId [bigint],
	@rPrice decimal(12,2)=0,
	@rStockBatchId [int]=0 OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN
 
	DECLARE @lNextNumber INT
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgId, 'sProcurement.tStockBatch',@lNextNumber = @lNextNumber output

	INSERT INTO sProcurement.tStockBatch
		(
			Id,
			StoreLocationId,
			StockItemId,
			Number,
			ExpiryDate,
			AvailableQuantity,
			ItemRate,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rStoreLocationId,
			@rStockItemId,
			@rNumber,
			@rExpiryDate,
			@rAvailableQuantity,
			@rPrice,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
	SET @rStockBatchId = @lNextNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchAddUpdate]
    
    --@rId bigint=0,
	@rStoreLocationId int=0,
	--@rStockItemId int=0,
	--@rNumber nvarchar(20)='',
	--@rStockItemTypeId [int],
	--@rExpiryDate date='',	 
	 @rAvailableQuantity decimal(12,2)=0,	 
	--@rCreatedUserId bigint=0,
	@rOrgGroupId smallint=0,
	--@rPrice decimal(12,2)=0,
	@rStockInwardDetailId int=0,
	@rbatchNo int=0
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

  
BEGIN
	--Declare @lAvailableQty decimal(12,2)
	--Select @lAvailableQty = AvailableQuantity from sProcurement.tStockBatch where Id=@rbatchNo  AND StoreLocationId=@rStoreLocationId AND OrgId=@rOrgId
 --Select @lAvailableQty
	--if(@rId=0)
	--BEGIN

	 DECLARE @lNextNumber INT 
	EXECUTE sCommon.pTableRowIdGet  @rOrgGroupId, 'sProcurement.tStockInwardBatch', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sProcurement.tStockInwardBatch
	(
		Id,StockInwardDetailId,Quantity,StockBatchId,OrgGroupId
	)
	Values
	(
		@lNextNumber,@rStockInwardDetailId,@rAvailableQuantity,@rbatchNo,@rOrgGroupId
	)
	Select 1 as result
	--EXECUTE sCommon.pTableRowIdGet  @rOrgId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumber output

	--INSERT INTO sProcurement.tStockBatch
	--	(
	--		Id,
	--		 StoreLocationId,
	--		 StockItemId,
	--		 Number,
	--		 ExpiryDate,
	--		 AvailableQuantity,
	--		 CreatedUserId,
	--		 CreatedDateTime,
	--		 OrgId,
	--		 Price
			 
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		 @rStoreLocationId,
	--		 @rStockItemId,
	--		 @rNumber,
	--		 @rExpiryDate,
	--		 @rAvailableQuantity,
	--		 @rCreatedUserId,
	--		 sCommon.fGetDate(),
	--		 @rOrgId,
	--		 @rPrice
	--	)
	--END
	--else
	--BEGIN
	--	Update sProcurement.tStockBatch Set AvailableQuantity =@lAvailableQty + @rAvailableQuantity 
	--	WHere Id=@rId
	--END
	 
 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchAvailableQuantity]
	@rOrgId [int], 
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON      

   DECLARE @rId INT = 0
   DECLARE @rAvailableQuantity DECIMAl(12,2) = 0.00

BEGIN  
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
   --IF EXISTS(SELECT Id,AvailableQuantity FROM sProcurement.tStockBatch WHERE (StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
	 	-- (StockItemId = @rStockItemId OR @rStockItemId = 0) --AND OrgId = @rOrgId  --Commented as No orgid is there in table
		 --)
   --     BEGIN
        
   -- 	SELECT Id,AvailableQuantity
		 --FROM sProcurement.tStockBatch WHERE (StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
	 	-- (StockItemId = @rStockItemId OR @rStockItemId = 0)-- AND OrgId = @rOrgId--Commented as No orgid is there in table
    		 
   --     END
   -- ELSE
     
      SELECT 0 AS Id, 0.00 AS AvailableQuantity
       
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchDetailsGet]
	@rOrgGroupId [int],	
	@rId [bigint] = 0,
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0,
	@rGoodsReceiptNoteDetailId [bigint] = 0,
	@rGoodsReceiptNoteReqd [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


SELECT		
			SB.Id						AS StockBatchId,
			SB.StoreLocationId			AS StoreLocationId,
			SB.StockItemId				AS StockItemId,
			GRN.GoodsReceiptNoteDetailId,
			GRN.GoodsReceiptBatchId 	AS GoodsReceiptBatchId,
			SB.number					AS BatchNumber, 
			SB.Expirydate				AS ExpiryDate,
			SB.AvailableQuantity		AS AvailableQuantity,
			GRN.ReceiptQuantity			AS ReceiptQuantity,
			GRN.ReceiptBonusQuantity	AS ReceiptBonusQuantity,
			CASE WHEN @rGoodsReceiptNoteReqd = 1 THEN
			GRN.UOM 
			ELSE
			UOM.UOM 
			END							AS UOM,
			CAST(ISNULL(GRN.ConversionFactor, 0) AS NVARCHAR(10)) AS ConversionFactor
FROM		sProcurement.tStockBatch SB
LEFT JOIN	
			(
			SELECT		GRND.Id						AS GoodsReceiptNoteDetailId,
						GRN.StoreLocationId,
						GRNB.Number,
						GRNB.Id						AS GoodsReceiptBatchId,
						POD.ItemSourceId,
						GRND.ReceiptQuantity, 
						GRND.ReceiptBonusQuantity,
						ESIPU.Title					AS UOM,
						SIPUOM.ConversionFactor		AS ConversionFactor
			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	sProcurement.tGoodsReceiptNoteBatch GRNB 
						ON GRNB.GoodsReceiptNoteDetailId = GRND.Id
			INNER JOIN	sIp.tStockItemPurchaseUom SIPUOM 
						ON SIPUOM.Id = POD.StockItemPurchaseUomId
			INNER JOIN	sIp.vExtStockItemPurchaseUom ESIPU 
						ON  ESIPU.Id = POD.StockItemPurchaseUomId
			WHERE GRN.OrgGroupId = @rOrgGroupId
			) GRN
			ON	GRN.StoreLocationId = SB.StoreLocationId
			AND GRN.ItemSourceId = SB.StockItemId
			AND	GRN.Number = SB.Number
			AND @rGoodsReceiptNoteReqd = 1
INNER JOIN	(
			SELECT		SIM.Id		AS StockItemId,
						SUoM.Title	AS UOM
			FROM		sIp.tStockItemMaster SIM 
			INNER JOIN	sFinanceCommon.tStockUomMaster SUoM
						ON SUoM .Id = SIM.IssueStockUomId
						WHERE SIM.OrgGroupId = @rOrgGroupId
						AND SIM.StoreLocationId = @rStoreLocationId
			)UOM
			ON UOM.StockItemId = SB.StockItemId
WHERE		(SB.storelocationid = @rStoreLocationId OR @rStoreLocationId = 0) 
AND			(SB.StockItemId = @rStockItemId OR @rStockItemId = 0)
AND			(GRN.GoodsReceiptNoteDetailId = @rGoodsReceiptNoteDetailId OR @rGoodsReceiptNoteDetailId = 0)
AND			(( @rGoodsReceiptNoteReqd = 1 AND ISNULL(GRN.GoodsReceiptNoteDetailId, 0) > 0 ) OR @rGoodsReceiptNoteReqd = 0)
AND			SB.AvailableQuantity > 0
AND			SB.ExpiryDate >= CAST(scommon.fgetdate() AS DATE)
AND         SB.OrgGroupId = @rOrgGroupId


--SELECT		
--			SB.Id AS StockBatchId,
--			SB.StoreLocationId AS StoreLocationId,
--			SB.StockItemId AS StockItemId,
--			GRNB.Id AS GoodsReceiptBatchId,
--			SB.number AS BatchNumber, 
--			SB.Expirydate AS ExpiryDate,
--			SB.AvailableQuantity AS AvailableQuantity,
--			GRND.ReceiptQuantity AS ReceiptQuantity,
--			GRND.ReceiptBonusQuantity AS ReceiptBonusQuantity,
--			'1' AS UOM,
--			'1' AS ConversionFactor
--FROM		sProcurement.tStockBatch SB
--LEFT JOIN	sProcurement.tGoodsReceiptNote GRN 
--			ON GRN.StoreLocationId = SB.storelocationid AND @rGoodsReceiptNoteReqd = 1
--LEFT JOIN	sProcurement.tGoodsReceiptNoteDetail GRND 
--			ON GRND.GoodsReceiptNoteId = GRN.Id AND @rGoodsReceiptNoteReqd = 1
--LEFT JOIN	sProcurement.tPurchaseOrderDetail POD
--			ON POD.Id = GRND.PurchaseOrderDetailId
--			AND POD.ItemSourceId = SB.StockItemId 
--			AND @rGoodsReceiptNoteReqd = 1
--LEFT JOIN	sProcurement.tGoodsReceiptNoteBatch GRNB 
--			ON GRNB.GoodsReceiptNoteDetailId = GRND.Id
--			AND GRNB.Number = SB.Number
--			AND @rGoodsReceiptNoteReqd = 1
--WHERE		(SB.storelocationid = @rStoreLocationId OR @rStoreLocationId = 0) 
----AND (SB.number = GRNB.Number)
--AND			(SB.StockItemId = @rStockItemId OR @rStockItemId = 0)
--AND			(GRND.Id = @rGoodsReceiptNoteDetailId OR @rGoodsReceiptNoteDetailId = 0)


--	 SELECT DISTINCT
--	SB.Id AS StockBatchId,
--	SB.StoreLocationId AS StoreLocationId,
--	SB.StockItemId AS StockItemId,
--	GRNB.Id AS GoodsReceiptBatchId,
--	SB.number AS BatchNumber, 
--	SB.Expirydate AS ExpiryDate,
--	SUM(SB.AvailableQuantity) AS AvailableQuantity,
--	GRND.ReceiptQuantity AS ReceiptQuantity,
--	GRND.ReceiptBonusQuantity AS ReceiptBonusQuantity,
--	'1' AS UOM,
--	'1' AS ConversionFactor
--FROM sProcurement.tstockBatch SB 
--	LEFT JOIN	sProcurement.tGoodsReceiptNote GRN 
--				ON GRN.StoreLocationId = SB.storelocationid
--	LEFT JOIN	sProcurement.tGoodsReceiptNoteDetail GRND 
--				ON GRND.GoodsReceiptNoteId = GRN.Id
--	LEFT JOIN	sProcurement.tGoodsReceiptNoteBatch GRNB 
--				ON GRNB.GoodsReceiptNoteDetailId = GRND.Id
--				AND GRNB.BatchNumber
--	WHERE (SB.storelocationid = @rStoreLocationId OR @rStoreLocationId = 0) 
--	--AND (SB.number = GRNB.Number)
--	AND (SB.StockItemId = @rStockItemId OR @rStockItemId = 0)
--	AND (GRND.Id = @rGoodsReceiptNoteDetailId OR @rGoodsReceiptNoteDetailId = 0)
--	GROUP BY SB.StockItemId, SB.Number, SB.ExpiryDate, SB.StoreLocationId, SB.Id,
--	 GRND.ReceiptQuantity, GRND.ReceiptBonusQuantity, GRNB.Id

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchForIssueReturnModify]
	@rOrgGroupId [int],	
	@rId [bigint] = 0,
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0,
	@rNumber [nvarchar](20) = '',
	@rExpiryDate [date] = '1/1/1900',
	@rQuantity [decimal](12, 2) = 0,
	@rUpdatedUserId [bigint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

DECLARE @lAvailableQty Decimal(12,2)
SET @lAvailableQty = 0
DECLARE @loNextNumber INT

BEGIN
BEGIN TRY
--To get ItemCode
DECLARE @lItemCode nVarchar(20)
SELECT @lItemCode = Code FROM sIp.tStockItemMaster WHERE Id = ISNULL(@rStockItemId, 0) AND OrgGroupId = @rOrgGroupId AND StoreLocationId = @rStoreLocationId

IF @rQuantity > 0
BEGIN
	
	SELECT @lAvailableQty = AvailableQuantity FROM sProcurement.tStockBatch WHERE Id = @rId AND OrgGroupId = @rOrgGroupId AND StoreLocationId = @rStoreLocationId
	IF @lAvailableQty > 0 AND @lAvailableQty >= @rQuantity
	BEGIN
	
		--UPDATE sProcurement.tStockBatch
		--SET 
		--		AvailableQuantity = AvailableQuantity + @rQuantity,
		--		UpdatedUserId = @rUpdatedUserId,
		--		UpdatedDateTime = sCommon.fGetDate()
		--WHERE (Id = @rId OR @rId = 0) 
		
		SET @loNextNumber =  (SELECT Id FROM sProcurement.tStockBatch WHERE StoreLocationId = @rStoreLocationId 
							AND StockItemId = @rStockItemId AND ISNULL(Number, '') = ISNULL(@rNumber, '') AND ISNULL(ExpiryDate, '') = ISNULL(@rExpiryDate, '')  AND OrgGroupId =  @rOrgGroupId AND StoreLocationId = @rStoreLocationId )
		SET @loNextNumber = ISNULL(@loNextNumber, 0)	 
			IF @loNextNumber > 0
			BEGIN
				UPDATE sProcurement.tStockBatch
				SET 
					AvailableQuantity = AvailableQuantity + @rQuantity,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 				 
				 Id = @loNextNumber AND OrgGroupId = @rOrgGroupId
				 
				 
				SELECT Result = @loNextNumber, 'Updated Successfully' AS Msg, @loNextNumber AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
				
			END
			ELSE
			BEGIN
				SET @rNumber = (CASE WHEN @rNumber = '' THEN NULL ELSE @rNumber END)
				SET @rExpiryDate = (CASE WHEN @rExpiryDate = '' THEN NULL ELSE @rExpiryDate END)
				EXECUTE sProcurement.pStockBatchAdd 
				@rOrgGroupId = @rOrgGroupId,
				 @rStoreLocationId = @rStoreLocationId, @rStockItemId = @rStockItemId, 
				 @rNumber = @rNumber,
				 @rExpiryDate = @rExpiryDate, @rAvailableQuantity = @rQuantity, @rCreatedUserId = @rUpdatedUserId, @rStockBatchId = @loNextNumber OUTPUT
				SELECT Result = @loNextNumber, 'Inserted Successfully' AS Msg, @loNextNumber AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
			END
	END
	ELSE
	BEGIN
		SELECT Result = -101, 'Insufficient Available Qty' AS Msg, @loNextNumber AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
	END	
END
END TRY
BEGIN CATCH
	SELECT Result = -1, ERROR_MESSAGE() AS Msg, @loNextNumber AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
	SELECT ERROR_MESSAGE()
END CATCH
END

/**********************************************OLD SP START W/O Add************************************************************/
--DECLARE @lAvailableQty Decimal(12,2)
--SET @lAvailableQty = 0


--BEGIN
--BEGIN TRY
----To get ItemCode AND Batch number
--DECLARE @lItemCode nVarchar(20)
--DECLARE @lBatchNumber nVarchar(20)


	


--IF ISNULL(@rId,  0) <> 0
--BEGIN
--	SELECT @lBatchNumber = Number FROM sProcurement.tStockBatch WHERE Id = @rId
--	SELECT @lItemCode = Code FROM sIp.tStockItemMaster WHERE Id = (SELECT StockItemId FROM sProcurement.tStockBatch WHERE Id = @rId)
	
--	IF @rQuantity > 0
--		BEGIN
			
--			SELECT @lAvailableQty = AvailableQuantity FROM sProcurement.tStockBatch WHERE Id = @rId
--			IF @lAvailableQty >= 0
--				BEGIN
				
--					UPDATE sProcurement.tStockBatch
--					SET 
--							AvailableQuantity = AvailableQuantity + @rQuantity, 
--							UpdatedUserId = @rUpdatedUserId, 
--							UpdatedDateTime = sCommon.fGetDate()
--					WHERE (Id = @rId OR @rId = 0) 
					
--					SELECT Result = @rId,  'Updated Successfully' AS Msg,  @rId AS Id,  @lBatchNumber AS BatchNumber,  @lItemCode AS ItemCode
					
					
--				END
--			ELSE
--				BEGIN
--					SELECT Result = -101,  'Insufficient Available Qty' AS Msg,  @rId AS Id,  @lBatchNumber AS BatchNumber,  @lItemCode AS ItemCode
--				END	
--		END
--END
--ELSE
--	SELECT Result = -1,  'No BatchId To Update' AS Msg,  @rId AS Id,  '' AS BatchNumber,  '' AS ItemCode
--END TRY
--BEGIN CATCH
--	SELECT Result = -1,  ERROR_MESSAGE() AS Msg,  @rId AS Id,  @rNumber AS BatchNumber,  @lItemCode AS ItemCode
--	SELECT ERROR_MESSAGE()
--END CATCH
--END

/**********************************************OLD SP START W/O Add************************************************************/

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchForTransferModify]
	@rOrgGroupId [int],	
	@rId [bigint] = 0,
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0,
	@rNumber [nvarchar](20) = '',
	@rExpiryDate [date] = '1/1/1900',
	@rQuantity [decimal](12, 2) = 0,
	@rUpdatedUserId [bigint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

DECLARE @lAvailableQty Decimal(12,2)
SET @lAvailableQty = 0
DECLARE @loNextNumber INT

BEGIN
BEGIN TRY
--To get ItemCode
DECLARE @lItemCode nVarchar(20)
SELECT @lItemCode = Code FROM sIp.tStockItemMaster WHERE Id = ISNULL(@rStockItemId, 0) AND OrgGroupId = @rOrgGroupId AND StoreLocationId = @rStoreLocationId

IF @rQuantity > 0
BEGIN
	
	SELECT @lAvailableQty = AvailableQuantity FROM sProcurement.tStockBatch WHERE Id = @rId AND OrgGroupId = @rOrgGroupId AND StoreLocationId = @rStoreLocationId
	IF @lAvailableQty > 0 AND @lAvailableQty >= @rQuantity
	BEGIN
	
		UPDATE sProcurement.tStockBatch
		SET 
				AvailableQuantity = AvailableQuantity - @rQuantity,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
		WHERE (Id = @rId OR @rId = 0) 
		AND OrgGroupId = @rOrgGroupId
		AND StoreLocationId = @rStoreLocationId
		SET @loNextNumber =  (SELECT Id FROM sProcurement.tStockBatch WHERE StoreLocationId = @rStoreLocationId 
							AND StockItemId = @rStockItemId AND ISNULL(Number, '') = ISNULL(@rNumber, '') AND ISNULL(ExpiryDate, '') = ISNULL(@rExpiryDate, '') AND OrgGroupId = @rOrgGroupId)
		SET @loNextNumber = ISNULL(@loNextNumber, 0)	 
			IF @loNextNumber > 0
			BEGIN
				UPDATE sProcurement.tStockBatch
				SET 
					AvailableQuantity = AvailableQuantity + @rQuantity,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 				 
				 Id = @loNextNumber
				 AND OrgGroupId = @rOrgGroupId
				 
				SELECT Result = @loNextNumber, 'Updated Successfully' AS Msg, @loNextNumber AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
				
			END
			ELSE
			BEGIN
				EXECUTE sProcurement.pStockBatchAdd @rOrgGroupId, @rStoreLocationId = @rStoreLocationId, @rStockItemId = @rStockItemId, @rNumber = @rNumber, @rExpiryDate = @rExpiryDate, @rAvailableQuantity = @rQuantity, @rCreatedUserId = @rUpdatedUserId, @rStockBatchId = @loNextNumber OUTPUT
				SELECT Result = @loNextNumber, 'Inserted Successfully' AS Msg, @loNextNumber AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
			END
	END
	ELSE
	BEGIN
		SELECT Result = -101, 'Insufficient Available Qty' AS Msg, @loNextNumber AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
	END	
END
END TRY
BEGIN CATCH
	SELECT Result = -1, ERROR_MESSAGE() AS Msg, @loNextNumber AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
	SELECT ERROR_MESSAGE()
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchGet]
	@rOrgGroupId [int],	
	@rId [bigint] = 0,
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT distinct SB.Id,
			SB.StoreLocationId,
			SLM.Code AS LocationCode,
			SLM.Title AS LocationTitle,
			SB.StockItemId,
			SB.Number,
			SB.ExpiryDate,
			SB.AvailableQuantity,
	    	SUMA.Code AS UOM,
			SUMA.Title AS UOMTitle,
			SIM.IsBatchWiseTracking,
			SB.CreatedUserId,
			SB.CreatedDateTime,
			SB.UpdatedUserId,
			SB.UpdatedDateTime
	   FROM sProcurement.tStockBatch SB
	   LEFT JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = SB.StoreLocationId
	   LEFT JOIN sIp.tStockItemMaster SIM ON SIM.Id = SB.StockItemId
	   LEFT JOIN sFinanceCommon.tStockUomMaster SUMA ON SUMA.Id = SIM.IssueStockUomId
	  WHERE ((SB.Id = @rId) OR (@rId = 0)) AND
	  ((SB.StockItemId = @rStockItemId) OR (@rStockItemId = 0)) AND
	  ((SB.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	  --AND (SB.ExpiryDate >= CAST(scommon.fgetdate() AS DATE) OR SB.ExpiryDate IS NULL)
	  AND SB.OrgGroupId= @rOrgGroupId
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchModify]
	@rOrgGroupId [int],	
	@rId [bigint] = 0,
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0,
	@rNumber [nvarchar](20) = '',
	@rExpiryDate [date] = '1/1/1900',
	@rQuantity [decimal](12, 2) = 0,
	@rCurrentReceiptQuantity [decimal](12, 2) = 0,
	@rCurrentReceiptBonusQuantity [decimal](12, 2) = 0,
	@rUpdatedUserId [bigint] = 0,
	@rIdReqd [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

DECLARE @lAvailableQty Decimal(12,2)
SET @lAvailableQty = 0

--SELECT @rExpiryDate
IF @rExpiryDate <> ''

SET @rExpiryDate = CAST(@rExpiryDate AS DATE)
BEGIN
BEGIN TRY

IF ISNULL(@rId, 0) = 0 OR @rId < 0
BEGIN
SELECT	@rId = Id 
FROM	sProcurement.tStockBatch 
WHERE	(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
		(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
		(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
		(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
		 OrgGroupId = @rOrgGroupId
END
--To get ItemCode
DECLARE @lItemCode nVarchar(20)
SELECT @lItemCode = Code FROM sIp.tStockItemMaster WHERE Id = ISNULL(@rStockItemId, 0) AND OrgGroupId = @rOrgGroupId And StoreLocationId = @rStoreLocationId

IF @rQuantity > 0
	BEGIN
		IF @rIdReqd = 0
		BEGIN
			SET @rId = 0
		END
		
		SELECT @lAvailableQty = AvailableQuantity FROM sProcurement.tStockBatch 
		WHERE (Id = @rId OR @rId = 0) 
			AND 
		(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
		(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
		(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
		(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
		OrgGroupId = @rOrgGroupId
		
		IF @lAvailableQty > 0 AND @lAvailableQty >= @rQuantity
			BEGIN
				 UPDATE sProcurement.tStockBatch
					SET 
						AvailableQuantity = AvailableQuantity - @rQuantity,
						UpdatedUserId = @rUpdatedUserId,
						UpdatedDateTime = sCommon.fGetDate()
				  WHERE (Id = @rId OR @rId = 0) 
						AND
					 (StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
					 (StockItemId = @rStockItemId OR @rStockItemId = 0) AND
					 (Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
					 (ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
					  OrgGroupId = @rOrgGroupId
				  SELECT Result = 1, 'Successfully Updated FRM GREN' AS Msg, @rId AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode, @rExpiryDate
			  END
		 ELSE
		BEGIN
			SELECT Result = -101, 'Insufficient Available Qty' AS Msg, @rId AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
		END
	END
ELSE IF @rQuantity = 0 AND @rCurrentReceiptQuantity > 0
	BEGIN
			
		SET @rId = ISNULL(@rId, 0)	 
		IF @rId > 0
			BEGIN
				 UPDATE sProcurement.tStockBatch
					SET 
						AvailableQuantity = AvailableQuantity + @rCurrentReceiptQuantity + @rCurrentReceiptBonusQuantity,
						UpdatedUserId = @rUpdatedUserId,
						UpdatedDateTime = sCommon.fGetDate()
				  WHERE (Id = @rId OR @rId = 0) AND
					 (StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
		(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
		(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
		(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
		OrgGroupId = @rOrgGroupId
		
				  SELECT Result = 1, 'Successfully Updated FRM GRN' AS Msg, @rId AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
			  END
		ELSE
		BEGIN
		DECLARE @loNextNumber INT
		DECLARE @lTotalQuantity Decimal(12,2)
		SET @lTotalQuantity = SUM(@rCurrentReceiptQuantity + @rCurrentReceiptBonusQuantity)
		EXECUTE sProcurement.pStockBatchAdd @rOrgGroupId = @rOrgGroupId, @rStoreLocationId = @rStoreLocationId, @rStockItemId = @rStockItemId, @rNumber = @rNumber, @rExpiryDate = @rExpiryDate, @rAvailableQuantity = @lTotalQuantity, @rCreatedUserId = @rUpdatedUserId, @rStockBatchId = @loNextNumber OUTPUT
		 SELECT Result = @loNextNumber, 'Successfully Inserted' AS Msg, @loNextNumber AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
		END	
		
	END
ELSE IF @rQuantity <= 0
	BEGIN		
		 
			BEGIN
				 UPDATE sProcurement.tStockBatch
					SET 
						AvailableQuantity = AvailableQuantity - @rQuantity,
						UpdatedUserId = @rUpdatedUserId,
						UpdatedDateTime = sCommon.fGetDate()
				  WHERE (Id = @rId OR @rId = 0) 
				  AND OrgGroupId = @rOrgGroupId
						
				  SELECT Result = 1, 'Successfully Updated' AS Msg, @rId AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
			  END	 
		 
	END	
	
END TRY
BEGIN CATCH
SELECT Result = -3, ERROR_MESSAGE() AS Msg, @rId AS Id, @rNumber AS BatchNumber, @lItemCode AS ItemCode
SELECT ERROR_MESSAGE()
END CATCH
END
--SELECT * FROM sProcurement.tStockBatch

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchModifyUsingDispense]
	@rOrgId [int], 
	@rStoreLocationId [int] = 0,
	@rStockItemId [int] = 0,
	@rQuantity decimal(12,2) = 0.00
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

       DECLARE @1AvailableQuantity Decimal(12,2) 
       DECLARE @1Id Int    


select @1AvailableQuantity =  AvailableQuantity  FROM sProcurement.tStockBatch WHERE (StoreLocationId = @rStoreLocationId  AND StockItemId = @rStockItemId)

BEGIN      
    --Commented on 19/06/2025 - Invalid column name 'OrgId'.
--    IF(@1AvailableQuantity >= @rQuantity)
    
--		 UPDATE  sProcurement.tStockBatch
                 
--         SET  AvailableQuantity = AvailableQuantity - @rQuantity
--	     WHERE  
--		(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
--		(StockItemId = @rStockItemId OR @rStockItemId = 0) 
--		--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
--		--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
--		AND OrgId = @rOrgId --Commented as No orgid is there in table

--SELECT SB.Id,AvailableQuantity,ISNULL(SIP.WeightedAverageCost,0) AS WeightedAverageCost  
--FROM sProcurement.tStockBatch SB INNER JOIN sIp.tStockItemMaster SIM 
--ON SIM.Id = SB.StockItemId  
--INNER JOIN sIp.tStockItemPlanning SIP 
--ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
--WHERE (SB.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) 
--AND (SB.StockItemId = @rStockItemId OR @rStockItemId = 0) 
--AND SB.OrgId = @rOrgId  
SELECT 0 AS Id, 0 AS AvailableQuantity,0 AS WeightedAverageCost 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchQuantityCheck]
	
	
	@rStockInwardBatchId int,
	@rStoreLocationId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	Declare @lStockBatchId int
	SET @lStockBatchId=(SELECT StockBatchId From sProcurement.tStockInwardBatch WHERE Id=@rStockInwardBatchId)
	
	SELECT 
			SB.AvailableQuantity,SIM.Title AS StockItemName From sProcurement.tStockBatch SB
			INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId
			
			WHERE SB.Id=@lStockBatchId AND SB.StorelocationId=@rStoreLocationId


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
-- exec [sProcurement].[pStockBatchUpdate]
-- drop proc [sProcurement].[pStockBatchUpdate]
CREATE OR ALTER PROCEDURE [sProcurement].[pStockBatchUpdate]
(
@rStockItemId [int],
@rStoreLocationId Int, 
@rStockBatchId int = 0,
@rNumber nvarchar(50)='',
@rExpiryDate date='' 
)
AS
SET NOCOUNT ON
 
BEGIN
	 
	 if not exists(Select 1 from sProcurement.tStockBatch where StockItemId =@rStockItemId  and isnull(Number,'')<> ''  AND StoreLocationId =@rStoreLocationId)
	 BEGIN
		Select -101 AS Result
		Return
	 END
	 Update sProcurement.tStockBatch Set Number =@rNumber,ExpiryDate = @rExpiryDate Where StockItemID =@rStockItemId AND StoreLocationId=@rStoreLocationId and Id=@rStockBatchId

	SELECT 1 AS Result 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockEnquiryDetailGet]
	@rOrgGroupId [int],
	@rDepartmentId [int] = 0,
	@rStockItemCode [nvarchar](20) = '',
	@rStockItemName [nvarchar](50) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	SELECT 
			SB.StoreLocationId AS DepartmentId,
			ISNULL(SB.ExpiryDate, NULL) AS ExpiryDate,
			ISNULL(SB.Number, NULL) AS BatchNumber,
			SIM.Code AS StockItemCode,
			SIM.Title AS StockItemName,
			SUOM.Title AS UOM,
			ISNULL(SB.AvailableQuantity, 0) AS SQuantity,
			SLM.Title AS DepartmentName
	FROM
			sIp.tStockItemMaster SIM
			INNER JOIN 
				sProcurement.tStockBatch SB
			ON 
				SIM.Id = SB.StockItemId
			INNER JOIN
				sFinanceCommon.tStockUomMaster SUOM
			ON
				SUOM.Id = SIM.IssueStockUomId
			INNER JOIN 
				sIp.tStoreLocationMaster SLM
			ON 
				SLM.Id = SB.StoreLocationId
			
	WHERE  
			((SB.StoreLocationId = @rDepartmentId) OR (@rDepartmentId = 0))
			--AND	((SIM.Title = @rStockItemName) OR (@rStockItemName = ''))
			AND ((SIM.Code = @rStockItemCode) OR (@rStockItemCode = ''))	
			AND     SIM.OrgGroupId = @rOrgGroupId
	GROUP BY 
				SB.StoreLocationId,
				SB.ExpiryDate,
				SB.Number,
				SIM.Code,
				SIM.Title,
				SLM.Title,
				SB.AvailableQuantity,
				SUOM.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockEnquirySearchGet]
	@rOrgGroupId [int],
	@rDepartmentId [int] = 0,
	@rStockItemId [int] = 0,
	@rStockItemCode [nvarchar](20) = '',
	@rStockItemName [nvarchar](50) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	IF @rDepartmentId <> 0
		BEGIN
		    --SET @rStockItemCode = sCommon.fSearchStringGet(@rStockItemCode)
			SET @rStockItemName = sCommon.fSearchStringGet(@rStockItemName)
		END
		
	IF @rDepartmentId = 0
		BEGIN	
				SELECT 
					SB.StoreLocationId AS DepartmentId,
					SB.StockItemId,
					SIM.Code AS StockItemCode,
					SIM.Title AS StockItemName,
					ISNULL(SUM(SB.AvailableQuantity), 0) AS Quantity,
					SLM.Title AS DepartmentName
				
				FROM sIp.tStockItemMaster SIM
					INNER JOIN 
						sProcurement.tStockBatch SB
					ON 
						SIM.Id = SB.StockItemId
					INNER JOIN 
						sIp.tStoreLocationMaster SLM
					ON 
						SLM.Id = SB.StoreLocationId
					
				WHERE  ((SB.StoreLocationId = @rDepartmentId) OR (@rDepartmentId = 0))
				AND    ((SB.StockItemId = @rStockItemId) OR (@rStockItemId = 0))
				--AND	   ((SIM.Title LIKE @rStockItemName) OR (@rStockItemName = ''))
				AND    ((SIM.Code LIKE @rStockItemCode) OR (ISNULL(@rStockItemCode, '') = ''))	
				AND     SIM.OrgGroupId = @rOrgGroupId
				
				GROUP BY SB.StoreLocationId,
						 SB.StockItemId,
						 SLM.Title,
						 SIM.Code, 
						 SIM.Title
				
		END
	ELSE
		BEGIN
				SELECT 
					SB.StoreLocationId AS DepartmentId,
					SB.StockItemId,
					SIM.Code AS StockItemCode,
					SIM.Title AS StockItemName,
					ISNULL(SUM(SB.AvailableQuantity), 0) AS Quantity,
					SLM.Title AS DepartmentName
				
				FROM sIp.tStockItemMaster SIM
					INNER JOIN 
						sProcurement.tStockBatch SB
					ON 
						SIM.Id = SB.StockItemId
					INNER JOIN 
						sIp.tStoreLocationMaster SLM
					ON 
						SLM.Id = SB.StoreLocationId
				
				WHERE ((SB.StoreLocationId = @rDepartmentId) OR (@rDepartmentId = 0))
				AND    ((SB.StockItemId = @rStockItemId) OR (@rStockItemId = 0))
				--AND	   ((SIM.Title LIKE @rStockItemName) OR (@rStockItemName = ''))
				AND    ((SIM.Code LIKE @rStockItemCode) OR (ISNULL(@rStockItemCode, '') = ''))	
				AND     SIM.OrgGroupId = @rOrgGroupId
				
				GROUP BY SB.StoreLocationId,
						 SB.StockItemId,
						 SLM.Title,
						 SIM.Code, 
						 SIM.Title 
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockFreezeAdjustmentAdd]
	@rNumber [nvarchar](20) OUTPUT,
	@rCreatedUserId [bigint],
	@rStoreLocationId [int],
	@rStockFreezeAdjustmentDetailXml [nvarchar](max),
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--DECLARE @lNextNumber INT
	--EXECUTE sCommon.pTableRowIdGet @rOrgId,'sProcurement.tStockFreezeAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output

	--DECLARE @loNextNumber nVarchar(20)
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId=@rOrgId,@rPrefixFunctionalityId = 102,@rStoreLocationId=@rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
	----SELECT @loNextNumber
	--IF (@loNextNumber IS NULL)
	--BEGIN
	--	RAISERROR('5000', 15, 106)
	--	RETURN
	--END
		
	--INSERT INTO sProcurement.tStockFreezeAdjustment
	--	(
	--		Id,
	--		Number,			
	--		CreatedUserId,
	--		CreatedDateTime
	--		,OrgId 
	--	)
	--VALUES
	--	(
	--		@lNextNumber,
	--		@loNextNumber,			
	--		@rCreatedUserId,
	--		sCommon.fGetDate()
	--		,@rOrgId
	--	)
		
	--SET @rNumber = @loNextNumber
	--EXEC sProcurement.pStockFreezeAdjustmentDetailAdd @rOrgId,@lNextNumber, @rStoreLocationId, @rCreatedUserId,@rStockFreezeAdjustmentDetailXml



----select * from sProcurement.tStockFreezeAdjustment
--	--DECLARE @lIntErrorCode INT, @lIntDoc INT
--	--EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
--	--DECLARE @tStockFreezeAdjustmentDetail TABLE
--	--(
--	--Id								Int IDENTITY(0, 1),
--	--StockFreezeAdjustmentId			Int, 
--	--StockBatchId					Int, 
--	--StockItemId						Int,
--	--SystemQuantity					Decimal(12,2),
--	--PhysicalQuantity				Decimal(12,2),  
--	--StockVerificationApprovalId 	Int
--	--)
	
--	--INSERT INTO @tStockFreezeAdjustmentDetail  
--	--(  
--	--	StockFreezeAdjustmentId,
--	--	StockBatchId,
--	--	StockItemId,
--	--	SystemQuantity,
--	--	PhysicalQuantity,
--	--	StockVerificationApprovalId
--	--)
--	--SELECT	@lNextNumber,
--	--		StockBatchId, 
--	--		StockItemId,
--	--		SystemQuantity,
--	--		PhysicalQuantity,
--	--		StockVerificationApprovalId
			
			
--	--FROM OPENXML (@lIntDoc, '/Root/StockFreezeAdjustmentDetail', 1)  
--	--	WITH  
--	--	(   
--	--		StockBatchId					Nvarchar(300)		'@StockBatchId', 
--	--		StockItemId						Nvarchar(300)		'@StockItemId'
--	--		SystemQuantity					Nvarchar(300)		'@SystemQuantity', 
--	--		PhysicalQuantity				Nvarchar(300)		'@PhysicalQuantity', 
--	--		ApprovalQuantity				Nvarchar(300)		'@ApprovalQuantity'
--	--		StockVerificationApprovalId		Nvarchar(300)		'@StockVerificationApprovalId'
--	--	) XmlTable
	
--	--DECLARE @lNextNumberStockFreezeAdjustmentDetail BigInt
--	--EXECUTE @lNextNumberStockFreezeAdjustmentDetail = sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockFreezeAdjustment', 0, 1, 1
	
	
--	--INSERT INTO sProcurement.tStockFreezeAdjustmentDetail
--	--	(
--	--		Id,
--	--		StockFreezeAdjustmentId,
--	--		StockBatchId,
--	--		StockItemId,
--	--		StoreLocationId,
--	--		SystemQuantity,
--	--		PhysicalQuantity,
--	--		StockVerificationApprovalId, 
--	--		OrgId
--	--	)
--	--SELECT 	@lNextNumberStockFreezeAdjustmentDetail + Id, 
--	--		StockFreezeAdjustmentId,
--	--		StockBatchId, 
--	--		StockItemId, 
--	--		@rStoreLocationId,
--	--		SystemQuantity,
--	--		PhysicalQuantity, 
--	--		StockVerificationApprovalId, 
--	--		@rOrgId
--	--FROM	@tStockFreezeAdjustmentDetail
	
--	--UPDATE @tStockFreezeAdjustmentDetail SET StockFreezeAdjustmentDetailId = @lNextNumberStockFreezeAdjustmentDetail + Id 
--	--SELECT @lNextNumberStockFreezeAdjustmentDetail = MAX(Id) + @lNextNumberStockFreezeAdjustmentDetail FROM @tStockFreezeAdjustmentDetail
--	--EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sProcurement.tStockFreezeAdjustmentDetail', @rCurrentNumber = @lNextNumberStockFreezeAdjustmentDetail 
SELECT 0 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockFreezeAdjustmentDetailAdd]
	@rOrgId [int],
	@rStockFreezeAdjustmentId [int],
	@rStoreLocationId [int],
	@rCreatedUserId [bigint],
	@rStockFreezeAdjustmentDetailXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	--DECLARE @loIdoc INT
	--DECLARE @lStockFreezeAdjustmentDetailCurrentId INT
	--DECLARE @lCount INT 
		
	--SET @lCount = 0	

	--EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockFreezeAdjustmentDetailXml
	--EXEC sCommon.pTableRowIdGet @rOrgId,  'sProcurement.tStockFreezeAdjustmentDetail', 1, 1, 1,@outNextNumber = @lStockFreezeAdjustmentDetailCurrentId output

	--INSERT INTO sProcurement.tStockFreezeAdjustmentDetail
	--	(
	--		Id,
	--		StockFreezeAdjustmentId,
	--		StockBatchId,
	--		StockItemId,
	--		StoreLocationId,
	--		SystemQuantity,
	--		PhysicalQuantity,			
	--		StockVerificationApprovalId
	--		,OrgId 
	--	)
	--SELECT  
	--	@lStockFreezeAdjustmentDetailCurrentId + ROW_NUMBER() OVER(ORDER BY StockBatchId) AS Id, 
	--	@rStockFreezeAdjustmentId,
	--	StockBatchId,
	--	StockItemId,
	--	@rStoreLocationId,
	--	SystemQuantity,		
	--	ApprovalQuantity,
	--	StockVerificationApprovalId
	--	,@rOrgId 
	--FROM OPENXML (@loIdoc, '/StockFreeze/StockFreezeAdjustmentDetail', 1)
	--	WITH ( 
	--			StockBatchId INT, 
	--			StockItemId INT,
	--			SystemQuantity DECIMAL(22, 6),
	--			PhysicalQuantity DECIMAL(22, 6),
	--			ApprovalQuantity DECIMAL(22, 6),
	--			StockVerificationApprovalId BIGINT
	--		  ) 
		
	--	SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockFreeze/StockFreezeAdjustmentDetail', 1)
	--			 WITH ( AssetId INT)
		
		
	--	UPDATE sProcurement.tStockBatch
	--	SET AvailableQuantity = XmlTable.ApprovalQuantity,
	--	UpdatedUserId = @rCreatedUserId,
	--	UpdatedDateTime = sCommon.fGetDate()
	--	,OrgId = @rOrgId 
	--	FROM		
	--	OPENXML (@loIdoc, '/StockFreeze/StockFreezeAdjustmentDetail', 1)
	--			WITH (
	--					StockBatchId INT, 
	--					ApprovalQuantity DECIMAL(22, 6)				 
						
	--				 ) XmlTable
	--	WHERE sProcurement.tStockBatch.Id = XmlTable.StockBatchId	
		
	--	SET @lStockFreezeAdjustmentDetailCurrentId  = @lCount + @lStockFreezeAdjustmentDetailCurrentId 
		
	--	EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sProcurement.tStockFreezeAdjustmentDetail', @rCurrentNumber = @lStockFreezeAdjustmentDetailCurrentId 
	SELECT 0 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockFreezeAdjustmentDetailGet]
	@rOrgId [int],
	@rStoreLocationId int,
	@rNumber [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		--Commented on 19/06/2025 - Invalid column name 'OrgId'.
		--SELECT 
		--		sProcurement.tStockFreezeAdjustmentDetail.Id,
		--		StockFreezeAdjustmentId,
		--		StockBatchId,
		--		SIP.StockItemId,
		--		SIP.StoreLocationId,
		--		SystemQuantity,
		--		PhysicalQuantity,
		--		StockVerificationApprovalId,
		--		SIP.WeightedAverageCost
		--FROM 
		--		sProcurement.tStockFreezeAdjustmentDetail
		--INNER JOIN
		--		sProcurement.tStockFreezeAdjustment
		--ON
		--		sProcurement.tStockFreezeAdjustment.Id = sProcurement.tStockFreezeAdjustmentDetail.StockFreezeAdjustmentId
		--INNER JOIN 
		--		sIp.tStockItemMaster SIM
		--ON 
		--		sProcurement.tStockFreezeAdjustmentDetail.StockItemId = SIM.Id
		--INNER JOIN sIp.tStockItemPlanning SIP 
		--ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId			
		
		--WHERE
		--		sProcurement.tStockFreezeAdjustment.Number = @rNumber
				--AND SIM.OrgId = @rOrgId 
		SELECT 
				0 AS Id,
				0 AS StockFreezeAdjustmentId,
				0 AS StockBatchId,
				0 AS StockItemId,
				0 AS StoreLocationId,
				0 AS SystemQuantity,
				0 AS PhysicalQuantity,
				0 AS StockVerificationApprovalId,
				0 AS WeightedAverageCost
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockFreezeAdjustmentGet]
	@rOrgId [int],
	@rStoreLocationId int ,
	@rNumber [nvarchar](50)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
		--SELECT Id, Number FROM sProcurement.tStockFreezeAdjustment
		--	WHERE Number like @rNumber 
		--	AND OrgId = @rOrgId
		--EXEC sProcurement.pStockFreezeAdjustmentDetailGet @rOrgId,@rStoreLocationId, @rNumber
	SELECT 0 AS Result
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockFreezeGet]
	@rOrgGroupId [int],
	@rStoreLocationId [int],
	@rItemMainGroupId [int],
	@rStatusId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

		BEGIN
		
		DECLARE  @tItemFreeze TABLE
		(
			Id BIGINT, 
			ItemTypeCode NVARCHAR(50),
			ItemTypeTitle NVARCHAR(300),
			StoreLocationId INT,
			Department NVARCHAR(300),
			CreatedDateTime DATETIME,
			UnfreezedDateTime DATETIME,
			StatusId INT
		)
		
		
		INSERT INTO  @tItemFreeze
		(Id, ItemTypeCode, ItemTypeTitle, StoreLocationID, Department, CreatedDateTime, UnfreezedDateTime, StatusId)
		(SELECT DISTINCT 
		ISNULL(SIF.ID, 0) AS ID,
		IMGM.ID AS ItemTypeCode,
		IMGM.Title AS ItemTypeTitle,
		SB.StoreLocationId,
		SLM.Title AS  Department,
		ISNULL(SIF.CreatedDateTime, NULL) AS CreatedDateTime,
		ISNULL(SIF.UnfreezedDateTime, NULL) AS UnfreezedDateTime, 
		ISNULL(SIF.StatusId, 0) AS StatusId
		
		
		 FROM sProcurement.tStockBatch SB
		INNER JOIN sIp.tStockItemMaster SIM
			ON    SIM.Id = SB.StockItemId
		--INNER JOIN sIp.tStockItemTypeMaster SITM
		--	ON SIM.StockItemTypeId = SITM.Id
		INNER JOIN sIp.tItemSubGroupMaster ISGM
			ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM
			ON IMGM.Id=ISGM.ItemMainGroupId
			INNER JOIN sIp.tStoreLocationMaster SLM
				 ON SB.StoreLocationId = SLM.Id
		LEFT JOIN sProcurement.tStockItemFreeze SIF
			ON SIF.StoreLocationId = SB.StoreLocationId AND SIF.ItemMainGroupId = IMGM.Id AND SIF.StatusId = 140
		
		 WHERE (SB.StoreLocationId  = @rStoreLocationId) 
	   AND ((IMGM.Id = @rItemMainGroupId ) OR (@rItemMainGroupId = 0)) AND SIM.OrgGroupId = @rOrgGroupId) 
	   
	     
	     
	    SELECT Id, 
			ItemTypeCode,
			ItemTypeTitle,
			StoreLocationId,
			Department,
			CreatedDateTime,
			ISNULL(ITemF.UnfreezedDateTime, T2.UnfreezedDateTime) UnfreezedDateTime,
			StatusId  FROM @tItemFreeze ITemF
		LEFT JOIN(		
		SELECT ItemMainGroupId, MAX(UnfreezedDateTime)  UnfreezedDateTime FROM (SELECT Id, ItemMainGroupId, UnfreezedDateTime FROM sProcurement.tStockItemFreeze WHERE StoreLocationId = @rStoreLocationId 	AND OrgGroupId = @rOrgGroupId AND ItemMainGroupId IN
		(SELECT ItemTypeCOde FROM @tItemFreeze WHERE StatusId = 0  ) AND StatusId = 141) T1 GROUP BY ItemMainGroupId) T2
		ON ITemF.ItemTypeCode = T2.ItemMainGroupId 
		WHERE  ((ITemF.StatusId = @rStatusId)  OR( @rStatusId = 0))  --AND   ((ITemF.ItemTypeCode = @rItemTypeId ) OR (@rItemTypeId = 0))
		--AND ((ITemF.Id = @rItemMainGroupId ) OR (@rItemMainGroupId = 0)) 
		
	   
END

--select * from sProcurement.tStockItemFreeze

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInward]
	
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rStoreLocationId int,
	@rFromDate date='',
	@rToDate date='',
	@rVendorId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	  
	SELECT		
			SI.Id,
			SI.Number,
			isnull(SI.StockInwardRequestId,0) as StockInwardRequestId,
			isnull(SI.InwardByName,'') as InwardByName,
			SI.CreatedDateTime			AS TransactionDate,
			SLM.Code					AS ToStoreLocationCode,
			SIReq.Number				AS RequestNumber,	
			SI.TransactionDate AS InwardDate,
			SIReq.CreatedDateTime AS RequestedDate,		
			--Case when SI.TransactionDate is not null then SI.TransactionDate else isnull(SIReq.CreatedDateTime,'') end
			--AS RequestedDate,
			SI.VendorId,
			 SIM.Code AS StockItemCode,
					SIM.TItle As StockItemName
			
	FROM		
		    sProcurement.tStockInward SI
			INNER JOIN	sIp.tStoreLocationMaster SLM ON SLM.Id = SI.ToStoreLocationId 		
			LEFT JOIN	sProcurement.tStockInwardRequest SIReq ON SIReq.Id = SI.StockInwardRequestId
			
			Inner join sProcurement.tStockInwardDetail SIDE on SI.ID= SIDE.StockInwardId
			INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SIDE.StockItemID

	WHERE		
			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = '*'))
			AND        SI.OrgGroupId = @rOrgGroupId	
			AND ((SI.CreatedDateTime>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SI.CreatedDateTime<=DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
			AND SI.ToStoreLocationId =@rStoreLocationId
			AND ((SI.VendorId=@rVendorId) or (@rVendorId=0))
			order by SI.Number desc
 
END


--select *From  sProcurement.tStockInwardDetail

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInward_Get]
	@rOrgGroupId int,
	@rId [int] = 0,
	@rNumber [nvarchar](20) = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	   
SELECT		SIDe.Id,
			SIDe.StockInwardId,
			SIDe.StockItemId,
			SIDe.RequestedQuantity,
			SIDe.InwardQuantity,
			SIDe.InwardValue,
			SIDe.Remark,
			SIM.Code				AS StockItemCode,
			SIM.Title				AS StockItemName,
			SUMa.Code				AS UOM,
			SIM.IsBatchWiseTracking,
			SIB.Id As StockInwardBatchId,
			SIB.StockBatchId, 
 			SIB.Quantity As InwardQuantity,
			isnull(SB.Number,'') AS Number,
			isnull(SB.ExpiryDate,'') as ExpiryDate , 
			SB.AvailableQuantity,
			isnuLL(SI.StockInwardRequestId,0) as StockInwardRequestId,
			SI.InwardByName,
			SI.CreatedDateTime			AS InwardDate,
			SI.ToStoreLocationId,
			SLM.Code					AS ToStoreLocationCode,
			SI.CreatedUserId			AS UserId,
			isnULL(SIReq.Number	,'')AS RequestNumber,
			ISNULL(SIReq.CreatedDateTime,'')AS RequestedDate
		 
FROM		sProcurement.tStockInwardDetail SIDe
			INNER JOIN	sProcurement.tStockInward SI ON SI.Id = SIDe.StockInwardId
			INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SIDe.StockItemId 
			INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
			LEFT JOIN sProcurement.tStockInwardBatch SIB ON SIB.StockInwardDetailId= SIDe.Id
			LEFT JOIN	sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId AND SB.Number!=''
			INNER JOIN	sIp.tStoreLocationMaster SLM ON SLM.Id = SI.ToStoreLocationId 		
LEFT JOIN	sProcurement.tStockInwardRequest SIReq ON SIReq.Id = SI.StockInwardRequestId
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId
AND			SI.ToStoreLocationId = @rStoreLocationId
 

 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To add records to sProcurement.tStockInward table
	Created date     : 09 Jan 2012
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Added @rStockInwardRequestId field
	Test script      : EXECUTE sProcurement.pStockInwardAdd @rNumber = '', @rStockInwardRequestId = 0, @rInwardByName = '', @rToOrganizationDepartmentId = 0, @rToStoreLocationId = 0, @rRemark = '', @rCreatedUserId = 0, @rDetail = ''
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardAdd]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rStockInwardRequestId			Int, 
		@rInwardByName					Nvarchar(100) = '',
		--@rToOrganizationDepartmentId	Int,
		@rToStoreLocationId				Int,
		--@rFirstAidId					Int,
		@rRemark						Nvarchar(300),
		@rCreatedUserId					BigInt,
		@rDetail						Nvarchar(Max)
	)
AS

SET NOCOUNT ON

BEGIN
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT

SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tStockInward WHERE ToStoreLocationId = @rToStoreLocationId
SET @rNumber = @rNumber + 1

--SET @rNumber = ISNULL(@rNumber, '-300')

--IF @rNumber = '-300'
--BEGIN

 
--SELECT -300 AS Result, '' AS Number, 0 AS Id 
--RETURN
--END
	
	DECLARE @lNextNumberStockInward INT
 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockInward',@lNextNumber = @lNextNumberStockInward output
 
 
	INSERT INTO sProcurement.tStockInward
		(
			Id,
			Number,
			StockInwardRequestId, 
			InwardByName,		 
			ToStoreLocationId,			 
			Remark,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumberStockInward,
			@rNumber,
		   (CASE WHEN @rStockInwardRequestId = 0 THEN NULL ELSE @rStockInwardRequestId END),	 
			@rInwardByName,		 
			@rToStoreLocationId,			 
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)


	DECLARE @lIntErrorCode INT, @lIntDoc INT
	EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	DECLARE @tStockInwardDetail TABLE
	(
	Id						Int IDENTITY(0, 1),
	StockInwardDetailId		Int, 
	StockInwardRequestDetailId	Int, 
	StockInwardId 			Int, 
	StockItemId				Int, 
	InwardQuantity			Decimal(12,2),
	RequestedQuantity		Decimal(12,2),  
	InwardValue 			Decimal(12,2),
	Remark					Nvarchar(300)
	)
	
	INSERT INTO @tStockInwardDetail  
	(  
		StockInwardId,
		StockItemId,
		InwardQuantity,
		RequestedQuantity,
		InwardValue,
		StockInwardRequestDetailId, 
		Remark
	)
	SELECT	@lNextNumberStockInward, 
			StockItemId,
			InwardQuantity,
			RequestedQuantity,
			InwardValue,
			(CASE WHEN StockInwardRequestDetailId = 0 THEN NULL ELSE StockInwardRequestDetailId END), 			
			Remark
			
	FROM OPENXML (@lIntDoc, '/Root/StockInwardDetail', 1)  
		WITH  
		(  
			StockItemId				Nvarchar(300)	'@StockItemId', 
			InwardQuantity			Nvarchar(300)	'@InwardQuantity', 
			RequestedQuantity		Nvarchar(300)	'@RequestedQuantity', 
			InwardValue			Nvarchar(300)		'@InwardValue', 
			StockInwardRequestDetailId  Nvarchar(300)'@StockInwardRequestDetailId', 
			Remark					Nvarchar(300)	'@Remark'
		) XmlTable
	
	DECLARE @lNextNumberStockInwardDetail BigInt
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardDetail output
	
	
	INSERT INTO sProcurement.tStockInwardDetail
		(
			Id,
			StockInwardId,
			StockItemId,
			InwardQuantity,
			RequestedQuantity,
			InwardValue,
			StockInwardRequestDetailId, 
			Remark,
			OrgGroupId
		)
	SELECT 	@lNextNumberStockInwardDetail + Id, 
			StockInwardId, 
			StockItemId, 
			InwardQuantity,
			RequestedQuantity, 
			InwardValue,
			StockInwardRequestDetailId, 
			Remark,
			@rOrgGroupId
	FROM	@tStockInwardDetail
	
	UPDATE @tStockInwardDetail SET StockInwardDetailId = @lNextNumberStockInwardDetail + Id 
	SELECT @lNextNumberStockInwardDetail = MAX(Id) + @lNextNumberStockInwardDetail FROM @tStockInwardDetail
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockInwardDetail', @rCurrentNumber = @lNextNumberStockInwardDetail 
	
	DECLARE @tBatch TABLE
	(
		Id						Int IDENTITY(0, 1), 
		StockInwardDetailId	Int,
		StockBatchId Int,		
		Quantity				Decimal(12,2),
		StockItemId				Int				
	)
	
	INSERT INTO @tBatch  
			(  
			StockInwardDetailId,	
			StockBatchId, 
			Quantity,
			StockItemId									
			)
	SELECT	1, 
			StockBatchId, 
			Quantity,
			StockItemId
	FROM OPENXML (@lIntDoc, '/Root/StockInwardDetail/StockInwardBatch', 1)  
		WITH  
		(  
			StockBatchId 	Nvarchar(200)	'@StockBatchId', 
			Quantity					Nvarchar(200)	'@Quantity',
			StockItemId					Nvarchar(200)	'@StockItemId' 			
		) XmlTable	
		
		
	DECLARE @lNextNumberBatch BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output
	
	INSERT INTO sProcurement.tStockInwardBatch
		(
			Id,
			StockInwardDetailId,
			StockBatchId,
			Quantity,
			OrgGroupId
		)
	SELECT 		@lNextNumberBatch + TD.Id, 
				STD.StockInwardDetailId, 
				StockBatchId, 
				Quantity,
				@rOrgGroupId
	FROM		@tStockInwardDetail STD 
	INNER JOIN	@tBatch TD 
				ON TD.StockItemId = STD.StockItemId
				
	SELECT @lNextNumberBatch = MAX(Id) + @lNextNumberBatch FROM @tBatch
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockInwardBatch', @rCurrentNumber = @lNextNumberBatch 
	
	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockInward AS Id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- drop procedure [sProcurement].[pStockInwardAdd_New]
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rStockInwardRequestId			Int=0, 
		@rInwardByName					Nvarchar(100) = '',
		--@rToOrganizationDepartmentId	Int,
		@rToStoreLocationId				Int,
		--@rFirstAidId					Int,
		@rRemark						Nvarchar(300)='',
		@rCreatedUserId					BigInt,
		@rDetail						Nvarchar(Max),
		@rLocationId int,
		@rOrgId int,
		@rVendorId int=0,
		@rInwardDate datetime = null,
		@rCreatedOnDate datetime = null,
		@rBillNoRemark						Nvarchar(300)='' --Added by dhananjay for mantis - 0034876
		--@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
Declare @loXML XML
SET @loXML = CAST(@rDetail AS XML)
 
	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1005,
	@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
	
	SET @rNumber = ISNULL(@rNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	END

	
 
	DECLARE @tStockInwardDetailBatch TABLE
	(
		Id						Int IDENTITY(1, 1),
		StockInwardRequestDetailId	Int, 
		StockItemId				Int, 
		StockItemName nvarchar(50),
		ItemBatch Nvarchar(300) NULL,
		ItemExpiryDate nvarchar(20) NULL,	
		InwardQuantity			Decimal(12,2),
		RequestedQuantity		Decimal(12,2),  
		InwardValue 			Decimal(12,2) 
		 
	)	
	INSERT INTO @tStockInwardDetailBatch
	Select 
		 T.c.value('@StockInwardRequestDetailId','int') AS StockInwardRequestDetailId,
            T.c.value('@StockItemId','Int') AS StockItemId,
            T.c.value('@StockItemName','nvarchar(50)') AS StockItemName,
            T.c.value('@ItemBatch','Nvarchar(300)') AS ItemBatch,
            T.c.value('@ItemExpiryDate','nvarchar(20)')   AS ItemExpiryDate,
            T.c.value('@InwardQuantity','Decimal(12,2)') AS InwardQuantity,
            T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity,
            T.c.value('@InwardValue','Decimal(12,2)') AS InwardValue 
			 
	
	FROM 
            @loXML.nodes('/Table/StockInward')T(c)
	
	
	
	DECLARE @lNextNumberStockInward INT
 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockInward',@lNextNumber = @lNextNumberStockInward output
	Declare @lNextNumberStockInwardBatch bigint
  
	INSERT INTO sProcurement.tStockInward
		(
			Id,
			Number,
			StockInwardRequestId, 
			InwardByName,		 
			ToStoreLocationId,			 
			Remark,
			TransactionDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			VendorId
		)
	VALUES
		(
			@lNextNumberStockInward,
			@rNumber,
		   (CASE WHEN @rStockInwardRequestId = 0 THEN NULL ELSE @rStockInwardRequestId END),	 
			@rInwardByName,		 
			@rToStoreLocationId,			 
			@rBillNoRemark,				--Added by dhananjay for mantis - 0034876
			@rInwardDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rVendorId
		)


	DECLARE @lIntErrorCode INT, @lIntDoc INT
	EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	DECLARE @lCount int,@lIsBatchWise bit,@lbatchId int,@lNextNumberStockBatch int,@lExpiryDate date,
			@lItemId int,@lBatch nvarchar(300),@lInwardQty decimal(12,2),@lInwardValue decimal(12,2),
			@lIdCount int,@lNextNumberStockInwardDetail bigint,@lStockItemName nvarchar(50)
	Select @lCount=Count(*) from  @tStockInwardDetailBatch
	
	 
	While(@lCount>0)
	BEGIN
		  
	    Select @lItemId =StockItemId,@lBatch = [ssetup].[fPortalXMLTagsReplaceReverse](ItemBatch),@lInwardQty=InwardQuantity,@lInwardValue=InwardValue
	    ,@lIdCount=Id,@lExpiryDate =ItemExpiryDate
		,@lStockItemname=[ssetup].[fPortalXMLTagsReplaceReverse](StockItemname)
		from  @tStockInwardDetailBatch WHERE Id = @lcount
		Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster    Where Id = @lItemId   
		
		 
		SET @lbatchId = 0
			
	    if (@lIsBatchWise=1)
		BEGIN
			Select @lbatchId= Id from sProcurement.tStockBatch    
			Where  Number =@lBatch   AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId
		END
		else 
		BEGIN
			Select @lbatchId= Id from sProcurement.tStockBatch    
			Where iSNULl( Number,'') =''  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId
		END	
		 
		if(ISNULL(@lbatchId,0)=0)
	    BEGIN
			
		 	EXECUTE sCommon.pTableRowIdGet @rOrggroupId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockBatch output
			INSERT INTO sProcurement.tStockBatch (Id,StoreLocationId,StockItemId,Number,ExpiryDate,AvailableQuantity,ItemRate,CreatedUserId
			,CreatedDateTime,OrgGroupId)
			Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate ,0,0,@rCreatedUserId,getdate(),@rOrgGroupId
			
			SET @lbatchId = @lNextNumberStockBatch
			
	    End
	
		if(isnull(@lbatchId,0)>0)
		BEGIN
			 
			if Exists(Select Id from sProcurement.tStockInwardDetail   
			where  StockInwardId = @lNextNumberStockInward  and  StockItemId = @lItemId  )
			BEGIN
					 
					Select @lNextNumberStockInwardDetail= Id from  sProcurement.tStockInwardDetail
					Where  StockInwardId = @lNextNumberStockInward AND StockIteMid =@lItemId
			END
			ELSE
			BEGIN
			
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardDetail output
				INSERT INTO sProcurement.tStockInwardDetail
				(	
					Id,StockInwardId,StockItemId,RequestedQuantity,InwardQuantity, 
					Remark,StockInwardRequestDetailId,OrgGroupId,InwardValue
				)
				SELECT @lNextNumberStockInwardDetail ,@lNextNumberStockInward,StockItemId,RequestedQuantity,
					    InwardQuantity,@rRemark,StockInwardRequestDetailId,@rOrgGroupId,@lInwardValue
					   from @tStockInwardDetailBatch where Id=@lcount
			END
			
			
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardBatch output
							
							INsert into sProcurement.tStockInwardBatch
							(Id,StockInwardDetailId,Quantity,StockBatchId,OrgGroupId)
							Select @lNextNumberStockInwardBatch,@lNextNumberStockInwardDetail,InwardQuantity,@lbatchId,@rOrgGroupID
							from @tStockInwardDetailBatch where Id=@lcount
							
							
							Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=1010,@rSourceId=@lNextNumberStockInwardBatch,
												@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lInwardQty ,@rValue=@lInwardValue,@rIsReceipt=1,
												@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId ,@rLocationId=@rLocationId
												,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname,@rOrgId=@rOrgId


			END
			set @lcount =@lcount-1
	END
	 
	 SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockInward AS Id 
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardBulkGet]
	
	@rId [int] = 0,
	@rOrgGroupId int,
	@rMainGroupId int,
	@rStoreLOcationId int,
	@rItemName nvarchar(500)='',
	@rItemCode nvarchar(500)='',
	@rSubGroupId int = 0,
	@rCatagoryid int = 0
	--@rIsDrug int = 0
 			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

 SET @rItemName = sCommon.fSearchStringGet(@rItemName)
	SELECT
		SIM.Code AS ItemCode,
		SIM.Title AS ItemName,
		SIM.Id AS StockItemId ,
		SIM.IsBatchWiseTracking as IsBatchWiseTracking
		--SIM.IsFirstAdd AS FirstAid
	FROM 
			sIp.tStockItemMaster SIM
			INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
			INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
			 
			
	WHERE 
		SIM.OrgGroupId=@rOrgGroupId
		AND((IMGM.Id=@rMainGroupId) OR (@rMainGroupId=0))
		AND((SIM.StoreLocationId=@rStoreLOcationId) OR (@rStoreLOcationId=0))
		AND(SIM.IsObsolete =0)
		AND ((SIM.Title LIKE @rItemName) OR (ISNULL(@rItemName, '') = ''))
		AND (ISNULL(SIM.Code,'') IN (SELECT item FROM  sCommon.fnsplit(@rItemCode,',')) OR @rItemCode='')
		AND(ISGM.Id=@rSubGroupId OR @rSubGroupId=0)
		AND(SIM.StockItemCategoryId=@rCatagoryid OR @rCatagoryid=0)
		--AND Number is null AND ExpiryDate is null
	    --AND (SIM.IsFirstAdd = (CASE @rISDrug 
		 		--					WHEN 1 THEN 1  			
		 		--	                ELSE SIM.IsFirstAdd 6
	 			--                END))
	 			                order by SIM.Title ASC
		
		 			   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardDetailGet]
	@rOrgGroupId int,
	@rId [bigint] = 0,
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
 
SELECT		SIDe.Id,
			SIDe.StockInwardId,
			SIDe.StockItemId,
			SIDe.RequestedQuantity,
			--SIDe.InwardQuantity,
			 SIDe.InwardValue ,
			SIDe.Remark,
			SIM.Code				AS StockItemCode,
			SIM.Title				AS StockItemName,
			 SUMa.Code				AS UOM,
			SIM.IsBatchWiseTracking ,
			ISNULL(B.Id,0) As StockInwardBatchId,
			ISNULL(B.StockBatchId,0) AS StockBatchId,
			 
			B.Quantity AS InwardQuantity,
			--ISNULL(B.Value,0) AS InwardValue,
			SB.Number AS 'Batch No',
			ISNULL(SB.ExpiryDate,'') AS ExpiryDate,
			ISNULL(SB.AvailableQuantity,0) As AvailableQuantity ,		 
			ISNULL(VM.Code,'') AS VendorCode,
			ISNULL(VM.Id,0) AS VendorId,
			case when (select Max(id) From sIp.tWeightedAverageCostLog WaCN Where WaCN.ItemSourceId=SIDe.StockItemId and SourceTypeId in (1010,2020) AND ItemSourceTypeId = 34) = Isnull(WAC.Id,0) then 'true' else 'false' end as CanEdit -- added for to check last transaction BY MS 2019-10-10
			
 
FROM		sProcurement.tStockInwardDetail SIDe
INNER JOIN	sProcurement.tStockInward SI ON SI.Id = SIDe.StockInwardId
LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id= SI.VendorId
INNER JOIN	sIp.tStockItemMaster SIM ON SIM.Id = SIDe.StockItemId 
INNER JOIN  sFinanceCommon.tStockUomMaster SUMa	ON SUMa.Id = SIM.IssueStockUomId
LEFT JOIN sProcurement.tStockInwardBatch B ON B.StockInwardDetailId= SIDe.Id
LEFT JOIN	sProcurement.tStockBatch SB	ON SB.Id = B.StockBatchId 
Inner join sIp.tWeightedAverageCostLog WAC on WAC.SourceId=B.Id and WAC.SourceTypeId in (1010,2020) AND ItemSourceTypeId = 34 AND SIDe.StockItemId = WAC.ItemSourceId -- added for update last transaction BY MS 2019-10-10		 
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId

 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardGet]
	@rOrgGroupId int,
	@rId [int] = 0,
	@rNumber [nvarchar](20) = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
SELECT		SI.Id,
			SI.Number,
			SI.StockInwardRequestId,
			SI.InwardByName,
			--SI.ToOrganizationDepartmentId,
			SI.ToStoreLocationId,
			--ISNULL(SI.FirstAidId,0) As FirstAidId,
			SI.Remark,
			SI.CreatedUserId			AS UserId,
			case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End AS InwardDate,
			SLM.Code					AS ToStoreLocationCode,
			--ODM.Title					AS ToOrganizationDepartmentCode,
			--ISNULL(FAM.Title,'')        AS FirstAid,
			SIReq.Number				AS RequestNumber,
			SIReq.CreatedDateTime		AS RequestedDate,
			ISNULL(SI.VendorId,0) As VendorId ,
			ISNULL(VM.Code,'') AS VendorCode,
			 SI.CreatedDateTime  as TranjactionDate 
			
			
FROM		sProcurement.tStockInward SI
INNER JOIN	sIp.tStoreLocationMaster SLM
			ON SLM.Id = SI.ToStoreLocationId 		
LEFT JOIN	sProcurement.tStockInwardRequest SIReq
			ON SIReq.Id = SI.StockInwardRequestId
LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id=SI.VendorID			

WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId
AND			SI.ToStoreLocationId = @rStoreLocationId


SELECT		SIDe.Id,
			SIDe.StockInwardId,
			SIDe.StockItemId,
			SIDe.RequestedQuantity,
			SIDe.InwardQuantity,
			SIDe.InwardValue,
			SIDe.Remark,
			SIM.Code				AS StockItemCode,
			SIM.Title				AS StockItemName,
			SUMa.Code				AS UOM,
			SIM.IsBatchWiseTracking
 
FROM		sProcurement.tStockInwardDetail SIDe
INNER JOIN	sProcurement.tStockInward SI
			ON SI.Id = SIDe.StockInwardId
INNER JOIN	sIp.tStockItemMaster SIM 
			ON SIM.Id = SIDe.StockItemId AND SIM.StoreLocationId = @rStoreLocationId
INNER JOIN  sFinanceCommon.tStockUomMaster SUMa
			ON SUMa.Id = SIM.IssueStockUomId
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId
AND			SI.ToStoreLocationId = @rStoreLocationId


SELECT	SIB.Id,
			SIB.StockInwardDetailId,
			SIB.StockBatchId,
			SIB.Quantity,
			SB.Number AS BatchName,
			SB.ExpiryDate, 
			SB.AvailableQuantity
FROM		sProcurement.tStockInwardBatch SIB
INNER JOIN	sProcurement.tStockInwardDetail SIDe
			ON SIDe.Id = SIB.StockInwardDetailId
INNER JOIN	sProcurement.tStockInward SI
			ON SI.Id = SIDe.StockInwardId
INNER JOIN	sProcurement.tStockBatch SB
			ON SB.Id = SIB.StockBatchId
INNER JOIN	sIp.tStockItemMaster SIM 
			ON SIM.Id = SIDe.StockItemId AND SIM.StoreLocationId = @rStoreLocationId
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId
AND			SI.ToStoreLocationId = @rStoreLocationId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardNumberGet]
	
	
	@rId int,
	@rStorelocationId int,
	@rNumber nvarchar(50) = ''
 			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN


	SELECT
		SI.Id,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIND.InwardQuantity,
		SIND.InwardValue,
		SIB.Id AS StockInwardBatchId,
		SIB.StockBatchId,
		SIND.Id AS StockInwardDetailId,
		SIM.Id AS StockItemId,
		Sb.Number as 'StockBatchNumber' ,
		(SELECT ISNULL(SUM(SIRB.Quantity),0) FROM sProcurement.tStockInwardReturn SIR 
		INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id WHERE SIR.StockInwardId=SI.Id AND SIRB.StockInwardBatchId=SIB.Id)
		 AS ReturnedQuantity
	FROM 
		sProcurement.tStockInward SI 
		INNER JOIN sProcurement.tStockInwardDetail SIND ON SIND.StockInwardId=SI.Id
		INNER JOIN sProcurement.tStockInwardBatch SIB ON SIB.StockInwardDetailId=SIND.Id
		left join sProcurement.tStockBatch Sb on sb.id = SIB.StockBatchId and sb.Number is not null
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId	
			
	WHERE 
		((SI.Id = @rId) OR (@rId = 0))
		AND	((SI.Number Like @rNumber) OR (ISNULL(@rNumber, '') = ''))
		AND SI.ToStoreLocationId=@rStorelocationId
		 			   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardReqGet]
	@rOrgGroupId int,
	@rNumber nvarchar(20),
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rStatusId int=0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT SIR.Id,
			SIR.Number,
			SIR.FromStoreLocationId,	 
			SIR.RequestedByName,
			SIR.Remark,
			SIR.CreatedDateTime,
			ISNULL(SIR.StatusId,0) AS StatusId,
			SM.Title As Status
			
	  FROM sProcurement.tStockInwardRequest SIR
	  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=SIR.StatusID
	  WHERE  
			((SIR.Number like '%'+ @rNumber+'%') OR (@rNumber='*'))
	  AND SIR.OrgGroupId = @rOrgGroupId
	  AND  (( SIR.CreatedDateTime>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 AND (( SIR.CreatedDateTime<=DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
	 AND SIR.FromStoreLocationId = @rStoreLocationId
	 AND ((SIR.StatusId=@rStatusId) OR (@rStatusId=0))
	  --AND ((SIR.STatusId=@rStatusId) OR (@rStatusId=0))
	  --AND ((SIR.VendorId=@rVendorId) OR (@rVendorId=0))
	  Order by  SIR.Number  desc
	   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardRequestAdd]
	@rOrgGroupId int,
	@rFromStoreLocationId [int],	 
	@rRequestedByName [nvarchar](100),
	@rCreatedUserId [bigint],
	@rStockInwardRequestXml [nvarchar](max),
	@rId [int] OUTPUT,
	@rNumber Nvarchar(20) = '',
	@rStatusId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockInwardRequest',@lNextNumber = @lNextNumber output	
	DECLARE @loNextNumber nVarchar(20)
	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1004,@rStoreLocationId = @rFromStoreLocationId,
	 @rNextNumber = @loNextNumber OUTPUT
	
	 
	
	IF (@loNextNumber IS NULL)
		BEGIN
			RAISERROR('5000', 15, 106)
			RETURN
		END
 
 --SELECT @rNumber = ISNULL(max(cast (Number as int)),0)   FROM sProcurement.tStockInwardRequest WHERE FromStoreLocationId = @rFromStoreLocationId
--SET @rNumber = @rNumber + 1

	INSERT INTO sProcurement.tStockInwardRequest
		(
			Id,
			Number,
			FromStoreLocationId,			 
			RequestedByName,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			StatusId
			
		)
	VALUES
		(
			@lNextNumber,
			@loNextNumber,
			@rFromStoreLocationId,			 
			@rRequestedByName,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rStatusId
		)
	SET @rId = @lNextNumber
	 EXEC [sProcurement].pStockInwardRequestDetailAdd @rOrgGroupId, @lNextNumber, @rStockInwardRequestXml
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardRequestDetailAdd]
	@rOrgGroupId int,
	@rStockInwardRequestId [int],
	@rStockInwardRequestXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loIdoc INT
	DECLARE @lStockInwardRequestDetailCurrentId INT 
	DECLARE @lCount INT
	Declare @lNextNumber INT
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockInwardRequestXml
 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockInwardRequestDetail',@lNextNumber = @lNextNumber output

	INSERT INTO sProcurement.tStockInwardRequestDetail
		(
			Id,
			StockInwardRequestId,
			StockItemId,
			RequestedQuantity,
			Remark,			
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
		@lNextNumber + ROW_NUMBER() OVER(ORDER BY StockItemId) AS Id, 
		@rStockInwardRequestId,
		StockItemId,
		RequestedQuantity,
		Remark,		
		UpdatedUserID,
		sCommon.fGetDate(),
		@rOrgGroupId
	FROM OPENXML (@loIdoc, '/StockInwardRequest/StockInwardRequestDetail', 1)
		WITH ( 
				StockItemId INT, 
				RequestedQuantity DECIMAL(22, 6), 
				Remark NVARCHAR(300),				
				UpdatedUserID BIGINT
			  ) 
	SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockInwardRequest/StockInwardRequestDetail', 1)
				 WITH ( StockItemId INT)
	SET @lNextNumber  = @lCount + @lNextNumber 
		
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockInwardRequestDetail', @rCurrentNumber = @lNextNumber 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardRequestDetailGet]
	@rOrgGroupId int,
	@rStockInwardRequestId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT SIRD.Id,
			SIRD.StockInwardRequestId,
			SIRD.StockItemId,
			SIRD.RequestedQuantity,
			SIRD.Remark,
			SIRD.UpdatedUserID,
			SIRD.UpdatedDateTime,
			SIM.Code ItemCode,
			SIM.Title ItemTitle,
			SU.Code UomCode,
			SU.Title UomTitle,
			SU.Id IssueStockUomId,
			SIM.IsBatchWiseTracking,
			SIM.Code StockItemCode,
			SIM.Title StockItemName,
			SU.Title Uom,
		    '' as Number,
			SIRD.InwardQuantity,
			'' ExpiryDate,
			'' As InwardValue,
			SB.AvailableQuantity AS AvailableQuantity
	   FROM 
			sProcurement.tStockInwardRequestDetail SIRD
		    INNER JOIN sIP.tStockItemMaster SIM ON SIM.Id = SIRD.StockItemId
		    INNER JOIN sFinanceCommon.tStockUomMaster  SU ON SU.Id = SIM.IssueStockUomId
		    LEFT JOIN sProcurement.tStockBatch SB ON SB.StockItemId=SIm.Id
	   WHERE 
		    ((SIRD.StockInwardRequestId = @rStockInwardRequestId) OR (@rStockInwardRequestId = 0))
		    AND SIRD.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardRequestGet]
	@rOrgGroupId int,
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Number,
			FromStoreLocationId,	 
			RequestedByName,
			Remark,
			CreatedDateTime,
			ISNULL(StatusId,0) As StatusId
	  FROM sProcurement.tStockInwardRequest
	  WHERE ((Id = @rId) OR (@rId = 0))
	  AND OrgGroupId = @rOrgGroupId
	  
	  EXEC [sProcurement].[pStockInwardRequestDetailGet] @rOrgGroupId, @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardRequestIdGet]
	@rOrgGroupId int,
	@rStockInwardRequestNumber [nvarchar](30),
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		SELECT
				ID
		FROM
				sProcurement.tStockInwardRequest
		WHERE Number = @rStockInwardRequestNumber
		AND OrgGroupId = @rOrgGroupId AND FromStoreLocationId = @rStoreLocationId
				
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardReturnAdd]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rReturnByName					Nvarchar(100) = '',
		@rFromStoreLocationId				Int,
		@rRemark						Nvarchar(300),
		@rCreatedUserId					BigInt,
		@rStockInwardId					int
		--@rDetail						Nvarchar(Max)
	)
AS

SET NOCOUNT ON

BEGIN
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1006,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

--SET @rNumber = ISNULL(@rNumber, '-300')

--IF @rNumber = '-300'
--BEGIN

----IF @rStockInwardRequestId = 0
----SET @rStockInwardRequestId = NULL
----SELECT -300 AS Result, 0 AS PrescriptionID, '' AS PrescriptionNumber
--SELECT -300 AS Result, '' AS Number, 0 AS Id 
--RETURN
--END
SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tStockInwardReturn WHERE FromStoreLocationId = @rFromStoreLocationId
SET @rNumber = @rNumber + 1

	DECLARE @lNextNumberStockInwardReturn INT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardReturn', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardReturn output
	
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sHostel.tHostelMaster',@lNextNumber = @lNextNumberStockInwardReturn output
 
	INSERT INTO sProcurement.tStockInwardReturn
		(
			Id,
			Number,
			ReturnByName, 
			FromStoreLocationId,		 	 
			Remark,
			StockInwardId,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumberStockInwardReturn,
			@rNumber,
			@rReturnByName,		 
			@rFromStoreLocationId,			 
			@rRemark,
			@rStockInwardId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)


	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockInwardReturn AS Id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardReturnAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rReturnByName					Nvarchar(100) = '',
		@rFromStoreLocationId				Int,
		@rRemark						Nvarchar(300),
		@rCreatedUserId					BigInt,
		@rStockInwardId					bigint,
	    @rDetail						Nvarchar(Max),
	    @rLocationId int ,
	    @rOrgId int,
	    @rInwardReturnDate DateTime = null
	    
	)
AS

SET NOCOUNT ON

BEGIN
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1006,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

--SET @rNumber = ISNULL(@rNumber, '-300')

--IF @rNumber = '-300'
--BEGIN

----IF @rStockInwardRequestId = 0
----SET @rStockInwardRequestId = NULL
----SELECT -300 AS Result, 0 AS PrescriptionID, '' AS PrescriptionNumber
--SELECT -300 AS Result, '' AS Number, 0 AS Id 
--RETURN
--END
EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1006,
		@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT
		
		SET @rNumber = ISNULL(@rNumber, '-300')

		IF @rNumber = '-300'
		BEGIN
			SELECT -300 AS Result, '' AS Number, 0 AS Id 
			RETURN
		END

--select @rNumber = ISNULL(max(convert(int,Number)),0) FROM sProcurement.tStockInwardReturn WHERE FromStoreLocationId = @rFromStoreLocationId
--select @rNumber = convert(int,@rNumber) + 1 

DECLARE @loXML XML
		SET @loXML = CAST(@rDetail AS XML)
		Declare @tStockInwardReturnDetail TABLE
		(
			ID int IDENTITY(1,1),StockInwardBatchId bigint,
			Quantity decimal(12,2),ReasonId int,
			StockItemId int,StockItemName nvarchar(50),
			StockBatchId int
		)
		INSERT INTO @tStockInwardReturnDetail
		SELECT T.c.value('@StockInwardBatchId','bigint') AS StockInwardBatchId,
		T.c.value('@Quantity','nvarchar(20)')   AS Quantity,
		T.c.value('@ReasonId','Decimal(12,2)') AS ReasonId,
		T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@StockItemName','nvarchar(50)')As StockItemName,
		T.c.value('@StockBatchId','int') AS StockBatchId
		FROM @loXML.nodes('/Table/StockInwardReturnDetail')T(c)
		
		BEGIN TRANSACTION
		DECLARE @lNextNumberStockInwardReturn BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardReturn', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardReturn output
		 
		INSERT INTO sProcurement.tStockInwardReturn
		(
			Id,Number,ReturnByName,FromStoreLocationId,Remark,
			StockInwardId,CreatedUserId,CreatedDateTime,OrgGroupId,TransactionDate
		)
		VALUES
		(
			@lNextNumberStockInwardReturn,@rNumber,
			@rReturnByName,@rFromStoreLocationId,@rRemark,
			@rStockInwardId,@rCreatedUserId,sCommon.fGetDate(),
			@rOrgGroupId,@rInwardReturnDate
		)
		Declare @lStockInwardBatchId bigint,@lQuantity decimal(12,2),@lCount int,@lReasonId int,
		@lNextNumberInwardReturnBatch bigint,@lBatchId int,@lStockItemId int,@lStockItemName nvarchar(50),
		@lStockBatchId int,@lWeightedAverageCost decimal(12,2),@lInwardValue decimal(12,2)
		Select @lCount = COUNT(*) from @tStockInwardReturnDetail
		While (@lCount>0)
		BEGIN
			Select @lStockInwardBatchId=StockInwardBatchId,@lQuantity=Quantity,@lReasonId=ReasonId,
			@lStockItemId=StockItemId,@lStockItemName =StockitemName,@lStockBatchId =StockBatchId from @tStockInwardReturnDetail where ID=@lCount
			
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lStockItemId AND StoreLocationId = @rFromStoreLocationId
			
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardReturnBatch', 0, 1, 1,@outNextNumber = @lNextNumberInwardReturnBatch output
			INSERT INTO sProcurement.tStockInwardReturnBatch
			(
				Id,StockInwardReturnId,StockInwardBatchId,Quantity,OrgGroupId,ReasonId
			)
			
			Values
			(
				@lNextNumberInwardReturnBatch,@lNextNumberStockInwardReturn,
				@lStockInwardBatchId,@lQuantity,@rOrgGroupId,@lReasonId
			)
			SET @lInwardValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lQuantity,0)
			EXEC sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId=@rOrgGroupId,@rSourceTypeId=1013,
			@rSourceId=@lNextNumberInwardReturnBatch,@rItemSourceTypeId=34,
			@rItemSourceId=@lStockItemId,@rQuantity=@lQuantity,@rValue=@lInwardValue,
			@rIsReceipt=0,@rCreatedUserId=@rCreatedUserId,@rStoreLocationId=@rfromStoreLocationId,
			@rLocationId=@rLocationId,@rItemBatchId=@lStockBatchId,@rItemName=@lStockItemName,@rOrgId=@rOrgId	
		
			set @lCount =@lCount-1
		END
		 
		 
		
--SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tStockInwardReturn WHERE FromStoreLocationId = @rFromStoreLocationId
--SET @rNumber = @rNumber + 1

--	DECLARE @lNextNumberStockInwardReturn INT
--	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardReturn', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardReturn output
	
--	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sHostel.tHostelMaster',@lNextNumber = @lNextNumberStockInwardReturn output
 
--	INSERT INTO sProcurement.tStockInwardReturn
--		(
--			Id,
--			Number,
--			ReturnByName, 
--			FromStoreLocationId,		 	 
--			Remark,
--			StockInwardId,
--			CreatedUserId,
--			CreatedDateTime,
--			OrgGroupId
--		)
--	VALUES
--		(
--			@lNextNumberStockInwardReturn,
--			@rNumber,
--			@rReturnByName,		 
--			@rFromStoreLocationId,			 
--			@rRemark,
--			@rStockInwardId,
--			@rCreatedUserId,
--			sCommon.fGetDate(),
--			@rOrgGroupId
--		)


	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockInwardReturn AS Id 
	COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardReturnBatchAdd]
	
	@rStockInwardReturnId int,
	@rStockInwardBatchId int,
	@rQuantity decimal(12,2),
	@rOrgGroupId int,
	@rReasonId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT     
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockInwardReturnBatch',@lNextNumber = @lNextNumber output
	
	INSERT INTO sProcurement.tStockInwardReturnBatch
		(
			Id,
			StockInwardReturnId,
			StockInwardBatchId,
			Quantity,
			OrgGroupId,
			ReasonId 
		)
	VALUES
		(
			@lNextNumber,
			@rStockInwardReturnId,
			@rStockInwardBatchId,
			@rQuantity,
			@rOrgGroupId,
			@rReasonId
		)	
 
	 
		SELECT @lNextNumber AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardReturnDataGet]
	
	@rNumber [nvarchar](30) = '',
	@rStoreLocationId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT SIR.Id,
			SIR.Number,
			ISNULL(SIR.ReturnByName,'') AS ReturnByName,
			SIR.FromStoreLocationId,
			SIR.Remark,
			SIR.StockInwardId,
			SIRB.StockInwardBatchId,
			SIRB.Quantity,
			SIM.Code AS StockItemCode,
			SIM.Title AS StockItemName,
			SIM.Id AS StockItemId,
			SIB.StockBatchId AS StockBatchId,
			SIR.CreatedUserId,
			SI.Number AS InwardNumber,
			SIRB.ReasonId,
			Sb.Number as 'StockBatchNumber',
			case when  SIR.TransactionDate is not null then SIR.TransactionDate else SIR.CreatedDateTime end  as TransactionDate,
			(SELECT ISNULL(SUM(SIRB.Quantity),0) FROM sProcurement.tStockInwardReturn SIR 
			INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id WHERE SIR.StockInwardId=SI.Id AND SIRB.StockInwardBatchId=SIB.Id) AS ReturnedQuantity,
			SIND.InwardQuantity,	--add for mantis: 35818
			SIND.InwardValue	--add for mantis: 35818


	FROM sProcurement.tStockInwardReturn SIR
		INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id
		INNER JOIN sProcurement.tStockInwardBatch SIB ON SIB.Id=SIRB.StockInwardBatchId
		left join sProcurement.tStockBatch Sb on sb.id = SIB.StockBatchId and sb.Number is not null
		INNER JOIN sProcurement.tStockInwardDetail SIND ON SIND.Id=SIB.StockInwardDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
		INNER JOIN sProcurement.tStockInward SI ON SI.Id=SIR.StockInwardId

	WHERE ((SIR.Number = @rNumber) OR (@rNumber = ''))
	   	AND SIR.FromStoreLocationId = @rStoreLocationId


--	   	 SELECT SIR.Id,
--		SIR.Number,
--		ISNULL(SIR.ReturnByName,'') AS ReturnByName,
--		SIR.FromStoreLocationId,
--		SIR.Remark,
--		SIR.StockInwardId,
--		SIRB.StockInwardBatchId,
--		SIRB.Quantity,
--		SIM.Code AS StockItemCode,
--		SIM.Title AS StockItemName,
--		SIM.Id AS StockItemId,
--		SIB.StockBatchId AS StockBatchId,
--		SIR.CreatedUserId,
--		SIND.InwardQuantity,
--		SIND.InwardValue,
--		SI.Number AS InwardNumber,
--		SIRB.ReasonId,
--		SIRB.Id AS StockInwardReturnBatchId,
--		(SELECT ISNULL(SUM(SIRB.Quantity),0) FROM sProcurement.tStockInwardReturn SIR 
--		INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id WHERE SIR.StockInwardId=SI.Id AND SIRB.StockInwardBatchId=SIB.Id) AS ReturnedQuantity

--FROM sProcurement.tStockInwardReturn SIR
--INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id
--INNER JOIN sProcurement.tStockInwardBatch SIB ON SIB.Id=SIRB.StockInwardBatchId
--INNER JOIN sProcurement.tStockInwardDetail SIND ON SIND.Id=SIB.StockInwardDetailId
--INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
--INNER JOIN sProcurement.tStockInward SI ON SI.Id=SIR.StockInwardId

--	   	WHERE ((SIR.Number = @rNumber) OR (@rNumber = ''))
--	   		AND SIR.FromStoreLocationId = @rStoreLocationId

	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [sProcurement].[pStockIssReturnGet]
-- drop proc [sProcurement].[pStockIssReturnGet]
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardReturnGet]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(200)='',
	@rSearchType nvarchar(5)= '1'
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SET @rNumber = sCommon.fSearchStringGet(@rNumber)
	if(@rSearchType='1')
		begin
				SELECT		
				SIR.Id,SIR.Number,isnull(SIR.StockInwardId,0) as StockInwardId,
				SIR.ReturnByName as ReturnByName,
				case when SIR.TransactionDate is not null  then SIR.TransactionDate else  SIR.CreatedDateTime End AS IssuedDate,
				 SIR.CreatedDateTime as TranjactionDate,
				 '' StockItemCode,
				 '' StockItemName
				FROM sProcurement.tStockInwardReturn SIR 
				WHERE ((SIR.Number like @rNumber) OR (@rNumber = ''))
				AND  SIR.OrgGroupId = @rOrgGroupId
				AND (( Convert(Date,SIR.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SIR.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SIR.FromStoreLocationId=@rStoreLocationId 
				Order by SIR.CreatedDateTime desc
				
		end
	else
		begin
				SELECT		
				SIR.Id,SIR.Number,isnull(SIR.StockInwardId,0) as StockInwardId,
				SIR.ReturnByName as ReturnByName,
				case when SIR.TransactionDate is not null  then SIR.TransactionDate else  SIR.CreatedDateTime End AS IssuedDate,
				 SIR.CreatedDateTime as TranjactionDate,
				 SIM.Code as StockItemCode,
				 SIM.TItle as StockItemName
				FROM sProcurement.tStockInwardReturn SIR 
				INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id
				INNER JOIN sProcurement.tStockInwardBatch SIB ON SIB.Id=SIRB.StockInwardBatchId
				left join sProcurement.tStockBatch Sb on sb.id = SIB.StockBatchId and sb.Number is not null
				INNER JOIN sProcurement.tStockInwardDetail SIND ON SIND.Id=SIB.StockInwardDetailId
				INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
				--INNER JOIN sProcurement.tStockInward SI ON SI.Id=SIR.StockInwardId
				
				WHERE ((SIR.Number like @rNumber) OR (@rNumber = ''))
				AND  SIR.OrgGroupId = @rOrgGroupId
				AND (( Convert(Date,SIR.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SIR.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SIR.FromStoreLocationId=@rStoreLocationId 
				AND (SIM.Id = @rItemCode or @rItemCode='')
				AND (SIM.Id = @rItemName or @rItemName='')
				Order by SIR.CreatedDateTime desc	
		end
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardReturnSearchGet]

	@rInwardNumber nvarchar(30) = '',
	@rStoreLocationId int,
	@rReturnByName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	    SELECT		
				Id AS InwardReturnId, 
				Number AS InwardReturnNumber,
				ReturnByName, 
				FromStoreLocationId, 
				CONVERT(varchar,TransactionDate,103) AS TransactionDate
		FROM		
				sProcurement.tStockInwardReturn SIR
		WHERE 
				((SIR.Number = @rInwardNumber) OR (@rInwardNumber = ''))
   				AND ((SIR.ReturnByName like @rReturnByName+'%') OR (@rReturnByName = ''))
   				AND ((SIR.FromStoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SIR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
	   		  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardSearchGet]

	@rInwardNumber nvarchar(30) = '',
	@rStoreLocationId int,
	@rInwardByName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		If @rInwardNumber = NULL SET @rInwardNumber=''
		If @rInwardByName = NULL SET @rInwardByName=''

	    SELECT		
				Id AS StockInwardId, 
				Number AS InwardNumber,
				InwardByName, 
				ToStoreLocationId, 
				TransactionDate
		FROM		
				sProcurement.tStockInward SI
		WHERE 
				((SI.Number = @rInwardNumber) OR (@rInwardNumber = ''))
   				AND ((SI.InwardByName like @rInwardByName+'%') OR (@rInwardByName = ''))
   				AND ((SI.ToStoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SI.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
	   		  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockInwardUpdate_New]
(
@rOrgId [int],
@rNumber Nvarchar(25) = '',
@rToStoreLocationId	Int,
@rCreatedUserId	BigInt,
@rDetail Nvarchar(Max),
@rLocationId int
)
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
BEGIN TRANSACTION

DECLARE @loXML XML
SET @loXML = CAST(@rDetail AS XML)

DECLARE @tStockInwardDetailBatch TABLE
	(
		Id Int IDENTITY(1, 1),				 
		StockItemId bigint,
		StockInwardBatchId bigint,
		StockInwardDetailId bigint,				
		InwardValue Decimal(12,2),
		WACId bigint
	)	
    INSERT INTO @tStockInwardDetailBatch
    SELECT  
            T.c.value('@StockItemId','bigint') AS StockItemId,
			T.c.value('@StockInwardBatchId','bigint') AS StockInwardBatchId,            
			T.c.value('@StockInwardDetailId','bigint') AS StockInwardDetailId,            
            T.c.value('@InwardValue','Decimal(12,2)') AS InwardValue,
			null 
    FROM 
            @loXML.nodes('/Table/StockInward')T(c)


update t set t.WACId=WAC.id
From @tStockInwardDetailBatch as t
inner join sIp.tWeightedAverageCostLog WaC on WAC.ItemSourceId=t.StockItemId and WAC.SourceId=t.StockInwardBatchId and StoreLocationId=@rToStoreLocationId

--update SIB Set SIB.value=t.InwardValue
--From sProcurement.tStockInwardBatch SIB
--inner join @tStockInwardDetailBatch as t  on t.StockInwardBatchId=SIB.id

update SIB Set SIB.InwardValue=t.InwardValue
From sProcurement.tStockInwardDetail SIB
inner join @tStockInwardDetailBatch as t  on t.StockInwardDetailId=SIB.id

--update SB Set SB.Price=t.InwardValue
--From sProcurement.tStockInwardBatch SIB
--inner join @tStockInwardDetailBatch as t  on t.StockInwardBatchId=SIB.id
--inner join sProcurement.tStockBatch SB on SIB.StockBatchId=SB.Id and t.StockItemId = SB.StockItemId 
--where SB.StoreLocationId=@rToStoreLocationId

--update SB Set SB.Price=t.InwardValue
--From sProcurement.tStockBatch SB
--Inner join sProcurement.tStockInwardBatch SIB on SIB.StockBatchId=SB.Id
--inner join @tStockInwardDetailBatch as t on t.StockInwardBatchId=SIB.id and t.StockItemId = SB.StockItemId 
--where SB.StoreLocationId=@rToStoreLocationId

declare @lCount int,@lStockInwardBatchId bigint,@lStockItemId bigint,@lWACId bigint,@loldWACId bigint,@lInwardValue decimal(12,2)
DECLARE @lTotalQuantityOld [decimal](12, 2) = 0
DECLARE @lWcCostOld [decimal](12, 2) = 0
DECLARE @lNewClosingValue [decimal](12, 2) = 0
DECLARE @lNewClosingQuantity [decimal](12, 2) = 0
DECLARE @lNewWeightedAverageCost [decimal](12, 2)= 0	

select @lCount=COUNT(*) from @tStockInwardDetailBatch
--select * from @tStockInwardDetailBatch 
print @lCount		 
	while @lcount > 0
		BEGIN
				Select @lStockInwardBatchId =StockInwardBatchId,@lStockItemId=StockItemId,@lWACId=WACId,@lInwardValue=Isnull(InwardValue,0)
				from  @tStockInwardDetailBatch WHERE Id = @lcount			
				
				Set @lNewClosingQuantity = Isnull((select ClosingQuantity From sIp.tWeightedAverageCostLog WaC Where WaC.ItemSourceId=@lStockItemId and WaC.Id = @lWACId and StoreLocationId=@rToStoreLocationId),0)
				Set @loldWACId = (select Max(id) From sIp.tWeightedAverageCostLog WaC Where WaC.ItemSourceId=@lStockItemId and WaC.Id < @lWACId and StoreLocationId=@rToStoreLocationId)

				if(@loldWACId>0)
					begin
						select @lTotalQuantityOld=Isnull(ClosingQuantity,0),@lWcCostOld=Isnull(WeightedAverageCost,0)     
						From sIp.tWeightedAverageCostLog where id=@loldWACId and StoreLocationId=@rToStoreLocationId

						SET @lNewClosingValue =   ISNULL(@lTotalQuantityOld,0) * ISNULL(@lWcCostOld,0)  + @lInwardValue
			
						if((@lNewClosingValue=0)And(@lNewClosingQuantity=0))
							SET @lNewWeightedAverageCost = 0
						else
							SET @lNewWeightedAverageCost = @lNewClosingValue / @lNewClosingQuantity	

						update sIp.tWeightedAverageCostLog set WeightedAverageCost=Isnull(@lNewWeightedAverageCost,0),ClosingValue=Isnull(@lNewWeightedAverageCost,0)*ClosingQuantity
							   ,value=Isnull(Isnull(@lNewWeightedAverageCost,0) * Quantity,0)	
						where id>=@lWACId and StoreLocationId=@rToStoreLocationId and ItemSourceId=@lStockItemId

						UPDATE sip.tStockItemPlanning  
								SET WeightedAverageCost = Isnull(@lNewWeightedAverageCost,0) 
						WHERE StockItemId = @lStockItemId AND StoreLocationId = @rToStoreLocationId

						--update DB set DB.UnitCost=Isnull(@lNewWeightedAverageCost,0)
						--From sPharmacy.tDispenseBatch DB
						--Inner join sIp.tWeightedAverageCostLog WAC on WAC.SourceId = DB.Id
						--where WAC.id>=@lWACId and StoreLocationId=@rToStoreLocationId and ItemSourceId=@lStockItemId and SourceTypeid=48
					end
				else
					begin						
						print @lInwardValue
						SET @lNewClosingValue =   @lInwardValue
			
						if((@lNewClosingValue=0)And(@lNewClosingQuantity=0))
							SET @lNewWeightedAverageCost = 0
						else
							SET @lNewWeightedAverageCost = @lNewClosingValue / @lNewClosingQuantity	
						
						print @lNewWeightedAverageCost
						print @lNewClosingQuantity
						print @lNewClosingValue
						update sIp.tWeightedAverageCostLog set WeightedAverageCost=Isnull(@lNewWeightedAverageCost,0),ClosingValue=Isnull(@lNewWeightedAverageCost,0)*ClosingQuantity
							   ,value=Isnull(Isnull(@lNewWeightedAverageCost,0) * Quantity,0)	
						where id>=@lWACId and StoreLocationId=@rToStoreLocationId and ItemSourceId=@lStockItemId

						UPDATE sip.tStockItemPlanning  
								SET WeightedAverageCost = Isnull(@lNewWeightedAverageCost,0) 
						WHERE StockItemId = @lStockItemId AND StoreLocationId = @rToStoreLocationId

						--update DB set DB.UnitCost=Isnull(@lNewWeightedAverageCost,0)
						--From sPharmacy.tDispenseBatch DB
						--Inner join sIp.tWeightedAverageCostLog WAC on WAC.SourceId = DB.Id
						--where WAC.id>=@lWACId and StoreLocationId=@rToStoreLocationId and ItemSourceId=@lStockItemId and SourceTypeid=48

					end
				set @lcount =@lcount-1
		END
SELECT 1 AS RESULT
COMMIT TRANSACTION
END TRY
BEGIN CATCH
        IF @@TRANCOUNT > 0  
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockIss_Get]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rAcademicId bigint=0,
	@rId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SELECT		
SI.Id AS  StockId,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
SI.IssuedByName,Convert(varchar,SI.TransactionDate,103) AS IssuedDate,
SM.FirstName AS StudentName,SID.IssuedQuantity as Quantity,
MS.Title,IG.Title As StockItemName,IG.Id as ItemSubGroupId,SI.ToOrganizationdepartmentid,
MG.Id As MainGroupId,MS.Id As StockItemId,
ISNULL(SI.PayTypeId,14) as PayTypeId,
ISNULL(SI.ReceiptNumber,0) as ReceiptNumber,
ISNULL(SI.BankName,'') as BankName,
ISNULL(SI.ChequeNo,'') as ChequeNo,
ISNULL(SI.ChequeDate,'') as ChequeDate,
SI.Remark--mantis - 0032618


FROM sProcurement.tStockIssue SI
INNER JOIN sProcurement.tStockIssueDetail SID ON SI.Id=SID.StockIssueId
INNER JOIN sStudent.tAcademic A ON A.Id=SI.IssueToSourceId AND SI.IssueToSourceTypeId=2001
INNER JOIN sStudent.tStudentMaster SM on SM.Id=A.StudentID
INNER JOIN sIp.tStockItemMaster MS ON MS.id=SID.StockItemId
INNER JOIN sIp.tItemSubGroupMaster IG on IG.Id=MS.ItemSubGroupId
INNER JOIN sIp.tItemMainGroupMaster MG on MG.iD=IG.ItemMainGroupId 
 
WHERE 
(( SI.Number like '%' + @rNumber + '%' ) OR (@rNumber = '*'))
AND  SI.OrgGroupId = @rOrgGroupId
AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
AND SI.FromStoreLocationId=@rStoreLocationId 
AND ((SI.IssueToSourceId =@rAcademicId) OR (@rAcademicId=0))
AND ((SI.Id =@rId) OR (@rId=0)) --add for mantis : 0040570
Order by SI.CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssGet]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(200)='',
	@rSearchType nvarchar(5)= '1',
	@rIssueToSourceId BIGINT = null,
	@rToDept int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SET @rNumber = sCommon.fSearchStringGet(@rNumber)

	if(@rSearchType='1')
		begin
				SELECT		
				SI.Id,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
				SI.IssuedByName,
				case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End AS IssuedDate,
				 SI.CreatedDateTime as TranjactionDate,
				 '' StockItemCode,
				 '' StockItemName,
				 ISNULL(SI.IssueToSourceId,'') as IssueToSourceId,
				 ISNULL(EM.ShortName,'') as ToEmployeeName,
				 ISNULL(DM.DisplayTitle,'') as ToDepartment,
				 ISNULL(SI.IssueToName,'') as IssueToName
				FROM sProcurement.tStockIssue SI 
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = SI.IssueToSourceId AND  ISNULL(EM.IsOtherUser,0) = 0
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = SI.ToOrganizationDepartmentId
				WHERE
				SI.OrgGroupId = @rOrgGroupId 
				AND  ((SI.Number like @rNumber) OR (@rNumber = ''))
				AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SI.FromStoreLocationId=@rStoreLocationId 
				AND ((SI.IssueToSourceId = @rIssueToSourceId) OR (ISNULL(@rIssueToSourceId,'')=''))
				AND ((DM.Id = @rToDept) OR (@rToDept = 0))
				Order by SI.CreatedDateTime desc
		end
	else
		begin
				SELECT		
					SI.Id,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
					SI.IssuedByName,
					case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End	AS IssuedDate,
					 SI.CreatedDateTime as TranjactionDate,
					 SIM.Code AS StockItemCode,
					SIM.TItle As StockItemName,
					isnull(SI.IssueToSourceId,'') as IssueToSourceId,
					ISNULL(EM.ShortName,'') as ToEmployeeName,
				    ISNULL(DM.DisplayTitle,'') as ToDepartment,
				    ISNULL(SI.IssueToName,'') as IssueToName
				FROM sProcurement.tStockIssue SI 
				Inner join sProcurement.tStockIssueDetail SIDE on SI.ID= SIDE.StockIssueId
				INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SIDE.StockItemID
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = SI.IssueToSourceId AND  ISNULL(EM.IsOtherUser,0) = 0
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = SI.ToOrganizationDepartmentId
				WHERE ((SI.Number like @rNumber) OR (@rNumber = ''))
				AND  SI.OrgGroupId = @rOrgGroupId 
				AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SI.FromStoreLocationId=@rStoreLocationId 
				AND (SIM.Id = @rItemCode or @rItemCode='')
				AND (SIM.Title = @rItemName or @rItemName='')
				AND ((SI.IssueToSourceId = @rIssueToSourceId) or (ISNULL(@rIssueToSourceId,'')=''))
				AND ((DM.Id = @rToDept) OR (@rToDept = 0))
				Order by SI.CreatedDateTime desc
		end
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssReqGet]
	@rOrgGroupId int,	 
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rstorelocationId int =0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SELECT Id,Number AS RequestNumber,
CreatedDateTime AS RequestedDate,RequestedByName
FROM sProcurement.tStockIssueRequest
WHERE (( Number like '%'+@rNumber+'%') OR (ISNULL(@rNumber, '') = '*'))
AND OrgGroupId = @rOrgGroupId	AND ((CreatedDateTime>=@rFromDate) OR (ISNULL(@rfromDate,'')=''))
AND ((CreatedDateTime<=DateAdd(Day,1,@rToDate))	 OR (ISNULL(@rToDate,'')=''))
AND FromStoreLocationId = @rstorelocationId
order by CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [sProcurement].[pStockIssReturnGet]
-- drop proc [sProcurement].[pStockIssReturnGet]
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssReturnGet]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(200)='',
	@rSearchType nvarchar(5)= '1'
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SET @rNumber = sCommon.fSearchStringGet(@rNumber)
	if(@rSearchType='1')
		begin
				SELECT		
				SIR.Id,SIR.Number,isnull(SIR.StockIssueId,0) as StockIssueId,
				SIR.ReturnedByName as ReturnByName,
				case when SIR.TransactionDate is not null  then SIR.TransactionDate else  SIR.CreatedDateTime End AS IssuedDate,
				 SIR.CreatedDateTime as TranjactionDate,
				 '' StockItemCode,
				 '' StockItemName
				FROM sProcurement.tStockIssueReturn SIR 
				WHERE ((SIR.Number like @rNumber) OR (@rNumber = ''))
				AND  SIR.OrgGroupId = @rOrgGroupId
				AND (( Convert(Date,SIR.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SIR.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SIR.ToStoreLocationId=@rStoreLocationId 
				Order by SIR.CreatedDateTime desc
		end
	else
		begin
				SELECT		
				SIR.Id,SIR.Number,isnull(SIR.StockIssueId,0) as StockIssueId,
				SIR.ReturnedByName as ReturnByName,
				case when SIR.TransactionDate is not null  then SIR.TransactionDate else  SIR.CreatedDateTime End AS IssuedDate,
				 SIR.CreatedDateTime as TranjactionDate,
				 SIM.Code as StockItemCode,
				 SIM.TItle as StockItemName
				FROM sProcurement.tStockIssueReturn SIR 
				INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id
				INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id=SIRB.StockIssueBatchId
				left join sProcurement.tStockBatch Sb on sb.id = SIB.StockBatchId and sb.Number is not null
				INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.Id=SIB.StockIssueDetailId
				INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
				WHERE ((SIR.Number like @rNumber) OR (@rNumber = ''))
				AND  SIR.OrgGroupId = @rOrgGroupId
				AND (( Convert(Date,SIR.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SIR.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SIR.ToStoreLocationId=@rStoreLocationId 
				AND (SIM.Id = @rItemCode or @rItemCode='')
				AND (SIM.Id = @rItemName or @rItemName='')
				Order by SIR.CreatedDateTime desc	
		end
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssSearch_Get]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rAcademicId bigint=0,
	@rId int=0,
	@rPayTypeId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SELECT		
SI.Id AS  StockId,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
SI.IssuedByName,SI.CreatedDateTime AS IssuedDate,
IssueToSourceId

FROM sProcurement.tStockIssue SI
 
 
WHERE ((SI.Number like '%' + @rNumber + '%') OR (@rNumber = '*'))
AND  SI.OrgGroupId = @rOrgGroupId
AND (isnull(PayTypeId,14)=@rPayTypeId OR isnull(@rPayTypeId,0)=0)
AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
AND SI.FromStoreLocationId=@rStoreLocationId 
AND ((SI.IssueToSourceId =@rAcademicId) OR (@rAcademicId=0))
AND SI.IssueToSourceTypeId = 2001
Order by SI.CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssue_Get]
	@rOrgGroupId int,
	@rId [int] = 0,
	@rNumber [nvarchar](20) = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
SELECT		 
		SIDE.Id,
		SIDE.RequestedQuantity,
		SIDE.IssuedQuantity,
		SI.Remark, 
		--SIDE.Remark, -- mantisid - 0032618
		SIM.Code AS StockItemCode,
		SIM.TItle As StockItemName,
		SUMa.Code AS UOM,
		isnull(SB.Number,'') AS Number,
		isnull(SB.ExpiryDate,'') as ExpiryDate , 
		SB.AvailableQuantity,
		SIM.ID AS StockItemID,
		SI.ToOrganizationdepartmentid,
		SI.IssuedByName,
		case when SI.TransactionDate is not null then  SI.TransactionDate  else  SI.CreatedDateTime end as 'TransactionDate',
		SI.CreatedDateTime,
		SI.IssueToName,
		SIReq.Number AS 'reqnumb',
		SIReq.CreatedDateTime as 'ReqDate',
		--Added by dhananjay for mantis id : 39100	
		ISNULL(EM.FirstName+' '+EM.LastName,'') as ToEmployeeName,
		ISNULL(DM.DisplayTitle,'') as ToDepartment,
		ISNULL(EM.Code,'') AS EmployeeCode
		--Added by dhananjay for mantis id : 39100	
		
			
			
FROM		
		sProcurement.tStockIssueDetail SIDE
		INNER JOIN sProcurement.tStockIssue SI ON SI.ID= SIDE.StockIssueId
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SIDE.StockItemID
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		LEFT JOIN sProcurement.tStockIssueBatch SIB ON SIB.StockIssueDetailId= SIDE.Id
		LEFT JOIN	sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId
		LEFT JOIN	sProcurement.tStockIssueRequest SIReq ON SIReq.Id = SI.StockIssueRequestId
		--Added by dhananjay for mantis id : 39100	
		LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = SI.IssueToSourceId AND  ISNULL(EM.IsOtherUser,0) = 0 AND SI.IssueToSourceTypeId = 95
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = SI.ToOrganizationDepartmentId
		--Added by dhananjay for mantis id : 39100	
WHERE		
		SI.ID=@rId
		AND ((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
		AND SI.OrgGroupId = @rOrgGroupId
		AND SI.FromStoreLocationId  = @rStoreLocationId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To add records to sProcurement.tStockIssue table
	Created date     : 09 Jan 2012
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Added @rStockIssueRequestId field
	Test script      : EXECUTE sProcurement.pStockIssueAdd @rNumber = '', @rStockIssueRequestId = 0, @rIssuedByName = '', @rToOrganizationDepartmentId = 0, @rFromStoreLocationId = 0, @rRemark = '', @rCreatedUserId = 0, @rDetail = ''
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueAdd]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rStockIssueRequestId			Int, 
		@rIssuedByName					Nvarchar(100) = '',
		@rToOrganizationDepartmentId	Int,
		@rFromStoreLocationId			Int,
		@rFirstAidId					Int,
		@rRemark						Nvarchar(300),
		@rCreatedUserId					BigInt,
		@rDetail						Nvarchar(Max)
	)
AS

SET NOCOUNT ON

BEGIN
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 26,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

--SET @rNumber = ISNULL(@rNumber, '-300')

--IF @rNumber = '-300'
--BEGIN
 
--SELECT -300 AS Result, '' AS Number, 0 AS Id 
--RETURN
--END

SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tStockIssue WHERE FromStoreLocationId = @rFromStoreLocationId
SET @rNumber = @rNumber + 1
	DECLARE @lNextNumberStockIssue INT
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockIssue',@lNextNumber = @lNextNumberStockIssue output

if @rFirstAidId < 0 
SET @rFirstAidId =  NULL

	INSERT INTO sProcurement.tStockIssue
		(
			Id,
			Number,
			StockIssueRequestId, 
			IssuedByName,
			ToOrganizationDepartmentId,
			FromStoreLocationId,
			FirstAidId,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumberStockIssue,
			@rNumber,
		   (CASE WHEN @rStockIssueRequestId = 0 THEN NULL ELSE @rStockIssueRequestId END),	 
			@rIssuedByName,
			@rToOrganizationDepartmentId,
			@rFromStoreLocationId,
			@rFirstAidId,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)


	DECLARE @lIntErrorCode INT, @lIntDoc INT
	EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	DECLARE @tStockIssueDetail TABLE
	(
	Id						Int IDENTITY(0, 1),
	StockIssueDetailId		Int, 
	StockIssueRequestDetailId	Int, 
	StockIssueId 			Int, 
	StockItemId				Int, 
	IssuedQuantity			Decimal(12,2),
	RequestedQuantity		Decimal(12,2),  
	Remark					Nvarchar(300)
	)
	
	INSERT INTO @tStockIssueDetail  
	(  
		StockIssueId,
		StockItemId,
		IssuedQuantity,
		RequestedQuantity,
		StockIssueRequestDetailId, 
		Remark
	)
	SELECT	@lNextNumberStockIssue, 
			StockItemId,
			IssuedQuantity,
			RequestedQuantity,
			(CASE WHEN StockIssueRequestDetailId = 0 THEN NULL ELSE StockIssueRequestDetailId END), 			
			Remark
			
	FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail', 1)  
		WITH  
		(  
			StockItemId				Nvarchar(300)	'@StockItemId', 
			IssuedQuantity			Nvarchar(300)	'@IssuedQuantity', 
			RequestedQuantity		Nvarchar(300)	'@RequestedQuantity', 
			StockIssueRequestDetailId  Nvarchar(300)'@StockIssueRequestDetailId', 
			Remark					Nvarchar(300)	'@Remark'
		) XmlTable
	
	DECLARE @lNextNumberStockIssueDetail BigInt
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output
	
	
	INSERT INTO sProcurement.tStockIssueDetail
		(
			Id,
			StockIssueId,
			StockItemId,
			IssuedQuantity,
			RequestedQuantity,
			StockIssueRequestDetailId, 
			Remark,
			OrgGroupId
		)
	SELECT 	@lNextNumberStockIssueDetail + Id, 
			StockIssueId, 
			StockItemId, 
			IssuedQuantity,
			RequestedQuantity, 
			StockIssueRequestDetailId, 
			Remark,
			@rOrgGroupId
	FROM	@tStockIssueDetail
	
	UPDATE @tStockIssueDetail SET StockIssueDetailId = @lNextNumberStockIssueDetail + Id 
	SELECT @lNextNumberStockIssueDetail = MAX(Id) + @lNextNumberStockIssueDetail FROM @tStockIssueDetail
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueDetail', @rCurrentNumber = @lNextNumberStockIssueDetail 
	
	DECLARE @tBatch TABLE
	(
		Id						Int IDENTITY(0, 1), 
		StockIssueDetailId	Int,
		StockBatchId Int,		
		Quantity				Decimal(12,2),
		StockItemId				Int				
	)
	
	INSERT INTO @tBatch  
			(  
			StockIssueDetailId,	
			StockBatchId, 
			Quantity,
			StockItemId									
			)
	SELECT	1, 
			StockBatchId, 
			Quantity,
			StockItemId
	FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail/StockIssueBatch', 1)  
		WITH  
		(  
			StockBatchId 	Nvarchar(200)	'@StockBatchId', 
			Quantity					Nvarchar(200)	'@Quantity',
			StockItemId					Nvarchar(200)	'@StockItemId' 			
		) XmlTable	
		
		
	DECLARE @lNextNumberBatch BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output
	
	INSERT INTO sProcurement.tStockIssueBatch
		(
			Id,
			StockIssueDetailId,
			StockBatchId,
			Quantity,
			OrgGroupId
		)
	SELECT 		@lNextNumberBatch + TD.Id, 
				STD.StockIssueDetailId, 
				StockBatchId, 
				Quantity,
				@rOrgGroupId
	FROM		@tStockIssueDetail STD 
	INNER JOIN	@tBatch TD 
				ON TD.StockItemId = STD.StockItemId
				
	SELECT @lNextNumberBatch = MAX(Id) + @lNextNumberBatch FROM @tBatch
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueBatch', @rCurrentNumber = @lNextNumberBatch 
	
	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockIssue AS Id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rStockIssueRequestId			Int=0, 
		@rIssuedByName					Nvarchar(100) = '',
		@rToOrganizationDepartmentId	Int,
		@rFromStoreLocationId			Int,
		@rFirstAidId					Int,
		@rRemark						Nvarchar(300) = '',
		@rCreatedUserId					BigInt,
		@rDetail						Nvarchar(Max),
		@rOrgId int,
		@rLocationId int,
		@rIssuedToName nvarchar(50)='',
		@rIssueDate datetime = null,
		@rCreatedOnDate datetime = null,
		@rIssueToSourceTypeId int = null,
		@rIssueToSourceId BigInt = null
	)
AS

SET NOCOUNT ON

BEGIN
EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 26,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

SET @rNumber = ISNULL(@rNumber, '-300')

IF @rNumber = '-300'
BEGIN
 
SELECT -300 AS Result, '' AS Number, 0 AS Id 
RETURN
END

	DECLARE @lNextNumberStockIssue INT
	 DECLARE @loXML XML
		SET @loXML = CAST(@rDetail AS XML)
	 DECLARE @tStockIssueDetail TABLE
		(
			Id Int IDENTITY(1,1),StockIssueRequestDetailId int,StockItemId Int,StockItemName nvarchar(50),
			StockItemCode nvarchar(50),IssuedQuantity Decimal(12,2),RequestedQuantity Decimal(12,2),
			ItemBatch Nvarchar(300) NULL,StockBatchId int 
		)

	INSERT INTO @tStockIssueDetail
		SELECT
		(
			CASE WHEN T.c.value('@StockIssueRequestDetailId','Nvarchar(300)') = 0 THEN 
				NULL
			ELSE T.c.value('@StockIssueRequestDetailId','Nvarchar(300)') END
		),
		T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@StockItemCode','nvarchar(50)') AS StockItemCode,
		T.c.value('@StockItemName','nvarchar(50)') AS StockItemName,
		T.c.value('@IssuedQuantity','decimal(12,2)') AS IssuedQuantity,
		T.c.value('@RequestedQuantity','decimal(12,2)') AS RequestedQuantity,
		T.c.value('@ItemBatch','Nvarchar(300)') AS ItemBatch,
		T.c.value('@StockBatchId','int') AS StockBatchId
		FROM @loXML.nodes('/Table/StockIssue')T(c)
	 
	 BEGIN TRANSACTION
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockIssue',@lNextNumber = @lNextNumberStockIssue output



if @rFirstAidId < 0 
SET @rFirstAidId =  NULL

	INSERT INTO sProcurement.tStockIssue
		(
			Id,
			Number,
			StockIssueRequestId, 
			IssuedByName,
			ToOrganizationDepartmentId,
			FromStoreLocationId,
			FirstAidId,
			Remark,
			TransactionDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			IssueToSourceTypeId,
			IssueToSourceId,
			IssueToName
		)
	VALUES
		(
			@lNextNumberStockIssue,
			@rNumber,
		   (CASE WHEN @rStockIssueRequestId = 0 THEN NULL ELSE @rStockIssueRequestId END),	 
			@rIssuedByName,
			@rToOrganizationDepartmentId,
			@rFromStoreLocationId,
			@rFirstAidId,
			@rRemark,
			@rIssueDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rIssueToSourceTypeId,
			@rIssueToSourceId,
			@rIssuedToName
		)


	DECLARE @lNextNumberStockIssueDetail BigInt,@lQuantity decimal(12,2),@lStockItemCode nvarchar(50)
		Declare @lCOunt int , @lItemId int,@lIssueQuantity decimal(12,2),@lRequestedQuantity decimal(12,2),
		@lbatchId int,@lIsBatchWise bit,@lBatch nvarchar(300),@lNextNumberStockBatch int,@lNextNumberBatch int,
		@lWeightedAverageCost decimal(12,2),@lInwardValue decimal(12,2),@lStockItemName nvarchar(50),
		@lNextNumberOtherStockBatch bigint
		Select @lCOunt = count(*) from @tStockIssueDetail
		while @lcount>0
		BEGIN
			Select @lItemId = StockItemId , @lIssueQuantity = IssuedQuantity , 
			@lRequestedQuantity=RequestedQuantity,@lCOunt=Id,@lBatch=ItemBatch,
			@lStockItemCode=StockItemCode,@lBatchId=StockBatchId,@lStockItemName=StockItemName
			from @tStockIssueDetail where Id=@lCOunt
			
			Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster Where Id = @lItemId   
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lItemId AND StoreLocationId =  @rFromStoreLocationId  
			
			Select @lQuantity=AvailableQuantity from sProcurement.tStockBatch where Id =@lBatchId
			AND StockItemId = @lItemId ANd StorelocationId=@rFromStoreLocationId
			
			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				ROLLBACK TRANSACTION
				Select -102 As Result,@lStockItemCode AS StockItemCode
				Return
			END 
			IF @lQuantity < @lIssueQuantity 
			BEGIN
				ROLLBACK TRANSACTION
				Select -101 AS Result,@lStockItemCode AS StockItemCode
				return
			END
			IF Exists(Select Id from sProcurement.tStockIssueDetail where StockIssueId = @lNextNumberStockIssue and StockItemId = @lItemId)					
			BEGIN
				Select @lNextNumberStockIssueDetail= Id from sProcurement.tStockIssueDetail
				Where StockIssueId = @lNextNumberStockIssue AND StockIteMid =@lItemId					 
			END	
			ELSE
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output
				-- use remark existing parameter in StockIssue there for in Stockdetail table pass '' string in remark -- in old functionality remark pass as a '' string and div hide from page side mantisid - 0032618
				INSERT INTO sProcurement.tStockIssueDetail
				(
					Id,StockIssueId,StockItemId,IssuedQuantity,RequestedQuantity,
					StockIssueRequestDetailId,Remark,OrgGroupId
				)
				SELECT @lNextNumberStockIssueDetail,@lNextNumberStockIssue,StockItemId,IssuedQuantity,
				RequestedQuantity,StockIssueRequestDetailId,'',@rOrgGroupId
				from @tStockIssueDetail where Id=@lcount	
			END
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output

			INSERT INTO sProcurement.tStockIssueBatch
			(
				Id,StockIssueDetailId,StockBatchId,Quantity,OrgGroupId
			)
		Select @lNextNumberBatch,@lNextNumberStockIssueDetail,@lbatchId,@lIssueQuantity,@rOrgID

		SET @lInwardValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lIssueQuantity,0)
		
		Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=51,@rSourceId=@lNextNumberBatch,
			@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lIssueQuantity ,@rValue=@lInwardValue,@rIsReceipt=0,
			@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rFromStoreLocationId ,@rLocationId=@rLocationId,
			@rItemBatchId = @lbatchId,@rItemName =@lStockItemName,@rOrgId=@rOrgId
		set @lcount =@lcount-1
		
		END
	 

	--DECLARE @lIntErrorCode INT, @lIntDoc INT
	--EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	--DECLARE @tStockIssueDetail TABLE
	--(
	--Id						Int IDENTITY(0, 1),
	--StockIssueDetailId		Int, 
	--StockIssueRequestDetailId	Int, 
	--StockIssueId 			Int, 
	--StockItemId				Int, 
	--IssuedQuantity			Decimal(12,2),
	--RequestedQuantity		Decimal(12,2),  
	--Remark					Nvarchar(300)
	--)
	
	--INSERT INTO @tStockIssueDetail  
	--(  
	--	StockIssueId,
	--	StockItemId,
	--	IssuedQuantity,
	--	RequestedQuantity,
	--	StockIssueRequestDetailId, 
	--	Remark
	--)
	--SELECT	@lNextNumberStockIssue, 
	--		StockItemId,
	--		IssuedQuantity,
	--		RequestedQuantity,
	--		(CASE WHEN StockIssueRequestDetailId = 0 THEN NULL ELSE StockIssueRequestDetailId END), 			
	--		Remark
			
	--FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail', 1)  
	--	WITH  
	--	(  
	--		StockItemId				Nvarchar(300)	'@StockItemId', 
	--		IssuedQuantity			Nvarchar(300)	'@IssuedQuantity', 
	--		RequestedQuantity		Nvarchar(300)	'@RequestedQuantity', 
	--		StockIssueRequestDetailId  Nvarchar(300)'@StockIssueRequestDetailId', 
	--		Remark					Nvarchar(300)	'@Remark'
	--	) XmlTable
	
	--DECLARE @lNextNumberStockIssueDetail BigInt
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output
	
	
	--INSERT INTO sProcurement.tStockIssueDetail
	--	(
	--		Id,
	--		StockIssueId,
	--		StockItemId,
	--		IssuedQuantity,
	--		RequestedQuantity,
	--		StockIssueRequestDetailId, 
	--		Remark,
	--		OrgGroupId
	--	)
	--SELECT 	@lNextNumberStockIssueDetail + Id, 
	--		StockIssueId, 
	--		StockItemId, 
	--		IssuedQuantity,
	--		RequestedQuantity, 
	--		StockIssueRequestDetailId, 
	--		Remark,
	--		@rOrgGroupId
	--FROM	@tStockIssueDetail
	
	--UPDATE @tStockIssueDetail SET StockIssueDetailId = @lNextNumberStockIssueDetail + Id 
	--SELECT @lNextNumberStockIssueDetail = MAX(Id) + @lNextNumberStockIssueDetail FROM @tStockIssueDetail
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueDetail', @rCurrentNumber = @lNextNumberStockIssueDetail 
	
	--DECLARE @tBatch TABLE
	--(
	--	Id						Int IDENTITY(0, 1), 
	--	StockIssueDetailId	Int,
	--	StockBatchId Int,		
	--	Quantity				Decimal(12,2),
	--	StockItemId				Int				
	--)
	
	--INSERT INTO @tBatch  
	--		(  
	--		StockIssueDetailId,	
	--		StockBatchId, 
	--		Quantity,
	--		StockItemId									
	--		)
	--SELECT	1, 
	--		StockBatchId, 
	--		Quantity,
	--		StockItemId
	--FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail/StockIssueBatch', 1)  
	--	WITH  
	--	(  
	--		StockBatchId 	Nvarchar(200)	'@StockBatchId', 
	--		Quantity					Nvarchar(200)	'@Quantity',
	--		StockItemId					Nvarchar(200)	'@StockItemId' 			
	--	) XmlTable	
		
		
	--DECLARE @lNextNumberBatch BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output
	
	--INSERT INTO sProcurement.tStockIssueBatch
	--	(
	--		Id,
	--		StockIssueDetailId,
	--		StockBatchId,
	--		Quantity,
	--		OrgGroupId
	--	)
	--SELECT 		@lNextNumberBatch + TD.Id, 
	--			STD.StockIssueDetailId, 
	--			StockBatchId, 
	--			Quantity,
	--			@rOrgGroupId
	--FROM		@tStockIssueDetail STD 
	--INNER JOIN	@tBatch TD 
	--			ON TD.StockItemId = STD.StockItemId
				
	--SELECT @lNextNumberBatch = MAX(Id) + @lNextNumberBatch FROM @tBatch
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueBatch', @rCurrentNumber = @lNextNumberBatch 
	
	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockIssue AS Id 
		COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueBatchQuantityCheck]
	
	
	@rStockInwardBatchId int,
	@rStoreLocationId int
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	Declare @lStockBatchId int
	SET @lStockBatchId=(SELECT StockBatchId From sProcurement.tStockIssueBatch WHERE Id=@rStockInwardBatchId)
	
	SELECT 
			SB.AvailableQuantity,SIM.Title AS StockItemName From sProcurement.tStockBatch SB
			INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SB.StockItemId
			
			WHERE SB.Id=@lStockBatchId AND SB.StorelocationId=@rStoreLocationId


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueDepositAdjustmentAdd]
	
	@rId bigint, 
	@rAdjustmentId bigint,
	@rDepositHeadId int,
	@rAmount decimal(12,2),
	@rAdjustmentDate date,
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	@rOrgGroupId smallint,
	@rAcademicId bigint,
	@rFeeDepositExpenseTypeId int,
	@rOrgGroupBatchId int,
	@rReferenceSourceId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint

BEGIN	
BEGIN TRY
BEGIN TRANSACTION	
 DECLARE @rAdjustmentNumber Int
 Select @rAdjustmentNumber=(MAX(AdjustmentNumber) +1) from sFee.tDepositAdjustment
DECLARE @lNextNumber bigint 
IF NOT EXISTS(Select Id From sFee.tDepositAdjustment Where ReferenceSourceId=@rReferenceSourceId)
BEGIN
EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositAdjustment', 0, 1, 1,@outNextNumber = @lNextNumber output 
	INSERT INTO sFee.tDepositAdjustment
		(
		Id,
		DepositHeadId,
		Amount,
		AdjustmentDate,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		AcademicId,
		FeeDepositExpenseTypeId,
		AdjustmentNumber,
		OrgGroupBatchId,
		ReferenceSourceTypeId,
		ReferenceSourceId
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		@rAmount,
		@rAdjustmentDate,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rAcademicId,
		@rFeeDepositExpenseTypeId,
		@rAdjustmentNumber,
		@rOrgGroupBatchId,
		2039 ,
		@rReferenceSourceId 
		) 
		SELECT @lNextNumber  AS Result   
	END	
ELSE
    BEGIN
    --SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdjustment
	    SET
	    DepositHeadId=@rDepositHeadId,
		Amount=@rAmount,
		AdjustmentDate=@rAdjustmentDate,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    AcademicId=@rAcademicId,
	    FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId,
		AdjustmentNumber=@rAdjustmentNumber,
		OrgGroupBatchId=@rOrgGroupBatchId,
		ReferenceSourceTypeId=2039,
		ReferenceSourceId=@rReferenceSourceId
	    WHERE ReferenceSourceId = @rAdjustmentId 
	    SELECT 11 AS Result
	 END  
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueGet]
	@rOrgGroupId int,
	@rId [int] = 0,
	@rNumber [nvarchar](20) = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
SELECT		SI.Id,
			SI.Number,
			SI.StockIssueRequestId,
			SI.IssuedByName,
			ISNULL(SI.ToOrganizationDepartmentId,0) AS ToOrganizationDepartmentId,
			SI.FromStoreLocationId,
			ISNULL(SI.FirstAidId,0) As FirstAidId,
			SI.Remark,
			SI.CreatedUserId			AS UserId,
			SI.CreatedDateTime			AS IssuedDate,
			SLM.Code					AS FromStoreLocationCode,
			ISNULL(ODM.Title,'')		AS ToOrganizationDepartmentCode,
			ISNULL(FAM.Title,'')        AS FirstAid,
			SIReq.Number				AS RequestNumber,
			SIReq.CreatedDateTime		AS RequestedDate
			
FROM		sProcurement.tStockIssue SI
INNER JOIN	sIp.tStoreLocationMaster SLM
			ON SLM.Id = SI.FromStoreLocationId
LEFT JOIN	sSetup.tDepartmentMaster ODM
			ON ODM.Id = SI.ToOrganizationDepartmentId
LEFT JOIN   sCommon.tFirstAidMaster FAM 
			ON SI.FirstAidId = FAM.Id			
LEFT JOIN	sProcurement.tStockIssueRequest SIReq
			ON SIReq.Id = SI.StockIssueRequestId

WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId
AND			SI.FromStoreLocationId = @rStoreLocationId


SELECT		SIDe.Id,
			SIDe.StockIssueId,
			SIDe.StockItemId,
			SIDe.RequestedQuantity,
			SIDe.IssuedQuantity,
			SIDe.Remark,
			SIM.Code				AS StockItemCode,
			SIM.Title				AS StockItemName,
			SUMa.Code				AS UOM,
			SIM.IsBatchWiseTracking
 
FROM		sProcurement.tStockIssueDetail SIDe
INNER JOIN	sProcurement.tStockIssue SI
			ON SI.Id = SIDe.StockIssueId
INNER JOIN	sIp.tStockItemMaster SIM
			ON SIM.Id = SIDe.StockItemId
INNER JOIN  sFinanceCommon.tStockUomMaster SUMa
			ON SUMa.Id = SIM.IssueStockUomId
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId
AND			SI.FromStoreLocationId = @rStoreLocationId


SELECT		SIB.Id,
			SIB.StockIssueDetailId,
			SIB.StockBatchId,
			SIB.Quantity,
			SB.Number,
			SB.ExpiryDate, 
			SB.AvailableQuantity
FROM		sProcurement.tStockIssueBatch SIB
INNER JOIN	sProcurement.tStockIssueDetail SIDe
			ON SIDe.Id = SIB.StockIssueDetailId
INNER JOIN	sProcurement.tStockIssue SI
			ON SI.Id = SIDe.StockIssueId
INNER JOIN	sProcurement.tStockBatch SB
			ON SB.Id = SIB.StockBatchId
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId
AND			SI.FromStoreLocationId = @rStoreLocationId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueNumberGet]
	
	
	@rId int,
	@rStorelocationId int,
	@rNumber nvarchar(50) = ''
 			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN


	SELECT
		SI.Id,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIND.IssuedQuantity, 
		SIB.Id AS StockIssueBatchId,
		SIB.StockBatchId,
		Sb.Number as 'StockBatchNumber' ,
		SIND.Id AS StockIssueDetailId,
		SIM.Id AS StockItemId,
		ISNULL((SELECT ISNULL(SUM(SIRB.ReturnQuantity),0) FROM sProcurement.tStockIssueReturn SIR 
		INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id WHERE SIR.StockIssueId=SI.Id AND SIRB.StockIssueBatchId=SIB.Id),0)
		AS ReturnedQuantity,
		SIND.IssuedQuantity AS IssueQuantity,
		ISNULL(SI.IssueToSourceTypeId,0) IssueToSourceTypeId,	-- MantisId : 0034851	
		ISNULL(SI.IssueToSourceId,0) IssueToSourceId,
		ISNULL(SI.PayTypeId,0) PayTypeId

	FROM 
		sProcurement.tStockIssue SI 
		INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.StockIssueId=SI.Id
		INNER JOIN sProcurement.tStockIssueBatch  SIB ON SIB.StockIssueDetailId=SIND.Id
		left join sProcurement.tStockBatch Sb on sb.id = SIB.StockBatchId and sb.Number is not null
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId	
			
	WHERE 
		((SI.Id = @rId) OR (@rId = 0))
		AND	((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
		AND SI.FromStoreLocationId=@rStorelocationId
		 			   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueRequestAdd]
	@rOrgGroupId int,
	@rFromStoreLocationId [int],
	@rToDepartmentId [int],
	@rFirstAidId [int],
	@rRequestedByName [nvarchar](100),
	@rCreatedUserId [bigint],
	@rStockIssueRequestXml [nvarchar](max),
	@rNumber Nvarchar(20) = '',
	@rId [int] OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockIssueRequest',@lNextNumber = @lNextNumber output
 
	DECLARE @loNextNumber nVarchar(20)
	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 52, @rStoreLocationId = @rFromStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
	
	
	IF (@loNextNumber IS NULL)
		BEGIN
			RAISERROR('5000', 15, 106)
			RETURN
		END
 
--SELECT   @rNumber=ISNULL(max(cast (Number as int)),0) FROM  sProcurement.tStockIssueRequest WHERE FromStoreLocationId = @rFromStoreLocationId
--SET @rNumber = @rNumber + 1


IF @rFirstAidId = 0 
SET @rFirstAidId = NULL

	INSERT INTO sProcurement.tStockIssueRequest
		(
			Id,
			Number,
			FromStoreLocationId,
			ToDepartmentId,
			FirstAidId,
			RequestedByName,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
			
		)
	VALUES
		(
			@lNextNumber,
			@loNextNumber,
			@rFromStoreLocationId,
			@rToDepartmentId,
			@rFirstAidId,
			@rRequestedByName,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
	SET @rId = @lNextNumber
	EXEC [sProcurement].[pStockIssueRequestDetailAdd] @rOrgGroupId, @lNextNumber, @rStockIssueRequestXml
	select @rNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueRequestDetailAdd]
	@rOrgGroupId int,
	@rStockIssueRequestId [int],
	@rStockIssueRequestXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loIdoc INT
	DECLARE @lStockIssueRequestDetailCurrentId INT
	DECLARE @lCount INT
	DECLARE @lNextNumber int
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockIssueRequestXml
 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockIssueRequestDetail',@lNextNumber = @lStockIssueRequestDetailCurrentId output
	--sProcurement.tStockIssueRequest

	INSERT INTO sProcurement.tStockIssueRequestDetail
		(
			Id,
			StockIssueRequestId,
			StockItemId,
			RequestedQuantity,
			Remark,			
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
		@lStockIssueRequestDetailCurrentId + ROW_NUMBER() OVER(ORDER BY StockItemId) AS Id, 
		@rStockIssueRequestId,
		StockItemId,
		RequestedQuantity,
		Remark,		
		UpdatedUserID,
		sCommon.fGetDate(),
		@rOrgGroupId
	FROM OPENXML (@loIdoc, '/StockIssueRequest/StockIssueRequestDetail', 1)
		WITH ( 
				StockItemId INT, 
				RequestedQuantity DECIMAL(22, 6), 
				Remark NVARCHAR(300),				
				UpdatedUserID BIGINT
			  ) 
	SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockIssueRequest/StockIssueRequestDetail', 1)
				 WITH ( StockItemId INT)
	SET @lStockIssueRequestDetailCurrentId  = @lCount + @lStockIssueRequestDetailCurrentId 
		
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueRequestDetail', @rCurrentNumber = @lStockIssueRequestDetailCurrentId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueRequestDetailGet]
	@rOrgGroupId int,
	@rStockIssueRequestId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			ISNULL(SIRD.Id,0) As ID,
			ISNULL(SIRD.StockIssueRequestId,0) AS StockIssueRequestId ,
			SIRD.StockItemId,
			ISNULL(SIRD.RequestedQuantity,0) As RequestedQuantity,
			SIRD.Remark,
			SIRD.UpdatedUserID,
			SIRD.UpdatedDateTime,
			SIM.Code ItemCode,
			SIM.Title ItemTitle,
			SU.Code UomCode,
			SU.Title UomTitle,
			ISNULL(SU.Id,0)AS  IssueStockUomId,
			SIM.IsBatchWiseTracking,
			SIM.Code StockItemCode,
			SIM.Title StockItemName,
			SU.Title Uom,
		    '' as Number,
			SIRD.IssuedQuantity,
			SIR.Number,
			SIR.CreatedDateTime as 'ReqDate',
			(
				Select sum( AvailableQuantity)
				FROM sProcurement.tStockBatch SB
				INNER JOIN sIP.tStockItemMaster SIM ON SIM.Id = SB.StockItemID
				INNER JOIN sProcurement.tStockIssueRequestDetail SIRD1 ON SIRD1.StockItemId = SIM.Id
				WHERE ((SIRD1.StockIssueRequestId = @rStockIssueRequestId) OR (@rStockIssueRequestId = 0))
				AND SIRD1.OrgGroupId = @rOrgGroupId  AND SB.StockItemId = SIRD.StockItemId
			) AS AvailableQuantity,
			EM.Code AS ReqEmployeeCode
 
	   FROM 
			sProcurement.tStockIssueRequestDetail SIRD
	   INNER JOIN  sIP.tStockItemMaster SIM
		ON SIM.Id = SIRD.StockItemId
		INNER JOIN sFinanceCommon.tStockUomMaster  SU
		ON SU.Id = SIM.IssueStockUomId
		INNER JOIN sProcurement.tStockIssueRequest SIR ON SIR.ID=SIRD.StockIssueRequestId
		Left Join sCommon.vEmployeeMaster EM ON SIR.CreatedUserId=EM.UserId
		--LEFT JOIN sProcurement.tStockBatch SB ON SB.StockItemID = SIM.Id AND SB.Number!=''
	  WHERE ((SIRD.StockIssueRequestId = @rStockIssueRequestId) OR (@rStockIssueRequestId = 0))
	  AND SIRD.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueRequestGet]
	@rOrgGroupId int,
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			Number,
			FromStoreLocationId,
			ISNULL(ToDepartmentId,0) AS ToDepartmentId,
			ISNULL(FirstAidId,0) AS FirstAidId,
			RequestedByName,
			ISNULL(Remark,'') As Remark,
			CreatedDateTime
	   FROM sProcurement.tStockIssueRequest
	  WHERE ((Id = @rId) OR (@rId = 0))
	  AND OrgGroupId = @rOrgGroupId
	  
	  EXEC [sProcurement].[pStockIssueRequestDetailGet] @rOrgGroupId, @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueRequestIdGet]
	@rOrgGroupId int,
	@rStockIssueRequestNumber [nvarchar](30),
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		SELECT
				ID
		FROM
				sProcurement.tStockIssueRequest
		WHERE Number = @rStockIssueRequestNumber
		AND OrgGroupId = @rOrgGroupId AND FromStoreLocationId = @rStoreLocationId
				
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueReturnAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rReturnByName					Nvarchar(100) = '',
		@rFromStoreLocationId				Int,
		@rRemark						Nvarchar(300),
		@rCreatedUserId					BigInt,
		@rStockIssueId				    Nvarchar(20),
	    @rDetail						Nvarchar(Max),
	    @rLocationId int ,
	    @rOrgId int,
	    @rIssueReturnDate DateTime = null
	    
	)
AS

SET NOCOUNT ON

BEGIN
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1006,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

--SET @rNumber = ISNULL(@rNumber, '-300')

--IF @rNumber = '-300'
--BEGIN

----IF @rStockInwardRequestId = 0
----SET @rStockInwardRequestId = NULL
----SELECT -300 AS Result, 0 AS PrescriptionID, '' AS PrescriptionNumber
--SELECT -300 AS Result, '' AS Number, 0 AS Id 
--RETURN
--END
EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 53,
		@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT
		
		SET @rNumber = ISNULL(@rNumber, '-300')

		IF @rNumber = '-300'
		BEGIN
			SELECT -300 AS Result, '' AS Number, 0 AS Id 
			RETURN
		END
 
--select @rNumber = ISNULL(max(convert(int,Number)),0) FROM sProcurement.tStockInwardReturn WHERE FromStoreLocationId = @rFromStoreLocationId
--select @rNumber = convert(int,@rNumber) + 1 

DECLARE @loXML XML
		SET @loXML = CAST(@rDetail AS XML)
		Declare @tStockIssueReturnDetail TABLE
		(
			ID int IDENTITY(1,1),StockIssueBatchId bigint,
			Quantity decimal(12,2),ReasonId int,
			StockItemId int,StockItemName nvarchar(50),
			StockBatchId int
		)
		INSERT INTO @tStockIssueReturnDetail
		SELECT T.c.value('@StockIssueBatchId','bigint') AS StockIssueBatchId,
		T.c.value('@Quantity','nvarchar(20)')   AS Quantity,
		T.c.value('@ReasonId','Decimal(12,2)') AS ReasonId,
		T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@StockItemName','nvarchar(50)')As StockItemName,
		T.c.value('@StockBatchId','int') AS StockBatchId
		FROM @loXML.nodes('/Table/StockIssueReturnDetail')T(c)
		
		BEGIN TRANSACTION
		DECLARE @lNextNumberStockIssueReturn BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueReturn', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueReturn output
		 
		INSERT INTO sProcurement.tStockIssueReturn
		(
			Id,Number,ReturnedByName,ToStoreLocationId,Remark,
			StockIssueId,CreatedUserId,CreatedDateTime,OrgGroupId,TransactionDate
		)
		VALUES
		(
			@lNextNumberStockIssueReturn,@rNumber,
			@rReturnByName,@rFromStoreLocationId,@rRemark,
			@rStockIssueId,@rCreatedUserId,sCommon.fGetDate(),
			@rOrgGroupId,@rIssueReturnDate
		)
		Declare @lStockIssueBatchId bigint,@lQuantity decimal(12,2),@lCount int,@lReasonId int,
		@lNextNumberIssueReturnBatch bigint,@lBatchId int,@lStockItemId int,@lStockItemName nvarchar(50),
		@lStockBatchId int,@lWeightedAverageCost decimal(12,2),@lIssueValue decimal(12,2)
		Select @lCount = COUNT(*) from @tStockIssueReturnDetail
		 
		While (@lCount>0)
		BEGIN
			 
			Select @lStockIssueBatchId=StockIssueBatchId,@lQuantity=Quantity,@lReasonId=ReasonId,
			@lStockItemId=StockItemId,@lStockItemName =StockitemName,@lStockBatchId =StockBatchId from @tStockIssueReturnDetail where ID=@lCount
			
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lStockItemId AND StoreLocationId = @rFromStoreLocationId
			
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueReturnBatch', 0, 1, 1,@outNextNumber = @lNextNumberIssueReturnBatch output
			INSERT INTO sProcurement.tStockIssueReturnBatch
			(
				Id,StockIssueReturnId,StockIssueBatchId,ReturnQuantity,OrgGroupId,ReasonId,CreatedDateTime
			)
			
			Values
			(
				@lNextNumberIssueReturnBatch,@lNextNumberStockIssueReturn,
				@lStockIssueBatchId,@lQuantity,@rOrgGroupId,@lReasonId ,sCommon.fGetDate()
			)
			SET @lIssueValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lQuantity,0)
			  
			EXEC sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId=@rOrgGroupId,@rSourceTypeId=1012,
			@rSourceId=@lNextNumberIssueReturnBatch,@rItemSourceTypeId=34,
			@rItemSourceId=@lStockItemId,@rQuantity=@lQuantity,@rValue=@lIssueValue,
			@rIsReceipt=1,@rCreatedUserId=@rCreatedUserId,@rStoreLocationId=@rfromStoreLocationId,
			@rLocationId=@rLocationId,@rItemBatchId=@lStockBatchId,@rItemName=@lStockItemName,@rOrgId=@rOrgId	
		
			set @lCount =@lCount-1
		END	
		 
		 
		
--SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tStockInwardReturn WHERE FromStoreLocationId = @rFromStoreLocationId
--SET @rNumber = @rNumber + 1

--	DECLARE @lNextNumberStockInwardReturn INT
--	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardReturn', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardReturn output
	
--	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sHostel.tHostelMaster',@lNextNumber = @lNextNumberStockInwardReturn output
 
--	INSERT INTO sProcurement.tStockInwardReturn
--		(
--			Id,
--			Number,
--			ReturnByName, 
--			FromStoreLocationId,		 	 
--			Remark,
--			StockInwardId,
--			CreatedUserId,
--			CreatedDateTime,
--			OrgGroupId
--		)
--	VALUES
--		(
--			@lNextNumberStockInwardReturn,
--			@rNumber,
--			@rReturnByName,		 
--			@rFromStoreLocationId,			 
--			@rRemark,
--			@rStockInwardId,
--			@rCreatedUserId,
--			sCommon.fGetDate(),
--			@rOrgGroupId
--		)


	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockIssueReturn AS Id 
	COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueReturnDataGet]
	@rNumber [nvarchar](30) = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT DISTINCT SIR.Id,
		SIR.Number,
		ISNULL(SIR.ReturnedByName,'') AS ReturnedByName,
		SIR.ToStoreLocationId,
		SIR.Remark,
		SIR.StockIssueId,
		SIRB.StockIssueBatchId,
		SIRB.ReturnQuantity,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIM.Id AS StockItemId,
		SIB.StockBatchId AS StockBatchId,
		SIR.CreatedUserId,
		SI.Number AS IssueNumber,
		SIRB.ReasonId,
		Sb.Number AS 'StockBatchNumber',
		CASE WHEN SIR.TransactionDate is not null THEN SIR.TransactionDate ELSE SIR.CreatedDateTime END AS TransactionDate,
		(SELECT ISNULL(SUM(SIRB.ReturnQuantity),0) 
		FROM sProcurement.tStockIssueReturn SIR 
			INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id 
		WHERE SIR.StockIssueId=SI.Id AND SIRB.StockIssueBatchId=SIB.Id) AS ReturnedQuantity,
		SIND.IssuedQuantity AS IssuedQuantity,
		ISNULL(SI.IssueToSourceTypeId,0) AS IssueToSourceTypeId, --mantis: 42319
		ISNULL(SI.IssueToSourceId,0) AS IssueToSourceId --mantis: 42319

	FROM sProcurement.tStockIssueReturn SIR 
		INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id
		INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id=SIRB.StockIssueBatchId
		LEFT JOIN sProcurement.tStockBatch Sb ON sb.id = SIB.StockBatchId AND sb.Number is not null
		INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.Id=SIB.StockIssueDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
		INNER JOIN sProcurement.tStockIssue SI ON SI.Id=SIR.StockIssueId

	WHERE ((SIR.Number = @rNumber) OR (@rNumber = ''))
		AND SIR.ToStoreLocationId = @rStoreLocationId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueReturnSearchGet]

	@rIssueReturnNumber nvarchar(30) = '',
	@rStoreLocationId int,
	@rIssueToName nvarchar(150),
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN
			SET @rIssueToName = sCommon.fSearchStringGet(@rIssueToName)
		END
	    SELECT 
	          SIR.Id AS StockIssueReturnId,
			  SIR.Number AS IssueReturnNumber,
			  SIR.ToStoreLocationId,
			  SI.Number AS IssueNumber,
			  SIR.TransactionDate,
			  U.DisplayTitle AS UserName,
			  (CASE WHEN SI.IssueToSourceTypeId = 2001 then SA.Name ELSE SI.IssueToName END) AS IssueToName -- chnages in name for mantis Id :0035260
		FROM 
			  sProcurement.tStockIssueReturn SIR 
			  INNER JOIN sProcurement.tStockIssue SI ON SI.Id=SIR.StockIssueId
			  LEFT JOIN sSecurity.tUser U ON U.Id = SIR.CreatedUserId
			  LEFT JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = SI.IssuetoSourceId
	   	WHERE 
	   	      ((SIR.Number = @rIssueReturnNumber) OR (@rIssueReturnNumber = ''))
	   	      AND ((SIR.ToStoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	   		  AND ((SI.IssueToName like @rIssueToName OR ISNULL(@rIssueToName,'')='')
			  OR (SA.Name like @rIssueToName OR ISNULL(@rIssueToName,'')='')	)	
	   		  AND ((SIR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	   		  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueSearchGet]

	@rIssueNumber nvarchar(30) = '',
	@rStoreLocationId int,
	@rIssueToName nvarchar(150), -- changes for mantis Id:0035260
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		BEGIN
			SET @rIssueToName = sCommon.fSearchStringGet(@rIssueToName)
		END

	    SELECT		
			SI.Id AS StockIssueId,
			SI.Number AS Number,
			(CASE WHEN SI.IssueToSourceTypeId = 2001 then  SA.Name ELSE SI.IssueToName END) AS IssueToName, -- chnages in name for mantis Id :0035260
			SI.FromStoreLocationId,
			SI.CreatedUserId AS UserId,
			SI.CreatedDateTime AS IssuedDate
		FROM		
			sProcurement.tStockIssue SI 
			INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = SI.FromStoreLocationId
			LEFT JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = SI.IssuetoSourceId

		WHERE 
			((SI.Number = @rIssueNumber) OR (@rIssueNumber = ''))
			AND (SI.IssueToName like @rIssueToName OR ISNULL(@rIssueToName,'')='')
   			AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   			AND ((SI.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
	   		  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueStudentAdd_New]
(
	@rOrgGroupId [int],
	@rNumber						nvarchar(20) = '',
	@rStockIssueRequestId			int=0, 
	@rIssuedByName					nvarchar(100) = '',
	@rToOrganizationDepartmentId	int,
	@rFromStoreLocationId			int,
	@rFirstAidId					int,
	@rCreatedUserId					bigint,
	@rDetail						Nvarchar(Max)='',
	@rOrgId int,
	@rLocationId int,
	@rIssuedToName nvarchar(50)='',
	@rIssueToSourceTypeId int,
	@rIssueToSourceId bigint,
	@rIssueDate datetime = null,
    @rCreatedOnDate datetime = null ,
	@rPayTypeId tinyint=null,
	@rReceiptNumber int=null,
	@rBankName  nvarchar(200)=null,
	@rChequeNo  nvarchar(40)=null,
	@rChequeDate Date=null,
	@rRemark Nvarchar(300) ='' --mantis - 0032618
)
AS

SET NOCOUNT ON

BEGIN
EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 26,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

SET @rNumber = ISNULL(@rNumber, '-300')

IF @rNumber = '-300'
BEGIN
 
SELECT -300 AS Result, '' AS Number, 0 AS Id 
RETURN
END
 
	  DECLARE @lNextNumberStockIssue INT
	  DECLARE @loXML XML
		SET @loXML = CAST(@rDetail AS XML)
	  DECLARE @tStockIssueDetail TABLE
		(
			Id Int IDENTITY(1,1),StockItemId Int,IssuedQuantity Decimal(12,2)
		)

	  INSERT INTO @tStockIssueDetail
		SELECT
		T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@IssuedQuantity','decimal(12,2)') AS IssuedQuantity 
		FROM @loXML.nodes('/Table/StockIssue')T(c)
	 
	 BEGIN TRANSACTION
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockIssue',@lNextNumber = @lNextNumberStockIssue output



If @rFirstAidId < 0 
SET @rFirstAidId =  NULL

	INSERT INTO sProcurement.tStockIssue
		(
			Id,
			Number,
			StockIssueRequestId, 
			IssuedByName,
			ToOrganizationDepartmentId,
			FromStoreLocationId,
			FirstAidId,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			IssueToName,
			IssueToSourceTypeId,
			IssueToSourceId,
			TransactionDate,
			PayTypeId,
			ReceiptNumber,
			BankName,
			ChequeNo,
			ChequeDate
		)
	VALUES
		(
			@lNextNumberStockIssue,
			@rNumber,
		   (CASE WHEN @rStockIssueRequestId = 0 THEN NULL ELSE @rStockIssueRequestId END),	 
			@rIssuedByName,
			@rToOrganizationDepartmentId,
			@rFromStoreLocationId,
			@rFirstAidId,
			@rRemark,-- replace '' with @rRemark for mantis - 0032618
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rIssuedToName,
			@rIssueToSourceTypeId,
			@rIssueToSourceId,
			@rIssueDate,
			@rPayTypeId,
			@rReceiptNumber,
			@rBankName,
			@rChequeNo,
			@rChequeDate
		)


	DECLARE @lNextNumberStockIssueDetail BigInt,@lQuantity decimal(12,2),@lStockItemCode nvarchar(50)
		Declare @lCOunt int , @lItemId int,@lIssueQuantity decimal(12,2),
		@lbatchId int,@lIsBatchWise bit,@lBatch nvarchar(300),@lNextNumberStockBatch int,@lNextNumberBatch int,
		@lWeightedAverageCost decimal(12,2),@lInwardValue decimal(12,2),@lStockItemName nvarchar(50),
		@lNextNumberOtherStockBatch bigint
		Select @lCOunt = count(*) from @tStockIssueDetail
		
		IF @lcount = 0
		BEGIN
			ROLLBACK TRANSACTION
			Select -211 As Result,@lStockItemCode AS StockItemCode
			Return
		END
		
		while @lcount>0
		BEGIN
			Select @lItemId = StockItemId , @lIssueQuantity = IssuedQuantity ,@lCOunt=Id
			from @tStockIssueDetail where Id=@lCOunt
			
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lItemId AND StoreLocationId =  @rFromStoreLocationId  
			 
			Select @lQuantity=AvailableQuantity,@lbatchId=Id from sProcurement.tStockBatch where  StockItemId = @lItemId ANd StorelocationId=@rFromStoreLocationId
			  
			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				ROLLBACK TRANSACTION
				Select -102 As Result,@lStockItemCode AS StockItemCode
				Return
			END 
			IF @lQuantity = 0 
			BEGIN
				ROLLBACK TRANSACTION
				Select -103 AS Result,@lStockItemCode AS StockItemCode
				return
			END
			IF @lQuantity < @lIssueQuantity 
			BEGIN
				ROLLBACK TRANSACTION
				Select -101 AS Result,@lStockItemCode AS StockItemCode
				return
			END
			
			IF Exists(Select Id from sProcurement.tStockIssueDetail where StockIssueId = @lNextNumberStockIssue and StockItemId = @lItemId)					
			BEGIN
				Select @lNextNumberStockIssueDetail= Id from sProcurement.tStockIssueDetail
				Where StockIssueId = @lNextNumberStockIssue AND StockIteMid =@lItemId					 
			END	
			ELSE
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output
				IF NOT EXISTS (SELECT 1 FROM sProcurement.tStockIssueDetail WHERE Id = @lNextNumberStockIssueDetail)
				BEGIN
				INSERT INTO sProcurement.tStockIssueDetail
				(
					Id,StockIssueId,StockItemId,IssuedQuantity,RequestedQuantity,
					StockIssueRequestDetailId,Remark,OrgGroupId
				)
				SELECT @lNextNumberStockIssueDetail,@lNextNumberStockIssue,StockItemId,IssuedQuantity,
				0,NULL,'',@rOrgGroupId
				from @tStockIssueDetail where Id=@lcount
				END 
			END
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output

			INSERT INTO sProcurement.tStockIssueBatch
			(
				Id,StockIssueDetailId,StockBatchId,Quantity,OrgGroupId
			)
		Select @lNextNumberBatch,@lNextNumberStockIssueDetail,@lbatchId,@lIssueQuantity,@rOrgID

		SET @lInwardValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lIssueQuantity,0)
		
		Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=51,@rSourceId=@lNextNumberBatch,
			@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lIssueQuantity ,@rValue=@lInwardValue,@rIsReceipt=0,
			@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rFromStoreLocationId ,@rLocationId=@rLocationId,
			@rItemBatchId = @lbatchId,@rItemName =@lStockItemName,@rOrgId=@rOrgId
		set @lcount =@lcount-1
END
	--DECLARE @lIntErrorCode INT, @lIntDoc INT
	--EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	--DECLARE @tStockIssueDetail TABLE
	--(
	--Id						Int IDENTITY(0, 1),
	--StockIssueDetailId		Int, 
	--StockIssueRequestDetailId	Int, 
	--StockIssueId 			Int, 
	--StockItemId				Int, 
	--IssuedQuantity			Decimal(12,2),
	--RequestedQuantity		Decimal(12,2),  
	--Remark					Nvarchar(300)
	--)
	
	--INSERT INTO @tStockIssueDetail  
	--(  
	--	StockIssueId,
	--	StockItemId,
	--	IssuedQuantity,
	--	RequestedQuantity,
	--	StockIssueRequestDetailId, 
	--	Remark
	--)
	--SELECT	@lNextNumberStockIssue, 
	--		StockItemId,
	--		IssuedQuantity,
	--		RequestedQuantity,
	--		(CASE WHEN StockIssueRequestDetailId = 0 THEN NULL ELSE StockIssueRequestDetailId END), 			
	--		Remark
			
	--FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail', 1)  
	--	WITH  
	--	(  
	--		StockItemId				Nvarchar(300)	'@StockItemId', 
	--		IssuedQuantity			Nvarchar(300)	'@IssuedQuantity', 
	--		RequestedQuantity		Nvarchar(300)	'@RequestedQuantity', 
	--		StockIssueRequestDetailId  Nvarchar(300)'@StockIssueRequestDetailId', 
	--		Remark					Nvarchar(300)	'@Remark'
	--	) XmlTable
	
	--DECLARE @lNextNumberStockIssueDetail BigInt
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output
	
	
	--INSERT INTO sProcurement.tStockIssueDetail
	--	(
	--		Id,
	--		StockIssueId,
	--		StockItemId,
	--		IssuedQuantity,
	--		RequestedQuantity,
	--		StockIssueRequestDetailId, 
	--		Remark,
	--		OrgGroupId
	--	)
	--SELECT 	@lNextNumberStockIssueDetail + Id, 
	--		StockIssueId, 
	--		StockItemId, 
	--		IssuedQuantity,
	--		RequestedQuantity, 
	--		StockIssueRequestDetailId, 
	--		Remark,
	--		@rOrgGroupId
	--FROM	@tStockIssueDetail
	
	--UPDATE @tStockIssueDetail SET StockIssueDetailId = @lNextNumberStockIssueDetail + Id 
	--SELECT @lNextNumberStockIssueDetail = MAX(Id) + @lNextNumberStockIssueDetail FROM @tStockIssueDetail
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueDetail', @rCurrentNumber = @lNextNumberStockIssueDetail 
	
	--DECLARE @tBatch TABLE
	--(
	--	Id						Int IDENTITY(0, 1), 
	--	StockIssueDetailId	Int,
	--	StockBatchId Int,		
	--	Quantity				Decimal(12,2),
	--	StockItemId				Int				
	--)
	
	--INSERT INTO @tBatch  
	--		(  
	--		StockIssueDetailId,	
	--		StockBatchId, 
	--		Quantity,
	--		StockItemId									
	--		)
	--SELECT	1, 
	--		StockBatchId, 
	--		Quantity,
	--		StockItemId
	--FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail/StockIssueBatch', 1)  
	--	WITH  
	--	(  
	--		StockBatchId 	Nvarchar(200)	'@StockBatchId', 
	--		Quantity					Nvarchar(200)	'@Quantity',
	--		StockItemId					Nvarchar(200)	'@StockItemId' 			
	--	) XmlTable	
		
		
	--DECLARE @lNextNumberBatch BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output
	
	--INSERT INTO sProcurement.tStockIssueBatch
	--	(
	--		Id,
	--		StockIssueDetailId,
	--		StockBatchId,
	--		Quantity,
	--		OrgGroupId
	--	)
	--SELECT 		@lNextNumberBatch + TD.Id, 
	--			STD.StockIssueDetailId, 
	--			StockBatchId, 
	--			Quantity,
	--			@rOrgGroupId
	--FROM		@tStockIssueDetail STD 
	--INNER JOIN	@tBatch TD 
	--			ON TD.StockItemId = STD.StockItemId
				
	--SELECT @lNextNumberBatch = MAX(Id) + @lNextNumberBatch FROM @tBatch
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueBatch', @rCurrentNumber = @lNextNumberBatch 
	
	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockIssue AS Id 
		COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sProcurement].[pStockIssueStudentImport]
	(
		@rXml  nvarchar(MAX),
		@rOrgGroupId int,
		@rNumber nvarchar(20) = '',
		@rStockIssueRequestId int = 0, 
		@rIssuedByName nvarchar(100) = '',
		@rToOrganizationDepartmentId int,
		@rFromStoreLocationId int,
		@rFirstAidId int,
		@rCreatedUserId bigint,
		@rOrgId int,
		@rLocationId int,
		@rIssuedToName nvarchar(50) = '',
		@rIssueToSourceTypeId int,
		@rIssueDate datetime = null,
		@rCreatedOnDate datetime = null ,
		@rPayTypeId tinyint = null,
		@rReceiptNumber int = null,
		@rBankName nvarchar(200) = null,
		@rChequeNo nvarchar(40) = null,
		@rChequeDate Date = null,
		@rRemark Nvarchar(300) = ''
	)
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE @lNextNumberStockIssue INT, @intDoc int, @lInterrorCode INT,@lInwardValue decimal(12,2),@lcount int,@lStockItemName nvarchar(50);
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml;

	BEGIN TRY
		CREATE TABLE #tempTable  
		(
			Id bigint identity,
			Code nvarchar(50),
			AcademicId bigint,
			ItemSubGroupCode nvarchar(50),
			ItemCode nvarchar(50),
			--WACCost decimal(10,2),
			Quantity int,
			--TotalCost decimal(10,2),
			StockItemId int,
			PayType nvarchar(100),
			PayTypeId int
		);

		-- Insert data from XML into #tempTable
		INSERT INTO #tempTable
		(
			Code,
			AcademicId,
			ItemSubGroupCode,
			ItemCode,
			--WACCost,
			Quantity,
			--TotalCost,
			StockItemId,
			PayType,
			PayTypeId
		)
		SELECT 
			A.Code,
			A.AcademicId,
			A.ItemSubGroupCode,
			A.ItemCode,
			--A.WACCost,
			A.Quantity,
			--A.TotalCost,
			A.StockItemId,
			A.PayType,
			PayTypeId
		FROM OPENXML (@intDoc, '/Table/StockIssue', 1)
		WITH
		(
			Code nvarchar(50) '@Code',
			AcademicId bigint '@AcademicId',
			ItemSubGroupCode nvarchar(50) '@ItemSubGroupCode',
			ItemCode nvarchar(50) '@ItemCode',
			--WACCost decimal '@WACCost',
			Quantity int '@Quantity',
			--TotalCost decimal '@TotalCost',
			StockItemId int '@StockItemId',
			PayType nvarchar(100) '@PayType',
			PayTypeId int '@PayTypeId'
		) A;

		-- Declare variables
		DECLARE @lAcademicId NVARCHAR(50), @lStockIssueId INT, @lId INT;
		DECLARE @stockCursor CURSOR;
		SELECT @lCount = COUNT(*) FROM #tempTable
		SELECT @lId= MIN(Id) FROM #tempTable	
		-- Declare the cursor here, before usage
		SET @stockCursor = CURSOR FOR
		SELECT DISTINCT AcademicId FROM #tempTable;

		-- Open the cursor once before the loop
		OPEN @stockCursor;

		-- Loop through each AcademicId in the cursor
		FETCH NEXT FROM @stockCursor INTO @lAcademicId;

		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- Generate next Stock Issue Number
			EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 26, @rStoreLocationId = @rFromStoreLocationId, @rNextNumber = @rNumber OUTPUT;
			SET @rNumber = ISNULL(@rNumber, '-300');

			IF @rNumber = '-300'
			BEGIN
				SELECT -300 AS Result, '' AS Number, 0 AS Id;
				RETURN;
			END;

			-- Generate new Stock Issue ID
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockIssue', @lNextNumberStockIssue OUTPUT;

			-- Insert new Stock Issue entry
			INSERT INTO sProcurement.tStockIssue
			(
				Id,
				Number,
				StockIssueRequestId,
				IssuedByName,
				ToOrganizationDepartmentId,
				FromStoreLocationId,
				FirstAidId,
				Remark,
				CreatedUserId,
				CreatedDateTime,
				OrgGroupId,
				IssueToName,
				IssueToSourceTypeId,
				IssueToSourceId,
				TransactionDate,
				PayTypeId,
				ReceiptNumber,
				BankName,
				ChequeNo,
				ChequeDate
			)
			VALUES
			(
				@lNextNumberStockIssue,
				@rNumber,
				(CASE WHEN @rStockIssueRequestId = 0 THEN NULL ELSE @rStockIssueRequestId END),
				@rIssuedByName,
				@rToOrganizationDepartmentId,
				@rFromStoreLocationId,
				@rFirstAidId,
				@rRemark,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgGroupId,
				@rIssuedToName,
				@rIssueToSourceTypeId,
				@lAcademicId,
				@rIssueDate,
				@rPayTypeId,
				@rReceiptNumber,
				@rBankName,
				@rChequeNo,
				@rChequeDate
			);

			-- Insert entries for each StockItemId in #tempTable
			DECLARE @lStockItemId INT, @lQuantity DECIMAL(12,2), @lNextNumberStockIssueDetail INT,@lNextNumberBatch int,@lbatchId int, 
			@lIssueQuantity decimal(12,2), @lItemId int,@lWeightedAverageCost decimal(12,2);

			Select @lItemId = StockItemId , @lIssueQuantity = Quantity ,@lCOunt=Id
			from #tempTable where Id=@lCOunt

			DECLARE itemCursor CURSOR FOR
			SELECT Id, StockItemId, Quantity
			FROM #tempTable
			WHERE AcademicId = @lAcademicId;

			OPEN itemCursor;
			FETCH NEXT FROM itemCursor INTO @lId,@lStockItemId, @lQuantity;

			WHILE @@FETCH_STATUS = 0
			BEGIN
				-- Generate next Stock Issue Detail ID for each item
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueDetail', 0, 1, 1, @outNextNumber = @lNextNumberStockIssueDetail OUTPUT;
				Select @lQuantity=AvailableQuantity,@lbatchId=Id from sProcurement.tStockBatch where  StockItemId = @lItemId ANd StorelocationId=@rFromStoreLocationId
				Select @lItemId = StockItemId , @lIssueQuantity = Quantity from #tempTable
				Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lItemId AND StoreLocationId =  @rFromStoreLocationId

				INSERT INTO sProcurement.tStockIssueDetail
				(
					Id, StockIssueId, StockItemId, IssuedQuantity, RequestedQuantity, StockIssueRequestDetailId, Remark, OrgGroupId
				)
				VALUES
				(
					@lNextNumberStockIssueDetail, 
					@lNextNumberStockIssue, 
					@lStockItemId, 
					@lIssueQuantity, 
					0, 
					NULL, 
					'', 
					@rOrgGroupId
				);

				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output

	INSERT INTO sProcurement.tStockIssueBatch
	(
		Id,StockIssueDetailId,StockBatchId,Quantity,OrgGroupId
	)
	Select @lNextNumberBatch,@lNextNumberStockIssueDetail,@lbatchId,@lIssueQuantity,@rOrgID

	SET @lInwardValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lIssueQuantity,0)
		
		Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=51,@rSourceId=@lNextNumberBatch,
			@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lIssueQuantity ,@rValue=@lInwardValue,@rIsReceipt=0,
			@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rFromStoreLocationId ,@rLocationId=@rLocationId,
			@rItemBatchId = @lbatchId,@rItemName =@lStockItemName,@rOrgId=@rOrgId
		set @lcount =@lcount-1

				-- Fetch next item
				FETCH NEXT FROM itemCursor INTO @lId,@lStockItemId, @lQuantity;
			END

			CLOSE itemCursor;
			DEALLOCATE itemCursor;

			-- Increment to next AcademicId
			FETCH NEXT FROM @stockCursor INTO @lAcademicId;
		END

		-- Close and Deallocate the main cursor
		CLOSE @stockCursor;
		DEALLOCATE @stockCursor;

		EXEC sp_xml_removedocument @intDoc;

		SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockIssue AS Id;
		DROP TABLE #tempTable;

	END TRY

	BEGIN CATCH
		SELECT -1 AS Result, ERROR_MESSAGE() AS MSG;
	END CATCH
END;

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockItemDetailsForPoDetailsGet]
	--@rOrgId int,
	@rStoreLocationId int,
	@rStockPurchaseUomId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	SELECT 
		 SIPU.Id,
		 SIPU.ConversionFactor,
		 SU.Id StockUomId,
		 Su.Code Code,
		 SU.Title Title,
		 SIM.Code StockItemCode,
		 SIM.Title StockItemTitle,
		 SIM.IsBatchWiseTracking,
		 ISNULL(SIP.StandardPrice, 0) StandardPrice,
		 ISNULL(SIM.TaxGroupId, 0) TaxGroupId, 
		 ISNULL(TGM.Code, '')  TaxCode,
		 ISNULL(TGM.Title, '')  TaxTitle,
		 ISNULL(sTax.fExtTaxRateGet(SIM.TaxGroupId, sCommon.fGetDate()), 0) TaxRate
		
	FROM 
		sIp.tStockItemPurchaseUom SIPU
	INNER JOIN 
		sFinanceCommon.tStockUomMaster SU
	ON
		SU.Id = SIPU.StockUomId
	INNER JOIN 
		sIp.tStockItemMaster SIM
	ON
		SIM.Id = SIPU.StockItemId
		 INNER JOIN sIp.tStockItemPlanning SIP 
	   ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId =@rStoreLocationId	
	LEFT JOIN
		sTax.vExtTaxGroupMaster  TGM
	ON
		TGM.Id = SIM.TaxGroupId
	WHERE SIPU.Id = @rStockPurchaseUomId 
	--AND IsHistory IS NOT NULL AND Inactive IS NOT NULL
	--AND SIM.OrgId = @rOrgId
END
 

/****** Object:  View [sIp].[vExtStockItemMaster]    Script Date: 07/09/2013 16:17:07 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockItemFreezeAdd]
	@rOrgId int,
	@rStockItemFreezeDataXML [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 1
	--Commented on 19/06/2025 - Invalid column name 'OrgId'.
--	DECLARE @loIdoc INT
--	DECLARE @lNextNumber BIGINT
--	DECLARE @lCount BIGINT 
		
--	SET @lCount = 0
	
--	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockItemFreezeDataXML
--	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockItemFreeze', 0, 1, 1,@outNextNumber = @lNextNumber output

--	INSERT INTO sProcurement.tStockItemFreeze
--		(
--			Id,
--			ItemMainGroupId,
--			StoreLocationId,
--			StatusId,			
--			CreatedUserId,
--			CreatedDateTime
--			--,OrgId --Commented as No orgid is there in table
		
--		)
--SELECT  
--		@lNextNumber + ROW_NUMBER() OVER(ORDER BY StoreLocationId) AS Id, 
--		ItemMainGroupId,
--		StoreLocationId,
--		IsObsolete,
--		CreatedUserId,
--		sCommon.fGetDate()
--		--,@rOrgId
		
		
--	FROM OPENXML (@loIdoc, '/StockItemFreeze/StockItemFreezeDetail', 1)
--		WITH ( 
--				ItemMainGroupId INT, 
--				StoreLocationId INT, 
--				SystemQuantity INT,
--				IsObsolete INT,
--				CreatedUserId BIGINT
			
--			  ) 
		
--		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockItemFreeze/StockItemFreezeDetail', 1)
--				 WITH ( StoreLocationId INT)
				 
--				 SET @lNextNumber  = @lCount + @lNextNumber 
		
--		EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sProcurement.tStockItemFreeze', @rCurrentNumber = @lNextNumber 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockItemFreezeModify]
	@rStockItemFreezeDataXML [nvarchar](max),
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	  DECLARE @lIntErrorCode INT, @lIntDoc INT				
	  EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rStockItemFreezeDataXML

	  
	  UPDATE  sProcurement.tStockItemFreeze
				SET	sProcurement.tStockItemFreeze.Statusid = XmlTable.IsObsolete,
				sProcurement.tStockItemFreeze.UnfreezedDateTime = sCommon.fGetDate(),
				sProcurement.tStockItemFreeze.UnfreezedBy  = XmlTable.CreatedUserId
			FROM OPENXML (@lIntDoc, '/StockItemFreeze/StockItemFreezeDetail', 1)
				 WITH ( 
				 Id BIGINT, 
				 IsObsolete INT,
				CreatedUserId BIGINT
				
					  ) XmlTable
	WHERE sProcurement.tStockItemFreeze.Id = XmlTable.Id 
		
	
	
	
		  UPDATE  sProcurement.tStockVerification
				SET	sProcurement.tStockVerification.IsObsolete = 1
				--sProcurement.tStockItemFreeze.UnfreezedDateTime = sCommon.fGetDate(),
				--sProcurement.tStockItemFreeze.UnfreezedBy  = XmlTable.CreatedUserId
			FROM OPENXML (@lIntDoc, '/StockItemFreeze/StockItemFreezeDetail', 1)
				 WITH ( 
				 Id BIGINT, 
				 IsObsolete INT,
				CreatedUserId BIGINT
				
					  ) XmlTable
	WHERE sProcurement.tStockVerification.StockItemFreezeId = XmlTable.Id 	
	
	
	  
	SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockItemFreezeVerification]
	@rOrgId int,
	@rStoreLocationId [int],
	@rStockVerificationDataXML [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	DECLARE @loIdoc INT
	DECLARE @tempIdtableItemFreeze TABLE (Id BIGINT, Status INT, ItemMainGroupId INT)
	
	DECLARE @lTempIdtableStockItemTypeFreeze TABLE(Id BIGINT,
	ItemTypeCode  INT,
	ItemTypeTitle NVARCHAR(200),
	StoreLocationId INT,
	Department   NVARCHAR(200),
	CreatedDateTime DATETIME,
	UnfreezedDateTime  DATETIME,
	StatusId INT)


	
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockVerificationDataXML
	
	
	INSERT INTO @tempIdtableItemFreeze
	SELECT d.Id AS Id, 0 AS Status, SIM.ItemManGroupId
		FROM OPENXML (@loIdoc, '/StockItemIds/StockItemId', 1) 
				WITH ( 
						Id INT
						 
					  )d
		INNER JOIN 
				sIp.vExtStockItemMaster SIM
		ON
				SIM.Id = d.Id AND SIM.StoreLocationId=@rStoreLocationId
			
		
	INSERT INTO @lTempIdtableStockItemTypeFreeze
	  EXEC sProcurement.pStockFreezeGet	@rOrgId, @rStoreLocationId, 0, 0
		
	SELECT ItemF.Id, (CASE WHEN ItemTypeF.StatusId =  140 THEN 1 ELSE 0 END) AS Status FROM @lTempIdtableStockItemTypeFreeze ItemTypeF
		INNER JOIN @tempIdtableItemFreeze ItemF		  	
		ON ItemTypeF.ItemTypeCode = ItemF.ItemMainGroupId
		 	 
END





/****** Object:  StoredProcedure [sProcurement].[pRptStockIssue]    Script Date: 07/09/2013 16:27:07 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockItemWiseTransaction]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rFilterId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rId int,
	--@rItemCode nvarchar(100),
	--@rItemName nvarchar(100),
	@rOrgId smallint,
	@rFromDate datetime = '',
	@rToDate datetime = ''
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
  
	  
	SELECT
	WAC.Id,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SIM.Id AS StockItemId,
		
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Good Reciept Note' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE
	   SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 46)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		--AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 7) OR (ISNULL(@rFilterId,  0) = 0))
		
		
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Good Return Note' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 47)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		--AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 8) OR (ISNULL(@rFilterId,  0) = 0))
		
		
		
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Adjustment' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 50)
		AND WAC.StoreLocationId= @rStoreLocationId
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		--AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 9) OR (ISNULL(@rFilterId,  0) = 0))
		
		
			
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Inward' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1010)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		--AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 11) OR (ISNULL(@rFilterId,  0) = 0))
		
		
					
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Issue' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 51)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		--AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 1) OR (ISNULL(@rFilterId,  0) = 0))
		
		
					
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Transfer' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 52)
	    AND WAC.StoreLocationId= @rStoreLocationId 
	    AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		--AND (SIM.Title like @rItemName OR @rItemName = '')
		
		AND ((@rFilterId = 2) OR (ISNULL(@rFilterId,  0) = 0))
		
		
						
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Freeze Adjustmnet' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 104)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		--AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 10) OR (ISNULL(@rFilterId,  0) = 0))
		
		
		
							
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Dispense' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 48)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		--AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 3) OR (ISNULL(@rFilterId,  0) = 0))
		
		UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Inward Return' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1013)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		--AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 12) OR (ISNULL(@rFilterId,  0) = 0))

		
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Issue Return' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1012)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		--AND (SIM.Code like @rItemCode OR @rItemCode = '')
		--AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 5) OR (ISNULL(@rFilterId,  0) = 0))

	Order by WAC.Id	desc	
END

 




/****** Object:  StoredProcedure [sIp].[pWeightedAverageCostLogGet]    Script Date: 07/09/2013 16:23:45 ******/
SET ANSI_NULLS ON

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 CREATE OR ALTER PROCEDURE [sProcurement].[pStockKitDetailAdd]
	@rStockKitId [int],
	@rStockKitDeatilXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loIdoc INT
	DECLARE @lStockKitDetailCurrentId INT
	DECLARE @lCount INT
	DECLARE @lNextNumber int
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockKitDeatilXml
	CREATE TABLE #TempStockKitDetail (StockKitId INT,StockItemId int,Quantity DECIMAL(22, 6));

	BEGIN TRY
	BEGIN TRANSACTION
		INSERT INTO #TempStockKitDetail (StockKitId,StockItemId,Quantity)
		SELECT  
			StockKitId,
			StockItemId,
			Quantity
		FROM OPENXML (@loIdoc, '/StockKit/StockKitDetail', 1)
			WITH ( 
					StockKitId INT, 
					StockItemId INT,
					Quantity DECIMAL(22, 6)
				  )

		DELETE SKD  
		From sProcurement.tStockKitDetail SKD
		Left JOIN #TempStockKitDetail Temp On SKD.StockKitId=Temp.StockKitId AND TEMP.StockItemId=SKD.StockItemId 
		 Where Temp.StockKitId is null AND SKD.StockKitId =@rStockKitId


		UPDATE SKD
		Set SKD.Quantity=Temp.Quantity
		From sProcurement.tStockKitDetail SKD
		Inner Join #TempStockKitDetail Temp  ON Temp.StockKitId=SKD.StockKitId  AND TEMP.StockItemId=SKD.StockItemId 


		INSERT INTO sProcurement.tStockKitDetail
			(
				StockKitId,
				StockItemId,
				Quantity
			)
		SELECT  
			@rStockKitId,
			Temp.StockItemId,
			Temp.Quantity
		FROM #TempStockKitDetail Temp
		Left JOIN sProcurement.tStockKitDetail SKD On SKD.StockKitId=Temp.StockKitId AND TEMP.StockItemId=SKD.StockItemId 
		Where SKD.StockKitId is null

	   COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockKitDetailGet]
	
	 @rStockKitId int = 0,
	 @rStockItemId int=0,
	 @rOrgGroupId int=0,
	 @rStoreLocationId int=0,
	 @rStockKitTitle nvarchar(100)='',
	 @rStockKitCode nvarchar(20)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SET @rStockKitCode = sCommon.fSearchStringGet(@rStockKitCode)
	SET @rStockKitTitle = sCommon.fSearchStringGet(@rStockKitTitle)
END	 

BEGIN 

	SELECT 
	
	SKD.StockKitId AS StockKitId, 
	SKD.StockItemId AS StockItemId,
	SKD.Quantity AS Quantity,
	ESIM.Code AS StockItemCode,
	ESIM.Title AS StockItemName,
	ISUBM.Title AS ItemSubGroup,
	ESIM.ItemSubGroupId as ItemSubGroupId

     
  FROM sProcurement.tStockKitDetail SKD
  INNER JOIN sProcurement.tStockKitMaster SKM ON SKM.Id=SKD.StockKitId
  Inner Join sIp.vExtStockItemMaster ESIM ON ESIM.Id=SKD.StockItemId  
  Inner Join  [sIp].[tItemSubGroupMaster] ISUBM ON ESIM.ItemSubGroupId=ISUBM.Id
             
  WHERE 
	  (SKM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)	
	  AND SKM.StoreLocationId=@rStoreLocationId
      AND ((SKM.Id = @rStockKitId) OR (@rStockKitId = 0))
      AND ((SKM.Code like @rStockKitCode) OR (ISNULL(@rStockKitCode,'') = ''))    
      AND ((SKM.Title like @rStockKitCode) OR (ISNULL(@rStockKitCode,'') = ''))  
	  AND (ESIM.Id =@rStockItemId or @rStockItemId=0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockKitIssueDetailAdd]
	@rStockKitIssueDeatilXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
	BEGIN TRANSACTION
	DECLARE @loDoc INT
		
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStockKitIssueDeatilXml
		INSERT INTO [sProcurement].[tStockKitIssueDetail]
				   ([StockIssueId]
				   ,[StockKitId])
		SELECT
			StockIssueId,
			StockKitId
		FROM OPENXML (@loDoc, '/Table/StockKitDetail', 1)
		WITH ( 
				StockIssueId int,
				StockKitId int
			  ) 



		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH



END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sProcurement].[pStockKitMasterAdd]
	 
	@rOrgGroupId int,	
	@rId int,
	@rNumber int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rCreatedUserId bigint,
	@rOrderIndex smallint,
	@rIsObsolete bit,
	@rStoreLocationId int,
	@rStockKitDeatilXml [nvarchar](max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	-- For New Entry
	print 1
	IF(@rId = 0)
		BEGIN
			If Exists(select Id from sProcurement.tStockKitMaster where Code=@rCode AND OrgGroupId= @rOrgGroupId AND StoreLocationId=@rStoreLocationId)
			BEGIN
				select -101 as Result
				RETURN
			END 
			If Exists(select Id from sProcurement.tStockKitMaster where Number=@rNumber AND OrgGroupId= @rOrgGroupId AND StoreLocationId=@rStoreLocationId)
			BEGIN
				select -102 as Result
				RETURN
			END
			If Exists(select Id from sProcurement.tStockKitMaster where OrderIndex=@rOrderIndex AND OrgGroupId= @rOrgGroupId AND StoreLocationId=@rStoreLocationId)
			BEGIN
				select -103 as Result
				RETURN
			END
		 
	 
		END
	-- For Update Entry	
	ELSE
		BEGIN
			If  Exists(select Id from sProcurement.tStockKitMaster where Code=@rCode AND Id<>@rId AND OrgGroupId=@rOrgGroupId AND StoreLocationId=@rStoreLocationId)
			Begin
				select -101 as Result
				RETURN
			End
			If  Exists(select Id from sProcurement.tStockKitMaster where Number=@rNumber AND Id<>@rId AND OrgGroupId=@rOrgGroupId AND StoreLocationId=@rStoreLocationId )
			Begin
				select -102 as Result
				RETURN
			End
			If  Exists(select Id from sProcurement.tStockKitMaster where OrderIndex=@rOrderIndex AND Id<>@rId AND OrgGroupId=@rOrgGroupId AND StoreLocationId=@rStoreLocationId )
			Begin
				select -103 as Result
				RETURN
			End
		END
BEGIN TRY
BEGIN TRANSACTION	
	IF(@rId = 0)	
	 BEGIN
		DECLARE @lNextNumber INT     
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockKitMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		print @lNextNumber
		INSERT INTO  sProcurement.tStockKitMaster
			(
				 OrgGroupId,
				 Id,
				 Number,
				 Code,
				 Title,
				 CreatedUserId,
				 CreatedDateTime,
				 OrderIndex,
				 IsObsolete,
				 StoreLocationId
			)
		VALUES
			(
				@rOrgGroupId,
				@lNextNumber,
				@rNumber,
				@rCode,
				@rTitle,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrderIndex,
				@rIsObsolete,
				@rStoreLocationId
			)
			EXECUTE [sProcurement].[pStockKitDetailAdd]  @rStockKitId = @lNextNumber,@rStockKitDeatilXml=@rStockKitDeatilXml
			SELECT 1 AS Result       
	END	 
	ELSE
	BEGIN
		 SET @lNextNumber = @rId
			UPDATE sProcurement.tStockKitMaster
			SET
				 Number=@rNumber,
				 Code=@rCode,
				 Title=@rTitle,
				 OrderIndex=@rOrderIndex,
				 IsObsolete=@rIsObsolete,
				 UpdatedUserId=@rCreatedUserId,
				 UpdatedDateTime=sCommon.fGetDate(),
				 StoreLocationId=@rStoreLocationId
	      
			  WHERE Id = @rId 	
			 EXECUTE [sProcurement].[pStockKitDetailAdd]  @rStockKitId = @lNextNumber,@rStockKitDeatilXml=@rStockKitDeatilXml
			  SELECT 11 AS Result    
	END  
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockKitMasterGet]
	
	 @rId int = 0,
	 @rTitle nvarchar(100)='',
	 @rCode nvarchar(20)='',
	 @rOrgGroupId int,
	 @rStoreLocationId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
END	 

BEGIN 

	SELECT 
	
	CTM.Id, 
	CTM.Code,
	CTM.Number,
	CTM.Title,
	CTM.IsObsolete,
	CTM.OrderIndex,
	OrgGroupId,
	CreatedUserId,
	StoreLocationId,
	CreatedDateTime
     
  FROM sProcurement.tStockKitMaster CTM         
             
  WHERE 
	  CTM.OrgGroupId = @rOrgGroupId		
	  AND StoreLocationId=@rStoreLocationId
      AND ((CTM.Id = @rId) OR (@rId = 0))
      AND ((CTM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))    
      AND ((CTM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	  Order By CTM.OrderIndex DESC 
	  
	EXECUTE [sProcurement].[pStockKitDetailGet]   @rStockKitId=@rId,@rOrgGroupId =@rOrgGroupId,@rStoreLocationId=@rStoreLocationId,@rStockKitTitle=@rTitle,@rStockKitCode=@rCode
	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockLocationFreeze]
	@rOrgId int,
	@rStoreLocationId [int],
	@rStatus [int] OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	SET @rStatus = 0
BEGIN


IF EXISTS(SELECT 1 FROM sProcurement.tStockItemFreeze WHERE StoreLocationId = @rStoreLocationId 
			AND StatusId = 140 AND OrgGroupId = @rOrgId)
BEGIN
SET @rStatus = 1
END
ELSE
BEGIN
SET @rStatus = 0
END			

--		IF ( 
		
--		(SELECT COUNT(A.ID) FROM 
--(
--SELECT DISTINCT 
--		ISNULL(SIF.ID, 0) AS ID,
--		SITM.ID AS ItemTypeCode,
--		SITM.Title AS ItemTypeTitle,
--		SB.StoreLocationId,
--		SLM.Title AS  Department,
--		ISNULL(SIF.CreatedDateTime, NULL) AS CreatedDateTime,
--		ISNULL(SIF.UnfreezedDateTime, NULL) AS UnfreezedDateTime, 
--		ISNULL(SIF.StatusId, 0) AS StatusId
		
--		 FROM sProcurement.tStockBatch SB
--		INNER JOIN sIp.tStockItemMaster SIM
--			ON    SIM.Id = SB.StockItemId
--		INNER JOIN sIp.tStockItemTypeMaster SITM
--			ON SIM.StockItemTypeId = SITM.Id
--		LEFT JOIN sProcurement.tStockItemFreeze SIF
--			ON SIF.StoreLocationId = SB.StoreLocationId AND SIF.StockItemTypeId = SITM.Id 
--			AND SIF.StatusId = 140
--		INNER JOIN sIp.tStoreLocationMaster SLM
--				 ON SB.StoreLocationId = SLM.Id
--		 WHERE SB.StoreLocationId  = @rStoreLocationId AND SB.OrgGroupId = @rOrgGroupId)  A
--		 WHERE A.StatusId = 140) = 
		 
		 
--		(SELECT COUNT(B.ID) FROM 
--		( 
--		 SELECT DISTINCT 
--		ISNULL(SIF.ID, 0) AS ID,
--		SITM.ID AS ItemTypeCode,
--		SITM.Title AS ItemTypeTitle,
--		SB.StoreLocationId,
--		SLM.Title AS  Department,
--		ISNULL(SIF.CreatedDateTime, NULL) AS CreatedDateTime,
--		ISNULL(SIF.UnfreezedDateTime, NULL) AS UnfreezedDateTime, 
--		ISNULL(SIF.StatusId, 0) AS StatusId
		
--		 FROM sProcurement.tStockBatch SB
--		INNER JOIN sIp.tStockItemMaster SIM
--			ON    SIM.Id = SB.StockItemId
--		INNER JOIN sIp.tStockItemTypeMaster SITM
--			ON SIM.StockItemTypeId = SITM.Id
--		LEFT JOIN sProcurement.tStockItemFreeze SIF
--			ON SIF.StoreLocationId = SB.StoreLocationId AND SIF.StockItemTypeId = SITM.Id 
--			AND SIF.StatusId = 140
--		INNER JOIN sIp.tStoreLocationMaster SLM
--				 ON SB.StoreLocationId = SLM.Id
--		 WHERE SB.StoreLocationId  = @rStoreLocationId AND SB.OrgGroupId = @rOrgGroupId ) B)
		
--		)
			--SET @rStatus = 1
			
			--ELSE
			
			--SET @rStatus = 0
			
			--PRINT @rStatus

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sProcurement].[pStockReset]
	@rOrgGroupId smallint, 
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
SELECT		SI.Id,
			SI.Number,
			isnull(SI.ResetByName,'') as ResetByName,
			SI.CreatedDateTime			AS ResetDate,
			SLM.Code					AS ToStoreLocationCode
FROM		sProcurement.tStockReset SI
INNER JOIN	sIp.tStoreLocationMaster SLM
			ON SLM.Id = SI.ToStoreLocationId 		
WHERE		 
 			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = '*'))
		AND        SI.OrgGroupId = @rOrgGroupId	
		AND ((SI.CreatedDateTime>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SI.CreatedDateTime<=DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		AND SI.ToStoreLocationId =@rStoreLocationId
Order by  SI.Number desc,
 SI.CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockResetAdd_New]
(
@rOrgGroupId [smallint],
@rNumber Nvarchar(max) = '',
@rResetByName Nvarchar(max) = '',
@rToStoreLocationId	Int,
@rRemark Nvarchar(max),
@rCreatedUserId	BigInt,
@rDetail Nvarchar(Max),
@rLocationId int,
@rOrgId int,
@rTranjectionDate datetime = null,
@rResetDate  datetime = null

)
AS
SET NOCOUNT ON
BEGIN
  BEGIN TRY	    
	DECLARE @loXML XML
	SET @loXML = CAST(@rDetail AS XML)

	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1007,
	@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
	
	SET @rNumber = ISNULL(@rNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	END


	DECLARE @tStockResetDetailBatch TABLE
	(
		Id Int IDENTITY(1, 1),	 
		StockItemId bigint,
		StockItemName nvarchar(max),
		ItemBatch Nvarchar(max) NULL,
		ItemExpiryDate Date NULL,	
		ResetQuantity Decimal(12,2),
		RequestedQuantity Decimal(12,2),
		ResetValue Decimal(12,2)
	)	
    INSERT INTO @tStockResetDetailBatch
    SELECT
            T.c.value('@StockItemId','bigint') AS StockItemId,
            T.c.value('@StockItemName','nvarchar(max)') AS StockItemname,
            T.c.value('@ItemBatch','Nvarchar(max)') AS ItemBatch,
            T.c.value('@ItemExpiryDate','Date')   AS ItemExpiryDate,
            T.c.value('@ResetQuantity','Decimal(12,2)') AS ResetQuantity,
            T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity,
            T.c.value('@ResetValue','Decimal(12,2)') AS ResetValue 
    FROM 
            @loXML.nodes('/Table/StockReset')T(c)


  BEGIN TRANSACTION
   
	DECLARE @lNextNumberStockReset bigint,@lNextNumberStockResetBatch bigint
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockReset', 0, 1, 1,@outNextNumber = @lNextNumberStockReset output

	INSERT INTO sProcurement.tStockReset
	(
		Id,Number,ResetByName,ToStoreLocationId,Remark,CreatedUserId,CreatedDateTime,OrgGroupId,TransactionDate
	)
	VALUES
	(
		@lNextNumberStockReset,@rNumber,
		@rResetByName,@rToStoreLocationId,@rRemark,@rCreatedUserId,@rResetDate,
		@rOrgGroupId,@rTranjectionDate
	)
            
	declare @lCount int,@lIsBatchWise bit,@lbatchId int,@lNextNumberStockBatch int,@lExpiryDate date
	Declare @lItemId int,@lBatch nvarchar(300),@lResetQty decimal(12,2),@lResetValue decimal(12,2),@lIdCount int,@lAvaliableStock decimal(12,2),@lMainQty decimal(12,2) 
	DECLARE @lStockItemname nvarchar(max)
	select @lCount=COUNT(*) from @tStockResetDetailBatch 
		 
	while @lcount > 0
	BEGIN
					 
		Select @lItemId =StockItemId,@lBatch = ItemBatch,@lResetQty=ResetQuantity,@lResetValue=ResetValue,@lIdCount=Id,@lExpiryDate =ItemExpiryDate 
		,@lStockItemname=StockItemname
		from  @tStockResetDetailBatch WHERE Id = @lcount
		Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster    Where Id = @lItemId   
		 
		SET @lbatchId = 0
		 
			if (@lIsBatchWise=1)
			BEGIN		
							
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where  Number =@lBatch   AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId --AND @lIdCount=@lcount
				 
			END
			else 
			BEGIN
				
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where iSNULl( Number,'') =''  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId--AND  @lIdCount=@lcount
			 
			END

			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				  
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockBatch output
				 INSERT INTO sProcurement.tStockBatch (Id,StoreLocationId,StockItemId,Number,ExpiryDate,AvailableQuantity,CreatedUserId,CreatedDateTime,OrgGroupId,ItemRate)
				Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate ,@lResetQty,@rCreatedUserId,getdate(),@rOrgGroupId,@lResetValue
				--from @tStockResetDetailBatch where Id=@lcount
				
				 SET @lbatchId = @lNextNumberStockBatch
				 
				 
			END 
			 	 
			 if(@lbatchId>0)
			BEGIN
					 
				Select  @lAvaliableStock =  isnull(SUM(AvailableQuantity),0)  from sProcurement.tStockBatch  where OrgGroupId=@rOrgId and StockItemId=@lItemId and Id= @lbatchId
					 
				 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockResetBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockResetBatch output
				
						INsert into sProcurement.tStockResetBatch(Id,StockResetId,Quantity,StockBatchId,OrgGroupId,UnitCost)
						Select @lNextNumberStockResetBatch,@lNextNumberStockReset,ResetQuantity,@lbatchId,@rOrgGroupId,ResetValue
						from @tStockResetDetailBatch where Id=@lcount
			 
			 if(@lAvaliableStock > @lResetQty)
					BEGIN	
					--out Stock
						
						set @lMainQty = @lAvaliableStock - @lResetQty
						Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=2028,@rSourceId=@lNextNumberStockResetBatch,
								@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lMainQty ,@rValue=@lResetValue,@rIsReceipt=0,
								@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId
								,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname ,@rOrgId=@rOrgId
							   ,@rPhysicalQuantity = @lResetQty	
							   
				    END
				    else
				    BEGIN	
				    -- in stock
				    
						set @lMainQty = @lResetQty - @lAvaliableStock 
				    Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=2028,@rSourceId=@lNextNumberStockResetBatch,
								@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lMainQty ,@rValue=@lResetValue,@rIsReceipt=1,
								@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId 
								,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname,@rOrgId=@rOrgId
								,@rPhysicalQuantity = @lResetQty
				    END
								
						 
			 END
			set @lcount =@lcount-1
		END
		
		SELECT 1 AS RESULT , @rNumber as Number,@lNextNumberStockReset as Id
		 COMMIT TRANSACTION
        END TRY
         
        BEGIN CATCH
        IF @@TRANCOUNT > 0  
		ROLLBACK TRANSACTION
		 
		SELECT -1 AS RESULT , @rNumber as Number,@lNextNumberStockReset as Id
	    END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sProcurement].[pStockResetDetailGet]
	@rOrgGRoupId smallint,
	@rId [bigint] = 0,
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
 
SELECT		SIDe.Id,
			SIDe.StockResetId,
			SB.StockItemId,			
			SIM.Code				AS StockItemCode,
			SIM.Title				AS StockItemName,
			SUMa.Code				AS UOM,
			SIM.IsBatchWiseTracking ,
			ISNULL(SIDe.Id,0) As StockResetBatchId,
			ISNULL(SIDe.StockBatchId,0) AS StockBatchId,
			SIDe.Quantity AS ResetQuantity,
			ISNULL(SIDe.UnitCost,0) AS ResetValue,
			SB.Number AS 'Batch No',
			ISNULL(SB.ExpiryDate,'') AS ExpiryDate,
			ISNULL(SB.AvailableQuantity,0) As AvailableQuantity 

FROM		sProcurement.tStockResetBatch SIDe
INNER JOIN	sProcurement.tStockReset SI
			ON SI.Id = SIDe.StockResetId
INNER JOIN	sProcurement.tStockBatch SB
			ON SB.Id = SIDe.StockBatchId 
INNER JOIN	sIp.tStockItemMaster SIM
			ON SIM.Id = SB.StockItemId 	
INNER JOIN  sFinanceCommon.tStockUomMaster SUMa
 			ON SUMa.Id = SIM.IssueStockUomId			
		 
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGRoupId

 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockResetGet]
	@rOrgGroupId smallint,
	@rId bigint = 0,
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
SELECT		SI.Id,
			SI.Number,
			SI.ResetByName,
			SI.ToStoreLocationId,			
			SI.Remark,
			SI.CreatedUserId			AS UserId,
			case when SI.TransactionDate is not null then SI.TransactionDate else  SI.CreatedDateTime end AS ResetDate,
			SLM.Code					AS ToStoreLocationCode,
			SI.CreatedDateTime as 'TranjectionDate'
			
FROM		sProcurement.tStockReset SI
INNER JOIN	sIp.tStoreLocationMaster SLM
			ON SLM.Id = SI.ToStoreLocationId 		
			
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId





SELECT	SIB.Id,			
			SIB.StockBatchId,
			SIB.Quantity,
			SB.Number,
			ISNULL(SB.ExpiryDate,'') AS ExpiryDate, 
			SB.AvailableQuantity
			
			
			
FROM		sProcurement.tStockResetBatch SIB
INNER JOIN	sProcurement.tStockReset SI
			ON SI.Id = SIB.StockResetId
INNER JOIN	sProcurement.tStockBatch SB
			ON SB.Id = SIB.StockBatchId
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sProcurement].[pStockStatusBatchGet]
	@rOrgGroupId [int],	
	 
	 
	@rStockItemCode [nvarchar](20) = '',
	@rStockItemName [nvarchar](50) = '',
	@rLocationId int =0,
	@rStorelocation int=0, 
	@rMainGroup int=0,
	@rSubGroup int=0,
	@rItemCatagory int=0,
	@rBatch nvarchar(50),
	@rDate date=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
      SET @rStockItemName = sCommon.fSearchStringGet(@rStockItemName)
      SET @rStockItemCode = sCommon.fSearchStringGet(@rStockItemCode)
      
	 SELECT distinct SB.StoreLocationId AS DepartmentId,
			SB.StockItemId,
			SIM.Code AS StockItemCode,
			SIM.Title AS StockItemName,
			ISNULL( SB.AvailableQuantity  , 0) AS Quantity,
			ISNULL(SIP.MaximumInventory,0) AS MaximumInventory,
			ISNULL(SIP.ReOrderPoint,0) AS ReOrderPoint ,
			ISNULL(SIP.SafetyStock,0) AS SafetyStock,
			ISNULL(SLM.Title,'') AS StoreLocationName,	
			SUOM.Title AS UOM,
			 
			 ISNULL(SB.ExpiryDate,'') AS ExpiryDate,
			--ISNULL(DATEDIFF(day,GETDATE(),SB.ExpiryDate),0) AS ExpireDays 
			 ISNULL(SB.Number,'') AS BatchName,
			 SB.Id As StockBatchId,
			 SIM.IsbatchWiseTracking,
			 SB.StorelocationId,
			 SLM.Title As StoreLocation
	   FROM sIp.tStockItemMaster SIM
					INNER JOIN 	sProcurement.tStockBatch SB ON 	SIM.Id = SB.StockItemId AND SB.Number!=''
					INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId
					INNER JOIN 	sIp.tStoreLocationMaster SLM
					ON	SLM.Id = SB.StoreLocationId
					
					--INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id
					 INNER JOIN sIp.tStockItemPlanning SIP ON SIM.Id = SIP.StockItemId  AND SIP.StoreLocationId =SLM.Id
						INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
					INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
					
	  WHERE ((SLM.LocationId = @rLocationId) OR (@rLocationId = 0))
				AND ((SLM.Id = @rStorelocation) OR (@rStorelocation = 0))
				 
				--AND (ISNULL(SIM.Code,'') IN (SELECT item FROM  sCommon.fnsplit(@rStockItemCode,',')) OR @rStockItemCode='')
				AND    ((SIM.title LIKE @rStockItemName) OR (ISNULL(@rStockItemname, '') = ''))
				AND    ((SIM.Code LIKE @rStockItemCode) OR (ISNULL(@rStockItemCode, '') = ''))
				AND     SIM.OrgGroupId = @rOrgGroupId
				AND ((IMGM.Id=@rMainGroup)OR(@rMainGroup=0))
				AND ((ISGM.Id =@rSubGroup)OR (@rSubGroup=0))
				 
				 
			   AND ((SIM.StockItemCategoryId=@rItemCatagory) OR (@ritemCatagory=0))
			   AND ((SB.Number = '' + @rBatch +'') OR (@rBatch=''))
			   AND ((SB.ExpiryDate=@rDate) OR (ISNULL(@rDate,'')=''))
			
			  --and SB.AvailableQuantity > 0 and SB.Number is not null
			   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To add records to sProcurement.tStockTransfer table
	Created date     : 09 Jan 2012
	Author           : Rajendra
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Added RequestedQuantity And 654
	Test script      : EXECUTE sProcurement.pStockTransferAdd @rNumber = '', @rStockTransferRequestId = 0, @rTransferredByName = '', @rRemark = '', @rCreatedUserId = 0, @rDetail = '', @rFromStoreLocationId = 0, @rToStoreLocationId = 0
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sProcurement].[pStockTransferAdd]
	(   @rOrgGroupId						int,
		@rNumber					Nvarchar(20) = '',
		@rStockTransferRequestId	Int,
		@rTransferredByName			Nvarchar(100),
		@rFromStoreLocationId		Int,
		@rToStoreLocationId			Int,
		@rRemark					Nvarchar(300),
		@rCreatedUserId				BigInt,
		@rDetail					Nvarchar(Max)
	)
AS

SET NOCOUNT ON

BEGIN

EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 25,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

SET @rNumber = ISNULL(@rNumber, '-300')

IF @rNumber = '-300'
BEGIN

--SELECT -300 AS Result, 0 AS PrescriptionID, '' AS PrescriptionNumber
SELECT -300 AS Result, '' AS Number, 0 AS Id 
RETURN
END
IF @rStockTransferRequestId = 0
SET @rStockTransferRequestId = NULL
	DECLARE @lNextNumberStockTransfer INT 

	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockTransfer',@lNextNumber = @lNextNumberStockTransfer output

	INSERT INTO sProcurement.tStockTransfer
		(
			Id,
			Number,
			StockTransferRequestId,
			FromStoreLocationId,
			ToStoreLocationId,
			TransferredByName,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumberStockTransfer,
			@rNumber,
			@rStockTransferRequestId,
			@rFromStoreLocationId,
			@rToStoreLocationId,
			@rTransferredByName,
			@rRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
		
	DECLARE @lIntErrorCode INT, @lIntDoc INT
	EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	DECLARE @tStockTransferDetail TABLE
	(
	Id						Int IDENTITY(0, 1),
	StockTransferDetailId	Int, 
	StockTransferId 		Int, 
	StockItemId				Int, 
	TransferredQuantity		Decimal(12,2), 
	Remark					Nvarchar(300),
	RequestedQuantity		Decimal(12,2)
	)
	
	
	INSERT INTO @tStockTransferDetail  
	(  
		StockTransferId,
		StockItemId,
		TransferredQuantity,
		Remark,
		RequestedQuantity
		
	)
	SELECT	@lNextNumberStockTransfer, 
			StockItemId,
			TransferredQuantity,
			Remark,
			RequestedQuantity
			
	FROM OPENXML (@lIntDoc, '/Root/StockTransferDetail', 1)  
		WITH  
		(  
			StockItemId				Nvarchar(300)	'@StockItemId', 
			TransferredQuantity		Nvarchar(300)	'@TransferredQuantity', 
			Remark					Nvarchar(300)	'@Remark',
			RequestedQuantity		Nvarchar(300)	'@RequestedQuantity'
		) XmlTable	
	
	DECLARE @lNextNumberStockTransferDetail BigInt
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockTransferDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockTransferDetail output
	
	
	INSERT INTO sProcurement.tStockTransferDetail
		(
			Id,
			StockTransferId,
			StockItemId,
			TransferredQuantity,
			Remark,
			RequestedQuantity,
			OrgGroupId
		)
	SELECT 	@lNextNumberStockTransferDetail + Id, 
			StockTransferId, 
			StockItemId, 
			TransferredQuantity, 
			Remark,
			RequestedQuantity,
			@rOrgGroupId
	FROM	@tStockTransferDetail
	
	UPDATE @tStockTransferDetail SET StockTransferDetailId = @lNextNumberStockTransferDetail + Id 
	SELECT @lNextNumberStockTransferDetail = MAX(Id) + @lNextNumberStockTransferDetail FROM @tStockTransferDetail
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sProcurement.tStockTransferDetail', @rCurrentNumber = @lNextNumberStockTransferDetail 
	
	DECLARE @tBatch TABLE
	(
		Id						Int IDENTITY(0, 1), 
		StockTransferDetailId	Int,
		FromStockBatchId		Int,
		ToStockBatchId			Int,
		Quantity				Decimal(12,2),
		StockItemId				Int				
	)
	
	
	INSERT INTO @tBatch  
			(  
			StockTransferDetailId,	
			FromStockBatchId,
			ToStockBatchId,	
			Quantity,
			StockItemId				
			)
	SELECT	1, 
			FromStockBatchId,
			ToStockBatchId,	
			Quantity,
			StockItemId 
	FROM OPENXML (@lIntDoc, '/Root/StockTransferDetail/StockTransferBatch', 1)  
		WITH  
		(  
			FromStockBatchId 			Nvarchar(200)	'@FromStockBatchId',
			ToStockBatchId 				Nvarchar(200)	'@ToStockBatchId',
			Quantity					Nvarchar(200)	'@Quantity',
			StockItemId					Nvarchar(200)	'@StockItemId'
		) XmlTable	
		
	DECLARE @lNextNumberBatch BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockTransferBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output
	
	INSERT INTO sProcurement.tStockTransferBatch
		(
			Id,
			StockTransferDetailId,
			FromStockBatchId,
			ToStockBatchId,	
			Quantity,
			OrgGroupId
		)
	SELECT 		@lNextNumberBatch + TD.Id, 
				STD.StockTransferDetailId, 
				FromStockBatchId,
				ToStockBatchId,	
				Quantity,
				@rOrgGroupId
	FROM		@tStockTransferDetail STD 
	INNER JOIN	@tBatch TD 
				ON TD.StockItemId = STD.StockItemId
				
	SELECT @lNextNumberBatch = MAX(Id) + @lNextNumberBatch FROM @tBatch
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sProcurement.tStockTransferBatch', @rCurrentNumber = @lNextNumberBatch 
	
	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockTransfer AS Id 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To get records from sProcurement.tStockTransfer table
	Created date     : 09 Jan 2012
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Changed RequestedQuantity
	Test script      : EXECUTE sProcurement.pStockTransferGet @rID = 0, @rNumber = ''
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sProcurement].[pStockTransferGet]
	(
	    @rOrgGroupId int,
		@rId Int = 0,
		@rNumber Nvarchar(20) = ''
	)
AS

SET NOCOUNT ON

BEGIN
SELECT		ST.Id,
			ST.Number,
			ST.StockTransferRequestId,
			ST.TransferredByName,
			ST.Remark,
			ST.CreatedUserId			AS UserId,
			ST.CreatedDateTime,
			ST.FromStoreLocationId,
			ST.ToStoreLocationId,
			FSLM.Code					AS FromStoreLocationCode,
			TSLM.Code					AS ToStoreLocationCode,
			STRe.Number					AS RequestNumber,
			STRe.CreatedDateTime        AS RequestedDate,
			ST.CreatedDateTime			AS TransferredDate
FROM		sProcurement.tStockTransfer ST
INNER JOIN	sIp.tStoreLocationMaster FSLM
			ON FSLM.Id = ST.FromStoreLocationId
INNER JOIN	sIp.tStoreLocationMaster TSLM
			ON TSLM.Id = ST.ToStoreLocationId
LEFT JOIN	sProcurement.tStockTransferRequest STRe
			ON STRe.Id = ST.StockTransferRequestId
			
WHERE		((ST.Id = @rId) OR (@rId = 0))
AND			((ST.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
			AND ST.OrgGroupId = @rOrgGroupId



SELECT		STD.Id,
			STD.StockTransferId,
			STD.StockItemId,
			STD.TransferredQuantity,
			STD.Remark,
			SIM.Code				AS StockItemCode,
			SIM.Title				AS StockItemName,
			SUMa.Code				AS UOM,
			SIM.IsBatchWiseTracking,
			STD.RequestedQuantity
FROM		sProcurement.tStockTransferDetail STD
INNER JOIN	sProcurement.tStockTransfer ST
			ON ST.Id = STD.StockTransferId
INNER JOIN	sIp.tStockItemMaster SIM
			ON SIM.Id = STD.StockItemId
INNER JOIN  sFinanceCommon.tStockUomMaster SUMa
			ON SUMa.Id = SIM.IssueStockUomId
--LEFT JOIN	sProcurement.tStockTransferRequest STRe
--			ON STRe.Id = ST.StockTransferRequestId
--LEFT JOIN	sProcurement.tStockTransferRequestDetail STRD
--			ON STRD.StockTransferRequestId = STRe.Id 
--			AND STRD.StockItemId = STD.StockItemId
WHERE		((ST.Id = @rId) OR (@rId = 0))
AND			((ST.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
	AND STD.OrgGroupId = @rOrgGroupId


SELECT		STB.Id,
			STB.StockTransferDetailId,
			STB.FromStockBatchId,
			STB.ToStockBatchId,	
			STB.Quantity,
			FSB.Number,
			FSB.ExpiryDate, 
			FSB.AvailableQuantity
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 FSB
			ON FSB.Id = STB.FromStockBatchId
WHERE		((ST.Id = @rId) OR (@rId = 0))
AND			((ST.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND STB.OrgGroupId = @rOrgGroupId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/******************************************************************************
	Purpose          : To get Pending Records for Transfer/Issue Requests.
	Created date     : 13 May 2012
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : ST.Number is addedremoved
	Test script      : EXECUTE [sProcurement].[pStockTransferQueueListing] @rStatus = 'All', @rFromDate = '5/17/2009', @rToDate = '5/17/2010', @rType = 'All'
*******************************************************************************/
CREATE OR ALTER PROCEDURE [sProcurement].[pStockTransferQueueListing]
	(
	    @rOrgGroupId int,
		@rStatus Nvarchar(30) = '', 
		@rFromDate Nvarchar(100) = '1/1/2009', 
		@rToDate Nvarchar(100) = '1/1/2009', 
		@rType Nvarchar(30) = '',
		@rStoreLocationId int,
		@rToDepartmentId int=0
	)
AS

SET NOCOUNT ON
BEGIN
IF @rStatus = 'Pending'
BEGIN
	IF @rType = 'Tran'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty],
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM  
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					LEFT OUTER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					LEFT JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
		END
	IF @rType = 'Issue'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT OUTER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					WHERE
					 --SR.OrgGroupId = @rOrgGroupId AND 
					 SR.FromStoreLocationId =  @rStoreLocationId
					AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
		END
	IF @rType = 'All'
		BEGIN
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						LEFT OUTER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						LEFT JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND
						 SR.FromStoreLocationId =  @rStoreLocationId 
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND
					 SR.FromStoreLocationId =  @rStoreLocationId
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by SR.Number
		END			
	END
	
	
IF @rStatus = 'Completed'
BEGIN
	IF @rType = 'Tran'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty], 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					INNER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					INNER JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
	IF @rType = 'Issue'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND
					 SR.FromStoreLocationId =  @rStoreLocationId 
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
	IF @rType = 'All'
		BEGIN
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						INNER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						INNER JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId  
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 					
					ON SR.ToDepartmentId = LM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END			
	END
	
IF @rStatus = 'All'
BEGIN
	IF @rType = 'Tran'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty],
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM  
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					LEFT OUTER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					LEFT JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId 
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate		
		UNION ALL
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty], 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]		   
		   FROM
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					INNER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					INNER JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
	IF @rType = 'Issue'
		BEGIN
		   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT OUTER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId 
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			
			SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location],
			   ISNULL( LM.Id,0) AS DepartmentId, 
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0)
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END
		IF @rType = 'All'
		BEGIN
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   0 AS DepartmentId, 
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						LEFT OUTER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						LEFT JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
							WHERE 
							--SR.OrgGroupId = @rOrgGroupId AND 
							SR.FromStoreLocationId =  @rStoreLocationId
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId 
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location], 
			   0 AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status],
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			   --ST.Id [TransferId]
			   FROM  
					sProcurement.tStockTransferRequest SR
						INNER JOIN sProcurement.tStockTransferRequestDetail SRD
						ON SR.Id = SRD.StockTransferRequestId
						INNER JOIN sProcurement.tStockTransfer ST
						ON ST.StockTransferRequestId = SR.id
						INNER JOIN sProcurement.tStockTransferDetail STD
						ON ST.Id = STD.StockTransferId
						INNER JOIN sIp.tStoreLocationMaster LM 
						ON SR.ToStoreLocationId = LM.Id
							WHERE 
							--SR.OrgGroupId = @rOrgGroupId AND 
							SR.FromStoreLocationId =  @rStoreLocationId
						GROUP BY 
							SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, ST.Id
						HAVING 
							SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
							AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
			UNION ALL
			   SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ISNULL( LM.Id,0) AS DepartmentId,
			   ST.Number AS [TransferNo],
			   'Completed' AS [Status], 
			   SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty,
			   SR.Id [ReqId]
			  -- ST.Id [TransferId]
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					INNER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					INNER JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
						WHERE 
						--SR.OrgGroupId = @rOrgGroupId AND 
						SR.FromStoreLocationId =  @rStoreLocationId
						 AND (SR.ToDepartmentId= @rToDepartmentId OR @rToDepartmentId =0 )
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title,LM.Id, ST.Number, SR.Id, ST.Id
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.CreatedDateTime BETWEEN @rFromDate AND @rToDate
						Order by  SR.Id,SR.Number
		END		
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockTransferQueueListingItmesGet]
	@rOrgGroupId [int],
	@rType [nvarchar](30) = '',
	@rId [int] = 0,
	 @rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF @rType = 'Tran'
BEGIN
SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status],
			   IM.Title [ItemName],
			   SRD.RequestedQuantity[RequestedQuantity],
			   ISNULL(STD.TransferredQuantity, 0) [TransferredQuantity], 
			   ISNULL(SRD.RequestedQuantity, 0) - ISNULL(STD.TransferredQuantity, 0) AS [PendingQty], 
			   --SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty],
			   SR.Id [ReqId]
		   FROM  
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					LEFT OUTER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					LEFT JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
					INNER JOIN sIp.tStockItemMaster IM
					ON SRD.StockItemId = IM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND
					 SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, IM.Title, SRD.RequestedQuantity, STD.TransferredQuantity
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) > 0
						AND SR.Id = @rId
		UNION ALL
			SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Tran'AS [Type], 
			   LM.Title AS [Location],
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status],
			   IM.Title [ItemName],
			   SRD.RequestedQuantity[RequestedQuantity],
			   ISNULL(STD.TransferredQuantity, 0) [TransferredQuantity], 
			   ISNULL(SRD.RequestedQuantity, 0) - ISNULL(STD.TransferredQuantity, 0) AS [PendingQty], 
			   --SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) AS [PendingQty],
			   SR.Id [ReqId]
		   FROM  
				sProcurement.tStockTransferRequest SR
					INNER JOIN sProcurement.tStockTransferRequestDetail SRD
					ON SR.Id = SRD.StockTransferRequestId
					LEFT OUTER JOIN sProcurement.tStockTransfer ST
					ON ST.StockTransferRequestId = SR.id
					LEFT JOIN sProcurement.tStockTransferDetail STD
					ON ST.Id = STD.StockTransferId
					INNER JOIN sIp.tStoreLocationMaster LM 
					ON SR.ToStoreLocationId = LM.Id
					INNER JOIN sIp.tStockItemMaster IM
					ON SRD.StockItemId = IM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, IM.Title, SRD.RequestedQuantity, STD.TransferredQuantity
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.TransferredQuantity, 0)) <= 0
						AND SR.Id = @rId
				
END
ELSE
BEGIN
		SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   IM.Title [ItemName],
			   SRD.RequestedQuantity[RequestedQuantity],
			   ISNULL(STD.IssuedQuantity, 0)[TransferredQuantity], 
			   ISNULL(SRD.RequestedQuantity, 0) - ISNULL(STD.IssuedQuantity, 0) AS [PendingQty], 
			   --SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]			   
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT OUTER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					INNER JOIN sIp.tStockItemMaster IM
					ON SRD.StockItemId = IM.Id
					WHERE 
					--SR.OrgGroupId = @rOrgGroupId AND
					 SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, IM.Title, SRD.RequestedQuantity, STD.IssuedQuantity 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) > 0
						AND SR.Id = @rId
			UNION ALL
				SELECT 
			   SR.Number AS [RequestNo],  
			   SR.CreatedDateTime AS [RequestDate],  
			   SR.RequestedByName AS [RequestedBy], 
			   'Issue'AS [Type], 
			   ISNULL(LM.Title,'') AS [Location], 
			   ST.Number AS [TransferNo],
			   'Pending' AS [Status], 
			   IM.Title [ItemName],
			   SRD.RequestedQuantity[RequestedQuantity],
			   ISNULL(STD.IssuedQuantity, 0)[TransferredQuantity], 
			   ISNULL(SRD.RequestedQuantity, 0) - ISNULL(STD.IssuedQuantity, 0) AS [PendingQty], 
			   --SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) AS PendingQty, 
			   SR.Id [ReqId]			   
		   FROM  
				sProcurement.tStockIssueRequest SR
					INNER JOIN sProcurement.tStockIssueRequestDetail SRD
					ON SR.Id = SRD.StockIssueRequestId
					LEFT OUTER JOIN sProcurement.tStockIssue ST
					ON ST.StockIssueRequestId = SR.id
					LEFT JOIN sProcurement.tStockIssueDetail STD
					ON ST.Id = STD.StockIssueId
					LEFT JOIN sSetup.tDepartmentMaster LM 
					ON SR.ToDepartmentId = LM.Id
					INNER JOIN sIp.tStockItemMaster IM
					ON SRD.StockItemId = IM.Id
					WHERE 
					SR.OrgGroupId = @rOrgGroupId AND 
					SR.FromStoreLocationId =  @rStoreLocationId
					GROUP BY 
						SR.Number, SR.CreatedDateTime, SR.RequestedByName, LM.Title, ST.Number, SR.Id, IM.Title, SRD.RequestedQuantity, STD.IssuedQuantity 
					HAVING 
						SUM(ISNULL(SRD.RequestedQuantity, 0)) - SUM(ISNULL(STD.IssuedQuantity, 0)) <= 0
						AND SR.Id = @rId
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockTransferRequestAdd]
	
	@rOrgGroupId [int],
	@rFromStoreLocationId [int],
	@rToStoreLocationId [int],
	@rStoreLocationId int = 0,
	@rRequestedByName [nvarchar](100),
	@rCreatedUserId [bigint],
	@rStockTransferRequestXml [nvarchar](max),
	@rId [int] OUTPUT
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockTransferRequest',@lNextNumber = @lNextNumber output
	
	DECLARE @loNextNumber nVarchar(20)
	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 23,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber = @loNextNumber OUTPUT
	  
	IF (@loNextNumber IS NULL)
		BEGIN
			RAISERROR('5000', 15, 106)
			RETURN
		END 

	INSERT INTO sProcurement.tStockTransferRequest
		(
			Id,
			Number,
			FromStoreLocationId,
			ToStoreLocationId,
			RequestedByName,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@loNextNumber,
			@rFromStoreLocationId,
			@rToStoreLocationId,
			@rRequestedByName,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
	SET @rId = @lNextNumber
	EXEC [sProcurement].[pStockTransferRequestDetailAdd] @rOrgGroupId, @lNextNumber, @rStockTransferRequestXml
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockTransferRequestDetailAdd]
	@rOrgGroupId [int],
	@rStockTransferRequestId [bigint],
	@rStockTransferRequestXml [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loIdoc INT
	DECLARE @lStockTransferRequestDetailCurrentId INT
	DECLARE @lCount INT
		
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockTransferRequestXml
 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockTransferRequestDetail',@lNextNumber = @lStockTransferRequestDetailCurrentId output

	INSERT INTO sProcurement.tStockTransferRequestDetail
		(
			Id,
			StockTransferRequestId,
			StockItemId,
			RequestedQuantity,
			Remark,
			OrgGroupId
		)
	SELECT  
		@lStockTransferRequestDetailCurrentId + ROW_NUMBER() OVER(ORDER BY StockItemId) AS Id, 
		@rStockTransferRequestId,
		StockItemId,
		RequestedQuantity,
		Remark,
		@rOrgGroupId
	FROM OPENXML (@loIdoc, '/StockTransferRequest/StockTransferRequestDetail', 1)
		WITH ( 
				StockItemId INT, 
				RequestedQuantity DECIMAL(22, 6), 
				Remark NVARCHAR(300)
			  ) 
	SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockTransferRequest/StockTransferRequestDetail', 1)
				 WITH ( StockItemId INT)
	SET @lStockTransferRequestDetailCurrentId  = @lCount + @lStockTransferRequestDetailCurrentId 
		
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockTransferRequestDetail', @rCurrentNumber = @lStockTransferRequestDetailCurrentId 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockTransferRequestDetailGet]
	@rOrgGroupId [int],
	@rStockTransferRequestId [bigint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT STRD.Id,
			STRD.StockTransferRequestId,
			STRD.StockItemId,
			STRD.RequestedQuantity,
			STRD.Remark,
			SIM.Code ItemCode,
			SIM.Title ItemTitle,
			SU.Code UomCode,
			SU.Title UomTitle,
			SU.Id IssueStockUomId,
			SIM.IsBatchWiseTracking
	   FROM 
			sProcurement.tStockTransferRequestDetail STRD
	   INNER JOIN 
			sIP.tStockItemMaster SIM
		ON
			SIM.Id = STRD.StockItemId
		INNER JOIN
			sFinanceCommon.tStockUomMaster  SU
		ON
			SU.Id = SIM.IssueStockUomId
	  WHERE ((STRD.StockTransferRequestId = @rStockTransferRequestId) OR (@rStockTransferRequestId = 0))
	  AND STRD.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockTransferRequestGet]
	@rOrgId [int], 
	@rId [int] = 0,
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--Commented on 19/06/2025 - Invalid column name 'OrgId'.
	 --SELECT Id,
		--	Number,
		--	FromStoreLocationId,
		--	ToStoreLocationId,
		--	RequestedByName,
		--	Remark,
		--	CreatedDateTime
	 --  FROM sProcurement.tStockTransferRequest
	 -- WHERE ((Id = @rId) OR (@rId = 0))
	 -- AND OrgId = @rOrgId
	 --AND ((FromStoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	  
	 -- EXEC [sProcurement].[pStockTransferRequestDetailGet] @rOrgId, @rId
	 SELECT 0 AS Id,
			0 AS Number,
			0 AS FromStoreLocationId,
			0 AS ToStoreLocationId,
			0 AS RequestedByName,
			0 AS Remark,
			0 AS CreatedDateTime
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockTransferRequestIdGet]
	@rOrgGroupId [int], 
	@rStockTransferRequestNumber [nvarchar](30),
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		SELECT
				ID
		FROM
		sProcurement.tStockTransferRequest
		WHERE Number = @rStockTransferRequestNumber
		AND OrgGroupId = @rOrgGroupId 
		AND FromStoreLocationId = @rStoreLocationId
				
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockVerificationAdd]
	@rOrgId int,
	@rStockVerificationDataXML [nvarchar](max),
	@rIdList [nvarchar](100) OUTPUT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @loIdoc INT
	DECLARE @lNextNumber BIGINT
	DECLARE @lCnextNumber BIGINT
	DECLARE @lCount BIGINT 
	DECLARE @lStockVerificationId BIGINT
	
	CREATE TABLE #tStockVerificationId
	(
		StockVerificationId BIGINT,
		ItemMainGroupId VARCHAR(20) 
	)
		
	SET @lCount = 0
	SET @rIdList = ''
	
	EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockVerificationDataXML
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockVerification', 1, 1, 1,@outNextNumber = @lNextNumber output
	SET @lCnextNumber = @lNextNumber
	--SET @rIdList = @lNextNumber + 1 
	INSERT INTO sProcurement.tStockVerification
		(
			Id,
			StockItemFreezeId,
			StockBatchId,
			SystemQuantity,
			PhysicalQuantity,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
SELECT  
		@lNextNumber + ROW_NUMBER() OVER(ORDER BY StockItemFreezeId) AS Id, 
		StockItemFreezeId,
		StockBatchId,
		SystemQuantity,
		PhysicalQuantity,
		IsObsolete,
		CreatedUserId,
		sCommon.fGetDate(),
		UpdatedUserId,
		sCommon.fGetDate(),
		@rOrgId
		
	FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationDetail', 1)
		WITH ( 
				StockVerificationId BIGINT,
				StockItemFreezeId BIGINT, 
				StockBatchId DECIMAL(22, 6), 
				SystemQuantity DECIMAL(22, 6),
				PhysicalQuantity DECIMAL(22, 6),
				IsObsolete Bit,
				CreatedUserId BIGINT,
				UpdatedUserId BIGINT
			  ) WHERE StockVerificationId = 0
		
		--PRINT @lNextNumber
		SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationDetail', 1)
				 WITH ( StockVerificationId BIGINT, StockItemFreezeId BIGINT) WHERE StockVerificationId = 0
				
				 SET @lNextNumber  = @lCount + @lNextNumber 
				 --PRINT @lNextNumber
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sProcurement.tStockVerification', @rCurrentNumber = @lNextNumber 
		--SET @rIdList = @rIdList + ':' + CAST (@lNextNumber AS VARCHAR(10)) 
		
		--PRINT @rIdList
		EXEC [sProcurement].[pStockVerificationModify] @rOrgId, @rStockVerificationDataXML--, @rIdList
		
		INSERT INTO #tStockVerificationId
		(StockVerificationId, ItemMainGroupId)
		SELECT ID, ItemMainGroupId FROM
		
		(SELECT @lCnextNumber + ROW_NUMBER() OVER(ORDER BY StockItemFreezeId)  AS Id, ItemMainGroupId AS ItemMainGroupId 
		FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationDetail', 1)
		WITH ( 
				StockVerificationId BIGINT,
				ItemMainGroupId VARCHAR(20),
				StockItemFreezeId BIGINT) WHERE StockVerificationId = 0
		UNION ALL 
		SELECT StockVerificationId AS Id, ItemMainGroupId AS ItemMainGroupId
		FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationDetail', 1)
		WITH ( 
				StockVerificationId BIGINT,
				ItemMainGroupId VARCHAR(20),
				StockItemFreezeId BIGINT) WHERE StockVerificationId > 0) T1
			
		SELECT 	@lCount = COUNT(1) FROM #tStockVerificationId
		WHILE (@lCount <> 0)
			BEGIN
				SELECT TOP 1 @lStockVerificationId = StockVerificationId FROM #tStockVerificationId  ORDER BY StockVerificationId
				SET @rIdList = @rIdList + ':' + CAST(@lStockVerificationId AS NVARCHAR(50))
				SET @rIdList = @rIdList + ':'
				DELETE #tStockVerificationId WHERE StockVerificationId IN (SELECT TOP 1  StockVerificationId FROM #tStockVerificationId  ORDER BY StockVerificationId)
				SELECT @lCount = COUNT(1) FROM #tStockVerificationId
			END
		SELECT 	@lCount = COUNT(1) FROM #tStockVerificationId
		WHILE (@lCount <> 0)
			BEGIN
				
				SET @rIdList = @rIdList + '#' + (SELECT TOP 1  ItemMainGroupId FROM #tStockVerificationId  ORDER BY ItemMainGroupId)
				SET @rIdList = @rIdList + '#'
				DELETE #tStockVerificationId WHERE ItemMainGroupId IN (SELECT TOP 1  ItemMainGroupId FROM #tStockVerificationId  ORDER BY ItemMainGroupId)
				SELECT @lCount = COUNT(1) FROM #tStockVerificationId
			END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockVerificationApprovalAdd]
	@rOrgId [int],
	@rStockVerificationDataXML [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

      DECLARE @loIdoc INT
      DECLARE @lNextNumber BIGINT
      DECLARE @lCount BIGINT 
      CREATE TABLE #temp (StockVerificationId BIGINT, ApprovalQuantity DECIMAL(22, 6))
      
      SET @lCount = 0

      EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockVerificationDataXML
      EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockVerificationApproval', 0, 1, 1,@outNextNumber = @lNextNumber output

      INSERT INTO sProcurement.tStockVerificationApproval
            (
                  Id,
                  StockVerificationId,
                  ApprovedQuantity,
                  CreatedUserId,
                  CreatedDateTime,
                  UpdatedUserId,
                  UpdatedDateTime,
                  OrgId
            )
      SELECT            
                  @lNextNumber + ROW_NUMBER() OVER(ORDER BY StockVerificationId) AS Id, 
                  StockVerificationId,
                  ApprovalQuantity,
                  CreatedUserId,
                  sCommon.fGetDate(),
                  CreatedUserId,
                  sCommon.fGetDate(),
                  @rOrgId
      FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationApproval', 1)
            WITH ( 
                        StockVerificationId BIGINT, 
                        ApprovalQuantity DECIMAL(22, 6),
                        CreatedUserId BIGINT,
                        UpdatedUserId BIGINT
                    ) 
                    
                  
            SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationApproval', 1)
                        WITH ( StockVerificationId BIGINT)
                        
                         SET @lNextNumber  = @lCount + @lNextNumber 
            
            EXECUTE sCommon.pTableRowIdModify @rOrgId = @rOrgId, @rTableTitle = 'sProcurement.tStockVerificationApproval', @rCurrentNumber = @lNextNumber 
            
            INSERT INTO #temp
                              SELECT
                                      StockVerificationId AS StockVerificationId,
                                      ApprovalQuantity AS ApprovalQuantity
                                       
                                     
                              FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationApproval', 1)
                              WITH ( 
                                          Id BIGINT, 
                                          StockVerificationId BIGINT, 
                                          ApprovalQuantity DECIMAL(22, 6)
                                               
                                      ) 
                                      
                                     
                                      SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationDetail', 1)
                                      WITH ( StockVerificationId BIGINT)   
                                      
                                      
                                      --SELECT * FROM #Temp
                                      
                                      --UPDATE sProcurement.tStockBatch 
                                      --SET SB.AvailableQuantity = #Temp.ApprovalQuantity 
                                      --WHERE ID IN (
                                      --SELECT StockBatchId FROM sProcurement.tStockVerification WHERE ID IN (
                                      --SELECT StockVerificationId FROM #Temp))
                                      
                                      --UPDATE SB 
                                      --SET SB.AvailableQuantity = #temp.ApprovalQuantity 
                                      --FROM sProcurement.tStockVerification SV INNER JOIN #temp ON SV.Id = #temp.StockVerificationId
                                      --INNER JOIN sProcurement.tStockBatch  SB ON SV.StockBatchId = SB.Id AND SV.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockVerificationApprovalGet]
	@rOrgId [int],
	@rStoreLocationId [int],
	@rItemMainGroupId [int],
	@rItemName [nvarchar](100) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN	 
	 SELECT 
			CASE WHEN SVA.Id IS NULL
			THEN 0 ELSE SVA.Id END AS Id, 
			SV.Id StockVerificationDetailId,
			SF.Id StockItemFreezeId,
			SB.Id StockBatchId,
			SB.Number AS BatchNo,
			SB.AvailableQuantity AS SystemQuantity,
			CASE WHEN SV.PhysicalQuantity IS NULL
			THEN 0 ELSE SV.PhysicalQuantity END AS PhysicalQuantity,
			CASE WHEN SVA.ApprovedQuantity IS NULL
			THEN SV.PhysicalQuantity ELSE SVA.ApprovedQuantity END AS ApprovedQuantity,
			(SV.PhysicalQuantity - SB.AvailableQuantity) AS VarianceQuantity, 
			SF.CreatedUserId,
			SF.CreatedDateTime,
			SV.UpdatedUserId,
			SV.UpdatedDateTime,
			SF.StoreLocationId,
			SLM.Title AS Location,
			SB.ExpiryDate,
			SIM.Id AS ItemId, 
			SIM.Title AS ItemName,
			SIM.Code AS ItemCode,
			IMGM.Title AS ItemType,
			SUoM.Title AS UOM,
			SIM.IsObsolete,
			SB.ExpiryDate
			
 
		 FROM sProcurement.tStockVerification SV
		 INNER JOIN sProcurement.tStockBatch SB 
		 ON SV.StockBatchId  = SB.Id AND SB.AvailableQuantity <> 0 AND ((CAST(SB.ExpiryDate AS DATE) >= CAST(sCommon.fGetDate() AS DATE)) OR SB.ExpiryDate IS NULL)
		 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 sFinanceCommon.tStockUomMaster SUOM
		 ON SIM.IssueStockUomId = SUOM.Id
		 INNER JOIN sProcurement.tStockItemFreeze SF
		 ON SV.StockItemFreezeId = SF.Id
		 LEFT JOIN sProcurement.tStockVerificationApproval SVA
		 ON SVA.StockVerificationId = SV.Id
		 INNER JOIN sIp.tStoreLocationMaster SLM
		 ON  SF.StoreLocationId = SLM.Id
	    
	  WHERE (SF.StoreLocationId = @rStoreLocationId)
		AND ((IMGM.Id = @rItemMainGroupId) OR (@rItemMainGroupId = 0)) 
		AND ((SIM.Title = @rItemName) OR (ISNULL(@rItemName, '') = ''))		
		AND SV.OrgId = @rOrgId
		AND SV.IsObsolete = 0
		ORDER BY SV.Id
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockVerificationApprovalModify]
	@rOrgId [int],
	@rStockVerificationDataXML [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN         
            DECLARE @loIdoc INT                       
            EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockVerificationDataXML
            DECLARE @lCount INT 
                  
            SET @lCount = 0
            
            CREATE TABLE #temp (StockVerificationId BIGINT, ApprovalQuantity DECIMAL(22, 6))
            
            UPDATE SVA
            SET SVA.ApprovedQuantity = d.ApprovalQuantity,
            SVA.UpdatedUserId = d.CreatedUserId, 
            SVA.UpdatedDateTime = d.UpdatedDateTime
            
           
            FROM sProcurement.tStockVerificationApproval SVA  
            JOIN
            (
            SELECT
                  Id AS Id, 
                  StockVerificationId AS StockVerificationId,
                  ApprovalQuantity AS ApprovalQuantity, 
                  CreatedUserId AS CreatedUserId, 
                  sCommon.fGetDate() AS UpdatedDateTime
            FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationApproval', 1)
            WITH ( 
                        Id BIGINT, 
                        StockVerificationId BIGINT, 
                        ApprovalQuantity DECIMAL(22, 6),
                        CreatedUserId BIGINT                   
                    ) 
            ) d
            ON (SVA.Id = d.Id)
            
            
            SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationDetail', 1)
            WITH ( StockVerificationId BIGINT)     
            
            
            
            
            
             
            --UPDATE SB
            --SET SB.AvailableQuantity = P.ApprovalQuantity
            --JOIN
            --(
            --SELECT StockBatchId
            --FROM sProcurement.tStockBatch SB
            -- JOIN
            --(      
                       
            --) P
            --ON (SB.Id = P.StockBatchId) 
            --SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationDetail', 1)
            --WITH ( StockVId INT)  
            
                              --DECLARE @Temp TABLE (StockVerificationId INT, ApprovalQuantity DECIMAL(22, 6))
                              INSERT INTO #temp
                              SELECT
                                      StockVerificationId AS StockVerificationId,
                                      ApprovalQuantity AS ApprovalQuantity
                                       
                                     
                              FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationApproval', 1)
                              WITH ( 
                                          Id BIGINT, 
                                          StockVerificationId BIGINT, 
                                          ApprovalQuantity DECIMAL(22, 6)
                                               
                                      ) 
                                      
                                     
                                      SELECT @lCount = COUNT(1) FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationDetail', 1)
                                      WITH ( StockVerificationId BIGINT)   
                                      
                                      
                                      --SELECT * FROM #Temp
                                      
                                      --UPDATE sProcurement.tStockBatch 
                                      --SET SB.AvailableQuantity = #Temp.ApprovalQuantity 
                                      --WHERE ID IN (
                                      --SELECT StockBatchId FROM sProcurement.tStockVerification WHERE ID IN (
                                      --SELECT StockVerificationId FROM #Temp))
                                      
                                      UPDATE SB 
                                      SET SB.AvailableQuantity = #temp.ApprovalQuantity 
                                      FROM sProcurement.tStockVerification SV INNER JOIN #temp ON SV.Id = #temp.StockVerificationId
                                      INNER JOIN sProcurement.tStockBatch  SB ON SV.StockBatchId = SB.Id  WHERE SV.OrgId  = @rOrgId
                                      
                                      --UPDATE sProcurement.tStockBatch 
                                      --SET SB.AvailableQuantity = 0
                                      --FROM 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockVerificationModify]
	@rOrgId int,
	@rStockVerificationDataXML [nvarchar](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

		DECLARE @loIdoc INT
		--SET @rIdList = ''
		--DECLARE @tempIdtable TABLE (item VARCHAR(8000))
		--DECLARE @tempIdtableItemType TABLE (item VARCHAR(8000))
		--DECLARE @tempIdtableStockVerification TABLE (item VARCHAR(8000))
		DECLARE @lCount INT 
	
		
		--SET @lCount = 0
		 
		
		EXEC sp_xml_preparedocument @loIdoc OUTPUT, @rStockVerificationDataXML
		
		UPDATE SV
		SET SV.PhysicalQuantity = d.PhysicalQuantity
		FROM sProcurement.tStockVerification SV
		JOIN
		(
		 SELECT StockVerificationId AS StockVerificationId, StockItemFreezeId AS StockItemFreezeId, StockBatchId AS StockBatchId, PhysicalQuantity AS PhysicalQuantity 
		 FROM OPENXML (@loIdoc, '/StockVerification/StockVerificationDetail', 1)
				WITH ( 
						StockVerificationId BIGINT,
						StockItemFreezeId BIGINT,
						StockBatchId INT,
						PhysicalQuantity DECIMAL(22, 6)
					  ) WHERE StockVerificationId > 0
		) d
		ON (SV.Id = d.StockVerificationId) 
		
		
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pStockXcGet]
	@rItemTypeId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
     BEGIN
     BEGIN TRY
		   BEGIN TRANSACTION
		   
		UPDATE  sIP.tStoreLocationMaster SET IsObsolete = 0 WHERE ID = @rItemTypeId
		RETURN
			
		        	RAISERROR('This is a test', 16, 1)
			    UPDATE  sIP.tStoreLocationMaster SET IsObsolete = 0 WHERE ID = 2
			
             COMMIT TRANSACTION 
		END TRY
		BEGIN CATCH
		 PRINT '@@error is ' + LTRIM(str(@@error)) + '.'	
		  PRINT 'errmsg: ' + error_message()

			ROLLBACK
		END CATCH
		
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pVendorCategoryMasterAdd]
	@rOrgGroupId [int],
	@rCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--SET @rOrgId = 0

IF NOT EXISTS (SELECT 1 FROM sProcurement.tVendorCategoryMaster WHERE UPPER(Title) = UPPER(@rTitle) AND OrgGroupId = @rOrgGroupId)

BEGIN	

	DECLARE @lNextNumber INT
	 
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tVendorCategoryMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tVendorCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sProcurement.tVendorCategoryMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId
		)
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pVendorCategoryMasterGet]
	@rOrgGroupId [int],
	@rId [int] = 0,
	@rTitle [nvarchar](50) = '',
	@rIsWildCardSearch [bit] = 1,
	@rCode [nvarchar](20) = ''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--SET @rOrgId = 0

IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle) 
		END 
	 
	 SELECT VC.Id,
			VC.Code,
			VC.Title,
			VC.IsObsolete
	   FROM sProcurement.tVendorCategoryMaster VC 
	  WHERE ((VC.Id = @rId) OR (@rId = 0))
	   AND ((VC.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND ((VC.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND VC.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pVendorCategoryMasterModify]
	@rOrgGroupId [int],
	@rId [int],
	@rCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--SET @rOrgId = 0

DECLARE @lAccId Int
IF NOT EXISTS (SELECT 1 FROM sProcurement.tVendorCategoryMaster WHERE UPPER(Title) = UPPER(@rTitle)  AND Id  <> @rId AND OrgGroupId = @rOrgGroupId)
BEGIN 
	 UPDATE sProcurement.tVendorCategoryMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,		 
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE Id = @rId
	  
SELECT 1 AS RESULT
 END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pVendorCategoryMasterRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tVendorCategoryMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
	  SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pVendorMasterAdd]
	@rOrgGroupId [int],
	@rCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@rVendorCategoryId [int],
	@rLocationId int,		
	@rArea nvarchar(50) = null,
	@rCity nvarchar(50)= null,
	@rContactPersonName [nvarchar](300) = '',
	@rCountry nvarchar(50)= null,
	@rCreditDays [smallint] = 0,
	@rCreditLimit [decimal](22, 6) = null,
	@rEmail [nvarchar](100)= '',
	@rFaxNumber [nvarchar](50)= '',	
	@rPhoneNumberMobile [nvarchar](50)= '',
	@rPhoneNumberOffice [nvarchar](50)= '',	
	@rState nvarchar(50)= null,
	@rStreetFour [nvarchar](50)= '',
	@rStreetOne [nvarchar](50)= '',
	@rStreetThree [nvarchar](50)= '',
	@rStreetTwo [nvarchar](50)= '',	
	@rZipCode [nvarchar](20)= '',
	@OutVendorId int = NULL OUTPUT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF NOT EXISTS (SELECT 1 FROM sProcurement.tVendorMaster WHERE UPPER(Title) = UPPER(@rTitle) AND OrgGroupId = @rOrgGroupId AND LocationId = @rLocationId )

BEGIN	

	DECLARE @lNextNumber INT
	 
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tVendorMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tVendorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	

	INSERT INTO sProcurement.tVendorMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			Area,
			City,
			ContactPersonName,
			Country,
			CreditDays,
			CreditLimit,
			Email,
			FaxNumber,			
			PhoneNumberMobile,
			PhoneNumberOffice,			
			State,
			StreetFour,
			StreetOne,
			StreetThree,
			StreetTwo,			
			VendorCategoryId,
			ZipCode, 
		    OrgGroupId,
		    LocationId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rArea,
			@rCity,
			@rContactPersonName,
			@rCountry,
			@rCreditDays,
			CAST(@rCreditLimit AS Decimal(12, 2)),
		--	@rCreditLimit,
			@rEmail,
			@rFaxNumber,			
			@rPhoneNumberMobile,
			@rPhoneNumberOffice,			
			@rState,
			@rStreetFour,
			@rStreetOne,
			@rStreetThree,
			@rStreetTwo,		 
			@rVendorCategoryId,
			@rZipCode, 
		    @rOrgGroupId,
		    @rLocationId
		)
	SET @OutVendorId = @lNextNumber -- ADDED FOR IMPORT FUNCTIONALITY
	SELECT 1 AS RESULT
END
ELSE
 BEGIN
 SELECT -100 AS RESULT
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pVendorMasterGet]
	@rOrgGroupId [int],
	@rId [int] = 0,
	@rTitle [nvarchar](300) = '',
	@rIsWildCardSearch [bit] = 1,
	@rCode [nvarchar](20) = '',
	@rVendorCategoryId [int] = 0,
	@rStartIndex [int] = 0,
	@rPageSize [int] = 0,
	@rLocationId int=0	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN



--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 
		  
		    VM.Id,
			VM.Code,
			VM.Title,
			VM.IsObsolete,
			VM.CreatedUserId,
			VM.CreatedDateTime,
			VM.UpdatedUserId,
			VM.UpdatedDateTime,
			--VM.Area,
			--VM.City,
			VM.ContactPersonName,
			--VM.Country,
			ISNULL(VM.CreditDays, 0) CreditDays,
			ISNULL(CAST(VM.CreditLimit AS DECIMAL(18, 2)), '0') CreditLimit,
			--VM.CreditLimit,
			VM.Email,
			VM.FaxNumber,			
			VM.PhoneNumberMobile,
			VM.PhoneNumberOffice,			
			--VM.State,
			VM.StreetFour,
			VM.StreetOne,
			VM.StreetThree,
			VM.StreetTwo,			
			VM.VendorCategoryId,
			VM.ZipCode,
			VC.Title VendorCategory,
			VM.State STATETITLE,
			VM.City CITYTITLE,
			VM.Country COUNTRYTITLE,
			VM.Area Area,
			VM.LocationID
	 
					
					
	   FROM sProcurement.tVendorMaster  VM 
	   LEFT JOIN   sProcurement.tVendorCategoryMaster VC
	   ON  VM.VendorCategoryId = VC.Id  
	   --LEFT JOIN  sCommon.tStateMaster SM 
	   --ON VM.StateId = SM.Id 
	   --LEFT JOIN   sCommon.tCityMaster CM 
	   --ON VM.CityId = CM.Id 
	   --LEFT JOIN    sCommon.tAreaMaster AM 
	   --ON VM.AreaId = AM.Id 
	   --LEFT JOIN   sCommon.tCountryMaster CAM
	   --ON VM.CountryId = CAM.Id 		     
	    WHERE ((VM.Id = @rId) OR (@rId = 0))
	    AND	((VM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND ((VM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	    AND ((VM.VendorCategoryId = @rVendorCategoryId) OR (@rVendorCategoryId = 0))
	    AND  VM.OrgGroupId = @rOrgGroupId
	 AND ((VM.LocationId = @rLocationId) OR (@rLocationId = 0))
	  -- AND VM.IsObsolete = 0
	 -- ) PS
		--WHERE
	 --  PS.RowNumber >= CONVERT(varchar(9), @rStartIndex) AND PS.RowNumber <  CONVERT(varchar(9), @lUpperBound) 
	 --  ORDER BY  PS.Id DESC
	   
	 END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pVendorMasterModify]
	@rOrgGroupId [int],
	@rId [int],
	@rCode [nvarchar](20),
	@rTitle [nvarchar](300),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rArea nvarchar(50),
	@rCity nvarchar(50),
	@rContactPersonName [nvarchar](300),
	@rCountry nvarchar(50),
	@rCreditDays [smallint],
	@rCreditLimit [decimal](22, 6),
	@rEmail [nvarchar](100),
	@rFaxNumber [nvarchar](50),	
	@rPhoneNumberMobile [nvarchar](50),
	@rPhoneNumberOffice [nvarchar](50),	
	@rState nvarchar(50),
	@rStreetFour [nvarchar](50),
	@rStreetOne [nvarchar](50),
	@rStreetThree [nvarchar](50),
	@rStreetTwo [nvarchar](50),	
	@rVendorCategoryId [int],
	@rZipCode [nvarchar](20),
	@rLocationId int	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF NOT EXISTS (SELECT 1 FROM sProcurement.tVendorMaster WHERE UPPER(Title) = UPPER(@rTitle)  AND Id  <> @rId AND OrgGroupId = @rOrgGroupId AND LocationId = @rLocationId )
BEGIN
	 UPDATE sProcurement.tVendorMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			Area = @rArea,
			City = @rCity,
			ContactPersonName = @rContactPersonName,
			Country = @rCountry,
			CreditDays = @rCreditDays,
			CreditLimit = @rCreditLimit,
			Email = @rEmail,
			FaxNumber = @rFaxNumber,			
			PhoneNumberMobile = @rPhoneNumberMobile,
			PhoneNumberOffice = @rPhoneNumberOffice,			
			State = @rState,
			StreetFour = @rStreetFour,
			StreetOne = @rStreetOne,
			StreetThree = @rStreetThree,
			StreetTwo = @rStreetTwo,
			VendorCategoryId = @rVendorCategoryId,
			ZipCode = @rZipCode
	  WHERE Id = @rId
	  
SELECT 1 AS RESULT
END

ELSE

 BEGIN
	 SELECT -100 AS RESULT
 END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sProcurement].[pVendorMasterRemove]
	@rId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sProcurement.tVendorMaster
	    SET IsObsolete = 1
	  WHERE Id = @rId
	   SELECT 1 AS RESULT
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE  [sProcurement].[UpdateWacBulk]	
	
	@rStoreLocationId Bigint = 0,
	--@rItemcode varchar(50) = '' ,
	----@rWeightedAverageoldcost Decimal(18,5) =0,
	--@rWeightedAverageCost Decimal(18,5) = 0,
	@rOrgId int =0,
	@rStrXML Nvarchar (max),
	@rScreenId int = 0,
	@rCreatedUserId bigint = 0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lInterrorCode INT,
			@intDoc INT,
			@lCount Int ,
			@lItemCode nvarchar(50),
			@lWeightedAverageCost Decimal(22,6),
			@lOperationRemark NVARCHAR(100),
			@lCreatedDateTime datetime = sCommon.fGetDate()
	--BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXML

		CREATE TABLE #tempValue (
			Id int IDENTITY(1,1),
			ItemCode nVarchar (50) ,
			WeightedAverageCost Decimal(22,6));

		Insert into  #tempValue(ItemCode, WeightedAverageCost)
		Select ItemCode, WeightedAverageCost
		FROM OPENXML (@intDoc, '/Table/StockWacBulk', 1)
		WITH
		(
			ItemCode nVarchar(50) '@ItemCode',
			WeightedAverageCost Decimal(22,6) '@WeightedAverageCost'

		)
		--Select * from #tempValue
		Select @lCount =Max(Id) from #tempValue

	while (@lCount > 0)
	Begin
		Select @lItemCode = ItemCode from #tempValue where Id = @lCount
		Select @lWeightedAverageCost = WeightedAverageCost from #tempValue where Id = @lCount


		Declare @lItemId bigint = 0,@lStockItemPlanningId bigint = 0,@lStockInwardDetailId bigint = 0,@lStockBatchId bigint = 0,@llocationId bigint = 0

		Select @llocationId = LocationId from sIp.tStoreLocationMaster where Id = @rStoreLocationId and OrgGroupId=@rOrgId
		Select @lItemId =  Id from sIp.tStockItemMaster where locationId=@llocationId and code=@lItemCode and OrgGroupId = @rOrgId
		Select @lStockItemPlanningId =  Id from sIp.tStockItemPlanning where StockItemId = @lItemId 
		 
		

		select @lStockInwardDetailId = SIDE.ID from sProcurement.tStockInward SI 
		inner join sProcurement.tStockInwardDetail SIDE on SIDE.StockInwardId = SI.Id
		inner join  sProcurement.tStockInwardBatch SIB on SIB.StockInwardDetailId = SIDE.Id
		inner join sProcurement.tStockBatch SB on SB.id = SIB.StockBatchId
		Where SIDE.StockItemId=@lItemId  and SI.OrgGroupId=@rOrgId


		select @lStockBatchId = SB.ID from sProcurement.tStockInward SI 
		inner join sProcurement.tStockInwardDetail SIDE on SIDE.StockInwardId = SI.Id
		inner join  sProcurement.tStockInwardBatch SIB on SIB.StockInwardDetailId = SIDE.Id
		inner join sProcurement.tStockBatch SB on SB.id = SIB.StockBatchId
		Where SIDE.StockItemId=@lItemId  and SI.OrgGroupId=@rOrgId

		---StockItemMaster In Planning cost update 

		Update sIp.tStockItemPlanning set WeightedAverageCost=@lWeightedAverageCost  where StockItemId =@lItemId
		and Id=@lStockItemPlanningId and OrgGroupId=@rOrgId

		---Tranjection table Cost Update

		update sIp.tWeightedAverageCostLog set WeightedAverageCost=@lWeightedAverageCost 
		where ItemSourceId =@lItemId and StoreLocationId=@rStoreLocationId and OrgGroupId=@rOrgId


		---Tranjection table Value Update

		update sIp.tWeightedAverageCostLog set ClosingValue=(ClosingQuantity*WeightedAverageCost) 
		where ItemSourceId =@lItemId and StoreLocationId=@rStoreLocationId and OrgGroupId=@rOrgId


		---Stock Batch Price Update If Inward Avaliable 

		if(len(@lStockBatchId) > 0)
		Update sProcurement.tStockBatch set ItemRate=@lWeightedAverageCost where StockItemId=@lItemId
		 and id=@lStockBatchId and StoreLocationId=@rStoreLocationId and OrgGroupId=@rOrgId

		 DECLARE @ConvertedValue NVARCHAR(50)
		SET @ConvertedValue = CONVERT(NVARCHAR(50), STR(@lWeightedAverageCost, 50, 2))

		 SET @lOperationRemark =  ' Updated WAC : ' + CONVERT(Nvarchar(50),@ConvertedValue)
		 Exec sAudit.pStockOperationLogAdd @rScreenId , @lItemId, 34, 15, @lOperationRemark,
		  @rCreatedUserId,@lCreatedDateTime
		 Set @lCount = @lCount - 1;
	END
	  COMMIT TRANSACTION
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pAttachmentLogAdd]
		@rMessageId NVARCHAR(MAX),
		@rAttachment NVARCHAR(MAX)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
	    BEGIN TRANSACTION
		BEGIN TRY
			INSERT INTO sAlert.tAlertAttachmentLog VALUES (@rMessageId, @rAttachment)
	    COMMIT TRANSACTION
		END TRY
		BEGIN CATCH
		    ROLLBACK TRANSACTION
			DECLARE @ErrorMessage NVARCHAR(4000);
			DECLARE @ErrorSeverity INT;
			DECLARE @ErrorState INT;

			SELECT
			   @ErrorMessage = ERROR_MESSAGE(),
			   @ErrorSeverity = ERROR_SEVERITY(),
			   @ErrorState = ERROR_STATE();

			RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	    END CATCH
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 -- select * from sConfig.tConfigurationSetup order by CreatedDateTime desc
 -- exec [sPurchase].[pConfigurationSetupAddUpdate] 'abcdefghijklmno',2010,9911,9911000000003,9911
CREATE OR ALTER PROCEDURE [sPurchase].[pConfigurationSetupAddUpdate]

	--@rConfigurationId [int],
	@rItemValue NVARCHAR(500),
	@rSourceTypeId INT,
	@rSourceId BIGINT,
	@rCreatedUserId BIGINT,
	@rOrgId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		 DECLARE @rConfigurationId INT = 542 --for Purchase StoreLocation
		 DELETE FROM sConfig.tConfigurationSetup
		 WHERE
		 ConfigurationId  = @rConfigurationId
		 AND SourceId=@rSourceId
		 AND SourceTypeId=@rSourceTypeId

		 DECLARE @lNextNumber BIGINT

		 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sConfig.tConfigurationSetup', 0, 1, 1,@outNextNumber = @lNextNumber OUTPUT

		 IF NOT EXISTS(SELECT 1 FROM sConfig.tConfigurationSetup WHERE ConfigurationId = @rConfigurationId AND SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId)
		 BEGIN

			IF(@rItemValue!='')
			BEGIN
			INSERT INTO [sConfig].[tConfigurationSetup]
				   ([Id]
				   ,[ConfigurationId]
				   ,[ItemValue]
				   ,[sourceTypeId]
				   ,[SourceId]
				   ,[CreatedUserId]
				   ,[CreatedDateTime]
					)
			 VALUES
				   (
					@lNextNumber,
					@rConfigurationId,
					@rItemValue,
					@rSourceTypeId,
					@rSourceId,
					@rCreatedUserId,
					sCommon.fGetDate()
					)
			  END
				  SELECT @rItemValue AS result
		  END
		  ELSE
		  BEGIN
			  UPDATE sConfig.tConfigurationSetup
				  SET ItemValue = @rItemValue,
				  UpdatedUserId = @rCreatedUserId,
				  UpdatedDateTime =  sCommon.fGetDate()

			  WHERE ConfigurationId  = @rConfigurationId AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId
			  SELECT @rItemValue AS result
		  END

	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pDependentConfigurationGet]
	  @rOrgId BIGINT,
	  @rOrgGroupId INT,
	  @rUserId BIGINT,
	  @rScreenId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		  SELECT CL.Title,
		       CM.Title AS ConfigTitle,
			   CM.ItemKey,
			   CASE WHEN  CS.ItemValue IS NULL THEN CM.ItemValue  ELSE ISNULL(CS.ItemValue,0) END AS ItemValue
	      FROM sConfig.tConfigurationMaster CM
		  INNER JOIN  sConfig.tConfigurationLevelMaster CL ON CL.Id=CM.ConfigurationLevelId
		  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.ConfigurationId
		  AND  CS.SourceTypeId=(CASE  WHEN CL.Id =1 THEN 1016 WHEN cl.Id=5 THEN 2010 WHEN cL.Id=4 THEN 95   END)
		  AND  CS.SourceId=(CASE  WHEN CL.Id =1 THEN @rOrgId WHEN cl.Id=5 THEN @rOrgGroupId WHEN cL.Id=5 THEN @rUserId END)
		  WHERE  IsObsolete=0 AND ScreenId = @rScreenId
		  ORDER BY CL.Id
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pDependentFunctionalityGet]
	  @rScreenId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT ISNULL(DependentFunctionlity,'') AS DependentFunctionlity,
			   ISNULL(DependentConfiguration,'')  AS DependentConfiguration
	     FROM  sSecurity.tScreenDependency WHERE ScreenId = @rScreenId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pEmployeeMasterIdGet]
		@rMobileNotificationCode nvarchar(max),
		@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT Id FROM sHrm.tEmployeeMaster WHERE Code = @rMobileNotificationCode AND OrgId= @rOrgId AND  ISNULL(IsOtherUser,0) = 0 
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pEventSMSTemplateIdGet]
		@rOrgId INT,
		@rEventId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT SMSTemplateID FROM sAlert.tEventTemplate WHERE EventId = @rEventId AND OrgId=@rOrgId AND AlertModeId = 2
		END TRY
		BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	    END CATCH
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pEventTemplateGet]
		@rOrgId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT EventId,Template FROM sAlert.tEventTemplate WHERE IsAutoSend = 1 AND OrgId =@rOrgId AND EventId = 158
			 --AND AlertModeId in (3)
		END TRY
		BEGIN CATCH
		ROLLBACK TRANSACTION
		    SELECT -1 AS Result
	    END CATCH
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec [sPurchase].[pGetGRNReport] 991100001
CREATE OR ALTER PROCEDURE [sPurchase].[pGetGRNReport]
      @rGoodsReceivedNoteId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);
	DECLARE
	@rGRNNumber AS NVARCHAR(20),
	@rPurchaseRequestNumber AS NVARCHAR(20),
	@rPurchaseOrderNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rPODueDate AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rBillToAddress AS NVARCHAR(1000)

	    SELECT @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rPurchaseRequestNumber = ISNULL(PR.Number,''),
				@rPurchaseOrderNumber = ISNULL(PO.RefNumber,''),
				@rRequestedBy = ISNULL(GRN.RequestedBy,''),
				@rPODueDate = ISNULL(GRN.PODueDate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rBillToAddress = ISNULL(GRN.BillToAddress,'')
		FROM  [sPurchase].[tGoodsReceivedNote] GRN(NOLOCK)
			   LEFT JOIN sProcurement.tVendorMaster  VM ON GRN.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  GRN.Id = @rGoodsReceivedNoteId AND GRN.IsObsolete = 0
               AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';
	IF EXISTS (SELECT * FROM [sPurchase].[tGoodsReceivedNoteDetail] GRND
			WHERE  GRND.GoodsReceivedNoteId = @rGoodsReceivedNoteId)
    BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>PreviousGRNQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>UnitPrice</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(GRND.POQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(GRND.ReceivedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(GRND.PreviousGRNQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(GRND.UnitPrice AS NVARCHAR(20)),'')+'</td></tr>'
	    FROM   [sPurchase].[tGoodsReceivedNoteDetail] GRND (NOLOCK)
		       INNER JOIN  sPurchase.tGoodsReceivedNote GRN ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   INNER JOIN  sPurchase.tPurchaseOrder PO	ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
			   INNER JOIN  sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  GRND.GoodsReceivedNoteId = @rGoodsReceivedNoteId AND GRN.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId
    END

SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template,
		'{GRNNumber}' , @rGRNNumber),
		'{PurchaseRequestNumber}' , @rPurchaseRequestNumber),
		'{PurchaseOrderNumber}' , @rPurchaseOrderNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{Status}' , @rStatus),
		'{PODueDate}' , @rPODueDate),
		'{VendorName}' , @rVendorName),
		'{BillToAddress}' , @rBillToAddress),
		'{GoodsReceivedNoteDetails}' , ISNULL(@HTMLTable,''))

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='GRN' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec [sPurchase].[pGetIGReport] 991100001
CREATE OR ALTER PROCEDURE [sPurchase].[pGetIGReport]
      @rInvoiceGenerateId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);
	DECLARE
	@rINVNumber AS NVARCHAR(20),
	@rGRNNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rInvoiceDate AS NVARCHAR(100),
	@rInvoiceDueDate AS NVARCHAR(100),
	@rBillToAddress AS NVARCHAR(1000),
	@rShipToAddress AS NVARCHAR(1000),
	@rRemarks AS NVARCHAR(500),
	@rVendorCode AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300)

	    SELECT  @rINVNumber = ISNULL(IG.INVNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(IG.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,''),
				@rInvoiceDate = ISNULL(IG.InvoiceDate,''),
		        @rInvoiceDueDate = ISNULL(IG.InvoiceDueDate,''),
				@rBillToAddress = ISNULL(IG.BillToAddress,''),
				@rShipToAddress = ISNULL(IG.ShipToAddress,''),
		        @rRemarks = ISNULL(IG.Remarks,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,'')
		FROM   [sPurchase].[tInvoiceGenerate] IG(NOLOCK)
		       LEFT JOIN sProcurement.tVendorMaster  VM ON IG.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = IG.StatusId
			   LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = IG.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		WHERE  IG.Id = @rInvoiceGenerateId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId

    SET @HTMLTable = '';
	IF EXISTS(SELECT * FROM [sPurchase].[tInvoiceGenerateDetail] IGD
			WHERE  IGD.InvoiceGenerateId = @rInvoiceGenerateId)

	BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>AcceptedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>RejectedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReasonForRejection</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(IGD.POQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(IGD.ReceivedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(IGD.AcceptedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(IGD.RejectedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(IGD.ReasonForRejection AS NVARCHAR(300)),'')+'</td></tr>'
	    FROM   [sPurchase].[tInvoiceGenerateDetail] IGD(NOLOCK)
		       INNER JOIN  [sPurchase].[tInvoiceGenerate] IG ON IG.Id = IGD.InvoiceGenerateId AND IG.LocationId = @rStoreLocationId AND IG.OrgGroupId = @rOrgGroupId AND IG.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = IGD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  IGD.InvoiceGenerateId = @rInvoiceGenerateId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId

    END

SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template,
		'{INVNumber}' , @rINVNumber),
		'{GRNNumber}' , @rGRNNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{Status}' , @rStatus),
		'{InvoiceDate}' , @rInvoiceDate),
		'{InvoiceDueDate}' , @rInvoiceDueDate),
		'{BillToAddress}' , @rBillToAddress),
		'{ShipToAddress}' , @rShipToAddress),
		'{Remarks}' , @rRemarks),
		'{VendorCode}' , @rVendorCode),
		'{VendorName}' , @rVendorName),
		'{InvoiceGenerateDetails}' , ISNULL(@HTMLTable,''))

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='IG' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec [sPurchase].[pGetQCReport] 991100001
CREATE OR ALTER PROCEDURE [sPurchase].[pGetQCReport]
      @rQualityCheckId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);


	DECLARE
	@rQCNumber AS NVARCHAR(100),
	@rGRNNumber AS NVARCHAR(100),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rQualityCheckDetails AS NVARCHAR(100)

	    SELECT  @rQCNumber = ISNULL(QC.QCNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(QC.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,'')
		FROM   [sPurchase].[tQualityCheck] QC(NOLOCK)
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QC.StatusId
			   LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = QC.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		WHERE  QC.Id = @rQualityCheckId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';
	IF EXISTS(SELECT *  FROM [sPurchase].[tQualityCheckDetail] QCD
			WHERE QCD.QualityCheckId = @rQualityCheckId)
	BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>AcceptedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>RejectedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReasonForRejection</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(QCD.POQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.ReceivedQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.AcceptedQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.RejectedQty AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(QCD.ReasonForRejection AS NVARCHAR(100)),'')+'</td></tr>'
	    FROM   [sPurchase].[tQualityCheckDetail] QCD (NOLOCK)
		       INNER JOIN  [sPurchase].[tQualityCheck] QC ON QC.Id = QCD.QualityCheckId AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QCD.QualityCheckId = @rQualityCheckId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId
    END

SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template,
		'{QCNumber}' , @rQCNumber),
		'{GRNNumber}' , @rGRNNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{Status}' , @rStatus),
		'{QualityCheckDetails}' , ISNULL(@HTMLTable,''))

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='QC' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec [sPurchase].[pGetQRReport] 991100004
CREATE OR ALTER PROCEDURE [sPurchase].[pGetQRReport]
      @rQuotationRequestId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);

	DECLARE
	@rNumber AS NVARCHAR(20),
	@rName AS NVARCHAR(100),
	@rRFQDate AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rDescription AS NVARCHAR(300),
	@rStartDate AS NVARCHAR(100),
	@rEndDate AS NVARCHAR(100),
	@rBidOpen AS NVARCHAR(50),
	@rBidClose AS NVARCHAR(50),
	@rPersonContact AS NVARCHAR(50),
	@rEmail AS NVARCHAR(50),
	@rSendToVendor AS NVARCHAR(10),
	@rVendorCode AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rPurchaseNumber AS NVARCHAR(20)

	    SELECT  @rNumber = ISNULL(QR.Number,''),
		        @rName = ISNULL(QR.Name,''),
				@rRFQDate = ISNULL(QR.RFQDate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rDescription = ISNULL(QR.Description,''),
		        @rStartDate = ISNULL(QR.StartDate,''),
				@rEndDate = ISNULL(QR.EndDate,''),
				@rBidOpen = ISNULL(QR.BidOpen,''),
		        @rBidClose = ISNULL(QR.BidClose,''),
				@rPersonContact = ISNULL(QR.PersonContact,''),
				@rEmail = ISNULL(QR.Email,''),
		        @rSendToVendor = ISNULL(QR.SendToVendor,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rPurchaseNumber = ISNULL(PR.Number,'')
		FROM   [sPurchase].[tQuotationRequest] QR(NOLOCK)
		       LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = QR.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';

	IF EXISTS(SELECT * FROM  [sPurchase].[tQuotationRequestDetail] QRD
			WHERE  QRD.QuotationRequestId = @rQuotationRequestId)
	BEGIN
		SET @HTMLTable = @HTMLTable + '<tr>';
		SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
		SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
		SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
		SET @HTMLTable = @HTMLTable + '<th>RequestedQty</th>';
		SET @HTMLTable = @HTMLTable + '<th>TargetPrice</th>';
		SET @HTMLTable = @HTMLTable + '<th>Remark</th>';
		SET @HTMLTable = @HTMLTable + '</tr>';

		SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
	+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(QRD.RequestedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(QRD.TargetPrice AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(QRD.Remark AS NVARCHAR(300)),'')+'</td></tr>'
			FROM   [sPurchase].[tQuotationRequestDetail] QRD(NOLOCK)
			       INNER JOIN [sPurchase].[tQuotationRequest] QR ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
				   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
				   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
			WHERE  QRD.QuotationRequestId = @rQuotationRequestId AND QR.IsObsolete = 0
			       AND QR.LocationId = @rStoreLocationId
			       AND QR.OrgGroupId = @rOrgGroupId
	END


SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template,
		'{Number}' , @rNumber),
		'{Name}' , @rName),
		'{RFQDate}' , @rRFQDate),
		'{Status}' , @rStatus),
		'{Description}' , @rDescription),
		'{StartDate}' , @rStartDate),
		'{EndDate}' , @rEndDate),
		'{BidOpen}' , @rBidOpen),
		'{BidClose}' , @rBidClose),
		'{PersonContact}' , @rPersonContact),
		'{Email}' , @rEmail),
		'{SendToVendor}' , @rSendToVendor),
		'{VendorCode}' , @rVendorCode),
		'{VendorName}' , @rVendorName),
		'{PurchaseNumber}' , @rPurchaseNumber),
		'{QuotationRequestDetails}' , ISNULL(@HTMLTable,''))

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='QR' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- select * from sPurchase.tPurchaseReportTemplate where id=6
-- exec [sPurchase].[pGetSRReport] 991100001
CREATE OR ALTER PROCEDURE [sPurchase].[pGetSRReport]
      @rSalesReturnId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);


	DECLARE
	@rSRNumber AS NVARCHAR(20),
	@rGRNNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rPurchaseOrderNumber AS NVARCHAR(20)

	    SELECT  @rSRNumber = ISNULL(SR.SRNumber,''),
		        @rGRNNumber = ISNULL(GRN.GRNNumber,''),
				@rRequestedBy = ISNULL(SR.RequestedBy,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rPurchaseOrderNumber = ISNULL(PO.RefNumber,'')
		FROM   [sPurchase].[tSalesReturn] SR(NOLOCK)
		       LEFT JOIN sProcurement.tVendorMaster  VM ON SR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
			   LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = SR.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  SR.Id = @rSalesReturnId  AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0


    SET @HTMLTable = '';
	IF EXISTS(SELECT *  FROM   [sPurchase].[tSalesReturnDetail] SRD
			WHERE  SRD.SalesReturnId = @rSalesReturnId)
    BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>POQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReceivedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>RejectedQty</th>';
	SET @HTMLTable = @HTMLTable + '<th>CreditNoteIssueDate</th>';
	SET @HTMLTable = @HTMLTable + '<th>ReasonForRejection</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(SRD.POQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(SRD.ReceivedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(SRD.RejectedQty AS NVARCHAR(20)),'')+'</td><td>'+ISNULL(CAST(SRD.CreditNoteIssueDate AS NVARCHAR(100)),'')+'</td><td>'+ISNULL(CAST(SRD.ReasonForRejection AS NVARCHAR(300)),'')+'</td></tr>'
	    FROM   [sPurchase].[tSalesReturnDetail] SRD(NOLOCK)
			   INNER JOIN  [sPurchase].[tSalesReturn] SR ON SR.Id = SRD.SalesReturnId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  SRD.SalesReturnId = @rSalesReturnId AND SRD.OrgGroupId = @rOrgGroupId

   END
SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template,
		'{SRNumber}' , @rSRNumber),
		'{GRNNumber}' , @rGRNNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{Status}' , @rStatus),
		'{VendorName}' , @rVendorName),
		'{PurchaseOrderNumber}' , @rPurchaseOrderNumber),
		'{SalesReturnDetails}' , ISNULL(@HTMLTable,''))

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='SR' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- exec [sPurchase].[pGetStoreLocationConfig] 95,9911000000003
CREATE OR ALTER PROCEDURE [sPurchase].[pGetStoreLocationConfig]
	@rSourceTypeId INT,
	@rSourceId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		 DECLARE @result INT
		 SELECT @result=ISNULL(ItemValue,0)
		 FROM sConfig.tConfigurationSetup
		 WHERE ConfigurationId  = 542 AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId
		 SELECT ISNULL(@result,0)
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pGetTemplate] 991100001
CREATE OR ALTER PROCEDURE [sPurchase].[pGetTemplate]
      @rPurchaseOrderId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	DECLARE @HTMLTable NVARCHAR(MAX);

	DECLARE
	@rRefNumber AS NVARCHAR(20),
	@rPurchaseRequestNumber AS NVARCHAR(20),
	@rRequestedBy AS NVARCHAR(100),
	@rPoDate AS NVARCHAR(100),
	@rStatus AS NVARCHAR(100),
	@rVendorCode AS NVARCHAR(100),
	@rVendorName AS NVARCHAR(300),
	@rRequiredBy AS NVARCHAR(100),
	@rBillToAddress AS NVARCHAR(1000),
	@rShipToAddress AS NVARCHAR(1000)

	    SELECT  @rRefNumber = ISNULL(PO.RefNumber,''),
				@rPurchaseRequestNumber = ISNULL(PR.Number,''),
				@rRequestedBy = ISNULL(PO.RequestedBy,''),
				@rPoDate = ISNULL(PO.PODate,''),
				@rStatus = ISNULL(SM.Title,''),
				@rVendorCode = ISNULL(VM.Code,''),
				@rVendorName = ISNULL(VM.Title,''),
				@rRequiredBy = ISNULL(PO.RequiredBy,''),
				@rBillToAddress = ISNULL(PO.BillToAddress,''),
				@rShipToAddress = ISNULL(PO.ShipToAddress,'')
		FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK)
			   LEFT JOIN sProcurement.tVendorMaster  VM ON PO.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = PO.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  PO.Id = @rPurchaseOrderId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId


    SET @HTMLTable = '';
	IF EXISTS(SELECT *  FROM   [sPurchase].[tPurchaseOrderDetail] POD
			WHERE  POD.PurchaseOrderId = @rPurchaseOrderId)
    BEGIN
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>TotalQty</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+ISNULL(CAST(SIM.Code AS NVARCHAR(100)),'')+'</td><td>'
+ISNULL(SIM.Title,'')+'</td><td>'+ISNULL(SUMa.Code,'')+'</td><td>'+ISNULL(CAST(POD.TotalQty AS NVARCHAR(20)),'')+'</td></tr>'
	  FROM   [sPurchase].[tPurchaseOrderDetail] POD (NOLOCK)
			   INNER JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM ON SIM.Id = POD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN   sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  POD.PurchaseOrderId = @rPurchaseOrderId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId

	END
SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template,
		'{RefNumber}' , @rRefNumber),
		'{PurchaseRequestNumber}' , @rPurchaseRequestNumber),
		'{RequestedBy}' , @rRequestedBy),
		'{PoDate}' , @rPoDate),
		'{Status}' , @rStatus),
		'{VendorCode}' , @rVendorCode),
		'{VendorName}' , @rVendorName),
		'{RequiredBy}' , @rRequiredBy),
		'{BillToAddress}' , @rBillToAddress),
		'{ShipToAddress}' , @rShipToAddress),
		'{PurchaseOrderDetails}' , ISNULL(@HTMLTable,''))

		AS Template FROM sPurchase.tPurchaseReportTemplateMaster WHERE Code='PO' AND IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteAdd]
		@rId BIGINT,
		@rPurchaseRequestId BIGINT,
		@rPurchaseOrderId BIGINT,
		@rPODueDate DATETIME,
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@rStatusId SMALLINT,
		@rVendorId INT,
		@rBillToAddress NVARCHAR(1000),
		@rUserId BIGINT,
		@rDetailList sPurchase.GoodsReceivedNoteDetailType READONLY

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tGoodsReceivedNote WHERE Id = @rId AND CreatedUserId = @rUserId  AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
            BEGIN
            SELECT -103
            END
			ELSE
			BEGIN
			   IF NOT EXISTS(SELECT Id FROM @rDetailList WHERE PreviousGRNQty+ReceivedQty > POQty)
			   BEGIN
				UPDATE sPurchase.tGoodsReceivedNote
				SET
					StatusId = @rStatusId,
					PurchaseRequestId = @rPurchaseRequestId,
					PurchaseOrderId = @rPurchaseOrderId,
					VendorId = @rVendorId,
					PODueDate = @rPODueDate,
					RequestedBy = @rRequestedBy,
					BillToAddress = @rBillToAddress,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = GetUtcDate()
				WHERE Id = @rId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tGoodsReceivedNoteDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND GoodsReceivedNoteId = @rId AND OrgGroupId = @rOrgGroupId

				UPDATE sPurchase.tGoodsReceivedNoteDetail
				SET
				OrgGroupId = @rOrgGroupId,
				GoodsReceivedNoteId = @rId,
				PurchaseOrderDetailId = DL.PurchaseOrderDetailId,
				StockItemId = DL.StockItemId,
				POQty = DL.POQty,
				ReceivedQty = DL.ReceivedQty,
				PreviousGRNQty = DL.PreviousGRNQty,
				UnitPrice = DL.UnitPrice,
				Remark = DL.Remark,
				UpdatedUserId = @rUserId,
				UpdatedDateTime = GETUTCDATE()
				FROM @rDetailList DL
				INNER JOIN sPurchase.tGoodsReceivedNoteDetail GRN ON DL.ID = GRN.Id
				WHERE GRN.GoodsReceivedNoteId = @rId AND GRN.OrgGroupId = @rOrgGroupId

				DECLARE @lNextNumberGRN BIGINT
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNoteDetail',@lNextNumber = @lNextNumberGRN OUTPUT
				SET @lNextNumberGRN=@lNextNumberGRN-1
				INSERT INTO sPurchase.tGoodsReceivedNoteDetail
				(
					Id,
					OrgGroupId,
					GoodsReceivedNoteId,
					PurchaseOrderDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					PreviousGRNQty,
					UnitPrice,
					Remark,
					CreatedUserId,
					CreatedDateTime
				)
				SELECT	@lNextNumberGRN+Id,
						@rOrgGroupId,
						@rId,
						PurchaseOrderDetailId,
						StockItemId,
						POQty,
						ReceivedQty,
						PreviousGRNQty,
						UnitPrice,
						Remark,
						@rUserId,
						GETUTCDATE()
				FROM @rDetailList
				WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tGoodsReceivedNoteDetail GRN ON DL.ID = GRN.Id
				WHERE GRN.GoodsReceivedNoteId = @rId AND GRN.OrgGroupId = @rOrgGroupId)

				SET @lNextNumberGRN=@lNextNumberGRN+(SELECT COUNT(Id) FROM @rDetailList WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tGoodsReceivedNoteDetail GRN ON DL.ID = GRN.Id AND GRN.OrgGroupId = @rOrgGroupId
				WHERE GRN.GoodsReceivedNoteId = @rId AND GRN.OrgGroupId = @rOrgGroupId))
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tGoodsReceivedNoteDetail', @rCurrentNumber = @lNextNumberGRN

				SELECT @rId
			END
			SELECT -101
		    END
			END
		ELSE
		BEGIN
		    IF NOT EXISTS(
                SELECT WFS.AutoId FROM [sWf].[tWfSetup] WFS
				WHERE WFS.[WfFunctionalityId] = 4 AND @rOrgGroupId = WFS.[OrgGroupId])
				BEGIN
					SELECT -102
				END
			ELSE
			BEGIN
			    IF(((SELECT EmployeeManagerId FROM [sHrm].[tEmployeeJobDetail] WHERE EmployeeId = (SELECT ISNULL(U.SourceId,U.Id) FROM sSecurity.tUser U WHERE U.Id = @rUserId)) IS NULL) AND EXISTS(SELECT WFS.WfTypeMasterId FROM [sWf].[tWfFunctionalityMaster] SFM INNER JOIN [sWf].[tWfSetup] WFS ON WFS.WfFunctionalityId = SFM.Id WHERE WFS.WfTypeMasterId = 2 AND WFS.WfLevel > 0 AND SFM.Id = 4))
				BEGIN
					SELECT -301;
				END
				ELSE
				BEGIN
				IF NOT EXISTS(SELECT Id FROM @rDetailList WHERE PreviousGRNQty+ReceivedQty > POQty)
				BEGIN
					DECLARE @lNextNumber INT
					EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNote',@lNextNumber = @lNextNumber OUTPUT
					--------------select @lNextNumber
					--DECLARE @loNextNumber nVarchar(20)
					--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
					--------------@rNextNumber = @loNextNumber OUTPUT

	 				INSERT INTO sPurchase.tGoodsReceivedNote
					(
						Id,
						GRNNumber,
						PurchaseRequestId,
						PurchaseOrderId,
						PODueDate,
						RequestedBy,
						OrgGroupId,
						LocationId,
						StatusId,
						VendorId,
						BillToAddress,
						CreatedUserId,
						CreatedDateTime

					)
					VALUES
					(
						@lNextNumber,
						@lNextNumber,
						@rPurchaseRequestId,
						@rPurchaseOrderId,
						@rPODueDate,
						@rRequestedBy,
						@rOrgGroupId,
						@rStoreLocationId,
						@rStatusId,
						@rVendorId,
						@rBillToAddress,
						@rUserId,
						GETUTCDATE()
					)

					SET @rId = @lNextNumber

					DECLARE @lNextNumberGRND BIGINT
					EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tGoodsReceivedNoteDetail',@lNextNumber = @lNextNumberGRND OUTPUT
					SET @lNextNumberGRND=@lNextNumberGRND-1

	 				INSERT INTO sPurchase.tGoodsReceivedNoteDetail
					(
						Id,
						OrgGroupId,
						GoodsReceivedNoteId,
						PurchaseOrderDetailId,
						StockItemId,
						POQty,
						ReceivedQty,
						PreviousGRNQty,
						UnitPrice,
						Remark,
						CreatedUserId,
						CreatedDateTime
					)
					SELECT	@lNextNumberGRND+Id,
							@rOrgGroupId,
							@rId,
							PurchaseOrderDetailId,
							StockItemId,
							POQty,
							ReceivedQty,
							PreviousGRNQty,
							UnitPrice,
							Remark,
							@rUserId,
							GETUTCDATE()
					FROM @rDetailList

					SET @lNextNumberGRND=@lNextNumberGRND+(SELECT Count(Id) FROM @rDetailList)
					EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tGoodsReceivedNoteDetail', @rCurrentNumber = @lNextNumberGRND

					SELECT @rId

					DECLARE @typeId SMALLINT=0
					DECLARE @Level SMALLINT=0
					SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 4
					IF(@typeId = 1)
					BEGIN
						EXEC [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,1,'',0,0,4,@rOrgGroupId
					END
					ELSE IF(@typeId = 2)
					BEGIN
						EXEC [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,1,'',1,@Level,4,@rOrgGroupId
					END
					ELSE IF(@typeId = 3)
					BEGIN
						EXEC [sWf].[pWfApprovalAdd] 0,@rId,2043,@rUserId,3,'',0,0,4,@rOrgGroupId
					END
				END
				SELECT -101;
				END
			END
		End
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pGoodsReceivedNoteApprovedGet] 991100002
CREATE OR ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteApprovedGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		SELECT  GRN.Id,
				GRN.GRNNumber                               ,
				GRN.OrgGroupId,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.RequestedBy,
				ISNULL(GRN.BillToAddress, PO.BillToAddress) AS BillToAddress,
				GRN.StatusId,
				GRN.PODueDate,
				ISNULL(SM.Title,'') AS Status,
				VM.Title AS VendorName,
			    PR.Number AS PurchaseRequestNumber,
				ISNULL(PO.ShipToAddress,'') AS ShipToAddress,
			    PO.RefNumber AS PurchaseOrderNumber
		FROM   [sPurchase].[tGoodsReceivedNote] GRN(NOLOCK)
			   LEFT JOIN sProcurement.tVendorMaster  VM ON GRN.VendorId = VM.ID AND VM.OrgGroupId = @rOrgGroupId AND VM.LocationId = @rStoreLocationId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  GRN.Id=@rId AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId

		SELECT GRND.Id,
			   GRND.GoodsReceivedNoteId,
			   GRND.PurchaseOrderDetailId,
			   GRND.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   GRND.StockItemId,
			   GRND.POQty,
			   GRND.ReceivedQty
			   - (SELECT ISNULL(Sum(QCD.AcceptedQty + QCD.RejectedQty), 0) AS AdjustedReceivedQty
				FROM [sPurchase].[tGoodsReceivedNote] GRN
					 INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND1 ON GRND1.[GoodsReceivedNoteId] = GRN.Id
					 LEFT JOIN [sPurchase].[tQualityCheckDetail] QCD ON QCD.[GoodsReceivedNoteDetailId] = GRND1.Id
				WHERE GRND1.[GoodsReceivedNoteId] = GRN.Id AND GRND1.Id = GRND.Id AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				GROUP BY GRND1.[GoodsReceivedNoteId]
				HAVING SUM(GRND1.ReceivedQty) > ISNULL(SUM(QCD.AcceptedQty + QCD.RejectedQty), 0)) AS ReceivedQty,
			   GRND.PreviousGRNQty,
			   GRND.UnitPrice,
			   GRND.Remark,
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM,
			   SCM.Id AS CategoryId,
			   SCM.Title AS CategoryName,
			   0 AS SubCategoryId
		FROM   [sPurchase].[tGoodsReceivedNoteDetail] GRND (NOLOCK)
			   INNER JOIN	sPurchase.tGoodsReceivedNote GRN	ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
		WHERE  GRND.GoodsReceivedNoteId=@rId AND GRN.StatusId = 3 AND GRND.ReceivedQty > 0 AND GRN.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pGoodsReceivedNoteApprovedSearchGet] null,991100001,null,9911,'2023-01-01','2023-12-30',1,10,null
CREATE OR ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteApprovedSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rOrgGroupId INT,
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

	    DECLARE @TotalRecords BIGINT;
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tGoodsReceivedNote GRN(NOLOCK)



		WHERE
				((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((GRN.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
				AND GRN.Id NOT IN
				(SELECT GRN8.GoodsReceivedNoteId
				  FROM [sPurchase].[tGoodsReceivedNoteDetail] GRN8
				  WHERE GRN8.GoodsReceivedNoteId = GRN.Id
				  AND  GRN8.ReceivedQty <=
				 (
				  SELECT ISNULL(SUM(QCD.AcceptedQty),0)+ISNULL(SUM(QCD.RejectedQty),0)
				  FROM [sPurchase].[tQualityCheckDetail] QCD
				  INNER JOIN [sPurchase].[tQualityCheck] QC ON QCD.QualityCheckId = Qc.Id AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				  WHERE  QC.GoodsReceivedNoteId = GRN8.GoodsReceivedNoteId	AND QCD.GoodsReceivedNoteDetailId =GRN8.Id
				  GROUP BY QC.GoodsReceivedNoteId)
				  )
				AND ((CAST(GRN.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(GRN.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))

	    SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY GRN.Id DESC
			) AS 'RowNum',GRN.Id,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.GRNNumber AS Number,
				GRN.RequestedBy,
				GRN.PODueDate,
				ISNULL(SM.Title,'') AS Status,
				VM.Code AS VendorCode,
			    VM.Title AS VendorName,
				PR.Number AS PurchaseNumber,
				PO.RefNumber AS PurchaseOrderNumber

	    FROM
				sPurchase.tGoodsReceivedNote GRN (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON GRN.StatusId = SM.Id
				LEFT JOIN sProcurement.tVendorMaster  VM ON GRN.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE
				((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((GRN.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
				AND GRN.Id NOT IN
				(SELECT GRN8.GoodsReceivedNoteId
				  FROM [sPurchase].[tGoodsReceivedNoteDetail] GRN8
				  WHERE GRN8.GoodsReceivedNoteId = GRN.Id
				  AND  GRN8.ReceivedQty <=
				 (
				  SELECT ISNULL(SUM(QCD.AcceptedQty),0)+ISNULL(SUM(QCD.RejectedQty),0)
				  FROM [sPurchase].[tQualityCheckDetail] QCD
				  INNER JOIN [sPurchase].[tQualityCheck] QC ON QCD.QualityCheckId = Qc.Id AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				  WHERE  QC.GoodsReceivedNoteId = GRN8.GoodsReceivedNoteId	AND QCD.GoodsReceivedNoteDetailId =GRN8.Id
				  GROUP BY QC.GoodsReceivedNoteId)
				  )
				AND ((CAST(GRN.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(GRN.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
					)t WHERE t.RowNum BETWEEN
		((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

		SELECT @TotalRecords AS TotalRecords
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tGoodsReceivedNote
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tGoodsReceivedNoteDetail WHERE GoodsReceivedNoteId = @rId)
			BEGIN
				DELETE FROM sPurchase.tGoodsReceivedNoteDetail
				WHERE GoodsReceivedNoteId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pGoodsReceivedNoteGet] 991100001
CREATE OR ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		SELECT  GRN.Id,
				GRN.GRNNumber                               ,
				GRN.OrgGroupId,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.RequestedBy,
				ISNULL(GRN.BillToAddress, PO.BillToAddress) AS BillToAddress,
				GRN.StatusId,
				GRN.PODueDate,
				ISNULL(SM.Title,'') AS Status,
				VM.Title AS VendorName,
			    PR.Number AS PurchaseRequestNumber,
				ISNULL(PO.ShipToAddress,'') AS ShipToAddress,
			    PO.RefNumber AS PurchaseOrderNumber
		FROM   [sPurchase].[tGoodsReceivedNote] GRN(NOLOCK)
			   LEFT JOIN sProcurement.tVendorMaster  VM ON GRN.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = GRN.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   LEFT JOIN [sPurchase].[tPurchaseOrder] PO On PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE  GRN.Id=@rId AND GRN.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId

		SELECT GRND.Id,
			   GRND.GoodsReceivedNoteId,
			   GRND.PurchaseOrderDetailId,
			   GRND.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   GRND.StockItemId,
			   GRND.POQty,
			   (SELECT GRND1.ReceivedQty - ISNULL(SUM(SRD.RejectedQty), 0)
				FROM sPurchase.tGoodsReceivedNoteDetail GRND1
				LEFT JOIN [sPurchase].[tSalesReturnDetail] SRD ON GRND1.Id = SRD.GoodsReceivedNoteDetailId
				WHERE GRND1.GoodsReceivedNoteId = @rId AND GRND1.Id = GRND.Id GROUP BY GRND1.ReceivedQty)
			   AS ReceivedQty,
			   GRND.PreviousGRNQty,
			   GRND.UnitPrice,
			   GRND.Remark,
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM,
			   SCM.Id AS CategoryId,
			   SCM.Title AS CategoryName,
			   0 AS SubCategoryId
		FROM   [sPurchase].[tGoodsReceivedNoteDetail] GRND (NOLOCK)
			   INNER JOIN	sPurchase.tGoodsReceivedNote GRN	ON GRN.Id = GRND.GoodsReceivedNoteId AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
		WHERE  GRND.GoodsReceivedNoteId=@rId AND GRN.IsObsolete = 0
		       AND GRN.LocationId = @rStoreLocationId
			   AND GRN.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pGoodsReceivedNoteSearchGet] null,991100001,null,9911,'2023-01-01','2023-12-30',1,10,null
CREATE OR ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rOrgGroupId INT,
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

	    DECLARE @TotalRecords BIGINT;
			-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tGoodsReceivedNote GRN(NOLOCK)



		WHERE
				((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((GRN.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND GRN.IsObsolete = 0
				AND ((CAST(GRN.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(GRN.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))

	    SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY GRN.Id DESC
			) AS 'RowNum',GRN.Id,
				GRN.PurchaseRequestId,
				GRN.PurchaseOrderId,
				GRN.VendorId,
				GRN.GRNNumber AS Number,
				GRN.RequestedBy,
				GRN.PODueDate,
				ISNULL(SM.Title,'') AS Status,
				VM.Code AS VendorCode,
			    VM.Title AS VendorName,
				PR.Number AS PurchaseNumber,
				PO.RefNumber AS PurchaseOrderNumber

	    FROM
				sPurchase.tGoodsReceivedNote GRN (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON GRN.StatusId = SM.Id
				LEFT JOIN sProcurement.tVendorMaster  VM ON GRN.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = GRN.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
				LEFT JOIN [sPurchase].[tPurchaseOrder] PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		WHERE
				((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((GRN.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND GRN.IsObsolete = 0
				AND ((CAST(GRN.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(GRN.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
					)t WHERE t.RowNum BETWEEN
		((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

		SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pGoodsReceivedNoteSearchSRGet] null,991100001,null,9911,'2023-12-01','2023-12-30',1,10,null
CREATE OR ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSearchSRGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	                DECLARE @rStoreLocationId BIGINT
					SELECT @rStoreLocationId = ISNULL(ItemValue,0)
					FROM sConfig.tConfigurationSetup
					WHERE ConfigurationId  = 542 AND SourceId = @rUserId

					IF @rNumber = NULL SET @rNumber=''
					IF @rName = NULL SET @rName=''
					IF @rStartDate = '' SET @rStartDate=NULL
					IF @rEndDate = '' SET @rEndDate=NULL
					IF @rStatusId IS NULL SET @rStatusId=0

					DECLARE @TotalRecords BIGINT;
		            -- Get the total number of records
					SELECT @TotalRecords = COUNT(*) FROM sPurchase.tGoodsReceivedNote GRN (NOLOCK)

					WHERE
							((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   							AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   							AND ((GRN.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   							AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
							AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
							AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
							AND GRN.Id IN
							(SELECT DISTINCT GRN12.Id FROM sPurchase.tSalesReturnDetail SRD
							INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId
								   AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
							INNER JOIN sPurchase.tGoodsReceivedNote GRN12 ON Sr.GoodsReceivedNoteId = Grn12.Id
								   AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0
							INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND ON SRD.GoodsReceivedNoteDetailId = GRND.Id
							AND GRND.GoodsReceivedNoteId = GRN12.Id
							GROUP BY GRN12.Id
							HAVING  SUM(SRD.RejectedQty) < (SELECT SUM(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
							INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id
								   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
							INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
							WHERE GRN12.Id = GRN.Id AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0))
							AND ((CAST(GRN.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
							AND((CAST(GRN.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))


					SELECT t.* FROM (
						SELECT ROW_NUMBER() OVER (
						ORDER BY GRN.Id DESC
						) AS 'RowNum',GRN.Id,
							GRN.GRNNumber AS Number,
							GRN.RequestedBy,
							GRN.PODueDate,
							ISNULL(SM.Title,'') AS Status,
							(SELECT SUM(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
							INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id
								   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
							INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
							WHERE GRN12.Id = GRN.Id AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0) AS RejectedQty

					FROM
							sPurchase.tGoodsReceivedNote GRN (NOLOCK)
							LEFT JOIN [sWf].[tWfStatusMaster] SM ON GRN.StatusId = SM.Id


					WHERE
							((GRN.GRNNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   							AND ((GRN.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   							AND ((GRN.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   							AND ((GRN.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
							AND ((GRN.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
							AND GRN.IsObsolete = 0 AND GRN.StatusId = 3
							AND GRN.Id IN
							(SELECT DISTINCT GRN12.Id FROM sPurchase.tGoodsReceivedNote GRN12
							INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id
								   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
							INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
							WHERE GRN12.Id = GRN.Id
							GROUP BY GRN12.Id
							HAVING  (ISNULL(SUM(QCD1.RejectedQty),0) >(
							SELECT ISNULL(SUM(SRD.RejectedQty),0) FROM sPurchase.tSalesReturnDetail SRD
							INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId
								   AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
							INNER JOIN sPurchase.tGoodsReceivedNote GRN1 ON SR.GoodsReceivedNoteId = GRN1.Id
								   AND GRN1.LocationId = @rStoreLocationId AND GRN1.OrgGroupId = @rOrgGroupId AND GRN1.IsObsolete = 0
							INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND ON SRD.GoodsReceivedNoteDetailId = GRND.Id
							AND GRND.GoodsReceivedNoteId = GRN1.Id))
							)
							AND ((CAST(GRN.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
							AND((CAST(GRN.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
								)t WHERE t.RowNum BETWEEN
							((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

				SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pGoodsReceivedNoteSRGet] 991100003
CREATE OR ALTER PROCEDURE [sPurchase].[pGoodsReceivedNoteSRGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF((SELECT
				(SELECT SUM(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
			    INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id
					   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
				WHERE GRN12.Id = @rId AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0) -
				 (SELECT ISNULL(SUM(SRD.RejectedQty),0) FROM sPurchase.tSalesReturnDetail SRD
				INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId
				AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
				INNER JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND ON SRD.GoodsReceivedNoteDetailId = GRND.Id
				AND GRND.GoodsReceivedNoteId = @rId
				WHERE SR.GoodsReceivedNoteId = @rId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0)) = 0)
		BEGIN
			SELECT -101
		END
		ELSE
		BEGIN
			SELECT DISTINCT GRN.Id AS GoodsReceivedNoteId,
					GRN.GRNNumber,
					GRN.OrgGroupId,
					GRN.PurchaseRequestId,
					GRN.PurchaseOrderId,
					GRN.VendorId,
					GRN.RequestedBy,
					GRN.BillToAddress,
					GRN.StatusId,
					GRN.PODueDate,
					PO.RefNumber AS PurchaseOrderNumber,
					ISNULL(SM.Title,'') AS Status,
					VM.Title AS VendorName
			FROM   [sPurchase].[tGoodsReceivedNote] GRN(NOLOCK)
				   INNER JOIN sPurchase.tQualityCheck QC ON QC.GoodsReceivedNoteId = GRN.Id AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				   INNER JOIN sPurchase.tPurchaseOrder PO ON PO.Id = GRN.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
				   LEFT JOIN  sProcurement.tVendorMaster  VM ON GRN.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				   LEFT Join  sWf.tWfStatusMaster SM ON SM.Id = GRN.StatusId
			WHERE  GRN.Id=@rId AND GRN.StatusId = 3 AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0

			SELECT DISTINCT GRND.Id AS GoodsReceivedNoteDetailId,
				   GRND.GoodsReceivedNoteId,
				   GRND.PurchaseOrderDetailId,
				   GRND.OrgGroupId,
				   SUMa.Id AS UnitTypeId,
				   GRND.StockItemId,
				   GRND.POQty,
				   GRND.ReceivedQty,
				   GRND.PreviousGRNQty,
				   GRND.UnitPrice,
				   GRND.Remark,
				 --  (SELECT Sum(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
				 --   INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id
				 --   INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
					--WHERE GRN12.Id = GRN.Id) AS RejectedQty,
					(SELECT SUM(QCD1.RejectedQty) FROM sPurchase.tGoodsReceivedNote GRN12
					INNER JOIN   sPurchase.tQualityCheck QC1 ON QC1.GoodsReceivedNoteId = GRN12.Id
						   AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
					INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
					WHERE GRN12.Id = GRN.Id AND GRN12.LocationId = @rStoreLocationId AND GRN12.OrgGroupId = @rOrgGroupId AND GRN12.IsObsolete = 0) -
					 (SELECT ISNULL(SUM(SRD.RejectedQty),0) FROM sPurchase.tSalesReturnDetail SRD
					INNER JOIN sPurchase.tSalesReturn SR ON SR.Id = SRD.SalesReturnId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
					WHERE SR.GoodsReceivedNoteId = GRN.Id AND SRD.GoodsReceivedNoteDetailId = GRND.Id
					AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0)
					AS RejectedQty,
				   '' AS ReasonForRejection,
				   SIM.Code	AS StockItemCode,
				   SIM.Title AS StockItemName,
				   SUMa.Code AS UOM,
				   SCM.Id AS CategoryId,
				   SCM.Title AS CategoryName,
				   0 AS SubCategoryId
			FROM   [sPurchase].[tGoodsReceivedNoteDetail] GRND (NOLOCK)
				   INNER JOIN	sPurchase.tGoodsReceivedNote GRN ON GRN.Id = GRND.GoodsReceivedNoteId
						  AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				   INNER JOIN sPurchase.tQualityCheck QC ON QC.GoodsReceivedNoteId = GRN.Id
						  AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
				   INNER JOIN   sPurchase.tQualityCheckDetail QCD ON QCD.QualityCheckId = QC.Id AND QCD.GoodsReceivedNoteDetailId = GRND.ID
				   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = GRND.StockItemId
					      AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
				   INNER JOIN   sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
				   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			WHERE  GRND.GoodsReceivedNoteId=@rId AND QCD.RejectedQty > 0 AND GRN.StatusId = 3
				   AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		END
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pHelperPopUpGet]
	  @rScreenId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT ISNULL(HelpDescription,'')
		 FROM sSecurity.tScreenHelp
		 WHERE ScreenId = @rScreenId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sPurchase].[pInvoiceGenerateAdd]
		@rId BIGINT,
		@rGoodsReceivedNoteId BIGINT,
		@rVendorId BIGINT,
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@rStatusId SMALLINT,
		@rInvoiceDate DATETIME,
		@rInvoiceDueDate DATETIME,
		@rBillToAddress NVARCHAR(1000),
		@rShipToAddress NVARCHAR(1000),
		@rRemarks NVARCHAR(500),
		@rUserId BIGINT,
		@rDetailList sPurchase.InvoiceGenerateDetailType READONLY

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tInvoiceGenerate WHERE Id = @rId AND CreatedUserId = @rUserId
			AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
            BEGIN
				SELECT -103
            END
			ELSE
			BEGIN
			    UPDATE sPurchase.tInvoiceGenerate
				SET
					StatusId = @rStatusId,
					GoodsReceivedNoteId = @rGoodsReceivedNoteId,
					VendorId = @rVendorId,
					RequestedBy = @rRequestedBy,
					InvoiceDate = @rInvoiceDate,
					InvoiceDueDate = @rInvoiceDueDate,
					BillToAddress = @rBillToAddress,
					ShipToAddress = @rShipToAddress,
					Remarks = @rRemarks,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = GETUTCDATE()
				WHERE Id = @rId  AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tInvoiceGenerateDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND InvoiceGenerateId = @rId AND OrgGroupId = @rOrgGroupId

				UPDATE sPurchase.tInvoiceGenerateDetail
				SET
				OrgGroupId = @rOrgGroupId,
				InvoiceGenerateId = @rId,
				GoodsReceivedNoteDetailId = DL.GoodsReceivedNoteDetailId,
				StockItemId = DL.StockItemId,
				POQty = DL.POQty,
				ReceivedQty = DL.ReceivedQty,
				AcceptedQty = DL.AcceptedQty,
				RejectedQty = DL.RejectedQty,
				ReasonForRejection = DL.ReasonForRejection,
				UnitPrice = DL.UnitPrice,
				Remark = IG.Remark,
				UpdatedUserId = @rUserId,
				UpdatedDateTime = GETUTCDATE()
				FROM @rDetailList DL
				INNER JOIN sPurchase.tInvoiceGenerateDetail IG ON DL.ID = IG.Id
				WHERE IG.InvoiceGenerateId = @rId AND IG.OrgGroupId = @rOrgGroupId

				DECLARE @lNextNumberIGD BIGINT
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerateDetail',@lNextNumber = @lNextNumberIGD OUTPUT
				SET @lNextNumberIGD=@lNextNumberIGD-1
				INSERT INTO sPurchase.tInvoiceGenerateDetail
				(
					Id,
					OrgGroupId,
					InvoiceGenerateId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					UnitPrice,
					ReasonForRejection,
					CreatedUserId,
					CreatedDateTime
				)
				SELECT	@lNextNumberIGD+Id,
						@rOrgGroupId,
						@rId,
						GoodsReceivedNoteDetailId,
						StockItemId,
						POQty,
						ReceivedQty,
						AcceptedQty,
						RejectedQty,
						UnitPrice,
						ReasonForRejection,
						@rUserId,
						GETUTCDATE()
				FROM @rDetailList
				WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tInvoiceGenerateDetail IG ON DL.ID = IG.Id AND IG.OrgGroupId = @rOrgGroupId
				WHERE IG.InvoiceGenerateId = @rId AND IG.OrgGroupId = @rOrgGroupId)
				SET @lNextNumberIGD=@lNextNumberIGD+(SELECT COUNT(Id) FROM @rDetailList WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tInvoiceGenerateDetail IG ON DL.ID = IG.Id AND IG.OrgGroupId = @rOrgGroupId
				WHERE IG.InvoiceGenerateId = @rId AND IG.OrgGroupId = @rOrgGroupId))
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tInvoiceGenerateDetail', @rCurrentNumber = @lNextNumberIGD

				SELECT @rId
			END
		END
		ELSE
		BEGIN
			DECLARE @lNextNumber INT
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerate',@lNextNumber = @lNextNumber OUTPUT
			--SELECT @lNextNumber
			--DECLARE @loNextNumber nVarchar(20)
			--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
			--@rNextNumber = @loNextNumber OUTPUT

	 		INSERT INTO sPurchase.tInvoiceGenerate
			(
				Id,
				INVNumber,
				GoodsReceivedNoteId,
				VendorId,
				RequestedBy,
				OrgGroupId,
				LocationId,
				StatusId,
				InvoiceDate,
				InvoiceDueDate,
				BillToAddress,
				ShipToAddress,
				Remarks,
				CreatedUserId,
				CreatedDateTime

			)
			VALUES
			(
				@lNextNumber,
				@lNextNumber,
				@rGoodsReceivedNoteId,
				@rVendorId,
				@rRequestedBy,
				@rOrgGroupId,
				@rStoreLocationId,
				@rStatusId,
				@rInvoiceDate,
				@rInvoiceDueDate,
				@rBillToAddress,
				@rShipToAddress,
				@rRemarks,
				@rUserId,
				GETUTCDATE()
			)

			SET @rId = @lNextNumber

			DECLARE @lNextNumberIGDD BIGINT= 10000 + 	(SELECT COUNT (ID) FROM sPurchase.tInvoiceGenerateDetail)
			EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tInvoiceGenerateDetail',@lNextNumber = @lNextNumberIGDD OUTPUT
			SET @lNextNumberIGDD=@lNextNumberIGDD-1

	 		INSERT INTO sPurchase.tInvoiceGenerateDetail
			(
				Id,
				OrgGroupId,
				InvoiceGenerateId,
				GoodsReceivedNoteDetailId,
				StockItemId,
				POQty,
				ReceivedQty,
				AcceptedQty,
				RejectedQty,
				UnitPrice,
				ReasonForRejection,
				CreatedUserId,
				CreatedDateTime
			)
			SELECT	@lNextNumberIGDD+Id,
					@rOrgGroupId,
					@rId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					UnitPrice,
					ReasonForRejection,
					@rUserId,
					GETUTCDATE()
			FROM @rDetailList

			SET @lNextNumberIGDD=@lNextNumberIGDD+(SELECT COUNT(Id) FROM @rDetailList)
			EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tInvoiceGenerateDetail', @rCurrentNumber = @lNextNumberIGDD
			SELECT @rId
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sPurchase].[pInvoiceGenerateDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tInvoiceGenerate
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tInvoiceGenerateDetail WHERE InvoiceGenerateId = @rId)
			BEGIN
				DELETE FROM sPurchase.tInvoiceGenerateDetail
				WHERE InvoiceGenerateId = @rId
			END
			SELECT 1
	    END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pInvoiceGenerateGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		SELECT  IG.Id,
				IG.INVNumber,
				IG.OrgGroupId,
				IG.GoodsReceivedNoteId,
				IG.RequestedBy,
				IG.VendorId,
				IG.InvoiceDate,
				IG.InvoiceDueDate,
				IG.BillToAddress,
				IG.ShipToAddress,
				IG.Remarks,
				ISNULL(GRN.GRNNumber,'') AS GRNNumber,
				IG.StatusId,
				ISNULL(SM.Title,'') AS Status,
				ISNULL(VM.Title,'') AS VendorName,
				ISNULL(VM.Code,'') AS VendorCode
		FROM   [sPurchase].[tInvoiceGenerate] IG(NOLOCK)
		LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = IG.GoodsReceivedNoteID AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		LEFT JOIN sProcurement.tVendorMaster  VM ON IG.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = IG.StatusId
		WHERE  IG.Id=@rId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId

		SELECT IGD.Id,
			   IGD.InvoiceGenerateId,
			   IGD.GoodsReceivedNoteDetailId,
			   IGD.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   IGD.StockItemId,
			   IGD.POQty,
			   IGD.ReceivedQty,
			   IGD.AcceptedQty,
			   IGD.RejectedQty,
			   IGD.UnitPrice,
			   IGD.ReasonForRejection,
			   SCM.Id AS CategoryId,
			   SCM.Title AS CategoryName,
			   0 AS SubCategoryId,
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM
		FROM   [sPurchase].[tInvoiceGenerateDetail] IGD (NOLOCK)
			   INNER JOIN	sPurchase.tInvoiceGenerate IG	ON IG.Id = IGD.InvoiceGenerateId AND IG.LocationId = @rStoreLocationId AND IG.OrgGroupId = @rOrgGroupId AND IG.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = IGD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  IGD.InvoiceGenerateId=@rId AND IG.IsObsolete = 0
		       AND IG.LocationId = @rStoreLocationId
			   AND IG.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pInvoiceGenerateSearchGet] '',991100001,'',9911,'2023-01-01','2023-12-01',1,10,null
CREATE OR ALTER PROCEDURE [sPurchase].[pInvoiceGenerateSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rOrgGroupId INT,
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tInvoiceGenerate IG (NOLOCK)

		WHERE
				((IG.INVNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((IG.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((IG.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((IG.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((IG.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND ((CAST(IG.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(IG.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
				AND IG.IsObsolete = 0



        SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY IG.Id DESC
			) AS 'RowNum',
			    IG.Id,
				IG.INVNumber AS Number,
				IG.RequestedBy,
				IG.InvoiceDate,
				ISNULL(SM.Title,'') AS Status

        FROM
				sPurchase.tInvoiceGenerate IG (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON IG.StatusId = SM.Id



        WHERE
				((IG.INVNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((IG.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((IG.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((IG.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((IG.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND ((CAST(IG.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(IG.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
				AND IG.IsObsolete = 0
				)t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pMasterBatchGet]
	  @rOrgId int
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Title
	     FROM  sSetup.tBatchMaster
		 WHERE IsObsolete = 0
		 AND IsHistory = 0
		 AND OrgId = @rOrgId
		 ORDER BY OrderIndex DESC
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pMasterOrganizationGet]
	  @rOrgGroupId INT,
	  @rUserId BIGINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   DisplayTitle AS Title
		FROM  sSetup.vUserOrganization
		WHERE IsObsolete = 0
		AND OrgGroupId = @rOrgGroupId
		AND UserId = @rUserId
		ORDER BY OrderIndex
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [sPurchase].[pMenuGet_Purchase] 9911000000270
CREATE OR ALTER PROCEDURE [sPurchase].[pMenuGet_Purchase]    
 @rUserId BIGINT,    
 @rMenuId INT = 0,    
 @rResourceTypeId INT= 0
 --,    
 --@rIsCoreMenu bit = 0     
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
 BEGIN TRY
 DECLARE @rIsCoreMenu INT=1
 IF(@rIsCoreMenu=0)    
 BEGIN    
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
    PageURL  AS PagePath,    
    IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermissionUser P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
       WHERE    
        T.IsObsolete = 0 AND P.UserId = @rUserId    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 ELSE     
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
     PageURL  AS PagePath,    
     IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermission P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
        INNER JOIN    
        (    
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0    
        ) B ON B.RoleId = P.RoleId    
       WHERE    
        T.IsObsolete = 0  
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 END    
 ELSE    
 BEGIN     
 SELECT    
   MenuID,    
   ModuleId,    
   ParentMenuID,    
   MenuTitle,      
   ScreenTitle,       
   PageURL,    
   ScreenId,    
   Permission,    
   OrderNumber,      
   TaskId,      
   PageURL  AS PagePath,    
   MenuIsObsolete,    
   Icon     
  FROM    
  (    

SELECT    
   ISNULL(Menu.Id,0) AS MenuID,     
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
   ISNULL(Menu.Title,'') AS MenuTitle,       
   ISNULL(Screen.Title, '') AS ScreenTitle,        
   ISNULL(Screen.Page, '') AS PageURL,    
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen.Id, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen.IconPath,'') AS Icon,
   ISNULL(Screen.OrderIndex,0) As OrderIndex     
  FROM     
  sSecurity.tMenu Menu     
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
  LEFT OUTER JOIN     
  (    
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId      
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id AND  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id        
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId     
  GROUP BY P.TaskId    
  ) TBL2 ON Screen.TaskId = TBL2.TaskId     
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
  WHERE (Menu.IsObsolete = 0)    
  AND ISNULL(Screen.IsObsolete, 0) = 0    
  AND (Menu.Id  IN (19184028))   
  --OR ParentMenuID  in (24,2711))     
  --AND (
  ----Menu.Id IN (19184027)  
  ----OR ParentMenuID IN (55)
  --)  

  UNION
  

  SELECT     
  
   ISNULL(Menu.Id, 0) AS MenuID,     
   ISNULL(Menu.Id, 0) AS ParentMenuID,     
   ISNULL(Screen1.Title,'') AS MenuTitle,       
   ISNULL(Screen1.Title, '') AS ScreenTitle,        
   ISNULL(Screen1.Page, '')  AS PageURL,    
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen1.Id, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen1.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen1.IconPath,'') AS Icon,
   ISNULL(Screen1.OrderIndex,0) As OrderIndex    
  FROM     
   sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId     
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId    
   LEFT OUTER JOIN (     
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId        
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id       
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId    
            
  GROUP BY P.TaskId    
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId    
  WHERE (Menu.IsObsolete = 0) AND ISNULL(Screen1.IsObsolete, 0) = 0    
  --AND (Menu.ParentMenuID  in (24,2711)   
  --OR Menu.Id  in (24,2711))   
  AND TBL2.PermissionValue > 0
  AND Screen1.Id IN (31296,31297,31298,31299,31300,31301,31310,31311,31312,31317)
  ) MenuTable      
  WHERE     
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)
  --AND   
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
  AND MenuIsObsolete = 0    
  AND MenuTable.MenuId IN (19184028)   
  AND ModuleId IN (96)
  ORDER BY MenuTable.OrderIndex, ParentMenuID  
 END   
 END TRY
 BEGIN CATCH
   ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);  
		DECLARE @ErrorSeverity INT;  
		DECLARE @ErrorState INT;  

		SELECT   
		   @ErrorMessage = ERROR_MESSAGE(),  
		   @ErrorSeverity = ERROR_SEVERITY(),  
		   @ErrorState = ERROR_STATE();  

		RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
 END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pMobileNotitficationTitleGet]
		@rEventId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT Title FROM sAlert.tEventMaster WHERE Id= @rEventId
		END TRY
		BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pNotitficationLogIdGet]
		@rFromId bigint,
		@rToId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY	
			SELECT Id AS NotificationId FROM sAlert.tNotificationLog WHERE (Id>=@rFromId) AND (Id<=@rToId)
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pOrgGroupIdGet]
		@rOrgId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		END TRY
		BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pPOPurchaseRequestDetailGet] 991100002
CREATE OR ALTER PROCEDURE [sPurchase].[pPOPurchaseRequestDetailGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		SELECT PRD.Id,
			   PRD.PurchaseRequestId,
			   PRD.OrgGroupId,
			   PRD.StockItemId,
			   PRD.RequestedQty,
			   PRD.Remark,
			   SIM.Code	AS StockItemCode,
			   SCM.Title AS CategoryName,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM
		FROM   [sPurchase].[tPurchaseRequestDetail] PRD (NOLOCK)
			   INNER JOIN	sPurchase.tPurchaseRequest PR	ON PR.Id = PRD.PurchaseRequestId  AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0 AND PR.StatusId = 3
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  PRD.PurchaseRequestId=@rId AND PR.IsObsolete = 0
		       AND PR.LocationId = @rStoreLocationId
			   AND PR.OrgGroupId = @rOrgGroupId
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseOrderAdd]
		@rId BIGINT,
		@rPurchaseRequestId BIGINT,
		@rPODate DATETIME,
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@rStatusId SMALLINT,
		@rVendorId INT,
		@rBillToAddress NVARCHAR(1000),
		@rShipToAddress NVARCHAR(1000),
		@rUserId BIGINT,
		@rRequiredBy DATETIME,
		@rDetailList sPurchase.PurchaseOrderDetailType READONLY

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		    IF NOT EXISTS(SELECT Id FROM sPurchase.tPurchaseOrder WHERE Id = @rId AND CreatedUserId = @rUserId
			AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
			BEGIN
				SELECT -103
			END
			ELSE
			BEGIN
				UPDATE sPurchase.tPurchaseOrder
				SET
					StatusId = @rStatusId,
					RequestedBy = @rRequestedBy,
					VendorId = @rVendorId,
					RequiredBy = @rRequiredBy,
					BillToAddress = @rBillToAddress,
					ShipToAddress = @rShipToAddress,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = GETUTCDATE()
				WHERE Id = @rId  AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tPurchaseOrderDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND PurchaseOrderId = @rId AND OrgGroupId = @rOrgGroupId

				UPDATE sPurchase.tPurchaseOrderDetail
				SET
				OrgGroupId = @rOrgGroupId,
				PurchaseOrderId = @rId,
				PurchaseRequestDetailId = DL.PurchaseRequestDetailId,
				StockItemId = DL.StockItemId,
				TotalQty = DL.TotalQty,
				Remark = DL.Remark,
				UpdatedUserId = @rUserId,
				UpdatedDateTime = GETUTCDATE()
				FROM @rDetailList DL
				INNER JOIN sPurchase.tPurchaseOrderDetail PO ON DL.ID = PO.Id
				WHERE PO.PurchaseOrderId = @rId AND PO.OrgGroupId = @rOrgGroupId

				DECLARE @lNextNumberPOD BIGINT
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrderDetail',@lNextNumber = @lNextNumberPOD OUTPUT
				SET @lNextNumberPOD=@lNextNumberPOD-1
				INSERT INTO sPurchase.tPurchaseOrderDetail
				(
					Id,
					OrgGroupId,
					PurchaseOrderId,
					PurchaseRequestDetailId,
					StockItemId,
					TotalQty,
					Remark,
					CreatedUserId,
					CreatedDateTime
				)
				SELECT	@lNextNumberPOD+Id,
						@rOrgGroupId,
						@rId,
						PurchaseRequestDetailId,
						StockItemId,
						TotalQty,
						Remark,
						@rUserId,
						GETUTCDATE()
				FROM @rDetailList
				WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tPurchaseOrderDetail PO ON DL.ID = PO.Id
				WHERE PO.PurchaseOrderId = @rId AND PO.OrgGroupId = @rOrgGroupId)
				SET @lNextNumberPOD=@lNextNumberPOD+(SELECT COUNT(Id) FROM @rDetailList WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tPurchaseOrderDetail PO ON DL.ID = PO.Id AND PO.OrgGroupId = @rOrgGroupId
				WHERE PO.PurchaseOrderId = @rId AND PO.OrgGroupId = @rOrgGroupId))
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseOrderDetail', @rCurrentNumber = @lNextNumberPOD

				SELECT @rId
			END
		END
		ELSE
		BEGIN
		    IF NOT EXISTS(
                SELECT WFS.AutoId FROM [sWf].[tWfSetup] WFS
				WHERE WFS.[WfFunctionalityId] = 3 AND @rOrgGroupId = WFS.[OrgGroupId])
				BEGIN
					SELECT -102
				END
			ELSE

				IF(((SELECT EmployeeManagerId FROM [sHrm].[tEmployeeJobDetail] WHERE EmployeeId = (SELECT ISNULL(U.SourceId,U.Id) FROM sSecurity.tUser U WHERE U.Id = @rUserId)) IS NULL) AND EXISTS(SELECT WFS.WfTypeMasterId FROM [sWf].[tWfFunctionalityMaster] SFM INNER JOIN [sWf].[tWfSetup] WFS ON WFS.WfFunctionalityId = SFM.Id WHERE WFS.WfTypeMasterId = 2 AND WFS.WfLevel > 0 AND SFM.Id = 3))
				BEGIN
					SELECT -301;
				END
				ELSE
				BEGIN

					IF EXISTS(SELECT PO.Id FROM sPurchase.tPurchaseOrder PO WHERE PO.StatusId <> 4 AND PO.PurchaseRequestId = @rPurchaseRequestId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0)
					BEGIN
						SELECT -101
					END
					ELSE
					BEGIN
						DECLARE @lNextNumber INT
						EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrder',@lNextNumber = @lNextNumber OUTPUT
						---------------SELECT @lNextNumber
						--DECLARE @loNextNumber NVARCHAR(20)
						--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
						---------------@rNextNumber = @loNextNumber OUTPUT

	 					INSERT INTO sPurchase.tPurchaseOrder
						(
							Id,
							RefNumber,
							PurchaseRequestId,
							PODate,
							RequestedBy,
							OrgGroupId,
							LocationId,
							StatusId,
							VendorId,
							RequiredBy,
							BillToAddress,
							ShipToAddress,
							CreatedUserId,
							CreatedDateTime

						)
						VALUES
						(
							@lNextNumber,
							@lNextNumber,
							@rPurchaseRequestId,
							@rPODate,
							@rRequestedBy,
							@rOrgGroupId,
							@rStoreLocationId,
							@rStatusId,
							@rVendorId,
							@rRequiredBy,
							@rBillToAddress,
							@rShipToAddress,
							@rUserId,
							GETUTCDATE()
						)

						SET @rId = @lNextNumber

						DECLARE @lNextNumberPO BIGINT
						EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseOrderDetail',@lNextNumber = @lNextNumberPO OUTPUT
						SET @lNextNumberPO=@lNextNumberPO-1

	 					INSERT INTO sPurchase.tPurchaseOrderDetail
						(
							Id,
							OrgGroupId,
							PurchaseOrderId,
							PurchaseRequestDetailId,
							StockItemId,
							TotalQty,
							Remark,
							CreatedUserId,
							CreatedDateTime
						)
						SELECT	@lNextNumberPO+Id,
								@rOrgGroupId,
								@rId,
								PurchaseRequestDetailId,
								StockItemId,
								TotalQty,
								Remark,
								@rUserId,
								GETUTCDATE()
						FROM @rDetailList

						SET @lNextNumberPO=@lNextNumberPO+(SELECT COUNT(Id) FROM @rDetailList)
						EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseOrderDetail', @rCurrentNumber = @lNextNumberPO

						SELECT @rId

						DECLARE @typeId SMALLINT=0
						DECLARE @Level SMALLINT=0
						SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 3
						IF(@typeId = 1)--parallel
						BEGIN
							EXEC [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,1,'',0,0,3,@rOrgGroupId
						END
						ELSE IF(@typeId = 2)--sequencial
						BEGIN
							EXEC [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,1,'',1,@Level,3,@rOrgGroupId
						END
						ELSE IF(@typeId = 3)--auto approved
						BEGIN
							EXEC [sWf].[pWfApprovalAdd] 0,@rId,2042,@rUserId,3,'',0,0,3,@rOrgGroupId
						END
						--select 1;
					END
		        END
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END








GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pPurchaseOrderApprovedGet] 991100003
CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseOrderApprovedGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF EXISTS(SELECT PO.Id
		FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK) 
		INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.PurchaseOrderId = PO.Id AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0 AND GRN.StatusId IN (1,2)
		WHERE PO.Id = @rId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0)
		BEGIN
			SELECT -101
		END
		ELSE
		BEGIN
			SELECT PO.Id AS PurchaseOrderId,
				   PO.RefNumber AS PurchaseOrderNumber,
				   PO.PurchaseRequestId,
				   PO.RequestedBy,
				   PO.StatusId,
				   PO.VendorId,
				   PO.OrgGroupId,
				   PO.PODate AS PODueDate,
				   PO.BillToAddress,
				   PO.ShipToAddress,
				   PO.RequiredBy,
				   ISNULL(SM.Title,'') AS Status,
				   VM.Code AS VendorCode,
				   VM.Title AS VendorName,
				   PR.Number AS PurchaseRequestNumber 
			FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK) 
				   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.ID = PO.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
				   LEFT JOIN sProcurement.tVendorMaster  VM ON PO.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0 
				   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			WHERE  PO.Id = @rId
			       AND PO.IsObsolete = 0
				   AND PO.StatusId = 3
			       AND PO.LocationId = @rStoreLocationId
				   AND PO.OrgGroupId = @rOrgGroupId

			DECLARE @PreviousGrnQty INT,@UnitPrice INT
			--SELECT @PreviousGrnQty = Sum(GRND.ReceivedQty)
			--FROM [sPurchase].[tGoodsReceivedNote] GRN 
			--LEFT JoiN sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id
			--WHERE GRN.PurchaseOrderId = @rId

			SELECT DISTINCT POD.Id AS PurchaseOrderDetailId,
				   POD.PurchaseOrderId,
				   POD.OrgGroupId,
				   POD.PurchaseRequestDetailId,
				   POD.StockItemId,
				   POD.TotalQty AS POQty,
				   POD.Remark, 
				   SUMa.Id AS UnitTypeId,
				   SIM.Code		AS StockItemCode,
				   SIM.Title AS StockItemName,
				   SUMa.Code	AS UOM,
				   SCM.Id AS CategoryId,
				   SCM.Title AS CategoryName,
				   0 AS SubCategoryId,
				   CAST((POD.TotalQty - (SELECT SUM(GRND.ReceivedQty)
					FROM [sPurchase].[tGoodsReceivedNote] GRN 
					LEFT JOIN sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id
					WHERE GRND.PurchaseOrderDetailId = POD.Id AND GRN.PurchaseOrderId = PO.Id AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0 AND GRN.StatusID <> 4)) AS DECIMAL) AS ReceivedQty ,
				   (SELECT SUM(GRND.ReceivedQty)
					FROM [sPurchase].[tGoodsReceivedNote] GRN 
					LEFT JOIN sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id
					WHERE GRND.PurchaseOrderDetailId = POD.Id AND GRN.PurchaseOrderId = PO.Id AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0 AND GRN.StatusID <> 4) AS PreviousGRNQty,
				   (SELECT QRD.TargetPrice FROM [sPurchase].[tQuotationRequestDetail] QRD
					INNER JOIN [sPurchase].[tQuotationRequest] QR ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0  
					WHERE QRD.StockItemId = POD.StockItemId AND POD.PurchaseRequestDetailId = QRD.PurchaseRequestDetailId
					AND QR.PurchaseRequestId = PO.PurchaseRequestId) AS UnitPrice
			FROM   [sPurchase].[tPurchaseOrderDetail] POD (NOLOCK)
				   INNER JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.IsObsolete = 0 AND PO.StatusId = 3 AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0  
				   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0  
				   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
				   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			WHERE  POD.PurchaseOrderId = @rId AND PO.IsObsolete = 0 
			       AND PO.LocationId = @rStoreLocationId
				   AND PO.OrgGroupId = @rOrgGroupId 
		END
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--exec [sPurchase].[pPurchaseOrderApprovedSearchGet] '',991100001,'',9911,'2023-01-01','2023-12-01',1,10,null
CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseOrderApprovedSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tPurchaseOrder PO (NOLOCK)

		WHERE
				((PO.RefNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PO.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PO.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PO.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PO.IsObsolete = 0 AND PO.StatusId = 3
				AND PO.Id NOT IN (SELECT DISTINCT PO.Id FROM sPurchase.tPurchaseOrder PO
				INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.PurchaseOrderId = PO.Id AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				INNER JOIN sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id AND GRND.PreviousGRNQty+GRND.ReceivedQty >= GRND.POQty
				WHERE Grn.PurchaseOrderId = PO.Id AND GRN.StatusID <> 4 AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0)
				AND ((CAST(PO.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PO.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))


	    SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY PO.Id DESC
			) AS 'RowNum',
				PO.Id,
				PO.RefNumber AS Number,
				PO.RequestedBy,
				PO.PODate,
				ISNULL(SM.Title,'') AS Status
		FROM
				sPurchase.tPurchaseOrder PO (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON PO.StatusId = SM.Id
		WHERE
				((PO.RefNumber LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PO.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PO.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PO.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PO.IsObsolete = 0 AND PO.StatusId = 3
				AND PO.Id NOT IN (SELECT DISTINCT PO.Id FROM sPurchase.tPurchaseOrder PO
				INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.PurchaseOrderId = PO.Id AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
				INNER JOIN sPurchase.tGoodsReceivedNoteDetail GRND ON GRND.GoodsReceivedNoteId = GRN.Id AND GRND.PreviousGRNQty+GRND.ReceivedQty >= GRND.POQty
				WHERE Grn.PurchaseOrderId = PO.Id AND GRN.StatusId <> 4 AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0)
				AND ((CAST(PO.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PO.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
					)t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords AS TotalRecords

	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseOrderDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tPurchaseOrder
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId and IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tPurchaseOrderDetail WHERE PurchaseOrderId = @rId)
			BEGIN
				DELETE FROM sPurchase.tPurchaseOrderDetail
				WHERE PurchaseOrderId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseOrderGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		SELECT PO.Id,
			   PO.RefNumber,
			   PO.PurchaseRequestId,
			   PR.Number AS PurchaseRequestNumber,
			   PO.RequestedBy,
			   PO.StatusId,
			   PO.VendorId,
			   PO.OrgGroupId,
			   PO.PODate,
			   PO.BillToAddress,
			   PO.ShipToAddress,
			   PO.RequiredBy,
			   ISNULL(SM.Title,'') AS Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName
		FROM   [sPurchase].[tPurchaseOrder] PO(NOLOCK)
			   LEFT JOIN sProcurement.tVendorMaster  VM ON PO.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PO.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = PO.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  PO.Id = @rId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId

		SELECT POD.Id,
			   POD.PurchaseOrderId,
			   POD.PurchaseRequestDetailId,
			   POD.OrgGroupId,
			   POD.StockItemId,
			   POD.TotalQty,
			   POD.Remark,
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SCM.Title AS CategoryName,
			   SUMa.Id AS UnitTypeId,
			   SUMa.Code AS UOM
		FROM   [sPurchase].[tPurchaseOrderDetail] POD (NOLOCK)
			   INNER JOIN	sPurchase.tPurchaseOrder PO	ON PO.Id = POD.PurchaseOrderId AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = POD.StockItemId  AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  POD.PurchaseOrderId = @rId AND PO.IsObsolete = 0
		       AND PO.LocationId = @rStoreLocationId
			   AND PO.OrgGroupId = @rOrgGroupId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH

END










GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseOrderSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tPurchaseOrder PO (NOLOCK)

		WHERE
				((PO.RefNumber LIKE @rNumber+'%') OR (@rNumber = ''))
   				AND ((PO.RequestedBy LIKE @rName+'%') OR (@rName = ''))
   				AND ((PO.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PO.StatusId = @rStatusId) OR (@rStatusId=0))
				AND PO.IsObsolete = 0
				AND ((CAST(PO.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PO.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))

	    SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY PO.Id DESC
			) AS 'RowNum',PO.Id,
				PO.PurchaseRequestId,
				PO.RefNumber AS Number,
				PO.RequestedBy,
				PO.PODate,
				ISNULL(SM.Title,'') AS Status

		 FROM
				sPurchase.tPurchaseOrder PO (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON PO.StatusId = SM.Id


		 WHERE
				((PO.RefNumber LIKE @rNumber+'%') OR (@rNumber = ''))
   				AND ((PO.RequestedBy LIKE @rName+'%') OR (@rName = ''))
   				AND ((PO.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PO.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PO.StatusId = @rStatusId) OR (@rStatusId=0))
				AND PO.IsObsolete = 0
				AND ((CAST(PO.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PO.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
				)t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseRequestAdd]
		@rId BIGINT,
		@rRequestDate DATETIME,
		@rResourceId BIGINT,
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@rBranchId INT,
		@rStatusId SMALLINT,
		@rVendorId INT,
		@rUserId BIGINT,
		@rRequiredBy DATETIME,
		@rDetailList sPurchase.PurchaseRequestDetailType READONLY


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
			DECLARE @rStoreLocationId BIGINT
            SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	        FROM sConfig.tConfigurationSetup
	        WHERE ConfigurationId  = 542 AND SourceId = @rUserId
		IF(@rId > 0)
		BEGIN

		    IF NOT EXISTS(SELECT Id FROM sPurchase.tPurchaseRequest WHERE Id = @rId AND CreatedUserId = @rUserId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
				BEGIN
					SELECT -101
				END
			ELSE
			  BEGIN
				UPDATE sPurchase.tPurchaseRequest
				SET
					StatusId = @rStatusId,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = GETUTCDATE()
				WHERE Id = @rId AND IsObsolete = 0 AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tPurchaseRequestDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND PurchaseRequestId = @rId

				UPDATE sPurchase.tPurchaseRequestDetail
				SET
				OrgGroupId = @rOrgGroupId,
				PurchaseRequestId = @rId,
				StockItemId = DL.StockItemId,
				RequestedQty = DL.RequestedQty,
				Remark = DL.Remark,
				UpdatedUserId = @rUserId,
				UpdatedDateTime = GETUTCDATE()
				FROM @rDetailList DL
				INNER JOIN sPurchase.tPurchaseRequestDetail PR ON DL.ID = PR.Id
				WHERE PR.PurchaseRequestId = @rId AND PR.OrgGroupId = @rOrgGroupId

				DECLARE @lNextNumberPRQA BIGINT
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequestDetail',@lNextNumber = @lNextNumberPRQA OUTPUT
				SET @lNextNumberPRQA=@lNextNumberPRQA-1
				INSERT INTO sPurchase.tPurchaseRequestDetail
				(
					ID,
					OrgGroupId,
					PurchaseRequestId,
					StockItemId,
					RequestedQty,
					Remark,
					CreatedUserId,
					CreatedDateTime
				)
				SELECT	@lNextNumberPRQA+Id,
						@rOrgGroupId,
						@rId,
						StockItemId,
						RequestedQty,
						Remark,
						@rUserId,
						GETUTCDATE()
				FROM @rDetailList
				WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tPurchaseRequestDetail PR ON DL.ID = PR.Id
				WHERE PR.PurchaseRequestId = @rId AND PR.OrgGroupId = @rOrgGroupId)

				SET @lNextNumberPRQA=@lNextNumberPRQA+(SELECT Count(Id) FROM @rDetailList WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tPurchaseRequestDetail PR ON DL.ID = PR.Id
				WHERE PR.PurchaseRequestId = @rId))
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseRequestDetail', @rCurrentNumber = @lNextNumberPRQA

				SELECT @rId
			END
		END
		ELSE
		BEGIN
			IF NOT EXISTS(
            SELECT WFS.AutoId FROM [sWf].[tWfSetup] WFS
			WHERE WFS.[WfFunctionalityId] = 1 AND @rOrgGroupId = WFS.[OrgGroupId])
			BEGIN
				SELECT -102
			END
			ELSE
			BEGIN
			    IF(((SELECT EmployeeManagerId FROM [sHrm].[tEmployeeJobDetail] WHERE EmployeeId = (SELECT ISNULL(U.SourceId,U.Id) FROM sSecurity.tUser U WHERE U.Id = @rUserId)) IS NULL) AND EXISTS(SELECT WFS.WfTypeMasterId FROM [sWf].[tWfFunctionalityMaster] SFM INNER JOIN [sWf].[tWfSetup] WFS ON WFS.WfFunctionalityId = SFM.Id WHERE WFS.WfTypeMasterId = 2 AND WFS.WfLevel > 0 AND SFM.Id = 1))
				BEGIN
					SELECT -301;
				END
				ELSE
				BEGIN
					DECLARE @lNextNumber INT
					EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequest',@lNextNumber = @lNextNumber OUTPUT
					--SELECT @lNextNumber
					--DECLARE @loNextNumber NVARCHAR(20)
					--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
					--@rNextNumber = @loNextNumber OUTPUT
	 				INSERT INTO sPurchase.tPurchaseRequest
					(
						Id,
						Number,
						RequestDate,
						ResourceId,
						RequestedBy,
						OrgGroupId,
						BranchId,
						LocationId,
						StatusId,
						VendorId,
						RequiredBy,
						CreatedUserId,
						CreatedDateTime
					)
					VALUES
					(
						@lNextNumber,
						@lNextNumber,
						@rRequestDate,
						@rResourceId,
						@rRequestedBy,
						@rOrgGroupId,
						@rBranchId,
						@rStoreLocationId,
						@rStatusId,
						@rVendorId,
						@rRequiredBy,
						@rUserId,
						GETUTCDATE()
					)

					SET @rId = @lNextNumber
					DECLARE @lNextNumberPRQ BIGINT
					EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tPurchaseRequestDetail',@lNextNumber = @lNextNumberPRQ OUTPUT
					SET @lNextNumberPRQ=@lNextNumberPRQ-1

	 				INSERT INTO sPurchase.tPurchaseRequestDetail
					(
						Id,
						OrgGroupId,
						PurchaseRequestId,
						StockItemId,
						RequestedQty,
						Remark,
						CreatedUserId,
						CreatedDateTime
					)
					SELECT	@lNextNumberPRQ+Id,
							@rOrgGroupId,
							@rId,
							StockItemId,
							RequestedQty,
							Remark,
							@rUserId,
							GETUTCDATE()
					FROM @rDetailList
					SET @lNextNumberPRQ=@lNextNumberPRQ+(SELECT COUNT(Id) FROM @rDetailList)
					EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tPurchaseRequestDetail', @rCurrentNumber = @lNextNumberPRQ


					SELECT @rId

					DECLARE @typeId SMALLINT=0
					DECLARE @Level SMALLINT=0
					SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 1
					IF(@typeId = 1)--parallel
					BEGIN
						EXEC [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,1,'',0,0,1,@rOrgGroupId
					END
					ELSE IF(@typeId = 2)--sequencial
					BEGIN
						EXEC [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,1,'',1,@Level,1,@rOrgGroupId
					END
					ELSE IF(@typeId = 3)--auto approved
					BEGIN
						EXEC [sWf].[pWfApprovalAdd] 0,@rId,2040,@rUserId,3,'',0,0,1,@rOrgGroupId
					END

				END
			END
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pPurchaseRequestApprovedGet] 991100002
CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseRequestApprovedGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		SELECT PR.Id,
			   PR.Number,
			   PR.RequestedBy,
			   PR.StatusId,
			   QR.VendorId,
			   PR.BranchId,
			   PR.OrgGroupId,
			   PR.ResourceId,
			   PR.RequestDate,
			   PR.RequiredBy,
			   ISNULL(SM.Title,'') AS Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName
		FROM   [sPurchase].[tPurchaseRequest] PR (NOLOCK)
			   LEFT JOIN [sPurchase].[tQuotationRequest] QR ON QR.PurchaseRequestId = PR.Id AND QR.StatusId = 3 AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
			   LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		WHERE  PR.Id=@rId AND PR.IsObsolete = 0 AND PR.StatusId = 3
		       AND PR.LocationId = @rStoreLocationId
			   AND PR.OrgGroupId = @rOrgGroupId

		SELECT PRD.Id,
			   PRD.PurchaseRequestId,
			   PRD.OrgGroupId,
			   PRD.StockItemId,
			   PRD.RequestedQty,
			   PRD.Remark,
			   SIM.Code	AS StockItemCode,
			   SCM.Title AS CategoryName,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM
		FROM   [sPurchase].[tPurchaseRequestDetail] PRD (NOLOCK)
			   INNER JOIN	sPurchase.tPurchaseRequest PR	ON PR.Id = PRD.PurchaseRequestId AND PR.StatusId = 3 AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  PRD.PurchaseRequestId=@rId AND PR.IsObsolete = 0
		       AND PR.LocationId = @rStoreLocationId
			   AND PR.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH

END









GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pPurchaseRequestApprovedSearchGet] '','',9911,'2021-01-01','2024-12-11',1,10,null
CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseRequestApprovedSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tPurchaseRequest PR (NOLOCK)

		WHERE
				((PR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
				AND ((PR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0 AND PR.StatusId = 3
				AND ((CAST(PR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))


		SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY PR.Id DESC
			) AS 'RowNum',PR.Id,
				PR.Number,
				PR.RequestedBy,
				PR.RequestDate,
				ISNULL(SM.Title,'') AS Status

	    FROM
				sPurchase.tPurchaseRequest PR (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON PR.StatusId = SM.Id


        WHERE
				((PR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
				AND ((PR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0 AND PR.StatusId = 3
				AND ((CAST(PR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')='')))t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseRequestDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tPurchaseRequest
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GetUtcDate()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tPurchaseRequestDetail WHERE PurchaseRequestId = @rId)
			BEGIN
				DELETE FROM sPurchase.tPurchaseRequestDetail
				WHERE PurchaseRequestId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pPurchaseRequestGet] 991100003
CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseRequestGet]
	  @rUserId BIGINT,
	  @rId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		SELECT  PR.Id,
				PR.Number,
				PR.RequestedBy,
				PR.StatusId,
				PR.VendorId,
				PR.BranchId,
				PR.OrgGroupId,
				PR.ResourceId,
				PR.RequestDate,
				PR.RequiredBy,
				ISNULL(SM.Title,'') AS Status,
				VM.Code AS VendorCode,
				VM.Title AS VendorName
		FROM    [sPurchase].[tPurchaseRequest] PR (NOLOCK)
			    LEFT JOIN sProcurement.tVendorMaster  VM ON PR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = PR.StatusId
		WHERE   PR.Id=@rId AND PR.IsObsolete = 0
				AND PR.LocationId = @rStoreLocationId
				AND PR.OrgGroupId = @rOrgGroupId

		SELECT PRD.Id,
			   PRD.PurchaseRequestId,
			   PRD.OrgGroupId,
			   PRD.StockItemId,
			   PRD.RequestedQty,
			   PRD.Remark,
			   SIM.Code	AS StockItemCode,
			   SCM.Title AS CategoryName,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM
		FROM   [sPurchase].[tPurchaseRequestDetail] PRD (NOLOCK)
			   INNER JOIN	sPurchase.tPurchaseRequest PR	ON PR.Id = PRD.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = PRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  PRD.PurchaseRequestId=@rId AND PR.IsObsolete = 0
		       AND PR.LocationId = @rStoreLocationId
		       AND PR.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH

END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pPurchaseRequestPOApprovedSearchGet] '',991100001,'',9911,'2023-01-01','2023-12-18',1,10,null
CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseRequestPOApprovedSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(DISTINCT PR.Id) FROM sPurchase.tPurchaseRequest PR (NOLOCK)
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON PR.StatusId = SM.Id
		INNER JOIN [sPurchase].[tQuotationRequest] QR ON QR.PurchaseRequestId = PR.Id AND QR.StatusId = 3 AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0

		WHERE
				((PR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0 AND PR.StatusId = 3
				AND ((CAST(PR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))


		SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY PR.Id DESC
			) AS 'RowNum',PR.Id,
				PR.Number,
				PR.RequestedBy,
				PR.RequestDate,
				ISNULL(SM.Title,'') AS Status,
				VM.Id AS VendorId,
				VM.Code AS VendorCode,
				VM.Title AS VendorName
	    FROM
				sPurchase.tPurchaseRequest PR (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON PR.StatusId = SM.Id
				INNER JOIN [sPurchase].[tQuotationRequest] QR ON QR.PurchaseRequestId = PR.Id AND QR.StatusId = 3 AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
			    LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0

        WHERE
				((PR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0 AND PR.StatusId = 3
				--AND Pr.Id in (SELECT DISTINCT PR.Id FROM sPurchase.tPurchaseRequest PR
				--INNER JOIN [sPurchase].[tQuotationRequest] QR ON QR.PurchaseRequestId = PR.Id AND QR.StatusId = 3)
				AND ((CAST(PR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')='')))t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)



        SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pPurchaseRequestSearchGet] '',9911000000065,'',9911,'2024-01-07','2024-01-30',1,10,0
CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseRequestSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rUserId BIGINT,
	@rName NVARCHAR  = '',
	@rOrgGroupId INT,
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tPurchaseRequest PR (NOLOCK)

		WHERE
				((PR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
   				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0
				AND ((CAST(PR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))


	    SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY PR.Id DESC
			) AS 'RowNum',PR.Id,
				PR.Number,
				PR.RequestedBy,
				PR.RequestDate,
				ISNULL(SM.Title,'') AS Status

        FROM
				sPurchase.tPurchaseRequest PR (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON PR.StatusId = SM.Id

        WHERE
				((PR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((PR.RequestedBy LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((PR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
   				AND ((PR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND PR.IsObsolete = 0
				AND ((CAST(PR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(PR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
					)t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [sPurchase].[pPurchaseScreenGet]
CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseScreenGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		SELECT
			S.Id			AS ScreenId,
			S.Title		AS ScreenTitle,
			S.TaskId		AS TaskId,
			S.Page		As PageUrl,
			S.IsObsolete	AS ScreenIsObsolete,
			S.Title,
			S.Page,
			SG.Id AS ScreenGroupId,
			ISNULL(SG.Title,'') AS ScreenGroupName

		FROM
			sSecurity.tScreen S (NOLOCK)
		LEFT JOIN sSecurity.tScreenGroupMaster SG ON SG.Id=S.ScreenGroupId
		WHERE
			S.IsObsolete = 0 AND S.ScreenGroupID=254 AND S.Id IN (31296,31297,31298,31299,31300,31301,31310,31311,31312,31317)
		ORDER BY S.OrderIndex
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseStatusGet]
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT Id,
			   Title
		FROM   [sWf].[tWfStatusMaster] (NOLOCK)
		WHERE  IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH

END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pPurchaseStoreLocationMasterGet] 9911
CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseStoreLocationMasterGet]
	@rOrgGroupId INT,
	@rUserId BIGINT
	--@rIsWildCardSearch [bit] = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
		SELECT        SLM.Id,
					  SLM.Title,
					  SLM.OrgGroupId,
					  SLM.IsObsolete,
					  UA.UserId
		FROM          sIp.tStoreLocationMaster AS SLM
		INNER JOIN    sSecurity.tUserAccess AS UA ON UA.SourceId = SLM.Id AND UA.SourceTypeId = 1014
					  AND SLM.IsObsolete = 0 AND SLM.OrgGroupId=@rOrgGroupId AND UA.UserId = @rUserId
		Order by SLM.Title
	 END TRY
	 BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT
		   @ErrorMessage = ERROR_MESSAGE(),
		   @ErrorSeverity = ERROR_SEVERITY(),
		   @ErrorState = ERROR_STATE();

		RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END

SET ANSI_NULLS ON


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pPurchaseVendorMasterGet] 9911,0,'','',0,9911000000270
CREATE OR ALTER PROCEDURE [sPurchase].[pPurchaseVendorMasterGet]
	@rOrgGroupId INT,
	@rId INT = 0,
	@rTitle NVARCHAR(300) = '',
	--@rIsWildCardSearch [bit] = 1,
	@rCode NVARCHAR(20) = '',
	@rVendorCategoryId INT = 0,
	@rUserId BIGINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN
	BEGIN TRY
			DECLARE @rStoreLocationId BIGINT
			SELECT @rStoreLocationId = ISNULL(ItemValue,0)
			FROM sConfig.tConfigurationSetup 
			WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		 --IF @rIsWildCardSearch = 1
		 --BEGIN
			 SET @rCode = sCommon.fSearchStringGet(@rCode)
		 --END
		     SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
	     SELECT 
		  
		    VM.Id,
			VM.Code,
			VM.Title,
			VM.IsObsolete,
			VM.CreatedUserId,
			VM.CreatedDateTime,
			VM.UpdatedUserId,
			VM.UpdatedDateTime,
			--VM.Area,
			--VM.City,
			VM.ContactPersonName,
			--VM.Country,
			ISNULL(VM.CreditDays, 0) CreditDays,
			ISNULL(CAST(VM.CreditLimit AS DECIMAL(18, 2)), '0') CreditLimit,
			--VM.CreditLimit,
			VM.Email,
			VM.FaxNumber,			
			VM.PhoneNumberMobile,
			VM.PhoneNumberOffice,			
			--VM.State,
			VM.StreetFour,
			VM.StreetOne,
			VM.StreetThree,
			VM.StreetTwo,			
			VM.VendorCategoryId,
			VM.ZipCode,
			VC.Title VendorCategory,
			VM.State STATETITLE,
			VM.City CITYTITLE,
			VM.Country COUNTRYTITLE,
			VM.Area Area,
			VM.LocationID		
					
	   FROM sProcurement.tVendorMaster  VM (NOLOCK)
	   LEFT JOIN   sProcurement.tVendorCategoryMaster VC
	   ON  VM.VendorCategoryId = VC.Id  
	   --LEFT JOIN  sCommon.tStateMaster SM 
	   --ON VM.StateId = SM.Id 
	   --LEFT JOIN   sCommon.tCityMaster CM 
	   --ON VM.CityId = CM.Id 
	   --LEFT JOIN    sCommon.tAreaMaster AM 
	   --ON VM.AreaId = AM.Id 
	   --LEFT JOIN   sCommon.tCountryMaster CAM
	   --ON VM.CountryId = CAM.Id 		     
	   WHERE ((VM.Id = @rId) OR (@rId = 0))
	   AND	((VM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND ((VM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((VM.VendorCategoryId = @rVendorCategoryId) OR (@rVendorCategoryId = 0))
	   AND  VM.OrgGroupId = @rOrgGroupId
	   AND VM.IsObsolete = 0 
	   AND VM.LocationId = @rStoreLocationId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  
    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sPurchase].[pQualityCheckAdd]
		@rId BIGINT,
		@rGoodsReceivedNoteId BIGINT,
		@rPurchaseOrderId BIGINT,
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@rStatusId SMALLINT,	
		@rUserId BIGINT,
		@rDetailList sPurchase.QualityCheckDetailType READONLY
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup 
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		   IF NOT EXISTS(SELECT Id FROM sPurchase.tQualityCheck WHERE Id = @rId AND CreatedUserId = @rUserId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
		   BEGIN
		   SELECT -102
		   END
		   ELSE
		    BEGIN
			IF NOT EXISTS(SELECT SR.Id 
			FROM [sPurchase].[tSalesReturn] SR
			INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON SR.GoodsReceivedNoteId = GRN.Id  AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			INNER JOIN [sPurchase].[tQualityCheck] QC ON GRN.Id = QC.GoodsReceivedNoteId  AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
			WHERE QC.Id = @rId  AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0)
			BEGIN
				--CREATE TABLE #temp_table (
				--	OrgGroupId SMALLINT,
				--	StockItemId BIGINT,
				--	AcceptedQty DECIMAL(12,2),
				--	Operation NVARCHAR(20),
				--	UserId BIGINT
				--);

				--INSERT INTO #temp_table
				--SELECT QCD.OrgGroupId,QCD.StockItemId,
				--CASE
				--WHEN QCD.AcceptedQty > DL.AcceptedQty THEN QCD.AcceptedQty - DL.AcceptedQty
				--ELSE DL.AcceptedQty - QCD.AcceptedQty
				--END,
				--CASE
				--WHEN QCD.AcceptedQty > DL.AcceptedQty THEN '-'
				--ELSE '+'
				--END,
				--@rUserId 
				--FROM sPurchase.tQualityCheckDetail QCD
				--INNER JOIN @rDetailList DL ON DL.StockItemId = QCD.StockItemId AND QCD.QualityCheckId = @rId
				--WHERE DL.StockItemId = QCD.StockItemId AND QCD.QualityCheckId = @rId

				UPDATE sPurchase.tQualityCheck
				SET 
					StatusId = @rStatusId,
					GoodsReceivedNoteId = @rGoodsReceivedNoteId,
					PurchaseOrderId = @rPurchaseOrderId,
					UpdatedUserId = @rUserId,		
					UpdatedDateTime = GETUTCDATE()
				WHERE Id = @rId  AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tQualityCheckDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND QualityCheckId = @rId AND OrgGroupId = @rOrgGroupId

				UPDATE sPurchase.tQualityCheckDetail
				SET
				GoodsReceivedNoteDetailId = DL.GoodsReceivedNoteDetailId,
				StockItemId = DL.StockItemId,
				POQty = DL.POQty,
				ReceivedQty = DL.ReceivedQty,
				AcceptedQty = DL.AcceptedQty,
				RejectedQty = DL.RejectedQty,
				ReasonForRejection = DL.ReasonForRejection,
				UpdatedUserId = @rUserId,
				UpdatedDateTime = GETUTCDATE()
				FROM @rDetailList DL
				INNER JOIN sPurchase.tQualityCheckDetail QC ON DL.ID = QC.Id AND QC.OrgGroupId = @rOrgGroupId
				WHERE QC.QualityCheckId = @rId AND QC.OrgGroupId = @rOrgGroupId

				DECLARE @lNextNumberQCD BIGINT	 
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheckDetail',@lNextNumber = @lNextNumberQCD OUTPUT
				SET @lNextNumberQCD=@lNextNumberQCD-1
				INSERT INTO sPurchase.tQualityCheckDetail
				(
					Id,
					OrgGroupId,
					QualityCheckId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					CreatedUserId,
					CreatedDateTime
				)
				SELECT	@lNextNumberQCD+Id,
						@rOrgGroupId,
						@rId,
						GoodsReceivedNoteDetailId,
						StockItemId,
						POQty,
						ReceivedQty,
						AcceptedQty,
						RejectedQty,
						ReasonForRejection,
						@rUserId, 
						GETUTCDATE() 
				FROM @rDetailList
				WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tQualityCheckDetail QC ON DL.ID = QC.Id AND QC.OrgGroupId = @rOrgGroupId
				WHERE QC.QualityCheckId = @rId AND QC.OrgGroupId = @rOrgGroupId)

				SET @lNextNumberQCD=@lNextNumberQCD+(SELECT COUNT(Id) FROM @rDetailList WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tQualityCheckDetail QC ON DL.ID = QC.Id AND QC.OrgGroupId = @rOrgGroupId
				WHERE QC.QualityCheckId = @rId AND QC.OrgGroupId = @rOrgGroupId))
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQualityCheckDetail', @rCurrentNumber = @lNextNumberQCD
				
				--declare @AcceptedQty decimal = 0
				--Select @AcceptedQty =(Select ISNULL(Sum(SB.AvailableQuantity),0) FROM sProcurement.tStockBatch SB
				--INNER JOIN #temp_table tt ON SB.StockItemId = tt.StockItemId AND tt.Operation = '+'
				--Group by tt.AcceptedQty) -(Select distinct tt1.AcceptedQty
				--FROM sProcurement.tStockBatch SB
				--INNER JOIN #temp_table tt1 ON SB.StockItemId = tt1.StockItemId AND tt1.Operation = '+')

				--UPDATE  sProcurement.tStockBatch
				--SET  AvailableQuantity = AvailableQuantity + @AcceptedQty,
				--	UpdatedUserId = @rUserId,
				--	UpdatedDateTime = sCommon.fGetDate()
				--	where @AcceptedQty > 0
				
				--WHERE  
				
				--(SB.StockItemId = tt.StockItemId) AND
				----(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
				----(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
				--	SB.OrgGroupId = @rOrgGroupId
				--	AND tt.Operation = '+'
				--Select @AcceptedQty =(Select ISNULL(Sum(SB.AvailableQuantity),0) FROM sProcurement.tStockBatch SB
				--INNER JOIN #temp_table tt ON SB.StockItemId = tt.StockItemId AND tt.Operation = '-'
				--Group by tt.AcceptedQty) -(Select distinct tt1.AcceptedQty
				--FROM sProcurement.tStockBatch SB
				--INNER JOIN #temp_table tt1 ON SB.StockItemId = tt1.StockItemId AND tt1.Operation = '-')

				--UPDATE  sProcurement.tStockBatch
				--SET  AvailableQuantity = AvailableQuantity - @AcceptedQty,
				--	UpdatedUserId = @rUserId,
				--	UpdatedDateTime = sCommon.fGetDate()
				--	where @AcceptedQty > 0
				--WHERE  
				
				--(SB.StockItemId = tt.StockItemId) AND
				----(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
				----(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
				--	SB.OrgGroupId = @rOrgGroupId
				--	AND tt.Operation = '-'

				SELECT @rId
			END
			SELECT -101
		END
		    END
		ELSE
		BEGIN
			IF NOT EXISTS(SELECT SR.Id 
			FROM [sPurchase].[tSalesReturn] SR
			INNER JOIN [sPurchase].[tGoodsReceivedNote] GRN ON SR.GoodsReceivedNoteId = GRN.Id 
			AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
			INNER JOIN [sPurchase].[tQualityCheck] QC ON GRN.Id = QC.GoodsReceivedNoteId 
			AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId AND QC.IsObsolete = 0
			WHERE QC.Id = @rId)
			BEGIN

				DECLARE @lNextNumber INT	 
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheck',@lNextNumber = @lNextNumber OUTPUT	
				---------------select @lNextNumber
				--DECLARE @loNextNumber nVarchar(20)
				--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
				---------------@rNextNumber = @loNextNumber OUTPUT

	 			INSERT INTO sPurchase.tQualityCheck
				(
					Id,
					QCNumber,
					GoodsReceivedNoteId,
					PurchaseOrderId,
					RequestedBy, 
					OrgGroupId,
					LocationId, 			 
					StatusId,
					CreatedUserId,		
					CreatedDateTime
	
				)
				VALUES
				(
					@lNextNumber,
					@lNextNumber,
					@rGoodsReceivedNoteId,
					@rPurchaseOrderId,
					@rRequestedBy,	 
					@rOrgGroupId,
					@rStoreLocationId, 		 
					@rStatusId,
					@rUserId,		
					GETUTCDATE()
				)
 
				SET @rId = @lNextNumber  
			
				DECLARE @lNextNumberQCDD BIGINT	 
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQualityCheckDetail',@lNextNumber = @lNextNumberQCDD OUTPUT	
				SET @lNextNumberQCDD=@lNextNumberQCDD-1

	 			INSERT INTO sPurchase.tQualityCheckDetail
				(
					Id,
					OrgGroupId,
					QualityCheckId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					AcceptedQty,
					RejectedQty,
					ReasonForRejection,
					CreatedUserId,
					CreatedDateTime
				)
				SELECT	@lNextNumberQCDD+Id,
						@rOrgGroupId,
						@rId,
						GoodsReceivedNoteDetailId,
						StockItemId,
						POQty,
						ReceivedQty,
						AcceptedQty,
						RejectedQty,
						ReasonForRejection,
						@rUserId, 
						GETUTCDATE() 
				FROM @rDetailList
						
				SET @lNextNumberQCDD=@lNextNumberQCDD+(SELECT COUNT(Id) FROM @rDetailList)
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQualityCheckDetail', @rCurrentNumber = @lNextNumberQCDD
				
				
				--inward insert entry
				DECLARE @XmlString XML;
 
				SET @XmlString = (
 					SELECT 
 						   QCD.GoodsReceivedNoteDetailId AS '@StockInwardRequestDetailId',
 						   QCD.StockItemId AS '@StockItemId',
 						   SIM.Title				AS '@StockItemName',
 						   --NULL AS ItemBatch,
 						   --NULL AS ItemExpiryDate,
 						   QCD.AcceptedQty AS '@InwardQuantity',
 						   0 AS '@RequestedQuantity',
 						   GRND.UnitPrice AS '@InwardValue'
 					FROM   [sPurchase].[tQualityCheckDetail] QCD (NOLOCK)
 						   INNER JOIN	sPurchase.tQualityCheck QC	ON QC.Id = QCD.QualityCheckId AND QC.IsObsolete = 0
 						   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId 
 						   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
 						   LEFT JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
 						   LEFT JOIN [sPurchase].[tGoodsReceivedNoteDetail] GRND ON GRND.ID = QCD.GoodsReceivedNoteDetailId
 					WHERE  QC.Id = @rId
 					--FOR XML AUTO, ROOT('Table'), ELEMENTS
 					FOR XML PATH('StockInward'), ROOT('Table')
 				);

				SELECT @rId
				-- Print or use @XmlString as needed
				--PRINT CONVERT(NVARCHAR(MAX), @XmlString);
				DECLARE @str NVARCHAR(MAX) = CAST(@XmlString AS NVARCHAR(MAX))
				DECLARE @inwardDate DATETIME 
				SET @inwardDate = GETUTCDATE()
				DECLARE @result INT 
				EXEC sProcurement.pStockInwardAdd_New @rOrgGroupId,'',0,@rRequestedBy,@rStoreLocationId,'Inward By Quality Check',@rUserId,@str,@rStoreLocationId,@rOrgGroupId,0,@inwardDate,NULL
				
				--declare @AcceptedQtyResult decimal = 0
				--Select @AcceptedQtyResult = (Select distinct QC1.AcceptedQty FROM sProcurement.tStockBatch SB
				--	INNER JOIN sPurchase.tQualityCheckDetail QC1 ON SB.StockItemId = QC1.StockItemId AND QC1.QualityCheckId = @rId)

				--UPDATE  sProcurement.tStockBatch
				--	SET  AvailableQuantity = AvailableQuantity + @AcceptedQtyResult,
				--		UpdatedUserId = @rUserId,
				--		UpdatedDateTime = sCommon.fGetDate()
				--	WHERE  @AcceptedQtyResult > 0
				

				--(SB.StockItemId = QC.StockItemId) AND
				--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
				--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
					--SB.OrgGroupId = @rOrgGroupId AND QualityCheckId = @rId

				
			END
			SELECT -101;
		END
	COMMIT TRANSACTION	
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    
    DECLARE @ErrorMessage NVARCHAR(4000);  
    DECLARE @ErrorSeverity INT;  
    DECLARE @ErrorState INT;  

    SELECT   
       @ErrorMessage = ERROR_MESSAGE(),  
       @ErrorSeverity = ERROR_SEVERITY(),  
       @ErrorState = ERROR_STATE();  

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);  
    
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sPurchase].[pQualityCheckDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tQualityCheck
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tQualityCheckDetail WHERE QualityCheckId = @rId)
			BEGIN
				DELETE FROM sPurchase.tQualityCheckDetail
				WHERE QualityCheckId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pQualityCheckGet] 991100001
CREATE OR ALTER PROCEDURE [sPurchase].[pQualityCheckGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		SELECT  QC.Id,
				QC.QCNumber,
				QC.OrgGroupId,
				QC.GoodsReceivedNoteId,
				QC.PurchaseOrderId,
				QC.RequestedBy,
				ISNULL(GRN.GRNNumber,'') AS GRNNumber,
				QC.StatusId,
				ISNULL(SM.Title,'') AS Status
		FROM   [sPurchase].[tQualityCheck] QC(NOLOCK)
		LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = QC.GoodsReceivedNoteID
		AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QC.StatusId
		WHERE  QC.Id=@rId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId

		SELECT QCD.Id,
			   QCD.QualityCheckId,
			   QCD.GoodsReceivedNoteDetailId,
			   QCD.OrgGroupId,
			   SUMa.Id AS UnitTypeId,
			   QCD.StockItemId,
			   QCD.POQty,
				CASE
					WHEN (SELECT Count(*) FROM sPurchase.tQualityCheck QCC WHERE QCC.GoodsReceivedNoteId = QC.GoodsReceivedNoteId
					AND QCC.LocationId = @rStoreLocationId AND QCC.OrgGroupId = @rOrgGroupId AND QCC.IsObsolete = 0  AND QCC.StatusId <> 4) = 1 THEN
						(SELECT GRND.ReceivedQty  FROM [sPurchase].[tGoodsReceivedNoteDetail] GRND
								   WHERE GRND.Id = QCD.GoodsReceivedNoteDetailId
								   AND GRND.GoodsReceivedNoteId = QC.GoodsReceivedNoteId)
					ELSE
						((SELECT GRND.ReceivedQty  FROM [sPurchase].[tGoodsReceivedNoteDetail] GRND
								   WHERE GRND.Id = QCD.GoodsReceivedNoteDetailId
								   AND GRND.GoodsReceivedNoteId = QC.GoodsReceivedNoteId)-
						(SELECT SUM(ISNULL(QCD1.AcceptedQty,0) + ISNULL(QCD1.RejectedQty,0))
						FROM [sPurchase].[tQualityCheckDetail] QCD1
						INNER JOIN	sPurchase.tQualityCheck QC1	ON QC1.Id = QCD1.QualityCheckId AND QC1.GoodsReceivedNoteId = QC.GoodsReceivedNoteID
						AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0
						WHERE QC1.GoodsReceivedNoteId = QC.GoodsReceivedNoteID AND QCD1.StockItemId = QCD.StockItemId AND QC1.IsObsolete = 0
						AND QC1.LocationId = @rStoreLocationId AND QC1.OrgGroupId = @rOrgGroupId
						GROUP BY QCD1.StockItemId))+((SELECT SUM(ISNULL(QCD2.AcceptedQty,0) + ISNULL(QCD2.RejectedQty,0))
						FROM [sPurchase].[tQualityCheckDetail] QCD2
						WHERE QCD2.Id = QCD.Id
						GROUP BY QCD2.Id))
					END
				AS ReceivedQty,
			   QCD.AcceptedQty,
			   QCD.RejectedQty,
			   QCD.ReasonForRejection,
			   SCM.Id AS CategoryId,
			   SCM.Title AS CategoryName,
			   0 AS SubCategoryId,
			   SIM.Code				AS StockItemCode,
			   SIM.Title				AS StockItemName,
			   SUMa.Code				AS UOM
		FROM   [sPurchase].[tQualityCheckDetail] QCD (NOLOCK)
			   INNER JOIN	sPurchase.tQualityCheck QC	ON QC.Id = QCD.QualityCheckId  AND QC.IsObsolete = 0
			   AND QC.LocationId = @rStoreLocationId AND QC.OrgGroupId = @rOrgGroupId
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QCD.StockItemId  AND SIM.IsObsolete = 0
			   AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QCD.QualityCheckId=@rId AND QC.IsObsolete = 0
		       AND QC.LocationId = @rStoreLocationId
			   AND QC.OrgGroupId = @rOrgGroupId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pQualityCheckSearchGet] null,991100001,null,9911,null,null,1,10,null
CREATE OR ALTER PROCEDURE [sPurchase].[pQualityCheckSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tQualityCheck QC (NOLOCK)

		WHERE
				((QC.QCNumber LIKE @rNumber+'%') OR (@rNumber = ''))
   				AND ((QC.RequestedBy LIKE @rName+'%') OR (@rName = ''))
   				AND ((QC.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QC.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((QC.StatusId = @rStatusId) OR (@rStatusId=0))
				AND QC.IsObsolete = 0
				AND ((CAST(QC.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(QC.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))

		SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY QC.Id DESC
			) AS 'RowNum',QC.Id,
				QC.QCNumber AS Number,
				QC.RequestedBy,
				ISNULL(SM.Title,'') AS Status

        FROM
				sPurchase.tQualityCheck QC (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON QC.StatusId = SM.Id


	    WHERE
				((QC.QCNumber LIKE @rNumber+'%') OR (@rNumber = ''))
   				AND ((QC.RequestedBy LIKE @rName+'%') OR (@rName = ''))
   				AND ((QC.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QC.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((QC.StatusId = @rStatusId) OR (@rStatusId=0))
				AND QC.IsObsolete = 0
				AND ((CAST(QC.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(QC.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
					)t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec sPurchase.pQuotationApprovedVendorGet 991100002,991100001,9911
CREATE OR ALTER PROCEDURE [sPurchase].[pQuotationApprovedVendorGet]
	@rPurchaseRequestId BIGINT = 0,
	@rOrgGroupId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		SELECT
		        QR.Id,
		        QR.Number,
				QR.Name,
				QR.PurchaseRequestId,
				QR.VendorId,
				ISNULL(VM.Title,'') AS VendorName,
				ISNULL(VM.Code,'') AS VendorCode

	    FROM
				sPurchase.tPurchaseRequest PR  (NOLOCK)
				INNER JOIN sPurchase.tQuotationRequest QR ON QR.PurchaseRequestId = PR.Id AND QR.StatusId = 3
				LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID


        WHERE
   				((PR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((PR.Id = @rPurchaseRequestId) OR (ISNULL(@rPurchaseRequestId,0)=0))
				AND PR.IsObsolete = 0 AND PR.StatusId = 3 AND QR.IsObsolete = 0

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE OR ALTER PROCEDURE [sPurchase].[pQuotationRequestAdd]
		@rId BIGINT,
		@rOrgGroupId SMALLINT,
		@rBranchId INT,
		@rPurchaseRequestId BIGINT,
		@rName VARCHAR(100),
		@rRFQDate DATETIME,
		@rDescription NVARCHAR(300),
		@rStartDate DATETIME,
		@rEndDate DATETIME,
		@rBidOpen NVARCHAR(50),
		@rBidClose NVARCHAR(50),
		@rPersonContact NVARCHAR(50),
		@rEmail NVARCHAR(50),
		@rSendToVendor BIT,
		@rStatusId SMALLINT,
		@rVendorId INT,
		@rUserId BIGINT,
		@rDetailList sPurchase.QuotationRequestDetailType READONLY

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
        DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		  IF NOT EXISTS(SELECT Id FROM sPurchase.tQuotationRequest WHERE Id = @rId AND CreatedUserId = @rUserId
				AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
		    BEGIN
				SELECT -103
		    END
		  ELSE
		    BEGIN
				UPDATE sPurchase.tQuotationRequest
				SET
					OrgGroupId =@rOrgGroupId,
					BranchId =@rBranchId,
					PurchaseRequestId =@rPurchaseRequestId,
					Name =@rName,
					RFQDate =@rRFQDate,
					Description =@rDescription,
					StartDate =@rStartDate,
					EndDate =@rEndDate,
					BidOpen =@rBidOpen,
					BidClose =@rBidClose,
					PersonContact =@rPersonContact,
					Email =@rEmail,
					SendToVendor =@rSendToVendor,
					StatusId =@rStatusId,
					VendorId =@rVendorId,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = GetUtcDate()
				WHERE Id = @rId  AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tQuotationRequestDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND QuotationRequestId = @rId AND OrgGroupId = @rOrgGroupId

				UPDATE sPurchase.tQuotationRequestDetail
				SET
				OrgGroupId = @rOrgGroupId,
				QuotationRequestId = @rId,
				PurchaseRequestDetailId = DL.PurchaseRequestDetailId,
				StockItemId = DL.StockItemId,
				RequestedQty = DL.RequestedQty,
				Remark = DL.Remark,
				TargetPrice = DL.TargetPrice,
				UpdatedUserId = @rUserId,
				UpdatedDateTime = GETUTCDATE()
				FROM @rDetailList DL
				INNER JOIN sPurchase.tQuotationRequestDetail QR ON DL.ID = QR.Id
				WHERE QR.QuotationRequestId = @rId AND QR.OrgGroupId = @rOrgGroupId

				DECLARE @lNextNumberQRDA BIGINT
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequestDetail',@lNextNumber = @lNextNumberQRDA output
				SET @lNextNumberQRDA=@lNextNumberQRDA-1
				INSERT INTO sPurchase.tQuotationRequestDetail
				(
					Id,
					OrgGroupId,
					QuotationRequestId,
					PurchaseRequestDetailId,
					StockItemId,
					RequestedQty,
					Remark,
					TargetPrice,
					CreatedUserId,
					CreatedDateTime
				)
				SELECT	@lNextNumberQRDA+Id,
						@rOrgGroupId,
						@rId,
						PurchaseRequestDetailId,
						StockItemId,
						RequestedQty,
						Remark,
						TargetPrice,
						@rUserId,
						GETUTCDATE()
				FROM @rDetailList
				WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tQuotationRequestDetail QR ON DL.ID = QR.Id AND QR.OrgGroupId = @rOrgGroupId
				WHERE QR.QuotationRequestId = @rId AND QR.OrgGroupId = @rOrgGroupId)
				SET @lNextNumberQRDA=@lNextNumberQRDA+(SELECT COUNT(Id) FROM @rDetailList WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tQuotationRequestDetail QR ON DL.ID = QR.Id AND QR.OrgGroupId = @rOrgGroupId
				WHERE QR.QuotationRequestId = @rId AND QR.OrgGroupId = @rOrgGroupId))
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQuotationRequestDetail', @rCurrentNumber = @lNextNumberQRDA

				SELECT @rId
			END
		END
		ELSE
		BEGIN
			IF NOT EXISTS(
                SELECT WFS.AutoId FROM [sWf].[tWfSetup] WFS
				WHERE WFS.[WfFunctionalityId] = 2 AND @rOrgGroupId = WFS.[OrgGroupId])
				BEGIN
					SELECT -102
				END
			ELSE
			    BEGIN
			    IF(((SELECT EmployeeManagerId FROM [sHrm].[tEmployeeJobDetail] WHERE EmployeeId = (SELECT ISNULL(U.SourceId,U.Id) FROM sSecurity.tUser U WHERE U.Id = @rUserId)) IS NULL) AND EXISTS(SELECT WFS.WfTypeMasterId FROM [sWf].[tWfFunctionalityMaster] SFM INNER JOIN [sWf].[tWfSetup] WFS ON WFS.WfFunctionalityId = SFM.Id WHERE WFS.WfTypeMasterId = 2 AND WFS.WfLevel > 0 AND SFM.Id = 2))
				BEGIN
					SELECT -301;
				END
				ELSE
				BEGIN
						DECLARE @lNextNumber INT
						EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequest',@lNextNumber = @lNextNumber OUTPUT
						-------------select @lNextNumber
						--DECLARE @loNextNumber nVarchar(20)
						--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
						-------------@rNextNumber = @loNextNumber OUTPUT
						IF NOT EXISTS(SELECT * FROM sPurchase.tQuotationRequest WHERE PurchaseRequestId = @rPurchaseRequestId AND VendorId = @rVendorId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
						BEGIN
							INSERT INTO sPurchase.tQuotationRequest
							(
								Id,
								Number,
								OrgGroupId,
								BranchId,
								LocationId,
								PurchaseRequestId,
								Name,
								RFQDate,
								Description,
								StartDate,
								EndDate,
								BidOpen,
								BidClose,
								PersonContact,
								Email,
								SendToVendor,
								StatusId,
								VendorId,
								CreatedUserId,
								CreatedDateTime

							)
							VALUES
							(
								@lNextNumber,
								@lNextNumber,
								@rOrgGroupId,
								@rBranchId ,
								@rStoreLocationId,
								@rPurchaseRequestId,
								@rName,
								@rRFQDate,
								@rDescription,
								@rStartDate,
								@rEndDate ,
								@rBidOpen ,
								@rBidClose,
								@rPersonContact,
								@rEmail,
								@rSendToVendor,
								@rStatusId,
								@rVendorId ,
								@rUserId,
								GETUTCDATE()
							)

							SET @rId = @lNextNumber

							DECLARE @lNextNumberQRD BIGINT
							EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tQuotationRequestDetail',@lNextNumber = @lNextNumberQRD OUTPUT
							SET @lNextNumberQRD=@lNextNumberQRD+1

							INSERT INTO sPurchase.tQuotationRequestDetail
							(
								Id,
								OrgGroupId,
								QuotationRequestId,
								PurchaseRequestDetailId,
								StockItemId,
								RequestedQty,
								Remark,
								TargetPrice,
								CreatedUserId,
								CreatedDateTime
							)
							SELECT	@lNextNumberQRD+Id,
									@rOrgGroupId,
									@rId,
									PurchaseRequestDetailId,
									StockItemId,
									RequestedQty,
									Remark,
									TargetPrice,
									@rUserId,
									GETUTCDATE()
							FROM @rDetailList
							SET @lNextNumberQRD=@lNextNumberQRD+(SELECT COUNT(Id) FROM @rDetailList)
							EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tQuotationRequestDetail', @rCurrentNumber = @lNextNumberQRD


							SELECT @rId

							DECLARE @typeId SMALLINT=0
							DECLARE @Level SMALLINT=0
							SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 2
							IF(@typeId = 1)--parallel
							BEGIN
								EXEC [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,1,'',0,0,2,@rOrgGroupId
							END
							ELSE IF(@typeId = 2)--sequencial
							BEGIN
								EXEC [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,1,'',1,@Level,2,@rOrgGroupId
							END
							ELSE IF(@typeId = 3)--auto approved
							BEGIN
								EXEC [sWf].[pWfApprovalAdd] 0,@rId,2041,@rUserId,3,'',0,0,2,@rOrgGroupId
							END
						END
						ELSE
						BEGIN
							SELECT -101;
						END

				END
				END
		  END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sPurchase].[pQuotationRequestDelete]
		@rId BIGINT,
		@rStatusId INT

AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tQuotationRequest
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tQuotationRequestDetail WHERE QuotationRequestId = @rId)
			BEGIN
				DELETE FROM sPurchase.tQuotationRequestDetail
				WHERE QuotationRequestId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pQuotationRequestGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		SELECT QR.Id,
			   QR.Number,
			   QR.PurchaseRequestId,
			   QR.Name,
			   QR.StatusId,
			   QR.VendorId,
			   QR.BranchId,
			   QR.OrgGroupId,
			   QR.RFQDate,
			   QR.Description,
			   QR.StartDate,
			   QR.EndDate,
			   QR.BidOpen,
			   QR.BidClose,
			   QR.PersonContact,
			   QR.Email,
			   QR.SendToVendor,
			   QR.VendorId,
			   ISNULL(SM.Title,'') AS Status,
			   VM.Code AS VendorCode,
			   VM.Title AS VendorName,
			   PR.Number AS PurchaseNumber
		FROM   [sPurchase].[tQuotationRequest] QR(NOLOCK)
			   LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = QR.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0

		WHERE  QR.Id=@rId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId

		SELECT QRD.Id,
			   QRD.QuotationRequestId,
			   QRD.PurchaseRequestDetailId,
			   QRD.OrgGroupId,
			   QRD.StockItemId,
			   QRD.RequestedQty,
			   QRD.TargetPrice,
			   QRD.Remark,
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SCM.Title AS CategoryName,
			   SUMa.Code AS UOM
		FROM   [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
			   INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId  AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QRD.QuotationRequestId=@rId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId

	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH

END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pQuotationRequestSearchGet] @rLocationId=991100001,@rOrgGroupId=9911,@rStartDate='2023-12-12',@rEndDate='2023-12-13',@rPageNo=1,@rPageSize=10
CREATE OR ALTER PROCEDURE [sPurchase].[pQuotationRequestSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rOrgGroupId SMALLINT,
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = 0,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

        DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tQuotationRequest QR (NOLOCK)

		WHERE
				((QR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
   				AND ((QR.Name LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
				AND ((QR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((QR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND QR.IsObsolete = 0
				AND ((CAST(QR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(QR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))


		SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY QR.Id DESC
			) AS 'RowNum',QR.Id,
				QR.Number,
				QR.Name AS RequestedBy,
				QR.RFQDate,
				ISNULL(SM.Title,'') AS Status

        FROM
				sPurchase.tQuotationRequest QR (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON QR.StatusId = SM.Id


		WHERE
				((QR.Number LIKE @rNumber+'%') OR (ISNULL(@rNumber,'') = ''))
                AND ((QR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((QR.Name LIKE @rName+'%') OR (ISNULL(@rName,'') = ''))
   				AND ((QR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((QR.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0)=0))
				AND QR.IsObsolete = 0
				AND ((CAST(QR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(QR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
					)t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--exec [sPurchase].[pQuotationVendorGet] 991100010
CREATE OR ALTER PROCEDURE [sPurchase].[pQuotationVendorGet]

		 @rQuotationRequestId BIGINT,
	     @rUserId BIGINT,
	     @rOrgGroupId INT
		 --,
	 	-- @rTemplate nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
        BEGIN TRY
        DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	    DECLARE
		@rDescription  AS NVARCHAR(1000),
		@rStartDate AS NVARCHAR(100),
		@rEndDate AS NVARCHAR(100),
		@rBidOpen AS NVARCHAR(100),
		@rBidClose AS NVARCHAR(100),
		@rPersonContact AS NVARCHAR(100),
		@rEmail AS NVARCHAR(100),
		@rRFQDate AS NVARCHAR(100)

	    SELECT  @rDescription = ISNULL(QR.Description,''),
				@rStartDate = ISNULL(QR.StartDate,''),
				@rEndDate = ISNULL(QR.EndDate,''),
				@rBidOpen = ISNULL(QR.BidOpen,''),
				@rBidClose = ISNULL(QR.BidClose,''),
				@rPersonContact = ISNULL(QR.PersonContact,''),
				@rEmail = ISNULL(QR.Email,''),
				@rRFQDate = ISNULL(QR.RFQDate,'')
		FROM   [sPurchase].[tQuotationRequest] QR(NOLOCK)
			   LEFT JOIN sProcurement.tVendorMaster  VM ON QR.VendorId = VM.ID AND VM.OrgGroupId = @rOrgGroupId AND VM.LocationId = @rStoreLocationId AND VM.IsObsolete = 0
			   LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = QR.StatusId
			   LEFT JOIN [sPurchase].[tPurchaseRequest] PR ON PR.Id = QR.PurchaseRequestId AND PR.LocationId = @rStoreLocationId AND PR.OrgGroupId = @rOrgGroupId AND PR.IsObsolete = 0
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId

	DECLARE @HTMLTable NVARCHAR(MAX);
	SET @HTMLTable = '';
    SET @HTMLTable = @HTMLTable + '<tr>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemCode</th>';
    SET @HTMLTable = @HTMLTable + '<th>StockItemName</th>';
    SET @HTMLTable = @HTMLTable + '<th>Uom</th>';
    SET @HTMLTable = @HTMLTable + '<th>TotalQty</th>';
    SET @HTMLTable = @HTMLTable + '<th>TargetPrice</th>';
    SET @HTMLTable = @HTMLTable + '<th>Remark</th>';
    SET @HTMLTable = @HTMLTable + '</tr>';

	SELECT @HTMLTable = @HTMLTable+'<tr><td>'+CAST(SIM.Code AS NVARCHAR(100))+'</td><td>'
	+SIM.Title+'</td><td>'+SUMa.Code+'</td><td>'+CAST(QRD.RequestedQty AS NVARCHAR(100))+
	+'</td><td>'+CAST(QRD.TargetPrice AS NVARCHAR(100))+'</td><td>'+QRD.Remark+'</td></tr>'
	  FROM   [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
		INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		INNER JOIN	sIp.tStockItemMaster SIM ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		AND QR.LocationId = @rStoreLocationId
	    AND QR.OrgGroupId = @rOrgGroupId

    --PRINT @HTMLTable;
	DECLARE @txtMessage NVARCHAR(MAX)
    SELECT @txtMessage=REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Template,
		'{Description}' , @rDescription),
		'{StartDate}' , @rStartDate),
		'{EndDate}' , @rEndDate),
		'{BidOpen}' , @rBidOpen),
		'{BidClose}' , @rBidClose),
		'{PersonContact}' , @rPersonContact),
		'{Email}' , @rEmail),
		'{RFQDate}' , @rRFQDate),
		'{QuatationDetails}' , @HTMLTable)FROM sPurchase.tPurchaseReportTemplate WHERE id = 1

		DECLARE @VendorId BIGINT
		SELECT @VendorId = QR.VendorId FROM sPurchase.tQuotationRequest QR WHERE QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0 AND QR.LocationId = @rStoreLocationId
		AND QR.OrgGroupId = @rOrgGroupId

	SELECT
			--A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,
			A.ParentEmail AS EmailId,
			@txtMessage	AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=A.OrgGroupId AND Id = A.OrgGroupId) AS OrgId,
			 A.OrgGroupId AS OrgGroupId,
			 --A.AcademicId AS ReceiverSourceId,
			 A.Id AS SourceId,
			 2001 AS SourceTypeId,
			 --DM.Title AS MeetingType,
			 --CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 --CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 --EE.EmployeeName AS Teacher,
			 --OM.Title AS Title,
			 A.WhatsAppContactNo
	FROM
		 [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
		INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		INNER JOIN	sIp.tStockItemMaster SIM ON SIM.Id = QRD.StockItemId AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		INNER JOIN (
			SELECT	VM.Id,
					VM.ContactPersonName AS Name,
					VM.Code,
					VM.PhoneNumberOffice AS ParentContactNo,
					VM.Email AS ParentEmail,
					VM.OrgGroupId,
					VM.PhoneNumberMobile WhatsAppContactNo
			FROM	sProcurement.tVendorMaster  VM
			LEFT JOIN   sProcurement.tVendorCategoryMaster VC
			ON  VM.VendorCategoryId = VC.Id
			WHERE VM.Id = @VendorId AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		) AS A ON A.Id = QR.VendorId
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId
	   END TRY
	   BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT
		   @ErrorMessage = ERROR_MESSAGE(),
		   @ErrorSeverity = ERROR_SEVERITY(),
		   @ErrorState = ERROR_STATE();

		RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pSalesReturnAdd]
		@rId BIGINT,
		@rGoodsReceivedNoteId BIGINT,
		@rPurchaseOrderId BIGINT,
		@rVendorId INT,
		@rRequestedBy NVARCHAR(100),
		@rOrgGroupId SMALLINT,
		@rStatusId SMALLINT,
		@rUserId BIGINT,
		@rDetailList sPurchase.SalesReturnDetailType READONLY

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF(@rId > 0)
		BEGIN
		  IF NOT EXISTS(SELECT Id FROM sPurchase.tQuotationRequest WHERE Id = @rId AND CreatedUserId = @rUserId AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0)
		    BEGIN
				SELECT -101
		    END
		  ELSE
		    BEGIN
				UPDATE sPurchase.tSalesReturn
				SET
					StatusId = @rStatusId,
					GoodsReceivedNoteId = @rGoodsReceivedNoteId,
					RequestedBy = @rRequestedBy,
					PurchaseOrderId = @rPurchaseOrderId,
					VendorId = @rVendorId,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = GETUTCDATE()
				WHERE Id = @rId  AND LocationId = @rStoreLocationId AND OrgGroupId = @rOrgGroupId AND IsObsolete = 0

				DELETE FROM sPurchase.tSalesReturnDetail
				WHERE Id NOT IN(SELECT Id FROM @rDetailList)
				AND SalesReturnId = @rId AND OrgGroupId = @rOrgGroupId

				UPDATE sPurchase.tSalesReturnDetail
				SET
				OrgGroupId = @rOrgGroupId,
				SalesReturnId = @rId,
				GoodsReceivedNoteDetailId = DL.GoodsReceivedNoteDetailId,
				StockItemId = DL.StockItemId,
				POQty = DL.POQty,
				ReceivedQty = DL.ReceivedQty,
				RejectedQty = DL.RejectedQty,
				CreditNoteIssueDate = DL.CreditNoteIssueDate,
				ReasonForRejection = DL.ReasonForRejection,
				UpdatedUserId = @rUserId,
				UpdatedDateTime = GETUTCDATE()
				FROM @rDetailList DL
				INNER JOIN sPurchase.tSalesReturnDetail SR ON DL.ID = SR.Id AND SR.OrgGroupId = @rOrgGroupId
				WHERE SalesReturnId = @rId AND OrgGroupId = @rOrgGroupId

				DECLARE @lNextNumberSRD BIGINT
				EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturnDetail',@lNextNumber = @lNextNumberSRD OUTPUT
				SET @lNextNumberSRD=@lNextNumberSRD-1
				INSERT INTO sPurchase.tSalesReturnDetail
				(
					Id,
					OrgGroupId,
					SalesReturnId,
					GoodsReceivedNoteDetailId,
					StockItemId,
					POQty,
					ReceivedQty,
					RejectedQty,
					CreditNoteIssueDate,
					ReasonForRejection,
					CreatedUserId,
					CreatedDateTime
				)
				SELECT	@lNextNumberSRD+Id,
						@rOrgGroupId,
						@rId,
						GoodsReceivedNoteDetailId,
						StockItemId,
						POQty,
						ReceivedQty,
						RejectedQty,
						CreditNoteIssueDate,
						ReasonForRejection,
						@rUserId,
						GETUTCDATE()
				FROM @rDetailList
				WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tSalesReturnDetail SR ON DL.ID = SR.Id AND SR.OrgGroupId = @rOrgGroupId
				WHERE SR.SalesReturnId = @rId AND SR.OrgGroupId = @rOrgGroupId)
				SET @lNextNumberSRD=@lNextNumberSRD+(SELECT COUNT(Id) FROM @rDetailList WHERE Id NOT IN(SELECT DL.Id FROM @rDetailList DL
				INNER JOIN sPurchase.tSalesReturnDetail SR ON DL.ID = SR.Id AND SR.OrgGroupId = @rOrgGroupId
				WHERE SR.SalesReturnId = @rId AND SR.OrgGroupId = @rOrgGroupId))
				EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tSalesReturnDetail', @rCurrentNumber = @lNextNumberSRD

				SELECT @rId
		    END
		END
		ELSE
		BEGIN
		    IF NOT EXISTS(
                SELECT WFS.AutoId FROM [sWf].[tWfSetup] WFS
				WHERE WFS.[WfFunctionalityId] = 5 AND @rOrgGroupId = WFS.[OrgGroupId])
				BEGIN
					SELECT -102
				END
				ELSE
				BEGIN
				    IF(((SELECT EmployeeManagerId FROM [sHrm].[tEmployeeJobDetail] WHERE EmployeeId = (SELECT ISNULL(U.SourceId,U.Id) FROM sSecurity.tUser U WHERE U.Id = @rUserId)) IS NULL) AND EXISTS(SELECT WFS.WfTypeMasterId FROM [sWf].[tWfFunctionalityMaster] SFM INNER JOIN [sWf].[tWfSetup] WFS ON WFS.WfFunctionalityId = SFM.Id WHERE WFS.WfTypeMasterId = 2 AND WFS.WfLevel > 0 AND SFM.Id = 5))
					BEGIN
						SELECT -301;
					END
					ELSE
					BEGIN
						DECLARE @lNextNumber INT
						EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturn',@lNextNumber = @lNextNumber OUTPUT
						-------------select @lNextNumber
						--DECLARE @loNextNumber nVarchar(20)
						--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rLocationId,
						------------@rNextNumber = @loNextNumber OUTPUT

	 					INSERT INTO sPurchase.tSalesReturn
						(
							Id,
							SRNumber,
							GoodsReceivedNoteId,
							PurchaseOrderId,
							VendorId,
							RequestedBy,
							OrgGroupId,
							LocationId,
							StatusId,
							CreatedUserId,
							CreatedDateTime

						)
						VALUES
						(
							@lNextNumber,
							@lNextNumber,
							@rGoodsReceivedNoteId,
							@rPurchaseOrderId,
							@rVendorId,
							@rRequestedBy,
							@rOrgGroupId,
							@rStoreLocationId,
							@rStatusId,
							@rUserId,
							GETUTCDATE()
						)

						SET @rId = @lNextNumber

						DECLARE @lNextNumberSRDD BIGINT
						EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sPurchase.tSalesReturnDetail',@lNextNumber = @lNextNumberSRDD OUTPUT
						SET @lNextNumberSRDD=@lNextNumberSRDD-1

	 					INSERT INTO sPurchase.tSalesReturnDetail
						(
							Id,
							OrgGroupId,
							SalesReturnId,
							GoodsReceivedNoteDetailId,
							StockItemId,
							POQty,
							ReceivedQty,
							RejectedQty,
							CreditNoteIssueDate,
							ReasonForRejection,
							CreatedUserId,
							CreatedDateTime
						)
						SELECT	@lNextNumberSRDD+Id,
								@rOrgGroupId,
								@rId,
								GoodsReceivedNoteDetailId,
								StockItemId,
								POQty,
								ReceivedQty,
								RejectedQty,
								CreditNoteIssueDate,
								ReasonForRejection,
								@rUserId,
								GETUTCDATE()
						FROM @rDetailList

						SET @lNextNumberSRDD=@lNextNumberSRDD+(SELECT COUNT(Id) FROM @rDetailList)
						EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sPurchase.tSalesReturnDetail', @rCurrentNumber = @lNextNumberSRDD

						SELECT @rId

						DECLARE @typeId SMALLINT=0
						DECLARE @Level SMALLINT=0
						SELECT @typeId=WfTypeMasterId, @Level=WfLevel FROM sWf.tWfSetup WHERE WfFunctionalityId = 5
						IF(@typeId = 1)--parallel
						BEGIN
							EXEC [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,1,'',0,0,5,@rOrgGroupId
						END
						ELSE IF(@typeId = 2)--sequencial
						BEGIN
							EXEC [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,1,'',1,@Level,5,@rOrgGroupId
						END
						ELSE IF(@typeId = 3)--auto approved
						BEGIN
							EXEC [sWf].[pWfApprovalAdd] 0,@rId,2044,@rUserId,3,'',0,0,5,@rOrgGroupId
						END
					--select 1;
					END
				END
		 END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END









GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sPurchase].[pSalesReturnDelete]
		@rId BIGINT,
		@rStatusId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId > 0)
		BEGIN
			UPDATE sPurchase.tSalesReturn
			SET
				StatusId = @rStatusId,
				IsObsolete = 1,
				DeletedDateTime = GETUTCDATE()
			WHERE Id = @rId AND IsObsolete = 0

			IF EXISTS(SELECT Id FROM sPurchase.tSalesReturnDetail WHERE SalesReturnId = @rId)
			BEGIN
				DELETE FROM sPurchase.tSalesReturnDetail
				WHERE SalesReturnId = @rId
			END
			SELECT 1
		END
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION


    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pSalesReturnGet] 991100001
CREATE OR ALTER PROCEDURE [sPurchase].[pSalesReturnGet]
	  @rId INT,
	  @rUserId BIGINT,
	  @rOrgGroupId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		SELECT  SR.Id,
				SR.SRNumber,
				SR.OrgGroupId,
				SR.GoodsReceivedNoteId,
				SR.PurchaseOrderId,
				SR.VendorId,
				SR.RequestedBy,
				ISNULL(GRN.GRNNumber,'') AS GRNNumber,
				SR.StatusId,
				ISNULL(SM.Title,'') AS Status,
				VM.Title AS VendorName,
				ISNULL(PO.RefNumber,'') AS PurchaseOrderNumber
		FROM   [sPurchase].[tSalesReturn] SR(NOLOCK)
		LEFT JOIN [sPurchase].[tGoodsReceivedNote] GRN ON GRN.Id = SR.GoodsReceivedNoteID
			  AND GRN.LocationId = @rStoreLocationId AND GRN.OrgGroupId = @rOrgGroupId AND GRN.IsObsolete = 0
		LEFT JOIN sPurchase.tPurchaseOrder PO ON PO.Id = SR.PurchaseOrderId
			  AND PO.LocationId = @rStoreLocationId AND PO.OrgGroupId = @rOrgGroupId AND PO.IsObsolete = 0
		LEFT JOIN [sWf].[tWfStatusMaster] SM ON SM.Id = SR.StatusId
		LEFT JOIN  sProcurement.tVendorMaster  VM ON SR.VendorId = VM.ID
			  AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		WHERE  SR.Id=@rId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0

		SELECT SRD.Id,
			   SRD.SalesReturnId,
			   SRD.GoodsReceivedNoteDetailId,
			   SRD.OrgGroupId,
			   SRD.StockItemId,
			   SRD.POQty,
			   SRD.ReceivedQty,
			   SRD.RejectedQty,
			   SUMa.Id AS UnitTypeId,
			   SRD.CreditNoteIssueDate,
			   SRD.ReasonForRejection,
			   SIM.Code	AS StockItemCode,
			   SIM.Title AS StockItemName,
			   SUMa.Code AS UOM,
			   SCM.Id AS CategoryId,
			   SCM.Title AS CategoryName,
			   0 AS SubCategoryId,
			   (SELECT SUM(QCD1.RejectedQty) FROM sPurchase.tQualityCheck QC1
			    INNER JOIN   sPurchase.tQualityCheckDetail QCD1 ON QCD1.QualityCheckId = QC1.Id AND QCD1.RejectedQty > 0
				AND QCD1.GoodsReceivedNoteDetailId = SRD.GoodsReceivedNoteDetailId
				WHERE QC1.GoodsReceivedNoteId = SR.GoodsReceivedNoteId AND QC1.LocationId = @rStoreLocationId
					AND QC1.OrgGroupId = @rOrgGroupId AND QC1.IsObsolete = 0) AS GRNRejectedQty
		FROM   [sPurchase].[tSalesReturnDetail] SRD (NOLOCK)
			   INNER JOIN	sPurchase.tSalesReturn SR	ON SR.Id = SRD.SalesReturnId
				      AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
			   INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = SRD.StockItemId
					  AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
			   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
			   INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		WHERE  SRD.SalesReturnId=@rId AND SR.LocationId = @rStoreLocationId AND SR.OrgGroupId = @rOrgGroupId AND SR.IsObsolete = 0
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pSalesReturnSearchGet]

	@rNumber NVARCHAR(30) = '',
	@rName NVARCHAR = '',
	@rStartDate DATETIME = NULL,
	@rEndDate DATETIME = NULL,
	@rOrgGroupId INT,
    @rPageNo INT,
	@rPageSize INT,
	@rStatusId SMALLINT = NULL,
	@rUserId BIGINT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	    DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		IF @rNumber = NULL SET @rNumber=''
		IF @rName = NULL SET @rName=''
		IF @rStartDate = '' SET @rStartDate=NULL
		IF @rEndDate = '' SET @rEndDate=NULL
		IF @rStatusId IS NULL SET @rStatusId=0

		DECLARE @TotalRecords BIGINT;
		-- Get the total number of records
		SELECT @TotalRecords = COUNT(*) FROM sPurchase.tSalesReturn SR (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON SR.StatusId = SM.Id

        WHERE
				((SR.SRNumber LIKE @rNumber+'%') OR (@rNumber = ''))
   				AND ((SR.RequestedBy LIKE @rName+'%') OR (@rName = ''))
   				AND ((SR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((SR.StatusId = @rStatusId) OR (@rStatusId=0))
				AND SR.IsObsolete = 0
				AND ((CAST(SR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(SR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))

        SELECT t.* FROM (
			SELECT ROW_NUMBER() OVER (
			ORDER BY SR.Id DESC
			) AS 'RowNum',SR.Id,
				SR.SRNumber AS Number,
				SR.RequestedBy,
				ISNULL(SM.Title,'') AS Status

        FROM
				sPurchase.tSalesReturn SR (NOLOCK)
				LEFT JOIN [sWf].[tWfStatusMaster] SM ON SR.StatusId = SM.Id

	    WHERE
				((SR.SRNumber LIKE @rNumber+'%') OR (@rNumber = ''))
   				AND ((SR.RequestedBy LIKE @rName+'%') OR (@rName = ''))
   				AND ((SR.LocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((SR.StatusId = @rStatusId) OR (@rStatusId=0))
				AND SR.IsObsolete = 0
				AND ((CAST(SR.CreatedDateTime AS DATE) >= CAST(@rStartDate AS DATE)) OR (ISNULL(@rStartDate,'')=''))
				AND((CAST(SR.CreatedDateTime AS DATE) <= CAST(@rEndDate AS DATE)) OR (ISNULL(@rEndDate,'')=''))
					)t WHERE t.RowNum BETWEEN
		        ((@rPageNo-1)*@rPageSize +1) AND (@rPageNo*@rpageSize)

        SELECT @TotalRecords AS TotalRecords
	 END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sPurchase].[pSearchScreenDependencyGet]
	  @rScreenId INT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		SELECT SH.ScreenId,
				SH.IsUpload,
				SH.UploadRemark,
				SH.IsExport,
				SH.ExportRemark,
				SH.IsImport,
				SH.ImportRemark
		FROM   [sSecurity].[tScreenHelp] SH
		INNER JOIN [sSecurity].[tScreen] S ON S.Id = SH.ScreenId
		WHERE SH.ScreenId = @rScreenId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pSMSTemplateIdGet]
		@rOrgId int,
		@rCustomEventId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT SMSTemplateID FROM sAlert.tCustomTemplateMaster WHERE Id = @rCustomEventId AND OrgId = @rOrgId
		END TRY
		BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [sPurchase].[pStockBatchAddModify] 9911,991100001,991100001,100,'+',9911000000270
CREATE OR ALTER PROCEDURE [sPurchase].[pStockBatchAddModify]
	@rOrgGroupId INT,
	@rStoreLocationId INT = 0,
	@rStockItemId INT = 0,
	@rQuantity DECIMAL(12,2) = 0.00,
	@rOperation NVARCHAR(20),
	@rUserId BIGINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

       DECLARE @1AvailableQuantity DECIMAL(12,2)

BEGIN
    BEGIN TRY
    IF EXISTS(SELECT Id FROM sProcurement.tStockBatch WHERE Id = @rStockItemId)
	BEGIN
		IF(@rOperation = '+')
		BEGIN
			 UPDATE  sProcurement.tStockBatch
			 SET  AvailableQuantity = ISNULL(AvailableQuantity,0) + @rQuantity,
				  UpdatedUserId = @rUserId,
				  UpdatedDateTime = sCommon.fGetDate()
			 FROM sProcurement.tStockBatch
			 WHERE
			(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
			(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
			 OrgGroupId = @rOrgGroupId
		END
		ELSE
		BEGIN
			UPDATE  sProcurement.tStockBatch
			 SET  AvailableQuantity = ISNULL(AvailableQuantity,0) - @rQuantity,
				  UpdatedUserId = @rUserId,
				  UpdatedDateTime = sCommon.fGetDate()
			 FROM sProcurement.tStockBatch
			 WHERE
			(StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) AND
			(StockItemId = @rStockItemId OR @rStockItemId = 0) AND
			--(Number = @rNumber OR ISNULL(@rNumber, '') = '') AND
			--(ExpiryDate = @rExpiryDate OR ISNULL(@rExpiryDate, '') = '') AND
			 OrgGroupId = @rOrgGroupId
		END
	END
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT
		   @ErrorMessage = ERROR_MESSAGE(),
		   @ErrorSeverity = ERROR_SEVERITY(),
		   @ErrorState = ERROR_STATE();

		RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [sPurchase].[pStockItemMasterGetWithCategory]  9911,9911000000270,991100017,'','',0,1
CREATE OR ALTER PROCEDURE [sPurchase].[pStockItemMasterGetWithCategory]
    @rOrgGroupId INT,
	@rUserId BIGINT,
	@rId INT = 0,
	@rCode NVARCHAR(100),
	@rTitle NVARCHAR(100),
	@rIsAbsoluteTitle BIT = 0,
	@rIsWildCardSearch BIT = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
    DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId
    IF @rIsAbsoluteTitle = 0
	BEGIN
		IF @rIsWildCardSearch = 1
			BEGIN
				SET @rCode = sCommon.fSearchStringGet(@rCode)
				SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			END
	END

	SELECT 	SIM.Id,
			SIM.Code,
			--CAST(SIM.StockItemTypeId AS INT) AS StockItemTypeId,
			SIM.Title,
			CAST(ISNULL(sIp.LastPurchasePrice, 0) AS DECIMAL(22, 2)) LastPurchasePrice,
			SIM.CreatedUserId,
			SIM.CreatedDateTime,
			SIM.UpdatedUserId,
			SIM.UpdatedDateTime,
			--SIT.Title AS StockItemTypeTitle,
			--SIT.Code AS StockItemTypeCode,
			SIM.IssueStockUomId,
			SU.Code UomCode,
			Su.Title UomTitle,
			SIM.IsBatchWiseTracking,
			SCM.Id AS CategoryId,
			SCM.Code AS CategoryName

	   FROM	sIp.tStockItemMaster SIM
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id

	 --  INNER JOIN sPurchase.tStockItemTypeMaster SIT
		--ON SIM.StockItemTypeId = SIT.Id
	   LEFT OUTER JOIN sFinanceCommon.tStockUomMaster SU
		ON SU.Id = SIM.IssueStockUomId
	   LEFT JOIN [sIp].[tStockItemCategoryMaster] SCM ON SCM.Id = SIM.StockItemCategoryId
	   WHERE((SIM.Id = @rId) OR (@rId = 0))
		AND	((SIM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
		AND	(((SIM.Title LIKE @rTitle) AND @rIsAbsoluteTitle = 0) OR (@rTitle = '' AND @rIsAbsoluteTitle = 0) OR ((SIM.Title = @rTitle ) AND @rIsAbsoluteTitle = 1))
		AND ((SIM.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   		AND ((SIM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND SIM.IsObsolete= 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT
		   @ErrorMessage = ERROR_MESSAGE(),
		   @ErrorSeverity = ERROR_SEVERITY(),
		   @ErrorState = ERROR_STATE();

		RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [sPurchase].[pStockItemMasterSearchGet] 9911000000270,991100001,''
CREATE OR ALTER PROCEDURE [sPurchase].[pStockItemMasterSearchGet]
	@rUserId BIGINT,
	@rOrgGroupId INT,
	@rCurrentAlphabet NVARCHAR(10)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
    DECLARE @rStoreLocationId BIGINT
    SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId  = 542 AND SourceId = @rUserId

	SELECT
			Id,
			Code,
			Title FROM sIp.tStockItemMaster SIM

	  WHERE
		 ((Title LIKE @rCurrentAlphabet + '%') OR (ISNULL(@rCurrentAlphabet,'')=''))
	     AND IsObsolete= 0
	     AND SIM.StoreLocationId = @rStoreLocationId
	     AND SIM.OrgGroupId = @rOrgGroupId
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT
		   @ErrorMessage = ERROR_MESSAGE(),
		   @ErrorSeverity = ERROR_SEVERITY(),
		   @ErrorState = ERROR_STATE();

		RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPurchase].[pStoreLocationGet]
	@rId INT = 0,
	@rTitle NVARCHAR(20) = '',
	@rCode NVARCHAR(100) = '',
	@rLocationId INT = 0,
	@rOrgGroupId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY

	--IF @rIsWildCardSearch = 1
	--	BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END

	 SELECT SLM.Id,
			SLM.Title,
			SLM.CreatedUserId,
			SLM.CreatedDateTime,
			SLM.IsObsolete,
			SLM.UpdatedUserId,
			SLM.UpdatedDateTime,
			SLM.Code,
			SLM.OrgGroupId,
			OM.Title AS OrgGroupName,
			SLM.Title AS StoreLocationName,
			ISNULL(SLM.IsBatchwiseTracking,0) AS IsBatchwiseTracking,
			Isnull(SLM.DepositHeadId,0) AS DepositHeadId,
			Isnull(SLM.DepositExpenseTypeId,0) AS DepositExpenseTypeId,
			Isnull(SLM.ReportId,0) AS ReportId

	   FROM sIp.tStoreLocationMaster SLM
	   INNER JOIN sSetup.tOrgGroupMaster OM ON OM.Id=SLM.OrgGroupId
	   WHERE ((SLM.Id = @rId) OR (@rId = 0))
	   AND ((SLM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((SLM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND  (SLM.OrgGroupId = @rOrgGroupId)
	   --AND SLM.IsObsolete = 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT
		   @ErrorMessage = ERROR_MESSAGE(),
		   @ErrorSeverity = ERROR_SEVERITY(),
		   @ErrorState = ERROR_STATE();

		RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sPurchase].[pStoreLocationMasterGet]
	@rId INT = 0,
	@rTitle NVARCHAR(20) = '',
	@rCode NVARCHAR(100) = '',
	@rLocationId INT = 0,
	@rOrgGroupId INT,
	@rIsWildCardSearch BIT = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY

	IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END




	 SELECT SLM.Id,
			SLM.Title,
			SLM.CreatedUserId,
			SLM.CreatedDateTime,
			SLM.IsObsolete,
			SLM.UpdatedUserId,
			SLM.UpdatedDateTime,
			SLM.Code,
			SLM.OrgGroupId,
			OM.Title AS OrgGroupName,
			SLM.Title AS StoreLocationName,
			ISNULL(SLM.IsBatchwiseTracking,0) AS IsBatchwiseTracking,
			Isnull(SLM.DepositHeadId,0) AS DepositHeadId,
			Isnull(SLM.DepositExpenseTypeId,0) AS DepositExpenseTypeId,
			Isnull(SLM.ReportId,0) AS ReportId

	   FROM sIp.tStoreLocationMaster SLM
	   INNER JOIN sSetup.tOrgGroupMaster OM ON OM.Id=SLM.OrgGroupId
	  WHERE ((SLM.Id = @rId) OR (@rId = 0))
	   AND ((SLM.Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = ''))
	   AND ((SLM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
	   AND  (SLM.OrgGroupId = @rOrgGroupId)
	   --AND SLM.IsObsolete = 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT
		   @ErrorMessage = ERROR_MESSAGE(),
		   @ErrorSeverity = ERROR_SEVERITY(),
		   @ErrorState = ERROR_STATE();

		RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pStudentProfileGet]
@rAcademicId BIGINT,
@rbatchId INT
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		SELECT  A.OrgId,
				BatchId,
				StudentId,
				A.Id AS AcademicId,
				SM.Code,
				A.RollNo,
				(FirstName +' '+MiddleName+' '+LastName) AS StudentName,
				SM.FirstName,
				SM.MiddleName,
				SM.LastName,
				A.ClassId,
				A.DivisionId,
				(CM.DisplayTitle +'-'+ DM.DisplayTitle) AS ClassDivision,
				DPM.Id AS DepartmentId,
				DPM.DisplayTitle AS DepartmentName,
				SM.SUID, B.Title AS BatchName
		FROM    sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
				INNER JOIN sSetup.tDepartmentMaster DPM ON DPM.Id = CM.DepartmentId
				INNER JOIN sSetup.tBatchMaster B ON b.Id = A.BatchId
		WHERE A.Id=@rAcademicId AND BatchId =@rbatchId;
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sPurchase].[pValidateCloudStorage]
	  @rOrgGroupId SMALLINT
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		 SELECT ISNULL(SUM(UD.DocumentSize),0)
		 FROM sCommon.tUploadDocument UD (NOLOCK)
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM
		 ON OGBM.Id = UD.OrgGroupBatchId
		 WHERE OGBM.OrgGroupId = @rOrgGroupId
	END TRY

	BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;
    SELECT
       @ErrorMessage = ERROR_MESSAGE(),
       @ErrorSeverity = ERROR_SEVERITY(),
       @ErrorState = ERROR_STATE();
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);

	END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--exec [sPurchase].[pVendorNotificationGet] 991100022,'',9911
CREATE OR ALTER PROCEDURE [sPurchase].[pVendorNotificationGet]
		 @rQuotationRequestId BIGINT,
		 @rNotificationLink NVARCHAR(1000),
		 @rOrgId SMALLINT,
	     @rUserId BIGINT,
	     @rOrgGroupId INT

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 BEGIN
        BEGIN TRY
        DECLARE @rStoreLocationId BIGINT
        SELECT @rStoreLocationId = ISNULL(ItemValue,0)
	    FROM sConfig.tConfigurationSetup
	    WHERE ConfigurationId  = 542 AND SourceId = @rUserId

		DECLARE @VendorId BIGINT
		SELECT @VendorId = QR.VendorId FROM sPurchase.tQuotationRequest QR WHERE QR.Id = @rQuotationRequestId AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0

		SET @rNotificationLink = '<a href="'+@rNotificationLink+'" target="_blank">'+@rNotificationLink+'</a>'

	DECLARE @txtMessage NVARCHAR(MAX)
    SELECT @txtMessage=REPLACE(REPLACE(Template,
		'[VendorName]' , (SELECT VM.ContactPersonName AS Name
						FROM	sProcurement.tVendorMaster  VM
						WHERE VM.Id = @VendorId AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0)),
		'[NotificationLink]' , @rNotificationLink) FROM sAlert.tEventTemplate WHERE IsAutoSend = 1 AND OrgId = @rOrgId AND EventId = 158

	SELECT
			--A.AcademicId,
			A.Code,
			A.Name,
			A.ParentContactNo AS MobileNo,
			A.ParentEmail AS EmailId,
			@txtMessage	AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=A.OrgGroupId AND Id = A.OrgGroupId) AS OrgId,
			 A.OrgGroupId AS OrgGroupId,
			 A.Id AS ReceiverSourceId,
			 A.Id AS SourceId,
			 2001 AS SourceTypeId,
			 --DM.Title AS MeetingType,
			 --CONVERT(varchar(11),ISNULL(OM.StartDate,'') ,103) AS StartDate,
			 --CONVERT(varchar(11),ISNULL(OM.EndDate,'') ,103) AS EndDate,
			 --EE.EmployeeName AS Teacher,
			 --OM.Title AS Title,
			 A.WhatsAppContactNo
	FROM
		 [sPurchase].[tQuotationRequestDetail] QRD (NOLOCK)
		INNER JOIN	sPurchase.tQuotationRequest QR	ON QR.Id = QRD.QuotationRequestId   AND QR.LocationId = @rStoreLocationId AND QR.OrgGroupId = @rOrgGroupId AND QR.IsObsolete = 0
		INNER JOIN	sIp.tStockItemMaster SIM	ON SIM.Id = QRD.StockItemId  AND SIM.StoreLocationId = @rStoreLocationId AND SIM.OrgGroupId = @rOrgGroupId AND SIM.IsObsolete = 0
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		INNER JOIN (
			SELECT	VM.Id,
					VM.ContactPersonName AS Name,
					VM.Code,
					VM.PhoneNumberOffice AS ParentContactNo,
					VM.Email AS ParentEmail,
					VM.OrgGroupId,
					VM.PhoneNumberMobile WhatsAppContactNo
			FROM	sProcurement.tVendorMaster  VM
			LEFT JOIN   sProcurement.tVendorCategoryMaster VC
			ON  VM.VendorCategoryId = VC.Id
			WHERE VM.Id = @VendorId AND VM.LocationId = @rStoreLocationId AND VM.OrgGroupId = @rOrgGroupId AND VM.IsObsolete = 0
		) AS A ON A.Id = QR.VendorId
		WHERE  QR.Id = @rQuotationRequestId AND QR.IsObsolete = 0
		       AND QR.LocationId = @rStoreLocationId
			   AND QR.OrgGroupId = @rOrgGroupId
	 END TRY
	 BEGIN CATCH
		ROLLBACK TRANSACTION

		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;

		SELECT
		   @ErrorMessage = ERROR_MESSAGE(),
		   @ErrorSeverity = ERROR_SEVERITY(),
		   @ErrorState = ERROR_STATE();

		RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sPurchase].[pWhatsAppTemplateGet]
		@rEventId INT,
		@rOrgId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	BEGIN
		BEGIN TRY
			SELECT Template,WhatsAppTemplate,WhatsAppTemplateLanguage FROM sAlert.tEventTemplate WHERE EventId = @rEventId AND OrgId = @rOrgId AND AlertModeId = 4
		END TRY
		BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateApplicationAdd]   									
	@rOrgGroupID smallint, 
	@rVacancyId int, 
	@rId bigint, 
	@rApplicationNumber int	,
	@rApplicationPassword nvarchar(100)='',
	@rCandidateNumber int, 
	@rFirstName nvarchar(100), 
	@rMiddleName nvarchar(100), 
	@rLastName nvarchar(100), 
	@rDateOfBirth date, 
	@rGenderId smallint, 
	@rReligionId int, 
	@rMaritalStatusId smallint, 
	@rQualification nvarchar(150),
	@rFamilyCast nvarchar(150), 
	@rCastCategoryId int, 
	@rRecruitmentStatusId smallint, 
	@rMobileNo nvarchar(20), 
	@rPersonalEmail nvarchar(100), 
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint, 	
	@rDataEntryModeId smallint, 
    @rDataEntryStatusId smallint,
    @OutAdmissionFormId BIGINT = NULL OUTPUT,
	@rLastDrawnSalary decimal,
	@rExpectedSalary decimal,
	@rAdditionalRemark nvarchar(500),
	@rReferenceId smallint,
	@rMainSubject nvarchar(100),
	@rOrgId int = 0 ,
	@rBloodGroupId smallint= 0,
	@rWhatsAppContactNo nvarchar(20)=''	--add for mantis:34273
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 IF(@rId = 0)	
 BEGIN
 SELECT  @rCandidateNumber =  ISNULL(MAX(CandidateNumber),0) 
                       FROM  sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupID
                       AND ISNULL(LEN(CandidateNumber),0)=
                       (SELECT ISNULL((MAX(LEN(CandidateNumber))),0) 
                       FROM  sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupID
                       AND Isnumeric(CandidateNumber) = 1)
	
	
	    SET @rCandidateNumber = @rCandidateNumber +1
	
		IF Exists(select ApplicationNumber from sRecruitment.tCandidateMaster where ApplicationNumber=@rApplicationNumber AND OrgGroupID=@rOrgGroupID)
			BEGIN
			select -101 as Result
			RETURN
		END 
 END
 ELSE
 BEGIN
	IF Exists(select @rApplicationNumber from sRecruitment.tCandidateMaster where ApplicationNumber=@rApplicationNumber AND OrgGroupID=@rOrgGroupID And Id <> @rId)
	BEGIN
		select -101 as Result
		RETURN
	END 
 END

	
 BEGIN TRY
 BEGIN TRANSACTION	
 DECLARE @lNextNumber BIGINT
 DECLARE @lBIGID BIGINT
 DECLARE @lSMALLID INT
 
 IF(@rId = 0)	
	BEGIN
	IF(@rApplicationNumber = 0)
	BEGIN
	SELECT @rApplicationNumber = ISNULL(MAX(ApplicationNumber),0) + 1 FROM sRecruitment.tCandidateMaster
	END
	IF(@rApplicationPassword = '')
	BEGIN
	SELECT @rApplicationPassword = @rApplicationNumber
	END
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sRecruitment.tCandidateMaster
		(
				OrgGroupID, 
				VacancyId, 
				Id, 
				ApplicationNumber,	
				ApplicationPassword ,
				CandidateNumber, 
				FirstName, 
				MiddleName, 
				LastName, 
				DateOfBirth, 
				GenderId, 
				ReligionId, 
				MaritalStatusId, 
				Qualification,
				FamilyCast, 
				CastCategoryId, 
				RecruitmentStatusId, 
				MobileNo, 
				PersonalEmail, 
				CreatedUserId, 
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,	
				DataEntryModeId, 
				DataEntryStatusId,
				LastDrawnSalary,
				ExpectedSalary,
				AdditionalRemark,
				ReferenceId,
				MainSubject,
				OrgId,
				BloodGroupId,
				WhatsAppContactNo	--add for mantis:34273
			
		)
	VALUES
		(
			 @rOrgGroupID , 
				@rVacancyId , 
				@lNextNumber , 
				@rApplicationNumber ,	
				@rApplicationPassword ,
				@rCandidateNumber , 
				@rFirstName , 
				@rMiddleName , 
				@rLastName , 
				@rDateOfBirth , 
				@rGenderId , 
				@rReligionId , 
				@rMaritalStatusId , 
				@rQualification ,
				@rFamilyCast, 
				@rCastCategoryId , 
				@rRecruitmentStatusId , 
				@rMobileNo , 
				@rPersonalEmail , 
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rUpdatedUserId,
				sCommon.fGetDate(),	
				@rDataEntryModeId , 
				@rDataEntryStatusId,
				@rLastDrawnSalary,
				@rExpectedSalary,
				@rAdditionalRemark,
				@rReferenceId,
				@rMainSubject,
				@rOrgId,
				@rBloodGroupId,
				@rWhatsAppContactNo	--add for mantis:34273
		)
	INSERT INTO sRecruitment.tRecruitmentStatusLog
		(
		OrgGroupId,
		CandidateId,
		RecruitmentStatusId,
		Remark,
		CreatedUserId,
		CreatedDateTime
			
		)
		VALUES
		(
		@rOrgGroupID , 
		@lNextNumber,
		@rRecruitmentStatusId,
		'',
		@rCreatedUserId,
		sCommon.fGetDate()
		)
	END	 
	ELSE
	BEGIN
	SET @lNextNumber = @rId
	    UPDATE  sRecruitment.tCandidateMaster
	    SET
				VacancyId=@rVacancyId, 	
				--ApplicationNumber=@rApplicationNumber,					
				--CandidateNumber=@rCandidateNumber, 
				FirstName=@rFirstName, 
				MiddleName=@rMiddleName, 
				LastName=@rLastName, 
				DateOfBirth=@rDateOfBirth, 
				GenderId=@rGenderId, 
				ReligionId=@rReligionId, 
				MaritalStatusId=@rMaritalStatusId, 
				Qualification=@rQualification,
				FamilyCast=@rFamilyCast, 
				CastCategoryId=@rCastCategoryId, 
				RecruitmentStatusId=@rRecruitmentStatusId, 
				MobileNo=@rMobileNo, 
				PersonalEmail=@rPersonalEmail, 				
				UpdatedUserId=@rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LastDrawnSalary=@rLastDrawnSalary,
				ExpectedSalary=@rExpectedSalary,
				AdditionalRemark=@rAdditionalRemark,
				ReferenceId = @rReferenceId,
				MainSubject = @rMainSubject,
				OrgId = @rOrgId,
				BloodGroupId=@rBloodGroupId,
				WhatsAppContactNo = @rWhatsAppContactNo	--add for mantis:34273

	      WHERE Id = @rId 	   
	END  
	SELECT @lNextNumber AS Result
	SET @OutAdmissionFormId=@lNextNumber

	COMMIT TRANSACTION

	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateApplicationCommunicationsAdd]
		
		 @rCandidateId bigint,
         @rPresentStreetOne nvarchar(150)='',
         @rPresentStreetTwo nvarchar(150)='',
         @rPresentStreetThree nvarchar(150)='',
         @rPresentCountry nvarchar(50)='',
         @rPresentState nvarchar(50)='',
         @rPresentCity nvarchar(50)='',
         @rPresentZipCode nvarchar(20)='',
         @rPresentContactNo nvarchar(20)='',
         @rPermanentStreetOne nvarchar(150)='',
         @rPermanentStreetTwo nvarchar(150)='',
         @rPermanentStreetThree nvarchar(150)='',
         @rPermanentCountry nvarchar(50)='',
         @rPermanentState nvarchar(50)='',
         @rPermanentCity nvarchar(50)='',
         @rPermanentZipCode nvarchar(20)='',
         @rPermanentContactNo nvarchar(20)='',
       
         @rCreatedUserId bigint=0
		 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	

	
 BEGIN TRANSACTION	
	
	IF NOT EXISTS (Select CandidateId from sRecruitment.tCandidateCommunications where CandidateId = @rCandidateId)
	BEGIN
	INSERT INTO sRecruitment.tCandidateCommunications
		(
				[CandidateId]
			   ,[PresentStreetOne]
			   ,[PresentStreetTwo]
			   ,[PresentStreetThree]
			   ,[PresentCountry]
			   ,[PresentState]
			   ,[PresentCity]
			   ,[PresentZipCode]
			   ,[PresentContactNo]
			   ,[PermanentStreetOne]
			   ,[PermanentStreetTwo]
			   ,[PermanentStreetThree]
			   ,[PermanentCountry]
			   ,[PermanentState]
			   ,[PermanentCity]
			   ,[PermanentZipCode]
			   ,[PermanentContactNo]			  
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
		)
	VALUES
		(
	    @rCandidateId,
			 @rPresentStreetOne,
			 @rPresentStreetTwo,
			 @rPresentStreetThree,
			 @rPresentCountry,
			 @rPresentState,
			 @rPresentCity,
			 @rPresentZipCode,
			 @rPresentContactNo,
			 @rPermanentStreetOne,
			 @rPermanentStreetTwo,
			 @rPermanentStreetThree,
			 @rPermanentCountry,
			 @rPermanentState,
			 @rPermanentCity,
			 @rPermanentZipCode,
			 @rPermanentContactNo,			
			 @rCreatedUserId,
			 sCommon.fGetDate(),
			 @rCreatedUserId,
			 sCommon.fGetDate()
		)
		             
	END	 
	 ELSE
	 BEGIN

	    UPDATE  sRecruitment.tCandidateCommunications
	    SET

	   
       [PresentStreetOne] = @rPresentStreetOne
      ,[PresentStreetTwo] = @rPresentStreetTwo
      ,[PresentStreetThree] = @rPresentStreetThree
      ,[PresentCountry] = @rPresentCountry
      ,[PresentState] = @rPresentState
      ,[PresentCity] = @rPresentCity
      ,[PresentZipCode] = @rPresentZipCode
      ,[PresentContactNo] = @rPresentContactNo
      ,[PermanentStreetOne] = @rPermanentStreetOne
      ,[PermanentStreetTwo] = @rPermanentStreetTwo
      ,[PermanentStreetThree] = @rPermanentStreetThree
      ,[PermanentCountry] = @rPermanentCountry
      ,[PermanentState] = @rPermanentState
      ,[PermanentCity] = @rPermanentCity
      ,[PermanentZipCode] = @rPermanentZipCode
      ,[PermanentContactNo] = @rPermanentContactNo            
      ,[UpdatedUserId] = @rCreatedUserId
      ,[UpdatedDateTime] =  sCommon.fGetDate() 
			
	      WHERE CandidateId = @rCandidateId 	   
	 END  
		SELECT @rCandidateId AS Result
	
		COMMIT TRANSACTION
		
	
	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateApplicationConfirmGet]
	 @rCandidateId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
	CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			CC.PresentStreetOne,
			CC.PresentStreetTwo,
			CC.PresentStreetThree,
			CC.PresentCountry,
			CC.PresentState,
			CC.PresentCity,
			CC.PresentZipCode,
			CC.PresentContactNo,
			CC.PermanentStreetOne,
			CC.PermanentStreetTwo,
			CC.PermanentStreetThree,
			CC.PermanentCountry,
			CC.PermanentState,
			CC.PermanentCity,
			CC.PermanentZipCode,
			CC.PermanentContactNo,
			CI.CandidatePhoto,
			MS.Title AS MaritalStatus,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			VM.ConfirmationRemark,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			ISNULL(DM.Title,'') AS Reference,
			ISNULL(CM.MainSubject,'') AS MainSubject,
			ISNULL(OM.Title,'') AS Organization,
			ISNULL(BG.Title,'') AS BloodGroup,
			ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo	--add for mantis:34273
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId 
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId 
			LEFT JOIN sRecruitment.tCandidateCommunications	 CC ON 	CC.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tCandidateImages	CI ON CI.CandidateId=CM.Id	
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id=CM.MaritalStatusId	 		 	
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id  = CM.ReferenceId
			AND DM.DataTypeId = 13
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			LEFT JOIN sCommon.tBloodGroupMaster BG ON CM.BloodGroupId = BG.Id

  WHERE 
  
      ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
       
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateApplicationEmploymentAdd]
	
	@rCandidateApplicationEmployementXml [nvarchar](max),
	@rId bigint,
	@rOrgGroupId smallint,
	@rCandidateId bigint,
	@rCreatedUserId bigint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--DECLARE @loDoc INT
--EXEC sp_xml_preparedocument @loDoc OUTPUT, @rCandidateApplicationEmployementXml

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rCandidateApplicationEmployementXml


		
	BEGIN TRY
	--BEGIN TRANSACTION

	--comment old code because TableRowId not Updated proper in xml form

	--DECLARE @lCount INT
	--DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE  CandidateId=@rCandidateId
	--DECLARE @lNextNumber BIGINT
	--	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidatePreviousEmployment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	-- INSERT INTO sRecruitment.tCandidatePreviousEmployment
	--	(	
	--			Id,
	--			OrgGroupId,
	--			CandidateId,
	--			CompanyName,
	--			Duration,						 
	--			Designation,
	--			LastSalary,
	--			ReasonForLeaving,				
	--			CreatedUserId,
	--			CreatedDateTime,
	--			UpdatedUserId,
	--			UpdatedDateTime,
	--			JobDescription,
	--			IsCurrentlyWorking,
	--			FromDate,
	--			ToDate
				  
	--		)
	--	SELECT
	--			@lNextNumber + ROW_NUMBER() OVER(ORDER BY CandidateId)AS NewEmploymentId,
	--			@rOrgGroupId,
	--			@rCandidateId,
	--			CompanyName,
	--			Duration,						 
	--			Designation,
	--			LastSalary,
	--			ReasonForLeaving,
	--			@rCreatedUserId,
	--			sCommon.fGetDate(),
	--			@rCreatedUserId,
	--			sCommon.fGetDate(),
	--			JobDescription,
	--			IsCurrentlyWorking,
	--			(CASE WHEN FromDate ='1900-01-01' THEN NULL ELSE CONVERT(Date,FromDate ,103)   END) AS FromDate,
	--			(CASE WHEN ToDate ='1900-01-01' THEN NULL ELSE CONVERT(Date,ToDate ,103) END) AS ToDate
			
	--	FROM OPENXML (@loDoc, '/Table/CandidatePreviousEmployment', 1)
	--	WITH ( 
	--			Id int,	
	--			CandidateId bigint,			
	--			CompanyName nvarchar(100),
	--			Duration nvarchar(50),						 
	--			Designation nvarchar(100),
	--			LastSalary int,
	--			ReasonForLeaving nvarchar(200),
	--			JobDescription nvarchar(200),
	--			IsCurrentlyWorking bit,
	--			FromDate varchar(100),
	--			ToDate varchar(100)
				
	--		  ) 
	--	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/CandidatePreviousEmployment', 1)
	--			 WITH ( Id int )
	--SET @lNextNumber  = @lCount + @lNextNumber 

	DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE  CandidateId=@rCandidateId
	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		OrgGroupId smallint ,
		CandidateId bigint ,
		CompanyName nvarchar(100) ,
		Designation nvarchar(100) ,
		Duration nvarchar(50) ,
		--Remark nvarchar(200) ,
		LastSalary int ,
		ReasonForLeaving nvarchar(200) ,
		JobDescription nvarchar(200) ,
		CreatedUserId bigint ,
		CreatedDateTime datetime ,
		UpdatedUserId bigint ,
		UpdatedDateTime datetime ,
		IsCurrentlyWorking bit ,
		FromDate date ,
		ToDate date 
	)
	INSERT INTO #tempTable(
		OrgGroupId  ,
		CandidateId  ,
		CompanyName  ,
		Designation  ,
		Duration ,
		LastSalary ,
		ReasonForLeaving ,
		JobDescription ,
		CreatedUserId ,
		CreatedDateTime ,
		UpdatedUserId ,
		UpdatedDateTime ,
		IsCurrentlyWorking ,
		FromDate ,
		ToDate  
		)
		SELECT
				--@lNextNumber + ROW_NUMBER() OVER(ORDER BY CandidateId)AS NewEmploymentId,
				@rOrgGroupId,
				@rCandidateId,
				CompanyName,
				Designation,
				Duration,						 
				LastSalary,
				ReasonForLeaving,
				JobDescription,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				IsCurrentlyWorking,
				(CASE WHEN FromDate ='1900-01-01' THEN NULL ELSE CONVERT(Date,FromDate ,103)   END) AS FromDate,
				(CASE WHEN ToDate ='1900-01-01' THEN NULL ELSE CONVERT(Date,ToDate ,103) END) AS ToDate
			
		FROM OPENXML (@intDoc, '/Table/CandidatePreviousEmployment', 1)
		WITH ( 
				--Id int,	
				CandidateId bigint,			
				CompanyName nvarchar(100),
				Designation nvarchar(100),
				Duration nvarchar(50),						 
				LastSalary int,
				ReasonForLeaving nvarchar(200),
				JobDescription nvarchar(200),
				IsCurrentlyWorking bit,
				FromDate varchar(100),
				ToDate varchar(100)
			  )
			  --Select * from #tempTable
	   --SELECT 1 AS Result
	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable

	WHILE @lId <= @lCount 
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidatePreviousEmployment', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sRecruitment.tCandidatePreviousEmployment
		(	
			Id,
			OrgGroupId,
			CandidateId,
			CompanyName,
			Duration,						 
			Designation,
			LastSalary,
			ReasonForLeaving,				
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			JobDescription,
			IsCurrentlyWorking,
			FromDate,
			ToDate
				  
		)
		Select
		@lNextNumber,
		tmp.OrgGroupId,
		tmp.CandidateId,
		tmp.CompanyName,
		tmp.Duration,
		tmp.Designation,
		tmp.LastSalary,
		tmp.ReasonForLeaving,
		tmp.CreatedUserId,
		tmp.CreatedDateTime,
		tmp.UpdatedUserId,
		tmp.UpdatedDateTime,
		tmp.JobDescription,
		tmp.IsCurrentlyWorking,
		tmp.FromDate,
		tmp.ToDate
		FROM  #tempTable tmp 
		where  Id = @lId

		SET @lId=@lId+1
	END

	EXEC sp_xml_removedocument @intDoc
	SELECT 1 as Result
	DROP Table #tempTable
	END TRY	

	BEGIN CATCH 
	SELECT -1 AS Result,error_message() AS MSG
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateApplicationGet]
	@rCandidateId bigint= 0,
	@rApplicationNumber int	,
	@rOrgGroupID smallint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
				CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			ISNULL(CM.ReferenceId,0)AS ReferenceId,
			ISNULL(CM.MainSubject,'')AS MainSubject,
			ISNULL(CM.OrgId,0) AS OrgId,
			ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo	--add for mantis:34273
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId							
		WHERE 
				 CM.OrgGroupID = @rOrgGroupID
		   AND ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
		   AND ((CM.ApplicationNumber =@rApplicationNumber ) OR (@rApplicationNumber = 0))
		 
 
       
 order by CM.ApplicationNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateApplicationQualificationAdd]
	
	@rCandidateApplicationQualificationXml [nvarchar](max),
   @rId bigint,
	@rOrgGroupId smallint,
	@rCandidateId [bigint],
	@rCreatedUserId [bigint]
	--@rRelationshipId tinyint
	--,
	--@rFeeMainGroupId int,
	--@rFeeHeadId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--DECLARE @loDoc INT
--EXEC sp_xml_preparedocument @loDoc OUTPUT, @rCandidateApplicationQualificationXml
BEGIN
	

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rCandidateApplicationQualificationXml
	--comment old code because TableRowId not Updated proper in xml form
	--DECLARE @lCount INT
	--DELETE FROM sRecruitment.tCandidateQualification WHERE CandidateId=@rCandidateId
	--DECLARE @lNextNumber BIGINT
	--	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateQualification', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	-- INSERT INTO sRecruitment.tCandidateQualification
	--	(Id,	
	--		    OrgGroupId,
	--			CandidateId,
	--			ExamPassed,
	--			PassYear,
	--			Percentage,
	--			Grade,
	--			InstituteDetail,
	--			CreatedUserId,
	--			CreatedDateTime,
	--			UpdatedUserId,
	--			UpdatedDateTime,				
	--			BoardDetail,
	--			Subjects,
	--			Medium
				
				
	--			--BoardDetail,
	--			--Subjects,
	--			--Remark,
				
	--			--CreatedDateTime,
	--			--UpdatedUserId,
	--			--UpdatedDateTime
	--		)
	--	SELECT
	--	@lNextNumber + ROW_NUMBER() OVER(ORDER BY CandidateId)AS NewQualificationId,
	--			@rOrgGroupId,
	--			@rCandidateId,
	--			ExamPassed,
	--			PassYear,
	--			Percentage,
	--			Grade,
	--			InstituteDetail,
	--			@rCreatedUserId,
	--			sCommon.fGetDate(),
	--			@rCreatedUserId,
	--			sCommon.fGetDate(),
	--			BoardDetail,
	--			Subjects,
	--			Medium
	--	FROM OPENXML (@loDoc, '/Table/CandidateQualification', 1)
	--	WITH ( 
	--		Id int,	
	
	--CandidateId bigint,
	--ExamPassed nvarchar(100),
	--PassYear nvarchar(20),
	--Percentage decimal(8,2),
	--Grade nvarchar(50),
	--InstituteDetail nvarchar(200),
	--BoardDetail nvarchar(200),
	--			Subjects nvarchar(200),
	--			Medium nvarchar(100)
				
	--		  ) 
	--	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/CandidateQualification', 1)
	--			 WITH ( Id int )
	--SET @lNextNumber  = @lCount + @lNextNumber 
	--   SELECT 1 AS Result

	BEGIN TRY

	DELETE FROM sRecruitment.tCandidateQualification WHERE CandidateId=@rCandidateId

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		OrgGroupId smallint,
		CandidateId bigint,
		ExamPassed nvarchar(100),
		PassYear nvarchar(20),
		Percentage decimal(8, 2),
		Grade nvarchar(50),
		InstituteDetail nvarchar(200),
		BoardDetail nvarchar(200),
		Subjects nvarchar(200),
		--Remark nvarchar(100),
		CreatedUserId bigint,
		CreatedDateTime datetime,
		UpdatedUserId bigint,
		UpdatedDateTime datetime,
		Medium nvarchar(100)
	)
	INSERT INTO #tempTable
	(
		--Id,	
		OrgGroupId,
		CandidateId,
		ExamPassed,
		PassYear,
		Percentage,
		Grade,
		InstituteDetail,
		BoardDetail,
		Subjects,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,				
		Medium
	)
	SELECT
		--@lNextNumber + ROW_NUMBER() OVER(ORDER BY CandidateId)AS NewQualificationId,
		@rOrgGroupId,
		@rCandidateId,
		ExamPassed,
		PassYear,
		Percentage,
		Grade,
		InstituteDetail,
		BoardDetail,
		Subjects,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rCreatedUserId,
		sCommon.fGetDate(),
		Medium
	FROM OPENXML (@intDoc, '/Table/CandidateQualification', 1)
	WITH ( 
			--CandidateId bigint,
			ExamPassed nvarchar(100),
			PassYear nvarchar(20),
			Percentage decimal(8,2),
			Grade nvarchar(50),
			InstituteDetail nvarchar(200),
			BoardDetail nvarchar(200),
			Subjects nvarchar(200),
			Medium nvarchar(100)
			) 
	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable

	WHILE @lId <= @lCount 
	BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateQualification', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO sRecruitment.tCandidateQualification
			(
				Id,	
				OrgGroupId,
				CandidateId,
				ExamPassed,
				PassYear,
				Percentage,
				Grade,
				InstituteDetail,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,				
				BoardDetail,
				Subjects,
				Medium
			)
			Select
				@lNextNumber,
				tmp.OrgGroupId,
				tmp.CandidateId,
				tmp.ExamPassed,
				tmp.PassYear,
				tmp.Percentage,
				tmp.Grade,
				tmp.InstituteDetail,
				tmp.CreatedUserId,
				tmp.CreatedDateTime,
				tmp.UpdatedUserId,
				tmp.UpdatedDateTime,				
				tmp.BoardDetail,
				tmp.Subjects,
				tmp.Medium
				FROM  #tempTable tmp 
				where  Id = @lId

				SET @lId=@lId+1
	END
	EXEC sp_xml_removedocument @intDoc
	SELECT 1 as Result
	DROP Table #tempTable
	END TRY	

	BEGIN CATCH 
	SELECT -1 AS Result,error_message() AS MSG
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateBulkImagesAdd] 
	 
	@rCandidateNumber int,
	@rCandidatePhoto varbinary(max),
	@rOrgGroupId smallint,
	@rPhotoType nvarchar(50)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	
	DECLARE @lCandidateId bigint
	
	SELECT @lCandidateId=Id FROM sRecruitment.tCandidateMaster WHERE CandidateNumber=@rCandidateNumber AND OrgGroupId=@rOrgGroupId
	IF(ISNULL(@lCandidateId,'') = '')
	BEGIN
		SELECT 1 AS Result
		RETURN
	END
	
	BEGIN TRANSACTION
	
	IF NOT EXISTS(SELECT CandidateId FROM sRecruitment.tCandidateImages WHERE CandidateId=@lCandidateId)
	BEGIN 
	INSERT INTO sRecruitment.tCandidateImages
		(
			CandidateId,
			CandidatePhoto,
			UpdatedDateTime
		)
	VALUES
		(
			@lCandidateId,
			@rCandidatePhoto,
			sCommon.fGetDate()
		)
		             
	END	 
	
	 IF @rPhotoType = 'TempEmployeePhotos'
	 BEGIN
	  UPDATE sRecruitment.tCandidateImages SET CandidatePhoto=@rCandidatePhoto,UpdatedDateTime = sCommon.fGetDate() WHERE CandidateId=@lCandidateId
	 END 
	 --ELSE IF @rPhotoType = 'TempEmployeeSign'
	 --BEGIN
	 -- UPDATE sRecruitment.tCandidateMaster  SET EmployeeSign=@rEmployeeSign,UpdatedDateTime = getdate() WHERE EmployeeId=@lEmployeeId	 	 
	 --END 
	 
	 ELSE
	 BEGIN
	    UPDATE sRecruitment.tCandidateImages
	    SET
			CandidatePhoto=@rCandidatePhoto,
			UpdatedDateTime=sCommon.fGetDate()
			
	      WHERE 
			CandidateId=@lCandidateId
	      
	 END
		SELECT 1 AS Result
	  
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateCommunicationsAdd]
	 
	     @rCandidateId bigint,
         @rPresentStreetOne nvarchar(150)='',
         @rPresentStreetTwo nvarchar(150)='',
         @rPresentStreetThree nvarchar(150)='',
         @rPresentCountry nvarchar(50)='',
         @rPresentState nvarchar(50)='',
         @rPresentCity nvarchar(50)='',
         @rPresentZipCode nvarchar(20)='',
         @rPresentContactNo nvarchar(20)='',
         @rPermanentStreetOne nvarchar(150)='',
         @rPermanentStreetTwo nvarchar(150)='',
         @rPermanentStreetThree nvarchar(150)='',
         @rPermanentCountry nvarchar(50)='',
         @rPermanentState nvarchar(50)='',
         @rPermanentCity nvarchar(50)='',
         @rPermanentZipCode nvarchar(20)='',
         @rPermanentContactNo nvarchar(20)='',
         --@rEmergencyStreetOne nvarchar(150)='',
         --@rEmergencyStreetTwo nvarchar(150)='',
         --@rEmergencyStreetThree nvarchar(150)='',
         --@rEmergencyCountry nvarchar(50)='',
         --@rEmergencyState nvarchar(50)='',
         --@rEmergencyCity nvarchar(50)='',
         --@rEmergencyZipCode nvarchar(20)='',
         --@rEmergencyContactNo nvarchar(20)='',
         --@rPhoneNoCompany nvarchar(50)='',
         --@rExtensionNo nvarchar(10)='',
         --@rCompanyEmail nvarchar(100)='',
         --@rPersonalEmail nvarchar(100)='',
         --@rMobileNumber nvarchar(20)='',
         @rCreatedUserId bigint=0
    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT * FROM sRecruitment.tCandidateCommunications WHERE CandidateId = @rCandidateId)
BEGIN 
	--DECLARE @lNextNumber BIGINT     
	--EXECUTE sCommon.pTableRowIdGet 0, 'sStudent.tStudentCommunication', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sRecruitment].[tCandidateCommunications]
           (
				[CandidateId]
			   ,[PresentStreetOne]
			   ,[PresentStreetTwo]
			   ,[PresentStreetThree]
			   ,[PresentCountry]
			   ,[PresentState]
			   ,[PresentCity]
			   ,[PresentZipCode]
			   ,[PresentContactNo]
			   ,[PermanentStreetOne]
			   ,[PermanentStreetTwo]
			   ,[PermanentStreetThree]
			   ,[PermanentCountry]
			   ,[PermanentState]
			   ,[PermanentCity]
			   ,[PermanentZipCode]
			   ,[PermanentContactNo]			  
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
           )
     VALUES
           (
			 @rCandidateId,
			 @rPresentStreetOne,
			 @rPresentStreetTwo,
			 @rPresentStreetThree,
			 @rPresentCountry,
			 @rPresentState,
			 @rPresentCity,
			 @rPresentZipCode,
			 @rPresentContactNo,
			 @rPermanentStreetOne,
			 @rPermanentStreetTwo,
			 @rPermanentStreetThree,
			 @rPermanentCountry,
			 @rPermanentState,
			 @rPermanentCity,
			 @rPermanentZipCode,
			 @rPermanentContactNo,			
			 @rCreatedUserId,
			 sCommon.fGetDate(),
			 @rCreatedUserId,
			 sCommon.fGetDate()
        )
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rStudentId
	  UPDATE [sRecruitment].[tCandidateCommunications]
   SET 
      
       [PresentStreetOne] = @rPresentStreetOne
      ,[PresentStreetTwo] = @rPresentStreetTwo
      ,[PresentStreetThree] = @rPresentStreetThree
      ,[PresentCountry] = @rPresentCountry
      ,[PresentState] = @rPresentState
      ,[PresentCity] = @rPresentCity
      ,[PresentZipCode] = @rPresentZipCode
      ,[PresentContactNo] = @rPresentContactNo
      ,[PermanentStreetOne] = @rPermanentStreetOne
      ,[PermanentStreetTwo] = @rPermanentStreetTwo
      ,[PermanentStreetThree] = @rPermanentStreetThree
      ,[PermanentCountry] = @rPermanentCountry
      ,[PermanentState] = @rPermanentState
      ,[PermanentCity] = @rPermanentCity
      ,[PermanentZipCode] = @rPermanentZipCode
      ,[PermanentContactNo] = @rPermanentContactNo            
      ,[UpdatedUserId] = @rCreatedUserId
      ,[UpdatedDateTime] =  sCommon.fGetDate() 
	   
	   WHERE CandidateId = @rCandidateId   
	 END  
		SELECT 11 AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateCommunicationsGet]
	 
	 @rCandidateId bigint,
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
	
SELECT [CandidateId]
      ,ISNULL([PresentStreetOne],'') AS [PresentStreetOne]
      ,ISNULL([PresentStreetTwo],'') AS [PresentStreetTwo]
      ,ISNULL([PresentStreetThree],'') AS [PresentStreetThree]
      ,ISNULL([PresentCountry],'') AS [PresentCountry]
      ,ISNULL([PresentState],'') AS [PresentState]
      ,ISNULL([PresentCity],'') AS [PresentCity]
      ,ISNULL([PresentZipCode],'') AS [PresentZipCode]
      ,ISNULL([PresentContactNo],'') AS [PresentContactNo]
      ,ISNULL([PermanentStreetOne],'') AS [PermanentStreetOne]
      ,ISNULL([PermanentStreetTwo],'') AS [PermanentStreetTwo]
      ,ISNULL([PermanentStreetThree],'') AS [PermanentStreetThree]
      ,ISNULL([PermanentCountry],'') AS [PermanentCountry]
      ,ISNULL([PermanentState],'') AS [PermanentState]
      ,ISNULL([PermanentCity],'') AS [PermanentCity]
      ,ISNULL([PermanentZipCode],'') AS [PermanentZipCode]
      ,ISNULL([PermanentContactNo],'') AS [PermanentContactNo]
     
    
  FROM sRecruitment.tCandidateCommunications
             
  WHERE 
		 CandidateId= @rCandidateId 
		--	((SM.Code=@rCode) OR (ISNULL(@rCode,'') = ''))
		--AND(SM.OrgId=@rOrgId)

 --     ((BM.Id = @rId) OR (@rId = 0))
	--AND  ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	--AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	--AND(BM.OrgId=@rOrgId)

--ORDER BY BM.OrderIndex ASC
  
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateCriteriaScoreDetailGet]
	 
	 --@rId bigint=0 ,
	 @rOrgGroupId smallint=0,
	 @rCandidateNumber int=0,
	 @rVacancyId int=0


	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	 

BEGIN 
	 
	 
	
	SELECT 
	CM.Id,
		CM.Id AS CandidateId,
	CM.CandidateNumber,
	CM.FirstName,
	CM.MiddleName,
	CM.LastName,
	CM.FirstName+' '+CM.LastName as Name,
	ISNULL(CM.DateOfBirth,'') AS DateOfBirth,
	CM.RecruitmentStatusId,
	RS.Title AS RecruitmentStatus,
	CM.VacancyId,
	CM.Qualification,
	VM.Title AS VacancyName,
	CM.MobileNo,
	CM.PersonalEmail,
	CM.CreatedDateTime AS CandidateRegisterDate,
	CM.GenderId,
	GM.Title AS Gender,
	RSL.Remark
	
	
	
	
  FROM 
             sRecruitment.tCandidateMaster CM
             LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
             LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=CM.GenderId
               LEFT JOIN sRecruitment.tRecruitmentStatusLog  RSL ON RSL.CandidateId=CM.Id
			
			 
  WHERE  
  --((CM.Id=@rId) OR (@rId=0))
  RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
  AND
 ((CM.CandidateNumber=@rCandidateNumber) OR (@rCandidateNumber=0))
  AND ((CM.OrgGroupId=@rOrgGroupId)OR(@rOrgGroupId=0))
  AND  ((CM.VacancyId=@rVacancyId) OR (@rVacancyId=0))
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateCriteriaScoreSetupAdd]
	
		@rVacancyId bigint=0,
		@rCandidateId bigint=0,
		@rInterviewCriteriaId int=0,
		@rObtainMark decimal
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
 
 BEGIN TRANSACTION	
  
	 
	 
		--IF Exists(select ObtainMark from sAdmission.tAdmissionSetupStudent where Code=@rCode AND OrgId=@rOrgId)
		--	BEGIN
		--	select -101 as Result
		--	RETURN
		--END 
	
	
		--DECLARE @lNextNumber BIGINT
		--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCriteriaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	
	IF NOT Exists(Select ObtainMark from sRecruitment.tCandidateVacancyCriteriaScore where
	 VacancyId=@rVacancyId AND CandidateId=@rCandidateId AND InterviewCriteriaId=@rInterviewCriteriaId)
	BEGIN
	
	INSERT INTO sRecruitment.tCandidateVacancyCriteriaScore
		(
			
			 VacancyId,
			 CandidateId,
			 InterviewCriteriaId,
			 ObtainMark
		)
	VALUES
		(
			 
			@rVacancyId ,
		    @rCandidateId,
			@rInterviewCriteriaId,
			@rObtainMark 
			 
		)
		     SELECT 103 AS Result
	END	 
		
ELSE
	 
	 BEGIN
	 
	 
	    UPDATE  sRecruitment.tCandidateVacancyCriteriaScore
	    SET 
			-- AdmissionFormId = @rAdmissionFormId
			--,AdmissionSetupId = @rAdmissionSetupId
			--,
			ObtainMark = @rObtainMark
			 
			
	     WHERE
	 VacancyId=@rVacancyId AND
	  CandidateId=@rCandidateId AND
	   InterviewCriteriaId=@rInterviewCriteriaId
	
		SELECT 104 AS Result
	END
		COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateCriteriaScoreSetupAllGet]
	 
	  @rCandidateId  bigint=0,
	  @rVacancyId bigint=0
	  
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	 
BEGIN 
 
	SELECT 
			IC.Id AS InterviewCriteriaId,
			IC.CriteriaName AS InterviewCriteriaName,
			IC.TotalMark,
			ISNULL(CVC.ObtainMark,0) AS ObtainMark,
			IC.VacancyId
			
			
	 
  FROM 
             sRecruitment.tInterviewCriteria IC
             LEFT JOIN sRecruitment.tCandidateVacancyCriteriaScore CVC ON IC.Id=CVC.InterviewCriteriaId
             
			AND ((CVC.CandidateId=@rCandidateId)OR(@rCandidateId=0))
			WHERE
	 ((IC.VacancyId=@rVacancyId)OR(@rVacancyId=0))  
     
	 

	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateCriteriaScoreSetupBulkAdd]
	 	
	@rStrXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
 
	INSERT INTO	sRecruitment.tCandidateVacancyCriteriaScore
		(VacancyId,
		CandidateId,
		InterviewCriteriaId,
		ObtainMark)
	SELECT		
		A.VacancyId,
		A.CandidateId,
		A.InterviewCriteriaId,
		A.ObtainMark
	FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
	WITH ( 			
		VacancyId bigint,
		CandidateId bigint,
		InterviewCriteriaId int,		
		ObtainMark decimal(12,2)					
	) A
	LEFT JOIN sRecruitment.tCandidateVacancyCriteriaScore CVCS 
	ON A.VacancyId = CVCS.VacancyId 
	AND A.CandidateId = CVCS.CandidateId  
	AND A.InterviewCriteriaId = CVCS.InterviewCriteriaId
	WHERE 
		CVCS.VacancyId IS NULL 
		AND CVCS.CandidateId IS NULL
		AND CVCS.InterviewCriteriaId IS NULL


	UPDATE  sRecruitment.tCandidateVacancyCriteriaScore
	SET	
		ObtainMark = A.ObtainMark				
	FROM
		(SELECT 
			VacancyId,
			CandidateId,
			InterviewCriteriaId,
			ObtainMark
		FROM OPENXML (@loDoc, '/Table/ResultDetail', 1)
		WITH ( 
			VacancyId bigint,
			CandidateId bigint,
			InterviewCriteriaId int,		
			ObtainMark decimal(12,2)					
		)) A
		INNER JOIN sRecruitment.tCandidateVacancyCriteriaScore CVCS
		ON CVCS.VacancyId = A.VacancyId 
		AND CVCS.CandidateId = A.CandidateId  
		AND CVCS.InterviewCriteriaId = A.InterviewCriteriaId
		
	SELECT 1 AS Result	
 		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateDetailExportGet]
(
		@rOrgGroupID smallint, 
		@rVacancyId int=0,		
		@rCandidateNumber int=0, 
		@rFirstName nvarchar(100), 
		@rLastName nvarchar(100),
		@rRecruitmentStatusId smallint,
		@rFromDate date=null,
		@rToDate date=null ,
		@rIsQualificationDetail bit = 0
		
	
 )
AS
SET NOCOUNT ON

BEGIN
 
 		--SET @rCandidateNumber = ISNULL( sCommon.fSearchStringGet(@rCandidateNumber),0)
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		IF(@rIsQualificationDetail = 0)
		BEGIN
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				GM.Title AS Gender,
				ISNULL(MS.Title,'') AS MaritalStatus,
				ISNULL(RM.Title,'') AS Religion,
				ISNULL(CCM.Title,'') AS CastCategory,
				ISNULL(CM.FamilyCast,'') AS FamilyCast,
				ISNULL(CM.Qualification,'')AS Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL([PresentStreetOne],'') AS PresentStreetOne,
				ISNULL([PresentStreetTwo],'') AS PresentStreetTwo,
				ISNULL([PresentStreetThree],'') AS PresentStreetThree,
				ISNULL([PresentCountry],'') AS PresentCountry,
				ISNULL([PresentState],'') AS PresentState,
				ISNULL([PresentCity],'') AS PresentCity,
				ISNULL([PresentZipCode],'') AS PresentZipCode,
				ISNULL([PresentContactNo],'') AS PresentContactNo,
				ISNULL([PermanentStreetOne],'') AS PermanentStreetOne,
				ISNULL([PermanentStreetTwo],'') AS PermanentStreetTwo,
				ISNULL([PermanentStreetThree],'') AS PermanentStreetThree,
				ISNULL([PermanentCountry],'') AS PermanentCountry,
				ISNULL([PermanentState],'') AS PermanentState,
				ISNULL([PermanentCity],'') AS PermanentCity,
				ISNULL([PermanentZipCode],'') AS PermanentZipCode,
				ISNULL([PermanentContactNo],'') AS PermanentContactNo,
				CM.CreatedDateTime,
				CM.MainSubject,
				ISNULL(DM.Title,'') AS Reference,
				ISNULL(OM.Title,'') AS Organization,
				ISNULL(BGM.Title ,'') AS BloodGroup,
				ISNULL(CM.WhatsAppContactNo ,'') AS WhatsAppContactNo	--Add for Mantis: 34273
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			
			INNER JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id		
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id = CM.MaritalStatusId	
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId
			LEFT JOIN sRecruitment.tCandidateCommunications CC ON CC.CandidateId = CM.Id
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = CM.ReferenceId AND DM.DataTypeId = 13 AND DM.IsObsolete = 0
			LEFT JOIN sRecruitment.tAssignOrganization AO ON AO.VacancyId = CM.VacancyId AND AO.OrgId = CM.OrgId
			LEFT JOIN sSetup.tOrganizationMaster OM ON AO.OrgId = OM.Id
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON CM.BloodGroupId = BGM.Id

		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
			ORDER BY CM.CandidateNumber
		END
		ELSE
		BEGIN
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				GM.Title AS Gender,
				ISNULL(MS.Title,'') AS MaritalStatus,
				ISNULL(RM.Title,'') AS Religion,
				ISNULL(CCM.Title,'') AS CastCategory,
				ISNULL(CM.FamilyCast,'') AS FamilyCast,
				ISNULL(CM.Qualification,'')AS Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL([PresentStreetOne],'') AS PresentStreetOne,
				ISNULL([PresentStreetTwo],'') AS PresentStreetTwo,
				ISNULL([PresentStreetThree],'') AS PresentStreetThree,
				ISNULL([PresentCountry],'') AS PresentCountry,
				ISNULL([PresentState],'') AS PresentState,
				ISNULL([PresentCity],'') AS PresentCity,
				ISNULL([PresentZipCode],'') AS PresentZipCode,
				ISNULL([PresentContactNo],'') AS PresentContactNo,
				ISNULL([PermanentStreetOne],'') AS PermanentStreetOne,
				ISNULL([PermanentStreetTwo],'') AS PermanentStreetTwo,
				ISNULL([PermanentStreetThree],'') AS PermanentStreetThree,
				ISNULL([PermanentCountry],'') AS PermanentCountry,
				ISNULL([PermanentState],'') AS PermanentState,
				ISNULL([PermanentCity],'') AS PermanentCity,
				ISNULL([PermanentZipCode],'') AS PermanentZipCode,
				ISNULL([PermanentContactNo],'') AS PermanentContactNo,
				CM.CreatedDateTime,
				CM.MainSubject,
				ISNULL(DM.Title,'') AS Reference,
				ISNULL(OM.Title,'') AS Organization,
				ISNULL(CQ.ExamPassed,'') AS ExamPassed,
				ISNULL(CQ.PassYear,'') AS PassYear,
				CQ.Percentage,
				ISNULL(CQ.Grade,'') AS Grade,
				ISNULL(CQ.InstituteDetail,'') AS InstituteDetail,
				ISNULL(CQ.BoardDetail,'') AS BoardDetail,
				ISNULL(CQ.Medium,'') AS Medium,
				ISNULL(CQ.Subjects,'') AS Subjects,
				ISNULL(CQ.Remark,'') AS Remark,
				ISNULL(CM.WhatsAppContactNo ,'') AS WhatsAppContactNo	--Add for Mantis: 34273
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			
			INNER JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id		
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id = CM.MaritalStatusId	
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId
			LEFT JOIN sRecruitment.tCandidateCommunications CC ON CC.CandidateId = CM.Id
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = CM.ReferenceId AND DM.DataTypeId = 13 AND DM.IsObsolete = 0
			LEFT JOIN sRecruitment.tAssignOrganization AO ON AO.VacancyId = CM.VacancyId AND AO.OrgId = CM.OrgId
			LEFT JOIN sSetup.tOrganizationMaster OM ON AO.OrgId = OM.Id
			LEFT JOIN sRecruitment.tCandidateQualification CQ ON CQ.CandidateId = CM.Id

		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
			ORDER BY CM.CandidateNumber
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateFamilyDetailsAdd]
    
    @rId bigint,
	@rOrgGroupId smallint,
	@rCandidateId bigint,
	@rRelationshipId smallint,
	@rName nvarchar(100),	
	@rDateOfBirth date,
	@rBloodGroupId tinyint,
	@rIsActive bit, 
	@rCreatedUserId bigint,
	@rOccupation nvarchar(100)

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION
	
 IF NOT EXISTS(SELECT 1 FROM sRecruitment.tCandidateFamilyDetails Where Id = @rId AND CandidateId = @rCandidateId AND OrgGroupId = @rOrgGroupId)
  
  BEGIN
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateFamilyDetails', 0, 1, 1,@outNextNumber = @lNextNumber output

		IF (@rBloodGroupId <= 0)
			SET @rBloodGroupId = NULL
 
		INSERT INTO sRecruitment.tCandidateFamilyDetails
			(
				Id,
				CandidateId,
				RelationshipId,
				Name,		
				DateOfBirth,
				BloodGroupId,
				IsActive,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				OrgGroupId,
				Occupation
			)
		VALUES
			(
				@lNextNumber,
				@rCandidateId,
				@rRelationshipId,
				@rName,			
				@rDateOfBirth,
				@rBloodGroupId,
				@rIsActive,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgGroupId,
				@rOccupation
			)
	END
	ELSE
	  SET @lNextNumber = @rId
	  
	  UPDATE sRecruitment.tCandidateFamilyDetails
	  SET  
	        Name = @rName,
			RelationshipId = @rRelationshipId,			
			DateOfBirth = @rDateOfBirth,
			BloodGroupId = @rBloodGroupId,
			IsActive = @rIsActive,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			Occupation = @rOccupation
	  WHERE 
			Id = @rId 
		AND CandidateId = @rCandidateId
	  
		SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateFamilyDetailsDelete]
			
			@rId bigint,
		    @rOrgGroupId int
AS
SET NOCOUNT ON
 
BEGIN 
      
    BEGIN
     DELETE FROM sRecruitment.tCandidateFamilyDetails WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
      SELECT 1 AS RESULT
    END
         
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateFamilyDetailsGet]
	
	@rOrgGroupId int,
	@rCandidateId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
				CFD.Id,
				CandidateId,
				RelationshipId,
				RM.Title AS Relationship,
				Name,		 
				ISNULL(DateOfBirth,'0001/01/01') AS DateOfBirth,
				CONVERT(VARCHAR, DATEDIFF(YEAR, DateOfBirth, sCommon.fGetDate())) AS Age,
				ISNULL(BloodGroupId,0) AS BloodGroupId,		 
				ISNULL(BGM.Title,'')  AS BloodGroup,
				ISNULL(CFD.Occupation,'') AS Occupation,
				IsActive,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				2 AS OperationState
		FROM 
				sRecruitment.tCandidateFamilyDetails CFD
			    INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id = CFD.RelationshipId		
			    LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = CFD.BloodGroupId		 
	  WHERE 
			((CandidateId = @rCandidateId) OR (@rCandidateId = 0))
		AND CFD.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateFamilyDetailsXMLAdd]
    
	@rCandidateFamilyDetailsXml [nvarchar](max),
    @rId bigint,
	@rOrgGroupId smallint,
	@rCandidateId bigint,
	@rCreatedUserId bigint

	WITH EXECUTE AS CALLER
	AS
	SET NOCOUNT ON

	BEGIN
		DECLARE @lInterrorCode INT,@intDoc INT
		DECLARE @lNextNumber BIGINT	

		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rCandidateFamilyDetailsXml

		BEGIN TRY
		DELETE FROM sRecruitment.tCandidateFamilyDetails WHERE  CandidateId=@rCandidateId

		CREATE TABLE #tempTable  
		(
		Id bigint identity,
		OrgGroupId smallint ,
		CandidateId bigint ,
		RelationshipId Int ,
		Name nvarchar(100) ,
		RelationalDateOfBirth date,
		BloodGroupId Int ,
		IsActive bit ,
		Occupation nvarchar(100) ,
		CreatedUserId bigint ,
		CreatedDateTime datetime ,
		UpdatedUserId bigint ,
		UpdatedDateTime datetime 
		)

		INSERT INTO #tempTable(
		OrgGroupId  ,
		CandidateId  ,
		RelationshipId ,
		Name ,
		RelationalDateOfBirth,
		BloodGroupId ,
		IsActive ,
		Occupation,
		CreatedUserId ,
		CreatedDateTime ,
		UpdatedUserId ,
		UpdatedDateTime   
		)

		SELECT
				@rOrgGroupId,
				@rCandidateId,
				RelationshipId,
				Name,
				(CASE WHEN RelationalDateOfBirth ='1900-01-01' THEN NULL ELSE CONVERT(Date,RelationalDateOfBirth ,103)   END) AS RelationalDateOfBirth,					 
				BloodGroupId,
				0,
				Occupation,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate()				

		FROM OPENXML (@intDoc, '/Table/CandidateFamilyDetails', 1)
		WITH ( 
				CandidateId bigint ,
				RelationshipId Int ,
				Name nvarchar(100) ,
				RelationalDateOfBirth varchar(100),
				BloodGroupId Int ,
				IsActive bit,
				Occupation nvarchar(100)
			  )

		DECLARE @lCount int,@lId int
		SELECT @lCount = COUNT(Id) FROM #tempTable
		SELECT Top 1 @lId=Id FROM #tempTable

		WHILE @lId <= @lCount 

		BEGIN

		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateFamilyDetails', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sRecruitment.tCandidateFamilyDetails
		(	
			Id,
			OrgGroupId  ,
			CandidateId  ,
			RelationshipId ,
			Name ,
			DateOfBirth,
			BloodGroupId ,
			IsActive ,
			Occupation,			
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
				  
		)
		Select
		@lNextNumber,
		tmp.OrgGroupId,
		tmp.CandidateId,
		tmp.RelationshipId,
		tmp.Name,
		tmp.RelationalDateOfBirth,
		tmp.BloodGroupId,
		tmp.IsActive,
		tmp.Occupation,
		tmp.CreatedUserId,
		tmp.CreatedDateTime,
		tmp.UpdatedUserId,
		tmp.UpdatedDateTime
		FROM  #tempTable tmp 
		where  Id = @lId

		SET @lId=@lId+1

	END
    EXEC sp_xml_removedocument @intDoc
    SELECT 1 as Result
    DROP Table #tempTable
    END TRY	

	BEGIN CATCH 
	SELECT -1 AS Result,error_message() AS MSG
	END CATCH	
	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateImagesAdd] 
	@rCandidateId bigint,
	@rCandidatePhoto varbinary(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
	IF NOT EXISTS(SELECT CandidateId FROM sRecruitment.tCandidateImages WHERE CandidateId=@rCandidateId)
	BEGIN 
	INSERT INTO sRecruitment.tCandidateImages
		(
			CandidateId,
			CandidatePhoto
		)
	VALUES
		(
			@rCandidateId,
			@rCandidatePhoto
		)         
	END	 
	 ELSE
	 BEGIN
	    UPDATE sRecruitment.tCandidateImages
	    SET
			CandidatePhoto=@rCandidatePhoto
	      WHERE 
			CandidateId=@rCandidateId
	 END  
		SELECT 1 AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateImagesGet] 
	 
	 @rCandidateId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
  SELECT 
		ISNULL(CandidatePhoto,0) AS CandidatePhoto
		--ISNULL(EmployeeSign,0) AS EmployeeSign
  FROM 
       sRecruitment.tCandidateImages
  WHERE 
		(CandidateId=@rCandidateId)
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateMasterAdd]     
	@rOrgGroupID smallint, 
	@rVacancyId int, 
	@rId bigint, 
	@rCandidateNumber int, 
	@rFirstName nvarchar(100), 
	@rMiddleName nvarchar(100), 
	@rLastName nvarchar(100), 
	@rDateOfBirth date, 
	@rGenderId smallint, 
	@rReligionId int, 
	@rMaritalStatusId smallint, 
	@rQualification nvarchar(150),
	@rFamilyCast nvarchar(150), 
	@rCastCategoryId int, 
	@rRecruitmentStatusId smallint, 
	@rMobileNo nvarchar(20), 
	@rPersonalEmail nvarchar(100), 
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint, 	
	@rDataEntryModeId smallint, 
    @rDataEntryStatusId smallint,
	@rLastDrawnSalary decimal(12,2),
	@rExpectedSalary decimal(12,2),
	@rApplicationNumber int,
	@rApplicationPassword int,
	@rAdditionalRemark nvarchar(500),
	@rReferenceId smallint = 0,
	@rMainSubject nvarchar(100) = '',
	@rOrgId int = 0,
	@rBloodGroupId smallint = 0,
	@rWhatsAppContactNo nvarchar(20) = ''	--add for mantis:34273

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	

    

	IF EXISTS(SELECT Id FROM sRecruitment.tCandidateMaster WHERE CandidateNumber=@rCandidateNumber AND OrgGroupID=@rOrgGroupID)
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
	
    
	BEGIN TRY
 	BEGIN TRANSACTION
	
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				
		INSERT INTO sRecruitment.tCandidateMaster
			(
				OrgGroupID, 
				VacancyId, 
				Id, 
				CandidateNumber, 
				FirstName, 
				MiddleName, 
				LastName, 
				DateOfBirth, 
				GenderId, 
				ReligionId, 
				MaritalStatusId, 
				Qualification,
				FamilyCast, 
				CastCategoryId, 
				RecruitmentStatusId, 
				MobileNo, 
				PersonalEmail, 
				CreatedUserId, 
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,	
				DataEntryModeId, 
				DataEntryStatusId,
				ApplicationNumber,
				ApplicationPassword,
				LastDrawnSalary,
				ExpectedSalary,
				AdditionalRemark,
				ReferenceId,
				MainSubject,
				OrgId,
				BloodGroupId,
				WhatsAppContactNo	--add for mantis:34273
			)
		VALUES
			(
				@rOrgGroupID , 
				@rVacancyId , 
				@lNextNumber , 
				@rCandidateNumber , 
				@rFirstName , 
				@rMiddleName , 
				@rLastName , 
				@rDateOfBirth , 
				@rGenderId , 
				@rReligionId , 
				@rMaritalStatusId , 
				@rQualification ,
				@rFamilyCast, 
				@rCastCategoryId , 
				@rRecruitmentStatusId , 
				@rMobileNo , 
				@rPersonalEmail , 
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rUpdatedUserId,
				sCommon.fGetDate(),	
				@rDataEntryModeId , 
				@rDataEntryStatusId,
				@rApplicationNumber,
				@rApplicationPassword,
				@rLastDrawnSalary,
				@rExpectedSalary,
				@rAdditionalRemark,
				@rReferenceId,
				@rMainSubject,
				@rOrgId,
				@rBloodGroupId,
				@rWhatsAppContactNo	--add for mantis:34273
			)
			INSERT INTO sRecruitment.tRecruitmentStatusLog
			(
			OrgGroupId,
			CandidateId,
			RecruitmentStatusId,
			Remark,
			CreatedUserId,
			CreatedDateTime
			
			)
			VALUES
			(
			@rOrgGroupID , 
			@lNextNumber,
			@rRecruitmentStatusId,
			'',
			@rCreatedUserId,
			sCommon.fGetDate()
			)
			
		SELECT @lNextNumber AS RESULT
		 --@loEmpNumber AS EmpCode FROM sHrm.tEmployeeMaster WHERE  Id = @lNextNumber
		--SET @OutEmployeeId = @lNextNumber -- added for import employee
		
		--BEGIN 
  --      Execute sHrm.pEmployeeJobDetailAdd  
	 --      @rOrgId,@lNextNumber,@rEmployeeDesignationId,@rDepartmentId,@rDateOfJoining,@rCreatedUserId,
	 --      @rEmployeeTypeId,@rEmployeeGradeId,@rEmployeeGroupId,'',@rEmployeeManagerId
	          
	 --    Execute sHrm.pEmployeePersonalDetailAdd @rOrgId,@lNextNumber,'',@rDateOfBirth,@rGenderId,@rReligionId,
	 --    0,'',@rBloodGroupId,@rQualification,@rCreatedUserId,@rFamilyCast,@rCastCategoryId
	     
	      
	     
		--END	

		COMMIT TRANSACTION
	 
		END TRY
		
		BEGIN CATCH
		ROLLBACK TRANSACTION 
 
			--RAISERROR ('Error saving employee Master', -- Message text.
   --            16, -- Severity.
   --            1 -- State.
   --            );           
		 
 
		END CATCH			
 
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateMasterGet]
(
		@rOrgGroupID smallint, 
		@rCandidateNumber int=0,		
	@rId [bigint] = 0,
	@rVacancyId int=0
 )
AS
SET NOCOUNT ON

BEGIN

		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL(CM.ReferenceId,0) AS ReferenceId,
				ISNULL(CM.MainSubject,'')AS MainSubject,
				ISNULL(CM.OrgId,0) AS OrgId,
				ISNULL(CM.BloodGroupId,0)AS BloodGroupId,
				ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo	--add for mantis:34273
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
						
		WHERE 
				 CM.OrgGroupID = @rOrgGroupID
		   AND ((CM.Id = @rId) OR (@rId = 0))
		   AND ((CM.CandidateNumber =@rCandidateNumber ) OR (@rCandidateNumber = 0))
		   AND ((CM.VacancyId =@rVacancyId ) OR (@rVacancyId = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---USE [NetVidyalaya]

CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateMasterListGet]
(
		@rOrgGroupID smallint, 
		@rVacancyId int=0,		
		@rCandidateNumber int=0, 
		@rFirstName nvarchar(100), 
		@rLastName nvarchar(100),
		@rRecruitmentStatusId smallint ,
		@rFromDate date=null,
		@rToDate date=null,
		@rOrgId int = 0
		
	
 )
AS
SET NOCOUNT ON

BEGIN
 
 		--SET @rCandidateNumber = ISNULL( sCommon.fSearchStringGet(@rCandidateNumber),0)
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				ISNULL(OM.Title,'') AS OrganizationTitle,
				ISNULL(CM.StatusId,207) AS StatusId,		--Mantis: 34780, add by dhruvik
				ISNULL(CM.CreatedDateTime,'') AS CreatedDateTime	  --Mantis: 0037201, add by krunal
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			--LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId		
			--LEFT JOIN sRecruitment.tRecruitmentStatusLog  RSL  ON RSL.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM.Id			
		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))   
			AND ((CM.OrgId = @rOrgId) OR (@rOrgId = 0))	
			ORDER BY CM.CandidateNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateMasterListWithPhotoGet]
(
		@rOrgGroupID smallint, 
		@rVacancyId int=0,		
		@rCandidateNumber int=0, 
		@rFirstName nvarchar(100), 
		@rLastName nvarchar(100),
		@rRecruitmentStatusId smallint,
		@rFromDate date=null,
		@rToDate date=null ,
		@rOrgId int = 0
		
	
 )
AS
SET NOCOUNT ON

BEGIN
 
 		--SET @rCandidateNumber = ISNULL( sCommon.fSearchStringGet(@rCandidateNumber),0)
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				RSL.RecruitmentStatusId AS RecruitmentStatusId,
				ISNULL(CI.CandidatePhoto, CONVERT(VARBINARY(MAX), 0)) AS CandidatePhoto,
				ISNULL(OM.Title,'') AS OrganizationTitle,
				ISNULL(CM.StatusId,207) AS StatusId,		--Mantis: 0037844, add by krunal
				ISNULL(CM.CreatedDateTime,'') AS	CreatedDateTime  --Mantis: 0037201, add by krunal
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			--LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sRecruitment.tCandidateImages CI ON CI.CandidateId= CM.Id		
			LEFT JOIN sRecruitment.tRecruitmentStatusLog  RSL  ON RSL.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=RSL.RecruitmentStatusId	
			LEFT JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM.Id	AND ((CM.OrgId = @rOrgId) OR (@rOrgId = 0))				
		WHERE 
			RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
			AND	((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((RSL.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			ORDER BY CM.CandidateNumber
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateMasterRemove]
 
	@rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
				-- SET @1Result = 1
				 
				-- IF EXISTS(Select 1 FROM sPayroll.tPayProcessEmployee Where EmployeeId = @rEmployeeId)
				-- BEGIN
				--   SET @1Result = -101				   
				-- END
				 
				-- IF EXISTS(Select 1 FROM sActivity.tActivityParticipant Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN
				--   SET @1Result = -101				   
				-- END
				 
				-- ELSE IF EXISTS(Select 1 FROM sHostel.tAssignRoom where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN
				--    SET @1Result = -101
				-- END			 
				 
				-- ELSE IF EXISTS(SELECT 1 FROM sCommunication.tPollMember WHERE SourceId = @rEmployeeId AND SourceTypeId = 95)
				--  BEGIN
				--     SET @1Result = -101
				--  END
				-- ELSE IF EXISTS(SELECT 1 FROM sHrm.tEmployeeAttendance Where EmployeeId = @rEmployeeId)
				-- BEGIN
				--    SET @1Result = -101
				-- END
				 
				-- ELSE IF EXISTS(Select 1 FROM sHostel.tHostelWarden Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END		
				-- ELSE IF EXISTS(Select 1 FROM sCommunication.tDiscussionGroupMember Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	
				-- ELSE IF EXISTS(Select 1 FROM sHrm.tLeave Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END				
				--ELSE IF EXISTS(Select 1 FROM sBi.tAction Where AssignedToEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END		 
				-- ELSE IF EXISTS(Select 1 FROM sBi.tAudit Where BackupAuditorEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	 
				-- ELSE IF EXISTS(Select 1 FROM sLibrary.tBookLog  Where ReaderSourceId = @rEmployeeId and ReaderSourceTypeId = 95)
				-- BEGIN 
				--    SET @1Result = -101
				-- END			 
				-- ELSE IF EXISTS(Select 1 FROM sFee.tChargeReceipt Where SourceId = @rEmployeeId AND SourceTypeId = 95)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	 
				-- ELSE IF EXISTS(Select 1 FROM sSetup.tDivisionMaster Where InchargeEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sProcurement.tFirstAidEmoloyee Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sProcurement.tFirstAidInspection Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sOrderEntry.tIssueReturn Where ParticipantSourceId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sTimetable.tProxySetting Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sCommunication.tQueryCategoryMaster Where InchargeEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sAccounting.tReimbursement Where ParticipantSourceId = @rEmployeeId AND ParticipantSourceTypeId = 95 )
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sTimetable.tTimeTable Where EmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END
				-- ELSE IF EXISTS(Select 1 FROM sBi.tAudit Where LeadAuditorEmployeeId = @rEmployeeId)
				-- BEGIN 
				--    SET @1Result = -101
				-- END	 
				-- ELSE 
				--  BEGIN 
				--     SET @1Result = 1 
				     DELETE From  sRecruitment.tCandidateCommunications Where  CandidateId= @rId 			
					 DELETE From  sRecruitment.tCandidatePreviousEmployment Where CandidateId= @rId 
					 DELETE From    sRecruitment.tCandidateQualification Where CandidateId= @rId 
					  --Delete From sHrm.tEmployeeImages where EmployeeId=@rId
					  
					  
					  
					 --DELETE From sHrm.tEmployeeFamilyDetails Where CandidateId= @rId 
					 --DELETE From sHrm.tEmployeePreviousEmployment Where EmployeeId = @rId
					 --Delete From sHrm.tEmployeeImages where EmployeeId=@rId
					--Delete from sSecurity.tDivisionPermission Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					--Delete from sSecurity.tUserPreference Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					--Delete from sSecurity.tUserProfile Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					--Delete from sSecurity.tUserRole Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95)
					--Delete from sSecurity.tUser Where SourceId=@rId AND SourceTypeId=95
					
					--UPDATE sSecurity.tUser SET SourceTypeId = 1,SourceId = 0 WHERE SourceTypeId = 95 AND SourceId = @rId
					
					DELETE FROM  sRecruitment.tCandidateMaster Where Id = @rId
				  COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateMasterUpdate] 
	
    
	@rVacancyId int, 
	@rId bigint, 
	@rCandidateNumber int, 
	@rFirstName nvarchar(100), 
	@rMiddleName nvarchar(100), 
	@rLastName nvarchar(100), 
	@rDateOfBirth date, 
	@rGenderId smallint, 
	@rReligionId int, 
	@rMaritalStatusId smallint, 
	@rQualification nvarchar(150),
	@rFamilyCast nvarchar(150), 
	@rCastCategoryId int, 
	@rRecruitmentStatusId smallint, 
	@rMobileNo nvarchar(20), 
	@rPersonalEmail nvarchar(100), 	
	@rUpdatedUserId bigint,
	@rLastDrawnSalary decimal(12,2),
	@rExpectedSalary decimal(12,2),
	@rAdditionalRemark nvarchar(500),
	@rReferenceId smallint = 0,
	@rMainSubject nvarchar(100) = '',
	@rOrgId int= 0 	,
	@rBloodGroupId smallint = 0,
	@rWhatsAppContactNo nvarchar(20) = ''	--add for mantis:34273


	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	
	DECLARE @lOrgGroupID int
	
	SELECT @lOrgGroupID = OrgGroupID FROM sRecruitment.tCandidateMaster WHERE Id=@rId

	IF EXISTS(SELECT Id FROM sRecruitment.tCandidateMaster WHERE CandidateNumber=@rCandidateNumber AND OrgGroupID=@lOrgGroupID AND Id<>@rId)
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
			
	 UPDATE sRecruitment.tCandidateMaster
		SET
				VacancyId=@rVacancyId, 			
				CandidateNumber=@rCandidateNumber, 
				FirstName=@rFirstName, 
				MiddleName=@rMiddleName, 
				LastName=@rLastName, 
				DateOfBirth=@rDateOfBirth, 
				GenderId=@rGenderId, 
				ReligionId=@rReligionId, 
				MaritalStatusId=@rMaritalStatusId, 
				Qualification=@rQualification,
				FamilyCast=@rFamilyCast, 
				CastCategoryId=@rCastCategoryId, 
				RecruitmentStatusId=@rRecruitmentStatusId, 
				MobileNo=@rMobileNo, 
				PersonalEmail=@rPersonalEmail, 				
				UpdatedUserId=@rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LastDrawnSalary=@rLastDrawnSalary,
				ExpectedSalary=@rExpectedSalary,
				AdditionalRemark =@rAdditionalRemark,
				ReferenceId = @rReferenceId ,
				MainSubject = @rMainSubject ,
				OrgId = @rOrgId,
				BloodGroupId = @rBloodGroupId,
				WhatsAppContactNo = @rWhatsAppContactNo	--add for mantis:34273
	  WHERE 
			Id = @rId
	  
	SELECT @rId AS RESULT
	
	--BEGIN 
	--UPDATE sHrm.tEmployeeJobDetail
	--	SET 
	--		EmployeeDesignationId = @rEmployeeDesignationId,	
	--		OrganizationDepartmentId = @rDepartmentId,
	--		DateOfJoining =	@rDateOfJoining,
	--		UpdatedUserId = @rUpdatedUserId,
	--		EmployeeTypeId = @rEmployeeTypeId,
	--		EmployeeGradeId = @rEmployeeGradeId,
	--		EmployeeGroupId = @rEmployeeGroupId
	--	WHERE 
	--		EmployeeId = @rId
	
	--UPDATE sHrm.tEmployeePersonalDetail
	--	SET 
	--		DateOfBirth	=	@rDateOfBirth,
	--		GenderId	=	@rGenderId,
	--		UpdatedUserId = @rUpdatedUserId
	--	WHERE 
	--		EmployeeId = @rId	
	
	--IF @rStatusId = 9
	--BEGIN
	--	UPDATE sSecurity.tUser
	--		SET 
	--			IsObsolete = 1,
	--			UpdatedUserId = @rUpdatedUserId,
	--			UpdatedDateTime = sCommon.fGetDate()
	--		WHERE 
	--			SourceId = @rId AND SourceTypeId = 95
	--END
	--ELSE IF @rStatusId = 7

	--BEGIN
	--	UPDATE sSecurity.tUser
	--		SET 
	--			IsObsolete = 0,
	--			UpdatedUserId = @rUpdatedUserId,
	--			UpdatedDateTime = sCommon.fGetDate()
	--		WHERE 
	--			SourceId = @rId AND SourceTypeId = 95
	--END
	  
	  --BEGIN
	  --   Execute sHrm.pEmployeeJobDetailModify 
	  --     0,@rId,0,@rEmployeeDesignationId,@rLocationId,@rDepartmentId,@rDateOfJoining,'','',0,0,@rUpdatedUserId,
	  --     0,0,@rEmployeeTypeId,@rProcessTypeId,NULL,NULL,NULL,0,0
	     --Execute sHrm.pEmployeePersonalDetailModify
	  
   --  0,@rId,'',@rDateOfBirth,@rGenderId,0,0,'','',0,0,'','','','','',0,'',0,'',0,0,@rUpdatedUserId,@rIsBirthDateUnknown
	     
	  --END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidatePreviousEmploymentAdd]
	
	@rId bigint,
	@rOrgGroupId smallint,
	@rCandidateId [bigint],
	@rCompanyName [nvarchar](300),	
	@rDesignation nvarchar(100), 
	@rDuration [nvarchar](300),
	@rRemark nvarchar(200),
	@rLastSalary int,
	@rReasonForLeaving nvarchar(100),
	@rJobDescription nvarchar(100),
	--@rIsInternal bit,
	@rCreatedUserId [bigint],
	@rIsCurrentlyWorking bit,
	@rFromDate Date ='',
	@rToDate Date = ''
 
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
 IF NOT EXISTS(SELECT 1 FROM sRecruitment.tCandidatePreviousEmployment WHERE Id = @rId AND CandidateId = @rCandidateId AND OrgGroupId = @rOrgGroupId)
		
		BEGIN		
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidatePreviousEmployment', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sRecruitment.tCandidatePreviousEmployment
			(
				Id,
				CandidateId,
				CompanyName,						 
				Designation,
				Remark,
				Duration,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				OrgGroupId,
			    LastSalary,
			    ReasonForLeaving,
			    JobDescription,
				IsCurrentlyWorking,
				FromDate,
				ToDate
			 
			)
		VALUES
			(
				@lNextNumber,
				@rCandidateId,
				@rCompanyName, 			
				@rDesignation,
				@rRemark,
				@rDuration,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgGroupId,
				@rLastSalary,
			    @rReasonForLeaving,
			    @rJobDescription,
				@rIsCurrentlyWorking,
				@rFromDate,
				@rToDate
			    
			)
		END
  ELSE
    BEGIN
       SET @lNextNumber = @rId
      UPDATE sRecruitment.tCandidatePreviousEmployment
		SET 			
			CompanyName = @rCompanyName,				
			Designation = @rDesignation,
			Remark = @rRemark,		 
			Duration = @rDuration,		 
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			LastSalary = @rLastSalary,
			ReasonForLeaving = @rReasonForLeaving,
			JobDescription = @rJobDescription,
			IsCurrentlyWorking=@rIsCurrentlyWorking,
			FromDate = @rFromDate,
			ToDate = @rToDate
			
	  WHERE 
			Id = @rId 
		AND CandidateId = @rCandidateId
    END		
		SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	--Select ERROR_Message()
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidatePreviousEmploymentDelete]
	
	@rId [bigint],
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 DELETE FROM sRecruitment.tCandidatePreviousEmployment
	 
	  WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
	  
	  SELECT 1 AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidatePreviousEmploymentGet]
	
	@rOrgGroupId smallint,
	@rCandidateId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			Id,
			CandidateId,
			CompanyName, 		
			ISNULL(Designation,'') AS Designation,
			ISNULL(Remark,'') AS Remark, 
			ISNULL(Duration,'') AS Duration ,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			2 AS OperationState,
			ISNULL(LastSalary,0) AS Lastsalary,
		    ISNULL(ReasonForLeaving,'') AS ReasonForLeaving,
		    ISNULL(JobDescription,'') AS JobDescription,
			IsCurrentlyWorking,
			FromDate,
			ToDate
			--(CASE WHEN IsCurrentlyWorking IS NULL THEN 'NO' 
			--	 WHEN IsCurrentlyWorking =1 THEN 'YES'
			--	 WHEN IsCurrentlyWorking =0 THEN 'NO' END)AS IsCurrentlyWorking
		   
	 FROM 
			sRecruitment.tCandidatePreviousEmployment
	 WHERE 
			 (CandidateId = @rCandidateId) 
		AND OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateQualificationDetailsAdd]
    
    @rId bigint,
	@rOrgGroupId smallint,
	@rCandidateId [bigint],
	@rExamPassed [nvarchar](100),
	@rPassYear [nvarchar](20),
	@rPercentage [decimal](8,2),
	@rGrade [nvarchar](50),
	@rInstituteDetail [nvarchar](200),
	@rBoardDetail [nvarchar](200),
	@rSubjects [nvarchar](200),
	@rRemark [nvarchar](100),
	@rCreatedUserId [bigint],
	@rMedium [nvarchar](100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION
	
 IF NOT EXISTS(SELECT 1 FROM sRecruitment.tCandidateQualification Where Id = @rId AND CandidateId = @rCandidateId AND OrgGroupId = @rOrgGroupId)
  
  BEGIN
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateQualification', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		
		INSERT INTO sRecruitment.tCandidateQualification
			(
				OrgGroupId,
				Id,	
				CandidateId,
				ExamPassed,
				PassYear,
				Percentage,
				Grade,
				InstituteDetail,
				BoardDetail,
				Subjects,
				Remark,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				Medium
			)
		VALUES
			(
				@rOrgGroupId,
				@lNextNumber,
				@rCandidateId,
				@rExamPassed,
				@rPassYear,
				@rPercentage,
				@rGrade,
				@rInstituteDetail,
				@rBoardDetail,
				@rSubjects,
				@rRemark,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rMedium
			)
			 
	END
	ELSE
	BEGIN
	  SET @lNextNumber = @rId
	  
	  UPDATE sRecruitment.tCandidateQualification
	  SET  
	        ExamPassed = @rExamPassed,
			PassYear = @rPassYear,			
			Percentage = @rPercentage,
			Grade = @rGrade,
			InstituteDetail = @rInstituteDetail,
			BoardDetail = @rBoardDetail,
			Subjects = @rSubjects,
			Remark = @rRemark,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			Medium = @rMedium
			
	  WHERE 
			Id = @rId 
		AND CandidateId = @rCandidateId
	  END
		SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateQualificationDetailsDelete]
			
			@rId bigint,
		    @rOrgGroupId int
AS
SET NOCOUNT ON
 
BEGIN 
      
    BEGIN
     DELETE FROM sRecruitment.tCandidateQualification WHERE Id = @rId AND OrgGroupId = @rOrgGroupId
      SELECT 1 AS RESULT
    END
         
  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pCandidateQualificationDetailsGet]
	
	@rOrgGroupId int,
	@rCandidateId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			--convert(nvarchar(20),EmployeeId) AS EmployeeIdText,
			--convert(nvarchar(20),@rOrgId) AS OrgIdText,
			OrgGroupId,
			Id,
			CandidateId,
			ISNULL(ExamPassed,'') AS ExamPassed,
			
			ISNULL(PassYear,'') AS PassYear,
			ISNULL(Percentage,0) AS Percentage,
			ISNULL(Grade,'') AS Grade,
			ISNULL(InstituteDetail,'') AS InstituteDetail,
			ISNULL(BoardDetail,'') AS BoardDetail,
			ISNULL(Subjects,'') AS Subjects,
			ISNULL(Remark,'') AS Remark,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ISNULl(Medium,'')AS Medium
		
		
	 FROM 
			sRecruitment.tCandidateQualification
	 WHERE 
			 (CandidateId = @rCandidateId) OR @rCandidateId=0
		AND OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sRecruitment].[pInterviewCriteriaAdd]
	 
	 	
        @rId int,
        @rVacancyId int,
        @rTotalMarks decimal(12,2),
		@rCriteriaName nvarchar(150),
		@rOrgGroupId int=0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tInterviewCriteria', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sRecruitment.tInterviewCriteria
		(
			
			Id,
			VacancyId,			
			TotalMark,
			CriteriaName
		)
	VALUES
		(
			 
			@lNextNumber,			
			@rVacancyId,
			@rTotalMarks,
			@rCriteriaName
		)
		     SELECT @lNextNumber AS Result
	
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sRecruitment.tInterviewCriteria
	    SET
	
			VacancyId=@rVacancyId,
			TotalMark=@rTotalMarks,
			CriteriaName=@rCriteriaName
	      
	      WHERE Id = @rId
	     SELECT @lNextNumber AS Result
	 END  	

 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sRecruitment].[pInterviewCriteriaDelete]
@rId int
AS
BEGIN
 	 
		DELETE	FROM sRecruitment.tInterviewCriteria WHERE Id=@rId	
		SELECT 1 AS RESULT
	   
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sRecruitment].[pInterviewCriteriaGet]
	 
	 @rVacancyId int=0		
	 	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	 
	SELECT 
		Id,
		VacancyId,
		TotalMark,
		CriteriaName	 
      
  FROM 
            sRecruitment.tInterviewCriteria
			 
  WHERE 
   (VacancyId=@rVacancyId)
  
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sRecruitment].[pInterviewCriteriaVacanyDelete]
@rVacancyId int
AS
BEGIN
 	 
		DELETE	FROM sRecruitment.tInterviewCriteria WHERE VacancyId=@rVacancyId
		SELECT 1 AS RESULT
	   
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pRecruitmentDocumentAdd]
	 
	 	
        @rDocumentId int,
        @rVacancyId bigint,
		@rRemark nvarchar(1000),
		@rIsMandatory bit
	 	
        

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	DECLARE @rCountId int 

	SET @rCountId = (SELECT ISNULL(COUNT(1),0) FROM sRecruitment.tRecruitmentCriteriaDocument WHERE VacancyId=@rVacancyId AND SubmitDocumentMasterId= @rDocumentId)

	BEGIN		
	
	if(@rCountId = 0)
	BEGIN
	INSERT INTO sRecruitment.tRecruitmentCriteriaDocument
		([VacancyId],[SubmitDocumentMasterId],[Remark],[IsMandatory])
	VALUES
		(@rVacancyId,@rDocumentId,@rRemark,@rIsMandatory)
		     SELECT 11 AS Result	
	END
	ELSE
		UPDATE sRecruitment.tRecruitmentCriteriaDocument SET [VacancyId]=@rVacancyId,[SubmitDocumentMasterId]=@rDocumentId, [Remark]=@rRemark,IsMandatory=@rIsMandatory
		WHERE  [VacancyId]=@rVacancyId AND [SubmitDocumentMasterId]= @rDocumentId

		     SELECT 11 AS Result	 
	END

	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pRecruitmentDocumentGet]
	 
	@rVacancyId bigint,
	@rDocumentId int,
	@rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
WITH CombinedResults AS ( -- Changed for mantis : 35443 by Nilesh
	SELECT 
		RCD.VacancyId,RCD.SubmitDocumentMasterId AS DocumentId,SDM.DocumentName,ISNULL(RCD.Remark,'') AS Remark,ISNULL(RCD.IsMandatory,0) IsMandatory 
	FROM 
		sRecruitment.tRecruitmentCriteriaDocument RCD
		INNER JOIN sCommon.tSubmitDocumentMaster SDM ON SDM.Id = RCD.SubmitDocumentMasterId and SDM.OrgId=@rOrgId --mantis: 44743, change LEFT JOIN to INNER JOIN
	WHERE 
		(RCD.VacancyId = @rVacancyId OR ISNULL(@rVacancyId,0)=0)
		AND (RCD.SubmitDocumentMasterId = @rDocumentId OR ISNULL(@rDocumentId,0)=0)

		UNION
		SELECT 
		0 VacancyId,Id AS DocumentId,DocumentName,'' AS Remark,CAST('FALSE' as bit) IsMandatory
	FROM 
		sCommon.tSubmitDocumentMaster SDM		
		WHERE  SubmitDocumentFunctionalityId=4 AND ID NOT IN(SELECT SubmitDocumentMasterId FROM sRecruitment.tRecruitmentCriteriaDocument WHERE VacancyId = @rVacancyId )
		AND OrgId=@rOrgId
			)

	/******Added for mantis : 35443 by Nilesh******/
	SELECT 
	    VacancyId,
	    DocumentId,
	    DocumentName,
	    Remark,
	    IsMandatory
	FROM 
	    CombinedResults
	ORDER BY 
	    DocumentId ASC;

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pRecruitmentRecruiterDocumentAdd]
	 
        @rRecruitmentId bigint,
		@rSubmitDocumentMasterId int,
		@rDocumenet NVARCHAR(MAX)
		--@rDocumenetXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		
	BEGIN		
	
	declare @rCount int

	Set @rCount = (SELECT ISNULL(COUNT (*),0)  FROM sRecruitment.tRecruitmentRecruiterDocument WHERE RecruitmentId = @rRecruitmentId AND SubmitDocumentMasterId= @rSubmitDocumentMasterId )

	
	IF(@rCount =0)
	BEGIN
	Select @rCount
		INSERT INTO sRecruitment.tRecruitmentRecruiterDocument
			([RecruitmentId],[SubmitDocumentMasterId],[DocumentName])
		VALUES
			(@rRecruitmentId,@rSubmitDocumentMasterId,@rDocumenet)
				 SELECT 1 AS Result	
	END
	ELSE
	BEGIN
		UPDATE  sRecruitment.tRecruitmentRecruiterDocument  SET  SubmitDocumentMasterId= @rSubmitDocumentMasterId ,DocumentName=@rDocumenet   WHERE RecruitmentId = @rRecruitmentId AND SubmitDocumentMasterId= @rSubmitDocumentMasterId 
	END
	
	SELECT 1 AS Result 
	
	COMMIT TRANSACTION
	END
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pRecruitmentRecruiterDocumentDelete]
	 
        @rRecruitmentId bigint,
		@rDocumentId bigint
		--@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
	
	DELETE FROM sRecruitment.tRecruitmentRecruiterDocument Where RecruitmentId=@rRecruitmentId and SubmitDocumentMasterId=@rDocumentId
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pRecruitmentRecruiterDocumentSubmitGet]
	 
        @rRecruitmentId bigint,
		@rOrgId bigint,
		@rVacancyId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN

	IF(@rRecruitmentId =0)
	BEGIN
			--SELECT  Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName, ISNULL(S.DocumentName,'') as DocumentFileName,
			--CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'False'END AS IsCheck, (SELECT ISNULL(IsMandatory,0) from  sRecruitment.tRecruitmentCriteriaDocument where SubmitDocumentMasterId = D.Id and VacancyId=@rVacancyId) IsMandatory
			-- --'False' AS IsCheck
		 --	FROM sCommon.tSubmitDocumentMaster D
			--LEFT JOIN sRecruitment.tRecruitmentRecruiterDocument  S ON S.SubmitDocumentMasterId=D.id AND (S.RecruitmentId= @rRecruitmentId  OR @rRecruitmentId=0)
			--WHERE  SubmitDocumentFunctionalityId='4' AND D.OrgId=@rOrgId AND D.Id IN (select SubmitDocumentMasterId from sRecruitment.tRecruitmentCriteriaDocument WHERE VacancyId=@rVacancyId )
			
SELECT  Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName, '' as DocumentFileName,
			'False' AS IsCheck, (SELECT ISNULL(IsMandatory,0) from  sRecruitment.tRecruitmentCriteriaDocument where SubmitDocumentMasterId = D.Id and VacancyId=@rVacancyId) IsMandatory
			 --'False' AS IsCheck
		 	FROM sCommon.tSubmitDocumentMaster D
			--LEFT JOIN sRecruitment.tRecruitmentRecruiterDocument  S ON S.SubmitDocumentMasterId=D.id AND (S.RecruitmentId= 0  OR 0=0)
			WHERE  SubmitDocumentFunctionalityId='4' AND D.OrgId=@rOrgId AND D.Id IN (select SubmitDocumentMasterId from sRecruitment.tRecruitmentCriteriaDocument WHERE VacancyId=@rVacancyId )
	END

	ELSE
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,ISNULL(S.DocumentName,'') as DocumentFileName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck,(SELECT ISNULL(IsMandatory,0) from  sRecruitment.tRecruitmentCriteriaDocument where SubmitDocumentMasterId = D.Id and VacancyId=@rVacancyId ) IsMandatory
			-- 'False'  AS IsCheck
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT JOIN sRecruitment.tRecruitmentRecruiterDocument  S ON S.SubmitDocumentMasterId=D.id AND (S.RecruitmentId= @rRecruitmentId  OR @rRecruitmentId=0)
			WHERE  SubmitDocumentFunctionalityId='4' AND  D.OrgId=@rOrgId AND D.Id IN (select SubmitDocumentMasterId from sRecruitment.tRecruitmentCriteriaDocument WHERE VacancyId=@rVacancyId )
			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pRecruitmentStatusBulkAdd]    
	@rOrgGroupID int, 
	@rCandidateId bigint,
	@rRecruitmentStatusId tinyint,
	@rRemark nvarchar(100),
	@rCreatedUserId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	--IF EXISTS(SELECT Id FROM sRecruitment.tCandidateMaster WHERE CandidateNumber=@rCandidateNumber AND OrgGroupID=@rOrgGroupID)
	--	BEGIN
	--	SELECT -101 as Result
	--	RETURN
	--END 
	
    
	BEGIN TRY
 	BEGIN TRANSACTION							
		INSERT INTO sRecruitment.tRecruitmentStatusLog
			(
				OrgGroupID, 
				CandidateId,
				RecruitmentStatusId,
				Remark,
				CreatedUserId,
				CreatedDateTime			
			)
		VALUES
			(
				@rOrgGroupID , 
				@rCandidateId,
				@rRecruitmentStatusId ,
				@rRemark ,
				@rCreatedUserId ,
				sCommon.fGetDate()
				
			)
		
			UPDATE sRecruitment.tCandidateMaster SET RecruitmentStatusId=@rRecruitmentStatusId Where Id=@rCandidateId
		SELECT 1 AS RESULT
	

		COMMIT TRANSACTION
	 
		END TRY
		
		BEGIN CATCH
		ROLLBACK TRANSACTION 
 SELECT -1 AS RESULT
			--RAISERROR ('Error saving employee Master', -- Message text.
   --            16, -- Severity.
   --            1 -- State.
   --            );           
		 
 
		END CATCH			
 
	
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pRecruitmentStatusBulkGet]
(
		@rOrgGroupID smallint, 
		@rVacancyId int=0,		
		@rCandidateNumber int=0, 	
		@rName nvarchar(100),	
	@rRecruitmentStatusId smallint=0
	 			
 )
AS
SET NOCOUNT ON

BEGIN  
			SET @rName = ISNULL( sCommon.fSearchStringGet(@rName),'')
			
	SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				
				CM.Qualification,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RSL.RecruitmentStatusId AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				RSL.Remark,
				CM.MobileNo,
				CM.PersonalEmail,
				--(SELECT SUM(Duration) FROM sRecruitment.tCandidatePreviousEmployment PE WHERE PE.CandidateId=RSL.CandidateId group by CandidateId)AS Experience,
			ISNULL((SELECT SUM(ObtainMark)From sRecruitment.tCandidateVacancyCriteriaScore CS  WHERE CS.CandidateId = RSL.CandidateId AND CS.VacancyId=@rVacancyId group by CandidateId),0)AS TotalObtainMark
             FROM sRecruitment.tRecruitmentStatusLog  RSL

			LEFT JOIN sRecruitment.tCandidateMaster CM ON RSL.CandidateId=CM.Id
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=RSL.RecruitmentStatusId	
		
			--LEFT JOIN sRecruitment.tCandidateVacancyCriteriaScore CCS ON CCS.CandidateId=RSL.CandidateId AND CCS.VacancyId=CM.VacancyId
           WHERE RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
                 
         AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
         AND CM.OrgGroupID = @rOrgGroupID    
         AND ((CM.FirstName Like '%' + @rName  + '%') OR (@rName = ''))	
           AND ((CM.CandidateNumber =@rCandidateNumber ) OR (@rCandidateNumber = 0))
             AND ((CM.RecruitmentStatusId =@rRecruitmentStatusId ) OR (@rRecruitmentStatusId = 0))
           					
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sRecruitment].[pRecruitmentStatusGet]
	 
	 --@rId bigint=0 ,
	 @rOrgGroupId smallint=0,
	 @rCandidateNumber int=0,
	 @rVacancyId int=0	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 
	SELECT 
	CM.Id,
	CM.CandidateNumber,
	CM.FirstName,
	CM.MiddleName,
	CM.LastName,
	CM.FirstName+''+CM.LastName as Name,
	ISNULL(CM.DateOfBirth,'') AS DateOfBirth,
	CM.RecruitmentStatusId,
	RS.Title AS RecruitmentStatus,
	CM.VacancyId,
	VM.Title AS VacancyName,
	CM.MobileNo,
	CM.PersonalEmail,
	CM.CreatedDateTime AS CandidateRegisterDate,
	CM.GenderId,
	GM.Title AS Gender,
	RSL.Remark
	
	
	
	
  FROM 
             sRecruitment.tCandidateMaster CM
             LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
             INNER JOIN sCommon.tGenderMaster GM ON GM.Id=CM.GenderId
             LEFT JOIN sRecruitment.tRecruitmentStatusLog  RSL ON RSL.CandidateId=CM.Id
             
			
			 
  WHERE  
  --((CM.Id=@rId) OR (@rId=0))
 ((CM.CandidateNumber=@rCandidateNumber) OR (@rCandidateNumber=0))
  AND ((CM.OrgGroupId=@rOrgGroupId)OR(@rOrgGroupId=0))
  AND  ((CM.VacancyId=@rVacancyId) OR (@rVacancyId=0))
   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pRecruitmentStatusLogCandidateDetailsGet]
(
		@rOrgGroupID smallint, 
		@rCandidateNumber int=0,		
		@rCandidateId [bigint] = 0,
		@rRecruitmentStatusId tinyint=0,
		@rVacancyId int=0,
		@rFromDate datetime,
		@rToDate datetime	
	
 )
AS
SET NOCOUNT ON

BEGIN

		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				
				CM.Qualification,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RSL.RecruitmentStatusId AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				RSL.Remark,
				RSL.CreatedDateTime
				--(SELECT SUM(Duration) FROM sRecruitment.tCandidatePreviousEmployment PE WHERE PE.CandidateId=RSL.CandidateId group by CandidateId)AS Experience,
			--ISNULL((SELECT SUM(ObtainMark)From sRecruitment.tCandidateVacancyCriteriaScore CS  WHERE CS.CandidateId = RSL.CandidateId AND CS.VacancyId=@rVacancyId group by CandidateId),0)AS TotalObtainMark
					
		FROM sRecruitment.tRecruitmentStatusLog  RSL
		
			LEFT JOIN sRecruitment.tCandidateMaster CM ON RSL.CandidateId=CM.Id
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=RSL.RecruitmentStatusId							
		WHERE 
				 CM.OrgGroupID = @rOrgGroupID
		   AND ((RSL.CandidateId = @rCandidateId) OR (@rCandidateId = 0))
		   AND ((CM.CandidateNumber =@rCandidateNumber ) OR (@rCandidateNumber = 0))
		   AND ((RSL.RecruitmentStatusId =@rRecruitmentStatusId ) OR (@rRecruitmentStatusId = 0))
		    AND ((CM.VacancyId =@rVacancyId ) OR (@rVacancyId = 0))
		     AND ((CAST(RSL.CreatedDateTime AS Date) >= CAST(@rFromDate AS Date)) OR (ISNULL(CASt(@rFromDate AS Date),'') = ''))
      AND ((CAST(RSL.CreatedDateTime AS Date) <= CAST(@rToDate AS Date)) OR (ISNULL(CAST(@rToDate AS Date),'') = ''))
      order by CM.CandidateNumber,RSL.CreatedDateTime desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pRptCandidateApplicationGet]
	 @rCandidateId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
				convert(nvarchar(20),@rCandidateId) AS CandidateIdText,
				CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			CC.PresentStreetOne,
			CC.PresentStreetTwo,
			CC.PresentStreetThree,
			CC.PresentCountry,
			CC.PresentState,
			CC.PresentCity,
			CC.PresentZipCode,
			CC.PresentContactNo,
			CC.PermanentStreetOne,
			CC.PermanentStreetTwo,
			CC.PermanentStreetThree,
			CC.PermanentCountry,
			CC.PermanentState,
			CC.PermanentCity,
			CC.PermanentZipCode,
			CC.PermanentContactNo,
			CI.CandidatePhoto,
			MS.Title AS MaritalStatus,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			CM.CreatedDateTime,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			ISNULL(DM.Title,'') AS Reference,
			ISNULL(CM.MainSubject,'') AS MainSubject,
			ISNULL(OM.Title,'') AS Organization,
			ISNULL(BG.Title,'') AS BloodGroup,
			ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo	--add for mantis:34273
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId 
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId 
			LEFT JOIN sRecruitment.tCandidateCommunications	 CC ON 	CC.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tCandidateImages	CI ON CI.CandidateId=CM.Id	
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id=CM.MaritalStatusId	 	
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id  = CM.ReferenceId
			AND DM.DataTypeId = 13
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			LEFT JOIN sCommon.tBloodGroupMaster BG ON CM.BloodGroupId = BG.Id
		
  WHERE 
  
      ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
       
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sRecruitment].[pRptCandidateEmployementSubGet]
	
	@rCandidateId [bigint] = 0

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	 SELECT 
	 convert(nvarchar(20),CandidateId) AS CandidateIdText,
			Id,
			CandidateId,
			CompanyName, 		
			ISNULL(Designation,'') AS Designation,
			ISNULL(Remark,'') AS Remark, 
			ISNULL(Duration,'') AS Duration ,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			2 AS OperationState,
			ISNULL(LastSalary,0) AS Lastsalary,
		    ISNULL(ReasonForLeaving,'') AS ReasonForLeaving,
		    ISNULL(JobDescription,'') AS JobDescription,
			IsCurrentlyWorking,
			FromDate,
			ToDate
	
	      
  FROM  
		    		sRecruitment.tCandidatePreviousEmployment
	 WHERE 
			 (CandidateId = @rCandidateId) 
		
	
								
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sRecruitment].[pRptCandidateFamilySubGet]
	
	@rCandidateId bigint = 0

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	 SELECT 
	       convert(nvarchar(20),CFD.CandidateId) AS CandidateIdText,
			CFD.Id,
			CFD.CandidateId,
			ISNULL(RM.Title,'') AS Relationship,
			CFD.Name ,
			ISNULL(BGM.Title,'') AS BloodGroup,
			CFD.DateOfBirth,	
			ISNULL(CFD.Occupation,'') AS Occupation,
			DATEDIFF(hour,Convert(Date,CFD.DateOfBirth,103),GETDATE())/8766 AS Age

  FROM  
		    sRecruitment.tCandidateFamilyDetails CFD
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON CFD.BloodGroupId = BGM.Id
			LEFT JOIN sCommon.tRelationshipMaster RM ON CFD.RelationshipId = RM.Id
	 WHERE 
			 (CFD.CandidateId = @rCandidateId) 
		
	
								
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sRecruitment].[pRptCandidateQualificationSubGet]
	
	@rCandidateId [bigint] = 0

AS
 SET NOCOUNT ON
			 

BEGIN 
	
	 SELECT 
			convert(nvarchar(20),CandidateId) AS CandidateIdText,
			--convert(nvarchar(20),@rOrgId) AS OrgIdText,
			OrgGroupId,
			Id,
			CandidateId,
			ISNULL(ExamPassed,'') AS ExamPassed,
			
			ISNULL(PassYear,'') AS PassYear,
			ISNULL(Percentage,0) AS Percentage,
			ISNULL(Grade,'') AS Grade,
			ISNULL(InstituteDetail,'') AS InstituteDetail,
			ISNULL(BoardDetail,'') AS BoardDetail,
			ISNULL(Subjects,'') AS Subjects,
			ISNULL(Remark,'') AS Remark,
			
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ISNULL(Medium,'') AS Medium
	
	      
  FROM  
		    		sRecruitment.tCandidateQualification
	 WHERE 
			 (CandidateId = @rCandidateId) OR @rCandidateId=0
	
								
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sRecruitment].[pRptRecruitmentOfferLetterGet]
	 @rCandidateId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 	
				CM.Id AS CandidateId,				
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,				
				VM.Title AS VacancyName,		
				CM.GenderId,		
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark
					
		FROM 
		
			sRecruitment.tCandidateMaster CM			
			INNER JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId								
  WHERE 
  
      ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
       
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pRptVacancyCustomFieldGet]	 
	@rOrgGroupId int,
	@rCandidateId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		VM.Id,
	    VM.FieldTitle,	
		VM.FieldGroup,	
		VM.FieldTypeId,
		VM.FieldList,
		VM.IsFieldMandatory,
		VM.IsObsolete,
		VM.FieldOrder,
		VCF.FieldData
	FROM 
		 sRecruitment.tVacancyCustomFieldMaster VM
		 INNER JOIN sRecruitment.tVacancyCustomFieldData VCF ON VCF.VacancyCustomFieldId=VM.Id AND VCF.CandidateId=@rCandidateId

	WHERE 
		OrgGroupId = @rOrgGroupId
		AND (VCF.FieldData <> '0' AND VCF.FieldData<>'' AND VCF.FieldData IS NOT NULL AND VCF.FieldData<>'- Select -')
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pVacancyCustomFieldAdd]
		 
	--@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	--@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	--@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	--@rIsObsolete int =0,
	@rDataTypeId int = 1,
	@rCustomFieldMasterId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		BEGIN TRANSACTION	

			DECLARE @lOrgGroupId int=0, @lIsVacancy bit = 0
			SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMAster WHERE Id = @rOrgId
			select @lIsVacancy = IsVacancy From sSetup.tCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId AND OrgGroupId=@lOrgGroupId
 
			IF(@lIsVacancy=1)	
			BEGIN
				IF NOT EXISTS(SELECT 2 FROM sRecruitment.tVacancyCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId)
				BEGIN
					DECLARE @lNextNumber int
					EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sRecruitment.tVacancyCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output --mantis: 39728, change @rOrgId => @lOrgGroupId
					Print @lNextNumber
					INSERT INTO sRecruitment.tVacancyCustomFieldMaster
					(
						Id
					   ,FieldTitle
					   ,FieldTypeId
					   ,FieldList
					   ,IsFieldMandatory
					   ,FieldGroup
					   ,FieldOrder
					   ,CreatedUserId
					   ,CreatedDateTime
					   ,OrgGroupId
					   ,IsObsolete
					   ,DataId
					   ,CustomFieldMasterId
					)
					VALUES
					(
					   @lNextNumber
					  ,@rFieldTitle
					  ,@rFieldTypeId
					  ,@rFieldList
					  ,0
					  ,@rFieldGroup
					  ,0
					  ,@rCreatedUserId
					  ,@rCreatedDateTime
					  ,@lOrgGroupId
					  ,0
					  ,@rDataTypeId
					  ,@rCustomFieldMasterId
					)
				END
			--ELSE
	--	 SELECT -101 As RESULT
	--END
	 	 
				ELSE
				BEGIN
				--SET @lNextNumber = @rId

					UPDATE sRecruitment.tVacancyCustomFieldMaster
					SET 
						FieldTitle = @rFieldTitle
						,FieldTypeId = @rFieldTypeId
						,FieldList=@rFieldList
						--,IsFieldMandatory=@rIsFieldMandatory
						--,IsObsolete=@rIsObsolete
						,FieldGroup=@rFieldGroup
						--,FieldOrder=@rFieldOrder
						,UpdatedUserId=@rUpdatedUserId
						,UpdatedDateTime=@rUpdatedDateTime
						,DataId = @rDataTypeId
					WHERE CustomFieldMasterId=@rCustomFieldMasterId
	
	
				END  
			END
			ELSE
			BEGIN
				IF EXISTS(SELECT 2 FROM sRecruitment.tVacancyCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId)
				BEGIN
					DECLARE @lVacancyCustomFieldMasterId int=0
					SELECT @lVacancyCustomFieldMasterId = Id FROM sRecruitment.tVacancyCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId

					EXEC sRecruitment.pVacancyCustomFieldDelete @lVacancyCustomFieldMasterId, @rOrgId, @lOrgGroupId
				END
			END	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pVacancyCustomFieldDataAdd]
	  
	@rCandidateId bigint=0,
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
print @rStrXml
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
	UPDATE sRecruitment.tVacancyCustomFieldData 
			SET 
				VacancyCustomFieldId=A.VacancyCustomFieldId,
				FieldData= [sSetup].[fPortalXMLTagsReplaceReverse](A.FieldData),				
				UpdatedUserId=A.UpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
			FROM (
			SELECT
				VacancyCustomFieldId,FieldData,UpdatedUserId,CandidateId,AutoId	
				FROM OPENXML (@loDoc, '/Table/VacancyCustomField', 1)
			WITH
			(
				AutoId int '@AutoId',		
				CandidateId Bigint '@CandidateId',
				VacancyCustomFieldId INT '@VacancyCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			))A 
			INNER JOIN sRecruitment.tVacancyCustomFieldData VCM ON  VCM.CandidateId=A.CandidateId AND VCM.AutoID=A.AutoId 
	
	
	  INSERT INTO sRecruitment.tVacancyCustomFieldData
		(
		    
			CandidateId,
			VacancyCustomFieldId,
			FieldData,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
		SELECT
				A.CandidateId,A.VacancyCustomFieldId,[sSetup].[fPortalXMLTagsReplaceReverse](A.FieldData),A.CreatedUserId,sCommon.fGetDate(),A.UpdatedUserId,sCommon.fGetDate()	
				FROM OPENXML (@loDoc, '/Table/VacancyCustomField', 1)
			WITH
			(		
			    AutoId int '@AutoId',		
				CandidateId Bigint '@CandidateId',
				VacancyCustomFieldId INT '@VacancyCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			)A 
			LEFT JOIN sRecruitment.tVacancyCustomFieldData VCM ON VCM.CandidateId=A.CandidateId AND VCM.AutoID=A.AutoId 
			WHERE VCM.CandidateId IS NULL 
			
	
		
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pVacancyCustomFieldDelete]

@rId int,
@rOrgId smallint=0,
@rOrgGroupId int=0
AS
BEGIN
 	 
	IF NOT EXISTS(Select 1 from sRecruitment.tVacancyCustomFieldData VCF 
				INNER JOIN sRecruitment.tCandidateMaster CM ON CM.Id=VCF.CandidateId
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
			WHERE VCF.VacancyCustomFieldId=@rId
				AND (VCF.FieldData <> '0' AND VCF.FieldData<>'' AND VCF.FieldData IS NOT NULL))
	BEGIN
        
		DELETE VCF FROM sRecruitment.tVacancyCustomFieldData VCF 
			INNER JOIN sRecruitment.tCandidateMaster CM ON CM.Id=VCF.CandidateId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
		WHERE VCF.VacancyCustomFieldId=@rId
         
		DELETE	FROM sRecruitment.tVacancyCustomFieldMaster WHERE Id=@rId 
		SELECT 1 AS RESULT
	END 

	ELSE
	BEGIN
		SELECT -101 As RESULT
	END
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pVacancyCustomFieldDetailsGet]	 
	@rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		Id,
	    FieldTitle,	
		FieldGroup,	
		FieldTypeId,
		FieldList,
		IsFieldMandatory,
		IsObsolete,
		FieldOrder,
		ISNULL(DataId,0) DataId
	FROM 
		 sRecruitment.tVacancyCustomFieldMaster

	WHERE 
		OrgGroupId = @rOrgGroupId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pVacancyCustomFieldUpdate]
		 
	@rId int,
	@rOrgId int,
	--@rFieldTitle nvarchar(500),
	--@rFieldTypeId tinyint,
	--@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	--@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	--@rCreatedUserId bigint,	
	--@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsObsolete int =0
	--@rDataTypeId int = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		BEGIN TRANSACTION	

			DECLARE @lOrgGroupId int=0
			SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
 
			--IF(@rId = 0)	
			--BEGIN
				--IF NOT EXISTS(SELECT 2 FROM sHrm.tEmployeeCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId AND OrgGroupId=@lOrgGroupId)
				----IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle)
				--BEGIN
	      --DECLARE @lNextNumber int
--	      EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
--Print @lNextNumber
--	      INSERT INTO sHrm.tEmployeeCustomFieldMaster
--	      (
--		    Id
--		   ,FieldTitle
--		   ,FieldTypeId
--		   ,FieldList
--		   ,IsFieldMandatory
--		   ,FieldGroup
--		   ,FieldOrder
--		   ,CreatedUserId
--		   ,CreatedDateTime
--		   ,OrgGroupId
--		   ,IsObsolete
--		   ,DataId
--	      )
--	     VALUES
--	     (
--		   @lNextNumber
--		  ,@rFieldTitle
--		  ,@rFieldTypeId
--		  ,@rFieldList
--		  ,@rIsFieldMandatory
--		  ,@rFieldGroup
--		  ,@rFieldOrder
--		  ,@rCreatedUserId
--		  ,@rCreatedDateTime
--		  ,@lOrgGroupId
--		  ,@rIsObsolete
--		  ,@rDataTypeId
--	     )
--     END
--	 ELSE
--	 SELECT -101 As RESULT
--END
	 	 
--ELSE
--BEGIN
	--SET @lNextNumber = @rId

	
	
			UPDATE sRecruitment.tVacancyCustomFieldMaster
			SET 
				--FieldTitle = @rFieldTitle
				--,FieldTypeId = @rFieldTypeId
				--,FieldList=@rFieldList
				IsFieldMandatory=@rIsFieldMandatory
				,IsObsolete=@rIsObsolete
				--,FieldGroup=@rFieldGroup
				,FieldOrder=@rFieldOrder
				,UpdatedUserId=@rUpdatedUserId
				,UpdatedDateTime=@rUpdatedDateTime
				--,DataId = @rDataTypeId
			WHERE Id = @rId 
	
	
--END  
			SELECT @rId AS Result
	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sRecruitment].[pVacancyMasterAdd]
	 
	    @rOrgGroupId int,
        @rId int,       
		@rTitle nvarchar(100),
		@rTotalVacancy smallint,
		@rMinimumQualification nvarchar(100),
		@rSubjects nvarchar(200),
		@rKeySkills nvarchar(200),
		@rExperience nvarchar(100),
		
		@rIsClose bit,
		@rCreatedUserId bigint,
	    --@rCreatedDateTime datetime,
	    @rUpdatedUserId bigint,
	    @rQualificationFor nvarchar(150),
	    --@rUpdatedDateTime datetime
		@rConfirmationRemark nvarchar(1000),
		@rFormRemark nvarchar(1000)
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		If Exists(select Id from  sRecruitment.tVacancy where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sHostel.tHostelMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from  sRecruitment.tVacancy where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tVacancy', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO  sRecruitment.tVacancy
		(
			OrgGroupId,
			Id, 
			Title, 
			
			TotalVacancy,
		    MinimumQualification, 
		    Subjects, 
		    KeySkills, 
		    Experience, 
		    
		    IsClose, 
		    CreatedUserId, 
		    CreatedDateTime, 
		    UpdatedUserId, 
            UpdatedDateTime,
            QualificationFor,
			ConfirmationRemark,
			FormRemark
			
		)
	VALUES
		(
		    @rOrgGroupId ,
			@lNextNumber ,       
			@rTitle ,
			@rTotalVacancy ,
			@rMinimumQualification ,
			@rSubjects ,
			@rKeySkills ,
			@rExperience ,
			@rIsClose ,
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate(),
			@rQualificationFor,
			@rConfirmationRemark,
			@rFormRemark								
		)
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE   sRecruitment.tVacancy
	    SET
	        Title=@rTitle, 
			TotalVacancy=@rTotalVacancy,
		    MinimumQualification=@rMinimumQualification, 
		    Subjects=@rSubjects, 
		    KeySkills=@rKeySkills, 
		    Experience=@rExperience, 
		    IsClose=@rIsClose, 
	        UpdatedUserId=@rCreatedUserId, 
            UpdatedDateTime=sCommon.fGetDate(),
            QualificationFor=@rQualificationFor,
			ConfirmationRemark = @rConfirmationRemark,
			FormRemark = @rFormRemark
	    
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

	COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sRecruitment].[pVacancyMasterDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sRecruitment.tInterviewCriteria where VacancyId=@rId
			Delete from sRecruitment.tVacancy where Id=@rId
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sRecruitment].[pVacancyMasterGet]
	 @rId int = 0,
	 @rTitle nvarchar(100),	
	 @rOrgGroupId smallint,
	 @rIsSearch bit = 1
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
CREATE TABLE #TotalCandidate (
VacancyId BigInt,
TotalAppliedCandidate Int
)
INSERT INTO #TotalCandidate (VacancyId,TotalAppliedCandidate)
SELECT VacancyId ,Count(Id) as TotalAppliedCandidate From [sRecruitment].[tCandidateMaster] Group By VacancyId;

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			VM.Id,
			VM.Title,
			VM.TotalVacancy,
		    VM.MinimumQualification, 
		    VM.Subjects, 
		    VM.Experience, 
		    VM.IsClose, 
		    VM.CreatedDateTime,
		    VM.KeySkills,
		    VM.QualificationFor,
		    VM.ConfirmationRemark,
			ISNULL(VM.FormRemark,'') AS FormRemark,
            ISNULL(TC.TotalAppliedCandidate,0) AS TotalAppliedCandidate
      
  FROM 
            sRecruitment.tVacancy VM LEFT JOIN #TotalCandidate TC ON TC.VacancyId = VM.Id
            
            
  WHERE   
           ((VM.Id = @rId) OR (@rId = 0))
	       AND ((VM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	   AND VM.OrgGroupId=@rOrgGroupId
	    
	      order by Id desc
 
 DROP TABLE #TotalCandidate
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sRecruitment].[pVacancyWiseAssignOrganization]
	 
	 @rVacancyId bigint,
     @rXmlDoc nvarchar(MAX)
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	--UPDATE sRecruitment.tAssignOrganization
	--SET
	--	OrgId = A.OrgId,
	--	VacancyId = A.VacancyId
		
		
	--FROM
	--(
	--SELECT
	--	VacancyId,
	--	OrgId
		
	--	FROM OPENXML (@intDoc, '/Table/tAssignOrganization', 1)
	--	WITH
	--	(
	--		OrgId int '@OrgId',
	--		VacancyId Bigint '@VacancyId'
			
		
	--	))A INNER JOIN sRecruitment.tAssignOrganization A1 ON A1.VacancyId = A.VacancyId AND A1.OrgId = A.OrgId
	
	
	Delete From sRecruitment.tAssignOrganization Where VacancyId = @rVacancyId
	
	INSERT INTO sRecruitment.tAssignOrganization
	(
		OrgId,
		VacancyId
	
	)
	SELECT
		A.OrgId,
		A.VacancyId
		
	FROM OPENXML (@intDoc, '/Table/tAssignOrganization', 1)
	WITH
	(
		OrgId int '@OrgId',
		VacancyId Bigint '@VacancyId'
	) A LEFT JOIN sRecruitment.tAssignOrganization A1
	ON A1.VacancyId = A.VacancyId AND A1.OrgId = A.OrgId
	WHERE A1.VacancyId IS NULL  AND A1.OrgId IS NULL

	
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sScholarship].[pDeleteAllScholarshipDetail]
	 
		@rScholarshipId int
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		
--For Delete sScholarship.tScholarshipStudentPaid
DELETE  sScholarship.tScholarshipStudentPaid
		FROM  sScholarship.tScholarshipStudentPaid SSP
		INNER JOIN sScholarship.tScholarshipReceive SR ON SSP.ScholarshipReceiveId=SR.Id
	WHERE 
		SR.ScholarshipId=@rScholarshipId
		
--For Delete sScholarship.tScholarshipReceive
DELETE  sScholarship.tScholarshipReceive
		FROM  sScholarship.tScholarshipReceive SR
	WHERE 
		SR.ScholarshipId=@rScholarshipId		

--For Delete sScholarship.tScholarshipEligibleStudent
DELETE  sScholarship.tScholarshipEligibleStudent
		FROM  sScholarship.tScholarshipEligibleStudent SES
	WHERE 
		SES.ScholarshipId=@rScholarshipId			

--For Delete sScholarship.tScholarshipMaster
DELETE  sScholarship.tScholarshipMaster
		FROM  sScholarship.tScholarshipMaster SM
	WHERE 
		SM.Id=@rScholarshipId
				
			SELECT 1 AS Result
		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sScholarship].[pRptScholarshipEligibleStudentGet]
          
           @rScholarshipId int,
           @rAcademicId bigint,
		   @rBatchId int =0 
AS
SET NOCOUNT ON
BEGIN
SELECT 
		STM.Title AS ScholarshipTypeName,
        SM.Title AS ScholarshipName,
        vSA.Code,
        vSA.Name AS StudentName,
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(SES.AcademicId,0) AS AcademicId,
        ISNULL(SES.ScholarshipId,0) AS ScholarshipId,
        ISNULL(SES.EligibleAmount,0) AS EligibleAmount
		
  FROM  sScholarship.tScholarshipEligibleStudent SES
	INNER JOIN  sScholarship.tScholarshipMaster SM ON SM.Id=SES.ScholarshipId
	INNER JOIN  sScholarship.tScholarshipTypeMaster STM ON STM.Id=SM.ScholarshipTypeId
    LEFT JOIN sStudent.vStudentAcademic vSA ON SES.AcademicId=vSA.AcademicId
  WHERE 
		(SES.ScholarshipId=@rScholarshipId OR @rScholarshipId=0)
		AND (SES.AcademicId=@rAcademicId OR @rAcademicId=0)
		AND (SM.BatchId=@rBatchId OR @rBatchId=0)

		order by ClassDivisionName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sScholarship].[pRptScholarshipReceiveGet]
			
           @rId int,
           @rScholarshipId int,
		   @rBatchId int =0 
AS
SET NOCOUNT ON
BEGIN
SELECT  
		SR.Id,
		SR.ScholarshipId,
		SR.Title,
		SR.ReceiveDate,
		SR.TotalAmount,
		SR.ChequeNumber,
		SR.BankName,
		SR.Remark,
		SM.Title AS ScholarshipName,
		STM.Title AS ScholarshipTypeName
		
  FROM  sScholarship.tScholarshipReceive SR
	INNER JOIN  sScholarship.tScholarshipMaster SM ON SM.Id=SR.ScholarshipId
	INNER JOIN  sScholarship.tScholarshipTypeMaster STM ON STM.Id=SM.ScholarshipTypeId
  WHERE 
		(SR.Id=@rId OR @rId=0)
		AND (SR.ScholarshipId=@rScholarshipId OR @rScholarshipId=0) 
		AND (SM.BatchId=@rBatchId OR @rBatchId=0)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sScholarship].[pRptScholarshipStudentPaidGet]
          
           @rScholarshipReceiveId bigint,
           @rScholarshipId int,
		   @rBatchId int =0 
AS
SET NOCOUNT ON
BEGIN
SELECT  
		STM.Title AS ScholarshipTypeName,
        SM.Title AS ScholarshipName,
        ISNULL(SES.AcademicId,0) AS AcademicId,
        ISNULL(SR.Id,0) AS ScholarshipReceiveId,
        ISNULL(SR.Title,'') AS ScholarshipReceiveName,
        ISNULL(SSP.PaidDate,sCommon.fGetDate()) AS PaidDate,
        ISNULL(SSP.PaidAmount,0) AS PaidAmount,
        ISNULL(SSP.ChequeNumber,'') AS ChequeNumber,
        ISNULL(SSP.BankName,'') AS BankName,
        ISNULL(SSP.Remark,'') AS Remark,
        vSA.Code,
        vSA.Name AS StudentName,
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName
		
  FROM 		
	  	sStudent.vStudentAcademic vSA
		INNER JOIN sScholarship.tScholarshipEligibleStudent SES ON SES.AcademicId =vSA.AcademicId
		INNER JOIN sScholarship.tScholarshipMaster SM ON SM.Id= SES.ScholarshipId
		INNER JOIN  sScholarship.tScholarshipTypeMaster STM ON STM.Id=SM.ScholarshipTypeId
		INNER JOIN sScholarship.tScholarshipReceive SR ON SR.ScholarshipId = SM.Id
		LEFT JOIN sScholarship.tScholarshipStudentPaid SSP ON SSP.ScholarshipReceiveId = SR.Id AND SSP.AcademicId = SES.AcademicId
  WHERE 
		(SR.Id=@rScholarshipReceiveId OR @rScholarshipReceiveId=0)
		AND (SM.Id=@rScholarshipId OR @rScholarshipId=0)
		AND SSP.PaidAmount <> 0
		AND (SM.BatchId=@rBatchId OR @rBatchId=0)
		order by ClassDivisionName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipAdd]
	
	@rOrgId int,
	@rBatchId int,
	@rScholarshipTypeId int,
	@rId int,
	@rTitle nvarchar(100),
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rRemark nvarchar(200)=''
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	-- For New Entry
	IF(@rId = 0)	
		BEGIN
			If Exists(select Id from sScholarship.tScholarshipMaster where Title=@rTitle AND  BatchId=@rBatchId AND ScholarshipTypeId=@rScholarshipTypeId)
				BEGIN
				select -103 as Result
				RETURN
			END 
	 
		END
	-- For Update Entry
	ELSE	
		BEGIN
			If  Exists(select Id from sScholarship.tScholarshipMaster where Id<>@rId AND Title =@rTitle AND BatchId=@rBatchId AND ScholarshipTypeId=@rScholarshipTypeId)
			Begin
				select -103 as Result
				RETURN
			End
		END
BEGIN TRY
BEGIN TRANSACTION	
 IF(@rId = 0)	
 BEGIN
	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sScholarship.tScholarshipMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO  sScholarship.tScholarshipMaster
		(
			BatchId,
			ScholarshipTypeId,
			Id,
			Title,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			Remark
		)
	VALUES
		(
			@rBatchId,
			@rScholarshipTypeId,
			@lNextNumber,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsObsolete,
			@rRemark
		)
		             
	END	 
ELSE
    BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sScholarship.tScholarshipMaster
	    SET
			 ScholarshipTypeId=@rScholarshipTypeId,
			 Title=@rTitle,
			 IsObsolete=@rIsObsolete,
			 UpdatedUserId=@rCreatedUserId,
			 UpdatedDateTime=sCommon.fGetDate(),
			 Remark=@rRemark
			 
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
		
END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipDelete]
	 
		@rId int 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		

	IF EXISTS (SELECT 1 FROM  sScholarship.tScholarshipEligibleStudent WHERE ScholarshipId=@rId)
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE IF EXISTS (SELECT 1 FROM  sScholarship.tScholarshipReceive WHERE ScholarshipId=@rId)
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE 
	BEGIN
--For Delete sScholarship.tScholarshipMaster	
		DELETE  sScholarship.tScholarshipMaster
		FROM sScholarship.tScholarshipMaster SM
		WHERE SM.Id=@rId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipEligibleStudentAdd] 
    @rScholarshipId INT
	,@rAcademicId BIGINT
	,@rEligibleAmount DECIMAL(10, 2)
	,@rIsDeleted BIT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		-- For Delete sScholarship.tScholarshipStudentPaid
		IF (@rIsDeleted = 1)
		BEGIN
			IF EXISTS (
					SELECT 1
					FROM sScholarship.tScholarshipStudentPaid SSP
					INNER JOIN sScholarship.tScholarshipReceive SR ON SR.Id = SSP.ScholarshipReceiveId
						AND SR.ScholarshipId = @rScholarshipId
						AND SSP.AcademicId = @rAcademicId
						AND SSP.PaidAmount > 0
					)
			BEGIN
				SELECT - 101 AS Result

				COMMIT TRANSACTION

				RETURN
			END
			ELSE
			BEGIN
				DELETE
				FROM sScholarship.tScholarshipEligibleStudent
				WHERE ScholarshipId = @rScholarshipId
					AND AcademicId = @rAcademicId

				SELECT @rAcademicId AS Result
			END
		END
		ELSE
		BEGIN
			IF EXISTS (
					SELECT AcademicId
					FROM sScholarship.tScholarshipEligibleStudent
					WHERE AcademicId = @rAcademicId
						AND ScholarshipId = @rScholarshipId
					)
			BEGIN
				SELECT - 103 AS Result

				COMMIT TRANSACTION

				RETURN
			END

			INSERT INTO sScholarship.tScholarshipEligibleStudent (
				ScholarshipId
				,AcademicId
				,EligibleAmount
				)
			VALUES (
				@rScholarshipId
				,@rAcademicId
				,@rEligibleAmount
				)
		END

		SELECT @rAcademicId AS Result

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipEligibleStudentGet]
          
           @rScholarshipId int,
           @rAcademicId bigint
AS
SET NOCOUNT ON
BEGIN
SELECT  
        SM.Title AS Scholarship,
        vSA.Code,
        vSA.Name AS StudentName,
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(SES.AcademicId,0) AS AcademicId,
        ISNULL(SES.ScholarshipId,0) AS ScholarshipId,
        ISNULL(SES.EligibleAmount,0.00) AS EligibleAmount
		
  FROM  sScholarship.tScholarshipEligibleStudent SES
	INNER JOIN  sScholarship.tScholarshipMaster SM ON SM.Id=SES.ScholarshipId
    LEFT JOIN sStudent.vStudentAcademic vSA ON SES.AcademicId=vSA.AcademicId
  WHERE 
		(SES.ScholarshipId=@rScholarshipId OR @rScholarshipId=0)
		order by ClassDivisionName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipGet]
	 @rBatchId int,
	 @rScholarshipTypeId int,
	 @rId int = 0,
	 @rTitle nvarchar(100)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
END	 
BEGIN 

	SELECT 
	SM.BatchId,
	SM.ScholarshipTypeId,
	SM.Id,
	SM.Title,
	SM.IsObsolete,
	ISNULL(SM.Remark,'') AS Remark,
	STM.Title AS ScholarshipType
		
  FROM sScholarship.tScholarshipMaster SM  
  INNER JOIN  sScholarship.tScholarshipTypeMaster STM ON STM.Id=SM.ScholarshipTypeId
             
  WHERE 		
      ((SM.Id = @rId) OR (@rId = 0))
      AND  ((SM.ScholarshipTypeId = @rScholarshipTypeId) OR (ISNULL(@rScholarshipTypeId,0) = 0))    
      AND  ((SM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      AND SM.BatchId = @rBatchId
     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipReceiveAdd]
	 
	@rOrgId int,
	@rId int,
	@rScholarshipId int,
	@rTitle nvarchar(100),
	@rReceiveDate date,
	@rTotalAmount decimal(10,2),
	@rChequeNumber nvarchar(20),
	@rBankName nvarchar(20),
	@rRemark nvarchar(200),
	@rIsDeleted bit,
	@rPayTypeId tinyint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

-- AMOUNT VALIDATIEON
			IF(@rId != 0)
			BEGIN
					IF EXISTS
					(SELECT SR.TotalAmount FROM sScholarship.tScholarshipReceive SR WHERE SR.Id = @rId AND @rTotalAmount 
					 < (SELECT  ISNULL(SUM(SSP.PaidAmount),0) FROM sScholarship.tScholarshipStudentPaid SSP 
						WHERE ScholarshipReceiveId = @rId)) 				
					BEGIN
						SELECT -102 as Result
						RETURN
					END 
			END
 IF(@rIsDeleted=1)
		BEGIN
			If Exists(select 1 from sScholarship.tScholarshipStudentPaid SSP INNER JOIN sScholarship.tScholarshipReceive SR ON SR.Id = SSP.ScholarshipReceiveId 
			AND SR.ScholarshipId=@rScholarshipId AND SR.Id=@rId AND SSP.PaidAmount > 0)
				BEGIN
					select -101 as Result
					RETURN
				END 
			ELSE
				BEGIN
					Delete from sScholarship.tScholarshipReceive where Id=@rId AND ScholarshipId=@rScholarshipId
					Select @rId as Result
				END
		END	
ELSE
BEGIN
	-- For New Entry
	IF(@rId = 0)
		BEGIN
			If Exists(select Id from sScholarship.tScholarshipReceive where Title=@rTitle AND ScholarshipId= @rScholarshipId)
				BEGIN
				select -103 as Result
				RETURN
			END 
	 
		END
	-- For Update Entry	
	ELSE
		BEGIN
			If  Exists(select Id from sScholarship.tScholarshipReceive where Id<>@rId AND Title =@rTitle AND ScholarshipId= @rScholarshipId)
			Begin
				select -103 as Result
				RETURN
			End
		END
BEGIN TRY
BEGIN TRANSACTION	
 IF(@rId = 0)	
 BEGIN
	DECLARE @lNextNumber INT    
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sScholarship.tScholarshipReceive', 0, 1, 1,@outNextNumber = @lNextNumber output 

	INSERT INTO  sScholarship.tScholarshipReceive
		(
			  Id,
			  ScholarshipId,
			  Title,
			  ReceiveDate,
			  TotalAmount,
			  ChequeNumber,
			  BankName,
			  Remark,
			  PayTypeId
		)
	VALUES
		(
			  @lNextNumber,
			  @rScholarshipId,
			  @rTitle,
			  @rReceiveDate,
			  @rTotalAmount,
			  @rChequeNumber,
			  @rBankName,
			  @rRemark,
			  @rPayTypeId
		)
		             
	END	 
ELSE
    BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sScholarship.tScholarshipReceive
	    SET
	          ScholarshipId=@rScholarshipId,
			  Title=@rTitle,
			  ReceiveDate=@rReceiveDate,
			  TotalAmount=@rTotalAmount,
			  ChequeNumber=@rChequeNumber,
			  BankName=@rBankName,
			  Remark=@rRemark,
			  PayTypeId=@rPayTypeId
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
	END	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipReceiveGet]
          
           @rId int,
           @rScholarshipId int
AS
SET NOCOUNT ON
BEGIN
SELECT  
		SR.Id,
		SR.ScholarshipId,
		SR.Title,
		SR.ReceiveDate,
		SR.TotalAmount,
		SR.ChequeNumber,
		SR.BankName,
		SR.Remark,
		SM.Title AS ScholarshipName,
		ISNULL(SR.PayTypeId,0) AS PayTypeId,
		ISNULL(PTM.Title,'') AS PayType
		
		
  FROM  sScholarship.tScholarshipReceive SR
	INNER JOIN  sScholarship.tScholarshipMaster SM ON SM.Id=SR.ScholarshipId
	LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=SR.PayTypeId
  WHERE 
		(SR.Id=@rId OR @rId=0)
		AND (SR.ScholarshipId=@rScholarshipId OR @rScholarshipId=0) 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipStudentPaidAdd] @rScholarshipReceiveId BIGINT
	,@rAcademicId BIGINT
	,@rPaidDate DATE
	,@rPaidAmount DECIMAL(10, 2)
	,@rChequeNumber NVARCHAR(20)
	,@rBankName NVARCHAR(20)
	,@rRemark NVARCHAR(200)
	,@rIsDeleted BIT
	,@rPayTypeId TINYINT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	-- FOR DELETE 
	IF (@rIsDeleted = 1)
	BEGIN
		DELETE
		FROM sScholarship.tScholarshipStudentPaid
		WHERE ScholarshipReceiveId = @rScholarshipReceiveId
			AND AcademicId = @rAcademicId

		SELECT @rScholarshipReceiveId AS Result
	END

	BEGIN
		BEGIN TRY
			IF EXISTS (
					SELECT 1
					FROM sScholarship.tScholarshipReceive
					WHERE ReceiveDate > @rPaidDate
						AND Id = @rScholarshipReceiveId
					)
			BEGIN
				SELECT - 101 AS Result

				RETURN
			END

			BEGIN TRANSACTION

			-- DATE VALIDATION
			
			--IF NOT EXISTS (SELECT 1 FROM sScholarship.tScholarshipStudentPaid WHERE AcademicId=@rAcademicId AND ScholarshipReceiveId=@rScholarshipReceiveId)
			--BEGIN
			--	IF EXISTS (SELECT 1 FROM sScholarship.tScholarshipReceive WHERE ReceiveDate > @rPaidDate AND Id=@rScholarshipReceiveId  )
			--	BEGIN
			--		SELECT -101 AS Result
			--		RETURN
			--	END
			--END 
			--ELSE
			--BEGIN
			--	IF EXISTS	(SELECT 1 FROM sScholarship.tScholarshipStudentPaid SSP INNER JOIN sScholarship.tScholarshipReceive SR ON SR.Id = SSP.ScholarshipReceiveId
			--					AND ScholarshipReceiveId=@rScholarshipReceiveId  AND SR.ReceiveDate > @rPaidDate)
			--	BEGIN
			--		SELECT -101 as Result
			--		RETURN
			--	END 
			--END 
			-- AMOUNT VALIDATIEON
			IF EXISTS (
					SELECT 1
					FROM sScholarship.tScholarshipStudentPaid
					WHERE AcademicId = @rAcademicId
						AND ScholarshipReceiveId = @rScholarshipReceiveId
					)
			BEGIN
				IF EXISTS (
						SELECT 1
						FROM sScholarship.tScholarshipReceive SR
						WHERE SR.Id = @rScholarshipReceiveId
							AND SR.TotalAmount < (
								SELECT ISNULL(SUM(SSP.PaidAmount), 0) + @rPaidAmount - (
										SELECT ISNULL(PaidAmount, 0)
										FROM sScholarship.tScholarshipStudentPaid
										WHERE AcademicId = @rAcademicId
											AND ScholarshipReceiveId = @rScholarshipReceiveId
										) AS TotalPaidAmount
								FROM sScholarship.tScholarshipStudentPaid SSP
								WHERE ScholarshipReceiveId = @rScholarshipReceiveId
								)
						)
				BEGIN
					SELECT - 102 AS Result

					RETURN
				END
			END
			ELSE
			BEGIN
				IF EXISTS (
						SELECT SR.TotalAmount
						FROM sScholarship.tScholarshipReceive SR
						WHERE SR.Id = @rScholarshipReceiveId
							AND SR.TotalAmount < (
								SELECT ISNULL(SUM(SSP.PaidAmount), 0) + @rPaidAmount AS TotalPaidAmount
								FROM sScholarship.tScholarshipStudentPaid SSP
								WHERE ScholarshipReceiveId = @rScholarshipReceiveId
								)
						)
				BEGIN
					SELECT - 102 AS Result

					RETURN
				END
			END

			IF NOT EXISTS (
					SELECT 1
					FROM sScholarship.tScholarshipStudentPaid
					WHERE AcademicId = @rAcademicId
						AND ScholarshipReceiveId = @rScholarshipReceiveId
					)
			BEGIN
				INSERT INTO sScholarship.tScholarshipStudentPaid (
					ScholarshipReceiveId
					,AcademicId
					,PaidDate
					,PaidAmount
					,ChequeNumber
					,BankName
					,Remark
					,PayTypeId
					)
				VALUES (
					@rScholarshipReceiveId
					,@rAcademicId
					,@rPaidDate
					,@rPaidAmount
					,@rChequeNumber
					,@rBankName
					,@rRemark
					,@rPayTypeId
					)
			END
			ELSE
			BEGIN
				UPDATE sScholarship.tScholarshipStudentPaid
				SET PaidDate = @rPaidDate
					,PaidAmount = @rPaidAmount
					,ChequeNumber = @rChequeNumber
					,BankName = @rBankName
					,Remark = @rRemark
					,PayTypeId = @rPayTypeId
				WHERE ScholarshipReceiveId = @rScholarshipReceiveId
					AND AcademicId = @rAcademicId
			END

			SELECT @rAcademicId AS Result

			COMMIT TRANSACTION
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION

			SELECT - 1 AS Result
		END CATCH
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipStudentPaidGet]
          
           @rScholarshipReceiveId bigint
AS
SET NOCOUNT ON
BEGIN
SELECT  
        ISNULL(SES.AcademicId,0) AS AcademicId,
        ISNULL(SR.Id,0) AS ScholarshipReceiveId,
        ISNULL(SR.Title,'') AS ScholarshipReceiveName,
        ISNULL(SSP.PaidDate,sCommon.fGetDate()) AS PaidDate,
        ISNULL(SSP.PaidAmount,0) AS PaidAmount,
        ISNULL(SSP.ChequeNumber,'') AS ChequeNumber,
        ISNULL(SSP.BankName,'') AS BankName,
        ISNULL(SSP.Remark,'') AS Remark,
        vSA.Code,
        vSA.Name AS StudentName,
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(SSP.PayTypeId,0) AS PayTypeId,
		ISNULL(PTM.Title,'') AS PayType
		
  FROM 		
	  	sStudent.vStudentAcademic vSA
		INNER JOIN sScholarship.tScholarshipEligibleStudent SES ON SES.AcademicId =vSA.AcademicId
		INNER JOIN sScholarship.tScholarshipMaster SM ON SM.Id= SES.ScholarshipId
		INNER JOIN sScholarship.tScholarshipReceive SR ON SR.ScholarshipId = SM.Id
		LEFT JOIN sScholarship.tScholarshipStudentPaid SSP ON SSP.ScholarshipReceiveId = SR.Id AND SSP.AcademicId = SES.AcademicId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=SSP.PayTypeId
  WHERE 
		(SR.Id=@rScholarshipReceiveId OR @rScholarshipReceiveId=0)
		order by ClassDivisionName
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipTypeAdd]
	 
	@rOrgGroupId smallint,
	@rId int,
	@rNumber int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rCreatedUserId bigint,
	@rOrderIndex smallint,
	@rIsObsolete bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	-- For New Entry
	IF(@rId = 0)
		BEGIN
			If Exists(select Id from sScholarship.tScholarshipTypeMaster where Code=@rCode AND OrgGroupId= @rOrgGroupId)
				BEGIN
				select -103 as Result
				RETURN
			END 
	 
		END
	-- For Update Entry	
	ELSE
		BEGIN
			If  Exists(select Id from sScholarship.tScholarshipTypeMaster where Code=@rCode AND Id<>@rId AND OrgGroupId= @rOrgGroupId)
			Begin
				select -103 as Result
				RETURN
			End
		END
BEGIN TRY
BEGIN TRANSACTION	
 IF(@rId = 0)	
 BEGIN
	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sScholarship.tScholarshipTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO  sScholarship.tScholarshipTypeMaster
		(
			 OrgGroupId,
			 Id,
			 Number,
			 Code,
			 Title,
			 CreatedUserId,
			 CreatedDateTime,
			 OrderIndex,
			 IsObsolete
		)
	VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
			@rNumber,
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrderIndex,
			@rIsObsolete
		)
		             
	END	 
ELSE
    BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sScholarship.tScholarshipTypeMaster
	    SET
	     
	     
	         Number=@rNumber,
			 Code=@rCode,
			 Title=@rTitle,
			 OrderIndex=@rOrderIndex,
			 IsObsolete=@rIsObsolete,
			 UpdatedUserId=@rCreatedUserId,
			 UpdatedDateTime=sCommon.fGetDate()
	      
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
		
END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipTypeDelete]
	 
		@rId int 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN TRY
		BEGIN TRANSACTION		

	IF EXISTS (SELECT 1 FROM sScholarship.tScholarshipMaster WHERE ScholarshipTypeId=@rId)
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE 
	BEGIN
	--For Delete sScholarship.tScholarshipMaster
		DELETE  sScholarship.tScholarshipTypeMaster
		FROM sScholarship.tScholarshipTypeMaster STM
		WHERE STM.Id=@rId
		
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sScholarship].[pScholarshipTypeGet]
	
	 @rId int = 0,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(20),
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
END	 

BEGIN 

	SELECT 
	
	STM.Id, 
	STM.Code,
	STM.Number,
	STM.Title,
	STM.IsObsolete,
	STM.OrderIndex 
      
  FROM sScholarship.tScholarshipTypeMaster STM         
             
  WHERE 		
      ((STM.Id = @rId) OR (@rId = 0))
      AND  ((STM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))    
      AND  ((STM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      AND OrgGroupId = @rOrgGroupId
     
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pAddScreenAdd]
	 
        @rTitle nvarchar(100), 
		@rIsObsolete bit, 
		@rModuleId tinyint, 
		@rAvailablePermission int , 
		@rOrderIndex int, 
		@rResourceTypeId tinyint,
		@rId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	--IF(@rId=0)
	--BEGIN
	--	IF EXiSTS (SELECT 1 FROM  sSecurity.tTask WHERE Title=@rTitle AND @rId=0)
	--	BEGIN
	--	select -103 as Result
	--	RETURN  
	--	END
	--END
	--ELSE
	--BEGIN
	--IF EXiSTS (SELECT 1 FROM  sSecurity.tTask WHERE Title=@rTitle AND @rId<>0)
	--Begin
	--	select -103 as Result
	--	RETURN 
	--	END
	--END
	
BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN 
	DECLARE  @lMaxTaskId smallint
	SELECT @lMaxTaskId=Isnull(MaX(Id),0)+1 FROM sSecurity.tTask
	
	INSERT INTO sSecurity.tTask
		(
		Id,
		Title,
		--TitleResourceKeyId, 
		IsObsolete, 
		ModuleId, 
		AvailablePermission, 
		OrderIndex, 
		ResourceTypeId
			
		)
	VALUES
		(
		@lMaxTaskId,
		@rTitle,
		--@rTitleResourceKeyId, 
		@rIsObsolete, 
		@rModuleId, 
		@rAvailablePermission, 
		@rOrderIndex, 
		@rResourceTypeId
		)
		 SELECT 1,@lMaxTaskId AS Result
	END	
ELSE
	 BEGIN
	  
	    UPDATE  sSecurity.tTask
	    SET
			Title=@rTitle,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
		    ModuleId=@rModuleId,
		    AvailablePermission=@rAvailablePermission,
		    ResourceTypeId=@rResourceTypeId
	      WHERE Id = @rId
	      SELECT 11 ,@rId AS Result
	 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pAddScreenGet]
	 @rId smallint = 0,
	 @rTitle nvarchar(100)='',
	 @rResourceTypeId tinyint=0,
	 @rModuleId tinyint=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
DECLARE @lPermission int
	SELECT 
			T.Id ,
			T.Title AS TaskTitle,
			Isnull(T.IsObsolete,0) AS IsObsolete,
			ISNULL(ModuleId,0) AS ModuleId,
			ISNULL(T.AvailablePermission,0) AS AvailablePermission,
			T.OrderIndex,
			ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
			Isnull(SR.Title,'') AS ResourceType,
			Isnull(CM.Title,'') AS Module,
			CAST(ISNULL((T.AvailablePermission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((T.AvailablePermission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((T.AvailablePermission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((T.AvailablePermission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((T.AvailablePermission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((T.AvailablePermission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((T.AvailablePermission & 64)/64, 0) AS BIT) AS [Execute]
      FROM  sSecurity.tTask T
      INNER JOIN sSecurity.tResourceTypeMaster SR ON SR.Id=T.ResourceTypeId
      INNER JOIN sCommon.tModuleMaster CM ON CM.Id=T.ModuleId

  WHERE   
           ((T.Id = @rId) OR (@rId = 0))
	        AND ((T.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	        AND ((T.ModuleId = @rModuleId) OR (ISNULL(@rModuleId,0) = 0))
	        AND ((T.ResourceTypeId = @rResourceTypeId) OR (ISNULL(@rResourceTypeId,0) = 0))
	        
	    ORDER BY ID desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pAddScreenSCreenAdd]
	 
        @rTitle nvarchar(100), 
		@rIsObsolete bit, 
		@rOrderIndex int, 
		@rId smallint,
		@rTaskId smallint,
		@rPage nvarchar(500),
		@rScreenGroupId smallint, 
	    @rScreenTypeId int, 
		@rIsHideInScreenGroup bit
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	--IF(@rId=0)
	--BEGIN
	--IF EXiSTS (SELECT 1 FROM sSecurity.tScreen WHERE Title=@rTitle AND @rId=0)
	--select -103 as Result
	--RETURN 
	--END
	--ELSE
	--BEGIN
	--IF EXiSTS (SELECT 1 FROM sSecurity.tScreen WHERE Title=@rTitle AND @rId<>0)
	--select -103 as Result
	--RETURN 
	--END
	 BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN 
	DECLARE  @lMaxTaskId smallint
	SELECT @lMaxTaskId=Isnull(MaX(Id),0)+1 FROM sSecurity.tScreen
	
	INSERT INTO sSecurity.tScreen
		(
		   Id,
		   Title,
		   TaskId,
		   Page,
		   IsObsolete, 
		   ScreenGroupId, 
		   OrderIndex, 
		   ScreenTypeId, 
		   --IconPath, 
		   IsHideInScreenGroup
		
		)
	VALUES
		(
		   @lMaxTaskId,
		   @rTitle,
		   @rTaskId,
		   @rPage,
		   @rIsObsolete, 
		   @rScreenGroupId, 
		   @rOrderIndex, 
		   @rScreenTypeId, 
		  -- @rIconPath, 
		   @rIsHideInScreenGroup
		
		)
		 SELECT 1 AS Result
	END	
ELSE
	 BEGIN
	  
	    UPDATE  sSecurity.tScreen
	    SET
			
		   Title=@rTitle,
		   TaskId=@rTaskId,
		   Page= @rPage,
		   IsObsolete=@rIsObsolete, 
		   ScreenGroupId=@rScreenGroupId, 
		   OrderIndex=@rOrderIndex, 
		   ScreenTypeId= @rScreenTypeId, 
		   IsHideInScreenGroup=@rIsHideInScreenGroup
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pAddScreenSearchScreenGet]
	 @rTaskId int = 0,
	 @rTitle nvarchar(100)='',
	 @rScreenGroupId smallint=0,
	 @rScreenId  smallint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
	SELECT 
			ISNULL(SC.Id,0) AS ScreenId,
		    Isnull(SC.Title,'')AS ScreenTitle,
		    ISNULL(SC.TaskId,0) AS TaskId,
		    Isnull(SC.Page,'') AS Page,
		   Isnull(SC.IsObsolete,0) AS IsObsolete,
		   Isnull(SC.ScreenGroupId,0) AS ScreenGroupId,
	       Isnull(SC.OrderIndex,0) AS ScreenOrderIndex ,
	       Isnull(SC.ScreenTypeId,0) AS  ScreenTypeId,
		   Isnull(SC.IsHideInScreenGroup,0) AS IsHideInScreenGroup,
		   	T.Title AS TaskTitle,
		   	ISNULL(ModuleId,0) AS ModuleId,
			ISNULL(AvailablePermission,0) AS AvailablePermission,
			T.OrderIndex,
			ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
			CAST(ISNULL((T.AvailablePermission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((T.AvailablePermission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((T.AvailablePermission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((T.AvailablePermission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((T.AvailablePermission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((T.AvailablePermission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((T.AvailablePermission & 64)/64, 0) AS BIT) AS [Execute]
		   
      FROM  sSecurity.tScreen SC
      INNER JOIN sSecurity.tTask T On T.Id=SC.TaskId 
  WHERE   
	           ((SC.ScreenGroupId = @rScreenGroupId) OR (ISNULL(@rScreenGroupId,0) = 0))
	           AND  ((SC.Id = @rScreenId) OR (ISNULL(@rScreenId,0) = 0))
	            AND  ((SC.TaskId = @rTaskId) OR (ISNULL(@rTaskId,0) = 0))
	           AND ((SC.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	       ORDER BY SC.Id  DESC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pAppPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App 
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,   -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,   -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,  -- Is Activity Entry View
			20556,  -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			,31305 --Consolidate - Staff Biometric Attendance
			,31314 -- Event Attendance Student Wise
			,31323 -- Poll Result
			,31383 -- Consolidate - Student Summary
			,20999 --Attendance Register - mantisid : 34918
			,30974 -- Student Leave Listing
			,31422 --Consolidate - Staff Attendance Inquiry
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,    -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance			
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,    -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,   -- Is Activity Entry View
			20556,   -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			,31305 --Consolidate - Staff Biometric Attendance
			,31314 -- Event Attendance Student Wise
			,31323 -- Poll Result
			,31383 -- Consolidate - Student Summary
			,20999 --Attendance Register - mantisid : 34918
			,30974 -- Student Leave Listing --Mantis Id : 35420
			,31422 --Consolidate - Staff Attendance Inquiry
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pAssignPermissionDelete]
	
	@rOrgGroupId smallint, 
	@rSourceTypeId int,
	@rUserId bigint = 0,
	@rRoleId int = 0,
	@rModuleId int = 0,
	@rResourceTypeId int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	

	 IF(@rSourceTypeId = 1)
	 BEGIN
		IF((SELECT Title FROM sSecurity.tRole WHERE Id = @rRoleId) = 'Admin')
		BEGIN
			DELETE P FROM sSecurity.tPermission P WHERE RoleId = @rRoleId AND OrgGroupId = @rOrgGroupId 
			AND TaskId IN (SELECT Id FROM sSecurity.tTask WHERE ((ModuleId = @rModuleId) OR (@rModuleId = 0)) 
			AND ((ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))) 
			AND TaskId NOT IN (141,30026)
		END
		ELSE
		BEGIN
			DELETE P FROM sSecurity.tPermission P WHERE RoleId = @rRoleId AND OrgGroupId = @rOrgGroupId 
			AND TaskId IN (SELECT Id FROM sSecurity.tTask WHERE ((ModuleId = @rModuleId) OR (@rModuleId = 0)) 
			AND ((ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0)))
		END
	 END
	 ELSE IF(@rSourceTypeId = 2)
	 BEGIN
		DELETE P FROM sSecurity.tPermissionUser P WHERE UserId = @rUserId AND OrgGroupId=@rOrgGroupId
		AND TaskId IN (SELECT Id FROM sSecurity.tTask WHERE ((ModuleId = @rModuleId) OR (@rModuleId = 0)) 
		AND ((ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0)))
	 END

	 SELECT 1 AS Result
	 COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sSecurity].[pAssignSubRole]

		@rRoleId bigint,
        @rSubRoleId bigint,
        @rAssign int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rAssign = 1)
	BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tAssignSubRole WHERE RoleId = @rRoleId AND SubRoleId = @rSubRoleId)
	BEGIN
		Return 1
	END
	ELSE
	BEGIN
		INSERT INTO sSecurity.tAssignSubRole  (RoleId,SubRoleId) VALUES (@rRoleId,@rSubRoleId)
	END
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tAssignSubRole WHERE RoleId = @rRoleId AND SubRoleId = @rSubRoleId)
		BEGIN
			DELETE FROM sSecurity.tAssignSubRole WHERE RoleId = @rRoleId AND SubRoleId = @rSubRoleId
		END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sSecurity].[pBackupAdd]
        
        @rDBName nvarchar(50)='',
        @rPath nvarchar(1000) = ''
        
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	--BEGIN TRANSACTION
	
	BACKUP Database @rDBName TO DISK = @rPath

	INSERT INTO sSystem.tBackupLog VALUES (sCommon.fGetDate(), @rPath, (SELECT VersionId FROM sSystem.tDatabaseInfo), 3)

	SELECT 1 AS RESULT
	    
	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pChangePassword]
@rCode varchar(100),
@rPassword varchar(255)
as
BEGIN
	UPDATE sSecurity.tUser set LoginPassword = @rPassword where isnull(TempPasswordCode,'') = @rCode
	--update sSecurity.tUser set PasswordExpiryDate = DateAdd(month,3,Getdate()) where isnull(TempPasswordCode,'') = @rCode
	UPDATE sSecurity.tUser set TempPasswordCode = null where isnull(TempPasswordCode,'') = @rCode
    SELECT 1 As Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pCheckSMSConfiguration]

	@rOrgId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS (SELECT 1 FROM sAlert.tSMSConfiguration WHERE OrgId = @rOrgId)
	BEGIN
		SELECT 1 AS StatusCode, '' AS StatusMessage
		RETURN
	END 
	ELSE 
	BEGIN 
		SELECT -101 AS StatusCode, 'SMS not configured, Please contact to school administrator' AS StatusMessage 
		RETURN
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pCheckUserExist]
	
		@rLoginTitle nvarchar(100),
		@rOrgId smallint
	
AS

SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION	
	
	DECLARE @lUserId bigint
	
	IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle=@rLoginTitle AND OrgId=@rOrgId)
	BEGIN
		SELECT @lUserId=Id FROM sSecurity.tUser WHERE LoginTitle=@rLoginTitle AND OrgId=@rOrgId
		SELECT @lUserId AS RESULT
		RETURN
	END
	
	SELECT -100 AS RESULT
	
	COMMIT TRANSACTION
	SELECT -1 AS RESULT
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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

--SELECT @lResult AS Result

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pClientSpecificTaskUpdate]
 
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 
 UPDATE sSecurity.tTask SET IsClientSpecific = 1,IsObsolete = 1 WHERE Id=20914 -- Transcript Assessment 
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20875 -- Change Batch Status 
UPDATE sSecurity.tTask SET IsClientSpecific = 1,IsObsolete = 1 WHERE Id=20972 -- Enrollment Status
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20973 -- Select Enrollment Status
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20947 -- Portal Download Data
--UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20985 -- Monthly Attendance Register
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20165 -- Subject Batch
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20168 -- Student Batch
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20633 -- Filter Criteria
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20634 -- Filter Student
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=30030 -- Attendance Group
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=30032 -- Subjectwise Attendance
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20462 -- Subject Attendance Report
UPDATE sSecurity.tTask SET IsClientSpecific = 1,IsObsolete = 1 WHERE Id=20552 -- Print Template
UPDATE sSecurity.tTask SET IsClientSpecific = 1,IsObsolete = 1 WHERE Id=20557 -- Print Template Student
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=30114 -- Batch Wise Result Report
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20963 -- Subject Remark
UPDATE sSecurity.tTask SET IsClientSpecific = 1,IsObsolete = 1 WHERE Id=20491 -- Result Graphical Analysis
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20411 -- Bulk Fee Add
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20874 -- Exemption Type Master
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20911 -- Assign Exemption Type
--UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=30116 -- Travel Listing
UPDATE sSecurity.tTask SET IsClientSpecific = 1,IsObsolete = 1 WHERE Id=30129 -- Add Screen
UPDATE sSecurity.tTask SET IsClientSpecific = 1,IsObsolete = 1 WHERE Id=20250 -- Manage Child Login
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=30120 -- Time Policy
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=30122 -- IP Policy
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20623 -- Custome Query
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20259 -- Portal Synch Data
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20913 -- Batch Class Lecture
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=30021 -- Batch Group Master
UPDATE sSecurity.tTask SET IsClientSpecific = 1 WHERE Id=20953 -- Subject Group Master
UPDATE sSecurity.tTask SET IsClientSpecific = 1,IsObsolete = 1 WHERE Id=20005 -- Term Master
UPDATE sSecurity.tTask SET IsClientSpecific = 1,IsObsolete = 1 WHERE Id=20678 -- Frequency Master
 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sSecurity].[pCloneUserAccessAdd]
	
	@rUserId bigint,
	@rCloneUserId bigint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 DELETE FROM sSecurity.tUserOrganization WHERE UserId=@rCloneUserId 
	 --AND OrgId=@rOrgId
	 DELETE FROM sSecurity.tUserAccess WHERE UserId=@rCloneUserId

	   INSERT INTO sSecurity.tUserOrganization
		(
			UserId,
			OrgId
		)
		SELECT
		@rCloneUserId,
        OrgId
	
		FROM sSecurity.tUserOrganization UO WHERE UserId = @rUserId

		INSERT INTO sSecurity.tUserAccess
		(
			SourceTypeId,
			SourceId,
			UserId
		)
		SELECT
		SourceTypeId,
		SourceId,
		@rCloneUserId
      
		FROM sSecurity.tUserAccess WHERE UserId = @rUserId 
	
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pConfigurationAdd]
	
	@rOrgId smallint,
	@rLicencedUser nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	

BEGIN TRY
BEGIN TRANSACTION	

	IF NOT EXISTS(SELECT OrgId FROM sSecurity.tConfiguration WHERE OrgId=@rOrgId)
	BEGIN
		INSERT INTO sSecurity.tConfiguration
		(
			OrgId,
			LicencedUser
		)
		VALUES
		(
			@rOrgId,
			@rLicencedUser
		)
	END
	ELSE
	BEGIN
		UPDATE sSecurity.tConfiguration
			SET
				LicencedUser=@rLicencedUser
			WHERE
				OrgId=@rOrgId
	END
	
		SELECT 1 AS RESULT
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pConfigurationGet]

	@rOrgId [smallint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT  
		C.LicencedUser
FROM
		sSecurity.tConfiguration C
WHERE 
		C.OrgId=@rOrgId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pDashBoardMenuGet]
	
	@rUserSourceTypeId smallint,
	@rUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT
		MenuID,
		ModuleId,
		ParentMenuID,
		MenuTitle,	 
		MenuTitle AS ScreenTitle,		 
		PageURL,
		ScreenId,
		Permission,
		OrderNumber,	 
		TaskId,		
	  PageURL  AS PagePath,
	  IconPath
	   
	FROM
   (SELECT Menu.Id AS MenuID, 
		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
		Menu.Title AS MenuTitle,		 
		ISNULL(Screen.Title, '') AS ScreenTitle,			 
		ISNULL(Screen.Page, '') AS PageURL,
		ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
		ISNULL(Menu.ScreenId, 0) AS ScreenId,
		ISNULL(PermissionValue, 0) AS Permission,
		ISNULL(OrderNumber, 0) AS OrderNumber,
		ISNULL(Screen.TaskId,0) AS TaskId,
		ISNULL(Screen.IconPath,'') As IconPath, 
		ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
		ISNULL(T.ModuleId,0) AS ModuleId
	  
		 
	FROM sSecurity.tMenu Menu	
	LEFT OUTER JOIN sSecurity.tScreen Screen
		ON Menu.ScreenId = Screen.Id  
		
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue			   
					FROM 
						sSecurity.tPermission P
						INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
						AND T.Id IN
						(
						--Assignment List
						20093,
						--Behaviour List
						20130,
						--Blog List
						20099,
						--Circular List
						20085,
						--Discussion List
						20109,
						--My Poll
						20204,
						--News List
						20104,
						--Query List
						20088,
						--View Task
						20172,
						--View Category
						20183,
						--View Photo
						20185,
						--Image Viewer
						9133,
						--Video Viewer
						9128,
						--Link Viewer
						9137,
						--Calender
						20054,
						--My Event List
						20198,
						--My Activity List
						20209,
						--View Placement
						20190,
						--Student View Result
						20180,
						--Employee View Result
						20181,
						--View Book List
						20182,
						-- Student Profile						
						10187,
						-- Employee Profile
						20246
						)
						
						INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
						INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId
					WHERE 
						--RoleId 
						-- IN						 
						--  (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0)
						--AND 
						T.IsObsolete = 0
					GROUP BY 
						TaskId) TBL2
					ON 
						Screen.TaskId = TBL2.TaskId 
						 INNER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId 	
						 AND T.Id IN
						(
						--Assignment List
						20093,
						--Behaviour List
						20130,
						--Blog List
						20099,
						--Circular List
						20085,
						--Discussion List
						20109,
						--My Poll
						20204,
						--News List
						20104,
						--Query List
						20088,
						--View Task
						20172,
						--View Category
						20183,
						--View Photo
						20185,
						--Image Viewer
						9133,
						--Video Viewer
						9128,
						--Link Viewer
						9137,
						--Calender
						20054,
						--My Event List
						20198,
						--My Activity List
						20209,
						--View Placement
						20190,
						--Student View Result
						20180,
						--Employee View Result
						20181,
						--View Book List
						20182,
						-- Student Profile						
						10187,
						-- Employee Profile
						20246
						)					
					WHERE 
					(Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
					AND	ISNULL(Screen.IsObsolete, 0) = 0) 
				    MenuTable  
					--INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId 
	WHERE 
		MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2
	 		
	ORDER BY 
		ParentMenuID

   --SELECT DISTINCT Menu.Id AS MenuID, 
	--		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
	--		Menu.Title AS MenuTitle, 
	--		Menu.TitleResourceKeyId AS MenuResourceKey, 
	--		Screen.Title AS ScreenTitle,
	--		Screen.TitleResourceKeyId AS ScreenResourceKey,
	--		Screen.Page AS PageURL
	--FROM sSecurity.tMenu Menu
	--LEFT OUTER JOIN sSecurity.tScreen Screen
	--	ON Menu.ScreenId = Screen.Id
	--LEFT OUTER JOIN sSecurity.tPermission Permission
	--	ON Screen.TaskId = Permission.TaskId
	--WHERE	Menu.IsObsolete = 0 AND
	--		Screen.IsObsolete = 0 AND
	--		Permission.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId) AND
	--		(Permission.Permission & 2) = 2
	--ORDER BY ParentMenuID
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/


CREATE OR ALTER PROCEDURE [sSecurity].[pDivisionPermissionAdd]
	 
		   @rUserId bigint, 
		   @rDivisionId int,
		   @rOrgId smallint
		   --@rDPDivisionId int
          

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
-- IF(@rDPDivisionId = 0)	
BEGIN

	--DECLARE @lNextNumber BIGINT     
	--EXECUTE @lNextNumber = sCommon.pTableRowIdGet 0, 'sFee.tFeeSetup', 0, 1, 1


	INSERT INTO sSecurity.tDivisionPermission
		(
		   UserId,
		   DivisionId,
		   OrgId
        )
	VALUES
		(
			@rUserId,
			@rDivisionId,
			@rOrgId
		)
		SELECT 1 AS Result
		             
	END	 
	 --ELSE
	 --BEGIN
	 --SELECT 11 AS Result
	 ----SET @lNextNumber = @rId
	 --   UPDATE  sSecurity.tDivisionPermission
	 --   SET
			
			 
			
	      
	      
	 --     WHERE (Id = @rId) AND (FeeId=@rFeeId) 
	 --     SELECT 11 AS Result   
	 --END  
		
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pDivisionPermissionGet]
	 @rUserId bigint, 
	 --@rDPDivisionId int,
	 @rOrgId smallint
	 --@rRoleId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		
		DM.Id AS DepartmentId,
		DM.DisplayTitle AS Department,
		CM.Id AS ClassId,	
		CM.DisplayTitle AS Class,
		DIM.Id AS DivisionId,
		DIM.DisplayTitle AS Division,
		ISNULL(DP.UserId,0) AS UserId,
		ISNULL(DP.DivisionId,0) AS DPDivisionId
		--ISNULL(SR.Title,'') AS RoleTitle
		 
	
  FROM 
  
		sSetup.tDepartmentMaster DM
	INNER JOIN sSetup.tClassMaster CM
		ON CM.DepartmentId=DM.Id
	INNER JOIN sSetup.tDivisionMaster DIM
		ON DIM.ClassId=CM.Id
	LEFT JOIN sSecurity.tDivisionPermission DP
		ON DP.DivisionId=DIM.Id AND (DP.UserId=@rUserId)
	--LEFT JOIN sSecurity.tUserRole UR
	--	ON UR.UserId=DP.UserId AND(UR.RoleId=@rRoleId)
	--LEFT JOIN sSecurity.tRole SR
	--	ON SR.Id=UR.RoleId 
		--AND(SR.Id=@rRoleId)
		
WHERE 

	--((DP.UserId=@rUserId)OR(@rUserId=0))
	--AND
	(DM.OrgId=@rOrgId)
	--AND ((DP.OrgId=@rOrgId)OR(@rOrgId=0))
	
	
ORDER BY DIM.OrderIndex
		

		

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pDivisionPermissionRemove]
	 @rUserId bigint,
	 @rOrgId smallint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    Delete From sSecurity.tDivisionPermission 
    
    where 
    UserId=@rUserId
    AND OrgId=@rOrgId
	
	
	
	SELECT 101 AS Result
 
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pDivisionWiseUserAccess]
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rClassId int,
	 @rOrgId int,
	 @rIsSearch [bit] = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		
BEGIN 

	SELECT 		
		2005 AS SourceTypeId,
		DM.Id AS SourceId,
		OM.DisplayTitle +' - '+ CM.Title +' - '+DM.Title AS SourceName,
		'False' AS IsObsolete,
		CONVERT(bigint,CONVERT(nvarchar(10),ISNULL(OM.OrderIndex,0))+CONVERT(nvarchar(10),ISNULL(CM.OrderIndex,0))+CONVERT(nvarchar(10),ISNULL(DM.OrderIndex,0))) AS OrderIndex
      
  FROM 
            sSetup.tDivisionMaster DM
           INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
		   LEFT JOIN sHrm.tEmployeeMaster EM 
				ON EM.Id = DM.InchargeEmployeeId AND EM.IsObsolete = 0 AND  ISNULL(EM.IsOtherUser,0) = 0 
		   INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id = DM.OrgId		
		  
  WHERE   
 --     ((DM.Id = @rId) OR (@rId = 0))
	--AND  ((DM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	--AND  ((DM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	--AND ((DM.ClassId=@rClassId) OR (@rClassId = 0))
	--AND
	DM.OrgId=@rOrgId
	order by DM.OrderIndex asc	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pEmailValidateUser]

    @rOrgId int = 0,
    @rUserTitle nvarchar(100)='',
    @rUserEmailId nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DECLARE @rUserSourceId bigint=0
		DECLARE @rUserId bigint=0
		DECLARE @rUserSourceTypeId smallint=0
		DECLARE @newpwd VARCHAR(100)
		SELECT @rUserId=Id,@rUserSourceId = SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
		
		IF(@rUserSourceTypeId = 95)
		BEGIN
			IF EXISTS (SELECT 1 FROM sHrm.tEmployeeCommunications WHERE CompanyEmail = @rUserEmailId and EmployeeId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId

					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Email Id is wrong' AS [Message],'' AS OTP
			END	
		END
		ELSE IF(@rUserSourceTypeId = 2003)
		BEGIN
			IF EXISTS (SELECT 1 FROM sStudent.tStudentCommunication WHERE ParentEmail = @rUserEmailId and StudentId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId
					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId  AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Email Id is wrong' AS [Message],'' AS OTP
			END		
		END
		ELSE
		BEGIN
			SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sSecurity].[pEmployeePasswordAdd]
	
	@rId bigint,
	@rEmployeeId bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rName nvarchar(100),
	@rEmailId nvarchar(100),
	@rMobileNo nvarchar(20),
	@rUserName nvarchar(100),
	@rLoginPassword nvarchar(100),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rIsFullUpdate bit,
	@rRoleId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
		
		
		IF(@rId = 0)	
		BEGIN
			IF(@rEmployeeId <> 0)
			BEGIN
				IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceTypeId = 95 AND SourceId = @rEmployeeId AND OrgId=@rOrgId)
				BEGIN
					SELECT -101 AS UserId
					RETURN
				END
			END
			
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rUserName AND OrgId = @rOrgId)
			BEGIN
				SELECT -101 AS UserId
				RETURN
			END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rUserName AND OrgId = @rOrgId AND Id<>@rId)
			BEGIN
				SELECT -101 AS UserId
				RETURN
			END
		END

		DECLARE @lOrgId int=0
		DECLARE @lUserSourceId bigint = 0
		DECLARE @rUserSourceTypeId smallint=0

		SELECT @lOrgId= OrgId,@lUserSourceId=SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE Id =@rId

		DECLARE @lOrgGroupId int =0 
		SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @lOrgId

		--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
		DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId=@lOrgId AND UserId=@rId AND UserSourceId=@lUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
		--AND DeviceToken=@rDeviceToken
		--END
		
	 DECLARE @lCurrentDateTime DATETIME
	 EXECUTE @lCurrentDateTime = sCommon.fGetDate
	 IF(@rIsFullUpdate=0)
	 BEGIN
	 UPDATE sHrm.tEmployeeCommunications
     SET
		MobileNumber=@rMobileNo,
		CompanyEmail=@rEmailId,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=@lCurrentDateTime
      WHERE (EmployeeId = @rEmployeeId) 
      SELECT 1 AS Result
      RETURN
     END

	BEGIN TRY
	
	 BEGIN TRANSACTION

IF(@rId = 0)	
BEGIN
	
	DECLARE @lNextNumber BIGINT	
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sSecurity.tUser
		(
			Id,		
			DisplayTitle,
			LoginTitle,
			LoginPassword,
			LastLockOutDate,
			NumberOfLogonAttempt,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			SourceTypeId,
			SourceId
        )
	VALUES
		(
			@lNextNumber,
			@rName,					
			@rUserName,
			@rLoginPassword,
			@lCurrentDateTime,
			0,
			@rIsObsolete,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rOrgId,
			95,
			@rEmployeeId
		)
		
		INSERT INTO sSecurity.tUserRole
		(
			RoleId,
			UserId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsPrimary
		)
		VALUES
		(
			@rRoleId,
			--sCommon.fGetIntIdForOrg(10,@rOrgGroupId),
			@lNextNumber,
			@rIsObsolete,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rCreatedUserId,
			@lCurrentDateTime,
			1
		)
		              
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sSecurity.tUser
	    SET
			LoginTitle=@rUserName,
			LoginPassword=@rLoginPassword,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=@lCurrentDateTime
	      WHERE (Id = @rId) 
	 END  
	 
	 UPDATE sHrm.tEmployeeCommunications
     SET
		MobileNumber=@rMobileNo,
		CompanyEmail=@rEmailId,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=@lCurrentDateTime
      WHERE (EmployeeId = @rEmployeeId) 
      
		SELECT @lNextNumber AS Result
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pEmployeePasswordGet]
	
	@rOrgId smallint,
	@rDepartmentId int,
	@rEmployeeGroupId int = 0,
	@rStatusId int = 0,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			ISNULL(U.Id,0) AS Id,
			EC.EmployeeId,
			EC.Code,
			--EC.EmployeeName AS Name,
			[sHrm].[fEmployeeNameGet](EC.FirstName , EC.MiddleName, EC.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Name,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			ISNULL(R.Id,0) AS RoleId,
			ISNULL(R.Title,'') AS Role,
			(CASE WHEN A.UserId IS NULL THEN 'Not Register' ELSE 'Register' END) AS UserRegisterStatus,
			ISNULL(EC.WhatsAppContactNo,'') AS  WhatsAppContactNo
	FROM 
			sHrm.vEmployeeCommunication EC
	LEFT JOIN sSecurity.tUser U ON U.SourceId=EC.EmployeeId AND U.SourceTypeId=95
	LEFT JOIN sSecurity.tUserRole UR ON UR.UserId=U.Id AND UR.IsPrimary = 1 AND UR.IsObsolete = 0
	LEFT JOIN sSecurity.tRole R ON UR.RoleId=R.Id
	LEFT JOIN 
			(
				SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers
			) AS A ON A.UserId = U.Id
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EC.OrgId
	WHERE 
		((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((EC.EmployeeGroupId=@rEmployeeGroupId) OR (@rEmployeeGroupId=0))
		AND	(EC.OrgId = @rOrgId)
		AND (EC.IsObsolete=0) 
		AND ((EC.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((U.LoginPassWord is Null AND @rIsPendingLogin=1)
		OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
		Order by EC.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pForgotPasswordFailureLogAdd]

	@rUserName varchar(255),
	@rMobileNumber nvarchar(50) = '',
	@rEmailId varchar(100)='',
	@rOrgId smallint,
	@rExceptionType nvarchar(1000)=NULL,
	@rExceptionMessage nvarchar(max),
	@rExceptionSource nvarchar(max)=NULL,
	@rExceptionStackTrace nvarchar(max)=NULL,
	@rExceptionDetail nvarchar(max)=NULL,
	@rOsTypeId smallint


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DECLARE @lCode VARCHAR(100) ,@lSourceId bigint = 0, @lUserId bigint = 0, @lSourceTypeId int
	
		IF (@rUserName != '')
		BEGIN
			SELECT @lUserId = Id, @lSourceId = SourceId, @lSourceTypeId = SourceTypeId
			FROM  sSecurity.tUser
			WHERE OrgId = @rOrgId AND LoginTitle = @rUserName
		END 

		IF(@lSourceId != 0 AND @lSourceTypeId = 2003)
		BEGIN
			SELECT @lCode=Code
			FROM  sStudent.tStudentMaster WHERE Id=@lSourceId AND OrgId = @rOrgId
		END
		
		IF (@lSourceId != 0 AND @lSourceTypeId = 95) 
		BEGIN
			SELECT @lCode=Code
			FROM  sHrm.tEmployeeMaster WHERE Id=@lSourceId AND OrgId = @rOrgId
		END
		
		IF NOT EXISTS(select 1 from sSecurity.tForgotPasswordFailureLog where OrgId = @rOrgId AND UserName=@rUserName AND UserId = @lUserId AND IsSendAlert = 0)
		BEGIN	
		Insert Into sSecurity.tForgotPasswordFailureLog
		(
			 OrgId
			,UserName
			,Code
			,EmailId
			,MobileNumber
			,SourceId
			,SourceTypeId
			,IsSendAlert
			,IsResetPassword
			,ExceptionType
			,ExceptionMessage
			,ExceptionSource
			,ExceptionStackTrace
			,ExceptionDetail
			,UserId
			,CreatedDateTime
			,OsTypeId
		)
		Values
		(
			 @rOrgId
			,@rUserName
			,@lCode
			,@rEmailId
			,@rMobileNumber
			,@lSourceId
			,@lSourceTypeId
			,0
			,0
			,@rExceptionType
			,@rExceptionMessage
			,@rExceptionSource
			,@rExceptionStackTrace
			,@rExceptionDetail
			,@lUserId
			,sCommon.fGetDate()
			,@rOsTypeId
		)
		END

		ELSE
		BEGIN
			update sSecurity.tForgotPasswordFailureLog
			SET 
				EmailId = @rEmailId, MobileNumber = @rMobileNumber, ExceptionType = @rExceptionType, ExceptionMessage = @rExceptionMessage, 
				ExceptionSource =@rExceptionSource, ExceptionStackTrace = @rExceptionStackTrace, ExceptionDetail = @rExceptionDetail, 
				UpdatedDateTime = sCommon.fGetDate(), OsTypeId = @rOsTypeId
			WHERE OrgId = @rOrgId AND UserName=@rUserName AND UserId = @lUserId AND IsSendAlert = 0
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pForgotPasswordFailureLogGet]
	 @rFromDate date='',
     @rToDate date='',
     @rOrgId int=0,
	 @rOrgGroupId smallint = 0,
	 @rOsTypeId smallint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT DISTINCT
		 FL.AutoId  AS FailureLogId
		,U.Id AS UserId
		,FL.UserName
		,FL.Code
		,FL.SourceId AS UserSourceId
		,FL.SourceTypeId AS UserSourceTypeId
		,CASE WHEN FL.SourceTypeId = 95 THEN 'Employee' 
			  WHEN FL.SourceTypeId = 2003 THEN 'Student' ELSE 'Other' END AS SourceType
		,FL.OrgId
		,FL.IsSendAlert
		,FL.IsResetPassword
		,FL.CreatedDateTime AS FailureLogDate
		,SC.Name AS Name
		,SC.ParentContactNo as MobileNo
		,SC.ParentEmail AS EmailId
		,SC.WhatsAppContactNo
		,OM.Title AS OrgName
        ,OST.Title AS OSTypeTitle
            
		FROM  [sSecurity].[tForgotPasswordFailureLog] FL
		INNER JOIN sSecurity.tUser U ON U.Id = FL.UserId
		INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = FL.SourceId AND SC.StudentId = U.sourceId AND U.SourceTypeId = 2003
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
		LEFT JOIN sAlert.tOSType OST ON OST.Id = FL.OSTypeId	
			
        WHERE ((FL.OrgId = @rOrgId) OR (@rOrgId=0))
		    AND (FL.CreatedDateTime >= @rFromDate OR  ISNULL(@rFromDate,'')='')
			AND (CAST(FL.CreatedDateTime AS DATE) <= @rToDate OR ISNULL(@rToDate,'')='' ) 
			AND ((OST.Id=@rOsTypeId) OR (@rOsTypeId=0)) 
			AND FL.IsResetPassword = 0
	UNION

	SELECT DISTINCT
		 FL.AutoId  AS FailureLogId
		,U.Id AS UserId
		,FL.UserName
		,FL.Code
		,FL.SourceId AS UserSourceId
		,FL.SourceTypeId AS UserSourceTypeId
		,CASE WHEN FL.SourceTypeId = 95 THEN 'Employee' 
			  WHEN FL.SourceTypeId = 2003 THEN 'Student'
			  ELSE 'Other' END AS SourceType
		,FL.OrgId
		,FL.IsSendAlert
		,FL.IsResetPassword
		,FL.CreatedDateTime AS FailureLogDate
		,EC.EmployeeName AS Name
		,EC.MobileNumber as MobileNo
		,EC.CompanyEmail AS EmailId
		,EC.WhatsAppContactNo
		,OM.Title AS OrgName
        ,OST.Title AS OSTypeTitle
		FROM  [sSecurity].[tForgotPasswordFailureLog] FL
		INNER JOIN sSecurity.tUser U ON U.Id = FL.UserId
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = FL.SourceId AND EC.EmployeeId = U.sourceId AND U.SourceTypeId = 95
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
		LEFT JOIN sAlert.tOSType OST ON OST.Id = FL.OSTypeId	
			
        WHERE ((FL.OrgId = @rOrgId) OR (@rOrgId=0))
		    AND (FL.CreatedDateTime >= @rFromDate OR  ISNULL(@rFromDate,'')='')
			AND (CAST(FL.CreatedDateTime AS DATE) <= @rToDate OR ISNULL(@rToDate,'')='' ) 
			AND ((OST.Id=@rOsTypeId) OR (@rOsTypeId=0)) 
			AND FL.IsResetPassword = 0	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pForgotPasswordFailureLogUpdate]   
	@rFailureLogIds nvarchar(max)='',
	@rIsAlert bit,
	@rCode nvarchar(100)='',
	@rUserId bigint =0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rIsAlert = 1)
	BEGIN
		Update sSecurity.tForgotPasswordFailureLog SET IsSendAlert = 1 
		WHERE AutoId IN (SELECT cast(item AS NVARCHAR(MAX)) FROM  sCommon.fnsplit(@rFailureLogIds,','))
	END

	ELSE 
	BEGIN
		DECLARE @lUserId bigint 
		SELECT @lUserId = Id from  sSecurity.tUser where isnull(TempPasswordCode,'') = @rCode
		IF(@lUserId IS NULL OR @lUserId = 0)
			SET @lUserId = @rUserId
		Update sSecurity.tForgotPasswordFailureLog SET IsResetPassword = 1, IsSendAlert = 1 
		WHERE UserId  = @lUserId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pIpPolicyAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rRemark nvarchar(300),
        @rIsObsolete bit,
        @rCreatedUserId bigint,
        @rOrgGroupId smallint,
        @rIpPolicyDetailXml nvarchar(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rIpPolicyDetailXml

BEGIN
	--BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT 1 FROM sSecurity.tIpPolicy WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		BEGIN SELECT -101 AS Result RETURN END 
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT 1 FROM sSecurity.tIpPolicy WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN SELECT -101 AS Result RETURN END
	END
	
	--BEGIN TRANSACTION	
	DECLARE @lNextNumber int 

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sSecurity.tIpPolicy', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sSecurity.tIpPolicy
		(Id,Title,Remark,IsObsolete,CreatedUserId,CreatedDateTime,OrgGroupId)
	VALUES
		(@lNextNumber,@rTitle,@rRemark,@rIsObsolete,@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId)
	
	    INSERT INTO sSecurity.tIpPolicyDetail
			(IpPolicyId,IP)
		SELECT @lNextNumber,IP
		FROM OPENXML (@loDoc, '/Table/IpPolicyDetail', 1)
		WITH (IP nvarchar(100)) 	
		
		SELECT 1 AS Result
	END	 
	ELSE
	BEGIN
	SET @lNextNumber = @rId
	UPDATE sSecurity.tIpPolicy
	SET Title=@rTitle,Remark=@rRemark,IsObsolete=@rIsObsolete,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=sCommon.fGetDate()
	WHERE Id = @rId AND OrgGroupId= @rOrgGroupId
	
	DELETE sSecurity.tIpPolicyDetail WHERE IpPolicyId= @rId
	INSERT INTO sSecurity.tIpPolicyDetail
		(IpPolicyId,IP)
	SELECT @lNextNumber,IP
	FROM OPENXML (@loDoc, '/Table/IpPolicyDetail', 1)
	WITH (IP nvarchar(100)) 
	
	SELECT 11 AS Result
	END  	
--	COMMIT TRANSACTION		
--	END TRY
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pIpPolicyDelete]
		@rId int
AS
BEGIN
BEGIN TRY
	  BEGIN
	  
		IF EXISTS(SELECT 1 FROM sSecurity.tUserPolicy WHERE IpPolicyId=@rId)
			BEGIN
				SELECT -101 AS RESULT
			RETURN
		END
		
		DELETE FROM sSecurity.tIpPolicyDetail WHERE IpPolicyId = @rId
		DELETE	FROM sSecurity.tIpPolicy WHERE Id=@rId		
		SELECT 1 AS RESULT
	   END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pIpPolicyDetailGet]

	@rIpPolicyId int 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			ROW_NUMBER() OVER (PARTITION BY IPD.IpPolicyId ORDER BY IPD.IpPolicyId) AS RowIndex, IPD.IpPolicyId,IPD.IP
	FROM 
			sSecurity.tIpPolicyDetail IPD
	WHERE 
		(IPD.IpPolicyId = @rIpPolicyId)
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pIpPolicyGet]

	@rId int,
	@rTitle nvarchar(100),
	@rOrgGroupId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	SELECT 
			IP.Id,IP.Title,IP.Remark,IP.IsObsolete,IP.OrgGroupId
	FROM 
			sSecurity.tIpPolicy IP
	WHERE 
		(IP.OrgGroupId = @rOrgGroupId)
		AND	((IP.Id = @rId) OR (@rId = 0))
		AND ((IP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pLoggedInUserGet]
	@rOrgId [smallint],
	@rUserId [bigint],
	@rStoreLocationId [int],
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lOrgGroupId int
DECLARE @lBatchId int
DECLARE @lBatchTitle nvarchar(100)
DECLARE @lDisplayTitle nvarchar(100)
DECLARE @lAffiliationId smallint
DECLARE @lAffiliationTypeId smallint
DECLARE @lOrgGroupBatchId int
DECLARE	@lFromDate date
DECLARE	@lToDate date
DECLARE @lOrgLogo varbinary(max)
--DECLARE @lLocationId int
--DECLARE @lLocationName nvarchar(100)

--SELECT @lLocationId = LocationId, @lLocationName = LocationName FROM sSecurity.vExtUserLocation
--WHERE StoreLocationId = @rStoreLocationId AND UserId = @rUserId 
	SELECT
		@lOrgGroupId=OM.OrgGroupId,
		@lBatchId=BM.Id,
		@lBatchTitle=BM.Title,
		@lDisplayTitle=OM.DisplayTitle,
		@lAffiliationId=OM.AffiliationId,
		@lAffiliationTypeId=AT.AffiliationTypeId,
		@lOrgGroupBatchId=BM.OrgGroupBatchId,
		@lFromDate=BM.FromDate,
		@lToDate=BM.ToDate,
		@lOrgLogo=OM.OrgLogo
	FROM sSetup.tOrganizationMaster OM WITH (NOLOCK)
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.OrgId=OM.Id AND BM.Id = @rBatchId AND BM.OrgId=@rOrgId
		INNER JOIN sSetup.tAffiliationMaster AT WITH (NOLOCK) ON OM.AffiliationId = AT.Id 
		
	SELECT 
		@rOrgId AS OrgId,
		@lOrgGroupId AS OrgGroupId,
		@lBatchId AS BatchId,
		@lBatchTitle AS BatchTitle,
		@lDisplayTitle AS OrgDisplayTitle,
		UserTbl.Id AS UserId, 		
		UserTbl.LoginTitle,
		UserTbl.DisplayTitle,		 
		--UserTbl.EmployeeId AS EmployeeId, 
		UserTbl.SourceId AS UserSourceId,
		UserTbl.SourceTypeId AS UserSourceTypeId,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			(EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)
		ELSE
			SA.Name
		END   AS EmployeeFullName,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			(EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)
		ELSE
			SA.Name
		END   AS UserFullName,
		--CASE WHEN UserTbl.SourceTypeId = 95 THEN
		--	EM.EmployeeJobTitleId
		--ELSE
		--	0
		--END AS EmployeeJobTitleId,
		ScreenTbl.Page AS HomePageUrl,
		MenuTbl.Id AS MenuId,
		UserPrefTbl.FavoriteScreenID AS ScreenID,
		ISNULL(UserTbl.SessionId,'') AS SessionId,
		UR.RoleId,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			0
		ELSE
			SA.RollNo
		END AS UserNo,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EM.DepartmentName
		ELSE
			SA.ClassName+' - '+SA.DivisionName
		END AS UserDepartment,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EM.Code
		ELSE
			SA.Code
		END AS UserIdNo,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EI.EmployeePhoto
		ELSE
			SI.StudentPhoto
		END AS UserPhoto,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EM.GenderId
		ELSE
			ISNULL(SO.GenderId,1)
		END AS GenderId,
		--0 AS AccountingYearId,
	 --   '' AS AccountingYearCode,
		--ISNULL((select Id from sAccounting.tAccountingYearMaster WHERE OrgId = @rOrgId AND IsActive = 1),0) AS AccountingYearId,
		--ISNULL((select Code from sAccounting.tAccountingYearMaster WHERE OrgId = @rOrgId AND IsActive = 1),0) AS AccountingYearCode,
		@lAffiliationId AS AffiliationId,
		@lOrgGroupBatchId AS OrgGroupBatchId,
		@lFromDate AS BatchFromDate,
		@lToDate AS BatchToDate,
		ISNULL(SA.AcademicId,0) AS AcademicId,
		@lAffiliationTypeId AS AffiliationTypeId,
		@lOrgLogo AS OrgLogo
		
		--@lLocationId AS LocationId,
		--@lLocationName AS LocationName	
					
	FROM sSecurity.tUser UserTbl WITH (NOLOCK)
		INNER JOIN sSecurity.tUserRole UR WITH (NOLOCK)
			ON UR.UserId=UserTbl.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND UR.UserId=@rUserId	
		LEFT JOIN sHrm.vExtEmployeeMaster EM WITH (NOLOCK)
			ON EM.Id = UserTbl.SourceId 
			--AND UserTbl.OrgId = EM.OrgId 
			AND UserTbl.SourceTypeId = 95 
			--AND EM.StatusId !=9
		LEFT JOIN sHrm.tEmployeeImages EI WITH (NOLOCK)
			ON EI.EmployeeId=EM.Id
		LEFT JOIN sStudent.vStudentAcademic SA WITH (NOLOCK)
			ON SA.StudentId = UserTbl.SourceId 
			--AND UserTbl.OrgId = SA.OrgId 
			AND SA.BatchId=@rBatchId 
			AND UserTbl.SourceTypeId = 2003	
		LEFT JOIN sStudent.tStudentOther SO WITH (NOLOCK) ON SO.StudentId=SA.StudentId
		LEFT JOIN sStudent.tStudentImages SI WITH (NOLOCK)
			ON SI.StudentId=SA.StudentId
		LEFT OUTER JOIN sSecurity.tUserPreference UserPrefTbl WITH (NOLOCK)
			ON UserTbl.Id = UserPrefTbl.UserId 
			--AND  UserTbl.OrgId = UserPrefTbl.OrgId
		LEFT OUTER JOIN sSecurity.tScreen ScreenTbl WITH (NOLOCK)
			ON UserPrefTbl.FavoriteScreenId = ScreenTbl.Id			
		LEFT OUTER JOIN sSecurity.tMenu MenuTbl WITH (NOLOCK)
			ON MenuTbl.ScreenId =  ScreenTbl.Id	
	WHERE 
		UserTbl.Id = @rUserId 
		AND UserTbl.IsObsolete=0
		AND ((EM.StatusId = 7 AND UserTbl.SourceTypeId = 95) OR (SA.StatusId = 1 AND UserTbl.SourceTypeId = 2003) OR (UserTbl.SourceTypeId=1) OR (ISNULL(UserTbl.SourceTypeId,0) = 0))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMainMenuIdByScreenIdGet]
	@rScreenId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT LEFT(menu.Id, 2) AS MainMenuId FROM sSecurity.tMenu menu
		INNER JOIN sSecurity.tScreen screen
		ON screen.Id = menu.ScreenId
	WHERE screen.Id = @rScreenId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMasterScreenGet]	
	@rUserId [smallint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
     select 
         MM.Title AS Menu,
         M.Title AS ScreenName,
         S.Page + '?MenuID=' +CONVERT(Nvarchar(50),M.Id) AS PagePath,
         MM.Id AS MenuId
               
          
     from sSecurity.tTask T Inner JOIN sSecurity.tScreen S ON S.TaskId = T.Id AND T.IsObsolete = 0 
     INNER JOIN sSecurity.tMenu M ON M.ScreenId = S.Id AND S.IsObsolete = 0 AND M.IsObsolete = 0 
     INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId AND MM.IsObsolete = 0 

      Where M.ParentMenuId IN (select Id from sSecurity.tMenu where  Title LIKE '%Master%') 
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sSecurity].[pMenu_Migration]
 @rUserId [bigint],
 @rMenuId int = 0,
 @rResourceTypeId int= 0,
 @rIsCoreMenu bit = 0,
 @rEnvironmentName nvarchar(max) ,
 @rScreenGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 IF(@rIsCoreMenu=0)
 BEGIN
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
  BEGIN
   SELECT
    MenuID,
    ModuleId,
    ParentMenuID,
    MenuTitle,
    ScreenTitle,
    PageURL,
    ScreenId,
    Permission,
    OrderNumber,
    TaskId,
    PageURL  AS PagePath,
    IconPath

   FROM
     (SELECT Menu.Id AS MenuID,
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
    Menu.Title AS MenuTitle,
    ISNULL(Screen.Title, '') AS ScreenTitle,
    ISNULL(Screen.Page, '') AS PageURL,
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
    ISNULL(Menu.ScreenId, 0) AS ScreenId,
    ISNULL(PermissionValue, 0) AS Permission,
    ISNULL(OrderNumber, 0) AS OrderNumber,
    ISNULL(Screen.TaskId,0) AS TaskId,
    ISNULL(Screen.IconPath,'') As IconPath,
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
    ISNULL(T.ModuleId,0) AS ModuleId


   FROM sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen
    ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN (
       SELECT
        TaskId,
        SUM(Permission & 2) PermissionValue
       FROM
        sSecurity.tPermissionUser P
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
       WHERE
        T.IsObsolete = 0 AND P.UserId = @rUserId
       GROUP BY
        TaskId) TBL2
       ON
        Screen.TaskId = TBL2.TaskId
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId

       WHERE
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
       AND ISNULL(Screen.IsObsolete, 0) = 0)
       MenuTable
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId
   WHERE
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2
    AND
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))

   ORDER BY
    ParentMenuID
  END
 ELSE
  BEGIN
   SELECT
    MenuID,
    ModuleId,
    ParentMenuID,
    MenuTitle,
    ScreenTitle,
    PageURL,
    ScreenId,
    Permission,
    OrderNumber,
    TaskId,
     PageURL  AS PagePath,
     IconPath

   FROM
     (SELECT Menu.Id AS MenuID,
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
    Menu.Title AS MenuTitle,
    ISNULL(Screen.Title, '') AS ScreenTitle,
    ISNULL(Screen.Page, '') AS PageURL,
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
    ISNULL(Menu.ScreenId, 0) AS ScreenId,
    ISNULL(PermissionValue, 0) AS Permission,
    ISNULL(OrderNumber, 0) AS OrderNumber,
    ISNULL(Screen.TaskId,0) AS TaskId,
    ISNULL(Screen.IconPath,'') As IconPath,
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
    ISNULL(T.ModuleId,0) AS ModuleId


   FROM sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen
    ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN (
       SELECT
        TaskId,
        SUM(Permission & 2) PermissionValue
       FROM
        sSecurity.tPermission P
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
        INNER JOIN
        (
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0
        ) B ON B.RoleId = P.RoleId
       WHERE
        T.IsObsolete = 0
       GROUP BY
        TaskId) TBL2
       ON
        Screen.TaskId = TBL2.TaskId
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId

       WHERE
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
       AND ISNULL(Screen.IsObsolete, 0) = 0)
       MenuTable
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId
   WHERE
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2
    AND
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))

   ORDER BY
    ParentMenuID
  END
 END
 ELSE
 BEGIN
 if (@rScreenGroupId = 0)
 BEGIN
  SELECT
   MenuID,
   ModuleId,
   ParentMenuID,
   MenuTitle,
   ScreenTitle,
   PageURL,
   ScreenId,
   Permission,
   OrderNumber,
   TaskId,
   PageURL AS PagePath,
   MenuIsObsolete,
   Icon
  FROM
  (
	SELECT
   ISNULL(Menu.Id,0) AS MenuID,
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
   ISNULL(Menu.Title,'') AS MenuTitle,
   ISNULL(Screen.Title, '') AS ScreenTitle,
   ISNULL(Screen.Page, '') AS PageURL,
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
   ISNULL(Menu.ScreenId, 0) AS ScreenId,
   ISNULL(PermissionValue, 0) AS Permission,
   ISNULL(OrderNumber, 0) AS OrderNumber,
   ISNULL(Screen.TaskId,0) AS TaskId,
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
   ISNULL(T.ModuleId,0) AS ModuleId,
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,
   ISNULL(Screen.IconPath,'') AS Icon
  FROM
  sSecurity.tMenu Menu
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id
  LEFT OUTER JOIN
  (
  SELECT
   P.TaskId,
   SUM(OT.AvailablePermission & 2) PermissionValue
  FROM
   sSecurity.tPermission P
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId
  GROUP BY P.TaskId
  ) TBL2 ON Screen.TaskId = TBL2.TaskId
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId
  WHERE (Menu.IsObsolete = 0)
  AND ISNULL(Screen.IsObsolete, 0) = 0
  AND (
		(@rEnvironmentName = 'Local' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811)) -- updated by parth/Darsh for showing more menu inside the communication 07-02-2023
	OR (@rEnvironmentName = 'QA' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811))
	OR (@rEnvironmentName = 'Production' AND Menu.Id in(24,55,2411,2412,2711,2714,19184006,19181022,2622,15,57,5535,19181039,5511,5510,5524))
	)

  --AND Menu.Id  in (24,2711,2411)  -- Issue: For Only Student Center, My Communication Menu , Developer: Foram, Date: 15-07-2022
  --AND (Menu.Id  in (24,2711)
  --Or ParentMenuID  in (24,2711))
  --AND (Menu.Id IN (15, 32, 55,24, 19181042, 36, 3606,2714)
  --OR ParentMenuID IN (15, 32, 55, 19181042, 36, 24, 18))
  UNION

  SELECT

   ISNULL(Menu.Id, 0) AS MenuID,
   ISNULL(Menu.Id, 0) AS ParentMenuID,
   ISNULL(Screen1.Title,'') AS MenuTitle,
   ISNULL(Screen1.Title, '') AS ScreenTitle,
   ISNULL(Screen1.Page, '')  AS PageURL,
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,
   ISNULL(Menu.ScreenId, 0) AS ScreenId,
   ISNULL(PermissionValue, 0) AS Permission,
   ISNULL(OrderNumber, 0) AS OrderNumber,
   ISNULL(Screen1.TaskId,0) AS TaskId,
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
   ISNULL(T.ModuleId,0) AS ModuleId,
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,
   ISNULL(Screen1.IconPath,'') AS Icon
  FROM
   sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId
   LEFT OUTER JOIN (
  SELECT
   P.TaskId,
   SUM(OT.AvailablePermission & 2) PermissionValue
  FROM
   sSecurity.tPermission P
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId

  GROUP BY P.TaskId
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId
  WHERE (Menu.IsObsolete = 0)
  AND ISNULL(Screen1.IsObsolete, 0) = 0
  --AND (Menu.ParentMenuID  in (24,2711)
  --or Menu.Id  in (24,2711))
  AND Screen1.Id IN (10187,30363,30342,20241,30282,20565,20563,30377,20915,30331,20564,20180,20617,30364,20130,30818,30828,20191,30787,20996,20717  -- Issue: For Only Student Center Menu , Developer: Foram, Date: 15-07-2022
		,9137,20054,20085,20088,20093,20099,20104,20107,20172,20198,20204,20209,20222,20566,20577,20692,20723,20724,30228,30242,30254,30365,30556,30559,30585,30794,30858,30943,31175,30921,20103,20102,30561, -- Issue: For Only My Communication Menu , Developer: Foram, Date: 20-07-2022
		30857,30696,30739,30284,20171,20105,31048,9136,30678,20179,30793,20720,20115,20693,20086,20819,20126,20950,20094,30856,30855,30795,30789,20697,20758,20083,30245,30246,20125,30874,30274,30817,30251,30252,30253,30247,30395, -- this line for communication screen changes by parth
		20983,30071,30103,30859,30935,30602,30848,30362,20181,20246,20576,20916,20979,30020,30093,30106,30115,30124,30134,30139,30149,30257,30327,30788,30455,30344,31005, -- this line for employee center screen changes by parth
		20108,30298,30552,20025,20026,20068,20336,20551,20719,20866,20894,20899,20900,3009530203,30296,30701,30816,30962, -- this line for fees screen changes by parth
		20396,20630,30138,30548,31012,20075,20161,20163,20167,20654,20985,30974,30994,20388,20073,20074,20165,20224,20462, -- this line for atte screen changes by parth
		20766,20927,20555,30366,20622,30651,30515,20554,20561,20159, 30664, -- this line is use for academic module
		30236,30500,30600,30604,31188,31182,30797,30471,30456,30411,30412,30409,30410,30447,30449,20949,20197,20056,20750,20759,20952,20059,20150,20153, --17/05/2023
		20951,20679,20233,31016,20124,30007,20120,20123,20375,20676,20986,20376,20122,30544,20194,30777,30193,30041,20131,20132,20133,20134,20374,20135,20136,20137,30381,30382,20677,20199,30292,20121,20413,31013,10160,20676,30390,30391,
		30100,30102,30105,30110,30107,30108,30113,
		31224,20930,20932,30936,30951,20284,20696,20698,20700,20776,20918,30164,30579,20570,20567,20568,20173,20174,20260, -- Payroll
		20187,20188,20189,30059,30034,
		20325,20379,20380,20631,20235,20043,
		20997,20201,20215,20297,20848,30235,30687,30688,30689,31307,20170,20195,30546,30547,20216,20221,30582,20961,20960,20962,
		20243,20244,20247,20945,30599,30755,30932,31179,30680,30116,30176,30070,20538,20687,20743,20816,20817,20248,20245,30694,20280,20537,10201,10202,10203,20846,30080,30081,30137,30346,30375,30682
		,30685,30580,30178,30180,20948,20919,20920,31382,
		30661,20845,20844,20843,20653,20681,20663,20658,30966,
		8,9,10,11,19,21,9013,9029,20018,20037,20142,20143,20144,20145,20146,20157,20173,20174,20332,20419,20678,20689,20835,20860,20941,30267,30698,30950,30985,31036,20728,20730,20831,7,20931,20,9030,18,
		30499,121,122,124,125,20158,20175,20176,20309,20596,30120,30122,30577,30602,30778,20250, -- Security
		20001,20002,20003,20004,20006,20007,20008,20285,30021,30338,30509,20953,31173,31379,20967,30995,20323,20616,20913,20055,30801,20632,30030,
		441,459,460,476,500,30699,30716,30847,31003,31004,31020,31021,31022,30852,30991,31177,31187,31257,30388,30627,20908,20909,20910,30269,30517,30614,30617,20035,601,602,603,604,605,606,9084,20270,20339,20402,20230,20573,20586,20629,20836,31174,10117,524,30446,30451,30675,30676,30619,10217,30923,31025,31034,31035,10097,20904,20905,20638,20729,20834,20613,20432,20433,20435,31176,10118,31262,31303,30774,30849,30337,20249,20841,20965,30679,30691,
		20409,20727,20907,20919,20971,30564,30732,20998,31315,31027,31028,30019,30831,30850,30612,30626,30650,30535,20978,20882,20208,20416,20513,20514,20544,20553,20688,31348,31359,31364,20716,20268,20968,20828,30271,30343,31225,30931,30596,30597,20259,20623,30538,30545,30955,30957,30939,31383,
		20518,30908,30259,30208,30118,20878,20969,20975,20840,31432,

500,476,459,460,449,408,409,449,472, -- this line for HR master module
31410,
20021,20643,30204,30205,30618,30796,30798,30971,30972,30970,30605,30609,31335,30329,30531,20628,20269,20539,20227,20127,20147,30268,30299,30554,20207,20539,30539,30615,30970,20963,20539,30098,30539,30096,30068,
20010,20013,20014,20016,20019,20560,20875,20973,20987,30234,30335,30332,30726,30534,20009,31435,31434, -- this line for Student Management and Setting module
20061,20063,20064,20065,20066,20067,20069,20070,20071,20072,20389,20390,20552,20557,30227,30457,30578, -- this line for Certificate module
20079,20080,20226,20540,20694,20695,20715,20726,20728,20818,20947,30008,30336,30549,30870,30958,31228,20917,20633,20168,30032, -- this line for Admission module
20058,20151,20621,20748,20751,31420, -- this line for Event | Activity Master
30027,20262,30111,30161,30243,30262,30415,30581,30976,30977,30978,30999,31038,31172,31204,31313,30889, -- this line for Biometric module
20033,20057,20034,20060,20062,20237,20258,20271,20276,20286,20316,20385,20418,20427,20464,20490,20682,20684,20711,20714,20761,20962,30072,30113,30114,30130,30132,30408,30450,30996,30997,31046,  -- this line for Assesment General module
20729,20741,20730,20742,20744,20745,20746,20749,20752,20829, -- this line for activity based
20096,20098,20239, -- line for cce
20076,20078,20081,20082,20084,20087,20090,20092,20072,20082,20932,20923,20925,20934,20995,30006,20434,20436,20468,20478,20479,20480,20618,20710, --co scholastic
20317, -- GSEB
20912, -- MHBHSE
30215, -- CBSE
143,127 -- Configuration
		)
  --AND Screen1.Id IN (9147, 30300, 30301, 30330, 30341, 30782, 30783, 30784, 30785, 30786, 30787, 30788, 30790, 30791, 30792, 30499,20246,
  --30914,30913,30912,30911
  --)
  ) MenuTable
  WHERE
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)
  --AND
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))
  AND MenuIsObsolete = 0
  --AND MenuTable.MenuId IN (15,32,36,55,24,1515,3606,19184009,19181042,2714,19184020)
  AND (
		(@rEnvironmentName = 'Local' AND MenuTable.MenuId in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811)) -- updated by parth/Darsh for showing more menu inside the communication 07-02-2023
	OR (@rEnvironmentName = 'QA' AND MenuTable.MenuId in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811))
	OR (@rEnvironmentName = 'Production' AND MenuTable.MenuId in(24,55,2411,2412,2711,2714,19184006,19181022,2622,15,57,5535,19181039,5511,5510,5524))
	)
  --AND MenuTable.MenuId  in (24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622)  -- updated by parth for showing more menu inside the communication 07-02-2023
  --AND MenuTable.MenuId  in (24,2711,2411)  -- Issue: For Only Student Center, My Communication Menu , Developer: Foram, Date: 15-07-2022
  ORDER BY ParentMenuID
  END
  ELSE
  BEGIN
	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
	BEGIN
		Select


				ISNULL(0, 0) AS MenuID,
				ISNULL(0, 0) AS ParentMenuID,
				ISNULL(S.Title,'') AS MenuTitle,
				ISNULL(S.Title, '') AS ScreenTitle,
				ISNULL(S.Page, '')  AS PageURL,
				ISNULL(S.ScreenGroupId,0) AS ScreenGroupId,
				ISNULL(S.Id, 0) AS ScreenId,
				ISNULL(0, 0) AS Permission,
				ISNULL(0, 0) AS OrderNumber,
				ISNULL(S.TaskId,0) AS TaskId,
				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
				ISNULL(MP.ModuleId,0) AS ModuleId,
				ISNULL(1,1) AS MenuIsObsolete,
				ISNULL(S.IconPath,'') AS Icon

			   From sSecurity.tScreen S
		INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId
		--INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.ID = T.ResourceTypeId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		INNER JOIN sSecurity.tModulePermission MP ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId

		WHERE
		(P.Permission & 2) =2
		AND ( ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		AND P.UserId=@rUserId
		AND T.IsObsolete = 0
		AND S.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		Order by RTM.OrderIndex,S.OrderIndex
	END
	ELSE
	BEGIN
		Select

				ISNULL(0, 0) AS MenuID,
				ISNULL(0, 0) AS ParentMenuID,
				ISNULL(S.Title,'') AS MenuTitle,
				ISNULL(S.Title, '') AS ScreenTitle,
				ISNULL(S.Page, '')  AS PageURL,
				ISNULL(S.ScreenGroupId,0) AS ScreenGroupId,
				ISNULL(S.Id, 0) AS ScreenId,
				ISNULL(0, 0) AS Permission,
				ISNULL(0, 0) AS OrderNumber,
				ISNULL(S.TaskId,0) AS TaskId,
				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
				ISNULL(MP.ModuleId,0) AS ModuleId,
				ISNULL(1,1) AS MenuIsObsolete,
				ISNULL(S.IconPath,'') AS Icon


			   From sSecurity.tScreen S
		INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId
		INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.ID = T.ResourceTypeId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		INNER JOIN sSecurity.tModulePermission MP ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId

		WHERE
		(P.Permission & 2) =2
		AND ( ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		 AND U.IsObsolete=0
		AND U.UserId=@rUserId
		AND T.IsObsolete = 0
		AND S.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		Order by RTM.OrderIndex,S.OrderIndex
	END
  END
 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMenuByMenuIdGet]
	@rMenuId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		M.Id AS MenuID,
		M.ParentMenuID AS ParentMenuID, 
		M.Title AS MenuTitle, 
		 
		S.Title AS ScreenTitle,
	 
		S.Page AS PageURL,
		S.Id AS ScreenId,
		0 AS Permission,
		M.OrderNumber AS OrderNumber
	FROM 
		sSecurity.tMenu M
		INNER JOIN sSecurity.tScreen S
			ON M.ScreenId = S.Id
	WHERE
		M.Id = @rMenuId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 -- exec [sSecurity].[pMenuGet] 9911000000003
CREATE OR ALTER PROCEDURE [sSecurity].[pMenuGet]
	@rUserId [bigint],
	@rMenuId int = 0,
	@rResourceTypeId int= 0 
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
BEGIN

	SELECT
		MenuID,
		ModuleId,
		ParentMenuID,
		MenuTitle,	 
		ScreenTitle,		 
		PageURL,
		ScreenId,
		Permission,
		OrderNumber,	 
		TaskId,		
	    PageURL  AS PagePath,
	    IconPath
	   
	FROM
   (SELECT Menu.Id AS MenuID, 
		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
		Menu.Title AS MenuTitle,		 
		ISNULL(Screen.Title, '') AS ScreenTitle,			 
		ISNULL(Screen.Page, '') AS PageURL,
		ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
		ISNULL(Menu.ScreenId, 0) AS ScreenId,
		ISNULL(PermissionValue, 0) AS Permission,
		ISNULL(OrderNumber, 0) AS OrderNumber,
		ISNULL(Screen.TaskId,0) AS TaskId,
		ISNULL(Screen.IconPath,'') As IconPath, 
		ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
		ISNULL(T.ModuleId,0) AS ModuleId
	  
		 
	FROM sSecurity.tMenu Menu	
	LEFT OUTER JOIN sSecurity.tScreen Screen
		ON Menu.ScreenId = Screen.Id		
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue			   
					FROM 
						sSecurity.tPermissionUser P
						INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
						--INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId 
						INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
					WHERE
						T.IsObsolete = 0 AND P.UserId = @rUserId
					GROUP BY 
						TaskId) TBL2
					ON 
						Screen.TaskId = TBL2.TaskId 
						 LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId
						
					WHERE 
					(Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
					AND	ISNULL(Screen.IsObsolete, 0) = 0) 
				    MenuTable  
					--INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId 
	WHERE 
		MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2	
		AND 
		((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
		AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))
	 		
	ORDER BY 
		ParentMenuID
END
ELSE 
BEGIN
	SELECT
		MenuID,
		ModuleId,
		ParentMenuID,
		MenuTitle,	 
		ScreenTitle,		 
		PageURL,
		ScreenId,
		Permission,
		OrderNumber,	 
		TaskId,		
	  PageURL  AS PagePath,
	  IconPath
	   
	FROM
   (SELECT Menu.Id AS MenuID, 
		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
		Menu.Title AS MenuTitle,		 
		ISNULL(Screen.Title, '') AS ScreenTitle,			 
		ISNULL(Screen.Page, '') AS PageURL,
		ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
		ISNULL(Menu.ScreenId, 0) AS ScreenId,
		ISNULL(PermissionValue, 0) AS Permission,
		ISNULL(OrderNumber, 0) AS OrderNumber,
		ISNULL(Screen.TaskId,0) AS TaskId,
		ISNULL(Screen.IconPath,'') As IconPath, 
		ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
		ISNULL(T.ModuleId,0) AS ModuleId
	  
		 
	FROM sSecurity.tMenu Menu	
	LEFT OUTER JOIN sSecurity.tScreen Screen
		ON Menu.ScreenId = Screen.Id		
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue			   
					FROM 
						sSecurity.tPermission P
						INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
						--INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId 
						INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
						INNER JOIN
						(
						SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0
						) B ON B.RoleId = P.RoleId
					WHERE
						T.IsObsolete = 0
					GROUP BY 
						TaskId) TBL2
					ON 
						Screen.TaskId = TBL2.TaskId 
						 LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId
						
					WHERE 
					(Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
					AND	ISNULL(Screen.IsObsolete, 0) = 0) 
				    MenuTable  
					--INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId 
	WHERE 
		MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2	
		AND 
		((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
		AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))
	 		
	ORDER BY 
		ParentMenuID

   --SELECT DISTINCT Menu.Id AS MenuID, 
	--		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
	--		Menu.Title AS MenuTitle, 
	--		Menu.TitleResourceKeyId AS MenuResourceKey, 
	--		Screen.Title AS ScreenTitle,
	--		Screen.TitleResourceKeyId AS ScreenResourceKey,
	--		Screen.Page AS PageURL
	--FROM sSecurity.tMenu Menu
	--LEFT OUTER JOIN sSecurity.tScreen Screen
	--	ON Menu.ScreenId = Screen.Id
	--LEFT OUTER JOIN sSecurity.tPermission Permission
	--	ON Screen.TaskId = Permission.TaskId
	--WHERE	Menu.IsObsolete = 0 AND
	--		Screen.IsObsolete = 0 AND
	--		Permission.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId) AND
	--		(Permission.Permission & 2) = 2
	--ORDER BY ParentMenuID
END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
CREATE OR ALTER PROCEDURE [sSecurity].[pMenuGet_Migration]    
 @rUserId [bigint],    
 @rMenuId int = 0,    
 @rResourceTypeId int= 0,    
 @rIsCoreMenu bit = 0     
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
 IF(@rIsCoreMenu=0)    
 BEGIN    
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
    PageURL  AS PagePath,    
    IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermissionUser P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
       WHERE    
        T.IsObsolete = 0 AND P.UserId = @rUserId    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 ELSE     
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
     PageURL  AS PagePath,    
     IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermission P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
        INNER JOIN    
        (    
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0    
        ) B ON B.RoleId = P.RoleId    
       WHERE    
        T.IsObsolete = 0    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 END    
 ELSE    
 BEGIN     
  SELECT    
   MenuID,    
   ModuleId,    
   ParentMenuID,    
   MenuTitle,      
   ScreenTitle,       
   PageURL,    
   ScreenId,    
   Permission,    
   OrderNumber,      
   TaskId,      
   PageURL  AS PagePath,    
   MenuIsObsolete,    
   Icon      
  FROM    
  (    
  SELECT    
   ISNULL(Menu.Id,0) AS MenuID,     
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
   ISNULL(Menu.Title,'') AS MenuTitle,       
   ISNULL(Screen.Title, '') AS ScreenTitle,        
   ISNULL(Screen.Page, '') AS PageURL,    
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Menu.ScreenId, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen.IconPath,'') AS Icon    
  FROM     
  sSecurity.tMenu Menu     
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
  LEFT OUTER JOIN     
  (    
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId      
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id        
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId     
  GROUP BY P.TaskId    
  ) TBL2 ON Screen.TaskId = TBL2.TaskId     
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
  WHERE (Menu.IsObsolete = 0)    
  AND ISNULL(Screen.IsObsolete, 0) = 0    
  --AND (Menu.Id  in (24,2711)   
  --Or ParentMenuID  in (24,2711))     
  AND (Menu.Id IN (15, 32, 55,24, 19181042, 36, 3606,2714)  
  OR ParentMenuID IN (15, 32, 55, 19181042, 36, 24, 18))  
    
  UNION    
       
  SELECT     
  
   ISNULL(Menu.Id, 0) AS MenuID,     
   ISNULL(Menu.Id, 0) AS ParentMenuID,     
   ISNULL(Screen1.Title,'') AS MenuTitle,       
   ISNULL(Screen1.Title, '') AS ScreenTitle,        
   ISNULL(Screen1.Page, '')  AS PageURL,    
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Menu.ScreenId, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen1.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen1.IconPath,'') AS Icon    
  FROM     
   sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId     
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId    
   LEFT OUTER JOIN (     
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId        
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id       
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId    
            
  GROUP BY P.TaskId    
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId    
  WHERE (Menu.IsObsolete = 0) AND ISNULL(Screen1.IsObsolete, 0) = 0    
  --AND (Menu.ParentMenuID  in (24,2711)   
  --or Menu.Id  in (24,2711))   
    
  AND Screen1.Id IN (9147, 30300, 30301, 30330, 30341, 30782, 30783, 30784, 30785, 30786, 30787, 30788, 30790, 30791, 30792, 30499,20246,
  30914,30913,30912,30911
  )  
  ) MenuTable      
  WHERE     
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)  
  --AND   
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
  AND MenuIsObsolete = 0    
  AND MenuTable.MenuId IN (15,32,36,55,24,1515,3606,19184009,19181042,2714,19184020)   
  ORDER BY ParentMenuID    
 END    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMenuGet_ModuleWise]    
 @rUserId [bigint],    
 @rMenuId nvarchar(30) = '0',    
 @rResourceTypeId int= 0,    
 @rIsCoreMenu bit = 0,
 @rParentMenuId nvarchar(30) = '0'   
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
	--IF(@rIsCoreMenu=0)    
	--BEGIN    
	--	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
	--	BEGIN    
	--		SELECT    
	--			MenuID,    
	--			ModuleId,    
	--			ParentMenuID,    
	--			MenuTitle,      
	--			ScreenTitle,       
	--			PageURL,    
	--			ScreenId,    
	--			Permission,    
	--			OrderNumber,      
	--			TaskId,      
	--			PageURL  AS PagePath,    
	--			IconPath    
	--		FROM    
	--		(
	--			SELECT 
	--				Menu.Id AS MenuID,     
	--				ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
	--				Menu.Title AS MenuTitle,       
	--				ISNULL(Screen.Title, '') AS ScreenTitle,        
	--				ISNULL(Screen.Page, '') AS PageURL,    
	--				ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
	--				ISNULL(Menu.ScreenId, 0) AS ScreenId,    
	--				ISNULL(PermissionValue, 0) AS Permission,    
	--				ISNULL(OrderNumber, 0) AS OrderNumber,    
	--				ISNULL(Screen.TaskId,0) AS TaskId,    
	--				ISNULL(Screen.IconPath,'') As IconPath,     
	--				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
	--				ISNULL(T.ModuleId,0) AS ModuleId    
	--			FROM 
	--				sSecurity.tMenu Menu     
	--			LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id      
	--			LEFT OUTER JOIN (     
	--				SELECT     
	--					TaskId,     
	--					SUM(Permission & 2) PermissionValue          
	--				FROM     
	--					sSecurity.tPermissionUser P    
	--				INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
	--				INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
	--				WHERE T.IsObsolete = 0 AND P.UserId = @rUserId    
	--				GROUP BY TaskId
	--				) TBL2 ON Screen.TaskId = TBL2.TaskId     
	--			LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
	--			WHERE     
	--			(Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
	--			AND ISNULL(Screen.IsObsolete, 0) = 0
	--		)MenuTable      
	--		WHERE     
	--		MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
	--		AND ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
	--		AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
	--		ORDER BY ParentMenuID    
	--	END    
	--	ELSE     
	--	BEGIN    
	--		SELECT    
	--			MenuID,    
	--			ModuleId,    
	--			ParentMenuID,    
	--			MenuTitle,      
	--			ScreenTitle,       
	--			PageURL,    
	--			ScreenId,    
	--			Permission,    
	--			OrderNumber,      
	--			TaskId,      
	--			PageURL  AS PagePath,    
	--			IconPath    
	--		FROM    
	--		(
	--			SELECT 
	--				Menu.Id AS MenuID,     
	--				ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
	--				Menu.Title AS MenuTitle,       
	--				ISNULL(Screen.Title, '') AS ScreenTitle,        
	--				ISNULL(Screen.Page, '') AS PageURL,    
	--				ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
	--				ISNULL(Menu.ScreenId, 0) AS ScreenId,    
	--				ISNULL(PermissionValue, 0) AS Permission,    
	--				ISNULL(OrderNumber, 0) AS OrderNumber,    
	--				ISNULL(Screen.TaskId,0) AS TaskId,    
	--				ISNULL(Screen.IconPath,'') As IconPath,     
	--				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
	--				ISNULL(T.ModuleId,0) AS ModuleId    
	--			FROM sSecurity.tMenu Menu     
	--			LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id      
	--			LEFT OUTER JOIN (     
	--				SELECT     
	--					TaskId,     
	--					SUM(Permission & 2) PermissionValue          
	--				FROM     
	--				sSecurity.tPermission P    
	--				INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
	--				INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
	--				INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0) B ON B.RoleId = P.RoleId    
	--				WHERE T.IsObsolete = 0    
	--				GROUP BY TaskId
	--			) TBL2 ON Screen.TaskId = TBL2.TaskId     
	--			LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
	--			WHERE     
	--				(Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
	--				AND ISNULL(Screen.IsObsolete, 0) = 0
	--		) MenuTable      
	--		WHERE     
	--			MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
	--			AND ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
	--			AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
	--		ORDER BY ParentMenuID    
	--	END    
	--END    
	--ELSE    
	--BEGIN     
		SELECT
			MenuID,    
			ModuleId,    
			ParentMenuID,    
			MenuTitle,      
			ScreenTitle,       
			PageURL,    
			ScreenId,    
			Permission,    
			OrderNumber,      
			TaskId,      
			PageURL  AS PagePath,    
			MenuIsObsolete,    
			Icon      
		FROM    
		(    
			SELECT    
				ISNULL(Menu.Id,0) AS MenuID,     
				ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
				ISNULL(Menu.Title,'') AS MenuTitle,       
				ISNULL(Screen.Title, '') AS ScreenTitle,        
				ISNULL(Screen.Page, '') AS PageURL,    
				ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
				ISNULL(Menu.ScreenId, 0) AS ScreenId,    
				ISNULL(PermissionValue, 0) AS Permission,    
				ISNULL(OrderNumber, 0) AS OrderNumber,    
				ISNULL(Screen.TaskId,0) AS TaskId,    
				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
				ISNULL(T.ModuleId,0) AS ModuleId,    
				ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
				ISNULL(Screen.IconPath,'') AS Icon    
			FROM     
				sSecurity.tMenu Menu     
			LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
			LEFT OUTER JOIN (    
				SELECT     
					P.TaskId,     
					SUM(OT.AvailablePermission & 2) PermissionValue          
				FROM     
					sSecurity.tPermission P    
					INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0  
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId      
					INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id        
					INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId     
				GROUP BY P.TaskId    
			) TBL2 ON Screen.TaskId = TBL2.TaskId     
			LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
			WHERE 
				(Menu.IsObsolete = 0)    
			AND ISNULL(Screen.IsObsolete, 0) = 0    
			AND (
			(Menu.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rParentMenuId,',')) OR @rParentMenuId='') 
			OR 
			(Menu.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rMenuID,',')) OR @rMenuID='')
			)
			
			UNION    
       
			SELECT     
				ISNULL(Menu.Id, 0) AS MenuID,     
				ISNULL(Menu.Id, 0) AS ParentMenuID,     
				ISNULL(Screen1.Title,'') AS MenuTitle,       
				ISNULL(Screen1.Title, '') AS ScreenTitle,        
				ISNULL(Screen1.Page, '')  AS PageURL,    
				ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,    
				ISNULL(Menu.ScreenId, 0) AS ScreenId,    
				ISNULL(PermissionValue, 0) AS Permission,    
				ISNULL(OrderNumber, 0) AS OrderNumber,    
				ISNULL(Screen1.TaskId,0) AS TaskId,    
				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
				ISNULL(T.ModuleId,0) AS ModuleId,    
				ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
				ISNULL(Screen1.IconPath,'') AS Icon    
			FROM     
				sSecurity.tMenu Menu     
			LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
			LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId     
			LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId    
			LEFT OUTER JOIN (		
				SELECT     
					P.TaskId,     
					SUM(OT.AvailablePermission & 2) PermissionValue          
				FROM     
					sSecurity.tPermission P    
				INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0  
				INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId        
				INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
				INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id       
				INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId    
				GROUP BY P.TaskId    
			) TBL2 ON Screen1.TaskId = TBL2.TaskId    
			WHERE (Menu.IsObsolete = 0) AND ISNULL(Screen1.IsObsolete, 0) = 0    
			AND Screen1.Id IN (
				30914,30913,30912,30911 -- Health Survery
				,30918 -- My Health Survey
				)  
		) MenuTable      
		WHERE     
			((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
			AND MenuIsObsolete = 0    
			AND (
			(MenuTable.MenuId IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rParentMenuId,',')) OR @rParentMenuId='') 
			OR 
			(MenuTable.MenuId IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rMenuID,',')) OR @rMenuID='')
			)
			 
		ORDER BY ParentMenuID    
	--END    
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EXEC [sSecurity].[pMenuMasterGet] 0,''    
CREATE OR ALTER PROCEDURE [sSecurity].[pMenuMasterGet]
     @rId int,     
     @rTitle nvarchar(100)=''      	       	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
    SELECT (M.Id) AS [Id],
           (M.ParentMenuId) AS [MenuId],
           (M.Title) AS [MenuTitle],
           (S.Id) AS [ScreenId],
           (S.Title) AS [ScreenTitle],
           --CASE 
           --   WHEN M.IsObsolete=1 THEN 'YES'  
           --   WHEN M.IsObsolete=0 THEN 'NO'
           --END AS 
           M.IsObsolete,
           --(SELECT MAX(OrderNumber) As OrderNumber FROM sSecurity.tMenu) AS OrderNumber,  
           M.OrderNumber,
           M.ShortcutKey
             
    FROM sSecurity.tMenu M
            LEFT JOIN sSecurity.tMenu MM ON M.Id=MM.ParentMenuId
            LEFT JOIN sSecurity.tScreen S ON M.ScreenId=S.Id     
    WHERE 
            ((@rTitle='' AND 0=0) OR (M.Title LIKE '%'+@rTitle+'%')) 
            AND	((M.Id = @rId) OR (@rId = 0)) AND M.Id>19184012
    ORDER BY M.Id       
   	
END




--select *from sSecurity.tMenu

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMenuMasterManage]
     @rId int=0,
     @rParentMenuId int=0,
     @rTitle nvarchar(100)='', 
     @rTitleResourceKeyid int=0, 
     @rScreenId int=0,
     @rIsObsolete bit=0,
     @rOrderNumber smallint=0,
     @rShortcutKey nvarchar(50)='',
     @rStatus varchar(1)
      	       	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY

IF(@rStatus = 'A')	
	BEGIN
	
	IF NOT EXISTS (SELECT Id from sSecurity.tMenu where Title =@rTitle)	
	
	BEGIN	
		
		Declare @MaxId Int 
		SET @MaxId=(SELECT MAX(id) as Id FROM sSecurity.tMenu)
		SET @MaxId=@MaxId + 1
		
		INSERT INTO sSecurity.tMenu
			(			
				 Id,
				 ParentMenuId,
				 Title,
				 TitleResourceKeyId,
				 ScreenId,
				 IsObsolete,
				 OrderNumber,
				 ShortcutKey

			)
		VALUES
			(			 
				 @MaxId, 
				 @rParentMenuId , 
				 @rTitle , 
				 @rTitleResourceKeyid , 
				 @rScreenId , 
				 @rIsObsolete,
				 @rOrderNumber ,			  
				 @rShortcutKey
			)
		SELECT 1 AS Result
	  END
	  ELSE
	  BEGIN
	    SELECT -103 AS Result
	  END
	  
	END	 

ELSE IF (@rStatus = 'U')
	 BEGIN
	 --SET @lNextNumber = @rId
	 IF NOT EXISTS (SELECT Id from sSecurity.tMenu where Title =@rTitle and Id<>@rId)	
	  BEGIN

	    UPDATE  sSecurity.tMenu
	    SET
	        ParentMenuId=@rParentMenuId,	        
			Title=@rTitle,
			TitleResourceKeyid=@rTitleResourceKeyid,
			ScreenId=@rScreenId,
			IsObsolete=@rIsObsolete,			
			OrderNumber=@rOrderNumber,
			ShortcutKey=@rShortcutKey
	      WHERE Id = @rId
	    SELECT 2 AS Result
	 
	   END
	  ELSE
	  BEGIN
	   SELECT -103 AS Result
	  END 
	 END 

ELSE IF (@rStatus = 'D')
	 BEGIN
	  DELETE 
	    FROM 
	       sSecurity.tMenu 
	  WHERE Id=@rId
	  
	  SELECT 3 AS Result
	  	  
	 END

	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMigrationModulePermissionAdd]
          
   @rOrgGroupId smallint,
   @rXML nvarchar(max)
 
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
DECLARE @loDoc INT

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION	
	
	EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
	CREATE TABLE #ListofData(AutoId int, [Key] VARCHAR(MAX),[Status] bit,Value VARCHAR(MAX),ERPProductId int,OrgGroupId int)
	insert into #ListofData
		select E.AutoId,E.[Key],E.[Status],E.Value,E.ERPProductId,E.OrgGroupId
		from
		(
			SELECT 
				AutoId,
				[Key],
				[Status],
				CASE WHEN CHARINDEX('<', Value) > 0 THEN REPLACE(Value, '<', '&lt;') 
				WHEN CHARINDEX('>', Value) > 0 THEN REPLACE(Value, '>', '&gt;') 
				ELSE Value END AS Value,
				ERPProductId,
				OrgGroupId 
			FROM
			OPENXML (@loDoc, '/Modules/Module', 2)
			WITH (
					AutoId int,
					[Key] VARCHAR(MAX), 
					[Status] bit,
					Value VARCHAR(MAX),
					ERPProductId int,
					OrgGroupId int
				)	
		)E 	

	 -- UPSERT logic: Update if AutoId > 0 and exists, else insert
    MERGE sSecurity.tMigrationModulePermission AS target
    USING (
        SELECT AutoId, [Key], [Status], Value, ERPProductId, OrgGroupId
        FROM #ListofData
    ) AS source
    ON target.OrgGroupId = source.OrgGroupId AND target.[Key] = source.[Key]
    WHEN MATCHED AND source.AutoId > 0 THEN
        UPDATE SET
            target.Value = source.Value,
            target.ERPProductId = source.ERPProductId,
            target.[Status] = source.[Status],
			target.UpdatedDateTime = GETDATE()
    WHEN NOT MATCHED BY TARGET THEN
        INSERT (OrgGroupId, [Key], Value, ERPProductId, [Status])
        VALUES (source.OrgGroupId, source.[Key], source.Value, source.ERPProductId, source.[Status]);

	--INSERT INTO sSecurity.tMigrationModulePermission(OrgGroupId,[Key],Value,ERPProductId,[Status])
	--SELECT OrgGroupId,[Key],Value,ERPProductId,[Status] FROM #ListofData WHERE [Status] = 1

	Drop Table #ListofData

	SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, ERROR_MESSAGE()
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMigrationModulePermissionGet]
       @rOrgGroupId int

AS
SET NOCOUNT ON
BEGIN
	SELECT 
		MMP.AutoId,
		ISNULL(MMP.OrgGroupId,0) AS OrgGroupId ,
		ISNULL(MMP.[Key],'') AS [Key] ,
		ISNULL(MMP.Value,'') AS Value,
		ISNULL(MMP.[Status],0) AS [Status],
		ISNULL(MMP.ERPProductId,0) AS ERPProductId
	FROM 
		sSecurity.tMigrationModulePermission MMP
	WHERE MMP.OrgGroupId = 1

	UNION ALL 

	SELECT 
		MMP.AutoId,
		ISNULL(MMP.OrgGroupId,0) AS OrgGroupId ,
		ISNULL(MMP.[Key],'') AS [Key] ,
		ISNULL(MMP.Value,'') AS Value,
		ISNULL(MMP.[Status],0) AS [Status],
		ISNULL(MMP.ERPProductId,0) AS ERPProductId
	FROM 
		sSecurity.tMigrationModulePermission MMP
	WHERE MMP.OrgGroupId = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sSecurity].[pMISUserSummaryDashboardGet] 

@rCommonOrgGroupBatchId int = 0,
@rOrgGroupId int = 0,
@rOrgId int = 0, 
@rOrgSubGroupId int = 0,
@rTypeId int = 0,
@rSourceTypeId int = 0,
@rRole int = 0,
@rDivisionId int = 0,
@rFilter nvarchar(50) = ''


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rTypeId = 1)-------------LEVEL 1
	BEGIN
		SELECT
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title As OrgSubGroupName,
			 (select COUNT(U.Id) FROM sSecurity.tUser U LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId LEFT JOIN sSetup.tOrgSubGroupMaster OSGM1 ON OSGM1.Id = OM.OrgSubGroupId INNER JOIN sStudent.vStudentCommunication SC ON U.SourceId = SC.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.Id=BM.OrgGroupBatchId INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId WHERE U.SourceTypeId = 2003 AND OSGM1.Id = OSGM.Id AND U.IsObsolete = 0 AND COGBM1.Id = @rCommonOrgGroupBatchId) as Student,
			 (select COUNT(U.Id) FROM sSecurity.tUser U LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId LEFT JOIN sSetup.tOrgSubGroupMaster OSGM1 ON OSGM1.Id = OM.OrgSubGroupId WHERE U.SourceTypeId = 95 AND OSGM1.Id = OSGM.Id AND U.IsObsolete = 0) as Employee
			
		FROM 
			sSetup.tOrgSubGroupMaster OSGM
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.OrgSubGroupId = OSGM.Id			
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  
			COGBM.Id=@rCommonOrgGroupBatchId AND OGM.IsObsolete = 0
			AND OGM.Id = @rOrgGroupId 
 		GROUP BY 
			OSGM.Id,OSGM.Title 
	END
	IF(@rTypeId = 2)-------------LEVEL 2
	BEGIN
		IF(@rSourceTypeId = 95)
		BEGIN
			SELECT 
				OM.Id AS OrganizationId,
				OM.Title As Organization,
				COUNT(U.Id) AS Users,
				COUNT(AU.UserId) AS RegisteredUsers,
				(COUNT(U.Id) - COUNT(AU.UserId)) as NotRegisteredUsers
			FROM 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT RU.UserId AS UserId ,RU.OrgId
				FROM sCommunication.tRegisteredUsers RU  
				WHERE UserSourceTypeId = 95 
				GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.USerId = U.Id
				 
			WHERE 
				COGBM.Id = @rCommonOrgGroupBatchId
				AND O.IsObsolete = 0
				AND U.IsObsolete = 0
				AND U.SourceTypeId = 95
				AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
			GROUP BY OM.Id,OM.Title 
		END
		ELSE IF(@rSourceTypeId = 2003)
		BEGIN
			SELECT 
				OM.Id AS OrganizationId,
				OM.Title As Organization,
				COUNT(U.Id) AS Users,
				COUNT((AU.UserId)) AS RegisteredUsers,
				(COUNT(((U.Id))) - COUNT((AU.UserId))) as NotRegisteredUsers
			FROM 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
				INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId=U.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId 
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT RU.UserId AS UserId ,RU.OrgId
				FROM sCommunication.tRegisteredUsers RU  
				WHERE UserSourceTypeId = 2003 
				GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.UserId = U.Id
				 
			WHERE 
				COGBM.Id = @rCommonOrgGroupBatchId
				AND U.IsObsolete = 0
				AND U.SourceTypeId = 2003
				AND ((OM.OrgSubGroupId = @rOrgSubGroupId) OR (@rOrgSubGroupId = 0))
			GROUP BY OM.Id,OM.Title 
		END
	END
	IF(@rTypeId = 3)-------------LEVEL 3
	BEGIN
		IF(@rSourceTypeId = 2003)
		BEGIN
			IF(@rFilter = 'Registered')
			BEGIN
				SELECT
					DM.Id AS DivisionId,			
					CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
					COUNT(((AU.UserId))) AS Count
					--(COUNT(((U.Id))) - COUNT((AU.UserId))) as NotRegisteredUsers
				FROM 
					sStudent.vStudentCommunication SC
					INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=SC.ClassId 
					LEFT JOIN (
					SELECT RU.UserId AS UserId ,RU.OrgId
					FROM sCommunication.tRegisteredUsers RU  
					WHERE UserSourceTypeId = 2003 
					GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.UserId = U.Id
				 
				WHERE
					U.IsObsolete = 0
					AND U.SourceTypeId = 2003
					AND SC.StatusId = 1
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
				GROUP BY CM.DisplayTitle,DM.DisplayTitle,DM.Id
			END
			ELSE IF(@rFilter = 'NotRegistered')
			BEGIN
				SELECT
					DM.Id AS DivisionId,			
					CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
					--COUNT(((AU.UserId))) AS RegisteredUsers,
					(COUNT(((U.Id))) - COUNT((AU.UserId))) as Count
				FROM 
					sStudent.vStudentCommunication SC
					INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=SC.ClassId 
					LEFT JOIN (
					SELECT RU.UserId AS UserId ,RU.OrgId
					FROM sCommunication.tRegisteredUsers RU  
					WHERE UserSourceTypeId = 2003 
					GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.UserId = U.Id
				 
				WHERE
					U.IsObsolete = 0
					AND U.SourceTypeId = 2003
					AND SC.StatusId = 1
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
				GROUP BY CM.DisplayTitle,DM.DisplayTitle,DM.Id
			END
		END
		ELSE IF(@rSourceTypeId = 95)
		BEGIN
			IF(@rFilter = 'Registered')
			BEGIN
				SELECT 
					R.Id AS RoleId,
					R.Title AS RoleName,
					COUNT(RU.UserId) AS Count
					--(COUNT(U.Id)- COUNT(RU.USerId)) AS NotRegisterUsers
				FROM 
					sSecurity.tUser U
					INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
					INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN (SELECT RU.UserId AS UserId  
					FROM sCommunication.tRegisteredUsers RU   
					GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				WHERE 
					U.IsObsolete = 0 
					AND UR.IsObsolete=0
					AND U.SourceTypeId = 95
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
				GROUP BY R.Title,R.Id
			END
			ELSE IF(@rFilter = 'NotRegistered')
			BEGIN
				SELECT 
					R.Id AS RoleId,
					R.Title AS RoleName,
					--COUNT(RU.UserId) AS RegisteredUsers,
					(COUNT(U.Id)- COUNT(RU.USerId)) AS Count
				FROM 
					sSecurity.tUser U
					INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
					INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN (SELECT RU.UserId AS UserId  
					FROM sCommunication.tRegisteredUsers RU   
					GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				WHERE 
					U.IsObsolete = 0 
					AND UR.IsObsolete=0
					AND U.SourceTypeId = 95
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
				GROUP BY R.Title,R.Id
			END
		END
	END
	IF(@rTypeId = 4)-------------LEVEL 4
	BEGIN
		IF(@rSourceTypeId = 95)
		BEGIN
			IF(@rFilter = 'Registered')
			BEGIN
				SELECT 
					EM.Code AS Code,
					EM.FirstName + ' ' + EM.LastName AS Name,
					ISNULL(C.MobileNumber,0) AS Contact
				FROM 
					sSecurity.tUser U
					INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
					INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN (SELECT RU.UserId AS UserId  
					FROM sCommunication.tRegisteredUsers RU   
					GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
					INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId
					LEFT JOIN sHrm.tEmployeeCommunications C ON C.EmployeeId = EM.Id
				WHERE 
					U.IsObsolete = 0 
					AND UR.IsObsolete=0
					AND U.SourceTypeId = 95
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
					AND ((R.Id = @rRole) OR(@rRole=0)) 
					AND RU.UserId is not null
				GROUP BY EM.Code,EM.FirstName,EM.LastName,C.MobileNumber
			END
			ELSE IF(@rFilter = 'NotRegistered')
			BEGIN
				SELECT 
					EM.Code AS Code,
					EM.FirstName + ' ' + EM.LastName AS Name,
					ISNULL(C.MobileNumber,0) AS Contact
				FROM 
					sSecurity.tUser U
					INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
					INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN (SELECT RU.UserId AS UserId  
					FROM sCommunication.tRegisteredUsers RU   
					GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
					INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId
					LEFT JOIN sHrm.tEmployeeCommunications C ON C.EmployeeId = EM.Id
				WHERE 
					U.IsObsolete = 0 
					AND UR.IsObsolete=0
					AND U.SourceTypeId = 95
					AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
					AND ((R.Id = @rRole) OR(@rRole=0)) 
					AND RU.UserId is null
				GROUP BY EM.Code,EM.FirstName,EM.LastName,C.MobileNumber
			END
		END
		ELSE IF(@rSourceTypeId = 2003)
		BEGIN
			IF(@rFilter = 'Registered')
			BEGIN
				SELECT		
					SC.Code AS Code,
					SC.Name AS Name,
					ISNULL(SC.StudentContactNo,0) AS Contact
				FROM 
					sStudent.vStudentCommunication SC
					INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=SC.ClassId 
					LEFT JOIN (
					SELECT RU.UserId AS UserId ,RU.OrgId
					FROM sCommunication.tRegisteredUsers RU  
					WHERE UserSourceTypeId = 2003 
					GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.UserId = U.Id
				WHERE
					U.IsObsolete = 0
					AND U.SourceTypeId = 2003
					AND OM.Id = @rOrgId
					AND SC.StatusId = 1
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
					AND DM.Id = @rDivisionId
					AND AU.UserId is not null
				GROUP BY DM.Id,SC.Name,SC.Code,SC.StudentContactNo
			END
			ELSE IF(@rFilter = 'NotRegistered')
			BEGIN
				SELECT		
					SC.Code AS Code,
					SC.Name AS Name,
					ISNULL(SC.StudentContactNo,0) AS Contact
				FROM 
					sStudent.vStudentCommunication SC
					INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=SC.ClassId 
					LEFT JOIN (
					SELECT RU.UserId AS UserId ,RU.OrgId
					FROM sCommunication.tRegisteredUsers RU  
					WHERE UserSourceTypeId = 2003 
					GROUP BY RU.UserId,RU.OrgId ) AU ON AU.OrgId = OM.Id AND AU.UserId = U.Id
				WHERE
					U.IsObsolete = 0
					AND U.SourceTypeId = 2003
					AND OM.Id = @rOrgId
					AND SC.StatusId = 1
					AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
					AND DM.Id = @rDivisionId
					AND AU.UserId is null
				GROUP BY DM.Id,SC.Name,SC.Code,SC.StudentContactNo
			END
		END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pMobileAppTaskGet]
		@rRoleId bigint,		
		@rOrgGroupId int,
		@rUserId bigint = 0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

    DECLARE @lRoleTitle nvarchar(100)=''
	
	IF(@rUserId=0)
	BEGIN
		SELECT @lRoleTitle = Title FROM sSecurity.tRole WHERE Id=@rRoleId
		IF(@lRoleTitle = 'Student')
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermission P ON T.Id = P.TaskId AND (P.RoleId = @rRoleId OR P.RoleId IS NULL)
					INNER JOIN sSecurity.tAssignSubRole ASR ON ASR.RoleId = P.RoleId AND ASR.SubRoleId = @rRoleId
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,2)
				ORDER BY T.ModuleId,RTM.Id
		END
		ELSE
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId 
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermission P ON T.Id = P.TaskId AND (P.RoleId = @rRoleId OR P.RoleId IS NULL)
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,1)
				ORDER BY T.ModuleId,RTM.Id
		END
	END
	ELSE
	BEGIN
		
		SELECT @lRoleTitle = Title FROM sSecurity.tRole R
		INNER JOIN sSecurity.tUserRole UR ON R.Id = UR.RoleId 
		WHERE UR.UserId=@rUserId
		
		IF(@lRoleTitle = 'Student')
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					--INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermissionUser P ON T.Id = P.TaskId AND (P.UserId = @rUserId OR P.UserId IS NULL)
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,2)
				ORDER BY T.ModuleId,RTM.Id
		END
		ELSE
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					--INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId 
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermissionUser P ON T.Id = P.TaskId AND (P.UserId = @rUserId OR P.UserId IS NULL)
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,1)
				ORDER BY T.ModuleId,RTM.Id
		END
	END
	
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMobileChangePassword]
	@rUserId bigint=0,
	@rUserPassword nvarchar(200)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lOrgId int=0
	DECLARE @lUserSourceId bigint = 0
	DECLARE @rUserSourceTypeId smallint=0
	
	SELECT @lOrgId= OrgId,@lUserSourceId=SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE Id =@rUserId
	
	DECLARE @lOrgGroupId int =0 
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @lOrgId
	
	--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
		DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId=@lOrgId AND UserId=@rUserId AND UserSourceId=@lUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
		--AND DeviceToken=@rDeviceToken
	--END

    UPDATE sSecurity.tUser SET LoginPassword=@rUserPassword WHERE Id=@rUserId
    SELECT 1 AS Result,'Password Change Successfully' AS [Message]
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pMobValidateUser]

    @rOrgId int = 0,
    @rUserTitle nvarchar(100)='',
    @rUserMobileNumber nvarchar(50)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DECLARE @rUserSourceId bigint=0
		DECLARE @rUserId bigint=0
		DECLARE @rUserSourceTypeId smallint=0
		DECLARE @newpwd VARCHAR(100)
		SELECT @rUserId=Id,@rUserSourceId = SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
		IF(@rUserId = 0 AND @rUserSourceTypeId=0)
		BEGIN
			SELECT -11 AS Result, 'User does not exist' AS [Message], '' AS OTP
			Return
		END
		IF(@rUserSourceTypeId = 95)
		BEGIN
			IF EXISTS (SELECT 1 FROM sHrm.tEmployeeCommunications WHERE MobileNumber = @rUserMobileNumber and EmployeeId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				--Changes for Mantis Id : 33613 4 digit OTP --changes for Mantis Id: 0035793 get 6 digit OTP
					EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId

					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
			END	
		END
		IF(@rUserSourceTypeId = 2003)
		BEGIN
			IF EXISTS (SELECT 1 FROM sStudent.tStudentCommunication WHERE ParentContactNo = @rUserMobileNumber and StudentId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN --Changes for Mantis Id : 33613 4 digit OTP --changes for Mantis Id: 0035793 get 6 digit OTP
					EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId
					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId  AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
			END		
		END
END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pMobValidateUser_new]

    @rOrgId int = 0,
    @rUserTitle nvarchar(100)='',
    @rUserMobileNumber nvarchar(50)=''
	
AS
SET NOCOUNT ON
BEGIN
		DECLARE @rUserSourceId bigint=0
		DECLARE @rUserId bigint=0
		DECLARE @rUserSourceTypeId smallint=0
		DECLARE @newpwd VARCHAR(100)
		SELECT @rUserId=Id,@rUserSourceId = SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
		
		IF(@rUserSourceTypeId = 95)
		BEGIN
			IF EXISTS (SELECT 1 FROM sHrm.tEmployeeCommunications WHERE (MobileNumber = @rUserMobileNumber or PersonalEmail = @rUserMobileNumber) and EmployeeId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId

					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
			END	
		END
		IF(@rUserSourceTypeId = 2003)
		BEGIN
			IF EXISTS (SELECT 1 FROM sStudent.tStudentCommunication WHERE (ParentContactNo = @rUserMobileNumber or ParentEmail = @rUserMobileNumber) and StudentId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId
					SELECT 1 AS Result,'student otp' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId  AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
			END		
		END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pModulePermissionAdd]
          
            @rOrgGroupId smallint,
            @rXML nvarchar(max) ,
            @rModuleGroupId tinyint=0,
            @rModeId tinyint=0
 
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
--Declare @Sql nvarchar(max) 
DECLARE @loDoc INT


BEGIN

	BEGIN TRY
	BEGIN TRANSACTION	
	 
	DECLARE @lIsObsolete bit = 0
	
	If(@rModeId=1)
		SET @lIsObsolete = 0
	else If(@rModeId=2)
		SET @lIsObsolete = 1 
	
	EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
	CREATE TABLE #ListofData(ModuleId int,IsPermission bit,OrgGroupId int)
	insert into #ListofData
		select E.ModuleId,E.IsPermission,E.OrgGroupId
		from
		(
				SELECT ModuleId,IsPermission,OrgGroupId FROM
				OPENXML (@loDoc, '/Modules/Module', 2)
				WITH (
						ModuleId int, 
						IsPermission bit,
						OrgGroupId int)	
						)E 	

	--DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId=@rOrgGroupId
    DELETE MP FROM sSecurity.tModulePermission  MP
	INNER JOIN sCommon.tModuleMaster MM ON MM.Id=MP.ModuleId AND (MM.IsObsolete = @lIsObsolete OR @rModeId=0)
	LEFT JOIN sCommon.tModuleGroupMaster MG ON MG.Id=MM.ModuleGroupId 
	WHERE MP.OrgGroupId=@rOrgGroupId AND ((MM.ModuleGroupId=@rMOduleGroupId) OR (isnull(@rMOduleGroupId,0)=0))
	
	--DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId AND 
	--TaskId IN(SELECT TaskId From sSecurity.tTask WHERE 
	--	ModuleId IN(SELECT ModuleId FROM #ListofData WHERE IsPermission = 0))
		
	--DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND 
	--TaskId IN(SELECT TaskId From sSecurity.tTask WHERE 
	--	ModuleId IN(SELECT ModuleId FROM #ListofData WHERE IsPermission = 0))
		
	INSERT INTO sSecurity.tModulePermission 
	SELECT OrgGroupId,ModuleId FROM #ListofData WHERE IsPermission=1 
	--Exec sp_executesql @sql
	Drop Table #ListofData
	--INSERT INTO sSecurity.tModulePermission
 --          (
 --           [OrgId],
 --           ModuleId            
 --          )
 --    VALUES
 --          (
 --            @rOrgId,
 --            @rModuleId     
 --          )
 
	SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pModulePermissionGet]
        @rOrgGroupId int,
        @rMOduleGroupId tinyint=0,
        @rModeId tinyint=0
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lIsObsolete bit = 0
	
	If(@rModeId=1)
		SET @lIsObsolete = 0
	else If(@rModeId=2)
		SET @lIsObsolete = 1
	
	SELECT 
		MM.Id,
		MM.Title AS ModuleName,
		(CASE WHEN MP.ModuleId IS NULL THEN 'False'	ELSE 'True' END) AS Selected,
		ISNULL(MP.OrgGroupId,0) AS OrgGroupId ,
		ISNULL(MG.Title,'') AS ModuleGroup,
		(CASE WHEN MM.IsObsolete = 0 THEN 'Active'	ELSE 'Inactive' END) AS Mode   
	FROM 
		sCommon.tModuleMaster MM
		LEFT JOIN sSecurity.tmodulepermission MP ON MP.ModuleId = MM.Id AND MP.OrgGroupId = @rOrgGroupId
		INNER JOIN sCommon.tModuleGroupMaster MG ON MG.Id=MM.ModuleGroupId
	WHERE 
		(MM.IsObsolete = @lIsObsolete OR @rModeId=0)
		AND ((MM.ModuleGroupId=@rMOduleGroupId) or (isnull(@rMOduleGroupId,0)=0))
	ORDER BY 
		MM.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pModulePermissionReset]
          
            @rOrgGroupId smallint,
            @rIsPortal bit  
       
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	
	BEGIN TRANSACTION	
	
	DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId=@rOrgGroupId
	
	IF(@rIsPortal=1)
	BEGIN
		INSERT INTO sSecurity.tModulePermission 
		SELECT @rOrgGroupId,Id FROM sCommon.tModuleMaster WHERE IsObsolete=0 
		AND Id IN
		(
-- 	select ID , ', --' + Title from scommon.tModuleMaster order by id	
	1	, --Security
	2	, --Alert
	3	, --Configuration
	135	, --Employee
	--136	, --Payroll
	151	, --Setup
	152	, --Student
	--153	, --Attendance
	--154	, --Fee
	--155	, --Timetable
	--156	, --Assessment General
	162	, --Communication
	209	, --Activity
	--210	, --Library
	--211	, --EExam
	--218	, --Placement
	219	, --Gallery
	220	, --Portal Academic
	--222	, --Employee Attendance
	225,--Academic
	221,--Administation
	234,--Employee Center
	235,-- My Communication
	233 -- Student Center
		 
		)
		
	END
	ELSE
	BEGIN
		INSERT INTO sSecurity.tModulePermission 
		SELECT @rOrgGroupId,Id FROM sCommon.tModuleMaster WHERE IsObsolete=0 
		AND Id NOT IN
		(
		 
4	,	--Globalization
91	,	--Utilities
106	,	--Order Entry
120	,	--Procurement
137	,	--Asset Management
140	,	--Audit Trail
162	,	--Communication
204	,	--Support
208	,	--BI
210	,	--Library
211	,	--EExam
212	,	--Accounting
213	,	--OMR
214	,	--Biometric
216	,	--Health
218	,	--Placement
219	,	--Gallery
220		--Portal Academic
	
		)
	END
	SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMultiChildLoginGet]
	
	@rLoginTitle nvarchar(100),
	@rStudentId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


DECLARE @lMobile nvarchar(20)


SELECT 
			@lMobile = SC.ParentContactNo 
			
	FROM  
	sStudent.tStudentMaster SM INNER JOIN
	 sSecurity.tUser U ON U.SourceId = SM.ID AND U.SourceTypeId=2003	 
	INNER JOIN sStudent.tStudentCommunication SC ON SM.Id = SC.StudentId
	WHERE  
	--U.LogInTitle = @rLoginTitle AND 
	SC.StudentId = @rStudentId

	SELECT 
			ISNULL(U.Id,0) AS Id,
			SA.StudentId,
			--SA.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS NAME,
			CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassName,
			SA.RollNo
			
	FROM sStudent.tAcademic SA
	INNER JOIN sSecurity.tUser U ON U.SourceId = SA.StudentId AND U.SourceTypeId=2003 
	INNER JOIN sSetup.tBatchMaster B ON B.Id = SA.BatchId  AND B.IsHistory = 0
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
	INNER JOIN sStudent.tStudentCommunication SC ON SM.Id = SC.StudentId
	WHERE  SC.ParentContactNo  = @lMobile AND SA.StudentId <> @rStudentId
	AND SC.ParentContactNo <> ''
	--WHERE  U.LogInTitle = @rLoginTitle AND SA.StudentId <> @rStudentId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pNewTaskAdd]
 
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lItemValue nvarchar(20) = ''
	SELECT 
		@lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END 
	FROM 
		sConfig.tConfigurationMaster CM
		LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
		AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 494
    
 
	 
	IF EXISTS (SELECT 1 FROM sSystem.tDatabaseInfo WHERE ISNULL(HostedAS,'') <> 'Portal' AND Id = 1)
	 
	BEGIN
	DELETE OT FROM 
	sSecurity.tOrganizationTask OT
	INNER JOIN sSecurity.tTask T ON OT.TaskId = T.Id
	 WHERE OT.OrgGroupId=@rOrgGroupId AND T.IsClientSpecific = 0
			
	INSERT INTO sSecurity.tOrganizationTask 
	(
		OrgGroupId, TaskId, AvailablePermission
	)
	SELECT  @rOrgGroupId, 
			T.Id,
			T.AvailablePermission
	FROM
			sSecurity.tTask T INNER JOIN sSecurity.tModulePermission P
			ON T.ModuleId = P.ModuleId
	WHERE 
			P.OrgGroupId = @rOrgGroupId
			--AND T.AvailablePermission != 0
			AND T.IsObsolete = 0
			AND T.IsClientSpecific = 0
			
	END
	
	--DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
	 
	
	IF(@lItemValue='True')
	BEGIN
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId)

		INSERT INTO 
		sSecurity.tPermission
		(
		TaskId, 
		RoleId, 
		Permission, 
		IsObsolete, 
		CreatedUserId, 
		CreatedDateTime, 
		UpdatedUserId, 
		UpdatedDateTime,
		OrgGroupId
		)
		SELECT  
		TaskId,
		sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
		AvailablePermission,
		0,
		1,
		sCommon.fGetDate(),
		1,
		sCommon.fGetDate(),
		@rOrgGroupId
		FROM 
		sSecurity.tOrganizationTask 
		WHERE 
		OrgGroupId = @rOrgGroupId
	END
	ELSE
	BEGIN

		DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id WHERE P.OrgGroupId=@rOrgGroupId AND P.RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
		AND T.IsClientSpecific = 0

		INSERT INTO 
		sSecurity.tPermission
		(
		TaskId, 
		RoleId, 
		Permission, 
		IsObsolete, 
		CreatedUserId, 
		CreatedDateTime, 
		UpdatedUserId, 
		UpdatedDateTime,
		OrgGroupId
		)
		SELECT  
		TaskId,
		sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
		OT.AvailablePermission,
		0,
		1,
		sCommon.fGetDate(),
		1,
		sCommon.fGetDate(),
		@rOrgGroupId
		FROM 
		sSecurity.tOrganizationTask OT
		INNER JOIN sSecurity.tTask T ON T.Id = OT.TaskId
		WHERE 
		OrgGroupId = @rOrgGroupId
		AND T.IsClientSpecific = 0
	END

	
		 
	
	
	--DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId

	SELECT 1 AS RESULT
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pNumericOTPGenerate]
    @len int,
    @min tinyint = 48,
    @range tinyint = 74,
    @exclude varchar(50) = '0:;<=>?@O[]`^\/',
    @output varchar(50) output
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
    DECLARE @char CHAR
    SET @output = ''
 
    WHILE @len > 0 
    BEGIN
       SELECT @char = CHAR(ROUND(RAND() * @range + @min, 0))
       IF CHARINDEX(@char, @exclude) = 0 
       BEGIN
           SET @output += @char
           SET @len = @len - 1
       END
    END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pOrganizationGroupSettingAdd]
	 
        @rOrgGroupId smallint,
        @rNoOfStudent int,
        @rPaymentDueDate date,
        @rIsPaymentReminder bit,
        @rPaymentReminderRemark nvarchar(300) ,
        @rExtraStudent int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 If Exists(select 1 from sSetup.tOrgGroupSetting where OrgGroupId=@rOrgGroupId)
			BEGIN
			 UPDATE  sSetup.tOrgGroupSetting
				SET
					 
					NoOfStudent=@rNoOfStudent,
					PaymentDueDate=@rPaymentDueDate,
					IsPaymentReminder=@rIsPaymentReminder,
					PaymentReminderRemark=@rPaymentReminderRemark,
					StudentExtraCap = @rExtraStudent
				  WHERE OrgGroupId = @rOrgGroupId
	      SELECT 11 AS Result
	 END  	
			 
	ELSE 
	BEGIN	 
	INSERT INTO sSetup.tOrgGroupSetting
		(
			OrgGroupId,
			NoOfStudent,
			PaymentDueDate,
			IsPaymentReminder,
			PaymentReminderRemark,
			StudentExtraCap
		)
	VALUES
		(
			@rOrgGroupId,
			@rNoOfStudent,
			@rPaymentDueDate,
			@rIsPaymentReminder,
			@rPaymentReminderRemark ,
			@rExtraStudent
		)
		    SELECT 1 AS Result
	END	 
 
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pOrganizationPermissionDetailGet]
	
		@rOrgId smallint,
		@rRoleId int,
		@rDisplayTitle nvarchar(100),
		@rLoginTitle nvarchar(20),
		@rSourceTypeId smallint,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		SET @rDisplayTitle = sCommon.fSearchStringGet(@rDisplayTitle)
		SET @rLoginTitle = sCommon.fSearchStringGet(@rLoginTitle)

		SELECT 
		
			U.Id AS UserId,
			U.DisplayTitle,
			U.LoginTitle,
			U.SourceId AS UserSourceId,
			U.SourceTypeId AS UserSourceTypeId,

			CASE WHEN U.SourceTypeId = 95 THEN	'Employee'
			WHEN ISNULL(U.SourceTypeId,1) = 1 THEN	'Other'
			END   AS UserSourceTypeName,

			CASE WHEN U.SourceTypeId = 95 THEN	Emp.Code
			WHEN  ISNULL(U.SourceTypeId,1) = 1  THEN	U.DisplayTitle
			END   AS EmployeeCode,

			CASE WHEN U.SourceTypeId = 95 THEN (Emp.FirstName +  ' ' + Emp.LastName)
			WHEN ISNULL(U.SourceTypeId,1) = 1 THEN U.LoginTitle
			END   AS UserFullName,

			R.Id AS RoleId,
			R.Title AS RoleName,

			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgName
			
		FROM
		
			sSecurity.tUser U
			LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = U.SourceId AND U.SourceTypeId = @rSourceTypeId 
			INNER JOIN sSecurity.tUserRole UR 
			ON UR.UserId=U.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
			ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
			ON OM.Id = U.OrgId
			
			
	WHERE
	
			((U.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((ISNULL(U.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0)) 
			AND ((U.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
			AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))		
			AND ISNULL(U.SourceTypeId,1) <> 2003
			and u.IsObsolete = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sSecurity].[pOrganizationTaskGet]

	@rOrgGroupId [smallint],
	@rModuleId [bigint],
	@rResourceTypeId smallint,
	@rModeId tinyint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

		DECLARE @lIsObsolete bit = 0
	
		If(@rModeId=1)
			SET @lIsObsolete = 0
		else If(@rModeId=2)
			SET @lIsObsolete = 1

SELECT  T.Id,
		T.Title,
		RTM.Title AS ResourceTypeName, 			
		CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [Create],
		CAST(ISNULL((T.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
		CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [Read],
		CAST(ISNULL((T.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
		CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [Update],
		CAST(ISNULL((T.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
		CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [Delete],
		CAST(ISNULL((T.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
		CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [Search],
		CAST(ISNULL((T.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
		CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [Print],
		CAST(ISNULL((T.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
		CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [Execute],
		CAST(ISNULL((T.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
FROM sSecurity.tTask T
INNER JOIN sSecurity.tResourceTypeMaster RTM
ON RTM.Id=T.ResourceTypeId
LEFT OUTER JOIN sSecurity.tOrganizationTask OT
	ON T.Id = OT.TaskId AND (OT.OrgGroupId = @rOrgGroupId OR OT.OrgGroupId IS NULL)
WHERE		(T.ModuleId = @rModuleID)
		AND (T.IsObsolete = 0) 
		AND (T.IsClientSpecific = @lIsObsolete OR @rModeId=0)
		AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
			ORDER BY T.ModuleId,RTM.Id
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pOrganizationTaskPermissionAdd]
 
	@rXML nvarchar(max),
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXML
BEGIN
	
	BEGIN TRANSACTION
	
	UPDATE sSecurity.tOrganizationTask
	SET AvailablePermission = A.Permission
	FROM
		(
		SELECT TaskId,Permission FROM
		OPENXML (@loDoc, '/Tasks/Task', 2)
		WITH (
			TaskID int,
		    Permission INT)
		) A
	WHERE	sSecurity.tOrganizationTask.TaskId = A.TaskID AND
			sSecurity.tOrganizationTask.OrgGroupId = @rOrgGroupId
		
	INSERT INTO sSecurity.tOrganizationTask (OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId, 
			A.TaskId,
			A.Permission
	FROM(
		SELECT TaskID, Permission FROM
		OPENXML (@loDoc, '/Tasks/Task', 2)
		WITH (
			TaskID SMALLINT, 
		    Permission INT)
		) A
	WHERE NOT EXISTS(SELECT TaskId FROM sSecurity.tOrganizationTask WHERE TaskId = A.TaskId AND OrgGroupId = @rOrgGroupId)
	
	
	
	
--Declare @lCount int 
--  CREATE TABLE #tTable1 
-- (
--		Id bigint identity,
--		TaskId int,
--		AvailablePermission int,
--		OrgId int
--  )
  
--  INSERT INTO #tTable1
--  Select TaskId,AvailablePermission,OrgId 
--  FROM sSecurity.tOrganizationTask WHERE OrgId = @rOrgId AND AvailablePermission = 0 
	
	
--SELECT @lCount =  COUNT(Id) FROM #tTable1


--WHILE @lCount > 0 
--  BEGIN
--  Update P SET P.Permission = T.AvailablePermission 
--  FROM sSecurity.tPermission P 
--  INNER JOIN #tTable1 T ON T.TaskId = P.TaskId AND T.OrgId = @rOrgID
  
--  WHERE T.Id = @lCount   
--  SET @lCount = @lCount - 1
--  END
	
	
	--DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId AND  TaskId  IN (Select TaskId FROM sSecurity.tOrganizationTask WHERE OrgGroupId = @rOrgGroupId AND AvailablePermission = 0)

	DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId = @rOrgGroupId and AvailablePermission = 0

	COMMIT TRANSACTION

END
EXEC sp_xml_removedocument @loDoc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pOrganizationTaskPermissionBulkAdd]
 
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId
			
	INSERT INTO sSecurity.tOrganizationTask 
	(
		OrgGroupId, TaskId, AvailablePermission
	)
	SELECT  @rOrgGroupId, 
			T.Id,
			T.AvailablePermission
	FROM
			sSecurity.tTask T
	WHERE 
			T.AvailablePermission != 0
			AND T.IsClientSpecific = 0
	
	
	--DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId

	SELECT 1 AS RESULT
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pOrganizationTaskPermissionBulkTempAppAdd]
 
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	
	DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId
			
	INSERT INTO sSecurity.tOrganizationTask 
	(
		OrgGroupId, TaskId, AvailablePermission
	)
	SELECT  @rOrgGroupId, 
			T.Id,
			T.AvailablePermission
	FROM
			sSecurity.tTask T
	WHERE 
			T.AvailablePermission != 0
			AND T.IsClientSpecific = 0
			AND Id IN(20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,
					  20056,20199,30228,20693,20692,20241,20563,20561,30249,20622,
					  143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,
					  20007,20285,20323,20616,20055,139,20175,20176,141,142,20158,
					  30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,
					  20216,20215,20962)
	
	
	--DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId

	SELECT 1 AS RESULT
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pOrgGroupMappingGet]

	 @rOrgGroupId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SELECT * FROM sSetup.tOrgGroupEIS WHERE OrgGroupId  = @rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pOrgGroupMobileApiGet]
	 @rOrgGroupId int
	 
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 

BEGIN 
	 
	SELECT 
		OGMA.OrgGroupId,
		OGMA.Code,
		OGMA.Title,
		ISNULL(OGMA.ApiUrl,'') AS ApiUrl,
		ISNULL(OGMA.MigrationApiUrl, '') AS ApiUrlMigration    -- For ERP – Add Mingration API URL in Mobile App Registration BY Foram
  FROM 
       sSecurity.tOrgGroupMobileApp OGMA
  WHERE 
      OGMA.OrgGroupId=@rOrgGroupId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pOrgGroupMobileAppAdd]
	 @rOrgGroupId int,
	 @rCode nvarchar(20), 
	 @rTitle nvarchar(100), 
	 @rApiUrl nvarchar(200), 
	 @rIsMobileSiteAccess bit,
	 @rIsStudentPortalAccess bit,
	 @rActivationDate date 	,
	 @rPackageName nvarchar(100),
	 @rSMSProviderId tinyint,
	 @rBundleId nvarchar(100),
	 @rLoginById smallint = 0,
	 @rMigrationApiUrl nvarchar(200) = '', -- For ERP – Add Mingration API URL in Mobile App Registration BY Foram
	 @rIsRestrictOtherAppLogin BIT = 0 -- For ERP – Add App Restriction in Mobile App Registration BY Foram - 0042503

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF NOT EXISTS(SELECT 1 FROM sSecurity.tOrgGroupMobileApp WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
		IF EXISTS(SELECT OrgGroupId FROM sSecurity.tOrgGroupMobileApp WHERE Code=@rCode)
		BEGIN
			SELECT -102 AS Result
		RETURN
		END 
		IF EXISTS(SELECT OrgGroupId FROM sSecurity.tOrgGroupMobileApp WHERE Title=@rTitle)
		BEGIN
			SELECT -103 AS Result
		RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT OrgGroupId FROM sSecurity.tOrgGroupMobileApp WHERE Code=@rCode AND OrgGroupId <> @rOrgGroupId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT OrgGroupId FROM sSecurity.tOrgGroupMobileApp WHERE Title=@rTitle  AND OrgGroupId <> @rOrgGroupId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 
	IF NOT EXISTS(SELECT 1 FROM sSecurity.tOrgGroupMobileApp Where OrgGroupId = @rOrgGroupId )
	BEGIN
		INSERT INTO sSecurity.tOrgGroupMobileApp
		(
			OrgGroupId,
			Code,
			Title,
			ApiUrl,
			IsMobileSiteAccess,
			IsStudentPortalAccess,
			ActivationDate,
			PackageName,
			SMSProviderId,
			BundleId,
			LoginById,
			MigrationApiUrl,	-- For ERP – Add Mingration API URL in Mobile App Registration BY Foram
			IsRestrictOtherAppLogin -- For ERP – Add App Restriction in Mobile App Registration BY Foram - 0042503
		)
		VALUES
		(
			@rOrgGroupId, 
			@rCode ,
			@rTitle ,
			@rApiUrl,
			@rIsMobileSiteAccess,
			@rIsStudentPortalAccess ,
			@rActivationDate,
			@rPackageName,
			@rSMSProviderId,
			@rBundleId,
			@rLoginById,
			@rMigrationApiUrl,	-- For ERP – Add Mingration API URL in Mobile App Registration BY Foram
			@rIsRestrictOtherAppLogin -- For ERP – Add App Restriction in Mobile App Registration BY Foram - 0042503
		)
		SELECT 1 AS Result
	END	 
	ELSE
	BEGIN
	    UPDATE sSecurity.tOrgGroupMobileApp
	    SET 
			--OrgGroupId,
			Code=@rCode,
			Title=@rTitle,
			ApiUrl=@rApiUrl,
			IsMobileSiteAccess=@rIsMobileSiteAccess,
			IsStudentPortalAccess=@rIsStudentPortalAccess,
			ActivationDate=@rActivationDate,
			PackageName = @rPackageName,
			SMSProviderId = @rSMSProviderId,
			BundleId = @rBundleId,
			LoginById = @rLoginById,
			MigrationApiUrl = @rMigrationApiUrl,	-- For ERP – Add Mingration API URL in Mobile App Registration BY Foram
			IsRestrictOtherAppLogin = @rIsRestrictOtherAppLogin -- For ERP – Add App Restriction in Mobile App Registration BY Foram - 0042503
	    WHERE OrgGroupId = @rOrgGroupId
		
		SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pOrgGroupMobileAppDelete]
	 @rOrgGroupId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from sSecurity.tOrgGroupMobileApp where OrgGroupId=@rOrgGroupId
			select 1
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pOrgGroupMobileAppDetailAdd]
	@rOrgGroupId	int,
	@rApplicationName	nvarchar(100),
	@rPrivacyPolicyURL	nvarchar(300),
	@rAndroidPackageName	nvarchar(200),
	@rAndroidLink	nvarchar(300),
	@rAndroidStatus	int,
	@rAndroidLastVersionCode	int,
	@rAndroidLastVersionName	nvarchar(20),
	@rAndroidLastRealeaseDate	date,
	@riOSBundleIdentifier	nvarchar(200),
	@riOSLink	nvarchar(300),
	@riOSStatus	int,
	@riOSLastVersionCode	int,
	@riOSLastVersionName	nvarchar(20),
	@riOSLastRealeaseDate	date,
	@riOSExpireDate	date
	   	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
			 BEGIN TRANSACTION	

	If NOT Exists(select 1 from [sSecurity].[tOrgGroupMobileAppDetail] where OrgGroupId=@rOrgGroupId)
	BEGIN
	INSERT INTO sSecurity.tOrgGroupMobileAppDetail
		(
			OrgGroupId,
			ApplicationName,
			PrivacyPolicyURL,
			AndroidPackageName,
			AndroidLink,
			AndroidStatus,
			AndroidLastVersionCode,
			AndroidLastVersionName,
			AndroidLastRealeaseDate,
			iOSBundleIdentifier,
			iOSLink,
			iOSStatus,
			iOSLastVersionCode,
			iOSLastVersionName,
			iOSLastRealeaseDate,
			iOSExpireDate
		)
	VALUES
		(
			@rOrgGroupId,
			@rApplicationName,
			@rPrivacyPolicyURL,
			@rAndroidPackageName,
			@rAndroidLink,
			@rAndroidStatus,
			@rAndroidLastVersionCode,
			@rAndroidLastVersionName,
			@rAndroidLastRealeaseDate,
			@riOSBundleIdentifier,
			@riOSLink,
			@riOSStatus,
			@riOSLastVersionCode,
			@riOSLastVersionName,
			@riOSLastRealeaseDate,
			@riOSExpireDate
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 UPDATE  sSecurity.tOrgGroupMobileAppDetail
	    SET 
	      
			ApplicationName=@rApplicationName,
			PrivacyPolicyURL=@rPrivacyPolicyURL,
			AndroidPackageName=@rAndroidPackageName,
			AndroidLink=@rAndroidLink,
			AndroidStatus=@rAndroidStatus,
			AndroidLastVersionCode=@rAndroidLastVersionCode,
			AndroidLastVersionName=@rAndroidLastVersionName,
			AndroidLastRealeaseDate=@rAndroidLastRealeaseDate,
			iOSBundleIdentifier=@riOSBundleIdentifier,
			iOSLink=@riOSLink,
			iOSStatus=@riOSStatus,
			iOSLastVersionCode=@riOSLastVersionCode,
			iOSLastVersionName=@riOSLastVersionName,
			iOSLastRealeaseDate=@riOSLastRealeaseDate,
			iOSExpireDate=@riOSExpireDate
	      WHERE OrgGroupId = @rOrgGroupId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pOrgGroupMobileAppDetailDelete]
	 @rOrgGroupId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			Delete from [sSecurity].[tOrgGroupMobileAppDetail] where OrgGroupId=@rOrgGroupId
			select 1
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE  [sSecurity].[pOrgGroupMobileAppDetailGet]

		@rOrgGroupId int,		
		@rApplicationName nvarchar(100),
		@rAndroidStatus int,
		@rIOSStatus int,
		@rCustomerStatus smallint
		--@rPrivacyPolicyURL nvarchar(300)
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		BEGIN
		SET @rApplicationName = sCommon.fSearchStringGet(@rApplicationName)		
	    END	
	    IF (@rAndroidStatus = -1 AND @rIOSStatus = -1)
		BEGIN 
		
			SELECT 
				OGM.*
			FROM 
				sSecurity.tOrgGroupMobileAppDetail  OGM
				INNER JOIN sErp.tCustomerMaster CM ON CM.OrgGroupId = OGM.OrgGroupId
				INNER JOIN sErp.tCustomerStatusMaster CSM ON CSM.Id = CM.CustomerStatusId
			WHERE 
				((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND ((OGM.ApplicationName like @rApplicationName) OR (ISNULL(@rApplicationName,'') = ''))	
				AND((CSM.Id = @rCustomerStatus) OR (@rCustomerStatus = 0))			
				--AND ((OGM.PrivacyPolicyURL like @rPrivacyPolicyURL) OR (ISNULL(@rPrivacyPolicyURL,'') = ''))
			ORDER BY OGM.AndroidLastRealeaseDate DESC
		END
		ELSE IF(@rAndroidStatus != -1 AND @rIOSStatus != -1)
		BEGIN
			SELECT 
				OGM.*
			FROM 
				sSecurity.tOrgGroupMobileAppDetail  OGM
				INNER JOIN sErp.tCustomerMaster CM ON CM.OrgGroupId = OGM.OrgGroupId
				INNER JOIN sErp.tCustomerStatusMaster CSM ON CSM.Id = CM.CustomerStatusId
			WHERE 
				((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND ((OGM.ApplicationName like @rApplicationName) OR (ISNULL(@rApplicationName,'') = ''))	
				AND (OGM.AndroidStatus = @rAndroidStatus)
				AND (OGM.iOSStatus = @rIOSStatus)
				AND((CSM.Id = @rCustomerStatus) OR (@rCustomerStatus = 0))					
				--AND ((OGM.PrivacyPolicyURL like @rPrivacyPolicyURL) OR (ISNULL(@rPrivacyPolicyURL,'') = ''))
			ORDER BY OGM.AndroidLastRealeaseDate DESC
		END
		ELSE IF(@rAndroidStatus != -1 AND @rIOSStatus = -1)
		BEGIN
			SELECT 
				OGM.*
			FROM 
				sSecurity.tOrgGroupMobileAppDetail  OGM
				INNER JOIN sErp.tCustomerMaster CM ON CM.OrgGroupId = OGM.OrgGroupId
				INNER JOIN sErp.tCustomerStatusMaster CSM ON CSM.Id = CM.CustomerStatusId
			WHERE 
				((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND ((OGM.ApplicationName like @rApplicationName) OR (ISNULL(@rApplicationName,'') = ''))	
				AND (OGM.AndroidStatus = @rAndroidStatus)
				AND((CSM.Id = @rCustomerStatus) OR (@rCustomerStatus = 0))					
				--AND ((OGM.PrivacyPolicyURL like @rPrivacyPolicyURL) OR (ISNULL(@rPrivacyPolicyURL,'') = ''))
			ORDER BY OGM.AndroidLastRealeaseDate DESC
		END 
		ELSE IF(@rAndroidStatus = -1 AND @rIOSStatus != -1)
		BEGIN
			SELECT 
				OGM.*
			FROM 
				sSecurity.tOrgGroupMobileAppDetail  OGM
				INNER JOIN sErp.tCustomerMaster CM ON CM.OrgGroupId = OGM.OrgGroupId
				INNER JOIN sErp.tCustomerStatusMaster CSM ON CSM.Id = CM.CustomerStatusId
			WHERE 
				((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND ((OGM.ApplicationName like @rApplicationName) OR (ISNULL(@rApplicationName,'') = ''))	
				AND (OGM.iOSStatus = @rIOSStatus)
				AND((CSM.Id = @rCustomerStatus) OR (@rCustomerStatus = 0))					
				--AND ((OGM.PrivacyPolicyURL like @rPrivacyPolicyURL) OR (ISNULL(@rPrivacyPolicyURL,'') = ''))
			ORDER BY OGM.AndroidLastRealeaseDate DESC
		END 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
   
CREATE OR ALTER PROCEDURE  [sSecurity].[pOrgGroupMobileAppGet]  
  
  @rOrgGroupId int,  
  @rOrgId smallint,  
  @rCode nvarchar(20),   
  @rTitle nvarchar(100)  
    
   
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
  BEGIN   SET @rTitle = sCommon.fSearchStringGet(@rTitle)  
  SET @rCode = sCommon.fSearchStringGet(@rCode)  
 END  
   
 SELECT   
   OGM.OrgGroupId,  
   OGM.Code,  
   OGM.Title,  
   OGM.ApiUrl,  
   OGM.IsMobileSiteAccess,  
   OGM.IsStudentPortalAccess,  
   OGM.ActivationDate,  
   CM.Title AS CustomerName,  
   ISNULL(OGM.PackageName,'') As PackageName,  
   ISNULL(OGM.SMSProviderId,0) As SMSProviderId,  
   ISNULL(OGM.BundleId,'') As BundleId,  
   ISNULL(OGM.LoginById,0) AS LoginById,  
   ISNULL(DM.Title,'') AS LoginBy  
 FROM   
 sSecurity.tOrgGroupMobileApp OGM  
 INNER JOIN sCommon.tDataMaster DM ON DM.Id = OGM.LoginById AND DM.DataTypeId = 2  
  LEFT JOIN sErp.tCustomerMaster CM ON  CM.OrgGroupId=OGM.OrgGroupId  
     
 WHERE   
   
   ((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))  
    AND((CM.OrgId = @rOrgId)OR (@rOrgId=0))  
    AND ((OGM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))  
  AND ((OGM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))  
    order by OGM.ActivationDate desc  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pPageTaskPermissionsGet]
	@rUserId [int],
	@rPageURL [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
	BEGIN
		SELECT	TP.TaskId,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
		SELECT 	TaskId,
				UserId,
				(Permission & 1) AS C,
				(Permission & 2)/2 AS R,
				(Permission & 4)/4 AS U,
				(Permission & 8)/8 AS D,
				(Permission & 16)/16 AS S,
				(Permission & 32)/32 AS P,
				(Permission & 64)/64 AS X
		FROM sSecurity.tPermissionUser
		WHERE TaskId IN (SELECT TaskId FROM tScreen WHERE Page = @rPageURL) AND 
			  UserId IN (SELECT UserId FROM sSecurity.tUserRole WHERE UserId = @rUserId)
		) TP
		GROUP BY TP.TaskId
	END
	ELSE
	BEGIN
		SELECT	TP.TaskId,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
		SELECT 	TaskId,
				RoleId,
				(Permission & 1) AS C,
				(Permission & 2)/2 AS R,
				(Permission & 4)/4 AS U,
				(Permission & 8)/8 AS D,
				(Permission & 16)/16 AS S,
				(Permission & 32)/32 AS P,
				(Permission & 64)/64 AS X
		FROM sSecurity.tPermission
		WHERE TaskId IN (SELECT TaskId FROM tScreen WHERE Page = @rPageURL) AND 
			  RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId)
		) TP
		GROUP BY TP.TaskId
	END
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sSecurity].[pPendingEmployeePasswordGet]
	
	@rOrgId smallint,
	@rDepartmentId int,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit,
	@rEmployeeGroupId int = 0,
	@rStatusId int = 0,
	@rUserId BigInt
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			ISNULL(U.Id,0) AS Id,
			EC.EmployeeId,
			EC.Code,
			--EC.EmployeeName AS Name,
			[sHrm].[fEmployeeNameGet](EC.FirstName , EC.MiddleName, EC.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Name,
			ISNULL(EC.MobileNumber,'') AS MobileNo,
			ISNULL(EC.CompanyEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			ISNULL(R.Id,0) AS RoleId,
			ISNULL(R.Title,'') AS Role,
			(CASE WHEN A.UserId IS NULL THEN 'Not Register' ELSE 'Register' END) AS UserRegisterStatus,
			ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
	FROM 
			sHrm.vEmployeeCommunication EC
	LEFT JOIN sSecurity.tUser U ON U.SourceId=EC.EmployeeId AND U.SourceTypeId=95
	LEFT JOIN sSecurity.tUserRole UR ON UR.UserId=U.Id AND UR.IsPrimary = 1 AND UR.IsObsolete = 0
	LEFT JOIN sSecurity.tRole R ON UR.RoleId=R.Id
	LEFT JOIN 
			(
				SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers
			) AS A ON A.UserId = U.Id
	INNER JOIN sSetup.vDepartment VD ON VD.Id = EC.DepartmentId AND VD.OrgId = EC.OrgID
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EC.OrgId
	WHERE 
		((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((EC.EmployeeGroupId=@rEmployeeGroupId) OR (@rEmployeeGroupId=0))
		AND	(EC.OrgId = @rOrgId)
		AND (EC.IsObsolete=0)
		AND ((U.LoginPassWord is Null AND @rIsPendingLogin=1)
		OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
		AND ((EC.StatusId=@rStatusId) OR (@rStatusId=0))
		AND VD.UserId = @rUserId
		AND VD.IsObsolete = 0
	Order By 
		EC.Number
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pPendingLoginStudentdGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rNotRegister bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
	-- TOP 100
			ISNULL(U.Id,0) AS Id,
			SC.StudentId,
			SC.Code,
			SC.Name,
			SC.ClassName + '-' + SC.DivisionName AS ClassName,
			SC.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			SC.SUId,
			SM.Title AS Status,
			(CASE WHEN A.UserId IS NULL THEN 'Not Register' ELSE 'Register' END) AS UserRegisterStatus,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			SC.Number
	FROM 
			sStudent.vStudentCommunication SC
			LEFT JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			INNER JOIN sStudent.tStatusMaster SM ON SM.Id = SC.StatusId 
			LEFT JOIN 
			(
				SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers
			) AS A ON A.UserId = U.Id
	WHERE 
			((U.LoginPassWord is Null AND @rIsPendingLogin=1) OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
			 AND	(SC.OrgId = @rOrgId)
			 AND	(SC.BatchId = @rBatchId) 
			 AND	((SC.ClassId = @rClassId) OR(@rClassId=0))
			 AND	((SC.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			 AND SC.StatusId = 1
			 AND ((A.UserId IS NULL AND @rNotRegister = 1) OR (@rNotRegister = 0))
	Order By SC.DivisionOrderIndex,SC.RollNo
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pPermissionAdd]
	@rSourceRoleID [int] = 0,
	@rDestinationRoleID [int] = 0,
	@rCreatedUserId [bigint],
	@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DELETE FROM sSecurity.tPermission	
WHERE 
		RoleId = @rDestinationRoleID
		AND OrgGroupId = @rOrgGroupId

	INSERT INTO sSecurity.tPermission
		(TaskId, 
		RoleId, 
		Permission, 
		IsObsolete, 
		CreatedUserId, 
		CreatedDateTime, 
		UpdatedUserId, 
		UpdatedDateTime,
		OrgGroupId)
	SELECT  
		TaskId,
		--sCommon.fGetIntIdForOrg(convert(int,RIGHT(RoleId,5)),@rOrgGroupId),
		@rDestinationRoleID,
		Permission,
		0,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rOrgGroupId
	FROM 
		sSecurity.tPermission 
	WHERE 
		RoleId = @rSourceRoleID
		AND OrgGroupId = @rOrgGroupId
	
    DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = @rDestinationRoleID 
	
	INSERT INTO sSecurity.tRoleModulePermission
	(RoleId,ModuleId)
	SELECT DISTINCT @rDestinationRoleID, T.ModuleId
	FROM sSecurity.tPermission P 
	INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId 
	WHERE P.RoleId = @rSourceRoleID AND OrgGroupId =@rOrgGroupId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WITH (NOLOCK) WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)
BEGIN
	SELECT		TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
	FROM
	(
		SELECT 	
			P.TaskId					AS	TaskID,
			(Permission & 1) 		AS	C, --[Create],
			(Permission & 2)/2		AS	R, --[Read],
			(Permission & 4)/4		AS	U, --[Update],
			(Permission & 8)/8		AS	D, --[Delete],
			(Permission & 16)/16 	AS	S, --[Search],
			(Permission & 32)/32 	AS	P, --[Print],
			(Permission & 64)/64 	AS	X --[Execute]
		FROM sSecurity.tPermissionUser P WITH (NOLOCK)
		INNER JOIN sSecurity.tOrganizationTask T WITH (NOLOCK) ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
		INNER JOIN sSecurity.tTask T1 WITH (NOLOCK) ON T1.Id=P.TaskId 
		INNER JOIN sSecurity.tModulePermission MP WITH (NOLOCK) ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
		WHERE
		P.OrgGroupId = @rOrgGroupId AND P.UserId = @rUserId
	) TP 
	GROUP BY TP.TaskId
END
ELSE
BEGIN
	SELECT		TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
	FROM
	(
		SELECT 	
			P.TaskId					AS	TaskID,
			(Permission & 1) 		AS	C, --[Create],
			(Permission & 2)/2		AS	R, --[Read],
			(Permission & 4)/4		AS	U, --[Update],
			(Permission & 8)/8		AS	D, --[Delete],
			(Permission & 16)/16 	AS	S, --[Search],
			(Permission & 32)/32 	AS	P, --[Print],
			(Permission & 64)/64 	AS	X --[Execute]
		FROM sSecurity.tPermission P WITH (NOLOCK)
		INNER JOIN sSecurity.tOrganizationTask T WITH (NOLOCK) ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
		INNER JOIN sSecurity.tTask T1 WITH (NOLOCK) ON T1.Id=P.TaskId 
		INNER JOIN sSecurity.tModulePermission MP WITH (NOLOCK) ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
		INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WITH (NOLOCK) WHERE IsObsolete = 0 AND UserId = @rUserId) R
		ON R.RoleId = P.RoleId 
		WHERE
		P.OrgGroupId = @rOrgGroupId 
		--AND
	--RoleId 
	
	--IN
	-- (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId )
	) TP 
	GROUP BY TP.TaskId
	
	--SELECT	CAST(MAX(TP.C) AS BIT) AS [Create],
	--		CAST(MAX(TP.R) AS BIT) AS [Read],
	--		CAST(MAX(TP.U) AS BIT) AS [Update],
	--		CAST(MAX(TP.D) AS BIT) AS [Delete],
	--		CAST(MAX(TP.S) AS BIT) AS [Search],
	--		CAST(MAX(TP.P) AS BIT) AS [Print],
	--		CAST(MAX(TP.X) AS BIT) AS [Execute]
	--FROM
	--(
	--	SELECT 	(Permission & 1) AS C,
	--			(Permission & 2)/2 AS R,
	--			(Permission & 4)/4 AS U,
	--			(Permission & 8)/8 AS D,
	--			(Permission & 16)/16 AS S,
	--			(Permission & 32)/32 AS P,
	--			(Permission & 64)/64 AS X
	--	FROM sSecurity.tPermission
	--	WHERE TaskId = @rTaskId AND 
	--		  RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId)
	--) TP
END


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pPermissionModify]
	@rRoleID [bigint] = 0,
	@rXML nvarchar(max),
	@rUpdatedUserId [bigint],
	@rOrgGroupId smallint,
	@rUserId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXML
BEGIN
	BEGIN TRANSACTION	
	
	IF(@rUserId=0)
	BEGIN 
		DECLARE @lConfigValue nvarchar(50)=''
		 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

		 IF @lConfigValue = ''
			SET @lConfigValue = 'False'
	
		 IF(@lConfigValue = 'True') -- Added By Dhruv for Issue No.0011295
		 BEGIN

			 CREATE TABLE #TempSubRoleId
					(
					SubRoleId bigint
					)
					BEGIN
						WITH EmployeeCTE AS
							(
							 SELECT
							ASR.SubRoleId as SubRoleId		 
							 FROM sSecurity.tAssignSubRole ASR
							 WHERE  ASR.RoleId = @rRoleId
				
							 UNION ALL

							 SELECT
							 ASR.SubRoleId as SubRoleId
							 FROM sSecurity.tAssignSubRole ASR
							 JOIN EmployeeCTE x ON x.SubRoleId = ASR.RoleId AND x.SubRoleId != @rRoleId
							 AND ASR.SubRoleId Not In (SELECT SubRoleId FROM sSecurity.tAssignSubRole WHERE RoleId = @rRoleId)
							)
							INSERT INTO #TempSubRoleId(SubRoleId) SELECT E.SubRoleId FROM EmployeeCTE E
					END

			 UPDATE sSecurity.tPermission
				SET Permission = A.Permission, 
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM
					(
					SELECT TaskID, Permission FROM
					OPENXML (@loDoc, '/Tasks/Task', 2)
					WITH (
						TaskID INT, 
						Permission INT)
					) A
				WHERE	sSecurity.tPermission.TaskId = A.TaskID AND
						sSecurity.tPermission.RoleId = @rRoleID  

			--- Update Permission with ParentRole Permission In Hierarchywise

			UPDATE sSecurity.tPermission
				SET Permission = A.Permission, 
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM
					(
					SELECT TaskID, Permission FROM
					OPENXML (@loDoc, '/Tasks/Task', 2)
					WITH (
						TaskID INT, 
						Permission INT)
					) A
				WHERE	sSecurity.tPermission.TaskId = A.TaskID AND
						sSecurity.tPermission.RoleId IN (SELECT * FROM #TempSubRoleId)
			
			INSERT INTO sSecurity.tPermission (TaskId, RoleId, Permission, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsObsolete,OrgGroupId)
			SELECT  A.TaskID, 
					@rRoleID, 
					A.Permission, 
					@rUpdatedUserId, 
					sCommon.fGetDate(), 
					@rUpdatedUserId, 
					sCommon.fGetDate(), 
					0,
					@rOrgGroupId
			FROM(
				SELECT TaskID, Permission FROM
				OPENXML (@loDoc, '/Tasks/Task', 2)
				WITH (
					TaskID SMALLINT, 
					Permission INT)
				) A
			WHERE NOT EXISTS(SELECT TaskId FROM sSecurity.tPermission WHERE TaskId = A.TaskID AND RoleId = @rRoleID)

			--Delete hierarchy wise SubRole Permission
			DELETE P FROM sSecurity.tPermission P
			WHERE P.RoleId IN (SELECT * FROM #TempSubRoleId) 
			AND  P.TaskId IN (SELECT TaskId FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId AND RoleId = @rRoleID AND Permission = 0)

			--Delete Role Permission
			DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId AND RoleId = @rRoleID AND Permission = 0

		 END
		 ELSE
		 BEGIN
			 UPDATE sSecurity.tPermission
				SET Permission = A.Permission, 
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				FROM
					(
					SELECT TaskID, Permission FROM
					OPENXML (@loDoc, '/Tasks/Task', 2)
					WITH (
						TaskID INT, 
						Permission INT)
					) A
				WHERE	sSecurity.tPermission.TaskId = A.TaskID AND
						sSecurity.tPermission.RoleId = @rRoleID 
			
				INSERT INTO sSecurity.tPermission (TaskId, RoleId, Permission, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsObsolete,OrgGroupId)
				SELECT  A.TaskID, 
						@rRoleID, 
						A.Permission, 
						@rUpdatedUserId, 
						sCommon.fGetDate(), 
						@rUpdatedUserId, 
						sCommon.fGetDate(), 
						0,
						@rOrgGroupId
				FROM(
					SELECT TaskID, Permission FROM
					OPENXML (@loDoc, '/Tasks/Task', 2)
					WITH (
						TaskID SMALLINT, 
						Permission INT)
					) A
				WHERE NOT EXISTS(SELECT TaskId FROM sSecurity.tPermission WHERE TaskId = A.TaskID AND RoleId = @rRoleID)

				DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId AND RoleId = @rRoleID AND Permission = 0
		 END
	END
	ELSE
	BEGIN
		UPDATE sSecurity.tPermissionUser
		SET Permission = A.Permission, 
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM
			(
			SELECT TaskID, Permission FROM
			OPENXML (@loDoc, '/Tasks/Task', 2)
			WITH (
				TaskID INT, 
				Permission INT)
			) A
		WHERE	sSecurity.tPermissionUser.TaskId = A.TaskID AND
				sSecurity.tPermissionUser.UserId = @rUserId 
			
		INSERT INTO sSecurity.tPermissionUser (TaskId, UserId, Permission, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsObsolete,OrgGroupId)
		SELECT  A.TaskID, 
				@rUserId, 
				A.Permission, 
				@rUpdatedUserId, 
				sCommon.fGetDate(), 
				@rUpdatedUserId, 
				sCommon.fGetDate(), 
				0,
				@rOrgGroupId
		FROM(
			SELECT TaskID, Permission FROM
			OPENXML (@loDoc, '/Tasks/Task', 2)
			WITH (
				TaskID SMALLINT, 
				Permission INT)
			) A
		WHERE NOT EXISTS(SELECT TaskId FROM sSecurity.tPermissionUser WHERE TaskId = A.TaskID AND UserId = @rUserId)

		DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId AND UserId = @rUserId AND Permission = 0
	END
	
	COMMIT TRANSACTION
	
END
EXEC sp_xml_removedocument @loDoc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/


CREATE OR ALTER PROCEDURE [sSecurity].[pRegeneratePassword]
	
	@rEmailId nvarchar(100),
	@rNewPassword nvarchar(100),
	@rOrgId smallint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	 
	 DECLARE @lSourceTypeId smallint
	 DECLARE @lSourceId bigint
	 IF EXISTS(SELECT CompanyEmail FROM sHrm.vEmployeeCommunication where CompanyEmail=@rEmailId AND OrgId=@rOrgId)
	 BEGIN
		SELECT @lSourceTypeId=95,@lSourceId=EmployeeId FROM sHrm.vEmployeeCommunication where CompanyEmail=@rEmailId
	 END
	 ELSE IF EXISTS(SELECT ParentEmail FROM sStudent.vStudentCommunication where ParentEmail=@rEmailId AND OrgId=@rOrgId)
	 BEGIN
		SELECT @lSourceTypeId=2003,@lSourceId=StudentId FROM sStudent.vStudentCommunication where ParentEmail=@rEmailId
	 END
	 ELSE
	 BEGIN
		SELECT -1 AS RESULT
		RETURN
	 END
	 
	 	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 DECLARE @lCurrentDateTime DATETIME
	 EXECUTE @lCurrentDateTime = sCommon.fGetDate
	 
	    UPDATE  sSecurity.tUser
	    SET
			LoginPassword=@rNewPassword,
			UpdatedUserId=9999000000001,
			UpdatedDateTime=@lCurrentDateTime
	      WHERE (SourceTypeId = @lSourceTypeId AND SourceId = @lSourceId AND OrgId=@rOrgId) 
	      
		SELECT @lSourceId AS Result
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pReportGet]
	@rUserId [bigint],
	@rReportGroupId [int] 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
BEGIN
	SELECT
		ISNULL(ReportId,0) AS ReportId,
		ReportTitle,
		ReportGroup,
		OrderIndex,
		OrgGroupId
		
 
	FROM
(SELECT	 
			Report.Id AS ReportId, 			
			Report.Title AS ReportTitle,
			Report.ReportGroup,	 
 			ISNULL(PermissionValue, 0) AS Permission,
 			Report.OrderIndex,
 			Report.OrgGroupId
 			 	 
	FROM sCommon.tReport Report	
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue 
					FROM 
						sSecurity.tPermissionUser p INNER JOIN sSecurity.tTask t ON  p.TaskId = t.Id
					WHERE 
						T.IsObsolete = 0 AND UserId  IN (SELECT UserId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0)
					GROUP BY 
						TaskId  ) TBL2
					ON 
						Report.TaskId = TBL2.TaskId
						--Report.Id = TBL2.TaskId 
						 AND Report.IsObsolete = 0	
						 --AND Report.OrgGroupId IS NULL
						
					 ) 
					ReportTable
	WHERE 
		 ReportTable.Permission >= 2	
		 AND ReportTable.ReportGroup=@rReportGroupId
		 
		
		
	ORDER BY 
		ReportTable.orderindex
END
ELSE
BEGIN
	SELECT
		ISNULL(ReportId,0) AS ReportId,
		ReportTitle,
		ReportGroup,
		OrderIndex,
		OrgGroupId
		
 
	FROM
(SELECT	 
			Report.Id AS ReportId, 			
			Report.Title AS ReportTitle,
			Report.ReportGroup,	 
 			ISNULL(PermissionValue, 0) AS Permission,
 			Report.OrderIndex,
 			Report.OrgGroupId
 			 	 
	FROM sCommon.tReport Report	
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue 
					FROM 
						sSecurity.tPermission p INNER JOIN sSecurity.tTask t ON  p.TaskId = t.Id
					WHERE 
						T.IsObsolete = 0 AND RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0)
					GROUP BY 
						TaskId  ) TBL2
					ON 
						Report.TaskId = TBL2.TaskId
						--Report.Id = TBL2.TaskId 
						 AND Report.IsObsolete = 0	
						 --AND Report.OrgGroupId IS NULL
						
					 ) 
					ReportTable
	WHERE 
		 ReportTable.Permission >= 2	
		 AND ReportTable.ReportGroup=@rReportGroupId
		 
		
		
	ORDER BY 
		ReportTable.orderindex
END



	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pReportOrgScopeGet]
	
	@rUserId [bigint],
	@rReportGroupId [int],
	@rScopeSourceId smallint,
	@rScopeSourceTypeId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
BEGIN
	SELECT
		ISNULL(ReportId,0) AS ReportId,
		ReportTitle,
		ReportGroup,
		OrderIndex,
		OrgGroupId
	FROM
(SELECT	 
			Report.Id AS ReportId, 			
			Report.Title AS ReportTitle,
			Report.ReportGroup,	 
 			ISNULL(PermissionValue, 0) AS Permission,
 			Report.OrderIndex,
 			Report.OrgGroupId
 			 	 
	FROM sCommon.tReport Report	
	INNER JOIN sCommon.tReportOrg RG ON Report.Id = RG.ReportId AND (RG.ScopeSourceId=@rScopeSourceId) AND (RG.ScopeSourceTypeId=@rScopeSourceTypeId)
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue 
					FROM 
						sSecurity.tPermissionUser p INNER JOIN sSecurity.tTask t ON  p.TaskId = t.Id
					WHERE 
						T.IsObsolete = 0 AND UserId  IN (SELECT UserId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0)
					GROUP BY 
						TaskId  ) TBL2
					ON 
						Report.TaskId = TBL2.TaskId
						 AND Report.IsObsolete = 0	
					 ) 
					ReportTable
	WHERE 
		 ReportTable.Permission >= 2	
		 AND ReportTable.ReportGroup=@rReportGroupId
	ORDER BY 
		ReportTable.orderindex
END
ELSE
BEGIN
	SELECT
		ISNULL(ReportId,0) AS ReportId,
		ReportTitle,
		ReportGroup,
		OrderIndex,
		OrgGroupId
	FROM
(SELECT	 
			Report.Id AS ReportId, 			
			Report.Title AS ReportTitle,
			Report.ReportGroup,	 
 			ISNULL(PermissionValue, 0) AS Permission,
 			Report.OrderIndex,
 			Report.OrgGroupId
 			 	 
	FROM sCommon.tReport Report	
	INNER JOIN sCommon.tReportOrg RG ON Report.Id = RG.ReportId AND (RG.ScopeSourceId=@rScopeSourceId) AND (RG.ScopeSourceTypeId=@rScopeSourceTypeId)
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue 
					FROM 
						sSecurity.tPermission p INNER JOIN sSecurity.tTask t ON  p.TaskId = t.Id
					WHERE 
						T.IsObsolete = 0 AND RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0)
					GROUP BY 
						TaskId  ) TBL2
					ON 
						Report.TaskId = TBL2.TaskId
						 AND Report.IsObsolete = 0	
					 ) 
					ReportTable
	WHERE 
		 ReportTable.Permission >= 2	
		 AND ReportTable.ReportGroup=@rReportGroupId
	ORDER BY 
		ReportTable.orderindex
END

	

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pResetParentPermission]
	
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	

BEGIN TRY
BEGIN TRANSACTION	

	DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
	
	INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			Id,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tTask
	WHERE ID IN(
9128	, -- Video Viewer
9137	, -- Link Viewer
10187	, -- My Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
20089	, -- New Query
20091	, -- Circular View
20093	, -- Assignment List
20095	, -- Assignment View
20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
20106	, -- News View
20109	, -- Discussion List
20110	, -- Discussion
20111	, -- Discussion View
20112	, -- Discussion Group
20114	, -- Group Members
20117	, -- Poll View
20118	, -- Poll Vote
20130	, -- Behaviour List
20172	, -- View Task
20180	, -- Student View Result
20182	, -- View Book List
20183	, -- View Category
20190	, -- View Placement
20191	, -- Available Tests
20198	, -- My Event List
20204	, -- My Poll
20209	, -- My Activity List
20241	, -- My Attendance
20563	, -- My Classwork
20564	, -- My Result
20565	, -- My Fee
20566	 -- My Book List
				)
		SELECT 1 AS RESULT
		
		
	--	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 114 
	--	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 172 
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pResetPermission]
	
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	

BEGIN TRY
BEGIN TRANSACTION	

	DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
	
	INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			TaskId,
			sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			OrgGroupId
	FROM 
		sSecurity.tOrganizationTask
	WHERE OrgGroupId = @rOrgGroupId
	
	DELETE FROM sSecurity.tUserOrganization WHERE RIGHT(UserId,5)=3 AND OrgId IN(SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId)
	
	DECLARE @lOrgId INT
	DECLARE @lGetOrgId CURSOR
	
	SET @lGetOrgId = CURSOR FOR
	SELECT Id
	FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId
	
	OPEN @lGetOrgId
	FETCH NEXT
	FROM @lGetOrgId INTO @lOrgId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO sSecurity.tUserOrganization SELECT @lOrgId,sCommon.fGetBigIntIdForOrg(3,Id) FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId
		FETCH NEXT
		FROM @lGetOrgId INTO @lOrgId
	END
	
	CLOSE @lGetOrgId
	DEALLOCATE @lGetOrgId
	
	SELECT 1 AS RESULT
		
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pResetPortalUserPermission]
	
	@rOrgGroupId smallint ,
	@rUserType nvarchar(50) 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	

BEGIN TRY

DECLARE @lIsWindowSupport bit	 
SELECT @lIsWindowSupport = ISNULL(IsWindowSupport,0)   FROM sSetup.tOrgGroupMaster OGM 
WHERE OGM.Id = @rOrgGroupId

BEGIN TRANSACTION	

	IF @rUserType = 'AdminPortal'
	BEGIN
		DELETE FROM  sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
		
		Delete from sSecurity.tRoleModulePermission  where RoleId= sCommon.fGetIntIdForOrg(2,@rOrgGroupId)
			
		INSERT INTO  sSecurity.tRoleModulePermission 
		(
			RoleId,
			ModuleId
		) 
		Select RoleId=sCommon.fGetIntIdForOrg(2,@rOrgGroupId),ModuleId from sSecurity.tModulePermission Where OrgGroupId =@rOrgGroupId 
		 
	END
	 
	ELSE IF @rUserType = 'EmployeePortal'
	BEGIN
		Delete from sSecurity.tRoleModulePermission  where RoleId= sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
			
		INSERT INTO  sSecurity.tRoleModulePermission 
		(
			RoleId,
			ModuleId
		) 
		Select RoleId=sCommon.fGetIntIdForOrg(10,@rOrgGroupId),ModuleId from sSecurity.tModulePermission Where OrgGroupId =@rOrgGroupId 
	END
	
	ELSE IF @rUserType = 'StudentPortal'
	BEGIN
		Delete from sSecurity.tRoleModulePermission  where RoleId= sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
			
		INSERT INTO  sSecurity.tRoleModulePermission 
		(
			RoleId,
			ModuleId
		) 
		Select RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId),ModuleId from sSecurity.tModulePermission Where OrgGroupId =@rOrgGroupId 
	END
	
	
	ELSE IF @rUserType = 'OrganizationPortalTask'
	BEGIN
		DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId 
	END

	 IF @rUserType = 'OrganizationPortalTask'
	BEGIN
	
	-- 1	, --Security	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,139,23) --User
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,141,6)  -- Assign Permission
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,142,23) -- Login
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,245,6)  -- Change Password
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20158,3) -- Change Organization
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20175,2) -- Manage Student Login
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20176,2) -- Manage Employee Login
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20250,2) -- Manage Multi Child Login
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,30026,2) -- User Profile
		
	--	2	, --Alert	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20170,6) -- Send Predefine Alert
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20195,2) -- SMS History
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20201,2) -- Email Configuration
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20215,31) -- Event Template
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20216,2) -- Send Custom Alert
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20221,2) -- Send Alert Others
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20297,2) -- Custom Template Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20962,6) -- App Registered USer
	-- 3	, --Configuration	
		  INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,143,2) -- Configuration
		  INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9072,6) -- Organization Configuration
	-- 135	, --Employee	
	    INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,10097,2) -- Employee List
	    --INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,10097,2) -- Employee List
	    
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20222,2) -- Employee Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20223,2) -- View Employee Profile
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20246,2) -- My Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20249,2) -- Employee List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20270,31) -- Upload Employee Photo
 
				
				
	--- 151	, --Setup		
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20001,2) -- Organization Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20002,2) -- Department Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20003,2) -- Class Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20004,2) -- Division Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20005,2) -- Term Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20006,2) -- Subject Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20007,31) -- Batch Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20008,6) -- Class Subject Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20055,6) -- Batch Class
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20285,31) -- Organization Group Batch Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20323,2) -- Upload Organization Photo
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20407,2) -- Organization Group Master
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20545,2) -- Org. Main Group Master
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20546,2) -- Org. Sub Group Master	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20616,31) -- Batch Admin	
		
	 --	152	, --Student
		
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20021,2) -- Student List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,10187,2) -- My Profile
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20147,2) -- Student Custom Search
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20207,2) -- Student Full
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20312,2) -- Student Full Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20269,31) -- Upload Student Photo
		
		 

 
		
	--		153	, --Attendance	
	INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20241,2) -- My Attendance
			
	 --154	, --Fee
	 INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20565,2) -- My Fee
	 
	 -- 155	, --Timetable
	 
	 -- 156	, --Assessment General
	 INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20564,2) -- My Result
	 
	-- 162	, --Communication
	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20179,31) -- Upload Result
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20268,3) -- Version Info
		
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20083,31) -- Query Category Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20086,31) -- Circular
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20094,31) -- Assignment
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20100,31) -- New blogs
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20105,31) -- News
		
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20116,31) -- Poll
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20130,31) -- Behaviour List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20204,2) -- My Poll
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20180,2) -- Student View Result
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20181,2) -- Employee View Result
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20182,2) -- View Book List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20171,7) -- Assign Task
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20172,2) -- View Task
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20241,2) -- Student View Presence
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20085,2) -- Circular List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20088,2) -- Query List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20089,31) --New Query
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20091,2) -- Circular View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20093,2) -- Assignment List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20097,31) -- View Query
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20099,2) -- Blog List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20101,2) -- Blog View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20102,2) -- My Blog
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20103,2) -- Blog Activity
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20104,2) -- News List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20106,2) -- News View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20107,2) -- Query Queue

		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20114,2) -- Group Member
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20115,2) -- Poll List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20117,2) -- Poll View
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20118,2) -- Poll Vote
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20125,31) -- Behaviour type Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20126,31) -- Behaviour Entry
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20246,2) -- My Profile
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20577,2) --  Birthday
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20222,2) --   My Staff
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20617,2) --20617   --My Class
		
 

		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20110,31) -- Discussion
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20112,31) -- Discussion Group
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20109,31) -- Discussion List
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20111,2) --  Discussion View
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20113,2) -- Discussion Activities
		
	-- 209	, --Activity
	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20054,3) -- Calendar
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20056,31) -- Event Schedule
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20058,31) -- Activity Type Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20059,31) -- Activity
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20151,31) -- House Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20152,31) -- Club Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20153,22) -- Assign Club
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20621,31) -- Event Type Master
		
	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20197,2) -- Enrollment List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20198,2) -- My Event List
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20199,7) -- View Event
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20209,2) -- My Activity List
		
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20187,31) -- Placement
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20188,31) -- Placement Invite
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20189,31) -- Placement Registration
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20190,2) -- View Palcement
		
	-- 210	, --Library
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20566,2) -- My Book
	
	---Administration
	INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20716,18)--Audit Log
	INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20968,18)--Exemption Log
	
	-- 211	, --EExam
	--218	, --Placement
	
	-- 219	, --Gallery
	
	
 

 
	
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20186,31) -- Add Photo
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20185,3) -- View Photo
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9136,31) -- Link Master
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9137,18) -- Link Viewer 
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9126,31) -- Vedio Master
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9127,31) -- Vedio Type Master
		--INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,9128,2) -- Vedio Viewer
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20183,2) -- View Category
		INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20184,31) -- Add Category
		
	-- 220	, --Portal Academic
	
	
	
	-- 222	, --Employee Attendance
	-- 225	 --Academic
	INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20622,31) -- Teacher Subject Division
	INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20563,2) -- My Classwork
	INSERT INTO sSecurity.tOrganizationTask VALUES (@rOrgGroupId,20561,31) -- Classwork
	
	
-- 20554	Topic Master
--20555	Lesson Plan

 
  IF (@lIsWindowSupport = 1)
BEGIN
DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId AND  
  TaskId IN (20565,20564,20566)
--20564	My Result
--20565	My Fee
--20566	My Books
END
ELSE
BEGIN
DELETE FROM sSecurity.tOrganizationTask WHERE OrgGroupId=@rOrgGroupId  
AND TaskId IN (20180,20181,20182 )
--20180	View Result
--20182	View Books
--20181  Employee View Result
END
	
	END	

	ELSE IF @rUserType = 'AdminPortal'
	BEGIN
	
	
			INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			TaskId,
			sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tOrganizationTask
	WHERE OrgGroupId = @rOrgGroupId
 
 
 IF (@lIsWindowSupport = 1)
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20565,20564,20566)
--20564	My Result
--20565	My Fee
--20566	My Books
END
ELSE
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20180,20182 )
--20180	View Result
--20182	View Books
END
 
 
 DELETE FROM sSecurity.tRoleDashlet WHERE RoleId = sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
INSERT INTO sSecurity.tRoleDashlet (DashletId,RoleId)
SELECT  
			Id,
			sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
			 
	FROM 
		sSecurity.tDashletMaster
		WHERE IsObsolete = 0
	 
  		
	END	
	
	ELSE IF ((@rUserType = 'EmployeePortal') OR (@rUserType = 'TeacherPortal'))
	BEGIN
	
	IF (@rUserType = 'EmployeePortal')
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
	ELSE IF (@rUserType = 'TeacherPortal')
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(24,@rOrgGroupId)
	--ELSE IF (@rUserType = 'PrinciplePortal')
	--	DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(25,@rOrgGroupId)	
	
    -- SELECT TaskId, ',-- ' + Title FROM sSecurity.tScreen WHERE ScreenGroupId = 114 
	-- SELECT TaskId, ',-- ' + Title FROM sSecurity.tScreen WHERE ScreenGroupId = 213 
	
	
	
			INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			Id,
			CASE
				WHEN @rUserType = 'EmployeePortal' THEN sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
				WHEN @rUserType = 'TeacherPortal' THEN sCommon.fGetIntIdForOrg(24,@rOrgGroupId)
				--WHEN @rUserType = 'PrinciplePortal' THEN sCommon.fGetIntIdForOrg(25,@rOrgGroupId)
			END AS RoleId, 
			--sCommon.fGetIntIdForOrg(10,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tTask
	WHERE ID IN(
142     ,--Login
245     , -- Change Password
--9128	, -- Video Viewer
9137	, -- Link Viewer
20246   , -- My Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
--20089	, -- New Query
--20091	, -- Circular View
20093	, -- Assignment List
--20095	, -- Assignment View
--20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
--20106	, -- News View
--20109	, -- Discussion List
--20110	, -- Discussion
--20111	, -- Discussion View
--20112	, -- Discussion Group
--20114	, -- Group Members
--20117	, -- Poll View
--20118	, -- Poll Vote
--20172	, -- View Task
--20181	,-- Result
--20246	,-- My Profile
--20577   ,-- Birthday
--20222   -- My Staff
20172	, -- View Task
20198	, -- My Event List
20204	, -- My Poll
20209	, -- My Activity List
--20241	, -- My Attendance
--20563	, -- My Classwork
--20564	, -- My Result
--20565	, -- My Fee
20566	, -- My Book List
20577   ,-- Birthday
20222   -- My Staff
--20191   ,-- My eTest
--20617   --My Class
 
				)
IF (@lIsWindowSupport = 1)
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20566)
--20566	My Books
END
ELSE
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20182 )

--20182	View Books
END

DELETE FROM sSecurity.tRoleDashlet WHERE RoleId = sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
INSERT INTO sSecurity.tRoleDashlet (DashletId,RoleId)
SELECT  
			Id,
			sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
			 
	FROM 
		sSecurity.tDashletMaster
	WHERE ID IN( 
	1,
	2,
	3,
	4,
	5,
	6,
	7,
	8,
	10,
	11,
	12,
	13,
	14,
	15,	 
	17,
	18
	
	)	
	AND IsObsolete = 0
	
 DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(24,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(24,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(24,@rOrgGroupId)
	
	
	DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(10,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(10,@rOrgGroupId)
	 
	END	
	
	ELSE IF @rUserType = 'ClerkPortal'
	BEGIN
	
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(26,@rOrgGroupId)
	
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
		SELECT  
				Id,
				sCommon.fGetIntIdForOrg(26,@rOrgGroupId),
				AvailablePermission,
				0,
				1,
				sCommon.fGetDate(),
				1,
				sCommon.fGetDate(),
				@rOrgGroupId
		FROM 
			sSecurity.tTask
		WHERE ModuleId IN(
		152, -- Student
		154, -- Fee
		159, -- Certificate
		161, -- Admission
		230) -- Student Setting
		
		DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
		WHERE P.OrgGroupId=@rOrgGroupId AND P.RoleId=sCommon.fGetIntIdForOrg(26,@rOrgGroupId) AND T.ModuleId = 154 
		AND P.TaskId NOT IN(
							20108, -- Fee Receipt List
							20068, -- Fee Receipt 
							20025, -- Student Fee
							20225  -- Fee Report
							)
							
							
	DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(26,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(26,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(26,@rOrgGroupId)
		
	END
	
	
	
	
	
	
	
	
	
		ELSE IF @rUserType = 'PrinciplePortal'
	BEGIN
	
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(25,@rOrgGroupId)
	
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
		SELECT  
			Id,
			 sCommon.fGetIntIdForOrg(25,@rOrgGroupId),  
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
		FROM 
			sSecurity.tTask
		WHERE ModuleId IN(
				--Clerk 
				152, -- Student
				154, -- Fee
				159, -- Certificate
				161, -- Admission
				230 )
				OR Id In 
				(
					--142     ,--Login
--245     , -- Change Password
--9128	, -- Video Viewer
9137	, -- Link Viewer
20246   , -- My Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
--20089	, -- New Query
--20091	, -- Circular View
20093	, -- Assignment List
--20095	, -- Assignment View
--20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
--20106	, -- News View
--20109	, -- Discussion List
--20110	, -- Discussion
--20111	, -- Discussion View
--20112	, -- Discussion Group
--20114	, -- Group Members
--20117	, -- Poll View
--20118	, -- Poll Vote
--20172	, -- View Task
--20181	,-- Result
--20246	,-- My Profile
--20577   ,-- Birthday
--20222   -- My Staff
20172	, -- View Task
20198	, -- My Event List
20204	, -- My Poll
--20209	, -- My Activity List
--20241	, -- My Attendance
--20563	, -- My Classwork
--20564	, -- My Result
--20565	, -- My Fee
20566	, -- My Book List
20577   ,-- Birthday
20222   -- My Staff
--20191   ,-- My eTest
--20617   --My Class
				)
	 
							
							
	DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(25,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(25,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(25,@rOrgGroupId)
		
	END
	
	
	
	
	
	
	
	
	ELSE IF @rUserType = 'HeadClerkPortal'
	BEGIN
	
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(27,@rOrgGroupId)
	
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
		SELECT  
				Id,
				sCommon.fGetIntIdForOrg(27,@rOrgGroupId),
				AvailablePermission,
				0,
				1,
				sCommon.fGetDate(),
				1,
				sCommon.fGetDate(),
				@rOrgGroupId
		FROM 
			sSecurity.tTask
		WHERE ModuleId IN(
		152, -- Student
		154, -- Fee
		159, -- Certificate
		161, -- Admission
		230) -- Student Setting
		
		DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(27,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(27,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(27,@rOrgGroupId)
	END
	
	ELSE IF @rUserType = 'FrontOfficePortal'
	BEGIN
	
		DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(28,@rOrgGroupId)
	
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
		SELECT  
				Id,
				sCommon.fGetIntIdForOrg(28,@rOrgGroupId),
				AvailablePermission,
				0,
				1,
				sCommon.fGetDate(),
				1,
				sCommon.fGetDate(),
				@rOrgGroupId
		FROM 
			sSecurity.tTask
		WHERE Id IN(
		-- Front Office
		20284, -- Visitor Log
		20696, -- Courier Dispatch
		20698, -- Courier Receive
		--20173, -- Contact Type Master
		--20174, -- Contact Master
		
		-- Employee Center 
		--20246,  -- My Profile
		--20576,  -- My Payroll
		--20181,  -- Result
		
		-- My Communication
		20054,  -- Calender
		20085,  -- Circular List
		20088,  -- Query List
		20099,  -- Blog List
		20104,  -- News List
		20109,  -- Discussion List
		20172,  -- View Task
		20222,  -- My Staff
		20577,  -- Birthdays
		20723,  -- E-Book List
		20724,  -- My Messages
		20183,  -- Photos
		--9128,   -- Videos
		20204,  -- My Poll
		20107,  -- Query Queue
		20093,  -- My Assignment
		20103,  -- Blog Activities
		--20209,  -- My Activity
		20198,  -- My Event
		20692,  -- Useful Info
		9137 ,  -- Useful Links
		20113   -- Discussion Activities
		) 
		
		DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(28,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(28,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(28,@rOrgGroupId)
	END


	ELSE IF @rUserType = 'ParentPortal'
	BEGIN
	
	DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
	
    --	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 114 
	--	SELECT TaskId FROM sSecurity.tScreen WHERE ScreenGroupId = 172 
		INSERT INTO sSecurity.tPermission
		(
			TaskId, 
			RoleId, 
			Permission, 
			IsObsolete, 
			CreatedUserId, 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			OrgGroupId
		)
	SELECT  
			Id,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId),
			AvailablePermission,
			0,
			1,
			sCommon.fGetDate(),
			1,
			sCommon.fGetDate(),
			@rOrgGroupId
	FROM 
		sSecurity.tTask
	WHERE ID IN(
142     ,--Login
245     , -- Change Password
--9128	, -- Video Viewer
9137	, -- Link Viewer
10187	, -- My Profile
--20312   , -- Student Full Profile
20054	, -- Calendar
20085	, -- Circular List
20088	, -- Query List
--20089	, -- New Query
--20091	, -- Circular View
20093	, -- Assignment List
--20095	, -- Assignment View
--20097	, -- View Query
20099	, -- Blog List
20101	, -- Blog View
20104	, -- News List
--20106	, -- News View
--20109	, -- Discussion List
--20110	, -- Discussion
--20111	, -- Discussion View
--20112	, -- Discussion Group
--20114	, -- Group Members
--20117	, -- Poll View
--20118	, -- Poll Vote
20130	, -- Behaviour List
--20172	, -- View Task
20180	, -- Student View Result
20182	, -- View Book List
20183	, -- View Category
--20190	, -- View Placement
--20191	, -- My eTest
20198	, -- My Event List
20204	, -- My Poll
20209	, -- My Activity List
20241	, -- My Attendance
20563	, -- My Classwork
20564	, -- My Result
20565	, -- My Fee
20566	, -- My Book List
20577   ,-- Birthday
20222   ,-- My Staff
--20191   ,-- My eTest
20617   --My Class

)
	
IF (@lIsWindowSupport = 1)
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20565,20564,20566)
--20564	My Result
--20565	My Fee
--20566	My Books
END
ELSE
BEGIN
DELETE FROM sSecurity.tPermission WHERE OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
AND TaskId IN (20180,20182 )
--20180	View Result
--20182	View Books
END
	
DELETE FROM sSecurity.tRoleDashlet WHERE RoleId = sCommon.fGetIntIdForOrg(22,@rOrgGroupId)

INSERT  INTO sSecurity.tRoleDashlet (DashletId,RoleId)
SELECT  
			Id,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
			 
	FROM 
		sSecurity.tDashletMaster
	WHERE ID IN( 
	1,
	2,
	3,
	7,
	12,
	13,
	14,
	15,	 
	17,
	18
	
	)
	AND IsObsolete = 0


DELETE FROM sSecurity.tRoleModulePermission WHERE RoleId = sCommon.fGetIntIdForOrg(22,@rOrgGroupId)

	INSERT  INTO sSecurity.tRoleModulePermission (ModuleId,RoleId)
    SELECT  
			DISTINCT 
			ModuleId,
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
			
			 
	FROM 
	
	sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id
	WHERE P.OrgGroupId=@rOrgGroupId AND RoleId=sCommon.fGetIntIdForOrg(22,@rOrgGroupId)
	 
	END		

	
	SELECT 1 AS RESULT
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pRoleAdd]
	@rOrgGroupId smallint,
	@rTitle [nvarchar](100),
	@rRemark [nvarchar](300),
	@rIsSystem [bit],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	
	IF EXISTS(SELECT Id FROM sSecurity.tRole WHERE Title = @rTitle AND OrgGroupId = @rOrgGroupId)
	BEGIN
		SELECT -1 AS RoleId
	END
	ELSE
	BEGIN	
		DECLARE @lNextNumber INT
		--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sSecurity.tRole',@lNextNumber = @lNextNumber output
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sSecurity.tRole', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		DECLARE @lCurrentDateTime DATETIME
		EXECUTE @lCurrentDateTime = sCommon.fGetDate	
		
		INSERT INTO sSecurity.tRole
			(
				ID,
				Title,			
				Remark,
				IsSystem,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				OrgGroupId
			)
		VALUES
			(
				@lNextNumber,
				@rTitle,			
				@rRemark,
				@rIsSystem,
				@rIsObsolete,
				@rCreatedUserId,
				@lCurrentDateTime,
				@rCreatedUserId,
				@lCurrentDateTime,
				@rOrgGroupId
			)


		SELECT @lNextNumber AS RoleId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pRoleDashletGet]
	 
	@rRoleId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT		 
		DM.Title AS DashletName,
		DM.Id AS DashletId,
		CASE 
			WHEN RD.DashletId IS NULL THEN Convert(Bit,0)
			ELSE Convert(Bit,1)
		END AS IsCheck,
		T.Title As TaskName,
		T.Id As TaskId,
		M.Title As ModuleName
	FROM
	sSecurity.tDashletMaster DM
	INNER JOIN sSecurity.tPermission P ON P.TaskId=DM.TaskId AND RoleId = @rRoleId	 
	INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
	INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
	INNER JOIN sCommon.tModuleMaster M ON M.Id=T.ModuleId
	LEFT JOIN  
   sSecurity.tRoleDashlet RD 		 	
		ON RD.DashletId=DM.Id AND RD.RoleId =@rRoleId 
		WHERE 
		(P.Permission & 2) =2
		--AND ScreenGroupId=@rScreenGroupId AND U.IsObsolete=0
		 
		AND T.IsObsolete = 0	
		AND DM.IsObsolete = 0
	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pRoleDashletUpdate]
	
	@rRoleDashletImpXml [nvarchar](max),
	@rRoleId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rRoleDashletImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sSecurity.tRoleDashlet Where RoleId = @rRoleId
	
	 INSERT INTO sSecurity.tRoleDashlet
		(
			RoleId,
			DashletId
			)
		SELECT
			RoleId,
			DashletId
		FROM OPENXML (@loDoc, '/Table/RoleDashlet', 1)
		WITH ( 
				RoleId int,
				DashletId int
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pRoleGet]
	@rOrgGroupId smallint,
	@rActiveOnly [bit] = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

IF @rActiveOnly = 0
	BEGIN
		 SELECT Id AS Id,
				Title,
				Remark,
				IsObsolete,
				IsSystem,
				UpdatedDateTime
		 FROM sSecurity.tRole WHERE OrgGroupId = @rOrgGroupId
	END
ELSE
	BEGIN 
		SELECT  Id AS Id,
				Title,
				--TitleResourceKeyId,
				CAST(1 AS BIT) AS PermissionPresent
		FROM sSecurity.tRole
		WHERE IsObsolete = 0 AND OrgGroupId = @rOrgGroupId  AND
				Id 
IN (SELECT DISTINCT RoleId FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId)

		UNION 

		SELECT  Id AS Id,
				Title,
				--TitleResourceKeyId,
				CAST(0 AS BIT) AS PermissionPresent
		FROM sSecurity.tRole
		WHERE IsObsolete = 0 AND OrgGroupId = @rOrgGroupId AND 
				Id NOT IN (SELECT DISTINCT RoleId FROM
 sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId  )

	END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pRoleModify]
	@rRoleId [int],
	@rTitle [nvarchar](100),
	@rRemark [nvarchar](300),
	@rIsSystem [bit],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	DECLARE @lReturnCode INT
	SET @lReturnCode = 1

	IF EXISTS (SELECT 1 FROM sSecurity.tUserRole WHERE RoleId = @rRoleId AND IsObsolete = 0 AND @rIsObsolete = 1)
	
		SET @lReturnCode = -401
	IF EXISTS (SELECT * FROM sSecurity.tPermission WHERE RoleId = @rRoleId AND IsObsolete = 0 AND @rIsObsolete = 1)
		SET @lReturnCode = -401
	
	IF(@lReturnCode = 1)
	BEGIN
		DECLARE @lCurrentDateTime DATETIME
		EXECUTE @lCurrentDateTime = sCommon.fGetDate	
			
		UPDATE sSecurity.tRole
			SET 
				Title = @rTitle,
				Remark = @rRemark,
				IsSystem = @rIsSystem,
				IsObsolete = @rIsObsolete,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = @lCurrentDateTime
		  WHERE Id = @rRoleId	
	END
	
	SELECT @lReturnCode AS ReturnCode
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pRoleModuleMaster]
	@rId [int] = 0,
	@rOrgGroupId smallint=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 
	SELECT Id,Title FROM sCommon.tModuleMaster MM  
	INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = MM.Id AND MP.OrgGroupId=@rOrgGroupId 
	INNER JOIN sSecurity.tRoleModulePermission RM ON RM.ModuleId = MP.ModuleId WHERE (IsObsolete = 0) 
	AND RoleId = @rId ORDER BY Title
 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pRoleModulePermissionGet]
	  
	 @rOrgGroupId smallint,
	 @rRoleId int 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	IF @lConfigValue = ''
		SET @lConfigValue = 'False'
	
	        DECLARE @lDefaultRoleId int=0
			DECLARE @lModuleId int=0
	
			SET @lDefaultRoleId = RIGHT(@rRoleId, 3)
	
			-- Employee
			IF(@lDefaultRoleId = 010) SET @lModuleId = 233
	
			-- Student
			IF(@lDefaultRoleId = 022) SET @lModuleId = 234
	IF(@lConfigValue = 'TRUE')
	 BEGIN
			IF EXISTS(SELECT 1 FROM sSecurity.tAssignSubRole WHERE SubRoleId = @rRoleID)
		      BEGIN
				SELECT * INTO #TmpTable 
				FROM (
				SELECT DISTINCT(ModuleId)
				FROM sSecurity.tRoleModulePermission 
				WHERE RoleId IN (SELECT RoleId FROM sSecurity.tAssignSubRole WHERE SubRoleId = @rRoleID)) AS T

				SELECT 
					MP.ModuleId,
					MM.Title AS ModuleName,
					MP.OrgGroupId,
					CASE WHEN RDM.ModuleId IS NULL THEN Convert(bit,0) ELSE Convert(bit,1) END AS IsChecked
				FROM 
					sSecurity.tModulePermission MP
					INNER JOIN  sCommon.tModuleMaster MM ON MP.ModuleId=MM.Id AND MM.Id!=@lModuleId
					LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId
					INNER JOIN #TmpTable Tmp ON Tmp.ModuleId = MM.Id
			    WHERE 
					MP.OrgGroupId =@rOrgGroupId
			  END
			ELSE
				SELECT 
					MP.ModuleId,
					MM.Title AS ModuleName,
					MP.OrgGroupId,
					CASE WHEN RDM.ModuleId IS NULL THEN Convert(bit,0) ELSE Convert(bit,1) END AS IsChecked
				FROM 
					sSecurity.tModulePermission MP
					INNER JOIN  sCommon.tModuleMaster MM ON MP.ModuleId=MM.Id AND MM.Id!=@lModuleId
					LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId
			    WHERE 
					MP.OrgGroupId =@rOrgGroupId
	 END
	ELSE
	 BEGIN
			SELECT 
				MP.ModuleId,
				MM.Title AS ModuleName,
				MP.OrgGroupId,
				CASE WHEN RDM.ModuleId IS NULL THEN Convert(bit,0) ELSE Convert(bit,1) END AS IsChecked
			FROM 
				sSecurity.tModulePermission MP
				INNER JOIN  sCommon.tModuleMaster MM ON MP.ModuleId=MM.Id AND MM.Id!=@lModuleId
				LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId
		  WHERE 
				MP.OrgGroupId =@rOrgGroupId
	 END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pRoleModuleUpdate]
	
	@rRoleModuleImpXml [nvarchar](max),
	@rRoleId int,
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rRoleModuleImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	 IF @lConfigValue = ''
		SET @lConfigValue = 'False'
	
	 IF(@lConfigValue = 'True') -- Added By Dhruv for Issue No.0011295
	 BEGIN
		CREATE TABLE #TempSubRoleId
		(
		SubRoleId bigint
		)
		BEGIN
			WITH EmployeeCTE AS
				(
				 SELECT
				ASR.SubRoleId as SubRoleId		 
				 FROM sSecurity.tAssignSubRole ASR
				 WHERE  ASR.RoleId = @rRoleId
				
				 UNION ALL

				 SELECT
				 ASR.SubRoleId as SubRoleId
				 FROM sSecurity.tAssignSubRole ASR
				 JOIN EmployeeCTE x ON x.SubRoleId = ASR.RoleId AND x.SubRoleId != @rRoleId
				 AND ASR.SubRoleId Not In (SELECT SubRoleId FROM sSecurity.tAssignSubRole WHERE RoleId = @rRoleId)
				)
				INSERT INTO #TempSubRoleId(SubRoleId) SELECT DISTINCT(E.SubRoleId) FROM EmployeeCTE E
	    END
		
		-- Delete hierarchy data of Role wise Permission
		DELETE R FROM sSecurity.tRoleModulePermission R
		INNER JOIN sCommon.tModuleMaster M ON M.Id = R.ModuleId
		INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = M.Id
		WHERE R.RoleId IN (SELECT * FROM #TempSubRoleId) AND R.ModuleId NOT IN(SELECT ModuleId FROM OPENXML(@loDoc, '/Table/RoleDashlet', 1) WITH(ModuleId int))
		AND M.IsObsolete = 0 AND MP.OrgGroupId =@rOrgGroupId

		-- Delete RoleModulePermission Table
		DELETE FROM sSecurity.tRoleModulePermission Where RoleId = @rRoleId
		
		-- Delete hierarchy data of Permission
		DELETE P FROM sSecurity.tPermission P
		INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
		WHERE P.RoleId IN (SELECT * FROM #TempSubRoleId) AND T.ModuleId NOT IN(SELECT ModuleId FROM OPENXML(@loDoc, '/Table/RoleDashlet', 1) WITH(ModuleId int))

		-- Delete Permission Table 
		DELETE P FROM sSecurity.tPermission P
		INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
		WHERE P.RoleId = @rRoleId AND T.ModuleId NOT IN(SELECT ModuleId FROM OPENXML(@loDoc, '/Table/RoleDashlet', 1) WITH(ModuleId int))
	 
		-- Insert RoleModulePermission Table 
		INSERT INTO sSecurity.tRoleModulePermission
			(
				RoleId,
				ModuleId
				)
			SELECT
				RoleId,
				ModuleId
			FROM OPENXML (@loDoc, '/Table/RoleDashlet', 1)
			WITH ( 
					RoleId int,
					ModuleId int
				  )

	  	   DROP TABLE #TempSubRoleId
		   SELECT 1 AS Result
		   COMMIT TRANSACTION
	END
	ELSE
	BEGIN
			-- Delete RoleModulePermission Table
			DELETE FROM sSecurity.tRoleModulePermission Where RoleId = @rRoleId
	
			-- Delete Permission Table 
			DELETE P FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
			WHERE P.RoleId = @rRoleId AND T.ModuleId NOT IN(SELECT ModuleId FROM OPENXML(@loDoc, '/Table/RoleDashlet', 1) WITH(ModuleId int))
	 
			-- Insert RoleModulePermission Table 
			INSERT INTO sSecurity.tRoleModulePermission
				(
					RoleId,
					ModuleId
					)
				SELECT
					RoleId,
					ModuleId
				FROM OPENXML (@loDoc, '/Table/RoleDashlet', 1)
				WITH ( 
						RoleId int,
						ModuleId int
					  )
	  
			   SELECT 1 AS Result
			   COMMIT TRANSACTION
	END	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pRolePermissionModify]
	@rRoleID [bigint] = 0,
	@rXML nvarchar(max),
	@rOrgGroupId smallint,
	@rCreatedUserId bigint 
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
DECLARE @loDoc INT
DECLARE @lTaskId INT
DECLARE @lPermissionId INT


EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXML
BEGIN

	BEGIN TRANSACTION	
	
 
	DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId AND RoleId = @rRoleID  
	
	INSERT INTO sSecurity.tPermission 
	(
		TaskId,
		RoleId,
		Permission,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		IsObsolete,
		OrgGroupId
	)
	SELECT  T.Id, 
			@rRoleID, 
			T.AvailablePermission, 
			@rCreatedUserId, 
			sCommon.fGetDate(), 
			@rCreatedUserId, 
			sCommon.fGetDate(), 
			0,
			@rOrgGroupId
	FROM(
		SELECT ModuleId FROM
		OPENXML (@loDoc, '/Tasks/Task', 2)
		WITH (
			ModuleId SMALLINT
		    )
		) A INNER JOIN sSecurity.tTask T ON T.ModuleId = A.ModuleId  
    SELECT 1 AS Result

	COMMIT TRANSACTION
	
END
EXEC sp_xml_removedocument @loDoc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pRoleSearch]
	@rOrgGroupId smallint,
	@rTitleSearchString [nvarchar](100),
	@rRemarkSearchString [nvarchar](100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rTitleSearchString = sCommon.fSearchStringGet(@rTitleSearchString)
	SET @rRemarkSearchString = sCommon.fSearchStringGet(@rRemarkSearchString) 
	SELECT 
		Roles.Id,
		Roles.Title,
		Roles.Remark,			
		Roles.IsObsolete,			
		CASE WHEN Roles.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay                              
	FROM 
		sSecurity.tRole Roles
	WHERE 
	(    OrgGroupId = @rOrgGroupId       
	AND ((Title LIKE @rTitleSearchString) OR (@rTitleSearchString = ''))
	AND ((Remark LIKE @rRemarkSearchString) OR (@rRemarkSearchString = ''))
	)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pRolewisePermissionGet]
	
	@rModuleId smallint,
	@rResourceTypeId smallint,
	@rTaskId smallint,		
	@rOrgGroupId int,
	@rRoleId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	 IF @lConfigValue = ''
		SET @lConfigValue = 'False'

	IF(@lConfigValue = 'True')
	 BEGIN
	 IF EXISTS(SELECT 1 FROM sSecurity.tAssignSubRole WHERE SubRoleId = @rRoleId)
	 BEGIN
	  SELECT * FROM
		(SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			INNER JOIN (SELECT DISTINCT(ASR.SubRoleId),T.Id FROM sSecurity.tAssignSubRole ASR 
			INNER JOIN sSecurity.tRole R ON R.Id = ASR.SubRoleId LEFT JOIN sSecurity.tPermission P ON P.RoleId = ASR.RoleId 
			LEFT JOIN sSecurity.tTask T ON T.Id = P.TaskId WHERE ASR.RoleId = @rRoleId) A ON A.SubRoleId = R.Id AND A.Id = @rTaskId

			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL) 
			
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)

			
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId

			UNION ALL

		SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			INNER JOIN (SELECT ASR.SubRoleId,T.Id FROM sSecurity.tAssignSubRole ASR 
			INNER JOIN sSecurity.tRole R ON R.Id = ASR.SubRoleId LEFT JOIN sSecurity.tPermission P ON P.RoleId = ASR.RoleId 
			LEFT JOIN sSecurity.tTask T ON T.Id = P.TaskId WHERE ASR.SubRoleId = @rRoleId) A ON A.SubRoleId = R.Id AND A.Id = @rTaskId

			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL) 
			
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
				
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId AND R.Id = @rRoleId
			) as a
	 END
	 ELSE
	 BEGIN
	   SELECT * FROM
		(SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			INNER JOIN (SELECT DISTINCT(ASR.SubRoleId),T.Id FROM sSecurity.tAssignSubRole ASR 
			INNER JOIN sSecurity.tRole R ON R.Id = ASR.SubRoleId LEFT JOIN sSecurity.tPermission P ON P.RoleId = ASR.RoleId 
			LEFT JOIN sSecurity.tTask T ON T.Id = P.TaskId WHERE ASR.RoleId = @rRoleId) A ON A.SubRoleId = R.Id AND A.Id = @rTaskId

			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL) 
			
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)

			
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId

			UNION ALL

		SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			 
			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL) 
			
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
				
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId AND R.Id = @rRoleId
			) as a
	 END
	END
	ELSE
	 BEGIN
		SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL)
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId 
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId		
		ORDER BY 			
			T.ModuleId
	 END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pRoleWiseUserFavoriteScreenAdd]
	
	@rUserId [bigint],
	@rFavoraiteScreenId int,
	@rIsDelete bit
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  	
 	IF EXISTS(SELECT 1 FROM sSecurity.tUserFavoriteScreen WHERE UserId = @rUserId AND FavoriteScreenId = @rFavoraiteScreenId) AND @rIsDelete = 0
			BEGIN
				Delete From sSecurity.tUserFavoriteScreen WHERE UserId = @rUserId AND FavoriteScreenId = @rFavoraiteScreenId
			END
	ELSE IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserFavoriteScreen WHERE UserId = @rUserId AND FavoriteScreenId = @rFavoraiteScreenId)
			BEGIN 
					INSERT INTO sSecurity.tUserFavoriteScreen
						(
							UserId,		
						    FavoriteScreenId
						)
					VALUES
						(
							@rUserId,
							@rFavoraiteScreenId							 
						) 
			END			
			SELECT 1 AS UserId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pRoleWiseUserFavoriteScreenGet]
	
	@rRoleId int	
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
      SELECT  
           U.UserId,
           FavoriteScreenId AS FavoraiteScreenId,
           S.Title AS UserFavoraiteScreen,
           --CASE WHEN S.ScreenTypeId = 1 THEN S.Page
           --ELSE S.Page + '?MenuID=' +CONVERT(Nvarchar(50),M.Id) END AS PagePath,
            CASE WHEN S.ScreenTypeId = 1 THEN  S.Page + '?MenuID=' +CONVERT(Nvarchar(50),(SELECT Id FROM sSecurity.tMenu M WHERE M.ScreenId = U.FavoriteScreenId AND M.IsObsolete = 0)) 
           ELSE S.Page  END AS PagePath,
           T.ResourceTypeId 
                       
      FROM
 	  sSecurity.tUserFavoriteScreen U 
 	  INNER JOIN sSecurity.tScreen S ON U.FavoriteScreenId = S.Id  
 	  INNER JOIN sSecurity.tUserRole UR On UR.UserId = U.UserId
 	  INNER JOIN sSecurity.tTask T ON S.TaskId = T.Id
		 
	  where UR.RoleId=@rRoleId  
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sSecurity].[pRptStudentPasswordGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rIsPendingLogin bit,
	@rIsCreatedLogin bit,
	@rClassId int =0,
	@rDivisionId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
	-- TOP 100
			ISNULL(U.Id,0) AS Id,
			SC.StudentId,
			SC.Code,
			SC.Name,
			SC.ClassName + '-' + SC.DivisionName AS ClassName,
			SC.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			TU.UserName,
			TU.UserPassword,
			SC.SUId,
			SM.Title AS Status,
			(CASE WHEN A.UserId IS NULL THEN 'Not Register' ELSE 'Register' END) AS UserRegisterStatus
	FROM 
			sStudent.vStudentCommunication SC
			LEFT JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			LEFT JOIN sSecurity.tTempUser TU ON U.Id = TU.UserId 
			INNER JOIN sStudent.tStatusMaster SM ON SM.Id = SC.StatusId 
			LEFT JOIN 
			(
				SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers
			) AS A ON A.UserId = U.Id
	WHERE 
			((U.LoginPassWord is Null AND @rIsPendingLogin=1) OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
			 AND	(SC.OrgId = @rOrgId)
			 AND	(SC.BatchId = @rBatchId) 
			 AND	((SC.ClassId = @rClassId) OR(@rClassId=0))
			 AND	((SC.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			 AND SC.StatusId = 1
	Order By SC.DivisionOrderIndex,SC.RollNo
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pScreenByMenuIdGet]
	@rMenuId [int]=0,
	@rScreenId [int]=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SET @rMenuId = ISNULL(@rMenuId ,0)
	SET @rScreenId = ISNULL(@rScreenId ,0)

	SELECT 
		Screen.Id			AS ScreenId,
		Screen.Title		AS ScreenTitle,
		Screen.TaskId		AS TaskId,	
		Screen.Page			As PageUrl,
		Screen.IsObsolete	AS ScreenIsObsolete,
		ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
		SGM.Title AS ScreenGroupName
		
		
	FROM sSecurity.tScreen Screen LEFT JOIN sSecurity.tScreenGroupMaster SGM ON SGM.Id = Screen.ScreenGroupId
	LEFT JOIN sSecurity.tMenu Menu
		ON Menu.ScreenId = Screen.Id
	WHERE ((Menu.Id = @rMenuId) OR (@rMenuId = 0))
	AND ((Screen.Id = @rScreenId) OR (@rScreenId = 0))

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pScreenByScreenIdGet]
	@rScreenId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		Id			AS ScreenId,
		Title		AS ScreenTitle,
		TaskId		AS TaskId,	
		Page			As PageUrl,
		IsObsolete	AS ScreenIsObsolete
	FROM sSecurity.tScreen 
	WHERE Id = @rScreenId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pScreenGet]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
SELECT	
	S.Id			AS ScreenId,
	S.Title		AS ScreenTitle,
	S.TaskId		AS TaskId,	
	S.Page		As PageUrl,
	S.IsObsolete	AS ScreenIsObsolete,	
	S.Title,		
	S.Page,
	SG.Id AS ScreenGroupId,
	ISNULL(SG.Title,'') AS ScreenGroupName
		
FROM 
	sSecurity.tScreen S
LEFT JOIN sSecurity.tScreenGroupMaster SG ON SG.Id=S.ScreenGroupId
WHERE 
	S.IsObsolete = 0 --and S.ScreenGroupID=122
	end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pScreenGroupDataListGet]

	@rUserId [bigint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lOrgGroupId bigint , @lConfigValue nvarchar(10) = ''

IF EXISTS (SELECT OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId)
BEGIN
	SELECT @lOrgGroupId = OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId
		
	SELECT @lConfigValue = ISNULL(CS.ItemValue,'False') FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.Configurationid AND CS.SourceId= @lOrgGroupId AND CS.SourceTypeId=2010 WHERE CM.Id = 327

		IF(@lConfigValue = 'True')
		BEGIN
		     IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002,31005,31015,30580,31023,31033,31038,31043,31048,31175,31188,20776)
				END
			ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002,31005,31015,30580,310235,31033,31038,31043,31048,31175,31179,30331,31182,31188,20776,31314,31295)
				END
		END
		ELSE
		BEGIN
			  IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
				END
			  ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
				END
		END
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pScreenHelpAdd]
	 
         @rScreenId int = 0,
	     @rHelpDescription nvarchar(max),
		 @rIsUpload bit,
		 @rUploadRemark nvarchar(500),
		 @rIsExport bit,
		 @rExportRemark nvarchar(500),
		 @rIsImport bit,
		 @rImportRemark nvarchar(500)	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
			
	 BEGIN TRANSACTION	

	IF NOT EXISTS(SELECT 1 FROM [sSecurity].[tScreenHelp] WHERE ScreenID=@rScreenId )	
	BEGIN
	INSERT INTO [sSecurity].[tScreenHelp]
		(
			ScreenId, 
			HelpDescription,
			IsUpload,
			UploadRemark,
			IsExport,
			ExportRemark,
			IsImport,
			ImportRemark
		)
	   VALUES
		(
			@rScreenId, 
			@rHelpDescription,
			@rIsUpload,
			@rUploadRemark,
			@rIsExport,
			@rExportRemark,
			@rIsImport,
			@rImportRemark	
		)
		SELECT 1 as Result
	END	 
	
ELSE
	 BEGIN
	
	    UPDATE   [sSecurity].[tScreenHelp]
	    SET
			ScreenId=@rScreenId,
			HelpDescription=@rHelpDescription,
			IsUpload = @rIsUpload,
			UploadRemark = @rUploadRemark,
			IsExport = @rIsExport,
			ExportRemark = @rExportRemark,
			IsImport = @rIsImport,
			ImportRemark = @rImportRemark

	      WHERE Screenid = @rScreenId
		  SELECT 11 as Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pScreenHelpGet]
	 @rScreenId int = 0,
	 @rHelpDescription nvarchar(max)='',
	 @rModuleId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 
	SELECT 
	
		ScreenId, 
		HelpDescription,
		SC.Title,
		CM.Title As Module,
		ST.Id As TaskId, 
		CM.Id As ModuleId,
		ISNULL(SH.IsUpload, 0) AS IsUpload,
		ISNULL(SH.UploadRemark, '') AS UploadRemark,
		ISNULL(SH.IsExport, 0) AS IsExport,
		ISNULL(SH.ExportRemark, '') AS ExportRemark,
		ISNULL(SH.IsImport, 0) AS IsImport,
		ISNULL(SH.ImportRemark, '') AS ImportRemark
      
  FROM 
         [sSecurity].[tScreenHelp]  SH
		 INNER JOIN [sSecurity].[tScreen]  SC ON SC.Id=SH.ScreenId 
		 INNER JOIN [sSecurity].[tTask] ST ON ST.Id = SC.TaskId
		 INNER JOIN sCommon.tModuleMaster CM ON CM.Id = ST.ModuleId 
  WHERE   
            ((SH.ScreenId = @rScreenId) OR (@rScreenId = 0))
            AND ((ST.ModuleId  = @rModuleId) OR (@rModuleId = 0))
		    AND ((SC.Title=@rHelpDescription) Or (@rHelpDescription=''))
			AND SC.iSObsolete=0
	      order by SC.OrderIndex desc
	      
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pScreenMasterAdd]

	@rId int,
	@rTitle nvarchar(100),
	@rTaskId int,
	@rOrderIndex int,
	@rScreenGroupId int,
	@rPagePath nvarchar(500),
	@rIconPath nvarchar(200),
	@rIsObsolete bit,
	@rIsHideInScreen bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


IF(@rId=0)
BEGIN
	IF EXISTS(Select 1 from sSecurity.tScreen WHERE Title = @rTitle)
	BEGIN
			SELECT -103 AS Result
			RETURN
	END
END
ELSE
BEGIN
	IF EXISTS(Select 1 from sSecurity.tScreen WHERE Id<>@rId AND Title = @rTitle)
	BEGIN
			SELECT -103 AS Result
			RETURN
	END
END

BEGIN TRY
BEGIN TRANSACTION


IF EXISTS(SELECT 1 FROM sSecurity.tScreen WHERE Id = @rId)
BEGIN
	UPDATE sSecurity.tScreen
	SET
	Title = @rTitle,
	TaskId = @rTaskId,
	Page = @rPagePath,
	IsObsolete = @rIsObsolete,
	ScreenGroupId = @rScreenGroupId,
	IconPath = @rIconPath,
	IsHideInScreenGroup = @rIsHideInScreen
	WHERE Id = @rId
	SELECT 2 AS RESULT
END
ELSE
BEGIN
	INSERT INTO 
	sSecurity.tScreen 
	VALUES
	(@rId,
	@rTitle,
	NULL,
	@rTaskId,
	@rPagePath,
	@rIsObsolete,
	@rScreenGroupId,
	@rOrderIndex,
	NULL,
	@rIconPath,
	@rIsHideInScreen)
	SELECT 1 AS Result
END
COMMIT TRANSACTION		
END TRY
BEGIN CATCH 
ROLLBACK TRANSACTION
		SELECT -1 AS Result
		RETURN
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pScreenMasterGet]
	
	@rTaskId int = 0,
	@rModuleId int = 0,
	@rTitle nvarchar(100) = '',
	@rIsObsolete int = -1,
	@rIsHideInScreen int = -1,
	@rId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT
		M.Id AS ModuleId,
		T.Id AS TaskId, 
		S.Id AS ScreenId,
		ISNULL(SG.Id,0) AS ScreenGroupId,
		M.Title AS ModuleTitle,
		T.Title AS TaskTitle,
		S.Title AS ScreenTitle,
		S.Page AS PagePath,
		ISNULL(S.IconPath,'') As IconPath,
		SG.Title AS ScreenGroup,
		ISNULL(S.OrderIndex,'') AS OrderIndex,
		S.IsObsolete AS InActive,
		S.IsHideInScreenGroup AS IsHideInScreenGroup
	FROM 
		sSecurity.tScreen S
		INNER JOIN sSecurity.tTask T ON S.TaskId = T.Id
		LEFT JOIN sSecurity.tScreenGroupMaster SG ON S.ScreenGroupId = SG.Id
		INNER JOIN [sCommon].[tModuleMaster] M ON T.ModuleId = M.Id
	WHERE
		((@rTitle='' AND 0=0) OR (S.Title LIKE '%'+@rTitle+'%'))
		AND  (M.Id = @rModuleId OR @rModuleId=0)
		AND (T.Id = @rTaskId OR @rTaskId=0)
		AND (S.Id = @rId OR @rId=0)
		AND (S.IsObsolete = @rIsObsolete OR @rIsObsolete= -1)
		AND (S.IsHideInScreenGroup = @rIsHideInScreen OR @rIsHideInScreen= -1)
	ORDER BY M.Id,T.Id,S.Id,S.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pSecurityDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rOrgGroupId int=0,
	 @rSourceTypeId int=0,
	 @rDeptRole int =0,
	 @rDepartmentId int=0,
	 @rRoleId int =0,	
	 @rDivisionId int =0,
	 @rCommonOrgGroupBatchId int=0,
	 @rCount int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
	  BEGIN
		SELECT 
			O.Id AS OrgGroupId,O.Title AS OrgGroupName,COUNT(U.Id) AS UserCount  
			FROM sSecurity.tUser U
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
			--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE U.IsObsolete = 0
			--AND (U.CreatedUserId != 1 OR U.DisplayTitle = 'Admin')
			--AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
			AND(OM.Id !=1)
			GROUP BY O.Id,O.Title
	  END
  ELSE IF(@rType = 'TypeWiseUserSummary')
	BEGIN


		SELECT 
			0AS OrgGroupId,0 AS OrgGroupName,ISNULL(U.SourceTypeId,0) AS SourceTypeId,
			CASE WHEN U.SourceTypeId = 95 THEN  'Employee' 
		  WHEN U.SourceTypeId = 2003 THEN  'Student'    WHEN U.SourceTypeId = 1 THEN  'Other'     ELSE  'NA' END AS SourceType,
			
			COUNT(U.Id) AS UserCount  ,
			 
			
			Count(RU.UserId) AS RegisteredUsers,
			(COUNT(U.Id) - Count(RU.UserId))  AS UnRegisteredUsers
			FROM sSecurity.tUser U
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
			--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
			LEFT JOIN (
		SELECT RU.UserId AS  UserId  
		FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
		INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
			INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
		  AND(OM1.Id !=1)
			AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
		WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
			
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
			--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE U.IsObsolete = 0
			AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0))
			--AND (U.CreatedUserId != 1 OR U.DisplayTitle = 'Admin')
			--AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
			AND(OM.Id !=1)
			
			GROUP BY U.SourceTypeId


		--SELECT O.Id AS OrgGroupId,O.Title AS OrgGroupName,ISNULL(U.SourceTypeId,0) AS SourceTypeId,CASE WHEN U.SourceTypeId = 95 THEN  'Employee' 
		--WHEN U.SourceTypeId = 2003 THEN  'Student'    WHEN U.SourceTypeId = 1 THEN  'Other'     ELSE  'NA' END AS SourceType,
		--COUNT(U.Id) AS UserCount,COUNT(RU.UserId) AS RegisteredUsers,ISNULL(COUNT(U.Id) - COUNT(RU.UserId),0) AS UnRegisteredUsers
		--FROM sSecurity.tUser U
		----INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
		----INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
		--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
		--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		--LEFT JOIN (
		--SELECT RU.UserId AS UserId  
		--FROM sCommunication.tRegisteredUsers RU   
		--GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
		--WHERE (O.Id = @rOrgGroupId OR @rOrgGroupId=0) AND  U.IsObsolete = 0 --AND UR.IsObsolete=0
		--AND (U.CreatedUserId != 1 OR U.DisplayTitle = 'Admin')
		--AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
		--AND(OM.Id !=1)
		--GROUP BY O.Id,O.Title,U.SourceTypeId
	END
  ELSE IF(@rType = 'TypeDetailsUserSummary')
	BEGIN
		IF(@rSourceTypeId = 2003)
			BEGIN
				IF( @rCount=1)
					BEGIN
						SELECT DM.Id AS DivisionId,CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision
							,COUNT(U.Id) AS UserCount,	COUNT(U.Id) AS RegisteredUsers,
						COUNT(U.Id) AS UnRegisteredUsers	
						FROM sSecurity.tUser U
						INNER JOIN sStudent.vStudentLastAcademic A ON A.StudentId=U.SourceId AND U.SourceTypeId = 2003
						INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 

						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId  
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
						INNER JOIN ( 				
						SELECT RU.UserId AS  UserId  
						FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
						INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
						INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
						AND(OM1.Id !=1)
						AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
						WHERE U1.IsObsolete = 0 GROUP BY RU.UserId				
						) RU ON RU.UserId = U.Id 
						WHERE ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0
						AND(OM.Id !=1)
						GROUP BY CM.DisplayTitle,DM.DisplayTitle,DM.Id
					END
				ELSE
					BEGIN
						SELECT DM.Id AS DivisionId,CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision
						,COUNT(U.Id) AS UserCount,
						COUNT(U.Id) AS RegisteredUsers,
						COUNT(U.Id) AS UnRegisteredUsers						
						FROM sSecurity.tUser U
						INNER JOIN sStudent.vStudentLastAcademic A ON A.StudentId=U.SourceId AND U.SourceTypeId = 2003
						INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId  
						INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
						LEFT JOIN ( 
						SELECT RU.UserId AS  UserId  
						FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
						INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
						INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
						AND(OM1.Id !=1)
						AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
						WHERE U1.IsObsolete = 0 GROUP BY RU.UserId				
						) RU ON RU.UserId = U.Id 
						WHERE ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0
						AND(OM.Id !=1)
						AND RU.UserId is null
						GROUP BY CM.DisplayTitle,DM.DisplayTitle,DM.Id
					END
				
			END
		ELSE
			BEGIN
				IF(@rDeptRole = 1)
					BEGIN
						SELECT DM.Id AS DepatmentId,DM.Title AS DepatmentName ,COUNT(U.Id) AS UserCount,COUNT(RU.UserId) AS RegisteredUsers,
						ISNULL(COUNT(U.Id) - COUNT(RU.UserId),0) AS UnRegisteredUsers
						FROM sSecurity.tUser U
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
						
						LEFT JOIN ( 
						SELECT RU.UserId AS  UserId  
						FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
						INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
						INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
						AND(OM1.Id !=1)
						AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
						WHERE U1.IsObsolete = 0 GROUP BY RU.UserId				
						) RU ON RU.UserId = U.Id 
				
						WHERE ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0 
						AND(OM.Id !=1)
						GROUP BY U.SourceTypeId,DM.Title,DM.Id
					END
				ELSE
					BEGIN
						SELECT R.Id AS RoleId,R.Title AS RoleName,COUNT(U.Id) AS UserCount,COUNT(RU.UserId) AS RegisteredUsers,
						ISNULL(COUNT(U.Id) - COUNT(RU.UserId),0) AS UnRegisteredUsers
						FROM sSecurity.tUser U
						INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
						INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
						LEFT JOIN (SELECT RU.UserId AS UserId  
						FROM sCommunication.tRegisteredUsers RU   
						GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
						WHERE ((O.Id = @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0 AND UR.IsObsolete=0
						AND ((U.CreatedUserId != 1) OR (U.DisplayTitle = 'Admin'))
						AND ((U.SourceTypeId = 95)OR(95=0))
						AND(OM.Id !=1)
						AND ((COGBM.Id=@rCommonOrgGroupBatchId )OR(@rCommonOrgGroupBatchId=0 ))
						AND  ISNULL(EM.IsOtherUser,0) = 0
						GROUP BY R.Title,R.Id
					END
			END
	END
  ELSE IF(@rType = 'DetailsUserSummary')
	BEGIN
		IF(@rSourceTypeId = 2003)
			BEGIN
				IF(@rCount =1)
					BEGIN
							SELECT  SM.Code AS Id,SM.FirstName+' '+SM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS Contact
							,COUNT(U.Id) AS UserCount,
							COUNT(U.Id) AS RegisteredUsers,
							COUNT(U.Id) AS UnRegisteredUsers
							FROM sSecurity.tUser U
							INNER JOIN sStudent.vStudentLastAcademic A ON A.StudentId=U.SourceId AND U.SourceTypeId = 2003
									INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId 
									INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
									INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId  
									INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
							INNER JOIN ( 				
								SELECT RU.UserId AS  UserId  
									FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
									INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
									INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
									AND(OM1.Id !=1)
									AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
								WHERE U1.IsObsolete = 0 GROUP BY RU.UserId				
							) RU ON RU.UserId = U.Id 
							LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SM.Id
							WHERE ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0
							AND((A.DivisionId=@rDivisionId)OR(@rDivisionId=0))
							AND(OM.Id !=1)
							--AND RU.UserId is null
							GROUP BY SM.Code,SM.FirstName,SM.LastName,SC.ParentContactNo
					END
				ELSE
					BEGIN
						SELECT  SM.Code AS Id,SM.FirstName+' '+SM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS Contact
							,COUNT(U.Id) AS UserCount,
							COUNT(U.Id) AS RegisteredUsers,
							COUNT(U.Id) AS UnRegisteredUsers
							FROM sSecurity.tUser U
							INNER JOIN sStudent.vStudentLastAcademic A ON A.StudentId=U.SourceId AND U.SourceTypeId = 2003
									INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId 
									INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
									INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId  
									INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
							LEFT JOIN ( 				
								SELECT RU.UserId AS  UserId  
									FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
									INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
									INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
									AND(OM1.Id !=1)
									AND((O1.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
								WHERE U1.IsObsolete = 0 GROUP BY RU.UserId				
							) RU ON RU.UserId = U.Id 
							LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SM.Id
							WHERE ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0
							AND((A.DivisionId=@rDivisionId)OR(@rDivisionId=0))
							AND(OM.Id !=1)
							AND RU.UserId is null
							GROUP BY SM.Code,SM.FirstName,SM.LastName,SC.ParentContactNo
					END
			END
		ELSE
			BEGIN
				IF(@rDeptRole = 1)
					BEGIN						
						SELECT EM.Code AS Id,EM.FirstName+' '+EM.LastName AS Name,ISNULL(EC.MobileNumber,'') AS Contact
						,COUNT(U.Id) AS UserCount,COUNT(RU.UserId) AS RegisteredUsers,ISNULL(COUNT(U.Id) - COUNT(RU.UserId),0) AS UnRegisteredUsers
						FROM sSecurity.tUser U
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
						LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
						LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
						LEFT JOIN ( 				
						SELECT RU.UserId AS  UserId  
						FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
						INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
						INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
						AND(OM1.Id !=1)
						AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
						WHERE U1.IsObsolete = 0 GROUP BY RU.UserId				
						) RU ON RU.UserId = U.Id 				
						WHERE ((OM.OrgGroupId= @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0 
						AND((DM.Id=@rDepartmentId)OR(@rDepartmentId=0))					
						AND(OM.Id !=1) AND  ISNULL(EM.IsOtherUser,0) = 0
						GROUP BY EM.Code,EM.FirstName,EM.LastName,EC.MobileNumber
					END
				ELSE
					BEGIN
						SELECT EM.Code AS Id,EM.FirstName+' '+EM.LastName AS Name,ISNULL(EC.MobileNumber,'') AS Contact
						,COUNT(U.Id) AS UserCount,COUNT(RU.UserId) AS RegisteredUsers,ISNULL(COUNT(U.Id) - COUNT(RU.UserId),0) AS UnRegisteredUsers
						FROM sSecurity.tUser U
						INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
						INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95 AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
						LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
						
						LEFT JOIN ( 
						SELECT RU.UserId AS  UserId  
						FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
						INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
						INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
						AND(OM1.Id !=1)
						AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
						WHERE U1.IsObsolete = 0  GROUP BY RU.UserId				
						) RU ON RU.UserId = U.Id 
						
						
						WHERE ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0 AND UR.IsObsolete=0						
						AND((R.Id=@rRoleId)OR(@rRoleId=0))
						AND(OM.Id !=1)
						GROUP BY EM.Code,EM.FirstName,EM.LastName,EC.MobileNumber
					END
			END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 
CREATE OR ALTER PROCEDURE [sSecurity].[pSecuritySummaryDashboard]
	@rType nvarchar(40)='',
	@rOrgId int =0,
	@rOrgGroupId int =0,
	@rOrgGroupBatchId int=0,
	@rDepositHeadId int =0,
	--@rLibraryId int =0
	@rBatchId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'SecurityList')
		BEGIN
				SELECT 
				CASE WHEN U.SourceTypeId = 95 THEN  'Employee' 
				WHEN U.SourceTypeId = 2003 THEN  'Student' ELSE  'NA' END AS 'Source Type',

				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND((OM.Id =  @rOrgId)OR(@rOrgId=0)) AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) WHEN U.SourceTypeId = 95 THEN ISNULL(COUNT(U.Id),0) END AS 'Created User',

				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL((SELECT COUNT(ISNULL(U.Id,0)) FROM sStudent.vStudentCommunication SC LEFT JOIN  sSecurity.tUser U ON SC.StudentId = U.SourceId AND U.SourceTypeId=2003
            	WHERE ((U.LoginPassWord is Null)) AND (SC.OrgId = @rOrgId) AND SC.StatusId = 1 AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0))),0) WHEN U.SourceTypeId = 95 THEN ISNULL((SELECT COUNT(ISNULL(U.Id,0)) FROM sHrm.vEmployeeCommunication EC LEFT JOIN  sSecurity.tUser U ON EC.EmployeeId = U.SourceId
            	WHERE ((U.LoginPassWord is Null)) AND (EC.OrgId = @rOrgId) AND EC.StatusId = 7),0) ELSE 0 END As 'Pending User' ,

				CASE WHEN U.SourceTypeId = 2003 THEN  ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND ((OM1.Id =  @rOrgId)OR(@rOrgId=0)) AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1),0) WHEN U.SourceTypeId = 95 THEN ISNULL(COUNT(RU.UserId),0) END  AS 'Registered',

				 
				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND((OM.Id =  @rOrgId)OR(@rOrgId=0)) AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003 AND A.UserId IS NULL),0) WHEN U.SourceTypeId = 95 THEN ISNULL((COUNT(U.Id) - COUNT(RU.UserId)),0) END AS 'Not Registered',

				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL(Convert(decimal(10,2),((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND ((OM1.Id =  @rOrgId)OR(@rOrgId=0)) AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1)*100)/(SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND((OM.Id =  @rOrgId)OR(@rOrgId=0)) AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003)),0.00)
				WHEN U.SourceTypeId = 95 THEN ISNULL(Convert(decimal(10,2),(COUNT(RU.UserId)*100)/COUNT(U.Id)),0.00) END AS Percentage

				FROM
				 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
				LEFT JOIN (
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND ((OM1.Id =  @rOrgId)OR(@rOrgId=0))
				AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				 
				WHERE U.IsObsolete = 0
				AND((OM.Id =  @rOrgId)OR(@rOrgId=0))
				AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1)
				GROUP BY U.SourceTypeId
		END
		 ELSE IF (@rType = 'StudentRegisteredUsers')
			BEGIN
				SELECT CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision
				,COUNT(U.Id) AS UserCount,	COUNT(RU.UserId) AS RegisteredUsers
				,(COUNT(U.Id)-COUNT(RU.UserId)) As NotRegister
				FROM  sStudent.vStudentCommunication SC
				INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId AND U.SourceTypeId = 2003
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId  
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
				LEFT JOIN ( 				
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1)AND((OM1.Id =  @rOrgId)OR(@rOrgId=0))
				AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId				
				) RU ON RU.UserId = U.Id 
				WHERE ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0)) AND SC.StatusId = 1
				AND(OM.Id !=1) AND ((OM.Id = @rOrgId) OR (@rOrgId=0)) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) 
				GROUP BY CM.OrderIndex, DM.OrderIndex,CM.DisplayTitle,DM.DisplayTitle,DM.Id--Changed For mantis : 35931 by Nilesh
				Order By CM.OrderIndex, DM.OrderIndex --Added For mantis : 35931 by Nilesh
			END
			ELSE IF (@rType = 'EmployeeRegisteredUsers')
				BEGIN
					SELECT R.Title AS RoleName,COUNT(U.Id) AS UserCount,COUNT(RU.UserId) AS RegisteredUsers,
						(COUNT(U.Id)- COUNT(RU.USerId)) AS NotRegisterUsers
						FROM sSecurity.tUser U
						INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
						INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId AND R.Title != 'SuperAdmin'
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
						--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
						--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
						LEFT JOIN (SELECT RU.UserId AS UserId  
						FROM sCommunication.tRegisteredUsers RU   
						GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
						WHERE ((O.Id = @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0 AND UR.IsObsolete=0
						AND ((U.CreatedUserId != 1) OR (U.DisplayTitle = 'Admin'))
						AND ((U.SourceTypeId = 95)OR(95=0))
						AND(OM.Id !=1) AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
						--AND ((COGBM.Id=1 )OR(1=0 ))
						GROUP BY R.Title,R.Id
				END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pStudentDashletDefaultPermissionAdd]
	
	@rRoleDashletImpXml [nvarchar](max),
	@rOrgId int,
	@rRoleId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

		DECLARE @loDoc INT
		EXEC sp_xml_preparedocument @loDoc OUTPUT, @rRoleDashletImpXml

		CREATE TABLE #UserTmp
		(
		  UserId bigint
		)
		INSERT INTO #UserTmp (UserId)
		SELECT 
			Users.Id
		FROM sSecurity.tUser Users			
		INNER JOIN sSecurity.tUserRole UR ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId)
		WHERE (Users.OrgId = @rOrgId) 

		CREATE TABLE #DashletTmp
		(
		  DashletId int
		)

		INSERT INTO #DashletTmp
		(
			DashletId
		)
		SELECT
			DashletId
		FROM OPENXML (@loDoc, '/Table/RolewiseDashlet', 1)
		WITH 
		( 
			DashletId int
		) 
		CREATE TABLE #UserDashlet
		(
			UserId bigint,
			DashletId int
		)
		
		INSERT INTO #UserDashlet
		(
			UserId,
			DashletId
		)
		SELECT 
			U.UserId,D.DashletId 
		FROM #UserTmp U 
		CROSS APPLY #DashletTmp D
		

		--SELECT * FROM  #UserTmp
	 --   SELECT * FROM  #DashletTmp
	 --   SELECT * FROM  #UserDashlet

		DELETE UD FROM sSecurity.tUserDashlet UD INNER JOIN #UserDashlet UD1 ON UD.UserId = UD1.UserId 
		
		IF NOT EXISTS(SELECT 1 FROM #DashletTmp WHERE DashletId =0)
			BEGIN
					INSERT INTO sSecurity.tUserDashlet
					(
						UserId,
						DashletId
					)
					SELECT 
						U.UserId,U.DashletId 
					FROM #UserDashlet U
			END

		
	
		DROP TABLE #UserTmp
	    DROP TABLE #DashletTmp
	    DROP TABLE #UserDashlet

	    SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pStudentPasswordAdd]
	
	@rId bigint,
	@rStudentId bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rName nvarchar(100),
	@rEmailId nvarchar(100),
	@rMobileNo nvarchar(20),
	@rUserName nvarchar(100),
	@rLoginPassword nvarchar(100),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rIsFullUpdate bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	  
	
		IF(@rId = 0)	
		BEGIN
			IF(@rStudentId <> 0)
			BEGIN
				IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceTypeId = 2003 AND SourceId = @rStudentId AND OrgId=@rOrgId)
				BEGIN
					SELECT -101 AS UserId
					RETURN
				END
			END
		
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rUserName AND OrgId = @rOrgId)
			BEGIN
				SELECT -101 AS UserId
				RETURN
			END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rUserName AND OrgId = @rOrgId AND Id<>@rId)
			BEGIN
				SELECT -101 AS UserId
				RETURN
			END
		END
	  
		DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserSourceId=@rStudentId AND UserSourceTypeId = 2003
	 
	 DECLARE @lCurrentDateTime DATETIME
	 EXECUTE @lCurrentDateTime = sCommon.fGetDate
	 --IF(@rIsFullUpdate=0)
	 --BEGIN
	 --UPDATE sStudent.tStudentCommunication
  --   SET
		--ParentContactNo=@rMobileNo,
		--ParentEmail=@rEmailId,
		--UpdatedUserId=@rCreatedUserId,
		--UpdatedDateTime=@lCurrentDateTime
  --    WHERE (StudentId = @rStudentId) 
	 -- SELECT 1 AS Result
  --    RETURN
  --   END
     
     BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
--SELECT @rId = ID FROM sSecurity.tUser WHERE SourceId = @rStudentId And SourceTypeId = 2003
     
IF NOT EXISTS( SELECT 1 FROM sSecurity.tUser WHERE SourceId = @rStudentId And SourceTypeId = 2003 And OrgId = @rOrgId)	
BEGIN
	
	DECLARE @lNextNumber BIGINT	
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sSecurity.tUser
		(
			Id,		
			DisplayTitle,
			LoginTitle,
			LoginPassword,
			LastLockOutDate,
			NumberOfLogonAttempt,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			SourceTypeId,
			SourceId
        )
	VALUES
		(
			@lNextNumber,
			@rName,					
			@rUserName,
			@rLoginPassword,
			@lCurrentDateTime,
			0,
			@rIsObsolete,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rOrgId,
			2003,
			@rStudentId
		)
		
		INSERT INTO sSecurity.tUserRole
		(
			RoleId,
			UserId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsPrimary
		)
		VALUES
		(
			sCommon.fGetIntIdForOrg(22,@rOrgGroupId),
			@lNextNumber,
			@rIsObsolete,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rCreatedUserId,
			@lCurrentDateTime,
			1
		)
		    
	END	 
	 ELSE
	 BEGIN
	 
	 --UPDATE sStudent.tStudentCommunication
  --   SET
		--ParentContactNo=@rMobileNo,
		--ParentEmail=@rEmailId,
		--UpdatedUserId=@rCreatedUserId,
		--UpdatedDateTime=@lCurrentDateTime
  --    WHERE (StudentId = @rStudentId) 
	 
	 SET @lNextNumber = @rId
	    UPDATE  sSecurity.tUser
	    SET
			LoginTitle=@rUserName,
			LoginPassword=@rLoginPassword,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=@lCurrentDateTime
	      WHERE (Id = @rId) 
	 END  
		SELECT @lNextNumber AS Result
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pStudentPasswordGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,
	@rIsPendingLogin  bit,
	@rIsCreatedLogin bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			ISNULL(U.Id,0) AS Id,
			A.StudentId,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassName,
			A.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			STM.Title AS Status
	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=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 SM.OrgId = OM.Id	
	        LEFT JOIN sSecurity.tUser U ON U.SourceId=SC.StudentId AND U.SourceTypeId=2003 
	        INNER JOIN sStudent.tStatusMaster STM ON STM.Id = SM.StatusId 
	WHERE 
			((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND	(A.OrgId = @rOrgId)
		AND	(A.BatchId = @rBatchId)
		AND SM.StatusId = 1
		AND ((U.LoginPassWord is Null AND @rIsPendingLogin=1) OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
		Order By A.RollNo
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pTallyPermissionGet]
    @rOrgGroupId SMALLINT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;

BEGIN
	SELECT 
		MM.Id AS ModuleId,
		MM.Title AS ModuleName,
		(CASE WHEN MP.ModuleId IS NULL THEN 'False'	ELSE 'True' END) AS Selected,
		ISNULL(MP.OrgGroupId,0) AS OrgGroupId,
		(CASE WHEN MM.IsObsolete = 0 THEN 'Active'	ELSE 'Inactive' END) AS Mode   
	FROM 
		sCommon.tModuleMaster MM
		LEFT JOIN sSecurity.tmodulepermission MP ON MP.ModuleId = MM.Id AND MP.OrgGroupId = @rOrgGroupId
	WHERE 
		(MM.IsObsolete = 0)
		AND MM.Id = 227
	ORDER BY 
		MM.Title
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sSecurity].[pTaskGet]
	@rModuleID [smallint],
	@rRoleID [bigint],		
	@rResourceTypeId smallint,
	@rOrgGroupId int,
	@rUserId bigint=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	 IF @lConfigValue = ''
		SET @lConfigValue = 'False'
		
	Print	@lConfigValue
IF(@rUserId=0)
BEGIN
	 IF(@lConfigValue = 'True')
	 BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tAssignSubRole WHERE SubRoleId = @rRoleID)
		BEGIN
			 Print 1
			SELECT * INTO #TmpTable 
			FROM (
			SELECT DISTINCT(TaskId)
			FROM sSecurity.tPermission 
			WHERE RoleId IN (SELECT RoleId FROM sSecurity.tAssignSubRole WHERE SubRoleId = @rRoleID) AND OrgGroupId = @rOrgGroupId) AS T

			SELECT  T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
			FROM sSecurity.tTask T
			INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
			INNER JOIN sSecurity.tResourceTypeMaster RTM
			ON RTM.Id=T.ResourceTypeId
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
			LEFT OUTER JOIN sSecurity.tPermission P ON T.Id = P.TaskId AND (P.RoleId = @rRoleID OR P.RoleId IS NULL)
			INNER JOIN #TmpTable Tmp ON T.Id = Tmp.TaskId 
			INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId	
			WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
					T.IsObsolete = 0 
					AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
					ORDER BY T.ModuleId,RTM.Id
		END
		ELSE
		BEGIN

			SELECT  T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
			FROM sSecurity.tTask T
			INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
			INNER JOIN sSecurity.tResourceTypeMaster RTM
			ON RTM.Id=T.ResourceTypeId
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
			LEFT OUTER JOIN sSecurity.tPermission P
				ON T.Id = P.TaskId AND (P.RoleId = @rRoleID OR P.RoleId IS NULL)
			INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId	
			WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
					T.IsObsolete = 0 
					AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
					ORDER BY T.ModuleId,RTM.Id
		END
	 END
	 ELSE IF(@lConfigValue = 'False')
	 BEGIN
	 
				SELECT  T.Id,
						T.Title,
						MM.Title AS ModuleName,
						RTM.Title AS ResourceTypeName, 			
						CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
						CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
						CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
						CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
						CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
						CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
						CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
						CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
						CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
						CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
						CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
						CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
						CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
						CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
				INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
				INNER JOIN sSecurity.tResourceTypeMaster RTM
				ON RTM.Id=T.ResourceTypeId
				INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
				LEFT OUTER JOIN sSecurity.tPermission P
					ON T.Id = P.TaskId AND (P.RoleId = @rRoleID OR P.RoleId IS NULL)
				INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId	
				WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
						T.IsObsolete = 0 
						AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
						ORDER BY T.ModuleId,RTM.Id
		END
END 
ELSE		 
	BEGIN
	       SELECT  T.Id,
				    T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
			FROM sSecurity.tTask T
			INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
			INNER JOIN sSecurity.tResourceTypeMaster RTM
			ON RTM.Id=T.ResourceTypeId
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
			LEFT OUTER JOIN sSecurity.tPermissionUser P
				ON T.Id = P.TaskId AND (P.UserId = @rUserId OR P.UserId IS NULL)
			WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
					T.IsObsolete = 0 
					AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
					ORDER BY T.ModuleId,RTM.Id
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EXEC [sSecurity].[pTaskMasterGet] 0,''    
CREATE OR ALTER PROCEDURE [sSecurity].[pTaskMasterGet]
     @rId int,
	 @rModuleId int = 0,    
	 @rResourceTypeId int = 0, 
	 @rIsObsolete int = -1,
	 @rIsClientSpecific int = -1,
     @rTitle nvarchar(100)=''      	       	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
    SELECT (M.Id) AS [Id],
           (M.Title) AS [Title],
           (M.TitleResourceKeyId) AS [TitleResourceKeyId],
            M.IsObsolete,
            M.ModuleId,
            M.AvailablePermission,
            M.OrderIndex,
            M.ResourceTypeId,
            M.IsClientSpecific,
            M.RoleScopeId,
            CAST(ISNULL((M.AvailablePermission & 1), 0) AS BIT) AS [Create],
            CAST(ISNULL((M.AvailablePermission & 2)/2, 0) AS BIT) AS [Read],
            CAST(ISNULL((M.AvailablePermission & 4)/4, 0) AS BIT) AS [Update],
            CAST(ISNULL((M.AvailablePermission & 8)/8, 0) AS BIT) AS [Delete],
            CAST(ISNULL((M.AvailablePermission & 16)/16, 0) AS BIT) AS [Search],
            CAST(ISNULL((M.AvailablePermission & 32)/32, 0) AS BIT) AS [Print],
            CAST(ISNULL((M.AvailablePermission & 64)/64, 0) AS BIT) AS [Execute],
            (RM.Title) AS ResourceTypeTitle,
            MM.Title AS ModuleTitle,
            CASE 
              WHEN M.RoleScopeId =0 THEN 'Both'
              WHEN M.RoleScopeId =1 THEN 'Employee'
              WHEN M.RoleScopeId =2 THEN 'Student'
            ELSE ''
            END AS RoleScopeType
            
           
    FROM sSecurity.tTask M
            LEFT JOIN sSecurity.tResourceTypeMaster RM ON RM.Id=M.ResourceTypeId
            LEFT JOIN sCommon.tModuleMaster MM ON MM.Id=M.ModuleId
    WHERE 
            ((@rTitle='' AND 0=0) OR (M.Title LIKE '%'+@rTitle+'%')) 
            AND	((M.Id = @rId) OR (@rId = 0))
			AND  (MM.Id = @rModuleId OR @rModuleId=0)
			AND  (RM.Id = @rResourceTypeId OR @rResourceTypeId=0)
			AND (M.IsObsolete = @rIsObsolete OR @rIsObsolete= -1)
		AND (M.IsClientSpecific = @rIsClientSpecific OR @rIsClientSpecific= -1)
    ORDER BY M.Id       
   	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pTaskMasterManage]
     @rId int=0,     
     @rTitle nvarchar(100), 
     @rTitleResourceKeyid int=0, 
     @rIsObsolete bit=0,
     @rModuleId int,
     @rAvailablePermission int,
     @rOrderNumber smallint,
     @rResourceTypeId int,
     @rIsClientSpecific bit=0,
     @rRoleScopeId int=0,     
     @rStatus varchar(1)
      	       	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY

IF(@rStatus = 'A')	
	BEGIN
	
	IF NOT EXISTS (SELECT Id from sSecurity.tTask where Title =@rTitle)	
	
	BEGIN	
		
		Declare @MaxId Int 
		SET @MaxId=(SELECT MAX(id) as Id FROM sSecurity.tTask)
		SET @MaxId=@MaxId + 1
		
		INSERT INTO sSecurity.tTask
			(			
				 Id,				 
				 Title,
				 TitleResourceKeyId,
				 IsObsolete,
				 ModuleId,
				 AvailablePermission,
				 OrderIndex,
				 ResourceTypeId,
				 IsClientSpecific,
				 RoleScopeId
				
			)
		VALUES
			(			 
				 @MaxId, 
				 @rTitle , 
				 @rTitleResourceKeyid , 
				 @rIsObsolete , 
				 @rModuleId , 
				 @rAvailablePermission,
				 @rOrderNumber ,			  
				 @rResourceTypeId,
				 @rIsClientSpecific,
				 @rRoleScopeId
			)
		SELECT 1 AS Result
	  END
	  ELSE
	  BEGIN
	    SELECT -103 AS Result
	  END
	  
	END	 

ELSE IF (@rStatus = 'U')
	 BEGIN

	 IF NOT EXISTS (SELECT Id from sSecurity.tTask where Title =@rTitle and Id<>@rId)	
	  BEGIN

	    UPDATE  sSecurity.tTask
	    SET	        
			Title=@rTitle,
			TitleResourceKeyId=@rTitleResourceKeyid,
			IsObsolete=@rIsObsolete,
			ModuleId=@rModuleId,
			AvailablePermission=@rAvailablePermission,
			OrderIndex=@rOrderNumber,
			ResourceTypeId=@rResourceTypeId,
			IsClientSpecific=@rIsClientSpecific,
			RoleScopeId=@rRoleScopeId
						
	      WHERE Id = @rId
	    SELECT 2 AS Result
	 
	   END
	  ELSE
	  BEGIN
	   SELECT -103 AS Result
	  END 
	 END 
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pTaskPermissionGet]
	
	@rModuleId smallint,
	@rResourceTypeId smallint,
	@rTaskId smallint,		
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL)
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId 
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
			LEFT JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id 
				AND OT.OrgGroupId = @rOrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId		
		ORDER BY 			
			T.ModuleId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pTaskPermissionsGet_delete]
	@rUserId [int],
	@rTaskXML [nvarchar](2000),
	@rIsType [bit]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rTaskXML

BEGIN
	SELECT	TP.TaskId,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
	FROM
	(
		SELECT 	TaskId,
				RoleId,
				(Permission & 1) AS C,
				(Permission & 2)/2 AS R,
				(Permission & 4)/4 AS U,
				(Permission & 8)/8 AS D,
				(Permission & 16)/16 AS S,
				(Permission & 32)/32 AS P,
				(Permission & 64)/64 AS X
		FROM sSecurity.tPermission
		WHERE TaskId IN 
			(	SELECT TaskID FROM
				OPENXML (@loDoc, '/Tasks/Task', 2)
				WITH (	ID SMALLINT )
			) AND 
			  RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId)
	) TP
	GROUP BY TP.TaskId
END
EXEC sp_xml_removedocument @loDoc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pTeacherSubjectDivisionWiseUserAccess]	
	 @rOrgId int,	 
	 @rStatus bit,
	 @rRoleId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		
BEGIN 
IF(@rStatus=1)
BEGIN
	SELECT distinct
		2005 AS SourceTypeId,
		DM.Id AS SourceId,
		OM.DisplayTitle +' - '+ CM.Title +' - '+DM.Title AS SourceName,
		EE.EmployeeId,
		EE.EmployeeName,
		EE.EmployeeCode,
		U.Id As UserId,
		U.LoginTitle AS UserName,
		CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
		
	FROM sAcademic.tTeacherSubjectDivision TSD 
		INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id  
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
		INNER JOIN sHrm.vExtEmployee EE ON EE.EmployeeId = TSD.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
		INNER JOIN sSecurity.tUser U ON U.SourceId= EE.EmployeeId
		INNER JOIN sSecurity.tUserRole UR ON UR.UserId=U.Id AND UR.IsObsolete=0 
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM.Id AND UA.SourceTypeId=2005 AND ((UA.UserId=U.Id) OR (U.Id=0))
		
	WHERE 	 
		OM.Id = @rOrgId AND 
		StatusId =7
		 And U.SourceTypeId=95 
		 AND UR.RoleId=@rRoleId	
		 
	END
ELSE
BEGIN
	SELECT 		
			2005 AS SourceTypeId,
			--UM.SourceTypeId,
			DM.Id AS SourceId,
			OM.DisplayTitle +' - '+ CM.Title +' - '+DM.Title AS SourceName,			
			DM.InchargeEmployeeId AS EmployeeId,
			ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,
		    EM.Code AS EmployeeCode,
		    U.Id As UserId,
		    U.LoginTitle AS UserName,
		    CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
	  FROM 
		   sSetup.tDivisionMaster DM
		   INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
		   INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId AND EM.IsObsolete = 0
		   INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id = DM.OrgId
		   INNER JOIN sSecurity.tUser U ON U.SourceId= EM.Id
		   INNER JOIN sSecurity.tUserRole UR ON UR.UserId=U.Id AND UR.IsObsolete=0 
		   LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM.Id AND UA.SourceTypeId=2005 AND ((UA.UserId=U.Id) OR (U.Id=0))
		   WHERE DM.OrgId=@rOrgId And U.SourceTypeId=95 AND UR.RoleId=@rRoleId
		   order by DM.OrderIndex asc	
END	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pTempAppModulePermissionReset]
          
            @rOrgGroupId smallint
       
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	
	BEGIN TRANSACTION	
	
	DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId=@rOrgGroupId
	
	BEGIN
		INSERT INTO sSecurity.tModulePermission 
		SELECT @rOrgGroupId,Id FROM sCommon.tModuleMaster WHERE IsObsolete=0 
		AND Id IN
		(
		SELECT DISTINCT ModuleId FROM sSecurity.tTask WHERE 
		Id IN(20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,30228,20693,20692,20241,20563,20561,30249,
			  20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,139,20175,20176,
			  141,142,20158,30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962)
		)	
	END
	SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pTempUserBulkAdd]
    @rXmldoc [nvarchar](max),
    @OrgGroupId smallint,
    @CreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
  BEGIN TRY

DECLARE @lInterrorCode INT,	@intDoc INT
		
BEGIN TRANSACTION
			
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	DELETE T
	   FROM sSecurity.tTempUser T
	     INNER JOIN sSecurity.tUser U ON T.UserId=U.Id
	     INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
	WHERE OM.OrgGroupId = @OrgGroupId
		
	INSERT INTO sSecurity.tTempUser
	SELECT
		UserId,
		UserName,
		sSetup.fPortalXMLTagsReplaceReverse(UserPassword),
		@CreatedUserId,
		getdate()
	FROM OPENXML (@intDoc, '/Table/TempUser', 1)
	WITH
	( 		
		UserId bigInt '@UserId',
		UserName nvarchar(100) '@UserName',
		UserPassword nvarchar(100) '@UserPassword'		
	) 
	
COMMIT TRANSACTION			
	
  SELECT 1 As Result

END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pTimePolicyAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rAccessTime nvarchar(200),
        @rRemark nvarchar(300),
        @rIsObsolete bit,
        @rCreatedUserId bigint,
        @rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		IF EXISTS (SELECT 1 FROM sSecurity.tTimePolicy WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		BEGIN SELECT -101 AS Result RETURN END 
	END
	ELSE
	BEGIN
		IF EXISTS (SELECT 1 FROM sSecurity.tTimePolicy WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		BEGIN SELECT -101 AS Result RETURN END
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber int 

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sSecurity.tTimePolicy', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sSecurity.tTimePolicy
		(Id,Title,AccessTime,Remark,IsObsolete,CreatedUserId,CreatedDateTime,OrgGroupId)
	VALUES
		(@lNextNumber,@rTitle,@rAccessTime,@rRemark,@rIsObsolete,@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId)
		SELECT 1 AS Result
	END	 
	ELSE
	BEGIN
	SET @lNextNumber = @rId
	UPDATE sSecurity.tTimePolicy
	SET Title=@rTitle,AccessTime = @rAccessTime, Remark=@rRemark,IsObsolete=@rIsObsolete,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=sCommon.fGetDate()
	WHERE Id = @rId AND OrgGroupId= @rOrgGroupId
	SELECT 11 AS Result
	END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pTimePolicyGet]

	@rId int,
	@rTitle nvarchar(100),
	@rOrgGroupId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	SELECT 
			TP.Id,TP.Title,ISNULL(TP.AccessTime,'') AS AccessTime,TP.Remark,TP.IsObsolete,TP.OrgGroupId
	FROM 
			sSecurity.tTimePolicy TP
	WHERE 
		(TP.OrgGroupId = @rOrgGroupId)
		AND	((TP.Id = @rId) OR (@rId = 0))
		AND ((TP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pTraceabilityTrackAdd]

@rScreenId int,
@rTraceabilityId int,
@rTraceabilitySourceId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS(Select 1 from sSecurity.tTraceabilityTrack WHERE ScreenId = @rScreenId AND TraceabilityId=@rTraceabilityId AND TraceabilitySourceId=@rTraceabilitySourceId)
BEGIN
	    SELECT -103 AS Result
		RETURN
END

BEGIN TRANSACTION
BEGIN
	INSERT INTO 
		sSecurity.tTraceabilityTrack
		VALUES
		(@rScreenId,
		@rTraceabilityId,
		@rTraceabilitySourceId)
        SELECT 1 AS Result
		END
COMMIT TRANSACTION		
--END TRY
--BEGIN CATCH 
--ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--		RETURN
--	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE OR ALTER PROCEDURE [sSecurity].[pTraceabilitytrackGet]

	@rId int = 0,
	@rScreenId int = 0,
	@rTraceabilityId int = 0,
	@rModuleId int =0	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
		TT.ScreenId,
		TM.Title AS Traceability,
		M.Title AS Module,
		CASE 
			WHEN(TT.TraceabilityId = 1) THEN C.ItemKey
			WHEN (TT.TraceabilityId = 2) THEN E.Title
			WHEN(TT.TraceabilityId = 3) THEN ST.Title
		END AS SourceData,
		S.Title AS ScreenTitle,
		TT.TraceabilityId,
		TT.TraceabilitySourceId
	
	FROM 
		sSecurity.tTraceabilityTrack TT		
		INNER JOIN sSecurity.tTraceabilityMaster TM on TM.Id=TT.TraceabilityId
		INNER JOIN sSecurity.tScreen S ON S.Id = TT.ScreenId
		INNER JOIN sSecurity.tTask T ON T.Id = S.TaskId 
		INNER JOIN sCommon.tModuleMaster M ON M.Id =T.ModuleId
		LEFT JOIN sConfig.tConfigurationMaster  C on C.Id=TT.TraceabilitySourceId
		LEFT JOIN sAlert.tEventMaster E on E.Id=TT.TraceabilitySourceId
		LEFT JOIN sSecurity.tTask  ST on ST.Id=TT.TraceabilitySourceId
	WHERE 
		T.IsObsolete=0  
		AND (TT.ScreenId = @rScreenId OR @rScreenId = 0)
		AND  (TT.TraceabilityId = @rTraceabilityId OR @rTraceabilityId = 0)
		AND  (M.Id= @rModuleId OR @rModuleId  = 0)
	ORDER BY 
		 M.Id,T.Id,TT.ScreenId,TT.TraceabilityId


END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sSecurity].[pUserAccessAdd]
	
	@rSourceTypeId smallint, 
	@rSourceId int,
	@rUserId bigint,
	@rIsObsolete bit
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	IF(@rIsObsolete = 0)
	BEGIN
		DELETE FROM sSecurity.tUserAccess WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND UserId=@rUserId
	END
	ELSE IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserAccess WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND UserId=@rUserId)
	BEGIN
		INSERT INTO sSecurity.tUserAccess
		(
			SourceTypeId,
			SourceId,
			UserId
		)
		VALUES
		(
			@rSourceTypeId,
			@rSourceId,
			@rUserId
		)
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserAccessDelete]
	
	@rSourceTypeId smallint, 
	@rSourceId int,
	@rUserId bigint,
	@rIsObsolete bit
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	IF(@rIsObsolete = 0)
	BEGIN
		DELETE FROM sSecurity.tUserAccess WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND UserId=@rUserId
	END
	ELSE IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserAccess WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND UserId=@rUserId)
	BEGIN
		INSERT INTO sSecurity.tUserAccess
		(
			SourceTypeId,
			SourceId,
			UserId
		)
		VALUES
		(
			@rSourceTypeId,
			@rSourceId,
			@rUserId
		)
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserAccessGet]
	 
	@rUserId bigint,	
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	IF(@rUserId<>0)
	BEGIN
	SELECT * FROM (
	SELECT
				113 AS SourceTypeId,
				AM.Id AS SourceId,
				AM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sAccounting.tAccountMaster AM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=AM.Id AND UA.SourceTypeId=113 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		AM.OrgGroupId=@rOrgGroupId
		
	UNION ALL	
		
	SELECT
				2019 AS SourceTypeId,
				PM.Id AS SourceId,
				PM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sPayroll.tPayrollMaster PM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=PM.Id AND UA.SourceTypeId=2019 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		PM.OrgGroupId=@rOrgGroupId	
		
		
	UNION ALL
	
	SELECT
				1014 AS SourceTypeId,
				SLM.Id AS SourceId,
				SLM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sIp.tStoreLocationMaster SLM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=SLM.Id AND UA.SourceTypeId=1014 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		SLM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2011 AS SourceTypeId,
				LM.Id AS SourceId,
				LM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sLibrary.tLibraryMaster LM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=LM.Id AND UA.SourceTypeId=2011 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		LM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2012 AS SourceTypeId,
				DBM.Id AS SourceId,
				DBM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sEExam.tDataBankMaster DBM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=DBM.Id AND UA.SourceTypeId=2012 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		DBM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2013 AS SourceTypeId,
				RBM.Id AS SourceId,
				RBM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sFee.tReceiptBookMaster RBM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		RBM.OrgGroupId=@rOrgGroupId
		
	UNION ALL
	
	SELECT
				2018 AS SourceTypeId,
				CRBM.Id AS SourceId,
				CRBM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sFee.tChargeReceiptBookMaster CRBM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=CRBM.Id AND UA.SourceTypeId=2018 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		CRBM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2014 AS SourceTypeId,
				HM.Id AS SourceId,
				HM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sHostel.tHostelMaster HM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=HM.Id AND UA.SourceTypeId=2014 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		HM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2022 AS SourceTypeId,
				TM.Id AS SourceId,
				TM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sTransport.tTransportMaster TM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=TM.Id AND UA.SourceTypeId=2022 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		TM.OrgGroupId=@rOrgGroupId	
		
		
		UNION ALL
			
	SELECT
				2017 AS SourceTypeId,
				DM.Id AS SourceId,
				OM.DisplayTitle + ' - ' + DM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sSetup.tDepartmentMaster DM INNER JOIN sSetup.tOrganizationMaster OM
			ON DM.OrgId = OM.Id
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM.Id AND UA.SourceTypeId=2017 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		DM.OrgId IN (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	
	
	UNION ALL
		
		SELECT
				2023 AS SourceTypeId,
				TS.Id AS SourceId,
				TS.Title  AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sTimetable.tTimeTableSchema TS 
			LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=TS.Id AND UA.SourceTypeId=2023 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		TS.OrgGroupBatchId = @rOrgGroupBatchId
		
		
		UNION ALL
	
	SELECT
				2026 AS SourceTypeId,
				CM.Id AS SourceId,
				CM.Title AS SourceName,
				CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
				0 AS OrderIndex
	FROM
			sCanteen.tCanteenMaster CM
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=CM.Id AND UA.SourceTypeId=2026 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
	WHERE
		CM.OrgGroupId=@rOrgGroupId
		
	UNION ALL
	
	SELECT
		2005 AS SourceTypeId,
		DM.Id AS SourceId,
		OM.DisplayTitle +' - '+ CM.Title +' - '+DM.Title AS SourceName,
		CASE WHEN UA.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete,
		CONVERT(bigint,CONVERT(nvarchar(100),ISNULL(OM.OrderIndex,0))+CONVERT(nvarchar(100),ISNULL(CM.OrderIndex,0))+CONVERT(nvarchar(100),ISNULL(DM.OrderIndex,0))) AS OrderIndex
	FROM
		sSetup.tClassMaster CM
		INNER JOIN sSetup.tDivisionMaster DM  ON CM.Id = DM.ClassId
		INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id = DM.OrgId
		LEFT JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM.Id AND UA.SourceTypeId=2005 AND ((UA.UserId=@rUserId) OR (@rUserId=0))
		WHERE DM.OrgId IN (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)	
		AND DM.IsObsolete = 0
	) A
	ORDER BY SourceTypeId,OrderIndex
	END		
	
	IF(@rUserId=0)
	BEGIN
	SELECT * FROM (
	SELECT
				113 AS SourceTypeId,
				AM.Id AS SourceId,
				AM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sAccounting.tAccountMaster AM
	WHERE
			AM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL	
		
	SELECT
				2019 AS SourceTypeId,
				PM.Id AS SourceId,
				PM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sPayroll.tPayrollMaster PM
	WHERE
		PM.OrgGroupId=@rOrgGroupId	
		
		
	UNION ALL
	
	SELECT
				1014 AS SourceTypeId,
				SLM.Id AS SourceId,
				SLM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sIp.tStoreLocationMaster SLM
	WHERE
		SLM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2011 AS SourceTypeId,
				LM.Id AS SourceId,
				LM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sLibrary.tLibraryMaster LM
	WHERE
		LM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2012 AS SourceTypeId,
				DBM.Id AS SourceId,
				DBM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sEExam.tDataBankMaster DBM
	WHERE
		DBM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2013 AS SourceTypeId,
				RBM.Id AS SourceId,
				RBM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sFee.tReceiptBookMaster RBM
	WHERE
		RBM.OrgGroupId=@rOrgGroupId
		
	UNION ALL
	
	SELECT
				2018 AS SourceTypeId,
				CRBM.Id AS SourceId,
				CRBM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sFee.tChargeReceiptBookMaster CRBM
	WHERE
		CRBM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2014 AS SourceTypeId,
				HM.Id AS SourceId,
				HM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sHostel.tHostelMaster HM
	WHERE
		HM.OrgGroupId=@rOrgGroupId
		
		
	UNION ALL
	
	SELECT
				2022 AS SourceTypeId,
				TM.Id AS SourceId,
				TM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sTransport.tTransportMaster TM
	WHERE
		TM.OrgGroupId=@rOrgGroupId	
		
		
		UNION ALL
			
	SELECT
				2017 AS SourceTypeId,
				DM.Id AS SourceId,
				OM.DisplayTitle + ' - ' + DM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sSetup.tDepartmentMaster DM INNER JOIN sSetup.tOrganizationMaster OM
			ON DM.OrgId = OM.Id
	WHERE
		DM.OrgId IN (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	 
	
	
	UNION ALL
	
	SELECT
				2023 AS SourceTypeId,
				TS.Id AS SourceId,
				TS.Title  AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sTimetable.tTimeTableSchema TS 
	WHERE
		TS.OrgGroupBatchId = @rOrgGroupBatchId
		
		UNION ALL
	
	SELECT
				2026 AS SourceTypeId,
				CM.Id AS SourceId,
				CM.Title AS SourceName,
				'False' AS IsObsolete,
				0 AS OrderIndex
	FROM
			sCanteen.tCanteenMaster CM
	WHERE
		CM.OrgGroupId=@rOrgGroupId
		
	
	UNION ALL
	
	SELECT
		2005 AS SourceTypeId,
		DM.Id AS SourceId,
		OM.DisplayTitle +' - '+ CM.Title +' - '+DM.Title AS SourceName,
		'False' AS IsObsolete,
		CONVERT(bigint,CONVERT(nvarchar(10),ISNULL(OM.OrderIndex,0))+CONVERT(nvarchar(10),ISNULL(CM.OrderIndex,0))+CONVERT(nvarchar(10),ISNULL(DM.OrderIndex,0))) AS OrderIndex
	FROM
		sSetup.tClassMaster CM
		INNER JOIN sSetup.tDivisionMaster DM  ON CM.Id = DM.ClassId
		INNER JOIN sSetup.tOrganizationMaster OM  ON OM.Id = DM.OrgId
		WHERE DM.OrgId IN (SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
		AND DM.IsObsolete = 0
	) A	
	ORDER BY SourceTypeId,OrderIndex
END
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserAdd]
	@rOrgId [smallint],
	@rDisplayTitle [nvarchar](100),
	@rLoginTitle [nvarchar](20),
	@rLoginPassword [nvarchar](100),
	@rIsObsolete [bit],
	--@rEmployeeId [int],
	@rUserSourceId bigint,
	@rUserSourceTypeId int,
	@rCreatedUserId [bigint],
	@rValidUpto date,
	@rIsCommon bit
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rUserSourceTypeId=0)
	BEGIN
		SET @rUserSourceId=NULL
		SET @rUserSourceTypeId=NULL
	END
	
	IF((@rUserSourceTypeId <> 1 OR @rUserSourceId<>0))
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceTypeId = @rUserSourceTypeId AND SourceId = @rUserSourceId AND OrgId=@rOrgId)
		BEGIN
			SELECT -1 AS UserId
			RETURN
		END
	END
	
	IF(@rIsCommon=0)
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rLoginTitle AND OrgId = @rOrgId)
		BEGIN
			SELECT -1 AS UserId
			RETURN
		END
	END
	IF(@rIsCommon=1)
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE DisplayTitle = @rDisplayTitle OR LoginTitle = @rLoginTitle)
		BEGIN
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceId != NULL AND SourceTypeId != NULL)
			BEGIN
				SELECT -1 AS UserId
				RETURN
			END
			ELSE IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE (DisplayTitle = @rDisplayTitle OR LoginTitle = @rLoginTitle) AND OrgId=@rOrgId)
			BEGIN
				SELECT -1 AS UserId
				RETURN
			END
		END
	END
	
	DECLARE @lNextNumber BIGINT	
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output
	
	DECLARE @lCurrentDateTime DATETIME
	EXECUTE @lCurrentDateTime = sCommon.fGetDate		

		INSERT INTO sSecurity.tUser
			(
				Id,		
				DisplayTitle,
				LoginTitle,
				LoginPassword,
				LastLockOutDate,
				NumberOfLogonAttempt,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				--EmployeeId,
				OrgId,
				SourceId,
				SourceTypeId,
				ValidUpto,
				IsCommon
			)
		VALUES
			(
				@lNextNumber,
				@rDisplayTitle,					
				@rLoginTitle,
				@rLoginPassword,
				@lCurrentDateTime,
				0,
				@rIsObsolete,
				@rCreatedUserId,
				@lCurrentDateTime,
				@rCreatedUserId,
				@lCurrentDateTime,
				--@rEmployeeId,
				@rOrgId,
				@rUserSourceId,
				@rUserSourceTypeId,
				@rValidUpto,
				@rIsCommon
			)
			
			
			IF(@rUserSourceTypeId=1  OR  @rUserSourceTypeId=95)
			BEGIN
			IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserOrganization WHERE UserId = @lNextNumber AND OrgId = @rOrgId)
			BEGIN
			INSERT INTO sSecurity.tUserOrganization
			SELECT @rOrgId,@lNextNumber
			END
			END
			
			
	SELECT @lNextNumber AS UserId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pUserByLoginUserNameGet]
	@rOrgId [smallint],
	@rDisplayTitle [nvarchar](100),
	@rLoginTitle [nvarchar](20),
	@rRoleId int,
	@rSourceTypeId smallint,
	@rSourceCode nvarchar(20),
	@rSourcename nvarchar(100),
	@rCondition [tinyint],
	@rIsCommon bit,
	@rOrgGroupId smallint,
	@rIsObsolete bit=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rDisplayTitle = sCommon.fSearchStringGet(@rDisplayTitle)
SET @rLoginTitle = sCommon.fSearchStringGet(@rLoginTitle) 
SET @rSourceCode= sCommon.fSearchStringGet(@rSourceCode)
SET @rSourceName= sCommon.fSearchStringGet(@rSourcename)

	IF (@rSourceTypeId = 95)
	BEGIN
		SELECT 
			Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,			
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Employee' AS UserSourceTypeName,			
			Users.IsObsolete,
			Emp.Code AS EmployeeCode,
			--Emp.FirstName +  ' ' + Emp.LastName AS UserFullName,
			[sHrm].[fEmployeeNameGet](Emp.FirstName , Emp.MiddleName, Emp.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            AT.AffiliationTypeId	            
       FROM sSecurity.tUser Users			
			INNER JOIN sHrm.vExtEmployeeMaster Emp			
			ON Emp.Id = Users.SourceId AND Users.SourceTypeId = 95
			AND((Emp.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND((Emp.EmployeeName like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))								
			INNER JOIN sSecurity.tUserRole UR ON UR.UserId=Users.Id AND UR.IsObsolete=0 
			AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Users.OrgId
			INNER JOIN sSetup.tAffiliationMaster AT ON OM.AffiliationId = AT.Id
			LEFT JOIN sSecurity.tUserProfile Uprof ON Users.Id = Uprof.UserId
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND (Users.SourceTypeId = 95)
		  AND ((@rIsCommon=0 AND Users.SourceId Is Not Null) OR (@rIsCommon=1 AND Users.SourceId Is Null))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (ISNULL(Users.IsCommon,0)=@rIsCommon)                        
          AND Users.IsObsolete=@rIsObsolete     
	END
	ELSE IF (@rSourceTypeId = 2003)
	BEGIN
		SELECT 
			Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,			
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Student' AS UserSourceTypeName,			
			Users.IsObsolete,
			SN.Code AS EmployeeCode,
			SN.FirstName +  ' ' + SN.LastName AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            AT.AffiliationTypeId	            
       FROM sSecurity.tUser Users			
			INNER JOIN sStudent.tStudentMaster SN
			ON SN.Id = Users.SourceId AND Users.SourceTypeId = 2003		
			AND((SN.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND((SN.FirstName like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))								
			INNER JOIN sSecurity.tUserRole UR ON UR.UserId=Users.Id AND UR.IsObsolete=0 
			AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Users.OrgId
			INNER JOIN sSetup.tAffiliationMaster AT ON OM.AffiliationId = AT.Id
			LEFT JOIN sSecurity.tUserProfile Uprof ON Users.Id = Uprof.UserId
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND (Users.SourceTypeId = 2003)
		  AND ((@rIsCommon=0 AND Users.SourceId Is Not Null) OR (@rIsCommon=1 AND Users.SourceId Is Null))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (ISNULL(Users.IsCommon,0)=@rIsCommon)                        
          AND Users.IsObsolete=@rIsObsolete     
	END
	ELSE IF (@rSourceTypeId = 1)
	BEGIN
		SELECT 
			Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,			
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Other' AS UserSourceTypeName,			
			Users.IsObsolete,
			'' AS EmployeeCode,
			'' AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            AT.AffiliationTypeId	            
       FROM sSecurity.tUser Users													
			INNER JOIN sSecurity.tUserRole UR ON UR.UserId=Users.Id AND UR.IsObsolete=0 
			AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Users.OrgId
			INNER JOIN sSetup.tAffiliationMaster AT ON OM.AffiliationId = AT.Id
			LEFT JOIN sSecurity.tUserProfile Uprof ON Users.Id = Uprof.UserId
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND (Users.SourceTypeId = 1)
		  AND ((@rIsCommon=0 AND Users.SourceId Is Not Null) OR (@rIsCommon=1 AND Users.SourceId Is Null))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (ISNULL(Users.IsCommon,0)=@rIsCommon)                        
          AND Users.IsObsolete=@rIsObsolete     
	END
	--ELSE
	--BEGIN
 --      SELECT 
 --           Users.Id,
	--		Users.DisplayTitle,
	--		Users.LoginTitle,
	--		--Users.EmployeeId,
	--		Users.SourceId AS UserSourceId,
	--		Users.SourceTypeId AS UserSourceTypeId,
	--		CASE WHEN Users.SourceTypeId = 95 THEN	'Employee'
	--		WHEN Users.SourceTypeId = 2003 THEN	'Student'
	--		ELSE
	--			'Other'
	--		END   AS UserSourceTypeName,
			
	--		Users.IsObsolete,
	--		CASE WHEN Users.SourceTypeId = 95 THEN	Emp.Code
	--		WHEN Users.SourceTypeId = 2003 THEN	SN.Code
	--		ELSE
	--		''
	--			--Users.DisplayTitle
	--		END   AS EmployeeCode,
	--		CASE WHEN Users.SourceTypeId = 95 THEN (Emp.FirstName +  ' ' + Emp.LastName)
	--		WHEN Users.SourceTypeId = 2003 THEN (SN.FirstName +  ' ' + SN.LastName)
	--		ELSE
	--		''
	--			--Users.LoginTitle
	--		END   AS UserFullName,
	--		--CASE WHEN Users.SourceTypeId = 95 THEN
	--		--	Emp.EmployeeJobTitleId
	--		--ELSE
	--		--	0
	--		--END AS EmployeeJobTitleId,
	--		Uprof.ElectronicSignature AS ElectronicSignature,
 --           CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
 --           UR.RoleId,
 --           R.Title AS RoleName,
 --           Users.OrgId,
 --           Users.ValidUpto AS ValidUptoDate,                     
 --           OM.Title AS OrgName,
 --           AT.AffiliationTypeId	
            
 --      FROM sSecurity.tUser Users
	--		-- Commented For Employee Migration
	--		--INNER JOIN sCommon.tEmployeeMaster Emp
	--		-- End of comment for Employee Migration
	--		-- Added for Employee Migration
	--		LEFT JOIN sHrm.vExtEmployeeMaster Emp
	--		-- End of addition for Employee Migration
	--		ON Emp.Id = Users.SourceId AND Users.SourceTypeId = 95
	--		AND((Emp.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
	--		AND((Emp.EmployeeName like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))
	--		LEFT JOIN sStudent.tStudentMaster SN
	--		ON SN.Id = Users.SourceId AND Users.SourceTypeId = 2003		
	--		AND((SN.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
	--		AND((SN.FirstName like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))		
	--		LEFT JOIN sSecurity.tUserProfile Uprof
	--		ON Users.Id = Uprof.UserId
	--		INNER JOIN sSecurity.tUserRole UR ON UR.UserId=Users.Id AND UR.IsObsolete=0 
	--		AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
	--		INNER JOIN sSecurity.tRole R ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Users.OrgId
	--		INNER JOIN sSetup.tAffiliationMaster AT ON OM.AffiliationId = AT.Id 
			
 --       WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	--      AND ((Users.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
	--	  AND ((@rIsCommon=0 AND Users.SourceId Is Not Null) OR (@rIsCommon=1 AND Users.SourceId Is Null))
	--	  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
 --         AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
 --         AND (ISNULL(Users.IsCommon,0)=@rIsCommon)                        
 --         AND Users.IsObsolete=@rIsObsolete
	--END
END	
--'sSecurity.tUser'
--'sCommon.tEmployeeMaster'
--'sSecurity.tUserProfile'

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserByParentId]
	@rId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		Id 	As UserId	
	FROM 
		sSecurity.tUser
	WHERE
		SourceId = @rId AND SourceTypeId = 2003
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserDashboardGet]
	 
	 @rType nvarchar(100)='',
	 @rDay int=0,
	 
	 @rOrgGroupId int=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rBatchId int=0,
	 @rUserId bigint = 0,
	 @rRoleId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  IF(@rType='Organization')
  BEGIN
	SELECT 
		COUNT(U.Id) AS UserCount 
	FROM 
		sSecurity.tUser U
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
	WHERE 
		(OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (U.OrgId = @rOrgId OR @rOrgId=0)
		AND U.IsObsolete = 0
		AND (U.CreatedUserId != 1 OR U.DisplayTitle = 'Admin')
  END
  
  IF(@rType='Role')
  BEGIN
	SELECT R.Id AS RoleId, R.Title AS RoleName,COUNT(*) AS UserCount FROM sSecurity.tUser U
	INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
	INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
	WHERE (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND (U.OrgId = @rOrgId OR @rOrgId=0) AND U.IsObsolete = 0 AND UR.IsObsolete=0
	GROUP BY R.Id,R.Title
  END
  
  IF(@rType='User')
  BEGIN
	SELECT U.DisplayTitle AS UserName,COUNT(*) AS UserCount FROM sSecurity.tUser U
	INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
	INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
	WHERE (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND (U.OrgId = @rOrgId OR @rOrgId=0) AND U.IsObsolete = 0  AND UR.IsObsolete=0
	AND R.Id = @rRoleId
	GROUP BY U.DisplayTitle
  END
  
  
  IF(@rType='OrgGroup')
  BEGIN
	SELECT OM.Id AS OrgId, OM.DisplayTitle AS Organization,COUNT(*) AS UserCount FROM sSecurity.tUser U
	INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
	INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
	WHERE (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND (U.OrgId = @rOrgId OR @rOrgId=0) AND U.IsObsolete = 0  AND UR.IsObsolete=0
	--AND R.Id = @rRoleId
	GROUP BY OM.Id , OM.DisplayTitle
  END
  
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pUserDashboardNotificationAdd]
	 
		@rUserId bigint,
		@rScreenId  int,
		@rLastAccessDateTime date=''
		
      
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
If Exists(select 1 from sSecurity.tUserDashboardNotification where UserId=@rUserId AND ScreenId=@rScreenId)
		 BEGIN
	    UPDATE sSecurity.tUserDashboardNotification
	    SET
			LastAccessDateTime=sCommon.fGetDate()
	      WHERE UserId = @rUserId AND ScreenId = @rScreenId
	      SELECT @rUserId AS Result
	 END  	
ELSE
BEGIN
		INSERT INTO sSecurity.tUserDashboardNotification
		(
		UserId,
		ScreenId,
		LastAccessDateTime
		)
	VALUES
		(
		@rUserId,
		@rScreenId,
		sCommon.fGetDate()
		)
		    SELECT @rUserId AS Result    
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pUserDashletGet]
	 
	@rUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT
		RD.DashletId AS  RoleDashletId,
		ISNULL(UD.DashletId,0) AS  UserDashletId,
		DM.Title AS DashletName,
		CASE 
			WHEN UD.DashletId = RD.DashletId THEN CONVERT(Bit, 1)
			ELSE CONVERT(Bit, 0)
		END AS IsCheck
	FROM
	
	
	  sSecurity.tRoleDashlet RD
	  INNER JOIN sSecurity.tUserRole UR ON RD.RoleId = UR.RoleId AND UR.UserId = @rUserId
	  INNER JOIN sSecurity.tDashletMaster DM 
		ON RD.DashletId=DM.Id
		INNER JOIN sSecurity.tPermission P ON P.TaskId=DM.TaskId AND P.RoleId = RD.RoleId		 
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId	
	  LEFT JOIN sSecurity.tUserDashlet UD 
		ON UD.UserId = UR.UserId AND RD.DashletId = UD.DashletId		 
	

	
	WHERE 
	(P.Permission & 2) =2
		--AND ScreenGroupId=@rScreenGroupId AND U.IsObsolete=0
		AND UR.UserId=@rUserId 
		AND T.IsObsolete = 0		 
	AND UR.UserId =@rUserId
	AND UR.IsPrimary = 1
	AND UR.IsObsolete = 0
	AND DM.IsObsolete = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pUserDashletUpdate]
	
	@rRoleDashletImpXml [nvarchar](max),
	@rUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rRoleDashletImpXml
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION
	
	 DELETE FROM sSecurity.tUserDashlet Where UserId = @rUserId
	
	 INSERT INTO sSecurity.tUserDashlet
		(
			UserId,
			DashletId
			)
		SELECT
			UserId,
			DashletId
		FROM OPENXML (@loDoc, '/Table/RoleDashlet', 1)
		WITH ( 
				UserId bigint,
				DashletId int
			  ) 
		
	   SELECT 1 AS Result
		
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserExistsByUserNameGet]
	@rOrgId smallint,
	@rUserName [nvarchar](20),
	@rPassword [nvarchar](100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		SELECT SessionId FROM sSecurity.tUser
		WHERE (LoginTitle = @rUserName)
			AND (LoginPassword = @rPassword)
			AND OrgId = @rOrgId

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserFavoriteScreenAdd]
	
	@rUserId [bigint],
	@rFavoraiteScreenId int,
	@rIsDelete bit
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
 	IF EXISTS(SELECT 1 FROM sSecurity.tUserFavoriteScreen WHERE UserId = @rUserId AND FavoriteScreenId = @rFavoraiteScreenId) AND @rIsDelete = 1
			BEGIN
				Delete From sSecurity.tUserFavoriteScreen WHERE UserId = @rUserId AND FavoriteScreenId = @rFavoraiteScreenId
			END
	ELSE IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserFavoriteScreen WHERE UserId = @rUserId AND FavoriteScreenId = @rFavoraiteScreenId)
			BEGIN 
					INSERT INTO sSecurity.tUserFavoriteScreen
						(
							UserId,		
						    FavoriteScreenId
						)
					VALUES
						(
							@rUserId,
							@rFavoraiteScreenId							 
						) 
			END			
			SELECT 1 AS UserId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserFavoriteScreenGet]
	
	@rUserId [bigint]
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
      SELECT  
           UserId,
           FavoriteScreenId AS FavoraiteScreenId,
           S.Title AS UserFavoraiteScreen,
           --CASE WHEN S.ScreenTypeId = 1 THEN S.Page
           --ELSE S.Page + '?MenuID=' +CONVERT(Nvarchar(50),M.Id) END AS PagePath,
            CASE WHEN S.ScreenTypeId = 1 THEN  S.Page + '?MenuID=' +CONVERT(Nvarchar(50),(SELECT Id FROM sSecurity.tMenu M WHERE M.ScreenId = U.FavoriteScreenId AND M.IsObsolete = 0)) 
           ELSE S.Page  END AS PagePath,
           T.ResourceTypeId 
                       
      FROM
 	  sSecurity.tUserFavoriteScreen U INNER JOIN sSecurity.tScreen S ON U.FavoriteScreenId = S.Id  
 	  --INNER JOIN sSecurity.tMenu M On M.ScreenId = S.Id
 	  INNER JOIN sSecurity.tTask T ON S.TaskId = T.Id
		 
	  where UserId = @rUserId
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserGet]
	@rOrgId smallint,
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			DisplayTitle,
			LoginTitle,
			LoginPassword,
			LastLockOutDate,
			NumberOfLogonAttempt,
			--IsOnline,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sSecurity.tUser
	  WHERE ((Id = @rId) OR (@rId = 0))
	  AND OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserInRole]
	@rRoleId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 	 SELECT P.UserId,
			P.FirstName,
			P.MiddleName,
			P.LastName,
			P.ContactId,
			C.PhoneNumberHome,
			C.PhoneNumberOffice,
			C.PhoneNumberMobile,
			C.EmailPrimary,
			C.EmailAlternative,
			P.AddressId,
			A.StreetOne,
			A.StreetTwo,
			A.StreetThree,
			A.StreetFour,
			A.CityId,
			city.Title AS CityName,
			city.StateId,
			S.Title AS StateName,
			S.CountryId,
			S.Title AS CountryName,
			A.ZipCode
	   FROM sSecurity.tUserRole UR
		INNER JOIN sSecurity.tUserProfile P
			ON UR.UserId = P.UserId
		INNER JOIN sCommon.tContact C
			ON P.ContactId = C.Id
		INNER JOIN sCommon.tAddress A
			ON P.AddressId = A.Id
		INNER JOIN sCommon.tCityMaster City
			ON A.CityId = city.Id
		INNER JOIN sCommon.tStateMaster S
			ON city.StateId = S.Id
		INNER JOIN sCommon.tCountryMaster Country
			ON S.CountryId = country.Id
	  WHERE UR.RoleId = @rRoleId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserInRoleCheck]
	@rUserId [bigint],
	@rRoleId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT ISNULL(COUNT(UserId),0) FROM sSecurity.tUserRole WHERE UserId = @rUserId AND RoleId = @rRoleId AND IsObsolete = 0
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserLocationAdd]
  
	@rOrgId [smallint],	
	@rUserId [bigint],	
	@rMapping [nvarchar](max),
	@rCreatedUserId [bigint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT

DECLARE @lCurrentDateTime DateTime
SET @lCurrentDateTime = sCommon.fGetDate()

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rMapping
BEGIN

DELETE FROM sSecurity.tUserLocation WHERE UserId = @rUserId


INSERT INTO   sSecurity.tUserLocation (
							StoreLocationId, 
							UserId, 
							CreatedUserId,							 
							CreatedDateTime							 
							)		
			SELECT StoreLocationId,@rUserId,@rCreatedUserId,@lCurrentDateTime
			FROM
			OPENXML (@loDoc, '/Items/Item', 2)
			WITH (
					StoreLocationId  int) A
 
			SELECT 1 As Result	
END
EXEC sp_xml_removedocument @loDoc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserLogAdd]
	@rOrgId int,
	@rUserId bigint,
	@rLoggedInIp [nvarchar](15),
	@rIsOnlinep [bit],
	@rLoggedInDateTime [datetime],
	@rLoggedOutDateTime [datetime],
	@rUiCultureIdp [tinyint],
	@rSessionIdp [nvarchar](100),
	@rLocalAddress [nvarchar](200)='',
	@rOSTypeId [tinyint]=0,
	@rDeviceUniqueId [nvarchar](100)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserLogAdd Start', 
	'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
	+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionIdp AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserLogAdd')
END

DECLARE @lNextNumber BIGINT
EXECUTE sCommon.pTableRowIdGet @rOrgId,'sSecurity.tUserLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	--SELECT @lNextNumber

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserLogAdd Table Row Id Generated', 
	'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
	+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionIdp AS nvarchar(100)), 
	CAST(@lNextNumber AS NVARCHAR(100)), '', GETDATE(), 'sSecurity.pUserLogAdd')
END

BEGIN
	INSERT INTO sSecurity.tUserLog WITH (ROWLOCK)
		(
			OrgId,
			Id,
			UserId,
			LoggedInIp,
			LoggedInDateTime,
			LoggedOutDateTime,
			IsOnline,
			UiCultureId,
			SessionId,
			LoggedInLocalIp,
			OSTypeId,
			DeviceUniqueId
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rUserId,
			@rLoggedInIp,
			@rLoggedInDateTime,
			@rLoggedOutDateTime,
			@rIsOnlinep,
			@rUiCultureIdp,
			@rSessionIdp,
			@rLocalAddress,
			@rOSTypeId,
			@rDeviceUniqueId
		)

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserLogAdd End', 
	'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
	+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionIdp AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserLogAdd')
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE OR ALTER PROCEDURE [sSecurity].[pUserLogDetailGet]
	@rOrgId [smallint],
	@rDisplayTitle [nvarchar](100),
	@rLoginTitle [nvarchar](20),
	@rRoleId int,
	@rSourceTypeId smallint,
	@rSourceCode nvarchar(20),
	@rSourcename nvarchar(100),
	@rIsCommon bit,
	@rOrgGroupId smallint,
	@rFromDate date,
	@rToDate date,
	@rOsTypeId smallint=0,
	@rIsHistory bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rDisplayTitle = sCommon.fSearchStringGet(@rDisplayTitle)
SET @rLoginTitle = sCommon.fSearchStringGet(@rLoginTitle) 
SET @rSourceCode= sCommon.fSearchStringGet(@rSourceCode)
SET @rSourceName= sCommon.fSearchStringGet(@rSourcename)

SET @rToDate = DATEADD(day,1,@rToDate)

IF(@rIsHistory = 1)
BEGIN
IF(@rSourceTypeId = 2003)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Student' AS UserSourceTypeName,
			Users.IsObsolete,
			SN.Code AS EmployeeCode,
			SN.Name AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users			
			INNER JOIN sStudent.vStudentName SN
				ON SN.StudentId = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId						
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SN.BatchId  AND BM.IsActive = 1
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLogHistory UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  
		 AND((SN.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((SN.Name like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))               
		  Order By UL.Id DESC
END
ELSE IF(@rSourceTypeId = 95)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Employee' AS UserSourceTypeName,
			Users.IsObsolete,
			Emp.Code AS EmployeeCode,
			(Emp.FirstName +  ' ' + Emp.LastName) AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users			
			INNER JOIN sHrm.vExtEmployeeMaster Emp
				ON Emp.Id = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId							
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLogHistory UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  
		 AND((Emp.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((Emp.EmployeeName like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))           
		  Order By UL.Id DESC
END
ELSE IF(@rSourceTypeId = 1)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Other' AS UserSourceTypeName,
			Users.IsObsolete,
			Users.DisplayTitle AS EmployeeCode,
			Users.LoginTitle AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users						
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLogHistory UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  		  
		 AND((Users.DisplayTitle like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((Users.DisplayTitle like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))                            
		  Order By UL.Id DESC
END       
END
ELSE
BEGIN
	IF(@rSourceTypeId = 2003)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Student' AS UserSourceTypeName,
			Users.IsObsolete,
			SN.Code AS EmployeeCode,
			SN.Name AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users			
			INNER JOIN sStudent.vStudentName SN
				ON SN.StudentId = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId						
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SN.BatchId  AND BM.IsActive = 1
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLog UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  
		 AND((SN.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((SN.Name like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))               
		  Order By UL.Id DESC
END
ELSE IF(@rSourceTypeId = 95)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Employee' AS UserSourceTypeName,
			Users.IsObsolete,
			Emp.Code AS EmployeeCode,
			(Emp.FirstName +  ' ' + Emp.LastName) AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users			
			INNER JOIN sHrm.vExtEmployeeMaster Emp
				ON Emp.Id = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId							
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLog UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  
		 AND((Emp.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((Emp.EmployeeName like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))           
		  Order By UL.Id DESC
END
ELSE IF(@rSourceTypeId = 1)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Other' AS UserSourceTypeName,
			Users.IsObsolete,
			Users.DisplayTitle AS EmployeeCode,
			Users.LoginTitle AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users						
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLog UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  		  
		 AND((Users.DisplayTitle like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((Users.DisplayTitle like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))                            
		  Order By UL.Id DESC
END  
END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserLogGet]
	@rOrgId [smallint],
	@rId [bigint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			UserId,
			LoggedInIp,
			LoggedInDateTime,
			LoggedOutDateTime
	   FROM sSecurity.tUserLog
	  WHERE ((Id = @rId) OR (@rId = 0))
	  AND OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserLoginAuthenticationEmailOTPGet] 
	@rOrgId INT = 0
	,@rOrgGroupId INT = 0
	,@rEmailId NVARCHAR(50)
	,@rMobileNumber NVARCHAR(50)
	,@rUserSourceId BIGINT
	,@rUserSourceTypeId INT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lUserId BIGINT = 0,@lId BIGINT = 0
	DECLARE @newpwd VARCHAR(100)

	DECLARE @lConfigVal nvarchar(50)
	DECLARE @lDefaultConfigVal nvarchar(50)
	SELECT @lDefaultConfigVal = ItemValue FROM sConfig.tConfigurationMaster WHERE Id = (CASE WHEN @rUserSourceTypeId = 2003 THEN 583 WHEN @rUserSourceTypeId = 95 THEN 584 END)
	SELECT @lConfigVal = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = (CASE WHEN @rUserSourceTypeId = 2003 THEN 583 WHEN @rUserSourceTypeId = 95 THEN 584 END) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	IF(@lConfigVal IS NULL OR @lConfigVal = '')
	BEGIN
		SET @lConfigVal = @lDefaultConfigVal
	END

	IF (@rUserSourceTypeId = 2003)
	BEGIN
		IF (@lConfigVal = 'Email')
		BEGIN
			SELECT @lUserId = SC.StudentId
			FROM sStudent.tStudentCommunication SC
			INNER JOIN sStudent.vStudentAcademic A ON A.StudentId = SC.StudentId --AND A.IsActiveBatch = 1
			INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId = 2003
			WHERE SC.ParentEmail = @rEmailId
				AND A.OrgId = @rOrgId
				AND U.SourceId = @rUserSourceId
		END

		IF (@lConfigVal = 'SMS')
		BEGIN
			SELECT @lUserId = SC.StudentId
			FROM sStudent.tStudentCommunication SC
			INNER JOIN sStudent.vStudentAcademic A ON A.StudentId = SC.StudentId --AND A.IsActiveBatch = 1
			INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId = 2003
			WHERE SC.ParentContactNo = @rMobileNumber
				AND A.OrgId = @rOrgId
				AND U.SourceId = @rUserSourceId
		END

		IF (@lConfigVal = 'Both')
		BEGIN
			DECLARE @lEmailUserId BIGINT = 0,@lMobileUserId BIGINT = 0
			SELECT @lEmailUserId = SC.StudentId
			FROM sStudent.tStudentCommunication SC
			INNER JOIN sStudent.vStudentAcademic A ON A.StudentId = SC.StudentId --AND A.IsActiveBatch = 1
			INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId = 2003
			WHERE SC.ParentEmail = @rEmailId
				AND A.OrgId = @rOrgId
				AND U.SourceId = @rUserSourceId

			SELECT @lMobileUserId = SC.StudentId
			FROM sStudent.tStudentCommunication SC
			INNER JOIN sStudent.vStudentAcademic A ON A.StudentId = SC.StudentId --AND A.IsActiveBatch = 1
			INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId = 2003
			WHERE SC.ParentContactNo = @rMobileNumber
				AND A.OrgId = @rOrgId
				AND U.SourceId = @rUserSourceId

			IF(@lEmailUserId > 0 AND @rEmailId IS NOT NULL AND @rEmailId <> '')
			BEGIN
				SET @lUserId = @lEmailUserId
			END
			IF(@lMobileUserId > 0 AND @rMobileNumber IS NOT NULL AND @rMobileNumber <> '')
			BEGIN
				SET @lUserId = @lMobileUserId
			END
		END
		
		IF (@lUserId > 0)
		BEGIN
			
			EXEC [sSecurity].[pNumericOTPGenerate] @len = 4
				,@min = 48
				,@range = 9
				,@exclude = ''
				,@output = @newpwd OUT

			UPDATE sSecurity.tUser
			SET TempPasswordCode = @newpwd
				,CreatedDateTime = sCommon.fGetDate()
				,OTPExpiryDate = DATEADD(SECOND, 120, GETDATE())
			WHERE SourceId = @lUserId
				AND OrgId = @rOrgId
				AND SourceTypeId = 2003

			SELECT 1 AS Result
				,@rMobileNumber AS MobileNo
				,'' AS [Message]
				,@rEmailId AS EmailId
				,'' AS MsgText
				,'' AS Subject
				,@lUserId AS ReceiverSourceId
				,2003 AS ReceiverSourceTypeId
				,TempPasswordCode AS OTP
				,Id AS UserId
			FROM sSecurity.tUser
			WHERE SourceId = @lUserId
				AND SourceTypeId = 2003
				AND OrgId = @rOrgId
		END

		ELSE
		BEGIN
			SELECT -102 AS Result
				,@rMobileNumber AS MobileNo
				,'Invalid Email or Mobile Number. Please check and try again.' AS [Message]
				,@rEmailId AS EmailId
				,'' AS MsgText
				,'' AS Subject
				,0 AS ReceiverSourceId
				,0 AS ReceiverSourceTypeId
				,'' AS OTP
				,0 AS UserId
		END
	END

	IF (@rUserSourceTypeId = 95)
	BEGIN
		IF (@lConfigVal = 'Email')
		BEGIN
			SELECT @lId = EC.EmployeeId
			FROM sHrm.tEmployeeCommunications EC
			INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id
			INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId = 95
			WHERE EC.CompanyEmail = @rEmailId
				AND EM.OrgId = @rOrgId
				AND U.SourceId = @rUserSourceId
		END

		IF (@lConfigVal = 'SMS')
		BEGIN
			SELECT @lId = EC.EmployeeId
			FROM sHrm.tEmployeeCommunications EC
			INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id
			INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId = 95
			WHERE EC.MobileNumber = @rMobileNumber
				AND EM.OrgId = @rOrgId
				AND U.SourceId = @rUserSourceId
		END

		IF (@lConfigVal = 'Both')
		BEGIN
			DECLARE @lEmailUserId1 BIGINT = 0,@lMobileUserId1 BIGINT = 0
			SELECT @lEmailUserId1 = EC.EmployeeId
			FROM sHrm.tEmployeeCommunications EC
			INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id
			INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId = 95
			WHERE EC.CompanyEmail = @rEmailId
				AND EM.OrgId = @rOrgId
				AND U.SourceId = @rUserSourceId

			SELECT @lMobileUserId1 = EC.EmployeeId
			FROM sHrm.tEmployeeCommunications EC
			INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id
			INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId = 95
			WHERE EC.MobileNumber = @rMobileNumber
				AND EM.OrgId = @rOrgId
				AND U.SourceId = @rUserSourceId
			
			IF(@lEmailUserId1 > 0 AND @rEmailId IS NOT NULL AND @rEmailId <> '')
			BEGIN
				SET @lId = @lEmailUserId1
			END
			IF(@lMobileUserId1 > 0 AND @rMobileNumber IS NOT NULL AND @rMobileNumber <> '')
			BEGIN
				SET @lId = @lMobileUserId1
			END
		END

		IF (@lId > 0)
		BEGIN
			EXEC [sSecurity].[pNumericOTPGenerate] @len = 4
				,@min = 48
				,@range = 9
				,@exclude = ''
				,@output = @newpwd OUT

			UPDATE sSecurity.tUser
			SET TempPasswordCode = @newpwd
				,CreatedDateTime = sCommon.fGetDate()
				,OTPExpiryDate = DATEADD(SECOND, 120, GETDATE())
			WHERE SourceId = @lId
				AND OrgId = @rOrgId
				AND SourceTypeId = 95

			SELECT 1 AS Result
				,@rMobileNumber AS MobileNo
				,'' AS [Message]
				,@rEmailId AS EmailId
				,'' AS MsgText
				,'' AS Subject
				,@lId AS ReceiverSourceId
				,95 AS ReceiverSourceTypeId
				,TempPasswordCode AS OTP
				,Id AS UserId
			FROM sSecurity.tUser
			WHERE SourceId = @lId
				AND OrgId = @rOrgId
				AND SourceTypeId = 95
		END
		ELSE
		BEGIN
			SELECT -102 AS Result
				,@rMobileNumber AS MobileNo
				,'Invalid Email or Mobile Number. Please check and try again.' AS [Message]
				,@rEmailId AS EmailId
				,'' AS MsgText
				,'' AS Subject
				,0 AS ReceiverSourceId
				,0 AS ReceiverSourceTypeId
				,'' AS OTP
				,0 AS UserId
		END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserLoginAuthenticationOTPGet]

	@rOrgId int = 0,
	@rMobileNumber nvarchar(50),
	@rUserSourceId bigint ,
	@rUserSourceTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0 
	DECLARE @lUserId bigint = 0,@lId Bigint = 0
	DECLARE @newpwd VARCHAR(100) 
	
	IF(@rUserSourceTypeId = 2003)
	BEGIN

		SELECT @lCount = COUNT(SC.StudentId) 
		FROM  sStudent.tStudentCommunication SC
		INNER JOIN sStudent.tAcademic A  ON A.StudentId = SC.StudentId
		INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
		WHERE SC.ParentContactNo = @rMobileNumber AND A.OrgId = @rOrgId  AND U.SourceId = @rUserSourceId
		GROUP BY SC.StudentId
		
		IF(@lCount > 0)
		BEGIN	
			
			SELECT SC.StudentId  INTO #UserId FROM  sStudent.tStudentCommunication SC
			INNER JOIN sStudent.tAcademic A  ON A.StudentId = SC.StudentId
			INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			WHERE SC.ParentContactNo = @rMobileNumber AND A.OrgId=@rOrgId  AND U.SourceId = @rUserSourceId
			
			SELECT @lUserId = StudentId FROM #UserId
			EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
		
			UPDATE sSecurity.tUser 
			SET	TempPasswordCode= @newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
			WHERE SourceId = @lUserId AND OrgId = @rOrgId AND SourceTypeId = 2003
			
			SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP,Id AS UserId, SourceId AS UserSourceId FROM sSecurity.tUser 
			WHERE SourceId = @lUserId AND OrgId = @rOrgId	
		
			DROP Table #UserId
		END
		
		ELSE
		BEGIN 
			SELECT -102 AS Result,'Mobile Number is wrong' AS [Message],'' AS OTP, 0 AS UserId, @rUserSourceId AS UserSourceId
		END

	END

	IF(@rUserSourceTypeId = 95)
	BEGIN
		SELECT @lCount = COUNT(EC.EmployeeId), @lId = EC.EmployeeId
		FROM sHrm.tEmployeeCommunications EC 
		INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id 
		INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId=95
		WHERE EC.MobileNumber = @rMobileNumber AND EM.OrgId=@rOrgId  AND U.SourceId = @rUserSourceId
		GROUP BY EC.EmployeeId		
		
		IF(@lCount > 0)
		BEGIN
		
			EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
			UPDATE sSecurity.tUser 
			SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
			WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95
			
			SELECT 1 AS Result,'' AS [Message], TempPasswordCode AS OTP,Id AS UserId,SourceId AS UserSourceId FROM sSecurity.tUser 
			WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95
		END

		ELSE
		BEGIN 
			SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP, 0 AS UserId, @rUserSourceId AS UserSourceId
		END
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserLogModify]
	@rId [bigint],
	@rUserId [int],
	@rLoggedInIp [nvarchar](15),
	@rLoggedInDateTime [datetime],
	@rLoggedOutDateTime [datetime]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 UPDATE sSecurity.tUserLog
		SET 
			UserId = @rUserId,
			LoggedInIp = @rLoggedInIp,
			LoggedInDateTime = @rLoggedInDateTime,
			LoggedOutDateTime = @rLoggedOutDateTime
	  WHERE Id = @rId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserLogOff]
	@rUserId [bigint],
	@rHostAddress [nvarchar](15)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		UPDATE sSecurity.tUser
			SET SessionID = NULL
		WHERE [Id] = @rUserId
			
		UPDATE sSecurity.tUserLog
		SET IsOnline = 0,
			LoggedOutDateTime = sCommon.fGetDate()			
		WHERE UserId = @rUserId AND
				LoggedInDateTime = (SELECT MAX(LoggedInDateTime) FROM sSecurity.tUserLog WHERE UserId = @rUserId) AND
				LoggedInIp = @rHostAddress

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserModify]

	@rUserId [bigint],
	@rLoginTitle nvarchar(100),
	@rLoginPassword [nvarchar](100),
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rValidUpto date,
	@rIsCommon bit,
	@rIsPassword bit,
	@rOrgGroupId smallint,
	@rDisplayTitle nvarchar(100)= ''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	DECLARE @rOrgId int
	SELECT @rOrgId = OrgId FROM sSecurity.tUser WHERE ID = @rUserId
	
	IF(@rIsCommon=0)
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rLoginTitle AND Id!=@rUserId AND OrgId = @rOrgId )
		BEGIN
			SELECT -1 AS ReturnCode
			RETURN
		END
	END
	
	
	DECLARE @lCurrentDateTime DATETIME
	EXECUTE @lCurrentDateTime = sCommon.fGetDate		
	
	IF (@rIsPassword=1 AND ISNULL(@rLoginPassword, '') = '')
	BEGIN
			EXEC sSecurity.pUserRemove  @rUserId, @rIsObsolete, @rUpdatedUserId
	END
	ELSE
	BEGIN
		IF (@rIsPassword=1)
		BEGIN
			IF(@rIsCommon=0)
			BEGIN
				UPDATE sSecurity.tUser
				SET	
				    --LoginTitle = @rLoginTitle,
					LoginPassword = @rLoginPassword,				
					IsObsolete = @rIsObsolete,			
					ValidUpto = @rValidUpto,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = @lCurrentDateTime			
				WHERE 
					Id = @rUserId
			END
			ELSE
			BEGIN
				UPDATE sSecurity.tUser
				SET	
				    --LoginTitle = @rLoginTitle,
					LoginPassword = @rLoginPassword,				
					IsObsolete = @rIsObsolete,			
					ValidUpto = @rValidUpto,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = @lCurrentDateTime			
				WHERE 
					LoginTitle = @rLoginTitle
				AND OrgId IN(SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId)
			END
		END
		ELSE
		BEGIN
			IF(@rIsCommon=0)
			BEGIN
			
	    IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rLoginTitle AND Id!=@rUserId AND OrgId = @rOrgId)
		BEGIN
			SELECT -1 AS ReturnCode
			RETURN
		END	
			
			
			
				UPDATE sSecurity.tUser
				SET	
				    LoginTitle = @rLoginTitle,
					IsObsolete = @rIsObsolete,			
					ValidUpto = @rValidUpto,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = @lCurrentDateTime,
					DisplayTitle = @rDisplayTitle			
				WHERE 
					Id = @rUserId
			END
			ELSE
			BEGIN
				UPDATE sSecurity.tUser
				SET	
					IsObsolete = @rIsObsolete,			
					ValidUpto = @rValidUpto,
					UpdatedUserId = @rUpdatedUserId,
					UpdatedDateTime = @lCurrentDateTime			
				WHERE 
					LoginTitle = @rLoginTitle
				AND OrgId IN(SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId)
			END
		END
	END
		
	SELECT 1 AS ReturnCode
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserNotInRole]
@rOrgId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	  SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId,
			Users.IsObsolete,
			Emp.Code AS EmployeeCode,
			ISNULL(Emp.FirstName, '') + ' ' + ISNULL(Emp.MiddleName, '') + ' ' + ISNULL(Emp.LastName, '') AS EmployeeFullName,
           CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay                              
       FROM sSecurity.tUser Users
			-- Commented For Employee Migration
			--INNER JOIN sCommon.tEmployeeMaster Emp
			-- End of comment for Employee Migration
			-- Added for Employee Migration
			INNER JOIN sHrm.vExtEmployeeMaster Emp
			-- End of addition for Employee Migration
				ON Emp.Id = Users.SourceId AND Users.SourceTypeId=95
		WHERE
			Users.IsObsolete = 0 AND Users.OrgId = @rOrgId	

	  EXCEPT
		
       SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId,
			Users.IsObsolete,
			Emp.Code AS EmployeeCode,
			ISNULL(Emp.FirstName, '') + ' ' + ISNULL(Emp.MiddleName, '') + ' ' + ISNULL(Emp.LastName, '') AS EmployeeFullName,
           CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay                              
       FROM sSecurity.tUser Users
			-- Commented For Employee Migration
			--INNER JOIN sCommon.tEmployeeMaster Emp
			-- End of comment for Employee Migration
			-- Added for Employee Migration
			INNER JOIN sHrm.vExtEmployeeMaster Emp
			-- End of addition for Employee Migration
				ON Emp.Id = Users.SourceId AND Users.SourceTypeId=95
			INNER JOIN sSecurity.tUserRole UR
				ON UR.UserId = Users.Id
        WHERE
			UR.IsObsolete = 0   
		AND Users.IsObsolete = 0  
		AND Users.OrgId = @rOrgId	 
		
		UNION ALL
		
		SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId,
			Users.IsObsolete,
			SN.Code AS EmployeeCode,
			SN.Name AS EmployeeFullName,
           CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay                              
       FROM sSecurity.tUser Users
			-- Commented For Employee Migration
			--INNER JOIN sCommon.tEmployeeMaster Emp
			-- End of comment for Employee Migration
			-- Added for Employee Migration
			INNER JOIN sStudent.vStudentName SN
			ON SN.StudentId = Users.SourceId AND Users.SourceTypeId = 2003		
	   WHERE
			Users.IsObsolete = 0 AND Users.OrgId = @rOrgId	

	  EXCEPT
		
       SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId,
			Users.IsObsolete,
			SN.Code AS EmployeeCode,
			SN.Name AS EmployeeFullName,
			CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay                              
       FROM sSecurity.tUser Users
			-- Commented For Employee Migration
			--INNER JOIN sCommon.tEmployeeMaster Emp
			-- End of comment for Employee Migration
			-- Added for Employee Migration
			INNER JOIN sStudent.vStudentName SN
			ON SN.StudentId = Users.SourceId AND Users.SourceTypeId = 2003		
			INNER JOIN sSecurity.tUserRole UR
				ON UR.UserId = Users.Id
        WHERE
			UR.IsObsolete = 0   
		AND Users.IsObsolete = 0  
		AND Users.OrgId = @rOrgId	                             
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sSecurity].[pUserOrganizationAdd]
	 
	@rUserId bigint,
	@rOrgId smallint,
	@rIsObsolete bit
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	IF(@rIsObsolete = 0)
	BEGIN
		DELETE FROM sSecurity.tUserOrganization WHERE UserId=@rUserId AND OrgId=@rOrgId
	END
	ELSE IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserOrganization WHERE UserId=@rUserId AND OrgId=@rOrgId)
	BEGIN
		INSERT INTO sSecurity.tUserOrganization
		(
			UserId,
			OrgId
		)
		VALUES
		(
			@rUserId,
			@rOrgId
		)
	END
	SELECT 1 AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sSecurity].[pUserOrganizationGet]
	 
	@rUserId bigint,
	@rOrgGroupId smallint
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	
	IF(@rUserId<>0)
	BEGIN
		SELECT
					OM.Id AS OrgId,
					OM.DisplayTitle AS Organization,
					CASE WHEN UO.UserId IS NULL THEN 'False' ELSE 'True' END AS IsObsolete
		FROM
				sSetup.tOrganizationMaster OM
			LEFT JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id AND ((UO.UserId=@rUserId) OR (@rUserId=0))
		WHERE
			OM.OrgGroupId=@rOrgGroupId
			order by OM.OrderIndex
	END
	IF(@rUserId=0)
	BEGIN
		SELECT
					OM.Id AS OrgId,
					OM.DisplayTitle AS Organization,
					'False' AS IsObsolete
		FROM
				sSetup.tOrganizationMaster OM
		WHERE
			OM.OrgGroupId=@rOrgGroupId
			ORDER BY OM.OrderIndex
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserPasswordModify]
	
	@rUserId [bigint],
	@rOldLoginPassword [nvarchar](100),
	@rNewLoginPassword [nvarchar](100),
	@rIsReset bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lResultCode Int
SET @lResultCode = -1
	IF EXISTS(SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND 
		(LogInPassword = @rOldLoginPassword OR @rIsReset = 1))
	BEGIN
			DECLARE @lOrgId int=0
			DECLARE @lUserSourceId bigint = 0
			DECLARE @rUserSourceTypeId smallint=0

			SELECT @lOrgId= OrgId,@lUserSourceId=SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE Id =@rUserId

			DECLARE @lOrgGroupId int =0 
			SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @lOrgId
			
			DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId=@lOrgId AND UserId=@rUserId AND UserSourceId=@lUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
		
			UPDATE sSecurity.tUser
			SET	
				LoginPassword = @rNewLoginPassword,	
				UpdatedUserId = @rUserId,
				UpdatedDateTime = sCommon.fGetDate()
			WHERE 
				Id = @rUserId
			SET @lResultCode = 1
	END
	ELSE
	BEGIN
		SET @lResultCode = -201	
	END
	SELECT @lResultCode AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserPasswordValidate]
	@rOrgId smallint,
	@rLoginTitle [nvarchar](20),
	@rLoginPassword [nvarchar](100)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN		

DECLARE @lUserId SmallInt

SELECT @lUserId = 
	(SELECT 
		Id 
	FROM 
		sSecurity.tUser 
	WHERE 
		LoginTitle = @rLoginTitle AND LoginPassword = @rLoginPassword AND OrgId = @rOrgId)
		
		
SELECT ISNULL(@lUserId, 0) AS UserId
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserPolicyAdd]
        @rUserId bigint,
		@rTimePolicyId int,
		@rIpPolicyId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	DELETE FROM  sSecurity.tUserPolicy WHERE UserId = @rUserId
	INSERT INTO sSecurity.tUserPolicy
		(UserId,TimePolicyId,IpPolicyId)
	VALUES
		(@rUserId,@rTimePolicyId,@rIpPolicyId)
		SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pUserPolicyGet]

	@rUserId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			UP.UserId,ISNULL(UP.TimePolicyId,0) AS TimePolicyId, ISNULL(UP.IpPolicyId,0) AS IpPolicyId
	FROM 
			sSecurity.tUserPolicy UP
	WHERE 
		(UP.UserId = @rUserId)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserPreferenceAdd]
	@rOrgId smallint,
	@rUserId [bigint],
	@rScreenId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUserPreference', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sSecurity.tUserPreference
		(
			Id,
			UserId,
			FavoriteScreenId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rUserId,
			@rScreenId,
			@rUserId,
			sCommon.fGetDate(),
			@rUserId,
			sCommon.fGetDate(),
			@rOrgId
		)
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserPreferenceDel]
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DELETE FROM sSecurity.tUserPreference
	WHERE UserId = @rUserId	
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserPreferenceGet] 
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			UserId,
			FavoriteScreenId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sSecurity.tUserPreference
	  WHERE ((Id = @rId) OR (@rId = 0))	  		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserPreferenceHomeScreenGet]	
	
	@rUserId [bigint] = 0,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
     select  
         S.Page + '?MenuID=' +CONVERT(Nvarchar(50),M.Id) AS PagePath    
          
     from sSecurity.tScreen S  
     INNER JOIN sSecurity.tMenu M ON M.ScreenId = S.Id AND S.IsObsolete = 0 AND M.IsObsolete = 0 
     INNER JOIN sSecurity.tUserPreference  UP ON UP.FavoriteScreenId =  S.Id 

     Where   UserId = @rUserId  AND OrgId = @rOrgId
		 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserPreferenceModify]
	@rUserId [bigint],
	@rScreenId [nvarchar](20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lResultCode Int
	SET @lResultCode = 0
	IF EXISTS(SELECT 1 FROM sSecurity.tUserPreference WHERE UserId = @rUserId)
	BEGIN
	 UPDATE sSecurity.tUserPreference
		SET 
			FavoriteScreenId = @rScreenId,
			UpdatedUserId = @rUserId,
			UpdatedDateTime = sCommon.fGetDate()
	  WHERE UserId = @rUserId
	  SET @lResultCode = 2
	END
	
	SELECT @lResultCode AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserProfileAdd]
	@rUserId [int],
	@rElectronicSignature [varbinary](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

 

BEGIN

      IF EXISTS(SELECT Id FROM sSecurity.tUserProfile WHERE UserId = @rUserId)

            BEGIN

                  SELECT -1 AS Result

            END

      ELSE

      BEGIN

 

      DECLARE @lNextNumber INT

      EXECUTE sCommon.pTableRowIdGet 'sSecurity.tUserProfile', 0, 1, 1,@outNextNumber = @lNextNumber output

 

      INSERT INTO sSecurity.tUserProfile

            (

                  Id,

                  UserId,

                  ElectronicSignature

            )

      VALUES

            (

                  @lNextNumber,

                  @rUserId,

                  @rElectronicSignature

            )

     SELECT @lNextNumber AS Result

    END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserProfileModify]
	@rUserId [int],
	@rElectronicSignature [varbinary](max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lResultCode Int
	SET @lResultCode = -1
	IF EXISTS(SELECT 1 FROM sSecurity.tUserProfile WHERE UserId = @rUserId)
	BEGIN
	 UPDATE sSecurity.tUserProfile
		SET 
			ElectronicSignature = @rElectronicSignature
	  WHERE UserId = @rUserId
	  SET @lResultCode = 2
	END
	
	SELECT @lResultCode AS Result
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserRemove]
	@rUserId [bigint],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	DECLARE @lCurrentDateTime DATETIME
	EXECUTE @lCurrentDateTime = sCommon.fGetDate	
	
	UPDATE sSecurity.tUser
	SET				
		IsObsolete = @rIsObsolete,			
		UpdatedUserId = @rUpdatedUserId,
		UpdatedDateTime = @lCurrentDateTime			
	WHERE 
		Id = @rUserId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserRoleAdd]
  
	@rUserId [bigint],
	@rMapping [nvarchar](max),
	@rCreatedUserId [bigint],
	@rIsCommon bit
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT

DECLARE @lCurrentDateTime DateTime
SET @lCurrentDateTime = sCommon.fGetDate()

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rMapping
BEGIN
IF(@rIsCommon=1)
BEGIN
	DECLARE @lCount INT
	DECLARE @lLoginTitle nvarchar(100)

	SELECT @lLoginTitle=LoginTitle FROM sSecurity.tUser WHERE Id=@rUserId

	CREATE TABLE #tTable  
		(
			Id bigint identity,
			UserId bigint
		)
	INSERT INTO #tTable
		(
			UserId
		)
	SELECT Id FROM sSecurity.tUser WHERE LoginTitle=@lLoginTitle

	UPDATE sSecurity.tUserRole 
	SET IsObsolete = 1,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = @lCurrentDateTime
	WHERE UserID IN(SELECT UserId FROM #tTable)

				
	SELECT @lCount =  COUNT(Id) FROM #tTable

	WHILE @lCount > 0 

	BEGIN
		SELECT
				@rUserId=UserId
		FROM #tTable WHERE Id = @lCount
	INSERT INTO  sSecurity.tUserRole (RoleId, 
								UserId, 
								IsObsolete,
								IsPrimary,
								CreatedUserId,
								CreatedDateTime,
								UpdatedUserId,
								UpdatedDateTime)		
				SELECT RoleID, @rUserId, 0, IsPrimary, @rCreatedUserId, @lCurrentDateTime, @rCreatedUserId, @lCurrentDateTime
				FROM
				OPENXML (@loDoc, '/Items/Item', 2)
				WITH (
						RoleID INT,
						UserID BIGINT,
						IsAdded BIT,
						IsPrimary BIT) A
				WHERE IsAdded = 1
		SET @lCount = @lCount - 1	
	END
END
ELSE
BEGIN
	UPDATE sSecurity.tUserRole 
	SET IsObsolete = 1,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = @lCurrentDateTime
	WHERE UserID = @rUserId 


	INSERT INTO  sSecurity.tUserRole (RoleId, 
								UserId, 
								IsObsolete,
								IsPrimary,
								CreatedUserId,
								CreatedDateTime,
								UpdatedUserId,
								UpdatedDateTime)		
				SELECT RoleID, UserID, 0, IsPrimary, @rCreatedUserId, @lCurrentDateTime, @rCreatedUserId, @lCurrentDateTime
				FROM
				OPENXML (@loDoc, '/Items/Item', 2)
				WITH (
						RoleID INT,
						UserID BIGINT,
						IsAdded BIT,
						IsPrimary BIT) A
				WHERE IsAdded = 1 
END			
END
EXEC sp_xml_removedocument @loDoc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserRoleGet]
    @rOrgGroupId smallint,
	@rId [bigint] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT	Id,
			Title
			--TitleResourceKeyId
	FROM sSecurity.tRole WHERE OrgGroupId = @rOrgGroupId

	EXCEPT

	SELECT	sSecurity.tRole.Id,
			sSecurity.tRole.Title
			--sSecurity.tRole.TitleResourceKeyId
	FROM sSecurity.tUserRole
	INNER JOIN sSecurity.tRole 
		ON sSecurity.tUserRole.RoleId = sSecurity.tRole.ID
	WHERE sSecurity.tUserRole.UserId = @rId AND sSecurity.tUserRole.IsObsolete = 0 AND sSecurity.tRole.OrgGroupId = @rOrgGroupId
	
	SELECT	sSecurity.tRole.ID,
			sSecurity.tRole.Title
			--sSecurity.tRole.TitleResourceKeyId
	FROM sSecurity.tUserRole
	INNER JOIN sSecurity.tRole 
		ON sSecurity.tUserRole.RoleId = sSecurity.tRole.ID
	WHERE sSecurity.tUserRole.UserId = @rId AND sSecurity.tUserRole.IsObsolete = 0 AND sSecurity.tRole.OrgGroupId = @rOrgGroupId
	
	ORDER BY sSecurity.tUserRole.IsPrimary DESC
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserSearch]
	@rOrgId smallint,
	@rEmployeeCode [nvarchar](20),
	@rEmployeeName [nvarchar](300)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SELECT	Emp.Id,
		Emp.Code,
		Emp.FirstName,
		Emp.MiddleName,
		Emp.LastName,
		HIMSUser.Id AS EmployeeId,
		HIMSUser.DisplayTitle,
		HIMSUser.LoginTitle
-- Commented For Employee Migration		
--FROM sCommon.tEmployeeMaster Emp
-- End of comment for Employee Migration
-- Added for Employee Migration
FROM sHrm.vExtEmployeeMaster Emp
-- End of Addition for Employee Migration
LEFT OUTER JOIN sSecurity.tUser HIMSUser
	ON Emp.Id = HIMSUser.SourceId
WHERE Emp.Code LIKE '%' + @rEmployeeCode + '%' OR 
	  (Emp.FirstName LIKE '%' + @rEmployeeName + '%' OR Emp.LastName LIKE '%' + @rEmployeeName + '%' OR Emp.MiddleName LIKE '%' + @rEmployeeName + '%')
	   AND HIMSUser.OrgId = 	@rOrgId	  
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserSessionAdd]
	@rOrgId [smallint],
	@rDisplayTitle [nvarchar](100),
	@rLoginTitle [nvarchar](20),
	@rLoginPassword [nvarchar](100),
	@rIsObsolete [bit],
	--@rEmployeeId [int],
	@rUserSourceId bigint,
	@rUserSourceTypeId int,
	@rCreatedUserId [bigint],
	@rValidUpto date,
	@rIsCommon bit
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rUserSourceTypeId=0)
	BEGIN
		SET @rUserSourceId=NULL
		SET @rUserSourceTypeId=NULL
	END
	
	IF((@rUserSourceTypeId <> 1 OR @rUserSourceId<>0))
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceTypeId = @rUserSourceTypeId AND SourceId = @rUserSourceId AND OrgId=@rOrgId)
		BEGIN
			SELECT -1 AS UserId
			RETURN
		END
	END
	
	IF(@rIsCommon=0)
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rLoginTitle AND OrgId = @rOrgId)
		BEGIN
			SELECT -1 AS UserId
			RETURN
		END
	END
	IF(@rIsCommon=1)
	BEGIN
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE DisplayTitle = @rDisplayTitle OR LoginTitle = @rLoginTitle)
		BEGIN
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceId != NULL AND SourceTypeId != NULL)
			BEGIN
				SELECT -1 AS UserId
				RETURN
			END
			ELSE IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE (DisplayTitle = @rDisplayTitle OR LoginTitle = @rLoginTitle) AND OrgId=@rOrgId)
			BEGIN
				SELECT -1 AS UserId
				RETURN
			END
		END
	END
	
	DECLARE @lNextNumber BIGINT	
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output
	
	DECLARE @lCurrentDateTime DATETIME
	EXECUTE @lCurrentDateTime = sCommon.fGetDate		

		INSERT INTO sSecurity.tUser
			(
				Id,		
				DisplayTitle,
				LoginTitle,
				LoginPassword,
				LastLockOutDate,
				NumberOfLogonAttempt,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				--EmployeeId,
				OrgId,
				SourceId,
				SourceTypeId,
				ValidUpto,
				IsCommon
			)
		VALUES
			(
				@lNextNumber,
				@rDisplayTitle,					
				@rLoginTitle,
				@rLoginPassword,
				@lCurrentDateTime,
				0,
				@rIsObsolete,
				@rCreatedUserId,
				@lCurrentDateTime,
				@rCreatedUserId,
				@lCurrentDateTime,
				--@rEmployeeId,
				@rOrgId,
				@rUserSourceId,
				@rUserSourceTypeId,
				@rValidUpto,
				@rIsCommon
			)
			
			
			IF(@rUserSourceTypeId=1  OR  @rUserSourceTypeId=95)
			BEGIN
			IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserOrganization WHERE UserId = @lNextNumber AND OrgId = @rOrgId)
			BEGIN
			INSERT INTO sSecurity.tUserOrganization
			SELECT @rOrgId,@lNextNumber
			END
			END
			
			
	SELECT @lNextNumber AS UserId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserSessionGet]
	@rOrgId smallint,
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id,
			DisplayTitle,
			LoginTitle,
			LoginPassword,
			LastLockOutDate,
			NumberOfLogonAttempt,
			--IsOnline,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
	   FROM sSecurity.tUser
	  WHERE ((Id = @rId) OR (@rId = 0))
	  AND OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserSessionIdModify]
	@rOrgId [smallint],
	@rUserId [bigint],
	@rSessionId [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN		

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserSessionIdModify Start', 
	'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserSessionIdModify')
END

	DECLARE @lCurrentDateTime DATETIME
	EXECUTE @lCurrentDateTime = sCommon.fGetDate		
	BEGIN
			UPDATE sSecurity.tUser WITH (ROWLOCK)
			SET	
				SessionId = @rSessionId,				
				LastLockOutDate = @lCurrentDateTime,
				UpdatedDateTime = @lCurrentDateTime,
				NumberOfLogonAttempt = 0		
			WHERE 
				Id = @rUserId AND
				OrgId = @rOrgId
				
				
	END		
IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserSessionIdModify End', 
	'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserSessionIdModify')
END
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pUserSessionPaymentAdd] 
			@rUserSessionId nvarchar(500)
           ,@rAcademicId bigint
           ,@rAccountId int
           ,@rAffiliationId int
           ,@rAffiliationTypeId int
           ,@rBackPageUrl nvarchar(500)
           ,@rBatchFromDate date
           ,@rBatchId nvarchar(500)
           ,@rBatchTitle nvarchar(500)
           ,@rBatchToDate date
           ,@rCurrentScreenId int
           ,@rDepartmentId int
           ,@rDisplayTitle nvarchar(500)
           ,@rGenderId int
           ,@rHomePageUrl nvarchar(500)
           ,@rIsImpersonate bit
           ,@rLocationId int
           ,@rLocationName nvarchar(500)
           ,@rLogitle nvarchar(500)
           ,@rMenuId int
           ,@rOrgDisplayTitle nvarchar(500)
           ,@rOrgGroupBatchId int
           ,@rOrgGroupId int
           ,@rOrgId int
           ,@rOriginalUserId bigint
           ,@rPageName nvarchar(500)
           ,@rRoleId int
           ,@rScreenID int
           ,@rSessionId nvarchar(500)
           ,@rStoreLocationId int
           ,@rStoreLocationName nvarchar(500)
           ,@rUserDepartment nvarchar(500)
           ,@rUserFullName nvarchar(500)
           ,@rUserId bigint
           ,@rUserIdNo nvarchar(500)
           ,@rUserNo int
           ,@rUserPhoto varbinary(max)
           ,@rUserSourceId bigint
           ,@rUserSourceTypeId int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

INSERT INTO [sSecurity].[tUserSession]
           ([UserSessionId]
           ,[UserSeeionDateTime]
           ,[AcademicId]
           ,[AccountId]
           ,[AffiliationId]
           ,[AffiliationTypeId]
           ,[BackPageUrl]
           ,[BatchFromDate]
           ,[BatchId]
           ,[BatchTitle]
           ,[BatchToDate]
           ,[CurrentScreenId]
           ,[DepartmentId]
           ,[DisplayTitle]
           ,[GenderId]
           ,[HomePageUrl]
           ,[IsImpersonate]
           ,[LocationId]
           ,[LocationName]
           ,[Logitle]
           ,[MenuId]
           ,[OrgDisplayTitle]
           ,[OrgGroupBatchId]
           ,[OrgGroupId]
           ,[OrgId]
           ,[OriginalUserId]
           ,[PageName]
           ,[RoleId]
           ,[ScreenID]
           ,[SessionId]
           ,[StoreLocationId]
           ,[StoreLocationName]
           ,[UserDepartment]
           ,[UserFullName]
           ,[UserId]
           ,[UserIdNo]
           ,[UserNo]
           ,[UserPhoto]
           ,[UserSourceId]
           ,[UserSourceTypeId])
     VALUES
           (@rUserSessionId
           ,GETDATE()
           ,@rAcademicId
           ,@rAccountId
           ,@rAffiliationId
           ,@rAffiliationTypeId
           ,@rBackPageUrl
           ,@rBatchFromDate
           ,@rBatchId
           ,@rBatchTitle
           ,@rBatchToDate
           ,@rCurrentScreenId
           ,@rDepartmentId
           ,@rDisplayTitle
           ,@rGenderId
           ,@rHomePageUrl
           ,@rIsImpersonate
           ,@rLocationId
           ,@rLocationName
           ,@rLogitle
           ,@rMenuId
           ,@rOrgDisplayTitle
           ,@rOrgGroupBatchId
           ,@rOrgGroupId
           ,@rOrgId
           ,@rOriginalUserId
           ,@rPageName
           ,@rRoleId
           ,@rScreenID
           ,@rSessionId
           ,@rStoreLocationId
           ,@rStoreLocationName
           ,@rUserDepartment
           ,@rUserFullName
           ,@rUserId
           ,@rUserIdNo
           ,@rUserNo
           ,@rUserPhoto
           ,@rUserSourceId
           ,@rUserSourceTypeId)






   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[sSecurity].[pUserSessionPaymentGet] 1101000000003
CREATE OR ALTER PROCEDURE [sSecurity].[pUserSessionPaymentGet] 
	@rUserId BIGINT=1101000000003
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	

SELECT TOP 1 [AutoId]
      ,[UserSessionId]
      ,[UserSeeionDateTime]
      ,[AcademicId]
      ,[AccountId]
      ,[AffiliationId]
      ,[AffiliationTypeId]
      ,[BackPageUrl]
      ,[BatchFromDate]
      ,[BatchId]
      ,[BatchTitle]
      ,[BatchToDate]
      ,[CurrentScreenId]
      ,[DepartmentId]
      ,[DisplayTitle]
      ,[GenderId]
      ,[HomePageUrl]
      ,[IsImpersonate]
      ,[LocationId]
      ,[LocationName]
      ,[Logitle]
      ,[MenuId]
      ,[OrgDisplayTitle]
      ,[OrgGroupBatchId]
      ,[OrgGroupId]
      ,[OrgId]
      ,[OriginalUserId]
      ,[PageName]
      ,[RoleId]
      ,[ScreenID]
      ,[SessionId]
      ,[StoreLocationId]
      ,[StoreLocationName]
      ,[UserDepartment]
      ,[UserFullName]
      ,[UserId]
      ,[UserIdNo]
      ,[UserNo]
      ,[UserPhoto]
      ,[UserSourceId]
      ,[UserSourceTypeId]
  FROM [sSecurity].[tUserSession]

  WHERE [UserId]=@rUserId
  ORDER BY [UserSeeionDateTime] DESC


   
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserValidate]
	@rOrgId int,
	@rUserTitle [nvarchar](100),
	@rUserPassword [nvarchar](1000),
	@rHostAddress [nvarchar](100),	
	@rSessionId [nvarchar](100),
	@rLocalAddress [nvarchar](100)='',
	@rOSTypeId [tinyint]=0,
	@rDeviceUniqueId [nvarchar](100)=''
	
WITH EXECUTE AS CALLER
AS

DECLARE @lIsLogEnable bit = 0

DECLARE @lUserId BIGINT
SET @lUserId = 0

DECLARE @lSourceTypeId SMALLINT
SET @lSourceTypeId = 0

DECLARE @lLoginAttempts INT	
SET @lLoginAttempts = 0

DECLARE @lLoginDateTime DateTime
SET @lLoginDateTime = sCommon.fGetDate()

DECLARE @lLastLockoutDate DateTime
SET @lLastLockoutDate = NULL

DECLARE @lValidUpto Date
SET @lValidUpto = NULL


DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId=OrgGroupId  FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

DECLARE @lItemValue nvarchar(20) = ''
SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
FROM sConfig.tConfigurationMaster CM
LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
AND SourceTypeId = 2010 AND SourceId = @rOrgId WHERE CM.Id = 224

DECLARE @lTimePolicyId int
DECLARE @lIpPolicyId int
DECLARE @lAccessTime nvarchar(300)

DECLARE @lTimePolicy TABLE(Id int identity, AccessTime nvarchar(100))
DECLARE @lIpPolicyDetail TABLE(IP nvarchar(100))

IF(@rOSTypeId = 0)
BEGIN
	SET @rOSTypeId =3
END

SET NOCOUNT ON

BEGIN

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserValidate Start', 
	'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
	+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserValidate')
END

	SELECT 
		@lUserId = Id,
		@lValidUpto = ValidUpto,
		@lSourceTypeId = ISNULL(SourceTypeId,0)
	FROM sSecurity.tUser WITH (NOLOCK)
	WHERE 
		    UPPER(LoginTitle) = UPPER(@rUserTitle) AND
		   	(LoginPassword = @rUserPassword  OR @rUserPassword = '')  AND 
			NumberOfLogonAttempt <= 5000 AND
			IsObsolete = 0 AND
			OrgId = @rOrgId
	
	IF(@rSessionId = 'AndroidSession' AND (@lSourceTypeId = 0 OR @lSourceTypeId=1))
	BEGIN
		RAISERROR('Invalid User', 16, 1)
		
		IF(@lIsLogEnable = 1)
		BEGIN
			INSERT INTO [sSystem].[tTraceLog]
			(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
			VALUES
			('sSecurity.pUserValidate', 
			'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
			+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
			'Invalid User', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
		END

		RETURN
	END
			
	IF @lUserId > 0
		BEGIN
			
			SELECT 
				@lTimePolicyId = TimePolicyId ,@lIpPolicyId = IpPolicyId 
			FROM sSecurity.tUserPolicy 
				WHERE  UserId = @lUserId
			
			IF(@lTimePolicyId IS NOT NULL AND @lTimePolicyId !=0)	
			BEGIN
				SELECT @lAccessTime = AccessTime FROM sSecurity.tTimePolicy	WHERE  Id = @lTimePolicyId
				INSERT @lTimePolicy SELECT * FROM sCommon.fnSplit(@lAccessTime,',')
				DECLARE @lCount int 
				SELECT @lCount = COUNT(AccessTime) FROM @lTimePolicy
				DECLARE @LoopCounter INT = 1
				DECLARE @lIsValid bit = 0
				
				WHILE (@LoopCounter <= @lCount)
				BEGIN
						
					DECLARE @lTime nvarchar(100)
					SELECT @lTime = AccessTime FROM @lTimePolicy WHERE Id = @LoopCounter
					DECLARE @lFromTime nvarchar(100)
					DECLARE @lToTime nvarchar(100)
					SELECT @lFromTime = SUBSTRING(@lTime, 1, 5 )
					SELECT @lToTime = SUBSTRING(@lTime, 7, 10 )
					IF(CONVERT(time,getdate()) BETWEEN CONVERT(time,@lFromTime) AND CONVERT(time,@lToTime))
					BEGIN	
						SET @lIsValid = 1
					END 
					ELSE IF(@lIsValid=0)
					BEGIN 
						RAISERROR('Not allowed due to time policy constrain', 16, 1)

						IF(@lIsLogEnable = 1)
						BEGIN
							INSERT INTO [sSystem].[tTraceLog]
							(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
							VALUES
							('sSecurity.pUserValidate', 
							'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
							+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
							'Not allowed due to time policy constrain', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
						END

						RETURN
					END 
					 SET @LoopCounter  = @LoopCounter  + 1
				END
			END
			
			IF(@lIpPolicyId IS NOT NULL AND @lIpPolicyId !=0)	
			BEGIN
				
				INSERT @lIpPolicyDetail SELECT IP FROM sSecurity.tIpPolicyDetail WHERE  IpPolicyId = @lIpPolicyId
				
				IF(@lItemValue='False')
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM @lIpPolicyDetail WHERE IP = @rHostAddress)
					BEGIN 
						RAISERROR('Not allowed due to ip policy constrain', 16, 1)

						IF(@lIsLogEnable = 1)
						BEGIN
							INSERT INTO [sSystem].[tTraceLog]
							(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
							VALUES
							('sSecurity.pUserValidate', 
							'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
							+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
							'Not allowed due to ip policy constrain', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
						END

						RETURN
					END
				END
				ELSE
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM @lIpPolicyDetail WHERE IP = @rLocalAddress)
					BEGIN 
						RAISERROR('Not allowed due to ip policy constrain', 16, 1)

						IF(@lIsLogEnable = 1)
						BEGIN
							INSERT INTO [sSystem].[tTraceLog]
							(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
							VALUES
							('sSecurity.pUserValidate', 
							'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
							+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
							'Not allowed due to ip policy constrain - else', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
						END

						RETURN
					END
				END
			END
			
			IF(@lValidUpto IS NOT NULL)
			BEGIN
				IF(CONVERT(date, getdate()) > @lValidUpto)
				BEGIN
					RAISERROR('Your Account is expired', 16, 1)

					IF(@lIsLogEnable = 1)
					BEGIN
						INSERT INTO [sSystem].[tTraceLog]
						(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
						VALUES
						('sSecurity.pUserValidate', 
						'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
						+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
						'Your Account is expired', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
					END
					RETURN
				END
			END
			
			--UPDATE sSecurity.tUser
			--SET IsOnline = 1,
			--	NumberOfLogonAttempt = 0,			
			--	UpdatedDate = sCommon.fGetDate()
			--WHERE Id = @lUserId
			IF(@lUserId != 1 AND @rUserTitle != 'SysSuperAdmin')
			BEGIN
			EXECUTE sSecurity.pUserLogAdd @rOrgId, @lUserId, @rHostAddress, 1, @lLoginDateTime, NULL, 1, @rSessionId,@rLocalAddress,@rOSTypeId,@rDeviceUniqueId
			END
			--INSERT INTO sSecurity.tUserLog(UserId, LoggedInIp, LoggedInDateTime)
			--VALUES (@lUserId, @rHostAddress, sCommon.fGetDate())

	--		SELECT Id, Title, TitleResourceKey 
	--		FROM sSecurity.tRole 
	--		INNER JOIN sSecurity.tUserRole
	--			ON RoleId = Id
	--		WHERE UserId = @lUserId AND sSecurity.tRole.IsObsolete = 0
			
		 --   UPDATE E
			--SET E.StatusId = 9
			--FROM sHrm.tEmployeeMaster E
			--JOIN sHrm.tEmployeeJobDetail J ON E.Id = J.EmployeeId 
			--WHERE 
			----J.activeupto <= getdate() and 
			--E.orgID= @rOrgId 	    
		    SELECT @lUserId as UserId
			--SELECT @lUserId 
		END
	ELSE
		BEGIN 
		
			DECLARE @lUpdatedDateTime datetime
			DECLARE @lMinute int = 0 
			
			SELECT @lUserId = Id,
					@lLoginAttempts = NumberOfLogonAttempt,
					@lLastLockoutDate = LastLockOutDate,
					@lUpdatedDateTime = UpdatedDateTime
					
			FROM sSecurity.tUser WITH (NOLOCK)
			WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND 
					OrgId = @rOrgId
			IF @lUserId > 0
				BEGIN
				
					DECLARE @lIsSecurityPolicy nvarchar(20) = ''
					SELECT @lIsSecurityPolicy = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
					FROM sConfig.tConfigurationMaster CM
					LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
					AND SourceTypeId = 2010 AND SourceId = @rOrgId WHERE CM.Id = 207

					IF(@lIsSecurityPolicy='True')
					BEGIN
						SET @lMinute = DateDiff(s, @lUpdatedDateTime, sCommon.fGetDate())%3600/60
						
						IF(@lMinute <> 0 AND @lMinute >= 10)
						BEGIN
							UPDATE sSecurity.tUser WITH (ROWLOCK)
							SET	
							SessionId = @rSessionId,				
							LastLockOutDate = sCommon.fGetDate(),
							UpdatedDateTime = sCommon.fGetDate(),
							NumberOfLogonAttempt = 0		
							WHERE 
							Id = @lUserId AND OrgId = @rOrgId
							
							SELECT @lLoginAttempts = NumberOfLogonAttempt FROM sSecurity.tUser WITH (NOLOCK) WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
						END
					
						IF @lLoginAttempts >= 5
						BEGIN
							IF @lLastLockoutDate IS NULL
								BEGIN
									UPDATE sSecurity.tUser WITH (ROWLOCK)
									SET LastLockOutDate = sCommon.fGetDate(),
										UpdatedDateTime = sCommon.fGetDate()
									WHERE Id = @lUserId AND
										 OrgId = @rOrgId
								END
							RAISERROR('Your access is blocked temporary due to 5 consecutive failed login attempts, Please try after some time to login with correct credential.', 16, 1)


							IF(@lIsLogEnable = 1)
							BEGIN
								INSERT INTO [sSystem].[tTraceLog]
								(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
								VALUES
								('sSecurity.pUserValidate', 
								'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
								+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
								'Your access is blocked temporary due to 5 consecutive failed login attempts, Please try after some time to login with correct credential.', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
							END

							RETURN
						END
						ELSE
						BEGIN
							UPDATE sSecurity.tUser WITH (ROWLOCK)
							SET NumberOfLogonAttempt = NumberOfLogonAttempt + 1,
								UpdatedDateTime = sCommon.fGetDate()
							WHERE Id = @lUserId AND
								OrgId = @rOrgId
						END
					END
					
					--IF @lLoginAttempts > 250
					--	BEGIN
					--		IF @lLastLockoutDate IS NULL
					--			BEGIN
					--				UPDATE sSecurity.tUser
					--				SET LastLockOutDate = sCommon.fGetDate(),
					--					UpdatedDateTime = sCommon.fGetDate()
					--				WHERE Id = @lUserId AND
					--					 OrgId = @rOrgId
					--			END
					--		RAISERROR('User account locked', 16, 1)
					--		RETURN
					--	END
					--ELSE
					--	BEGIN
					--		UPDATE sSecurity.tUser
					--		SET NumberOfLogonAttempt = NumberOfLogonAttempt + 1,
					--			UpdatedDateTime = sCommon.fGetDate()
					--		WHERE Id = @lUserId AND
					--			OrgId = @rOrgId
					--	END
					
				END		

			RAISERROR('Username/password does not match or Inactive user.', 16, 1)	

			IF(@lIsLogEnable = 1)
			BEGIN
				INSERT INTO [sSystem].[tTraceLog]
				(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
				VALUES
				('sSecurity.pUserValidate', 
				'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
				+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
				'Username/password does not match or Inactive user.', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
			END	
		END

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserValidate End', 
	'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
	+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserValidate')
END

END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR 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
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserWithEmployeeDetailByRoleId_Delete]
	@rOrgId [int],
	@rRoleId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		U.Id AS UserId,		
		U.DisplayTitle AS DisplayTitle,
		U.LoginTitle AS LoginTitle,
		U.IsObsolete AS UserIsObsolete,
		E.Id AS EmployeeId,
		E.Code AS EmployeeCode,
		ISNULL(E.FirstName, '') + ' ' + ISNULL(E.MiddleName, '') + ' ' + ISNULL(E.LastName, '') AS EmployeeFullName,
		E.FirstName AS FirstName,
		E.MiddleName AS MiddleName,
		E.LastName AS LastName,
		-- Commented for Employee Migration	
		--E.EmployeeTypeId AS EmployeeTypeId,
		-- End of comment for Employee Migration
		--Added for Employee Migration
		EJD.EmployeeJobTitleId AS EmployeeTypeId,
		E.EmployeeTypeId AS EmployeeCategoryId,
		EPD.GenderId AS GenderId,
		EPD.DateOfBirth AS DateOfBirth,
		EA.DateOfJoining AS DateOfJoining,
		EC.PermanentAddressId AS PermanentAddressId,
		EC.PresentAddressId AS CommunicationAddressId,
		EC.PresentContactId AS CommunicationContactId,
		ECON.PhoneNumber AS PhoneNumberHome,
		EC.PhoneNoCompany AS PhoneNumberOffice,
		ECON.MobileNumber AS PhoneNumberMobile,
		EC.CompanyEmail AS EmailPrimary,
		ECON.Email AS EmailAlternative
		---- End of addition for Employee Migration
		-- Commented for Employee Migration	
		--E.EmployeeTypeId AS EmployeeTypeId,
		--E.EmployeeCategoryId AS EmployeeCategoryId,
		--E.GenderId AS GenderId,
		--E.DateOfBirth AS DateOfBirth,
		--E.DateOfJoining AS DateOfJoining,
		--E.PermanentAddressId AS PermanentAddressId,
		--E.CommunicationAddressId AS CommunicationAddressId,
		--E.CommunicationContactId AS CommunicationContactId,
		--EC.PhoneNumberHome,
		--EC.PhoneNumberOffice,
		--EC.PhoneNumberMobile,
		--EC.EmailPrimary,
		--EC.EmailAlternative
		-- END of comment for Employee Migration
	FROM 
		sSecurity.tUser U
			INNER JOIN sSecurity.tUserRole UR
				ON UR.UserId = U.Id															
			-- Commented for Employee Migration	
			--INNER JOIN sCommon.tEmployeeMaster E
			--	ON U.EmployeeId = E.Id								
			--LEFT JOIN sCommon.tEmployeeContact EC	
			--	ON E.CommunicationContactId = EC.Id				
			-- END of comment for Employee Migration
			--Added for Employee Migration
			INNER JOIN sHrm.vExtEmployeeMaster E
				ON U.SourceId = E.Id AND U.SourceTypeId=95
			INNER JOIN sHrm.vExtEmployeeJobDetail EJD
				ON E.Id = EJD.EmployeeId	
			INNER JOIN sHrm.tEmployeePersonalDetail EPD
				ON E.Id = EPD.EmployeeId
			INNER JOIN sHrm.vExtEmployeeAdministration EA
				ON E.Id = EA.EmployeeId	
			INNER JOIN sHrm.vExtEmployeeCommunication EC
				ON E.Id = EC.EmployeeId		
			LEFT OUTER JOIN sHrm.vExtEmployeeContact ECON
				ON EC.PresentContactId = ECON.Id		
			-- END of addition for Employee Migration
	WHERE 
		UR.RoleId = @rRoleId
	AND	UR.IsObsolete = 0	
	AND U.OrgId = @rOrgId
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pUserWithEmployeeDetailByUserId_Delete]
	@rOrgId [smallint],
	@rUserId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		U.Id AS UserId,	
		U.DisplayTitle AS DisplayTitle,	
		U.LoginTitle AS LoginTitle,
		E.Id AS EmployeeId,
		E.Code AS EmployeeCode,
		ISNULL(E.FirstName, '') + ' ' + ISNULL(E.MiddleName, '') + ' ' + ISNULL(E.LastName, '') AS EmployeeFullName,
		E.FirstName AS FirstName,
		E.MiddleName AS MiddleName,
		E.LastName AS LastName,
		--Added for Employee Migration
		EJD.EmployeeJobTitleId AS EmployeeTypeId,
		E.EmployeeTypeId AS EmployeeCategoryId,
		EPD.GenderId AS GenderId,
		EPD.DateOfBirth AS DateOfBirth,
		EA.DateOfJoining AS DateOfJoining,
		EC.PermanentAddressId AS PermanentAddressId,
		EC.PresentAddressId AS CommunicationAddressId,
		EC.PresentContactId AS CommunicationContactId,
		ECON.PhoneNumber AS PhoneNumberHome,
		EC.PhoneNoCompany AS PhoneNumberOffice,
		ECON.MobileNumber AS PhoneNumberMobile,
		EC.CompanyEmail AS EmailPrimary,
		ECON.Email AS EmailAlternative
		---- End of addition for Employee Migration
		-- Commented for Employee Migration
		--E.EmployeeTypeId AS EmployeeTypeId,
		--E.EmployeeCategoryId AS EmployeeCategoryId,
		--E.GenderId AS GenderId,
		--E.DateOfBirth AS DateOfBirth,
		--E.DateOfJoining AS DateOfJoining,
		--E.PermanentAddressId AS PermanentAddressId,
		--E.CommunicationAddressId AS CommunicationAddressId,
		--E.CommunicationContactId AS CommunicationContactId,
		--EC.PhoneNumberHome,
		--EC.PhoneNumberOffice,
		--EC.PhoneNumberMobile,
		--EC.EmailPrimary,
		--EC.EmailAlternative
		-- End of comment for Employee Migration
	FROM 
		sSecurity.tUser U
			-- Commented for Employee Migration	
			--INNER JOIN sCommon.tEmployeeMaster E
			--	ON U.EmployeeId = E.Id					
			--LEFT JOIN sCommon.tEmployeeContact EC	
			--	ON E.CommunicationContactId = EC.Id	
			-- End of comment for Employee Migration	
			--Added for Employee Migration
			INNER JOIN sHrm.vExtEmployeeMaster E
				ON U.SourceId = E.Id AND U.SourceTypeId=95	
			INNER JOIN sHrm.vExtEmployeeJobDetail EJD
				ON E.Id = EJD.EmployeeId	
			INNER JOIN sHrm.tEmployeePersonalDetail EPD
				ON E.Id = EPD.EmployeeId
			INNER JOIN sHrm.vExtEmployeeAdministration EA
				ON E.Id = EA.EmployeeId	
			INNER JOIN sHrm.vExtEmployeeCommunication EC
				ON E.Id = EC.EmployeeId		
			LEFT OUTER JOIN sHrm.vExtEmployeeContact ECON
				ON EC.PresentContactId = ECON.Id		
			-- End of addition for Employee Migration				
	WHERE 
		((U.ID = @rUserId) OR (@rUserId = 0))
		AND U.OrgId = @rOrgId
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sSecurity].[pValidateLoginCode]
@rCode varchar(100)
as
BEGIN
	DECLARE @res INT
	IF exists(SELECT 1 from sSecurity.tUser WHERE isnull(TempPasswordCode,'') = @rCode)
	BEGIN
		SELECT @res = 1
	END
	SELECT isnull(@res,0) AS res
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSecurity].[pValidateOTPForgotPassword]

	@rUserTitle nvarchar(100)='',
	@rUserMobileNumber nvarchar(50)='',
	@rOrgId int=0,
	@rOTP nvarchar(10)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	DECLARE @rUserSourceId bigint=0
	DECLARE @rUserId bigint=0
	DECLARE @rUserSourceTypeId smallint=0
	DECLARE @newpwd VARCHAR(100)
	SELECT @rUserId=Id,@rUserSourceId = SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
	
	IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId and TempPasswordCode = @rOTP)
	BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId  and TempPasswordCode = @rOTP and DATEDIFF(SECOND,OTPExpiryDate,GETDATE()) <0)
		BEGIN
			UPDATE sSecurity.tUser SET TempPasswordCode = NULL	WHERE Id = @rUserId  and TempPasswordCode = @rOTP		
			SELECT 1 AS Result ,'OTP Matched' AS [Message], @rUserId AS UserId
			RETURN
		END
		ELSE
		BEGIN
			SELECT -101 AS Result ,'OTP Expired' AS [Message],@rUserId AS UserId
			RETURN
		END
	END
	ELSE
	BEGIN
		SELECT -102 AS Result ,'OTP does not match' AS [Message],@rUserId AS UserId
		RETURN
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pValidateUserAuthentcationOTP]

	@rUserId bigint,
	@rOrgId int,
	@rOTP nvarchar(10)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId and TempPasswordCode = @rOTP)
	BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId  and TempPasswordCode = @rOTP and DATEDIFF(SECOND,OTPExpiryDate,GETDATE()) <0)
		BEGIN
			UPDATE sSecurity.tUser SET TempPasswordCode = NULL	WHERE Id = @rUserId  and TempPasswordCode = @rOTP		
			SELECT 1 AS Result ,'OTP Matched' AS [Message], @rUserId AS UserId
			RETURN
		END
		ELSE
		BEGIN
			SELECT -101 AS Result ,'OTP Expired' AS [Message],@rUserId AS UserId
			RETURN
		END
	END
	ELSE
	BEGIN
		SELECT -102 AS Result ,'OTP does not match' AS [Message],@rUserId AS UserId
		RETURN
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pValidateUserDetails]
@rUserName varchar(255),
@rEmail varchar(255),
@rOrgId int
as
begin
	DECLARE @lRes varchar(2000)='',@lUserId bigint,@lCode varchar(100),@lEmployeeId bigint,@lStudentId bigint=0
	SELECT @lUserId = Id from sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserName) AND
	  NumberOfLogonAttempt <= 5000 and IsObsolete = 0 and OrgId = @rOrgId
	
	IF @lUserId > 0
	BEGIN
		UPDATE sSecurity.tUser set TempPasswordCode = newid() WHERE Id = @lUserId
		SELECT @lCode = TempPasswordCode,@lRes = '',@lEmployeeId = SourceId from sSecurity.tUser where Id = @lUserId and SourceTypeId = 95
		SELECT @lCode = TempPasswordCode,@lRes = '', @lStudentId = SourceId from sSecurity.tUser where Id = @lUserId and SourceTypeId = 2003
		
		IF @lEmployeeId > 0
		BEGIN		
			IF exists (SELECT 1 from sHrm.tEmployeeCommunications WHERE EmployeeId = @lEmployeeId and isnull(CompanyEmail,'') = '')
			BEGIN
				update sHrm.tEmployeeCommunications set CompanyEmail = @rEmail WHERE EmployeeId = @lEmployeeId
				SELECT @lRes = ''
			END
			ELSE
			BEGIN
				if exists (SELECT 1 from sHrm.tEmployeeCommunications WHERE EmployeeId = @lEmployeeId and CompanyEmail = @rEmail)
				BEGIN
					SELECT @lRes = ''
				END
				else
				BEGIN
					SELECT @lRes = 'Invalid Email Address'
				END			
			END
		END
		ELSE IF @lStudentId>0
    	BEGIN
    	IF EXISTS (SELECT 1 from sStudent.tStudentCommunication WHERE StudentId = @lStudentId AND isnull(ParentEmail,'') = '')
			BEGIN
				UPDATE sStudent.tStudentCommunication set ParentEmail = @rEmail WHERE StudentId = @lStudentId
				SELECT @lRes = ''
			END
			ELSE
			BEGIN
				if exists (SELECT 1 from sStudent.tStudentCommunication WHERE StudentId = @lStudentId and ParentEmail = @rEmail)
				BEGIN
					SELECT @lRes = ''
				END
				else
				BEGIN
					SELECT @lRes = 'Invalid Email Address'
				END			
			END
    	
		END
		ELSE
		BEGIN
			SELECT @lRes = 'Invalid User Name'
		END
	END
	ELSE
	BEGIN
		SELECT @lRes = 'Invalid User Name'
	END
	SELECT @rEmail as Email,isnull(@lRes,'') as Res,isnull(@lEmployeeId,0) as EmployeeId,isnull(@lCode,'') as Code
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pValidateUserMobileDetails]
@rUserName VARCHAR(100),
@rMobileNumber VARCHAR(50),
@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lRes varchar(2000)='',@lUserId bigint,@lCode varchar(100),@lEmployeeId bigint,@lStudentId bigint=0
	SELECT @lUserId = Id from sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserName) AND
	  NumberOfLogonAttempt <= 5000 and IsObsolete = 0 and OrgId = @rOrgId
	
	IF @lUserId > 0
	BEGIN
		UPDATE sSecurity.tUser set TempPasswordCode = newid() WHERE Id = @lUserId
		SELECT @lCode = TempPasswordCode,@lRes = '',@lEmployeeId = SourceId from sSecurity.tUser where Id = @lUserId and SourceTypeId = 95
		SELECT @lCode = TempPasswordCode,@lRes = '', @lStudentId = SourceId from sSecurity.tUser where Id = @lUserId and SourceTypeId = 2003
		
		IF @lEmployeeId > 0
		BEGIN		
			IF exists (SELECT 1 from sHrm.tEmployeeCommunications WHERE EmployeeId = @lEmployeeId and isnull(@rMobileNumber,'') = '')
			BEGIN
				update sHrm.tEmployeeCommunications set MobileNumber = @rMobileNumber WHERE EmployeeId = @lEmployeeId
				SELECT @lRes = ''
			END
			ELSE
			BEGIN
				if exists (SELECT 1 from sHrm.tEmployeeCommunications WHERE EmployeeId = @lEmployeeId and MobileNumber = @rMobileNumber)
				BEGIN
					SELECT @lRes = ''
				END
				else
				BEGIN
					SELECT @lRes = 'Invalid Mobile Number'
				END			
			END
		END
		ELSE IF @lStudentId>0
    	BEGIN
    	IF EXISTS (SELECT 1 from sStudent.tStudentCommunication WHERE StudentId = @lStudentId AND isnull(ParentContactNo,'') = '')
			BEGIN
				UPDATE sStudent.tStudentCommunication set ParentContactNo = @rMobileNumber WHERE StudentId = @lStudentId
				SELECT @lRes = ''
			END
			ELSE
			BEGIN
				if exists (SELECT 1 from sStudent.tStudentCommunication WHERE StudentId = @lStudentId and ParentContactNo = @rMobileNumber)
				BEGIN
					SELECT @lRes = ''
				END
				else
				BEGIN
					SELECT @lRes = 'Invalid Mobile Number'
				END			
			END
    	
		END
		ELSE
		BEGIN
			SELECT @lRes = 'Invalid User Name'
		END
	END
	ELSE
	BEGIN
		SELECT @lRes = 'Invalid User Name'
	END
	SELECT @rMobileNumber as MobileNumber,isnull(@lRes,'') as Res,isnull(@lEmployeeId,0) as EmployeeId,isnull(@lCode,'') as Code
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pVerifyEmailIdForEmployeeOTP]

	@rOrgId int = 0,
	@rEmailId nvarchar(50), 
	@rEmployeeId bigint 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0
	DECLARE @lUserId bigint = 0,@lId Bigint = 0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(EC.EmployeeId), @lId = EC.EmployeeId
	FROM sHrm.tEmployeeCommunications EC 
	INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id 
	INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId=95
	WHERE EC.CompanyEmail = @rEmailId AND EM.OrgId=@rOrgId  AND EC.EmployeeId = @rEmployeeId
	GROUP BY EC.EmployeeId
	
	IF(@lCount > 0)
	BEGIN
	
		EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
		UPDATE sSecurity.tUser 
		SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
		WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95
		
		SELECT 1 AS Result,'' AS [Message], TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
		WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95

	END

	ELSE
	BEGIN 
		SELECT -102 AS Result,'EmailId is wrong' AS [Message],'' AS OTP, 0 AS UserId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pVerifyEmailIdForOTP]

	@rOrgId int = 0,
	@rBatchId int =0,
	@rEmailId nvarchar(50), 
	@rAcademicId bigint 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0 
	DECLARE @lUserId bigint =0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(SC.StudentId) 
	FROM  sStudent.tStudentCommunication SC
	INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
	INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
	WHERE SC.ParentEmail = @rEmailId  AND A.BatchId = @rBatchId AND A.OrgId=@rOrgId  AND A.Id = @rAcademicId
	GROUP BY SC.StudentId

	IF(@lCount > 0)
	BEGIN
	
		SELECT SC.StudentId  INTO #UserId FROM  sStudent.tStudentCommunication SC
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
		INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
		WHERE SC.ParentEmail = @rEmailId AND A.BatchId = @rBatchId AND A.OrgId=@rOrgId AND A.Id = @rAcademicId
		
		SELECT @lUserId = StudentId FROM #UserId
		EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
		UPDATE sSecurity.tUser 
		SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
		WHERE SourceId = @lUserId AND OrgId = @rOrgId AND SourceTypeId = 2003
		
		SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
		WHERE SourceId = @lUserId AND OrgId = @rOrgId	

		DROP Table #UserId
	END

	ELSE
	BEGIN 
		SELECT -102 AS Result,'Email Id is wrong' AS [Message],'' AS OTP, 0 AS UserId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pVerifyMobileNumberForEmployeeOTP]

	@rOrgId int = 0,
	@rMobileNumber nvarchar(50), 
	@rEmployeeId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0
	DECLARE @lUserId bigint = 0,@lId Bigint = 0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(EC.EmployeeId), @lId = EC.EmployeeId
	FROM sHrm.tEmployeeCommunications EC 
	INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id 
	INNER JOIN sSecurity.tUser U ON U.SourceId = EC.EmployeeId AND U.SourceTypeId=95
	WHERE EC.MobileNumber = @rMobileNumber AND EM.OrgId=@rOrgId  AND EC.EmployeeId = @rEmployeeId
	GROUP BY EC.EmployeeId
	
	
	IF(@lCount > 0)
	BEGIN
	
		EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
		UPDATE sSecurity.tUser 
		SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
		WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95
		
		SELECT 1 AS Result,'' AS [Message], TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
		WHERE SourceId = @lId AND OrgId = @rOrgId AND SourceTypeId = 95

	END

	ELSE
	BEGIN 
		SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP, 0 AS UserId
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSecurity].[pVerifyMobileNumberForOTP]

	@rOrgId int = 0,
	@rBatchId int =0,
	@rMobileNumber nvarchar(50), 
	@rAcademicId bigint 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount int = 0
	DECLARE @lUserId bigint =0
	DECLARE @newpwd VARCHAR(100) 

	SELECT @lCount = COUNT(SC.StudentId) 
	FROM  sStudent.tStudentCommunication SC
	INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
	INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
	WHERE SC.ParentContactNo = @rMobileNumber  
	--AND A.BatchId = @rBatchId    -- No Need as per mantis 0027903
	AND A.OrgId=@rOrgId  AND A.Id = @rAcademicId
	GROUP BY SC.StudentId
	
		IF(@lCount > 0)
		BEGIN
		
			SELECT SC.StudentId  INTO #UserId FROM  sStudent.tStudentCommunication SC
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SC.StudentId
			INNER JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			WHERE SC.ParentContactNo = @rMobileNumber 
			--AND A.BatchId = @rBatchId		-- No Need as per mantis 0027903
			AND A.OrgId=@rOrgId AND A.Id = @rAcademicId
		
			--END
			--SELECT * FROM #UserId
			SELECT @lUserId = StudentId FROM #UserId
			EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
			UPDATE sSecurity.tUser 
			SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
			WHERE SourceId = @lUserId AND OrgId = @rOrgId AND SourceTypeId = 2003
		
			SELECT 1 AS Result,'' AS [Message], TempPasswordCode AS OTP,Id AS UserId FROM sSecurity.tUser 
			WHERE SourceId = @lUserId AND OrgId = @rOrgId

			DROP Table #UserId
		END

		ELSE
		BEGIN 
			SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP, 0 AS UserId
		END
		
	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[pVerifyOTP]

	@rUserMobileNumber nvarchar(50)='',
	@rOrgId int=0,
	@rOTP nvarchar(10)='',
	@rUserId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;
BEGIN
	
	DECLARE @rUserSourceId bigint=0
	
	DECLARE @newpwd VARCHAR(100)
	DECLARE @LoginTitle nvarchar(100)
	DECLARE @LoginPassword nvarchar(200)
	
	SELECT @rUserSourceId = SU.SourceId 
	FROM sSecurity.tUser SU WHERE OrgId = @rOrgId AND SourceTypeId = 2003 AND Id = @rUserId
	print @rUserSourceId
	IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId and TempPasswordCode = @rOTP)
	BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId  and TempPasswordCode = @rOTP and DATEDIFF(SECOND,OTPExpiryDate,GETDATE()) <0)
		BEGIN
			SELECT @LoginTitle= LoginTitle  , @LoginPassword = LoginPassword FROM sSecurity.tUser Where ID = @rUserId and TempPasswordCode=@rOTP
			UPDATE sSecurity.tUser SET TempPasswordCode = NULL	WHERE Id = @rUserId  and TempPasswordCode = @rOTP		
			SELECT 1 AS Result ,'OTP Matched' AS [Message],@LoginTitle As UserName , @LoginPassword As 'Password'
			RETURN
		END
		ELSE
		BEGIN
			SELECT -101 AS Result ,'OTP Expired' AS [Message],@rUserId AS UserId
			RETURN
		END
	END
	ELSE
	BEGIN
		SELECT -102 AS Result ,'OTP does not match' AS [Message],@rUserId AS UserId
		RETURN
	END
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSecurity].[tResourceTypeGet]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SELECT Id,Title,IsObsolete FROM sSecurity.tResourceTypeMaster WHERE IsObsolete = 0 ORDER BY Id

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSetup].[pBatchAdminUpdate]
	
	@rOrgGroupId int, 
	@rOrgId int,
	@rBatchGroupId int,
	@rBatchId int,
	@rIsHistory bit=0,
	@rFromActionId int, 
	@rUpdatedUserId bigint,
	@rIsLock bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
BEGIN
	
	 IF (@rFromActionId = 1) -- For Active
		BEGIN
			UPDATE sSetup.tBatchMaster SET IsActive = 0 WHERE OrgId = @rOrgId
			UPDATE sSetup.tBatchMaster SET IsActive = 1,IsHistory = 0,UpdatedUserId=@rUpdatedUserId,UpdatedDateTime=sCommon.fGetDate() WHERE OrgId = @rOrgId AND Id = @rBatchId
		END
	 ELSE IF (@rFromActionId = 2) -- For In Context
		BEGIN
			UPDATE sSetup.tBatchMaster SET IsInContext = 0 WHERE OrgId = @rOrgId AND OrgGroupBatchId = @rBatchGroupId
			UPDATE sSetup.tBatchMaster SET IsInContext = 1,UpdatedUserId=@rUpdatedUserId,UpdatedDateTime=sCommon.fGetDate() WHERE OrgId = @rOrgId AND Id = @rBatchId
		END
	 ELSE IF (@rFromActionId = 3) -- For In History
		BEGIN
			UPDATE sSetup.tBatchMaster SET IsHistory = @rIsHistory,UpdatedUserId=@rUpdatedUserId,UpdatedDateTime=sCommon.fGetDate() WHERE OrgId = @rOrgId AND Id = @rBatchId
		END
	 ELSE IF (@rFromActionId = 4) -- For Lock
		BEGIN
			UPDATE sSetup.tBatchMaster SET IsLock = @rIsLock,UpdatedUserId=@rUpdatedUserId,UpdatedDateTime=sCommon.fGetDate() WHERE OrgId = @rOrgId AND Id = @rBatchId
		END

		SELECT 1 AS Result
END
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSetup].[pBatchClassAdd]
	 
	@rBatchId int,
	@rClassId int,
	@rIsObsolete bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 --DECLARE @lNextNumber BIGINT
	 --SET @lNextNumber = @rBatchId 
	--EXECUTE sCommon.pTableRowIdGet 0, 'sSetup.tBatchClass', 0, 1, 1,@outNextNumber = @lNextNumber output 
	If(@rIsObsolete=1)
	BEGIN
		Delete from sSetup.tBatchClass where BatchId=@rBatchId AND ClassId=@rClassId
	END	
	ELSE
	BEGIN
		If Exists(select @rBatchId from sSetup.tBatchClass where BatchId=@rBatchId AND ClassId=@rClassId)
		BEGIN
			SELECT @rBatchId AS Result
			RETURN
		END 
		
		INSERT INTO sSetup.tBatchClass
		(
			BatchId,
			ClassId 
		)
		VALUES
		(
			@rBatchId,
			@rClassId
		)		
	END 	            
	--ELSE
	--BEGIN
	--    --SET @lNextNumber = @rBatchId
	--	UPDATE  sSetup.tBatchClass
	--	SET
	--		ClassId=@rClassId
	--    WHERE BatchId = @rBatchId AND ClassId = @rClassId 	   
	--END  
		SELECT @rBatchId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sSetup].[pBatchClassGet]
          
           @rBatchId int,
           @rOrgId smallint
           
AS
SET NOCOUNT ON

BEGIN
	SELECT  Batch=(Select Title from sSetup.tBatchMaster where Id=@rBatchId),
			CM.Id as ClassId,
			CM.Title as Class,
			CASE WHEN BC.BatchId Is Null THEN 'False' ELSE 'True' END AS IsObsolete,
			ISNULL(BC.IsBatchClassActive,0) as IsBatchClassActive
		
  FROM sSetup.tClassMaster CM
	LEFT JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId AND BC.BatchId=@rBatchId
  WHERE 
	CM.OrgId=@rOrgId
	order by CM.OrderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSetup].[pBatchClassLectureAdd]
	@rBatchClassLectureDetailXml [nvarchar](max),
	@rBatchId int,
	@rClassId int
	--@rSubjectId int,
	--@rLectureHoursPerWeek decimal(6,2),
	--@rLabHoursPerWeek decimal(6,2)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rBatchClassLectureDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	
	 DELETE FROM sSetup.tBatchClassLecture
				 WHERE ClassId=@rClassId AND BatchId=@rBatchId
	 
	 INSERT INTO sSetup.tBatchClassLecture
		(
			BatchId,
			ClassId,
			SubjectId,
			LectureHoursPerWeek,
			LabHoursPerWeek
			)
		SELECT
		
			BatchId,
			ClassId,
			SubjectId,
			LectureHoursPerWeek,
			LabHoursPerWeek
		FROM OPENXML (@loDoc, '/Table/BatchClassLectureDetail', 1)
		WITH ( 
				BatchId int,
				ClassId int,
				SubjectId int,
				LectureHoursPerWeek decimal(6,2),
				LabHoursPerWeek decimal(6,2)
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSetup].[pBatchClassLectureListGet]
          
           @rClassId int,
           @rOrgId smallint,
           @rBatchId int
 
AS
SET NOCOUNT ON

BEGIN

SELECT 
      -- ISNULL(CS.Id,0) AS ClassSubjectId
	   ISNULL(CS.SubjectId,0) AS SubjectId
	  ,ISNULL(S.Title,'') AS Subject 
     -- ,ISNULL(CS.IsObsolete,0) AS IsObsolete
      ,(CASE WHEN BL.SubjectId Is Null THEN 'False' ELSE 'True' END) AS Selected 
      ,ISNUll(BL.LectureHoursPerWeek,0) AS LectureHoursPerWeek
      ,ISNUll(BL.LabHoursPerWeek,0) AS LabHoursPerWeek
	 ,CS.ClassId
 
FROM sSetup.tClassSubject CS
      INNER JOIN [sSetup].[tSubjectMaster] S ON S.Id=CS.SubjectId 
	  LEFT JOIN [sSetup].[tBatchClassLecture] BL 
	  ON  CS.SubjectId= BL.SubjectId AND BL.ClassId=@rClassId  AND BL.BatchId=@rBatchId
	  
WHERE (CS.OrgId=@rOrgId) 
      AND CS.ClassId=@rClassId	 
	  ORDER by selected desc
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSetup].[pBatchClassUpdate]
	
	@rClassId int,
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
BEGIN
	
		UPDATE sSetup.tBatchClass SET IsBatchClassActive = 0 WHERE ClassId = @rClassId
		UPDATE sSetup.tBatchClass SET IsBatchClassActive = 1 WHERE ClassId = @rClassId AND BatchId = @rBatchId
	 
		SELECT 1 AS Result
END
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSetup].[pBatchFromOrganization]
	 
	
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	select * from [sSetup].[tBatchMaster] where OrgId=@rOrgId order by orderIndex
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSetup].[pBatchGroupMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rNumber int, 
	@rOrderIndex smallint, 
	@rCreatedUserId bigint, 
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
 IF(@rId = 0)	
 BEGIN
 
 if exists(select 1 from sSetup.tBatchGroupMaster where Code=@rCode ANd OrgGroupId=@rOrgGroupId)
	BEGIN
		Select -102 as result
		RETURN
	END
	if exists(select 1 from sSetup.tBatchGroupMaster where Title =@rTitle ANd OrgGroupId=@rOrgGroupId)
	BEGIN
		Select -103 as Result
		RETURN
	END
	if exists(select 1 from sSetup.tBatchGroupMaster where Number=@rNumber and OrgGroupId=@rOrgGroupId)
	BEGIN
		Select -104 as Result
		Return
	END
	if exists(select 1 from sSetup.tBatchGroupMaster where OrderIndex =@rOrderIndex and OrgGroupId=@rOrgGroupId)
	BEGIN
		Select -105 As Result
		Return
	END
 END
 Else
 BEGIN
	if exists(select 1 from sSetup.tBatchGroupMaster where Code=@rCode and OrgGroupId=@rOrgGroupId and Id<>@rId)
	BEGIN
		Select -102 AS Result
		RETURN
	END
	
	if exists(select 1 from sSetup.tBatchGroupMaster where Title =@rTitle and OrgGroupId=@rOrgGroupId and Id<>@rId)
	BEGIN
		Select -103 as result
		RETURN
	END
	
	if exists(select 1 from sSetup.tBatchGroupMaster where Number =@rNumber and OrgGroupId=@rOrgGroupId and Id<>@rId)
	BEGIN
		Select -103 as result
		RETURN
	END
	
	if exists(select 1 from sSetup.tBatchGroupMaster where OrderIndex =@rOrderIndex and OrgGroupId=@rOrgGroupId and Id<>@rId)
	BEGIN
		Select -103 as result
		RETURN
	END
 END
 
 
 IF(@rId = 0)	
BEGIN 

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sSetup.tBatchGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	
	INSERT INTO sSetup.tBatchGroupMaster
		(
			Id,
			Code,
			Title,
			Number,
			  
			OrderIndex,
			OrgGroupId,
			 
			CreatedUserId,
			CreatedDateTime 
			  
		 
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rNumber,
			 
			@rOrderIndex,
			@rOrgGroupId,
			 
			@rCreatedUserId,
			sCommon.fGetDate() 
			 
		)
	SELECT @lNextNumber AS Result
	-- Insert Batch Class
	 
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sSetup.tBatchGroupMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			number=@rNumber,
			OrgGroupId=@rOrgGroupId,
		 
			OrderIndex=@rOrderIndex,
			 
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	 
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSetup].[pBatchGroupMasterGet]
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint,
	 @rIsSearch bit=0, 
	 @rnumber int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsSearch=1)
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			BM.Id,
			BM.Code,
			BM.Title,
			BM.Number,
			BM.OrgGroupId,
			BM.OrderIndex ,
			 
			BM.CreatedUserId,
			BM.CreatedDateTime,
			BM.UpdatedUserId,
			BM.UpdatedDateTime	
		 
			
			
  FROM 
            sSetup.tBatchGroupMaster BM
   --         INNER JOIN sSetup.tOrgGroupBatchMaster OGBM
			--	ON OGBM.Id = BM.OrgGroupBatchId
			--INNER JOIN sSetup.tOrganizationMaster OM
			--	ON OM.Id = BM.OrgId
  WHERE 
  
    ((BM.Id = @rId) OR (@rId = 0))
    AND ((BM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))  
	AND ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((BM.Number = @rnumber) OR (@rnumber = 0))  
	 
ORDER BY  BM.OrderIndex ASC
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [sSetup].[pBatchMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rOrgId int,
	@rIsHistory bit,
	@rIsObsolete bit,
	@rOrderIndex smallint,
	@rFromDate date,
	@rToDate date,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int,
	@rBatchGroupId int=0,
	@rLeaveYearFromDate date,
	@rLeaveYearToDate date,
	@rIsLock bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
	DECLARE @lBatchCount int,@lBatchCountActive int
	DECLARE @lTermPattern int
	DECLARE @lIsInContext bit,@lIsActive bit
	
	SELECT @lBatchCountActive = ISNULL(COUNT(ID),0) FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId
	
	SELECT @lBatchCount = ISNULL(COUNT(ID),0) FROM sSetup.tBatchMaster WHERE OrgGroupBatchId = @rOrgGroupBatchId AND OrgId = @rOrgId
	SELECT @lTermPattern = TermPatternId FROM sSetup.tOrganizationMaster WHERE  Id = @rOrgId
	
	IF (@lBatchCount >= @lTermPattern)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END
	
	IF (@lBatchCountActive = 0)
	SET @lIsActive = 1
	ELSE
	SET @lIsActive = 0
	
	IF (@lTermPattern = 1)
		SET @lIsInContext = 1
	ELSE IF (@lTermPattern = 2 AND  @lBatchCount = 0)
		SET @lIsInContext = 1
	END
	--BEGIN
	--		IF EXISTS(SELECT 1 FROM sSetup.tBatchMaster WHERE OrgId=@rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId)
	--		BEGIN
	--			SELECT -100 AS Result
	--			RETURN
	--		END
	--END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSetup.tBatchMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sSetup.tBatchMaster
		(
			Id,
			Code,
			Title,
			OrgId,
			IsHistory,
			IsObsolete,
			OrderIndex,
			FromDate,
			ToDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupBatchId,
			IsInContext,
			IsActive,
			BatchGroupId,
			LeaveYearFromDate,
			LeaveYearToDate,
			IsLock
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rOrgId,
			@rIsHistory,
			@rIsObsolete,
			@rOrderIndex,
			@rFromDate,
			@rToDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupBatchId,
			@lIsInContext,
			@lIsActive,
			@rBatchGroupId,
			@rLeaveYearFromDate,
			@rLeaveYearToDate,
			@rIsLock
		)
	
	-- Insert Batch Class
	INSERT INTO sSetup.tBatchClass
	SELECT @lNextNumber,Id,0
	FROM sSetup.tClassMaster
	WHERE OrgId = 	@rOrgId
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sSetup.tBatchMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			OrgId=@rOrgId,
			--IsHistory=@rIsHistory,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			BatchGroupId=@rBatchGroupId,
			FromDate=@rFromDate,
			ToDate=@rToDate,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LeaveYearFromDate=@rLeaveYearFromDate,
			LeaveYearToDate=@rLeaveYearToDate,
			IsLock = @rIsLock
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE OR ALTER PROCEDURE [sSetup].[pBatchMasterGet]
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rIsSearch bit=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgGroupId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsSearch=1)
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			BM.Id,
			BM.Co